Advanced BASIC
Advanced BASIC
JAMES S. COAN
CID@JWCIDITU©®@J
~&~O©
Hayden Computer Programming Series
JAMES S. COAN
Community Computer Corporation
Germantown Friends School
[JJ
HAYDEN BOOK COMPANY, INC.
Rochelle Park, New Jersey
Library of Congress Cataloging in Publication Data
Coan, James S
Advanced BASIC.
6 7 B 9 PRINTING
78 79 BO 81 82 83 84 85 YEAR
PREFACE
Students are finding that after they have been through the intro-
ductory texts presenting BASIC they are pretty much on their own.
They may get additional bits and pieces of assistance from other texts,
finding that each adds something to their repertoire, but there is still
all that introductory material to sort through. The present text is in-
tended for those who have been introduced to the BASIC language and
want to go further with the language. It is also intended for those who
have already learned another language (such as FORTRAN or COBOL)
and need only a brief introduction to what is for them a second or
third programming language.
A review chapter is placed at the beginning of the book for those
whose coverage of BASIC may have been somewhat limited or distant
in time, and for those who come to it with competence in one or more
other programming languages. In fact, this text can even be used by
students with no former programming experience, if tutorial assistance
is available, by a more extensive use of the review chapter.
Some extended features of BASIC are presented so that students
working on systems providing extensions will have an opportunity to
experiment with or master new techniques. Strings and files are intro-
duced in Chapters 3 and 4. Due to the variety of implementations for
use of both strings and files, two systems are presented in each area:
General Electric and Hewlett Packard.
In addition to other topics, the applications chapters cover
coordinate geometry, area, sequences and series, polynomials, graphing,
simulation, and games. These chapters may be studied independently
and in any order, although, where appropriate, the student may occa-
sionally be referred to another section in the text. Generally these
topics evolve from dr build on the ground of a second course in algebra
and beyond.
'.Vhe topic of efficiency is treated explicitly on several occasions,
though not necessarily to the point of optimizing execution time. The
topic of structured programming is treated implicitly in that all exam-
ple programs incorporate a clear programming style with minimal un-
conditiona l branching and maximal use of appropriate data and control
structures. These two topics provide good stepping-off points in a
computer science course.
Appendix A presents an abbreviation of the ASCII character
codes. Appendices B and C summarize flowchart shapes and program
statements in BASIC. Appendix Dis an index of the nearly 100 demon,
strati on programs in the text. Some solution programs for selected
problems in the text follow these appendices.
I wish to thank Community Computer Corporatio n for computer
time, General Electric Informatio n Services for assistance, and those
who commented on the first draft for invaluable suggestions.
JAMES s. COAN
Philadelphia
CONT ENTS
1 Review of BASIC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1-1 Introductio n, 1
1-2 Some Simple Programs, 1
1-3 Functions, Loops, and Lists, 7
1-4 User Defined Functions, Subroutines, and Arrays, 12
1-5 MAT Statements in BASIC, 18
2 Some Extended Features of BASIC. . . . . . . . . . . . . . . . . . . . . . . . 23
2-1 Introductio n, 23
2-2 TAB, 23
2-3 Print Using, 25
2-4 Logical Operations, MAX and MIN, 27
2-5 Multiple Line Defined Function, 29
3 Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3-1 Introductio n, 31
3-2 The String Simple Variable, 31
3-3 The String Subscripted Variable, 34
3-4 The Substring Scheme, 35
3-5 The String Array Scheme, 40
4 Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
4-1 Introductio n, 46
4-2 Hewlett Packard Files, 46
4-3 General Electric Files, 54
5 Plotting on the Terminal. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5-1 Introductio n, 64
5-2 Plotting a Function, 64
5-3 Plotting Using Data Stored in an Array, 68
6 Area Under a Curve. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6-1 Introductio n, 72
7 Coordinate Geometry. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
7-1 Points in a Plane, 78
7-2 Pairs of Points, 78
7 -3 Parallel and Perpendicular Lines, 84
7-4 Point of Intersection of Two Lines, 88
7-5 Three Points in a Plane, 93
8 Polynomials. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
8-1 Introduction, 101
8-2 Finding a Real Zero of a Polynomial, 104
8-3 Synthetic Division to Get Further Zeros, 108
8-4 Miscellaneous Aids, 112
9 Sequences and Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
9-1 Sequences, 115
9-2 Convergence and Divergence, 119
9-3 Series, 122
9-4 More on Series, 125
10 Matrices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
10-1 Introduction, 127
10-2 Solving Simultaneous Linear Equations Using MAT INV, 131
11 Some Topics of Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
11-1 Introduction, 137
11-2 Average, Variance, and Standard Deviation, 137
11-3 Median, 140
11-4 Coefficient of Linear Correlation, 143
12 Simulation and Games. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
12-1 Introduction, 147
12-2 Lines at the Bank, 147
12-3 Magic Squares, 152
12-4 Games, 154
Appendix A ASCII Character Set Printable on Model 33 161
Appendix B Summary of Flowchart Shapes . . . . . . . . . . . . . . . . . . . 162
Appendix C Summary of Statements in BASIC . . . . . . . . . . . . . . . . . 163
Appendix D Index of Programs in Text . . . . . . . . . . . . . . . . . . . . . . 169
Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Answers to Selected Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
1
REVIEW OF
BASIC
1-1 Introduction
This chapter is intended to serve several purposes. The student who is al-
ready competent in BASIC will move quickly through the chapter and perhaps
write a few programs. The student who has studied BASIC, but not recently or
not extensively, will want to move more slowly and write more programs. The
student who comes to BASIC with competence in another language will be
mainly interested in the differences between the language with which he or she is
familiar and BASIC.
There are numerous implementations of BASIC available in schools, col-
leges, and businesses today. These implementations have many common fea-
tures and some differences. This chapter will concentrate primarily on those
features which are almost universally available. We will mention some of the
more common variations (you can usually determine which features are part of
your system by writing very short programs to see what works), but beyond that
the student should obtain the specific features for his system from the BASIC
reference manuals supplied by the computer center or the vendor.
It is also true that the specifications sometimes change as the people
responsible for maintaining the computer update its language capabilities. Since
these changes tend to be additions, however, programs previously tested will
usually still run.
1-2 Some Simple Programs
We can demonstrate many features of BASIC by writing a program that
will compare two numbers to determine whether the first is greater than, less
than, or equal to the second. See program C</>MP AR.
2 Advanced BASIC
CI ST
CGMPAR
3 IS LESS THAN 4
J .7 JS GRF:ATF:K THA~J J. J
31 IS EOIJAL. TC 31
-3 IS LESS THAN ?.
0 JS FO'IAL TC 0
The first item shown is LIST. This is a system command rather than a
program statement, and we type it to instruct the computer to print out the
program exactly as it stands. Next the computer automatically prints C<t'>MPAR,
which is the program name. Some computers also print the time of day and date
along with the program name. On some systems we assign program names with
the system command NAME-C<t'>MPAR. On others, to name a new program,
NEW Cq.>MP AR is typed before the program itself is. Having typed the pro-
gram name, the computer goes on to list the program itself. Let us examine the
program statements.
Read-Data
Line 100 is a READ statement. In this case we want the computer to
READ two numbers into two variables A and B. Those numbers must come
from one or more DATA statements. We provide data in lines 200 and 210.
Conditional Transfer
Lines 110, 120, and 130 are all examples of the conditional transfer in
BASIC. Line 110 is used to terminate the execution of the program itself. We
send the computer to the END statement only if the value of A is .01. This is an
example of the use of dummy data to control program execution. Lines 120
and 130 direct the computer to the appropriate PRINT statement according to
the relation between the values of A and B. BASIC also allows "greater than"
(>), "greater than or equal to" (>=) and "less than or equal to" (<=). To test
for "not equal to" use (< >). Some systems also allow"#" for "not equal to."
In place of the algebraic symbols just mentioned, some systems require
special symbols as relational operators. They are (\LT) or (LT) for "less than,"
Review of BASIC 3
(\LE) or (LE) for "less than or equal to," (\GT) or (GT) for "greater than,"
(\GE) or (GE) for "greater than or equal to," (\EQ) or (EQ) for "equal to"
and (\NE) or (NE) for "not equal to." The paired relational operators listed
above are not generally interchangable. The first is for certain systems, and the
second is for others. So there are three sets of possible relational operators.
You can quickly tell which works on your computer by consulting the vendor-
supplied manual or by trial and error.
Another conditional transfer is available on many systems. It is called the
computed G</JT</J. It takes the form,
100 </JN K G</JT</J niln 2 ,n 3 , etc.
or
or
100 G</JT</J n 1 ,n 2 ,n 3 , etc, </JN K
At line 100 computer control passes to line n 1 if K = 1, 1 2 if K = 2, etc. If K
is not in the range from one to the number of line numbers named, some sys-
tems terminate with an error message, while others simply pass control to the
line after 100.
Print
Lines 140, 160, and 180 result in printed output to the terminal for the
operator to see. We may mix literal output with numeric results by enclosing
literal messages in quotation marks. Replacing semicolons in the PRINT state-
ment with commas would result in wider spacing of printed output. On many
systems, using commas to separate printed results causes the page to be divided
into five columns of 15 characters each. For terminals with only 72 character
spaces, the fifth column is 12 characters wide. Generally speaking, use of a semi-
colon to separate printed output results in closer spacing than with a comma.
Unconditional Transfer
Lines 150, 170, and 190 are examples of unconditional transfer. The
G</JT</J statement in BASIC serves to name the number of the next line to be
executed. When the computer gets to line 150, the next line the computer exe-
cutes is 100. The same is true for lines 170 and 190. Generally speaking, good
programs try to minimize the number of G</JT</J statements. We shall see ways
to do this later.
End
The final statement in our example is the END statement. On most sys-
tems the highest numbered statement must be an END statement. After the
END statement we see the system command RUN, which is typed by us to cause
the computer to actually carry out the instructions of the program. In response
to the RUN command, the computer has printed the program name, C</JMPAR
(some systems will also print the date and time), followed by the printed output
4 Advanced BASIC
specified by the instructions of our program. (Some systems will follow pro-
gram results with information about the computer resources used by this RUN
of the program.)
Variables
In program C</>MP AR we used A and B as variables to name stored nu-
meric values. BASIC allows us to use every letter of the alphabet and also every
letter of the alphabet followed by a single digit. (Some systems also provide ad-
ditional symbols as variables.) Every letter or letter plus digit allows us to store
a single number at any one time in a program. However, variables may be used
over and over again to store new values as long as we have no further need for a
particular old value. In C</>MPAR, the variables A and B were each used for six
different numbers.
Prettyprinting
Note the overall appearance of program Cl/.>MPAR. An attempt has been
made to provide spacing within the program statements to facilitate readability
and therefore clarity of thought. The practice of indenting and spacing to
achieve this goal is called "prettyprinting." In program C</>MPAR, the IF state·
men ts have been indented three spaces. Spaces have been inserted in the PRINT
statements to avoid a crowded appearance. The blank REM in line 194 is used
to offset the DATA portion of the program, and the data has been grouped in
the DATA statements to show just how the values will be read in the READ
statement. Some systems do not allow prettyprinting. However, if your system
does allow prettyprinting, you should work on developing a style of spacing to
enhance program readability. Prettyprinting becomes more and more worth-
while as programs become longer and more complex.
Arithmetic Operations
The computer is often used to perform arithmetic opera.!;ions on numbers.
The operations allowed are exponentiation (**) or (t), multiplication (*),
division (/), addition (+) and subtraction (- ). The priorities assigned these opera-
tors are the same as those assigned in conventional algebra, that is, first exponen-
tiation followed by multiplication and division followed by addition and sub-
traction. Program </>PRATN shows a use of each of the arithmetic operators.
CPRATN
RIJN
OPRATN
A 3 8 = 4
-1
81 12 0.75
A 2 8 = 40
l. 0995 l E. + 12 BO o.os 42 - 38
A = l. 4 B =
65.2
66.6 -63. R
3.36936E+9 91·2R 2.14724E-2
.ADD
SIJM IS 1R7.2
6 Advanced BASIC
ADDI
I72
17 4 REM
!RO DATA 21, 39, 11.J, :'!4.~, 91·3
190 DATA -.QI
200 END
RIJC)
ADDI
S'J'l IS I 8 7 • ?.
THERE ARE 5 CJJ'1Rl'riS
ADD2
#?45
#?7 g
#? 34
#?98-12
#?43
#? - • 0 I
S'JM IS 29~·12
Note that input statements may be used to call for several values. 100 IN-
PUT X,Y,B9 calls for three numbers to be typed, separated by commas at the
keyboard.
Summary of Sec. 1-2
We have looked at three system commands to give a program a name, in-
struct the computer to RUN a program, and to LIST a program. We have used
the following eight statements in programs; READ, DATA, IF-THEN, PRINT,
END, ST</>P, LET, and INPUT. With just these statements we are able to write
substantial programs (nevertheless, the language does contain tremendous ad-
ditional power in other statements to come in the next sections). The concepts
of variable and program control have been discussed. We have looked at three
kinds of operators: arithmetic, relational, and assignment.
Problems for Sec. 1-2
1) Write a program to average numbers entered as DATA or on INPUT.
2) Write a program to find the largest and/or smallest number of a set of
DATA.
3) Write a program to repeatedly average groups of numbers.
4) Write a program to add all positive integers from 1 ton, where n is an
item of DATA.
5) Write a program to calculate n factorial. Be sure to make the value of
O! equal 1.
6) Write a program to solve equations of the form, ax + b = ex + d.
7) Write a program to solve quadratic equations, ax 2 + bx + c = 0.
8) Write a program to find the sum of the reciprocals of the first n positive
integers.
1-3 Functions, Loops and Lists
BASIC provides computer functions or subroutines for special purposes.
INT(X), SGN(X), ABS(X), and SQR(X) are among them. On some systems the
INT(X) function takes the greatest integer not greater than X, such as 4 for 4.3
and - 2 for -1.6. Other systems simply give the integral part of X, such as 4 for
4.3 and -1 for -1.6, by removing the decimal part. For non-negative numbers,
the two are equivalent. SGN(X) becomes +l if Xis positive, zero if Xis zero,
and -1 if Xis negative. ABS(X) becomes X if Xis non-negative and becomes - X
if X is negative. SQR(X) becomes the principle square root of X so long as Xis
8 Advanced BASIC
HO'JND
94 REM *
THIS PHOGRAM DF.MONSTRATF.S A USE CF THF.
95 REM INT< l FIJNCTICN JN BASH; FC·{ HC'J'.'JDING
96 REM NUMRERS
100 LET E 0 =
110 LET X =
t.R2564
120 PRINT "RO'JND"; ~
130 PRINT
140 PRINT "POWER CF TENTHS", " ROUNDS TC"
-150 LET R = INT< ~•IOtF.+.5 )/!OtE
160 PRINT E, R
162
164 REM *
LINF. 170 JNCRFMF.NTS TYE EXPONUIT OF 10
170 LET E E+l
!RO JF F. <= 5 THF.N 150
190 $ND
RIJN
RO'JND
ROU'JD J. R25~4
DRAW
DRAWOI
2 9 5 2 10
10 Advanced BASIC
Lists
Now suppose that the five people who drew slips of paper from the hat
did not replace them. We must make sure that no number is drawn twice. In
order to achieve this goal we need to be able to keep track of what numbers have
been drawn and what numbers are left. This can be done rather nicely using a
subscripted variable called a "list." A list, designated by a single letter, reserves
space for more than one number. At the time that we first designate a list
variable, the computer automatically reserves 10 locations (some computers re·
serve 11 by allowing zero as a subscript). We can simulate the numbered slips
of paper in the hat by establishing a 10-item list with the integers 1 through 10
stored in locations 1through10. This is done by the following routine:
100 FOR I = I TO 10
110 LETL<Il=l
120 NEXT I
Line 110 sets up the subscripted variable L( ) so that L(l) = 1, L(2) = 2, etc.,
through L(lO) = 10. If we need more than 10, we can get them by using the
DIMension statement. This is usually placed at the very beginning of the pro-
gram. For example, if we want 25 slips of paper in our hat, we would begin with
10 DIM L(25), and 25 locations would be available. Note that we could dimen-
sion for 25 and then use only 10 of them, but we cannot use more than the
DIM statement specifies. Any number of lists may be dimensioned on the same
line as: 10 DIM A(36), B(43). Systems allow a maximum number of storage
locations from a few thousand to many thousands.
Now we can develop a procedure to select five numbers at random without
replacement. For the first draw there will be 10 numbers from which to draw;
for the second draw one has been removed, leaving nine. The process is re-
peated until there remain only six from which to draw for the last draw. This
can be done with another FG)R-NEXT pair. We can step backwards with FG)R
J = 10 TG) 6 STEP -1. We may specify all three numbers on the right of the
equals sign by variable or formula.
If we design a program that merely checks to see if the latest number has
already been drawn, then we get into a trial and error situation. And if we try
to draw 10 numbers from among 10, or worse yet, 100 from 100, the drawing
gets slower and slower as we get nearer and nearer to the last draw (adding sus-
pense and expense). For efficiency's sake we should avoid this pure trial and
error scheme. Thus consider the following procedure for eliminating trial and
error entirely.
For the first draw we may select a number R at random from one to 10.
We may use the value of L(R) as the number on our randomly selected slip of
paper. If we draw the same value of R later on, we need a method that does not
require testing to see if L(R) has been used. We can acheive this by simply re-
placing the value of L(R) with the value of L(J) where J is the number of slips
from which the drawing is being made after each drawn number has been
printed. The important consideration here is that this scheme allows us to use
every number that is drawn. We have taken care here to develop an efficient
algorithm to solve the problem submitted to us. See in particular line 160 in
program DRA W02.
Review of BASIC 11
9 7 3 4 s
We can see from a run of DRA W02 that no number has been drawn more
than once, but one run is not a certainty. A further check can be made by draw-
ing all ~O. We leave this as an exercise.
More Functions
In addition to the functions already described, the following are univer-
sally available: SIN, C</JS, ATN, L</JG, and EXP. SIN(X), C</JS(X) and TAN(X)
give the sine, cosine, and tangent of X, where X is taken as an abstract dimen-
sionless number or the measure of an angle in radians. ATN(X) gives the princi-
ple arctangent in radians, where X is the tangent of the required number.
L</JG(X) gives the natural logarithm of a non-negative X and EXP(X) gives ex.
Besides these there are other functions which may or may not be available on a
particular system. Among these will be log base 10, secant, cosecant, etc. On
some systems CLK(X) gives the present time using a 24-hour clock, and TIM(X}
gives the elapsed time of program run in seconds. It is best to consult the
manual for your system to determine the full extent of function capabilities.
Summary of Sec. 1-3
BASIC generally provides INT, SQR, SGN, ABS, SIN, C</JS, TAN, ATN,
EXP, and L</JG as standard functions, where trigonometric functions are based
on radian measure and exponentials use e as the base. The routine RND is avail-
able to provide random numbers. The language created loop is F</JR A = B
T</J C STEP D, where the loop variable A first takes on the value of B and
increments by D until A passes C and control passes to the next line following
NEXT A which closes the BASIC loop. The default STEP value is always 1.
The list is available as a subscripted variable to allow block storage of several
numbers attached to a single letter. The DIM statement is required for sub-
scripts exceeding 10.
12 Advanced BASIC
PRT
x f"NPCXl f"NT<f"NPCXl l
B 1949.53 1949.5
6 841 .61 841. 6
-5 -245.52 -245.S
10 3746.73 37116.7
-R - 136 3. 11 -1363.t
Subroutines
If we want the computer to return with two or more values, we cannot
use a defined function. Also, in the unlikely case that we want more than 26
functions, we need a new capability. In such cases we use a subroutine. A sub-
routine amounts to a detour in the program that returns to the statement im-
mediately following the one that caused the detour in the first place. 'I'his
capability permits a set of program statements to be accessed from more than
one point in a program. The statement pair G</>SUB-RETURN accomplishes
this.
One significant use of the subroutine is to improve the flow of control
through a program. A subroutine may be used to eliminate the proliferation of
G</>T<l> statements by replacing them with RETURN statements where appropri-
ate. This technique often simplifies the writing of programs. Programs written
in this way are also easier to read and thus easier to correct or modify later (see,
for example, programs GRAPH2 and GRAPH3 of Chap. 5).
Suppose that we want the product and the sum of two numbers modulo
M. We can write a subroutine that calculates and prints both values. Then we
can "call" the subroutine from anywhere in the program with G</>SUB n where
n is the first line of the subroutine. See lines 140 and 210 in program M</>D.
M0D
Subroutines may in turn call other subroutines as in both lines 510 and
550 of MQ>Dl. One thing to avoid in subroutines is inadvertent use of variables
that have been used elsewhere in the program. Subroutines called from other
subroutines are called "nested subroutines." (What else?) In our example
Ml,l>Dl we have nested them two deep. Systems vary, but many have a limit on
how deep subroutines may be nested.
M0DI
or
Arrays
An array is simply a two dimensional list. For this we use two subscripts
separated by a comma and enclosed in parentheses. The first subscript desig-
nates the row and the second subscript designates the column. As with lists,
we can use a subscript as high as 10 without the need for a DIM statement.
Suppose you recorded the temperature at 6AM, 12NOON and 6PM for
one week. This data could easily be stored in an array to enable a program to
carry out various calculations, for example, see program WETHR.
•,JET HR
154 REM *
C:ALC 11LATF: AV<:RAGF: F:ACH DAY
160 FOR D = 1 TO 5
170 LET T = 0
180 FOR I = 1 TO 3
190 LET T = T+A<D, I)
200 NEXT I
210 LET A<D, 4) T/3
220 NEXT D
222
224 REM *
CALCULATE AVERAGF EACH READING
230 FOR I = 1 TO 3
240 LET T = O
250 FOR D = I TO 5
260 LETT= T+ACD,I>
270 NEXT D
?.80 LET AC6, I> = T/5
290 NEXT I
292
300 PRINT "DAY\TIME", "6AM", "12NOCN", "6PM", "DAILY AVG"
310 PRINT
320 FOR D = 1 TC 5
322
324 REM *
~EEP TFRMINAL ON THIS LINE
,125 REM FCR THE NEXT PRINTED RESULT
326 REM WITH TRAILING COMMA IN LINE 330
330 PRINT "DAY"; Q,
340 FOR I = 1 TO 3
350 PRINT A<D, I),
360 NEXT I
370 PRINT A<D,4l
380 NEXT D
382
390 l'Q R I = I TO 5 0
400 PRINT "-";
410 NEXT I
420 PRINT
422
430 PRINT "AVE'<AGF:S",
440 FOR I = 1 TO 3
450 PRINT AC6, I),
460 NEXT I
470 PRINT
472
474 RF:M
4RO DATA ?.7,J6,J4 .. 40,50,55, so,s?.,4~
500 END
RIJN
1 •.!F:THR
AVERAGES 38
Even though the computer permits a subscript as high as 10 for rows and
for columns, it does not require that we use them all. In WETHR we used only
six rows and four columns.
Note that we used loops within loops, or nested loops, several times in
WETHR. The requirement here is that the loops must be nested entirely within
Review of BASIC 17
WETHRl
94 REM * THIS PR0GRAM FINDS HIGHEST TEMPERATURE
95 REM IN A FIVE DAY PERI0D USING ARRAYS
100 DIM AC6,4l
102
104 REM * READ DATA
110 FOR D = 1 TO 5
120 FOR I = 1 TO 3
130 READ ACO, I>
140 NEXT I
150 NEXT D
152
154 REM * THE FIRST ENTRY IS THE HIG4EST SO FAR
160 LETH= AC1,l>
170 LET R = C = 1
180 FOR D = 1 TO 5
190 r0R I = 1 T0 3
200 IF ACD•I> <= H THEN 240
202
204 REM * IF THE CU~RENT ENTRY IS HIGHER THEN
205 REM SAVE DATA IN H, R, AND C
210 LET H ACD,J)
220 LET R D
230 LET C = I
240 NEXT I
250 NEXT D
252
260 PRINT "HIGHEST TEMPERATURE ="I H
262
264 REM * USE Or 24-HOIJR CLOCK SIMPLIFIES
265 REM PRINTING THE TIME
270 PRINT "OCCURS AT"J C*600; "HOURS ON DAY"; R
474 REM
480 DATA 27.36.34. 40,50,55, so,s2,4g
490 DATA 43,41,37, 30,33,28
500 END
RUN
WETHRl
HIGHEST TEMPERATURE = 55
OCCURS AT 1800 HOURS ON DAY 2
MATO!
94 REM *
THIS PROGRAM DEMONSTRATES
95 REM MAT READ AND MAT PRINT
100 DIM A(3,4i, 8(6, IOJ, C<8,9l
110 READ R,c
-120 MAT READ A. 8(2,5), cm.Cl
-130 MAT PRINT A, BJ C
132 REM
140 DATA 4,3
150 DATA 1.,2,3,4,5,6,7,g,9,10,11,12
160 DATA 13, 14, IS, 16, 17, IR, 19,20,21,22
170 DATA 23,24,25,26,27,28,29,30,31,32,33,34
180 END
RUN
MATO!
2 3 4
5 6
9 10 11 12
13 14 15 16 17
18 19 20 21 ~~
23 24 25
26 27 2!l
29 30 31
32 33 34
MAT02
RUN
MAT02
83 98 113 128
83 98 113 128
identity matrix. Having found the inverse of Z, we multiply Y by it. The in-
verse (if it exists) is obtained with the following statement:
100 MAT X = INV(Z)
BASIC allows us to find the transpose of a matrix with the following
statement:
100 MAT X = TRN(Z)
The transpose consists of an array X such that the columns of X are the rows of
Z and the rows of X are the columns of Z. Note that if the dimensions of Z are
(R,C), then the dimensions of X must be (C,R).
We can duplicate an array with
.100 MAT X = Z
and can multiply every entry of an array by the same number with
100 MAT X = (C)*Z
where C is any legal BASIC formula.
In the last seven cases just presented, some systems use the statement
itself to dimension or redimension X, whereas others require that the program
make the dimensions of X compatible in advance.
Summary
BASIC provides a number of MAT statements that greatly simplify pro-
grams which deal with arrays. They are as follows:
MAT READ Reads data into a variable list.
MAT INPUT Enters data from the keyboard into a variable list.
MATX = ZER Fills X with zeros.
MATX = Cq'.>N Fills X with ones.
MATX = IDN Creates the identity matrix.
MAT PRINT Prints the contents of a variable list to the terminal.
MATX = Y Copies the contents of Y into X.
MATX = Y + Z Enters the sum of Y and Z into X.
MAT X = Y - Z Enters the difference of Y and Z into X.
MAT X = Y*Z Enters the product of Y and Z into X.
MAT X = (C)*Y Multiplies each entry of Y by C and enters result in X.
22 Advanced BASIC
2-1 Introduction
None of the features to be discussed in this chapter is absolutely necessary
to writing programs in BASIC. Other language statements may be assembled to
achieve the same effect of each one. Some of them may not even be available on
the computer you are using. However, if your system does provide any of the
features presented here, you are encouraged to experiment since they save
programming effort and storage space and make programs more readable.
(Note about problems: The author has not attempted to contrive problems
which would require the reader to use the various features presented in this
chapter. Rather it is recommended that you be alert to possibilities for using
the material of this chapter in programs you will be writing throughout the rest
of the book.)
2-2 TAB
The T AB(X) function is available on many BASIC systems. T AB(X)
placed in a PRINT statement causes the printing mechanism of the terminal to
be located in the xth space of the current line, provided it has not already passed
that point. Note that on most systems the leftmost space is numbered zero and
the counting is modular, with the mod being typically 72 or 75, but sometimes
more. Some systems are not modular but start on a new line when the TAB
argument exceeds the system line length. An explicit number or BASIC formula
may be entered as the argument of the TAB function. If the value of the argu-
ment is not an integer, most systems use only the integer part. See program
TABOl.
23
24 Advanced BASIC
TABOl
94 REM *
PRINT SCALE TC AID COUNTING SPACES
100 FOR I = 1 TO 5
110 FOR J = 1 TO 9
120 PRINT "-";
130 NEXT J
140 PRINT "!";
150 NEXT I
160 PRINT
162
164 HEM *
PRINT IN LOCATIONS READ FROM DATA
170 FCR K = 1 TO 5
180 READ T
190 PRINT TAflCTlJ "X";
200 NEXT K
210 PRINT
212
214 REM *
SHOW TAfl MORE THAN ONCE IN
215 REM THE SAME PRINT STATEMENT
220 READ A, 9, C
-·230 PRINT TABCAJ; "A"; TAB<Bll "fl"J TA8CCll "C"
234 REM
240 DATA 3, s, 12, 28, 48
250 DATA 2, 7, 15
260 F.:ND
RUN
TABOl
---------!---------!---------!---------!---------!
x x x x x
A B c
Examining the output of program TABOl and counting the leftmost space
as zero, we see that the X's are printed in the spaces numbered 3, 8, 12, 28, and
48, as designated in the DATA ofline 240.
The uses of the TAB function are not limited to literal output. We may
also format numeric output or a mixture of numeric and literal output. See
program TAB02.
TAB02
94 REM *
TAfl DEMONST~ATION PROGRAM
100 DIM AC4l
102
104 REM * HEAD FOUR ITEM A LIST
1 10 F 0 R I = 1 TC 4
120 READ AC!l
130 NEXT I
132
140 PRINT TABC15lJ "CO'IMA SPACING"
150 FOR I = 1 Tr. 4
160 PRINT A<IJ,
170 NEXT I
l'lO PRINT
182
190 PRINT TAAClOll "IJS!NG TAB FOR 10 CHARACTER PRINT ZCNE
200 FDR I = 1 TO 4
210 PRINT TAR< 10•(!-l l l l AC!);
220 NF.XT I
23D PR INT
232
24D PRINT TA'lC6lJ "SF:'11COLCN SPACI'JG"
25 0 FDR I = 1 Tn ,,
260 PR!'JT A<Ill
?.70 ~l".XT I
280 PRINT
Extended Features of BASIC 25
2fl2
~90 Rf'M
300 DATA -3, 11,0,406
310 END
RllN
COM"IA SPACING
-3 I I CJ 40~
llSING TAR FCR 10 r.HARAC:FR PRICIT ZCNES
-3 11 0 406
SEMICOLON SPACING
- 3 1I 0 406
Note that systems differ in the number of spaces generated by the comma
and semicolon delimiters.
2-3 Print Using
While it is possible with the string facilities available in BASIC (see Chap-
ter 3) to print output in any desired form, formatting can require tedious pro-
gramming. It is for this reason that many systems provide PRINT USING and
image statements.
PRINT USING permits the format for printing output for the current line
to be specified in yet another line. The specifications for printing are called the
image. The image can be defined in an image statement, which begins with a
colon. Very simply, a pound sign is used to specify where we want digits printed.
For pound signs placed to the right of the decimal point, zeros to the right of
the last nonzero digit are printed. For pound signs placed to the left of the
decimal point, zeros to the left of the leading nonzero digit are not printed.
One of the common uses of PRINT USING is to obtain zeros to the right
of the decimal point in printed output, since as a numeric the trailing zero is
dropped in BASIC. If we want $3.10 printed, we may use an image to force the
printing of the zero, as shown in our first demonstration program, IMAGEOl.
!MAGED I
IMAGF:02
THE NUMBER rs I
$ I. 000 1.00 1.
THE NUMBER rs 12
$12.000 12.00 12. 12 12 •12
THE NUMBER rs 12.J
$12.300 12.30 12. 12 12 •12
Note that where several dollar signs appear only one of them gets printed.
The one that is printed is as far right as possible in a space that has a dollar sign
in the image. When there is not room to the right of the decimal point in the
image to print all of the digits, the excess is dropped. No rounding off is done.
Where there is not room to the left, all digits get printed anyway, and an asterisk
is printed to call attention to the fact that the number did not fit the image.
The image can be a string. In this case, the line number which calls the
image in the PRINT USING statement is replaced by the string variable that con-
tains the image, as in program IMAGE03.
!MAGE03
We can force the computer to print numeric output using E-format. Four
up arrows are used for this, as shown in program IMAGE04.
Extended Features of BASIC 27
IMAGE04
94 REM *
PRINTS E-FORMAT
100 : ##,##tttt
110 LET N =
24.3
120 PRINT USING 100, N
130 PRINT NJ "IS THE NUMBER"
140 END
RUN
IMAGE04
2.43E+OI
24·3 IS THE NUMBER
IMAGE05
gram statement with IF X THEN 200, and when X=l the computer goes to 200;
otherwise control passes to the next line in sequence, provided X can be only 0 or 1.
We may even print the logical value of statements. If we print the value of
N/X=INT(N/X), we should get a one when Xis a factor of Nanda zero when X
is not a factor of N (see line 150 of program L<!>GICl).
UJGICI
INPUT N?6
x N/X INT<N/Xl TRUTH VALUE OF
N/X INT<N/Xl
I 6 6 I
2 3 3 I
3 2 2 I
4 1. 5 0
5 1.2 0
6
LOG I C2
RUN
LOGIC2
Logical Operators
The logical operators AND, fl>R, and Nfl>T are available on some BASIC
systems and may be used in a wide variety of applications. One rather straight-
forward application is an extension of IF-THEN statements. We may often com-
bine several IF-THEN's into one statement. For example, the pair,
100 IF X= 3 THEN 200
110 IF Y<2 THEN 200
becomes
100 IF X=3 OR Y<2 THEN 200
become
100 IF X=3 AND Y<2 THEN 510
110 PRINT "MESSAGE"
We can negate a statement with Nfl>T. That is, X<>3 and NIPT(X=3) are
equivalent. (When you are unsure of the order of operations, it may be best to
use parentheses if only to make the statement easier to read.) What about X and
Nfl>T X'? In this case, Xis either equal to zero or it isn't. So in the case IF Nfl>T
X THEN 200, control passes to line 200 for X=O (because Nfl>T 0 equals 1) and
passes to the next statement in sequence for all other values.
save program
accessed at any point of the program. In this way we may often
to avoid repeatin g a set of program state-
space, just as G(j>SUB is often used
defined function is accesse d directly whenev er its name is
ments. However, the
control to it.
used and thus it does not require a special stateme nt to transfer
value is re-
The defined functio n may be used in all situatio ns where a single
of parame ters, whereas a subrout ine is more
quired for each parame ter or set
appropr iate if two or more variable s must be returne d.
FIJNCT ION
OF THE
94 REM * THIS PROG'lAM IJFMONST RATES A USE
95 REM MIJLTIPL E LINE 'JSER DEFINED FIJNCTIQ N
96 160
IN L.INES 100 THiW'JGH
97 REM * THE F'JNCTIO N IS DEF INF.D
DEF F NM CX, Y, 7l
=
-{m
LET P X*Y
IF P < Z TH~N 150
LET P = P-Z
140 GOTC 120
150 LET FNM = P
160 FNEND
192
200 PRINT "MULTIP LY A TINIES 8 MOD M TC C:ET"
210 READ A, 8, M
220 IF M =
0 THEN 260
TA8C27l ; FNM(A,
230 PRINT TABC8l; Al TASC16 ll 8; TA8C22) ; M;
240 GOTO 210
242
244 REM
250 DATA 1,2,3, 3,2,4, 3,3,4, Q,O,Q
260 END
R•JN
FIJNCT ION
3-1 Introduction
A string is simply any set of characters that is not to be treated as a number
but is to be otherwise manipulated by the computer. The characters are referred
to as alphameric or alphanumeric, since both alphabetic and numeric symbols
may be used, as are most other symbols permitted by your terminal, even includ-
ing the nonprinting characters. It is the purpose of this chapter to outline a few
of the possible uses of strings and string variables in BASIC even though the
specifications are not uniform from system to system. The user should deter-
mine the capabilities of his or her own system before planning extensive pro-
gramming activity.
3-2 The String Simple Variable
To distinguish the string variable from the numeric variable, virtually all
systems use a trailing dollar sign ($) in the variable name for a string. Legal sim-
ple string variable names are A$, K$, B3$, and C8$. Some systems are restricted
to the 26 letters of the alphabet, not permitting such variables as B3$. Others
allow additional variables such as &$. The number of characters you are allowed
to store in one simple string varies typically from 18 to thousands. Most of the
manipulations allowed for numeric variables are allowed for string variables ex-
cept for arithmetic operations. String variables can be READ, INPUT, assigned,
printed, and compared for order. Order comparison is accomplished according
to ASCII (American Standard Code for Information Interchange) specifications,
which place the digits in order 0 through 9 ahead of the letters of the alphabet
in alphabetical order. (See Appendix A for relevant parts of the code.)
One of the uses of strings is to permit person-computer "conversation."
We do not need to numerically code our answers to questions put to the pro-
gram user. If we wish to give the program operator options, the answers can be
words which the computer processes directly. If for example, we write a pro-
gram that will require a lot of yes-no answers from the keyboard, we may write
31
32 Advanced BASIC
a subroutine that prints the question, checks the answer to be sure that it is
either a "YES" or a "N't)," and rerequests the answer for all other responses.
Program DECIDE uses such a subroutine repeatedly as the computer as-
sembles the information fed into it by the user. The subroutine outlined above
begins in line 800.
DECIDE
FORTRAN?NO
COBOL? NO
BASIC? YES
OLD? YES
PROGRAM NAME?DEC!DE
Strings are read from data in exactly the same manner that numerics are
read from data. String and numeric data may be intermixed. Some systems re·
quire that string data be enclosed in quotes. On systems that do not require
quotes, any expression that contains a comma will have to be enclosed in quotes
anyway, since the comma will otherwise be interpreted as the end of the string.
Look at line 170 of program DECIDE. Note that the string variables are
separated by semicolon delimiters in that PRINT statement. You should see
that the printed output has no spaces other than those actually placed in string
Y$ and the literal expression" - "by the program itself. When printing numeric
values, the computer always provides some space automatically when using semi-
colons as delimiters. When printing strings, the computer does not provide any
space automatically. We can print string characters right next to each other by
using semicolons. We can print strings in 15-character columns using commas, or
we can use the TAB function for other spacing. Some systems also provide
PRINT USING for yet another formatting capability.
We can easily construct a program to do for two strings exactly what pro-
gram C</.>MPAR in Sec. 1-2 did for two numerics, as shown in program C</.>MPR$.
All we want is to determine if A$ is less than, greater than, or equal to B$. Look
carefully to see what happens to the leading and trailing blanks in the strings. In
this case, the leading blank makes" ALPHA" less than "ALPHA", but the trail-
ing blank in "BETA " has no effect. Some systems will not ignore trailing
blanks. Also note that the string 0123456789 is placed in quotes. When calling
for a string read, some computers will ignore such a string unless it is in quotes
because it 'looks like' a numeric.
COM PR$
ARRAYS
AS C 1 l = F IR ST
A$( 2 l = SECOND
AS< 3 l THIRD
Strings 35
array. This makes B$(I) the Ith element of a string list called B$ which may con-
tain up to 11 strings before the DIMension statement is required.
The other concept, as shown in program SUBSTR, considers A$(I,J) as a
substring having J- I+l characters going from the Ith to the Jth character inclu-
sive. So A$(I,I) is the single Ith character. Using this concept, B$(I) is the sub-
string beginning with the Ith character and continuing to the end of the string.
The next two sections will treat these two concepts separately.
SiJ8STR
ASC I
ASC 5
4
6
.
AS = T!1IS IS A TS:ST
) 'THIS'
I•
'
AS( 9
ASC 13
12
17. 'A T".,
'ST
ALPHA
94 REM *
THIS PROGRAM ALPHABETIZES THE
9S REM CHARACTERS OF A STRING
-· 100 DIM ASl72J
110 INPUT AS
-120 LET L=LENCASl
122 REM
124 REM *LINE lSO TESTS ALL PCSSIFlLE PAIRS CF
12S REM CHARACTERS TO SFE IF THEY ARF IN ORDER
130 FOR I=! TO L-1
140 FOR J= I+ 1 TO L
150 IF AS(!,!J <= AS[J,JJ THEN 190
!S2 REM
!S4 REM* IF ASC!,Il IS NOT LESS THAN ASCJ,Jl THEN
!SS REM WE EXCHANGE THOSE CHARACTERS
-160 LET BS=AS[ I, I l
·-170 LET ASC I, ll=AS(J,JJ
-180 LET AS[J,Jl=FlS
190 NEXT J
200 NEXT l
204 REM
210 PRINT AS
220 END
RUN
ALPHA
REV RS
94 REM *
THIS PROGRAM DEMONSTRATES PRINTING THE
9S REM CHARACTERS OF A STRING JN REVERSE ORDER
96 REM WITHOUT MODIFYING THE CONTENTS OF
97 REM THE STRING
100 DIM ASC72J
110 INPUT AS
120 PRINT
130 PRINT " THE STRING CONTENTS JN REVERSE ORDER:"
134 REM
140 FOR I=LENCASl TO 1 STEP -1
ISO PRINT AS(I,Ill
160 NEXT I
164 REM
170 PRINT
180 PRINT
190 PRINT " THE CONTENTS PRINTED IN TACT:"
200 PRINT AS
210 END
RUN
REV RS
END
94 REM *
THIS PROGRAM DEMONSTRATES THE USE OF
95 REM PRINT A$CI> IN THE SUBSTRING SCHEME
100 DIM AS(72l
110 INPUT A$
120 FOR I=LENCA$> TO I STEP · I
130 PRINT "ASC"Jll"> "JA$(!J
140 NEXT I
142 REM
150 END
RUN
END
?THIS IS IT
A$( 10 ) T
A$( 9 ) IT
A$( 8 IT
AS< 7 s IT
A$< 6 IS IT
A$( 5 ) = IS IT
AS< 4 ) = s JS IT
AS< 3 JS IS IT
AS< 2 HIS IS IT
AS< I THIS IS IT
\!EEKA
?TUE
DAY # 3
We can even test parts of two strings. We could test the first three charac-
ters of D$ successively against groups of three characters in A$ looking for a
match by changing line 160 to
160 IF D$(1,3) <> A$(I,I+2) THEN 190
This is left for the reader to try.
It should be clear that by the use of strings we can control what is printed
in every space of the paper on our terminal. If we convert numeric values to
string variables, then we gain some added flexibility for the printing of numeric
results since these can be printed imbedded in strings to avoid extra spaces. If
you have PRINT USING, this step is not necessary.
We shall develop here the beginnings of a routine to convert a numeric to
a string. The fundamental idea is simply to pick off the digits one at a time as
numbers and use the numbers to store string equivalents in the correct positions
of a string variable. The way to get the string equivalent is to use what is called
a dummy string. In this case the dummy string to use contains all the digits.
As shown in program C(/>NVRT, it is D$="0123456789". The string A$ in pro-
gram WEEKA is another example of a dummy string. If we want a "3" stored
in the sixth position of string 8$, we use the following statement:
100 LET 8$(6,6) = D$(4,4)
since the "3" is really in the fourth position of D$. To get the digit "I" in the
Jth position of 8$, we use:
200 LET S$(J,J) = D$(1+1,I+l)
as shown in line 200 of program C(/>NVRT.
CCNIJRT
94 REM *
THIS PRr.GRAM CGNVO:RTS A NIJMFR!r:
95 REM TO A STRING
100 DIM SSC6J,DS( !OJ
110 LET DS="Ol?.34567q9"
120 INP•.JT N
130 IF N=INTCNl THEN 160
140 PRl'IT "INTSGF:RS CNLY"
150 GOTG 120
160 P~INT "*"lNl"*"
170 FOR E=5 TO 0 STEP -I
180 LFT ,J=6-E
190 L~T l=INTCN/!OtEl
-200 U:T S$[.J,Jl=D$[l+ld+ll
210 LET N=N-l*IOtF.
220 NICXT E
:::!30 PRINT "$ 11 ; SS; 0
S"
240 ENO
R•JN
CONVRT
?975310
* 975310. *
$975310$
To append a string onto thP. end of another string, use the technique of
program C(/>NCAT.
Strings 39
C0NCAT
*The programs of Sec. 3-5 were run on the General Electric Information
Services time sharing system.
Strings 41
ALPHA I
HEVRSI
\•!EEKA I
212
214 REM
220 DATA SUNDAY, ·'10NflAY, T 1 1ESDAY, ''!EDNESOAY
230 DATA TH•JRSDAY, Fl<JDAY, SAT•JRDAY
240 END
RIJN
WEEKAI
DAY? T•JESDAY
DAY # 3
?54 ilFM
260 DATA SIJNDAY, MONDAY, T 1 JFSOAY, 1•TDNESO.l\Y
270 D.l\TA THl!RSDAY, FRIDAY, SAT•J!WAY
2fl0 END
RllN
DAY? SIJNDAF
SUNDAY IS DAY # 1
JONES
SMITH
WILLIAMS
Y0UNGMAN
Since strings in the scheme we are now considering may be treated as array
variables, we should realize that we may MAT READ and MAT PRINT string
arrays with all of the same options that these two statements allow for numerics.
That is, we may MAT READ A$(M,N) to redimension the array in the MAT
READ statement. And we may MAT PRINT with semicolon or comma spacing.
Use semicolon spacing with care, however, as this will result in strings being
printed with no spaces. For most systems, quotes are not required when placing
strings in DATA statements unless the string contains a comma or is a numeral.
MAT$
94 REM *
THIS PROGRAM D•MONSTHATFS NAT RFAD
95 REM AND MAT PRINT FCR STHING A~RAYS
100 DIM ASl5, IOI
110 READ R,C
120 MAT READ ASCH.Cl
130 MAT PRINT AS;
140 PRINT
150 MAT PRINT A$,
152
15 4 REM
160 DATA 2,5
170 DATA THIS. rs, A. SAMPLE. PROGRAV
180 DATA WITH, STRING, MAT RFAD, AND, MAT PRINT
190 END
44 Advanced BASIC
RUN
MAT$
THISISASAMPLFPHOGRAM
WITHSTHINGMAT READANDMAT P~INT
Generally speaking, you need not be intimately familiar with the ASCII
code because the ASC( ) function gives the numeric code for the character in
parentheses. Alternatively, we may write a program to print the ASCII code for
alphanumeric characters stored in a string variable, as shown in program ASC.
Note that lines 130, 150, and 160 are used to store single characters from A$ in
the string variable B$. Some time sharing systems provide the EXT$ function.
The statement B$ = EXT$(A$,I,I) would result in the Ith character of A$ being
stored in B$. Some systems use SEG$ for this. You may find numerous other
functions for working with string data available in your system.
ASC
'6. 54
32
••• 58
• /. 47
• (. 40
'(. 91
'A' 65
'A 1 66
'Z' 90
4-1 Introduction
There are tremendous differences in file handling from system to system.
Files give a tremendous extension of power to the BASIC language in two sig-
nificant ways. First, the use of files allows us to handle far more data than we
could ever store in DATA statements of a single program because of computer
space limitations. Second, the use of files allows us to process the same data
using several different programs. We might use one program only to enter data
into a file. Another program might be used to make corrections. Another might
be used to extract a particular piece of information, and yet another might be
used to modify the data in the files. And so on and so on. There is no limit to
the number of programs which may work on the data in a single file or group of
files.
We have chosen to present here file programs on two different systems.
You will want to determine which one resembles your system before attempting
to write programs. The systems chosen here are Hewlett Packard and General
Electric since both are in common use and differ in many ways.
4-2 Hewlett Packard Files
Serial Data Files
Serial files have the advantage that they are quite efficient in the use of
computer storage space. We simply print entry after entry until all desired
entries are in the file or files. Serial files have the disadvantage that we cannot
easily go into the file to change an existing entry or insert a new entry. To do
this to a serial file, we must copy the entire contents into another file making
the changes on the way and then copy the corrected data back into the original
file. Naturally, this is a serious problem only if we are working with a large
amount of data.
Let us construct an inventory file and work on it. Suppose that for each
item of inventory we have a part name, a part number, a price, and a quantity.
46
Files 47
Program ENTERl will enter an initial set of inventory data into a file called
INVOl.
!':.NTF:"ll
94 REM *
THIS P~OGRAM "NT~RS DATA IN AN EMPTY FILE
JOO FIL>'.S I"JVOI
110 DIM PSPSl
120 READ PS,"J,P,Q
130 IF N=O TH~N 240
134 R<:M *
LIN~ 140 Ptl!NTS IT""1 AFTE'l IT~"1 CLOSE PACKED
135 llFM IN THE: FILE MAKIN(; IT si;:RJAL IN STR'JCT'JR'C
140 P~INT #t;PS1N1P10
ISO GOTO 120
194 Rr:M
~00 D!\TC\ "F~AMIS'',10r)t,~.J,l80()," 1 ·llDGi::T'',t00?.1L!.1i,tlOO
210 DATA "RFG'ILATO;<", IOOJ,J.4R,9QQ,"5LIC"JEP", I0r)4,.r)4,9QQO
220 DATA "F-lASMALATO-l". I QOS. I q. 49, qoo. ""'HATS IT". I -Jf)~. I 0. 9R. 1000
230 DATA "STOP",Q,t),O
240 END
'l'IN
"NTF..Rl
DCNE
Line 100 is necessary to make file INVOl available to the present program.
The file must be in existence at the time the program is run. (Some HP systems
provide for ASSIGNing files during program execution.) In this case, we typed
the executive command <tJPEN-INVOl,50 to create the file. That command
specified 50 discrete storage blocks referred to as "sectors" or "records." Each
of our 50 records will hold as many as 32 numerics, where one numeric occu-
pies the same space as 4 string characters. We must add one string character each
for delimiters at the beginning and end of a string and add one if the number of
characters in the string is odd. The record size varies from computer to com-
puter, and some computers allow the user to specify its length. The maximum
number of records allowed varies also.
Line 120 reads from program data statements in the usual way.
Line 130 checks for dummy data.
Line 140 prints the data as read in line 120 but to the external file instead
of to the paper on the terminal in front of us. The #1 is used because the file we
use is the first named in the files statement. If we want to print to the second
file named in a files statement, then we use PRINT #2. We can also use PRINT
#F where F is the file number. File names are separated by commas in the
FILES statement. For example,
100 FILES FILE1,FILE2,FILE3
makes three files available to the program in which this statement appears. Sys-
tems vary as to the number of files that may be named in a files statement. Most
allow at least 8.
This is the very first time that we have run a program which failed to print
anything and yet did something useful. Generally speaking, we should print
something to the terminal. To prove that the data really is in that file, we pre-
sent program READ to read the data out of file INVOl.
48 Advanced BASIC
94
I 00
110 rJ IM PS("" l
l~O P<I\JT "P.'\n \J'\M:O:","P!\H #","Pnc1c","JJANTITY"
l".:!Ll ~C:"'i *
RO:AD DA fl\ '"<8'1 TY" F !IJ
-130 RF.A[) H};P·~ .. ~,;.i,J
134 ·<F.'1 *
Pn\JT T'l'" l)l\TA TC Fl~ TF. <MP.J!\L
140 P ·~ Tr,J T PS, ~, P, ')
1~0 f;'.JTC 111
-140 C::N!J
'J\J
~. '1 I "JCJ
'.• rnr-r. T I IJO~ I~ • ll 111 11
·~>-: r: 11_ C\ TG i~ lrJ<)J J •I~~ 91)0
SL! CNEP 1004 .04 9000
l"~ASMAL.A TOR I 005 18.49 ~00
WHATS IT 1006 10.98 3000
We get all of the information from the file and an error message to boot.
We may avoid the error message by inserting an IF END statement. We will use
105 IF END #1 THEN 160. This statement, executed just once, sets a flag so
that if line 130 tries to read nonexistent data or tries to read past the physical
end of the file, the computer will next execute line 160. Alternatively, of
course, we could have placed our own flag in the file by printing dummy data
into the file at the end of the real data.
We can now sit down and dream up little programs to process the data in
file INVOl. We might want to know the number of parts in inventory. You can
easily verify that program READ2 does that.
READ2
16600 PARTS
It is left as an exercise for the reader to find the total value of inventory
with a program.
Now suppose we want to add inventory to INVOl. Using ENTERl again
with different data will simply replace what is in INVOl with new data. (Actu-
ally, the new data might replace only part of what is already in there, and this
result has other complications.) What we must do is read out to the end of the
data already in the file and then begin printing new data to the file at that point,
as shown in program ENTER2.
Note that program ENTER2 may also be used to enter data into an empty
file. We do not need a different program for this purpose. It is a good practice
to provide for printed output to the terminal in a program of this kind. We run
READl again to make sure that the new data was properly added to the end of
the file.
ENTER2
RIJN
READ!
The next area we might get into is that of making changes in file INVOl
according to business activity. We can do this with the procedures mentioned
earlier, that is, by copying the entire contents of the file into another file,
making changes on the way. However, if the amount of data becomes very
great, the time lost by this method tends to be more important than the space
saved by using serial files. Furthermore, there are many devices for utilizing ran-
dom access files more efficiently. So let's talk about random access files.
Random Access Files
Files are serial or random access according to the structure the program-
mer creates for them. In fact, the same file may be treated as serial by one
program and random access by another. File INVOl was serial because we
printed the data in serially. We may instead use the discrete records of the file
for specifically arranged data.
In our inventory example we might consider placing one inventory item on
one record. Since most of our sample data are equivalent to about 5 numerics,
this would be wasteful of computer space. However, in practice, an item of in-
ventory will contain more data, and thus it is often wise to allow more file space
than is needed at first. Then we will not have to restructure the entire storage
plan as we might if we had placed several inventory items on a single record.
In fact, if programmers anticipate that additional data may be required, they
go one step further. They incorporate the extra variables into all programs,
using zeros for numbers and empty or null strings for anticipated alphameric
data. Then the existing programs will carry all of the variables needed and will
not have to be rewritten to accommodate the new data structure. Of course,
changes will have to be made to actually utilize the newly activated variables
later. Moreover, in some situations we can use space more efficiently by storing
numerics in one file and strings in another with a scheme to link the data from
the two files to each other. That way numeric data may be MAT READ out
of the file for very easy processing.
ENTER3
6 RECORDS USED
Files 51
ENTER4
10 RECORDS USED
52 Advanced BASIC
the first record that has an end of file (sometimes referred to as EOF) marker
and begin printing the new data on that record. Here again, as a check on the
program, we have the computer tell us how many records have been used.
Now we are in a position to explore some possibilities for editing the ran-
dom access file. Note that we selected part numbers, so that if we subtract
1000, we get the number of the record on which that part will be found. Often
in data processing it is helpful to organize data so that something about the data
tells us where to find it. This method is sometimes called "content addressing."
It could consist of an extra item of data for file management purposes only.
Let's write a program that allows us to go into the inventory file and
change anything but the part number. We do this with program UPDATE. The
part number is requested in line 150, and the part is found in line 200. Line
210 prints the part name and offers to make a change possible. The same is
done for the price in line 260 and for the quantity in line 310. When all infor-
mation is correct, it is re,entered into the file in line 360. The IF END state-
ment in line 130 provides for attempting to access a nonexistent record or for
attempting to access a record that has no data on it.
IJPDATE
PART #?1001
F'RAMIS OK?YES
PRICE = $ 2.3 OK?NO
CHANGE T0 $? 3, 24
QTY = 1800 OK?YES
A run of READl confirms that the proper changes were indeed made in
the file.
4) Write a program to find the first empty record and determine the num-
ber of records in the file.
4-3 General Electric Files
We actually are going to talk about external data files in this section, for
in fact, programs are files too, and the data contained in DATA statements of a
program are referred to as "internal files." The creation and use of data files can
be a very complex business indeed. It is the purpose of this section to present
some of the data file concepts and provide sufficient examples so that the reader
will be able to use the power of files in future programming. (Our examples will
of necessity handle only small amounts of data, as it would not be practical to
print the entire contents of very large files.)
Files of two types are available to BASIC programs. They are called
"ASCII files" and "BINARY files." ASCII files are also referred to as "Teletype
files." This term reflects the fact that they may be created by typing data
directly at the terminal using line numbers exactly as a program is typed at the
terminal and that they may be listed directly to the terminal just as a program
may be listed to the terminal. ASCII files may also be used by programs. Binary
files may be used only under program control and may not be written to or read
from the terminal.
ASCII Files
Data may be typed directly to the terminal. All we have to do is create a
file with the command NEW and begin typing our data as if it were a program.
Each line must have a line number followed by a space followed by our data
separated by commas. String and numeric data may be intermixed. Lines may
be corrected by retyping them. Lines may be deleted by typing the line number
followed by return. For an ASCII file to be usable at some later time, it must be
saved by typing the command SA VE.
To demonstrate some of the uses of ASCII files, we have selected the
names of the ten largest cities in the UB. according to the 1960 census, their
rank, and the percentage change in population from 1960 to 1970. File CITY
has been created, the data typed to the terminal, and the file saved as described
above. Since this is a listable file, we do so below.
LIST CITY
CITY
We may now write programs to access the data in file CITY. Probably the
simplest useful task we could perform would be to print the contents of the file
under program control.
Files 55
In order to make the file available to the program we use the FILES state·
ment in line 100 of program READCITY. We may read data from the external
file in a manner similar to that with which we read data from internal files. To
read from the file named in the files statement, we use READ #1 followed by
the list of variables we want. This is done in line 120 of the program. Every
time such a statement is executed, a pointer is moved in the file so that the next
read statement begins to read at the pointer. Initially, all file pointers are at the
very beginning of the file. Note that we could use READ #0 to read from the
data statement of the program. Since it is possible to attempt to read past the
end of the data in the file, we use the IF MIJ)RE statement in line 140. As long
as there is more data in the file, line 140 in our program will direct the computer
to 120. When the data has all been read, line 140 will test false and control
passes to line 150 in this case.
RE ADC I TY
94 REM *
THIS PROGRAM READS THE CONTENTS Or rlLE CITY
-100 rlLES CITY
110 PRINT "CITY"l TABC20)J "RANK"J TABC25)J "% GROWTH"
-120 READ Nt, C$,R,G
130 PRINT C$J TABC20)J Rl TABC25ll G
-140 Ir MORE NI THEN 120
t 50 END
RUN
READC!TY
It turns out that ASCII files are always sequential (serial) in format. This
means that data must be accessed by reading from the first set of data step by
step until the desired information is obtained. There is no way to begin at some
intermediate point of the file. We can, however, add data to the end of the file
with an append statement. APPEND #1 sets the file pointer to the end of data in
the file and prepares the file for writing. For any data processing that requires
tabulating information from each line of data, the sequential nature of ASCII
files is ideal. Furthermore, ASCII files are very easy to edit from the keyboard,
as described earlier. Having seen how to read an ASCII file, we will next see how
to write to such a file with a program.
Let's write a program to transfer the data from file CITY to file CITYl,
rearranging the data so that the order in which the cities appear in the new file
will be according to decreasing percentage growth. One way to create the new
file is with the NEW command. Once you have named the file, type 100, press
the space bar, then the return key, and save the file. Now we have to provide
access to two files in one program. This is done with the FILES statement. Up
to eight files may be named in a FILES statement as long as they are separated
56 Advanced BASIC
GROWTH
94 REM * THIS PROGRAM ARRANGES TEN CITIES ACCORDING TO
95 REM GROWTH RATE USING TWO SEQUENTIAL FILES
IDO FILES CITYJ CITY!
110 DIM ACIQ), BCIO>
112
114 REM* ENTER GROWTH DATA IN ARRAY A AND ORIGINAL
115 REM POSITION IN FILE CITY IN ARRAY B
120 FOR I = I TO 10
130 READ Nt, N$,R,G
140 LET AC!> G
150 LET BCI> = I
160 NEXT I
162
164 REM * BEGINNING OF SORT
170 LET N = I 0
180 LET s = 0
190 FOR I = I TO N-1
200 IF AC!> >= AC!+ I> THEN 280
202
204 REM * EXCHANGE OUT OF ORDER DATA
205 REM AND TURN SWITCH ON
210 LET SI = AC!>
220 LET AC!>= ACI+I>
230 LET AC!+I) = SI
240 LET SI = BC!>
250 LET BC!>= BCI+I>
260 LET BC!+I> = SI
270 LET S = I
280 NEXT I
282
290 LET N = N-1
300 IF S = I THEN 180
302
304 REM * GROWTH RATE IS IN ORDER NOW PRINT
305 REM DATA IN FILE CITY!
31 0 SCRATCH H2
320 FOR I = I TO I 0
330 RESTORE #I
340 FOR J = I TO BC!>
350 READ Nt, N$,R,G
360 NEXT J
362
370 WRITE #2, N$,R,G
380 PRINT N$
390 NEXT I
392
400 END
RIJN
GROWTH
HOUSHlN tEXAS
LOS ANGELES CALIF
NEW YORK N.Y.
PHILADELPHIA PA.
BALTIMORE MD
WASHINGTON D· c.
CHICAGO ILL
DETRO IT MICH
CLEVELAND OHIO
ST LOUIS MO
Files 57
the first city in the file and A(lO) becomes the percentage growth of the tenth
city in the file. Entering is done in lines 120 through 160. We store the original
position in a B array.
Now that the list is in order we know that whatever city has the percentage
growth stored in A(l) goes first in our second file and whatever city has the
growth rate in A(I) goes in the Ith position of file CITYl. However, in order to
prepare a file for printing, we must use the SCRATCH statement. That state-
ment erases whatever is in a file, prepares it for write mode, and sets the file
pointer at the beginning of the file. Since we want to write to the second file
in our FILES statement, we use SCRATCH #2 in line 310. The next complica-
tion we face is that the pointer in file CITY is now at the end of the data. We
move the pointer to the beginning of the file and keep the file in read mode with
the REST</)RE statement in line 330. REST</)RE #N acts on the Nth file in the
FILES statement. The REST</)RE statement must be executed every time we
want to reread the file. The actual entry of the data to file CITYl takes place
in line 370 of program GR</)WTH when we have found the city with the growth
rate in the Ith location of the arranged list A by reading to that city's position
in the original file as determined by list B.
We now run READCITY on file CITYl to confirm the contents of that
file.
Binary Files
Binary files are available only under program control. Whereas ASCII files
may be only sequential, binary files may be either sequential or random access.
Random access means that any data item may be accessed without reading all
data from the beginning of the file up to that data item and that data may be
written to any point in the file directly in the same manner.
An ASCII file or a binary file may be used as a sequential file as deter-
mined by the first WRITE statement which applies to that file after the file is
made available for write mode by the SCRATCH statement. To work with a
file as a sequential binary file simply use a colon (:) where the pound sign (#)
occurs in the READ, REST</>RE, SCRATCH, IF M</>RE and WRITE statements.
The distinction between ASCII and binary files, regardless of sequentiality or
randomness, has to do with the code that is used to store the data on some
device peripheral to the computer, and does not generally effect the programmer
at the level of programming in BASIC.
58 Advanced BASI<;;
RNDENTER
Note that the program generates no printed output. (It is not good general
procedure to write programs with no visible output except to prove, as with pro-
gram RNDENTER, that the program did in fact do something invisible.) We
now need a program to read file RAND. Program RNDREAD does that.
RN DREAD
o.~~0239
0.257207
0.705748
0.717468
0.143835
o. 349935
0.704994
0.649726
0.974231
0.852828
file number N. Once the pointer is set, the next read or write statement begins
reading or writing from that point. In our problem we will be reading a single
numeric value.
In program RNDS'l>RT, line 130 sets the pointer to the Ith word of the
file so that the Ith number may be read by line 140. Line 150 sets the pointer
to the I+ 1st word so that the I+ 1st number may be read out. If they are in the
desired order, line 170 directs the computer to line 230, which causes the next
pair of adjacent numbers to be tested. Should the test in line 170 fail lines 180
RNDSORT
DCJNE
through 210, exchange the positions that the two values occupied in the file.
Then a switch is turned on by setting S equal to one. When the computer has
passed through the list, we test in line 240 to see if any exchanges have been
made. If there have been no exchanges, then the numbers are in order and we
have the computer print "D'l>NE". In the present situation, we rerun
RNDREAD to verify that the program did in fact sort the file.
RUN
RNDREAD
a. 143835
a. 220289
0.251201
Q.349935
Q.649726
0.704994
Q.705748
Q.717468
0.852828
Q.974231
For our final example, let us take the data in the ASCII file CITY and
enter it into a random access file. To do this we must plan very carefully, as we
Files 61
must be able to specify the position of all data in the file exactly. It is usually
convenient to group the data that belongs together on a single record. In our
problem we have three variables: the city name, its rank, and its percentage
growth. The rank and percentage growth are both numerics and so occupy one
word of computer storage each. The city names are strings of different lengths
and so require different amounts of space. A reasonable approach is to allow
space for the largest string and dimension our file accordingly. Clearly L(,t)S
ANGELES CALIF is the longest string we use. The string has four groups of
four characters and one character left over. That requires five words. We must
add one word for internal control plus the two for the numerics. That puts the
required space at eight words of storage per city. So we must CREATE a file
with at least 10 records at eight words per record. We do this with
CRE CITY2,(RAN(8,10))
In order to set the file pointer to the beginning of the Ith record where the
records contain eight words each, all we have to do is point 8(I-1)+1 words from
the beginning of the file, as shown in line 140 of program XFER. This program
transfers the data from ASCII file CITY to random access file CITY2. Notice
that there is no difficulty whatever in accessing two different kinds of file with
the same program.
XFER
10 ENTRIES
Our final task is to arrange the cities according to rank without using a
second file and without using the technique of saving the numbers to be sorted
in an array. This program, program RANK, is very similar to RNDS(,t)RT except
that the pointer is a formula and the read and write statements work with three
variables instead of one.
RANK
REDCITY2
94 REM * THIS PROGRAM READS THE CONTENTS OF FILE CITY2
95 REM AND PRINTS TO THE TERMINAL
100 Fil.ES CITY2
110 PRINT "CITY"; TABC20)J "RANK"J TABC25)J "% GROWTH"
120 FOR I = I TO I 0
130 SETW I TO 8*CI-l) +I
-140 READ 11, C$,R,G
--150 PRINT CSJ TABC20JJ RJ TABC26J; G
160 NEXT I
162
170 END
RUN
REDC!TY2
CITY RANK % GROWTH
NEW YORK N.y, I -0.J
CHICAGO ILL 2 -6.3
LOS ANGELES CALIF 3 12.2
PHILADELPHIA PA. 4 -3.8
DETR01T MICH 5 -10.6
BAL T IM0RE MD 6 -4,7
HOUST0N TEXAS 7 29.3
CLEVELAND 0Hl0 8 - 15· 7
WASHINGT0N D. C. 9 -4.8
ST L0UIS M0 10 -19
FILES statement must name the files we want, separated by semicolons. The
files are numbered according to the order of appearance in the files statement.
As many as eight files may be accessed by a single program simultaneously.
(Provision may be made for substituting new files for previously named old ones
within a program.)
The following special statements apply to ASCII files: REST</>RE #N
moves the file pointer to the beginning of file N and places the file in read mode.
READ #N,A,B,C$ reads values from file N for variables A,B,C$. WRITE
#N,X,B$ enters the contents of X and B$ into file N. SCRATCH #N erases
the contents of file N and places the file in write mode at its beginning. IF
M</>RE #N tests for more data in file N. IF END #N tests for the end of data
condition in file N. All the above statements can be used for binary files by
changing the pound sign (#)to a colon(:). There are some differences when it
comes to random access files, however. SCRATCH :N, when applied to a
random file, fills the file with zeros, sets the pointer to the beginning of the file,
and places it in write mode. IF END and IF M</>RE work only at the physical
end of the file. In addition, there is a special statement for random files to place
the file pointer under program control. SETW N TC/> I may be used to place the
file pointer of file N at the beginning of the Ith word of the file.
Problems for Sec. 4-3
1) Enter student names followed by a fixed number of test scores in a
sequential file. Arrange the students by test average and write the re-
sults to another file.
2) Suppose you have entered a large number of names in a file, last name
first, one name to a string for alphabetizing. Write a program to print
a list of names in alphabetical order but first name first.
3) Write a program to read numerics from two ordered files and print a
single merged and ordered list to the terminal.
4) Write a program that will insert an item of data into an already ordered
random access file so that the new item is in order.
5) You have a random access file with unknown contents. Write a pro-
gram to determine the number of words the file contains.
6) Write a program to enter inventory data into a random access file. The
data should include, for every part, a number, name, price, quantity,
low order point, and reorder quantity. The low order point is the
quantity that should trigger reordering for that part, and the reorder
quantity is the quantity that should be ordered. Write a program or
programs to do any or all of the following: modify quantity and or
price according to business activity, edit the low order point and re-
order quantities, process the file to find the total dollar value of the
inventory, and process the file to determine what parts must be re-
ordered and the quantities to be ordered.
5
E INAL
5-1 Introductio n
There are many sophisticated mechanical plotters on the market offered
by a number of manufacturers. These generally use a pen which draws very
short (0.01 inch is typical) straight line segments as determined by a program.
The smaller the segments, the smoother the curve. However, this chapter is
limited to using the terminal itself as a plotter. There are a number of disad-
vantages to using the terminal for this purpose. Plotting is slow and may there-
fore be expensive. The graphs we get are imprecise, and we can't easily use
graph paper. Be all that as it may, if we have no other plotter, we can get very
helpful plots from the terminal. The terminal has the advantage that it is con-
veniently available.
5-2 Plotting a Function
We can greatly simplify plotting by choosing a function, since functions
have the feature that for any value of x there is exactly one value for y. So, if
we think of y as increasing across the page from left to right and x increasing
down the page from top to bottom, when the plot is completed, we just turn
the paper ninety degrees counterclockwise to obtain the conventional orienta-
tion.
To plot a single function, we first locate the origin and then concern our-
selves with having the terminal mark the axes. Let's plot y = t x + 3. The
b2s!c p!ctt!~g !::; VC"tj" ::;:rnp!c. All that is i1Ccessary is to use Lile T AB(I~) printing
function to get the printing mechanism out to the proper location on the paper
and then print some symbol. Since the TAB function begins counting at the
left margin and we would like to have negative values available for y on the
graph, it will be necessary to move the x axis to the right. How far we move it
64
Plotting on the Terminal 65
will depend on the particular graph. We simply add some constant value to
all TAB arguments. This value is set in line 110 of program GRAPHl. If your
version of BASIC does not have a TAB(N) function, then you may put
PRINT" ";in a loop to get the printing head to the proper spot on the paper.
We print a plus sign to indicate the origin. We will therefore have to check to
see if we are at x = 0 and then determine whether the point of the graph is to
the left or the right of zero.
GRAPH I
*
*
*
*
*
*
+ *
*
**
*
*
*
*
*
GRAPHl seems to do the job we set out to do. (Be sure to tum the re-
sults ninety degrees counterclockwise to view the graph.) However, there are
many improvements that we can make. Let's put in a set of axes. Since the
y-axis is the line where x = 0, the y-axis provision can go after line 140 of
GRAPHl. In order to put the x-axis in, we have to check for each value of x
whether or not the plotted point is below the x-axis. This is done in line 200 of
GRAPH2. As long as we are working on the program, let's add a little flexibility
by putting the position of the x-axis and the domain in as data. See lines 110,
130, and 600 of GRAPH2. Note that a distinguishing character is used to mark
every tenth location in each of the axes. This greatly improves the readability of
the plot. Lines 210 and 420 determine where those marks are printed.
66 Advanced BASIC
GRAPH2
Three runs of G RAPH2 show a variety of results. For the first RUN of
GRAPH2, we present the line y = 1-
x + 3 from program GRAPHl. For the
second RUN, we re-define the function in line 100 to plot the parabola, y =
-.4x 2 - x + 8. For the third RUN, we again re-define the function in line
100 to get the graph of y = .2x 3 - 2x 2 + x + 5.
We have in GRAPH2 a sat!sfacto:ry bas!c graph!?!g p!og!~!!!, =.!!d. the !e-
sults may be enhanced by sketching a curve through the plotted points by hand.
We can still improve on the program itself, though. Consider what the sine
graph would look like using the program as it stands. The graph would show us
little. Clearly we could do better by putting a scale capability in for both axes.
This is left as an exercise.
Plotting on the Terminal 67
*'*'*
* •
I
* •
'*'* *
*
*
*
I
I
* *
* I •
1---------+--*-
*
-----1----- *
! *
* *
--------1---------1---------1---------·-------•-1---
* I *
* *
* !
*
*
'*
* I
* * I
* *
* *
* *
x = 12 * x = 9
c) y = x - INT(x)
d) y = x + INT(x)
e) Y = Vx
2) You may have noticed that the mechanics of your terminal are such
that the vertical and horizontal scales are different. On many termi-
nals there are 10 characters per inch on the horizontal line and six
lines per inch on the vertical page. Use the scaling ability of problem
1 to provide equal scale for both axes relative to the graph.
3) Modify GRAPH2 to handle more than one function.
However, by increasing the value oft, we can have more points plotted. This
tends to "fill in" the graph. Lines 110 and all other references to D are
employed to limit the actual use to only that part of the array that seems neces·
sary for the graph requested. This will save printing time. As written, the pro-
gram causes the printing mechanism to scan the entire line. Considerable print-
Plotting on the Terminal 69
GRAPH3
94 REM *
GRAPH F'RDM DATA ENTERED IN AN ARRAY
100 DIM AC4B,4Bl
102
104 REM * 0 SPECIF'IES WIDTH AND HEIGHT OF' GRAPH
105 REM L IS THE NUMBER OF' SPACES EACH SIDE OF' ZERO
106 REM T DETERMINES GRAPH RESOLUTION
107 REM LI IS USED TO SAVE TYPING L+I REPEATEDLY
110 LET D =
21
120 LET L = <D-1 l/2
130 LET T = •4
140 LET LI = L+I
142
144 REM * ENTER AXES AND ORIGIN IN THE ARRAY
150 F'0R I = I TD D
- 160 LET A<Ll• I> 3
-170 LET A(!, Lt> 2
!BO NEXT I
-190 LET ACLl•LI> =I
192
194 REM * NOW INSERT 4' S TD DESIGNATE PLOTTED POINTS
200 F'OR Y = -L TD L
210 F'0R X = -L TO L
-220 IF' ABS< •5*X+3-Y > > T THEN 300
-230 LET AC X+LI , D-CY+Ll > = 4
300 NEXT X
310 NEXT Y
312
314 REM * THE VALUES ARE STORED NOW PRINT
320 PRINT TABCLllJ "Y"
330 F'DR Y = I TO D
340 F'OR X = I T0 D
350 PRINT TAB<X>J
360 IF' ACX,Y> 0 THEN 380
370 G0SUB 500
380 NEXT X
390 PRINT
400 NEXT Y
410 PRINT TAB<L>J "-Y"
420 ST0P
492
494 REM * PRINTING SUBROUTINE
500 IF' ACX,Y> 2 THEN 550
510 IF' A<X•Y> 3 THEN 580
520 IF' ACX,Y> =
4 THEN 610
530 PRINT "+"J
540 RETURN
550 IF' <X-Lll/10 INT< CX-Lll/10 >THEN 590
560 PRINT "-''J
570 RETURN
580 IF' <Y-Lll/10 INT< <Y-Lll/10 > THEN 560
590 PRINT "!";
600 RETURN
610 PRINT "*"J
620 RETURN
692
700 END
ing time could be saved by sending the printing head back to the beginning of
the new line as soon as the last point is printed. This is left as an exercise.
Three runs of GRAPH3 are presented. The first RUN is the straight line of
the first RUN of program GRAPH2; the second RUN is the parabola of the
second RUN of GRAPH2; and the third RUN is a circle with radius 10 and
center at the point (2,- 3). Note that as with the graphs of Sec. 5-2, these graphs
are distorted by the fact that the space occupied by a single character on the
printed page is higher than it is wide.
70 Advanced BASIC
y
*
*
*
! ** * *
* *!
!
! *
*
!---*-----+---------! *
* !-~~*-----+---~-----!
*
*
*
*
*
*
-Y
*
* -Y
110 LET D = 29
130 LET T 5 =
220 IF ABSC CX-2lt2+CY+3lt2-IOO l > T THEN 300
RUN
GRAPH3
* *****
! *
* *
* *
* *
* *
-~~-!---------+---~-----!----
* ! *
* *
* *
* *
* *
* *
* *
**
*
* !
*****
-Y
Plotting on the Terminal 71
6-1 Introduction
Let us consider a moving object. At constant speed, the distance traveled
is simply its speed multiplied by time. If an object travels 15 feet per second for
5 seconds, it will travel 75 feet. However, it is often true that the speed of an
object is not constant. Suppose the graph of Fig. 6-1 represents an object in
nonconstant motion. The distance the object has traveled at time t is the area
under the graph from the origin to t. For Fig. 6-1 that area is a convenient
geometric shape. We get Area = A = t*60*3 = 90 ft.
70
60
.,,~ 50
::: 40
30
20
10
2 3 4 5
Figure 6-1
Now suppose a graph does not provide such a convenient geometric shape,
as in Fig. 6-2.
72
Area Under a Curve 73
ft/sec
seconds
Figure 6-2
To find the total area of such a shape, we can subdivide the area into many
smaller segments, find the area of each segment, and sum up the individual areas.
All we have to do is decide what kind of smaller segments to use and how large
they should be. Consider Fig. 6-3.
Figure 6-3
Figure 6-3 subdivides the area into rectangles so constructed that each one
falls completely within the desired area. Thus we know that the sum of these
areas will be less than the actual area. We could alternatively place the rectangles
as shown in Fig. 6-4. But that would have the opposite effect on the accuracy.
Another possibility is to construct the rectangles so that the midpoint of the top
Figure 6-4
74 Advanced BASIC
side is a point of the curve, as shown in Fig. 6-5. Now we have some area in-
cluded by the rectangles that is not included by the actual curve and some area
included by the curve but excluded by the rectangles. Thus we expect some
cancelling-out effect.
Figure 6-5
Let us begin by writing a program to sum up the area shown in Fig. 6-5.
In order to test the program, we can make our first function contain a known
2 2
area. We choose a semicircle derived from the circle (x - 5) + y = 25.
This circle has a radius of 5 and its center at the point (5,0), as shown in
f 2
Fig. 6-6A, and so the area we expect is n r 2 or (rr*5 )/2.
(0,0) (10,0)
Figure 6·6A
and
y -./25 - (x - 5) 2
Area Under a Curve 75
For the shaded area of Fig. 6-6A, the function is
y = f(x) = y25 - (x - 5) 2
Thus we can easily define a computer function as follows:
100 DEF FNS(X) = SQR(25 - (X-5)t2))
For this problem we can begin by taking 10 intervals one unit wide. Then the
midpoint of an interval will be x - .5, and the height of the rectangle will be
FNS(X - .5). See Fig. 6-6B and program AREAl.
Figure 6-68
AREAi
The relative error is about .38 in 39 or about 1%. We can improve on this
by taking smaller intervals within the accuracy of the computer.
Let's rewrite program AREAl to allow varying widths of intervals. We can
take the b = 1 out of the x loop and allow the value of b to be read from data.
76 Advanced BASIC
Now since the width of interval will change according to the value of b, the mid-
point of the interval will be x - b/2, and the value of x must be successively
incremented by b, the interval width. While we are at it, let us allow the value of
x to have a variable range read as data. This is done in lines 140 and 160 of
AREA2.
AREA2
Summary of Chapter 6
We have developed a routine that approximates the area under a curve for
functions. The method used is to sum up areas of rectangles whose heights are
determined by the midpoint of the intervals. (There are several other methods,
which are left as exercises.)
Figure 6·7
7) Use the ideas of this section to find the length of the graphed line of a
continuous function instead of the area.
7
c
OME
A(3,5)
e
•8(3, -1)
Figure 7-1
For the points A(3,5) and B(-1,2), we may find the distance by plotting
the points and constructing a right triangle, as shown in Fig. 7-2.
A(3, 5)
I
1 Ac= s- 21=3
J
I
8(-1,2) ___ ..de
BC= I3 - (-1) I= 4
Figure 7-2
or
AB = VBC 2 + AC 2
so that
AB = V4 2 + 32
AB = y'25
AB= 5
It is evident that for any two points A(x 1 ,yi) and B(x 2 ,y 2 ) we have the
relationships shown in Fig. 7-3.
80 Advanced BASIC
I
ii
I AC= IY2 - y
I
______ .de
BC=lxz-xd
Figure 7~3
2
AB = Vlx2 - X11 + IY2 - Y11 2
but since the square of a number equals the square of its absolute value, we get
DIST!
94 REM *
THIS PR0GRAM FINDS THE DISTANCE AB
95 REM r0R THE C00RDINATES CXJ,Yl> AND CX2,Y2)
100 PRINT "T0 rIND THE DISTANCE BETWEEN TW0 POINTS"
150 PRINT
160 PRINT "P01NT A"J
170 INPUT XI.YI
160 PRINT "POINT B"J
190 INPUT X2.Y2
192
194 REM *
CALCULATE DISTANCE AND PRINT IT
-200 LET D = SQRC CX2-Xll•2 + CY2-Yll•2 >
210 PRINT "DISTANCE AB ="J D
222
230 END
RUN
DIST!
T0 r!ND THE DISTANCE BETWEEN TW0 P01NTS
P01NT A?J,5
P01NT B?-1,2
DISTANCE AB = 5
Coordinate Geometry 81
Program DISTl works fine for a single pair of points. But suppose we
had several pairs of points. We may simply request the number of calculations
desired and use FIJ}R-NEX'l', as shown in DIST2.
DIST2
94 REM * FINDS DISTANCE r0R PAIRS 0F P0INTS
95 REM PERMITS M0RE THAN 0NE SET 0r DATA
100 PRINT "T0 FIND THE DI STANCE BETWEEN TW0 P0 INTS"
110 PRINT
120 PRINT "N0W MANY PAIRS"J
130 INPUT N
132
140 F0R I = I T0 N
ISO PRINT
160 PRINT "P0 INT A"J
170 INPUT XI.YI
IBO PRINT "P0 INT B"J
190 INPUT x2,y2
192
194 REM * CALCULATE DISTANCE AND PRINT IT
-200 LET D = SQRC CX2-Xl)t2 + CY2-YJ>t2 >
210 PRINT "DISTANCE AB ="J D
220 NEXT I
222
230 END
RUN
DIST2
T0 rIND THE DISTANCE BETWEEN TW0 P0INTS
N0W MANY PAIRS?2
P0 INT A? 3, 4
P01NT B?o.o
DI STANCE AB = 5
P01NT A?-3.4, 5.75
P0 INT B? 3. 1251 2
DISTANCE AB = 7.52583
For any two points A and B, it can be shown that the coordinates of the
midpoint of segment AB are found by taking the average of the corresponding
coordinates of A and B. 'l'hus the midpoint of AB for A(x 1 ,yi) and B(x 2 ,y 2 ) is
Y2
Slope = m = - ---Y1
-
6 - 3 3
m
5 - 1 4
Note that slopes up and to the right are positive and slopes up and to the
left are negative. A short program can easily be written to make the above cal-
culation, as shown by program SLQ}PE.
SLOPE
POINT A?O,O
POINT 8?4,5
SUJPE = 1.25
POINT A?3,6
POINT 8?5,-3
SL.OPE =-4.5
Look at line 230 in program SLl;1>PE. Note that we instruct the computer
to perform division. When two points have the same x-coordinate, division by
zero is required, which is a mathematically, and thus computationally, unde-
fined condition. The program should be modified to test the value of x 2 - x 1
before allowing division to take place. This is left as an exercise for the reader.
The idea that two points determine a line has been referred to several
times. It can be shown that any line in a plane can be described by an equation
of the form ax + by + c = 0, where a, b, and c are constants. This is called
the general form of the equation. It can also be shown that all nonvertical lines
can be described by an equation of the form y = mx + k, where m is the slope
as defined earlier and k is the value of y when x = 0, that is, the value of y
Coordinate Geometry 83
Figure 7-4
where the line crosses the y-axis, called the y-intercept, as shown in Fig. 7-4.
'I'he form y = mx + k is called the slope-intercept form.
If we are given two points, we can find m in y = mx + k. Then we can
get a value for k by solving y = mx + k for k to get k = y - mx. With a
value for m and a value for k, we can write the equation of the line in slope-
intercept form by using program LINEl.
LINEI
(7-3)
Coordinate Geometry 85
Figure 7-5
= - !!:2 (7-4)
t
we get
t 1
(7-5)
(7-7)
That is, for perpendicular lines having slopes m 1 and m2 , the product of
the slopes is -1, or the slopes are negative reciprocals of each other.
We can use the parallel and perpendicular properties for a variety of prob·
!ems. We can test lines to see if they are either parallel or perpendicular. We can
find the equation of a line through a fixed point parallel or perpendicular to
another line. We can write the equation of a line which is the perpendicular
bisector of a segment.
We shall now present a program to give an equation for the line through a
given point perpendicular to the line determined by a pair of given points. There
are many conditions that we must account for. Suppose the given points deter-
mine a vertical or a horizontal line? We might even be given the same point
86 Advanced BASIC
Start
PERP
(_EN_D)
Begin G¢sus
equation equation
subroutine subroutine
Yes Yes
No
Figure 7-6 Flowchart for finding the equation of a line given one point on
the line and two points determining a line perpendicular to it.
Coordinate Geometry 87
RUN
PERP
LINE THROUGH C 4 , 3
PERPEND I CUL AR Tel THE LINE THROUGH POINTS
C-1 ,9 ),( 4 , 5
EQUATION IS: Y 1.25 *X+C-2
(7-11)
Multiplying Eq. (7-10) through by-a?. and Eq. (7-11) by a, gives
(7-12)
(7 -13)
Adding Eqs. (7-12) and (7-13) produces
Coordinate Geometry 89
(7-14)
Factoring, we get
y(a 1 b 2 - a2b 1) = a 2c 1 - a 1c 2
Let's write a program to use the above results to find the point of inter-
section, if it exists. Note that in Eqs. (7-16) and (7-17) the denominators are
equal. So we may use the BASIC statement,
180 LET D = Al*B2 - A2*Bl
This will allow us to divide the numerators from Eqs. (7-16) and (7-17) by D to
obtain the values for y and x, respectively, unless D happens to equal zero. This
situation would require division by zero, which means that the value is either
indeterminant or undefined depending on whether the numerator is zero or not.
Thus, if the value of D is not zero, we have a unique intersection, which we may
calculate using Eqs. (7 ·16) and (7-17). If D equals zero, we may obtain more
information about the two lines as outlined in the following discussion.
D = 0 means the following:
(7 -18)
and therefore
(7-19)
~ = ll2
(7-20)
b1 b2
To see the significance of this, let's look at the original equations, (7-8)
and (7-9). They are a 1 x + b 1y + c 1 = 0 and a 2 x + b 2 y + c 2 = 0. Solving
each for y we get:
y -ll1X
- - C1
(7-21)
b1 b1
and
ll2X C2
y
bz b2
90 Advanced BASIC
Now the equations are in y mx + k form. Notice that the slope of line 1 in
Eq. (7-21) is -a 1 /b 1 and of line 2 in Eq (7-22) is -a 2 /b 2 unless bi or b2 is zero.
Clearly by multiplying both sides of Eq. (7--20) by -1 we get
- !:.!._. = - ~ (7-23)
b1 b2
Since the two sides of Eq. (7-23) are the slopes of the lines in Eqs. (7-21) and
(7 -22), that makes line 1 parallel to line 2. To sum up, if D = 0, then the lines
are paraiiei and there is no soiution uniess bi or b2 is zero.
T'Jov~' :;uppose that either b 1 or b 2 is zero when D ~ 0. Looking at Eq.
(7-19), if bi = 0 then either a i or b2 is also zero. Now, if Eq. (7-8) is not
meaningless, that means that b 2 must also be zero. If bi and b 2 are both zero,
we get
C1
aix + Ci = 0 or x = (7 -24)
ai
C2
ll2X + C2 = 0 or x = (7-25)
a2
in which case both lines are vertical because x is constant. If what we are look-
ing for is the point of intersection, there won't be any unless the two equations
define the same line, in which case all points on one line will also lie on the other.
We really have three levels of information to test for. First we want to
know if the lines intersect in a single point. If they do intersect in a single point,
then we want the coordinates of that point. If they don't intersect in a single
point, then it is useful to know whether or not they are vertical, because if one
is, they both are. And finally, we can determine whether or not they coincide.
If they coincide, the solution is indeterminan t. If they do not coincide and
are parallel, we say the equations are inconsistent. A flowchart should help to
sort out all of the above considerations. See Fig. 7-7 and program Pq'.>INT.
Start
P0JNT
END~
N1 =A2*C1 -A1*C2
N2= Bl H2 - B2*C1
X =N2/D
Y =Ni/D
calculate solution
POINT
RUN
PO INT
LINES
*X+( l l*Y+( 0
AND
2 *X+( 2 l*Y+( 2 0
NUN-VERT!~AL ~O!N~!UENT
LINES
*X+ ( 2 l*Y+ < 3 0
AND
4 *X+( 5 l*Y+< 6 0
S0LUTI0N IS: C I ,-2
Coordinate Geometry 93
LINES
3 *X+C 0 l*Y+< 4 0
AND
7 *X+C 0 l*Y+C-8 0
VERTICAL PARALLEL
LINES
5 *X+C 3 l*Y+C 10 0
AND
10 *X+C 6 >*Y+C-3 0
N0N-VERT!CAL PARALLEL
;
4) Write a program to find the distance from a point to a line, given two
points on the line.
7-5 Three Points in a Plane
If we are given two points, we know that they lie on a straight line, but if
we are given three points, they may or may not lie on a straight line, that is, they
may or may not be collinear. If they are not collinear, there are many questions
we may ask.
Let us look at three points, A(x 1 , y 1 ), B(x 2 , y 2 ) and C(x 3 , y 3 ), to deter-
mine if they are collinear. Suppose for the moment that if they are, the line
containing them is not vertical. One way to see if they are collinear is to look
at the slope of AB and the slope of BC. If the two slopes are equal, then the
points are on a single line.
Now suppose that we select points (1, 2), (1, 4) and (2, 3) as DATA.
Clearly the slope ciµculation will produce an undefined condition due to an
attempt to divide by zero. We need to check for equal x-coordinates. We need
onlycheckx 1 = x 2 andx 2 = x 3 • lfx 1 = x 2 ,whataboutx 1 - x 2 ? Notice
that x 1 - x 2 would be zero. Now we see that if (x 1 - x 2 )(x 2 - x 3 ) = 0,
then either AB or BC, or both, are vertical segments. Or, to put it another way,
if (x 1 - x 2 )(x 2 - x 3 ) is not zero, then neither AB nor BC is vertical, and it is
safe to instruct the computer to calculate the slopes of both segments. See
especially line 190 in program C(,t)LIN.
94 Advanced BASIC
C0LIN
94 REM *
THIS PR0GRAM DETERMINES WHETHER 0R N0T
95 REM THREE P0INTS IN A PLANE ARE C0LLINEAR.
96 REM IT ALL0WS F0R P0INTS IN A VERTICAL LINE.
100 READ T
110 Ir T = 0 THEN 900
120 PRINT
130 READ x1.v1. x2.v2. X3.Y3
140 PRINT "C"J XIJ "• 1 'J YIJ ">•"J
150 PRINT "C"J X2J "• .. , Y2J "> AND 11 J
160 PRINT ''C''J X3J ''•''J YJJ ''>''
t llJ i.F.i IJ'I
), ( 0 AND (-9
( 6
C0LL !NEAR
' 5 ' 7 J ' 10
( I , 2 ), ( 3 , 4 > AND ( 5 , 7
N0N-C0LLINEAR
( I , 2
N0N-C0LLINEAR
) .
( . 4 AND ( 2 , 3
( 5 , 2 ), ( 5 .-3 ) AND ( 5 , 50
VERTICALLY C0LLINEAR
Suppose we first look for a right triangle. There are at least two proce-
dures we might use. One is to test the lengths of the three sides using the
Pythagorean Theorem, c 2 = a 2 + b 2 • Another is to test the slope of each pair
of sides to see if their product is -1 or if one side is vertical and another is hori-
zontal. Either procedure will be instructive. Let's first investigate Pythagoras
with the aid of Fig. 7-8.
Figure 7-8
A(X(I), Y(1))
Figure 7·9
PYTHI
-{180
170
190
PRINT .. ("J
PRINT ("J
PRINT Jt (II J
fl
XC 1 >1 ", "J YC 1 >J ">, "J
X<2>J ". "J Y<2>J ") AND
X< 3)J "• .. J y ( 3) J ")"
.,
200 G0T0 110
792
794 REM
800 DATA 1. 1 .. 2, 5.--111 6. 15
810 DATA 1. o.. o.. o.. 3.o 4,0
820 DATA 0
900 END
RUN
PYTHI
TABLE 7-1
200 I T0 3
F"0 R P "
210 LET X(P+3l X<P>
220 LET Y<P+3l = Y<P>
230 NEXT P
These four lines have the effect of copying the three points 1, 2, and 3
into locations 4, 5, and 6, respectively, of the X and Y lists. This will enable us
to organize the testing of each side in turn for being the hypotenuse of triangle
ABC, as shown in TABLE 7-1. See lines 200 to 230 in PYTH2.
PYTH2
94 REM *THIS PR0GRAM STORES THE C0RDINATES 0F THE
95 REM VERTICES 0F A TRIANGLE IN THE FIRST THREE
96 REM ELEMENTS 0F X AND Y LISTS AND DUPLICATED
97 REM IN THE NEXT THREE ELEMENTS 0F THOSE LISTS
98 REM T0 FACILITATE USE OF SUBSCRIPTS AND L00PS
99 REM T0 TEST PR0PERTIES OF THE TRIANGLES.
100 DIM X<6» YC6l
110 READ T
120 IF T = 0 THEN 900
130 PRINT
132
134 REM * READ COORDINATES IN LINES 140 TO 160
140 FOR P 1 T0 3
150 READ XCP» Y<P>
160 NEXT P
162
164 REM * PRINT C00RDINATES IN LINES 170 TO 190
170 PRINT "( 0 J X(J)J ",,"; YCl)J "),,"J
IBO PRINT "C"J XC2)J "•"J YC2)J "> AND "J
0
190 PRINT "C"J XC3)J ",,"; YC3)J )"
192
194 REM *DUPLICATI0N TAKES PLACE IN LINES 200 TO 230
200 F0R P = 1 TO 3
210 LET XCP+3> XCP>
- { 220 LET Y<P+3> = YCP>
230 NEXT P
232
234 REM * WE PRINT THE C0NTENTS 0F THE X AND Y LISTS
235 REM F0R DEMONSTRATION PURP0SES ONLY
98 Advanced BASIC
( I 2 .
»( 5 >- I ) AND ( 6
VALUES OF x L00K LIKE THIS IN THE x LIST
. 15
I 5 6 I 5 6
VALUES 0F Y L00K LIKE THIS IN THE Y LIST
2 -1 15 2 -1 15
( 0
VALUES
. 0 »( 0 3 ) AND ( 4.
0F X L00K LIKE THIS IN THE x LIST
. 0
0 0 4 0 0 4
VALUES 0F Y L00K LIKE THIS IN THE y LI ST
0 3 0 0 3 0
Now all that remains is to calculate the lengths of the sides of the triangle
and to store them in such a way that we may test in sequence around the tri-
angle, trying each side as possible hypotenuse. This is accomplished by lines 300
to 350 in PYTH3. Note that line 340 does for the lengths of sides what 210 and
220 do for the coordinates of the vertices.
PYTH3
94 REM *
THIS PROGRAM DETERMINES FROM THE COORDINATES
95 REM 0F THE VERTICES OF A TRIANGLE WHETHER OR
96 REM NOT IT IS A RIGHT TRIANGLE
100 DIM XC6), YC6), DC6)
110 READ T
120 IF T = 0 THEN 900
130 PRINT
132
134 REM *
READ COORDINATES IN LINES 140 TO 160
140 FOR P I TO 3
150 READ X<P>, YCPl
160 NEXT P
162
164 REM PRINT COORDINATES IN LINES 170 TO 190
170 *
PRINT "("J X< 1 )J .. , .. ,; YC 1 ); "),"J
18'0 PR!~IT "("_l 'x:('?)! ": .. ! Y'(2~! ") /\MD "!
190 PRINT ·•c"1 XC3>J "•"J YC3lJ ")"
192
194 REM *
DUPLICAT!0N TAKES PLACE IN LINES 200 T0 230
200 F0R P = I TO 3
210 LET XCP+3) XCP>
220 LET YCP+3> = YCP)
230 NEXT P
232
Coordinate Geometry 99
294 REM *
ENTER LENGTHS IN THE D LIST IN THE
295 REM SAME F'CiJRMAT AS USED F0R COORDINATES IN
296 REM THE X AND Y LISTSJ THAT IS - DUPLICATED
300 F0R J = I TO 3
310 LET A =
X<Jl·XCJ+ll
320 LET B =
YCJl-YCJ+ll
- 330 LET DCJl = SQRC At2+Bt2 l
{ 340 LET DCJ+3l =DCJl
350 NEXT J
352
394 REM *
N0W TEST EACH SIDE FOR BEING A HYPOTENUSE
400 FOR P =
I TO 3
410 IF DCPlt2 DCP+llt2 + DCP+2l•2 THEN 500
420 NEXT P
422
424 REM *IF THE TEST FAILS FOR ALL THREE SIDES THEN
425 REM WE HAVE A NON-RIGHT TRIANGLE
430 PRINT "N0T A RIGHT TRIANGLE"
440 GOTO 110
492
500 PRINT "RIGHT TRIANGLE WITH HYPOTENUSE DETERMINED BY"
510 PRINT "P01NTS: ("J XCP)J ","; YCPlJ ") AND "J
520 PRINT "C"J XCP+l)J ","J Y<P+llJ ")"
530 GOTO 110
'792
794 REM
BOO DATA 1, 1, 2, 5,-1, 6, 15
BIO DATA 1, o, Q, o, 3, 4,0
B20 DATA 0
900 END
RUN
PYTH3
( I .2 ), ( 5
N0T A RIGHT TRIANGLE
,- I ) AND ( 6 . 15
8-1 Introduction
A real polynomial in x can be defined as any expression that can be
written in the following form:
2 + a1X + ao
anxn + an_ 1xn-l + · · · + a2x
For a given value of x, n is a non-negative integer and the a's are constant
values. Examples of polynomials are
2x; 3x 2 + 2; 4; 5x 11 + 3x 3 - 2
The highest exponent of x, called n, is the degree of the polynomial.
Polynomials are of interest to the mathematician and scientist alike.
The distance an object travels in a gravitational field is described by a second
degree polynomial, for example. We will now explore some ways in which
the computer may be programmed to evaluate polynomials and make some
comparisons.
Regardless of the final procedure to be used to evaluate a polynomial,
we will probably want to store the coefficients in a list. If you have zero sub-
scripts available, this is a perfect fit because the subscript of the coefficient is
equal to the exponent on x in each term. If you don't use zero subscripts,
4
simply adjust the variable used for exponents. We arbitrarily select 3x +
3 2
2x - x + 5x + 3 for our first example. The degree of the example is
four, and hence there are five coefficients. The coefficients and the degree of
the polynomial may be entered as data.
One procedure for evaluating a polynomial is to use a BASIC language
function such as
degree less than four we could fill in with zeros, but for degrees more than
four, we would have to retype the line. We are l!lso limited by line length
when DEFining a function on some computer systems. Others allow multiple
line DEFinitions. So while the DEF capability is very useful in some situa-
tions, we might give some thought to developing another procedure for evalu-
ating a polynomial.
Note that the exponent of x is one less than the subscript of the list co-
efficient in each term of the DEF statement. (They are the same if you use
zero subscripts.) Even p(2)*x can be vvTitte11 p(2)~.xtl and p(l) ca11 he writ-
hm .n(l)*x to (unless x = 0). This suggests the fd!c~·!l!!g !ccp:
This four line routine has the desirable feature that it requires no change for
handling polynomials of differing degree.
Suppose we give some thought to the number of operations we are in-
structing the computer to perform. Look at line 320. There we can see an
addition and a multiplication and an exponentiation. For positive integers as
exponents, exponentiation amounts to successive multiplication. That means
for an exponent of I - 1 there will be I - 2 multiplications plus the multi-
plication of the coefficient. That makes I - 1 multiplications for that line.
If we take another look at 3x 4 + 2x 3 - x 2 + 4x + 3 and count the number
of operations, we get four additions and 10 multiplications for our fourth de-
gree polynomial (not accounting for how the computer might handle the ex-
ponent one as a special case). For a 10th degree polynomial there would be
10 additions and 55 multiplications.
Programmers often try to improve the efficiency of their programs because
of the limitations of the computer and the size of the job to be done or purely
for the challenge involved. Notice that in any polynomial, beginning with the
second term, each term has x as a factor one less time than the previous term.
This suggests some sort of successive factoring, as shown by the following:
3x4 + 2x3 (3x + 2)x 3
(3x + 2)x 3 - x2 ((3x + 2)x - l)x 2
((3x + 2)x - l)x 2 + 4x (((3x + 2)x - l)x + 4)x
(((3x + 2)x - l)x + 4)x + 3 (((3x + 2)x - l)x + 4)x + 3
Thus our original polynomial 3x 4 3
+ 2x - x 2 + 4x + 3 can be written in the
following form:
(((3x + 2)x - l)x + 4)x + 3
This is called nested form.
Now there are only four multiplications and four additions called for in a
fourth degree polynomial. Of course, a saving of six multiplications is not much
to a computer, but the saving accumulates as the degree of the polynomial in-
Polynomials 103
creases and as the number of times we evaluate the polynomial increases. Con-
sider the following routine:
We have another four-line routine that is more efficient than the first one.
We now have three procedures for evaluating polynomials. The first is a
defined function, the second is a loop which evaluates the polynomial using ex-
ponents term by term, and the third is a loop which uses nested form. Let's
assemble these three procedures into a program so that we can compare some
values. As we expected, we see that all values do check out by looking at the
output of program PCJ>LYOl.
POL YO l
step through the specified region, trying pairs of values for x to see if f (x 1 )*f (x 2 )
is positive. If it is not, then we have a zero between x 1 and x 2 or either x 1 or x 2
is a zero. If we always find f (x i)*f (x 2 ) positive, there are numerous possible
reasons. We may not have included the zeros in our limits, or we may have had
the computer search such large increments that the graph crosses the x-axis an
even number of times, or the graph may just touch the x~axis at a minimum or
maximum point and never cross the x-axis (the point at which it touches, how-
ever, is still a zero of the polynomial), or there are no real zeros. We must bear
all of these problems in mind as we construct and operate a program.
In program ZER<,l>Ol, line 120 reads the degree of the polynomial and line
140 reads the coefficients. Line 280 tests for sign change. The subroutine
which starts at line 800 evaluates the polynomial by nesting. Line 840 checks
for exact zeros. The general procedure here is just as valid for any continuous
function as it is for polynomial functions. Note that we could use the graphing
of Chapter 5 to assist us in finding regions where we might expect to find zeros.
ZEROOI
884 REM
890 DATA 3, 1,2,3,4
900 END
RUN
ZE.ROOI
POLYNOMIAL IS I 2 3 4
SIGN CHANGE:
P(-2 l=-2 AMO P(-1 l= 2
Interval Halving
Now we have an interval in which we expect to find a zero. We would like
to make that interval smaller and smaller to get successively better approxima-
tions of a zero. We can simply evaluate the polynomial at the midpoint of the
interval found in program ZER</)01 and check for a change of sign against one
endpoint. If a change in sign is found, we bisect and repeat. If a change in sign
is not found, then the change must occur between the midpoint and the end-
point not tested above; therefore we bisect that interval and repeat. After each
bisection the interval is smaller and the midpoint is a better approximation of
the zero. This process is accomplished in lines 400 to 550 of program ZER</>02.
The process needs a stopping place. We need a test of the accuracy of the
current approximation that works for roots very close to zero and far away from
zero, a test, moreover, that is compatible with the precision of the computer.
We would like to get six significant digits in our results. We label the endpoints
of the interval x 1 and x 2 • If we test lx 1 - x 2 I against 10- 6 , we will not get six
significant digits for x 1 and x 2 when they are very close to zero. For x 1 and x 2
large in magnitude, say 100,000, we would require a machine with 12-digit pre-
cision. These problems are avoided by using relative error and testing lx 1 - x 2 I/
(lx 1 I + lx 2 I) against 10- 6 • See line 450 in program ZER</>02.
ZER002
POLYNOMIAL IS I 2 3 4
SIGN CHANGE:
PC-1.7 >=-0.233 AND PC-lo6 >= Q.224
APPR0XIMATE ZERO:
PC-1.65063 >=-4o7632E-6
Factor Theorem
We note that when the value of r is zero, we have p (z) = 0, and that makes
z a solution of the equation p (x) = 0 or a zero of the polynomial Rin~f! t.he rf!-
mainder is zero after dividing by (x - z), it follows that (x - z) must be a
factor ofp(x), or
p(x) = (x - z)q(x)
Having found the first zero using the procedure of Sec. 8-2, we need only find
Polynomials 109
q(x) and then use the procedure of 8-2 on it, repeating until all real zeros are
found.
Synthetic Division
We now develop the synthetic division algorithm using x 4 + 5x 3 +
2
9x + 8x + 4 divided by x + 2 as an example. It is this division that will
enable us to find q (x) above. We begin by performing the division "long hand":
x 3 + 3x 2 + 3x + 2
+ 5x 3 + 9x 2 + 8x + 4
+ 2x3
3x 3 + 9x 2
3x 3 + 6x 2
3x 2 + 8x
3x 2 + 6x
2x + 4
2x + 4
Notice that a great many things will always be written twice. We will always
"bring down" 9x 2 and 8x and 4. For division by x + 2, we will always get x 4
3
and 3x and 3x 2 and 2x repeated. So let us eliminate these repetitions and
compress the problem vertically:
x3 + 3x 2 + 3x + 2
x + 2)x4 + 5x 3 + 9x 2 + 8x + 4
2x3 + 6x 2 + 6x + 4
3x3 + 3x 2 + 2x
Now if we line things up properly, there is no need to write the x's and their
exponents. And there will always be an x in the divisor, so we don't need that.
Let's condense again:
1 + 3 + 3 + 2
+ 2)1 + 5 + 9 + 8 + 4
2 + 6 + 6 + 4
3 + 3 + 2
Since the coefficient of the first term of the quotient is always the same as the
coefficient of the first term of the original polynomial, we can make the bottom
line of figures exactly agree with the top line by simply bringing down the first
figure. Now we eliminate the top line to get:
+ 2)1 + 5 + 9 + 8 + 4
2 + 6 + 6 + 4
1 + 3 + 3 + 2
110 Advanced BASIC
Recognizing that subtraction is the same as "changing the sign and adding," we
can change the 2 to a -2 and add instead of subtracting. That leaves us with:
- 2)1 + 5 + 9 + 8 + 4
-2-6-6-4
---··--· ----
1 + 3 + 3 + 2
The sequence of operations is as folknvs: Bring d{nvn the 1, !!!U1t!p1y the 1 by
- 2, and '.'!rlte it under the 5. Adrl fi anrl - 2 to get 3. Multiply the 3 by - 2 and
write it down under the 9. Add 9 and -6 to get 3. Multiply 3 by -2 and write it
down under the 8. Add 8 and - 6 to get 2. Multiply 2 by - 2 and write it down
under the 4. Add 4 and -4 to get a remainder of 0. Division done by this
algorithm is called "synthetic division."
Since synthetic division is an iterative process, it is especially suited to the
computer. Notice that most of the process consists of multiplying and adding.
Not only is that an iterative process, but it is the same iterative process used for
evaluating polynomials by the nesting method. All that is required to adapt the
subroutine 800 in program ZER'l>02 to synthetic division is to store the sub·
totals along the way in an appropriate list element. This is done in line 820 of
program DIVIDE. Look at program DIVIDE and compare subroutine 800 in
it with the subroutine 800 in ZER'l>02.
DIV IDE
94 REM * THIS PROGRAM USES SYNTHETIC DIVISION
100 DIM PCIS), QCl5>
I I0 READ N
120 PRINT "PCX)•"J
130 FDR I • N+I TO I STEP -I
140 READ PC!>
150 PRINT PCl)J
160 NEXT I
162
170 PRINT
l!lO PRINT "DIVIDE BY X-"I
190 INPIJT XO
200 PRINT "QUOTIENT "J
210 GOSUB 800
220 ST0P
792
794 REM *THE DIVISION TAKES PLACE IN LINES 800 TO 830
795 REM * NOTE THE SIMILARITY TD NESTING
800 LET P3 • QCN+I) • P<N+ll
810 FOR I • N TO I STEP - I
-·820 LET OC!l • P3 • P3•XO + PC!)
830 NEXT I
832
834 REM * PRINT RESULTS
840 FOR I • N+I TO 2 STEP -I
850 PRINT OC!ll
860 NEXT I
862
870 PRINT "REMAINDER •"J QC I>
880 RETURN
882
884 REM
890 DATA 4, 1,5,9,3,4
900 END
Polynomials 111
RIJN
DIVIDE
PCXl= I 5 9 8 4
DIVIDE BY X-? -2
QUOTIENT I 3 3 2 REMAINDER =0
Program DIVIDE works well, but why use a program to perform division
in the first place? Why not simply use program ZERQ)02 to look for zeros until
we find all of them? It is true that program ZER</)02 would easily find - 2 as a
zero of f(x) = x 4 + 5x 3 + 9x 2 + 8x + 4, but then what? Program ZERQ)02
will find no further zeros. We may use the results of a run of program DIVIDE
to see why.
The output of program DIVIDE above tells us that
4
x + 5x 3 + 9x 2 + 8x + 4 = (x + 2)(x 3 + 3x 2 + 3x + 2)
POLYNOMIAL JS I 3 3 2
-2 IS A ZERO
A run of ZER</)02 with the new data reveals why we could not have found one
of the other zeros. We now see that - 2 is a zero of the function f twice and our
program had no way of determining that fact. Values that occur more than once
as zeros are called multiple zeros. Why wouldn't ZER</)02 find the other two
zeros? Let's divide q(x) by (x + 2) and find out.
PCXl= I 3 3 2
DIV IDE BY X-? -2
QUOTIENT I I I REMAINDER 0
The first two factors tell us that - 2 is a zero twice and analyzing the third factor
using the quadratic formula tells us that the final two zeros are nonreal numbers.
They are -t
+ trJ3 and -t -
trJ3.
112 Advanced BASIC
Tht: Fa(;tf;::: Tht:t":re111 teHs us that \;;;hen ·\Ive fh:.d a zero z, ;ve may divide the
polynomial by (x - z) to obtain a new polynomial with one less zero. Synthetic
division has been shown to duplicate the steps of evaluating a polynomial by the
nesting method and so enables us to easily perform the division indicated by the
results of the factor theorem. This enables us to find multiple zeros and, in
some cases, nonreal zeros.
Problems for Sec. 8-3
1) Write a program to find the zeros of third-degree polynomials by find·
ing the first zero and then finding the remaining zeros by using the
quadratic formula.
2) Incorporate synthetic division into program ZER'1>02 so that when·
ever a zero is found, the division is performed and a search is begun for
the next zero.
3) Use the methods of this section to find as many zeros as possible for
the problems of problem 1 in Sec. 8-2.
8-4 Miscellaneous Aids
Integral Zeros
It can be shown that for an nth degree polynomial with zeros Zn,
Considering the product of n binomials on the left we can see that (-zn) ·
(-zn-d ... (-z 2 )(-zi) is the constant term in the product which must equal the
constant term on the right, or a0 • If there is at least one integral zero and a0 is
an integer, that means that all integral zeros of a polynomial must be factors of
a0 • So we could write a program somewhat simpler than ZER<l>Ol that would
search only for integral zeros by first determining all integral factors of a0 • In
program ZER<!>Ol we used p (1) for a0 .
Descartes' Ruie of Signs
Consider the polynomial x 2 + 8x + 1. It should be clear that no matter
2
what positive value we might try for x, we can never make x + 8x + 1 equal
2
zero because x and 8x are both positive for x positive. Thus in searching for
real zeros we need not consider any positive numbers. The same is true for
-2x 2 - 5x - 1. Now, what about x 2 + 3x - 1? Can there be more than one
Polynomials 113
the number of positive zeros depends on the number of variations in the se-
quence, an, an-I, ... , a 1 , a0 , in the following manner. If v is the number of
variations, then the number of positive zeros is either v or v - 2 or v - 4, etc.,
but not less than zero. This may be written v - 2i where i is a positive integer.
It turns out that we may find a corresponding number for negative zeros
by finding positive zeros for p (- x). Substituting - x for x will change the sign of
all terms which have an odd exponent for x. Thus if p(x) = -4x 5 - 3x4 +
5x 3 - 2x 2 + x 3, the value of v is 4 and there must be 4 or 2 or 0 positive
zeros. Now we find that p(-x) = +4x 5 - 3x4 - 5x 3 - 2x 2 - x - 3 and
that v is 1. Thus there must be exactly one negative zero. For example, in
3x 6 - 2x 5 + x 4 - 2x 3 + 5x 2 - x + 1, we might expect to find as many as
six positive zeros, but under no conditions would we look for negative zeros
since p(-x) = 3x 6 + 2x 5 + x 4 + 2x 3 + 5x 2 + 1, which gives zero varia-
tions. All of this gives us a great deal of information. Sometimes the informa-
tion is exact, as when we get 0 or 1 as the number of variations. At other times
we get only a guide, as with x 3 + 2x 2 + 2x + 1, which has no positive real
zeros and three variations for p(-x), which gives 3 or 1 negative real zeros. A
solution of the problem will yield one negative zero and two nonreal zeros in
this particular example.
Problems for Sec. 8-4
1) Write a program to produce polynomials of random degree when zeros
are all random integral values.
2) Write a program to produce an nth degree polynomial given n integral
zeros.
3) Modify program ZER<JlOl to find all integral zeros by having x go from
-a 0 to a0 STEP SGN (ao ).
4) In problem 3, how many additions and multiplications would be re-
quired in a0 = 100 for nesting compared to the use of exponents, not
counting the loop operations?
5) Modify program ZER<JlOl to find all integral zeros by having x take on
only values which are factors of a0 •
114 Advanced BASIC
9-1 Sequences
A sequence is simply a list of numbers. It is, of course, a natural for use in
computers, although a computer list may not be essential for a particular
application.
Sequences come in two kinds, finite and infinite. Obviously we will only
be able to evaluate a finite number of terms for any sequence used in a computer.
We routinely work with sequences. The set of counting numbers is a
sequence, as is the set of odd integers and the set of even integers. If we were to
consider 10 random numbers, they could constitute a sequence. It is more usual
that the numbers in a sequence follow some relatively simple pattern. One such
sequence you've probably seen goes 1, 1, 2, 3, 5, 8, where every number from
the third on is the sum of the previous two. This is called the Fibonacci sequence.
The numbers in this sequence have widespread significance in mathematics, art,
and nature. We can easily write a program to compute elements of this sequence,
store them in a list, and print them, as shown in Program FIBOl. One can
generate a Fibonacci type sequence by selecting any two integers for F(l)
and F(2).
F'l BO 1
144 REM *
N0W PRINT THE LIST
150 F'0R X = I T0 30
160 PRINT F"CX»
170 NEXT X
172
IBO END
RUN
F'lBO I
I I 2 3 5
B IJ 21 34 55
B9 144 233 377 610
00, t c;a"T L "1'£ C:
2584 ~!8!
10946 17711 26657 46J6tl 75025
:.:: : .,,;.-.,, : 96 .!~ i 6 .:; i 75 ii 5i~22~ 032(:40
HALF"
94 REM * THIS PROGRAM HALVES DISTANCE
95
96 REM * INITIAL CONDITIONS - 200 FEET AT TIME ZERO
100 LET D = ?.flO
110 LET T = O
112
114 REM* N0W COVER HALF THE REMAINING DISTANCE
115 REM EVERY MINUTE
120 LET T = T+I
130 LET D = D*Cl/2J
140 IF" D > 6112 THEN 120
150 PRINT "'DISTANCE ="'J DJ "'FEET"
160 PRINT "'IN"'J TJ "'MINUTES"'
17D END
RUN
HALF"
135 PRINT Tl D
RUN
HALF"!
Sequences and Series 117
100
2 50
3 25
4 12.5
5 6.25
6 3. 125
7 1.5625
8 o.78125
9 o.390625
DISTANCE = 0.390625 rEET
IN 9 MINUTES
INT
For some sequences we are merely given a formula. For example, consider
the sequence for which the nth term is (2n - 1)/(2n + 1). We see the first 20
terms in program SEQOl.
118 Advanced BASIC
SEQOI
0.333333 I / 3
U.(; 3 .i ~
0.714286 5 / 7
o. 777778 7 / 9
0.818182 9 / II
0.846154 II / 13
0.866667 13 / 15
0.882353 15 / 17
0.894737 17 / 19
0.904762 19 / 21
0.913043 21 / 23
0.92 23 / 25
0.925926 25 / 27
0.931034 27 / 29
0.935484 29 / 31
o. 939394 31 / 33
o.942857 33 / 35
0.945946 35 / 37
0.948718 37 / 39
0.95122 39 / 41
8) Find how many minutes it will take for you to get to within six
inches of a point if you start 200 feet away and every minute you
cover one-third of the remaining distance.
9) Suppose that a rubber ball is known to bounce to three-fourths of the
height from which it is dropped. If the ball is dropped from 10 feet,
how many bounces will it take to bounce back less than one inch?
10) If you were to place one grain of rice on the first square of a chess
board, two grains on the second, four grains on the third, doubling
the number from each square to the next, how many grains would
you have to place on the 64th square? (Could you?)
11) Print a few terms of any of the following:
(a) 2n + 3 (d) nn
{b} 2n 2 - n + 1 (e) n(l fn)
(c) 2n /n 2 (f) (1 + 1/nt
9-2 Convergence and Divergence
Looking at the sequences of the last section and the results of the prob-
lems, we can see some differences. Note that for the Fibonacci sequence, the
numbers get larger and larger, and for the sequence in which the distance is halved
each minute, the terms get closer and closer to zero. For the sequence generated
by (2n - l}/(2n + 1), the terms seem to get closer and closer to one. The later
two sequences are examples of converging sequences, and the Fibonacci sequence
is an example of a diverging sequence.
If a sequence converges on some value, then that value is called the limit of
the sequence. In the formal study of limits, methods are developed for deter-
mining whether or not a sequence has a limit and for finding the limit if it does
exist. However, we will take a somewhat informal approach here.
The limit of a sequence of values s 1 , s2 , •• • Sn is denoted by
lim Sn
n-+"'
Thus for Sn (2n - l)/{2n + 1), we write:
2n - 1
lim - - - = 1
+ 1
n-+oo 2n
Note that there is no integer for which (2n - l}/(2n + 1) actually equals one,
but the larger n gets, the closer to one the value of (2n l)/(2n + 1) becomes.
We can get some insight into the behavior of sequences by looking at a few terms,
even if that insight is that we need to look at still more terms. In order to be
certain about the properties of some sequences, you should pursue a formal
study of limits. However, one clear benefit of using the computer is that we
may look at hundreds or even thousands of terms without tedious hand calcu-
lations. Of course, one way to save computer time is to print only those values
that we are interested in seeing. Sequences converge and diverge at vastly
different rates. Therefore don't be too quick to infer too much from just a few
terms.
We can look at .lim (-
1-+oo
t/ by writing a very short program to print some
terms. See program LIMO!.
120 Advanced BASIC
LIMO!
I -0.6
2 o. 36
3 -0.216
4 0.1296
5 -0.07776
6 o. 046656
7 -2.79936E-2
B 1.67962E-2
9 - I. 00777E-2
10 6.Q4662E-3
100 6.53319E-23
101 -3.91991E-23
Looking at just the first 10 terms we can see that each term is closer to
zero than the one before and that the values alternate between positive and
negative. For the one-hundredth term, we get 6.5 X 10- 23 and for the one-
hundred and first term we get - 3.9 X 10-23 , making us more and more confi-
dent that the limit is zero.
Not all converging sequences converge on zero. Consider lim (2 + t").
n-+oo
We can see that (i-)" converges on zero, and therefore 2 + (i-)" converges on
2 + 0, or 2. Look at program LIM02, and see how much faster it converges
than program LIMOl.
LIM02
I 2.2
2 2.04
3 2.oos
4 2.0016
5 2.00032
6 2.00006
7 2.00001
B 2.
9 2.
10 2.
I II
2 12.1
3 13.31
4 14.641
5 16. I 051
6 17.7156
7 19.48'72
8 21.4359
9 23.5795
10 25.9374
( c) 1/n!
1
(d) 1 - 1/3! + 1/5! + ... + (-1)"+ /(2n - 1)!
(e) (1 + (1/n)")
{f) sin(n)
n
5) It can be shown for the Fibonacci sequence that the nth term is:
122 Advanced BASIC
+ (2t 1 + (n l)d)
which is therefore twice the sum sn. Note that 2t 1 + (n - l)d occurs n times.
Thus we get 2sn = n(2t 1 + (n - l)d) or 2sn = n(t1 + (t1 + (n - l)d).
Sincethenthte rmist 1 + (n - l)d,weget2sn = n(t 1 + tn)or
Sn (n/2)(t1 + tn)
This gives us a choice for finding the sum of an arithmetic series. We may
use either the formula, or add terms as we generate them in a computer loop.
For a geometric series we have
.L •• 2 • Jn-1\
'JI T lt/ (8-3)
Multiplying both sides by r we get
rsn = t 1r + t 1 r 2 + t 1r 3 + . . . + t 1rn (8-4)
Subtracting (8-4) from (8-3) we get
Sequences and Series 123
which simplifies to
Again we have the choice of finding the sum by formula or by having the
computer add terms as it generates them.
We can get some idea about how the arithmetic and geometric series
behave by picking two terms and treating them as the first and second terms for
both kinds of sequences. This is done for two pairs of terms in two runs of
program GEq.>ARI.
Note that in both cases the sequence of sums for the arithmetic sequence
seems to diverge. In fact, all arithmetic sequences ford <> 0 diverge and so
do their associated sequences of sums. We can see that one of the geometric
sequences diverges and the other seems to converge. All geometric sequences
and their associated series for which lrl < 1 converge.
GEO ARI
RUN
GE0ARI
RUN
GEil AR I
Sn =ti(~)
1 - r
we can see for lrl < 1 that rn gets closer and closer to zero as n gets larger
and larger. Thus 1 - rn gets closer and closer to one, that is, Jim 1 - r n = 1,
n-+~
and
Jim
n-+ 00
Sn = n-+
Jim 00
ti(~)
1 - ,. = ti (
1
1
_ r)
tree; the third day three French hens, two turtle doves, and a partridge
in a pear tree. This continues for 12 days. On the twelfth day she
receives 12 + 11 + · · · + 2 + 1 gifts. How many gifts were there
altogether? Note that the figure asked for here is the twelfth term of
the sequence of partial sums of the sequence of partial sums of the
sequence of positive integers.
9-4 More on Series
There are many series that have importance in the field of mathematics
which are neither arithmetic nor geometric.
It can be shown that the cosine is the sum of an infinite sequence:
x2 x4 x2n-2
cos(x) = 1 - - + - - · · · + (-l)n+l + ···
2! 4! (2n - 2)!
While this is a very tedious calculation by hand, it is relatively simple with the
aid of a computer program. As with finding zeros for polynomials, we use a
relative comparison to decide when to stop (see line 180 of program Cft>SINE).
However, in the case of polynomial evaluation, we were using the value at the
midpoint of an interval which we knew contained the true value. In that case we
had a measure of relative error. In the present situation we have somewhat less
information. We have only the sum of n terms to compare with the sum of
n - 1 terms. Thus we are saying that the magnitude of the most recent term is
small enough to stop summing. When the magnitude of the most recent term is
very small compared to the sum so far, we may expect the error to be small also,
but not necessarily as small. We have not attempted to measure the cumulative
effect of the remaining terms, although methods exist for evaluating it.
COSINE
+ __!__)
nz
+
(2n ~ 1) 2)
10-1 Introduction
A matrix is simply a rectangular array of numbers. As such, an array is a
set of numbers arranged in rows and columns. This is, of course, exactly the ar-
ray we have been using whenever we have used subscripted numeric variables in
BASIC. A matrix may also consist of a single row or a single column. Such
arrays are sometimes called "row vectors" and "column vectors."
It is the purpose of this chapter to study some of the properties of matri-
ces and see some applications. We will not concern ourselves with theorems and
their proofs. A brief review of Sec. 1-5 at this time might be helpful.
Matrices may be studied in a totally abstract setting, but it is useful to
have a concrete example. Suppose that we are operating the Framis Corpora-
tion, which employs three salesmen (it could be 300): Brown, Jones, and Smith.
Brown, Jones, and Smith are selling clevises, hammer handles, shoehorns, and
whipsockets. In a given week the three salesmen turn in orders for merchandise
as shown in Table 10-la.
One fundamental piece of information is the amount of money brought in
by each salesman. To calculate that we need the prices as shown in Table 10-lb.
We can find subtotals by multiplying the price of an item by the number of
items. The subtotals are shown in Table 10-2a. Now to obtain each salesman's
total, we simply add across the rows to get the figures shown in Table 10-2b.
Hammer
Salesman Clevis handle Shoehorn Whipsocket
Brown 30 800 50 20
Jones 50 31 40 10
Smith 0 500 50 90
127
128 Advanced BASIC
IADLC i0·2a
Hammer
Salesman Clevis handle Shoehorn Whipsocket
To make the discussion easier, we label the array of Table 10-la as S, the
array of Table 10-lb as P, and the array of Table 10-2b as M. Thus to get
M(l,1), we add the products S(l,I)*P(I,l), for I going from one to four, and to
get M(2,l), we sum the products 8(2,I)*P(I,l), for I going from one to four.
That makes M(J,1) the sum of the products S(J,I)*P(I,1) for J going from one to
three and for I going from one to four. If the P array had had a second column,
such as the salesmen's commission per item, we could carry out the above pro-
cess for the second column, getting M(J,K) by summing up the products
S(J,I)*P(I,K), for K going from one to the number of columns in P, J going from
one to the number of rows in S, and I going from one to the number of columns
in S. Note that the number of columns in S must equal the number of rows in
P and that the product array has the number of rows in S and the number of
columns in P. This is exactly the definition for matrix multiplication. There-
fore, instead of constructing triply-nested loops to perform the algorithm de-
scribed above, we take advantage of the BASIC matrix multiplication statement
(see line 290 of program SALESl). To make the run of the program more
readable, we have used string lists to provide labeling.
SALES I
130 F0R I =
I T0 4
140 PRINT !$CI>,
150 NEXT I
152
16 0 F0 R I = I T0 3
170 PRINT S$C!l,
180 F0R J = I T0 4
Matrices 129
ITEM PRICE
CLEVIS I
HAMMER HANDLE o. 39
SHOE HORN 0.49
WHIPSOCKET 3.'79
It may strike you that SALESl is rather long, and indeed it is. However,
most of the program is devoted to producing nicely formatted output. If all that
is required is the three dollar amounts at the end of the printout, that can be
done with an extremely short program having just one calculation statement and
one print statement, as shown in program SALES2.
SALES2
442.3
119.59
560.6
There are rnany properties of rnatrices \i\fhich corn.e to light lhrough the
process of just experimenting with different relationships. So it is recommended
that you do as many probiems as possible and that you work on problems of
your own throughout this chapter.
Summary of Sec. 10-1
Matrices are not only convenient as storage areas for data, they possess
mathematical properties that are both interesting and of practical value. The
mathematics of matrix algebra is fairly complex, containing numerous abstract,
involved, and intricate theorems. The thrust of our work will be to use familiar
properties to develop new facts.
A B c
Bulbs 3 1 4
Switches 1 1 2
Meters of wire 9 2 3
Screws 15 8 12
<·r m; :J 2 (blO 2
l 0
1 0
5
8
1
0 1
0 1 m; 5
8 :J
Matrices 131
(<l~ ~ n~ :J
6) Find the result:
:
~1 [~:
800 50
.39
20]] . [1.00]
31 40 10
1 1]
500 50 90 .49
3.79
and compare with the results of problem 1.
(10-1)
We say that two matrices are equal if each entry of one equals the corresponding
entry of the other. (Each entry of a matrix is often referred to as an element of
the matrix.) For MAT A = MAT B that means A(I,J) = B(I,J) for all values of
I and J. Therefore, we may say that
ll1X + b1Y + C1Z = di
a2x + b2Y + C2Z = d2 (10-3)
ll3X + b3y + C3Z = d3
iviairix C may be referred to as the coefficient matrix, : : ; the solution matrix, and
K the matrix of constants. Now we may rewrite Eq. (10-1) in the form
C*S = K
and proceed to solve for S.
It would be very convenient if we could just divide both sides by C. But
it turns out that the division of one matrix by another is not an easily describ-
able process. However, division by C is equivalent to multiplication by the in-
verse of C and the inver~e of C, if it exists, is easily obtained in BASIC.
Before we use an inverse to solve simult.anP.ons linP.ar P.rprntiom:: !i:>t's !ook
more closely at just what the inverse of a matrix is. The inverse of a matrix C
is the matrix c- 1 such that the product of C and c- 1 is the identity matrix. The
identity matrix has the same number of rows as columns and is filled with zeros
except for the upper left to lower right diagonal, which is filled with ones. Note
that in order for a matrix to have an inverse, it must be square.
Let's find, for example, the inverse of
[: :J .[~ :J = [~ ~]
Finding the product on the left we get
[ :: : ~: :: : :: ] = [ ~ ~]
If two matrices are equal, then their corresponding entries are equal. So we get
the following four equations with four unknowns:
5a + 7b 1 6a + Sb 0
5c + 7d 0 6c + 8d 1
We can easily solve these equations to get a -4, b 3, c 3.5, and d
- 2.5. Therefore,
[~ ~]
or
r-4 3 1
L3.5 -2.5J
We can easily verify this with the demonstration program MATINV. (Note
that the computer in some cases, unlike our example here, is susceptible to slight
roundoff errors when the MAT INV statement is used.)
Now to get back to solving simultaneous linear equations. We had the
Matrices 133
MAT INV
94 REM *
THIS IS A PR0GRAM TO DEMONSTRATE MAT INV
100 DIM xc2.2>. AC2.2), PC2.2>
110 MAT READ A
120 MAT X = INVCAl
122
130 PRINT "ORIGINAL MATRIX"
140 MAT PRINT A
150 PRINT
152
160 PRINT "INVERSE MATRIX"
170 MAT PRINT X
!BO PRINT
182
190 PRINT "THE PRODUCT IS"
200 MAT P =
X*A
210 MAT PRINT P
212
214 REM
220 DATA
230 END
RUN
MA TI NV
0RIGINAL MATRIX
5 6
7 B
INVERSE MATRIX
-4 3
3,5 -2.5
THE PRODUCT IS
I 0
0 I
S0LVE
RUN
S0LVE
S0LUTI0NS1
s-m
translates back to x = 1, y = 2, and z = 3. We may now substitute these
values in Eq. (10-6) to verify that they do in fact solve the system of equations.
Summary of Sec. 10-2
We have seen that sets of simultaneous linear equations may be solved by
considering an equivalent matrix equation C*S = K, where C is the coefficient
matrix, S is a column vector which contains the values of the variables in the
original set of linear equations, and K is a column vector containing the constant
terms in the original set of linear equations. We may solve for S by finding the
inverse of matrix C, so that S c- 1 *K. The inverse may be found with the
BASIC statement MAT I = INV(C). For systems of simultaneous linear equa-
tions having a unique solution, MAT C will always be square, which is one of the
requirements for having an inverse.
Problems for Sec. 10-2
1) Let
A [~ -~ J
Find the print A- 1 , A*A- 1 , and A- 1 *A.
2) Let
B [-80 -1-3]
=
Matrices 135
A = [~ :~ -!] •nd B
11-1 Introduction
The possibilities for using the computer to analyze and summarize large
amounts of data are virtually unlimited. This chapter will introduce just a few
fundamental statistical calculations.
11-2 Average, Variance, and Standard Deviation
One of the most common measures of statistical information is the average
or arithmetic mean. The average is the sum of the measures divided by the num-
ber of measures. In some cases the mere task of counting the number of mea-
surements may be a job in itself. So we can even use the computer to do the
counting for us. All that is necessary is to append an item of artificial data as a
flag to stop counting and calculate the average, as shown in program AVG.
AVG
RUN
AVG
MEASUREMENTS 23
AVERAGE MEASURE B0.3478
The average for a set of data gives no idea of the spread or dispersion of
the data. The average of zero and 100 is 50, and the average of 49 and 51 is also
50. We could get some idea by having the computer find for us the largest and
the smallest rneasures. Even that inf0:rrnatiun eou!d be misleading" since the
largest measure could be much larger than the next largest, or the smallest could
be much smaiier than the next smallest. One way to gain some insight into the
distribution of the measures is to find the average of the amount by which each
measurement differs or deviates from the average of the measures. There is a
flaw here, however, as some will deviate by a positive amount and some will
deviate by a negative amount, thus cancelling each other out. Using mean ab-
solute deviation would avoid this difficulty. However, expressions involving
absolute value are difficult to work with algebraically, and statisticians thus find
the average of the squares of the deviations. This figure is called the "sample
variance." In order to write a formula for variance, we use the Greek letter
sigma, L , which indicates summation. Defining average using summation nota-
tion looks like this:
n
.2: xi
i=l
A =
n
The average A is the sum of all values of xi for i going from 1 to the number of
measurements, which is n, divided by the number of measurements. We define
variance in terms of the average as follows:
n
L (xi - A)2
i=l
V=
n
Even the variance, which gives an indication of how measurements are distrib-
uted, doesn't indicate actual dispersion. It indicates the square of dispersion.
Thus we take the square root of V, getting a number called "standard
deviation":
n
L (xi - A)2
i=l
s2
n
and
s
Some Topics of Statistics 139
I: (xi - A)2 11
i=l 1 x~I - Az
n
I:
n i=l
This means that we can, alternatively, have the computer sum up the squares of
the measures rather than the squares of the deviations. This can easily be incor-
porated into program A VG. See lines 150 and 210 of program VAR.
VAR
MEASUREMENTS 23
AVERAGE MEASURE 80.3478
VARIANCE 202.314
STANDARD DEVIATION 14·2237
2) Modify program VAR so that we get the deviations of the largest and
smallest measures from average in terms of the number of standard
deviations. (If the largest measure is 91 for an average of 70 and the
standard deviation is 7, then the largest measure would be three stan -
dard deviations from average.)
3) Often in practice we use what is called the "weighted average." Sup-
pose that tests count three quizzes and that the final exam counts two
tests. Find the weighted average for quiz marks 70, 80, and 73, test
marks 63, 82, and 91, and a final exam of 83.
4) Generate 100 random numbers from 1 to 201. Caicuiate the average
and standard deviation.
5) Generate 100 random numbers from -100 to 100 and calculate the
average and standard deviation.
6) Devise a scheme without reading data twice for finding accurately
the average and standard deviation for the following data: 9999.12,
9999.36, 9999.64, 10000.03, 10000.41, 9999.83, 9999.51, 9999.13
and 10000.08. Due to roundoff error, many programs will give a large
standard deviation for the above data. (Hint: we can simply measure
differences from 10000 instead of from zero.)
11-3 Median
The median is the middle value. Sometimes the median is presented as an
item of statistical information, such as median income or median weight. If
there are an even number of data items, then the median is the average of the
middle two values. One reason for using the median is that it tends to be less
affected by a few widely dispersed items of data than the average. There are
no particularly difficult calculations required to find the median. What does
have to be done, though, is to first arrange the data in numerical order. Thus
let us develop an ordering routine.
There are many, many ways of ordering. Some ordering procedures are
very elaborate and some are very simple. As the number of items to be sorted
increases, the need for efficiency increases. The study of sorting is a fascinating
and intriguing one. However, we hesitate to become too involved at this time.
We will instead develop an ordering routine that works with only a little atten-
tion to efficiency and defer a more sophisticated study of ordering for another
time and place.
If we test every adjacent pair of numbers in a list and find that they are
in order, then we know that the entire list is in order. This is called a "bubble
sort." If we find any adjacent pair that is not in order, then we can direct the
computer to exchange those two elements so that they are in order. If every
time that we make such an exchange, we turn a switch on by letting S = 1,
J:hen we Cl\n oeterinine ::it the enfl of Checking thro11gh the list th::it lln P}(Ch::inge
has been made and that the list might not be in order yet. If after scanning the
entire list we find that switch Sis still zero, then we know that no exchange has
been made and the list must be in order. After the first scan through the list,
we know that the number at the end of the list is the highest or lowest depend-
ing on which order we specify. That is, it is the number that will be there when
the list is finally ordered. Thus we do not need to check the entire list the next
time; we can check one less item. See program <!>RDER.
Some Topics of Statistics 141
ORDER
94 REM *
THIS PROGRAM ORDERS UP TO 200 NUMBERS
100 DIM LC200)
102
104 REM *READ ANO COUNT DATA
110 LET I = 0
120 LETI=I+l
130 Ir I <= 200 THEN 160
140 PRINT "CURRENT LIMIT IS 200 NUMBERS"
150 ST0P
160 READ L< I>
170 I f L<I> <> .at THEN 120
IBO LET N = I = 1-1
IB4 REM *TURN SWITCH Orr ANO BEGIN SORT
190 LET S = 0
200 LET N = N-1
210 f0R J = I T0 N
-220 Ir L<J> >= LCJ+I) THEN 270
222
224 REM * EXCHANGE ELEMENTS AND TURN SWITCH ON
230 LET St = L<J>
240 LET L<J> = LCJ+t>
250 LET L <J+ I) = SI
-260 LET S = I
270 NEXT J
272
274 REM * CHECK SWITCH
275 REM S = 0 SORT C0MPLETE
276 REM S = I S0RT N0T C0MPLETE
-2BO If S = I THEN 190
2B2
2B4 REM *
THE LIST IS IN 0ROER - PRINT IT
290 r0R X = I T0 I
300 PRINT LCX>J
310 NEXT X
492
494 REM
500 DATA 9B. BO. 73, 92. 11. B4. 83. 79, B7. 73
510 DATA 99, 63. 63. 92. st. 93, 47, 53. B9• 100
520 DATA 9B. 11. 73, .01
530 ENO
RUN
0ROER
100 99 9B 9B 93 92 92 89 B7 B4 B3 Bl BO 79 77 73 73 73
71 63 63 53 47
Note that in line 220 we check for greater than or equal to. What would
happen if we only checked for greater than? If there are two equal numbers in
the list, the switch will always get turned on and cause the routine to be re-
peated endlessly. In program </)RDER we have done two things in the interest
of efficiency. We do not scan that part of the list that we know to be in order,
and we quit when we know the entire list is in order.
There are other things that may be done to improve the efficiency of
program </)RDER. One is to sort "up" the list as well as "down." However,
in spite of these precautions, the general procedure here is satisfactory only for
relatively small amounts of data. If we are to order thousands or hundreds of
thousands of data items, then there are far more efficient algorithms which we
would have to use. The fundamental weakness in the procedure we have used
is that on each pass the computer checks only one less pair of data items than
on the previous pass. Much can be gained by partitioning the data to be ordered
in such a way that only a small fraction of the data need be scanned each time
an item is placed in its final spot in the list. However, such procedures generally
require much more programming effort.
142 Advanced BASIC
If all we want is the median, then there is no need to actually print the
data in order. The middle number for I odd is L(INT(I/2)+1) or L(INT((I+ 1)/2)).
See line 320 of program MEDIAN.
MEDIAN
94 REM *
THIS PROGRAM FINDS THE MEDIAN FOR
95 REM AN ODD NUMBER OF DATA ITEMS
!00 D!M L<200l
i iG LEi ;;; 0
120 LET I = I+ 1
l3U 11• 1 <= ;;!UU IHt.N 160
140 PRINT "CURRENT LIMIT IS 200 NUMBERS"
150 ST0P
160 READ LC I>
170 IF L<I> <> .01 THEN 120
180 LET N = I = 1-1
190 IF N/2 <> INTCN/2) THEN 220
200 PRINT "N EVEN"
210 STOP
220 LET S = 0
230 LET N N-1 =
240 FOR J I TO N =
250 IF L<J> >= LCJ+I> THEN 300
260 LET SI = L<J>
270 LET LCJ) l.CJ+I> =
280 LET L<J+I> = SI
290 LET S = I
300 NEXT J
310 IF S = I THEN 220
312
-320 PRINT "MEDIAN"J LC INTCCI+l>/2> )
492
494 REM
500 DATA 98> so, 73, 92, 77, 84> 83, 79, 87, 73
510 DATA 99, 63, 63, 92, 81, 93, 47, 53, 89, 100
520 DATA 98. 71, 7 3, .01
530 END
RUN
MEDIAN
MEDIAN 81
IQ TEST
110 80
105 84
134 92
128 71
92 83
where rxy is the linear correlation coefficient, Vx is the variance of the X data,
and Vy is the variance of the Y data.
Let's look at the correlation coefficient for the data of Table 11-1. See
program Cft>RREL. The correlation is about .03. That may safely be taken to
indicate that there is no correlation between these two sets of data. That is, IQ
is unrelated to the test score. We can see by inspection that no obvious pat-
tern is present.
We can get some idea of how the value of r is affected by various patterns
in the data by simply using Cfl>RREL with a variety of data. We present two
additional runs for your observation.
CEJRREL
IQ TEST SCORE
110 60
105 64
134 92
126 71
92 63
RUN
C0RREL
IQ TEST SCCJRE
134 92
126 64
110 63
105 60
92 71
CORRELATION ,930
RUN
CORREL
IQ TEST SC0RE
I -2
2 -3
4 -5
5 -6
CORRELATION *-1.000
correlation coefficient for columns 1 and 2, 1 and 3, and 2 and 3 for the data
shown in Table 11-2. See program runs labelled WEATHER. The program is
actually CQ'.>RREL with the READ statement modified as shown in each run.
An alternative approach would be to RESTQ'.>RE the data and use the entire
program as a subroutine three times.
TABLE 11-2 Run Table Showing Normal, Record High, and Record Low
Temperatures for 24 Selected Dates of the Year
32 61 4 32 63 5
46 81 14 53 91 27
33 61 2 34 63 -2
58 90 35 63 90 37
36 68 11 41 86 10
68 97 44 72 98 44
74 102 52 76 98 56
62 89 34 55 89 34
76 97 56 74 94 56
50 84 30 44 72 21
71 97 49 67 93 44
39 68 11 33 60 7
x y x y x y
32 61 32 4 61 4
32 63 32 s 63 s
46 Bl 46 14 B1 14
S3 91 S3 27 91 27
33 61 33 2 61 2
34 63 34 -2 63 -2
SB 90 SB 3S 90 3S
63 90 63 37 90 37
36 6B 36 11 6B II
41 B6 41 10 B6 10
6B 97 68 44 97 44
72 98 72 44 9B 44
74 102 74 S2 102 S2
76 9B 76 S6 98 S6
62 B9 62 34 89 34
SS 89 S5 34 89 34
76 9'7 76 56 97 S6
74 94 74 56 94 56
50 B4 so 30 84 30
44 72 44 21 72 21
71 97 71 49 97 49
67 93 67 44 93 44
39 68 39 II 6B II
33 60 33 7 60 7
For correlation normal to high, we get .944; for normal to low, we get
.984; and for high to low, we get .920. These all indicate a high degree of linear
correlation.
146 Advanced BASIC
12-1 Introduction
'I'he ability of the computer to store information, generate random num-
bers, and make decisions makes it well suited for simulations of all kinds. Com-
puters can be programmed to play games. Programs can be written to simulate
business activity, social phenomena, and numerous activities in the physical
sciences. Computers can be used to conduct gambling enterprises, schedule
classes, and manage production schedules. Some situations are dealt with by
having the computer investigate all possible alternatives. Other situations are so
complex that a procedure must be found that enables the computer to make a
best reasonable decision which may not be the best possible decision. For
example, it is possible to write an unbeatable tic.tac-toe program. However, the
game of chess allows so many possible sequences of moves that it is impossible
to write a program for existing computers to investigate them all.
'l'he purpose of this chapter is to present a few examples of simulation and
to suggest areas for further investigation.
12-2 Lines at the Bank
As the manager of a new bank branch, you are interested in knowing what
to expect in the way of teller requirements. You are presented a bank that has
five windows. As a preliminary trial, you make the following estimates and
assumptions:
1. Assume that there is always a customer waiting with a four-minute
transaction when the bank opens at 9 AM.
2. Always open two windows at 9 AM.
3. Customers will tolerate only as many as 10 persons per line; thus when
all lines are full, a new window must be opened.
147
148 Advanced BASIC
4. During every minute of the day one or two or no customers will enter
with equal probability.
5. Every customer after the first has transactions that will last one, two,
or three munutes with equal probability.
6. A new customer upon entering the bank goes to the line with the
fewest persons. In case of a tie, the customer takes the line closest to the door.
'l. The bank closes at 3 PM.
Our joh now is to wr·ite a c•)mputer program that reacts to each of the
restrictions above and keeps track of the day's business. One possible simulation
is to use two arrays-one from the customer's point of view and one from the
window's point of view. Both arrays have five columns, one per window. The
customer array has 10 rows to allow as many as 10 people in line. The window
array has four rows. The first row contains a '1' to signify that the window is
open and a 'O' to signify that the window is closed. The second row contains the
number of people in line for that window. The third row contains the number
of people served since the run began. The fourth row contains the number of
minutes that the window has been open. The customer array contains the
number of minutes each customer in line will take.
In program LINES, all loops F</>R Wl = 1 T</> 5 scan all five windows.
Lines 200 and 210 open two loops to keep track of time. H stands for hours
and Ml stands for minutes of that hour. Line 240 looks to see if a window is
open, and line 250 adds one minute to open time for the window. Line 260
looks to see if anyone is in line at the open window. Lines 390 through 500
search for the line having the fewest people. Numerous other relevant comments
appear in the REM statements of program LINES.
LINES
94 REM * THIS PR0GRAM SIMULATES LINES AT
95 REM TELLER WINDOWS 0, A BANK
96
97 REM *
ARRAY L IS THE CUSTOMER ARRAY
98 REM ARRAY R IS THE WINDOW ARRAY
100 DIM LCI0,5>. RC4,5J. A$C4l
I 05 RAND0M I ZE
110 MAT READ A$
120 MAT R = ZER
130 MAT L = ZER
132
134 REM *
0PEN WIND0WS I AND 2 BY PLACING A
135 REM I IN ROW I OF COLUMNS I AND 2 IN ARRAY R
140 LET RCl,ll = RCJ.2> = I
142
144 REM *
THE FIRST CUSTOMER ENTERS WITH A
145 REM FOUR MINUTE TRANSACTION
150 LET LCI, I> = 4
160 LET RC2, I> = I
162
164 REM * SET UP L00PS Tel KEEP TRACK lff TIME
200 roR H 0 TO 5
210 rnR Ml I TO 60
220 LET T = 60*H + Ml
222
224 REM * THIS L0BP ADJUSTS TIME FOR
225 REM CUST0MERS AND WIND0WS
230 ,0 R WI = I T0 5
240 ff RC 1,w1 > = 0 THEN 350
250 LET RC4,Wll = RC4,Wll+I
Simulation and Garnes 149
974
980
REM
OATA
..
"!=OPEN O= CLOSED", .. PEO PL.E IN LINE"
990 DATA PEOPLE SSRVED 0 ~ " MINUTES OPENED"
999 END
RUN
LINES
The run shows that ten minutes into the fourth hour the third window
was opened. We can see that at the end of the day there was one person waiting
at window 1, which had served 178 people during the day. Window 2 also had
one person in line, but had served only 153 customers. Similarly, the third win-
dow had served 51 customers and left none in line at the end of the day's
business.
While the results of LINES provide some interesting information, there are
virtually unlimited possibiiities for extracting more information and for testing
changes in the original list of assumptions and estimates.
There have been no provisions for closing a window. We might want to
close a window due to lack of activity or to allow employees time to lunch. In
practice, bank tellers close windows but service those customers already in line.
Simulation and Games 151
Program LINES does not provide for having a window closed with people
standing in line. We could use a "-1" in the window array to signify this
condition.
It is fairly obvious that the assumption of random arrival of customers
is an oversimplification of the true pattern. Clearly, large numbers of people
conduct bank business during their lunch hour. Not only does the arrival of
customers vary during the day, but it varies with the days of the week and of
the month. Fridays tend to be heavier, and the first of the month is heavy.
The limit of 10 persons per line was thus arbitrary and perhaps unrea-
sonable as an absolute limit. The program could be modified to open a new
window when all the lines contain 10 customers, but when all windows are
open and all lines contain 10, then we should allow the lines to grow.
In practice, a new customer generally steps into the shortest line, but
the customer is not obligated to stay there. Thus we could make provision in
our simulator for customers to move to a faster moving line. (We know from
experience that fast-moving lines immediately become slow-moving lines when
we step into them and slow-moving lines immediately become fast-moving lines
when we step out of them.) This points up the fact that although a customer
enters a line based on the number of customers in it, what he really cares about
is how long he has to wait. We could add a row to the window array giving
maximum waiting time so far. We could cause a certain waiting time to trigger
opening a new window.
As the program is written, when a new window opens only new customers
may enter that line. Generally when a new window opens, a whole bunch of
people swarm into the new line. Sometimes the new line quickly exceeds the
old lines in length. We could modify the simulation of LINES to allow an
orderly shift of customers from all lines to a newly opened window.
It is easy to see that we could go on and on at great length, making our
simulation program more and more like what we believe to be the real life
activity. What about drive-in windows, automatic tellers, etc.?
Based on many runs of simulations like this, a business person is in a better
position to make decisions about hiring, opening hours, business procedures, and
other aspects of management than he would be without the computer. Once we
are convinced that a simulation is realistic, then we can experiment with innova-
tive procedures using computer results to warn us of poor changes without
actually having to use customers as guinea pigs.
Similar simulations could be set up for toll booths, grocery store check-
outs, post offices, gas stations, and stores and businesses of all kinds.
Summary of Sec. 12-2
We have looked at a much simplified set of rules for lines at the tellers'
windows of a bank and written a program to imitate the activities of bank
customers for a sample business day. Random numbers are used to simulate the
random nature of the arrival of people at the bank and the random nature of
transactions. Arrays have proved very useful for keeping track of many of the
activities of our banking model. We recognize that simulations usually must be
simplifications of the real activity under study.
152 Advanced BASIC
MAGIC
MAGIC NUMBER IS 65
17 24 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
II 18 25 2 9
A(l,1) ~ A(4,4)
A(2,2) ~ A(3,3)
A(3,2) A(2,3)
A(4,1) A(l,4)
12-4 Games
There are hundreds of games which may be played with computers. There
are games played with cards, dice, dominoes, and numbers. There are board
games and two- and three-dimensional tic-tac-toe. Programs have been written
to play casino gambling games and to simulate slot machines. There are programs
which simulate horse races. Programs can be written to play word games such as
Hangman or Geography using strings and files. Using computer files, game-
p!aying prog:rf!.ms ~2n be dev!setl i,x,rhich mcdify st!'.'atcgy depending en ccnsc··
quences of previous decisions. It is not the purpose of this section to present
any comprehensive or systematic study of games or game strategy. Rather, it is
the purpose of this section to arouse the sleeping giant of gamesmanship that
may lie within the reader by exploring two examples.
Simulation and Garnes 155
Battle of Numbers
The game, Battle of Numbers, begins with two integers, such as 63 and 11,
where one should always be somewhat larger than the other. Two players take
turns subtracting an integer in the range 1 to 11 from 63 and subsequent new
remainders. The last player to subtract loses. The feature that makes this game
intriguing is that usually the first player may assure a win by applying proper
strategy on the very first move. Working out the strategy is fairly straightforward
if we look at the last few moves. Suppose it is your turn, and you may subtract
up to 11 from 15. If you subtract 2 leaving 13, you win because your opponent
must leave you a number in the range of 2 to 12, subtracting in the range 11 to 1.
Now it is your turn again and you can be assured of leaving your opponent a "1,"
which he must subtract, thereby losing. Now one pair of plays earlier you can
assure yourself of leaving your opponent with 13 by leaving 25 and before that
37, and so forth. That is, you want to leave (11 + 1) i + 1, or one more than
an integral multiple of one more than the largest number you are allowed to
subtract. For subtracting in the range 1 to a, then leave (a + 1) i + 1. This
means that if the human player goes first in competition with the computer, the
human can always win except when the original larger number is one more than
an integral multiple of the largest subtractable number. However, one slip-up,
and the computer can always win.
Thus in our game with 63 as the starting total and 11 as the maximum
subtractable integer, divide 63 by 12 to get 5 as the integral quotient. Since 5
times 12 is 60, if we are faced with 61 we can't win and should subtract some
random integer. But since we are not faced with 61, we want to leave our
opponent with 61 by subtracting 2. No matter what our opponent does, we will
leave 49, then 37, then 13, then 1. The calculations and testing here are done in
lines 370 through 410 of program BATTLE. Note that lines 280 through 320
assure that the human player inputs a number in the range 1 to a. If you would
like to play the game, but don't want to type the program, many timesharing
systems include the game under the name BATNUM.
BATTLE
360 STOP
,.,. , .........
,n .. t,,, ..
,,.... t ,"-
-{~~g
TM'T'' ~,I\•
'
LET C = B - C CA+ll*l+I l
Ir C > 0 THEN 420
400 LET C = INT C RNDC-1 HA+ I l
410 Ir B-C < 0 THEN 400
420 LET B =
B-C
430 PRINT "I TAKE"J C
440 Ir B =0 THEN 470
450 PRINT "LEAVING A TaTAL Or"J B
460 GCJTa 250
470 PRINT "*** YClU 'A IN ***"
480 END
RUN
BATTLE
STARTING TOTAL IS 68
YalJ GO? 4
I TAKE 6
LEAVING A TOTAL aF 58
Y0!J G0? 15
I TAKE 7
LEAVING A TOTAL OF 36
YOU G0? 14
I TAKE 6
LE.AV ING A TOTAL OF 16
Y0U GCJ? 15
I TAKE I
*** YCJU 'NIN ***
T0UR
BEGIN WHERE?4,4
G0T T0 41
PRINT IT? YES
0 6 15 0 0 24 39 0
14 II 0 7 36 0 0 25
0 16 9 12 0 26 23 40
10 13 16 6 37 D D
17 0 5 36 27 22 41 0
D 0 2 19 32 35 26 0
0 0 0 4 0 30 21 34
0 3 0 31 20 33 0 29
AND R1<9). If a move is found to be legal, then we enter it into the T array.
When all legal moves are in the Array T, Kl is the number of legal moves. If
Kl is zero, then the knight has reached a dead end and we may print the tour
or not. We present a flowchart in two parts. Figure 12-1 details the sorting out
of legal next moves. Figure 12-2 shows where a legal move chosen at random
is incorporated into the tour.
MAT B=Z:l
Clear the b:~J
M=1
Start move counter
B(R,C) = M
Place move
on the board
MATT =ZER
Clear possible
move array
M=M+1
Bump move
counter
v ••
1c.:i
Yes
Kl=Klg+
Bump legal
move counter
T(1,K1l=R1
T(2, K1)= C1 NEXT T
Enter point as
possible move
Return to main
flowchart at
this point
Figure 12-2 Flowchart for selecting moves at random for Knight's Tour.
APPENDIX A
ASCII Character Set Printable on Model 33
32 64 i
33 65 A
34 66 B
35 67 c
36 $ 68 D
37 % 69 E
38 & 70 F"
39 71 G
40 72 H
41 73 I
42 74 J
43 *
+ 75 K
44 76 L
45 77 M
46 78 N
47 I 79 0
48 0 80 p
49 I 81 Q
50 2 82 R
51 3 83 s
52 4 84 T
53 5 85 u
54 6 86 v
55 7 87 w
56 8 68 x
57 9 89 y
58 90 l.
59 91 c
92
60
61 93 '
l
62 94
63 95
161
Summary of flowchart Shapes
162
APPEND IX C
Summary of Statements in BASIC
NOTE: Not all statements which appear in this appendix will run on all systems
and the list here does not cover every statement for some systems.
163
164 Appendix C
MATRIX INSTRUCTIONS
MAT READ Enters data into numeric and string arrays. Several
arrays can be read in the same MAT READ state·
ment by separating the array names with commas.
MAT PRINT Prints the array(s) listed, separated by commas or
semicolons. The delimiter used specifies spacing
for the preceding array. Numeric and string arrays
are allowed.
MAT INPUT Enters data into an array (string or numeric) from the
keyboard. Some systems allow more than one
array listed here; others do not.
MAT C =A* B Enters the produc t of A and B into array C.
MAT A B + C Enters the sum of B and C into array A.
MAT A B C Enters the difference of Band C into array A.
MA1' A (K)*B Multiplies each entry of B by the scalar K and enters
the result into A.
MAT A= ZER Creates the zero matrix (fills each entry of A with
zero). ZER may be followed by redimensioning
specifications in parentheses.
MAT A C<f>N Fills each element of A with 1. C<!>N may be fol-
lowed by redimensioning specifications in
parentheses.
MATE IDN Forms the identity matrix E. E must be square. All
elements with equal row and column numbers are
1 and all other elements are 0. IDN may be fol-
lowed by redimensioning specifications in
parentheses.
MAT X = INV(A) Finds the inverse of A and enters it in X (if it exists).
MAT A = TRN(B) Fills A with the transpose of B.
FUNCTIONS
FILES
ASCII Files
READ #N, Reads data from the Nth file named in the program
into the variables of the variable list following the
comma.
WRITE #N, Writes data from the variable list following the
comma to the file. The variables in the list may be
separated by semicolons or commas to achieve
corresponding spacing in the file.
IF Mct>RE #N Determines whether or not there is more data in the
file.
IF END #N Determines whether or not the end of the file has
been reached.
APPEND #N Allows additional data to be written to an existing
168 Appendix C
Descriptio n Section
Program
Adds Numbers from Data . . . . . . . . . . . . . 1-2
ADD 1-2
ADDl Adds and Counts Numbers from Data . . . . .
Adds Numbers from Input . . . . . . . . . . . . 1-2
ADD2 3-3A
ALPHA Arranges Character s of String . . . . . . . . . .
First Use of Change Statemen t . . . . . . . . . 3-3B
ALPHAl
Area by Summing Rectangle s . . . . . . . . . . 6
AREAl
Areal with Variable Interval Width . . . . . . 6
AREA2 3-3
ARRAY$ Demonstr ates a String Array . . . . . . . . . . .
Prints Sample ASCII Codes . . . . . . . . . . . . 3-3B
ASC
AVG Averages Numbers from Data . . . . . . . . . . 11-2
Plays Battle of Numbers . . . . . . . . . . . . . . 12-4
BATTLE
B(,l)UNCE Prints Successiv e Heights for a Magic Ball .. 9-2
CITY First GE Data File . . . . . . . . . . . . . . . . . 4-3
C(,l)LIN Determin es Colineari ty of Three Points
in a Plane . . . . . . . . . . . . . . . . . . . . . . . 7-5
C(,l)MPAR Compares Two Numerics . . . . . . . . . . . .. 1-2
C(,7)MPR$ Program COMPAR with Strings . . . . . . . . . 3-2
C(,l)NCAT Appends One String on Another . . . . . . . . 3-3A
C(,l)NVRT Converts Numeric to String . . . . . . . . . . .· 3·3A
C(,l)RREL Calculate s Linear Correlatio n Coefficie nt . . 11-4
C(,l)SINE Compares Computer cos(x) Function and
Series Evaluatio n . . . . . . . . . . . . . . . . . . 9-4
DECIDE First Demonstr ation of Strings . . . . . . . . . 3-2
DISTl Uses Distance Formula for Two Points ... . 7-2
DIST2 Finds Distance for Several Pairs of Points .. 7-2
DIVIDE Demonstr ates Synthetic Division . . . . . . . . 8-3
DRAW Draws 5 Numbers at Random from 10 with
Replacem ent . . . . . . . . . . . . . . . . . . . . . 1-3
DRAWOl Draws with FOR-NEX T . . . . . . . . . . . . . 1-3
DRAW02 Draws Numbers from io Without
Replacem ent . . . . . . . . . . . . . . . . . . . . . 1-3
END Prints A$(I) in Substring Scheme . . . . . . . . 3-3A
ENTERl Prints Data Serially in File INVOl (HP) ... . 4-2
ENTER2 Adds Data to File INVOl (HP) . . . . . . . . . 4·2
ENTER3 Prints Data to Random Access File
INV02 (HP) . . . . . . . . . . . . . . . . . . . . . . 4-2
ENTER4 Adds Data to File INV02 (HP) . . . . . . . . . 4-2
FIB(,7)1 Prints the First 30 Fibonacci Numbers ... . 9-1
FUNCTI(,l)N Demonstr ates Multiple Line Defined
Function . . . . . . . . . . . . . . . . . . . . . . . . 2-5
GE(,l)ARI Compares Geometri c and Arithmeti c
Sequence s and Series . . . . . . . . . . . . . . . . 9-3
GRAPHl Bare Plot, No Axes, Origin Only . . . . . . . . . 5-2
GRAPH2 Graphl with Axes . . . . . . . . . . . . . . . . . . 5-2
GRAPH3 Plotting from an Array with Axes . . . . . . . 5-3
GR(,l)WTH Orders Contents of City into File
CITYl (GE) . . . . . . . . . . . . . . . . . . . . . 4-3
HALF Halves Remainin g Distance of Separatio n .. 9-1
IMAGE01 -
IMAGE05 Demonstr ates Print Using . . . . . . . . . . . . . 2·3
INT Compute s Compoun d Interest by Formula . 9-1
LIMOl Prints Powers of (-3/5) . . . . . . . . . . . . . . 9-2
LIM02 Prints Terms of (2+(1/5)1 H) . . . . . . . . . . . 9-2
LINEl Gives Equation of Line Given Two Points 7-2
169
Program Description Section
LINES Simulates Bank Teller Window Activity 12-2
L(iJGICl Prints Truth Vaiues . . . . . . . . . . . . . . ::l-4
L(,l)GIC2 Gets Factors Using Truth of
N/X=INT(N/X) . . . . . . . . . . . . . . . . 2-4
MAGIC Prints Odd Order De La Loubere Magic
Squares . . . . . . . . . . . . . . . . . . . . . . . . . 12-3
MAT$ Demonstrates MAT READ and MAT PRINT
for String Arrays . . . . . . . . . . . . . . . 3-3B
MATOl Demonstration MAT READ and MAT
PRINT . . . . . . . . . . . . . . . . . . . . . . 1-5
MAT02 Demonstrates
iviATI:N~l
......... . . ...Matrix Product . . . . . . .
.......................... ...
uemonstrates 1v11y1·
1-5
11'~ v 10-~
MEDIAN Finds Median for Odd Number of Data . 11-3
M(}.>D Modular Arithmetic with One Subroutine 1-4
M(,l)Dl Modular Arithmetic with Nested
Subroutines . . . . . . . . . . . . . . . . . . . 1-4
(,l)PRATN Uses t ,*,/,+,- . . . . . . . . . . . . . . . . . . . 1-2
(,l)RDER Orders Numbers from Data . . . . . . . . . . . 11-3
(,l)RDER$ Alphabetizes Names in a String Array ... . 3-3B
PERP Equation of Line Given Point and Points
on Perpendicular Line . . . . . . . . . . . . . . 7-3
P(,l)INT Finds Intersection of Two Lines in
AX+BY+C=O Form . . . . . . . . . . . . . . . . 7-4
P(,l)LYOl Compares Values of F(X) by Three Methods 8-1
PRT Demonstration of User Defined Function .. 1-4
PYTHl Reads and Prints Coordinates of Three
Points . . . . . . . . . . . . . . . . . . . . . . . . . . 7-5
PYTH2 Sets Up Three Points in Six List Positions .. 7-5
PYTH3 Checks Three Points for Vertices of
Right Triangle . . . . . . . . . . . . . . . . . . . . 7-5
RANK Arranges the Contents of File CITY2 (GE) 4-3
READ Reads File INVOl (HP) . . . . . . . . . . . 4-2
READl Reads with IF END Trap (HP) . . . . . . . . . 4-2
READ2 Finds Number of Parts in Inventory File
INVOl (HP) . . . . . . . . . . . . . . . . . . . 4-2
READCITY Reads File CITY (GE) . . . . . . . . . . . . 4-3
REDCITY2 Reads Contents of File CITY2 (GE) .. . 4-3
REVRS Prints String in Reverse Order . . . . . . . 3-3A
REVRSl Reverses Characters of a String Using Change 3-3B
RNDENTER Writes 10 Random Numbers to Binary File
RAND (GE) . . . . . . . . . . . . . . . . . . . . 4-3
RNDREAD Reads File RAND (GE) . . . . . . . . . . . . . 4-3
RNDS(,l)RT Arranges Contents of File RAND (GE) .. . 4-3
R(,l)UND Rounds to Various Precisions . . . 1-3
SALESl Matrix Demonstration . . . . . . . . . . . . 10-1
SALES2 Salesl Stripped to Bare Essentials ... . 10-1
SEQOl Prints Ratios of Successive Odd Integers 9-1
SL(,l)PE Finds Slope of Lines Given Two Points . 7-2
S(,l)LVE Solves Simultaneous Linear Equations Using
MAT INV . . . . . . . . . . . . . . . . . . 10-2
SUBSTR Demonstrates A$(I,J) As a Substring . . . . . 3-3
TABOl Demonstrates Tab Printing of String
Ch?..r?~-cters . ., . . . . . . . ., . . . . . . . . 2-2
TAB02 Prints Numerics Using the Tab Function .. . 2-2
T(,l)UR Knight's Tour-Prints at Dead End . . . . . . . 12-4
UPDATE Edits Inventory File INV02 (HP) . . . . . . . . 4-2
VAR Calculates Variance and Standard Deviation 11-2
WEATHER Calculates Linear Correlation for
Temperature Data . . . . . . . . . . . . . . . . . . 11-4
170
Program Description Section
WEE KA Matches String and Substring . . . . . . . . . . 3-3A
WEEKAl Finds Day Number from String Day . . . . . . 3-3B
WEEKBl WEEKAl Checking Only First Three
Letters of Input String . . . . . . . . . . . . . . . 3·3B
WET HR Array Demonstra tion with Weather Data .. . 1-4
WETHRl Array Demonstra tion with Weather Data .. . 1-4
XFER Transfers Contents of City to Random
File CITY2 (GE) . . . . . . . . . . . . . . . . . . 4-3
ZER<l>Ol Search for Change of Sign in Polynomial
Function . . . . . . . . . . . . . . . . . . . . . . . . 8-2
ZER(,))02 Uses Interval Halving to Find an Approxi-
mate Zero . . . . . . . . . . . . . . . . . . . . . . . 8·2
BIBLIOGRAPHY
Albrecht, Robert L., LeRoy Finkel and Jerold R. Brown, BASIC, Wiley,
1973. Programmed instruction is used to introduce BASIC.
Coan, James S., Basic BASIC, Hayden, 1970. An introductio n to BASIC
in a mathematics setting.
Gateley, Wilson Y., and Gary G. Bitter, BASIC for Beginners, McGraw-Hill
Book Company, 1970. Brief introductio n to the rudiments of BASIC.
Gruenberger, Fred, and George Jaffray, Problems for Computer Solution,
Wiley, 1965. A book of problems from a wide variety of topics.
Kemeny, John G., and Thomas E. Kurtz, BASIC Programming, 2nd Ed.,
Wiley, 1971. BASIC programming presented by the originators of the
language.
Knuth, Donald E., The Art of Computer Programming, Vol. 3, Sorting and
Searching, Addison-Wesley, 1973. A comprehensive treatment on
arranging data in order and locating items in an ordered data structure.
Ledgard, Henry F., Programming Proverbs, Hayden, 1975. Writing pro-
grams that work the first time.
Nolan, Richard L., Introduction to Computing Through the BASIC
Language, Holt, Rinehart and Winston, 1969. Introduction to com-
puters and computing as well as BASIC.
Pavlovich, Joseph P. and Thomas E. Tahan, Computer Programming in
BASIC, Holden-Day, 1971. An introduction to BASIC assuming a
traditional background in high-school mathematics.
Pegels, C. Carl, BASIC A computer Programming Language, Holden-Day,
1973. With business and management applications.
Sage, Edwin R., Problem Solving with the Computer, Entlek, 1969. An
introductio n to BASIC using mathematics problems.
Smith, Robert E., Discovering BASIC, Hayden, 1970. Introduces BASIC
using a wide variety of interesting problems.
Spencer, Donald D., A Guide to BASIC Programming; A Time-Sharing
Language, Addison-Wesley, 1970. Introduces the language, solves
problems from general interest topics, and presents problems for
reader solution.
Spencer, Donald D., Game Playing with Computers, Rev. 2nd Ed., Hayden,
1975. Mostly Fortran with some BASIC. Detailed anaylsis of a wide
variety of games.
171
..__,
Each two-page spread should be read from top to bottom as an individual page.
LET C = 0
F"IRST I
50
28
JS 5
I
-
174 REM 160 IF B/ I :: ltlTCB/I l THEN 200 S20 IF' INTC CPCZ)-1)/9 ) <> 0 THEN 490
~ DATA -5, o, 3, -2• 2.4, -.OOI 170 NEXT I 530 LET P :: -z
S40 RETURN
IN
NOo I
END
"'
180
190
PRINT 1 592
S94 REM • ENTER NEl.I MOVE ANO CHECK F'OR WIN
192 600 LET C "' 0
ABSC-S 200 PRINT ) 610 F'OR I "' I TO 3
ABS< 0 210 GOTO 110 620 F'OR J : I TO 3
ABS< 3 3 212 630 LET C " C + I
__,
~
ABSC-2 2 214 REM 6'10 IF' C < PCZ> THEN 710
(,J ABSC 2.4 ) :: 2.4 220 DATA 50• JS, 650 IF' Act.Jl " PCZ> THEN 690
R•JN
.._, .)<:,tion 1-·l lum!'dl Chaptcr3
N:l.11
-"" .'ii mber J icont'ch '.-<-'ltlOll l-~ AS? 10
CS?6
660 PRINT "SPACE TAKEN'' 6 IO
670 GOSUB 500 i'.wnbcr 1
680 GOTO 600 AS?6
94 REM • "/IGHEST A'<D L0';1£5T STRl'lGS 1~; OATA
662 CS? 10
100 RE:AD OS
68•1 REM • ENTER NEW MOVE
LET Act~J) = l IO LET HS=DS ' to
6~0 P
GOTO 730 120 LET LS:>OS
7CO AS?AIOO
122 REM
710 NEXT J CS?A60
720 NEXT ~ 1:10 PRINT OS
ASO AJO'.J
140 READ OS
122
12·1 REM • F'OR WIN 150 IF' OSe"LAST" THE'l 220
AS?ASO
160 If." LS <= OS T>iEN 190
7~0
7.·,Q
FOR l ::::
LET '
'0 170 LET LS=OS CS?AlOO
ASO AIOO
NEXT 1 ISO GOTO 130
·~2
162 REM
190 IF' HS>" OS THE:-J 130 AS? STOP
F"OR I = 1 TO 3
7l2 200 LET HS,,OS
1(4 REM * CHECK DIAGONALS 210 GOTO 130
770 IF AO.I> <> P THEN 212 RE.,
Chapter]
7CO LET IHll = W<ll + 1 220 PiHNT
7'.'0 ff A(J,4-ll <> P THEr, 810 230 PRINT " LOWEST : "ILS
Section J-5
600 LET W(2) = WC2) + I 240 PRINT ''HIG'-IEST = "P·IS
8112 242 RE"I
Nurnber
60.t REM * CHECK ROWS AND COLUM!JS 250
250
DATA "O'l£", "TWO"• "THREE"• "FO'JR", "FIVE"• "LAST"
ENO
810 LET WC3> = IH4> = 0 100 DIM A<75J
8'.~0 FOR J = 1 TO 3 R•JN
110 INPUT AS
8'.10 If" A(l,J) <> P THJ:N 850 NO.J
120 CHANGE AS fO A
8·10 LET WC3l = \HJ) + I 130 LET L = At1})
8~10 IF ACJ, I> <> P THCN 870 ONS
132
St10 LET WC4) = W(4) + I 140 FOR t = i iO L-1
870 NEXT J 150 FORJ=l+!TJL
872 160 11" ACJJ <; A<J> THEN 200
SHO FOR K TO 4 = i 170 LET { = A<J l
6'10 IF WCKJ < J THEN )30 urn LET HI) = A<J>
9·l0 PRINT "YOU WIN l"J LO\..IEST = FIVE 190 LET HJ> : X
910 GOSUB 400 HIGHEST = TWO 200 NEXT J
9:!0 STOP 2>0
9JO NEXT K
212
9-lO NEXT I t>.umberS 220 LET X = 1
9-12 230 IF ACX)<> AC1<•1> THEN 290
9)0 RETURN 100 PRINT 232
9-;_2 110 HEAO As.as.cs.os 23' REM* I~ ACX>= ACX+ll THEN MOVE EACH
9;,4 REM 120 IF" AS="STOP" HiEl-1 250 REM 1EM UP HE POSITION
235
9~0 DATA 1,2,3,4,5,6,;,5,9 !JO tF BS<OS THE~ 190 FOR (::: X .. I TO --1
2<0
970 END 140 tF BS>OS T'-IE~ 160 LETACil=A<IHl
250
R'JN ISO IF AS<CS TKEN 190 260 NEXT !
NJ.3 152 REM 270 LET i.. ::: L- !
160 PRINT OSI"• "1C.S 280 GOTO 230
T-tE BOARD 170 PRINT SSI"• "IAS
I 2 282
160 GOTO 100 290 LET X = X.. !
5 182 REH 300 IF X < '.-1 T-t::·~ 230
8 190 PRINT BSI"• "IAS
I ?3 310 LET ACOl = L
200 PRINT OSI"• "JCS 312
• 2 ?2 210 GOTO 100
-2 -I 320 CHANGE A T J AS
212 REM 330 PRINT AS
5 6
'7 220 DATA "\.llLLIA"l","SMITH","GEORGE"•"SMITH " 340 ENO
'I
8
?5 ' 230
240
DATA "ALtCE''."JONES''.''ROBERTA",".J:JNES "
OATA "STOP"•'"'•""•'"'
RUN
NO• I
• 2 71 250 ENO
-2 -2 -I
R'JN .. THE OUlCK BROm F'OX JUMPED OVER THE LAZY DOGS
-I 6 NO,S ABCOEFGHl JKLM1l lPORSTUVWXYZ
8
'
'I
YOU WIN I
-2
" _, I S'ilTHo GEORGE
Number:!
SMITH, WILLIAM
-I 6
100 OJM NS{IOO>. NC:JO)
8
' J:l'IES, ALICE
JONES• ROBERTA 110 REAON
,'.11rnber6 120 MAT READ llS<N>
130 F'OR 1 ::: l TO N
94 REM *
COMPAR WITH COMPUTED GOSUB
140 PRINT ~S<l>J TA8(20lJ
JOO READ A18
Ch.ip1er3 ISO CHANGE 'IS< I) T>J N
110 IF" A= ,QI THEN 320
152
120 GOSUB SGNCA-81+2 OF 240,2201200
!JO GOTO 100 Scc!mnJ--1 15' REM *SEARCH F>JR FIRST SPACE
160 FOR J"' N<O> HJ I STEP -I
200 PRINT Al "IS GREATER THAN"! B
:-.:umbcrU 170 !=- NC.J> = 32 THEN 190
2 !O RETURN
Al "IS EQUAL TO": 6 180 NEXT J
220 PRINT
"4 REM • WJLTlPLIES TWO l"HEGEHS 'J? TO 20 OIGlTS EACH 190 LET NSCIJ = EXTS<NSC1>.J+1,NC0l) • "• " • EXTS<NS0>.11J)
2JO RETURN ~SCil
AJ "IS LESS THAN"J S 100 otM Asr201.ssr201.osc 101.At201.sr201.cr;io1 200 PRINT
2·~0 PRINT
250 RETURN 110 LET 05="01234567'39" 210
292 120 READ As.as 212
294 REM 130 IF AS="STDP" TYEN 530 220 FOR I = I TO N-1
300 DATA 3,4, l•7• I• I• :,31,31, -3,2, o.o 140 PRINT AS1"•"16S1" = "J 230 F'OR J = l + l TO N
310 DATA .01.0 142 REM 240 IF' NSCil <" NSCJ) TfiEN 280
320 END 144 REM *
CO:-.!VEiH AS TO Lt ST A 250 LET AS = NS CI}
RUN 150 LET A=LEN<ASl 260 LET NSCll = NSCJ>
NO.& 160 MAT A=ZERtAl 270 LET NSCJl : AS
170 FOR '=I TO A 280 NEXT J
l S LESS THAN 4 180 FOR J= I TO 10 290 NEXT I
i.7 IS GREATER THAN l•I 190 IF AS(I,Il=DS{J,J) THE'll 210 292
3t IS EQUAL TO 31 200 NEXT J 300 PRINT
-3 IS LESS THAN 2 210 LET ACA+l-ll=J-t 310 PRINT "OROEREDt"
0 IS EQUAL TO 0 220 NEXT I 320 PRINT
222 REM 330 F'OR I = I TO N
224 REM • CONVERT BS TO LI ST B 340 PRINT NS CI)
Chi1plcr1 230 LET B=LE'H8Sl 3SO NEXT I
240 MAT 8=ZERt91 352
~l'l[J()[J !-5 360 DATA 3
250 FOR I:I TO B
260 F'OR J= I TO 10 370 DATA GEORGE WASHINGTON.- JOHNNY APPLESEED• JOHN O. AOAMS
Number.!
270 1F' BS[J,JJ:OStJ,JJ HIEN 290 380 ENO
94 REM • FIND LARGEST RA!'JDOM INTEGER IN ROWS AND COLUMNS 280 NEXT J RUN
100 DIM A<S.5) 290 LET aCB+l-ll=J-t NOo2
102 JOO NEXT .1
104 REM *
F'ILL ARRAY WITH RA.'llDOM INTEGERS 302 REM GEORGE WASHINGTON WASHINGTON. GEORGE
110 F'OR I "' I TO 5 304 RE~ *M'.JLTIPLY DIGIT BY DIGIT JOHNNY APPLESEED APPLESEED, JOHNNY
120 F'OR J "' I TO S 310 LET N=A+B JOHN Q, ADAMS ADAMS• JOHN Oo
130 LET ACl.J> = INT< RN0<-1U51-2S) 320 MAT C;ZERtNl
140 NEXT J 330 F'OR ): I TO A ORDERED:
ISO NEXT l 340 FOR J=I TO 8
152 350 LET So: 1 +J-1 ADAMS.- JOHN O.
160 MAT PRINT AJ 360 LET CESl=CtSl+ACll•BCJl APPLESEED• JOHNNY
162 370 IF CCS1<10 TfiEN 410 WASHINGTON> GEORGE
164 REM *
F'INO LARGEST INTEGER JN EACH ROW 380 LET C(Sl=CtSl-10
170 F'OR R I TO 5 390 L.ET C( S+l l,,.CtS+l l+ I
180 LET Cl "' I <lOO GOTO 370 Number 5
190 LET L = ACR.o I) 410 NEXT J
200 F'OR C = 2 TD 5 NEXT I 100 DIM O<IO>. AC!S>.. 8Cl5>. PC30>. OC30l
210 IF' A<R.C> <= L THEN 240 REM 110 LET OS = "0123456789"
220 LETCl=C REM • PRINT RESULTS 120 CHANGE OS TO 0
230 LET L = ACR~Cl <13{} IF C[NJ <> 0 Tl-li':N 4SO 130 Rf:AO AS.- SS
240 NEXT C 440 LET N;N-1 140 PRINT A.SJ . . . "J es
250 PRINT "ROW": RJ "LARGEST IS"J Lj "IN COLUMN"! Cl FOR l:"I TO I STEP - I ISO CHANGE AS TO A
260 NEXT R PRINT OSCCEIJ+l,Ctll+lll 152
270 PRINT NEXT J 160 FOR I = I TO ACOl
212 480 PRINT 110 FOR J = I TO 10
--
* F'INO LARGEST INTEGER lN EACH COLUMN <190 PRINT !BO IF AC!l <> DCJ) THEN 210
~·
REM
•o
no
F'OR C "' I TO S
LET RI :: I
500
502
GOTO 120
R.EM
190
200
LET AC!) = J~l
GOTO 220
LET L"' ACl.-Cl 5 I0 DATA "I 000"•" I 000" • "9999999", "9999999" 210 NEXT J
3 10 F'OR R : 2 TO 5 520 DATA "STOP",'"' 220 NEXT I
=
~ PRINT
9999999•9999999 = 99999980000001 270 LET sen : J-1
-
= NEXT C
280 GOTO 300
290 NEXT J
~- 300 NEXT l
N 0.-2 Xumber 11 302
310 MAT P :: ZERCACOl+BCO))
-IS -19 -14 94 REM *
ORDERS N'.J'1ERIC CYARACTE:RS I"l STRING VARIABLES 320 F'OR 1 : BCOl TO 1 STEP -I
100 DI"! AS£25J.CSt25l 330 F'OR J : ACOl TO I STEP -I
23 17 ! JO PHHlT 340 LET K = l+J
120 PRINT "AS"I 350 LET PCK> : POO + ACJHaC!)
-10 130 INPUT AS 360 IF' PCK> < 10 THEN 390
140 IF AS="STOP" THEN 290 310 LET PCK-1} :: PCK-1> + INTcPCK)/10)
13 -9 23 15 -10 150 PRINT "CS"! 360 LET PCK) = PCK) - lNTCf\CK)/10>*10
_, 25
160
170
IN?tJT CS
IF LEN<AS);LEN<CS> HIEN 260
390
400
NEXT J
NEXT I
3
' 23
180
190
F'OR G:J TO L~N<A$)
IF' AS(G,Gl o CSCG.Gl THEN 210
002
ROW i LARGEST IS 3 IN COLUMN 4 010 LET PCO> " ACO> + BCO>
ROW 2 LARGEST IS 23 IN COLUMN 4 200 NEXT G •20 IF' PC!) <> 0 THEN 470
ROW 3 LARGEST l S 20 IN COLUMN 2 210 IF' AStG•Gl>"d" T!-IE"I 260 430 FOR I :: I TO P<Ol -I
ROW o LARGEST IS 23 IN COLUMN 3 220 IF' csrG.Gl>"!J" TH€'."I 260 440 LET PCI > = PCl +I}
ROIJ 5 LARGEST IS 25 IN COLUMN 4 230 IF LE/\ICASl<Lf::.•HCSl Tf.IE'J 270 ..ol50 NEXT I
240 PRINT CSJ" "JAS '52
COLUMN I LARGEST IS 13 IN ROW 4 250 GOTO 110 460 LET PCOl :: PCOl - 1
COLUMN 2 LARGEST l S 20 IN ROW 3 260 IF' AS>CS THEN 240 470 MAT 0 ZERCPCO))
03LUMN 3 LARGEST IS 23 IN ROW 4 270 PRINT A.SJ" "JCS 480 F'DR I = I TO PCO>
COLUMN 4 LARGEST IS 2S IN ROW 5 280 GOTO 110 490 LET OCI>: OCPCJ>+ll
"
CJ1 COLUMN 5 LARGEST 1S 23 IN ROW 5 290 ENO 500 NEXT l
S"cl!m1 J-5 lc:ont'dl 12 REM Y-AXIS.
-..j 96 READ s1.s2 N0.6
(J) 100 DEF' F'NF'CXl = C!/S2>•SINCX>
~.t1mher 5( cont'd)
115 l.ET K "' IVS2 II OF' INCREMENT:;??.
5J2 117 LET N = NIS2 AREA ISi 6500•17
510 LET OCO> " PCO> IJO F'OR X = F TO L STEP SI
520 CHANGE 0 TO OS 160 FOR YI = -K•52 Ta CN-K>•S2 STEP 52
530 PRINT "THE PRODUCT IS "1 410 IF' ABSCY-Yll < .5•52 THEN 470 Chaplcr7
5J2 600 DATA .S;.2
540 DATA "9999999"• "9999999" 610 DATA a, 3, -4, 12 Sechon 7-2
550 ENO 620 END
Numbcr4
"'"
NJ.S
100 PRINT "TO FIND .. HE DISTANCE BETWEEN nio POINTS"
9"99999 • 9999999 '50
T-lE PRODUCT IS 99999980000001 ••o
170
RUN 100
1'.\imberU
NO. I 190
JOO DIM AC IQ), BC )0) 200 LET DI ' <X2-:(1)•2 + CY2-Yllt2
." .
X=-4 210
110 PRINT
120 PRINT "AS"I '' 220
230
130 INPUT AS
\•lO IF AS = "STOP" THEN 32( 232
l•\2
240 F'OR X = If!T<OJ.':!l TO 2 STEP - t
250 IF' .iORCXl "> INTCSORCX)) THEN 270
.--·,
150 PRINT "BS"I I 260 IF lll/X -" INTCDllX> THEN JOO
! 60 INPUT BS I
CHANGE AS TO A 270 NEXT X
HANGE BS TO 8 ' 272
1'10 IF A(Q) = BCOl THEN 27C 280 PRINT "SOilC"'I
200 FOR G = I TO A<O> 290 GOTO 330
JOO PRINT SOF:'.X)J "~50RC"J 01/Xl "l"
210 IF A<G) = S(G) THEN 260
310 GCTO 330
<·12
:!14 REM• ASCCO) = 64 CSEE ASCll 320 PRltlT D
220
~JO
240
IF A<G> > 64 THEN 210
IF' BCG> ,. 64 THEN 210
ff A(Q} < BCD) THEN JOO . '" '
330
RUN
N0.4
END
2•12
260
270
GOTO 280
NEXT G
IF' AS < as THP:N JOO
.. 1
1
I
TO FIND THE 01 ;TANC;: 3ETWEEN TWO POHITS
POHIT A? 15,0
POINT B? o, 15
280 PRINT BSJ "
GOTO 110
"; AS " I DISTANCE AB : lS •S:l'H 2 >
PRINT ASJ " 1
GOTO I 10 t-<umbcrB
I
~ :rn ENO I
1 UN
'. 100
I 10
DIM X(20) • YC20l
LET N = 0
120 READ A1 !l
rs? 100 130 IF A : -.001 THEN 180
[ $? 60 140 LET N = N•I
to 100 150 LET XCNl ' A
rs? A60 160 LET Y<N> ' 8
FS? AJOO 12 170 GOTO 120
(>(,Q AlOO 172
!BO FOR P = l
rs? STOP 190 FOR Pl = P+l TO N
200 PRl'IT "C"1 XCP>J .. , .. , YC?)J "b C"l
210 ?R!TlT XC?llJ "•"J YC?l)J "l"
Chapter-I 220 !F XCP\ <> XC?l > THEN 280
230 !F YC?) <> YC?I l THEN 260
'c•(l!on·l-2 2.iO ?RfllT "PJl'lTS COINCIDE"
:.umber·l 250 GOTIJ 340
260 ?Rl!IT "EJJ.;TJotJ IS X :"J XCP>
!00 "1LES TRY Chilptcr.'i 270 GOT<l 340
110 IF' ENO II THE•~ 200 280 LET M = Cl'C?l>-YC?))ICXC?Jl-XCPll
1?.0 LET 1=0 ~ectam5-J 290 LET 8 = y( ?l - M•XCPl
130 LET l=l+l 300 [F M C> 0 THEN 330
1•10 READ 11, l Number6 310 ?Rt IT "EQJAT!ON IS Y ="1 8
150 IF' TYPC-ll <> 3 THEN 130 320 GOTJ 340
160 PRUIT "F'lRST EMPTY RECORD IS"J I 10 REM • THESE CHANGES IN GRAPHJ PROVlOE F'OR SCALE 330 PR! 1T "ECJATION IS Y ='"; MJ "*X+C"; Bl "l"
170 LET I=I+l 11 REM FACTORS OF" SI ON THE X-AXIS ANO S2 ON THE 340 PRI!IT
1'>0 R!::AO 11, 1 12 REM Y-AXIS· 350 NEXT Pl
190 GOTO liO 110 LET D ::: 47 360 NEXT P
:'.OO PRINT "F'ILE SIZE !S''1t-11"RECOROS" 130 LET T " 5 362
C!O END 195 READ 511 S2 495 REM
215 LET XI = X•SI 500 OATA 3,.1, 5,5, -1.6
CPEN-TRY.11
J«JN 217 LET YI = Y•S2 510 DATA -J, 3, 6,3. 516
220 IF ABSC Xlt2+CYl+llt2 - 169 1 :. T THEN 300 520 OATA -.o)l,O
550 IF ABSHX-LIHSl/10-INTCCX-Ll>•Sl/10)) < .OS THEN 590 530 ENO
F JRST EMPTY RECORD IS I 580 IF" A8SCCY-Ll>•S2/I0-1NTCCY-Lih'S2/10)) < .OS THEN 560 RUN
FILE SIZE IS 11 RECOROS 630 DATA .6, I NO.B
RUN ! 3 • <l >. ~ s • 6 )
Ch;ipter4
N0•6 ECUATION IS Y : I •X+r I )
Sectmn·l-J I 3 1 4 ),(-! • 6)
EQUATION IS y =-o.s •X+C s.s l
NumbL•rJ
r 3 , 4 hC-j , 3 i
100 F"ILES F'ILEIJ F'ILE2
l!O PRINT "F'IRST F'ILE1"
EQUATION l S Y : o. 25 .:<;:+r 3• 25
120 READ IJ, A
r 3 , <l >. ~ 6 • 3 )
130 PRINT A
IF' MORE 11 THEN 120 EQUATION IS Y "-0.2 •X•C
140
150 PRINT
! 3 • 4 ), ( 5 • 6
160 PRlNT "SECOND F'lLEt"
170
160
190
200
READ 12• A
PRINT A
IF' MORE 12 THEN 170
PRINT
.......
'
EQUATION IS Y
t 5 • b ,, (-j •
EQUATION IS Y :
= I
6
6
•XH
l
I )
210 RESTORE II
..
( 5. 6 ),l-1. 3}
220 RESTORE 12
230
240
250
260
PRINT "MERGED LISTS:"
READ 11, A
READ 12; B
IF' A <: 8 THEN 340
.. EQUATION IS Y = o.S •X-+t
' 5 • b 8 • 3 l
), (
EQUATION IS Y =-I •X+t 1!
3.5 l
270 PRINT a
r 5 , 6 ), l 5 • 6
2BO IF' HORE 12 THEN 250
POINTS COINCIDE
290 PRINT A
300
310 STOP
IF' HORE I I THEN 320 ,_,. 6 ),l-1. :l,
320 READ 11, A
EQUATION rs x =-I
330 GOTO 290
I- I • b ), ~ 8 1 3 )
340 PRINT A )
...
EQUATION IS Y =-0.:)33333 •X+t 5.66667
350 IF' HORE II THEN 410
360 PRINT B
..
1-1. b l . l 5 . b )
370 IF' MORE 12 THEN 390
360
390
-400
410
-420
STOP
READ 12, 8
GOTO 360
READ 11, A
GOTO 260
. EQUATION IS Y = 6
t-1 •
EQUATION l S Y
3 ;,t B,
=
3)
3
r 6 , 3 >. 1 5 , o ;
EQUATION IS Y =-I •X+i 11
F'lRST F'ILE:
Cli.1ptcri
~ecl!on 7-J
0:wnber2
SECOND F'ILE1
lo! 100 PRINT
2.2 110 READ Xl1Yl1 X2.oY2
120 IF XI = .OQI THEN 530
4.4 130 PRINT "PERPENDICULAR BISECTOR CF'"
5.5 Ch;iplcr6 140 PRINT ''LINE SEGMENT - GIVEN HID EtlO POHHS"
!SO PRINT "t"J XIJ ","! YIJ "} ANO (''J X2J "•"I Y21
MERGED LtSTSt NumhL•rb 160 PRINT "EQUATION IS "J
! 17Q LET XO : CX1+X2>12
1.1 94 REM • SIMPSON'S RULE 180 LET YO = <Yl-+Y2ll2
2 100 DEF' F'NSCX) : 2•XT3 - 2•Xt2 + X + S 190 IF' Xl-X2 <> 0 THEN 250
2.2 110 READ F';T 200 IF" Yl-Y2 <> 0 THEN 23Q
3 120 PRINT " I OF' INCREMENTS"J 202
3.3 130 INPUT l 204 REM *
THE TWO GIVEN POINTS COINCIDE
140 LET W = CT-F')/J 210 PRINT "NOT UN I OUE"
4.4 150 LET Al = F'NSCF') 220 GOTO 100
5 160 F'OR C = i TO l-1 222
5.5 170 LET X = F + C•W 224 REM • HORIZONTAL LINE
6 180 IF' C/2 = INT<C/2) THEN 210 230 PRINT "Y =" J YO
7 190 LET Al : Al • 4•FNS(Xl 240 GOTO 100
200 GOTO 220 250 1F' Y!-Y2 <> 0 THEN 280
210 LET Al = Al • 2•FtJSCXl 252
220 NEXT C 254 REM • VERTICAL LINE
Ch.ipler5 222 260 PRINT "X =": XO
230 LET Al = Al • F'NS<Tl 270 GOTO 100
Sechon 5-2 2-40 LET A : Al•CW/3) 2BO LET M = CY2-YlllCX2-Xll
250 PRINT "AREA I St"! A 290 LET MO= -JIM
Numherl 252 300 LET 8 = YO - MO•XO
254 REM 310 PRINT "y ="I MDI "•X+C"l BJ ")"
-......j 10 REH • THESE CHANGES IN GRAPH2 PROVIDE FOR SCALE 260 DATA -3, I I 320 GOTO 100
-.....J I J REM FACTORS OF' SI ON THE X-AXIS ANO S2 ON THE 270 ENO 322
Chaptcr7 Chapter{)
~'-'' 1ion 7-J (cont'd!
"
())
Nuinber 2 fcon!'dl
:iec!1on ;:-.:;
Number·\
Sect1onil-I
;-..'umb1.>r2
4'/•\ REM
500 DATA 1.2, 4,7, <1,7, 4,3 '22 100 DIM PC20), FCIO:, SCIOl
510 DATA -3,9, 4,5, 11,-7, 11,-1 REM • THE FOLLOWING NEW LINES IN PROGRAM 110 l'"OR W = I 10 10
520 DATA .001.0.0.0 425 REM PYTHJ WILL PRODUCE THE DESI RED RESULTS 120 LET F'CWl " SCl.O ~ P('.l) " PHl+IOl
SJO END 430 FOR P = l TO 3 130 NEXT :./
RWl 435 IF OCPlT2 > D<P+l)T2+0CP+2lt2 THEN 475 132
NC.2 NEXT P 134 REM *
READ A'JO f'f:JNT COEF"FIC!ENTS
"2 140 READ A
•MS LET 0 = OCJ) 150 ff A = C THEil •120
PERPENDICULAR BISECTOR OF 450 FOR P = 2 TO 3 160 F'OR X =A 10 1 !iTEP -l
LHIE SEGMENT - GlVEN TWO END POINTS 455 IF ASSCO-OCPl>,. .QOOOOI THEN 465 170 R!:AD F'O l
C ! • 2 ! ANO t 4 , 1 1 460 NEXT P 180 PRINT F'CX)J
ECUATION IS Y "'-0.6 •X+C 6 l '62 190 NEXT X
465 PRINT "EQUILATERAL ANO EQUIANGULAR" 200 PRINT
PERPENDICULAR BISECTOR OF 470 GOTO 110 210 READ B
LlrlE SEGMENT - GIVEN nm END PO!NTS 475 PRINT "OBTUSE TRIANGLE WITH LONG SIOE DETERMINED BY" 220 F'OR y " B 10 i '.;'."EP -I
< -~ , 7 • AND t 4 , J 1 460 GOTO 510 230 READ SC) l
E(UATHIN IS Y : 5 4BS PRINT "ACUTE TRI ANGLE" 240 PRINT 51 Y>J
490 GOTO 110 250 NEXT Y
PERPENDICULAR BISECTOR OF' 260 PRINT
"2
Ll!lE SEGMENT - GIVEN TWO ENO POlNTS REM 262
(- 3 • 9 ·, ANO ~ 4 , 5 1
EfUATION IS '( = 1.75 'l'X+( 6.12:5 l
'"
BOO
BIO
DATA
DATA
1.
1.
o,o.
1.2.
2:.o.
5,-1.
1. j,73205
6.15
264
270
REM *
F"IND A'JO i>JUNT PRODUCT
PRINT "PRONJCT '"';
,,o
PERPENDICULAR BISECTOR OF'
LHIE SEGMENT - GIVEN TWO END POJNTS
820
830
DATA
DATA ,,
1. o.o.
-2.6.
o.3,
1.2.
280
290
300
F'OR I " I ··o A
l'"OR J = I TO !l
LET !'Cl+J-ll" PCI+J-1> + F"CIHS(J)
6'0 DATA 0
( -1 ,-7 l ANO ;: 4 ,-7 l RUN 310 NEXT J
EfUATION IS NOT UNIQUE N(h4 320 NEXT I
33D F"OR Z : A+B-1 TO 1 STEP -1
340 PRINT F• Zl I
1':umber.t ( 0 • 0 '• { 2 • 0 1-73205 350 NEXT Z
EQUILATERAL ANO EQUIANGULAR 360 PRINT
PRINT 370 PRINT
GOSUB 5000 ,-1 l ANO t 6 , 15 380 GOTO 110
'1
LET 1<1 : I< OBTUSE LONG SIDE DETERHHlEO BY 382
IF' I< <> 3 THEN 150 ( t ANO ( 6 , 15 384 REM
POINTS:
LET H2 " M 390 DATA 5, J. 2,Q, !, l•
PRINT TAB< 15lJ "AND" • 3 I AND i 4 • 0 400 DATA 2, J, 2, 2, 2• 3
GOSUB 5000 HYPOTENUSE DETERMWED BY 410 DATA 0
ON I< GOTO 600· 700. aoo. 1:100 t ANO ( 4 , 0 l 420 ENO
RUN
ON i<l GOTO 1100• 1000• 1200, 1300 <-2 , 6 i,t 1 , 2 i ANO ( q • 8 N0.2
ON I< I GOTO 1000, 11 oo, 12:0•1• 1300
RIGHT TRIANGLE WITH HYPOTEtlUSE DETERMHlEO BY
ON I<\ GOTO 1200• 1200• 140•l• 1300 POINTS1fQ ,a >A.'JOC-2 .6 l 3 2 0 2 I
2 5 2
PRINT "PERPENDICULAR" PRODUCT = 5 3 12 " 2
GOTO 100 ~>:umlH'r 5
PRINT "PARALLEL" 3 2
GOTO 100 100 FOR A " 3 TO 98
2 3
PRINT "NEITHER" 110 F'OR B" A+! TO 99
PRODUCT " 6 13 6
GOTO 100 12:0 LET Kl : SORCA12 + Bt2l
IJO IF' Kl <> INT<l<ll THEN 160
PRINT "MEANINGLESS"
GOTO 100 1'0 IF I< I > 100 THEN 170
IF' M•M2 "' - I THEN I 000 150 PRINT A; BJ Kl
160 NEXT B Ch.1pkr9
IF' M = M2 THEN 1100
GOTO 1200 170 NEXT A
160 END Sectmn 'l-l
ilUN
5'J00 READ A. B, C ,-...:llmber I
5010 IF' A "' -.001 THEN 9999 N0.5
5J20 PRINT AJ "•X+C"l BJ "l•Y+C"1 CJ "l:Q "l
100 DIM F'(50)
5J30 IF' A= 0 THEN 5100 4 5
102
5J40 IF' B " 0 THEN 5200 12 13
104 REM • STOfE F"IE:i·rncc1 NUMBERS IN A LIST
5J50 LET H " -AIB B 10
110 LET F'C l l " F'!2) " !
5J60 LET K " J u e 120 l'"OR X = 3 ro II!
15
5J70
5J80
PRINT "SLOPE :••1 M
RE1URN 12
0
"
15 130
140
LET F'CO = F'C<:-1 > + F"CX-21
NEXT X
5100
5110
IF' B = O THEN 5300
LET I< = 2
'10
11
u
60
"
H
61
1'2
144 REM *
NO'« "'RlNT R::SUL TS
5120 PRINT "HORIZONTAL" "DIF'F'ERENCE"
12 16 u 150 PRINT "FC:OT2"• ";;"CX-ll•F'CX+ll''.
5130 RETURN 160 FOR x " 2: ro 17
5200 LET I< : I 12 B H
13 ~ e 110 LET A " F'CXh2
5210 PRINT "VERTICAL" 180 LET 8 " F'CX-\HF(X+ll
a so
5220
5300
RETURN
LET I< "' 4 "
15
15
u
~
e
H
190
200
PRINT /\, B, A-3
NEXT X
5310 PRINT "MEANINGLESS" 202
5320 RETURN
16 H M
210 ENO
5322
5995 REM
16
1B
1B
63
N
u
"aH RUN
"
-
H
n
•
H
H
2
H
"H
F'00•2
I
'9
25
F'O(-ll•F'CX .. 1>
2
3
10
" I
.
0 u 65 -I
"n"
N0.4 SI
w 169
,.,
166
0
65
0
53
"'
1156
3025
1155
3026
I
-I
ANO
H 7921 7920
2 •X•C 2 )*'(•C 4 ):0
PARALLEL
SLOPE=-!
m
m
"n" H
H
IM
20736
54289·
20737
54288.
-I
I
0 •XH l
>•Y•C 2 ):::0
ANO
HORIZONTAL
•
~
60
M
u
H
142129·
372100·
l42JJO •
372099.
-I
SLOPE = 2 H -
"
"
42
H "n
65
H
NunibN2
""
PERPENDICULAR
H H 110 LET F'CI > = F'C2l "' I
--
3 •X•C 4 >•Y•f 5 >=O SLOPE =-0.?S 42 H w 120 F'OR X = 3 TO 25
0 60 H IJO LET FCX> = F'CX-1)
ANO
8 •X•C 9 >*YH 2 ):0 SLOPE =-0.888889 H 13 140 NEXT X
u 142
NEITHER
'umber 10 RlJ:-.1
N0-4
Number 10
!00 LET A = 2J63
110 PRINT Al "GRAINS" H:J\.I MA'lY POINTS? 2500
!00 DIM A(3,)), 8C:!;J), CC:J.J), DC3,Jl• £{3,3)
120 ff A > 1000 THEN 150 1958 IN THE CIRCLE 3.1328
110 MAT READ A, 8
130 PRINT "YES THEY WILL FJT"
120 "lAT C = ,,•8
140 STOP
150 PRlNT "NO THEY WILL NEVER FIT IN THAT LITTLE SPACE" 130 MAT D : !'iVCCl
Chapter 10 140 PRINT
!60 END
150 PRINT "I:l<HA•E>"
·!UN
Section 10·1 160 MAT PRl~T D
'l[l.10
170 MAT C = !'IVCAl
Numbl'r 160 MAT D = !'IVCS>
9.22337£+18 GRAINS
190 MAT E = IHC
'Hl THEY WILL NEVER F'IT IN THAT LITTLE SPACE 100 DIM SCJ14l.P<4• ll.MC3. I l.TC J,4},AC 11 I l 200 PRINT
110 MAT READ 5, ? 210 PRINT "l'.hfCBl•l~NCAl"
i:tiapter<J 120 F'OR R = l TO .J 220 MAT PRINT E
130 F'ORC=IT04 222
'(.'Cl!on'J-l 140 LET TCl.tC) = TU.Cl + so~.Cl 224 REM
150 NEXT C 230 DATA 1,-2,3, s.-1,-2. 0,3,4
-..umber:! 160 NEXT R 240 DATA 2.-4.0. -J· 1.2. s.2.-s
162 250 ENO
100 PRINT "N''. "1+(2/JltN''. ''Cl+C2/Jl)tN" 170 MAT A : T•P RUN
110 FOR N = J TO 10 180 MAT PRINT A N0.10
!20 GOSUB 180 182
!JO NEXT N 164 REM
132 190 DATA JO, 6001 SO. 20, SO, 31•40t Io, o, 500, SO, 90 INV<A•Bl
140 F'OR N = 20 TO 70 STEP 10 200 OATA 1,. J9,, 49, J. 79
!SO GOSU8 180 210 ENO !050575 -1.2c11s -2.72989
!60 NEXT N RUN 0.747126 -o.6~9425 -1.38506
162 NOo I 1.11012 - I .~5.-.02
!70 STOP
172 1122.49 lNVCB>*lNVCA)
!80 PRINT N.o l+C2/3)TN, Cl+C2'J))TN
!90 RETUR.'I !.50575 -J.2C 115 -2.72989
?00 ENO Number4 00747127 -O.El9425 -I .J8506
~'JN 1.11012 -1 • .os.-.02 -3- 3046
'JJ.2 100 DIM A(J, !l, 8(4,Jl. CC41 ll. NSC4l
a,
., l+C2/JltN : 1+(2/J))TN
110
120
MAT READ A,
MAT C :: 6•A
NS
'
IO
20
1.02601
1.01734
1.0003
99.2291
165.382
27351.1
180
190
RUN
DATA
ENO
BULBS• SWITCHES• METERS OF' ~HRE• SCREWS 160
170
180
PRWT
PRINT "CONSTA"JT TERMS"
MAT PRINT K
JO 1.00001 •h52338E+06 190 MAT 1 "' HIVCC}
<O I 7o<l8085E+08 200 MAT S : !ti(
50 I J.23720E:+l I 8600 BULBS 210 PRINT
60 I 2004610£+ 13 4000 Sl.JITCHES 220 PRINT "SOLUTIONS"
J,J8388E .. 15 12100 METERS OF WIRE 230 MAT PRINT S
31600 SCREWS 240 PRINT
Numbers 250 GOTCl 110
252
100 DIM F'C20l 254 REM
110 LET F'CI) "'F'C2): I
Numberb
260 DATA 2, 3,1, S,-J
120 F'OR N "' 3 TO 20 270 DATA ;,21
100 DIM ACl.3»BC3,4»CC4,J>.DC!.4l>ECl,\l
130 LET F'CNl "' F'CN-)) 280 DATA 3, 2,J,-1. J,Q,1, 1,-2,-S
110 MAT READ A. B. C 290 DATA 20.- Q, 6
140 NEXT N
1'2 120 MAT 0 :: A•B
300 DATA 0
ISO PRINT "BY A001Tl0N"• "BY FORMULA" 130 MAT C : D•C 310 ENO
160 LET SO : SORCSl 140 MAT PRINT E
RUN
1'2
170 F'OR N = I TO 20 NQ, JI
LET SI "' CCl•SOhN-Cl-SO)tN)/((21N>•SOl 145 REM
ISO
PRINT F'CN), SI
!SD DATA I, I• I
190
16D DATA JD. aoo. so. 20. so. 31. 40. Io.
200 NEXT N
170 OATA 1,.39,.49,3.79 COEFFICIENT MATRIX
202
210 END 180 END
RUN
RUN
NO.S
~
INDEX
GQ.>T(/J, 3 LIST, 2 10
.,.TA 1\11'1.' 0
IF Ef~D, 48, 59 J. "4 .t"'.. J..~'.! !.:.1' .::. subscriiJLt!d stihig, 34
IF M(/JRE, 55 NEW, 2, 54 Variance, 138, 142
IF-THEN , 27 Q.>PEN, 47 Variation , 113
image, 25 RUN,3 Vector; column, 127
INPUT, 6, 31, 40 SAVE, 54 row, 127
LET, 5, 40
MAT, 18, 19 TAB(X) function, 23, 64 WRITE statemen t, 57
multiple assignmen t, 6 TAN(X) function, 11
PRINT, 2, 31, 40 Teletype files, 54 X-axis, 65, 68
PRINT USING, 25 TIM(X) function, 11 X-coordin ate, 78
RAND(/JM IZE, 9 Transfer; condition al, 2
READ, 2, 31, 40, 55 unconditi onal, 3
Trapezoid method, 77 Y-axis, 65, 68
REM,4 Y-coordin ate, 78
RESTQ.>RE, 57 Trial and error, 10
RETURN , 13 Triangles, similar, 85
SCRATC H, 57 TRN, 21 ZER, 19
SETW, 59 Truth values, 27 Zeros; integral, 112
STQ.>P, 5 TYP(N) function, 51 multiple, 111
WRITE, 57 nonreal, 104
STQ.>P statement , 5 Undefine d condition , 82 real, 104
ADVANCED BASIC:
Applications and Problems
James S. Coan
Now you can extend your expertise in the BASIC language with
this book of advanced techniques and applications of the BASIC
language. It allows you to gradually increase both your understand-
ing of concepts and your ability to write programs. The develop-
ment of each topic progresses from simple to more sophisticated
problems and is accompanied by many sample programs to clarify
the discussions.
ADVANCED BASIC opens with a review chapter on the elemen-
tary points of BASIC. Then, the book covers extended features,
strings and files, and the applications of the BASIC language in
such areas as: coordinate geometry, area, sequences and aeries,
polynomials, graphing, simulations and games. Summaries and
problem exercises end each section.
BASIC BASIC:
An Introduction to Computer Programming In
BASIC Language
James S. Coan
This popular text for high school and college students integrates pro-
gramming in BASIC language and the teaching of mathematics. Each topic
begins with a short. complete program and moves to more sophisticated
problems. The use of flowcharts is encouraged as an aid in writing programs.
Summaries and questions review important concepts. #5872-1. pa,,.r,
# 5873-X, cloth, 256 pages, 6 x 9, illus.
[{]
HAYDEN BOOK COMPANY, INC.
Rochelle Park, New Jersey
ISBN 0·8104-5855·1