01 / 21

2D Array
Traversals

Master row-major and column-major traversal patterns, nested loop mechanics, and common pitfalls when navigating two-dimensional arrays in Java.

AP Computer Science A

What Is a 2D Array?

A 2D array is an array of arrays: the outer array holds references to inner arrays, each of which stores actual data values. Think of it as a grid with rows and columns.

[0] [1] [2] [0] [1] [2] 5 12 3 8 1 7 4 9 6

The Memory Model

In Java, a 2D array is not a contiguous block of memory like in C. Each row is a separate 1D array object on the heap. The outer array stores references to these inner arrays.

arr ref[0] ref[1] ref[2] 5 12 3 8 1 7 4 9 6

Why Traversals Matter

Nearly every 2D array problem on the AP exam requires you to visit every element systematically. The order you visit determines what you can compute and how efficiently.

Searching
Find a target value, the max, the min, or count occurrences in the grid.
Transforming
Rotate, flip, transpose, or apply a filter to every cell of the grid.
Aggregating
Sum rows, compute averages, or build frequency tables from grid data.

Row-Major Traversal

The outer loop iterates over rows, and the inner loop iterates over columns. This visits every element left to right, top to bottom.

for (int r = 0; r < arr.length; r++) { for (int c = 0; c < arr[r].length; c++) { // process \(\text{arr[r][c]}\) } }
1 2 3 4 5 6 7 8 9 10 11 12

Column-Major Traversal

Swap the loop order: the outer loop iterates over columns, the inner loop iterates over rows. This visits elements top to bottom, left to right.

for (int c = 0; c < arr[0].length; c++) { for (int r = 0; r < arr.length; r++) { // process \(\text{arr[r][c]}\) } }
1 2 3 4 5 6 7 8 9 10 11 12

Row-Major vs Column-Major

Row-Major Column-Major
Outer loop rows (\(\text{r}\)) columns (\(\text{c}\))
Inner loop columns (\(\text{c}\)) rows (\(\text{r}\))
Visit order Left → right, top → bottom Top → bottom, left → right
Best for Row sums, reading text Column sums, vertical scans
AP CSA default? ✓ Yes Only when needed

A restorer repairs a luminous pixel mosaic

A restorer lifts a tile from a luminous rectangular mosaic.Grid algorithms turn a visual pattern into explicit row and column operations. Bounds checks determine which neighboring cells can be accessed.

Traversal order changes the first match

The same 3-by-4 array shows column-major and row-major search paths stopping at different qualifying cells.For this 3-by-4 array, column-major search finds the first value greater than 20 at [2][1]: 21. Row-major search instead reaches 25 at [1][2] first. The row sums are 28, 62 and 64.

Enhanced For-Each Loop

Java's enhanced for loop provides a cleaner syntax when you don't need the index. The outer loop retrieves each row (a 1D array), and the inner loop retrieves each element.

for (int[] row : arr) { for (int val : row) { // process val } }
✓ Use when
You need to read every value but don't need row or column indices.
✕ Avoid when
You need to modify elements, check neighbors, or track position.

Step-by-Step Approach

1
Identify the task: Do you need row sums, column sums, a search, or a transformation?
2
Choose traversal order: Row-major for row operations, column-major for column operations.
3
Pick the loop type: Standard for loops if you need indices; enhanced for-each if you only need values.
4
Set correct bounds: Use \(\text{arr.length}\) for rows and \(\text{arr[r].length}\) for columns (not the other way around).
5
Process each element: Accumulate, compare, or modify inside the inner loop body.

Example: Sum All Elements

Given a 2D array, compute the total sum of all elements using a row-major traversal.

int total = 0; for (int r = 0; r < grid.length; r++) { for (int c = 0; c < grid[r].length; c++) { total += grid[r][c]; } } // total now holds the sum
2 5 3 8 1 4 → total 23

Example: Column Sums

Compute the sum of each column. This requires a column-major traversal so we can accumulate each column's total separately.

int numCols = grid[0].length; int[] colSums = new int[numCols]; for (int c = 0; c < numCols; c++) { for (int r = 0; r < grid.length; r++) { colSums[c] += grid[r][c]; } }
2 5 3 8 1 4 6 7 9 = 16 = 13 = 16 colSums: 16 13 16

Example: Search for a Value

Search a 2D array for a target value and return its row and column. We need index-based loops because we must report the position.

public static int[] find(int[][] grid, int target) { for (int r = 0; r < grid.length; r++) { for (int c = 0; c < grid[r].length; c++) { if (grid[r][c] == target) { return new int[]{r, c}; } } } return null; // not found }

Example: Reverse Each Row

Reverse the elements within each row of a 2D array. Here the inner loop only goes halfway across each row, swapping from both ends toward the center.

for (int r = 0; r < grid.length; r++) { int left = 0; int right = grid[r].length - 1; while (left < right) { int temp = grid[r][left]; grid[r][left] = grid[r][right]; grid[r][right] = temp; left++; right--; } }
Before 1 2 3 4 → After 4 3 2 1 swap swap

Understanding .length

The most critical detail on the AP exam: knowing which \(\text{.length}\) gives you what. Getting it wrong causes an ArrayIndexOutOfBoundsException.

\(\text{arr.length}\)
Number of rows in the 2D array (the outer array's size).
\(\text{arr[r].length}\)
Number of columns in row r (the inner array's size).
int[][] arr = new int[3][5]; // arr.length → 3 (rows) // arr[0].length → 5 (cols in row 0) // arr[2].length → 5 (cols in row 2)

Common Mistakes

✕ Swapped Bounds
Using \(\text{arr.length}\) for columns and \(\text{arr[0].length}\) for rows: this crashes or silently skips data.
✕ Wrong Index Order
Writing \(\text{arr[c][r]}\) instead of \(\text{arr[r][c]}\): the first index is always the row, the second is the column.
✕ Off-by-One
Using \(\le\) instead of \(<\) in loop conditions: arrays are zero-indexed, so the last valid index is \(\text{length} - 1\).
✕ Modifying with For-Each
Assigning to the loop variable \(\text{val} = 0\) inside an enhanced for loop: this doesn't change the array.

Traversal Summary

Pattern Outer Inner Use Case
Row-major (standard) row col Default; row ops
Column-major col row Column ops
Enhanced for-each \(\text{int[] row}\) \(\text{int val}\) Read-only scan
Partial traversal row subset col subset Sub-grid, border
Diagonal Single loop: \(\text{arr[i][i]}\) Main diagonal

Question 1 of 5

Given \(\text{int[][] m = new int[4][6];}\), what does \(\text{m.length}\) return?

Question 2 of 5

Which traversal visits elements in the order: \(\text{arr[0][0], arr[1][0], arr[2][0], arr[0][1], arr[1][1], ...}\)?

Question 3 of 5

What is the value of \(\text{sum}\) after the code executes?

Question 4 of 5

You need to double every element in a 2D array. Which loop type should you use?

Question 5 of 5

What does the \(\text{mystery}\) method return?