C part 7 - Function
C part 7 - Function
Example: result=add(num1,num2);
The result of a function call is a value of type
<Function type>
Arguments/Parameters
one-to-one correspondence between the
arguments in a function call and the parameters
in the function definition.
int argument1;
double argument2;
// function definition
Int functionname(int parameter1, double parameter2){
// Now the function can use the two parameters
// parameter1 = argument 1, parameter2 = argument2
Call by Value
The call by value method of passing arguments to a function
copies the actual value of an argument into the formal
parameter of the function.
#include<stdio.h>
int swap(int , int);
main( )
{
int a = 10, b = 20 ;
printf ( "Before swapping:\na = %d b = %d", a, b ) ;
swap(a,b);
}
int swap( int x, int y )
{
int t ;
t=x;
x=y;
y=t;
printf ( "\nAfter swapping:\na = %d b = %d", x, y ) ;
}
Call by Reference
The call by reference method of passing arguments to a function
copies the address of an argument into the formal parameter.
#include <stdio.h>
void swap(int *a,int *b);
int main(){
int num1=500,num2=100;
swap(&num1,&num2);
printf("Number1 = %d\n",num1);
printf("Number2 = %d",num2);
return 0;
}
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Recursion
Recursion is a function which calls itself.
Recursive function are very useful to solve many
mathematical problems like to calculate factorial of a
number, generating Fibonacci series, etc.
But while using recursion, programmers need to be careful to
define an exit condition from the function, otherwise it will
go in infinite loop.
void recursion()
{
recursion(); // function calls itself
}
int main()
{
recursion();
}
Factorial using Recursion
#include<stdio.h>
int fact(int);
int main()
{
int a,f;
scanf("%d",&a);
f=fact(a);
printf("%d",f);
return 0;
}
int fact(int n)
{
if(n==0)
return 1;
else
return n*fact(n-1);
}