Menu

Writing and Refining Algorithms

Interpreting an Algorithm

Interpreting an algorithm means saying in plain words what it does, what it outputs for particular inputs, and how many times each loop runs. Saying what it outputs means stating the result it produces, such as a total it prints or a message it displays. A computer works through the lines in order, one at a time, so you can do the same: take each line in turn and write down the value of every variable afterwards.

Work through it line by line

Choose test values for any inputs, then follow the lines in order. Replace each variable name with the value it currently holds, carry out the step, and note any change before you move on. Writing down each new value as you go stops you losing track of where the algorithm has got to.

The algorithm below adds 15 tokens to a jar each round until the jar holds 60, and counts the rounds it took.

tokens = 0
rounds = 0
while tokens < 60:
    tokens = tokens + 15
    rounds = rounds + 1
print(rounds)

Output:

4
Stagetokensroundstokens < 60
Before any pass00True
After pass 1151True
After pass 2302True
After pass 3453True
After pass 4604False

The test is checked before every pass. After the fourth pass tokens holds 60, so the test at the top gives False, the indented block is skipped and the loop stops, leaving rounds at 4, the value in the last row. In one sentence, the algorithm counts how many rounds of 15 tokens are needed to fill the jar to 60.

Working out how many times a loop runs

For a for loop the answer comes from the start and end values: range(1, 6) repeats for 1, 2, 3, 4 and 5, so five passes. For a while loop you cannot tell from the line alone, so follow the changing variable until the condition becomes false. Check the very first test as well, because a while loop whose condition is already false runs no passes at all.

Where the algorithm asks for input, use the value given in the question, follow it through the lines and state the output it produces. A different input can mean a different output and a different number of passes.

Practise this

OCR GCSE Computer Science · Writing and Refining Algorithms