A problem, one smaller step.
Every recursion needs a stopping point.
Now each answer comes back up.
Solve a smaller problem. Then come back.
To find sum(3), keep the 3 and ask for sum(2) — a smaller problem.
sum(2) does the same: 2 plus an even smaller call, sum(1).
In this example, sum(1) = 1 is the base case: no more calls.
Answers return in reverse order and finish each waiting addition.
sum(n) = n + sum(n − 1), stopping at sum(1) = 1.
LAYER 1 · n = 3
returns 6
sum(3) = 3 +
sum(2)
waiting for sum(2)…
sum(3) = 3 + 3 = 6
LAYER 2 · n = 2
returns 3
sum(2) = 2 +
sum(1)
waiting for sum(1)…
sum(2) = 2 + 1 = 3
calls sum(2)
LAYER 3 · n = 1
STOP · base case
sum(1) =
1
n = 1: stop, no sum(0)
calls sum(1)
returns 1
returns 3
call: hand off a smaller problem
return: send the answer back
Step 1 · Start with sum(3)
Step 2 · Go one layer deeper
Step 3 · Base case reached
Step 4 · Return: 1 → 3 → 6
sum(3) = 3 + 2 + 1 = 6
Pause
Replay
0.0 / 18.0 s