๐Ÿ““8.2: Traversing 2D Arrays

Table of Contents


๐Ÿ“– This page is a condensed version of CSAwesome Topic 8.2


Traversing 2D Arrays with Nested Loops

Since 2D arrays are really arrays of arrays, you can use nested loops to iterate through all elements in an array. We first loop through each of the rows (the โ€œinner arraysโ€), and then loop through all the values inside each inner array.

image

Enhanced For-Each Loops

An enhanced for-each loop โ€œvisitsโ€ each item in an array sequentially. Notice the type of the outer loop array variable - it is an array that will hold each row, String[] in the example below for a 2D String array. The type of the variables in the for-each loops must match the type of the array.

String[][] data;

// ENHANCED FOR-EACH nested loops to traverse 2D array
for (String[] rowArray : data) {
  for (String colValue : rowArray) {
    System.out.println(colValue);
  }
}

In this case the for (String[] rowArray : array) means to loop through each element of the outer array (data) which will set the current rowArray to the current array of columns. Then the inner loop iterates through the inner array (the current โ€œcolumnโ€), printing each of the values (colValue).

DATA TYPES: To traverse with enhanced for-each loops, the variable of the outer loop must be the type of each row - which is a 1D array. The inner enhanced for loop variable must be the same type as the elements stored in the array.

Standard For Loops

When writing nested loops to traverse a 2D array, for-each loops like above are much simpler since you donโ€™t have to use the indices and the []โ€™s, but you can only use them if you are NOT going to modify the values in an array.

If you do need to change values, or keep track of the index for another reason, stick to a standard (indexed) for loop:

// STANDARD/INDEXED FOR nested loops to traverse 2D array
for (int row = 0; row < data.length; row++) {
  for (int col = 0; col < data[row].length; col++) {
    System.out.println(data[row][col]);
  }
}
  • array.length provides the number of rows in a 2D array
  • array[0].length provides the number of columns

    The length of the inner array (array[0] is the first row)

Looping through a Subset

You can loop through a subset (smaller portion) of a 2D array as long as you use a standard for loop. You just change the starting and ending bounds for your loops:

int[][] matrix = { {3, 2, 3}, {4, 3, 6}, {8, 9, 3}, {10, 3, 3}};

for (int row = 1; row < 3; row++) {
  for (int col = 0; col <= 2; col++) {
    System.out.println(matrix[row][col]);
  }
}

๐Ÿ’ฌ DISCUSS: What do you think the above code will print out? Which part of the matrix 2D array?

2D Array Algorithms

All of the array algorithms can be applied to 2D arrays too. For example, counting and searching algorithms work very similarly.

๐Ÿงฎ Counting/Accumulating

Method Definition:

public static int getTotalForRow(int row, int[][] a) {
  int total = 0;
  for (int col = 0; col < a[0].length; col++) {
    total = total + a[row][col];
  }
  return total;
}

Method Call (in main):

public static void main(String[] args) {
  int[][] matrix = { {1, 2, 3}, {4, 5, 6}};
  System.out.println(getTotalForRow(0, matrix));
}

๐Ÿ’ป Can you complete the method called getTotalForCol that computes the total for a column? To do this, you must loop through the rows. The arrayโ€™s length will tell you how many rows you have, while the length of the arrayโ€™s first element will tell you how many columns.

public static int getTotalForCol(int col, int[][] a) {
  int total = 0;
  // Add a loop here to total a column col

  return total;
}

The linear (sequential) search algorithm for a 2D array iterates through all of the rows and columns until either the target value is found, or the entire 2D array has been traversed without finding the target.

Method Definition:

public static boolean search(int[][] array, int value) {
  boolean found = false;
  for (int row = 0; row < array.length; row++) {
    for (int col = 0; col < array[0].length; col++) {
      if (array[row][col] == value) {
        found = true;
      }
    }
  }
  return found;
}

Method Call (in main):

public static void main(String[] args) {
  int[][] matrix = { {3, 2, 3}, {4, 3, 6}, {8, 9, 3}, {10, 3, 3}};
  System.out.println(search(matrix, 10));
  System.out.println(search(matrix, 11));
}

๐Ÿ’ป Can you change the methodโ€™s code to work for a String 2D array instead of an int array? Note that the indices row and col will still be integers.

// In the MAIN method, try these:
String[][] matrix2 = { {"a","b","c"},{"d","e","f"} };
System.out.println(search(matrix2, "b"));

โญ๏ธ Summary

  • We can iterate through 2D arrays using nested standard for loops or nested enhanced for-each loops.

  • The outer loop for a 2D array usually traverses the rows, while the inner loop traverses the columns in a single row.

  • The 2D arrayโ€™s length gives the number of rows. A rowโ€™s length array[0].length gives the number of columns.

  • Nested iteration statements can be written to traverse the 2D array in โ€œrow-major orderโ€ or โ€œcolumn-major order.โ€

  • In an enhanced for-each loop, the variable of the outer loop must be the type of each row, which is a 1D array. The inner enhanced for loop variable must be the same type as the elements stored in the array.

  • All standard 1D array algorithms can be applied to 2D array objects.

    • When applying sequential/linear search algorithms to 2D arrays, each row must be accessed, then sequential/linear search applied to each row of a 2D array.

2D Arrays Practice Game

๐ŸŽฒ Try the game below to practice! Click on Arrays and then check on 2D. To play, click on the element of the * array that would be printed out by the given code.

If youโ€™re stuck, check on Labels to see the column indices.


Acknowledgement

Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.