Recursion is a technique in programming where a function calls itself. Recursion can be a powerful tool for solving problems that can be broken down into smaller sub-problems. Here is an example of how to use recursion in C++:
int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } } int main() { int n = 5; int result = factorial(n); cout << "The factorial of " << n << " is " << result << endl; return 0; }
In this example, the `factorial` function calculates the factorial of an integer `n` by calling itself with a smaller value of `n` until `n` is 0. The base case is when `n` is 0, in which case the function returns 1. If `n` is not 0, the function calculates `n * factorial(n-1)` and returns the result.
When the `factorial` function is called with `n = 5`, it calls itself with `n = 4`, then `n = 3`, then `n = 2`, then `n = 1`, and finally `n = 0`. At this point, the base case is reached, and the function returns 1. The previous recursive calls then return the result of `n * factorial(n-1)` for each value of `n`, until the original call to `factorial(5)` returns the final result of `5 * 4 * 3 * 2 * 1 = 120`.
Recursion can be a powerful technique because it allows you to break down a complex problem into smaller, more manageable sub-problems. However, it is important to be careful when using recursion, as it can lead to stack overflow errors if the function calls itself too many times. It is important to have a base case that will eventually terminate the recursion, and to make sure that the function does not call itself indefinitely.