O Level Computer Science 2210 · Area 2 · Algorithms, programming and logic

One-dimensional and two-dimensional arrays

An array is one name for a whole list of values of the same type, and the exam tests whether you can declare one, fill it and read from it without stepping outside its bounds. You need the exact Cambridge declaration, an index that is inside the range you declared, and a loop whose counter is the index. Most marks are lost by an off-by-one loop bound, by giving a grid only one dimension, or by trying to assign a value to the whole array at once.

Not started

Syllabus coverage

  • Declare and use one-dimensional (1D) and two-dimensional (2D) arrays
  • Understand the use of arrays, including the use of variables as indexes
  • Write values into, and read values from, an array using iteration, including nested iteration
  • State the lower bound of an array, remembering that the first index can be zero or one
  • Use meaningful identifiers for arrays, as for variables, constants, procedures and functions

Part of the O Level Computer Science syllabus 2210.

An array is one name for many valuesThe index says which element you mean; iteration is how you visit them all.A two-dimensional array needs two indexes, one for the row and one for the column.A one-dimensional array: one row, one index each12[1]8[2]45[3]3[4]27[5]A two-dimensional array: a grid, one index for the row and one for the columncol 1col 2col 3col 4cellcellcellcellcellcellcellcellcellcellcellcell
A one-dimensional array drawn as five consecutive cells with an index printed under each cell, sitting above a two-dimensional array drawn as a grid whose rows and columns are numbered.

Why a program needs an array

A variable holds one value. If a program had to keep the marks of 30 pupils it could declare 30 variables, Mark1 to Mark30, but no loop could work through them, because a loop repeats the same statement and each of those variables has a different name. Adding a 31st pupil would mean editing the program in several places.

An array solves this. It is a fixed-length structure of elements of the same data type, and every element is reached by the array's name plus an index in square brackets. Because the index is a number, a loop counter can be used as the index, so one pair of statements can write to any element or read from any element.

Arrays matter because most of the data a program handles arrives as a list: the marks of a class, the stock levels of a shop's products, the temperature recorded each hour. The syllabus asks you to understand the use of arrays as well as the syntax - to see that a list of values of one type belongs in one structure under one name.

An array holds many values but has one identifier. The identifier plus an index is what picks out a single value, so `Scores` on its own is the whole list and `Scores[4]` is one mark.

Declaring a one-dimensional array

A one-dimensional (1D) array is a single list - one row of cells, one after another. It is declared by naming the identifier, giving the lower and upper bounds in square brackets, and giving the data type of the elements:

DECLARE Scores : ARRAY[1:25] OF INTEGER

That declaration settles three things at once. The identifier is Scores, the array has 25 elements numbered 1 to 25, and every element holds an integer. The length is fixed when the declaration is read: it cannot grow while the program runs, so the upper bound must be large enough for the biggest amount of data expected.

Every element has the same data type, so one array cannot hold a name in one cell and a mark in another; that would need two arrays. The syllabus expects the lower bound to be stated explicitly, because different systems number the first element 0 or 1, and a program that assumes the wrong one is wrong at both ends of the list.

  • Form: `DECLARE <identifier> : ARRAY[<lower>:<upper>] OF <data type>`
  • `DECLARE Scores : ARRAY[1:25] OF INTEGER` holds 25 whole numbers, numbered 1 to 25.
  • `DECLARE StudentNames : ARRAY[1:30] OF STRING` holds 30 names.
  • The bounds are part of the declaration, not something the program can change later.
Write the lower bound every time. ARRAY[1:25] and ARRAY[0:24] both hold 25 elements, but they are not the same 25 elements, and an index that is valid in one is out of range in the other.

Indexes, elements and bounds

The value inside the brackets is the index, and it selects one element of the array. In `Scores : ARRAY[1:25]`, `Scores[1]` is the first element and `Scores[25]` is the last. The index does not have to be a literal: it can be a variable such as `Scores[Index]` or an expression such as `Scores[Index + 1]`. That is the whole point of an array - the element being used can be worked out while the program runs.

