A-Level Computer Science / Unit 11: Structured Programming

11.2.5 Choosing and Combining Control Structures

πŸ”’ Lesson slides are available to signed-in users. Sign in

11.2.5 Choosing and Combining Control Structures

Most useful algorithms contain more than one control structure. A solution might validate an input with a post-condition loop, process a fixed number of records with a count-controlled loop and use selection to classify each record.

Choosing a structure is not simply a matter of personal preference. The structure should match the way the problem is controlled and should make the algorithm correct, clear and straightforward to trace.

By the end of this section, you should be able to:

  • Distinguish sequence, selection and repetition.
  • Choose between IF and CASE.
  • Choose between FOR, WHILE and REPEAT...UNTIL.
  • Justify a loop choice using the problem’s requirements.
  • Place selection inside repetition.
  • Place repetition inside a selection branch.
  • Write and trace nested loops.
  • Combine validation, processing, accumulation and classification.
  • Identify which structure controls each block of statements.
  • Reduce unnecessary nesting and repeated processing.
  • Check that every loop can reach its stopping point.
  • Trace a complete algorithm containing several control structures.
A strong justification names a feature of the problem. For example: β€œA FOR loop is appropriate because exactly 12 readings must be processed.” Merely saying that it is β€œeasier” is not enough.

The Three Main Control-Structure Families

Family Purpose Common structures
Sequence Execute statements in a fixed order Assignments, input, calculations and output
Selection Choose which path should execute IF, IF...ELSE, nested IF, CASE
Repetition Execute a block several times FOR, WHILE, REPEAT...UNTIL

Sequence remains important

INPUT Length
INPUT Width
Area ← Length * Width
OUTPUT "Area: ", Area

No decision or repetition is required here. The statements execute once in their written order.

Common misconception: a solution does not need an IF or loop merely because those structures have recently been taught. Use only the structures required by the problem.

Choosing an Appropriate Selection Structure

Problem characteristic Likely structure Reason
One optional action One-way IF The block may be executed or skipped
Exactly two exclusive outcomes IF...ELSE One branch executes when the condition is true and the other when it is false
A later test depends on an earlier result Nested IF The inner condition should be tested only after a particular outer branch is reached
Several independent conditions may all cause actions Separate IF statements More than one block may need to execute
One selector is matched against several values or ranges CASE The alternatives all depend on the same controlling value

Use IF for a general Boolean condition

IF IsLoggedIn = TRUE AND HasUploadPermission = TRUE
THEN
    OUTPUT "Upload permitted"
ELSE
    OUTPUT "Upload rejected"
ENDIF

Use CASE for one selector

CASE OF UploadMode
    1 : OUTPUT "Replace existing file"
    2 : OUTPUT "Create a new version"
    3 : OUTPUT "Store as a separate file"
    OTHERWISE OUTPUT "Invalid upload mode"
ENDCASE
Ask whether each alternative tests the same selector. When several unrelated Boolean expressions are required, IF is normally clearer.

Choosing an Appropriate Loop

Question Answer Suitable loop
Is the repetition count or complete control sequence known before the loop? Yes FOR...NEXT
Could the body validly execute zero times? Yes WHILE...DO...ENDWHILE
Must the body execute before the condition can be tested? Yes REPEAT...UNTIL

Count known before execution

FOR SensorNumber ← 1 TO 16
    OUTPUT "Test sensor ", SensorNumber
NEXT SensorNumber

Work may already be complete

WHILE JobsWaiting > 0 DO
    OUTPUT "Process next job"
    JobsWaiting ← JobsWaiting - 1
ENDWHILE

Input must be obtained before it can be checked

REPEAT
    OUTPUT "Enter a value from 1 to 20: "
    INPUT Value
UNTIL Value >= 1 AND Value <= 20
Common mistake: β€œThe number of repetitions is unknown” does not by itself distinguish WHILE from REPEAT...UNTIL. You must also decide whether zero executions are possible or whether the body must run first.

How to Justify a Control-Structure Choice

A complete justification connects the chosen structure directly to a requirement of the problem.

Weak statement Stronger justification
β€œUse FOR because it is simple.” β€œUse FOR because exactly 24 shelf positions must be processed.”
β€œUse WHILE because it is a loop.” β€œUse WHILE because processing should continue only while unprocessed messages remain, and the queue may initially be empty.”
β€œUse REPEAT because it checks input.” β€œUse REPEAT...UNTIL because an input must be obtained at least once before its validity can be tested.”
β€œUse CASE because there are many choices.” β€œUse CASE because one command code is matched against several fixed values.”
β€œUse IF because it is shorter.” β€œUse IF because the decision uses two variables joined by a logical operator.”
A useful sentence pattern is: β€œUse [structure] because [specific property of the problem].”

