Start learning free

LESSON 257 OF 289 · NESTED LOOPS OVER GRIDS

Row Sums in C#: One Total per Row of an int[][]

Practice Read the full explanation

Given a grid of integers grid, return a List with the sum of each row, in the same order as the rows.

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: [6, 15]
Explanation: Row 0 adds up to 1 + 2 + 3 = 6 and row 1 to 4 + 5 + 6 = 15.

Example 2:

Input: grid = [[-1, -2],
               [-3, -4],
               [5, 5]]
Output: [-3, -7, 10]
Explanation: One sum per row, top to bottom. A row of negative numbers has a negative sum.

Example 3:

Input: grid = [[3],
               [1],
               [4]]
Output: [3, 1, 4]
Explanation: Every row has a single value, so each row's sum is that value.

 

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 7
    Ctrl + Enter to check

    C# · NESTED LOOPS OVER GRIDS

    Row Sums in C#, explained

    Problem overview

    RowSums receives grid, an int[][], and returns a List<int> holding the sum of each row, in the same order as the rows. A grid is a table: every row has the same number of values, one per column, and rows are counted from the top starting at 0.

    For the rows [1, 2, 3] and [4, 5, 6] the result is [6, 15]. For [-1, -2], [-3, -4] and [5, 5] it is [-3, -7, 10]: a row of negative numbers has a negative sum. For three rows with one value each, [3], [1] and [4], each sum is just that value, so the result is [3, 1, 4].

    Approach: reset the total for every row

    Summing a whole grid needs one total. Here the answer has one sum per row, so each row gets its own total. The shape of the code is:

    • an outer loop over the rows;
    • inside it, a fresh total that starts at 0;
    • an inner loop that adds the row's values to that total;
    • after the inner loop, the finished total goes into the result list.

    Where each of these lines sits is the whole lesson. Create total inside the outer loop and it starts at 0 again for every row, so one row's numbers never leak into the next row's sum. Add it to the list at the end of the outer loop's body, and the sums come out in row order.

    Step by step

    1. Create an empty List<int> named sums. The sums are added one at a time, so it starts with nothing in it.
    2. Loop over the rows with foreach (int[] row in grid). Each item of an int[][] is an int[], so that is the loop variable's type. The loop runs once per row, and each row gives exactly one sum.
    3. Create int total = 0 inside this loop. It holds the sum of the current row only.
    4. Write the inner loop, foreach (int value in row). It visits the values of the current row and only that row.
    5. Add value to total inside the inner loop.
    6. After the inner loop, still inside the outer one, call sums.Add(total). When the inner loop has ended, the whole row has been added, so total is this row's sum.
    7. Return sums after the outer loop. Returning inside it would hand back only the first row's sum.

    The solution in C#

    class Solution {
        public List<int> RowSums(int[][] grid) {
            List<int> sums = new List<int>();
            foreach (int[] row in grid) {
                int total = 0;
                foreach (int value in row) {
                    total += value;
                }
                sums.Add(total);
            }
            return sums;
        }
    }
    

    C# details:

    • A list, not an array. The result is a List<int> because it is built by adding items. An array's length is fixed when it is created, while a list grows with Add. For a list, use Count for its size; for an array, Length.
    • Scope. A variable declared inside a loop body, like total here, exists only for that pass of the loop. That is exactly what the lesson wants: every pass has its own total.
    • Printing a list. Console.WriteLine on a List<int> prints the type's name, not the numbers. To see the contents, use string.Join(", ", sums). For the first example it gives 6, 15.
    • List<T> is in System.Collections.Generic; in a file of your own, add using System.Collections.Generic;.

    Edge cases and common mistakes

    • Declaring total before the outer loop. It would never reset, so every sum would include all the rows above it. For the first example the result would be [6, 21] instead of [6, 15].
    • Adding to sums inside the inner loop. The list would get one item per value, not per row.
    • Adding to sums before the inner loop. It would add the row's sum before it is computed, which is always 0.
    • Single-column grids. Each row has one value, so every sum equals that value, and the list has as many items as the grid has rows.
    • Negative values. They need no special handling.

    Testing

    gridResult
    [[1, 2, 3], [4, 5, 6]][6, 15]
    [[-1, -2], [-3, -4], [5, 5]][-3, -7, 10]
    [[3], [1], [4]][3, 1, 4]
    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