FOR...NEXT - BASIC Stamp Command Reference
Explanation
FOR...NEXT loops let your program execute a series of instructions for a
specified number of repetitions (called iterations). By default, each time
through the loop, the counter variable is incremented by 1.
continue to loop until the result of the counter is outside of the range set
by StartValue and EndValue. Also, FOR...NEXT loops always execute at
least once. The simplest form is shown here:
Reps
VAR
NIB
FOR Reps = 1 TO 3
DEBUG "*"
NEXT
In the above code, the FOR command sets Reps = 1. Then the DEBUG line
(within the FOR...NEXT loop) is executed; printing an asterisk (*) on the
screen. When the BASIC Stamp sees the NEXT command, it goes back to
the previous FOR command, adds 1 to Reps and compares the result to the
range set by StartValue and EndValue. If Reps is still within range, it
executes the code in the loop again. Each time the FOR...NEXT loop
executes, the value of Reps is updated (incremented by 1) and the code
within the loop (the DEBUG line) is executed; printing another asterisk on
the screen. This code will run through the loop three times; setting Reps to
1, 2 and 3, and printing three asterisks on the screen. After the third loop,
again the BASIC Stamp goes back up to the FOR command, adds 1 to Reps
and compares the result (4 in this case) to the range. Since the range is 1 to
3 and the value is 4 (outside the range) the FOR...NEXT loop is done and
the BASIC Stamp will jump down to the first line of code following the
NEXT command.
You can view the changing values of Reps by including the Reps variable in
a DEBUG command within the loop:
Reps
VAR
NIB
FOR Reps = 1 TO 3
DEBUG DEC Reps, CR
NEXT
Running this example should display "1" , "2", and "3" on the screen.
FOR...NEXT can also be made to decrement (rather than increment) the
counter variable. The BS1 does this when you specify a negative StepValue
(as well as a StartValue that is greater than the EndValue). All other BASIC
Page 118 • BASIC Stamp Programming Manual 2.0b • www.parallaxinc.com
' Counter for the FOR/NEXT loop.
' Repeat with Reps = 1, 2, 3.
' Each repetition, put one * on the screen.
' Counter for the FOR/NEXT loop.
' Repeat with Reps = 1, 2, 3.
' Each repetition, put the number of the
' repetition on the screen.
S
IMPLEST FORM OF
It will
NOTE: On the BS1, the loop will
continue until Counter has gone
past EndValue.
NOTE: Replace the first line with
SYMBOL Reps = B0
on the BS1.
P
FOR...NEXT
ROCESSING A
NOTE: Change the first line as
noted above and replace line 3 with
DEBUG #Reps, CR
on the BS1.
D
ECREMENTING THE COUNTER
INSTEAD OF INCREMENTING IT
FOR...NEXT.
1
1
.
LOOP
1
.
Need help?
Do you have a question about the BASIC Stamp 2e and is the answer not in the manual?