Tracing Algorithms: Trace Tables, Test Plans and Correctness

MODULE 2 • LESSON 09

An algorithm can look sensible and still be wrong. It might give the right answer for most inputs but fail when two values are equal, when no data is entered, or when a value sits exactly on a boundary. Before an algorithm is turned into a program, you need a reliable way to work out what it really does and to prove that it does what it is supposed to do.

This lesson gives you two tools for that job. A trace table lets you run an algorithm by hand, one step at a time, and record every value. A test plan lists carefully chosen test data with the expected results, so you can compare them with what the algorithm actually produces. You will fill in live trace tables that check each row, then use a test plan to catch a bug in a “largest of three” algorithm and choose the correct fix.

What you will learn

  • What it means for an algorithm to be correct.
  • How to carry out a dry run and record it in a trace table, for pseudocode and flowcharts.
  • How to work out the output of an algorithm, including loops and selection.
  • How to choose normal, boundary and erroneous test data.
  • How to write a test plan with expected and actual results.
  • How to decide whether an algorithm meets its objective, find the error and correct it.
  • How to trace a C program with printf statements.

Part 1: What does “correct” mean?

An algorithm is correct when it achieves its stated objective for every valid input, not just the example the writer had in mind. In practice that means it:

  • produces the expected output for all valid data, including values on the boundaries and unusual cases such as equal values or no data;
  • deals sensibly with invalid data (rejects it or reports it) when the problem says it should;
  • always terminates: every loop eventually ends;
  • does exactly what the problem statement asks, no more and no less.

The syllabus asks for two related skills. Interpreting an algorithm means working out what it outputs for given data. Analysing an algorithm for correctness means deciding whether it achieves its objective and, if it does not, giving a corrected version. Trace tables help with both; test plans make the analysis systematic.

Part 2: Dry runs and trace tables

A dry run is running an algorithm by hand, on paper, without a computer. A trace table is the record of a dry run. It has:

  • one column for each variable, in the order they appear;
  • a column for each condition that is tested (or one combined “Condition” column), holding True or False;
  • an Output column;
  • one row for each step that changes something. Write a new value only in the column that changes; leave the other cells blank, so that the latest value of a variable is the last one written in its column.

Some exam questions give you a ready-made table with one row per loop pass instead of one per line. Use the layout the question gives you, and if it has fewer rows than you expect, check your work: examiners usually supply the right number.

Worked example 1: a WHILE loop

1  a ← 3
2  b ← 0
3  WHILE a <= 11 DO
4     b ← b + a
5     a ← a + 4
6  ENDWHILE
7  OUTPUT b
Lineaba <= 11Output
13
20
3True
43
57
3True
410
511
3True
421
515
3False
721

Notice three things. When a = 11 the condition a <= 11 is still True, so there is a third pass: the boundary matters. The loop body ran 3 times, but the condition was tested 4 times. And the final value of a (15) is never output; only b is.

Try it 1Live trace table

Choose an algorithm. The highlighted line is the one being carried out. Type the new value (or tap True or False for a condition) and the row is added to the trace table when you are right. Use Show me if you are stuck.

In the FOR example, the loop variable n gets its own row each time it changes, just like any other variable. In the REPEAT example, the condition is tested at the bottom, after the body: the first test happens only once x and k have already changed.

Part 3: Tracing flowcharts and working out output

A flowchart is traced in exactly the same way: follow the arrows, write a row whenever a value changes, and record the outcome of each decision. When the algorithm reads input, add an Input column (or show the input value being stored in its variable).

Worked example 2: counting values above a limit

The flowchart below reads four readings and counts how many are above 50. Trace it with the inputs 64, 38, 50, 71.

Startcount = 0i = 1i ≤ 4 ?YesInput rr > 50 ?Yescount =count + 1Noi = i + 1NoOutput countStop
Counting readings above 50.
irr > 50countOutput
10
64True1
238False
350False
471True2
52

Here the table is compressed to one row per pass, which is common in exams. The key moment is the boundary: 50 is not greater than 50, so it is not counted, and the output is 2. If the objective had been "count readings of 50 or more", this algorithm would be incorrect, and the fix would be to change the condition to r ≥ 50.

Tips for working out output. Output happens only at OUTPUT (or PRINT) steps, and in the order they occur. If an OUTPUT is inside a loop, there is one line of output per pass. Write the output exactly, including any text in quotation marks, and do not output variables that the algorithm never outputs.

Part 4: Test data and test plans

A dry run with one set of data shows what happens for that data only. To be confident an algorithm is correct, you test it with data chosen to cover every kind of case. There are three main kinds of test data:

KindWhat it isExample (mark must be 0 to 100)
NormalTypical, valid data the algorithm should accept and process45, 72
Boundary (extreme)Valid values at the very edges of the range, and the values just outside them0, 100 (and -1, 101 just outside)
Erroneous (invalid)Data that should be rejected: out of range or the wrong type150, -20, "abc"

Boundary data matters because that is where mistakes between < and <= show up. For algorithms that compare values, also test special cases: equal values, all values the same, negative values, and no data at all (for sentinel loops).

A test plan is a table prepared before testing. For each test it records:

ColumnWhat goes in it
Test number1, 2, 3, … so that results can be referred to
Purpose / reasonWhat the test checks, e.g. "boundary: lowest pass mark"
Test dataThe exact input values
Expected resultWorked out by hand from the problem statement, not from the algorithm
Actual resultWhat the algorithm (or program) really produced
Pass / FailPass if actual equals expected; otherwise investigate

Worked example 3: a test plan for a pass mark

Objective: input a mark from 0 to 100; output "Pass" for 50 or more and "Fail" otherwise; output "Invalid" for any mark outside the range.

#PurposeDataExpected
1Normal pass72Pass
2Normal fail31Fail
3Boundary: lowest pass50Pass
4Boundary: highest fail49Fail
5Boundary: lowest valid0Fail
6Boundary: highest valid100Pass
7Erroneous: above range101Invalid
8Erroneous: below range-5Invalid

Notice that the expected results come straight from the objective. If you worked them out by running the algorithm, you would only ever confirm its mistakes.

Part 5: Analysing an algorithm for correctness

To analyse an algorithm, follow these steps:

  1. Read the objective carefully and list what the output should be.
  2. Build a test plan, including boundary and special cases, with the expected results.
  3. Dry run the algorithm with each test, using a trace table where it helps, and record the actual results.
  4. For any test that fails, find the exact line that causes the difference.
  5. Correct that line (or add the missing step) and test again with all the tests, not just the one that failed.

The algorithm below is meant to output the largest of three numbers. It looks reasonable and it works for many inputs. Use the test plan to find out when it fails, then try the three suggested fixes.

Try it 2Test plan: largest of three

The expected results were worked out by hand. Tap Run all tests to fill in the actual results. Find the failing test, then choose a fix and run the tests again. Changed lines are shaded green. You can also set your own test (the last row).

The original fails when the two largest values are equal and come first (9, 9, 2): neither a nor b is strictly greater than the other, so the algorithm falls through to c. Fix A uses ≥, so a tie still picks a correct value; every test passes. Fix B fixes nothing useful: with OR, a only needs to beat one of the others. Fix C passes the tie but now fails whenever c is the largest. A fix must be tested against every test, not only the one that failed.

Common logic errors to look for

ErrorTypical symptomCorrection
Wrong relational operator (> instead of ≥)Boundary values handled wronglyRe-read the objective: "or more", "at least", "over"
Wrong initial valueTotal or count is off from the startSet totals and counts to 0 (and a product to 1) before the loop
Initialising inside the loopOnly the last value seems to countMove the initialisation above the loop
Missing update of the loop variableThe loop never endsAdd the increment or the next INPUT
Wrong loop boundsOne pass too many or too fewCount the passes; check < versus <=
Sentinel processed as dataCount is one too many, total is offRead the next value at the end of the body
Wrong divisor for an averageAverage is wrong when the amount of data changesDivide by the counter, and check it is not 0

Worked example 4: finding and correcting an error

Objective: read 5 prices and output their average. A student wrote:

1  FOR i ← 1 TO 5 DO
2     total ← 0
3     INPUT price
4     total ← total + price
5  ENDFOR
6  avg ← total / 5
7  OUTPUT avg

