📓2.11: Nested Iteration
Table of Contents
📖 This page is a condensed version of CSAwesome Topic 2.11
Nested For Loops
A nested loop has one loop inside of another. These are typically used for working with two dimensions such as printing stars in rows and columns as shown below:
When a loop is nested inside another loop, the inner loop runs many times inside the outer loop. In each iteration of the outer loop, the inner loop will be re-started.
The inner loop must finish all of its iterations before the outer loop can continue to its next iteration!
💬 DISCUSS: What does the following code print out? Watch the code run in the Java visualizer.
Notice how the inner loop is started over for each
row
. Can you predict how many rows and columns of stars there will be?
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 5; col++) {
System.out.print("*");
}
System.out.println();
}
Can you change the code to print a rectangle with 10 rows and 8 columns of stars? You can also try replacing line 10 with this print statement to see the rows and columns:
System.out.print(row + "-" + col + " ");
Nested Loops with Turtles
❄️ Try nested loops with Turtle
objects to create a snowflake design!
💻 In-Class Activity: Turtle Snowflakes
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.