An index outside the declared bounds does not exist. `Scores[0]` and `Scores[26]` are not part of the array above; using them gives an error or picks up whatever happens to be in memory next to the array, which is worse, because the program carries on with rubbish values.

The same notation reads and writes. `Scores[3] ← 68` puts a value into the third element. `OUTPUT Scores[3]` takes the value out again without removing it. `Scores[Index + 1] ← Scores[Index]` copies one element into its neighbour, which is the first step in shifting a list along by one place - and if you are shifting the whole list, the loop has to run backwards so that no value is overwritten before it has been copied.

StatementWhat it does
Scores[7] ← 61Writes 61 into the element with index 7
INPUT Scores[Index]Reads a value from the keyboard straight into an element
Total ← Total + Scores[Index]Reads an element and adds it to a running total
Scores[Index + 1] ← Scores[Index]Copies one element into the next one

Writing values into an array

Values are written one element at a time. A short list can be filled with individual assignments: `StudentNames[1] ← "Ali"`, `StudentNames[2] ← "Bea"`, and so on. A program that did this for 30 names would be long and would have to be rewritten whenever the class changed, so real programs fill an array with a loop.

The loop counter is used as the index, which is exactly what the syllabus means by writing values using iteration:

DECLARE Scores : ARRAY[1:30] OF INTEGER FOR Index ← 1 TO 30 INPUT Scores[Index] NEXT Index

On the first pass `Index` is 1 and the value goes into `Scores[1]`; on the last pass it is 30 and the value goes into `Scores[30]`. The loop bounds must match the array bounds. A loop of 0 to 29 over an array declared 1 to 30 leaves the first element empty and writes one value past the end.

The same pattern sets every element to a starting value before the program uses the array - `Scores[Index] ← 0` inside the loop - which is good practice, because an element that has never been written holds nothing you can rely on.

Read the declaration before you write the loop. If the array is ARRAY[1:30], the loop is FOR Index ← 1 TO 30. The two sets of numbers must be the same.

Reading values from an array

Reading an element does not remove it. `OUTPUT Scores[4]` displays the fourth mark and leaves it in place, so the same element can be used again and again. This is why an array is the natural place to hold data that several parts of a program need: the marks are entered once and then totalled, averaged, searched and sorted without being re-entered.

A loop that reads every element is the standard way to process a list. Totalling and averaging look like this:

Total ← 0 FOR Index ← 1 TO 30 Total ← Total + Scores[Index] NEXT Index OUTPUT "Average is ", Total / 30

Only the statement inside the loop changes when the job changes. To count the passes, add one to a counter when the element is at least the pass mark. To find the highest mark, compare each element with a variable that holds the best value so far. To find a name, compare each element with the name being searched for. In every case the array is read element by element, because a computer cannot look at a whole list at once.

TaskStatement inside the loop
Total the valuesTotal ← Total + Scores[Index]
Count the passesIF Scores[Index] >= 50 THEN Passes ← Passes + 1
Find the highestIF Scores[Index] > Highest THEN Highest ← Scores[Index]
Output each valueOUTPUT Scores[Index]

Two-dimensional arrays

A two-dimensional (2D) array is a grid. Every element belongs to a row and a column, so it needs two indexes, separated by a comma. The first index is the row and the second is the column:

DECLARE Seats : ARRAY[1:5, 1:4] OF BOOLEAN

This array has 5 rows and 4 columns, so it holds 5 × 4 = 20 elements, each TRUE or FALSE. `Seats[3, 2]` is the seat in row 3, column 2. Each dimension has its own lower and upper bound, and they need not be the same: `DECLARE NoughtsAndCrosses : ARRAY[1:3, 1:3] OF CHAR` is the 3 by 3 board for a game.

Use a 2D array whenever each value belongs to two things at once. A mark belongs to a pupil and to a test, so `Marks[Pupil, Test]` is natural. A seat belongs to a row and a seat number. A pixel belongs to a row and a column of an image. A 1D array would need a separate list for every row, and the relationship between the rows would be lost.

  • Form: `DECLARE <identifier> : ARRAY[<l1>:<u1>, <l2>:<u2>] OF <data type>`
  • `Seats[3, 2]` means row 3, column 2 - row first, column second.
  • The number of elements is the first dimension multiplied by the second.
  • A 2D array is not an array of arrays in the exam: one identifier, two indexes, one data type.