Combining Control Structures

A control structure may contain another complete control structure. This is called nesting.

Nesting: placing one control structure inside the body or branch of another.

The outer structure determines whether or how often the inner structure is reached. The inner structure then controls a smaller part of the algorithm.

General example

FOR RecordNumber ← 1 TO RecordCount
    INPUT Reading

    IF Reading > AlertLimit
    THEN
        OUTPUT "Alert"
    ELSE
        OUTPUT "Normal"
    ENDIF
NEXT RecordNumber

The FOR loop determines how many records are processed. The IF determines what happens to each individual reading.

Common misconception: the inner structure does not execute independently of the outer structure. It is reached only when the outer path enters its containing block.

Selection Inside a Loop

Selection inside repetition allows each repeated item to be processed differently.

Original example: classifying package temperatures

FOR PackageNumber ← 1 TO 6
    OUTPUT "Enter package temperature ", PackageNumber, ": "
    INPUT PackageTemperature

    IF PackageTemperature > 8
    THEN
        OUTPUT "Move to temperature-controlled storage"
    ELSE
        OUTPUT "Standard storage permitted"
    ENDIF
NEXT PackageNumber
Structure Role
Outer FOR Processes exactly six packages
Inner IF...ELSE Classifies the current package

The selection is evaluated six times because it lies inside the loop body.

When explaining nested structures, state both roles: what the outer structure controls and what the inner structure controls.

A Loop Inside a Selection Branch

Repetition may be needed only when a particular decision result is reached.

Original example: exporting records

IF ExportRequired = TRUE
THEN
    FOR RecordNumber ← 1 TO RecordCount
        OUTPUT "Export record ", RecordNumber
    NEXT RecordNumber

    OUTPUT "Export complete"
ELSE
    OUTPUT "No export requested"
ENDIF

The FOR loop is reached only when ExportRequired is true.

Do not trace the inner loop when the containing branch is not selected.

Nested Loops

A nested loop repeats its complete inner loop for every execution of the outer loop.

Original example: testing a panel grid

FOR Row ← 1 TO 3
    FOR Column ← 1 TO 4
        OUTPUT "Test cell ", Row, ",", Column
    NEXT Column
NEXT Row
Outer value Inner values Cells tested
Row = 1 1, 2, 3, 4 (1,1), (1,2), (1,3), (1,4)
Row = 2 1, 2, 3, 4 (2,1), (2,2), (2,3), (2,4)
Row = 3 1, 2, 3, 4 (3,1), (3,2), (3,3), (3,4)

The inner body executes:

3 outer iterations Γ— 4 inner iterations = 12 times
Common mistake: the inner control variable must restart for each new outer iteration.
For two count-controlled loops, determine the inner iteration count and multiply it by the outer iteration count.

Validation Before Repeated Processing

Different loops can be used for different parts of the same algorithm. A post-condition loop can validate a count before a count-controlled loop uses that count.

Original example: selecting a batch size

REPEAT
    OUTPUT "Enter a batch size from 2 to 10: "
    INPUT BatchSize
UNTIL BatchSize >= 2 AND BatchSize <= 10

FOR ItemNumber ← 1 TO BatchSize
    OUTPUT "Process item ", ItemNumber
NEXT ItemNumber
Loop Purpose Why appropriate?
REPEAT...UNTIL Obtain a valid batch size Input must occur before it can be tested
FOR...NEXT Process the validated number of items The repetition count is now known
The best loop may change during an algorithm because different stages have different control requirements.

Using Built-in Routines with Control Structures

A built-in function can normalise or transform a value before it is tested by a control structure.

Original example: normalising a command

REPEAT
    OUTPUT "Enter S, P or Q: "
    INPUT Command

    Command ← UCASE(Command)
UNTIL Command = 'S'
   OR Command = 'P'
   OR Command = 'Q'

CASE OF Command
    'S' : OUTPUT "Start system"
    'P' : OUTPUT "Pause system"
    'Q' : OUTPUT "Close system"
ENDCASE

Converting the character to uppercase means that lower- and uppercase input do not need separate branches.

Common mistake: avoid calling the same function repeatedly when its result can be calculated once and stored before the decision.

State, Updates and Termination

When structures are combined, several variables may control different parts of the algorithm.

