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
IFandCASE. - Choose between
FOR,WHILEandREPEAT...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.
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.
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
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
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.β |
Combining Control Structures
A control structure may contain another complete control structure. This is called nesting.
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.
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.
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.
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:
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 |
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.
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 |
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
- Identify every control structure and mark its beginning and end.
- Use indentation to determine which structure contains each statement.
- Record all variable values before the first structure begins.
- Evaluate only the conditions or loops reached by the current path.
- For an outer loop, complete the entire inner structure before advancing the outer loop.
- Record every assignment, input and output in execution order.
- Include the final condition check that ends a conditional loop.
- 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 |
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.
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.
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
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,NEXTorENDWHILEcloses 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:
- Display one message when a sensor exceeds its safe limit.
- Display βvalidβ or βinvalidβ according to one Boolean condition.
- Match one transport code against six fixed values.
- Award a project badge and an attendance badge independently.
Question 2: choose a loop
Choose and justify a suitable loop:
- Output exactly 18 labels.
- Process messages while the queue is not empty.
- Input a percentage until it is from 0 to 100.
- 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
-
One-way
IF: one optional action is required. -
IF...ELSE: exactly two exclusive outcomes are required. -
CASE: one transport code is matched against fixed values. -
Two separate
IFstatements: both badges may be awarded.
Question 2
-
FOR: exactly 18 repetitions are known. -
WHILE: processing continues while work exists and the queue may initially be empty. -
REPEAT...UNTIL: input must occur before its validity can be checked. -
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 |
|---|---|---|
| 32 | Low | 1 |
| 55 | Normal | 1 |
| 88 | High | 2 |
| 64 | Normal | 2 |
The final output is 2.
Question 10
One possible design uses:
-
REPEAT...UNTILto validate the team count; -
FORto process the known number of teams; -
CASEto classify each score using ranges; - an assignment inside the high-score branch to update the count;
-
IF...ELSEafter 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 |