Use pseudocode to write: a 'pre-condition' loop

Published by Patrick Mutisya · 14 days ago

Cambridge A-Level Computer Science 9618 – Topic 11.2 Constructs: Pre‑condition Loops

Topic 11.2 – Constructs

Objective

Use pseudocode to write a pre‑condition loop (also known as a while loop) and understand its role in algorithm design.

What is a Pre‑condition Loop?

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.

Pseudocode Syntax

The standard pseudocode format used in the Cambridge syllabus is:

WHILE condition DO

statements

END WHILE

Key Characteristics

  • The loop condition is a pre‑condition – it must be true for the loop to start.
  • Potentially zero executions if the condition is false at the start.
  • Often used when the number of repetitions is not known in advance.

Example: Sum of Positive Numbers

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‑by‑Step Execution

StepConditionActionSum
1\$number \ge 0\$Enter loop0
2\$number \ge 0\$Add \$number\$ to sumUpdated
3Read next \$number\$Re‑evaluate condition
n\$number < 0\$Exit loopFinal sum

Common Pitfalls

  1. Forgetting to update a variable that influences the loop condition, leading to an infinite loop.
  2. Using the wrong relational operator (e.g., > instead of ).
  3. Assuming the loop will execute at least once – that is a post‑condition loop (REPEAT … UNTIL).

Comparison with Other Loop Types

Loop TypeCondition CheckGuaranteed Execution?Typical Use
Pre‑condition (WHILE)Before each iterationNoWhen the number of repetitions is unknown and may be zero.
Post‑condition (REPEAT … UNTIL)After each iterationYesWhen the loop must run at least once.
Counted (FOR)Based on a counterDepends on rangeWhen the exact number of repetitions is known.

Practice Exercise

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.

Solution Sketch

DECLARE input AS STRING

READ input

WHILE input ≠ "Cambridge" DO

OUTPUT "Incorrect, try again."

READ input

END WHILE

OUTPUT "Access granted."

Summary

  • A pre‑condition loop tests its condition before each iteration.
  • Syntax: WHILE … DO … END WHILE.
  • Useful when the loop may need to execute zero times.
  • Always ensure the loop condition will eventually become false.

Suggested diagram: Flowchart showing the WHILE loop decision node, body, and back‑edge to the condition.