Tracing a program
SOF ICSO · Computer Science · about 7 minutes
“What is the output?” questions are solved by tracing: keep a small table of every variable and update it line by line.
Run the program one step at a time and watch the variables.
Be the computer
To trace a program, make a table with a column for every variable and a row for every step. Run each line exactly as written, updating the table.
Computers do not guess: x = x + 1 means ‘take the old x, add 1, store it back’.
Loops
A for loop from 1 to 5 runs 5 times. A while loop runs as long as its condition is true, and checks it before each run. Count the runs carefully: off-by-one mistakes are the most common error.
Nested loops multiply: an outer loop of 3 and an inner loop of 4 run the inner body 12 times.
Conditions
If–else picks one path. Check comparison signs carefully: < is not ≤.
Integer division and remainder (// and % in Python) are common: 17 // 5 = 3 and 17 % 5 = 2.
Worked examples
Example 1s = 0; for i in 1 to 4: s = s + i * i. What is s?
- i = 1: s = 1.
- i = 2: s = 5.
- i = 3: s = 14.
- i = 4: s = 30.
Answer: 30
Example 2n = 20; c = 0; while n > 1: n = n // 2; c = c + 1. What is c?
- n: 20 → 10 → 5 → 2 → 1.
- That is 4 halvings.
Answer: 4
See it move
Where marks are lost
- Running a loop one time too many or too few.
- Using a value before it is updated in the same line.
- Forgetting that integer division drops the remainder.
Exam tips
- A loop “for i in 1 to 5” runs five times.
- Update the table after every line, not in your head.
- Watch for = (store) versus == (compare).
Practice questions
x = 2; repeat 3 times: x = x × 2. What is x?
total = 0; for i in 1 to 4: total = total + i. Output total?
a = 5; b = 3; a = a + b; b = a − b. What is b?
More worked examples
Try each one first, then open the working.
Fill the trace table. What value replaces “?”?
Show the working
Start: Each row adds i × k to the total from the row above.
total after i = 3: 6 + 9 = 15.
Answer: 15
Trace the flowchart. What number is printed?
Show the working
Start: Write down s and n after every pass round the loop.
s takes the values 12 + 11 + 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 78.
Answer: 78
How many times is print called? for i in range(5): for j in range(i, 8): print(i, j)
Show the working
Start: For each i, the inner loop runs b − i times.
The inner loop runs 8 + 7 + 6 + 5 + 4 = 30 times.
Answer: 30
Fill the trace table. What value replaces “?”?
Show the working
Start: Each row adds i × k to the total from the row above.
total after i = 4: 3 + 6 + 9 + 12 = 30.
Answer: 30
Practise more
New questions every time, at exam level
Fill the trace table. What value replaces “?”?