Iteration with loops — Computing, 14–17
Loops let a program repeat a small set of instructions without writing the same lines again and again. The key is knowing what makes the repetition stop.
A loop repeats a pattern
A loop tells a computer to run the same instructions repeatedly. It may repeat for each item in a collection, or while a condition remains true. The instructions stay in one place, while a counter, item or condition controls which repetition is happening.
Why loops were needed
Writing one instruction for every repeated task is slow, bulky and easy to get wrong. People have always needed machines to process long lists, print patterns or measure many values. Loops solve this problem by describing the repeated rule once and letting the computer carry it out as many times as required.
Adding four prices
Suppose prices are 3, 7, 2 and 8 euros. Set total = 0, then loop through the prices: after 3, total is 3; after 7, it is 10; after 2, it is 12; after 8, it is 20. The loop stops because there are no items left, so the answer is 20 euros.
The endless loop
A very reasonable mistake is to write a loop whose stopping value never changes. For example, while count < 5 is endless if count starts at 0 and the loop never increases count. The computer is obeying perfectly; the programmer forgot to provide a path towards the stopping condition.
Loops outside school
A weather service can loop through thousands of readings to find an average. A website can loop through a list of messages to display them, and a game can update every moving object once per frame. In each case, the repeated action follows the same pattern but works on different data.
Keep exploring
Other languages
Loading MyLeoNes™…