Skip to main content
Logo image

Section 5.4 Nested loops

Nested loops (or as the College Board likes to call them nested iterations) are simply loops placed in the body of another loop. If we understand how loops work, there’s nothing magic about nested loops: the outer loop runs its body in the normal way for a loop and if that body contains a loop, that loop also runs in the normal way. The whole inner loop, like any other statement in the body of the outer loop, will run as many times as the outer loop’s body runs. And each time it runs, the inner loop must complete all of its iterations before it ends and outer loop can continue to its next iteration.
Nested loops are typically used for working with two dimensions, for example printing a rectangle of stars in rows and columns as shown below.
Figure 5.4.1. Nested Loops

Activity 5.4.1.

What does the following code print out? Click the CodeLens button to trace the code step by step. Notice how the inner loop is started over for each row. Can you predict how many rows and columns of stars there will be?
Can you change the code to print a rectangle with ten rows and eight columns of stars? You can also try replacing the inner print statement with this to see the rows and columns: System.out.println(row + "-" + col + " ");

Activity 5.4.2.

What does the following code print?
for (int i = 1; i < 7; i++) {
    for (int y = 1; y <= 5; y++) {
        System.out.print("*");
    }
    System.out.println();
}
  • A rectangle of 7 rows with 5 stars per row.
  • This would be true if i was initialized to 0.
  • A rectangle of 7 rows with 4 stars per row.
  • This would be true if i was initialized to 0 and the inner loop continued while y < 5.
  • A rectangle of 6 rows with 5 stars per row.
  • The outer loop runs from 1 up to 7 but not including 7 so there are 6 rows and the inner loop runs 1 to 5 times including 5 so there are 5 columns.
  • A rectangle of 6 rows with 4 stars per row.
  • This would be true if the inner loop continued while y < 5.

Activity 5.4.3.

What does the following code print?
for (int i = 0; i < 5; i++) {
    for (int j = 3; j >= 1; j--) {
        System.out.print("*");
    }
    System.out.println();
}
  • A rectangle of 4 rows with 3 star per row.
  • This would be true if i was initialized to 1 or ended at 4.
  • A rectangle of 5 rows with 3 stars per row.
  • Yes, the outer loop runs from 0 up to 5 but not including 5 so there are 5 rows and the inner loop runs from 3 down to 1 so 3 times.
  • A rectangle of 4 rows with 1 star per row.
  • The inner loop runs 3 times when j is 3, 2, and then 1, so there are 3 stars per row.
  • The loops have errors.
  • Try the code in an Active Code window and you will see that it does run.

Activity 5.4.4.

The main method in the following class should print 10 rows with 5 *s in each row. But, the blocks have been mixed up and include one extra block that isn’t needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.

Subsection 5.4.1 Nested loops with Turtles

Try nested loops with turtles to create a snowflake design! If the code below does not work in your browser, you can copy the code into this replit link (refresh page after forking and if it gets stuck) or download the files here to use in your own IDE.

Activity 5.4.5.

The turtle below is trying to draw a square many times to create a snowflake pattern. Can you change the outer loop so that the pattern completes all the way around? Try different ending values for the counter i to find the smallest number that works between 5 and 15.
To make the drawing faster, you can call the World or Turtle object’s setSpeed method with a 0-100 delay value where 0 is the fastest.

Subsection 5.4.2 Coding Challenge: Turtle Snowflakes

In the last exercise, you used nested for-loops to have the turtle draw a square repeatedly to make a snowflake. Use the Active Code window below to have yertle draw the following shapes using nested loops. We encourage you to work in pairs on this.
  1. Complete the code in the active code window below to draw a snowflake of triangles. Remember that triangles have 3 sides and you will need to turn 120 degrees (external angle) 3 times to draw the triangle. Use the turnAmount variable for the single turn after drawing a triangle. How many times did you need to run the outer loop to go all the way around? Try changing the turnAmount variable to 40 to see how many times you need to loop with a wider distance between the triangles.
  2. In the exercise above, you figured out how many times to run the outer loop to finish the snowflake. You may have noticed that the number of times the loop needs to run is related to the angle you turn before drawing the next triangle. These turns have to add up to 360 degrees to go all the way around. Change the outer loop so that it runs the number of times needed by using a formula with the turnAmount variable and 360. Can you draw a snowflake using more or less triangles than before by just changing the turnAmount value?
  3. Create another variable called n for the number of sides in the polygon the inner loop draws. Change the angle in the inner loop to also use a formula with 360 and this new variable. Can you change your snowflake to draw squares or pentagons instead? (Note if this overwhelms the Active Code server and times out, try a larger turnAmount. (Or you can switch to using this replit link or your own IDE).
  4. Let’s add some more color! Add an if/else statement that changes the Color of the pen before the inner loop depending on whether the outer loop variable is odd or even. Remember that even numbers have no remainder when divided by 2.
  5. Be creative and design a unique snowflake!

Project 5.4.6.

Use nested for-loops to have the turtle draw a snowflake of polygons. Use the variable turnAmount to turn after each shape and the variable n for the sides of the polygon.
To make the drawing faster, you can call the World or Turtle object’s setSpeed method with a 0-100 delay value where 0 is the fastest.

Subsection 5.4.3 Summary

  • Nested loops are just loops that appear in the body of another loop.
  • When a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue.
You have attempted of activities on this page.