C++ recursion
Created By: chatGPT
Recursion is a powerful programming technique in C++ that allows a function to call itself. A recursive function typically has two main components: the base case, which stops the recursion, and the recursive case, which continues to call the function. Recursion can simplify complex problems by breaking them down into smaller, manageable subproblems. Let's look at an example of calculating the factorial of a number using recursion.
#include <iostream>
int factorial(int n) {
// Base case: factorial of 0 or 1 is 1
if (n <= 1) {
return 1;
}
// Recursive case: n * factorial of (n-1)
return n * factorial(n - 1);
}
int main() {
int number = 5;
std::cout << "Factorial of " << number << " is " << factorial(number) << std::endl;
return 0;
}
In the code above, the
factorial
function calculates the factorial of a number n
. If n
is 0 or 1, the function returns 1 (the base case). For any other positive integer, it recursively calls itself with the argument n - 1
(the recursive case). This continues until the base case is reached.Output:
Factorial of 5 is 120
Recursive functions can also be used to solve problems such as the Fibonacci sequence, where each number is the sum of the two preceding ones. This is another classic example of recursion that showcases its utility.
#include <iostream>
int fibonacci(int n) {
// Base case: the first two Fibonacci numbers
if (n <= 1) {
return n;
}
// Recursive case: sum of the two preceding numbers
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int number = 6;
std::cout << "Fibonacci of " << number << " is " << fibonacci(number) << std::endl;
return 0;
}
When you run this code, you will compute the 6th Fibonacci number, which is 8. Note that while recursion is elegant and often easier to read, it can lead to high computational costs and potential stack overflow for large inputs due to excessive function calls. Tail recursion and memoization can help optimize recursive functions in such cases.
Output:
Fibonacci of 6 is 8