C++ Recursion

Recursion refers to the process when a function calls itself inside that function directly or indirectly or in a cycle. And such functions are called recursive functions. However, the crucial part is the termination condition, if not handled properly then it might go into an infinite loop.

void recursion()
{
    ......
    recursion(); //calling itself
    ......
}

int main()
{
    ......
    recursion();
    ......
}
Recursion

We can use the if…else statement to stop it from going into an infinite loop. Using the if…else statement, one branch of if-else can call the function itself and the other can give the condition to end the function.


Example: C++ Recursion Program

Program to find the factorial of a number in C++ using recursion.

#include <iostream>
using namespace std;

int factorialFunc(int);

int main()
{
   int fact, num;

   cout << "Enter a positive integer: ";
   cin >> num;

   //calling factorial function
   fact = factorialFunc(num);

   cout << "Factorial of " << num << " is: " << fact << endl;
   return 0;
}

int factorialFunc(int n)
{
   if (n == 0)
      return (1);  //base condition
   else
   {
      return (n* factorialFunc(n - 1));	//recursion
   }
}

Output:

Enter a positive integer: 5
Factorial of 5 is: 120

If you want to learn more about recursion in detail, click here. Although it is for C programming but the theory concept of recursion is the same for all programming languages.