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

Published by Patrick Mutisya · 14 days ago

Cambridge A-Level Computer Science – 11.2 Constructs – Post‑condition Loop

Topic 11.2 – Constructs

Objective

Use pseudocode to write a post‑condition loop (repeat‑until loop).

Definition of a Post‑condition Loop

A post‑condition loop executes its body first and then evaluates the termination condition. Consequently the body is guaranteed to run at least once.

Pseudocode Syntax

REPEAT

  /* statements */

UNTIL condition

Key Characteristics

  • The condition is checked after the statements have been executed.
  • Commonly used when the initial state of the loop variable is not known in advance.
  • In Cambridge A‑Level specifications the loop is written as REPEAT … UNTIL.

Comparison with Pre‑condition Loops

AspectPre‑condition Loop (WHILE)Post‑condition Loop (REPEAT … UNTIL)
When is the condition evaluated?Before the first execution of the body.After each execution of the body.
Guarantee of at least one executionNo – body may never run.Yes – body runs at least once.
Typical syntaxWHILE condition DO … END WHILEREPEAT … UNTIL condition
Example condition\$i \le 10\$\$i > 10\$

Step‑by‑Step Construction of a Post‑condition Loop

  1. Identify the task that must be performed at least once.
  2. Write the statements that achieve the task inside the REPEAT block.
  3. Determine the condition that will end the loop.
  4. Place the condition after the UNTIL keyword.
  5. Verify that the condition will eventually become true to avoid an infinite loop.

Example: Summing the First n Positive Integers

Goal: Compute \$S = 1 + 2 + \dots + n\$ where \$n\$ is entered by the user.

Pseudocode using a post‑condition loop:

READ n

sum ← 0

i ← 1

REPEAT

  sum ← sum + i

  i ← i + 1

UNTIL i > n

OUTPUT sum

Why a Post‑condition Loop Works Here

  • The first addition must be performed even if n equals 0 (the loop still runs once, adding 0).
  • The termination condition i > n is checked after each addition, ensuring the loop stops exactly after the \$n^{\text{th}}\$ term has been added.

Suggested Diagram

Suggested diagram: Flowchart showing the flow of a REPEAT‑UNTIL loop – start → body → condition check → back to body if false, exit if true.