Unit 4 Cycle 1 Day 23: 2D Array Column Traversal
Share
2D Array Column Traversal
Section 4.10 — 2D Array Traversal
Key Concept
Column-major traversal processes all elements in column 0 first, then column 1, and so on. The outer loop iterates over columns and the inner loop iterates over rows: for (int c = 0; c < grid[0].length; c++) for (int r = 0; r < grid.length; r++). This visits the same elements as row-major traversal but in a different order. The AP exam tests whether you can distinguish between row-major and column-major output and predict which elements are processed when.
Consider the following code segment.
What is printed?
Answer: (B) 1 4 2 5 3 6
Column-major: outer loop is columns (c), inner loop is rows (r). Col 0: 1, 4. Col 1: 2, 5. Col 2: 3, 6. Result: 1 4 2 5 3 6.
Why Not the Others?
(A) 1 2 3 4 5 6 is row-major order.
(C) This does not match column-major traversal order.
(D) Row 1 is not visited before row 0.
Common Mistake
Column-major traversal: outer loop on columns, inner loop on rows. This visits top-to-bottom within each column, then moves to the next column.
AP Exam Tip
Row-major: outer=rows, inner=columns. Column-major: outer=columns, inner=rows. The AP exam tests both orderings.