|
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
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
|