Test with 10, 20, 30, 40, 50 (expected average 30). Tracing shows total being reset to 0 on every pass, so after the loop total = 50 and the output is 10. The actual result (10) does not match the expected result (30), so the algorithm is not correct. Correction: move line 2 above the loop, so that total ← 0 runs once. Re-test: total = 150, output 30. Pass.

Part 6: Tracing in C

Programmers trace real programs too. The simplest way is to add printf statements that print the variables after each change; the output becomes a trace table. Here is worked example 1 in C:

#include <stdio.h>

int main(void)
{
    int a = 3, b = 0;

    printf("a\tb\n");
    printf("%d\t%d\n", a, b);
    while (a <= 11) {
        b = b + a;
        a = a + 4;
        printf("%d\t%d\n", a, b);
    }
    printf("Output: %d\n", b);
    return 0;
}

Output:

a	b
3	0
7	3
11	10
15	21
Output: 21

The buggy "largest of three" in C, run with the failing test 9, 9, 2. In C, AND is written &&:

#include <stdio.h>

int main(void)
{
    int a, b, c, big;

    printf("Three numbers: ");
    scanf("%d %d %d", &a, &b, &c);

    if (a > b && a > c)
        big = a;
    else if (b > a && b > c)
        big = b;
    else
        big = c;

    printf("\nLargest: %d\n", big);
    return 0;
}

Sample input: 9 9 2

Output:

Three numbers: 
Largest: 2

And the corrected version (Fix A), run with the same test:

#include <stdio.h>

int main(void)
{
    int a, b, c, big;

    printf("Three numbers: ");
    scanf("%d %d %d", &a, &b, &c);

    if (a >= b && a >= c)
        big = a;
    else if (b >= c)
        big = b;
    else
        big = c;

    printf("\nLargest: %d\n", big);
    return 0;
}

Sample input: 9 9 2

Output:

Three numbers: 
Largest: 9

For bigger programs, a debugger lets you step through one line at a time and watch the variables change, which is a trace table produced by the computer. The Go further box links to a guide.

Try it 3Tracing and test data practice

Pick a mode. "Output" gives a short algorithm: trace it and type the output. "Test data" gives a validation rule and a value: say what kind of test data it is.

Summary

IdeaRemember
Correct algorithmMeets its objective for all valid data, handles invalid data, always terminates.
Dry runRunning an algorithm by hand.
Trace tableColumns for variables, conditions and output; a row for each change; latest value is the last one in the column.
Test dataNormal, boundary (extreme), erroneous; plus special cases such as equal values and no data.
Test planTest number, purpose, data, expected result, actual result, pass or fail. Expected results come from the objective.
CorrectingFind the line causing the failure, fix it, then re-run every test.

Review questions

1. What is a trace table, and why is it used?

Show answer

A table that records the value of each variable (and conditions and output) after each step of a dry run. It is used to work out the output of an algorithm and to find logic errors by comparing what happens with what should happen.

2. Distinguish between normal, boundary and erroneous test data, using the rule "a quantity must be from 1 to 20".

Show answer

Normal: valid typical data such as 7. Boundary: values at the edges, 1 and 20 (and 0 and 21 just outside). Erroneous: invalid data that should be rejected, such as -4, 35 or "ten".

3. Why must the expected results in a test plan be worked out from the problem statement and not by running the algorithm?

Show answer

Because the algorithm may be wrong. Expected results taken from the algorithm would always match its actual results, so no error could ever be found.

4. Trace and give the output: s ← 1; FOR k ← 1 TO 4 DO s ← s * 2 ENDFOR; OUTPUT s

Show answer

k = 1: s = 2; k = 2: s = 4; k = 3: s = 8; k = 4: s = 16. Output: 16.

5. Trace and give the output for the input values 4, 9, 0: INPUT n; t ← 0; WHILE n <> 0 DO t ← t + n; INPUT n ENDWHILE; OUTPUT t

Show answer

n = 4, t = 4; n = 9, t = 13; n = 0, condition False, stop. Output: 13.

6. An algorithm should count the marks of 40 or more in a list ending with -1. It uses IF mark > 40 THEN count ← count + 1. Give a test that shows the error and correct the line.

Show answer

Test with the data 40, -1: expected count 1, actual count 0. Correct the line to IF mark >= 40 THEN count ← count + 1.

7. State TWO things that an algorithm must do to be considered correct.

Show answer

