The Plain Picture#
A stack of sticky notes. Each time you start a new sub-task, you write it on a new note and put it on top. You can only work on the top note. When you finish it, you peel it off and go back to the note underneath — which was waiting, exactly where you left it.
The Real Names#
Every call — recursive or not — gets its own stack frame with its own copy of the parameters and local variables (Operating Systems Ch 6).
So factorial(4), factorial(3), factorial(2) and factorial(1) each have their own n, all alive on the stack at the same time.
Winding (going down): each call pauses at
factorial(n - 1)and pushes a new frame.Unwinding (coming back up): once the base case returns, each paused frame resumes, finishes its multiplication, and returns to the one below.
Under the Hood — a real trace#
The same method, instrumented to print as it goes (indentation = depth on the stack):
static int factorial(int n, int depth) {
String pad = " ".repeat(depth);
System.out.println(pad + "factorial(" + n + ") called");
if (n <= 1) {
System.out.println(pad + "base case -> 1");
return 1;
}
int smaller = factorial(n - 1, depth + 1);
int result = n * smaller;
System.out.println(
pad + "factorial(" + n + ") = " + n + " * " + smaller + " = " + result
);
return result;
}factorial(4) called
factorial(3) called
factorial(2) called
factorial(1) called
base case -> 1
factorial(2) = 2 * 1 = 2
factorial(3) = 3 * 2 = 6
factorial(4) = 4 * 6 = 24
result = 24The stack at its deepest moment:
┌──────────────────────────┐ ← top: running now │ factorial n = 1 │ returns 1 ├──────────────────────────┤ │ factorial n = 2 │ paused at "2 * factorial(1)" ├──────────────────────────┤ │ factorial n = 3 │ paused at "3 * factorial(2)" ├──────────────────────────┤ │ factorial n = 4 │ paused at "4 * factorial(3)" ├──────────────────────────┤ │ main │ └──────────────────────────┘
Notice: the "called" lines go down (winding), the "=" lines come back up in reverse order (unwinding). Work written before the recursive call happens on the way down; work written after it happens on the way up. Being able to say which is which is the key to reading any recursive code.
Check yourself
3 questionsWhen factorial(1) is running, how many frames of factorial are on the stack, and what is n in each?
Show answerHide answer
Four: n = 4, 3, 2, 1 — each with its own copy.
In the trace, why do the "=" lines appear in the order 2, 3, 4?
Show answerHide answer
Unwinding happens in reverse: the deepest call finishes first and returns to the one that called it.
If you print something before the recursive call, when does it print — going down or coming up?
Show answerHide answer
Going down (during winding).