Loops: for, while and do-while
At opening time the barista wants the till to print ticket numbers 1 to 20, and later to keep taking orders until the "closed" key is pressed. The first job has a known count; the second does not. Java has a loop shaped for each.
The rule
Know the count, use for; know the stop condition, use while.
A for loop packs the counter's start, test and step into one line:
for (int ticket = 1; ticket <= 20; ticket++) {
System.out.println("Ticket " + ticket);
}It runs in a fixed rhythm: initialise once, then test → body → step, repeated until the test is false.
A while loop repeats as long as its condition holds, and is ideal when you cannot know the count in advance:
int stockCups = 30;
while (stockCups > 0) {
stockCups -= 4; // serve a table of four
}A do-while loop tests at the bottom, so its body always runs at least once, which is handy for "show the menu, then ask whether to continue":
do {
showMenu();
} while (wantsMore());When you just want every element of an array or list, the enhanced for reads best: for (int price : pricesCents) { ... }.
Two keywords adjust a loop from inside:
breakleaves the loop immediately.continueskips the rest of this pass and moves on to the next one.
The shortcut
For any for loop, write down the values the counter takes before touching the body. Start value, then keep stepping while the test is true. The length of that list is the number of passes.
Start
ibegins at 0.
The classic trap is the off-by-one: mixing < and <= and doing one pass too many or too few. Listing the counter's values catches it at once.
Drills
Answer fast — trust the rule.
What does for (int i = 0; i < 3; i++) System.out.print(i); print?
What does int i = 5; do { System.out.print(i); i++; } while (i < 3); print?
What does for (int i = 1; i <= 5; i++) { if (i % 2 == 0) continue; System.out.print(i); } print?
In the while (stockCups > 0) example starting at 30 and serving 4 cups a pass, what is stockCups when the loop ends?
Remember
- Know the count, use for; know the stop condition, use while; must run once, use do-while.
- List the counter's values to count the passes.
- Traps: off-by-one with
<versus<=, and forgetting that the last pass can overshoot.
