DSA Factory
Free lessonsProgramming basics · Stage 8 · Loops inside loops · Step 3

A grid of numbers

Read a table of numbers, row by row, with a loop inside a loop. About 10 minutes.

A list of lists

A spreadsheet is a table: rows going across, and columns going down. In code, a grid is a list whose items are themselves lists. Each inner list is one row.

To reach a single cell you need two positions: the row first, then the column. Both start at 0. In the grid below, row 1 is the list [4, 5, 6], so the cell in row 1 and column 2 is the 6. A grid is the tool for boards, maps, and tables of marks.

Two positions: the row first, then the column, both from 0.
In code
grid = [[1, 2, 3],
        [4, 5, 6]]
cell = grid[1][2]     # 6

Visit every cell

To look at every cell, use two loops. The outer loop takes one row at a time, and the inner loop takes each number in that row. This is just like handing out rows of exam papers: you finish a whole row before you start the next.

If you want a total, make the total before both loops, and add each number inside the inner loop. When both loops finish, every cell has been visited exactly once.

Outer loop: each row. Inner loop: each number in that row.
In code
total = 0
for row in grid:
    for x in row:
        total = total + x
Adding up a 3 by 3 grid
012
0
3
1
4
1
1
5
9
2
2
6
5
row
0
total
8

The outer loop takes row 0. The inner loop adds 3, 1 and 4 one by one, and the total reaches 8.

Move 1 of 3
Quick check

grid is [[1, 2], [3, 4]]. What is grid[1][0]?

  1. A3
  2. B2
  3. C4
Show the answer

3. Row 1 is [3, 4], and column 0 of it is 3.

Your problem

Grid total

You get a grid of numbers as a list of rows. Return the sum of all the numbers in it.

Example
grid = [[3, 1, 4], [1, 5, 9], [2, 6, 5]] → 36

0 ≤ number of rows ≤ 20 · 0 ≤ numbers per row ≤ 20 · −1,000 ≤ each number ≤ 1,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding