Q.Let us answer the following questions using the pesudocode given in example 4.9:
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Tracing Example 4.9's sentinel loop on 6, 7, 4, 8, 2, 5, 0, …: the loop ends at 0, giving sum = 32 and count = 6; the two input statements form the priming-read pattern that keeps the sentinel out of the sum; sum/count is the average; and yes, count-first or list-based designs are alternative approaches.
The idea. Example 4.9 computes the average of numbers entered until the user types 0 (the sentinel). Its shape: initialise sum and count to 0; INPUT num once; WHILE num ≠ 0 → add num to sum, add 1 to count, INPUT num again; finally average = sum / count. Answering the five questions is a matter of dry-running that pseudocode on the given inputs.
Dry-run for inputs 6, 7, 4, 8, 2, 5, 0, 3, 1:
| num read | num = 0? | sum | count |
|---|---|---|---|
| 6 | No | 6 | 1 |
| 7 | No | 13 | 2 |
| 4 | No | 17 | 3 |
| 8 | No | 25 | 4 |
| 2 | No | 27 | 5 |
| 5 | No | 32 | 6 |
| 0 | Yes — loop ends | 32 | 6 |
The 3 and 1 typed after 0 are never read — the algorithm has already left the loop.
1) What will the sum be? 32 (= 6 + 7 + 4 + 8 + 2 + 5). The sentinel 0 adds nothing and stops the loop before 3 and 1.
2) Value of count? 6 — six numbers were processed before the sentinel.
3) Why input num twice? It is the priming read pattern. The first INPUT (before the loop) fetches a value so the WHILE condition has something to test on the very first pass; the second INPUT (at the bottom of the body) fetches the next value so it is tested before being processed. Together they guarantee the sentinel 0 is never added to sum or counted.
4) Why divide sum by count? sum holds the total of exactly count genuine numbers, and average is defined as total ÷ how-many. Dividing by a fixed number (like 5) would be wrong because the user decides how many numbers to enter.
5) Any other approach? Yes, several:
- Count-controlled: first ask "how many numbers?" (n), then loop exactly n times — no sentinel needed. …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.