Recursion
- In C programming it is possible to call a function itself.A function is said to be recursive if the statements within the function call itself. a conditional statement is necessary otherwise it will form infinite loop.
#include<stdio.h>
void recursion(){
recursion(); //Function calls itself
if(condition)
break;
}
void main(){
recursion();
}
consider the example of factorial of number:
#include<stdio.h>;
long f;
long fact (int n) //2
{ if(n==1)
return 1;
else
f=n*fact(n-1);
return f;
}
void main()
{ int n;
printf("Enter the number : ");
scanf("%d\n",&n);
long r;
r=fact(n); // 1
printf("Factorial of %d is %ld",n,r);
}
output:
Enter the number : 5
Factorial of 5 is 120
Lets try to understand the working of recursion :
- let 3 is passed to fact function . control enters checks if(3==1) , false . control enters else therefore now f=3*fact (2) , here fact(2) again calls fact function with argument 2 inside.
- control again enters checks if(2==1) it is false, control enters 'else' therefore now f=3*2*fact(1) , here fact(1) again calls fact function with argument 1 inside.
- control again enters checks if(1==1) it is true it returns 1 . now f=3*2*1 therefore f=6, which it returns to main function.
- Print Page