IBDP Computer Science B2.4 Programming algorithms SL Paper 1 - New Syllabus

Question 

Construct a trace table for the following algorithm:
N = 5
S = 0
R = 0

loop while N > 0
    A = N mod 3

    if A = 0
    then
        S = S - N
    else
        if A = 1
        then
            S = S + N
        else
            S = S + 1
        end if
    end if

    R = R + S
    N = N - 1
end loop

output('The result is ', R)
[6]

Most-appropriate topic code (CED):

• TOPIC B2.4: Programming algorithms
▶️ Answer/Explanation

Answer:

The values of N, S, R and A are recorded during each iteration of the loop.

NSRAOutput
5002 
4111 
3560 
2282 
13111 
0415 The result is 15

Working through the iterations:

  • For \(N=5\), \(A=5\operatorname{mod}3=2\), so \(S=S+1=1\), then \(R=0+1=1\).
  • For \(N=4\), \(A=4\operatorname{mod}3=1\), so \(S=S+4=5\), then \(R=1+5=6\).
  • For \(N=3\), \(A=3\operatorname{mod}3=0\), so \(S=S-3=2\), then \(R=6+2=8\).
  • For \(N=2\), \(A=2\operatorname{mod}3=2\), so \(S=S+1=3\), then \(R=8+3=11\).
  • For \(N=1\), \(A=1\operatorname{mod}3=1\), so \(S=S+1=4\), then \(R=11+4=15\).

After the final iteration, \(N\) becomes \(0\), so the loop terminates and the algorithm outputs 15.

Award [6 max]
Award [1] for a trace table with at least four columns, excluding the output column.
Award [1] for each correct column: \(N\), \(S\), \(R\), \(A\), and output.

Scroll to Top