A dry run means working through an algorithm by hand, one line at a time, exactly as the computer would. A trace table records every change to every variable and every output. It is the most reliable way to find out what an algorithm does, and it is in almost every exam.
A dry run is working through an algorithm by hand with given test data. A trace table has a column for each variable and one for OUTPUT (including user prompts). Work line by line: write a new value in the column only when it changes, move down a row as the algorithm moves on, and follow every condition and loop exactly as written, not as you think the programmer meant.
Load a program in the lab, enter the test data and step through it line by line. The trace table fills in as each line runs: compare it with the one below.
Count ← 0
Total ← 0
OUTPUT "Enter a number, -1 to stop"
INPUT Number
WHILE Number <> -1 DO
IF MOD(Number, 2) = 0
THEN
Total ← Total + Number
Count ← Count + 1
ENDIF
INPUT Number
ENDWHILE
OUTPUT Count, " even numbers, total ", Total
Test data: 4, 7, 10, 3, -1
| Number | Count | Total | OUTPUT |
|---|---|---|---|
| 0 | 0 | Enter a number, -1 to stop | |
| 4 | 1 | 4 | |
| 7 | |||
| 10 | 2 | 14 | |
| 3 | |||
| -1 | 2 even numbers, total 14 |
The rogue value -1 is input and recorded in the trace table, but the loop ends before it is processed. Do not add it to the total.
With a FOR loop, the loop counter gets its own column. With an IF, check the condition with the current values every time round: the branch taken can change from one pass to the next.
INPUT Number
FOR Count ← 1 TO 4
IF MOD(Number, 2) = 0
THEN
Number ← DIV(Number, 2)
ELSE
Number ← 3 * Number + 1
ENDIF
OUTPUT Number
NEXT Count
Use the new value of a variable on the next line. After Number becomes 3, the OUTPUT on the same pass shows 3, not 6.
Four quick checks. Each correct answer earns XP and records this skill on your profile.
What is a dry run?
What does a trace table record?
In the even-number algorithm, which input ends the loop?
In the lab, what does DIV(352, 10) evaluate to?
This algorithm adds up the digits of a whole number. MOD(Number, 10) gives the last digit and DIV(Number, 10) removes it. Fig. 1 shows its trace table with input 352.
OUTPUT "Enter a whole number"
INPUT Number
Sum ← 0
REPEAT
Digit ← MOD(Number, 10)
Sum ← Sum + Digit
Number ← DIV(Number, 10)
UNTIL Number = 0
OUTPUT Sum
A REPEAT loop always runs at least once, because the condition is tested at the end. With input 0 this algorithm still runs once and outputs 0.
Unlocks once the four checks above are done. Worth more XP, written to IGCSE Paper 1 standard.
X ← 2, then a loop runs X ← X * 3 three times. What is the final value of X?
What is MOD(47, 5)?
A WHILE loop condition is false the first time it is tested. How many times does the loop body run?
In the even-number algorithm, the inputs are 2, 8, 5, -1. What is output?
This skill is now recorded on your profile. Keep the chain going.