Recursion in C: #Include
Recursion in C: #Include
Recursion is the process which comes into existence when a function calls a copy of itself to work on a smaller
problem. Any function which calls itself is called recursive function, and such function calls are called recursive
calls. Recursion involves several numbers of recursive calls. However, it is important to impose a termination
condition of recursion. Recursion code is shorter than iterative code however it is difficult to understand.
Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be defined in terms
of similar subtasks. For Example, recursion may be applied to sorting, searching, and traversal problems.
Generally, iterative solutions are more efficient than recursion since function call is always overhead. Any
problem that can be solved recursively, can also be solved iteratively. However, some problems are best suited
to be solved by the recursion, for example, tower of Hanoi, Fibonacci series, factorial finding, etc.
#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
Output
Enter the number whose factorial you want to calculate?5
factorial = 120
We can understand the above program of the recursive method call by the figure given below:
Let's see an example to find the nth term of the Fibonacci series.
#include<stdio.h>
int fibonacci(int);
void main ()
{
int n,f;
printf("Enter the value of n?");
scanf("%d",&n);
f = fibonacci(n);
printf("%d",f);
}
int fibonacci (int n)
{
if (n==0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return fibonacci(n-1)+fibonacci(n-2);
}
}
Output
Enter the value of n?12
144