Teachers' Portal  /  IGCSE Computer Science 0478  /  Algorithm design and problem-solving  /  Finding and correcting errors in algorithms
Lesson pack · IGCSE Computer Science 0478 · 7 (7-9) · IGCSE

Finding and correcting errors in algorithms

Spot the bug. Exam papers often give you an algorithm that almost works, with a few lines wrong.

Student lesson Lab, full screen
At a glance

The shape of the lesson

Topic
Algorithm design and problem-solving
Syllabus reference
Cambridge IGCSE Computer Science 0478, 7 (7-9)
Level
IGCSE
Duration
45 minutes, lab-led; stretches to a 60 minute block (see the contingency notes)
Position in topic
Lesson 8 of 9 in Algorithm design and problem-solving; follows Dry-running algorithms with trace tables; leads into Writing and amending algorithms
Central model
Fig. 1: line 4 adds 1 instead of the number input, so the algorithm counts instead of totalling
Cooperative structure
Assessment
Stage 1 check and the exam-style plenary from the student lesson, plus the worksheet as the exit task
Learning objectives

By the end of the lesson, learners can

Section by section
  • Where errors hide: Try the find-the-error tab in the lab.
  • A worked example: This algorithm should input 10 positive numbers, then output the highest number and the average.
  • Errors that stop a loop: Some errors make a loop run the wrong number of times, or never stop.
Key points to leave on the board
  • Purpose: read what the algorithm is meant to do.
  • Dry run: use small, simple test data and compare actual with expected results.
  • Check the usual suspects: operators, initial values, loop bounds, inputs in loops, swaps, divisors.
  • Answer: the line number plus the full corrected statement.
The core visual model

One picture every idea returns to

To find errors, first work out the algorithm's intended purpose, then dry-run it with simple test data and compare the actual result with the expected result. Common errors are a wrong operator (< for >), counting instead of totalling, a wrong initial value or one set inside the loop, wrong loop bounds, a missing input inside a loop and a swap without a temporary variable. For each error give the line number and the corrected line of pseudocode.

Intended: output the total of 10 numbers 1 Total ← 0 2 FOR Count ← 1 TO 10 3 INPUT Number 4 Total ← Total + 1 5 NEXT Count 6 OUTPUT Total Total ← Total + Number line 4 counts instead of adding
Fig. 1: line 4 adds 1 instead of the number input, so the algorithm counts instead of totalling
Lesson sequence

Forty-five minutes, phase by phase

TimePhaseWhat happens in the roomGrouping
0 to 5 minHook: predictOpen with the question in the title, Spot the bug.. Exam papers often give you an algorithm that almost works, with a few lines wrong. Put the figure on the board: it is the one picture every idea in the lesson returns to.Whole class, then pairs
5 to 13 minTeach and check: Where errors hideTry the find-the-error tab in the lab. Project tab 4 of the lab (Find the error) and let a student drive it while the class predicts.Whole class, then pairs
13 to 21 minTeach and check: A worked exampleThis algorithm should input 10 positive numbers, then output the highest number and the average. Model the worked example Find and correct the errors on the board, one line at a time.Pairs
21 to 30 minTeach and check: Errors that stop a loopSome errors make a loop run the wrong number of times, or never stop. Your turn: Explain why this algorithm never stops if the first number is 5, and correct it.Jigsaw
30 to 36 minCheckThe four Stage 1 questions from the student lesson, answered on mini whiteboards or by show of fingers. Re-teach the one most get wrong.Individual, then whole class
36 to 43 minPlenaryThe exam-style questions from Stage 2, one at a time: thirty seconds alone, then a random call. The feedback lines in the key give the examiner's wording.Individual, random call
43 to 45 minExit and homeworkSet the worksheet below (6 questions, 16 marks). Learners self-assess against the objectives before they leave.Individual
Timing and contingency

Protect the parts that carry the learning

The sequence carries about fifty minutes of material, so the lab is driven by one student while the class predicts rather than explored freely. Times are a guide.

Protected: the check at 30 minutes. It is the only individual read on whether the key idea landed, and it is not cut.

Cut first if the build overruns: the last check in Errors that stop a loop, never the check or the plenary.

In a 60 minute block: run worksheet questions 1 to 3 in class as a Rally Coach set and model both the hardest worked example and its check live.

Running the cooperative task

Jigsaw

Split the content into expert pieces. Expert groups master one piece each, then regroup so every home team has one expert per piece, and each expert teaches their piece to the team.

