1. Introduction
Let's start with a question: why would you ever need to nest one loop inside another? Often our data or tasks are organized not as a single line but, for example, as a table, grid, or even a multidimensional structure. Suppose you want to print a multiplication table, iterate over a two-dimensional array, or compute intersections between all pairs of elements. One loop is clearly not enough—you need a loop inside a loop.
In programming, a nested loop is like two alarm clocks: the outer one starts ringing, and inside it another one runs that will ring each time as long as the first is active. Thus, while one “outer” iteration is in progress, the inner one runs through its entire path (and does so again and again for each outer iteration).
A good example is hours and minutes. Hours are the outer loop from 0 to 23, minutes are the inner loop from 0 to 59. For each change of the outer loop, the inner loop goes through all its values.
2. Syntax of nested loops
In Java, the syntax of nested loops is no different from regular loops—you simply write one loop inside the body of another. Let's look at examples with for and while:
// Outer for loop
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++) // Inner for loop
{
System.out.print(i + "," + j + " ");
}
System.out.println(); // Line break after the inner loop
}
Here the outer loop controls the variable i (from 0 to 2), and the inner loop controls j (from 0 to 3). For each value of i, the inner loop fully runs from j == 0 to j == 3. If you run this code, you'll see a neat grid of coordinates:
0,0 0,1 0,2 0,3
1,0 1,1 1,2 1,3
2,0 2,1 2,2 2,3
An analogous example using while:
int i = 0;
while (i < 3)
{
int j = 0;
while (j < 4)
{
System.out.print(i + "," + j + " ");
j++;
}
System.out.println();
i++;
}
Note: during each pass of the outer loop, the inner loop's variable (j) must be reinitialized; otherwise, you'll see only a single row!
3. Examples of nested loops in action
Example 1: printing a chessboard (8x8)
Let our first task be to print a classic chessboard as black and white cells (let ‘#’ be black and ‘.’ be white). We'll implement it using nested for loops:
for (int row = 0; row < 8; row++)
{
for (int col = 0; col < 8; col++)
{
// If the sum of row and column indexes is even, the cell is white; otherwise, it is black
if ((row + col) % 2 == 0)
System.out.print("_");
else
System.out.print("#");
}
System.out.println(); // Line break after each row
}
Result:
_#_#_#_#
#_#_#_#_
_#_#_#_#
#_#_#_#_
_#_#_#_#
#_#_#_#_
_#_#_#_#
#_#_#_#_
Important point: nesting ensures that for each row (row) we fully iterate over all columns (col). Without nesting, you wouldn't get the board structure—only a single row or a single column.
Example 2: multiplication table
One of the classic candidates for nested loops! Let's print the 1–9 multiplication table:
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= 9; j++)
{
System.out.print(i * j + "\t");
}
System.out.println();
}
The formatting i * j + "\t" adds tabs so the table looks neat.
Result:
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
...
9 18 27 36 45 54 63 72 81
4. Nested loops and how to control them—nuances
On the effect of break and continue in nested loops
This is where many beginners get tripped up! If you use break or continue in the inner loop, they affect only that loop. The outer loop continues as if nothing happened.
Example: early exit from the inner loop only
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 5; j++)
{
if (j == 3)
break; // exit only from the inner loop!
System.out.print(i + "," + j + " ");
}
System.out.println();
}
Result:
0,0 0,1 0,2
1,0 1,1 1,2
2,0 2,1 2,2
If you need to exit two nested loops at once (for example, to stop a search immediately upon the first successful match in a table), you typically use a flag or a special technique (for example, return if everything happens inside a function).
5. Visualizing nested loops
Sometimes it's hard to “see” the execution order of nested loops. Let's look at the following flowchart:
In tabular form—how many iterations in total will there be for i from 1 to 3, j from 1 to 4?
| i | j (iterated for each i) | Inner loop iterations |
|---|---|---|
| 1 | 1, 2, 3, 4 | 4 |
| 2 | 1, 2, 3, 4 | 4 |
| 3 | 1, 2, 3, 4 | 4 |
| Total: 3 × 4 = 12 |
6. Mistakes and pitfalls when working with nested loops
A common mistake is incorrect initialization of the inner loop variable. For example, declaring it outside the outer loop but not resetting it on each step. As a result, the inner loop may not run at all or may run incorrectly.
int j = 0;
for (int i = 0; i < 3; i++)
{
while (j < 4) // Oops! j may already be 4 after the first iteration.
{
System.out.print(i + "," + j + " ");
j++;
}
System.out.println();
}
Here the loop will run only once. Don't forget to initialize inner-loop variables inside the outer loops!
Also, if you accidentally write two nested loops with the same variables (for (int i = 0; ...) { for (int i = 0; ...) { ... } }), the compiler will complain: the variable is already defined.
GO TO FULL VERSION