Lesson 2 · Unit 01
The call stack
Where unfinished calls wait
What you practise
- Trace frames
- Work before vs after the recursive call
- Depth is O(n) space
Try a question from this lesson
Pick one
Here the print comes after the recursive call. What does it print, top to bottom?
def show(n):
if n == 0:
return
show(n - 1)
print(n)
show(3)function show(n) {
if (n === 0) return;
show(n - 1);
console.log(n);
}
show(3);function show(n: number): void {
if (n === 0) return;
show(n - 1);
console.log(n);
}
show(3);Correct answer
1 2 3
Why
show(3) cannot print until show(2) has finished, and show(2) waits for show(1). The deepest call prints first, so the numbers come out on the way back up: 1 2 3.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Frames on a stack
Every call gets a frame: its own copy of n and a note of where to continue. A frame waits on the call stack while the call it made runs.
The last call made is the first to finish. Lines before the recursive call run on the way down; lines after it run on the way back up.
show(3) waiting
show(2) waiting
show(1) waiting
show(0) returns firstshow(3) waiting
show(2) waiting
show(1) waiting
show(0) returns firstshow(3) waiting
show(2) waiting
show(1) waiting
show(0) returns first9 more exercises in the app
- 2× type the answer
- 3× multiple choice
- 1× true or false
- 1× fill the blanks
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.