Unit 4 Cycle 1 Day 22: 2D Array Row Traversal
Share
2D Array Row Traversal
Section 4.10 — 2D Array Traversal
Key Concept
Row-major traversal of a 2D array processes all elements in row 0 first, then row 1, and so on. The standard pattern uses nested loops: the outer loop iterates over rows and the inner loop iterates over columns. for (int r = 0; r < grid.length; r++) for (int c = 0; c < grid[r].length; c++). The AP exam tests whether you can predict the order in which elements are visited and what output is produced by a row-major traversal with specific processing logic.
Consider the following code segment.
What is printed?
Answer: (A) 21
Sum all elements: 1+2+3+4+5+6 = 21. The nested loop visits every element in row-major order.
Why Not the Others?
(B) 15 = 1+2+3+4+5, missing the last element.
(C) 6 is the last element, not the total sum.
(D) 9 = sum of first row plus one more element.
Common Mistake
Row-major traversal: outer loop iterates rows, inner loop iterates columns. This visits every element left-to-right, top-to-bottom.
AP Exam Tip
grid.length = rows. grid[r].length = columns in row r. Use both in nested loops. This is the standard 2D traversal pattern.