Attempts ← 0
IsAccepted ← FALSE

WHILE Attempts < 3 AND IsAccepted = FALSE DO
    INPUT AccessCode
    Attempts ← Attempts + 1

    IF AccessCode = StoredCode
    THEN
        IsAccepted ← TRUE
    ENDIF
ENDWHILE
Identifier Role How it changes
Attempts Limits the maximum number of body executions Increases during every iteration
IsAccepted Allows early termination when the correct code is entered Changes only in the successful IF branch
Flag: a Boolean variable used to record whether a particular state or event has occurred.
For every loop condition, identify each variable used and locate the statement that can change it.

Correctness, Clarity and Efficiency

Several control structures may produce the same result, but some designs are clearer and perform less unnecessary work.

Design issue Less effective approach Improvement
Fixed number of repetitions Manually maintain a counter in a WHILE loop Use a FOR loop when the count is already known
Many exact alternatives Long nested equality-based IF chain Use CASE when one selector controls the alternatives
One-time calculation Recalculate it during every iteration Move it before the loop when its inputs do not change
Shared output Repeat the same statement in every branch Place the shared statement after the selection
Deep nesting Several unnecessary decision levels Combine related conditions or validate early
Conditional loop No reliable update towards termination Make the state change explicit

Move fixed calculations outside a loop

Unnecessary repetition

FOR Item ← 1 TO ItemCount
    TaxRate ← StandardPercentage / 100
    ItemTax ← ItemPrice[Item] * TaxRate
NEXT Item

Clearer placement

TaxRate ← StandardPercentage / 100

FOR Item ← 1 TO ItemCount
    ItemTax ← ItemPrice[Item] * TaxRate
NEXT Item

The fixed tax rate is now calculated once rather than once per item.

A Method for Tracing Combined Structures

  1. Identify every control structure and mark its beginning and end.
  2. Use indentation to determine which structure contains each statement.
  3. Record all variable values before the first structure begins.
  4. Evaluate only the conditions or loops reached by the current path.
  5. For an outer loop, complete the entire inner structure before advancing the outer loop.
  6. Record every assignment, input and output in execution order.
  7. Include the final condition check that ends a conditional loop.
  8. Confirm where execution continues after each structure closes.

Useful trace-table columns

Step Outer structure Inner structure Condition or control value Changed variables Output
1 Record active loop or branch Record nested loop or branch TRUE/FALSE or counter value Record new state Record visible result
Do not jump directly to the final output. Combined-control questions usually reward accurate intermediate states and branch decisions.

Worked Example: Greenhouse Zone Inspection

A greenhouse contains between two and six monitored zones. The algorithm must validate the zone count, receive a moisture percentage for each zone, classify it and count readings requiring attention.

Complete pseudocode

DECLARE ZoneCount : INTEGER
DECLARE ZoneNumber : INTEGER
DECLARE Moisture : INTEGER
DECLARE TotalMoisture : INTEGER
DECLARE AlertCount : INTEGER
DECLARE AverageMoisture : REAL
DECLARE Status : STRING

REPEAT
    OUTPUT "Enter the number of zones from 2 to 6: "
    INPUT ZoneCount
UNTIL ZoneCount >= 2 AND ZoneCount <= 6

TotalMoisture ← 0
AlertCount ← 0

FOR ZoneNumber ← 1 TO ZoneCount
    REPEAT
        OUTPUT "Enter moisture for zone ", ZoneNumber, ": "
        INPUT Moisture
    UNTIL Moisture >= 0 AND Moisture <= 100

    TotalMoisture ← TotalMoisture + Moisture

    CASE OF Moisture
        0 TO 24 :
            Status ← "Too dry"
            AlertCount ← AlertCount + 1

        25 TO 74 :
            Status ← "Balanced"

        75 TO 100 :
            Status ← "Too wet"
            AlertCount ← AlertCount + 1
    ENDCASE

    OUTPUT "Zone ", ZoneNumber, ": ", Status
NEXT ZoneNumber

AverageMoisture ← TotalMoisture / ZoneCount

OUTPUT "Average moisture: ", AverageMoisture

IF AlertCount = 0
THEN
    OUTPUT "All zones are within the preferred range"
ELSE
    OUTPUT "Zones requiring attention: ", AlertCount
ENDIF

Role of each structure

