FOR…NEXT
Description
A control structure that is a numerical iteration, used to
execute one or more statements a specified number of times.
Syntax
|
1 |
FOR <span>varname</span> = <span>start</span> TO <span>end</span> {STEP <span>increment</span>}<br><span>   statementblock</span><br>NEXT |
|
Parameter |
Description |
|---|---|
|
varname |
The name of the iteration counter variable. |
|
start |
Starting value of varname. |
|
end |
Ending value of varname. |
|
increment |
The increment value. Increment must |
|
statementblock |
The block of statements you want to repeat. |
Ending statement
You can end the FOR loop with the keywords END
FOR instead of NEXT.
Usage
Using the start and end parameters
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:
|
1 |
FOR n = 1 TO dw_1.RowCount( ) |
|
1 |
dw_1.DeleteRow(1) |
|
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.
Nesting
You can nest FOR…NEXT statements. You
must have a NEXT or END FOR for
each FOR.
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:
|
1 |
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.
Examples
These statements add 10 to A as long
as n is >=5 and <=25:
|
1 |
FOR n = 5 to 25 |
|
1 |
A = A+10 |
|
1 |
NEXT |
These statements add 10 to A and increment
n by 5 as long as n is >= 5
and <=25:
|
1 |
FOR N = 5 TO 25 STEP 5 |
|
1 |
A = A+10 |
|
1 |
NEXT |
These statements contain two lines that will never execute because increment is
negative and start is less than end:
|
1 |
FOR Count = 1 TO 100 STEP -1 |
|
1 |
IF Count < 1 THEN EXIT // These 2 lines |
|
1 |
Box[Count] = 10 // will never execute. |
|
1 |
NEXT |
These are nested FOR…NEXT statements:
|
1 |
Int Matrix[100,50,200] |
|
1 |
FOR i = 1 to 100 |
|
1 |
FOR j = 1 to 50 |
|
1 |
FOR k = 1 to 200 |
|
1 |
Matrix[i,j,k]=1 |
|
1 |
NEXT |
|
1 |
NEXT |
|
1 |
NEXT |