Unit 4 Cycle 2 Day 12: 2D Array: Column Sum
Share
2D Array: Column Sum
Section 4.11 — 2D Array Algorithms
Key Concept
Computing column sums in a 2D array reverses the loop nesting from row sums: the outer loop iterates over columns and the inner loop iterates over rows. For column c, sum grid[0][c] + grid[1][c] + ... + grid[rows-1][c]. This requires grid[0].length for the column count and grid.length for the row count. The AP exam tests column operations to verify you understand the row-column distinction and can correctly nest loops for column-first processing.
Consider the following code segment.
What is printed?
Answer: (B) 15
Column 1: grid[0][1]=2, grid[1][1]=5, grid[2][1]=8. Sum = 2+5+8 = 15.
Why Not the Others?
(A) 6 is the first row sum, not column 1 sum.
(C) 12 is the second row sum.
(D) 9 is grid[2][2], not a column sum.
Common Mistake
Column sum: fix the column index, loop over rows. grid[r][fixedCol].
AP Exam Tip
Column processing uses a single loop over rows with a fixed column index.