maximum limit.
A while loop executes zero or more times since the expression might be false the first time it is evaluated.
Sometimes you want to execute a loop body at least once, which is why you also have a dowhile loop:
do
statement
while (expression);
Here, the expression is evaluated after the statement is executed. While the expression is true, the statement
is executed repeatedly. The statement in a dowhile loop is almost always a block.
Exercise 10.4: Select a few previous exercise solutions for which you have used a for loop and rewrite it
using a while loop. Can you also rewrite it using a dowhile loop? Would you do so? If not, why not?
10.5. for
The for statement comes in two forms: a basic and an enhanced form. The basic form is the more general
and powerful of the two.
10.5.1. Basic for Statement
You use the basic for statement to loop over a range of values from beginning to end. It looks like this:
for (initialization-expression;
loop-expression;
update-expression)
statement
The initialization-expression allows you to declare and/or initialize loop variables, and is
executed only once. Then the loop-expressionof boolean or Boolean typeis evaluated and if it is
true the statement in the body of the loop is executed. After executing the loop body, the
update-expression is evaluated, usually to update the values of the loop variables, and then the
loop-expression is reevaluated. This cycle repeats until the loop-expression is found to be
false. This is roughly equivalent to
{
initialization-expression;
while (loop-expression) {
statement
update-expression;
}
}
except that in a for statement the update-expression is always executed if a continue is
encountered in the loop body (see "continue" on page 244).
The initialization and update parts of a for loop can be comma-separated lists of expressions. The
expressions separated by the commas are, like most operator operands, evaluated from left-to-right. For