Recursion & Iterative Subprograms
Recursion solves a problem by calling itself on a smaller input. Every recursive function needs a base case and enough stack space.
In plain English
Recursion is a set of nesting dolls. Each doll opens a smaller doll, and the smallest one stops.
Base case and recursive case
A recursive function has two parts: a base case that stops the recursion, and a recursive case that calls the function with a smaller or simpler input. If the base case is missing or unreachable, the recursion continues until the stack is exhausted. The factorial function is the classic example: factorial(0) is 1, and factorial(n) is n times factorial(n - 1).
int factorial(int n) {
if (n <= 1) return 1; /* base case */
return n * factorial(n - 1);
}Stack frames and iteration
Each recursive call creates a stack frame holding parameters and local variables. Deep recursion can overflow the stack. An iterative version uses a loop and constant stack space, which is often safer for large inputs. Recursion is clearest when the problem naturally decomposes into smaller subproblems, such as tree traversal.
int factorial_iter(int n) {
int result = 1;
for (int i = 2; i <= n; i++) result *= i;
return result;
}Similarities and trade-offs
Iterative and recursive subprograms are equivalent in power. Both need a terminating condition, both can use local variables and return values, and both can be analyzed for time and space complexity. Recursion expresses the solution in terms of smaller subproblems; iteration expresses it as a repeated state update. A recursive function can always be rewritten iteratively, though the iterative version may need an explicit stack to remember pending work.
Key takeaways
- Every recursive function needs a base case.
- The recursive case must move toward the base case.
- Each call consumes stack space.
- Iteration avoids deep recursion and often uses less memory.
- Recursion and iteration are equivalent in power but differ in how they store pending work.
Common pitfalls
- Missing or unreachable base case.
- Forgetting to return the recursive result.
- Using recursion for very deep inputs.
- Assuming recursion is always faster than iteration.
Key focus
- Trace recursive calls and their return values.
- Know the difference between iterative and recursive subprograms.
- Expect a question asking you to rewrite a recursive function iteratively.
Quick check
1. Which part of a recursive function prevents infinite recursion?
2. What happens if a recursive function never reaches its base case?