Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
131 views

Unit 5 Functions

The document discusses C functions including creating functions, function prototypes, parameters, return values, and math functions. It provides examples of defining functions, passing parameters, return values, and using math functions in C code.

Uploaded by

shubhangi
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
131 views

Unit 5 Functions

The document discusses C functions including creating functions, function prototypes, parameters, return values, and math functions. It provides examples of defining functions, passing parameters, return values, and using math functions in C code.

Uploaded by

shubhangi
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 26

C Functions

Objectives
• Create functions
• Function prototypes
• Parameters
– Pass by value or reference
– Sending a reference
• Return values
• Math functions
Intro
• Why:
– Divide and conquer
– Reuse abstractions
– Don’t rebuild the bridge
• What:
– Used prepackaged functions
• printf, scanf, rand()
– Create our own
• main
– Pass parameters
– Accept return values
C FUNCTIONS
Some definition: A function is a named, independent section of C code that
performs a specific task and optionally returns a value to the calling program
or/and receives values(s) from the calling program.

 Basically there are two categories of function:


1. Predefined functions: available in C / C++
standard library such as stdio.h, math.h,
string.h etc.
2. User-defined functions: functions that
programmers create for specialized tasks
such as graphic and multimedia libraries,
implementation extensions or dependent
etc.
www.tenouk.com, © 2/66
Math
• #include <math.h>
• Use any math function
• If c1 = 13.0, d = 3.0 and f = 4.0, then the
statement
printf( "%.2f", sqrt( c1 + d * f ) );
©1992-2013 by Pearson Education, Inc. All
Rights Reserved.
©1992-2013 by Pearson Education, Inc. All
Rights Reserved.
• Choose a name
Create your function
– Function should perform a single well defined task
– If you can’t find a concise descriptive name, you may have too
many jobs for the function
• Define a contract
– Inputs
• Arguments – choose type
• None should be noted as void
• Will the function change the parameter’s value?
– Output
• Only one ; by convention, 0 means good
Write prototype
– Looks like function header but has ;
– int square( int y );
– Tells compiler what is valid input and output
– Forces type conversion
• Write body
• Call the function
C FUNCTIONS
 The following figure illustrates function calls (also the memory’s
stack record activation – construction & destruction.

www.tenouk.com, © 7/66
Sample Function
#include <stdio.h>
int square ( int y ); // function prototype
// function main begins program execution
int main ( void )
{ int x; // counter
for ( x = 1; x <= 10; x++ ) {// loop 10 times and calc square of x each time
printf ( "%d ", square ( x ) ); // function call
}
puts (""); // add a blank line
}
// square function returns the square of its parm
int square ( int y ) // y is a copy of the x sent
{
return y * y; // returns square of y as an int
}
return
• return serves two purposes:
– It tells the computer the value to return as the
result
– It tells the computer to leave the function
immediately and return the calling function (or
the main program).
• Void return:
– Ex: void printit ( int x );
– You can still return to leave, but without a value
Prototypes
• Looks like function header but has ;
• char square( int y );
• Int square(char z);
• Forces type conversion
• Tells compiler what is valid input and output

• No Overloading
• Every function name can have only one contract
C FUNCTIONS
Passing an array to a function What are the output and
#include <stdio.h> the content of num &
 
// function prototype
mood variables after
void Wish(int, char[ ]); program execution was
 
void main(void) completed?
{
   Wish(5, "Happy");
}

www.tenouk.com, © 53/66
C FUNCTIONS
#include <stdio.h>
 
void Rusted(char[ ]);
Build this program, show
  the output & what it do?
void main(void)
{
      // all work done in function Rusted()...
      Rusted("Test Test");
      printf("\n");
}
 
void Rusted(char x[ ])
{
      int j;
      printf("Enter an integer: ");
      scanf_s("%d", &j);
      for(; j != 0; --j)
            printf("In Rusted(), x = %s\n", x);
}

A function call from main() that passes a character string and


callee will print the number of character string based on the user
input.
www.tenouk.com, © 55/66
What Are Reference Parameters?
• Reference parameters do not copy the value of
the parameter.
• Instead, they give the function being called a
copy of the address at which the data is stored.
This way, the function works with the original
data.
• We call this passing by reference because we
are making references to the parameters.
Write SquareInPlace
with Reference Parm
• tell the main program about the change in y by
placing (*) between the data type and variable
name:
int squareInPlace (int *y)
{ *y = *y * *y;
return 0;}
• Send an address instead of the variable contents
using (&) before variable name:
int number = 6;
squareInPlace (&number);
printf(“%d”, number);
Passing Reference Parameters

Any data
number 4.0 y intended for y
in the
function goes
to the
location of
number in the
main
program
Use of math functions in C
// the use of ceil function.
#include <stdio.h>
#include <math.h>
 
int main ()
{
float val1, val2, val3, val4;
 
val1 = 1.6;
val2 = 1.2;
val3 = -2.8;
val4 = -2.3;
 
printf ("value1 = %.1lf\n", ceil(val1));
printf ("value2 = %.1lf\n", ceil(val2));
printf ("value3 = %.1lf\n", ceil(val3));
printf ("value4 = %.1lf\n", ceil(val4));
     
return(0);
}
String Functions in C
// C program to illustrate
// strcmp() function
#include <stdio.h>
#include <string.h>
  
int main()
{
  
    char leftStr[] = "g f g";
    char rightStr[] = "g f g";
  
    // Using strcmp()
    int res = strcmp(leftStr, rightStr);
  
    if (res == 0)
        printf("Strings are equal");
    else
        printf("Strings are unequal");
  
    printf("\nValue returned by strcmp() is:  %d", res);
    return 0;
}
C program to find GCD of
two numbers
/ C program to find GCD of two numbers
#include <stdio.h>
 
// Recursive function to return gcd of a and b
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
 
// Driver program to test above function
int main()
{
    int a = 98, b = 56;
    printf("GCD of %d and %d is %d ", a, b, gcd(a, b));
    return 0;
}
Recursion – Function calls itself
• Method for repetition
• Need a stopping condition
• Need to call with some way to reach the stop
eventually
• Pushes copies of itself onto the stack (memory
use)
©1992-2013 by Pearson Education, Inc. All
Rights Reserved.
©1992-2013 by Pearson Education, Inc. All
Rights Reserved.
©1992-2013 by Pearson Education, Inc. All
Rights Reserved.

You might also like