while loops


A while loop is a kind of loop, which is a kind of control statement. It is a loop with the test at the top. The syntax is:

while (condition) {

Here's what it does. First, the condition is tested; if it is false, nothing more is done, and the loop is finished without ever executing the statements. If the condition is true, then the statements are executed, then the entire loop (starting with the test) is executed again.

For example, the approximate common log (that is, log base ten) of a number x can be computed by:

int log = 0;
while (x > 1) {
    x = x / 10;
    log = log + 1;

The braces indicate a block of statements. If there is only one statement, the braces may be omitted; however, it is good style to always include the braces.

Normally, the statements controlled by the loop must affect the condition. In the above example, the value of x is tested, and the controlled statements change the value of x. If the controlled statements never make the condition false, then the loop never exits, and the program "hangs" (stops responding). This is a kind of error commonly, if inaccurately, called an infinite loop.

Question: Why was the programmer stuck in the shower for hours?
Answer (select to view): The instructions on the shampoo bottle read "Lather. Rinse. Repeat."

Two additional statement types, break and continue, can also control the behavior of while loops.


The break and continue statements can be used with statement labels.