Introduction to Problem Solving
Repetition
Write a loop that stops at the right time.
Repetition (also called iteration or a loop) runs a set of statements again and again, until a condition is met. In daily life: clap five times, walk 10 steps, skip until you are tired.
When the number of repetitions is known, a counter keeps track of them. For example, to find the total of 3 marks:
- Set count = 0 and total = 0
- WHILE count < 3:
- … INPUT mark
- … total = total + mark
- … count = count + 1
- PRINT total
The counter goes 0, 1, 2, and when it reaches 3 the loop stops, after exactly three runs.
When the number of repetitions is not known in advance, the WHILE construct keeps checking a condition. For example, to add up numbers until the user enters 0:
- INPUT num
- WHILE num is not 0:
- … total = total + num
- … INPUT num
- PRINT total
Notice the two inputs. The input before the loop gives the first value to test. The input inside the loop gets the next value, so the loop can end when 0 arrives.
Every loop must change something inside it, so that its condition eventually becomes false. Otherwise, the loop would never end (an infinite loop).
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.