Nested Iteration
A loop body can contain another loop. This one prints a picture of a bakery's muffin tray, with one
o for each cup.for (int row = 1; row <= 2; row++)
{
for (int cup = 1; cup <= 6; cup++)
{
System.out.print("o ");
}
System.out.println();
}
The output is two lines, each holding six cups. Each time the outer loop's body runs, the inner loop starts again with
cup at 1 and runs all six passes. Only then does the outer loop reach System.out.println(), which ends the line, and go on to the next row.Counting the passes
The inner loop makes 6 passes per row, and there are 2 rows, so
System.out.print("o ") runs 12 times. Multiplying works here because the inner header doesn't depend on row.The bakery also has a tiered stand where tier 1 holds 4 cakes and each tier holds one more than the tier above it.
for (int tier = 1; tier <= 4; tier++)
{
for (int cake = 1; cake <= tier + 3; cake++)
{
System.out.print("o ");
}
System.out.println();
}
Now the inner loop runs 4 times, then 5, 6, and 7. The counts differ from tier to tier, so they're added rather than multiplied: 4 + 5 + 6 + 7 is 22.
Where a statement goes
The position of a statement in the nest decides how often it runs. The
println() above is inside the outer loop and after the inner one, so it runs after each row's cups. Put inside the inner loop, it would put every cup on its own line. Put after the outer loop, it would run once at the end, and all the cups would print on one line.A variable that describes one row belongs inside the outer loop's body, where it starts fresh for every row.
for (int tier = 1; tier <= 4; tier++)
{
int onTier = 0;
for (int cake = 1; cake <= tier + 3; cake++)
{
onTier++;
}
System.out.println(onTier);
}
This prints 4, 5, 6, and 7, one count for each tier.