Recursion
Recursion
Recursion
What is Recursion?
Recursion: It is a process by which a function calls itself repeatedly
until some specified condition has been satisfied
It is a processing of defining something in terms of itself.
A function is called recursive if a statement within the body of a
function calls the same function.
Example: Factorial Calculation
How to calculate 5!?
5 * 4 * 3 * 2 * 1 = 120
i.e., 5 * 4! (Or) 5 * 4 * 3!
(Or) 5 * 4 * 3 * 2! (Or) 5 * 4 * 3 * 2 * 1! (Or) 5 * 4 * 3 * 2 * 1
So, n! = n * (n-1)!
Factorial in C Language
#include <stdio.h>
int main()
{ int a, fact;
printf (“Enter any number”);
scanf (“%d”,&a);
fact = factorial(a);
printf (“Factorial Value:%d”,fact);
}
Loop 4
Loop 5 for (i=x; i>=1) - - - for i = 2 & 2 >=1
for (i=x; i>=1) - - - for i = 1 & 1 >=1 then f = f * i; - - - f = 60 * 2; then f = 120
condition is false. Break;
i - -; - - - then i=1;(2-1)
Factorial using Recursion
#include <stdio.h> int rec(int x)
int main() {
int f;
{ int a, fact; Function “rec”
printf (“Enter any number”); if (x==1) is calling itself
return 1;
scanf (“%d”,&a); else
fact = rec(a); f = x * rec (x-1);
printf (“Factorial Value:%d”,fact);
return (f)
} }
Control flows of recursive call
from main()
If x != 1 If x != 1 If x == 1
to main()
Recursive call with an example
from main()
If x =
4
int rec(4) int rec(3) int rec(2) int rec(1)
{ { { {
int f; int f; int f; int f;
to main()