Whenever a function calls a replica of its own to resolve a smaller issue, this is known as recursion. A recursive function is one that calls itself, and recursive calls are function calls that call themselves. Any problem can be solved iteratively if it can be solved recursively.
A recursive function is one that calls itself, and such function calls are referred to as recursive calls. There are some recursive calls in recursion. It is, however, important to enforce a recursion termination condition. While recursion code is shorter than iterative code, it is more difficult to comprehend.
Recursion cannot be used to solve all problems; however, it is more useful for tasks that can be broken down into smaller subtasks. Recursion can be used to solve problems like sorting, searching, and traversal.
Since function calls are still overhead, iterative solutions are generally more effective than recursion. Any problem can be solved iteratively if it can be solved recursively. However, some problems, such as the Tower of Hanoi, the Fibonacci sequence, and factorial finding, are better solved by recursion.
Example:
The factorial of a number is calculated using recursion.
#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 (5*4*3*2*2*1)
Interested in learning about similar topics? Here are a few hand-picked blogs for you!
- What is data structure?
- What is sorting algorithm?
- What is DNS?
- What is computer processor?
- What is computer?