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 2 3 |
FOR varname = start TO end {STEP increment} statementblock NEXT |
|
Parameter |
Description |
|---|---|
|
varname |
The name of the iteration counter variable. It can be |
|
start |
Starting value of varname. |
|
end |
Ending value of varname. |
|
increment (optional) |
The increment value. Increment must be a constant and |
|
statementblock |
The block of statements you want to |
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 2 3 |
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.
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
Example 1
These statements add 10 to A as long as n is >=5 and
<=25:
|
1 2 3 |
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:
|
1 2 3 |
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:
|
1 2 3 4 |
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:
|
1 2 3 4 5 6 7 8 |
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 |