Learn
7.8.1 | IDENTIFY AND CORRECT ALGORITHM ERRORS
01 | AN ERROR IS SOMETHING YOU CAN EXPLAIN
A program is supposed to total three scores, but its output is only the final score. “The answer is wrong” identifies a symptom. To correct it, we need to find why the instructions produce that result.
Debugging means finding and correcting the cause of an error. A trace table helps by showing where the algorithm’s behaviour first differs from the requirement.
Start with the intended task, then follow the instructions actually provided. Do not silently fix them while tracing; the faulty behaviour is evidence.
This lesson uses small examples so every correction has a clear reason. You will practise identifying the faulty instruction, explaining its effect, stating a precise replacement and checking the corrected behaviour.
02 | UNDERSTAND THE KIND OF PROBLEM
A logic error occurs when the steps or reasoning produce unintended behaviour, even though the instructions may be valid. An incorrect comparison or misplaced initialisation can cause one.
A syntax error breaks the rules of a particular notation or programming language, such as a missing required closing keyword. In pseudocode, also distinguish a genuinely missing step from harmless presentation differences.
A runtime error occurs during execution, such as division by zero or invalid array access in an implementation. An algorithm design can create the situation that causes it.
Knowing the category helps, but naming it alone does not correct the problem. “Logic error” is less useful than “Total is reset inside the loop, so earlier additions are discarded.”
The syllabus asks students to identify errors and suggest corrections. Focus on the actual cause and the required behaviour.
03 | USE A REPEATABLE INVESTIGATION
First read the requirement. Identify what should be input, calculated, stored and output. Then choose a small test case whose expected result you can calculate independently.
Trace the given algorithm, recording assignments, conditions and outputs. Find the first relevant step where the state no longer supports the intended result.
Explain that cause before editing. Replace or move the smallest necessary set of instructions, then trace the corrected version.
Finally test contrasting cases. A fix that works on one input may still mishandle an endpoint, a missing target or zero accepted items.
This approach is more reliable than randomly changing operators until one output looks right.
04 | ERROR ONE: RESETTING A RUNNING TOTAL
The requirement is to add three whole-number scores and output their sum. Use inputs 4, 7 and 2.
// Faulty body; variables are declared INTEGER
FOR Index ← 1 TO 3
Total ← 0
INPUT Score
Total ← Total + Score
NEXT Index
OUTPUT TotalTotal is set to zero inside every repetition. The three totals become 4, 7 and 2, so the final output is 2 rather than 13.
| Input | Faulty Total after body | Correct cumulative Total |
|---|---|---|
| 4 | 4 | 4 |
| 7 | 7 | 11 |
| 2 | 2 | 13 |
The correction is to initialise Total once before the loop, so each addition retains the earlier scores.
Total ← 0
FOR Index ← 1 TO 3
INPUT Score
Total ← Total + Score
NEXT Index
OUTPUT TotalRetest with 4, 7 and 2. Also try 0, 3 and 0: the corrected result should be 3. A normal input set should distinguish a true total from a count or the last input.
05 | ERROR TWO: CONFUSING COUNTING WITH TOTALLING
The requirement is to count how many of five input scores are at least five. The update inside the qualifying branch is written as Count ← Count + Score.
For inputs 4, 5, 8, 2 and 5, this gives 18. That is the total of the qualifying scores, not their number.
// Faulty for counting qualifying scores Count ← Count + Score // Correct: one occurrence per qualifying input Count ← Count + 1
Each qualifying input represents one occurrence, so add one. The corrected count is 3.
If the task instead asked for the qualifying total, adding Score would be correct. An instruction is wrong relative to its requirement, not simply because it resembles a particular pattern.
Use data where total and count differ. Several qualifying inputs of one could conceal this mistake under a different threshold rule.
06 | ERROR THREE: WRONG RANGE LOGIC
A numeric mark must be from zero to fifty inclusive. The faulty condition is Mark >= 0 OR Mark <= 50.
Five hundred satisfies the first side and minus ten satisfies the second. OR needs only one true side, so both unwanted values pass.
// Faulty acceptance condition Accepted ← Mark >= 0 OR Mark <= 50 // Correct inclusive acceptance condition Accepted ← Mark >= 0 AND Mark <= 50
Acceptance requires both limits, so use AND. Alternatively, rejection can be tested with Mark < 0 OR Mark > 50, because either violation is enough.
Retest an interior value, both accepted endpoints and nearby rejected values: 34, 0, 50, −1 and 51. This also detects accidentally changing inclusive comparisons into strict ones.
The fragment assumes the mark is already numeric. Handling raw non-numeric text is a separate input concern.
07 | ERROR FOUR: A LOOP THAT CANNOT PROGRESS
The task is to output one, two and three. Count is initialised to one, and a WHILE loop tests Count ≤ 3, but it does not update Count.
Count ← 1
WHILE Count <= 3 DO
OUTPUT Count
ENDWHILEThe first check is true and outputs one. The next check still sees one, so it is true again. The state repeats and the loop does not reach its intended exit.
Add Count ← Count + 1 after output inside the body. The outputs become 1, 2 and 3. Count becomes 4 and the next check ends repetition.
Count ← 1
WHILE Count <= 3 DO
OUTPUT Count
Count ← Count + 1
ENDWHILEPlacing the increment before output would give 2, 3 and 4 under the same condition and initialisation. The fix needs the correct position as well as the correct instruction.
08 | ERROR FIVE: REVERSING A REPEAT STOPPING RULE
The task is to request a whole-number mark until it is between zero and fifty inclusive. The faulty final condition is UNTIL Mark < 0 OR Mark > 50.
REPEAT UNTIL stops when its condition is true. This faulty condition stops on an out-of-range value and repeats after a valid value, reversing the intended behaviour.
// Replace the faulty UNTIL line with: UNTIL Mark >= 0 AND Mark <= 50
Use the valid-range condition after UNTIL. With inputs 51 then 34, the first check is false and requests another value; the second is true and ends the retry.
This differs from a WHILE continuation condition. Read whether TRUE means continue or stop for the construct you are correcting.
09 | ERROR SIX: SKIPPING AN ARRAY ITEM
A linear search uses an array indexed from 1 to ItemCount. Position starts at one, but its loop condition uses Position < ItemCount.
The final valid index is never checked. In an array 14, 7, 22, a search for 22 would incorrectly finish without finding it.
// Faulty for indexes 1 to ItemCount WHILE Position < ItemCount AND NOT Found DO // Correct opening line for that indexing scheme WHILE Position <= ItemCount AND NOT Found DO
Use the inclusive bound because ItemCount is a valid index in this 1-based design. Keep the array access inside the body after the bounds test permits entry.
Retest first, middle and last matches plus an absent target. Fixing the last-item case should not allow an out-of-bounds access after all mismatches.
Do not apply this correction blindly to a zero-based array, whose final index may be ItemCount − 1. The indexing rule determines the correct bound.
10 | ERROR SEVEN: CHOOSING AN UNSUITABLE EXTREME CANDIDATE
A maximum-finding algorithm begins with Maximum ← 0 and compares three inputs with it. The inputs are −6, −2 and −8.
None is greater than zero, so it outputs zero. The true maximum is −2, and zero was not an input.
For a non-empty collection, initialise Maximum from the first actual value and compare the remaining values. The candidate will then always be drawn from the data seen so far.
| Input | Candidate with first-input initialisation | Reason |
|---|---|---|
| -6 | -6 | Initial candidate |
| -2 | -2 | Greater than -6 |
| -8 | -2 | Not greater than -2 |
Retest all-negative, mixed and all-equal values. For a variable-length collection, also define what happens if no values are supplied; do not pretend an empty set has a genuine maximum of zero.
11 | ERROR EIGHT: DIVIDING BY THE WRONG COUNT
The task is to average only scores at least five. With 4, 5, 8, 2 and 5, the qualifying total is 18 and the qualifying count is 3.
Dividing by all five inputs gives 3.6, which is not the mean of the qualifying set. Divide by the count of values included in the total.
IF QualifyingCount > 0
THEN
Average ← QualifyingTotal / QualifyingCount
OUTPUT Average
ELSE
OUTPUT "No qualifying scores"
ENDIFIf none qualifies, the count is zero. Add a check before division and report that no qualifying scores were supplied.
This correction involves both the divisor and the no-data path. A single ordinary qualifying case cannot demonstrate that the zero-count case is safe.
12 | DO NOT LOSE DATA WHEN SWAPPING
In bubble sort, a faulty swap copies the right value into the left position and then copies the new left value back into the right. Starting with 5 and 2, it produces 2 and 2.
The first instruction overwrote the original five. Use a temporary variable to preserve it before changing either position.
Temp ← Values[Index] Values[Index] ← Values[Index + 1] Values[Index + 1] ← Temp
Trace each assignment: Temp becomes 5, the left position becomes 2 and the right position becomes 5. Both original values survive.
A sorted-looking result is not sufficient if an item was lost or duplicated. Check contents and order after the correction.
13 | STATE THE ERROR, EFFECT AND CORRECTION
A useful answer has three connected parts: identify the faulty instruction or placement, explain the effect and give a precise correction.
| Part of response | Worked example |
|---|---|
| Identify | Total ← 0 is inside the repeated body. |
| Explain | It resets the accumulated sum before every addition. |
| Correct | Move Total ← 0 before FOR. |
| Check | Trace 4, 7 and 2; corrected output is 13. |
“The loop is wrong” does not identify a cause. “Move Total ← 0 before FOR” is a concrete change another reader can apply.
For an explain question, use cause-and-effect wording: “Total is reset on every pass, therefore earlier scores are discarded and only the last score remains.”
Keep a trace of the faulty version separate from the corrected version. Both help show why the change is justified.
14 | RETEST WITHOUT HIDING THE ORIGINAL FAILURE
After a correction, rerun the failing case from its stated starting conditions. Then rerun relevant previously working cases to check that the change has not introduced another fault.
Record the original failure and the corrected run separately. Do not change the expected answer merely to make the faulty version look successful.
If a correction changes a condition, check both sides of its decision and important equality cases. If it changes a loop, check progress, exit and any zero-repetition case that the requirements permit.
Passing the selected tests gives evidence for those cases, not proof of every possible behaviour. State what has been checked and what remains.
You should now be able to use traces as evidence, correct specific causes and explain why the repaired algorithm better meets its requirement. Next you will construct solutions from complete scenarios.