FOR / NEXT Counts For You
Repeat a thing a fixed number of times without retyping it. FOR sets a counter and its range; NEXT sends the loop round again; STEP changes how the counter moves — even backwards, for a countdown.
To do a thing ten times, you don't write ten lines. FOR / NEXT is the counted
loop: FOR names a counter and the range it runs through, NEXT sends control back for
the next value, and the lines between run once per step.
Milestone 1 — count from 1 to 5
10 FOR N=1 TO 5
20 PRINT "LINE";N
30 NEXT N
Line 10 sets N to 1 and remembers it must reach 5. Line 30, NEXT N, adds one to N
and jumps back to line 10's partner — the line after FOR — until N passes 5. The body
(line 20) runs five times, with N holding 1, 2, 3, 4, 5 in turn:
The counter isn't just a tally you ignore — it's a value you can use, here as part of the text. That's what makes a loop more than repetition.
Milestone 2 — STEP, and counting backwards
FOR climbs by 1 unless you tell it otherwise. STEP sets the stride — and a negative
STEP counts down:
| 1 | - | 10 FOR N=1 TO 5 | |
| 2 | - | 20 PRINT "LINE";N | |
| 1 | + | 10 FOR N=10 TO 1 STEP -1 | |
| 2 | + | 20 PRINT N | |
| 3 | 3 | 30 NEXT N | |
| 4 | + | 40 PRINT "LIFTOFF!" | |
| 4 | 5 | |
FOR N=10 TO 1 STEP -1 starts at 10 and subtracts one each time round, stopping after 1.
RUN it for a countdown:
When it doesn't work
?NEXT WITHOUT FOR ERROR. ANEXTran with no matchingFORabove it — usually a jump landed inside the loop, or theFORline was deleted.- The loop ran once, or not at all. Check the range and
STEP.FOR N=1 TO 5 STEP -1never moves toward 5, so the body runs a single time. - The counter was off by one.
FOR N=1 TO 5includes both 1 and 5 — five passes. If you wanted five starting at 0, use0 TO 4.
Before and after
You started writing one line per repetition and finished with a loop that runs the body as
many times as you set — forwards or backwards. The idea underneath: FOR sets a counter
and a range, NEXT advances it, STEP changes the stride. A loop with a counter you
use is the workhorse of every list, every grid, every animation to come.
Try this
- Count the evens.
FOR N=2 TO 10 STEP 2— print each. Predict the values first. - A row of stars. Loop five times and
PRINT "*";(with the semicolon) so they sit on one line. - Nest two loops. Put a
FORinside aFORand print both counters — the start of drawing a grid.
What you've learnt
FORnames a counter and its range;NEXTadvances it and loops back.- The counter is a value you can use, not just a tally.
STEPsets the stride; a negativeSTEPcounts down.- A range like
1 TO 5includes both ends — five passes.
What's next
FOR repeats a fixed number of times. Games need a loop that runs until something
happens — and a way to package a job and call it by name. In Unit 8 we meet GOTO,
GOSUB, and the endless game loop, with RND to pick a secret number.