This special type of loop, in which something has to be done a certain number of times, is well known.
A special structure, called a FOR loop, has been invented for it. In such a loop the count from 1 to 4 is
handled automatically. So is the exit when all four items have been handled.
Program 4
100 RESTORE 160
110 DIM high_st$(4,3)
120 FOR number = 1 TO 4
130 READ high_st$(number)
140 PRINT ! high_st$(number) !
150 END FOR number
160 DATA "VAL","HAL","MEL","DEL"
The output from all four programs is the same:
VAL HAL MEL DEL
Which proves that the data is properly stored internally in the four array variables:
Method 4 is clearly the best so far because it can deal equally well with 4 or 40 or 400 items by just
changing the number 4 and adding more DATA items. You can use as many DATA statements as
you need.
In its simplest form the FOR loop is rather like the simplest form of REPeat loop. The two can be
compared:
100 REPeat greeting
110 PRINT 'Hello"
120 END REPeat greeting
100 FOR greeting = 1 TO 40
110 PRINT 'Hello"
120 END FOR greeting
Both these loops would work. The REPeat loop would print 'Hello' endlessly (stop it with the BREAK
sequence) and the FOR loop would print 'Hello' just forty times.
Notice that the name of the FOR loop is also a variable, greeting, whose value varies from 1 to 40 in
the course of running the program. This variable is sometimes called the loop variable or the control
variable of the loop.
Note the structure of both loops takes the form:
Opening statement
Content
Closing statement
However certain structures have allowable short forms for use when there are only one or a few
statements in the content of the loop. Short forms of the FOR loop are allowed so we could write the
program in the most economical form of all:
Program 5:
100 RESTORE 140 : CLS
110 DIM high st$(4,3)
120 FOR number = 1 TO 4 : READ high_st$(number)