24su ver.

Note: this is for the Summer 2024 iteration of CSE 121. Looking for a different quarter? Please visit https://courses.cs.washington.edu/courses/cse121/.

2D Arrays

Properties

  • A 2D array is an array of arrays
  • Outer array holds references to each of the inner arrays
  • Often visualized as a grid, table, or matrix, where each row is an inner array
Finding target value in a 2 D array with 4 rows and 3 columns explained below

2D arrays are written in matrix format. In order to access the value at row 2 and column 1, we will first find the target row and then the target column.

  1. Find the target row: arr[2]

We will start from the top of the matrix and traverse downwards to find the desired row, row 2.

  1. Find the target column: arr[2][1]

Once we have found row 2, we will traverse the columns from left to right to find column 1.

  1. Access the target value: arr[2][1]

Remember that 2D arrays also have zero based indexing, so we start counting from the zero row and zero column. Once column 1 is reached, we have identified our target value stored in row 2 and column 1. The target value is arr[2][1].

Constructing A New 2D Array

int[][] arr = new int[numRows][numColumns];

Working with 2D Arrays

Function Description
int value = arr[i][j] Get the value at row i, column j
arr[i][j] Set the value at row i, column j
int[] innerArray = arr[i] Get the inner array at row i
arr.length Return number of rows (number of inner arrays)
arr[i].length Return number of columns (length of inner array)

Common 2D Array Pattern

for (int row = 0; row < arr.length; row++) {
    for (int col = 0; col < arr[row].length; col++) {
        // do something with arr[row][col]
    }
}

2D Array Row Traversal

for (int row = 0; row < arr.length; row++) {
    for (int col = 0; col < arr[row].length; col++) {
        int value = arr[row][col];
        System.out.print(value + " "); // Print the value in each cell of the 2D array
    }
}

The array row traversal works for any 2D array, regardless of its shape

2D Array Column Traversal

for (int col = 0; col < arr[0].length; col++) {
    for (int row = 0; row < arr.length; row++) {
        int value = arr[row][col];
        System.out.print(value + " "); // Print the value in each cell of the 2D array
    }
}

The array column traversal only works if the 2D array is a rectangle