FOR Statement

Top  Previous  Next

Repeats a group of statements a specified number of times.

 

Syntax

 

FOR counter = start TO end  [STEP step ]

    [statements ]

NEXT

 

counter        Variable used as a loop counter.  This variable must be declared as an integer before using.  See the VARIABLES statement.

 

start        Initial value of counter (can be a complex expression)

 

end        Final value of counter (can be a complex expression)

 

step        Integer amount counter is changed each time through the loop. If not specified, step defaults to one.

 

statementsOne or more statements between FOR  and NEXT  that are executed the specified number of times.

 

First the expression start and end are evaluated.

 

When the NEXT statement is encountered, step is added to the variable defined as the counter . At this point, if counter is less than or equal to end, the statements in the loop execute again. If counter is greater than end, then the loop is exited and execution continues with the statement following the NEXT statement.

 

The expressions start, end and step can be any expression or variable of any type. However, unlike with the WHILE statement, if end is an expression, the FOR statement evaluates this expression only once at the start of the loop and stores this value for subsequent comparisons. So you should not write code that relies on the end expression being evaluated every time through the loop.

 

Examples

 

FOR index = 1 TO 25

    PRINT index

NEXT

 

 

The following loop decrements index:

 

FOR index = -1 TO -25 STEP -1

    PRINT index

NEXT

 

 

You can nest FOR...NEXT  loops by placing one FOR...NEXT  loop within another. The following illustrates a nested FOR statement:

 

FOR monthIndex = 1 TO 12 STEP 1

    FOR  dayIndex = 1 TO 31 STEP 1

        print "Month = ", monthIndex, " Day = ", dayIndex

    NEXT

NEXT