CIE AS & A Level Computer Science, section 10.2 (Arrays)
What a 2D array is
A two-dimensional (2D) array is like a table with rows and columns. Each element is accessed with two indices: Array[row, column].
Declaring
DECLARE Marks : ARRAY[1:3, 1:4] OF INTEGER
This has 3 rows (students) and 4 columns (tests), so elements.
| Test 1 | Test 2 | Test 3 | Test 4 | |
|---|---|---|---|---|
| Student 1 | 60 | 70 | 80 | 90 |
| Student 2 | 55 | 65 | 75 | 85 |
| Student 3 | 40 | 50 | 60 | 70 |
Marks[2, 3] is 75.
Processing with nested loops
Use a loop for the rows inside another loop for the columns.
FOR Row ← 1 TO 3
RowTotal ← 0
FOR Col ← 1 TO 4
RowTotal ← RowTotal + Marks[Row, Col]
NEXT Col
OUTPUT "Student ", Row, " total: ", RowTotal
NEXT Row
Python
marks = [[60, 70, 80, 90],
[55, 65, 75, 85],
[40, 50, 60, 70]]
for row in range(3):
print("Student", row + 1, "total:", sum(marks[row]))
print(marks[1][2]) # 75 (Python indexes from 0)
Choosing 1D or 2D
- Use a 1D array for a simple list.
- Use a 2D array for tabular data with two dimensions: a seating plan, a game board, or marks for several students over several tests.
Common mistake: mixing up the row and column indices, or using the wrong loop order. The first index is the row and the second is the column. Also, use the correct upper bound for each dimension.
Exam tip: draw the table and mark the row and column numbers. Use nested loops (outer loop for rows, inner for columns) and check that every element is visited exactly once.
Check yourself
How many elements are in `ARRAY[1:4, 1:5]`?
.
How do you access the element in row 2, column 3 of `Grid`?
Grid[2, 3].
Why are nested loops used to process a 2D array?
One loop goes through the rows and the other through the columns, so every element is visited.