 C Recursion

Recursion is a process to function calling by direct or indirect. when function calling itself that is called direct recursion. And function is calling other function that is called to indirect recursion.Recursion are suitable to solve complex problem by dividing sub problem. Recursion always need a base condition to stop execution of function calling. there are is an important points to control recursion. most of language are using recursion internally of stack data structure. recursion are execute until when certain condition (terminate condition) are fulfill.

Types of Recursion

There are two type

1) Direct Recursion

function calling itself that is called direct recursion. some time we are need to use of direct recursion. for example calculate factorial of given number. /*
Example of Direct recursion

*/
#include <stdio.h>

//function declaration
int factorial(int);

//Calculate factorial of given number
int factorial(int num){
if(num==0){ return 1;}
else {
return factorial(num-1)*num;//Recursive call
}
}
int main(){
int num=5;
printf(" factorial of %d is : %d", num,factorial(num)); //function call
} Output:

factorial of 5 is : 120

2) Indirect recursion

Indirect recursion also called mutual recursion. Example

/*
Example of Indirect recursion

*/
#include <stdio.h>

//function declaration
void funct1(int);
void funct2(int);

void funct1(int num){
if(num==0){
//base condition
return ;
}
printf("\n funct1 num : %d",num);
funct2(num-1);//indirect function call
}
void funct2(int num){
if(num==0){
//base condition
return ;
}
printf("\n funct2 num : %d",num);
funct1(num-1); //indirect function call

}

int main(){
//function calling
funct1(4);
return 0;
}

Output Output:

funct1 num : 4
funct2 num : 3
funct1 num : 2
funct2 num : 1

Memory allocation of Recursive Function

When calling any user defined function there are using to space of stack area. stack are free this function memory when execute all statement of function. this process are automatically execute.

/*
Example of recursion are use stack memory
*/
#include <stdio.h>
//function declaration
void display(int);

void display(int value){
if(value>10){
//base condition
return;
}else{
printf("\n %d",value); //print value
display(value+1);//recurive call
}
}

int main(){
//Start execution of
display(5);
return 0;
} Output

5
6
7
8
9
10