Commodore 2001-8 User Manual page 36

Table of Contents

Advertisement

Chapter 5.
ELEMENTARY PROGRAMMING
Use of decision logic in writing programs.
A major advance in BASIC programming
is
the ability to loop back and re-execute lines of
a
program. It
may be done in two ways -- unconditionally with a GOTO and conditionally with an IF-THEN.
GOTO
is
written to specify
a
target line number where execution will a/ways branch. GOTO maya/so be
written with
a
space between GO and TO. PET BAS/C will recognize both forms.
GO TO 50
GOTO 100
IF-THEN has three forms:
IF (condition) THEN (statement)
IF (condition) GOTO (line number)
IF (condition) THEN (line number)
Conditions are written as two arithmetic expressions separated by a relational operator. PET BASIC
provides six relational operators:
<, >,
=,
<
>, <
=,
>
=.
Until now we have been developing programs which do single functions in serial order. You should be
familiar with the concept that says that first line 10 is executed, then line 20, and other line numbers in
ascending order.
If we wanted to take and print numbers betwenn 1 and 20, their square and square root values on the
screen, we could write the linear program as before:
10 PRINT 1,1,1
20 PRINT 2,2"2, SQR(2)
30 PRINT 3,3"3, SQR(3)
The big disadvantage of this is that we would have to keep typing in lines until the 20th line.
200 PRINT 20,20"20, SQR(20)
UNCONDITiONAL LOOPING
However, with our concepts of variables and the addition of a lOOP, we can write a program that
computes values and prints them out without having to type such a long program.
The program reads as follows:
10 PRINT "VALUE","SQUARE", SQUARE ROOT"
Line 10 prints a heading for the column of numbers. It is executed only once.
201=1+1
Line 20 computes the next number to use. The first time this line is executed, I has
never been referenced so it has an initial value of
O.
30 PRINT 1,1"1, SQR (I)
Line 30 is like lines 10-200 of the previous program except that the constants have been replaced by a
variable.
40 GOTO 20
Line 40 contains a GOTO command which directs execution back to start again at line 20.
BASIC stores text lines so that a pointer to the next line precedes each line. Using this technique, the
interpreter can quickly examine only the line numbers, determine If- a line does exist, and transfer
execution to that line.
GOTO is not limited to branching to a lesser line number but It can branch to a greater number too. You
32

Advertisement

Table of Contents
loading

This manual is also suitable for:

Pet 2001-8

Table of Contents