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

Walking the grid

Visit a grid by positions, and choose whether to go along the rows or down the columns. About 10 minutes.

Which loop goes outside?

The loop on the outside decides which direction you walk. With rows outside and columns inside, you read the grid like a book: the whole of row 0, then the whole of row 1.

Swap the loops, and you walk down the columns instead: the whole of column 0, then the whole of column 1. That's what you want for a sum of each column. Decide what each pass of the outer loop should finish, then put that loop outside.

The outer loop: decides what each answer is about.

Walking by position

To walk down a column you need positions, because you have to say which row and which column. A grid's number of rows is its length. The number of columns is the length of any row, such as the first.

For the sum of each column, loop over the column positions. Inside, start a total, loop over the row positions, and add the cell at that row and that column. When the inner loop is done, that column's sum is ready, so add it to the answer list.

A cell needs two positions: the row first, then the column.
In code
sums = []
for c in range(len(grid[0])):
    total = 0
    for r in range(len(grid)):
        total = total + grid[r][c]
    sums.append(total)
Column sums of a 2 by 3 grid
012
0
1
2
3
1
4
5
6
sums
[5]
column
0

Column 0: the inner loop goes down it, adding 1 and 4. The first column's sum is 5.

Move 1 of 3
Quick check

grid is [[1, 2, 3], [4, 5, 6]]. What is the sum of column 2, counting from 0?

  1. A9
  2. B15
  3. C7
Show the answer

9. Column 2 holds 3 in the first row and 6 in the second, and 3 + 6 = 9.

Your problem

Column sums

Return a list with the sum of each column of the grid, from the first column to the last. Every row has the same number of numbers.

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

1 ≤ number of rows ≤ 20 · 1 ≤ 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