Use pseudocode to write: a 'count-controlled' loop

Topic 11.2 – Constructs (Cambridge AS & A‑Level Computer Science 9618)

Learning Objective

  • Write correct pseudocode for each of the five fundamental constructs required by the syllabus:

    • Selection: IF … THEN … ELSE … END IF and CASE … OF … END CASE
    • Repetition: FOR … TO … STEP … DO … END FOR, WHILE … DO … END WHILE, REPEAT … UNTIL … END REPEAT

  • Justify the most appropriate loop type for a given problem and link the choice to AO2/AO3 assessment objectives.

Overview of the Five Constructs

ConstructPurposePseudocode Syntax (Cambridge style)
IF‑statementExecute a block only when a condition is true; optionally provide an alternative block.

IF condition THEN

// statements

[ELSE

// statements]

END IF

CASE (SWITCH) statementSelect one of many alternatives based on the value of an expression.

CASE expression OF

value1: // statements

value2: // statements

OTHERWISE: // statements

END CASE

FOR‑loop (count‑controlled)Repeat a known number of times; the loop counter is initialised, tested and updated automatically.

FOR i ← start TO end [STEP step] DO

// loop body

END FOR

WHILE‑loop (pre‑condition)Repeat while a condition is true; the condition is tested before the first iteration.

WHILE condition DO

// loop body

// (update counter or other variables)

END WHILE

REPEAT‑UNTIL loop (post‑condition)Execute the body at least once and repeat until a condition becomes true; the condition is tested after each iteration.

REPEAT

// loop body

// (update counter or other variables)

UNTIL condition

1. Selection Constructs

1.1 Simple IF‑statement

Used when a single condition determines which block of code runs.

DECLARE mark : INTEGER

INPUT "Enter the mark (0‑100): ", mark

IF mark ≥ 70 THEN

OUTPUT "Grade: A"

ELSE IF mark ≥ 60 THEN

OUTPUT "Grade: B"

ELSE IF mark ≥ 50 THEN

OUTPUT "Grade: C"

ELSE

OUTPUT "Grade: F"

END IF

1.2 Nested IF‑statement

Often required when two or more conditions must be checked sequentially.

DECLARE age : INTEGER

DECLARE licence : CHARACTER

INPUT "Enter age: ", age

INPUT "Do you have a driving licence? (Y/N): ", licence

IF age ≥ 18 THEN

IF licence = 'Y' THEN

OUTPUT "You may drive."

ELSE

OUTPUT "You need a licence."

END IF

ELSE

OUTPUT "You are too young to drive."

END IF

1.3 CASE (SWITCH) statement

Best when a variable can take one of several discrete values. The OTHERWISE clause is optional.

DECLARE grade : CHARACTER

INPUT "Enter grade (A‑F): ", grade

CASE grade OF

'A': OUTPUT "Excellent"

'B': OUTPUT "Very good"

'C': OUTPUT "Good"

'D': OUTPUT "Satisfactory"

'F': OUTPUT "Fail"

OTHERWISE: OUTPUT "Invalid grade"

END CASE

2. Repetition Constructs

2.1 Count‑controlled loop – FOR

Use when the exact number of iterations is known before the loop starts.

Standard Form

FOR i ← start TO end [STEP step] DO

// loop body

END FOR

  • start – initial value of the loop counter.
  • end – final value (inclusive).
  • step – amount added each iteration (default = 1). Use STEP -1 for a decrementing loop.

Example 1 – Sum of the first 10 natural numbers (inclusive bounds)

DECLARE sum, i : INTEGER

sum ← 0

FOR i ← 1 TO 10 DO

sum ← sum + i

END FOR

OUTPUT "The sum is ", sum

Example 2 – Sum of even numbers between 2 and 20 (non‑unit step)

DECLARE sum, i : INTEGER

sum ← 0

FOR i ← 2 TO 20 STEP 2 DO

sum ← sum + i

END FOR

OUTPUT "Sum of evens = ", sum

Example 3 – Countdown from 10 to 1 (decrementing loop)

FOR i ← 10 TO 1 STEP -1 DO

OUTPUT i

END FOR

Note on wording

Some past papers use the phrase “count‑down” and write FOR i DOWNTO 1 DO. The Cambridge syntax is always FOR i ← … TO … STEP …; simply use a negative STEP to achieve the same effect.

Inclusive vs. Exclusive Bounds (Sidebar)

Inclusive boundFOR i ← 1 TO 5 runs with i = 1,2,3,4,5 (5 iterations).

Exclusive bound – If the requirement is “repeat *until* 5”, the correct loop is FOR i ← 1 TO 4. Adjust the end value or use a WHILE loop where the condition is i < 5.

2.2 Pre‑condition loop – WHILE

Use when the number of repetitions is not known in advance; the condition is checked before each iteration.

Example 1 – Sentinel‑controlled input (standard)

DECLARE total, number : INTEGER

total ← 0

INPUT "Enter a number (0 to stop): ", number

WHILE number ≠ 0 DO

total ← total + number

INPUT "Enter a number (0 to stop): ", number

END WHILE

OUTPUT "Total = ", total

Example 2 – Loop that may never execute (pre‑condition illustration)

DECLARE n : INTEGER

INPUT "Enter a positive integer: ", n

WHILE n < 0 DO // condition false initially → body skipped

OUTPUT "This will never be printed."

n ← n + 1

END WHILE

OUTPUT "Program continues."

2.3 Post‑condition loop – REPEAT … UNTIL

Guarantees that the body executes at least once; the condition is tested after the iteration.

Example 1 – Password length (already in notes)

DECLARE password : STRING

REPEAT

INPUT "Enter password (min 6 chars): ", password

UNTIL LENGTH(password) ≥ 6

OUTPUT "Password accepted"

Example 2 – Boundary‑check for a number between 1 and 100

DECLARE n : INTEGER

REPEAT

INPUT "Enter a number (1‑100): ", n

UNTIL n ≥ 1 AND n ≤ 100

OUTPUT "You entered ", n

3. Choosing the Right Loop – Justification & AO2/AO3 Links

SituationPreferred LoopJustification (AO2/AO3)
Exact number of repetitions known beforehandFORCounter is managed automatically; the algorithm’s time‑complexity is obvious (O(n)). Ideal for AO2 where the candidate must “design, write and trace” a solution.
Number of repetitions depends on input or a condition that may be false initiallyWHILECondition is evaluated before the first iteration, so the loop may execute zero times – a common trick in exam questions testing understanding of pre‑conditions (AO2). The loop’s termination condition must be justified to avoid infinite loops (AO3).
Loop must run at least once (e.g., menu display, password entry)REPEAT … UNTILPost‑condition guarantees one execution, matching specifications that require an initial prompt. Demonstrates control‑flow analysis (AO3) and clear algorithmic design.
Simple selection among many discrete optionsCASEMore readable than nested IFs; reduces cyclomatic complexity, which is a point of interest for AO3 (analysis of algorithm efficiency and readability).

Justification for the Practice Exercises

  1. Multiplication table for 7FOR is chosen because the number of rows (12) is known in advance. The loop clearly shows a linear O(12) time‑complexity and the counter i maps directly to the multiplier.
  2. Sentinel‑controlled inputWHILE is appropriate because the number of entries cannot be predicted; the loop must stop only when the sentinel value -1 appears. The pre‑condition ensures the body may be skipped if the first input is the sentinel, satisfying the “zero‑iteration” case.
  3. Password validatorREPEAT … UNTIL guarantees the user is prompted at least once, which is required for a password entry routine. The termination condition combines two Boolean checks, illustrating compound conditions and post‑condition logic.

4. Common Pitfalls & How to Avoid Them

  • Forgetting to update the counter – leads to infinite loops (especially with WHILE and REPEAT).
  • Wrong relational operator – using < instead of (or vice‑versa) causes off‑by‑one errors.
  • Incorrect STEP sign – a positive STEP with a decreasing range (or negative step with an increasing range) makes the loop never terminate.
  • Boundary confusion – remember that FOR i ← a TO b includes b. Adjust b if the specification says “up to but not including”.
  • Infinite REPEAT‑UNTIL – ensure the condition will eventually become true; usually by updating a variable inside the loop.
  • Using the wrong loop type for the specification – e.g., choosing FOR when the number of iterations depends on user input; examiners award marks for recognising the most suitable construct.

5. Practice Exercises

  1. Multiplication table for 7 (use a count‑controlled loop)

    Justification: The table always has 12 rows, so a FOR loop cleanly expresses the known iteration count.

    DECLARE i, product : INTEGER

    FOR i ← 1 TO 12 DO

    product ← 7 * i

    OUTPUT 7, " × ", i, " = ", product

    END FOR

  2. Sentinel‑controlled input: read integers until the user enters -1, then output the average

    Justification: The number of values is unknown; a WHILE loop stops only when the sentinel appears, handling the possible zero‑input case.

    DECLARE sum, count, n : INTEGER

    sum ← 0

    count ← 0

    INPUT "Enter a number (-1 to stop): ", n

    WHILE n ≠ -1 DO

    sum ← sum + n

    count ← count + 1

    INPUT "Enter a number (-1 to stop): ", n

    END WHILE

    IF count = 0 THEN

    OUTPUT "No numbers entered."

    ELSE

    OUTPUT "Average = ", sum / count

    END IF

  3. Password validator: prompt for a password until it contains at least one digit and one uppercase letter (use REPEAT‑UNTIL)

    Justification: The user must be asked at least once; the loop terminates only when both conditions are satisfied, making REPEAT … UNTIL the natural choice.

    DECLARE pwd : STRING

    FUNCTION hasDigit(s) RETURNS BOOLEAN

    RETURN (s CONTAINS "0" OR s CONTAINS "1" OR s CONTAINS "2"

    OR s CONTAINS "3" OR s CONTAINS "4" OR s CONTAINS "5"

    OR s CONTAINS "6" OR s CONTAINS "7" OR s CONTAINS "8"

    OR s CONTAINS "9")

    END FUNCTION

    FUNCTION hasUpper(s) RETURNS BOOLEAN

    RETURN (s CONTAINS "A" OR s CONTAINS "B" OR s CONTAINS "C"

    OR s CONTAINS "D" OR s CONTAINS "E" OR s CONTAINS "F"

    OR s CONTAINS "G" OR s CONTAINS "H" OR s CONTAINS "I"

    OR s CONTAINS "J" OR s CONTAINS "K" OR s CONTAINS "L"

    OR s CONTAINS "M" OR s CONTAINS "N" OR s CONTAINS "O"

    OR s CONTAINS "P" OR s CONTAINS "Q" OR s CONTAINS "R"

    OR s CONTAINS "S" OR s CONTAINS "T" OR s CONTAINS "U"

    OR s CONTAINS "V" OR s CONTAINS "W" OR s CONTAINS "X"

    OR s CONTAINS "Y" OR s CONTAINS "Z")

    END FUNCTION

    REPEAT

    INPUT "Enter password: ", pwd

    UNTIL hasDigit(pwd) AND hasUpper(pwd)

    OUTPUT "Password accepted"

6. Cross‑References

  • Section 11.3 – Procedures and Functions: see how loops can be placed inside sub‑programs and called repeatedly.
  • Section 10.4 – Abstract Data Types (ADTs): loops are essential for traversing arrays, lists, and other ADTs.
  • Section 12 – Algorithm Design & Analysis: consider loop complexity (e.g., O(n), O(n²)) and how choice of loop influences efficiency.

Key Take‑aways

  • Selection constructs (IF, CASE) direct program flow based on conditions.
  • Repetition constructs (FOR, WHILE, REPEAT‑UNTIL) implement loops; choose the one that matches the problem’s known/unknown iteration count and required first‑/last‑iteration behaviour.
  • Always initialise, test, and update loop variables correctly to avoid infinite loops and off‑by‑one errors.
  • Use STEP for non‑unit increments or decrements, and be mindful of inclusive vs. exclusive bounds.
  • Link each construct to AO2 (design, write, trace) and AO3 (analysis, justification) for full exam credit.