The For Loop

From Catglobe Wiki
Revision as of 09:26, 21 March 2011 by Cg pham (talk | contribs)
Jump to: navigation, search



The For Loop

The general form of the for loop for repeating a single statement is:

for (initialization; condition; iteration) statement;

For repeating a block, the general form is:

for (initialization; condition; iteration)

{

Statement sequence

}

The initialization is usually an assignment statement that sets the initial value of the loop control variable, which acts as the counter that controls the loop.

The condition is an expression of type bool that determines whether the loop will repeat.

The iteration expression defines the amount by which the loop control variable will change each time the loop is repeated.

The for loop will continue to execute as long as the condition tests true. Once the condition becomes false, the loop will exit, and the script execution will resume on the statement following the for.

For example, the following script prints the numbers from 1 to 5 in increments of 1:

{

for(number i = 1; i<6; i=i+1)

{

print(i);

}

print("Counting completed.");

}

The output from the script is shown here:

1

2

3

4

5

Counting completed.