The while Loop
A
while loop repeats a block of statements for as long as a Boolean expression is true. The loop below loads boxes onto a shelf that holds 30 kilograms. The first box weighs 2 kilograms, and each box is 2 kilograms heavier than the one before.Loading the shelf
int box = 2;
int load = 0;
while (load + box <= 30)
{
load = load + box;
box = box + 2;
}
Java checks
load + box <= 30 before every pass through the body. The table shows the values at each check.check box load load + box fits
first 2 0 2 yes
second 4 2 6 yes
third 6 6 12 yes
fourth 8 12 20 yes
fifth 10 20 30 yes
sixth 12 30 42 no
So there are five passes and six checks, because this loop stops only when a check comes out false. After the sixth check,
load holds 30 and box holds 12. That 12-kilogram box is the next one in line, and it never went on the shelf.Zero passes
Since the check comes before even the opening pass, a loop can end before its body ever runs. With
int box = 35; on the first line, load + box <= 30 is false at the first check. The body is skipped, load stays 0, and the program continues after the loop.Counting and accumulating
The variable
load is an accumulator: each pass adds the current box's weight to it. A counter goes up by a fixed amount instead, usually 1, to record how many times something happened. Adding one to the shelf loop counts the boxes.int box = 2;
int load = 0;
int boxes = 0;
while (load + box <= 30)
{
load = load + box;
box = box + 2;
boxes = boxes + 1;
}
After the loop,
boxes is 5 and load is 30. Both start at 0 before the loop, since each pass adds to whatever they already hold.The order inside the body
The body runs from top to bottom on every pass, so the order of its statements matters. Swap the first two lines of the original body.
while (load + box <= 30)
{
box = box + 2;
load = load + box;
}
Now each pass makes the box heavier before adding it. The weights added are 4, 6, 8, and 10, for a load of 28. At the next check,
load + box is 38, so the loop ends. The 2-kilogram box is never added, and the shelf ends 2 kilograms short of the first version.