|
|
|
|
|
|
|
Just like the condition in an If statement, the condition in a While statement can be an expression of any simple data type. Nearly always, it is a logical (Boolean) expression. The While statement says, If the value of the expression is nonzero (TRUE), execute the body and then go back and test the expression again. If the expression's value is zero (FALSE), skip the body. So the loop body is executed over and over as long as the expression is TRUE when it is tested. When the expression is FALSE, the program skips the body and execution continues at the statement immediately following the loop. Of course, if the expression is FALSE to begin with, the body is not even executed. Figure 6-1 shows the flow of control of the While statement, where Statement1 is the body of the loop and Statement2 is the statement following the loop. |
|
|
|
|
|
|
|
|
The body of a loop can be a compound statement (block), which allows us to execute any group of statements repeatedly. Most often you'll use While loops in the following form: |
|
|
|
|
|
|
|
|
while (Expression)
{
.
.
.
} |
|
|
|
|
|
|
|
|
In this structure, if the expression is TRUE, the entire sequence of statements in the block is executed, and then the expression is checked again. If it is still TRUE, the statements are executed again. The cycle continues until the expression becomes FALSE. |
|
|
|
|
|
|
|
|
Figure 6-1
While Statement Flow of Control |
|
|
|
|
|