Skip to content
Justice Tech School

Nested Loops and Patterns

Loops can be nested to build tables and patterns. A labelled break leaves several loops at once.

Example
for (int r = 1; r <= 3; r++) {
    StringBuilder sb = new StringBuilder();
    for (int c = 1; c <= 3; c++) sb.append(r * c).append(" ");
    System.out.println(sb.toString().trim());
}
outer:
for (int i = 0; i < 3; i++)
    for (int j = 0; j < 3; j++) {
        if (i * j == 2) { System.out.println("found " + i + "," + j); break outer; }
    }

Result

1 2 3
2 4 6
3 6 9
found 1,2

Exercise

Leave nested loops.

 outer;

Quiz Test

What does a label do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.