Lesson 4.12: Traversing 2D Arrays
Lesson 4.12: Traversing 2D Arrays
What You'll Learn
- 4.12.A: Traverse a 2D array using nested for loops.
- Write row-major and column-major traversals.
- Apply standard algorithms (sum, max, count, search) to 2D arrays.
- Use
arr.lengthandarr[0].lengthcorrectly in nested loop bounds. - Trace nested loop output over a 2D array.
The Nested For Loop Pattern
To visit every element in a 2D array, you need two loops — one for rows and one for columns. The outer loop controls the row index, the inner loop controls the column index:
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println();
}
Output:
1 2 3
4 5 6
7 8 9
This is called row-major order — all columns of row 0 first, then all columns of row 1, and so on.
📌 Loop Bounds — Memorize This
Outer loop (rows): row < arr.length
Inner loop (cols): col < arr[0].length
These two bounds appear in every 2D array traversal on the AP exam. Getting them swapped produces a wrong-shaped traversal or an out-of-bounds exception.
Column-Major Traversal
Swap the loops — outer loop over columns, inner loop over rows — to traverse column by column:
for (int col = 0; col < grid[0].length; col++) {
for (int row = 0; row < grid.length; row++) {
System.out.print(grid[row][col] + " ");
}
System.out.println();
}
Output (column 0 first, then column 1, column 2):
1 4 7
2 5 8
3 6 9
Standard Algorithms on 2D Arrays
Sum of All Elements
int total = 0;
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
total += grid[row][col];
}
}
System.out.println(total); // 45
Finding the Maximum
int max = grid[0][0];
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
if (grid[row][col] > max) {
max = grid[row][col];
}
}
}
System.out.println(max); // 9
Counting Elements That Meet a Condition
int count = 0;
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
if (grid[row][col] % 2 == 0) {
count++;
}
}
}
System.out.println(count); // 4 (values 2, 4, 6, 8)
Row Sum — Processing One Row at a Time
// Print the sum of each row
for (int row = 0; row < grid.length; row++) {
int rowSum = 0;
for (int col = 0; col < grid[0].length; col++) {
rowSum += grid[row][col];
}
System.out.println("Row " + row + " sum: " + rowSum);
}
⚠️ AP Exam Trap: Swapped Loop Bounds
A common error is writing row < grid[0].length and col < grid.length — swapping the two bounds. For a rectangular (non-square) array this produces wrong output or an exception. Always: outer = grid.length (rows), inner = grid[0].length (columns).
✅ FRQ #4 Connection
FRQ #4 on the AP exam always involves a 2D array. Questions typically ask you to write a method that traverses the grid — summing a row, finding a value, counting matches, or processing columns. The nested loop structure and correct use of arr.length / arr[0].length are non-negotiable for full credit.
Summary
- Nested for loops: outer over rows (
arr.length), inner over columns (arr[0].length). - Row-major: outer = rows, inner = cols. Column-major: outer = cols, inner = rows.
- Standard algorithms (sum, max, count, search) extend naturally to 2D with nested loops.
- Swapping loop bounds is the most common 2D array bug — always double-check which is which.
Practice Questions
int[][] arr = {
{1, 2},
{3, 4},
{5, 6}
};
int sum = 0;
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[0].length; col++) {
sum += arr[row][col];
}
}
System.out.println(sum);
data?row < data[0].length
row < data.length
row <= data.length
row < data.length - 1
data.length gives the number of rows. A uses data[0].length which gives columns — wrong for an outer row loop. C uses <= which goes out of bounds. D uses length - 1 which skips the last row.int[][] m = {
{2, 4, 6},
{1, 3, 5}
};
int count = 0;
for (int row = 0; row < m.length; row++) {
for (int col = 0; col < m[0].length; col++) {
if (m[row][col] % 2 == 0) count++;
}
}
System.out.println(count);
int[][] t = {
{10, 20, 30},
{40, 50, 60}
};
int max = t[0][0];
for (int row = 0; row < t.length; row++) {
for (int col = 0; col < t[0].length; col++) {
if (t[row][col] > max) max = t[row][col];
}
}
System.out.println(max);
int[][] arr = {
{1, 2},
{3, 4}
};
for (int col = 0; col < arr[0].length; col++) {
for (int row = 0; row < arr.length; row++) {
System.out.print(arr[row][col] + " ");
}
}
Mastery: Traversing 2D Arrays
int[][] arr = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i][i];
}
System.out.println(sum);
arr[0][0]=1, arr[1][1]=5, arr[2][2]=9 — the main diagonal. Sum = 1+5+9 = 15. Using arr[i][i] is the standard pattern for accessing a diagonal.int sum = 0;
for (int col = 0; col < arr.length; col++) {
sum += arr[rowNum][col];
}
return sum;
int sum = 0;
for (int row = 0; row < arr.length; row++) {
sum += arr[row][rowNum];
}
return sum;
int sum = 0;
for (int row = 0; row < arr[0].length; row++) {
sum += arr[row][rowNum];
}
return sum;
int sum = 0;
for (int col = 0; col < arr[0].length; col++) {
sum += arr[rowNum][col];
}
return sum;
rowNum) and loop over all columns (0 to arr[0].length). A uses arr.length (rows) as the column bound — wrong for non-square arrays. B and C loop over rows and use rowNum as a column — that sums a column, not a row.int[][] g = {
{5, 10, 15},
{20, 25, 30},
{35, 40, 45}
};
for (int row = 0; row < g.length; row++) {
int rowSum = 0;
for (int col = 0; col < g[0].length; col++) {
rowSum += g[row][col];
}
if (rowSum > 60) System.out.println(row);
}
arr?for (int col = 0; col < arr[0].length; col++) {
System.out.println(arr[col][arr.length - 1]);
}
for (int row = 0; row < arr.length; row++) {
System.out.println(arr[row][arr.length - 1]);
}
for (int row = 0; row < arr.length; row++) {
System.out.println(arr[row][arr[0].length - 1]);
}
for (int col = 0; col < arr.length; col++) {
System.out.println(arr[arr[0].length - 1][col]);
}
arr[0].length - 1. Loop over all rows and fix the column. A uses the wrong index for the column (arr.length - 1 gives last row, not last column). B uses arr.length - 1 for the column — same error as A, works only for square arrays. D loops columns and fixes the last row, which traverses the last row, not last column.int[][] arr = {
{3, 1, 4},
{1, 5, 9},
{2, 6, 5}
};
int total = 0;
for (int row = 0; row < arr.length; row++) {
total += arr[row][0];
}
System.out.println(total);
arr[row][0] — always column 0. Column 0 values: 3, 1, 2. Sum = 6. This is the column-sum pattern using a single loop with a fixed column index.Get in Touch
Whether you're a student, parent, or teacher — I'd love to hear from you.
Just want free AP CS resources?
Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]