for Statement

 

The for statement lets you repeat a statement or compound statement a specified number of times. The body of a for statement is executed zero or more times until an optional condition becomes false. 

Syntax

for ( init-expression ; cond-expression ; loop-expression ) statement

Execution of a for statement proceeds as follows:

  1. The init-expression, is evaluated. This specifies the initialization for the loop. There is no restriction on the type of init-expression.

  2. The cond-expression,  is evaluated. This expression must have arithmetic type. It is evaluated before each iteration. Three results are possible:
    • If cond-expression is true (nonzero), statement is executed; then loop-expression, if any, is evaluated. The loop-expression is evaluated after each iteration. There is no restriction on its type. Side effects will execute in order. The process then begins again with the evaluation of cond-expression.

    • If cond-expression is false (0), execution of the for statement terminates and control passes to the next statement in the program.

This example illustrates the for statement:

myema[ 0 ] = Close[ 0 ];
for( i = 1; i < BarCount; i++ )
{
    myema[ i ] =
0.1 * Close[ i ] + 0.9 * myema[ i - 1 ];
}

This example iterates all bars of close array to calculate exponential moving average.

For loop is extremely flexible.

loop-expression can be ANY kind of expression you wish. You can produce not only regular series like this:

for( i = 0; i < BarCount; i = i + 3 ) // increment by 3 every iteration

but you can produce exponential series too:

for( i = 1; i < BarCount; i = i * 2 ) // produces series of 1, 2, 4, 8, 16, 32, ...