AP® Computer Science A · Unit 4 · Topic 4.13
Summing Rows and Columns of a Grid
Summing rows or columns of a grid means accumulating values with a running total, but where you reset that total to 0 decides whether you get one sum per row, one per column, or just one grand total.
A grid is just an array of arrays, rows nested inside an outer array. To sum one row, you walk across its columns adding each value into an accumulator. To get a separate total for every row, that accumulator has to start over at 0 each time you move to a new row. That means the reset line goes inside the outer loop, right before the inner loop starts, so each pass through a row begins collecting from scratch instead of carrying over what came before.
A grand total works differently: you want everything added together, so the accumulator resets once, before the outer loop even begins, and never resets again. Row sums and grand totals use the same nested-loop skeleton; the only difference is where the reset line sits. Column sums flip the structure: now the outer loop must step through columns and the inner loop through rows, because a column cuts across every row at the same index. Whichever direction you're summing becomes the outer loop, with its accumulator reset there, while the other direction becomes the inner loop doing the adding.
This topic is the natural follow-up to nested loop traversal of 2D arrays: once you can visit every element in the right order, summing rows and columns is just deciding when to zero out the accumulator. It sets up later work like finding row or column maximums and totals used in matrix-style problems, all of which depend on this same reset-placement logic.
Key terms
- accumulator
- A variable that collects a running sum as a loop adds each new value to it.
- outer loop
- The loop controlling which row or column is currently being processed in a nested traversal.
- inner loop
- The loop that walks across the elements within one row or one column.
- 2D array
- An array of arrays, commonly visualized as a grid with rows and columns.
Watch it explained
- How it worksHow does resetting the accumulator inside the outer loop give one total per row?
- Worked exampleFind every row sum of { {1,2,3}, {4,5,6} } and trace where the accumulator resets.
- Worked exampleFind the column sums of that same grid and show which loop has to move outside.
- Common mistakeWhy doesn't declaring the row total before the outer loop give per-row answers?
Check yourself
End of topic.