The full structure, with its variations and the other twelve, is on the cooperative-learning page.

Examiner traps to pre-empt

What to head off, and how

Trap learners fall intoTeaching move that pre-empts it
"Line 5 is wrong" earns no mark on its own.Give the line number and the full corrected statement in pseudocode.
Do not rewrite the whole algorithm.Change only the faulty lines, and keep the original variable names.
A loop condition that uses a variable never changed inside the loop is a warning sign: either the loop never runs, or it never ends.Return to Errors that stop a loop: ask a pair to state the correct version and show it on the lab before moving on.
Worksheet

Finding and correcting errors in algorithms: worksheet

6 questions, 16 marks. Written in the style of the papers; no past paper question is reproduced.

NameClassDate
Q1 · analysis[4 marks]

This algorithm should input 5 prices and output the total and the number of prices over 20. Identify the two errors and write the corrected lines.

01 Total ← 0
02 Over ← 0
03 FOR Count ← 1 TO 5
04     INPUT Price
05     Total ← Price
06     IF Price > 20
07       THEN
08         Over ← Over + Price
09     ENDIF
10 NEXT Count
11 OUTPUT Total, " ", Over
Q2 · analysis[2 marks]

This algorithm should output the numbers 1 to 10. Identify the error and correct it.

Number ← 1
WHILE Number <= 10 DO
    OUTPUT Number
ENDWHILE
Q3 · analysis[3 marks]

This algorithm should find the largest of 8 temperatures, which can be from -30 to 40. Explain the error and give two different ways to correct it.

Largest ← 50
FOR Day ← 1 TO 8
    INPUT Temp
    IF Temp > Largest
      THEN
        Largest ← Temp
    ENDIF
NEXT Day
OUTPUT Largest
Q4 · analysis[2 marks]

This loop should run 12 times: FOR Month ← 1 TO 11. State the problem and correct the line.

Q5 · analysis[3 marks]

This should swap the values of A and B. A = 4 and B = 9 at the start. State the values after the code runs, explain the error and correct it.

A ← B
B ← A
Q6 · analysis[2 marks]

This validation should reject marks outside 0 to 100: UNTIL Mark >= 0 OR Mark <= 100. Explain why it accepts every number, and correct it.

Answer key and marking notes
Q1 · 4 marks
  • Line 05: the total is replaced, not added to.
  • Correct: Total ← Total + Price
  • Line 08: adds the price instead of counting.
  • Correct: Over ← Over + 1
Q2 · 2 marks
  • Number is never changed inside the loop, so it outputs 1 for ever (infinite loop).
  • Add Number ← Number + 1 inside the loop, after OUTPUT Number (before ENDWHILE).
Q3 · 3 marks
  • Largest starts at 50, higher than any possible temperature, so it is never replaced and 50 is always output.
  • Correction 1: Largest ← -30 (or any value lower than -30, e.g. -999).
  • Correction 2: input the first temperature and set Largest to it before the loop (loop over the other 7).
Q4 · 2 marks
  • It runs only 11 times, so one month is missed.
  • FOR Month ← 1 TO 12
Q5 · 3 marks
  • A = 9 and B = 9 after the code runs.
  • The original value of A is overwritten before it is copied to B.
  • Correct: Temp ← A; A ← B; B ← Temp.
Q6 · 2 marks
  • Every number is either at least 0 or at most 100, so the OR condition is always true and the loop always ends.
  • Correct: UNTIL Mark >= 0 AND Mark <= 100
Quiz

6 multiple-choice questions on this lesson

From the topic question bank. Assign them in the app for a marked score in your gradebook, or run the topic as a class game.

Q11 mark

This algorithm should output the total of 8 numbers. Which correction is needed?

01 Total ← 0
02 FOR Count ← 1 TO 8
03     INPUT Number
04     Total ← Number
05 NEXT Count
06 OUTPUT Total

  • ALine 04: Total ← Total + Number
  • BLine 01: Total ← Number
  • CLine 02: FOR Count ← 0 TO 8
  • DLine 04: Total ← Total + 1
Q21 mark

This algorithm should count how many of 6 numbers are negative, but line 04 is wrong. The inputs are -3, 4, -1, -8, 7, 0. What does it output, and what should it output?

