Skip to content
myAudience.
← Explore the library

Loops need state meanings and stopping reasons

By UK GCSE Computer Science · independent study · myAudience

Accumulator table: input 4 changes total 0 to 4, input 7 changes 4 to 11, input 2 changes 11 to 13. Pre-test loop initialises zero and checks for another input before reading; empty input returns zero.

Original AI-generated teaching raster via built-in image_gen; author inspected 2026-10-04. · Generated project artwork; no copied exam or publisher illustration. Independent rights/publication review pending.

Loops need state meanings and stopping reasons

Iteration repeats a process while updating state. A count-controlled loop has a planned number of repetitions; a condition-controlled loop continues according to a changing condition. Python range(3) produces 0,1,2 and excludes its stop value. A while loop tests before its body, so it can run zero times. An end-tested repeat-until algorithm runs its body at least once. Python has no native repeat-until statement, but while True with a break after the body can implement it. Entry skills are assignment and Boolean selection; changing syntax must preserve when the decision occurs.

An accumulator starts from an identity value and combines successive inputs. For adding readings, total starts at zero. The invariant is “total equals the sum of readings already processed”. Before any input it holds for the empty prefix. If it holds before the next reading x, total + x becomes the sum of the extended prefix. After the last reading it therefore equals the sum of all inputs. This proof explains why resetting total inside the loop is wrong: it destroys the prefix meaning. The generated trace visual illustrates 4,7,2 producing totals 4,11,13, not an average.

Termination is a separate obligation. A for loop over a finite list terminates after its elements are exhausted. A while loop needs a reason its condition eventually becomes false; simply hoping input will change is not a proof. A validation prompt can intentionally wait indefinitely for a user, but that limitation belongs in its interface. A bounded retry counter creates a definite resource limit. Nested loops multiply work: for r rows each containing c cells, an inner visit for every cell runs r times c times. Empty data should be considered before division by its length.

The program below deliberately counts a measurement at or above a threshold while summing all measurements. State variables serve different meanings and must not be conflated. A conditional count increment does not make the sum conditional. The return value is a pair; it lets a caller decide how to display the result. Negative readings can be valid in a temperature model, while a negative number of books was invalid earlier. Reusing a generic “reject negatives” policy across unrelated contracts would silently change the question.

Trace each iteration with the input, total before and after, and count before and after. For 4,7,2 at threshold 4, the final total is 13 and count 2. A zero threshold counts zero itself, so >= matters. A data set with no readings yields sum zero and count zero. If an average is required, specify whether an empty set returns a missing value or rejects the request rather than pretending it averages to zero. The transfer question adds consecutive-state reasoning so that a single accumulator pattern is no longer enough.

Runnable original Python 3 example (also saved verbatim in examples for CLI execution):
```python
def summarise(readings, threshold):
"""Return (sum, count >= threshold); readings is a finite numeric sequence."""
total = 0
count = 0
for reading in readings:
total += reading
if reading >= threshold:
count += 1
return total, count

assert summarise([4, 7, 2], 4) == (13, 2)
assert summarise([], 4) == (0, 0)
assert summarise([-2, 0, 3], 0) == (1, 2)
```

Worked example: Trace the summaries for readings 2,5,5 with threshold 5.

Start total=0 and count=0.

After 2: total=2,count=0. After first 5: total=7,count=1.

After second 5: total=12,count=2. The equality cases count.

Answer: (12, 2).

Check your understanding: Transfer: find the longest consecutive run of readings >= 5 in [6,7,2,5,5,5,1,9]. Describe state and update rules; then justify the empty-input result.

Answer: Use current=0 and longest=0. If reading >= 5 increment current; otherwise set current=0. After each reading set longest=max(longest,current). The result is 3. Empty input returns 0 because no run has been encountered.

Why: current measures the qualifying suffix of the processed prefix; longest measures the maximum completed or current run. Reset only current on a failure. Counting all qualifying values gives 6 and fails to answer a question about consecutive readings.

Author source references