Learn
7.7.2 | TRACING SELECTION AND LOOPS
01 | EXECUTION DOES NOT ALWAYS MOVE STRAIGHT DOWN
In the previous lesson, a simple sequence received two numbers, calculated their sum and displayed a result. Reading from top to bottom followed the execution.
A decision changes that pattern: one branch runs while another is skipped. A loop changes it again: control returns to an earlier step, sometimes many times.
Selection chooses instructions according to a condition. Iteration repeats instructions. To trace either accurately, use the current values to decide what executes next.
This lesson starts with a small IF statement, develops the three main loop forms and then combines selection with repetition. Do not try to guess the final answer first; follow the actual route.
02 | IF: EVALUATE THE CONDITION BEFORE THE BRANCH
Assume Score already contains a whole number. Read this selection with Score equal to 4.
IF Score >= 5
THEN
OUTPUT "Target reached"
ELSE
OUTPUT "Keep practising"
ENDIFThe condition 4 ≥ 5 is false, so the ELSE instruction executes. Record “Keep practising”. The THEN instruction is skipped.
| Starting Score | Score >= 5? | Executed branch | Output |
|---|---|---|---|
| 4 | False | ELSE | Keep practising |
| 5 | True | THEN | Target reached |
| 8 | True | THEN | Target reached |
With Score equal to 5, equality makes the condition true and the output is “Target reached”. With Score equal to 8, it is also true.
For each independent trace, start with the stated Score. Do not combine outputs from different starting cases into one run.
A condition check does not assign a new value to Score. It selects a path using the value already present.
03 | AN INSTRUCTION AFTER ENDIF IS NOT PART OF ONE BRANCH
Now add a common final output after the selection.
IF Score >= 5
THEN
OUTPUT "Target reached"
ELSE
OUTPUT "Keep practising"
ENDIF
OUTPUT "Check complete"For Score 4, the output sequence is “Keep practising”, then “Check complete”. For Score 8, it is “Target reached”, then “Check complete”.
Both branches finish at ENDIF, and execution continues afterwards. The final output is outside the selection, so it runs in either case.
Indentation helps show the grouping, but read the opening and closing keywords as well. Do not assume that every instruction beneath ELSE belongs to it if ENDIF has already closed the selection.
This is a common trace-table mistake: skipping a shared instruction because it appears below the unchosen branch on the page.
04 | FOR: TRACE EACH SPECIFIED LOOP VALUE
A FOR loop repeats its body for the specified counter values. In Cambridge pseudocode, the endpoints are included.
DECLARE Index : INTEGER
DECLARE Total : INTEGER
Total ← 0
FOR Index ← 1 TO 3
Total ← Total + Index
OUTPUT Total
NEXT Index
OUTPUT "Done"Index takes 1, 2 and 3. Total begins at zero; each pass adds the current Index and outputs the new total.
| Event | Index in body | Total afterwards | Output |
|---|---|---|---|
| Initialisation | Not assigned | 0 | |
| First body | 1 | 1 | 1 |
| Second body | 2 | 3 | 3 |
| Third body | 3 | 6 | 6 |
| After loop | Not recorded | 6 | Done |
The outputs are 1, 3, 6, followed by “Done” after NEXT. They are running totals, not the loop values 1, 2 and 3.
For this simple FOR loop, progression through the specified values is handled by the construct. Do not add an extra manual increment that is absent from the algorithm.
This table records Index only while a body repetition is being processed. We do not infer an unstated post-loop counter convention to answer a question that does not use it.
05 | WHILE: CHECK BEFORE EVERY BODY EXECUTION
A WHILE loop executes its body while the condition is true. The condition is checked before the first repetition and again after each completed body.
DECLARE Count : INTEGER
Count ← 1
WHILE Count <= 3 DO
OUTPUT Count
Count ← Count + 1
ENDWHILE
OUTPUT "Finished"Count starts at 1. When Count ≤ 3 is true, output Count and increase it by one. Then return to the condition.
| Count at check | Count <= 3? | Body output | Count after body |
|---|---|---|---|
| 1 | True | 1 | 2 |
| 2 | True | 2 | 3 |
| 3 | True | 3 | 4 |
| 4 | False | None | No body; stays 4 |
The final check at Count 4 is false, so no body instructions execute for four. The next output is “Finished”.
Include the exit check when tracing conditions. Reaching the intended last output does not itself stop the loop; the specified condition must fail.
06 | A WHILE BODY CAN RUN ZERO TIMES
Use the same WHILE example but initialise Count to 4. The first condition 4 ≤ 3 is false.
The loop body is skipped entirely: no number is output and Count remains 4. Execution continues after ENDWHILE, producing “Finished”.
This is why WHILE is called a pre-condition loop: it tests before entering the body.
Do not force one repetition just because you see instructions between WHILE and ENDWHILE. They only execute when the condition permits them.
A useful test pair is Count starting at 1 and at 4. The two traces demonstrate repeated execution and immediate exit without changing the algorithm’s loop rule.
07 | REPEAT UNTIL: EXECUTE FIRST, THEN CHECK
A REPEAT loop enters its body before checking the UNTIL condition. It stops when that condition becomes true.
DECLARE Count : INTEGER
Count ← 1
REPEAT
OUTPUT Count
Count ← Count + 1
UNTIL Count > 3With Count starting at 1, output 1 and increase Count to 2. The condition 2 > 3 is false, so repeat. Next output 2 and increase to 3; the condition is still false. Next output 3 and increase to 4; the condition is true, so stop.
| Count before body | Output | Count after increment | Count > 3? | Action |
|---|---|---|---|---|
| 1 | 1 | 2 | False | Repeat |
| 2 | 2 | 3 | False | Repeat |
| 3 | 3 | 4 | True | Stop |
The condition uses the value after the update, not the value displayed earlier in that body.
Remember the direction of the rule: WHILE continues when its condition is true; REPEAT UNTIL stops when its condition is true.
08 | THE POSITION OF THE CHECK CHANGES BEHAVIOUR
If Count starts at 4 in the REPEAT example, the body still runs once. It outputs 4, increases Count to 5 and then finds that 5 > 3 is true.
With Count starting at 4 in the WHILE example, the body runs zero times. The outputs are therefore different even though both examples can output one through three when started at one.
| Starting Count | WHILE body outputs | REPEAT body outputs |
|---|---|---|
| 1 | 1, 2, 3 | 1, 2, 3 |
| 4 | None | 4 |
Do not identify a loop solely from a familiar output sequence. Inspect where the condition is checked and what result allows repetition or ends it.
This distinction is especially useful for input validation: a REPEAT body can receive the first input before testing whether it is acceptable.
09 | COMBINE A LOOP WITH A CONDITIONAL UPDATE
Now receive four whole-number scores. Count and total only those at least five. Assume all inputs are valid whole numbers for this task.
DECLARE Score : INTEGER
DECLARE Index : INTEGER
DECLARE QualifyingTotal : INTEGER
DECLARE QualifyingCount : INTEGER
QualifyingTotal ← 0
QualifyingCount ← 0
FOR Index ← 1 TO 4
OUTPUT "Enter score"
INPUT Score
IF Score >= 5
THEN
QualifyingTotal ← QualifyingTotal + Score
QualifyingCount ← QualifyingCount + 1
ENDIF
NEXT Index
OUTPUT "Qualifying total: ", QualifyingTotal
OUTPUT "Qualifying count: ", QualifyingCountThe FOR loop receives four inputs. The IF condition decides whether the two updates execute on that repetition.
QualifyingTotal and QualifyingCount begin at zero before the loop. A score below five completes a repetition without changing either value.
The prompt is inside the loop but outside the IF, so it appears once for every requested score, whether or not that score qualifies.
The final two outputs are after NEXT, so they communicate the completed summaries rather than an intermediate result.
10 | TRACE QUALIFYING AND NON-QUALIFYING INPUTS
Use scores 4, 5, 8 and 2. The first fails the condition, the next two satisfy it and the final one fails.
| Event | Score | Condition | Total | Count | Prompt / output |
|---|---|---|---|---|---|
| Body 1 | 4 | False | 0 | 0 | Enter score |
| Body 2 | 5 | True | 5 | 1 | Enter score |
| Body 3 | 8 | True | 13 | 2 | Enter score |
| Body 4 | 2 | False | 13 | 2 | Enter score |
| Final total output | 2 | Not checked | 13 | 2 | Qualifying total: 13 |
| Final count output | 2 | Not checked | 13 | 2 | Qualifying count: 2 |
The final total is 13 and qualifying count is 2. A score of five qualifies because the comparison includes equality.
The full output sequence is four occurrences of “Enter score”, then “Qualifying total: 13”, then “Qualifying count: 2”. The entered scores themselves are not explicit OUTPUT instructions.
The table summarises each completed repetition. The Prompt column records its earlier output within that repetition; final result outputs are shown in separate rows.
11 | FOLLOW RETRIED INPUTS WITHOUT ADVANCING TOO SOON
A loop inside another loop is called nested iteration. In a design that needs three valid scores, an outer FOR can count the accepted scores while an inner REPEAT asks again for an invalid entry.
If the input sequence is 4, 12, 7 and 9 and the accepted range is zero to ten, the second outer repetition receives 12, rejects it and then receives 7. It has not advanced to the third outer repetition yet.
Only after the inner loop accepts 7 does the outer body finish. Nine becomes the third accepted score. The rejected twelve is not added to a valid-score total if addition is placed after the inner loop.
Write down both loop roles and which closing instruction you have reached. Reaching UNTIL for the inner loop is not the same as reaching NEXT for the outer loop.
Do not consume a new input unless an executed INPUT requests it. Conditions and loop-counter progress do not independently take values from the supplied sequence.
12 | SPOT ERRORS BY FOLLOWING THE REAL FLOW
If Total is reset to zero inside every repetition, the trace will lose earlier additions. If a WHILE update is missing, the same condition may stay true and the algorithm may repeat indefinitely.
If an IF condition is changed from Score ≥ 5 to Score > 5, input five follows the non-qualifying path. Trace that actual condition instead of silently restoring the intended one.
When an infinite loop becomes clear, do not invent a stopping point and claim normal termination. Show the repeated state and explain why the condition cannot change under the given instructions.
Keep tracing and debugging separate: the trace records what happens; your explanation can identify why that behaviour violates the task.
13 | RECORD ONLY WHAT EXECUTES
Use a full-state table when learning: repeat current variable values after each event or summarised body, and identify your convention. A compact change-only table can be used when supplied or requested, but unchanged values remain in force.
Do not write assignments from a skipped branch into the trace. Do not output a value merely because it changed. Include every explicit prompt and result message in the correct order.
For detailed tracing, record each condition check, including the final exit. For a table supplied by an exam question, follow its required columns and row convention rather than introducing incompatible entries.
A clear comment beside a row can explain the path, but it is not itself program output.
14 | EXPLAIN WHY THE PATH IS FOLLOWED
A precise explanation is: “At Count four, Count ≤ 3 is false, therefore the WHILE body is skipped and execution continues after ENDWHILE.”
For conditional counting: “Score four fails the threshold, so both updates are skipped; the values retained from the previous repetition stay unchanged.”
Avoid saying “the loop repeats three times” without checking its initial values, bounds and updates. The same loop body can have different repetition counts with different starting states.
You should now be able to trace chosen branches, repeated checks and conditional updates, keeping the distinction between input, variable changes and output visible. Next you will use these skills to identify and correct algorithm errors.