Arrays and data structures at GCSE

Computer Science · GCSE · The School

One name for many values

Storing thirty test scores in thirty separately named variables is unworkable — thirty names to invent, thirty lines to write for anything done to all of them. An ARRAY stores many values of the same type under ONE name, each one reached by its position. `scores` can hold all thirty; `scores[3]` reaches just one of them.

Indexing starts at zero

The first element of an array is at INDEX 0, not 1. In an array of six items, the valid indices run 0 to 5 — the sixth and last element is `scores[5]`, not `scores[6]`. Reading `scores[6]` on a six-item array asks for an element that does not exist, which is the single most common array bug at this level.

Visiting every element with a loop

A FOR loop from 0 to the array's length minus 1 visits every index in turn. `total = 0; FOR i FROM 0 TO 4; total = total + scores[i]; ENDFOR` adds all five values of a five-item array. The loop variable IS the index — that is what lets one short loop replace five separate lines.

Searching inside an array

A linear search over an array checks `scores[0]`, then `scores[1]`, and so on, comparing each to the target and stopping when it matches. The search itself is unchanged from a search over any list; what an array adds is that each position has a known, reachable index, which is what lets a program report WHERE the match was found, not only that one exists.

A grid needs two indices

A noughts-and-crosses board, a seating plan, a spreadsheet — each is naturally a grid, not a single line. A TWO-DIMENSIONAL array reaches a cell with a row index and a column index together: `board[1][2]` is row 1, column 2. It is stored as an array of arrays — each row is itself a one-dimensional array.

Tracing a total step by step

Array `marks` holds [7, 4, 9, 2]. `total = 0`. i=0: total = 0+7 = 7. i=1: total = 7+4 = 11. i=2: total = 11+9 = 20. i=3: total = 20+2 = 22. Loop ends once i passes the last valid index (3), and `total` is 22 — trace one line per pass, and an off-by-one in the loop's end condition is exactly the kind of error tracing catches.

The School — all subjects · Knowledge map