01 Negative ← 0
02 FOR Count ← 1 TO 6
03     INPUT Number
04     IF Number > 0
05       THEN
06         Negative ← Negative + 1
07     ENDIF
08 NEXT Count
09 OUTPUT Negative

  • AIt outputs 2; it should output 3
  • BIt outputs 3; it should output 3
  • CIt outputs 3; it should output 2
  • DIt outputs 2; it should output 4
Q31 mark

This algorithm should output the square numbers 1, 4, 9, 16, 25 but never stops. Which change corrects it?

Count ← 1
WHILE Count <= 5 DO
    OUTPUT Count * Count
ENDWHILE

  • AAdd Count ← Count + 1 inside the loop
  • BChange the first line to Count ← 0
  • CChange the condition to Count < 5
  • DMove the OUTPUT to after ENDWHILE
Q41 mark

This algorithm should output the total of three numbers. The inputs are 4, 9, 6. What is actually output?

FOR Count ← 1 TO 3
    Total ← 0
    INPUT Number
    Total ← Total + Number
NEXT Count
OUTPUT Total

  • A6
  • B19
  • C0
  • D4
Q51 mark

Values[1:3] holds 6, 2, 5. One pass of a faulty bubble sort is run. What does the array hold afterwards?

FOR I ← 1 TO 2
    IF Values[I] > Values[I + 1]
      THEN
        Values[I] ← Values[I + 1]
        Values[I + 1] ← Values[I]
    ENDIF
NEXT I

  • A2, 2, 5
  • B2, 5, 6
  • C2, 6, 5
  • D6, 6, 5
Q61 mark

This validation should accept ages from 11 to 18 inclusive. What happens when it runs?

REPEAT
    OUTPUT "Enter your age (11 to 18)"
    INPUT Age
UNTIL Age < 11 AND Age > 18

  • AIt never ends, because no age is below 11 and above 18 at once
  • BIt ends for every age, because one of the two tests is always true
  • CIt works correctly, accepting only ages from 11 to 18
  • DIt ends only for ages outside 11 to 18, accepting invalid data
Quiz key
Q1: A

Line 04 replaces Total with each new number, so only the last number is output; it must add the number to the running total. Line 01 correctly initialises Total to 0 (Number has no value yet). Changing line 02 to 0 TO 8 would make the loop run 9 times. Total ← Total + 1 would count the numbers instead of totalling them.

Q2: A

The faulty test Number > 0 counts the positive numbers 4 and 7, so 2 is output. The negative numbers are -3, -1 and -8, so 3 should be output (line 04 should be IF Number < 0). 0 is neither positive nor negative, so it is not counted either way; counting it gives 4. The other options reverse or ignore the effect of the error.

Q3: A

Count is never changed inside the loop, so Count <= 5 stays true for ever. Adding Count ← Count + 1 inside the loop (after the OUTPUT) makes Count reach 6 and the loop end. Starting at 0 or using < 5 still leaves Count unchanged, so the loop still never ends. Moving the OUTPUT out of the loop would output nothing while the loop runs for ever.

Q4: A

Total is reset to 0 at the start of every pass, so after the last pass it holds only 0 + 6 = 6. The intended output, 19, needs Total ← 0 before the loop. 0 would be output only if the reset came after the addition. 4 is the first number, which is wiped out on the second pass.

Q5: A

I = 1: 6 > 2, so Values[1] becomes 2, then Values[2] is set to Values[1], which is now also 2: the 6 is lost, giving 2, 2, 5. I = 2: 2 > 5 is false. 2, 5, 6 is what a correct pass (with Temp) gives. 2, 6, 5 is a correct single swap with no second comparison. 6, 6, 5 assumes the copy overwrites the 2 instead of the 6.

Q6: A

Both parts of the AND can never be true together, so the UNTIL condition is always false and the loop keeps asking for ever, even for valid ages; the fix is UNTIL Age >= 11 AND Age <= 18. The "always true" behaviour belongs to an OR condition. It cannot work correctly because the loop never ends. Ending only for invalid ages would need UNTIL Age < 11 OR Age > 18.

Lab and demo

What to project

The student lesson embeds these tabs. Open them full screen on the projector; every slider has a drag handle on the stage.

Slides

Slides for this lesson

A projectable deck for every pack is on the way. Until then, present the student lesson full screen: its sections, figure and lab tabs follow the same order as the plan above.

Also for this topic

Everything else you can use

Original work by the TheLucidSTEM team. The worksheet items are written in the style of the papers; no past paper question is reproduced.
Previous lessonDry-running algorithms with trace tables