A function that calls itself is known as a recursive function This technique is known as recursion It is important to impose a termination condition of recursion Recursion code is shorter than iterative code however it is difficult to understand
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function and such function calls are called recursive calls. Using recursive algorithm, certain problems can be solved quite easily.
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, inorder/preorder/postorder Tree Traversals, DFS of Graph, etc.
Recursion always consists of two main parts
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
#include <stdio.h>
unsigned long long int factorial(int i) {
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
Output
Factorial of 12 is 479001600
A function funRecursion is called direct recursive if it calls the same function funRecursion . A function funRecursion is called indirect recursive if it calls another function say funRecursionOuter and funRecursionOuter calls funRecursion directly or indirectly.
An example of direct recursion
void directRecFun()
{
// Some code....
directRecFun();
// Some code...
}
An example of indirect recursion
void indirectRecFun1()
{
// Some code...
indirectRecFun2();
// Some code...
}
void indirectRecFun2()
{
// Some code...
indirectRecFun1();
// Some code...
}