Nested iteration over a 2D array

One loop cannot visit every cell of a grid, because each cell has two coordinates. Two loops are needed, one inside the other. The outer loop fixes the row and the inner loop runs along every column of that row:

FOR Row ← 1 TO 5 FOR Column ← 1 TO 4 Seats[Row, Column] ← FALSE NEXT Column NEXT Row

The inner loop runs to completion for each single pass of the outer loop, so the cells are visited row by row: row 1 column 1, row 1 column 2, and so on to the end of the row, then the whole of row 2. Twenty assignments are made, and no cell is missed or written twice. This is nested iteration, and the syllabus expects you to use it for both writing and reading a 2D array.

Nested loops also do the arithmetic that a grid needs. To total each row and then the whole grid, the running total for the row is reset before the inner loop, added to inside it, and output after it, while a grand total is added to once per row:

GrandTotal ← 0 FOR Row ← 1 TO 5 RowTotal ← 0 FOR Column ← 1 TO 4 RowTotal ← RowTotal + Amount[Row, Column] NEXT Column OUTPUT "Total for row ", Row, " is ", RowTotal GrandTotal ← GrandTotal + RowTotal NEXT Row OUTPUT "Grand total is ", GrandTotal

Where a statement sits matters. Put the output inside the inner loop and you print every cell; put it between the loops and you print one line per row; put it after both loops and you print one number for the whole grid.

How arrays are used in real programs

Arrays are the structure behind almost every list a program keeps, and recognising the shape of the data tells you which array to declare. If each item is one value of the same kind, it is 1D. If each value is identified by two coordinates, it is 2D.

Once the data is in an array, the standard methods of solution work on it directly. Totalling, counting and finding an average walk through the elements once. Finding a maximum or minimum compares each element with the best so far. A linear search compares each element with the value being looked for, and a bubble sort compares and swaps neighbouring elements. All of them need the array and an index, which is why this topic comes just before those methods are used in earnest.

Data a program keepsDeclarationWhy this shape
The marks of 30 pupils in one testARRAY[1:30] OF INTEGEROne value per pupil, so one index is enough
A cinema's 8 rows of 12 seatsARRAY[1:8, 1:12] OF BOOLEANEach seat is found by row and seat number
A noughts and crosses boardARRAY[1:3, 1:3] OF CHAREach square is a row and a column
The stock level of 200 productsARRAY[1:200] OF INTEGEROne quantity per product code
The marks of 30 pupils in 6 testsARRAY[1:30, 1:6] OF INTEGEREach mark belongs to a pupil and a test
If a question gives you the number of rows and columns, multiply them to check the array is big enough, and remember the bounds are inclusive: 1 to 5 is five rows, not four.

Key terms you must be able to define

Array
A fixed-length structure of elements of the same data type, reached by one identifier and one or more indexes.
Element
One value stored in an array, selected by its index or indexes.
Index
The number in square brackets that selects an element; it may be a literal, a variable or an expression.
Lower bound
The index of the first element, written before the colon in the declaration. It is 0 in some systems and 1 in others, so it should always be stated.
Upper bound
The index of the last element, written after the colon. The number of elements is the upper bound minus the lower bound plus one.
One-dimensional (1D) array
A single list of elements, each selected by one index, such as the marks of a class.
Two-dimensional (2D) array
A grid of elements, each selected by a row index and a column index, such as a seating plan or a game board.
Nested iteration
One loop inside another. Used with a 2D array so that the inner loop visits every column of the row chosen by the outer loop.

In context

2210 sets its questions inside systems a student already uses - a school network, a phone, a supermarket till, a vending machine, a website. These show how the theory is applied to a context you have not seen before, then you answer for the system you are given.

Marks for a class

A teacher keeps one test mark for each of 30 pupils in `DECLARE Scores : ARRAY[1:30] OF INTEGER`. The marks are entered with a FOR loop that uses Index as the index, and the average is found by adding each element to a total inside a second loop and dividing by 30. No variable is declared for each pupil, so the same code works for a class of 28 or 31 once the upper bound is changed.

