Techniques of BASIC (1981)
Techniques of BASIC (1981)
·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
ISBN 0-697--{)9951- 2
Introduction xiii
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
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
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.
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.
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
120 I
2(l0 let user sLoP or· Proceed, but accePt onll:l YES or NO answer
I
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
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 :
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)
10 FILENAME: "C1P4''
I
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
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 .
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 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 ••••••••• ••••
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.
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.
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 'random intese rs
20 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
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.
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>
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:
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.
10 FILENAME: "C2F'2"
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
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.
11·--,
10 I FILENAME: "C2P4"
20 'FUNCTION! MONTECARLO SELECTION OF SONG PROGRAMS
30 'AUTHOR : JPG/JDR 12/79
40 I .
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
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
LEN The LEN function returns the length of the string. argument.
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$.
Instr·uct.ion Out..Pu t
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.
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.
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
Inst.r·uct..ion OutPut.
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
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
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.
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
See Table 3.1 for a summary of these image specifiers and their
effects.
Instructio n Out..?ut
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
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
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 -
Instruction Output.
----------- --·----
10 AS="ABC": XS= XYZ"! 1$:::"!
11 II
70 PRINT II
CLONE" B. T. CLONE
Instruction Output.
90 AS="% z~~:BS="%%"
100 XS="MONTANA YS="OHIO"
11 :
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)
40 OUT 127,60
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)
70 X=PEEI\(15360+1>
80 POKE 15650, 65
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
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)
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.
Chapter 4 Variables
45
Inteser Sinsle Precision Double f'reci sian
2 8
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
10 FILENAME: . "C4Pl"
I
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
48 Chapter 4 Variable s
Ins true lion Ou iF-U t.
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 .
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
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.
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 .
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
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
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 * 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 '
60 Chapter 5 Graphics
ranges.
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
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
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.
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
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
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
***
***-
*****
*****
*****,.....
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
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:**
** ** ** *-***** **
****************
: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.
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.
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 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.
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..
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:
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
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
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.
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.
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 '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- -- -----¥--
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 '')
' 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
94 Chapter 5 Graphics
440 next 4 lines actua llY tell the dot where to move
1
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
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.
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.
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:
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.
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
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
Bleam: Jo
.Jo Bleau;.:
Farnsworth Ferdinand
Ferdinand Farnsworth
Badinase Bill~bob
Bill~bob Badinase
$$END
1050 m~ke sure keY is a disit, then add slrinss & So back
1
I I
I !
10 FILENAME! "C6P4"
I
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).
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
' \
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
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.
Instruction Ou lPu t
MM/DD/YY HH:MM: SS
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.
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
' '
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
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
' 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:
RUN
SAVE "PROG6",A Save the Prosran, in ntemor·'::! ont.o disK
in ASCII (character) format., one record
Per line.
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
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:
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
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/
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
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
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
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
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 "
660 1
if done, check for ON ••• GOT0 s and ON ••• GOSUB's
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
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
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
~· 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
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:
~~ 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
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:
GETfn
or
GET fn, rn
100 GET 2, ,J
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.
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:
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 5
> I
r .,
I ·I
Case 1 : Conversion to character strings, then storage in the
buffer.
I$ S$ D$
2 4 8
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.
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
l )
Length Name Descript ion
94 bytes total
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
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.
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 ,-'
RUN "MESSAGE"
10 FILENAME! "C8P3"
I
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/
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
+
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
7. SUMMA~:Y REPORTS
(2)
Statistics Packase!
5. Chi -S8uar·e
6. T-Tesl
7. ItescriPtive
8. Cor-r·elalion
9. An ova
10. Probabilities
(3)
G A ME S
C Chess
A Ani rnal
B Breakout
I Ivanhoe
E En em~ Be .low
T Ti.c-Tac-Toe
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.
50 X=Y /N
60 PRINT "X=" ;x
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.
\ ...
NAME? BACILLUS, VACILLA
PLEASE OMIT COMMAS IN DATA INPUT
NAME? BACILLUS VACILLA
STREET ADDRESS? 66 SEPSIS ST
CITY't WOUND
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
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
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.
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
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
' '
1. _____:_ -··- '- I
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
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.
'-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.
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
-T
Symbol Name Meaning
__)
( Termina l Start or end of a
sequence of operatio ns
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.
- - I .
200 IF A THEN GOSUB 500: GOTO 200
•
300 IF X<Y THEN GOSllB 500t 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
-, ---- 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:
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
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.
\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
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,~~
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
lines.
Other REMs appear as last statem ents in multi statem ent
·~ '
1, ,.
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
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
******************************
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
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
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.
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.
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.
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
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.
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
~~Erl ~('\~~~
~E::-('-G.~
~rd ~~0"'~'
~ ~~~!f-low
Figure 12.1 Structure Chart for Program C12P3
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
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
190 NEXT I
1000(1 CLOSE! END
73
74
75
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.
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
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
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..
k -·)
I.)
f •
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
2100 J=Jtl
2110 IF J<=K THEN 2050
ELSE 2020
2120 RETURN
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-
~
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
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)
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
' '
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;
' !
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
' 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
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
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.
This is the dialog that INVPRI produces as the user executes it.
''I
\""J
. . ~
This is what the output looks like from a typical run of the
traversal program.
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
l •
INVPRS The INVPRS program lists all records in their physical order,
ignoring the BSST's logically sorted order.
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
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/'!' ~
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
' )
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
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
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
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!
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
--- .. --~ ...... ---~-·--.,_-----------·--------------------------..;.----
\ '
I-
r-
f -
f •
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
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
' )
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
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
256 Index