Unit 4 Cycle 2 Day 12: 2D Array: Column Sum

Unit 4 Advanced (Cycle 2) Day 12 of 28 Advanced

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.

int[][] grid = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int colSum = 0; for (int r = 0; r < grid.length; r++) { colSum += grid[r][1]; } System.out.println(colSum);

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.

Review this topic: Section 4.11 — 2D Array Algorithms • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.