Skip to main content

Section 5.6 Stack Frames: Implementing Recursion

Suppose that instead of concatenating the result of the recursive call to toStr with the string from convertString, we modified our algorithm to push the strings onto a stack instead of making the recursive call. The code for this modified algorithm is shown in Task 5.6.1.a.

Exploration 5.6.1. Using Stack Instead of Recursion.

(a) C++ Implementation.

(b) Python Implementation.

Each time we make a call to toStr, we push a character on the stack. Returning to the previous example we can see that after the fourth call to toStr the stack would look like Figure 5.6.1. Notice that now we can simply pop the characters off the stack and concatenate them into the final result, "1010".
Image of a stack with character strings representing the result of a conversion process. The stack shows four blocks, each containing a single character. From top to bottom, the blocks are labeled ’1’, ’0’, ’1’, and ’0’, aligned vertically above a horizontal line that represents the base of the stack. This illustrates the sequence of characters placed on the stack during a number conversion, presumably from a recursive process.
Figure 5.6.1. Strings Placed on the Stack During Conversion.
The previous example gives us some insight into how C++ implements a recursive function call. When a function is called in Python, a stack frame is allocated to handle the local variables of the function. When the function returns, the return value is left on top of the stack for the calling function to access. Figure 5.6.2 illustrates the call stack after the return statement on line 4.
Diagram illustrating a call stack generated from the function toStr(10,2), which converts the number 10 into a base 2 string. The bottom of the stack shows ’toStr(10/2, 2) + convertString[10%2]’, then above it ’toStr(5,2) n = 5 base = 2’ with ’toStr(5/2,2) + convertString[5%2]’, followed by ’toStr(2,2) n = 2 base = 2’ and at the top ’toStr(2/2,2) + convertString[2%2]’. A single character ’1’ floats above the stack, indicating the start of the conversion process.
Figure 5.6.2. Call Stack Generated from toStr(10,2).
Notice that the call to toStr(2//2,2) leaves a return value of "1" on the stack. This return value is then used in place of the function call (toStr(1,2)) in the expression "1" + convertString[2%2], which will leave the string "10" on the top of the stack. In this way, the C++ call stack takes the place of the stack we used explicitly in Task 5.6.1.a. In our list summing example, you can think of the return value on the stack taking the place of an accumulator variable.
The stack frames also provide a scope for the variables used by the function. Even though we are calling the same function over and over, each call creates a new scope for the variables that are local to the function.
You have attempted of activities on this page.