Iterating Through 2D Array

Two Dimensional Arrays

Iterating Through 2D Array

🙋 Need help? Ask an expert now!

We explored using for loops with one-dimensional arrays. Now let's jump into nested for loops as a method for iterating through 2D arrays. A nested for loop is one for loop inside another. Take a look below to see what this means.

Iteration2DExample.java
package exlcode;
 
public class Iteration2DExample {

  public static int[][] exampleVariableOne = {{0, 1, 2, 3, 4}, {4, 5, 6, 7, 8}};

  public static void main(String[] args) {
    // nested for loops are necessary for
    // iterating through a 2D array
    for (int countOne = 0; countOne < exampleVariableOne.length; countOne++) {
      for (int countTwo = 0; countTwo < exampleVariableOne[countOne].length; countTwo++) {
        System.out.print("Index [" + countOne + "][" + countTwo + "]: ");
        System.out.println(exampleVariableOne[countOne][countTwo]);
      }
    }
  }
}

The first for loop loops through each row of the 2D array one by one. As the first loop runs through each row, the second (nested) for loop inside the first loop loops through the columns one by one. The nested for loops runs row by row, checking each column within the row before moving on to the next row.

Because each row could have different numbers of columns, we need to access the specific column length of the specified row. That is why you see exampleVariableOne[countOne].length used within the second nested for loop.

The concept of using loops when working with 2D arrays is an essential tool in every programmer's toolkit. Look meticulously through the code above and become comfortable with how each loop fits into the big picture. When you become comfortable with the for loop, try using “for-each” loops with 2D arrays.

Edit Me on GitHub!

Application Question

A two dimensional array, paramOne, holds integer values ranging from 1 to 10. Consider the following method:

public int exampleMethod(int[][] paramOne)
{
  int row;
  int column;
  int varOne;
  int max = 0;

  for(row = 0; row < paramOne.length; row++) {
    for(column = 0; column < paramOne[0].length; column++) {
      varOne = paramOne[row][column];
      if(varOne > max){
        max = varOne;
      }
    }
  }
  return max;
}

What does this method compute?