Arrays
Programming · 4 question types
A 2-dimensional array (2D array) is a table of values with rows and columns. Each element is accessed using two indices: one for the row, one for the column.
A 2D array is the natural way to store anything that fits a grid: a noughts-and-crosses board, a school timetable, a spreadsheet, the pixels of a small image.
Declaring a 2D array
DECLARE Grid : ARRAY[1:3, 1:3] OF INTEGER
This creates a 3 × 3 grid: 3 rows (indices 1 to 3) and 3 columns (indices 1 to 3), 9 elements in total, each an integer.
Reading and writing 2D elements
Access an element with two indices separated by a comma:
Grid[1, 1] ← 1 // top-left
Grid[1, 2] ← 2
Grid[1, 3] ← 3
Grid[2, 1] ← 4
Grid[2, 2] ← 5
Grid[2, 3] ← 6
Grid[3, 1] ← 7
Grid[3, 2] ← 8
Grid[3, 3] ← 9 // bottom-right
OUTPUT Grid[1, 1] // outputs 1
OUTPUT Grid[2, 3] // outputs 6
The first index is the row; the second is the column. CIE conventions are 1-indexed for both.
Matching each 2D index to its row and column
The first index picks the row, in most exam scenarios one record (a room, a club, a customer); the second picks the column, and the question says which field each column holds. Hold the column number constant and let the loop variable supply the row: Sizes[Room, 1] for a length, Sizes[Room, 2] for a width. One error-correction question read city names into the countries' column; the correction was the right column number.
To total one field for every record, one loop down the rows with the column fixed is enough; nested loops, rows outer and columns inner, visit every cell.
A 2D array as a worked table
Visualise the array above as a 3 × 3 grid:
| Col 1 | Col 2 | Col 3 | |
|---|---|---|---|
| Row 1 | 1 | 2 | 3 |
| Row 2 | 4 | 5 | 6 |
| Row 3 | 7 | 8 | 9 |
Grid[2, 3] is the element at row 2, column 3 (the value 6).
Convention: [Row, Column] or [X, Y]?
The CIE convention is Array[Row, Column], with both indexes inside one pair of square brackets (Python writes array[row][column] instead). Always check the question's description of what each row and column holds; do not assume.
Whatever the indexing base, the same principle holds: the first index selects the row and the second index selects the column, as shown below.
