Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

2.5 Iteration — nested loops

Lesson

Loops inside loops

A loop can contain another loop. For every single pass of the outer loop, the inner loop runs all the way through. Nested loops are how you build grids, tables, and rows of repeated output.


Worked example

for (int r = 1; r <= 2; r++) {
    for (int c = 1; c <= 3; c++) {
        System.out.print("*");
    }
    System.out.println();
}

The inner loop prints ***; the outer loop repeats that on 2 rows. Output is two lines of *** (6 stars total).


▶ Try it: run this, then change 2 (rows) and 3 (columns) and re-run — you get a rectangle of any size.



How many times does print("*") run in total?

for (int r = 1; r <= 2; r++) {
    for (int c = 1; c <= 3; c++) {
        System.out.print("*");
    }
}

For each single pass of the outer loop, how many times does the inner loop run?


Type exactly what this prints:

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        System.out.print("x");
    }
    System.out.println();
}

True or false?