Free revision guides

Running total within a loop

National 5 Computing Science: Software design and development

A running total inside a loop is the other algorithm that comes up in the National 5 exam almost every year, often for 4 marks. The examiners' reports say many answers are left blank, or written without a loop at all.

The pattern

Five days of rainfall, in millimetres, are stored in an array. The program adds them up and works out the average:

DECLARE rainfall INITIALLY [12, 0, 7, 3, 18]
SET total TO 0
FOR index FROM 0 TO 4 DO
   SET total TO total + rainfall[index]
END FOR
SET average TO total / 5
SEND "Average rainfall: " & average & " mm" TO DISPLAY

Every running total has three parts:

  1. Before the loop: set the total to 0.
  2. Inside the loop: add the next value to the total. Here that is rainfall[index], the next item in the array.
  3. After the loop: use the total: display it, or work out an average.

The same program in Python:

rainfall = [12, 0, 7, 3, 18]
total = 0
for index in range(5):
    total = total + rainfall[index]
average = total / 5
print("Average rainfall:", average, "mm")
What the marker looks for
  • A loop that runs the right number of times: 5 items means indexes 0 to 4.
  • The value added to the total inside the loop.
  • The next array item used each time, with the array name from the question.
  • Any average worked out after the loop, not inside it.

Mistakes that lose the marks

  • Setting the total to 0 inside the loop. It goes back to 0 every time, so at the end it holds only the last value.
  • Adding the index instead of the item. total + index adds 0, 1, 2, 3, 4, not the rainfall.
  • Using your own names. If the question calls the array rainfall, use rainfall. A general formula with made-up names does not gain the mark.
  • Going one too far. FOR index FROM 0 TO 5 tries to read a sixth item that does not exist.

Try two exam-style questions

Choose an answer, say how sure you are, then press Check. Every wrong answer tells you why it is wrong.

The Loop visualiser simulation
In the course: Loop visualiser. Watch a loop run and a total grow, pass by pass, with the array and the variables on screen.

The full course covers every topic like this. Every topic in National 5 Computing Science has a short note, a simulation to try and a practice quiz with feedback on every answer, plus coding lessons, a full mock exam and a progress report for parents.

Create an accountTry more for freeAbout the course

More guides

This site is independent: it is not connected to the SQA or Qualifications Scotland. Points from the examiners' course reports are given in our own words.