Study Guide

Finding and Fixing Errors

How to find what is wrong with a program that does not work: syntax errors and logic errors, tracing a faulty algorithm to the line where it goes wrong, the usual culprits (off-by-one, wrong operator, wrong starting value, wrong loop condition), and how to write programs that other people can maintain.

Lesson 5.14 Algorithms and Programming

For: Cambridge IGCSE Computer Science learners, or Key Stage 3 learners who can write loops, selection and trace tables (about ages 13 to 14)

Stage: Think

Two problems, two kinds of message

Zara (a fictional pupil) writes a program to add up the scores of a five-round quiz. The first time she runs it, the computer refuses to start and points at line 3, where she has typed INPT instead of INPUT. She fixes that. The program now runs, but when she types the scores 3, 5, 2, 6 and 4, it outputs 16. The scores add up to 20.

Think it through

The computer told Zara about the first problem but said nothing about the second. Why do you think that was? How could Zara find the second problem herself?

Show a model answer

INPT is not an instruction the language knows, so the computer can see straight away that the line breaks its rules. The second problem follows every rule: the program does exactly what its lines say, just not what Zara meant. The computer does not know she wanted 20. Zara has to find it herself, by working through the program with the same scores and comparing what happens with what she intended, which is what a trace table is for.

Stage: Discover

Breaking the rules, and following them wrongly

Think it through

Sort these four faults into two groups, with a reason for the grouping: (1) the keyword ENDIF is spelt ENDFI; (2) a program for the area of a rectangle adds the length and the width instead of multiplying; (3) a FOR loop has no NEXT; (4) a loop that should run 10 times runs 9.

Show a model answer

Faults 1 and 3 go in one group: they break the rules of the language, and the computer can notice them without knowing what the program is for. Faults 2 and 4 go in the other: every line is allowed, but the program does the wrong thing, and only someone who knows the purpose can tell.

The two groups have names:

  • A syntax error is a mistake in the rules of the programming language, such as a misspelt keyword, a missing ENDIF or a loop with no NEXT. The program will not run, and the computer normally reports the line.
  • A logic error is a mistake in the design of the program. It follows the rules, so it runs, but it gives wrong results: adding where it should multiply, or running a loop one time too few.

Do not confuse: Syntax error and logic error

What is wrong?Syntax error
The program breaks the rules of the language, so it cannot run.ENDFI instead of ENDIF
What is wrong?Logic error
The program follows the rules but does the wrong thing, so its results are wrong.Area ← Length + Width

The computer finds syntax errors for you. Only a person who knows what the program should do can find a logic error, by comparing the results with the ones expected.

Check your understanding

A program has the line FOR Round ← 1 TO 4 but no matching NEXT Round. What kind of error is this?
Show the answer

Answer: A. A syntax error, because the loop breaks the rules of the language.

A program that cannot run because of a broken rule has a syntax error.

Check your understanding

A program for the area of a rectangle contains Area ← Length + Width. It runs, and outputs 11 for a 3 by 8 rectangle. What kind of error is this?
Show the answer

Answer: C. A logic error, because it runs but uses the wrong operation.

A program that runs and gives a wrong result has a logic error.

Stage: Predict

Following a program to where it goes wrong

Here is Zara’s program after she mended INPT. It should total the five scores of the quiz.

Total ← 0
FOR Round ← 1 TO 4
  INPUT Score
  Total ← Total + Score
NEXT Round
OUTPUT "Total: ", Total

Think it through

Without running it, work out how many scores the loop reads. Which score does Zara’s program never use, and what does it output for the scores 3, 5, 2, 6 and 4?

Show a model answer

The loop goes round 4 times, so it reads only the first four scores and the fifth, 4, is never read. It outputs 3 + 5 + 2 + 6 = 16, but the total of all five is 20.

A trace table follows the program step by step:

