Apple II Another Square Root Program, Print Nsqrn Next N, COUNT-BACKWARD Program, Print Next

Models: II

1 257
Download 257 pages 49.17 Kb
Page 226
Image 226

The output of the program listed above will be exactly the same as the previous two programs.

At line 10, N is set to equal 1. Line 20 causes the value of N and the square root of N so be printed. At line 30 we sees new type of statement. The "NEXT N" statement causes one to be added to N,

and then if N<=9 we go back to the statement following the "FOR" statement. The overall operation then is the same as with the previous program.

Notice that the variable following the "FOR" is exactly the same as the variable after the "NEXT." There is nothing special about the N in this case. Any variable could be used, as long as it is the same in both the "FOR" and the "NEXT" statements. For instance, "Z1" could be substituted everywhere there is an "N" in the above program and it would function exactly the same.

ANOTHER SQUARE ROOT PROGRAM

Suppose we want to print a table of square roots of each even number from 10 to 20. The following program performs this task:

10 N=10

20 PRINT N;SQR(N)

30 N=N+2

40 IF N<=20 THEN 20

Note the similarity between this program and our "improved" square root program. This program can also be written using the "FOR" loop just introduced.

10 FOR N=10 TO 20 STEP 2

20 PRINT N;SQR(N)

30 NEXT N

Notice that the only major difference between this program and the previous one using "FOR" loops is the addition of the "STEP 2" clause.

This tells BASIC to add 2 to N each time, instead of 1 as in the previous program. If no "STEP" is given in a "FOR" statement, BASIC assumes that 1 is to be added each time. The "STEP" can be followed by any expression.

A COUNT-BACKWARD PROGRAM

Suppose we wanted to count backward from 10 to 1. A program for doing this would be as follows:

10I=10

20PRINT I

30I=I-1

40IF I>=1 THEN 20

Notice that we are now checking to see that I is greater than or equal to the final value. The reason is that we are now counting by a negative number. In the previous examples it was the opposite, so we were checking for a variable less than or equal to the final value.

SOME OTHER LOOPING OPERATIONS

The "STEP" statement previously shown can also be used with negative numbers to accomplish this same result. This can be done using the same format as in the other program:

10 FOR I=10 TO 1 STEP -1

20 PRINT I

30 NEXT I

"FOR" loops can also be "nested." For example:

10 FOR I=1 TO 5

20 FOR J=1 TO 3

30 PRINT I,J

40 NEXT J

50 NEXT I

Notice that "NEXT J" precedes "NEXT I." This is because the J-Ioop is inside the I-loop. The following program is incorrect; run it and see what happens:

Page 226
Image 226
Apple II manual Another Square Root Program, Print Nsqrn Next N, COUNT-BACKWARD Program, Some Other Looping Operations