A cinema's seating plan

A booking screen shows 8 rows of 12 seats, held in `DECLARE Seats : ARRAY[1:8, 1:12] OF BOOLEAN`, where TRUE means the seat is booked. When a customer chooses row 4, seat 9, the program tests `Seats[4, 9]`; if it is FALSE it books it with `Seats[4, 9] ← TRUE`. To count the free seats, nested loops visit all 96 elements and add one to a counter for each FALSE.

A noughts and crosses board

The board is `DECLARE Board : ARRAY[1:3, 1:3] OF CHAR`, with each element holding a space, an X or an O. A move is written as `Board[2, 3] ← 'X'`. Checking a win means reading the three elements of each row, each column and each diagonal and comparing them, which is only possible because a row is a set of elements with the same first index.

Stock levels in a shop

A shop holds the quantity of each of 200 products in `DECLARE StockLevel : ARRAY[1:200] OF INTEGER`. Each evening a loop reads the array and outputs the product number of every element below its reorder level. The product number is the index, so the output can name the item without a second array of names.

Flashcards

Click a card to flip it. Mark honestly — the tracker uses this.

Q1What is an array?
A fixed-length structure of elements of the same data type, reached by one identifier and an index. The length is set when it is declared and cannot change while the program runs.
Q2Give the Cambridge pseudocode to declare an array of 25 whole numbers numbered from 1.
DECLARE Scores : ARRAY[1:25] OF INTEGER
Q3In ARRAY[1:25], how many elements are there, and what are the first and last indexes?
25 elements, indexed 1 to 25. The number of elements is the upper bound minus the lower bound plus one.
Q4Why must the lower bound be written in a declaration?
Because the first index defaults to 0 in some systems and 1 in others. Stating it makes the program correct on either, and shows which element is the first.
Q5How is one element of a 2D array named?
With two indexes separated by a comma, row first: Grid[3, 2] is row 3, column 2.
Q6How many elements are in ARRAY[1:5, 1:4]?
20 - five rows of four columns. Multiply the number of values in each dimension.
Q7Why does a 2D array need nested loops?
Each element has two coordinates. The outer loop fixes the row and the inner loop visits every column of that row, so every cell is reached exactly once.
Q8Write pseudocode that fills a 1D integer array called Scores of 30 elements from the keyboard.
FOR Index ← 1 TO 30 INPUT Scores[Index] NEXT Index
Q9How do you find the total of every element in a 1D array?
Set Total ← 0 before the loop, add Scores[Index] to Total inside the loop, and output Total after it.
Q10What happens if an index is outside the declared bounds?
That element does not exist. The program raises an error or reads whatever is in memory beside the array, so the results cannot be trusted.
0 of 10 marked as known

Exam-style questions

6 questions, 19 marks. Write your answer and press Mark my answer — it is marked against the scheme and tells you which points you made and what would gain the next mark. You can still reveal the scheme and mark it yourself instead.

StateAO11 mark
State what is meant by an element of an array.

Mark scheme — tick each point you actually made

Examiner tip: Keep it to the single value and the index that finds it. 'A part of the array' is too vague to score.
GiveAO12 marks
A program must store the names of 40 club members. Give the pseudocode statement that declares a one-dimensional array for this data, and state the value of the last index.

Mark scheme — tick each point you actually made

Examiner tip: The data type for a name is STRING, and the upper bound is 40 because there are 40 members. Do not write ARRAY[40] - Cambridge pseudocode needs both bounds.
IdentifyAO23 marks
A program contains the declaration DECLARE Grid : ARRAY[1:10, 1:6] OF REAL. Identify the number of elements in the array, the data type of each element, and the element in row 4, column 2.

Mark scheme — tick each point you actually made

Examiner tip: Multiply the dimensions for the count, read the type straight from the declaration, and write the element with the row first and a comma between the indexes.
GiveAO24 marks
A weather station records the rainfall for each of the 12 months of a year in a one-dimensional array called Rainfall, indexed 1 to 12. Give pseudocode that reads the 12 values from the keyboard into the array and then outputs the total rainfall for the year.

