Loading....
Coupon Accepted Successfully!

 

Recursion

Recursion is the phenomenon of function calling itself repeatedly.

Consider a function calls itself from within itself. Recursion is useful in the situation, where some series of similar and dependant calculations are needed. The best example is
factorial. Factorial of n(n!) can be written as n*(n-l)*(n-2)*(n-3)*......*2*1

So it is a continued product from n to 1. Hence we can rewrite it as n*factorial of(n-l). From this we can write a function to calculate the factorial of a number
int factorial(int n)
{
if(n<=l)
return(l);
else
return(n*factorial(n-l));
}

 

Example-1

/* to calculate the factorial through recursion */
#include
#include
int fact(int);
void main()
{
int n,result;
clrscr();
printf("Enter the number");
scanf("%d",&n);
result=fact(n);
printf("\n The factorial of %d is %d",n,result);
getch();
}
int fact(int x)
{
int f;
if(x==1)
{
return(x);
}
else
{
return(x*fact(x-1));
}
}

 

 

Example
/* program to find the first nth terms Fibonacci series */
#include
main()
{
int i,n;
int fibonacci(int,i);
printf("Enter no. of terms:"); /* read the number of entries */
scanf("%d",&n);
printff("The fibonacci series: \n"); /* calculate and display the fibonacci series */
for(i=l; i printf("%d\n",fibonacd(i) );
}
int fibonacci(int x) /* function to find the nth fibonacci no */
{
if (( x== 1) || (x = = 2))
return(l); else
return(fibonacci(x-l) + fibonacci(x-2));
}
OUTPUT:
Enter no.of terms: 9
The fibonacci series:
1
1
2
3
5
8
13
21
34
 

 





Test Your Skills Now!
Take a Quiz now
Reviewer Name