100% found this document useful (1 vote)
300 views

Techniques of BASIC (1981)

.

Uploaded by

Delfin Butlonosy
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
100% found this document useful (1 vote)
300 views

Techniques of BASIC (1981)

.

Uploaded by

Delfin Butlonosy
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/ 274

TECHNIQUES

·O F B A S IC
John P. Gril lo/J. D. Robertson
Bentley College
Waltham, Massachusetts

Date Due

TECHNIQUES OF BASIC

rncb
Personal Computer Seri es
Wm. C. Brown Company Publishers
Dubuque , Iowa 52001

/
Copyright © 1981 by Wm. C. Brown Company Publishers

Library of Congress Catalog Card Number: 81-65445

ISBN 0-697--{)9951- 2

All rights reserved. No part of this publication may be reproduced,


stored in a retrieval system, or transmitted, in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise,
without the prior written permission of the publisher.

Third Printing, 1982

Printed in the United States of America


TECHNIQUES
OF BA SIC
'}£,:~'·
To Our families
Contents Acknowledgements xi

Introduction xiii

1 Decisions and Branching


IF-THEN-ELSE 1
Logical Operators 4
ON-GOTOandON-GOSU B 6

2 Statements and Functions 9


Multiple Statements on a Line 9
RND Function 10
RANDOM 11
DIM and Subscripted Variables 12
String Functions 22
User-defined Functions 26

3 Input and Output 29


Cued INPUT 29
LPRINT 30
PRINT USING 30
INP and OUT 39
PEEK and POKE 40

4 Variables 43
Long Variable Names 43
Variable Types , 44
Conversion of Constants 45
Implicit Conversion 48
Memory Storage After Mixed Operations 49
DEFINT, DEFSNG, DEFDBL, DEFSTR 51
Hexadecimal and Octal Constants §2
VARPTR 53

vii
5 Graphics 55
Line Printer Graphics 55
Character Graphics 7 5
Pixel Graphics 84

6 I/0, Strings, and Disk BASIC 103


DEFUSR and USRn 103
POS, INSTR, and MID$ 105
INKEY$ 107
LINE INPUT 109
MID$ for Replacement 111
TIME$ 112

7 Sequential Access File Processing 117


Commands for Program Files 117
Commands for Data Files 120

8 Direct Access File Processing 133


FIELD 134
GET 137
LOP 138
LSET and RSET 138
PUT 139
MKI$, MKS$, and MKD$ 140
CVI, CVS, and CVD 141
Direct Access File Creation 142
Direct Access File Processing 144

9 Conversational Programming 149


User Prompts and Menus 149
ERR, ERL, ON ERROR GOTO, and RESUME 153
Anticipating User Responses 155
Check Digit Calculations 157
Praise and Chastisement 160
Informing the User During Processing 162

10 Structured Programming 165


Program Planning 166
Phrase Flowcharts 167
ANSI Flowcharts 167
Programming Structures 171
GOT0-1ess Programming 174
Top-down Programming 176

11 Documentation 179
Internal Documentation 179
External Documentation 183

viii Contents
12 File Manipulation Techniques 187
Building 18 7
Accessing 193
Modifying 197
Deleting 197
Sorting 197
Sorting Algorithms 199
Direct Access File Statistics Program 204

13 Inventory System Application 213


Appendix 239
A Comparison of Three BASICs 240
B ASCII Codes and Character Set for the TRS-80 241
C 48K TRS-80 Level II with Disk Memory Map 243
D Level II Instructions and Reserved Words 244
E TRSDOS Commands 245
F Error Codes 246

Index 249

Contents ix
Acknowledgements When two people decide to write a book, the problem s of
planning, commu nicatio n, and finally produc tion are compou nded.
Were it not for the efforts of Ed Bowers and Rita Dunkin of the
Wm. C. Brown Business, Professional, and Trade Division, we would
not have maintai ned our enthusi asm during this project . We are
indebte d to them for their patienc e and foresight.
We owe special thanks to Steve Grillo, who as a 1980 high
school graduat e, has demons trated a level of talent and
responsibility beyond his years. He proofre ad the book, helped type
the final manusc ript, shot, developed, and printed all picture s in the
book, and wrote a substan tial portion of the programs.

xi
Introduction BASIC has come a long way since its first days at Dartmo uth
College in 1964, when because of its simplicity it helped student s
to learn about the comput er. It has evolved in two stages. The first
stage occurre d in the early 1970's when minico mputer s became
standar d fixtures in many small business, scientific, and educati onal
environments. At that time BASIC became more than a curiosity.
Because of its expand ed features, particu larly file manage ment, it
began to appear as the applica tion language of choice for the
popula r minis.
The second stage of BASIC's evoluti on is occurring right now,
at the turn of the decade. The popular ization of the microc ompute r
in the last three years of the 1970's has resulted in BASIC being the
de facto standar d as a high-levellanguage for these new devices.
Remem ber that minis were used primari ly in small businesses,
scientific labs, and schools. The micros have come into the home,
and BASIC has come with them. Sudden ly the phrase "compu ter
power to the people " means someth ing tangible to millions of
individuals. The decade of the '80s is going to see a substan tial
fraction of the public actively involved in developing programs for
their acquisition, and most of these program s will be written in
BASIC.
All this is fine, as long as this tool is used for its intende d
purpose , that being to enterta in, educate , calculate, and manage
files. However, many purchasers of microc ompute rs will bring it
home, play a few games of Blackjack, Chess, or Star Trek, and
perhaps maintai n a recipe file. This is not enough. These devices
are more powerf ul than the million-dollar comput ers of the 1960's,
and to use them only for such trivial tasks is to waste their true
potenti al. It's as if you were to buy a TV set and leave it tuned to
just one channel. Microc ompute r power should be explore d and
exploit ed to its fullest, and one way you can do so is to use it for
more than repetiti ve executi on of one or a few programs. Program
it yourself.
As educato rs we have expose d many student s to the joys of
compu ter programming, and we are continu ally surprised at the
variety of people who exhibit a talent for this science, or art, or
craft. No general rule seems to apply; program ming talent seems to
appear in a fairly large and unpred ictable segment of the populat ion.

xiii

/'
The micro comp uter revolution will add greatly to the growing
people
numb ers who know how to write programs. A few of these
mmer s. Our aim with this book is to
will becom e excellent progra
progra mmer s by expos ing them to some
increase the ranks of better
g proble ms that are comm only found in a wide
techni ques for solvin
variety of applications. ·
When you write a progra m, remem ber that you must consider
three differ ent points of view.
r.
1. The progra mmer is the originator of the progra m, its creato
In many situations, you will find no existing progra m that
even remot ely begins to solve your problem. This is when
your skill as a programmer is tested to its fullest. You are
most of all a proble m solver at this stage, and your major
task is to decide on the metho d of soluti on, or algorithm,
for your problem.
r,
2. The reader of your program is very possibly also its autho
but may also be someone else who wishes to adapt it to his
or her own application. A program's reader must
under stand the fvndamentals of the language about as well
as the programmer, but is rarely involved in its original
creation. The remarks in a program are intend ed for its
reader. During your progra m's development, you are also
its reader, and you can use the remarks effectively to remin d
you of the program's logic or to help modularize it for easier
alteration.
3, The user of your program is the intend ed target for its
application. Usually, that person is naive about comp uters
and programs. The program, its advanced techniques, and
its wealth of remarks are lost to the user. But you, the
programmer, must always keep the user in mind. Here's one
of the few gener al rules that has no exceptions: All well
'writt en programs are easy to run.

The programs, program segments, and examples contai ned


Level-11
within this book h-ave been tested on a Radio Shack TRS-80
ced
system with one minifl oppy disk drive. The listings were produ
sely
on an Integral Data Systems Model 225 printe r. We have purpo
s.
orient ed this book towar d the TRS-80 for the following reason
1. The TRS-80 is one of the many micro comp uters that use
Microsoft BASIC, which is fast becoming a standa rd of
comparison for perfor mance and for variety of extensions.
2. The TRS-80 as of this writing is the most popul ar
micro comp uter for personal use, and its Level II BASIC is a
subset of the BASIC that is imple mente d on its bigger
brothe r, the TRS-80 Model II. The Model II gives all
indica tions of becoming a very popul ar small business
comp uter.
3. The TRS-80 does not have a color display monit or, so its
BASIC does not have the variety of comm ands to manage
that aspect of outpu t. This may seem to be a disadvantage,

xiv Introd uction


but the fact is that of all of the sets of BASIC comman ds
that are available on microco mputers , those that deal with
color displays are the least standard ized.
4. The TRS-80 has a wide range of available peripheral
equipme nt. In addition , the TRS-80' s populari ty has
prompte d many peripher al manufac turers other than Tandy
to produce competi ng hardwar e, including hard disks with
capacities on the order of 20 million characters.

We hope that you will try out all of the features that are
discussed in this book. Your reward will be a deep understa nding
of both a fine compute r program ming language and some excellent
program ming techniqu es.

Introduction
XV
''
''

''
\'

f'

l
\,I

,,
j

Decisions and The IF-THEN and the GOTO are certainly simple to learn and
Branching understand, but as a person improves in programming techniques,
the limitations of these statements become a real burden. This is
where the extensions to the language are particularly rewarding.
They are very easy to learn and use, and they make any program
easier to read.

IF-THEN-ELSE Primitive BASIC is limited to having just a line number


following the THEN, for example:

300 IF X=A THEN 820

This restriction leads to awkward programs full of GOTOs


that force the reader to jump around from one line of code to
another. This process of bypassing some lines and tracing the
program in various sequences tends to frustrate both the programmer
and the reader. As an example of this poor, and all too common
type of programming, look at the program below:

Otapter 1 Decisions and Branching 1


10 'FILENAf1E: "C1P1"
20 'FUNCTION! TO FIND LARGEST OF 3 NUMBERS POORLY STRUCTURED>
3(1 AUTHOF: :
I JPG DATE~ 12/ 9
40 DATA 1'2'3'1'3'2,22,11,33,22,33;11,35~15,25,35,25,15,0,0r0
50 'read three values from data block
60 F:EAD A,B,C
70 IF A*B*C=O THEN 10000
80 'check lo see if A is larsest
90 IF B > A THEN 130
100 IF C > A THEN 170
110 L =A
120 GOTO 190
130 'check to see if B is larsest
140 IF C > B THEN 170
150 L =B
160 GOTO 190
170 'here we know that C is larsesl
18(1 L =C
190 'Print the value of L; it is the larsesl
200 LPRINT L; "JS THE LARGEST OF"; A; Bi C
21(1 GOTO 60 .
10000 END
3 IS THE LARGEST OF 1 2 3
3 IS THE L.AF:GEST OF 1 3 2
Tl"
33 .i;:) THE LARGEST OF 22 11 33
33 IS THE LARGEST OF 22 33 11
35 IS THE LARGEST OF 3.,..J 15 25
"Zt:" , r··
w.J .i;:) THE Li~f<GEST OF 35 25 15

*Note: The LPRINT command is used here and throughout the


book whenever we wish to show the program's output. To
run the program on your computer and have the output
appear on th~ screen, just change all LPRINT commands to
PRINT.

The program ClPl is difficult to compose, to trace, and to


debug. Extended BASIC lets the programmer instruct the computer
to do something after finding out that the condition is true, instead
of just branching somewhere else. Look at this rewrite of the same
program.

2 Chapter 1 Decisions and Branching


10 FILENAME! "C1P2"
I

20 FUNCTION! TO FIND LARGEST OF 3 NUMBERS <BETTER)


I

30 AUTHOR : JPG
I DATE! 12/79
40 I

50 DATA 1r2r3,1r3r2r22,11r33,22,J3,11,35r15,25,35,25,15,0,0r0
60 'read three values from data block
70 READ ArBrC
80 IF A*B*C=O THEN 10000
90 ' store the lar~est in L, then Print L
100 IF A>B THEN IF A>C THEN L=A
110 IF B>A THEN IF B>C THEN L=B
120 IF C>A THEN IF C>B THEN L=C
130 LPRINT Li "IS THE LARGEST OF"; A; B; C
140 GOTO 70
10000 END

· Notice that the decisions in this program have no branches. Each IF


statement checks the truth of a pair of conditions, and the value of
Lis set when both conditions within the same statement are true.
But extended BASIC has even more. The THEN clause may be
followed by another clause, called the ELSE clause. The resulting
compound statement allows the programmer to specify one statement
to be executed if the condition is true, and another statement if the
condition is false.

50_ if discriminant D of auadratic eauation is


1
non-ne~ative,
60 'then comPut~ and Print the roots; otherwise Print the
70 1 messa~e' "NO REAL ROOTS"
80 D=B*B-4*A*C ' calculate the discriminant
90 D2=2*A ' calculate denoulinator of cwadratic eauation
100 IF D>=O THEN PRINT "ROOTS="i<-B*SQR(D})/D2i(-B-SGR<D>>ID2
ELSE PRINT "NO REAL ROOTS"
110 I

120 I

2(l0 let user sLoP or· Proceed, but accePt onll:l YES or NO answer
I

210 PRINT "DO YOU WANT TO GO ON <ANSWER YES OR NO>"i


220 INPUT A$
230 IF A$="NO" THEN STOP
ELSE IF A$()"YES" THEN 210

Chapter 1 Dc~cisions and Branching 3


al state ment s
Logical Oper ators This feature allows more English-looking cond ition
by the use of OR, AND, and NOT opera tors.

10 'if A is less than Ban d A is less than c,


20 'then Prin t A as the sma llest .
"
30 IF A<B AND A<C THEN PRINT A; "IS SMALLEST500
40 IF AS="YES" OR AS="SURE " OR AS="OK" THEN

logical
Program ClP3 shows how much more readable these
sed to neste d IFs or an abun danc e
opera tors are in a program, as oppo
ofGO TOs.

l(l·'FILENAMEt "C1P3"
(BEST)
20 'FUNCTION: TO FIND LARGEST OF 3 NUMBERS 1
30 AUTHOR : .JPG
I
D~iTE: 12/7'
40 I
,35, 25,1 5,0, 0,0
50 DATA 1'2'3 '1'3' 2,22 ,11, 33,2 2,33 ,11, 35,1 5,25
60 'rea d thre e valu es from data block
n f<EAD A,B,C
80 IF A*B*C=O THEN 10000
90 'fin d and Prin t the lars est all in one SPac shot
ram occu Pies ruore e in memory,
100 'not e that the Pros
110 but its OPe ratio n is verw clea r.
IF A>B AND A>C THEN LPRINT A; "IS THE LARG
EST OF";A;B;C
120 EST OF";A;B;C
130 IF B>A AND B>C THEN LPRINT B; "IS THE LARGEST OF";A;B;C
140 IF C>A AND C>B THEN LPRINT c; "IS THE LARG
15(l GOTO /(l
10(l(l (l END

3 IS THE LARGEST OF l ...


rl
3
3 IS THE LARGEST OF 1- 3 ...
'1

33 IS THE LARGEST OF 22 11 33
33 IS THE LARGEST
35 IS THE LARGEST
OF ')'1
,:_~

OF 3:,
-··15
,j,.., 11
25
35 Tr· THE LARGEST
J.;:} OF 35 ")o::'
<-..l 15

used for
The logical opera tors AND, OR, and NOT can be
Boolean logic operations. Stud y this state ment :

10' set A to TRUE (-1) if both cond ition s are true ,


othe rwis e to FALSE (0)
20 A=<X=Y) AND (J)O ) .-
4 Chapter 1 Decisions and Branching
The parenthes es around each of the condition s are necessary to
isolate the condition s from the assignment of the answer to A.

10 'set the fl3S V lo TRUE if A is not less than B


20 \,':::NOT( A<B)

This statemen t sets V to true (-1) if the statemen t is true; that is,
the value of A is not less than B. Notice that the statemen t

l 0 V::::( fi>=B)

does the same thing, and it is perhaps clearer.


There are some applications for using purely logical operators .
Remembe r that in these cases the values in question are stored by
the computer as either true (-1) or false (0). Such applications lead
to statement s like these:

10 'set P lo -1 if X is 0 and vice versa


'1(1
-lt,.\l P==NOT( X)
30 IF J THEN PRINT "TRUE"
? 4(1 IF NOT(A AND Bl THEN PRINT "NEITHER IS TRUE"
E:"
.•
l\
.Jt~:IF <A OR B) THEN F'RINT "EHHEF-: ONE OR BOTH IS TRUE"

A third possible applicatio n of logical operators is in bit


manipula tion or bit comparison. This could be used in a program to
identify the positions of the 1-bits in any variable, in effect
representing it in binary form. The program ClP4 exemplifies the
problem, converting the variable X that the user input to its binary
represent ation. The test value T starts at the value 16384, which is
two to the fourteent h power. Each time through the loop in lines
100-150, Tis reduced by a factor of two, in effect shifting the
single one-bit to the right one position.

10 FILENAME: "C1P4''
I

20 FUNCTION: DISPLAY LAST 15 BITS OF INTEGER X


I

3(1 AUTHOR •• JPG DATE; 12/79


40 I

50 set t to be the first (larses l) Power of 2


1

60 1=16384
70 PRINT "WHAT INTEGER DO YOU WISH CONVERTED CO=STOF')";
SO INPUT X
IF X=O THEN 10000 ELSE LPRINT x, "IN BINARY IS
II a
'I
90
100 FOF: 1=1 TO 15
110 I isoJ ~te the sinsle bit from X

Chapter 1 Decisions and Branching 5


120 B=T ANI! 1\v
13(1 IF B>O THEN LPRINT "1 " ELSE . LF'~:INT "() It •

140 T=T/2 ' '


150 NEXT J.·r

16(1 LF'RINT
170 GOTO 60
100(1() END

1
r)
IN BH~t1I:::Y 'P''
J.;:) 0 .,
0 0 0 0 () 0 0 (l {•
,I 0 0 (i 1
..:. IN BINARY I"' .;:) 0 (l 0 0 0 () 0 0 (l 0 0 v {I
1 () 0
15 IN BINAf~:Y IS 0 0 (l () 0 0 () 0 0 0 0 •J. ...i 1 1
3456 IN BINARY IS () 0 () ..."I J.i 0 J.•I 1 0 0 0 (l 0 0 0
32767 IN BINAr:Y IS 1 •.!. 1 1 1 1 .L1 1J. 1 1 1 1 1 1 1
Some of the effects of binary operation s using the logical
operators can be very misleading. You should study the explanati ons
of these operation s in the Level II Manual. We include the examples
below more for completen ess than for clarification. We suggest that
you use these operation s only if you feel comfortab le with binary
represent ation of values in the computer .

InE",tr·uc iion Ou iPui


.. ----·---- -·
~-- --···.. --......

10 LPRINT v" AND () ,,


20 LPRINT 0 AND 1 0
3(l LPRINT 1 AND 0 ()
40 LF'r:INT 1 AND ·1 1
50 !...PRINT 0 OR 0 0
6(l LPRINT 0 OR 1 1
70 L.PRINT 1 OR 0 1
8(l LPRINT 1 or: 1 1
90 LF'RINT NOT 0 -1
100 LPRINT NOT -1 0

ON-GOT O and These closely related branching statement s allow a great deal of
ON-GOS UB flexibility when a program needs to perform a multiple-way branch.
They both use a variable after the ON, and a series of line numbers
after the GOTO or GOSUB. The integer value of the variable is
calculated, and a branch is taken to the first statement ifthe variable
is I, the second if 2, the third if 3, and so on. On the TRS-80, as on
most other computer s, if the integer value of the variable does not
correspon d to the position of a given line number, the statement
following the ON-GOT O or ON-GOS UB is executed.
Example:

50 ON X GOTO 80, 300, 750, 10, 80, 90(1


60 ' fall throush if X<O or X>6

6 Chapter 1 Decisions and Branching


v

The computer obtains the integer portion of X, which must be


between 0 and 255.
If the integer then the computer branches
portion of X is to this line number
<0 ERROR MESSAGE
0 60 (the next line-no branch)
1 80
2 300
3 750
4 10 (notice that the line numbers do not
need to be in order)
5 80 (notice that the same line can be
reached with different values of X)
6 900
7-255 60 (the next line-no branch)
>=256 ERROR MESSAGE

You could write the equivalent of line 50 above without use of


an ON-GOTO like this:

50 IF INT<X>=l THEN 80
51 IF INT<X>=2 THEN 300
52 IF INT<X>=3 THEN 750
53 IF INT<X>=4 THEN 10
54 IF INT(X)=5 THEN 80
55 IF INTIX>=6 THEN 900
60 ••••••••• ••••

If the word GOTO was replaced by GOSUB, the multiway branch


would become:

50 ON X GOSUB 80, 300, 750, 10, ao, 900


62 'fall throush if X<O or X>6

which is equivalent to:

50 IF INTCX ):::1 THEN GOSUB 80 •• GOTO 62


52 IF I NT< X)=2 THEN GOSUB 300.! GOTO 62
54 IF INT<X>=3 THEN GOSUB 750: GOTO 62
56 IF INT< X>=4 THEN GOSUB 10 •• GDTO 62
58 IF INH X)::5 THEN GOSUB 80 •• GOTO 0.:.
"1
6(l IF INT<X>=6 THEN GO SUB 90(l
62 + •••• +
f •••••

Chapter 1 Decisions and Branching 7


Obviously the economy of the ON-GOTO and ON-GOSUB
makes them very attractive to any programmer who has this kind of
branching to perform.
One nice application of these statements is in a branch that is
based on the sign of a number. Suppose your program must branch
(with either a GOTO or a GOSUB) to line 50 if the value of X 2 -4=0,
and to line 150 if X 2 -4 is positive. Either one of these statements
would do it.

20 ON SGN(XIX-4)+2 GOSUB 50, 100, 150


20 ON SG~X*X-4)+2 GOTO 50, 100, 150

This three-way branch uses the fact that the SGN function evaluates
its argument, and returns a -1 if the argument is negative, 0 if it is
zero, and +1 if it is positive.
In this chapter, we have explored a few of the many extensions
that provide flexibility and make the programmer's job easier and in
many ways more enjoyable.

8 Chapter 1 Decisions and Branching


Statements and Language features such as multi-s tatemen t lines, RANDOM,
Functions DIM, string functio ns, and many more are incorpo rated into
extende d BASIC to make the program mer's job easier and to
provide problem solving power seen in other high-level programming
languages. This chapter explore s these extensi ons and suggests some
possible applications.

Multiple Statem ents Because the variable names in primitive BASIC are limited in
on a Line size to no more than three charact ers, many BASIC programs take
on the appeara nce of one long list of t1ny stateme nts down the left
side of the screen. This is somew hat inconve nient when the screen is
limited to displaying 16 lines, as on the TRS-80.
Fortun ately, most BASICs allow mere than one stateme nt on
a given line. The Microsoft Compa ny (Bellevue, Washington) has
been a leader in developing languages for microc ompute rs. Many
microc ompute rs, including the Apple-II and the TRS-80, use some
version of BASIC developed by Microsoft. For a full comparison of
two popula r BASICs on microc ompute rs, see Append ix A. All
versions of Microsoft BASIC, including the TRS-80 's Level II, use a

9
colon( :) to separate statem ents; but some other BASICs use other
_symbols. For example, DEC's BASIC-PLUS that is used on the
PDP-11 series of compu ters uses the backslash (\). We will use the
colon because it is used by Level II BASIC on the TRS--80, and it is
also the most comm on statem ent separa tor for microc omput ers.

10 Z=O: Y=l: P=3.14159: E=EXPC1)


20 XS=XStJSt IF I<20 THEN I=It1 : GOTO 20
30 IF Jl>J2 THEN T=J1: J1=J2: J2=T

Note that these examples do not necessarily improve the


readability of the code. In many cases where multiple statem ents
are crowded into one line the readability suffers as far as the
understanding of the program logic. This proble m is often alleviated
throug h indent ation and logical grouping in its multis tateme nt lines.
Consider the two examples that follow:

90 'crow ded-- saves sPace at the cost of readabilit~


95 '
100 PRINT: PRINT "WHAT ACTIVITY CO=STOP)";
110 INPUT A: IF A=O THEN STOP ELSE ON A GOTO 200, 300, 400
120 GOTO 100

90 'bette r -- multi Ple statem ent lines chansed to


95 ' to maint ain losic al flow of Prosram
100 PRINT: PRINT "WHAT ACTIVITY <O=STOP)";: INPUT A
110 IF A=O THEN STOP
ELSE ON A GOTO 200, 300, 400
120 GOTO 100

In the first example, the IF statem ent is crowded into the same
is
line as the INPUT, while in the second example, the IF statem ent
isolated and indent ed for high legibility, and the INPUT is reloca ted
with the output to produc e one line that generates the message.
Note that statem ent 110 has a line feed (.J..) after the word STOP
instead of a carriage return (ENTER). This allows statem ent 110 to
be spread over two lines, greatly improving the overall readability of
the program.

RND Functi on The RND functio n is comm only found on primitive BASICs as
well as the extend ed versions of the language. Usually, its argument
is immaterial or even omitte d, and its purpose is to return a pseudo
random numbe r betwee n zero and one. A pseudo random numbe r
differs from a truly random numbe r in that the former is produc ed

10 Chapte r 2 Statem ents and Functi ons


by an algorithm that uses a seed value to generate a numbe r
apparen tly at "rando m". For various reasons, most pseudo random
numbe r generat ors use a large prime numbe r as a seed for the first
random value, then use that random value, or some modific ation of
it, as a seed for the second value, and so on.
Level II BASIC on the TRS-80 is similar to most BASICs in that
if the RND functio n call uses 0 as an argume nt, the returne d value is
a positive real numbe r betwee n 0 and 1.

10 'random numbers between 0 and 1


20
30 FOR I=l TO 5: LPRINT RNDCOl;: NEXT I
10000 END

.988032 .64224 .047616 .0655122 .423838

A useful extensi on to this functio n is its ability to return a


pseudo random integer within a given range. You can return
random integers betwee n 1 and 6 with the functio n call RND(6)
which might be used to simulate the throw of one die.

10 'random intese rs
20 J

30 LPIUNT "1 TO 6", "1 TO 10", "1 TO 52", "0 TO 1"


40 FOR 1=1 TO 10
50 LPRINT RND(6), RNDC10), RNDC52), RNDC2)-1
60 NEXT I
10000 END
1 TO 6 1 TO 10 1 TO 52 0 TO 1
4 5 30 0
6 E:"
,J 49 0
4 8 11
., 1
.:i 2 7 0
5 9 41 1
5 5 29 1
2 10 38 1
2 '1
.<.. 50 1
5 3 25 (l
6 8 48 ()

RANDOM A feature of pseudo random numbe r generat ors is that the


initial seed is always the same. If you turn off the comput er, then
reload and rerun the program , you get the same output.

Chapte r 2 Statem ents and Functio ns


11
20 'FUNCTIO GENERATE 50 REPEATABLE RANDOM NUMBERS
DATE! 12/7S'
4(i J

50 FOR I =1
TO 50
60 LPRINT RND<lO OO);
70 'retur n the carria se after evers lOth value
80 IF INT(l/10>*10= 1 THEN LPRINT
9(l NEXT I
100 (l () END

368 72 219 825 52 891 119 981 911R"") 616


912 844 856 153 324 550 271 532 409 \J~L

500 199 519 I ,; 83 62


-y E;·
688 474 736 292
21? 470 or,
u .. 866 677 290 178 867 173 697
655 528 976 907 798 31 866 266 234 53

The purpose of the RANDOM stateme nt is to seed the


generat or with a differen t value, based on some varying interna l
value in the comput er. Add a new line

45 RANDOM

and run the program after turning off the compu ter and then
powering it back up. Notice that the output is differen t.

250 669 426 63 16 733 905 368 147 718


255 913 75 201 849 823 798 494 334 705
-,-.,
731 820 860 689 321 232 i..:J 232 405 287
84(1 658 317 4'1:"
OJ 741 461. 7"'"'1
...J,.:_
I 345 299 345
966 ;..7 162 285 858 787 JJ.O::. 31
'")l"l C"C"'">
370 523

DIM and BASIC is not limited to managing its variables in memor y one
Subscripted at a time. It can allow the program mer to set up lists and tables in
Variables memor y by name, and access specific position s of those lists and
tables by using subscripts.
The DIM stateme nt does two things:
(1) It names a list or table.
(2) It sizes that list or table.

Examples:

10 DIM A( 50>

The variable named A is a list 50 values long.

12 Chapter 2 Statements and Functions


The variable X is a table with 50 rows and 20 columns.
30 DIM VU< 30)

The string variable Vl $is a list of 30 strings.

Most people call dimensioned variables arrays, so that a list is


called a one-dimensional array and a table is a two-dimensional
array.
The statem ent

creates a three-dimensional array. You can imagine it as a cube,


with 5 rows, 7 columns, and 2 ranks.

I '
Most microc omput er BASICs, including Level II for the TRS-80,
allow the creation of arrays with multiple dimensions.
When a program refers .to a particular element of an array, it
does so by s,ubscript. In mathematics, a matrix element is referred to
by its subsdi pts, such that the matrix A has an element Ai,j·
In BASIC, a true subscript canno t be written below tlie line, so
it is parenthesized. Thus the programmer can refer to the seventh
element of the one-dimensional array X as X(7).

Examples:

10DIM A<5,20) 'set UP the array , 5 rows, 20 columns


20A(1,12>=50 'Plac e the value 50 in row 1, column 12
. JOAC2,20>=A(1,1> 'coPY row 1, col. 1 into row 2,
40X=J: Y=7: A<X,Y>=B.J 'Plac e the value a.J in rowcol. 20
3r col. 7
50'set all value s to -1
60 FOR 1=1 TO 5: FOR J=1 TO 20: A(I,J>=-1: NEXT J, I

Chapter 2 Statem ents and Functi ons 13


the
Notice in line 10 the use of the apostrophe as a substi tute for
apostr ophe
REM to denot e a remark. Also notice in line 20 that the
middl e of a
does not have to follow a colon to start a remark in the
ce of writin g
line. These niceties allow more flexibility in the practi
remarks.
One common use of multiply subscripted arrays is in the
are the
statistical analysis of polls and questionnaires. Suppose these
characteristics that one wishes to analyze:

Characteristics Number of possible responses

Sex 2 (male and female)

Age 3 (unde r 20, 20 to 50, over 50)

Geographical 5 (Pacific, Mountain, Midwest,


Location South, Atlantic)

Political 3 (Republican, Democratic,


Preference Other)

Answer to Poll 5 (Strongly disagree, disagree,


Question no opinion, agree,
strongly agree)

Now suppose that 50,00 0 observations are made all over the
le,
count ry, and that they are encoded as numeric values. For examp
represe:Q.ts a male more than 50 years old,
the coded response 13225
living in the Mountain states, a Democrat, whose answer was
"strongly agree", The encoded value is generated this way: The
response to "sex' \ a 1 or a 2, is multiplied by 10,000. The age
er,
response is multiplied by 1000 and added to the previous numb
lied by
10,000 or 20,000. The remaining three responses are multip
en 11,111
100, 10, and finally 1. The resultant integer sum lies betwe
polls of
and 23,535. Note- that this encoding scheme won't work for
6 or more questions, or with 5-question polls in which the first
to
response is greater than 3. An interesting challenge might be
on, which would
develop a coding scheme in octal integer representati
allow values of 37777 , or even 77777.
The results of the entire poll could be stored on one or two
program
cassette tapes for input to a micro comp uter for analysis. The
segment below transfers all of the inform ation on tape into a
5-dimensional array for analysis. Rathe r than storing one
, this
questionnaire's results as a single value, say the integer 13225 al
program adds one to the tally of like respon ses in the 5-dim ension
statem ent names the array A and sizes
array. The DIM A(2,3,5,3,5)
it as 2x3x5 x3x5, or 450 values. A prqgram such as the one below
of this
could analyze almost any numb er of questionnaire responses
type, and yet run on a mode rately config ured micro comp uter
system.

14 Chapter 2 Statem ents and Funct ions


The program C2P2 listed below does such an analysis. It
generates its own test data, because it is the analysis techni que
rather
than the data which is the issue here. The outpu t that follow
s the
program shows a sample run. Notice how diffic ult it is to tally
like
responses by scanning the sea of numbers. Imagine how error-
prone
such a visual analysis would be with a sample size in the thousa
nds,
instea d of just 297:

10 FILENAME: "C2F'2"
I

20 'FUNCTION: QUESTIONNAIRE ANALYSIS WITH LARGE ARRAY


30I AUTHOR : JPG DATE: 12/79
40 I

50 DEFINT A-Z
60 DIM A(2, 3,5,3 ,5h B<5>
70 'inPu t from taPe is simu lated with artif icial data
80 LPRINT"T A B L E 0 F A R T I F I C I A L D A T
90 LPRINT A"
'assume a total of 297 resPonses
100 FOR OBS = 1 TO 297
110 GOSUB 500! LPRINT x;•se nera te one 5-answer resPonse
120 IF INT<OBS/9)*9=0BS THEN LPRINT 'new line everY 9th
130 FOR J=5 TO 1 STEP -1 'extr act each dieit as B(J)
140 B<J>=X-INT<X/10>*10: X=X/10
150 NEXT J
160 ' add 1 to ProPer Posit ion of A
170 A<B<lhB<2hB<3h ••• is tedio us
180 ti=B< 1>: E=B< 2 H F=B( 3 >: G=B( 4 )! H=B< 5)
190 A< tl, E, F, G, H) = A( [hE, F, G, H) + 1
200 NEXT OBS: LPRINT: LPRINT
210 'sum UP all resPo nses accor dine to sex
220 GOSUB 600
230 LPRINT "SUM OF MALE RESPONDENTS =";S1
240 LPRINT "SUM OF FEMALE RESPONDENTS =";S2
250 'Prin t user- selec ted elements of the arraY A
260 INPUT "SEX: M=1 F=2 STOP=O"; N1
270 IF N1=0 THEN 10000
280 INPUT "AGE: <30=1 30-50=2 >50=3"; N2
290 INPUT "AREA: PAC=l MTN=2 MDW=3 5=4 ATL=5"; N3
300 INPUT "PARTY! REP=1 DEM=2 OTHER=3"; N4
310 T=O 'tota l all resPondents for this catesorY
320 FOR I=l TO 5: B<I>=A<N1,N2,N3,N4,I): T=T+B<I>: NEXT
330 'rePo rt the resu lts of the tallY I
340 LPRINT"SEX =" ;Nlr "AGE =" ;N2, "AREA =" ;N3, "PARTY =" ;N4
350 FOR 1=1 TO 5
360 LPRINT B<I>; "OF THIS GROUP ANSWERED"il
370 NEXT I
380 LPRINT "TOTAL OF RESPONDENTS";Nl;N2;N3;N4;"X =";T
390 LPRINT
400 GOTO 260

Chapt er 2 Statem ents and Funct ions 15


500 '**** * mal\e artif icial data usins Pando nt functio~t
510 J1=RN£!< 2 >: J2=RNrt< 3 >: J3=RN [I( 5 >: J4=RND< 3 H J5=RNrt;( 5)
~
520 X=(( (J1*1 0tJ2) *10tJ 3l*10 tJ4)* 10tJ5
530 RETURN
600 '**** * SU1J1 the se>~es
610 FOR N2 = 1 TO 3 'N2=subscl"iPt fop ase
620 FOR N3 = 1 TO 5 'N3= subsc riPt for locat ion.
630 FOR N4 = 1 TO 3 'N4= subsc riPt for Pol. Pref.
640 FOR N5 = 1 TO 5 'N5= subsc riPt for answer
650 51= 51 t AC1,N2,N3,N4,N5) 'sum of males
660 52= 52+ AC2,N2,N3,N4,N5> 'sum of female~
670 NEXT N5rN4,N3rN2
680 RETURN
10000 END

TAB LE OF AR TIF ICI AL DAT A

23321 13215 11411 13223 23524 22422 22131 13225


13224 13311 11131 21224
11122 23435 13135 21521 21321 23114
22322 23515 13215 13213 13512 11114 21235 13331
12312 12533 21213 21222
22122 12212 12525 23313 12233 11521
13325 22421 22434 22333 11511 21334 23324 12535
22123 22531 1241.1
22421 12335 21422 11332 23231 13234 22434
13335 21422 22521 11322 21435 13422 11334 23515
23433 11114
13312 21132 13531 12315 12225 22311 12211 23112
21521 21222 21135 13321 11112 12122 13134 12231
13125 21135 11533
23135 21334 11334 22133 11113 22323 22521
13431 22525 11422 12335 23424 13423 22425 22221
11235 22315 11513
21522 23331 22134 12533 11132 11112 22231
11311 23334 23532 13123 12314 13314 13421 21434
13523 21211
21313 11322 22324 12524 22125 21121 12312 23413
13521 11523 21235 21211 23523 11313 21325 13531
12421 23424 21332
11533 11533 12231 23314 11311 12531 23424
23135 21424 22134 13423 23132 11333 21412 21132
12312 11412 12535
21312 12225 13422 21211 12534 11512 13522
13211 21335 23212 23515 22134 23132 13121 13313
21411
22534 23125 12225 13425 13124 22425 11314 21115
12222 12325 21424
11131 21114 22424 13111 13525 11224 23112
23125 21415 13212 23521 23432 12115 23322 22123
22213 21335
11433 23132 11312 23531 22534 23125 11435 22435
13315 12512 11124 23313 12135 21121 13312 13511
23323 22425 23414
23514 22431 23234 12435 11121 22115 22233
11534 21213 21333 23514 13112 13311 21225 23511
11423 21422 13521
11131 23415 11311 22233 21121 21421 22222
22515 11424 13535 23533 13533 21522 13424 23235
13113
12224 12134 23524 22112 13134 21213 21434 22523
12431 23333 13324
13124 11231 12433 13223 12335 21321 22333
12435 22113 22315 12315 12122 21222 22412 21432
23411
11331 22233 23535 12313 23323 23215 21221 23222
22324 22135 21211
12235 22331 13323 22321 13325 22334 23432

16 Chapter 2 Statements and Funct ions


SUM OF MALE RESPONDENTS = 140
SUM OF FEMALE RESPONDENTS = 157
SEX = 1 AGE = 2 AREA = 3 PARTY =1
0 OF THIS GROUP ANSWERED 1
3 OF THIS GROUP ANSWERED 2
1 OF THIS GROUP ANSWERED 3
1 OF THIS GROUP ANSWERED 4
2 OF THIS GROUP ANSWERED 5
TOTAL OF RESPONDENTS 1 2 3 1 X = 7
SEX =2 AGE = 3 AREA =5 PARTY =3
1OF THIS GROUP ANSWERED 1
1OF THIS GROUP ANSWERED 2
1OF THIS GROUP ANSWERED 3
0OF THIS GROUP ANSWERED 4
1OF THIS GROUP ANSWERED 5
TOTAL OF RESPONDENTS 2 3 5 3 X =4
SEX = 1 AGE = 1 . AREA = 1 PARTY =1
0 OF THIS GROUP ANSWERED 1
2 OF THIS GROUP ANSWERED 2
1 OF THIS GROUP ANSWERED 3
2 OF THIS GROUP ANSWERED 4
0 OF THIS GROUP ANSWERED 5
TOTAL OF RESPONDENTS 1 1 1 1 X =5
SEX = 2 AGE = 2 AREA ~ 2 PARTY =2
1 OF THIS GROUP ANSWERED 1
1 OF THIS GROUP ANSWERED 2
0 OF THIS GROUP ANSWERED 3
0 OF THIS GROUP ANSWERED 4
0 OF THIS GROUP ANSWERED 5
TOTAL OF RESPONDENTS 2 2 2 2 X =2
SEX = 2 AGE = 3 AREA = 3 PARTY =3
1 OF THIS GROUP ANSWERED 1
0 OF THIS GROUP ANSWERED 2
1 OF THIS GROUP ANSWERED 3
1 OF THIS GROUP ANSWERED 4
0 OF THIS GROUP ANSWEREr• 5
TOTAL OF RESPONDENTS 2 3 3 3 X =3

Chapte r 2 Statem ents and Functi ons


17
The two progra ms that follow exemplify the Monte Carlo
in a
techni que, which is a comm on way to establish rando mness
series of observations.
of
The flrst progra m, C2P3, demon strate s how to shuffle a deck
g two
52 cards quick ly and effectively on the comp uter by pickin
itch
cards at rando m and switching their positions. The pick-and-sw
be just as
is repeat ed 100 times, althou gh fewer switches might
effective.

10 'FILENAME: "C2P3"
20 'FUNCTION: SHUFFLE A nECK OF CARDS
30 IAUTHOR : JPG DATE! 12/79
40 DIM C( 52)
50 ' gene rate the decK and deal it in order
60 FOR I= 1 TO 52t C(I) =I! NEXT I: GOSUB 500
70 'shuf fle the deck
80 RANDOM
90 'swit ch two cards at random 100 tiaes
100 FOR I= 1 TO 100! X= RND<52)! Y =RNDC I
52)
110 T = C( X>: C< X) = C<Y H C<Y ) = T: NEXT
120 'now deal it shuff led
130 GOSUB 500! GOTO 10000
500 'deal ins subro utine <4 hand s)
510 FOR. 1=1 TO 52
520 LPRINT C<I>;: IF INT< I/13)
N
*
13 =I THEN LPRINT
530 NEXT I: LPRINT! RETUR
10000 END

1 2 3 4 5 6 7 B 9 10 11 12 13
14 15 16 17 18 19 20 21 22 23 24 25 26
27 28 29 30 31 32 33 34 35 36 37 38 39
40 41 42 43 H 45 46 47 48 49 50 51 52

18 3 17 27- 37 19 14 2 10 8 51 26 31
4 25 5 13 30 22 49 36 20 41 15 50 35
24 23 52 6 11 32 29 44 21 9 42 45 28
39 33 43 34 46 16 48 47 7 1 40 12 38

The second Monte Carlo demo nstrat ion shows how the
.
techni que can be used to balance two (or more) series of events
closel y as possib le
Suppose a record comp any wishes to equat e as
an LP record . The
the total playing time on each of two sides of
flrst side must conta in 12 selections while the second side must
contai n 13 selections for a total of 25 selections with a total
ed
playing time of 93 minut es. Ideally, each side should be record
playin g time. The proble m
with 46 minut es and 30 seconds of
time
arises when trying to find the 12 or 13 tunes whose playing
that figure . The Monte Carlo techni que
most closely appro ximat es
m, adds their playin g time, and keeps the
selects 12 tunes at rando
"best " schedule.

18 Chapt er 2 Statem ents and Funct ions

11·--,
10 I FILENAME: "C2P4"
20 'FUNCTION! MONTECARLO SELECTION OF SONG PROGRAMS
30 'AUTHOR : JPG/JDR 12/79
40 I .

50 DIM T$(25), MC25), SC25), H 25), K< 25 h U 25)


60 1
T$= sons title M= minutes Per cut
70 ' S =seconds Per cut T = time Per cut, in seconds
80 ' K = random Poin ter L =second random Poin ter
90 I

100 read in the title s, minutes, and seconds


1

110 ' N = total number of sonss , both sides


120 INPUT "HOW MANY OF THE 25 SONGS ON THIS ALBUM";N
130 LPRINT "THIS ALBUM HAS";N;"OF THE 25 SONG TITLE
140 FOR 1=1 TO 25 S"
150 READ T$( I ), MC I h S( I )
160 H I >=60
170 NEXT I
*
M< I ) + S( I ) ! K< I ) = I
180 C=60ooo: set smal lest diff. between sides verY hish
1

190 INPUT "HOW MANY SCRAMBLES";N5


200 LPRINT "SELECTED NUMBER OF SCRAMBLES=";N5
210 FOR Q=1 TO N5 ' scramble sonss N5 times
220 FOR I=1 TO N
230 J=RND< N)! Z=K< I H t\( I >=K< ,J H KC ,J >=Z
240 NEXT I
250 sum times for sides
1

260 Zl=O! Z2=0: N2=INTCN/2)


270 FOR 1=1 TO N2
280 J=KO H Z1=Z 1HC .J)! J=K( ItN2 ) ! Z2=Z2+ T( J )
290 NEXT I
300, IF NI2<>INT< N/2) TI-IEN Z2=Z2+T< N)
310 B=ABS<Z1-Z2)! B = diff. in time between sides
1

320 IF B>=C THEN 380! I C =Pre vious lY smal lest diff.


330 C=B! C1=Zl! C2=Z2
340 FOR I=l TO Nt L(I)=KCI)! NEXT I
350 PRINT "LEAST=";c;"IN TRY"iQ
360 LPRINT "LEAST="iC;"IN TRY"iQ
370 IF C=O THEN 390 'srea t! 0 is diffe rence !
380 NEXT Q
390 PRINT! PRINT 'set next shuff le of ti~es
400 LPRINT!LPRINT
410 Ml=INTCCl/60)! Sl=Cl-60*M1
420 PRINT "SIDE 1",M l;"t"i S1! LPRINT "SIDE l"rM li"t"; Sl
430 FOR I=l TO N2: J=L<I>
440 PRINT T~J)TABC40)M(J)"!"S(J)
450 LPRINT H< J HAB< 40 >M< J )" !"S( J)
460 NEXT I
470 PRINT~PRINT!LPRINT!LPRINT
480 M2=INT(C2/60)! S2=C2-60*M2
490 PRINT "SIDE 2", H2; ":"; S2

Chapt er 2 Statem ents and Funct ions


19
5()0 LPRINT "SIDE 2"' M2; t"; S2
II

510 FOR I=N2t1 TON: J=LC I>


52(l PRINT T$( ,J )T ABC 40 )M( ,J )" t S( ,J )
II

530 LPRINT TSCJ)TABC40)M(J)":"&J)


540 NEXT I
550 DATA "MAGMA COME LOUDLY",2v45r"CRAMP MY STYLE"r2r20
560 DATA "PORKY AND TESS"r5r21r"PUSHBUTTON POLKA"r6r23
570 DATA "THE GODMOTHER THEME"r4r33r"FIG NEWTON"r3,2
580 DATA "MOTEL COLORADO"r2r43r"YELLOW FEVER",2r10
590 DATA "STAGNANT"r3r55r"NEW HAVEN NEW HAVEN"r8,23
600 DATA "LIFE IN THE FAT LANE"r3r21,"HOT SNUFF",5,31
610 DATA "FIRST RATE ROMANCE RITZ RENDEZVOUS"r3r33
62(l DAH1 "IRON ORCHID" r3d6r"FIFTY-FIRST SH:EET" dr23
630 DATA "BLACK HOLE BLUES"r2r51r"YELLOW PILLOW"r6,0
640 DATA "PINACOLATAVILLE"r2r44r"SALADA CANTATA"r4r25
650 DATA "FLORIBUNDA"r3r8r"TAKE THIS JOBBIN SHOVEL",3r8
660 DATA "STAR TRUCK"r3r40r"SEMIHEMIDEMIQUAVER"r2,2
670 DATA "IPHEGENIA IN QUEENS",2r34r"CABINETWORKS"r3,42
l(i(l(i() END

THIS ALBUM HAS 25 OF THE 25 SONG TITLES


SELECTED NUMBER OF SCRAMBLES~ 50
LEAST= 46 IN TRY 1
LEAST= 36 IN TRY 7
LEAST= 8 IN TRY 28

SIDE 1 47 1
THE GODMOTHER THEME 4 33
HOT SNUFF 5 31
IPHEGENIA IN QUEENS 2 34
FIFTY-FIRST STREET 1 23
IRON ORCHID 3 36
SALADA CANTATA 4 25
PORKY AND TESS 5 21
PUSHBUTTON. POLKA 6 23
BLACK HOLE BLUES ...
'")
51
TAKE THIS JOBBIN SHOVEL 3 8
STAGNANT 3 55
LIFE IN THE FAT LANE 3 21

20 Chapter 2 Statements and Functions


SIDE 2 !.7 •
"'tJ
0
? I

F'INACOLATAVILLE 2 44
FIRST RATE ROMANCE F:ITZ RENDEZVOUS 3 33
FLORI BUNDA 3 8
CRAMP MY STYLE 2 20
STAR TRUCK 3 40
YELLOW PILLOW 6 0
SEMIHEMIDEMIQUAVER 2 2
NEW HAVEN NEW HAVEN s 23
CABINETWORt;;s 3 42
YELLOW FEVER 2 10
FIG NEWTON 3 2
MOTEL COLORADO 2 43
MAGMA COME LOUDLY 2 45
THIS ALBUM HAS 17 OF THE 25 SONG TITLES
SELECTED NUMBER OF SCRAMBLES= 50
LEAST= 200 IN TRY 1
LEAST= 145 IN TRY 2
LEAST= 17 IN TRY 4
LEAST= 8 IN TRY 14
SIDE 1 35 11
NEW HAVEN NEW HAVEN 8 23
FIG NEWTON 3 2
F'ORt\Y AND TESS 5 21
YELLOW PILLOW 6 0
YELLOW FEVER 2 10
LIFE IN THE FAT LANE 3 21
HOT SNUFF 5 31
FIFTY-FIRST STREET 1 23
SIDE 2 35 3
STAGNANT 3 55
CRAMP MY STYLE 2 20
THE GODMOTHER THEME 4 33
MAGMA COME LOUDLY 2 45
PUSHBUTTON POLKA 6 23
FIRST RATE ROMANCE RITZ RENDEZVOUS 3 33
BLACK HOLE BLUES 2 51
MOTEL COLORADO 2 43
IRON ORCHID 3 36

Chapter 2 Statements and Functions 21


String Functions String functions are designed to return strings or information
concerning the strings that are referenced in the argument.

LEN The LEN function returns the length of the string. argument.

Instru ction OutPu t

10 PRINT LEN< "ABC") 3


20 PRINT LEN< "COUNT"t"DRACULA") 12
30 PRINT LEN( "MAC" >+LEN<"HINES"> 8
40 A$="SCR": B$="AM"
50 IF LEN(A$)(10 THEN AS=A$t"E": GOTO 50
60 A$=AStBS: PRINT LEN(A$);As 12 SCREEEEEEEAM

Line 50 above pads A$ with as many "E"s as it takes to make


it 10 characters long, then "adds" (concatenates) B$ to the result.

LEFT$ and LEFT$ and RIGHT$ return substrings of the string argument
RIGH T$ for the length specified by the numeric argument.
LEFT$(X$,N) returns theN leftmost characters of X$.
RIGHT$(X$,N) returns the N rightmost characters of X$.

Ins ir·uct ion OutPu t

70 PRINT LEFTSC"ABCD",3) ABC


SO PRINT RIGHT$C"ABCD",2) CD
90 AS="BAN": PRINT AS+RIGHTS(A$,2)t"A" BANANA
100 PRINT LEFTS<"FIRE"t" ",6)t" Z" FIRE Z

MID$ MID$(A$,P,L) extracts a substring of the argument string A$


starting with the character at position P for a length of L characters.
If the third argument Lis omitte d, the function returns all of the
string starting at position P.

Instru ction OutPu t

100 PRINT MIDS<"ABCDE",3,2) CD


110 PRINT MIDSC"ABCDE",3,3) CDE
120 PRINT MIDS<"ABCDE",2) BCDE

22 Chapter 2 Statements and Functi ons


If the positio n argume nt exceeds the length of the string, the
returne d ("extra cted") string is null.

Instr·uct.ion Out..Pu t

130 BS=MIDSC"ABCDE",B)! PRINT BS; LENCB$) 0

The MID$ functio n is useful for searching a string for a


particu lar charact er or substring. This exampl e shows how the
length of a person' s first name could be determ ined in order to
reposit ion the last name.

10 'FILENAME! "C2P5"
20 'FUNCTION: REVERSE LAST AND FIRST NAME
30 AUTHOR : JPG
I
DATE: 6/79
4(1
50 CLEAR 100! INPUT "TYPE YOUR NAME --LAST FIRST MI";N$
f;O L.PF:INT N$
70 FOR I=l TO LEN<NS)
8(1 IF MID$( N$' If 1 )()-" THEN NEXT I
II

90 IF I=LEN(N$) THEN 40
100 LPRINT MIDSCN$,1+1 >+" "tlEFTSCNS,I-1)
10000 END
Clone Bozo T
Bozo T Clone

ASCan d CHR$ The ASC functio n returns the ASCII (American Standar d
Code for Inform ation Interch ange) code equivalent in decimal of
the first charact er of its string argume nt, which cannot be null.
See Append ix B for a comple te listing of all ASCII codes.

Inst..ru ct.ion Ou iPui


----------- ------
10 PRINT ASC( "ABC") 65
20 PRINT ASC( "1979" ) 49
30 PF:INT ASC( II II )
32
4(1 PRINT ASC< "1" ) 49

Chapter 2 Statements and Functions


23
.The CHR$ function is the reverse of the ASC function. Its
of an
argument is a value that is taken to be the decimal equivalent
ASCII code, and the character it represents is return ed.

Instr- uctio n Ou t?ut

50 PRINT CHR$(77) M
60 PRINT CHR$(65) A
70 FOR I=40 TO 63
80 PRINT CHRS(I); ( >*h- ./012 3456 789:; <=>?
90 NEXT I
The TRS-80 has an unusual extension to the character set. As
uses
is the case with all 8-bit micros, the 128-character ASCII code
ns, and so Radio Shack uses the
only half of the possible bit patter
of reasons. Half of these, from 192
values 128 to 25 5 for a variety
d using the CHR$ functi on, and the
to 255 inclusive, can be printe
result is a variable-length TAB argument.

Exam ples-V arious Ways to Tab

Tabbins witho ut TAB with TAB

10 PRINT CHR$( 192t5);"X" 10 PRINT TABC5);"X"


50 PRINT CHRS<255);"Y" 50 PRINT TAB(63);"Y"
100 V=192: PRINT CHRS(V);"z" 100 PRINT TAB(Q);"z"

VALa ndST R$ The VAL and STR$ are two companion functions used for
string-to-numeric and numeric-to-string conversion. The VAL
is
function uses a string as its argument. It return s the value that
represented in the string. If the string is mixed, and starts with
If
numeric characters, the value of the leading numb er is return ed.
the value return ed is 0.
the string starts with non-numeric characters

Ins ir-uct.ion OutPut

130 LPRINT VALC"2E3" > 2000


140 LPRINT VAL< "12. 34" ) 12.34
150 LPRINT VAL< "8 O'Clock" >*100 BOO
0
160 LPRINT VALC"B29")
170 X$="-8.765": LPRINT VALCX$) -8.76 5

24 Chapter 2 Statem ents and Funct ions


The STR$ function perform s the opposite of the VAL function .
It converts a value to a string. Its argumen t is a constant , a numeric
variable, or a numeric expression. Note that 9-digit accuracy is
maintain ed.

Inst.r·uct..ion OutPut.

160 LPRINT STR$(5) !::"


J
170 LPRINT STR$(123456789) 123456789
180 LPRINT VALCSTR$(123457689)) 123456789
190 LPRINT STRSCVAL("123457689" )) 123456789
200 LPRINT RIGHTSCSTRS(5)r1l+RIGHTSCSTRS(7),1) 57
210 LPRINT RIGHTS<STRS(5),1l+LEFT$(STRS(7),1 >
220 LPRINT RIGHTSCSTRS(5),1)fSTRS(7) t;·
t...i
-.•
j

Note that STR$(5 ) is two bytes long, representing the sign and
the digit.
10 'FILENAME: "C2P6"
20 'FUNCTION: VERY LONG ADDITION
30 ' AUTHOR : JPG DATE: 12/79
40 I

50 CLEAR 1000' clear enoush st.rin~ space


60 ' inPut. both Ions int.ese rs as strinss , A$ and 8$
70 PRINT "TYPE THE FIRST NEMBER, UP TO 60 DIGITS LONG."
80 PRINT "TYPE 'STOP' TO EXIT."
90 INPUT AS: Ll = LENCAS): C=O
100 IF A$ = "STOP" THEN STOP
110 PRINT "TYPE THE SECOND NUMBER, UP TO 60 DIGITS LONG."
120 INPUT BS: L2 = LENCBS)
130 CS="": C=O' set. answer str·ins t.o null, car·rB to 0
140 1
Pad both st.rinss at. left. with blanks
150 AS=STRINGSC60-L1," ">+AS
160 BS=STRINGS(60-L2," ">+BS
170 ' add one disit. at a lime; keeP track of carrY
180 FOR I=60 TO 1 STEP -1
190 S=VAL(MIDS<As,I,1)) t VAL<MIDSCBS,J,1)) t C
200 IF S>9 THEN C=1: S=S-10 ELSE C=O
210 CS=RIGHTSCSTR$(5),1) + CS
220 NEXT I
230 now set. rid of leadins zeros in answer
1

240 first find Positio n of first non-zer o charac ter


1

250 FOR I= 1 TO LEN(CS>: IF MIDS<CS,I,l)=nO" THEN NEXT I


260 lhen concate nate blanks whefe there were zeros
1

270 CS=STRING$( I-1 'II II) + RIGHT$( C$,61- I)


280 Print bolh lhe inPul and the answer
1

290 LPRINT " "+AS: LPRINT "+ t B$ 11

300 LPRINT STRINGS(61,"-" )t LPRINT" "tCS


310 LPRINT: LPRINT: GOTO 20
10000 END
Chapter 2 Statements and Functions 25
7645685435807335437453311285003
+ 346844343222609212144399

7645685782651678660062523429402

98765498765443321254398709877654323276548765432545766565
+ 11111111111111111111111111111111111111111111111111111111
109876609876554432365509820988765434387659876543656877676

1234567876543212345678765432123456787654321
+ 8765432123456787654321234567876543212345678

9999999999999999999999999999999999999999999

77777777777777777777777777777777777777777777777777777777
+ 77777777777777777777777777777777777777777777777777777777
155555555555555555555555555555555555555555555555555555554

99999999999999999999999999999999999999999999999999999999
+ 1

100000000000000000000000000000000000000000000000000000000

User-defined Some programs use a few simple routines so often that they
Function s are best written as single-line function s. This is possible in most
versions of extende d BASIC. The format for defining single-line
function s is:
DEF FNX(V l, V2, ... ) =expres sion
or
DEF FNX$(V 1, V2, ... ) = string expression

The X or X$ is any legal numeric or string variable that will


identify whether the function returns a numeric or string result.
The Vl, V2, and others if necessary are dummy arguments to the
function definitio n. That is, their name is immater ial, except for
type and position . They represen t the type and position of the
actual argumen ts as the function is invoked within the program.
The expression shows the way the dummy argumen ts interrela te to
produce the single answer.
There are two distinctl y differen t occurren ces of user-defined
function s in any program. One occurren ce is its definitio n, and
this must precede all other occurren ces, which are called its
invocations. Your study of these example s will help you to
apprecia te this feature of BASIC.

26 Chapter 2 Statements and Functions


Ins tr·t.iction OutPut

5 Tl=5t R7=Bt B2=75


10 DEF FNACx,y,z>=X+YtZ
20 LPRINT FNA<T1,R7,B2> 88
30 DEF FNDCA,B,C>=B*B-4*A*C
40 LPRINT FNDCT1,B2,R7) 5465
50 DEF FNR<A,B,C>=<-BtSQRCFND<A,B,C))/(AtA))
60 LPRINT FNRCT1,B2,R7) -67.6074
70 DEF FNX$(N$)=LEFT$(N$,2)tRIGHT$CN$,2)
80 LPRINT FNX$("FINS SPLASH"> FISH
90 DEF FNLt<At,Bt>=At/Bt
100 LPRINT FNLtCR7~B2) .1066666666666667
110 LPRINT FNAC45,67,89) 201
120 LPRINT FND<3243,234,123) -1.5408Et06
130 LPRINT FNRC34,567,89) -558.82
140 LPRINT FNLt(1,7) .1428571428571429

Notice that the variables used when the function was invoked are
not the same as those used in the definition, but that they are used
in a one-to-one substitution.
Double precision is explained in Chapter 4, but this example
is used here to show that user-defined functions can return integer
or double precision answers, unlike the library functions, which
return only single precision answers.
In this chapter, you have learned that strings can be
manipulated in a variety of ways to ease the burden of character .·.
processing. Also, you have seen some unusual features of the
TRS~80 Level II BASIC that further extend its flexibility in
programming. The next chapter discusses some extensions of BASIC
that the TRS-80 uses to communicate to the user through video
screen and line printer.

Chapter 2 Statements and Functions 27


Input and Output Programmers are often quick to point out that programming a
computer to process information is only one phase of the work.
Often the input of data into the computer for future processing or
the output of the processed information is at least as troublesome.
As college teachers we have found that what is obvious to the
professional programmer is not at all obvious to the beginning
programmer: Good output is by definition highly readable and well
organized, and requires a great deal of prior planning to produce.
In this chapter we will discuss the PRINT USING, a statement
that greatly simplifies the task of making output readable. We will
also discuss the PEEK and POKE instructions that read or alter
memory directly, and the INP and OUT instructions that control
the interface ports of the microcomputer.

Cued INPUT Most extended BASICs have a feature that allows a message to
be printed along with the usual question mark prompt upon
execution of an INPUT statement. The programmer simply places
the message in quotes after the word INPUT, then a semicolon and
the list of variables.

29
Examples:

Inst.r·uction Out.Pu i
----------- --- .... --
10 INPUT "NAME" H~$ NAt1E?
20 INPUT "WEIGHT";W WEIGHT?
30 INPUT "SEX" jS$ SEX?
40 INPUT "VALUE";A VALUE?

LPRINT One of the signs that BASIC has matured as a computer language
is its ability to use an attached printer as an output device. The
LPRINT command acts exactly like all versions of the PRINT
command, except the output is sent to the printer. Most of the
examples and programs in this book have used and will use the
LPRINT as well as the PRINT.

PRINT USING If any one feature has enhanced the reputation of BASIC as a
language in the professional community, it is the PRINT USING
statement. This feature allows a great deal of flexibility in the
formatting of output, and for this reason is used extensively in the
printing of reports and in increasing the readability of screen output.
Some examples should clarify its use. Suppose you want to
produce a chart of the values of the sine, cosine, and tangent for
angles between 0 and 45 degrees in increments of 5 degrees.

10 'FILENAME: "C3P1"
20 'FUNCTION: CHART FOR VARIOUS FUNCTIONS
30 I AUTHOR : JPG DATE: 3/80
40 ' Print column headinss
50 LPRINT "DEGkEES", "SINE", "COSINE", "TANGENT"
60 FOR I = 0 TO 45 STEf' 5
70 ' conver· t. radians t.o deSir-ees
80
90
A : .0174533 I *
LPRINT I, SIN(A), COSCA), TANCA)
100 NEXT I
10000 END

30 Chapter 3 Input and Output


DEGREES SINE COSINE TANGENT
0 0 1 (l
5 .0871558 •996195 .0874887
10 .173648 .984808 .176327
15 .258819 .965926 .267949
20 .34202 .939693 .36397
25 .422618 • 906308 .466308
30 .5 .866025 .577351
35 .573577 .819152 .700208
40 .642788 .766044 .8391
45 .707107 .707107 1

Wouldn't it be nice if the same chart could contain the square


root and cube root of these values? Unfortunately, this would print
six values causing overflow of the four 16-column zones that make
up the TRS-80 screen. The first four values would appear on one
line, then the last two on the second line, as shown here.

DEGREES SINE COSINE TANGENT


SQ ROOT CUBE ROOT
0 0 1 0
0 0
5 .0871558 •996195 .0874887
.295409 .443557
10 .173648 • 984808 .176327
.417772 .558847
15 .258819 .965926 .267949
.511663 .63972
20 .34202 .939693 .36397
.590818 .704103
25 .422618 •906308 .466308
.660555 .758471
30 .5 .866025 .577351
.723601 .805996
35 .573577 .819152 .700208
.781579 .848494
40 .642788 .766044 .8391
.835543 .887114
45 .707107 .707107 1
.886227 .922635

A clever programmer could use the TAB function and a


rounding function to produce some much better looking output.
Consider this alteration of the program.

Chapter 3 Inputand Output 31


10 'FILENAME: "C3P2"
20 'FUNCTION! PRINT NEAT TABLE WITH NOT-SO-NEAT PROGRAM
30 IAUTHOR : JPG DATE: 4/80
40 ' Print column headinss
50 LPRINT "DEG"; TAB( 10); "SINE"; TAB<20); "COSINE";
60 LPRINT TABC3Q); "TANGENT"; TABC40); "SQ ROOT";
70 LPRINT TABC50}; "CUBE ROOT"
80 FOR I=O TO 45 STEP 5
90 A=.0174533*I convert radians to desrees
I

100 ' convert all values to 3-?lace numbers


110 X=SIN<A>! GOSUB 190! S=X
120 X=COS(A)! GOSUB 190! C=X
130 X=TAN<A>: GOSUB 190: T=X
140 X=SGR<I>: GOSUB 190! U=X
150 X=I[(1/3): GOSUB 190! V=X
160 note the minimal Punctuation
I

170 LPRINT I TAB(10)S TABC20>C TABC30)T TAB(40)U TAB(50)V


180 NEXT I! GOTO 10000
190 X=INT<1000*X+.0005)/1000
200 RETURN
10000 END

DEG SINE COSINE TANGENT SQ ROOT CUBE ROOT


(l 0 1 0 0 0
5 .087 .996 .087 2.236 1.709
10 .173 .984 .176 3.162 2.154
15 .258 .965 .267 3.872 2.466
20 .342 .939 .363 4.472 2.714
25 .422 .906 .466 5 2.924
30 .5 .866 .577 5.477 3.107
35 .573 .819 .7 5.916 3.271 ~- ""1

40 .642 .766 .839 6.324 3.419


45 .707 .707 1 6.708 3.556

The real problem with this kind of programming is not that it


doesn't do the job. Rather, the job it does is not obvious to the
reader of the program. One doesn't "see" the layout of the output
line by studying the program. Also, a small change in layout format
would be difficult to implement.
The PRINT USING statement allows the programmer to define
an image of the output line as a string variable, and then print the
variables using that image. There two ways this can be done:
(1) The PRINT USING statement can contain the image
(without any variables).
(2) The PRINT USING statement can contain a string variable
that defines the image.
The image is a string that acts as a mask for the output line.

32 Chapt~r 3 Input and Output


There are five possible contents to an image statement.
( 1) Spaces, used to spread out the values of the variables.
(2) Literals, used to place headings or messages.
(3) Digit specifiers(# ), used to mask digit positions.
(4) String specifiers(% and !), used to mask characters in a
string.
(5) Special characters( ,.$*+-), used to designate punctuation ,
fill characters, signs, or exponents in scientific notation.

See Table 3.1 for a summary of these image specifiers and their
effects.

The PRINT USING statement has the following form:

PRINT USING string; values

where string is the image, either as a string constant or variable, and


values is the list of variables or constants to be printed.
The following examples show the use of spaces, literals, and
digit specifiers.

Su?Rose A=25, B=368, and C=71904

Instructio n Out..?ut

30 PRINT USING "ttttt";A 25


40 PRINT USING "ttttt";B 368
50 PRINT USING "ttttt";c 71904
60 PRINT USING "tiiit tt#it";A,B 25 368
70 PRINT USING "tttt tttt ttit";A,B ,C 25 368 7.71904
75 A$="itt Itt ttttt"
80 PRINT USING A$;A,B,C 25 368 71904
85 B$="A=tt B=ttti"
90 PRINT USING B$;A,B A=25 B= 368
95 C$~':"VALUESt"
100 PRINT USING C$tA$;A,B,C VALUES: 25 368 71904

Chapter 3 Input and Output 33


Liter-a l an~ Pr-inta ble I the literal
char-acter- but iisel f
t or- specia l
char-acter-~;

SPecia l 111ar·Ks a disi t disit or- a


Char-acter·s POSition sPace

seF·ara tes ever'::! ' or a blanK


three disit.s in
the cor-rec t
Posi t.ions
( 475,34 6,257)

mar-ks the Positio n the , is


of the decimal Point alwa'::ls Pr-inted
in a numer-ic field

$ Pr-ints a floatin s Pr· in ted just.


dollar· sisn in front of the
first disi t in
the numeric field

sives checK is Printed


Protec tion instead of the
leadin s zeros
or sPaces

Pr-ints correc t sisn positiv e value


+ r-:-r·ints a +
of the follow ns
number nesativ e value
Prints a -

Print a - if value F·ositiv e value


is nesativ e Prints a sPace;
nesativ e value
Prints a - sisn

four- of them denote the letter E Plus


scient ific notatio n the sisn of the
usins e>:Ponent.s exPonent Plus two
e:-:Ponen t dis its

7. marKs the bounda ries allows strins


of an alPhanumer-ic variab les to be
field used in the imase

marKs the Positio n allows sinsle


of a charac ter charac ters
Table 3.1 Image Specifie rs and Their Effects

34 Chapter 3 Input and Output


A number of features enhance the value of the PRINT USING.
(1) It prints the value even if it is too large for its
correspon ding image.
(2) Formats can be changed during the execution of the
program.
(3) Trailing zeros are printed.
(4) Values are printed in rounded form.
(5) If the number to be printed is too large for its image, the
entire value is printed, but with a leading percent sign to
signal the user that the number was too large for its image.
An example of this was shown in the output from line 70
in the above examples. For more, see the following
examples.

Instruct ion Outr-ut.

10 PRINT .USING "tt.lt";4 50 ;~450. ()()


20 PRINT USING "ll.ll"i8 30.375 %830.38
Punctuati on, such as decimal points, commas separating
thousands and millions, plus and minus signs, dollar signs, and fill
characters, can be inserted in an output field with very little trouble.

SuPPose E=2.718282, G=-65.4 32, H=7492835, and P=3.141593

InE tr-ucU.on Ou iPu i

10 PRINT USING ul,tltt" ;E 2.7183


20 PRINT USING "t,ttl,l lt.tt";H 7,492,84 0.0()
25 A":li=" ft, If"
30 PRINT USING ASiG /.·-65. 43
40 PRINT USING ASiP 3.14
45 B$="11, 11-": CS="tt. tlt"
50 PRINT USING BS;G 65.43-
60 PRINT USING cs;G 65.43-
70 PRINT USING Bs;p 3.14
80 PRINT USING cs;p 3.14+

Chapter 3 Input and Output 35


The examples above show that when a plus sign is placed at the
end of a digit specifier field, it forces the printing of a sign at that
position : +for positive number s and -for negative numbers. When a
minus sign is placed at the end of a digit specifier field, it forces the
printing of a space for positive and a - for negative numbers.
Now let's look at that table-printing program again, only this
time it will have a PRINT USING stateme nt.

10 .. FILENAME: "C3P3"
20 'FUNCTION: PRINT A TABLE WITH PRINT USING STATEMENTS
30 l
AUTHOR ,Jf'G DATE! 4/80
40 I
Print colUlitn headin ss
50 LPfUNT II
DEG SIN cos TAN SQ RT CU RT"
60 1 define the imase for the table
70 AS = " Itt tt.ttt ~~.ttt tt.ttt tt.ttt tt.ttt "
80 FOR I = 0 TO 45 STEP 5
90 A=.0174533*I conve rt radian s to desree s
100 1 note the minimal Punctu ation
110 LPRINT USING AS; I,SIN(A),COStA>,TAN<A),SQR( I ),I[(l /3)
120 NEXT I
10000 END

DEG SIN cos TAN SQ RT ClJ RT


0 o.ooo 1.000 o.ooo o.ooo o.ooo
5 0.087 0.996 0.087 2.236 1. 710
10 0.174 0.985 0.176 3.162 2.154
15 0.259 0.966 0. 268 3.873 2.466
20 0.342 0.940 o. 364 4.472 2.714
25 0.423 0.906 0.466 5.000 2.924
30 0.500 0.866 0.577 5.477 3.107
35 0.574 0..-819 0. 700 5. 916 3.271
40 0.643 0.766 0.839 6.325 3.420
45 0.707 0.707 1.000 6.708 3.557

The output of program C3P3 shows the advantage of the


PRINT USING in printing trailing zeros to fill the image. The
compu ter prints the sine of 30° as 0.500, and not just 0.5.
You can build image strings during executi on of the program
that depend upon certain features of the variable values to be
printed . For example, suppose your program is to print an amoun t
with varying size embedd ed within text withou t any extra blanks.
Study the followi ngprog ram to see how this is done.

36 Chapte r 3 Input and Output


10 'FILENAME: "C3P4"
20 'FUNCTION! ANOTHER EXAMPLE OF HOW IMAGES CAN BE USED
30 ' AUTHOR ! JPG DATE: 4/BO
40 CLEAR 300
50 INPUT "AMOUNT TO BE EMBEDDED ([IOLLARS AND CENTS)";X
60 IF X=O THEN 10000
70 F$=""! A$=STR$(X)! L=LENCA$)
BO FOR I=1 TO L-3! F$=F$t"t"!NEXT I
90 F$="$"tF $t".tt"
100 LPRINT "OUR ACCOUNTS SHOW YOU TO BE IN ARREARS"
110 LPRINT USING "BY THE AMOUNT OF "+Fit" DOLLARS"; X
120 LPRINT " FOR THE MONTH OF AUGUST."
130 GOTO 50
10000 END

OUR ACCOUNTS SHOW YOU TO BE IN ARREARS


BY THE AMOUNT OF $ 4338.24 DOLLARS
FOR THE MONTH OF AUGUST.
OUR ACCOUNTS SHOW YOU TO BE IN ARREARS
BY THE AMOUNT OF $ 1.23 DOLLARS
FOR THE MONTH OF AUGUST.

When very large or very small values are to be printed, it is


sometimes better, either for convenience or for appearance, to print
these values in scientific notation. The up-arrow (t) indicates the
exponentia tion operation in BASIC, but in a PRINT USING
statement it also serves as an image specifier for the exponent portion
of a number. Four up-arrows (tttt) are used in an image that serves
for scientific notation output.
The first t masks the letter E.
The second t masks the sign of the exponent.
The last two t t mask the value of the exponent.
Study the following examples to see how very large values can be
printed.

Chapter 3 Input and Output 37


Instructio n Oul.F·ui

10 CLEAR 200
20 A=6.023E-8t B=.000000000012345
30 C=5.43E12: D=4920450000000000
40 S$="J.t tttttttttt ttttttt"
50 L$="ttt ,ttt,ttt,t tt,ttt,1tt "
60 ES="t.tt tttttt"
70 PRINT USING S$;A 0.000000060230000000
75 PRINT USING S$;B 0.000000000012345000
80 PRINT USING ES;A O.Ml23E-0 7
85 PRINT USING ES;B 0.1235E-10
90 PRINT USING L$jC s,43o,ooo ,ooo,ooo
95 PRINT USING LS;D 4,920,45o,ooo,ooo,ooo
100 PRINT USING Es;c O. 5430E +13
105 PRINT USING ES;D 0.4920Et1 6

The $ and * ch<;1racters can be used as fill characters in an image


statement. This is useful in payroll programs that contain a check
protection feature.

Inst.r·uct.ion OutPut
-------·-- -- ------
Hl PRINT USING "Ut"txs;A *****3.75
20 PRINT USING "Ut"tYS;A UU:I3. 75*
30 PRINT USING U:t"+XHB
9 IUI-4.86
40 PRINT USING "U:t"+YS;B *****4.86-
50 PRINT USING asu"txs;B -$4.86
60 PRINT USING 0 $$t"tYS;B $4.86-
70 PlUtH USING "S t"txs;B $ -4.86
80 PRINT USING "$ t"tYS;B $ 4.86-
90 PRINT USING "**S"tXSiB **~*-$4 .86
100 PRINT USING "IIS"tYS;B UU:$4.86 -

38 Chapter 3 Input and Output


String specifiers in a PRINT USING image statement can control
the positioning of strings. There are two string specifiers:

! is used to denote a single character.


% % is used to denote an enclosed string.

The ! specifier positions just the first character of a string.

Instruction Output.
----------- --·----
10 AS="ABC": XS= XYZ"! 1$:::"!
11 II

20 PRINT USING u;As A


30 PRINT USING II! II; X$ X
40 PRINT USING II ! ! II; A$, X$ AX
50 PRINT USING ! ! ! !"jA$,X$,"LIVID","ENACT"
H
A X L E
60 PRINT USING ! ! !!";"BOZO" ,",","THE"," ,";
H

70 PRINT II
CLONE" B. T. CLONE

The% %specifiers are always used in pairs, each pair enclosing


the string that it is masking. The spaces between the % characters,
plus the % characters themselves, provide the mask.

Instruction Output.

90 AS="% z~~:BS="%%"
100 XS="MONTANA YS="OHIO"
11 :

110 PRINT USING AS;X$ MONT A


120 PRINT USING As;ys OHIO
130 PRINT USING BStBs;xs,YS MOOH
140 PRINT USING BS+" "tBs;ys,ys OH OH

The four features that follow-INP, OUT, PEEK, and POKE-


are not found just in the TRS-80 Level II BASIC. This is why they
are explained in this chapter. However, the reader should be
cautioned that some microcompute rs handle these features in slightly
different ways than the TRS-80. We have explained them as they
operate on the TRS-80 because that isthe target system for this book.

INP and OUT The INP is a function that returns a-single byte from the
TRS-80's I/0 (input/output ) port specified in the argument. For
example, the statement

30 X=INP< 127)

Chapter 3 Input and Output 39


returns the byte that is at port 127 and stores it in the variable X.
The expansion interface is necessary to make full use of this function.
The OUT statement acts much like the INP, but in reverse. It
requires two values, the first being the port number in decimal and
the second being the byte that is to be transmitted to that port.
For example, the statement

40 OUT 127,60

transfers a 60 to port 127.

PEEK and POKE The PEEK function and POKE statement are very much like
the INP function and OUT statement respectively. The difference
is that they pick up or deposit single bytes in memory, rather than
at the 1/0 ports.
The function PEEK has a single argument which is a decimal
memory address. An example statement using the PEEK function
is

50 A=PEEK< 14520}

This statement causes the variable A to take on the value of the byte
stored at the decimal address 14520.
The statement

60 PRINT PEEK<16650)

prints the byte at memory address 16650.


The statement

70 X=PEEI\(15360+1>

places in X the value at location 15360 displaced by an increment I.

The POKE statement has two arguments, an address and a


value. For example, the statement

80 POKE 15650, 65

places the character "A" in a location of memory which happens to


be in the portion of memory that is displayed on the video screen
(see Appendix C for a complete memory map for the TRS-80).
The memory positions with addresses 15360 to 16383 represent the
1024 specific positions on the screen, that section of memory which

40 Chapter 3 Input and Output

t ·-J
serve as a buffer to the screen. The image of the screen at any time
is in memory at those addresses, and a programmer can "rea.d" the
screen with a PEEK or "write" to the screen with a POKE into that
area.
This program accesses (and does a quick read/write check of)
the memory addresses 17129 to 204 79, the 3300-byte area of memory
that a 4K Level II system has reserved for user programs.

10 'FILENAME: "C3P5"
20 'FUNCTION: MEMORY TESTER
30 ' AUTHOR : JPG DATEI 4/80
40 FOR I = 17129 TO 20479
50 X= PEEK<I>: Y =X
60 IF INT( I/100)*100=1 THEN PRINT I;
70 POKE J,y: Y =PEEK(!)
80 IF X <> Y THEN PRINT "SOMETHING WRONG AT";;I
90 NEXT I
10000 END

This chapter concludes the coverage of the extensions of


BASIC that are commonly found on most microcomputers. The
following chapters discuss in detail the extensions of BASIC that are
found in the TRS-80's version of Microsoft BASIC.

Chapter 3 Input and Output 41


Variables Level II BASIC on the TRS- 80 is rich with features
that makes it
perfo rm like other popu lar high-level languages.
This chap ter will
discuss how variables can be used in various ways
to make them more
appro priat e for their appli catio n.

Long Variable Most BASICs hold to the rule of lette r or letter-and-


Names digit as the
only permissible variable names. This string ent requi
reme nt reduces
the total possible numb er of variable name s to 286.
(26 for A to Z,
26 for AO to ZO, ... , 26 for A9 to Z9). A serious
flaw with this
schem e is that it greatly reduc es the mean ing that
can be attac hed to
a parti cular variable. For exam ple, the high-level
language COBOL
allows up to 30 chara cters per variable name , so that
name s like
NET -AFT ER-T AXE S, NAME-TABLE-POINTER,
and
DEP REC IATI ON are allowed. FOR TRA N allow
s up to 6 characters,
and name s like SUM, SPEED, and BALNCE can be
used in programs.
The majo rity of BASIC progr ams, because of the
variable nami ng
limit ation , are terse and hard er to unde rstan d.
Many of the best mode rn BASICs for micr ocom puter
s have
incor porat ed the featu re of allowing long variable
names. Micr osoft 's

43
BASIC, as incorp orated in the TRS-80's Level II, has adopte d a
compromise. A variable name can be a single letter, or it must begin
with a letter and be followed by either a letter or a digit, so there are
exactly 962 possible distinc t variable names. Level II BASIC allows
longer names, but only the first two characters are used by the
d
compu ter to distinguish betwee n variables. Also, a Level II reserve
a variabl e name. Appen dix D has a
word canno t be contai ned within
full list of all reserved words in TRS-8 0's BASIC .

Examples:
Legal in Level II Illegal in Level II
X 8J (digit first)
V7 STAB (conta ins TAB)
AB COST (contains COS)
ABC (same as AB) IRON (conta ins ON)
SUM STIFF (conta ins IF)
SUPER (same as SUM) POST (conta ins POS)
SHUPER FORMIDABLE (conta ins FOR)

The programs in this book will use names of one or two


characters only, except for a few carefully chosen names that are
longer when their use clarifies the meaning of the programs
significantly.

Variable types Variables are named according to their application by using a


type declaration character as part of the variable name. The string
variable A$ is distinc t from the numer ic variable A because it is
declared as a string by the dollar sign ($),wh ich is its type
declaration character.

Integer Variables Integers in Level II BASIC use the percen t sign(% ) as a type
declaration character. Integers are whole numbe rs that vary in size
betwee n -32768 and +32767 inclusive. ' '1

Examples:
Integer variables Typica l values
X% 5
SUM% 0
NUM% -8
I% 7982
12% -3000
COUNT% -1

Single Precision Single precision real variables use the exclam ation point( !) as a
Real Variables type declaration character, or they use nothin g at all, since numer ic
variables are declared by defaul t to be single precision real variables.
These variables are accurate to seven digits, and vary in size from

44 Chapter 4 Variables
~ . }

' )
about-1. 7xl0 38 toabout+ l.7xl0 38 .

Examples:
Single precision real variables Typical values
A 372.871
V7 -6.5
XX -.09
J! 142.
B2! 4E-12
GROUP! 2.5E-34

Double Precision Double precision real variables use the pound sign ( #) to signify
Real Variables the ability to represent 16 decimal digits of accuracy. Like single
precision values, they vary from about -1.7xl0 38 to about +1.7xl0 38
in magnitud e.

Examples:
Double precision real variables Typical values
F# 32984532 891.77
V8# 3.141592 65358979 3
JA# .3333333 33333333 3
GR# 1. 00000000 000000 I
NUM# 2. 71828182 8459045
The flexibility of programm ing that these three numeric precision
types allow is bought at a price. Integer variables have a limited
range; single precision real variables are accurate to just 7 digits;
and double precision real variables take up more than twice as much
memory as single precision variables. Each type has various
characteristics, favorable and unfavorable, as table 4.1 shows.

Conversion of The conversion of a constant to internal represent ation can be


Constants a time-consuming process, and a good programm er should always be
on guard for ways to speed up particular ly slow sections of code.
This is where some basic knowledge about the particular
characteristics for the TRS-80 and its Level II BASIC can be very
helpful.
The program below does some simple additions in a loop that
can be varied in the number of times it is executed. Both constants
and variables appear in the calculations within the loop. The
timings for the program's execution are shown in table 4.2.

Chapter 4 Variables
45
Inteser Sinsle Precision Double f'reci sian

Dec lar·ation ! (default)


character
Ranse -32767 1.701411. -E38 1.70141183460469221-E38
to to to
+32767 1.701411tE38 1.70141183460469221tE38

2 8

Pr·ec i sian all in 7 17


(stared ranse
disHs >
Precision all in 6 16
( pr· in ted ranse
disits)

Rur1 tin1e 5 7 11
RiE!R10r~
c:)locatio n
Conversio n .05- .1 5-10 500-1000
. tiRI~ to
· b:l.nal~\:S, llisec

Table 4.1 Variable Types and Their Characteristics

10 FILENAME: . "C4Pl"
I

20 ~ FUNCTION: DEMONSTRATE DECLAREII.VARIABLE, CONSTANT TIMING


30 AUTHOR
I JPG DATE! 12/79
40 I

50 X%=01 X=O! XI=O! 'declare thr~e t~Pes, initializ e to zero


60 INPUT "LOOP SIZE= tO:::STOP)";N1 IF N=O THEN STOP
70 M%=17.: 5=1.1! Ilt=.123456789012345! 'increR,en ts for looP
. 80 ' let user select the l~Pe to be added.
90 IC=inlese r constant,
I
IV=intese r variable
100 SC=sinsle
I Precision constant, SV=sinsle Prec. var.
· 110 ' DC=double Precision constant, IIV=double Prec. var.
120 INPUT "TYPE <1=IC, 2=IV, 3=SC, 4=5Ui 5=DC, 6=DV>";TY
130 PRINT "TIME BEFORE=";RIGHTS(TIME$,5)
140 now execute a simPle addition N times, accordins to
1

150 ' the user's reGiJested t!:lPe> oote that the looP
160 ' · overhead of ON-GOTO and GOTO instructio ns is the same
170 for all l~Pes of conver~ion or addition.
1
'

46 Chapter 4 Variables
180 FOR !=1 TO N
190 ON TY GOTO 210,220 ~ 230, 24(>, 25(>, 260
20 (} GOT 0 40
210 X%=X%t1! GOTO 270
220 X%=X%tM%! GOTO 270
230 X=X+L1! GOTO 270
240 X=XtS: GOTO 270
250 Xt=Xtt .12345 678901 2345! GOTO 270
260 Xt=XttDt! GOTO 270
270 NEXT I
280 I Print the values and the curren t time.
290 PRINT xz, x, Xt
300 PRINT "TIME AFTER=";RIGHTSCTIME$,5)
310 GOTO 50
1(l(nj(l END

For-rl• within looP


IJar-iabJ.e Consta nt
INT SNG DBL INT SNG DBL
5 4
10 8
20 ...1 15
50 1
... 1 1 1 2 38
.,...,)
100 ')
2 3 2 3
200 4 c-
.J 4 r.
.J
500 8 8 13 1(1 12
10(10 17 18 r)7
... , 20 23
-----------------------------------------------------------
L:ecu tion 17 18 20 23 800
time, Per
instru ction (msec)
Table 4.2 Timings from Program C4Pl, in Seconds
Notice that the time it takes to deal with double precision is
negligible, so long as conversion is kept to an absolute minimu m.
This can be achieved by doing all arithme tic within the program on
values that are stored as variables. For example, both of these
program segments produc e double precision answers to the same
problem , but their executi on times are vastly differen t. The first one,
which execute s a loop that contain s some double precision conversion,
execute s in 80 seconds, while the second , which contain s only
previously defined variables, execute s in 2 seconds.
10 PRINT THiES 10 PRINT TIME·$
20 Bt=1.00000000000001
25 Ct=.lOOOOOOOOOOOOOl
30 FOR 1=1 TO 100 30 FOR I=l TO 100
40 S~=S~t.100000000000001 40 St=St+Ct
50 NEXT I 50 NEXT I
60 PRINT St, TIME$ 60 PRINT S:J, TIMES
10000 END 10000 END
Chapte r 4 Variabl es 47
Implicit Conversion A program may have numerou s statemen ts that mix differen t
types of variables, and a program mer who writes such mixed mode
expressions and statemen ts must be able to predict exactly what the
compute r will do in all circumstances.
These rules show how the TRS-80 will treat various constant s
that appear in the program, either as a part of an expression or as
created during the actual executio n of an expression. Notice that in
general, the precision of an answer maintains the maximu m precision
of any operand .
Rule 1: Any constant with more than 7 digits, with a# type
declaration character, or with aD exponen t forces
storage as a double precision value. In the examples
that follow, the values in the PRINT statemen t are
first converted as necessary, then operated upon and
stored tempora rily, and finally printed as shown.

Ins t.ruct.io n Ou iPu i


----------- ------
Hl PRINT 12345678+.12345 123456 78.1234 5
20 PRINT 12345DOt12345 12345.12344999611
30 PRIN"T 123.456 78 123.456 78
40 PRIN"T •ooo oooooooo oa lD-13
50 PRINT -600 000 0 000 (l 0 1 -60000000000001
60 PRIN"T 5000000000000 5000000000000
70 X:t=~i00(1(l: PRINT X:tt.000 05 50000.0 000499 99995

Rule 2: Any non-dou ble precision constant less than -32768


or more than +32767 or containing a decimal point
forces storage as a single precision value.

Ins t.Fuc t.ion Ou LPU t.


----------- ------
10 PRINT 12345+.12345 12345.1
20 PRINT 123.456 123.456
30 PRINT 123.4567 123.457
40 PRINT -81245 -81245

Note that if a value that is printed cannot be represen ted with


either six digits for single precision, or sixteen digits for double
precision, the value is printed in scientific notation . The following
examples show this.

48 Chapter 4 Variable s
Ins true lion Ou iF-U t.

10 PRINT .OOOOOOOOOOOOlt lD-13


20 PRINT .00000000000012345 1.2345E-13

Rule 3: Any constant between -32768 and +32767 inclusive


not containing a decimal point and not declared single
precision with a ! or double precision with a # is
stored as an integer value.

11emory Storage When an operation is performed on two or more operands in a


After Mixed statement, the result must be predictable even though the operands
Operations are not all the same type. Microsoft's Level II BASIC is not only
predictable , but it usually produces the result that a programme r
would have liked to get.
( 1) Most Precise Operand Rule
The result of a+,-, or* operation has the precision of its
most precise operand.

Instructio n OutPut Consments


----------- -· ..----- --------
10 PRINT 2*3.6 7.2 INT * SNG _.... SNG
20
30
PRINT
PRINT
2*4
3+2.718281828
8
5.718281828
INT *INT
INT t DBL
·'
-> INT
-> DBl.
40 PRINT 3.3+2.718281828 6.018281828 SNG t DBL -> DBL

Note that when two different precision operands are compared,


the computer actually compares temporary versions of the operands,
and these temporary versions have a precision of the most precise
operand.

Instructio n OutPut..
----------- ------
10 IF 2=2.00001 THEN LPRINT "YES"
ELSE LPRINT "NO• NO
20 IF 2.5=2.5000000000001 THEN LPRINT "YES"
ELSE LPRINT "NO" NO
30 IF 2=2.00000000001 THEN LPRINT "YES"
ELSE Lf'RINT "NO" NO

Chapter 4 Variables 49
(2) No Integer Division Rule
The result of a division obeys the Most Precise Operand
Rule, except that when it is indicated between two integers,
both operands are converted to single precision before the
division is performed .

Inst..r·uction Ou t.Pu t Corflltten t. s


·-··--------···-- ------- --------
10 PIUiH 2/3 .666667 INT/INT -> SNG
2(i PRINT
")"/
.k.laJ
,-.,.,
.!:J1. .666667 INT /HIT -> SNG
3(l PFnNT ':1 /..,
~~
•t
.;;;. .666667 INT./I NT -> SNG
40 PfUNT 2/3.5 .571429 INT/5NG -> SNG
50 PRINT 2/3.1234 5678 .64031620760893 INT/IIBL -> IIBL.
60 PRINT 3.5/4.12 345678 .848802397293467 SNG/DBL -··...·· DBL

(3) Integer Truncation, Otherwise Rounding Rule


During conversion from single precision to an integer, a
number is reduced to the largest integer not greater than the
original number, exactly as the INT function does it.
During conversio n from double precision to single precision,
the number is rounded up. Conversion from double
precision to integer goes through conversion to single
precision.

Instr-uc tion OutPut CollHitHt t.s

10 I%=7,999! PRINT I% 7 5NG - ....·· INT (tr-unca tion)


20 5!=7.999999999! PRINT S! 8 DBL. -> SNG ( r-ounclins)


30 J%=7,999999999! PRINT J% 8 DBL -> SNG -> INT
(roundin s,
then tr·uncati on)

(4) Integer Boolean Operations Only Rule


A Boolean AND, OR, or NOT between two unlike
operands forces conversion to integer first. This rule is
included here only for the sake of completen ess. It is
unlikely that you would ever need to use this feature.

Instr-uc tion Output Con,n,en ts

10 PRINT 2 AND 3,5 2 same as 2 AND 3


20 PRINT 2 OR 4.999999999 7 same as 2 OR 5
30 PRINT 1.9999 OR 7,999999999 9 same as 1 OR 8 (7,9 •••
rounded UP first, then
con ver· ted to in ieser· )

50 Chapter 4 Variables
DEFINT, DEFSNG, Level II BASIC allows a programmer to reserve sections of the
DEFD BL,D EFST R alphabet for various types of variables. This is in effect a form
of
implicit type declaration. Instead of having to type a # charac
ter at
every occurrence of a double precision variable, the programmer
can
declare any variable starting with that letter of the alphabet to
be
double precision.
The general form of these statem ents is

DEFt yp letter-range

where typ is:


INT for integer,
SNG for single precision real,
DBL for double precision real, or
STR for string variables.
and letter-range is:
a single letter from A to Z,
two or more letters separated by commas,
two letters separated by a hyphe n, or
any comb inatio n of the above.
These statem ents are normally used at the beginning of a progra
m.
Examples:

100 DEFINT I-N

All variables beginning with any letter I through N are integer,


such as I, J2, 18, MM, NICE.

110 DEFDBL B' Cr D


All variables beginning with the letters B, C, or D are double
preCision, such as DIG, C, COUNT, BB, B5.

120 DEFSNG X-z, Vr R


All variables beginning with the letters X through Z, V, orR
are
single precision. Note that single precision is the default condi
tion
of the comp uter, so this statem ent is not necessary excep t as
a
reminder to the programmer, unless it is used to override a previo
us
declaration.

130 IIEFSTR Ar P
All variables beginning with the letters A or P are strings, even
thoug h they are not followed by a$.

Chapt er 4 Variables
51
140 DEFINT I, K-R, T-Z
150 DEFSNG A, c, T-Z
160 DEF[IBL IhE
170 DEFSTR M-0
180 DEFINT A-Z

The use of the DEF statem ents does not preclu de the use of
the
type declar ation characters. For example, if your progra m has
statem ent:

25 [IEFDBL [I

le D% is
the variable D in the program is doubl e precision, the variab
D! can be
a distinctly differ ent intege r variable, D$ is a string, and
used for single precision. If the program uses D#, it will be
considered the same variable as D when it is used.

Hexadecimal and Radio Shack's Disk BASIC allows the progra mmer to define
as
Octal Const ants consta nts in hexadecimal (base 16) or octal (base 8) as well
decimal. This featur e is conve nient for dealing with memo ry
addresses or for manip ulatin g specific bytes in memo ry.
The prefix &H signifies a hex consta nt and the prefix &0 or
nts
& (the 0 is option al) signifies an octal consta nt. These consta
are two bytes (16 bits)
repres ent signed integers in memo ry, so they
long. See table 4.3 for examples of this featur e.

Cons tant' stor-e d as decim al rc .. ~

(oct al) (he>:) he>: b~tes eauiv alent


M C.HO 0000 0
u C.Hl 0001 1
U7 C.HF OOOF 15
C-20 l'.H10 0010 16
&255 &HAD OOAD 173
&377 S.HFF OOFF 255
&77777 &.H7FFF 7FFF 32767
uooooo &H8000 8000 -32768
U00001 &.HS001 8001 -32767
&100002 6.H8002 8002 -32766
&177776 &HFFFE FFFE -2
&177777 &HFFFF FFFF -1
Table 4.3 Octal and Hexadecimal Conversions

52 Chapt er 4 Variables

' '
The following exampl e illustrates the use of hex conversion as a
possible aid in program writing. If you become more familiar with
the hexade cimal represe ntation of certain memor y addresses, such as
hex 3COO being the first address of the screen buffer area, you may
take advantage of this feature as illustra ted here. ·

Result
110 FOR I=C&H3C00) TO <&H3FFF) The screen buffer is at
120 POKE I, RNDC64)t127 memorY addres ses from 3COO
130 NEXT I to 3FFF, so lhis sesment
Places a random sraPhi c
charac ter (see lhe nexl
chaPte r) on everY Positi on
of the screen .

VARPT R This functio n of Level-II BASIC returns the address of its


argume nt. The argume nt is a variable name and if it has not been
defined, the compu ter prints an error message.
When the argume nt's variable is numeri c, whethe r it is integer,
single precision, or double precision, the address that is returne d is
that of the least significant byte (LSB) of the variable. The other
bytes are from 1 to 7 bytes past the returne d address, with the
address of the most significant byte (MSB) being the largest.
When the argume nt of the V ARPTR functio n is a string variable,
the value returne d is the address of the length of the string and the
two-by te address for the string itself is in the next two bytes.
The VARPTR functio n is useful for passing the addresses of
variables back and forth betwee n assembly language routine s and
BASIC programs, but it finds little use elsewhere.

With what you know now about the screen's buffer area and
the comput er's memor y represe ntation of variables, you are ready to
explore graphics, which many program mers conside r to be the most
exciting challenge in a microc ompute r. The following chapter
discusses graphics in detail, and includes a wealth of examples for
you to try.

Chapte r 4 Variables 53
Graphics There are three distinct ly differen t ways to produc e picture s on
the screen of a TRS-80 . The first is as old as comput ers; lines are
printed one at a time on the screen, just as if it were paper. The
other two method s are more accomm odating to the program mer,
allowing conside rable flexibil ity and some rather stunnin g graphical
displays.
This chapter will discuss all three method s and show by exampl e
what can be done with a little care and imagina tion.

Line Printer Line printer graphics is called what it is because anythin g that
Graphic s can be done on the screen can also be done on a line printer. It can
be used on almost any compu ter and with most compu ter languages.
In many ways it is the most powerf ul method of graphing. We
propose to show you by exampl e some of the various picture s that
can be produc ed with line printer graphics.

Graphi ng with Problem : Repres ent the sine and cosine functio ns graphically
Tabs for all values betwee n 0 and 360 degrees.

55
10 'FILENAME: "C5P:I."
20 'FUNCTION: GRAPH SINE AND COSINE FUNCTIONS
30 'AUTHOR JPG DATE: 12/79
40 I

50 ' K=conversion consta nt for desree s to radian s


60 t\=3. :1.4159/180
70 • draw axis of values -:1. to 1
80 LPRINT " ";
90 FOR I=-1 TO 1 STEP .2
100 LPRINT USING "tt.i ";I;
110 NEXT It LPRINT
120 'Print S for siner C for cosine at aPPro Priate Positi on.
130 'each Point is 10 de~rees apart.
140 FOR D=O TO 360 STEP 10
150 'conve rt desree s to radian s
160 R=D*K
170 'determ ine Positi ons of the S and C chara cters.
180 S=25*SIN(R)t32: C=25*COS(R)t32
190 ' if ansle is a Guadr anl divide r then Print its value
200 ' and Print the !rid line
210 IF INT<<Dt90)/90>=<Dt90)/90 THEN LPRINT o;: GOSUB 260: GOTO 240
220 'if cosine is less, Print C then s, otherw ise revers e,
230 IF C<S THEN LPRINT TAB<C>"C" TAB<Sl"S"
ELSE LPRINT TABCS)"S" TABCC)"C"
240 NEXT It
250 STOP
260 LPRINT TABC5)i" ";
270 FOR I=-1 TO .8 STEP LPRINT "+----";: NEXT I
'")+
+Ll

280 LPRINT "t": RETURN


10000 END

56 Chapter 5 Graphics
-1.0 -o.a -0.6 -0.4 -0.2 -o.o 0.2 o.4 o.6 o.e 1.0
0 +----+----+----+----+----+----+----+-
,... ---+----+----+
;:J c
s c
0
f"
c
s c
c s
c c·.J
c ,...
s
c ;:J
90 +----+----+----+----+----+----+----+----+----+----+
c s
c s
c c._,
c s
c
c
c s
c s
180 +-~--+----+----+----+----+----+----+----+----+----+
c s
c s
c s
c c u

s c
s c
s c
s c
270 +----+----+----+----+----+----+----+----+----+----+
s c
s c
s c
s c
s
s c
s c
I"•
;:J
c
360 +----+----+----+----+----+----+----+----+----+----+

Chapter 5 Graphics 57
Another way that tabs can be used in a design is to symbolize
them in a list of data statement s. The program below was written by
Steve Grillo to draw the Starship Enterprise. We have included just a
portion of its three pages of data statement s. Note that the program
analyzes the data that it reads and executes its LPRINT statement s
according to the contents of the DATA statement s.

10 'FILENAME: "C5P2"
20 'FUNCTION: PRINT A PICTURE OF THE USS ENTERPRISE
30 I AUTHOR : SPG DATE: 6/79
40 I

50 Here are a few remarKs concern ins the Prosram:


60 1 About the data stateme nts:
7(l ' TlO = TAB ( 10 )
80 ' ANY STRING = Print the followin s text
90 1 R = Carriase Return
100 Q = Left BracKet
110 W = Risht BracKet
120 A =ToP to bottom diasonal (oPPosi te of"/")
130 M = A comma ( , )
140 S =A Quotation mark(")
150 CLEAR 300: DEFINT A-Z
160 READ AS: IF AS="END" THEN STOP
170 IF AS="R" THEN LPRINT CHR$( 13);: GOTO 160
180 READ Bs: IF BS="END" THEN STOP
190 FOR N=l TO LEN(Bflt CS=MID$(8$,1)
200 IF CS="Q" THEN BS=MIDSCBS,lrN-1ltCHRSC91)tMIDS(BS,Nt1l
210 IF CS="W" THEN BS=MIDSCB$,1,N-1ltCHRSC93)tMIDSCBS,Nt1)
220 IF CS="A" THEN BS=MIDSCBS,1,N-1ltCHRS(92ltMIDS(B$,Nt1)
230 IF CS="M" THEN BS=MIDSCB$,1,N-1>tCHRSC44ltMIDS<BS,Nt1)
240 IF CS="C" THEN BS=MIDSCB$,1,N-1l+CHRSC58)tMIDSCBSrNt1l
250 IF CS="S" THEN BS=MIDS(B$,1,N-1l+CHRSC34l+MIDS(BS,Nt1)
260 NEXT N: IF LEFTS<AS,1l="S" THEN 280
270 LPRINT TAB<1tVALCMIDSCA$~2)));Bs;: GOTO 290
280 LPRINT STRINGSCVAL<MIDSCA$,2)),~ ");Bs;
290 READ At: IF LEFTSCA$,1 l="T" THEN 190 ELSE 170
9(10 I

910 This is onl~ a Partial data listing


'12(l for the EnterPri se
I
930
1000 DATA T22,11t,R,T21,QI II,R,T2 2,tl Mt,R,T22,t Ml
1010 DATA R,T22,1----Mt,R~T22,1 !t,R,T22 ,1 MI,R,T22
1020 DATA I QW Mt,R,T22,t QW MI,R,T22,1 QW MI,T22,"----MI
1030 DATA R,T22,1 !t,R,T22 '1 Mt,R,T21,*1 MI,R,T21
1040 DATA II MI,R,T2 0,/II Mt,R,T20
105(l DATA 120,1 I Mt,R,T19,/* I----Mt,R ,T19
1060 DATA I I AIA,R,T19,1 I MI*'R,T19'* /1 Mil
107•:> DATA R,TlB,/1 / I MIO*'R, T18,1/ I MIOI,R,T18
1080 DATA I I MIOI,R,T18,1 /1 MIO I,R,T18
109(l DATA I I I MIO I,R,T18~ 1/ I MID I,R,T17
58 Chapter 5 Graphics
...
.. ....
[t "'
If '"
t-·-·--·:1
t If

t [ J ••
t [ ] ••

...·----··...
t [] ••

t !I

..
*" .•••
/:U
**..• .••*
* of-·---··\1\
/:t:

*
t
t .u
tIt ,u:
It/ t .tot
tl t ,tot
t I ,:IO:t
*t 1 ,to 11 :t

tJ •
** t-- t
..o,to **
,to *
:t

U:t:JI.: :t: -riO


** * / t \10
:t:t::t:/:trtO *:t:
**** t~:f * 1 " ..tot o **
* * r J * t ,to u
"** ** []r J t* o •t .to o o *:t: ***
( u * [ J * (·-----10----0--:t:
0

.u * CJ * <t ,to o **
* :t r J :t* o f .to
:+:
:t
r:IO
o o
0
t
:+: :+:
*D:t
* :t
tO
* •I .10
:t otO
on
O:t
:tOOt :t \ I olD "Oll'.
***=• * \ t .to" Not
:to::, :t: \1----/IO"~""Ot
u:oo: ::+:\ t ,to·"~ot
:t:OOOOO:t:' t o:IOOOO:t
UOOO:t \ t oiDOOt
:t:t:t:ot \t ,toot
*** *t
U\
,tot
.to:t
n:\ t .tot
:t:0\1 • :JO:t
tOOl , It D
toOt- --/1** I
:tot ,uo:t 1
:tot .tooot -------1-----·--
:tot- ":IOOOO:t U /OOOU
:tOt
Ut
B" IOOOOO:t
•"tOOOOOO:t
'*********!
\U:t:/
:tu~" "" •tooooooo:t:
:t I""''" "tOOOOOOOO:t *******************
UU:t:tt:t:UUt:t:t:Ut: t::tU:t:
:t: t"~""OtOOO : Ot * ,00*1:1!:\
* t"""OOtOO : 1: * tO oOOJ!: t
t tO[ JOOtO
:t: tOOOOOtO
J!:
t
tUUU:**
t
***'******
t 88888 *0 , DOOt 1!:
t

* to[ Jooto
t :toooooto a:
************ 88888 ***********
:t: 88/\B to .ooooo:t:t
t 'i:OOOUOO 0 ; ntU:t:UJ!:*** 8/ \ ************
:t: :tOOOOOtO Ol 0 0 : t : : I -- \ l .,""0001:1!:
t tooouoo : o : :t: ;/188\l :,,~"oon:t:
:t: :tOftOOOO 0 : Cl 0 10 :t:
* utooooo
:t: tUU:J!:DO
;
:o t
* L/8888
88888
:.,""OOt:t:J!:
; .. ""ooot:t:
88888 :,, ""DOOU
t tUt :t::t:O 88888 ; , , ""OOO:t::t:
il':t::t:J!::t: :t::t" 8"888 :,,""000**
tt"" : 8 8"8 ;,,""OOOJ!::t:
l
:t:t""
**" 8 8 8
8 8 8
: ,[""OOOt:t:
;,(""OOO:t::t:
/:t:ttt:t:t:t:t:t:t\ U" B 8 8 : ,.""OODtt
/:t::t: :t:JI:\ :t:t"" : B 8 8 ;,,""OOOt:t:
:t: OO:t:
* Jl:/\
~oot
tt"l Jl:,,;,,,,,;,,,8,8r8•• rlo•""OOO:t:t
**"" * : : :,, . ·ooo**
"OOOO:t: U" t l 8 8 : ••""OOOU
UL**:t::t:U:t:ntUU::t : :t::t:":t: : 8 8 : ••""OOOU
:t: OOO:t: :t::t: : 8 8 :.,""OOOJ!:J!:
t:t:nt:t::t:*JI::t:UJ!:UU U n l 8 :, , "" DOO:t:/
JUUtUUtU :t: :t:
UU:t::t::t:U:t:U:t:t j:
:t:l! :t: t t
* :t: l
t l
8
8
:, , "ODO:t::t:
:, , "ODO:t:/
t l ,"'"'OOD:t:
Jl:l! t J!::t:tlk 11: l ,""OOOU
ll:l!
:t:::l *•••**
**"'* t l
:t: l
.,""OOO:t:/
:t:::! J!::t::t::t::t::t: ••""OOO:t:
t l r•"HQQOt
:t::!
:t:::! 888
•"ooll::t:
"HOO:t::t:
*: t :
.B~ooo:t:ll:
Or o""OOO:t:/
:t:t! 888 ""OO:t::l 11:: o,,""OOClf
:t::: I 1\8 ""OO:t::J: :t:,;,,,,;,,,Q,,Q,,,"" OOO:t:f
:t::! I -\ •~oo:t:::t: ••""OOO:t:/
:t:::! I /9\] ""DO:t:lk l : , 0 ••""OODl
:t::: I L/888 "" OO:t::t:UU:t::t:U:t:tlf:t::tUU:t::tU:t:t:::t:::t:l:t:f:t::t:: : , r" "OOO:t:
t:! 888 ""OO:t::O r ,,;;""OO:t:: : Or""OOOf
:t:: I 888 ~"OO:t::O ' orll""OD:t:: : Q,""OOO*
•:! 888 ""0/:t::O r rO:l""OO:t: : o""OOOf
*!I 888 "" :t::t:t:::t:::t:U:t::UU:t:t:t:Ut:t:::t:::t:t:t:n*::t:tntt:t:::t:::t: : ""OOOO:t:
:t:::' aa8 "OOlk :t: 000 ; "OO:t:nu
:t::P 888 "DOll: t 000 l "DOff
:t::' 888 "DOt :t:: 000 : '' OOU
:t:::!
:t::!
888
888
"OO:t::
"OO:t:
* ooo : , .. oon
:t:: 000 : :oO:t:
:t::! 888 dOO:t:: f 000 : l l**
:t:::! 888 "DOt * o,,,;,,,,,;::t:
:t::! "OO:t:

.
tOO : Dl:t::
*='
:t:::!
ttf.tt "OOlk
"OO:t::
:t:OO : Ol:t::
(fOI : lU
:t:::! Jlttt "DOt [r:t:Ol : UUU'$
•no•

...•.
:t:: I I E:t::": u-----n:
:t::! tttH "OO:t:: t : :t::\~-----U:
:t:::!
:t:::! "001k
"OO:t:: *****
llll "OOlk
:t::l I "00*
*l! •oat

..
:t::l! tt:tU "DOt
*l! "OOIIC
:t::! "OO:t:
:t::! "OO:t::
•......•
I

........•
t: I "OOIIC
tl! "OO:t:
ll:l! "OD:t::
"OOIIC
:t::! I I "OO:t:
:t::! "OOIIC

.•
:t::! •oat
•:'
:t:::!
tUU "OOIIC
"OO:t:
:t:::! "OO:t::
:t::! tltU •oot
*:! "OOIIC
liO::!
*l!
88
88
"'*
r"O:t::
t:! 88 •"O:t:
f:!
:t:::!" 8
•"0*
r"Ot

...··:
I***-'*
'"* '
'"O:t:
• ,,'*** 8 r"OIIC

' ''
8 r"O:t::
,•o:t:
• ':t::l
'tl
o"O:t:
.·o:t::
•"0*
·:r: r"Ol
*t ':t::
't:
,•o:t:
r"O*
* 'tl
'lkl • "0*
** •:t::: tttl
t++t
r"Olk
,•ot
* ':t::: lttt r"Ot
*J!: ·'tl:t::
•: t++t
t+tt
, ·o:t::
r"O:t:
J!:==:=:t:: ttft o"O:t:
'***** ''"' .•o:t::
·------------"0*
:t::------------"0*
:t::ll o"Olk
:t:::'
tl!
:t::ll /t 00
********'
0
tt IUOOOOO
•••
Using Memory to Problem: Display the thermal gradient at equilibrium
Hold the Picture throughout a water-carrying rectangular copper pipe held at ooc if it
is covered with a heated lid at 100°C, and contains a rectangular
heater at its center heated at 200°C.

\-\t-a-\1~ E-\~E:nt'
v...t too'"c..

Water at
Eq\.) \\ \bri \l m
I
.I
---- 0
-
r '

This problem is a modificatio n of an old FORTRAN problem


found in A Guide to FORTRAN IV Programming, Daniel D.
McCracken, p. 98 (Wiley, 1965).
Solution: (1) Consider the pipe's dimensions to be 40 units
wide and 30 units deep; both sides and the bottom are the cold
copper, and the top is the hot heating element. (2) Reserve a
30x40 integer array X in memory, with X(O,l) to X(0,39) held at
a value of 100; X(30,0) to X(30,40), X(O,O) to X(0,30), and
X(0,40) to X(30,40) held at a value of 0. These are the edges of the
pipe. The 6-unit wide by 4-unit deep center heating element is held
at 200 degrees. (3) Proceed throughout the array wherever there is
water, from X(l,l) to X(1,39), then X(2,1) to X(2,39), ... through
X(29,1) to X(29,39), modifying each point on the basis ofits
neighbors according to the formula:

X(l,J) = (X(I-l,J)+X (I,J-l)+X(l +l,J)+X(I,J +l))/4

This formula calculates the temperatur e of a point by averaging the


temperature s of that point's four neighbors. (4) Repeat Step 3 for
as many iterations as the user wishes. (5) Convert all numeric values
of X, one 64-characte r line at a time, from numeric to graphic
symbols using this chart of symbols to indicate various temperatur e

60 Chapter 5 Graphics
ranges.

Intege r value Graph ic symbo l

0-9 A
20-29 B
40-49 c
60-69 D
80-89 E
100-109 F
120-12 9 G
140-149 H
160-169 I
180-189 J
200 K
All tempe ratures in the unspecified intervals are symbolized with a
blank. (6) Paint the picture on the screen one line at a time.

10 'FILENAME! C5P3"
8

20 'FUNCTION! SHOW THERMAL GRADIENTS USING RELAXATION


30 I AUTHOR ! JPG nATE: 3/80
40 CLEAR 300! DEFINT A-Z 'all intese r math
50 DEF FNACX) = 5 *X I 12 'FNA is Propo rtion of PiPe width
60 DEF FNBCX) = 7 * X I 12 'FNB is ProPcirtion of PiPe dePth
70 IT = 100 'IT is total itera tions
80 DEPTH = 30! WIDTH = 40 'set UP sraPh size
90 LL = FNACWIDTH)! LR = FNBCWIDTH> 'set four corne rs of PiPe
100 LT = FNACDEPTH>! LB = FNBCDEPTH>
110 INPUT "LID, EDGE, CENTER TEMPERATURES"iLID,EDGE,CENTER
120 LPRINT "TemPeratures! Lid = iLID;TABC26)"Edse =";EDGE;
8

130 LPRINT TABC43>"Center ="iCENTER


140 LPRINT
150 LPRINT
160 LPRINT "Dimensions! DePth ="iDEPTHi
170 LPRINT TABC26) 8 Width =•;wiDTHiTABC39)"1terations =8 iiT
180 LPRINT
190 DIM X<DEPTHrWIDTH>r S$(21) 'S$ is swmbol for temPerature
200 FOR I= 0 TO 20 STEP 2! READ SSCI>! NEXT I
210 DATA A, B, Cr Dr E, Fr G, Hr I, J, K
220 ' everw other swmbol is blank
230 FOR I= 1 TO 19 STEP 2! SS(I) = H " : NEXT I
240 ' set starti ns temPerature from user
250 INPUT "INITIAL TEMPERATURE CO TO 200, NEG. = RANDOM>•;T
260 IF T>=O THEN 310
270 ' set temPerature to random - besin
280 FOR 1=1 TO DEPTH-1! FOR J=1 TO WIDTH-1! XCirJ>=RND<200}
290 NEXT J,I: GOTO 330

Chapte r 5 Graphics
61
300 ' set temPerature to user' s suSie stion
310 FOR 1=1 TO DEPTH-it FOR J=1 TO WIDTH-lt X<I,J>=Tt NEXT J,I
320 ' set lid and ed•e temPeratures
330 FOR I=O TO WIDTHt X((h I>=LIDt XHtEPTH, I>=EDGE: NEXT I
340 FOR I=O TO DEPTH! X(!,Q)=EDGEt XCI,WIDTH>=EDGEt NEXT I
350 ' set PiPe temPeratures
360 FOR I=LT TO LBt FOR J=LL TO LRt X(I,J)=CENTER: NEXT J,I
370 CLS now comes the tedious Portio n
380 FOR N=l TO ITt I = 0 t GOSUB 460
390 ' calcu lation s. The busY loop
400 FOR I = 1 TO DEPTH - 1: FOR J = 1 TO WIDTH - 1
410 IF I > LT AND I < LB AND J > LL AND J < LR THEN.25NEXT J
420 X(I,.J)=(X(I-1,JHX<It!J.JHXCI,J-1HXCI,J+1 »*
430 NEXT Jt GOSUB 460t NEXT It GOSUB 460! NEXT N
440 GOTO 440 freez e screen
450 ' subroutine to calcu late and Print one line
460 A$=""! FOR K=O TO WIDTH ,
' checK if cente r Portio n -don 't calcu late it
,...
470
480 IF K > LLt1 AND K < LR-1 AND I > LTt1 AND I < LB-1
THEN A$=Aft"t" ELSE A$=A$tS$(X(I,K)/10)
490 NEXT K
500 I

510 IF DEPTH >15 PRINT A$, N; I ELSE PRINT @ I*64, A$, N; I;


520 IF INT<N/10)t10<>N OR I<>O THEN 560
530 LPRINTt LPRINTt LPRINT
540 LPRINT TABC15>"0utPul GraPh"
550 LPRINT TAB< 15)"- ----- -----" TAB< 43)"l terati on" B(54);I
560 IF INTCN/10)l10=N THEN LPRINT A$;TABC46);N;TA
570 RETURN
10000 END
TemPer atures: Lid = 100 EdSe = 0 Center = 200
Dimensi ons: DePth = 30 Width = 40 Iteratio ns = 30
OutPut GraPh
Iteratio n
AFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA 10 0
ACDD DDCA 10 1
AB CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC BA 10 2
A BBB BBB A 10 3
AAA AA 10 4
AAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAA AAAAAA 10 5
AAAAAAA AAAAAA 10 6
AAAAAAAAAAAAAAAAAAAAAAAAAAAA 10 7
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 10 B
AAAAAAAAAAAAAAAA B AAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAA B B AAAAAAAAAAAAAAA 10 9
AAAAAAAAAAAAAA BC D[IDD C AAAAAAAAAAAAAA 10 10
AAAAAAAAAAAAA BCDE FF EDC AAAAAAAAAAAAAA 10 11
AAAAAAAAAAAA BCD HHHH DCB AAAAAAAAAAAAA 10 12
AAAAAAAAAAAA B E KKKKKKGE B AAAAAAAAAAAAA 10 13
AAAAAAAAAAAA HKttttK E AAAAAAAAAAAAA 10 14
AAAAAAAAAAAA KttttK E AAAAAAAAAAAAA 10 15
AAAAAAAAAAAA B EGKKKKKKGE AAAAAAAAAAAAA 10 16
AAAAAAAAAAAA BCD GHHHHG DCB AAAAAAAAAAAAA 10 17
AAAAAAAAAAAAA BCDE EDC AAAAAAAAAAAAA 10 18
AAAAAAAAAAAAA BC [1))[1 C B AAAAAAAAAAAAAA 10 19
AAAAAAAAAAAAAA B B AAAAAAAAAAAAAAA 10 20
AAAAAAAAAAAAAAAA BBB AAAAAAAAAAAAAAAA 10 21
AAAAAAAAAAAAAAAAAAA 10 22
AAAAAAAAAAAAAAAAAAA 10 23
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 24
AAAAAAAAAAAAAAAAAAAAA AAAAAAA AAAAAAAAAAAAA 10
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 10 25
10 26
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 27
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 10
AAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 10 28
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 10 29
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 10 30

62 Chapter 5 Graphics

' i
OutPut Gl'aPh
Iterat ion
AFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA
ACD 20 0
DCA 20 1
AB C CCBA
A B CCCCCCCCCCCCCCCCCCCCCCCCCCCC 20 2
AA BBBBBBBBBBBBB B A 20 3
BBBBBBBBBBB AA 20 4
AAA BBBBBBBBBBBB AAA
AAAAAAAAAAA 20 5
BBBBBBB AAAAAAA 20 6
AAAAAAAAAAAAA BBBBBBBB AAAAAAAAAAAAA
AAAAAAAAAAAAA BB 20 7
C B AAAAAAAAAAAAAA 20 8
AAAAAAAAAAAAA B CC C B AAAAAAAAAAAAA
AAAAAAAAAAAA B C D EE 20 9
C B AAAAAAAAAAAAA 20 10
AAAAAAAAAAAA BCDE F F EDCB AAAAAAAAAAAA
AAAAAAAAAAA B 20 11
F F B AAAAAAAAAAAA 20 12
AAAAAAAAAAA BCD KKKKKK DCB AAAAAAAAAAAA
AAAAAAAAAAA BCDFHK$ti1KHFDCB AAAAAAAAAAAA 20 13
AAAAAAAAAAA BCDFHKIIIIKHFDCB AAAAAAAAAAAA 20 14
AAAAAAAAAAA BCD KKKKKK DCB AAAAAAAAAAAA 20 15
AAAAAAAAAAA B 20 16
F H HF B AAAAAAAAAAAA 20 17
AAAAAAAAAAAA BC F F DCB AAAAAAAAAAAA
AAAAAAAAAAAA B C D 20 18
D C B AAAAAAAAAAAAA 20 19
AAAAAAAAAAAAA BB C C B AAAAAAAAAAAAAA
AAAAAAAAAAAAAA BB 20 20
BBB AAAAAAAAAAAAAAA 20 21
AAAAAAAAAAAAAAA BB AAAAAAAAAAAAAAAA 20 22
AAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 20 23
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 20 24
20 25
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 20 26
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 20 27
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 20 28
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 20 29
20 30

Output GraPh
AFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA Iterat ion
ACD 30 0
EEEEEEEEEEEEEEEEEEE DCA 30 1
ABCC DDDDDDDDDDDDDDDDDDDDDDDDD CCBA
A B CCCCCCCCCCC 30 2
CCCCCCCCC B A 30 3
AA BBB CCCCCCCCCC BBB AA
AAA 30 4
BBBBBB BBBBBBB AAA 30
AAAAAA BBBB 5
BBBB AAAAAA 30 6
AAAAAAAAAA BBB CCCC BBB AAAAAAAAA
AAAAAAAAAAA BB CC 30 7
CC B AAAAAAAAAAA 30 8
AAAAAAAAAAA B C DDDDDD C BB AAAAAAAAAAAA
AAAAAAAAAAA B C DEE EED C B AAAAAAAAAAAA 30 9
30 10
AAAAAAAAAAA B EF GG F B AAAAAAAAAAA
AAAAAAAAAAA BCDE H 30 11
H EDC AAAAAAAAAAA 30 12
AAAAAAAAAAA C FHKKKKKKHF B AAAAAAAAAAA
AAAAAAAAAA B 30 13
FHKttl tKHF B AAAAAAAAAAA 30 14
AAAAAAAAAA B FHKf$ftKHF B AAAAAAAAAAA
AAAAAAAAAA 30 15
C FHKKKKKKHF B AAAAAAAAAAA 30 16
AAAAAAAAAAA BCDE H H EDCB AAAAAAAAAAA
AAAAAAAAAAA B CDEF 30 17
FED B AAAAAAAAAAAA 30 18
AAAAAAAAAAAA B D EEEE D B AAAAAAAAAAAA
AAAAAAAAAAAA B C DDD C BB AAAAAAAAAAAAA 30 19
AAAAAAAAAAAAA B CCCC B AAAAAAAAAAAAAA 30 20
30 21
AAAAAAAAAAAAAA BBBBBBBB AAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAA 30 22
AAAAAAAAAAAAAAAAA 30 23
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 30 24
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 30 25
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAA
30 26
AAAAt,AAA<~AAAAAAMAAAAAAAAAAAA
30 27
AAAAAAAAAAAA 30 28
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAA
30 29
30 30

Chapter 5 Graphics
63
The previous outpu t shows the effect of starting the pipe's
no
water temperature at 0 degrees. In McCracken's original work,
water at any other tempe rature .
menti on was made of initializing the
is, half way betwe en heate r and
We tried it at an average setting, that
the
edge, then at random settings from 1 to 200 degrees. Although
to be the most effect ive in reachi ng
latter case is not realistic, it seems
that the goal of this proble m is to
equilibrium quickly. Remember
the
produce a visual representation of the equilibrium condi tion in
rature can be anyth ing, even an unreal istic
pipe, so the starting tempe
random value.

TemPe ratures : Lid 100 Edse =0 Center = 200

Dimens ions: DePth 30 Width = 40 Iterati ons = 30

Output GraPh
Iterati on
0
AFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAE A
10
10 1
A E FF
A EE FFFF E DA 10 2
FFFFFF E BA 10 3
ABCD EE 4
ABCD EE FFFFFFF EEDCBA 10
ABC EE FFFFFFF EEDCBA 10 5
EEDCBA 10 6
ABC EE FFFFFFF
ABC EE FrFFFFFF FFFFFFFFF E DCBA 10 7
E DCBA 10 8
ABCD EE FFFFFFFFFFFFFFFFFFFF
ABCD EE FFFF FFFFFFF E DCBA 10 9
FFFF GGG GGG FFFF E DCBA 10 10
ABCD E E DCBA 10 11
ABCD E FFF GG HHHHHH G FF
ABCD E FFF GG I IH G FF EEDCBA 10 12
EEDCBA 10 13
ABCD E FFF G HIKKKKKKIHG FF EDCBA 10 14
ABCD E FF G H KIIIIKIHG FF
EDCBA 10 15
ABCD E FFF G H KlltiKI HG FF 10 16
ABCD E FFF GHIKKKKKKI G FF EDCBA
E CBA 10 17
ABCD E FFFFF GHIII IIH G FF 10 18
ABC E FFFFF G HHHHH G FF E BA
FFFF GGGGGG FF E BA 10 19
ABC EE E BA 10 20
ABC EE FFF FF
FFFFFFFFFF FF E BA 10 21
ABC D E 10 22
ABC D E FFFFFFF FF E BA
FF E BA 10 23
ABC D E 10 24
AB It EE E CBA
10 25
AB D EEEEEEEEEEEEEEEEEEEEEEEEEEE EE EEDCBAA 10 26
A C D EEE EEEE
27
A B C DDDDDDDDDDDDDDitDDDDDDD DDDDDD C A 10
10 28
A B CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC B A
AA 10 29
AAA BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 30
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAA 10

64 Chapter 5 Graphics
Ou lpu t GraPh
--·---- ----- Iterat ion
AFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA
A EEE 20 0
A D EEE EE A 20 1
EE D A 20 2
ABC D EEE EEE D CBA
A CD EEE 20 3
EEEE D A 20 4
A c II EEEE EEEE DC A
A c D EEEE 20 5
A c D EEE FFFFFFFFFF
EEE D c A 20 6
EEE D c A 20 7
A c D EEE FFFF FFFF EEE D c A
A c D EEE FFF 20 B
GGGG FF EEE rr c A 20 9
A c D FE FF G GG FF EEE D c A
A c [I EE FF G H 20 10
HG F EEE D c A 20 11
A c D EE FF G I I G FF EEE D c A
A c D EE F 20 12
HIKKKKKKIHG FF EEE D c
A c D EE F G H KUUK HG FF EEE D c A A
20 13
A c rr EE F 20 14
H KUUK HG FF EEE c A
A BC D EE FF GHIKKKKKKIHG FF EEE D rr c A
20 15
20 16
A BC D E F G HI I G F EEE rr c A
A BC D EE FF G HH HH G FF 20 17
EEE [I c A 20 18
A BC D EEE FF GG GG FF EEE D c A 20 19
A B DD EEE FFF G FFF EEE D c A
A B 20 20
D EEEE FFFFFFFFF EEEEE D CB A 20
A f.< c [I EEEEE 21
EEEEEE D CB A 20 22
A f.< c [1[1 EEEEEEEEEEEEEEEEEEE D CB A 20 23
A f.< c IIDD DD c B
A BB c DDDDDDDDDDDDDDDDDDDDDDDDD c BAAA 20
20
24
AA B CCC 25
cc AA
API BB ccccccccccccccccccccccc BB AA 20
20
26
27
AAA BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB AAA 20 28
AAAA1'1A
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAA
20 29
20 30

OutPut Graph
---·---· ----- Iterat ion
AFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA
ACD EE 30 0
EE DCA 30 1
A D EEEE EEEE D A
AB DD EEEEE 30 2
EEEEE DD BA 30 3
A c DII EEEE EEEEEE [I c A
A BC [I EEEE 30 4
EEEEE [I B A 30 5
A B c [I EEE EEEE [I c B A
A B c DD EEE 30 6
FFFFFFFF EEE Dc B A 30 7
A B c DD EE FFFF FFFF EE D c B A
A B c DD EE F 30 8
GGGG FFF EE Dc B A 30 9
A B c [Iff EE F G GG F EE [I c B A
A B c DD EE FF G H 30 10
A B c fi[l EE F G I
H G FF EE D c B A 30 11
I G F E [I c B A 30
A B c D EE F GHIKKKKKKIHG F EE D c 12
B A 30 13
A B c D EE F H i':UHK HG F EE DD
A B c [I [I EE F H KUttK HG F EE DD c BA 30 14
A B c DD EE F GHIKKKKKKIHG F EE DD c B A
c BA 30 15
A B c [I E FFG HI 30 16
I G F E DD c B A 30 17
A B cc [I EE F G HH H G F EE [I c B A
AA B c [I [I EE F G 30 18
GG FF EEE [I cc BAA 30 19
AA B c DD EE FF FF EEE DD c B AA
AA B c DII EEE 30 20
FFFFF EEE [I [I c B AA 30
AI'• B cc fi[l 21
EEEE EEEEE [I [I c B AA 30 22
AA B cc DDDD [1[1[10 cc B AA
AA BB cc 30 23
IIDDDDDDDD[I[IDDDDD cc BB AA 30
AA BB ccccc 24
ccccc B AA 30 25
AAA BBB ccccccccccccccccc BB AAA 30 26
APIA A BBBBBBB BBBBB AAAA 30
AAAAA 27
BBBBBBBBBBfiB AAAAA 30 28
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 30 29
3() 30

Chapter 5 Graphics
65
Histograms or The pictorial representations variously called histograms or
Bargraphs bargraphs are easy to understand but in some ways difficult to
to
program. If the bars vary in length horizontally, they are trivial
is arrang ed contra ry to custom .
program, but the descriptive text
Problem: Draw a histogram of month ly rainfall for one year.
The rainfall in inches is stored in the array R dimensioned 12.
Solution 1: Horizontal arrangement of bars.

10 'FILENAME: "C5P4"
20 'FUNCTION: BARGRAPH OF RAINFALL
30 ' AUTHOR : JPG DATE: 3/80
40 CLEAR SOOt DIM M$(1 2), R<12)
50 ' inPut secti on
60 FOR I=l TO 12: READ M$( I)! NEXT I
70 FOR I=1 TO 12: READ R<I>t NEXT I
80 DATA Jan, Feb, Mar, APr, Maw, Jun
90 DATA Jul, Aug, SePr Oct, Nov, Dec
100 DATA 5.23, 5.79, 3.02, 2.44, 2.62, 3.99
110 DATA 4.75' 4.2o, 2.01, 3.49, 4.21' 4.05
120 LPRINT "Month Inches of rainf all"
130 ' calcu late cons tant for keePing bar under 40 *'s
140 L=O
150 FOR I=l TO 12: IF L<=RCI) THEN L=R(I)
160 NEXT I: K=40/L
170 ' looP to Print ~raPh
180 FOR I=1 TO 12
190 LPRINT " "Hi$( I H" ";STRINGS(R( I >*K'"*" H
200 LPRINT TA~55) USING "tt.tt ";R< I>
210 S=S+R<I>: NEXT I
220 LPRINT STRING$(60,"=" >
230 LPRINT "Aveu;: A = S/12
240 LPRINT STRINGS<A*K-2,"*">;
250 LPRINT TABC55) USING "tt.t t";A
260 LPRINT "Tw,lve ruonth total ";
270 LPRINT TA~54) USING "ttt. tt";S
10000 ENlt

66 Chapt er 5 Graphics
Month Inches of rainf all
Jan ************************************ 5.23
Feb **************************************** 5.79
Mar ******************** 3.02
APr IIIII IIIII IIIJI I
2.44
Ma~ ****************** 2.62
Jun *************************** 3.99
Jul ******************************** 4.75
Aug ***************************** 4.20
SeP ************* 2.01
Ocl ************************ 3.49
Nov ***************************** 4.21
Dec ***************************
---------- 4.05
---------------------N"_____
----------------------------------- _____
----- _____
----- _____
----- _____
----- __-_
Ave************************ -----
Twelve 3.82
~onth total 45.80

Anoth er bargra ph could be arranged so that the bars are


vertical, which is the more typica l display. The following progra
m
does this, and also shows the use of a list of sentinels, or flags,
in
the FLAG array.
Soluti on 2: Vertical arrang ement of bars.
10 'FILENAME: "C5P5"
20 'FUNCTION: REVISED RAINFALL GRAPH
30 AUTHOR : JPG
I
DATE: 4/80
40 DIM FLAG(13), M$(13), RC13)
50 ' read in the data
60 FOR 1=1 TO 13: READ M$(1): NEXT I
70 FOR I=l TO 12: READ R(I): NEXT I
80 DATA Jan, Feb, Mar, APr, Ma~, Jun
90 DATA Jul, Aug, Sep, Oct, Nov, Dec, Ave
100 DATA 5.23, 5.79, 3.02, 2.44, 2.62' 3.99
110 DATA 4.75, 4.20, 2.01, 3.49, 4.21, 4.05
120 LPRINT TABC20);"Rainfall bw month"
130 LPRINT TABC20);"-------- -- ----- "
140 LPRINT
150 ' calcu late cons tant for keePin~ the heish t under 20
160 L=O lines
170 FOR I=1 TO 12: IF L<RCI) THEN L=R<I>
180 S=StRCI> 'calc ulate the su~
190 NEXT I: K=L/20: R<13>=S/12
200 FOR J=20 TO 1 STEP -1
210 FOR 1=1 TO 13
220 IF RCI><J*K THEN 250
230 IF FLAG( I >=1 LPRINT TAB< U:4-4 >USING ''i. i. '' ;M$( I H: GOTO
240 IF FLAG( I >=O LPRINT TAB< 1*4-4 )USING ":l.t ";R( I H t FLAG( 250
250 NEXT I: LPRINT I >=1
260 NEXT J
10000 END
Chapt er 5 Graphics 67
Rainf all b~ month
--------
5.8
Feb
..Jt.<. Feb
0: '1

Jan Feb
.Jan Feb 4.8
Jan Feb Jul
Jan Feb .Jul 4.2 4.2
Jan Feb 4.0 Jul Aus Nov 4.1 3.8
Jan Feb Jun Jul Aus 3.5 Nov Dec Ave
Jan Feb Jun Jul Aus Oct Nov tlec Ave
Jan Feb 3.0 Jun Jul Aus Oct Nov nee Ave
Jan Feb Mar 2.6 Jun Jul Aus Oct Nov Itec Ave
.Jon Feb Mar 2.4 lia~ Jun Jul Aus Oct Nov Itec Ave
Jan Feb Mar Ar-r· Ma~ Jun Jul Aus Oct Nov Itec Ave
Jan Feb Mar APr· Ma!:l Jun Jul Aus 2.0 Oct Nov Itec Ave
Jan Feb Mar A?r Ma~ Jun Jul Aus Se? Oct. Nov Dec Ave
Jan Feb Mar APr Ma~ Jun Jul Aus Se? Oct Nov !lee Ave
.Jan Feb Mar APr Ma~ Jun Jul Aus Sep Oct Nov Itec Ave
Jan Feb Mar AF-r Ma~ Jun Jul Aus Sep Oct Nov Dec Ave
Jan Feb Mar APr· Ma~ Jun Jul Aus SeP Oct Nov Itec Ave

Table-Driven Many graphic designs can be summarized in the form of a table


Pictures of starting addresses and lengths. For example, the design of the
numeral 1 could be stored in a two-dimensional intege r array D( 12,2)
in which the first subscript represents the starting colum n and the
m
second subscript represents the string length. The following progra
prints the numeral 1 shifted right approx imatel y 30 spaces .

10 'FILENAME: "C5P6"
20 'FUNCTION: !ABLE-DRIVEN DIGIT
30 ' AUTHOR : JPG DATE: 12/79
40 DEFINT A-Z: DIM DC12 ,2)
50 FOR I=1 TO 12: FOR J=l TO 2: READ [I(I,J >: NEXT J,I
60 DATA 31, 3, 30,'4 ' 29, 5,131 , 3, 31,\3 , 31, 3
70 DATA 31, 3, 31, 3, 31, 3, 30' 5, 30, 5, 30, 5
80 FOR I=l TO 12
90 LPRINT TABCD(I,l)); STRING$CDCI,2),"*">
100 NEXT I
10000 EN[I

68 Chapte r 5 Graphics
***
****
**~~}-
***
***
**r
***
***-
*****
*****
*****,.....

The graph of this digit is hardly representative of the many such


designs that could be done, particularly since it is solid throughout;
each printed line is made up of just one string. The Starship
Enterprise printing program shown earlier (program C5P2) includes
a number of features that lend flexibility to this technique. That
program requires the printing of one or more strings per line, so it
uses a signal value which has to be included in the table. This table
is really a series of DATA statements, and the signal value tells the
computer to return the cursor for the production of another line.

Picture Within The simplest procedure for painting a picture is to contain the
Program design itself within the program. For example, the output of
program C5P7 is obvious.
This technique wastes memory, because each line that is printed
is stored in its entirety. However, it can be useful as an intermediate
tool to develop pictures, from which data tables can be designed.
Program C5P8 is one last example of table driven graphics. It
was written by Steve Grillo and his goal was to write a program that
would produce banners of his choice on the screen. It does this, and
more: You can select whether you want the banner displayed on the
screen or printed on paper, and you can select the width of the
letters. The output hints at the power of the program.

Chapter 5 Graphics 69
10 'FILENAME: nc5p7n
20 'FUNCTION: PICTURE OF SNOOPY
30 I AUTHOR : SPG DATE: 2/80
40 CLS: CLEAR 1000
100 LPRINT n XXXX"
110 LPRINT " X XX"
120 LPRINT " X *** X XXXXX"
130 LPRINT " X ***** X XXX XX"
140 LPRINT " XXXX ******* XXX XXXX XX"
150 LPRINT " XX X ****** XXXXXXXXX XX XXX"
160 LPRINT " XX X **** X X** X"
170 LPRINT " X XX XX X X***X"
180 LPRINT " X //XXXX X XXXX"
190 LPRINT " X // X XX"
200 LPRINT "X II X XXXXXXXXXXXXXXXXXX"
210 LPRINT "X XXX// X xn
220 LPRINT "X X X X X"
230 LPRINT "X X X X X"
240 LPRINT " K X X X X XX"
250 LPRINT " X X X X X XXX XX"
260 lPRINT " X XXX X X X X X X"
270 LPRINT " X X X XX X XXXX"
280 LPRINT " X X XXXXXXXXA XX XX X"
290 LPRINT " XX XX X X X XX"
300 LPRINT " XX XXXX XXXXXX/ X XXXX"
310 LPRINT " XXX XX*** X x•
320 LPRINT XXXXXXXXXXXXX * * X X"
330 lPRINT ·---· X X X"
340 LPRINT *-* * XXX X X"
350 LPRINT ·- I XXX X"
360 LPRINT ·- *X XXX"
370 LPRINT *- *X X XXX"
380 LPRINT ·- *X X XX"
390 LPRINT *- *XX X X"
400 LPRINT ' * *X* X X X"
410 LPRINT * *X * X X x•
420 LPRINT * * X** X XXXX x•
430 LPRINT * * X** XX X X"
440 LPRINT * ** X** X XX X"
450 LPRINT * ** X* XXX X X"
460 LPRINT ' * ** XX XXXX XXX"
470 LPRINT " * ** XXXX X X"
480 LPRINT "
490 LPRINT " =======******* * *
* ** X
X
X
X
X"
XXXXXXXXA"
500 LPRINT " * ** /XXXXX XXXXXXXXA >"
510 LPRINT " =====**********
520 LPRINT " ====• *
* X
X > A )"
A A >XXXXX"
530 LPRINT "=========********** XXXXXXXXXXXXXXXXXXXXXX"
10000 END

70 Chapter 5 Graphics
10 'FILENAME! "C5F'8"
20 'FUNCTION! TO PRINT MESSAGES ON THE SCREEN OR PRINTER
30 AUTHOR
I SPG DATE t 6/79
40
45 data lines: 1000-1070
50 maJor subroutines :
60 1
2000 converts the decimal number to binar·~ <>.nd
70 Plots the Proper Pixels on the screen
80 3000 Plots a larse word ([$) on the screen at. x,v
90 4000 initialize matrix P<N,B) usins the data
100 5000 stores 6 Power of 2 in arraY 0
110 6()00 accePts a temporars strin! from the user and
12(l if desired, copies lhe screen to the Printer
13(i I

500 CLEAR 200! DEFSTR A! DEFINT B-z: DIM P<91,B>


510 GOSUB 4010! GOSUB 5000
520 CLS! INPUT "WOULD YOU LIKE A SAMPLE MESSAGE";A
530 IF A<>"YES" THEN 700
600 CLS: WIDTH=l! E$="LETTER": X=JO: Y=O: GOSUB 300~! ES="Bs!"t
X=30! Y=15: GOSUB 3000! ES="Steve": X=O: Y=25: GOSUB 3000:
ES="Grillo" : X=35: Y=36: GOSUB 3000: PRINT@950,"<<CR>>";:
INPUT S$
70~'"J Y=O : H=(l: CLS
710 PF-:INT IINote:"
720 PRINT II To Print lower case messases, hold t.he"
730 PF-:INT II shift kes while LYPins."
740 PF-:INT
750 H=H+l: IF H>5 THEN 8:1.0
ELSE LINE INPUT "TYPE IN THE WORD ('END' TO STOP)! ";ES(H)t
IF ESCH>="END" THEN 810
760 WIDTH( H)=0
770 INPUT "WHAT WIDTH ( :1.-4) WOULD YOU LIKE";WIDTH<H>t
IF WIDTHCH>=O THEN WIDTH<H>=l
780 X( H >=O
790 INPUT "FIRST HORIZONTAL POSITION OF THIS WORD C>=O)";XCH)
800 PRINT! GOTO 740
810 PRINT: PRINT
850 PRINT nno YOU WANT THE MESSAGE SENT TO THE PRINTER"
860 INPUT H 1=YES 2=NO";P1
900 CLS: FOR 1=1 TO H-:1.: X=X<I): WIDTH=WIDTH(l): ES=ESCI)!
GOSUB 3000! Y=Y+9: NEXT I: GOSUB 6000
910 GOTO 520
920 I lines 1000-1070 hold all of the dat.a
930 I for the characters
940 I

Chapter 5 Graphics 71
;!J'HHl DATA -2, -2,-·1 ,95, -1 r 7, -2,7,--1 r20 r 127,20 r 127 r2(l'
-·2,-2~
-1,4r42r127 r42r16,-1r6 7r32r19r8rl 00,2r97r-1r 48'74r69r1B r32,64r
-1r4r2r1r-1r 28,34r65r-1 r65t34r28r- 1r34r20r127 r20r34r-1rB r8r127r
a,s,-1,88,56 r-lr8r8rBrB r-lr32,80,32 r-1r64r32r1 6r8r4r2'-1
1010 DATA 28r34r65r65 r34r28r-lr66 r127r64r-1r 66r33r64r17 r64r9r
70r-lr~3r64r1,72r5r74r49,-1,16r8r20r2r125r16r-1r39r64r5r64r5r
64r57r-lr48 r72r4r74rlr 72r48r-lr65 r32r17r8r5r 2•lr-lr54,73 r-2r73r
-2r73r54,-1, 6r9t64,41r1 6r9r6v-1r34 v85r34v-1r9 0Y33r26r-1
1020 DATA Br-2r20r-2r 34r-2r65r-lr 20r20r20r20 r-lr65r-2r34 r-2r20r
-2r8r-1r2r1 r-2r93r-2J5 r2r-1,62r65 r-2r89r84r1 4r-lr120r20 r18r17r
1Br20r120r- 1r65r127r73 r73r54,-1,62 r65r65r65r3 4r-1r65r127 r65r65r
62r-1r127r7 3r73r65r-1r 127r9r9r1r- 1r62r65r65r 81r50r-1
1030 DATA 127r8r8,127 r-1r65,127r6 5r-1J48r64r 65r63r1r-1r 127r4r8r
is' 3ir ,:j 5,-1, 127, 64, 64' 64, -:1. , 127, 2, 4, 8r 4, 2, 127, --1, 127,2, 4, 8, 16,
32r127r-1r6 2r65r65r65r 62r-1r127r9 r9r6r-1r62r6 5r65r17r33r
94r-lr127r9 r25r38r64r- 1
1040 DATA 38r73r73r73 r50r-1r1r1r1 27r1r1r-1r6 3r64r64r64r 63r-1r
15r:l.6r32r6 4r32r16r15r -1r63r64r32 r24r32r64,6 3,-1,65r34,2 0t8;20,
34;65,-1,1;2 J4¥120r4f2 J1r-1,65,32 ,81,8;69,2r6 5J-1f4f6J12 7,6,4,
-1,16,48;12 7,48,16,-1, 8,20,42,8;- 1;8;42;20.8 .-1,64•64,6 4,64,-1
1050 DATA 62,65,-2,89 ,84,14,-1,32 ,84,84,84,4 0,-1,127,68 r68,68,
56,-1, 56-; 68r68, 68, 72r -1,56, 68, 68.68,127 ;-1 ,56;84 ,a4' 84 'a, -1 ,4,
126;5,1,2,-1 ,72,84,84;8 4,106;-1,12 7,4,4r4,120 ,-1,6B,125, 64,-1,
32,64,64,64 ,61,-1,127r8 r20,34r64r- 1J65,127,64
l.Q.QO DATA -1,124,4,:1. 20,4r120',-1 ,124'4'4'120 r-1,56r68,
68, 68,56";-1, 124,20., 20,20 ,a, -··1, 56,68,68.20 , 36,88,
-1,124J4r·4f 4,8
1070 DAT~-1t8,84r84r84,32r-lr4;63,68t64r32,-1,60,64,64,124'-1'
i2, hn 32,64 • 32r 16, 12r-1 '60' 64,32d6; 32'64' 60 ;-1 ,68' 4(h 16,40 ,68,
-1~12rBOtB0,80r44,-1,68,32,68,16,68,8,68,-999
2000 ' subroutine to chanse decimal t to binarY
2010 1 and Plot. the discrete Pixels on the screen
2020 FOR U=l TO 7: W=O(V)! IF D-W<O THEN 2090
2030 D=D-W
2040 FOR R=l TO WIDTH
2050 IF XtR<128 AND Y-Vt7<48 THEN 2070
2060 PRINT: PRINT " ***OUT OF BOUNDS ERROR***"! STOP
2070 SET<XtR,Y-Vt7)
2080 NEXT R
2090 NEXT u: X=X+WIDTH-1: RETURN
3000 1 subroutine t.o Plot a wor·d ( E$) on the scr·een ai x,y
:5010 FOR G=1 TO LEN< E$ )! M=ASC( MID$(E$,Gd ))-31.: B=O
3020 B=Bt1! IF P(M,B>=O THEN 3030 ELSE D=P<MrB}t X=Xt1t
GOSUB 2000! GOTO 3020

72 Chapter 5 Graphics
3030 X=X+5: NEXT G: RETURN
400(/ Isubrouti ne to initiali ze matrix P(N,B) usins
4005 1
lhe data in lines 1000-1070
4010 CLS! B=O: PRINT: PRINT "LOADING CHARACTER-";
4020 FOR N=l TO 91
4030 READ CS: C=VAL<CS>: IF C$="-1" THEN 4050 ELSE
IF C>O PRINT@85,CHRS<N+31 );
4040 IF C=-999 GOTO 4070 ELSE B=Btl: P<N~B>=C: GOTO 4030
4050 B=O
40t,O NEXT N
4(170 RETU~:N
5000 1
subrouti ne to store 6 Powers of 2 in arra~ 0
5010 FOR M=l TO 7: 0(M)=2[(7-M>: NEXT M: RETURN
6000 PRINT@950,"<<CR>>";:INPUT SS
6010 IF P1=2 THEN RETURN ELSE PRINT@950r" " .f
6020 1
the ne;d. J.ine ~:.et.~, t.he IP-··225 r-r-int.er t.o :1.6.5
6030 LPRINT CHR$(31)
6040 cop~ the screen srar-hics t.o t.he Print.er-
6050 FOR Y=O TO 47: FOR X=O TO :1.23
6060 IF POINT(X,Y) THEN LPRINT "*"; ELSE LPRINT " ";
6070 NEXT X: LPRINT" ": SETCOrY)! NEXT Y: RETURN
:1.0000 END

********** **u **
** t.tt:t.
**
u ******** n ******
** **
** **
** **
** **
** n
** ** ** ** ** u:**
** ** ** *-***** **

*** *** *** ***


***
***
*** ***
*** *** *** ******
***
************ *********
m
*** *** *** ***
m ***
:t:Ui*iitt:U:t
*** ****** ***
***
*** ***
*** ***
:t.:t.UU::t.:t.:t.
*** *** ***
*** *** ************ *********

****************
:n:tt ****
****
**** **************** **********-
************ **** **
**** ************ ****
****
****
****
************
**** ****
********
****

Chapter 5 Graphics 73
m ·mtt m m
*** * p* *** ** ****
* ** * *
* * ** ** *** * ** ** * *
** * *
*
***** ****
** * * *** * *m
*** * * *t t *
*
** t * *
**
* *
** **
* **
** ***** * **
tm ** t t m
m * * *
***
******** ** ** ******** ******u
**tnt **** ** u ** ** **u u
** ** ** ** **u **
u **
mtU
** **** **** ******
u ** ** ** ********
**
**
.tt **** ** ** ** u
** u
mttm ******** **
** ** ** **
n u mmtt
**
**** ** n **
** u **
**u
****
n ** ** ** u **u mt
u ** ** ** umt
**
** **
**
************** ** **u **
u
u ** u ** **
u ** u ** u ********
**
* * *** *** ***** **** * * * ***
* * *t *u * * *
* * *
*********** ** *m * *m
** *
*
**
*m
**
* *
* * ** * * ******* **
* ** ** * *t *
*t ** *** *m * *
* mt * ***

74 Chapter 5 Graphics
Charac ter Graphics The second major graphical method is charact er graphics. This
method is realized on the TRS-80 through the use of the PRINT @
instruc tion which can address any of the video screen's 1024
positions. The position s in the screen's top row have addresses 0 to
63, the second row 64 to 127, the third row 128 to 191, and so on
until the last row, which has addresses 960 to 1023.

PRINT @ The PRINT @ instruc tion uses the screen address to positio n the
leftmos t charact er to be printed . Caution : The @ symbol is
represe nted differen tly in memor y when the shift key is depressed,
so be sure to use the unshift ed @,othe rwise a syntax error results
when the program is execute d.

Instru ction OutPut

10 PRINT @ O,"X" X at the loP left of the screen


20 PRINT @ 95,"ZOT" ZOT center ed on the second line
30 PRINT @ 510,"ZOTZOT" ZOTZOT center ed on the screen
40 PRINT@ 1023,"Z"; Z al the bottom risht of the screen

If the PRINT@ instruc tion ends with no punctu ation, the cursor
returns to the beginning of the next line, and this may produc e
undesirable results. If the address is betwee n 960 and 1023, the
string prints on the last line of the screen, then the screen scrolls one
line. The effect of a PRINT @960 is the same as a PRINT @896,
which of course is not what was intende d.
If the PRINT @instr uction ends with a semicolon (;) the result
is predict able. We recomm end that you always end all PRINT @
instruc tions with a semicolon.

STRIN G$ A Level II BASIC functio n which is useful in graphing is the


STRING$ functio n. This functio n has two arguments: The first is
the numbe r of characters desired, up to 255, and the second is the
charact er itself.

Chapter 5 Graphics 75
Ins t.ru c t.i on Ou t.Pu t

AAAAA ****
******
10 PlUtH STRING$( 10, ":t." )
20 PRINT STRING$(5~CHR$(65))
30 PRINT STRING$C8rCHRS( 13)) Cursor moves down B linesr
Positi ons itself at left of
line. CHRS( 1.3) is a
carria~e/cursor return
which is the charac ter
Produced by the ENTER
1\e\:! (/EN/) .
zzz .•. zzz (64 of them> on
the bottom of the screen
50 A=128! BS="9"! PRINT STRINGSCArBS) Two rows of 9s

Note: Since the comput er builds the string in its memor y first
before displaying it, your program may require additio nal string
space to be reserved for it. Use the CLEAR instruc tion to allow for
more string space.

The Character Set A look at Append ix B reveals that the TRS-80 has a total of
25 6 possible characters, and the effect of each can be displayed by
using the instruc tion PRINT CHR$(N) where N is a numbe r from 0
to 255. A few of these values of the TRS-SO's charact er code have
no effect on the TRS-80, but most do, and they are certainly more
numero us than would be necessary for just the alphabe t, digits, and
special characters that BASIC needs. The table below is a summa ry
of the expand ed table in Append ix B.

Code Functio n

0-7 None
8-31 Carriage/Cursor Contro l
32-47 Special Characters
48-57 Digits
58-64 Special Characters
65-90 Alphab et (Upper Case)
91-95 Carriage/Cursor Contro l
96 Lower Case@
97-122 Alphab et (Lower Case)
123-127 Lower Case of Codes 91-9 5
128-191 Graphics Characters
192-255 Tabs for 0 to 63 Spaces

76 Chapter 5 Graphics
Tabulation Codes The last two groups of codes represe nt half of the possible
printab le charact ers, and they deserve special mentio n. The last 64
codes allow tabbing withou t the TAB functio n.

Inst.ructj.on OutPut

10 PRINT CHR$(202);"*" * in lhe lOth Positi on


20 AS=CHRS( 192ti) : PRINT AS;"*" * in the Ith Positi on

These codes make possible some very simple graphics programs,


such as the one below. Note that this techniq ue is restrict ed to
screen graphics because printers don't respond to the tabulat ion
codes.

10 I FILENAME: 11 C5P9n
2(l I FUNCTION:
DRAW A VERY SIMPLE CHRISTMAS TF:EE
3(l I
AUTHOR • JPGt
DATn Oi 7
l E7ri
I
40 CLEAF\ 200
50 i'\=32
60 FOR I=1 TO 12
70 IF 1>1 THEN M=M-RND<3>: R1=RND(5)-3: R2=RNDC5)-3
80 PS=CHRSC192tM-R1)
90 L=65-M*2+R2
100 PF:INT PS; SHUNG$( L'" X" )
110 NEXT I
120 PRINT TAB(29)"MERRY"
130 PRINT TAB(29)"XMAS!"
140 GOTO 140 freeze the screen
10(!00 END

Chapter 5 Graphics 77
Graphics Codes The codes from 128 to 191 are graphic characters that are made
up of six small rectangles, or pixels, arranged in three rows and two
column s for each character. Each charact er entirely fills one of the
1024 print position s on the screen. Each pixel is either on (bright)
or off (blank), depend ing on the code. For example, the graphic
charact er 134loo ks like this:

~
where I is off, and

and 0 is on.

The result of PRINT CHR$( 134) would be the graphics


charact er shown above.

Graphic to Binary Each charact er code can be though t of as a visual represe ntation
Conversion of a six-bit binary numbe r from 000000 to 111111 , corresp onding to
all 64 possible combin ations of bits. The charact er's code value can
be compu ted by translating each off pixel to a 0 and each on pixel to
a 1. Then the position s of the 1s can be masked into the six-bit

78 Chapter S Graphics
binary numbe r. The value of that numbe r plus 12S"is equal to the
code value.

-
&
---
4- - -
.
lb l8
'
···E..

Thus the graphics charac ter whose code is 134 is

£. .2. .£.. _l - ..2.. = 4-+ 2. - "


tp+lZ.~ ":. \M

and so the statem ent PRINT CHR$ (134) produc es that graphic.
symbol. The graphic charac ter whose code is 191 is the one in
which all pixels are on, resulting in a large rectangle of light. This
graphic symbo l is one of the most useful, as shown in the following
discussion.

Uses for Graphics All pictori al printe r graphic applications that have been
Characters mentio ned so far in this chapte r are fair game for these characters.
For example, the histogram application (program CSP4) requires
this line change and all LPRINTs to be changed to PRINTs to
modify the outpu t dramatically.

Otapter S Graphics
79
Program C5P4 will now produ ce outpu t like:

t reflect
Other programs can be changed very simply, and their outpu
the use of graphics characters.
Program C5P6 with the change
50 PRINT TAB<mi,lllSTRING$(D(!,2),CHRS(191 ))
yields outpu t like:

80 Chapter 5 Graphics
Program C5P9 with the modifica tion
60 PRINT ps;: FOR J=I TO L: PRINT CHRSCRND<64)t128);: NEXT J: PRINT
now produce s output like:

Cartoon ing is possible with these graphic characters. This


techniqu e requires very fast display rates, so the POKE comman ds
should be used to transfer the characte rs directly to the screen.
POKE is about six times faster than PRINT, so it's worth the effort.
To give the semblance of motion, it is necessary to display a
sequence of slightly altered pictures in rapid order. The time it takes
to plan this sequence is truly imposing.
The following program uses the characte r graphics, and its
purpose is to draw a full screen of digits on the screen very quickly.
The digits are made up of four screen position s each, so they appear
larger than normally printed characte r digits. We show you this
program and its output here to prompt you into thinking of uses for
this "enhanc ed digits" display.

Chapter 5 Graphics
81
10 'FILENAME: "C5P10"
20 'FUNCTION: PRINTS DIGITS USING CHARACTER GRAPHICS
30 ' AUTHOR : JDR DATE: 9/79
40 CLS: DEFINT A-Z: CLEAR 100! DIM II$( 10 ) initi
1 alize
50 1 comPose strin~ to linef eed, then backs Pace twice
60 E$=CHR$(26>tCHR$(8)tCHR$(8)
70 ' this loop forms all of the ten di!it s
80 FOR I=1 TO 10: AS=""
90 FOR J=1 TO 4: READ X: A$=~$tCHRS<12BtX)
100 IF J=2 THEN AS=AStE$' add LF & backsPace twice
110 NEXT J
120 D$( I )=A$: NEXT I
130 DATA 23t43 ,13t1 4,47, 0,15t 15t51 ,59,1 3,12
140 DATA 51,53 ,12,1 5,21, 48,3t 15t55 t51,1 2,14
150 DATA 53t48 ,13t1 4t3,2 7t10, 0,55, 59,13 t14t5 5t59, 0,15
160 1 Print the diSil s on the scree n randomlY
170 FOR K=O TO 62 STEP 3
180 FOR Y=K TO 896tK STEP 128
190 C=RNDC10>-1: PRINT@YtDS<Ct1);
200 NEXT Y
210 NEXT K
220 GOTO 220 1 freez e the scree n
10000 ENrt

82 Chapt er S Graphics

•· I
The outpu t of the following program shoul d look famil
iar.
This progr am's outpu t is used as the chapt er heads, or
first page
illustrations.

10 'FILENAME: "C5P10An
20 'FUNCTION: CHAPTER HEAD PROGRAM USING CHARACTER
30 GRAPHICS
I AUTHOR : JDR DATE! 10/79
A·O f.:~,NDOMi DEFINT A-·Z! CLEAR 1.00! DIM D$(1
50 0)' initi aliz e
comPose strin s to linef eed, then backsPace twice
60 ES=CHR$(26)tCHR$(8)tCHRS(8)
70 1
comPose st.rin s for s:,illtPle desis n
80 BS=CHRS( 191 )tCHRS< 191 ltEStCHRS( 143)tCHR$(143
)
90 1
this looP forms all of the ten disi ts
100 FOR I=1 TO 10: AS=»»
110 FOR J=1 TO 4: READ x: AS=AStCHRS( 128tX)
120 IF J=2 THEN AS=AStES add LF & back sPac e twice
1

130 NEXT ,J: DS( I ):."AS


140 NEXT I
15(1 ' dat.a for disi t.s 0-9
160 DATA 23,43,13,14,47,o,15,15,51,59,13~12
170 DATA 51,5 3,12 ,15,2 1,48 ,3,15 ,55,5 1,12 '14
180 DATA 53,4 8,13 ,14,J ,27,1 0,0,5 5,59 ,13,1 4,55 ,59,0
190 ' 'l5
main looP for Prin lins 10 chaP ters is below
200 FOR K=O TO 9: CLS
i10 I Prin t head ins on left. Porti on of scree n
220 PRINT@138,"CHAPTER";: PRINT@205,DS<Kt1 );
230 1
loop s to Prin t desi sns on the scree n
240 FOR I=1 TO 8! B=ABS( Iti-3 )! E=It 9-IN T(I/8 )
250 FOR J=B TO E
260 IF RNrl(3)=3 THEN PRINT@1031-128*It3t.J,BS;
270 NEXT J
280 NEXl I
290 ' looP to Prin t disi ts on the scree n
3(10 FOR ,J= 1 TO 19: R=RND< 8 )
310 B=ABS<R+R-3>! E=Rt9-INT<R/8)! S=B-1tRND<E-Bt1)
320 PRINT@1031-12B*R+3*S,D$CKtl)i
330 NEXT ,J
34(1 1
hold the scr-een befo re getti ng ne;-:i chaP ter
350 FOR 1=1 TO 1000: NEXT I
360 ' get next chaP ter
370 NEXT K
10000 END

Chapter 5 Graphics
83
' \

is
Pixel Graphics The third major techni que for programming graphic displays
ls the on-of f
pixel graphics, so-called because the progra mmer contro
ns 64 colum ns
state of every single pixel. Whereas the screen contai
the
and 16 rows of characters, wheth er they are script or graphic,
same screen contai ns six times as many pixels. There are 128
I

I columns and 48 rows of pixels, and their screen addresses are


they
radically differ ent from the addresses of the graphic characters ' ,
with X and Y
generate. A progra mmer can address a single pixel
row
coordinates, using the colum n numb ers 0 to 127 for X and the
numb ers 0 to 47 for Y.

is
SET The SET comm and turns on the pixel whose screen address
diatel y follow ing the
in X,Y coord inate form in paren theses imme
word SET.

Instr uctio n Ou tF>u t.

10 SET< OrO> UF>F>er left. Pixel is turne d on


20 SET< 2r4 > Second F>i>:el on fourt h row
30 SEH 127r47> Last F>ixel on 47th row
40 SET< Or47) Bottom left Pixel
50 SEH 127r0 > Toft risht F>ixel
60 POKE 15360r 128t21 See te>: t. be 1ow
70 SET<OrO>: SET<Or1>: SET<Or2> See text below

84 Chapt er S Graphics

l I
The last two statemen ts above have the same effect, except
that the POKE is much faster. Both light up the top left pixels like
this:

RESET The RESET comman d turns off the pixel whose screen address
is in X,Y coordina te form.

10 PRINT @0, CHR·$( 191 )


21' RESET< 1 , 0 )
rn
~
10 'FILENAME: II CSP 11"
20 'FUNCTION: SHOOT A DIAGONAL LINE ACROSS THE SCREEN
30 ' AUTHOR : JPG DATE: 6/79
40 CLS
50 FOR 1=0 TO 119: X=I: Y=I •• 4: J=I-10: K=J*.4
60 SET< x,y)
70 IF I>9 THEN RESET( J,K)
8(1 NEXT I
10000 END

The program above "shoots " a line from the top left to the
bottom right of the screen. Try it.

Chapter 5 Graphics 85
POINT The POINT function returns a zero (false) if the pixel at the X,Y
coodinate s that make up its argument is off, and a -1 (true) if that
pixel is on. Thus it is useful when testing if a particular spot is on or
off.

10 IF POINT<OfO) THEN RESET(O,O)

Pixel graphics give the programm er a true graphing capability on


the screen with 128-column, 48-row resolution. This may not be the
finest resolution you can find on the graphic terminals and
computer s, but the latter generally cost about five times as much as a
TRS-80. With pixel graphics you can draw horizonta l, vertical, and
angled lines, and even graph geometric shapes.

10 'FILENAME: "e!Pl2"
20 'FUNCTION: DF:AW A HORIZONTAL Of.: VERTICAL LINE
30 ' AUTHOR : JPG DATE: 6/79
40 CLS
50 INPUT "HORIZONTAL (l.} OR VEF:TICAL (2)"; A
60 INPUT "STARTING COORDINATE"; B
70 CLS: ON A GOTO 80,90: GOTO 50
80 FOF: X=O TO 127: SET(X,B): NEXT x: GOTO 50
90 FOF: Y=O TO 47: SET<B,Y)! NEXT Y: GOTO 50
10000 END

86 Chapter 5 Graphics
10 'FILENAME: "C5P13"
20 'FUNCTION: DRAW AN ANGLED LINE <POLAR
30 ' AUTHOR : JPG METHOD)
DATE: 6/79
4(l CLS
50 INPUT "X ANDY OF ORIGIN"i x,y
60 INPUT "ANGLE IN DEGREES"HH:
A=T H/57 .3: S=S IN(A >: C=COSCA)
70 INPUT "LEN GTH";R
80 CLS
90 ' dr·aw t.he line
100 FOR N=l TO R
110 SET<X+N*C,47-<Y+N*S))
120 NEXT N
130 GOTO 130 ' free ze Lhe scre en
1(100(l END

Chapter 5 Graphics 87
10 'FILENAME! "C5P14"
20 'FUNCTION: IIRAW ANY LINE BY CARTESIAN METHOD
30 AUTHOR : SPG
I DATE! 5/79
40 CLS: INPUT" POINT OF ORIGIN CXrY)";X1,Y1
50 INPUT " POINT OF TERMINATION (X,Y)";X2,Y2
60 CLS
70 ' switch variables if needed to reverse direction
80 IF Y2<Y1 THEN X3=X2t X2=X1t X1=X3: Y3=Y2: Y2=Y1t Y1=Y3
90 ' checks for a vertical an~le and acts accordin~l~
100 IF X1<>X2 THEN 180
110 IF Y1<Y2 THEN ST=l ELSE ST=-1 1
set steP size
120 1 looP io draw ver·tical line
130 FOR Y=Y1 TO Y2 STEP ST
140 SET <Xl,Y}
150 NEXT Y
160 GOTO 260
170 1 lakes care of all other an~les
180 M=<Y2-Y1>J<X2-X1)' calculate sloPe of ansle
190 ' set steP size
200 IF M<-1 OR M>1 THEN ST=1/M-1/(M*90) ELSE ST=SGN<M>
210 IF ST=O THEN ST=1' set steP size if M=O
220 ' draw line between Points
230 FOR X=O TO X2-X1 STEP ST
240 SET <XtX1rM*X+Y1)
250 NEXT X
260 GOTO 260' freeze screen
10000 END

88 Chapter S Graphics
10 'FILENAME: "C5P15"
20 'FUNCTION: DRAW A CIRCLE USING SINE AND COSINE FUNCTIONS
30 I AUTHOR : JPG DATE: 10/79
40 CLS
50 INPUT "RADIUS";R: INPUT "CENTER COORDINATES";Xl,Yl
60 CLS
70 FOR TH=O TO 6.3 STEP 1/R
80 X=RtCOS<TH)tX1: Y=.5*R*SINCTHJtY1: SETCX,Yl
90 NEXT TH
100 GOTO 100' freeze screen
10000 END

Chapter 5 Graphics 89
Bounci ng Dots In many games, as well as in serious graphing applications, you
will want to have a dot move in a straight directio n until it meets an
obstacle and keep moving in a new direction. Consider the possible
bounces:
Vertical Wall Collision

2.

I
I

: (')y :-iY'(
?:> --
I
4- -- -----¥--

Each moving dot changes its X directio n by an amoun t DX,


and its Y directio n by an amoun t DY. In all the conditi ons above,
the Y directio n increm ent DY never changes sign. In conditi ons I
and 2, DX starts as positive, but changes sign to negative on the
bounce .
If you investigate the four possible bounce s from a horizon tal
wall, you will find that, as expecte d, the only change is the reversal
of the sign of DY.
This underst anding is all that is necessary to graph a moving and
bouncin g dot. The dot is a pixel drawn with a SET comma nd. The
coordin ates of the SET are X and Y. The movem ent is provided with
a SET at a new positio n X+DX, Y+DY followed with a RESET of the
old dot at X,Y.

100 SET< x,y)


110 X=X+DX: Y=YtDY
120 SET( x,y)
130 RESET<X-DX,Y-DY>
:l-40 GDTD 110

90 Chapter 5 Graphics
To bounc e the dot off the wall, you must "feel" ahead to see if
any part of the surrou nding territo ry is occupied. It is not enough
to just sense the status of the next point. For example, suppose the
dot is moving up and to the right, and it encoun ters a horizo ntal wall
.
.......
···=· .
· ... Next place to be set
is already occupi ed

.· /
If the "next place" is the only point that is considered on a
bounc e, the compu ter couldn 't tell if the wall were horizo ntal or
vertical.

.....
··-·.... Next place to be set
is already occupi ed
.
·/ '
The only way to judge which directi on increm ent, the DX or the
DY, needs to change sign is to sense in all four directions.

Examples:
..... .
-:, There is something above
.~/=r:
... the dot, so reverse the sign
ofDY

Chapter 5 Graphics
91
' ;

.... ..._.....
~-
: '
'.,...} ,:.. ~. -.: There issome thing to the right of
. ..: .
\
the dot, so reverse the sign of DX
.
·/
This program bounce s a dot off any wall set up in either a
horizo ntal or vertical position. It allows DX and DY to be define d
for any value betwee n 1 and 2, and builds its walls on the four sides
of the screen.

10 'FILENAME: "C5P16"
20 'FUNCTION! BOUNCING DOT PROGRAM
30 I AUTHOR : JPG nATE: 2/80
40 INPUT "DX, DY BETWE EN 1 AND 2 INCLU SIUE";nx,DY
50 INPUT "STARTING COOR DINAT ES";x,y: CLS
60 FOR I=O TO 127 ' t..his looP dr'aws hor-izontal bound aries
70 SET<I,O>! SET<Id>: SET<I,46)! SET<I,47)
80 NEXT I
90 FOR I=O TO 47 ' draw verti cal bound aries
100 SET(O,I)! SET(1ri>t SET< 126,I )! SET<127,I>
110 NEXT I
120 SET(X,Y) I PUt. a POint. at locati on x,y
130 ' chans e direc tion of dot. if necessarY
140 IF POINT <XtDX ,Y) OR POINT<X-DX,Y> DX=-DX
150 IF POINT <X,YtD Y) OR POINT(X,Y-DY> DY=-DY '')

160 X=XtDX! Y=YtD Y! GOTO 120


10000 END

' J

92 Chapte r 5 Graphics

' i

~ ---)
Chapt er S Graphics
93
for
A very nice program that actually served as an inspir ation
one that Steve Grillo wrote as an exerc ise
the discussion above is the ns.
it "The Happ y Hopi " for obvio us reaso
in visual graphics. He calls

n :-·t:·r·J ..r-: H
1(1 I FILENAME: L-~.tr· j, 1

CREATING COMPUTER ART


30 ' AUTHOR : SPG 2/79
40 next line initi aliz es varia bles ; clea rs scree n
P=-1: CLS
50 RANDOM: CLEAR 1000: DEFSTR At DEFINT B-z: E=l:
60 CLOSE: PRINT H PRESS!"
70 PRINT " L- TO LOOK AT OLD PICTURES"
80 PRINT " M- TO CREATE NEW PICTURES"
90 A=INKEYS: IF A="" THEN 90
100 IF A="L" THEN 790
lHl user wants to crea te new art
120 CLS
130 I the next loop draws 6 random lines on the scree n
14() I (3 vert ical , 3 hori zont al)
15(l FOR T=l TO 3
160 ' set UP random varia bles
4
170 BO=RND(25>12t4: B1=BtRND(50-.5*B>*2: B2=RND(21)12t 4
C=RND(11)*2+4: C1=C+RNDC23-.51C)*2: C2=RND(6 0)12t
180
190 I draw the lines using the varia bles
200 FOR N=BO TO B1: SET(N,B2>: NEXT
21(l FOR N=C TO Clt SET<C2,N): NEXT
220 NEXT T of the dot
230 ' the next two lines initi aliz e the dire ction
240 S=INT<RND( 100 )/50>: IF S=O THEN S=-1
250 T=INTCRND(100)/50 >: IF T=O THEN T=-1 n
260 ' the ne>:t two lines draw a boundar·s ar·ound the scr-ee
270 FOR N=l TO 125! SETCN,3)! SET<N,47) ! NEXT
280 FOR N=4 TO 46! SET(l,N>: SET< 12S,N)! NEXT N
290 ' ne;d. line sive s the Poin t a star tins sPot &
300 ' makes su~e it isn' t occuPied
310 X=RN D<61 >*2+2: Y=RND<20)*2+5: IF POINTCX,Y) THEN 310
320 ' Prin t the command state men t on the scree n
330 PRINT@ l(l,"COMMAND(f',s, ,R,E ): ";
340 ,
35(1
360 ' the r-est is the main Porti on of the Prosram
370 next 4 lines chan se the direc tion if nece ssarY
380 IF POINT<Xtl,Y> THEN S=-1
390 IF POINT<X-1,Y) THEN 5=1
400 IF POINT<X,Yt1) THEN T=-1
410 IF POINT(X,Y-1) THEN 1=1
420 ' Pr-evious Poin t is blanked if P=1
430 IF P=l THEN RESETCX,Y)

94 Chapter 5 Graphics
440 next 4 lines actua llY tell the dot where to move
1

450 IF S=l THEN X=Xtl


460 IF S=-1 THEN X=X-1
470 IF T=l THEN Y=Ytl
480 IF T=-1 THEN Y=Y-1
490 next line erase s Poin t if it was white
1

500 IF POINT(X,Y) AND E=l THEN RESET(XrY) ELSEandSET(X E=l


,Y)
510 the next line check s to see if a keY was Press ed-
1

520 ' if not, then so back. to the main prosranc


530 A=INKEYS: IF A="" THEN 380
540 1
Print the lette r that was Press ed in the corne r
550 PRINT@ 3(h A¥
560 I execu te the command
570 I rever se the dot?
580 IF A="R" THEN T=-T: S=-S! GOTO 330
590 ' erase the dots train ·
600 IF A="P" THEN P=-P: GOTO 330
610I erase the dot when it runs over anoth er?
620 IF A="E" THEN E=-E~ GOTO 330
630 ' stoP the motion of the dot'!'
640 IF A<>" H THEN 670
650 A=INKEYS: IF A=•" THEN 650 ELSE 330
660 ' store the Pictu re on disk?
670 IF A<>"S" THEN 330
680 ' store the file usins random acces s
690 OPEN "R"r1r"SCRNGRPH/DAT" 1
open the file for acces s
700 FIELD 1r 255 AS BS! M=LOF(i)! I=15359 initi
1
alize
710 A=""' nulli fy AS
720 1
the next 5 lines coPY the scree n to disk
730 I=Itl
740 IF LEN<A><255 THEN 770
750 M=Mtl: LSET BS=A: PUT 1rM
760 IF M/4=INT(M/4) THEN 60 ELSE 710
770 A=AtCHRS<PEEKCil>t POKE Ir46! GOTO 730
780 ' this Porti on coPie s the art on disk
790 OPEN "R"r1r"SCRNGRPH/DAT": FIELD 1r 255 AS toBS the scree n
800 IF LOF< 1 )<>O .GOTO 830
810 PRINT "SORRYr BUT THERE IS NO ART ON FILE ... <<CR>>";
820 A=INKEYS: IF A="" THEN 820 ELSE 60
830 CLS
840 FOR C=1 TO LOF(l) STEP 4
850 FOR D=O TO 3: GET lrCtD! PRINT BS! NEXT D
860 PRINT @970, H <<CR>>";
870 A=INKEY$! IF A="" THEN 870 ELSE PRINT
880 NEXT C
10000 END

Chapter 5 Graphics
95
r 1

'.,

96 Chapte r 5 Graphics
Chapt er 5 Graphics 97
to
The last progra m produ ces graphic designs that are familiar
roses, limaco ns,
all mathe matic ians: These are variously called
to
lemniscates, or Lissajous figures, and they are not diffic ult
user to select a patter n,
produ ce. The following progra m allows the
on either the screen or
choos e its densit y, then produ ce the outpu t
includ ed a numb er of
both the screen and the line printe r. We have
examp les to show you its flexibility.

10 'FILENAME: "C5P18"
20 'FUNCTION: PRODUCE INTERESTING PATTERNS4/79
30 I AUTHOR : SPG DATE:
40 DEFINT x,y,z ,(hK
50 DEFINT K,Q, x,y,z : P2=6.283: Z=23! K=2: C=62: T=3
60 INPUT "FIRST VARIABLE ( O<X<10 )" iA .
70 INPUT "SECOND VARIABLE <GREATER THAN THE FIRST
VARIABLE)";B
80 INPUT "OUTPUT TO PRINTER <1=Y ES)"iP
)";ST
90 INPUT "DENSITY C1=SUPER DENSE, BUT SLOW; 200=SCATTERED
100 ST=ST/1000 comPute steP size
1

110 CLS
120 I creat e the Pict.ur·e
130 FOR TH=O TO P2 STEP ST
140 R=Z*SINCTHlTJ! X=K*R%COSCA*TH>+C! Y=R*SINCB*TH>+Z
15(1 SET<X, Y>
160 NEXT TH
170 IF P<>1 THEN 300' did the user want. it coPied?
180 1Print value s for two main varia bles
190 LPRINT CHRSC29)' normal Print er densitY (10 cpi)
200 LPRINT TAB<12)"First. Variable="iAi
210 LPF:INT TAB< 44 )"Second Var·i ahle=" ;B
220 LPRINT
230 LPRINT CHR$(31)' set Print er densi ty to 16.5 CPi
240 coPY the screen to the Print er
I

250 FOR Y=O TO 47


260 FOR X=O TO 123
270 IF POINTCX,Y> THEN LPRINT "*"; ELSE LPRINT " ";
280 NEXT x: LPRINT SET(Q,y)
II ":

290 NEXT Y
300 GOTO 300' freez e the scr·een
10(100 END

98 Chapter 5 Graphics
Chapte r 5 Graph ics 99
100 Chapter 5 Graphics
Graphing techniques are supremely rewarding to both the
programmer who masters them and the program user who delights
in their visual effects. They often transform a dull program into an
exciting one, and provide the user with pictures, generally known to
be worth a thousand words each. Sometimes, though, words are the
stock in trade for the computer, as in the many word processing
applications indicate. When this is the case, BASIC's ability to handle
strings is of paramount importance, and this capability makes it a
language chosen by many. String handling will be discussed in the
next chapter.

Chapter 5 Graphics 101


1/0, Strings, and As good as Level II BASIC is with its graphics and enhanc ed
Disk BASIC string handli ng capabilities, the TRS-80 Disk Operat ing System or
TRSDOS, includes some embell ishmen ts that furthe r increase the
power of the language. These additio ns to the language are
supple mental to the 12K ROM (Read Only Memory) BASIC, and
occupy RAM (Rand om Access Memory). You may refer to the
memo ry map in Appen dix C for a visual explan ation of the way
these enhanc ement s use the RAM.
This chapte r discusses the Disk BASIC features that don't deal
with tape or disk I/0, since chapte rs 7 and 8 cover those topics
thorou ghly.

DEFU SR and USRn These two language feature s are very closely related. The
DEFU SR corres ponds to a DEF FN, except that it refers to a
user-defined machin e language functio n, and the USR corresp onds
to the invoca tion of that functio n.
The DEFU SR defines the entry point to a machin e language
routin e as an address, and it also associates that routin e with a
numbe r from 0 to 9, which allows up to 10 machine language

103
routines to be called within a program.

10 DEFUSR0=32000 1 Each of the four arguments is in


20 DEFUSR1=32100 decimal (b~ default) ,
30 DEFUSR2=32200
40 DEFUSR3=32300

The four lines above could just as well have defined the machine
language subroutin e entry points in hexadecimal.
10 DEFUSRO=&H7DOO I 7DOO HEX= 32000 DECIMAL
20 DEFUSR1=&H7D64 I 7D64 HEX= 32100 DECIMAL
30 DEFUSR2=&H7DCB I 7DC8 HEX= 32200 DECIMAL
40 DEFUSR3=&HZE2C 7E2C HEX= 32300 DECIMAL
You may wish to define a machine language subroutin e's entry point
in hex depending on which way it is convenient for you to think of
addresses in the computer 's memory. In this example we have
assumed that the four programs have been loaded into the appropria te
places, and that each one is less than 100 bytes long. Note that when
BASIC is loaded and asks the question "MEMORY SIZE?" you
should respond 31999 (or less) to prevent your BASIC program from
using the area above 32000, which is the portion of memory in which
the machine language subroutin es were loaded.
The USR instructio n is really a function, and in TRSDOS
BASIC it must have a suffix digit of 0 to 9 corresponding to the
DEFUSR statemen t that specifies the entry point. There is but a
single argument to the function, and as with all functions it returns
only one value. Both the argument and the returned value are
integers.
Examples:

500 X=USR3( .J+l )


600 Y=UGF:7( F:ND( 99) )
700 Z=USl\6( -5)
If you are interested in writing an assembly language routine
that can be placed in memory for use with USR and DEFUSR , we
refer you to your local Radio Shack store, on whose shelves you will
find several books dealing with this subject. Below are some
examples of functions that could be written in assembly language
(for speed), and are therefore suited to the DEFUSR -USR approach.
(1) The argument is the screen address (0 to 1023) for the
cursor. The value returned is the length of the non blank string of
characters to the right (or left) of the cursor.
(2) The argument is a distributi on specifier for a random
variable. The value returned is a random variate of the specified
distributi on (Poisson, normal, or other).
(3) The argument is a coded musical note. Ten thousand s=
port number (1, 2, or 3). Thousand s= A toG (A= 1000, B = 2000,
etc.) Hundreds = Octave (100 =lowest, 800 =highest) . Tens= time

104 Chapter 6 1/0, Strings, and Disk BASIC


(1 = 32nd note, 2 = 16th, 3 =8th, 4 =4th, ... ). Ones= sharp (1 ),
natural (2 ), or flat (3 ). The value returned is the specified note for
the specified time on the specified port.

POS, INSTR, Although the POS function can be used with Level II BASIC
and MID$ without having to use TRSDOS BASIC, it is closely related to the
other topics of this chapter. It is a function that returns the position
of the cursor on the line, a value from 0 to 63. The argument of the
POS function is a dummy. It must be there, and can be any numeric
expression.
Examples:
10 PIHNT "A" TAB< POS( 0 HlO )"B" TAB( POS( 0 H:I.O )"C"
There will be 10 spaces between the A and the B, and 10 spaces
between the B and the C.
10 FOR I=l TO 100: INPUT XS
20 IF POS(0)tLEN<XSl>=63 THEN PRINT
30 PRINT XSt" ";
40 NEXT I
This loop reads text one word at a time and prints the words
side by side, separated by blanks. A word will not be divided
between two lines.

The INSTR function searches one string to see if it contains


another. Like the MID$ function, it can have either two or three
arguments. The function is written

INSTR(p ,stringl $,string2$)

where the optional variable p indicates the byte position at which


the search is to begin; string 1$ is the string expression being searched;
and string2$ is the string expressio n being sought.
The value returned is the starting position of the substring that
was found in the target string, or zero if it wasn't found. If the
optional starting position for the search is not specified, the search
begins at byte 1.
Instruct ion Ou t.Pu t.
----------- ------
10 AS="NOT WITH A BANG, BUT A WHIMPER"
20 PRINT INSTR(A$," " ) 4
30 PRINT INSTR( 5,A$," " ) 9
40 PRINT INSTR<AS,"A") 10
50 P~:INT INSTR( A$, J" )
II
0
60 PRINT INSTR< 4,A$,"T " ) 20
70 PRINT INSTR< A$," WITH" ) 5
80 PRINT INSTR( 2,A$," A II )
9
Chapter 6 1/0, Strings, and Disk BASIC 105
The INSTR function can simplify the neat printing of inputted
text, as in the example for the POS function .

10 ·'FILENAME: "C6F'l"
20 'FUNCTION: DEMONSTRATION OF STRING FUNCTIONS
30 IAUTHOR : JPG DATE! 6/79
40 CLEAR 3000: DIM B$(50): I=1 initial ize variab les
50 INPUT "TYPE TEXT (NO COMMAS)"; At: LPRINT AS
60 IF AS="SSEND" THEN 160 ' check for end of data entries
70 BS(I >=8$(1 )t" "+AS' concate nate old and new strinss
80 IF LEN(B$(1 ))(60 THEN 50 ' back if strins short enoush
9(l ' looP t.o find firs.t. ( r·isht.iilost.) SF'c>Ce < 60 charact er·s
100 FOR J=60 TO 1 STEP -1: X=INSTR(J,B$( 1)," II)
110 IF X=O THEN NEXT J ' keeP checkin s for a space
120 'found one. adJust. st.rinss accordinsl~, lhen so back
1.30 B$( I+l )::f'liD$( 8$( I), X )t 8$( I >~:LEFT$( F.l$( I hX)
140 I=Itl: GOTO 50
150 I Prinl lhe final COPY
160 FOR J=1 TO I: LPRINT BS<J>: NEXT J
10000 END

The Prosram which is resPon sible


for allowin s lhe user lo
modif~ a record 's conten ts
should be fairlY siruple set reauire s Sreal care in its desisn.
Consid er Lhe fields of the
record and the effect that
a chanse would have
on each of theri••
$$END
The Prosram which is resPon sible for allowin s the user to modifY
a record 's conten ts should be fairlY simPle Yet reGuire s sreal
care in its desisn. Consid er the fields of the record and the
effect that a chanse would have on each of lhem.

In the example above, notice how in line 130 the two-argu ment
MID$ function acts like a RIGHT$ function , but instead of the
numeric argumen t being a length, it is a starting position . The
INSTR can take advantage of this feature of the MID$ in a name
reversal subrouti ne, such as the one below. Compar e the following
program to program C2P5 in chapter 2. This example is typical of
many applications, such as mailing lists or accounti ng, in which the
name on a record is its key and it is arranged last name, then first
but it is used in the order first, then last name. For example , a stored
record might contain:
MINDE RBINDE R MILO
and the output should be:
MILO MINDE RBINDE R

106 Chapter 6 1/0, Strings, and Disk BASIC


10 'FILENAME.! "C6P2"
20 ,'FUNCTION: REVERSAL OF NAMES
30 AUTHOR •• JPG IIATE: 7/79
40 I
the ne>:t lines use the subr-outine
50 INPUT NS: LF'RINT N$
60 IF NS="SSEND" THEN STOP
70 GOSUB 80: LPRINT Nf: GOTO 50
80 ' the next line does the r-eversal
90 X=INSTR<NSt" •>: NS=MIDS<NS,Xtl)t" "tLEFTS(NS,X-1)
100 RETURN
10000 END

Bleam: Jo
.Jo Bleau;.:
Farnsworth Ferdinand
Ferdinand Farnsworth
Badinase Bill~bob
Bill~bob Badinase
$$END

A one-line user-defined function could do all that this


subroutine does, but it leaves much to be desired in clarity.

5 DEF FNRSCN$)=MIDS(N$,INSTR(N$," )t1) II

+" "tLEFTSOHdNSTR( N$,'' II )-1)

IN KEY$ The INKEY$ string function is a very powerful part of LEVEL II


BASIC. It does not have an argument. You can think of it as a
single-character input function that doesn't need an enter keystroke.
When the INKEY$ function is executed, it ''strobes", or scans, the
keyboard checking for a depressed key. If no key is depressed, the
string returned is a null string, "". If a key is depressed, the string
returned is that keystroke, even if it is a control key such as the
backspace or the ENTER key. Because the keyboard scan occurs so
fast, when INKEY$ is executed it must be given multiple
opportunities to execute in order to find .. a key that is depressed. For
this reason the INKEY$ is always placed inside a loop.
Example:

100 XS=INKEYS: IF XS="" THEN 100


110 PRINT @ 960,xs;

Chapter 6 1/0, Strings, and Disk BASIC 107


This program segment strobes the keyboard repeatedly. When a
key is depressed, the keystroke isn't null, X$ isn't "", so line 11 0 is
executed and prints that character at the bottom of the screen. Note
the ";"punctuation at the end of the PRINT@. Remember that it
keeps the carriage/cursor from returning so that what was printed on
the bottom line stays on the bottom line without the standard
single-line scrolling of the screen.

100 X$=INKEYS: IF X$="" THEN 100


110 PRINT~ o, ASC<XS>;xs;: GOTO 100
When a key is depressed the ASCII code value for the depressed
character is printed at the upper left, immediately followed by the
character itself.

100 PRINT "TYPE JUST DIGITS"


110 XS=INKEY$! IF X$="" THEN 110
120 IF XS<"O" OR XS>u9" THEN PRINT "ERROR": GOTO 100
130 PRINT ~ o,xs;: GOTO 110

The two following subroutines might seed a fertile mind with


ideas for other uses of their capabilities.

10 ;FILEN~d1Ei "C6P3" ' \

20 'FUNCTION! USING INKEYS FOR NUMERIC VA~IABLES


30 AUTHOR : JPG
I DATE: 7/79
40 ' routine lo test the inPut subroutine
50 CLS! PRINT "TYPE AN INTEGER VALUE <O=STOP)"
60 GOSUB 1000! PRINT: PRINT A
70 IF A=O THEN 10000
80 GOTO 80
1000 subroutine to Pl~ce ~n ~11-disit Positive value
1

1010 1 into a strins <AS>


1020 AS="n null the slrinS
1

1030 XS=INKEYS: IF XS="" THEN 1030 w~it for Pressed keY


1

1040 IF XS=CHR$( 13) THEN A=VAL(A$)! RETURN /EN/ KEY? I

1050 m~ke sure keY is a disit, then add slrinss & So back
1

1060 IF X$>="0" AND X$<="9" THEN


AS=AStXS! PRINT @ 512,As;: GOTO 1030
1070 ' Print error messase <AS not lesal keY) and So back
1080 PRINT @ 576'"***ERROR*** -- SO FAR YOU HAVE _n;As;
1090 GOTO 1030
10000 ENil

108 Chapter 6 1/0, Strings, and Disk BASIC

I I

I !
10 FILENAME! "C6P4"
I

20 'FUNCTION! FLASH A PROMPT WHILE KEYING IN A STRING


30 ' AUTHOR : SPG DATE! 1/80
40 ' test the subroutine
50 P$=" NAME: " ' this wi 11 be flashed on the screen
60 GOSUB 1000: PRINT: PRINT: PRINT N$
70 STOP
80 ' subroutine to flash a PromPt for strins inPut
90 • Note:
100 • I i~ a dummY timinS variable which is
110 I chansed as necessarY to Keep the PromPt
120 • flashins at a fairlY constant rate while the
130 1 strins is beins tYPed in.
1000 CLS: I=JO 1
maKe sure PromPt sets Printed soon
1010 X$=INKEY$! IF X$="" THEN 1050 'wait for Pressed KeY
1020 IF ASCCXS>=13 RETURN • leave routine if done enterins
1030 1 add strinss and Print the strins on the screen
1040 NS=NStXS! PRINT@ 135,NS;: I=It3
1050 I=Itl ' increment the timins variable
1060 ' Put PromPt on screen0& reset timer if necessarY
1070 IF I>=20 THEN I=O: PRINT @ 128,P$f
1080 • blank out the PromPt if it is time to do so.
1090 IF I>7 AND I<13 PRINT@ 128, STRINGSCLENCP$)," ");
1100 GOTO 1010
10000 END

LINE INPUT The commonly used INPUT command is quite flexible, but it
has its limitations. You can't input commas or quotes, and if you
try to input a string with leading blanks, BASIC does you the
questionable favor of eliminating them to shorten the string. Also,
a question mark is printed on the screen every time the INPUT is
executed, sometimes leading to awkward~looking displays.
The LINE INPUT command overcomes all of these difficulties
at the minor expense of being able to input only one variable at a
time, which must be a string. Probably the most useful feature of
the LINE INPUT results from the fact that if you input a null string
(hit the ENTER key) it is inputted, whereas this action is ignored
during the usual INPUT operation.
The following examples should serve to show the power of this
very useful command.
Assume this statement is executed:
10 LINE INPUT "TYPE A LINE! ";xs: PRINT XS: GOTO 10
Study this dialog to see how the LINE INPUT works.
(The /EN/ signifies the ENTER stroke).

Chapter 6 1/0, Strings, and Disk BASIC 109


TYPE A LINE! 79r282.44/EN/
79r282.44
TYPE A LINE: HE SAID, "HI!"/EN/
HE SA In, HI!"
11

TYPE A LINE: CENTERED TITLE/EN/


CENTERED TITLE

The next program segment illustrates a useful feature of LINE


INPUT: it accepts a new value as input, even if a null string is
entered. Note that the INPUT statement cannot accept a null string.
If a null string is INPUT, the previous INPUTted value is used.

10 INPUT AS: IF AS="" PRINT "NULL A" ' tYPe ABC (no outPut>
20 INPUT BS: IF BS="" PRINT "NULL B" ' tYPe DEF (no outPut)
30 INPUT AS: IF AS="" PRINT "NULL A AGAIN"
ELSE PRINT LENCA$);AS tYPe "", outPut is 3 ABC
40 LINE INPUT XS! IF XS="" PRINT "NULL X" ' tYPe XYZ (no outPut)
50 LINE INPUT YS: IF YS="" PRINT "NULL Y" ' tYPe RST Cno outPut}
60 LINE INPUT XS: IF XS="" PRINT "NULL X AGAIN"
ELSE PRINT LEN<XS>iXS ' tYPe "", outPut is NULL X AGAIN
' \

This feature of the LINE INPUT is quite useful in file editing.


In the example below, the array X$ contains the names, street
addresses, city, state, zip code, and phone numbers of some data that
is on file, and this subroutine allows the user to update the data.

10 'FILENAME! "C6P5"
20 'FUNCTION: MORE EXAMPLES OF USING LINE INPUT
30 I AUTHOR : JPG DATE: 9/79
40. CLEAR 1000: DIM XS<20r6>'•ake lots of room for strinSs
50' XS(ld) is nau.e XS(I,2) is street X$(I,3> is cit!:l
60 ' X$( h4} is zip X$( 1,5) is state X$( I r6} is Phone
70 ' main Prosram besins here
80 N=3! GOSUB 100! GOSUB 100: GOSUB 100
90 STOP
100 ' subroutine for uPdate of records
110 FOR J=l TO 6! READ PS(J): NEXT J! RESTORE
120 FOR I=l TO N!CLS! FOR J=l TO 6
130 PRINT @64*JrP$CJ), XSCirJ);
140 LINE INPUT AS! IF AS<>"" THEN XS<IrJ)=A$
150 NEXT Jri! RETURN
160 nATA NAMEtSTREETtCITY,STATE;ZIPrPHONE
10000 END

110 Chapter 6 1/0, Strings, and Disk BASIC

I •!
The LINE INPUT in the subroutine uses an ENTER stroke on
the keyboard as an indication that there is no change in the filed
data. Otherwise, the user types in the new information and it
replaces the old information in the array.

MID$ for Our previous encounter with MID$ showed it to be a powerful


Replacement function that would extract one string from another.
For example, if A$= "ABCDEFG" the statement:
XS=MHI$( A$,4,2)
copies the two characters of A$, starting at the fourth, into X$.
With Disk BASIC, the MID$ function can disobey the usual rule
that functions must appear to the right of the equal sign. If MID$
appears to the left of the equal sign, it is a replacement function
instead of an extraction function. It copies any portion of the string
to the right of the equal sign into the string argument of MID$
beginning at the position specified by the middle argument for the
length specified by the third argument.
SuPPose XS="ABCDEFGH"

Instruction Ou lPu t

10 MIDS(X$,4,2)="XY": LPRINT XS ABCXYFGH


20 MIDS(X$,1,5}="12345": LPRINT XS 12345FGH
30 MIDSCX$,6,1}="XYZ": LPRINT XS ABCDEXGH
This function is powerful in text editing programs. The example
below searches the 64-character string X$ for the specified target
string T$. If T$ is found in X$, it is changed to the new version N$.
For example, the string might contain a line of text and the user
could change an occurrence of the misspelled word "COERTION"
to the proper spelling "COERCION".
:1.0 ' FILENAME: C6F'6"
II

20 'FUNCTION! TO SUBSTITUTE WITHIN A STRING


30 ' AUTHOR ! JPG DATE! S/80
40
50CLEAR 200! CLS
60 DIM X$(20}
70 DATA "anteloPe elund dikdik imPala sazelle serenuk"
80 DATA "couser t.iser lion leopard Jaguar lwnx"
90 FOR I=l TO 2
95 READ XS<I>! PRINT XS< I)! GOSUB 1000
100 NEXT I! GOTO 10000

Chapter 6 I/0, Strings, and Disk BASIC 111


1000 '***** subroutine to substitute
1010 LINE INPUT "l~Pe tarset strins: ";Ts
1020 LINE INPUT "t~Pe new (replacemen t) strins: ";N$
1030 IF LENCNS>>LENCTS> THEN PRINT ntoo Ions": GOTO 1020
1050 FOR .J=1 TO LEN< X·:li( I ) ) ; P=!NSTRC ..h J:·H I J, T·~~)
1060 IF P<>O THEN MIDS<XS( I ),P>=NS
1070 NEXT .J! PRINT X$( I 1
1080 ~:ETURN
10000 END

anteloPe elund diKdiK imPala sazelle serenuK


t~Pe tarset strins: elund
l~Pe new (rePlacemen t) strins: eland
anteloPe eland dikdik imPala sazelle SerenuK
couser tiSer- lion leoP<wd j;::;Suar· 1\:m;.:
lYPe tarset sLrins: couser
tYPe new (rePlacemen t) strins: cousar
cousar tiser lion leoPard Jasuar lwnx
READY

TIME$ TIME$ is a variable that is defined by the computer when it is


turned on and Disk BASIC is loaded. If this statement is executed:
500 PF:INT TIME$
the output is the system date and time. That is, whatever date and
time was typed in when TRSDOS was initiated is displayed as

MM/DD/YY HH:MM: SS

This 17-character string is initialized automatically to

00/00/00 00:00:00

if the TIME and DATE DOS commands were not used to accurately
set the internal clock and calendar.
The TIME$ string is useful in two very important application
areas. First, the date portion can be used in programs for account
ageing, proper billing, inventory reorder, and all the other business
applications that require action on particular dates. Second, the time
portion can be used by a.programmer for timing program loops and
user responses. The two programs below illustrate this use.

112 Chapter 6 1/0, Strings, and Disk BASIC


10 I FILENAME: "C6P7"
20 'FUNCTION: TIMING OF ARITHMETIC OPERATIONS
30 'AUTHOR JPG DATE! 12/79
40 I

50 DEFSNG A-Z
60 'add=l, sub=2, mul=3, div=4
70 CLS! FS="Z % Z % % % % % % Z"
80 GS="ttlitti tit tti Iii tit"
90 LPRINT USING FS; "NO. OPS","ADD","SUB","MUL","DIV"
100 'iterations are 100 to 1000 in stePs of 100.
110 'note that each iteration contains 10 oPerations.
120 FOR I=10 TO 100 STEP 10
130 S=O! K=1.012321t GOSUB 500: T1=T
140 FOR J=1 TO I: S=StK! S=StK! S=S+K! S=S+K: S=S+K
150 S=StK: S=StK! S=StK: S=StK! S=StK
160 NEXT J! GOSUB 500! TA=T-T1! T1=T
170 FOR J=1 TO I! S=S-K! S=S-K! S=S-K: S=S-K! S=S-K
180 S=S-·K! S=S-K: S=S-K: S=S·-1(! S=S-K
190 NEXT J! GOSUB 500! TS=T-Tl! T1=T
200 FOR J=1 TO I! S=S*K: S=S*K: S=S*K! S=S*K! S=S*K
210 S=S*K! S=S*K! S=S*Kt S=S*K: S=S*K
220 NEXT J! GOSUB 500! TM=T-T1! T1=T
230 FOR J=1 TO I! S=S/K! S=S/K! S=S/K! S=S/K! S=S/K
240 S=S/Kt S=S/K! S=S/K! S=S/K! S=S/K
250 NEXT J! GOSUB 500! TD=T-T1
260 LPRINT USING Gs; r,TA,TS,TM,TD
270 NEXT I
280 STOP
500 'subroutine returns the lime in seconds
510 H=VAL<MIDS<TIME$,11,1))!' isolate hours
520 M=VAL<MIDS<TIME$,13,2))!' isolate minutes
530 S1=VAUMHIS<TIMES,t6,2)):' isolate seconds
540 T=S1+M*60+Ht3600t RETURN
10000 END

NO. OF'S ADD SUB MUL rnv


10 1 0 1 ...'i
20 1 2 1 3
30 2 2 3 3
40 3 3 3 5
50 3 4 4 5
60 4 4 5 6
70 4 5 6 7
80 5 5 7 9
90 6 6 7 10
100 7 7 B 11

Chapter 6 1/0, Strings, and Disk BASIC 113

' '

1 . I --- ~- ,-··-'I- -- -~ -- --
10 'FILENAME: "C6PB"
20 'FUNCTION: SIMPLE MATH PROGRAM USING TIMED INPUTS
30 ' AUTHOR ! JPG DATE! 7/79
40 DEF FNTCA,B>=VALCMIDSCTIME$,A,B))
50 CLS
60 ' tin,e user- r-esponse~. t..o 10 seconds or less
70 A=RNDC100)! B=RNDC100)
80 PRINT @ 520r A;"t";B;"=" i
90 GOSUB 170: Tl=T: YS=""
100 XS=INKEYS! IF XS<>"" THEN 130
110 GOSUB 170: IF T-T1<10 THEN 100
120 PRINT! PRINT "SORRY --OUT OF liMEn: GOSUB 210: GOTO 70
130 IF ASCCXS><>13 THEN YS=YStXS! PRINT@ 534,ys;; GOTO 100
140 C=VALCYS>: PRINT
150 IF C=A+B THEN PRINT "CORRECT!!"
ELSE PRINT "SORRY, THAT IS INCORRECT."
160 GOSUB 210: CLS: GOTO 70
170 I TIMING SUBROUTINE
180 H=FNH11d)t M=FNT<1:h2H S=FNTC16,2)
190 T=StM*60+H*3600! RETURN
200 ' hold scr-een for- a few seconds, then ~o back
210 FOR I=l TO 400! NEXT I: RETURN
100•j(l END

32 + 80 =
SORRY -- OUT OF TIME

114 Chapter 6 1/0, Strings, and Disk BASIC

l ._1
If you need more accurate timing of a routine or of a response
from a user, you may access the running clock of the computer from
BASIC by PEEKing at (decimal) addresses 16448 through 16450.
Try this program to test this feature.

10 'FILENAME! "C6P9"
20 'FUNCTION: USE COMPUTER AS STOPWATCH CTO lOOTHS OF SECONDS>
30 IAUTHOR : SPG DATE! 7179
40 CLS: M=16450: 5=16449: P=16448 'clock locations in memory
50 INPUT "TYPE 'ENTER' TO BEGIN";As
60 set orisinal timins values
70 CLS: M1=PEEKCM>: Sl=PEEK<S>: P1=PEEKCP>
80 INPUT "PRESS /EN/ AGAIN TO STOP THE TIMER";AS
90 ' set final t.i111ins values
100 M2=PEEKCM>: S2=PEEKCS>: P2=PEEK<P>
110 ' comPute the elaPsed lime
120 E2=M2*15300tS2*255tP2: El=M1*15300tS1*255tP1
130 PRINT:PRINT
140 ' chanse the ti111e to seconds
150 ET = CE2-E1 }/255
160 ' Print the elaPsed lime in seconds
170 PRINT USING "ELAPSED TIME WAS ABOUT ttt.tt SECONDS";ET
10000 END

This chapter has explored a number of niceties that Radio


Shack's TRS-80 provides the programmer. These features give a
flexibility to BASIC that tends to make it more acceptable as a
language to be used in most application areas. But it is the ability to
deal with files that makes BASIC particularly useful in business,
education, scientific, and home applications. The file handling
capabilities of the microcomputer will be discussed in depth in the
next chapter.

Chapter 6 1/0, Strings, and Disk BASIC 115


' '

' J
Sequential Access The next three chapters will differ from those that have gone
File Processing before because they cover the BASIC commands, statements, and
functions that deal with cassette and disk files. This chapter will
cover the subject of sequential files on tape and on disk.

Commands for
Program Files

SAVE, CSAVE Files on tape or disk can be either programs or data, and in most
instances both kinds of files will reside on a given medium. When a
program is stored on disk or tape, it is copied directly from memory
onto the medium as a whole. The command to do this is CSAVE for
a tape file and SAVE for a disk file. The name under which the
program is stored is written within quotes immediatel y following the
SAVE or CSAVE command. The names of programs stored on tape
are limited to a single character, but the names of programs on disk
can be from one to eight characters long, as discussed in the TRSDOS
manual. Just remember that the SAVE command does not store data

117

-,
files, just program files. The SAVE command can store a program on
disk in ASCII character format by placing a comma and the letter A
following the file name.

LOAD, CLOAD The reverse of the program saving process takes programs
stored on disk or tape and copies them into the computer's memory.
The commands that effect this transfer are LOAD for disk programs
and CLOAD for cassette tape programs. The file name must be
specified for a disk load. If the file name is not specified for a tape
load, the computer will load the first program it encounters on the
tape.

KILL, RUN Disk BASIC has three more commands that manage program
files. The KILL command is used to delete a file from the disk. It
is the same command that TRSDOS uses (see Appendix E for a list
of all TRSDOS commands), except that the file name must be
enclosed in double quotes. The RUN command can be used to run
the program in memory, or in Disk BASIC it can be used to load a
specified program, then run it. In Disk BASIC the LOAD command
can also copy the named program into memory and run it if the
command endswith a comma and the letter R.
Examples:

10 LOAn "PROG1" Disk BASIC command within a Pro~ram.


After loadins the prosram, the comPuter
returns to the command mode <>READY>.

20 RUN "PROG4" Load the nanted Prosralll fro111 disK and


besin its execution.

30 LOAn "PROG4",R This effect is identical to line 20.


LOAD "PROG2" Load the Prosr ant frorr, contntand Rtode.
RUN "PROG3" Load the Prosramt then run it.

LOAD "F'ROGJ",R This command is identical to RUN


"f'ROG3".
SAVE "PROG5" Save the Prosram in memorY to disk
under the name "PROG5".
KILL "PROG6" Delete the file called "PROG6• from
the diskette.
Save the Prosram in memorY to cassette
under the name "B"•

118 Chapter 7 Sequential Access File Processing


I '

CLOAD "X" Load the Prosr-an, "X" fr·on, cassette io


RtelitOf"!:lt

CLOAD Load ihe next Pro!ram on the cassette t.o


lltelllor!:l.

RUN
SAVE "PROG6",A Save the Prosran, in ntemor·'::! ont.o disK
in ASCII (character) format., one record
Per line.

MERGE This command combines a program in memory with a program


on disk. The program on disk must have been SAVEd in ASCII
format with a SAVE "filename",A command. The result of the
combination is left in memory. The MERGE command meshes
together, or merges, the two programs according to their respective
line numbers. If the disk program has a line number that is not
present in the memory version, that line is added to the memory
version. If the line number is present in both versions, the line from
the disk version replaces the line in memory.
Examples:
Assume the disk file's name is "TESTSUB", and the command
is MERGE "TESTSUB"

Memory Disk Result in memory


lOA lSB lOA
20A 25B lSB
30A 20A
25B
30A

Memory Disk Result in memory


lOA 30B lOA
20A 40B 20A
30B
40B

Memory Disk Result in memory


lOA 20B lOA
20A 30B 20B
30A 40B 30B
40B

The MERGE command is nice for adding commonly used


routines to various programs. For example, suppose you have a good
sorting subroutine that is numbered from 1000-1999. You can

Chapter 7 Sequential Access File Processing 119


MERGE it into a number of programs without having to reenter it
line by line in each program.

Commands for Data files are entirely different from program files. For this
Data Files reason very few commands work for both kinds of files. The KILL
command is one of the few exceptions that doesn't discriminate. It
can delete both program files and data files.
A data file is a collection of records. Each record is a related
set of data. For example, you could have a data file of rainfall for a
given year. There might be 12 monthly rainfall records, each one
containing between 28 and 31 data values for the daily rainfall. Or
maybe there would be 52 weekly records, each with 7 daily data
values. You could even arrange the data to be hourly (if needed) so
that each of the 365 records contains 24 values. It is the
programmer's decision to arrange the data and records. The
commands that manipulate data files are of two types: Either they
deal with the entire file as a unit, or they manipulate records one at a
time. You have already seen the KILL command, which deals with
the entire file.

OPEN, CLOSE The records on a disk data file are inaccessible unless the file is
opened for use. Also, some records on a file may be lost if that file
is not closed when processing is complete.
The OPEN command has two primary functions:
(1) It identifies the mode of the file. That is, the OPEN
statement prepares the file for (a) input, in which records
can be transferred sequentially from file to memory;
(b) output, in which records can be transferred sequentially
from memory to file; and (c)random> in which the transfer
can occur in either direction. ...
(2) It associates the name of a file with a file number, so that
commands using the file need only refer to its number once
the file has been opened.
The OPEN commandh{ls the format:'

OPEN rri$,q,filena111e$ \
' ' ',!

where m$ is either "I" -for input mode, "0" for output mode, or
"R" for random access mode. The next chapter, which
discusses direct !lCcess files, will cover the case when(m$,is "R~'.
n is a numeric expression from 1 to 15; which is the number
that the program uses to refer to the file. filename$ is a
standard file name.
Once the records on a file have been read, written,or modified,
the file must be closed. The command

CLosE,;~
closes thefile numbered n. The CLOSE command can have more

120 Chapter 7 Sequential Access File Processing


than one argument separated by commas, or it can be just the word
CLOSE. In the latter case, all opened files are closed.
When a program deals with tape files, OPEN and CLOSE
commands are not used.
Examples:

10 OPEN "I",1,"INVEN/DAT" The fil~ called I~VEN/DAT is


OPtnieQ__for__~JlPUi. It. J.~, file :U.
20 CLOSE 2 /- The file numbered 2 is OPened for
30 OPEN ~0" ,2, "MASTER''-·// outPut. If (he old file :1:2 (the
one that ~as closed) was called
MASTER, it j.s no l.onser ac·eessible
for- im:.-u t \

40 CLOSE
50 CLOSE 1,2,3
60 CLOSE: OPEN •J",15,"ACCRCVB/DAT"
70 INPUT "FILE NAME"iFS! OPEN "I",2,FS
BO INPUT nMODE";Ms: OPEN Ms,S,"MASTER2"

Sequential File Sequential files, whether they are on cassette tape or floppy
INPUT and PRINT disk, are accessible with only two commands that actually read or
write records once the file is opened. They are the INPUT # n. If
n is -1, the cassette drive is accessed, otherwise n must be between
1 and 15 inclusive, and it corresponds to the file number that was
assigned with the OPEN statement.
Two variations to the INPUT and PRINT are available for
record input and output. These are the LINE INPUT# and the
PRINT#, USING. The formats of the two statements are:

INPUT# n, vl, v2, ...

LINE INPUT # n, v 1, v2, ...

PRINT# n, vl, v2, ...

PRINT# n, USING f$; vl, v2, ...

With the LINE INPUT # statement, there can be only one string
variable name following the command.
Examples:
50 INPUT t-l,A,Bs,c
60 PRINT t-l,AiBs;c;x
70 PRINT t4,X$;","iM$;"f"iJ
BO LINE INPUT tl,VS
.90PRINT tJ, USING "tf# ttt$.t";x,y
Chapter 7 Sequential Access File Processing 121
Command File medium File transfer Variables

INPUT# n, ... disk file to string and


memory numeric

PRINT#n, ... disk memory string and


to file numeric

INPUT# -1, ... cassette file to string and


memory numeric

PRINT# -1, ... cassette memory string and


to file numeric

LINE INPUT # n disk file to one string '\


memory only )

PRINT # n, USING ... disk memory any,


to file formatted

Table 7.1 Sequential File Commands

The following pro.gram illustrates first the output of numeric


variables to cassette tape, !hen the input from that same tape.

10 'FILENAME: "C7P1"
20 'FUNCTION: STORE A NUMERIC MATRIX ON TAPE
30 I AUTHOR : JPG DATE.: 8/79
40 JU1t_}:_(_3Q,__5j_~_ define n,at.i~i>: as 30 elen,ent.s b!:! 5 elen1EHils
50 'fill matrix with random values from 1001 to 9999
60 FOR 1=1 TO 30: FOR J=1 TO 5
70 X<I,J>=RND<8999lt1000: PRINT X(I,J>;: NEXT J,I
80 ' ,now store t.he n.atri>: on t.ar-e . -
90 PRINT "Rewind the taPe and set Past the leader,"
J0-0-1Nf'Ul'litum-press/EN/" ;,AS
110 FOR i:1--Trr10·--------
120 PRINT I-1,X(IdHX(Ir2)jX(I,3HX(I,4·HX(l,5)
130 NEXT I -
140 INPUT "Rewind asain, Press Play, then Press /EN/";As
150 FOR I = 1 TO 30: INPUT t-1, A,B,c,n,E
160 PRINT ~REC t"; I,"CONTAINS";A;B;c;n;E
170 NEXT I
10000 EN[I/

122 Chapter 7 Sequential Access File Processing


The next program represents a disk-based game that uses a
sequential file called "GEOG/D AT". The point of the game is to
challenge the computer in a dialog to see if the computer 's "memory "
contains the name and descriptio n of a geographical location that the
player knows.
The program uses a data structure that is known as a binary
tree. Each record has two elements of string informati on, the name
of the geographical location, and the characteristic that distinguishes
it from the previously reached location. Each record also has two
pieces of numeric informati on, YES and NO links to further
locations. Thus each record has four fields.

Variable Field Type Description


name length

L1 4 Numeric YES links, 0 to 999

L2. 4 Numeric NO links, 0 to 999

AI$ Not limited String Location name


Q$ 240-len(A$) String Distinguishing
characteristic

Table 7.2 GEOGRA PH Record Layout

The program "learns" new geographical locations and their


characteristics from the player. It starts the play with the question,
"ARE YOU THINKING OF A GEOGRAPHICAL LOCATIO N?"
There are five possible responses:
1. A YES response elicits a very specific location, for example,
"IS IT LAKE ERIE?"
2. A NO response is refused, and the computer displays the
message, "YES, LIST, SAVE, OR DEBUG". Later on in
the game, a NO response elicits a very general characteristic,
for example, "IS IT A LAKE?".
3. DEBUG displays a table of links, locations, and
characteristics. It is used onl)' for debugging purposes.
4. LIST displays all locations that the computer "knows".
5. SAVE transfers all records, both those that were initially
loaded into memory from the file, and those that the
computer "learned" during the play.

Chapter 7 Sequentia l Access File Processing 123


Consider the sample dialog below:
ARE YOU THINKING OF A GEOGRAPHICAL LOCATION? YES
IS IT A LAKE? NO
IS IT A MOUNTAIN? YES
IS IT MT. POPOCATAPETLT NO
IS IT IN AFRICA? YES
IS IT MT, KILIMANJARD? YES

I THOUGHT SO. .._,rr·


ARE YOU THINKING OF A GEOGRAPHICAL LOCATION? i r:. ;:~

IS IT A LAKE? YES
IS IT LAKE ERIE? NO
IS IT IN EUROPE? NO
WHAT WAS THE PLACE YOU WERE THINKING OF? LAKE TITICACA
TYPE A CHARACTH~ISTIC ~JHICH WOULD DISTINGUISH LAt\E TITICAC~,
FROM LAKE GENEVA
? IS IT IN SOUTH AMERICA
ARE YOU THINKING OF A GEOGRAPHICAL LOCATION?
Table 7.3 shows the contents of a file record by record after
one typical session of this game.

Record# Al$ Q$ L1 L2

1 LAKE ERIE IS IT A LAKE 4 2


2 MT. SHASTA IS IT A 6 3
MOUNTAIN
3 CINCINNATI WHAT ABOUT A 7 999
CITY
4 LAKE IS IT IN SOUTH 4 5
TITICACA AMERICA
5 LAKE GENEVA IS IT IN EUROPE 5 9
6 MT. EVERES T IS IT IN ASIA 8 999
7 WASHINGTON IS IT A CAPITOL 7 999
8 MT, FUJI IS IT VOLCANIC 8 999
9 LAKE MEAD IS IT DAMMED 9 999
10 END END 0 0

Table 7.3 Example Record for GEOGRA PH

This table can be represent ed as a binary tree structure,


which indicates how the two links L1 and L2 tie the array
together.

124 Chapter 7 Sequentia l Access File Processing


Figure 7.1 GEOGR APH Binary Tree Structur e

10 'FILENAME! "C7P2"
20 'FUNCTION! GEOGRAPHY QUIZ GAME
30 I AUTHOR : JPG DATE: 6/79
40 'OS=ch aracler istic, A1$=localion name' AS=lemPorar~ slrin~
50 L1=lef t link,
1
L2 =· risht link, N =number of Places
60 DEFINT I-N: CLEAR 2000: DIM Q$(50) ,A1$(50 ),L1(50 ),L2C5 0)
70 1
set UP first record if needed
80 INPUT "DOES THE DATA FILE EXIST";A$ -
90 IF ~~S<>"YES" THEN CH•: 1 )::"IS IT A LAKE" t L:U 1 )::1 :L2C 1 )=9'7'9t
N=l: A1$(1)="LAKE ERIE": G01D 1BO
100 ' sel all filed sites·
110 CLOSE 1! OPEN "I '1' GEOG/DAT" t I:-;() .
li II

120 I=I+l: INPUT t1, (H;(Ih L1(IhA l$(lhl. 2(I); PRINT l·r ; I
130 IF 0$( I )<>"END" THEN 12(r
140 N=I-1! INPUT "/CR/"; A$
150 IF N>50 THEN PRINT "C A R E F U L THt1N 50! !I

160 I

170 I ne;-:l Place


180 CLS: INPUT "ARE YOU THINKING OF A LOCATION";A$
190 IF AS="LIST" THEN K=l
200 IF AS="YES" THEN K=2
210 IF AS="DEBUG"THEN K=3
220 IF AS="SAVE" THEN K=4
Chapter 7 Sequent ial Access File Processing 125
230 ON K GO SUB 270 'i 300 '~ 600, 630
240 IF K>O AND K<5 THEN 180
250 INPUT "YES'~ LIST, SAVE, OR DEBUG /CR/"; As: GOTO 180
260 "LIST" ROUTINE
270 PRINT "THE PLACES l KNOW ARE •••"
280 FOR 1=1 TON: PRINT Alt<I> ,: NEXT I
290 INPUT ./CR/" jA$ t RETUF:N
II

300 I "YES"J the Plaser is thinki ns of a Place


310 I=l
320 PRINT QS(l)i : INPUT AS
330 IF AS="YES" THEN 410
340 IF AS<>"NO" THEN 320
350 NO, not the listed chara cteris tic so if ri!hl linK
360 is null, use il -- otherw ise 5et new site's detail s
J7(l IF L2(I)( )999 THEN I;:::L.2( I )t GOTO
ELSE GOSUB 54(1
380 1 set UP all linKs and set a new locati on
390 L2( Il=Ntl : GOSUB 580: RETURN
400 ask if this is the correc t chara cteris tic
410 PRINT "IS IT ";AlSC I);; INPUT AS
420 IF AS<>"YES" THEN 460
430 ' Yes' the comPu ter suesse d it (Print the messaS e)
440 PRINT! PRINT! PRINT "••• I THOUGHT SO."
450 FOR X=l TO 400! NEXT x: RETURN
460 IF AS<>"NO" THEN 410
470 ' set next locati on if left linK isn~l null
480 IF I<>Ll( I) THEN I=LlCI>: GOTO 320
set the new locati on's detail s
500 GOSUB 540
510 1 set UP all new linKs and set ne;.;t locati on
520 LlCI )=Ntl: GOSUB 580: RETURN
530 I DIALOG
540 INPUT "WHAT WAS THE PLACE YOU WERE THINKING OF";A$
550 PRINT "TYPE A CHARACTERISTIC lhal WOULD DISTINGUISH "
560 PRINT AS;" FROH ";Alt (l): INPUT QlS: RETURNJ
570 ' new locati on links
580 N=Nt1!Q$(N)=Q1$tA1S<N>=AS:Ll(N)=N:L2(N)=999:RETURN
590 "DEBUG" routin e -- disPla Ys all linKsr data
I

600 PRINT" I Q$( I) A1 $(I) LH I) L2( I l"


610 FOR I=l TO N:PRINT I;Q$( I ),Al$( I hLH I );L2( I ;:NEXT l
620 INPUT "/CR/";As: RETURN
630 "SAVE" routin e
1

640 PRINT "REC.t"i: CLOSE 1: OPEN "O"rlr"GEOG/DAT"


650 FOR I=l TO N
660 PRINT U,QSCI);",";.uciH"r"~AliCI)i"r"iL2Cil
670 PRINT I;: NEXT I
680 PRINT tl,"END,";o;"ENDr";o
690 INPUT "/CR/";As: RETURN
10000 END

126 Chapte r 7 Sequen tial Access File Processing


The following program demonstrates two software techniques.
One of these, the Sheil-Metzner sort, is also used in a later chapte
r.
The other technique, that of merging two sequential files, is the
primary reason for including the program here.
The program has three parts. Part 1 creates a numb er of files,
that numb er determ ined by the user, and all files are of the same
size, again determined by the user. Part 2 sorts each of the files
in
memo ry, then rewrites the files in sorted order. Part 3 merge
s all
the files into one which is in sorted order.
Since the program's purpose is to demonstrate a technique
rather than to produ ce outpu t for some more useful reason, the
outpu t that follows the listing should be considered in that light.
The first part of the outpu t shows three unsor ted files. The secon
d
part shows those three files, each in sorted order, The last part
shows the single file that results from the merge operation. Note
that this sorted outpu t could not have been produced nearly
as
quickly had the sort been condu cted any other way.
10 'FILENAME: "C7P3"
20 'FUNCTION: SORT~MERGE OF SEQUENTIAL FILE
30 I AUTHOR : JPG DATE: 11/79
40 CLEAR 20001 DEFINT A-z: CLS: DIM NS(50l
50 JS=" ttt% % ": JS=JStJStJS
60 INPUT •How RtanB files " ;NF
70 INPUT "How manY entri es will be in each file"i SIZE
80 INPUT "File SrouP name";F$
90 PRINT "O=Shuffle l=Cre ate 2=Edit. 3=Sort"
95 INPUT "4=Merse 5=Stop"; Y
100 ON Ytl GOSUB 110,1 70,23 0,320 ,480: GOTO 90
110 ' shuff le the entri es in all of the
120 FOR W=1 TO NF: FLS=FStRIGHTSCSTR$(W),1) files
130 K=11 GOSUB 630
140 FOR J=1 TO SIZE: A=RNDCSIZE>: B=RND<SIZE>
15Q T$=N$(Al: N~A>=NS<B>: N$CB~Tt: NEXT J
155 LPRINT "File "; FL$; " in orisi nal orde r."
160 GOSUB 670: N=SIZEI GOSUB 720: NEXT w: RETURN
170 ' creat e the files
180 FOR W=l TO NF: FLS=FHRIGHT$( STR$CW h 1 )
190 FOR J=1 TO SIZE: PRINT "FILE t";w; ", ENTRY t";J;
200 INPUT N$(J): NEXT J: PRINT
210 K=l: GOSUB 670 ' write out names on file
220 NEXT w: RETURN
230 ' edit entri es withi n a file
240 FOR W=l TO NF: FL$=FHRIGHTS(STR$(W)d) v·
250 PRINT "INPUT FILE IS ";FLS: K=l: GOSUB 630' read
260 FOR J=l TO SIZE
270 PRINT N$( J), TAB< 30)," :";
280 INPUT NE$: IF LEN< NE$ ><>O THEN N$( ,J >=NE$
290 NEXT J
300 GOSUB 670 ' write out edit~d file
310 NEXT w: RETURN
Chapt er 7 Sequential Access File Processing 127
320 I sinsl e file sor· i
330 CLS! FOR W=1 TO NF: FLS=FS+RIGHTSCSTRSCW)v1)
340 K=1: GOSUB 630 read .the file
370 M=SIZE
380 M=INTCM/2)! PRINT Mit IF M=O THEN PRINT! GOTO 440
390 K=SIZE-M! J=1
400 I=J
410 L=ItH: IF NS( IJ<=NS(L) THEN 430
420 H=NSC I H NS< I J=NSC L )! N$( L J=Ht I=I--H
425 IF I>=l THEN 410
430 J=Jt1 ! IF J<=K THEN 400 ELSE 380
440 LPRINT "File "; FLS; " in sorte d order ."
450 N=SIZE! GOSUB 720 ' Prin t the sorte d file
460 K=1! GOSUB 680 1 write out sorte d file onto dis~
470 PRINT! PRINT! PRINT! PRINT: NEXT W! RETURN
480 ruerse the files
490 PRINT "ReG uires ";NF tli"fi les /EN/"! LINE INPUT AS
oPen file
500 LPRINT "Mersed file 'NEW'."! OPEN "O",NFtl,"NEW" '
510 FOR W=l TO NF! OPEN "I",WvFStRIGHT SCST RSCW ),l)
520 INPUT tw, NSCWJ! K<W>=l! NEXT W
530 CN=O! 5=0! PLUGS="ZZZZZZ"! GOSUB 590
540 PRINT tNFt1,SMALLS;","i!CN=CNt1!PRINTCNOTO i! KtMJ=KCMJt1
550 IF KtM><=SIZE INPUT tH,NS<M)tG OSUB 590!G 540
560 NS<M>=PLUGS!S=Stl!IF S<NF THEN GOSUB 590!G OTO 540
570 PRINT!CLOSE!SIZE=SIZE*NF!K=NF tl!FLS ="NEW ":GOS UB 630
580 N=SIZE! GOSUB 720! SIZE= SIZE/NF! RETUR N
590 1find the smal lest of NF strin ss
600 SMALLS=PLUGS W
610 FOR W=1 TO NF! IF NS<W><SMALLS THEN SMALLS=NSCWJ!M=
620 NEXT W! RETURN
630 1 load a data file from diske tte ' }

640 OPEN "I",K,FLS


650 FOR J=1 TO SIZE! INPUT tt\,N$(,JH NEXT ,J
660 CLOSE! RETURN
670 ' save a data file- on disK ette
680 OPEN "O",K,FL$
690 FOR J=1 TO SIZE
700 PRINT tK, N$( .J HII' II;
710 NEXT J: PRINT: CLOSE: RETURN
720 1 Print a file from memorY
730 Nl=INT<N/3): FOR J=l TO Nl
740 LPRINT USING J$jJ,NS(J),JtN1rNS(JtN1 ),Jt2*N1,NS<Jt2*N1J
750 NEXT J: LPRINT: RETURN
10000 EN[t

128 Chapter 7 Sequential Access File Processing


File testl in oriSin al order.
1 SAL HIA TELL Y 5 GNASHGNAT NATHANIE 9 MINDERBINDER MILO
2 FISTULA FELICITY b PONTltiC Ci~f~:LO 10 ANOMALY ANTHONY
3 BEL.LEF: ELLERY 7 SITHLE SIBILANT 11 LAVORIS MORRIS
4 HEGIRA IRA 8 PA~~SLEY PELVIS 12 Ut)ULA U~~SULA

File . .,.,
L85t..Lin or isinal order·.
1 LANCASTER BAfn 5 GROMMET ANDfWMEDA 9 SIDDHARTHA GHAUTI'\f'l
.:.. SITHLE SIMEON
'1
6 CUERVO CERVESA 10 ALIQUOT ALICE
3 PARVENU MARVIN 7
t10NACO MONICA
I 11 VERMIFORM VERNON
4 ASININE ARNOUt 8 POWER CYCLONE 12 LOOSELIF'S LINDA
File iesi3 in orisin al or·der.
1 GABLE MARK 5 LANCHESTER ELSIE 9 RUBELLA ELLA
2 SITHLE SAMANTHA 6 PATELLA PETER 10 HARSHBARGER HERSCH
3 ENEMA ANOMIE 7 MERGER MARGINAL 11 BANDERSNATCH FRUMI
4 MUSHMOUTH MUNGO 8 SITHLE SYBIL 12 ANOMALY ANNABELLE
File testl in sorted or·der.
1 ANOMALY ANTHONY 5 HEGIRA IRA ? PONTIAC CARLO
2 BELLER ELLERY 6 LAVORIS MORFUS 10 SALI tJA TELL Y
3 FISTULA FELICITY 7 MINDERBINDER MILO 11 SITHLE SIBILANT
4 GNASHGNAT NATHANIE 8 PARSLEY PELVIS 12 UVULA URSULA
File tesi2 in sorted order·.
1 ALIQUOT ALICE 5 LANCASTH: BART 9 POWER CYCLONE
2 ASININE ARNOLD 6 LOOSELIPS LINDA 10 SIDDHARTHA GHAUTAM
3 CUERVO CERVESA 7 MONACO MONICA 11 SITHLE SIMEON
4 GROMMET ANDROMEDA 8 PAR!)ENU MARVIN 12 VERMIFORM VERNON
File test3 in sorted order.
1 ANOMALY ANNABELLE 5 HARSHBARGER HERSCH 9 PATELLA PETn:
2 BANDERSNATCH FRUMI 6 LANCHESTER ELSIE 10 RUBELLA ELLA
3 ENEMA ANOMIE 7 MERGER MARGINAL 11 SITHLE SAMANTHA
4 GABLE MARK 8 MUSHMOUTH MUNGO 12 SITHLE SYBIL
Mersed file 'NEW'.
1 ALIQUOT ALICE 13 HARSHBARGER HERSCH 25 PATELLA PETEr.:
2 ANOMALY ANNABELLE 14 HEGIRA IRA 26 PONTIAC CARLO
3 ANOMALY ANTHONY 15 LANCASTER BART 27 POWER CYCLONE
4 ASININE ARNOLD 16 LANCHESTER ELSIE 28 RUBELLA ELLA
5 BANDERSNATCH FRUMI 17 LAVORIS MORRIS 29 SALIVA TELLY
6 BELLER ELLERY 18 LOOSELIPS LINDA 30 SIDDHARTHA GHAUTAM
7 CUERVO CERVESA 19 MERGER MARGINAL 31 SITHLE SAMANTHA
8 ENEMA ANOMIE 20 MINDERBINDER MILO 32 SITHLE SIBILANT
9 FISTULA FELICITY 21 MONACO MONICA 33 SITHLE SIMEON
10 GABLE MARK 22 MUSHMOUTH MUNGO 34 SITHLE SYBIL
11 GNASHGNAT NATHANIE 23 PARSLEY PELVIS 35 UVULA URSULA
12 GROMMET ANDROMEDA 24 PARVENU MARVIN 36 VERMIFORM VERNON

Chapte r 7 Sequen tial Access File Processing 129


The last program in this chapter illustrates the use of sequential
ASCII files in one very common and necessary application, the
renumbering of a BASIC program. It contains many advanced
BASIC programming features, such as variable dimensioning, input
and output mode sequential files, MID$, and INSTR.

10 'FILENAME: "C7F'4"
20 'FUNCTION: RENUMBER DISK BASIC PROGRAMS FROM BASIC
30 ' AUTHOR : SPG D1HE: 1/13/79
40 CLEAR 1000: DEFINT A-Z
50 CLSt PRINT: PRINT
60 PRINT "KeeP the follow ins in mind when usins this Prosram:"
70 PRINT " a. Your Prosram must alread~ be saved on"
80 PRINT " disk in ASCII format. "
90 PRINT" b. The Prosram on file can't contain "
100 PRINT 11 the follow ins t~Pe of line:"
110 PRINT II IF X=Y 100"
120 PRINT " Chanse all such lines to:"
130 PRINT " IF X=Y THEN 100"
140 PRINT " c. An~ Prosram stateme nts within a strins"
150 PRINT " will be renumbered."
160 PRINT " (E>:antPle: 10 PRINT 'GOTO 240' )"
170 PRINT: PRINT "/EN/" ;
180 TS=INKEYS: IF TS="" THEN 180
190 CLS: PRINT: PRINT
200 PRINT " After this Prosram is finishe d renumberins"
210 PRINT "your Prosram, the new renumbered version will"
220 PRINT "be under the file name RENUM/DAT"
230 PRINT
240 PRINT " If at an~ time, this Prosraru is sloPPed before"
250 PRINT "the complete renumberins~ Your Prosram will still"
260 PRINT "be saved under its old file name (this Prosram"
270 PRINT "doesn 't chanse sour Prosraru at all; it creates a"
280 PRINT "coruPletelY n.ew file)."
290 PRINT: PRINT "/EN/"
300 Tf=INKEYS: IF TS="" THEN 300
310 CLS: PRINT: PRINT
320 PRINT • How mans lines are in the Prosram that You"
330 INPUT "want renumbered (aPProximately)";M
340 M=Mt20: DIM Bl(M), B2(M)
350 INPUT "What should the new line increme nt be";x
360 INPUT "What should the first line number be";y: Y=Y-X
370 IF Y<O THEN PRINT ">>>E rror<< < Trw asain": GOTO 350
380 INPUT " What is the name of the Prosram";Bs
390 OPEN "I",1,B S

130 Chapter 7 Sequent ial Access File Processing


400 set UP arrays Bl (old line Is) and 82 (new line Is)
1

410 K=Kt1: PRINT K;


420 IF EOFCl) THEN CLOSE: PRINT: GOTO 460
430 LINE INPUT Jl,A$
440 B1<K>=VALCLEFTS<AS,INSTRCA$," ")-1>>: B2<K>=K*X+Y: GOTO 410
450 1
OPen both files
460 OPEN KI",1,BS: OPEN "0",2,"RENUM/DAT"
470 1
main routine immediatelY below
480 D=Dtl
490 POKE 14305,1 keeP disk drive on durins renumberins
I

500 IF EOFC1) THEN 10000


510 LINE INPUT t1,AS: GOSUB 580 read and chanse a line
1

520 1
save &. Print the line, then so back for another·
530 PRINT t2,AS: PRINT AS: GOTD 480
540
550 I* * * *routine
* * * *to* *chanse
* * *the* *line
* * *number
* * *of* *a *line* * * * *
560 1
* and chanse all reference numbers followins commands *
570
580 I* * GOSUB
H=1: * * * 830 * * * *the* *line
* * * chanse 1 * * *number
* * *of* *this* *line
* * * **
590 ' skiP the remark lines
600 IF INSTR<A$," >>O AND INSTRCA$," ><7 THEN RETURN
1 " 1 "

610 IF INSTR<ASr"REM" ))0 AND INSTR<Af,"REM" ><7 THEN RETURN


620 RESTORE reset the data Pointer
I

630 'data of lhe list of commands to check for


640 DATA GOTO,GOSUB,THEN,ELSE,DONE
650 set next command
1

660 1
if done, check for ON ••• GOT0 s and ON ••• GOSUB's
1

670 READ NS: H=1: IF NS="DONE" THEN 760


680 H=INSTR(H,AS,N$) is lhe command in lhe line?
1

690 IF H=O THEN 670 if not, then so back to set next command
1

700 1
N$ was found in the line!
710 H=H+LEN(N$) H is where the next Possible line number is
1

720 IF VAL<MIDS<AS,H))=O THEN 680 not a number after NS


I

730 GOSUB 830: GOTO 680 chanse the number after NS


1

740 1
subroutine to chanse the numbers in all
750 1
"ON ••• GOTO ••• 's and ON ••• GOSUB ••• ~s
760 H=INSTR< A$,'' ON" )
770 IF H=O THEN RETURN ON not found, so so back
1

780 1
if no COIT•n•as, then chanses alr·eadB done. retur·n
790 H=INSTR(H,A$,"," )tl: IF H=l THEN RETURN
800 1 chanse the line number afler the comma, and check ~ore
810 GOSUB 830: GOTO 790
820 I routine lo chanse first line number after H in AS
830 FOR R=H TO LENCAS>: IF MIDSCAS,Rvl)=" "THEN NEXT R
840 H1=R
850 FOR R=Hl TO LENCAS>: Tl=ASCCMIDSCAS,R))
860 IF T1>47 AND T1<58 THEN NEXT R
870 V=VALCMID$(A$,Hl,R-H1 )) ' Vis lhe line number

Chapter 7 Sequential Access File Processing 131


880 ' chec~ to see if V is a valid line number
890 FOR T=l TO M
900 IF V=Bl<T> THEN 940
910 NEXT T
920 GOSUB 950: RETURN ' nol a valid line f
930 ' west a ~ood t. chanse the number and return
940 A$=LEFT$CAStH1-1>tMIDSCSTRSCB2(T)),2)tMIDSCAS,R)! RETURN
950 ' error traPPin~ subroutine, not found line number
960 PRINT: PRINT: PRINT
970 PRINT" I'm sorrY' but I can't find"
980 PRINT "line t";v;"anYwh ere in the Prosraru.
990 PRINT
1000 PRINT "It is referenced in this line!"
1010 PRINT AS! PRINT
1020 PRINT 0 These are You choices at this Point!"
1030 PRINT " 1. Continue, leaving this line as it is (or)
1040 PRINT " 2. StoP execution of this renuruberins Prosraru"
1050 PRINT
1060 INPUT n Which do YOU want me to do";J
1070 IF J=O THEN RETURN
1080 PRINT "O.K., Your Prosraru is unchansed under Lhe old"
1090 PRINT "file name of ";as;"."
1100 PRINT
1110 PRINT "Press /EN/ and I will delete the other unneeded»
1120 INPUT "file";Ts
1130 KILL •RENUM/DAT"
10000 END

Sequential files are useful in applications that require the


processing of most or all of the records on the file. Also, sequential
files must be processed one record at a time in their physical order,
and that severely limits the use of this method of file management.
In the next chaptoc, you will discover the advantages that direct
access file processing can offer.

132 Chapter 7 Sequential Access File Processing


~- _ 1 __ , _ _ _ _ 1_ _ _I _ _ _ _ j _ _ I __ _

Direct Access A comp uter witho ut the ability to manage files is just a glorifi
File Processing ed
calculator. Can you imagine the tedium of retypi ng the same
long
program every time you want to run it? Programming and files
go
togeth er, because the impor tance of saving them, then having
the
comp uter be able to load them directly into memo ry, increa
ses as the
programs get larger and more sophisticated. But sequential
files are
at times rather cumbe rsome . Their struct ure dictat es that on
the
average half of the file must be read to find a desired record
, even if
its positi on in the file relative to all of the others is known .
Direc t access files allow the progra mmer to read from or writ~
to any one of the records on the file witho ut any interm ediate ;
read
or write operations. This is the reason for the access metho d
having
the name "direc t access". If one specific record is desired and
its
positi on is know n, you can issue a comm and in BASIC that
fetches
the record witho ut any unnecessary inputs of other records.
The
savings in time alone make direct access file processing a tempt
ing
metho d of data management. This chapt er will review the
programming techni ques used for input and outpu t of data on
a
direct access storage device, specifically the TRS-80 mini-floppy
disk.

133
Figure 8.1 TRS-80 Disk Drive

FIELD A programme r using sequential access techniques on a disk file


is not concerned with the length of the record in a PRINT #
statement. Put another way, the logical record (the set of related
data items in the PRINT#) can vary in length; when the system
calculates that over 256 bytes of records are ready to be stored, it
writes out a physical record (one complete sector of bytes) to the
disk.
When a program uses direct access (also called random access)
files, the output statement PUT does the actual transfer of
information from memory to the disk. Contrary to the system doing
the transfer as in sequential processing, the programme r is responsible
for this operation. The record that is PUT onto the disk is again a ''I

256-byte physical record. However, the logical record size is also


determined by the programme r and it can be as large as 255 bytes.
The purpose of the FIELD statement is to define the layout
of the 255-byte record to TRSDOS, the operating system. Not all
255 bytes need to be defined, but in every case the FIELD statement
starts in the first byte of the 25 5-byte physical record.
With direct access file processing, the program prepares a special
area of memory called the sector buffer, or just buffer, 255 bytes at a
time. Data transfer to the disk is a three step affair: First, the buffer
is described with the FIELD statement, then the variables in memory
are placed in this buffer by using the LSET and RSET statements, and

134 Chapter 8 Direct Access File Processing.

~· J

k )
Ix~
I
CJ~~ \{Q
\
I
I '' \
) ME:Mo{Z..'(
'' !Jt-
I
1..
..... ..... DR>"/" '' \ I
.....
.......... ,
''' I
\
I
I
LSE::I
0~
I
',
., ' -, '' I
I I K_SE:T
''
t
I
\ I
I \
' I

II I I Bu~~
')(!$ !.$ ~ J\$ \1~

P1..H
',
'
''
' \
I

I
r
l
PH'ISlc.AL R.ccoi2.D,..
/ :i :SE.C-TO fL {)C:. lJts)C

Figure 8.2 Schemat ic of Data Transfer to Disk

last, the entire buffer is copied onto the disk with the PUT
comman d. Figure 8.2 illustrate s this three-ste p transfer.
Note that the variable names in memory and the buffer are
differen t in figure 8.2. This is because they are physical ly located in
two differen t places.
The format of the FIELD stateme nt is:

FIELD fn, lenl AS varl, len2 AS var2, ...

The FIELD describes the buffer in all of these ways:


1. (fn) File number or specifier, as defined in the OPEN
statemen t, from 1 to 15. fn is any numeric expressi on,
such as 1, 2, ... , 15, A, X, I*2, ...
2. (len 1) Length of the first field, in bytes.
3. (varl) Name of the first field, any legal Level II BASIC
variable name.
4. (len2, var2, len3, var3, ... ) Lengths and names of all
subsequ ent fields in the 255-byte buffer. The sum of all
lengths (len 1 + len2 + ... ) cannot exceed 25 5, but it can be
less.

Chapter 8 Direct Access File Processing 135


Examples:

500 FIELD 1, 255 AS NS


The entire buffer of File #1 is just one field, a string 255
bytes long. Suppose the program has OPENed file #1,
then the FIELD statement above is executed, then a
specific record is read into the buffer with a GET (to be
discussed later). Then the program has available for
inspection and processing the 255-charac ter string N$.

500 FIELD 2, 40 AS X$, 8 AS II$, 100 AS .J$

The buffer for File #2 is partially used, with only 148


bytes of the 255 bytes being fielded as three variables X$,
D$, and J$. D$ might be an 8-byte double precision
numeric variable stored as a string to conserve space. See
the discussion on the conversion functions in this chapter.
Note that all data fields that are described in the form of
strings: Each integer value is fielded as a 2-byte string,
each single precision value as a 4-byte string, and each
double precision value as an 8-byte string, compared to
sequential files, in which the value 1.23456789 012345
takes up 18 bytes, including the leading and trailing blanks.

FIEUI K, 32 AS N$( 1 h 20 AS S$( 1 ) , 12 AS C":li( 1 )


500
510 FIELD 1(, 64 AS B2$, 32 AS N'$( 2), 20 AS S$( 2 ) ' 1'1.:.. AS C${ 2)
520 FIELD 1(, 128 AS B3S, 32 AS N$( 3 h 20 AS SS< 3 ), 12 AS C$( 3)
530 FIELD 1(, 192 AS B4$, 32 AS N$( 4 h 20 AS S$( 4 ), 11 AS C$( 4)

This series of statements describes a single 255-byte buffer,


but each statement is responsible for one fourth of the
record. Since 255 is one less than 64*4, the last FIELD
statement cannot describe 192+64, but only 192+63. This
layout is shown in figure 8.3.
Nd\ I)E.\0-'I).)t()
I N~(l)
32.
1 S$.(1)
z..o
IC$())1
12. '-'+ I <.'I' I.A·
~<S\ Dtf-WC.D
~(Z..) ~s~<.z..")
e.z.$
b'-1- 32. U>
ld!z.)l
IL fo'+ I 1.'+

~~ No\ t'>Ef.!to:l6D
rJ:t.(?.) Is.~(.?.) 1~(3~,
I ~2. u, 12.
IV!. ""'"
t-11.(<\-~
I~~
~(.-.+)
-e.~ I
?.<.. t.o II
,q-z..
Figure 8.3 255-Byte Buffer Description by Four FIELD Statements

136 Chapter 8 Direct Access File Processing

l ,J
The fields B2$, B3$, and B4$ are dummy fields that will not be used.
Their purpose is to reposition the location of the first fields N$(2),
N$(3), and N$(4) further down the buffer. The four statements
could also have been written as a single statement:

500 FIELD t;;, 32 AS N$( 1h 20 AS S$( 1 h 12 AS C$( 1 h


32 AS N$( 2h 20 AS S$( 2), 12 AS C$( 2),
32 AS N$( 3)' 20 AS S$(3), 12 AS C$(3),
32 AS N$( 4h 20 AS S$( 4 h 11 AS C$( 4 )

The dummy field must be used to describe some buffers whose


item-by-item descriptions would exceed the 256 byte limit on the
length of BASIC statements. For example, suppose you wish to
store 125 two-byte integers on each record. You have to field the
array so that it would look like this:

X$(1) X$(2) X$(3) X$(4) X$( 125) (unused)


2 2 2 2 2 5
You cannot write this as a single statement:

500 FIELD 1, 2 AS X$(1 ), 2 AS X$(2), •• +

because that statement would be more than 1000 characters long


without any blanks! But this little program segment can do it:

100 FOR I=1 TO 125


110 FIELD 1, ( I-1 )*2 AS f.l$, 2 AS X$( I}
120 NEXT I

This program segment describes the 125 different fields for


2-byte integers in the buffer. The variable D$ is a dummy variable,
whose sole purpose is to displace the location of the FIELDed
integer two bytes further down the record.

GET The GET statement transfers the information from a record on


disk to the buffer in memory. It uses just two arguments, and one is
optional. The form of the GET statement is:

GETfn
or
GET fn, rn

The fn is a numeric expression that corresponds to a value from I to


15, indicating the file number. The rn is an optional numeric
expression that corresponds to the record number, from 1 to the last
255-byte physical record number. If the record number is not
specified in the GET, the next record on the file is read and its

Chapter 8 Direct Access File Processing 137


contents are transferred to the buffer.
Examples:
100 GET 1, 2
Copy the contents of the second record on File #1 into
the corresponding buffer.

100 GET 2, ,J

Copy the Jth record to the buffer for File #2.

10(> GET r;, U:3


The record number is L *3 and its contents are copied to
the buffer of File #K.

100 GET 3, LOF( 3)

Get the last on file (LOF) record from File #3. See the
discussion following.

LOF The LOF function returns the number of the last physical
record of the file specified by its argument.
Examples:
20 IF X<LOF<l) THEN GET 1,X
If the value of X has not reached the file's limit, read the
Xth record.
50 PRINT "FILE";J;"HAS";LOF(J);"RECORD~"

LSET and RSET The variables that are specified in a FIELD statement are in the
sector buffer, which is a location different from the other variables in
the program. They are not alterable in the same way that ordinary
string variables in memory can be modified by BASIC. For example,
in the sequence of statements below, the record that is written back
onto the disk is completely unaltered, because line 130 affected some
strings in ordinary memory whose names were the same as those in
the buffer.

100 OPEN "R",l,"TEST"


110 FIELD 1, 10 AS X$, 20 AS Y$, 30 AS ZS
120 GET 1 d
130 SS=XSt"ABC": YS=YSt"DEP": ZS=ZS+"GHI"
140 PUT 1,1

138 Chapter 8 Direct Access File Processing

l J
To transfer informati on to the buffer from memory you must
use one of two instructio ns, the LSET or the RSET. These
command s transfer strings to the fielded buffer. LSET left justifies
a string in memory into a fielded string variable, and RSET right
justifies a string in memory into a fielded string variable.
Examples:
10 FIELD 1, 5 AS ASr 6 AS BSr 7 AS CS
2(lLSET A$="ABC"
30 JS="XYZ": LSET 8$=J$
40 LSET CS="ABCDEFGHIJ"
The result is:

ABC .. XYZ ... ABCDEFG


A$ B$ C$

where the periods represent blanks.


Note that all strings are left justified in their fields, and that
in the case where C$ was fielded, the string being placed in the
buffer was truncated to the right.

PUT The output statemen t for direct access files is the PUT. Like
the GET, it has two argument s, the file number and the physical
record number, or sector number, with the last being optional. If
the record number is omitted, the record in the buffer correspon ding
to the file number is written at the current record number position.
Examples:
l.O(l PUT 1, 4
Write a record into the fourth position of File # 1.

100 PUT L, .J-1

Write a record into the J-1 position of File #L.

100 PUT 5, LOF(5)t1

Write a record on File #5 just past the end of the file.

100 PUT 5

Write a record into the current record position of File #5.

100 FIELD 1r 255 AS A$


110 GET 1, N: A1S=AS: GET 1JP
120 PUT l,N: LSET AS=AlS: PUT 1rP

Switch the contents of the Nth and Pth records of


File #1.

Chapter 8 Direct Access File Processing 139


MKI$, MKS$, When numeric values (constants, variables, or expressions) are
and MKD$ fielded into a direct access file buffer, they must be converted to
strings. Integer values are converted to two-byte-long strings with
the MKI$ function, single precision values are converted to four-byte
strings with the MKS$ function, and double precision values are
converted to eight-byte strings with the MKD$ function. It may
help to think of these functions as "MaKe Integer String", "MaKe
Single precision String", "MaKe Double precision String".
Examples:

10 FIELD 1, 2 AS XIS, 4 AS XS$, 8 AS XDS


20 XS=MKISCX): LSET XIS=XS
30 LSET XSS=MKS$(3.27)
40 LSET XDS=MKDStPlt)

Line 10 fields the File # 1 buffer to store three strings of two,


four, and eight bytes.
Line 20 first converts the value X to a two-byte string X$,
assuming the value of X lies between -32768 and +32767 inclusive,
else an error would occur. Note that if X is not an integer, its
fractional value is dropped, in effect converting X to an integer.
Then line 20 transfers the string X$ to the two-byte field XI$. After
this conversion to string, either the LSET or RSET instruction can be
used, since the two-byte string fits exactly into its two-byte buffer
space.
Line 30 converts the single precision value 3.27 to a four-byte
string and transfers it directly into the file buffer.
Line 40 converts the double precision value at PI# into an
eight-byte string directly into the file buffer.
If this statement were executed
50 LSET XDS=MKl$(5)
the two-byte string equivalent to the integer value 5 would be
transferred into the leftmost two bytes of the eight-byte buffer
field called XD$. Not only would this waste space, but it would ' 1

make the subsequent proper reconversion of XD$ toits original


value of 5 extremely difficult.
To show you the advantage of these three conversion functions
in saving space, compare the storage space used in two possible
cases:
(1) three values, -32767, -2.71828E- 14, and
.:3.141592653589793 are stored as strings of characters,
each character representing a single digit;
(2) the same three values are converted with the MKI$, MKS$,
and MKD$ functions to two, four, and eight byte strings.

140 Chapter 8 Direct Access File Processing


c 1

> I

r .,

I ·I
Case 1 : Conversion to character strings, then storage in the
buffer.

10 FIELD 1, 6 AS IS, 12 AS S$, 18 AS DS


20 LSET U=STRS< -327 67)
30 LSET S$=STRS(-2.71828E-14)
40 LSET DS=STR$(-3.141592653589793)

The result is:

-32767-2 .71828E- 14-3.1415 92635897 93


6bytes 12bytes 18bytes

In case 1, the total amount of record space used to


store these three values is 36 bytes.

Case 2: Represen tation of values as direct copies of memory


storage.

10 FIELD 1, 2 AS I$, 4 AS ss, 8 AS DS


20 LSET IS=MKI$(-32767)
30 LSET S$=MKSSC-2.71828E-14)
40 LSET DS~MKD$(-3.141592653589793)

The result is:

I$ S$ D$
2 4 8

In case 2, the total amount of record space used to


store the same three variables to the same accuracy
is just 14 bytes, a saving of more than 150%.

CVI, CVS, and CVD When a direct access record is read into a buffer with a GET,
the numeric values are most likely in 2-, 4-, or 8-byte string form as
a result of MKI$, MKS$, or MKD$ functions. These strings are not
printable, and they are not convertible with a VAL function. The
functions that are used to reverse the process of the MKI$, MKS$,
and MKD$ functions are CVI, CVS, and CVD, the ConVert to
Integer, Con Vert to Single precision, and Con Vert to Double
precision. They take two, four, and eight byte buffer fields and
convert the strings to numeric values.

Chapter 8 Direct Access File Processing 141


Examples:

510 FIELD 1, 2 AS NS, 8 AS X$, 4 AS AS


520 GET 1,L
530 AZ=CVH NS)
540 B=CVS( AS )
550 CJ=CVD< X$)
560 PRINT Ai.,B,Ct

In the program segment above, the buffer is described as having


· three strings, N$, X$, and A$. Line 520 fills that buffer with the
ftrst 14 bytes of the Lth record. Then lines 530-550 produce three
numeric values A%, B, and C# that correspond to the strings N$, A$,
and X$.

Direct Access The steps involved in creating a direct access me are more
File Creation involved than those used in creating sequential access files because
the programmer is responsible for opening the me, converting values
to strings, filling the buffer, and finally writing the record. The order
of these steps is important, so they are listed below, in the order in
which they must appear in the program.
1. Open an existing file or open a new file, entering its name in
the TRSDOS directory (in effect creating it).
OPEN "R",n,"file name"
2. Describe the records of the file with the FIELD statement.
FIELD n, lenl AS varl $, len2 AS var2$, ...
3. Load the buffer with just strings.
LSET varl $=exp
or
RSET var 1$=exp
4. Write the record at the desired location.
PUT nfile, nrec

A complete program may best serve as an example of the


process. Suppose the problem is to create a direct access file called
MASTER containing this information: amount owed (AM$), date
of last purchase (PU$), date of last payment (PA$), and amount of
last payment (AL$). Table 8.1 supplies the buffer field information.
Since each one of these logical records is less than half the length
(256 bytes) of each physical record, it would be economical to
include two logical records for each physical record. To allow for
possible growth ofthese records to include more fields, we can start
the second logical record half way down at byte 129 of the 25 5 byte
buffer.
Once the file has been opened and its buffer described, the user
can enter information starting where the file ends,

142 Chapter 8 Direct Access File Processing·

l )
Length Name Descript ion

24 NA$ Custome r name


20 SA$ Street address
26 CZ$ City-stat e-zip
12 PH$ Phone No. (ARC-EX C-DDDD )
4 AM$ Amount owed (single precision )
2 PU$ Date of last purchase
(integer, coded MMDDY)
2 PA$ Date of last paymen t
(integer, coded MMDDY)
4 AL$ Amount of last paymen t
(single precision )

94 bytes total

Table 8.1 Buffer Field Informa tion

10 'FILENAME: "CBPl"
20 'FUNCTION! DIRECT ACCESS ACCOUNTS RECEIVABLE FILE BUILDER
30 ' AUTHOR! JPG DATE: 2/80
40 CLEAR 200! CLS! N=O
50 ' open t.he file for· f'<mdom access inPut./out.Put.
60 OPEN "R"Y1,"MASTER"
70 ' de·fine t.he use of t.he l:.~uffer ar-e<>.
80 FIELD b 24 AS NA$( 1 ), 20 AS SA$( 1 ),
26 AS CZ$( 1 h 12 AS PH$( 1 h
4 AS AM$( 1 ), ,_ AS Pll$( 1 ),
"')

"')
1.. AS PA$( l ), 4 r,:;
Ar·· AL $( 1 )
9•) FIELD AS D$, 24 AS NA$( 2 h 20 AS SA$( 2)'
1 ' 128
26 AS CZ$(2), 12 AS PH$( 2 h
4 AS AM$( 2), 2 AS F'U$( 2 h
...
"')
AS F'fiH 2 h 4 AS AL$( 2)
100 GOSUB 600' clear- the disk buffer-
110 ' skiP t.he next. section if the file doesn't . exist Yet
120 IF LOF(1)=0 THEN 200
130 deter-mine what the value of N should be
140 N=( LOF( 1 )--1 >»:2+ 1! GET 1 d. OF< 1 )
15() ' incr·eritPn t. N and clear- the buffer if
160 the second sub-rec or-d is not. bl<>.nK
170 IF ASC<NA$(2>><>32 THEN N=Ntl: GOSUB 600
180 incr-ement. N (logica l r-ecord number)
190 ' 2-nd find I <the sub-rec ord Pointe r)
200 N=Ntl~ I=INT(N/2)*2-Nt2
210 LINE INPUT "NAME <TYPE 'END' TO STOP>: ";N$
220 ' if that's all' save this record, then end
230 IF NS<>"END" THEN 290

Chapter 8 Direct Access File Processing 143


240 ' if this record hasn 't been writte n wet, do so now
"")f.:"~
~~·.. ,J\f IF I=2 THEN GOSUB 500
260 close UP the file' then stop
270 CLOSE: GOTO 10000
280 otherw ise, begin fillin~ the buffe r with text
290 LSET NAS(I)=NS
300 LINE INPUT "STREET ADDRESS! ";As: LSET SASCI>=AS
310 LINE INPUT "CITY-STATE-ZIP: ";As: LSET CZSCI>=A$
320 LINE INPUT "PHONE NO.: "; AS: LSET PHS<I>=A$
330 INPUr "AMOU NT OWED"; A: LSET AMSCI>=MKSSCA)
340 INPUT "DATE LAST PURCHASE <MMD DY)";A: LSET PUSCI>=MKISCA)
350 INPUT "DATE LAST PAYMENT CMMDDY)";A: LSET PASCI>=MKI$(A)
360 INPUT "AMT LAST PAYMENT"iA: LSET ALS<I>=MKSS(A)
370 I if 2nd sub-r ecord , save that recor d,
380 • then clear the disk buffe r and return
390 IF 1=2 THEN GOSUB 500: GOSUB 600
400 ' !o back for anoth er record from the user
410 PRINT: PRINT: PRINT: GOTO 200
420 ' save the buffe r onto disk
500 PUT l,INT<<N-1 )12>+1: RETURN
strai~ht
510 • this looP clear s the buffe r to keeP lhin~s
600 FOR ,J:::l TO 2
610 LSET NASCJ~"": LSET SAS(J)=""t LSET CZS(J)=""
620 LSET PHSCJ)=""t LSET AMS(J)=""t LSET PUS(J)=""
630 LSET PAS(J)=""t LSET ALSCJ~""
640 NEXT J: RETURN
100(>0 END

Direct Access The creatio n of a direct access file must precede any other
File Processing activity that deals with the file, so it is impor tant to unders tand this
technique. However, the reason for a direct access file's existence in
the first place is to provide a way to input any one of its records into
memo ry for processing. This is done with the GET instruc tion,
along with a numbe r of other instruc tions and functions, just as the
PUT instruc tion canno t operat e alone. The usual order of execut ion
for the instruc tions that load variables from a direct access disk
record to various memo ry locations is as follows:
1. Open the file.
OPEN "R", n, "filena me"
2. Describe the records of the file with a FIELD statem ent.
FIELD n, lenl AS varl $, len2 AS var2$, ...
3. Read the record into the buffer
GET nfile, nrec
4. Transfer the buffer 's conten ts into memo ry, converting
numeric variables if necessary.

144 Chapter 8 Direct Access File Processing


Note that for writing a record, the order is:
FIELD .. .
LSET ... = MKt$( ... )
PUT .. .
where the t in MKt$ indicates type, for example S, D, or I.
For reading a record, the order is:
FIELD .. .
GET .. .
. . . = CVt( ... )
where the tin CVt indicates type.

The following program fetches the Nth record from the file
MASTER that was created in the previous program C8Pl, then
allows a change in that record, then rewrites it in updated form.
This program exemplifies what is meant by the term "direct access".
Note that the user of the program enters the actual entry number
(logical record number), and the computer determine s which
physical record to GET and where in that record the entry is located.

10 ·'FILENAME: "C8P2"
20 'FUNCTION! DIRECT ACCESS FILE UPDATE
30I AUTHOR : JPG DATE! 4/80
40 CLEAR 200: CLS
50 OPEN "R",1,"MASTER"! GOSUB 220
70 INPUT "LOGICAL RECORD NUMBER CO=ENDJ";N
80 IF N=O THEN CLOSE: _GOTO 10000
90 GET 1,JNT<CN
" -1 >12>tt ,-'

100 I=INH N/2):t:L=Nt2' I=losica l record t


110 PRINT "ENTER NEW INFO. OR /EN/ = NO CHANGE"
120 PRINT "NAME: ";NAS(I);
130 LINE INPUT AS! IF AS<>"" THEN LSET NASCI>=AS
140 PRINT "STREET ADDRESS: "; SAS(IJ;
150 LINE INPUT AS: IF AS<>"" THEN LSET SA$( I >=AS
160 PRINT "CITY-STATE-ZIP! "; CZS<I>;
170 LINE INPUT AS: IF AS<>"" THEN LSET CZS<I>=A$
180 PRINT "PHONE : "; PHS( I H
190 LINE INPUT AS! IF AS<>"" THEN LSET PHS( IJ=A$
200 PRINT! PRINT "/EN/": LINE INPUT AS: CLS: PRINT! GOTO 70
220 FIELD 1, 24 AS NA$( 1 h 20 AS SA$( 1 h
26 AS CZ$( 1 ), 12 AS PHS( 1 h
4 AS AMSC1), 2 AS PUS(1 ),
2 AS PAS( 1 h 4 AS AL $( 1 )
230 FIELD 1, 128 AS DS, 24 AS NA$(2), 20 AS SAS(2),
26 AS CZS(2J, 12 AS PH$(2),
4 AS AM$(2), 2 AS PU$(2),
2 AS PAS( 2 ), 4 AS AL $( 2 )
240 RETURN
10000 END

Chapter 8 Direct Access File Processing 145


Program C8P2 is notewort hy because it uses the LINE INPUT
to advantage by allowing the user to enter a /EN/ (ENTER
keystroke ) as a null response if no change is necessary. This speeds
up the response time considerably over having to enter a "NO", a
digit, or even a blank, as a null response. Another possible technique
could have been used to update this file, and that is to display the
entire record in menu format down the screen, then allowing the
user to select a field for change. For example, the list below could
be displayed:

1. NAME HARSHBARGER HERSHEL


2. ADDRESS 99 KNOWNOTHING ACRES
3. CITY-STATE-ZIP SHOWME MO 72787
4. PHONE 123-456-7890
5. NO FURTHER CHANGE
ENTER SELECTION BY DIGIT
The user could type the digit, immediat ely followed by the
new informati on, for example:

2451 INANITY AVE.


3DULLARD CT 42179
5

The screen would show the entire record again.

1. NAME HARSHBARGER HERSHEL


2. ADDRESS 451 INANITY AVE.
3. CITY-STATE-ZIP DULLARD CT 42179
4. PHONE 123-456-7890
5. NO FURTHER CHANGE
ENTER SELECTION BY DIGIT
The menu could be modified by allowing the user to enter a 6,
which would ask for a new record number to give the user an
opportun ity to change another record.
As a last example, we include a program that might brighten a
morning by selecting some random "Message of the Day" from a

146 Chapter 8 Direct Access File Processing


file that is easy to run and expand. The idea is simple: Have the
user come in and type

RUN "MESSAGE"

from BASIC. The computer randomly accesses a single record from


a file of jokes, sayings, greetings, and potpourri of other messages.
It displays the record on the screen, gives the user a chance to add a
new message, then branches off to a master menu of activities for
the day.

10 FILENAME! "C8P3"
I

20 'FUNCTION: MESSAGE FILE BUILDER AND ACCESSER


30 I AUTHOR : JPG DATE: 4/80
40 CLEAR 300! DEFINT A-Z: CLS
50 OPEN "R", 1, "MESSAGE/DAT"t FIELD 1, 255 AS AS
60 LAST=LOFC1)
70 IF LAST=O THEN LSET AS="THE FUNGO BAT IS IN TOLEDO.":
PUT 1J 1
80 GET 1, RNDCLAST): PRINT@ 520v A$
90 LINE INPUT "Your turn: "iBS
100 IF BS<>"" THEN LSET A$=8$! PUT 1, LAST+1: GOTO 60
110 CLOSE! RUN "MENU" • some other master menu disPlaY
10000 END

A typical dialog with this program could go something like


this, with the user's entries followed by /EN/.

RUN/EN/
THERE ARE 336 DIMPLES IN THE STANDARD GOLF BALL.
DARTH VADER IS ALIVE AND WELL IN URUGUAY./EN/
THE FUNGO BAT IS IN TOLEDO.
OCT 9! CABBAGE & LIME JELLO SIT DOWN DINNER./EN/
/EN/

This chapter has introduced the techniques that programmers


use to read and write records using direct access files. The
techniques for file management-those that deal with overall file
design and access algorithms-will be introduced in the next section.

Chapter 8 Direct Access File Processing 147


\ I
- ~- - i-

Conversational When computers did their jobs at a distance through batch


Programming processing with punched cards, no one really cared about the
quality or quantity of messages that the programs wrote to the
operator at the console typewriter. After all, one of the skills that
the operator learned was to decipher the terse and arcane jargon of
the operating system.
When timesharing became popular in the early 1970's,
programmers realized that a user at the terminal was more likely to
enjoy the session if a dialog could be established to "humanize" the
computer. The users would accept mild rebuke from the computer.
Since that time programmers have developed many techniques to
promote proper responses from the users. This chapter discusses
some techniques that have been found effective.

User Prompts It is up to the programmer to let the user know what a proper
and Menus response should be. This is the reason for BASIC allowing a string
to be printed along with the question mark with an INPUT
statement. The prompt should also be used whenever a list ofvalues
or strings is to be inputted from the terminal. For example, suppose

149
a dialog has proceeded to the point shown below, with the user's
responses underlined:
HOW MANY IIATA VA.LUES ARE THERE? 15
ENTER EACH IIATA VALUE
? 140

1 220

Notice that although the first response, the 15, was cued well
with the question
HOW MANY DATA VALUES ARE THERE?
all the other entries are just pued once. Then the user must keep
track of the number of entries that are typed. If a double carriage
return is entered (the ENTER key was hit twice, or the keyboard
suffers from bounce) that'sjust too bad, because as chapter 6
pointed out, that just enters the previous entry again. Also, notice
that the question mark prompt is artificial; it is the result of an
INPUT being executed, not a question being asked.
A much better dialog would be:
HOW MANY DATA VALUES ARE THERE? 15
TYPE DATA VALUE 1? 140
TYPE DATA VALUE 2? 220
+

This dialog is produced with the statement:


100 PRINT "TYPE DATA VALUE"H;! INPUT X<I>
At least the dialog reminds the user of which value to enter.
However, it still suffers from the question mark being printed, and
from an accidental double /EN/ causing false input.
The next sample dialog is made possible by using the LINE
INPUT statement.
HOW MANY DATA VALUES ARE THERE? 15
TYPE DATA VALUE 1! 140
TYPE DATA VALUE 2! 220

150 Chapter 9 Conversational Programming

t j
If the user accidentally double strokes the /EN/, a good program
·should be able to discover the mistake. Also, since the input variable
is a string, the program must be able to check it for illegal characters,
because the computer won't give any automatic second chances for
input with a ? REDO message, as is normally the case with numeric
-input.
Here is a subroutine that acts like the line
100 PRINT "TYPE DATA VALliE"; H! INPUT X( I)
except that it uses LINE INPUT and translates the string to a value
after checking to see if it is an integer between 0 and 200 inclusive.
800 ' input subroutine
810 PRINT "TYPE DATA VALliE";!;": ";
820 LINE INPUT AS: N=LENCA$)! V=VAL(A$)
830 FOR J=l TO Nt CS=MID$CA$,J,1>
840 IF CS<"O" OR C$)"9" THEN 870
850 NEXT J
860 IF V<=200 THEN X<I>=V: GOTO 880
870 PRINT "*** ERROR ON INPUT ***"
880 RETURN

Another useful technique that should accompany data input is


echo checking, which involves the display of all data entered in one
session. This may be sectioned in such a way as to simplify the
process of updating any value that was entered in error.
The INKEY$ is useful when the responses are limited to single
characters, because the user is saved the trouble of pressing the
ENTER key after every stroke. But be careful about mixing
INKEY$, LINE INPUT, and INPUT. As the programmer, you are
responsible for making data input and interactive dialog as easy to
understand and use as possible, and that includes being consistent.
A menu is the display of a list of commands with a convenient
way to access the commands. Some examples of menus are shown
below.
(1)

ACCOUNTS RECEIVABLE PACKAGE:


1. ADD ACCOUNTS
2. DELETE ACCOUNTS
3. POST PAYMENTS
4. POST CHARGES
5. AGE ACCOUNTS

Chapter 9 Conversational Programming 151


6. BILLING ~:UN

7. SUMMA~:Y REPORTS

ENTER THE ACTIVITY OF YOUR CHOICE BY NUMBER:

(2)
Statistics Packase!

1. Build data fHe

2. Sor l data file

3. Create lest dala file

4. Edit. dala file

5. Chi -S8uar·e

6. T-Tesl
7. ItescriPtive

8. Cor-r·elalion

9. An ova

10. Probabilities

11. Curvilinear resression

Enter choice of aclivitw:

(3)

G A ME S
C Chess

A Ani rnal

B Breakout

I Ivanhoe

152 Chapter 9 Conversational Programming


N NiRt

E En em~ Be .low

T Ti.c-Tac-Toe

w Hunt t.he WURtPUS

0 Othello

R Rocket.

K Kinsl<ons

s Star trek
Enter \,JOUr choice b~ its fir· st. .let.t.er:

ERR, ERL, Not many versions of BASIC, even the better versions found on
ON ERROR GOTO, the newest microcomputers, have user-defined error trapping. This
and RESUME is one of the TRS-80 Level II BASIC's outstanding features. In
general terms, it allows the programmer to branch to specific lines of
code when an error during the execution of a program.
The ON ERROR GOTO statement enables you to branch to a
segment of code that checks for possible program recovery in case of
an execution time error. This statement must be executed before the
error occurs, otherwise the computer generates the usual error
message and terminates execution. If the line number specified is 0
(ON ERROR GOTO 0) the error trapping feature is disabled and
BASIC will print an error message as it usually does.
The RESUME command returns control of the program to any
line after an execution time error has occurred. The RESUME can
be written in any one of three ways:
(1) RESUME (no line number)
or RESUME 0 returns control to the
statement that caused the
error.

(2) RESUME line-no ·returns control to the specified


line number.

(3) RESUME NEXT returns control to the line


following the one that caused
the error.

Chapter 9 Conversational Programming 153


Example:
10 ON ERROR GOTO 9000

50 X=Y /N
60 PRINT "X=" ;x

9000 I N must nol be zero -- if it is, chanse it


90 10 1 in t.o a ver s Sll12.ll mm1ber
9020 N=lE-20
9030 PRINT "N CHANGED FROM 0 TO lE-20"
9040 ~:ESUME
The effect of this program is to prevent termination of the
program's execution due to a division by zero in line 50. A message
is printed to indicate the change that was necessary to keep the
program running. Notice that line 9040 could have been written as
either of the following:
RESUl1E (l
(l'(l4(l
'1040 RESUME 50
There is a particular advantage to the RESUME or RESUME 0,
and this is that it allows a single error handling routine, like lines
9000-9040 above, to manage the possible occurrence of errors in
many places within the program. For example, the example above
could have contained the line
20 0 A< R )=2tiJ /N
If this line were executed with N=O, the error trap would
function just as well, and the RESUME statement would return
execution to the next line.
The ERR and ERL functions allow the programmer to use some
very specific error traps. ERL returns the line number in which the
error occurred, and the ERR returns a value related to the error code.
Both functions need no argument.
The value that ERR returns is related to the error code this way:
ERR/2+ 1=Code value
or
ERR=2*Code value- 2
Appendix F lists all of the error codes that Level II BASIC and Disk
BASIC can generate.
The following example shows various ways that the ERR and
ERL functions can serve to isolate specific errors.

154 Chapter 9 Conversational Programming


10 ON ERROR GOTO 9000
20 INPUT "ARRAY SIZE (ROW, COLUMN)";R,C
30 DIM X(R,C>
40 FO~: I=l TO ~:
50 INPUT "ENTER";c;"VALUES FOR ROW";I
60 FOR J=l TO c: INPUT X(I,J>: NEXT J,I
70 PRINT "ANY VALUES TO CHANGE (Q,O=NONEJ"
80 PRINT "ENTER ROW, COLUMN";
90 INPUT Rl,Cl

9000 error code 7 = oul of rueruorY


9010 IF ERL<>30 OR ERR/2+1<>7 THEN 9050
9020
9030
PRINT "*** OUT OF MEMORY ***"
PRINT "RERUN PROGRAM AND REDUCE ARRAY SIZE"
9040 STOP
9050 ' error code 10 = subscriPt out of ranse
9060 IF ERL<>90 OR ERR/2+1<>10 THEN 9100
9070 PRINT "*** SUBSCRIPT OUT OF BOUNDS ***"
9080 PRINT "TRY AGAIN -- THAT POSITION IS NOT LEGAL"
9090 RESUME 80
9100 no idea what's Soins on -- better
9110 let BASIC handle the Probleru
9120 ON ERROR GOTO 0

Anticipating It is always a pleasure to interact with a computer through a


User Responses well thought out program, one that was written with the user in
mind. Many users, especially novices, regard any such interaction
with trepidation because they know the computer is a machine.
Either through fear of doing damage or through anxiety caused by
the unfamiliar nature of this form of communication, these users
dread the sessions and commit blunders. Good programming practice
includes anticipating user errors and if possible correcting them or
certainly allowing the user a second chance. Whatever approach is
taken, you should always try to create a friendly and informative
dialog with the user.
Consider these two dialogs:

NAMET KUMQUAT, KATHY


NAME? 14 PUNCTILIOUS PLACE
NAME? PERSIMMON~ ALASKA 98765
NAME? 878-787-8/break/
Chapter 9 Conversational Programming 155
The user has realized that the computer ignored all of these
entries. The clue was the repeated prompt NAME? which the user
remembers (too late) should change to
STREET?
CITY STATE ZIP?
F'HONE'f
The user's action ofinterrupting the program's execution with a
/BREAK/ is rather excessive, because now the program may have to
be restarted. The dialog could have been:

NAMET MOMERATH, POMEROY


NAMET MOMERATH POMEROY
STREETT 291 OUTGRABE ALLEY
CITY STATE ZIP? BRILLIG, VERMONT 24938
CITY STATE ZIP? BRILLIG VERMONT 24938

At least the program was kept running, and the user realized that
the repeated prompt meant that something was wrong with that
entry. But how did the user know? The dialog didn't say that
commas weren't allowed, yet obviously that's what was wrong. As
soon as commas were removed, the program proceeded nicely.
The example above shows rat maze behavior on the part of the
user (try, try again-when you get it right, maybe you'll remember
it) and sadistic behavior on the part of the programmer. After all,
if the program was clever enough to determine that there was a
comma in the entered data, certainly it should be clever enough to
remove the comma, and kind ertough to remind the user to omit
commas between entries. The following dialog is nicer in all
respects.

156 Chapter 9 Conversational Programming

\ ...
NAME? BACILLUS, VACILLA
PLEASE OMIT COMMAS IN DATA INPUT
NAME? BACILLUS VACILLA
STREET ADDRESS? 66 SEPSIS ST
CITY't WOUND

STATE ZIP? WEST VIRGINIA, 49228


NO COMMAS, PLEASE, YOU KNOW I DON'T LIKE THEM!
STATE ZIP? WEST VIRGINIA 49228
PHONE? 499-994- 4949

This dialog is polite (note all the PLEASEs) and varies even if the
same input error is committe d.

Check Digit When specific numbers are used in a record as a code and their
Calculations accuracy is imperativ e, such as serial numbers, account numbers, and
other unique identifica tion numbers, a check digit is often employed
to verify the number. A check digit is a single digit added to the
code number to make that code number self-checking. It has a
unique relation to the rest of the code number and the way it is
calculated determine s the types of errors that can be detected by it.
The four kinds of errors that a check digit can detect are:
(1) Transcrip tion: A wrong number is written, such as a 1 for
a 7 or a 5 for a 0.
(2) Transposi tion: The correct numbers are written but their
positions are reversed between neighboring columns, such
41582fo r 41852.
(3) Double transposit ion: Numbers are interchan ged between
columns other than neighbori ng columns, such as 41582 for
48512.
(4) Random: A combinat ion of two or more of the above, or
any other error not listed.
The use of check digits involves the computer 's initial
calculatio n and storage of the digit with its correspon ding code
number as the number gets filed initially. For example, as a file of
accounts is built, the account numbers become the access codes to

Chapter 9 Conversa tional Programm ing 157


to the file which will incorpor ate the check digits. As each new
account is entered, its access code is generated from the account
number followed by the calculated check digit. This access code
becomes a permane nt part of the record. When an access operatio n
is perform ed on the file, it is done by access code, including the
check digit. If there is any error in either the account number
portion or the check digit portion of the access code, the user is
warned that the code doesn't exist, and should try again.
Check digits are related to their code numbers through any one
of various methods of calculation. Some methods of calculating
check digits are rather poor, detectin g only some of the possible
errors that occur. We will show you one of the best, and for that
reason the most popular: the modulus 11 procedu re. The method
of calculation is the same as that which is used for detectio n. That
is, when an access code is checked, its check digit is recalculated and
compare d to the one that was originally attached . If it is differen t,
the user is warned of an error.

Modulus Eleven Check Digit Calculation Method


1. Multiply each digit in turn with its correspo nding weight.
The weight is simply the digit's position in the code number
from right to left, plus one. For example, for the code
32604:
3*6 2*5 6*4 0*3 4*2
18 10 24 0 8
2. Add the resultan t products ,
18 + 10 + 24 + 0 + 8 = 60
3. Divide the sum by the modulus (in this method it is 11) and
keep the remainder. 60 / 11 = 5 with a remaind er of 5.
4. Subtract the remaind er from the modulus , and the result is
check digit. 11 - 5 = 6. If the remaind er is 0 the check digit
is 0. If the remaind er is 1, the check digit is 1. If the
remaind er is 10, that account number must be rejected.
Therefo re the access code is 326046.

Examples:
1. Code number 421865
4*7+2*6 +1*5+8* 4+6*3+5 *2
28+12+5+18+10=105
105/11= 9, remaind er=6
11-6=5
Access code=4 21865 5

2. Code number 2493


2*5+4*4 +9*3+3* 2=59
59/11=5 , remaind er 4
11-4=7
Access code=24 937

158 Chapter 9 Conversational Programming


3. Code numb er 2653
2*5+ 6*4+ 5*3+ 3*2
10+24+ 15+6=55
55/11 =5, rema inder 0
11-0=11: special case: checkdigit=O
Access code= 2653 0

4. Code numb er 4653


4*5+ 6*4+ 5*3+ 3*2= 65
6 5/ 11 = 5, remai nder 10
Rejec t this accou nt numb er. Do not allow it in the system
,
and choos e the next code numb er, 4654. It's check digit
is
0, making the access code 4654 0.

5. The access code that the user gave is 26214 . Is this a prope
r
access code? (Does the check digit of 4 corre spond to
that
calculated for code numb er 2621 ?)
2*5+ 6*4+ 2*3+ 1*2= 42
42/11 =3, rema inder 9
11-9=2
The access code 2621 4 is impro per since 2621 has check
digit 2,
not 4. An error message shoul d be issued to the user.

Instead of recalculating the check digit, the comp uter


program
that verifies the accuracy of the input access code can
multi ply all
digits of the access code by their weights, using a weigh
t of 1 for the
check digit itself. When the sum of all of these produ cts
is divided by
the modu lus, the result shoul d be zero.
The modu lus 11 check digit calculation proce dure can
detec t
all of the user's transc riptio n and transp ositio n errors,
which accou nt
for 95% of all the errors that users comm it. The meth
od also detec ts
90% of the rando m errors. Thus the modu lus 11 meth
od can detec t
99.5% of all errors. If even more accuracy is neede d, the
meth od
can be modi fied by using prime numb ers larger than 11
for a
modu lus. For exam ple, the modu lus 37 meth od detec
ts 99.987% of
all user errors.
Check digit calculations impo se a penal ty in calcu lation
time,
but that penal ty is not severe when the appli cation involv
es a single
user on the comp uter.
The following progr am attach es a check digit to a six digit
accou nt numb er.

Chapter 9 Conversational Programming


159
10 'FILENAME: "C9P1"
20 'FUNCTION: CHECK DIGIT CALCULATOR : 4/BO
30 I AUTHOR : JPG DATE
40 I
50 PRINT "To stop , Pres s /bre ak/, othe rwis
e ente r"
ts)"
60 PRINT "an account number (anY number of disi er: ";Ns
70 PRINT! LINE INPUT "Ple ase ente r the numb
BO S=O ' rese t the sum to zero
valu es and
the follo wins is a looP for addi ns theweis
90 1
ht
100 mult iPlY ins the Ith disi t by its
I
sums so far
110 ' while keePinS a runn ins tota l of the
120 FOR I=l TO LENCNSl
130 S=S+VAL(MIDSCN$,I,l))*CLENCNS)t2-Il
140 NEXT
150 ' set modulo elev en from the sum
160 M=S-INT(S/11)*11
170 add the ProPer check disi t to the number
I

180 IF M>O THEN NS=NStRIGHTS(STR$( 11-M),1)


ELSE NS=N$+"0"
190 if acct . J is Sood, Prin t it, othe rwis e
200 Prin t reJe ct messase
1

210 IF M=10 THEN PRINT "Acc t. t reJe cted "


ELSE PRINT "Acc t. t is ";NS
10000 END

whic h is made
Praise and One of the most irrita ting forms of dialog is that
g:
Chas tisem ent up of unifo rm words of praise. Consider this dialo

WHAT IS 2+2, JOHNNY? 4


GOOD! WHAT IS 5t7, JOHNNY? 12

GOOD! WHAT IS 6t19 , JOHNNY? 25


GOOD! •••
GOOD! t t I

dialog, and
John ny is by now well beyo nd reading the comp uter's
er respo nse. If that's
merely looks at the digits to make the prop
the word s entire ly.
the case, the progr am shou ld do away with as a
led prop erly it can act
Praise does work , thoug h, and if hand is a child
vior whet her the user
stron g stimu lus for prop er user beha ents, or
, a book keep er posti ng paym
being drilled in arith metic skills e
t of using prais
an executive study ing stock portf olios . The secre
rando mize it. Cons ider this dialog:
with the comp uter is to

160 Chapter 9 Conversational Programming

' '
1. _____:_ -··- '- I

WHAT IS 5t7, JOHNNY? 12


GOOD WORt\.
WHAT ABOUT 8t17 , JOHNNY? 23
YOU MISSED THAT ONE. BETTER LUCK NEXT TIME.
CAN YOU COMPUTE 8+17? 25
SUPER!
TRY ADDING 22+17? 39
VERY GOOD!

These kinds of messages are fun to create in a program, fun for


the user to receive, and significantly improve the user's perfor
mance
in whatever task is being tried. The technique relies on genera
ting
entire sentences from randomly chosen phrases in two phrase
pools:
one pool is for praise and the other for chastisement, or scoldi
ng.
The following program illustrates the technique.

10 'FILENAME: "C9P2"
20 'FUNCTION: ILLUSTRATE PRAISE AND SCOLDING
30 ' AUTHOR : JPG DATEt 6/80
40 CLEAR 1000
50 R=20 ' nu~bers will initi allB be between 1 and 20
60 CLS: INPUT What is ~our name";N$
0

80 X=RND< R>: Y=RNII( R>: S=XtY 'Get. the random nu~bers


90 PRINT "What is";X ;"t"; Y;", ";N$;
100 INPUT S1
110 IF S1<>S THEN GOSUB 150: GOTO 90
ELSE R=R+1: GOSUB 1.20: GOTO 80
120 FOR 1=1 TO 10: READ Y$: NEXT I
130 GOSUB 150: RETURN
140 • subro utine to Prin t the messases
150 GOSUB 170: A$=X$t GOSUB 1.70: B$=X$
160 PRINT A$t", "tB$: RESTORE: RETUR
170 J=RND(5)t FOR 1=1 TO J: READ Xit N NEXT I
180 IF ,J<5 THEN FOR I=Jt1 TO 5: READ n: NEXT I
190 RETURN
200 DATA You nlissed, Bad news, Ush, Too bad, Yuch, klutz
210 DATA nerd! , turke y!, buffo on!, dolt! , Good, Exce llent!
220 DATA Fine, Nice, Great., You sot it, You're rishl
230 DATA Just fine, KeeP it up, SuPer
10000 END
Chapt er 9 Conversational Programming 161

~~r- ---1-- --, ~ , '-- ~ ----,- ,, - - - , -


for data
Infor ming the User Comm unica tion with the user is more than just asking
abou t how to
During Processing and giving answers. It also involves inform ing the user
ging a file, and
perfo rm a task, such as running a program or mana ss
g some proce
inform ing the user that some thing is happe ning durin
in a progr am's execu tion.
n:
Suppose, for instance, the dialog proceeds in this fashio

Do '::lOU want. t.o;


( 1 ) sor· t. (2) uPda te (3) rename a file? 1

What is the name of the file? MAYACCTS

(A pause while the file is opene d)

On what. kes do sou wish t.o sort?

(2) acco unt number

(3) dale of last serv ice

(4) aruount. Past due

Ente r sour choi ce bs digi t: 2

OutP ut on (1) scre en, (2) Print er·, (3) file? 3

(A very long pause while the file is being sorted .


There may
dismay
be much hissing and clacking of drives, to the possible
of the user)

Done.
g process.
Consider the conce rn of the novice user during the sortin
isn't
Is there something wrong because of all the noise? Why
it sortin g the file, and creati ng a new one, as
anyth ing happening? Is
off the
it shoul d be? How long does this go on? Should I turn
comp uter befor e it break s?
by
The progr amme r can do a lot to ease the user's anxie ty
to keep the
printi ng simple interm ediate messages during processing er 7
in chapt
user inform ed abou t what is going on. The last program the
sort to let
shows how to use a simple PRIN T statem ent during a
, as it may
user know how it is progressing. When a sort takes hours
thous ands, a PRIN T
if the numb er of eleme nts to be sorted is in the It can
the user greatl y.
strategically placed within the sort can help
tell:
( 1) Whether the sort is working.

162 Chapter 9 Conversational Programming


(2) Appr oxim ately how long it takes.
(3) What stage of the sort is being perfo rmed .
Anot her use of the process-time message is to keep the
user
from doing some thing during critical times, or to inform
the user of
abnor mal events. For example, a process may turn the
disk drive on
and off with long pauses when intern al processing takes
over and the
drive is off. The user shoul d be given some message, such
as:
Ill STILL USING THE DISK DRIVE! ***
*** DO NOT OPEN THE DRIVE DOOR! ***
Anot her case in point is in the instan ce when one drive
gets full, the
program senses it, and opens a new file on anoth er drive.
The user
may be caugh t by surprise, and absol utely must n't distur
b the
process. A helpf ul message migh t be:

DON'T WORRY ABOUT ACTIVITY ON OTHER DRIVES,


YOUR FILE WAS TOO LARGE FOR ONE DRIVE.
Ill DO NOT OPEN ANY DRIVE DOORS ***
Such messages as these often spell the difference betwe
en a
happy user who is pleased to work with the system, and
an anxious
user who can't wait to get away from the machine.

Obviously, the progr amme r must be aware of the user's


point of
view when the progr am is still in its initial stages of comp
ositio n.
This techn ique of user-proofing a program is not trivial
. It requires
both the knowledge of progr ammi ng techn iques and consi
derable
imagi nation in trying to antici pate user responses.
The techn ique that follows in the next chapt er is an aid
to the
progr amme r rathe r than to the user. As you will see, it
involves the
overall design of progr ams to make them more readable
and easier
to alter.

Chapter 9 Conversational Programming


163
' i

'-1
Structured The number of program mers that use BASIC will increase
Programming greatly during the 1980s, primaril y due to the rising populari ty and
falling price of microco mputers . Many of these new program mers
will commit the same fundame ntal errors in techniqu e that were
committ ed ten and twenty years ago by today's professionals.
Unless these new ranks of program mers learn the proper ways of
program ming, their level of frustrati on will increase in proporti on
to their level of producti vity.
By the late 1960's the speed and memory capacity of compute rs
had increase d to such a point that it was economi cally unwise for a
program mer to "fine-tu ne" his or her product to run a little bit faster
or to fit into a slightly smaller area of memory . The program mer's
time was worth more than any possible gain in machine time or
memory use. Aside from this econom ic oonsider ation, the number
of program mers was rising, and the ability to commun icate the
contents of a program to new member s of the staff became a very
valuable asset.
Program s got more complex as they dealt with more file storage
hardwar e. With some of these program s, as their complex ity grew,
their reliabilit y dwindle d, sometim es to the point of complet e failure.

165
Some of these aging and dying programs represente d large
investmen ts in time and money, yet because of their great
complexi ty, their slightest alteration risked severe and unexpect ed
complications.
During the 1970's, programm ers developed various technique s
to design their product from the beginning as a set of independ ent
modules, each of which could be altered without affecting any other.
Also, new and independ ent modules could be added to the program
without the risk of creating a bug in a previously tested and
debugged module.
These technique s yielded three immediat e benefits:
(1) Programm er productiv ity increased due to a better under-
standing of the fundamen tal problems that were being
solved.
(2) Program debugging and testing was simplified. A new
module could be tested independ ently of all others.
(3) Program maintenan ce was simplified as a result of the ease
of module addition, modificat ion, and deletion.
These three factors made programs more flexible and extended
their useful life. As the environm ent and the computer hardware
changed, these modular programs had a much better chance of
surviving and being productiv e than their predecessors.

Program Planning Students in most introduct ory programm ing classes are taught
that a program is written in five stages:
(1) Understan d the problem.
(2) Formulat e and flow chart an algorithm, or method, for its
solution.
(3) Code the program.
(4) Test it and debug it.
(5) Documen t the program and its output.
The first stage is intuitively obvious. How can any problem be
solved without a thorough understan ding of its nature? A
programm er usually understan ds the problem when he or she
understan ds the four major phases of input, processing, storage, and
output, clearly. This overall view usually determine s the format of
most of the program's outputs.
The second stage normally involves a rather detailed design of
all records: input, transactio n, storage, and output. The algorithm
is usually flowchart ed using some variation of the standard ANSI
(American National Standards Institute) symbols.
The third and fourth stages are often performe d simultane ously.
The key ingredien t in the testing phase is imaginati on. The
programm er must be able to anticipate as many of the user's
responses as possible. This phase was discussed in some detail in the
last chapter.
Documen tation is the fifth phase, and this subject is covered in
the next chapter.

166 Chapter 10 Structured Programming


In this chapter we will consider program planning to include
both the first and the second phase.

Phrase Flowcha rts When one thinks of flow charts, what usually comes to mind is
a map-like drawing full of variously shaped symbols and arrows. This
is not necessarily the case. A flowcha rt is a step-by-step
represen tation of a problem 's method of solution (an algorithm), and
it is often just a set of English phrases and notes in some semblance
of the order of solution . This is a phrase flowcha rt . It is easy to
understa nd, and it is a more natural product of the program mer than
a symboli c flowcha rt, particula rly during the initial stages of the
program 's creation . As an example of a phrase flowcha rt, we have
included here the original phrase flowcha rt for the Sort-Merge
program in chapter 7.
(I) Create 4 files, fill with random alphanu meric data,
50 records with 30 characte rs per record,
list them.
(2) Sort each file.
Repeat the next four steps four times.
(a) Load file into memory .
(b) Sort.
(c) Close: open.
(d) Write out.
(3) Merge.
(a) Read I record into each of four buffers.
Start each of 4 counters at 1.
(b) Scan top of stacks, write out smallest to 1 file,
read new one, add 1 to proper counter.
The usual approac h to making phrase flowcha rts is to state in
phrase form what is to be done in a series of steps, and to number
each step. The final product vaguely resembles a set of broadly
worded instructi ons. Its chief advantages are simplicity and
familiarity to the program 's creator.

ANSI Flowcha rts Since the 1960's, the compute r industry has made efforts to
establish some standard s that would cover the wide variety of
products of the technolo gy. The organiza tion that has had the most
impact has been the America n National Standard s Institute (ANSI).
This body has established industry -wide standard s for compute r
languages, methods and codes for machine -to-mach ine
commun ication, and even the symbols that should be used for
flowcharting.
ANSI symboli c flowcha rts are what comes to mind when
flowcha rts are mention ed. They are symbolic; that is, they are made
up of connect ed diagrams that represen t various segments and
processes of the program . The five basic ANSI flowcha rt symbols
are shown in figure 10.1. These five symbols are intercon nected with
straight lines. The chart is read from top down and to the right

Chapter 10 Structured Programming 167

-T
Symbol Name Meaning

__)
( Termina l Start or end of a
sequence of operatio ns

Input/O utput I/0 operatio n

Process Any processing


function

Decision Any kind of branchin g


operatio n

0 Connect or Connect ion between


parts of a flowcha rt

Figure 10.1 Basic ANSI Flowchart Symbols

unless an arrow indicates a differen t direction of logic flow.


Consider the problem of inputtin g an all-digit answer with the
INKEY$ function , as program med in chapter 6. First, we will show
you a phrase flowchart of the problem 's solution , then an ANSI
symboli c flowchart.

168 Chapter 10 Structured Programming


Phrase Flowchart for Digit Input Subrou tine

(1) Null the input string.


(2) Input a charact er with INKEY$.
(a) Return if /EN/ stroke.
(b) Print error message if out of range,
then get new charact er (step 2).
(c) Add to input string if OK, then get
new charact er (step 2).

Symbol ic Flowchart for Digit Input Subrou tine

Chapter 10 Structured Programming 169


Symbolic flowcharts can be very specific; that is, every symbol
can represen t a single instructi on, such as the flowcha rt above. Or
they can be very broad; that is, every symbol represen ts a large set of
instructi ons. The following example is a broad symboli c flowcha rt.

Symboli c Flowchart for a Statistics Package

170 Chapter 10 Structured Programming


- _l

Progr ammi ng All programs and their inclu ded parts can be broke n down
Struc tures into
one or more of three basic struct ures.
1. The Seque nce Struc ture consists of a set of imper ative
progr am statem ents that are execu ted in sequence. For
exam ple, this progr am segm ent is a seque nce struct ure.

200 OPEN "R", 1, "RANKEN"


210 FIELD 1, 255 AS X$
22(1 LAST=LOF< 1 )
23(1 GET 1, LAST

2. The Selection Struc ture, or the IF-T HEN -ELS E Struc


ture,
repre sents a choice betwe en two and only two action s
based
on a condi tion. If the condi tion is true, one action is
perfo rmed ; if it is false, the other action is perfo rmed
.
Cons ider the following seque nce of code as an exam ple.

100 IF A<NUM THEN SUM=SUMtX: K=Ktlt


S2=S2+X*X! GOTO 50
ELSE S3=SUM#SUM
3. The Iteration Structure, or FOR -NEX T Struc ture,
provides
for execu ting a funct ion as long as a condi tion is true.
When
the condi tion is no longe r true, the progr am perfo rms
the
next funct ion in sequence. A comm on altern ate form
of the
iterat ion struc ture allows the funct ion to be execu ted
until
the condi tion becom es true. In BASIC the FOR -NEX
T is
the stand ard iterat ion struct ure, in some cases the
IF-TH EN-G OSU B can act as an altern ate form. Here
are
some exam ples of the logic of iterat ion struct ures.

100 FOR I=l TO 100 STEP 5


150 NEXT I

Chapter 10 Structured Programming


171

- - I .
200 IF A THEN GOSUB 500: GOTO 200


300 IF X<Y THEN GOSllB 500t GOTO 300

200 IF NOT A THEN GOSUB 500! GOTO 200

300 IF X:Y THEN GOSllB 500: GOTO 300

these
Figure 10.2 shows the symbolic flowcharts for each of
clarif y the differ ences in their action s.
struct ures and will help

172 Chap ter 10 Struc tured Programming


L--

Sequence Struct ure

Selection Struct ure

Iterati on Struct ure

Figure 10.2 Symbo lic Flowcharts of Programming Structures

Chapter 10 Structured Programming 173

-, ---- I I-----~;---;-
with
GOT O-Le ss The term GOT O-les s programming has been associated
in 1965
Programming Edsger Dijkstra of the University of Eindhoven, who
GOTO
suggested that any program could be writte n witho ut using
ased a progr am's
statem ents. He said that GOTOs in a program decre
clarity and one's ability to test and maint ain it. so
In practice the GOTO is perm itted in struc tured programs
When BASI C allow s
long as it is used as an exit from a module.
multiple statem ents per line, the form:

lnl IF condi tion THEN GOSUB ln2 : GOTO lnl


ins a
is well suited as an iterat ion struct ure, even thoug h it conta
ompl icate code in order
GOTO. Many texts would have you overc
was estab lished for
to maint ain confo rmity to a stand ard that
y rathe r
COBOL. We feel that BASIC's concise coding can clarif
than complicate the logic of a program.
of
The practice that shoul d be avoided in BASIC is the use
point where the reade r
GOTOs followed by line numb ers to the ous
need to get back to a previ
loses the progr am's conti nuity . If you
GOSU B to the set of statem ents
statem ent, you might find a way to
example,
above the GOTO, and replace it with a RETURN. For
lates the mean and stand ard
consider this little program that calcu
deviation of a sample.

20 'FUNCTION: DEMONSTRATION OF POOR STRUCTURE


30 ' AUTHOR : JPG DATE: 9/79
40 1=1: 5=0: 52=0
50 PRINT "NUMBER";r;: INPUT X
60 IF X<>O THEN 80
70 GOTO 90
80 I=It l: S=StX: S2=S2+X*X: GOTO 50
90 M=S/I: PRINT "MEAN="iM
100 PRINT "STD~ DEV.=";SQR<CS2-S*M)/CI-1))
110 INPUT "ANOTHER SAMPLE";AS
120 IF AS<>"YES" THEN 10000
130 GOTO 40
10000 END
,
This program is a trivial example that is quite easy to follow
s as possib le. The
even if it has been writte n with as many GOTO
s
first and most obvious step is to get rid of all simple GOTO
imme diatel y after the IFs. The following progr am is an
impro veme nt.

174 Chapter 10 Structured Programming


I
I
I ,

10 'FILENAME: "C10P2"
20 'FUNCTION: BETTER STRUCTURE THAN PREVIOUS PROGRAM
30 AUTHOR : JPG
I
DATE: 9/79
40 I=1t S=O: S2=0
50 PRINT "NUMBER";I;: INPUT X
60 IF X<>O THEN I=It1 : S=StX: S2=S2+X*X: GOTO 50
ELSE I=I-1 : M=S/I: PRINT "MEAN=";M:
PRINT "STD. DEV.=";SGRCCS2-S*M)/CI-1 ))
70 INPUT "ANOTHER SAMPLE";A$
80 IF AS="YES" THEN 40
10000 END
This is a much better program. It is clearer, even though its
selection structures, the IF-T HEN -ELSE statements, are rather
complex.
. Now consider the following program. Its single GOTO is a
part of the UNTIL iterati on structure. The only other refere
nces
to line numbers are in the GOSUBs. Subroutine 60 is clearly
the
main subroutine, and subroutines 200, 300, and 400 perform
the
initialization, input, final calculations, and print- out functions.

10 'FILENAME: "C10P3"
20 'FUNCTION: SAME PROGRAM WITH GOOD STRUCTURE
30 IAUTHOR : JPG DATE: 9/79
40 INPUT "DO YOU WANT STATISTICS <YES OR NO)";AS
50 IF AS="NO" THEN STOP
ELSE GOSUB 60: GOTO 40
60 GOSUB 200 initi alize varia bles
70 GOSUB 300 inPut data
80 GOSUB 400 calcu late mean and std. dev.
9(1 GOSUB 500 Print std. dev. and mean
100 RETURN
200 S=O: 52=0: M=O: RETURN initi alizi ng routi ne
I

210 I subro utine for data inPut


300 INPUT "HOW MANY OBSERVATIONS";N
310 FOR I=l TO N
320 PRINT "TYPE VALUE NO." au INPUT x
330 S=StX: S2=S2+X*X
340 NEXT I
350 RETURN
360 ' subro utirie for calcu latio ns
400 M=S/N: SD=SGRCCS2-S*M)/CN-1>>: RETURN
410 1
subro utine to Prin t resu lts
500 PRINT "MEAN=";M
510 PRINT "STD. DEV.=";SD
520 RETURN
10000 END

Chapter 10 Structured Programming


17 5
ntage this
At this poin t you may be wondering what adva
simp ler-lo okin g predecessors.
program could possibly have over its
and grow th pote ntial . For
The key is in its ease of mod ifica tion le, you
the rang e of the samp
example, if you want ed to calculate st-se en and
keep track of the lowe
could alter the inpu t subr outin e to do there
ing that what ever you
highest-seen values, and do so know
ed to add a new
cann ot affec t the othe r modules. If you want
feature, you could just add a new subr outin e.

is but a facet of
Top- down The entir e subje ct of GOT O-le ss programming
it leads natu rally
Programming of the area of struc tured programming. However,
n, top-d own prog ramm ing, and
into the area of program desig
is the segm entat ion of the logic of a
mod ular programming. It
program into its parts.
n of a
Top-down programming involves the overall desig
hierarchical order.
program into a series of mod ules arranged in a
is inco rpor ated into
That is, the primary objective of the program
tives are next , and the
its first mod ule or section, the secondary objec
ious program is an
subo rdina te objectives are belo w those. The prev
a clearly iden tifiab le
example of top-d own programming. There is
ules, the subroutines.
main mod ule and a num ber of subo rdina te mod program is
A good way to visualize the design of a struc tured
is a struc ture char t of
with a hierarchy chart or structure chart. This
program C 1OP3.

Structure Chart for Program Cl OP3

\0
OpE:>A.IIII~
ll:::·JE:L 0
Dio..\~

(00
l
Proc:!....x..E::
LE\.\cL l
5\u..+is-\-\c.s.
I
I I I
I~O()
12-Co
1000
PciV\T
LIAf:"''T C.o..\w\o..~
Do-..+o.... ~'o.l\'ts

176 Chapter 10 Structured Programming


j__--

The struct ure chart shows all of the modules in the program and
the relationships betwe en these modules. Input and outpu t functi
ons
are distinguished from processing functions. It is easily gener
ated
before any actual coding is done. In contra st to the symbolic
flowchart, which is more of a representation of an existing progra
m,
the struct ure chart serves best as a design aid.
A major advantage of the struct ure chart over a programmer's
informal phrase flow chart as a program design tool is the struct
ure
chart' s capacity for modification and growth. Let us consider
the
previous statistics program -as a kernel for a much larger system
of
programs for statistical analysis. Suppose you want to add these
features:
1. Input of data by groups.
2. Each el~ent of a group can have more than one
observation.
The new struct ure chart could be:

10
Pfb<hl(f;
S,~a,

J -
I I
IOO
z.oo I
1..\~ ~oO

~
Co..\-w\o..-1., PriV\t
~\llts
I I
I I I I I
1000
IV\f"l\"
f.~<>.Y<:\
'* 1\00
~t
~lo'1
U:>oO
Co..lc.l\rk
~-\-\'5.-ht<
2..\00
c....\c."\c.-\t:,
~000
1'r-i..q
a1oo
1"1-i~
J
0~\iW\~ r..c-0\Jf' 1>-.t~ps
~~-nc.s . s+c..+istics ~I..
~0"""-''""' """fooro->ps .....,01,~~

This major change was incorp orated by adding anoth er level


to
the existing struct ure chart. This added level describes the new
modules that will be necessary to imple ment the changes. The
programmer could write new subroutines, numbered in the 1000's
,
with no more change to the existing modules than some new
GOSUBs in the level 1 modules.
The program planning and design aids we have shown in this
chapt er can greatly increase programmer produ ctivity and enhan
ce

Chapter 10 Structured Programming 177


in a more
program clarity. You can rewrite existing programs
so doing , very likely breat he new life into
struc tured style, and in
you how to
those programs. The chap ter that follows will show
ams. It is the
prepare associated docu ment ation with your progr
een an easily
docu ment ation that usually spells the difference betw
that no matt er
usable program and mark etabl e program, and one
popu lar with its
how fine it is technically, just does n't seem to be
users.

178 Chapter 10 Structured Programming


L -

Documentation Docu men tatio n is often considered to be the prog


bane and burd en, the cross to bear for writing ramm er's
good programs. It is
unfo rtun ate that this attitu de exists, because
it tend s to reduce the
amo unt of docu men tatio n that needs to be creat
ed in man y
programs.
In fact, docu men tatio n shou ld be treat ed as the
chef treat s his
or her pots , pans, and cook book s. Accu mula ting
the prop er
ingredients is only part of the prep arati on of a
fine dish, just as
coding the prop er algorithms is only part of the
prod uctio n of a
good program. A program must display its auth
or's pride and skill
in both its exec ution and its docu men tatio n.
In this chap ter, we will discuss a wide variety
of techn ique s that
fall into eithe r one of two broa d categories: inter
nal or exter nal
docu men tatio n.

Inter nal As a class of techn ique s, inter nal docu men tatio
n includes all
Docu men tatio n meth ods of explaining a prog ram' s workings from
with in the
program itself. You will see that it means more
than a liberal dose
of REM state men ts, altho ugh that is an impo rtant
cons idera tion.

179
r to
Program Comm ents The REM statem ent provides a meth od for the progr amme
struct ure witho ut
write a comm ent abou t a statem ent or program
any sizeable
altering the progr am's execu tion. The first few lines of
in the form of
program should include the following inform ation
remarks:
ion.
1. Program ID-fi le name and brief statem ent of funct
2. Auth or ID-n ame and date of progr am creati on.
3. Revision ID-n ame, date, and numb er of revision.
In many micro comp uters, including the TRS-80, REM
memo ry
statem ents suffe r the disadvantage of occupying valuable
ns of their work ing
space. Many programmers keep two versio
highly reada ble, and it is
programs: One is rich with comm ents and
ed of all REM statem ents,
generally kept on file; the other is stripp
chang e must be made in the
and used for execu tion only. When a an
docum ented progr am as
program, the progr amme r lists the well
appro priate chang es are made
aid in locating the area of change. The
n runs prope rly,
in both programs, and when the undo cume nted versio
the docum ented version is restored on file.
familiar
REM statem ents come in a variety of forms. The most
ated solely to a remar k.
one is the single line that is dedic

10 REM PROGRAM TO COUNT VIRUSES

500 I SUBROUTINE TO CONVERT SPEED OF LIGHT


510 I TO FURLONGS PER FORTNIGHT

3000 I REMOVE UNWANTED RECORDS

lines.
Other REMs appear as last statem ents in multi statem ent

50 A=At1: REM COUNT THIS VIRUS

550 V=2:¥.X +R I CALCULATE VENOUS FLOW

2250 X( I )=X< I )-·N REDUCE VOLUME CALCULATED

180 Chapter 11 Documentation

·~ '
1, ,.

A word of caution concerning remarks in a multistatement line:


Take great care to avoid inserting a remark between two statements
on the same line. It is easy to do this in Level II BASIC because the
line's length can be up to 25 5 bytes, and the down-arrow ( +)
provides a neat way to return the carriage and provide a line-feed
without generating the /EN/ (hex OD) character that marks the end
of the line. But a REM between two statements on the same line
makes all statements after the remark a part of the remark. For
example, don't do this:

10 X=Xtl: I INCREMENT x: Y=Ytl: I INCREMENT y


The statement Y=Y+l is seen by BASIC as a part of the remark
following the statement

X=Xtl
Right-justified or indented REM statements are often more
easily distinguishable from the active BASIC statements. Consider
the two following examples:
10 DIM X(100)! CLS
20 INPUT at OF GROUPS";NG I INPUT THE LIMITING
30 INPUT nGROUP SIZE";N I SIZES FOR THE SAMPLE

500 I
SUBROUTINE FOR ANOVA.CALCULATIONS
510 FOR I=l TO NG
520 I TREAT EACH GROUP SEPARATELY
530 S( I >=O : 52( I )=0

If your printer prints lower case as well as upper case


characters, you can use lower case for remarks. This technique is
used in many examples in this book.

Window boxes A very distinctive form for remarks is called the window box.
This form visually isolates titles, and is particularly effective for
major program headings and structure and subroutine titles.
10
********************-************
I

20 I
FILE EDITING
30 ,
40 I
******************************

Chapter 11 Documentation 181


1000 I

1010 I SORT THE ARRAY


1020 I

1030 I

2000
2010
I

I *
*******
2020 I
*************
2030 I tttttt INPUT tttttt
2040 I
*************
2050 I
*******
2060
2070
I

I *

1
2
I
I
***************
* ************************
G-E-N-E-A-L-0-G-Y
3 t A MANAGEMENT SYSTEM FOR RECORDS t
*t
1

4
5
I *t OF ANCESTRY AND KIN
BY
6 * ALICE x. HOLEY *
7
I

I * 7/4/76 * r ",

89 I
I
**************************************
Blank Lines and A lot of information about a program's structure and logic can
Text Formatting be conveyed without words. In some cases, the insertion of a blank
line (actually there's an apostrophe as a first character) is enough to
demarcate one program structure from another. In other instances,
a programmer can tell a lot about the program's actions by indenting
certain lines.
Examples:

1000
1010
I
*******************
FIELD RECORDS
I

1020 , *****************
1030 I

1040 FIELD 1, 255 AS X$


1050 I

1060 FIELD 2, 4 AS F1$, 4 AS F2$r 4 AS F3$,


4 AS F4$, 4 AS F5$, 4 AS F6$,
4 AS MS
1070 I

182 Chapter 11 Documentation

l '
100 FOF: 1=1 TO NG DO BY GROUPS
11(l FOR J=1 TO N< I ) I
DO BY QB,JECTS
120 -------
130 -------
140 -------
150 NEXT J
160 -------
170 -------
1so NEXT .1.T

50 IF P<Q THEN X=Xt1: L=SQR(M)


ELSE J(I )=!J

300 IF A<B THEN IF B<C THEN Q=V


ELSE Z=V
ELSE X=V
Grouped One of the most obvious signs of a programm er's attention to
Line Numbers the clarity of the program's logic is the proper selection of line
numbers to be grouped within structures . For example, during the
initial stages of program design you should try to group the Level 0
structure, the main or driver portion of the program, within lines 1
to 999. Then you can reserve blocks of line numbers for various
other structures : Lines numbered 1000 to 1999 for the first module
of Level 1, 2000 to 2999 for the second module, and so on. Then
the second level can be blocked into the ten thousands . This makes
any modificat ion to the program fairly simple.
A number of commerci ally available line renumber ing programs
can be very useful for grouping line numbers. It is possible to
selectively renumber lines past a certain value with these programs.
This allows you to modify one structure at a time, starting with a
low level and working up.

External
Documen tation

Structure Charts The first documen tation of a program is a set of written notes,
possibly a phrase flowchart . Its purpose is to organize on paper
some of the structural requireme nts of a program. This should be
replaced immediat ely with a general structure chart for the program.
The structure chart can be modified as the program is composed and
tested, but its overall design should remain essentially constant.

Chapter 11 Documentation 183


Symbolic During the coding and testing phase of a program, it is often
Flowcharts necessary to unravel the intricacies of an algorithm, or to create a
new symbolic flowchart as the algorithm is coded. This form of
external documen tation is useful during coding to record visually the
logic of a specific module, so that it can be modified without
destroyin g its logic. Sometimes the lucky programm er has symbolic
flowcharts already prepared from some other source. If not, the
algorithm may be coded first from a phrase flowchart ; then the
symbolic flowchart is drawn to record the algorithm in some
language-free form for future use.

Run Books Once the program or system of programs is written and tested,
it needs to be released to the user, who is most often someone
totally unfamiliar with the code itself. The programm er must
inform the user how to run the program, how to answer its questions,
and what to do in case of specific anticipate d failures. Some of these
directions can be included in user prompts within the program.
Some overall guiding directions can be given in a set of PRINT
statement s when the program begins to execute. But the most
importan t directions, those that tell the user how to load the program
and its ancillary files and how to get it running, cannot have internal
directions. They must be written into an external documen t called a
run book, or user manual. Run books range in size from a
three-by-five printed card that can be pasted onto an obvious place
near the computer to a full set of books that detail the programs '
actions for an entire system.
Run books usually start with a section that tells the purpose of
the program, followed with a section written in cookbook fashion on
how to start execution of the program. Then various other sections
can be included, such as how each module works, what the range of
answers should be for certain inquiries, and what to do in case of a
program or hardware failure. Programs that areprodu ced for
commercial purposes are often sold primarily on the basis of the
quality of their run books.

Help Files Aside from charts and run books, there exists a third kind of
external documen tation which has gained increasing acceptanc e as
timesharing systems have become more popular. This form of
do cum entation is called the help file. A help file is a set of records
accessible from within a program which gives informati on about a
certain module of a system or porgram. This file is usually opened
on demand from the user with a response of "HELP" instead of the
normal response to a program's question. For example, suppose the
user is presented with this menu and doesn't understan d it.

184 Chapter 11 Documentation


WORD PROCESSING SYSTEM
1. GENERATE RAW DOCUMENT FILE
'")
"· . EDIT RAW DOCUMENT FILE
3. LIST RAW DOCUMENT FILE
4-. RUN FINAL DOCUMENT GENERATOR
C'
..J+ EDIT FINAL DOCUMENT
6. PRODUCE N FINAL DOCUMENTS
TYPE DIGIT OR 'HELP' OR 'HELP N':

If the user is not sure of the overall purpose and actions of the
system, entry of the word "HELP" as an answer opens a file of text
that is displayed on the screen. If there is doubt about how to run
any one of the six listed modules , the user can type the word HELP
immedia tely followed by the digit correspo nding to the desired
activity. For example, the response HELP 5 would open a file of
text that explains how to list a raw docume nt file.
Docume ntation and program structuri ng techniqu es, as discussed
in this and previous chapters , represen t an importa nt aspect of the
program mer's craft. Equally importa nt is a working knowledge of the
techniqu es that a program mer uses to structure and manage the
various files that the programs access.

Chapter 11 Documentation 185


File Manipulation Programs that deal with files must be thought out very carefully
Techniques because they use data that is stored in some fairly permanent
fashion. The files are not just an extension of the computer's
high-speed memory. They provide a method of computer-accessible
storage for masses of data that sometimes represent months or years
of accumulated work.
The records in a computerized file are managed much as records
in a manually maintained file in some office's steel cabinet. This
chapter will discuss some of the various techniques of building,
accessing, modifying, deleting, and sorting sequential and direct
access files.

Building The first phase in any dealings with computerized files is


building them. They have to exist on the disk before they can be
accessed in any way for any purpose.

187
Building Sequential disk files, as you remember from the discussion in
Sequential Files chapters 6 and 7, require special handling. String variables that are
printed next to each other must be separated by a comma.
You may use the PRINT # statement either as part of a
subroutine or within the main flow of the program. As an
alternative method to the usual PRINT # statement followed by a
series of variables names, you may build a single long string variable
to be decomposed into its component variab'Ies on input.
A typical file building subroutine is shown in program C 12P 1,
starting at line 1000.

10 'FILENAME: "C12F'1"
20 'FUNCTION! DEMONSTRATE HOW TO BUILD A SEQUENTIAL FILE
30 I AUTHOR : JPG DATE: 6/80
40 I

50 'user will SUPPlY N sets of names, each set up to 50 names


60 CLEAR 2000! DEFINT A-Z! CLS: DIM N$(50)
70 INPUT •HoW MANY SETS OF NAMES"iN
80 INPUT "HOW MANY NAMES IN EACH SET"iS
90 'inPut arraY of na~es into memorY one at a time
100 FOR 1\=1 TO N
110 FOR I=1 TO S! PRINT "NAME";z;: INPUT NS<I>! NEXT I
120 INPUT "WHAT IS FILE NAME" ;FS
130 GOSUB 1000 'FILE ARRAY ONTO DISK
140 NEXT K~ GOTO 1070
1000 'subroutine for buildins seauential file ·
1010 CLOSE: OPEN "0",1,FS 'FS is file name
1020 'let user see what sets stored
1030 FOR I=l TO 5
1040 PRINT H NS< I )
1050 PRINT Jl, CHRSC34)iNS<I );CHR$(34);
1060 NEXT I! CLOSE! RETURN
1070 END
Sometimes it is desirable to prepare the sequential output
variables as a string separate from the actual file building subroutine.
Program Cl2P2 below shows how a string array N$ can be used to
hold logical records that contain both numeric and string variables.
It uses the identical builder subroutine starting at line 1000 as in the
previous program.

188 Chapter 12 File Manipulation Techniques


10 'FILENAME: uC12P2u
20 'FUNCTION: ANOTHER WAY TO BUILD SEQUENTIAL FILES
30 I AUTHOR : JPG DATE: 6/80
40 I

50 CLEAR 2000: DEFINT A-Z: CLS: DIM N$(50>


60 'inPut arra~ of co•Posi te sirinss
70 FOR 1=1 TO 50: PRINT "NAME ('END' TO STOP)";I;
80 INPUT AS
90 IF AS="ENDu THEN N=I-1: GOSUB 1000! GOTO 1080
100 'accePt rest of data ohl~ if not end
110 INPUT "AGE";A: INPUT "WEIGHT";W
120 INPUT "SEX <H OR F>;ss: INPUT "PT SCORE";py
130 'build composi te string
140 Nt<I>=ASt";"tSSt";"tSTRS(A)tSTRSCWltSTRSCPT>
150 NEXT I
160 PRINT "ONLY 50 STRINGS ALLOWED IN THIS BUILDER"
170 PRINT NYOUR 50 ENTRIES WILL BE SAVED."
180 N=50! GOSUB 1000: GOTO 1080
1000 'seauen tial file buildins subrouti ne
1010 'N = number of losical records
1020 CLOSE! OPEN "0",1,FS 'FS is name of file
1030 'let user see what is stored
1040 FOR I=1 TO N
1050 PRINT I;NSCI)
1060 PRINT 11, CHR$(34); N$( I); CHR$(34};
1070 NEXT It CLOSE! RETURN
1080 END

Building Direct The TRS-80 disk system allows two basically different methods
Access Files with to build direct access files. The first method is universally permissible
Hash Addressin g on any computer system with direct access files: You PUT the
records to the file one at a time in sequence, with the first PUT
placing informati on on record #1, and the Nth PUT placing
informati on on record #N. The second method of direct access file
building is not always available on a given computer . It allows you
to PUT a record into the lth position of the file without having
written any of records 1 through I-1. This latter method makes
hash addressing easy to implemen t. A hash address is a calculated
record number that is generated from a record's key, that part of the
record which uniquely identifies it. Since the first method was amply
demonstr ated in chapter 8, we will include here an example of the
second technique .
Suppose you want to build a file of names in which the names
are the unique keys. The following are the assumptio ns and
condition s for the program:
I. The number of names is exactly 45. They are to be found in
a sequentia l file generated by the merge operation described
in chapter 7.
2. There is room for a direct access file of up to 75 records.

Chapter 12 File Manipula tion Techniqu es 189


3. The key of the record is the name itself. That is, once the
direct access file is built, the name will be used to access the
proper record directly.
4. The record number (the record's position on the file) will be
calculated by the program as a unique number between 1
and 45 inclusive. If one name happens to generate the same
record number as another name, the second record will be
placed in the overflow area, which consists of positions 46
· through 75 in the file.

Figure 12.1 shows a structure chart for this direct file builder
program Cl2P3.

IO
~\\J
I)~ Rle:
I
I I I
IOO 2..00' ~co 1.\-00
'!11\:,-\-\o..\\~ l:.v\pl.)-\ No..wtcr. wr:,~ tJc,.~ C..\asc I i

~f:.i\o/ %OM OV\ f-ile H\~


F-IE.L.D ~~\fi\c
I
I I
Z.Ooo !.,.:lOQ '3.\ 00

~~Erl ~('\~~~
~E::-('-G.~
~rd ~~0"'~'
~ ~~~!f-low
Figure 12.1 Structure Chart for Program C12P3

190 Chapter .12 File Manipulatio n Techniques

t : ~J
10 'FILENAME! uC12P3 11
20 'FUNCTION: DIRECT ACCESS FILE BUILDER
30 IAUTHOR : JPG DATE: 6/80
A·O "'
50 CLEAR 2000: CLS
60 'set name of seGu entia l file used for inPu t
70 INPUT "what is inPu t (seG uenl ial) file
80 OPEN "I",l ,Fl$ narue";Fl$
90 '~et name of dire ct acce ss file used for outP
100 INPUT "what is outP ut (dir ect acce ss) file ut
110 OPEN "R"t2rF2S: FIELD 2, 2 AS NN$, 30 AS NA$name";F2S
120 'NNS is reco rd number, NAS is store d name
130 'sel up looP lo read all 45 reco rds from inPu
140 LPRINT "SAl name"; t file
150 LPRINT TABCJO); "hash rec. cont ents" ;
160 LPRINT TABC52)i "wri tten on"
170 FOR 1=1 TO 45
180 INPUT ll,NS
190 LPRINT I; TABCS); N$;
200 GOSUB 1000 'sen erat e hash addr ess base d on name
210 GOSUB 2000 'felc h the hashed addr ess reco rd
220 if reco rd not on file CR<>N) write rec, in
230 ' H on file CR=N) wr·it e r·ec. in over·flow ar·ea
Prime area
240 IF R=N THEN GOSUB 4000 'set over flow addr ess"
~.'5() GO SUB 300 0 'wr- i it• r· ecord
260 NEXT I
270 GOTO 10000
:1.000 I Sene rate a hash addr ess
1010 S=O
1020 FOR J=1 TO LENCN$)! S=S+ASC<MIDSCN$,J,1)):
NEXT J
1030 K=S/45! N=CK-INT<K>>*45! N=INT<Nt1.1) 'to
1040 LPRINT TAB<JO); N; near est int. +1
1050 RET URN
2000 ' set hash ed reco rd
2010 GET 2tN! R=CVICNN$)
2020 IF R<>N THEN NBS="sarbase"
ELSE NBS=LEFTS<NA$?10)
2030 LPRINT TABC35); R; TAB(40); NBS;
204(1 RETURN
3000 ' wr-ite reco rd
3010 LSET NAS=NS: LSET NNS=MKIS<N)! PUT 2,N
3020 LPRINT TAB<59);N
3030 RETURN
4000 1 sene rate over flow area addr ess
4010 FOR J=46 TO 75
4020 GET 2,J: JJ=CVI<NNS>
4030 IF JJ=J THEN NEXT ,J 'this reco rd is occu Pied
4040 N::,J I this is the one
4050 LPRINT TABC53); "oflo w";
4060 RETURN
10000 CLOSE: END
Chapter 12 File Manipulation Techniques
191
name hash rec. cont ents writ ten on
SAt sartt aSe 26
1 ALIQUOT ALICE 26 0
34 0 sar-base 34
....
.:. ANOMALY ANNABELLE 27
3 ANOMALY ANTHONY 27 8370 sar-base
10 -6683 sar·b ase 10
4 ASININE ARNOLD 14
.,..J BANDERSNATCH FRUMIOUS 14 10981 sar·b ase
32 13088 sar-base 32
6 BELLER ELLERY low 46
7 CUERVO CERVESA 32 32 BELLER ELL of
'1'1

8 ENEMA ANOMIE 22 13618 sarb ase .L~

45 -6683 sar-b ase 45


9 FISTULA FELICITY 4
10 GABLE MARK 4 -6683 sarb ase
10 ASININE A~: of low 47
11 GNASHGNAT NATHANIEL 10
8
12 GROMMET ANDROMEDA 8 8250 sarb ase
37 -24031 sarb ase 37
13 HARSHBARGER HERSCHEL AR of low 48
14 HEGIRA IRA 10 10 ASININE
9 -6683 sarb ase 9
15 LANCASTER BART 23
16 LANCHESTER ELSIE 23 -6683 sarb ase
18 12628 sarb ase 18
17 LAVORIS MORRIS ase 11
18 LOOSELIPS LINDA 11 -13569 sarb
35 4215 £1arb ase 35
19 MERGER MA~:GINAL 6
20 MINDERBINDER MILO 6 -13569 £1arbase
17 17744 sarb ase 17
21 MONACO MONICA £1e 12
22 MUSHMOUTH MUNGO 12 -14533 sarba
9 9 LANC ASTE R oflow 49
23 PARSLEY PELVIS MARt\ of low 50
24 PA~:VENU MARVIN 4 4 GABL E
32 32 BELL ER ELL of low 51
25 PATELLA PETEF: 28
26 PONTIAC CARLO 28 8224 sarb ase
1(1 10 ASIN INE AR of low 52
27 POWER CYCLONE CA of low 53
28 RUBELLA ELLA 28 28 PONT IAC
20 -6683 sar·b ase 20
29 SAL IVA TELLY ase 44
30 SIDDHARTHA GHAUTAMA 44 -668 3 sarb
44 44 SI r!IIHA RTHA oflow 54
31 SITHLE SAMANTHA AN of low 55
32 SITHLE SIBILANT 8 8 GROM MET
4 4 GABL E MARK of low 56
33 SITHLE SIMEON A ANOM of low 57
34 SITHLE SYBIL 22 22 ENEM
6 6 MIND ERBIN D of low 58
35 UVULA URSULA 30
36 VERMIFORM VERNON 30 8250 sarb ase
23 LANCHESTER of low 59
37 WEEIIEATER WANDA 23
41
38 WHEREWITHALL WILLY 41 -668 3 sarb ase
37 37 HARS HBA~ :GE of low 6()
39 WOMBAT WILLY of low 61
40 WOMBAT WILLY 37 37 HARSHBAr:GE
12 12 MUSH MOUT H of low 62
41 ZOTZOT XAVIEF: ase 7
42 ZOTZOT ZELDA 7 1489 6 sarb
37 37 HARSHBA~:GE oflow 63
43 ZOTZOT ZEF'PO 33
44 ZOTZOT ZIGGY 33 14936 sarb ase
41 41 WHEREWITHA of low 64
45 ZOTZOT ZIPPO

192 Chap ter 12 File Mani pulat ion Tech nique s


Accessing The process of accessing a record involves reading the record
from the direct access or sequential access file, and storing the
informati on on the record into memory.

Accessing Sequential access files can be loaded into memory one record
Sequentia l Files at a time, or they can be copied into an array in their entirety. The
GEOGRAPH program uses the latter technique to fill the record
pointers, location names, and location descriptors.

Accessing
Direct Access Files Direct access files may be read either sequentia lly one record
at a time from the first to some desired key, or directly by accessing
a specific record according to its calculated hash address. The two
programs that follow show both techniques.

10 'FILENAME: "C12P4"
20 'FUNCTION: DIRECT ACCESS IN SEQUENTIAL ORDER
30 ' AUTHOR : JPG DATE! 6/80
40 I

50 CLEAR 2000! CLS


60 INPUT "Exislin s direcl access file name";F2$
70 OPEN "R",2,F2$! FIELD 2, 2 AS NN$, 30 AS NA$
80 'read all records in order' Print blank line when no record
90 LPRINT "All records on file": LPRINT
100 FOR 1=1 TO 45
110 GET 2,1: N=CVI(NN$)
120 ' if N is not I then record Position is not used
130 IF N=I THEN LPRINT I;NAS
ELSE LPRINT I;" "
140 NEXT I
150 'r·ead over·f low ar·ea
160 FOR I=46 TO 75
170 GET 2d! N=CVI< NNS)
:!.80 IF N=I THEN LF'RINT UNA$
ELSE LF'RINT I;" II

190 NEXT I
1000(1 CLOSE! END

Chapter 12 File Manipula tion Techniqu es 193


All record s on file
1
..,.
,J
4 GABLE MARK
£!"
.J
6 MINDERBINDER MILO
7 ZOTZOT ZELDA
8 GROMMET ANDROMEDA
9 LANCASTER BART
10 ASININE ARNOLD
11 LOOSELIPS LINDA
12 MUSHMOUTH MUNGO
13
14 BANDERSNATCH FRUMIOUS
•i£:"
···'-'
16
17 MONACO MONICA
18 LAVORIS MORRIS
19
20 Sc~Ll VA TELL Y
21
22 ENEMA ANOMIE
23 LANCHESTER ELSIE
24
....,r.:·
·L".i
26 ,;LICWOT ALICE
27 ANOMALY ANTHONY
28 PONTIAC CARLO
29
30 VERMIFORM VERNON
31
32 BELLER ELLERY
33 ZOTZOT ZIGGY
34 ANOMALY ANNABELLE
35 MERGER MARGINAL
36
37 HARSHBARGER HERSCHEL
38
39
40
41 WHEREWITHALL WILLY
42
43
44 S!IIDHARTHA GHAUTAMA
45 FISTULA FELICITY

194 Chapte r 12 File Manipu lation Techni ques


46 CUERVO CERVESA
47 GNASHGNAT NATHANIEL
48 HEGIRA IRA
49 PARSLEY PELVIS
50 PARVENU MARIJIN
1:"'
,JJ. PATELLF1 PETER
52 POWER CYCLONE
53 RUBELLA ELLA
54 SITI-ILE SAMANTHA
55 SITHLE SIBILANT
56 SITHLE SIMEON
1:""1
..JI SITI-ILE SYBIL
58 UVlJI.. A URSULA
59 WEEIIEATER WANitA
60 WOMBAT WILLY
61 WOMBAT WILLY
62 ZOTZOT XAVIER
63 ZOTZOT ZEPPO
64 ZOTZOT ZIF'F'O
65
66
67
68
69
70
71
7'1
J t..

73
74
75

Chapter 12 File Manipulation Techniques 195


10 'FILENAME: "C12P5"
20 'FUNCTION: DIRECT ACCESS BY HASH ADDRESS CALCULATION
30 AUTHOR : JPG
I DATE: 6/80
4(J I

45 CLEAR 2000: CLS


50 INPUT "Existins direct access file name";F2S
60 OPEN "R",2,F2S! FIELD 2, 2 AS NNSr 30 AS NAS
70 ·~et name from user
BO INPUT nname ('end' to stop)"iNS
85 LPRINT "narue sousht is ";Ns;
9(1 IF N$="end" THEN 10000
ELSE GOSUB 1000 'Set hash address
:l(JO GET 2,N! L=LENCNS)
120 IF NS=LEFTSCNAS,L) THEN LPRINT TABC40>i "on record t";N:
GOTO 70
ELSE GOSUB 2000 'read oflow area
140 IF R<>O THEN LPRINT TABC40)i "found on overflow tn;R
ELSE LPRINT TAB<40}i "not on file"
150 GOTO 70
1000 ' senerate hash address
1010 S=(l
1020 FOR 1=1 TO LENCNS)
1030 S=StASC(MIDS(N$,I,1 ))
1040 NEXT I
1050 K=S/45: N=<K-INT(K})I45: N=INTCNt1.1}
1060 RETURN
2000 ' read overflow area
2010 FOR J=46 TO 75
2020 GET 2,J
2030 IF NS=LEFTS<NAS,L) THEN R=J: GOTO 2100
ELSE NEXT J
2040 R=O 'not on file
2100 RETURN
10000 CLOSE: END

nan.e sousht is MINDERBINDER MILO on recor-d t 6


nan.e sousht is SITHLE SIBILANT found on overflow t 55
nan.e sousht is MERGER MARGINAL on record t 35
nar~.e sou!:lht is SUBLIMINAL SAMUEL not on file
nante SO\E':lhi is UVULA URSULA found on overflow t 58
na111e sousht is end

196 Chapter 12 File Manipulation Techniques

I.;
Modifying Direct access files have a major advantage over sequential access
flles when you have to modify just one record. Consider the process
that is required when modifying a sequential file:
1. Open old file for input. Open new file for output.
2. Read all records on old file and write out on new file until
proper record is found.
3. Change the record that needs modification.
4. Write out changed record on new file.
5. Read the rest of the records from the old file, and write
them out onto the new file.
When one record of a direct access file needs modification, it
can be done without reading any other records, and without having
to create a new file.

Deleting Deletion is the file operation that results in an unwanted record


being culled or purged, and it is normally performed in two steps.
The first step is to mark a record for future deletion. Numerous
records can be marked, perhaps 10 or 20 percent of a file's contents
are records marked for deletion. The second step is to rebuild the
file excluding the marked records.
Marking records for deletion can be done in one of two ways:
1. A specific numeric value that appears in every record, such
as record number or age, can be assigned a negative value or
an unlikely value, such as -32767.
2. A string can be replaced with a flag or marker, signifying the
fact that it has been marked for deletion.
Deleting the records is accomplished by rewriting the file one
record at a time, omitting the flagged records.

Sorting Of all the operations that can be done on a file, its arrangement
into some predetermined ascending or descending order seems to be
one of the most common and troublesome. You can sort a file using
any of three basic approaches:
1. In-memory sort
a. Read the file into an array in memory.
b. Sort the array in memory.
c. Write the memory array back out onto the file.
2. Record-by-record sort
Rearrange the records on file by reading them two at a time,
and switching their positions when necessary.
3. Sort-merge
a. Read the file a portion at a time into an array in memory,
sort each portion in memory, and create a series of new
sub-files.
b. Merge the sub-files into a single large file.
In all three approaches, the key operation is the sorting
operation itself, which rearranges the records into the desired order.
The choice of sorting algorithm to do this is critical to the overall

Chapter 12 File Manipulation Techniques 197


speed of the operation. We will discuss this choice of algorithms
shortly, but first you must consider which type of program you
should use: ·In-memory, record-by-record, or sort-merge.
The in-memory sort is by far the fastest, if you have the
memory space. The array in memory must be able to hold the
entire file, and in the case of 255-byte logical records that occupy
the entire physical record, this could mean that the file would have
to be quite small. Consider the case where the sorting program itself,
not including the array, occupies 2000 bytes. In a 16K disk system,
the memory that is left for the sort is only about 3800 bytes. In a
32K system, the space is a more respectable 20,000 bytes. And in a
maximum system of 48K, the total space free for the array is roughly
36,400 bytes. Study of the table 12.1 will give you a feel for the
effect of memory size on the computer's capacity to sort arrays of
records. Table 12.1 points out a rather disturbing fact: If you have
a 16K system, you cannot store more than 14 physical records of
255 bytes each in the computer's free memory. However, all is not
lost. If your file is longer than the 14 maximum records, it can still
be sorted. This is because it is a direct access file and it can be sorted
record-by-record. However, this second technique is between 100
and 1000 times slower than an in-memory sort!
We suggest that whenever the file is too large to fit into memory
to be sorted there, you should use a combination of the in-memory
and record-by~record sorts, which is the third technique, the '·1

sort-merge. We have discussed and demonstrated the sort-merge in


chapter 7 when it was shown operating on a sequential file.

losical " s~stem Size (free memorY)


Record Size " 16K 32K 48K
in B~tes II
(3800) (20,000) (36,400)
================+===================================
II

255 II
14 78 142
128 II
29 156 284
64 II
59 312 568
32 II
118 625 1137
16 "n 237 1250 2275
8 475 2500 4550
4 II
950 5000 9100
Table 12.1 Number of Records That Can Be Sorted in Memory

198 Otapter 12 File Manipulation Techniques


Sorting Algorithms · Aside from the medium on which the array to,be sorted is
located, which is either memory or disk, the single most important
factor that determines the speed of the overall operation is your
choice of sorting algorithm. The choice is rather large and varied,
but there are some algorithms that are clearly better than others.

Exchange Sorts The class of sorting algorithms known as exchange sorts


includes the bubble sort, delayed exchange sort, and direct exchange
sort. They are all very slow and unfortunately are often found in
many otherwise good systems of programs.

Binary Sorts The better sorting programs all use binary sorts of one form or
another. These algorithms rely on the fact that one can sort two
sets of 50 elements with subseqUent merging faster than one sort of
100 elements; one can sort twenty sets of five elements with
subsequent merging faster than five sorts of twenty elements; and
one can sort 50 sets of two elements with subsequent merging faster
than 25 sets of 4 elements. It is the comparison and subsequent
rearrangement, or switching, of the elements that takes the time,
and not the merging.
We will show you two recommended methods for sorting: the
Shell (really, a variation called the Shell·Metzner) and the Quicksort
(one word). The Sheil-Metzner sort was used previously in the
Sequential File Sort-Merge program in chapter 7. We will not explain
how these two sorts work, but we will show each of the sorts in two
forms: Symbolic flowchart and BASIC subroutine. For those of
you who are curious about the techniques of sorting and wish to
study how they work, we suggest that you investigate Knuth's
Volume 3 of the Art of Computer Programming: Sorting and
Searching..

Chapter 12 File Manipulation Techniques 199


l.~l-M

N ·ls V\l.lvv.loE:<" at- c\t..v.~ +o b~ s.cMe-c\


X. \.s. V\o..W'{::: ~ ~~ ~1v\3 sortEd,

Figure 12.2 Shell-Metzner Flowchart

200 Chapter 12 File Manipulation Techniques

k -·)

I.)
f •

Figure 12.3 Quicksort Flowchart

Chapter 12 File Manipulation Techniques 201


Program Cl2P6 demonstrates three sorts: exchange,
Sheil-Metzner, and Quicksort. The program times the sorts, so you
can get a sense of their relative efficiencies.

10 'FILENAME: °C12P6"
20 'FUNCTION: TO DEMONSTRATE SORTING ROUTINES
30 I AUTHOR : JPG DATE: 7/80
40 I

50 CLEAR 300
60 DEFINT A-z: DIM X(1000), STK<700)
70 INPUT how manY numbers to sort";N
0

80 FOR 1=1 TON: X<I>~RNDC900 )t99! NEXT I


90 PRINT "choose sort»: PRINT "1 exchan~e"
100 PRINT n2 Shell-MeLzner": PRINT "3 Quicksort"
110 INPUT nwhich one";c
120 GOSUI! 160: BS=:TIME$
130 ON C GOSUB 1000, 2000, 3000
140 CS=TIMES! GOSUB 160
150 PRINT cs: PRINT BS: GOTO 70
160 FOR I=l TON! PRINT XCI>;: NEXT It PRINT: RETURN
1000 **exchan~e sorL**
1010 FOR 1=1 TO N-1
1020 FOR J=Itl TO N
1030 IF X< I >>X< J) THEN T=X< I>: X< I >=X( J H X< J >=T
1040 NEXT J
1050 NEXT I
1060 RETURN
2000 ' **Sheil-Metzner sorL**
2010 M=N
2020 M=INH M/2)
203(1 IF M=O THEN 2120
204(1 K=N-M! J=1
2050 I=J
2(l6(l L=I+M
2()70 IF X<I><=X(L) THEN 2100
2(180 T=X<I>! XO>=X<L.>: X<U=T! I=I-M
2(190 IF I>=1 THEN 2060 ~. J

2100 J=Jtl
2110 IF J<=K THEN 2050
ELSE 2020
2120 RETURN

202 Chapter 12 File Manipulation Techniques


3000 IIQuicksortll
3010 P=O: R=PtP: STKCR+1 )=1: STK<Rt2l=N! P=Pt1
3020 IF P=O THEN 3150
3030 P=P-1: R=PtP! A=STK<Rtl )t B=STK<Rt2)
3040 Z=XCAJ: TP=A: BT=Bt2 'TP is top, BT is bottom
3050 BT=BT-·1
3060 IF BT=TP THEN 3110
3070 IF Z<=XCBTl THEN 3050
ELSE X( TP >=X< B.T >
3080 TP=TP+l
3090 IF BT=TP THEN 3110
3100 IF Z>=X<TP> THEN 3080
ELSE X<BT)=XCTP)! GOTO 3050
3110 XCTP>=Z
3120 IF B-TP>=2 THEN R=P+P! STK<Rt1l=TPt1!
P=Pt1! STK<R+2>=B
3130 IF BT-A>=2 THEN R=PtP! STK<Rtll=A!
P=Pt1: STK<Rt2l=BT-1
3140 GOTO 3020
3150 RETURN
10000 END

Table 12.2 below summarizes a few observed sorting times


using program C 12P6.

N " E>:ch. S-M G


=========+================================
20 u
5 5 5
n
50 24 16 16
100 n
94 33 29
200 " 382 93 73
500 " 221.7 303 184
Table 12.2 Sort Times in Seconds

Chapter 12 File Manipulation Techniques 203


Direct Access File Program Cl2P7 is included here to show the techniques that
Statistics Program have been explained in this chapter. We have selected statistics as an
area for data management because its records are often created,
edited, deleted, and sorted, as well as having various statistical
operations performed on them.

Structure Chart for Program C12P7, Statistics System

lO~

sto-..-\is-hc.s.
I
I I I
\00 z..oo lo.:l
~ Co..\e..~\;...1t-
M~r.;.
Si<-hs\-\c.s.,
tilE: \)o;:\-&...R\E: PriV\l- \«5\1 ~
I I
I I I I I
\Oo() 1100 Z.Ooo ~100 <2J:>o
Uf'tv' hIE-/ w.-'.-\c R.f<.nrrls, &lit Sor-t j)r-"w,-\-
l:.-1.~-IT ~1""'\V\\- o..n-
~

204 Chapter 12 File Manipulation Techniques

I )
The user of this program selects an activity from a menu that is
displayed by the program's first module. The main activities are
independent of each other, but subordinate to the main module.
The menu display looks like this:

10 'FILENAME! "C12P7u
20 'FUNCTION: GENERAL PURPOSE STATISTICS PACKAGE
30 ' AUTHOR : JPG DATE! 6/80
40 J

50 CLEAR 20000: DEFINT I-L


60 'maximum of 3 SrouPs of observation s,
70 I 4 variables Per observation
80 1
20 observation s? or subJects Per srouP
90 values , sums , sums of sas,, sad. sumsr corrs.
1(10 DIM X( 3,,iJ20 JrS( 3r4 )rS2( 3,4 hS3( 4 hR( 3r4r4)
1 Hl CLS
120 disPlaY menu
13(! PF:INT II S TAT I S T I C S
S Y S T E M": PRINT
140 PRINT "1 create artificial data"
150 PRINT "2 inPut real data"
160 PRINT 3 edit data ar·r·ay"
II

Chapter 12 File Manipulation Techniques 205


170 PRINT "4 sort data arraY"
180 PRINT "5 descriPtive statistics"
190 PRINT "6 correlation coefficient matrix"
200 PRINT "7 disPlaY data"
210 PRINT "8 store data on disk"
220 PRINT "9 sloP"
230 PRINT: PRINT "select Your choice by diSiL"
240 INPUT AS! SP=VAL(A$) 'SP for subroutine Pointer
250 IF SP<1 OR SP>9 THEN 130
260 ON SP GOSUB 1000,2000,3000, 4000,5000,
6000,7000,8000,9000
270 GOTO 110
280 ' u Li 1 i LY s u b r o u t i n e s
290 · chanse all LPRINTs lo PRINTs
300 POKE 16422,88! POKE 16423,4! RETURN
310 ' restore all LPRINTs to LPRINTs
320 POKE 16422,141: POKE 16423,5: RETURN ' J
330 ' chanse all PRINTs to LPRINTs
340 POKE 16414,141! POKE 16415,5! RETURN
350 ' restore all PRINTs to PRINTs
360 POKE 16414,88! POKE 16415,4! RETURN
370 1 Pron,pt and scr·een hold
380 INPUT "/EN/ to continue"; AS! RETURN
390 ' Load data file from disk
400 INPUT "file name";F$
410 ' set number of srouPs ~nd variables first
420 OPEN UJ",l,F$! INPUT t1, NG, NV
430 1 set number of subJects Per srouP next
440 FOR K=1 TO NG! INPUT t1, NM<K>! NEXT K '4 Per !P
450 FOR K=1 TO NG 'first by !roup,
460 FOR I=1 TO NM(K) 'then by subJect in Sroup,
470 FOR J=l TO NV I and last bY var·iable
480 INPUT u, xo::,J,I)
490 NEXT J,I,K! CLOSE: RETURN
500 ·' Store data arraY onto disk
510 ' save nutnber of srouPs and nun,ber of variables
520 OPEN "0",1,FS! PRINT tl, NG,NV
530 ' then save number of subJects Per sroup
540 FOR K=l TONG: PRINT tl, NM<K>: NEXT K
550 FOR K=1 TO NG
560 ' and last, the observations themselves
570 FOR I=1 TO NM<K>
580 FOR J=1 TO NV
590 PRINT t!J X( K, J, I )
600 NEXT J ri ,t\
610 CLOSE: RETURN ' '

206 Chapter 12 File Manipulation Techniques


H>OO I Create artificial data
1010 CLS: INPUT "how many SrOUPS (to 3)";NG
1020 INPUT »ranee of subJects Per erouP
<1 to 20 -- LYPe low & hiSh)";N1,N2
1030 INPUT »how manY variables Per subJect (io 4J";NV
1040 FOR K=1 TO NG 'K is srouP index
1050 NM<K)=RND<N2-N1)tN1
1060 PRINT "sroup";K, NMCK)"subJecls"
1070 FOR I=l TO NM<K> 'I is subJect index
1080 FOR J=1 TO NV 'J is variables index
1090 X(K,J,I>=RNDC90H9: PRINT X(K,.JdH
1100 NEXT J! PRINT,
1110 NEXT I: PRINT: GOSUB 370
1120 NEXT K: RETURN
2000 ' Data inPut
2010 CLS
2020 INPUT »data on file (yes or no)";A$
2030 IF AS="Yes" THEN GOSUB 390: RETURN
2040 INPUT "how many SrouPs (to 3)"iNG
2050 INPUT "how manY observation s Per subJect (to 4)";Nv
2060 FOR K=1 TO NG
2070 PRINT "how manY in eroup";K;: INPUT NM<K>
2080 FOR I=1 TO NM(K)
2090 PRINT "enter»; NVi »values for subJect J"; I
2100 IF NV=1 THEN INPUT XCK,1ti>: GOTO 2140
2110 IF NV=2 THEN INPUT X(K,1,I),X( K,2,1}! GOTO 2140
2120 IF NV=3 THEN INPUT X<K,1,I),~K,2,I>~XcK,3,I>:
GOTO 2140
2130 INPUT XCKd,I),X (K,2dhX(K ,3,IhX(K,4, I>
2140 NEXT I, K
2150 INPUT "save on file (yes or no)";A$
2160 IF AS="yes" THEN GOSUB 500
ELSE RETURN
2170 RETURN
3000 ' Edit data file
3010 FTS=" tit ttll.tt lllt.tt lttt.tt tttt.tt"
3020 IF NG=O THEN PRINT "no data!"! GOTO 3130 'return
3030 PRINT NG "sroups"
3040 FOR K=1 TO NG
3050 PRINT
"subJ. var. 1 var. 2 var. 3 var. 4"
3060 FOR I=l TO NM< t\)
3070 PRINT USING FT$;
I, XO\ddh X(K,2,Ih X(K,3J!), X0\,4,!)
3080 NEXT I
3090 LINE INPUT
"chanse which subJect (/EN/=no chanse)";A$
3100 IF A$<>"• THEN INPUT "which var. to what";J1,X2 !
XCK,Jl,VAL<AS>~X2: GOTO 3090
ELSE 3110
Chapter 12 File Manipulation Techniques 207
3110 NEXT K: INPUT "save this version (yes or no)"jA$
3120 IF AS="YES" THEN GOSUB 500 ~~o to SAVE subr.
3130 RETURN
4000 ' sort data usins Sheil-Metzner sort
4010 PRINT "what srouP ( 1 to" ;NG;" or all >";: 1 1

INPUT AS
4020 IF A$="all" THEN N1=1: N2=NG: GOTO 4040
ELSE NK=VAU A$>
4030 IF NK=O THEN 4200
ELSE N1=NKt N2=NK
4040 PRINT "on which kew C1 to";Nu;")";: INPUT Q
4050 FOR K1=N1 TO N2: M=NMCK1)
4060 M=INTCM/2): PRINT@ 245,M;
4070 IF M=O THEN 4190 ELSE 4080
4080 K=NM<K1>-Mt J=l
4090 I=.J
4100 L==I+M
4110 IF XCK1,Q,I><=X<K1,Q,L) THEN 4170
4120 FOR J1=1 TO NV
4130 T=XCK1,J1,I>t XCK1,J1,I>=XCK1,J1,L>:
X< K1 ,J1 ,L >=T
4140 NEXT J1
4150 I=I-M
4160 IF I>=l THEN 4100
4170 J=Jt1
4180 IF J<=K THEN 4090
ELSE 4060
4190 NEXT Kl
4200 RETURN
5000 I DescriPtive statistics
5010 INPUT "on screen (1) or Printer (2)";A
5020 IF A=2 THEN GOSUB 330 'set for Printer
5030 FOR J=1 TO NUt S3< J >=O: NEXT J 'srand su01s
5040 FOR K=l TO NG 'srouP bY srouP calculations
5050' CLS: PRINT "srouP t";t.:;, NM<K>
5060 PRINT "VAR","SUM","MEAN"r"STD. DEU."
5070 FOR J=l TO NV: S(K,J>=O: S2CKrJ)=0
5080 FOR JJ=l TO NV: RCK,J,JJ)=O: NEXT JJ
5090 FOR I=1 TO NM<K>
5100 S(K,J>=S(K,J)t X(K,J,I) 'su01s
5110 S2C K, J >=S2< K, J H XC K, J, I >*X< K, J, I )
5120 FOR JJ=l TO NV 'crossproducts
5130 RC K,J, ,JJ >=R< KrJ ,J,J HX< K,J ,r >*X< K,JJ, I>
5140 NEXT JJ
5150 NEXT I
5160 MCK,J>=SCK,J)/NMCK> 'means
5170 V=CS~K,J>-SCK,J>*MCK,J))/CNMCK>-1> 'vars.
5180 DCK,J>=SQR<V> 'standard deviations
5190 PRINT J, S(K,J), M<K,J), DCK,J)

208 Chapter 12 File Manipulation Techniques

I,,

'·!
5200 53( J >=53( ,J HS<t\,.J) I srand sums
5210 NEXT J: N=NtNM<K>
5220 IF A<>2 THEN GOSUB 370
5230 NEXT K
5240 PRINT "GRAND MEANS=";
5250 FOR J=1 TO NV: PRINT Jj53(JUN,: NEXT J
5260 IF A=2 THEN GOSUB 350 'reset for screen
5270 IF A<>2 THEN GOSUB 370 'promPt to continue
5280 RETURN
6000 ' Correlation coefficients
6010 INPUT "on screen (1) or Printer (2)";A
6020 IF A=2 THEN GOSUB 330 'set for Printer
6030 GOSUB 5030 · 'set descriPtive statistics
6040 FOR K=1 TO NG
6050 FOR J=l TO NV
6060 PRINT "var."; Ji
6070 FOR JJ=1 TO NV
6080 IF J=JJ THEN R(K,J,JJ)=1! GOTO 6120 'dias.
6090 T=R<K,J,JJ)-S(K,J>*S<K,JJ)/NM<K>
6100 B=NMCK>*DCK,J>*D(K,JJ)
6110 R(K,J,JJ)=T/B
6120 PRINT TABCJJ*10) USING "l.ttt"iR(K,J,JJ)i
6130 NEXT JJ: PRINT
6140 NEXT J: PRINT
6150 NEXT K
6160 IF A=2 THEN GOSUB 350 'reset for screen
6170 IF A<>2 THEN GOSUB 370 'promPt to continue
6180 RETURN
7000 ' list data arra!:f
7010 INPUT "on screen (1) or Printer (2)"iA
7020 IF A=2 THEN GOSUB 330 'set for Printer
7030 CLS: PRINT NG "grouPs",
NV "variables Per subject"
7040 FOR K=1 TO NG
7050 PRINT NMCK) "subjects in SrouP t" K
7060 FOR I=1 TO NK(K) STEP 2
7070 FOR J=1 TO NV
7080 PRINT X<K,J,I)i
7090 NEXT J! PRINT,
7100 FOR J=1 TO NV
7110 PRINT XCK,J,It1)i
7120 NEXT J! PRINT
7130 NEXT I: PRINT
7140 IF A=2 THEN GOSUB 350 'reset for screen
7150 IF A<>2 THEN GOSUB 370 'promPt to continue
7160 RETURN
8000 ' store data on disl<
8010 INPUT ''filenafite" ;F$! GOSUB SOOt RETURN
9000 ' closing routine
9010 CLOSE
9020 END
Chapter 12 File Manipulation Techniques 209
' '

210 Chapter 12 File Manipulation Techniques

I l
Chapter 12 File Manipulation Techniques 211
This chapter has shown by example several techniques that are
commonly used to manage, or manipulate, the records that exist on
sequential or direct access files. So far, we have assumed that the
information of the records is independent of the file's structure.
That is, no record has any information that relates to its position on
the file, or to the position of any other record on the file. We have
introduced one exception to that scheme, and that was the direct
access file structure generated by hash addressing, each record of
which had its record number embedded within the record as a data
entry.
In the next chapter, we will expand on the idea of a record
containing some information about its position on. the file. You
will discover fast acc~ssing methods, sorts that don't rearrange keys,
and a process for arranging the data file so that these techniques and
others are a part of the overall package.
Through development of a parts inventory system we will use
most of the ideas discussed in the previous chapters of this book.
The system is based on the Binary Sequence Search Tree structure
which has been thoroughly explained in Microcomputer Power:
1 Guide to Systems Applications.

,.
'.,

I;

212 Chapter 12 File Manipulation Techniques

' !
Inventory System The discussion and program listings that follow are all part of
Application an existing, working system that uses Binary Sequence Search Tree
file organizatio n and structure. It is a generalized inventory system
that maintains the data file's entries, whether they relate to shoes,
ships, or sealing wax. The programs are written to be non-specific
so that the reader may adapt them to whatever record-keeping
functions are desired.
Each record of the file occupies 63 bytes of a 256-byte phy-
sical record, or sector, on a direct access disk file. The records
consist of 13 fields and are detailed in table 13 .1.
The last record on the file has only three fields:
Field 1 (integer) is the root record number for the tree
structure.
Field 2 (integer) is the total number .of records.
Field 3 (string) is a file description .

213
Size Variable
No. T!:lF"e ( b!:ltes > Nan.e DescriPti on
1 Int. 2 LL left link of BSST
2 Int. 2 RL Rishi link of BSST
3 Sir. 12 PT$ Part number or name
4 Sir. 25 Des$ DescriPti on of Pari
5 Sns. 4 DP! Dealer Price' Per· unit
6 Sns. 4 LP! List Price, Per unit
7 Int. 2 OH Units on hand
8 Int. 2 00 Un i is on order
9 Int.. 2 SB Minimum stock GuaniitY
10 Int.. 2 M Units sold in Past ll1Dnih
11 Int. 2 N Units sold in Past. 3
months
12 Int. 2 0 Units sold in Past 12
months
13 Int. 2 p Units said in Past 24
months
Table 13.1 Inventory System Record Description

' '

r 1

Purpose Lines
--------------------------------------------------------
0 INVMAIN Main driver Prosram 700 20
1 INVF'Rl Add a Part to a file 4300 1Hl
2 INVF'R2 List Parts (sorted) 1800 50
3 INVF'R3 Delete a Part from a file 3300 90
4 INVPR4 Chanse a Part descriPti on 3600 llO
or informatio n about a Part
5 INVPR5 List the records in entered 1200 40
order-
6 INVPR6 List deleted Parts in a file 1100 30
7 INVF'R7 Balance BSST tree linKs 4500 120
8 INVF'RS List files in use 700 20
9 INVF'R9 Delete a file 17(l(l 30
10 INVF'R10 Show all informatio n on a 3600 so
selected Par-t
Table 13.2 Index to Programs in Inventory System

214 Chapter 13 Inventory System Application

' J
INVMAIN Program The entire system of programs runs from one central menu
driver program that both displays the list of activities and branches
to the program that performs the selected activity.
There are ten programs subordinate to INVMAIN in the
inventory system. Each one was designed to perform a different
task. Table 13.2 is an index to those programs, including their
names, purpose, and approximate size in bytes (to the nearest
hundred), and length in number of lines (to the nearest ten).

10 'FILENAME: "INVMAIN"
20 'FUNCTION: DRIVER PROGRAM FOR BSST INVENTORY SYSTEM
30 IAUTHOR SPG DATE: 1/12/79 REV: 7/80
40 I

50 '**
60 CLSt PRINT: PRINT: PRINT
dis P 1 a Y • en u
70 PRINT "0 N - L I N E I N V E N T 0 R Y S Y S T E H"
80 PRINTtPRINT
90 PRINT "1 add Parts 7 balance BSST tree file"
100 PRINT "2 list Parts (sorted) 8 list files in use"
110 PRINT n3 delete a Part 9 delete a file"
120 PRINT "4 chanse Part desc. 10 !el info. on a Part"
130 PRINT "5 list all records 11 stoP"
140 PRINT "6 list deleted Parts•
150 PRINT
160 LINEINPUT "Select your activity by nuabert "; AS
170 IF AS="" THEN 50
180 IF A$="11• THEN STOP
190 IF VAUA$)<1 OR VAUA$))10 THEN 50
200 P$="INVPR"tASt RUN P$
210 ENII

The output of the INVMAIN program is the menu display.


Here is what it looks like.

ON-LIN E I N VE NT 0 R Y S YS T E M

1 add Paris 7
I balance BSST ir'ee file
2 list Par is ( sorted ) 8 list files in use
3 delete a Par·t 9 delete a file
4 chanse Part desc. 10 !et info. on a Part
5 list all records 11 stoP
6 list deleted Parts

Select Your activitY bY number: 1~

Chapter 13 Inventory System Application 215


INVPRl The INVPRl program adds items to an inventory file.

1000 'FILENAME~ "INVPR1" <CALLED BY "INVMAIN")


1005 'FUNCTION! ADD AN ITEM TO THE INVENTORY
1010 I AUTHOR : SPG DATE: 1/19/79 REV. 7/80
1015 I

1020 DEFINT A-z: CLEAR 1000: FIRST=O


1025 CL.S
:I.•J30 ~u: set file name - FLS.
1035 FUi=""
1040 PRINT "Please tYPe either:"
1045 PRINT " the file name of an old file"
1050 PRINT " or"
1055 PRINT " 'helP' for a list of the files in use"
1060 PRINT " or"
1065 LINE INPUT "' 0 1
for· a new file! "; FLS
1070 IF FLS="helP" OR FLS="HELP" THEN RUN "INVPR8"
1075 IF FLS<>"O" AND FLS<>"" THEN 1175
1080 IF VALCFL$))0 THEN 1030 trw asain.
1085 1
new file. set its name.
1090 INPUT "What is this new file's name (to 8 chars. )";FLS
1095 IF FLS="" THEN 1030
1100 stor·e new fi .l.ename into file "FILENAME".
1105 CLOSE: PRINT "stand by ••• ": OPEN "R",l,FLS
1110 IF LOFC1)()0 THEN PRINT "File ";FL$;" alreadY exists":
GOTO 1030
1115 CLOSE: [!$=LEFTS( FL..S+" ",a) 'tr·ir11 to 8 chars.
1120 OPEN "R",1,"FILENAME": FIELD 1, 255 AS AS
1122 '**
1125 S=Stl
search for risht file.
1130 IF L..OF(1)=S-1 THEN BS=DS: L=l! GOTO 1145
ELSE GET 1 ,s
1135 FOR L=1 TO 255 STEP 8
1140 IF MI[ISCA$,L,1){)" THEN NEXT L: GOTO 1122
II

ELSE BS=LEFTSCAS,L-1 >+D$


1145
1148
I** D1S=MIDSCA$,L,1tLENCDS)-1)
store file descriPtion .
1150 IF DS<>D1S THEN LSET AS=BS: PUT 1,S: CLOSE
1155 CLOSE: OPEN "R",1,FL..S
H60 GOSUB 1800
1165 IF IEN=O THEN IEN=1t GOTO 1225
1170 1
set last record on file.
1175 '**
1180 CLOSE: OPEN "R"r1,FLS
OPen the file labeled FLS.
1185 I check to see if file exists --
1l. 9(1 t if not, so back to besinnins.
1195 IF LOF(1)=0 THEN PRINT" no such file ••• "t GOTO 1030
1200 I set record that has the root, etc.
1205 IF IEN=O THEN IEN=1
216 Chapter 13 Inventory System Application
1210 GOSUB 1700
1215 GET 1,LQF( 1)
1220 R=CVI<ROOTS>: NM=CVI(NMS): FLS=DESC$! IEN=LOF(l)
1225 CLS! PRINT "Diskette file descriPtion is ";FL$
1230
1235
'**
I=R: PiS=""
set new Part number PlS.
1240 LINEINPUT "Part number (/EN/=return >: ";Pl$
1262
1265
'**
P1$=RIGHTS(" "tPHd2)
redefine Part number.

1270 ' is P1$ null?


1275 IF RIGHTS(Pl$,2)()" 0" AND RIGHTS(Pl$,1)()" " THEN 1285
1280 IF LOFC1)=1 AND FIRST=O THEN 1422
ELSE 1:w2
1285
1290
'**
IF I=O THEN R=l! RL=O: LL=O! GOTO 1327
set links to (l,

1295 '**
1300 FIRST=1: GOSUB 1600
read data record.
1305 IF P1S>P2$ THEN 1317
1310 IF P1S=P2S THEN PRINT "alreadw on file": GOTO 1225
1315 IF LL=O THEN LSET LLS=MKISCIEN)! PUT 1,I: GOTO 1327
ELSE I=LL: GOTO 1295
1317 1
**
1320 GOSUB 1800
field data record.
1325 IF RL=O THEN LSET RLS=MKIS(IEN)! PUT 1,I
ELSE I=RL! GOTO 1295
1327 1
**
1330 RSET PTS=P1S! LSET LLS=MKI$(0) !
set new JinKs too.
LSET RLS=MKI$(0)
1335 1 set other details on the Part.
1340 INPUT "Short Part descriPtion" ;DSS! LSET DESS=DSS
1345 INPUT "Dealer Price" ; SP! t LSET DPS=Mt\S$( SP! )
1350 INPUT "List Price" ;XP!: LSET LP:"Ii=MKSS< XP!)
1355 INPUT "How manY on hand"iOH: LSET OHS=MKIS(OH)
1360 INPUT "What is minimum stock"iSB: LSET SBS=MKISCSB>
1365 LSET NS=MKIS<O>: LSET OOS=NS: LSET MS=NS: LSET OS=NS
1370 LSET F'$=N$
1375 NM=NMt1 incr·ease no. of active records.
1380 IF R=O THEN R=1 if r·oot. is 0 !Ttal<.e it. L
1385 I Put the new recor·d on file.
1390 PUT 1, IENt IEN= LOF( 1)t1: GOTO 1225
1392 'U: field data on the last record.
1395 GOSUB 1700
1400 ' Put the new data into the record buffer.
1405 LSET DESCS=FL$
1410 LSET NMS=MKISCNM)
1415 LSET ROOTS=MKIS<R>
1420 PUT 1, LOF<1>+1 Put. last. record onto file.
1422 1
** ·
1425 INPUT "/EN/"; AS! RUN "INVMAIN"
return to menu disPlaw.

1600 '**
1610 GOSUB 1800
subroutine to read a record.

Chapter 13 Inventory System Application 217


1620 GET 1,1: LL=CVI<LL$)! RL=CVI<RL$)% P2$=PT$
1630 RETURN
1700 '** routine to field root record •
1705 FIELD 1, 2 AS ROOTS, 2 AS NMS, 25 AS DESCS
1710 RETURN
**
1800 ., routine to field data record.
1805 FIEUI 1, 2 AS LL$, 2 AS RLS, 12 AS PT$, 25 AS DES$,
4 AS DPS, 4 AS LPS, 2 AS OH$, 2 AS 00$,
2 AS SB$, 2 AS M$, 2 AS N$, 2 AS os,
2 AS PS
1810 RETURN
1820 END

This is the dialog that INVPRI produces as the user executes it.

Please tYPe either:


Lhe file name of an old file
or
'help' for a list of the files in use
or·
'0' foP a new file! Par·ts~

DisKette file descriPtio n is Parts


Part number ( /EN/=retu rn )t 1984
ShoPt Part descriPtio n? unflansed srommet
Dealer Price? .13
List Price? .39
How manY on hand? 6999
What is minimum stock? 1000~

218 Chapter 13 Inventory System Application

''I

\""J
. . ~

INVPR2 The INVPR2 program performs a traversal of the binary


sequence search tree structure which allows the listing of all parts in
sorted order.

200~ 'FILENAME! "INUPR2" (CALLED BY "INVMAIN")


2010 'FUNCTION: LIST PARTS IN SORTED ORDER
2020 I AUTHOR : SPG DATE: 1/19/79 REV: 7/80
2030 I

2040 DEFINT A-Z


2050 CLEAR 500: DIM STt\( 100 )! CLS
2060 PRINT "S 0 R T E D 0 R D E R T R A U E R S A L"
2070 B$=
nz i. i. 7. Utt,tt Utt.U"
208(J I

2090 '** oPen aPProPriate file.


2100 CLOSE .
2130 INPUT "Naw.e of file ( 'help'=J.ist of files)" ;Ft.$
2135 IF FL$="helP" OR FL$="HELP" THEN RUN "INVPRB"
2140 IF VAUFL$)>0 THEN PRINT "invalid entr~."! GOTO 2090
2150 OPEN "R",1,FL$
2160 IF LOF( 1)=0 THEN PRINT "no such file.": GOTO 2090
2170 ' now fj.eld last (root) record.
2180 FIELD 1, 2 AS ROOT$, 2 AS NM$, 25 AS .DESC$
2190 GET l,LQF(l)! R=CVICROOT$)
2200 ' ini t.ialize order·ed traversal.
2210 P='=R! T=O
2220 GOSUB 2500
2230 FIELD 1, 2 AS LL$, 2 AS RL$, 12 AS PT$, 25 AS DES$,
4 AS DP$, 4 AS LP$
2240 '** traverse.
2250 T=Ttl: STK<T>=P.
2260 IF P<>O THEN GOSUB 2600: P=LL: GOTO 2240
2270 T=T-1
2280 IF T=O THEN 2350
2290 P=STt\( T)
2300 GOSUB 2600 set Pth record and its linKs.
2310 LOOP=LOOPt1: PRINT USING BS; PTS; DSS; LP!; DP!: T=T-1
2320 IF LOOP>11 THEN PRINT! INPUT "/en/";AS! GOSUB 2500
2330 P=RL: GOTO 2240
2340 I

2350 '***** closins routine to set root,


2360 FIELD 1, 2 AS ROOT$, 2 AS NM$, 25 AS DESC$
2370 PRINT "file is of the class ";
2380 GET 1, LOF( 1)! FS=DESC$
2390 PRINT F$
2400 INPUT "/EN/"; AS
2405 '***** return to menu.
2410 RUN "INVMAIN"

Chapter 13 Inventory System Application 219


250 (l / **-*** Print heading for table.
2510 CLS! P!UN.T
" PM::T:J DESCRIPTION L. PR. D. PR."
2515 LOOF'=(l zero the counter variable LOOP
252(l ~:ETUF:N
2600
2605
'***** Set data from buffer.
GET l,P: LL=CVICLLS): RL=CVICRL$)
2610 DSS=DESS: DP!=CVS(DPS): LP!=CVS<LPS)
2620 RETURN
2630 END

This is what the output looks like from a typical run of the
traversal program.

220 Chapter 13 Inventory System Application


INVPR3 The INVPR3 program performs record deletion.
r ,

3000 'FILENAME! "INVPR3" (CALLED BY "INVMAIN")


3010 'FUNCTION! TO DELETE ITEMS FROM THE FILE
3020 I AUTHOR : SPG DATE! 1/19/79 REV. 7/80
3030 I

3040 DEFINT A-Z! CLEAR 500! CLS


3050
3060
'**
CLOSE
set root CR) from last record.
3070 PRINT "What is the file's name"
3080 INPUT "(type 'helP' for the list of files)"; FL$
3090 IF FLS="" OR VALCFL$))0
THEN PRINT "invalid entry."! GOTO 3050
3100 IF FLS="helP" OR FLS="HELP" THEN RUN "INUPR8"
3110 OPEN "R",1,FL$
3120 IF LOFC1)=0 THEN PRINT "no such file."! GOTO 3050
3130 GOSUB 3850! GET 1,LOFC1 )! R=CUICROOT$)! N=CUICNHS)
3140 I

3150 '** set new name' NlS. set W to latest root.


3:1.60 I

3170 INPUT "Part to be deleted -- 0'=return"; N1S! W=R


1

3180 NlS=LEFTSCNl$,12)! NlS=RIGHTS(" "tNl$,12)


3190 ' if no more deletions' rePlace R on last record.
3200 IF RIGHTSCNl$,5)=" 0" OR RIGHTSCNl$,1 >=" " THEN 3700
3210 ' set root. if deletion is not r·ootv sec.:r'ch on.
3220 I=R! GOSUB 3800.! LL=CUH lLS )! Rl..=CVH RL$)
3230 IF N1S<>PTS THEN 3320
3240 1 if no risht. branch, new root is left link.
3250 IF Rl=O THEN R=Ll! GOTO 3580
3260 ' if no left branch' new root is right link.
3270 IF Ll=O THEN R=RLt GOTO 3580
3280 ~ neither link is null. new root is risht link.
3290 F=R: ... R=RL: S=O
3295 ~** set 1th. record.
3300 IF W=O THEN INPUT "Part not on file. /EN/";A$! GOTO 3150
3310 I

3320 '** this name is not root. look some more.


3330 I=W! GOSUB 3800: LW=CVH LLS H RW=CVH RLS)
3340 IF ~1S=PTS THEN 3390
3350 I name still not found. look asain.
3360 F=W
3370 IF N1S<PTS THEN 5=1! W=LW! GOTO 3295
ELSE S=O! W=RW! GOTO 3295
3380 I name is found! check links LW and RW.

Chapter 13 Inventory System Application 221


3390
3400
1
** it at least the left link is null' check RW.
IF LW=O THEN 3500
3410 ' left link is not null. what about ri!ht link?
3420 IF RW=O THEN 3550
3430 1
neither link is null. set father record.
3440 I=F! GOSUB 3800
3445 IF S=O THEN LSET RL$=MKI$(RW>
ELSE LSET LL$=MKI$(RW)
3450 1 once new risht link is attached, rewrite on file.
3460 PUT lii! Z=RW
3470 '** reset new null link.
3480 I=Z! GOSUB 3800! LZ=CVI(LL$)
3490 IF LZ=O THEN LSET LLS=MKI~LW)! GOTO 3580
ELSE Z=LZ! GOTO 3470
3500 **
1
left link is null. what about ri9ht link?
3510 IF RW=O THEN 3550
3520 ' set father record, write with new rishi link.
3530 I=Ft GOSUB 3800
3540 IF S=O THEN LSET RLS=MKI$CRW)! GOTO 3580
ELSE LSET LL$=MKI$CRW)! GOTO 3580
3550 '** set father' reset left link with this risht.
3560 I=F! GOSUB 3800
3570 IF S=O THEN LSET RL$=MKI$(LW)
ELSE LSET LL$=MKI$(LW)
3580 **
1
rewrite both new records, return to search.
3590 N=N-1! PUT 1,1: I=W
3600 GOSUB 3800
3610 LSET [IF'$=MKS$( -DP! ) ! PUT 1, I
3620 GOTO 3150
3700 *****
1
routine to rewrite new root record.
3710 GOSUB 3850
3720 GET 1,LOF(1)! LSET ROOT$=MKI$(R)! LSET NM$=MKI$(N)
3730 PUT 1,LOf(1)
3740 RUN "INVMAIN"
3800
3810
'***** routine to fetch the Ith. record.
1
set Ith. record.
3820 GOSUB 3900
3830 GET 1,1: PT$=P1$! DP!=CVS<DP$)
3840 RETURN
3850 '***** routine to describe the root r~cord.
3860 FIELD 1, 2 AS ROOT$, 2 AS NM$,25 AS DESC$
3870 RETURN
3900 '***** rou t.ine to describe the data record.
3910 FIELD 1, 2 AS LL$, 2 AS RL$, 12 AS Pl$, 25 AS DES$,
4 AS DP$, 4 AS 2 AS OH$, 2 AS 00$,
2 AS SB$, 2 AS 2 AS N$, 2 AS Q$,
2 AS P$
3920 RETURN
3930 END

222 Chapter 13 Inventory .System Application


The dialog between the user of INVPR3 and the computer is
shown below.

What is the file's narue


(t~Pe 'helP' for the list of files)? Parts
Part to be deleted -- 'O'=return? 7890
Part not on file. /EN/?
Part to be deleted -- 'O'=return? 789
Part to be deleted -- 'O'=return? 565z
Part not on file. /EN/?
Part to be deleted 'O'=return? 565b
Part to be deleted -- 'O'=return? ~

Chapter 13 Inventory System Application 223


INVPR4 The INVPR4 program performs an access to the file in order to
update the contents of a record. It is essentially a modification of
the INVPRI program that added records to the file.

4000 'FILENAME: "INVPR4" (CALLED BY "INVMAIN")


4005 'FUNCTION: TO CHANGE AN INVENTORY RECORD
4010 AUTHOR :
I SPG DATE: 1/19/79 REV. 7/80
4015 CLEAR 500: DEFINT A-z: CLS
4020
4025
'** oPen a data file.
INPUT "File name -- ( 'helP'=list of files)";FLS
4030 IF FLS="helP" OR FL$="HELP" THEN RUN "INVPR8"
4035 IF FLS="" THEN PRINT "bad file name"! GOTO 4020
4040 OPEN "R"v1,FL$
4045 IF LOFC 1)=0 THEN PRINT "no such file": GOTO 4020
4050 FIELD 1,2 AS ROOT$, 2 AS NM$, 25 AS DES$
4055 GET 1rl0F(1)
4060 R=CVI<ROOTS)
4065 PRINT " file descr-iPtion is "¥DES$
4070 FIELD 1r £.r, AS LL$, 2 AS RL$, 12 AS pu, 25 AS DES$,
4 AS DP$, 4 AS LP$, 2 AS OHS, '1.:.. AS oos,
2 AS SB$, .:.. AS M$,
rl
.:.. AS tH;,
'1
2 AS os,
.:.. AS PS
')

4075 I

4080 I ma i n r e c o r d c h a n ! e r
4085
4(190 N1·$=""
4095 INPUT "Part number -- /EN/=no further chan!es";Nl$
4100 N1S=LEFTSCN1$,12)! N1$=STRINGSC12-LEN<N1$)," ">+N1S
4105 IF RIGHTSCN1S,2)=" 0"
OR RIGHTSCN1Sv1)=" "
THEN RUN "INVMAIN"
4110 1
search for Part number N1$,
4115 I=R! GOSUB 4770
4120
4125
I**
IF N1S>PTS THEN 4140
, start access of tree,
4130 IF N1S=PT$ GOTO 4160
4135 IF LL<>O THEN I=LL! GOSUB 4770: GOTO 4120
4140 '** checK ri!ht lin~.
4145 IF RL<>O THEN I=RL: GOSUB 4770: GOTO 4120
4150 I=O
4155 IF I=O THEN PRINT "Part no. ";N1S;" was not found.":
INPUT "/EN/";As: GOTO 4080
4160 '** ***record was found!***
4165 ' get the rest of the information oul of the buffer.
4170 DP!=CVSCDPSlt LP!=CVSCLPS>: OH=CVICOHS>t OO=CVI<OOS>:
SB=CVI<SBS>t M=CVICMS>: N=CVICNSlt O=CVICOS)t P=CVICP$)
4175 PRINT "RECORD I";I
4180 I

224 Chapter 13 Inventory System Application


4185
4190
'**
PRINT
m a i n ' m i n i d r i v e r'
"1 descriPtion 5 no. on
r o u t i n e
order"
419~5 PRINT "2 dealer Price 6 no. there should be"
42(1 (lPRINT "3 list Price 7 sales histors info."
420 :; PRINT "4 no. on hand 8 no more chanses"
4210 INPUT "Which acLivity";A $
4215 IF A$="" THEN PUT 1,1: GOTO 4080
4220 IF VAL(A$)(1 -OR VALCAS)>B THEN 4185
4225 IF VAL(A$)=8 THEN AS="": PUT 1,I: GOTO 4080
4230 ON VALCA$) GOSUB 4300v4350,4400,4450,4500,4550,4600
4235 GOTO 4185
subroutine to chanse descriPtion .
43(l(l
I*****
4310 PRINT "descriPtion =";DESS! AS=""
4320 INPUT A$
4330 IF LEN( A$ ><>O THEN LSET DESS=AS
4340 RETURN
4350 '***** subroutine to chanse dealer Price.
4360 PRINT "dealer Price=";DP!
437(! INPUT DP!
4380 IF DP!<>O THEN LSET DPS=MKSS<DP!)
4390. RETURN
4400 '***** subroutine to chanse list Price.
4410 PRINT "list Price=";LP!
4420 INPUT LP!
443(! IF LP<> THEN LSET LPS=MKS$( LP! )
4440 RETURN
4450 '***** subroutine to chanse 4 of units on hand.
4460 PRINT "no. on hand=";OH
4470 INPUT OH
4480 IF OH<>O THEN LSET OHS=MKISCOH)
4490 F:ETURN
4500 '***** subroutine to chanse *of units on order.
4510 PRINT "no. on order=";oo
4520 INPUT 00
4530 IF OO<>O THEN LSET OOS=MKIS(00)
4540 RETURN
4550 '***** subroutine to chanse stock limit.
should be (slack limil)=";SB
4560 PRINT "no. there
4570 INPUT SB
4580 IF SB<>O THEN LSET SBS=MKIS(SB)
4590 RETURN
4600 '***** subroutine to chanse the sales histors.
4610 PRINT "sales historY information :"
4620 PRINT 1 TAB(5} M "units sold in the Past 2 months.•
4630 PRINT 2 TAB(5) N "units sold in the Past 6 months.•
4640 PRINT 3 TA~5} 0 "units sold in the Past 12 months."
4650 PRINT 4 TABC5> P »units sold in the Past 24 months."
4660 A$=•": PRINT

Chapter 13 Inventory System Application 225


4670 INPUT "which do Bou want to chanse (/EN/=none )";A$
4680 IF VAL< A$ ><1 OR VAL< A$ ))4 THEN RETURN
4690 C$=""t PRINT
4700 INPUT "What is the new number"; C$
4710 ON VALCA$) GOSUB 4730,4740,4750,4760
4720 RETURN
4730 M=VALCC$)t LSET M$=MKI$CM>t RETURN
4740 N=VALCC$): LSET N$=MKI$CN)! RETURN
4750 O=VAL(C$)t LSET O$=MKI$CO>t RETURN
4760 P=VAU C$ )t LSET F'$=MKUC P >: RETURN
4770
4780
'***** get, ILh record, links, and Part number.
GET 1,I: LL=CVICLL$)! RL=CVI<RL$}t F'T$=P1$
4790 RETURN
4800 END

User interaction with INVPR4 looks like this.

File name-- ('helP'=list of files)? Parts


file descriPtion is Parts
Part number -- /EN/=no further chanses? 1984
RECOR[I t 22
1 descriPtion 5 no. on order-
2 dealer Price 6 no. ther-e should be
3 list Price 7 sales histor~ info.
4 no. on hand 8 no 1nore chanses
Which activit~? 1
descriPlion=unf lansed SrORII'flet
? reflansed srommet.
1 descriPtion 5 no. on order
2 dealer Price 6 no. there should be
3 . list Price 7 sales histor~ info.
4 no. on hand 8 no Rtore chanses '
Which activitY? ~

226 Chapter 13 Inventory System Application

l •
INVPRS The INVPRS program lists all records in their physical order,
ignoring the BSST's logically sorted order.

5000 'FILENAME: "INVPR5" <CALLED FROM "INVMAIN")


5010 'FUNCTION! TO LIST ALL RECORDS ON A DATA FILE
5020 AUTHOR : SPG
I
DATE: 1/19/7 9 REV. 7/80
5030 CLEAR 500: DEFINT A-Z
5040
CLOSE: CLS
:;o~)(l
'** set file name from user.
5060 INPUT "file name ('helP '=lisl of files)" ;FLS
5070 IF FLS="helP" OR FLS="HELP" THEN RUN "INVPRB"
ELSE OPEN "R"tl,F L$
5080 IF LOF< 1}=0 THEN PRINT "no such file." : GOTO 5040
5090 FIELD 1, 2 AS ROOT$, 2 AS NM$,15 AS DESCS
5100 GET 1, LOF( 1)
5110 NM=CVHNM$)
5120 CLS
5130 PRINT "file descri Ption is"; DESCS
5140 PRINT TAB(10)i NMf "activ e items. "
5150 B·$::::
"tf U:J: iU i; "!
I•
5160 GOSUB 5600
5170 FOR I=l TO LOF(l )-1
5:1.80 GOSUB 5500
51.90 LOOP=LOOPtl
52(l0 IF LOOP>11 THEN GOSUB 5600
5210 PF:HH USING B$; r, LL, F:L, PH~ DES$, DP! J LP!
5220 NEXT I
5230 INPUT /EN/"; AS: RUN "INVMAIN"
II

5235 I

5500
5510 PTS="" '***** field and set data record .
5520 FIELD 1, 2 AS LL$,2 AS RL$,12 AS PT$,25 AS DES$,
4 AS DP$,4 AS LP$
5530 GET 1,I
5540 LL =CUI(LLS>: Rl =CVICRLS): PTS=PTS
5550 DP!=CVS<DPS>: LP!=CVS<LPS>
5560 RETURN
5600
5610 LOOF'=O
'***** subrou tine to Print headin ••
5620 INPUT "/EN/";As: CLS
5630 PRINT
II
11 rl Pt descri Ption dP lP"
5640 RETURN
5650 EN II

Chapte r 13 Invento ry System Applica tion


227
The output from the INVPRS program looks like this.

11 r·1 Pi descriP tion dP J.p


1 ...
'") ..,
"7 8430 steam sKYhooK 945.00 1488.00
2 8 r
.J 5643 Sfltall wid!:;et 45.66 61.50
3 6 7
I 2456Y Yellow wazoo 6.75 7.89
4 18 8 789 fan t.asf!tasor· ion -55.00 89.95
5 9 0 565a ten sallon hat 23. ~)7 38.99
.6 20 10 8440 sas sKYhooK 1011.00 1444.88
7 11 ...
1'1 62651 older' folder- h 0.69 (l,89
8 13 21 2397 r·isht-h anded e 13.80 2•). 99
9 0 14 5648 lar· se widset 59. 9(i 88t99
10 15 0 2456s str· i Ped wa:zoo 8.50 12.99
11 (I 16 36433 funneL; coPe 67.80 76t89
/EN/? t·

11 r·l Pi descriP tion dP lP


12 17 0 62659 Pl<::in folder-- h 0.79 0.99
13 ......
'")'")
0 2394 left-ha nded ea 14.60 21.88
14 0 0 5650 e>:t.r·a- li::r-se I,J i 72.88 99.80
15 0 0 2456b blue wazoo 6.25 9.99
16 0 0 46559 tow hooK 42.84 49.95
17 0 0 62656 newer folder·- rt L99 2.39
:1.8 (l 0 562 r·isht.-· ansled f (l, 57 1.29
19 0 0 565b five sal J.on ha --18.43 29.98
r:-~~
1 ..,r~o
20 0 0 8432 electri c sK~4lO 893.00 ..)·;I V J.i.

21 0 0 5440 fJ.ansed Sf'"Oiliflte (l, 16 (1,39


22 18 0 1984 r·eflans ed Sf'" OR! 0.13 0,39
/EN/? H-

228 01apter 13 Inventor y System Applica tion


INVPR6 The INVPR6 program provides a list of the deleted parts by
searching the desired file in sequence until it finds a negative dealer
price, which is how the deletion program INVPR3 marks a record to
be deleted. All the records with negative dealer prices are listed.

6000 'FILENAME: "INVPR6" <CALLED FROM "INUMAIN")


6010 'FUNCTION! TO LIST DELETED PARTS
6020 I AUTHOR : SPG DATE: 1/19/79 REV. 7/80
6030 DEFINT A-Z
6040 :S$=
u ....,
!. i. i.
M50
606(1 CLOSE
I** set file name from user.
6070 INPUT "file name C'helP'=list of files)";FLS
6080 IF FLS="helP" OR FLS="HELP" THEN RUN "INUPRB"
6090 IF VALCFL$))0 THEN PRINT "no such file.": GOTO 6050
6095 OPEN "R",l,FL$
6097 IF LOFC1)=0 THEN PRINT "file is emPtY."! GOTO 6050
6100 FIELD 1, 4 AS F$, 12 AS PT$, 25 AS DESS,
4 AS DP$, 4 AS LPS ·
6110 GOSUB 6220
6120 FOR I=l TO LOF( 1 )-1
6130 GET 1,1: DP!=CVSCDP$)
6140 IF DP!>O THEN NEXT I: GOTO 6200
6150 LP! =CUS< LPS)
6160 LOOP=LOOPtl
6170 IF LOOP>=12 THEN INPUT "/EN/"; AS: GOSUB 6220
6180 PRINT USING BS; PTS, DESS, ABS<DP!), LP!
6190 NEXT I
6200 '**
6210 INPUT "/EN/"; AS: RUN "INUMAIN"
return to menu driver.
6220 '*****
6230 CL S: LOOP=O
Print headins.
6235 PRINT " L I S T 0 F D E L E T E D I T E M S"
6237 PRINT
6240 PRINT
" Part i descriPtion dlr Pr list Pr"
6250 RETURN
6260 END

Output from INVPR6 would look like this.

LI ST 0F DE L E T E D I T ~ MS
Part J descriPtion dlr Pr list Pr
789 fantasmasorion 55.00 89.95
565b five sallon hat 18.43 29.98
/EN/'!' ~

Chapter 13 Inventory System Application 229


INVPR7 The INVPR7 program performs the tree balancing necessary to
maximize the efficiency of the BSST file structure. Table 13.3
shows a, typical tree before and after balancing. Program INVPR7
causes this transformat ion.

Before Afier
Record Part t LL RL Par-t t LL RL
1 7 2 3 a 2 3
2
3
...
.r:.
B 0
4 6
5 ..,...
4
.i.:.. 6
4 5
7
4 1 0 0 .r:. 3 9
5 11 9 10 6 10 11
6 4 15 7 10 1"'1
J.L 13
7 5 0 8 14 14 15 r \

8 6 0 0 1
J. 0 0
9 9 0 14 3 0 0
10 15 11 0 5 0 0
11 14 12 0 7 0 0
12 12 0 13 9 0 0
13 13 0 0 11 0 0
14 10 0 0 13 0 0
15 3 0 0 15 0 0
Table 13.3 A Typical Tree Before and After Balancing

7000 'FILENAME! "INUPR7"


7010 'FUNCTION! TO BALANCE THE BINARY SEARCH TREE
7015 IAUTHOR : SPG DATE: 1/19/79. REV. 7/80
7020 ' after a method originallY described bY JDR
7025 CLSt PRINT! PRINT
7030 PRINT " T H I S P R 0 GR AM B A L AN C E S
T H E B I N A R Y S E A R C H T R E E"
7035 PRINT! PRINT
7040 CLEAR 300! DEFINT A-Z: DIM MSK(200), KLN(200)
7045 '**
7050 CLOSE
~et file name from user.

7055 INPUT "file name C'helP'= list of files}";FL S


7060 IF FLS="helP" OR FLS="HELP" THEN RUN "INUPR8"
7065 IF VALCFLS>>O THEN PRINT "no such file.": GOTO 7045
7070 OPEN "R",1,FLS
7075 IF LOF(1)=0 THEN PRINT "no such file."! GOTO 7045
7080 GO SUB 7650
7085 FOR S=l TO LOF< 1}-1
7090 GET 1,5
7095 LL=CUI<LJ$)t RL=CVI<LK$)! DP!=CUSCDPS>
7100 IF DP!<O THEN 7110

230 Chapter 13 Inventory System Application

' )
7105 IF LL>O AND RL=O OR RL>O AND LL=O THEN Y=Ytl
7110 NEX.T S
7115 BAL~lOO*CY/CLOFC 1)-2))
7120 PRINT "The tree is alreadY "; 100-BAL; "% balanced."
7125 S=7*CLOFC1>-1 )! H=INTCS/3600)! MI=INT(S/60>
7130 MI=MI-Ht60! S=S-(H*3600tMI*60}
7135 PRINT " Balancins the file could taKe as Ions as --"
7140 PRINT " Ch!m!s), "; H; "!"; MI; "!"; S
j145 INPUT "Do YOU want it balanced further (y or n)";S$
7150 IF LEFT$ES$,1 ><>"w" THEN RUN "INVMAIN"
7155 GOSUB 7600
7160 GET 1,LOF<1)
7165 N=CVI<NM$)! R=CVI<ROOT$)! D$=DESCS
7170 PRINT "N=•;N, "R=";R, "DSS=";DESC$! N1=N
7175 1
fill kln arraY with balanced Pointers.
7180 K=1! M=INTCCN1t1)/2)
7185 KLN<K>=M! MSKCM)=1! I=l! Q=I
7190 '**
7195 M=INT<<Mt1 )/2)! U=Q! Q=QtQ
7200 FOR C=U TO Q-1
7205 L=KLNCC)-M
7210 IF L<l OR L>Nl THEN 7220
7215 IF MSK<L>=O THEN K=Ktl! KLNCK)=L: MSK< L )=:1.
7220
7225 '**L=KLN( CHM
7230 IF L<l OR L>Nl THEN 7240
7235 IF MSK<L~O THEN K=Kt:l.! KLNCK>=L! MSK< L >=1
7240
7245
I**
NEXT C! I=Itl
7250 IF M>1 THEN 7190
7255 FOR I=l TO Nl!
IF MSK<I> <> 1 THEN K=Ktl! KLN<K>=I
7260 NEXT I
7265 PRINT H N0 w c 0 p y I N G"
7270 ' traverse, coPwins into "NEATFILE" in sorted order.
7275 CLOSE 2! OPEN °R"v2,"NEATFILE"
7280 I=O! T=O! P=R
7285
7290
'** felch and slack until P=O.
IF P<>O THEN T=Ttl: STK<T>=P: GOSUB 7650! GET 1,P:
P=CVICLJ$)! GOTO 7285
7295 I if t<>O POP the stack, transfer to "NEATFILE".
7300 IF T·G·O THEN P=STt\( T )! T=T-1! I=I+l: GOSUB 7800:
P=CVICLK$)! GOTO 7285
7305 ' Print out the Po~ilions to be filled.
7310 FOR I=l TO N
7315 PRINT KLNCI),
7320 NEXT It PRINT

Chapter ·13 Inventory System Application 231


7325 1 build tree. simPlY traverse and rewrite FLS.
7330 1 note thai KLN contains Pointers for neat new file.
7335 R=O: T=O! CLOSE 1! KILL FLS! OPEN "R",l,FLS
7340
7345
I** ~et record from "NEATFILE" accordins to KLN.
I=R! T=Ttl! L=KLN<T>
7350 GOSUB 7900! GET 2,L
7355 IF I=O THEN R=T! GOSUB 7650! GOTO 7400
7360 1** set new record.
7365 GOSUB 7700
7370 IF P2S=PTS THEN PRINT P2S; "duPlicate"! GOTO 7435
7375 1 rebuild file in BSST order onto FLS.
7380 IF P2S>PTS THEN 7390
7385 IF LL=O THEN LSET LJS=MKIS(T)t PUT l,I: GOTO 7400
ELSE I=LL! GOTO 7360
7390 I**
7395 IF LR=O THEN LSET LKS=MKIS(T)! PUT 1,1
ELSE I=LR! GOTO 7360
7400 1** PUt variables in field.
7405 LSET LJS=MKIS<O>: LSET LKS=MKI$(0)! RSET PTS=P2$
7410 LSET DESS=DSS: LSET DPS=D2S! LSET LPS=L2S
7415 LSET OHS=02S! LSET 00$=03$! LSET SBS=S2S! LSET MS=M2S
7420 LSET NS=N2S! LSET 0$=04$! LSET PS=P4$
7425 1 PRINT THE PART NUMBER
7430 PRINT USING •1. Z"; PTS;: PUT l,T
7435 I** check for end of looP.
7440 IF T<N THEN 7340
7445 ' rewrite new root record on new "INVENDATu.
7450 GOSUB 7600
7455 LSET ROOTS=MKI$( 1 )! LSET NMS=MKU< N)! LSET DESCS=IIS
7460 PUT 1, LOFC1)tl
7465 1 reirun to INVMAIN after cleanins uP.
7470 KILL "NEATFILE"! PRINT! PRINT
7475 PRINT "b a 1 a n c i n S i s c o m P 1 e t e."
7480 INPUT "/EN/"; AS! RUN "INVMAIN"
7485 I

7600 ***** 1 field the root record.


7605 FIELD 1, 2 AS ROOT$, 2 AS NM$, 25 AS DESCS
7610 RETURN
7650 ***** 1 routine to field data record.
7655 FIELD 1, 2 AS LJ$, 2 AS LKS, 12 AS PTS, 25 AS DES$,
4 AS DPS, 4 AS LPS, 2 AS OH$, 2 AS 00$, 2 AS SBS,
2 AS MS, 2 AS NS, 2 AS OS, 2 AS PS
7660 RETURN
7700 '***** routine to fetch a data record from FLS.
7705 GOSUB 7655! GET 1,I! LL=CVICLJS)!
LR=CVICLK$)! RETURN

232 Chapter 13 Inventory System Application

l J

' " - - _ __
' '

7800
7805
'***** routine to set from FLS, write on "NEATFILE".
GOSUB 7650! GET l,P
7810 GOSUB 7900! L3S=LJS! L4S=LKS
7815 LSET P2S=PTS! LSET DSS=DES$! LSET D2S=DPS
7820 LSET L2S=LPS! LSET 02$=0HS! LSET 04S=OOS: LSET S2$=SBS
7825 LSET M2S=MS! LSET N2S=NS! LSET 04$=0$! LSET P4S=P$
7830 lF I>=1 THEN
I1S=PT$! PRINT I; I!S;" descriPtion= ";DES$
7835 PUT 2d: RETURN
7840 RETURN
7900
7905 '***** routine to describe dat• on "NEATFILE".
FIEUI 2, 2 AS L3$, 2 AS L4$, 12 AS P2$, 25 AS DS$,
4 AS 02$, 4 AS L2$, 2 AS 02$, 2 AS 03$,
2 AS 52$, 2 AS M2$, 2 AS N2$, 2 AS 04$,
2 AS P4$
7910 RETURN
7920 ENII

The balancing program is an example of a program


communicating to the user its state of execution. It not only
calculates how well balanced the tree is (by counting unbalanced
terminal nodes) but it prints the records that it is copying as it
performs the balancing.

T H I S P R 0 G RA M BAl ANC E S
T H E B I NA R Y S E AR C H T R E E

f.ile name ('helP'=list of files)? Parts


Lhe tree is alread~ 84 Z balanced.
balancins the file could take as Ions as --
<h:m:sh 0 : 0 : 49

do ~ou want it balanced further- ( ~ or n)? B


N= 7 R= 1 IISS=Parts
N0 W C0 P YI NG
1 2923 descriPtion= towhook
2 36932 descriPtion= ear trumPet
3 245623 descriPtion= blue wazoo
4 564322 descriPtion= widset
5 843234 descriPtion= sk~hook
6 3643325 descriPtion= funnel scoPe
4 2 6 1
3 5 7
564322 36932 3643325 2923 245623
843234
b a 1 a n c i n s i s c o Rt P 1 e t e.
/EN/1' lE-
Chapter 13 Inventory System Application 233
INVPR8 The INVPR8 program accesses the file called FILENAME,
which is a file whose sole purpose is to record the names of all files
used in the system.

8000 'FILENAME: "INVPRB" (CALLED FROM MOST PROGRAMS)


8010 'FUNCTION: LISTS ALL OF THE FILES IN USE
8020 ' AUTHOR : SPG DATE: 1/19/79 REV. 7/80
8030 CLEAR 1000: DEFINT A-z: CLS: S=O
80·10 PRINT " T H I S P R 0 GR AM L I S T S
A L L 0 F T H E F I L E S I N U S E!"
8050 PRINT! PRINT
8(16() i. i. i. i. ., .
i. I•

8070 OPEN "R",l,"FILENAHE": FIELD 1, 255 AS A$


8080 S=S+l
809•) IF LOF(l)=S-1 THEN 8160
ELSE GET hS
8100 FOR L=l TO 223 STEP 32: IF MIDS(Af,L,1>=" " THEN 8160
81:1.0 IF MIDS(AS,L,l )::" " THEN 8160
8120 FOR I=L TO Lt24 STEP 8
8130 PRINT USING cs; MIDS<AS,I,It7)i
8140 NEXT I
8150 NEXT L! GOTO 8080
8160 INPUT "/EN/";As: RUN "INVMAIN"
8170 END

The output produced by INVPR8 looks like this.

THI S P R0 GRAM l I S T S
A l l 0 F T H E F I L E S I N U S E!

Par-ts IIIOPClf't.S /EN/? f-

234 Chapter 13 Inventory System Application


INVPR9 The INVPR9 program removes the name of a file from the
index file "FILENAM E" and kills that file if the user wishes.

9000 'FILENAME: "INVPR9"


9010 'FUNCTION! TO DELETE ANY SELECTED FilE
9020 I AUTHOR : SPG DATE! 1/19/79 REV. 7/BO
9030 CL.S
9040 PRINT " F I L E D E L. E T I 0 N P R 0 G R A M"
9050 PRINT! PRINT
9060 INPUT "name of fi)e to be deleted ('helP'=l ist)"; FL.S
9070 IF FLS="helP" OR FLS="HELP" THEN RUN "INVPr:;;8"
9080 OPEN "R",1,FL$
9090 IF LOF< 1)=0 THEN PRINT "file contained no data."!
PRINT "It has been deleted." !
. PRINT "Will be deleted from 'helP'"!
GOTO 9140
9100 PRINT "file contains" ; LOFC 1); "data items."
9110 PRINT "Are You sure YOU want it deleted <Y=yes)"
9120 INPUT BS
9130 IF BS<>"Y" THEN 9260 'note that. Y is caPitaliz ed.
9140 CLOSE! KILL FL$ 'delete t.he dat.a file itself,
9150 OPEN "R",1r"FILENAME" 'then delete from "FILENAME•.
9160 FLS=FLS+STRING$(8-LENCFL$)," ")
9170 FIELD 1, 255 AS N$
9180 M=M+1
9190 GET iJM
9200 FOR J=1 TO 255 STEP 8
9210 IF MIDS(N$,J,1 )=" " THEN 9250
9220 IF MIDSCNf,J,8><>FLS THEN NEXT J! GOTO 9180
9230 NS=LEFTSC Nf,,J-1 HMID$( N$,Jt8,LEN( N$))
9240 PUT 1,M
9250 PRINT "Deletion comPleted. ";
9260 PRINT "Returnin s to main menu."
9270 RUN "INVMAIN•
9280 END

Chapter 13 Inventory System Application 235


INVPRlO The INVPRlO program uses the BSST access algorithm to get a
specific record and then it displays all of the information on that
record. The display is designed specifically for the record contents
of this system.

10000 'FILENAME: "INVPR10n <CALLED FROM "INVMAIN")


10010 'FUNCTION! TO PRINT THE CONTENTS OF ANY RECORD,
10020 I AUTHOR : SPG DATE! 1/19/79 F:EI.J, 7/80
1003(1 IIEFINT A-Z! CLEAF: 500
gel file name from user.
10040
10050 '**
CLOSE
10060 INPUT "What is file name ('helP'=lis l)"; FL$
10070 IF FLS="" THEN 10040
10080 IF FLS="helP" OR FLS="HELP" THEN RUN "INVPRB"
10090 OPEN "R",l,FLS
10100 IF LOFC1J=O THEN PRINT "no such file.": GOTO 10040
10110 GOSUB 10800
10120 GET 1,LQF(1)! R=CVICROOTS>t N=CVI<NM$)
10130
10140
'**
I

10150 set new Part no.r N1$! set W to latest root.


1016(1 Nl$=""
10170 INPUT" What is Part no. ('O'=relurn) "iN1S
10180 W=R
10190 'Pad Part number lo 12 characters with blanKs.
10200 N1S=RIGHTSC" "+Nl$,12>
10210 RS=RIGHTSCN 1Sr1 >: IF RS=" " THEN 10660
1022(1 1 set. r·ooL if Part is. not r·oot, sear·ch on,
10230 I=R: GOSUB 10700! LL=CVI<LLSJ: RL=CI.JICRLSJ
10240 IF NlS<>PTS THEN 10340
1025(1 if no risht br·<mchr new r·oot is left lin~,.
1

10260 IF RL=O THEN R=LL! GOTO 10150


10270 if no left. branchv new root is ri~ht link,
1

10280 IF LL=O THEN R=Rlt GOTO 10150


10290 neither link is null. new root is ri~hl linK.
1

10300 F=Rt R=RL! S=O


10310
10320
'** Part number not found.
IF W=O THEN INPUT "Part. not on file. /EN/"; ASt
GOTO 10150
10330 ,
10340 '** narue is not root. look some ruore.
10350 I=W! GOSUB 10700! LW=CVI<LLSlt RW=CVI(RLS)t
IF NlS=PTS THEN 10380
10360 1 nar11e s.till not found. looK asain.
10370 F=W!
IF NlS<PTS THEN S=1! W=LW: GOTO 10310
ELSE S=Ot W=RW! GOTO 10310

236 Chapter 13 Inventory System Application


10380
10390
I**
GOSUB 10900
nanre is found.
10400 DP!=CVSCDPS): OH=CVICOHS>: M=CVICMS>: N=CVI<NS>
10410 LP!=CVSCLPS>: OO=CVI(OQS): O=CVICOS)! P=CVJ(P$)
10420 SB=CVICSB$)
10430 CLS
10440 PRINT STRING$( 63, "-")
10450 PRINT " part no.--- "; PT$
10460 PRINT " descriPtion "; DES$
10470 PRINT STRING$(63,"-")
10480 PRINT " dealer Price --- ";
10490 PRINT USING "SS,ttt+tt"; DP!;
10500 PRINT " list Price --- "j
10510 PRINT USING "$$,ttt.tt"; LP!
10520 PRINT STRING$(63,"-")
10530 PRINT " There are"; OH; •units on hand."
10540 PRINT TAB<4>; oo; "units are on order.";
10550 PRINT SB; is the minimum stock ouanlity,"
11

10560 PRINT STRING$( 63, "_u )


10570 PRINT TABC19); "SALES HIS T 0 R Y"
10580 PRINT TABC23); "past ~months:"; M
10590 PRINT TAB<23); "Past 6 months:"; N
10600 PRINT TABC23); "Past 12 months:"; 0
10610 PRINT TAB(2J); "Past 24 months:";p
10620 PRINT STR~NG$(63,CHRSC95})
10630 FOR Y=10 TO 15: SET (60,Y>: SET C61,Y>: NEXT Y
10640 FOR Y=l TO 43: SET (l,Y>: SET <126,Y>: NEXT Y
10650 GOTO 10150
10660 '** return to menu driver.
10670 INPUT "/EN/";As: RUN "INVMAIN"
10700 '***** routine to fetch the Ith record.
10710 GOSUB 10900: GET 1,1: PTS=P1S: DP!=CVS<DP$)
10720 RETURN
10800 '***** routine to describe the root record.
10810 FIELD 1, 2 AS ROOTS, 2 AS NM$, 25 AS DESCS
10820 RETURN
10900
10910
'***** routine to describe the data record,
FIELD 1, 2 AS LL$, 2 AS RL$, 12 AS P1$, 25 AS DES$,
4 AS DPS, 4 AS LP$, 2 AS OH$, 2 AS 00$,
2 AS SB$, 2 AS M$, 2 AS N$, 2 AS 0$,
2 AS P$
10920 RETURN
10930 END

Chapter 13 Inventory System.Application 237


I '
This is what the screen looks like when it displays' the
information on an item on file.

Well, there it is. This last system represents a high degree of


sophistication on a microcomputer. It contains examples of some
of the best building, accessing, updating, and sorting techniques that
are available today, on any computer. When you have mastered
these techniques, you will have at your disposal the variety of tools
that will provide you with both breadth and depth in the application
of your craft. We can only suggest.that you keep using these tools,
and others as you discover them, to further sharpen your expertise.

238 Chapter 13 Inventory System Application


Appendix A Comparison of Three BASICs

B ASCII Codes and Character Set for the TRS-80

c 48K TRS-80 Level II with Disk Memory Map

D Level II Instructions and Reserved Words

E TRSDOS Commands

F Error Codes

239
The table that follows this brief discussion comPares thre~
PoPular versons of BASIC. The three have been abbreviated M, E, and
n: Mstands for Microsoft's BASIC as imPlemented on the TRS-ao,
includins the enhancements in TRSDOS; E stands for BASIC-E Version
2.0, a somewhat dated Clate 19781 version of one of the most PoPular
comPiler-tYPe BASICs; and D stands for DEC BASIC PLUS, Disital
EGuipment ComPanY's most POPular minicomPuter BASIC. BASIC-PLUS is
included here in order to comPare an "old" (earlw '70s) version of
the 1ansuase formed on Rtuch more e>:Pens.ive hardware to the newer
BASICs develoPed stricti!:-! for RticrocomPuters. The reader should note
also thai sotTte hiShlY advanced versions of BASIC-E e>:ist' such as
CBASIC or CBASIC-2.

T~:;pe of
BASIC
11 E II BASIC Features
--- .. --~ ...... ---~-·--.,_-----------·--------------------------..;.----

N y y ComPiler that Produces storable obJect code


Y N N Direct, or calculator' mode of OPeration
Y N N Built-in editor·
N N Y ·' RENUM or RESEQ
Y. r4·;,:~,TN TRACE to helP debussins
y y. N lons variable names (more than lett.er-disit)
Y N N Double Precision variables
Y N N Inteser variables
Y N' N Hex and octal variables
Y N N . VARPTR
N N Y ·. Multiline user-definable functions
Y N N Error traPPinS with ON ERROR - GOTO
y N y Text error messases
y N y ImPlicit dimensioninsl Default size is 10
I <

N N Y Matrix instructions, e.s. MAT X=INVCY>


N N Y Matri>: I/O
Y N N ? substitutes for PRINT
y N y ' substitutes for REM
y y y IF - THEN - ELSE
y N y PRINT USING
y N y INSTR finds the Position of a character
Y N N STRING$ Prints a series of characters
Y N N PEEK ~ POKE
y N y TIME$ accesses swstem clocK

\ '

240 Appendix A - Comparison of Three BASICs


\ .

I-

r-
f -

f •

Appendix B - ASCIT Codes and Character Set 241


ASCII codes 192through 255 are called space compression
codes because printing one of these characters causes tabbing for
0 to 63 spaces.

10 'FILENAME! "APPENDIX"
20 'FUNCTION: PRODUCE ASCII CODES & CHARACTERS IN 3 SCREENS
30 I AUTHOR : JDR DATE 8/80
40 CLEAR 1000 : CLS! DIM A$( 191)
50 FOR I=O TO 31 :READ X$ : A$(I~LEFT$CX$t" ",3): NEXT I
60 DATA NUL,SOH,STX,ETX;EQT,ENQ,ACK,BEL,BS,HT,LF
70 DATA VT,FF,CR,SO,ShDLE,DCbDC2,DC3,ItC4,NAK
80 DATA SYN,ETB,CAN,EM,SUB,ESC,FS,GS,RS,US
90 FOR 1=32 TO 191 : A$(I)=CHR$CI>: NEXT I
100 FOR M=O TO 128 STEP 64 : N=Mt63
110 GOSUB 140 ' Print screen of ASCII codes
120 FOR K=1 TO 1000 ! NEXT K : CLS ' dela~
130 NEXT M : STOP
140 1subroutine to dis?la~ 64 codes and ASCII eGuivalenls
150 FOR I=M TO N
160 IF I=INTCI/8)*8 THEN PRINT
170 IF I<32 THEN PRINT RIGHT$<" "tSTR$CI),J);" ";A$(1);" ";
ELSE PRINT RIGHT$CSTR$(I),J);" ";A$(I);" ";
180 NEXT I : RETURN
190 END

242 Appendix B - ASCII Codes and Character Set


Address Mentory Content~
Hex.' Deci~r~al

0000 0 1K ROM I/0 Drive rs and BootstraP


0400 1024 UK ROM Level II BASIC, DisK BASIC

3000 12288 2K ROM 1/0 addre sses


3800 14336 1K RAM Ke~board ritemor~
3COO 15360 1K RAM CRT scree n me~r~or~
40~0 16384 5K RAM BASIC vecto rs
4200 4K RAM TRSDOS

5200 6.5K RAM Disk BASIC


TRSDOS. Utili ties
' '

6COO 1K RAM User Men.orY


7000 4K RAM User MemorY <to 16K sYstem)

8000 32768 16K RAM User Men.orY (to 32K syslerr,)

cooo 16K RAM User MemorY ( to 4BK S!:IS ten,)

FFFF 65535

'
Appen dix C - 48K TRS-80 Level II with Disk Memory Map 243
LOAD r~~ESET
@ (Lower· Ca'::.e) EDIT
ABS EL~)E
*.,.. LOC
\to" F:ESTOF:E
fi:ESUt-1E
AND um * LOG
~rrr
L_ur
EOF HTUF:N
ASC r;:IGHT·:Ji
ATN EF:L.
,).•
If. LSET
CDBL ERF: MHl RND
r1H:GE "'"· RSET
CHIU
CHIT
EF:F:cm
EXF' * MID·t
d.·
'i· SAVE
FIELD "'If·... t1KD~~ SET

*
CLEAF:
CLOSE * FTV
J.r, ~ r'it·;;r ·:~>
Mf-;5$
SGN
r· T'l
!'<
FOF:
*
;:) J.
CLS r-nrr
CMD FRE NnJ \Jt..'tfo,.

* NEXT f;TEP
CONT
cos
* GET
GO SUB NOT STOP
GOTO ON STRING$
CSNG
STR·$
* CVD IF
INt;:EY$
* OPEN
OR TAB
CVI
** cvs INP
INPUT
OUT
PEEK
TAN
THEN
IIATA $
DEFDBL
DEFFN
w
'I"· INSTR
INT
POINT
PO!"~:E * TIME·
H:OFF
* IIEFINT * !GLL
LEFT$
POS
PRINT
Tr.pq r:\._1 It
USING
IIEFSNG USR
* DEFUSR
IIEFSTR
LET
LEN * F:ANDOM PUT
* lJAL
LINE F:EAD lJAF:F'TR
DELETE
DIM LIST REM

*indi cates Level II Disk BASIC


s
244 Appe ndix D - Level II Instru ction s and Reserved Word
Extended UtilitY Commands (maY use all of memorY)
BACKUP duPlicate an entire diskette
fORMAT -- PrePare a data diskette
Auxilliar~ UtilitY Pro~rams (maY use all of memory)
TAPEDISK coPY a taPe file to a disk file
DISKDUMP/BAS -- disPlay a disk file
Syste~ Commands (load below 5200 Hex)
BASIC2 JumP to Level II BASIC
DEBUG examine and alter resisters and ROM
TRACE disPlaY the PC resister
LibrarY ColftiJtands.
AUTO modifY the Power-uP seGuence
ATTRIB set the Protection level on a file
CLOCK disPlaY the sYstem time on screen
COPY duPlicate a file
DATE set the system date
DUMP coPY memorY to a disk file
KILL delete a file
FREE disPlaY the amount of free sPace on all drives
liB disPlaY all librarY commands
liST disPlaY a text file
LOAD load a machine lansuaae file
PRINT list a text file on the line Printer
PROT chanae the Protection of all non-system files
RENAME chanse a file's name
TIME set the system closk
VERIFY have TRSDOS verify all user disk writes

Appendix E - TRSDOS Commands 245


Level II Error Codes
Code Abbreviation Error·
1 NF NEXT without FOR
2 SN s~ntax error
3 RG RETURN without GOSUB
4 0[1 Out of data
5 FC Illesal function call
6 ov Overflow
7 OM Out of ll•emor ~
8 UL Undefined 1ine
9 BS SubscriPt out. of ranse
10 DD Redimensioned arraY
11 /0 Division b~ zero
12 ID Illesal use of a direct command
13 TM T~Pe mi Sll1atch
14 OS Out of str-ins SPace
15 LS Strins lonser than 255 characters
16 ST Strins for-mula too comPlex
17 CN Can't CONT after END or EDIT
18 NR No RESUME before end of Prosr-am
19 RW RESUME without error
20 UE UnPrintable error after- usins ERROR
21 MO Missins oPerand
22 FD Bad file data
23 L3 Disk BASIC onl~
24-49 not used

246 Appendix F - Error Codes

' )
Disk BASIC Error Codes
Code Messa~e Error
50 FIELD OVERFLOW More than 255 bstes for a buffer
51 INTERNAL ERROR DOS or disk I/0 fault
52 BAD FILE NUMBER File number used without OPEN
53 FILE NOT FOUND Read attemPted on nonexistent file
54 BAD FILE MODE Disk I/0 conflicts with OPEN mode
55,56 not used
57 DISK I/0 ERROR Error during data transfer
58-60 not. used
61 DISK FULL No more room
62 INPUT PAST END End of file reached during sea. inPut
63 BAD RECORD NUMBER Record number <1 or >340
64 BAD FILENAME Invalid file SPecification
65 not used
66 DIRECT STATEMENT AttemPt to LOAD, RUN, or MERGE a
IN FILE dc::t.a file
67 TOO MANY FILES Tried 49th, file on diskette
68 DISK WIUTE- Wrile-Protecl notch was covered
PROTECTED
69 FILE ACCESS DENIED

Appendix F - Error Codes 247


(- J
Index AND 4r 50 BinarY oPerations 6
ANSI Flowcharts 167 BinarY tree structure 124
ANSI 166 Bit coruparison 5
ASC 23 BlanK Lines and Text
ASCII files 130 Fornratlins 182
ASCII 23, lOS, 118 Boolean oPerators 4
Accessins Direct Access Files Bouncins Dots 90
193 Bouncins dots <Pros C5P16)
Accessins Seouential Files 92
193 Bouncins dots comPuter art
Accessins a record 193 (Pros C5Pll) 94
Accounts receivable file Buffer descriPtion ' sketch
build£~r (Pros C8P1) 143 136
Addition, verY lons (Pros Buffer 134, 143
C2P6) 25 Buildins Direct Access Files
AruPersand (l) Prefix 52 189
Ansled line (Pros C5P13) 87 Buildins Seouential Files
AnticiPaiin s User ResPonses 188
155 Buildins 187
APostroPhe for REM 14
f~PP le- II 9
Arsun,en t.s 26
fir·rass 13 C10P1: Poor Pf'OSran, st.r·ucture
At ( ') ssntbol 75 174
C10P2: Fair Pr·oSr<Hlt structure
175
C10P3! Good Pf'OSr·am structure
BASIC-PLUS <DEC) 10 175
Banner Printer (Pros C5P8) C12P1! Seouential file
71 builder· 188
BarsraPhs 66 C12P2: Seauential file of
Binars Seauence Search Tree sir inss 188
<BSST) 213 C12P3: Direct access file
Binary Sorts 199 buUciew l91
Binary conversion <Pros C1P4) C12P4! Direct access in
5 seauential order 193

249
C12P5: Direct access bs C5P5: Rainfal l barsraph ,
hashed Ke~s 196 r·evised 67
C12P6: ComParison of three C5P6: Table-d riven diSit 68
sorts 202 C5P7: SnooPY 70
C12P7: Statisti cs s~stem 205 C5P8t Messase s on screen or
C1P1: Lar~est of 3 numbers 2 Pr· in t.er- 7l
C1P2: Larsest of 3 numbers 3 C5P9: Christm as tree 77
C1P3: Larsest of 3 numbers 4 C6P1: Demons tration of strins
C1P4: Binar~ conversi on function s :1.06
C2P1: Random numbers 12 C6P2! Reversa l of names 107
C2P2: Question naire analYsis C6P3: Usins INKEYS for-
15 numeric variable s 108
C2P3: Shufflin s cards 18 C6P4: Flash a PromPt while
C2P4: Record album balancin s l<eYinS in a strins 109
1? C6P5: Usins LINE INPUT 110
C2P5: Reverse last and first C6P6: Substitu tion within a
ncH11e 23 str·ins 111
C2P6: Ver~ Ions addition 25 C6P7: Timins of arithme tic
C3P1: Chart of various oPer·atio ns 113
func:U.ons 30 C6PB: SimPle math usins limed
C3P2: Table~ function s with inPuts :J.14
TABs 32 C6P9: Stopwatc h to 100lhs of
C3P3: Table' function s with a second 115
PRINT USING 36 C7P1: Store a numer-ic matrix
C3P4: Variable -sized outPut or1 taPe 122
fields 37 C7P2: Geosr-aPhY auiz Same
C3P5! Memors tester 41 125
C4P1: Timins of operatio ns, C7P3! Sort-mer -se of
various t~Pes 46 seauent ial file 127
C5P10: Characte r sraPhics to C7P4! Renumber Disk BASIC
n,al\e disi ts 82 H· osr- ams 130
C5P10A: ChaPter heads 83 CBP1! Direct access accounts
C5P11: Diasonal .1 ine 85 receivab le file builder
C5P12: Line, horizon tal or 143
ver· tical 86 CBP2! Direct access file
C5P13: Polar method for update 145
ansled lines 87 CBP3! Messase of the da~ 147
C5P14: Line, an~ ansle, bY C9P1: Check disit. calculat or
Cartesia n method 88 160
C5P15: Circler usins sine and CHR$ 23, 76, 79
cosine 89 CLEAR 76
C5P16: Bouncins dots 92 CLOAD 118
C5P17: Bouncins dots comPuter CLOSE 120
ar· t 94 CSAVE 117
C5P18: LissaJou s Patterns 98 CVD 141
C5P1: Sine and cosine SraPh CVI 141.
56 cvs 141
C5P2: EnterPr ise sraPhic 56 Card shufflin s 18
C5P3: PiPe sraPhic 61 Car·toord. ns 81
C5P4: Rainfall barsraPh 66

250 Index
ChaPte r heads <Pros C5P10A) DiJkst. ra, Edsser 174
83 Direct Access File Creatio n
Charac ter GraPhics 75 142
Charac ter Set, TRS-80 76 Direct Access File Process ing
Charac ter sraPhic s to make 133? 144
disits <Pros C5P10) 82 Direct access file builder
Chart of various functio ns <Pros Cl2P3) 191
( Pr·os C3Pl) 30 Direct access file update
Check disit calcula tion <Pros (Pros C8P2) 145
C9P1 ) 1M Direct access in seauen tial
Check disits 157 or·der· ( Pr·os C12P4) 193
Christm as tree <Pros C5P9) Direct access with hash
. 77 addres sins <Pros C12P5)
Circles usins sine and cosine :1.96
<Pros C5P15) 89 Discrin finant 3
Collisi on with wall 91 Disk BASIC 52, 1.18, 154
Commands for Data Files 120 Disk DPerat inS s~stem 103
Commands for Prosram Files Documentation 179
l17 Dots, Bounci ns 90
Conver sationa l Prosrammins Double Precisi on Real
149 Var· iables 45
Conver sion of Consta nts 45 Double Precisi on additio n,
Conver sion of nU111er· ic to timins 47
sir ins 140 DUillllJH <:wsun,en ts 26
Con ver· s ion of s t.r· ins to
nun,er ic 141
Cued inF·ut. '10
LJ

ELSE clause 3
ENTER l·~e~ 109 ~ 146, 151
ERL 153
D.A. files <see Direct Access ERR 153
files) 193 EnterP rise SraPhic (Pros
DATE 112 C5P2) 58
DEFDBL 51 Exchanse Sorts 199
DEFINT 51 ExPone ntiation imase 37
DEFSNG 51 Extended BASIC 2
DEFSTR 51 Externa l Documentation 183
DEFUSR 103
DIM 12
Data transfe r to disk, sketch
135 FIELD 134
Decisio ns and Branch ins 1 File ManiPu lation Technia ues
Deletin s from D.A. files 197 187
Diason al line <Pros C5P11) File uPdate , direct access
85 ( Pr·os C8F'2) 145
Dice, simula tin£ throws of Fill charac ters wiLh PRINT
11 USING 38
Disit sraPh 68 Flashin s a PromPt <Pros C6P4>
Disits with charac ter 109
sraPhic s (pro! C5P10) 82 Flowch art sYmbols, ANSI 168
Index 251
Flowcha rt, Quickso rt 201 recor-d 236
Flowcha rt, Sheil-M etzner sort INVPR1: Add items to
200 inventor·~:-; 216
Flowcha rt, all-dis it inPut INVPR2: Traverse file, list
1.69 in sorted order 219
Flowcha rt, statisti cs Packase INVPR3: Record deletion 221
INVPR4: Access and update a
Flowcha rt, structur es 173 r·ecoPd 22·1-
Flowcha rt, s~mbolic 184 INVPRS: List recordsr
Functio ns, user-def ined 26 PhYsical order 227
INVPR6: List deleted Parts
229
INVPR7: Balance tree 230
GEOGRAPH record lasoul 123 INVPRB: Lisl all files 234
GET 137 INVPR9: Delele a file 235
GOTO-less Prosrammins 174 ImPlicit conversi on 48
GOTO l In-ruemor~ sortins 198
GeosraPhs ouiz Same <Pros Indentat ion 10, 11
C7P2) 125 Index to prosram s in
GraPhic Codes 78 Inventor Y Ssstem 214
GraPhic to BinarY Conversi on Informin s the User Durins
78 Process ins 162
GraPhin s sine and cosine InPut. (file f110de) 120
functions:. Inteser Boolean OPeratio ns
GraPhin s with tabs Onh! ~:ule 50
Inleser Truncat ion, Otherwis e
Roundins Rule 50
Int.eser Variable s 44
HELP 184 Inteser addition , limins 47
HaPPY HoPi <Pros C5P17) 94 Int.eser· lo binar'::! (Pros ClP4)
Hash Addressi ng 189 5
HelP Files 184 Internal Documentation 179
Hexadecimal Constan ts 52 Inventor s S'::!stem APPlica tion
Hierarch~ chart 176 213
His t..os;r an1s 66 Inventor y system index 214
Horizon tal line 86 Inventor Y system record
descr·ip tion 214
Inventor s system, add items
(PPoS INVPR1) 216
IF-THEN-ELSE 1, 171, 175 Inventor Y s'::!stem' balance
IF- THEN 1 tree (Pros INVPR7} 230
IF 1 Inventor Y s~stem' delete a
nw;EY$ 101, 151, 168 file (Pros INVPR9) 235
I NP 40 Inventor Y system, delete
INPUT :1: 121 records (Pros INVPR3l 221
INSTR 105, 130 InventorY system, disPlaY
INT ~·0 selected record (Pros
INVMAIN: Main driver Prosram INlJP~:10} 236
215 Inventor Y swstem' list all
INVPRlO: DisPlaY selected files <Pros INVPR8l 234

252 Index
Inventorw swsteru' list Losical OPerators 4
deleted Parts <·Pros LoSical record 134
INVPR6) 229 Lons Variable Names 43
Inventorw swstem, list in Lons addition (Pros C2P6) 25
PhYsical order <Pros
1NVPR5} 227
InventorY swstem' list in
sorted order <Pros INUPR2) MEMORY SIZE messase 104
219 MERGE ·119
InventorY swstem, main driver MID$ for rePlacement 111
(Pros INVMAIN) 215 MIDS 22, 105, 111, 130
Inventory sYstem' record MKD$ 140
access and uPdate <Pros MKI$ 140
INVPR4) 224 MKSS 140
Invocation, of a function 26 MemorY Storase After Mixed
Iteration structure 171 OPerations 49
MemorY tester (Pros C3P5) 41
Menu, statistics sYstem 205
Menus 149, 151
KILL 118, 120 Messase of the .daY <Pros
Kew, record 189 CBP3) 147
Knuth, Donald 199 Messases on screen or Printer
(Pros C5P8) 71
Microsoft 9, 43
Mode of a file 120
LEFTS 22 Modifwins D.A. files 197
LEN 22 Modulus eleven checK disits
LINE INPUT t 121 158
LINE INPUT examPles (Pros Monte Carlo techniGue 18
C6P5>. 110 Most Precise OPerand Rule 49
LINE INPUT 109, 146, 151 MultiPle Statements on a Line
LOAD 118 9
LOF 138
LPRINT 2, 30
LSET 134, 138
Larse arraY Prosram <Pros NOT •h 50
C2P2) 15 Name reversal <Pros C2P5) 23
Larsest of 3 numbers <Pross Name reversal <Pros C6P2)
C1P1, C1P2, C1P3) 2, 3, 4 107
Lemnisc.ates 98 No Inteser Division Rule 50
LiRIBCOn S 98 Numeric variable inPut with
Line Printer GraPhics 55 INKEYS <Pros C6P3> 108
Line feed 10, 11
Line numbers, srouPed 183
Line, anY ansle, bY Cartesian
method <Pros C5P14> 88 ON ERROR GOTO 153
Line, horizontal or vertical ON-GOSUB 6
<Pros C5P12) 86 ON-GOTO 6
LinKs of a binarY tree 124 OPEN 120
LissaJous fisures 98 OR 4, 50
Index 253
OUT 39 Prosrammins Structures 171
Octal Constants 52 Pseudo random number
OutPut (file mode) 120 senerators 11
Overflow area 190

Quadratic eaualion 3
PDP-11 (DEC> 1Q, 11 Questionnaire analYsis (Pros
PEEt\ 40, 115 C2P2) 15
F'OINT 86 Quicksort flowchart 201
Pot\E 41, Bb 85
POS 105
PRINT :t 121
PRINT tn, USING 122 RAM 103
PRINT USING specifiers, table RANDOM 11
34 REM 179
PRINT USING, fill characters RESET B5, 90
38 RESUME 153
PRINT USING, sirin~ RIGHT$ 22, 106
speci fier·s 38 RND 10, 11
PRINT USING 30, 33 ROM 103
PRINT 75, 108 RSET 134, 138
PUT 134, 139, 189 RUN 118
Patterns <Pros C5P18) 98 Rainfall barsraPh <Prog C5P4)
Percent (%) sisn for inteser 66
44 Rainfall bar~raPh, revised
Percent (%) sisn for string (Pro~ CSPS ) 67
39 Random (file mode) 120
Phrase Flowcharts 167 Random numbers <Pros C2P1>
PhYsical record 134 12
Pick-and-switch <Monte Carlo) Random temPerature settinss
techniaue 18 in PiPe 64
Picture Within Prosram 69 Real Variables 44
PiPe sraPhii <Pros C5P3> 61 Real number addition, iimins
PiPe temPeratures 60 47
Pixel GraPhics 84 Record album balancins <Pros
Pi>:els 78 C2P4 > 19
Polar method for ansled lines Renumberins Disk BASIC
<Prog C5P13> 87 Prosrams <Prog C7P4> 130
Praise and Chastisement 160 Reverse last and first name
Primitive BASIC 1 (Pross C2P5, C6P2) 23, 107
Process-time messases 162 Roses, computer~drawn 98
Prosram Comments 180 Run BooK 184
Pro~ram Plannins 166
Pro~ram structure, bad <Pros
C10P1) 174
Pro~ran, struct.ur·e, fair (Pros SAVE 117
C10P2) 175 SET 84, 90
Pro~ram structure, sood <Pros SGN 8
C10P3 > 175 STR$ 24
254 Index

I .,

.,I-->;-\
STRING$ 75 USING 39
Scient ific notatio n iruase 38 Structu re chart, Statist ics
Screen overflo w 31 tl~.;.~. "l-PHI 2(l.<j.
Sector buffer 134 Structu re chart, direct
Selecti on structu re 171 access file builder 190
Seouence structu re 171 St.r·uct.u r·p Cfli:':r t. :!.7 6, lB3
Seauen lial Access File Structu red Prosrammins 165
Pr·oces sins 117 Subscr iPted Variab les 12
Seauen lial File INPUT and Substit ution within a st.rins
PRINT 121 ( F'r·os C6P6) l11
Seouen tial file builder (Pros Ssrubolic flowch art 184
Cl2P1) 188
Seauen lial file commands,
table 122
Seauen lial file of slrinss TAB 24
f. Pros C12P2) 188 TAble-Driven Picture 68
Seauen lial filesr buildin s TIME$ 112
188 TRSDOS BASIC 105
She 11 sor·l 199 TRSDOS 103, 112, 118, 134
Sheil-M etzner sort 127, 199 Table, PRINT USING specif iers
Shuff 1 ins car·ds ( Pr·os C2P3) 34
18 Table, functio ns with PRINT
Sine and cosine sraPh <Pros USING <Pros C3P3) 36
C5P1 ) 56 Table, functio ns with TABs
Sinsle Precisi on Real ( Pr·os C3F'2 ) 32
Variab les 44 Table, number of records that
Six-bi t sraPhic code 78 can be sorted in memorY
Snoopy (Pros C5F'7) 70 198
Sons selecti on (Pros C2P4) Table, seauen tial file
19 contlltands 122
Sort, Sheil-M etzner 127 Table-d riven Disit (Pros
Sort-m erse of seauen tial file C:iP6) 68
( Pr·os C7P3) 127 Tabula tion Codes 77
SortinS alsorith ms 199 The Charac ter Set 76
Sorlins time table 203 Ther·n,al sradie nt sr-aPhic 60
Sor tins 197 Timed inPuts for- simPle ruath
Sorts comParison <Pros C12P6) (Pros C6P8) 114
202 Tiruins of arithm etic
Statis tics ssste~ <Pros oPer-at ions <Pros C6P7) 113
C12P7) 205 Timins of oPerat ions, table
Statis tics ssstem menu 205 47
Statis tics sy~tem structu re Timins of operat ions, various
char i 204 tYPes (ProS C4P1) 46
StoPwa tch <Pros C6P9) 115 Tiruins to lOOth of a second
Storins a numeric matrix on (Pros C6P9) 115
taPe (Pros C7P1 ) 122 Top-down Prosrammins 176
Strins Functio ns 22 Trailin s zeros' Printin s of
Strins functio n de~onslraiion 36
( Pr·os C6P1) 106 TYPe declara tion charac ter
Strins specif iers with PRINT 44
Index 255
UNTIL iteratio n structur e
175
USRn 103
User Prompts 149
User manual 184
User resPonse s 155
User-de fined function 26,
107
Uses for GraPhics Charact ers
79
Usins Meruor~ Lo Hold Lhe
Picture 60

V& ~
VARPTR . 53
Variable l~Pes, iable of 46
Variable T~Pes 44
Variabl e-sized ouLPui fields
<Pros C3P4)
Vertica l line 86
VerY lons addition <Pros
C2P6) 25

Wall, collisio n with 91


Windowboxes 181

256 Index

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy