SDD  ·  Software Design & Development

Arrays

Lesson 12 of 18 Approx 60 min Requires: SDD9 Fixed Loops, SDD11 Predefined Functions
Learning intentions
  • Understand what an array is and why it is used instead of separate variables
  • Create and access elements in an array using index notation, starting at index 0
  • Use arrays with FOR loops to traverse and process multiple values efficiently
Success criteria
  • I can explain what an array is and state why it is more efficient than using separate variables
  • I can create an array in Python and access individual elements using their index number
  • I can update an element in an array by assigning a new value to a specific index
  • I can use len() to find the number of elements in an array
  • I can use a FOR loop with range(len(array)) to traverse all elements of an array
  • I can write SQA pseudocode for array creation, element access, and traversal
Warm up — what do you already know?

Answer before the lesson begins. These check prior knowledge from earlier lessons — it's fine if you're unsure.

1. A program needs to store the test scores of 5 pupils separately. How many variables would be needed if an array is NOT used?

2. A Python FOR loop begins: for i in range(5):. What values does i take during the loop?

3. What does len("hello") return?

Key vocabulary

array
A variable that stores multiple values of the same data type under one name. Each value is accessed using an index number.
index
The position of an element within an array. Indexing starts at 0 in Python — the first element is at index 0, the second at index 1, and so on.
element
A single value stored in an array. An array with five values has five elements, each at a different index.
traverse
To go through each element of an array one at a time, usually using a FOR loop. Traversal is used for tasks like calculating totals or finding the highest value.
list
Python's built-in name for a collection of values in square brackets. In N5 Computing Science, lists are used as arrays. The terms are interchangeable for this course.
out of bounds
Trying to access an index that does not exist in the array. For example, accessing index 5 in a 5-element array (which only has indices 0–4) causes an IndexError.

Arrays

Why use arrays?

Imagine a program that stores the test scores of 30 pupils. Without arrays, you would need 30 separate variables: score1, score2, score3, … score30. Adding them all up would require writing every variable name out explicitly — 30 separate lines just to calculate a total. If the number of pupils changed, you would have to rewrite large parts of the program.

Arrays solve this problem. An array stores multiple values of the same data type under one name. A loop can then process all the values without naming each one individually. This makes programs shorter, easier to maintain, and straightforward to extend.

Creating an array in Python

In Python, arrays are implemented as lists. A list is created using square brackets with values separated by commas:

scores = [85, 72, 91, 68, 88]

This creates an array called scores containing 5 integer values. For N5 Computing Science, all elements in an array should be the same data type — integers, real numbers (floats), or strings.

Accessing elements — index notation

Each element has an index number starting at 0. To read an element, write the array name followed by the index in square brackets:

Element8572916888
Index01234
scores[0]   # 85  — first element
scores[1]   # 72  — second element
scores[4]   # 88  — fifth (last) element

The index of the first element is always 0. An array with n elements has indices 0 to n − 1. This is the most commonly tested fact about arrays in the N5 exam.

Updating elements

You can change the value at a specific index by assigning a new value to it:

scores[2] = 95   # changes the third element from 91 to 95

After this line, the array becomes [85, 72, 95, 68, 88]. All other elements remain unchanged.

Finding the number of elements: len()

The len() function works on arrays just as it does on strings — it returns the number of elements:

len(scores)   # returns 5

This is especially useful in loops, because it means you do not have to know (or hard-code) the size of the array.

Traversing an array with a FOR loop

The most common array operation is traversal — processing every element in order. Combine range() with len() to generate every valid index:

for i in range(len(scores)):
    print(scores[i])

The variable i takes values 0, 1, 2, 3, 4 in turn. On each iteration, scores[i] reads the element at that index. The result is that every element is printed, in order.

A typical traversal accumulates a running total:

scores = [85, 72, 91, 68, 88]
total = 0
for i in range(len(scores)):
    total = total + scores[i]
print("Total:", total)

Always initialise the accumulator variable (here, total = 0) before the loop begins, or Python will raise a NameError when it tries to add to a variable that does not yet exist.

Combining traversal with selection

An if statement inside a loop allows you to process only certain elements:

scores = [85, 72, 91, 68, 88]
for i in range(len(scores)):
    if scores[i] >= 80:
        print("High score:", scores[i])

This prints only the elements that are 80 or above: 85, 91, and 88.

SQA pseudocode for arrays

In the N5 exam, you may be asked to write or trace pseudocode involving arrays. The key patterns are:

OperationPythonSQA Pseudocode
Create arrayscores = [85, 72, 91]SET scores TO [85, 72, 91]
Access elementscores[0]scores[0]
Update elementscores[2] = 95SET scores[2] TO 95
Traversefor i in range(len(scores)):FOR index FROM 0 TO LEN(scores) - 1 DO

Note the upper bound in pseudocode: LEN(scores) - 1, not LEN(scores). For a 5-element array, the loop runs from 0 to 4 — going up to 5 would attempt to access an index that does not exist.

Worked examples

Example 1 — Creating an array and accessing elements

A program stores the daily maximum temperatures (°C) for a week: 15, 18, 14, 20, 17, 16, 13. Display the temperature for Monday (first day) and Thursday (fourth day).

1
Create the array: temps = [15, 18, 14, 20, 17, 16, 13]. There are 7 elements, so indices run from 0 (Monday) to 6 (Sunday).
2
Access Monday: Monday is the first day — index 0. temps[0] = 15.
3
Access Thursday: Thursday is the fourth day — index 3. temps[3] = 20.
temps = [15, 18, 14, 20, 17, 16, 13]
print("Monday:   ", temps[0])
print("Thursday: ", temps[3])
Output: Monday: 15 Thursday: 20
Example 2 — Updating an element and calculating the total

Marks for 4 pupils are stored as [62, 78, 54, 91]. The third pupil's mark is corrected to 69 after an appeal. Calculate and display the new total.

1
Update element: The third pupil is at index 2. marks[2] = 69 changes 54 to 69. Array is now [62, 78, 69, 91].
2
Traverse to calculate total: Initialise total = 0 before the loop, then add each element in turn.
3
Python code and trace:
marks = [62, 78, 54, 91]
marks[2] = 69
total = 0
for i in range(len(marks)):
    total = total + marks[i]
print("Total:", total)
Trace: i=0 → total=62; i=1 → total=140; i=2 → total=209; i=3 → total=300. Output: Total: 300. Verified: 62 + 78 + 69 + 91 = 300 ✓
Example 3 — Traversal with selection: finding pass scores

Five exam scores are stored: [45, 72, 38, 88, 61]. Display only the scores that are a pass (50 or above).

1
Plan: Traverse the array. For each element, use an if statement to check whether it is ≥ 50. Only print it if the condition is true.
2
Python code:
scores = [45, 72, 38, 88, 61]
for i in range(len(scores)):
    if scores[i] >= 50:
        print("Pass:", scores[i])
3
Trace: i=0: 45 < 50 — skipped. i=1: 72 ≥ 50 — prints Pass: 72. i=2: 38 < 50 — skipped. i=3: 88 ≥ 50 — prints Pass: 88. i=4: 61 ≥ 50 — prints Pass: 61.
Example 4 — SQA pseudocode for array traversal

An array called prices holds 6 real numbers: [12.99, 8.50, 24.99, 6.75, 15.00, 3.49]. Write pseudocode to calculate and display the total.

1
Pseudocode structure: Use SET ... TO [...] to create the array. Use FOR index FROM 0 TO LEN(prices) - 1 DO for the loop — the upper bound is 5 (6 elements, indices 0–5).
2
Complete pseudocode:
SET prices TO [12.99, 8.50, 24.99, 6.75, 15.00, 3.49]
SET total TO 0
FOR index FROM 0 TO LEN(prices) - 1 DO
    SET total TO total + prices[index]
END FOR
SEND "Total: " + total TO DISPLAY
3
Verify the total: 12.99 + 8.50 + 24.99 + 6.75 + 15.00 + 3.49 = 71.72 ✓. The loop runs 6 times (index 0 to 5). Using LEN(prices) - 1 rather than a hard-coded 5 means the pseudocode still works correctly if the array size changes.
Now you try

A program uses an array to store the number of goals scored by a football team in each of their 5 matches: 2, 0, 3, 1, 4.

Answer the following:

  1. Write the Python code to declare this array.
  2. What is the value of goals[3]?
  3. Write the Python code to calculate and print the total number of goals scored.
  1. goals = [2, 0, 3, 1, 4]
  2. goals[3] = 1. Index 3 is the fourth element (2 is at index 0, 0 at index 1, 3 at index 2, 1 at index 3).
  3. goals = [2, 0, 3, 1, 4]
    total = 0
    for i in range(len(goals)):
        total = total + goals[i]
    print("Total goals:", total)
    Trace: 0+2=2, 2+0=2, 2+3=5, 5+1=6, 6+4=10. Output: Total goals: 10. Verified: 2+0+3+1+4=10 ✓
Common mistakes
Using index 1 for the first element. The first element is always at index 0, not index 1. Writing scores[1] accesses the second element. This off-by-one error is the most common mistake in array questions and will produce a wrong answer in a trace question without any error message from Python.
Going out of bounds. For an array with 5 elements, the valid indices are 0, 1, 2, 3, 4. Trying to access scores[5] causes an IndexError: list index out of range. This often happens when a loop uses range(len(scores) + 1) instead of range(len(scores)), or when pseudocode uses FOR index FROM 0 TO LEN(array) instead of LEN(array) - 1.
Starting the loop at index 1. Writing for i in range(1, len(scores)): skips the first element (index 0). The total will be wrong, and no error is raised, making this a difficult bug to spot. The correct form is range(len(scores)) which starts at 0 automatically.
Forgetting to initialise the accumulator. Writing a loop that does total = total + scores[i] without first declaring total = 0 causes a NameError — Python cannot add to a variable that does not yet exist. Always set accumulator variables to 0 (for totals) before the loop begins.
Using round brackets instead of square brackets. Writing scores = (85, 72, 91) creates a tuple, not a list/array. Tuples look similar but behave differently — in particular, you cannot update individual elements. Always use square brackets [ ] when creating an array in Python.
Exam tip

The SQA most commonly tests 0-based indexing and FOR loop traversal with arrays. In any trace question, always start from index 0, not 1. If asked to give the value of names[2] for the array ["Alice", "Bob", "Charlie", "David"], the answer is "Charlie" — it is the third element, at index 2.

In pseudocode questions, the loop bounds are a frequent mark — examiners look for FOR index FROM 0 TO LEN(array) - 1 DO. Writing TO LEN(array) (without the −1) is a common error that costs marks. The minus-one is needed because the last valid index is always one less than the length.

When a question asks you to find a total, average, or count using an array, the structure is always the same: initialise the accumulator before the loop, update it inside the loop, and use the result after the loop ends.

Task Set

Questions 1–5 are auto-checked. Questions 6–10 are self-marked — write your answer, then reveal the model answer to check your work.

1. Which of the following correctly creates an array of three integers called ages in Python? TYPE 1

2. An array is declared as temps = [18, 22, 15, 20, 17]. What does temps[3] return? TYPE 1

3. An array has 8 elements. What is the index of the last element? TYPE 1

4. Which code correctly traverses all elements of an array called values using a FOR loop? TYPE 1

5. What does the following code output?

numbers = [10, 20, 30, 40, 50]
total = 0
for i in range(len(numbers)):
    total = total + numbers[i]
print(total)
TYPE 1

6. An array heights = [162, 175, 158, 180, 170] stores the heights (cm) of 5 pupils. Write Python code to display only the heights that are 170 cm or more. TYPE 2

heights = [162, 175, 158, 180, 170]
for i in range(len(heights)):
    if heights[i] >= 170:
        print(heights[i])

Output: 175, 180, 170 (each on a separate line). The loop visits every element; the if statement filters out those below 170. Note that 170 is included because the condition uses >= (greater than or equal to), not >.

7. Write SQA pseudocode for a program that: (a) declares an array of 4 integers called scores, (b) uses a FOR loop to receive each value from the keyboard, and (c) uses a second FOR loop to display each value. TYPE 2

DECLARE scores ARRAY OF INTEGER
FOR index FROM 0 TO 3 DO
    RECEIVE scores[index] FROM KEYBOARD
END FOR
FOR index FROM 0 TO 3 DO
    SEND scores[index] TO DISPLAY
END FOR

With 4 elements, valid indices are 0 to 3 (i.e. LEN − 1 = 3). Two separate loops are used — one to fill the array, one to display it. You could also write FOR index FROM 0 TO LEN(scores) - 1 DO if the declaration makes the size clear.

