A Guide To Programming The Commodore Computers VIG20 C64 (1983)
A Guide To Programming The Commodore Computers VIG20 C64 (1983)
PROGRAMING THE
COMPUTER
BRUCE PRESLEY
AlKIBENCEWLLE
H
//RESS.JNC.
flNRENCBMLLE
POST OFFICE BOX 6167
LAWRENCEVILLE, N.J. 08648
TELEPHONE: (609) 896-3570
BRUCE W. PRESLEY
President
Dear Educator:
As you review this textbook, I'm sure you will be immediately aware
of the value of a text written especially for your classroom and the
computer you're using. The author, Mr. Presley, has been teaching
programming at The Lawrenceville School for more than fifteen years.
His knowledge of computers and, most importantly, his experience in
how to teach programming, are clearly reflected in his books.
With the release of our text for the Commodore 64/Vic 20 computers
this fall our planned series of machine-specific books (Apple, IBM,
Radio Shack and DEC) is complete. We will now be concentrating on
producing teachers guides and updating the texts as new machines come
on the market (i.e., the IBM Peanut). Our schedule now calls for the
March release of the second edition of our text for the Apple, which
will specifically cover the lie. Along with it, we will also publish
a teacher's guide which will contain work sheets, lesson plans, assign
ments, chapter tests, and transparency masters for overhead projectors
These guides will eventually be available for all our texts.
As you will note, our texts are distributed by Van Nostrand Reinhold.
Orders may be placed by contacting them at: 7625 Empire Drive,
Florence, KY 41042, ATTN: Bob Edwards, telephone (606) 525-6600.
Please note also that there is an educational discount of 20% on any
size order.
We thank you for your interest, and hope that after reviewing our text
you will find it the one best suited to your classroom needs. Should
you have any comments or suggestions, we hope you'll return the
enclosed evaluation card. Our books are written for you, and your
input is not only invaluable, but greatly appreciated.
Sincerely,
Carol S. Tibbetts
Vice President
CST:mls
Enc.
PRDERflMEIJNE ThE
BRJCE PRESLEY
flWREMCEWLLE
\
First published in 1983
Copyright© 1983
by
fiKIRENCEWLLE
ISBN 0-422-27375-4
ftfftf
Macmillan of Canada
Division of Gage Publishing Limited
164 Commander Boulevard
Agincourt, Ontario M1S 3C7, Canada
16 15 14 13 12 11 10 9 8 7 6 5 4 3
Bruce Presley
TflBLE DF CONTENTS
INTRODUCTION
What is a computer? ix
What is a program? ix
The Development of the computer ix
Computer Languages x
CHAPTER SIX—Graphics
Color 6-1
Reverse Mode 6-2
Graphic Symbols 6-4
Cursor Movement 6-6
PEEK and POKE 6-9
Peeking and Poking on the Commodore-64 6-10
Peeking and Poking on the VIC-20 6-13
Lower Case Mode 6-16
Commodore-64 Screen Memory 6-17
VIC-20 Screen Memory 6-20
Joysticks 6-23
Commodore-64 Joysticks 6-23
VIC-20 Joystick 6-24
Sound on the Commodore-64 6-26
Sound on the VIC-20 6-29
Exercises 6-35
VI
CHAPTER SEVEN—Mathematical Functions
SQR 7-1
SGN and ABS 7-1
Trigonometic Functions: SIN, COS, TAN 7-3
ATN 7-4
Logarithms and the Exponential Function: LOG, EXP 7-5
DEF 7-6
Exercises 7-9
CHAPTER NINE—Files
Cassette Files 9-1
OPEN 9-1
CLOSE 9-2
PRINT# 9-2
INPUT 9-4
Updating Cassette Files 9-5
STATUS 9-8
Demonstration Programs 9-10
Diskette Files 9-14
OPEN 9-14
Updating Diskette Files 9-14
Bubble Sort 9-16
Exercises 9-20
APPENDIX A—Editing
Editing A-1
VII
SAVE A-4
VERIFY A-5
LOAD A-5
Renaming Programs and Files A-5
Copying Programs and Files A-6
Diskette Directories A-7
Removing Programs and Files A-7
WEDGE A-8
INDEX
VIII
INTRODUCTION
When discussing computers, it is convenient to divide the subject into two broad
categories—hardware and software. Hardware refers to the computer itself and its peripheral
devices—disk drives, printers, etc., whereas software refers to the programs or instructions
which are entered into the computer to make it perform specific tasks. It is the purpose of this
book to teach you how to program your computer. Therefore, it is a guide for producing
software.
What is a computer?
What is a program?
A program is a list of instructions that direct the computer in performing its operations. The
computer never does any of its own thinking but merely repeats operations that it has been
instructed to do. It is the program that instructs the computer as to which operations it will
perform and in what sequence it will perform them.
The modern computer evolved from simple calculating machines. Although for centuries
simple arrangements of beads, wheels, and rods had been employed to perform addition and
subtraction, the first large scale effort to design a machine capable of performing higher
IX
mathematical functions was the "Difference Engine" of Charles Babbage, first produced in
1820, which used a complicated system of gears and wheels. The British government later
funded a project to make a large scale version of Babbage's machine, but the project was never
successfully completed.
The first major breakthrough on the way to producing a modern computer occurred in the
early nineteen forties when engineers started to use vacuum tubes to replace mechanical
elements in calculating machines. This innovation resulted in the first fully electronic machine
called the ENIAC (Electronic Numerical Integrator And Calculator), which was built at the
University of Pennsylvania in 1946. Although considerably faster than its mechanical
predecessors, the ENIAC had the major drawback of having its programs wired into the
machine. Huge calculations might take only minutes to solve, but programming the machine
could take many days.
John von Neumann proposed the idea of storing a program in a computer's memory rather
than wiring it. This would eliminate the problem of rewiring the machine each time a new
program was needed. The first computer to use the von Neumann concept was the EDSAC
{Electronic Delay Storage Automatic Calculator) built at Cambridge University in 1949. Other
computers quickly followed with increased speed and efficiency.
The next significant development occurred in the early nineteen sixties with the introduc
tion of transistors into computers to replace the large and inefficient vacuum tubes. This
innovation substantially decreased the size of a computer while increasing its speed and
efficiency. But it is only within the last ten years with the development of integrated circuits to
replace most of the computers components that the computer has decreased both in size and
in price to the point where it is now available to almost anyone desiring one. The computer you
will program is considerably more powerful and efficient than the early computers built only
twenty-five years ago, yet it costs only a tiny fraction of the early machines.
Computer Languages
The first modern computers used a group of commands called machine language. A
command in machine language is just a group of specially coded numbers that the computer
understands. This language is still used today within the computer, but few people ever pro
gram in it. Just as computers advanced, so did programming languages. Today there are
hundreds of higher level programming languages with names like FORTRAN, BASIC,
PASCAL, and PL/I. The computer translates the higher level programming language into
machine language and then executes the program. The purpose of this manual is to present a
comprehensive guide designed to teach the beginner the programming language called BASIC
{Beginners All-purpose Symbolic Instruction Code), developed in the early nineteen sixties by
John Kemeny and Tim Kurtz at Dartmouth College.
BASIC, as the name suggests, is well suited for the beginner. The commands are easy to
remember because they describe the operations they represent. Like any programming lan
guage, BASIC has its specific commands and rules of syntax which determine the form of the
commands submitted to the computer. In addition, the computer will only understand com
mands defined in the higher level language it is using. For instance, in the language BASIC the
command PRINT will direct the computer to send information to the screen, but a similar
command WRITE will not work at all. This similar command WRITE seems to have the same
meaning as PRINT, but the computer will not understand it because WRITE is not defined in the
language called BASIC.
This manual will teach you the specific commands and rules necessary to program your
microcomputer in BASIC.
JMTBQDIICTJDN
TD PROGRAMME
PRINT
LIST
NEW
READ
DATA
GOTO
INPUT
PRINT TAB
REM
PRINT
LIST
NEW
READ
DATA
GOTO
INPUT
PRINT TAB
REM
PRINT
LIST
NEW
READ
DATA
GOTO
INPUT
PRINT TAB
REM
PRINT
Communicating with the computer requires a special language. The language described in
this manual is Commodore BASIC, which consists of simple English words understood by the
computer, In this chapter the user will be introduced to the most fundamental statements
required to write a program on the Commodore computers.
Line Numbering
To establish the sequence of instructions for any given program, the programmer must
assign numbers to each line within a program. This operation is essential because the com
puter reads instructions beginning with the lowest line number, then progresses to the next
higher number and ends with the highest numbered line.
It is permissible to type the program lines out of order because the computer puts them
back into their proper order. For example, line 20 may have been typed before line 10, but when
the program is run, the computer automatically reads line 10 first. Such a system has the
advantage of allowing any forgotten instructions, say between lines 10 and 20, to be entered
later as lines 15, or 12, or 17, etc. For this reason it is best to number the lines of the program in
units of ten (10, 20, 30, etc.) since this leaves nine possible line numbers that can later be
inserted. It is also important to realize that the capital letter O cannot be used in place of zero.
An error in any instruction may be corrected at any time by depressing the RETURN key
and retyping the entire line using the same line number. If two lines are given the same line
number, the computer uses only the last one typed and erases the first. Typing only the line
number followed by the RETURN key eliminates the line entirely. The highest line number
allowed on the computer is 63999.
There are two basic types of information which the computer can use: numbers and words.
What distinguishes one from the other is that a number can be used in a mathematical calcula
tion whereas a word cannot. The PRINT statement is used to print both numbers and words.
Program 1.1
This program uses the PRINT statement at each line to print the results shown below:
10 PRINT 5*3
20 PRINT 12 + 8
30 PRINT 7/2
40 PRINT "SAND"
50 PRINT "5*3"
RUN
15
20
3.5
SAND
5*3
READY.
1-1
Line 10 instructs the computer to print the product of 5 and 3. Note than an asterisk (*) is
used to indicate multiplication. Line 20 adds 12 and 8 whereas line 30 divides 7 by 2, with the
slash (/) indicating division. At line 40 the word SAND is printed. When a word or any set of
characters is printed, it must be enclosed within quotation marks. Line 50 prints "5*3" rather
than 15 because quotation marks are used. Information enclosed in quotation marks is called a
string; therefore, lines 40 and 50 contain strings.
The command RUN is typed after a program has been entered to execute the program, but
it is not part of the program.
Typing Errors
An error in a program can be corrected in one of three ways. First, the program line can be
retyped using the same line number. For example,
40 PRINT "ROCKS"
RUN
15
20
3.5
ROCKS
5*3
READY.
changes only that part of the output which is produced by line 40. The second method of
correcting an error involves the use of the key marked (DEL), which can be used if the error is
detected while the line containing the error is being typed. Pressing the DEL key causes the
computer to erase one character to the left of the cursor on the screen. The third method of
error correction consists in the use of the built in editing feature. To learn how to use this feature
refer to Appendix A.
LIST
The LIST command is used to print the program currently in the computer's memory.
Typing LIST followed by striking the RETURN key will print the entire program; typing LIST
followed by a line number and a RETURN will cause only that line to be printed. To list portions
of a program, type LIST followed by the first and last line numbers of the portion desired,
separating the two numbers with a hyphen (-). For example:
LIST
10 PRINT 5 * 3
20 PRINT 12 + 8
30 PRINT 7 / 2
40 PRINT "ROCKS"
50 PRINT "5*3"
READY.
1-2
LIST 50
50 PRINT "5*3"
READY.
LIST 20-40
20 PRINT 12 + 8
30 PRINT 7 / 2
40 PRINT "ROCKS"
READY.
NEW
Before entering a program into the computer the programmer should use the NEW com
mand to clear the computer's memory. The use of this command insures that program lines
from a previous program do not affect the new program:
LIST
10 PRINT 5 * 3
20 PRINT 12 + 8
30 PRINT 7 / 2
40 PRINT "ROCKS"
50 PRINT "5*3"
READY.
NEW
READY.
LIST
READY.
Observe that after the NEW command is used, a subsequent LIST shows that no program is
currently in the computer's memory.
What is a variable?
One of the most useful properties of a computer is its ability to manipulate variables. A
variable is a name which represents a value. On the computer, as in mathematics, X, Y, and Z
are variables in the expression Z = 10 + X + Y since they can assume many different values.
The computer allows words as well as numbers to be represented by variables.
Numeric Variables
Numeric variables are represented by letters or by letters and numbers. A, D, Al, and B1
are all legal names for numeric variables. The computer allows the use of longer names for
1-3
variables, but for the sake of simplicity only a single letter or a single letter followed by a single
digit will be used in the early chapters of this manual.
To assign a value to a variable the following format is used:
20 X - 5
could be used. Thus, when line 20 is reached, the variable X will be assigned the value 5.
Internally, the computer stores values in memory locations. It is possible to compare these
memory locations to boxes. In this case X is the name of the box, and 5 is the value in the box.
Variables can change in value as the name itself implies; however, it is important to realize
that a variable can hold only one value at a time. Suppose a later statement such as
50 X = 7
50 7 = X
is invalid.
1-4
Program 1.2
This program assigns values to the variables X and Y, the value of Y being dependent
upon the value of X:
10 X = 1
20 Y = 3 * X + 5
30 PRINT X, Y
40 X = 1 5
50 PRINT Y
60 Y = 3 * X + 5
70 PR I NT x. Y
RUN
12 41
15 41
l 5 50
READY.
The value of X is originally 12 at line 10 and then becomes 15 at line 40. Y changes its
value at line 60 because X changed at line 40. Note than when X and Y are printed at line 50, X
is now 15, but Y is still 41 because the variable Y is not changed until it is reassigned at line 60.
A comma is used in the PRINT statements at lines 30, 50, and 70 to allow the values of X and Y
to be printed on a single line. On the Commodore-64 up to four variables can be printed on a
single line of the display by the use of commas to separate each variable name; on the VIC-20
two variables can be printed on a single line.
String Variables
String variables are variables which are assigned values consisting of a sequence of
characters. A character is a symbol found on the computer keyboard, which may be a letter, a
number or any of the special graphic symbols.
String variable names are used in the same way as numeric variable names, except that a
string variable name must end with a dollar sign ($). For example, A$, D$, A1$, C5$ all
represent string variables. To assign characters to a string variable, the programmer must
enclose the characters in quotation marks. For example, the statement
10 A$ = "HARRY"
A$
HARRY
1-5
At some later point in a program it is possible to assign different characters to the same
variable. For example, the statement
50 AS = "SHERRY"
will replace "HARRY" with "SHERRY." Thus, the box named A$ now contains "SHERRY."
A$
SHERRY
Program 1.3
This program assigns two different sets of characters to the string variable
10 B* - "GEORGE"
20 PRINT B*
30 B$ = "JUDY"
40 PRINT B$
50 PRINT "IT IS NICE TO SEE YOU, "5 B$
RUN
GEORGE
JUDY
IT IS NICE TO SEE YOU, JUDY
READY.
Observe that at line 50 a sentence can be formed from two strings, the first of which in this
case is not a variable.
Note that when a semicolon rather than a comma is used to separate items in a PRINT
statement, the items will be printed next to each other on the same line.
Review
2. Write a program that will produce the following output by using string variables for "HARRY'
and "SHERRY" but not for the other words.
RUN
HELLO, HARRY
SHERRY IS LOOKING FOR YOU.
READY.
READ. DATA
A variable may be directly assigned its value not only by a statement such as X = 5 but
also by a combination of READ and DATA statements.
Program 1.4
This program uses READ and DATA statements to assign values to numeric variables:
10 READ X, y, z
20 PRINT X + Y + Z
30 DATA 3, 2, 0.5
RUN
,5
READY.
The READ statement at line 10 instructs the computer to assign numbers to the variables
X, Y, Z. The computer finds these numbers in the DATA statement at line 30 and assigns them
in the order listed {X = 3, Y = 2, and Z = 0.5). If the program contains more than one DATA
statement, the computer starts reading data from the first statement and continues sequentially
through the remaining DATA statements.
In a DATA statement only numbers that are expressed in decimal or scientific form are
acceptable. For example, the numbers .0032, -5.78, 1050, 2.9E5, and 4.76 E-12 are accepta
ble. The E stands for "times ten to the power" (e.g., 5.3 E3 = 5300 and 8.72 E-3 - .00872).
However, data such as the arithmetic expressions 15/3, 3*5, and 7+2 are not permitted in
DATA statements since, unlike PRINT statements, DATA statements allow for no calculations.
GOTO
Suppose that a student has more than one set of values for the variables X, Y, Z in
Program 1.4. To introduce the extra values, the student can retype line 30 as follows:
READY.
Note that only the first three numbers in the DATA statement are processed; the remaining
numbers are not used. To overcome this problem, the programmer can retype line 30 each time
a new set of data is to be used, but this involves unnecessary labor. A GOTO statement
between lines 20 and 30 solves this problem by establishing a loop which allows line 10 to be
used again.
1-7
LIST
10 READ XB Y, Z
20 PRINT X + Y + Z
25 GOTO 10
30 DATA 3, 2, 0.5, 1E2
READY.
RUM
5.5
95.5
Observe that by typing the command LIST the computer prints the current version of
Program 1.4 including the new line. Running Program 1.4 now allows all the data in line 30 to be
processed.
Each time the computer reaches line 25 the GOTO statement causes the computer to
return to line 10 where the next set of data is assigned to the variables. On the first pass through
the loop X -3, Y = 2, Z = .5; on the second pass X - -7, Y - 2.5, Z = 1E2. However, on the
third attempted pass, no additional data is available for assignment to the variables at line 10
and, therefore, an error message is printed.
The location of DATA statements within a program is not important, so they can be placed
anywhere. Good programming style suggests that you place them at or near the end of a
program. When the computer encounters a READ statement, it makes use of DATA statements
regardless of their location. DATA statements may contain strings as well as numbers.
Program 1.5
This program reads the names and grades of three students and prints the averages of
their grades:
RUN
NAME AVERAGE
WATERS 86
KANE 77
MI KAN 69
1-8
Examine this program carefully because it contains a number of important concepts. Line 5
produces the headings for the columns and is placed at the beginning of the program to insure
that the headings will be printed only once. Line 10 assigns a student's name to the string
variable N$ and the student's four grades to the numeric variables A, B, C, D. Unless the
sequence of string variables and numeric variables in the READ statement is the same as the
sequence of strings and numbers in the DATA statement, a -rror will occur. Line 40 returns
the program to line 10 to read more data. What would happen if
40 GOTO 5
Review
4. Write a program containing the DATA line from Program 1.5 which prints only the name and
first grade of each student.
RUN
NAME FIRST GRADE
WATERS 83
KANE 56
MI KAN 61
INPUT
In many instances it is preferable to introduce data from the keyboard rather than place it in
a DATA statement. To do this an INPUT statement is used in place of the READ, DATA
statements. When an INPUT statement is executed, the computer prints a question mark (?)
and then waits for data to be entered.
Program 1.6
Data entered from the keyboard is used to assign a value to the variable X in the following
program:
10 INPUT X
20 PRINT 5 * X * X + 3
30 GOTO 10
1-9
RUN
? 3
48
? 6
18
The GOTO statement at line 30 creates a loop which will continue to run until it is halted.
Ordinarily a program may be halted by pressing the STOP key; however, when a program is
waiting for input from the keyboard, the computer must be reset in order to halt it. To reset the
computer, press the RESTORE key while depressing the STOP key. This operation halts the
run of the program, clears the screen and causes the computer to print READY.
Program 1.7
This program is a revision of Program 1.5. Here a student is asked for his or her name and
four grades. The computer then prints the name and grade average. It is possible to have the
INPUT statement print a question or a remark by enclosing the words to be printed in quotation
marks followed by a semicolon and the variable names. Also, note that more than one variable
can be entered by using a single INPUT statement:
RUN
WHAT IS YOUR NAME? TED
WHAT ARE YOUR GRADES? 87, 54, 76, 95
TED 78
WHAT IS YOUR NAME? JOHN
WHAT ARE YOUR GRADES? 96, 96, 47, 84
JOHN 81.25
WHAT IS YOUR NAME? SHERRY
WHAT ARE YOUR GRADES? 100, 95, 31, 60
SHERRY 71.5
WHAT IS YOUR NAME?
PRINT Formatting
There are a number of ways in which output can be formatted by the use of punctuation. A
few of the more important uses of punctuation are demonstrated by the following program:
1-10
Program 1.8
RUN
NAME GRADES AVERAGE
HAYES3 90 87 93 90
GRAHAM 74 98 83 85
WATSON 53 76 18 49
?GUT OF DATA ERROR IN 10
READY.
Note the output produced by line 5. Each word begins at the beginning of one of the zones
because commas have been used to separate the words. The PRINT at line 30 is used to place
a blank line between each of the printed lines. When printing a number, the computer places a
single space in front of and behind the number. If the number is negative, the space in front is
occupied by the minus (-) sign.
When semicolons (;) are used in place of commas (as in line 40), the output of each
variable begins in the next space following the last variable printed.
Note also that for the VIC-20 only 22 characters per line can be printed. This line is divided
into 2 print zones consisting of 11 characters each.
Program 1.9
This program demonstrates the difference between commas and semicolons used in a
PRINT statement:
1-11
RUN
ZONE 1 ZONE 2 ZONE 3 ZONE 4
**-14 **
** 42 **
-14 42 86 99
READY.
Note how the values -14 and 42 were printed by lines 30 and 50, respectively. Line 70
shows that strings are not printed with a leading or trailing space.
PRINT TAB
The PRINT TAB statement provides an easy way to format output and allows the pro
grammer to begin portions of the printout at specified locations. The left edge of the
Commodore-64 screen is TAB(O), and the right edge of the screen is TAB(39). The left edge of
the VIC-20 is TAB(O), and the right edge is TAB(21). The printing of information at TAB
positions 3, 11 and 17 is accomplished in the following manner:
RUN
THIS IS TAB
READY.
Program 1.10
The substitution of variables for the numbers in the TAB parentheses is permissible pro
vided these variables have previously been assigned values.
10 READ X, Y, Z
20 PRINT TAB(X); "THIS"; TAB(Y); "IS"; TAB(Z); "TAB"
30 DATA 3, 11, 17
RUN
THIS IS TAB
READY.
1-12
Program 1.11
RUN
* *
* *
* *
* *
*
READY.
The PRINT TAB statement moves the cursor to the right only, never to the left. If a TAB
position is specified which is to the left of the current TAB position, the cursor will remain where
it is and the printing will proceed from there.
RUN
READY.
Review
5. Write a program in which you input a value of X and have the computer calculate 5*X and
X/5. The printout should appear exactly as shown below:
RUN
WHAT IS X?
5*X - 60
X/5 ■ . 4
WHAT IS X? 20
5#X ■ 100
X/5 = 4
WHAT IS X? 64
5*X ■ 3 20
X/5 = a 2.8
WHAT [S X?
1-13
6. Write a program which allows you to input your name and the name of a friend and then
produces the printout as follows:
RUN
WHAT IS YOUR NAME? BRUCE
WHAT IS YOUR FRIEND'S NAME? JUDY
JUDY IS A FRIEND OF BRUCE
Immediate Mode
The computer may perform simple tasks using the immediate mode rather than a program.
An immediate mode instruction is typed without a line number. When the computer receives a
command without a line number, it recognizes that the command is not part of a program but is
to be executed immediately. The following are examples of immediate mode statements:
PRINT (3*5) + 4
19
READY.
PRINT 7/9
.777777778
READY.
A = 5
READY.
B = 2
READY.
PRINT A + B + 4
11
READY.
A$ » " BETTY"
READY.
PRINT A*; " BOO"
BETTY BOO
READY.
Note that a RUN command was not used in any of the preceding examples. Most com
mands are permissible in the immediate mode with the notable exception of the INPUT state
ment. In performing most tasks it is best to write complete programs and to reserve the use of
immediate mode for simple calculations.
1-14
REM
The REM statement is used in the body of a program to allow the programmer to introduce
explanatory remarks. Everything to the right of a REM statement is ignored by the computer
when the program is run. For example,
will be printed only when the program is listed. Remarks placed strategically within a program
are useful in explaining the function of various parts of the program.
Program 1.12
This program incorporates the major topics covered in this chapter, which the reader
should now be familiar with, and demonstrates how they might be used together in a single
program.
RUN
HOW FAR OVER IS EACH ITEM
TO BE PRINTED? 7
THIS
IS
A
SAMPLE
OF
THE
MATERIAL
IN
CHAPTER
ONE
1-15
EXERCiSES
RUN
A
B
C
ABCD
READY.
2. Write a program which makes the following calculations. Check the results by hand
computation:
10 A = 3
20 PRINT "THE VALUE OF B"
30 B = A + 4*4
40 PRINT B
4. How many lines of output does the following program produce before an error message
appears indicating "?OUT OF DATA ERROR IN 10"?
10 READ A,B,C
20 PRINT (A+B+C)/3
30 GOTO 10
40 DATA 11,32,42,14,25,36,47
50 DATA 58,39,50,61,22,83,94
5. Peter Kolodnigork has loused up once again. Here is a program of his which he says
"mysteriously doesn't work." Give Peter a hand and correct this monstrosity for him so that
the output looks like the following:
1-16
THE SUM IS 20
THE SUM IS 14
?OUT OF DATA ERROR IN 10
10 READ A B
20 PRINT THE SUM IS A+B
30 GOTO 12
40 DATA 12,8,3*5,5
10 READ A*
20 PRINT A*
30 GOTO 10
40 DATA S,I,X!," 6",6
7. Write a program in which the price (P) in cents of a loaf of bread and the number (N) of
loaves bought are entered from the keyboard. The total spent for bread is to be printed in
dollars and cents.
8. Write a program which will enter your weight (W) in pounds and height (H) in inches and
which then will print the quotient W/H followed by the words "POUNDS PER INCH."
9. Using an INPUT statement, write a program which produces the following output:
RUN
? 2,4
X « 2 Y ~ 4 X*Y ■ S
? -8,70
X =-8 Y » 70 X*Y = ~560
10. Predict the output of the following program. Check the answer by running the program:
10 P* = "TOTAL PRICE"
20 P - .89
3(3 PRINT P*3 " = *0";P
10 READ ASB»C,D
20 PRINT A,B
30 PRINT CS" "5D
40 DATA 3E2,510p3E-lp.51
1-17
13. Self-proclaimed computer whiz Cecil Cedric Cenceless has typed the following gibberish in
the immediate mode and has challenged anyone to guess the output correctly before he or
she presses the RETURN key. Put Cecil in his place and correctly predict the answer:
RUN
12345678901234567890
* 9 ?
READY.
10 A* » "ABCD"
20 B$ » "XYZ"
30 F = 7
40 g * -4
50 PRINT A*;B*
60 PRINT A*;;F
70 PRINT FSB*
80 PR: I NT 6 5 B*
16. Write a program to evaluate each of the following expressions for A = 10 and B = 7:
(7A + 10B)/2AB
17. In the first week of the season the cross country team ran the following number of miles
each day: 2, 3,4, 3, 5. Write a program to calculate and print the total mileage for the week.
18. A piece of pizza normally contains about 375 calories. A boy jogging one mile uses about
100 calories. Write a program that asks him how many pieces he wishes to eat and then
tells him how far he must run to burn up the calories he will consume.
RUN
HOW MANY PIECES DID YOU EAT? 4
YOU MUST RUN 15 MILES.
READY.
19. Have the computer evaluate the expression 12x + 7y for the following data:
X 3 7 12
y 2 9 -4
20. Write a program that will allow a string A$ to be entered. Then have the computer print the
string followed by " KEEPS THE DOCTOR AWAY."
1-18
21. Using an INPUT statement, write a program that will compute the volume of a room given
its length, width, and height.
22. Write a program to compute the areas (cm-) of circles with radii 5.0 cm., 3.0 cm. and 8.0
cm. Have the output in the form "AREA OF CIRCLE^" with two spaces between each of
the printed lines.
24. With the equation E = MC-, Einstein predicted that energy could be produced from matter.
If the average human hair weighs a tenth of a gram and the town of Woodsylvania uses 2 x
10" units of energy in a day, find out how many hairs from Einstein's head would be
required to supply the town for a day (C^3x 101")-
25. Use the computer to calculate your library fines. Enter the number of books you have
borrowed and how many days late they are. Have the computer print the amount of your
fine if you are charged 10C per day per book.
26. The perimeter of a triangle is equal to the sum of the lengths of the three sides of the
triangle. The semiperimeter is one-half of the perimeter. A triangle has sides of lengths 13
cm, 8 cm, 11 cm. A second triangle has sides of 21 ft, 16 ft, 12 ft. Write a program that
reads these measurements from a DATA statement and then prints the semiperimeter of
each triangle, showing the correct units. The output should look like this:
27. Professional athletes have succeeded in making staggering sums of money through care
ful negotiations. Of course, the real winner is Uncle Sam, who does not negotiate at all.
Write a program which asks for a player's name and salary and then prints the player's
name, take-home salary and taxes if the tax rate for his income bracket is 44%
PUN
WHAT IS THE PLAYER'S NAME?
RUN
WHAT IS THE PLAYER7S NAME? JUGGIE RACKSON
WHAT IS JUGGIE RACKSON'S WAGE 150000
JUGGIE RACKSON WOULD KEEP $ S4000
HE WOULD PAY $ 66000 IN TAXES.
READY.
RUN
WHAT IS THE PLAYER'S NAME? DOPEY
WHAT IS DOPEY*8 WAGE 4200
DOPEY WOULD KEEP * 2352
HE WOULD PAY $ 1B4S IN TAXES.
READY.
1-19
28. Sale prices are often deceptive. Write a program to determine the original price of an item,
given the sale price and the discount rate.
RUN
SALE PRICE? 3.78
DISCOUNT RATE? 10
THE ORIGINAL PRICE WAS * 4.2
READY.
29. The area of a triangle can be found by multiplying one-half times the length of the base
times the length of the altitude (A = .5 * base * height). Write a program that allows the
user to enter from the keyboard the base and altitude of a triangle and then skips a line
before printing out the area of the triangle.
RUN
WHAT IS THE BASE? 10
WHAT IS THE ALTITUDE? 5
THE AREA IS 25
READY.
30. A state has a 7 percent sales tax. Write a program that will allow you to INPUT the names
and prices (before taxes) of different items found in a department store and then print the
item, tax, and the price of the item including tax.
RUN
ITEM'S NAME? COAT
WHAT IS ITS PRICE" 65
COAT HAS A TAX OF * 4.55 AND COSTS $ 69.55
ITEM'S NAME? TENNIS RACKET
WHAT IS ITS PRICE? 23
TENNIS RACKET HAS A TAX OF * 1.61 AND COSTS $ 24.61
ITEM'S NAME?
31. In an election in Grime City candidate Sloth ran against candidate Graft for mayor. Below is
a listing of the number of votes each candidate received in each ward. What total vote did
each candidate receive? What percentage of the total vote did each candidate receive?
2 313 721
3 1003 822
4 413 1107
5 516 1700
32. A Susan B. Anthony dollar of diameter 2.6 centimeters rests on a square postage stamp as
shown. Have the computer find the area in square centimeters of the part of the stamp not
covered by the coin.
1-20
33. Given the assumption that you sleep a healthy 8 hours a night, have the computer print the
number of hours of your life which you have spent sleeping. Input the date of your birth and
today's date in numeric form (e.g., 6, 4, 62). Use 365 days in each year and 30 days in a
month.
34. Using an INPUT statement, write a program which averages each of the following sets of
numbers: (2, 7, 15, 13); (8, 5, 2, 3); (12, 19, 4); (15, 7, 19, 24, 37). Note thatthe sets do not
contain the same number of elements.
1-21
loops
IF...THEN
AND OR
END
FOR...TO
STEP
NEXT
RESTORE
IF...THEN
AND OR
END
FOR...TO
STEP
NEXT
RESTORE
IF...THEN
AND OR
END
FOR...TO
STEP
NEXT
RESTORE
IF...THEN
AND OR
END
FOR...TO
STEP
NEXT
RESTORE
The statements presented in Chapter 1 allow the user to perform routine calculations and
to print numbers or strings in different formats. The computer executes routine calculations
according to specific rules of precedence calied Order of Operations. The higher capabilities of
a computer are not called upon until the computer is used to make decisions or to carry out a
process many times. This chapter will first outline the Order of Operations and then present the
conditional statement IF... THEN, which allows the computer to make simple decisions.
Finally this chapter will introduce the statements FOR... TO... STEP, NEXT, which allow
loops to be established in a convenient manner.
Order of Operations
What is the value of 2 + 20/4? Should the 2 be added first to the 20 and then the division
performed afterward, or should the 20 first be divided by 4 and then be increased by 2? The
latter procedure is correct because division is carried out before addition. When parentheses
are used, the operations in the innermost parentheses are completed first. For example, (2 +
20)14 = 22/4 = 5.5.
The computer performs arithmetic operations in the same order as that employed by
mathematicians. Quantities in parentheses are evaluated first (starting from the innermost),
followed by raising to a power, then by multiplication and division, and finally by addition and
subtraction. Operations of equal priority are carried out from left to right. For example:
6/3*2 The result is 4. Although the answer might seem to be 6/6 = 1, the
computer starts at the left and performs the division first and then the
result of the division is multiplied by 2.
3*(5 + 6) The result is 33. The computer first adds 5 and 6 and then multiplies
the sum by 3.
5 + (3*(6/2)) The result is 14. The computer first divides 6 by 2, the operation within
the innermost parentheses. Next it multiplies that result by 3 and
finally adds 5.
12 + 4/0 The result is an error message. The computer does not divide by zero.
2|3| 2 The result is 64, just as it would be for (2f 3)f 2. Again, the left-to-right
rule is in operation. Remember that t is used to raise to a power.
IF... THEN
The statements introduced in Chapter One (GOTO, PRINT, etc.) are called unconditional
because the computer will always execute them. In contrast, the IF... THEN statement is
conditional because the action taken depends upon whether the condition is found to be true.
2-1
The simplest form of the IF... THEN statement is:
The 'condition' portion of the statement compares two quantities which must be separated by
one of the symbols indicated in the table below:
SYMBOL MEANING
equal to
> greater than
< less than
> = greater than or equal to
<= less than or equal to
<> not equal to
20 IF X > 5 THEN 60
When the condition in line 20 (X is greater than 5) is true, the computer jumps to line 60. When
the condition is false, as when X is less than or equal to 5, the computer proceeds to the next
line of the program.
Program 2.1
This program determines whether the value entered for X is the solution to the equation
2X - 18 = 0. The computer decides which of two messages is to be printed:
10 INFUT X
20 IF 2*X-18=0 THEN 50
30 PRINT X;"IS NOT THE SOLUTION"
40 GOTO 10
50 PRINT X;"IS THE SOLUTION"
RUN
? 15
15 IS NOT THE SOLUTION
? 4
4 IS NOT THE SOLUTION
? 9
9 IS THE SOLUTION
READY.
Note the necessity of line 40. Without it, the program would print "IS THE SOLUTION"
even when the solution was not X. The line number sequence that the computer follows when X
2-2
is the solution is 10, 20, 50; and when X is not the solution, it follows the line number sequence
10, 20, 30, 40, 10.
The IF ... THEN statement can be used to compare two strings. Here the symbols greater
than (>), less than (<), equal to (=), etc., now refer to an alphabetical rather than a numerical
order.
Program 2.2
The following program determines if A$ is alphabetically before, the same, or after B$:
10 PRINT
20 INPUT "ENTER TWO STRINGS";A*,B*
30 IF A*=B* THEN 70
40 IF A*>B* THEN 90
50 PRINT A*; " IS BEFORE ";B*
60 GOTO 10
70 PRINT A$; " IS EQUIVALENT TO ";B*
80 GOTO 10
90 PRINT A* " IS AFTER " ; B*
100 GOTO 10
RUN
Line 30 directs the computer to line 70 if A$ and B$ are equivalent. Line 40 causes a jump
to line 90 if A$ comes after B$ in the alphabet. Line 50 is reached only if both conditions in lines
30 and 40 fail and, therefore, A$ comes before B$ in the alphabet.
In the preceding section the simplest form of the IF... THEN statement was given as:
2-3
More flexible usage of IF ... THEN permits a statement instead of a line number to follow the
word THEN. This means that the statement after the condition will be executed only if the
condition is true. The form is:
The following examples illustrate legal use of the IF... THEN statement:
The computer allows a series of statements to be entered on a single program line if they
are separated from each other by colons (:). Multiple statement lines have special meaning
when used with IF ... THEN. All statements following THEN will be executed when the condi
tion following IF is true. No statements following THEN will be executed when the condition is
false. For example,
has two statements on one line. If the condition X = 5 is true, then "GOOD" will be printed and
program control will be passed to line 80. If the condition is false, neither of these actions is
taken. Instead, the program will continue on to the line following line 60. This means either the
PRINT "GOOD" and the GOTO 80 statements are executed, or neither is executed. Whichever
of the two occurs depends upon whether the condition X = 5 is true.
Program 2.3
10 INPUT X
20 IF 2*X-18=0 THEN PRINT X;"IS THE SOLUTION": GOTO 10
30 PRINT X;"IS NOT THE SOLUTION": GOTO 10
RUN
? 15
15 IS NOT THE SOLUTION
7 2
2 IS NOT THE SOLUTION
? 9
9 IS THE SOLUTION
Note that the statement GOTO 10 in line 20 is executed only if the condition in the IF ...
THEN statement is true. Otherwise the program proceeds to line 30. The statement GOTO 10
in line 30 will always be executed if line 30 is reached since it is not preceded by an IF ... THEN
statement on the same line.
2-4
Review
1. Allow two numbers, A and B, to be entered in the computer and then print the two numbers
in descending order.
RUN
ENTER TWO LAST NAMES? PATRICK,GREER
GREER
PATRICK
ENTER TWO LAST NAMES?
AND. OR
The statement modifiers AND and OR can be used in the IF... THEN statement when
more than one condition is to be considered. The statement
will cause a transfer to line 50 only if both conditions are true. On the other hand, the statement
20 IF X > 5 OR Y = 3 THEN 50
will cause program control to be transferred to line 50 if either or both conditions are true.
Program 2.4
The following program uses the OR modifier and reviews much of what has been
presented:
2-5
RUN
WHO ARE YOU? BRAVE SIR ROBIN
THIS MISSION IS NDT MEANT FOR YOU!
READY.
Line 10 asks the user for a name. The name entered as N$ is compared with the two
names at line 20. If N$ is either 'JAMES BOND' or '007', then the program skips to line 50.
Otherwise, a message is printed by line 30 and the program returns to line 10. At line 50 a
warning message is printed whereas line 60 inquires whether Mr. Bond is alone. Note that in
line 70 any response other than 'YES' will cause the program to print 'TRY LATER' and jump
back to line 10. Otherwise, the mission description is printed by lines 80 through 110.
END
The END statement is used to terminate the run of a program. For example,
80 END
will cause the run of a program to stop when line 80 is reached. It is possible to place END
statements at more than one location within a program, including insertion in an IF... THEN
statement.
Program 2.5
This program uses the END statement to terminate program execution when the name
KERMIT is input:
RUN
WHAT IS YOUR NAME? CYNTHIA
IT'S GOOD TO MEET YOU, CYNTHIA
READY.
2-6
Review
3. Write a program that will allow a number N to be entered. If the number is between 25 and
112, then the computer should indicate this; otherwise, the computer should say that the
number is out of range.
RUN
ENTER A NUMBER? 14
14 IS OUT OF RANGE
ENTER A NUMBER? 54
54 IS BETWEEN 25 AND 112
ENTER A NUMBER? 112
112 IS OUT OF RANGE
ENTER A NUMBER?
4. Write a program in which the user enters a string N$. If it comes alphabetically before
Garbage or after Trash, then have the computer print "YES"; otherwise have it print "NO".
The FOR ... TO ... STEP, NEXT statements provide a simple way of establishing a loop.
A loop is a section of a program designed to be executed repeatedly. The FOR... TO...
STEP, NEXT loops provide a method for generating a large sequence of numbers in a case
where each number in the sequence differs from its predecessor by a constant amount. The
general form of the FOR ... TO... STEP, NEXT statement is:
NEXT <variable>
Note that the 'variable1 after FOR and NEXT must be the same. A string variable cannot be
used in FOR ... NEXT loop. The STEP portion may be omitted if the increment equals +1.
For example:
10 FOR X = 2 TO 6
■40 NEXT X
2-7
-70 FOR HI = N*2 TO 26 STEP + 2
100 NEXT H1
180 NEXT T
Note that a loop is formed by the FOR... TO... STEP and NEXT statements. In the
example,
30 FOR N - 3 TO 11 STEP 2
80 NEXT N
the variable N starts at line 30 with a value of 3. N retains the value of 3 until the NEXT N
statement is encountered at line 80. At this point N is increased by the STEP value. In this
example N changes from 3 to 5 to 7, etc. All the statements in the lines occurring between lines
30 and 80 are executed in sequence during each consecutive pass through the loop. The
program continues to return from line 80 to the line immediately following line 30 until N
exceeds the specified limit of 11. At this point the program exits from the loop and moves on to
the line following 80.
Program 2.6
This program uses READ, DATA, whereas Program 2.7 uses a FOR .TO ... STEP,
NEXT loop to print all integers between 10 and 30, inclusive.
10 READ N
20 PRINT N;
30 GOTO 10
40 PRINT " DONE"
50 DATA 10,11,12,13,14,15,16,17,18
60 DATA 19,20,21,22,23,24,25,26,27
70 DATA 28,29,30
RUN
10 1 1 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30
?0UT OF DATA ERROR IN 10
READY
2-8
Program 2.7
10 FDR N - 10 TO 30
20 PRINT N;
30 NEXT N
40 PRINT " DONE
RUN
10 11 12 13 14 15 16 17 18 19
20 21 22 23 4
24 25 26 27 28 29
30 DONE
READY.
Program 2.6 continues to read data until all of it is exhausted. Since N is incremented by 1,
the STEP portion is omitted. Program 2.7 generates all of the values of N between 10 and 30.
Note that the loop in Program 2.7 is completed by a NEXT statement, not a GOTO statement.
Therefore, unlike Program 2.6, Program 2.7 can proceed to line 40.
Indentation is used in program 2.7 to clarify the contents and boundaries of the FOR ...
NEXT loop. This practice is recommended since it clarifies the program's structure. After typing
the line number you can indent the contents of the line by typing the letter I while depressing the
Commodore (c=) key. This will cause a graphic character to appear, which may be ignored
since it will not appear when the program is listed. The space bar may now be used to indent
the line to the desired position.
Program 2.8
This program finds solutions to the compound condition 5X + 3 < 100 and 2X2 - 1 > 50
and tests all odd integers from 1 to 25:
10 FDR X = 1 TO 25 STEP 2
20 IF 5*X+3<100 AND 2*X "2-1>50 THEN PRINT X;
30 NEXT X
40 PRINT " DONE"
50 END
RUN
7 9 11 13 15 17 19 DONE
READY.
Note that the symbol (f) is used to denote 'raised to the power1 (e.g., X f 2 means X*X).
Lines 10 and 30 create a loop for testing the conditions located at line 20. The loop starts at line
10 with X = 1. Each time the program reaches the NEXT X statement at line 30, X is in
cremented by the STEP value, which is 2. The program will then return to line 20 unless the
value of the loop variable X has exceeded its maximum value of 25, at which point the loop will
be exited. Remember that a FOR loop is not completed by a GOTO statement but by a NEXT
statement.
2-9
Program 2.9
The following program illustrates the use of a negative STEP value. The integers from 1 to
10 are printed in descending order:
10 FDR X = 10 TO 1 STEP -1
20 PRINT X;
30 NEXT X
40 PRINT
50 END
RUN
10 9 8 7 6 5 4 3 2 1
READY.
Review
5. Write a program that prints the integers between 1 and 25, inclusive.
6. Using a FOR ... TO... STEP, NEXT loop, have the computer print the following:
RUN
20 IS 16 14 12 10
READY,
7. Write a program that will allow a number N to be entered. Using N as a STEP value, print
numbers between 8 and 20.
RUN
STEP VALUE? 2
8 10 12 14 16 18 20
READY.
RESTORE
At times the user might find it desirable to employ a set of data more than once. The
RESTORE statement makes it possible to read data again starting at the beginning of the data.
For example,
40 RESTORE
causes the next READ statement encountered to read data starting with the first item in the first
DATA statement.
2-10
Program 2.10
This program searches DATA statements for a specific student and then prints the stu
dent's grades. It employs the RESTORE statement so that each time a student's name is
entered a searching process starts at the beginning of the first DATA statement. How would the
program run if line 20 were deleted?
5 PRINT
10 INPUT "NAME"; B$
20 RESTORE
30 FOR P - 1 TO 6
40 READ N*,A,B,C,D
50 IF N$^B$ THEN 80
60 NEXT P
70 PRINT "STUDENT "HE*;!" NOT FOUND" : GOTO 5
B0 PRINT N$; " HAS THE FOLLOWING GRADES:"
90 PRINT A;B;C;;D
100 GOTO 5
110 DATA WATERS,83,75,92,80,TRANTER,74,81,92,76
120 DATA SAVAGE,72,31,63,60,RICKARD,99,84,92,87
130 DATA MULRYAN,100,93,82,S9,LEMONE,94,93,85,94
140 END
RUN
NAME? RICKARD
RICKARD HAS THE FOLLOWING GRADES:
99 84 92 87
NAME? LEMONE
LEMONE HAS THE FOLLOWING GRADES:
94 93 85 94
NAME? BROWNE
STUDENT BROWNE NOT FOUND
NAME? MULRYAN
MULRYAN HAS THE FOLLOWING GRADES:
100 93 82 89
NAME? SAVAGE
SAVAGE HAS THE FOLLOWING GRADES:
72 81 63 60
NAME? WATERS
WATERS HAS THE FOLLOWING GRADES:
83 75 92 80
NAME?
2-11
Program 2.11
This program incorporates the major topics covered in this chapter, which the reader
should now be familiar with, and demonstrates how they might be used together in a single
program.
RUN
WORD TO SKIP? CHAPTER
THIS
IS
A
SAMPLE
OF
THE
MATERIAL
IN
TWO
REPEAT? YES
REPEAT? NO
READY.
2-12
EXERCJEES
1. Write a program to allow two numbers (A and B) to be entered. Have the computer
compare them and print a message stating whether A is less than, equal to, or greater than
B.
2. Write a program which allows three names to be entered as A$, B$ and C$. Have the
computer print the name which is alphabetically last.
3. Perform each of the following computations on paper. Check your results by using im
mediate mode on the computer.
(A) 3 + 2 + 3 (B) 5 - 4 + 2
(C) 3*(5 + 16) (D) 5 + 3 *6/2
(E) 640/10/2 * 5 (F) 5 + 3 *4 - 1
(G) 2 + 3+2 (H) 2+(3+2)
(I) 64/4 * 0.5 + ((1 +5)* 2 + 3) * l/(2 *4)
4. Write a program which prints six exclamation marks if BIGWOW is entered for the string X$
but which otherwise prints six question marks. The program is run until interrupted by the
user.
5. Use only one line number to enter two strings (A$ and B$) and to print output similar to the
following:
RUN
? START,FINISH
START FINISH
FINISH START
READY.
6. Allow a number (X) to be entered. Print the message "NOT BETWEEN" if X is either less
than -24 or greater than 17. Only one IF... THEN statement is permitted.
7. Allow a string (A$) to be entered. Print the message "A$ IS BETWEEN" If A$ comes
between "DOWN" and "UP" alphabetically. Only one IF... THEN statement is permitted.
2-13
8. Allow a number (X) to be entered. Print "IN THE INTERVAL" if X satisfies the inequality
25 < X < 75, but otherwise print "NOT IN THE INTERVAL." Only one AND and one IF ...
THEN statement are to be used.
10. Use only one PRINT statement to produce the following rectangle:
RUN
************
************
************
READY.
11. Print the cubes of the odd integers from 11 to -11, inclusive, in descending order.
12. Print all the integers which end in 4 from 4 to 84, inclusive.
14. Write a one line Immediate Mode command for each of the following:
(A) Find the value of 143 x 74.
(B) Find the average of 53. 72, 81 and 76.
(C) Find which is larger, X T Y or Y t X, when X = 4 and Y = 5.
15. Print all of the integers in the set 10, 13, 16, 19,... 3 94, 97.
RUN
*****
***
***
***
***
**■*
***
*****
READY.
17. Below is a list of various creatures and the weapon necessary to destroy each:
Creature Weapon
Lich Fire Ball
Mummy Flaming Torch
Werewolf Silver Bullet
Vampire Wooden Stake
Medusa Sharp Sword
Triffid Fire Hose
Using READ and DATA, have the computer state what weapon is to be used to destroy a
given creature.
2-14
18. Menacing Matilda has written the following program using too many GOTO statements and
cannot figure out in what order the lines of the program will be executed. Assist her by
listing the line numbers in the sequence in which the computer will execute them:
10 READ A.B
20 IF A>4 OR B>4 THEN 50
30 IF A<1 AND B<1 THEN 60
40 GOTO 7(3
50 X - A+B : GOTO 80
60 X - A*B : GOTO 80
70 X = A/B
80 IF X>1 THEN PRINT X : GOTO 10
90 DATA 5,3,-1,-2,0,2
19. John Doe's brother Jim has been assigned the following program for homework. Jim is not
in shape today, so assist him by stating the exact order in which the lines of the following
program are to be executed:
10 READ A,B,C
20 S - A+B*C
30 IF S=10 THEN RESTORE : READ S
40 PRINT S,
50 IF S=14 THEN END
60 GOTO 10
70 DATA 4,2,3,6,0,2,7
20. Write a program which asks for a person's age. If the person is 16 years or older, have the
computer print "YOU ARE OLD ENOUGH TO DRIVE A CAR." Otherwise, have the com
puter indicate how many years the person must wait before being able to drive.
RUN
HOW OLD ARE YOU? 16
YOU ARE OLD ENOUGH TO DRIVE A CAR.
READY.
21. The Happy Holiday Motel has 10 rooms. Have the computer print a label for each room's
door indicating the room number. For example:
RUN
22. As candidate for mayor, you are very busy. Use the computer to print thank you letters to
10 people who have contributed money to your election campaign. Be sure to mention the
exact amount each person has contributed.
2-15
RUN
SMILEY R. POLITICO
RUN
X X--2 X-3
2 4 8
4 16 64
6 36 216
8 64 512
10 100 100(3
READY.
24. The Bored Auto Company has done it again! Some models of their cars may be difficult to
drive because their wheels are not exactly round. Cars with model numbers 102, 780,119,
229, 189, and 195 have been found to have a defect. Write a computer program that allows
10 of their customers to enter the model number of their car to find out whether or not it is
defective.
25. Using only two print statements, write a program to print a triangle that in N lines high and N
columns wide. For example:
RUN
**■*■*■
READY.
2-16
26. Write a program that will produce the following triangle. The figure is centered on TAB(10):
RUN
* *
READY.
27. The following table contains employee performance data for the Tippecanoe Typing
Company:
Employee Performance
Oakley 69%
Howe 92%
Anderson 96%
Wol ley 88%
Goerz 74%
Tippecanoe Typing is suffering from financial difficulties and needs to cut back on its staff.
Using READ, DATA and a loop, have the computer print notices of dismissal for any
employee whose production performance is below 75%.
RUN
DEAR OAKLEY,
I AM SORRY THAT I MUST FIRE YOU.
YOU HAVE BEEN SUCH A FINE EMPLOYEE
WITH A PERFORMANCE RATING OF 69 "/.
I'M SURE YOU'LL HAVE NO TROUBLE
FINDING ANOTHER JOB.
SINCERELY,
GEORGE SHWABB
DEAR GOERZ,
I AM SORRY THAT I MUST FIRE YOU.
YOU HAVE BEEN SUCH A FINE EMPLOYEE
WITH A PERFORMANCE RATING OF 74 "X
I'M SURE YOU'LL HAVE NO TROUBLE
FINDING ANOTHER JOB.
SINCERELY,
GEORGE SHWABB
READY.
2-17
28. Wayne Peber bought stock two years ago and wants to use the computer to calculate his
profit or loss. He bought 200 shares of Consolidated Technologies at $85.58 per share and
400 shares of American Amalgamated Securities at $35.60 per share. Today C.T. is worth
$70.82 a share and A.A.S. is worth $47.32 a share. What is his profit or loss?
29. The Exploitation Oil Company uses the computer to determine the weekly wages of its
employees by inputting the hours worked and the hourly wage for each employee. If the
employee works over 40 hours, he or she is paid one and a half times the hourly rate for
each additional hour.
RUN
HOURS WORKED? 45
HOURLY WAGE? 10.00
THE WAGE FOR THE WEEK IS $ 475
READY.
30. The Last Chance Finance Company is charging a rate of 2% per month on all loans it is
making. Write a program that allows Last Chance to calculate the monthly payments
charged a customer using the following formula:
L# I
Monthly Payment = .
RUN
THE AMOUNT OF THE LOAN? 100
LENGTH OF THE LOAN IN YEARS? 5
THE MONTHLY PAYMENT IS $ 2.87679654
TOTAL AMOUNT FAID WILL BE * 172.607792
READY.
31. You have $200.00 to spend on a buying spree. Write a program that, as you buy merchan
dise, subtracts the cost and the appropriate sales tax (5%) from your remaining money and
shows your present total. The program should prevent you from buying items that cost
more than you have.
RUN
HOW MUCH DOES THE ITEM COST? 10.00
YOUR TOTAL IS NOW $ 189.5
READY.
32. Have the computer find all odd integers from 5 to 25 which are simultaneous solutions of
the inequalities X:! > 500 and X- + 3X + 2 < 700. Print only the solutions.
2-18
COMPUTER GOMES
RND
INT
POS
TIME
GET
RND
INT
POS
TIME
GET
RND
INT
POS
TIME
GET
RND
INT
POS
TIME
GET
RND
INT
POS
TIME
GET
RND
INT
POS
This chapter will introduce material which should be interesting, practical and entertaining.
In fact, the emphasis will be placed on techniques to involve the user in computer games, which
are often the most enjoyable way to learn computer programming.
RND
In many computer simulations that involve science problems and also in a variety of
computer games, the process of generating random numbers is essential. The RND function
generates random numbers on the computer. The statement
X = RND(O)
Program 3.1
10 FDR I = 1 TO 4
20 PRINT RND(0),
30 NEXT I
RUN
.335939109 .0234396458
. 218750238 . 15234524
READY.
INT
The statement A = INT(X) sets A to the largest integer that is not greater than X. This
function does not round off a positive number but simply truncates its decimals. In the case of a
negative number, it takes the next lower negative integer. For example:
At times it is preferable to have the computer pick random integers instead of long random
decimals. This can be accomplished by using INT. The following formula can be used to assign
X a random integer between A and B, inclusive:
3-1
For example, the statement
X = INT(26*RND(0) + 75)
Program 3.2
This game program selects a random number from 1 to 100 and then gives the player an
unlimited number of chances to guess it. After each guess the computer informs the player that
the guess is too high, too low or correct.
RUN
I'M THINKING OF A RANDOM NUMBER FROM 1 TO 100.
WHAT IS YOUR GUESS? 50
TOO LOW!
WHAT IS YOUR GUESS? 75
TOO LOW!
WHAT IS YOUR GUESS? 86
TOO LOW!
WHAT IS YOUR GUESS? 90
THAT IS CORRECT!!!
READY.
Review
1. Write a program that will generate 2 random integers between 50 and 150 and find their
product.
RUN
134 MULTIPLIED BY 110 IS 14740
READY.
2. Write a program similar to Program 3.2 which picks a random number between 1 and 50,
inclusive, and gives the player only five attempts to guess it.
3-2
RUN
I'M THINKING OF A RANDOM NUMBER FROM 1 TO 50
WHAT IS YOUR GUESS? 25
TOO LOW!
WHAT IS YOUR GUESS? 37
TOO LOW!
WHAT IS YOUR GUESS? 44
TOO HIGH!
WHAT IS YOUR GUESS? 40
TOO LOW1
WHAT IS YOUR GUESS? 41
TOO LOW!
YOU'VE HAD 5 GUESSES NOW.
THE NUMBER WAS 42
READY.
Summation
If the programmer decides to keep score for the number guessing game (Program 3.2),
some technique will have to be devised to keep count of the number of guesses taken. One
possible technique is to use a summation statement of the form:
30 A - A + 1
The statement A = A + 1 makes no sense in mathematics since A can equal A but not A +
1. The computer, however, interprets the equal sign to mean "is replaced by" rather than "equal
to", and each time it encounters line 30 above, it takes the present value of A, adds 1 to it, and
makes that sum the new value of A.
Program 3.3
This program demonstrates how the summation statement works by printing the values of
the variable A until the program is halted with the STOP key:
10 A = A + 1
20 PRINT A;
30 GOTO 10
RUN
12345 678 9 10 11 12
13 14 15 16 17 18
BREAK IN 20
READY.
10 A = A + 5
3-3
then 5 will be added to A each time the statement is encountered.
10 A = A + 5
RUN
5 10 15 20 25 30 35 40 45 50
55 60 65 70 75 80
BREAK IN 20
READY.
In this problem the initial value of A is zero for both runs because the computer sets any
undefined numeric variables to zero at the start of a run.
Program 3.4
Here, Program 3.2 has been modified to record the number of turns required to guess the
random number. In this case the variable A acts as a counter, increasing in value by 1 after
each guess:
RUN
I'M THINKING OF A RANDOM NUMBER FROM 1 TO 100.
WHAT IS YOUR GUESS? 50
TOO LOW!
WHAT IS YOUR GUESS? 75
TOO HIGH!
WHAT IS YOUR GUESS? 67
TOO HIGH!
WHAT IS YOUR GUESS? 59
THAT IS CORRECT!!!
THAT TOOK YOU 4 GUESSES.
READY.
Rounding Errors
Because the computer has a finite capacity, any numerical computations involving infinitely
repeating decimals cannot be accurate (for example, 1/3 = .3333..., which the computer
truncates to a limited number of digits). Since the computer uses binary numbers (0 and 1), any
fraction whose denominator is not an integral power of 2 (2, 4, 8, 16) will be an infinitely
repeating decimal and therefore will be truncated by the computer. In Chapter Eight binary
numbers are examined in greater detail.
3-4
Program 3.5
10 FOR X = l TO 1500
20 A = A + (1/2)
30 B = B + (1/3)
40 NEXT X
50 PRINT "A = ";A
60 PRINT "B = ";B
RUN
A - 750
B = 500.000023
READY.
The final value of A is the result of adding Vfe 1500 times, which comes out to exactly 750.
B, however, which is the result of adding Vz 1500 times, does not come out to exactly 500
because of the rounding error. At times the computer does not recognize an equality when one
in fact exists. If the line
were added to the above program, then the computer would not print the word "EQUAL."
Review
3. Select 50 random integers between 0 and 9, inclusive, and have the computer tell how many
of the numbers were from 0-4 and how many were from 5-9.
RUN
THERE WERE 22 NUMBERS BETWEEN 0 AND 4.
THERE WERE 28 NUMBERS BETWEEN 5 AND 9.
READY.
POS
The POS function is used to find the current horizontal position of the cursor. The
statement
X - POS(O)
will assign X a value corresponding to the horizontal position (the current TAB position) of the
cursor on the screen. On the Commodore-64, X = 0 for the left edge and 39 for the right edge.
On the ViC-20, X = 0 for the left edge and 21 for the right edge.
3-5
TIME
The variable TIME is set by the computer to the number of "jiffies" which have elapsed
since the computer was turned on. A jiffy is equal to 1/60 of a second. For example,
T = TIME
sets the variable T equal to the number of jiffies accumulated since the computer was turned
on.
Program 3.6
This program checks how long it takes a student to respond to a multiplication problem,
awarding 100 points if the student answers correctly within 1 second and subtracting 20 points
for each additional second taken:
10 X - INT(12*RND(0) + 1)
20 Y - INT<12*RND<0> + 1)
30 PRINT "WHAT IS";X;"*";Y
40 Tl = TIME
50 INPUT A
60 T2 ■ TIME
70 IF AOX*Y THEN PRINT "INCORRECT, YOU GET 0 POINTS" : END
80 T = INT< (T2-TD/60 + .5)
90 PRINT "THAT TOOK YDU";T;"SECONDS."
100 IF T>3 THEN PRINT "YOU GET 0 POINTS." : END
110 PRINT "YOU GET";20*<6-T);"POINTS."
RUN
WHAT IS 6 * 7
42
THAT TOOK YOU 2 SECONDS.
YOU GET 80 POINTS.
READY.
When the computer executes line 40, the current time in jiffies is assigned to the variable
T1. After the answer has been entered at line 50, the current time at that point is assigned to T2
at line 60. The elapsed time in jiffies, the time taken to respond, is the difference between T2
and Tl. Line 80 converts this elapsed time from jiffies to the nearest second.
GET
The GET statement is used to input a single digit or character from the keyboard. Its for
mat is:
GET <variable>
3-6
Unlike the INPUT statement, the character struck is not printed and it is not followed by striking
the RETURN key. When a GET statement is executed, the computer immediately checks the
keyboard to see what key is being pressed and assigns the variable that value. If no key has
been struck when a GET statement is executed, then numeric variables are assigned 0, and
string variables are assigned a null("") character. For example,
100 GET A$
Program 3.7
This program requires the user to type an X to complete the printing of a limerick. Note the
use of the GET statement at line 70:
RUN
THERE ONCE WAS A CAT
NAMED HARRY,
WHO WISHED HE COULD
CATCH A CANARY,
(PRESS X TO CONTINUE)
ONE DAY IN THE HOUSE,
HE SAW A MOUSE,
AND SOON THE TWO
WERE MARRIED
READY.
Game Programs
Two game programs are presented here which the programmer should study carefully and
then attempt to modify to write other game programs.
3-7
Program 3.8
In the game of NIM, two players in turn take matches from a pile originally containing
twenty matches. Each player may take either 1 or 2 at a time. The player who takes the last
match wins the game. The computer's strategy is simple. If the computer goes first, it will take 2
matches. If the player is allowed to go first, then the computer will match the player's first move.
Thereafter, in either case, the computer will select a number of matches so that the total of the
player's previous selection and the computer's is 3. For example, if the player picks 2, the
computer will pick 1. The following program plays NIM with the user, randomly deciding who
goes first:
RUN
HERE I HAVE TWENTY MATCHES.
EACH PLAYER MAY TAKE EITHER
1 OR 2 AT A TIME. THE PLAYER
WHO TAKES THE LAST MATCH WINS
YOU GO FIRST.
20 MATCHES REMAIN.
HOW MANY MATCHES DO YOU WANT?
COMPUTER TAKES 2
16 MATCHES REMAIN.
HOW MANY MATCHES DO YOU WANT?
COMPUTER TAKES 1
13 MATCHES REMAIN.
3-8
HOW MANY MATCHES DO YOU WANT?
COMPUTER TAKES 1
10 MATCHES REMAIN.
HOW MANY MATCHES DO YOU WANT?
COMPUTER TAKES 1
7 MATCHES REMAIN.
HOW MANY MATCHES DO YOU WANT?
COMPUTER TAKES 1
4 MATCHES REMAIN.
HOW MANY MATCHES DO YOU WANT?
COMPUTER TAKES 1
1 MATCHES REMAIN.
HOW MANY MATCHES DO YOU WANT?
YOU WIN1
READY.
The random number generated at line 60 determines who will go first. If the computer goes
first, then lines 70 and 80 are executed, forcing the computer to select 2 matches. Otherwise, if
the player goes first, control is passed to line 130. A GET is used at line 160 to input the player's
choice. Note that a PRINT statement is used at line 180 so that the player can see his or her
response. Remember that the GET statement does not print the keyboard input. Line 170
insures that only 1 or 2 matches are taken by the player and that the number of matches
selected does not exceed the number of matches remaining. The computer's choice, based on
the player's previous choice, is calculated at line 100. The sum of the two moves should be 3.
Program 3.9
This program simulates a roulette wheel, which has two colors (red and black) and thirty
numbers. The player is asked to make a bet and pick a color and number. Picking the correct
color returns the bet; picking the correct number but wrong color wins thirty times the bet, and
picking the correct number and color wins the player sixty times the bet. Why would a casino
using this roulette wheel be highly unprofitable?
3-9
100 REM
110 REM SPIN ROULETTE WHEEL
120 Nl = INT(30*RND<0) + 1)
130 Cl ■ INT<2*RND<0) + 1)
140 PRINT "THE WHEEL STOPPED ON:"; Nl;
150 IF Cl = 1 THEN PRINT "RED" : GOTO 200
160 PRINT "BLACK" ! REM C = 2
200 REM
210 REM COMPUTE WINS OR LOSSES
220 M » -B : REM ASSUME PLAYER LOST
230 IF Nl = N THEN AND Cl » C THEN 270
240 IF Nl - N THEN PRINT "YOU GOT THE NUMBER" : M - 30*B ! GOTO 300
250 IF Cl - C THEN PRINT "YOU GOT THE COLOR" : M = B : GOTO ZM*
260 PRINT "YOU LOSE. BETTER LUCK NEXT TIME1" : GOTO 300
270 PRINT "CONGRATULATIONS! YOU GOT BOTH!" : M « 60*B
300 REM
310 REM TELL PLAYER OF WINS OR LOSSES
320 IF M < 0 THEN PRINT "YOU LOST *";-M I GOTO 340
330 PRINT "YOU NOW HAVE *" 3 M+B
340 PRINT "WHY NOT TRY AGAIN?" : END
RUN
WHAT NUMBER (1-30)? 27
WHAT COLOR, (R)ED OR (B)LACK? R
WHAT IS YOUR BET? 200
THE WHEEL STOPPED ON: 6 RED
YOU GOT THE COLOR
YOU NOW HAVE $ 400
WHY NOT TRY AGAIN?
READY.
RUN
WHAT NUMBER (1-30)? 32
WHAT COLOR, (R)ED OR (B)LACK? B
WHAT IS YOUR BET? 100
THE WHEEL STOPPED ON: 3 RED
YOU LOSE. BETTER LUCK NEXT TIME!
YOU LOST * 100
WHY NOT TRY AGAIN?
READY.
Lines 20 through 70 prompt the gambler for a number between 1 and 30, a color (red or
black), and his or her bet. Line 80 insures that the gambler does not attempt to defraud the bank
by placing a negative bet. This simulated roulette table has a $1000 limit, which is strictly
enforced by line 90. The actual 'spin'of the roulette wheel takes place at lines 120 and 130. The
player's winnings {or losses) are computed in lines 220 through 270. Note that line 270 is
reached only if both conditions are satisfied in the IF... THEN statement at line 230, which
determines if both the color and number were matched by the player. Line 260 is reached only if
the player incorrectly guessed both the color and the number, conditions which are checked by
lines 240 and 250. Lines 320 and 330 inform the gambler of his or her good (or bad) fortune.
Note that a GET is used at line 40 rather than INPUT so that only a single letter can be
entered. If INPUT were used and the user responded by typing 'RED' rather than just 'R' as
instructed, the comparison at line 60 would fail.
3-10
EXERCJSE5
1. Generate ten random numbers between 0 and 1, but print only those which are greater
than 0.5.
2. Generate three random numbers between 0 and 1, and print their sum.
3. Input a number (N). Print it only if it is an integer. (Hint: compare N with INT(N)).
4. Allow a user to guess a random integer between -3 and 4, inclusive. Print whether the
guess was correct or not. If the guess was wrong, the correct value is also to be printed.
5. Determine randomly how many coins you find on the street. You are to find from 2 to 5
nickels, 1 to 4 dimes and 0 to 3 quarters. Lunch costs 99 cents. The program is to report the
amount that you found and whether you are able to buy lunch with it.
RUN
YDU FOUND * .95
SORRY, YOU CAN'T BUY LUNCH
READY.
RUN
YOU FOUND * 1.15
YOU CAN BUY LUNCH
READY.
6. Input an integer (N), and print the sum of N random numbers between 0 and 1. Also print
N/2 for comparison with the sum.
7. A child puts pennies into a piggy bank once each week for four weeks. The bank already
contains 11 pennies in it when the child first receives it. Write a program to allow pennies to
be added each week and to print the dollar value of the bank's contents after each addition.
8. Write a program that will act as a stopwatch. Use the GET and TIME commands to produce
output similar to the following:
3-11
RUN
PRESS S TO START AND AGAIN TO STOP
THE STOPWATCH IS RUNNING
ELAPSED TIME - 6.35 SECONDS
READY.
9. Write a program that will print ten random integers from -10 to 10, inclusive.
10. Write a program to flip a coin 50 times and print the total number of heads and tails. Run
the program ten times to get a comparison among the runs.
11. Les Brains wrote both of the following programs but has forgotten what their output is.
Determine the output and check your answer by running the program:
(a) 10 for Z - l to 3
20 A = A+Z
30 PRINT A
40 NEXT Z
50 A - A+Z
60 PRINT A
(b) 10 G - 123.456
20 PRINT INT(10 * G>/10, INT(10 * G + .5)7100
30 PRINT INTU00 * 6)/100, INT(100 * S + ,.5>/100
40 END
12. Write a program that generates 10 random integers betwen 8 and 25, inclusive, and prints
them on the same line. The output should be similar to the following:
17 12 22 25 8 17 19 II 21 23
13. Make a chart showing in their correct order the values taken by the variables X and Y.
Circle those values that are printed by the computer. Check by running the program.
10 FOR X = i TO 3
15 READ Y
20 IF Y>0 THEN 35
25 Y = Y + X
30 IF X=2 THEN Y = Y - 1 : GOTO 40
35 PRINT X,Y
40 NEXT X
45 DATA 5,0,-1
3-12
10 A = INT(10 * RND(0) + 1)
20 B = INT(10 * RND(0) + 1)
30 PRINT TAB<7);A;"*";B;"=";
40 INPUT C
50 IF C = A * B THEN 80
60 PRINT "YOU ARE WRONG, TRY AGAIN."
70 GOTO 30
80 PRINT TAB<12);"CORRECT"
15. Write a program that contains one FOR ... NEXT loop which finds the sum of all the odd
integers from 13 to 147, inclusive. The output should be as follows:
16. Suzy Fowlup, one of the slower members of the computing class, wrote the following
program. It allows the user to enter at the keyboard any integer greater than 1 and to have
the computer tell the user whether or not the integer is prime. A prime number is an integer
that contains only itself and 1 as factors. The computer tests the integer by repeatedly
dividing it by integers smaller than itself but larger than 1 and checking whether the
quotient is whole. If so, the integer entered by the user is not prime. The program contains
three errors. Find them, rewrite the program and run it. The output should look like this:
RUN
INTEGER > 2 PLEASE? 12
THAT INTEGER IS NOT PRIME.
READY.
RUN
INTEGER > 2 PLEASE? 17
THAT INTEGER IS PRIME.
READY.
17. Generate 1000 random integers between 1 and 9, inclusive, and print how many were
even and how many were odd. The output should be similar to the following:
RUN
THERE WERE 559 ODD INTEGERS.
THERE WERE 441 EVEN INTEGERS.
READY.
3-13
18. Write a program that allows the user and computer to select alternately integers between 3
and 12, inclusive, keep a sum of all the integers selected and declare the winner to be the
one who selects that integer which makes the sum greater than 100. Have the program ask
the user if he or she would like to proceed first or second.
19. A bank pays interest once a year at a yearly rate of 5%. A man deposits $1000 on January
1, 1983 and wishes to leave it there to accrue interest until the balance is at leat $2000.
Compute the balance on Jan. 1 of each year, starting with 1984 and ending in the year
when the balance exceeds $2000. The output should resemble the following:
DATE BALANCE
JAN 1, 1985 $ 1050
JAN 1, 1986 $ 1102.5
* 1979.93
* 2078.93
20. Input a positive integer N, and print all positive integers that are factors of N. The output
should resemble the following:
RUN
A POSITIVE INTEGER, PLEASE? 1.4
YOUR NUMBER WAS NOT AN INTEGER
A POSITIVE INTEGER- PLEASE? 12
1 2 3 4 6 12
READY.
21. Print the radius (cm.) of a sphere, given its volume (cm.:J). Round off the results to the
nearest hundredth:
22. (a) Print twenty random integers between 0 and 100, inclusive.
(b) Change the program so that sixty percent of the twenty integers printed will be less
than 25.
23. Using the POS function, write a program that determines the length of a string.
RUN
YOUR STRING? 02-1335
OZ-1335
THE LENGTH OF DZ-1335 IS 7
READY.
24. Write a program to simulate the rolling of a pair of dice. (Each has six sides labeled with the
numbers 1 through 6.) For each of the rolls add the two values obtained, calling the sum S
(note that S may vary between 2 and 12). Roll the dice 100 times and print the average
value of S.
3-14
25. Write a program that will pick 20 random integers from 1 to 100, inclusive, and print only
those numbers that are prime. A prime number is one that can be only divided exactly (i.e.
no remainder) by itself and 1.
26. You are to write a program to simulate a simplified version of the game 21. A deck of cards
numbered from 1 to 10 are used and any number can be repeated since the deck contains
many cards, the computer starts by asking you how many cards you want. It then deals you
the cards, which are randomly picked, and totals their value. If the value exceeds 21, you
automatically lose. If your value is under 21, the computer deals itself three randomly
picked cards. The winner is the one with the highest score equal to or less than 21. Write
your program so that the game can be played 10 consecutive times with the winner of each
game winning one dollar. At the end of the 10 games print out the total winnings for you and
the computer. The example below shows only the last three of the ten games:
READY.
27. Have the computer randomly select a number of quarters (from 0 to 7), dimes (from 0 to 4)
and pennies (from 0 to 9) and print the exact number of coins and their total value. The user
has three chances to determine how many quarters, dimes and pennies were selected.
28. The following table shows production output per day for each employee of Fazioli's Pizza
Parlor. Plot a bar graph showing the output for the week for each of Fazioli's employees:
RUN
SCALE: * = 5 PIZZAS
PAPA ********************
DELLACONA ****************************
RICARDO ************************
FERRARA *****************************
READY.
3-15
NESTED LOOPS flND
SUBSCRIPTED UflRJfiBLES =
DIM
CLR
DIM
CLR
DIM
CLR
DIM
CLR
DIM
CLR
DIM
CLR
DIM
CLR
DIM
CLR
DIM
CLR
DIM
CLR
DIM
CLR
DIM
CLR
DIM
DIM
CLR
DIM
We have previously observed that the FOR... TO... STEP, NEXT statements set up
loops. This chapter proceeds further by showing how to combine two or more loops in such a
way as to place one loop inside another.
The second part of this chapter deals with subscripted variables, which use a fixed variable
name in conjunction with a variable subscript (e.g. A(N), where A is fixed and N varies). This
technique enables a program to deal conveniently with a large amount of data. Subscripted
variables usually employ FOR... NEXT loops to generate the values for the subscripts.
The concept of a FOR ... NEXT loop was presented in Chapter Two. In this chapter, the
concept of nested FOR ... NEXT loops (that is, one loop placed, or 'nested' within another) is
introduced. For example:
-10 FOR P = 1 TO 20
-20 FORQ = 3 TO 10
-30 NEXT Q
-40 NEXT P
By definition nested loops must never cross. One loop must be contained entirely within
another or be entirely separated from another. For example, the following arrangement is not
permissible because the loops cross each other:
—10 FOR P = 1 TO 20
—20 FOR Q = 3 TO 10
—30 NEXT P
—40 NEXT Q
When this program is run, the following error message will result:
Program 4.1
This program uses nested loops to print a portion of the multiplication table:
10 FDR X = 1 TO 5
20 FOR Y - 2 TO 3
30 PRINT X; "*"; Y; " = "; X*Y,
40 NEXT Y
50 PRINT
60 NEXT X
RUN
1*2 = 2 1*3 = 3
2*2 = 4 2*3 = 6
3*2 = 6 3*3 = 9
4*2=8 4*3= 12
5*2= 10 5 * 3 = 15
READY.
4-1
Line 10 establishes the outer X loop and starts X with the value 1. X retains this value until
it is incremented by the execution of line 60. Line 60 is not executed, however, until the inner Y
loop, lines 20-40, has run its entire course. X therefore retains the value 1 while Y changes from
2 to 3. When the Y loop has finished its cycle of two passes, line 60 is executed, incrementing X
to 2. The program returns to line 20 and starts the Y loop over again at its initial value of 2.
Whenever a program encounters the FOR ... TO statement of a loop, the loop variable is reset
to its initial value. Since this program does not return to line 10, the X loop is never reset to 1.
Notice that Y will take on its values of 2 and 3 five times. Indentation is used in the above
program in order to clarify the program's structure, and the contents of each loop are indented
to clarify the boundaries of the loop. Remember, to indent a line, type the I key while depressing
the Commodore ( c=) key immediately after typing the line number. The space bar may then be
used to indent the line to the desired position.
Program 4.2
This program calculates and prints all possible combinations of quarters, dimes and nic
kels that add up to fifty cents:
10 PRINT "QUARTERS","DIMES","NICKELS"
20 FDR Q = 0 TO 2 : REM QUARTERS
30 FOR D = 0 TO 5 : REM DIMES
40 FOR N = 0 TO 10 : REM NICKELS
50 IF Q*25+D*10+N*5=50 THEN PRINT Q. D, N
60 NEXT N
70 NEXT D
80 NEXT Q
RUN
QUARTERS DIMES NICKELS
0 0 10
0 1 a
0 2 6
0 3 4
0 4 2
0 5 0
1 0 5
1 1 3
1 2 1
2 0 0
READY.
Q represents the number of quarters, D the number of dimes and N the number of nickels.
There may be anywhere from 0 to 2 quarters in a combination. Similarly, there may be any
where from 0 to 5 dimes and from 0 to 10 nickels. Three nested loops ensure that every
possible combination that might work is checked at line 50.
4-2
Review
1. Use nested loops to produce the following output. The outer loop runs from 20 to 24, and the
inner loop runs from 1 to 3:
RUN
OUTER LOOP: 20
INNER: 1 INNER: 2 INNER: 3
OUTER LOOP: 21
INNER: 1 INNER: 2 INNER: 3
OUTER LOOP: 22
INNER: 1 INNER: 2 INNER: 3
OUTER LOOP: 23
INNER: 1 INNER: 2 INNER: 3
OUTER LOOP: 24
INNER: 1 INNER: 2 INNER: 3
READY.
The major purpose of subscripted variables is to store easily and later retrieve large
quantities of data. Programs 4.3 and 4.4 do not use subscripted variables but demonstrate
when contrasted with later programs how useful subscripted variables are.
Program 4.3
This program generates ten random numbers from one to twenty, inclusive:
10 FOR X m l TO 10
20 Y = INT(20 * RND(0) + 1)
30 PRINT Y;
40 NEXT X
RUN
5 14 1 16 20 13 20 11 17 17
READY.
Every time a new value is assigned to Y, it replaces the previous value for Y. Since the
previous values of Y are not remembered, it is impossible to prevent repetition by comparing
the old values of Y with the new value of Y. If a box analogy is used here, the first two cycles of
Program 4.3 would appear as follows:
Y
Y = RND 1st cycle
14
Y = RND 2nd cycle
4-3
Program 4.4
This program prints four random numbers between 1 and 20, inclusive, without any repeti
tion. The technique can be expanded to have the program choose 10 numbers if the user is
willing to type the program lines required:
10 Yl = INT(20 * RND(0) + 1)
20 PRINT Yl;
30 Y2 ■ INT(20 * RND(0) + 1)
40 IF Y2 » Yl THEN 30
50 PRINT Y2;
60 Y3 = INT(20 * RND(0) + 1)
70 IF Y3 = Y2 OR Y3 = Yl THEN 60
80 PRINT Y3;
90 Y4 ■ INT(20 * RND(0) + 1)
100 IF Y4 = Y3 OR Y4 = Y2 OR Y4 ■ Yl THEN 90
110 PRINT Y4
RUN
13 17 12 IS
READY.
The similarity between the three sets of lines 30-50, 60-80 and 90-110 is obvious. In each
set the first line selects a random number between 1 and 20, inclusive, and the second line
checks to see if the number is a repetition of a number previously chosen. If this is the case,
then execution goes back to the first line in the set so that another number may be chosen.
Finally, the third line of the set prints the random number selected. The use of subscripted
variables will eliminate the need for the repetition of these sets.
In mathematics a set of single subscripted numeric variables (e.g., Xi, , X2, X3,... ) Is
symbolized by a letter and a subscript, which is written below the line of the letter. On the
computer the same set of subscripted variables would be referred to as X(1), X(2), X(3) and so
on, where the integer enclosed in parentheses is the subscript.
The name for a set of single subscripted numeric variables consists of one of the usual
numeric variable names, followed by the parenthesized subscript. For example, A(1), B2(17)
and X(8) are all legal subscripted variable names. Similarly, single subscripted string variables
names such as Z$(5), Y1$(20) and M$(14) are acceptable.
The subscript variable L(2) isnof the same as the variable L2. Furthermore, the subscript is
a part of the variable name and must not be confused with the value of the variable. For
example, in the statement L{5) = 32 the subscript is 5 and the value of L(5) is 32.
4-4
Program 4.5
This program illustrates the difference between the subscript and the value of a sub
scripted variable:
10 L(1) - 7
20 L (2) =5
30 L(3) - 4
4i£i PRINT "L<1) = "; LCI), "L(2) =";L<2>, "L(3> ="; L(3)
50 PRINT "HI i- 2) = "; L < 1 + 2)
60 PRINT "LU) + L(2) = "; LCD + L(2)
70 X - 2
B0 PRINT "L(X> =»"! L(X)
RUN
L (1) = 7 L(2)=5 L<3)=4
L (1 + 2) ^4
L (1) + L(2) m 12
L ( X) « c.5
READY.
L(2) L(3)
Lines 50 and 60 point out the difference between adding two subscripts and adding the
values of two variables. L(1 + 2) is identical to L(3) and therefore has a value of 4. L{1) + L(2)
calls for the values 7 and 5 to be added, thus producing a total of 12. Since the subscript X
equals 2 in line 80, a value of 5 is printed. As can be seen, it is permissible to use a numeric
variable as the subscript of a subscripted variable.
Program 4.6
Like Program 4.3, this program selects 10 random numbers between 1 and 20 and makes
no attempt to prevent repetition. Yet unlike Program 4.3, it stores the numbers chosen in a
subscripted variable:
10 FDR X - 1 TO 10
20 R<X) = INT(20 * RND(0) + 1)
30 NEXT X
40 PRINT "TEN RANDOM NUMBERS HAVE BEEN STORED IN R<>."
50 PRINT
60 FOR N = 1 TO 10
70 PRINT "R<"SNJ ") HAS A"; RCN); "STORED IN IT."
80 NEXT N
4-5
RUN
TEN RANDOM NUMBERS HAVE BEEN STORED IN RO.
READY.
This program has two loops which are not nested but which follow one another. Each loop
is executed 10 times. In the first loop line 20 chooses a random number and stores it in one of
the subscripted R() variables. The first time through this loop (X - 1) a random number is
stored in R(1);the second time (X = 2), a new number is stored in R{2) and so on repeating 10
times. After the above run of this program, the R() boxes had contents as follows:
The second loop (lines 60 through 80) prints the contents stored in the boxes.
The ability to store numbers in this way will allow the writing of a new program to choose 10
random numbers without repetition. By checking whether a chosen random number equals any
of those previously selected, a program can determine whether to accept the random number
chosen or to make another selection.
4-6
Program 4.7
This program uses nested loops and subscripted variables to pick 10 random numbers
between 1 and 20 without repetition:
10 FDR X ■ 1 TG 10
20 Y (X) = INT (20 * RND<0> + 1)
30 IF X =
1 THEN 70
40 FOR Q =
1 TO X-1
50 IF Y< X ) a Y CQ) THEN 20
60 NEXT Q
70 PRINT Y ( X) ;
80 NEXT X
RUN
2 20 12 4 11 9 14 5
READY.
Line 20 selects a random number between 1 and 20, inclusive, and stores it in one of the
subscripts of Y{). Since Y(1) is the first random number, line 30 is included to insure Y(1) will be
printed immediately because it is obviously not a repeat of another number. Lines 40 to 60
constitute a nested loop which determines if a number just chosen, Y(X), is equal to any of the
previously chosen numbers, Y(1) through Y(X-1). The X-1 in line 40 insures that Y(X) is not
rejected by being checked against itself. If X rather than X-1 were used, then Q would eventu
ally equal X. Line 50 would determine that Y(X) was a repeated number when Q equalled X and
would then mistakenly return to line 20.
There is an additional reason for including line 30. When X and Q are equal to 1, Y(X) will
equal Y(Q), and without line 30, program flow would continuously return to line 20.
Program 4.8
The following program will randomly read a list of 5 names into a subscripted string
variable N$() without repeating any of the names:
10 FOR X = 1 TO 5
20 Y = INT(5 * RND(0) + 1)
30 IF N*(Y)<>"" THEN 20
40 READ N*(Y)
50 NEXT X
60 FOR Z = 1 TO 5
70 PRINT N*(Z)
80 NEXT Z
90 DATA TED,JOHN,MARY,DON,SUSAN
RUN
SUSAN
DON
JOHN
TED
MARY
READY.
4-7
RUN
MARY
SUSAN
TED
JOHN
DON
READY.
This program reads the names in the DATA statement in order but randomly places them
in N$(1) to N$(5). Repetition is avoided by checking each new box as it is selected to discover
whether it contains a name. If it is full, a new box is tried by selecting a new random number.
The consecutive double quotation marks ("") at line 30 are used to check whether the box is
empty. Unassigned subscripted string variables, which are empty, are represented on the
computer by ("").
Review
2. Using subscripted variables, write a program in which 3 numbers are input. Then have the
computer type them back in reverse order.
RUN
? 4
? 6
? 1
1
6
4
READY.
3. Six words are to be entered from the keyboard. Have the computer randomly select and
print four of the words as a "sentence" (which may or may not make sense). Repetition of
words is allowed.
RUN
JACK
? AND
JILL
RAN
AWAY
SCREAMING
JACK SCREAMING AWAY AWAY .
READY.
4. Modify the program of the previous exercise so that words are not repeated.
RUN
JACK
AND
JILL
RAN
AWAY
HAPPILY
AND AWAY RAN JACK .
READY.
4-8
DIM
Whenever the highest subscript of a subscripted variable exceeds 10, the computer must
be informed. The DIM statement is used to direct the computer to reserve enough space in
memory to accommodate the anticipated input. Its format is:
DIM <variable>(<dimension>)
For example, Program 4.8 could be changed to store 100 names by making the appropriate
changes in several lines and adding the following line:
5 DIM N$(100)
The dimension may be either a numeric constant or a numeric variable. For example,
It is possible to request more space (i.e. boxes) in memory than the computer can supply.
This results in the following error message:
It is a good idea to place DIM statements at the beginning of a program because the DIM
statement must be executed before more than 10 subscripts of a subscripted variable have
been used. Though it is possible to have several DIM statements in a program, each sub
scripted variable may only be dimensioned once. If there are two DIM statements for the same
variable or if a DIM statement is executed more than once, the error message
will result.
CLR
100 CLR
4-9
Program 4.9
This program demonstrates the effect of CLR on variables stored in the computer's
memory:
10 A=47.9
20 R$="THIS IS AN EXAMPLE OF CLR"
30 T<4>-3.1416
40 PRINT A;R$;T<4>
50 CLR
60 PRINT
70 PRINT A!!R*;T(4) ; "WHAT HAPPENED TO THE VARIABLES?"
RUN
47.9 THIS IS AN EXAMPLE OF CLR 3.1416
READY.
The computer can also use double subscripts to name a variable. This is similar to single
subscripting except that there are two numbers within the parentheses instead of one. For
example,
B3(7,3) CS(4,9)
are all double subscripted variables. The programmer can visualize the space in memory for a
double subscripted variable as an array of rows and columns, rather than in a single column (as
in the case with a single subscripted variable). This procedure provides a convenient technique
for dealing with problems in which the data are two-dimensional in nature, such as the location
of seats in a theater.
10 DIM N*(4)
20 FOR L = 1 TO 4
30 READ N*(L)
40 PRINT N*(L)
50 NEXT L
60 DATA KAREN LEMONE
70 DATA DAVID MULRYAN
80 DATA BRUCE TRANTER
90 DATA CAROL SAVAGE
4-10
The box analogy will help the programmer understand more clearly how the double sub
scripted variable operates. The first integer in the subscript identifies the row and the second
the column in which the variable is located. For example, A(2,3) is located at the second row,
third column:
Row 1
Row 2
Row 3
Program 4.10
A classroom has 5 rows of seats with 3 seats to a row. The following program randomly
assigns a class of 14 students to seats, leaving one seat empty:
1 0 DIM N*<5,3 )
20 FOR X ■ 1 TO 14
30 READ A*
40 R * INT< 5 * RIMD ( 0 ) + 1 )
50 C - INTC 3 * RND (0) + 1)
S,II it
60 IF N*(R, C)< THEN 40
70 N$(R,C) *
80 NEXT X
90 FOR Rl ■ 1 TO 5
100 FOR Cl — \
TO
1 10 IF N* (Rl ,C1): ="" THEN PRINT "EMPTY", s GOTO 130
120 PRINT N$ (Rl, Cl) ,
130 NEXT Cl
140 PRINT
150 NEXT Rl
160 DATA ANNE, DON, SHERRY, MAGGIE, TED, LIZ, ROB
170 DATA MARY, DAVID, MARK, KEVIN, SUSAN, WENDELL, CINDY
4-11
RUN
MARY ROB EMPTY
CINDY DON MAGGIE
DAVID SHERRY SUSAN
WENDELL LIZA KEVIN
MARK TED ANNE
READY.
The computer also allows 3, 4, etc., all the way up to 46 dimensions in a subscripted
variable (e.g., DIM X(5,5,8,2,3,1)). However, the more dimensions that a subscripted variable
has, the smaller each dimension must be because of the limited amount of space available in
the computer's memory.
Review
5. Six numbers are to be input from the keyboard and stored in the subscripted variable X().
These are subsequently to be printed in a vertical column, and then a second time, closely
spaced on a single line.
RUN
67
128
1 37
' 42
> 143
67
128
37
42
143
23 67 128 37 4! 143
READY.
6. Use the double subscripted variable X$(I,J) for which the row variable I runs from 1 to 5 and
the column variable J from 1 to 3. Enter the letters A, B, C as the first row, D, E, F as the
second, up to M, N, O as the fifth. Have the program print the following, making the rows
become columns (Hint: Use READ, DATA):
RUN
A D G J M
B E H K N
G F I L 0
READY.
4-12
Some Final Notes on Subscripted Variables
Subscripted string and numeric variables greatly enhance the programmer's ability to store
and deal with large quantities of data within any one program run. It must be remembered,
however, that if the program is run again, all of the stored data in the computer's memory is
erased. This means that all of the boxes become either null ("") or zero at the start of the next
run. A method for permanently storing data is presented in Chapter 9.
Previously, variable names have consisted of a single letter or a single letter followed by a
digit. As was pointed out in this chapter, these names may also be subscripted. Actually,
variable names may be of any length. For example, ALPHABET, HAROLD, SCARE and
BLACKBEARD23 are all permissible variable names. There are, however, drawbacks in these
names. Nowhere in the name of a variable may any key word occur. For example, SCORE,
FORTUNE, SAND and DIMWIT are all unacceptable variable names because they contain the
words OR, FOR, AND and DIM, respectively. Also, no matter how long the variable name may
be, the Commodore considers only the first two characters. This means the variable names
XMIN and XMAX are considered the same because they both start with XM. Because of these
drawbacks, it is recommended that extended variable names not be used except where they
are useful in identifying what a variable represents.
4-13
EXERCISES
1. Using a nested loop, have the computer print a rectangle consisting of eight lines of thirty
asterisks each.
2. Show the output of the following program and check by running it. Rerun the program after
removing line 50:
10 FOR I - 1 TO 5
20 FOR J = 1 TO 2*1 - 1
30 PRINT "."•
40 NEXT J
50 PRINT
60 NEXT 1
3. Enter values of X(l) for I = 1 to 6. Print the values of I and X(l) in two columns with I
proceeding in the order 1, 3, 5, 2, 4, 6.
4. Enter 15 letters of the alphabet (not necessarily different) and print them in reverse order
as a single block of letters.
5. Have the computer compute the values of A(I,J), where A(I,J) = 3* I + J*J, I varies from 1
to 4, and J varies from 1 to 12. The user is to input a number N from 1 to 4 so that all values
of A(N,J) can be printed.
6. Using a DATA statement, have the computer enter one letter of the alphabet for each
member of A$(I,J), where I runs from 1 to 11 and J from 1 to 3. The letters are first to be
printed in the form of an 11 word sentence, each word consisting of 3 letters. Then, the
letters are to be printed again as a 3 word sentence, each word consisting of 11 letters. The
words may or may not make sense.
7. Les Brains, who has forgotten where the computer is, needs to know the output for the
following programs. Predict the output in each case and check by running the program.
(a) 10 FOR Ll - 1 TO 3
20 FOR L2 = 5 TO 6
Z0 PRINT L1,L2
40 NEXT L2
50 NEXT Ll
4-14
(b) 10 FOR X - 10 TO 15 STEP 2
20 FOR Y - 15 TO 10 STEP -2
30 IF Y=X THEN 99
40 IF X<Y THEN PRINT X : GOTO 60
50 PRINT Y
60 NEXT Y
70 NEXT X
99 END
8. Suzy Fowlup has done it again and has written another program that will not run properly.
Assist her by correcting the program. The output should look like this:
RUN
3 4
4
4
er
READY.
10 FOR A - 3.5
20 FOR B '■= 1,4
30 IF A * B 10 GOTO 50
40 PRINYAB
50 NEXT A
60 NEXT B
9. The following program is designed to print the numbers in the DATA statement in decreas
ing order. However, there are some errors in the program. Correct and run the program to
produce this output:
RUN
40 37 27 27 16 9 8 5 :
READY -
10 i rOR X - 40 TO 1
20 FOR Y ~ 1 TO 10
30 READ N
40 IF N ■ X THEN PRINT NS
50 NEXT X
60 ME XT Y
70 DATA 5,27,37,16,27,8,2,40,1,9
4-15
10. What is the exact output for the following program?
10 READ Bi,B2,B3,B4,B5,B6
20 FOR X - 1 TO 6
30 READ B(X)
40 NEXT X
50 PRINT "B4=";B4;M BUT B(4)=";B(4)
60 PRINT Bl + B2 + B3,
70 PRINT B<1) + B(2) + B(3)3B<1+2+3)
B0 DATA 3,7,4,1,8,12
90 DATA 14,42,69,86,12,111
11. The following program is designed to generate random integers between 1 and 99, inclu
sive, until it encounters a duplicate. At that point it should print how many numbers it has
found and then print all of them. However, there are a number of errors in the program.
Correct them to produce output similar to:
RUN
DUPLICATE AFTER 9 NUMBERS
95 47 71 87 1 25 12 10 95
READY.
20 FOR X = 1 TO 100
30 N(X) - INT(99*RND(0)+1)
40 FOR Y « 1 TO 1(50
50 IF N(X) <> N<Y) THEN 70
60 PRINT "DUPLICATE AFTER";X;"NUMBERS"
70 FOR 2 = 1 TO X : PRINT N(X); : NEXT 2
80 NEXT Y
90 NEXT X
12. Write a program that reads the names, street addresses, towns and zip codes of five
people into subscripted variables N$(X), A$(X), T$(X) and Z${X). The user enters a name,
and the program prints the full name and address of that person. If the name is not there,
have the program print PERSON NOT FOUND.
13. A Pythagorean triple is a set of three integers which are the lengths of the sides of a right
trangle (C2 = A2 + B-). Find all sets of three integers up to C - 50 which are Pythagorean
triples. For example, A = 3, B = 4, C = 5 is a solution. {Note that due to rounding errors, it
is better to use A*A + B*B = C*C rather than Af2 + B|2 = C?2 to check for
equalities.)
14. Stan's Grocery Store has 3 aisles and in each aisle there are five items. Write a program
that will read 15 items into the subscripted variable I$(X,Y), dimensioned 3x5. Let his
customers type in the item they want to buy and be informed by the computer of the aisle
and the item's number.
4-16
RUN
WHAT ARE YOU LOOKING FOR? CHERRIES
YOU WILL FIND CHERRIES IN AISLE # 1 ITEM # 4
WHAT ARE YOU LOOKING FOR? MILK
YOU WILL FIND MILK IN AISLE # 2 ITEM tt 2
WHAT ARE YOU LOOKING FOR? BROCCOLI
I'M SORRY, WE DON'T HAVE BROCCOLI
WHAT ARE YOU LOOKING FOR?
15. Pick 20 random integers between 10 and 99, inclusive. Print the odd integers on one line
and the even integers on the next line. The output should look like this:
RUN
ODD INTEGERS: 15 81 89 33 97 23 23 55 55 11
EVEN INTEGERS: 84 72 76 44 52 84 88 58 66 78
READY.
16. Find the average of four grades for each of five students. The output should give in
columns on consecutive lines each student's name, four grades and average. Each col
umn should have a heading. The last student's average should be underlined and the class
average printed below it in the same column.
RUN
STUDENT tt 1 ? DON
ENTER FOUR GRADES:? 42,86,99,99
STUDENT tt 2 ? LESTER
ENTER FOUR GRADES:? 50,55,45,34
STUDENT tt 3 ? LIZ
ENTER FOUR
*■)
grades: 100,98 ,99,97
STUDENT ? ROB
ENTER FOUR grades: 67,72, 71,68
STUDENT ? SUE
ENTER FOUR GRADES: 89,91, 93,90
NAME 1 2 4 AVE.
DON 42 86 99 99 81.5
LESTER 50 55 45 34 46
LIZ 100 98 99 97 98.5
ROB 67 72 71 68 69.5
SUE 89 91 93 90 90.75
77.25
READY.
17. Marcus Welby wants you to program the computer to keep track of his busy schedule.
(a) Write a program to allow a patient to choose the day and time he or she wants to see
the doctor. There are 5 days and 6 time slots for each day. If the desired slot is empty, the
patient enters his or her name. If it is full, the program asks for another slot.
(b) Add the steps needed to allow Dr. Welby to print his schedule for any particular day.
18. Susie Gossip has 3 skirts—red, green, and purple; 2 pairs of jeans—white and electric
purple; 4 blouses—blue, pink, orange, and black; and 2 slightly tight sweaters—yellow and
green. Have the computer print a list of all possible combinations of the articles she can
wear (e.g., red skirt and blue blouse, or white jeans and yellow sweater).
4-17
RED SKIRT YELLOW SWEATER
19. Write an extended version of the game high-low. In this game, the computer picks a secret
random number from 1 to 100 and gives the player an unlimited number of chances to
guess it. For each wrong guess the computer tells whether to guess higher or lower and
stores the guess in a subscripted variable. If the player guesses the same number twice,
the computer should produce the message WAKE UP! YOU GUESSED THAT NUMBER
BEFORE.
20. Betty Boo has written the following two programs to sort data. Read the programs carefully
and predict the output:
4-18
21. The game Penny Pitch is common in amusement parks. Pennies are tossed onto a chec
kerboard on which numbers have been printed. By adding up the numbers in the squares
on which the pennies fall, a score is accumulated. Write a program which simulates such a
game in which ten pennies are to be randomly pitched onto the board shown below:
K J
V
z z Z Z
z 3 3 z
z 3 3 z
z Z Z z
y.
Have the computer print the board with an X indicating where each penny has landed and
then the score. Below is a sample run. Note that more than one penny can land in one
square:
RUN
1 X 1 1 1 X
1 2 2 2 1
*p
1 2 X 3 X
1 2 X X 2 1
1 2 X X X ].
1 1 1 1 X 1
SCORE 19
22. Write a program that rolls two dice 1000 times and prints the number of times each different
point total (2, 3, 4, 5... , 12) appeared. The output should resemble the following:
4-19
23. Write a program which makes up 15 "words" (i.e. groups of letters, whether pronounceable
or not) composed of from one to seven randomly chosen letters and prints them. (Hint: use
addition of strings. For example, if A$(2) = "B" and A$(12) - "L", then A$(2) + A$(12) =
"BL".)
24. Use the computer to play a modified game of Othello. Have it randomly fill an 8 x 8
subscripted string variable with X's and O's and print the array by row (horizontal) and
column (vertical). Examples are shown below. The X's are for player 1, the O's for player 2.
Have the program ask the players alternately for the row and column of the opponent's
piece that should be flipped {changed from an X to an O or vice versa). All of the oppo
nent's pieces along the horizontal or vertical line passing through the flipped piece are also
flipped. For example, if player 1 flipped the 0 at 1,8, board A would be changed to board B.
(a) 12 3 4 5 6 7 8 (b) 12 3 4 5 6 7 8
1 XXOOXOXO 1 XXXXXXXX
2 OOOXXOXX 2 OOOXXOXX
3 XOXXOXOO 3 XOXXOXOX
4 OOXOXOXO 4 OOXOXOXX
5 OOXXXOXO 5 OOXXXOXX
6 OOXOOXXO 6 OOXOOXXX
7 OOXXOXOX 7 OOXXOXOX
8 XXOXXOXX B XXOXXOXX
25. Mr. and Mrs. Charles Windsor want to start a bank account for their newborn son, William.
They open the account with $500. At the beginning of each successive year they deposit
$60 more. When William is 21, how much money will be in the account? (Assume the
interest rate to be 6% compounded quarterly).
4-20
PRDEHfllfflUME
TECHWJDLJEH
GOSUB
RETURN
ON... GOTO
ON...GOSUB
STOP
CONT
GOSUB
RETURN
ON...GOTO
ON...GOSUB
STOP
CONT
GOSUB
RETURN
ON... GOTO
ON...GOSUB
STOP
CONT
GOSUB
RETURN
ON...GOTO
ON...GOSUB
STOP
CONT
GOSUB
RETURN
ON... GOTO
ON...GOSUB
Writing long, complex programs may require special programming techniques. It is often
helpful to divide these programs into sections, called subroutines. Subroutines are useful
because they perform a specified task and may be accessed from anywhere in the program. A
long program may be divided into a main section and a series of subroutines. The main section
directs the order in which the subroutines do their specialized jobs. This type of organization
usually reduces the size of a program because the lines needed to perform a certain task have
only to be placed once in a program, even though the task may be performed several times.
GOSUB, RETURN
In the case of programs whose various portions are repeated at different places, it
may be efficient to use a subroutine. A subroutine is entered by the statement
RETURN
For example:
10
20 GOSUB 200
30
40
200
210
220
230 RETURN
999 END
The skeleton program illustrates the use of a subroutine. At line 20 the program jumps to
the subroutine, which begins at line 200, executes the subroutine and then returns from line 230
to the body of the program at line 30. It is legal to use more than one RETURN statement within
a subroutine. You should remember that the computer always returns to the first statement after
the GOSUB statement which caused the subroutine to be executed. The major difference
between GOSUB and the GOTO statement is that GOSUB permits the use of RETURN.
Subroutines are usually placed towards the bottom of a program. They may be written so that
one subroutine can access another.
Program 5.1
Given the numbers of pennies, nickels, dimes and quarters as input, this program will
output the total amount of money represented by these coins. One subroutine processes and
reports the amount of money involved for each of the four types of coins:
5-1
10 A* « "PENNIES": V ■ 1
20 GOSUB 200
30 A* = "NICKELS": V = 5
40 GOSUB 200
50 A* ■ "DIMES": V = 10
60 GOSUB 200
70 A* ■ "QUARTERS": V = 25
80 GOSUB 200
90 PRINT "THE TOTAL VALUE WAS *";T/100
100 END
200 REM SUBROUTINE
210 PRINT "NUMBER OF ";A*;
220 INPUT N
230 PRINT N;A*;" =";N*V;"CENTS"
240 T = T + N*V
250 RETURN
RUN
NUMBER OF PENNIES? 4
4 PENNIES = 4 CENTS
NUMBER OF NICKELS? 9
9 NICKELS = 45 CENTS
NUMBER OF DIMES? 3
3 DIMES m 30 CENTS
NUMBER OF QUARTERS? 6
6 QUARTERS = 150 CENTS
THE TOTAL VALUE WAS * 2.29
READY.
Line 10 assigns the type (A$) and value (V) of the first coin. Line 20 causes a jump to the
subroutine, which begins at line 200, where the number of coins is input. Line 210 prints
information about the particular coin being considered, and line 240 adds its contribution to the
previous total value of all coins up to this point. Line 250 returns the program to the line
following the most recently used GOSUB statement. This entire process, beginning at line 200,
repeats itself three more times, and then the dollar total is printed. What would happen if line
100 were deleted?
ON... GOTO
The GOTO statement allows a program to jump to a single specified line. The ON ...
GOTO statement allows jumps to one of several lines, depending on the value of a numeric
variable at the time the statement is encountered. This statement takes the form:
For example:
If X = 1, the program jumps to line 100; if X = 2, it jumps to line 120 and so on. Note that X
should not be less than one or greater than the number of line numbers in the list.
5-2
Program 5.2
This program simulates the random path taken by a mouse through the following maze:
Once the mouse enters the maze, the door is shut. The mouse wanders about until it either
finds the cheese or stumbles upon the cat.
100 PRINT 1,
110 X - INT(2*RND<0)+1>
120 ON X GOTO 200,300
200 PRINT 2,
210 X - INT(2#RND<0)+1)
220 ON X GOTO 100,300
300 PRINT 3,
310 X - INT(3*RND(0>+1>
320 ON X GOTO 100,200,400
400 PRINT 4,
410 X = INT(3*RND(0)+1)
420 ON X GOTO 300,500,600
500 PRINT 5
510 PRINT "THE MOUSE IS GORGING ITSELF!"
520 END
600 PRINT 6
610 PRINT "THE CAT HAS BEEN AWAKENED BY ITS LUNCH."
RUN
13 13
2 3 4 6
THE! CAT HAS BEEN AWAKENED BY ITS LUNCH.
READY.
At line 100 the program prints a 1 to indicate that the mouse is in room #1. Line 110 randomly
picks either the number 1 or the number 2. The ON ... GOTO statement at line 120 sends
program execution to line 200 if X = 1, and to 300 if X = 2; lines 200 and 300 correspond to
rooms 2 and 3, respectively. Once the mouse is in one of the other rooms, the program prints
the room number and decides where the mouse will go from there. Execution continues until
the mouse finds itself either in room 5 or room 6.
5-3
ON... GOSUB
The ON ... GOSUB statement operates in much the same way as the ON ... GOTO
statement. If there are a number of subroutines in a program, they can be called using the
ON ... GOSUB statement:
If X - 1, the program jumps to the subroutine at line 300; if X = 2, to the subroutine at line 400;
and if X - 3, to the subroutine at line 500. When the subroutine is completed, the RETURN
statement directs the program back to the first statement after line 50.
Program 5.3
RUN
1- STAR WARS
2- THE EMPIRE STIKES BACK
3- RETURN OF THE JEDI
CHOOSE THE MOVIE REVIEW BY NUMBER.
1,2 OR 3? 1
LUKE BATTLES THE EMPIRE
RESCUES THE PRINCESS AND
DESTROYS THE DREADED DEATHSTAR.
5-4
Review
1. Write a program in which names are input and then printed. If DONALD is input, use a
subroutine to underline the name.
RUN
NAME? MARY
MARY
NAME? SUE
SUE
NAME? DONALD
DONALD
NAME?
2. Write a program to draw five cards from a deck. The computer picks two random numbers,
the first between 1 and 4, inclusive, and the second between 1 and 13, inclusive. An
ON ... GOTO statement should use the first number to pick each suit. The second repre
sents the card's value within the suit.
RUN
CARD 1 IS THE 6 OF HEARTS
CARD t. IS THE OF SPADES
T
CARD IS THE OF CLUBS
CARD 4 IS THE 9 OF SPADES
CARD 5 IS THE 1 OF SPADES
READY
3. Write a program using an ON ... GOSUB statement that takes one of four different courses
of action depending on the number entered (A).
Planning a Program
Now that you are familiar with most of the BASIC commands it is important to spend time
refining your programming techniques. The first step to this end is learning to plan your
program.
The programmer's first concern in planning a program is to define precisely the problem to
be solved. This requires the programmer to analyze the problem carefully and to develop a
logical sequence of steps to solve the problem. The problem is first broken down into smaller
units, each of which should be easier to solve. Just as the task of building a house is made
manageable by breaking it down into a series of smaller tasks, so such subdivision of a problem
can simplify programming. The solution to the total problem will be accomplished when the
solutions to the smaller problems are pieced together in a logical sequence.
5-5
The plan used to solve a problem is called an algorithm. Each step in the algorithm should
be clear, feasible and unambiguous. A useful technique to develop an algorithm is to determine
how a problem could be solved using only pencil and paper. The same step by step sequence
required to produce this non-computer solution can usually be translated directly into the
sequence employed within a computer program.
Proper planning, as suggested above, will enable the programmer to avoid the common
mistake of writing the program before the problem or its solution is understood. Premature
"coding" (the term "code" is used to define the instructions which comprise a program) fre
quently results in a program which must be modified by adding or deleting lines of code until the
desired output is achieved, with the consequence that the resulting program is usually a
"mish-mash" of statements which do not flow logically from one to another. For example, when
excessive GOTO and IF ... THEN statements have been added to a program to make it work,
the sequential flow from line to line, a sign of good programming, is often destroyed. Moreover,
the code itself will lack clarity and will be less easily understood by other programmers. There
fore, one should plan a program as thoroughly as possible before approaching the computer.
As the computer pioneer R. W. Hamming declared, "Typing is no substitute for thinking."
To demonstrate the use of an algorithm, we will design a program that will give a student a
mathematics quiz. This quiz will consist of ten questions, each of which will be one of four types:
addition, subtraction, multiplication or division. Two randomly chosen numbers betweeen 1 and
10, inclusive, will be used in each problem, and the student will be given two chances to answer
each question correctly. If the student answers a question correctly on the first attempt, then he
or she will receive full credit (10 points), or if the second attempt is correct, then half credit (5
points) is awarded. The quiz might be similar to the following:
At the outset, a plan or algorithm must be outlined and the problem broken down into
separate parts. For example:
5-6
Notice that no matter which type of problem (add., subt., mult, or div.) is chosen, the
testing procedure remains the same. This means that we could place each type of problem in
its own subroutine. Since we want a random selection of four types of problems, we could
generate a random number from 1 to 4 and use it as the variable in an ON... GOSUB
statement.
At this point it is useful to assign names to the variables we will use and then use these
names in refining our algorithm. We will call the variable that represents the type of question
(N), the two random numbers used in each question (A) and (B), the student's answer
(ANSWER), and the loop variable (QUEST), the correct answer (C), and the score (SCR).
Because ten questions are to be asked, a FOR ... NEXT loop will be used. The algorithm
using variable names can now be further refined to read:
Print Instructions
FOR QUEST = 1 to 10
Choose random number N from 1 to 4 inclusive
Choose two random numbers (A,B) from 1 to 10 inclusive
ON N GOSUB (add, sub., mult., div.)
FOR GUESS - 1 to 2
INPUT ANSWER
Compare ANSWER to correct answer (C)
Compute SCR
NEXT GUESS
NEXT QUEST
PRINT SCR
END
Subroutines:
Addition
Subtraction
Multiplication
Division
The structure of the algorithm is now quite clear. First the student will be given instructions.
The body of the program will consist of a main loop which is repeated ten times. Within the loop
the computer will choose the type of question to ask and the numbers to be used in the
question, ask for an answer, and then compute the score depending on the answer. The last
step will print the final score.
Each of the four subroutines will ask one type of problem and compute the correct answer.
We have attempted to put parts of the program common to each type of problem in the main
body (within the QUEST loop) and only those parts which are unique to a specific type of
problem in each subroutine. For example, the subroutine for addition will print the question and
determine the correct answer:
This plan will work for each of the four subroutines, each of which will have a different PRINT
statement and answer for the variable C.
5-7
In order to structure a program properly, observe the following rules :
1. Place REM statements at the beginning of a program to indicate what the program does and
to define the variables used within the program. In addition, REM statements strategically
placed throughout the program can be helpful in explaining how the program works.
2. Indent the lines within FOR ... NEXT loops to clarify where the loops begin and end and
what portions of the program are contained within each loop.
3. Break a program down into separate modules or subroutines, where each performs a
specific task. It is a good programming practice to separate each subroutine from the others
by choosing appropriate line numbers. For example, if a program contains three sub
routines, each of which is about 15 lines long, then number the lines of the first subroutine
from 100 to 250, the second from 300 to 450, and the third from 500 to 650. In addition, each
subroutine should be separated from the next by using blank REM statements, and each
subroutine should start with a REM which explains its function.
Program 5.4
With these rules in mind, we are now ready to translate our plan into a program. Note the
almost one to one correspondence between the program and the math quiz algorithm:
5-8
300 REM ADDITION
310 PRINT "WHAT DOES";A; " + " ;B;" = "
320 C ■ A+B
330 RETURN
340 REM
350 REM
400 REM SUBTRACTION
410 PRINT "WHAT DOES";A;"-";B;"="
420 C m A-B
430 RETURN
440 REM
450 REM
500 REM MULTIPLICATION
510 PRINT "WHAT DOES";A;"*";B;"="
520 C = A*B
530 RETURN
540 REM
550 REM
600 REM DIVISION
610 PRINT "WHAT DOES";A;"/";B;"="
620 C = A/B
630 RETURN
RUN
YOU WILL BE ASKED TEN QUESTIONS THAT
COULD BE OF 4 TYPES: ADDITION,
SUBTRACTION, MULTIPLICATION, GR
DIVISION. YOU WILL GET 2 TRIES TO
GET EACH CORRECT. YOUR SCORE WILL
BE BASED ON THE NUMBER OF GUESSES
YOU TAKE.
WHAT DOES 2 + 9 =
YOUR ANSWER IS? 18
WRONG
YOUR ANSWER IS? 29
WRONG
YOU'VE HAD 2 TRIES; THE ANSWER IS 11
WHAT DOES 3 / 2 =
YOUR ANSWER IS? 1.4
WRONG
YOUR ANSWER IS? 1.5
CORRECT
5-9
WHAT DOES 8 / 9 =
YOUR ANSWER IB? .9
WRONG
YOUR ANSWER IS? .888
WRONG
YOU'VE HAD 2 TRIES; THE ANSWER IS ,888888889
WHAT DOES 4 - 7 ■
YOUR ANSWER IS? -3
CORRECT
WHAT DOES 4 + 7 -
YOUR ANSWER IS? 11
CORRECT
WHAT DOES 3 - 5 =
YOUR ANSWER IS? -2
CORRECT
WHAT DOES 3 / 1 «
YOUR ANSWER IS? 5
CORRECT
READY.
This math quiz example illustrates that some problems cannot always be foreseen in
planning a program. A good algorithm, however, can make correcting these problems substan
tially easier. In addition, a clearly structured and annotated program can eliminate any un
necessary confusion. The run of Program 5.4 illustrates that there is something wrong in the
division subroutine. Although the student answered the division problem correctly each time,
the computer did not always acknowledge that fact. The error occurs in the division at line 620,
where a rounding error is introduced. At line 170 the student's response, ANSWER, is com
pared with the desired answer, C. Unfortunately, these variables are compared to ten decimal
places of accuracy, and because the student responded by giving an answer to only three
decimal places, the comparison failed. The problem might be corrected by rounding the correct
answer, C, to 3 decimal places by the line
but then a new rounding error is introduced by dividing by 1000. In order to get an accurate
5-10
comparison to only 3 decimal places, it will be necessary to compare the integer values of
ANSWER* 1000 with C which is multiplied by 1000 in lines 320, 420, 520, and 620.
This statement will correct the rounding problem without affecting the other operations. In
addition, the instructions should be modified so that the student is asked to round his or her
responses to 3 decimal places.
The following modifications can be made to Program 5.4 to account for the rounding error
in the division problems:
420 C = (A - B) * 1000
520 C = (A * B) * 1000
620 c — INT(A / B * 1000 + 0.5)
RUN
YOU WILL BE ASKED TEN QUESTIONS THAT
COULD BE OF 4 TYPES: ADDITION,
SUBTRACTION, MULTIPLICATION, OR
DIVISION. YOU WILL SET 2 TRIES TO
GET EACH CORRECT. YOUR SCORE WILL
BE BASED ON THE NUMBER OF GUESSES
YOU TAKE. ROUND DIVISION PROBLEMS
TO 3 DECIMAL PLACES. GOOD LUCK
WHAT DOES 5 - 7 =
YOUR ANSWER IS? -2
CORRECT
5-11
WHAT DOES 4 / 9 =
YOUR ANSWER IS? .35
WRONG
YOUR ANSWER IS? .444
CORRECT
READY.
Debugging
Debugging is the process of locating errors or "bugs" in a program and then correcting
them. Obviously, the best approach is to avoid bugs by carefully planning a program, but even
the most carefully written programs will often contain errors. The rounding error encountered in
Program 5.4 illustrates how even a well planned program can have unforeseen errors. Two
other types of errors which will cause a program to fail are runtime and logic errors.
Runtime Errors
Runtime errors are detected by the computer when a program is run. These errors result
from either syntactical and/or semantic errors. Syntactical errors are caused by typing an
improper statement. For example,
10 REED X, Y
should be
10 READ X. Y
A semantic error is one that violates the computer's rules of operation. For example,
10 READ A$, B
20 DATA 35. SMITH
is a semantic violation since the computer attempts to assign the string "SMITH" to the numeric
variable B. Another common runtime error is caused by using two different variables in defining
a FOR... NEXT loop:
10 FOR X - 1 TO 10
20 PRINT X, X*2, X*3
30 NEXT W
Fortunately, the computer detects the runtime error and prints an appropriate error message.
5-12
Logic Errors
If the program does not violate any of the syntactical or semantic rules of BASIC, the
computer will accept and run it even though the output may not reflect the programmer's true
intent. In such a case the errors in the program may stem instead from the programmer's
incorrect analysis of how to develop a logical sequence of statements to achieve the intended
goal. These forms of errors—referred to as logic errors—are the most difficult to detect and
correct.
Program 5.5
This program is supposed to print the areas of circles whose radii are integers varying from
1 to 100 except for those whose computed areas are integers (note line 30). The equation
A = nR2 is used with the value of n taken as 3.1:
10 FDR X - 1 TO 1 00
20 A = 3. 1 * X--2
30 IF A = INT (A) THEN 10
40 PRINT A,
50 NEXT X
60 END
RUN
3. 1 12.4 27.9 49.6
77.5 111. 6 151.9 198.4
251. 1 3. 1 12.4 27.9
49.6 77-5 111.6 151.9
198.4 251. 1 3. 1 12.4
27.9
BREAK IN 40
READY.
Note that the printed areas go as high as 251.1 and then start to repeat. The program actually
goes into an infinite loop, which means that it keeps running until the STOP key is struck.
A good way to detect the logic error in Program 5.5 is to place an extra PRINT statement in
the program in order to print the loop variable X. This extra statement can later be removed
when the error has been corrected:
RUN
X= 1 3. 1 X* 12.4
X» 3 27.9 x= 4 49.6
X= 5 77.5 x= 6 111.6
X= 7 151.9 x= 8 198.4
X» 9 251. 1 X— 10 X= 1
3. 1 X= 2 12.4 X" 3
27-9 X« 4 49.6 X« 5
77.5 X= 6 11 LI.6 X" 7
151.9 x= e 198.4 X= 9
251. 1 X« 10 1 3. 1
X= 2 12.4 x= 27.9
BREAK IN 40
READY.
5-13
The output indicates that X reaches only 10 and then starts repeating rather than continuing on
to 100 as it should. The problem is that line 30 should send the program to line 50 rather than to
line 10, where it restarts the X loop at one.
In longer programs it is often useful to place additional print statements at a number of
locations to check the value of variables and then remove them when the program is operating
properly.
Another technique is to place a line in the program to indicate whether it is getting to a
certain point as anticipated. For example:
Hand Tracing
It is almost impossible to guarantee that a program will run properly for all possible situa
tions that it may encounter, but one technique that creates confidence in the validity of a
program is called hand tracing. Using test data, the programmer solves calculations by hand
and checks the results against those produced by the program. If the computer program
produces identical answers for the same data, the programmer is then confident that the
program works at least for the data that is being tested.
Program 5.6
This is a program which attempts to find the sum of the first N odd integers:
RUN
NUMBER BUM
3 9
S 73
10 173
5-14
bypass the bug. If Program 5.6 is further hand-tested with N=8, S = 1+3 + 5 + 7 + 9 + 11 +
13 + 15 = 64, this result disagrees with the output above. The presence of a bug is now
apparent.
The next problem is to locate the position of the error in the program. One effective way to
do this, or even better, to avoid errors in the first place, is to "play computer" with the program.
This method is commonly called hand simulation or hand tracing.
To find the bug in Program 5.6 by this method, the programmer makes a table displaying
each variable in the program and then performs the numerical assignments of the variables as
the program dictates, line-by-line:
Line N K S
20 0
30 3
40 I
50 I
60-»40 2
50 4
60—40 3
50 9
60->70 (Print 3,9)
80—30 8
40 I
50 10 (Error! S should now be 1)
The error was caused by not resetting S to 0 before reading the new data N = 8. Hence, to
correct the error, change line 80 to:
B0 GOTO 20
RUN
NUMBER SUM
3 9
8 64
10 100
Halting a program at certain points by using one or more STOP statements is a useful
debugging technique. Upon interruption, the values of the program's variables may be
examined. Typing CONT will continue program execution from the point at which it was
interrupted.
5-15
Program 5.7
10 FDR X = 1 TD 100
20 A = 3*XV3 + 2*X'-2 + 5
30 B = 7*X'"2 + 2*X + 5
40 IF B > A THEN PRINT B;">";A
50 NEXT X
60 END
RUN
14 > 10
READY.
When Program 5.7 is run, the computer prints one solution to the condition at line 40 and
then gives the appearance of being at rest until it finally prints READY. Is there only one
solution or is there a bug in the program? The values of A and B can be checked when X = 50
by adding the following line:
45 IF X = 50 THEN STOP
The values of A and B can then be examined when the program is halted by typing PRINT
A,B. Typing CONT allows this program to continue to completion. Since A is much larger than B
when X = 50, it is obvious that there will be no other solutions than the first one. Hence, there is
no bug in the program:
RUN
14 > 10
BREAK IN 45
READY.
PRINT A,B
380005 17605
READY.
CONT
READY.
Review
4. Each of the following programs contains a 'bug'. Find it and correct it.
a) 10 INPUT A
20 FOR X=10 TD 1
30 C = A/X
40 PRINT INT(C)
50 NEXT X
b) 10 INPUT N
20 IF N < 0 THEN 10 : REM PREVENTS NEGATIVE INPUT
30 P = N*5
40 IF P < 0 THEN PRINT "THE PRODUCT IB NEBATIVE" : GOTO 60
50 PRINT "THE PRODUCT IS POSITIVE"
60 END
5-16
EXERCISES
1. Have the computer produce the printout below. Use a subroutine to print out "PART" and
the appropriate number:
RUN
FART 1
*JM***************************
PART 2
i I !
PART 3
ABABABABABABABABABABABABABABAB
READY.
2. Have the computer pick a random integer from 1 to 4 which will determine if the prize to be
awarded will be a ball, balloon, toy car or candy bar.
3. Input an integer from 1 to 4. The integer should cause one of the following four phrases to
be printed:
10 READ X
20 ON X GOTO 30,40,50,60,70,80,100
30 PRINT "MERRILY, ";: GOTO 10
40 PRINT "ROW, ";: GOTO 10
50 PRINT "YOUR BOAT11: GOTO 10
60 PRINT "GENTLY DOWN THE STREAM": GOTO 10
70 PRINT "LIFE IS BUT A DREAM": GOTO 10
80 PRINT: GOTO 10
90 DATA 2,2,2,3,4,1,1,1,1,6,5,7
100 END
5-17
5. (a) Give the exact order in which the lines of the following program are executed:
(b) If line 80 is changed to:
10 READ X
20 IF X=999 THEN 90
30 ON SGN<X>+2 GOSUB 50,60,70
40 GOTO 10
50 N = N+l: RETURN
60 Z m Z+l: RETURN
70 p = p+ij RETURN
80 DATA 6,-1,0,999
90 PRINT "N-"|N,uZ-"|Zt"P«"jP
100 END
6. (a) Give the exact order in which the lines of the following program are executed:
(b) If line 90 were changed to:
10 READ X
20 IF X=0 THEN 95
30 GOSUB 60
40 T = T+X
50 GOTO 10
60 IF X < O THEN 80
70 P m p+X
80 RETURN
90 DATA 5,2,-9,0,3,5
95 PRINT "T=»";T,"p="3p
100 END
7. Write a program which reads the dimensions of a triangle from a DATA statement and
prints its area and perimeter if it is a right triangle. The program should call a subroutine to
check whether the triangle is a right triangle or not. Begin by developing an algorithm for
this problem.
8. Let X and Y be the coordinates of a point in a plane. Write a program which randomly picks
X and Y, each as an integer from -5 and 5, inclusive. The user of the program is to guess X
and Y, with the guesses being called X1 and Y1. A subroutine must be used to print the
distance between the guessed point and the actual point after each guess. The user is to
be given 3 guesses and, if unsuccessful, is then to be given the value of X as well as 2
more tries to guess Y. Begin by developing an algorithm for this problem.
9. Isolated in his ski-lodge in the Swiss Alps, Bjorn Rich often gets his mail late. As a result the
statements from his Swiss bank account rarely arrive on time. To solve this problem, write
5-18
a program to assist Bjorn in keeping his account up to date. Have three subroutines which
take care of deposits, withdrawals and the interest (5%% compounded quarterly). Begin by
developing an algorithm for this problem.
RUN
WITHDRAWAL(1),DEPOSIT(2),
CALCULATE INTERESTS), OR EXIT(4)
1,2.3, OR 4? 2
HOW MUCH WOULD YOU LIKE TO DEPOSIT
? 500.75
YOUR BALANCE STANDS AT * 500.75
WITHDRAWAL(1),DEPOSIT(2),
CALCULATE INTEREST(3), OR EXIT(4)
1,2,3, OR 4? 3
HOW MANY MONTHS SINCE LAST CALCULATION
? 5
YOUR BALANCE STANDS AT $ 507.95
WITHDRAWAL(1),DEPOSIT(2),
CALCULATE INTERESTS), OR EXIT<4>
1,2,3, OR 4? 1
HOW MUCH WOULD YOU LIKE TO WITHDRAW
? 175.45
YOUR BALANCE STANDS AT $ 332.5
WITHDRAWAL(1),DEPOSIT(2),
CALCULATE INTEREST(3), OR EXIT<4)
1,2,3, OR 4? 3
HOW MANY MONTHS SINCE LAST CALCULATION
7 1
TOO SOON
YOUR BALANCE STANDS AT * 332.5
WITHDRAWAL(1),DEPOSIT(2) ,
CALCULATE INTEREST(3), OR EXIT(4)
1,2,3, OR 4? 4
READY.
5-19
10. The area of any triangle may be found from Hero's formula
11. Develop an algorithm to play the game Black Jack. The computer will act as dealer in this
game. The object of the game is to get closer than your opponent to 21 without going over.
Picture cards are worth ten, and aces are worth one or eleven. All other cards are worth
their face value. The dealer and the player are each dealt two cards. The player then takes
as many cards as he wants to get as close to but not exceed 21. When the player
determines that he has enough cards, the dealer takes cards until his cards total at least 17
but not more than 21. The winner is the one who is closest to 21 without going over 21. In
the event of a tie the dealer wins.
12. Develop an algorithm for playing the card game War on the computer. The computer will
run through the game in a simulation. In this game two players are each given half a normal
deck of cards. The top card of each players stack is revealed and the higher card takes the
lower card. In the event of a tie each player puts in three cards face down and then reveals
a fourth card to determine who will win all ten cards. Whoever runs out of cards first for any
reason loses.
13. Each of the following programs contains an error. In each case identify and correct the
error(s):
5-20
(e) 10 FOR X=l TO 8
20 FOR Y=l TO 3
30 X = X+Y
40 NEXT X
50 NEXT Y
60 PRINT X
70 END
14. Trace the following program by hand and determine its output:
10 READ N,A,B
20 FOR 1=1 TD N
30 FOR J =2 TO N+1
40 A = 2*A+B
50 B = 2KB+A
60 NEXT J
70 PRINT A: iB
B0 NEXT I
90 DATA 3,- t,
100 END
15. What output is produced by the following program? (Do not run the program.)
16. The following simple programs have errors in logic (i.e. the program runs, but the output is
illogical). Find and correct the errors:
5-21
(c) 10 READ A,B,C
20 FOR X=l TO 10
30 y = <A*B)/(C-X)
40 IF Y<1 THEN 50
50 PRINT "Y<l"jY
60 NEXT X
70 DATA 20,10,5,5,10,20
80 END
17. Each of the following programs contains errors which will result in error messages being
printed by the computer when the program is run. Find and correct the errors:
18. The following program is designed to arrange sets of numbers in descending order. If the
second number is larger than the first, the computer interchanges the two values. (This
occurs in lines 30 and 40.) Explain the output and correct the program to give the desired
output:
5-22
10 READ
20 IF A > B THEN 50
30 A = B
40 B = A
50 PRINT A, B
60 GOTO 10
70 DATA 10, ,2 0,20,1C
80 END
RUN
20 20
20 1 0
19. The area of a square that measures one inch on a side is equal to one square inch. If the
computer takes various slices of this same square and sums the areas of the slices, the
answer should be one square inch. In the following program 100, 500, 1000 and 1024
slices are used and the output printed below. Explain the results:
10 READ N
20 FOR X=l TO N
30 Y ■ Y+l/N
40 NEXT X
50 PRINT Y;"SQ. INCHES FOR";N$"SLICES"
60 Y = 0
70 GOTO 10
00 DATA 100,500,1000,1024
90 END
RUN
1 SQ. INCHES FOR 100 SLICES
1.00000002 SQ. INCHES FOR 500 SLICES
.999999975 SQ. INCHES FOR 1000 SLICES
1 SQ. INCHES FOR 1024 SLICES
20. Structure the following programs by adding spaces and REM statements and by indenting
where appropriate and necessary:
(a) 10 FORX=1TO10
20 B=RND<0)
30 IFB>«.5THENPRINT"HEADS":BOTO50
40 PRINT"TAILS"
50 NEXTX
60 END
5-23
(b) 1 DIMJ(8,B)
2 FORX=0TO7
3 PRINTTAB(X*4+5>;X+l;
4 NEXTX
5 FRINT
6 FORX=0TO6
7 FRINTTAB(X*4+6>;"—";
8 NEXTX
9 PRINTTABC34);"—"
10 FORX=1TOS
11 FORY=1T08
12 J (X,Y)=X+Y
13 IFF-0THENPRINTX;":";
14 PRINTTABCF*4+5);J(X,Y)
15 F=F+1
16 IFF=8THENPRINT:F=0
17 NEXTY
18 NEXTX
19 END
5-24
GHflPHJCB
PEEK
POKE
PEEK
POKE
PEEK
POKE
PEEK
POKE
PEEK
POKE
PEEK
POKE
PEEK
POKE
PEEK
POKE
PEEK
POKE
PEEK
POKE
PEEK
POKE
PEEK
POKE
PEEK
POKE
PEEK
POKE
The Commodore-64 and VIC-20 computers have the ability to display a multitude of
shapes and colors. Using the special color and graphic keys, which are unique to the Commo
dore computers, the programmer can create pictures and graphs.
Color
The Commodore-64 and the VIC-20 computers can print text (letters, numbers, and other
symbols) in a variety of colors on the display screen. Along the top row of the keyboard, on the
front side of the number keys (1-8), are eight color selections. These keys, when pressed
simultaneously with the CTRL key, are used to change the color of the characters as they
appear on the display screen. For example, by pressing and holding the CTRL key (in the same
manner that the SHIFT key is operated) along with the 3 key, the programmer selects the color
red. Notice that all subsequent text appears in red until another color is selected. The following
key combinations allow 1 of 8 colors to be selected:
('ombinution Color
CTRL-1 Black
CTRL-2 White
CTRL-3 Red
CTRL-4 Cyan
CTRL-5 Purple
CTRL-6 Green
CTRL-7 Blue
CTRL-8 Yellow
Unlike the VIC-20 the Commodore-64 can print text in an additional 8 colors. The pro
grammer selects these 8 colors with the c= (Commodore) key instead of the CTRL key, again
using the number keys 1 through 8. The following key combinations can be used to select one
of the eight additional colors on the Commodore-64.
Combination Color
c= -i Orange
G -2 Brown
C= -3 Light Red
O -4 Dark Gray
C= -5 Gray
& -6 Light Green
C= -7 Light Blue
C= -8 Light Gray
When any of the color key combinations are used, the color change takes place im
mediately unless the selection is made within quotation marks such as in a PRINT statement.
When used within quotation marks, each color selection is displayed as a unique graphic code.
6-1
Keyboard Color Display Keyboard Color 1 )isp]
10 PRINT •'COLORFUL"
CTRL- 12 3 4 5 6 7 8
to print "icaora^i
RUN
COLORFUL
READY.
However, when line 10 is executed, each letter of the word COLORFUL will be in a different
color. If line 10 is the last line in the program, then all subsequent output such as the "READY"
prompt will appear in yellow since that was the last color selected. To get back to the normal
display, simply press the RESTORE key while simultaneously holding the RUN/STOP key.
Reverse Mode
The RVS ON key (located on the 9 key) allows characters to be displayed in inverse or
"reverse", much like a photographic negative. Normally, text appears in the "foreground" color,
which is the color of the characters on the screen. The "background" color is the dominant color
of the screen on which the characters themselves are displayed. It is possible to reverse the
foreground and background colors for one or more characters by pressing CTRL-9. Then all
subsequent characters typed will be in reverse until reverse mode is exited by pressing RVS
OFF (CTRL-0) or until the end of a line is reached. Remember that the front of each number key
indicates the action that takes place when it is used simultaneously with the CTRL key. For
example:
6-2
If the background color is blue and the foreground color is white, then normal output is
white on blue. However, characters will appear blue on a white background when reverse mode
is selected. It is important to note that the dominant background itself does not change, but
rather each character printed appears with its own reversed background.
It is possible to combine normal and reverse text on a single line of output. For example:
Reverse mode is automatically exited at the end of each line of output. If more than one
line of reverse text is desired, then it is necessary to use RVS ON (CTRL-9) in each additional
PRINT statement which starts a new line of output. When RVS ON or RVS OFF is used within
quotation marks, a unique graphic code appears in the same manner as for the color key
combinations.
CTRL-9 Reverse On
Remember that reverse video mode is only active for a single line of output on the screen
and reverses the background of only that line.
Program 6.1
6-3
HUH
READV.
Examine the output produced by lines 60 and 70. The word PHYSICS appears in reverse,
but " IS FUN" does not, even though reverse mode was not cancelled with a CTRL-0. Yet the
output produced by line 10 and 20 is in reverse. Because there is a semicolon at the end of line
10, line 20 does not start a new line of output. If a semicolon were appended to the end of line
60 in Program 6.1, then the last three words would appear in reverse.
Program 6.2
This program illustrates how color and the inverse mode can be used to create a rainbow
of colors:
16 FOR C = ± TO ±6 _
2O READ Cl : PRINT CS;
3O PRINT " U
•48 NEXT C
58 REM
188 REM COLOR CODE DATA
JLJLO DATA "■", "\M"m nH"j "fc/" * "#■"* Binii#"B"# "El"
Ido f\ a ~r £3, ■ ir-ii i ■ ■■■■ ■ ■ i.'i ■ ■ »rn' ■ ■ ■M1 ■ ■■■in ■■p"t
"£3" "mZ"
Line 10 defines a loop which will be repeated 16 times. The variable C is used in a READ
operation at line 20 to select one of 16 colors for each line of the rainbow. Note how RVS ON is
used in line 30 to print a solid bar on the display for each color. Because reverse mode is
automatically exited at the end of each line of output, RVS OFF is not needed.
Graphic Symbols
The Commodore-64 and the VIC-20 are equipped with 62 unique graphic symbols which
can be used to create simple drawings and graphs. The symbols are easily accessed through
SHIFT or c= (Commodore) keys. Notice that the front side of most of the keys is marked with
two small blocks, each of which contains a special symbol:
6-4
The symbol contained in the rightmost box is generated by striking the corresponding graphic
symbol key while depressing the SHIFT key. For example, to produce the symbol [Jj (located
on the B key), it is necessary to press SHIFT and B. The symbol on the left is produced by
striking the desired symbol key while depressing the c= (Commodore) key. Thus, the symbol Si
is produced by pressing c= and B. Remember that the c= key and SHIFT key are operated in
the same manner; that is, one key is depressed while another key is typed.
The box in which each symbol is shown serves only as an outline. This allows symbols of
various shapes and sizes to be compared easily.
Program 63
O
20 PRINT
30 PR 1 N T "■
-40 PR INT "
50 PR INT f' L.
RUN
READY
o
Program 6.4
This program produces a picture of E.T. Note how adjacent symbols touch one another on
the screen. This is useful for creating complete figures:
6-5
RUN
READY.
Cursor Movement
The Commodore-64 video display is capable of holding 25 lines of text, each line consist
ing of 40 characters. The VIC-20 is able to display only 23 lines of text of 22 characters each.
The two keys, located in the lower right corner of the keyboard, can be used to move the cursor
to any position on the display screen.
When the cursor keys are used within quotation marks (e.g., in a PRINT statement), a
special graphic code is produced. The cursor movement takes place when the PRINT state
ment containing the code is executed. For example, the following line moves the cursor up 5
lines and then prints a name:
Note the graphic symbol produced when CRSR-*is pressed within the quotation marks. Other
keys are also able to manipulate the display screen. The CLR/HOME key positions the cursor
at the top left corner of the display (home), and when it is pressed simultaneously with the
SHIFT key, the display is first cleared, then the cursor is repositioned at "home."
6-6
The following table shows the keys required to move the cursor and the unique graphic
symbols that will appear when the key is used within quotation marks:
4
CRSR Move cursor right 1 space
»
«
SHIFT - CRSR Move cursor left 1 space
Program 6.5
Bar graphs are useful for displaying and comparing groups of data. This program plots a
bar graph of gross income for Tropical Waters Inc., a construction management company.
Carefully examine the program, noting how color and cursor movement are used in creating the
graph:
6-7
REM NOW PLOT BAR FOR EACH YEAR
0 PRINT "rg"; : REH COLOR
110 FOR V - 1 TO -4
128 X0 — C Y — 1 ?■**■! 0
138 FOR V0 - 22-GRCY> TO
GOSUB 580 : REM, CURSOR
156 PRINT "La ■!'
1G0 NEXT Y0
176 NEXT V
180 PRINT "LS"i = GOTO 2880
500 REM
501 REM POSITION CURSOR AT <X0 Y0)
510 PRINT "&": REM PUT CURSOR AT CO, 8>
520 if xe = 8 THEN 560
53O FOR L = 0 TO XO~i
5-4© PRINT "Vi 1; ::REM MOUE CURS Oi R RIGHT
550 NEXT L
5G0 IF VO = O THEN RETURN
570 FOR L = O TO
580 PRINT "tUAJ MOUE CURSOR DOWN
590 NEXT L
600 RETURN
1000 DATA 1981 J- ~*—r 1-I1 -ft- ji H ■ 1982.16
1010 DATA 198 3,11 1984,28
2808 END
RUN
TROPI RS INC
OME
Lines 10 and 15 clear the screen and print a header; lines 20 and 70 label each bar in
the graph. The four bars are plotted by lines 100 through 170. Note that a subroutine, beginning
at line 500, is used to position the cursor at the desired point on the display screen. Although
this program is written for the 40-column display of the Commodore-64, it can easily be re
written for the VIC-20. The following changes to Program 6.5 will allow it to run on the VIC-20:
6-8
Review
1. Write a program that will print N squares, where N is entered from the keyboard.
RUN
□
□
READV.
The PEEK function is used to retrieve the contents of a particular location in the computer's
memory. The general format for PEEK is:
N = PEEK (<address>)
The contents of the memory address specified are assigned to the variable N. Note that a value
between 0 and 225, inclusive, is returned by PEEK. PEEK can also be used in a PRINT
statement. For example:
PRINT PEEK(1023)
165
READY.
As can be seen, the contents of memory location 1023 are currently 165.
The POKE statement is used to change the contents of a single memory location. The
format for POKE is:
The "value" specified, a number which must be between 0 and 255, is placed into the com
puter's memory at the location specified by "address." The statement
POKE 1023,223
changes the contents of location 1023 from 165 to 223. A subsequent PEEK confirms the value
contained at 1023 to be 223:
FRINT PEEK(1023)
READY.
6-9
Proper care should be exercised when using the POKE statement. Incorrect use can
drastically impair the proper operation of the computer. Should a problem occur, simply press
the RUN/STOP and RESTORE keys simultaneously to reset the computer to normal operation.
In some situations it may be necessary to turn the computer off and then on again. However, it
is very important to realize that by doing this everything stored in the computer's memory will be
lost.
The following table lists some of the more important memory locations on the
Commodore-64 which can be examined and modified. A more complete memory table can be
found in the Commodore-64 Programmer's Reference Guide. This table does NOT apply to the
VIC-20 computer. Refer to the next section in this chapter for information on peeking and
poking on the VIC-20.
Address Description
Memory locations 211 and 214 contain the current coordinates of the cursor on the display
screen. Consider the display as a 40x25 grid containing 1,000 character positions. The upper
left corner of the screen is (0,0); the lower left, (0,24); the upper right, (39,0); and the lower right,
(39,24). The line
40 X = PEEK(211) : Y - PEEK(2I4)
returns the current cursor position (X,Y), X being the horizontal position of the cursor (0-39),
and Y the vertical position (0-24).
The horizontal position of the cursor can be changed by the statement
POKE 211, X
in which X is the desired column number (0-39). The vertical position can be changed by the
following statements, assuming Y contains a value between 0 and 39, representing the desired
row number;
6-10
POKE 214, Y
POKE 209, ((1024+ 40* Y) AND 255)
POKE 210, INT ((1024 + 40* Y) / 256)
50 POKE 211,29
60 POKE 214,8
70 T = 1024+ 40*8
80 POKE 209, (T AND 255)
90 POKE 210, INT (T / 256)
0 10 20 30 39
i :1
X 10 ROW
24
Note that the horizontal (column) position varies from 0 to 39 whereas the vertical (row) position
varies from 0 to 24.
Memory location 646 contains the color code for the foreground color; 53280, the color
code for the border color; and 53281, the color code for the current background color. Refer to
the Color Table below for a list of screen colors and their associated color codes.
COMMODORE-64
COLOR CODE TABLE
0 Black 8 Orange
1 White 9 Brown
2 Red 10 Light Brown
3 Cyan 11 Dark Gray
4 Purple 12 Gray
5 Green 13 Light Green
6 Blue 14 Light Blue
7 Yellow 15 Light Gray
6-11
For example, to find the current background color of the display, simply type:
READY.
In this case, the color code returned is 6; therefore, the background color is blue. To change the
background color to red, use:
POKE 53281.2
Be sure that the foreground color (that of the cursor) differs from the background color;
otherwise, output will not be visible because characters will be the same color as their
background. The border color can also be changed by a POKE statement. For example, the
statement
POKE 53280,8
The foreground color, the color of the characters, can be changed by a PRINT statement
(using a CTRL or c= key with a number key, discussed earlier in this chapter) or by a POKE
statement. The statement
POKE 646,1
changes the foreground color to white. Then all subsequent output will appear in white until a
new color is selected.
Program 6.6
INT"
^ :■:■
8 PRINT" ¥: S ¥: W: % :•> x-
6-12
RUN
i
I i
§
. 1 ttftfiftttfe 1
Note that the letter M wraps around to a new line in lines 30 through 90 because of the
limited screen width. Line 110 selects a random background color, whereas line 120 picks a
random border color. The inconsistent flash of the explosion is created by the randomly timed
delay loop at line 130.
The following table lists some of the more important memory locations on the VIC-20 which
can be examined and modified. A more complete memory table can be found in the VIC-20
Programmer's Reference Guide. This table does NOT apply to the Commodore-64 computer.
Address Description
Memory locations 211 and 214 contain the current coordinates of the cursor on the display
screen. Consider the display as a 22x23 grid containing 506 character positions. The upper left
corner of the screen is (0,0); the lower left, (0,22); the upper right, (21,0); and the lower right,
(21,22). The line
40 X - PEEK(211) : Y = PEEK(214)
returns the current cursor position (X,Y), X being the horizontal position of the cursor (0-21),
and Y the vertical position (0-22).
6-13
The horizontal position of the cursor can be changed by the statement
POKE 211. X
in which X is the desired column number (0-21). The vertical position can be changed by the
following statements, assuming Y contains a value between 0 and 22, representing the desired
row number:
POKE 214, Y
POKE 209, ((7680 + 22* Y) AND 255)
POKE 210, INT ((7680 + 22* Y) / 256)
50 POKE 211,29
60 POKE 214,8
70 T = 7680 + 22*8
80 POKE 209, (T AND 255)
90 POKE 210, INT (T / 256)
COLUMN
10 20 21
' 10
ROW
20
22
Note that the horizontal (column) position varies from 0 to 21 whereas the vertical (row) position
varies from 0 to 22.
Memory locations 646 and 36879 contain data relevant to screen colors. Refer to the Color
Code Table below for a list of screen colors and their associated color codes.
6-14
VIC-20
COLOR CODE TABLE
0 Black 8 Orange
1 White 9 Pink
2 Red 10 Light Red
3 Cyan 11 Light Cyan
4 Purple 12 Light Purple
5 Green 13 Light Green
6 Blue 14 Light Blue
7 Yellow 15 Light Yellow
Memory location 36879 deserves special attention because it is used to store three pieces
of information, namely the background and the border colors, and the screen mode. The
following statement assigns the variable B a value between 0 and 7 which corresponds to the
current border color.
On the VIC-20 the border color may only be 1 of 8 colors whereas the background color can be
1 of 16. The variable K is assigned a value corresponding to the background color in the
following statement:
For example, to find the color code of the current background color, simply type:
In this case the color code is 1; therefore, the background color is white.
In addition to the background and border colors, location 36879 also contains data relevant
to reverse text mode. The following statement determines whether reverse or normal mode is
the current display mode on the VIC-20:
will select the colors and mode as specified by the three variables. For example, to select
normal text mode, a light blue background, and a red border, use the statement:
6-15
POKE 36879. 14* 16 + 1*8+2
or
Be sure that the foreground color (the color of the cursor) differs from the background
color; otherwise, output will not be visible because characters will be the same color as their
background.
The foreground color, the color of the characters, can be changed by either a PRINT
statement (using a CTRL or c= key with a number key, discussed earlier in this chapter) or by a
POKE statement. The statement
POKE 646. 1
changes the foreground color to white. Then all subsequent output will appear in white until a
new color is selected.
Program 6.7
This program draws a milk truck and moves it across the screen using a FOR ... NEXT
loop and PRINT TAB:
± PRINT '"En"1
19 FOR P = O TO ±2
26 PRINT TAB(P)
~B PRINT TAB(P)
PRINT TAB(P)
TO PRIN1 TABCP> o
so print "nrm
3G NEXT P
AGO PRINT "IL
RUN
I MILK
o
'•:>.
o
READY.
Line 80 repositions the cursor using CRSR-*- so that output begins at the same screen
location each time the loop is executed. Line 100 moves the cursor down 6 lines (5 CRSR-*-
and 1 RETURN) so that READY appears below the truck.
The Commodore computers are capable of generating both upper and lower case
characters. Normally, the computer only displays upper case output along with a variety of
graphic symbols. When the SHIFT key is depressed in combination with a letter key, a graphic
symbol is produced. In lower case mode, lower case characters can be typed and the SHIFT
key is then used to generate upper case characters. Unfortunately, in this mode many of the
graphic symbols are sacrificed.
6-16
Lower case mode is entered by pressing the c= and SHIFT keys simultaneously. Note that
the change is immediate and affects all characters on the display screen. In lower case mode,
the line
will appear as
Pressing SHIFT- c= a second time causes lower case mode to be exited. Again, the change
is immediate. Normal and lower case mode may be selected from within a program via the
POKE statement, as indicated in the following table:
To Select To Select
Review
3. Write a program that will allow two numbers, A and B, to be entered. The background color
of the screen should then be set to A, and the border color set to B.
4. Modify the answer to Review question 3 so that a third number can be entered as C. If C is 1,
then use a POKE statement to select lower case mode; otherwise select normal mode.
Certain sections of memory contain information about the computer's display screen.
Memory locations 1024-2023 contain values which correspond to a character code for the
characters displayed on the screen, and memory locations 55296-56295 contain values which
correspond to a color code for the color of each character displayed. The display screen may be
thought of as a 40x25 grid containing 1000 character positions, as shown in figure 6-1. It is
possible to use PEEK and POKE to examine and change the contents of the screen. The
statement
L = PEEK(l024 + X + 40*24)
will assign L the character code for the character position (X,Y) on the screen. The list of
possible character codes is shown in the character code table. For example,
READY.
6-17
indicates that position (39,24) contains the letter "A" in normal mode or the letter "a" in lower
case mode. The statement
will assign C the color code for the color of the character in position (X,Y). The list of color codes
is shown in the Commodore-64 color code table in this chapter. For example,
READY,
SET I SET 2 CODK SET 1 SET 2 CODE SET I SET 2 CODE SET I SET 2 CODE
0 32 64 95
1 33 65
I 97
2 34 66 98
3 35 67 99
4
36 - 63
_
100
S
37 69 I 101
6
3S i-i 70 102
7
39 71 □ 103
8
40 i 12 104
9 41 v 73 r 1C5
10 42 ^~ 74
i 106
H
11 75
43 107
12 44 76 108
13 ■■■5 \ 77 109
14 46 78 110
IS 47 □ 79 -
111
16 48 112
80 r
17
49 81 113
IB 50 a? T 114
19 51 83 H 115
20 52 84 I ! 116
21 53 r BS I 117
22 54 86 1 118
23 55 87 " 119
24 56 68 n 120
25 57 1 Bfl - 121
26 58 90
j 122
27 59 91 123
as 60 92
■ 124
29 61 1 93 125
30 62 94 ■ I2fl
31 63 95 127
6-18
The statement
will place the letter "B" at position (20,12), which is about the middle of the screen. Note that the
character will be invisible if its color is the same as the background color. Therefore, it may be
necessary to change the color of the character in order to see it, using the following statement:
The statement
Program 6.8
This program demonstrates how to examine and change the Commodore-64 screen
memory by printing a gray, white and red dart board on the screen. It then takes ten random
shots at the board and computes a score, with the gray area worth 0 points, white 1 point, and
red 10 points:
6-19
300 REM NOW TAKE RANDOM SHOTS
310 for r - i to 10
320 X - INT(40*RND<0))
330 Y - INT<25*RND<0)>
340 C * PEEK(55296+X+40*Y) AND
350 POKE 1024+X+40*Y,42
360 POKE i296+X+40*Y,0
370 IF Ol THEN S = S 1
380 IF C=2 THEN S = S 10
390 NEXT I
400 REM
410 PRINT "YOU SCORED";S;"POINTS.
*
*
Lines 20-30 set up the screen with a gray background and a blue border. Lines 120-130,
which plot a space in reverse mode in white, are placed in a nested loop to plot the white area of
the dart board. Similarly, line 200 is placed in a nested loop to plot the red portion of the dart
board. The loop contained in lines 310-390 causes ten random shots to be taken at the board.
Lines 320-330 pick the random X and Y coordinate, and line 340 checks the color at that
coordinate. Next, a star ("*") is plotted in black by lines 350 and 360 to indicate the coordinate
hit, and lines 370-380 update the score according to the color found. Note that if a spot is hit
twice, its point value will be counted only once.
Certain sections of memory contain information about the computer's display screen.
Memory locations 7680-8185 contain values which correspond to a character code for the
characters displayed on the screen, and memory locations 38400-38905 contain values which
correspond to a color code for the color of each character displayed. The display screen may be
thought of as a 22x23 grid containing 506 character positions, as shown in figure 6-3. It is
possible to use PEEK and POKE to examine and change the contents of the screen. The
statement
L = PEEK(7680 + X + 22* Y)
6-20
will assign L the character code for the character position (X,Y) on the screen. The list of
possible character codes is shown in the character code table. For example,
READY.
indicates that position (21,23) contains the letter "A" in normal mode or the letter "a" in lower
case mode. The statement
will assign C the color code for the color of the character in position (X,Y). The list of color codes
is shown in the VIC-20 color code table in this chapter. For example,
READY.
The statement
will place the letter "B" at position (11,12), which is about the middle of the screen. Note that the
character will be invisible if its color is the same as the background color. Therefore, it may be
necessary to change the color of the character in order to see it, using the following statement:
The statement
Program 6.9
This program demonstrates how to examine and to change the VIC-20 screen memory by
printing a white, yellow and red dart board on the screen. It then takes ten random shots at the
board and computes a score, with the white area worth 0 points, yellow 1 point, and red 10
points:
6-21
10 POKE 646,0 : REM FOREGROUND COLOR=BLACK
20 POKE 36879,1*16+1*8+6 ! REM BACKGROUND-WHITE BORDER-BLUE
* *
*
*
Lines 20 sets up the screen for normal text mode with a white background and a blue
border. Lines 120-130, which plot a space in reverse mode in yellow, are placed in a nested
loop to plot the yellow area of the dart board. Similarly, line 220 is placed in a nested loop to plot
the red portion of the dart board. The loop contained in lines 310-390 causes ten random shots
to be taken at the board. Lines 320-330 pick the random X and Y coordinate, and line 340
checks the color at that coordinate. Next, a star ("♦") is plotted in black by lines 350 and 360 to
indicate the coordinate hit, and lines 370-380 update the score according to the color found.
Note that if a spot is hit twice, its point value will be counted only once.
6-22
Joysticks .
A joystick is an alternate device for interfacing with the computer. Typically found on most
arcade game machines, the joystick is used on the computer in a similar fashion.
Joysticks can be used in a variety of ways. Typical game applications include moving a
figure around on the screen or firing a missile. The joystick has four internal direction switches
which represent up, down, left and right and which are activated by moving the stick. If two of
the switches are activated simultaneously, then a diagonal direction is indicated. For example,
the down switch and the left switch would be activated when the stick is moved to the lower left.
The joystick also has a fire button, which operates independently of the stick. A different set of
commands is required to use the joystick on the Commodore-64 than on the VIC-20. Each will
be explained separately.
Commodore-64 Joysticks
Two joysticks may be connected to the Commodore-64, both of which are used similarly.
Joystick 1 is plugged into Control-Port 1 and joystick 2 is plugged into Control-Port 2.
The following statements are used to determine which direction the sticks are presently
being moved:
The value of the variables J1 and J2 will indicate one of the following:
5 UP and LEFT
6 DOWN and LEFT
8 RIGHT
9 UP and RIGHT
10 DOWN and RIGHT
To determine if the fire button is being pressed the following statements are used:
If either the variables F1 or F2 equal 0, then the respective fire button is being pressed;
otherwise, if the button is not being pressed, the value returned is 16.
6-23
Program 6.10
Each time the fire button on joystick 1 is pressed, this program prints the stick's direction.
The loop at line 70 delays execution of the program to allow the user sufficient time to release
the fire button before the computer checks at line 40 to see if the button is being pressed:
10 FOR I ■ 0 TO 10
20 READ J*(I)
30 NEXT I
40 IF (PEEK<56321) AND 16)=16 THEN 40
50 Jl ■ 15-(PEEK(56321) AND 15)
60 PRINT "THE JOYSTICK IS "iJ$(JD
70 FOR J = 1 TO 200 : NEXT J 1 REM DELAY LOOP
80 GOTO 40
100 DATA CENTERED,UP,DOWN,,LEFT,UP AND LEFT
110 DATA DOWN AND LEFT,,RIGHT,UP AND RIGHT,DOWN AND RIGHT
HUH
THE JOYSTICK IS CENTERED
THE JOYSTICK IS UP
THE JOYSTICK IS RIGHT
THE JOYSTICK IS LEFT
THE JOYSTICK IS LEFT
THE JOYSTICK IS UP AND RIGHT
THE JOYSTICK IS DOWN AND RIGHT
THE JOYSTICK IS DOWN
THE JOYSTICK IS UP AND LEFT
THE JOYSTICK IS DOWN AND LEFT
BREAK IN 40
READY.
Review
5. Write a program for the Commodore-64 that will place the symbol # in one of nine locations
on the display screen, depending upon the movement of the joystick. For example, if the
joystick is moved down and right, the ffishould appear at coordinates (39,24), which is the
lower right hand corner of the screen. If the joystick is centered, the £j should appear in the
middle of the screen.
VIC-20 Joystick
Only one joystick can be connected to the VIC-20. The following initialization statement
must be used in a program before the joystick can be used:
POKE 37139,0
After this statement has been used the following statement determines the status of the fire
button:
F= PEEK(37137) AND 32
6-24
This will set F to 0 if the fire button is being pressed; otherwise F will equal 32.
To determine the direction in which the joystick is being moved, an additional initialization
statement is needed:
POKE 37154,127
will assign to the variable J a value which indicates the direction of the joystick. These values
are the same as those given in figure 6-6 for the Commodore-64.
Because the statements used to make the joystick operative render the keyboard inopera
tive, it is necessary to use the following statement to restore the use of the keyboard and
disengage the joystick:
POKE 37154,255
Program 6.11
This program prints the direction of the joystick each time the fire button is pressed. The
loop at line 130 delays execution of the program to allow the user sufficient time to release the
fire button before the computer checks at line 80 to see if the fire button is being pressed:
10 REM INITIALIZE
20 POKE 37139,0
30 REM
40 FOR I - 0 TO 10
50 READ J*<I)
60 NEXT I
70 REM
80 IF (PEEK(37137) AND 32) THEN 80
90 POKE 37154,127
1 00 J « 15-( (PEEK(37137) AND 28)/4 + (PEEK(37152) AND 123)716)
110 POKE 37154,255 : REM RESET FDR KEYBOARD INFUT
120 PRINT "THE JOYSTICK IS ";J*(J)
130 FOR J = 1 TO 200 : NEXT J
140 GOTO 30
200 DATA CENTERED,UP,DOWN,,LEFT,UP AND LEFT
210 DATA DOWN AND LEFT,„RIGHT,UP AND RIGHT,DOWN AND RIGHT
RUN
THE JOYSTICK IS RIGHT
THE JOYSTICK IS LEFT
THE JOYSTICK IS UP AND LEFT
THE JOYSTICK IS DOWN AND RIGHT
THE JOYSTICK IS DOWN AND LEFT
THE JOYSTICK IS DOWN
THE JOYSTICK IS UP
THE JOYSTICK IS UP AND RIGHT
THE JOYSTICK IS CENTERED
THE JOYSTICK IS DOWN
BREAK IN 80
READY.
6-25
Review
6. Write a program for the VIC-20 that will place the symbol + in one of nine locations on the
display screen, depending upon the movement of the joystick. For example, if the joystick is
moved down and right, the + should appear at coordinates (21,22), which is the lower right
hand corner of the screen. If the joystick is centered, the + should appear in the middle of
the screen.
The Commodore-64 computer, using its built-in sound generator, is capable of producing a
wide range of sounds. Six locations in the computer's memory are used to control the volume
and pitch of the sound:
Memory Poke
Location Purpose Range
The tone code can be any value between 0 and 65535, inclusive, with 0 the lowest note and
65535 the highest. The following program segment will set the tone registers (locations 54272
and 54273):
6-26
The sound generator is capable of producing notes over a range of 8 musical octaves. The
following table can be used to find the tone code of a particular sound, given the octave and
note:
OCTAVE
4 5
For example, to produce the note F# in the sixth octave, use the tone code 12139. Remember
that two POKE statements are used when setting the tone code.
Before any sound can be heard, several additional steps must be taken. First, the volume
level must be set by poking a value between 0 and 15 into memory location 54296, the volume
control register. For example, the statement:
POKE 54296.8
sets the volume level to about halfof the loudest setting, which is 15.
The second step is to select the desired ATTACK, DECAY, SUSTAIN, and RELEASE
rates of the sound to be played. When a musical tone is played, for instance on a piano, its
volume changes continuously. The ATTACK is the rate at which the volume level rises from
zero to maximum or peak value. After peak volume has been reached, the sound begins to
subside. The rate at which this happens is called the DECAY. The sound will diminish until it
hits the SUSTAIN level, which is the proportion of the peak volume that will be maintained after
the DECAY cycle. The RELEASE is the rate at which the sound volume falls from the SUSTAIN
level to zero. Graphically, the sound appears as follows:
6-27
Peak volume
Sustain
level
The ATTACK and DECAY rates, each of which is between 0 and 15, are set by poking
memory location 54277. For example:
Since both the ATTACK and DECAY share the same memory location, it is necessary to
multiply the ATTACK by 16. Remember that neither the ATTACK nor the DECAY rates can
exceed 15, which is the slowest rate of change.
The third step is to set the SUSTAIN level and RELEASE rate, each of which must also be
between 0 and 15. Similar to ATTACK and DECAY, SUSTAIN and RELEASE share a single
memory location. These values can be set by poking location 54278 as follows:
Remember to multiply the SUSTAIN level by 16 and add it to the RELEASE rate in poking
location 54278. The slowest RELEASE rate is obtained by using 15, while the fastest is 0.
The fourth step is to select the wave form of the sound to be heard. The following table is a
summary of available wave forms:
Poke Wave
Value Action Form
0 Disable Sound
As soon as the wave form is selected and location 54276 is poked, the sound will begin to play.
The ATTACK cycle is started, followed by the DECAY cycle, until the SUSTAIN level is
6-28
reached. The sound will continue to play at the sustain level until the sound control register is
again poked with the statement:
The variable K represents the value used in the first POKE done on memory location 54276,
which started the sound to play. This second use of the POKE statement starts the RELEASE
cycle, causing the sound to fade out. Optionally, the sound may be immediately cut off by
poking zero into the sound control register {location 54276). Be sure to provide an ample delay
before beginning the RELEASE cycle to allow the ATTACK, DECAY and SUSTAIN cycles to
occur properly.
Program 6.12
This program plays the note G# from the 7th octave. The RELEASE cycle is not begun
until the user presses the spacebar.
A delay is created by line 130 which allows the tone to play for a few seconds. If line 160 were
omitted, the sound would continue to play, even after the program finished its run.
Review
7. Write a program that will play the note D# in the third octave followed by the note A in the
seventh octave.
The VIC-20 computer is capable of producing a variety of sounds using its 4 built-in sound
generators. Five locations in the computer's memory, called "registers", are used to control the
volume and pitch of the sounds. There are 3 tone generators, which are each capable of
6-29
generating an independent sound. In addition, there is a separate noise generator, which
produces a static sound. By combining the static noise generator with the tone generators,
interesting sound effects can be created. The following table lists the five memory locations
relevant to sound control:
Memory Poke
Location Purpose Range
Note that each tone generator is capable of producing a sound in a three octave range, yet
all three cover only a five octave range. The tone generators are staggered so that the octaves
of each overlap.
The following musical notes can be played by poking appropriate values into any of the
three tone generators:
can be used. The note will continue to play until the tone generator is turned off by the
statement:
POKE 36876, 0
Note that each tone generator must be turned off individually. If the tone generator located at
36874 is used, then the statement
6-30
POKE 36874, 0
POKE 36878. 8
sets the volume output to about half. The sound from all four generators is controlled by this
single setting. The sound can be turned off by the statement:
POKE 36878. 0
One of the best features of the VIC-20 sound generators is that up to four different sounds
can be played simultaneously. To play C# in the third octave and G# in the fifth, the following
program segment is used:
or
Program 6.13
This program creates an acceleration sound effect by staggering the notes played by each
tone generator and the static sound generator:
6-31
Note that the S loop (lines 20-70) runs from 128 to 254, but the second tone generator creates
no sound until S-32 exceeds 127. Likewise, the third generator creates no sound until S-64
exceeds 127, and the static generator doesn't produce sound until S-96 exceeds 127. Re
member that a sound generator does not produce sound until the value of the POKE statement
is between 128 and 255.
Review
8. Write a program that will play F# from the first octave followed by the note A# from the fifth
octave.
Program 6.14
This program plays a simplified space game. The enemy, an "@", starts at the top left
hand corner of the screen and begins walking. When an edge of the screen is reached, she
moves one row closer to the player and reverses direction. The player, which is represented by
a "1", must destroy the alien before it reaches the row in front of the player. To do this the
player may move left or right with either the joystick or the comma (,) and period (.) keys on the
keyboard. The player must shoot the alien with an arrow (| ) by using the joystick's fire button
or the space bar. If the player hits the alien with the arrow, the alien is destroyed and a smoke
ring appears; otherwise, if the alien reaches the player, the player is destroyed.
6-32
240 IF (0*="," DR J=4) AND XP>1 THEN XP=XP-1
250 POKE SCRN+XP+XM*YM,113 : POKE COLR+XP+XM*YM,14
260 REM
270 REM
300 REM ARROW UPDATE
310 POKE SCRN+XA+XM*YA,32 : REM REMOVE OLD ARROW
320 IF F»l THEN YA=YA-1 : XF YA<0 THEN YA=YM-1 : XA=XP : F*0
330 IF F=0 THEN XA=XF
340 POKE SCRN+XA+XM*YA,30 : POKE COLR+XA+XM*YA,2
350 REM
360 REM
400 REM INVADER UPDATE
410 POKE 54276,32 : C-360S : REM SOUND
420 POKE 54272,C-INT(C/256)*256 : POKE 54273,INT(C/256)
430 POKE 54276,33
440 POKE SCRN+XI+XM*YI,32 : REM BLANK OUT OLD INVADER
450 XI=XI+D : IF XIXXM-1) THEN XI^XM-1 : D=-l : YI=YI + 1
460 IF XK0 THEN XI-0 : D=l : YI=YI+1
470 POKE SCRN+XI+XM*YI,0 : POKE COLR+XI+XM*YI,0
4S0 REM
490 REM
500 GOTO 130
510 REM
800 REM EXPLOSION SEQUENCE
810 POKE 54296,15 : POKE 54276,129 : C=8000
820 POKE 54272,C-INT(C/256)*256 : POKE 54273,INT(C/256)
830 POKE SCRN+X+XM*Y,73 : POKE COLR+X+XM*Y,0
840 POKE SCRN+X-1+XM*Y,85 : POKE COLR+X-1+XM*Y,0
850 POKE SCRN+X-1+XM*(Y+1),74 : POKE COLR+X-1+XM*(Y+l),0
860 POKE SCRN+X+XM*(Y+1),75 : POKE COLR+X+XM*<Y+l),0
870 FOR D - 1 TO 750 : NEXT D : POKE 54276,128 : POKE 54296,0
880 IF W=0 THEN PRINT "YOU WIN!"
890 IF W=l THEN PRINT "YOU LOSE."
900 END
Lines 10-20 clear the screen, set the background to white, and the border to blue. Lines
100-110 initialize the needed variables.
The section at 200-250 tests to see what the player wants to do. First the player's old
position is blanked out, then line 215 gets a character from the keyboard and the joystick
direction value. The conditions in line 220 check to see if a shot is to be fired, while lines
230-240 check to see if the player wishes to move either right or left. Finally, line 250 redraws
the player on the screen.
The block from 300-340 moves the arrow on the screen. After line 310 erases the arrow,
line 320 calculates the arrow's next position only if it is being fired. Otherwise line 330 keeps the
arrow positioned immediately above the player. The arrow is redrawn in its new position by line
340.
Lines 410-430, in combination with lines 150-170, produce the sound of the moving alien,
whereas lines 440-470 move the alien. The old position in blanked out by line 440, then lines
450-460 calculate the invader's next position. The invader's X coordinate is either increased or
decreased by 1, depending on the direction she is moving. However, if an edge of the screen is
reached the invader's Y position is increased by 1, and the direction of movement is changed.
This is repeated until either the alien is hit, which is checked for at line 130, or the invader
reaches row 21. When one of these conditions is found to be true, the variables X and Y are set
6-33
to the coordinates of where the explosion is to occur. Then program control is passed to line
800, where the explosion sound is produced and the explosion is drawn.
Note that this program will only work on the Commodore-64. To run this program on the
VIC-20 the following lines must be changed:
Also, lines 160, 170, 420, 430 and 870 must be deleted.
6-34
EXERCJ5E5
1. Have the computer draw a solid red rectangle with its upper left corner at (4,8), a length of
16 columns and a height of 10 rows.
2. Using graphic characters, draw a black vertical line and a black horizontal line which
intersect at (5,17).
3. Place a flashing red notice on the text screen which advertises Uncle Bill's Whamburgers
for 790. The screen should have a blue background and a green border.
TODAV ONLV!
UNCLE BILL'S
WHAMBURGERSf
ONLV SO.79
5. Have the computer completely fill the left half of the screen with randomly colored points.
(a) Using the PEEK function, duplicate the left portion of the screen on the right side of the
screen.
(b) Rewrite part (a) so that the right portion of the screen is a mirror image of the left
portion.
6-35
6. Write a program that will play the game called Bomb in a Box. There are six boxes and only
one box contains a bomb. The player and the computer alternately pick a box number, and
if the box chosen contains the bomb, the bomb explodes. The player chooses first, and
then the computer chooses from the remaining boxes, using a random number. Use the
sound generator to simulate a click of the lid of an empty box being opened or an appro
priate sound for the explosion of the bomb. If the computer loses, have the screen and the
cursor turn black.
7. Have the computer generate 100 random integers between 1 and 10, inclusive. Plot a
properly labeled bar graph showing the number of occurrences of each number.
±23-456789 ±8
8. Write a program to produce a bar graph for Cheryl's Shoe Shop. The data given below
represents the number of pairs of shoes sold a day by each of the five employees over the
course of a week. Make a bar graph showing the average number of shoes sold per day for
each employee.
9. Turn the Commodore into an organ. Pressing a key on the keyboard should cause certain
notes to play continuously until another key is depressed. Use the following table of keys
and fifth octave notes:
key Z s X D C V G B H N J M
note C c# D D# E F F# G# A A# B C
6-36
If a key other than one in the table is pressed, all sound should stop until a key in the table
is pressed. Your program should make sure a moment of silence is heard if the same note
is played more than once in a row.
10. A programmer can make computer animation by flashing pictures on a screen in quick
succession,
(a) Write a program that will make an arrow similar to the one shown below:
(b) Make the arrow appear to move across the screen by continuously redrawing it a space
to the right each time, using the TAB function.
11. (a) Write a program that will make a stick figure run in place on the screen. The runner is
made of five different pictures flashed on the screen in sequence. The five different pic
tures, given below in sequence, are made from the special graphic characters on the
keyboard:
o o o
A h I
(b) Make the runner appear to move across the screen by redrawing the runner a space or
two to the right after the last picture.
12. Write a program to simulate the roll of a single die which shows a picture of the die on the
screen. The die should be rerolled with each press of any key.
13. A seven segment display is used to represent a number on a digital clock. The seven
segments are arranged as shown below in figure-a (numbered zero through six), and when
certain segments are lit, they form the figure of a numeral:
2 -4
iTl ± 8
ITl
l_l 6 16
l_l 6-4
5 32
figure a figure b
6-37
109, successively divide it by two. If the result of the first division is not an integer, then the
segment numbered zero should be lit. Then take the INT of the result and again divide by
two. If on this second pass the result is again not an integer, then the segment numbered
one should be lit. Again take the INT of the result. Continue this process of dividing by two
and checking the result seven times (once for each segment). Use POKE to place the bars
on the screen as three connecting horizontal or vertical graphic characters,
(a) Write a program to produce one seven segment display as described above, and
program the computer to display slowly the sequence from zero to nine.
(b) Modify part (a) of this problem to incorporate a second seven segment display and have
the computer count slowly to ninety-nine.
6-38
CO ^ O < |_ O
< < <wOH<i
era
□
This chapter covers the various mathematical functions that the computer can perform.
The extent to which they can be useful to an individual depends on his or her mathematical
background. Generally speaking, the functions presented here are primarily employed by
mathematicians, scientists and engineers.
SQR
10 PRINT SQR(14)
The square root of a number N is defined as that value which, when multiplied by itself, gives N.
For instance, the square root of 36 is 6 because 6x6 = 36.
Program 7.1
10 FOR X = 1 TO 4
20 PRINT "THE SQUARE ROOT OF"; X; "IS"; SQR(X)
30 NEXT X
RUN
THE SQUARE ROOT OF 1 IS 1
THE SQUARE ROOT OF 2 IS 1.41421356
THE SQUARE ROOT OF 3 IS 1.73205081
THE SQUARE ROOT OF 4 IS 2
READY.
In the expression SQR(X), SQR is the function name and X is called the argument. With the
SQR function, the argument may be any mathematical expression with a non-negative value.
For example, SQR{3*X + 5) is perfectly acceptable provided that the expression
3*X + 5 produces a non-negative value.
Note that the argument of a function must be enclosed in parentheses. In its evaluation of a
mathematical function, the computer first evaluates the argument and then the function. Some
functions have a limitation on the value of the argument. Such limitations will be indicated as the
functions are introduced.
SGN(X) = I if X>0
SGN(X) - 0 if X=0
SGN(X) = -1 if X<0
7-1
Program 7.2
This program finds the SGN (signum) of the numbers from 6 to -6, incrementing by -1.2:
RUN
SGN C 6 ) « 1
SGN( 4.8 >= 1
SGN< 3.6 ) = X
S6N( 2.4 )= 1
SGN( 1.2 )= 1
SGN< 0 ) = 0
SGN(-1.2 ) =-1
SGN(-2.4 ) =-1
SGNC-3.6 ) =-1
SGN(-4.8 ) =-1
READY.
Note that X does not reach -6. This is due to the rounding error.
The ABS function can be used to find the absolute value of a number. The ABS function
yields values according to the rule:
ABS(X) - X if X> = 0
ABS(X) = -1*X if X<0
Program 7.3
RUN
6 4.8 3.6 2.4 1.2 0 1.2 2.4 3.6 4.8
READY.
Review
1. What is X when
X = SQR (ABS(SGN(-9+9/3)-6)+9)?
7-2
2. Write a program to calculate the distance between any 2 points in a Cartesian coordinate
system. Hint: use the formula:
RUN
FIRST COORDINATE (X1,Y1)? 1,1
SECOND COORDINATE (X2,Y2)? 4,5
DISTANCE IS 5
READY.
The computer is able to find the values of several trigonometric functions. The functions
SIN(X), COS(X) or TAN(X) will produce the value of the sine, cosine or tangent of the angle X,
where X is measured in radians. To convert an angle from degrees to radians, multiply it by n
and then divide the result by 180 (180 degrees equals n radians). On the computer n =
3.14159265.
Program 7.4
10 INPUT "VALUE";A
20 X ■ A * «f / 180
30 PRINT A; "DEGREES EQUALS"; X "RADIANS
40 PRINT "SIN<";A;") =";SIN(X>
50 PRINT "C0S(";A;"> =";COS(X)
60 PRINT "TANCjAj ") =";TAN(X>
70 PRINT
80 GOTO 10
RUN
VALUE 30
30 DEGREES EQUALS .523598776 RADIANS.
SIN( 30 ) = .5
C0S( 30 ) = 866025404
TAN( 30 ) = .577350269
VALUE 45
45 DEGREES EQUALS ,735398163 RADIANS
SIN < 45 ) = .707106781
C0S( 45 ) « .707106782
TAN< 45 ) - .999999999
VALUE?
7-3
ATN
The only inverse trigonometric function supplied by the computer is the principal arctan
gent function ATN. The function ATN(X) is used to find the angle whose tanget is X. The value
produced by the ATN function is in radians. Thus, the arctangent of 1 is n/4 radians =
.785398163. To convert an angle from radians to degrees, multiply it by 180 and then divide the
result by n. The ATN function, just like the principal arctangent function in mathematics, gives
values only between - n/2 and n/2 radians. There is no limitation on the value that the
argument may assume.
Program 7.5
This program finds the angle whose tangent is entered and prints the result in degrees:
RUN
ENTER A TANGENT VALUE? 1
THE ANGLE WHOSE TAN8ENT IS 1 IS 45 DEGREES.
To find the principal arcsine of a number, the programmer must use the following identity:
Therefore, to find the principal angle whose sine is X, the expression ATN(X/SQR(1 -
XT2)) is used. This angle will be measured in radians and will be between -n/2 and n/2. The
value of X, however, must be between -1 and 1, not inclusive.
To find the arc cosine of X, use the expression ATN(SQR(1 -X"[2)/X). This gives the angle,
which is between -n/2 and n/2 whose cosine is X. In this expression, X must be between -1
and 1, inclusive, not not equal to 0.
7-4
Program 7.6
This program finds the arcsine and arc cosine of X in both radians and degrees:
10 INPUT "VALUE";X
20 S = ATN(X / SQRU - X'2))
30 Si - S * 180 / -rf
40 C = ATNCSQRU - X^2) / X)
50 Cl = C * 180 / rt
60 PRINT "THE ANGLE WHOSE SIN IS";X;"IS";S|"RADIANS"
70 PRINT "THE ANGLE WHOSE COSINE IS";X;MIS";C;"RADIANS.
80 PRINT "THE ANGLE WHOSE SIN IS";X;"IS";Si;"DEGREES."
90 PRINT "THE ANGLE WHOSE COSINE IS";X;"IS";Cl;"DEGREES
100 PRINT : GOTO 10
RUN
VALUE? .5
THE ANGLE WHOSE SIN IS .5 IS .523598776 RADIANS
THE ANGLE WHOSE COSINE IS .5 IS 1.04719755 RADIANS.
THE ANGLE WHOSE SIN IS .5 IS 30 DEGREES.
THE ANGLE WHOSE COSINE IS .5 IS 60 DEGREES.
VALUE? .877
THE ANGLE WHOSE SIN IS .877 IS 1.06958255 RADIANS
THE ANGLE WHOSE COSINE IS .877 IS .501213777 RADIANS.
THE ANGLE WHOSE SIN IS .877 IS 61.282566 DEGREES.
THE ANGLE WHOSE COSINE IS .877 IS 28.7174341 DEGREES.
VALUE?
The LOG function can be used to find natural logarithms, that is, logarithms to the base e.
To find the natural logarithm of X, LOG(X) is used. Do not confuse the natural logarithm with the
common logarithm usually studied in a second year algebra course. The common logarithm,
that is, logarithm to base 10, can be found from the natural logarithm by using the formula:
ln(X)
log10 (X) =
In the above ln(X) designates the natural logarithm of X. Therefore, to find logio (X), simply
use LOG<X)/LOG(10). The argument in the LOG function must always be positive.
The function EXP(X) is used to find values of the exponential function ex, where e =
2.71828. This number is the same as the base of the natural logarithm function.
7-5
Program 7.7
RUN
ENTER X? 1
LN(X) - 0
E RAISED TO X = 2.71B2B183
THE COMMON LOGARITHM OF 1 IS 0
ENTER X? .01
LN<X) =-4.60517019
E RAISED TO X = 1.01005017
THE COMMON LOGARITHM OF .01 IS-2
ENTER X? 10000
LN(X) ■ 9.21034038
THE COMMON LOGARITHM OF 10000 IS 4
ENTER X? .525
LN(X) =-.644357016
E RAISED TO X = 1.69045885
THE COMMON LOGARITHM OF .525 IS-.279840697
ENTER X?
Line 30 is necessary to avoid the memory overflow that occurs when X is larger than 88.
DEF
Several standard functions, such as SQR, ABS and LOG, have already been introduced in
this chapter. In addition, the programmer can define other functions by using a DEF statement.
The major advantage of DEF lies in the fact that the expression for the function need only be
written once, even though the function can be evaluated at more than one location within the
program. The form of a DEF statement is:
The function name may be any acceptable numeric variable name (e.g., FNA, FNF, FNG3).
The variable name (i.e., the argument) following the function name must always appear within
parentheses and may be any appropriate numeric variable. In the following example,
7-6
P is the function name, X is the variable name, and X2 - 2X -1 is the expression used to
compute the function's value. For instance, when X = 5, FNP(X) = 14 because 5|2 - 2*5 - 1
= 14.
Program 7.8
The following program evaluates the polynomial function FNP(X) several times:
RUN
X FNP(X)
1 ~2
2 -1
3 2
4 7
5 14
? -10
THE RESULT OF FNP(-10 ) IS 119
READY.
When the function is evaluated at line 40, the variable in parentheses is A. When it is evaluated
at line 70, the variable is X. The name of the variable in parentheses may be the same as or
different from the variable name used in the DEF statement. Note also that if the DEF statement
were not used, the formula on line 10 would have to appear twice {lines 40 and 70). Though the
function is defined only once, it may be evaluated anywhere within the program, providing
program economy.
Another advantage of the DEF statement is that it can be easily retyped to define a
different function. This is illustrated by re-running Program 7.8 with line 10 changed to:
RUN
X FNP(X)
T
1
2 -11
3 -17
-15
5 1
*■?
10
THE RESULT OF FNP< 10 ) IS-1499
READY.
7-7
Review
3. Write a program that will produce the following output. Two user defined functions should be
used: one to convert degrees to radians, the other to convert radians to degrees:
RUN
DEGREES? 30
THAT IS .523598775 RADIANS.
RADIANS? .785375
THAT IS 44.9986729 DEGREES.
READY.
7-8
EXEBCJSES
1. When a number is input, have the computer generate the following output. Be sure to
account for a negative input:
RUN
? -l
NO NEGATIVE NUMBERS ALLOWED.
? 4
N = 4 SQUARE ROOTS = + OR - 2
2. Write a program which prints the integers from 121 to 144, inclusive, and their respective
square roots. Label each column of the output.
3. Write a program that will print COS(X) and SiN(X+9(T), where X varies from 0 to 360
degrees in increments of 10 degrees.
4. Input a number N. If N is zero, print 0. Otherwise, print ABS(N)/N. What does the program
do?
5. Input a number N and print the product of SGN(N) and N. What does this program do?
6. Input a number N, square it and print the square root of the result. What should the
program produce?
7. Print a table consisting of 2 columns with headings showing each angle in radians and
degrees. The angles in radians are to be 0, .25, .5, 75, ..., 3.0. Remember that 180° - ■»
radians.
8. Input an angle in degrees and convert it to a fraction of a revolution (1 rev. = 360°) and to
radians.
9. Input an angle in degrees. Of the three functions sine, cosine, and tangent, print the value
of the one which has the greatest value.
7-9
10. For angles from 0° to 180° (at intervals of 10°) print the angle in degrees, the sine, the
cosine, and the sum of their squares in columns with headings. What patterns emerge?
11. Input two numbers (A,B). Print the quantity F(B)-F(A), given that F(X) - 9X:! - 7X2 +
4X - 1.
12. Input a number N. Print the values of F{N) and F(F(N)), where F(X) = 20 * SQR (ABS(X))
- 10 * SGN(X) + 5 * INT(X).
13. Print a table (with headings) of X, the natural logarithm of X and the exponential function of
XforX = 1 to 15.
14. Print a table (with headings) of X, the logarithm of X to the base 10, and 10 raised to the
power X for X = 1 to 15.
15. What is the exact output for the following program? Check by running the program:
10 READ A,B,C,D
20 PRINT SQR(A) , INT<B) ,SQR(INT(C) ) f INT(SQR(D) )
30 DATA 25,-3.4,9.7,24
16. Print the square root of the integers from 50 to 60, inclusive.
17. What is the exact output for the following program? Check by running the program:
18. Input a number and print the square root, sign, log and sine of the number. For example:
RUN
? 16
SQR( 16 > = 4
SGN< 16 ) « I
L0G( 16 ) = 2.77258872
SIN( 16 > =-.287903315
READY.
19. What is the exact output for the following program? Check by running the program:
10 FOR X = ~3 TO 4
20 READ A
30 PRINT SGN(X) * ABS(X)
40 NEXT X
50 DATA 3,-5*1,6,-2,4,-9,5
7-10
20. Using three user-defined functions, have the computer evaluate the following for the inte
gers from -10 to 10:
X2 + 3X + 2
LOG(X2 + 1) - X
ATN(SIN(X))
21. Write a program to convert from polar to rectangular coordinates (i.e., from (r,0) to (X,Y)).
22. If two functions, F and g, are inverse to each other, the following relations hold:
f(g(x)) = x and g(f{x)) = x.
(a) Tabulate the values of the following quantities for X = -5 to 10: X, EXP(X),
LOG(EXP(X)).
(b) Print a table for X = 1 to 151 of X, LOG(X), EXP(LOG(X)), using STEP 10.
(c) Do EXP and LOG appear to be inverse to each other?
23. Produce your own sequence of random numbers without using the RND command. To do
this, let X vary from 1 to 100 in steps of 1. Obtain SIN(X) and multiply this by 1000, calling
the absolute value of the product Y. Divide INT(Y) by 16, and let the remainder R serve as
your random number. Hint: the remainder of A -^ B is A/B - INT{A/B).
24. Six year old Dennis the Menace has decided to invest 500 in the Last Chew Bubble Gum
Company. Starting with the 11th year, he withdraws 50 at the beginning of each year. His
money earns 8% interest compounded continually. The formula for interest compounded
continually is P = P^e1', where t is the elapsed time in years, Po is the initial deposit, P is the
amount at time t, and i is the interest rate. In this case the formula would be P = P,,el)M.
How much is Dennis's deposit worth after 50 years?
7-11
25. Use the SIN function to generate the following:
RUN
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
SHAZAM!
READY.
26. Write a program that will solve a triangle (computer the unknown sides and angles) for the
following situations:
(a) given two sides and the included angle,
(b) given two angles and any side,
(c) given three sides.
7-12
STflJNG HJWCTJQWS
t) DflTfl TVPES
ASC
CHR$
LEFT$
LEN
MID$
RIGHTS
STR$
VAL
ASC
CHR$
LEFT$
LEN
MID$
RIGHTS
STR$
VAL
ASC
CHR$
LEFTS
LEN
MIDS
RIGHTS
STRS
VAL
ASC
CHRS
LEFTS
LEN
Modern computers have resulted from the union of the binary system with the principles of
electricity. The binary number system uses only two digits, 0 and 1, and can therefore be
represented by the two states of an electric circuit, off or on. This concept has made digital
computers possible because they operate by reducing all data to a binary code. How different
types of data can be reduced to a binary system is explained in this chapter.
Binary Code
The most familiar number system, the decimal system, uses ten digits: 0, 1, 2, 3, 4, 5, 6, 7,
8, 9 and is therefore considered to be base ten. In contrast, the binary system, which uses only
the digits 0 and 1, is base two.
In the base ten system, columns are used to represent powers of ten with the first column
left of the decimal point representing 10°, the second 101, the third 102 and so on. For example,
in the numeral 458, 8 represents 8x10°, 5 represents 5x101 and 4 represents 4x102. The
numeral itself represents the sum: 4x102 + 5x101 + 8x10°.
The base two system works identically except the columns represent powers of two
instead of ten. For example, in the numeral 101, the 1 on the right represents 1x2°, the 0
represents 0x21 and the 1 on the left represents 1x22. The numeral itself represents the sum
1x22 + 0x21 + 1x2°, which is known as five in the base ten system.
To convert a number from base ten to base two, we must find which powers of two add up
to the number. Since 13 = 8 + 4 + 1, the base two representation for 13 is 1101 (1x8 + 1x4 +
0x2 + 1x1).
8-1
A single binary digit (0 or 1) is called a "bit", and eight of these bits constitute a "byte".
Single characters require one byte and integers two bytes of memory for storage. The memory
stores both instructions for the CPU and data as binary digits.
The power of a computer is vastly increased when it is capable of storing letters and
special characters as well as numbers. In order to do this, a code has been established to
translate letters and special characters into numbers, which can then be stored in a binary form.
This code has been standardized by the computer industry as the American Standard Code for
Information Interchange (ASCII). In this code each letter of the alphabet, both upper case and
lower case, each symbol, and each control function used by the computer is represented by a
number. For example, the name JIM is translated by the computer into ASCII numbers
74,73,77. In turn these numbers are then stored by the computer in binary form:
j = 74= 01001010
I = 73 = 0I001001
M - 77 = 010O1I0I
In order for the computer to store a name such as JIM, or any piece of non-numeric
information, it must be entered in the form of a string, converted character by character to ASCII
numbers, and then stored in memory as binary numbers. On the following page is a table of the
ASCII character codes available on the computer.
8-2
ASCII Code Table
0 50 2 100
a 150 (light red)
1 51 3 101
□ 151 (dark gray)
4 54 6 104
a 154 (light blue)
11 61 - 111
□ 161 D
12 62 ^> 112 □ 162 H
13 (carnage return) 63 ? 113 m 163 □
D
r 1
15 65 A 115 y 165 □
16 66 B 116 I 166
B
17 (cursor down) 67 C 117
Q 167 □
18 (reverse on) 68 D 118 X 168 a
19 (home) 69 E 119 o 169 B
20 (delete) 70 F 120 B 170 □
21 71 G 121 a 171
22 72 H 122 m 172 .
23 73 I 123 BB 173 Q
24 74 J 124 I] 174
ffl
25 75 K 125 CD 175 U
26 76 L 126 E 176 H
27 77 M 127 a 177 e
28 (red) 78 N 128 178 -r
45 _ 95 _
145 (cursor up)
47 / 97
a 147 (clear screen)
48 0 9a CD 148 (insert)
49 1 99 B 149 (brown)
8-3
Data Types
When information is entered into the computer, it can take one of three forms: ASCII
characters, integers or floating point numbers. An integer is a number without decimal places,
while a floating point number has either a decimal point or an implied decimal point and decimal
places. For example, the number 29 could be either integer or floating point, but 29.73 is
definitely floating point. Floating point numbers are internally accurate to ten significant figures
but rounded to nine when printed.
Storage of an integer requires 16 bits, a floating point number 32 bits, and an ASCII
character 8 bits. Because of storage requirements it is important to distinguish among the
several forms. When files are presented in Chapter 9, the significance of this factor in planning
efficient storage of data will become apparent.
The three data types employ different symbols to inform the computer as to which is being
used. Strings of ASCII characters employ the familiar symbol ($) for string variable names (e.g.
G$, B3$). Integers, which have the disadvantage of being restricted to the range -32768 to
32767, are denoted by a percent sign (%). B% and Z% are variable names for integers. While
integers have a severe range limitation, they are processed fastest by the computer. Variables
and constants not specifically declared otherwise are assumed to be floating point (e.g., R, L).
Program 8.1
This program demonstrates the difference between floating point and integer arithmetic:
10 A7.-4/3
20 PRINT A7.
30 A=4/3
40 PRINT A
50 END
RUN
1
READY.
The computer approximates the fraction 4/3 as 1.33333333 and assigns this value to the
floating point variable A at line 30. However, as A% can only have integer values, the computer
truncates all the numbers after the decimal point and assigns it the value of 1.
Review
1. What are the minimum number of bits required to store the following data in the computer?
(a) 6167
(b) APRIL I. I963
(c) 42864
(d) 35.78
8-4
ASCII Code—ASCII Character Conversions
Earlier in this chapter the ASCII code was described as a method by which the computer
converts information in the form of strings into numbers. Commands exist to convert strings into
ASCII values and vice versa:
Function Operation
X = ASC(P$) Converts only the first character of the string P$ to its ASCII code
number.
P$ = CHR$(X) Assigns the character with the ASCII code number of X to P$, which
now contains only one character.
Program 8.2
RUN
ENTER ANY CHARACTER? R
THE ASCII VALUE OF 'RMS: 82
>R' REPEATED 17 TIMES LOOKS LIKE THIS:
RRRRRRRRRRRRRRRRR
WOULD YOU LIKE TO RUN THIS AGAIN? N
READY.
8-5
Review
2. Write a program that will allow the user to input a letter. Have the computer print that letter's
ASCII code and then print the letter that comes two letters after it in the alphabet. If Y or Z is
the letter input, then A or B should be returned respectively.
RUN
INPUT A LETTER? R
THE ASCII OF 'R' IS 82
TWO LETTERS AFTER 'R* IS ' T'
READY.
Function Operation
L = LEN(A$) Assigns L a value equal to the number of characters in the string A$,
including blank spaces.
M$ = MID$(A$,N) Assigns M$ a substring of the string A$ from the Nth character to the
rightmost character of the string.
M$ = MID$(A$,N1,N2) Assigns M$ a substring of the string A$, starting with the character N1
and being N2 characters long.
V = VAL(A$) Converts the first set of numeric characters in the string A$ into a
numeric value that is assigned to V. Non-numeric characters are
ignored.
8-6
Program 8.3
This program will input a string and manipulate it to show the use of string functions:
10 INPUT T*
20 PRINT
30 PRINT "'"3T*F"* BACKWARDS IS: ";
40 FOR X=LEN(T*> TO 1 STEP -1
50 PRINT MID$(T$,Xs1);
60 NEXT X
70 PRINT
80 PRINT "THE VALUE OF "l;T$il" IS:";VAL(T$)
90 PRINT "'"IT*!1" HALVED AND FLIPPED IS:11
100 PRINT RIGHT*(T*,LEN<T*>/2>;LEFT*(T*,LENCT*>/2)
110 PRINT "'"5VAL(T$>5"' BACKWARDS IS: "J
120 FOR X=LEN<STR*<VAL(T*>)) TO 1 STEP -1
130 PRINT MID$(STR$(VAL(T*) ) ,X, 1);
140 NEXT X
RUN
? 145RTLMJDQ
Program 8.4
This program plays the game Hangman with the user. The computer picks a random word
from the DATA statements and allows the user to guess letters which may be contained in the
word. If the letter guessed is in the word, the computer shows the user the position in which it
appears. If the letter guessed is not in the word, it is counted as a mistake. Play continues until
the user guesses all the letters in the word or makes 6 mistakes.
90 NEXT I
90 PRINT D$
100 PRINT "YOU HAVE";H;"MISTAKES."
110 INPUT "LETTER";L*
120 REN
8-7
200 REM PRINT CURRENT WORD STATUS
210 FOR 1=1 TO LEN(W*>
220 IF MID*(W$, I, 1)OL$ THEN 240
230 D*=LEFT*(D*,1-1)+L*+RIGHTS(D*,LEN<D*>-I)
240 NEXT I
250 IF D$=W* THEN 400
260 M=M+F : F»l
270 IF M=6 THEN 500
300 GOTO 90
310 REM
400 PRINT "YOU GOT IT!!" : END
410 REM
500 PRINT "YOU HAVE TOO MANY MISTAKES."
510 PRINT "THE WORD WAS ";W$;".n
520 REM
600 REM DATA SECTION
610 DATA COMMODORE,COMPUTER,KEYBOARD,MONITOR
620 DATA HUTT,JEDI,EWOK,CARBONITE,SABER,FALCON
RUN
O.K. I'M THINKING OF A WORD.
READY.
Function Keys
Both the Commodore-64 and VIC-20 computers have a set of function keys on the right
hand side of the keyboard. In order to tell which key is being pressed, a GET must be used in
conjunction with the ASC function. The table below shows the ASCII codes that correspond
with the function keys:
Key ASCII
Fl 133
F2 137
F3 134
F4 138
F5 L35
F6 139
F7 136
F8 1-41)
8-8
The odd-numbered keys are activated by pressing the appropriately numbered key, even-
numbered keys by pressing SHIFT and the appropriately numbered key. The function keys are
useful in allowing a user to direct program flow to one of up to eight options.
Program 8.5
This program uses the function keys to send the flow of the program to one of eight
subroutines. The technique demonstrated is useful when employed in programs in which
selections must be made:
10 FOR X«l TO 8
20 READ K(X)
30 NEXT X
40 PRINT "PRESS ONE OF THE FUNCTION KEYS"
50 GET G$ : IF G*="" THEN 50
60 X=ASC(G*>-132
70 ON K<X) GOSUB 100,200,300,400,500,600,700,S00
80 END
90 REM
100 PRINT "YOU PRESSED Fl"
110 RETURN
120 RFM
200 PRINT "YOU PRESSED F2"
210 RETURN
220 REM
300 PRINT "YOU PRESSED F3"
310 RETURN
320 REM
400 PRINT "YOU PRESSED F4"
410 RETURN
420 REM
500 PRINT "YOU PRESSED F5"
510 RETURN
520 REM
600 PRINT "YOU PRESSED F6"
610 RETURN
620 REM
700 PRINT "YOU PRESSED F7"
710 RETURN
720 REM
300 PRINT "YOU PRESSED F8"
810 RETURN
820 REM
830 DATA 1,3,5,7,2,4,6,8
RUN
PRESS ONE OF THE FUNCTION KEYS
YOU PRESSED F3
READY.
The loop (lines 10-30) reads the data at line 830. This technique is required since the ASCII
values of the function keys are not sequential. Note how line 60 is now able to produce a value
for X of from 1 through 8, depending upon which key has been pressed at line 50.
8-9
EXERCJSE5
1. Enter a string A$ and use a loop to print the ASCII number of each of its characters.
2. Input three letters, add their ASCII numbers, find the INT of one third of their sum and print
the character corresponding to the result. Is there any meaning to this process?
3. Using properly selected ASCII numbers on a DATA line, print the sentence "ASCII DID
THIS!"
4. Using ASCII numbers 45 and 46 and the PRINT TAB statement, print the following figure:
RUN
READY.
6. Enter a string A$ of any length. Print the length of A$ and the ASCII number of its first and
last characters.
7. Write a program where you input a name and then have the computer print the ASCII
number of the letter which appears most often in the name.
8. Let A$ = "2598." Have the computer apply VAL to those parts of A$ whose sum is 123.
9. Enter the words "QUEEN," "LENGTH" and "REMEMBER." Print each word with all E's
removed.
10. Use the computer or a hand calculator to find the binary equivalents of the decimal values
given below:
89, 74, 80, 107, 255, 129, 28, 39, 29, 24, 43
8-10
11. Use the computer or a hand calculator to find the decimal equivalents for the binary values
given below:
12. Input a string A$ which consists of the digits 0 to 9, inclusive, each to be used only once
(e.g., 1956472038). Use string functions to obtain from A$ two numbers N1 and N2, N1
being the number represented by the first three digits of A$ and N2 the number rep
resented by the last three digits. Print the sum of N1 and N2.
ABCDE
ABCDEF
ABCDEFG
ABCDEFGH
ABCDEFGHI
ABCDEFGHIJ
ABCDEFGH UK
ABCDEFGHIJKL
READY.
14. As a young boy Franklin Roosevelt signed his letters to his mother backwards:
TLEVESOOR NILKNARF. Write a program that accepts a person's name and prints it
backwards.
15. Using the ASCII chart given in the text, determine the output for the following program.
Check by running the program:
10 FDR A-l TO 4
20 READ A$
30 PRINT ASC(A$)
40 NEXT A
50 DATA "W", "H", "7", "625"
60 END
16. The output of the following program is Foxy Moxie's message to Jimmy Band. What is the
message? Check by running the program:
10 FOR W ■ 1 TO 6
20 READ A*,B*,C*
30 PRINT LEFT$<A$., 1) ;MID$<B$,2,2) ;RIGHT$(C«, 1)
40 NEXT W
50 END
8-11
60 REM DATA SECTION
70 DATA FDO,NOXP,LUY
S0 DATA SSSpHAYE,RRS
90 DATA HYF,OELR,EVP
100 DATA WER,LILO,VEL
110 DATA CIS.TOMHj.EIE
120 DATA SRS,WOai,SHN
17. Choose fifteen random integers from 65 to 90, inclusive, to serve as ASCII code numbers.
Convert these fifteen integers to the fifteen characters for which they stand and print the
results.
18. Write a program which produces a sentence containing twenty nonsense words. Each
word can contain from two to five letters. Use random numbers and the ASCII code to
produce the words.
RUN
ET IN RWCEB IDL
TLH QNDYU LWRIR AWMM
uvsr CNLGY SXNV FR
DO PGL XYKV TQSGR
LJSRL DX QRLNL QCOCU
READY.
19. Using random numbers and the ASCII code numbers from 32 to 126, inclusive, have the
computer generate a string of 100 characters, allowing repetitions. Tabulate how many
characters are letters, numbers or miscellaneous characters. Print the results.
20. Using string functions, write a program to play a word guessing game. Ask the player to
guess a secret word. Search through each guess to see if the guess contains any correct
letters. If any letter is correct, have the computer print the ones that are. If the entire word is
guessed, type "YOU GUESSED IT!!"
RUN
GUESS A WORD? HANGMAN
'&' IS IN THE WORD
11 A7 IS IN THE WORD
GUESS A WORD? DATAPHONE
^A1 IS IN THE WORD
"A" IS IN THE WORD
JE? IS IN THE WORD
GUESS A WORD? TERMINAL
'E> IS IN THE WORD
'R' IS IN THE WORD
?A! IS IN THE WORD
>L> IS IN THE WORD
GUESS A WORD? SCRABBLE
YOU GUESSED IT!!
READY.
8-12
21. You are a spy who will use the computer to produce a secret code.
(a) Input a short message and have the computer type back what appears to be nonsense
words. To produce the coded words, convert each letter of the original message into its
corresponding ASCII code number, add two to each number and convert to characters to
produce the message. Keep all spaces between the words in their original places and
understand that the letters Y and Z are to be converted to A and B.
NCYTGPEGXKNNG
UEJQQN
A - 1500 B - 999.9764
Explain in a clear, brief manner why the value of B is not exactly 1000, and why the value of
A is exactly 1500.
23. Create bizarre "sentences" by having the computer print the words in a real sentence in
reverse order. Your program should NOT reverse the order of the letters in each word.
READY.
8-13
25. Enter a positive integer N$ as it would be expressed in binary form. That is, enter a string of
ones and zeros. Have the computer print the equivalent of N$ as it is expressed in the
decimal system.
8-14
HLES
OPEN
CLOSE
PRINT#
INPUT#
STATUS
OPEN
CLOSE
PRINT#
INPUT#
STATUS
OPEN
CLOSE
PRINT#
INPUT#
STATUS
OPEN
CLOSE
PRINT#
INPUT#
STATUS
OPEN
CLOSE
PRINT#
INPUT#
STATUS
OPEN
CLOSE
PRINT#
So far we have discussed only two methods for saving data in the computer. Variables
could be assigned a constant value (e.g., A = 5) or the data could be placed in DATA state
ments that are read by the computer when the program is run. There are two drawbacks to
these methods. First, if it becomes necessary to update the data, program lines have to be
retyped, thus altering the program and increasing the chance for errors. Second, since the data
is an integral part of a program, it cannot be accessed by other programs. The solution to these
problems is to store the data in a file. Since files are separate from programs, they can be
updated without changing any part of a program. Also, a single data file can be accessed by
many programs, allowing more flexible use of the data. Files and programs should not be
confused. A program is a set of instructions that tell the computer what do do; a file is a set of
data used by a program.
The first part of this chapter will explain how to use data files stored on cassette tapes; the
second part will cover files stored on diskettes. Before proceeding to learn the use of files
stored on cassette tapes or diskettes, the programmer should read either Appendix B to
become familiar with the operation of the cassette unit or Appendix C to become familiar with
the disk drive.
Several conventions are used in this chapter. Writing to a file means transferring data from
the computer's memory to a file stored on a tape or diskette. Reading from a file means
transferring data from a file to the computer's memory. Whenever the general format for a new
command or statement is presented, part of the definition will be enclosed in angle brackets
(< ... >). The brackets are not part of the statement. They indicate the parts of the statement
that can change and require information to be supplied by the programmer. For example,
<variable> means that an appropriate variable such as D1 or R$ is needed.
Cassette Files
The computer stores files on tape sequentially, one data item after another. Therefore,
these files are best suited to situations in which the data will be recalled in the same order as it
was originally stored.
OPEN
The OPEN statement establishes a line of communication between a program and a file.
The OPEN statement must specify the name of the file, a file number, a device number and the
mode of access desired. A file name is used by the computer to identify each file and program
stored on a tape. Therefore, each file and program on a tape must have a different name. The
file number must be an integer from 1 to 255, which is used throughout a program to identify a
specific file. The device number specifies the device the file is to be stored on. For the cassette
unit, the device number is 1. The three modes of access are:
0: The computer will read data from a previously created file.
1: The computer will write data to a new file.
2: The computer will write data to a new file and place an end of tape
marker after the end of the file.
Mode 2 is useful when the file is to be placed near the end of the tape because ir searching
for a file or program that is not on the tape the computer will end its search and print the
9-1
message 7DEVICE NOT PRESENT ERROR only if an end of tape marker is found. Otherwise,
the computer will continue its search even after the tape has run out.
The general format for the OPEN statement is:
will instruct the computer to prepare to write to a new file called PAYROLL FILE (using file
number 35) on the cassette (device 1). Since the mode is specified as 1, the computer will not
place an end of tape marker after the end of the file. When the computer is instructed to use
mode 1 or mode 2 to open a file, it will print the message PRESS RECORD & PLAY ON TAPE
and then wait for the buttons to be pressed before opening the file. When the computer is
instructed to open a file using mode 0, it will print the message PRESS PLAY ON TAPE and
then wait for the button to be pressed before attempting to open the file.
CLOSE
Any file previously opened must be closed. This procedure is necessary in order to break
the line of communication between a program in the computer's memory and a file. The format
for a CLOSE statement is:
CLOSE <file#>
For example,
100 CLOSE 35
will close the file previously opened with the file number 35.
Closing a file ensures that all of its information will be properly retained. A tape with open
files on it should not be removed from the cassette unit, nor should the tape be advanced or
rewound before the files have been closed. Removing a tape prematurely may result in the loss
of data.
PRINT#
After the OPEN statement establishes a line of communication between a program and a
file, the PRINT# command is used to place data in the file, its form is:
Information contained in the variables in the PRINT# statement will be placed in the file
specified by the file number. If the contents of more than one variable are to be placed in a file
9-2
by a single PRINT# statement, commas within quotation marks must be placed between each
variable. The commas are stored in the file and act as markers so that the computer can
distinguish each item of data when reading the file. For example,
PRINT#5. A$;",":C:'\";QS
transfers the contents of a string (A$), floating point variable (C) and string (Q$) to the file,
separating each with a comma.
Program 9.1
This program, named CREATE, opens a file on the tape named WORK FILE. In it are
stored the names of four employees, their hourly wages and the number of hours they have
worked. Note the structure of line 60, in which the name (N$), wage (W) and hours worked (H)
for each employee are written to the file:
RUN
PRESS RECORD S< PLAY ON TAPE
OK
NAME? GWEN WALDEN
WAGE? 4.45
HOURS WORKED? 39
READY.
9-3
Review
1. Write a program named CALENDAR that will create a file named MONTH FILE and store
the names of the months of the year in it.
INPUT#
The INPUT# statement is used to read information from a file and transfer it to the
computer's memory. Its format is similar to that of the PRINT# statement:
INPUT#<file#>,<variable>.<variable> ...
The commas between the variable names in the !NPUT# statement are not enclosed in
quotation marks. The order in which the variables are listed in the INPUT# statement must be
the same as the order used originally in the PRINT# statement that created the file. For
example, a program that reads the data from WORK FILE created by Program 9.1 would have
to input the data in the order N$, W, H:
INPUT#2, NS. W. H
After a file has been closed, the same file number need not be used to access it at a
later time.
Program 9.2
This program, named HOURS, will open the file WORK FILE created by Program 9.1 and
print the names and hours worked for the four employees:
READY.
9-4
Line 10 specifies the access mode as 0 because the program will input data from the file to the
computer.
The variable W is read in the input line but is not printed. The computer has an internal
pointer that indicates the next item of information that is to be transferred from the file by the
INPUT# statement. When the INPUT# statement is executed, the pointer is moved across the
data line as each item is read. To ensure that the data in the file is read in the correct sequence,
it is important that all of the necessary variables be included in the INPUT# statement, even if
some of them are not used by the program.
Review
2. Write a program named RETRIEVE that will retrieve the name of every other month of the
year from MONTH FILE created in Review problem 1.
RUN
READY.
Commodore Basic does not have provisions for adding or removing data in already exist
ing files. When an OPEN command is executed with either mode 1 or 2 specified, the computer
opens a new file and prepares to write to it starting at the beginning of the file. Any old file with
the same name is ignored. To add information to an old file, the programmer must first read the
entire file into memory. A new file must then be opened and the old and new data written to the
new file. To delete data from a file, the programmer must read the entire file into memory and
then write the data to be retained into a new file.
Program 9.3
This program, named ADD, will update WORK FILE, created by Program 9.1, so that it
includes information on two new employees just hired:
9-5
1 REM N*?N*() = EMPLOYEE NAME
2 REM W,W() = WAGE
3 REM H,H() ■ HOURS WORKED
4 REM
5 REM
100 REM READ OLD FILE
110 REM
120 DIM N*<4>,W(4>,H<4)
130 OPEN 1,1,0,"WORK FILE"
140 FOR X=l TO 4
150 INPUT#1,N*(X>,W<X),H<X)
160 NEXT X
170 CLOSE 1
180 REM
200 REM DISPLAY PROMPT S< WAIT
210 REM
220 PRINT "REWIND TAPE TO BEGINNING";
230 PRINT " OF FILE"
240 PRINT "STRIKE ANY KEY WHEN READY"
250 PRINT
260 GET G* : IF G*="" THEN 260
270 REM
300 REM MAKE NEW FILE
310 REM
320 OPEN 1,1,1,"WORK FILE"
330 FOR X«l TO 4
340 print#i,n*(X);",";W<X);",";h(X)
350 NEXT X
360 FOR X«l TO 2
370 INPUT "NAME";N*
380 INPUT "WAGE"|iW
390 INPUT "HOURS WORKED"5H
400 frint#i,n*;",";W;",";H
410 PRINT
420 NEXT X
430 CLOSE 1
440 END
RUN
READY.
9-6
Two aspects of Program 9.3 should be noted. First, the contents of each line of data from
the old file are saved in memory by placing them in appropriately dimensioned subscripted
variables. Second, a GET statement is used with an IF. . .THEN statement at line 260 to cause
the computer to wait until the user strikes a key. This allows the user as much time as needed to
rewind the tape. The tape is rewound so that the new file can be written over the old file thus
saving space on the tape.
After the FOR. .. NEXT loop in Program 9.2 is changed, the program can be re-run to
show that the new data is now in WORK FILE:
RUN
READY.
Program 9.4
When an employee retires, this program, named REMOVE, will remove the employee's
name from WORK FILE. All of the data is read sequentially from WORK FILE and the data that
is to be kept is written to a new WORK FILE:
9-7
280 GET G$ : IF G*="" THEN 280
290 REM
300 REM
400 REM MAKE NEW FILE
410 REM
420 OPEN 1,1,1,"WORK FILE"
430 FOR X"«l TO 6
440 IF N*(X)=R* THEN 460
450 PRINT#1SN*(X) ; 'V;W<X> ; ", "5H<X>
460 NEXT X
470 CLOSE 1
480 PRINT "THE INFORMATION ON ";R$
490 PRINT "HAS BEEN REMOVED"
500 END
RUN
READY.
Programs 9.3 and 9.4 work well in this limited example, but the technique they use is not
always practical. Both programs use a FOR... NEXT loop to prevent the program from at
tempting to read past the end of the file. However, this method could only be used because the
length of WORK FILE was known in both cases. To read a file of unknown length, the pro
grammer must employ a loop containing a GOTO statement to ensure that the entire file is
read. The file will then be read sequentially until the computer comes to the file's end. When the
computer tries to read past the end of the file, however, an error will occur. This may result in
files left open and lost data. To prevent this error, the system variable STATUS is used.
STATUS
The computer sets the value of the variable STATUS every time it attempts to read from or
write to a file. When the computer has read the last item of data from a file, it automatically sets
the value of STATUS:
50INPUT#3,R$
60 IF (STATUS AND 64) - 64 THEN CLOSE 3 : END
In the program fragment above, the computer checks the value of STATUS at line 60. If at line
50 the input statement has read the last item of data in the file, the value of STATUS will be set
so that the statement (STATUS AND 64) = 64 will be true. In this event the IF... THEN
statement at line 60 will cause the computer to close the file and stop execution of the program.
9-8
Program 9.5
This program, named REMOVE2, is a revision of Program 9.4, which allows WORK FILE
to have up to one hundred employees in it:
190 INPUT#1,N*(OL),W<OL),H(OL)
200 IF N*(OL)=R* THEN T=l
210 GOTO 170
220 CLOSE 1
230 IF T=l THEN 300
240 PRINT "THERE IS NO ";R*(" ON"
250 PRINT "THE PAYROLL"
260 GOTO 500
270 REM
280 REM
300 REM DISPLAY PROMPT AND WAIT
310 REM
320 PRINT "REWIND TAPE TO BEGINNING")
330 PRINT " OF FILE"
340 PRINT
350 GET G* : IF G*«"" THEN 350
360 REM
370 REM
400 REM MAKE NEW FILE
410 REM
420 OPEN 1,1,1,"WORK FILE"
430 FOR X=l TO OL
440 IF N*(X)=R* THEN 460
450 PRINT#1,N*(X);","JW(X);",";H(X)
460 NEXT X
470 CLOSE 1
480 PRINT "THE INFORMATION ON ";R»
490 PRINT "HAS BEEN REMOVED"
500 END
9-9
RUN
WHO HAS RETIRED? JEANNETTE MCDONALD
READY.
Program 9.5 demonstrates two major improvements over Program 9.4. First, the program
informs the user if a name has been entered that is not in the file, using the variable T as an
indicator. If the name is in the file, T becomes 1; if not, T remains 0. Second, the STATUS
variable and a GOTO loop are used to read the file. This technique is recommended for reading
most files. The programmer must dimension the arrays used to a sufficient size to ensure that
they hold the entire file, keeping in mind that the amount of memory available in the computer
places a restriction on the size of files it can hold. If the size of the file exceeds the amount of
memory available, it will be necessary to break the file down into several smaller files and work
with each individually.
Demonstration Programs
The following programs illustrate applications for the material covered in this part of the
chapter. They consist of a series of examples concerning the record keeping process of a
sporting goods manufacturer.
Program 9.6
This program, named ACME, will produce a file named SALES FILE that contains the
sales record of all salespeople working for the Acme Sporting Goods Company. Each sales
person sells bats, balls and helmets:
1 REM N$ = NAME OF SALESPERSON
2 REM Bl = BATS SOLD
3 REM B2 = BALLS SOLD
4 REM H = HELMETS SOLD
5 REM
100 OPEN 1,1,1,"SALES FILE"
120 PRINT "ENTER STOP FOR THE NAME";
130 PRINT " WHEN FINISHED"
140 PRINT
150 INPUT "SALESPERSON";N*
160 IF N$="STOP" THEN 220
170 INPUT "BATS SOLD"«B1
180 INPUT "BALLS S0LD";B2
190 INPUT "HELMETS
SOLD";H
200 print#i,n$;",";bi;",";B2;",";H
210 GOTO 140
220 CLOSE 1
230 PRINT "THE INFORMATION IS IN";
240 PRINT " THE FILE"
250 END
9-10
RUN
PRESS RECORD 2< PLAY ON TAPE
OK
ENTER STOP FOR THE NAME WHEN FINISHED
SALESPERSON? STOP
THE INFORMATION IS IN THE FILE
READY.
Program 9.7
This program, named ACME2, will update the sales records for an individual salesperson:
RUN
READY.
9-12
Program 9.8
This program, named ACME3, will write a personalized letter of congratulations to all
salespersons who have sold 75 units or more:
RUN
YOUR BOSS
READY.
9-13
Diskette Files
The programs that access diskette files are similar to the programs that access cassette
files. Diskette files are stored sequentially, as are cassette files. The next part of this chapter will
explain the differences between the use of diskette files and cassette files. It is assumed that
the programmer has already read the section on cassette files.
OPEN
The only statement relating to files that has a different syntax for cassette and diskette files
is the OPEN statement. The general format for the OPEN statement for diskette files is:
The file number must be an integer from 1 to 255, which is used throughout a program to
identify the file. The device number specifies the device on which the file is to be stort-J. For
single drive systems this is usually 8. (The examples in this book are written for single drive
systems.) The channel number must be an integer from 2 to 14, which is used to specify a
channel of communication between the computer and the disk drive. To reduce confusion, a file
is usually opened with the same file number and channel number. The file name, the S, and the
mode of access must be enclosed within a single set of quotation marks.
The three modes of access are:
W: WRITE. The computer will transfer data from memory to the file.
R: READ. The computer will transfer data from the file to memory.
A: APPEND. The computer will transfer data from memory and append it
to the file. Previously stored data will be added to, not lost.
For example,
OPEN 7, 8, 7, "'ADDRESSES,S,W"
will instruct the computer to prepare to write to a file named ADDRESSES on the diskette
(device #8), using the file and channel numbers 7.
Program 9.1 can be changed to store WORK FILE on a diskette simply by changing
line 10 to
To examine the contents of the diskette version of WORK FILE, the programmer changes
line 10 of Program 9.2 to
The procedures for updating diskette files are different from the procedures for updating
cassette files. Specifying the (A)ppend mode allows the user to add new information directly to
the end of an existing file on a diskette.
9-14
Program 9.9
This program, named ADD, is a modified version of Program 9.3. It will add information on
two new employees to the diskette version of WORK FILE:
RUN
NAME? ROBERT LYNCH
WAGE? 4.60
HOURS WORKED? 44.25
READY.
There is no single command that will remove or alter outdated information in a diskette file.
To change such a file, the programmer must transfer information to be kept to a new file along
with the new or corrected information. After the transfer, the old file can be deleted and the new
file given an appropriate name.
Program 9.10
This program, named RETIRE, will remove from the diskette version of WORK FILE the
name of an employee who has retired. It should be examined very closely and compared to
program to Program 9.5:
9-15
40 IF (S AND 64)=64 THEN
50 INPUT#2,N*?W,H
60 5=STATUS
70 IF N*=R* THEN 40
80 FRINT#3,N*j ","5W;",";H
90 GOTO 40
100 CLOSE 2 : CLOSE 3
110 OPEN 15,8,15
120 PRINTW15,"S:WORK FILE"
130 PRINT#15,"R:WORK FILE=TEMPORARY"
140 CLOSE 15
150 END
RUN
WHO HAS RETIRED? ERMA MCCONNELL
READY.
All of the data is read sequentially from WORK FILE, and the information to be retained is
placed in the file TEMPORARY. After the program has finished building the new file
TEMPORARY, the old WORK FILE is deleted and TEMPORARY is renamed as WORK FILE
(lines 110-140). The value of STATUS is saved in S immediately after the INPUT# statement is
executed because the computer will set the value of STATUS to 0 after executing the PRINT#
statement at line 80. If the test at the top of the loop (line 40) were to check the value of
STATUS instead of S, the test would always fail and the computer would repeat the loop
indefinitely.
Bubble Sort
Sometimes it is desirable to sort data that has been originally placed in a file in random
order. A list of names might be sorted into alphabetical order, or a list of numbers might be
sorted into ascending or descending order. One of the most fundamental and easiest sorting
techniques is known as a bubble sort. In a bubble sort the computer starts at the bottom of the
list, then proceeds sequentially to the top, comparing each item in the list with the one above it.
If the two elements are not in the proper order, they are interchanged. In this way the name that
comes first alphabetically in the list is "bubbled" to the top of the list. For example, given the
initial list
Lester
Don
Bruce
Rob
Eli
the computer would start by comparing the names Rob and Eli. Because Eli comes alphabeti
cally before Rob, the computer would switch the names and the list would become:
Lester
Don
Bruce
Eli
Rob
9-16
Next, Bruce and Eli are compared. Because Bruce comes before Eli, no change is made. Then
Don and Bruce are compared and interchanged, so the list becomes:
Lester
Bruce
Don
Eli
Rob
Bruce and Lester are then compared and interchanged. The order of the names in the list now
becomes:
Bruce
Lester
Don
Eli
Rob
Bruce, the name that comes first alphabetically in the list, is now at the top of the list. Now the
computer starts over at the bottom of the list, and the name that comes next alphabetically is
"bubbled" up to its proper position. After the procedure has been repeated enough times, the
order of the list becomes:
Bruce
Don
Eli
Lester
Rob
Program 9.11
This program uses a bubble sort to sort a list of first names into alphabetical order:
9-17
280 REM
290 REM
300 REM NAME OUTPUT SECTION
310 REM
320 PRINT
330 FOR X= l TO N
340 PRINT N*(X)
350 NEXT X
360 END
RUN
HOW MANY NAMES TO SORT? 5
ENTER NAMES
? ELI
? DON
? ROB
? LESTER
? BRUCE
BRUCE
DON
ELI
LESTER
ROB
READY.
The loop between lines 230 and 260 causes the computer to scan the list from the bottom (the
Nth item) to the top. Each successive pair of items is compared at line 240, and they are
interchanged at line 250 if they are out of order. The loop between lines 220 and 270 causes the
computer to scan the list N-1 times. For a bubble sort to work properly, a list with N items must
be scanned N-1 times. In addition this loop also controls how far the computer scans up the list
on each pass. On the first pass all the items in the list are checked. On the second pass the item
that comes first alphabetically is already at the top of the list, so the list is only scanned up to the
second item. This upper bound is pushed down on each pass through the list until it is at the
second to last item on the list (N-1), after which the sort is complete. By changing the variables
used, the programmer may use this technique to sort a list of numbers also. To sort a list of
names into reverse alphabetical order or a list of numbers into descending order, all that need
be done is to change the direction of the inequality in the comparison. The integration of this
sorting technique with programs that manipulate files is left as an exercise for the reader.
9-18
EHEHCJSES
The first five problems can be answered using either cassette or diskette files. The next
five should be answered using diskette files.
1. Store 50 random numbers between 0 and 20 in a file. Use a second program to retrieve the
numbers, add them and print the sum.
2. Store in a file the names and prices of five different desserts served at MADGE'S DINER.
With a second program add two additional desserts. Have a third program retrieve and
print the information.
3. (a) Establish a file name SEQ FILE which contains the members of the following sequence:
1001, 1002, 1003, ...1128.
(b) Write a program to retrieve any member of the sequence from SEQ FILE and print it
when its place in the sequence (i.e. third number, eighth number, etc.) is entered.
4. Store ten different first names of friends in a file. A second program is to print all the names
in the file which begin with the letters D, E, F, G and H or a message if none are found.
5. (a) Create a payroll file called PAY FILE to store each of ten person's names (last name
first), his or her hourly pay rate, the number of dependents, and deductions for medical and
life insurance for each week. Supply appropriate data.
(b) Use PAY FILE to prepare the payroll data sheet (supply the number of hours (H) each
person worked during the week). The sheet should list the name, hours worked, gross pay,
three deductions and net pay. Assume a tax rate of 25%, with 2% being subtracted from
this rate for each dependent.
RUN
MENACE DENNIS -
HOURS WORKED: 40
GROSS PAY: % 40
tax: % 10
MEDICAL INSURANCE: $ 1
LIFE INSURANCE: $ 1
net: * 20
9-19
6. (a) Write a program that will create the file FRAT FILE, which will contain the names,
fraternities and ages of thirty college students.
(b) Write a program that will access FRAT FILE, and create the file SIGMA FILE, which
contains the names and ages of only students who live in Sigma Chi.
(c) Write a program that accesses FRAT FILE and randomly selects sixteen students for
seats in a classroom of four rows, four seats to a row. Have the computer print the seating
plan for the class, placing each student's name at the correct seat location.
7. (a) Two persons, NIT and WIT, measured the Fahrenheit temperature (F) outside on Feb.
12 at various times (T) during a ten hour period. Their results are recorded here. Set up two
files, one for each person's data, naming each file after that person.
NIT WIT
T F I F
0.0 18.1 1.0 20.9
2.1 24.0 1.9 23.3
3.8 27.2 3.5 26.1
6.0 29.3 6.0 28.8
8.0 26.6 8.2 26.2
9.0 16.1 10.0 16.0
(b) Write a program that will merge the two files into one file named MERGE. The times
should be sequentially in order. However, when a value of (T) occurs both in NIT and WIT,
the average of the two values of (F) should be placed in MERGE.
(c) Retrieve and print the contents of MERGE.
8. (a) You have just been hired to help produce a new dictionary. Write a program to create
the file WORD FILE. The file is to contain twenty-five words in random order.
(b) Write a program to sort the contents of the file WORD FILE into alphabetical order. Hint:
To sort the contents of the file, the program should:
(1) read the contents of WORD FILE
(2) sort the list of words in memory
(3) write the sorted list to the file TEMP FILE
(4) remove WORD FILE from the diskette
(5) rename TEMP FILE as WORD FILE
The program should also print the sorted list on the display.
9. (a) Write a program to create the file NAME & AGE FILE. The file is to contain the first
names and ages of fifteen people.
(b) Write a program to sort the contents of NAME & AGE FILE alphabetically. For example,
given the list:
Rob 20
Don 19
Lester 21
Don 19
Lester 21
Rob 20
9-20
Note the ages have been switched also.
(c) Write a program to sort the contents of NAME & AGE FILE by age. For example, given
the above initial list, the computer should change it to:
Don 19
Rob 20
Lester 21
10. (a) Create a file named NUMBER FILE that contains a list of telephone numbers. The area
codes are not to be included.
(b) Write a program to sort the contents of NUMBER Fl LE by exchange only. For example,
given the list:
676-2004
609-4444
676-5112
867-5309
932-6840
867-1441
the computer should change it to:
609-4444
676-2004
676-5112
867-5309
867-1441
932-6804
11. The program fragment given below should be used as the data lines for the answer to this
question. The names <N$()) and associated telephone numbers (T$()) should be sorted
into alphabetical order by last name. For example, the first three names of the sorted list
should be:
9-21
flPPENDJCES
SAVE
VERIFY
LOAD
SAVE
VERIFY
LOAD
SAVE
VERIFY
LOAD
SAVE
VERIFY
LOAD
SAVE
VERIFY
LOAD
SAVE
VERIFY
LOAD
SAVE
VERIFY
LOAD
SAVE
VERIFY
LOAD
SAVE
VERIFY
LOAD
SAVE
APPENDIX A
EDITING
The Commodore-64 and VIC-20 computers have an editing feature which helps the pro
grammer correct a program currently in the computer's memory. The programmer can best
learn the use of this feature by spending time becoming familiar with it. An outline of the editing
controls is presented here:
KEY FUNCTION
CLR Moves the cursor to the upper left hand corner of the screen.
HOME
CLR
Clears the screen and moves the cursor to the upper left
SHIFT
HOME hand corner.
-*-
A-1
APPENDIX B
CASSETTE OPERATION
Program and File Names
Every program and file stored on a tape is identified by a unique name. The name may be
from one to sixteen characters long. Any type of character, either standard or graphic, may be
used in the name. To help distinguish between programs and files, it is useful to incorporate the
word FILE in file names. For example, a program named PAYROLL might access a file named
PAYROLL FILE. The following examples are valid program and file names:
MAIL
CODE FILE
NAMES & NUMBERS
SAVE
The SAVE command is used to store a program on a tape. Its form is:
SAVE"TAXES"
The computer will print the message PRESS RECORD & PLAY ON TAPE and then wait
for the buttons to be pressed before saving the program currently in memory on tape. To
prevent the erasure of a previously stored program, position the tape at a blank section.
The user should keep a written record of the programs and files stored on a tape, along
with their locations on the tape so that the tape may be correctly positioned when the user
wishes to recall a program or file.
VERIFY
The VERIFY command is used to check a program in memory against a program that has
been saved on tape. Its form is:
VERIFY 'TAXES'1
A-2
When the computer has found TAXES, it will print the message VERIFYING and proceed to
compare the program on tape with the program in memory. If they are identical, the computer
will print the message OK. If the message 7VERIFY ERROR is printed, the program has not
been saved on the tape correctly. In this event, the programmer should attempt to save the
program again.
LOAD
Programs previously saved on a tape may be recalled using the LOAD command. Its form
is:
To recall a program from a tape and transfer it into the computer's memory, make sure the
tape is at a point preceeding the beginning of the program. Type LOAD followed by the program
name. For example:
LOAD "TAXES"
The computer will print the message PRESS PLAY ON TAPE and wait for the button to be
pressed before attempting to load the program.
Programs and files are removed from a tape by recording over them. The user should
guard against doing this accidentally. The computer will save a program or file at whatever
position the tape happens to be located when the appropriate instructions are given.
A-3
APPENDIX C
DISKETTE OPERATION
Every program and file on a disk is identified by a unique name. The name may be from
one to sixteen characters long, made up of any type of character, either standard or graphic.
The only restriction is that @: cannot be used as the first two characters of the name. To help
distinguish between programs and files, it is useful to incorporate the word FILE in file names.
For example, a program named PAYROLL might access the file PAYROLL FILE. The following
examples are valid program and file names:
ADDRESS FILE
COMMODORE
NAMES & NUMBERS
Formatting Diskettes
The following procedure must be used, as given, to initialize or "format" a new diskette
before the computer can use it for the first time:
OPEN 15. 8. 15
PRINT#15, "N: <name>, <id>"
CLOSE 15
The name becomes part of the directory as the name of the entire diskette. The name
appears only when the directory of the diskette is displayed. The ID code, which may be any
two characters, is used by the computer to identify the disk.
OPEN 15. 8. 15
PRINT#I5. "N:PAYROLL DISK.PD"
CLOSE 15
will instruct the computer to format the disk in the drive, giving it the name PAYROLL DISK and
the ID code PD. The disk will then be ready to be used.
SAVE
The SAVE command is used to store a program on a diskette. Its form is:
A-4
The program name must be enclosed in quotation marks. The device number specifies
which disk drive the program is to be stored on. For single drive systems this is 8. The examples
in this appendix will assume single drive systems.
SAVE "TAXES".8
will save the program currently in memory on the diskette and give it the name TAXES.
VERIFY
The VERIFY command is used to check a program in memory against a program that has
been saved on a diskette. Its form is:
To verify that the program TAXES has been saved properly type:
VERIFY "TAXES".8
When the computer has found TAXES, it will print the message VERIFYING and proceed
to compare the program on the diskette with the program in memory. If they are identical, the
computer will print the message OK. If the message 7VERIFY ERROR is printed, the program
has not been saved correctly. In this event, the programmer should attempt to save the pro
gram again.
LOAD
Programs previously saved on a diskette may be recalled using the LOAD command. Its
format is:
For example,
LOAD "TAXES",8
will load the program TAXES into memory from the diskette. Any program previously in memory
will be erased.
It is possible to change the name of files and programs that have been stored on a diskette
with the following procedure:
A-5
OPEN 15, 8. 15
PRINT#15, "R:<new name> = <old name>
CLOSE 15
For example:
OPEN 15. 8, 15
PRINT#15, l'R:IRS=TAXES"'
CLOSE 15
will give the program TAXES on the diskette the name IRS.
OPEN 15, 8. 15
PRINT#15, ■'C:<new> = <original>"
CLOSE 15
For example:
OPEN 15. 8. 15
PRINT#15. "C:IRS BACKUP=IRS"
CLOSE 15
will instruct the computer to make an exact copy of IRS and place it on the same diskette with
the name IRS BACKUP.
A similar procedure can be used to combine up to four files on the disk:
OPEN 15, 8, 15
PRINT#15. "CMASTER FILE=NAMES, ADDRESSES. NUMBERS'"
CLOSE 15
will place the contents of NAMES, ADDRESSES and NUMBERS in that order, in the new file
MASTER FILE. The files NAMES, ADDRESSES and NUMBERS will not be affected.
A-6
Diskette Directories
LOAD "$", 8
and then
LIST
Note that this procedure will erase any program currently in memory:
LOAD M*'\S
SEARCHING FOR $
LOADING
READY.
LIST
0 "TRANSFER 11 TG 2A
1 "C3P23" PRG
1 "C5F2511 PRG
1 "C3P27" PRG
1 "C3P33" PRG
660 BLOCKS FREE.
READY.
Unwanted programs and files are removed from a diskette with the following procedure:
OPEN 15, 8. 15
PRINT#15, "S:<program or file name>"
CLOSE 15
For example,
OPEN 15, 8, 15
PR[NT#15. "S:PAYROLL FILE"
CLOSE 15
will instruct the computer to remove the file PAYROLL FILE from the diskette.
A-7
WEDGE
The demonstration disk provided by Commodore with the disk drive contains a program
that modifies the operating system of the computer. VIC-20 WEDGE will modify the VIC-20,
and C-64 WEDGE will modify the COMMODORE-64. After running the appropriate program,
the programmer can obtain a catalogue of a diskette by typing $. This will not cause any
program currently in memory to be erased. In addition, a program can be loaded into memory
by typing / followed by the program name.
0 "TRANSFER " TG 2A
1 "C3P23" PRG
1 "C3F25" PRG
1 "C3F27" PRG
1 "C3P33" PRG
660 BLOCKS FREE.
READY.
A-8
REWEKJ flNSKJERS
CHAPTER ONE
1. 10 X - 5
20 Y = 5*X + 7
30 PRINT Y
2. 10 A$ = "HARRY"
20 B$ - "SHERRY"
30 PRINT "HELLO, " ; A$
40 PRINT B$;" IS LOOKING FOR YOU."
3. .1.0 READ X
20 Y ■ 3*X + 5
30 PRINT YJ
40 GOTO 10
50 DATA 3,5,12,17,8
R-1
6. 10 INPUT "WHAT IS YOUR NAME"5N*
20 INPUT "WHAT IS YOUR FRIEND'S NAME";F*
30 PRINT F*; "IS A FRIEND OF "| N*
40 PRINT
50 GOTO 10
CHAPTER TWO
5. 10 FOR I = 1 TO 25
20 PRINT I;
30 NEXT I
6. 10 FOR S = 20 TO 10 STEP -2
20 PRINT S;
30 NEXT S
40 PRINT
CHAPTER THREE
R-2
2. 1 REM W = NUMBER OF WRONG GUESSES
10 PRINT "I'M THINKING OF A RANDOM NUMBER FROM 1 TO 50."
20 R = INT(50 * RND<0) + 1)
30 FOR W - 1 TO 5
40 INPUT "WHAT IS YOUR GUESS";G
50 IF B»R THEN PRINT "CORRECT!!": END
60 IF G>R THEN PRINT "TOO HIGH)"
70 IF G<R THEN PRINT "TOO LOW!"
80 NEXT W
90 PRINT "YDU^VE HAD 5 GUESSES NOW."
100 PRINT "THE NUMBER WAS";R
3. 10 FOR I ■ I TO 50
20 N = INT(10 * RND(0))
30 IF N<5 THEN L = L + 1
40 NEXT I
50 PRINT "THERE WERE";L;"NUMBERS BETWEEN 0 AND 4."
60 PRINT "THERE WERE" ;50-L; "NUMBERS BETWEEN 5 AND 9."
CHAPTER FOUR
1. 10 FOR X - 20 TO 24
20 PRINT "OUTER LOOP:"; X
30 FOR Y = 1 TO 3
40 PRINT "INNER:"JY,
50 NEXT Y
60 PRINT
70 NEXT X
2. 10 FOR I = 1 TO 3
20 INPUT N(I)
30 NEXT I
40 FOR I - 3 TO 1 STEP -1
50 PRINT N(I>
60 NEXT I
R-3
4. 10 REM READ 6 WORDS FROM THE KEYBOARD
20 FOR X = 1 TO 6
30 INPUT W$(X)
40 NEXT X
50 REM PICK FOR DIFFERENT WORDS AND PRINT THEM AS A SENTENCE
60 CC1) - I NT(5 * RND(0) + 1) : REM FIRST RANDOM NUMBER
70 PRINT W*(C(1));M "g : REM ALWAYS SHOW FIRST WORD
80 FOR P = 2 TO 4
90 C(P) ■ INT(5 * RND(0) + 1)
100 REM NOW CHECK FOR DUPLICATE RANDOM NUMBERS
110 FOR K = 1 TO P-l
120 IF C<K)«C<P) THEN 90 : REM PICK ANOTHER IF USED
130 NEXT K
140 PRINT W*(C(P)>; " "5
150 NEXT P
160 PRINT REM PERIOD = END OF SENTENCE
6. 5 DIM X*(5,3)
10 FOR I = 1 TO 5
20 FOR J = 1 TO 3
30 READ X*(I,J)
40 NEXT J
50 NEXT I
60 REM OUTPUT X*<)„ MAKING THE ROWS BECOME COLUMNS
70 FOR I = 1 TO 3
80 FOR J = 1 TO 5
90 PRINT X$(J,I);11 ";
100 NEXT J
110 PRINT
120 NEXT I
130 DATA A5B,C,D,E,F,G,H,I,J,K,L,M,N,Q
R-4
CHAPTER FIVE
1. 10 INPUT "NAME";N$
20 PRINT N$
30 IF Nt « "DONALD" THEN GDSUB 100
40 GOTO 10
50 REM
60 REM
100 REM THIS IS THE CODE TO UNDERLINE
110 FOR I « 1 TO 6
120 PRINT "-";
130 NEXT I
140 PRINT
150 RETURN
2. 10 FOR D - 1 TO 5
20 C - INTU3*RND(0> + 1)
30 S = INT(4*RND<0)+1>
40 PRINT "CARD"3DS"IS THE ";C;"OF ";
50 ON S GOTG 60,70,80,90
60 PRINT "CLUBS": GOTO 100
70 PRINT "DIAMONDS": GOTO 100
80 PRINT "HEARTS": GOTO 100
90 PRINT "SPADES"
100 NEXT D
4b. The product in line 30 is always positive. The best way to correct this error in logic
would be to eliminate line 40 and replace it with:
R-5
CHAPTER SIX
1. ±O INPUT N
2O FOR I = A TO N
25 PRINT
38 PRINT
-40 PRINT "I 11"
5O PRINT "I I"
60 NEXT I
READY.
3. 10 INPUT A,B
20 POKE 33281,A
30 POKE 53280,B
40 GOTO 10
VIC-20:
10 INPUT A,B
20 POKE 36879,A*16+8+B
30 GOTO 10
4. 10 INPUT A,B,C
20 POKE 53281,A
30 POKE 53280,8
40 POKE 53272,21 : IF Ol THEN POKE 53272,23
50 GOTO 10
VIC-20:
10 INPUT A,B,C
20 POKE 36879,A*16+8+B
30 POKE 36869,240 I IF C=l THEN POKE 36869,242
40 GOTO 10
5. 5 PRINT "Lj"1 : D = 3
10 FOR I = 0 TO 10
20 READ C(I)
30 NEXT I
40 Jl - 15-(PEEK(56321) AND 15)
50 IF J1«D THEN 40
55 POKE C(D),32 : POKE C(J1)5S1 : POKE 54272+CCJ1),0
60 D « Jl
70 GOTO 40
80 REM
100 DATA 1523;, 1043,2003,0, 1504, 1024, 1 784,0, 1543, 1063,2023
6. 5 PRINT "t/"
10 POKE 37139,0 : D=3
20 FOR I = 0 TO 10
30 READ C(I)
40 NEXT I (Continued on next page)
R-6
50 POKE 37154,127
60 J ■ 15-(CREEK(37137) AND 28)/4 + (PEEKC37152) AND 128)/16)
70 POKE 37154,255
80 IF J=D THEN 50
85 POKE C(D),32
90 POKE C(J),81
100 POKE 30720+C(J),0
110 D=J
120 GOTO 50
130 REM
140 DATA 7932,7690,8174,0,7922,7680,8164,0,7943,7701, 8185
7. 10 POKE 54296, 15
20 A-12 : D=5 : REM ATTACK AND DECAY RATES
30 POKE 54277,A*16+D
40 S«8 : R-2 : REM SUSTAIN AND RELEASE VALUES
50 POKE 54278,S*16+R
60 O1273 : REM Dtt IN 3RD OCTAVE
70 FOR I - 1 TO 2
80 POKE 54272, C--INT <C/256) *256
90 POKE 54273,INT(C/256)
100 POKE 54276,33
110 FOR D = 1 TO 500 : NEXT D : REM DELAY TO HEAR SOUND
120 POKE 54276,(PEEK(54276) AND 254)
130 C ■ 28871 : REM A IN 7TH OCTAVE
140 NEXT I
8. 10 POKE 36878, 15
20 POKE 36876,167
30 FOR D - 1 TO 500 : NEXT D
40 POKE 36876,238
50 FOR D = 1 TO 500 : NEXT D
60 POKE 36878,0
CHAPTER SEVEN
■0
2. 10 INPUT "FIRST COORDINATE (XI,Yl>";XI,Yl
20 INPUT "SECOND COORDINATE (X2,Y2)";X2,Y2
30 D = SQR( (Xl-X2)-"-2 + (Yl-Y2)'2)
40 PRINT "DISTANCE IS";D
R-7
CHAPTER EIGHT
CHAPTER NINE
R-8
ODD EXEfiCJSE flNSKIERS
CHAPTER ONE
1. 10 PRINT "A"
20 PRINT " B"
30 PRINT " C"
40 PRINT "ABCD"
3. RUN
THE VALUE OF B
19
READY.
5. 10 READ A,B
20 PRINT "THE SUM IS"; A+B
30 GOTO 10
40 DATA 12,8,9,5
9. 10 INPUT X,Y
20 PRINT "X =";X,"Y ="jY,"X*Y =";X*Y
30 GOTO 10
11. RUN
300 510
-3 .51
READY.
READY.
E-1
15. RUN
ABCDXYZ
ABCD 7
7 XYZ
-4 XYZ
READY.
E-2
33. 10 INPUT "MONTH, DAY, AND YEAR OF BIRTH";Ml,Dl,Yl
20 D9 = Yl*365 + Ml*30 + Dl
30 INPUT "TODAY'S MONTH, DAY, AND YEAR";M2,D2,Y2
40 D8 ■ Y2*365 + M2*30 + D2
50 S = 8*<D8-D9)
60 PRINT "YOU HAVE SLEPT ABOUT";S;"HOURS."
CHAPTER TWO
1. 10 INPUT A,B
20 IF A<B THEN PRINT A;"IS LESS THAN";B
30 IF A>B THEN PRINT A; "IS GREATER THAN".!B
40 IF A=B THEN PRINT A;"IS EQUAL TO";B
50 GOTO 10
7. 10 INPUT A*
20 IF A*>"DOWN" AND A*<"UP" THEN PRINT "A* IS BETWEEN"
9. 10 INPUT X
20 IF X<=25 OR X>=75 THEN PRINT "NOT IN THE INTERVAL" : GOTO 10
30 PRINT "IN THE INTERVAL" : GOTO 10
13. 10 FOR I = 1 TO 20
20 PRINT "*";
30 NEXT I
E-3
17. 10 INPUT "CREATURE" ; X*
20 RESTORE
30 FOR I = 1 TO 6
40 READ C*,W*
50 IF C*=X$ THEN 90
60 NEXT I
70 PRINT "CREATURE ";X$;" NOT FOUND."
80 GOTO 10
90 PRINT "YOU CAN KILL A ";C$5" WITH A ";W*
100 GOTO 10
110 DATA LICH,FIRE BALL,MUMMY,FLAMNG TORCH,WEREWOLF,SILVER BULLET
120 DATA VAMPIRE, WOODEN STAKE,MEDUSA,SHARP SWORD,TRIFFID,FIRE HOSE
19. LINE: 10 20 30 40 50 60 10 20 30 40
50 60 10 20 30 40 50
21. 10 FOR I = 1 TO 10
20 PRINT : PRINT " "
30 PRINT " HAPPY HOLIDAY MOTEL"
40 PRINT " ROOM"!I
50 PRINT " "
60 NEXT I
25. 10 INPUT N
20 FOR H = 1 TO N : REM H IS HEIGHT OF TRIANGLE
30 IF W=H THEN 70 : REM W IS WIDTH
40 PRINT "*";
50 W = W+l
60 GOTO 30
70 PRINT : W = 0 : REM RESET WIDTH FOR EACH H
80 NEXT H
27. 10 FOR I = 1 TO 5
20 READ N*,P : REM GET NAME, PERFORMANCE
30 IF F>=75 THEN 120
40 PRINTIPRINT "DEAR "IN*?","
50 PRINT " I AM SORRY THAT I MUST FIRE YOU."
60 PRINT "YOU HAVE BEEN SUCH A FINE EMPLOYEE"
70 PRINT "WITH A PERFORMANCE RATING OF" 5 P? "7."
80 PRINT "I'M SURE YOU'LL HAVE NO TROUBLE"
90 PRINT "FINDING ANOTHER JOB."
100 PRINT TAB(20);"SINCERELY,"
110 PRINT : PRINT TAB<20>;"GEORGE SHWABB" : PRINT
120 NEXT I
130 DATA OAKLEY,69,HOWE,92,ANDERSON,96,OLLEY,88,GOERZ,74
E-4
29. 10 INPUT "HOURS WORKED"; H
20 INPUT "HOURLY WAGE";W
30 M ■ W*H
40 IF H>40 THEN M - M+W/2»(H-40)
50 PRINT "THE WAGE FOR THE WEEK IS *";M
CHAPTER THREE
1. 10 FOR I = 1 TO 10
20 R - RND(0>
30 IF R>.5 THEN PRINT R
40 NEXT I
3. 10 INPUT N
20 IF N-INT(N) THEN PRINT N
30 GOTO 10
5. 10 N - INT(4*RND<0)+2)
20 D = INT<4*RND<0>+1)
30 Q = INT(4*RND<0>)
40 F ■ .03*N + .1*D + . 25*Q : REM TOTAL AMOUNT FOUND
50 PRINT "YOU FOUND *";F
60 IF F>.99 THEN PRINT "YOU CAN BUY LUNCH" : END
70 PRINT "SORRY, YOU CAN'T BUY LUNCH"
9. 10 FOR I = 1 TO 10
20 PRINT INT(21*RND(0)-10)
30 NEXT I
E-5
11a. RUN 11b. RUN
1 123.4 12.35
3 123.45 123.46
6
10 READY.
READY.
13. X V
L
2 8
2 2
2 A
3 A
3 -A
21. 10 READ V
20 PI = 3.14159
30 R = (.75*V/PI>A<l/3)
40 PRINT "A SPHERE WITH VOLUME";V;"CM."3"
50 PRINT "HAS A RADIUS OF ABOUT"!INT(100*R+.5)/100;"CM."
60 PRINT
70 GOTO 10
100 DATA 690,720,460,620
E-6
25. 10 FOR I = 1 TO 20
20 N - INT(100*RND<0>+1 )
23 IF N=l THEN 70
25 IF N=2 THEN 60
30 FOR X = 2 TO SQR(N)
40 IF N/X ■ INT(N/X) THEN 70
50 NEXT X
60 PRINT N;
70 NEXT I
27. 10 Q = INTCS*RND<0) )
20 D = INT(5*RND<0>)
30 P = INT(10*RND<0))
40 V = .25*0 + .1*D + . 01*F
CHAPTER FOUR
10 FOR I = 1 TO B
20 FOR 11 = 1 TO
30 PRINT ";
NEXT I 1
50 PRINT
60 NEXT I
3. 10 FOR I - 1 TO 6
20 INPUT
ii
ENTER X <I) " ;X < I)
30 NEXT I
40 FOR I = 1 TO 5 STEP 2
50 PRINT I ,X( I)
60 NEXT I
70 FOR I = TO 6 STEP 2
80 PRINT i ,x< I)
90 NEXT I
E-7
5. 10 DIM A(4, 12)
20 FOR I = 1 TO 4
30 FOR J a 1 TO 12
40 A(I, J) = 3*1 + J*J
50 NEXT J
60 NEXT I
70 INPUT "N ";N
80 FOR I - 1 TO 12
90 PRINT A(N, i);
100 NEXT I
110 PRINT
120 GOTO 70
2 6 12
3 12
3 6 11
14
READY. 13
11
READY
7c. RUN
45 89 35
READY.
9. 10 FOR X - 40 TO 1 STEP -1
20 FOR Y = 1 TO 10
30 READ N
40 IF N » X THEN PRINT N!
50 NEXT Y
55 RESTORE
60 NEXT X
70 DATA 5,27, 37,16,27,8,2,40,1,9
E-8
13. 10 FOR I = 3 TO 50
20 FOR J - 1+1 TO 50
30 FOR K « J+I TO 50
40 IF K*K > 1*1 + J*J THEN 70
50 IF K*K = 1*1 + J*J THEN PRINT I,J,K
60 NEXT K
70 NEXT J
80 NEXT I
E-9
19. 10 DIM N<100)
20 R - INT(100*RND<0)+1)
30 FOR X = 1 TO 100
40 INPUT "GUESS";G
50 IF G=R THEN 150
60 FOR Z = 1 TO X-l
70 IF N(Z) = G THEN 130
30 NEXT Z
90 N(X) ■ G
100 IF 0>R THEN PRINT "LOWER" : GOTO 120
110 PRINT "HIGHER"
120 NEXT X
130 PRINT "WAKE UP! YOU GUESSED THAT NUMBER BEFORE."
140 GOTO 40
150 PRINT "CORRECT."
E-10
23. 1 REM A*<> = LETTERS OF THE ALPHABET
2 REM W*O - THE WORD FORMED
10 DIM A$<26)
20 FOR I = 1 TO 26
30 READ A*(I)
40 NEXT I
50 FOR W m 1 TO 1
60 R = INT(7*RND(0)+1) : REM RANDOM LENGTH
70 FOR L = 1 TO R : REM GET WORD OF LENGTH R
80 W* ■ W*+A*(INT(26*RND(0)+1))
90 NEXT L
100 PRINT
110 W* = REM BLANK W$ FOR NEXT WORD
120 NEXT W
200 REM
210 DATA A,B,CfD,E,F,B,H,I,J,KfL,M,N(OfFfQfR,SfT,U,V,WpXpYfZ
25. 10 M - 500
20 FOR X = 1 TO 21
30 FOR Q = 1 TO 4
40 M = M + M * .06/4
50 NEXT Q
60 PRINT "AT THE END OF YEAR"}X;"THERE IS V';M
70 M = M + 60
80 NEXT X
CHAPTER FIVE
10 GOBUB 200
20 FOR J«"l TO 30
30 PRINT "*";
40 NEXT 3
50 GOSUB 200
60 FOR J=l TO 3
70 PRINT "!",
80 NEXT 3
90 GOSUB 200
100 FOR J=l TO 15
110 PRINT "AB";
120 NEXT J
130 END
200 PRINT
210 I ■ 1+1
220 PRINT "PART11; I
230 RETURN
E-11
3. 10 INPUT "1,2,3, OR 4";X
20 IF X<1 OR X>4 THEN 10
30 ON X GOTO 40,60,80,100
40 PRINT "AVOID BEING A VICTIM"
50 END
60 PRINT "PROGRAMMING IS COMMON SENSE"
70 END
80 PRINT "A LITTLE VICE IS SOMETIMES NICE"
90 END
100 PRINT "A COMMON COMIC COMUTER COMMANDS HIS COMMODORE"
110 END
7. 10 READ A,B,C
20 GOSUB 200
30 IF L=l THEN PRINT NOT A RIGHT TRIANGLE": GOTO 10
40 R = A*B/2
50 PRINT "AREA=";R,"PERIMETER^"3A+B+C
60 GOTO 10
200 L = 0
210 IF A+B <« C THEN 250
220 IF A+C <» B THEN 250
230 IF B+C <<■ A THEN 250
240 IF INT<AA2 + B-^2) = INT(C^2) THEN 260
250 L = 1
260 RETURN
270 DATA 3,4,5,0,1,1,2,2,2,12,5,13
280 END
9. 10 PRINT "WITHDRAWAL(1),DEF0SIT(2),"
20 PRINT "CALCULATE INTEREST(3), OR EXIT(4)
30 INPUT "1,2,3, OR 4"JD
40 IF D<1 OR D>4 THEN 30
50 ON D GOSUB 100,200,300,400
60 PRINT "YOUR BALANCE STANDS AT *";INT(100*B+.5)/100
70 PRINT: GOTO 10
100 REM WITHDRAWAL ROUTINE
110 PRINT "HOW MUCH WOULD YOU LIKE TO WITHDRAW"
115 INPUT A
120 IF A >= 0 AND B-A > 0 THEN B « B-A: RETURN
130 GOTO 110
200 REM DEPOSIT ROUTINE
210 PRINT "HDW MUCH WOULD YOU LIKE TO DEPOSIT"
215 INPUT A
220 IF A >= 0 THEN B = B+A : RETURN
230 GOTO 210
240 RETURN
E-12
300 PRINT "HOW MANY MONTHS SINCE LAST CALCULATION"
305 INPUT M
310 Q - M/3
320 IF Q < 1 THEN PRINT "TOO SOON": RETURN
330 FOR C = 1 TO Q
340 B = B+.0575/4*B
350 NEXT C
360 RETURN
400 END
13. (a) This program will generate an "?OUT OF DATA ERROR IN 10". Line 10 attempts to
read a fourth data element from line 40. A possible correction might read:
40 DATA 2,3,4,5
(b) This program will endlessly print .5 because no new data is read in at line 10. Correct
line 40 as follows:
40 GOTO 10
E-13
(c) Lines 20 and 30 each contain syntax errors. The function "* /" referenced at line 20 is
illegal. The statement may be corrected to read:
20 PRINT A*B+C
20 PRINT A/B+C
30 PRINT "D/F=";D/F
In addition, the variables D and F should be defined, or else a division by zero will result in
line 30.
(d) The conditional clause at line 20 is incomplete. The user has not specified what variable
should be less than 10. The obvious variable is F, so that line 20 reads:
A comma or a semicolon must be inserted between the variables F and G at line 40 so that
the computer understands that they are two separate elements:
40 PRINT F,G
(e) The FOR ... TO... NEXT loops are improperly nested:
10 FORX=1 TO 8
20 FOR Y=l TO 3
30 X=X+Y
40 NEXT X
50 NEXT Y
60 PRINT X
70 END
40 NEXT Y
50 NEXT X
Also, changing the value of variables used in FOR... TO... NEXT loops is not recom
mended practice such as at line 30.
(f) This program will continuously print the sum of 3, 6 and 9 since new data is not being
read at line 10. Correct line 40 as follows:
40 GOTO 10
E-14
15. RUN
-6 6
READY.
17. The computer will return the error "7SYNTAX ERROR IN 20". Since it appears that the
variable "X" is intended to contain formula weight, line 20 may be corrected to read:
(b) When this program attempts to branch to line 50 at line 35, it will not find fin 50, and the
error message "?UNDEF'D STATEMENT ERROR IN 35" will be printed. Change line 35
to:
(c) Note that both lines 10 and 20 do not contain the same number of closing parentheses
as opening parentheses, thereby causing an "7ILLEGAL QUANTITY ERROR IN 10". The
computer reports the first error encountered so the errors in line 20 and 30 go undis
covered. The first opening parenthesis is not necessary in either line 10 or 20. Line 30
should read:
IFXl>X2THEN50
(d) Upon encountering line 30, the computer will print the error message "7SYNTAX
ERROR IN 30". The line in question should read:
30 IF X>200 THEN 10
(e) When the computer runs this program, it will print "7TYPE MISMATCH IN 20" and
terminate the run. The problem arises from trying to add a floating point variable to a string
variable. Variables can be of several types. They can be integers (which means they have
no decimal places), floating point or real (which means they have decimal places), or string
variables. Assuming the intent of the program was to sum all the numbers between 1 and
26, the best way to correct this program is to change all occurrences of "A$" to "A".
20 A-A+X
40 PRINT A
19. The computer stores all decimal numbers in binary form. Because of this, small "rounding
errors" are introduced into stored numbers. When these errors are compounded as in the
large summation at lin 30 (100 and 1000 times), it leads to very visible miscalculations as
seen when this program is run. In this case the error was small.
E-15
CHAPTER SIX
Due to the difficulty of the material in Chapter 6, both odd and even answers are given
here. Each question is answered with the Commodore-64 solution. In addition, alterations are
included where necessary so that the program can run on the VIC-20 computer.
1. 10 PRINT
20 PRINT
36 FOR I
48 PRINT
30 NEXT I
2. 10 PRINT "i^
28 FOR V =^ TO 23
38 PRINT " |"
■48 NEXT V
ii P*5 :■ W W V ■"
78 PRINT "—"j
18 "I
8 pI¥nT+:
X88 FOR X = 6 TO 39
i±0 PRINT «-••;
±20 NEXT X
VIC-20 Alterations:
28 FOR V =
O PRINT a'lsi*t»X*MruX9l3Xf'l9X3X!X3l'l!X!V
±88 FOR X = G TO ±
±30 PRINT "feS"
3. S PRINT LQ
h% ^S^
38 PRINT " UNCLE BILL'S"
532Bi-12
28 KSIHI "WHAMBURGERS■"
58 PRINT " ONLV $8.79"
60 FOR D =* ± TO ±00 : NEXT D
78 PRINT "Li"
88 FOR D = ± TO ±86 : NEXT D
96 GOTO 28
VIC-20 Alterations:
±e POKE 36879,6*16+8+5
E-16
190 REM DIAGONAL
200 FDR I - 1 TO 13
210 POKE 1024+3+1+40*1,77 : POKE 55296+3+1+40*1,1
220 NEXT I
238 PRINT ■ 'LilPljlPliMPlJl!lPim3' ■
VIC-20 Alterations:
20 POKE 7680+3+22*Y,103 : POKE 3B400+3+22*Y,0
30 POKE 7680+10+22*Y,93 : POKE 38400+10+22*Y,0
40 POKE 7680+17+22*Y,101 : POKE 3S400+17+22*Y,0
110 POKE 7680+X+l+22*14,99 : POKE 38400+X + l+22*14., 0
120 POKE 7680+X+8+22*l,99 : POKE 38400+X+8+22*l,0
210 POKE 7680+3+1+22*1,77 : POKE 38400+3+1+22*1,0
VIC-20 Alterations:
10 FOR X = 0 TO 10
20 FOR Y = 0 TO 22
30 POKE 7680+X+22*Y,160
40 POKE 38400+X+22*Y,INT(8*RND<0)+1)
100 FOR X ■ 0 TO 10
110 FOR Y = 0 TO 22
120 C « PEEK<38400+X+22*Y) AND 15
130 POKE 7680+X+ll+22*Y,160
140 POKE 3S400+X+11+22*Y,C
E-17
90 REM MIRROR LEFT HALF OF SCREEN ON RIGHT HALF
100 FOR X = 0 TO 19
110 FOR Y * 0 TO 24
120 C = PEEK(55296+X+40*Y) AND 15
130 POKE 1024+39-X+40*Y,160
140 POKE 55296+39-X+40*Y,C
150 NEXT Y
160 NEXT X
170 60T0 170 : REM SUPPRESS READY.
ViC-20 Alterations:
10 FOR X = 0 TO 10
20 FOR Y = 0 TO 22
30 POKE 7680+X+22*Y,160
40 POKE 3B400+X+22*Y,INT<8*RND<0)+1)
100 FOR X = 0 TO 10
110 FOR Y = 0 TO 22
120 C ■ PEEK(38400+X+22*Y) AND 15
130 POKE 76B0+21-X+22*Y,160
140 POKE 3S400+21-X+22*Y,C
E-18
360 REM CLICK NOISE
370 REM SET VOLUME,WAVE FORM,NOTE
380 POKE 54296,B:POKE 54276,17:C=1300
390 REM POKE NOTE
400 POKE 54272,C-INT(C/256)#256:POKE 54273,INT(C/256)
410 FOR D=l TO 300:NEXT DlPOKE 54276,PEEK(54276) AND 254
420 POKE 54296,0
430 IF G <> B THEN RETURN
440 IF X/2 <> INTCX/2) THEN PRINT"HA HA,YOU LOSE": END
450 PRINT "ARB!!- YOU WIN TOUGH GUY"
460 FOR D = 1 TO 300 : NEXT D
470 POKE 53280,0:POKE 53281,0 : REM TURN SCREEN BLACK
480 PRINT " Ljm ■■ : REM CLEAR srprrN cct
CURSOR BLACF^ i*LtnK &LREEH, SET
VIC-20 Alterations:
310 IF G <> B THEN PRINT "CLICK.":A(X)=6:X = X+l:GOTO 400
340 POKE 36878,15
350 FOR Z = 1 TD 255
360 POKE 36877,Z
370 NEXT Z
380 POKE 36878,0
390 GOTO 430
400 REM CLICK NOISE
410 POKE 36878,5: POKE 36877,200
420 FOR D = 1 TO 300: NEXT D: REM DELAY
425 POKE 36878,0
470 POKE 36879,8: REM TURN SCREEN BLACK
E-19
VIC-20 Alterations:
10 REN CLEAR SCREEN, SET CURSOR BLACK, P
§|H?¥6?^ OF IB6 RANDOM tt'S";
h P5B E
45 S = 0
50 READ
66 FOR X = i TO T
70 READ N
86 S = S+N
90 NEXT X
±06 A<E> « S/7 - REM CALCULATE AVERAGE
±28 NEXT E: PRINT
±25 FOR I = ±9 TO 6 STEP -±
136 PRINT I
±35 NEXT I
±46 REM NOW PLOT BAR FOR EACH EMPLOVEE
±60 FOR E » ± TO 5
±T0 XO = <E-±>**7 + 4
±86 FOR V6 m 22-ACE) TO 2±
198 GOSUB 360: REM POSITION CURSOR
2O0 PRINT "U* "'"i : REM PRINT A SI
NGLE BAR
220 NEXT V0
225 REM POSITION CURSOR,PRINT NAME
236 PRINT"tJIIU";NS(E)
2-4© NEXT E
256 PRINT "\M"y - GOTO 606
300 REM Pp-SITION CURSOR AT CX6,V6>
316 PRINT #itart; = REM PUT CURSOR AT <8,8>
320 IF X0 * 0 THEN 360
330 FOR L » 0 TO X6-±
346 PRINT "IJ1"; : REM MOUE CURSOR RIGHT
350 NEXT L
366 IF V6 = 0 THEN RETURN
376 FOR L = 6 TO V6-1
386 PRINT "W; - REM MOUE CURSOR DOWN
396 NEXT L
466 RETURN
506 DATA HOWARD.7,±0,±0,±6,8, 9, 7
5±0 DATA JASONli±'20'±8;±5'27.£e,28
520 DATA JOSH.17.£©.±2,±8,1©,±5,£2
530 DATA JARE6,2±.25,±t,±6,26.14,22
540 DATA JESS,i7,i±,8,±0,±4,2i,±3
660 END
VIC-20 Alterations:
EAR SCREEN,SET CURSOR BLACK,PRI
E-20
9- 5 DIM N*<14) ,N(14>
10 FOR I = 1 TO 13
20 READ N*(I>
30 READ N(I)
40 NEXT I
50 POKE 54277,15 : POKE 54278,255
60 GET L$ : IF L$="" THEN 60
65 IF L* - N*<I) THEN POKE 54296,0
70 GOSUB 100 : GOTO 60
80 REM
90 REM
100 FOR I = 1 TO 13
110 IF L*=N*(I) THEN 150
120 NEXT I
130 POKE 54296,0
140 GOTO 210
150 POKE 54276,33: POKE 54296,8
160 C = N(I)
170 POKE 54272,C-INT(C/256)*256
180 POKE 54273,INT(C/256)
200 POKE 54276,32
210 RETURN
300 REM NOTE DATA
310 DATA Z,4291,S,4547,X,4817,D,5103
320 DATA C,5407,V,5728,G,6069,B,6430
3Z0 DATA H,6812,N,7217,J,7647,M,8101
340 DATA ",",8583
VIC-20 Answer:
5 DIM N*C14),N<14)
10 FOR I - 1 TO 13
20 READ N*(I)
30 READ N(I)
40 NEXT I
60 GET L* : IF L*«="" THEN 60
65 IF L* = N*(I) THEN POKE 36878,0
70 GOSUB 100 : GOTO 60
80 REM
90 REM
100 FOR I = 1 TO 13
110 IF L*=N$(I) THEN 150
120 NEXT I
130 POKE 36878,0
140 GOTO 210
150 POKE 36878,8
160 C = N(I)
170 POKE 36876,C
210 RETURN
300 REM NOTE DATA
310 DATA Z,225,S,227,X,228,D,229
320 DATA 0,231,7,232,8,233,6,235
330 DATA H,236,N,237,J,238,M,239
340 DATA ",",240
E-21
O o
£U cr D)
UUWICflU10101(flUCfl*,\Wk***£**W^^
(0aW)UI& CDODOOXn^^ UH3Q LnSi 9 GDOCD
ti -n 10
o o o OZ
HMH
S Si
coco :h
MM
:> m
Ul 01 x
ts a o H
Z
2 z m
m n X m
x x 3
H H H a
m
r
H
-4 H
z Z 2 z H
H H
ro
LJ
Z Tjj-
t-t O>
03
Q.
»-* 5
z c
. o
■ : T :i :i :i -J o>
N / ^ ^ ^ O g
H h H H g &
H Z Z Z Z ll
Z H W M M
S
0,
£ " S! £ 5
Ui
I
q
H_
o o
§ g
m w
tt q q 2 tn
m u. <r <r
u o u. u. tr a:
a fi O fi w ooquj
° t_ l_ i_ !_- (viTUJUJaQ:
h: :::::::: x::::::::: x::::::::: x::::::::: x::: I ::::: « i- « « u. u_
Ul LJ LJ \ Uifs J _/\l
uj -i j—Ii rz \
^ .—"i rnvl
zn I -^rrJ! Knr
zO -^J
_y\i zDl
zOr "\\ Jsu.
„ - - 33 Vs?
X QOUfOt-i ujujuj
::::::::: h: :::::::: h: :::::::: -h: :::::::: h: :::::::: * " g >< >■ ^^^
I^.^.^.S^.^.^,^,^,, .^.%.S,^,^,^^,^.S .^.^.^.%.4.^.^.4.% .*.*.*.*.*.*.*.*.« .^^i^.m^.s^.^-O QJ (j J- ^ ^ ..
zoxxxxxxxxxHXXxxxxxxxHxxxxxxxxxt-xxxxxxxxxi-xxxxxxxxxo ^ _ P"1 c(1: slil
wwwvw wwvwwv wvwww vwwwwts ■ j: ,h .. .. ^- (N # (N
z -« n lu cn a
CCCCCCCGC CCCCCCCCC CCCCCCCCC CCCCCCCCC- ¥ ^J ^n01 n^rj ?^n^
n HHHKHHHHh!IHt-HHh-h-HHI-III-l-t-Ht-HhHt-IIHHHHH'h'Hh+-ll(-hHhH-HI-l-N ..f= ^ -k " h - « *Cfi~ta
ll +«lcNS!»-Ht-t^-oao
i^ hHHHhhHHI-QhHH-h'HHHhOHHHHHH'HI-HfiHhHHHHHhHfiHI-KHHHhi-HX o10 J'S"4^ rt^n Hu lltD
&ZZZZZZZZZ ZZZZZZZZZ ZZZZZZZZZ ZZZZZZZZZ ZZZZZZZZZ ~ H ?J m f! ii « z ■■ « •■
X NHHHHHHHHQlHHMHHHMHHttHHHHHHHHHQlHHHHHMHHWlklHHHHHHMHHll w A Z — [fl Q '-' Q Q n Z
L.oo.CLa.a.Q.a.iLaiiLi.a.o^ixa.i^^ <x ar^ttcc£ir^^uj"iLjj-
ML. oU_ IhOO UJO ZtCU CDU
CM ^ P Q. LL Z Ll
... - _- -.-. ... . ^* 0*> IS Si 12 Si Si IS Si S Si 'H CN hO *3" If)
CM
2 uj
200 FOR I = L(R) TO L<R+1)-1
210 X » C(I,1)
220 Y « C(I,2>
230 POKE 1024+X+40*Y,81 : REM DRAW A DOT
240 POKE 55296+X+40*Y,Cl : REM SET COLOR OF DOT TO Cl
250 NEXT I
260 RETURN
270 REM
299 REM INDEX DATA
300 DATA 1,2,4,7,11,16,22
310 REM
400 REM COORDINATE DATA
410 DATA 19,12,11,4,27,20
420 DATA 11,4,19,12,27,20
430 DATA 11,4,27,4,27,20,11,20
440 DATA 11,4,27,4,27,20,11,20,19,12
450 DATA 11,4,27,4,27,20,11,20,11,12,27,12
VIC-20 Alterations:
30 POKE 36879,0*16+8+0
230 POKE 7680+X+22*Y!,81 : REM DRAW A DOT
240 POKE 38400+X+22*Y.Cl : REM SET COLOR OF DOT TO Cl
410 DATA 10,11,5,5,15,17
420 DATA 5,5,10,11,15,17
430 DATA 5,5,15,5,15,16,5,17
440 DATA 5,5,15,5,15,17,5,17,10,11
450 DATA 5,5,15,5,15,17,5,17,5,11,15,11
E-24
300 REM PRINTS VERTICAL BAR AT <X1,Y1)
310 FOR Y = Yl+1 TO Yl+3
320 POKE 1024+X1+40*Y,66
ZZ0 POKE 55296+Xl+40*Y,1
340 NEXT Y
350 RETURN
360 REM
400 REM POSITION DATA
410 DATA 14,11,18,7,14,7,14,7
420 DATA 14,11,14,15,18,11
430 REM
500 REM SEGMENT DATA
510 DATA 126,66,55,103,75,109,125,70,127,111
VIC-20 Alterations:
15 POKE 36B79,S
220 POKE 7680+X+22*Yl,64
230 POKE 38400+X+22*Y1,1
320 POKE 7680+Xl+22*Y,66
330 POKE 38400+Xl+22*Y,1
410 DATA B,11,12,7,8,7,8,7
420 DATA 8,11,8,15,12,11
E-25
300 REM PRINT VERTICAL BAR AT (XI,YD
310 FOR Y - Yl+1 TO Yl+3
320 POKE 1024+X1+40*Y,66
330 POKE 55296+Xl+40*Y,C
340 NEXT Y
350 RETURN
360 REM
400 REM ROUTINE TO DECODE SEGMENT DATA
410 FOR I = 0 TO 6 : REM 7 SEGMENTS
420 N « N/2 : REM IS N DIVISIBLE BY 2?
430 IF N « INT(N) THEN 460
435 REM POSITION BAR AT (XI,YD
440 XI - P(I,1) + F Yl • P(I,2)
450 ON 1+1 GOSUB 200,300,200,300,300,200,300
460 N - INT(N)
470 NEXT I
480 RETURN
490 REM
500 REM POSITION DATA
510 DATA 12,11,16,7,12,7., 1
520 DATA 12 11,12,15,16,11
530 REM
600 REM SEGMENT DATA
610 DATA 126,66,55,103,75,109,125,70,127,111
VIC-20 Alterations:
10 POKE 36879,8 REM SET BACKGROUND BLACK
220 POKE 7680+X+22*Yl,64
230 POKE 38400+X+22*YlfC
320 POKE 7680+Xl+22*Y,66
330 POKE 38400+Xl+22*Y,C
510 DATA 5,11,9,7,5,7,5,7
5
520 DATA 5 ,11,5,15,9,11
CHAPTER SEVEN
1. 10 INPUT N
20 IF N < 0 THEN PRINT "NO NEGATIVE NUMBERS ALLOWED." : GOTO 10
30 PRINT "N =";N, "SQUARE ROOTS - + OR -"!;SQR<N> : GOTO 10
5. 10 INPUT N
20 PRINT SGN(N) * N REM THIS IS EQUIVALENT TO ABS(N)
E-26
7. 10 FRINT "RADIANS","DEGREES"
20 FOR A = 0 TO 3 STEP .25
30 PRINT A
40 NEXT A
9. 10 INPUT N
15 N - N/180
20 C = COS(N)
30 S - SIN(N)
40 T = TAN(N)
50 IF OS AND OT THEN PRINT "COSINE -MfC
60 IF S>T AND B>C THEN PRINT "SINE =";S
70 IF T>S AND T>C THEN PRINT "TANGENT -nST
15. RUN
5 -4
READY.
17. RUN
FNF<-4 ) IS NEGATIVE
FNF(-2 ) IS NEGATIVE
FNF( 0 ) IS NEGATIVE
FNF( 2 ) IS ZERO
FNF( 4 ) IS POSITIVE
FNF( 6 ) IS POSITIVE
READY.
19. RUN
-3
-2
— 1
0
1
2
3
4
READY
E-27
21. 10 INPUT "R AND THETA (IN DEGREES) :";R,T
20 T = T**-rf/180
30 X = R*COS<T)
40 Y = R*SIN(T)
50 PRINT "(X,Y) - <";XS",";Y;")"
CHAPTER EIGHT
1. 10 INPUT "A*"; A*
20 FOR 1=1 TO LEN(A$>
30 PRINT ASC(MID$(A$,I,1>);
40 NEXT I
3. 10 READ X
20 PRINT CHR*(X):
30 GOTO 10
40 DATA 65,83,67,73,73,32,66,73
50 DATA 68,32,84,72,73,83,33
E-28
40 FOR 1=1 TO LENCN*)
50 S^ASCCMIDf* CN$, 1,1))
60 A(S-64)»A(S-64)+l
70 NEXT I
80 REM
S9 REM
100 REM FIND MOST COMMON LETTER
110 REM
120 M=l
130 FOR 1=1 TO 26
140 IF A<I)»M THEN F=»l
150 IF A(I)>M THEN M«A (I > : V«I: F=«0
160 NEXT I
170 REM
180 REM
200 REM PRINT MOST COMMON LETTER
210 IF F»0 THEN PRINT CHR*(V+64);
" IS THE MOST COMMON LETTER" END
220 PRINT "THE FOLLOWING LETTERS HAVE AN"
230 PRINT "EQUAL OCCURRENCE:'1
240 FOR 1=1 TO 26
250 IF A(I) - M THEN PRINT CHR*<1+64);" ";
260 NEXT I
9. 10 READ W*
20 FOR I 1 TO LEN (W*)
30 T$ - ^
1ID*(l <!*., I i 15
40 IF :>"E" THEN PRINT
50 NEXT I
60 PRINT : (30TO 10
100 DATA QUEEN,LENGTH,REMEMBER
13. 10 A$ = "ABCDEFGHIJKL"
20 FOR I = 1 TO 12
30 PRINT LEFT*(A*,I)
40 NEXT I
E-29
15. RUN
87
72
55
54
READY.
E-30
23. 1 REM T$ - A WORD FROM THE SENTENCE
2 REM W*() = UP TO 30 WORD SENTENCE
3 REM 5$ = ORIGINAL SENTENCE
4 REM
5 REM
10 DIM W*(30)
20 INPUT "YOUR SENTENCE";3$
30 S*=CHR*(32>+S*+CHR«<32)
40 FOR X»l TO LEN(3$)
50 T$=MID*<S$? X, 1)
60 IF ASC(T*>»32 THEN C=C+1:GOTO 80
70 W*<C)=W*(C)+T*
80 NEXT X
90 FOR L-30 TO 1 STEP -1
100 IF W$<L)<>"" THEN PRINT W*(L);" "J
110 NEXT L
CHAPTER NINE
Tape Files
E-31
3a. i REM CASSETTE FILE
10 OPEN 2,1,1,"SEG FILE"
20 FOR 1=1001 TO 1128
30 PRINT#2,I
40 NEXT I
50 CLOSE 1
60 END
E-32
10 REM FUNCTION TO ROUND TO NEAREST 100TH
20 REM
30 DEF FNR(X)=INT(100*X+.5)/100
40 REM
50 REM
100 OPEN 2,1,0,"PAY FILE"
110 FOR X = 'l TO 10
120 INPUT#2,N*,R,D,M,L
130 READ H : REM GET HOURS WORKED
140 G=H*R : T=(25-2*D)*G/100
150 IF T<0 THEN T=0
160 P=G-T-M-L
170 PRINT N*;" - "
180 PRINT "HOURS WORKED:";TAB(25);H
190 PRINT "GROSS PAY:"jTAB(24);"*";FNR(6)
200 PRINT "TAX:";TAB(24>;"$";FNR(T)
210 PRINT "MEDICAL INSURANCE: " ; TAB(24) ;"$"; FNR(M)
220 PRINT "LIFE INSURANCE:";TAB(24)!"*"!FNR(L)
230 PRINT "NET:";TAB(24);"*"!FNR(P)
240 PRINT
250 NEXT X
260 CLOSE 2
270 REM
280 REM
300 REM DATA SECTION
310 DATA 40,37.1,51,48,39.21,18,6,59.8
320 DATA 45.3,68.3,41
330 END
Diskette Files
E-33
3a. 1 REM DISKETTE FILE
10 OPEN 3,8,3,"SEQ FILE,SfW"
20 FOR 1=1001 TO 1128
30 PRINT#3,I
40 NEXT I
50 CLOSE 3
60 END
E-34
10 REM FUNCTION TO ROUNP TO NEAREST 100TH
20 REM
30 DEF FNR<X)»INTU00*X+.5)/10J8
40 REM
50 REM
100 OPEN 7,8,7,"PAY FILE.S,R"
110 FOR X-l TO 10
120 INPUT#7,N$,R,D,M,L
130 READ H : REM GET'HOURS WORKED
140 G=H*R : T-(25-2*D)*G/100
150 IF T<0 THEN T=0
P*B-T-M-L
170 PRINT N$;" - "
180 PRINT "HOURS WORKED: " ; TAB (25) JH
190 PRINT "GROSS PAY:";TAB(24);"$";FNR(G)
200 PRINT "TAX:"STAB(24)5"*"sFNR(T)
210 PRINT "MEDICAL INSURANCE:" ;TAB(24);"*";FNR(M)
220 PRINT "LIFE INSURANCE:";TAB(24);"*";FNR(D
230 PRINT "NET:";TAB(24);"$";FNR(P>
240 PRINT
250 NEXT X
260 CLOSE 7
270 REM
280 REM
300 REM DATA SECTION
310 DATA 40,37.1,51,48,39.21,18,6,59.8
320 DATA 45.3,68.3,41
330 END
E-35
7b. 1 REM DISKETTE FILE
2 REM TO = ARRAY WHICH HOLDS TEMP IN
3 REM POSITION TIME#10
4 REM H = TIME IN HOURS
5 REM
10 DIM T<100>
20 OPEN 3,8,3,"NIT FILE,S,R"
30 OPEN 4,8,4,"WIT FILE,S,R"
40 OPEN 5,8,5,"MERGE FILE,S,W"
50 FDR L=l TO 6
60 INPUT#3,H,F : GOSUB 100
70 INPUT#4,H,F : GOSUB 100
80 NEXT L : GOTO 200
90 REM
100 REM IF T(TIME*10) IS EMPTY THEN PUT
110 REM THE TEMP IN IT, ELSE AVERAGE
120 REM THE VALUES
130 REM
140 IF T<H*10>»0 THEN T(H*10)=F:RETURN
150 T(H*10)=<T(H*10)+F>/2 : RETURN
160 REM
170 REM
200 REM WRITE TO MERGE FILE
210 REM
220 FOR Z=0 TO 100
230 IF T(Z)<>0 THEN PRINT#5,Z/10;","ST(Z>
240 NEXT Z
250 CLOSE 3 : CLOSE 4 : CLOSE 5
260 END
E-36
200 REM BUBBLE SORT
210 REM
220 FOR T«l TO 14
230 FDR 1=15 TO T+l STEP -l
240 IF N*(I )>N*(I-1) THEN 270
250 T$=N$(I ):N$(I)~N$(I -i>:n*<i-1)=t* : REM SWAP NAMES
260 T1=A(I) ; ft ( I ) a=A ( I~l ) «HU-n-l 1 . r\fc.r SWAP AGES
270 NEXT I
280 NEXT T
300 REM
400 REM OUTPUT SECTION
410 REM
420 OPEN 6,8,6, "TEMP FILE,S , W"
430 FOR X«l TO 15
440 PRINT#6,N *<X) ; ", "S A(X )
450 NEXT X
460 CLOSE 6
480 REM
500 REM FILE MANAGEMENT SECTION
510 REM
520 OPEN 15,8,1
530 PRINT#15,"S :NAME h. AGE FILE"
540 PRINT#15,"R :NAME %'. AGE FILE-TEMP FILE"
550 CLOSE 15
560 END
450 NEXT X
460 CLOSE 6
(Continued on next page)
E-37
500 REM FILE MANAGEMENT SECTION
510 REM
520 OFEN 15,8,15
530 PRINTttlS,"S:NAME & AGE FILE"
540 PRINT#15,"RrNAME & AGE FILE=TEMP FILE11
550 CLOSE 15
560 END
E-38
INDEX
COMMENTS:
D have adopted D will adopt □ will consider adopting □ will not adopt
VNRFEV
A GUIDE TO PROGRAMMING THE COMMODORE COMPUTERS is a compre
hensive manual designed to help people exploit thoroughly the considerable ca
pabilities of their Commodore-64 or VIC-20 computers. Appropriate for people
with a wide range of backgrounds, this manual is structured in a unique way.
Topics are discussed individually so that students may select the sequence that
interests them. Individual chapters are devoted to programming techniques, color
graphics and sound, mathematical functions, data types and the disk operating
system.
Although the manual has been developed and extensively tested for classroom
use, it is also an effective tool for individual study. From the beginning of the man
ual, students are taught good programming techniques which are essential to writ
ing logical, easy to read prog. ams. This manual also features review exercises in
each chapter and comprehensive problem sets, which offer the student program
mer an opportunity to try out newly learned skills. Solutions to odd-numbered
problems are given at the back of the manual.
Bruce Presley, a graduate of Yale University, has taught computer programming at
The Lawrenceville School for more than fifteen years and is presently serving as a
member of the Advanced Placement Computer Science Committee of the College
Entrance Examination Board.