AQA GCSE Computer Science (8525), section 3.2.6 (Data structures)
Data structures
A data structure is a way of organising and storing related data so a program can use it easily. Instead of ten separate variables score1, score2... you can store all ten scores together.
Arrays
An array stores a fixed number of items under one name, all of the same data type. Each item is found using its index (its position). In AQA pseudo-code and Python, the first index is 0.
names ← ["Ali", "Bea", "Cara", "Dev"]
OUTPUT names[0] (Ali)
names[2] ← "Chloe" (changes the third item)
| Index | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| Value | Ali | Bea | Chloe | Dev |
names = ["Ali", "Bea", "Cara", "Dev"]
print(names[0]) # Ali
names[2] = "Chloe"
print(len(names)) # 4
Looping through an array
total ← 0
FOR i ← 0 TO 3
total ← total + scores[i]
ENDFOR
OUTPUT total / 4
scores = [12, 18, 9, 15]
total = 0
for i in range(len(scores)):
total = total + scores[i]
print(total / len(scores)) # 13.5
Two-dimensional arrays
A 2D array is like a table with rows and columns. You need two indexes: array[row][column].
| col 0 | col 1 | col 2 | |
|---|---|---|---|
| row 0 | 5 | 8 | 2 |
| row 1 | 7 | 1 | 9 |
grid = [[5, 8, 2],
[7, 1, 9]]
print(grid[1][2]) # 9 (row 1, column 2)
grid[0][1] = 6
for row in range(2):
for col in range(3):
print(grid[row][col], end=" ")
print()
Examples: a noughts and crosses board, or a table of marks for several students in several tests. Only one- and two-dimensional arrays are needed.
Why use arrays?
- Store lots of related values neatly under one name.
- Use a loop to process every item.
- The code stays the same length, however many items there are.
Common mistake: counting from 1 instead of 0. An array of 4 items has indexes 0 to 3, so names[4] does not exist and causes an error. Also, in a 2D array the row index comes first, then the column.
Exam tip: draw a small table of the array and write the index above each cell. For a 2D array, label the rows and columns to avoid mixing them up.
Check yourself
In an array of 6 items, what is the index of the last item?
What is grid[1][0] if grid = [[4, 5], [6, 7]]?
Give one advantage of an array compared with separate variables.
A loop can process every item, and related data is stored together under one name.