Recursion in C
Function repeatedly calling itself is called recursion. But we need to specify some condition to stop execution of recursive function otherwise function may run infinite.
|Program using recursion to find factorial of a number .|
int fact(int no)
printf(“\nEnter a number”);
printf(“\nFactorial of %d=%d”,n,f1);
|Enter a number=4|
Factorial of 4 =24
Function fact() check whether value of parameter no is equal to 1 or 0. In case of 1 or 0, factorial will be returned as 1 otherwise statement no*fact(no-1) will execute.
Suppose value of n is 4, execution will be as follows:
f = 4* fact (3); will be evaluated. This statement again calls fact() function with value n-1 which will return value
This process continues until value of no is equal to 1 or 0 and when no is equal to 1 it returns 1 and execution of this function stops. Process is as f0llows
f1 = 4* fact (3-1);
f1 =4*3* fact (3-1);
f4 = 4*3*2*fact (2-1);
f 1= 4*3*2*1;
f = 24;
Nesting of functions in C
It is the process in which a function calls another function.
|Program for nesting of function.|
msg(); /*Function msg() nested within function show().*/
Best Books of C