Menu

Pseudocode

One- and Two-Dimensional Arrays

An array stores many related items under one identifier. Each item is reached by its index, which is its position, so one name plus a changing index can reach every item in turn. Indexes start at 0, so the third item in an array sits at index 2.

One-dimensional arrays

A one-dimensional array is a single row of items. Think of a vending machine: one identifier, snacks, where snacks[0] holds crisps, snacks[1] holds a cereal bar and snacks[5] holds mints. To visit every slot you use a FOR loop that counts from 0 up to one less than the number of items. Arrays are useful because one loop can process every item, so the same code works as the array grows.

Two-dimensional arrays

A two-dimensional array stores data in rows and columns, so each item needs two indexes: the row first, then the column. The table shows a car park with three rows of four bays, where 1 means a bay is occupied and 0 means it is free. The value in row 2, column 1 is 1, so that bay has a car in it.

Column 0Column 1Column 2Column 3
Row 01011
Row 10001
Row 21100

The car park two-dimensional array drawn as a grid of 3 rows (Row 0 to Row 2) and 4 columns (Column 0 to Column 3), with 1 for an occupied bay and 0 for a free one; numbers 1 to 12 show the nested loops visiting each row from left to right (inner loop) before moving down a row (outer loop). Row 2, column 1 is highlighted as holding 1, and the occupied bays add up to 3 + 1 + 2 = 6.

Processing with nested loops

A two-dimensional array can be processed with nested loops: an outer loop steps through the rows and an inner loop steps through the columns. The inner loop finishes its whole row before the outer loop moves down, so each pair of indexes is visited exactly once — all twelve bays in the example. A single loop with one index can step through the rows, but a second loop is needed to step through the columns in each row. The nested pair also counts the occupied bays correctly: add one to a total only when the item you are looking at is 1.

Practise this