Recursion in C can be defined as the process of calling a function itself repeatedly. The function is called as "Recursive function". This is similar to looping concept which repeats the same code discussed earlier.
Recursion in C helps in expressing ideas in which the recursive call result, necessary to complete the task. Sometimes the process may complete without the recursive call also.
What happens if Recursion in C continues for many times..?
Basic function of Recursion in C is to repeat many times and it may happen forever.But, in real time what happens is,after some recursions, the program gets crashed. This is because,
For every recursion occurring, the memory creates a stack.
As the recursion occurs multiple times, multiple stacks are added into the memory.
After reaching a point, creation of stacks stops since there occurs a stack overflow.So the program crashes finally.
Example - 1
Control flow for factorial example will be as follows.
//program for finding factorial of a number
printf("\nEnter a number: ");
printf("\nFactorial of %d is: %d",number,f);
int fact(int n)
Enter a number: 5
Factorial of 5 is: 120
Example - 2
//program for finding sum of n numbers
printf("Enter the value of n: ");
sum = getSum(a);
printf("Sum of n numbers: %d",sum);
static int sum=0;
sum = sum + a;
Enter the value of n: 8
Sum of n numbers: 36
Advantages of Recursion
Recursion is more powerful in C-language because, it requires only few variables to perform the action on the variables.
Recursion reduces the code.
Recursion helps in finding bugs easily.
Dis-advantages of Recursion
Due to repetition, stack overflow occurs.
Writing logic for recursion requires a lot of effort.
Also becomes difficult to debug the code.
Recursive function calls itself for multiple times.
Stacks are created during recursion.
Take care of count of Recursion in C because it leads to overflow.