Function recursion in C++ is when a function calls itself to solve a problem. It breaks down a problem into smaller, simpler versions of itself until it reaches a base case, which stops the recursion.
A recursive function generally has two parts
Base Case: This is the condition where the recursion stops. Without a base case, the function would call itself indefinitely, causing a stack overflow.
Recursive Case: This is where the function calls itself to solve a smaller part of the problem.
General Structure of Recursive Function:
return_type function_name(parameters) {
if (base_case_condition) {
// Return result (or handle the simplest case)
} else {
// Recursive case (call the function itself)
return function_name(smaller_sub_problem);
}
}
Example: Factorial Function
The factorial of a number n is defined as:
- n! = n * (n – 1) * (n – 2) * … * 1
- Base case: 0! = 1
#include <iostream>
using namespace std;
int factorial(int n) {
// Base case
if (n == 0) {
return 1;
}
// Recursive case
return n * factorial(n - 1);
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout << "Factorial of " << num << " is " << factorial(num) << endl;
return 0;
}
Explanation:
- The factorial function calls itself with n-1 until n reaches 0.
- The base case (n == 0) returns 1, which stops further recursive calls.
- The recursive case multiplies the current number n by the result of factorial(n - 1).
Output:
Enter a number: 5
Factorial of 5 is 120
Factorial of 5 is 120