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 is 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.

../_images/nestedloops.png

Figure 1: Nested Loops

coding exercise Coding Exercises

What does the E01NestedLoops program print out? Step through the code in the debugger. 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 be a 10x8 rectangle? Try replacing line 14 with this print statement to see the rows and columns: System.out.print(row + “-” + col + “ “);

exercise Check your understanding

The main method in the following class should print 10 rows with 5 <code>*</code> in each row. But, the blocks have been mixed up and include <b>one extra block</b> 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 <i>Check Me</i> button to check your solution.</p>

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.

You have attempted of activities on this page