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.

void recursive_function()
{
//statements;
recursive_function();
}
int main()
{
//statements;
recursive_function();
}

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.

Control flow for factorial example will be as follows.
[c]
//program for finding factorial of a number
#include<stdio.h>
#include<conio.h>
#include<math.h>
int fact(int);
int main()
{
int number,f;
printf("\nEnter a number: ");
scanf("%d",&number);
f=fact(number);
printf("\nFactorial of %d is: %d",number,f);
return 0;
}
int fact(int n)
{
if(n==1)
{
return 1;
}
else
return(n*fact(n-1));
}[/c]
**Output**:
[c]
Enter a number: 5
Factorial of 5 is: 120
[/c]

[c]
//program for finding sum of n numbers
#include<stdio.h>
#include<math.h>
int main()
{
int a,sum;
printf("Enter the value of n: ");
scanf("%d",&a);
sum = getSum(a);
printf("Sum of n numbers: %d",sum);
return 0;
}
int getSum(a)
{
static int sum=0;
if(a>0)
{
sum = sum + a;
getSum(a-1);
}
return sum;
}
[/c]
**Output**:
[c]
Enter the value of n: 8
Sum of n numbers: 36
[/c]

- 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.

- 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.

© 2013 - 2023 SPLessons.com