A control structure that is a numerical iteration, used to execute one or more statements a specified number of times.
FOR varname = start TO end {STEP increment} statementblock NEXT
Parameter |
Description |
---|---|
varname |
The name of the iteration counter variable. It can be any numerical type (integer, double, real, long, or decimal), but integers provide the fastest performance. |
start |
Starting value of varname. |
end |
Ending value of varname. |
increment (optional) |
The increment value. Increment must be a constant and the same datatype as varname. If you enter an increment, STEP is required. +1 is the default increment. |
statementblock |
The block of statements you want to repeat. |
For a positive increment, end must be greater than start. For a negative increment, end must be less than start.
When increment is positive and start is greater than end, statementblock does not execute. When increment is negative and start is less than end, statementblock does not execute.
When start and end are expressions, they are reevaluated on each pass through the loop. If the expression’s value changes, it affects the number of loops. Consider this example—the body of the loop changes the number of rows, which changes the result of the RowCount function:
FOR n = 1 TO dw_1.RowCount( )
dw_1.DeleteRow(1)
NEXT
A variable as the step increment If you need to use a variable for the step increment, you can use one of the DO...LOOP constructions and increment the counter yourself within the loop.
You can nest FOR...NEXT statements. You must have a NEXT for each FOR.
You can end the FOR loop with the keywords END FOR instead of NEXT.
Avoid overflow If start or end is too large for the datatype of varname, varname will overflow, which might create an infinite loop. Consider this statement for the integer li_int:
FOR li_int = 1 TO 50000
The end value 50000 is too large for an integer. When li_int is incremented, it overflows to a negative value before reaching 50000, creating an infinite loop.
Example 1 These statements add 10 to A as long as n is >=5 and <=25:
FOR n = 5 to 25
A = A+10
NEXT
Example 2 These statements add 10 to A and increment n by 5 as long as n is >= 5 and <=25:
FOR N = 5 TO 25 STEP 5
A = A+10
NEXT
Example 3 These statements contain two lines that will never execute because increment is negative and start is less than end:
FOR Count = 1 TO 100 STEP -1
IF Count < 1 THEN EXIT // These 2 lines
Box[Count] = 10 // will never execute.
NEXT
Example 4 These are nested FOR...NEXT statements:
Int Matrix[100,50,200]
FOR i = 1 to 100
FOR j = 1 to 50
FOR k = 1 to 200
Matrix[i,j,k]=1
NEXT
NEXT
NEXT