Skip to content
Programming Data structures
All classes Intermediate About 15 min Premium

Rows and columns: 2-D arrays

Store a class's marks in a table with a row for each student and a column for each subject. Read one mark with grid[row][col], add up a student's row or a subject's column, and find the highest mark with a loop inside a loop.

Core concept

A two-dimensional array is a list of rows, each a list of values; grid[row][col] picks one value, a loop along a row or down a column adds them up, and two nested loops visit every cell

Topic: Data structures

Many things are tables: a class's marks, a cinema's seats, a calendar, the squares of a chessboard. A program keeps a table in a two-dimensional (2-D) array: a list of rows, where each row is itself a list. To read one value you give two indexes, the row first and then the column: grid[1][2] is row 1, column 2. As with any list, both start at 0, so the first student is row 0 and the first subject is column 0. To add up one student's marks, a loop: Steps that repeat, either a set number of times or until something becomes true. All key words walks along that row with the column changing. To add up one subject, a loop walks down its column with the row changing. To look at every mark, such as to find the highest, a loop over the rows has a loop over the columns inside it.

Key words explained

What you will learn

  • Read a value from a 2-D array with grid[row][col].
  • Explain why the first row and the first column are numbered 0.
  • Add up a row or a column with a loop.
  • Use nested loops to visit every cell and find the largest value.

Before you start

  • Know how a list is indexed from 0 and how a for loop works.

Materials

  • A notebook to draw the table

Equipment

  • None

Procedure

  1. Read grid[1][2] and say whose mark it is.
  2. Add up Chameli's row.
  3. Find the highest mark in the whole table.
  4. Answer the practice challenges.
Premium experiment Create a free account