For ... Next

For X = Y To Z { Step S }

The beginning of a FOR-NEXT loop takes a starting variable (X), assigns it a value (Y) and sets a limit (Z). An optional STEP argument (S) specifies the increment for each iteration of the loop. If the step value is negative, the variable counts down. The body of the loop is not executed if the end condition is true initially.

For X = 1 to 10 Step 0.5
Print X
Next X

For ... Next loops may be nested up to 100 deep.

Next { X }

Next ends a FOR-NEXT loop. If the termination conditions are met then execution falls through to the following statement, otherwise execution returns to the statement following the For.

The index variable following a Next is optional in Basic version 5.4 and later.

Exit For

For loops should never be exited with a Goto statement. If you must exit a For loop use the Exit For command.

For Example:

For i = 1 to 10
If i = 5 Then Exit For
Next i

If you are in a subroutine you may exit a For loop with a Return.

For Example:

Sub MySub()

For i = 1 to 10
If i = 5 Then Return
Next i

End Sub

Become a Patron