8. The code below contains an error. Identify the error, explain what goes wrong when the program runs, and write the corrected code.

prices = [4.99, 2.50, 8.00, 1.25]
total = 0
for i in range(1, len(prices)):
    total = total + prices[i]
print("Total:", total)
TYPE 2

Error: The loop starts at index 1 instead of 0, so prices[0] (the value 4.99) is never added to total. No error message is produced — the code runs without crashing, but gives the wrong answer: 2.50 + 8.00 + 1.25 = 11.75 instead of the correct 16.74.

Corrected code:

prices = [4.99, 2.50, 8.00, 1.25]
total = 0
for i in range(len(prices)):
    total = total + prices[i]
print("Total:", total)

Correct total: 4.99 + 2.50 + 8.00 + 1.25 = 16.74 ✓. Using range(len(prices)) starts at 0 automatically.

9. Write a complete Python program that uses an array to store 5 temperatures: 22, 18, 25, 20, 15. The program should display each temperature (numbered 1 to 5), then calculate and display the average rounded to 1 decimal place. TYPE 3

temps = [22, 18, 25, 20, 15]
for i in range(len(temps)):
    print("Temperature", i + 1, ":", temps[i])
total = 0
for i in range(len(temps)):
    total = total + temps[i]
average = round(total / len(temps), 1)
print("Average temperature:", average)

Trace: total = 22+18+25+20+15 = 100. Average = 100 / 5 = 20.0. round(20.0, 1) = 20.0. Note i + 1 in the print — this gives display numbers 1 to 5 while the loop index runs 0 to 4. Verified: 22+18+25+20+15 = 100 ✓

10. The following pseudocode has a logic error. State what the error is and write the corrected pseudocode.

SET names TO ["Alice", "Bob", "Charlie", "David"]
FOR index FROM 0 TO LEN(names) DO
    SEND names[index] TO DISPLAY
END FOR
TYPE 3

Error: The loop runs FROM 0 TO LEN(names). Since LEN(names) = 4, the loop tries to access names[4] on the last iteration. The array only has indices 0–3, so this is an out-of-bounds error — it would cause an IndexError in Python. The upper bound must be LEN(names) - 1.

Corrected pseudocode:

SET names TO ["Alice", "Bob", "Charlie", "David"]
FOR index FROM 0 TO LEN(names) - 1 DO
    SEND names[index] TO DISPLAY
END FOR

For a 4-element array, LEN(names) - 1 = 3, so the loop visits indices 0, 1, 2, 3 — exactly the four valid positions.

Teacher notes — Shift+T to hide

Suggested timing: 60 minutes. Warm up 10 min; notes + tables 15 min; worked examples 15 min; now you try 5 min; task set 15 min.

Key misconception to address: 0-based indexing. Virtually every pupil will at some point say "the first element is at index 1." Reinforce with a concrete analogy: house numbers in a row starting at 0 — the first house is number 0, the second is number 1. In a trace question, always write out the indices explicitly before starting: index 0 = first value, index 1 = second value, etc.

Live demo suggestion: Open a Python REPL. Create a list live — names = ["Alice", "Bob", "Charlie"]. Print names[0], names[1], names[2]. Then deliberately try names[3] to trigger an IndexError — pupils should see this error and know what causes it. Then show the traversal loop and the accumulator pattern. Finally demonstrate the off-by-one bug by changing range(len(names)) to range(1, len(names)) and asking pupils to predict what will be missed.

Extension question: Ask pupils to write a program that stores 5 test scores in an array, then counts how many are above the average. This combines traversal, accumulation, round() from SDD11, and a conditional counter — a good preparation for the standard algorithms in SDD13 and SDD14.

Note on Python for loops: Python also supports for item in array: which iterates over values directly without an index variable. This is not covered here because the N5 exam uses index-based pseudocode (FOR index FROM 0 TO LEN(array) - 1) and pupils need to understand indexing for standard algorithms. If pupils ask about the direct form, you can acknowledge it exists but explain that the indexed form is required for the exam.

SQA command words covered: "state" (Q2, Q3, Q10), "write" (Q6, Q7, Q9, Q10 pseudocode/Python), "identify" and "explain" (Q8 error).