| Applying science to business management |
  
for
Like while and do/while, the for statement
is used to create an execution loop. A loop usually contains an
initialization expression that sets the initial value of a
counter, an expression that tests the counter value, and an
incrementing expression that alters the counter. Using while, the initialization and
incrementing expressions are not part of the basic statement
syntax. Instead, they are separate statements. The for
statement simply integrates these additional statements into a
single composite statement. For has the format
for( initialize; test;
increment )
statement
This is identical to the while statement
initialize ;
while( test ) {
statement
increment ;
}
For example, code that sums the square of all integers between
1 and 10 can be created using for as follows:
var total=0,n;
for(n=1; n<=10; n++)
total+=n*n;
The for statement does not provide any functionality
that you cannot accomplish using while;
it just allows you to create code that is a bit more structured.
For this reason, for is the statement you will use most
often to create program loops.
See Also
Loop Primitives
|