π4.4: Nested Loops
Table of Contents
π This page is a condensed version of CSAwesome Topic 4.4
π Take notes in a Codespace during class, coding along with the instructor.
- Go to GitHub and click on your picture in the TOP RIGHT corner
- Select
Your repositories
- Open
CS2-Unit-4-Notes
- Now on your repository, click and select the
Codespaces
tab - Click
Create Codespace on main
(unless you already have one listed there), wait for the environment to load, then youβre ready to code!
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
βοΈ Summary
-
Nested iteration statements are iteration statements that appear in the body of another iteration statement.
-
When a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue.
π When class ends, donβt forget to SAVE YOUR WORK!
- Navigate to the
Source Control
menu on the LEFT sidebar - Type a brief commit message in the box, for example:
updated Main.java
- Click the button on the LEFT menu
- Click the button on the LEFT menu
- Finally you can close your Codespace!
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.