Loops-The For-Next Command - Commodore 128 System Manual

Hide thumbs Also See for 128:
Table of Contents

Advertisement

Now change line 10 to read N=20, and RUN the program again.
Notice you can tell the computer to execute more than one
statement when N is less than 5. You can put any statement(s)
you want after the THEN command. Remember that the GOTO
40 will not be reached until N<5 is true. Any command that
should be followed whether or not the specified condition is met
should appear on a separate line.

LOOPS-THE FOR-NEXT COMMAND

ln the program used for the IF-THEN example, we made the
computer print Commodore five times by telling it to increase or
" increment" the variable J by units of one, until the value of J
equalled five; then we ended the program. There is a simpler way
to do this in BASIC. We can use a FOR-NEXT loop, like this;
10 FOR J=1 TO 5
20 ?J, " COMMODORE 128"
30 NEXT J
40 END
Type and RUN this program and compare the result with the
result of the IF-THEN program—they are the same, ln fact, the
steps taken by the computer are almost identical for the two
programs. The FOR-NEXT loop is a very powerful programming
tool. You can specify the number of times the computer should
repeat an action. Let's trace the computer's steps for the program
above.
First, the computer assigns a value of 1 to the variable J. The 5 in
the FOR statement in line 10 tells the computer to execute all
statements between the FOR statement and the NEXT statement,
until J is equal to 5. ln this case there is just one statement—the
PRINT statement.
The computer first assigns 1 to J, it then goes on to execute the
PRINT statement. When the computer reaches the NEXT J
statement, J is incremented and compared with 5. If J has not
exceeded 5 the computer loops back to the PRINT statement.
After five executions of this loop the value of J exceeds 5, the
program drops down to the statement that comes immediately
after the NEXT statement and continues from there, ln this case
the following statement is the END command, so the program
stops.
4-5

Hide quick links:

Advertisement

Table of Contents
loading

This manual is also suitable for:

128d

Table of Contents