Tracing Recursion
in C++
Master the art of tracing recursive calls step by step, understand the call stack, and build intuition for how functions call themselves.
What Is Recursion?
A recursive function is a function that calls itself as part of its own execution. Every recursive function must have two essential parts: a base case that stops the recursion, and a recursive case that breaks the problem into a smaller sub-problem.
The Call Stack
The call stack is a region of memory that keeps track of active function calls. When a function is called, a new frame is pushed onto the stack. When it returns, that frame is popped off. The stack follows a Last In, First Out (LIFO) order.
Why Tracing Matters
Tracing recursion means manually following each function call and return value step by step. It builds intuition about the order of operations, helps you predict output, and is essential for debugging recursive code.
The Two Rules of Recursion
Anatomy of a Recursive Call
Iteration vs Recursion
| Iteration (Loops) | Recursion | |
|---|---|---|
| Mechanism | Repeats via for/while | Calls itself |
| Termination | Loop condition becomes false | Base case is reached |
| Memory | Single frame on the stack | One frame per call |
| Risk | Infinite loop | Stack overflow |
| Readability | Familiar, straightforward | Elegant for tree/divide problems |
How to Trace: Step by Step
Example 1: Tracing sumTo(4)
Example 2: Fibonacci Tree
Example 3: Print Before vs After
Stack Unwinding Visualized
When countUp(3) is called, the print statement comes after the recursive call. The function reaches the base case first, then unwinds back up, printing at each return.
Multiple Recursive Calls
Some functions make more than one recursive call per invocation. This creates a tree of calls instead of a linear chain. Each branch is resolved independently before the caller can combine results.
Tracing Return Values
Common Mistakes
Recursion Cheat Sheet
| Concept | Key Point | Example |
|---|---|---|
| Base Case | Stops recursion | if (\(n \le 1\)) return 1 |
| Recursive Case | Calls itself smaller | \(n \cdot f(n-1)\) |
| Call Stack | LIFO frame storage | Each call = new frame |
| Print Before | Output on the way down | 3 2 1 |
| Print After | Output on the way up | 1 2 3 |
| Tree Recursion | Multiple calls per frame | \(\text{fib}(n-1) + \text{fib}(n-2)\) |
Question 1 of 5
What is the output of the following code?
void mystery(int n) {
if (n <= 0) return;
cout << n << " ";
mystery(n - 2);
}
// Called as: mystery(5)
Question 2 of 5
How many times is fib() called in total when computing fib(5)?
Question 3 of 5
What is the output of this code?
void printReverse(int n) {
if (n <= 0) return;
printReverse(n - 1);
cout << n << " ";
}
// Called as: printReverse(4)
Question 4 of 5
What happens if a recursive function has no base case?
Question 5 of 5
What does the following function return when called as mystery(4)?
int mystery(int n) {
if (n == 0) return 1;
return n * mystery(n - 1);
}