Mark scheme — tick each point you actually made

Examiner tip: The total must start at zero before the loop and be output after it. A total that is reset inside the loop will only ever hold the last month's value.
DescribeAO24 marks
A program holds a 6 by 6 grid of characters in a two-dimensional array called Grid. Describe how nested iteration would be used to set every element of the grid to a full stop.

Mark scheme — tick each point you actually made

Examiner tip: Say which loop is outside and why. The examiner wants to see that you know one pass of the outer loop covers a whole row, not one cell.
ExplainAO35 marks
A programmer needs to store the stock level of 30 products. Explain why an array is more suitable for this than 30 separate variables.

Mark scheme — tick each point you actually made

Examiner tip: Every mark here is about what the array makes possible, not about it being 'easier'. Mention the index, the loop, the search and the single declaration.

Exam technique for this topic

  • Write the declaration in the syllabus form exactly: `DECLARE Name : ARRAY[1:30] OF STRING`. Missing the lower bound, the data type or the colon loses the mark even if the idea is right.
  • Match the loop to the declaration. `ARRAY[1:30]` means `FOR Index ← 1 TO 30`, and `ARRAY[1:5, 1:4]` means two loops, 1 to 5 and 1 to 4. Examiners see the same off-by-one error every session.
  • For a 2D array, put the row loop outside and the column loop inside, and use one index per dimension inside the brackets: `Grid[Row, Column]`, never `Grid[Row][Column]`.
  • When asked why an array is used, say what it allows: one identifier for many values of the same type, and an index that a loop can calculate so every element can be processed without writing a statement for each one.
  • Answers are marked as pseudocode. A Python list, a Java array declaration or a C-style loop scores nothing, however correct the logic.

Why students lose marks here

A student wroteA student declared `Scores : ARRAY[1:30] OF INTEGER` and then filled it with `FOR Index ← 0 TO 29`.
Why it loses marksThe loop writes to `Scores[0]`, which is outside the declared bounds, and stops at `Scores[29]`, so the last element is never filled. The program either fails or works with one missing mark and one value written past the end of the array.
The answer that scoresThe loop must use the declared bounds: `FOR Index ← 1 TO 30` with `INPUT Scores[Index]` and `NEXT Index`. If the declaration were `ARRAY[0:29]`, the loop 0 to 29 would be correct - which is why the lower bound should always be written down and checked.
A student wroteA student declared a noughts and crosses board as `DECLARE Board : ARRAY[1:9] OF CHAR`.
Why it loses marksThat is a one-dimensional array of nine cells in a line. It has no rows and columns, so a move such as row 2, column 3 cannot be stored, and no nested loop can work through the board.
The answer that scoresA board has two coordinates, so it needs two dimensions: `DECLARE Board : ARRAY[1:3, 1:3] OF CHAR`, giving nine elements reached as `Board[Row, Column]`. The number of elements is the same, but the shape is what allows a row or a column to be read.
A student wroteA student tried to empty an array with `Scores ← 0`.
Why it loses marksA value can only be assigned to one element at a time. The identifier on its own means the whole structure, and the language has no single assignment that fills every element.
The answer that scoresEvery element must be written separately, which is a job for a loop: `FOR Index ← 1 TO 30` then `Scores[Index] ← 0` then `NEXT Index`. The same is true of input, output and comparison - an array is always used one element at a time.
A student wroteA student wrote `FOR Index ← 1 TO 30` and then `INPUT Scores` inside the loop.
Why it loses marks`INPUT Scores` has no index, so it does not name an element. The value is not stored in the array at all, and the same statement is repeated 30 times without anything changing.
The answer that scoresThe index must be attached to the identifier: `INPUT Scores[Index]`. As the loop runs, `Index` takes each value from 1 to 30 in turn, so each value read is stored in the next element of the array.

Where this fits in O Level Computer Science 2210

This page is one topic of Cambridge O Level Computer Science 2210. O Level Computer Science 2210 is the course home: every area and every topic in Cambridge's own order, the papers you sit and what each one tests, and the exam-practice tools. The full topic list, with each topic linked to its revision page, is on the O Level Computer Science 2210 syllabus page.