Apple II User Manual

Page of 257
At line 20, if A is smaller than B, A<=B is true so we goto line 50.  At line 50, A<B will be true
so we then go to line 80.  "B IS BIGGER" is then printed and again we go back to the beginning.
Try running the last two programs several times.  It may be easier to understand if you try writing
your own program at this time using the IF-THEN statement.  Actually trying programs of your
own is the quickest and easiest way to understand how BASIC works.  Remember, to stop these
programs just give a RETURN to the input statement.
208  LOOPING
One advantage of computers is their ability to perform repetitive tasks.  Let's take a closer look and
see how this works.
A SQUARE ROOT PROGRAM
Suppose we want a table of square roots from 1 to 9.  The BASIC function for square root is "SQR";
the form being SORIX), X being the number whose square root is to be calculated.  We could write
the program as follows:
    10 PRINT 1,SQR(1)
    20 PRINT 2,SQR(2)
    30 PRINT 3,SQR(3)
    40 PRINT 4,SQR(4)
    50 PRINT 5,SQR(5)
    60 PRINT 6,SQR(6)
    70 PRINT 7,SQR(7)
    80 PRINT 8,SQR(8)
    90 PRINT 9,SQR(9)
AN IMPROVED SQUARE ROOT PROGRAM
This program will do the job, but is terribly inefficient.  We can improve the program considerably
by using the IF statement just introduced as follows:
    10 N=1
    20 PRINT N;SQR(N)
    3D N=N+1
    40 IF N<=9 THEN 20
When this program is run, its output will look exactly like that of the 9 statement program above
it.  Let's look at how it works:
At line 10 we have a LET statement which sets the value of the variable N equal to 1.  At line 20
we print N and the square root of N using its current value.  It thus becomes 20 PRINT 1;SQR(1),
and this calculation is printed out.
At line 30 we use what will appear at first to be a rather unusual LET statement.  Mathematically,
the statement N=N+1 is nonsense.  However, the important thing to remember is that in a LET
statement, the symbol "=" does not signify equality.  In this case, "=" means "to be replaced
with."  All the statement does is to take the current value of N and add 1 to it.  Thus, after the
first time through line 30, N becomes 2.
At line 40, since N now equals 2, N<=9 is true so the THEN portion branches us back to line 20,
with N now at a value of 2.
The overall result is that lines 20 through 40 are repeated, each time adding 1 to the value of N.
When N finally equals 9 at line 20, the next line will increment it to 11.  This results in a false
statement at line 40, and since there are no further statements to the program it stops.
BASIC STATEMENTS FOR LOOPING
This technique is referred to as "looping" or "iteration."  Since it is used quite extensively in
programming, there are special BASIC statements for using it.  We can show these with the
following program:
    10 FOR N=1 TO 9
    20 PRINT N;SQR(N)
    30 NEXT N