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. Key Idea The number of times the inner body runs equals rows cols. By choosing where to declare and where to print your accumulator, the same nested-loop pattern computes a grand total, per-row totals, or counts of matching cells. This control of variable scope is the heart of every 2D-array algorithm.

Challenge: Sum of All Grid Values