Programming Algorithms
Senior 4 · ICT
Programming Algorithms
Lesson 5 of 5
25 min
Uwase belongs to an ikimina, a savings group, and puts aside 2 500 Frw every week. She wants 30 000 Frw for a solar lamp. How many weeks will it take? One way is to write "add 2 500" twelve times. But if the target changes to 47 500, the algorithm has to be rewritten. A loop says it once: keep adding 2 500 while the total is below the target. Repetition is where computers beat people: a loop that runs 12 times can just as easily run 12 million times. (The amounts in this lesson are illustrative.)
Definition
Iteration (loop): a control structure that repeats a block of steps, the loop body.
Count-controlled loop (FOR): repeats a set number of times. Condition-controlled loop (WHILE, REPEAT…UNTIL): repeats until a condition changes.
Counter: a variable that counts the passes (count ← count + 1). Accumulator: a variable that builds up a total (total ← total + value). Both must be given a starting value first.
Sentinel: a special input value, such as −1, that is not real data and signals "stop".
Infinite loop: a loop whose stopping condition is never met.
FOR i ← 1 TO n … ENDFOR sets the counter to 1, runs the body, adds 1 to , and repeats until it has run with .
An accumulator inside a FOR loop: it adds the numbers 1 to 5.
Worked example 1: trace the FOR loop
| Pass | i | total after the pass |
|---|---|---|
| before | 0 | |
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
| 4 | 4 | 10 |
| 5 | 5 | 15 |
Output: 15. Check with the formula for the sum of the first whole numbers: . The loop body ran exactly 5 times.
WHILE condition DO … ENDWHILE checks the condition before each pass. If it is TRUE the body runs and the condition is checked again; when it is FALSE the loop ends. If the condition is FALSE at the start, the body never runs at all.
Each pass adds a week's savings and counts the week. The loop stops as soon as saved reaches the target.
Worked example 2: trace the savings loop
| Check | saved < 30000? | saved after the pass | weeks |
|---|---|---|---|
| 1 | 0: Yes | 2 500 | 1 |
| 2 | 2 500: Yes | 5 000 | 2 |
| … | … | … | … |
| 12 | 27 500: Yes | 30 000 | 12 |
| 13 | 30 000: No, exit |
Output: 12 weeks. Check: . The condition was checked 13 times but the body ran 12 times; the last check is the one that stops the loop.
REPEAT … UNTIL condition runs the body, then checks the condition, and stops when it becomes TRUE. The body always runs at least once, which suits anything that must happen before it can be checked, such as asking for input.
A PIN check: the user always gets at least one try, and at most three. The loop stops on a correct PIN or on the third attempt, whichever comes first; the IF after the loop works out which one it was.
When the amount of data is not known in advance, a sentinel ends it: "enter marks, and −1 when you have finished".
The first mark is read before the loop and each next one at the end of the body, so the sentinel −1 is never added to the total. The IF avoids dividing by zero when no marks are entered.
| FOR | WHILE | REPEAT…UNTIL | |
|---|---|---|---|
| Controlled by | a counter | a condition | a condition |
| Condition checked | (counter limit) | before each pass | after each pass |
| Fewest passes | fixed number | 0 | 1 |
| Stops when the condition is | (counter passes the limit) | FALSE | TRUE |
| Use when | the number of repeats is known | it may not need to run at all | it must run at least once |
Press Run. The first loop prints Weeks needed: 12. Then type some marks, for example 60, 75 and 81, and finish with −1; the average is 72.0. Python has while and for but no REPEAT…UNTIL; Unit 4 shows how to get the same effect.
Pseudocode Pro: Iteration, For, While and Repeat Until loops. Watch when each kind of loop is chosen and how a count-controlled loop differs from a condition-controlled one.
Warning
Infinite loops. If nothing inside a WHILE loop changes the condition (for example, forgetting saved ← saved + 2500), the loop never ends. Every loop body must move towards the exit.
Off by one. FOR i ← 0 TO 5 runs 6 times, not 5. Check the first and last values of the counter.
Initialise before the loop. Set counters and totals to 0 before the loop, not inside it, or they restart on every pass.
Tip
Trace the first two passes and the last one. Most loop mistakes happen at the start (wrong initial value) or the end (one pass too many or too few). A trace table with columns for the counter, the condition and each variable shows both.
Practice
x ← 1; FOR i ← 1 TO 4: x ← x * 2; ENDFOR; OUTPUT x.n ← 10; WHILE n > 0 DO OUTPUT n ENDWHILE. Correct it so it counts down 10, 9, …, 1.total ← 0; count ← 0; mark ← 0; WHILE mark ≠ -1 DO INPUT mark; total ← total + mark; count ← count + 1 ENDWHILE; OUTPUT total / count. Trace it with the inputs 60, 80, −1 and evaluate the result.n > 0 stays TRUE: an infinite loop. Add n ← n - 1 after OUTPUT n.Key points
Further reading
Sources and credits
while statement: Compound statements, Python documentation, Python Software Foundation (linked for reference).This lesson adapts CC BY-SA material and is shared under CC BY-SA 4.0.
total ← 0
FOR i ← 1 TO 5
total ← total + i
ENDFOR
OUTPUT totaltarget ← 30000
saved ← 0
weeks ← 0
WHILE saved < target DO
saved ← saved + 2500
weeks ← weeks + 1
ENDWHILE
OUTPUT "Weeks needed: ", weeksattempts ← 0
REPEAT
OUTPUT "Enter PIN:"
INPUT pin
attempts ← attempts + 1
UNTIL pin = correctPIN OR attempts = 3
IF pin = correctPIN THEN
OUTPUT "Welcome"
ELSE
OUTPUT "Card blocked"
ENDIFtotal ← 0
count ← 0
INPUT mark
WHILE mark ≠ -1 DO
total ← total + mark
count ← count + 1
INPUT mark
ENDWHILE
IF count > 0 THEN
OUTPUT "Average: ", total / count
ELSE
OUTPUT "No marks entered"
ENDIF# Loops in Python: the savings loop, then a sentinel loop.
target = 30000
saved = 0
weeks = 0
while saved < target:
saved = saved + 2500
weeks = weeks + 1
print("Weeks needed:", weeks)
total = 0
count = 0
mark = int(input("Mark (-1 to finish): "))
while mark != -1:
total = total + mark
count = count + 1
mark = int(input("Mark (-1 to finish): "))
if count > 0:
print("Average:", total / count)
else:
print("No marks entered")Quick check
Which loop always runs its body at least once?