Professional Documents
Culture Documents
3.5. The While Loop
3.5. The While Loop
Here's a simple example in which a while is used to print the alphabet. In this program, ch
is initialized to the letter a. Each time through the loop, ch is output and then
incremented. This process continues until ch is greater than z.
As with the for loop, the while checks the conditional expression at the top of the loop,
which means that the loop code may not execute at all. This eliminates the need for
performing a separate test before the loop.
The following program illustrates this characteristic of the while loop. It computes the
integer powers of 2, from 0 to 9. Notice that the while loop executes only when e is
greater than 0. Thus, when e is zero, as it is in the first iteration of the for loop, the while
loop is skipped.
This is the output from the program:
Summary
In this lesson, you learned that the general form of the while loop is:
while(condition) statement;
You also learned that the condition may be any valid Boolean expression. As long as the
condition is true the loop will repeat. Program control will pass to the code immediately
following the loop when the condition becomes false.