JAVA LOOPS

Java nested loops

One loop can be placed inside another. This construct is called a nested loopand helps process tables, grids and multidimensional data.

How do nested loops work?

The outer loop controls the main repetitions. On each of its iterations, the inner loop starts again and completes all its own iterations.

This program creates a simple three-day plan with two meals each day:

// The outer loop iterates through the days
for (int diena = 1; diena <= 3; diena++) {
    System.out.println("Diena: " + diena);

    // The inner loop iterates through that day’s meals
    for (int valgis = 1; valgis <= 2; valgis++) {
        System.out.println("  Valgis: " + valgis);
    }
}
Console output

Diena: 1
  Valgis: 1
  Valgis: 2
Diena: 2
  Valgis: 1
  Valgis: 2
Diena: 3
  Valgis: 1
  Valgis: 2

  1. The outer loop starts on the first day and displays Diena: 1.
  2. The inner loop then starts. It displays the first and second meals for that day.
  3. When the inner loop ends, the program returns to the outer loop and moves to the second day.
  4. On the second day, the inner counter starts again at 1, so two meals are displayed again.
  5. The same happens on the third day. The outer loop thus runs 3 times and the inner loop runs a total of 3 × 2 = 6 times.

A two-dimensional grid example

Imagine a small cinema. The outer loop can traverse the rows, while the inner loop traverses the seats in each row:

for (int eile = 1; eile <= 3; eile++) {
    for (int vieta = 1; vieta <= 4; vieta++) {
        System.out.print("[" + eile + ":" + vieta + "] ");
    }
    System.out.println();
}
Console output

[1:1] [1:2] [1:3] [1:4]
[2:1] [2:2] [2:3] [2:4]
[3:1] [3:2] [3:3] [3:4]

  1. The outer counter eile selects the cinema row: first, second or third.
  2. In each row, the inner counter vieta goes from 1 to 4.
  3. The notation [2:3] means the second row and third seat.
  4. System.out.print() does not move the cursor to a new line, so four seats appear side by side.
  5. When the inner loop ends, an empty System.out.println() starts a new console line for the next cinema row.

Total iteration count

When each outer iteration runs the entire inner loop, the total number of executions of the inner block is the product of the two loops' iteration counts:

int vietuSkaicius = 0;

for (int eile = 1; eile <= 3; eile++) {
    for (int vieta = 1; vieta <= 4; vieta++) {
        vietuSkaicius++;
    }
}

System.out.println("Iš viso vietų: " + vietuSkaicius);
Console output

Iš viso vietų: 12

  1. Initially, vietuSkaicius is 0.
  2. The outer loop traverses 3 cinema rows.
  3. In each row, the inner loop traverses 4 seats.
  4. Whenever a seat is found, vietuSkaicius++ increments the total by one.
  5. The inner block runs a total of 3 × 4 = 12 times, so the console displays Iš viso vietų: 12.
3 rows × 4 seats = 12 seats.

Adding another nested loop multiplies the execution count again, so performance matters for large datasets.

Where are nested loops used?

  • processing table rows and columns;
  • traversing two-dimensional arrays and matrices;
  • creating seating plans for cinemas, classrooms and other spaces;
  • comparing every pair from two datasets;
  • generating repeating patterns and reports.

Write clear nested loops

Give each counter a meaningful name, such as eile and vieta. Proper indentation helps show which block belongs to the outer loop and which to the inner loop.

If there are many nesting levels, consider moving some of the logic into a separate method.