FOR ... NEXT
Syntax
Parameters
- iterator: a variable identifier that is used to iterate from an initial value to an end value.
- startvalue: an expression that denotes the starting value of the iterator.
- endvalue: an expression used to compare with the value of the iterator.
- stepvalue: an expression that is added to the iterator after every iteration.
Description
A For...Next loop initializes iterator to startvalue, then executes the sentences, incrementing iterator by stepvalue until it reaches or exceeds endvalue. If stepvalue is not explicitly given it will set to 1.
Examples
Counts downwards
Loops using odd numbers
Differences From Sinclair Basic
-
The variable name after the NEXT statement is not required.
-
Note that variable types can cause issues with ZX Basic For...Next Loops. If the upper limit of the iterator exceeds the upper limit of the variable type, the loop may not complete. For example:
Clearly, since the largest value a byte can hold is 255, it's not possible for i in the above example to exceed 300.
The variable will "wrap around" to 0 and as a result, the loop will not ever terminate.
This can happen in much more subtle ways when STEP is used.
There has to be "room" within the variable type for the iterator to exceed the terminator when it is being
incremented by <step> amounts.
For example, this loop will neved end
This loop will never end. UInteger type allows values in the range [0..65535] so apparently it's ok, because
65500 fits in it. However STEP is 100, so 65500 + 100 = 65600 which fall out if such range. There will be an
overflow and the variable i will take the value 64 and the loop will continue.