Task 5 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

5.4 2D arrays — summing a 2D array

Lesson

Combining every element of a grid

To total a two-dimensional array, use the same accumulator idea as before, but with a nested loop so you visit every element. Start a sum at 0, then add each grid[r][c] to it as the two loops run. When both loops finish, sum holds the grand total.


Worked example

int[][] grid = {{1, 2, 3}, {4, 5, 6}};
int sum = 0;
for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[r].length; c++) {
        sum = sum + grid[r][c];
    }
}
System.out.println(sum);   // 21

▶ Try it: run this to add up the whole grid. Change the values and re-run — the total follows.



To sum a 2D array, the accumulator should start at...


What is the sum of all elements of {{1, 2}, {3, 4}}?


Type the total this prints:

int[][] g = {{2, 2}, {2, 2}};
int sum = 0;
for (int r = 0; r < g.length; r++) {
    for (int c = 0; c < g[r].length; c++) {
        sum = sum + g[r][c];
    }
}
System.out.println(sum);

Order these lines to start summing a 2D array grid into sum (closing braces omitted).


True or false?