What is Recursion?
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph,
- Advantages:
- Reduce unnecessary calling of function.
- Through Recursion one can Solve problems in easy way while its iterative solution is very big and complex.
- Disadvantages:
- Recursive solution is always logical and it is very difficult to trace.(debug and understand).
- In recursive we must have an if statement somewhere to force the function to return without the recursive call being executed, otherwise the function will never return.
- Recursion takes a lot of stack space, usually not considerable when the program is small and running on a PC.
- Recursion uses more processor time.
Example:
C program to calculate factorial using recursion:
#include<stdio.h>
long Factorial(int);
void main()
{
int num;
long fact;
printf("\n\tEnter any positive number : ");
scanf("%d",&num);
fact = Factorial(num);
printf("\n\tThe Factorial of %d is %ld",num,fact);
}
long Factorial(int num)
{
if (num == 1)
return 1;
else
return num*Factorial(num-1);
}
Enter any positive number :
The Factorial of 10 is 3628800