Skip to main content

Section 21.2 Recursive Stack Diagrams

Because recursive functions call themselves, stack diagrams that involve recursive functions will show the same function multiple times. Here is the stack diagram Codelens produces for the countdown function:
There are 4 stack frame boxes for the countdown function. They have different values of n, from 3 to 0.
Figure 21.2.1. Stack diagram for the countdown program.
The frame for main is empty because main does not have any variables. The next frame down is the original call to countdown and in it, n has the value 3. Each additional call to countdown creates a new stack frame with a new value of n. As we return from those function calls, the stack frames will be removed one by one.
It can sometimes help to think of each instance of the recursive function as a separate worker (even though it is more accurate to think of one worker managing multiple tasks). Someone is given the task of doing countdown(3). They say β€œhold on a second, let me ask someone to help out” and ask another worker to take care of countdown(2) and then wait for that worker to report that they are done. Once the worker in charge of 2 tells the 3 worker β€œall done with 2”, the 3 worker can then proceed to finish their task. The stack diagram shows a series of workers all waiting to hear from the next worker that it is safe to continue.

Checkpoint 21.2.1.

Run the codelens and answer the questions it asks you.
You have attempted of activities on this page.