for

Syntax for identifier = expression1 to expression2

statements

or,

for identifier = expression1 downto expression2

statements

Action Evaluates expression1 and expression2 as numeric values, and assigns the result of expression1 to identifier.

As long as the value of identifier is less than or equal to the result of expression2, for does the following:

1. executes statements;

2. adds 1 to the value of identifier.

In the second form, using the downto keyword, statements are executed as long as the value of identifier is greater than or equal to the result of expression2, and 1 is subtracted from the value of identifier each time through the loop.

Examples for i = 1 to sizeOf (root) {
msg (nameOf (root [i]));

clock.waitSixtieths (30)}

It posts the name of each item in the root table to the Main Window, pausing a half-second between each one.

for i = 3 to 2
{msg ("This statement will not be executed")}

for i = 3 downto 2
{msg ("This statement will be executed twice")}

Notes If the result of expression1 is greater than that of expression2, the loop body will not be executed even once.

The action of the for statement is almost identical to the following loop statement:

loop (identifier = expression1; identifier <= expression2; ++identifier)

statements

However in the for statement, the expressions are always evaluated as numbers, and expression2 is evaluated once before entering the loop, rather than for each iteration. This gives the for statement a substantial performance advantage.

See Also for ... in

loop

while

break

continue

Discuss