Problem Statement
What is the most critical component of a recursive function?
Explanation
The base case is the most critical component because it defines when the recursion should stop. Without a proper base case, the recursive function will call itself infinitely, leading to stack overflow.
The base case is the condition where the function returns a value directly without making another recursive call. It represents the simplest version of the problem that can be solved without recursion. Every recursive call should move closer to the base case, ensuring the recursion eventually terminates.
Code Solution
SolutionRead Only
// Factorial with base case
int factorial(int n) {
// BASE CASE - Critical!
if (n <= 1)
return 1;
// RECURSIVE CASE
return n * factorial(n - 1);
}
// Without base case - INFINITE RECURSION!
int badFactorial(int n) {
return n * badFactorial(n - 1); // Never stops!
}
// factorial(5) execution:
// 5 * factorial(4)
// 5 * 4 * factorial(3)
// 5 * 4 * 3 * factorial(2)
// 5 * 4 * 3 * 2 * factorial(1)
// 5 * 4 * 3 * 2 * 1 = 120