Arrays & Lists

💻 Computer Science Years 8–11 Foundation

Storing many values under one name, reading and changing them by zero-based index, and looping through them.

Open this lesson, with practice and a printable worksheet →

Imagine storing the marks of 30 students. You could make 30 separate variables — mark1, mark2, all the way to mark30 — but that is madness. An array (also called a list) stores many values under a single name, and reaches each one by its position number, called an index. One name, many boxes.

Why this matters: Data almost never comes one item at a time. High scores, playlists, pixels, sensor readings — all are collections. Arrays let a single loop process the whole collection in a few lines, which is why they appear in nearly every real program.
1279420 01234 index 0 = first
One array named scores; indices run 0, 1, 2, 3, 4.

Creating and reading an array

127942001234scores[4]the index is the house number
The index is like a house number: give it to fetch that one value.

You write the values in square brackets, then read any one by its index in more brackets:

scores = [12, 7, 9, 4, 20]
OUTPUT scores[0]     // 12
OUTPUT scores[4]     // 20

Think of a street of houses: the array name is the street, and each index is a house number. To visit one value you give its number. Every element must be the same type — an array of integers holds only integers — which is what lets the computer store them neatly in a row and jump straight to any position.

Indexing starts at ZERO

01234firstlastindex 0length − 15 items → indices 0 to 4
The first index is 0; the last is always length − 1.

This is the single most important rule. The first item is at index 0, not 1. So an array of 5 items has indices 0 to 4. The last index is always the length minus one.

Index01234
Value1279420

Changing values and looping through

scores[1] = 157old valueat index 115new valueoverwritten
Assigning to an index overwrites whatever was in that box.

You can overwrite any element by assigning to its index, and — best of all — a loop can visit every element in turn:

scores[1] = 15          // the 7 becomes 15
total = 0
FOR i ← 0 TO 4
    total = total + scores[i]
NEXT i
Worked trace of the loop, using scores = [12, 15, 9, 4, 20]:
i=0: total = 0 + 12 = 12
i=1: total = 12 + 15 = 27
i=2: total = 27 + 9 = 36
i=3: total = 36 + 4 = 40
i=4: total = 40 + 20 = 60
Final total = 60 — the whole array summed in one small loop.
Common mistake: the off-by-one error. In a 5-item array, scores[5] does not exist — the valid indices are 0 to 4. Asking for index 5 causes an "out of range" error.
012345?✗valid: 0 to 4out ofrange
Off-by-one: index 5 points past the end of a 5-item array — an error.

To loop over an array, count from 0 up to length minus one. If in doubt, write the indices above the values on paper before you code — it kills off-by-one bugs before they start.

Get the printable worksheet →
← Iteration (Loops) → Strings
← Sasta Basta home All subjects