APrep Open the app

AP Computer Science A · Unit 4: Data Collections

4.7 Developing Algorithms Using 2D Arrays

Traversing 2D Arrays

2D arrays are traversed using nested loops — an outer loop for rows, an inner loop for columns (or vice versa). To visit every element, loop `row` from 0 to `arr.length - 1`, and `col` from 0 to `arr[row].length - 1`. Order of traversal (row-major vs column-major) matters for algorithms like searching or printing patterns.

Common Algorithms

Typical tasks include finding a min/max value, summing all elements or a specific row/column, counting elements meeting a condition, and searching for a target value. Many algorithms process partial rows or columns, requiring careful loop bounds using `arr.length` (rows) and `arr[i].length` (columns in that row).

Modifying and Comparing

Algorithms may modify elements in place (e.g., doubling every value) or compare elements across rows/columns (e.g., checking if a matrix is symmetric). Off-by-one errors are common — always double-check loop bounds and whether you're indexing `arr[row][col]` correctly to avoid `ArrayIndexOutOfBoundsException`.

Key terms

How do you traverse a 2D array?
Use nested loops: an outer loop for rows and an inner loop for columns.
arr.length (for 2D array arr)
Returns the number of rows in the 2D array.
arr[i].length
Returns the number of columns (elements) in row i.
Row-major traversal
Processing all elements in a row before moving to the next row.
Common 2D array algorithm tasks
Finding min/max, summing rows/columns, searching for a value, and comparing elements (e.g., symmetry checks).

Try an AP-style question

Code

int[][] g = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int s = 0;
for (int r = 0; r < g.length; r++)
    s += g[r][1];

What is s?

  1. 6
  2. 12
  3. 45
  4. 15
Show the answer

D. Column 1: 2 + 5 + 8.

Practice 8 AP-style questions with instant explanations, flashcards and spaced review.

Study 4.7 free in APrep