CIE IGCSE | 7.8.1 Identify and Correct Algorithm Errors

Lesson objective

Identify algorithm errors using requirements and traces, explain their effects, propose precise corrections and select tests that check the fixes.

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 Total

Total is set to zero inside every repetition. The three totals become 4, 7 and 2, so the final output is 2 rather than 13.

The faulty reset discards earlier additions
InputFaulty Total after bodyCorrect cumulative Total
444
7711
2213

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 Total

Retest 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
ENDWHILE

The 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
ENDWHILE

Placing 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.

Correct maximum is -2
InputCandidate with first-input initialisationReason
-6-6Initial candidate
-2-2Greater than -6
-8-2Not 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"
ENDIF

If 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.

A precise correction linked to evidence
Part of responseWorked example
IdentifyTotal ← 0 is inside the repeated body.
ExplainIt resets the accumulated sum before every addition.
CorrectMove Total ← 0 before FOR.
CheckTrace 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.

MATCH THE FAULT TO ITS CORRECTION

Terminology

Terminology

Debugging

Finding and correcting the cause of an error.

Symptom

The observed incorrect behaviour, distinct from its underlying cause.

Logic error

Instructions or reasoning producing behaviour inconsistent with the intended task.

Syntax error

A violation of a notation or programming language’s rules.

Runtime error

An error arising during execution, such as division by zero.

Dry run

Following the given instructions by hand with chosen data.

Initialisation error

An absent, unsuitable or misplaced starting assignment.

Off-by-one error

An incorrect bound including or excluding one value or position.

Infinite loop

Repetition that cannot reach its intended exit under the current instructions.

Conditional update

An assignment that runs only when its condition permits it.

Temporary variable

Working storage preserving a value during an exchange.

Out-of-bounds access

Attempting to use an invalid array index.

Zero-count guard

Checking a count before using it as a divisor.

Correction

A precise change addressing the identified cause.

Retest

Running the originally failing case after a correction.

Regression testing

Checking previously working behaviour after changes.

Expected result

The outcome derived from requirements before testing.

Actual behaviour

What the supplied algorithm or tested implementation really does.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. What should a trace of a faulty algorithm show?
2. Total resets inside every iteration. Which fixes the accumulation?
3. A qualifying count adds Score. Which update counts occurrences?
4. Which acceptance rule includes both limits zero and fifty?
5. Which describe the missing-update WHILE fault?
6. What is the correct REPEAT UNTIL acceptance stopping rule?
7. Which are suitable maximum and mean corrections?
8. Which support a reliable correction?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Explain why resetting Total inside the loop gives only the last input.

2. State a precise correction to that reset error.

3. Explain why OR wrongly accepts five hundred under the zero-to-fifty rule.

4. Explain why the missing Count update causes endless repetition in the example.

5. Explain why a strict last-index bound misses the final linear-search element.

6. Explain why zero is an unsuitable maximum candidate for unrestricted negative data.

7. Explain how to correct a qualifying-average algorithm that divides by all inputs.

8. Describe how to check a correction.

REPAIR IT | AVERAGE OF POSITIVE INPUTS

The requirement is to average only positive values among three whole-number inputs and report no qualifying values when none is positive. Trace inputs two, minus one and four using the faulty algorithm below. Identify the wrong updates and divisor, state corrections and add the missing no-data handling.

DECLARE Value : INTEGER
DECLARE Total : INTEGER
DECLARE Count : INTEGER
DECLARE Index : INTEGER
DECLARE Average : REAL
Total ← 0
Count ← 0
FOR Index ← 1 TO 3
    INPUT Value
    IF Value > 0
      THEN
        Total ← Total + 1
        Count ← Count + Value
    ENDIF
NEXT Index
Average ← Total / 3
OUTPUT Average
Reveal a suggested correction

The faulty trace gives Total two, Count six and Average two divided by three. Correct the updates to Total ← Total + Value and Count ← Count + 1. After the loop, if Count > 0 calculate Average ← Total / Count and output it; otherwise output a no-positive-values message. For two, minus one and four, the corrected total is six, count two and mean three. Retest with zero, minus one and minus two to check the no-data path.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

    Selections are kept while this page is open.

    Workbook

    Workbook

    COMING SOON

    The workbook for 7.8.1 Identify and Correct Algorithm Errors is coming soon. Complete the matching task and written questions in your exercise book.