while and do-while
What you'll learn:
- repeat code with
while,do-whileandforloops and pick the right loop for a task; - predict how many times a loop body runs and in which order the parts of a
forheader work; - tell
i++from++iwhen their value goes on into an expression; - skip an iteration with
continue, leave a loop withbreak, and leave two loops at once with a label.
Picture a runner at a stadium. The coach has told them: "Run laps until you have run three." Next to the start there is a board with the lap number.
Before each lap the runner looks at the board: if the number is no more than three, they run that lap. After the lap the number on the board goes up by one. When it gets past three, the runner leaves the track.
Programs also keep repeating the same thing: print a hundred lines, add up a thousand numbers, divide a number by 10 while something is left of it. Writing a hundred identical statements in a row is slow, and often impossible: you don't know in advance how many repeats you need. That is what a loop is for: a construct that runs a block of code again and again while its condition is true.
Here is the runner from the example, written in Java:
public class Main {
public static void main(String[] args) {
int lap = 1;
while (lap <= 3) {
System.out.print(lap + " "); // 1 2 3
lap++;
}
}
}Let's go through the program line by line:
int lap = 1;: the board shows the number of the first lap.while (lap <= 3)checks the condition.1 <= 3is true, so the block in braces runs.System.out.print(lap + " ")prints the lap number and a space.lap++adds one tolap: the lap is done, and the board shows2.- Execution goes back to
whileand checks the condition again. For2and3everything repeats, and whenlapis4, the condition4 <= 3is false and the loop ends.
The program prints 1 2 3.
How while works
A while loop has three parts:
- the keyword
while, which reads as plain English; - a condition in parentheses: as in
if, it must have the typeboolean; - the loop body: a block in braces that repeats.
One pass through the body is called an iteration. The example makes three iterations: for lap equal to 1, 2 and 3.
while always works in the same order:
- Check the condition.
- If it is true, run the body and go back to step 1.
- If it is false, move on to the statement after the loop.
The condition is checked before every iteration, the first one included. If it is false from the start, the body never runs at all. The runner looked at the board, saw 4 there and did not even step onto the track.
For the loop to end some day, the body must change what the condition checks. In the example, lap++ does that.
do-while: the lap first, then the check
while has a relative that checks the condition at the end. It is written like this: do { body } while (condition);. The parts of this construct:
- the keyword
doopens the body; - the body in braces;
whilewith a condition in parentheses after the closing brace of the body;- a semicolon at the end: the whole construct is one statement.
The order here is reversed: the body first, then the check. That is why the body of a do-while runs at least once, even if the condition is false from the start. This is the main difference from while, and interviewers like to ask about it.
At the stadium this is how the warm-up lap works: the runner runs it straight away and looks at the board only afterwards.
Where is this needed? For example, when counting the digits of a number. You divide the number by 10 and count the divisions until it becomes zero:
int n = 4096;
int digits = 0;
do {
digits++;
n = n / 10;
} while (n != 0);
System.out.println(digits); // 4Integer division drops the last digit, so n goes like this: 4096, 409, 40, 4, 0. The body ran four times, and digits is 4.
Now take n equal to 0. Zero is written with one digit, and do-while gets this right: the body runs once, digits becomes 1, and the condition 0 != 0 is false. A while with the same condition gets it wrong:
int n = 0;
int digits = 0;
while (n != 0) {
digits++;
n = n / 10;
}
System.out.println(digits); // 0while checked the condition before the first iteration, saw that 0 != 0 is false and never ran the body. Hence the rule for choosing:
while: when the body may not be needed at all;do-while: when the body must run at least once, and whether to repeat it depends on its result.
Common mistake
The body does not change the variable from the condition:
int lap = 1;
while (lap <= 3) { // ✗
System.out.print(lap + " ");
}lap always equals 1, the condition 1 <= 3 is always true, and the program prints 1 1 1 … forever. Such a loop is called infinite. The program will not stop on its own: in a terminal you interrupt it with the Ctrl+C key combination.
This is where the stadium picture parts ways with Java. A real runner gets tired sooner or later and leaves the track on their own. A loop never gets tired: if nobody changes the number on the board, it runs forever. Add lap++; at the end of the body, and the loop prints 1 2 3.
Key points
whilechecks the condition before each iteration, so the body may not run at all.do-whilechecks the condition after the body, so the body runs at least once; the construct ends with;.- The loop body must change what the condition checks, or the loop becomes infinite.