Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem until it reaches a base case (stopping condition). It is useful for problems that can be broken down into simpler, repetitive tasks.
When a recursive function is called:
A recursive function must have:
The factorial of a non-negative integer n (written as n!) is the product of all positive integers less than or equal to n.
int factorial(int n) {
if (n == 0) // Base case
return 1;
else
return n * factorial(n - 1); // Recursive case
}
Here, when n becomes 0, recursion stops. Otherwise, the function calls itself with n - 1.
The Fibonacci sequence is a series where each number is the sum of the two preceding ones, starting from 0 and 1.
int fibonacci(int n) {
if (n == 0)
return 0; // Base case 1
else if (n == 1)
return 1; // Base case 2
else
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
}
The function calls itself twice to get the two previous Fibonacci numbers and sums them.
For factorial(3), the call stack grows as follows:
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 0)
return 1; // Base case
else
return n * factorial(n - 1); // Recursive call
}
int main() {
int num;
cout << "Enter a positive integer: ";
cin >> num;
if (num < 0)
cout << "Factorial is not defined for negative numbers." << endl;
else
cout << "Factorial of " << num << " is " << factorial(num) << endl;
return 0;
}
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!