# Recursion in C

#### Chapter 19

5 Steps - 3 Clicks

# Recursion in C

### Description

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.

### Syntax

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

### Reason

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,

### Example - 1

Control flow for factorial example will be as follows.

```//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));
}```

Output:

```
Enter a number: 5

Factorial of 5 is: 120
```

### Example - 2

```//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;
}
```

Output:

```Enter the value of n: 8
Sum of n numbers: 36
```