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.
sum
0
grid[r][c]
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}}?
{{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).
grid
True or false?