Start learning free

LESSON 254 OF 671 · NESTED LOOPS OVER GRIDS

Grid Sum in Java: Nested For-Each Loops 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

    JAVA · NESTED LOOPS OVER GRIDS

    Grid Sum in Java, explained

    Problem overview

    Given a grid grid of type int[][], gridSum returns the sum of all its numbers. A grid is a table made of rows, each row has the same number of values, and rows and columns are counted from 0.

    For [[1, 2, 3], [4, 5, 6]] the first row adds up to 6, the second to 15, and the answer is 21. For [[-3, 4], [5, -6]] the answer is 0, because negative numbers simply make the sum smaller. For [[7]] the answer is 7.

    Approach

    In Java, an int[][] is an array of arrays. Each item of grid is a row, and each row is itself an int[]. So there are two levels to walk through: first pick a row, then pick each value in it.

    That is a pair of nested loops. The outer loop runs once per row. For each row, the inner loop visits every value in it before the outer loop moves on. Together they visit every cell exactly once, which is what a sum over the whole grid needs. One variable, total, collects the numbers as they go by.

    Step by step

    1. Create an int named total and start it at 0. No number has been added yet, so the sum starts at 0.
    2. Write a for-each loop with an int[] named row over grid. The type of the loop variable is int[], not int, because each item of an int[][] is a whole row.
    3. Inside it, write a second for-each loop with an int named value over row. For every row, this loop visits all of its values before the outer loop continues.
    4. Inside the inner loop, add value to total with +=.
    5. After both loops, return total. A return inside the loops would stop after part of the grid.

    Tracing the first example

    For [[1, 2, 3], [4, 5, 6]], the outer loop first gives row = [1, 2, 3]. The inner loop adds 1, 2 and 3, so total is 6. The outer loop then gives row = [4, 5, 6], and the inner loop adds 4, 5 and 6, which brings total to 21. Both loops end, and the method returns 21.

    The solution in Java

    class Solution {
        public int gridSum(int[][] grid) {
            int total = 0;
            for (int[] row : grid) {
                for (int value : row) {
                    total += value;
                }
            }
            return total;
        }
    }
    

    Java details in this code:

    • The loop variable's type. In for (int[] row : grid), row has type int[]. Writing for (int row : grid) would not compile, because an int[] can't be stored in an int.
    • Rows are shared, not copied. row refers to the same array that lives inside grid. This code only reads it, so that doesn't matter here. If a loop assigned to row[0], the grid would change.
    • For-each has no index. The loops give values without telling you the row or column number. For this task that is fine, since the position of a number doesn't affect the sum. Problems that need positions use ordinary for loops with indexes.
    • Rows can differ in length in Java. An int[][] can hold rows of different sizes. The lesson guarantees the same size in every row, and the for-each version works either way, because each inner loop uses its own row's length.

    Edge cases and common mistakes

    • Negative values. Adding a negative number lowers the total. For [[-3, 4], [5, -6]], -3 + 4 + 5 - 6 gives 0. Nothing special is required.
    • A single cell. [[7]] has one row with one value, and each loop runs once. The result is 7.
    • Returning too early. Putting return total; inside a loop returns after the first row or the first value.
    • Resetting the total. If total is declared inside the outer loop, it starts over at 0 for every row and the method sums only the last row. It has to be declared before both loops.
    • Mixing up the loop types. The inner loop goes over row, not grid. Looping over grid again would give you rows, not numbers.

    Testing

    • gridSum(new int[][]{{1, 2, 3}, {4, 5, 6}}) returns 21.
    • gridSum(new int[][]{{-3, 4}, {5, -6}}) returns 0.
    • gridSum(new int[][]{{7}}) returns 7.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free