First, if you would format your code as code by clicking the </>
icon, and then paste your code in the space indicated, that will make your code much easier to read. I had to add some curly braces, but your formatted code would look like this:
public 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();
}
}
}
The integer variable k
is initialized at 0
and incremented after each assignment to your array. It is where the values are coming from that make up the elements of the array. By nesting for loops, you are able to iterate through the 2 dimensional array, and populate each index with the value of k
. Let’s look at it step by step:
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++ {
twoD[i][j] = k;
k++;
}
}
First iteration:
i = 0 and j = 0 and k = 0, so twoD[0][0] = 0
Second iteration:
i = 0, j = 1 and k = 1, so twoD[0][1] = 1
Third iteration:
i = 0, j = 2 and k = 2, so twoD[0][2] = 2
Fourth iteration:
i = 0, j = 3 and k = 3, so twoD[0][3] = 3
Fifth iteration:
i = 0, j = 4 and k = 4, so twoD[0][4] = 4
Now j will be 5, so the inner for
loop is finished, and i gets incremented to 1:
Sixth iteration:
i = 1, j = 0 and k = 5, so twoD[1][0] = 5
This process continues until the entire array is populated.
Fast Forward…
Twentieth iteration:
i = 3, j = 4 and k = 19, so twoD[3][4] = 19
When the array is printed, k
is no longer needed. The array already has the values assigned to it. You just iterate through the indexed addresses using the nested for
loops again, and print each value. It may help to visualize this array as a grid like so:
Hope this helps!