Menu

Pseudocode

Following and Tracing Pseudocode

Following an algorithm means reading it as the computer would, one statement at a time, and keeping a record of every value that changes. A trace is that record: for each step you note the value of each variable and whether each condition is true or false. The same method works whether the algorithm is printed as pseudocode in an exam paper or written as a program in Python.

Work through the statements in the order they are written. When an assignment runs, the new value replaces the old one. At an if, test the condition once and follow only the branch that applies. In a while loop the condition is tested before each pass, and the body runs only while that condition is true. Constants never change, so use their value in every expression that uses them. If the algorithm works through a data structure, trace the position as well as the value, because the body may run once for each item. Variables, constants and data structures must be used so that the logic of the algorithm is correct. When you write an algorithm, keep the steps and conditions clear so a trace would produce the intended result.

Worked trace

EVEN_POINTS = 10
score = 0
lap = 1
while lap <= 4:
    if lap % 2 == 1:
        score = score + lap * 2
    else:
        score = score + EVEN_POINTS
    lap = lap + 1
print(score)

Output:

28
laplap <= 4lap % 2 == 1score
1TrueTrue2
2TrueFalse12
3TrueTrue18
4TrueFalse28
5Falsenot tested28

A flowchart of the lap and score while loop: set values, test lap <= 4, then test lap % 2 == 1 to choose between adding lap * 2 or EVEN_POINTS, add 1 to lap and loop back, finishing with print(score).

After lap becomes 5 the loop condition is false, so the loop stops and the output is 28. The trace shows what the algorithm does: odd laps add twice the lap number (2, then 6) and every even lap adds the constant 10. If the output were wrong, the trace would show the first statement or condition where the values stop matching what the algorithm should do, helping you find the logic error and confirm the algorithm does what it is meant to do. You can also trace an algorithm to work out its purpose when the output alone is not obvious.

Practise this