C++ Recursion

If a function is invoked in the exact same way within the function it’s called recursion. The function that calls the same function is referred to as a recursive function.

The function which calls itself but doesn’t do any work following the function call is referred to as tail theorem. In tail recursion, we usually use the same function by calling it with a return statement.

Let’s take a look at an easy illustration of the recursion.

``````recursionfunction(){
recursionfunction(); //calling self function
}    ``````

C++ Recursion Example

Let’s take a look at an example to print a factorial number by using the recursion feature in the C++ language.

``````#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); /*Wrong value*/
if(n==0)
return(1);  /*Terminating condition*/
else
{
return(n*factorial(n-1));
}
}  ``````

Output:

```Enter any number: 5
Factorial of a number is: 120```

We can comprehend the above program of recursive method calls through the diagram below: