MODULE 2 • LESSON 08
Computers are valuable because they repeat work quickly and without getting bored. Adding up 5 000 sales, checking every student’s mark, or asking for a password until it is right all need the same steps carried out again and again. The construct that does this is iteration (also called repetition or looping), the third control structure of structured programming.
In this lesson you will meet the two families of loops in the syllabus: bounded loops, which run a fixed number of times, and unbounded loops, which run until a condition changes, often when a special sentinel value is entered. You will run all three loop forms (FOR, WHILE and REPEAT … UNTIL) in a loop lab, feed data to a sentinel-controlled statistics machine, and write each loop in C.
What you will learn
- What iteration is, and the vocabulary used to describe loops.
- How a bounded (fixed-count) FOR loop works, and how to count its passes.
- How unbounded loops work: pre-test WHILE and post-test REPEAT … UNTIL.
- What a sentinel value is, and how to write a sentinel-controlled loop correctly.
- Standard loop patterns: counting, totalling, averages, highest and lowest, input validation.
- How to choose the right loop and avoid off-by-one, infinite and sentinel errors.
- How to write for, while and do … while loops in C.
Part 1: Loop vocabulary
| Term | Meaning |
| Iteration | One pass through the loop body; also the name of the construct as a whole. |
| Loop body | The statements that are repeated. |
| Loop control variable | The variable whose value decides whether the loop continues (for example i, or the input x). |
| Counter | A variable that goes up by a fixed amount each pass: count ← count + 1. |
| Accumulator | A variable that builds up a total: total ← total + x. |
| Sentinel (rogue value) | A special input value that is not real data and signals the end of the data, such as -1 or “XXX”. |
| Pre-test loop | The condition is tested before each pass, so the body may run zero times (WHILE). |
| Post-test loop | The condition is tested after each pass, so the body always runs at least once (REPEAT … UNTIL). |
| Bounded loop | The number of passes is known before the loop starts (FOR). |
| Unbounded loop | The number of passes is not known in advance; it depends on a condition or a sentinel. |
Part 2: Bounded iteration: the FOR loop
Use a bounded loop when you know, before the loop starts, how many times it must run: 30 students, 12 months, n items where n has already been input. The FOR loop manages a counter for you: it sets the start value, tests it against the end value, and adds the step after each pass.
total ← 0 FOR i ← 1 TO n total ← total + i ENDFOR OUTPUT total
With n = 4 the body runs for i = 1, 2, 3 and 4, and the output is 10. The number of passes for FOR i ← a TO b (step 1) is b − a + 1: from 1 to 4 is 4 passes, from 3 to 7 is 5 passes. If b is less than a, the body does not run at all.
A STEP changes the amount added each time. FOR k ← 2 TO 8 STEP 2 gives k = 2, 4, 6, 8. FOR k ← 10 TO 1 STEP -1 counts down. Worked example: what does FOR k ← 1 TO 4: OUTPUT k * 3 output? The loop runs for k = 1, 2, 3, 4, so the output is 3 6 9 12. In exams, write each pass out rather than guessing.
A flowchart has no special FOR symbol. A counted loop is drawn as initialise the counter, test it in a diamond, run the body, add to the counter, and go back to the test:
In C the three parts of the counter (start, test, step) go in one line: for (i = 1; i <= n; i++). Remember that i++ means i = i + 1.
Part 3: Unbounded iteration: the WHILE loop
Often you cannot know in advance how many passes are needed: a teacher may have 12 marks today and 31 tomorrow, a file may hold any number of records, a user may need several tries to type a valid date. An unbounded loop keeps going while a condition is True.
The WHILE loop is a pre-test loop: it checks the condition before each pass. If the condition is False the very first time, the body never runs.
Sentinel-controlled loops
A sentinel is a value chosen to mark the end of the data. It must be a value that can never be real data: -1 for marks, 0 for a quantity, “XXX” for a name. The correct pattern has two INPUT statements:
total ← 0 INPUT x WHILE x <> -1 DO total ← total + x INPUT x ENDWHILE OUTPUT total
Line 2 is the first (or priming) read. Line 4 processes the value. Line 5 reads the next value at the end of the body.
The first INPUT gives the condition something to test. The second, at the very end of the body, reads the next value so that the condition is tested again before that value is processed. That ordering is what stops the sentinel from being added to the total.
Not every unbounded loop uses a sentinel. A condition-controlled loop can stop when a calculated value reaches a target, for example “double the savings each year WHILE savings < 10000”. The idea is the same: the number of passes depends on the data, not on a fixed count.
Part 4: Unbounded iteration: REPEAT … UNTIL
The REPEAT … UNTIL loop is a post-test loop: the body runs first, then the condition is tested. So the body always runs at least once, and the loop stops when the condition becomes True (the opposite of WHILE, which continues while its condition is True).
REPEAT OUTPUT "Choose 1 to 3: " INPUT choice UNTIL choice >= 1 AND choice <= 3
This is ideal for input validation: you must ask at least once, and you keep asking until the answer is acceptable. In a flowchart, the decision comes at the bottom and the No path goes back up to the top of the body:
Be careful using REPEAT for sentinel data. A naive version reads the value and adds it before testing, so the sentinel itself is added to the total. You can see this in the loop lab below.
In C the post-test loop is do { … } while (condition);. C continues while the condition is True, so you write the opposite of the UNTIL condition: UNTIL choice is valid becomes while (choice < 1 || choice > 3).
Try it 1Loop lab
Choose a loop. For FOR, change n. For WHILE and REPEAT, add values to the input queue (they go in before the -1 sentinel). Tap Next to go one step at a time. Then try Only the sentinel with WHILE and with REPEAT and compare the totals.
With only the sentinel, the WHILE loop runs zero times and outputs 0, which is correct. The REPEAT loop runs once, adds -1 and outputs -1, which is wrong. The post-test loop is the right tool for validation, but sentinel data is safer with a pre-test WHILE.
Part 5: Standard loop patterns
Most loops you will write in exams are one of a handful of patterns. They all follow the same rule: initialise before the loop, update inside the loop, use the result after the loop.
| Pattern | Before the loop | Inside the loop | After the loop |
| Counting | count ← 0 | count ← count + 1 | OUTPUT count |
| Totalling | total ← 0 | total ← total + x | OUTPUT total |
| Average | count ← 0, total ← 0 | update both | IF count > 0 THEN avg ← total / count |
| Highest | highest ← first value (or a very low value) | IF x > highest THEN highest ← x | OUTPUT highest |
| Lowest | lowest ← first value (or a very high value) | IF x < lowest THEN lowest ← x | OUTPUT lowest |
| Conditional count | passes ← 0 | IF x >= 50 THEN passes ← passes + 1 | OUTPUT passes |
Notice that selection often sits inside a loop. Combining constructs like this is what makes real algorithms. Two warnings: if you put total ← 0 inside the loop, the total is wiped on every pass; and an average must check that count is not 0 before dividing.
Try it 2Sentinel statistics machine
This loop reads temperatures until -1 is entered. Tap values to feed them in, then tap -1 (stop). Watch the counter, accumulator, highest and lowest update. Then switch on the faulty version, which processes the value before checking for the sentinel, and run the same data again.
Part 6: Choosing a loop, and common mistakes
| Situation | Best loop | Why |
| Number of passes known before the loop | FOR | The counter is handled for you; no risk of forgetting to increase it. |
| Unknown amount of data ending with a sentinel | WHILE with a priming read | Handles the case of no data; never processes the sentinel. |
| Must run at least once, e.g. validation or a menu | REPEAT … UNTIL | The question is always asked before the answer is checked. |
| Stop when a calculated value reaches a target | WHILE | The condition is checked before each pass. |
Common loop errors to look for when you trace:
- Off-by-one: using < when you meant <=, so the loop runs one pass too few (or too many).
- Infinite loop: nothing inside the loop changes the loop control variable, or it skips past the end value (Lesson 04).
- Missing second input: in a sentinel WHILE loop, forgetting the INPUT at the end of the body, so the same value is processed for ever.
- Processing the sentinel: adding or counting the sentinel as if it were data.
- Initialising inside the loop: resetting total or count to 0 on every pass.
- Dividing by zero: calculating an average when no data was entered.
Loops can also be nested: a loop inside a loop. The inner loop runs completely for each pass of the outer loop, so FOR row ← 1 TO 3 containing FOR col ← 1 TO 4 runs the inner body 3 × 4 = 12 times. You will use nested loops for tables and grids later in the course.
Part 7: Loops in C
A bounded for loop that prints the first five lines of a times table:
#include <stdio.h>
int main(void)
{
int n, i;
printf("Times table for: ");
scanf("%d", &n);
printf("\n");
for (i = 1; i <= 5; i++) {
printf("%d x %d = %d\n",
n, i, n * i);
}
return 0;
}
Sample input: 7
Output:
Times table for: 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
A sentinel-controlled while loop with the priming read, a counter, an accumulator and a check before dividing. The (float) makes the division keep its fraction.
#include <stdio.h>
int main(void)
{
int mark, count = 0, total = 0;
printf("Type -1 to stop.\n");
printf("Mark: ");
scanf("%d", &mark);
while (mark != -1) {
count = count + 1;
total = total + mark;
printf("Mark: ");
scanf("%d", &mark);
}
printf("\n");
if (count > 0) {
printf("Count: %d\n", count);
printf("Average: %.1f\n",
(float) total / count);
} else {
printf("No marks entered\n");
}
return 0;
}
Sample input: 60 75 90 -1
Output:
Type -1 to stop. Mark: Mark: Mark: Mark: Count: 3 Average: 75.0
A post-test do … while loop for validation. Given the inputs 0, 9 and then 2, it asks three times and accepts 2:
#include <stdio.h>
int main(void)
{
int choice;
printf("Choose 1 to 3.\n");
do {
printf("Choice: ");
scanf("%d", &choice);
} while (choice < 1 || choice > 3);
printf("\nYou chose %d\n", choice);
return 0;
}
Sample input: 0 9 2
Output:
Choose 1 to 3. Choice: Choice: Choice: You chose 2
Try it 3Loop practice
Pick a mode. "Which loop?" gives a situation. "Count the passes" asks how many times a loop body runs (or the final total). Tap New question for another.
Summary
| Idea | Remember |
| Bounded (FOR) | Number of passes known in advance: b − a + 1 for FOR i ← a TO b. |
| Unbounded, pre-test (WHILE) | Test first; may run 0 times; continues while the condition is True. |
| Unbounded, post-test (REPEAT … UNTIL) | Test last; runs at least once; stops when the condition is True. |
| Sentinel | An end-of-data value that is never real data. Read once before the loop and again at the end of the body. |
| Patterns | Initialise before, update inside, use after: counting, totalling, average, highest, lowest. |
| C | for (i = 1; i <= n; i++), while (x != -1), do { } while (cond); |
Review questions
1. Distinguish between bounded and unbounded iteration, giving an example of each.
Show answer
In bounded iteration the number of passes is known before the loop starts (e.g. FOR i ← 1 TO 30 to read 30 marks). In unbounded iteration it is not known in advance and depends on a condition (e.g. WHILE mark <> -1 to read marks until a sentinel is entered).
2. What is a sentinel value? Give a suitable sentinel for a loop that reads ages.
Show answer
A special value, not valid as real data, that signals the end of the input and stops the loop. For ages, -1 (or 999) is suitable because no one has that age.
3. How many times does the body of FOR k ← 4 TO 11 run? What does FOR k ← 1 TO 5: OUTPUT k * k output?
Show answer
11 − 4 + 1 = 8 times. The output is 1 4 9 16 25.
4. Explain why a sentinel-controlled WHILE loop needs an INPUT both before the loop and at the end of the body.
Show answer
The first INPUT gives the condition a value to test. The INPUT at the end reads the next value so that it is tested before it is processed. Without the first, the condition tests an unset value; without the second, the same value is processed for ever; reading at the start of the body instead would process the sentinel.
5. State ONE difference between a WHILE loop and a REPEAT … UNTIL loop.
Show answer
WHILE tests before each pass, so its body may run zero times; REPEAT tests after each pass, so its body runs at least once. (Also: WHILE continues while its condition is True; REPEAT stops when its condition becomes True.)
6. Trace and give the output: x ← 9; y ← 2; WHILE x > y DO x ← x - 2; y ← y + 1; OUTPUT x, y ENDWHILE
Show answer
Pass 1: x = 7, y = 3, output 7 3. Pass 2: x = 5, y = 4, output 5 4. Test 5 > 4 True, pass 3: x = 3, y = 5, output 3 5. Test 3 > 5 False, stop. Output: 7 3, 5 4, 3 5.
7. Write pseudocode that reads numbers until 0 is entered and outputs the largest.
Show answer
INPUT x
highest ← x
WHILE x <> 0 DO
IF x > highest THEN highest ← x ENDIF
INPUT x
ENDWHILE
OUTPUT highest
(If the first value is 0 there is no data; a full answer would output a message instead.)
8. Which type of loop should be used to read records from a file when the number of records is not known? Explain.
Show answer
An unbounded, condition-controlled loop (WHILE NOT end of file, or a sentinel-controlled loop), because the number of passes cannot be known before the loop starts. A FOR loop needs a known count.
Homework
- Write pseudocode, a flowchart and a C program that read the number of goals scored in each of a team’s 10 matches and output the total and the average. Which kind of loop did you use, and why?
- Change your program so that the number of matches is not known: the coach types -1 to finish. Make sure it handles the case where -1 is the very first input.
- Write a REPEAT … UNTIL loop that keeps asking for a password until it equals "ic2026" or three attempts have been made. Then write it in C with do … while.
- Trace
total ← 0; FOR i ← 1 TO 6 STEP 2: total ← total + i * iin a trace table. What is the final total? - In Try it 2, use the faulty version with the data 12, 27, 31, 8. Write down the count, total and average it gives, and explain each error.
Mastery quiz: Loops
This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.
Mastery quiz: Loops: Bounded and Unbounded Iteration
Your course badges: loading saved progress…
View badges
No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.
Saved in this browser on this device. Clearing browser data may remove your badges.
Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.
Exam tips
Specimen Unit 1 Paper 01 (2021), Items 17 and 18. Recognising a counted loop as bounded iteration, and working out what it outputs. List each value of the counter and apply the output statement to each one.
Specimen Unit 1 Paper 01 (2021), Items 20 and 23. What a sentinel is, and which loop to use when the number of records is unknown. Key phrases: "signals the end of the data" and "unbounded / sentinel-controlled".
Specimen Unit 1 Paper 01 (2021), Items 25 and 26. Recognising a test-first (pre-test) WHILE loop and an increment statement. Know the words pre-test/test-first and post-test/test-last.
CAPE 2012 Unit 1 Paper 02, Question 3(b). Classifying loops as bounded or unbounded and justifying the answer. The justification is "the number of passes is fixed / known in advance" versus "depends on a sentinel or condition". A worked answer is linked in the Go further box.
CAPE 2024 Unit 1 Paper 02, Question 4(d). A trace table for a WHILE loop. Write one row per pass, and stop when the test fails. Do not write a row for a pass that never happens.
More worked answers are on the CS Solutions page.
Previous: Module 2 • Lesson 07 – Selection: IF-THEN, IF-THEN-ELSE and Nested IF. Next: Module 2 • Lesson 09 – Tracing Algorithms: Trace Tables, Test Plans and Correctness.
Syllabus link: CAPE Computer Science (CXC A19/U2/21), Problem-Solving with Computers (Unit 1, Module 2). Specific Objective 6: explain constructs used in structured programming (the control structure iteration or repetition: bounded, for example a fixed number of iterations, and unbounded, for example sentinel control).
Video search terms
Search YouTube for: "sentinel controlled loop", "bounded vs unbounded iteration", "while vs do while in C", "pre-test vs post-test loop".
Try it 4Quick quiz
Tap an answer. All eight questions are self-checks on this lesson.
Updates
2026/12/01
- Updated the copyright line.
- Published. Previous/Next links and the mastery quiz links now use the full lesson addresses.
- Small script tidy-up for the site (no change to how the activities work).
2026/11/24
- Linked Previous/Next and the mastery quiz URLs to draft shortlinks (?p=ID), which will redirect to the permalink after publish.
- First version of the lesson.
© 2026 islandclass.org
