for loop
SYNTAX
for (
initialization ;
test ;
increment) {
statements ;
}
OR
for (
initialization ;
test ;
increment)
statement ;
PROGRAM FLOW
- The initialization is first executed. This is typically
something like
int i=0
, which creates a new variable with
initial value 0, to act as a counter. Variables that you declare in this
part of the for loop cease to exist after the execution of the loop is
completed. Multiple, comma separated, expressions are allowed in the
initialization section. But declaration expressions may not be mixed with
other expressions.
- The boolean expression test is then evaluated.
This is typically something like
i<10
. Multiple,
comma separated, expressions are not allowed. If test
evaluates to true, flow contiues to step 3. Otherwise the loop exits.
- The statement(s) are executed.
- Then the statement increment is executed. It is typically
something like
i++
, which increments i
by one or
i+=2
, which increments i
by two. Multiple,
comma separated, expressions are allowed in the increment section.
- Flow returns to step 2.
EXAMPLE
The following example computes an approximate value for the integral
of f(x) from x1 to x2 using nsteps steps of the trapezoidal rule.
double dx = (x2-x1)/nsteps ;
double x = x1+dx ;
double integral = 0 ;
for (int i=1 ; i< nsteps ; i++, x+= dx) {
integral += f(x) ;
}
integral = dx*(integral +( f(x1)+f(x2) )/2) ;
COMMON ERRORS
Putting a semicolon after the closing ) as in
for (initialization ; test ; increment) ;
statement ;
terminates the for loop immediatley. statement is NOT PART OF THE
LOOP. If you find you are plagued by this problem, try always using the
multiple statement format even if you have just one statement in the
loop body.
David Maxwell,
who is still writing this, would like to
hear your comments and suggestions.