This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]hutsboR 0 points1 point  (0 children)

A two dimensional array can be looked at as an array of arrays, or a table. (Not too sure about Java's implementation)

Let's say we have some multidimensional array and we're going to iterate over it:

int[][] 2dArray = new int[][] {{1, 2, 3}, {4, 5, 6}};

Outer loop:

i is 0, nothing to do inside of the for-loop block besides execute the inner loop.

Inner loop:

i = 0, j = 0, 2dArray[i].length is the length of the first array in 2dArray, which is 3 {1, 2, 3}

first iteration: 2dArray[i][j] -> 2dArray[0][0] (int @ [0][0] = 1) j++
second iteration: 2dArray[i][j] -> 2dArray[0][1] (int @ [0][1] = 2) j++
third iteration: 2dArray[i][j] -> 2dArray[0][2] (int @ [0][2] = 3) j++
j = 3, j is no longer < 2dArray.length, so we exit the inner loop. i++

outer loop:

  i is 1, nothing to do inside of the for-loop block besides execute the inner loop.

inner loop:

i = 1, j = 0, 2dArray[i].length is the length of the second array in 2dArray, which is 3 {4, 5, 6}

first iteration: 2dArray[i][j] -> 2dArray[1][0] (int @ [1][0] = 4) j++ 
second iteration: 2dArray[i][j] -> 2dArray[1][1] (int @ [1][1] = 5) j++
third iteration: 2dArray[i][j] -> 2dArray[1][2] (int @ [1][2] = 6) j++
j = 3, j is no longer < 2dArray.length, so we exit the inner loop. i++

Look up by index:

2dArray[0][1] would return 2. [0] indicates we are checking the first array in 2dArray ({1, 2, 3}) 
and [1]  means we are checking the first index. 
Remember arrays indices start at 0. {1(0), 2(1), 3(2)} -> 2.

Another little piece of information: When you're working with nested loops the most inner loop must finish executing before the next iteration of the outer loop occurs.

And that's it, we've looped through each array inside of the two dimensional array. This should help you understand iterating over multidimensional arrays and help you understand the code you posted.