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.
Creating and reading an array
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
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.
| Index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Value | 12 | 7 | 9 | 4 | 20 |
Changing values and looping through
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
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.
scores[5] does not exist — the valid indices are 0 to 4. Asking for index 5 causes an "out of range" 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.