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?
- Hint 1: Could the computer tell that INPT is not a real instruction?
- Hint 2: Could the computer know that Zara wanted 20 and not 16?
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.
- Hint 1: Which faults could the computer notice without knowing what the program is for?
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
ENDIFor a loop with noNEXT. 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
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
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: ", TotalThink 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?
- Hint 1: How many times does FOR Round ← 1 TO 4 go round?
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:
| Round | Score typed | Total after the round |
|---|---|---|
| 1 | 3 | 3 |
| 2 | 5 | |
| 3 | 2 | |
| 4 | 6 |
Show the completed table
| Round | Score typed | Total after the round |
|---|---|---|
| 1 | 3 | 3 |
| 2 | 5 | 8 |
| 3 | 2 | 10 |
| 4 | 6 | 16 |
The fifth score, 4, is never read. The program outputs Total: 16, not 20.
- 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.
- Run the program on the same data, with a trace table. The table above shows the total reaching 16.
- 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.
- 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. - 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
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: ", PriceThink 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?
- Hint 1: Is 12 under 12?
- Hint 2: Is 12 <= 12 true?
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.
| Age typed | Expected price | Price the program gives | Same? |
|---|---|---|---|
| 11 | 4 | 4 | Yes |
| 12 | 8 | ||
| 13 | 8 |
Show the completed table
| Age typed | Expected price | Price the program gives | Same? |
|---|---|---|---|
| 11 | 4 | 4 | Yes |
| 12 | 8 | 4 | No |
| 13 | 8 | 8 | Yes |
The fault shows only at the limit: the program treats 12 as a child.
Apply it
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: ", HighestThink it through
What is the highest of the three temperatures? Predict what the program outputs, and say which line you think causes it.
- Hint 1: Is -3 greater than 0?
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.
| Day | Temperature typed | Is it > Highest? | Highest after the day |
|---|---|---|---|
| Start | 0 | ||
| 1 | -3 | ||
| 2 | -8 | ||
| 3 | -1 |
Show the completed table
| Day | Temperature typed | Is it > Highest? | Highest after the day |
|---|---|---|---|
| Start | 0 | ||
| 1 | -3 | No | 0 |
| 2 | -8 | No | 0 |
| 3 | -1 | No | 0 |
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
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: ", TotalThink it through
Predict what the program outputs for 4, 6 and 0. Then say which one line is wrong, and what it should say.
- Hint 1: After the first INPUT, Number holds 4. Is Number = 0 true?
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
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 cThink 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.
- Hint 1: What do a, b and c stand for?
- Hint 2: How would you spot which numbers are the group size and the discount?
- Hint 3: Does the layout show where the IF starts and ends?
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, nota,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
IFor 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
CONSTANTwith 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
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.
Work this out on paper or the board first. Nothing here is marked: compare yours with the model answer.
- Hint 1: Choose names for a, b and c first.
- Hint 2: Which two numbers are rules that might change?
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: ", CostFor 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
ENDFUNCTIONApply it
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: ", AverageThink 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.
Work this out on paper or the board first. Nothing here is marked: compare yours with the model answer.
- Hint 1: How many times does FOR Count ← 1 TO 3 go round?
- Hint 2: Compare the number of passes with the number the division uses.
Show a model answer
| Count | Mark typed | Total after |
|---|---|---|
| 1 | 10 | 10 |
| 2 | 12 | 22 |
| 3 | 8 | 30 |
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
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
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).
A sequence of precise steps that solves a problem or completes a task.
A line in a program that the computer ignores and that explains the purpose of the code to the people who read it. In Cambridge pseudocode it starts with //.
A named value that is set once and does not change while the program runs.
A subroutine that works out one value and returns it, to be used in an expression. It is defined with FUNCTION … RETURNS … ENDFUNCTION and ends with RETURN.
The name a programmer gives to a variable, constant, array, procedure or function.
A mistake in the design of a program that lets it run but gives wrong results, such as writing > where >= was needed.
A program written so that other people, or its writer at a later date, can understand it, correct it and change it easily.
A loop that tests its condition before each repeat, so its instructions may run zero times. In pseudocode it is a WHILE … ENDWHILE loop.
A subroutine that carries out a task and does not return a value. It is defined with PROCEDURE … ENDPROCEDURE and used with CALL.
A precise but language-independent way of writing an algorithm, with set keywords such as IF, WHILE and OUTPUT, that is not tied to any one programming language.
A high-level programming language written as text, popular for learning and for real work, in which indentation shows which lines belong together.
A mistake in the rules of the programming language, such as a missing ENDIF or a misspelt keyword, which stops the program from running.
A setting that changes how adventurous a model’s choice of the next token is: low means it nearly always picks the most likely token, high spreads its choices.
Values chosen to test a program, with the correct result for each worked out before the test is run.
A table used to follow an algorithm by hand, with a column for each variable and for the output and a row for each step, to record how the values change.
Your progress on this lesson
Saved in this browser only. It is not sent anywhere, does not follow you to another device, and is lost if you clear this site’s data.
This browser is not allowing the site to save progress, so it will be forgotten when you leave the page.