Recursion in C

Recursion in C is the process in which the function calls itself directly or indirectly is known as “Recursion”. And the corresponding function is called “Recursive function”. And the recursion functions in C are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating the Fibonacci series, etc., Recursion code is shorter than iterative code however it is difficult to understand.

Recursion in C

And it cannot be applied to all the problems, but it is more useful for the tasks that can be defined in terms of similar subtasks.
Example: recursion may be applied to sorting, searching, and traversal problems.

Syntax
void recursion( )
{
recursion( ); /*function calls itself*/
}
int main( )
{
recursion( );
}



Example 1: Factorial of a number using Recursion

#include<stdio.h>           
#include<conio.h>            
int fact(int f) {           
if (f & lt; = 1) {           
printf("Calculated Factorial");            
return 1; }            
return f * fact(f - 1); }            
int main(void) {            
int f = 12;             
clrscr();            
printf("The factorial of %d is %d \n",f,fact(f));             
getch();            
return 0; }

Output: factorial of 12 is 479001600

Recursive Function

A recursive function performs the tasks by dividing it into the subtasks. There is a termination condition defined in the function which is satisfied by some specific subtask. After this, the recursion stops and the final result is returned from the function.

Recursion makes the program elegant and more readable.

Example 2: Fibonacci series

#include<stdio.h>        
#include<conio.h>         
int fibo(int g) {        
if(g == 0)
{        
return 0;  
}        
if(g == 1) {         
return 1;      
}        
return fibo(g - 1) + fibo(g - 2);     
}        
int main(void) {        
int g;        
clrscr();       
for (g = 0; g < 10; g++) {       
printf("\nNumbers are: %d \t ", fibonacci(g));      
}       
getch();      
return 0;   }

Output
0
1
1
2
3
5
8
13
21
34