Explain Recursion in C++?

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.

Example of Recursion Function to print factorial of a number -

#include<iostream>  
using namespace std;    
int main()  
{  
int factorial(int);  
int fact,value;  
cout<<"Enter any number: ";  
cin>>value;  
fact=factorial(value);  
cout<<"Factorial of a number is: "<<fact<<endl;  
return 0;  
}  
int factorial(int n)  
{  
if(n<0)  
return(-1);  
if(n==0)  
return(1);  
else  
{  
return(n*factorial(n-1));      
}  
}

As we can see, the factorial() function is calling itself. However, during each call, we have decreased the value of n by 1. When n is less than 1, the factorial() function ultimately returns the output.

Recursion is required in problems concerning data structures and advanced algorithms, such as Graph and Tree Traversal.