Structure Role Why suitable?
First REPEAT...UNTIL Validate the number of zones The count must be entered before it can be checked
FOR Process every zone The validated zone count is known
Nested REPEAT...UNTIL Validate each moisture reading Every zone requires at least one entered reading
CASE Classify the current percentage One selector is matched against non-overlapping ranges
Final IF...ELSE Choose the summary message Exactly two outcomes depend on one Boolean condition

Partial trace

Suppose the validated zone count is 3 and the readings are 18, 52 and 81.

Zone Moisture Status Total moisture Alert count
1 18 Too dry 18 1
2 52 Balanced 70 1
3 81 Too wet 151 2
AverageMoisture ← 151 / 3

The final selection reports that two zones require attention.

A justification should address each structure separately. Do not describe the entire algorithm as merely β€œusing a loop”.

Interactive: Control-Structure Choice Guide

Select a category and scenario. Step through the questions that lead to an appropriate structure and a syllabus-style justification.

Choosing a selection structure

Decide how alternatives are controlled.


Decision path

Recommended structure: Deciding...
Main reason: Follow the questions

Question 1

Identify the decision

Determine what controls the alternatives.

Interactive: Combined Control-Structure Visualiser

This visualiser builds a centred pattern without using subroutines. It combines input validation, a pre-condition loop, two inner count-controlled loops and a selection statement.

Pseudocode represented by the widget

REPEAT
    INPUT BaseWidth
UNTIL BaseWidth >= 3
  AND BaseWidth <= 13
  AND BaseWidth MOD 2 = 1

INPUT Symbol

Spaces ← (BaseWidth - 1) DIV 2
Symbols ← 1

WHILE Symbols <= BaseWidth DO
    Line ← ""

    FOR Counter ← 1 TO Spaces
        Line ← Line & " "
    NEXT Counter

    FOR Counter ← 1 TO Symbols
        Line ← Line & Symbol
    NEXT Counter

    IF Symbols = BaseWidth
    THEN
        Line ← Line & "  < base"
    ENDIF

    OUTPUT Line

    Spaces ← Spaces - 1
    Symbols ← Symbols + 2
ENDWHILE

Current program stage

Ready

Build the trace, then move through each control-structure step.

Current values
-- spaces
-- symbols
-- row
REPEAT...UNTIL Validate the odd base width
WHILE Decide whether another row is required
FOR spaces Append the required leading spaces
FOR symbols Append the selected symbol repeatedly
IF Identify the base row
Sequence Update values for the next row
Output so far

At each step, name the active structure and explain what its condition or control variable decides.

Common Mistakes and Misconceptions

  • Choosing by habit: using the most familiar structure rather than matching the problem requirement.
  • Weak justification: saying a structure is β€œeasy” or β€œshort” without identifying the known count, condition position or selector.
  • Using CASE for unrelated conditions: CASE should match one selector against alternatives.
  • Using IF...ELSE for independent actions: ELSE makes the outcomes mutually exclusive.
  • Using FOR for unknown repetition: the count or sequence must be known before the loop.
  • Using WHILE when the body must run first: the initial check may skip the body.
  • Using REPEAT when zero executions are valid: its body always runs at least once.
  • Tracing an inner structure when its outer branch is not reached.
  • Advancing an outer loop before completing the entire inner loop.
  • Mismatching closing keywords: unclear indentation can hide which ENDIF, NEXT or ENDWHILE closes each structure.
  • Leaving loop state unchanged: a conditional loop may become infinite.
  • Initialising an accumulator inside a repeated block: earlier results are lost.
  • Repeating fixed calculations inside a loop.
  • Over-nesting: unnecessary levels make the algorithm difficult to understand and trace.

Practice

Question 1: choose a selection structure

Choose and justify a suitable structure for each problem:

  1. Display one message when a sensor exceeds its safe limit.
  2. Display β€œvalid” or β€œinvalid” according to one Boolean condition.
  3. Match one transport code against six fixed values.
  4. Award a project badge and an attendance badge independently.

Question 2: choose a loop

Choose and justify a suitable loop:

  1. Output exactly 18 labels.
  2. Process messages while the queue is not empty.
  3. Input a percentage until it is from 0 to 100.
  4. Continue searching while more records remain.

Question 3: selection inside repetition

Write pseudocode that inputs exactly five battery readings. For each reading, output "Low" when the value is below 25 and "Acceptable" otherwise.

Question 4: repetition inside selection

When PrintReport is true, output the record numbers from 1 to RecordCount. Otherwise output "Report not requested".

Question 5: nested loop trace

FOR Row ← 1 TO 2
    FOR Column ← 3 TO 5
        OUTPUT Row, Column
    NEXT Column
