Firstly, here's the code in a bit more "readable" format, which makes it a bit easier to interpret:
class TwoDArray {
public static void main(String args[]) {
int twoD[][] = new int[4][5];
int i, j, k = 0;
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twoD[i][j] = k;
k++;
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
You have four
for
loops totally (two outer for loops with each an inner for loop).
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twoD[i][j] = k;
k++;
}
The above is the first outer loop. The code that's ran in the outer loop is not wrapped within
{ }
so that means that only the next statement will be ran in the loop, and here this statement is another loop! So you have a
nested loop[
^], a loop in a loop. When your loop runs, this is what will happen with the variables
i
,
j
and
k
(
before k++
) in chronological order:
i = 0, j = 0, k = 0
i = 0, j = 1, k = 1
i = 0, j = 2, k = 2
i = 0, j = 3, k = 3
i = 0, j = 4, k = 4
i = 1, j = 0, k = 5
i = 1, j = 1, k = 6
i = 1, j = 2, k = 7
i = 1, j = 3, k = 8
i = 1, j = 4, k = 9
i = 2, j = 0, k = 10
- ... and so on. As you can see, for each
i
, the whole loop for j
runs.
Then, the second outer loop:
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
Same idea: it's a nested loop. But here, the inner loop doesn't have brackets to specify the block for the loop 'contents', so only the next statement belongs to the loop, which is the
print
statement - the
println
only belongs to the outer loop, and not to the inner loop.