Skip Top Navigation Bar

Iterating over a Two-Dimensional Array

Iterating Over a Two-Dimensional Array

Using a For Loop

Since a two-dimensional (2D) array is an array of arrays, each row of the 2D array is an array. To access the entire row of data, we would use the index of the row. For example:

<type of data>[][] arrayName = { {<data>}, {<data>}, {<data>}, {<data>} };
<type of data>[] firstRow = arrayName[0];

To get the number of columns in a row, access the length of that row. For example:

<type of data>[][] arrayName = { {<data>}, {<data>}, {<data>}, {<data>} };
<type of data>[] firstRow = arrayName[0];
int numCols = firstRow.length;

One way to iterate over the elements of a 2D array is to use a for loop to iterate over the indicies of the rows and columns. Since the indices of the rows array start at 0 and go to length - 1, we will set up our for loop to count the rows from 0 to length - 1 . For each row, we will set up a for loop to iterate over the indices of the columns. Since the columns start at 0 and go to the length of each row - 1, we will nest a for loop that has a counter that starts at 0 and goes to arrayName[<current row>].length - 1.

int[][] gradeBook = { {80, 70, 90, 95}, {83, 72, 95, 100}, {85, 70, 98, 90} };
for(int row = 0; row < gradeBook.length; row++) {
    for (int col = 0; col < gradeBook[row].length; col++) {
        IO.print(gradeBook[row][col] + " ");
    }
    IO.println();
}

Your Turn

Let's try it in the Java Playground.

Using an Enhanced For Loop to Iterate Over Values

An enhanced for loop can be used to iterate over all the values of the 2D array instead of the indicies of the rows and columns. Using the enhanced for loop means that the values are directly accessed without the need for square brackets. The outer loop will access each row and nested inner loop will access each element of that row.

NOTE: You cannot modify the values of an array using an enhanced for loop. If you want to modify the values, use a regular for loop or while loop structure.

The structure of an enhanced for loop to iterate over a 2D array is as follows:

<type of values> [][] nameOfArray = { {<data>}, {<data>}, {<data>} };
for (<type of values>[] row : nameOfArray) {
    for (<type of values> colValues : row) {
        //what you want to do 
    }
}

Your Turn

Let's try it in the Java Playground.

Resources

To come