The for Statement


Syntax

for (statement_initial expression_terminate; expression_loop)
 statement

Notes

Any of the above mentioned inputs to a for statement may be omitted. Providing a vacuous statement_initial means that no initialization is required prior to loop entry. Omitting expression_terminate is equivalent to specifying a constant of 1 (and thus an infinite loop is formed). Omitting expression_loop indicates that no expression evaluation is performed after each loop iteration.

Examples

The following loop adds the numbers 1 to 9 (inclusive).

int j=0;
for (int i=0; i<10; i++) j += i;  // Loop adds numbers 0 - 9, upon exit i==10, j==45.

Notice how the variable i is declared in the initialization section of the for statement. i can be referenced after loop termination because its scope is that of the scope containing the loop.

The following for statement forms an infinite loop that requires a break statement to escape.

int j=0;
int i=0;
for (;;)  // Forever
 {
  j += i;
  i++;
  if (i==10) break;    // Break out of the loop.
 }
 // Loop adds numbers 0 - 9, upon exit i==10, j==45.