Iteration Statements
A loop can be expressed as a for, while, or do statement.
For Statement
The for statement has the form:
for ( expression1 ; expression2 ; expression3 ) statement
The for statement executes a statement zero or more times. It uses three control expressions as shown, any of the expressions are optional but the two semicolons must always be specified. The for loop is executed in the following steps:
- Expression1, if specified, is evaluated before the first iteration of the loop, and only once. It usually specifies the initial values for variables.
- Expression2, if specified, is a relational or logical expression that specifies the termination criterion of the loop. Expression2 is evaluated before each iteration. If it is zero, execution of the loop terminates. If it is not zero, the statement is executed.
- Expression3 is evaluated after each iteration. It usually specifies increments for the variables initialized by expression1.
- Iterations of the loop continue until expression2 produces a false (zero) value, or until some statement, such as break or continue, interrupts it.
The for statement is equivalent to:
expression1 ;
while ( expression2 ) { statement expression3 ; }
While Statement
The while statement has the form:
while ( expression ) statement
The expression is evaluated before each execution, and the statement is executed zero or more times, as long as the expression is not zero.
Do Statement
The do statement has the form:
do statement while ( expression ) ;
The statement is executed at least once, and the expression is evaluated after each execution. If the expression is not zero, the statement is executed again.