Unit 4 Cycle 1 Day 24: 2D Array Row Sums
Share
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.
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.