C++ Recursion

Recursion is a programming method where a function calls itself to address an issue. A recursive function in C++ must have both a base case, which is the recursion’s ending condition, and a recursive case, which is the circumstance under which the function calls itself.

Example:

#include <iostream>
using namespace std;

int factorial(int n) {
   if (n == 0) {
      return 1;
   } else {
      return n * factorial(n - 1);
   }
}

int main() {
   int num = 5;
   int result = factorial(num);
   cout << "The factorial of " << num << " is " << result << endl;
   return 0;
}

Output:

The factorial of 5 is 120

Until the base case (when n equals 0) is reached, the factorial function is called again in this example. The function returns 1 when the base case is reached, and the outcome is determined by multiplying the parameter by the recursive call’s outcome by n-1.