Syntax |
For counter = start To end [Step increment] [statements] [Exit For] [statements] Next [counter [,nextcounter]... ] |
Description |
Repeats a block of statements a specified number of times, incrementing a loop counter by a given increment each time through the loop. |
Comments |
The For statement takes the following parameters: |
|
Parameter |
Description |
|
counter |
Name of a numeric variable. Variables of the following types can be used: Integer, Long, Single, Double, Variant. |
|
start |
Initial value for counter. The first time through the loop, counter is assigned this value. |
|
end |
Final value for counter. The statements will continue executing until counter is equal to end. |
|
increment |
Amount added to counter each time through the loop. If end is greater than start, then increment must be positive. If end is less than start, then increment must be negative. If increment is not specified, then 1 is assumed. The expression given as increment is evaluated only once. Changing the step during execution of the loop will have no effect. |
|
statements |
Any number of Basic Control Engine statements. |
|
The
For...Next
statement continues executing until an
Exit For
statement is encountered when counter is greater than end.
For...Next
statements can be nested. In such a case, the
Next [
counter
]
statement applies to the innermost
For...Next
. The
Next
clause can be optimized for nested next loops by separating each counter with a comma. The ordering of the counters must be consistent with the nesting order (innermost counter appearing before outermost counter). The following example shows two equivalent
For
statements: For i = 1 To 10 For i = 1 To 10
For j = 1 To 10 For j = 1 To 10
Next j Next j,i
Next I
|
|
A
Next
clause appearing by itself (with no counter variable) matches the innermost
For
loop. The counter variable can be changed within the loop but will have no effect on the number of times the loop will execute. |
Example |
Sub Main()
'This example constructs a truth table for the OR statement 'using nested For...Next loops.
Msg1 = "Logic table for Or:" & crlf & crlf
For x = -1 To 0
For y = -1 To 0
z = x Or y
msg1 = msg1 & CBool(x) & " Or "
msg1 = msg1 & CBool(y) & " = "
msg1 = msg1 & CBool(z) & Basic.Eoln$
Next y
Next x
MsgBox msg1
End Sub
|
See Also |
Do...Loop (statement); While...Wend (statement). |
Notes |
Due to errors in program logic, you can inadvertently create infinite loops in your code. You can use Ctrl+Break to break out of infinite loops. |