Lesson 4.12: Traversing 2D Arrays

Unit 4 · Lesson 4.12 · 2D Arrays

Lesson 4.12: Traversing 2D Arrays

🕑 40–50 min · 10 Practice Questions · Nested Loops · Row-Major · Column-Major · FRQ #4

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.length and arr[0].length correctly 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

MCQ 1
What is printed?
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);
Predict before reading the options.
A 9
B 12
C 21
D 6
C. All six elements are summed: 1+2+3+4+5+6 = 21. The nested loop visits every element in row-major order.
MCQ 2
What is the correct outer loop bound for traversing all rows of a 2D array named data?
A row < data[0].length
B row < data.length
C row <= data.length
D row < data.length - 1
B. 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.
MCQ 3
What is printed?
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);
Count carefully across both rows.
A 2
B 4
C 6
D 3
D. Row 0: 2 ✓, 4 ✓, 6 ✓ = 3 even. Row 1: 1 ✗, 3 ✗, 5 ✗ = 0 even. Total = 3.
MCQ 4
What is printed?
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);
Predict before reading the options.
A 60
B 10
C 30
D 50
A. The standard max algorithm initializes to the first element (10) and updates whenever a larger value is found. The largest value is 60 at row 1, col 2.
MCQ 5
What output does column-major traversal produce for this array?
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] + " ");
    }
}
Trace the column-major order carefully.
A 1 2 3 4
B 2 4 1 3
C 1 3 2 4
D 4 3 2 1
C. Column-major: col=0 → rows 0,1 → prints 1, 3. col=1 → rows 0,1 → prints 2, 4. Full output: "1 3 2 4". A is row-major order.
Tier 3 · AP Mastery

Mastery: Traversing 2D Arrays

MCQ 6
What is printed?
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);
This accesses the diagonal — trace which elements.
A 12
B 15
C 45
D 9
B. The loop accesses 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.
MCQ 7
A method receives a 2D int array and should return the sum of all elements in a given row. Which implementation is correct?
Predict before reading the options.
A
int sum = 0;
for (int col = 0; col < arr.length; col++) {
    sum += arr[rowNum][col];
}
return sum;
B
int sum = 0;
for (int row = 0; row < arr.length; row++) {
    sum += arr[row][rowNum];
}
return sum;
C
int sum = 0;
for (int row = 0; row < arr[0].length; row++) {
    sum += arr[row][rowNum];
}
return sum;
D
int sum = 0;
for (int col = 0; col < arr[0].length; col++) {
    sum += arr[rowNum][col];
}
return sum;
D. To sum a specific row, fix the row index (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.
MCQ 8
What is printed?
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);
}
Compute each row sum before deciding.
A 1 and 2
B 0 and 1
C 2 only
D 0, 1, and 2
A. Row sums: row 0 = 5+10+15 = 30 (not >60). Row 1 = 20+25+30 = 75 ✓ (prints 1). Row 2 = 35+40+45 = 120 ✓ (prints 2). Output: "1" then "2" on separate lines.
MCQ 9
Which loop correctly traverses only the last column of a 2D array named arr?
Predict before reading the options.
A
for (int col = 0; col < arr[0].length; col++) {
    System.out.println(arr[col][arr.length - 1]);
}
B
for (int row = 0; row < arr.length; row++) {
    System.out.println(arr[row][arr.length - 1]);
}
C
for (int row = 0; row < arr.length; row++) {
    System.out.println(arr[row][arr[0].length - 1]);
}
D
for (int col = 0; col < arr.length; col++) {
    System.out.println(arr[arr[0].length - 1][col]);
}
C. Last column index = 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.
MCQ 10
What is printed?
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);
Identify which column is being summed.
A 45
B 6
C 12
D 3
B. The loop accesses 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.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]