APrep Open the app

AP Computer Science A · Unit 4: Data Collections

4.6 Traversing 2D Arrays

Nested loops traverse 2D arrays

A 2D array is traversed using nested for loops — an outer loop for rows and an inner loop for columns. The outer loop variable indexes `arr.length` (number of rows), and the inner loop indexes `arr[row].length` (number of columns in that row). This structure lets you visit every element exactly once.

Row-major order

Standard traversal visits elements in row-major order: all elements of row 0 first, then row 1, and so on. Code pattern: `for (int r = 0; r < arr.length; r++) { for (int c = 0; c < arr[r].length; c++) { ...arr[r][c]... } }`. Swapping loop order gives column-major traversal instead.

Common traversal tasks

Traversals are used to sum elements, find max/min, search for a value, or modify elements in place. When array rows have different lengths (ragged arrays), always use `arr[r].length` in the inner loop rather than a fixed number to avoid `ArrayIndexOutOfBoundsException`.

Key terms

Nested for loops (2D array)
An outer loop iterates over rows (arr.length) and an inner loop iterates over columns (arr[r].length) to visit every element.
Row-major order
Traversal method that processes all elements of a row before moving to the next row.
arr.length vs arr[r].length
arr.length = number of rows; arr[r].length = number of columns in row r.
Ragged (jagged) array
A 2D array whose rows have different lengths; requires using arr[r].length in the inner loop.
Common 2D traversal tasks
Summing elements, finding max/min, searching for a value, and modifying elements in place.

Try an AP-style question

Code

int[][] g = {{1, 2}, {3, 4}};
for (int r = 0; r < g.length; r++)
    for (int c = 0; c < g[0].length; c++)
        System.out.print(g[r][c]);

What is printed?

  1. 4321
  2. 1234
  3. 1324
  4. 12
Show the answer

B. Row-major order.

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

Study 4.6 free in APrep