
Printing five lines takes five PRINTs. Printing five hundred would take five hundred - unless the program can be told to do the same thing again. Repeating is what computers are for, and FOR is the simplest way to ask for it.
10 FOR I=1 TO 5
20 PRINT I
30 NEXT I
FOR I=1 TO 5 sets I to 1. The lines down to NEXT I are done. At NEXT, I goes up by one and, if it has not passed 5, the program goes back up and does them again. So line 20 runs five times, with I being 1, 2, 3, 4 and 5.
The lines between FOR and NEXT are the loop. LIST shows them indented by two spaces, so you can see where a loop starts and ends:
10 FOR I=1 TO 5
20 PRINT I
30 NEXT I
You typed them without the spaces; BBC BASIC adds them when it lists.
I is an ordinary variable, and the loop can use it - that is the point. And you can write just NEXT; the I after it is only a reminder of which loop it closes.
STEP says how much to add each time:
FOR I=1 TO 9 STEP 2
gives 1, 3, 5, 7, 9. A negative step counts down: FOR I=5 TO 1 STEP -1 gives 5, 4, 3, 2, 1.
FOR I=5 TO 1 - counting up from 5 to 1, with no STEP -1 - looks as if it should do nothing at all. It does the loop once, with I at 5. BBC BASIC only checks whether it has finished when it reaches NEXT. Remember that when a loop's limits come from a sum that might be backwards.
10 FOR I=1 TO 5
20 PRINT I,I*I
30 NEXT I
40 PRINT "DONE"
Starting from
A fresh boot, or NEW.
What you should see
>RUN
1 1
2 4
3 9
4 16
5 25
DONE
>
The comma in line 20 puts I*I in the next ten-column space, so the numbers line up in two columns.

FOR I=1 TO 9 STEP 2. Which numbers are used now?FOR I=5 TO 1 STEP -1. What order are the lines in?FOR I=5 TO 1, with no STEP. How many lines are printed, and why any at all?12.1 Print the seven times table, from 1 X 7 = 7 to 12 X 7 = 84.
12.2 Add up all the whole numbers from 1 to 100, and print the total.
12.3 Print a triangle of stars: one star, then two, then three, up to five. (S9's STRING$ helps.)
Worked solutions are in Appendix II.
| Symptom | Cause |
|---|---|
| A loop ran once when you expected none | A FOR loop always runs at least once. |
| A loop counting down ran only once | Counting down needs STEP -1. |
FOR V=start TO end ... NEXT repeats the lines between, with V counting from start to end. STEP sets how much it counts by, and a negative step counts down. A loop always runs at least once.
S13, Round And Round - repeating until something happens, however many times that takes.