CIE IGCSE | 7.7.2 Tracing Selection and Loops

Lesson objective

Trace selection and iteration accurately, record repeated condition checks and distinguish executed instructions from skipped branches.

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"
ENDIF

The condition 4 ≥ 5 is false, so the ELSE instruction executes. Record “Keep practising”. The THEN instruction is skipped.

Independent starting cases
Starting ScoreScore >= 5?Executed branchOutput
4FalseELSEKeep practising
5TrueTHENTarget reached
8TrueTHENTarget 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.

Running totals are output inside the body
EventIndex in bodyTotal afterwardsOutput
InitialisationNot assigned0
First body111
Second body233
Third body366
After loopNot recorded6Done

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.

After the false check, Finished is output
Count at checkCount <= 3?Body outputCount after body
1True12
2True23
3True34
4FalseNoneNo 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 > 3

With 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.

Condition uses the updated value after the body
Count before bodyOutputCount after incrementCount > 3?Action
112FalseRepeat
223FalseRepeat
334TrueStop

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.

These examples differ in check position and stopping rule
Starting CountWHILE body outputsREPEAT body outputs
11, 2, 31, 2, 3
4None4

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: ", QualifyingCount

The 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.

Full-state rows after each body, followed by final outputs
EventScoreConditionTotalCountPrompt / output
Body 14False00Enter score
Body 25True51Enter score
Body 38True132Enter score
Body 42False132Enter score
Final total output2Not checked132Qualifying total: 13
Final count output2Not checked132Qualifying 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.

MATCH THE CONTROL-FLOW TERM

Terminology

Terminology

Selection

Choosing instructions according to a condition.

Iteration

Repeating instructions.

Branch

One path of instructions associated with a decision outcome.

Condition

An expression evaluated as TRUE or FALSE.

Skipped instruction

A statement not executed on the current path.

Loop body

The instructions executed during a repetition.

FOR loop

Count-controlled repetition over specified counter values.

WHILE loop

A pre-condition loop continuing while its condition is true.

REPEAT UNTIL loop

A post-condition loop stopping when its condition becomes true.

Pre-condition

A check performed before entering the repeated body.

Post-condition

A check performed after a repeated body has executed.

Exit check

A condition evaluation that ends repetition.

Nested iteration

A loop contained within another loop.

Conditional update

An assignment executed only when its condition permits it.

Retained value

A current value kept because no executed instruction changes it.

Infinite loop

Repetition that does not reach its intended exit.

Trace convention

The stated way rows and unchanged values are recorded.

Execution path

The actual route through instructions for the current values.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Score four is tested with Score >= 5. Which output occurs?
2. OUTPUT Check complete is after ENDIF. Which are correct?
3. Total starts at zero; FOR Index one to three adds Index and outputs Total. Which sequence?
4. Count starts at four in WHILE Count <= 3. Which are correct?
5. Count starts at four in the REPEAT example. What is body output?
6. Which stopping rules are correct?
7. For conditional inputs four, five, eight and two, which are correct?
8. Which make tracing accurate?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Explain why only one IF branch executes for a given condition check.

2. Explain the outputs one, three and six in the FOR running-total example.

3. Describe the final check in the WHILE counter trace.

4. Compare WHILE and REPEAT when Count begins at four in these examples.

5. Explain why a below-threshold score leaves both conditional summaries unchanged.

6. Explain why four prompts occur in the combined example.

7. Explain why an invalid input inside a retry loop does not necessarily advance an outer accepted-score counter.

8. Explain how to report a missing-update infinite loop during a dry run.

TRACE IT | POSITIVE VALUES ONLY

Trace inputs two, minus one and four. Record Index, Value, Total, condition results and every output in order. Then repeat with zero replacing minus one and explain whether the output changes.

DECLARE Value : INTEGER
DECLARE Index : INTEGER
DECLARE Total : INTEGER
Total ← 0
FOR Index ← 1 TO 3
    OUTPUT "Enter value"
    INPUT Value
    IF Value > 0
      THEN
        Total ← Total + Value
        OUTPUT "Added"
      ELSE
        OUTPUT "Not added"
    ENDIF
NEXT Index
OUTPUT "Total: ", Total
Reveal a suggested trace

Total changes from zero to two, stays two on minus one, then becomes six on four. Outputs are Enter value; Added; Enter value; Not added; Enter value; Added; Total: 6. Replacing minus one with zero follows the same false branch because zero is not greater than zero, so those outputs and the total are unchanged.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

    Selections are kept while this page is open.

    Workbook

    Workbook

    COMING SOON

    The workbook for 7.7.2 Tracing Selection and Loops is coming soon. Complete the matching task and written questions in your exercise book.