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.
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 + “ “);
- 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
.
4-4-1: 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 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.
4-4-2: 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();
}
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.