Start learning free

LESSON 256 OF 289 · NESTED LOOPS OVER GRIDS

Grid Sum in C#: Nested foreach over an int[][]

Practice Read the full explanation

Given a grid of integers grid, return the sum of all the numbers in it.

A grid is a table of numbers made of rows. Every row has the same number of values, one in each column. Rows are counted from the top and columns from the left, both starting at 0.

 

Example 1:

Input: grid = [[1, 2, 3],
               [4, 5, 6]]
Output: 21
Explanation: The first row adds up to 1 + 2 + 3 = 6 and the second to 4 + 5 + 6 = 15. Together: 6 + 15 = 21.

Example 2:

Input: grid = [[-3, 4],
               [5, -6]]
Output: 0
Explanation: -3 + 4 + 5 + (-6) = 0. Negative numbers make the sum smaller.

Example 3:

Input: grid = [[7]]
Output: 7
Explanation: A grid with one row and one column holds a single number.

 

Constraints:

  • grid has at least 1 row and at most 10 rows.
  • Every row has the same number of values, at least 1 and at most 10.
  • Every value is an integer between -1000 and 1000.
STEP 1 OF 5
    Ctrl + Enter to check

    C# · NESTED LOOPS OVER GRIDS

    Grid Sum in C#, explained

    Problem overview

    GridSum receives grid, an int[][], and returns the sum of every number in it. A grid is a table: it is made of rows, and every row holds one value per column. Rows are counted from the top and columns from the left, both starting at 0.

    For a grid with the rows [1, 2, 3] and [4, 5, 6], the first row adds up to 6 and the second to 15, so the answer is 21. For the rows [-3, 4] and [5, -6] it is 0, because negative values make the sum smaller. A grid with the single row [7] gives 7.

    Approach: a loop inside a loop

    In C#, int[][] is an array of arrays (a jagged array). Each item of grid is itself an int[]: one row. So a grid takes two levels of looping. An outer loop picks the rows one by one, and for each row an inner loop visits its values.

    Together the two loops reach every cell exactly once. All that is left is a running total that starts at 0 and grows by every value.

    Step by step

    1. Create int total = 0. No number has been added yet.
    2. Loop over the rows with foreach (int[] row in grid). The loop variable has the type of one item of grid, which is int[].
    3. Inside it, loop over the values of that row with foreach (int value in row). For each row, the inner loop finishes all of its values before the outer loop moves on.
    4. Add the value with total += value; in the inner loop. Negative values are added like any other.
    5. Return total after both loops. Returning inside them would give only part of the grid.

    The solution in C#

    class Solution {
        public int GridSum(int[][] grid) {
            int total = 0;
            foreach (int[] row in grid) {
                foreach (int value in row) {
                    total += value;
                }
            }
            return total;
        }
    }
    

    C# details:

    • Two ways to write a 2D array. int[][] is a jagged array: an array whose items are arrays, indexed grid[row][col]. Its rows can have different lengths. A rectangular array, int[,], is a different type, indexed grid[row, col]. This lesson uses the jagged kind, so grid[1][2] is the third value of the second row, and a plain foreach over grid gives rows.
    • Lengths. grid.Length is the number of rows and row.Length the number of values in a row. For new int[][] { new[] {1, 2, 3}, new[] {4, 5} } the grid has length 2, and its rows have lengths 3 and 2. The lesson's grids have equal rows, but the nested foreach does not depend on that.
    • Why foreach here. The sum doesn't need the position of a cell, so there is no index to manage and no way to be off by one.
    • Overflow. An int wraps silently when it gets too big. With at most 100 values of at most 1000 each, the total can't come close.

    Edge cases and common mistakes

    • A single cell. The grid [[7]] gives 7: one row, one value.
    • Negative values. [[-3, 4], [5, -6]] gives 0. Nothing special is needed for the minus signs.
    • Returning too early. A return total; inside the loops ends the method after the first value.
    • Declaring total inside the outer loop. A variable declared inside a loop body exists only there, so the return total; after the loops would not compile. Declare it before the loops.
    • Using int for the row variable. foreach (int row in grid) doesn't compile: each item of grid is an int[], so the loop variable must be too.

    Testing

    gridResult
    [[1, 2, 3], [4, 5, 6]]21
    [[-3, 4], [5, -6]]0
    [[7]]7
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free