Recursion

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

How recursion works?

How recursion works

The recursion continues until some condition is met to prevent it.

To prevent infinite recursion, if....else Statement (or similar approach) can be used where one branch makes the recursive call and other doesn't.

 

Example

 

#include<stdio.h>
int factorial(int x){ 
if(x<=1)  
{
return 1; 
}
return (x * factorial(x-1));
}
int main(){ 
int x=5;
printf("Factorial of %d is %dn",x,factorial(x));
return 0;
}

Output

Factorial of 5 is 120