CIE AS & A Level Computer Science, section 19.2 (Recursion)
The call stack
Each time a routine is called, the computer stores the return address, parameters and local variables on the call stack as a stack frame. When the call finishes, its frame is popped and control returns.
For a recursive function, there is a frame for every active call.
Winding and unwinding
- Winding: the function keeps calling itself, and the frames are pushed until the base case is reached. No results yet.
- Unwinding: the base case returns, and each earlier call finishes in turn, using the returned value.
Tracing factorial(3)
| Step | Action | Stack (top on the right) |
|---|---|---|
| 1 | call factorial(3) |
3 |
| 2 | call factorial(2) |
3, 2 |
| 3 | call factorial(1) |
3, 2, 1 |
| 4 | call factorial(0), base case returns 1 |
3, 2, 1, 0 |
| 5 | factorial(1) returns |
3, 2, 1 |
| 6 | factorial(2) returns |
3, 2 |
| 7 | factorial(3) returns |
3 |
The final answer is 6.
def factorial(n, depth=0):
pad = " " * depth
print(pad + "call", n)
if n == 0:
print(pad + "base case, return 1")
return 1
result = n * factorial(n - 1, depth + 1)
print(pad + "return", result)
return result
factorial(3)
Stack overflow
If a recursion goes too deep (or has no base case), the stack runs out of space: a stack overflow.
import sys
print(sys.getrecursionlimit()) # Python's limit, often 1000
Output order
Statements before the recursive call run during winding; statements after it run during unwinding, in reverse order.
def countdown(n):
if n == 0:
return
print("going down", n)
countdown(n - 1)
print("coming back", n)
countdown(2)
# going down 2, going down 1, coming back 1, coming back 2
Common mistake: writing the results in the wrong order. Nothing is returned until the base case is reached, and calls then finish in reverse order (the last call first). Also, do not forget the base case call in your trace.
Exam tip: draw the stack as a table of calls and mark where the base case is reached. State what is returned at each step during unwinding.
Check yourself
What is stored on the call stack for each call?
The return address, parameters and local variables (a stack frame).
What is a stack overflow?
When the call stack runs out of space, usually from recursion that is too deep or never ends.
During which phase are results calculated?
The unwinding phase, after the base case has been reached.