πŸ““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.

  1. Go to GitHub and click on your picture in the TOP RIGHT corner
  2. Select Your repositories
  3. Open CS2-Unit-4-Notes
  4. Now on your repository, click and select the Codespaces tab
  5. 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:

image

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

  1. Go to
  2. Make sure you SIGN IN!
  3. Complete the Programming Challenge: Turtle Snowflake activity in pairs.

⭐️ 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!

  1. Navigate to the Source Control menu on the LEFT sidebar
  2. Type a brief commit message in the box, for example: updated Main.java
  3. Click the button on the LEFT menu
  4. Click the button on the LEFT menu
  5. Finally you can close your Codespace!

Acknowledgement

Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.