Page 29 of 62
SBasic User's Manual SBasic Version 2.7 Page 29
Printed: December 5, 1999
The FOR-NEXT structure creates an iterated loop. This means that a
selected variable, called the index variable, controls exactly how
many times the loop is executed. Control executes all statements
between the FOR statement and the NEXT statement until the value in
the index variable EXCEEDS a specified limit. The index variable is
always tested at the top of the loop. The comparison is signed for
the usual FOR-NEXT loop, although you can use an unsigned comparison
if necessary.
Example:
for n = 1 to 10
a = a + n
next
Here, the variable N starts with a value of one. The statement inside
the loop is executed ten times, with N incrementing each time the NEXT
statement executes. Eventually, N holds the value 11 when the FOR
statement executes. At this point, the statement inside the loop is
not executed. Instead, control passes directly to the statement
following the NEXT statement.
Sometimes you must use a limit larger than $7fff. Since SBasic uses
16-bit math, numbers larger than $7fff are treated as negative in
signed comparisons. Therefore, the following example:
for n = 1 to $9000
a = a + 1
next
will exit immediately, as SBasic treats $9000 as a negative number,
and 1 is already greater than a negative number.
To change the above example to use an unsigned comparison, use the TO*
operator. The above example becomes:
for n = 1 to* $9000
a = a + 1
next
This loop will execute the expected $9000 times.
Remember to leave room on your limit value so that the index variable
can actually exceed the limit. For example:
for n = 1 to* $ffff
a = a + 1
next
This loop will never end, since the value of N can never exceed the
limit of $ffff.