AQA GCSE · Question 02.3 · Fundamentals of algorithms
In the algorithm in Figure 2, what is the largest possible value of the variable counter when the user input is 36?
Answer options:
A.
0
B.
2
C.
4
D.
5
How to approach this question
1. This is another trace question. Start with user input `a = 36`.
2. The `IF a > 0` is true.
3. `counter` is set to 0 (line 5).
4. The inner `WHILE a > 0` (line 6) starts.
- **Pass 1:** `a` is 36. `a ← 36 DIV 3` results in `a = 12`. `counter` becomes 1.
- **Pass 2:** `a` is 12. `a ← 12 DIV 3` results in `a = 4`. `counter` becomes 2.
- **Pass 3:** `a` is 4. `a ← 4 DIV 3` results in `a = 1`. `counter` becomes 3.
- **Pass 4:** `a` is 1. `a ← 1 DIV 3` results in `a = 0`. `counter` becomes 4.
5. The inner `WHILE` loop condition `a > 0` is now false, so it ends.
6. The largest value `counter` reached was 4.
Full Answer
C.4✓ Correct
The correct answer is C (4). The variable `counter` increments each time the inner loop runs. Tracing with an input of 36: `a` goes 36 -> 12 -> 4 -> 1 -> 0. The loop runs 4 times, so `counter` reaches a final value of 4.
This question requires tracing the value of the `counter` variable.
- **Input:** `a = 36`
- The condition `a > 0` is true.
- `counter` is initialized to 0.
- The inner `WHILE` loop begins.
- **Iteration 1:**
- `a` is 36. `a > 0` is true.
- `a = 36 DIV 3` = 12.
- `counter` = 0 + 1 = 1.
- **Iteration 2:**
- `a` is 12. `a > 0` is true.
- `a = 12 DIV 3` = 4.
- `counter` = 1 + 1 = 2.
- **Iteration 3:**
- `a` is 4. `a > 0` is true.
- `a = 4 DIV 3` = 1.
- `counter` = 2 + 1 = 3.
- **Iteration 4:**
- `a` is 1. `a > 0` is true.
- `a = 1 DIV 3` = 0.
- `counter` = 3 + 1 = 4.
- **End of loop:**
- `a` is now 0. The condition `a > 0` is false. The inner loop terminates.
The final and largest value of `counter` is 4.
Common mistakes
✗ Stopping the trace too early.\n✗ Making a mistake in the integer division, for example, calculating 4 DIV 3 as 1.33 instead of 1.