Tino APCS

The while Loop

The general form of a while statement is:

while (expression){
  statement;
}


As in the if-else control structure, the boolean expression must be enclosed in parentheses ().

The statement executed by the while loop can be a simple statement, or a compound statement blocked with braces {}.

If the expression is true, the statement is executed. After execution of the statement, program control returns to the top of the while construct. The statement will continue to be executed until the expression evaluates to false.

The following diagram illustrates the flow of control in a while loop:


The following loop will print out the integers from 1-10.

int number = 1;               // initialize

while (number <= 10){         // loop boundary condition
  System.out.println(number);
  number++;                   // increment/decrement
}


The above example has three key lines that need emphasis.

You must initialize the loop control variable. If you do not initialize number, Java produces an error message warning you that the variable may not have been initialized.

The loop boundary conditional test (number <= 10) is often a source of error. Make sure that you have the correct comparison (<, >, ==, <=, >=, !=) and that the boundary value is correct. Programmers have to ensure that the loop is executed exactly the correct number of times. Performing the loop one too many or one too few times is called an OBOB , Off By One Bug.

There must be some type of increment/decrement or other statement so that execution of the loop eventually terminates, otherwise the program will get stuck in an infinite loop and never end!

It is possible for the body of a while loop to execute zero times. The while loop is an entry check loop. If the condition is false due to some initial value, the statement inside of the while loop will never happen. This is appropriate in some cases.

Last modified: December 12, 2022

Dark Mode

Outline