Any two of: produce the expected output for all valid inputs (including boundaries); handle invalid input as required; terminate after a finite number of steps; achieve exactly the stated objective.

8. Explain why, after correcting an error, you should run all the tests again and not just the one that failed.

Show answer

A change can fix one case but break another (as Fix C did in Try it 2). Re-running every test shows the correction has not introduced new errors.

Homework

  1. Write a test plan of at least 8 tests for an algorithm that inputs a temperature and outputs "Cold" below 20, "Warm" from 20 to 30 and "Hot" above 30. Include every boundary.
  2. Dry run Worked example 2 with the inputs 51, 50, 49, 100 using a trace table. What is output?
  3. The REPEAT loop in Try it 1 halves x until it is less than 5. Change the starting value of x to 80, predict the output, and check by tracing.
  4. Type in max3.c, run it with each test from Try it 2, and complete the Actual and Pass/Fail columns yourself.
  5. Add printf trace lines to the sentinel average program from Lesson 08 and use them to show what goes wrong when the second scanf is removed.

Mastery quiz: Tracing Algorithms

This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

Mastery quiz: Tracing Algorithms: Trace Tables, Test Plans and Correctness

Your course badges: loading saved progress…

View badges

    No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

    Saved in this browser on this device. Clearing browser data may remove your badges.

    Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

    1. A dry run is...
    2. In a trace table, the columns usually represent...
    3. For the rule "age from 12 to 19", which value is boundary data?
    4. For the same rule, which value is erroneous data?
    5. Expected results in a test plan should be worked out from...
    6. s ← 0; FOR k ← 1 TO 3 DO s ← s + k * k ENDFOR. The final value of s is...
    7. x ← 20; WHILE x ≥ 5 DO x ← x − 6 ENDWHILE. The final value of x is...
    8. A "largest of three" algorithm fails only when two values are equal. This error was found using...
    9. A total is set to 0 inside a FOR loop. The likely symptom is...
    10. After correcting an error, you should...

    Exam tips

    Specimen Unit 1 Paper 02 (2021), Question 4(b). Completing a trace table for a given algorithm. Fill in each row in order, write only changed values, and make sure the final output appears in the Output column.

    CAPE 2024 Unit 1 Paper 02, Question 4(d). A trace table for a WHILE loop. Watch the boundary: test whether the condition is still True when the variable reaches the limit. A worked answer is linked in the Go further box.

    CAPE 2009 Unit 1 Paper 02, Question 3(c). Tracing a flowchart to find what it does wrong, then giving the correction. State the error, the line or symbol where it happens, and the corrected version.

    CAPE 2009 Unit 1 Paper 02, Question 4, Part B. A trace table with output. Label columns clearly and show every value, not only the final ones, because method marks are given for the rows.

    Specimen Unit 1 Paper 01 (2021), Item 24. Spotting the line of an algorithm that stops it meeting its objective. Dry run the algorithm with simple data and see where the values first go wrong.

    More worked answers are on the CS Solutions page.

    Previous: Module 2 • Lesson 08 – Loops: Bounded and Unbounded Iteration. Next: Module 2 • Lesson 10 – Developing Algorithms from Case Problems.

    Syllabus link: CAPE Computer Science (CXC A19/U2/21), Problem-Solving with Computers (Unit 1, Module 2). Specific Objective 7: interpret algorithms from case problems (determination of output and correctness of a given algorithm in narrative, flowcharts or pseudocode). Specific Objective 8: analyse algorithms from case problems for correctness (whether an algorithm achieves its stated objective and, if not, provision of the correct algorithm, using test plans and trace tables).

    Video search terms

    Search YouTube for: "trace table tutorial", "dry run algorithm", "normal boundary erroneous test data", "test plan example".

    Try it 4Quick quiz

    Tap an answer. All eight questions are self-checks on this lesson.

    Updates

    2026/12/01

    - Updated the copyright line.

    - Published. Previous/Next links and the mastery quiz links now use the full lesson addresses.

    - Small script tidy-up for the site (no change to how the activities work).

    2026/11/24

    - Linked Previous/Next and the mastery quiz URLs to draft shortlinks (?p=ID), which will redirect to the permalink after publish.

    - First version of the lesson.

    © 2026 islandclass.org

    Leave a Reply