B2.3.3 · Programming constructs
Iteration structures
By the end you can
Trace count-controlled (for) and condition-controlled (while, do-while) loops and avoid off-by-one errors.
(looping) allows a block of code to repeat multiple times without duplicating source code. There are two primary categories of iteration: count-controlled and condition-controlled.
Count-controlled loops (for)#
A count-controlled loop repeats a specific number of times known beforehand:
// Standard count-controlled loop
for (int i = 0; i < 10; i++) {
System.out.println(i);
}The loop header contains three parts: initialization (int i = 0), condition (i < 10), and update step (i++). The counter variable advances monotonically until the loop condition fails.
Condition-controlled loops (while and do-while)#
When the number of iterations depends on runtime events (such as reading until end-of-file, or waiting for valid user input), condition-controlled loops are required:
- Pre-test loop (
while): Evaluates the condition before executing the body. If the condition is initially false, the loop body executes 0 times. - Post-test loop (
do - while): Executes the body first, then evaluates the condition at the end. Guarantees execution at least 1 time (ideal for menu selection prompts).
Check yourself
Iteration constructs
Quick questions, made fresh every time and marked here. Do a few until they feel easy.
Exam practice
Paper 1-style questions
3 questions · 8 marks
Write your answer as you would in the exam, then show the mark points and tick each one your answer made. These are our own questions in the style of the exam, not past-paper questions.
1.Compare count-controlled (for) loops and condition-controlled (while / do-while) loops, specifying when each should be used.
[4]Compare: Similarities and differences, about both things, point by point.
2.Explain what causes an infinite loop in a condition-controlled while loop and how it can be prevented.
[2]Explain: Give reasons: say what happens AND why, or how one thing causes another.
3.Distinguish between a pre-condition loop (while) and a post-condition loop (do-while / repeat-until) regarding minimum iterations.
[2]Distinguish: Make the differences between two things clear.
In a nutshell
- Iteration repeats code blocks without duplication: count-controlled (for) and condition-controlled (while, do-while).
- Count-controlled loops execute a predetermined number of iterations using counter variables.
- Pre-test while loops evaluate conditions before executing and may execute 0 times; post-test do-while loops always execute at least once.
- Off-by-one errors occur when loop boundary conditions use < instead of <= or start at index 1 instead of 0.
