Commodore 2001-8 User Manual page 51

Table of Contents

Advertisement

this
10 GOSUB 20
20 RETURN
10 GOSUB 20
15 END
20 RETURN
Sometimes, you might have a tendency to make everything into a subroutine. If a given subroutine is used
just once, then it should be incorporated into a program where it is used to save execution time and
memory space. On the other hand, subroutines are incredibly powerful programming tools and allow you
to structure your program into blocks.
FOR-NEXT LOOPS
FOR-NEXT simplifies the writing of BASIC programs by allowing one to specify complex loop structures
with a single statement.
FOR 1= A TO B STEP C
The end of the "loop is specified by the statement
NEXT
Nested FOR NEXT loops are permitted as long
as
each loop uses
a
unique variable. Use of identical loop
variable names may result in NEXT WITHOUT FOR errors.
Exiting a FOR-NEXT loop via
a
branch wllf leave the FOR entry on the stack. The best way to handle thIs
is
to assign the maximum limit to the variable then exit the loop through a NEXT.
We have seen how repeated operations can be performed using a counting variable such as I in the
routine.
10
1=1
20
1=1+1
30IFI<=10THENGOT020
In this case, any routine appearing in lines 21-29 will be repeated 10 times. In addjtion, the variable I will
have values which range from 1 to 10 in increments of 1.
This looping process can be genralized in the case:
10
1 =A
20
I=I+C
30
IF 1< =B THEN GOTO 20
The values of I will range from A to B in increments of size C.
Since this process is cumbersome to use, BASIC also prOVides you with the FOR-NEXT statement:
10
FOR I = A TO B STEP C
20
NEXT
I is the counting variable, A is the initial value, B is the ending value, and C is the increment.
A, B, C may not only be constants, but they can be any valid arithmetic expression
10 FOR I = A(2) + 1 TO J'2 STEP-1
On the other hand, the counting variable can be any floating variable but cannot be integer
(1%)
or
subscripted 1(1,4). When the increments are of size 1(C
=
1)yOU need not include the STEP in the program.
10
REM COMPUTATION OF FACTORIAL
20
NF
=
1
30
FOR 1=1 TO N
47

Advertisement

Table of Contents
loading

This manual is also suitable for:

Pet 2001-8

Table of Contents