Recursive Functions
As we have learned Functions in C Language. There is an another word ‘Recursion’ that is connected to functions. When any function is being called from its own body, then it is called Recursive Call. eg.
void main()
{
//Some Code
main(); //Recursive Call
}
Above call will result in infinite execution. In Recursion Termination Condition is important. Recursion can be used as an alternative of Iteration. There are some popular example for Recursion like Factorial using Recursion, Power using Recursion etc.
#include<stdio.h>
#include<conio.h>
long fact(int n)
{
if(n==0) //Termination condition
{
return 1;
}
else
{
return n*fact(n-1); //Recursive Call
}
}
void main()
{
int n;
long f;
clrscr();
printf("\nEnter N :");
scanf("%d",&n);
f=fact(n);
printf("\nFactorial %ld",f);
getch();
}
Above is the example of Factorial using Recursion. For Power we can write a function like
long power(int b,int p)
{
if(p==0)
return 1;
else
return b*power(b,p-1);
}
We can also calculate fibonacci number using Recursion like
int fibbo(int n)
{
if(n==1)
return 0;
else if(n==2)
return 1;
else
return fibb(n-1) + fibb(n-2);
}
In short we can say ‘Recursion is Function Calling It Self’