Unit 4 Cycle 1 Day 24: 2D Array Row Sums

Unit 4 Foundation (Cycle 1) Day 24 of 28 Foundation

2D Array Row Sums

Section 4.11 — 2D Array Algorithms

Key Concept

Computing row sums in a 2D array uses the accumulator pattern inside nested loops. For each row, initialize a sum to 0, iterate through that row's columns adding each element, then store or use the sum. The AP exam extends this to finding the row with the maximum sum, computing the average of each row, or comparing row sums. The pattern generalizes to any row-level aggregate: count, max, min, or string concatenation. Always reset the accumulator for each new row.

Consider the following code segment.

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

What is printed?

Answer: (C) 24

Row 0: 1+2+3=6. Row 1: 4+5+6=15. Row 2: 7+8+9=24. Maximum row sum is 24.

Why Not the Others?

(A) 6 is the sum of row 0, the smallest.

(B) 15 is the sum of row 1.

(D) 45 is the sum of ALL elements, not the maximum row sum.

Common Mistake

To find the maximum row sum: compute each row sum separately, then track the maximum. Reset rowSum to 0 at the start of each row.

AP Exam Tip

Nested loops with per-row accumulators are common in 2D array algorithms. Reset the inner accumulator for each row.

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.