Summary: A while loop evaluates its test expression before executing the body of the loop.
A while loop repeats as long as a given condition remains true. It consists of the while keyword followed by a test expression in parentheses and a loop body, as shown in Figure 3.1. The “test expression” can be any C expression and is evaluated before the loop body is executed. The loop body is a single statement or a statement block that executes once every time the loop is iterated. The distinguishing feature of a while loop is that it evaluates the test expression before it executes the loop body, unlike the do loop, which we'll examine next.
We've incorporated the simple while loop from Figure 3.1 in the WHILE.C program, shown below.
/* WHILE.C: Demonstrate while loop. */
#include <stdio.h>
main()
{
int test = 10;
while( test > 0 )
{
printf( "test = %d\n", test );
test = test - 2;
}
}
Here is the output from WHILE.C:
test = 10
test = 8
test = 6
test = 4
test = 2
In WHILE.C, if the variable test is positive when the loop begins, the test expression evaluates as true and the loop executes. If test has a 0 or negative value when the loop starts, the test expression is false; the loop body does not execute and the action falls through to the statement that follows the loop.
(Chapter 6, “Operators,” explains true and false values. For now, it's enough to know that an expression is evaluated as false if it equals 0. Any nonzero value is true.)
The loop body in WHILE.C happens to be a statement block enclosed in braces. If the loop body is a single statement, as in the following code, no braces are needed.
main()
{
int test = 10;
while( test > 0 )
test = test - 2;
}
Occasionally, you'll see a while loop with a test expression such as
while( 1 )
or
#define TRUE 1
.
.
.
while( TRUE )
The test expressions above are always true, creating an indefinite loop that never ends naturally. You can only terminate this kind of loop with some overt action, usually by executing a break statement. (See “The break Statement” later in this chapter.) You can use such a loop to repeat an action for an indefinite time period—until a certain key is pressed, for instance.