Recursion and the call stack

A theatre has one seat in its first row, two in its second, and one more in each new row. How can a function count every seat while handling just one row at a time?

Learning goal

Identify the base case, count active calls and trace a value back through the stack.

Theory

For n seating rows, sum(n) needs the total for the first n − 1 rows. Each active call remembers which row number to add later.

Listen to the explanation

Audio transcript

A theatre has one seat in its first row, two in its second, and three in its third. To count the seats in three rows, the function saves the three and asks for the total in two rows. That call saves the two and asks about one row. The calls stop at zero rows, which contain zero seats. Now follow the returns. One plus zero gives one. Two plus one gives three. Three plus three gives six. Watch the stack as you step forward. Which row number is waiting to be added next?

Read full theory

One row smaller

For four rows, add the four seats in the last row to the total for the first three rows. The function sum(n) returns the total number of seats in the first n rows.

sum(n)
    if n == 0: return 0
    return n + sum(n - 1)

What waits on the stack?

Each call remembers its own row number. For sum(3), calls for 3, 2 and 1 are waiting when sum(0) returns 0. On the way back, the running totals are 1, 3 and 6. The most recent call finishes first.

1Explore

Start with three rows. Step down to the base case, then predict the value passed back on each return.

2Solve it yourself

Make a prediction and test it in the model. If the results differ, compare them and try again with new values.

How you learn here

  1. ExploreYou change the simulation yourself and watch.
  2. Predict & solveFirst you predict, then you calculate, click or build – not just type in numbers.
  3. See the consequencesAfter a mistake the simulation plays out your result and shows the gap.
  4. Write it downYou note in one sentence what you noticed – only then can you go on.
  5. New numbersAfter every mistake you get a new variant. Solving it shows you have understood – guessing does not help.

Curriculum: Recursive algorithms, stopping conditions and tracing function calls.

For teachers: Set this lab as homework and check the proof codes of your class →

Found a mistake? Tell us – every simulation and every answer is checked by code, but people still make mistakes.