*** (Q) Explain and Working Principles of Recursion Function in C-Programming?
The Function which calls same function is called Recursive Function. In other words when a
function calls itself, then that functio9n is called Recursion Function.
Example: - Program to find the Factorial of a number by using Recursion Function?
#include<stdio.h>
#include<conio.h>
main()
{
int n, factorial();
clrscr();
printf("\n Enter the Value of N : ");
scanf("%d", &n);
printf("\n Factorial of Number %d is %d", n, factorial(n));
getche();
}
int factorial(n)
int n;
{
int m;
if(n == 1)
{
return(n);
}
else
{
m = n * factorial(n-1); return(m);
}
}
OUTPUT:
Enter the Value of N : 5
Factorial of Number 5 is 120.
Working Principle: - Formula : n * fact(n – 1); (or) n * (n – 1)!. Example N = 5!
The First time when Factorial() function is called from main() function, „n‟ collects value 5.
From here, since „n‟ is not equal to 1, the if block is skipped and Factorial() function is called again
with the argument (n - 1) therefore (5 -1) 4, this is recursive call.
Since „n‟ is still not equal to 1, Factorial() function is called yet another time, with argument (n – 1)
therefore (4-1) 3, this is again recursive call.
Since „n‟ is still not equal to 1, Factorial() function is called yet another time, with argument (n – 1)
therefore (3-1) 2, this is again recursive call.
This process will carry on until the value of argument „n‟ is 1.
When the value of „n‟ is 1, the control goes back to previous Factorial() function with the value1,
and „m‟ is evaluated as 2.
And then control back to next previous Factorial() function with the value 2 and „m‟ is again
evaluate 6.
Similarly, each Factorial() function evaluates its „m‟ from the returns value, and finally 120 is
return to main() function.
1
4 3 2
factorial(n)
factorial(n) factorial(n) factorial(n)
From main() 5 int n;
int n; int n; int n;
factorial(n) {
{ { {
int n;
int m; if(n
{ int m; int m; int m; if(n
==1)
if(n ==1) if(n ==1) ==1)
int m; return(1);
return(1); return(1); return(1);
if(n ==1) else
else else else
return(1);
else
m =n*factorial(n-1) m =n*factorial(n-1) m =n*factorial(n-1) m =n*factorial(n-1) m =n*factorial(n-1)
return(m); return(m); return(m); return(m); return(m);
} } }
} }
24 6 2 1
120 to main()
Fact(5)
5 *Fact(4)
4 *Fact(3)
3 *Fact(2)
2 *Fact(1)
2*1=2 1*1=1
3*2=6
5 * 24 = 120 4 * 6 = 24