In C, there is a set of control flow statements that can be divided into two categories: looping and conditional
branching.
The for, while, and do-while Loops
The general form of the for statement is
for (expression1; expression2; expression3) {
statement1;
statement2;
.
.
.
}
The for statement first evaluates expression1, which is usually an expression that initializes one or more variables.
The second expression, expression2, is the conditional part that is evaluated and tested by the for statement for each
looping. If expression2 returns a nonzero value, the statements within the braces, such as statement1 and statement2,
are executed. Usually, the nonzero value is 1 (one). If expression2 returns 0 (zero), the looping is stopped and the
execution of the for statement is finished. The third expression in the for statement, expression3, is evaluated after
each looping before the statement goes back to test expression2 again.
The following for statement makes an infinite loop:
for ( ; ; ){
/* statement block */
}
The general form of the while statement is
while (expression) {
statement1;
statement2;
.
.
.
}
Here expression is the field of the expression in the while statement. The expression is evaluated first. If it returns a
nonzero value, the looping continues; that is, the statements inside the statement block, such as statement1 and
statement2, are executed. After the execution, the expression is evaluated again. Then the statements are executed one
more time if the expression still returns a nonzero value. The process is repeated over and over until the expression
returns zero.
You can also make a while loop infinite by putting 1 (one) in the expression field like this:
while (1) {
/* statement block */
}
The general form for the do-while statement is
do {
statement1;
statement2;
.
.
.
} while (expression);
Here expression is the field for the expression that is evaluated in order to determine whether the statements inside the
statement block are executed one more time. If the expression returns a nonzero value, the do-while loop continues;
otherwise, the looping stops. Note that the do-while statement ends with a semicolon, which is an important
distinction. The statements controlled by the do-while statement are executed at least once before the expression is
evaluated. Note that a do-while loop ends with a semicolon (;).
Friday, October 16, 2009
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment