lesson

The condition must eventually change

1 · Learn

A while loop repeats while its condition is true. If the body never changes anything affecting the condition, the loop may never terminate. Plan the initial state, condition and update before running it.

For a model count starting at 0, repeatedly adding 1 while count < 3 gives updates to 1, 2 and 3, then stops. If count already begins at 3, the body runs zero times.

Initial stateConditionBodyUpdateRetest
Key words and supplied examples.

2 · Worked example

I trace count values before and after each iteration. This reveals whether the loop stops at the intended boundary and whether an update was accidentally omitted.

3 · Your turn

If count starts at 5 and the condition is count < 3, how many iterations run?

Check your answer

Zero; the condition is false before the first iteration.

4 · Apply your learning

Trace a terminating and a deliberately incomplete paper loop; identify the missing update without running an uncontrolled loop.

Adult guidance and safety

Use an approved private interpreter, simulator or authoring tool with fictional data. Trace and predict before running. Never execute unknown downloaded code, inspect real credentials or use other people's private data. Working examples still need saved-project and assessment integration before release.

Practice this lesson

Lesson resources

Browse the available practice activities and worksheets for this lesson.

Open course resources
Exercise preview