0% found this document useful (0 votes)
17 views292 pages

32 Basic Programs For Trs-80 Level II

Uploaded by

Filipe Dias
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views292 pages

32 Basic Programs For Trs-80 Level II

Uploaded by

Filipe Dias
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 292

v ( rs

5) ie ae ee : H
ye‘S f‘

fil,co yo

APPLICATIONS PROGRAMS
Biorhythm Checkbook Decide
Loan Mileage
EDUCATIONAL PROGRAMS
Arithmetic Flashcard Metric
Numbers _Tachist Vocab | GAME PROGRAMS
Decode Groan
Obstacle Roadrace
GRAPHICS PROGRAMS Jot Wari
Kaleido Sparkle
Squares Walloons

MATHEMATICS PROGRAMS
Curve Diffeqn Graph
Integrate Simeqn Stats
MISCELLANEOUS PROGRAMS
Birthday Pi
Powers Pythag
PHILLE sALKVas

32 BASIC Programs for the


TRS-80 (Level Il) Computer
32 BASIC Programs for the
TRS-80 (Level Il) Computer

Tom Rugg and Phil Feldman

dilithium Press
Portland, Oregon
© Copyright, dilithium Press, 1980

10 9 8 7 6 5 4 3 2 1

All rights reserved. No part of this book may be reproduced


in any form or by any means without permission in writing
from the publisher, with the following two exceptions: any
material may be copied or transcribed for the non-profit use
of the purchaser; and material (not to exceed 300 words and
one figure) may be quoted in published reviews of this book.

ISBN: 0-918398-27-4
Library of Congress catalog card number: 79-56399

Printed in the United States of America.

dilithium Press
P.O. Box 92
Forest Grove, Oregon 97116

TRS-80 refers to the Radio Shack microcomputer and is a


registered trademark of Tandy Corporation, Fort Worth, Texas.
Acknowledgements

Our thanks to the following for their help and encouragement:


Our wives and families, John Craig, Merl and Patti Miller,
Asenatha McCauley, Herb Furth, Freddie, Wayne Green, and
Knute Johnson.
vi BASIC Programs for the TRS-80

AN IMPORTANT NOTE

The publisher and authors have made every effort to assure


that the computer programs and programming information in
this publication are accurate and complete. However, this
publication is prepared for general readership, and neither the
publisher nor the authors have any knowledge about or ability
to control any third party’s use of the programs and program-
ming information. There is no warranty or representation by
either the publisher or the authors that the programs or pro-
gramming information in this book will enable the reader or
user to achieve any particular result.
Preface

You have bought yourself a Radio Shack TRS-80 computer


with Level II BASIC (or maybe you just have access to one at
school or work). You will soon find that the most frequent
question you are asked goes something like this: ‘“‘Oh, you got a
computer, eh? Uh... what are you going to do with it?”’
Your answer, of course, depends on your own particular
situation. Maybe you got it for mathematical work, or for your
business, or for home usage, or to enable you to learn more
about computers. Maybe you got it for a teaching/learning tool
or for playing games.
Even if you got the computer specifically for only one of
these reasons, you should not neglect the others. The computer
is such a powerful tool that it can be used in many different
ways. If it is not being used for its “‘intended’’ function right
now, why not make use of it in some other way?
The TRS-80 is so small and portable that you can, say, take it
home from work over the weekend and let the kids play educa-
tional games. They will have fun and learn a lot. After they go
to bed, you can use it to help plan your personal finances. Or,
you can let your guests at a party try to outsmart the TRS-80
(or each other) at some fascinating games. The possibilities go
on and on. |
All these things can be done with the TRS-80, but the TRS-80
cannot do any of them without the key ingredient—a computer
program. People with little or no exposure to computers may be
in for a surprise when they learn this. A computer without a
program is like a car without a driver. It just sits there.
viii BASIC Programs for the TRS-80

So you ask, “‘Where can I get some programs to do the things


I want my computer to do?’’ Glad you asked. There are several
alternatives.

1. Hire a computer programmer. If you have a big budget, this is


the way to go. Good programmers are expensive and hard to
find (and you will not know for sure if they’re really good
until after the job is finished). Writing a couple of programs
that are moderately complex will probably cost you more
than you paid for the TRS-80 itself.

2. Learn to program yourself. This is a nice alternative, but it


takes time. There are lots of programming books available—
some are good, some not so good. You can take courses at
local colleges. If you can afford the time and you have a fair
amount of common sense and inner drive, this is a good
solution.
3. Buy the programs you want. This is cheaper than hiring your
own programmer because all the buyers share the cost of
writing the programs. You still will not find it very cheap,
especially if you want to accumulate several dozen programs.
Each program might cost anywhere from a few dollars to
several hundred dollars. The main problem is that you cannot
be sure how good the programs are, and, since they are gen-
eralized for all possible buyers, you may not be able to easily
modify them to do exactly what you want. Also, they have
to be written in a computer language that your computer
understands. Even if you find a program written in the BASIC
language, you will soon learn that the TRS-80’s BASIC is not
the same as other versions. Variations between versions of the
same language typically result in the program not working.
This book gives you the chance to take the third alternative
at the lowest possible cost. If you divide the cost of the book
by the number of programs in it (use your computer if you like),
you will find that the cost per program is amazingly low. Even
if there are only a few programs in the book that will be useful
to you, the cost is pretty hard to beat.
Just as important is the fact that these programs are written
specifically for your TRS-80. If you type them in exactly as
shown, they will work! No changes are needed. In addition, we
show you exactly what to change in order to make some simple
modifications that may suit your taste or needs. Plus, if you
Preface ix

have learned a little about BASIC, you can go even further and
follow the suggestions about more extensive changes that can be
made. This approach was used to try to make every program
useful to you, whether you are a total beginner or an old hand
with computers.
But enough of the sales pitch. Our main point is that we feel
a computer is an incredibly flexible machine, and it is a shame
to put it to only one or two limited uses and let it sit idle the
rest of the time. We are giving you a pretty wide range of things
to do with your TRS-80, and we are really only scratching the
surface.
So open your eyes and your mind. Play a mental game against
the computer (WARI, JOT). Evaluate your next financial deci-
sion (LOAN, DECIDE). Expand your vocabulary or improve
your reading speed (VOCAB, TACHIST). Solve mathematical
equations (DIFFEQN, SIMEQN).
But please, don’t leave your TRS-80 asleep in the corner too
much. Give it some exercise.
BASIC Programs for the TRS-80
How to Use This Book

Each chapter of this book presents a computer program that


runs on a 16K Radio Shack TRS-80 (Level II) computer. Most
will also run on a 4K TRS-80 with Level II (see Appendix 1).
Each chapter is made up of eight sections that serve the follow-
ing functions:
1. Purpose: Explains what the program does and why you might
want to use it.
2. How To Use It: Gives the details of what happens when you
run the program. Explains your options and the meanings of
any responses you might give. Provides details of any limita-
tions of the program or errors that might occur.
. Sample Run: Shows you what you will see on the screen when
you run the program.
. Program Listing: Provides a “‘listing’’ (or “‘print-out’’) of the
BASIC program. These are the instructions to the computer
that you must provide so it will know what to do. You must
type them in extremely carefully for correct results.
. Easy Changes: Shows you some very simple changes you can
make to the program to cause it to work differently, if you
wish. You do not have to understand how to program to
make these changes.
. Main Routines: Explains the general logic of the program, in
case you want to figure out how it works. Gives the BASIC
line numbers and a brief explanation of what each major
portion of the program accomplishes.
. Main Variables: Explains what each of the key variables in
the program is used for, in case you want to figure out how it
works.
xii BASIC Programs for the TRS-80

8. Suggested Projects: Provides a few ideas for major changes


you might want to make to the program. To try any of these,
you will need to understand BASIC and use the information
provided in the previous two sections (Main Routines and
Main Variables).

To use any of these programs on your TRS-80 computer, you


need only use the first four sections. The last four sections are
there to give you supplementary information if you want to
tinker with the program.

RECOMMENDED PROCEDURE

Here is our recommendation of how to try any of the programs


in this book:

1. Read through the documentation that came with the TRS-80


learn the fundamentals of communication with the computer.
This will teach you how to turn the computer on, enter a
program, correct mistakes, run a program, etc.
2. Pick a chapter and read Section 1 (“‘Purpose’’) to see if the
program sounds interesting or useful to you. If not, move on
to the next chapter until you find one that is. If you are a
beginner you might want to try one of the short ““Miscellaneous
Programs’”’ first.
3. Read Sections 2 and 3 of the chapter (‘““How To Use It” and
‘Sample Run’’) to learn the details of what the program does.
4. Enter the NEW command to eliminate any existing program
that might already be in your TRS-80’s memory. Using Sec-
tion 4 of the chapter (“Program Listing’’), carefully enter the
program into the TRS-80. Be particularly careful to get all
the punctuation characters right (i.e., commas, semicolons,
colons, quotation marks, etc.).
5. After the entire program is entered into the TRS-80’s memory,
use the LIST command to display what you have entered so
you can double check for typographical errors, omitted lines,
etc. Don’t mistake a semicolon for a colon, or an alphabetic
I or O for a numeric 1 or 0 (zero). Take a minute to note the
differences in these characters before you begin.
6. Before trying to RUN the program, use the CSAVE command
to save the program temporarily on cassette. This could pre-
vent a lot of wasted effort in case something goes wrong
(power failure, computer malfunction, etc.).
How To Use This Book xiii

7. Now RUN the program. Is the same thing happening that is


shown in the Sample Run? If so, accept our congratulations
and go on to step 9. If not, stay cool and go to step 8.
.If you got a SYNTAX ERROR in a line, LIST that line and
look at it closely. Something is not right. Maybe you inter-
changed a colon and asemicolon. Maybe you typed a numeric
1 or O instead of an alphabetic I or O. Maybe you misspelled
a word or omitted one. Keep looking until you find it, then
correct the error and go back to step 7.
If you got some other kind of error message, consult the
TRS-80 documentation for an explanation. Keep in mind that
the error might not be in the line that is pointed to by the
error message. It is not unusual for the mistake to be in a line
immediately preceding the error message line. Another possi-
bility is that one or more lines were omitted entirely. In any
event, fix the problem and go back to step 7.
If there are no error messages, but the program is not doing
the same thing as the Sample Run, there are two possibilities.
First, maybe the program isn’t supposed to do exactly the
same thing. Some of the programs are designed to do unpre-
dictable things to avoid repetition (primarily the game pro-
grams and graphic displays). They should be doing the same
types of things as the Sample Run, however.
The second possibility is that you made a typing error that
did not cause an error message to be displayed, but simply
changed the meaning of one or more lines in the program.
These are a little tricky to find, but you can usually narrow
it down to the general area of the problem by noting the
point at which the error takes place. Is the first thing dis-
played correct? If so, the error is probably after the PRINT
statement that caused the first thing to be displayed. Look
for the same types of things mentioned before. Make the
corrections and go back to step 7.
. Continue running the program, trying to duplicate the Sample
Run. If you find a variation that cannot be accounted for in
the “How To Use It” section of the chapter, go to step 8.
Otherwise, if it seems to be running properly, CSAVE the
program on cassette and check it with CLOAD.
10. Read Section 5 of the chapter (‘“‘Easy Changes’). Try any of
the changes that look interesting. If you think the changed
version is better. CSAVE it on cassette, too. You will probably
Xiv BASIC Programs for the TRS-80

want to give it a slightly different title in the first REM state-


ment to avoid future confusion.

A NOTE ON THE PROGRAM LISTINGS

A line on the screen of the TRS-80 is 64 characters wide. The


printer that was used to create the Program Listing section of
each chapter prints lines up to 80 characters long. For best
reproduction in this book, it is preferable that each published
line be no longer than 59 characters. This combination of facts
might cause you a little confusion when you are copying the
programs into your TRS-80. Here’s the way it works.
Wherever there is a line in a program that is longer than 59
characters, it has been divided into two lines that are each no
more than 59 characters. You can recognize this easily because
the second part has no line number at the left-hand side. This
division is only for the purpose of printing the book. You should
think of a divided line like this as one long line and enter it
into your TRS-80 as a single line. Where possible, this division
is made in such a way that the first part of the line ends with
a colon so you can notice it more easily.
Don’t be fooled by the fact that the cursor on your TRS-80
jumps down to the next line after you enter the 64th character
—it’s just one long line until you press ENTER.
Contents

How to Use This Book Xi

Section 1—APPLICATIONS PROGRAMS


Practical uses at home or work.
BIORHYTHM Can you predict your good
and bad days?
CHECKBOOK Balance your checkbook.
DECIDE Choose the best decision from
your list of alternatives. 21
LOAN Calculate payments and interest
for mortgages, car loans, etc. 33
MILEAGE Analyze your car’s gasoline
usage. 41
QUEST/EXAM Determine the results of
questionnaires and examinations. 49

Section 2—EDUCATIONAL PROGRAMS


To help yourself or others to learn.
ARITHMETIC Math drills for school-aged
children. : 61
FLASHCARD Create your own flashcards,
then practice. 69
METRIC Learn the metric system. 79
NUMBERS Help pre-school children to
learn numbers. 87
TACHIST Increase your reading speed
with this tachistoscope. 93
VOCAB Expand your vocabulary. 101
Xvi BASIC Programs for the TRS-80

Section 3—GAME PROGRAMS


Match wits with the computer or a friend.
DECODE Figure out the computer’s
secret code. 111
GROAN This dice game will make you
do just that. 119
JOT Challenge the computer to this
word and logic game. 127
OBSTACLE _ Play a friend at this
arcade-like game. 137
ROADRACE Try to keep the car on the road. 145
WARI Attempt to beat the computer
at this ancient African
skill game. 153

Section 4—GRAPHICS DISPLAY


PROGRAMS
Dazzling visual diversions.
KALEIDO A kaleidoscope with eight
point symmetry. 165
SPARKLE Hypnotic sparkling patterns. 169
SQUARES Overlaying concentric squares. 173
WALLOONS Aclassic from the
TRS-80 Theatre. 177

Section 5—MATHEMATICS PROGRAMS


For math, engineering, and statistical uses.
CURVE Perform least-squares
curve fitting. 185
DIFFEQN Solve ordinary differential
equations. 195
GRAPH Display a simple graph
of a function. 205
INTEGRATE Determine the area under
a curve. 213
SIMEQN Solve simultaneous
linear equations. 221
STATS Perform standard “‘statistics of
population” calculations. 227
Contents Xvil

Section 6—MISCELLANEOUS
PROGRAMS
Short programs that do interesting things.
BIRTHDAY ~~ What are the odds of identical
birthdays in a group of people? 243
P| Calculate an approximation
Of pi. 247
POWERS Calculate powers of integers—
up to 250 digits long. 253
PYTHAG Generate Pythagorean triplets
(a? + b? = C?). 259

Appendix 1—MEMORY USAGE 263

Bibliography 265
x Vili BASIC Programs for the TRS-80
section 1
Applications Programs

INTRODUCTION TO APPLICATIONS PROGRAMS

Good practical applications are certainly a prime use of per-


sonal computers. There are a myriad of ways the TRS-80 can
help us to do useful work. Here are six programs for use around
the home or business.
Financial considerations are always important. LOAN will
calculate interest, payment schedules etc. for mortgages, car
loans, or any such business loan. Do you ever have trouble
balancing your checkbook(s)? CHECKBOOK will enable you to
rectify your monthly statements and help you find the cause of
any errors.
Fuel usage is a constant concern for those of us who drive.
MILEAGE will determine and keep track of a motor vehicle’s
general operating efficiency.
The tedium of analyzing questionnaires and examinations can
be greatly relieved with the aid of your computer. In particular,
teachers and market researchers should find QUEST/EXAM
useful.
Often we are faced with difficult decisions. DECIDE trans-
forms the TRS-80 into a trusty advisor. Help will be at hand for
any decision involving the selection of one alternative from
several choices.
Before anything else, you might want to consult BBORHYTHM
each day. Some major airlines, and other industries, are placing
credence on biorhythm theory. If you agree, or ‘“‘just in case,”
simply turn on your TRS-80 and load this program.
BASIC Programs for the TRS-80

S2ty
BIORHYTHM

PURPOSE

Did you ever have one of those days when nothing seemed to
go right? All of us seem to have days when we are clumsy, feel
depressed, or just cannot seem to force ourselves to concentrate
as well as usual. Sometimes we know why this occurs. It may
result from the onset of a cold or because of an argument with a
relative. Sometimes, however, we find no such reason. Why
can’t we perform up to par on some of those days when nothing
is known to be wrong?
Biorhythm theory says that all of us have cycles, beginning
with the moment of birth, that influence our physical, emo-
tional, and intellectual states. We will not go into a lot of detail
about how biorhythm theory was developed (your local library
probably has some books about this if you want to find out
more), but we will summarize how it supposedly affects you.
The physical cycle is twenty-three days long. For the first
11% days, you are in the positive half of the cycle. This means
you should have a feeling of physical well-being, strength, and
endurance. During the second 11% days, you are in the negative
half of the cycle. This results in less endurance and a tendency
toward a general feeling of fatigue.
The emotional cycle lasts for twenty-eight days. During the
positive half (the first fourteen days), you should feel more
cheerful, optimistic, and cooperative. During the negative half,
you will tend to be more moody, pessimistic, and irritable.
The third cycle is the intellectual cycle, which lasts for
thirty-three days. The first half is a period in which you should
4 BASIC Programs for the TRS-80

have greater success in learning new material and pursuing


creative, intellectual activities. During the second half, you are
supposedly better off reviewing old material rather than at-
tempting to learn difficult new concepts.
The ups and downs of these cycles are relative to each indi-
vidual. For example, if you are a very self-controlled, unemo-
tional person to begin with, your emotional highs and lows may
not be very noticeable. Similarly, your physical and intellectual
fluctuations depend upon your physical condition and intellec-
tual capacity.
The day that any of these three cycles changes from the plus
side to the minus side (or vice versa) is called a “‘critical day.”
Biorhythm theory says that you are more accident-prone on
critical days in your physical or emotional cycles. Critical days
in the intellectual cycle aren’t considered as dangerous, but if
they coincide with a critical day in one of the other cycles, the
potential problem can increase. As you might expect, a triple
critical day is one on which you are recommended to be es-
pecially careful.
Please note that there is quite a bit of controversy about
biorhythms. Most scientists feel that there is not nearly enough
evidence to conclude that biorhythms can tell you anything
meaningful. Others believe that biorhythm cycles exist, but that
they are not as simple and inflexible as the 23, 28, and 33 day
cycles mentioned here.
Whether biorhythms are good, bad, true, false, or anything
else is not our concem here. We are just presenting the idea to
you as an interesting theory that you can investigate with the
help of your TRS-80 computer.

HOW TO USE IT

The program first asks for the birth date of the person whose
biorhythm cycles are to be charted. You provide the month and
day as you might expect. For the year, you only need to enter
the last two digits if it is between 1900 and 1999. Otherwise,
enter all four digits.
Next the program asks you for the start date for the biorhythm
chart. Enter it in the same way. Of course, this date cannot be
earlier than the birth date.
After a delay of about asecond, the program clears the screen
and begins plotting the biorhythm chart, one day at a time. The
BIORHYTHM 5

left side of the screen displays the date, while the right side dis-
plays the chart. The left half of the chart is the ‘“down”’ (negative)
side of each cycle. The right half is the “up’’ (positive) side. The
center line shows the critical days when you are at a zero point
(neither positive or negative).
Each of the three curves is plotted with an identifying letter—
P for physical, E for emotional, and I for intellectual. When the
curves cross, an asterisk is displayed instead of either of the two
(or three) letters.
Twelve days of the chart are displayed on one screen, and
then the program waits for you to press a key. If you press the
E key, the current chart ends and the program starts over again.
If you press the SPACE key (or any other key except BREAK or
SHIFT), the program clears the screen and displays the next
eighteen days of the chart.
The program will allow you to enter dates from the year
100 A.D. and on. We make no guarantees about any extreme
future dates, however, such as entering a year greater than
3000. We sincerely hope that these limitations do not prove to
be too confining for you.

SAMPLE RUN

Ot

secu ls

MONTH (1 TO 12)? 1
DAY (1 10 31)? 3%
sid: Cand
1947 ASSUMED.

I Ue aa ad

MONTH (i TO 12)? 4
DAY (1 10 31)?1
YEAR? 79
eel28

The operator enters his or her birth date and the date for the beginning of
the chart
6 BASIC Programs
for the TRS-80

dt
= TTL f " P
OOOO

Wi ld E I
vey iad I
Cia Mae 4 id I
rn? id |
nee P
I
Vero o£ id I
7s an 3 id i
bed E lg
479/79 13 Pp I
418/79 13 iy
aba) 3 I 4
ate ie E I P

SRAM PARP
LL

The program responds with the first 12 days of the operator's biorhythm
chart, then waits for a key to be pressed.

PROGRAM LISTING
189 REM: BIORHYTHM
119 REM: COPYRIGHT 1979 BY TOM RUGG AND PHIL FELDMAN
129 CLEAR 2@0:DEF INT K,L:QEFUBL B,J,M-Z
136 L=@:T=25sP=3.1415926535 CLS
149 PRINT TABC1S) 5"BIORHYTHM" sPRINT
15@ PRINT"ENTER BIRTH DATE"
148 GOSUB 599
178 GOSUR 499
188 JB=JD
19@ PRINTSPRINT"ENTER START DATE FOR CHART"
299 GOSUBR 599
218 GOSUB 699
229 JCsJD
238 IF JC2=JB THEN 279
248 PRINT"CHART DATE CAN°T BE EARLIER THAN"
259 PRINT’RIRTH DATE. TRY AGAIN."
268 GOTO 1598
278 FOR K=1 TO 168@:NEXT
289 GOSUB 789
398 N=JC-JB
BIORHYTHM 7

519 V=23:GOSUB 8@@:GOSUB 859


529 V=28:GOSUB 880:GOSUB 85d
339 V=33:GOSUB 894:GOSUB 859
549 GOSUB 1990
358 PRINT C$iTAR(8)IL$
549 JC=JC+1sLsl+1rIF L412 THEN 399
376 PRINT"PRESS “E’ TO END, SPACE TO CONTINUE":
389 R$=INKEY$:IF R$="" THEN 389
39D IF R$="E" THEN 120
AGB L=@:GOTO 289
JOO PRINT
8S INPUT"MONTH (1 TO 12)"3M
31d M=INT(M) SIF M<1 OR M212 THEN 585
J28 INPUT"DAY (1 TO 31)"s0
33d D=INTCIF D1 OR 0231 THEN 529
JAD INFUT" YEAR" 2Y
JIG Y:INT(Y) IF Y<@ THEN 549
349 IF Y:99 THEN 589
JG Y=Y+1990:PRINT Ys"ASSUMED."
389 RETURN
499 W=FIX((M-14)/12)
619 JD=INT (1461 (Y+48004U)/4)
628 B=F 1X( 367 (M-2-W#12)/12)
649 JD=J0+B
6359 B= INT (INT (3*(Y+4900+U)/108)/4)
649 JD=JD+0-32675-F
479 RETURN
799 CLS
719 PRINT TAB(29) s"BIORMYTHM"
729 PRINT'--DATE--"sTAB( 12) 3
739 PRINT'D O W N'STARC33)5"O"TAB(45) 2°U Pp”
74S PRINT TAB(Q)!
PIG FOR K=1 TO T+T+12PRINT CHR$(131) 2 :NEXT:PRINTSRETURN
899 W=INT (N/V) SR=N- (UY)
819 RETURN
B59 IF V<223 THEN 99
848 L#=CHR$(32) FOR K=1 TO Ssh $=L$4L$:NEXT
873 L$=L$+LEFT$(L%,19)
889 L$=LEFT$(L$,T)+CHRS (149) +RIGHTS(L$,T)
896 IF V=23 THEN C$="F"
98D IF V=28 THEN C$="E"
919 IF Y=33 THEN C$="I"
928 UER/Y sUsWe2eP
9398 W=T#SIN(W) SW=W4+T41.5
949 W=INT(W) SAS=MIDS(L$,W, 1)
P59 IF AS="P" OR AS="E" OR A$="*" THEN C$="#"
8 BASIC Programs for the TRS-80

955 IF W=1 THEN 98¢


957 IF W=T+T+1 THEN 999
969 L$=LEFT$(L$,U~1)+C$+RIGHTS (L$, T+T+1-W)
974 RETURN
989 L$=C$+RIGHTS(L$,T+T) sRETURN
999 L$=LEFTS(L$, T+T)4C$ RETURN
199% W=JC+68569 :R=INT (44U/144097)
1919 W=W-INT((146097#R+3)/4)
1020 Y=INT( 4090: (U+1)/1461981)
193@ W=W-INT(1461#Y/4) +31
1949 M=INT( 8941/2447)
195@ D=W-INT(24474M/89)
1960 W=INT(M/11) 2M=M+2-124U
1070 Y=190*(R-49)+Y+U
1989 A$=STR$(M) SW=LEN(A$)~1
1999 CS=MIDS(AS,2,W)+"7"
1199 A$=STR$(D) SW=LEN (AS) ~1
1119 C$=C$4MIDS(AS,2,U)+"7"
1128 AS=STR$(Y) SW=LEN(AS)~1
1139 C$=C$4MID$ (A$ ,W, 2)
1149 RETURN

EASY CHANGES

1. Want to see the number of days between any two dates?


Insert this line:
305 PRINT “DAYS =”; N: END
Then enter the earlier date as the birth date, and the later
date as the start date for the chart. This will cause the pro-
gram to display the difference in days and then end.
2.To alter the number of days of the chart shown on each
screen, alter the 12 in line 360.

MAIN ROUTINES

120-140 Initializes variables. Displays titles.


150-180 Asks for birth date and converts to Julian date
format (i.e., the number of days since January 1,
4713 B.C.
190-220 Asks for start date for chart and converts to Julian
date format.
230-260 Checks that chart date is not sooner than birth date.
BIORHYTHM 9

270 Delays about one second before displaying chart.


280 Displays heading at top of screen.
300 Determines number of days between birth date and
current chart date.
310-330 Plots points in L$ string for each of the three cycles.
340 Converts Julian date back into month-day-year
format.
350 Displays one line on the chart.
360- 400 Adds one to chart date. Checks to see if the screen is
full.
500- 580 Subroutine to ask operator for month, day, and year.
Edits replies.
600 - 670 Subroutine to convert month, day, and year into
Julian date format.
700 - 750 Subroutine to clear screen and display headings.
800- 810 Subroutine to calculate remainder R of N/V.
850- 990 Subroutine to plot a point in L$ based on V and R.
1000 -1140 Subroutine to convert Julian date JC back into
month-day-year format.

MAIN VARIABLES

L Counter of number of lines on screen.


T Number of characters on one side of the center of
the chart.
P Pi.
JB Birth date in Julian format.
JD Julian date calculated in subroutine.
JC Chart start date in Julian format.
K Loop and work variable.
N Number of days between birth and current chart date.
V Number of days in present biorhythm cycle (23, 28,
or 33).
C$ String with date in month/day/year format.
L$ String with one line of the biorhythm chart.
R$ Reply from operator after screen fills up.
M Month (1 - 12)
D Day (1 - 31)
Y Year (100 or greater)
10 BASIC Programs for the TRS-30

W, B Work variables.
R Remainder of N/V (number of days into cycle).
A$ Work variable.

SUGGESTED PROJECTS

Investigate the biorhythms of some famous historical or ath-


letic personalities. For example, are track and field athletes
usually in the positive side of the physical cycle on the days
that they set world records? Where was Lincoln in his emotional
and intellectual cycles when he wrote “The Gettysburg Address’’?
Do a significant percentage of accidents befall people on critical
days?
CHECKBOOK

PURPOSE

Many people consider the monthly ritual of balancing the


checkbook to be an irritating and error-prone activity. Some
people get confused and simply give up after the first try, while
others give up the first time they cannot reconcile the bank
statement with the checkbook. Fortunately, you have an advan-
tage—your computer. This program takes you through the
necessary steps to balance your checkbook, doing the arithmetic
for you, of course.

HOW TO USE IT

The program starts off by giving you instructions about how


to verify that the amount of each check and deposit are the
same On the statement as they are in your checkbook. Some-
times the bank will make an error in reading the amount that
you wrote on a check (especially if your handwriting is not too
clear), and sometimes you will copy the amount incorrectly
into your checkbook. While you are comparing these figures,
make a check mark in your checkbook next to each check and
deposit listed on the statement. A good system is to alternate
the marks you use each month (maybe an “*x’”’ one month and a
check mark the next) so you can easily see which checks and
deposits came through on which statement.
Next, the program asks for the ending balance shown on the
bank statement. You are then asked for the check number (not
the amount) of the most recent check shown on the statement.
12 BASIC Programs for the TRS-80

This will generally be the highest numbered check the bank has
processed, unless you like to write checks out of sequence.
Your account balance after this most recent check will be
reconciled with the statement balance, so that is what the pro-
gram asks for next—your checkbook balance after the most
recent check.
The program must compensate for any differences between
what your checkbook has in it prior to the most recent check
and what the statement has on it. First, if you have any deposits
that are not shown on the statement before the most recent
check, you must enter them. Generally, there are none, so you
just enter ““END.”’
Next you have to enter the amounts of any checks that have
not yet “‘cleared”’ the bank and that are prior to the most recent
check. Look in your checkbook for any checks that do not have
your check mark next to them. Remember that some of these
could be several months old.
Next you enter the amount of any service charges or debit
memos that are on the statement, but which have not been
shown in your checkbook prior to the most recent check.
Typically, this is just a monthly service charge, but there
might also be charges for printing new checks for you or some
other adjustment that takes money away from you. Credit
memos (which give money back to you) are not entered until
later. Be sure to make an entry in your checkbook for any of
these adjustments so that next month’s statement will balance.
Finally, you are asked for any recent deposits or credit
memos that were not entered in your checkbook prior to the
most recent check, but that are listed on the bank statement. It
is not unusual to have one or two of these, since deposits are
generally processed by banks sooner than checks.
Now comes the moment of truth. The program tells you
whether or not you are in balance and displays the totals. If so,
pack things up until next month’s statement arrives.
If not, you have to figure out what is wrong. You have seven
options of what to do next which allow you to review the num-
bers you entered in case of a typing error. If you find an error,
go back to the beginning and try again. Of course, if it is a simple
error that precisely accounts for the amount by which you are
out of balance, there is no need to go through the whole thing
again.
CHECKBOOK 13

If you entered everything correctly, the most likely cause of


the out of balance condition is an arithmetic error in your
checkbook. Look for errors in your addition and subtraction,
with subtraction being the most likely culprit. This is especially
likely if the amount of the error is a nice even number like one
dollar or ten cents.
Another common error is accidentially adding the amount of
a check in your checkbook instead of subtracting it. If you did
this, your error will be twice the amount of the check (which
makes it easy to find).
If this still does not explain the error, check to be sure you
subtracted last month’s service charge when you balanced your
checkbook with the previous statement. And, of course, if you
did not balance your checkbook last month, you cannot expect
it to come out right this month.
The program has limitations of how many entries you can
make in each category (checks outstanding, deposits outstanding,
etc.), but these can be changed easily. See “‘Easy Changes”
below.

NOTE: SEE DISCLAIMER IN FRONT PART OF BOOK.

SAMPLE RUN

CHECKBOOK BALANCER

FIRST, COMPARE THE BANK STATEMENT


WITH YOUR CHECKBOOK.
MAKE SURE THE STATEMENT AND THE
CHECKBOOK SHOW THE SAME FIGURES
FOR EACH CHECK AND DEPOSIT.

MAKE A MARK IN THE CHECKBOOK NEXT TO


EACH CHECK AND DEPOSIT LISTED
ON THE STATEMENT.

WHAT'S THE ENDING BALANCE SHOWN


ON THE STATEMENT?
? 529.16
14 BASIC Programs for the TRS-80

NOW FIND THE MOST RECENT CHECK THAT


IS SHOWN ON THE BANK STATEMENT.
WHAT IS THE CHECK NUMBER OF THIS CHECK?
? 16052

WHAT BALANCE DOES YOUR CHECKBOOK


SHOW AFTER CHECK NO. 1652
? 489.12

ENTER THE AMOUNT OF EACH DEPOSIT


THAT IS SHOWN IN YOUR CHECKBOOK
PRIOR TO CHECK NO. 1652
BUT IS NOT ON THE STATEMENT.
WHEN NO MORE, SAY 'END!
2? END
TOTAL = Q

NOW ENTER THE AMOUNTS OF ANY CHECKS


THAT ARE IN YOUR CHECKBOOK PRIOR
TO CHECK 1652 BUT THAT
HAVE NOT BEEN SHOWN ON A BANK
STATEMENT YET.

WHEN NO MORE, SAY 'END'


? 35.94
? 1g
? N D
mM

TOTAL = 45.94

NOW ENTER THE AMOUNTS OF ANY


SERVICE CHARGES OR DEBIT MEMOS.

WHEN NO MORE, SAY ‘END!


2? 2.35
2.65
*

ND
v

mM

TOTAL = 5

ENTER THE AMOUNT OF EACH DEPOSIT


THAT IS SHOWN IN YOUR CHECKBOOK
AFTER CHECK NO. 1652 THAT IS
ALSO LISTED ON THE STATEMENT.
CHECKBOOK 15

WHEN NO MORE, SAY ‘END!


> END

TOTAL = @

CONGRATULATIONS! IT BALANCES.

STATEMENT BALANCE + DEPOSITS OUTSTANDING


+ SERVICE CHARGES 525.16

CHECKBOOK BALANCE + CHECKS OUTSTANDING


+ RECENT DEPOSITS = 525.16

DIFFERENCE = §@

PRESS ANY KEY TO CONTINUE

NEXT ACTION:
- LIST CHECKS OUTSTANDING
DO oF

- LIST DEPOSITS OUTSTANDING


- LIST SERVICE CHARGES
ON

- START OVER
- END PROGRAM
UT

- DISPLAY BALANCING INFO


“SIO

-~ LIST DEPOSITS AFTER LAST CHECK

PROGRAM LISTING

199 REM: CHECKROOK


119 REM: COPYRIGHT 1979 BY TOM RUGG AND PHIL FELDMAN
129 CLEAR SG:DEFDBL C,0,S,R,T,W:CLS
1398 PRINT TAB(9)s"CHECKBOOK BALANCER"
148 PRINT
158 MC=59 :MD=50 :MS=5@:MR=50
169 DIM CCMC) DMD) ,S¢MS) ,RCMR)
1779 TC=9:TI=02TS=G: TR=O :NC=G :ND=@ =NS=0 :NR=@
189 E$="ERROR. RE-ENTER, PLEASE."
199 PRINT'FIRST, COMPARE YOUR BANK STATEMENT"
299 PRINT'WITH YOUR CHECKBOOK."
228 PRINT"MAKE SURE THE STATEMENT ANID THE"
239 PRINT'CHECKBOOK SHOW THE SAME FIGURES"
249 PRINT'FOR EACH CHECK AND DEPOSIT."
250 PRINTSPRINT'MAKE A MARK IN THE CHECKBOOK NEXT TO"
269 PRINT'EACH CHECK AND DEPOSIT LISTEN"
279 PRINT'ON THE STATEMENT."SPRINT
16 BASIC Programs for the TRS-80

289 PRINT'WHAT“S THE ENDING BALANCE SHOWN"


299 FRINT'ON THE STATEMENT? S INPUT SR
386 PRINTSFRINT'NOW FINO THE AO5T RECENT CHECK THAT"
318 PRINT'IS SHOWN ON THE BANK STATEMENT."
439 PRINT WHAT IS THE CHECK NUMBER OF THIS CHECK?”
348 INFUT LC
Bud TF LC=INTCLC) THEN 389
344 PRINT'NO, NOT THE AMOUNT OF THE CHECK."
378 GOTO 39d
389 PRINT
398 PRINT WHAT BALANCE DOES YOUR CHECKROOK"
4G PRINT’SHOW AFTER CHECK AQ. ELC
419 INFUT CR
g20 PRONT
439 PRINTVENTER THE AMOUNT OF EACH DEPOSIT"
449 PRINT THAT [5 SHOWN IN YOUR CHECKBOOK"
4G PRINT PRIOR TO CHECK NO. ELC
44D PRINT'BUT ITS NOT ON THE STATEMENT."
479 A$="WHEN NO MORE, SAY “END "' SPRINT At
439 INFUT FS
499 TF RS="END! THEN 245
ISO IF YALCR#I28 THEN 320
318 FRING E$2sGOTO 4-70
oe NO=NTI+1 sOONTO =VAL CRS) s TO=TO+0 (ND)
58 IF NOAMO THEN 409
240 L$="NO MORE ROOM." SPRINTSPRINT 1%
AS PRINTSPRINT’ TOTAL =" 5 T0sPRINT
Due PRINT'NOW ENTER THE AMOUNTS OF ANY CHECKS"
IO’ PRINT’ THAT ARE IN THE CHECKBOOK PRIOR"
378 FRINT’TO CHECK’ ELCs" BUT THAT"
JO PRINT'HAVE NOT BEEN SHOWN ON @ BANK"
I9G FRINT'STATEMENT YET."
500 PRINTSPRINT A$
516 INPUT R$
629 IF RS="ENT" THEN 699
6398 IF VAL(R$)298 THEN 459
649 PRINTsPRINT ES
600 GOTO 69¢
649 NCHNC+1 eC ON) =VAL CRS) s TCS TC+C ONC)
679 IF NCAMC THEN 619
489 FRINTSPRINT LSsFRINT
599 PRINTSPRINT TOTAL ="STCsPRINT
7 OO PRINT NOW ENTER THE AMOUNTS OF ANY"
714 PRINT'SERVICE CHARGES ORK DERIT MEMOS."
P29 PRINTSFRINT Ax
CHECKBOOK 17

#38 INPUT RS
749 TF RS="ENU" THEN 889
Pg TF VAL CRS) 2@ THEN 779
74 FRINTsPRINT ESsG0TO #29
27B NS=NS+7 SONS) eUGL CRS) 2 TS=TS+S (NS)
789 TF NS=M5 THEN 27.49
796 FRINTsPRINT L&sFRINT
896 PRINTSPRINT TOTAL ="eTSsPRINT
Bas GOSUBR 2989
8192 WeSR+TN+TS-Ca-TC~TR sW=ARS (CW)
O15 TF W..981 THEN W=8 ELSE GOTO 84¢
B29 PRINT'CONGRATULATIONS! IT BALANCES."
83 GOTO 859
B49 PRINT SORRY. [f°S OUT OF BALANCE."
Boy FRINT
34d PRINT 'STATENMENT BALANCE + DEPOSITS OUTSTANDING"
3,73 FRINT’+ SERVICE CHARGES =" SR+T0U+TS
889 PRINT
BPM PRINT? CHECK BOOK BALANCE + CHECKS QUTSTANDING"
9G PRINT+ RECENT UEPOSETS ="SCR+TC+TR
918 PRINT
978 PRINT UOTFFERENCE ="5
Pe PRINT&EPRINT PRESS ANY KEY TO CONTINUE”
238 TF INKEYS="" THEN 944
oan PRINT
FAG PRINT NEXT ACTIONS"
950 FRINT" 1 LIST CHECKS OUTSTANDING"
i

946 PRINT" LIST DEPOSITS QUTSTANTINING”


PQ

978 PRINT" 3 ~ LIST SERVICE CHARGES"


Gi

939 PRINT" START QVER"


b>

99G PRINT" ~ ENT PROGRAM"


“iii

1849 PRINT" & ~ DISPLAY BALANCING INFO"


191¢ PRINT? # - LIST GEPOSTTS AFTER LAST CHECK"
1929 INFUT R&sR=VAL CRS)
1939 IF Ret OR Ro? THEN 1859
19849 ON RK GOTO 17990, 1298, 1499, 1499, 1589 859, 179d
1S PRINTSPRINT ESsGO0TU 935
1189 PRINTSPRINT CHECKS OUTSTANIUING"
1114 FOR Je 7 TO NC
11298 PRINT CC) shEAT
1138 GOTO P25
1296 PRINTSPRIATUOEPOSTTS QUTSTANDING"
1214 FOR Je? TO Nt
122d PRINT [06d sNEXT
1238 GOTO 925
18 BASIC Programs for the TRS-80

1390 FRINTsFRINT'SERVICE CHARGES"


1319 FOR J=1 TO NS
1323 FRINT $4.1) sNEXT
1339 GOTO 925
1499 GOTO 129
1580 ENT!
1788 FRINTsPRINT"RECENT DEPOSITS"
1718 FOR J=1 TO NK
1729 FRINT ROI) sNEXT
1738 GOTO 92%
29988 FRINT
2818 FRINT"ENTER THE AMOUNT OF EACH DEPOSIT"
2929 PRINT’ THAT IS SHOWN IN YOUR CHECKBOOK"
2938 PRINT'AFTER CHECK NO.°SLCs "THAT IS"
2948 FRINT'ALSO LISTED IN THE STATEMENT."
2659 FRINTSFRINT AS
29469 INFUT RS
2679 IF R$="ENU" THEN 2149
2889 IF VALCR$I2¢0 THEN 21944
2996 FRINTSPRINT ESeGOTO 2050
2108 NR=NR+1 sR ONRD=VAL CRS) s TRETRAR ONE)
2118 IF NRZMR THEN 2869
2129 PRINTSPRINT L$
2138 PRINTSPRINT' TOTAL ="STREPRINT
21498 RETURN
EASY CHANGES

Change the limitations of how many entries you can make in


each category. Line 150 establishes these limits. If you have
more than 50 checks outstanding at some time, change the
value of MC to 100, for example. The other three variables can
also be changed if you anticipate needing more than 50 entries.
They are: the number of deposits outstanding (MD), the number
of service charges and debit memos (MS), and the number of
recent deposits and credit memos (MR).

MAIN ROUTINES

120 - 290 Initializes variables and displays first instructions.


300 - 370 Gets most recent check number.
380-410 Gets checkbook balance after most recent check
number.
420-545 Gets outstanding deposits.
CHECKBOOK 19

550- 690 Gets outstanding checks.


700- 800 Gets service charges and debit memos.
805 Gets recent deposits and credit memos.
810-920 Does balancing calculation. Displays it.
925 - 1050 Asks for next action. Goes to appropriate sub-
routine.
1100- 1130 Subroutine to display checks outstanding.
1200 - 1230 Subroutine to display deposits outstanding.
1300- 1330 Subroutine to display service charges and debit
memos.
1400 Restarts program.
1500 Ends the program.
1700 - 1730 Subroutine to display recent deposits.
2000- 2140 Subroutine to get recent deposits.

MAIN VARIABLES

Maximum number of checks outstanding.


Maximum number of deposits outstanding.
Maximum number of service charges, debit memos.
Maximum number of recent deposits, credit
memos.
Array for checks outstanding.
Array for deposits outstanding.
Array for service charges and debit memos.
Array for recent deposits and credit memos.
Total of checks outstanding.
Total of deposits outstanding.
Total of service charges and debit memos.
Total of recent deposits and credit memos.
Number of checks outstanding.
Number of deposits outstanding.
Number of service charges and debit memos.
Number of recent deposits and credit memos.
Error message.
Statement balance.
Number of last check on statement.
Checkbook balance after last check on statement.
Reply from operator.
Amount by which checkbook is out of balance.
Numeric value of reply for next action.
20 BASIC Programs for the TRS-80

A$ Message showing how to indicate no more data.


L$ Message indicating no more room for data.
J Loop variable.

SUGGESTED PROJECTS

. Add more informative messages and a more complete intro-


duction to make the program a tutorial for someone who has
never balanced a checkbook before.
. Allow the operator to modify any entries that have been
discovered to be in error. This could be done by adding
another option to the “NEXT ACTION” list, which would
then ask the operator which category to change. This would
allow the operator to correct an error without having to
re-enter everything from the beginning.
. If the checkbook is out of balance, have the program do an
analysis (as suggested in the ‘“‘How To Use It”’ section) and
suggest the most likely errors that might have caused the con-
dition.
. Allow the operator to find arithmetic errors in the check-
book. Ask for the starting balance, then ask for each check or
deposit amount. Add or subtract, depending on which type
the operator indicates. Display the new balance after each
entry so the operator can compare with the checkbook entry.
DECIDE

PURPOSE

‘“‘Decisions, decisions!’’ How many times have you uttered


this lament when confronted by a difficult choice? Wouldn’t a
trusty advisor be helpful on such occasions? Well, you now have
one—your TRS-80 computer of course.
This program can help you make decisions involving the
selection of one alternative from several choices. It works by
prying relevant information from you and then organizing it in
a meaningful, quantitiative manner. Your best choice will be
indicated and all of the possibilities given a relative rating.
You can use the program for a wide variety of decisions. It
can help with things like choosing the best stereo system,
saying yes or no to a job or business offer, or selecting the best
course of action for the future. Everything is personalized to
your individual decision.

HOW TO USE IT

The first thing the program does is ask you to categorize the
decision at hand into one of these three categories:
1) Choosing an item (or thing),
2) Choosing a course of action, or
3) Making a yes or no decision.
You simply press 1, 2, or 3 to indicate which type of decision is
facing you. (It is not necessary to hit the ENTER key.) If you
are choosing an item, you will be asked what type of item it is.
22 BASIC Programs for the TRS-80

If the decision is either of the first two types, you must next
enter a list of all the possibilities under consideration. A question
mark will prompt you for each one. When the list is complete,
type ““END” in response to the last question mark. You must,
of course, enter at least two possibilities. (We hope you don’t
have trouble making decisions from only one possibility!) After
the list is finished, it will be re-displayed so that you can verify
that it is correct. If not, you must re-enter it.
Now you must think of the different factors that are important
to you in making your decision. For example, location, cost,
and quality of education might govern the decision of which
college to attend. For a refrigerator purchase, the factors might
be things like price, size, reliability, and warranty. In any case,
you will be prompted for your list with a succession of question
marks. Each factor is to be entered one at a time with the word
‘““END”’ used to terminate the list. When complete, the list will
be re-displayed. You must now decide which single factor is the
most important and input its number. (You can enter 0 if you
wish to change the list of factors.)
The program now asks you to rate the importance of each of
the other factors relative to the most important one. This is
done by first assigning a value of 10 to the main factor. Then
you must assign a value from QO - 10 to each of the other factors.
These numbers reflect your assessment of each factor’s relative
importance as compared to the main one. A value of 10 means
it is just as important; lesser values indicate how much less
importance you place on it.
Now you must rate the decision possibilities with respect to
each of the importance factors. Each importance factor will be
treated separately. Considering only that importance factor,
you must rate how each decision possibility stacks up. The
program first assigns a value of 10 to one of the decision possi-
bilities. Then you must assign a relative number (lower, higher,
or equal to 10) to each of the other decision possibilities.
An example might alleviate possible confusion here. Suppose
you are trying to decide whether to get a dog, cat, or canary for
a pet. Affection is one of your importance factors. The program
assigns a value of 10 to the cat. Considering only affection, you
might assign a value of 20 to the dog and 6.5 to the canary. This
means you consider a dog twice as affectionate as a cat but a
canary only about two thirds as affectionate as a cat. (No
DECIDE 23

slighting of bird lovers is intended here, of course. Your actual


ratings may be entirely different.)
Armed with all this information, the program will now
determine which choice seems best for you. The various possi-
bilities are listed in order of ranking. Alongside each one is a
relative rating with the best choice being normalized to a value
of 100.
Of course, DECIDE should not be used as a substitute for
good, clear thinking. However, it can often provide valuable
insights. You might find one alternative coming out surprisingly
low or high. A trend may become obvious when the program is
re-run with improved data. At least, it may help you think
about decisions systematically and honestly.

SAMPLE RUN

DECIDE

I CAN HELP YOU MAKE A DECISION. ALL I


NEED TO DO IS ASK SOME QUESTIONS AND THEN
ANALYZE THE INFORMATION YOU GIVE.

WHICH OF THESE BEST DESCRIBES THE TYPE OF


DECISION FACING YOU?

1) CHOOSING AN ITEM FROM VARIOUS


ALTERNATIVES.
2) CHOOSING A COURSE OF ACTION FROM
VARIOUS ALTERNATIVES.
3) MAKING A 'YES' OR 'NO!' DECISION.

WHICH ONE (1, 2, OR 3)? 1


WHAT TYPE OF ITEM MUST YOU DECIDE UPON
2 VACATION

I NEED TO HAVE A LIST OF EACH


VACATION UNDER CONSIDERATION.

INPUT THEM ONE AT A TIME IN RESPONSE


TO EACH QUESTION MARK. THE ORDER IN WHICH
YOU INPUT THEM HAS NO SPECIAL SIGNIFICANCE.
24 BASIC Programs for the TRS-80

TYPE THE WORD ‘END! TO INDICATE THAT


THE WHOLE LIST HAS BEEN ENTERED.

MOUNTAIN CAMPING
oD

AFRICAN SAFARI
9D

TRIP TO WASHINGTON D.C.


90

END
"2

».K. HERE'S THE LIST YOU'VE GIVEN ME:


©

1) MOUNTAIN CAMPING
2) AFRICAN SAFARI
3) TRIP TO WASHINGTON D.C.

IS THIS LIST CORRECT CY OR N) ? YES

NOW, THINK OF THE DIFFERENT FACTORS


THAT ARE IMPORTANT TO YOU IN CHOOSING
THE BEST VACATION.

INPUT THEM ONE AT A TIME IN RESPONSE


TO EACH QUESTION MARK.

TYPE THE WORD ‘END! TO TERMINATE THE


LIST.

RELAXATION
oD

AFFORDABILITY
oD

CHANGE OF PACE
DO

END
VO

HERE'S THE LIST OF FACTORS YOU GAVE ME:

1) RELAXATION
2) AFFORDABILITY
3) CHANGE OF PACE

DECIDE WHICH FACTOR ON THE LIST IS THE


MOST IMPORTANT AND INPUT ITS NUMBER.
CTYPE 6 IF THE LIST NEEDS CHANGING.)

2? 2

NOW LET'S SUPPOSE WE HAVE A SCALE OF


IMPORTANCE RANGING FROM 6-12.
DECIDE 25

WE'LL GIVE AFFORDABILITY A


VALUE OF 18 SINCE AFFORDABILITY
WAS RATED THE MOST IMPORTANT.

ON THIS SCALE, WHAT VALUE OF IMPORTANCE


WOULD THE OTHER FACTORS HAVE?

RELAXATION
2? 5.5

CHANGE OF PACE
? 9

EACH VACATION MUST NOW BE COMPARED WITH


RESPECT TO EACH IMPORTANCE FACTOR.
WE'LL CONSIDER EACH FACTOR SEPARATELY
AND THEN RATE EACH VACATION IN TERMS
OF THAT FACTOR ONLY.

LET'S GIVE MOUNTAIN CAMPING


A VALUE OF 18 ON EVERY SCALE.
THEN EVERY OTHER VACATION
WILL BE ASSIGNED A VALUE HIGHER OR LOWER
THAN 18. THIS VALUE DEPENDS ON HOW MUCH
YOU THINK IT IS BETTER OR WORSE THAN
MOUNTAIN CAMPING.
AARAAARAA CHIT ANY KEY TO CONTINUE)
CA key is pressed)
CONSIDERING ONLY RELAXATION AND
ASSIGNING 18 TO MOUNTAIN CAMPING ;
WHAT VALUE WOULD YOU ASSIGN TO
AFRICAN SAFARI? 3
TRIP TO WASHINGTON D.C.? 9

CONSIDERING ONLY AFFORDABILITY AND


ASSIGNING 18 TO MOUNTAIN CAMPING ;
WHAT VALUE WOULD YOU ASSIGN TO
AFRICAN SAFARI? 1
TRIP TO WASHINGTON D.C.? 8

— ee ame oem jee om ee ee ee ews we i i i =U

CONSIDERING ONLY CHANGE OF PACE AND


ASSIGNING 18 TO MOUNTAIN CAMPING ;
26 BASIC Programs for the TRS-80

WHAT VALUE WOULD YOU ASSIGN TO


AFRICAN SAFARI? 69
TRIP TO WASHINGTON D.C.? 25
TRIP TO WASHINGTON D.C. COMES OUT BEST
BUT IT'S VERY CLOSE.
---- HERE IS THE FINAL LIST IN ORDER ----
TRIP TO WASHINGTON D.C. HAS BEEN
GIVEN A VALUE OF 18% AND THE OTHERS RATED
ACCORDINGLY.

199 TRIP TO WASHINGTON D.C.


98.6587 MOUNTAIN CAMPING
78.8376 AFRICAN SAFARI

PROGRAM LISTING

190 REM: DECIDE


118 REMs COPYRIGHT 19°9 BY FHIL FELUMAN AND TOM RUG
159 CLEAR 59a
14@ MUt=1¢
178 TIM L&CMtD) FS CMT YONI .COMT MO) CMD, 20M)
180 ES="ENT”
288 GOSUB 2690
218 PRINT” I CAN HELP YOU MAKE A DECISION.
ALL I NEED TO 00 [8 Ask”
228 PRINT’ SOME QUESTIONS AND THEN ANALYZE THE
TNFORMATION YOU GIVE.”
248 PRINTSFRINT TARCB) I STRINGH (Ad, UU aPROINT
248 PRINT WHICH OF THESE BEST DESCRIBES THE
TYFE OF TECTSTON FACING YOU?
2a@ FRINTsSPRINT’ 7) CHOOSING AN TTEM FROM VARTOUS
ALTERNATIVES,”
268 PRINT" 2) CHOOSING A COURSE OF ACTION FROM
VAR TOUS ALTERNATIVES,”
278 PRINT" 3) MAKING A “YES” OR “NOe PECTS fON."
264 PRINTSPRINT WHICH ONE C1, 2, QR 337";
298 R= TNKEY$s TF Ro="" THEN 299
344 T=VALCRS) STF Te1 OR Tea THEN 299
350 PRINT TsGOSUR 200d
449 FOR w=1 TO 9:Ré=TNKEYS2NEXT:OM T GOTO 410,444, 4°9
41@ PRINT'UWHAT TYPE QF ITEM MUST YOU DECTOE UFQN"
ACB INFUT T$sGOTO 204
448 T$="COURSE OF ACTION’ S GOTO 3@9
479 TH="° YES" OR “NOT”
49@ NI=2sL$t1)="CECTDING YES" sL$(2)="0ECIOING NO"
DECIDE 27

49Q GOTO 738


JOG GOSUR 2998:NI=9
1d FRINT" I NEED TO HAVE & LIST OF EACH"
wed FRINT T$)" UNDER CONSTOERATION. "sF RINT
IO PRINT” CNFUT THEM ONE AT A TIME IN RESPONSE TO
FACH QUESTION MARK.”
PRINT THE ORDER TN WHICH YOU TNFUT THEM HAS
NO SFECTAL SIGNIFICANCE."
FPRINTSPRINT" TYPE THE WORT “"SE&s"° TO INGICATE
THAT THE WHOLE LIST"
"159 FRIATUHAS BEEN ENTERED. sPR INT
S38 CF NTS=M0 THEN PRINT! LIST FULL --"sG0TO 42¢
PG NT=M T+ Ts INPUT Léon.)
SAB Tk LBCNTISSES THEN 289
619 NaN]
626 IF MT>=2 THEN 4639
439 FRINTSPRINT YOU MUST HAVE AT LEAST 2 CHOICES !"':
PRINT
548 PRINT’ TRY AGAIN’ sGOQSUB 2169:G0TO 5a¢
SSG GOSUR 2006:
PRINT'O.K, HERES THE LIST YOUVE GIVEN MES SFRINT
469 FOR w=? TO NTs
PRINT US ISCHREC24) 5°) “LBC ENEXTIPRINT
479 FOR J=1 TO SRS INKEYSENEXT s
FRINT'IS THIS LIST CORRECT CY OR A) P'S
438 Ré=TNKE ($2 (F Rb="" THEN 48d
ag TF Ré="Y¥" THEN PRIATUYES"'sGOTO 7S
Fag TR R&="N" THEN PRINT UNG!
718 TF Rb="N" THEN PRINT:
PEINT THE LIST MUST BE RE-ENTERED
Peis IF R#e"AN? THEN GOSUB 21aasGOSUR Mae
em
Z 3 4 GOTO Aga
oe GOUSUG 2O8OdeFOR 1 TO SsRb=INKEY$ENEXT
7a PRINT" NOW, THINK OF THE DIFFERENT FACTORS"
PFO IF T3 > THEN
PRINT THAT ARE TMPORTANT TO YOU IN CHOOSING"
PAS TF 123 THEN PRINT’ THE BEST UPTbir
209
IF f=3 THEN
PRINTUTMAT ARE TMFORTANT YO YOU IN DECITHNG "STB!
849 PRINT SPRINT" TNFUT THEM ONE AT & TIME IN
RESPONSE TO EACH"
81d FRINTUQUESTTION MARK. SPRINT
a8 PRINT" TYFE THE WORD USE BEY. TO
TERMINATE THE List."
(3.4 if PRINT aNF sd
8.35 TF NF OSM THEN FRIAT'-- LIST FULL --"SseRINTsG0TO 874
28 BASIC Programs for the TRS-80

8438 NFSNF +1: INPUT FSCNF)


B50 IF FeC(NFISSES THEN 835
360 NF=NF-TIFRINT
878 IF NF<1 THEN PRINT"YOU MUST HAVE AT
LEAST ONE ! -- REDO I[T"
889 IF NF=1 THEN GOSUBR 2108:GOTO 759
899 GOSUB 2906:
PRINT’HERE“S THE LIST OF FACTORS YOU GAVE ME" sFRINT
999 FOR J=1 TO NF:
PRINT’ "SJ,CHR¢(24)5") "SF SCJ) sNEXTSPRINT
919 PRINT’ GECIUE WHICH FACTOR ON THE LIST IS THE
, MOST IMPORTANT"
929 PRINT'AND INPUT [TS NUMBER. (TYPE @ IF THE
LIST NEETIS CHANGING.)"
938 PRINT
949 INPUT ASA=INTCA) SIF A=@ THEN 759
959 IF ANF OR Ax@ THEN 899
199¢@ GOSUG 2690sIF NF=1 THEN 120¢
1918 PRINT’ NOW LETS SUPPOSE WE HAVE A SCALE OF
IMPORTANCE"
1926 PRINT'RANGING FROM 9-19."
1939 PRINTSPRINT' WELL GIVE "SFE TADS" A"
1949 PRINT'VALUE OF 1@ SINCE "SS tA)
1958 FRINT'WAS RATED THE MOST IMPORTANT." SPRINT
1960 PRINT" ON THIS SCALE, WHAT VALUE OF IMFORTANCE”
1478 PRINT WOULD) THE OTHER FACTORS HAVE?"
1988 FOR J=1 TQ NFsIF J=A THEN 1119
1990 PRINTSPRINT FStJos INPUT YC)
1168 IF VCJo<8 OR VCJOF19 THEN
PRINT" IMPOSSIBLE VALUE ~ TRY AGAIN’ sGOTO 189¢
1118 NEXT
1280 VCAI=18sQ=9eFOR J=1 TO NF sQ=Q+¥0 I) sNEXT:
FOR J=1 TO NF
1218 VID=EVCI/QENEXT:GOSUBR 2998
1228 IF Ta23 THEN FRINT" EACH "ST$;5
1238 IF T=3 THEN
PRINT" QECIQING “YES” OR DECIDING “NO’ "5
1248 PRINT" MUST NOW"
1259 PRINT’ BE COMPARED WITH RESPECT TQ
EACH IMPORTANCE FACTOR."
1269 PRINT" WE“I.L CONSIQER EACH FACTOR SEPARATELY
ANID THEN RATE"
1276 IF Tx23 THEN PRINT"EACH "5 T$5" IN TERMS"
1289 IF T=3 THEN
PRINT DECIDING “YES” OR DECIDING “NO” IN TERMS”
1299 FRINT’OF THAT FACTOR ONLY."sPRINT
DECIDE 29

139d PRINT" LETS GIVE "Sheed


1.319 PRINTA YALUE OF 74 ON EVERY SCALE."
1329 IF Teed THEN PRINT" THEN EVERY OTHER "STS
1339 IF J=3 THEN PRINT" THEN CECIDING “NQ?"
1346 PRINT WILL BE ASSTGNED A VALUE HIGHER OF
LOWER THAN 14. THIS"
140 PRINT YALUE DEPENDS GN HOW MUCH YOU THINK IT IS
GETTER OR WORSE"
1344 PRINT THAN USLétdd oo!
1372 PRINT! detacidtcte CHET ANY KEY TO CONTINUE)"
1 489 RE=INKEY$:TIF R="" THEN 1389
13998 FOR J=1 TO WF
1496 PRINT TAR(8) (STRINGS (25,"-")
1419 PRINT’ CONSIDERING ONLY "FSCJOI" ANG”
1426 FRINTVASSIGNING 10 TO "SLecie 3"
14.39 PRINT WHAT YALUE WOULD YOU ASSTGN TO"
1448 FOR K=2 TO NI
1459 PRINT LOCK) ps INPUT CORK, 2IF COK,J)2=@ THEN 14779
1449 PRINT" -- NEGATIVE YALUES NOT LEGAL --"sGOTO 1459
14798 NEXTSFRINTsS CO). J=198NeEXT
1399 FOR J&1 TO NF sQ=@sFOR K=1 TO NTI
1512 Q=Q+C CK, J sNEXTsFOR Ket TO NI
1328 CCK DECK, J /QsNEXT sNEXT
1339 FOR K=1 TO NDsfi(koeasFOR J=1 TO NF
1348 NOK =OCK +0 Ok JY CD NEXT SNEXT
Bo he
sdyf MxX=OsFOR K=1 TO NI
1549 TF TAK OOM THEN MxXS0ICK)
1573 NEXTSFOR K=1 TQ NT ste kK =DCK #1 9O/MX ENEXT
1409 FOR Ke) TO NDTs2¢K)=K sNEXT sNMENT-1
1418 FOR Ke) TO NDeFOR Jt TO NMsNTREZ
CJ ene e+ ds
TF DENT S0N2) THEN 14638
1620 ZO IHVIENT EZ OIEND
1430 NEXTSNEXTeJT=2Z 01) 9 J2=2¢2) Oreo ( JT) 0 J2) 3
GOSUBR 2989
1789 PRINT Lodi);
1719 FRINT’ COMES OUT GEST"
1726 IF UFeS THEN FRINT'BUT IT°S VERY CLOSE." :GOTO 184%
1738 TF DF£19 THEN PRINT BUT IT°S FAIRLY CLOSE."
GOTO 13888
1749 IF DF<2@ THEN FRINT'RY A FAIR AMOUNT. ":GOTO 1889
1759 FRINT’QUITE GECISTVELY."
1892 FRINT"- - - - HERE IS THE FINAL LIST IN
ORQER - - - 7"
1819 PRINT L&Ctt)9" HAS BEEN"
1828 PRONT'GIYVEN A VALUE OF 148 AND THE
QTHERS RATED ACCORTIAGLY."
30 BASIC Programs for the TRS-80

1846 PRINT" NS OTRINGS(38. °-"")


1884 FOR J&1 TO NGsQ=Z2CJ) sPRINT 060),L3(Q) sNEXT
186¢@ END
2993 FOR J=1 TO 49@:sNEXT
2819 CLSSPRINT TABC26) 5 °0ECTOE sPRINT s RETURN
21986 FOR JF1 TO 1588sNEXTSRETURN

EASY CHANGES

1. The word ““END”’ is used to flag the termination of various


input lists. If you wish to use something else (because of con-
flicts with items on the list), change the definition of E$ in
line 180. For example, to use the word “DONE,” change line
180 to
180 E$="““DONE”
2. Line 2100 contains a timing delay used regularly in the pro-
gram. If things seem to change too fast, you can make the
number 1500 larger. Try
2100 FOR J=1 TO 3000: NEXT: RETURN
3. The program can currently accept up to ten decision alterna-
tives and/or ten importance factors. If you need more, in-
crease the value of MD in line 160. Thus, to use 15 values,
line 160 should be
160 MD=15

MAIN ROUTINES

150- 180 Initializes and dimensions variables.


200 - 350 Determines category of decision.
400 - 490 Gets or sets T$.
500 - 730 Gets list of possible alternatives from user.
750-950 Gets list of importance factors from user.
1000-1110 User rates each importance factor.
1200-1470 User rates the decision alternatives with respect to
each importance factor.
1500-1570 Evaluates the various alternatives.
1600-1630 Sorts alternatives into their relative ranking.
1700-1860 Displays results.
2000 - 2010 Subroutine to clear screen and display header.
2100 Time wasting subroutine.
DECIDE 31

MAIN VARIABLES

MD Maximum number of decision alternatives.


NI Number of decision alternatives.
L$ String array of the decision alternatives.
NF Number of importance factors.
F$ String array of the importance factors.
V Array of the relative values of each importance
factor.
A Index number of most important factor.
C Array of relative values of each alternative with
respect to each importance factor.
T Decision category (l=item, 2=course of action,
3=yes or no).
TS$ String name of decision category.
E$ String to signal the end of an input data list.
J,K Loop indices.
R$ User reply string.
Q,NI,N2 Work variables.
D Array of each alternative’s value.
MX Maximum value of all alternatives.
DF Rating difference between best two alternatives.
Z Array of the relative rankings of each alternative.

SUGGESTED PROJECTS

1. Allow the user to review his numerical input and modify it if


desired.
2. Insights into a decision can often be gained by a sensitivity
analysis. This involves running the program a number of times
for the same decision. Each time, one input value is changed
(usually the one you are least confident about). By seeing
how the results change, you can determine which factors are
the most important. Currently, this requires a complete re-
running of the program each time. Modify the program to
allow a change of input after the regular output is produced.
Then recalculate the results based on the new values. (Note
that many input arrays are clobbered once all the input is
given. This modification will require saving the original input
in new arrays so that it can be reviewed later.)
32 BASIC Programs for the TRS-80
LOAN

PURPOSE

One of the most frustrating things about borrowing money


from a bank (or credit union or Savings and Loan) is that it’s
not easy to fully evaluate your options. When you are borrowing
from a credit union to buy a new car, you might have the choice
of a thirty-six or a forty-eight month repayment period. When
buying a house, you can sometimes get a slightly lower interest
rate for your loan if you can come up with a larger down pay-
ment. Which option is best for you? How will the monthly
payment be affected? Will there be much difference in how fast
the principal of the loan decreases? How much of each payment
will be for interest, which is tax-deductible?
You need to know the answers to all these questions to make
the best decision. This program gives you the information you
need.

HOW TO USE IT

The program first asks you the size of the loan you are con-
sidering. Only whole dollar amounts are allowed—no pennies.
Loans of ten million dollars or more are rejected (you can
afford to hire an investment counselor if you want to borrow
that much). Then you are asked the yearly interest rate for the
loan. Enter this number as a percentage, such as “10.8”. Next,
you are asked to give the period of the loan in months. For a five
year loan, enter 60. For a thirty year mortgage, enter 360. The
program then displays this information for you and calculates
34 BASIC Programs for the TRS-80

the monthly payment that will cause the loan to be paid off
with equal payments each month over the life of the loan.
At this point you have four options. First, you can show a
monthly analysis. This displays a month-by-month breakdown,
showing the state of the loan after each payment. The four
columns of data shown for each month are the payment number
(or month number) of the loan, the remaining balance of the
loan after that payment, the amount of that payment that was
interest, and the accumulated interest paid to date. Twelve lines
of data are displayed on the screen, and then you can either
press the T key to get the final totals for the loan, or any other
key to get the data for the next twelve months of the loan.
The second option is overriding the monthly payment. It is
a common practice with second mortgage loans to make smaller
monthly payments each month with a large “balloon”? payment
as the final payment. You can use this second option to try
various monthly payments to see how they affect that big pay-
ment at the end. After overriding the monthly payment, you
will want to use the first option next to get a monthly analysis
and final totals using the new monthly payment.
The third option is to simply start over. You will generally
use this option if you are just comparing what the different
monthly payments would be for different loan possibilities.
The fourth option ends the program.
By the way, there is a chance that the monthly payment
calculated by your lender will differ from the one calculated
here by a penny or two. We like to think that this is because we
are making a more accurate calculation.

NOTE: SEE DISCLAIMER IN FRONT PART OF BOOK


LOAN

SAMPLE RUN

LOAN CALCULATOR

ee eae
233) ee ee)
LENGTH OF LOAN (MONTHS)? 368.

The operator enters the three necessary pieces of information about his or
her loan.

Pe eae eee lf
MONTHLY PAYMENT IS 368.85

NEXT ACTION:
1 - SHOW MONTHLY ANALYSIS
2 — OVERRIDE MONTHLY PAYMENT
ciemel(.1i 2 4
4 - END
pa

The program responds with the monthly payment that will pay off the
loan with equal payments over its life, then asks the operator what to do
next. The operator asks for the monthly analysis.
BASIC Programs for the TRS-80

Peee ea 83
REMAINING © ——INTEREST——
Pree tod Pete a
41908.48 341.5 341.5
ens] ve ee RD
ers CR ee A
oe SO

ee CO
Veo

ee CO Se A)
ee] ce <8)
TEs ey e/a 3
Cea. SOAR
OCA, KS OI
417%.68 339.77 345.18 -
mm
>

Si Sta S keh | Wr)


le 4175401 339.43 4884.21
RAM BU Ce mn Team net ia ae

The program responds with information about the first twelve months of
the loan, then waits.

Pee SOent aes


3.) 2,3
Pte: a
CALCULATING TOTALS...
LAST PAYMENT = 358.11
TOTAL PAYMENTS = 129895.26
MONTHLY PAYMENT WAS 368.85

PRESS ANY KEY TO CONTINUE

The operator presses ‘‘T’’, and after a few seconds the program displays
totalling information about the loan.
LOAN 37

PROGRAM LISTING

190 REM: LOAN CALCULATOR


119 KEM: COPYRIGHT 1979 BY TOM RUGG ANDI PHIL FELDMAN
120 CLEAR 5@:CLS:DEFINT J,L,N:DEFDBL A-F,M,P-Z
136 PRINT TAB(8)""LOAN CALCULATOR"
149 PRINT
159 INPUT"LOAN AMOUNT"SA
155 GOSUB 1900:IF A= THEN 15@
166 INPUT" INTEREST RATE"sR
179 INPUT"LENGTH OF LOAN (MONTHS) "SN
186 R=ABS(R) sM=R/1209
190 GOSUR 9899
299 W= (14M)4N
218 P= (AxMRW)/ (W-1)
229 P=INT(P#190+.99) sP=P/199
230 PRINT"MONTHLY PAYMENT IS" SP
249 FP=PsPRINT
259 PRINT"NEXT ACTION!"
278 FRINT" 1 - SHOW MONTHLY ANALYSIS"
289 PRINT’ 2 - OVERRITE MONTHLY PAYMENT"
299 PRINT" 3 - START OVER"
399 PRINT" 4 ~ END"
319 INPUT C
329 ON C GOTO 449,499,129,379
339 PRINT'CHOICES ARE 1, 2, 3, ANID 4"
349 GOTO 259
374 ENII
499 PRINT: INPUT"MONTHLY PAYMENT"3F
41g GOTO 249
449 GOSUB 459:GOTO 519
450 GOSUB 849
A6G PRINT TAR(7) s"REMAINING" s TAR(22) 3
47a PRINT" --~~- INTEREST----- "
4gg PRINT'MONTH BALANCES TAR( 22):
49g PRINT" MONTH TO-DATE"
500 RETURN
519 R=A«199:TT=0:TP=G:L=9:P=P4190sRg="""
520 FOR J=1 TO N
538 T=M#B
54g T=INT(T+.5)
550 IF J=N THEN P=B+T
560 TP=TP+P sB=B-P+T s TT=TT+T
565 IF Bid THEN GOSUR 2499
578 IF R¢="T" THEN 4649
18D PB=B/189
38 BASIC Programs for the TRS-80

J98 PT=T/199
609 T2=TT/199
618 PRINT J; TABCS),.
615 PRINT USING HHHHHHHH .HH-" SPBSPT; 12
61/7 IF B=@ THEN JENsGOTO 639
629 |L=L+1sIF Lsi2 THEN 669
639 PRINT'PRESS “T~ FOR TOTALS, ANY OTHER
KEY TO CONTINUE":
649 R$=INKEYS:IF R$="'"" THEN 649
659 L=@:GOSUB 459:
IF R$="T" THEN PRINT'CALCULATING TOTALS..."
6469 NEXT
678 PRINT:PRINT"LAST PAYMENT ="5P/199
589 PRINT" TOTAL PAYMENTS ="STF/19¢
699 PRINT’ MONTHLY FAYMENT WAS" SFF
719 PRINTsPRINT'PRESS ANY KEY TO CONTINUE"
229 RS=INKEYSsIF RG="" THEN 72¢
738 P=FPsGOTO 249
899 CLS
819 PRINT As"FOR’ SN; "MONTHS AT" SRS"PER CENT"
838 RETURN
1899 A=ABS(A) sA=INT(A)
1919 IF AX18999998 THEN RETURN
1928 PRINT’ TO0 LARGE"
1930 A=OsRETURN
2999 P=P+R:TP=TP+B2B=6
2919 RETURN

EASY CHANGES

1.The number of lines of data that are displayed on each screen


when getting a monthly analysis can be changed by altering
the constant 12 in statement 620.
2. To include the monthly payment in the heading at the top of
each screen of the monthly analysis, insert the following line:
815 IF FP<>0O THEN PRINT““MONTHLY PAYMENT IS” ;FP

MAIN ROUTINES

120-170 Displays title. Gets loan information.


200 - 230 Calculates and displays monthly payment.
250- 370 Asks for next action. Goes to corresponding
routine.
LOAN 39

400- 410 Gets override for monthly payment.


440- 730 Calculates and displays monthly analysis.
800- 830 Subroutine to clear screen and display data about
the loan at the top.
1000 - 1030 Edits loan amount (size and whole dollar).
2000 - 2010 Subroutine to handle early payoff of loan.

MAIN VARIABLES

Amount of loan.
Interest rate (percentage).
Length of loan (number of months).
Monthly interest rate (not percentage).
Work variable.
Monthly payment (times 100).
First monthly payment.
Choice of next action.
Remaining balance of loan (times 100).
Total interest to date (times 100).
Total payments to date.
Number of lines of data on screen.
Reply from operator at keyboard.
Work variable for loops.
Monthly interest.
Remaining balance to be displayed (two decimal
places).
PT Monthly interest to be displayed (two decimal
places).
T2 Total interest to be displayed (two decimal places).

SUGGESTED PROJECTS

1. Display a more comprehensive analysis of the loan along with


the final totals. Show the ratio of total payments to the
amount of the loan (TP divided by A), for example.
2. Modify the program to show an analysis of resulting monthly
payments for a range of interest rates and/or loan lengths
near those provided by the operator. For exampl]:2, if an
interest rate of 9.5 percent was entered, display the: xnthly
payments for 8.5, 9, 9.5, 10, and 10.5 percent.
40 BASIC Programs for the TRS-80
MILEAGE

PURPOSE

For many of us, automobile operating efficiency is a contin-


ual concern. This program can help by keeping track of gasoline
consumption, miles driven, and fuel mileage for a motor vehicle.
It allows reading and writing data files with the cassette unit.
Thus, a master data file may be retained and updated. The pro-
gram computes mileage (miles per gallon or MPG) obtained
after each gasoline fill-up. A running log of all information is
maintained. This enables trends in vehicle operation efficiency
to be easily checked.

HOW TO USE IT

The program requests the following data from the operator as


a record of each gasoline fill-up: date, odometer reading, and
number of gallons purchased. The most useful results will be
obtained if entries are chronological and complete, with each
entry representing a full gasoline fill-up.
In order to use the cassette features, the operator must be
able to position the tape correctly for both reading and writing.
The simplest way to do this is to only record files at the begin-
ning of a tape. One tape could certainly be used this way, with
each file writing over the previous one. However, we suggest
alternating between two physical tapes. This will insure a_rea-
sonably up-to-date back-up tape in case of any failure. A special
cassette control technique allows the recorder to be operational
42 BASIC Programs for the TRS-80

when necessary. Thus, you will be able to fast forward or rewind


the cassette to reach any desired tape location.
The program operates from a central command mode. The
operator requests branching to any one of five available subrou-
tines. When a subroutine completes execution, control returns
to the command mode for any additional requests. A brief
description of each subroutine now follows:
1) READ OLD MASTER FILE
This reads previously stored data from the cassette. Any data
already in memory is deleted. During the read, the name of the
data file and the total number of records read are displayed.
2) INPUT FROM TERMINAL
This allows data records to be entered directly from the
terminal. This mode is used to provide additional information
after a cassette read and to enter data for the first time. The
program will prompt the operator for the required information
and then let him verify that it was entered correctly. A response
of ‘‘F” to the verification request signals that no more data is to
be entered.
3) WRITE NEW MASTER FILE
This command causes the current data to be written on cas-
sette. The program requests a name for the file. When later read,
this name will be displayed, allowing verification of the correct
data file.
4) DISPLAY MILEAGE DATA
This subroutine computes mileage (miles per gallon) from the
available data. It formats all information and displays it in tabu-
lar form. When data fills the screen, the user is prompted to hit
any key to continue the listing. When all data is displayed,
hitting any key will re-enter command mode.
5) TERMINATE PROGRAM
Ends execution and returns the computer to BASIC.

SAMPLE RUN

MILEAGE

COMMAND LIST
- READ OLD MASTER FILE FROM CASSETTE
re

- INPUT DATA FROM THE TERMINAL


FWPb

- WRITE NEW MASTER FILE TO CASSETTE


- DISPLAY MILEAGE DATA
- TERMINATE PROGRAM
Wm
MILEAGE 43

ENTER COMMAND BY NUMBER? 2

ENTER THE FOLLOWING DATA AS REQUESTED


- DATE CE.G. 1/39/79)
- ODOMETER READING CMILES)
-~ # GALLONS BOUGHT

DATE? 9/28/78
ODOMETER? 5151.1
# GALLONS? 14.6

INPUT DATE: 9/28/78


CHECK ODOMETER: 51951.1
GALLONS: 14.6

-~ IS INPUT OK ? -

CY=YES, N=NO, F=YES AND FINISHED)? Y

DATE?

(10 more entries are input)

CY=YES, N=NO, F=YES AND FINISHED)? F

(the five commands are listed again)

ENTER COMMAND BY NUMBER? 4&

DATE ODOMETER GALLONS MPG


9/28/78 51951.1 14.6 g
18/6/78 51299.7 13.8 18.8143
18/17/78 51553.8 13.1 19.3971
19/29/78 51798 13.7 17.8248
11/5/78 52941.9 13.3 18.3382
11/15/78 52394.9 14 18.7857
11/26/78 52576.8 13.7 19.4989
12/1/78 52842.5 14.6 18.6995
12/9/78 53948.4 11.8 17.449
12/15/78 53359.7 14.7 21.1769
12/23/78 5361.2 13.3 18.1579

HIT ANY KEY FOR COMMAND MODE


44 BASIC Programs for the TRS-80

(a key is pressed)
(the five commands are listed again)
ENTER COMMAND BY NUMBER? 3.

1) THE CASSETTE KEYS ARE NOW OPERATIONAL.


2) POSITION THE CASSETTE TAPE FOR WRITING.
3) PRESS THE CASSETTE STOP KEY.
4) HOLD DOWN THE KEYBOARD'S ENTER KEY.
(the above is duly done)
5S) PRESS THE RECORD AND PLAY KEYS ON
CASSETTE UNIT.
(the above is done)
NAME FOR FILE? VOLVO78
WRITING FILE: VOLVO78
RECORDS #1234567 8 9 19 11

6) PRESS THE CASSETTE STOP KEY.


7) PRESS THE KEYBOARD'S ENTER KEY.

(a subsequent run)

ENTER COMMAND BY NUMBER? 1

1) THE CASSETTE KEYS ARE NOW OPERATIONAL.


2) POSITION THE CASSETTE TAPE FOR READING.
3) PRESS THE CASSETTE STOP KEY.
4) HOLD DOWN THE KEYBOARD'S ENTER KEY.

(the above is duly done)


5) PRESS THE PLAY KEY ON CASSETTE UNIT.
6) PRESS THE KEYBOARD'S ENTER KEY.
(the above is done)
READING FILE: VOLVO 78
READING RECORDS #12345 678916 11
11 DATA RECORDS READ

7) PRESS THE CASSETTE STOP KEY.


8) PRESS THE KEYBOARD'S ENTER KEY.
(the above is done to return to command mode)
MILEAGE 45

ENTER COMMAND BY NUMBER? 5


READY

PROGRAM LISTING
198 REM: MILEAGE
119 REM: COPYRIGHT 1979 BY PHIL FELIMAN AND TOM RUGG
1298 CLEAR 299
138 MW= 15 sMR=29 sN=d
149 CIM DS (MR) DCM) ,G(MR) JM (MR) sB$=""
138 CLO:R=@:PRINT TAB(25)2"MILEAGE" :PRINTs
PRINT"COMMAND LIST"
169 PRINT" 1 - READ OLD MASTER FILE FROM CASSETTE"
178 PRINT" 2 - INPUT DATA FROM THE TERMINAL”
189 PRINT’ 3 - WRITE NEW MASTER FILE TO CASSETTE"
199 PRINT 4 - DISPLAY MILEAGE DATA"
298 PRINT’ S ~- TERMINATE PROGRAM’ sPRINT
219 INFUT" ENTER COMMAND BY NUMBER" SR:
IF R“1 OR RYS THEN 1598
229 ON R GOSUB 769,390,509,4608,899:GOTO 159
399 IF N=MR THEN 479
319 PRINTSPRINT"ENTER THE FOLLOWING [IATA AS REQUESTED"
529 PRINT" - DATE (E.G. 1/30/79)"
538 PRINT" ~ OUOMETER READING (MILES)"
549 FRINT" - # GALLONS BOUGHT"
559 N=N+1 PRINTS INPUT'DATE" SR$2RS=LEFTS (R$, 8) 11S (NERS
549 INPUT"ODOMETER" SRiD(N)=RiIF RG THEN 348
379 INPUT"H GALLONS" SR:G(N)=REIF R<@ THEN 376
389 PRINT:PRINT TAB(3) s"INFUT DATE: "s$(N)
398 PRINT TAB(3) s"CHECK ODOMETER: "STN:
PRINT TAB(13) "GALLONS" 3G(N)
499 PRINT:PRINT" -~ I$ INPUT OK ? -"sPRINT
419 INPUT" (Y=YES, N=NO, F=YES AND FINISHED) "sR$:
R$=LEFTS$(R$,1)
429 IF R$="N" THEN N=N-12PRINT!FRINT" REDO LAST DATA":
GOTO 35¢
439 IF R$="F" THEN RETURN
449 TF R#<>"Y" THEN 409
450 IF N=MR THEN 479
460 GOTO 359
478 PRINT sPRINT'dee NO MORE DATA ALLOWED :GOSUB 920:
RETURN
509 IF Nel THEN PRINT:PRINT’&* NO DATA TO WRITE":
GOSUB 926:RETURN
Jd R$="WRITING" :GOSUB 858sPRINT
46 BASIC Programs for the TRS-80

oO PRINTS) PRESS THE RECORD ANI! PLAY KEYS ON


CASSETTE UNIT."
INPUT"NAME FOR FILE"ST$:K=NiIF N3MW THEN K=MW
PRINTH-1, T$:PRINTH-1,KsK=1 sL=N
IF NOMW THEN K=N-MW+1s
PRINT” — ONLY LAST"SMWs"VALUES WILL BE WRITTEN"
PRINT"WRITING FILE: "$7$:PRINT" RECORDS # "Ss
FOR J=K TO LePRINTH-1,0$(J) ,0¢1) ,G(J)sPRINT Js :NEXT
PRINT!PRINTsPRINT"S) PRESS THE CASSETTE STOF KEY."
PRINT"?) PRESS THE KEYBOARDS ENTER KEY."
GOSUB 94@:RETURN
IF N<=1 THEN PRINT:PRINT«:«: NOT ENOUGH DATA":
GOSUB 926:RETURN
619 M(1)=@:FOR J=2 TON:
IF G(J)=@ OR G(J-1)=@ THEN M(J)=@:GOTO 649
628 R=(D(J)-D(J-1))/G(J) sIF R&@ THEN R=9
639 MC JSR
549 NEXT :K=-10:L=9
650 K=K+112L=L+11sIF LON THEN L=N
669 CLS:PRINT" DATE", "ODOMETER", "GALLONS", "MPG"
679 FOR J=K TO LePRINT I$(J),D(J),G(J) ,M(J) 2NEXT PRINT
486 IF L=N THEN PRINT"HIT ANY KEY FOR COMMAND MODE":
GOSUB 969:sRETURN
596 PRINT'HIT ANY KEY TO CONTINUE’ sGOSUB 9469:GOTO 459
799 R$="READING' sGOSUBR 859d
719 PRINTsPRINT'S) PRESS THE PLAY KEY ON CASSETTE UNIT."
729 PRINT"S) PRESS THE KEYBOARI-’S ENTER KEY."sGOSUB 969
738 INPUTAH-1,T$:PRINT"READING FILE: "5 TS:INPUT#-1,N
PAD IF NOMR THEN PRINT’ :t4:* TOO MANY FILES ON TAPE" SEND
750 PRINT" READING RECORDS # ";
749 FOR J=1 TO Ns INPUTH-1,09(J5),0¢3),G(J) sPRINT
NEXT:PRINT
779 PRINT N;" DATA RECORDS READ"
789 PRINTsPRINT'?) PRESS THE CASSETTE STOP KEY."
799 PRINT"8) PRESS THE KEYROARD“’S ENTER KEY."
GOSUB 969:RETURN
889 ENT
B59 PRINT:PRINT'1) THE CASSETTE KEYS ARE NOW OPERATIONAL."
849 PRINT'2) POSITION THE CASSETTE TAPE FOR "5R$5"."
8779 PRINT'3) PRESS THE CASSETTE STOP KEY."
889 PRINT'4) HOLD DOWN THE KEYBOARD’S ENTER KEY."
898 PRINTH-1,B$:RS=INKEY$:IF R$=BS THEN 899
999 RETURN
926 FOR Q=1 TO 1969:NEXTsRETURN
9698 R$=INKEY$sIF R$=BS THEN 969
979 RETURN
MILEAGE 47

EASY CHANGES

1. Changing the value of MR in line 130 alters the maximum


number of data records that the program allows. You may
need to make MR smaller if you are running out of memory,
or larger to accomodate additional data. The current value of
twenty is appropriate for a TRS-80 with 4K of memory. For
typical data (such as in the sample run), a 16K TRS-80 will
allow well over 500 data records. To adjust MR, simply change
its value in line 130 from its current value of 20 to whatever
you choose. If you increase the value of MR, you should also
change the argument of the CLEAR in line 120. Make this
argument ten times the value used for MR in line 130.
. Currently, the program will write a maximum of fifteen data
records during the cassette write operation. This number can
be altered by changing the value of MW in line 130 from its
value of fifteen to whatever you choose. Only the most recent
MW records will be written to tape if MW is less than the
number of available records when a cassette write is
issued. If the number of available records is less than MW,
then all the records will be written. The value of MW should
not be larger than the value of MR.
3. If youdonotcare about seeing the dates, they can be removed
easily. This saves a little typing on data entry and also allows
more data records in a given amount of memory. To remove
this feature, delete line 320 entirely and change line 350 to
read
350 N=N+1:PRINT:D$(N)=“- - ---”
MAIN ROUTINES

120 - 140 Dimensioning and variable initialization


150 - 220 Command mode. Displays available subroutines.
300-470 Accepts terminal input.
500 - 590 Writes data to the cassette unit.
600 - 690 Calculates mileage and displays all information.
700 - 790 Reads data from the cassette unit.
800 Terminates execution.
850 - 900 Displays messages for cassette operation.
920 Delay loop.
960 - 970 Tests for operator response.
48 BASIC Programs for the TRS-80

MAIN VARIABLES

MW Maximum number of data records to write.


MR Maximum number of data records in memory.
N Current number of data records in memory.
D$ Array of dates.
D Array of odometer readings.
G Array of gallons per fill-up.
M Array of mileage per fill-up.
R Command mode input.
R$ Temporary string variable, holds operator’s input.
T$ Data file name used in reading or writing with cas-
sette.
B$ Null string.
J Work variable, loop index.
K,L Loop bounds.

SUGGESTED PROJECTS

1. Calculate and print the average MPG over the whole data file.
The total miles driven is D(N)— D(1). The total gallons used
is the sum of G(J) for J=2 to N. This calculation can be done
at the end of the DISPLAY MILEAGE subroutine. Program-
ming should be done between lines 670 and 680.
2. Allow the user the option to write to cassette only the entries
since a certain date. Ask which date and search the D$ array
for it. Then set MW to the appropriate number of records to
write. These changes are to be made between lines 500 and
510 at the beginning of the subroutine to write on cassette.
3. Add a new command option to verify a data file just written
to cassette. It would read the tape and compare it to the
data already in memory.
4. Add an option to do statistical calculations over a given sub-
set of the data. The operator inputs a beginning and ending
date. He is then shown things like average MPG, total miles
driven, total gallons purchased, etc.; all computed only over
the range requested.
5. Write a subroutine to graphically display MPG. A bar graph
might work well.
6. Add a new parameter in each data record—the cost of each
fill-up. Then compute things like the total cost of gasoline,
miles/dollar, etc.
QUEST/EXAM

PURPOSE

If you’ve ever had to analyze the results of a questionnaire,


or grade a multiple-choice examination, you know what a
tedious and time-consuming process it can be. This is particularly
true if you need to accumulate statistics for each question
showing how many people responded with each possible answer.
With this program, you provide the data, and the computer
does the work.

HOW TO USE IT

First, enter the number of questions on the questionnaire or


exam. The maximum is 50. Then enter the number of choices
per question. This is an integer from 2 through 9. Each answer
will be a digit from one to this number or left blank.
Next enter the maximum number of entries (exam papers)
that you are going to analyze. Be sure to enter a number at least
as large as the number of papers that you will be evaluating.
Finally, you are asked if you want to input names for each
entry. This is especially useful when grading exams, to enable
you to re-check later to verify that you entered the proper data
for each student.
At this point, the program asks you for the answer key. If
you are scoring an exam, provide the correct answers. The pro-
gram displays ‘‘guide numbers”’ to help you keep track of which
answers you are providing. If you are analyzing a questionnaire,
you have no answer key, so just press the ENTER key.
50 BASIC Programs for the TRS-80

Now the program asks you to begin providing the answers for
each entry. Again, guide numbers are displayed above the area
where you are to enter the data so you can more easily provide
the proper answer for the proper question number. If no answer
was given for a particular question, leave a blank space. However,
if either the first or the last question was left blank, you will
have to enclose the entire string of answers within quotation
marks. This will cause a small problem in keeping your alignment
straight with the guide numbers, but you’ll get used to it. See
the Sample Run for an example.
If you make a mistake when entering the data, the program
will tell you and ask you to re-enter it. This is most commonly
caused by either failing to enter the correct number of answers
or entering an invalid character instead of an acceptable answer
number. Remember that each answer must be either a blank or
a number from one to the number of choices you allowed per
question.
By the way, you can avoid entering blanks for unanswered
questions. Suppose you have a maximum of 5 possible answers
per question. Simply tell the program there are 6 choices per
question. Then, when a question is unanswered, you can enter a
6 instead of leaving it blank.
If you specified that you wanted names for each entry, the
program asks you for the name after you have entered the
answer key. Do not use commas in the name unless you enclose
the entire name in quotation marks.
If you provided an answer key, the program displays the
number and percentage correct after each entry before going on
to ask for the next one. When you have no more entries, press
the ENTER key instead of entering a string of answers.
At this point, the program displays five options from which
you choose your next action. Here are brief explanations. You
can experiment to verify how they work.
Option one lets you analyze each question, to see how many
people responded with each answer. The percentage of people
who responded with each answer is also shown. In the case of
an exam, the right answer is indicated with the word ““RIGHT.”
Option two allows you to go back and provide more entries.
This allows you to pause after entering part of the data, do
some analysis of what you have entered so far, and then go back
and continue entering data.
QUEST/EXAM 51

Option three lets you review what you have entered, including
the answer key. This permits you to check for duplicate, omitted,
or erroneous entries.
Option four starts the program over at the beginning again,
and option five ends the program.

SAMPLE RUN

The operator provides the required information about the examination


being scored. The program waits for the data from the first examination
paper.
BASIC Programs for the TRS-80

1 2
1234567890 1234567898
PRS tak acl x, ara

ENTRY NUMBER 1
1 2
ere Ms dees5]
2 3322302144421 121341
Pea em ae
enact)
A a Sf
aaa laa
1 2
Wee Mee OCA My
B

The answers are entered for the first student, followed by the student’s
name. The program responds with the number and percentage correct.

Pamel A0e Es 3)
3.

raya
ta 2
1 rd
NRA acy SUK se)
4

AYERAGE
= 82.5 PERCENT

NEXT ACTION:
1 - ANALYZEEACH QUESTION
LMS a3
ei) (2 BUC (33)
Semi. mt 3
Sie e |
1

Later, instead of providing data for a ninth student, the operator presses
the ENTER key, indicating no more entries. The program displays the
overall percentage correct, and displays a ‘‘menu” of choices of actions.
The operator picks number one.
QUEST/EXAM

Pee ala
eee ag Cea)
Pema: Aid
eee ery
1

ANALYSIS FOR QUESTION NO. 1


RESPONSE uly
1
8
?
i
ae )
ssa MAME Ot | 2

The program provides an analysis of the responses for question number


one, then waits for a key to be pressed. Note that seven students an-
swered with number 3, the correct answer.

5 - END PROGRAM

1 ia
RRL tae Oka sab)

33124321443422121341—ANSHER KEY
33223321443421 1213410. 1 J ANDERSON
RS k aC Saati tee)
3321442234242 12°331—-ND. 3 R FORBES
Rea C x0. x aes iG Re. aif
estes rats waa ete) a
Restos sea ee Big Ect
13124221433420121344—NO. 7 K VANFLEET
BSR ROR Sco tk see Me 2)
ose AMMEN 2

Later, the operator asks for option number 3, which lists the data entered
for each of the students.
54 BASIC Programs for the TRS-80

PROGRAM LISTING
199 REM: QUESTIONNAIRE/EXAM ANALYZER
119 REM: COPYRIGHT 1979 BY TOM RUGG AND) PHIL FELDMAN
120 CLEAR 7@9:CLS:DEFINT C-W
139 PRINT" cee EXAM/QUESTIONNAIRE ANALYZER :ettek" sPRINT
149 E$="sekk ERROR. RE-ENTER. dete!’
P$="PRESS A KEY TO CONTINUE"
15@ INPUT"NUMBER OF QUESTIONS":Q
149 IF Q<1 OR Q>5@ THEN 159
174 INPUT"CHOICES PER QUESTION’SC
189 IF C<2 OR C>9 THEN 178 ELSE DIN C(C)
199 INPUT"MAXIMUM NUMBER OF ENTRIES"sN
296 IF N<1 THEN 199 ELSE DIM Q$(N)
219 INPUT"WANT NAMES FOR EACH ENTRY" sR$
226 RS$=LEFT$(R$,1)2IF R$="N" THEN 256
239 IF R$<>"Y" THEN 219
249 TIM NS(N)
256 PRINT:
PRINT'ENTER ANSWER KEY. IF NONE, PRESS “ENTER’."
260 GOSUR 900:A$="" :C$=RIGHTS(STRB(C),1)
319 INPUT A$:IF LEN(A$)=@ THEN A$=""sGOTO 349
326 IF LENCA$)<2Q THEN PRINT E$:GOTO 259
339 T$=A$:GOSUR SS@:IF T#="B" THEN PRINT E$:GOTO 259
349 K=1
350 R=OsPRINT:PRINT"ENTRY NUMBER"SK
366 GOSUB 999
376 INPUT Q$(K) :W=LEN(Q$(K))
389 IF W=@ THEN 599
399 IF WoQ THEN PRINT E$:GOTO 359
490 T$=0$(K):GOSUB 850:IF T$="B" THEN PRINT E$:GOTO 359
416 IF R$="N" THEN 430 ELSE
PRINT'NAME FOR ENTRY NUMBER"SK
420 INPUT N$(K)2IF LEN(NS(K))=@ THEN N$(K)=""
436 IF A$="" THEN 489
449 FOR J=1 TO Q
450 IF MIDS(A$,J,1)=MID$(Q$(K),J,1) THEN R=R+1
469 NEXT
476 TR=TR#RPRINT Ri"CORRECT,",R#190/Q5 "PERCENT"
ABO K=K+1:IF K“=N THEN 359
509 K=K-12IF A$=""" THEN 52d
S10 PRINTPRINT"AVERAGE ="sTR#199/ (GK) s"PERCENT"
529 GOTO 949
538 PRINT:FOR J=1 TO Q
S49 R=G:PRINT:PRINT"ANALYSIS FOR QUESTION NO."J
545 PRINT'RESPONSE", "COUNT", "PERCENT"
QUEST/EXAM 55

JI FOR L=@ TO CrC(L)=@:NEXT:M=9


JOM FOR L=1 TO K:T$=MIN$(Q$(L),J,1)
J/D W=VAL (TS)
389 CCW)=CCW41
499 NEXT L
629 FOR L=1 TO C:PRINT L,C(L),C(L)#190/K,
639 IF A$="" THEN PRINT:GOTO 649
649 T$=RIGHT$(STRS(L),1)
659 IF T$=MID$(A$,J,1) THEN PRINT"RIGHT" ELSE PRINT
649 NEXT :PRINT" BLANK" ,C(B) ,C(G)#190/K
679 PRINT PS
589 IF INKEY$="" THEN 689
499 NEXT J:GOTO 969
789 L=9@:GOSUB 990:PRINT:IF A$="" THEN 729
719 PRINT TAB(2)SA$3"--ANSWER KEY"
729 FOR J=1 TO K
7 3@ PRINT TAB(2)20$(J)5"--NO. "32
74D IF R$="N" THEN PRINTIELSE PRINT NS(J)
PG L=L+1:IF L<1@ THEN 789
749 L=@:PRINT PS
779 IF INKEY$="" THEN 779
789 NEXT:PRINT P$
299 IF INKEY$="" THEN 798 ELSE 9469
B32 FOR J=1 TO LEN(TS)sIF MID$(T$,J,1)=" " THEN 879
849 IF MIDS(T$,J,1)<"1" OR MID$S(T$,J,1)2C$ THEN 889
8/9 NEXT : RETURN
889 T$="B" sRETURN
989 W=Q/1G2IF U1 THEN 929
919 FOR J=1 TO WsPRINT TABCJ10) Js NEXTSPRINT
926 PRINT TAB(2)3
938 FOR J=1 TO Q:T$=STR#(J) PRINT MID$(T$,LEN(T$),1)3
949 NEXT PRINT sRETURN
949 PRINT:PRINT"NEXT ACTION!"
979 PRINT" 1 - ANALYZE EACH QUESTION"
939 PRINT" 2 - ADD MORE ENTRIES"
998 PRINT" 3 - REVIEW DATA ENTERED"
19966 PRINT" 4 - START OVER"
1919 PRINT" 5 - END PROGRAM"
1959 INPUT T$:IF T$<"1" OR T$2"S5" THEN 18779
1949 ON VAL(T$) GOTO 339, 489,789,129,1196
1878 PRINT E$:GOTO 969
1198 END
56 BASIC Programs for the TRS-80

EASY CHANGES

1. This program will run in a4K TRS-80 if a limited amount of


data is entered. The limit is about 20 questions, five choices
per question, 30 entries, and no names for each entry. To
take advantage of a 16K computer, change the 700 in line
120 to be 8000. This way, there’s easily room for 50 ques-
tions, nine choices per question, 100 entries, with names for
each entry.

MAIN ROUTINES

120
- 140 Initializes variables.
150
- 240 Performs initialization dialog. Selects options.
Allocates arrays.
250 - 320 Gets answer key (if any) from operator.
330 Checks legality of answer key.
350 - 400 Gets exam data for Kth entry.
410 - 420 Gets name for Kth entry, if applicable.
430 - 470 Scores Kth exam, if applicable.
500 - 510 Displays average score, if an exam.
530 - 690 Analyzes responses to each question.
700 - 790 Displays data entered.
850 - 880 Subroutine to check legality of input data.
900 - 940 Subroutine to display guide numbers over input
data area.
960- 1100 Displays choices for next action. Gets response
and goes to appropriate routine.

MAIN VARIABLES

E$ Error message
P$ Message about pressing a key to continue.
Q Number of questions (1 - 50).
C Number of choices per question (2 - 9).
C Array for tallying number of people responding
with each choice.
N Maximum number of entries.
Q$ Array of N strings of entries.
R$ Set to N if no names for each entry, or Y other-
wise.
N$ Array of Q names (if R$ is Y).
QUEST/EXAM 57

A$ Answer key string (null if not an exam).


C$ String value of highest legal answer choice.
K Counter of number of exams scored.
R Number of questions answered right (if exam).
W Work variable.
J, L,M Loop variables.
TR Total right for all entries.
T$ Temporary work string variable.

SUGGESTED PROJECTS

1. Add an option to change the answer key after the data for
the exams is entered. This would be useful in case a mistake
was found when reviewing the data.
2. Add an option to allow the operator to re-score each of the
exams after all are entered, in case some were overlooked at
the time of entry.
3. Combine some of the capabilities of the STATS program
with this one.
58 BASIC Programs for the TRS-80
section 2
Educational Programs

INTRODUCTION TO EDUCATION PROGRAMS

Education is one area where computers are certain to have


more and more impact. Though a computer cannot completely
replace a human teacher, the machine does have certain advan-
tages. It is ready anytime you are, allows you to go at your own
pace, handles rote drill effortlessly, and is devoid of any person-
ality conflicts.
With a good software library, the TRS-80 can be a valuable
learning center in the school or at home. Here are six programs
to get you started.
Mathematics is certainly a “‘natural’’ subject for computers.
NUMBERS is designed for pre-school children. While familiar-
izing youngsters with computers, it provides an entertaining
way for them to learn numbers and elementary counting.
ARITHMETIC is aimed at older, grade school students. It pro-
vides drill in various kinds of math problems. The child can
adjust the difficulty factors, allowing the program to be useful
for several years.
By no means is the TRS-80 restricted to mathematical disci-
plines. We include two programs designed to improve your word
skills. VOCAB will help you expand your vocabulary. TACHIST
turns the TRS-80 into a reading clinic, helping you to improve
your reading speed.
Do you have trouble familiarizing yourself with the increas-
ingly prevalent metric system? METRIC is the answer.
Need help learning a certain subject? FLASHCARD allows
you to create your own “‘computer flashcards.”’ Then you can
drill yourself until you get it right.
60 BASIC Programs for the TRS-80
ARITHMETIC

PURPOSE

ARITHMETIC provides mathematics drills for grade school


children. The student can request problems in addition, sub-
traction, or multiplication from the program. Also, he or she
may ask that the problems be easy, medium, or hard. The pro-
gram should be useful to a child over an extended period of
time. He can progress naturally to a harder category of problems
when he begins to regularly perform well at one level. The diffi-
culty and types of problems encompass those normally en-
countered by school children between the ages of six and ten.
The problems are constructed randomly within the con-
straints imposed by the degree of difficulty selected. This gives
the student fresh practice each time the program is used. After
entering answers, he is told whether he was right or wrong. The
correct answers are also displayed.

HOW TO USE IT

To begin, the student must indicate what type of problem he


wishes to do. The program requests an input of 1, 2, or 3 to
indicate addition, subtraction, or multiplication, respectively. It
then asks whether easy, medium, or hard problems are desired.
Again an input of 1, 2, or 3 is required.
Now the screen will clear and four problems of the desired
type will be displayed. The user now begins to enter his answers
to each problem.
62 BASIC Programs for the TRS-80

A question mark is used to prompt the user for each digit of


the answer, one digit at a time. This is done moving right to left,
the way arithmetic problems are naturally solved.
To start each problem, the question mark will appear in the
spot for the rightmost (or units column) digit of the answer.
When the key for a digit from O - 9 is pressed, that digit will
replace the question mark on the screen. The question mark
moves to the immediate left waiting for a digit for the “‘tens”’
column.
Digits are entered in this right to left manner until the com-
plete answer has been input. Then the ENTER key must be
pressed. This will end the answer to the current problem and
move the question mark to begin the answer for the next
question.
If the ENTER key is pressed to begin a problem, an answer
of zero is assumed intended. No problems created by this pro-
gram have answers of more than three digits. If a four-digit
answer is given, the program will accept the answer, but then go
immediately to the next problem. Answers to the problems are
never negative.
The program will display the correct answers to the four
problems on the screen after the student has entered his four
answers. The message “RIGHT!” or “WRONG!” will also be
displayed below each problem.
Then the message “HIT ANY KEY TO CONTINUE” will be
displayed. After the key is pressed, a new set of four problems
of the same type will be presented.
This continues until twenty problems have been worked. The
program then shows what the student’s performance has been.
This is expressed as the number of problems solved correctly
and also as the percentage of problems solved correctly.
The program then asks whether or not the student would like
to do more problems. Simply hit “Y” or “N” to answer this
question.
ARITHMETIC

SAMPLE RUN

ARITHMETIC

HHAT TYPE PROBLEM SHALL HE DO?


1 — ADDITION
2 — SUBTRACTION
3 — MULTIPLICATION
WHICH TYPE <i» 2> OR 3> - 1

WHAT KIND SHALL WE DO?


1 — EASY PROBLEMS
2 — MEDIUM PROBLEMS
3 — HARD PROBLEMS
WHAT KIND <i» 2> OR 3> - 3

The operator chooses to do hard addition problems.

ARITHMETIC

The initial set of 4 problems is presented. With a question mark, the pro-
gram prompts the operator for the answer to the first problem.
64 BASIC Programs for the TRS-80

ARITHMETIC

63 =
+ 17 ae 3
CC

Fs15) 148

ANSWERS

88 es re 54
RIGHT! RIGHT! RIGHT! WRONG!
HIT ANY KEY TO CONTINUE

The operator has entered his or her four answers. The program displays the
correct answers and indicates whether or not each problem was solved
correctly. The program waits for the operator to hit any key in order to
continue with the next set of four problems.

PROGRAM LISTING

199 REM: ARITHMETIC


119 REM: COPYRIGHT 1979 BY PHIL FELDMAN AND TOM RUGG
14@ CLEAR SOs0IM AC4),B(4).0(04) 604)
130 NIl=g
148 NF=29
178 RANIIOM
238 GOSUB 91ISsPRINTSPRINT WHAT TYPE PROBLEM SHALL We tO?"
219 FRINT' 7 - ADUITION"
228 PRINT" 2 - SUBTRACTION"
238 PRINT 3 ~ MULTIPLICATION"
249 PRINT"WHICH TYPE (1, 2. OR 3) 7")
208 RE=INKEYSsT=VAL CRS) STF Tet OR T23 THEN 259
268 PRINT CHR$(24)2"-"O TsGOSUB 1399
2?8 FRINT STRINGS (32.02 "0 FSFRINT WHAT KIND SHALL WE fn?"
290 FRINT' 1 - EASY PROBLEMS"
290 PRINT’ 2 - MEDIUM PROBLEMS"
398 PRINT’ 3 - HARD PROBLEMS"
319 PRINT WHAT KIND (1, 2, OR 3) ?";
320 RE=INKEYS20=VAL CRS) SIF O21 OR O23 THEN 32¢
ARITHMETIC 65

339 PRINT CHR 624) 5°-" 50


3a ON tt GOTO 349,378,490
368 GOSUB 948:sGOSUB 92¢sGOSUBR 939sGOTO 429
3,8 GOSUB 248sGOSUR 939
308 IF T=3 THEN GOSUB 943:GQOSUBR 929:sG0TO 428
398 IF Tx>3 THEN GOSUB 958:GOSUR 928:G0TO 429
4G GOSUB 958sGOSUR 920sGOSUER 93d
4i9 IF T=3 THEN GOSUB 946:GOQOSUB 939
426 IF Tee? THEN 439
439 FOR J=1 TO 4sIF B¢JoeCCJ) THEN REC (J sCCD=BCI)s
R( eK
449 NEXT
45g GOSUER 1900sGOSUB 919
508 FOR J=1 TQ 4:sGOSUB 119@=:NEXT
61¢ FOR K=1 TO 42F=378+K+14:GOSUB 899:G(K=NENEXT
629 PRINT@S32."A N SWE RS")
6.39 FOR J1 TO 4sP bb. ht 62608 SUK 149@:NEXT
649 FOR we] TO 48P=693+te16
656 TF At<2G(J5) THEN FRINT@P, "WROWG!' S sGOTO 679
449 PRINT@P, "RIGHT!" s sNR=NR +I
679 NEXTSFOR K=1 TO 9sR$=INKEYSsNEXT
539 PRINT@B34,°HIT ANY KEY TO CONTINUE":
596 RS=INKEY$: IF R=" THEN S99
2 FOR wt? 70 1a aRb=INKEYS NEXT
718 NIEANT+4s TF NDANE THEN GOSUB 916sG0TO 35d
72 GOSUB 1340
rag FRINTSPRINT"WANT MORE PROBLEMS CY OR N) ?"
749 Rb=TINKEYS:iIF R$="" THEN 7468
PIG IF R#="Y" THEN GOTO 1494
759 IF R="N" THEN CLSOSENT!
778 GOTO 49
BOE N=@sM=1sFOR J=1 TO 1¢@sR$=INKEYSsNEXT
$19 PRINTOP P'S
326 RE=INKEY$eIF RO="" THEN S29
3.33 ASASCCRS) 2TF A=13 ANT M=1 THEN FPRINT@F,'@" 5 SRE TURN
348 IF 4=13 THEN FRINT@F, PCHRS (32); :RETURN
B58 VeVALCRS) SIF Veg AND Aiz4a THEN 829
840 P= 4R+U SPR INT@E , CHRE CPN) 5 SNEN+MEY SM =i eT
8774 TF M1800 THEN RETURN
B38| Pee O2G0TO ale
919 CLOSPRINT CHREC23) STAR(S S"A RIT HME TI C's
RE TUR
oo FOR K=1 TO 4s CK =L+tRNOCH-L+1)-TENe x Pe RE TURN
738 FOR Ke? TO 48 BCK)=.-+RNDCH-L+1)-1T NEXT RETURN
949 H=9 sl=@sRE TURN
66 BASIC Programs for the TRS-80

958 H=992L=9 SRE TURN


9468 He 25sl=1 sRE TURN
1409 ON T GOTO 1910,1929, 1938
1919 FOR J=1 TO 4:00) = BO 400) sNEXTSRETURN
1428 FOR J=1 TO 4:ACD2C0¢.1-BC)) =NEXTSRETURN
1339 FOR J=1 TO 4:ACJ=C(J)#B() sNEXT RETURN
1198 RS=""STF CCJ<1@ THEN BS=CHRS (32)
1119 P2182+J416sPRINTOF ASIC) SSP 24446 SEP RINTOP C$!
1129 RS=""STF BCI<1@ THEN BS=CHRS(32)
1139 P=246+Jt1GrPRINT@F BSTBC.I)S
1149 P= 308+ I416 sPRINTGP STRINGS (4,131)8
1158 RETURN
1399 ON T GOTO 1319,1328, 1338
1319 C$="4" :RETURN
1329 C$="-"sRETURN
1338 CH="X" sRETURN
1499 RS=CHR$(32)sIF ACI2999 THEN PRINT@P,ACI) £2RETURN
1419 IF ACI299 THEN PRINT@P,BSIAC) ¢ RETURN
1429 IF ACJ29 THEN PRINT@P,RSSB$°A(J) sRETURN
1434 FRINT@P, R$ SB$2B$2A (CI) 5 sRETURN
1389 GOSUB 919:PRINT
1519 PRINT'YOU GOT" SNRs "RIGHT"
128 PRINTOUT OF SNPS "PROBLEMS"
1338 P=NR/NP+1 98
1548 PRINTSPRINT' THATS tPs" PERCENT CORRECT” sRETURN

EASY CHANGES

1. The program currently does twenty problems per session.


You can change this number by altering the variable NP in
line 160. For example,
160 NP=12
will cause the program to do only twelve problems per ses-
sion. The value of NP should be kept a positive multiple of
four.
2. Zero is currently allowed as a possible problem operand. If
you do not wish to allow this, change lines 940 and 950 to
read as follows:
940 H=9:L=1:RETURN
950 H=99:L=1:RETURN
ARITHMETIC 67

MAIN ROUTINES

140-170 Initializes constants.


200 - 330 Asks operator for type of problems desired.
350 - 450 Sets A, B, C arrays, clears screen.
600- 770 Mainline routine—displays problems, gets opera-
tor’s answers, displays correct answers and user’s
performance.
800 - 880 Subroutine to get and display user’s answers.
910 Subroutine to clear screen and display title.
920 - 930 Subroutine to set B, C arrays.
940 - 960 Subroutine to set L, H.
1000-1030 Subroutine to calculate A array from B, C arrays.
1100-1150 Subroutine to display problems.
1300-1330 Subroutine to set C$.
1400-1430 Subroutine to display the correct answers.
1500-1540 Subroutine to display operator’s performance.

MAIN VARIABLES

NP Number of problems to do in the session.


ND Number of problems done.
NR Number of correct answers given.
C,B,A Arrays of top operand, bottom operand, and cor-
rect answer to each problem.
N Operator’s answer to current problem.
G Array of operator’s answers.
T Type of problems requested (1=addition, 2=sub-
traction, 3=multiplication).
D Kind of problem requested (1=easy, 2=medium,
3=hard).
H,L Highest, lowest integers to allow as problem oper-
ands.
M Answer column being worked on.
R$ Operator’s input character.
V Value of R$.
A Ascii value of R$.
PN CHR$ argument.
BS Character spacing string.
C$ Operation symbol string.
68 BASIC Programs for the TRS-80

R Work variable.
J,K Loop indices.
P Screen position, also percentage correct.

SUGGESTED PROJECTS

. Keep track of problems missed and repeat them quickly for


additional practice.
. No negative operands or answers are currently allowed. Re-
write the problem generation routines and the operator’s
answer routines to allow the possibility of negative answers.
. The answers are now restricted to three-digit numbers. How-
ever, the program will work fine for four-digit numbers if the
operands of the problems were allowed to be large enough.
Dig into the routines at lines 350 - 450 and 940 - 960. See
how they work and then modify them to allow possible four-
digit answers.
. The operator cannot currently correct any mistakes he makes
while typing in his answers. Modify the program to allow him
to do so.
. Modify the program to allow problems in division.
FLASHCARD

PURPOSE

There are certain things that the human mind is capable of


learning only through repetition. Not many people can remem-
ber the multiplication tables after their first exposure, for
example. The same applies to learning the vocabulary of a foreign
language, the capital cities of the fifty states, or famous dates in
history. The best way to learn them is to simply review them
Over and over until you have them memorized.
A common technique for doing this involves the use of flash-
cards. You write one half of the two related pieces of informa-
tion on one side of a card, and the other half on the other side.
After creating a set of these cards, you can drill yourself on
them over and over until you always remember what’s on the
other side of each card.
But why waste precious natural resources by using cards?
Use your computer instead. This program lets you create
flashcards, drill using them, and save them on cassette tape for
later review.

HOW TO USE IT

The program gives you seven options. The first time you run
it, you'll want to enter new flashcards, so you should reply with
number 1.
To create the cards, the program asks you for each side of
each flashcard, one at a time. First enter side one of the first
card, and so on. As you enter the data, be careful not to use any
70 BASIC Programs for the TRS-80

commas or colons unless the entire expression is enclosed in


quotes. Also, be careful not to enter such a long stream of data
that it goes to the next line on the screen. This can cause
erroneous results.
At any time, you can enter the keyword ““*BACK” to correct
an erroneous entry. This causes the program to back up and ask
you for the previous entry again.
As the program is currently written, you must enter at least
five flashcards, and no more than twelve. We will show you how
to change these limits in the “‘Easy Changes” section.
When you have entered all the flashcards you want, enter
‘““* END” instead of side one of the next card. This puts the pro-
gram back into “‘ccommand”’ mode to ask you what to do next.
If you want to quiz yourself on the cards you just entered,
respond with the number 4.
The program flashes one side of one card on the screen for
you. Both are chosen at random—the side and the card. Your
job is to respond with the other side. If you enter it correctly,
the program says ““RIGHT!” If not, it tells you the correct
response. In either event, the program continues by picking
another side and card at random. This continues until you
respond with ‘“‘**END’’, which tells the program you do not
want to drill any more. It will then tell you how many you got
right out of the number you attempted, as well as the percentage,
and then return to command mode.
During the drill sequence, by the way, the program will not
repeat a card that was used in the previous four questions (i.e.,
one less than the minimum number of cards you can enter).
To save a Set of flashcards on cassette, use option number 3.
The program will tell you to put the cassette into position and
then enter a name for the file. You should give it a good descrip-
tive name in order to remember what kind of flashcards they
are in the future. Be sure to write the name on the cassette, too.
After the flashcards have been copied to the cassette, the pro-
gram will say ““DONE” and return to the command mode.
The other commands are easily understood, so we will just
explain them briefly. A little experimentation will show you
how they work.
Command number 5 lets you verify that the set of flashcards
just saved on tape are okay. You do not have to enter the name
of the file—the same name is used that was used to save the file.
FLASHCARD 71

Command number 2 is used to load a flashcard tape that has


been previously saved. The program asks for the name of the
file, so it can scan the cassette until it finds the one you asked
for. If you don’t care or don’t know the name of the file, you
can load the first file that is found on the cassette by entering
a null string for the name (two consecutive double quote
marks).
Command number 6 allows you to add more flashcards to
those currently in memory.
Command number 7 ends the program.

SAMPLE RUN

FLASHCARD PROGRAM
LIMIT IS 12 CARDS
----OPTIONS----
1 - ENTER NEW FLASHCARDS
2 - LOAD A FLASHCARD TAPE
3 - SAVE CURRENT SET ON TAPE
4 - DRILL ON CURRENT SET
5 - VERIFY FLASHCARDS ON TAPE
6 — ADD TO CURRENT CARDS
7 - END PROGRAM
? 1
SIDE ONE OF CARD NO. 1
2? THE PEN
SIDE TWO
? LA PLUMA

SIDE ONE OF CARD NO. 2


? THE DOOR
SIDE TWO
2? LA PUERTA

SIDE ONE OF CARD NO. 3


? THE SCHOOL
SIDE TWO
? LA ESCUELA

SIDE ONE OF CARD NO. 4


? THE FLOOR
SIDE TWO
2? EL SUELO
72 BASIC Programs for the TRS-80

SIDE ONE OF CARD NO. 5


? THE STORE
SIDE TWO
? LA TIENDRA

SIDE ONE OF CARD NO. 6


? *END

-~---OPTIONS----
- ENTER NEW FLASHCARDS
Fr

- LOAD A FLASHCARD TAPE


Rh

- SAVE CURRENT SET ON TAPE


EN

DRILL ON CURRENT SET


|

- VERIFY FLASHCARDS ON TAPE


“S) Oi

- ADD TO CURRENT CARDS


- END PROGRAM
2 4
TELL ME WHAT'S ON THE
OTHER SIDE OF EACH CARD AS I SHOW IT.

THE DOOR
? LA PUERTA

RIGHT!

LA PLUMA
? THE PEN

RIGHT!

THE FLOOR
? LA ESCUELA

NO, THE CORRECT RESPONSE IS


EL SUELO

THE SCHOOL
? LA ESCUELA

RIGHT!

LA TIENDRA
? SEND
FLASHCARD 73

3 RIGHT OUT OF 4
75 PER CENT

PROGRAM LISTING
188 REM: FLASHCARD
118 REM: COPYRIGHT 1979 BY TOM RUGG AND PHIL FELIMAN
128 CLEAR 24@sNEFINT A-ZsN=-1
138 L=12sM=5
148 TIM FS(h) »BSCL) PMT)
158 RANDOMSCLSOSE$=""4e ERROR cet"
168 We='se+ PRESS “STOP” KEY ON RECORDER st"
178 FRINT’FLASHCARD FROGRAM"
186 PRINTSPRINT"LIMIT IS" SLs "CARUS.":G0TO 24d¢
198 Ket sWe@ eC dsPRINT
248 FSCK 2" "SPRINT STE ONE OF CARTE NO. SREINPUT FECK)
205 TF LENCFS¢K)=@ THEN PRINT E€sGOTOQ 208
219 TF LEFTS(FSCK) 4)="4END" THEN 28d
220 IF LEFTS(FS(K) a) ai ‘"' THEN 2398
222 K=K-1TsIF ket THEN Ks
20 PRINTsPRINT’ BACKING Wp" 6070 296
39 BECK)" "SPRINT SIDE TWO"SINFUT RSCK)
3% IF LENCBS(k))=@ THEN PRINT ESsGOTO 23:
49 IF LEFTS(RS(K),S)="kBACK" THEN 225
JO PRINT
46 Kek+1s0F Kes ‘l. THEN 230
2°60 PRINT THATS THE’ SLs "CARD LIMIT."
239 FRINTskK=K-1 sG0TO 2006
296 IF Ke=M THEN 314
34@ FRINT ES3" MINIMUM TS" SMe CARTS .°sGOTO 2000
319 PRINTSPRINT’ TELL ME WHATS ON THE”
328 PRINT 'OTHER SI0k OF EACH CARH AS I SHOW IT."
3349 FRINT
346 ReRNDCKOSFOR Je@ TO M-2sTF POD=R THEN 349
399 NEXTsJ=RNDC2Q)2IF J=2 THEN 429
496 PRINT FS(R) sC$=BS(R) 2G0TO 439
429 PRINT RS$(R)sC$=F$(R)
438 R=" "Ss INPUT RS
446 IF LEFTS(R$,4)="#ENU" THEN 6960
459 FRINT
460 IF R*=C$ THEN 39d |
4/7@ PRINT'NO, THE CORRECT RESPONSE IS”
460 PRINT C$
499 W=W+1sGOTO S28
348 PRINT' RIGHT!"
74 BASIC Programs for the TRS-80

wld CaC+4
woe FOR J=1 TO M-2rF(J-1)=F (1) sNEXT EF OM-2)2REPRINT
wag GOTO 349
490 GOSUB 1586:GOTO 2009
708 IF Ket THEN 188
718 GOSUB 1499
P29 PRINT'PRESS “RECORT” AND “PLAY” BUTTONS, THEN"
736 PRINT'PROVIDE NAME FOR FILE WHEN READY." sINPUT NS
23S PRINT'WRITING "INS
JAG PRINTHN NSZPRINTHN, STRE(K)SFOR Jet TO K
Pu PRINTHN FS (1) RSC)
769 PRINT JtsNEXT
779 PRINTHN, "END"
799 PRINTIF RINT" DONE”
889 PRINT Wt
B18 GOTO 2009
996 E=@:GOSUB 1499
9198 PRINT'PRESS “PLAY”. THEN PRESS ANY KEY."
929 RS=INKEY$:IF R$=""" THEN 926
930 PRINT'SEARCHING FOR "INS
93 INFUTHN RSIIF R&=N$ THEN 959
949 PRINT'FOUND "AR$:
IF R$="#ENIU' THEN 939 ELSE GOTO 93%
wd PRINTSPRINTFQUND "tN: INFUTHN, RS
949 IF VALCRS)<>K THEN E=1t:PRINT E$2" RAD COUNT":
GOTO 1929
976 FOR J=1 TO KeINFUTHN,RS,74
PPS PRINT R&sPRINT 1%
989 TF R&<eF$(J) OR TH2B341) THEN E=1
999 NEXT
1919 PRINTsFRINT DONE"
1928 IF E=9 THEN PRINT"O.K."sPRINT W$:GOTO 299d
193d PRINT NO GOOD" SPRINT WE:GOTO 29989
1159 INFUT"NAME OF TAPE FILE" INS
114d GOSUB 1499:FRINT’PRESS “PLAY”,"
11798 PRINT’ THEN PRESS ANY KEY."
1188 RS=INKEYSsIF R#="" THEN 11382
1185 PRINT’ SEARCHING FOR "INS
1199 INFUTHN ROSTF RSLENS THEN PRINT RS$:GOTO 1199
1299 PRINTSFRINT FOUND "SNSEFRINT
1216 INPUTHN, RS SK=VAL CRS) SIF Kd THEN 1434
1229 IF Ke=| THEN 7250 ELSE PRINT ES
1238 PRINT'FILE HAS’ SKS "CARIIS. FROGRAM LIMITED TO" SL
1246 GOTO 29699
1259 FOR J=1 TO K
FLASHCARD 75

1260 INFUTHN FC) BSC)


1279 PRINT F$(J) SPRINT BS6))
1289 NEXT
1299 INPUTHN ROS TF RSCe#ENI THEN 1939
1300 PRINT SPRINT LOADED 2K: "CARIS."
1.314 PRINT W6sGOTO 2009
1380 FRINTSIF C+W=@ THEN RETURN
1519 PRINT CIURIGHT QUT OF" 30+
1528 PRINT C#190/(C+W) °F ERCENT"
12.38 PRINT :RETURN
1699 PRINT
1619 PRINT’HOLD A KEY DOWN AFTER CASSETTE IS
IN POSITION.”
1629 PRINT
16.39 LF INKEY$<2"" THEN RETURN
1649 PRINTHN."X":GQTO 1436
1889 PRINTIPRINT E%:" NO CARDS YET."
181d GOTO 2606
2908 R=" SPRINT SPRINT! -~--OPTIONS----"
2916 FRINT" 1 - ENTER NEW FLASHCARDS"
2928 PRINT’ 2 ~ LOAD A FLASHCARD TAPE"
i

28.38 PRINT 3 - SAVE CURRENT SET ON TAFE”


2B4D PRINT" 4 — DRILL ON CURRENT SET"
Re 1) PRINT” % ~ VERTFY FLASHCARIIS ON TAFE"
2959 PRINT 4 — ADD TO CURRENT CARTS"
2979 PRINT" 7 — END PROGRAM"
2089 INPUT R¢:TF VALCRAD<1 OR VALCRS)? THEN 2144
2996 ON VAL(R$) GOTO 199, 1159,789.298, 998,249,214
2199 PRINTSFRINT E#:GOTO 2008
2146 ENT
EASY CHANGES

1. Change the limits of the number of flashcards that can be


entered by altering line 130. L is the upper limit and M is the
minimum. The current upper limit of twelve will fit in a
TRS-80 with 4K of memory if each side of each flashcard
averages no more than about twelve to fifteen characters
in length. In a 16K TRS-80, you can make L as large as about
four hundred for flashcards this size. You will also need to
change line 120 to CLEAR 8000 or so (instead of 240). Do
not make M much larger than about ten or so, or you will
slow down the program and use more memory than you
might want.
BASIC Programs for the TRS-80

. If you want to use some keywords other than “*END” and


‘** BACK’’, substitute whatever you like in lines 210, 220,
240, and 440. Be sure you use expressions that are the same
length as these two, however, If not, you will also need to
change the last number just before each occurrence of the
expression to correspond with the length.
. To cause the program to always display side one of the flash-
cards (and ask you to respond with side two), change this line:
390 NEXT
To cause it to always display side two, change it this way:
390 NEXT:GOTO 420
4. To eliminate the “echoing” on the screen of a tape file being
verified, remove line 975. To do the same for a tape being
loaded, remove line 1270.

MAIN ROUTINES

130-180 Initializes variables. Creates arrays. Displays title


and options.
190 - 280 Accepts flashcards entered by operator.
290 - 600 Drills operator on flashcards in memory.
700 - 810 Saves flashcards on cassette file.
900-1030 Verifies that flashcards on cassette tape are the
same as those in memory.
1150-1310 Loads flashcards from cassette file into memory.
1500-1530 Subroutine to display number right and attempted
during drill.
1600-1640 Subroutine to free cassette recorder until a key is
held down.
1800-1810 Displays error message if operator tries to save
flashcards on cassette before any are entered.
2000 - 2140 Displays options and analyzes response. Branches
to appropriate routine.

MAIN VARIABLES

N Cassette number for cassette files.


L Upper limit of number of flashcards that can be
entered.
M Minimum number of flashcards that can be en-
tered.
FLASHCARD 77

Subscript of random flashcard chosen during drill.


Number of flashcards entered.
<n

Number of wrong responses.


Number of correct responses.
wtTwaemda

Array containing front side of flashcards (side 1).


AA

Array containing back side of flashcards (side 2).


Array containing subscripts of M-—I1_ previous
flashcards during drill.
Loop and subscript variable.
Aas

The correct response during drill.


nA

Response from operator. Also temporary string


variable.
Name of cassette file.
1 Zz
a

Error flag—set to 1 if error occurs on cassette.


TS Temporary string variable.

SUGGESTED PROJECTS

1. Modify the program for use in a classroom environment. You


might want to allow only command 2 to be used (to load a
cassette tape), and then immediately go into “‘drill’’ mode for
some fixed number of questions (maybe 20 or 50).
78 BASIC Programs for the TRS-80
METRIC

PURPOSE

In case you don’t realize it, we live in a metric world. The


United States is one of the last holdouts, but that is changing
rapidly. So if you're still inching along or watching those
pounds, it’s time to convert.
METRIC is an instructional program designed to familiarize
you with the metric system. It operates in a quiz format; the
program randomly forms questions from its data resources. You
are then asked to compare two quantities—one in our old
English units and one in the corresponding metric units. When
you are wrong, the exact conversion and the rule governing it
are given.
The two quantities to compare are usually within 50% of
each other. Thus, you are constantly comparing an “‘English”’
quantity and a metric one which are in the same ball park. This
has the effect of providing you some insight by sheer familiarity
with the questions.

HOW TO USE IT

The first thing the program does is ask you how many
questions you would like to do for the session. Any value of
one or higher is acceptable.
The sample run shows how each question is formulated. A
quantity in English units is compared with one in metric units.
Fither one may appear first in the question. Each quantity will
have an integral value. The relating word (“longer,” “hotter,”
80 BASIC Programs for the TRS-80

“heavier,” etc.) indicates what type of quantities are being com-


pared.
There are three possible replies to each question. Pressing Y
or N means that you think the answer is yes or no, respectively.
Pressing any other key indicates that you have no idea as to the
correct answer.
If you answer the question correctly, you will be duly con-
gratulated and the program will proceed to the next question.
A wrong answer or a response of “no idea,’ however, will
generate some diagnostic information. The first value used in
the question will be shown converted to its exact equivalent in
the corresponding units. Also, the rule governing the situation
will be displayed. At the end of any question, the program will
request that you hit any key to proceed to the next question.
The program will continue generating the requested number
of questions. Before ending, it will show you how many correct
answers you gave and your percentage correct.

SAMPLE RUN

A METRIC QUIZ
HOW MANY QUESTIONS SHALL WE DO? 3
QUESTION 1 OF 3
IS 48 MILES LONGER THAN
92 KILOMETERS ? C''N' key pressed)
YOU SAY 'NO' AND YOU'RE RIGHT - VERY GOOD!

aaee HIT ANY KEY TO CONTINUE *##%


paras
aud

QUESTION 2 OF 3
IS 73 DEGREES FAHRENHEIT HOTTER THAN
22 DEGREES CENTIGRADE ? C'"Y'" key pressed)
YOU SAY 'YES' AND YOU'RE RIGHT - VERY GOOD!
#4XXX HIT ANY KEY TO CONTINUE *#%
QUESTION 3 OF 3
IS 79 KILOGRAMS HEAVIER THAN
152 POUNDS ? C'N' key pressed)
YOU SAY 'NO' BUT YOU'RE WRONG
METRIC 81

79 KILOGRAMS EQUALS
174.166 POUNDS
---- THE RULE IS ----
1 KILOGRAM EQUALS
2.28463 POUNDS
ae HIT ANY KEY TO CONTINUE “8%
YOU GOT 2 RIGHT OUT OF 3 QUESTIONS
PERCENTAGE CORRECT = 66.6667

PROGRAM LISTING

186 REM: METRIC


119 REMs COPYRIGHT 1979 BY PHIL FELDMAN AND TOM RUGG
138 CLEAR SOs R$=CHR$ C32) sRANDOMSDEF INT JN
1468 DIM ES8(38) ,MS$ (30) R038) 0039) EPSC30) MPSS)
“88 GOSUB 4990:GOSUB 454
219 INPUT'HOW MANY QUESTIONS SHALL WE DO" UNG
228 TF NQ<1 THEN 219
238 FOR Jet TO NQsGOSUR 443:G0SUGR 998sNEXTSGOSUBR 45¢
248 PRINT’ YOU GOT" SNARE "RIGHT OUT OF SNQS "QUESTIONS"
208 PRINT sP=1084NR/NQSPRINT"PERCENTAGE CORRECT ="3F
243 END
493 RESTORE :NIl=@
419 NO=NI+1
420 REAM ES# (ND) .MSS (NT) ,RBONID .CONTD JEP SOND) MP SOND)
436 IF ES#(NID<2"XXX" THEN 4198 ELSE NO=NII-1 RETURN
459 CLSSPRINT,"A METRIC QUIZ" SPRINT sRETURN
608 N=RNITCONDD sFedeIF RNC) 28.5 THEN F=1
618 VI=RNN(98)412U3=V14C(N) SIF Fel THEN VS=V1/C0(N)
628 TF N=1 THEN V3=(Y1-32)/1.83
IF F=1 THEN V3=(V141,8)+4+32
639 VO=INT (VS (O. S+tRNN(8) 40.5) 2T=O2TF Y22N3 THEN T=
649 GOSUB 45¢:PRINT" QUESTION 32 "OF" SNQsPRINT
658 IF F=@ THEN .
PRINT’ IS" sV1SEPS(N) SRS eRS(N) 5" THAN" ELSE 679
569 PRINT BS SBS SV2SMPS(N) 5" ?"sGOTO 4699
678 PRINT’ IS" SV1 SMPS(N) SBSSRECN) 5" THAN"
580 PRINT BRSSBS2V23EPS(ND 5" P"
698 Qh=""SQ$S=INKEYSs IF Q$="" THEN 699
798 IF Q$="Y" THEN PRINTSPRINT"YQU SAY “YES""esk=1:
GOTO 739d
82 BASIC Programs for the TRS-80

719 IF Q$="N" THEN PRINTSFRINT' YOU SAY “NO“"SsR=9:


GOTO 739
P28 PRINTSPRINT' YOU HAVE NO IDEA" sR=2
738 X=T-Rs iF R=2 THEN GOSUR 806:60TO 743
74D IF XA0¢ THEN PRINT" BUT YOUCRE WRONG" sGOSUB 886:
GOTO 749
78 PRINT AND YOU“RE RIGHT - VERY GOOD!" sNR=NR+1
768 RETURN
889 FRINT STRING$(35,"-")
8168 IF F=@ THEN PRINT VISEPS(ND5" EQUALS":
FRINT V35MP3(N)
829 IF F=1 THEN FRINT VISMFS(ND5" EQUALS":
FRINT V3SEPS(N)
838 PRINT" ----------- THE RULE IS ----------- "
844 IF F=1 THEN IF N= THEN 848 ELSE 889 ELSE IF
N=1 THEN 879
B59 PRINT’ DEG.C = (QEG.F ~ 323/1.8" RETURN
84d PRINT’ DEG.F = (MEG.C # 1,8) + 32" sRETURN
87'S PRINT’ 1 "SESS(ND 3" EQUALS" SPRINT CON) SMFS(N)s
RETURN
889 Qe INTCTES/CCND)/1.E3
399 PRINT! 7 "SMSS(N) 5" EQUALS" SPRINT QSEFS(N) SRE TURN
989 PRINTSPRINT Acece HIT ANY KEY TO CONTINUE se4c8!'
919 Q$=""sQ$=(INKEY$eIF QH="" THEN 919
920 RETURN
1982 DATA DEGREE FAHRENHEIT, UEGREE CENTIGRAIE,
HOTTER, 9.5
1419 ATA WEGREES FAHRENHEIT, (EGREES CENTIGRADE
1820 ATA MILE PER HOUR,KILOMETER FER HOUR,FASTER,
1.69935
19398 VATA MILES PER HOUR.KILOMETERS PER HOUR
1949 VATA FOOT, METER,LONGER, 3.3948
1959 TATA FEET, METERS
194698 DATA MILE, KILOMETER, LONGER, 1.68935
19779 DATA MILES,KILOMETERS
1986 CATA INCH,CENTIMETER,LONGER, 2.54
1899 DATA INCHES, CENTIMETERS
1199 DATA GALLON,LITRE, MORE .3.78533
11198 ATA GALLONS LITRES
11296 VATA POUNT, KILOGRAM HEAVIER 9.45359
1139 LATA POUNLIS, KILOGRAMS
1999 IWATA XXX,XXX,XXX,G.XXX XXX
METRIC 83

EASY CHANGES

l. To have the program always ask a fixed number of questions,


change line 210 to set NQ to the desired value. For example:
210 NQ=10
will cause the program to do 10 questions.
. There are currently seven conversions built into the program:
N Type English Unit Metric Unit
l temperature degrees F. degrees C.
2 speed miles/hour kilometers/hour
3 length feet meters
4 length miles kilometers
5 length inches centimeters
6 volume gallons litres
7 weight pounds kilograms
If you wish to be quizzed on only one type of question, set
N to this value by adding line 605. Thus,
605 N=4
will cause the program to only produce questions comparing
miles and kilometers. To add additional data to the program,
see the first “Suggested Project.”
. You can easily have the questions posed in one “direction”
only. To go only from English to metric units add
607 F=0
while to go from metric to English units use
607 F=1
. You might want the converted value and governing rule to be
displayed even when the correct answer is given. This is ac-
complished by adding line 755 as follows:
755 GOSUB 800

MAIN ROUTINES

150- 160 Dimensions and initializes variables.


200 - 260 Mainline routine, drives other routines.
84 BASIC Programs for the TRS-80

400 - 430 Reads and initializes data.


450 Displays header.
600 - 760 Forms and asks questions. Processes user’s reply.
800 - 890 Displays exact conversion and governing rule.
900 - 920 Waits for user to hit any key.
1000 - 1999 Data statements.

MAIN VARIABLES

ND Number of conversions in the data.


ES$,EP$ String arrays of English units’ names (singular,
plural).
MS$,MP$ String arrays of metric units’ names (singular,
plural).
String array of the relation descriptors.
Array of the conversion factors.
Work variable.
String constant of one blank character.
Current question number.
Number of questions answered right.
Percentage answered right.
Number of questions in session.
Index number of current question in the data list.
Flag on question “direction” (O=English to metric;
l1=metric to English).
Numeric values on left, right sides of the question.
The correct value of the right hand side.
Flag on the question’s correct answer (1=true;
O=false).
User reply string.
User reply flag (Q=no; 1=yes; 2=no idea).
User’s result ( O if correct answer was given).

SUGGESTED PROJECTS

1. Each built-in conversion requires six elements of data in this


order:
Element Data Description
| English unit (singular)
2 Metric unit (singular)
3 Relation descriptor (e.g., “hotter,” “‘faster,”’ etc.)
METRIC 85

4 Conversion factor (from English to metric)


5 English unit (plural)
6 Metric unit (plural)
Each of these elements, except the fourth, is a string. The
data statements in the listing should make clear how the
information is to be provided. You can add new data to the
program with appropriate data statements in this format.
New data should be added after the current data, i.e. just
before line 1999. Line 1999 is a special data statement to
trigger the end of all data to the program. The program is
dimensioned up to thirty entries while only seven are currently
used. (Note: this format allows only conversions where one
unit is a direct multiple of the other. Temperature, which
does not fit this rule, is handled as a special case throughout
the program.)
2. Convert the program to handle units conversion questions of
any type.
3. Keep track of the questions asked and which ones were
missed. Then do not ask the same questions too soon if they
have been answered correctly. However, do re-ask those ques-
tions missed for additional practice.
86 BASIC Programs for the TRS-80
NUMBERS

PURPOSE

This is an educational program for pre-school children. After


a few weeks of watching Sesame Street on television, most three
and four year old children will learn how to count from one to
ten. The NUMBERS program allows these children to practice
their numbers and have fun at the same time.

HOW TO USE IT

We know a child who learned how to type CLOAD and RUN


to get this program started before she turned three, but you'll
probably have to help your child with this for a while. The pro-
gram asks the question, “WHAT NUMBER COMES AFTER n?”’,
where n is a number from one to nine. Even if the child can’t
read yet, he or she will soon learn to look for the number at
the end of the line. The child should respond with the appro-
priate number, and then press the ENTER key.
If the answer is correct, the program displays the message
“THAT’S RIGHT!’’, pauses for a couple of seconds, and then
clears the screen and displays three geometric shapes. In the
upper left of the screen a square is drawn. In the lower center, a
triangle is drawn. Then as asterisk (or a snowflake, perhaps?) is
drawn in the upper right portion of the screen. After about a
five second delay, the program clears the screen and asks
another question. The same number is never asked twice in a
row. The size of the three figures is chosen at random each time.
88 BASIC Programs for the TRS-80

If the child provides the wrong answer, a message indicates


the error and the same question is asked again.
The program keeps on going until you hit the BREAK key.
Remember that most children have a pretty short attention
span, so please do not force your child to continue after his or
her interest diminishes. Keep each session short and fun. This
way, it will always be a treat to “‘play” with the computer.

SAMPLE RUN

bE ao)

ea
28

ai ee oto oe

The program asks what number comes after 7, and waits for a response.
The operator says ‘’8’’, and the program acknowledges that the answer is
correct.
NUMBERS 89

Because of the correct response, the program draws three geometric figures.

PROGRAM LISTING

189 REM: NUMBERS


116 REM: COPYRIGHT 1979 BY TOM RUGG AND PHIL FELDMAN
129 CLEAR S@:UEFINT A-Z
139 M=9sE=16:TS=29
148 RANTOM:CLS
159 PRINT CHR$(23)
168 PRINT TAB(1@) 5 "NUMBERS"
179 R=RNDOCM) SIF R=P THEN 1793
189 PRINT
199 PRINT"WHAT NUMBER COMES AFTER"SR
208 INPUT R$
219 PRINT
228 IF VAL(R$)=R+1 THEN 349
239 FRINT"NO, THAT“’S NOT IT. TRY AGAIN."
248 GOTO 18¢
3988 PRINT" THAT“’S RIGHT!"
318 FOR X=1 TO 19@0@:NEXT
3298 P=RsCLS
339 E=RNI(195)+5
499 Y=1:FOR X=1 TO 26 sSET(X,Y) sNEXT
90 BASIC Programs for the TRS-80

419 X=24E:FOR Y=1 TO EsSET(X,Y) sSET(X+1,Y) sNEXT


429 Y=E3FOR X=24#E TO 1 STEP -1sSET(X,Y) sNEXT
439 X=1:FOR Y=E TO 1 STEP -1SSET(X,Y)sSET(X4+1,¥) sNEXT
45@ FOR J=1 TOE
46D Y=TS+JEX=TS+Y :SET(X, Y) sNEXT
479 FOR J=1 TOE
48G Y=TS+J:X=TS+TS—J+2:SET (X,Y) sNEXT
49B Y=TS+E+1:FOR X=TS+TS-E+1 TO TS+TS+E+1
569 SET(X,Y) sNEXT
528 A=90:B=192IF E217 THEN E=17
539 FOR J=1 TOE
549 X=A+J+J2Y=B+J:SET(X~1, Y) sSET(X,Y)
55@ Y=B-J:SET(X,Y) sSET(X-1,Y)
560 Y=B:SET(X,Y)sSET(X-1,Y)
578 XsAsSET(X,Y) sSET(X-1,Y)
589 Y=B+J:SET(X,Y) :SET(X-1,Y)
599 Y=B-J:SET(X-1,Y) :SET(X,Y)
it

608 X=A-J-J:SET(X-1,Y) sSET(X,Y)


KX
< on D>

618 SET (X-1,Y) :SET(X,Y)


ud
—t + «as

629 JsSET(X-1,Y) 2SET(X,Y)


ax
mit

639
899 FOR J=1 TO 260@:NEXT
819 CLS:PRINT CHR$(23)
829 GOTO 179

EASY CHANGES

1. Change the range of numbers that the program asks by altering


the value of M in line 120. For a beginner, use a value of 3
for M instead of 9. Later, increase the value of M to 5, and
then 8.
2. Alter the delay after ““THAT’S RIGHT!”’ is displayed by al-
tering the value of 1000 in statement 310. Double it to double
the time delay, etc. The same can be done with the 2000 in
line 800 to alter the delay after the figures are drawn.
3. To avoid randomness in the size of the figures that are drawn,
replace line 330 with
330 E=15
Instead of 15, you can use any integer from 3 to 26.
NUMBERS 91

4. To slowly increase the size of the figures from small to large


as correct answers are given (and the reverse for incorrect
answers), do the following:
a. Replace the 10 in line 130 with a 3.
b. Insert this line
225 E=E—-3:IF E<3 THEN E=3
c. Replace line 330 with the following:
330 E=E+3: IF E > 20 THEN E=20

MAIN ROUTINES

120- 160 Initializes variables. Clears screen.


170 Picks random integer from 1 to M.
180 - 240 Asks question. Gets answer. Determines if right or
wrong.
310 Delays about 1% seconds.
320 - 430 Draws a square.
450- 500 Draws a triangle.
520- 630 Draws an asterisk.
800 Delays about 5 seconds.
810- 820 Clears screen. Goes back to ask next question.

MAIN VARIABLES

M Maximum number that will be asked.


E Edge length of geometric figures.
R Random integer in range from 1 to M.
P Previous number that was asked.
R$ Reply given by operator.
X,Y Coordinates in CRT display.
TS Triangle’s starting location (top).
A,B X,Y coordinate values.
J Subscript variable.
92 BASIC Programs for the TRS-80

SUGGESTED PROJECTS

1. Modify the program to ask the next letter of the alphabet.


Use the ASC and CHR$ functions in picking a random letter
from A to Y, and to check whether the response is correct or
not.
2. Ask each number from | to M once (in a random sequence).
At the end of the sequence, repeat those that were missed.
3. Add different shapes to the graphics display that is done after
a correct answer. Try an octagon, a diamond, and a rectangle.
Or, combine this program with one of the graphics display
programs.
TACHIST

PURPOSE

This program turns your computer into a_ tachistoscope


(tah-KISS-tah-scope). A tachistoscope is used in reading classes
to improve reading habits and, as a result, improve reading
speed. The program displays a word or phrase on the screen for
a fraction of a second, then asks you what it was. With a little
practice, you will find that you can read phrases that are dis-
played for shorter and shorter time periods.

HOW TO USE IT

The program starts off by displaying a brief introduction and


waiting for you to press any key (except the BREAK key or shift
keys, of course). After you press a key, the screen is blanked
out except for two horizontal dash lines in the upper left-hand
corner. After two and a half seconds, a phrase is flashed on the
screen between the two lines. Then the screen is blanked again,
and you are asked what the phrase was.
If you respond correctly, the next phrase is displayed for a
shorter time period (half as long). If you respond incorrectly,
the program shows you the correct phrase, and the next phrase
is displayed for a longer period of time (twice as long).
The fastest the computer can display a phrase and erase it is
about .02 seconds (one-fiftieth). See if you can reach the top
speed and still continue to read the phrases correctly.
94 BASIC Programs for the TRS-80

A great deal of research has been done to determine how


people read and what they should do to read both faster and
with better comprehension. We will not try to explain it all (see
the bibliography), but a couple of things are worth mentioning.
To read fast, you should not read one word at a time. Instead,
you should learn to quickly read an entire phrase at once. By
looking at a point in the center of the phrase (and slightly above
it), your eyes can see the whole phrase without the necessity of
scanning it from left to right, word by word. Because the
tachistoscope flashes an entire phrase on the screen at once, it
forces you tolook at a single point and absorb the whole phrase,
rather than scanning left to right, word by word.
If you can incorporate this technique into your reading and
increase the width of the phrases you absorb, your reading
speed can increase dramatically.

SAMPLE RUN

Pee MC OLB aM

THIS PROGRAM IS DESIGNED TO IMPROVE YOUR


READING SPEED.

IM Re C eC ga 2
Ue aaa 2 oe

She Meese eee


TF YOU HERE RIGHT.

PRESS ANY KEY WHEN YOURE READY,

The program displays an introduction, then waits.


TACHIST

The program clears the screen and displays two parallel lines in the upper
left corner of the screen for a couple of seconds.

The program flashes a short phrase (chosen at random) between the two
lines for a fraction of a second, then clears the screen.
96 BASIC Programs for the TRS-80

Te oe Oe
? THE BABY CRIED
Meal

THE NEXT ONE WILL BE DISPLAYED FOR HALF AS LONG.

SSE Mm
DR ae

The program asks what the phrase was. The operator responds correctly.
The program acknowledges the correct response, and indicates that the
next phrase will be shown for half as long.

PROGRAM LISTING

199 REM: TACHISTOSCOPE


119 REM: COPYRIGHT 19779 BY TOM RUGG ANI PHIL FELIIMAN
129 CLEAR S@sDEFINT A-Z
138 T=128
148 L=59
159 DIM T$(L)
168 c=9
178 READ R$
189 IF R#="XXX" THEN 259
199 C=C+1
209 IF CL THEN PRINT" TOO MANY DATA STATEMENTS” SEND
219 TS$(C)=R$
229 GOTO 176
258 RANDOM
268 CLS
278 PRINT #4«:« TACHISTOSCOPE stt:t:k"
288 PRINT
299 PRINT" THIS PROGRAM IS DESIGNED TO IMFROVE YOUR"
389 PRINT"READING SPEED."
TACHIST 97

319 PRINT
329 PRINT'I’LL BRIEFLY DISPLAY A SHORT PHRASE,"
338 PRINT'AND YOU TRY TO READ IT."
549 PRINT
559 PRINT" TYPE WHAT YOU SEE, AND I’LL TELL YoU"
349 PRINT'IF YOU WERE RIGHT."
379 PRINT
419 PRINT"PRESS ANY KEY WHEN YOU’RE READY."
429 RS=INKEY$:IF R$="" THEN 420
439 R=RND(C)
449 IF R=P1 OR R=P2 OR R=P3 THEN 439
459 IF R=P4 OR R=P5 THEN 439
Abd GOSUB 849:FOR K=1 TO 15@@:NEXT
479 PRINT@64,7$(R)3
A489 FOR J=1 TO TsNEXT
JOO CLS:FOR K=1 TO 5@O:NEXT
y19 PRINT :PRINT PRINT :PRINT
wow PRINT'WHAT WAS IT?"
358 INPUT R$
WO IF R$<>T$(R) THEN 799
369 PRINT" THAT’S RIGHT!"
JY T=1/2
39D R$="FOR HALF AS LONG.”
699 P1=P2:P2=P3:P3=P4:P4=P52P5=R
4619 PRINT
6298 IF T<=4 THEN T=4:R¢="AT MAXIMUM SPEED."
639 PRINT" THE NEXT ONE WILL BE DISPLAYED "sR$
549 PRINT:GOTO 419
789 PRINT'NO, THAT’S NOT IT. IT WAS"
718 PRINT'“":T#(R) "7"
729 T=T#2
738 IF 1>169@ THEN T=160G:R%="AT THE SAME SPEED.":
GOTO 639
74D R$="FOR TWICE AS LONG."sGOTO 699
849 CLS:PRINT STRING$(12,"~")
8598 PRINT
849 PRINT STRING$(12,"-")
879 RETURN
919 DATA"AT THE TIME"
929 DATA" THE BROWN COW"
939 DATA"LOOK AT THAT"
949 DATA" IN THE HOUSE"
93598 TATA" THIS IS MINE”
949 DATA"SHE SAID SO”
979 DATA" THE BABY CRIED"
98 BASIC Programs for the TRS-80

989 DATA"TO THE STORE"


999 DATA"REABING IS FUN"
1986 DATA"HE GOES FAST”
1819 DATA"IN ALL THINGS"
1929 DATA"GREEN GRASS"
1939 DATA"TWO BIRDS FLY"
1949 DATA"LATE LAST NIGHT"
1958 DATA" THEY ARE HOME"
1948 DATA"ON THE PHONE”
1979 DATA" THROUGH A DOOR"
1989 DATA"WE CAN TRY"
1998 DATA"MY FOOT HURTS"
1199 DATA"HAPPY NEW YEAR"
9999 DATA XXX

EASY CHANGES

1. Change the phrases that are displayed by changing the DATA


statements that start at line 910. Add more and/or replace
those shown with your own phrases or words. Line 140 must
specify a number that is at least as large as the number of
DATA statements. So, to allow for up to 100 DATA state-
ments, change line 140 to say
140 L=100
Be sure to enter your DATA statements in the same form
shown in the program listing. To begin with, you may want
to start off with shorter phrases or single words. Later, try
longer phrases. Do not alter line 9999, which has to be the last
DATA statement. In a 4K TRS-80, you have room for about
60 phrases of the approximate size shown in the program
listing. In a 16K TRS-80, you can have several hundred of
them. Be sure to have at least 6.
. To change the length of time the first phrase is displayed,
change the value of T in line 120. Double it to double the
length of time, etc. Don’t make it less than four.
. To cause all phrases to be displayed for the same length of
time, remove lines 570 and 720, and insert these lines:
S95 R$=“AT THE SAME SPEED”
725 R$=“AT THE SAME SPEED”:GOTO 600
_ If you want to change the waiting period before the phrase is
flashed on the screen, change the 1500 in line 460. To make
TACHIST 99

the delay five seconds, change it to 3000. To make it one


second, change it to 600.
. To put the program into a sort of flashcard mode, in which
the phrases are flashed, but no replies are necessary, insert
these three lines:
515 GOTO 710
595 R$=“AT THE SAME SPEED”
715 GOTO 590
This will cause each phrase to be flashed (all for the same
length of time), and then displayed again so you can verify
what it was.

MAIN ROUTINES

120-150 Initializes variables


160 - 220 Reads DATA statements into T$ array.
260 - 370 Displays introduction.
410-420 Waits for operator to press a key.
430-450 Picks random phrase from T$ array. Ensures no
duplication from previous five phrases.
460 Clears screen and displays horizontal lines.
470 - 500 Displays phrase for appropriate length of time.
510 - 530 Asks what the phrase was.
550 Determines if typed phrase matches the phrase
displayed.
560 - 640 Shortens time for next phrase if reply was correct.
Saves subscript to avoid repetition. Goes back to
wait for key to be pressed.
700 - 740 Shows what phrase was. Lengthens time for next
phrase. Ensures that time period does not exceed
maximum.
840 - 870 Subroutine to display horizontal dash lines.
910-9999 DATA statements with phrases to be displayed.

MAIN VARIABLES

T Time that phrase will be displayed.


J Loop variable.
L Limit of number of phrases.
TS$ Array of phrases (read into from DATA state-
ments).
100 BASIC Programs for the TRS-80

C Count of number of phrases actually read.


R$ Temporary string variable. Also, reply of operator.
R Work variable. Also, subscript of phrase to be dis-
played.
P1,P2, Subscripts of the five previous phrases.
P3,P4,P5
K Temporary work variable.

SUGGESTED PROJECTS

1. Instead of picking phrases at random, go through the list


once sequentially. Change line 250 to set R to zero, and line
430 to add one to R, then check if R is greater than C-.
2. Instead of only verifying that the current phrase does not
duplicate any of the previous five phrases, modify the pro-
gram to avoid duplication of the previous ten or more.
Changes will be needed to lines 440, 450, and 600.
3. Keep score of the number of correct and incorrect replies,
and display the percentage each time. Alternatively, come up
with a rating based on the percentage correct and the speed
attained, possibly in conjunction with a difficulty factor for
the phrases used.
4. Add the capability to the program to also have a mode in
which it can display a two to seven digit number, chosen at
random. Have the operator try several of the numbers first
(maybe five-digit ones) before trying the phrases. The phrases
will seem easy after doing the numbers.
VOCAB

PURPOSE

Did you ever find yourself at a loss for words? Well, this vo-
cabulary quiz can be used in a Self-teaching environment or as
reinforcement for classroom instruction to improve your ability
to remember the jargon of any subject. It allows you to drill at
your own pace, without the worry of ridicule from other
students or judgment by an instructor. When you make mistakes,
only the computer knows, and it’s not telling anyone except
you. Modifying the program to substitute a different vocabulary
list is very simple, so you can accumulate many different
versions of this program, each with a different set of words.

HOW TO USE IT

This program is pretty much self-explanatory from the sample


run. After you enter ““RUN,” it asks you how many questions
you would like. If you respond with a number less than five,
you will still do five. Otherwise, you will do the number you
enter.
Next, you get a series of multiple choice questions. Each
question is formatted in one of two ways—either you are given
a word and asked to select from a list of definitions, or you are
given a definition and asked to select from a list of words. The
format is chosen at random. You respond with the number of
the choice you think is correct. If you are right, you are told so.
If not, you are shown the correct answer. From the second
correct answer on, you are shown a Status report of the number
correct out of the number attempted so far.
102 BASIC Programs for the TRS-80

Finally, after the last question, you are shown the percentage
you got correct, along with a comment on your performance.
Then you have the option of going back for another round of
questions or stopping.

SAMPLE RUN

#XXX VOCABULARY QUIZ *® ar as


ues

THIS PROGRAM WILL TEST YOUR KNOWLEDGE


OF SOME USEFUL VOCABULARY WORDS.

HOW MANY QUESTIONS SHALL WE DO? 5

1 -- WHAT WORD MEANS ALL-KNOWING?


1 -- LACONIC
2 -- HEDONISTIC
3 -- OMINOUS
4 -- CONGENITAL
5 -- OMNISCTENT
2? 5
RIGHT!
2 -- WHAT DOES PARSIMONIOUS MEAN?
1 -- INDIFFERENT OR UNINTERESTED
2 -- KEEN IN JUDGMENT
3 -- STINGY OR FRUGAL
4 -- WEAK OR EXHAUSTED
5 -- OF UNKNOWN OR HIDDEN ORIGIN
? 4
NO, THE ANSWER IS NUMBER 3

( ... later)
YOU HAVE 3 RIGHT OUT OF 5 QUESTIONS.
THAT'S 69% PERCENT.
NOT BAD, BUT ROOM FOR IMPROVEMENT.
WANT TO TRY AGAIN? NO

CHECK YOU LATER.


VOCAB 103

PROGRAM LISTING

198 REM: VOCABULARY QUIZ


119 REM: COPYRIGHT 1979 BY TOM RUGG AND PHIL FELIIMAN
129 CLEAR 5@:DEFINT A-Z
399 GOSUB 199
49D GOSUB 2909
388 GOSUB 3999
599 GOSUB 499¢
799 GOSUB 5999
889 GOSUB 4939
999 IF E=8 THEN 599
918 GOTO 399
999 REM
1999 IF E<>@ THEN 1969
1919 CLS
1929 PRINT «tt: VOCABULARY QUIZ sxtece"
19396 PRINT
1949 PRINT" THIS PROGRAM WILL TEST YOUR KNOWLEDGE”
1959 PRINT"OF SOME USEFUL VOCABULARY WORDS."
1949 PRINT
1119 INPUT"HOW MANY QUESTIONS SHALL WE DO"SL
1128 IF L>4 THEN 1149
1139 PRINT" THAT’S NOT ENOUGH. LET’S DO 5.":L=5
1149 IF E<>@ THEN 1299
11598 PRINT
1148 RANDOM
1299 RETURN
2999 IF E<>@ THEN 2299
2919 C=5
2929 D=26
2838 DIM D$(D),E$(D)
2949 DIM P(C)
2959 J=1
2859 REAL D$(J)
28768 IF D$(J)="XXX" THEN 2149
2899 REAL E$(J)
21998 J=J+1
2119 IF J<=I) THEN 2960
2129 PRINT"TOO MANY DATA STATEMENTS."
2139 PRINT'ONLY FIRST" 20:"ARE USED."
2149 Li=J~1
2299 Q=1
2219 E=¢
104 BASIC Programs for the TRS-80

2nd Q1=9
23588 RETURN
3899 FOR J=1 TOC
3819 PC J)=9
3929 NEXT
3938 FOR J=1 TOC
5849 P=RND(D)
5845 IF P=P1 OR P=F2 OR P=P3 THEN 3949
5959 FOR K=1 TO J
59469 IF P(K)=P THEN 384¢
38/72 NEXT K
3989 P¢J)=P
3899 NEXT J
3119 A=RNDC(C)
32BO RETURN
49BD PRINT
4919 M=RND(2)
4G2G IF M=2 THEN 4199
4G 39 PRINT Q;"-- WHAT WORDT MEANS "SES(P(A))
5" ?"
ADAG FOR J=1 TOC
4959 PRINT TABCS)5 J5%-- USDSCP CJ) )
ADSD NEXT
4979 GOTO 4219
4199 PRINT Q3"-- WHAT DOES "sn$(P(A))3" MEAN?"
4119 FOR J=1 TO €
4129 PRINT TARCS)su2"-- "SES(PCJ))
413d NEXT
4218 RETURN
JOG INPUT R
JO18 IF Re=1 AND R“=C THEN 5059
IG29 PRINT’I NEED A NUMBER FROM 1 TO"SC
1838 GOTO 54a
IIIO IF R=A THEN 5199
0469 PRINT'NO, THE ANSWER IS NUMBER"SA
38." GOTO 5219
3199 PRINT’ RIGHT!"
3119 Q1=Q141
J218 IF Ql=1 THEN 5399
228 PRINT" YOU HAVE" 3Q1s"RIGHT QUT OF :Q:" QUESTIONS."
3388 P3=P2
518 FDssfy
ISO P1=F (A)
Jo5K RETURN
5890 Q=Q+1
4919 IF Q<=l THEN RETURN
VOCAB 105

6929 E=1
6939 Q=Q1+199/(Q-1)
5949 IF Q>6 THEN 4979
6959 PRINT"WELIL, THAT“S A “PERFECT” SCORE..."
6949 GOTO 6299
49/79 PRINT’ THAT“S"5Q3;"PERCENT."
4989 IF Q225 THEN 6119
4999 PRINT"CONGRATULATIONS ON AVOIDING A SHUTOUT."
6198 GOTO 6298
6119 IF Q259 THEN 6149
6129 PRINT"YOU CAN USE SOME MORE PRACTICE."
6136 GOTO 6299
5149 IF Q375 THEN 6179
6159 PRINT"NOT BAD, RUT ROOM FOR IMPROVEMENT."
5169 GOTO 6289
6179 PRINT"VERY GOOD!"
4189 IF Q>95 THEN PRINT" YOU“RE ALMOST AS SMART AS I ANI"
62989 PRINT
6218 INPUT"WANT TO TRY AGAIN’; R$
62298 IF LEFTS(R$,1)<2"N" THEN 62498
6239 PRINT:PRINT"CHECK YOU LATER." :PRINTSEND
4246 IF LEFTS¢(R$,1)<2"Y" THEN 6219
6259 RETURN
FOOD REM: ON LINE 2026, I! MUST BE AT LEAST ONE GREATER
7883 REM: THAN THE NUMBER OF DIFFERENT WORDS.
7919 DATA ANONYMOUS, "OF UNKNOWN OR HIDDEN ORIGIN"
7929 DATA OMINOUS, "THREATENING OR MENACING"
7839 DATA AFFLUENT, "WEALTHY"
7949 DATA APATHETIC, "INDIFFERENT OR UNINTERESTED"
PBIB DATA LACONIC,""TERSE"
7868 DATA INTREPID, "FEARLESS OR COURAGEOUS"
79/8 DATA GREGARIOUS, "SOCTAL OR COMPANY-LOVING"
7888 DATA ENERVATED, "WEAK OR EXHAUSTED"
7899 DATA VENERABLE, "WORTHY OF RESPECT OR REVERENCE"
71898 DATA DISPARATE, "DIFFERENT AND DISTINCT”
7118 DATA VIVACIOUS, "LIVELY OR SPIRITED"
7128 DATA ASTUTE,"KEEN IN JUDGMENT”
71398 DATA URSINE, "BEARLIKE"
7149 DATA PARSINONIOUS,"STINGY OR FRUGAL"
P1AS9 DATA OMNISCIENT,"ALL-KNOWING”
F999 DATA XXX
106 BASIC Programs for the TRS-80

EASY CHANGES

1. Add more DATA statements between lines 7000 and 7999,


or replace them all with your own. Be careful not to use two
or more words with very similar definitions; the program
might select more than one of them as possible answers to
the same question. Note that each DATA statement first has
the vocabulary word, then a comma, and then the definition
or synonym. Be sure there are no commas or colons in the
definition (unless you enclose the definition in quotes). If
you add more DATA statements, you have to increase the
value of D in line 2020 to be at least one greater than the
number of words. The number of DATA statements you can
have depends on how long each one is and how much user
memory your computer has. Using DATA statements that
average the same length as these, you can probably have
about thirty of them in a 4K TRS-80, or as many as 400 in a
16K model. Be sure to leave statement 7999 as it is—it signals
that there are no more DATA statements.
2. To get something other than five choices for each question,
change the value of C in line 2010. You might want only
three or four choices per question.
3. If you do not want to be given a choice of how many ques-
tions are going to be asked, remove lines 1110 through 1140
and insert the following lines:
1110 PRINTWE’LL DO TEN QUESTIONS.”
1120 L=10
This will always cause ten questions to be asked. Of course,
you can use some number other than ten if you want.

MAIN ROUTINES

120-910 Mainline routine. Calls major subroutines.


1000-1200 Displays introduction. Initializes RND function.
Determines number of questions to be asked.
2000 - 2300 Reads vocabulary words and definitions into
arrays. Performs housekeeping.
3000 - 3200 Selects choices for answers and determines which
will be the correct one.
4000-4210 Determines in which format the question will be
asked. Asks it.
VOCAB 107

5000-5330 Accepts answer from operator. Determines if


right or wrong. Keeps score. Saves subscripts of
last three correct answers.
6000-6250 Gives final score. Asks about doing it again.
7000-7999 DATA statements with vocabulary words and
definitions.

MAIN VARIABLES

E Set to | to avoid repeating introduction after the


first round.
Limit of number of questions to ask.
Work variable. Also used for operator’s reply to
each question.
Number of choices of answers given for each
question.
D At least one greater than number of DATA
statements. Used to DIM arrays.
D$ Array of vocabulary words.
E$ Array of definitions.
P Array for numbers of possible answers to each
question.
J Work variable (subscript for FOR-NEXT loops).
Q Number of questions asked so far (later used to
calculate percent correct).
Ql Number of questions correct so far.
P Work variable.
P1,P2,P3 Last three correct answers.
A Subscript of correct answer in P array.
M Work variable to decide which way to ask ques-
tion.
R$ Yes or no reply about doing another round.

SUGGESTED PROJECTS

1. Modify lines 6030 through 6200 to display the final evaluation


messages based on a finer breakdown of the percent correct.
For example, show one message if 100 percent, another if
95 to 99, another if 90 to 94, etc.
2. Ask the operator’s name in the introduction routine, and per-
sonalize some of the messages with his/her name.
108 BASIC Programs for the TRS-80

3. Instead of just checking about the last three questions, be


sure that the next question has not been asked in the last
eight or ten questions. (Check lines 3045 and 5300 through
5320.)
4. Keep track of which questions the operator misses. Then,
after going through the number of questions he/she requested,
repeat those that were missed.
Section 3
Game Programs

INTRODUCTION TO GAME PROGRAMS

Almost everyone likes to play games. Computer games are a


fun and entertaining use of your TRS-80. Besides providing
relaxation and recreation, they have some built-in practical
bonuses. They often force you to think strategically, plan ahead,
or at least be orderly in your thought processes. They are also a
good way to help some friends over their possible ‘computer
phobia.’’ We present a collection of games to fit any game
playing mood.
Maybe you desire a challenging all-skill game? Like chess or
checkers, WAR] involves no luck and considerable thinking. The
TRS-80 will be your opponent, and a formidable one indeed.
Perhaps you’re in the mood for a game with quick action and
mounting excitement. GROAN is a fast-paced dice game involving
mostly luck with a dash of skill (or intuition) thrown in. The
TRS-80 is ready for your challenge anytime.
JOT is a word game. You and the TRS-80 each take secret
words and then try to home in on each other’s selection.
Do you like solving puzzles? If so, try DECODE. The compu-
ter will choose a secret code and then challenge you to find it.
Graphic electronic arcade games are a prevalent landmark of
the late seventies. We include two such games. ROADRACE
puts you behind the wheel of a high speed race car. You must
steer accurately to stay on course. OBSTACLE lets you and a
friend compete in a game of cut and thrust. Each of you must
avoid crossing the path laid by the other, and by yourself!
110 BASIC Programs for the TRS-80
DECODE

PURPOSE

Decode is really more of a puzzle than a game, although you


can still compete with your friends to see who can solve the
puzzles the fastest. Each time you play, you are presented with
a new puzzle to solve.
The object is to figure out the computer’s secret code in as
few guesses as possible. The program gives you information
about the accuracy of each of your guesses. By carefully selec-
ting your guesses to make use of the information you have, you
can determine what the secret code must be in a surprisingly
small number of guesses. Five or six is usually enough.
The first few times you try, you will probably require quite a
few more guesses than that, but with practice, you'll discover
that you can learn a lot more from each guess than you origi-
nally thought.

HOW TO USE IT

The program starts off by displaying a brief introduction.


Here are some more details.
The program selects a secret code for you to figure out. The
code is a four digit number that uses only the digits 1 through 6.
For example, your TRS-80 might pick 6153 or 2242 as a secret
code.
Your object is to guess the code in the fewest possible guesses.
After each of your guesses, the program tells you a ‘‘black”’ and
a “white” number. The black number indicates the number of
112 BASIC Programs for the TRS-80

digits in your guess that were correct—the digit was correct and
in the correct position. So, if the secret code is 6153 and your
guess is 4143, you will be told that black is 2 (because the 1 and
the 3 will have been correct). Of course, you aren’t told which
digits are correct. That is for you to figure out by making use of
the information you get from other guesses.
Each of the white numbers indicates a digit in your guess that
was correct, but which is in the wrong position. For example,
if the secret code is 6153 and your guess is 1434, you will be
told that white is 2. The | and 3 are correct, but in wrong
positions.
The white number is determined by ignoring any digits that
accounted for a black number. Also, a single position in the
secret code or guess can only account for one black or white
number. These facts become significant when the secret code
and/or your guess have duplicate digits. For example, if the
code is 1234 and your guess is 4444, there is only one black,
and no whites. If the code is 2244 and your guess is 4122, there
are no blacks and three whites.
This may sound a little tricky, but you will quickly get the
hang of it.
At any time during the game, you can ask for a “SUMMARY”
by entering an S instead of a guess. This causes the program to
clear the screen and display each guess (with the corresponding
result) that has occurred so far.
Also, if you get tired of trying and want to give up, you can
enter a Q (for ‘“‘quit’’) to end your misery and find out the
answer. Otherwise, you continue guessing until you get the code
right (four black, zero white), or until you have used up the
maximum of twelve guesses.

SAMPLE RUN
DECODE

a hl

FIGURE OUT A 4 POSITIONCOE


USING THE DIGITS 1 THROUGH6

EM (sa! a sg
IN THE RIGHT POSITION.
*VHITE? INDICATES SOME OTHER CORRECT BIGIT
BUT IN THE WRONG POSITION.

T’VE CHOSEN MY SECRETCORE.


GUESS NUMBER 1 ? 6413
C1 SS0 ie ieeeare Seo
LO) 30h 1 2 rae

The program displays an introduction, chooses its secret code, and asks for
the operator’s first guess. After the operator makes a guess, the program
responds with a “‘black’’ and a ‘‘white’’ number, and asks for the second
guess.

Later in the same game, the operator asks for a summary, then makes the
guess that turns out to be correct. The program acknowledges that the
guess is correct and asks about trying another game.
114 BASIC Programs for the TRS-80

PROGRAM LISTING

198 REM: DECOUE


119 REM: COPYRIGHT 1979 BY TOM RUGG AND PHIL FELDMAN
129 CLEAR 199:D=6:F=4:L=12
139 DIM G$(L),G(P),C(P) ,B<L) HCL)
149 RANDOM
158 GOSUB 1209
179 GOSUB 3@9:GOSUB 379
188 PRINT'GUESS NUMBER" 5G;
199 INPUT A$
299 IF LEFT$(A$,1)="S" THEN 599
219 IF LEFT$(A$,1)="Q" THEN 699
228 GOSUB 799
238 GOSUB 89¢
LAD GOSUB 1990
239 IF B(G)=P THEN 2009
269 G$(G)=AS
279 G=G+1:I1F GL THEN 2299
289 GOTO 189
589 G=1:C$=""
319 RETURN
378 FOR J=1 TO P
3589 R=RND(D)
399 CH=C$4MID$ (STRE(R), 2,1)
499 NEXT
419 PRINT"I“VE CHOSEN MY SECRET CODE.”
439 RETURN
J99 IF G=1 THEN PRINT"NO GUESSES YET":GOTO 18¢
J1d CLS:PRINT, “SUMMARY”
Joe PRINT"NO. GUESS BLACK WHITE”
338 FOR J=1 TO G-1
349 PRINTJSTAB(7) 5G$(J) STABC16) SBC J) STABC24) SUC 5)
369 NEXT :PRINT
w77G GOTO 189
499 PRINT
619 PRINT'CAN’T TAKE IT, HUH?"
629 PRINT:PRINT"WELL, MY CODE WAS "3
639 FOR J=1 TO 4
649 PRINT” "3
659 FOR K=1 TO 9@@:NEXT
569 NEXT
678 PRINT C$:PRINT
4689 GOTO 2099
799 IF LEN(A$)<OP THEN 788
DECODE 115

719 FOR J=1 TO F


P29 R=VAL (MIDS (A$, J,1))
7 3O IF R<1 OR R=D THEN 79¢
74D NEXT
Pe RETURN
739 PRINT" ILLEGAL. TRY AGAIN."
799 GOTO 18¢
889 K=9 2W=9
319 FOR J=1 TOP
B29 G(J)=VAL (MIDS (A$,J,1))
839 CC =VAL (MIDS (C$,J,1))
84d IF G(sC(J) THEN B=B41:G())=O:C (=
850 NEXT
849 FOR J=1 TO PIF C(J)=@ THEN 929
878 H=@:FOR K=1 TO P
88¢ IF C(0=@ THEN 919
B99 IF CQN<3G(K) THEN 919
799 H=1:G(K)=8:C())=
719 NEXT K:W=W+H
929 NEXT J
9°39 RETURN
1989 B(G)=B:W(G)=W
1916 PRINT"GUESS NO."2Gs"-— BLACK ="sB!" WHITE ="5W
1829 RETURN
1299 CLS
1219 PRINT eke DECODE terer!
1229 PRINT
12.39 PRINT"FIGURE QUT A"SPs"POSITION CODE"
1259 PRINT"USING THE DIGITS 1 THROUGH"sD
1269 PRINT
1276 PRINT" BLACK’ INDICATES A CORRECT DIGIT"
1288 PRINT’IN THE RIGHT POSITION."
1389 PRINT" “WHITE” INDICATES SOME OTHER CORRECT DIGIT"
1.329 PRINT’ BUT IN THE WRONG POSITION."
1338 PRINT
1349 RETURN
2898 PRINT
2819 PRINT'YOU GOT IT IN":G;"GUESSES."
2829 IF G5 THEN B$="QUTSTANIING!"
2839 IF G=5 OR G=é THEN K$="PRETTY GOOD"
2949 IF G=? THEN H$="NOT BAD
2959 IF G=8 THEN B$="NOT TOO GREAT"
2869 IF G>8 THEN B$="PRETTY RAD"
28/8 PRINT’. ...THAT’S "SBS
2098 INPUT"WANT TO TRY AGAIN" SAS
116 BASIC Programs for the TRS-80

2199 IF LEFT$(A$,1)="Y" THEN 159


2119 IF LEFT$(A$,1)<>"N" THEN 2999
2128 PRINTsPRINT"COWARD." PRINT
2139 END
2288 PRINT
2218 PRINT" THAT“S YOUR LIMIT OF"5L; "GUESSES."
2228 PRINT"MY CODE WAS ";C$
2248 GOTO 2896

EASY CHANGES

l. Modify line 120 to change the complexity of the code and/or


the number of guesses you are allowed. For example, the
following line would allow fifteen guesses at a five position
code using the digits 1 through 8:
120 CLEAR 100: D=8:P=5:L=15
The introduction will automatically reflect the new values for
D and P. Be sure that neither D nor P is set greater than 9.
. To change the program so it will always display the “‘Sum-
mary” information after each guess automatically, replace
line 280 with this:
280 GOTO 500

MAIN ROUTINES

120-170 Initializes variables. Displays introduction.


Chooses secret code.
180 - 240 Gets a guess from operator. Analyzes reply. Dis-
plays result.
250 Determines if operator guessed correctly.
260- 280 Saves guess. Adds one to guess counter. Deter-
mines if limit on number of guesses was exceeded.
300 - 310 Subroutine to initialize variables.
370 - 430 Subroutine to choose secret code and inform
Operator.
500- 570 Subroutine to display summary of guesses so far.
600- 680 Subroutine to slowly display secret code when
operator quits.
700- 790 Subroutine to determine if operator’s guess was
legal.
DECODE 117

800 - 930 Subroutine to determine number of black and


white responses for the guess.
1000- 1020 Subroutine to display number of black and white
responses for the guess.
1200- 1340 Subroutine to display title and introduction.
2000- 2130 Subroutine to analyze operator’s performance
after correct answer is guessed and ask about
playing again.
2200 - 2240 Subroutine to display secret code after operator
exceeds limit of number of guesses.

MAIN VARIABLES

D Number of possible digits in each position of the


code (i.e., a digit from 1 to D).
P Number of positions in the code.
L Limit of number of guesses that can be made.
G$ Array in which guesses are saved.
G,C Work arrays in which each guess is analyzed.
B,W Arrays in which the number of black and white
responses is saved for each guess.
R,H Work variables.
G Counter of the number of guesses made.
A$ Reply by the operator.
C$ Secret code chosen by the program.
J,K Loop variables.
B,W Number of black and white responses for this
guess.
BS String with message about operator’s performance.

SUGGESTED PROJECTS

1. Change the analysis at the end of the game to take into


account the difficulty of the code as well as the number of
guesses it took to figure the code out. A four position code
using the digits 1 through 6 has 1296 possibilities, but a five
position code using | through 8 has 32768 possibilities.
Change lines 2020 through 2060 to determine the message to
be displayed based on the number of possibilities in the code
as well as G.
2. At the beginning of the game, give the operator the option of
deciding the complexity of the code. Ask for the number of
118 BASIC Programs for the TRS-80

positions and the number of digits. Make sure only “reason-


able’? numbers are used—do not try to create a code with
zero positions, for example. Another approach is to ask the
operator if he/she wants to play the easy, intermediate, or
advanced version. Then set the values of D and P accordingly.
Suggestions are:

Easy: D=3 and P=3


Intermediate: D=6 and P=4
Advanced: D=8 and P=5
3. In addition to using the number of guesses to determine how
well the operator did, keep track of the amount of time.
This will require use of the INKEY$ function instead of the
INPUT function in line 190, and a bit of logic to “build” the
A$ reply one character at a time. By counting the number of
null strings encountered while waiting for keys to be pressed,
you can “time” the operator.
GROAN

PURPOSE

Do you like the thrills of fast-paced dice games? If so, GROAN


is right up youralley. It is a two-person game with the computer
playing directly against you. There is a considerable amount of
luck involved. However, the skill of deciding when to pass the
dice to your opponent also figures prominently.
The TRS-80 will roll the dice for both players, but don’t
worry—it will not cheat. (We wouldn’t think of stooping to such
depths.)
Why is the game called GROAN? You will know soon
after playing it.

HOW TO USE IT

The game uses two dice. They are just like regular six-sided
dice except for one thing. The die face where the ‘‘1’’ would
normally be has a picture of a frowning face instead. The other
five faces of each die have the usual numbers two through six
on them.
The object is to be the first player to achieve a score agreed
upon before the start of the game. Players alternate taking turns.
A turn consists of a series of dice rolls (at least one roll, possibly
several) subject to the following rules.
As long as no frown appears on either die, the roller builds a
running score for this current series of rolls. After each roll with
no frown, he has the choice of rolling again or passing the dice
to his opponent. If he passes the dice, his score achieved on the
current series is added to any previous total he may have had.
120 BASIC Programs for the TRS-80

But if he rolls and a frown appears, he will be groaning. A


frown on only one die cancels any score achieved for the current
series Of rolls. Any previous score is retained in this case. How-
ever, if he rolls a double frown, his entire previous total is wiped
out as well as his current total. Thus, he reverts back to a total
score of zero—true despair.
The program begins by asking what the winning score should
be. Values between 50 and 100 tend to produce the best games,
but any positive value is acceptable. Next, a simulated coin toss
randomly decides who will get the first roll.
Each dice roll is portrayed with a short graphics display. The
dice are shown rolling and then the outcome is displayed pic-
torially. Before each roll, the TRS-80 indicates whose roll is
coming up.
Each roll is followed by a display of the scoreboard. This
scoreboard gives all relevant information: score needed to win,
both players’ scores before the current series of rolls, and the
total score for the current series.
If a frown should appear on a die, the scoreboard will indi-
cate the current running total as zero. In addition, the previous
total will become zero in the case of the dreaded double frown.
In either case, the dice will be passed automatically to the next
player.
If a scoring roll results, the roller must decide whether to roll
again or to pass the dice. The program has a built-in strategy to
decide this for the TRS-80. For you, the question will be asked
after the scoreboard is displayed. The two legal replies are P and
R. The R means that you wish to roll again. The P means that
you choose to pass the dice to the TRS-80. If you should score
enough to win, you must still pass the dice to add the current
series to your previous total.
The first player to pass the dice with a score greater than or
equal to the winning score is the victor. This will surely cause
his opponent to GROAN. The computer will acknowledge the
winner before signing off.

SAMPLE RUN
GROAN 121

GROAN
Pept
p ssa Re
CBETIEEN
58-108 1S BEST) ? 58
LET’S TOSS FOR FIRST ROLL

THE COIN IS IM THE AIR AD

The operator has decided to challenge the TRS-80 to a fifty point game of
GROAN. The computer wins the coin toss and gets the first dice roll.

--SCOREBOARD--

5@ POINTS NEEDED TO WIN

UCR BL 3]
BEFORE THIS SERIES

a BavUibm Gee d ala)

DICE PASS TO YOU

The computer's roll, however, results in a “groan” and a four. This scores
no points and the dice pass to the operator.
122 BASIC Programs
for the TRS-80

cae a ee

5@ POINTS NEEDED TO WIN

POINTS SCORED yu
pat ae epeedala (rs)

pli Se aU Gi 13)

Mia) ieee ote)


UL RG Cat ee

Much later in the same game, the operator rolls a 12 to start a series of rolls.
The score was operator-29, TRS-80-20 before the roll. The operator must
now decide whether to pass the dice or risk rolling again.

PROGRAM LISTING

198 REM: GROAN


119 REM: COPYRIGHT 1979 BY PHIL FELDMAN AND TOM RUGG
128 CLEAR 25@:RANDOM:DEFINT W
149 BS=CHRS$ (191) sC$=CHRS (179) sL$=CHRS$ (1776) 2M$=CHRS (149)
158 US=CHR$ (131) sNS=CHRS (32) sF3S=BRS+STRINGS (49,148) +BS
168 L1$=BS+STRINGS (7, 131) +8% s02$=BS+STRINGS (7,32) +BS
176 N3$=BS+STRINGS (7,176) +KS =
E1$=STRINGS (4,32) +L $+M$+L$+STRINGS (4,32)
189 EQS=NS+LS+MS+USHNS+NS+NG+US+MS+1_S+NG2
E3S=US+MS+LS+STRINGS (5, 32) +L S4+NS+US
185 E4$=NGtNS+NS+US+MS +L SMS +USHNS+NG ENG
199 FIS=BS+STRINGS (40,131 +RS2F23=BS+STRINGS (49,176) +B9
298 CLSSFRINT TAR(25)5"G RO AN"
218 FRINT'HOW MUCH NEEDEG TO WIN”
228 INFUT' (BETWEEN 5@-180 IS BEST) "“SWsIF We=8 THEN 268
238 PRINT:FRINT"LET“S TOSS FOR FIRST ROLL":GOQSUB 838
248 PRINTSERINT' THE COIN IS IN THE AIR ANI"
250 Q$="YOU"sQ=RNO(2)sIF Q=2 THEN Q$="1"
248 PRINT TAR(8)¢:FOR J=1 TO SPRINT". "5 :GOSUR 838:NEXT
GROAN 123

278 PRINT Q$:" GET FIRST ROLL":GOSUB 849:T=¢:


IF Q=2 THEN 499
598 P$=" YOU'SCLS:PRINT TAB(25)5"YOURE ROLILING":
GOSUB 839:GOSUB 549
319 T=T+R14+R22IF F2@ THEN T=¢
329 IF F=2 THEN H=d
339 GOSUR S5@:IF F2@ THEN FRINT'DICE PASS TO ME":
GOSUBR 849:GOTO 499
549 PRINT'(P=PASS DICE - R=ROLL AGAIN)":
PRINT" YOUR DECISION (PF OR R) 7"
JG Q$=INKEY$:IF Q$="" THEN 35¢
349 IF Q$="R" THEN 340
37D IF Q$<>"P" THEN 359
389 PRINT:H=H+TsIF H>=W THEN 97¢
599 T=O2F=1:CLS:GOTO 339
49D T=O2P$="I"
419 CLS:PRINT TAR(26):"I°M ROLLING" :GOSUB 839:GOSUB 549
429 T=T+R1+R2sIF F2@ THEN T=¢
439 IF F=2 THEN P=¢
44D GOSUB 85@:IF F>@ THEN PRINT"DICE PASS TO YOU":
GOSUB 849:T=9:GOTO 399
GOSUR 1900:IF X=1 THEN PRINT'I“LL ROLL AGAIN":
GOSUB 849:GOTO 41¢
PRINT'I°LL STOP WITH THIS":GOSUB @30:P=P+T:
IF Fs=W THEN 976
PRINT:PRINT"DICE PASS TO YOU":T=@:GOSUEK 849:
GOTO 399
[#266 :DL=5:2R1=RND(6) sR2=RND(S) FOR K=9 TO 48 STEP 8
C=[+K:GOSUB 659:C=C+384:GOSUB 4659:GOSUB 494:CLS
GOSUK 646:C=C-384:GOSUR 4649:GOSUB 699:CLS
NEXT:C=04+48:GOSUB 450:C=C+384:GOSURB 65¢
C=D+48:R=R1:GOSUB 789
C=C+384:R=R2:GOSUB 76@:F=O:IF R1=1 THEN F=1:
GOSUB 849
IF R2=1 THEN F=F+1:GOSUB 819
IF F=2 THEN GOSUB 826:GOSUR 93¢
RETURN
FOR J=1 TO DLsNEXT:RETURN
PRINT@C-136,D1$sPRINT@C-72, [12$ :FRINT@C-8 , 03$ :RETURN
PRINT@C-197 ,£1$sPRINT@C-133 ,£2%:PRINT@C-69 E34
PRINT@C-5,E4$ :RETURN
ON R GOSUB 719,738,740, 750,749, 770:RETURN
PRINT@C-134,C$2sPRINT@C-139,C$5:PRINT@C-48," ("ss
PRINT@C-6,CHR$(182)5
124 BASIC Programs for the TRS-80

729 FOR Q=3 TO S:PRINT@C-Q,C$5 sNEXTs


PRINT@C-2,CHR$ (185) 5 sRE TURN
38 PRINT@C~134.C%; sPRINT@C~2,C%5 sRETURN
49 PRINT@C-68, CHR$(149).:GOSUB 73O:RETURN
759 PRINT@C-138,C$ 5 sPRINT@C-6,C$:GOSUB 739SRETURN
69 GOSUBK 749:GOSUR 75@:RETURN
78 PRINT@C-78,CHRS (149) 5 sFRINTCC-66,CHRS(149) 5:
GOSUB 759:sRETURN
899 FRINT@S2, "GROAN": sRETURN
819 PRINT@829, "GROAN" 5s RETURN
829 PRINT@434,"-DESPAIR-"; sRETURN
839 FOR K=1 TO 8@@:NEXTSRETURN
849 FOR K=1 TO 299¢:NEXTsRETURN
859 PRINT@464,F1$;5 2G=128:GO0SUB 949:
PRINT@135,"- -SCOREBOARTI- -",
849 PRINT@192,F3$5 sG=2546:GO0SUB 949:
PRINT@2464,W;"FOINTS NEEDED TO WIN";
878 PRINT@329,F3%5 sG=384:GOSUR 948
889 PRINT@384," POINTS SCORED YOu ME" ss
G=448
899 GOSUR 969:PRINT@450,"BEFORE THIS SERIES";:
PRINT@475,H3
999 PRINT@482,P5 sPRINT@S12,F 3%; :G=5/6:G0SUB 949
919 PRINT@S582,P$;," HAVE’ ST ,"POINTS THIS SERIES";
929 PRINT@649,F 25 sPRINT@/468, °°" 5 sSRETURN
969 FRINT@G, RE; sPRINT@G+41 BS; SRE TURN
979 T=@:CLS:GOSUB 859d:
IF P2>=W THEN PRINT@748,"SKILI WINS AGAIN”
989 IF H>=W THEN
PRINT@768,"YOU WIN - IT WAS SHEER LUCK"
999 ENT
1988 V=P+TsIF Vo=W THEN 1199
1919 IF (W-HO<19 THEN 1119
1920 IF P>=H THEN L=T/25:GOTO 1959
193@ IF VXH THEN L=T/35:GOTO 19598
1948 L=T/38
1959 IF RNIMS)>L THEN 1119
1198 X=9:RETURN
1118 X=1sRETURN

EASY CHANGES

1. If you wish to set the program for a fixed value of the winning
score, it can be done by changing line 210 and deleting line
220. Simply set W to the winning score desired. For example:
GROAN 125

210 W=100
would make the winning score 100. Don’t forget to delete
line 220.
. The rolling dice graphics display before each roll can be elimi-
nated by changing lines 500 and 540 as follows:
500 D=266: RI=RND(6):R2=RND(6):GOTO 540
540 C=D+48:GOSUB 650: C=C+384:GOSUB 650
This has the effect of speeding up the game by showing each
dice roll immediately.
. After you play the game a few times, you may wish to change
the delay constants in lines 830 and 840. They control the
“pacing” of the game; i.e., the time delays between various
messages, etc. To speed up the game try
830 FOR K=1 TO 400: NEXT: RETURN
840 FOR K=1 TO 1000: NEXT:RETURN
Of course, if desired, the constants can be set to larger values
to slow down the pacing.

MAIN ROUTINES

120-190 Initializes constants.


200 - 270 Initial display. Gets winning score.
300 - 390 Human rolls.
400 - 470 TRS-80 rolls.
500 - 590 Determines dice roll. Drives its display.
600 Delay loop.
700-770 Draws die face.
800 - 820 Displays groan messages.
830 - 840 Delay loops.
850 - 960 Displays scoreboard.
970 - 990 Ending messages.
1000-1110 Computer’s strategy. Sets X=0 to stop rolling or
X=1 to continue rolling.

MAIN VARIABLES

W Amount needed to win.


H Previous score of human.
P Previous score of TRS-80.
126 BASIC Programs for the TRS-80

T Score of current series of rolls.


x TRS-80 strategy flag (O=stop rolling; 1=roll again).
L Cutoff threshold used in computer’s built-in stra-
tegy.
V Score TRS-80 would have if it passed the dice.
DL Delay length.
Q,Q$ Work variable, work string variable.
J,K Loop indices.
P$ String of name of current roller.
R1,R2 Outcome of roll for die 1, die 2.
R Outcome of a die roll.
F Result of roll (O=no frown; l=one frown; 2=dou-
ble frown).
C,D,G Screen printing positions.
NT Argument for TAB function.
B$-U$§ Strings for graphics displays.

SUGGESTED PROJECTS

l. The computer’s built-in strategy is contained from line 1000


on. Remember, after a no frown roll, the TRS-80 must decide
whether of not to continue rolling. See if you can improve on
the current strategy. You may use, but not modify, the varia-
bles P, T, H, W. The variable X must be set before returning.
Set X=0 to mean the TRS-80 passes the dice or X=1 to mean
the TRS-80 will roll again.
. Ask the operator for his/her name. Then personalize the mes-
sages and scoreboard more.
. Dig into the workings of the graphics routines connected
with the dice rolling. Then modify them to produce new,
perhaps more realistic, effects.
JOT

PURPOSE

JOT is a two player word game involving considerable mental


deduction. The TRS-80 will play against you. But be careful!
You will find your computer quite a formidable opponent.
The rules of JOT are fairly simple. The game is played
entirely with three-letter words. All letters of each word must be
distinct—no repeats. (See the section on Easy Changes for
further criteria used in defining legal words.)
To begin the game, each player chooses a secret word. The re-
mainder of the game involves trying to be the first player to
deduce the other’s secret word.
The players take turns making guesses at their opponent’s
word. After each guess, the asker is told how many letters (or
hits) his guess had in common with his opponent’s secret word.
The position of the letters in the word does not matter. For
example, if the secret word was “‘own,” a guess of “who”
would have 2 hits. The winner is the first person to correctly
guess his opponent’s secret word.

HOW TO USE IT

The program begins with some introductory messages while


asking you to think of your secret word. It then asks whether or
not you wish to make the first guess. This is followed by you
and the TRS-80 alternating guesses at each other’s secret word.
After the TRS-80 guesses, it will immediately ask you how it
did. Possible replies are 0, 1, 2, 3, or R. The response of R (for
128 BASIC Programs for the TRS-80

right) means the TRS-80 has just guessed your word correctly—
a truly humbling experience. The numerical replies indicate that
the word guessed by the TRS-80 had that number of hits in your
secret word. A response of 3 means that all the letters were cor-
rect, but they need to be rearranged to form the actual secret
word (e.g. a guess of ““EAT”’ with the secret word being ““TEA’’).
After learning how it did, the computer will take some time
to process its new information. If this time is not trivial, the
TRS-80 will display the message: “I’M THINKING” so you do
not suspect it of idle daydreaming. If it finds an inconsistency
in its information, it will ask you for your secret word and then
analyze what went wrong.
When it is your turn to guess, there are two special replies
you can make. These are the single letters S or Q. The S, for
summary, will display a table of all previous guesses and corre-
sponding hits. This is useful as a concise look at all available
information. It will then prompt you again for your next guess.
The Q, for quit, will simply terminate the game.
When not making one of these special replies, you will input
a guess at the computer’s secret word. This will be, of course, a
three letter word. If the word used is not legal, the computer
will so inform you. After a legal guess, you will be told how
many hits your guess had. If you correctly guess the computer’s
word, you will be duly congratulated. The TRS-80 will then ask
you for your secret word and verify that all is on the ‘‘up and
up.
99

SAMPLE RUN
JOT
JUST A MOMENT PLEASE .....
THANKS, NOW LET'S EACH THINK
OF OUR SECRET WORD
CTHIS TAKES ME A WHILE ...)

I'VE ALMOST GOT IT

OK, DO YOU WANT TO GO FIRST? N

MY GUESS IS -- NIP
HOW DID I DO Cg-3 OR RD? 1
JOT 129

I'M THINKING

YOUR GUESS COR S OR Q)? DOG


# OF HITS IS 1

MY GUESS IS -- NOR
HOW DID I DO Cf-3 OR RD? G

I'M THINKING

(later in the same game)

YOUR GUESS COR S OR Q)? S

YOUR GUESSES SUMMARY MY GUESSES


WORD HITS WORD HITS
DOG 1 1 NIP l
CAT g 2 NOR g
LIP g 3 DIG p
SON g 4 PUT 2
5 PUB 1
YOUR GUESS COR S OR Q)? FED
# OF HITS IS 2

MY GUESS IS -- PET
HOW DID I DO Cf-3 OR RI? R

IT SURE FEELS GOOD

MY WORD WAS —- WED

HOW ABOUT ANOTHER GAME? NO


READY.

PROGRAM LISTING
108 REM: JOT
118 REM: COPYRIGHT 192° BY PHIL FELUMAN ANG TOM RUGG
128 CLEAR 2A@GsTEF INT A-2sRANTION
148 Meat n= 404
178 DTM ACN)
130 BASIC Programs for the TRS-80

189 CIM G1$(M) ,G2$(M),H1 (CM) ,H2CM)


29 (51=9262=9
219 LN
230 CLOsPRINT TARC25) 5° O T"sFRINT
269 PRINT’ JUST A MOMENT PLEASE ....."2GOSUB 39904:
PRINTSQ=RNDCN)
PRINT’ THANKS, NOW LETS EACH THINK OF
QOUR SECRET WORT"
288 PRINT’ CTHIS TAKES ME A WHILE ...)"
2 9G GOSUB 22982M$=A8(Q) sSPRINTSPRINT OK, "5
389 INFUT'OO YOU WANT TO GO FIRST" Q$
319 Q&=LEFTS(Q$.7)2IF Q$="N" THEN 699
329 IF Q$="Y" THEN 588
33d PRINTSPRINT' YES OR NO PLEASE" SPRINT:GQTO 389
OG PRINTS INPUT YOUR GUESS (OR $ OR Q)"5F%
wl® IF F$="S" THEN GOSUR 19908sGOTO 3¢d
we TF F$="Q" THEN 1196
JG TF P#=M$ THEN G1=614+1261$(61)=P$sH1(61)=92G0TO0 3499
Jt49 GOSUR 1899:
IF F=@ THEN PRINT’ THAT“S NOT A LEGAL WORT":
wae TF F=@ THEN PRINT" -- TRY AGAIN’ 2G0TO 30%
8 QE=M$2GOSUR 2609 2Q$=F$2G0SUB 1508:
PRINT'H OF HITS IS":@
JO G1=61412619(G1)=Q$:H1(G1)=Q:IF Gi=M THEN 36¢9
599 QS=A$(L) :G2=G62+41 262$ (G2) =0$
619 PRINT!PRINT'MY GUESS IS -- "103
629 INPUT"HOW DIDI 00 (9-3 OR RY Ps
539 P$=_EFT$(PS,1)
649 IF P$="R" THEN H2(G2)=9:G0TO 3294
658 P=VAL CPS)
649 IF P23 OR (F=@ AND P#<2"9") THEN PRINT" BAD ANSWER:
GOTO 419
679 IF L218 THEN PRINTSPRINT'I°M THINKING ..."
689 H2(G2)=FsGOSUR 889:GOTO 59d
846 Q$=G2$(G2) sH=H2(G2) sJ=@:GOSUB 2600:L=L~-1:
IF L“1 THEN 999
819 JeJ+120F JL THEN 879
826 Q$=A$(J) sGOSUR 1599
839 IF Q=H THEN 819
849 A=JrH=L:GOSUB 2400:1L=L~1
859 IF L<1 THEN 999
84h IF L>=J THEN 826
8,79 RETURN
999 PRINTSFRINT’SOMETHING’S WRONG |!"
919 PRINTSINPUT"WHAT’S YOUR SECRET WORI'sF$:GOSUB 1899
JOT 131

928 IF Fase THEN 949


938 PRINT’ ILLEGAL WORD - I NEYER HAT A CHANCE":
GOTO 114%
949 PRINTsPRINT’ YOU GAVE A BAD ANSWER SOMEWHERE --"
958 PRINT"HIT ANY KEY TO CHECK THE SUMMARY"
9469 QE=INKEY$sIF Q$="" THEN 949
776 GOSUH 1969886:G0TO 1199
1992 PRINT:Q26121F G22G1 THEN Q=62
1819 IF Q=@ THEN PRINT'NO GUESSES YET" sRETURN
1828 FOR J=1 TO 41sPRINT"=~"ssNEXT#PRINT?="
163¢ PRINT" YOUR GUESSES SUMMARY MY GUESSES"
18496 PRINT'WORD HITS" STABC32)2"WORD HITS"
1939 FOR J=1 TO Q:K=12IF Jo9 THEN K=9
1849 IF J2G1 THEN PRINT STRINGS (194K, 32) $5
STRINGS (19,32) 16.2$(J) ISTRINGS(2, 32) sH2J) £6070 1096
1979 IF J2G2 THEN
PRINT’ "<G1$CD5" "SH1 (J) SSTRINGS (104K, 32) tus
GOTO 1999
1989 PRINT" "2G1$CJ02" "SHI CI) SSTRINGS (194K, 32) 23
STRINGS (19,32) 1G26(J) 3" "SH2CI)
1999 NEXT RETURN
1182 PRINT:INPUT"HOW ABRQUT ANOTHER GAME" 0%
1119 QS=LEFT#(Q$,1)2IF Q$="Y" THEN 268
1129 IF Q$="N" THEN END
11.39 PRINTIFRINT"YES OR NO FLEASE"sGOTO 119¢
150d F$=LEFT$(Q$,1)2Q=0:GOSUB 1699
15198 E$=410$(Q$,2,1):GOSUB 14699
1328 F$=RIGHT$(Q$,1):GOSUB 1680:RETURN
1609 IF FS=M1% OR F$=42$ OR F$=M3$ THEN Q=Q+1
1619 RETURN
1889 F=g
1819 FOR J=1 TO N
1829 IF A$(J=P$ THEN F=1:RETURN
1839 NEXT RETURN
2oOO FOR ASN TO 190 STEP -1:B=RNDIKA):GOSUB 2498
2218 NEXT :PRINT
2228 PRINT"I"VE ALMOST GOT IT wee"
2258 FOR A=99 TO 2 STEF -1:B=RNDCA)
2249 GOSUR 2409 :NEXT :RETURN
24989 Q$=A$(B) 2A$(B)=A$(A) 209 (A)=Q$:RETURN
269d M1$=LEFT$(Q$,1) sM2$=MID9(Q$,2, 1)
2619 M3$=RIGHT$(Q$, 1) sRETURN
JOOS RESTORE:FOR P=1 TO N:READ A$(P) NEXT RETURN
5268 PRINTIPRINT'IT SURE FEELS Goon”
3219 FRINTSPRINT'MY WORD) WAS - "SM
132 BASIC Programs for the TRS-80

3299 GOTO 11900


3460 PRINTSFRINT'CONGRATULATIONS - THAT WAS IT’ SPRINT
341 INPUT"WHAT WAS YOUR WORD’ TP $:GOSUR 199¢sJ=1
3429 IF F<u@ THEN 3449
3439 PRINT’ ILLEGAL WORD - T HAN NO CHANCE’ :GOTO 1193
3449 IF A$(J=F4 THEN PRINT'NICE WORT':GOTO 1196
3450 JsJ+12IF Jel THEN 3449
3440 PRINTSPRINT"YOU MADE AN ERROR SOMEWHERE --"
3479 PRINT"HIT ANY KEY TQ CHECK THE SUMMARY”
3480 QS=INKEY$:IF Q$="" THEN 3499
3499 GOSUR 148@:GOTO 1194
3690 PRINT’SORRY, I°M OUT OF MEMORY SPRINT
3610 PRINT'MY WORD WAS ~ "IM$:GOTO 1196
5000 LATA ACE, ACT, ALE, AUO, ALIS, AFT.AGE
5910 DNATA AGO,AID,AIL,AIM,AIR-ALE,ALF
5920 DATA ANIL,ANT, ANY APE. APT ARC, ARE
5030 TATA ARK, ARM, ART.ASH.ASK ASF ATE
5049 DATA AWE.AWL,AXE.AYE. BAT. BRAG. BAN
5959 DATA BAR. BAT, BAY, BEU.BEG, RET, BID
5048 DATA RIG, BIN. BIT, BOA, BOG, BOW, BOX
5976 DATA ROY, BUU. BUG, BUM, BUN, RUS, BUT
5080 DATA BLY, RYE,CAB,CAD,CAM,CAN, CAF
5699 DATA CAR,CAT,COB,COU.COG,CON, COP
5198 DATA COT,COW.COY,CRY, CUB, CUD, CUE
S110 DATA CUP,CUR.CLUT, UAB, DAM, DAY, DEN
5126 DATA GEN, UIE, (IG, DIM. 0IN, OIF. 00E
5136 DATA ROG, DON, TOT, ORY, TUR, WUE, DUG
5149 DATA DYE,DUO,EAR,EAT,EGO,ELK ELM
S15@ DATA END,ELF,ERA,FAU.FAG,FAN,FAR
5140 DATA FAT,FED,FEW,FIG.FIN,FIR.FIT
S178 TATA FIX,FLY.FOE,FOG,.FOR FOX, FRY
5180 ATA FUN,FUR,GAP,GAS.GAY.GEM,GET
5198 CATA GIN, GNU,GOR,GOD,GOT,GUM, GUN
52908 CATA GUT,GUY,GYE.HAD.HAG,HAM.HAS
5210 DATA HAT.HAY.HEN,HEX HI0,HIM HIF
5226 DATA HIS,HIT,HER,HEM,HOE.HOG,HOP
5239 DATA HOT,HOW,HUB,HUE HUG, HUM, HLT
5249 UWATA ICE, ICY,ILK, INK. IMP. TON, TRE
5059 ATA IRK. TTS, IVY. JAR, JAR. IAW, JAY
5240 DATA JO8,J0G.JOT. JOY. JUG, IAG. 1am
S979 UATA JET.JT8. JIG, JUT KEG. KEY KIO
5298 DATA KIN,KIT.LAB,LAD.LAG.LAP.LAW
5299 DATA LAY,!AX,LEU.LEG.LET.LI0.LIE
5309 ATA LIF,LIT.LOB,LOG,LOF.LOT.1.OU
5310 TATA LYE.MAIL.MAN, MAP .MAR. MGT .MAY
JOT 133

328 UATA MEN. MET, MIU. MOR. MOF. NOW. MUD


458 NATA MIX. MUG,NAB.NAG NAF. NAY NET
3349 CATA NEW.NILNIF NOD. NOT.NOR NOW
35.39 ATA NUT .OAF .QAK.OAR, OAT, QUE OIL
3568 IIATA OLD,ONE,OFT,ORE,QUR,OUT,OVA
3579 DATA QUE OWL OWN, PAD.FAL FAN, PAR
388 LATA FAT, PAW,FAY .PEA.PEG. FEN PET
9g VATA PEW.PIEFIGPIT PLY POL .POT
JAGD NATA FOX PER. PIN ERO.PRY ,PUB SPUN
419 ATA FUS,PUT,.RAG, RAM. RAN, RAP RAT
428 ATA RAW, RAY, RED RIB RID, REV, RIG
439 IATA RIM, RIP,ROB. ROU. ROE,ROT,ROW
I4AD IATA RUB, RUE RUG, RUM, RUN, RUT RYE
4g LATA SAL.SAG, SAP, SAT SAW, SAY SET
449 IATA SEU, SEX,SHY,SEA.SIN.SHE. SIP
3476 VATA SIR, SIT,SIX.SKI.SKY.SLY.S08
JAD IATA SOU.SON.SQU,SOY.SFA.SFY.STY
1499 DATA SUE,SUM.SUN, TAB, TAL, TAG. TAN
IIgs NATA TAP, TAX, TAR, TEA. TEN, THE, THY
3318 DATA TIC, TIE, TIN, TIF. TOE, TON, TOF
wed VATA TOW, TOY, TRY, TUB, TUG, THO, URN
dad QATA USE UPS YAN, VAT, VEX VIA, VIE
on

IAG DATA VIM, VOU, YAK, YAM, YEN. YES. YET


“i
£5

DNATA YOU, WAL WAG, WAN WAR, WAS WAX


‘Fi
oh
1 cn on

ATA WAY WER, WED, WET,WHO,WHY WIG


oN
0

LATA WIN.WIT WOE WON WRY, ZIFF IB


fact}
“yy

“wd
ni

EASY CHANGES

1. It is fairly common for players to request a summary before


most guesses that they make. If you want the program to
automatically provide a summary before each guess, change
lines 500 and 510 to read
500 IF G1>0 OR G2>0 THEN GOSUB 1000
510 PRINT: INPUT “YOUR GUESS (OR Q)”;P$
. The maximum number of guesses allowed, M, can be changed
in line 160. You may wish to increase it in conjunction with
Suggested Project 2. You might decrease it to free some
memory needed for other program additions. The current
value of twenty-five is really somewhat larger than necessary.
An actual game almost never goes beyond fifteen guesses. To
set M to 15 change line 160 to read
160 M=15:N=406
134 BASIC Programs for the TRS-80

3. Modifying the data list of legal words is fairly easy. Our cri-
teria for legal words was as follows: they must have three
distinct letters and not be
— capitalized
— abbreviations
— interjections (like ‘“‘ugh’’, ““hey”’ etc.)
— specialized words (like “‘ohm’’, 9 “‘sac’’, > “yaw” etc.)
In line 160, N is set to be the total number of words in the
data list. The data list itself is from line 5000 on.
To add word(s), do the following. Enter them in data state-
ments after the current data (use line numbers larger than
5570). Then redefine the value of N to be 406 plus the number
of new words added. For example, to add the words ‘‘ohm”’ and
‘‘vaw’’ onto the list, change line 160 to read
160 M=25:N=408
and add a new line
5580 DATA OHM, YAW
To word(s), the opposite must be done. Remove the
delete
words the appropriate data statement(s) and decrease
from
the value of N accordingly.

MAIN ROUTINES

150-180 Dimensions arrays.


200- 330 Initializes new game.
500- 570 Human guesses at the computer’s word.
600- 680 TRS-80O guesses.
800- 870 Evaluates human’s possible secret words. Moves
them to the front of A$ array.
900 - 970 Processes inconsistency in given information.
1000 - 1090 Displays the current summary table.
1100-1130 Inquires about another game.
1500 - 1610 Compares a guess with key word.
1800 - 1830 Checks if input word is legal.
2000 - 2010 Sets Q$ to Q’th element of A$—BS$ array.
2100-2110 Sets P’th element of A$—B$ array to P$.
2200 - 2240 Shuffles A$ array randomly.
2400 Swaps elements A and B in the A§ array.
2600 - 2610 Breaks word Q$ into separate letters.
3000 Fill A$ array from data.
JOT 135

3200 - 3220 Post-mortem after TRS-80 wins.


3400 - 3490 Post-mortem after human wins.
3600-3610 Error routine - too many guesses.
5000-5570 Data.

MAIN VARIABLES

N Total number of data words.


M Maximum number of guesses allowed.
A$ String array holding data words.
G1$,G2$ String arrays of human’s, computer’s guesses.
H1,H2 Arrays of human’s, computer’s hits corresponding
to G1$, G2S.
G1,G2 Current number of human’s, computer’s guesses.
M$ Computer’s secret word.
M1$,M2$, First, second, and third letters of a word.
M3$
P$,Q$ String temporaries and work variables.
L Current number of human’s possible secret words.
F Flag for input word legality.
H Number of hits in last guess.
A,B A$ array locations to be swapped.
J,P,Q Temporaries; array and loop indices.

SUGGESTED PROJECTS

1. Additional messages during the course of the game can per-


sonify the program even more. After the TRS-80 finds out how
its last guess did, you might try an occasional message like
one of these:
JUST AS I THOUGHT...
HMM, I DIDN’T EXPECT THAT...
JUST WHAT I WAS HOPING TO HEAR...
The value of Lis the number of words to which the computer
has narrowed down the human’s secret word. You might
check its value regularly and when it gets low, come out with
something like
BE CAREFUL, ?’M CLOSING IN ON YOU.
2. Incorporate a feature to allow the loser to continue guessing
at the other’s word. The summary display routine will
136 BASIC Programs for the TRS-80

already work fine even if Gl and G2 are very different from


each other. It will display a value of “9” for the number of
hits corresponding to the correct guess of a secret word.
OBSTACLE

PURPOSE

This program allows you and a friend (or enemy) to play the
game of OBSTACLE, an arcade-like game that’s one of our
favorites. A combination of physical skills (reflex speed, hand
to eye coordination, etc.) and strategic skills are needed to beat
your opponent. Each game generally takes only a minute or
two, so you'll want to play a match of several games to deter-
mine the better player.

HOW TO USE IT

The object of the game is to keep moving longer than your


opponent without bumping into an obstacle. When the program
starts, it asks in turn for the name of the player on the left and
on the right. Then it displays the playing field, shows the starting
point for each player, and tells you to press any key to start.
After a key is pressed, each player begins moving indepen-
dently in one of four random directions—up, down, left, or
right. As each player moves, he or she builds a “‘wall’’ inside the
playing field. The computer determines the speed of the move;
the player can only control his own direction. The player on the
left can change direction to up, down, left, or right by pressing
the key W, X, A, or D, respectively. The player on the right
does the same by using the keys for O (not zero), . (period), K,
and ; (semi-colon). Find these keys on the TRS-80 keyboard
and you will see the logic behind these choices.
138 BASIC Programs for the TRS-80

The first time either player bumps into the wall surrounding
the playing field or the obstacle wall built by either player, he
loses. When this happens, the program indicates the point of
impact for a few seconds and displays the name of the winner.
Then the game starts over.
The strategic considerations for this game are interesting.
Should you attack your opponent, trying to build a wall around
him that he must crash into? Or should you stay away from him
and try to make efficient moves in an open area until your
opponent runs out of room on his own? Try both approaches
and see which yields the most success.
When pressing a key to change direction, be sure to press it
quickly and release it. Do not hold a key down—you might
inhibit the computer from recognizing a move your opponent
is trying to make. Once in a while, only one key will be recog-
nized when two are hit at once.

SAMPLE RUN

Ht og

NAME OF PLAYER ON THE LEFT? TOM


PLAYER ON THE RIGHT? PHIL

The program starts off by asking for the names of the two players.
OBSTACLE 139

tf neg

occe mam Ca

= bi

The program redraws the playing field and starts both players moving in a
random direction (in this case, both start moving to the left). Phil (on the
right) doesn’t change directions soon enough and crashes into the wall,
making Tom the winner.
140 BASIC Programs for the TRS-80

PROGRAM LISTING

199 REM: OBSTACLE


119 REM: COPYRIGHT 1979 BY TOM RUGG ANDI FHIL FELIMAN
129 CLEAR 26@:DEF INT A-Z:RANDOMSGOSUB 4699
125 CLSOsPRINT sPRINT
139 PRINT TAR(C24)5 "OBSTACLE"
149 PRINT sPRINT
159 PRINT TAR(19)5"PRESS ANY KEY TO START"
133 W=32Z=1912Z2$=STRINGS(W,CHRS(Z)) sA=446628=487
149 AS=CHRS$ (183) +CHRS(17°9)+4CHRS(
1877):
RS=STRINGS (WU, CHR$(153))
165 $=15369 :E$=STRINGS (W,CHRS(173)) sAD=RND( 4) sBD=RND( 4)
178 GOSUB 999:GOSUR 959:sFOR J=1 TO 1@sR$=INKEYSsNEXT
189 R$=INKEY$:IF R$=""" THEN 1898
199 CLS
289 GOSUB 9359:GOSUBR 998:FOR J=1 TO 1@:R$=INKEYS:NEXT
219 X=As0=AU:sGOSUB 19098
229 AR=R sA=X
239 X=BsD=BN:sGOSUB 196d
249 BR=R
s R=X
245 IF AR=1 OR BR=1 THEN 499d
258 GOSUB 99¢
269 FOR J=1 TO 8sR$=INKEYS
279 IF R$="W" THEN Ali=1
289 IF R$="X" THEN All=2
299 IF R#="A" THEN An=3
399 IF R¢="00" THEN Ali=4
31d TF R#="0" THEN BI
529 IF R#="." THEN Bli=2
338 IF R$="K" THEN BD=3
549 IF R#="5" THEN Bli=4
358 NEXT
349 GOTO 219
499 GOSUB 799:xX=A
419 IF BR=1 THEN X=R
429 FOR J=1 TO 15
439 PRINTG@X,Z$5
44D FOR K=1 TO 20@:NEXT
4G FRINT@X," "y
459 FOR K=1 TO 28@:NEXT
479 NEXT
499 GOTO 125
699 CLSOsPRINT TAR(29) 5"QRSTACLE” sFRINT
4619 INPUT"NAME OF PLAYER ON THE LEFT" SANS
OBSTACLE 141

626 INPUT"PLAYER ON THE RIGHT" SENS


630 RETURN
708 PRINT@9469," "5
719 IF AR<21 OR BR<1 THEN 739
72@ PRINT’ YOU BOTH LOSE!" : :RETURN
738 R$=ANSIIF AR=1 THEN R$=BNS
748 PRINT ROS" WING'S
758 RETURN
900 PRINT@A,A$sSPRINT@B,B$* sRETURN
959 FOR X=0 TO 69 STEP 3
968 PRINT@X,E$3 sPRINT@X+896 $5 NEXT
978 FOR X=@ TO 896 STEP 44
990 PRINT@X,E$s :PRINT@X+459,E $5 :NEXT
999 RETURN
1999 IF D=1 THEN X=X-é4
1916 IF t=? THEN X=X+44
1920 IF ll=3 THEN X=X~3
1930 IF U=4 THEN X=X+3
1949 R=d
1950 IF PEEK(S+X)<232 THEN R=1
1948 RETURN
EASY CHANGES

1. To speed the game up, change the 8 in line 260 toa 5 or so.
To slow it down, make it 12 or 15.
2. To make both players always start moving upward at the
beginning of each game (instead of in a random direction),
insert the following statement:
168 AD=1:BD=1
To make the players always start off moving toward each
other, use this statement instead:

168 AD=4: BD=3


3. To change the length of time that the final messages are dis-
played after each game, modify line 420. Change the 15 to 8
(or so) to shorten it, or to 25 to lengthen it.

MAIN ROUTINES

120-170 Initializes variables. Gets players’ names. Displays


titles, playing field.
180 - 200 Waits for key to be pressed to start game. Re-dis-
plays playing field.
142 BASIC Programs for the TRS-80

210 - 250 Makes move for player A (on left side) and B (on
right). Saves results.
260 - 350 Accepts moves from keyboard and translates
direction.
400 - 490 Displays winner’s name at bottom of screen.
Flashes a square where collision occurred. Goes
back to start next game.
600 - 630 Subroutine that gets each player’s name.
700 - 750 Subroutine that displays winner’s name.
900 Subroutine that displays each graphics character
of each player’s obstacle on the screen.
950- 990 Subroutine that displays playing field.
1000- 1060 Subroutine that moves marker and determines
if space moved to is empty.

MAIN VARIABLES

A Player A’s current position.


B Player B’s current position.
A$ A’s marker.
BS B’s marker.
S Starting address of CRT memory area.
AD,BD Current direction that A and B are going (1l=up,
2=down, 3=left, 4=right).
E$ Graphics character for edge of playing field.
R$ Character being read from keyboard.
X Temporary position on screen.
D Temporary direction.
AR,BR Result of A’s and B’s moves (O=okay, 1=loser).
AN$,BN$ Names of players A and B.
Z$ Graphics character displayed when collision is
made.
J,K Loop variables.

SUGGESTED PROJECTS

1. Keep score over a seven game (or so) match. Display the cur-
rent score after each game. Don’t forget to allow for ties.
2. Modify the program to let each player press only two keys—
one to turn left from the current direction of travel, and one
to turn right.
OBSTACLE 143

3. Instead of a game between two people, make it a game of a


person against the computer. Develop a computer strategy to
keep finding open areas to move to and/or to cut off open
areas from the human opponent.
144 BASIC Programs for the TRS-80
ROADRACE

PURPOSE

Imagine yourself at the wheel ofa high-speed race car winding


your way along a treacherous course. The road curves unpre-
dictably. To stay on course, you must steer accurately or risk
collision. How far can you go in one day? How many days will
it take you to race cross-country? Thrills galore without leaving
your living room.
The difficulty of the game is completely under your control.
By adjusting the road width and visibility conditions, ROAD-
RACE can be made as easy or as challanging as you wish.

HOW TO USE IT

The program begins with a short graphics display. It then asks


you for two inputs: road width and visibility. The road width
(in characters) can be set anywhere between 4 and 15. The
degree of difficulty changes appreciably with different widths.
A very narrow setting will be quite difficult and a wide one
relatively easy. Visibility can be set to any of four settings,
ranging from “‘terrible”’ to “‘good.’’ When visibility is good, the
car appears high on the screen. This allows a good view of the
twisting road ahead. When visibility is poor, the car appears
low on the screen allowing only a brief look at the upcoming
road.
Having set road width and visibility, the race is ready to start.
The car appears on the road at the starting line. A five-step
Starting light counts down the start. When the bottom light
146 BASIC Programs for the TRS-80

goes on, the race begins. The road moves continually up the
screen. Its twists and turns are controlled randomly. You must
steer the car accurately to keep it on track.
The car is controlled with the use of two keys on the key-
board. Pressing the comma (,) will cause the car to move to the
left while pressing the period (.) will cause a move to the right.
On these keys are the helpful symbols, < and >, respectively.
Doing neither will cause the car to continue straight down.
The race proceeds until the car goes “‘off the road.” Each
such collision is considered to terminate one day of the race.
After each day, you are shown the number of miles achieved
that day along with the cumulative miles achieved for consecu-
tive days of the race.
After each collision, you can proceed by pressing either C, R,
or Q. Selecting C will continue the race for another day with
the same road conditions. Cumulative totals will be retained. R
will restart the race. This allows changing the road conditions
and initializing back to day one. Q simply quits the race and
returns the TRS-80 back to direct Basic. Either of the last two
options will produce a display of the average miles travelled
per day for the race.
There are several different ways to challenge yourself with
the program. You can try to see how far you get in a given num-
ber of days. You might see how many days it takes you to goa
given number of miles—say 3000 miles for a cross-country trip.
As you become proficient at one set of road conditions, make
the road narrower and/or the visibility poorer. This will increase
the challenge. Different road conditions can also be used as a
handicapping aid for two unequally matched opponents.

SAMPLE RUN
ROADRACE 147

ROAD WIBTH (4-15)? 6_

The program displays its logo and begins the short input phase. The opera-
tor selects to run a course with a 6 character road width.

ci aCe tea)

Pet MONA U0)


iis. ta
2- BD
cima
be 1)

VISIBILITY (1-4)? 3.

The operator selects fair visibility and the race is ready to begin.
BASIC Programs for the TRS-80

The car is on the startingline. The starting light counts down the beginning
of the race. When the last light goes on, the race will be off and running.

YOU WENT 11@ MILES FOR A


TOTAL OF 315 MILES IN 3 DAY(S)

iSieaeerha bg
esi 1a td
"Y - WIT

The operator, steering the car from the keyboard, finally crashes. A dis-
tance of 110 miles is obtained on this leg for a total of 315 miles in 3 days
(legs). The options for continuing are displayed while the program waits
for the operator’s choice.
ROADRACE 149

PROGRAM LISTING

199 REM: ROADRACE


119 REM: COPYRIGHT 1979 BY PHIL FELDMAN AND TOM RUGG
129 CLEAR 209:RANDOM:Q=0:0$="""
138 LC=.45:RC=1-LC
149 LS$=CHR$(191)+CHR$(32) sRS$=CHR$(32)+CHRS (191)
159 L3="' , ee sRg=:" . oe

148 LT$=CHR$ (184 )+CHR$( 135) sRT$=CHR$ (139) +CHR$( 199)


178 B=32 sEL=2sER=58:C1=175:C2=159:DEFINT V,W
189 GOSUB 89
299 PRINT: T=@:N=9
219 INPUT"ROAD WIDTH (4-15) "SW
229 IF Wi4 OR U>15 THEN 2960
239 PRINT:PRINT"VISIBILITY CONILITIONS"
249 PRINT’ 1 - TERRIBLE"
259 PRINT” 2 - BALI”
249 PRINT’ 3 - FAIR"
279 PRINT’ 4 ~ GOOD" :PRINT
289 INPUT"VISIBILITY (1-4)"sV
299 IF V1 OR V4 THEN 289
389 NEN+1 sh =24sR=L+W+227= 16384-1284
319 C=INT((L+R)/2) sH=G
328 FOR J=1 TO 16:Q$=INKEY$:GOSUB 499:NEXT
339 GOSUB 799
539 H=H+1sQ=RND(@)sIF Q>RC AND R<ER THEN GOSUB 449:
GOTO 499
549 IF Q<LC AND L>EL THEN GOSUB 624:GOTO 499
579 GOSURB 498
499 ZC=Z+CsZP=ZC+1 sQ$=INKEY$:IF Q$=1.$ THEN C=C-1
419 IF Q$=R$ THEN C=C+1
429 IF PEEK(ZC)=B AND PEEK(2P)=B THEN POKE ZC,C1:
POKE ZP,C2:GOTO 359
439 FOR J=1 TO 82Q$=INKEY$:POKE ZC,B:POKE ZP,B:
FOR K=1 TO 59
4AD NEXT:POKE ZC,C1sPOKE ZP,C2:FOR K=1 TO S@:NEXT:NEXT
459 M=HkSsT=T+MsPRINTSPRINT"YOU WENT" SMs"MILES FOR A"
449 PRINT’ TOTAL OF"sTs"MILES IN'INS"DAY(S)"sFRINT
479 PRINT"HIT “C’ - CONTINUE RACE"
489 PRINT" “R’ - RESTART RACE"
499 PRINT” = “Q" ~~ QUIT"
396 Q$=INKEY$:IF Q$="C" THEN 36
319 IF Q$<>"R" AND Q$<>"Q" THEN 599
wd PRINT:PRINT"AVERAGE MILES PER DAY="=T/N
4d IF Q$="R" THEN 290
150 BASIC Programs for the TRS-80

wo END
699 PRINT TAB(L) SRS$;TAB(R) SLS$
619 RETURN
629 PRINT TAB(L) SLT$;TAB(R-1)sLT$
639 L=L-1:R=R-1sRETURN
649 PRINT TAB(L+1)SRT$3TAB(R) RTS
459 L=L+1:R=R+1 RETURN
709 P=Z+C:GOSUB 959:P=Z+C-15349-26
719 Q$=CHR$ (191) +CHR$(B)+"0"+CHRS(B)
+CHRS$ (191)
729 P=P-32G:PRINT @ P,STRINGS(5,176)3
739 FOR J=1 TO SsP=P+64:PRINT @ P,Q$5:NEXT
74D PRINT @ P+64,STRING$(5, 131):
70 FOR J=1 TO 6@@:NEXT
769 FOR J=4 TO @ STEP -1:FOR K=1 TO 3@0:NEXT
779 PRINT @ P+2-64#*J,CHR$(143)5:NEXT:PRINT @896,CHR$(B)
789 RETURN
889 DIM D(9)sL=18:R=28:CLS
819 FOR J=1 TO 9:READ D(J) sNEXT
829 DATA 82,79,65,48,82,65,67,69,32
839 GOSUB 499
B49 GOSUB 449
859 FOR J=1 TO 2:GOSUB 42@:NEXT
849 FOR J=1 TO 16:GOSUB 649:NEXT
879 P=15383:POKE P,C1:POKE P+1,C2
889 FOR J=1 TO S80:NEXT
899 P=P+65:GOSUB 958
999 FOR J=1 TO 2:P=P+63:GOSUB 950:NEXT
919 P=P+45:GOSUB 959
929 FOR J=1 TO 9:P=P+465:GOSUB 959
939 POKE P,D(J):POKE P+1,BsNEXT
959 POKE P,C1:POKE P+1,C2:FOR K=1 TO 5@:NEXTRETURN
EASY CHANGES

1. The keys which cause the car to move left and right can be
easily changed. You may wish to do this if you are left-
handed or find that two widely separated keys would be
more convenient. The changes are to be made in line 150.
Left and right movements are controlled by the two string
variables L$ and RS. If, for example, you wanted 1 to cause
a left move and 9 to cause a right move, change line 150 to
read
150 L$=*1":R$="9”
ROADRACE 151

2. The amount of windiness in the road can be adjusted by


changing the value of LC in line 130. Maximum windiness is
achieved with a value of 0.5 for LC. To get a straighter road,
make LC smaller. A value of O. will produce a completely
straight road. LC should lie between OQ. and 0.5 or else the
road will drift to one side and linger there. To get a somewhat
less winding road, you might change line 130 to read
130 LC=0.4: RC=1-LC

MAIN ROUTINES

120-180 Variable initialization.


200
- 290 Gets road conditions from user.
300
- 330 Initializes the road.
350
- 370 Determines the next road condition.
400
- 420 Updates the car position.
430
- 550 Processes end of race day.
600
- 650 Draws next road segment.
700
- 780 Graphics to begin race.
800
- 950 Initial graphics display.

MAIN VARIABLES

Road width.
moi2zs<=

Visibility.
Miles driven on current day.
Number of days of the race.
Total miles driven for whole race.
Elapsed time during race.
L$,R$ String characters to move car left, right.
L,R Position of left, right side of road.
LC,RC Random value cutoff to move road left, right.
EL,ER Leftmost, rightmost allowable road _ position.
Q$ User replies.
C Position of car.
Z,ZC,ZP POKE arguments for car location.
RS$,LS$ Strings to display road segments.
LT$,RT$
B Blank character value.
Pp Printing position.
D Array of POKE arguments for display message.
152 BASIC Programs for the TRS-80

J,K,Q Loop indices and work variables.


C1,C2 Graphics characters to display car.

SUGGESTED PROJECTS

1. Write a routine to evaluate a player’s performance after each


collision. Display a message rating him anywhere from
“expert” to “back seat driver.”’ This should involve comparing
his actual miles achieved against an expected (or average)
number of miles for the given road width and visibility. For
starters, you might use
Expected miles = W? + (10*V)— 35
This formula is crude, at best. The coding can be done be-
tween lines 550 and 600.
2. Incorporate provisions for two players racing one at a time.
Keep cumulative totals separately. After each collision, dis-
play the current leader and how far he is ahead.
3. Add physical obstacles or other hazards onto the road in
order to increase the challenge. These can be done with
appropriate PRINT or POKE statements before the various
RETURNs in lines 600-650. Warning: Be sure the address
arguments of any POKEs lie between 15360 and 16383.
Anything else may result in hanging up your system. The
program will recognize a collision if the car moves into any
non-blank square.
WARI

PURPOSE

Wari is an old game with roots that are even older. Its origins
go back thousands of years to a variety of other similar games,
all classified as being members of the Mancala family. Other
variations are Awari, Oware, Pallanguli, Kalah, and countless
other offshoots.
The program matches you against the computer. You are
probably going to lose a few games before you win one—the
computer plays a pretty good game. This may hurt your ego a
little bit, since Wari is purely askill game (like chess or checkers).
There is no element of luck involved, as would be the case with
backgammon, for example. When you lose, it’s because you
were outplayed.

HOW TO USE IT

When you start the program, the first thing it does is display
the Wari board and ask you if you want to go first. The board
is made up of twelve squares in two rows of six. Your side is
the bottom side, numbered one through six from left to right.
The computer's side is on the top, numbered seven through
twelve from right to left.
At the start of the game, each square has four ‘“‘stones”’ in it.
There is no way to differentiate between your stones and the
computer’s. They all look alike and will move from one side to
the other during the course of play.
The first player “picks up”’ all the stones in one of the squares
on his side of the board and drops them, one to a square, starting
154 BASIC Programs for the TRS-80

with the next highest numbered square. The stones continue to


be dropped consecutively in each square, continuing over onto
the opponent’s side if necessary (after square number 12 comes
Square number | again).
If the last stone is dropped onto the opponent’s side and
leaves a total of either two or three stones in that square, these
stones are captured by the player who moved, and removed
from the board. Also, if the next-to-last square in which a stone
was dropped meets the same conditions (on the opponent’s side
and now with two or three stones), its stones are also captured.
This continues backwards until the string of consecutive squares
of two or three on the opponent’s side is broken.
Regardless of whether any captures are made, play alternates
back and forth between the two players.
The object of the game is to be the first player to capture
twenty-four or more stones. That’s half of the forty-eight
Stones that are on the board at the beginnning of the game.
There are a few Special rules to cover some Situations that can
come up in the game. It is not legal to capture all the stones on
the opponent’s side of the board, since this would leave the
opponent with no moves on his next turn. By the same token,
when your opponent has no stones on his side (because he had
to move his last one to your side on his turn), you have to make
a move that gives him at least one stone to move on his next
turn, if possible. If you cannot make such a move, the game is
over and counted as a draw.
During the course of the game, it’s possible for a square to
accumulate twelve or more stones in it. Moving from such a
Square causes stones to be distributed all the way around the
board. When this happens, the square from which the move was
made is skipped over. So, the square moved from is always left
empty.
It takes the computer anywhere from five seconds to about
forty seconds to make a move, depending on the complexity of
the board position. The word THINKING is displayed during
this time, and a period is added to it as each possible move is
evaluated in sequence (seven through twelve).
WARI 155

SAMPLE RUN

ret
i ua
2 Wm @ 9 8 ts

1 2 3 4 3 6
yw

WANT TO GD FIRST?
YES_

The program starts off by drawing the playing ‘‘board’’ and asking who
should move first. The operator decides to go first.

Trai
Ci alia. 4
i 1} re Re 7

1 2 3 4 $5 6
yu

bita ade)
i
1) 4. Saaee

The program asks for the operator’s move. He or she decides to move
square number 5. The program alters the board accordingly, and begins
“thinking’’ about what move to make.
156 BASIC Programs for the TRS-80

ial

i 2 3 4 3 6

Later is the same game, the computer is about to move square number 11,
which will capture four more stones and win the game.

PROGRAM LISTING

1§2 REM: VARI


118 REM: COPYRIGHT 1979 BY TOM RUGG AND PHIL FELDMAN
129 CLEAR 18@:DEFINT ADI, J-T,W-Y:J=12K=1:Q=14:P=13:
F=5@s0=12
139 DIM T(Q),Y(Q) ,W(Q),V(6) ,E(4) ,B(Q)
149 RANDOM: ZB=RNDG) sZB=ZB/Q:ZA=.25+2B:2B=.25-ZB:
GOSUB 75@
159 FOR J=1 TO D:B(J)=4:NEXT:B(P)=0:B(Q)=O:MN=O:
GOSUB 1299:GOSUB 999
169 GOSUB 998s INPUT"WANT TO GO FIRST" 5R$
178 GOSUB 99G:PRINT D$:RS=LEFTS$(R$,1)s
IF R$="Y" THEN 256
188 IF R$"'N" THEN 169
199 GOSUB 1959:PRINT D$;U$'0$;:GOSUB 1959:
PRINT’ THINKING"; :GOSUB 51
195 IF M<1 THEN 2009
299 GOSUB 1950:PRINT D$;:GOSUB 1959:PRINT"MY MOVE IS"3M
218 FOR J=1 TO Q:T(J)=B(J) sNEXT:GOSUB 359
229 FOR J=1 TO Q:B(J)=T(J) sNEXT:GOSUB 999
WARI 157

259 IF B(Q)<24 THEN 259


249 GOSUB 1959sPRINT"I WIN! ";0¢:GOTO 819
2:39 GOSUB 99G3PRINT DS; 0SsGOSUB 999s INPUT" YOUR MOVE" SRS
268 M=INT(VAL(RS)) SIF M246 OR MX1 THEN 339
279 FOR J=1 TO QsT(J)=BCJ) sNEXT
239 GOSUB 359:IF M<@ THEN 339
299 FOR J=1 TO QsB(J)=T( J) sNEXT
399 MN=MN+1:GOSUB 999
319 IF B(P)<24 THEN 199
529 GOSUB 1958:PRINT"YOU WIN! "50$sGOTO 819
538 PRINT@8S2," ILLEGAL ";sFOR J=1 TO 39O80sNEXT:
GOTO 259
559 IF T(M)=@ THEN M=-1SRETURN
369 R$="H" SIF M>& THEN R$="C":GOTO 389
3/8 FOR J=1 TO Qs¥¢(J)=T(J)sNEXT:GOTO 499
389 FOR J=1 TO 6sYCJ=TC St) 2 YC S46) 270) sNEXT
596 Y(P)=T(Q) s¥(Q)=T(P) sM=M-6
ADD C=MsN=Y(C)sFOR J=1 TO NsC=C+1
419 IF C=P THEN C=1
429 IF C=M THEN C=C+1sGOTO 419
439 YCC=V¥(C)+T NEXT SY (M) =O eL=C
449 IF Le? OR Y(L)23 OR YC(L)<2 THEN 449
ASG YCPI=Y(P)4V(L) 2 Y(L)=8sL=L-1:GOTO 449
458 S=$9sFOR J=? TO IsS=S+Y¥(J) sNEXT
479 IF S=@ THEN M=-2:RETURN
489 IF R$="H" THEN FOR J=1 TO Q:T(J)=¥(J) sNEXTSRETURN
499 FOR J=1 TO 62T(J=¥ (S46) TC J+6)=9 (4) sNEXT
JOP TCQ)=Y¥(P) ST (P=Y(Q) sRETURN
19 FOR A=1 TO 6sM=A+t6:IF BC(M)=9 THEN E(A)=-F:GOTO 699
358 FOR J=1 TO QsT(J)=B(J) sNEXT:GOSUB 35¢
JAD IF M.@ THEN E(A)=-F:GOTO 499
sue TF 1(Q)723 THEN M=A+6sRETURN
360 FOR J=1 TO QeW(J)=TCJ)2NEXTSFOR K=1 TO 6
JO IF T(K)=@ THEN V(K)=F sG0TO 679
JEG FOR J=1 TO QsT(J)=WCJ) NEXT sM=K:GOSUB 359
JID IF M<@ THEN V(K)=FsGOTO 679
699 FA=9sFB=9sFC=9:FD=9:FOR J=7 TO 0
6198 FB=FB+T(J)2IF T(J)>@ THEN FA=FA+1
629 IF T(J)<3 THEN FC=FC+1
639 IF T¢(J)>F0 THEN FD=T(J)
549 NEXTSFE=FBsFOR J=1 TO 6sFE=FE+T (J) sNEXT
659 FA=FA/6sFD=1-FD/FBsFC=1-FC/ésFBR=FRB/FE
649 V(K)=ZA*(FAtFB) +ZB* (FC+FD) +7 (Q)+B(F)-B(Q)-T(P)
679 NEXTsECA)=FsFOR J=1 TO 6sIF V(J)<ECA) THEN E(A)=V(J)
489 NEXT
158 BASIC Programs for the TRS-80

699 PRINT" ."5 sNEXT:N=@:FA=~-F sFOR J=1 TO 6


799 IF EC(J)>FA THEN FA=E( J) sM=J+6
?19 NEXT sRETURN
73@ AS=""SFOR J=1 TO 36:AS=AS$+CHRS (176) NEXT
769 R$=CHR$ (1/79) sFOR J=1 TO 6:BS=BS+" "+CHR$ (179):
NEXT
779 C$=CHR$ (179) 21$=CHR$(175)+CHR$(176) FOR J=1 TO 4
?89 C$=C$+D$4D$+CHR$ (176) +CHR$ (184)
799 NEXT:D$="_ "FOR J=1 TO S:D$=0$40$:NEXT:RETURN
819 PRINT"GOOD GAME!"
849 INPUT"WANT TO PLAY AGAIN’ SRS
B59 R$=LEFT$(R$,1):IF R$="Y" THEN 124
Bdd IF R$<>"N" THEN 849
8,9 PRINT:PRINT"SEE YOU LATER"
889 PRINT sEND
999 FOR J=8 T0 5
919 PRINT@(322+J#6) ,B(12-J) 3
929 IF B(12-J)-@ THEN GOSUB 1199
938 NEXT :PRINT@3467, "COMPUTER "B(Q)!
949 FOR J=@ TO 5
959 PRINT@(5144+3#6) ,B(J+1)¢21F B(J+1)=@ THEN GOSUB 1199
969 NEXT=PRINT@564, "YOU "SR(P)ssRETURN
999 PRINT@932," "!:RETURN
1959 PRINT@896," "t sRETURN
1189 PRINT CHR$(24)5" "= sRETURN
12989 CLS:PRINT TAB(30)3"W A RI"
12298 PRINT TAB(14) "COMPUTER"
1238 FOR J=9 TO S:PRINT TAR(S#J+2)212-J¢sNEXT
1249 PRINT@192,CHR$(169) SsPRINT ASS TAR(S@)
s "CAPTURED"
12598 FOR J=1 TO 2:PRINT B$:PRINT B$:PRINT C$:NEXT
12698 FOR J=@ TO SPRINT TAB(6*J+2) sJ4+1¢:NEXT
1279 PRINT:PRINT TAB(17) "YOU" RETURN
2999 PRINT"NO LEGAL MOVES.":GOTO 849
EASY CHANGES

1. If youhave a 4K TRS-80, you'll need to delete lines 100, 110,


an d 180 to make this program fit in your computer. Line 870
can also be deleted if you need more room to make other
changes.
2. Want a faster moving game against an opponent who isn’t
quite such a good player? Insert the following two lines:
555 GOTO 600
665 E(A)=V(K):GOTO 690
WARI 159

In the standard version of the game, the computer looks at


each of its possible moves and each of your possible replies
when evaluating which move to make. This change causes
the computer to only look at each of its moves, without
bothering to look at any of your possible replies. As a result,
the computer does not play as well, but it takes only a few
seconds to make each move.
. If you are curious about what the computer thinks are the
relative merits of each of its possible moves, you can make
this change to find out. Change line 690 so it looks like this:
690 PRINT E(A);: NEXT: M=0: FA=—F:FOR J=1 TO 6
This will cause the program to display its evaluation number
for each of its moves in turn (starting with square seven). It
will select the largest number of the six. A negative value
means that it will lose stones if that move is made, assuming
that you make the best reply you can. A value of negative 50
indicates an illegal move. A positive value greater than one
means that a capture can be made by the computer, which
will come out ahead after your best reply.

MAIN ROUTINES

120-150 Initializes variables. Displays board.


160- 180 Asks who goes first. Evaluates answer.
190- 220 Determines computer’s move. Displays new board
position.
230 - 240 Determines if computer’s move resulted in a win.
Displays a message if so.
250- 300 Gets operator’s move. Checks for legality. Dis-
plays new board position.
310-320 Determines if operator’s move resulted in a win.
330 Displays message if illegal move attempted.
350 - 500 Subroutine to make move M in T array.
360 - 390 Copies T array into Y array (inverts if computer
is making the move).
400 - 430 Makes move in Y array.
440-450 Checks for captures. Removes stones.
Checks previous square.
460 - 470 Sees if opponent is left with a legal move.
480 - 500 Copies Y array back into T array.
510-710 Subroutine to determine computer’s move.
160 BASIC Programs for the TRS-80

750 - 790 Subroutine to create graphics strings for board


display.
810- 880 Displays ending message. Asks about playing again.
900- 960 Subroutine to display stones on board and cap-
tured.
990 Subroutine to move cursor to “YOUR MOVE”
position on screen.
1050 Subroutine to move cursor to “MY MOVE” posi-
tion on screen.
1100 Subroutine to backspace cursor one space and dis-
play one blank character.
1200 - 1270 Subroutine to display Wari board (without stones).
2000 Displays message when computer has no legal
move.

MAIN VARIABLES

J,K Subscript variables.


Q,P,F,D Constant values of 14, 13, 50 and 12, respectively.
T,Y,W Arrays with temporary copies of the Wari board.
V Array with evaluation values of operator’s six
possible replies to computer’s move being con-
sidered.
Array with evaluation values of computer’s six
possible moves.
Array containing Wari board. Thirteenth element
has stones captured by operator. Fourteenth has
computer’s.
ZA,ZB Weighting factors for evaluation function.
MN Move number.
R$ Operator’s reply. Also used as switch to indicate
whose move it is (C for computer, H for human).
Move being made (1 - 6 for operator, 7 - 12 for
computer). Set negative if illegal.
Subscript used in dropping stones around board.
Last square in which a stone was dropped.
Stones on opponent’s side of the board after a
move.
Subscript used to indicate which of the six
possible computer moves is currently being
evaluated.
FA First evaluation factor used in determining favora-
WARI 161

bility of board position after a move (indicates


computer’s number of occupied squares).
FB Second evaluation factor (total stones on compu-
ter’s side of the board).
FC Third evaluation factor (number of squares with
two or less stones).
FD Fourth evaluation factor (number of stones in
most populous square on computer’s side).
FE Total stones on board.
A$,B$,C$ Strings of graphics characters used to display the
Wari board.
D$ String of thirty-two blanks.

SUGGESTED PROJECTS

1. Modify the program to declare the game a draw if neither


player has made a capture in the past thirty moves. Line 300
adds one to the counter of the number of moves made. To
make the change, keep track of the move number of the last
capture, and compare the difference between it and the cur-
rent move number with 30.
2. Modify the evaluation function used by the computer strategy
to see if you can improve the quality of its play. Lines 600
through 660 examine the position of the board after the
move that is being considered. Experiment with the factors
and/or the weighting values, or add a new factor of your own.
3. Change the program soit can allow two people to play against
each other, instead of just a person against the computer.
162 BASIC Programs for the TRS-80
Section 4
Graphics Display Programs

INTRODUCTION TO GRAPHICS DISPLAY PROGRAMS

The TRS-80 is an amazing machine. It has very useful graphics


capabilities in addition to its other capacities. Programs in the
other sections of this book take advantage of these graphics to
facilitate and ‘“‘spice up” their various output. Here we explore
the use of the TRS-80’s graphic capabilities for sheer fun,
amusement, and diversion.
Ever look through a kaleidoscope and enjoy the symmetric
changing patterns produced? KALEIDO will create such effects
with full eight point symmetry.
Two other programs produce ever changing patterns but with
much different effects. SPARKLE will fascinate you with a
changing shimmering collage. SQUARES uses geometric shapes
to obtain its pleasing displays.
WALLOONS demonstrates a totally different aspect of the
TRS-80. This program will keep you entertained with an exam-
ple of computer animation.
164 BASIC Programs for the TRS-80
KALEIDO

PURPOSE

If you have ever played with a kaleidoscope, you were pro-


bably fascinated by the endless symmetrical patterns you saw
displayed. This program creates a series of kaleidoscope-like
designs, with each one overlaying the previous one. Some of the
designs are symmetrical about eight axes (others about four)—
can you find them?

HOW TO USE IT

There is not much to say about how to use this one. Just
type RUN, then sit back and watch. Turning down the lights
and playing a little music is a good way to add to the effect.
By the way, it is a little misleading to say that the designs
you see are symmetrical. It is more accurate to say that the
positions occupied by the individual graphics characters are
located symmetrically. The overall design is usually not com-
pletely symmetrical, since the individual graphics characters are
not themselves symmetrical. The characters on the lower half of
the design would have to be the upside-down equivalent of the
corresponding characters on the upper half for that to be true.
Have a few friends bring their TRS-80s over (all your friends
do have TRS-80s, don’t they?), and get them all going with
KALEIDO at once. Let us know if you think you have set a
new world’s record. Please note that we will not be responsible
for any hypnotic trances induced this way.
166 BASIC Programs
for the TRS-80

SAMPLE RUN

One of the patterns generated by the KALEIDO program.

PROGRAM LISTING
198 REM: KALEIDOSCOPE
118 REM: COPYRIGHT 1979 BY TOM RUGG AND PHIL FELIMAN
129 CLEAR S@:RANDOMSCLS:DEFINT A-Z
139 A=477 :T=~1
135 W=42S=7 sL=64 sM2=22:G=169
149 DIM R$(S)
159 FOR J=9 TO SsA$=""sFOR K=1 TO W
169 AS=AS+CHRS (RNU(M)+G) sNEXT
179 R$(J)=A$ sNEXT
189 D=-D
199 P=9:Q=S:IF D048 THEN Q=9:P=S
289 FOR K=P TO @ STEP 0
219 FOR J=K TO Q STEP D
229 PRINT@A+J#U+K#L ROCK) 5 SPRINT@GATK#U+J#L RS (K) 5
2398 PRINT@A+J#U-K#L ROCK) 5 SPRINT@ATK#W-J#L yRSCK) 5
248 PRINT@A~J#W+K#L ,RE(K) 5 sPRINT@A-K#U+ JL »RS(K) 5
258 PRINT@A-J#W-K#L RS (CK) 5 sSPRINT@A-K#W-J#L RSCK) |
268 NEXT sNEXT
388 GOTO 159
KALEIDO 167

EASY CHANGES

1. To clear the screen before the next pattern about 20% of the
time (chosen at random), insert this:
175 IF RND(100)<=20 THEN CLS
For 50%, use 50 instead of 20, etc.
2.To randomly select either a square or rectangular pattern,
insert:
176 W=RND(2)+2
To always get a square pattern, use this instead:
176 W=3
3. To randomly change the size of the patterns, insert:
177 S=RND(4)+3
4. To cause only the outward patterns to be displayed, change
line 180 to say |
180 D=1
To cause only inward patterns, change it to say
180 D=-1
5. To alter the intricacy of the graphics characters used in the
patterns, alter the values of M and Gin line 135. Be sure both
are positive integers, that G is at least 127, and that the sum
of M and G does not exceed 191. For example, try M=64 and
G=127. Or, try M=16 and G=127. Or, M=4 and G=187.
6. To lengthen the delay after each pattern is drawn, insert this
line:
270 FOR J=1 TO 3000:NEXT
Use a number larger than 3000 to increase the length of the
delay even more.
Note: These changes add a lot of the appeal of the designs. Ex-
periment! Each change can be done by itself or in combination
with other changes.

MAIN ROUTINES

120- 140 Housekeeping. Initializes variables, RND.


150-170 Picks S+l random graphics characters, each W
characters wide.
180 Reverses direction of display (inward-outward).
168 BASIC Programs for the TRS-80

190 - 260 Displays a full screen of the pattern.


300 Goes back to create next pattern.

MAIN VARIABLES

Pointer to center of design.


Direction in which design is drawn (1=outward,
—]=inward).
Width of each graphics string.
Size of one-quarter of the pattern.
Length of one line on the screen (64).
Multiplier used to determine the range of random
graphics characters.
Low number in range of random graphics charac-
ters.
Array for the S random graphics strings.
Subscript variables.
Inner and outer bounds of design (distance from
center).
Temporary string variable used to build graphics
strings.
SPARKLE

PURPOSE

This graphics display program provides a continuous Series of


hypnotic patterns, some of which seem to sparkle at you while
they are created. Two types of patterns are used. The first is a
set of concentric diamond shapes in the center of the screen.
Although the pattern is regular, the sequence in which it is
created is random, which results in the “‘sparkle”’ effect.
The second type of pattern starts about two seconds after the
first has finished. It is a series of ““sweeps”’ across the screen—left
to right and top to bottom. Each sweep uses a random graphics
character that is spaced equally across the screen. The spacing
distance is chosen at random for each sweep. Also, the number
of sweeps to be made is chosen at random each time in the
range from 11 to 30.
After the second type of pattern is complete, the program
goes back to the first type, which begins to overlay the center
of the second type.

HOW TO USE IT

Confused by what you just read? Never mind. You have to


see it to appreciate it. Just enter the program into your TRS-80,
then sit back and watch the results of your labor.
170 BASIC Programs
for the TRS-80

SAMPLE RUN

A UNA, bli Py

mane
™ Wy
Wa aged
SO ho eT
THY Se

Peery

eye

One of the patterns generated by the SPARKLE program.

PROGRAM LISTING
188 REM: SPARKLE
119 REM: COPYRIGHT 1979 BY TOM RUGG AND PHIL FELDMAN
128 CLEAR S@sRANDIOMSCLS:REFINT A-Z
136 DIM AC?),B(7) 2A=19sB=7 sS=G
149 T=RND (49) +139
159 FOR J#@ TO 7sA(J)=J2B( Js JsNEXT
1469 FOR J=@ TO 7sR=RND(8)-12WeAC J) sAC J =A(R)
178 ACR) =WUsNEXT
188 FOR J=8 TO 7:R=RNDIM8)-12W=B(J)2B(J)=B(R)
199 B(R)=WeNEXT
299 FOR J=@ TO 7sFOR K=@ TO 7?
21g R=A (J) sW=BCK) sC=R+W+T
246 X=A+RsY=BtWsGOSUB 99¢
259 Y=E-W:GOSUB 99¢
269 X=A-R:GOSUB 998
279 Y=B+W:GOSUB 999
289 X=A+W2Y=B+RsGOSUB 999
299 Y=B-RsGOSUB 989
399 X=A-W:GOSUB 999
318 Y=B+K:GOSUB 996
SPARKLE 171

528 NEXT sNEXT


339 FOR J=1 TO 2889sNEXT
ADD N=128 24=64
419 FOR J=1 TO RND(28)+19¢
429 R=RNDC17)4#2 sW=RNDCM)
439 T=SsIF RNICG)>.8 THEN T=T+2
449 AS=CHRS (N+W) +CHRS (N+W) SPRINT@S,
AS;
439 FOR K=T TO S+1921 STEP R
459 PRINTG@K , A$ 5
479 NEXT sNEXT
489 GOTO 1498
789 AS=CHRS$ (C)+CHRS$(C)+CHRS(C)
919 PRINT@S+464*Y+3X ,AS5 SRE TURN
929 PRINT@S+44#7434#X+2 ,CHRS(C) 5
939 RETURN

EASY CHANGES

|. Make the second type of pattern appear first by inserting this


line:
135 GOTO 400
Or, eliminate the first type of pattern by inserting:
145 GOTO 400
Or, eliminate the second type of pattern by inserting:
360 GOTO 140
. Increase the delay after the first type of pattern by increasing
the 2000 in line 350 to, say, 5000. Remove line 350 to
eliminate the delay.
. Increase the number of sweeps across the screen of the second
type of pattern by changing the 10 at the right end of line
410 into a 30 or a 5O, for example. Decrease the number of
sweeps by changing the 10 to a 1, and also changing the 20 in
line 410 to 5 or 10.
4. Watch the effect on the second type of pattern if you change
the 17 in line 420 into various integer values between 2 and
100.
5. Change the values of N and M in line 400 to alter the graphics
characters used in the second type of pattern. For example,
try

N=128 and M=5


or, N=142 and M=20
172 BASIC Programs for the TRS-80

Be sure that N is at least 127, and the sum of N and Mis no


more than 192.

MAIN ROUTINES

120- 130 Initializes variables. Clears screen.


140 - 320 Displays square pattern in center of screen.
150-190 Shuffles the numbers O through 7 in the A and B
arrays.
200 - 320 Displays graphics characters on the screen.
350 Delays for about 2 seconds.
400 - 480 Overlays the entire screen with a random graphics
string spaced at a fixed interval chosen at random.
900 - 930 Subroutine to display graphics string A$ at loca-
tion (X,Y). Upper left corner of screen is location
(0,0).

MAIN VARIABLES

Random integer. Also, work variable.


Arrays in which shuffled integers from 0 to 7 are
stored for use in making first type of pattern.
Coordinates of center of screen (10 across,7 down).
Address of beginning of screen.
Integer from 131 to 170, used in creating random
graphics characters. Also, work variable.
Work and loop variables.
Work variable.
Coordinates of a position on the screen for a
graphics string.
Graphics character to be displayed on screen at
X,Y.
Lowest graphics character to be used in second
type of pattern.
Multiplier used in getting a random integer to add
to N.

SUGGESTED PROJECTS

Make the second type of pattern alternate between ‘‘falling


from the top” (as it does now) and rising from the bottom of
the screen.
SQUARES

PURPOSE

This is another graphics-display program. It draws a series of


concentric squares and rectangles, with the graphics character
used for each one chosen at random. After a full set of concen-
tric squares is drawn, the next set starts again at the center and
overlays the previous one. Each set may be a narrow rectangle,
wide rectangle, or square, chosen at random.

HOW TO USE IT

As with most of the other graphics display programs, you just


sit back and enjoy watching this one once you get it started.
174 BASIC Programs for the TRS-80

SAMPLE RUN

CETTE
pee

One of the patterns generated by the SQUARES program.

PROGRAM LISTING

189 REM: SQUARES


119 REM: COPYRIGHT 1979 BY TOM RUGG AND PHIL FELDMAN
129 CLEAR S@sDEFINT A-Z:RANDOM:CLS
139 N=1:W=RND(4) sL=488-U
148 C=RND(464)+127 :AS=CHRS(C)
158 CS=STRINGS(U,AS)
179 FOR J=1 TO WANsPRINT@GL AS; sL=L+1 NEXT
189 N=N+1
199 FOR J=1 TO NsPRINT@L C$): L=L-64sNEXTsL=L+63
298 FOR J=1 TO W#NsPRINTG@L,AS sls “ NEXT#L=L+65
218 N=N-1
229 FOR J=1 TO NePRINT@L
,C$5 sL=L+64:NEXT
238 N=N+2
246 IF N<14 THEN 149
258 FOR J=1 TO 180@:NEXT
269 GOTO 138
SQUARES 175

EASY CHANGES

1. Change the delay after each set of patterns by changing the


1000 in line 250. A bigger number causes a longer delay.
2. To cause the patterns to be only overlaying squares (i.e., no
variation in width), change line 130 to say:
130 N=1:W=3:L=480—W
3. To occasionally blank out the screen (about 20% of the time),
insert this:
255 IF RND(100)<=20 THEN CLS

MAIN ROUTINES

120 Housekeeping. Clears screen.


130 Initializes counters for the pattern. Points to the
center of the screen.
140
- 150 Picks a graphics character and creates a string of
W repetitions of it.
170 Draws the bottom side of the square.
190 Draws the right side.
200 Draws the top side.
220 Draws the left side.
240 Tests if the outermost square has been drawn.
250 Delays about one second.
260 Goes back to start at the center again.

MAIN VARIABLES

Length of the side currently being drawn.


r= Zz

Width of the vertical sides of the square (1 to 4).


Location on the screen where characters are cur-
rently being displayed.
Numeric equivalent of the random graphics char-
acter chosen.
A$ String representation of the random graphics
character.
C$ String of W consecutive copies of the graphics
character.
Loop variable.
176 BASIC Programs for the TRS-80
WALLOONS

PURPOSE

The TRS-80 is quite a versatile machine. This program takes


advantage of its powerful graphics capability to produce com-
puter animation. That’s right, animation! WALLOONS will
entertain you with a presentation from the TRS-80 Theatre.
The TRS-80 Theatre searches the world over to bring you the
best in circus acts and other performing artists. Today, direct
from their performance before the uncrowned heads of Europe,
the Theatre brings you the Flying Walloons.

HOW TO USE IT

Just sit back, relax, and get ready to enjoy the show. Type
RUN and the Flying Walloons will be ready to perform. You
have a front row center seat and the curtain is about to go up.
Applause might be appropriate if you enjoy their performance.
Please note that the Walloons have been working on a big new
finish to their act which they haven’t yet quite perfected.
178 BASIC Programs for the TRS-80

SAMPLE RUN

The billboard announces a new presentation of the (in)famous TRS-80


Theatre.

FLYING

HALLOONS

“The Flying Walloons” are to perform!


WALLOONS 179

XK

ae
oe
The Walloons attempt a dangerous trick from their repertoire.

PROGRAM LISTING

199 REM: WALLOONS


119 REMSCOPYRIGHT 1979 BY PHIL FELDMAN ANI TOM RUGG
138 CLEAR 319:0=64:3E=128
299 NS=CHRS (32) sK$=CHRS (149) 5K1S=CHRS (131):
K2$=CHRS(191)
218 BS=K1$+CHR$ (177 +K2$4+CHRS (151 +K1$3
TS$=K$S+CHRS (188) +K$
228 C$=CHRS (184) +CHRS (135) +NS4CHRS (139) +CHRS (189)
239 L$=STRINGS (3,176) sM$=STHINGS (3,149)
246 US=STRINGS (3,131) sS$=NS4NS 2AS=S$+CHRS (198):
WS=LS+MS+US
258 N$=S$+CHRS$(188)+STRINGS(15,N$) +US
268 ES=BS+5S+5S+L $+ TS+US 2 YS=SS+5$4NG 27 1$=STRINGS (8, 32)
278 £9=CHRS (149) +CHRS (199) +K2$+CHR$ (189) +CHRS$( 144)
289 FS=CHR$ (184) +CHRS (183) +CHRS (176) 4CHRS (143) 4K$
299 FS=FS+KS+US+99+2$ sG$=STRINGS (18 NS) +US
329 JS$=US+SS+ICHRS (149) +CHRS (198) +K2$+CHRS (189)
338 J$=JS$+CHRS (144) sHP=STRINGS (9 NS) +L S+T$+US
549 T1S=US+M$+L $+STRINGS(15,N$) +CHRS (188)
373 E1$=STRINGS (9 NS )+US+TS+LS+SS+S9+R$
388 FIS=STRINGS (11 NS) 4Z$4+SS+UStKS+KS
180 BASIC Programs for the TRS-80

399 F1$=F1$+CHRS (143) +CHR$ (176) +CHRS (187) +CHRS (199)


499 V1$=CHR$ (131) #KS+CHRS (176) +CHR$ (169) +CHRS (176)
419 V1$=V1$4+CHRS (198) V2$S=NS+CHRS (176) +K$+CHRS (139)
429 V2$=Y2$+4+CHR$ (143) +K294K194K1$
439 V3$=CHR$ (172) +CHRS (144) +NS+CHRS (169) +CHRS (156)
449 V4$=N$+CHR$ (171) +CHRS$(198)+CHRS$ (151)
459 USS=K1$+K1S4K2$-+K1S4K1$
479 GOSUB 1394:GOSUB 1499:GOSUR 189¢
JOG CLS:L=783:GOSUB 9996:GOSUB 1899:FOR H=770 TO 782:CLS
319 GOSUB 989:GOSUB 919:NEXT:CLS:GOSUB 920:GOSUB 1899
WM FOR H=298 TO 319:PRINT@H,K1$:NEXT:H=123:GOSUB 919
949 GOSUB 18@9:GOSUB 1299:H=191:GOSUB 919
399 FOR J=1 TO 4
499 H=191:FOR K=1 TO 8:GOSUB 949:H=H+D:GOSUB 91¢
619 NEXT :H=591sCLS:GOSUB 939:GOSUB 919:FOR K=1 TO 8
629 GOSUB 949:H=H-D:GOSUB 919:NEXT:FOR K=1 TO 8:
GOSUB 949
639 H=H+D:GOSUB 919:NEXT:H=413:CLS:GOSUB 926:GOSUB 919
649 FOR K=1 TO 8:GOSUB 94@:H=H-D:GOSUB 919:NEXT=:NEXT
789 FOR K=1 TO 3:GOSUB 94@:H=H+1:GOSUB 91@:NEXT
718 FOR K=1 TO 8:GOSUB 94@:H=H+D:GOSUB 919:NEXT
729 GOSUB 949:H=L-37:GOSUB 959:GOSUB 970:H=H+6é6:
GOSUB 969
898 GOSUBR 1899:CLS:FRINT CHR$(23)
819 PRINT@448,"F I N I S"sGQSUR 18@0:CLS:END
789 PRINT@L,G$$ sPRINT@GL+D,H$3 :PRINT@L+E ,J$5 sRETURN
918 PRINT@H, ASS SPRINTGH+D, B$* sPRINT@H+E ,C45 RETURN
929 PRINTGL , Ii$s :PRINT@L+D,E$5 :PRINT@L+E,F$* sRETURN
939 PRINTG@L ,1$7:PRINT@L+D,E1$3 :PRINT@L+E,F1$% sRETURN
749 PRINTGH, Y$3 :PRINTGH+I!, Y$; :PRINT@H+E, $$ :RETURN
958 PRINT@H,V1$3 sPRINTGH+D,V2$s sPRINTGH+E ,K1$5 RETURN
969 FRINTGH, V3$s :PRINT@H+D,U4$5 SPRINTGH+E ,V5$" sRETURN
979 PRINT@H, Y1$%:PRINTGH+D, Y1$5 :PRINT@H+E, ¥1$3 :RETURN
1298 FOR H=123 TO 197 STEP -1:GOSUB 919:GOSUER 94¢sNEXT
1219 GOSUR 918:GOSUB 1899:FOR J=1 TO 3:GOSUBR 949:H=H-1
1229 GOSUB 919:NEXT:GOSUB 189@:FOR J=1 TO 6:GOSUB 949:
H=H+1
12.39 GOSUB 9192NEXT:FOR K=1 TO SOO:NEXT
1249 FOR J=1 TO 8:PRINT@H,SS+N$5:sFOR K=1 TO SOsNEXT
1259 PRINT@H,A$;SFOR K=1 TO SOSNEXTSNEXT:GOSUB 18989
1269 FOR J=1 TO 8:GOSUB 94@:H=H-1:GOSUB 914:NEXTSRETURN
1399 CLSSPRINT CHRS$(23) sH=33462US=CHRS$ (143)
1319 FRINT@H,"TRS-89 THEATRE" SPRINT@H+E," PROUDLY”
1339 FRINT@H+E+E,' PRESENTS"
1349 FOR J=208 TO 242 STEP 2:PRINT@J, USENEXT
WALLOONS 181

1358 FOR J=299 TO 712 STEP DsPRINT@J,K2$3 sNEXT


1368 FOR J=242 TO 754 STEP DsPRINT@J,K2%% sNEXT
1378 FOR J=712 TO 754 STEP 2:PRINT@J,U$5 =NEXT
1388 GOSUB 1899:FOR J=9 TO 26:PRINT@HtE+J,"-"s
1399 FOR K=1 TO 9MSNEXTSNEXT:GOSUB 1889sRETURN
1499 M$="F LY IN G'sUS="W ALL NS":
US=STRINGS$ (16,32)
1419 L$="T H E"sCLSsPRINT CHR$(23):
FOR J=398 TO 268 STEP ~-2
1428 PRINT@J,W$sGOSUB 1799:PRINT@J,L$=sNEXT
1439 FOR J=552 TO 524 STEP ~2:PRINT@J,WS:GOSUB 1799:
PRINT@J,M$
1449 NEXT:FOR J=892 TO 788 STEP -2:PRINT@J,WS:
GOSUB 1/989
1459 PRINT@J,USsNEXT:GOSUBR 1899:FOR J=34 TO 748 STEP D
1468 PRINT@J,"0'"5 sGOSUB 1798:PRINT@J,N$; SNEXT:
PRINT@894,"0"3
1474 FOR J=49 TO 744 STEP DsPRINT@J,"0"s:GOSUB 1799
1486 PRINT@J,N$s SNEXT:PRINT@S98, "0" s sRETURN
1768 FOR K=1 TO 12:NEXT:RETURN
1809 FOR I=1 TO 149@:NEXT:RETURN

EASY CHANGES

l. If you wish to have the Walloons perform more (or less)


jumps during their performance, change the loop bound value
of 4 in line 590 accordingly. To get six jumps, use
590 FOR J=1 TO 6
. Timing delays are used often in the program. To change the
length of the delay, alter the 1400 in line 1800 to a different
value. Values larger than 1400 will lengthen the delays, while
values smaller than 1400 will shorten the delays.
. You might want to personalize the title placard and make
yourself the presenter of the Walloons. This can be done by
altering the string literal, ‘““TRS-80 THEATRE” in line 1310
to something else. However, you cannot use a string with a
length of much more than 16 characters or it will print
beyond the end of the placard. To say, for example, that
Simon Fenster presents the Walloons, change line 1310 to:
1310 PRINT @H,‘“SIMON FENSTER”:
PRINT@Ht+E,”’ PROUDLY”
182 BASIC Programs for the TRS-80

MAIN ROUTINES
150 Initializes.
200 - 450 Sets string variables.
470 Introduces the Walloons.
500 - 540 The Walloons make their entrance.
590 - 640 Flying Walloons perform.
700 - 720 Concludes Walloon’s performance.
800 - 810 Displays final message.
900 - 970 Subroutines to draw (and erase) Walloons and
their performing lever.
1200-1260 Subroutine for second Walloon’s entrance.
1300-1390 Subroutine to display placard.
1400-1480 Subroutine to announce the performers.
1700-1800 Time delaying subroutines.

MAIN VARIABLES
A$-Z$ Various graphics strings.
D,E Position increments for graphics displays.
L Location of lever’s left end.
H Location of Walloon’s head.
LJ,K Loop indices.

SUGGESTED PROJECTS
1. There are many possibilities for “‘spicing up’? the Walloons’
act with extra tricks or improved ones. Perhaps you would
like to change their finish to something less crude. To get
you started, here are the changes to produce one alternate
ending:
650 GOTO 730
730 GOSUB 940: H=H—D:GOSUB 910:GOSUB 940
740 PRINT@H,B$:PRINT@H+D,C$:[email protected]$
750 PRINT@H+D, Y$:PRINT@H,C$:PRINT@H,Y$
. If you add some alternate tricks or endings as suggested in
the previous project, try randomizing if and when they will
be done. Thus, the Walloons’ performance will be different
each time the program is run. At least their ending may be
variable.
3. Scour the world yourself for other acts to include in the
TRS-80 Theatre. Maybe someday we will have a complete
software library of performing artists.
Section 5
Mathematics Programs

INTRODUCTION TO MATHEMATICS PROGRAMS

Since their invention, computers have been used to solve


mathematical problems. Their great speed and reliability render
solvable many otherwise difficult (or impossible) calculations.
Several different numerical techniques lend themselves naturally
to computer solution. The following programs explore some of
them. They will be of interest mainly to engineers, students,
mathematicians, statisticians, and others who encounter such
problems in their work.
GRAPH takes advantage of the TRS-80’s graphic powers to
draw the graph of a function Y = f(X). The function is supplied
by you. INTEGRATE calculates the integral, or ‘“‘area under the
curve,” for any such function.
Experimental scientific work frequently results in data at
discrete values of X and Y. CURVE finds a polynomial alge-
braic expression to express this data with a formula.
Theoretical scientists (and algebra students) often must find
the solution to a set of simultaneous linear algebraic equations.
SIMEQN does the trick.
Much modern engineering work requires the solution of
differential equations. DIFFEQN will solve any first-order
ordinary differential equation that you provide.
STATS will take a list of data and derive standard statistical
information describing it. In addition, it will sort the data list
into ranking numerical order.
184 BASIC Programs for the TRS-80
CURVE

PURPOSE AND DISCUSSION

CURVE fits a polynomial function to a set of data. The data


must be in the form of pairs of X-Y points. This type of data
occurs frequently as the result of some experiment, or perhaps
from sampling tabular data in a reference book.
There are many reasons why you might want an analytic
formula to express the functional relationship inherent in the
data. Often you will have experimental errors in the Y values. A
good formula expression tends to smooth out these fluctuations.
Perhaps you want to know the value of Y at some X not ob-
tained exactly in the experiment. This may be a point between
known X values (interpolation) or one outside the experimental
range (extrapolation). If you wish to use the data in a computer
program, a good formula is a convenient and efficient way to do
it.
This program fits a curve of the form

Y=Co +C,X! +C,X? +...+C)X?


to your data. You may select D, the degree (or power) of the
highest term, to be as large as 9. The constant coefficients,
Co - C,, are the main output of the program. Also calculated is
the goodness of fit, a guide to the accuracy of the fit. You may
fit different degree polynomials to the same data and also ask to
have Y calculated for specific values of X.
The numerical technique involved in the computation is
known as least squares curve fitting. It minimizes the sum of the
squares of the errors. The least squares method reduces the
186 BASIC Programs for the TRS-80

problem to a set of simultaneous algebraic equations. Thus


these equations could be solved by the algorithm used in
SIMEQN. In fact, once the proper equations are set up, CURVE
uses the identical subroutine found in SIMEQN to solve the
equations. For more information, the bibliography contains
references to descriptions of the numerical technique.

HOW TO USE IT

The first thing you must do, of course, is enter the data into
the program. This consists of typing in the pairs of numbers.
Fach pair represents an X value and its corresponding Y value.
The two numbers (of each pair) are separated by a comma. A
question mark will prompt you for each data pair. After you
have entered them all, type
999,999
to signal the end of the data. When you do this, the program
will respond by indicating how many data pairs have been
entered. A maximum of 30 data pairs is allowed.
Next, you must input the degree of the polynomial to be
fitted. This can be any non-negative integer subject to certain
constraints. The maximum allowed is 4. Also, D must be less
than the number of data pairs.
A few notes regarding the selection of D may be of interest.
If D=0, the program will output the mean value of Y as the
coefficient Cy. If D=1, the program will be calculating the best
straight line through the data. This special case is known as
‘‘linear regression.’ If D is one less than the number of data
pairs, the program will find an exact fit to the data (barring
round-off and other numerical errors). This is a solution which
passes exactly through each data point.
Once you have entered the desired degree, the program will
begin calculating the results. There will be a pause while this
calculation is performed. The time involved depends on the
number of data pairs and the degree selected. For twenty data
pairs and a second degree fit, the pause will be about fifteen
seconds. Thirty data pairs and a fourth degree fit will take
about forty-five seconds.
The results are displayed in a table. It gives the values of the
coefficients for each power of X from O to D. That is, the values
of Co - Cp) are output. Also shown in the percent goodness of
CURVE 187

fit. This is a measure of how accurately the program was able to


fit the given case. A value of 100 percent means perfect fit,
lesser values indicate correspondingly poorer fits. It is hard to
say what value denotes satisfactory fit since much depends on
the accuracy of data and the purpose at hand. But as a rule of
thumb, anything in the high nineties is quite good. For those
interested, the formula to calculate the percent goodness of fit
is

= (Y, ¥;)?
P.G.F= 100 * 1 - -
zy, - YP
1

where Y, are the actual Y data values, v. are the calculated Y


values (through the polynomial expression), and Y is the mean
value of Y.
To continue the run, hit any key when requested to do so.
Next, you are presented with three options for continuing the
run. These are 1) determining specific points, 2) fitting another
degree, 3) ending the program. Simply type 1, 2, or 3 to make
your selection. A description of each choice now follows.
Option | allows you to see the value of Y that the current fit
will produce for a given value of X. In this mode you are con-
tinually prompted to supply any value of X. The program then
shows what the polynomial expression produces as the value for
Y. Input 999 for an X value to leave this mode.
Option 2 allows you to fit another degree polynomial to the
same data. Frequently, you will want to try successively higher
values of D to improve the goodness of fit. Unless round-off
errors occur, this will cause the percent goodness of fit to
increase.
Option 3 simply terminates the program and with that we
will terminate this explanation of how to use CURVE.

SAMPLE PROBLEM AND RUN

Problem: An art investor is considering the purchase of


Primo’s masterpiece, “‘Frosted Fantasy.’’ Since 1940, the
painting has been for sale at auction seven times. Here is the
painting’s sales record from these auctions.
188 BASIC Programs for the TRS-80

Year Price
1940 $ 8000.
1948 $13000.
195] $16000.
1956 $20000.
1962 $28000.
1968 $39000.
1975 $53000.
The painting is going to be sold at auction in 1979. What price
should the investor expect to have to pay to purchase the
painting? If he resold it in 1983, how much profit should he
expect to make?
Solution: The investor will try to get a polynomial function
that expresses the value of the painting as a function of the year.
This is suitable for CURVE. The year will be represented by the
variable X, and the price is shown by the variable Y. To keep
the magnitude of the numbers small, the years will be expressed
as elapsed years since 1900, and the price will be in units of
$1000. (Thus a year of 40 represents 1940, a price of 8 repre-
sents $8000.)

SAMPLE RUN

- LEAST SQUARES CURVE FITTING -

ENTER A DATA PAIR IN RESPONSE TO EACH


QUESTION MARK. EACH PAIR IS AN X VALUE
AND A Y VALUE SEPARATED BY A COMMA.

AFTER ALL DATA IS ENTERED, TYPE


999 , 999
IN RESPONSE TO THE LAST QUESTION MARK.

THE PROGRAM IS CURRENTLY SET TO ACCEPT


A MAXIMUM OF 38 DATA PAIRS.

46,8
VD
<~<<~<~<~<~<~<-«<
XK

Hom om it wa
Ne

3
oD

ae on
i) Or 100
lw Wit
eo
KK

oD

oO
“Se

NO
oD
‘es
KKK

co
i)
eS
we

LO
YQ

1S)
CO
oO
we
CURVE 189

X,Y=? 75,53
X,Y=? 999,999
7 DATA PAIRS ENTERED
DEGREE OF POLYNOMIAL TO BE FITTED? 1
X POWER COEFFICIENT
p -48.2797
1 1.28724
PERCENT GOODNESS OF FIT= 97.5342
HIT ANY KEY TO CONTINUE

CONTINUATION OPTIONS
1 - DETERMINE SPECIFIC POINTS
2 - FIT ANOTHER DEGREE TO SAME DATA
3 - END PROGRAM
WHAT NEXT? 2
DEGREE OF POLYNOMIAL TO BE FITTED? 2
X POWER COEFFICIENT
g 38.5297
1 -1.83686
2 ~6278514

PERCENT GOODNESS OF FIT= 99.9486

(continuation options displayed again)

WHAT NEXT? 1
ENTER 999 TO LEAVE THIS MODE

X=? 79
Y= 62.2451

X=? 83
Y= 72.427
X=? 999

(continuation options displayed again)

WHAT NEXT? 3.
READY.
190 BASIC Programs for the TRS-80

Initially, a first degree fit was tried and a goodness of fit of


about 97.5% was obtained. The investor wanted to do better,
so he tried a second degree fit next. This had a very high good-
ness of fit. He then asked for the extrapolation of his data to
the years 1979 and 1983. He found that he should expect to
pay about $62250 to buy the painting in 1979. Around a
$10000 profit could be expected upon resale in 1983.
Of course, the investor did not make his decision solely on
the basis of this program. He used it only as one guide to his
decision. There is never any guarantee that financial data will
perform in the future as it has done in the past. Though CURVE
is probably as good a way as any, extrapolation of data can
never be a totally reliable process.

PROGRAM LISTING
199 REM: CURVE
119 REM: COPYRIGHT 1979 BY FHIL FELDMAN AND TOM RUGG
129 CLEAR 54
149 DEF INT IL.
158 MX=39
149 EF=999
178 MII=4
299 LIM X(MX),Y (MX)
219 Q=MD+1:0IM A(Q,Q),R(Q),V(Q)
229 Q=MEe2 201M PQ)
38d CLS!FRINT” - LEAST SQUARES CURVE FITTING -":PRINT
319 PRINT"ENTER A DATA PAIR IN RESFONSE TO EACH"
329 PRINT'QUESTION MARK. EACH PAIR IS AN X VALUE"
339 PRINT"AND A Y VALUE SEPARATEL BY A COMMA.":PRINT
349 FRINT"AFTER ALL DATA IS ENTERED, TYPE"
359 PRINT EFS", "SEF
3568 PRINT'IN RESPONSE TO THE LAST QUESTION MARK." :PRINT
379 PRINT’ THE PROGRAM IS CURRENTLY SET TO ACCEPT"
389 PRINT’A MAXIMUM OF IMX!"DATA FAIRS."
469 PRINT: J=9
419 J=J41 SINPUT'X, Y=" XCD) YO)
429 TE XQD=EF AND YOSEF THEN J=J-1:G0TO 459
439 IF J=4X THEN PRINT#c® NO MORE DATA ALLOWED set's
GOTO 459
449 GOTO 419
458 NP=JsPRINT
46D IF NF=d
PRINT": FATAL ERROR! a -- NO OATA ENTERED :STOP
4/9 PRINT NPS"DATA FAIRS ENTERED"
CURVE 191

J99 PRINTS INPUT"DEGREE OF POLYNOMIAL TO BE FITTED" sD:


PRINT
wd IF 069 PRINT'#:« ERROR! #+« -—- DEGREE MUST RE 3= @"s
GOTO 589
wd Q=INT(Q)sIF DANP THEN 54¢
359 PRINT'*:« ERROR! ++ -- NOT ENQUGH DIATA':GOTO 3é@¢d
349 tig=2«]
JI IF DoM0 PRINT'+ ERROR! 44 -- DEGREE TOO HIGH'':
GOTO 38d
JOd N=[+1
699 FOR J=1 TO 02:P(J)=@sFOR K=1 TO NP
519 PCJ=PCU4X (CK PIJENEXTSENEXTs #P (9) =NP
629 R(1)=@:FOR J=1 TO NPsR¢(1=RC1) +O)
639 NEXTsIF N=1 THEN 6649
649 FOR J=2 TO NsR¢J)=@:FOR K=1 TO NP
659 RIDERC J+ CR) EX CRIA CI 1) SNEXT SNEXT
449 FOR J=1 TO NsFOR K=1 TO NsACJ,K)=PCJ+K-2) sNEXTSNEXT
479 GOSUB 286¢
789 PRINTsPRINT"X POWER COEFFICIENT”
718 FOR J=1 TO NsPRINT" "“oJ-1,U¢J) NEXT
72e Q=9:sFOR J=1 TO NPsQ=Q+Y (J) eNEXTsM=Q/NP 3 T=9:6=9
739 FOR J=1 TO NPsQ=@:FOR K=1 TO NsQ=Q4¥CK XC J OCK-1) 8
NEXT
749 T=T# CY (J) -Q) 42 8 G=64+ 01 CI -MF22NEXT
738 IF G=@ THEN T=199:GOTO 772
749 T=199+#S5QR(1-T/G)
779 PRINTSPRINT"PERCENT GOODNESS OF FIT="5T
7839 PRINTSFRINT'HIT ANY KEY TO CONTINUE"
799 Q$=INKEYSsIF Q$=""" THEN 799
899 PRINTSPRINT"CONTINUATION OF TIONS"
819 PRINT’ 1 - DETERMINE SPECIFIC POINTS"
826 PRINT” 2 - FIT ANOTHER DEGREE TO SAME [IATA"
839 PRINT" 3 - END PROGRAM"
849 INFUT"WHAT NEXT’ 3QsQ=INT(Q) sIF Q=3 THEN ENE
B58 IF Q=2 THEN 549d
869 IF Q#21 THEN 882
989 PRINTSPRINT"ENTER' SEF S"TO LEAVE THIS MODE"
919 PRINTS INPUT’X="SXVsIF XV=EF THEN 899
9298 YV=9sFOR K=1 TO N
939 YV=YV+Y CK) #XV4AC K-17) ENEXTSPRINT' Y="'5 YU
IAG GOTO 919
20909 IF N=1 THEN VC 1)=R(01)/AC1,1) SRETURN
2818 FOR K=1 TO N-1
2829 T=K+]
2839 L=K
192 BASIC Programs for the TRS-80

2649 IF ABS(ACT,K))>ABS(ACL,K)) THEN LI


2956 IF I<N THEN [=I+1:GOTOQ 2949
2849 IF L=K THEN 2199
2079 FOR JEK TO NsQ=ACK,J) sACK,J=A(L, J)
2889 A(L,J)=QENEXT
2999 Q=R(K) sRCKI=R(L) sR(L)=Q
2198 I=K+1
2119 Q=ACT,K)/ACK,K) SACI, K)=8
2128 FOR J=K+1 TO NsACT,J=ACT,J)-Q#ACK, J) SNEXT
2139 RCI=RCT)-Q#R(K) es IF TAN THEN [=I+1:GOTO 2119
2148 NEXT
2158 VIN)=RK(N)/ACN,N) SFOR I=N-71 TO 1 STEP ~1
2169 Q=@:FOR J=I+1 TO NsQ=Q+A(T,J)#¥(J)
2178 V(T)=(RCT)-Q)/AC1, 1) sNEXTSNEXT
2189 RETURN

EASY CHANGES

1. The program uses 999 as the flag number to terminate various


input modes. This may cause a problem if your data include
999. You can easily change the flag number by modifying
the value of EF in line 160 to any value not needed in your
data. To use 10101, for example, make this change:
160 EF=10101
2. The current dimensioning is set to accomodate a TRS-80
with 4K of RAM memory. If you have a 16K machine, you
can handle well over 500 data pairs. To use up to 500 pairs,
set the value of MX in line 150 appropriately:
150 MX=500
3. A 16K machine will also allow you to use higher degree fits.
To achieve up to tenth degree fits, set the value of MD
appropriately:
170 MD=10
However, it must be stressed that it can be unreliable to
attempt high degree fits. Unless your data is well behaved
(X and Y values close to 1), the program will often not
produce accurate results if D is greater than 5 or so. This is
because sums of powers of X and Y are calculated up to
powers of 2*D. These various sums are several orders of
magnitude different than each other. Errors result because
of the numerous truncation and round-off operations in-
CURVE 193

volved in doing arithmetic with them. A practical limit for


MD is 7.
4. For some applications, significantly improved accuracy can
be attained by using “double-precision’’ computation. This
can be achieved by simply inserting the following line:
130 DEFDBL A-Z

MAIN ROUTINES

120-170 Initializes constants.


200- 220 Dimensions arrays.
300- 380 Displays introductory messages.
400 - 470 Gets X-Y input data from the user.
500 - 560 Gets degree of polynomial from the user, deter-
mines if it is acceptable.
600 - 670 Sets up equations for the simultaneous equation
solver and calls it.
700 - 790 Calculates percent goodness of fit, displays all
results.
800 - 860 Gets user’s continuation option and branches to
it.
900 - 940 Determines Y value corresponding to any X value.
2000 - 2180 Subroutine to solve simultaneous linear algebraic
equations.

MAIN VARIABLES

Mx Maximum number of data pairs allowed.


MD Maximum degree allowed to fit.
EF Ending flag value for data input and X point mode.
X,Y Arrays of X and Y data points.
NP Number of data pairs entered.
D Degree of polynomial to fit.
D2 2*D, the maximum power sum to compute.
N D+1, number of simultaneous equations to solve.
A,R,V Arrays for simultaneous linear equation solver.
P Array for holding sums of various powers of X.
LJ,K,L Loop indices.
Q,G Work variables.
M Mean value of Y.
T Percent goodness of fit.
194 BASIC Programs for the TRS-80

XV Specific X point to calculate Y for.


YV Y value corresponding to XV.
Q$ User input string.

SUGGESTED PROJECTS

1. No provision for modifying the data is incorporated into the


program. Often it would be nice to add, subtract, or modify
parts of the data after some results are seen. Build in a capa-
bility to do this.
2. You may desire other forms of output. A useful table for
many applications might include the actual X values, calcu-
lated Y values, and/or percentage errors in Y.
3. Sometimes certain points (or certain regions of points) are
known to be more accurate than others. Then you would
like to weight these points as being more important than
others to be fit correctly. The least squares method can be
modified to include such a weighting parameter with each
data pair. Research this technique and incorporate it into the
program. (Note: you can achieve some weighting with the
current program by entering important points two or more
times. There is a certain danger in this, however, You must
only ask for a solution with D less than the number of unique
data points. A division by zero error may result otherwise.)
. Often you wish to try successively higher degree polynomials
until a certain minimum percent goodness of fit is obtained.
Modify the program to accept a minimally satisfactory
percent goodness of fit from the user. Then have the program
automatically try various polynomial fits until it finds the
lowest degree fit, if any, with a satisfactory goodness of fit.
DIFFEQN

PURPOSE

Differential equations express functions by giving the rate of


change of one variable with respect to another. This type of
relation occurs regularly in almost all the physical sciences. The
solution of these equations is necessary in many practical
engineering problems.
For many such equations, a closed form (or exact analytical
expression) solution can be obtained. However, for just as many,
no such “simple” solution exists. The equation must then be
solved numerically, usually by a computer program such as this.
There are many types and classes of differential equations.
This program solves those of a simple type; namely, first order,
ordinary differential equations. This means the equation to be
solved can be written in the form

dY
— = (any function of X,Y)
dx
Here, X is the independent variable and Y is the dependent vari-
able. The equation expresses the derivative (or rate of change)
of Y with respect to X. The right-hand-side is an expression
which may involve X and/or Y.
To use the program, you must supply it with the differential
equation to be solved. The procedure to do this is explained in
the “‘How To Use It”’ section.
A technique known as the “fourth-order, Runge-Kutta”’
method is used to solve the equation. Space limitations prevent
196 BASIC Programs for the TRS-80

any detailed explanation of it here. However, it is discussed well


in the numerical analysis books referenced in the bibliography.
The program allows two forms of output. You can have the
answers tabulated in columns or plotted graphically.

HOW TO USE IT

The first thing you must do is enter the differential equation


into the program. This must be done at line 3000. Currently
this line contains a GOTO statement. This GOTO will cause an
error message to be displayed if the program is run before you
have changed line 3000. The form of line 3000 should be:
3000 D = (your function of X,Y)
D represents dY/dX. GOSUBs are made to line 3000 with X and
Y set to their current values. Thus, when each RETURN is
made, D will be set to the appropriate value of dY/dX for that
given X and Y. If necessary, you may use the lines between
3000 and 3999 to complete the definition of D. Line 3999 al-
ready contains a RETURN statement so you do not need to add
another one.
The program begins by warning you that you should have
already entered the equation at line 3000. You acknowledge
that this has been done by hitting the C key to continue.
Now the various initial conditions are input. You are prompted
for them one at a time. They consist of: the initial values of X
and Y, the stepsize interval in X at which to display the output,
and the final value of X.
You now have a choice between two types of output. Enter a
T for tabular output or a G for graphical output. The tabular
form is simply atwo column display of the corresponding values
of X and Y.
The graphical output plots the values of Y along a horizontal
axis as each corresponding X value is displayed on successive
lines of the screen. This graphical display requires you to input
the minimum and maximum values of Y that will be used on
the Y axis. You will be prompted for them if this output form
is chosen. An open circle is used to plot the value of Y. If, how-
ever, the value of Y is “‘off=scale,’’ an asterisk is plotted at the
appropriate edge of the graph.
With the input phase completed, the program initializes things
to begin the output. A question mark will be displayed in the
DIFFEON 197

lower left of the screen, telling you the program is waiting for
you to hit any key to begin the output.
The output is displayed at each interval of the stepsize until
the final value of X is reached. Output may temporarily be
halted at any time by simply hitting any key. This will stop the
display until you hit any key to resume the output. The output
may be started and stopped as often as desired, thus enabling
you to leisurely view intermediate results before they scroll off
the screen. It is applicable to both the tabular and graphical
forms of output.

SAMPLE PROBLEM AND RUN

Problem: A body, originally at rest, is subjected to a force of


2000 dynes. Its initial mass is 200 grams. However, while it
moves, it loses mass at the rate of | gram/sec. There is also an
air resistance equal to twice its velocity retarding its movement.
The differential equation expressing this motion is:

dy _ (2000-2Y) where Y=velocity (cm./sec.)


dX (200 — X) X=time (sec.)

Find the velocity of the body every 10 seconds up through two


minutes. Also, plot this velocity as a function of time.

Solution and Sample Run: The solution and sample run are
illustrated in the accompanying photographs.
198 BASIC Programs for the TRS-80

Pate) ae aga ap S(t ee2

ai we iaaa eC Oe: 2
DEFINED AT LINE 3088. THE FORM IS
Koos lage aaOU a)
Uae

IF THIS HAS ALREADY BEEN DONE HIT


THE ’C’ KEY TO CONTINUE THE PROGRAM.
IF NOT) HIT ANY OTHER KEY. THEN
ENTER LINE 3888 AND RE-RUN THE PROGRAM.

a
ec BC
are OAC

The operator hits a key to exit from the program. Then he enters the
differential equation into line 3000. He types RUN to restart the program.

(Mt 2 dm tgg3 41 Me Us a

Meat eC Mae

C’ FEY TQ CONTINUE THE PROGRAH.


IF HOT» HIT ANY OTHER KEY. THEN
ENTER LINE 3800 AND RE-PUN THE PROGRAM,

INITIAL YALUE OF 2? _

The operator has hit the ‘‘C’’ key. The program responds by beginning the
input phase.
DIFFEON 199

INITIAL VALUE OF X? @
INITIAL VALUE OF Y? @
STEPSIZE IN X? 18
FINAL VALUE OF x? 128
Ud ume ed Gy eae en

THE FOLLOWING OUTPUT CAN BE HALTED BY HITTING


ANY KEY. IT CAN THEN BE RESUMED BY HITTING ANY
KEY. THIS MAY BE DONE AS OFTEN AS DESIRED.

WHEN THE QUESTION MARK (?) APPEARS? HIT ANY


KEY 10 BEGIN THE OUTPUT.

i Y
a

The operator has completed the input and requested tabular output. The
program signals with a question mark that it is waiting for him to hit any
key. It will not continue the run until he does so.

HS
8
i)
ra)
38
48
i]
co)
a
88
%
Uy
118
128
bag
ns
f

The operator hits a key and the program responds with the tabulated
output. X is time in seconds and Y is velocity in cm./sec.
200 BASIC Programs
for the TRS-80

x
8
rT)
F)
E
rf)
F)
6a
rt
E
e)
108
1
he

The program is rerun requesting graphical output. Before this photo, the
program requested a minimum and maximum value of Y to use on the Y
axis. Values of 0 and 850 respectively were entered. The program displays
the desired graph.

PROGRAM LISTING
198 REM: DIFFEQN
119 REM: COPYRIGHT 1979 BY PHIL FELDMAN AND TOM RUGG
158 CLEAR 159
209 CLSsFOR J=1 TO 1@sR$=INKEY$=:NEXT
219 PRINT" FIRST ORUER DIFFERENTIAL EQUATION SOLVER"
228 PRINT@197, "THE DIFFERENTIAL EQUATION MUST BE"
2398 PRINT@259, "QEFINED AT LINE 3404. THE FORM IS”
249 PRINT@328, "3908 Di=(YOUR FUNCTION OF X,Y)"
259 PRINT@387, "WHERE D=DY/0X."
268 PRINT@S17,"IF THIS HAS ALREADY BEEN DONE, HIT"
279 PRINT@S79,"THE “C“ KEY TO CONTINUE THE PROGRAM."
289 PRINT@4645,"IF NOT, HIT ANY OTHER KEY. THEN”
298 PRINT@797, "ENTER LINE 3889 AND RE-RUN THE PROGRAM."
399 PRINT@139,STRINGS (41,143) 5 sBS=STRINGS (2,191)
319 FOR J=128 TO 768 STEP 64:PRINT@J, BS; sNEXT
329 PRINT@459,STRINGS(41,149)5:FOR J=171 TO 747 STEP 64
338 [email protected],BS5sNEXT sPRINT@748, STRINGS (45,143)
496 RS=INKEY$:IF R$="" THEN 469
419 IF R$<>"C" THEN END
DIFFEON 201

429 INPUT" INITIAL VALUE OF X"=XX


439 INPUT'INITIAL VALUE OF Y°SYY!Y=YY:X=XX:GOSUB 3999
AAG INPUT"STEPSIZE IN X"s0XsINPUT"EINAL VALUE OF X" SXF
459 INPUT"QUTPUT FORM (T=TABLE, G=GRAPH) "IFS
449 FS=LEFTS(F$,1)2IF FS<2°T" AND FS<2"G" THEN 459
479 IF F$="T" THEN 690
489 INPUT’MINIMUM Y FOR THE GRAPH AXIS": YL
AMG INFUT’MAXIMUM Y FOR THE GRAPH AXIS" = YH
OG IF YH=YL THEN 499
31d PRINT tek ERROR! -- MAX Y MUST BE > MIN Y sete"
od GOTO 499
4690 PRINTIPRINT STRINGS (50,45)
419 PRINT" THE FOLLOWING QUTPUT CAN
KE HALTED BY HITTING"
629 PRINT"ANY KEY. IT CAN THEN BE RESUMED BY
HITTING ANY"
636 PRINT’KEY. THIS MAY BE DONE AS OFTEN AS DESIRED."
PRINT
549 PRINT" WHEN THE
QUESTION MARK (?) APPEARS, HIT ANY”
659 PRINT'KEY TO BEGIN THE OUTPUT."
FRINT STRING$(59,45)
709 IF F$="T" THEN PRINT "X","Y"sGOTO 899
719 PRINT TABC14) S"YMIN="3YLSTAB(45) 2° YMAX=" 2YH
P29 PRINTsPRINT TABCI5) s'YMIN'*TABCS4) 5" YMAX"
739 BS=CHR$ (188) sC$=CHR$ (14) I=CHRS (191) SES=RS4CS-419
74D FOR J=1 TO 19:E$=ES+CS+B$:NEXT SE S=ES+4CS+0$+C$+489
FaG PRINT "X"3TAB(14)5E$
898 PRINT!?"s
819 R$=INKEY$:1F R$="" THEN 81
829 PRINT CHR$(24) SCHR$ (32) SCHRS(24) 5
8.38 GOSUR 1599
789 Q=XX+0X21F Q2XF+1.E-5 THEN ENT
919 X=XX2rY=VYVsGOSUR 3OGGsKO=UsX=XX+0X/2 :Y=VV+KG4lK/2
926 GOSUB 3000sK1=0sY=YY+K140X/2:GOSUR 3966:K2=0
936 X=XX+0X Y=YY+K240X sGOSUB 3G0G2K3=0
249 LY =X (RO+2¢K 1 424K 24K3)/6
TY YY=YY4DY :XX=XX+0X:GOSUB 1506
949 GOTO 909
1898 PRINT:
PRINT set ERROR! -- YOU HAVE NOT [IEF INE THE”
1918 FRINT" DIFFERENTIAL EQUATION IN LINE 39890."
1928 PRINT
1438 END
1508 [F F$="T" THEN PRINT XX,YYsGOSUB 168@:RETURN
202 BASIC Programs for the TRS-80

11S F=C(YY-YLI/CYH-YL) sV=INT (146+40«F +925)


1529 C=79:IF Ve1é THEN V=16:C=42
1538 IF Ve56 THEN V=546sC=42
1549 PRINT XX$TAR(14) 5 Ii$5 TABCY) SCHRS(C) 5 TAB(S8) 5S
1559 GOSUB 1498:sRETURN
1698 RS=INKEY$sIF R$=""" THEN RETURN
1618 RS=INKEY$:IF R$='""" THEN 1419
1628 RETURN
2969 REM
919 REM sR
ACCEECEECHC CECH ECC HEE EEE CHE RE RR

2929 REM * THE DIFFERENTIAL EQUATION MUST BE DEFINED «


2938 REM *« BETWEEN LINES 353999 AND 3999. #
2949 REM + f
2959 REM + LINE 3489 MUST BE OVERWRITTEN, MAKING IT *
2968 REM * THE FIRST LINE OF THE EQUATION. f
2977 REM HICH
CHCRR HCE HEC HEC ECHR CHEECH
2989 REM
53999 GOTO 1999:
REM MAKE THIS LINE D=(YOUR FUNCTION OF X,Y)
3999 RETURN

EASY CHANGES

1. If you have already entered the differential equation and


wish to skip the introductory output, add this line:
205 GOTO 420
This will immediately begin the input dialog.
2.If you wish to use negative stepsizes, line 900 must be
changed to:
900 Q=XX+DX:IF Q<XF-1.E-—5 THEN END

MAIN ROUTINES

200 - 330 Displays initial messages.


400 - 520 Gets user’s inputs.
600 - 650 Displays additional messages.
700 - 750 Initializes output display.
800 - 830 Waits for user to hit a key to start the output.
900 - 960 Computes each step.
1000-1030 Error message.
1500-1550 Plots graphical output.
1600-1620 Stops and starts output.
3000-3999 User supplied routine to define D.
DIFFEQN 203

MAIN VARIABLES

D Value of dY/dX.
X, Y Values of X,Y on current step.
XX, YY Values of X,Y on last step.
DX Stepsize in X.
XF Final value of X.
F$ Output flag string (T=table, G=graph).
YL,YH Minimum, maximum values of Y plot axis.
F Fractional distance of graphical point along Y axis.
V Tab position for graphical output.
C CHR$ argument for graphical output.
KO,K1, Runge-Kutta coefficients.
K2,K3
R$ User entered string.
Q Work variable.
J Loop index.
B$,C$ Graphical format strings.
D$,E$

SUGGESTED PROJECTS

1. Modify the program to display the tabular output followed


by the graphical output. During the tabular phase, the mini-
mum and maximum values of Y can be saved and automati-
cally used as the plot limits for the graphical output.
2. The value of dY/dX as a function of X is often a useful quan-
tity to know. Modify the program to add it to the columnar
display and/or the graphical display.
3. The inherent error in the calculation depends on the stepsize
chosen. Most cases should be run with different stepsizes to
insure the errors are not large. If the answers do not change
much, you can be reasonably certain that your solutions are
accurate. Better yet, techniques exist to vary the stepsize
during the calculation to insure the error is sufficiently
small during each step. Research these methods and incor-
porate them into the program.
4. The program can be easily broadened to solve a set of coupled,
first order, differential equations simultaneously. This would
greatly increase the types of problems that could be solved.
Research this procedure and expand the program to handle
it.
204 BASIC Programs for the TRS-80
GRAPH

PURPOSE

Is a picture worth a thousand words? In the case of mathe-


matical functions, the answer is often “‘yes.’’ A picture, i.e. a
graph, enables you to see the important behavior of a function
quickly and accurately. Trends, minima, maxima, etc. become
easy and convenient to determine.
GRAPH produces a two-dimensional plot of a function that
you supply. The function must bein the form Y = (any function
of X). The independent variable X will be plotted along the
abscissa (horizontal axis). The dependent variable Y will be
plotted along the ordinate (vertical axis). You have complete
control over the scaling that is used on the X and Y axes.

HOW TO USE IT

Before running the program, you must enter into it the func-
tion to be plotted. This is done as a subroutine beginning at line
5000. It must define Y as a function of X. The subroutine will
be called with X set to various values. It must then set the
variable Y to the correct corresponding value. The subroutine
may be as simple or as complex as necessary to define the
function. It can take one line or several hundred lines. Line
5999 is already set as a RETURN statement, so you need not
add another one.
Having entered this subroutine, you are ready to run the pro-
gram. The program begins by warning you that it assumes the
function has already been entered at line 5000. It will then ask
206 BASIC Programs for the TRS-80

you for the domain of X, 1.e. the lowest and highest values of X
that you wish to have plotted. Values can be positive or negative
as longas the highest value is actually larger than the lowest one.
Now you must choose the scale for Y. To do this intelligently,
you probably need to know the minimum and maximum values
of Y over the domain of X selected. The program finds these
values and displays them for you. You must then choose the
minimum and maximum values you wish to have on the Y scale.
Again, any two values are acceptable as long as the maximum
scale value of Y is larger than the minimum scale value of Y.
The program will now display the plot of your function. Each
axis is forty characters long, with the origin defined as the
minimum scale values of both X and Y. Twenty tick marks
appear on each axis. The minimum, middle, and maximum
values on each scale are displayed appropriately.
If a value for Y should be off-scale, an asterisk will be dis-
played at the appropriate value of X. If the actual value of Y is
too large, it will be plotted at the maximum Y value. Similarly,
it will be drawn at the minimum Y value if it is too low.
Some plots have open circles plotted along the X axis. These
correspond to points whose Y values are equal to the value of Y
along the X axis.
After the plot is drawn, the program will tell you to hit any
key to continue. When you do so, information about the plot
scaling is provided. For both X and Y, you are given the mini-
mum, mid, and maximum values on each axis.
You now have the option of hitting G to draw the graph
again or any Other key to terminate the program.
GRAPH 207

SAMPLE RUN

s4 teth
>S5000 Y=SINCX>
>RUN_

After loading the program, the operator enters line 5000 to request the
graph Y=SIN(X). RUN is typed to begin the program.

Tee PORE gy
THE SUBROUTINE AT LINES
5660-5999 IS ASSUMED To
DEFINE Y AS A FUNCTION OF x

LOWEST VALUE OF X? @
HIGHEST VALUE OF 2%? 6.28

‘OVER THIS RANGE OF X


MINIMUM Y =—. 999997
MAXIMUM Y = 1
NOW CHOOSE THE SCALE FOR ¥

MINIMUM Y SCALE VALUE? -1


MAXIMUM Y SCALE VALUE? 1_

The input dialog transpires. The operator asks that the domain of X be
0-6.28. The program responds by showing the maximum and minimum
value of Y over this domain. The operator chooses an appropriate scale for
the Y axis.
208 BASIC Programs for the TRS-80

The graph is displayed as requested. The program waits for the operator to
hit any key to continue.

* SCALING
Paap aye lal
pet)
MAXIMUM

SCALING
POP ae
MID
MAXIMUM

HIT *G’ TO SEE THE GRAPH AGAIN


ANY OTHER KEY TO QUIT

Relevant scaling information is shown. By pressing “G’’, the operator can


see the graph again.
GRAPH 209

PROGRAM LISTING

199 REM: GRAPH


119 REM: COPYRIGHT 1979 BY PHIL FELDMAN AND TOM RUGG
129 CLEAR 5@:A$=CHR$(191) 2BS=CHR$( 143) :C$=CHR$(179)
138 H$=CHR$ (131) sM$=CHR$ (149) sL$=CHRS(176) sFos"e''s
X$="'Q""

299 CLS:PRINT CHR$(23)STAB(11)2"G R A P H'sPRINT


219 GOSUB 1999:PRINT
229 PRINTSINPUT"LOWEST VALUE OF X"3XL
239 INPUT"HIGHEST VALUE OF X"SXU
249 IF XU<=XL THEN PRINT:PRINT" -- BAL X RANGE --":
GOTO 226
259 GOSUB 894:GOSUB 399:GOSUB 599
249 GOSUR 994:CIL_S:END
399 CLS:FOR J=89 TO 912 STEP 64:PRINT@J,A$s NEXT
319 FOR J=913 TO 952:PRINT@J,H$3 sNEXT:
PRINT@14,L$°L$:L$%
329 FOR J=79 10 719 STEP 128:PRINT@J,M$3:PRINT@J+64,C$3
359 NEXT :PRINT@847, $5 :PRINT@270,H$s :PRINT@462,$5
349 PRINT@654,L $3 :PRINT@919,HSSH$!:
FOR J=914 TO 952 STEF 2
35d PRINT@J,B$s:NEXT:FOR J=922 TO 952 STEP 19:
PRINT@J,A$5 NEXT
549 PRINT@12,"Y"s sPRINT@954,"X"s
37@ XM=(XL+XU) /2 2 YM= (YL#YU) /2 :05LEN (STR$ (YU) )
389 PRINT@12-Q, YUs sQ=LEN(STR$(YM) ) sPRINT@469-Q, YM3
399 Q=LEN(STR#(YL) ) sPRINT@908-Q, YL 3 :Q=LEN(STR$(XL))/2
A499 PRINT@976-Q, XL 5 2Q=LEN(STR$ (XM) )/2:PRINT@994-Q, XM!
419 Q=LEN(STR$ (XU) )/2:PRINT@1916-Q, XUs sRETURN
JOO NX=(XU-XL)/89:DY=(YU-YL)/4@:FOR J=@ TO 8d
w1d X=XL+0X« (J) XP=32+JI:GOSUB 700
woO IF F=1 THEN PRINT@9124+J/2,F$::GOTO 549
358 IF F=2 THEN PRINT@16+J/2,F$3:G0TO 569
JAG IF F=3 THEN PRINT@9124+J/2,X$3:GOTO 569
we SET(XP, YP) :SET(XP+1, YP)
JOO NEXT
w7@ FRINT@193,"HIT ANY KEYS sPRINT@321,"TO CONTINUE":
89 Q$=INKEY$:IF Q¢="" THEN 5Q¢
199 RETURN
7 OO GOSUB 5990:V=(Y-YL)/DY sD=INT(V)
719 IF Y<YL THEN F=1 RETURN
228 IF Y>YU THEN F=2:RETURN
739 IF [=@ THEN F=3:RETURN
74D F=0:YP=42-D RETURN
210 BASIC Programs for the TRS-80

899 DX=(XU-XL)/89:X=XL sGOSUB SOOBsMN=Y sMX=Y


FOR J=1 TO 89
819 X=XL+DX*JsGOSUB SO9O92IF YOMX THEN MX=Y
829 IF Y<MN THEN MN=Y
8359 NEXT
849 PRINTsPRINT"OVER THIS RANGE OF X":
PRINT” MINIMUM Y ="5MN
B59 PRINT" MAXIMUM Y ="5MX=
FRINT"NOW CHOOSE THE SCALE FOR Y"
869 PRINTS INPUT"MINIMUM Y SCALE VALUE"; YI
879 INPUT"MAXIMUM Y SCALE VALUE"; YU:
IF YU>YL THEN RETURN
889 PRINTsPRINT" -- BAD Y SCALING --"sGOTO 849
799 CLSOsPRINT CHRS(23)5"X SCALING''s
PRINT’ MINIMUM - "5X1
919 PRINT" MID ~ "*S¥MsPRINT' MAXIMUM - "SXUs
PRINT
929 PRINT"Y SCALING" :PRINT” MINIMUM - "SYL
930 PRINT" MID ~ "SYMsPRINT" MAXIMUM - "SYU:
PRINT
949 PRINT'HIT “G" TO SEE THE GRAPH AGAIN"
958 PRINT" ANY OTHER KEY TO QUIT"
949 Q$=INKEY$sIF Q$="" THEN 949
97@ IF Q$="6" THEN GOSUB 3899:GOSUR 399
989 RETURN
1969 PRINT@128,A$,:FOR J=139 TO 148sPRINT@JS, BS; sNEXT
1919 PRINT@152, "WARNING! "5 sFOR J=17¢0 TO 188:
FRINT@J), B$SNEXT
1929 PRINT@199,A$; sPRINT@200,"THE SUBROUTINE AT LINES"s
1938 PRINT@264, "5909-5999 IS ASSUMED TO";
1949 PRINT@324,"UEFINE Y AS A FUNCTION OF X";
1959 FOR J=192 TO 329 STEP 64:PRINT@J,AS5 sK=J+é628
PRINT@K,A$;
1969 NEXT:PRINT@384,
RSs sPRINT@444,8%52FOR J=386 TO 444
1979 PRINT@J,
BS; sNEXTsRETURN
49590 REM
969 REM ce CEERI SCCRECCE CEASE BCE EEE CS

49/9 REM * SUBROUTINE AT LINE 3999 MUST BE SET


4989 REM eeeeecetscintci acini fede ected
4999 REM
3999 REM sett = Y=FCX) GOES HERE :t:t+
3999 RETURN
GRAPH 211

EASY CHANGES

1. You may want the program to self-scale the Y axis for you.
That is, you want it to use the minimum and maximum Y
values that it finds as the limits on the Y axis. This can be
accomplished by adding the following line:
835 YU=MX:YL=MN:RETURN
2.Do you sometimes forget to enter the subroutine at line 5000
despite the introductory warning? As is, the program will
plot the straight line Y=O if you do this. If you want a more
drastic reaction to prevent this, change line 5000 to read
5000 Y=1/0
Now, if you don’t enter the actual subroutine desired, the
program will stop and print the following message after you
enter the X scaling values.
?/0 ERROR IN 5000

MAIN ROUTINES

120- 130 Initializes constants.


200- 210 Displays introductory warning.
220- 260 Mainline routine—gets X scaling from user and
calls various subroutines.
300- 410 Subroutines to draw graph axes and scale labeling.
500- 590 Subroutine to plot the function.
700- 740 Subroutine to determine the plotting position
for Y.
800 - 880 Subroutine which determines the minimum, max-
imum Y values; gets Y scale from user.
900 - 980 Subroutine which displays the scaling parameters,
asks user if he wants the graph re-plotted.
1000 - 1070 Subroutines to display the introductory warning.
5000- 5999 User supplied subroutine to evaluate Y as a func-
tion of X.

MAIN VARIABLES

XL,XM, Lower, middle, upper scale values of X.


XU
YL,YM, Lower, middle, upper scale values of Y.
YU
212 BASIC Programs for the TRS-80

DX,DY Scale increments of X,Y.


X,Y Current values of X,Y.
XP,YP Plot position of X,Y point.
A$,B$,C$, Strings used in messages, graph axes, and scale
H$,M$,L$ labeling.
F$ Off-axis character string.
X$ X-axis character string.
Q Axis number string length.
F Special plot character flag (1=Y too high, 2=Y
too low, 3=Y on X axis).
V Value of X or Y in scale units.
D Integer value of V.
MN,MX Minimum, maximum values of Y.
Q$ User reply string.
J Loop index.

SUGGESTED PROJECTS

1. Determine and display the values of X at which the minimum


and maximum values of Y occur.
2. After the graph is plotted, allow the user to obtain the exact
value of Y for any given X.
3. Expand the graph to a 30 character width in the X direction.
INTEGRATE

PURPOSE AND DEFINITION

The need to evaluate integrals occurs frequently in much


scientific and mathematical work. This program will numerically
integrate a function that you supply using a technique known
as Simpson’s rule. It will continue to grind out successive ap-
proximations of the integral until you are satisfied with the
accuracy of the solution.
Mathmetical integration will probably be a familiar term to
those who have studied some higher mathematics. It is a funda-
mental subject of second-year calculus. The integral of a function
between the limits x= (lower limit) and x=u (upper limit)
represents the area under its curve;i.e. the shaded area in Figure 1.
We may approximate the integral by first dividing up the area
into rectangular strips or segments. We can get a good estimate
of the total integral by summing the areas of these segments by
using a parabolic fit across the top. For those who understand
some mathematical theory, Simpson’s rule may be expressed as

X—=U

f f(x) dx & 7 £(2) + £(u)


<2
N/2 (N- 2)/2
+4 >> f[RQ+ AQI-D1+2 YS f[k+ 2Aj]
j=1 j=1
214 BASIC Programs for the TRS-80

L_ MQW ’vw‘”
SSvV”"
WWWW’W’W’w
y = f(x)

SS

:
Wi
x

Cc
|

Figure 1. The Integral of f(x)

Here N is the number of segments into which the total interval


is divided. N is 4 in the diagram.
For a good discussion of the numerical evaluation of integrals
see: McCracken, Dorn, Numerical Methods and Fortran Pro-
gramming, New York, Wiley, 1964,pp.160. Don’t let the word
‘“‘Fortran”’ scare you away. The discussions in the book are inde-
pendent of programming language with only some program
examples written in Fortran.

HOW TO USE IT

The program begins with a warning! This is to remind you


that you should have already entered the subroutine to evaluate
Y as a function of X. This subroutine must start at line 5000.
More about it shortly.
You will then be asked to provide the lower and upper limits
of the integration domain. Any numerical values are acceptable.
INTEGRATE 215

It is not even necessary that the lower limit of X be smaller than


the upper one.
The program will now begin displaying its numerical evalua-
tions of the integral. The number of segments used in the
calculation continually doubles. This causes the accuracy of the
integral to increase at the expense of additional computation
time. For most functions, you should see the value of the inte-
gral converging quickly to a constant (or near constant) value.
This, of course, will be the best numerical evaluation of the
integral at hand.
When you are satisfied with the accuracy of the solution, you
must hit the BREAK key to terminate the program. If not, the
program will run forever (assuming you can pay the electric
bills). The amount of computation is approximately doubled
each step. This means it will take the computer about the same
amount of time to compute the next step that it took to
compute all the previous steps. Thus, it will soon be taking the
TRS-80 hours, days, and weeks to compute steps. Eventually,
round-off errors begin degrading the results, causing a nice, con-
stant, converged solution to change. However, the high precision
of the computer’s floating point arithmetic will postpone this for
quite a while. You will probably lose patience before seeing it.
The function to be integrated can be as simple or as compli-
cated as you desire. It may take one line or a few hundred lines
of code. In any case, the subroutine to express it must start at
line 5000. This subroutine will be continually called with the
variable X set. When it returns, it should have set the variable Y
to the corresponding value of the function for the given X. The
subroutine must be able to evaluate the function at any value of
X between the lower and upper bounds of the integration
domain.
If your function consists of experimental data at discrete
values of X, you must do something to enable the subroutine
to evaluate the function at intermediate values of X. We recom-
mend one of two approaches. First, you could write the subrou-
tine to linearly interpolate the value of Y between the appropriate
values of X. This will involve searching your data table for the
pair of experimental X values that bound the value of X where
the function is to be evaluated. Secondly, the program CURVE
presented elsewhere in this section can produce an approximate
polynomial expression to fit your experimental data. This
216 BASIC Programs for the TRS-80

expression can then be easily entered as the subroutine at line


5000.
By the way, Simpson’s rule is exact for any polynomial of
degree 3 or less. This means that if the function can be written
in the form
Y = A*X13 + B¥XT2 + C*X+D
where A, B, C, D are constants, the program will calculate the
integral exactly even with only two segments.

SAMPLE RUN

The sample run illustrates the following integration

x=]

‘ d
/ 1+x? *
x=0

This integral has the theoretical value of m (pi) as the correct


answer! Pi, as you may know, has the value 3.1415926535. ..
Before the run in started, the above function is entered at line
5000.

5806 Y=4/C14+X*x)
RUN
INTEGRAL BY SIMPSON'S RULE

WARNING!

THE SUBROUTINE AT LINES

5882-5999 IS ASSUMED TO DEFINE

Y AS A FUNCTION OF X

LOWER LIMIT OF X? §@

UPPER LIMIT OF X? 1
INTEGRATE 217

# SEGMENTS INTEGRAL

2 3.13333
Ly 3.14157
8 3.14159
16 3.14159
32 3.14159
64 3.14159
128 3.14159

(BREAK key pressed)

PROGRAM LISTING

199 REM: INTEGRATE


119 REM: COPYRIGHT 1979 BY PHIL FELDMAN AND TOM RUGG
158 CLEAR 2@9s0EFINT J,M,N
149 N=2
28d V$=STRINGS (11,131)
219 L$=CHRS (149)
229 R$=CHRS$ (179)
239 CLS
249 PRINT CHR$(196)5"INTEGRAL BY SIMPSON’S RULE" sPRINT
29 PRINT CHR$(151)+V$+" WARNING! "“4V$+CHR$(1771)
249 PRINT L$+" THE SUBROUTINE AT LINES "+R
279 FRINT L$+" 5988-5999 IS ASSUMED TO DEFINE "+R$
289 PRINT L$+" Y AS A FUNCTION OF X "RS
299 PRINT CHR$(141)+STRING$ (32, 140) +CHR$(142)
399 INPUT"LOWER LIMIT OF X"SL
319 INPUT"UPPER LIMIT OF X"sU
349 PRINT
389 PRINT’H SEGMENTS", "INTEGRAL"
ADD DIX=(U-L)/NiT=@
419 X=L:GOSUB 50G0:T=T+Y
420 X=U:GOSUB 5900:T=T+Y
459 M=N/2:2=9
449 FOR J=1 TO #
479 XSL +X (24I-1)sGOSUB 59002Z=Z+Y
489 NEXT: T=T+4#Z
389 M=M-1sIF M=@ THEN 699
J1d Z=9:FOR J=1 TO M
329 X=L+DXk2*J:GOSUB 5G00:Z=Z+Y
338 NEXT: T=T+24Z
599 A=DX#T/3
619 PRINT N,A
218 BASIC Programs for the TRS-80

628 N=N+#2
638 GOTO 499
4979 REM
4988 REM +e ENTER SUBROUTINE AT LINE S900 +t:
4999 REM
JOGO REM etcetek Y=F CX) GOES HERE etctcte
I999 RETURN

EASY CHANGES

1. You might want the program to stop calculation after the


integral has been evaluated for a given number of segments.
Adding the following line will cause the program to stop after
the integral is evaluated for a number of segments greater
than or equal to 100.
615 IF N>=100 THEN END
Of course, you may use any value you wish instead of 100.
. Perhaps you would like to see the number of segments
tO

change at a different rate during the course of the calculation.


This can be done by modifying line 620. To increase the rate
of change, try
620 N=N*4

To change it at a constant (and slower) rate, try


620 N=N+50
Be sure, however, that the value of N is always even.

3. Take advantage of TRS-80 Basic’s double-precision to com-


pute the results to a high degree of accuracy. Simply change
line 150 to:
150 CLEAR 200: DEFDBL A-Z:DEFINT J,M,N
How long does it take to compute Pi to 15 correct decimal
digits?

MAIN ROUTINES

150- 160 Initializes constants.


200 - 290 Displays introductory messages and warning.
300 - 310 Gets integration limits from operator.
360 - 380 Displays column headings.
INTEGRATE 219 -

400 - 420 Computes integral contribution from end points.


450 - 480 Adds contribution from one summation.
500 - 530 Adds contribution from other summation.
600 - 630 Completes integral calculation and displays it.
Increases number of segments and restarts cal-
culation.
5000
- 5999 Operator supplied subroutine to evaluate f(x).

MAIN VARIABLES

N Number of segments.
J Loop index.
L,U Lower, Upper integration limit of x.
DX Width of one segment.
Partial result of integral.
Number of summations.
Subtotal of summations.
PN

Value of integral.
Current value of x.
Kx

Current value of the function y=f(x).


V$,L$,R$ Strings used in messages.

SUGGESTED PROJECTS

1. Research other similar techniques for numerical integration


such as the simpler trapezoid rule. Then add a column of
output computing the integral with this new method. Com-
pare how the two methods converge toward the (hopefully)
correct answer.
SIMEQN

PURPOSE

This program solves a set of simultaneous linear algebraic


equations. This type of problem often arises in scientific and
numerical work. Algebra students encounter them regularly
—many ‘‘word’’? problems can be solved by constructing the
proper set of simultaneous equations.
A TRS-80 with 4K of memory can handle upwards of fifteen
equations in fifteen unknowns. This should prove more than
sufficient for any practical application. A 16K system can han-
dle many more if, somehow, this should ever be necessary.
The equations to be solved can be written mathematically as
follows:

A,X, tA, 2% +--+. FAN Ay = R,


Ay, * +A, 4%, +...
t+ ASN AN FR,

Ay, %,; t Aya X%.t--- tAny Ay = Ry


N is the number of equations and thus the number of unknowns
also. The unknowns are denoted X, through Xy-
Each equation contains a coefficient multiplier for each un-
known and a right-hand-side term. These coefficients (the A
matrix) and the right-hand-sides (R, through R,) must be
constants—positive, negative, or zero. The A matrix is denoted
with double subscripts. The first subscript is the equation num-
ber and the second one is the unknown that the coefficient
multiplies.
222 BASIC Programs for the TRS-80

HOW TO USE IT
The program will prompt you for all necessary inputs. First,
it asks how many equations (and thus how many unknowns)
comprise your set. This number must be at least 1. If it is too
large, a OM or BS error will immediately result.
Next, you must enter the coefficients and right-handsides for
each equation. The program will request these one at a time,
continually indicating which term it is expecting next.
Once it has all your inputs, the program begins calculating
the solution. This may take a little while if the value of N is
high. The program ends by displaying the answers. These, of
course, are the values of each of the unknowns, X, through Xx -
If you are interested, the numerical technique used to solve
the equations is known as Gaussian elimination. Row interchange
to achieve pivotal condensation is employed. (This keeps maxi-
mum significance in the numbers.) Then back substitution is
used to arrive at the final results. This technique is much simpler
than it sounds and is described well in the numerical analysis
books referenced in the bibliography.
SAMPLE PROBLEM AND RUN
Problem: A painter has a large supply of three different
colors of paint: dark green, light green, and pure blue. The dark
green is 30% blue pigment, 20% yellow pigment, and the rest
base. The light green is 10% blue pigment, 35% yellow pigment,
and the rest base. The pure blue is 90% blue pigment, no yellow
pigment, and the rest base. The painter, however, needs a me-
dium green to be composed of 25% blue pigment, 25% yellow
pigment, and the rest base. In what percentages should he mix
his three paints to achieve this mixture?
Solution: Let X, = percent of dark green to use,
X, = percent of light green to use,
X, = percent of pure blue to use.
The problem leads to these three simultaneous equations to
Solve:
0.3X, +01 X, +0.9 X, = 0.25
0.2 X, + 0.35X, = 0.25
X, + X, + X, = 1.0
The first equation expresses the amount of blue pigment in the
mixture. The second equation is for the yellow pigment. The
SIMEQN 223

third equation states that the mixture is composed entirely of


the three given paints. (Note that all percentages are expressed
as numbers from Q-1.) The problem leads to the following use
of SIMEQN.

SAMPLE RUN

A SIMULTANEOUS LINEAR EQUATION SOLVER


HOW MANY EQUATIONS IN THE SET? 3.
THE 3 UNKNOWNS WILL BE DENOTED
X1 THROUGH X3

ENTER THE PARAMETERS FOR EQUATION 1


COEFFICIENT OF X1? .3
COEFFICIENT OF X2? .1
COEFFICIENT OF X3? .9
RIGHT HAND SIDE? .25

ENTER THE PARAMETERS FOR EQUATION 2


COEFFICIENT OF X1? 2
COEFFICIENT OF X2? .35
3
COEFFICIENT OF X3? gf
RIGHT HAND SIDE? .25
— me eee we ee ese ee we ee = oe

ENTER THE PARAMETERS FOR EQUATION 3


COEFFICIENT OF X1? 1
COEFFICIENT OF X2? 1
COEFFICIENT OF X3? 1
RIGHT HAND SIDE? 1

THE SOLUTION IS
X1= .55
X2= .4
X3= .95
READY.

Thus, the painter should use a mixture of 557


dark green, 40% light green, and 5% pure blue.
224 BASIC Programs for the TRS-80

PROGRAM LISTING

169 REM: SIMEQN


119 REM: COPYRIGHT 1979 BY PHIL FELDMAN AND TOM RUGG
1598 CLEAR S@:DEFINT I,J,K,L,N
299 CLS
219 PRINT'A SIMULTANEOUS LINEAR EQUATION SOLVER"
229 PRINT
58D INPUT"HOW MANY EQUATIONS IN THE SET'SN
319 IF Ni@ THEN 339
528 PRINT ERROR! ‘ek THERE MUST BE AT LEAST 1":
GOTO 399
539 [HIM ACN,N) »RON) VIN)
349 PRINT’ THE" SNS"UNKNOWNS WILL BE DENOTED"
JSP PRINT'X1 THROUGH X"MIDIS(STRS(N) 2,19)
549 GOSUB 999:FOR J=1 TO N
579 PRINT'ENTER THE PARAMETERS FOR EQUATION";J
589 PRINT:FOR K=1 TO N
399 PRINT'COEFFICIENT OF X"sSMIDS(STR$(K),2,18)3
499 INPUT A(J,K) NEXT
419 INPUT"RIGHT HAND SIDE"!R(J)
429 GOSUB 990:NEXT
439 GOSUB 2699
99 PRINT" THE SOLUTION IS"sPRINT
w1d FOR J=1 TON
20 PRINT" X"SMIDS(STRS(J) 2,18) "=" UCI)
339 NEXT END
999 PRINT STRING$(35,"~")
919 RETURN
2889 IF N=1 THEN ¥(1)=R(1)/A(1,1) SRETURN
2919 FOR K=1 TO N-1
2628 T=K+1
2939 Lk
2049 IF ABS(ACI,K))2ABS(A(L,K)) THEN L=I
295@ IF I<N THEN I=14+1:GOTO 2049
29468 IF L=K THEN 2199
2978 FOR J=K TO NsQ=A(K,J) ACK, J)=A(L, J)
2988 ACL, J)=Q:NEXT
2998 Q=R(K) sR(K)=R(L) sR(L)=Q
2190 I=K+1
2119 Q=ACI,K)/A(K,K) SACI, K=8
2120 FOR J=K+1 TO NzACI,J)=ACT, J) -Q:#A(K, J) SNEXT
2130 RCT)=R(1)-Q4R(K) IF I<N THEN I=1+1:GOTO 2114
2149 NEXT
2150 VIND=R(N)/ACN,N)EFOR I=N-1 TO 1 STEP -1
SIMEQN 225

2169 Q=O9:FOR J=I+1 TO NeQ=Q+ACT, J#¥C 5) -


2178 VCI)=(RCT)-Q)/ACT, 1) sNEXT sNEXT
2188 RETURN

EASY CHANGES

You may be surprised sometime to see the program fail com-


pletely and display this message:
?/0 ERROR IN 2150
This means your input coefficients (the A array) were ill-condi-
tioned and no solution was possible. This can arise from a variety
of causes; e.g. if one equation is an exact multiple of another, or
if every coefficient of one particular unknown is zero. If you
would like the program to print a diagnostic message in these
cases, add this line.
2145 IF A(N,N)=0 THEN PRINT“ILL-CONDITIONED
INPUT” :STOP

MAIN ROUTINES

200 - 220 Clears screen and displays program title.


300 - 430 Gets input from user and calculates the solution.
500 - 530 Displays the solution.
900 - 910 Subroutine to space and separate the output.
2000-2180 Subroutine to calculate the solution; consisting
of the following parts:
2000 Forms solution if N=1.
2010-2140 Gaussian elimination.
2030-2100 Interchanges rows to achieve pivotal condensation.
2150-2180 Back substitution.

MAIN VARIABLES

LJ,K,L Loop indices and subscripts.


N Number of equations (thus number of unknowns
also).
Doubly dimensioned array of the coefficients.
QO<A YS

Array of right-hand-sides.
Array of the solution.
Work variable.
226 BASIC Programs for the TRS-80

SUGGESTED PROJECTS

1. The program modifies the A and R arrays while computing


the answer. This means the original input cannot be displayed
after it is input. Modify the program to save the information
and enable the user to retrieve it after the solution is given.
2. Currently, a mistake in typing input cannot be corrected
once the ENTER key is pressed after typing a number.
Modify the program to allow correcting previous input.
STATS

PURPOSE

Ever think of yourself as a statistic? Many times we lament at


how we have become just numbers in various computer memories,
Or we simply moan at our insurance premiums. To most people,
the word “statistics” carries a negative connotation. To invoke
Statistics is almost to be deceitful, or at least de-humanizing.
But really, we all use statistical ideas regularly. When we speak
of things like “‘she was average height” or the “hottest weather
in years,’ we are making observations in statistical terms. It is
difficult not to encounter statistics in our lives, and this book is
no exception.
Of course, when used properly, statistics can be a powerful,
analytical tool. STATS analyzes a set of numerical data that
you provide. It will compile your list, order it sequentially, and/
or determine several statistical parameters which describe it.
This should prove useful in a wide variety of applications.
Teachers might determine grades by analyzing a set of test
scores. A businessman might determine marketing strategy by
studying a list of sales to clients. Little leaguers always like to
pore over the current batting and pitching averages. You can
probably think of many other applications.

HOW TO USE IT

Before entering the data, the program will ask whether or not
you wish to use identifiers with the data values. These identifiers
can be anything associated with the data: e.g. names accom-
228 BASIC Programs for the TRS-80

panying test scores, cities accompanying population values,


corporations accompanying Sales figures, etc. Hit the Y or N
key to indicate yes or no regarding the use of identifiers. You
do not need to hit the ENTER key.
Next, your data list must be entered. The program will
prompt you for each value with a question mark. If identifiers
are being used, you will be prompted for them before being
asked for the associated data value. You may use any length
character strings you desire for identifiers. However, if you
limit them to a maximum of forty characters, the formatting
of later output will be “‘cleaner.”’
Two special inputs, *END and *BACK, may be used at any
time during this data input phase. They are applicable whether
or not identifiers are being used. To signal the end of data,
input the four character string, “END, in response to the (last)
question mark. You must, of course, enter at least one data
value.
If you discover that you have made a mistake, the five
character string, “BACK, can be used to back up the input
process. This will cause the program to re-prompt you for the
previous entry. By successive uses of *BACK you can return
to any previous position.
With the input completed, the program enters a command
mode. You have four options to continue the run:
1) List the data in the order input
2) List the data in ranking order
3) Display statistical parameters
4) End the program
Simply input the number 1, 2, 3, or 4 to indicate your choice.
If one of the first three is selected, the program will perform the
selected function and return to this command mode to allow
another choice. This will continue until you choose 4 to termi-
nate the run. A description of the various options now follows.
Options 1 and 2 provide lists of the data. Option | does it in
the original input order while option 2 sorts the data from
highest value to lowest. In either case the identifiers, if used,
will be shown alongside their associated values.
The lists are started by hitting any key when told to do so.
Either list may be temporarily halted by hitting any key while
the list is being displayed. This allows you to leisurely view data
that might otherwise start scrolling off the screen. Simply hit
STATS 229

any key to resume the display. This starting and stopping can be
repeated as often as desired. When the display is completed, you
must again hit a key to re-enter the command mode.
Option 3 produces a statistical analysis of your data. Various
statistical parameters are calculated and displayed. The following
is an explanation of some that may not be familiar to you.
Three measures of location, or central tendency, are provided.
These are indicators-of an “‘average”’ value. The mean is the sum
of the values divided by the number of values. If the values are
arranged in order from highest to lowest, the median is the
middle value if the number of values is odd. If it is even, the
median is the number halfway between the two middle values.
The midrange is the number halfway between the largest and
smallest values.
These measures of location give information about the
average value of the data. However, they give no idea of how
the data is dispersed or spread out around this “‘average.”’ For
that we need ‘“‘measures of dispersion” or as they are sometimes
called, “‘measures of variation.”’ The simplest of these is the
range which is just the difference between the highest and
lowest data values. Two other closely related measures of dis-
persion are given: the variance and the standard deviation. The
variance is defined as:
N

> (V,> M?
_ i=l
VA =
N-1
Here N is the number of values, Vv. is value i, M is the mean
value. The standard deviation is simply the square root of the
variance. We do not have space to detail a lengthy discussion of
their theoretical use. For this refer to the bibliography. Basically,
however, the smaller the standard deviation, the more all the
data tends to be clustered close to the mean value.
One word of warning—the first time option 2 or 3 is selected,
the program must take some time to sort the data into numerical
order. The time this requires depends upon how many items are
on the list and how badly they are out of sequence. Average
times are twenty-five seconds for twenty-five items, almost two
minutes for fifty items, about seven minutes for a hundred
items. The TRS-80 will pause while this is occurring, so don’t
230 BASIC Programs for the TRS-80

think it has hung up or fallen asleep! If you have several items


on your list, this is the perfect chance to rob your refrigerator,
make a quick phone call, or whatever.

SAMPLE RUN

STATS

THIS PROGRAM DOES A STATISTICAL ANALYSIS ON A


LIST OF DATA VALUES. IT WILL ORDER THE LIST AND
PQs gia: MC ML PRN ase It
THE DATA.

THE DATA MAY BE ENTERED IN EITHER


OF THO FORHS:
Oe ECR UOC Tlsym
om Bese ee Le

LUREO LabsMb agian)


LtOt 2 ea (35

The program describes its wares. It asks whether or not the operator
wishes to use identifiers with his or her input data. The operator replies
yes.
STATS 231

FEE en eaAAAASAAAASALLASALAaLanoaece eT sett tts


ce iB. 32.2

Tee PC meals eee saa


Cy): 39a Ope RL
TO THE SEPARATE QUESTION MARKS.

IF YOU MAKE A MISTAKEr TYPE


#BACK TO RE-ENTER THE LAST DATUM.

WHEN THE LIST 1S COMPLETED TYPE


SEND TO TERMINATE THE LIST.
sane none took cake none 88 88888 kee t Ret RARER SORA AAA SS

DATA ITEM # 1
1.0.2 _

VALUE? 76

Cm ae
a eed i
VALUE? 81.5

DATA ITEM # 4
eae
VALUE? 97.5

DATA ITEM #5
Sg
VALUE? 69

DATA ITEM # 6
hee 3,1

The operator completes entering the names and scores of those who took a
programming aptitude test. The actual test was given to many people, but
for demonstration purposes, only five names are used here. The special
string, “END, is used to signal the end of the data.
232 BASIC Programs for the TRS-80

EEE

SOG LPR6 Udi

POOR CURL Mati3


2) LIST DATA IN RANKING ORDER
3) BISPLAY STATISTICS
Oot ahh)

WHAT NEXT
(ir 2r 3h OR 4)? 2
HEHEHE

CUth et i ag

MG Waa ti at35

The operator requests that the list be sorted into numerical order. The
program first shows the total number of entries.

WHILE THE LIST IS DISPLAYING YOU CAN HIT


ANY KEY TO CAUSE A TEMPORARY HALT. THE DISPLAY
sh aa

HIT ANY KEY TO START THE DISPLAY.

bhi 1
8
TN}
3)
A)
Cy]

OM mame OC Lg

The operator hits a key to start the display and is then shown the data list
in ranking order. The program waits for the pressing of a key to continue.
STATS 233

vee en, Ta)


Sue uae
MOR Tae)
Pee ae
RANE = 29
Sea alee
aa
3) Cee
Be ae cs
CU 20st ee rae S:4
VARIANCE = 168.175

WU mam
me eta

Later in the run, the operator selects continuation option 3. This calculates
and displays the various statistical quantities.

PROGRAM LISTING

164 REM: STATS


118 REM: COPYRIGHT 1979 BY PHIL FELDMAN AND) TOM RUGG
139 CLEAR 589
158 BS="*BACK" :E$="4END”
148 MX=199
178 DIM DS(MX) VIMX) »Z(MX)
188 2(9)=G8:NS=CHRS (32)
268 CLSsPRINT TABR(24)5"S T A T S"sPRINT
219 PRINT" THIS PROGRAM DOES A
STATISTICAL ANALYSIS ON A"
229 PRINT"LIST OF DATA VALUES. IT WILL ORDER THE
LIST AND"
239 PRINT"FIND SEVERAL STATISTICAL QUANTITIES
DESCRIBING"
249 PRINT" THE DATA. "sPRINT
258 PRINT" THE DATA MAY BE ENTERED IN EITHER OF
TWO FORMS :"
268 PRINT’ 1) AS A SIMPLE LIST OF VALUES, OR"
278 PRINT" 2) WITH AN IDENTIFIER ACCOMPANYING EACH
VALUE."
234 BASIC Programs for the TRS-80

288 PRINT
299 PRINT" WOULD YOU LIKE TO USE IDENTIFIERS WITH"
58D PRINT’ YOUR INPUT (Y OR N) ? "5
519 R$=INKEY$:IF R$=""" THEN 319
329 IF R#="Y" THEN PRINT’ YES" sF=1:GOTO 488
339 IF R$="N" THEN PRINT’ NO" :F=@:GOTO 4694
3549 GOTO 319
499 FOR J=1 TO 34@:NEXT:GOSUB 2199
419 PRINT" THE DATA MUST NOW BE ENTERED." sPRINT
429 IF F=1 THEN 459
439 PRINT" ENTER EACH VALUE SEPARATELY IN RESPONSE TO"
449 PRINT"THE QUESTION MARK." :GOSUB 2949:GOTO 399
459 PRINT" FOR EACH GATA ITEM, ENTER ITS IDENTIFIER"
4469 PRINT’ (ARBREVIATED I.0.) AND ITS VALUE IN RESPONSE"
4/9 PRINT"TO THE SEPARATE QUESTION MARKS.":sGOSUB 2499
IBD GOSURK 2190sFOR J=1 TO 9sR¢=INKEY$s:NEXTsN=1
31d IF Nit THEN N=1
woe PRINTsSPRINT' DATA ITEM #'5N
338 IF F=8 THEN DS(N)=N$SGOTO 579
JAD INFUT"I.0."SR$:IF R$=E$S THEN 799
JO IF R#=B% THEN N=N-1:G60TO 5192
169 lis (ND SRS
w7@ INPUT" VALUE" SR$:IF R$=ES THEN 700
JOO IF R#=B% AND F=1 THEN 3298
39D IF R$=B$ THEN N=N-1:GOTO 519
599 VIN)=VAL (RS)
619 IF N=MX THEN PRINT ELSE 6392
629 PRINT: NO MORE DATA ALLOWED! +" sN=N+1:sGOTO 74d
439 N=N+1:G0TO Sid
799 N=N~-TsIF N=@ THEN FRINT ELSE 729
719 PRINT':#+ NO DATA -- RUN ABORTED +" s END
726 GOSUR 2194
738 PRINTSPRINT’-- CONTINUATION OF TIONS -~-"'sPRINT
74d PRINT’ 1) LIST DATA IN ORIGINAL ORDER"
PIO PRINT’ 2) LIST DATA IN RANKING ORDER"
7&9 PRINT’ 3) DISPLAY STATISTICS"
778 PRINT" 4) END PROGRAM
789 PRINTsPRINT'WHAT NEXT (1, 2, 3, OR 4) 7 "5
798 R$=INKEY$SsIF R$=""" THEN 799
899 R=VAL(R$) SIF R<1 OR R>4 THEN 799
819 PRINT RsIF R=4 THEN END
829 ON R GOSUR 1949,1289,150¢
838 GOTO 726
1998 GOSUR 219@:FRINT
1919 PRINT” THE ORIGINAL DATA ORDER’ sFRINT
STATS 235

19298 PRINT Ns"TOTAL ENTRIES" :GOSUB 2399


1932 PRINTIFRINT" # VALUE"s
1849 IF F=@ THEN PRINT
1959 IF F=1 THEN PRINT STRINGS(12,32):"1.D."
194d FOR J=1 TO NsFOR K=1 TO 19@:NEXT
1978 PRINT JSTAB(6) £¥(J) STAB 24) s0$(J)
1989 GOSUB 2599
1899 NEXT:GOSUB 2900:RETURN
1289 GOSUB 219@:PRINT
1219 PRINT" THE DATA IN RANKING ORDER" sFRINT
1229 PRINT Ns"TOTAL ENTRIES"
1239 GOSUB 2769
12898 GOSUB 2304:PRINT:PRINT" # VALUE":
1299 IF F=@ THEN PRINT
1389 IF F=1 THEN PRINT STRING$(12,32)5"1.0."
1319 FOR J=1 TO N:FOR K=1 TO 1@@:NEXT
1328 PRINT JSTAB(S) SV(2(J)) STAR(24) SIS(Z20)))
1339 GOSUB 259¢
1349 NEXT:GQSUB 2999:RETURN
1599 GOSUR 2190:PRINT
1519 PRINT TAB(8)s;"STATISTICAL ANALYSIS" sPRINT
1529 FOR J=1 TO 89@:NEXT:PRINT" YOUR LIST HAS" SNs "VALUES"
15.39 NP=@ :NN=@2NZ=0 2S0=0:U=9
1549 FOR J=1 TO NsW=W+V (J) SQ=SQ4V(J)#UC))
1559 IF V(J)2@ THEN NP=NP+1:GOTO 1599
1569 IF V(J)<@ THEN NN=NN41:G0TO 1599
15/76 NZ=NZ+1
1599 NEXT :M=W/N:VAZ@rIF N=1 THEN 1419
1689 VA=(SQ~NEMHM) / (N=)
1619 Sl=SOR (VA)
1629 PRINT" "SNPS"POSITIVES INNS "NEGATIVES" SNZs"ZERO”
14639 GOSUB 2700:PRINT"MINIMUM VALUE = "ZY(Z(N))
14649 PRINT’MAXIMUM VALUE = "S¥CZ(1))
1659 FRINT'RANGE = "3VC201))-UCZCN))
14669 PRINT'SUM OF THE VALUES = "“SW:sFRINT
1678 PRINT'MEAN = "3M
1489 Q=INTCN/2) +17 eM0=V(Z(Q)) SIF N/2>INT(N/2) THEN 1768
1499 MD=(YCZ (CQ) 4U(Z(Q-1))9)72
1788 PRINT’MEDIAN = "SMI
1718 PRINT'MID-RANGE = "3 (V¥CZ01))4V0Z0N)) 0/2
1728 PRINTSPRINT'STO. DEVIATION = "350
1738 PRINT’ VARIANCE = "3VA
1749 GOSUB 2998 :RETURN
2OOD PRINTSPRINT" IF YOU MAKE A MISTAKE, TYPE”
2819 PRINT B$5" TO RE-ENTER THE LAST DATUM."
236 BASIC Programs for the TRS-80

2929 PRINT:PRINT" WHEN THE LIST IS COMPLETED, TYPE"


2939 PRINT E$3;" TO TERMINATE THE LIST." sRETURN
2199 FOR J=1 TO 44sPRINT'+"5 sNEXTSRETURN
2399 PRINTsPRINT’ WHILE THE LIST IS
DISPLAYING, YOU CAN HIT"
2519 PRINT"ANY KEY TO CAUSE A TEMPORARY HALT. THE
DISPLAY"
2528 PRINT'WILL RESUME WHEN YOU HIT ANOTHER KEY.”
23.38 PRINTSPRINT" HIT ANY KEY TO START THE DISPLAY."
2349 RS=INKEY$sIF R$="" THEN 2349
2559 RETURN
2989 RS=INKEYS:IF R$="" THEN RETURN
2319 RS=INKEYSsIF R$="" THEN 2519
2928 RETURN
2799 IF Z(9)=1 THEN RETURN
2718 FOR J=1 TO NeZ(J)=JsNEXT:IF N=1 THEN RETURN
2728 NM=N-1T2FOR K=1 TO NsFOR J=1 TO NMeN1=Z¢J)
2739 N2=Z(J+1) IF VINT)EU(N2) THEN 2759
2748 ZC IFT ENTE ZC J) =N2
2758 NEXT NEXT 32Z(9)=1 RETURN
2988 PRINTsPRINT'HIT ANY KEY TO CONTINUE”
2919 R$=INKEY$:IF R$="" THEN 2919
2929 RETURN

EASY CHANGES

1. The program arrays are currently dimensioned to allow a


maximum of 100 data items. The total storage required for
the program depends on the maximum dimension parameter,
MX; whether or not identifiers are being used; and if so, on
the length of a typical identifier. A 16K TRS-80 has enough
storage for 500 data items with associated identifiers of 10
character length. If no identifiers are being used, over 900
data values can be accommodated. If there are more than 100
items in your application, you will need to adjust the value of
MX in line 160 and change the argument of the CLEAR func-
tion in line 130. To achieve up to 900 data items with no
identifiers, make these changes:
130 CLEAR 1000
160 MX=900
To achieve up to 500 data items with 10 character identifiers,
make these changes:
STATS 237

130 CLEAR 5000


160 MX=500
Note that the argument of the CLEAR function should be
greater than or equal to the value of MX times the average
identifier length. Even with no identifiers, this argument
must be at least the value of MX. Should an OS error (out of
string space) occur when running the program, try increasing
the argument of the CLEAR function and/or lowering the
value of MX, if possible.
2. Because of possible conflicts with identifiers in your list,
you may wish to change the special strings that signal termi-
nation of data input and/or the backing up of data input.
These are controlled by the variables E$ and B$, respectively.
They are set in line 150. If you wish to terminate the data
with /DONE/ and to back up with /LAST/ for example,
line 150 should be:
150 B$=‘‘/LAST/”:E$=“*/DONE/”’
3. You may wish to see your lists sorted from smallest value to
largest value instead of the other way around, as done now.
This can be accomplished by changing the “greater than”
sign (>) in line 2730 to a “‘less than” sign (<<). Thus:
2730 N2=Z(J+1):1F VONI)<V(N2) THEN 2750
This will, however, cause a few funny things to happen to the
statistics. The real minimum value will be displayed under the
heading “‘maximum”’ and vice-versa. Also, the range will have
its correct magnitude but with an erroneous minus sign in
front. To cure these afflictions, make these changes also:
1630 GOSUB 2700:PRINT“MINIMUM VALUE = ”;V(Z(1))
1640 PRINT“MAXIMUM VALUE = ”;V(Z(N))
1650 PRINT“RANGE = ”;V(Z(N))—V(Z(1))

MAIN ROUTINES

130-180 Initializes constants and dimensioning.


200 - 340 Displays messages, determines if identifiers will be
used.
400 - 630 Gets data from the user.
700 - 710 Checks that input contains at least one value.
720 - 830 Command mode - gets user’s next option and
does a GOSUB to it.
238 BASIC Programs for the TRS-80

1000- 1090 Subroutine to list data in the original order.


1200- 1340 Subroutine to list data in ranking order.
1500- 1740 Subroutine to calculate and display statistics.
2000 - 2350 Subroutines to display various messages.
2500- 2520 Subroutine to allow user to temporarily start and
stop display listing.
2700 - 2750 Subroutine to sort the list in ranking order.
2900 - 2920 Subroutine to detect if user has hit a key to
continue.

MAIN VARIABLES

MX Maximum number of data values allowed.


D$(MX) String array of identifiers.
V(MX) Array of the data values.
Z(MX) Array of the sorting order.
N Number of data values in current application.
F Flag on identifier usage (1=yes, O=no).
BS Flag string to back up the input.
E$ Flag string to signal end of the input.
N$ String for a null identifier.
R$ User input string.
NM N-1.
R Continuation option.
NP Number of positive values.
NN Number of negative values.
NZ Number of zero values.
Ww Sum of the values.
SQ Sum of the squares of the values.
M Mean value.
MD Median of the values.
VA Variance.
SD Standard deviation.
JK Loop indices.
© ,N2 Possible data locations to interchange during
sorting.
Q Work variable.

SUGGESTED PROJECTS

1. The sorting algorithm used in the program is efficient only


when the number of list items is fairly small—less than
STATS 239

twenty-five or so. This is because it does not do checking


along the way to see when the list becomes fully sorted. If
your lists tend to be longer than twenty-five items, you might
wish to use another sorting algorithm more appropriate for
longer lists. Try researching other sorts and incorporating
them into the program. To get you started, try these changes:
2720 Q=0:FOR J=1 TO N—-1:N1=Z(J)
2730 N2=Z(J+1):IF V(N1)>=V(N2) THEN 2750
2745 Q=1
2750 NEXT:IF Q=1 THEN 2720
2760 Z(0)=1: RETURN
If your lists are short, this routine will probably be a little
slower than the current one. However, for longer lists it will
save proportionately more and more time.
2. Because the INPUT statement is used when entering identi-
fiers, commas cannot be used inside identifier names. Basic
will ignore anything entered past the comma. This can be
circumvented if you use quotes around the identifier name,
but you may forget to do this. By modifying the input rou-
tine to use a series of INKEY$ commands, you can build up
the identifier strings piecemeal and allow imbedded commas.
Modify the appropriate routine to do this.
3, Many other statistical parameters exist to describe this kind
of data. Research them and add some that might be useful
to you. One such idea is classifying the data. This consists
of dividing the range into a number of equal classes and then
counting how many values fall into each class.
240 | BASIC Programs for the TRS-80
section 6
Miscellaneous Programs

INTRODUCTION TO MISCELLANEOUS PROGRAMS

These programs show how simple programs can do interesting


things. All of them have a mathematical flavor. They are short
and, as such, would be useful for study for those just learning
BASIC in particular or programming in general.
Monte Carlo simulation involves programming the computer
to conduct an experiment. (It doesn’t involve high-stakes gam-
bling!) PI shows how this technique can be used to calculate an
approximation to the famous mathematical constant pi.
PYTHAG will find all right triangles with integral side lengths.
A clever algorithm is utilized to do this.
Have you ever looked around your classroom or club meeting
and wondered if any two people had the same birthdate?
BIRTHDAY will show you what the surprising odds are.
Very high precision arithmetic can be done on the TRS-80
with the proper “‘know-how.”’ POWERS will calculate the values
of integers raised to various powers; not to the TRS-80’s “nor-
mal’’ six or sixteen digit precision, but up to 250 full digits of
precision.
242 | BASIC Programs for the TRS-80
BIRTHDAY

PURPOSE

Suppose you are in a room full of people. What is the proba-


bility that two or more of these people have the same birthday?
How many people have to be in the room before the probability
becomes greater than 50 per cent? We are talking only about
the month and day of birth, not the year.
This is a fairly simple problem to solve, even without a com-
puter. With a computer to help with the calculations, it becomes
very easy. What makes the problem interesting is that the correct
answer is nowhere near what most people immediately guess.
Before reading further, what do you think? How many people
have to be in aroom before there is better than a 50-50 chance
of birthday duplication? 50? 100? 200?

HOW TO USE IT

When you RUN the program, it starts by displaying headings


Over two columns of numbers that will be shown. The left
column is the number of people in the room, starting with one.
The right column is the probability of birthday duplication.
For one person, of course, the probability is zero, since there
is no one else with a possible duplicate birthday. For two
people, the probability is simply the decimal equivalent of
1/365 (note that we assume a 365 day year, and an equal likeli-
hood that each person could have been born on any day of the
year).
244 BASIC Programs for the TRS-80

What is the probability of duplication when there are three


people in the room? No, not just 2/365. It’s actually
1 — (364/365 times 363/365)
This is simply one minus the probability of no duplicate birth-
days.
The probability for four people is
1 — (364/365 times 363/365 times 362/365)
The calculation continues like this, adding a new term for
each additional person in the room. You will find that the result
(probability of duplication) exceeds .50 surprisingly fast.
The program continues with the calculation until there are
60 people in the room. You will have to BREAK the program
long before that to see the point where the probability first
exceeds 50 per cent.

SAMPLE RUN

NO. OF PROB. OF 2 OR MORE


PEOPLE WITH SAME BIRTHDAY
1 g
2 2.73973E-G3
3 8. 2G41E-G3
4 .8163558
5 ~8271355
6 6494624

(etc.)

PROGRAM LISTING
199 REM: COINCIDENT BIRTHDAY PROBABILITY PROBLEM
118 REM: COPYRIGHT 1979 BY TOM RUGG AND PHIL FELIMAN
129 CLS
138 PRINT'NO. OF PROB. OF 2 OR MORE"
149 PRINT" PEOPLE WITH SAME BIRTHDAY"
158 Q=1
148 FOR N=1 TO 68
179 PRINT N,1-Q
188 Q=Q:*(365-N)/365
198 NEXT N
298 ENT!
BIRTHDAY 245

EASY CHANGES

1. Change the constant value of 60 in line 160 to alter the range


of the number of people in the calculation. For example,
change it to 100 and watch how fast the probability ap-
proaches 1.
2. Insert this line to make double precision calculations:
125 DEFDBL Q

MAIN ROUTINES

120 - 140 Displays headings.


150 Initializes Q to 1.
160- 190 Calculates probability of no duplication, then
displays probability of duplication.

MAIN VARIABLES

N Number of people in the room.


Q Probability of no duplication of birthdays.

SUGGESTED PROJECTS

Modify the program to allow for leap years in the calculation,


instead of assuming 365 days per year.
246 BASIC Programs for the TRS-80
PI

PURPOSE AND DISCUSSION

The Greek letter pi, 7 represents probably the most famous


constant in mathematical history. It occurs regularly in many
different areas of mathematics. It is best known as the constant
appearing in several geometric relationships involving the circle.
The circumference of a circle of radius r is 27r, while the area
enlosed by the circle is mr?.
Being a transcendental number, picannot be expressed exactly
by any number of decimal digits. To nine significant digits, its
value is 3.14159265. Over many centuries, man has devised
many different methods to calculate pi.
This program uses a valuable, modern technique known as
computer simulation. The name “‘simulation”’ is rather self-
explanatory; the computer performs an experiment for us.
This is often desirable for many different reasons. The experi-
ment may be cheaper, less dangerous, or more accurate to run
on a computer. It may even be impossible to do in “‘real life.”’
Usually, however, the reason is that the speed of the computer
allows the simulation to be performed many times faster than
actually conducting the real experiment.
This program simulates the results of throwing darts at a
specially constructed dartboard. Consider Figure 1 which shows
the peculiar square dartboard involved. The curved arc, outlining
the shaded area, is that of a circle with the center in the lower
left hand corner. The sides of the square, and thus the radius of
the circle, are considered to have a length of 1.
248 BASIC Programs for the TRS-80

-
ond
©

Figure 1. The Pl Dartboard

Suppose we were able to throw darts at this square target in


such a way that each dart had an equal chance of landing any-
where within the square. A certain percentage of darts would
result in “‘hits,’’ i.e. land in the shaded area. The expected value
of this percentage is simply the area of the shaded part divided
by the area of the entire square.
The area of the shaded part is one fourth of the area the entire
circle would enclose if the arc were continued to completely
form the circle. Recall the area of a circle is mr* where ris the
radius. In our case, r=1, and the area of the entire circle would
simply be a. The shaded area of the dartboard is one fourth of
this entire circle and thus has an area of 7/4. The area of the
square is s*, where s is the length of a side. On our dartboard,
s=1, and the area of the whole dartboard is 1.
P| 249

Now the expected ratio of “hits” to darts thrown can be


expressed

#hits shaded area 7/4


RATIO = = =— =
# thrown entire area 1 1 4
SO we now have an experimental way to approximate the value
of a. We perform the experiment and compute the ratio of
“‘*hits’” observed. We then multiply this number by 4 and we
have calculated m expenmentally.
But instead of actually constructing the required dartboard
and throwing real darts, we will let the TRS-80 do the job. The
program “throws” each dart by selecting a separate random
number between O and | for the X and Y coordinates of each
dart. This is accomplished by using the built-in RND function
of Basic. A “‘dart’’ is in the shaded area if X*? + Y* <1 forit.
So the program grinds away, continually throwing darts and
determining the ratio of “hits.” This ratio is multiplied by 4 to
arrive at an empirical approximation to 7.

HOW TO USE IT

The program requires only one input from you. This is the
‘“‘sample size for printing,” i.e. how many darts it should throw
before printing its current results. Any value of one or higher
is acceptable.
After you input this number, the program will commence the
simulation and display its results. A cumulative total of “hits,”
darts thrown, and the current approximation to 7 will be dis-
played for each multiple of the sample size.
This will continue until you press the BREAK key. When you
are satisfied with the total number of darts thrown, press the
BREAK key to terminate the program execution.

SAMPLE RUN

A DARTBOARD PI CALCULATOR

SAMPLE SIZE FOR PRINTING? 15@


250 BASIC Programs for the TRS-80

A DARTBOARD PI CALCULATOR
# HITS # THROWN PI

116 158 3.99333


230 302 3.06667
337 456 2.99556
462 626 3.98
584 758 3.11467
697 992 3.689778
818 1852 3.11619
949 1266 3.13333
166¢ 1352 3.14974
1179 152 3.144

( BREAK key pressed)

PROGRAM LISTING

189 REMs FI
1198REM: COPYRIGHT 1979 BY PHIL FELUMAN AND TOM RUGG
159 RANTIOMECLEAR SM@sUEFINT J
149 T=O2 THe
398 GOSUB 68d
3198TNPUT'SAMPLE SIZE FOR PRINTING" 9 NF
A28 NP INTONPO STF NFAT THEN 3986
338 GOSUB 699
349 PRINTSR HITS # THROWN" 5 TAB( 34) 2"R I"
4G GOSUB 540s TH=THtNHs T= T+NF eh sel H/T
419 PRINT TH. T.F
429 GOTO 484
98 NH=@sFOR J=1 TO NF
“1d KERNTCA) sY=RNGCG)
28 IF (XeX+YY 1 THEN NH=NH+1
3G NEXT sRE TURN
688 CLSOsPRINT TABCS)5
619 PRINT'A TIARTROART PI CALCULATOR"
629 PRINT sRE TURN
251

EASY CHANGES

1. If you want the program to always use a fixed sample size,


change line 310 to read
310 NP=150
Of course, the value of 150 given here may be changed to
whatever you wish. With this change, line 320 is not needed
and may be deleted.
.If you want the program to stop by itself after a certain
number of darts have been thrown, add the following two
lines:
315 INPUT“TOTAL # DARTS TO THROW” ;ND
415 IF T>=ND THEN END
This will ask the operator how many total darts should be
thrown, and then terminate the program when they have
been thrown.
. The calculated values of pi will be shown with six digits of
precision as is standard for single precision variables in
Level II Basic. This is sufficient for the degree of accuracy
possible in this simulation. However, you might want to try
the following change to see the effects of computing pi to
double precision:
155 DEFDBL P-Z

MAIN ROUTINES

150-160 Initializes constants.


300 - 340 Gets operator input, displays column headings.
400 - 420 Calculates and displays results.
500- 530 Throws NP darts and records number of “‘hits.”’
600 - 620 Clears screen and displays program title.

MAIN VARIABLES

T Total darts thrown.


TH Total “‘hits.”’
NP Sample size for printing.
NH Number of hits in one group of NP darts.
P Calculated value of pi.
252 BASIC Programs for the TRS-80

X, Y Random-valued coordinates of a dart.


J Loop index.

SUGGESTED PROJECTS

1. Calculate the percentage error in the program’s calculation


of pi and display it with the other results. You will need to
define a variable, say PI, which is set to the value of pi. Then
the percentage error, PE, can be calculated as:
PE = 100*ABS(P — PI)/PI
2. The accuracy of this simulation is highly dependent on the
quality of the computer’s random number generator. Try re-
searching different algorithms for pseudo random number
generation. Then try incorporating them into the program.
Change line 510 to use the new algorithm(s). This can actually
be used as a test of the various random number generators.
Gruenberger’s book, referenced in the bibliography, contains
good material on various pseudo random number generators.
POWERS

PURPOSE

By now you have probably learned that the TRS-80 keeps


track of six significant digits when dealing with numbers. For
integers less than one million (1,000,000), the TRS-80 can re-
tain the precise value of the number. But for larger integers the
TRS-80 only keeps track of the most significant (leftmost) six
digits, plus the exponent. This means, of course, that there is no
way you can use the TRS-80 to deal with precise integers
greater than one million, right?
Wrong.
Of course, you say. You can use double precision variables to
get precise results up to 16 digits. So, undoubtedly, the absolute
limit on the TRS-80 is 16 digit integers, right?
Wrong again.
This program calculates either factorials or successive powers
of an integer, and can display precise results that are up to 250
digits long. By usinga “‘multiple-precision arithmetic”’ technique,
this program can tell you exactly what 973 to the 47th power
is, for example.

HOW TO USE IT

The program first asks you how many digits long you want
the largest number to be. This can be any integer from 1 to 250.
So, for example, if you enter 40, you will get answers up to
forty digits long.
254 BASIC Programs for the TRS-80

Next you are asked for the value of N. If you respond with a
value of 1, you are requesting to be shown all the factorials that
will fit in the number of digits you specified. First you will get
one factorial, then two factorial, and so on. In case you have
forgotten, three factorial is 3 times 2 times 1, or 6. Four fac-
torial is 4 times 3 times 2 times 1, or 24.
If you enter an N in the range from 2 through 100,000, you
are requesting the successive powers of that number up to the
limit of digits you specified. So, if you provide an N of 23, you
will get 23 to the first power, then 23 squared, then 23 cubed,
and so on.
Finally, after it has displayed the largest number that will fit
within the number of digits you entered, the program starts
over. The larger the number of digits you ask for, the longer
it will take the program to calculate each number.

SAMPLE RUN

POWERS AND FACTORIALS

NUMBER OF DIGITS? 48
LE h2

i 98789
2 Baal asa
3 BU Ck SF
rt ava ha: Jest cS
3 Bet RRS nae)
) Bis SCL NaC RC S|
Fi Sn nae eR abe era
cs Bana SEK eee Sass Ue cl

NUMBER OF DIGITS? _

The operator wants answers up to 40 digits long in the calculations of the


powers of 98789. The program calculates numbers up to 987898 and then
asks for the number of digits again (in preparation for the next calculation
the operator requests).
POWERS 255

PROGRAM LISTING

189 REM: POWERS AND FACTORIALS


119 REM: COPYRIGHT 1979 BY TOM RUGG AND PHIL FELDMAN
129 CLS:CLEAR S@:DEFINT J,f
139 PRINT TAB(19);"POWERS AND FACTORIALS"
149 PRINT
169 DIM N(255)
179 INPUT"NUMBER OF DIGITS" 5M
182 M=INT(M) SIF M2259 OR M1 THEN 179
199 INPUT"N" SN
299 N=INT(N)
219 IF N<1 OR N?>199998 THEN 199
229 PRINT
2359 F=9:sIF N=? THEN F=1sPRINT"FACTORIALS"
249 IF F=@ THEN PRINT"POWERS OF" SN
258 T=19sK=12N(@)=N
269 FOR J=8 TO
279 IF N(JO<T THEN 399
289 Q=INTCN(J)/T) SWEN( JS) -OQeT
299 NC J=WENCI+T ENC J+1 +0
388 NEXT
319 J=M+1
529 IF N(J)=8 THEN J=J-1:2G0TO 329
539 IF J>=M THEN 59¢
349 N=9:PRINT K3TAR(?);
358 NS=STRS (NCJ) ) SNS=RIGHTS (NS, 1)
369 U=0+12IF 0258 THEN D=1sPRINTsPRINT TAB(?);5
3/9 PRINT N$;eJ=J-1sIF Jo=8 THEN 359d
389 Ik F=1 THEN N=N+1
399 K=K+1sPRINT
ABD FOR J=@ TO MsN(J)=NCJ)4NSNEXT
419 GOTO 269
389 FOR J=1 TO 255:N(J)=@sNEXT
319 N=9:N=@:2PRINT:GOTO 179

EASY CHANGES

1. To change the program so that it always uses, say, fifty digit


numbers, remove lines 170 and 180, and insert this line:
170 M=50
2. To clear the screen before the output begins being displayed,
change line 220 to say:
220 CLS
256 BASIC Programs for the TRS-80

3. If 250 digits isn’t enough for you, you can go higher. For
500 digits, make these changes:
a. In line 160, change the 255 into 505.
b. In line 180, change the 250 into 500.
c. In line 500, change the 255 into 505.

MAIN ROUTINES

120- 160 Displays title. Sets up array for calculations.


170 - 240 Asks for number of digits and N. Checks validity
of responses. Displays heading.
250 Initializes variables for calculations.
260- 300 Performs “‘carrying”’ in N array so each element
has a value no larger than 9.
310-320 Scans backwards through N array for first non-zero
element.
330 Checks to see if this value would be larger than
the number of digits requested.
340 - 370 Displays counter and number. Goes to second line
if necessary.
380- 390 Prepares to multiply by N to get next number.
400-410 Multiplies each digit in N array by N. Goes back
to line 260.
500
- 510 Zeroes out N array in preparation for next request.
Goes back to 170.

MAIN VARIABLES

Array in which calculations are made.


£2

Number of digits of precision requested by opera-


tor.
Starting value. If 1, factorials. If greater than 1,
2

powers of N.
Set to zero if powers, | if factorials.
QoAAT

Constant value of 10.


Counter of current power or factorial.
Subscript variable.
Temporary variables used in reducing each integer
position in the N array to a value from 0 to 9.
POWERS 257

D Number of digits displayed so far on the current


line (maximum is 50).
N$ String variable used to convert each digit into dis-
playable format.

SUGGESTED PROJECTS

1. Determine the largest N that could be used without errors


entering into the calculation (because of intermediate results
exceeding one million), then modify line 210 to permit
values that large to be entered. Then declare the necessary
variables to be double prcision, and determine how large N
can be.
2. Create aseries of subroutines that can add, subtract, multiply,
divide, and exchange numbers in two arrays, using a technique
like the one used here. Then you can perform high precision
calculations by means of a series of GOSUB statements.
258 BASIC Programs for the TRS-80
PYTHAG

PURPOSE

Remember the Pythagorean Theorem? It says that the sum of


the squares of the two legs of a right triangle is equal to the
square of the hypotenuse. Expressed as a formula, it is a? + b?
= c*, The most commonly remembered example of this is the
3-4-5 right triangle (37 + 4% = 5). Of course, there are an
infinite number of other right triangles.
This program displays integer values of a, b, and c that result
in right triangles.

HOW TO USE IT

To use this program, all you need to do is RUN it and watch


the ‘“‘Pythagorean triplets” (sets of values for a, b, and c) come
out. The program displays twenty sets of values on each screen,
and then waits for you to press any key (except BREAK)
before it continues with the next twenty. It will go on indefin-
itely until you press the BREAK key.
The left-hand column shows the count of the number of sets
of triplets produced, and the other three columns are the values
ofa, b, andc.
The sequence is which the triplets are produced is not too
obvious, so we will explain how the numbers are generated.
It has been proved that the following technique will generate
all primitive Pythagorean triplets. (‘‘Primitive’> means that no
set is an exact multiple of another.) If you have two positive
integers called R and S such that:
260 BASIC Programs for the TRS-80

1. Ris greater than S,


2. R and S are of opposite parity (one is odd and the other is
even), and
3. Rand S are relatively prime (they have no common integer
divisors except 1),
then a, b, and c can be found as follows:
a= R? — S?
b=2RS
c=R? +S?
The program starts with a value of 2 for R. It generates all
possible S values for that R (starting at R—1 and then decreasing)
and then adds one to R and continues. So, the first set of triplets
is created when R is 2 and S is 1, the second set when R is 3 and
Sis 2, and so on.

SAMPLE RUN

eet PYTHAGOREAN TRIPLETS se:


COUNT --A-~ --B-~ ~-C--
3 4 5
2 5 12 13
3 7 24 25
4 15 g 17
5 9 4g ay
é 21 2g 29
? 11 69 61
8 35 12 37
9 13 84 85
19 33 56 65
1 45 28 53
12 15 112 113
13 39 ag 89
PRESS ANY KEY TO CONTINUE
PYTHAG 261

PROGRAM LISTING
189 REM: PYTHAGOREAN TRIPLETS
119 REM: COPYRIGHT 1979 BY TOM RUGG AND PHIL FELDMAN
129 CLEAR S@:DEFDBL A~Z
139 R=2ek=1s0=9
15d GOSUB 359
188 S=R~-1
198 A=R#*R-S:#5
299 B= 2eRS
219 C=R#R+545
229 PRINT K,A,B,C
2359 K+) sU=0+1:G0TO 489
249 S=$-2:IF S<=@ THEN R=R+1:GOTO 189
209 S1=5
250 B1=R
269 N=INT(B1/S1)
279 R1=B1-(S1#N)
289 IF R1<2@ THEN B1=51:S1=R1:G0TO 249
589 IF S1<>1 THEN 249
329 GOTO 199
3a8 CLS
548 PRINT TAB( 19) 5 "et: PYTHAGOREAN TRIPLETS ‘tte!
PRINT" COUNT" ,"--A--", "=-B-~","--C--"
589
398 RETURN
499 IF D<13 THEN 249
429 PRINT'PRESS ANY KEY TO CONTINUE";
439 IF INKEY$="" THEN 439
449 GOSUB 359
459 D=9
449 GOTO 249

EASY CHANGES

1. Alter the starting value of R in line 130. Instead of 2, try


50 or 100.
2. If you want, you can change the number of sets of triplets
displayed on each screen. Change the 13 in line 400 to a 10,
for example. You probably won’t want to try a value greater
than 13, since that would cause the column headings to roll
off the screen.
3. To make the program continue without requiring you to
press a key for the next screen of values, insert either of these
lines:
262 BASIC Programs for the TRS-80

405 GOTO 440


Or
405 GOTO 450
The first will display headings for each screen. The second
will only display the headings at the beginning of the run.

MAIN ROUTINES

130 Initializes variables.


150 Displays the title and column headings.
180 Calculates first value of S for current R value.
190-210 Calculates A, B, and C.
220- 230 Displays one line of values. Adds to counters.
240 Calculates next S value. If no more, calculates
next R value.
250
- 300 Determines if R and S are relatively prime.
350
- 390 Subroutine to display title and column headings.
400
- 460 Checks if screen is full yet. If so, waits for key to
be pressed.

MAIN VARIABLES

R,S See explanation in “How To Use It.”’


K Count of total number of sets displayed.
D Count of number of sets displayed on one screen.
A,B,C Lengths of the three sides of the triangle.
S1,B1, Used in determining if R and S are relatively
RI,N prime.

SUGGESTED PROJECTS

1. In addition to displaying K, A, B, and C on each line, display


R and S. You will have tosqueeze the columns closer together.
2. Because this program uses integer values that get increasingly
large, eventually some will exceed the TRS-80’s double pre-
cision integer capacity and produce incorrect results. Can you
determine when this will be? Modify the program to stop
when this occurs.
Appendix |
Memory Usage

Each of the programs in this book will fit in a Radio Shack


TRS-80 Level I] computer that has 16K or more of user mem-
ory. If your TRS-80 has only 4K of user memory, you’ll find
that the great majority of the programs will still fit in your com-
puter with no changes. A few other programs will require minor
changes that are discussed in the text of the corresponding
chapters.
Based on our estimates, here are the programs that will not
fitin a 4K TRS-80:

Programs that will probably fit in a 4K TRS-S80 if you make


fairly extensive changes:
(for example, eliminating unnecessary spaces from program
statements, reducing the length of text literals where possible,
deleting REM statements, removing unneeded options, reducing
array sizes where possible, etc.)

CHECKBOOK

Programs that are too large to be compressed into 4K:

DECIDE, JOT, STATS


264 BASIC Programs for the TRS-80
Bibliography

BOOKS

Bell, R. C., Board and Table Games From Many Civilizations,


Oxford University Press, London, 1969. (WARIT)
Brown, Jerald R., Instant BASIC, Dymax, Menlo Park, Calif.,
1977. (Self-teaching text on the BASIC language)
Cohen, Daniel, Biorhythms in Your Life, Fawcett Publications,
Greenwich, Connecticut, 1976. (BIORHY THM)
Crow, E. L., David, F. A., and Maxfield, M. W., Statistics Manual,
Dover Publications, New York, 1960. (STATS)
Croxton, F. E., Crowden, D. J., and Klein, S., Applied General
Statistics (Third Edition), Prentice-Hall, Englewood Cliffs,
N. J., 1967. (STATS)
Gruenberger, Fred J., and Jaffray, George, Problems for Com-
puter Solution, John Wiley and Sons, New York, 1965.
(BIRTHDAY, PI)
Gruenberger, Fred J., and McCracken, Daniel D., Introduction
to Electronic Computers, John Wiley and Sons, New York,
1961. (MILEAGE, PI, PYTHAG, WARI as Oware)
Hildebrand, F. B., Introduction to Numerical Analysis, McGraw-
Hill, New York, 1956. (CURVE, DIFFEQN, INTEGRATE,
SIMEQN)
Kuo, S. S., Computer Applications of Numerical Methods,
Addison-Wesley, Reading, Massachusetts, 1972.
(CURVE, DIFFEQN, INTEGRATE, SIMEQN)
266 BASIC Programs for the TRS-80

McCracken, Daniel D., and Dorn, W. S., Numerical Methods


And FORTRAN Programming, John Wiley and Sons,
New York, 1964. (CURVE, DIFFEQN, INTEGRATE,
SIMEQN)
Shefter, Harry, Faster Reading Self-Taught, Washington Square
Press, New York, 1960. (TACHIST)

PERIODICALS

Feldman, Phil, and Rugg, Tom, “‘Pass the Buck’’, Kilobaud,


July 1977, pp. 90-96. (DECIDE)
Fliegel, H. F., and Van Flandern, T. C., ““A Machine Algorithm
for Processing Calendar Dates’, Communications of the
ACM, October, 1968. p. 657. (BIORHYTHM)
267

All of the programs in this book have been tested carefully


and are working correctly to the best of our knowledge. How-
ever, we take no responsibility for any losses which may be
suffered as a result of errors or misuse. You must bear the
responsibility of verifying each program’s accuracy and applica-
bility for your purposes.
If you want to get a copy of an errata sheet that lists cor-
rections for any errors or ambiguities we have found to date,
send one dollar ($1.00) and a self addressed stamped envelope
(SASE) to the address below. Ask for errata for this book (by
name). We hope we won’t have any errors to tell you about, in
which case we'll try to send you some other worthwhile infor-
mation about the TRS-80.
If you think you’ve found an error, please let us know. If you
want an answer, include a SASE.
Tom Rugg and Phil Feldman
Errata—32 Programs for the TRS-80
P.O. Box 24815
Los Angeles, CA 90024
About the Authors...
TOM RUGG ana PHIL FELDMAN have a long-standing association
with the microcomputer field. Together they wrote the popular col-
umn ‘‘Games and Things” in SOUTHERN CALIFORNIA COMPUTER
SOCIETY INTERFACE and are presently associate editors at KILO-
BAUD magazine, for which they have written numerous articles. This
is their second book.

About the Book...


32 BASIC PROGRAMS FOR THE TRS-80 (LEVEL II) COMPUTER is
precisely that. . .32 fully documented programs that are ready-to-run
on your TRS-80 computer. You also have the option of making a
number of changes, as suggested, to these programs if you wish.
Ths book is an absolute must for the TRS-80 owner.

A Division of Tandy Corporation

You might also like