Arrays and records
One-dimensional arrays
An array stores an ordered collection of values of the same type under one name. An ERL array has a fixed size; Python lists can grow, but use a fixed number of elements when writing a list as an exam-style array. The first index is 0. This loop adds the three scores and prints 13:
scores = [4, 7, 2]
total = 0
FOR i = 0 TO 2
total = total + scores[i]
NEXT i
OUTPUT total
i | scores[i] | total |
|---|---|---|
| 0 | 4 | 4 |
| 1 | 7 | 11 |
| 2 | 2 | 13 |
Common mistake
For three values, the last index is 2. Python range(3) stops before 3; ERL's TO 2 includes 2.
Key terms
Two-dimensional arrays and records
A 2D array arranges values in rows and columns, like a table. Use two indexes: the row first, then the column. A record groups related fields about one thing; in this specification, represent records as rows of a 2D array. Keep the column meanings consistent: here, each row is [name, age, score].
students = [["Ada", 15, 81], ["Ben", 16, 68]]
OUTPUT students[0][2]
Both print 81, the score in row 0, column 2. A nested loop can visit every row and column.
Key terms
Finding the highest value
Loops over arrays solve many problems. To find the highest value, start with the first element, then compare each of the others with the highest found so far:
array scores = [4, 7, 2]
highest = scores[0]
for i = 1 to 2
if scores[i] > highest then
highest = scores[i]
endif
next i
print(highest)
Both print 7. The loop starts at index 1, because element 0 is already in highest. Starting highest at the first element, rather than at 0, means the algorithm still works if every value is negative.
Looping through records
To process every record in a 2D array, loop through its rows. This finds the mean score, which is in column 2 of each row:
array students = [["Ada", 15, 81], ["Ben", 16, 68]]
total = 0
for row = 0 to 1
total = total + students[row, 2]
next row
print(total / 2)
Both print 74.5. ERL writes a 2D position as [row, column]; Python uses two sets of brackets, [row][column]. To visit every value, put a second loop over the columns inside the loop over the rows.