Nested Loops: Summing and Counting

Part of: 2D Array

Traversing Every Cell. Most grid problems require visiting every cell exactly once . The standard tool is a pair of nested loops : an outer loop over rows and an inner loop over columns. Inside the innermost body you have access to one cell, grid[r][c]. Accumulator Patterns. Two of the most common grid algorithms reuse the same skeleton: - Summing : start an accumulator at 0 and add each cell. - Counting : start a counter at 0 and add 1 whenever a cell meets a condition. Where to Declare the Accumulator. The placement of a variable controls what it measures: - Declare before both loops to total the whole grid. - Declare inside the outer loop but before the inner loop to total each row separately. What usually goes wrong. What you see What caused it How to fix it --- --- --- One giant total where a total per row was expected The accumulator was declared before both loops, so it never resets Declare it inside the outer loop so it starts fresh for each row Every row reports the same number The accumulator was printed after both loops instead of at the end of each row Print inside the outer loop, right after the inner loop finishes The count stays 0 no matter what the grid holds The co

Challenge: Sum of All Grid Values