Programming in BASIC For Personal Computers (1981)
Programming in BASIC For Personal Computers (1981)
in BASIC
for Personal
Computers
Research and Development Consultant
Programming
in OASIC
for Personal
Computers
Editorial/production supervision
by Gary Samartino a:t:ld Daniela Lodes
Interior design by Gary Samartino
Cover design by Jorge Hernandes
Manufacturing buyer: Joyce Levatino
10 9 8 7 6 5 4 3 2
Preface xi
v
vi Contents
Index 327
Preface
Computer power is within the grasp of most people now living in the
advanced technological societies of today. Computers are no longer
limited to large rooms in industry, business, universities, and military
installations. You might even know a youngster down the street who
plays with a computer instead of building model airplanes or flying
kites. Or maybe you have a computer sitting there on the desk in
front of you.
Perhaps computer power has moved into the consumer market-
place a bit too quickly. Many owners of new personal computing sys-
tems are not prepared to handle the programming tasks and are thus
facing a sort of computer shock. Once the novelty of running pre-
recorded cassette programs wears off, many people begin wondering
if the whole affair was worth the investment.
"I have this dandy new computer at home. Now what can I do
with it, and how do I go about doing it?" That's where this book
enters the scene.
The BASIC programming language is the overwhelming choice
for personal computing systems, and this book is about programming
in BASIC. What you can learn here applies to most personal compu-
ters on the market-including Radio Shack's TRS-BO, Apple II, and
the Commodore PET. The notions apply to a number of other
brands, but these three happen to be the pace-setters.
There is much more to BASIC programming than simply learning
the fundamental expressions. If that were not so, you could learn
xi
xii Preface
Computers are virtually useless unless there is some means for getting
information into them from the outside world. In the case of small
personal computers, this generally means entering information from
a keyboard, cassette tape machine, or disk operating system (DOS).
In some special cases, input devices can also include joystick con-
trols, pushbuttons, and a host of interfacing circuits that translate
electrical signals into computer "words."
By the same token, it is important to provide some means for
presenting computer information to the outside world in an intelli-
gible fashion. Usually, this is handled by a cathode ray tube (CRT)
monitor or, in some instances, a line printer. In the first case, the
computer-generated information is presented in the form of alpha-
numeric characters (combinations of ordinary letters and numerals)
and special symbols on the face of the CRT. In the second case, the
same sort of information is presented as typewritten hardcopy on a
sheet of paper.
For our purposes throughout this book, assume the system is
operating with the most common input/output (I/O) configura-
1
2 Ch.1 The System READY Status and PRINT Command
READY
>
Other expressions and symbols might precede this particular
message when the system is first turned on, but once this message
appears on the screen, you know that the system is expecting you to
begin entering new data and instructions.
The READY expression is automatically generated from within
the system, and it indicates that the system has just entered the
command mode of operation.
The greater-than symbol (», properly called the prompt symbol,
also indicates that the system is ready to accept information from
the keyboard. But unlike the READY message, which appears only
when the system first enters the command mode, the prompt symbol
appear each time the system is expecting a new line of information,
whether that line happens to be the first one or not.
READY
>
The system is then ready to start all over again. You enter a line of
information and strike the ENTER key. The computer does whatever
you tell it to do, then returns the READY status message again-and
so on, and so on, and so on.
EXAMPLE 1-1
READY
>PRINT "DAVID"
DAVID
READY
>
The whole thing began with the system printing READY to indicate it has
just entered the command mode of operation. It then printed the prompt
symbol at the beginning of the next line.
The operator responded by typing a valid command, PRINT "DAVID" ,
and striking the ENTER key.
Immediately after striking the ENTER key, the system did exactly what
it was told to do-print the expression DAVID. It then returned to the com-
mandmode.
When the sequence was first started, the screen showed only the READY
status message:
READY
>
The indication is that the system had just entered the command mode (as
signaled by READY) and is prepared to receive some instructions from the
keyboard (as signaled by the prompt and cursor symbols).
The user then typed
PRINT "DAVID"
And before striking the ENTER key, the display looked like this:
READY
>PRINT"DAVID"_
Note that the prompt symbol remained at the beginning of the second
line, but the cursor moved toward the right, still indicating where the
next character or space would go. There is no more information to be
entered, however.
Striking the ENTER key at this point told the computer that the com-
mand sequence from the keyboard was complete and that it was time for
the computer to execute that particular command. Here is what the com-
puter did:
6
Sec.1-2 The PRINT "expression" Command 7
DAVID
READY
>
What did the computer do? It executed the command, PRINT "DAVID".
It printed that name enclosed in quotes. And upon executing that command,
the system immediately returned to the command mode of operation, gen-
erating the
READY
>
EXAMPLE 1-2
READY
>PRINT "DAVID"
DAVID
READY
>PRINT "PRINT NEW@@#2A"
PRINT NEW@@#2A
READY
>
The lines showing PRINT "expression" were all entered by the user,
followed by an ENTER-key operation. The remainder of the work was done
by the computer itself. In one case it PRINT-ed DAVID, and in the other it
PRINToed nonsense such as PRINT NEW @@#2A.
Attempting to include quotation marks within the PRINToed expression
causes a problem, however. The machine cannot tell the difference between
8 Ch.1 The System READY Status and PRINT Command
READY
>PRINT "THE COMPUTER SAYS, 'HELLO."'_
~______________PR_'_N_T_"_PR_'_N_T_'P_R_'_N_T_'''________________~I?
Sec.1-2 The PRINT "expression" Command 9
~___________________PR__IN_T_'_'A_"______________________~I?
The response will be simply A, followed by the READY status characters.
PR_I_N_T_'_'2_+3_"______________________
L -__________________ ~I?
The response will be 2+3, followed by the READY status characters-
nothing more, nothing less.
~__________________P_R_I_N_T_"_A_$'_'____________________~I?
It will return the A$ characters.
READY
>PRINT "PRINT 'PRINT'"
PRINT 'PRINT'
READY
>PRINT "A"
A
READY
>PRINT "2+3"
2+3
READY
>PRINT"A$"
A$
READY
>
10 Ch.1 The System READY Status and PRINT Command
In ordinary algebra, letters of the alphabet are often used for terms
that can take on varying numerical values. The expression A+ I, for
example, is equal to any desired number, A, plus one.
BASIC has a very nice, built-in algebraic feature that allows the
user to assign numeric values to any letter of the alphabet; and the
PRINT command is used for displaying the numerical values. Con-
sider the following sequence of operations:
EXAMPLE 1-7
READY
>A=10
READY
>PRINT A
10
READY
>
EXAMPLE 1-8
READY
>A=25
READY
>PRINT A
25
READY
>PRINT "A"
A
READY
>
In this example, you will fmd two different PRINT commands: PRINT A
and PRINT" A". Although they are quite similar in appearance, they mean
two entirely different things. Without enclosing the A in quotes, the com-
mand is a request that says, "Print the current numerical value of variable
A." Otherwise the request is "Print the letter A."
puter has set aside a certain amount of memory for holding the
values of numerical variables, and the size of that memory is often
far less than that required for storing 912 separate variables.
You do have the option of choosing from 912 variables in this
instance, but the actual number of them you can use at anyone time
is determined by the machine at hand. Consult your owner's manual
to determine the size of your variable memory space.
Some systems also accept numerical variables having more than
two characters, but in such cases, only the first two are ever con-
sidered. If you enter AAB=I~, for example and then call for a
PRINT AAA at a later time, the system returns IC/J. The third char-
acter is ignored. Check your manual to see if this situation might be
handled differently on your machine.
In the process of describing and demonstrating the PRINT
numerical variable command, we have actually managed to introduce
another kind of command-numerical variable = numerical value.
When operating in the command mode, typing a numerical variable,
an equal sign, a numerical value, and then striking the ENTER key
tells the system to assign that particular numerical value to that par-
ticular numerical variable.
EXAMPLE 1-9
READY
>A=1
Sec. 1-4 The PRINT math Command 13
READY
>B=2
READY
>C=-4
READY
>PRINT A
1
READY
>PRINT B
2
READY
>PRINTC
-4
READY
>
In this instance, the operator used the numerical variable = numerical
value command to preset, or initialize, the values of variables A, B, and C
to 1,2, and -4, respectively. The operator then did three PRINT numerical
variable commands in succession. The computer responded by printing the
numerical values that were established in the fIrst three LET commands.
Consider this:
READY
>PRINT2+3_
READY
>PRINT2+3
5
READY
>
READY
>PRINT "2+3"
2+3
READY
>PRINT 2+3
5
READY
>-
EXAMPLE 1-10
READY
>PRINT 2+3
5
READY
>PRINT 2-3
-1
READY
>PRINT 2*3
6
READY
>PRINT 2/3
.666667
READY
>PRINT 2t3
8
READY
>PRINT SQR(2)
1.41421
READY
>PRINT LOG(2)
.693147
READY
>
+ add a+b
subtract a-b
* multiply aXb
I divide alb
t exponent ab
SQR(n) square root of n v'n
LOG(n) natural log of n loge n
(base e)
ABS(n) absolute value of n ±n =n
EXP(n) natural exponential of n en
SIN(n) sine of n, where n is sin(n)
in radians
COS(n) cosine of n, where n is cos(n)
in radians
TAN(n) tangent of n, where n is tan(n)
in radians
16 Ch.1 The System READY Status and PRINT Command
EXAMPLE 1-11
READY
>A=10
READY
>B=2
READY
>PRINT A+B
12
READY
>
In this case, the user first set the values of A and B to 10 and 2, respec-
tively. The next step then calls for summing the values of the two variables
and printing the result.
EXAMPLE 1-12
READY
>A=10
READY
>B=2
READY
>C=A+B
READY
>PRINT C
12
READY
>
The result is the same in both cases. Example 1-11 uses a PRINT
math command that includes a pair of predefined numerical variables.
Example 1-12, on the other hand, first solves the math problem,
Sec. 1-5 The PRINT string variable Command 17
EXAMPLE 1-13
READY
>C=A+B
READY
>A=10
READY
>B=2
READY
>PRINT C
o
READY
>
EXAMPLE 1-14
READY
>A$="MUGGINS"
READY
>PRINT A$
MUGGINS
READY
>
A null string is a string variable that has no value at all. The fol-
lowing example shows how to create a null string, and it shows what
happens if the operator tries to get the system to print a null string:
READY
>A$=""
Sec. 1-5 The PR I NT string variable Command 19
READY
>PRINT A$
READY
>
The null string is defined by the operation A$="". This is a string
variable = "expression" command where the expression amounts to
nothing at all-there is nothing enclosed within the quotes. So when
the operator entered the PRINT A$ command, the system printed
nothing. It just left a blank space.
Can you think of any applications of string variables? How about
an instance where the programmer wants to call up printed state-
ments that change under certain circumstances? Suppose that a
certain program calls for printing the name NANCY at one time and
then BILL at some other time?
The same string variable, C$, perhaps, could be inserted into the
program at one particular point. At one time it could be defined as
NANCY, and at a later time it could be defined as BILL.
Working with string variables in the command mode can be a lot
of fun. Take a look at this example:
EXAMPLE 1-15
READY
>A$="MUGGIN5 "
READY
>B$="15 51 LL Y "
READY
>C$="BUT HAPPY "
If the operator now types the command PRINT B$ and strikes the ENTER
key, the computer returns IS SILLY; and entering the command PRINT C$
makes the computer answer with BUT HAPPY. That's all nice, but let's take
advantage of something else. Suppose that the operator does this:
READY
>PRINT A$+B$+C$_
What is going to happen when the operator hits the ENTER key? Here is
what happens:
String variables, you see, can be strung together, and that is why
they are called string variables. Of course, string variables can be
"strung" together in different ways:
EXAMPLE 1-16
READY
>PRINT C$+A$+B$
BUT HAPPY MUGGINS IS SI LL Y
READY
>
The material in this chapter deals explicitly with the following kinds
of PRINT commands:
Command Example
Command Example
EXERCISES
1-1 Derme the following terms and expressions introduced in this chapter:
(a) DOS
(b) I/O
(c) CRT monitor
(d) prompt symbol
(e) cursor symbol
(f) hardcopy
(g) alphanumeric character
(h) numerical variable
(i) string variable
G) null string
(k) concatenate
1-2 What is the Significance of READY as it appears on the monitor? What is
the significance of the prompt symbol as it appears on the monitor? What
is the difference in meaning between READY and the prompt symbol?
1-3 What does the cursor indicate? How can it be moved to the right without
leaving behind a visible character? How can it be moved to the left, erasing
characters as it goes along?
ell. 1 Exercises 23
24
Sec. 2-1 Line Numbers Make the Difference 25
EXAMPLE 2-1
READY
>10 PRINT "PAUL"
>
After noting that the system is in the command mode, the operator typed
a one-line program. The program line in this case begins with line 10,
followed by the program statement, PRINT "PAUL".
Line numbers are positive integers between zero and some very
large number. The largest allowable line number is determined by the
specifications for the computer at hand; and in the case of Radio
Shack's TRS-SO, that number happens to be 32767. But line num-
bers, no matter how large they might be, must never contain commas.
For example, a system will not know what to do with a line number
26 Ch.2 RUN, END, and Some Simple Programs in Between
READY
>RUN
PAUL
READY
>RUN
PAUL
READY
28 Ch.2 RUN, END, and Some Simple Programs in Between
>RUN
PAUL
READY
>
READY
>PRINT "PAUL"
PAUL
READY
>PRINT "PAUL"
PAUL
READY
>PRINT "PAUL"
PAUL
READY
>PRINT "PAUL"
PAUL
READY
>
EXAMPLE 2-2
READY
>10 PRINT "PAUL"
>20 PRINT "JUDY"
>
PAUL
JUDY
READY
>
EXAMPLE 2-3a
READY
>20 PRINT "JUDY"
>10 PR INT "PAUL"
>RUN
PAUL
JUDY
READY
>
In spite of the fact that the operator programmed line 20 before entering
line 10, the system straightened things out; and upon running the program,
the machine executed the lower-numbered line first.
EXAMPLE 2-3b
READY
>10 PRINT "PAUL"
>20 PRINT "JUDY"
>30 END
>
It is probably obvious that the END statement in line 30 tells the com-
puter that it has reached the end of the current program sequence. Normally,
running this program produces the same result as running without the END
statement. END is really important only when there are other programs
having larger line numbers residing elsewhere in the memory and the oper-
ator doesn't want the system to execute them.
EXAMPLE 2-3c
READY
>10 PRINT "PAUL"
>20 PRINT "JUDY"
>30 END
>40 PRINT "MUGGY"
>
Upon typing and entering the RUN command, the display shows
>RUN
PAUL
JUDY
READY
>
line 40 in the program is never executed because the system is told to
END the program at line 30.
Sec. 2-2 Patching Up Programs 31
EXAMPLE 2-4
READY
>10 CLS
>20 A$ ="1 AM DOING "
>30 B$="A GOOD JOB"
>40 PRINT A$+B$
>50END
>
This program is complete, but the operator hasn't done a RUN command
yet. When the program is run, the fIrst thing the machine will do is clear the
screen, as prescribed by line 10. Then it will print the concatenated string
variables I AM DOING and A GOOD JOB, and end.
The screen looks like this after doing the RUN command:
The program can then be recalled to the screen by typing LIST and striking
the ENTER key:
READY
>RUN
READY
>
34 Ch.2 RUN. END. and Some Simple Programs in Between
The operator entered the RUN command; but since NEW wipes out the
program memory, there is no program to run. So the system responds imme-
diately with another READY status.
But is the program really gone? Maybe the PRINT statement in line 40
simply got lost somewhere along the line. So the operator tries a LIST
command:
READY
>RUN
READY
>LIST
READY
>
No; the program is gone. Doing a LIST when the program memory is
empty merely causes the READY status to appear again.
EXAMPLE 2-5a
READY
>10 A=10
>20 B=2
>30 C=A*B
>40 PRINT C
>50 END
>
But you really wanted to sum variables A and B, instead of multiplying
them as indicated by the asterisk (*) in line 30. Line 30 has to be changed
before running the program. How can you fIx it?
Sec. 2-2 Patching Up Programs 35
One way to correct the error is by entering the NEW command and
starting all over again. It doesn't take a whole lot of imagination, however,
to realize this is a rather drastic step-especially if the program contains per-
haps a hundred steps.
A more attractive alternative is to retype line 30 by itself. In BASIC, it is
possible to "write over" any program line by simply typing the line number
and entering the revised version of the command. In this particular instance,
you can correct line 30 by doing
>30 C=A+B
>-
anywhere along the way.
To make sure the line is entered properly, you can then do a LIST com-
mand. Here is the whole procedure as it would appear on the monitor:
READY
>10 A=10
>20 B=2
>30C=A*B
>40 PRINT C
>50 END
>30 C=A+B
> LIST
10 A=10
20 B=2
30 C=A+B
40 PRINTC
50 END
>RUN
12
READY
>
In this particular case, the operator discovered the error in line 30 just
after entering program line 50. The line was rewritten after that; and doing a
LIST command confirmed that the system accepted the correction.
The operator ran the program after inspecting the listing; and by that
time, the screen was getting cluttered. So wouldn't it have been nice to
include a CLS at the beginning of the program? Is it too late to add the
CLS operation?
No, of course not. A CLS operation can be inserted before line 10 in the
program by typing
>5CLS
>
36 Ch.2 RUN, END, and Some Simple Programs in Between
A new program line can be inserted at any place in the program and at any
time the system is in the command mode. Simply pick a line number that
will make the statement fall wherever you want it. In this example the idea
is to get the CLS operation at the beginning of the program; so the line
number could actually be any integer between zero and 9 inclusively.
EXAMPLE 2-5b
>LlST
5 CLS
10 A=10
20 B=20
30 C=A+B
40 PRINT C
50 END
READY
>
In all of the examples presented thus far in this chapter, the oper-
ator initiates the execution of a program by entering the RUN
command. The assumption is that the computer will begin executing
the program with the lowest-numbered line and work its way up to
the highest-numbered line.
Indeed, that is what happens when the operator enters the RUN
command. It is not absolutely necessary to begin the execution of a
program from the very beginning, however; and a slightly modified
form of the RUN command forces execution to begin at any desired
program line.
Before seeing how this can be done, take a look at this little
math program:
EXAMPLE 2-6a
READY
>10 CLS
>20 A=10
>30 B=2
>40 C=A+B
>50 PRINT A"+"B"="C
>60 C=A*B
>70 PRINT A"X"B"="C
>80 END
>
Can you figure out what this program will do? Well, line 10 calls for clear-
ing the screen, while lines 20 and 30 set the numerical values of variables
A and B. Mter that, variables A and B are summed, and the solution is
assigned to variable C (line 40).
Line 50 is a little bit different from anything we have done so far, but the
idea shouldn't be too confusing. line 50 is basically a PRINT statement that
combines three PRINT "numerical variable" and two PRINT "expression"
statements. Reading line SO from left to right, it is saying: PRINT the
numerical value of A, literally reproduce the plus-sign character, PRINT the
numerical value of B, literally reproduce the equal sign character, and
PRINT the value of variable C.
37
38 Ch.2 RUN, END, and Some Simple Programs in Between
Perhaps this is getting a bit ahead of the story, but when line 50 is executed,
the computer will respond by printing 10 + 2 = 12.
Line 60 in the program redefmes variable C, making it equal to the product
of variables A and B. Line 70 calls for another combination of two kinds of
PRINT statements, and line 80 ends the program.
Upon entering RUN, the screen will look something like this:
10+2=12
10 X 2 = 20
READY
>
Now that's a nice little arithmetic sequence. Its appearance on the screen
is enhanced by clearing away the program in line 10.
Look over the program again, comparing it with the results appearing on
the screen after running it. Make sure you understand the little trick of
doing more than one kind of PRINT operation in a single command line.
Suppose that you now clear the screen by striking the CLEAR key, and
then enter the LIST command. The screen looks like this:
>LlST
10 CLS
20 A=10
30 S=2
40 C=A+S
50 PRINT A"+"S"="C
60 C=A*S
70 PRINT A"X"S"="C
80 END
READY
>
Then take advantage of the fact you left room for inserting new state-
ments between the existing program lines. Type and enter this:
>55 END
10+2=12
READY
>
Sec.2-3 Running from Different Places 39
Inserting END into the program at line 55 allowed the system to do only
the fIrst part of the program. The remainder of the program is just hanging
there, completely closed off from execution by the new END statement.
But it is possible to get access to the second part of the program by doing
a different sort of RUN command, RUN 6f/J.
READY
>RUN 60
0X0=0
READY
>
Oh-oh, something went wrong. Program execution began at line 60 all
right-you know that because the computer printed the X (times) symbol
from line 70 in the program. But where did those zeros come from?
Beginning program execution from line 60, you can see that the values of
variables A and B are not set. Most home computer systems automatically
set the values of numerical variables to zero every time a RUN command is
executed. So doing a RUN 6f/J started execution at line 60; but at the same
time, it reset the values of A and B back to zero.
Again, you must take advantage of the numerical spacing between the pro-
gram lines, and insert some commands that reinitialize the values of A and B
ahead of line 60. Try this:
READY
>57 A=10
>58 B=2
>
Then enter RUN 57, and you will see this added to the existing display on
the screen:
>RUN 57
10 x 2 = 20
READY
>
There it is! Everything is put back into good order. Enter the RUN com-
40 Ch.2 RUN, END, and Some Simple Programs in Between
10+2=12
READY
>
Then enter RUN 57, and the overall display looks something like this:
10+2=12
READY
>RUN 57
10X2=20
READY
>
The first part of the program, the summing part, is executed by entering
RUN. You could do the same thing by entering RUN 10. In either case,
execution begins with line 10 in this particular example.
The second part of the program, the multiplication part, is then executed
by entering RUN 57. There are no options in this case: Execution of the
second part of the program must begin with a RUN 57.
EXAMPLE 2-6b
>LlST
10 CLS
20 A=10
30 B=2
40 C=A+B
50 PRINT A"+"B"="C
55 END
57 A=10
58 B=2
60 C=A*B
70 PRINT A"X"B"="C
80 END
READY
>
This listing actually represents two separate programs: lines 10 through 55
is one of them, and lines 57 through 80 is the other. One or the other can be
executed by entering the appropriate RUN n command.
Sec. 2-4 Tighten ing Up a Program 41
>40.-------------~
EXAMPLE 2-6c
>LlST
10 CLS
20 A=10
30 B=2
50 PRINT A"+"B"="A+B
55 END
57 A=10
58 B=2
70 PRINT A"X"B"="A*B
80END
>
It turns out that the computer returns the same display as the
earlier version. This revised version, however, uses only nine program
lines and contains one less variable. That isn't a remarkable reduction
in program complexity, but the example illustrates that it is indeed
possible to do a task at least two different ways.
There is rarely one "correct" way to handle a computing task-
most jobs can be done any number of ways, ultimately yielding the
same results. There are always just a few "better" ways to do a com-
puting job, however; and that is where a programmer's knowledge,
skill, and experience payoff.
EXERCISES
(h) END
(i) ENTER
2-3 Name at least two functions perfonned by a line number.
2-4 Describe how it is possible to correct a command line or program state-
ment before terminating it by striking the ENTER key.
2-5 Describe the procedure for deleting an entire line from a program.
2-6 Describe the procedure for inserting a new program line into an existing
program.
2-7 Describe the procedure for changing an existing program line after it has
already been committed to the program memory.
2-8 Compare NEW and CLEAR, describing both their similarities and dif-
ferences.
2-9 Under what conditions is it possible to omit the END statement without
affecting the execution of a program?
2-10 Suppose that the lowest-numbered line in a program is line 100. What is
the difference between executing the program with RUN and RUN 100?
2-11 In each of the following examples, describe how the computer will
respond upon entering RUN 10:
(a) 10 CLS
20 PRINT2*8
30 END
(b) 10CLS
20 PRINT 2*8
30 CLS
40 END
(c) 10 CLS
20A=2
308=8
40 PRINT "THE ANSWER IS" A*8
50 END
(d) 10 CLS
20 A=2
308=8
40 PRINT A "TIMES" 8
50 PRINT "THE ANSWER IS" A*8
60 END
2-12 How will the computer respond to the programs in Exercise 2-11 upon
entering RUN 20? RUN 30?
INPUT and GOTO
for
Interaction and Automation
44
Sec. 3-1 Getting Yourself into the Program with INPUT 45
EXAMPLE 3-1
10 CLS
20 PRINT "WHAT IS 'A'"
30 INPUT A
40 PRINT "WHAT IS 'B'"
50 INPUT B
60 CLS
70 PRINT A"+"B"="A+B
80 END
Upon entering RUN, the computer will first clear the screen of any infor-
mation (CLS statement in line 10) and then print the expression WHAT IS
'A'. Nothing new so far. When the system encounters the INPUT A state-
ment in line 30, all operations come to a halt, and the screen looks like this:
WHAT IS 'A'
?
Note the question mark. The computer always prints a question mark
when it is halted by an INPUT statement. In effect, it is asking the question:
What value do you want assigned to variable A?
How do you, as the operator, respond to this? Answer the machine's ques-
tion. Type a numerical value and strike the ENTER key to let the machine
know the value is ready.
Upon entering a numerical value and striking the ENTER key, the com-
puter resumes executing the program-in this case, it goes on to line 40 and
prints WHAT IS 'B', followed by another question mark. It's doing another
INPUT halt, waiting for you to type in the numerical value of variable B.
After you type the numerical value of B and strike the ENTER key, oper-
ations resume again at line 60. But take a look at the screen just before you
strike the ENTER key:
WHAT IS 'A'
?2
WHAT IS 'B'
74
So strike the enter key. Operations then resume at line 60, first clearing
the screen and then printing the line specified in line 70:
2+4=6
READY
>
EXAMPLE 3-2
10 CLS
20 PRINT "FIRST PHRASE"
30 INPUT A$
40 PRINT "SECOND PHRASE"
50 INPUT B$
60 CLS
70 PRINT A$+B$
80 END
This program is essentially the same as the first one. The only differences
are that the system is expecting string expressions at lines 30 and 50, and it
concatenates them (rather than adding them) at line 70. Suppose that the
operator runs this program, responding to the question marks as follows:
FIRST PHRASE
? MUGGINS IS
SECOND PHRASE
?A SILLY CAT
Sec. 3-1 Getting Yourself into the Program with INPUT 47
Entering the second phrase, A SILLY CAT, the computer might respond
with this:
FIRST PHRASE
7MUGGINS IS - - - - - - {
SECOND PHRASE
7A SILLY CAT
FIRST PHRASE
710
SECOND PHRASE
720_
Will the system show an error condition? Will the system sum the
two numerals at line 70? It will do neither of these things. Numerals
are valid string expressions, and the system will concatenate them in
a literal fashion:
1020
READY
>
EXAMPLE 3-3
10 CLS
20 PRINT "WHAT IS 'Au,
30 INPUT A
40 PRINT "WHAT IS 'B'"
50 INPUT B
60CLS
70 PRINT A"+"B"="A+B
80 INPUT A$
90 GOTO 10
100 END
If you have studied Section 3-1 carefully, you should have no trouble
following the program down to line 80-that's where a couple of different
things begin happening.
At line 80, the system encounters an INPUT string command. It responds
by printing a question mark and waiting for the operator to strike the
ENTER key. You can input any string expression you want; but in this par-
ticular application, you will see the value of entering the null string.
Suppose that you do enter the null string in response to line 80. What
happens then? The following line, line 90, is a GOTO statement accom-
panied by a valid line number-line number 10, in this case.
Upon encountering line 90, the computer obeys the statement and jumps
up to line 10, effectively starting the program an over again. Work through
the entire program, beginning with a RUN command.
Operation begins at line 10 and the computer clears the screen. Imme-
diately after that, it prints WHAT IS 'A', followed by a question mark.
Suppose, for the sake of discussion, that the operator responds by typing 15
and striking the ENTER key.
After that, the system prints WHAT IS 'B' and a question mark. Suppose
that the operator responds with a 12. Before hitting the enter key, the
display looks something like this:
49
50 Ch.3 INPUT and GOTO for Interaction and Automation
WHAT IS 'A'
?15
WHAT IS '8'
?12
When the operator strikes the ENTER key, execution resumes at line 60
and the computer clears the screen. Now here is where things are a bit dif-
ferent from the example in Section 3-1:
15 + 12 = 27
?
Line 70 calls for printing this nice little arithmetic format; but then line
80 tells the system to expect a string expression from the keyboard. That's
why the question mark is appearing just ahead of the cursor.
In the context of this program, the question mark might be interpreted
as saying, "Let me know when you are ready to go on."
Now the operator can respond by typing anything at all and striking the
ENTER key. But notice that A$ is never acted upon in the program, so any-
thing typed as a response to the INPUT A$ statement in line 80 will never
be used. So why not keep things simple, and enter the null string. In other
words, respond to that statement by striking the ENTER key.
Program execution will then resume at line 90; and since line 90 tells the
system to jump back to line 10, the apparent response is a clearing of the
screen and the question, WHAT IS A.
The operator can now assign some different numerical value to A and go
on from there. The whole program can be executed any number of times,
using any desired combinations of A and B values. All of this takes place in
~esponse to just one initial RUN command.
In a sense, this program makes the computer work as a simple calculator
that sums any two numbers.
EXAMPLE 3-4
10 CLS
20 PRINT "PRINT YOUR NAME, PLEASE."
30 INPUT N$
40 A$;"HELLO,"
50 PRINT A$+N$
60 PRINT "STRIKE THE 'ENTER' KEY TO CONTINUE,"
70 PRINT N$
80 INPUT D$
90 PRINT
100 PRINT "HOW ARE YOU, "N$"?"
110 PRINT "lAM FINE, THANK YOU."
120 PRINT
130 PRINT "STRIKE THE 'ENTER' KEY TO DO THIS AGAIN."
140 PRINT "OR HIT THE 'BREAK' KEY IF YOU DON'T"
150 PRINT "WANT TO PLAY WITH ME ANY MORE"
160 PRINT "(YOU JERK, "N$")"
170 PRINT D$
180 PRINT "YOU'RE A SWELL PERSON, "N$
190 GOTO 20
Type SALLY and strike the ENTER key. The display then takes this
form:
Now you have the option of either playing the program all over again from
the beginning, or being a coward and ending the whole affair. If you decide
to play some more and respond by striking the ENTER key, the computer
responds by printing YOU'RE A SWELL PERSON, SALLY, followed by
PRINT YOUR NAME, PLEASE. In this particular case, the screen is not
cleared when the sequence is restarted.
Text games such as this one can be a lot of fun and they are highly in-
structive. We will leave it up to you to do the "fun" things with your
computer, however, and work here with the "instructive" phase.
First take note of the fact that this is a looping program. If things ever
get to the point where the computer encounters line 190, everything starts
over from line 20. The GOTO 2(/) statement in line 190 forces this condi-
tion to occur.
A second point of particular importance at this time is the use of INPUT
string variable statements. These statements are used in two different ways:
to set the "value" of variable N$ in line 30 and to resume program execu-
tion by entering the null string at lines 80 and 170.
The value of a third string variable, A$, is set by the program itself in
line 40.
The remaining steps all use some variation of PRINT statements.
Now for a line-by-line analysis.
When the operator does a RUN command, the system executes line 10,
clearing the screen. Immediately after that, line 20 calls for printing PRINT
YOUR NAME, PLEASE. This is a standard sort of PRINT "expression"
statement.
Line 3(/) is an INPUT string variable statement that halts program execu-
tion until the user enters some string variable and strikes the ENTER key.
Presumably, the variable in this case will be the operator's name. It can be
any sort of nonsense, however. In any event, the string is assigned to N$.
After accepting the value of N$, the value of A$ is established by the pro-
gram. Remember: Whenever a string is assigned as a program statement, it
must take the form, string variable = "expression". The expression must be
enclosed in quotation marks. Establishing the string expression for INPUT
N$ does not require quotation marks. What is the essential difference be-
tween these two situations? Answer that one for yourself.
Line 50 then uses the established values of A$ and N$ to concatenate the
expressions and print HELLO, SALLY.
54 Ch.3 INPUT and GOTO for Interaction and Automation
So line 90 creates a blank line above the text generated by line 100. Line
100 is an example of a PRINT statement followed by a string variable in-
serted between a pair of "expression" forms. This line combines two dif-
ferent kinds of PRINT statements into one. The portions to be literally
reproduced are enclosed in quotes, while the variable expression is not.
Lines 110 through 180 are all examples of various PRINT and INPUT
statements already described in this particular discussion. You might want
to give line 160 some special consideration, however, because it includes
some rather tricky formatting.
ator which figures are to be entered at any given time and spelling
out the meaning of the results in a clear fashion.
Before starting to write such a program, it is important to define
the exact nature of the task. It is necessary to assemble the necessary
mathematical equations, assign variables, and corne up with a step-
by-step calculation procedure. On a larger scale, this phase of the
work would be handled by a system analyst.
Ultimately, this program should show the total weight of the
material to be shipped, and that is a matter of working this equation:
WT= V X WB (1)
WB
WT=VX-- (la)
2000
Presumably, WB will still be entered in pounds per cubic foot and the
computer will take care of converting that figure to tons.
The volume of material required is not normally known from the
outset, so it is necessary to calculate that value as well:
V=XXYXD (2)
D
V=XXYX- (2a)
12
56 Ch.3 INPUT and GOTO for Interaction and Automation
D WB
WT=X X YX - X - - (3)
12 2000
10 CLS
20 INPUT V,WB
30 PRINT V*WB/2000
40 INPUT A$
50 GOTO 10
Before trying this test, note a new feature in line 20. The INPUT
statement in line 20 shows two different numerical variables separated
by a comma. This is a matter of combining two INPUT numerical
variable statements into one. When the computer first encounters
line 20, it will print a question mark and wait for a numerical value
for V from the keyboard. When the operator enters that value and
strikes the ENTER key, the system prints another question mark
(or two of them if you are using a TRS-80). Now the system is
waiting for a numerical value for variable WB.
In this particular example, the system expects two numerical
values at line 20; and it won't go on to line 30 until the two values
are entered from the keyboard, each followed by an ENTER.
Line 20, in effect, does something equal to this:
20 INPUT v
21 INPUT WB
Sec.3-3 Building a Text-and-Math Program 57
72000
??
The system has accepted your numerical value for V and is now wait-
ing for a value for WB. Respond by entering the numeral 1 :
?2000
??1
1
10 CLS
20 INPUT X, Y, D
30 PRINT X*Y*D/12
40 INPUT A$
50 GOTO 10
EXAMPLE 3-5a
10 CLS
20 PRINT "WHAT IS THE X DIMENSION IN FEET"
30 INPUT X
40 PRINT "WHAT IS THE Y DIMENSION IN FEET"
50 INPUT Y
60 PRINT "WHAT IS THE AVERAGE MATERIAL DEPTH IN INCHES"
70 INPUT D
80 V=X*Y*D/12
90 PRINT "WHAT IS THE BULK WEIGHT IN POUNDS PER CUBIC FOOT"
1001NPUTWB
110 CLS
120 PRINT "THE NET WEIGHT REQUIRED IS "V*WB/2000 "TONS"
130 PRINT
140 PRINT "STRIKE THE 'ENTER' KEY TO RESTART"
150 INPUT A$
160 GOTO 10
Sec.3-3 Building a Text-and-Math Program 59
Test the overall program by entering RUN and responding to the plain-
text questions with the appropriate numerical values. This is what the dis-
play looks like if you enter 100 for X, 100 for Y, 8 for D, and 85 for WB.
That takes the program through line 100. Upon striking the ENTER key
now, line 110 clears the screen and the display takes this general form:
The program is stopped at line 150, waiting for a null string from the
keyboard. (Note the line space between the two lines of text. It is created
by the PRINT nothing statement in line 130.)
When the operator strikes the ENTER key in response to the fmalline of
text, the program picks up at line 160, and its GOTO line number state-
ment carries operations all the way back to line 10.
The only way to get out of the program is by either striking the BREAK
key or turning off power to the computer.
For all intents and purposes, the programming job is done. The
program performs its intended task. But consider this matter of pro-
gramming "style."
The example shown here is just one of many different ways to
accomplish the same task. A certain programming style is reflected at
a couple of points.
For instance, the program includes two CLS statements. Neither
of them is essential to the execution of the program, but the pro-
grammer deemed them important for avoiding needless confusion
on the screen. The PRINT nothing statement in line 130 falls into
that same general category.
What is even more telling, in terms of programming style, is the
way the equations are handled. The mathematical function in line 80,
for example, could be eliminated and its terms included in the func-
tion in line 120. Such a modification would eliminate one program
60 Ch.3 INPUT and GOTO for Interaction and Automation
line and one numerical variable (V). If you choose to make this
modification, get the system back into the command mode and type
the following:
80
120 PRINT "THE NET WEIGHT REQUIRED IS"X*Y*D/12*WB/2000"TONS"
Recall that typing a line number and striking the ENTER key
effectively deletes that line from the program. So the first step
deletes line 80. The next step is to rewrite line 120 so that it in-
cludes the composite equation [Equation (3)].
After making these two modifications, the program seems to run
exactly as it did before. Only the programmer knows that anything
has changed.
Now suppose that the programmer demonstrates the scheme to
the ultimate user-the owner of the building materials company. The
individual is impressed with the basic idea but objects to the fact that
the original parameters (dimensions, cubic-foot weights, and so on)
are erased from the screen before the final result is displayed. In this
case, the CLS statement in line 110 is causing the programmer some
trouble with the customer.
So what can be done to please the customer? Of course, the pro-
grammer could delete line 110, but that leaves a mess. A satisfactory
alternative would be to reprint the original parameters, in a neat
fashion, above the final result. So go to the command mode and
insert these lines:
Let us see what the final display looks like now. Then take a look
at the entire program.
EXAMPLE 3-5b
10 CLS
20.PRINT "WHAT IS THE X DIMENSION IN FEET"
30 INPUT X
40 PRINT "WHAT IS THE Y DIMENSION IN FEET"
50 INPUT Y
60 PRINT "WHAT IS THE AVERAGE MATERIAL DEPTH IN INCHES"
70 INPUT D
90 PRINT "WHAT IS THE BULK WEIGHT IN POUNDS PER CUBIC FOOT"
1001NPUTWB
110 CLS
112 PRINT "WITH X ~"X"FEET"
114 PRINT "WITH Y ~"Y"FEET"
62 Ch.3 INPUT and GOTO for Interaction and Automation
Section 3-2 introduced the notion of striking the BREAK key to get
out of a program loop and force the system into its command mode
of operation. This section deals with BREAK in a bit more detail and
describes two closely related operations, CONT and STOP.
BREAK is used under three different kinds of conditions. First,
it can be a legitimate, routine way to get the operator out of one
kind of GOTO looping program, into the command mode, and then
into another program residing elsewhere in the program memory.
Second, BREAK can serve as a "panic button" in cases where a pro-
gram "blows up" and starts running out of control. Third, it serves
as a debugging tool for working the wrinkles out of programs under
development.
Consider the following example that shows how BREAK can be
used for exiting one program and getting to another one:
EXAMPLE 3-6
10 CLS
20 PRINT "THIS IS A MATH PROGRAM"
30 PRINT "IF YOU WANT TO ADD, FIRST STRIKE THE 'BREAK' KEY"
40 PRINT "AND THEN TYPE 'RUN 100.'"
50 PRINT "IF YOU WANT TO MULTIPLY, FIRST STRIKE THE 'BREAK' KEY"
60 PRINT" AND THEN TYPE 'RUN 200.'"
70 PRINT
80 INPUT A$
90 PRINT "YOU GOOFED UP. TRY AGAIN"
91 PRINT
92 PRINT
95 GOTO 20
100 CLS
Sec. 3-4 More about Breaking into Programs 63
This text is the result of running program lines 10 through 80. If the user
fails to handle the situation properly (a BREAK, followed by entering RUN
64 Ch.3 INPUT and GOTO for Interaction and Automation
1~~ or RUN 2f/J~), the INPUT A$ statement in line 80 picks up any other
sort of operation that is followed by striking the ENTER key. The result is
To this point, program execution is down to line 150. After entering that
second number, line 160 clears the screen. Then the user sees
40+20=60
If the user elects to do another addition problem, striking the ENTER key
carries program operation down to line 196, which, in turn, causes the
system to go to line 100. The screen is thus cleared and the addition routine
is started all over again. Doing a BREAK, however, returns the system to the
command mode, and if the user then types RUN and strikes the ENTER
key, program execution picks up at line 10, and the header is printed on the
screen once again. (Remember that entering a RUN without a line-number
suffIx automatically runs the program from the lowest-numbered line.)
Doing a BREAK, followed by entering RUN 2f/J~, causes the system to
run the multiplication routine in lines 200 through 297. The program steps
are virtually identical to those used in the addition routine-only line 270 is
different.
Although this particular program is rich in examples of programming
procedures and tricks, the main point is that the BREAK key can allow the
user to move from one kind of program to another. In this case, BREAK is
used as a normal keyboard operation.
BREAK can also be used as a panic button to break up a program that is
getting out of hand-running out of control for one reason or another. Con-
sider the following example of a "runaway" program:
10 A=0
20 PRINT A
Sec.3-4 More about Breaking into Programs 65
30 A~A+1
40 GOTO 20
variable. You can also set the values of variables from the keyboard
by doing numerical variable = numerical value or string variable =
expression. Any of these command-mode operations can be followed
by CONT to resume execution of the program after doing a BREAK.
You cannot, however, expect the program to continue if you have
changed any of the program text. In the latter case, you must restart
the program with a RUN command. .
So it is possible to BREAK an ongoing program, do just about
anything except alter the program itself, and then resume operations
from the BREAK point by entering CONT.
Most programs are executed very rapidly, however; and it is thus
difficult to halt a program at one particular point. In that case, the
programmer has access to a program-statement version of BREAK.
A STOP statement inserted into a program causes it to break at that
point, automatically returning the system to the command mode.
10 A=100
20 A=A-1
30 GOTO 20
10 A=100
20 A=A-1
25 STOP
30 GOTO 20
>RUN
BREAK IN 25
READY
>
Now the program has been executed down to line 25. To see if
the down-counting operation is actually taking place, the programmer
can enter the command, PRINT A. If all is going well, the computer
should respond by printing 99. Execution can then be resumed by
entering CONT. Study the following sequence of operations:
>RUN
BREAK IN 25
READY
>PRINT A
99
READY
>CONT
BREAK IN 25
READY
>PRINT A
98
READY
>CONT
BREAK IN 25
READY
>A=1
READY
>CONT
BREAK IN 25
READY
>PRINT A
o
READY
>
99 and then 98. After doing the next CONT and getting the BREAK
IN 25 signal, the programmer decided to set the value of A to 1-
note the A= 1 command from the keyboard. Doing a CONT let the
program resume from that point, and it responded by decrementing
the value of A to O.
It thus appears that the program is working rather well, and after
noting the system stopping at line 25 again, the operator can delete
the STOP statement by typing 25 and striking the ENTER key.
Deleting the STOP statement amounts to a change in the pro-
gram, however; and that means that it cannot be resumed by
entering CONT. Whenever the program itself is altered in any way
after BREAK or STOP, it can be restarted only by entering a RUN
command.
EXERCISES
3-1 An INPUT statement tells the computer to expect information from the
keyboard. Describe, in each of the following situations, the exact sort of
information the computer is expecting:
(a) INPUT A
(b) INPUT D$
(c) INPUT A, CA
(d) INPUT A$, X$
(e) INPUT D$, Z$, AB, C
3-2 Describe how the computer will respond to the following PRINT state-
ments:
(a) PRINT A
(b) PRINT D$
(c) PRINT
If you think RUN line number and GOTO line number are nifty
statements for jumping around in programs, wait until you have a
chance to try IF ... THEN, FOR ... TO, and NEXT statements.
EXAMPLE 4-1
11,1 CLS
21,1A=1,1
3I,1PRINTA~
41,1 INPUT B$ unconditional
51,1 A=A+1 loop
61,1CLS ~
71,1GOT031,1~
70
Sec. 4-1 Loops: Unconditional versus Conditional 71
When the user enters the RUN command, the computer rust executes the
program lines in numerical order. Line 10 clears the screen, 20 sets the
initial value of A, and line 30 prints the value on the screen. All operations
come to a halt at the INPUT statement in line 40, waiting for the user to
enter a string statement-presumably a null string because the B$ value is
never used.
Mter that, the computer resumes running the program, incrementing the
value of A at line 50, clearing the screen, and then returning to line 30 in
response to the GOTO statement in line 70.
This is an example of a loop operation, because the same sequence of
operations take place in a cyclic fashion: always running lines 30 through 70
in sequence, and then returning to line 30.
EXAMPLE 4-2
10 CLS
20A=0 ~
30 PRINT A
40 INPUT B$
50 A=A+1 conditional
60 CLS loop
70 IF A<10 THEN 30 /
80END ~
72 Ch.4 Looping with Conditional Statements
This program is identical to Example 4-1 through line 60. Line 70,
however, is a conditional statement that places a limit on how many times
the loop can be executed. As long as A is less than 10, line 70 returns opera-
tions back to line 30, creating the same effect on the screen as Example 4-1.
But when line 70 sees a value of A that is greater than 10, its condition is
no longer satisfied and program execution proceeds to the next line. The
program, in other words, counts 0 through 9 and then ends. The loop is
broken as soon as line 70 sees A greater than 10.
Table 4-1 lists the relational operators that can be used as the
"relation" part of IF ... THEN conditional statements. Table 4-2
shows a fairly complete list of possible "expression" terms in that
same kind of conditional statement.
Table 4-1 Relational Operators for IF ... THEN Statements
· .. is equal to ...
> · .. is greater than ...
< · .. is less than ...
>= · .. is greater than or equal to ...
<= · .. is less than or equal to ...
<> · .. is not equal to ...
73
74 Ch.4 Looping with Conditional Statements
Example 4-3a
10 CLS
20A=0
30 PRINT At2
40 A=A+1
50 IF A<=10 THEN 30
60 PRINT "DONE"
70 END
This program lists the squares of integers between 0 and 10, and then
prints DONE before returning to the command mode. The value of A is
initialized at zero by line 20. Line 30 calculates and prints the square of A,
and line 40 increments the value of A.
The conditional statement in line 50 is responsible for looping the squaring,
printing, and incrementing cycle as long as A is less than or equal to 10.
The moment this condition is no longer satisfied (specifically, when A is
incremented to 11), the system leaves the loop and resumes program exe-
cution at line 60.
This happens to be an example of a program using an IF . . . THEN
statement of the form:
EXAMPLE 4-3b
10CLS
20 PRINT "TERMINAL NUMBER"
30 INPUT B
40A=0
50 PRINT At2
60 A=A+1
Sec.4-2 The IF ... THEN Conditional Statement 75
70 IF A<=8 THEN 50
80 PRINT "DONE"
90 END
This program now prints the values of squared integers between 0 and any
specified value, B. The user specifies the value of variable B at the INPUT
statement in line 30. And after initializing variable A at zero, the program
begins looping through a calculate-print-increment sequence. The looping
continues until line 70 is no longer satisfied-A is incremented beyond the
value ofB.
Line 70 is an example of an IF ... THEN statement of the form
10 CLS
20 PRINT "INITIAL VALUE"
30 INPUT 8
40A=8
50 PRINT At2
60 A=A+1
70 IF A<=8+10 THEN 50
80 PRINT "DONE"
90 END
In this instance, the user specifies the initial value at the INPUT statement
in line 30. Variable A is then set to that value by the equality statement in
line 40; and after that, it is squared, printed, and incremented.
The conditional statement in line 70, in essence, asks this question: Is the
value of A presently less than 10 units greater than at the start? If the cur-
rent value of A is indeed less than its initial value plus 10, the looping action
continues. The program concludes only after A exceeds B+I0.
It's a neat way to pick up the squares of integers, although the for-
matting (form of the presentation on the screen) leaves something to
be desired. You will have a chance to improve the format in a later
lesson.
EXAMPLE 4-4
10 CLS
20A=0
30 PRINT "ZERO"
40 INPUT C$
50CLS
60 A=A+1
70 IF A=1 PRINT "ONE"
80 IF A=2 PRINT "TWO"
90 IF A=3 PRINT "THREE"
100 IF A=4 PRINT "FOUR"
110 IF A=5 PRINT "FIVE"
120 IF A<=5 THEN 40
130 GOTO 10
140 END
either comes across a condition that it can meet or it runs out of condi-
tional statements.
Since we have said that A is equal to 5 at the moment, the conditional in
line 110 is satisfied. The system responds by carrying out the consequential
statement PRINT "FIVE".
So now the conditional statement in line 110 has been satisfied, and the
computer has responded by printing FNE on the screen. What happens
. after that?
Since the conditional does not specify a line number, the computer
assumes that it is supposed to go to the next program line-line 120 in this
case.
Now line 120 is a different sort of IF ... THEN conditional statement,
but it should be no stranger. It is one of the basic conditionals already de-
scribed in Section 4-2.
Variable A is still equal to 5 by the time the system gets down to line 120.
As a result, the condition A<=5 is satisfied, so control is picked up at line
40-the operation loops at least one more time.
Line 40 calls for a null string input from the keyboard. And when the user
strikes the ENTER key to enter that particular string value, the screen is
cleared by line 50, A is incremented to 6, and the series of conditional state-
ments test that value again.
This time, however, none of the conditional statements, including the one
in line 120, is satisfied; so by default, the computer leaves the conditional
loop and goes to line 130.
Now line 130 is an unconditional GOTO statement that forces the system
up to line 10-the very beginning of the program. Shortly after that, the
word ZERO appears on the screen, and the whole scheme starts over.
So this program counts around between ZERO and FNE, and then back
to ZERO, and so on. The main point of interest, however, is the application
of a series of IF ... THEN statements. The system runs through the list
until it fmds a condition that can be satisfied or runs out of conditional
statements. In the former case, the program loops back to line 40. In the
latter case, the loop is broken and line 130 is executed by default.
Incidentally, this program is also an example of one having a nested loop-
a loop within a larger loop. The "inside" loop is being executed as long as
one of the conditionals is satisfied. In that instance, operation loops around
between lines 40 and 120. But when the system fmds that none of the con-
ditionals is satisfied, the large loop comes into play. That one runs between
lines 130 and 10.
78 Ch.4 Looping with Conditional Statements
EXAMPLE 4-5
10 CLS
20 PRINT "ENTER A NUMBER BETWEEN 1 AND 10"
30 INPUT A
40 IF A<1 THEN 80
50 IF A>10 THEN 110
60 PRINT "GOOD SHOT. YOU SEEM TO KNOW WHAT YOU'RE DOING."
70 END
80 PRINT "THAT NUMBER IS TOO SMALL."
90 PRINT "TRY AGAIN."
100 GOTO 20
110 PRINT "THAT NUMBER IS TOO LARGE."
120 GOTO 90
130 END
EXAMPLE 4-6
10 CLS
20 INPUT A,B,C
30 IF A<>3 THEN 100
40 IF B<>3 THEN 100
50 IF C<>8 THEN 100
60 PRINT "YOU MADE ITII"
70 END
100 PRINT "YOU BLEW IT, KLUTZ"
110 GOTO 100
120 END
EXAMPLE 4-7
10 CLS
20A=0
30 A=A+1
40 IF A<100 THEN 30
50 PRINT "DONE"
60 END
This program actually contains a loop that forces the value of the variable
A to increment, or count, from zero to 100. At the conclusion of that
operation, the computer is told to print DONE on the screen.
Here is a chance to appreciate the fact that a computer carries out the
program steps, one at a time; and that each step occupies some amount of
time. Depending upon the kind of computer system you are using, this
program might tak~ about 1 second to show the DONE expression. It takes
about 1 second to count from 0 to 100.
What makes the system stop looping and counting? Why, the conditional
statement in line 40. As long as the condition, A less than 100, is satisfied,
control continues looping around between lines 30 and 40. Only after"the
count reaches 100 does the system get out of the loop.
But Example 4-7 does not have a loop within a loop. So try
putting the timing loop within a larger control loop.
EXAMPLE 4-8
10 CLS
20 A=0
30 A=A+1
40 IF A<100 THEN 30
50 IF 8=1 THEN 90
608=1
70 GOTO 10
90 PRINT"* * * *"
1008=0
110 GOTO 20
120 END
Run this program and you will find a set of four asterisks flashing on and
off in the upper left-hand corner of the screen. In the context of what has
been discussed to this point, this example might seem rather hard to under-
stand-there are too many conditionals for most novice programmers to
follow.
Give it a try, anyway. After that, you will come across an important tool
for analyzing tricky, loopy programs such as this one.
Sec. 4-4 Some Nested Loops and Timing Programs 81
For one thing, you ought to be able to pick out the timing loop between
lines 30 and 40. It is basically the same loop as the one in Example 4-7.
But then line 50 is a conditional that carries operations down to line 90
whenever it is satisfied-satisfied by having variable B somehow set to 1.
And then after getting down to line 90, the computer is told to print four
asterisks on the screen, set B=I, and then go back to line 20, where the
timing loop starts all over again.
If the conditional in line 50 is not satisfied, however, variable B is set to 1
(so that's how it's done!), and line 70 sends the computer to line 10, where
the screen is cleared and the next timing loop begins.
Now take a look at Fig. 4-1. It should help clarify the whole
matter. This type of diagram is technically called a flowchart. A flow-
Display ON loop
Timing loop
5$ Y
N
9\'l
SET B = 1
7\'l
EXAMPLE 4-9
10 CLS
20 PRINT "ENTER CURRENT TIME AS HOUR, MINUTE, SECOND"
30 PRINT "FOR EXAMPLE - -10,15,48."
40 INPUT H,M,S
50 CLS
60 C:0
70 PRINT H";"M";"S
80 C:C+l
90 IF C<100 THEN 80
100 S:S+l
110 IF S<60 THEN 50
120 S:0
130 M:M+l
140 IF M<60 THEN 50
150 M:0
160 H:H+l
170 IF H<:12 THEN 50
180 H:l
Sec. 4-4 Some Nested Loops and Timing Programs 83
The looping operations can be sorted out and studied much easier from
the flowchart than from the program itself. There is, for instance, a little
conditional loop between statements 80 and 90. The purpose of this loop is
to slow down the computer's natural counting rate; and until variable C is
incremented from 0 to 101, the "seconds" display is not changed.
Incidentally, if your clock seems to be running a bit fast, you can slow it
down by increasing the value of the numerical value in the IF ... THEN
statement in line 90. If the clock seems slow, try decreasing the value of
that numerical value in line 90.
Seconds counting takes place at line 100; and as long as S is less than 60,
the conditional statement in line 110 loops the operation directly back to
line 50, where the display is updated.
84 Ch.4 Looping with Conditional Statements
The moment the IF ... THEN statement in line 110 is no longer satisfied
(because the seconds count reaches 60), line 120 resets S to 0, and line 130
increments the minutes by one unit.
As long as the minutes counter is at something less than 60, the display is
simply updated; but when M reaches a count of 60, it is reset to zero and
the hours counter is incremented by line 160.
The hours counter is allowed to increment up to, and including, 12. After
that, line 180 resets the hours counter to 1 and the display is updated.
EXAMPLE 4-10
10 CLS
20 PRINT "ENTER YOUR FIRST NAME"
30 INPUT N$
40 IF N$ = "GEORGE" END
50 PRINT "NOPE. TRY AGAIN"
Sec. 4-5 Conditional String Statements 85
60 GOTO 20
70 END
Upon entering RUN, line 10 clears the screen and line 20 prints a request
for the user's first name. That string is input at line 30.
In essence, line 40 checks to see if the name is George. If the user typed
GEORGE in response to the opening statements, the IF ... THEN con-
dition in line 40 is satisfied and the program is terminated by the END
consequences. But if the user enters anything other than GEORGE, the
conditional line line 40 is not satisfied, and program control picks up at
line 50, printing NOPE. TRY AGAIN and looping back to line 20.
Symbol(s) Meaning
· .. is identical to ...
> · .. follows alphabetically .. .
< · .. precedes alphabetically .. .
>= · .. follows (alphabetically)
or is identical to ...
<= · .. precedes (alphabetically)
or is identical to .. .
<> · .. is not identical to .. .
I'm sure you can think of some ways to use the "is identical to"
relational operation and its negated form, "is not identical to." But
it is sometimes a bit harder to come up with some practical (and
simple) applications of the other operators-the ones conditioning
according to alphabetical order. Anyway, here is a simple (if not
practical) application.
EXAMPLE 4-11
10 CLS
20 PRINT "ENTER ANY WORD"
30 INPUT A$
40 PRINT "ENTER ANOTHER WORD"
50 INPUT B$
60 IF A$<B$ THEN 120
70 IF A$>B$ THEN 140
80 IF A$=B$ PRINT "SAME"
90 PRINT "ENTER TO DO AGAIN"
100INPUTC$
110 GOTO 10
120 PRINT A$,B$
86 Ch.4 Looping with Conditional Statements
130 GOTO 90
140 PRINT B$,A$
150 GOTO 90
160 END
EXAMPLE 4-12
10 CLS
20A=0
30 PRINT A
40 A=A+1
50 IF A<=10 THEN 30
60 END
EXAMPLE 4-13
10 CLS
20 FOR A=0 TO 10
30 PRINT A
40 NEXT
50 END
These two programs do precisely the same job: They clear the screen and
print integers 0 through 10. Example 4-12 does the job using the condi-
tional procedures already outlined a number of times in this chapter.
Example 4-13, on the other hand, uses a FOR ... TO statement in line 20
and a NEXT statement in line 40.
Given the choice, most BASIC programmers would opt for the program in
Example 4-13-not because it uses Significantly fewer program lines, but
because it is so much easier to set up. For instance, there is no need for care-
fully thinking through the conditional operators-being concerned about
Sec.4-6 Simplifying Counting Loops with FOR ... TO ... STEP and NEXT 87
12q)
whether or not the program will actually print to 9, 10, or 11 (things such
as that can go wrong with a careless selection of IF ... THEN operators).
Line 20 in Example 4-13 clearly sets the counting range between 0 and 10
inclusively.
Another advantage of the program in Example 4-13 is that there is no
need to fix a line number telling the computer where to go if the condi-
tional statement is satisfied. The NEXT statement in line 40 of Example
4-13 "knows" it is supposed to carry operations back to its own FOR ...
NEXT line-no matter where that line might appear.
In both programs, it is necessary to initialize the value of the variable
being counted. Example 4-12 sets the initial value of A in line 20, whereas
it is set to 0 as part of the FOR ... TO statement in Example 4-13.
EXAMPLE 4-14
10 CLS
20 FOR T = 0 TO 100
30 NEXT
40 PRINT "BLAMIl"
50END
EXAMPLE 4-15
10 CLS
20 PRINT "TIMING INTERVAL"
301NPUTT0
40CLS
50 FOR T=0 TO T0
60 NEXT
70 PRINT "BLAMIlI"
80 END
Both of these examples use the FOR ... TO and NEXT statements for
executing a time-delay scheme. In Example 4-14, the time delay is fIxed
at the interval required for counting by 1's from 0 to 100. Example 4-15
has the special advantage of allowing the user to adjust the time-delay
interval. In that case, the user enters some numerical value for T0 at the
INPUT statement in line 30. The FOR ... TO, NEXT counting interval is
then from 0 to whatever value T0 might have.
Example 4-15 also illustrates the notion of using a numerical variable
as the terminal value in a FOR ... TO statement.
FOR ... TO and NEXT loops can be neated quite easily. In other
words, there is no real difficulty with the notion of building loops
within loops. Compare the programs in Examples 4-16 and 4-17:
90 Ch.4 Looping with Conditional Statements
EXAMPLE 4-16
10 CLS
20 FOR S=0 TO 10 ~s
30 PRINT S
40NEXTS" ~loop
50END ~
EXAMPLE 4-17
10 CLS
20 FOR S=0 TO 10 ....
30 PRINT S ----------
40 FOR C=0T0250 ----C~S
::~~~~~~lOOP loop
70 END
Both of these programs first clear the screen and then list numerals
through 10. The program in Example 4-16 does the job very rapidly, how-
°
ever, whereas the one in Example 4-17 prints the numerals at a rate of
about one per second.
Example 4-16, you see, contains only one FOR ... TO, NEXT loop,
°
which, according to line 20, causes variable S to increment from to 10.
The counting takes place at a rate determined by the execution time of lines
20,30, and 40-and that rate can be very high.
In Example 4-17, the programmer decided to insert a time delay between
the printing of each new value of S. There are two FOR ... TO, NEXT
loops in this program; and the C loop is nested within the Sloop.
Having the C loop nested within the S loop means that variable S cannot
be incremented until C goes through its entire looping cycle. C cycles to °
°
250, and then S is incremented by one. C is set to zero and allowed to cycle
from to 250 again, but S cannot increment until that cycle is completed.
Looking at the situation from a slightly different view: For every com-
plete, 250-step cycle of the C loop, the S loop is executed just one time.
The whole process is complete only after the 10-step cycle of the S loop is
fmished.
It might be helpful to bear in mind that a NEXT statement works like a
GOTO. Whenever C in Example 4-17 is somewhere between and 250, °
NEXT C means, "Go to the FOR C in line 40." So as long as the value ofC
is less than 250, the program "buzzes" between lines 40 and 50.
By the same token, NEXT S might be interpreted as saying, "If S is less
than 10, go to line 20." Here is an important point: If the NEXT S tells the
°
system to return to line 20, that means the system will print the S value in
line 30 and then restart C from at line 40.
Every time the outer loop is executed (loop S), the inner loop goes
through its entire counting cycle (loop C).
Nested FOR ... TO, NEXT loops are executed from the inner-
Sec.4-7 Nested FOR ... TO and NEXT Loops 91
most to the outermost. Each loop must complete its entire cycle
before the one just outside it can be executed one time. Figure
4-4 illustrates this principle with a diagram.
Figure 4-4a shows a set of four nested loops labeled A through D.
Loop A is the innermost one, followed by B, C, and D. Since loop
execution is from the innermost to the outermost loop, A loop will
have to be satisfied (or "cycled out") before B loop can be executed
one time. Executing the B loop resets the A loop; and the A loop
then has to be satisfied again before the B loop can undergo another
execution.
The C loop rests in its initial condition until the cycling action of
the A loop finally satisfies the B loop. Then the C loop is executed
one time. But running the C loop causes all the inner loops-A and
B-to be reset to their initial conditions; and that means the C loop
won't be executed again until the B loop is satisfied once more.
All this is going on, and the D loop has not done a thing. It won't
until the C loop is satisfied.
If you are getting the right perspective on this situation, you can
see that it is possible to tie up the computer for a long time before
the D loop is finally satisfied.
FOR 0 = d1 TO d2
1~
FORC=c1 TOc2
FOR B = b1 TO b2
FOR A = a1 TO a2
~
Other operations
Loop statements B C 0
and loop loop loop 100p
other operations
!
LJ
NEXTA
NEXT B
NEXTC
NEXTD
L - - ._ _ _
(a) (b)
Figure 4-4 Nesting FOR ... TO, NEXT loops. (a) Four nested
loops shown in a diagram fashion. (b) General programming se-
quence for four nested loops.
92 Ch.4 Looping with Conditional Statements
10 CLS
20 FOR S=0 TO 10
30 PRINT S
40 FOR C=0 TO 250
50 NEXT
60 NEXT
70 END
EXAMPLE 4-18
10 CLS
20 FOR H=l TO 12
30 FOR M=0 TO 59
Ch. 4 Exercises 93
40 FOR S=0TO 59
50 FOR C=0 TO 250
60 NEXTC
7I/JCLS
80 PRINT H":"M":"S
90 NEXT S
1001 NEXT M
110 NEXT H
120 GOTO 10
Note the hierarchy of nested loops: C is the innermost loop (the one that
cycles most often), and H is the outermost loop (the one that cycles least
often).
Note. FOR ... TO, NEXT loops can be executed much faster
than an IF . . . THEN sequence. And faster operation means
doing more operations in the same period of time.
EXERCISES
4-1 Defme the following terms:
(a) loop
(b) unconditional loop
94 Ch.4 Looping with Conditional Statements
4-3 For each of the following programs, specify the numeral appearing on the
screen when the program ends:
(a) 10 CLS (b) 10 CLS
20 A=0 20A=0
30 A=A+1 30 A=A+1
40 IF A<10 THEN 30 40 IF A<10 THEN 60
50 PRINT A 50 GOTO 30
60 END 60 PRINT A
70 END
(c) 10 CLS (d) 10 CLS
20A=0 20A=0
30 A=A+1 30A=A+1
40 IF A>10 THEN 30 40 IF A>10 THEN 60
50 PRINT A 50 GOTO 30
60 END 60 PRINT A
70END
(e) 10 CLS (f) 10 CLS
20A=0 20A=0
30 A=A+1 30 A=A+1
401F A>=10THEN 30 401F A<=10 THEN 60
50 PRINT A 50 GOTO 30
60 END 60 PRINT A
70 END
(g) 10 CLS (h) 10 CLS
20 A=0 20A=0
30 A=A+l 30 A=A+l
40 IF A<>10 THEN 30 401F A>=10 THEN 60
50 PRINT A 50 GOTO 30
Ch.4 Exercises 95
60 END 60 PRINT A
70 END
(i) 10 CLS G) 10 CLS
20 FOR A=0 TO 10 20 FOR A=0 TO 10
30 NEXT 30 NEXT
40 PRINT A 40 PRINT A-1
50 END 50 END
4-5 Under what circumstance can the THEN word be omitted from an IF ...
THEN conditional statement? Give at least two specific examples. Are
there any circumstances where the THEN word must be omitted from an
IF ... THEN conditional statement? If so, give one example.
4-6 Describe the literal meaning of the following string statements:
(a) IFA$=B$THEN .. .
(b) IF A$>B$ THEN .. .
(c) IF A$<B$ THEN .. .
(d) IF A$<=B$ THEN .. .
(e) IF A$>=B$ THEN .. .
(£) IF A$<>B$ THEN .. .
4-8 Describe the effect this program will have on the screen:
10 CLS
20 B=0
30 FOR T=0 TO 200
40 NEXT
50 IF B=1 THEN 100
60CLS
96 Ch.4 Looping with Conditional Statements
70 PRINT "TICK"
80 B=1
90 GOTO 30
100 CLS
110 PRINT
120 PRINT "TOCK"
130 GOTO 20
You have covered a lot of new material in the first four chapters of
this book. You have learned something about getting a computer
wound up, programmed, and running in BASIC. There is a lot more
material to cover before you can begin claiming to be something of
an expert in the BASIC language; but this is a good place to take
stock of everything that has gone before, look at just one new pro-
gram statement, learn some techniques for making neater looking
displays on the CRT, and consider some ways to make the pro-
grammingjob a bit easier.
After that, it will be time to get back to the heavier stuff.
has room for 64 characters on each line and for just 16 lines down
the screen. That provides a total of 1024 characters that can be
visible at any given moment.
To check the line capacity of your video screen, clear the screen
and get into the command mode by typing and entering the com-
mand NEW. That should leave a READY status appearing in the
upper left-hand corner of the screen.
Now begin striking the "greater than" key (» until the line is
filled and overflowing to the next line. The number of greater-than
symbols on the full line should be 64. Continue striking the> key
until you are convinced that each line can hold just 64 characters.
Choose any other keyboard character and you will find the same
result.
Now clear the screen by either striking the CLEAR key or enter-
ing NEW. Then begin striking the ENTER key. Each time you hit the
ENTER key in the command mode, the prompt symbol should
appear at the beginning of each new line. You will find that you can-
not get more than 16 of these prompt symbols lined up vertically
along the left-hand edge of the screen. The system can display only
16 lines of characters at one time.
Of course, the system will accept more than 16 lines; but after
the sixteenth is displayed, attempting to enter yet another line causes
the entire display to scroll upward. The new line is entered at the
bottom of the screen, and the top line is effectively lost from view as
it "pops" off the top.
All printing on the screen is done within this 16 X 64 graphic
format; formatting is the term applied to the process of setting up
displays within the l6-line, 64-characters-per-line format on the
screen.
Some special systems, especially those designed for high-quality
video graphics, can handle larger amounts of information on the
screen at one time. The 16 X 64 format is standard for conventional
computer systems.
Through the first four chapters of this book, the computer sys-
tem itself has handled most of the formatting. It automatically starts
a new line when one is overflowed by anything that causes more than
64 characters and spaces to appear in sequence. And the system auto-
matically scrolls the display whenever the line count overflows.
EXAMPLE 5-1
1.0 CLS
20 PRINT "$"
30 GOTO 20
Basically, this example is one of those endless looping programs that can
be terminated only by striking the BREAK key. The point of the demon-
stration, however, is to show that the computer does a carriage-return each
and every time it executes line 20. What appears on the screen is a single
string of dollar signs along the left-hand edge. (Note that there are just 16
of them on the screen at once. Why is that?)
EXAMPLE 5-2
10 CLS
20 PRINT "$";
30 GOT020
The only difference between this program and the one in Example 5-1 is
that line 20 in this example has a semicolon at the end of it. That semi-
colon instructs the computer to suppress its natural desire to do a carriage
return after every PRINT statement.
Run the program and you will fmd the display looking quite different
from that generated by Example 5-1. The screen is literally filled with
dollar signs-64 in a row and 16 rows of them. That one little bit ofpunc-
tuation in line 20 makes all the difference in the world. The system still
does an automatic carriage-return operation when a line is filled, however.
If you are now convinced that it is possible for you, as the pro-
grammer, to suppress the system's automatic carriage-return feature
after a PRINT operation, consider this little wrinkle:
EXAMPLE 5-3
10CLS
20 PRINT "NAME"
30 INPUT A$
40 PRINT
50 PRINT A$
60 END
EXAMPLE 5-4
10 CLS
20 PRINT "NAME";
30 INPUT A$
40 PRINT
50PRINT A$
60 END
Again, the only difference between these two programs is the presence of
a semicolon at the end of the PRINT statement in line 20 of Example 5-4.
Upon running the program in Example 5-3, this blurb appears imme-
diately on the screen:
NAME
?
Sec. 5-2 Formatting with Semicolons 101
The question mark and cursor appear as a result of the INPUT A$ statement
in line 20. Now you can enter a name such as HERMAN, and complete the
program execution:
NAME
?HERMAN
HERMAN
READY
>
NAME?
Note that using the semicolon after the PRINT statement in line 20 sup-
pressed the normal carriage return, causing the question mark and cursor to
appear on the same line as the printed word NAME.
Typing and entering HERMAN in response to this INPUT request, the
overall display looks like this:
NAME? HERMAN
HERMAN
READY
>
In Example 5-4, the printed request and INPUT-generated question mark
appear on the same line-and so does the operator's response. Although the
difference between this program and the one in Example 5-3 might seem
trivial at this point, this demonstration clearly shows the effect of following
a PRINT statement with a semicolon.
EXAMPLE 5-5
10 CLS
20 FOR N=0 TO 100
30 PRINT N;
40 NEXT
50END
In this case numerals 0 through 100 will be printed on the screen in hori-
zontal rows. Zero through 17 will appear on the ftrst line, 18 through 30 on
the next, and so on. Without the semicolon in line 30, the numerals would
appear vertically, one on a line.
You can confirm that the # symbol is in the space for imaginary
rectangle number 10 by using the PRINT command about it as a
reference. The cursor on that command line occupies position 0, the
P in PRINT occupies position 1, the R is in position 2, and so on.
Count it out, and you will find that the # on the second line is
directly below the number-l 0 character-( -on the line above.
Figure 5-1 shows the imaginary grid of TAB numbers on the
screen. There are 64 TAB positions, labeled 0 through 63. Having
convenient access to such a grid can be invaluable when formatting
lines of text on the screen.
As described thus far, the TAB statement takes the following
form:
where tab number is any number between 0 and 63, inclusively. The
larger the tab number, the farther to the right the "expression" is
printed on the line.
Actually, the TAB statement is simply a modified PRINT state-
ment; and anything you can do with PRINT you can do with PRINT
TAB(tab number). For example:
EXAMPLE 5-6
10 CLS
20 PRINT "A";
30 PRINT TAB(12) "A SQUARED";
40 PRINT TAB(28) "SQUARE ROOT";
50 PRINT TAB(47) "LOG A"
60 PRINT TAB(30) "OF A"
70 FOR N=0 TO 63
80PRINT"-";
90 NEXT
:;;
.Q
•. 5
Jc
~
M N ~
e-
li
1
2
3
4
5
6
7
8
9
111
j
11
12
13
14
15
16
17
18
19
211
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
4q,
41
42
43
44
45
46
47
48
49
51)
51
52
53
54
55
56
57
58
59
611
61
62
63
104
Sec.5-3 Formatting with the PRINT TAB (. . .) Statement 105
1 1 1 ii
2 4 1.41421 .692147
3 9 1.732ii5 1.1'19861
4 16 2 1.38629
5 25 2.236ii7 1.60944
6 36 2.44949 1.79176
7 49 2.64575 1.94591
8 64 2.82843 2.1'17944
9 81 3 2.19722
1ii l¢ii 3.16228 2.3¢259
READY
>-
All of the PRINT TAB statements in Section 5-3 were fixed nu-
merical values-an integer somewhere between 0 and 63. But it is
Sec.5-4 Getting Fancy with PR INT TAB (math) 107
EXAMPLE 5-7
10 CLS
20 FOR N=0 TO 14
30 PRINT TAB(N) "#"
40 NEXT
50 GOTO 50
As the value of N increments from ° toward 14, the tab position of the
# figure increments one space farther to the right with each line. Each #
appears on a different line because there is no semicolon at the end of line
30 to suppress the carriage returns. What you see on the screen is some-
thing like the figure in Fig. 5-3a.
Incidentally, line 50 might seem to be a rather peculiar operation. All it
does is tell the line to go to itself. So when the computer encounters line 50,
it just "buzzes" there until the operator strikes the BREAK key to return to
the command mode of operation.
Having a line return to itself is a popular trick when drawing pictures on
the screen. Without it, the computer would return the ready status charac-
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
ters, mess up the picture, and maybe even shift everything upward by one
line. So you get the computer busy with some nonsense task so it won't
mess up the image.
Now if you want to get a shallower slope than the program generates,
simply modify line 30 to read
That statement sets the tab four times farther to the right with each line,
creating an image much like the one in Fig. 5-3b.
Of course, you can enclose any character or combination of characters
within the quotes in line 30. Maybe # figures don't interest you much.
So how about this?
Or maybe you think you are ready to try your hand at some
computer animation-making that line wiggle around a little bit.
Then try this:
EXAMPLE 5-8
10 CLS
20 FOR A=0 TO 4 STEP .5
30 FOR N=0 TO 14
40 PRINT TAB(N*A) "ZZZIP"
50 NEXT N
60 CLS
70 NEXT A
80 GOTO 20
With this program, the angle itself changes. The ZZZIPs are first printed
straight downward, then at a slight angle, and then at greater angles until A
is incremented to 4. Then the whole cycle starts all over again. One gets the
impression of a funny sort of searchlight in action. It (whatever "it" is)
fires out streams of ZZZIP's (whatever they are) in a sweeping pattern.
Since the program is built around an unconditional GOTO statement, it
can be stopped only by hitting the BREAK key.
PRINT TAB(math) can be used for graphing just about any sort
of mathematical function; and programmers who are mathematically
inclined can set up all sorts of basic math graphs.
Consider, for instance, the basic exponential function A = x 2 .
Sec.5-4 Getting Fancy with PRINT TAB (math) 109
EXAMPLE 5-93
10 CLS
20 FOR X=0 TO 7
30PRINTTAB(Xt2) "*"
40 NEXT
EXAMPLE 5-9b
10 CLS
20 X=0
30 A=Xt2
40 IF A>63 END
50 PRINT TAB(A) "*"
60 X=X+1
70 GOTO 30
*
*
*
*
*
* * *
READY
>-
EXAMPLE 5-9c
10 CLS
2(1) PRINT "WHAT INTERVAL";
3(1) INPUT I
40CLS
50 x=0
60 NL=0
7(1) A=Xt2
8(1) IF A>63 GOTO 140
9(1) PRINT TABlA)" *"
1(1)0 NL=NL+1
110 IF NL>14 GOTO 140
120 X=X+I
13(1) GOTO 7(1)
140 GOTO 140
Sec.5-4 Getting Fancy with PRINT TAB (math) 111
All that remains for graphing this function are some values for X
and a few housekeeping chores.
EXAMPLE 5-10
10 CLS
20 FOR X=0 TO 6.28 STEP .4
30 PR INT TA8(30*SIN (XI+31 I" *"
40 NEXT
50 GOTO 50
EXAMPLE 5-11
10 CLS
20 FOR X=1 TO 10
30 PRINT x, Xt2,SQR(Xl. LOG(X)
40 NEXT
50 END
This program prints the value of X, the square of X, the square root of
X, and the log of X in four columns on the screen. Attempting to do the
114 Ch. 5 Some Formatting Hints and Programming Short Cuts
same job with TAB statements would call for three additional program lines;
and, more important, a lot of planning concerning the values of the tab
numbers.
EXAMPLE 5-12
10 CLS
20 PRINT "A","A saUARED","saUARE ROOT","LOG A"
30 PRINT ,,"OF A"
70 FOR N=0 TO 63
80 PRINT "-";
90 NEXT
100 FOR A=1 TO 10
110 PRINT A, At2, saR(A) ,LOG(A)
150 NEXT
160 END
So far in this chapter you have seen how semicolons and commas
affect the formatting of PRINT statements. It so happens that the
Sec.5-6 Simplifying INPUT Routines 115
100 INPUT A
110 INPUT B
120 INPUT C
100 INPUT A, B, C
EXAMPLE 5-13
10 CLS
20 PRINT "TYPE THE NAME OF THE MONTH, DAY, YEAR"
30 PRINT TAB(20l "EXAMPLE: MAY, 10,1979"
40 INPUT A$.A,B
50 CLS
60 PRINT "TODAY IS "A$;A ","B
70 END
JULY 11,1980
READY
>
EXAMPLE 5-14
10 CLS
20 INPUT "WHAT DAY IS THIS";D$
30 CLS
40 PRINT "TODAY IS"D$
Maybe the operator responds by typing TUESDAY and striking the ENTER
key. Line 30 then clears the screen, and line 40 prints the fmal result:
TODAY IS TUESDAY
READY
>
10 CLS
20 PRINT "WHAT DAY IS THIS";
30 INPUT D$
40 CLS
50 PRINT "TODAY IS"D$
The original program is shorter and it occupies less memory space. Pro-
gram execution is also a lot faster, but that's a trivial point when working
with programs that are as short as these.
Now, let's put together all the ideas introduced in this chapter.
The problem is one of calculating the value of the equation Ax2
+ Bx + C = D, where the operator inputs the values of A, B, C, and x
from the keyboard.
118 Ch.5 Some Formatting Hints and Programming Short Cuts
EXAMPLE 5-15
10 CLS
20 INPUT "ENTER VALUES A,B,C,X";A,B,C,X
30 PRINT
40 PRINT "D="A*Xt2+B*X+C
D=3
READY
>
What would the program look like if it were not possible to place printed
expressions within an INPUT statement and fit more than one variable into
the statement? Well, in part, it would look something like this:
10 CLS
20 PRINT "ENTER THE 'A' VALUE"
30 INPUT A
40 PRINT "ENTER THE 'B' VALUE"
50 INPUT B
10 PRINT 10 PRINT:PRINT:PRINT:PRINT
20 PRINT
30 PRINT
or
40 PRINT
Sec.5-8 Tightening Up Programs-In Retrospect 119
Take your pick. The computer does the same thing in either case.
Using multiple-statement lines, Example 5-15 could be rewritten
as:
10 CLS:A=0:PRINT "ZERO"
40 INPUT C$
50 CLS:A=A+1
70 IF A=l PRINT "ONE";IF A=2 PRINT "TWO"
90 IF A=3 PRINT "THREE":IF A=4 PRINT "FOUR"
110 IF A=5 PRINT "FIVE"
120 IF A<=5 THEN 40: GOTO 10
14(1 END
120 Ch. 5 Some Formatting Hints and Programming Short Cuts
The only thing to watch out for in this example is making certain
that the THEN and GOTO statements in line 120 carry the program
back to a valid point. For example, you would be in trouble if
INPUT C$ from line 40 were tacked onto the end of line la-there
would be no way to get to that statement without executing all the
statements preceding it; and you don't want to do that in this case.
Example 5-5 could look more like this:
10 CLS
20 FOR N=0 TO 100:PRINT N;:NEXT
50 END
10 CLS
20 INPUT"WHAT INTERVAL";I
40 CLS:X=0:NL=0:A=Xt2
80 IF A>63 THEN 140
90 PRINT TAB(A)"*":NL=NL+l
110 IF NL>14 THEN 140
120 X=X+I: GOTO 70
140 GOTO 140
EXERCISES
#########
# - #
&# #&
# #
# -0- #
(( ( ( ) ) ) )
( ( ) )
Sorting with ON ... GOTO
and
Scrambling with RND en)
EXAMPLE 6-1
10 CLS
20 INPUT "ENTER A NUMBER, 1 THRU 5";N
30 ON N GOTO 50,60,70,80,90
40 PRINT "YOU GOOFED IT. TRY AGAIN": GOTO 20
50 PRINT "*":GOTO 20
60 PRINT "**":GOTO 20
122
Sec. 6-1 The ON n GOTO line numbers Statement 123
70 PRINT "***":GOTO 20
80 PRINT "****":GOTO 20
90 PR INT "*****"GOTO 20
100 END
There is nothing new in the first two lines. Line 10 merely clears the
screen, and line 20 instructs the user and allows a numerical value for N to
be entered from the keyboard.
Line 30 is the case in point here. This single line says this:
IF N=1 THEN 50
IF N=2 THEN 60
IF N=3 THEN 70
IF N=4 THEN 80
IF N=5 THEN 90
The line actually says more than that, but the example will suffice for the
time being. The point is that an ON n GOTO line numbers statement per-
mits you to select one of any number of GOTO branching statements,
depending upon the integer value of n.
The computer then does a GOTO 90, which calls for printing five
asterisks and returning to line 20 again.
It is really a rather simple sort of routine once you catch on to it.
But as promised earlier in this discussion, there is more to the state-
ment than these examples might lead you to believe there is.
For one thing, you should be able to see that the ON n GOTO
line numbers statement involves some internal counting operation-
counting designated line numbers out to the nth one. That fact
implies that n ought to be an integer, a whole number. It doesn't
make a whole lot of sense to try counting out to the 2.5th line
number.
The inventors of this statement were apparently sympathetic to
this idea and built in an automatic roundoff feature. So if the value
of n is specified as something other than an integer, the system auto-
matically figures the least-integer value and adjusts n accordingly.
So if the operator using the program in Example 6-1 happens to
enter 2.16678 as a value for N, the system automatically does a
greatest-integer operation on the number, setting n to 2. So entering
a numeral such as 2.16678 (or in fact any numeral between 2 and
2.99999) will result in an n value of 2, and the system prints two
asterisks (by line 60).
The program in Example 6-1, then, can actually handle values of
N between 1 and 5.99999 without any difficulty at all.
The meaning ofline 30 in Example 6-1 can thus be represented by
instructed to print YOU GOOFED IT. TRY AGAIN and then return
to line 20 to start over.
Bearing in mind that the execution of an ON n GO TO line num-
bers statement involves an integer counting operation, one might
wonder what the system will do with a n value of zero or between
zero and 0.99999. That is a good question, because the response
might well vary from one kind of personal computer BASIC to
another. In the case of Radio Shack's TRS-80, n values from 0
through 0.99999 are treated as 1 through 1.99999. A zero, in other
words, is treated as a I; but the I is still treated as a I, and that can
cause some confusion. The moral of the story is to check a current
version of your own manual to see how the system treats n values be-
tween 0 and 0.99999 in these ON n GOTO line numbers statements.
While on the subject of n values between 0 and 1, it must be
said that BASIC cannot handle n values less than zero-that is, nega-
tive values. Counting out to the (-2)nd line does not make any sense
to people or to computers.
Don't be discouraged about the fact that your system will have
trouble working with n values that are less than 1 or negative. There
is a way around it.
First consider a good way to resolve the ambiguity surrounding a
need for dealing with an n value of 0 through 0.99999:
EXAMPLE 6-2
10 CLS
20 INPUT "ENTER A NUMBER BETWEEN 0 AND 4";N
30 ON N+1 GOTO 50,60,70,80,90
40 PRINT "YOU BLEW IT. TRY AGAIN":GOTO 20
50 PRINT "ZERO": GOTO 20
60 PRINT "ONE": GOTO 20
70 PRINT "TWO": GOTO 20
80 PRINT "THREE ":GOTO 20
90 PR INT "FOUR" :GOTO 20
100 END
This program can deal with an INPUT value of zero because 1 is added to
N before the count-out operation in line 30 begins. Entering a 0 at line
20 actually makes the system look for the 0+ I , or fust GOTO line number.
Entering a I makes it look for the 1+ 1, or second line number; and so on.
25 IF N<0 THEN 40
EXAMPLE 6-3
10 CLS
20 FOR N;0 TO 55
30 PRINT RND(101.
40 NEXT
50 END
The program in this case fills the screen with four columns of random num-
bers between 1 and 10. If you want to extend the range of random values to
100, simply change line 30 to read PRINT RND(I00).
127
128 Ch.6 Sorting with ON ... GOTO and Scrambling with RND (n)
Note. Check the BASIC manual for your own system to see how
it handles RND(n) when n is equal to 1 or less.
RANDOM does not have to be used at all for very simple pro-
grams. Where RND(n) is used a large number of times within a more
Sec.6-2 Scrambled Numbers from RND (n) 129
EXAMPLE 6-4
10 CLS
20 PRINT TAB(RND(63))"."
30 GOTO 20
10 CLS
15 I NPUT "SET SPEED (1 TO 100)";S
20 PRINT TAB(RND(63))"."
25 FOR T=0 TO 100-S: NEXT
30 GOTO 20
130 Ch.6 Sorting with ON ... GOTO and Scrambling with RND (r.)
EXAMPLE 6-5
10 CLS
20 INPUT R$
30 D=RND(6)
40 CLS
50 PRINT D
60 GOTO 20
(~_R--.-UN_~)
FETCH A
RANDOM NO.
(1-6)
A good many dice games call for using two dice at the same time,
as the following example illustrates.
132 Ch.6 Sorting with ON ... GOTO and Scrambling with RND en)
EXAMPLE 6-6
10 CLS
20 INPUT R$
30 RANDOM
40 D1=RND(6):D2=RND(6)
50CLS
60 PRINT "DICE-2"
70 FOR L=0TO 5:PRINT:NEXT
80 PRINT TA8(20)D1 ;:PRINT TAB (40)D2
90 GOTO 20
100 END
With this program, the user effectively rolls two dice each time he strikes
the ENTER key (entering the null string in response to the INPUT state-
ment in line 20). Line 40 is responsible for generating random numbers be-
tween 1 and 6 for the two dice, designated D1 and D2.
After the two values are selected in line 40, the CLS statement in line 50
clears the screen and then line 60 causes the message DICE-2 to appear in
the upper left-hand corner of the screen.
Line 70 carries the system down the screen six additional lines, and line
80 causes the values of the two dice to appear side by side, but separated by
20 tab spaces.
A question mark and cursor near the lower left-hand side of the screen
reminds the user to strike the ENTER key to roll the dice again.
The RANDOM statement in line 30 isn't absolutely necessary for this
simple RND(n) program, but it is included here for purposes of illustration.
In this case, the random-number generator is "reseeded" each time the user
rolls the dice.
EXAMPLE 6-7
10 CLS
20 INPUT "NUMBER OF DICE USED (1 TO 5)";N
Sec. 6-3 Developing a Dice Game Program 133
30 IF N>5 THEN 70
40 01 =RND(S) :D2=RND(S) :D3=RND(S) :D4=RND(S) :D5=RND(S)
50 FOR L=0 TO 5:PRINT:NEXT
S0 ON S-N GOTO 80, 90,100,110,120
70 PRINT "BAD NUMBER OF DICE. DO AGAIN.":GOTO 20
80 PRINT TAB(10)D5;
90 PRINT TAB(20)D4;
100 PRINT TAB(30)D3;
110 PRINT TAB(40)D2;
120 PRINT TAB(50)D1;
131.1 FOR L=I.I TO 5:PRINT:NEXT
140 INPUT "ENTER TO ROLL AGAIN";R$
151.1 RANDOM:CLS:GOTO 40
Lines 10,20, and 30 merely get things started, allowing the user to select
the number of dice to be used in the game. Line 30 takes care of the case
where the user might enter a number larger than 5, which would, of course
blow up the whole program. If the user does respond to the INPUT state-
ment in line 20 with an N value larger than 5, line 30 picks up the fact and
sends control down to line 70.
Whenever line 70 is executed, the user sees the message BAD NUMBER
OF DICE. DO AGAIN; and control is automatically returned to line 20,
where things start all over again.
This goof-proofmg feature makes it impossible to start the game until the
user enters a value for N is 5 or less. What about values that are less than I?
Well, that situation will be covered later in a different fashion.
After the user enters the proper number of dice, the five RND(6) state-
ments in line 40 generates a random number, between 1 and 6 inclusively,
for each of the five dice. All five pick up a random value on this line, no
matter how many are actually used in the game. The die values, you might
note, are designated 01,02,03,04, and 05.
After picking up a random value for each of the dice, line 50 causes the
system to skip down six lines on the screen before printing anything. Then
comes the ON ... GOTO statement in line 60.
Notice the use of ON 6-N GOTO line numbers. Why is the math expres-
sion 6-N used here instead of the usual sort of N expression? You'll see why
in a moment.
What is more important now is to see how the program is protected from
entering "number of dice" less than 1. Recall from Chapter 5 that an
ON n GOTO line numbers statement defaults and goes to the next program
line if the least-integer value of n is greater than the number of designated
line numbers. In this particular program, the system Will default to line
70 if 6-N is greater than 5 (there are five line numbers specified in the
statement).
Now that means 6-N must not be greater than 5, and that is the same as
saying N must not be less than 1. So if the user happens to respond to the
INPUT statement in line 20 with a number less than 1, the program will
134 Ch.6 Sorting with ON ... GOTO and Scrambling with RND (n)
begin normal execution until it defaults at line 60. At that time, control
goes to line 70, which prints out the error message and causes the whole
program to start again from line 20. The user then has a chance to correct
the mistake.
The program is thus fully protected against invalid entries as far as the
number of dice to be used is concerned. Line 30 takes care of the instances
where the user might try to specify too many dice, and the default feature
of the ON ... GO TO statement takes care of cases where the user might
try to enter a number of dice that is too small. The conditional statement in
line 30 represents a very direct approach to the matter, while the trick in
lines 60 and 70 represent a somewhat more subtle approach. But using the
ON ... GOTO feature to cover the case where N is less than 1 saves at
least one program line.
Certainly, one could insert a line 35 that might read IF N< 1 GOTO 70;
or better yet, amend line 30 to include a logical OR clause of the kind
described later in this book. But it is always better to take advantage of
existing features, doubling up functions wherever possible-making the
sequence of operations in lines 60 and 70 cover the case where N is less than
1, for example.
A programmer doesn't do this sort of thing just to show off. It is more a
matter of using some of the less obvious features of existing program state-
ments to keep the wits sharpened and pick up additional experience. At
some time and in some way, such sharp-witted experience will payoff,
giving the programmer a chance to do some things far more effiCiently and
effectively than most others in the business can. Some wise philosopher of
practical life once stated that 10 percent additional effort reaps 100 percent
superior results. That's the case in point here. And if you can buy the idea,
you can start putting it to work right now.
Lines 80 through 120 are responsible for printing the dice values along a
single line near the middle of the screen. Looking at the various TAB values,
you can see that the value of D5 die is always printed near the left-hand side
of the screen, the value of D4 is printed a bit farther to the right (10 addi-
tional tab values, to be precise), and the value of dice D3 is printed near the
middle of the screen.
In short, the values for D5 through DI are printed from left to right across
the screen. D1 is printed near the right-hand edge and D5 near the left-hand
edge.
To see why the died values are printed in this reverse order (and why line
60 uses a 6-N expression), consider a particular example. Suppose the user
decides to use two dice. That being the case, line 60 selects the GOTO line
number on the basis of 6 minus 2, or 4. The fourth GOTO line in line 60 is
110. So calling for two dice means the dice-value printing operation begins
at line 110.
Now line 110 calls for printing the value of D2 at TAB 40, followed by
line 120, which calls for printing the value of Dl at TAB 50. After that, the
system runs out of printing statements and goes on to other things.
Suppose, however, the user specifies five dice. That being the case, line 60
Sec. 6-3 Developing a Dice Game Program 135
does its GOTO operation on the basis of 6 minus 5, or the fIrst designated
GOTO line, line 80 in this case. Going to line 80 means doing all fIve print-
ing and tabbing operations specified in lines 80 tI:uough 120. The values for
all five dice thus appear lined up across the middle of the screen.
Again, there are more straightforward ways to specify the number of dice
values to be printed-ways more obvious than using a 6-N expression in
line 60 and printing the dice values in reverse order. Given the statements
described through the fIrst six chapters of this book, however, there is good
reason to doubt that any alternative method could produce a simpler pro-
gram than the one in this example.
Lines 130 through 150 are responsible for properly recycling the pro-
gram for another roll of the dice. Line 130 injects another set of six blank
lines, and line 140 prints the message ENTER TO ROLL AGAIN and give
the user a chance to "roll the dice" by striking the ENTER key-entering
the null string value for R$.
Upon seeing that the user has hit the ENTER key, the program reseeds the
random-number generator, clears the screen, and returns program control
back to line 40. Line 40 sets new random values for all the dice, and the
whole thing is under way again.
Note that program control does not return back to the very beginning.
There is no need to specify the number of dice each time they are rolled.
The only way to select a different number of dice is by getting out of the
program with a BREAK and entering RUN to start from the beginning.
EXAMPLE 6-8
10 CLS
20 INPUT "NUMBER OF DICE TO BE USED (1 TO 5)";N
301FN5THEN70
40 D1 =RND(6) :D2=RND(S) :D3=RND(6) :D4=RND(6) :D5=RND(6)
50 FOR L=0 TO 5:PRINT:NEXT
55 T=0
60 ON N-6 GOTO 80,90,100,110,120
70 PRINT "BAD NUMBER OF DICE. DO AGAIN":GOTO 20
80 PRINT TAB(10)D5;: T=T+D5
90 PRINT TAB(20)D4;: T=T+D4
100 PRINT TAB(30)D3;: T=T+D3
110 PRINT TAB(40)D2;: T=T+D2
120 PRINT TAB(50)D1;: T=T+D1
130 FOR L=0 TO 5: PRINT:NEXT:PRINl rAB(40)"TOTAL="T
140 INPUT "ENTER TO ROLL AGAIN" ;R$
150 RANDOM:CLS:PRINT N"-DIE GAME":GOTO 40
136 Ch.6 Sorting with ON ... GOTO and Scrambling with RND (n)
EXAMPLE 6-9
50 CLS:A=RND(5):B=RND(5):C=RND(5)
60 ON A GOTO 100, 105, 110, 115, 120
70 ON B GOTO 125, 130, 135, 140, 145
80 ON C GOTO 150,155,160,165,170
90 PRINT "THE "A$" "B$" THE "C$
95 PRINT: PRINT: GOTO 35
100 A$="DOG": GOTO 70
105 A$="CAT": GOTO 70
110 A$="MOUSE": GOTO 70
115 A$="ELEPHANT": GOTO 70
120 A$="TURTLE": GOTO 70
125 B$="ATE": GOTO 80
130 B$="JUMPED OVER": GOTO 80
135 B$="CHASED": GOTO 80
140 B$="SLIPPED AND SQUASHED": GOTO 80
145 B$="SAT ON": GOTO 80
150 C$="CH ICKEN": GOTO 90
155 C$="GARDEN HOSE": GOTO 90
160 C$="LAKE AND ALL ITS CONTENTS": GOTO 90
165 C$="HOUSE": GOTO 90
170 C$="ELEPHANT": GOTO 90
them. The values of A, B, and C are selected by the computer itself; and as
everyone knows, computers never make mistakes.
Of course, you can assign any values you desire to the A$, B$, and C$
string variables in lines 100 through 170. In this particular application A$
variables represent the subject of a sentence, B$ is the verb, and C$ is the
direct object.
EXERCISES
6-10 Write a two-dice program that will clearly indicate a WIN!! whenever the
sum of the dice values is 7 or 11.
6-11 Referring to Example 6-9, suppose line 50 yields A=I, B=4, and C=3.
(a) How will the system respond to the ON A GOTO ... statement in
line 60?
(b) How will the system respond upon going to line 70?
(c) How will the system respond upon going to line 80?
(d) What message appears on the screen after executing line 90?
Integrating Smaller Programs
with
GOSUl3 and RETURN
The programming examples cited so far in this book have been in-
structive and, hopefully, somewhat entertaining as well. These
haven't been your run-of-the-mill programs, however. In the con-
text of modern BASIC programming, they have been exceedingly
simple programs.
To be sure, the programs appearing in the first few chapters have
done their intended task, but the fact of the matter is that little was
expected of them in the first place.
Maybe you are now thinking that a person has to be some sort of
genius to assemble more useful and complex BASIC programs. Un-
fortunately for the ego, that isn't the case. BASIC includes a scheme
which, among other things, greatly simplifies the task of building
complex programs.
With this particular scheme at hand, a programmer can write,
enter, test, and debug bite-sized portions of a program. And after
getting all those little building blocks working, the programmer can
write just one more program that ties them together into an inte-
grated unit.
These "bite-sized . portions" or "building blocks" are actually
140
Sec. 7-1 A First Look at Subroutines 141
Suppose you devise a TAB graphics program that causes the figure of
an arrow to travel from left to right across the top of the screen. The
program might look something like this:
EXAMPLE 7-1a
Every time you enter RUN 100, the arrow moves across the screen, start-
in the upper left-hand corner and moving to the upper right-hand corner.
Everything comes to a stop after that, because the END statement in line
140 returns the system to its command mode.
This is just another one of those instructive, but hardly sophisticated,
demonstration programs. Note, however, that the line numbers begin at
100. There is a good reason for using larger-than-norma1line numbers-the
program is going to be a subroutine within a larger program.
At any rate, the program in Example 7-1a works so well that you
decide to write another program to make the arrow turn around and
move from left to right. That program might look this this:
EXAMPLE 7-1b
200 FOR H=58 TO 4 STEP -1
210 CLS
142 Ch.7 Integrating Smaller Programs with GOSUB and RETURN
Entering RUN 2f/Jf/J, you will see the arrow pointing to the left and moving
across the top of the screen from right to left.
Now you should have these two small programs in the computer's
memory. You can select either one by entering RUN 100 or RUN
200. But now you want to combine the two programs, creating the
impression of an arrow moving continuously back and forth across
the screen.
You ought to be able to figure out some ways to combine the two
programs by altering a couple of statements and using some new
GO TO statements. But that's defeating the point of the demon-
stration.
The idea is to combine the two programs, treating them as sub-
routines and devising a third program for integrating into a single
unit.
Subroutines are called by means of a GOSUB line number state-
ment, where line number is the first line number in the subroutine
being called. In this sense, GOSUB line number works just like the
unconditional GOTO line number statement.
So think about this:
EXAMPLE 7-1 c
10 CLS
20 GOSUB 100
30 GOSUB 200
40 GOTO 20
50 END
This little program fIrst clears the screen and then calls the subroutine
beginning at line IOO-the little program specifIed in Example 7-1. Upon
executing line 20, the system fmds itself running the program that starts at
line 100. It still looks like a GO TO 100 statement, right?
What is important now, however, is what happens after the system is
fmished executing subroutine 100. As it stands, line 140 in that subroutine
will return the system to the command mode, and it's all over.
Of course, you don't want the program to conclude that way, so you must
do something to subroutine IOO-amend line 140 to show a RETURN state-
ment, rather than END.
Subroutine 100 is called by line 20 in the controlling program. The
Sec. 7-1 A First Look at Subroutines 143
EXAMPLE 7-1d
10 CLS
20 GOSUB 100
30 GOSUB 200
40 GOTO 20
50 END
100 FOR H=4 TO 58
110 CLS
120 PRINT TAB(H)"---->"
130 NEXT
140 RETURN
200 FOR H=58 TO 4 STEP -1
210 CLS
220 PRINTTAB(H)"<----"
230 NEXT
240 RETURN
Admittedly, this does not make a very compelling case for using sub-
routines; the job could be done easier with other programming tools already
144 Ch.7 Integrating Smaller Programs with GOSUB and RETURN
In this section you are going to take a tour through a complete pro-
gramming job for a moderately complicated task. While studying this
material, you should be conscious of the following principles:
1. The importance of carefully defining the task at hand and
specifying how the results are to be presented.
2. The usefulness of subroutines as a means for breaking down a
complex task into manageable pieces.
3. The power of subroutines as a means of reducing the number
of often-repeated operations.
"In addition to these main ideas, you will find a host of little
tricks and procedures that characterize routine work with sub-
routines. These will be spelled out and discussed as the occasion
arises.
The main idea of this project is to test the quality of the random-
number generator in your own computer. As mentioned in Chapter 6,
home computers normally generate a quasi-random sequence of num-
bers that does tend to repeat itself. The program described here will
show just how "quasi" quasi-random is.
The general procedure will be to simulate a coin-toss situation-
one where 50-50 odds is the ideal result. The program will "toss a
coin" a designated number of times and then compile a figure repre-
senting the number of "heads" divided by the total number of tosses.
The result will be a number between 0 and I, with 0.5 being the
theoretical best result.
And while you're at it, you might as well compare the results of
tossing the coin with and without the RANDOM seeding operation.
If there is something to the notion that one can get better random
numbers by seeding the number generator at certain intervals, the
Sec. 7-2 Designing Moderately Complex Programs with Subroutines 145
TOSS COIN
WITH
RANDOM
146
Sec. 7-2 Designing Moderately Complex Programs with Subroutines 147
begin sketching in more details, not even thinking about getting close
to the computer for awhile.
Still others would start dividing the job into specific subroutines,
entering some program lines into the machine and modifying things
as they go along.
Who's to say there is a best way to approach the situation from
this point? But to get this discussion moving along, the approach used
here will be to design the main subroutines first and then weave them
together later.
The key operation in the program is presenting the information
on the screen. The importance of this operation lies in the fact that it
requires a definition for just about every variable used in the program.
So by starting with the display format, you will have a pretty good
idea about what has to be done elsewhere.
Borrowing an idea from the disciplines of psychology and human
engineering, there ought to be some way to assure the operator that
something is actually taking place every step along the way. It is
going to take some significant amount of time to do all those coin
tosses, and an operator would be justifiably concerned about watch-
ing a blank screen-wondering if anything at all is actually taking
place.
Weaving this notion into the program, it seems important, or at
least highly desirable, to generate a screen display every time a coin is
tossed. The fact that all that information might be virtually worthless
is beside the point.
Bearing these things in mind, it can be seen that there should be
three distinctly different phases in the display process: one kind of
display when tossing the coin without the RANDOM statement,
another display when tossing the coin with RANDOM, and finally, a
display that shows the overall results.
Figure 7-2a through c shows some sketches of the screen as it
ought to appear during the three main display phases.
Aside from serving as general guides for formatting the three dif-
ferent kinds of displays, the sketches in Fig. 7-2 help define most of
the variables to be used in the program. Here's what the programmer
had in mind with regard to the variables:
;8~
WITHOUT RANDOM
~
WITH RANDOM
H T H T
(a)
"',
RANDOM COIN-TOSS FOR ( 'TOSSES
GJ
WITHOUT RANDOM WITH RANDOM
H T H T
G6~cJ'
\ I
DONE FOR \
/~
1 TOSSES
® 03 SCORE = (~),
'-
(b)
FINALSCORE= C~
Figure 7-2 Display formatting plans for the coin-toss experiment. (a)
Phase-l format. (b) Phase-2 format. (c) Phase-3 format.
148
Sec. 7-2 Designing Moderately Complex Programs with Subroutines 149
That takes care of the text that is common to all three phases of
the display. You have not yet encountered the REM statement in
line 100, so that calls for some explanation.
REM is one program statement that causes absolutely no opera-
tion to take place. It is simply a way of indicating some note for the
programmer's convenience. You can follow a REM statement with
any combination of characters you choose, as long as they all appear
on the same line.
In this particular case, REM is used to assign something of a title
to the subroutine. The title is DISPLAY, and the asterisks are in-
cluded merely to make the REMark stand out from the rest of the
text in the program.
When the programming for this job is completed, you will be
able to fInd the DISPLAY subroutine rather easily amid many other
lines and subroutines.
150 Ch.7 Integrating Smaller Programs with GOSUB and RETURN
Upon entering RUN 100, you should see a display quite similar to
that in Fig. 7-2a. The numerical values will probably be zeros, but
that's alright.
To check the phase 2 picture, insert 105 P=2:N=1 and then RUN
100. Compare the result with Fig. 7-2b. And to check out the final
phase of the display scheme, insert 105 P=3 :N=l and, again, do a
RUN 100. Be sure to delete line 105 when you are finished with
these tests.
So much for designing, programming, testing, and, maybe, de-
bugging the DISPLAY subroutine. In itself, it isn't very complicated.
What is needed next is another subroutine for tossing the coin,
TOSS. Here is the beginning of it:
Line 200 merely prints the name ** TOSS ** so that the sub-
routine can be easily found in the overall program listing. The real
work begins in line 210.
Line 210 uses the same phase variable, P, that the DISPLAY sub-
routine does. Whenever P= 1, the system is running its WITHOUT
RANDOM phase; and that being the case, line 210 tells the system
to pick up operations from line 230.
The "coin tossing" is done at line 230, generating a 1 or 2 each
time it's encountered. The sequence of 1's and 2's from this line
Sec.7-2 Designing Moderately Complex Programs with Subroutines 153
ought to be fairly random, and that is precisely what this whole pro-
gram is supposed to show. The fact that it is all put into a coin-
tossing format is simply window dressing.
After line 230 picks a 1 or 2 at random, line 240 sends opera-
tions to one of two other lines. If D0 happens to be aI, line 240
sends things to line 250, where the string variable, A$, is set as
HEADS. In other words, the play is HEADS whenever D0 turns up 1.
But when D0 turns out to be 2, line 240 sends operations down
to line 255, where A$ is set to TAILS. D0=2 really means TAILS.
Going to line 250 from the ON ... GOTO statement in line 240
also increments the value of AH-a numerical variable representing
the number of times "heads" appears during phase 1 of the project.
Line 250 then concludes with a RETURN statement that carries
operations out of the TOSS subroutine and back to the main calling
routine.
The same sort of thing happens if D0 turns up a 2. By line 255,
A$ is fixed at TAILS, the AT "tails counter" is incremented by 1,
and control returns to the main program.
All of this if P= 1. What if P=2? You need more program to answer
that question.
260 RANDOM:D0=RND(2)
270 ON D0 GOTO 280.285
280 A$="HEADS" :BH=BH+1: RETURN
285 A$="TAILS":BT=BT+1: RETURN
290 END
If P=2 back in line 210, the ON ... GOTO statement in that line
sends the system to line 260; and line 260 is the one that does a
RANDOM seeding operation before the RND(n) step. After that, the
operation of this part of the TOSS subroutine is identical to the
phase 1 portion in lines 240 through 255. A$ is set to HEADS or
TAILS, the phase 2 heads and tails counters are incremented by 1,
and operations are returned to the main calling program (which, if
you haven't noticed yet, still isn't written).
Incidentally, the STOP statement in line 220 is one of those pro-
grammer's tricks that reflect a cautious style. The TOSS subroutine
should never be called while the system is in its phase 3 mode-the
one that merely prints out the overall results of the project. If TOSS
should be called during phase 3 (because the programmer goofed),
P would be equal to 3, and the ON ... GOTO statement in line 210
would force a default to line 220.
Recall that a STOP statement is a programmable version of the
154 Ch.7 Integrating Smaller Programs with GOSUB and RETURN
The first step in the flowchart calls for initializing some variables.
Not all the variables have to be initialized at this point-just those
that must be set from the very start. Variable N should not be
initialized at this point, because it will pick up an assigned value in
the INPUT step that follows the initialization step. DIP doesn't have
to be initialized, either, because it will be assigned a value of I or 2
during the TOSS subroutines; and by the same token, there is no
need to initialize A$.
What this all boils down to is the fact that the" counters" AH,
AT, BH, and BT should be set to zero. If it so happens that your
system does not automatically set all numerical variables to zero
when a program is first run, failing to initialize these counters will
produce some very strange results when it comes to counting the
number of heads and tails tosses. So to be on the safe side, they
should be set to zero in the first step of the program.
The second step in the flowchart is a rather straightforward
INPUT N operation where the operator designates the number of
times the coin is to be tossed in each of the two tossing phases.
The phase counter, P, is set to I in the next step, forcing the sys-
tem to carry out phase I operations, namely TOSS and DISPLAY.
The TOSS and DISPLAY subroutines are run in the next two steps;
and immediately after that, the numbers of "heads" and "tails" are
summed and compared with the value of N.
According to the AH+A T>=N conditional block, operations
move on to the second phase (P=2) if the condition is satisfied; that
is, the total number of tosses in the first phase is equal to the desired
number of tosses, N. If the conditional is not satisfied, however, con-
trol returns to the beginning of phase I, and the TOSS and DISPLAY
sequence is repeated.
From all appearances, phase 2 in Fig. 7-3 appears identical to
phase I, the only difference being that P has different values. In
reality, the two operations are quite different, but the differences
are hidden within the TOSS and DISPLAY subroutines.
Once the conditional block labeled BH+BT>=N is satisfied, P is
set to 3 and the system enters the final phase. The final results are
displayed on the screen (by running DISPLAY with P=3), and the
display is held on the screen by doing one of those GO TO "your-
self" statements.
So now you have a complete flowchart for the entire program.
This is the time to look over such charts carefully, doublechecking
your thinking and, in fact, the principle of the whole thing. If it
seems to make sense, it is time to use it as a guide for writing the
main program. Here it is:
1~
15
20
'--------,,..-----'
Sub.
2¢¢ '---_--.-_-----1
45
Sub. L--_---,_-....J
1¢¢
N
5¢
Sub.
1¢~ ' - _ - - , - _ - J
65
'-----.----'
155
Sec. 7-2 Designing Moderately Complex Programs with Subroutines 157
10 CLS:AH=0:AT=0:BH=0:BT=0
15 INPUT "SPECIFY NUMBER OF TOSSES PER PHASE";N
20 P=1 :GOSUB 200
25 GOSUB 100
30 IF AT+AT =N THEN 40
35 GOT020
40 P=2:GOSUB 200
45 GOSUB 100
50 IF BH+BT=N THEN 60
55 GOT040
60 P=3:GOSUB 100
65 GOTO 65
70 END
And that's it. That is the program that pulls together the two sub-
routines and makes things work. Assuming TOSS and DISPLAY are
still residing at lines 200 and 100 in the program memory, you are
ready to check out the whole thing.
You have already tested the subroutines; so if the program
doesn't work properly, the trouble is most likely in the main pro-
gram. In any event, you should now run through the main program
in an "on-paper" fashion, justifying each statement and comparing
it with the flowchart.
By now you are in a good position to appreciate the real power
of subroutines and their associated GOSUB and RETURN statements.
Imagine what this program would be like if you hadn't designed the
tossing and displaying operations as subroutines! The TOSS sub-
routine, for instance, is called with GOSUB 2(/J(/J on two entirely dif-
ferent occasions, and the DISPLAY subroutine is called by GOSUB
1(/J(/J on three different occasions. Without using them as subroutines,
most of their lines would have to be repeated through a long and
ghastly complicated program.
basis for specifying where operations are to go. Before seeing what
happens if M is a valid entry, look at what happens if M happens to
be greater than 3.
If M is greater than 3 (or, to be more accurate, 4 or greater), the
ON ... GOTO statement defaults to line 350; and as already de-
scribed, this is an error line that returns operations to line 310,
giving the operator a chance to enter a valid value for M.
Now suppose the operator enters a I in response to the INPUT
statement in line 320. According to line 340, M=l carries opera-
tions down to line 360, and that line is made up of the statement,
RETURN. In other words, if M=I, operations simply leave this sub-
routine and go back to the program that called it in the first place.
Nothing changes-the main program will be run as if this particular
discussion never existed.
But if the operator enters a 2, line 340 sends operations down to
line 370. That line is made up of a sequence of statements that create
a time delay before doing a RETURN to the calling operation. That
represents the AUTO WITH DELAY option.
Finally, entering a 3 in response to the INPUT M statement
ultimately carries the computer to line 380. Line 380 is one of those
statements that halts all operations until the null string is entered or,
in other words, the operator strikes the ENTER key. After the oper-
ator strikes the ENTER key, the RETURN statement at the end of
line 380 returns operations back to the calling program.
The TOSS MODE SELECT program can be tested by itself upon
doing a RUN 3~~ and responding to the SELECT TOSS MODE
message with a I, 2, or 3. The subroutine will conclude at one of
three RETURN statements, depending on the value of M you enter.
Since you have not yet written any GOSUB 3~~ statements,
running this subroutine will result in an error message that ought to
include the line number containing the RETURN. The error message
generated by the computer ought to specify an error in line 360 if
you have entered a I at line 320. It should specify an error at line
370 if you have entered a 2, and it should show an error at line 380
if you have entered a 3.
Also enter a 0 and a 4 to check the goof-proofing statements.
All that remains to be done is to fit this new subroutine into the
main program. There are a number of ways to go about it, but the
following sequence of insertions gets the job done in a very effective
and efficient fashion:
12 GOSUB 300
27 GOSUB 340
47 GOSUB 340
160 Ch.7 Integrating Smaller Programs with GOSUB and RETURN
Now that was relatively painless, wasn't it? GOSUB 3~~ is placed
at line 12, between the lines that initialize the counting variables
(line 10) and the one that asks for a value of N (line 15). The oper-
ator thus has a chance to initialize the value of M each time the pro-
gram is started.
But what is subroutine 340 called in lines 27 and 47? Well, lines
27 and 47 follow the DISPLAY subroutine in phases 1 and 2 of the
overall program. You don't want to set the value of M after every
display subroutine, just at the first part of the program. So by doing
a GOSUB 34~, the M-setting part of the TOSS MODE SELECT
subroutine is omitted, going directly to the part that actually deter-
mines the mode of operation.
So if the operator initially sets the value of M at I (in response to
the INPUT statement called by line 12 and, subsequently, line 320),
M will hold that value of 1, no matter how many times the program
calls line 340.
The entire subroutine 300 is thus called only as part of the pro-
gram's initializing process. After that, line 340 is called, and the sys-
tem responds with normal automatic coin tossing, delayed automatic
coin tossing or purely manual coin tossing-depending, of course,
upon the numerical value of M.
Now you know what subroutines are for:
1. They allow the programmer to build relatively complex pro-
grams in a piecemeal fashion, and then weave things together
with a master program.
2. They can simplify the program itself by replacing repeated
sequences of operations with one subroutine that can be
called any number of times.
3. They make it possible to modify and extend programs with-
out having to do extensive surgery on the existing work.
EXERCISES
7-1 What is the purpose of a REM statement? How does the computer respond
upon encountering a REM statement in a program?
Ch. 7 Exercises 161
7-2 Which of the following do you think are valid subroutine-calling statements?
(a) 10 GOSUB 400
(b) 10 IF A>50 THEN GOSUB 400
(c) 10 ON A GOSUB 400, 500, 600, 700,
where A is an integer between 1 and 4 inclusively.
7-3 How would you go about testing the following subroutines before they are
written into a master program?
(a) 200 REM ** COUNT **
210 A=A+1 :CLS:PRINT A
220 IF A>=10 RETURN
230 GOTO 210
240 END
(b) 200 A1=2:A3=3:A4=25:A6=A5/A1 :RETURN
(c) 200 REM "DECIDE"
210 ON Q GOTO 230, 240
220 RETURN
230 A=B+C:CLS:PRINT A:RETURN
240 A=B/C:CLS:PRINT A:RETURN
7-4 What do you think is the meaning of the expression nested subroutines?
What are the implications of the idea? See if you can make up a program
that uses some nested subroutines.
7-5 Name at least three distinctly different advantages of using subroutine-
oriented programs, then write an illustrative example of each.
7-6 Carefully defme the differences between a GO TO line number and a
GOSUB line number statement. Study the ways these two statements are
used in the examples in this chapter and see if you can arrive at some
guidelines for using one or the other under a given set of circumstances.
More about
Composing Programs
with Subroutines
162
Ch.8 More about Composing Programs with Subroutines 163
before the next step is begun. You will find yourself going around
and around several times, changing and extending earlier ideas on the
basis of what you discover later.
None of the steps in the programming process is complete-not
even the first one-until you enter RUN and find things working
exactly as you planned. Even then, you might wonder if there are a
few rough edges that might be smoothed.
While working your way through this chapter, you are going to
find that subroutines and flowcharts are invaluable tools. Of course,
all the programming statements and principles described so far in this
book are important, too; but they take on almost trivial significance
compared to the overall perspectives engendered by using subroutines
and flowcharts.
ing whether or not they will really work. This is especially true when
working on a job you have never done before. If at all possible, test
some of the ideas on the machine. You will then know whether or
not you are on the right track.
By the time you have worked your way through the third pri-
ority, you are going to have a very good idea of how simple or diffi-
cult the task is going to be. If things seem simple, you are in fine
shape for moving on. But if things seem to be getting overly compli-
cated and perhaps a bit out of hand, the real problem might rest with
your approach.
The world is basically a simple place that is made to appear com-
plicated only by one's perspective; and it is this bit of homely
philosophy that makes the fourth priority an important one: re-
examine the plan and subroutines in the light of the main task.
It is at this fourth priority level that your own skill, talent,
crea tivity, and fortitude come into play. In the extreme cases, you
might even find it necessary to work out another approach or maybe
redefine the task. Throwing away all the work you have done to this
point can mean one of two things: either you have completely lost
patience with the job, or you've been blessed with a bit of hard-won
insight that promises to smooth out the work.
In the first instance, you're just postponing the inevitable; and in
the second, you've just conquered it. In either case, you eventually
wind up at the fifth level of priority.
You should write, enter, and test the subroutines only after you
know exactly what you are trying to do. Writing one subroutine
often calls for having previously established the values of some
variables; and since those values might be established by yet another
subroutine, you aren't going to write very good ones until everything
fits together.
When the key subroutines appear to mesh together properly,
rework the flowchart. This time the flowchart can be labeled with
more specific details-more specific PRINT statements, names of the
subroutines, and so on. The subroutines themselves do not have to be
flowcharted in great detail, but the revised chart should more clearly
indicate how you are handling the task.
Now you are down to the eighth priority level. It's the proper
time to write the main program that calls the subroutines at the
proper times and does all the little tasks that are too simple to
occupy subroutine space. This program ought to be a reflection of
your revised flowchart. Ideally, it will follow the main flowchart in
every detail; but in practice you might find yourself modifying the
flowchart a little bit to suit your evolving program. That isn't a case
of cheating but one of applying some practical wisdom.
Sec.8-2 A Feasibility Study for Buying a New Home 167
Then run the whole program, looking first for gross errors and
then for finer annoyances. Make any relevant modifications in the
flowchart as you go along.
A programmer rarely anticipates every detail of the system from
the outset, and the need for altering the existing program or adding
some extra features shows up quite clearly when running the whole
thing. So the tenth priority level is to add any of those necessary or
newly discovered possibilities that make the program a bit more
useful or attractive to the user.
Every program must be thoroughly documented. As wise old
Murphy (the Murphy of Murphy's Law) says: "If it can go wrong, it
will." . That applies to electronically stored computer programs.
Imagine weeks of hard work going down the drain in a few micro-
seconds when something goes wrong-a power outage garbles the
computer memory, someone carries your cassette tape too close to
an alternating magnetic field, and all those other nasty things that
make up the nightmares of developmental programmers.
Write down your program as you go along. If you have access to
a line printer, keep a running log of program listings.
Can we afford to buy the dream home we have just found? What
kind of home can we afford? If we can afford a new home, what will
the monthly payments be and should we buy-with a VA, FHA, or
conventional loan?
These are questions prospective home buyers must ask them-
selves, and the purpose of this section is to compose a BASIC pro-
gram that will help answer those questions. The example illustrates
the general procedures for designing subroutine-oriented programs,
and it introduces a couple of new ideas along the way.
The first part of the job is to carefully define the task at hand.
This can be a time-consuming and tedious task at times, but it is
generally a manageable task as long as you don't try to do too
much at one time.
After giving the matter some careful consideration, you might de-
cide the job ought to be divided into three categories of operations:
Option A-Given the price of a new home, calculate the monthly
payments and recommend a loan plan.
Option B-Given the amount of money available for making
168 Ch.8 More about Composing Programs with Subroutines
1 Sub.
1~
Sub.
y 6¢1/I
tion is that the buyer cannot afford to make the mortgage payments,
and the NOT RECOMMENDED MESSAGE tells him so.
In any event, control returns to the main calling program after
making these recommendations.
The option A flowchart in Fig. 8-2a appears to be a nice little
program in itself. And it turns out that it includes some operations
that could also be written as subroutines.
Subroutine 7~
SUb.
} 3~~
Sub.
2rprp
(e)
RETURN
(a)
172
Sec. 8-2 A Feasibility Study for Buying a New Home 173
This test program clears the screen and calls subroutine 200-
the one just entered. While executing subroutine 200, the system
will request values for SO, OM, OS, and ME; calculate the value of
DP; and print the value of DP after writing DOWN PAYMENT
AVAILABLE $.
You know the subroutine is put together properly when you see
the values repeated on the screen (line 20 of the test program),
followed by an OK. You can repeat the test any number of times by
striking the ENTER key after seeing OK and a question mark (line
30).
Another useful subroutine can be one that accepts the value of
AI from the keyboard and uses it to figure the value of FR. This is
an exceedingly simple routine; but since it is used in all three options,
you might as well designate it as a subroutine. The choice is yours.
300 REM $$ INCOME $$
310 INPUT "GROSS ANNUAL INCOME $";AI
320 FR=AI *.2/12
330 RETURN
Sec.8-2 A Feasibility Study for Buying a New Home 175
Upon running this test program, it first calls for some values
of MP, FR, and DP; then it runs subroutine 400. The test pro-
gram ought to be run several times, plugging in values that cause
PURCHASE NOT RECOMMENDED, PURCHASE RECOMMENDED
BY VA OR FHA LOAN, and PURCHASE RECOMMENDED BY
CONVENTIONAL LOAN. If you have never been much of a mathe-
matician before, this is your chance to build some confidence.
These three subroutines-INPUTS, INCOME, and RECOM-
MEND-contain just about all the variables used anywhere in the
overall program. So now it's time to string them together with three
other subroutines: OPTION A, OPTION B, and OPTION C.
Subroutine 500, OPTION A, is written almost exclusively from
the flowchart in Fig. 8-2a. Here it is:
Again, the rationale and method for testing this subroutine are
left to the reader. Being fully acquainted with the definitions, equa-
tions, and intended task ought to make the analysis a rather straight-
forward affair.
Thus far, the procedure is down to the sixth priority level in the
general programming process-seeing if the main flowchart could be
more clearly drawn. In this case some of the labels for the blocks in
Fig. 8-1 could be reworked to reflect subroutine numbers and actual
BASIC statements that are relevant at key points. In a general sense,
the main flowchart in Fig. 8-1 is in pretty good shape.
The eighth priority level is the next one calling for some clear-cut
action: Write the main program according to the main flowchart.
Thus far, all that has been done is to develop the subroutines and,
incidentally, some subroutines within the subroutines. The final
step in the actual programming process is to write the main program
according to the flowchart in Fig. 8-1.
But hold on a minute! The very first step in the main flowchart
calls for a rather extensive printout of the available options. You de-
cided earlier in the job that this PRINT OPTIONS operation ought to
be delegated to a separate subroutine. So there is yet one more sub-
routine to write.
Before showing a version of this OPTIONS subroutine, note how
a programming job that is carefully and completely spelled out from
the beginning is almost foolproof. We almost forgot an important
part of the work-something that is easy to do when working through
an extensive program. The fact that the whole plan was set up in
advance, however, makes it possible to walk away from the whole
thing for a day or two at a time without losing track of what has hap-
pened and what must be done.
Here is the subroutine for PRINT OPTIONS:
100 REM $$ CHOICES $$
110 PRINT "OPTION A -- GIVEN COST OF NEW HOME,"
120 PRINT TAB(121"CALCULATE MONTHLY PAYMENTS."
125 PRINT TAB(201"OR"
130 PRINT "OPTION B -- GIVEN DESIRED MONTHLY PAYMENTS,"
140 PRINT TAB(121"CALCULATE MAXIMUM PRICE OF NEW HOME."
145 PRINT TAB(201"OR"
178 Ch.8 More about Composing Programs with Subroutines
>RUN 100
OPTION A -- GIVEN COST OF NEW HOME,
CALCULATE THE MONTHLY PAYMENTS.
OR
OPTION B -- GIVEN DESIRED MONTHLY PAYMENTS,
CALCULATE MAXIMUM PRICE OF NEW HOME.
OR
OPTION C -- GIVEN INCOME, CALCULATE
THE MAXIMUM COST OF A NEW HOME AND
THE MONTHLY PAYMENTS.
With that job out of the way, the main calling program comes
next.
10 CLS
20 GOSUB 100
30 IFA$="A" THEN 50
35 IF A$="B" THEN 70
40 IF A$="C" THEN 90
45 PRINT "ERROR. TRY AGAIN":GOTO 20
50 CLS: GOSUB 500
60 GOTO 95
70 CLS: GOSUB 600
80 GOTO 95
90 CLS: GOSUB 700
95 INPUT X$: GOTO 10
97 END
This is the master program that pulls together all the work done
so far. All that remains of the programming process is to run it
thoroughly, trying all the options.
Sec.8-2 A Feasibility Study for Buying a New Home 179
But there are still two steps remaining in the general program
composing procedures; and one of those is to make any necessary or
desirable modifications. In this case the program has been fairly well
debugged. What about desirable modifications?
You recall that the BASIC language accepts large numbers with-
out the benefit of commas. Ten thousand, for example, must be
entered as 10000, not as 10,000. The system would be confused by
the comma, either generating erroneous results or an automatic error
message. Your user might not know that, though; so the program
ought to include a notation to the effect that commas must not be
used in large numbers.
There are a number of ways to handle this particular modifica-
tion, but here is a very straightforward one:
EXERCISES
8-3 Repeat the work requested in Exercise 8-2 for the following program:
10 CLS: PRINT "START AT 10"
20 GOSUB 100
30 PRINT "AT THE START AND ENDING"
40 PRINT "DONE"
50 END
100 PRINT "AT SUB 100": GOSUB 200
110 PRINT "AT SUB 100 AND RETURNING":RETURN
200 PRINT "AT SUB 200": GOSUB 300
210 PRINT "AT SUB 200 AND RETURNING":RETURN
300 PRINT "AT SUB 300": GOSUB 400
310 PRINT "AT SUB 300 AND RETURNING":RETURN
400 PRINT "AT SUB 400": GOSUB 500
410 PRINT "AT SUB 400 AND RETURNING":RETURN
500 PRINT "AT SUB 500 AND RETURNING":RETURN
8-4 Subroutines 600 and 700 in Section 8-2 both contain the sequence
CALCULATE CN followed by PRINT CN. Devise a subroutine for this
sequence, beginning at line 800 and having any literal name you choose.
Rewrite the programs for OPTION B and OPTION C to include your new
subroutine (and, of course, eliminate the original references to CAL-
Ch.8 Exercises 181
2X4+3=
182
Sec. 9-1 Order of Math Operations 183
That's "two times four plus three." What is it equal to? 11 or 14?
Do you multiply 2 times 4 and then add 3? Or should you add 4 plus
3 and then mUltiply by 2?
Without being aware of a certain convention concerning the order
in which arithmetic operations are performed, the problem is an
ambiguous one.
One way to resolve the ambiguity is by inserting parentheses into
the expression:
(2 X 4) + 3 =_
or
2X(4+3)=_
2 X 4 + 3 = (2 X 4) + 3 = 11
EXAMPLE 9-1
Third step
Final step
Of course, the bulk of this activity takes place behind the scenes; and as
far as the user and programmer are concerned, the only apparent parts of
the job are the original problem and the final step.
EXAMPLE 9-2
EXAMPLE 9-3
Going from left to right, BASIC multiplied 2 times 4 and then divided the
result by 10.
and division operations from left to right. In this case you'll get the
same answer if you happen to work from left to right: 2 *4 = .8.
The need for working equal-priority math functions from left to
right becomes more apparent when they are mixed with operations
of the fourth level-addition and subtraction.
Like multiplication and division, addition and subtraction oper-
ators carry equal weight and are always executed from left to right.
EXAMPLE 9-4
BASIC first multiplied 2 times 4 and then divided 8 by 2. That took care
of the left-ro-right execution of the higher-order multiplication and division
operations. After that, in the third step, BASIC subtracted 1 from 8 and
then added 4 to the result to come up with the final answer.
EXAMPLE 9-5
The first objective in solving this example is to clear out the inner set of
parentheses. But to do that, BASIC must apply the rule that multiplication
and division take precedence over addition, first working with multiplica-
tion and division from left to right. See the first and second steps.
The inner set of parentheses is eliminated only after doing the addition
indicated in the second step. Even after that, another set of parentheses
remains to be worked out; so BASIC does the exponentiation (fourth step),
followed by a left-ro-right execution of the addition and subtraction (fifth
and sixth steps).
The parentheses are fmally gone by the sixth step, and all that remains is a
single multiplication.
For the sake of checking the operation of the BASIC version, let G=32,
T=2, and V~=l~. Applying these values to the original equation, S=84.
Now walk through the BASIC version:
S=1/2GTt2+V0T
EXAMPLE 9-8 Write a BASIC statement for solving the equation ra+b,
or the cube root of the sum of a and b. Now the only provision for working
with radicals in BASIC involves the mathematical principle -{Vx = x 1/n. The
radical is expressed as a fractional exponent. Mathematically speaking,
..:ya+b can be represented as (a + b) 1/3; in BASIC, it should look like this:
(A+B)t(1/3)
You can test the idea by substituting some :')nvenient values for variables
A and B-such as 2 and 6, respectively. That should yield the cube root of
8, or 2. See if the BASIC equation works:
It works. Plug it into a program and run the equation for a number of dif-
ferent values for A and B. It will work every time.
In retrospect, however, is it necessary to enclose the fractional exponent
in parentheses? Couldn't the BASIC form of the equation be written
(A+B)t1/3?
Substitute the same values for A and B, and walk through the BASIC rules
for working equations.
Sec. 9-2 Writing Ordinary Eouations in BASIC 189
One of the best ways to master the technique for writing mathe-
matical equations in BASIC is to transcribe equations found in
technical books. If you are not especially good at solving the prob-
lems yourself, there is nothing lost by using examples already worked
out in the book. Simply rewrite the equations in a BASIC format and
run them on the computer. Any mistakes you make in the pro-
gramming ought to show up quite clearly. In that case, it is up to you
to figure out what you did wrong.
EXAMPLE 9-9 Solve the equation Ax2 + Bx + C =0 for the two possible
values of x, given the values of A, B, and C.
The simplest way to approach the situation is by applying the quadratic
equation:
-B ±yB2 -4AC
x=------
2A
The ± operator in the numelator of the quadratic equation implies there are
two answers to the problem-that there are two possible values for x. One
value comes about when -B is added to the radical expression; the second
comes about when the radical expression is subtracted from -B. It is alto-
gether possible that the product 4AC can be larger than B2. Whenever that
is the case, the equation calls for taking the square root of a negative num-
ber, and the result is a set of imaginary solutions. Home computers cannot
deal with imaginary solutions without some help from the programmer;
so to keep this task down to manageable proportions, the program ought to
give up whenever the solutions are imaginary. Set up the program to print
out real solutions only.
30 IF R0<0 THEN 90
40 R=R0t.5
50 X1=(-B+RII(2*A)
60 X2=(-B-RII(2*A)
70 PRINT "X1="X1,"X2="X2
80 GOTO 100
90 PRINT "IMAGINARY ROOTS"
100 INPUT X$; GOTO 10
The values of A, B, and C are entered from the keyboard in line 10. line 20
then solves the expressions inside the radical: B2_4*A*C. The result is
assigned to variable R(b.
If R(b is negative, the roots are imaginary and the system ought to pass on
the problem, printing simply IMAGINARY ROOTS. This is what happens if
the conditional statement in line 30 is satisfied.
line 40 takes the square root of the expression under the radical and
assigns it to variable R. In this case, using an exponent of 0.5 gets around
the fractional-exponent difficulty described in Example 9-8. Alternative
procedures would be to use R=R(b (1/2) or, better yet, R=SQR(R(b). Recall
from Table 1-1 that SQR(n) extracts the square root of n.
Line SO completes the solution of the quadratic equation for the case
where -B is added to the radical term. line 60 picks up the second solution
where the radical term is subtracted from -B. The solutions are assigned to
Xl and X2, respectively. See if you can work out the equations in those two
lines of the program without having to install two sets of parentheses.
Table 9-1 summarizes all the math functions that are available on
most BASIC-oriented home computer systems. You have seen some
Sec.9-3 A Roundup of Other BASIC Functions 191
of them already, but they are repeated here for the sake of con-
venience and completeness.
This is not the place to launch a lengthy and detailed dissertation
on the mathematics involved in these BASIC functions. A good
college textbook on intermediate mathematics treats such subjects in
all their glory. The task at hand is one of BASIC computer program-
ming; so other than a few remarks and some examples, it is up to the
reader to dig out the mathematics of the affair in another source.
The INT(n) function is worthy of special note because several
other BASIC statements apply the function automatically. Take, for
example, the ON (n) GOTO line numbers. Recall from Chapter 6
that n can be a math expression that generates numbers that are not
necessarily integers. It is logically necessary, however, to count line
numbers with whole numbers, or integers. As described in Chapter 6,
a value of n that is something like 2.554 going into an ON(n) GOTO
line numbers statement will fIrst be "rounded" to 2-the greatest-
integer value of 2.554. In short, BASIC does an automatic INT(n)
before executing an ON(n) GOTO line numbers statement.
As long as the n in an INT(n) expression is zero or more (posi-
tive), you can think of the function doing no more than simply
dropping off all the decimal values. So a number such as 1.1 be-
comes I, and 89.999 becomes 89. But that isn't quite the case for
192 Ch.9 More about BASIC Math and Numbers
CL = .4343*LOG(n)
where n is any number larger than zero and CL is your own variable
designation for common, base 10 log.
You can try this conversion with the system in the command
mode by entering PRINT .4343*LOG(0). The system immediately
returns 1.0000 I-a number very close to the base 10 log of 10
(which is 1.00000).
Sec.9-3 A Roundup of Other BASIC Functions 193
EXAMPLE 9-10
100 INPUT N
1101F N<=0THEN 130
120 Y=LOG(N): GOTO 140
130 PRINT "N MUST BE GREATER THAN ZERO. TRY AGAIN":GOTO 100
1413 PRINT Y
EXAMPLE 9-11
10 CLS
20 INPUT "ENTER ANGLE IN DEGREES";N
30 IF INT(N/90)=N/90 THEN 60
40 PRINT "N="N,"TAN(N)="TANL17453*N)
50 INPUT X$: GOTO 10
60 PRINT "INVALID N (MULTIPLE OF 90 DEGREES). TRY AGAIN"
70 GOTO 20
80 END
The user actually enters some angle N in degrees at the INPUT statement
in line 20. Line 30 uses an INT(n) function to see whether or not N is an
integer multiple of 90. If that is the case, INT(N/90) is equal to N/90 and
the condition is satisfied, and control is sent down to the error message in
line 60.
If, however, the conditional statement in line 30 is not satisfied-N is not
an integer multiple of 90-the system prints the value of N, followed by the
tangent of the angle.
Line 50 merely gives the user a chance to run the program again by
striking the ENTER key.
SIN(.017453*N)
COS(.017453*N)
TAN(.017453*N)
Note.
And then when you want to work out the sine of N later, all you
have to do is refer to function S(N). Maybe you want to input a
value of N and then print the sine of it:
INPUT N
PRINT FNS(N)
the DEF FN statement. Consult your manual to see if you have this
advantage available to you.
EXAMPLE 9-12
10 N=0
20N=N+.1
30PRINTN
40 GOTO 20
Now you could reasonably suppose that this program would print out an
endless list of numbers, from zero to infinity in steps of .1. As long as the
program is running, you would expect to see only one digit to the right of
the decimal point, right?
Try it, and watch what happens. Somewhere along the line, the program
seems to undergo spasms where more than one number appears to the right
of the decimal point-the accuracy goes to pieces temporarily.
Exactly where and how often the problem arises, and how long it
lasts, depends a lot on the electronics in the system you are using. On
the Radio Shack TRS-80, the inaccuracies first creep in as this
program counts past 7.7. The glitch looks like this:
7.7
7.79999
198 Ch.9 More about BASIC Math and Numbers
7.89999
7.99999
8.09999
8.2
Everything goes along fine until it is time to count and print 7.8.
Instead, the system produces 7.79999; and the little error persists
until it gets down to 8.2.
The program in Example 9-12 is just one way of detecting
groups of these little inaccuracies; and they occur rather frequently,
and tend to last longer, as the program runs.
There isn't much to be gained by going into a lengthy technical
discussion about the reasons that this sort of thing happens. In a
nutshell, the problem is caused by the fact that computers do their
calculations on the basis of binary numbers rather than decimal num-
bers. BASIC works with decimal numbers for the convenience of the
user and programmer. And that means decimal numbers from BASIC
have to be converted into binary numbers before they can be handled
by the electronics. After that, the electronic results have to be
translated from binary into decimal form again.
"Something is always lost in the translation," as the old saying
goes; and this is just'one example of how accuracy can get "lost" on
a computer.
This is a grossly oversimplified explanation, but it should suffice
for most programmers.
The inaccuracies of this sort creep into math operations other
than the counting one specified in Example 8-12. They can crop up
just about anywhere.
Now, of course, this means that some results of calculations are
going to have some small errors in them. Most people can live with
that sort of thing. 7.79999 is close enough to 7.8 for most practical
purposes.
However, there is a far more serious situation involved here. Con-
sider the following modification of Example 9-12:
EXAMPLE 9-13
10 N=0
20 N=N+.1
313 PRINT N
35 IF N=7.8 END
413 GOTO 20
Sec. 9-5 Some Notes about Numbers and Scientific Notation in BASIC 199
Preswnably, the program will run until it prints 7.8, and then it comes to a
stop. But it won't do that-it just keeps running along, passing 7.8 as though
it never existed. Why? Because the exact value, 7.8, never did exist. Nwn-
bers such as 7.79999 and 7.89999 were there, but they bracket the 7.8
value.
Nasty little feature, isn't it! What's worse is writing a program
that looks perfect on paper but doesn't work on the machine because
of such a problem.
Take heart-there is an easy way around all this. In this partic-
ular case, modify line 35 in Example 9-13 to read
35 IF N>=7.8 END
Develop the habit of using >= and <= in place of =, and you will
rarely run into the problems caused by rounded and translated num-
bers. The computer still makes its "mistakes," but now you know
how to cover for it.
While on the subject of roundoff errors and such, you have
probably noticed that your system never prints numbers having any
more than six digits in them. That's the case, anyway, if you are
using the usual single-precision accuracy.
Not all the numbers have all six digits specified, however. Doing
an operation such as PRINT 1/2 causes the machine to return .5-
a single-digit number that effectively has five zeros following it. The
system automatically suppresses, or truncates, trailing zeros in a
decimal expression (as most people do). In fact, getting a number
having less than six digits implies that the number is quite accurate.
Try PRINT 1/3 and you will get .333333 printed on the screen.
Try PRINT 2/3 and you get .666667 for an answer. Irrational frac-
tions result in unending decimals; but in the real world, one has to
draw the line somewhere and round off the result. Your computer
system, using single-precision accuracy, rounds off the answer at the
sixth digit.
Now here is an important question: How does a system limited
to six digits handle very large and very small numbers? The answer is
200 Ch. 9 More about BASIC Math and Numbers
EXAMPLE 9-14
10 CLS
20 INPUT "VALUES OF A, B"; A,B
30 PRINT A, B, AlB
40 INPUT X$: GOTO 20
With this program, you can enter all sorts of numbers in scientific nota-
tion, and then see how the system interprets the pairs of numbers and works
out their ratio. Running this program on Radio Shack's TRS-80, the activity
on the screen looks like this:
VALUES OF A, B7 .000123, 123000.<
1 .23E-04 123000 1 E-09
7
Ch. 9 Exercises 201
Get the program in Example 9-14 plugged into your own ma-
chine and play around until you recognize the peculiarities.
The important thing is that BASIC is indeed equipped to deal
with scientific notation.
EXERCISES
9-2 Transform the following standard equations into the BASIC syntax. Assume
that the values of the variables are available.
(a) A = %BH
(b) V= £3
(c) S=%GT2+VoT+So
202 Ch.9 More about BASIC Math and Numbers
9-4 State the order of priorities for execution of BASIC math operations.
9-5 What values of n are invalid for the BASIC function TAN(n)?
9-6 Suppose that you wrote the following statement into a program. Assuming
that the value of P is available, how would you specify an operation that
would print the result of the function?
DEF FNU(P)=(P+2)t(1/3)
203
204 Ch.10 An Introduction to Logical Operations
EXAMPLE 10-1
The only way you can get the computer to print THAT'S RIGHT is by
setting A=l AND B=2. Any other combination of values merely restarts the
program.
EXAMPLE 10-2
a bit looser than for an AND statement. Only one of the conditions
must be met in order to satisfy the overall statement.
EXAMPLE 10-3a
EXAMPLE 10-3b
Sue and Bill or Jack visits us tonight, we will go to the movies." Here
are the requirements spelled out in this statement:
1. We will go to the movies if both Sue and Bill visit. Jack
does not have to come.
2. We will go to the movies if Jack visits. Sue and Bill do not
have to show up.
3. We will go to the movies if Sue, Bill, and Jack visit.
Looking at the same situation from a negative point of view:
1. We won't go to the movies if just Sue visits.
2. We won't go to the movies if just Bill visits.
3. We won't go to the movies if none of the three show up.
One of the most useful and, in fact, vital applications of AND
and OR operators is that of setting upper and lower boundaries on
variable quantities. The standard BASIC inequalities are adequate for
setting upper or lower boundaries, but not both at the same time.
Upper boundaries, for example, can be set by means of expressions
such as A<l~ and A<5~. By the same token, lower boundaries can
be set by using expressions such as A>~ and A>=l~. But home-
computer BASIC generally cannot handle both at the same time-
~<A<=l~ won't work, even though it represents a common sort of
mathematical expression.
In a literal sense, the expression O<A<=lO means the value of A
is greater than zero but less than or equal to 10. The BASIC version
of the same idea must be expressed this way: A>~ and A<=l~.
That does it. It is saying that A has to be greater than zero AND, at
the same time, less than or equal to 10.
Try this experiment:
EXAMPLE 10-4
So what you see is a simple listing of numbers 1 through 10. You can
prove to yourself that the system is still counting by doing a BREAK,
followed by entering PRINT A in the command mode. The result will be
some relatively large number-one representing the progress of the counter.
where line number, in this instance, carries the program to a valid se-
Sec. 10-1 Logical Operators for IF ... TH EN Statements 209
EXAMPLE 10-1
EXAMPLE 10-5
Both programs do exactly the same job. They print the message THAT'S
RIGHT only if the operator enters the sequence 1, 2 in response to line 10
in both instances. Entering any other sequence of numbers merely restarts
the program.
The use of a NOT/AND conditional in Example 10-5 shortens the pro-
gram by one line, however. Instead of printing THAT'S RIGHT whenever
210 Ch. 10 An Introduction to Logical Operations
A=1 AND B=2 (as in Example 10-1), the message is not printed if the
combination A=1 AND B=2 is NOT satisfied.
The programs accomplish the same task, but the programmer's thinking is
just a bit different. And although it might seem confusing to use negated
AND statements at this time, the fact that such statements can simplify pro-
grams makes it worth your effort to get negated logic straightened out in
your mind.
Note the parentheses enclosing the AND conditionals in line 20 of Ex-
ample 10-5. The parentheses are essential in this instance because, you
might recall, all logical operators carry the same level of priority and are
executed strictly from left to right. Using the parentheses forces the system
to consider the A=l AND B=2 statement before it negates the result with
the preceding NOT expression. Logic statements, like math expressions, give
priority to expressions within parentheses. If the parentheses in this example
were to be omitted, the NOT expression would apply only to the A=l
portion of the AND statement, and the overall result would be quite
different.
EXAMPLE 10-3a
EXAMPLE 10-6
EXAMPLE 10-7
Literally speaking, line 20 says: If A=l AND B=2 at the same time,
THEN go to 40; ELSE (otherwise) go to 10. Using the ELSE expression
eliminates the need for a separate GOTO 1~ statement line.
EXAMPLE 10-8
10 CLS: A=l
20 IF A<10 THEN 30 ELSE END
30 PRINT A: A=A+l: GOTO 20
211
212 Ch.10 An Introduction to Logical Operations
its value. Whenever the conditional in line 20 is no longer satisfied (the value
of A is equal or greater than 10), the ELSE expression comes into the
picture and the program is ended.
Here is a tricky little game that illustrates the use of all the logical
operators described in Section 10-1. As usual, you can expect to find
some new ideas of other kinds tucked into the program.
The game requires two players. One player selects a combination
of numbers and letters, and it is up to the other player to fmd the
exact combination. Clues provided through the course of the game
give especially sharp players a better chance of finding the combina-
tion in a short time.
The combinations, for the sake of simplicity, are limited to a
number between I and 9, followed by a letter between A and D. No
other combination works-and you can be sure the program will let
you know that.
So the first player, called the selector, enters a number between 1
and 9 and a letter between A and D. That player then clears the
screen and lets the guesser go to work. The program keeps a running
tally of the number of invalid or incorrect guesses. After entering a
valid guess, the guesser is told whether either of the two characters
is higher or lower than the one hidden away in the system's memory.
The catch is that the machine doesn't tell the player which one of
the two characters is too low or too high.
The game goes along until the guesser finally hits upon the right
combination. The final tally is that player's score. The player's then
change around their roles, and the whole thing is run again. The
player ending up with the lowest tally is the winner.
Figure 10-1 is the flowchart for this high-low guessing game.
When it is started, the player selecting the "secret" combination sees
the screen filled with instructions. It looks something like this:
SELECTOR:
ENTER:
1. A NUMBER BETWEEN 1 AND 9
2.ACOMMA
3. A LETTER BETWEEN A AND D
EXAMPLE - - l,C
N
...
Co)
(AND MAKE SURE YOUR OPPONENT ISN'T LOOKING OVER YOUR SHOULDER)
HOLY COWl
PLAYER:
TIME FOR YOU TO GO TO WORK.
Sec.10-3 A "High-Low" Game Using Logical Operators 215
EXAMPLE - - 1.C
Once you see what the game is supposed to do and how the flow-
chart displays the operations, you shouldn't have too much trouble
following the program itself. With that in mind, there is little more to
the analysis of the program than pointing out the new or critical
features.
Lines 5 through 55 in the program in Example 10-9 comprise the
SELECT HEADING and ENTER COMBINATION blocks on the
flowchart. There is nothing new among those program lines.
Lines 60, however, includes several points of special interest.
First note that it represents the first VALID conditional on the flow-
chart. The job of this line is to determine whether or not the selector
has entered a valid combination of terms.
In line 60, the expression N<>INT(N) is a technique that tests
number N to see whether or not it is an integer. This particular ex-
pression is satisfied if N is not an integer.
Then there is the expression N <1, followed shortly thereafter by
N>9. The first checks for N values less than 1, while the second
checks for N values greater than 9. What we are doing here is check-
ing for N values that are invalid because they fall outside the range I
through 10.
EXAMPLE 10-9
100 CLS:PRINT//PLAYER://
110 PRINT//TIME FOR YOU TO GO TO WORK.//
115 PRINT//FIGURE OUT THE RIGHT COMBINATION OF//
120 PRINT//A NUMBER BETWEEN 1 AND 9 AND A LETTER BETWEEN A AND D.
300 PRINT"yOU MESSED UP THE ENTRY. THAT WILL COST YOU A TRY//:GOT
0350
310 PRINT//SORRY, SOMETHING IS TOO LARGE//:GOTO 350
320 PRINT//SORRY, SOMETHING IS TOO SMALL//:GOTO 350
350 PRINT:PRINT:INPUT"HIT THE ENTER KEY TO TRY AGAIN//;X$
360 L=L +1: GOTO 160
And fmally, line 60 checks the value of N$ "D". Recall that inequalities
used with string expressions indicate the relative position of the expres-
sions in the alphabet. So if N$ "is greater than" D, it means it comes after
D in the alphabet.
Line 60 thus checks the validity of the selector's letter entry by making
certain it is only one letter and it is a letter between A and D.
Now all of these inequality functions are tied together by OR operators.
In other words, the entire statement is true if anyone of the individual
inequalities is true. All of the inequalities, however, test for negative con-
ditions-all the relevant invalid conditions. For that reason, the whole set of
conditions is negated by the NOT expression preceding them.
Putting it all together, line 60 is satisfied if not a single one of the terms in
the expression is true. If N is less than 1, for example, the line is NOT
true. If N$ has more than one character in it, the line is NOT true, and so on.
If line 60, as a whole, is true, THEN control goes down to line 100. Other-
wise, operations pick up at line 70.
Assume for the time being that line 60 is not satisfied. The selector's
entry, in other words, has something wrong with it. That being the case,
lines 70 through 95 take care of the necessary INVALID MESSAGE and
READY operations, ultimately returning control back to line 10. At line
10, the selector has a chance to try entering a valid set of characters.
Lines 100 through 150 take care of the PLAYER HEADING, its corre-
sponding READY conditional, and the INITIALIZE TRY NUMBER blocks
on the flowchart.
Lines 160 through 170 print the player's try number (line 160) and
prompt the player to enter the guess (line 170). The guess combination
is assigned numerical variable M and string M$.
Line 210 checks the guessed entry for validity, using the same criteria
applied to the selector's entry. Note, however, that the OR expressions
in line 210 are not negated by a NOT operator as is done in line 60. Line
210 actually checks for the bad entries and, if satisfied, calls line 300 to
print out the INVALID MESSAGE.
Lines 220 and 225 check to see whether either of the guessed characters
is greater or less than the selected values. In line 220, for instance, some-
thing is wrong (a bad guess) if M>N, M$> N$, or both.
The remainder of the program includes no new ideas. You should be
able to analyze it for yourself, using the flowchart as a general guide.
EXERCISES
10-1 Account for all conditions for variables A and B that satisfy (make true)
the following statements:
(a) IF A=0 AND 8=1 THEN ...
Ch. 10 Exercises 219
10-2 Why is the statement IF B=0 AND B=l THEN ... nonsense?
10-3 Write BASIC IF . . . THEN conditional statements for the following
inequalities:
(a) O';:;;A';:;; 10
(b) O<A';:;; 10
(c) O';:;;A < 10
(d) O<A<10
10-4 Describe in literal terms the meaning of the following BASIC statements:
(a) IF N=INT(N) AND N>0 THEN .. .
(b) IF N=INT(N) OR N>0THEN .. .
(c) IF SIN(N»0 THEN ...
A First Lool~
at
Data Processing
220
Sec. 11-1 Reading Lists of Numerical Data 221
such. You have seen very little in the way of processing information
taking the form of names, dates, serial numbers, and any other
meaningful descriptive expressions that are not limited to numerical
quantities or simple string expressions.
Much of the work remaining in this book deals with processing
lists of information-information of all kinds. The procedures might
appear to be cumbersome and restrictive in the early going here, but
you will find things smoothing out as you go along.
That is a complete DATA line. It has a valid line number (100), the
DATA statement, and a list of data following it. There are six items
in the data list here. There can be any number of items in the list,
just as long as each item is separated from the preceding one by a
comma. (Some personal computer systems have a limit on the num-
ber of items in a single DATA line. Check your owner's manual for
details.)
Now the unusual thing about the DATA item list statement is
that the computer does nothing whenever it encounters the state-
ment in a program. It is treated much as a REM statement. And what
222 Ch. 11 A First Look at Data Processing
EXAMPLE 11-1 a
10 DATA 2,4,8,16,32,64
20CLS
30 FOR N=1 TO 6
40 READ D
50 PRINT D
60 NEXT
70 END
This is a rather simple program. When you RUN it, you will see the list of
numbers in the DATA line printed vertically on the screen:
2
4
8
16
32
64
READY
>
Note the presence of DATA item list in line 10, and its associated READ
variable name in line 40. Since the item list is composed entirely of nu-
merical values, the variable name for the READ statement must be a numer-
ical variable-D in this case.
Now notice that the FOR ... NEXT combination of statements between
lines 30 and 60 cause the READ statement to be executed exactly six times.
The DATA list, in other words, is read six times-one time for each item in
the list.
Furthermore, each time the item list is read in line 40, the corresponding
value of D is printed by the statement in line 50. The FOR ... NEXT loop
thus causes the program to READ and PRINT six items in the DATA
listing-no more, and no less.
Sec. 11-1 Reading Lists of Numerical Data 223
Looking at the situation in a more general way, the first time the FOR ...
NEXT loop is executed, the READ statement picks up the first item in the
DATA list. The second time the READ statement is executed, it picks up
the second item in the DATA list. The third time READ is executed, it
picks up the third item; and so on to the end of the process.
Principle. Items in a DATA item list are always read from left
to right, one at a time, each time the corresponding READ
statement is executed.
EXAMPLE Il-lb
20CLS
30 FOR N=l TO 6
40 READ D
50 PRINT D
60 NEXT
70 END
80 DATA 2.4,8,16,32,64
Run this program, and you will fmd that the results are exactly the same as
running Example I 1-1 a-even though the DATA item list statement follows
an END statement!
Or try this:
224 Ch. 11 A First Look at Data Processing
EXAMPLE II-Ie
20CLS
30 FOR N=1 TO 6
40 READ D
45 DATA 2.4,8,16,32,64
50 PRINT D
60 NEXT
70END
The DATA item list can go anywhere, even in the middle of a FOR ...
NEXT loop.
EXAMPLE ll-Id
10 DATA 2.4,8
15 DATA 16,32,64
20CLS
30 FOR N=1 TO 6
40 READ D
50 PRINT D
60 NEXT
70END
In this example, the item list from previous examples is split between two
separate DATA statements. The overall result is the same, however. Reading
begins with the fust item in the DATA line carrying the lower line number
and works, one item at a time, through the fmal item in the higher-numbered
DATA line.
EXAMPLE 11-1e
10 DATA 2,4.8
20CLS
30 FOR N=l TO 6
40 READ D
50 PRINT D
60 NEXT
70 END
80 DATA 16.32.64
The results of running this example are no different from any of the other
examples cited so far.
EXAMPLE 11-2
10 CLS
20 PRINT "STOCK NO ...... QTY IN STOCK ..... COST ..
30 FOR N=1 TO 5
40 READ S: READ Q: READ C
226 Ch. 11 A First Look at Data Processing
50 PRINT s,a,c
60 NEXT
70 END
100 REM ** DATA **
110 DATA 100,20,2.55
111 DATA 101,220,3.95
112 DATA 103,0,1.85
113 DATA 104,11000,1.35
114 DATA 110,23,6.95
This program is divided into two distinctly different sections: the main
programming section in lines 10 through 70, and the data section in lines
100 through 114. Upon running the program, you should see something like
this on the screen:
The program contains five separate DATA lines, each containing three
items. The job could be done with a single DATA line containing 15 items,
but there is a method to the madness. Note that each DATA line contains a
stock number, quantity in stock, and corresponding cost-in that order.
Whenever the stock listing changes for one item, you have to alter only one
DATA line. If the information were all contained in a single DATA line, you
would have to edit the line or rewrite the whole thing.
Even though the data are broken up into five different lines, the items are
still read in sequence, beginning with the first item in line 110 and ending
with the last item in line 114. So how are the stock numbers, quantities, and
costs kept separate and properly lined up on the screen?
To shed some light on the answer to that question, notice that line 40 is
made up of three separate READ statements, each assigning a different
variable name to the items they read. Each time the FOR ... NEXT loop is
executed, then, line 40 reads three different DATA items in succession.
The first time the FOR ... NEXT loop is executed, for example, READ S
picks up the first item in DATA line 110, READ Q picks up the second item
in that DATA line, and READ C picks up the third item. So there they are-
just like J-2-3. On that first pass through the FOR ... NEXT loop, S=100,
Q=20, and C=2.55
Line SO merely calls for a printing of the three values picked up by line
40.
Sec. 11-2 Reading Lists of String Data 227
On the second pass through the FOR ... NEXT loop, line 40 picks up
values for the next three items in the DATA listing-the items from DATA
line 111. And on the third pass through the loop, line 40 picks up the three
items, in sequence, from DATA line 112.
This operation continues, reading the DATA listing three items at a time,
until the FOR ... NEXT loop has cycled five times, and the program is
ended.
The loop is executed five times, and there are three READ statements in-
cluded in each execution. That figures out to a total of 15 READ opera-
tions. That figure lines up exactly with the total number of items in the
DATA listing.
If you are following this discussion, you might be seeing a bit ahead
toward some of the exciting possibilities inherent in DATA/READ state-
ments. And you might be formulating a few questions concerning ways to
alter the DATA listings as well. Before pushing the discussion further, how-
ever, take a moment to consider something else that" can be done with this
program.
Suppose that you revise line 20 to read
50 PRINT S,Q,C,Q*C
The general principles for structuring and applying DATA and READ
commands to numerical items carryover to string items. The most
important difference-a rather logical one, however-is that the vari-
able name associated with the read statement must be a string
variable.
Getting down to cases right away, here is a computerized "date
book."
228 Ch. 11 A First look at Data Processing
EXAMPLE 11-3
1(J ClS
2(J PRINT"NAME" ,"ADDRESS" ;:PRINT TAB(401"PHONE"
25 PRINT
3(J FOR N=1 TO 4
40 READ N$,A$,T$
5(J PRINT N$,AS;:PRINTTAB(4(JIT$
6(J NEXT
7(J END
100 DATA AlICE,123 ClEARVIEW,221-4567
11(J DATA BETTY,16 E. MAIN,221-899(J
12(J DATA CARlA*,452 CENTRAL APT.7,556-7734
130 DATA DORIS,1556 STATE,433-8876
So you could have the system print 452 CENTRAL, APT.7 if DATA
line 120 is revised to read
EXAMPLE 11-4
10 DATA 2,3.4,5,6,7,8,9,10,J,Q,K,A
20CLS
30 FOR NC=1TO 5
40 FOR N=1 TO RND(13):READ P$:NEXT
50 PRINT TAB(25)P$;"";
60 RESTORE:NEXT
70 FOR L=1 TO 15:PRINT:NEXT
80 INPUT X$:GOTO 20
The DATA line, line 10, is the source of string items representing the
available cards. The DATA line is read five times in succession as indicated
by the FOR ... NEXT loop running between lines 30 and the end of line
230 Ch. 11 A First Look at Data Processing
60. Of course, all the statements appearing between those two points are
executed five times for each complete deal of the cards.
Line 40 is the one responsible for selecting the card and reading its value.
The first statement in that line sets it up for counting between I and some
random number between I and 13. The NEXT statement for this loop is at
the end of line 40. The READ statement falls right in this FOR ... NEXT
loop.
Suppose the value of RND(I3) in line 40 happens to be 5. That means
the READ statement reads the first five items in the DATA list, the card
designations between 2 and 6. The values are sequentially assigned to P$,
and P$ retains the last-read value (6 in this case) when the FOR ... NEXT
loop in line 40 is done.
In effect, line 40 assigns one of the DATA items to P$. The assignment, of
course, is a random one.
Line 50 then causes the value of P$ to be printed along the top of the
screen and near the center. The quotes enclosing a space merely places a
nice space between the cards as they appear on the screen.
Line 60 is very important to the entire discussion of DATA/READ pro-
gramming. The RESTORE statement is a new one as far as we are con-
cerned, so it requires some special explanation.
Recall that a DATA line must be read in sequence, from left to right.
Furthermore, the number of times a READ statement is executed must not
exceed the number of items in the DATA listing. If it does, the machine
generates an out-of-data error signal. READ operations do not automatically
return to the first item after the last one is read.
In this particular program, the same line of data must be read five dif-
ferent times-one time for each card to be dealt. What the RESTORE state-
ment does is set the READ operation back to the first item in the DATA
list.
Actually, you have been using a RESTORE operation all along without
knowing it. Every time you begin a program with a RUN command, any
READ operations are automatically set to the first item in the corresponding
DATA list.
So the READ operations are reset to the first item in the DATA line at
line 60. The NEXT statement at the end of that same line loops operations
back to line 30 to pick up another randomly selected DATA item.
Operations continue cycling around in this fashion until the values of five
cards are displayed on the screen. After that, line 70 carries the cursor down
to the bottom of the screen. (Having a question mark after the list of cards
Sec. 11-3 Combining Numerical and String Data 231
Numerical and string data can be mixed together in the same DATA
line as long as the corresponding READ statements assign the correct
type of variable. The numerical items in the DATA list, if they are to
be manipulated mathematically, must be read by means of READ
numerical variable. String items must be read with a READ string
variable statement.
Incidentally, numerical values that are never manipulated mathe-
matically can be treated as either a numerical or string item.
Here is an example of a program combining numerical and string
variables in the DATA lines:
EXAMPLE 11-5
This program prints out a typical mail-order list. The heading specified in
line 10 shows columns of data for quantity, stock number, cost per unit,
and total cost for each item ordered. The data, listed in lines 101 through
105, includes the quantity, stock number, and cost per unit.
The data are printed by the statement in line 40. Q is a numerical variable
232 Ch. 11 A First Look at Data Processing
Lo! the dollar values are lined up so that they are neater and far
less confusing. Again, this notion of using field specifiers is not
directly related to the DATA/READ process, and it can be used any-
where it is necessary to line up numbers having decimal points in
them.
EXAMPLE 11-6a
.END
Example 11-6a contains no FOR ... NEXT loops. The program first
reads N$, the individual's name. But if the first item in the DATA listing
happens to be END, line 20 shows that the program itself is to be ended.
So the program will print out the data (name, address, and phone num-
ber) until it reaches the DATA line in line 104. That line begins with the
string expression END-and by line 20, seeing END as N$ stops the program.
In other words, this program cycles until it reaches a DATA line con-
taining an N$ expression END. There is no limit to how many times the
program can cycle and, more important, it is possible for the user to add
new names, addresses, and phone numbers by:
1. Writing over the END expression in line 104 and replacing it with a
new DATA line.
2. Adding as many new lines of data as desired.
3. Terminating the new DATA listing with DATA END.
If you run this example as shown, you should see something like this on
the screen:
This time the program runs until it lists the three original names as well
as the three new ones. It is an open-ended program that continues looping,
reading data, and printing it, until it sees N$="END".
Incidentally, you might have noticed the null-string address in line 104.
Apparently, Sammy's address isn't known. Even so, it must not be totally
omitted, else the reading scheme will get behind by one item listing; doing
terrible things such as putting Sammy's phone number in the ADDRESS
column, Gretchen's name in place of Sammy's phone number, and so on to
the end of the DATA listing. Entering the null string in place of Sammy's
unknown address causes the computer to leave a blank in the appropriate
space on the screen.
Even though you now have some insight into preparing DATA lists that
can be expanded at any later time, you might fmd the process a bit awk-
ward. One way to simplify matters is by entering all the new information
on a single DATA line. For example, you could add the three new names,
addresses, and phone numbers this way:
The idea is to enter the data on one line, bearing in mind that the READ
scheme has no regard at all for the line numbers. In this case, all that's
necessary is that the data be presented in the right sequence and that each
item be separated from the preceding one by a comma. At least you don't
have to type in a new line number and the statement, DATA, for each new
entry. That simplifies the task somewhat.
It's a good idea to put the END "name" on a separate line,however. That
way you know where to begin adding new DATA listings at some later time.
Sec. 11-4 Expandable Data Lists 237
EXAMPLE 11-6b
Running the program in this example, you see this sort of display on the
screen:
Striking the ENTER key in response to this prompting message, the screen
is cleared and the new display looks like this:
READY
>
The next time you run the program, the entire list of names appears on the
screen. And if you strike the ENTER key to add new data, the prompting
message will read
It's one way of making the task of entering new DATA lines somewhat
simpler and less prone to operator errors. The only drawback is that each
set of data-name, address, and phone number-must be entered on separate
program lines, and those lines must be presented in succession. (There are
ways to get around this particular drawback, but the techniques are beyond
the scope of the prese~t discussion.)
The next step in the DATA/READ scheme is to see how the data
can be manipulated and reorganized, doing something more than
simple listings and a bit of mathematical manipulation. That is the
subject of the next chapter.
EXERCISES
11-1 How many READ operations must be performed to read all the data in
the following DATA lines?
(a) DATA 2,4,6,8,10
(b) DATA 1.2,3.14,1,000,10.24
(c) DATA MIKE, J, SAM, L,EDWARD, J, PAGE 3
(d) DATA MIKE,20, SAM L. -- 200, J. PAGE
11-2 The DATA line in Example ll-la has six items in it. Explain how all six
are read with a single READ D statement in line 40.
11-3 How is the statement READ A:READ B: READ C$ operationally dif-
ferent from READ A,B,C$?
240 Ch. 11 A First Look at Data Processing
241
242 Ch.12 Putting DATA and READ to Work in Larger Programs
where N$ and C$ are the string variables for student name and course,
and Hand G are the numerical variables for course hours and grade.
In the process of composing the program, you will have to estab-
lish the form of several mathematical equations. Perhaps the total
number of course hours for a given student seems important. Getting
that figure is a matter of summing all the H values for a given student.
Let's call the total class hours HT.
Although you might not consider it important to display the HT
value as such, it is required for calculating the point-hour ratio. That
figure is generally computed by the equation
EXAMPLE 12-1
The items in each data line are presented in a specific order as described
earlier: student name, course, course hours, and grade. There is, however, no
rationale behind the order of the DATA lines as they are presented here-
the items for SMITH E. could appear first instead of last. In fact, the DATA
lines for SMITH E. could be scattered throughout the list. You are working
with something that is technically known as a random data file.
The operator will be able to enter data in any order, following only two
rules that you, as the programmer, are imposing. First, the four items for
each data en try must be written in the specified order, and second, each list
of four items must be assigned a separate line number. The latter "rule" is
necessary only because of the nature of one of the tasks described later in
this section.
The first task available to the user is a simple listing of the data.
This is the sort of job represented by most of the DATA/READ
examples in Chapter 11. The subroutine and associated flowchart for
this particular task appear in Example 12-2 and Fig. 12-1.
EXAMPLE 12-2
INITIALIZE
LINE
COUNT (LI
RETURN
245
246 Ch.12 Putting DATA and READ to Work in Larger Programs
The essential elements of this subroutine begin with the READ NAME
(N$) block on the flowchart. If the "name" happens to be END, the com-
puter leaves the subroutine and returns to the master program (which you
haven't written yet). Otherwise, program control goes to READ C$,H,G;
and immediately after that, the computer prints N$, C$, and G-the stu-
dent's name, course, and grade.
Now note from the flowchart that the subroutine reads all four items on a
given DATA line, but prints only three of them. The course hours (H) is
read, but not printed. It must be read, however, in order to keep the item
pointer advancing to the appropriate place in the DATA listing.
So basically, the subroutine first looks for an END statement that indicates
the end of the data listings. If it doesn't fmd END, it reads the remaining
three items in the DATA line and prints three of the items on the screen.
There is nothing really new as far as this part of the job is concerned.
The remaining steps in the flowchart in Fig. 12-1 have to do with dis-
playing no more than 10 lines of information on the screen at one time.
Displaying a very long list of data on the screen would be a meaningless
operation as far as the user is concerned. Without separating the display into
blocks of 10 listings, the whole list would scroll by so rapidly that no one
could read it.
The ftrst operational step on the flowchart is thus one that initializes a
line counter (L). Every time the computer displays a new line of data, this
counter is advanced by the block labeled INCREMENT L. The conditional
block following INCREMENT L then checks the number of lines presently
on the screen. If the number of lines is less than 10, the N output carries
operations back up to READ NAME (N$), where another READ/PRINT
cycle is initiated. On the other hand, if there are 10 lines of information
already presented on the screen, the system stops reading data and outputs a
"MORE" MESSAGE. And if the user wants to see another block of informa-
tion, the MORE conditional is satisfted, the line count is initialized, and the
READ/PRINT cycles begin from the top of the screen.
The subroutine listing in Example 12-2 follows the flowchart in
a rather straightforward way. Carefully compare the two, making
certain you understand what they do and how they do it.
Enter the subroutine WHOLE LIST as shown in Example 12-2
and then write a temporary test routine:
EXAMPLE 12-3
10 CLS:GOSUB 100
15 PRINT: PRINT "END OF LISTING"
20 END
Sec. 12-2 Subroutines for the STUDENT COURSE/GRADE Program 247
Upon entering RUN, line 10 in this test routine clears the screen and sends
operations down to the WHOLE LIST subroutine. The screen should then
look like this:
ADAMS R. B 101 3
ADAMS R. E 301 3
ADAMS R. M201 3
JONES S. B 101 4
JONES S. A202 4
JONES S. M201 3
JONES D. B 101 0
JONES D. M101
JONES D. E 301 1
SMITH E. B 101 3
Sure enough, the first 10 DATA listings are shown on the screen. Every-
thing is there in each case except the number of hours per course. The
"MORE" MESSAGE near the bottom of the screen tells the operator there
are more data to be seen.
So striking the enter key resumes the listing and, in this case, terminates it
as well.
SMITH E. M101 4
SMITH E. E 301 2
END OF LISTING
READY
>
EXAMPLE 12-4
Upon running this subroutine, the system fIrst requests a student's name
from the operator. This operation is reflected. in the INPUT NAME (M$)
block on the flowchart and line 210 of the subroutine itself.
The system then prints the appropriate headings, including the specifIed
student name, and then initializes the relevant elements for calculating the
student's overall point-hour ratio.
The next step is to read the fIrst name in the DATA listing. If that fIrst
name isn't an END statement, the program calls for reading the remaining
items in the DATA line-C$, H, and G.
The next step is an important one to this pa~;::ular task: The system com-
pares the student name in the DATA listing (N$) with the student name
entered at the beginning of the subroutine (M$). If indeed they are the
same, the system compiles the relevant terms for the point-hour ratio and
then prints the course, hours, and student grade. The program then returns
to READ NAME (N$), where the computer looks at the next name on the
list.
The program also returns to READ NAME(N$) if the two names don't
match at the N$=M$ conditional block.
So the system continues looking for names that match the one entered by
the operator, printing out the relevant information whenever the names are
the same. Things change only when READ NAME (N$) finds the END state-
ment at the end of the DATA listing. That operation satisfIes the END
conditional statement, and the next conditional determines whether the
computer found any of the specifIed name. If not, it prints a THIS NAME
NOT ON FILE and returns to the master program. If, on the other hand,
the system found some matching names, the system calculates the student's
point-hour ratio by CH/HT, prints the fIgure, and returns to the master
program.
250 Ch.12 Putting DATA and READ to Work in Larger Programs
EXAMPLE 12-5
WHAT NAME?
Suppose that you respond by typing and entering SMITH E. The resulting
display looks something like this:
SMITH E.
COURSE HOURS GRADE
B 101 4 3
M101 4 4
E 301 4 2
POINT-HOUR RATIO=3
END OF LISTING
READY
>
And there you have it-the course schedule, grades, and overall PHR for a
student named SMITH E. Try running the test routine for all the students in
your data me: ADAMS R., JONES S., JONES D., and SMITH E.
RALPH F.
COURSE HOURS GRADE
END OF LISTING
READY
>
EXAMPLE 12-6
Notice that the flow of operations is pretty much the same as the LIST
NAME subroutine. This one is a bit simpler because it doesn't include the
point-hour algorithm.
The program first prompts the operator to enter a course designation.
That expression is assigned to string variable M$. As usual, the system looks
at the name N$ in the DATA listing to see if it represents the end of the
data. If not, the system reads C$, H, and G (block READ C$, H, G on the
flowchart) and checks for a match between the specified course number
(M$) and the course number at hand in the data (C$). If there is a good
match, PRINT N$ prints the student's name and operations return to READ
NAME (N$) to look for the end of the DATA list or another match between
C$ and M$.
The purpose of the counter, E, is to tell whether or not the computer
fmds any listings at all for the specified course. This counter is set to zero
early in the subroutine [at INITIALIZE COUNTER (E)] and incremented
whenever the system fmds a course match and prints the corresponding
student name (at INCREMENT COUNTER).
When the computer reaches the end of the listing, as determined by the
252 Ch.12 Putting DATA and READ to Work in Larger Programs
RETURN
EXAMPLE 12.7
10 CLS:GOSUB 300
20 PRINT: PRINT "END OF LISTING"
30 END
Then RUN the program. You should first see the prompt message WHAT
COURSE? Respond by entering one of the course designations, say B101.
The resulting display looks like this:
COURSE: B101
ADAMS R.
JONES S.
JONES D.
SMITH E.
END OF LISTING
READY
>
Run the subroutine for each of the course designations in the DATA list-
ing: B101, M201, E301, A202, and M10l. In each case you should see a
listing of the students taking the specified course. Finally, try entering a
course designation that is not in the me-maybe something like X2, for
instance. The display will respond this way:
COURSE: X2
END OF LISTING
READY
>
Hang in there, there is just one more subroutine to go. It's a short
one that lets the operator enter more data to the DATA listing. You
have already studied such a routine in Chapter 11, so there is no need
for extensive commentary on it. The flowchart and subroutine listing
for this NEW LIST are shown in Fig. 12-4 and Example 12-8.
EXAMPLE 12-8
y
END
The program simply counts the number of DATA lines, and upon rmding
the END statement in the data, the system prints the line number contain-
ing that END statement. That is where the next line of data is to be placed.
The line counter, in this case, is initialized at 1001, because that is the first
line of data in the DATA listing.
EXAMPLE 12-9
Consult your DATA listing or Example 12-1, and you will find that
DATA END is at line 1013.
Notice that the NEW LIST subroutine does not return to the master pro-
gram. It concludes with an END statement that puts the computer into its
command mode. Why is this done? It is done so that the operator can begin
typing in new DATA lines with no further hassle. Try it.
That set of new listings adds a new student to the fUe, SCHULTZ X., and
gives ADAMS R. an additional course. To see if these new listings have in-
deed been added to the DATA listing, either do a LIST command to display
lines 1000 through 1015, or write the test routine in Example 12-3 and
run it.
The master program does little more than automate the subroutine-
selection process and, at the same time, prompt the operator to do
things right. Basically, the master program first prompts the operator
to select one of the four available tasks: (1) COMPLETE LISTING,
(2) STUDENT RECORD AND PHR, (3) COURSE ROSTER, or (4)
INPUT NEW LISTINGS.
After the operator selects one of the tasks, the program sends
operations to the appropriate subroutine. And after the subroutine
is executed, control is usually returned to the master program, where
the END OF LISTING message is generated. The only exception to
this returning process is the NEW LISTING subroutine, which, you
recall, concludes by shifting the system over to the command mode.
After printing END OF LISTING, the system then wants to
know if the operator desires the same task to be run again. If so, the
system runs the same subroutine as before. If not, the operator is
again presented with the four choices.
The master program for doing this work is pre.sented in Example
12-10.
256 Ch.12 Putting DATA and READ to Work in Larger Programs
EXAMPLE 12-10
Enter the program and do a RUN. You should be greeted with this display.
1 -- COMPLETE LISTING
2 -- STUDENT RECORD AND PHR
3 -- COURSE ROSTER
4-- INPUT NEW LISTINGS
READ N$,D$,P$,A
258
Sec.12-6 Programs for CHECKBOOK TRANSACTION 259
EXAMPLE 12-11
Entering and running this portion of the program makes the display on
the screen look something like this:
WHICH TASK:
1 - NEW LISTINGS
260 Ch. 12 Putting DATA and READ to Work in Larger Programs
The display is the result of executing lines 20 through 27 and the INPUT
statement in line 28. At this point, however, the program "blows up" if
you try entering one of the numbers-the subroutines called by these
numbers do not yet exist in the computer's program memory.
This program is quite similar to the master program for the STUDENT
COURSE/GRADE version in Example 12-10. In principle, they're iden-
tical. Example 12-11 has a couple of lines that require special attention,
however.
Line 15 in Example 12-11 specifies two field variables. They aren't used
in the main program here, but they are used in all the subroutines. So
rather than using separate field-specifying statements in each subroutine,
they are established, once and for all, early in the master program.
Once these printing fields are established, they can be called at any later
time by statements such as PRINT USING R$ and PRINT USING S$. In
the first instance, the R$ field specifier forces a numerical value to have a
plus sign in front of it, followed by character spaces for four numerals, a
decimal point, and two more numerals. In the context of dollar values, the
R$ specifier in line 15 can print any dollar value from +0.00 to +9999.99
dollars.
The S$ field specifier in the second part of line 15 accomplishes the same
thing, but without preceding the printing with a plus sign.
Line 30 contains an ON ... GOSUB line numbers statement. There is
nothing unusual about the statement in itself-you've already studied it in
an earlier chapter. What is somewhat different from anything described
earlier is the fact that the last three subroutine lines specified in the state-
ment are identical. What are the implications of that fact?
Well, first notice that the operator sets the value of T in response to the
INPUT statement in line 28. The numerical value of T determines which one
of the five possible tasks will be performed.
So if the operator sets T equal to 1, the ON ... GOSUB statement in line
30 sends control to a subroutine beginning at line 100. If the operator
selects task number 2, T is equal to 2, and tne ON ... GOSUB statement
turns over program control to a subroutine beginning at line 200. But if the
operator selects task 3, 4, or 5, line 30 sends program control to the same
subroutine-the one starting at line 300.
There must be something about tasks 3,4, and 5 that make them quite
similar-so similar, in fact, that they can be run by the same subroutine.
Apparently, tasks 1 and 2 are not sufficiently similar to warrant using the
same subroutine for running them.
Now it's time to look at the subroutines. Unfortunately, it is rather diffi-
cult to describe the subroutines in separate, bite-sized pieces. The difficulty
Sec. 12-6 Programs for CHECKBOOK TRANSACTION 261
arises from the fact that they are written more for overall efficiency than
ease of description.
Subroutines 100 and 200, shown in Example 12-12, are rather different
in many respects; but it is hard to understand some of the statements in
subroutine 100 without referring to 200, and in fact, subroutine 200 cannot
even be run without having access to 100.
EXAMPLE 12-12
The master program calls line 100, NEW LISTING, whenever the operator
selects task I-NEW LISTINGS. This subroutine merely counts the number
of DATA lines in the me, and prints out the line number for the next line
of data. The idea is to tell the operator where to begin tacking on a series
of new checkbook transactions.
The DATA listings will begin at line 1001, and for that reason the line
counter is initialized at 1001 in line 110. As the program reads through the
data, L is incremented, and this line-counting loop between lines 120 and
130 continues until N$ reads END in the data.
When N$ is read as END, the IF ... THEN conditional statement in line
120 sends program control down to line 140. And that's where subroutine
200 becomes relevant. To get through this analysis, it is a good idea to
ignore line 140 for the time being, assuming it is not satisfied and that the
system does not break out of subroutine 100.
Assuming line 140 is not satisfied, program control then goes to line 150,
and that line is responsible for displaying BEGIN NEW LISTING, followed
262 Ch.12 Putting DATA and READ to Work in Larger Programs
You can find a LEFT$ statement in line 240. In this case it is used as
part of an IF ... THEN conditional statement. IF the first five characters of
N$ is equal to DEPOS, THEN go to line 250. DEPOS, you see, is a trun-
cated version of DEPOSIT; and whenever this string appears as the N$ item
in a DATA line, it means the user made a deposit to the checking account.
This is quite a significant fact, because it means the amount of the current
transaction (a deposit) is added to the balance rather than subtracted from
it. See line 250 called by satisfying the conditional statement in line 240.
You will also fmd two LEFT$ statements in line 270. These truncate the
transaction and recipient designations to make certain everything fits onto
the screen. Without using the LEFT$ statements in this way, a long recipient
name could shove the amount and balance figures far to the right and off
the screen. (Actually, those figures would "fold over" to the left side of the
screen; but that would be messy, too.)
Do you remember the filed specifiers listed in line 12? You can fmd
references to them in lines 245 and 250. Aside from making certain the
dollar amounts in the AMOUNT and BALANCE columns line up neatly, the
use of R$ in line 250 automatically inserts a plus sign at the beginning of
AMOUNT figures for deposits. The operator does not have to specify +
amounts for deposits and - amounts for checks written against the account.
That's nice, isn't it? It's up to you to figure out exactly how it
works, though.
The next step in this analysis is to look at the subroutine that
handles tasks 3, 4, and 5. Recall that the purpose of these tasks is to
list relevant checkbook information regarding a certain, user-specified
criteria. Task 3, for instance, lists all the register information and
balances for any specified type of transaction, including DEPOSIT
and valid check numbers. Task 4 lists the same kind of information,
but according to a certain date specified by the user. And finally,
task 5 lists the register information according to the name of the
recipient.
These three tasks are basically the same: Given a certain criterion,
list all register information related to that criterion. It really isn't a
very difficult task, either. The subroutine, FIND, is given as Example
12-13.
Sec. 12-6 Programs for CHECKBOOK TRANSACTION 265
The first major task of this subroutine is to sort out which one of
the three tasks (3, 4, or 5) is being run. This is necessary because the
three tasks attempt to match three different variables with the DATA
items. Task 3 looks for a match between a transaction designation
and an N$ item, task 4 looks for a match between a date and a D$,
and task 4 looks for a match between a specified recipient designa-
tion and a P$ item in the DATA listing. Lines 305 through 320
handle the job of getting the user's task-oriented variable into the
works.
EXAMPLE 12-13
This part of the job begins with the ON ... COTO statement in line 305.
A numerical value is assigned to variable T way back in the first part of the
master program, when the operator selects a task. This FIND subroutine,
however, is called only when T is equal to 3,4, or 5. The T-2 expression in
line 305 reduces these numbers to 1, 2, or 3, thus making them fit the
COTO line numbers statement. If you were to write this statement as ON T
266 Ch.12 Putting DATA and READ to Work in Larger Programs
GOTO ... , you would have to insert two" dummy" lines in front of line
designations 310,315,320.
The ON . . . GOTO statement in line 305 thus sends program control
to one of three INPUT lines, depending on the designated task. And
those lines request the appropriate kind of criteria for the search: WHAT
TRANSACTION, WHAT DATE (MONTH-DAY), and WHAT RECIPIENT,
respectively.
When the operator responds to one of these INPUT statements, the re-
sponse is assigned to string variable T$. T$ thus carries the criteria for the
matching operation throughout the entire subroutine.
That match-criteria variable-representing the type of item the computer
is going to seek out-is truncated to its first five characters in line 325.
Lines 330 through 334 merely print the headings for the information to
be listed on the screen:
After all that, the reading operations finally begin at line 340. After
checking for the END statement in the DATA list, and assuming for the
time being that the statement is not satisfied, the computer reads the re-
maining items in the DATA line, D$ (date), P$ (recipient), and A (amount
of the transaction).
Skipping down to line 365, it is time to sort things according to the task
being run. This is the second, and final, time this happens. Here is another
ON T-2 GO TO ... statement. IfT=3, control is sent to line 370, where T$
is compared with a truncated version of the N$ item previously read in line
340. Doing task 3, in other words, forces the system to attempt a match
between T$ and N$-transaction designations.
If the operator has specified task 4, line 365 causes the system to check
the match between D$ and T$ (dates) at line 375. But if task 5 is being run,
line 365 tells the system to attempt a match between a truncated version of
the P$ item and T$ (recipients).
If there is a good match in anyone of these three cases, control goes to
line 385, where the checkbook information, including the compiled balance,
is listed on the screen under the appropriate headings generated by lines
330 through 334. But if there is no match, the ELSE operators return con-
trol to line 340, where the system begins reading the next DATA line.
The system continues reading DATA lines and printing information when-
ever there is a match up until one of two things happens: either the system
displays 10 lines of information on the screen or READ N$ fmally fmds an
END statement in the DATA list.
You don't want to list more than 10 lines of information on the screen.
Allowing that to happen would run the risk of having some of it scrolled
off the top of the screen. So the subroutine in this example includes a
mechanism for counting the number of lines of information that is printed.
The counting variable in this case is L. L is set to zero at line 335 and incre-
Sec. 12-6 Programs for CHECKBOOK TRANSACTION 267
men ted by the first statement in line 390-directly after each line-printing
operation. Also, by line 390, if L is less than 10, the system continues
cycling through its match-search routine. But the moment L becomes equal
to or greater than 10, the second statement in line 390 defaults to line 395.
Upon executing line 395, all searching and printing operations come to
a halt, and the operator is prompted to STRIKE 'ENTER' TO SEE MORE.
When the operator has a chance to study the lines of information on the
screen, striking the ENTER key makes operations pick up at line 397. The
screen is cleared, and by going back to line 330, the system prints a fresh
heading and resets the printed-line counter, L, back to zero. The search then
continues where it left off.
Eventually, the READ N$ statement in line 340 is going to encounter and
END statement at the end of the DATA listing. The IF ... THEN condi-
tional in that line is thus satisfied and control goes to line 400.
tine 400 is a logic statement that, in effect, tests to see whether or not
any relevant information has been found. If L=0, for instance, the implica-
tion is that there are no lines of information printed on the screen. Perhaps
none was found in the entire searching operation. But there is a chance that
the screen might have been filled with lines and that the operator struck the
ENTER key to see more-but there was no more, and L=0. There has to be
some provision for covering this case. That's the purpose of the M-variable
counter.
M keeps track of the number of times an overloaded screen is cleared and
restarted. Note that M is set to zero at the very start of the subroutine (line
305) and is incremented whenever the operator must strike the ENTER key
to see another block of match-ups.
So if M and L are zero at the same time, it means no match-ups were
found in the entire DATA listing. The logic statement is negated by NOT,
however. So if M and L are both zero at the same time, control goes to line
405, causing the message NO SUCH LISTING to appear on the screen. In
either case, the system breaks away from the subroutine and returns to the
master program.
Earlier in this discussion of the FIND subroutine, you were asked to skip
over lines 350 through 360. They should look rather familiar, because the
same sequence of operations appeared in the subroutine in Example 12-12.
All they do is keep a running tally of the checking-account balance and
make provisions for inserting a plus sign in front of AMOUNTS figures for
deposit-type transactions.
planations several times, revising the notes and trying to answer your
questions for yourself.
Eventually, you will get the impression you understand what is
happening and, in the process, become a more knowledgeable and
experienced BASIC programmer. Making up a flowchart for this pro-
gram is left as an exercise at the end of this chapter. It's doubtful
you can master the analysis without making up some sort of a flow-
chart as you study it, however.
No matter how you feel about the program when you're finished
studying it, you should eventually load it into your computer and try
it for yourself. Of course, you'll have to enter some DATA listings
before the program can be run. Here is a suggested listing. It isn't
long enough to cover all the features of the program, but it is ade-
quate for demonstrating the basic principles.
EXAMPLE 12-14
Assuming you have loaded the program and data as listed in Ex-
amples 12-11, 12-12, 12-13 and 12-14, it is time to run some of the
task options. Do a RUN and enter task number 1. You should see
this on the screen:
Enter RUN again and select task 2. The listing will look like this:
END OF LISTING
END OF LISTING
END OF LISTING
In the first case, the operator requested and got a complete de-
posit history contained in the DATA file. In the second instance, the
operator requested information about check number l22S-which
happened to be a voided check.
Enter N to get back to the main heading and then request task 4.
You should see a message, WHAT DATE (MONTH-DAY)? Respond
by entering 6-12.
END OF LISTING
And there are all the transactions and relevant information for
June 12.
Enter N again, and select task 5. The message in this case is
WHAT RECIPIENT? Look at RADIO SHACK.
END OF LISTING
EXERCISES
12-8 Explain the difference, if any, between the following examples using
field specifiers:
(a) PRINT USING "##.##";A
(b) LET F$="##.##": PRINT USING F$;A
12-9 Specify the result of running the following statements:
(a) N$="NOW YOU DID ITI": PRINT LEFT$(N$,5)
(b) M$="MONEY":E$=LEFT$(M$,2): PRINT E$
(c) N$="SAMUEL":0$=LEFT$(N$,3): PRINT 0$" IS SHORT FOR "N$
12-10 Each DATA line in Example 12-14 must be read with four READ oper-
ations. Account for those four operations in Example 12-12 and 12-13.
12-11 What is a random file? The opposite of a random file is a sequential file-
what do you suppose characterizes a sequential file?
Easing into Data Arrays
with
Subscripted Variables
Until now, you have had to select numerical and string variables in a
rather conscious fashion. You have been consciously selecting the
variables, fitting them into a program and making some provisions
for assigning the right kinds of values to them.
There are instances that call for using a great many numerical or
string variables, and what's more, there are situations where the num-
ber of variables you must specify changes with the operation 'of the
program. Running a program at one time might call for assigning
values to 20 variables, but running the same program under slightly
different conditions at a later time might call for using 50 variables.
This can be a very tricky situation if you are tied down to the notion
of selecting all the variable names in advance.
There has to be a better way. And there is-using subscripted
variables. It is rather pointless to establish a formal definition of
subscripted variables at this time because it probably wouldn't mean
much to you. To get headed in the right direction, consider some
tinkering with the computer in its command mode. Try this sequence:
273
274 Ch. 13 Easing into Data Arrays with Subscripted Variables
READY
>LETT(1)=4
READY
>PRINTT(1)
4
READY
>
The operator first set up the computer for the command mode of
operation, then entered the statement LET T( I )=4. The next step was
to enter the command PRINT TO), and the computer responded by
printing the numeral 4. TO) in this example is a subscripted variable.
Now look at this sequence:
READY
> T(1 )=9:T(2)=8:T(3)=7
READY
>PRINT T(11.T(21.T(3)
9 8 7
READY
>
READY
>0$ (2)="MUGGINS"
READY
>PRINT 0$ (2)
MUGGINS
READY
>
EXAMPLE 13-1
First note the FOR ... NEXT loop between lines 10 and 40. Ten times,
you are prompted to enter an item X. And each time you enter the item
(a numerical value), it is assigned to the subscripted variable T. So by the
time the program gets down to line 50, you have stored 10 item values in
memory, each assigned a subscribed variable between T(1) and T(9).
And after the system executes lines 50 and 60, it waits for you to strike
the ENTER key. The display to this point looks like this:
ENTER ITEM 1 ? aa
ENTER ITEM 2 ? 99
ENTER ITEM 3 ? 88
ENTER ITEM 4 ? 77
ENTER ITEM 5 ? 66
ENTER ITEM 6 ? 55
ENTER ITEM 7 ? 44
ENTER ITEM 8 ? 33
ENTER ITEM 9 ? 22
ENTER ITEM 10? 11
ENTER PHASE DONE
STRIKE 'ENTER' FOR DISPLAY?
276 Ch.13 Easing into Data Arrays with Subscripted Variables
Of course, this display was built from the top and downward, adding a
new line every time you enter a new item. The items in this instance happen
to be a sequence 0(/J, 99, 88, ... , 11. You can respond to the question
marks with any number you choose.
Responding to the STRIKE 'ENTER' ... message, another FOR ... NEXT
begins. This one, however, runs between lines 70 and 90, printing out the
information stored in the first phase. The display ought to look something
like this:
ENTRY 1 = 00
ENTRY 2 = 99
ENTRY 3 = 88
ENTRY 4 = 77
ENTRY 5 = 66
ENTRY 6 = 55
ENTRY 7 =44
ENTRY 8 = 33
ENTRY 9 = 22
ENTRY 10 = 11
DISPLAY DONE
READY
>
The program worked its way through all 10 subscripted variables
and printed out their respective values that were assigned in the first
phase of the program.
How would you compose a program for doing this same job if
you did not have the benefit of subscripted variables? The first phase
of the job would have to look like this:
EXAMPLE 13-2
10 CLS: FOR N=1 TO 11
20 PRINT "ENTER ITEM NUMBER"N
30 ON N GOTO 40.41,42,43.44,45.46,47,48,49.50
40 INPUT T1 :NEXT
41INPUTT2:NEXT
42 INPUT T3:NEXT
43 INPUT T4:NEXT
441NPUTT5:NEXT
45 INPUT T6:NEXT
46 INPUT T7:NEXT
47 INPUT T8:NEXT
48 INPUT T9:NEXT
49INPUTT0:NEXT
50 PRINT "ENTRY PHASE DONE"
601NPUT "STRIKE 'ENTER' KEY FOR DISPLAY";X$
Sec. 13-1 Some Preliminary Experiments with Subscripted Variables 277
EXAMPLE 13-3
10 CLS:N=1
20 PRINT "ENTER ITEM NUMBER"N;: INPUT X
30 T(N)=X
40 IF X=9999 THEN 60
50 N=N+1 : GOTO 20
60 PRINT "OK. DONE FOR"N-1 "IT:::MS"
70 INPUT "STRIKE 'ENTER' KEY FOR DISPLAY";X$
80 CLS: FOR M=1 TO N-1
90 PRINT "ENTRY" M"="T(M) :NEXT
100 PRINT "LISTING DONE":END
This is an open-ended program that allows the user to enter any number
of numerical values, X. With each entry, counting variable N is incremented
at line SO, generating a looping action that is similar to the FOR ... NEXT
loop in Example 13-1, but unending.
The operator signals the end of the data-entry operation by specifying
9999. Whenever X is set to 9999, line 40 sends operation down to line 60,
and the operator sees the message OK. DONE FOR so many ITEMS. Using
9999 as an entry for signaling the end of the data-entering process is a rather
arbitrary move that assumes 9999 will never be one of the items to be saved
as a subSCripted value.
The display phase of the job begins at line 80, using the number N-l as
the end point for the FOR ... NEXT operation. Other than that little varia-
tion, the display phase is virtually identical to the version already described
in connection with Example 13-·1
The main point of this example, however, is that the operator is free to
enter any number of values. The scheme automatically specifies the sub-
sCripted variables-something that cannot be done with ordinary variables.
Suppose you run the program. The display generated through the frrst,
data-entry phase might look like this:
278 Ch.13 Easing il1to Data Arrays with Subscripted Variables
In this example, the operator responded to the requests for item numbers
with the sequence 12, 23, 34, 45, and then terminated the operation by
entering the "magic number" 9999. The computer responded to that last
entry by printing a couple of relevant messages.
Mter striking the ENTER key, the display changes to this:
ENTRY 1 = 12
ENTRY 2 = 23
ENTRY 3 = 34
ENTRY 4 =45
LISTING DONE
READY
>
EXAMPLE 13-4
10 CLS: N=1
20 PRINT "ENTER ITEM"N;: INPUT X$
30 T$(N)=X$
40 IF X$="DONE" THEN 60
50 N=N+1: GOTO 20
60 PRINT "OK. DONE FOR"N-1"ITEMS"
70 INPUT "STRIKE 'ENTER' KEY FOR DISPLAY";X$
80 CLS: N=1
90 IF T$(N)="DONE" THEN 110
100 PRINT "ENTRy"N"="T$(N): N=N+1: GOTO 90
110 PRINT "LlSTING DONE":END
This program runs much the same way as that in Example 13-3, the only
differences being that Example 13-4 accepts string expressions and the
entry phase is ended by entering DONE. Note the use of the subSCripted
string variable T$(N) and input variable X$, in place of T(N) and X shown
in Example 13-3.
The flowchart for this example appears in Fig. 13-1.
Figure 13-1 Flowchart for a program that
lets the operator enter string variables into
subscript memory space, and then list the
results. See the program in Example 13-4.
279
280 Ch. 13 Easing into Data Arrays with Subscripted Variables
ENTRY 1 =BIC
ENTRY 2 =TAB
ENTRY 3 =MUG
LISTING DONE
READY
>
If you have been running these examples exactly as they are pre-
sented here, you probably haven't run into any system-generated
error messages related to running out of subscript range. Most home
computers allow at least 10 memory locations for subscripts. That
means you can use up to 10 subscripted variables within any pro-
gram. And since none of the previous examples called for more than
10 subscripts, you haven't run into the out-of-range problem.
Here is a short experiment that lets you determine exactly how
much subscript memory is normally available.
EXAMPLE 13-5
10 CLS:N=l
20T(N)=N: PRINTT(N)
30 N=N+1 : GOTO 20
40 END
The idea is to build an N counter, using the values of N to specify the sub-
script as well as its value. So whenever N=5, for instance, T(5)=5. As the
values are assigned in the fIrst statement in line 20, the second statement in
that line prints them on the screen.
The program is essentially an unending counting loop, but you will run
out of available string space before the program counts very far. The result
of this experiment, as run on Radio Shack's Level II TRS-BO, looks like this:
Sec. 13-2 Allocating More Memory Space for Subscripts 281
RUN
1
2
3
4
5
6
7
8
9
10
?BS ERROR IN 20
READY
>
5 DIM T(1001
Now run the program and watch what happens. Ah-ha! The thing counts
like crazy up to 100-and then you get the error message. The statement
DIM T(100) allocated 100 memory spaces for subscripted variable T(n).
How large can you make the memory space? That depends on
the system you have. A system featuring a 4K memory cannot allo-
cate as much subscript space as an 8K or 16K system. An out-of-
memory error will signal that you have assigned more subscript space
than the system can handle.
All of the examples presented in the first part of this chapter merely
list the information entered in an earlier phase of the program. The
point was to show that subscripted variables can accept numerical or
string values, store it, and then read it out at a later time. But, of
course, it is also possible to manipulate the information as it is read
out of the memory, doing things such as mathematical operations,
sorting, and even program control operations.
The program in Example 13-6 allows the operator to enter up to
100 numbers and then get a printout of those numbers and a figure
representing their average value. A flowchart for the program is illus-
trated in Fig. 13-2.
EXAMPLE 13-6
10 DIM A(100):CLS:N=1
20 PRINT"TYPE A BUNCH OF NUMBERS (UP TO 100 OF THEM),"
30 PRINT"DOING 'ENTER' AFTER EACH ONE OF THEM."
40 PRINT:PRINT"ENTER 9999 TO END THE ENTRY OPERATION."
50 INPUT A(N): IF A(N)=9999 THEN 70
60 N=N+1: GOTO 50
Sec. 13-3 Manipulating Information Specified as Subscripted Variables 283
Upon entering RUN, you are greeted with this message on the screen:
The question mark and cursor indicate that it is time to enter the fIrst
number. Upon entering a "bunch of numbers," the display might look like
this:
Lines 10 through 30 of the program in Example 13-6 are the ones that let
the operator enter the "bunch of numbers." Line 50 directly inputs the
value of subscripted variables, checks for 9999 "magic number," and if the
9999 is not specifIed, sends operations down to line 60. Line 60 then incre-
ments the value of N and loops the program back up to line 50.
This looping operation between lines 50 and 60 continues until the oper-
ator speciftes 9999. When that happens, control is sent to line 70.
The second phase of the program picks up at line 90, clearing the screen
and initializing an ordinary variable, AS. Line 100 prints a simple message
that includes the number of numbers included in the entry process; and
after that, line 110 begins reading the values of the subscripted variables,
printing them, and accumulating a sum of the values, AS.
When all the subscripted values have been read-as determined by the
completion of the FOR ... NEXT loop in line 1l0-the system prints the
Sec. 13-3 Manipulating I nformation Specified as Subscripted Variables 285
fmal message, which includes the average value. That average is calculated
by dividing the sum of the values by the number of values: AS/(N-l).
Information that is stored as subscripts can be manipulated mathemati-
cally in much the same fashion as items in a DATA list are handled.
EXAMPLE 13-7
90 CLS: PV=0
100 PRINT "YOUR"N-1"NUMBERS WERE:"
110 FOR M=1 TO N-1 : PR INT A(M)" ,";
120 IF A(M»PV THEN PV=A(M)
130 NEXT
140 PRINT: PRINT"THE LARGEST OF YOUR"N-1"NUMBERS IS"PV
150 END
The idea here is to examine all the subscripted information, one element
at a time, saving the largest value as ordinary variable PV. This is done by
first setting PV to zero in line 90, looking at the value of A(l), and if that is
larger than PV, saving the value of A(1) as PV. The FOR ... NEXT loop
then causes the system to compare A(2) and PV. If A(2) happens to be
smaller, PV is not changed; but if A(2) is larger, its value replaces the smaller
one in PV.
This comparison operation continues through the entire list of subscripts,
the current largest value of A(N) being held as value PV. Line 140 then
prints the fmal value of PV, which, of course, has to be the largest of all the
A(N) numbers.
The complete flowchart for this program is shown in Fig. 13-3. Load the
program and run it for yourself. You'll see that it prints out the largest of all
the numbers you enter during the rust phase of the program.
RUN
regarding wind speed and the times the speeds occurred. After enter-
ing the time/speed information, the program then lists the informa-
tion, figures the average wind speed for the period of time the data
represent, and sorts out the maximum speed.
The flowchart for Example 13-8 is shown in Fig. 13-4.
EXAMPLE 13-8
100 NEXT
110 PRINT: PRINT"THE AVERAGE WIND SPEED IS"SS/IN-1)
115 PRINT"THE PEAK WIND SPEED IS"SP"AT "HP$":"MP$
120 END
line 40 causes the system to READ the data from the fust item to an
item determined by RND(52). After executing line 40, string variable S$
holds the value of a card randomly selected from the DATA me.
Line 50 then searches the list of card designations already assigned to the
"hand"-the values already assigned to C$(n). And if there is a match be-
tween a newly selected card, S$, and one of the cards already saved in the
subscript memory, C$(n), the system is restored and another card is pulled
from the me. The point of all this is to make certain that no two cards in
the hand are identical.
The new card is assigned to the "hand" by the fIrst statement in line 70.
If the hand already contains more than fIve cards, control goes down to
line 90, where the values of the cards are printed out on the screen. Other-
wise, the card counter, CD, is incremented at line 80, and control goes back
to line 30 for picking another card.
By line 100, any number of fresh hands can be dealt by simply striking
the ENTER key.
12,24,2,18
12,24,2,18
But then the system compares the second and third items-24 and 2.
294 Ch.13 Easing into Data Arrays with Subscripted Variables
In this instance, the second is smaller than the first, and the system
responds by exchanging their places in the list. So now the list looks
like this:
12,2,24,18
12,2,18,24
Notice how the largest number in the list "bubbles" to the top of
the list. That always happens on the first pass through the list.
Obviously, the task of setting these items into numerical order is
not done yet-the 12 and 2 are still out of order. So the whole job is
done again.
Looking at the first two items, the computer sees that they are
out of order, and responds by exchanging their positions. The list
then looks like this:
2,12,18,24
The job is actually done at this point, but the computer doesn't
know that. It continues running through the list, comparing succes-
sive pairs of items, until it runs through the complete list without
making any exchanges. Then the computer has the information it
needs to signal the end of the program.
Getting down to specifics, assume the computer has some mem-
ory space containing subscripted numerical variables A( I) through
A(20); and further assume those 20 variables have been assigned
random numbers between I and 99. The idea of the bubble-sort pro-
gram is to rearrange the list so that the numbers are in numerical
order.
As the program progresses, the system inspects the values of two
successive subscript locations, say A(I) and A(I+ I). A(I) represents
anyone of the values, and A(I+ I) represents the next one along the
line.
Now values A(I) and A(I+ I) are compared, and if A(I) is smaller
than A(I+ I), the two are already in numerical order and there is no
need to exchange their locations in memory. But when it turns out
that A(I) is greater than A(I+ 1) the numbers in those two locations
Sec. 13-5 A First Look at Bubble Sorting 295
EXAMPLE 13-10
The fact that the process calls for swapping information around
in variable spaces made it difficult to introduce the idea earlier in this
book. But rest assured, you have not seen the end of it now.
The following examples make up a complete bubble sorting pro-
gram. It starts out with a list of 20 randomly generated numbers that
are assigned to an equal number of spaces in the subscript memory.
The idea is to rearrange the list so that the values are in numerical
order.
The actual sorting routine is presented as a subroutine in Example
13-11. Two additional subroutines in Example 13-12 are responsible
for generating the list of random numbers and printing the results of
both the random and ordered lists. The subroutines are then pulled
together into a working program by the main program in Example
13-13. The whole business is presented as a flowchart in Fig. 13-7.
s
~
m
A(I) A(I+1)
(a)
([]
m
A(I) A(I+1)-
(b)
[]
A(I) A(I+1)
(e) I-I: I
(d)
296
RUN 10101
INITIALIZE
SUBSCRIPT
COUNTER
(X)
INITIALIZE
SUBSCRIPT
COUNTER
(I)
(b)
INITIALIZE
SUBSCRIPT
COUNTER
(X)
(a)
(e)
297
298 Ch.13 Easing into Data Arrays with Subscripted Variables
Subroutine
2¢~
Subroutine
25\6
Subroutine
1~
Subroutine
25~
(d)
EXAMPLE 13-11
The statement in line 120 sets up the system for searching through the
A(n) subscript memory, one item at a time. Although there will be 20 items
in the list, the FOR ... NEXT loop will not be executed more than 19
tunes. if you were to write line 120 as FOR 1=1 TO 20, you would be
Sec.13-5 A First Look at Bubble Sorting 299
EXAMPLE 13-12
those spaces with number values, the RETURN statement in line 220 re-
turns operations to the master program. So that's where the program will be
getting the data to be sorted. It can come from a lot of different kinds of
sources, but this random source is a nice one for the sake of demonstration.
Subroutine 250, included in Example 13-12, simply scans the existing
subscript space and prints the values contained therein.
EXAMPLE 13-13
Line 10 in Example 13-13 clears the screen and sets the dimension of the
subscript memory at 20 elements. Line 20 then calls subroutine 200 to fill
that space with random numbers.
When subroutine 200 completes this task, line 30 of the main program
prints RAW ARRAY:, followed by a complete listing of the random num-
bers residing in the subscript memory space. The printing of these numbers
is handled by subroutine 250, as called by line 40 in the main program.
Mter printing out the original number list, line 50 calls for the sorting
subroutine. The numbers are thus arranged in numerical order, using the
bubble-sorting algorithm in subroutine 100. And upon returning to the main
program, line 60 prints SORTED ARRAY:, followed by a printing of the
revised array of numbers. If all has gone as planned, the second list of num-
bers will be in numerical order.
Upon running this program, you will note a considerable time delay (some-
thing on the order of 6 seconds) between the printing of the original list and
the sorted list. The time delay is caused by the sorting algorithm, and the
more scrambled the values in the list, the longer it takes to sort them into
numerical order.
The program can be run any number of times, each run starting out with a
different list of scrambled numbers in the subscript memory space.
EXAMPLE 13-14
The first task in Example 13-14 is to get the listed information out of the
DATA listing and into subscript space A$(n). The information residing as
DATA in line 510, you see, cannot be organized at that level. It is fixed by
the fact that it is a program line. Once the same information is copied into
subscript space, however, it can indeed be shuffled, sorted, and reorganized.
The original DATA base in line 510 will remain unchanged by the sorting
operation.
Lines 15 through 30 in Example 13-14 are responsible for copying the
DATA items into A$(n) subscript space. This is a counting loop that reads
an item of data, assigns it to ordinary string variable A$ (first statement in
line 20), and then checks to see whether or not it is reading the last item in
the DATA listing, DONE. If that item is not DONE, the item counter, N
is incremented in line 15 and the copying operations are repeated.
This copying loop continues until READ A$ turns up a DONE. And that
is how one goes about transferring items in a DATA list to subscript space
where it can be sorted.
Basically, the next phase of the operation is to bubble-sort the names, re-
arranging the string statements in the list into alphabetical order. Lines 50
and 60 are largely responsible for this part of the job. Line 50 tests to see
whether or not a given name falls alphabetically ahead of the next name on
the list. Recall that inequality operators, as applied to string variables, test
302 Ch.13 Easing into Data Arrays with Subscripted Variables
CARMEN
DAVID
EDWARD
HARRIET
HERMAN
JUDY
MABEL
MARGARET
MUGGINS
PAUL
PUMPKIN
STANLEY
TABATHA
READY
>
EXERCISES
13-1 Explain how ordinary variables and subscripted variables differ (a) in
appearance in a program and (b) in their application.
13-2 What is the purpose of the DIM statement when it comes to using sub-
scripted variables? What factor is mainly responsible for limiting the
maximum DIMension of subscript space?
13-3 A DIM statement must be specified only one time within the running of a
program. What is the best way to be certain a DIM statement will never be
included in a looping operation?
an
13-4 For each of the examples listed below, list variables, describing them as
(1) ordinary numerical or string varibles or (2) subscripted numerical or
string variables. Describe the purpose of each variable in terms of its place
in the program.
(a) Example 13-6
(b) Example 13-8
(c) Example 13-9
13-5 Sketch a flowchart illustrating the bubble-sorting algorithm as it applies
to (a) numerical values and (b) string values.
13-6 Explain why DATA items to be bubble-sorted must first be copied into
subscript memory space.
Worl~ing
with
Multidimensional Arrays
Recall from basic algebra and geometry that a point on a straight line
can be specified by a single number. A straight line can be viewed as
a one-dimensional coordinate system, and a single number is ade-
quate for specifying a point on it.
A plane, however, is a two-dimensional figure that requires two
numbers to specify any point on it. One of the numbers represents
the horizontal coordinate of the point, and the second specifies the
vertical coordinate.
These notions carryover directly to arrays in computer memory.
Chapter 13 dealt with one-dimensional arrays-arrays whose separate
elements could be specified or addressed by means of a single num-
ber. A piece of information stored in one-dimensional subscript space
can be accessed by means of a term such as A(n), where n is any
integer between 1 and some larger number that falls within the di-
mension-size-of the array.
In a one-dimensional array, you can store information in location
A(S), for example, by doing a statement such as A(S)=numerical
value. And you can retrieve that information later by means of a
statement such as numerical variable=A(S). The term A(S) can be
considered the fifth element in memory block A.
304
Working with Multidimensional Arrays 305
EXAMPLE 14-18
READY
>A(1 )=10
READY
>A(2)=20
READY
>A(3)=30
READY
>A(4)=40
PRINT A(1),A(2I,A(3),A(4)
>10 20 30 40
A(1)
10
A(2) A(l,l) A(2,1)
20 l~ 30
A(3) A(l,2) A(2,2)
30 20 40
A(4)
(b)
40
(a)
READY
>
EXAMPLE 14-1b
READY
>A(1.1)=10
READY
>A(1.2)=20
READY
>A(2.1 )=30
READY
>A(2.2)=40
READY
>PRINT A(1.1) ,A(1.2),A(2.1 ),A(2.2)
10 20 30 40
READY
>
From all outward appearances, Example 14-1 b does the same job as Ex-
ample 14-1a. The only difference lies in the way the elements are organized
in the memory. Compare Fig. 14-1a and b.
In the two-dimensional case, 1~ is stored in a location specified as A(1,I)-
a memory element found in the first column, first row. Number 2~ is stored
in the first column, second row, as specified by A(1 ,2). Number 3~ is stored
in the second column, first row, and number 4~ was stored in the second
column, second row.
Suppose that you are the chairperson of a local beauty contest and
want to computerize a list of contestants' names, including the color
of eyes and hair, heights, addresses, and telephone numbers.
Now you will probably want to enter the list of items as DATA
in the program itself, thus making it possible to save the list on
cassette tape. (It is altogether possible to save just the list, using a
home computer equipped with a disk operating system, but such a
feature is generally an option most users cannot yet afford.)
So you enter the information like this:
EXAMPLE 14-2
That is a rather short list, but it will serve the purpose. Note the sequence
of items in each line: name, eye color, hair color, height, address, phone
number.
You want to be able to manipulate, sort, and reorganize these data, and as
308 Ch.14 Working with Multidimensional Arrays
you learned in the previous chapter, this means that some or all of the in-
formation has to be pulled out of the DATA me and transferred into sub-
script space. And that means reading through the data list, systematically
assigning the items to some sUbscript space.
Using the procedures for one-dimensional subscripts in the previous chap-
ter, you could do the job by assigning a one-dimensional array to each of
the items in the list. Names, for instance, could be assigned to N$(n), eye
color to E$(n), hair color to H$(n), and so on. You would end up with a set
of six subscripted string variables, one for each of the DATA items-name,
hair, eyes, height, address, and phone number. And if you used the same
n value at any given moment, the six subscripts would all relate to one girl.
For instance, setting n=2, you would get N$(2) for JANICE, H$(2) for her
BROWN eyes, H$(2) for her BROWN hair, and so on. Changing n to 3
would then set all the one-dimensional arrays to elements relevant to ANNE.
This parallel application of several one-dimensional arrays isn't really too
bad. You could make it work quite nicely for the DATA in Example 14-2.
The program might be a little bit cumbersome in places. Consider how you
would have to dimension those six different arrays: DIM N$(1~~):DIM
E$(1~~): DIM H$(1~~), and so on through DIM P$(100). You need six DIM
statements to set the dimensions of the arrays-to 100 elements in this
case.
But you will have to agree that the DATA list in Example 14-2 is a very
simple one. What if you had 100 different items related to each name on the
list? Let your own imagination play around with 100 different parameters
for these girls-the point is that working with 10,25,50,100, or more items
on each line isn't that unusual in the data processing business.
With so many items on each DATA line, you would have to assign a lot of
subscript variable names yourself. And then there are programs that call for
item lists of varying length.
Now, doesn't this sound a lot like the opening sections of Chapter 3,
where the use of subscripted variables is clearly better than the use of ordi-
nary variables? You are facing the same sort of predicament here-one-
dimensional variables are getting cumbersome. It would be nice if the
computer could assign subscripts to the subscripts, thereby eliminating the
need for having to specify the variable names in the program itself.
Well, the computer does that sort of work, and that is where multi-
dimensional arrays enter the picture. The DATA list, as shown in Example
14-2, can be handled quite easily with a two-dimensional array.
You will need only one subscript variable name; and since this project has
a lot to do with girls, make that name G$. The minimum dimension of the
array can be specified as five rows (girls' names) by six columns (items for
each girl). An expression such as G$(1,4) would thus specify 5'4" -first girl
(HELEN) and fourth item (height 5'4"). In fact, everything related to
HELEN can be summarized by the expression G$ (1 ,n), where n is an integer
between 1 and 6 inclusively. By the same token, the information for SUSAN
can be specified by G$(4,n).
There is only one variable specifier, G$, as opposed to six that would be
Sec. 14-1 Why Use Multidimensional Arrays? An Example 309
Now put together a program for drawing the items out of the
DATA list and putting it into the subscript space we have just
defined.
EXAMPLE 14-3
That is all. Enter the program along with the DATA in Example 14-2.
When you first RUN the program, you will see this:
HELEN/BLUE/BLONDE/5'4/2175 E. MAIN/334-5591
JAN ICE/BROWN/BROWN/5'8/16 CR ESCENT /286-2551
ANNE/BLACK/BLACK/5'3/1226 N. FOURTH/291-4478
SUSAN/GREEN/RED/5'10/980 KING/334-9909
SALL Y/BROWN/BROWN/4'11/123 SUMMIT/291-4567
Example 14-3 in Section 14-1 shows how items in a DATA list can
be transferred into a two-dimensional array. A READ statement
picks up an item from the DATA listing, and a set of nested FOR ...
NEXT loops place that item into the array.
The FOR ... NEXT loops generate a systematic pattern of row-
column coordinates. And if the READ operation is properly synchro-
nized with the operation of the nested FOR ... NEXT loops, each
item is deposited into a well-defined position in the array's memory
space.
That was just one example illustrating how items in a DATA list
can be transferred into array space. An array can also be loaded from
the keyboard as shown in the next example. The scheme still uses
nested FOR ... NEXT loops to access the elements in the array in a
systematic fashion, but the items are entered via INPUT statements
rather than READ statements.
Example 14-4 demonstrates this particular process, using a
student grade summary as its objective.
EXAMPLE 14-4
The entry operations for this program occupies lines 10 through 110. The
general idea is to enter a student ID number (variable ID) and a set of grades
for that student (variable G). The number of students to be entered into the
scheme is set by the operator in line 20 (NS), and the number of grades for
each student is set by line 30 (NG). The two-dimensional array for this
information is dimensioned to 50 X 11, meaning that the program can
accept up to 50 rows of names having up to 10 columns of grades associated
with each name.
The statement DIM F(50,10) in line 10 also infers that the program is
going to work with only numerical expressions. If the program included
string expressions (which it doesn't, the dimensioning statement would have
to read something such as DIM F$(50,I0).
Once the operator establishes values for NS and NG, line 40 sets up the
"outside" FOR ... NEXT loop for the ROW operations-rows 1 through
NS. Line 50 then requests a student ID number to be placed in the first row
position, and that value is entered in that row and column 1 by the expres-
sion in line 60: F(ROW,I)=ID. So if ROW happens to be equal to 1 at the
moment, the value of the first student's ID goes into array position (1,1).
The next step is to enter that student's grades, one at a time, into the suc-
ceeding columns of that row. And since the first column in that row already
contains the student's ID number, the grade-entry process must begin at
column 2. Hence the "inner" FOR ... NEXT loop specified in line 70
begins with COL=2. It should then cause an INPUT looping operation that
runs to the NG+ 1 position in the array. So if there happens to be five grades
entered for each student, this loop specifies columns 2 through 6.
The request for a grade is generated by line 80, and the grade that is
INPUT on that same line is then assigned to coordinate (ROW,COL)=G by
line 90.
Line 100 then specifies the return points for both of the FOR ... NEXT
loops, causing the entry phase to continue until all grades for all students
have been entered. After that, the system (by line 110) prints the message
ENTRY JOB DONE and waits for the operator to strike the ENTER key
to get a printing of the results.
Figure 14-3 shows the layout of this particular array, assuming that the
information has all been entered.
The next phase of the task is to print out the contents of the array. This is
Sec. 14-2 Getting the Elements Into a Multidimensional Array 313
ren
Z
F(U)
ID NO.
F(2,1)
ID NO.
F(3,1)
F(U)
GRADE 1
F(2,2)
GRADE 1
F(3,2)
F(1,3)
GRADE2
F(2,3)
GRADE 2
F(3,3)
F(;:)
GR
F(2,4)
GRAD
F(3,4)I~
I
F( 1,11)
GRADE 10
F(2, 11)
GRADE 10
F(3,11)
ID NO. GRADE 1 GRADE2 GRADE GRADE11
F(4,1) ~
1 '- ID NO..-.......
F(4,2) F(4,3)
-~
F(4,41 F(4,11)
L F(5¢,1)
ID NO.
F(50,2)
GRADE 1
F(5P,3)
GRADE2
F(5P,
GRA I
F(5¢,11)
GRADE 11
done with another set of nested FOR .. , NEXT loops. The loops in this
instance print out the contents of the array, rather than load the array with
keyboard information.
The FOR ... NEXT loop established in line 120 is responsible for keeping
track of the student names-the row specifiers for the array. Upon selecting
a new row, the PRINT statement in line 20 sets up a heading on the screen:
Line 130 then prints the ID number of the student selected by the outer,
row-selecting FOR ... NEXT loop. Immediately after that, line 140 sets up
the inner FOR ... NEXT loop that systematically picks and prints the
column information concerning that student's grades.
tine 150 is picked up when the grade-printing operation is done and the
operator strikes the ENTER key to get the grade summary for the next
student. Note that the NEXT statement in line 150 loops operations all the
way back to line 120, where the row count is incremented by that outer,
ID-specifying loop.
The operator is greeted with the message THAT WAS THE LAST STU-
DENT SUMMARY when all grades have been viewed on the screen. The
operator then has the option of viewing the entire sequence of grade sum-
maries again, or ending the program.
Consider the entire program, using just one student and four grades. In a
practical sense, the project is too simple to be of any use, but you can enter
more names and see the scheme work in a more realistic sense.
Upon doing a RUN, the first message on the screen is: HOW MANY STU-
DENTS (1 to 5~)? For this demonstration, respond by entering 1. Then the
system prints the request: HOW MANY GRADES (1 to 1~)? The reply in
this case should be 4. So this point, the screen shows:
314 Ch.14 Working with Multidimensional Arrays
Entering that grade, you will see a request for the second grade, and the
process continues until you've entered the number of grades specilled earlier
in the program. For example:
1234 80
85
90
95
Sec. 14-3 Working with Mixed Variable Types in Arrays 315
And because this listing represents the last student in the me, striking the
ENTER key yields the message
The arrays presented so far in this chapter are defmed as either string
or numerical arrays. The DIM G$(50,6) statement in line 10 of
Example 14-3 clearly specifies string information, and in that
example all the information had the characteristics of string variables.
By the same token, the DIM F(50, 11) statement in line 10 of
Example 14-4 specifies numerical elements. No string elements were
allowed.
There is no problem as long as all the information in the array is
either string or numerical information. Simply dimension the array
accordingly. But, of course, there are many situations where it is
necessary to work with both string and numerical values within the
same array. In the grade-summary program of Example 14-4, for
example, it would be nice if the first column in each row could carry
the student's name, instead of an ID number. That would call for a
string specification in that column. If you want to manipulate the
grades as numerical values-doing somet!ling useful such as averaging
them-the grade columns must carry numerical designations.
The array must be specified as string or numerical, never both.
So how do you reconcile a contradiction of variable types?
The key to the answer is that a string variable can be made up of
numbers as well as any other combination of alphanumeric characters
316 Ch. 14 Working with Multidimensional Arrays
EXAMPLE 14-5
sort the names first and then work through the revised, sorted list of
names one at a time. Each time the system picks a new name on the
list, it searches the DATA listing for that particular name and then
loads the items properly associated with it. The following programs
assume the DATA listing in Example 14-2 is loaded into program
memory.
EXAMPLE 14-6
The program in Example 14-6 is divided into three phases. The first phase,
represented by lines 10 through 50, loads the first item in each DATA line-
the girls' names-into the first column of the two-dimensional array. The
second phase, lines 60 through 140, bubble-sorts the names, shuffling them
around so that they are in alphabetical order in the array.
The fmal phase runs through the sorted list of names in the array, return-
ing to the DATA list to select the information related to the name being
searched. The program ends when each name has the appropriate informa-
tion arranged beside it in the two-dimensional array. The fmal steps are re-
sponsible for printing this reorganized information.
Doing a run on the program in Example 14-6, you see this first on the
Sec. 14-4 Sorting Multidimensional Arrays 319
screen:
ANNE
HELEN
JANICE
SALLY
SUSAN
ENTER FOR MORE INFO?
There are the names arranged in alphabetical order. This display marks the
end of the second, bubble-sorting phase. The system has not yet sorted the
DATA to attach the appropriate information to each of the names.
So striking the ENTER key one more time you get:
That is the same information shown in Example 14-2. Here, however, the
names are arranged in alphabetical order.
EXAMPLE 14-7
The flow of the program in Example 14-7 follows that of the previous
version. Items from the DATA list (Example 14-2) are read into the two-
dimensional space specified and dimensioned in line 10, DIM G$(50,6).
That part of the job is completed at line 50.
Lines 60 through 110 take care of the bubble-sorting algorithm, working
with the entire listing this time. And lines 130 through the end simply print
out the sorted list of information in an orderly fashion. The final display is
identical to the one shown for the program in Example 14-6.
EXERCISES
and six items associated with each name. What is the appropriate dimen-
sioning statement for that array?
14-3 If a two-dimensional array is specified at U(m,n), which one of the three
terms represents column information? row information?
14-4 How would you go about adding more names and relevant information to
the DATA listing in Example 14-2 without having to write a program
routine?
14-5 Referring to the program in Example 14-3, how many girls' names could
be included in the DATA listing?
14-6 Why is it necessary to transfer DATA listings (such as the one in Example
14-2) to an array before the information can be sorted or manipulated
in some sorting fashion?
14-7 Why is the array in Example 14-4 dimensioned to 50 X 11 when later
statements in the program limit the number of grades to 1O? Why not
dimension to 50 X 10, in other words?
14-8 What puts an upper limit on the size of an array?
-,
CHAPTER 1
CHAPTER 2
16
READY
>
(b) The end result is READY and prompt. Character 16 appears as line
20 is executed, but line 30 clears it away in a fraction of a second.
The program is virtually useless.
(c) Clearing the screen, followed by
THE ANSWER IS 16
322
Answers to Selected Exercises 323
READY
>
(d) Clearing the screen, followed by
2 TIMES 8
THE ANSWER IS 16
READY
>
CHAPTER 4
4-2 (a) Unconditional
(b) Conditional
(c) Conditional
(d) Conditional because preceding FOR ... TO statement is assumed.
4-3 (a) 10 (b) 1 (c) 1 (d) 11 (e) 1 (f) 1
(g) 10 (h) 10 (i) 11 G) 10
CHAPTERS
CHAPTER 6
6-4 I=RND(1I)-6
6-11 (a) GOTO line 100 (b) GOTO line 140 (c) GOTO line 160
(d) THE DOG SLIPPED AND SQUASHED THE LAKE AND ALL ITS
CONTENTS
CHAPTER 8
8-3 START AT 10
AT SUB 100
AT SUB 200
AT SUB 300
ATSUB 400
AT SUB 500 AND RETURNING
AT SUB 400 AND RETURNING
AT SUB 300 AND RETURNING
AT SUB 200 AND RETURNING
AT SUB 100 AND RETURNING
AT THE START AND ENDING
DONE
READY
>
CHAPTER 9
CHAPTER 10
CHAPTER 11
CHAPTER 12
CHAPTER 14
A B
329
330 Index
Computer, analyst, 58 E
Apple II, 2
Commodore PET, 2 Edit mode of operation, 119
program, 25 Elements of an array, 3 11
programmer, 25 ELSE statement, 203, 211
Radio Shack TRS-80, 2, 15, END statement, 24, 30-31, 39
197 ENTER, command, 2, 10
Concatenating strings, 20 key, 5,10
Conditional loop, 71-72 Equality, operator, 73
Conditional operator, string variables, 18-21
AND,205 Equal sign, 12
NOT, 208, 210 Equations, programs for solving,
NOT-AND, 209 186
OR,206 Erasing lines, 36
Conditional statement, 84, 85 Errors, corecting, 13, 36
(see also Statement, IF ... EXP function, 15, 182, 184, 191
THEN) Exponential operator (see EXP
CONT command, 65-67 function)
COS function, 182, 191 Expressions, printing of, 7, 8, 11,
operator, 15, 182 20,22
Cosine function (see COS
function)
CR key, 5 F
CRT (cathode-ray tube), 1,2,
31,97 Field specifier, 233
Counting loop, 86 FIX statement, 182, 201
Cursor symbol, 5 Flowchart, program, 81-82
Formatting displays, 97-102
FOR ... TO NEXT, loops,
D 89-91
statement, 70, 86, 88-93
Dartmouth BASIC language, 2, Function,ABS, 182, 191
12 ATN, 182, 191
DATA, statement, 220-27, 290 COS, 182, 191
numerical, 22 I, 23 I EXP, 182, 191
string, 227,23 I INT (integer value), 182, 191
default operation, 77 LOG, 182, 191-93
DEF FN statement, 182, 195-96 SGN,182
Dice game program, 130 SIN, 182, 191
DIM statement, 273, 281 SQR (square root), 182, 190-
Division function and operator, 91
15, 183 TAN, 182, 191
Index 331
K
N
Key, CLEAR, 31
CR,5
Nested operations, loops, 79
ENTER,S, 10
subroutines, 173
RETURN,S
NEW command, 24, 31-32
Keyboard layout, 2 NOT -AND conditional operator,
209-10
NOT conditional operator, 208
L NOT -EQUAL operator, 73
NOT-IDENTICAL operator, 85
Least-integer value, 124 Null string, 18
LEFT$ function, 241, 264 Number, line, 24-29, 36
332 Index
T v
TAB statement, 102-7 Variable, subscripted, 273-90
animation, 108
graphics, 109 z
math, 103-6, 110-11
TAN function, 182, 191 Zeros, symbol, 10
Unconditiona11oop,71
Up-arrow symbol, 184