Beruflich Dokumente
Kultur Dokumente
Functions
Defining a Function
In C, a program is a collection of well defined and interrelated
functions. The general form of a function is as follows
return-type function(type arg1, type arg2, ..)
{
local variables Declaration;
executable statement 1;
executable statement 2;
:
:
return(expression);
}
Functions
Example 1: Function for finding the biggest of
two integers
int find_big(int a, int b)
{
if ( a > b) return a;
else return b;
}
Functions
Invoking a Function
Functions
Example
Program for finding biggest of two integers using the function
void main( )
{
int num1, num2, big;
scanf(%d%d, &num1, &num2);
big=find_big(num1,num2);
printf( The biggest is : %d , big);
}
int find_big(int a, int b)
{
if ( a > b) return a;
else return b;
}
/* prints 20 */
Call by Value
Call by Value
Example
void main()
{
int a, b;
a=10;
b=20;
swap(a, b);
/* Prints 10 20 */
}
void swap(int c, int d)
{
int temp;
temp = c;
c = d;
d = temp;
}
Call by Reference
Call by Reference
Call by Reference
Example : Program that illustrates Call by Reference mechanism
void main()
{
int a, b;
a=10;
b=20;
swap(&a, &b);
/* passing the addresses of a and b to c and d
of swap function*/
printf(%d %d, a, b); /* Prints 20 10 */
}
void swap(int *c, int *d)
{
int temp;
temp = *c;
*c = *d;
*d = temp;
}
Function Prototyping
Function Prototyping
Function prototype is a function declaration that specifies the
return type and data types of the arguments.
A function prototype/declaration informing the compiler the
number and data types of arguments to be passed to the function,
and the data type of the value returned by the called function.
Recursion
Recursion
Recursion
Example Illustrative examples of Recursive function
Factorial Function : n! = n * (n-1)!
Base Criteria is 0! =1
int factorial( int n)
{
if(n = = 0)
return 1;
else
return( n* factorial(n-1));
}
Review
A function in C is a small sub-program
that performs a particular task, and
supports the concept of modular
programming design techniques. In
modular programming the various tasks
that your overall program must
accomplish are assigned to individual
functions and the main program
basically calls these functions in a certain
order.
local declarations;
function statements;