Topic 2.7 — while Loops
Goal: write and trace while loops, understand how the loop condition controls repetition,
and avoid common mistakes like infinite loops and off-by-one errors.
The big idea
A while loop repeats a block of code as long as its condition is true.
The condition is checked before each repetition.
Think: “Keep going while this is true.”
Structure
while (condition) {
// repeat while condition is true
}
If the condition starts false, the loop runs 0 times.
Counting loop (classic)
This loop runs a known number of times by updating a counter.
int i = 1;
while (i <= 5) {
sum = sum + i;
i++;
}
- Initialization:
int i = 1; - Condition:
i <= 5 - Update:
i++
Sentinel loop (stop when something happens)
Sometimes you don’t know how many repeats you need. You loop until a “stop signal” is reached.
// Pseudocode-style idea
while (input is not "quit") {
process input
get next input
}
Tracing a while loop (how to do it)
- Check the condition. If false → stop.
- If true → run the body once.
- Make sure something changes so the condition can eventually become false.
- Repeat.
int x = 3;
while (x > 0) {
x--;
}
// Runs 3 times, then x becomes 0
Infinite loop warning
If the loop body never changes anything related to the condition, the loop may never end.
int x = 5;
while (x > 0) {
// x never changes...
}
// infinite loop
Off-by-one errors
Using < vs <= (or starting at 0 vs 1) changes the number of repetitions.
int i = 0;
while (i < 5) { // runs 5 times: i = 0,1,2,3,4
i++;
}
int j = 0;
while (j <= 5) { // runs 6 times: j = 0..5
j++;
}
Exam mindset
- Identify the three parts: initialize → condition → update.
- Condition checked first (so it can run 0 times).
- Watch for infinite loops and off-by-one errors.
- Trace carefully: update happens inside the loop body.
Quick self-check
- When is a while loop condition checked?
- Can a while loop run 0 times? When?
- What causes an infinite loop?
- How many times does this run:
int i=1; while(i<4){i++;}? - What’s an “off-by-one” error?