Sams Teach Yourself C in 21 Days

(singke) #1
Basic Program Control 135

6


You might have noticed that a whilestatement is essentially a forstatement without the
initialization and increment components. Thus,
for ( ; condition; )
is equivalent to
while (condition)
Because of this equality, anything that can be done with a forstatement can also be done
with a whilestatement. When you use a whilestatement, any necessary initialization
must first be performed in a separate statement, and the updating must be performed by a
statement that is part of the whileloop.
When initialization and updating are required, most experienced C programmers prefer
to use a forstatement rather than a whilestatement. This preference is based primarily
on source code readability. When you use a forstatement, the initialization, test, and
increment expressions are located together and are easy to find and modify. With a while
statement, the initialization and update expressions are located separately and might be
less obvious.

ThewhileStatement
while (condition)
statement(s)
conditionis any valid C expression, usually a relational expression. When condition
evaluates to false (zero), the whilestatement terminates, and execution passes to the first
statement following statement(s); otherwise, the first C statement in statement(s)is
executed.
statement(s)is the C statement(s) that is executed as long as conditionremains true.
Awhilestatement is a C looping statement. It allows repeated execution of a statement
or block of statements as long as the condition remains true (nonzero). If the condition is
not true when the whilecommand is first executed, the statement(s)is never executed.
Example 1
int x = 0;
while (x < 10)
{
printf(ā€œ\nThe value of x is %dā€, x );
x++;
}

,


S

YNTAX

,


10 448201x-CH06 8/13/02 11:20 AM Page 135

Free download pdf