An Animated Introduction To Computer Science
With Processing And Java

Thomas C. O'Connell


DRAFT 2024


Copyright © 2016, 2024 Thomas C. O'Connell, All Rights Reserved

6.2 Drawing Stairs With Loops

With any loop, we have some way to initialize the variables involved in the loop, some condition to tell us when to stop, and some way to update the variables inside the loop. The variables involved in drawing the stairs represent the width and height of the steps. In other words, the parameters to the recursive method, stepWidth and stepHeight become the loop variables. We initialize these variables to have the values passed in to our recursive method by draw. From the code in Figure 6.1.5, we see these values are 800 and 50, respectively. Our initialization code preceding our loop is then:

float stepWidth = 800;

float stepHeight = 50;

Next, we move on to consider the condition on the loop. Remember that in any recursive method, we must have some condition that terminates the recursion. In the case of our recursive drawStairs method, we terminated the recursion when stepWidth was 5 or less. We use this condition as the condition on the while loop. In other words, we will continue executing the loop while stepWidth is larger than 5. The first line of our while loop then becomes:

while (stepWidth > 5) {

Finally, we need to consider how the variables change inside the loop. We can see from the recursive drawStairs method that each time we move on to a new step, we decrease the width of the step by 10% and decrease the height of the step by 5%. In the recursive call, this is accomplished by passing in the arguments stepWidth * 0.9f and stepHeight * 0.95f for the first and second parameters. This initializes the stepWidth parameter in the called drawStairs method to be 90% of what the value of the stepWidth parameter in the calling drawStairs method.

We need to translate this whole process into the loop variables. While in the recursion, there is a different stepWidth parameter for each recursive call, in the loop, there is only one stepWidth variable. To update the value of the stepWidth and stepHeight variables in the loop, we simply use an assignment statement, like so:

stepWidth = stepWidth * 0.9;

stepHeight = stepHeight * 0.95;

The structure of the recursion translates nicely into the structure of the loop. The rest of the loop’s body is identical to the body of the recursive method. The final code for the iterative version of our method is shown in Figure 6.2.1; the output is shown in Figure 6.2.2.

image not found


Figure 6.2.1: Our final code to draw the stairs iteratively.

pict


Figure 6.2.2: The stairs drawn iteratively using the code in Figure 6.2.1 are identical to the stairs drawn recursively in Figure 6.1.6.

Back To Top