A nested for
loop is a for
loop that is contained within another for
loop. It allows you to iterate over a set of values multiple times, with the inner loop completing all of its iterations for each iteration of the outer loop.
Here’s an example of a nested for
loop in Java:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
System.out.println("i is " + i + ", j is " + j);
}
}
In this example, the outer for
loop will iterate three times, with the variable i
taking on the values 0
, 1
, and 2
. For each iteration of the outer loop, the inner for
loop will iterate twice, with the variable j
taking on the values 0
and 1
. This means that the code inside the inner loop will be executed a total of six times, with the values of i
and j
being printed to the console each time.
Here’s the output of this code:
i is 0, j is 0
i is 0, j is 1
i is 1, j is 0
i is 1, j is 1
i is 2, j is 0
i is 2, j is 1
You can nest for
loops to any depth, but be careful not to create infinite loops or loops that take a long time to complete.
Nested for
loops can be useful when you need to iterate over a two-dimensional array or perform a task multiple times with different combinations of input values.