Now that we've understood the concept of recursion in C++, let's see how to implement it. A classic problem in programming used to illustrate recursion is the calculation of the factorial of a number.
In mathematics, the factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n!. For example, 5! is 5*4*3*2*1 = 120.
The factorial problem can be divided into two sub-problems:
- Base Case: If
n = 1, the function returns1, because1!equals to1. - Recursive Case: If
n > 1, then the function calls itself withn - 1, multiplyingnwith the factorial ofn-1.
Factorials are used in many areas of computer science, including algorithm complexity computation (Big O notation), artificial intelligence, and financial calculations. In the attached code we're exploring how to compute a factorial of a number (in this case 5) using recursion in C++.
In the code, the factorial() function is defined such that it calls itself (recursion) to compute a factorial of a given number. The function takes one argument, n, and uses the if statement to check if n equals 1 which is our base case. If n > 1, then the function calls itself with the argument n-1; and n is multiplied with the result. This operation is performed until n equals 1, and that's where the function stops calling itself (the base case). The factorial of n is then returned to the calling function and printed to the console.
xxxxxxxxxxusing namespace std;int factorial(int n) {if (n == 1)return 1;elsereturn n * factorial(n-1);}int main() {int n = 5;//Factorial of 5 (used in some complex problems in AI and finance)cout<<"Factorial of 5 is "<<factorial(n)<<endl;return 0;}