NEXT Row

List every output pair and state how many times the inner body executes.

Question 6: validation and processing

Write pseudocode that validates an integer ReadingCount from 1 to 8 and then inputs exactly that many readings.

Question 7: identify the inappropriate loop

Counter ← 1

WHILE Counter <= 10 DO
    OUTPUT Counter
    Counter ← Counter + 1
ENDWHILE

The algorithm is correct. Explain why a different loop would communicate the known repetition more clearly and rewrite it.

Question 8: reduce unnecessary work

FOR Item ← 1 TO ItemCount
    ConversionRate ← 1000 / 60
    ConvertedValue ← Reading[Item] * ConversionRate
NEXT Item

Rewrite the algorithm so that the fixed calculation occurs only once.

Question 9: trace combined structures

AlertCount ← 0

FOR ReadingNumber ← 1 TO 4
    INPUT Reading

    CASE OF Reading
        0 TO 39 :
            OUTPUT "Low"
            AlertCount ← AlertCount + 1

        40 TO 70 :
            OUTPUT "Normal"

        71 TO 100 :
            OUTPUT "High"
            AlertCount ← AlertCount + 1
    ENDCASE
NEXT ReadingNumber

IF AlertCount > 0
THEN
    OUTPUT AlertCount
ENDIF

Trace the algorithm for inputs 32, 55, 88 and 64.

Question 10: design a combined algorithm

A program must:

  • input a valid number of teams from 2 to 6;
  • input one score for every team;
  • classify each score as low, medium or high;
  • count the number of high scores;
  • display a final summary.

Choose and combine appropriate control structures. Justify each choice.

Show suggested answers

Question 1

  1. One-way IF: one optional action is required.
  2. IF...ELSE: exactly two exclusive outcomes are required.
  3. CASE: one transport code is matched against fixed values.
  4. Two separate IF statements: both badges may be awarded.

Question 2

  1. FOR: exactly 18 repetitions are known.
  2. WHILE: processing continues while work exists and the queue may initially be empty.
  3. REPEAT...UNTIL: input must occur before its validity can be checked.
  4. WHILE: searching continues while records remain and may require zero executions.

Question 3

FOR ReadingNumber ← 1 TO 5
    INPUT BatteryReading

    IF BatteryReading < 25
    THEN
        OUTPUT "Low"
    ELSE
        OUTPUT "Acceptable"
    ENDIF
NEXT ReadingNumber

Question 4

IF PrintReport = TRUE
THEN
    FOR RecordNumber ← 1 TO RecordCount
        OUTPUT RecordNumber
    NEXT RecordNumber
ELSE
    OUTPUT "Report not requested"
ENDIF

Question 5

1,3
1,4
1,5
2,3
2,4
2,5

The inner body executes six times: two outer iterations multiplied by three inner iterations.

Question 6

REPEAT
    INPUT ReadingCount
UNTIL ReadingCount >= 1 AND ReadingCount <= 8

FOR ReadingNumber ← 1 TO ReadingCount
    INPUT Reading
NEXT ReadingNumber

Question 7

The sequence 1 to 10 is known before repetition begins, so a count-controlled loop communicates the design more directly.

FOR Counter ← 1 TO 10
    OUTPUT Counter
NEXT Counter

Question 8

ConversionRate ← 1000 / 60

FOR Item ← 1 TO ItemCount
    ConvertedValue ← Reading[Item] * ConversionRate
NEXT Item

Question 9

Input Output Alert count
32Low1
55Normal1
88High2
64Normal2

The final output is 2.

Question 10

One possible design uses:

  • REPEAT...UNTIL to validate the team count;
  • FOR to process the known number of teams;
  • CASE to classify each score using ranges;
  • an assignment inside the high-score branch to update the count;
  • IF...ELSE after repetition to choose the summary message.

Review

Requirement Likely structure Key justification
Statements run once in order Sequence No decision or repetition is required
One general Boolean decision IF A Boolean expression determines the branch
One selector with several alternatives CASE The same value is matched against labels or ranges
Known count or sequence FOR The repetitions are known before the loop
May execute zero times WHILE The condition must be checked before the body
Must execute at least once REPEAT...UNTIL The body must run before the stopping test
Every repeated item needs a decision Selection inside a loop The decision is applied once per item
Every outer item contains several inner items Nested loops The complete inner loop runs for each outer iteration
Final exam tip: first identify what controls each part of the problem. Then choose the structure, justify it using that control rule and trace the structures from the outside inward.