CIE AS & A Level Computer Science, section 10.2 (Arrays)
What an array is
An array is a data structure that stores a fixed number of items of the same data type under one name. Each item is called an element and is accessed by its index (its position).
Terms
- Index: the number that identifies an element.
- Lower bound and upper bound: the first and last index. In
ARRAY[1:5]the lower bound is 1 and the upper bound is 5. - Element: one item stored in the array.
Declaring and using
DECLARE Marks : ARRAY[1:5] OF INTEGER
Marks[1] ← 60
Marks[2] ← 72
Processing an array
Use a count-controlled loop to visit each element.
Total ← 0
FOR i ← 1 TO 5
Total ← Total + Marks[i]
NEXT i
Average ← Total / 5
Finding the largest:
Largest ← Marks[1]
FOR i ← 2 TO 5
IF Marks[i] > Largest THEN
Largest ← Marks[i]
ENDIF
NEXT i
Python
Python lists start at index 0, so index in the pseudocode ARRAY[1:5] is marks[i - 1].
marks = [60, 72, 55, 80, 68]
total = sum(marks)
print(total / len(marks), max(marks)) # 67.0 80
When to use a 1D array
Use one for a list of values of the same type: a set of marks, names or temperatures. It avoids using many separate variables.
Common mistake: going outside the bounds, such as Marks[0] or Marks[6] for ARRAY[1:5], which causes an error. Also, remember an array has one data type for all its elements.
Exam tip: in pseudocode, state the array's bounds and type in the declaration, and use the bounds in the loop. Trace the loop with a small example to check the first and last elements are included.
Check yourself
What is the upper bound of `ARRAY[1:10]`?
What does the index of an element show?
The position of the element in the array.
Write a loop to output every element of `Names : ARRAY[1:20]`.
FOR i ← 1 TO 20 then OUTPUT Names[i] then NEXT i.