Recursion
What is recursion?
A function solves a problem by calling itself on a smaller version of the same problem.
Two essential parts
- Base case — the smallest problem, answered directly (stops the recursion)
- Recursive case — break the problem down and call yourself
int factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
How it runs: the call stack
factorial(4) → 4 * factorial(3) → 3 * factorial(2) → 2 * factorial(1) → 1
Then results unwind: 2 → 6 → 24.
Each call has its own stack frame with its own local variables.
Stack overflow ⚠️
- No base case (or never reaching it) → infinite recursion → crash
- Very deep recursion (e.g. 1,000,000 levels) can overflow the stack even if correct — use a loop instead
Classic recursive problems
| Problem | Idea |
|---|---|
| Factorial, power | n × f(n−1) |
| Fibonacci | f(n−1) + f(n−2) (slow without memoization!) |
| Sum of digits | last digit + f(n / 10) |
| Reverse a string | f(rest) + first char |
| Binary search | search one half |
| Tower of Hanoi | move n−1, move 1, move n−1 |
| Trees, folders, JSON | process node, recurse into children |
| Permutations, backtracking | try a choice, recurse, undo |
Recursion vs iteration
| Recursion | Iteration |
|---|---|
| Elegant for trees/divide-and-conquer | Usually faster, no stack risk |
| Uses stack memory | Constant memory |
Memoization
Naive Fibonacci recomputes the same values exponentially many times. Store results (in a vector or map) to make it linear — the start of dynamic programming (Unit 18).
Example
#include <iostream>
#include <string>
#include <vector>
long long factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
int sum_digits(int n) { return n < 10 ? n : n % 10 + sum_digits(n / 10); }
std::string reverse(const std::string& s) {
if (s.size() <= 1) return s;
return reverse(s.substr(1)) + s[0];
}
int calls = 0;
long long fib_slow(int n) { ++calls; return n < 2 ? n : fib_slow(n - 1) + fib_slow(n - 2); }
long long fib_memo(int n, std::vector<long long>& memo) {
if (n < 2) return n;
if (memo[n] != -1) return memo[n]; // already computed
return memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo);
}
void hanoi(int n, char from, char to, char via, int& moves) {
if (n == 0) return;
hanoi(n - 1, from, via, to, moves);
++moves;
if (n == 3) std::cout << " move the largest disk " << from << " -> " << to << '\n';
hanoi(n - 1, via, to, from, moves);
}
int main() {
std::cout << "10! = " << factorial(10) << '\n';
std::cout << "sum_digits(98765) = " << sum_digits(98765) << '\n';
std::cout << "reverse(\"budget\") = " << reverse("budget") << '\n';
std::cout << "fib_slow(25) = " << fib_slow(25) << " using " << calls << " calls\n";
std::vector<long long> memo(91, -1);
std::cout << "fib_memo(90) = " << fib_memo(90, memo) << '\n';
int moves = 0;
std::cout << "Tower of Hanoi with 3 disks:\n";
hanoi(3, 'A', 'C', 'B', moves);
std::cout << " total moves: " << moves << '\n';
return 0;
}
/* Output:
10! = 3628800
sum_digits(98765) = 35
reverse("budget") = tegdub
fib_slow(25) = 75025 using 242785 calls
fib_memo(90) = 2880067194370816120
Tower of Hanoi with 3 disks:
move the largest disk A -> C
total moves: 7
*/