Following Zara’s program with the scores 3, 5, 2, 6, 4
RoundScore typedTotal after the round
133
25
32
46

    Show the completed table
    RoundScore typedTotal after the round
    133
    258
    3210
    4616

    The fifth score, 4, is never read. The program outputs Total: 16, not 20.

    1. Say what the program should do, and work out the result by hand. It should total five scores: 3 + 5 + 2 + 6 + 4 = 20. Doing this first gives something to compare with.
    2. Run the program on the same data, with a trace table. The table above shows the total reaching 16.
    3. Find where the program stops matching the plan. Each row is right for its own pass, so the fault is not in the adding. The plan has five scores but the table has only four rows: the loop ends too soon.
    4. Name the fault and correct it. The loop’s upper limit is 4 and should be 5. This kind of logic error, where a loop goes round one time too many or too few, is called an off-by-one error. The correction is FOR Round ← 1 TO 5.
    5. Run it again. With the same data the total is now 20. Test any other case that might also fail, such as a different number of scores.

    Check your understanding

    Which change corrects Zara’s program?
    Show the answer

    Answer: B. Change the loop to FOR Round ← 1 TO 5.

    The number of passes of FOR a TO b is b − a + 1.

    Stage: Explain

    One symbol out

    The Riverside Cinema (a fictional cinema) charges £4 for children under 12 and £8 for everyone aged 12 or over. This program is meant to give the price for any age.

    INPUT Age
    IF Age <= 12
      THEN
        Price ← 4
      ELSE
        Price ← 8
    ENDIF
    OUTPUT "Ticket price: ", Price

    Think it through

    Work out the expected price for the ages 11, 12 and 13 from the cinema’s rule, and then the price the program gives. For which age do they differ?

    Show a model answer

    Expected: 11 pays £4, 12 pays £8, 13 pays £8. The program: 11 gives 4, 12 gives 4 (because 12 <= 12 is true) and 13 gives 8. The ages differ only for 12, the age exactly on the limit.

    Testing the cinema program with the ages 11, 12 and 13
    Age typedExpected pricePrice the program givesSame?
    1144Yes
    128
    138

      Show the completed table
      Age typedExpected pricePrice the program givesSame?
      1144Yes
      1284No
      1388Yes

      The fault shows only at the limit: the program treats 12 as a child.

      Apply it

      Which correction makes the program match the rule “children under 12 pay £4”?
      Show the answer

      Answer: D. Change <= to <, giving IF Age < 12

      A wrong comparison (< for <=, or > for >=) is the most common logic error in selection. Boundary test data (Lesson 13) finds it.

      Stage: Predict

      Where a program starts from

      A fictional weather station in a cold winter records the temperature at noon on three days: -3, -8 and -1 degrees. This program should output the highest.

      Highest ← 0
      FOR Day ← 1 TO 3
        INPUT Temperature
        IF Temperature > Highest
          THEN
            Highest ← Temperature
        ENDIF
      NEXT Day
      OUTPUT "Highest: ", Highest

      Think it through

      What is the highest of the three temperatures? Predict what the program outputs, and say which line you think causes it.

      Show a model answer

      The highest temperature is -1. The program outputs 0: none of the readings is greater than the starting value of 0, so Highest is never replaced. The line Highest ← 0 is the cause.

      Following the highest-temperature program
      DayTemperature typedIs it > Highest?Highest after the day
      Start0
      1-3
      2-8
      3-1

        Show the completed table
        DayTemperature typedIs it > Highest?Highest after the day
        Start0
        1-3No0
        2-8No0
        3-1No0

        A variable’s value before the loop matters as much as what happens inside it. Two errors come from this. A starting value that is not in the data (here 0) can never be beaten. And a total with no starting line at all, such as a missing Total ← 0, starts with whatever the variable already held: in some languages the program stops with an error, and in others it uses a leftover value, so the answer is wrong. In a trace table, write ? for such a value to show that nothing sensible is there.

        Check your understanding

        Which correction makes the program give the right answer for any temperatures, including negative ones?
        Show the answer

        Answer: C. Start Highest with the first temperature typed, then loop from Day 2.

        The starting value of a highest (or lowest) must come from the data, or be beyond anything the data can be.

        Stage: Predict

        A loop that never starts

        This program should add up numbers until the number 0 is typed. The user types 4, then 6, then 0, so the total should be 10.

        Total ← 0
        INPUT Number
        WHILE Number = 0 DO
          Total ← Total + Number
          INPUT Number
        ENDWHILE
        OUTPUT "Total: ", Total

        Think it through

        Predict what the program outputs for 4, 6 and 0. Then say which one line is wrong, and what it should say.

        Show a model answer

        It outputs Total: 0. After the first INPUT, Number is 4, so Number = 0 is false and the loop body never runs. The WHILE line should keep the loop going while the number is not 0: WHILE Number <> 0 DO.

        A WHILE loop runs while its condition is true, and a REPEAT … UNTIL loop runs until its condition becomes true. Writing the condition the wrong way round, or choosing the wrong comparison, gives a loop that never starts or never stops.

        Apply it

        Which correction makes the program output 10 for the numbers 4, 6 and 0?
        Show the answer

        Answer: A. Change the line to WHILE Number <> 0 DO

        Say in words when the loop should carry on, and write that as the condition.

        Stage: Think

        A program nobody can change

        A colleague has left the school. Their program works out the price of a school trip, with a discount for large groups. It works, but it has been written badly on purpose, to show what to avoid.

        INPUT a
        INPUT b
        IF a > 30 THEN
        c ← a * b - a * b * 0.1
        ELSE
        c ← a * b
        ENDIF
        OUTPUT c

        Think it through

        Tomorrow the group size for the discount changes from 30 to 40, and the discount from 10% to 15%. List everything that makes this program hard to read and to change.

        Show a model answer

        The names a, b and c say nothing about what they hold. There is no note of what the program is for. The numbers 30 and 0.1 appear without any hint that they are a group size and a discount, so they are easy to miss or to change wrongly. Nothing is indented, so the structure of the IF is hard to see. The multiplication a * b is written twice, so a change might be made in one place and forgotten in the other.

        A program written so that other people, or its writer at a later date, can understand it, correct it and change it easily is a maintainable program. Four habits make it so:

        • Meaningful identifiers. An identifier is the name of a variable, constant, array, procedure or function. A name should say what it holds or does: Pupils, PricePerPupil, DiscountRate, not a, b, c.
        • Comments. A comment is a line the computer ignores, written for the reader; in Cambridge pseudocode it starts with //. A good one says what a section is for, or why something is done.
        • Indentation. Lines inside an IF or a loop are moved in, so the structure can be seen at a glance.
        • Constants and subroutines. A value that is used by rules (the group size, the discount) is declared as a CONSTANT with a name, in one place. A task that can be separated or repeated goes into a procedure or function.

        A comment that only repeats the code, such as // add 1 to Passes beside Passes ← Passes + 1, adds nothing: the reader can see that. A useful comment gives what the code cannot say by itself, such as why the line exists.

        Check your understanding

        Which comment is most useful above the line Passes ← Passes + 1 in a program that counts pupils who pass?
        Show the answer

        Answer: D. // Another pupil has reached the pass mark of 50

        A good comment tells the reader what the code cannot show.

        Stage: Apply

        Improve it yourself

        Think it through

        Rewrite the trip program so that it is easy to maintain. Use meaningful identifiers, constants for the group size and the discount, a comment saying what the program does, indentation and a clear output message.

        Show a model answer
        // Works out the cost of a school trip, with a discount for large groups
        CONSTANT GroupSize ← 30
        CONSTANT DiscountRate ← 0.1
        DECLARE Pupils : INTEGER
        DECLARE PricePerPupil : REAL
        DECLARE Cost : REAL
        INPUT Pupils
        INPUT PricePerPupil
        Cost ← Pupils * PricePerPupil
        IF Pupils > GroupSize
          THEN
            // Groups larger than the limit pay less
            Cost ← Cost - Cost * DiscountRate
        ENDIF
        OUTPUT "Total cost: ", Cost

        For 40 pupils at 12 each, both versions give 40 × 12 = 480, then 480 − 48 = 432. For 30 pupils at 12 each, both give 360, because 30 > 30 is false. The two numbers that might change are now declared once, with names.

        If the cost is also needed elsewhere in a larger program, the calculation can be moved into a function, so that it is written once and given a name:

        FUNCTION TripCost(Pupils : INTEGER, PricePerPupil : REAL) RETURNS REAL
          DECLARE Cost : REAL
          Cost ← Pupils * PricePerPupil
          IF Pupils > GroupSize
            THEN
              Cost ← Cost - Cost * DiscountRate
          ENDIF
          RETURN Cost
        ENDFUNCTION

        Apply it

        With the improved version, the group size becomes 40 and the discount 15%. How many places in the program need to change?
        Show the answer

        Answer: B. Two: the value of each constant, at the top.

        A named constant puts a rule in one place.

        Go deeper The same ideas in Python
        GROUP_SIZE = 30
        DISCOUNT_RATE = 0.1
        
        def trip_cost(pupils, price_per_pupil):
            """Cost of a trip, with a discount for large groups."""
            cost = pupils * price_per_pupil
            if pupils > GROUP_SIZE:
                cost = cost - cost * DISCOUNT_RATE
            return cost
        
        print(trip_cost(40, 12))
        print(trip_cost(30, 12))

        This prints 432.0 and then 360. Python programmers usually write names in lower case with underscores, and constants in capitals, so the style differs, but the principle is the same: a name that says what a value is. The text in triple quotes is a docstring, Python’s way of describing a function.

        Python also reports the three kinds of error differently. A SyntaxError (such as print("Total:" total), which is missing a comma) stops the program before it starts. A logic error gives no message at all. A third kind, a run-time error, stops a program part-way through when something impossible happens: 10 / count when count is 0 raises a ZeroDivisionError, saying that division by zero is not allowed. The averaging methods in Lesson 6 guard against it with IF Count > 0.

        Stage: Apply

        Find the fault and fix it

        A teacher’s program should output the average of four marks. She tests it with the marks 10, 12, 8 and 14, which should give 11.

        // Average of four marks
        Total ← 0
        FOR Count ← 1 TO 3
          INPUT Mark
          Total ← Total + Mark
        NEXT Count
        Average ← Total / 4
        OUTPUT "Average: ", Average

        Think it through

        Complete a trace table for the marks 10, 12, 8 and 14, say what the program outputs, name the kind of error and write the corrected line.

        Show a model answer
        CountMark typedTotal after
        11010
        21222
        3830

        The loop ends after Count 3, so the fourth mark (14) is never read. The program outputs Average: 7.5, because 30 / 4 = 7.5. It is a logic error, an off-by-one error in the loop. The corrected line is FOR Count ← 1 TO 4, which gives a total of 44 and an average of 44 / 4 = 11.

        Apply it

        Sam’s program counts the marks of 50 or more among 62, 45, 50, 38 and 71. It uses IF Mark > 50 and outputs 2. The correct count is 3. What kind of error is it, and what is the fix?
        Show the answer

        Answer: C. A logic error in the comparison, fixed by writing Mark >= 50.

        Check the value on the limit, and read what the specification says: “50 or more”.

        Stage: Consolidate

        Show what you know

        Think it through

        Explain to a friend how you would find the fault in a program that runs but gives the wrong answer. Include what you would work out first, what you would do with it, and how you would know you had fixed it.

        Show a model answer

        A good answer works out the correct result by hand first (from what the program is meant to do), then runs the program on the same data with a trace table, finds the first row where the table stops matching the plan, names the kind of fault (such as off-by-one, a wrong comparison, a wrong starting value or a wrong loop condition) and changes that line. It then runs the program again on the same data, plus data at the limits, to check that the fix works and nothing else has broken.

        Apply it

        A program uses the names X, Y and Z for the length, width and area of a room, and has no comments. Which single change makes it most maintainable?
        Show the answer

        Answer: B. Rename them Length, Width and Area, and add a comment about the program.

        Meaningful names and a comment help every later reader.

        • A syntax error breaks the rules of the language, so the program will not run. A logic error follows the rules but gives wrong results.
        • To find a logic error: work out the expected result by hand, trace the program on the same data, find the first row where it goes wrong, name the fault and fix it, then test again.
        • Common faults: off-by-one loop limits, a wrong comparison (< for <=), a wrong starting value (or a missing one), and a loop condition the wrong way round.
        • A maintainable program has meaningful identifiers, useful comments, indentation, named constants, and procedures or functions.

        Sources and scope

        • What this lesson is. The fourteenth lesson of the Algorithms and Programming module, written for this site. It covers points 7.8 (identifying errors in algorithms and suggesting corrections) and 8.1.8 (maintainable programs) of Cambridge IGCSE Computer Science 0478 (2026 to 2028, version 6). Its curriculum links are provisional and imply no review or endorsement by any examination board.
        • Original material. Zara, Sam, the quiz, the Riverside Cinema, the weather station, the trip program and the teacher’s marks are fictional, written for this lesson. The deliberately badly written program is invented to show habits to avoid. The pseudocode follows the layout in the syllabus’s pseudocode guide, and each trace and output was worked out by hand.
        • Simplified on purpose. Run-time errors are mentioned briefly in the Python box and are not examined at IGCSE. The common faults are taught through a small set of programs, not as a complete list.
        • Left to other lessons. Choosing test data (Lesson 13) and writing a whole program for a scenario (Lesson 16).