# Error Detection, Debugging & Algorithm Correction

- **Track:** Cambridge IGCSE™ Computer Science (0478 / 0984) (CAMBRIDGE IGCSE 0478)
- **Module:** Section 7: Algorithm Design & Problem-Solving
- **Estimated Duration:** 15 minutes
- **Access:** Open Theory (All-Access for Interactive IDE &amp; Autotests)

---

## Theory & Conceptual Background

A central objective of Cambridge IGCSE Paper 2 is assessing a student's ability to inspect algorithms, detect deliberate flaws, explain the nature of the error, and provide the exact corrected code.

---

## 1. The Three Error Classes

  
| Error Class | Definition & Timing | Primary Cause | Classic Exam Example |
| --- | --- | --- | --- |
| **Syntax Error** | A violation of the formal grammar, spelling, or punctuation rules of the language. Prevented or caught **before** execution by the translator. | Misspelled keywords, missing closing structures, illegal characters. | Misspelling `OUTPUT` as `OUPUT`, omitting `ENDIF`, using single `=` for assignment. |
| **Logic Error** | The program is syntactically valid and executes without crashing, but generates **incorrect results**. | Flawed algorithmic reasoning, wrong mathematical formulas, inverted conditions. | Writing `Area <- L + W` instead of `L * W`. Calculating `Average <- Total / 4` when 5 items were added. |
| **Runtime Error** | An illegal or impossible operation attempted while the program is actively running, causing an immediate **crash**. | Division by zero, accessing an array index outside allocated bounds. | `Average <- Total / Count` when `Count = 0`. Evaluating `Array[6]` on `ARRAY[1:5]`. |

---

## 2. Common Algorithm Bugs to Look For in Paper 2

1. **Incorrect Initialisation**:

- `Total` initialized inside the loop (resets every pass).
- `Min` initialized to `0` (locks minimum at 0 for positive numbers).
- `Max` initialized to `999` (locks maximum at 999).

1. **Off-by-One Loop Bounds**:

- Loops running `1 TO N - 1` when all $N$ items need processing.
- Loops running `1 TO N` during bubble sort comparisons, causing `Array[i + 1]` to access index $N + 1$ (Array Index Out of Bounds runtime crash).

1. **Loop Condition Inversion**:

- Using `<` instead of `>` or `<=` instead of `>=`.
- In `REPEAT ... UNTIL`, using the continuation condition instead of the termination condition.

1. **Sentinel Inclusion**:

- Reading sentinel values and adding them to the total before testing the condition.

## Written practice and self-review

Consider this flawed algorithm intended to calculate the sum of 10 input numbers:

```pseudocode
1  FOR Counter <- 1 TO 10
2      Total <- 0
3      INPUT Number
4      Total <- Total + Number
5  NEXT Counter
6  OUTPUT "Final Total: ", Total
```

1. Identify the line number containing the logic error and explain what problem it causes during execution.
2. State how to correct this error.

Write an explanation before checking the theory. Check that each claim answers the question, uses the correct concept and explains why it applies. Discuss uncertain points with a teacher. The structured exercise below checks specific facts; it does not automatically mark this explanation.

---

## Interactive Exercises & Autotest Specifications

### Exercise 1: Exam-Style Check: Classify Programming Error Types (Matching terms, 25 XP)

**Instructions:**
Match each programming error description to its error classification.


**Starter Code:**
```text
{"prompt":"Match each programming error example with its class:","left":[{"id":"err_syntax","text":"Typing OUPUT instead of OUTPUT"},{"id":"err_logic","text":"Writing Area <- Length + Width instead of Length * Width"},{"id":"err_runtime","text":"Dividing a sum by a counter when the counter equals 0"}],"right":[{"id":"cat_syntax","text":"Syntax error (violates language grammatical rules, caught before execution)"},{"id":"cat_logic","text":"Logic error (runs without crashing but produces incorrect calculation output)"},{"id":"cat_runtime","text":"Runtime error (causes unexpected program crash during execution)"}]}
```

**Autotest Expectations:**
- **Error classes correctly identified**: `match_pairs` -> Expected: `{&quot;err_syntax&quot;:&quot;cat_syntax&quot;,&quot;err_logic&quot;:&quot;cat_logic&quot;,&quot;err_runtime&quot;:&quot;cat_runtime&quot;}`

### Exercise 2: Application: Check the reasoning (Fill in blank, 30 XP)

**Instructions:**
Work out each answer before submitting. Wrong result from otherwise executable code: syntax or logic error? Does an inclusive 1 TO 5 loop run four or five times? Should a mean use the total divided by count or last value?


**Starter Code:**
```text
{"prompt":"Application: Check the reasoning","template":"1. Wrong result from otherwise executable code: syntax or logic error? [blank_1]\n2. Does an inclusive 1 TO 5 loop run four or five times? [blank_2]\n3. Should a mean use the total divided by count or last value? [blank_3]","blanks":[{"id":"blank_1"},{"id":"blank_2"},{"id":"blank_3"}],"word_bank":["logic","syntax","runtime","four","five","count","last value"]}
```


### Exercise 3: Independent Practice: Repair an average (Pseudocode, 30 XP)

**Instructions:**
Read five integer scores and output their mean rounded to two decimal places. The broken approach starts at item 0, stops before item 5 and divides by 4. Repair all three errors; your program must process exactly five scores.

Write a complete program. Read inputs in the stated order. Output only the requested results, one per line, without input prompts. Test with your own values before submitting.


**Starter Code:**
```text
DECLARE Scores : ARRAY[0:4] OF INTEGER
DECLARE i, Total : INTEGER
Total <- 0
FOR i <- 0 TO 4
    INPUT Scores[i]
    Total <- Total + Scores[i]
NEXT i
OUTPUT ROUND(Total / 4, 2)

```

**Autotest Expectations:**
- **Last item matters**: `test_case` -> Expected: `{&quot;inputs&quot;:[0,0,0,0,100],&quot;output&quot;:&quot;20&quot;}`
- **Fractional mean**: `test_case` -> Expected: `{&quot;inputs&quot;:[1,2,3,4,6],&quot;output&quot;:&quot;3.2&quot;}`
- **All zero**: `test_case` -> Expected: `{&quot;inputs&quot;:[0,0,0,0,0],&quot;output&quot;:&quot;0&quot;}`

