I touched briefly upon loops in part 1 with the example code; it would loop forever (or until you pressed BREAK) printing “Hello!” on the screen.
If you combine this with the IF instruction and variables, you can control looping. Take this example:
10 LET I = 1 20 PRINT "The value of I = "; I 30 LET I = I + 1 40 IF I <= 10 THEN GOTO 20
This example prints and increments the value of variable I, looping around whilst I is less than or equal to 10. Whilst this is essentially how you would do it in assembly language there is a more elegant construct for this type of loop in BASIC; the FOR…NEXT loop.
This is the same example, written using the FOR…NEXT loop:
10 FOR I = 1 TO 10 20 PRINT "The value of I = "; I 30 NEXT I
You can see that this is much easier to read. You can also make it loop backwards, or with a different increment by adding the STEP instruction:
10 FOR I = 100 TO 50 STEP -3 20 PRINT "The value of I = "; I 30 NEXT I
This will loop backwards from 100 to 50, going down in increments of 3. You can see that the value of the STEP instruction is the amount to be taken from I. Note that in this example it will only display values of I between 100 and 52; the next increment would take it below the second loop value of 50.
You can also nest loops, that is run one loop inside another. Take this example:
10 FOR X = 0 TO 31 20 FOR Y = 0 TO 21 30 PLOT X*8,Y*8 40 NEXT Y 50 NEXT X
In this example, there is an outer loop (lines 10 and 50) that contains an inner loop (lines 20 to 40). The inner loop (Y) will run 32 times, for every value of the outer loop (X) between 0 and 31. This example plots a grid of dots on the screen.
Note, you must get the order of the NEXT instructions in the correct order; the inner loop must be completely enclosed by the outer loop. You can also have more than two levels of nested loop.
Our programs may be getting fairly complicated at this point, so we’ll look at how we can organise similar pieces of code into subroutines next.