Published by Patrick Mutisya · 14 days ago
Use pseudocode to write a pre‑condition loop (also known as a while loop) and understand its role in algorithm design.
A pre‑condition loop repeats a block of statements while a given condition is true. The condition is evaluated before each iteration, so if the condition is false initially, the loop body may never execute.
The standard pseudocode format used in the Cambridge syllabus is:
WHILE condition DO
statements
END WHILE
Read a sequence of integers from the user until a negative number is entered, then output the sum of the positive numbers entered.
DECLARE sum, number AS INTEGER
SET sum ← 0
READ number
WHILE number ≥ 0 DO
SET sum ← sum + number
READ number
END WHILE
OUTPUT "Sum =", sum
| Step | Condition | Action | Sum |
|---|---|---|---|
| 1 | \$number \ge 0\$ | Enter loop | 0 |
| 2 | \$number \ge 0\$ | Add \$number\$ to sum | Updated |
| 3 | Read next \$number\$ | Re‑evaluate condition | — |
| … | … | … | … |
| n | \$number < 0\$ | Exit loop | Final sum |
> instead of ≥).REPEAT … UNTIL).| Loop Type | Condition Check | Guaranteed Execution? | Typical Use |
|---|---|---|---|
Pre‑condition (WHILE) | Before each iteration | No | When the number of repetitions is unknown and may be zero. |
Post‑condition (REPEAT … UNTIL) | After each iteration | Yes | When the loop must run at least once. |
Counted (FOR) | Based on a counter | Depends on range | When the exact number of repetitions is known. |
Write pseudocode for a program that asks the user for a password and keeps prompting until the correct password "Cambridge" is entered. Use a pre‑condition loop.
DECLARE input AS STRING
READ input
WHILE input ≠ "Cambridge" DO
OUTPUT "Incorrect, try again."
READ input
END WHILE
OUTPUT "Access granted."
WHILE … DO … END WHILE.