0% found this document useful (0 votes)
30 views

OceanofPDF.com IBM PC Basic Programming - Richard E Haskell

Uploaded by

mf6ky7h4cf
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

OceanofPDF.com IBM PC Basic Programming - Richard E Haskell

Uploaded by

mf6ky7h4cf
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 200

te Cone schol ¢

oof elcera Ee gaat AcapetengNaa aR cia dus

RICHARD HASKELL and GLENN A. JACK

a
This easy-to-use book provides begin-
ning and advanced programmers with a
hands-on step-by-step approach to pro-
gramming an IBM PC™ in BASIC.
Complete with actual photographs taken
from the computer’s video screen,
uses graphical exam-
ples to develop many fundamental.program-
ming concepts. This unique teaching: method
gives you the opportunity to actually see a
direct visual picture of what the program is
doing. What’s more, this comprehensive intro-
duction features numerous examples to help
you write your own programs for specific appli-
cations.
Ideal for self-study or classroom instruction,
includes valu-
Fle}(-Miaicelmut-licela melap

holds a Ph.D. from Rens-


selaer Polytechnic Institute and is a professor
fo) Mate Lal-t-ialare Me-lare Mmedar-liquar-lalmey my (-Yod
(alef] ME-Tale|
computer engineering at Oakland University in
Michigan. He has written five other Prentice-
Hall books entitled Apple !I-6502 Assembly Lan-
(o[E-Te[mam 0)Ce) am @RS)<36)Pa ff Dott] Oa = @-Y a 0-10 Ml@X0) lo)g
BASIC (1983), Atari BASIC (1983), Apple BASIC
(1982), and PET/CBM BASIC (1982).

is a professor of engi-
ttlalate lite Meal-ligiit-leMelmexelulelviClar-liteM lilt e
tion science at Oakland University:in Michigan.
a en
eh

“a
Richard Haskell holds a Ph.D. from Rensselaer Poly-
technic Institute and is a professor of engineering and
chairman of electrical and computer engineering at
Oakland University in Michigan. He has written five
other Prentice-Hall books entitled Apple I-6502 As-
sembly Language Tutor (1983), TRS-80 Extended
Color BASIC (1983), Atari BASIC (1983), Apple BA-
SIC (1982) and PET/CBM BASIC (1982).

Glenn A. Jackson holds a Ph.D. from the University


of Michigan and is a professor of engineering and chair-
man of computer and information science at Oakland
University in Michigan.
IBM PC”
BASIC
PROGRAMMING

Richard Haskell and Glenn A. Jackson

SPECTRUM BOOK

Englewood Cliffs, New Jersey 07632


Library of Congress Cataloging in Publication Data

Haskell, Richard E.
IBM PC BASIC programming.

“A Spectrum Book.”
Includes index.
1. IBM Personal Computer—Programming. 2. Basic
(Computer program language) I. Jackson, Glenn A.
II. Title.
QA76.8.12594H38 1984 001.64'24 83-19220
ISBN 0-13-448432-0
ISBN 0-13-448424-X (pbk.)

This book is available at a special discount when ordered


in large quantities. Contact Prentice-Hall, Inc., General
Publishing Division, Special Sales, Englewood Cliffs, N.J. 07632.

© 1984 by Prentice-Hall, Inc., Englewood Cliffs, New Jersey 07632

All rights reserved. No part of this book


may be reproduced in any form or by any means
without permission in writing from the publisher.
A Spectrum Book. Printed in the United States of America.

ODEO S een Om ome aa ane 1

Editorial/production supervision by Chris McMorrow


Cover design by Hal Siegel
Manufacturing buyer: Joyce Levatino

ISBN O-13-44643e-0
USBNSO-b3s=4464c4-X {PBK .F

Prentice-Hall International, Inc., London


Prentice-Hall of Australia Pty. Limited, Sydney
Prentice-Hall Canada Inc., Toronto
Prentice-Hall of India Private Limited, New Delhi
Prentice-Hall of Japan, Inc., Tokyo
Prentice-Hall of Southeast Asia Pte. Ltd., Singapore
Whitehall Books Limited, Wellington, New Zealand
Editora Prentice-Hall do Brasil Ltda., Rio de Janeiro
CONTENTS

Preface, vii

1 LEARNING TO USE THE IBM PC


PERSONAL COMPUTER KEYBOARD, 1

2 LEARNING TO PROGRAM IN
BASIC, 8

3 LEARNING MORE ABOUT PRINT, 16

4 ENTERING DATA FROM THE KEYBOARD:


LEARNING ABOUT INPUT AND INKEY$, 31

5 A REPETITION LOOP:
LEARNING ABOUT FOR. . . NEXT, 37

6 MAKING CHOICES: LEARNING ABOUT


ieee em CINGAN Dale?.* ait EIN en. HELSE 43
7. LEARNING TO USE MEDIUM RESOLUTION GRAPHICS:
DISPLAYING THE FLAG, 54

8 LEARNING ABOUT LOOPS, 64

9 LEARNING TO USE GOSUB AND RETURN:


SUBROUTINES, 74

100 MAKING BAR GRAPHS:


LEARNING ABOUT READ . . . DATA, 84

11. LEARNING TO USE ARRAYS, 93

12 $$$ WITH STRINGS ATTACHED:


LEARNING ABOUT LEFT$, RIGHT$, AND MID$, 101

13 LEARNING TO USE
HIGH RESOLUTION GRAPHICS, 115

14 LEARNING TO PEEK AND POKE, 135

15 LEARNING TO PUT IT ALL TOGETHER, 153

APPENDIXES, 171

Index, 187
PREFACE

Anyone planning to teach a BASIC programming Chapter 1 introduces the IBM PC keyboard and
course using an IBM PC™ is faced with the problem the idea of string variables. Chapter 2 talks about the
of selecting an appropriate text. Programming manuals general nature of BASIC programs and introduces the
provided by the manufacturer are generally more suit- use of the IBM PC Disk Operating System.
able for reference than for teaching. Standard text- Chapter 3 covers numerical variables, arithmetic
books on BASIC programming will describe a BASIC expressions, and the IBM PC’s built-in functions. The
language enough at variance with IBM PC BASIC INPUT statement and the INKEY$ function are cov-
to lead to considerable frustration on the part of the ered in Chapter 4 with examples that include making
student. Such texts will be of no help in learning to sounds. Chapter 5 introduces the FOR . . . NEXT
use the graphics capability of the IBM PC. Since many loop with programs to produce several sound effects.
interesting programs involve graphics, these texts will Chapter 6 introduces the IF . . . THEN statement
be of little value. and relational and logical operators.
This book is designed to be used as a text for learning The use of medium resolution graphics is introduced
to program in BASIC using the IBM PC. It should in Chapter 7 and the American flag is displayed on
be suitable for introductory programming courses at the screen. A more complete discussion of loops is
the high school, junior college, or university levels. given in Chapter 8. The use of subroutines is covered
It can also be used for self-study with an IBM PC. in Chapter 9 where the student learns to draw multiple
The strategy of this book is “learning by doing.” figures of varying size.
Step by step the student is led through all aspects of The READ . . . DATA statement is introduced
BASIC programming on an IBM PC. All examples in Chapter 10 where a method of drawing bar graphs
are illustrated with many photographs taken from the is covered. The topic of arrays is discussed in Chapter
computer’s TV screen. Many of the fundamental pro- 11. String functions are described in detail in Chapter
gramming ideas are developed using examples involv- 12 with examples given for dealing a hand of cards.
ing graphics. This has the advantage of providing a High resolution graphics is covered in Chapter 13 in-
direct visual picture of what the program is doing. cluding the use of the DRAW statement for drawing
In addition it provides examples that will be useful predefined shapes. Chapter 14 describes the use of the
for anyone wishing to write programs in a specific PEEK and POKE statements including how to POKE
applications area. a picture and introduces the area of animated graphics.

vii
Chapter 15 describes the development of two complete (May 1982), Version 1.1; IBM PC Disk Operating Sys-
programs: the Hangman word game, and a PC organ tem manual, Second Edition (May 1982), Version 1.1;
that plays four octaves of music from the computer IBM PC Guide to Operations Manual, First Edition
keyboard. This chapter also includes an example of (Revised April 1982); IBM PC Technical Reference
how to store data on a floppy disk. manual, Revised Edition (July 1982).
Students who complete this text will have a solid It is a pleasure to acknowledge our students of many
foundation in fundamental programming techniques years, who had to learn to program on a large computer
and will have acquired the particular skill of being with none of the graphics capability of the IBM PC,
able to program the IBM PC using BASIC. For further but on whom many of the ideas in this book were
reading they may refer to the following IBM reference first tested. Special thanks go to Sharon Rix who typed
manuals, all of which are under copyright of IBM the manuscript with skill, patience, and good humor.
corporation: IBM PC BASIC manual, Second Edition

viii
LEARNIN O USE THE
IBM PERSONAL CO PUTER KEYBOARD

There is only one way that you can learn how to pro- that your computer has a graphics monitor (either
gram a computer. You must write programs and run color, or black and white) and at least one disk drive
them on a computer. It is not possible to learn to with Advanced BASIC available. If your system does
program by reading about it. Programming is an action not have a graphics monitor, or if you have a graphics
activity. You must do it! This book is designed to monitor but no disk drive, you will not be able to
help you learn how to program in the BASIC program- run some of the graphics programs to be presented.
ming language by actually using an IBM Personal Those programs that require Advanced BASIC will
Computer. be clearly marked. However, you should find this book
The IBM Personal Computer (PC) is one of several to be of value regardless of the configuration you have
popular personal computers (such as the PET, the Ap- on your IBM PC. All photos showing computer output
ple II, and the Atari) that are finding their way into from a terminal will be from a graphics monitor set
an increasing number of homes, offices and schools. at 40 characters/line output. Figure 1.1 shows a typical
All of these personal computers will run programs IBM PC installation.
written in the BASIC programming language. How- In this chapter you will become familiar with the
ever, the BASIC programming language is imple- use of the IBM PC keyboard. In particular you will
mented somewhat differently on each of these various learn the meaning of the special keys shown in Figure
computers. This is particularly true with respect to 2:
how graphics programming is done. This means that You will also:
a BASIC program written for an Apple II computer
will not, in general, run on an IBM PC without some 1. learn to use the PRINT statement,
modification. It also means that if you are learning 2. learn what strings and string variables are,
BASIC for the first time it will be easier for you if
3. learn the difference between the direct and indi-
you use a book written specifically for the kind of
rect modes of execution,
computer you are using. In this way you will not be-
4. learn to use the LIST and RUN commands, and
come frustrated by all of the little “exceptions” that
the function keys Fl and F2,
apply only to your computer.
This book is written assuming that you have an 5. learn to use the NEW command, and
IBM PC available for you to use. It is also assumed 6. learn to edit a statement.
yr
Figure 1.1 IBM PC’s may be connected to either graphics
Or monochrome monitors (or both).
Figure 1.3 Turning on the IBM PC.
Begin by turning on your IBM PC. This is done by
flipping up the ON-OFF switch located toward the
back of the right side of your computer as shown in In addition to the read only memory (ROM) your
Figure 1.3. (Do not insert a disk in your disk drive.) computer also contains some read/write memory
After a few seconds, the TV screen should look like called RAM for random-access memory. The differ-
the display shown in Figure 1.4. The number of “free ence between ROM and RAM is that you can change
bytes” showing on your display may not be the same the contents of a RAM location while the contents
as that in Figure 1.4, since this is determined by the of a ROM location is fixed and can’t be changed. Also
amount of memory in your computer. when you turn the power off to your IBM PC the
Your IBM PC contains a Read Only Memory, called contents of the RAM locations are lost while the con-
a ROM, that contains what is termed the Cassette tents of the ROM locations are retained. This is why
BASIC interpreter and other systems programs. Ad- the BASIC interpreter, located in ROM, is always
vanced BASIC is contained on a diskette labeled DOS there every time you turn on your computer. On the
(for Disk Operating System). Advanced BASIC is an other hand every program that you write is stored
extension of ROM BASIC and has added graphics in RAM and is lost whenever you turn the power
capabilities. There is also a third version of BASIC off. This is why you must save your programs on a
called Disk BASIC that is in between cassette and diskette (or cassette) if you wish to run them at a
advanced BASIC as far as the number of extensions later time without having to type in the entire program
to the language is concerned. Most of the programs again.
in this book will run with any of the three types of The amount of RAM that you have in your IBM
BASIC. We will point out those statements that are PC can be anywhere from 32K to 256K. The more
only available in disk or advanced BASIC as we go
along. Figure 1.4 Initial screen display using IBM PC BASIC.

Figure 1.2 Special keys discussed in this chapter.


The IBM Personal Computer Basic
Uersion C1.@@ Copyright
62944 Bytes free ilaae cal bes Seg

cSLis) Beraniine| KILOAD MESAUE MEESCONT€


BACKSPACE ENTER

SHIFT
RAM that you have the larger programs you can run PRINT “THIS IS A STRING”
and the more data you can store in the computer. If
followed by ENTER. The result should be as shown
you have 64K of RAM this means that your computer
in Figure 1.6.* Note that the computer immediately
actually contains 65,536 bytes of RAM. (1K = 1024
printed the words THIS IS A STRING. Any sequence
bytes.) A byte is 8 bits where a bit is a 1 or a 0.
of characters enclosed between quotation marks (“‘ ”)
Thus, for example, the binary (base 2) number
is called a string. If you type the word PRINT followed
10101101 is a byte. It takes one byte to store a character
by a string the computer will immediately print this
in the IBM PC. Most “home” computers have from
string (without the quotation marks) on the screen.
16K to 64K bytes of RAM.
This is called the direct mode of execution.
When the TV screen contains the Ok followed (on
the next line) by a blinking cursor then the computer
Figure 1.6 Using the PRINT statement in the direct mode
is ready and waiting for you to type in something. of execution.
Try typing your name and then press the ENTER
Ok
key. (The ENTER key contains the arrow symbol —. FRINT "THIS IS A STRING"
See Figure 1.2.) If your name is JOHN you should THIS’ IS A STRING
see something like that shown in Figure 1.5. Ok

Any characters can be included in a string. For


example, if you type
Personal Computer Bas PRINT COA RR KK ID
. 88 Copyright IBN Cate i9si

the computer will print this line of asterisks just as


you typed it in the string as shown in Figure 1.7.

Figure 1.7 Strings can contain any characters.


Ok
PRINT "THIS IS A STRING"
THIS IS A STRING
Ok
PRINT "OOK OK KKK"

Ok

INDIRECT MODE OF EXECUTION


Figure 1.5 A SYNTAX ERROR occurs when you type an
invalid BASIC command. If a BASIC statement such as PRINT is preceded
by a line number (such as 10) then the statement is
not executed immediately but rather its execution is
Note that the message Syntax error appears on the deferred until the command RUN is typed. For exam-
screen when you pressed the ENTER key. This is be- ple, Figure 1.8 shows how to print a line of asterisks
cause JOHN is not a valid BASIC command and the
computer can only respond to BASIC commands that Figure 1.8 PRINT statement using the indirect mode of
it understands. You will learn many of the valid BASIC execution.
commands in this book. However, anytime you type
Ok
an invalid command because of misspelling, or other- 10 PRINT "“xXxXxkKK"
wise, the IBM PC will respond with a Syntax error RUN
xX KKK
message. You cannot hurt the computer by pressing
Ok
the wrong key. If it doesn’t like what you typed it
will just display Syntax error on the screen.
using the indirect mode of execution. When BASIC
statements have line numbers these statements are
“stored” in the computer. They can be RUN at any
STRINGS AND THE PRINT STATEMENT

Type in the command CLS and press the ENTER * Many of the figures appearing in the book are listings of programs,
or program results, that are images of what appears on the screen
key. CLS stands for “clear screen,” and entering this
display. Textural data that are on the screen can be copied directly
command will clear the screen and move the cursor to the printer by pressing the shift key and the PrtSc key simultane-
to the upper left-hand corner of the screen. Now type ously.
10 PRINT 66 ee eK KID
time. If you type RUN (followed by ENTER) again
the computer will again display the line of asterisks. 20 PRINT 662 oe2koe ke 99

Try it. 30 PRINT “#* **”


Note that you must press ENTER at the end of 40 PRINT “** **”
each statement (such as PRINT) or command (such
as RUN). The IBM PC does not look at what you
50 PRINT “#*###4»
60 PRINT 66 eK KID
have typed on a line until you press ENTER. When
you press ENTER the computer then deciphers what RUN
you typed on the line and decides what to do.
You can always look to see what BASIC statements you should obtain the result shown in Figure 1.11.
you currently have stored in the computer by typing As a second example, Figure 1.12 shows how to
LIST. Try it. You should have listed the single PRINT have the IBM PC print the name JEFF in block letters.
statement number 10 shown in Figure 1.9. Try it one
more time, only this time type in CLS followed by
Figure 1.11 Simple figures can be drawn by including each
ENTER, and then LIST followed by ENTER. row ina string in a PRINT statement.
Ok
LIST
Figure 1.9 The LIST command will list all BASIC statements
10 PRINT "XXxKKKK"
stored in memory.
20 PRINT "XXKKKK"
Ok SHON [RCUUININy Pye e 8 gee
10 PRINT "xxxxx" 40 FRINT "xXx xXx"
RUN JO PRINT "“KKKKKR"
KXKKX 60 PRINT "Xk * KKK"
Ok Ok
rsin RUN
10 PRINT "xXxKKxK" XK KK KX
Ok x KKK KK
xX XX
XK KX
The question mark (?) can be used as an abbreviation
XX KK KX
for the word PRINT. Try typing KKK KKK
Ok
? “THIS WILL STILL PRINT”
In the indirect mode, if you type
Figure 1.12 Example of using PRINT statements to print
10 ? “HELLO” your name in block letters.
RUN Ok
LIST
the word HELLO will be printed. Note that if you 10 PRINT" wid) Valassis ininimicisie. iPislsipizis
now type LIST the word PRINT has been substituted 20 PRINT" die aa ssan (Rare ilFPieirie&
20 PRINT" aid! 1alS Fikes FF a
for the question mark. See Figure 1.10.
40 PRINT" VU Asaasss IAS PRPs
On PRN! def RSassis (eirisisizic iFlsieisisies
SVOPRINT Cds Site ses Bis Frito
Figure 1.10 The question mark (?) can be used as a
Oe Tinga Volivolidinlid’ {SSsjsisjS 0 [Sis Fata
substitute for the word PRINT.
80 PRINT"JJJJJJ EEEEEE FF aS #
Ok Qk
eMail iites UN CNP ee TeaN ae RUN
Taihsy (NUE, ep i Ter JJ) SEEEEBEES SSheer reso eis
Ok di (saeco PARP (era PR
ie) Se EY eteegluioly wef (El rie Pie
RUN dof (SSS (aa episim ) Paar
REG we Tissyjass (asap lara
Ok wid! aijdf [SiS ie Talks
LOU F JJJJJJI EEEEEE FF FF
ay ee SPS elaly JJJIJJI EEEEEE FF in
Ok Ok

If more than one PRINT statement is stored in


the IBM PC then, when the program is RUN, all of EXERCISE 1.1
the PRINT statements will be executed in increasing Make the IBM PC print your name in block letters
order of the line number. For example, if you type using the technique shown in Figure 1.12.
space to the left and erases any character that may
LIST AND RUN FUNCTION KEYS
have been located at that position on the screen. For
example, type
LIST and RUN are used so often that the designers
of the IBM PC included function keys that save you PRINT “ABCSEF”
the trouble of typing them! When function key F1 but do not press the ENTER key. Now press the back-
(in the upper left-hand corner of the keyboard) is de- space key 4 times so as to erase the SEF”. Now retype
pressed the word LIST will immediately appear as a DEF” and then press ENTER. The letters ABCDEF
command on your screen. Try it! Now depress ENTER should be printed on the screen. If you wish to erase
and the last statements you entered should be listed the entire line you are currently typing, depress the
on the screen. ESC (escape) key before you depress ENTER. Try
Function key F2 is the RUN key. When this key this by typing
is depressed, it has the same effect as typing RUN
50 THIS IS A MISTAKE
followed by ENTER. Assuming that you have the pro-
gram from Exercise 1.1 still in the computer, depress and then depressing the ESC key. This line should
key F2. The statements from Exercise 1.1 should be immediately disappear.
executed immediately with the same results as before. Suppose you have already pressed the ENTER key
The “prompt line” at the bottom of the TV screen before you notice a mistake. There are a couple of
reminds you that Fl = LIST and F2 = RUN, in case things you can do. You can just type the entire line
you forget. The other function keys will be discussed over again, including the line number. Whenever you
in later sections of the book. You can remove the type a BASIC statement beginning with a particular
prompt line from your screen by entering the command line number, this new statement will replace any previ-
KEY OFF, and get it back with the command KEY ous statement having the same line number. This is
ON. also an easy way to erase an entire line in a BASIC
program. For example, if you type the number 50 and
then press the ENTER key immediately, line 50 will
THE NEW COMMAND be completely erased from the program.
You can also edit a line by using the EDIT state-
Before continuing with other examples using the key- ment. This statement is described in Appendix E.
board, it should be pointed out how you can get rid
of all of the statements that are presently in RAM
in your computer. This is done by typing in the com- STRING VARIABLES
mand NEW followed by ENTER. Try this by entering
the following sequence: As you have seen any sequence of characters enclosed
between quotation marks is called a string. Thus, for
LIST followed by ENTER example, the following are strings.
NEW followed by ENTER “HELLO”
LIST followed by ENTER cee

The first LIST should give a listing of all the statements “THIS IS A STRING”
you presently have in the computer. The second LIST Any character can be included in a string. To the
command should give you nothing but the prompt IBM PC a blank space is just another character when
Ok, which means you have cleared all BASIC state- included in a string.
ments from RAM. The statements cleared in this man- A string can be given a special name and then can
ner are lost forever, unless you retype them. You be referred to by its name. These string names are
should always use the NEW command before you start sometimes called string variables. The name of a string
typing a new program so that statements from your must end with a dollar sign ($). It must also start
last program don’t inadvertently get included in the with a letter and can contain up to 40 characters. The
new one. characters used between the first letter and the $ sign
that ends the name can be letters, numbers or the
decimal point. Thus, the following are valid string
EDITING USING THE BACKSPACE
names.
AND ESCAPE KEYS AS
B3$
The backspace key contains an arrow pointing to the
XRAYS
left — and is located above the ENTER key. When
you press the backspace key the cursor moves one THIS.IS.A.VALID.STRING.VARIABLE.NAMES
Actually, the IBM PC will allow you to use names 30 PRINT A$
with more than 40 characters. However, it uses only 40 PRINT A$
the first 40 characters to identify the string. Thus if 50 PRINT B$
two variable names were 5O and 60 characters long,
60 PRINT BS
but the first 40 characters in each name were the same,
the computer would think that the two names were 70 PRINT A$
identical—even though they aren’t. 80 PRINT A$
The reason for using longer names is just to make This is illustrated in Figure 1.14.
the name more meaningful to the programmer (not
to the computer). However, it is doubtful that any Figure 1.14 Drawing a box using string variables.
programmer would choose to use a 40 character varia- Ok
LIsT
ble name, since this requires a great deal of typing.
10 AB = "KKKKKK"
In choosing a variable name, you must make certain 20 BS = "kX KK"
that the name chosen is not a reserved word. The IBM 20 PRINT At
PC has special names, like RUN and LIST, that cannot 406 PRINT At
a0 FRINT BS
be used for variable names. A complete list of reserved
60 PRINT Bt
words is given in Appendix A. Your variable names 7O FRINT AS
should thus be fairly short, but meaningful, and not 86 PRINT At
reserved words. Shorter names require less memory Ok

to store. RUN
* KKK KK
The equal sign (=) can be used in BASIC to assign KKK KKK
a particular string to a particular string variable or KK xX
name. Thus, for example, you could type* KK KX
KOK KKK
10 A$S=“THIS IS A STRING” OK KKK K
Ok
From now on the name A$ is considered to be the
same thing as the string “THIS IS A STRING.” You
can, for example, print it with the PRINT statement
LINE LENGTH

20 PRINT A$ Each line on the IBM PC screen contains either 40


or 80 character positions (depending upon your partic-
Try this. You should get the result shown in Figure
1213. ular configuration). However, the computer is able to
process up to 255 characters per BASIC statement.
Figure 1.13 Using string variables in a PRINT statement. This means that you can use several screen lines for
Ok any BASIC statement. (If you type more than 255
10 AS = "THIS IS A STRING" characters in one statement the IBM PC will give you
2O PRINT A® a Syntax error when you RUN it.) Thus, for example,
Shs
10 AS = "THIS IS A STRING"
if you are defining a string using a statement such as
20 PRINT Ax 10 AS=“-------
Ok
RUN and you get to the end of the line on the screen, you
THIS IS A STRING just keep on typing. DO NOT PRESS ENTER. The
Ok IBM PC will automatically continue the statement on
the next line. When you finish the statement you must
The box that we drew in Figure 1.11 could be drawn then press ENTER. (Note that characters can be re-
by defining the two strings peated by merely depressing the key and holding it
10 ASHSSe teres? down. Try this in this case by holding down the “-”
20 BS=“** =**? key).
On the IBM PC you can switch from 40 to 80
and then printing these strings in the following order characters per line by entering the command WIDTH
80. To switch from 80 to 40, enter the command
* Some versions of BASIC require you to use the word LET in WIDTH 40.
an assignment statement. Thus, you would write
10 LET A$=“THIS IS A STRING” EXERCISE 1.2
The use of the word LET is optional in IBM PC BASIC. We will Write and run a BASIC program that will print the
not use it. following figures on the screen.
Figure 1.15 Sample screens.
(a) Ok (b) Qk (c) Ok (d) Ok
RUN RUN RUN RUN
x +H 0000 X
x x ## Qa a) XXX
x x Z HHHHHHHHHH ia) (a) KKK
x x : HHHHHHHHHH ia) (a) vee
x x #4 9000 x
x x ## a a) vee
x HHHHHH oO 0 Oe
Ok HHHHHH fa) Q XXX
Ok 0000 Xx
Ok
LEARNING TO.PROGRAM IN BASIC

In Chapter 1 you became familiar with using your vanced BASIC are all similar to the BASIC that is
IBM PC keyboard. We will now begin to look at some found on most microcomputers today.
of the ideas associated with writing BASIC programs. The main advantage of using BASIC is that it is
In this chapter you will simple to use and readily available on a wide range
of computers. For all its simplicity you will find that
1. learn how to use a floppy disk unit to save your
BASIC is quite powerful and will allow you to write
programs,
high performance programs fairly easily. Microcom-
2. learn to use the commands, LOAD, SAVE,
puter versions of BASIC have been expanded so as
CONT, and their related function keys F3, F4 and
to make the writing of programs that produce graphics
FS, output fairly easy.
3. learn to use the BREAK key, There are, however, certain drawbacks to BASIC.
4. learn the general structure of a BASIC program, First of all it is slow. You probably won’t notice this
5. learn to use the statements GOTO, STOP, END, until you try to draw a large picture quickly. The rea-
and REM, and son it is slow is that the IBM PC contains a BASIC
6. learn to use the DELETE command. interpreter in its ROM. This means that each time
you RUN your program the interpreter must decode
and execute each of your BASIC statements one by
one. This takes time.
THE BASIC
PROGRAMMING LANGUAGE
Assembly Language
The programming language BASIC was developed at
Dartmouth College in 1963. The word BASIC stands If you want to really speed up the execution time of
for Beginners All-purpose Symbolic Instruction Code a program you must write the program in assembly
and the language was designed to be easy to learn language rather than BASIC. This is a lower level
and easy to use. Over the years the BASIC language language that the IBM PC can execute directly. The
has been extended and modified by various manufac- “brain” of the IBM PC is a 40-pin chip called an
turers. IBM’s Cassette BASIC, Disk BASIC and Ad- Intel 8088 microprocessor. This chip is shown in Fig-
example, the PRINT statement must be spelled P-R-
I-N-T and a string must be enclosed between quotation
marks. We will look at more details of the PRINT
statement in the next chapter. Semantics refers to what
it is that a particular statement does. For example,
the statement PRINT followed by a string will print
the string on the screen when that statement is exe-
cuted.

Learning How to Write Programs

Learning how to write a program to accomplish a par-


ticular task is the hard part of computer programming.
You must determine what you have to tell the com-
puter in order for the computer to do what you want.
Figure 2.1 The 8088 microprocessor is the ‘brain’ of the You will find that the computer always does exactly
IBM PC. what you tell it to do. However, often what you tell
it to do is not what you think you are telling it to
ure 2.1. It is this chip that can decode and execute do. This will lead to errors that are sometimes hard
an 8088 assembly language program. Any microcom- to find. The best way to avoid many of these errors
puter that uses the 8088 microprocessor can execute is to think through the problem carefully before you
programs written in 8088 assembly language. The Ra- start to write any BASIC statements. Understanding
dio Shack TRS-80 Level II and Level III computers exactly what you want to do is a major step in solving
use the Z80 microprocessor which executes a com- a problem.
pletely different assembly language. The Apple II and It turns out that there are only a few basic rules
Atari computers use a 6502 microprocessor which ex- for telling a computer what to do. Computers like to
ecutes still a different assembly language. We will not do the same thing over and over again. This is accom-
consider assembly language programming further in plished in a computer program by means of a loop.
this book. We will look at a simple loop later in this chapter.
More detailed discussions of loops are given in Chap-
ters 5 and 8. The other thing that computers like to
Structured Programming do is to make a simple choice between two alternatives.
This process of making choices will be described in
You may hear that BASIC is not a very “well struc- Chapter 6. Any computer program can be constructed
tured” language and that other languages such as PAS- by combining loops with the process of making simple
CAL are “better” in some sense. While it is true that choices.
PASCAL almost forces you to write well structured
programs it is also true that well structured programs
can be written in any language including BASIC. In SAVING YOUR PROGRAMS
this book we will try to minimize any bad programming
habits that BASIC might encourage and show you Your IBM PC can be configured to have one or more
how to write good programs in BASIC. floppy disk drives attached to it. We will assume that
you have only one, and that you have made copies
of the DOS diskette that came in the IBM DOS Manual
Learning the Language 46024001. You should use only backup copies of the
DOS diskette and save the master in a safe place. If
There are two aspects to learning computer program- you have not made a backup copy you should do so
ming. The first is to learn a programming language. before proceeding. (See Chapter 3 in the Guide to Op-
This is the easy part. The second is to learn how to erations Manual #6025000 that came with your com-
write programs to accomplish a particular task. This puter.) In this section we will show you how to save
is the hard part. Learning a computer language consists a program on a floppy disk.
of learning the syntax and semantics of the various Insert the DOS backup copy into the disk drive,
statements that make up the language. Syntax refers close the door, and turn on the power. After a short
to the rules for forming the various statements. For period of time you should see the disk drive light come
Figure 2.2 Terminal Output while booting on and hear the read head move as the disk operating
DOS Version 1.1, system software is read into the computer. After the
disk drive light goes out the display on your terminal
should be as shown in Figure 2.2. In computer par-
Current date is Tue 1-@1-1989 lance, we say that the computer has just been “booted.”
Entes sew date:
Once the computer has been turned on, it can be booted
without using the ON-OFF switch by simultaneously
depressing the CTRL, ALT and DEL keys. This is
most easily done by first pressing down the CTRL
and ALT keys with your left hand and, while these
keys are depressed, depressing the DEL key with your
right hand. Now release all three keys. Try this.
The output appearing on your screen will give you
the last current date entered into the computer (see
Figure 2.2a). In response to this, enter today’s date
(for example 6-21-83), followed by the ENTER key.
(If the current date originally output to the screen is
correct, merely depress the ENTER key.) The result
of this action is shown in Figure 2.2b, where the system
has output what it thinks is the current time, and a
request for you to change it, if it is incorrect. Enter
the correct time, e.g. 10:06 followed by ENTER. This
caren’ Bae it peek a tre ane finishes the initialization process and will result in the
Cup pene Se ket ee es screen output shown in Figure 2.2c. (The DOS booting
procedure shown assumes you have DOS version 1.1.
If you have DOS version 1.0, the only difference will
be that the computer will not ask you for the time
of day.)
The output appearing on your screen, as shown
in Figure 2.2c, ends with the prompt A>. This prompt
is put there by the disk operating system (DOS) and
indicates that DOS is ready for a command. If we
wish to write a BASIC program, we must give DOS
a command that will request DOS to turn control over
to the BASIC interpreter. If you wish to use the Disk
BASIC version of BASIC, type in BASIC followed

Figure 2.3 Terminal output after transferring control from


DOS to the BASIC interpreter.

Current date is rus, £,9%5 i986 IBM


jan. Personal Computer
Di. 40 Copurigh t B ee
rene or
Enter new date: 6-21-
Current time is m io utes fees
Enter new time: 10:

i BM perc Computer DOS


mm 1.180 (C)Copyright IBM Corp i192: .

10
by ENTER. If you wish to use Advanced BASIC, example, if you now type LIST you will find that noth-
you must type in BASICA followed by ENTER. As- _ ing gets listed. In order to retrieve your program, you
sume we wish to use Disk BASIC (remember that must load it in from the floppy disk.
Disk BASIC is merely an enhanced version of BASIC To load the program back into computer memory,
that has a few more statements than are present in type
Cassette BASIC). Type
LOAD “NUMBERS”
BASIC
followed by ENTER. The cursor should disappear, the
followed by ENTER. disk drive light will come on and the disk motor will
After a brief period during which a reading of the run. The computer is searching the disk directory for
diskette takes place, the display should be as shown your program. When it finds the program “NUM-
in Figure 2.3. Note that we have the Ok prompt again, BERS” it will be loaded back into the computer. When
which means we are ready to enter a BASIC program. Ok returns to the screen, your program has been com-
Remember: A “A>” prompt means DOS is in control; pletely loaded. You can see the program listing now
an “Ok” prompt means a BASIC interpreter is in con- by typing LIST and you can execute the program by
trol. typing RUN.
Now type in the following program. Function keys F3 and F4 have been programmed
to reduce the amount of typing required to SAVE and
10 A$=“333”
LOAD BASIC programs. When you depress key F3,
20 BS=“666666” SAVE* will immediately appear on the display. When
30 CS$=*999999999” you depress F4, LOAD“ will appear. In either case,
40 - PRINT AS all you have to do to complete the command is to
50 PRINT BS type in the name of the program followed by the last
60 PRINT C$ double quotes (’’).

This program listing and its execution are shown in


Figure 2.4. STOPPING PROGRAM EXECUTION
Suppose you wish to save the program shown in
Figure 2.4 on your floppy disk. To save this program Add the statement
merely type
70 GOTO 40
SAVE “NUMBERS”
to the program shown in Figure 2.4. If the program
followed by ENTER. The blinking cursor should dis- in Figure 2.4 is in the computer memory, then you
appear, and you will see the disk drive light come can add the above statement by simply typing it as
on, and hear the disk motor running. This means that shown. Type LIST in order to see the entire program.
the IBM PC has started to store your program on It should look like Figure 2.5. =
the floppy disk. When it has finished writing your pro-
gram on the diskette the letters Ok and the blinking Figure 2.5 Program to display a continuous sequence of
cursor will return to the screen. three number strings.
Your program is now stored on the floppy disk. Ok
oh
In order to verify this, type NEW, which will clear 10 AS = "BAS"
your BASIC program in the IBM PC memory. For 20 BRB = "466666"
SO UES = EP OOGSOOOs
Figure 2.4 This program prints three strips of numbers. 40 PRINT AS
20 PRINT BS
Ok
60 PRINT CH
JE SEENIE
70 GOTO 40
NBO) 8 ea
Ok
20 BS = "666666"
AG) TEES: See SEAS
CIS hehele
40 PRINT AS The statement
SO PRINT BS
60 PRINT CS 70 GOTO 40
Ok
RUN means exactly what it says. When statement number
70 is executed it simply branches back and executes
646666
statement number 40 again. This is a Joop that contin-
Ol ues indefinitely as shown in Figure 2.6.

11
Figure 2.6 An indefinite loop that prints numbers until you
press the CTRL and BREAK keys simultaneously.
40 PRINT A$ prints three 3s
50 PRINT BS prints six 6s
60 PRINT C$ prints none 9s
70 GOTO 40
Now RUN this program. As you can see the three
strings A$, B$, and C$ are being printed endlessly.
In order to stop this program press the CTRL key
and, while holding down the CTRL key, depress the
BREAK key. Note that you get a BREAK message
as shown in Figure 2.7.

CONT
Figure 2.8 RUN causes the program to start at the
The program shown in Figure 2.5 displays three 3s, beginning.
six 6s and nine 9s over and over again. Each time
the program is RUN it will always start with the three
STOP
3s. This can be seen in Figure 2.8 where the program
was stopped by pressing the CTRL plus BREAK keys The statement STOP can be included in a BASIC pro-
just after displaying the six 6s. Note that the program gram. This will have the same effect as pressing CTRL
starts again by displaying the three 3s. plus BREAK. This can be very useful in debugging
If a program has been stopped, the statement CONT (i.e., finding the errors in) a program that doesn’t work
can be used to continue the program from where it properly. You can just insert a STOP statement and
left off. This is illustrated in Figure 2.9 where the pro- then check what the program has done up to that
gram was stopped just after displaying the three 3s. point. You can then resume execution of the program
Note that after typing CONT the program restarts
by depressing F5, the CONTinue function key.
at the point of the break, rather than at the start of
the program.
Function key F5 is the CONTinuation key. Depress-
END
ing this key after a BREAK has the same effect as
typing in CONT followed with ENTER. Try this by
The END statement is traditionally used to stop a
breaking your program and then depressing FS.
BASIC program at the end of the program. It does

Figure 2.7 Stopping a program by pressing CTRL plus Figure 2.9 CONT causes the program to start from where
BREAK. it left off.

Break in 66
ay

12
not cause a BREAK message as the STOP statement easier to understand. For example, in the program
does. In IBM PC BASIC the END statement is op- | shown in Figure 2.5 you may want to add the statement
tional. As you have seen we have not been using the
END statement in our programs. A BASIC program 5 REM PROGRAM TO PRINT THREE STRINGS
OF NUMBERS
in the IBM PC will automatically stop if there are
no more statements to execute. as shown in Figure 2.10. Note that in Figure 2.10
the remark takes up two lines on the screen.

THE STRUCTURE OF A BASIC PROGRAM Figure 2.10 Use of the REM statement to make remarks
in a program.
Sequence Numbers Ok
LIST
A BASIC program consists of a sequence of BASIC 2 REM FROGRAM TO FRINT THREE STRINGS OF
NUMBERS
statements. Each line of a BASIC program must begin 10 AS = "SAR"
with a sequence number. When the program is exe- 20 BS = "666666"
cuted the statement with the lowest sequence number 20 CH = "999999999"
4QO PRINT At
is executed first. Additional statements are then exe-
SO PRINT BS
cuted in the order of increasing sequence number. 60 PRINT C$
When you write a BASIC program you should in- 70 GOTO 40
crement your sequence numbers by 10. That is, your Ok
program should look like this.
As mentioned earlier any BASIC statement can
10 first statement
use more than one screen line. When you type the re-
20 second statement
mark in Figure 2.10 you must keep on typing when
30 third statement you get to the end of the first line. Do not type EN-
TER at the end of the first line or you will terminate
the statement at that point. You must then start the
next line with a new sequence number and another
REM statement. The apostrophe (the ‘ symbol under
etc.
the ’’) can be used as an abbreviation for REM.
The reason for doing this is that if you later want to
insert a new statement between the second and third
statement you can just type Multiple Statements Per Line
25 new statement
IBM PC BASIC allows you to write more than one
and this new statement will be inserted between state- BASIC statement per line by separating the statements
ment number 20 and statement number 30. If you with a colon (:). By a line we mean the characters
hadn’t left any room between the second and third from the line (or sequence) number to the ENTER,
statements then you would have had to renumber all which may consist of several screen lines. This can
of your statements! be an advantage for a number of reasons. 1) It allows
If you think that you may want to add some new you to group a number of short related statements
statements at the beginning of your program, then it together; 2) it allows you to include remarks on the
would be a good idea to start your program with a same line as a BASIC statement; and 3) it saves some
higher sequence number such as 100 and then continue memory by reducing the number of sequence numbers
with 110, 120, 130, etc. in the program. Only the first BASIC statement on a
line has a sequence number. The remaining BASIC
statements on the line are simply separated from the
REM preceding one by a colon.
There are, however, some disadvantages to writing
A good statement to include at the beginning of your more than one statement per line. If used indiscrimi-
program is a REMark statement. This statement con- nately it can result in a program that is very difficult
sists of the three letters REM. The remainder of the to read and understand. You will not be able to branch
line can then be used for any kind of remark. These to a statement (e.g. with a GOTO statement) that starts
remarks are ignored by the IBM PC when the program in the middle of a line since it will not have a sequence
is executed. Their only purpose is to make the program number. Finally, it is more difficult to insert a new

13
statement between existing multiple statements. You DELETE 40-60
should, therefore, be careful when writing multiple
then statements 40 through 60 will be deleted. If you
statements on a single line.
only want to delete a single line, such as line 50, then
One good use of the multiple statement capability
it is easiest to simply type
is to include remarks that help to tell what is going
on in the program. For example, in Figure 2.11 we
have added three remarks that tell what each PRINT Figure 2.12 Examples of using the LIST statement.
statement prints. Note that a colon (:) is used to sepa-
rate multiple statements on a single line. e, °
iiST
a cs 398= "999999999"
Figure 2.11 Multiple statements on a single line are
separated by a colon (:).
Ol:
eo
= REM FROGRAM TO PRINT THREE STRINGS OF
NUMBERS
LOAAS = "SRS"
20 BE = "666666"
BO C® = "999999999"
40 FRINT AS:SREM PRINT THREES
SO PRINT BS:REM FRINT SIXES
60 FRINT C:REM PRINT NINES
70 GOTO 406
Ck:

More About LIST

We have seen that the command LIST will list the


entire BASIC program that is stored in memory. It
is also possible to list only selected parts of a program.
For example, if you type

LIST 30
then only the line with the sequence number 30 will
be printed on the screen.
You can also list lines 20 through lines 40 by typing

LIST 20-40
If you type

LIST -30
then you will list all of the lines from the beginning
of the program through line 30. If you type Ok

Ee
LI Va)|La @
> ROGRAM TO PRINT THREE STRINGS oF
LIST 30- Nu
1@ AS "333"
228 "666666"
you will list all of the lines from line 30 to the end af
Be
ah "9393999999"
of the program. These examples are shown in Figure
Dale

DELETE

The command DELETE can be used to delete a block


of consecutive statements in a BASIC program. For
example, if you type

14
“address” or name that identifies the seat. These names
correspond to the variable names in a BASIC program.
For example, three different seat names could be A$,
B$, and C$. Each seat would have a different name.
Whoever or whatever is in a particular seat corre-
sponds to the contents of a particular memory location
in the computer. For example, if “JOHN” is sitting
in seat A$, then the BASIC statement

A$= “JOHN”
can be interpreted as meaning ‘put “JOHN” in seat
A$.’ It is very important to clearly distinguish between
the name of the memory location or seat on the train
(A$) and the contents of that memory location or seat
(“JOHN”). See Figure 2.13.
Up to now all of our memory locations have con-
tained strings and have had names that end with a
50 dollar sign. If a memory cell name does not end with
a dollar sign then the computer will assume that the
followed by ENTER. You could accomplish the same memory cell contains a number. The use of memory
result by typing cells containing numbers will be discussed in the next
DELETE 50 chapter.

but this is more work.


If you were to type

DELETE 150-370
then lines 150-370 would be deleted. If there were
no line 150, then the IBM PC would start deleting
lines with the next higher line number. If there were
no line 370, or if neither 150 or 370 are present, then
you will get an Illegal function call error message on
the terminal. In this case nothing is deleted.
If you type
DELETE -30
then all program lines from the beginning of the pro-
gram through line 30 will be deleted.

Memory Locations
and Computer Programs

A computer program is like a train going on a trip.


The seats in the train are like the memory locations
or memory cells in the computer. Each seat has an Figure 2.13 Memory locations are like seats on a train.

15
LEARNING MORE BOUT PRINT

In the first two chapters of this book you have written Addition
short programs that print strings. In this chapter you
will see how the IBM PC can work with numbers If you type
as well as strings. You will find that the IBM PC
PRINT 5+ 3
can serve as a very good calculator.
In this chapter you will learn: the computer will respond with 8. You can use the
question mark as an abbreviation for PRINT. Thus
1. how to use the IBM PC as a calculator,
if you type
2. to write arithmetic expressions involving addi-
tion, subtraction, multiplication, division, and expo- 2.353
nentiation, the computer will also respond with 8 as shown in
3. how numeric values and variables are specified, Figure 3.1. Try it.
4. how to use the comma and semi-colon in a
PRINT statement,
5. to use the TAB function and the LOCATE state- Figure 3.1 Using the IBM PC in the calculator mode.
ment, Ok

6. how to display letters in blinking and reverse


video modes, and
7. some of the built-in functions in the IBM PC.

THE IBM PC AS A CALCULATOR

By using the PRINT statement in the direct mode


of execution you can use your IBM PC as a calculator.
You can add, subtract, multiply, divide, and raise a
number to a power.

16
Subtraction ? 6+12/2+4
Try it. Did it display what you thought it would?
If you type
You should have found that the computer gave the
? 12-5 answer 16. This is because the computer does division
before addition. All computer languages don’t work
the computer will respond with 7 as shown in Figure
this way. For example, the language APL evaluates
3A. Try it.
all expressions right to left. Thus, it would evaluate
the above expression to have a value of 8. (Do you
see why?)
Multiplication In BASIC, arithmetic expressions are evaluated ac-
cording to the following order of precedence:
The symbol for multiplication in BASIC is the asterisk
*. Thus, if you type 1, all exponentiations, /, are evaluated first,
2. all multiplications, *, and divisions, /, are evalu-
23*4
ated next,
the computer will respond with 12 as shown in Figure 3. all additions, +, and subtractions, —, are evalu-
ON)eedMega US ated last.
Within each level of precedence, the expression is eval-
uated left to right. Parentheses can always be used
Division
to change the above order of precedence. In this case
expressions within the innermost parentheses are eval-
The symbol for division in BASIC is the slash /. Thus,
uated first.
if you type
Try to evaluate each of the following arithmetic
? 15/3 expressions and then type them on the IBM PC to
check your results. The answers are shown in Figure
the computer will respond with 5 as shown in Figure
aoe
3.8 Try it.
? 8—3+4/2
23*2—5+8/4
Exponentiation ? 8+1/3
? G+4)*(6—3)
The symbol for exponentiation in BASIC is the caret,
? 20/2/5
/\. The caret is located above the 6 on the keyboard.
Thus, if you want to raise 2 to the power of 3 (2 Figure 3.2 Evaluation of arithmetic expressions on the IBM
cubed) you would type RG:
Ok
? 2A3 ?B-3+4/2
7
and the computer would respond with 8 as shown in
Ok
Figure 3.1. Try it. Note that when the exponent is POK2-S+8/4
an integer, exponentiation is equivalent to repeated
multiplication. Thus,

2A3 = 2*2*2
Ok
° C3S+4)X (6-3)
21
Arithmetic Expressions Ok
20/2/35

The arithmetic operators +,—,*, /, and /\ can be com-
=

Ok
bined in a single arithmetic expression. For example,
if you type Did you guess the correct answer for the last one?
25 ootck Remember that the two divisions are evaluated left
to right so that the correct result is
the computer will respond with 6. What do you think
the computer will display if you type the following 20/2 AQvs
expression? 5 5

17
and not 50

2omea0%si_ -36
2145
2/5 2
-6219
If you want the second result you can type
Examples of fixed point constants are:
? 20/(2/5)
3k
rye:
-8765.92
Note that in the next to last example in Figure
3.2 it is necessary to use the multiplication symbol *. 0.00025
Although (3+4)(6—3) is used to imply multiplication Examples of floating point constants are:
in ordinary algebra it does not imply multiplication
to the IBM PC. Any time you want to multiply any- 3.1E—5 which is a BASIC form for 0.000031
thing on the IBM PC you must use the multiplication -3.1E+5 which is a BASIC form for -310000.0
symbol *. 3.1E5 which is equivalent to 3.1E+5.
3E6 which is equivalent to 3000000.0

DECIMAL CONSTANTS In floating point form note that to put the number
into its fixed point constant form you must move the
In the examples given in the last section, all the decimal decimal point to the Jeft if the exponent is ““—’’, and
constants used were integers. “Integer” is only one to the right if the exponent is “+”.
of three possible forms that decimal constants can take The BASIC notation
in an IBM PC program. We will briefly discuss these 3.1E-5
three forms at this time, note the precision of the num-
bers which can be stored, and indicate the amount is equivalent to the normal mathematical notation
of memory required to store each type. We will also Bix 10-5
give additional examples to illustrate the concepts in-
volved. (The next few paragraphs may appear to be The first form is used in BASIC since superscripts
too “technical” for some readers. However, the con- aren’t present on the keyboard.
cepts involved must be understood before a program- Most programmers refer to fixed point and floating
mer can truly understand how certain answers are ob- point numbers as being “real’’ numbers (which may
tained during the execution of a program.) have fractional parts) in contrast to “integer” numbers
which will never have fractional parts. We will use
the term real number in this sense in this book.
Integer Constants

Integer constants are whole numbers in the range Numeric Precision and
—32768 to +32767. These numbers must appear in Memory Storage Requirements
the program without a decimal point.
Decimal numbers that are integers are stored on the
IBM PC using two bytes of memory. (Remember, in-
Fixed Point Constants tegers must be in the range —32768 to +32767 and
have no decimal point.) A second type of numeric
Fixed point constants are decimal numbers written data storage used on the IBM PC is called single preci-
with a decimal point. sion. This type of storage uses four bytes of memory
to store one number. A decimal constant will be stored
as a Single precision number if it isn’t classified as
Floating Point Constants an integer, and:

* it is written with seven or fewer digits, or


Floating point constants are decimal numbers written * it is written in scientific notation (using an E), or
in Scientific notation, which consists of either an integer
* it is written with a trailing exclamation point (!).
or a fixed point constant followed by an E, followed
by a (possibly signed) integer. Single precision numbers may be output in either fixed
Examples of numbers that are considered to be in- or floating point form with up to seven digits showing.
teger constants by the IBM PC are: Normally, only six of the seven digits are accurate.

18
Examples of constants that will be stored as integers Figure 3.3 Only very large, and very small values are output
are: using scientific notation.
Ok
3 70, 00000810, 125
—2000 9, 963001E-O7
Ok
ml957
SOTO eect dw tks
12008. 3
while the following would be stored in single precision
Ok
form: BeOS hh
« P4AO4 R89
5!
Ok
5.0 P1I2ZS45.6X56789.0
7.010943E+08
-0.5E1
Ok
212356 (because it is > 32767)
If you try to store a larger number you will get an
Note that 5! is the same as 5.0 and is not “‘5 factorial.” Overflow error. Also, any number with a magnitude
A third type of data storage called double precision smaller than
is also used on the IBM PC. We will not use double
precision constants, or variables, in this text. + 2.93874E—39
In reviewing the results given in Figure 3.2 in light will be stored in the IBM PC as zero. Examples of
of our discussion on constants being either of type these are given in Figure 3.4.
integer, or of type single precision (real), it should
be pointed out that the operators “+” and ““—” assume Figure 3.4 There are limits on the size of real numbers
that the two numbers being added or subtracted are that can be stored.
of the same storage type. If the two numbers being Ok
Pabst lSNete:
operated upon are both integer, or both real, the values Overflow
are immediately added or subtracted, and the result
has the same type as the operands. On the other hand, 1.701412E+38
if one of the operands is real and the other is integer, Ok
Pee
SS SNS
the integer is converted to its single precision equiva- oO
lent before the addition, or subtraction, takes place. Ok
In this case the result is left in real (single precision)
form. The operators ‘‘/” and ‘“*”’ assume that both
operands being used in the division, or multiplication,
are of type real. If they are not, the integer values NUMERICAL VARIABLES
are converted to their real forms before the operation
takes place, and the result is left in real form. We have seen that strings such as “JOHN” can be
To illustrate this last point, let’s look at the reason stored in memory cells with names such as S3$. If a
why 8+1/3, which involved arithmetic operations on memory cell name does not end with a dollar sign
three integers, gave an answer of 8.333333. (See Figure then the IBM PC will assume that the memory cell
3.2.) Since ‘‘/” has precedence over “+,” the division contains a numerical value. For example, if you type
was done first. The 1 and 3 are internally converted A=3
from integer form to real form and the real division
2A
gives a result of 0.3333333. The next step the computer
takes is to add the integer 8 to the real number the computer will respond with 3 as shown in Figure
0.3333333. To do this, the computer converts the in- 3.5. Similarly, if you type
teger 8 to the real number 8.0 and adds it to 0.3333333 A=5
getting the answer 8.333333.
B=3
Values are output in floating point form only when
they cannot be output accurately using only 7 digits ? A*B
in fixed point form. Figure 3.3 gives several examples the computer will respond with 15 as shown in Figure
of how the output form varies with the size of the 3.5.
value. Note that the above examples used the direct mode
The largest real number (magnitude) you can store of execution. The indirect mode of execution can also
on the IBM PC is be used as shown in Figure 3.6.
+ 1.701412E+38 The rules for naming numerical variables are the

19
Figure 3.5 Numerical variables can be used in the direct 2. A DEFINT statement must be used at the begin-
mode of execution and in arithmetic expressions. ning of a program. This statement specifies that
Ok all variables in the program beginning with a certain
A= tq letter will be integer variables.
Ok
7A For instance a DEFINT statement of the form

Ok
10 DEFINT I,J,K

A = ay specifies that all variable names beginning with I, Jor K


Ok can hold only integer values. The statement
R= i]
Ok
TAKE 10 DEFINT I-N
13
Ok specifies that all variable names beginning with
I, J, K, L, Mor N can hold only integer values. Integer
Figure 3.6 Use of numerical variables in the indirect mode
variable names should be specified in all those cases
of execution.
where a count is being made in a program, such as
Ok
fs eg the number of times you wish to go around a loop.
10 A = 3 When a real value is assigned to an integer variable,
20 B= 3S the fractional part of the real number is rounded to
20 PRINT AXB
Ol:
the nearest integer upon assignment. The DEFINT
RUN statement, the %-extension, and the effect of rounding
ilbe on assigning a real value to an integer variable are
Ok all illustrated in Figure 3.7.
same as for string variables except that there is no
Figure 3.7 Use of integer variable names and the effect
dollar sign at the end. That is, each name can contain
of round off on assignment.
up to 40 characters; the first character must be a letter
Ok
while the others can be letters, digits or the decimal rou
point. Thus, for example, the following are valid names LOO DER TINT Sh x a
for numerical variables. 15 REM ALL VARIABLES IN THIS FROGRAM
THAT BEGIN WITH THE CHARACTERS I
Q OR J WILL BRE "INTEGER" VARTARLES

A3 2O TKE = 7.464
PAO) TetasdUiNf Isls:
XRAY.2 40 JOKER = 13,3
SPEED 20 PRINT JOKER
60 ZIFPFERZ = JOKER + IKE +8.¢2
VELOCITY 6a REM ZIFFERAZA IS ALSO AN INTEGER
VARIBALE SINCE IT ENDS WITH A %
PADS Ted MINIT 978 Ue etl re
B80 ACE = 7.64
NUMERICAL VARIABLE TYPES 90 PRINT ACE

In the BASIC programming language if a variable


name doesn’t end in a “$” sign, the computer knows
that the variable will hold only numeric values. It is
further assumed that the type of value to be stored
there will be a real number. If the programmer knows,
or wishes, that only integers be stored under a particu-
lar variable name, then the programmer must specify
this fact in one of two ways.
CONTROLLING PRINTED OUTPUT
1, The name used must have a percent sign (%)
appended to it, e.g.
When you use the PRINT statement you can control
A% where on the screen the output is printed by using
SPEED.3% commas, semi-colons, and the statements PRINT TAB
A2% and LOCATE.

20
Comma Figure 3.10 Using the comma tab with strings.
Ok
The comma has a special meaning in BASIC. It can- Seay stan 8/2 Ost le7
ABCD EFGH
not be used in the customary way to separate every
Ol:
three digits in a large number. For example, in BASIC eS afl 7ASLoa "Yes4"
the number 3,526 mustbe written without a comma 123456789 1234
as 3526. Ok
P"L2S4S679901 2345", "1234"
Try printing the number 3,526 with the comma
L2D456789901 2245 24
by typing Ok

2? 3,526 prior to printing a second string. Also note that strings


as shown in Figure 3.8. Note that instead of printing begin printing in column number 1 and at the start
one number the computer thought you wanted to print of tab position 15.
the two numbers 3 and 526. In a PRINT statement The comma can be used in PRINT statements to
separate strings from numerical variables as shown
Figure 3.8 The comma acts like a tab in a PRINT statement. in Figure 3.11. Note that after the string “A=” is
Ok
printed on line 30 the comma causes a tab to column
Ro, ae number 16 before the value of A (3) is printed. The
Ss S26 third comma in line 40 causes a tab to the next line.
0 kk This looks a little awkward. This gap can be eliminated
by using a semi-colon instead of a comma.
the comma is used to move to the next fixed tab posi-
tion. These fixed tab positions are located in columns Figure 3.11 Using the comma to separate strings
and numerical variables.
1,15 and 29 where the screen columns are numbered
Ok
1 through 40. If you try to PRINT more than three sd
numbers on a line, separated by commas, the extra 10 A Sy
numbers will be printed on the next line as shown in 20 B= doi 4
Figure 3.9 (example 1). Note that a blank space has 30 PRINT "A=",A
40 PRINT "A=",A,"B IS",B
been left in front of each number for the sign. This Ob
can be seen in the second example of Figure 3.9, where RUN
some of the numbers have negative signs. If single A= 3
precision numbers cannot be displayed with seven or A=
£4
a Es 9

less digits, the value is converted to scientific notation Ok


as shown by the third example of Figure 3.9. One or
more commas can precede a number in order to skip
tab positions as shown:in the last example of Figure
3:9. Semi-colon
The comma can also be used with strings as shown
in Figure 3.10. Note that up to 13 characters can be
If numerical values are separated by semi-colons in-
included in a string before a tab position is skipped
stead of commas then only a single space (plus a space
for the sign) is inserted after each value as shown in
Figure 3.9 Examples of using the comma as Figure 3.12.
a tab. When used with strings the semi-colon leaves no
blank spaces between two strings as shown in Figure
vine 2 B
Figure 3.12 Using the semi-colon to separate numerical
Ok
values.
Pe OVEN ie ogGees Ok
re 66 ay Sige
ss tear

Ok
FO, OOOOOORA, 4 44
8.8E-O7 hq}
Ok Ok
7, AS 211:22:3
gi

Oh:

21
Figure 3.13 The semi-colon leaves no blank spaces Figure 3.15 The function TAB(18) will tab to column 18.
between strings. Ok (a)
Ok cirsn
SeARED Ss EF GH" Hom (ss
ARCDEFGH 20 PRINT TARC1&8); PREEEOY
Ok Ok

3.13. When combining strings and numerical variables


the semi-colon can be used to eliminate unsightly gaps
as shown in Figure 3.14. Note that if the value of B
is negative then you may want to include a blank space
at the end of the string ““B IS” in line 30 of Figure
3.14b in order to leave a space before the number.

Figure 3.14 Using the semi-colon to separate strings and


numerical variables.
OK
lSih
10 A aa
20 #8 4
20 PRINT "B="5A

PRINT "A="5A, "ER Ie yl

= 3 BE Is 4
Figure 3.16 The TAB function can be used
to separate printed output.
(b) Ok
Ok
LDS IP
ERIN) 21979: SHAR ClO SStoses
19 A 3
LOTS. 1980
20 &B oil
q -4
SO PRINT “A=":A Ok
is =|
40 PRINT "A="sA,"R IS
Qk
must be between 1 and 255. If the value of X is less
RUN than the current column of the cursor on the line,
A= then the TAB function moves to column X on the
A= &
te
fj im
next line. Values of X greater than 40 will TAB to
Ok
succeeding lines on the screen.

TAB LOCATE Line, Column

Whereas the comma can be used to tab to the next Sometimes you may want to print something at a par-
fixed tab position on a line (1, 15 or 29) the TAB func- ticular location on the screen. This can be done using
tion can be used in a PRINT statement to tab to any the LOCATE statement. In the text mode the screen
position on a line. For example, PRINT TAB(13) contains 25 rows, with 40 (or 80) character positions
will move the cursor to column number 13 on the on each row. The rows are numbered 1 to 25 from
line. As an example, suppose you want to print the top to bottom, while the columns are numbered 1 to
word HELLO near the top center of the screen. The 40 from left to right as shown in the layout in Figure
program shown in Figure 3.15a will do this. In line 3.17. The upper left-hand corner is position line 1,
10 the statement column 1, and the lower right hand corner is position
line 25, column 40. Although normal BASIC programs
CLS will not write on line 25 (the prompt line) you can
will clear the screen. The PRINT statement in line write on this line through use of the LOCATE state-
20 TABs to column number 18 and then prints the ment.
word HELLO. The statements
Figure 3.16 shows how the TAB function can be LOCATE L,C
used to separate the strings “1979” and “1980”. The
PRINT “STRING”
use of the semi-colon following the TAB function is
optional. will print a string on line L starting in column C.
When using the function TAB(X) the value of X The program shown in Figure 3.18a will print the

22
Figure 3.17 Screen layout for using the LOCATE statement. message given in Figure 3.17 as shown in Figure 3.18b.
Column Number Note that the purpose of the LOCATE statement is
to move the beginning point for the following PRINT
statement to a given spot on the screen. The values
L and C in a LOCATE L.C statement can be either
integer constants, or arithmetic expressions that yield
integer values. If either L or C yield values that give
a location “off the screen” an illegal function call error
will result when the statement is executed. If either
L or C is omitted, then the current value for that
WELCOME
(eo)
ine)
»
-_a
parameter will be used. For instance, if statement 60
in Figure 3.18a were followed by the statements
10 TO: THE 65 LOCATE ,28
Number
Line
67 PRINT “CHECK”
15 IBM PC the word CHECK would be put on line 16 starting
at column 28. After the PRINT statement in program
line number 60 has been executed, the BASIC inter-
preter automatically moves the cursor to the beginning
20 of the next line on the screen. This would be screen
21 line 16 and column 1 in this case. The LOCATE ,28
statement does not change the line position, but does
22
change the column position to 28. This is illustrated
23 in Figures 3.19a and 3.19b.
24

25
Figure 3.19 The LOCATE statement may have missing
parameter values.
Figure 3.18 The LOCATE statement can be used to print Ok (a)
a string anywhere on the screen. Sasi
Ok ay LEYS
LIST IMG), mea AS ete) Lis,
5 CLS 7a ol0 0D
AO Ce be cre 1s KO) LAYESgles) NG) 5 lear
20 PRINT “WELCOME" 40 FRINT "TO THE"
SO LOCATE 10,15 wa) (LABIGVAV IS aeetig alten
40 PRINT "TQ THE" COM REC nabiti rae
50 LOCATE 15,15 fate (sHEAyils) 9 7
6O PRINT "IBM FC" 67 PRINT “CHEER!
7O END 70 END
Ok Ok

WELCOME WELCOME

TO THE

23
CHANGING THE SCREEN BACKGROUND mC
AND CHARACTER COLORS CREEN G,1: COLOR 8,6,2
SDs
Ae es
Up until this point, the background color on your
screen has been black and the foreground color (the
color of the characters) has been white. The actual
colors on your screen may have varied from black
and white, depending upon how the color and intensity
knobs are adjusted on your color monitor.
IBM PC BASIC allows you to change the back-
ground color to any one of eight colors, and the fore-
ground (character) color to any one of sixteen colors.
The color for the border around the outside edge of
the screen can also be made different from the back-
Mus
Figure 3.20 Screen after entering the statement COLOR
ground color. (The border is referred to as the overscan
8,6,2 followed by a REM statement.
area.) The statement that allows you to do these things
is the COLOR statement. colors as white and black, but you wish to put a red
The general form of the COLOR statement is border around it, type
COLOR foreground, background, border COLOR ,,4
where foreground, background and border are integers, followed by ENTER. Since the first two arguments
or integer expressions, that represent the color codes in the color statement are omitted, the foreground and
according to the following restrictions: background colors won’t change, but the border will
foreground: color code value 0 thru 15, change to red (4). Try it.
background: color code value 0 thru 7, To get the background back to black enter
border: color code value 0 thru 15. COLOR ,,0
The color code numbers are chosen from the following
Experiment with different colors. Note that once
table.
you have set the foreground and background colors,
everything typed in after that time will use that color
O—Black 8—Gray scheme. If you omit the third number in the COLOR
1—Blue 9—Light Blue
statement, the border will remain the same color.
2—Green 10—Light Green
3—Cyan 11—Light Cyan If you should set the foreground and background
4—Red 12—Light Red colors to the same value then everything you type in
5—Magenta 13—Light Magenta will be invisible! Try this by entering
6—Brown 14—Yellow
7—White 15—High-intensity white COLOR 7,7
Now type something. You will find that all you
To try this do the following. In the direct mode, enter
get is a white square for each character entered. This
the statements
is really a white character on a white background,
SCREEN 0,1 : COLOR 8,6,2 which is invisible. To get out of this mode you can
either reboot the system, or type
The SCREEN 0,1 statement is required to enable the
use of color, and will be discussed at length in Chapter COLOR 7,0,0
7. The COLOR 8,6,2 statement should make the back-
followed by ENTER. The computer will accept this
ground brown (6), the foreground gray (8) and the
statement, even though you can’t see it on the screen
border green (2). (You may have to adjust the color
as you are typing it!
knobs on your color monitor to obtain these colors.)
See Figure 3.20. Type in a few characters to make
sure they are gray on a brown background. To return REVERSE VIDEO
the screen to its white on black mode type AND BLINKING CHARACTERS
COLOR 7,0,0
Reverse video and/or blinking characters are easy ef-
followed by ENTER. Try this. fects to generate on the IBM PC using the COLOR
If you wish to leave the foreground and background statement. These are done as follows.

24
Blinking characters: To make characters blink, 2. COLOR 16,7 sets the screen to a black, blinking
merely add 16 to the color code used as the foreground foreground (0+16) and a white (7) background.
code in the COLOR statement. For example 3. The first LOCATE statement followed by
COLOR 23,0 PRINT “HELLO” will print the word HELLO
near the middle of the screen. This word will be
or
in blinking, inverse video mode.
COLOR 7+16,0 4. The COLOR 0,7 statement will leave the fore-
ground and background colors as before, but remove
will set the foreground to blinking white (7+16) and the blinking option.
the background to black (0). This means that all char-
5. The second LOCATE and PRINT statements
acters displayed after this point will be blinking white
will cause the word THERE to be printed on screen
characters on a black background. Try this by entering
line 20. This will be in inverse video, but not blink-
COLOR 23,0 and then typing a few characters.
ing.
Reverse Video: Reverse video is obtained by picking
a light background color and a dark foreground color. When you run this program the output should be as
As an example, enter shown in Figure 3.21b.
COLOR 0,7
Everything you type in now will have a white back-
ground with black characters. SOME BUILT-IN FUNCTIONS
To illustrate the programming techniques involved
in blinking and reverse video, look at the program The IBM PC has a number of built-in functions that
given in Figure 3.2la simplify many calculations. You may use any of these
When this program is executed the following actions you care to in your programs.
will take place:
1. The screen is cleared.
The functions ABS, INT,
FIX and SGN
Figure 3.21 A program that generates both blinking and
inverse video output. The absolute value of a number is the magnitude of
a number without regard to its sign. The absolute value
LIST of a number can be found by using the built-in function
10 CLS ABS(X). Thus, for example, if X = —7, then the value
20 COLOR 14,7 of ABS(X) will be 7.
30 LOCATE 10,18
40 PRINT "HELLO" The value of the function INT(X) is equal to the
50 COLOR 0,7 integer part of X, and returns the largest integer that
60 LOCATE 20,18 is less than or equal to X. Thus, if X = 3.25 then
70 PRINT "THERE" INT(X) is equal to 3. If X = —3.25 then the value
Ok of INT(X) will be —4.
IBM PC BASIC has a function FIX(X) whose value
is the truncated, or whole number, value of X. Al-
though this may seem to be the same as INT(X) it is
different for negative numbers. For example,
FIX(—3.25) will have the value —3 while INT (—3.25)
will have the value —4.
The function SGN(X) can be used to determine the
sign of a number. It can have the following three
values:

+1 if X>0
SGN(X) = 0 if X=0
—1 if X<0

Examples of using ABS, INT, FIX and SGN are


shown in Figure 3.22.

25
Figure 3.22 Examples of finding the (a) absolute value, ABS, The function RND(X) will return a pseudo-random
the integer part, INT, and FIX and (b) the sign, SGN, of a number between 0 and 1. Each time RND(100) is
number.
called it produces a different number between 0 and
(a) Ok
1. Note that each time the program is run, you get
?TARS (-3, 2)
J ak the same sequence of “random” numbers. Actually,
Ok you will find that if you turn your computer off and
RINT.
CaS ee) then back on and rerun the program in Figure 3.23,
Qk
you will obtain the same set of “random numbers.”
ZINT (-3. 2) Additionally, you will find that you get the same set
—-4 of random numbers with any positive argument for
Ok X in RND(X). For instance, replace RND(100) by
Shp Ua eee)
RND(§) in Figure 3.23 and you will get the same se-
Ok quence when the program is run. This is because the
function RND uses a “‘seed” that determines the initial
(b) Ok random number that is subsequently generated. This
SGN C3. 2) “seed”’ is set to the same value each time a program
1
Ok
is run. Therefore, the first time you call RND(100)
*SGN(—3,2) in a program you will always get the same “random”
~1 number.
Ok _ This is not a good state of affairs unless you always
7 SGN (O)
i)
want to deal the same bridge hand each time you run
Ok the program. You need some way to change the “seed.”
You can do this in two ways on the IBM PC. The
first is by calling the RND function with a negative
Random Numbers argument. For example, if you add the statement
5 X=RND(—10)
In many programs, particularly game programs, it is
useful to be able to generate random numbers. These to the above program, then you will generate a different
can be used to simulate dealing cards, rolling dice, sequence of random numbers. However, you will al-
or creating other unpredictable results. BASIC has a ways generate the same sequence following the execu-
built-in function called RND that makes generating tion of statement number 5 as shown in Figure 3.24.
random numbers easy.
Type the following program and run it twice as
Figure 3.24 The function RND(—10) produces a particular
shown in Figure 3.23. seed.
10 ? RND(100) Ok
STSai
20 ? RND(100) o xX = RND(-10)
30 ? RND(100) 10 PRINT RND(100)
20 FRINT RND(100)
20 PRINT RNDCLOO)
Ok
Figure 3.23 The function RND(100) produces a random RUN
number between 0 and 1. 5 eratestat
Ok » 794ROR4
ErSth » 4955937
10 FRINT RND(100) ia
20 PRINT RND( 100) RUN
20 PRINT RND(100) A aihaiveyekeyihra
Ok 2 /P4SB624
RUN »AQ6S9S7
Ok
» 6291626
» 1948297
Pee Oke Ar he)
Ok A different negative argument will produce a differ-
RUN ent seed and therefore a different random sequence
26291626
as shown in Figure 3.25. Thus, if you know what nega-
» 1948297
26205799 tive number is used in RND(—X) you will, in principle,
Ok know what sequence of “random” numbers will follow.

26
Figure 3.25 The function RND (—25) produces a different Figure 3.26 Use of RANDOMIZE function to change the
seed. seed for RND(X).
Qk Ok (a)
Ee GSt hr Les f
3 xX = RND(-25) 2 RANDOMIZE 68
10 PRINT RND(100) 10 FRINT RND( 100)
20 PRINT RND(100) 20 PRINT RND(100)
=0 PRINT RND(100) 30 PRINT RND(100)
Ok Ok
RUN RUN
oSekapete
(3Caer . 1807458
eu7o61i24 » INN956S
- 1528437 » 7670702
Ok Ok
RUN RUN
oiejsea) hate . 1807458
23756124 » JO09865
2 1528437 » 7670702
Qk Qk

Ok (b)
A second method to change the “seed” is through Leiteylf
the built-in RANDOMIZE function. This statement = RANDOMIZE
has two forms 10 PRINT RND(100)
20 FPRINT RND(1O0)
20 PRINT RND(C1OO)
RANDOMIZE Ok
RUN
and Random number seed (-32768 to 32767)? 69

RANDOMIZE N , 1807458
25009565
where N is an integer constant, or expression, with a » 7670702
value between —32768 and +32767. Each time this Qk
function is called, a new seed is generated. The seed RUN
Random number seed (-32768 to 22767)? 23
generated depends upon the value of “N”’. If “N” is
not given in the statement, BASIC will suspend opera- 5 BhEES (2)
tion when the function is called and ask for a value = 7851209
for N by displaying the message » 4489519
Ok
Random Number Seed (—32768 to 32767)?

At this point you must enter a value for N. Figure used as N with the RANDOMIZE function. This can
3.26a and Figure 3.26b show examples of using the be done by using the statement
RANDOMIZE function with N included, and not in-
5 RANDOMIZE VAL(RIGHTS(TIMES,2))
cluded, in the program. Note that when the value for
N ended up the same in each program (68), the same in your program. The sequence VAL(RIGHT$
sequence of random numbers were generated in each (TIME$,2)) takes the right 2 characters from the
case. It would be useful if you could introduce more string TIMES and returns its integer value. This value
“randomness” into the selection of a seed and therefore will be in the range 0 to 59, and will change each
be able to get different “random” numbers every time. second. Thus, if you use this statement in the program
There is an easy way to do this if you are using either in Figure 3.26 you will generally get a different set
Disk or Advanced BASIC. The function TIMES re- of random numbers each time the program is run.
turns a character string that is in the form hh:mm:ss Try it. The functions VAL and RIGHTS are discussed
(hours, minutes, seconds). This value gets incremented in detail in Chapter 12, and will not be discussed fur-
once every second. Therefore, if you were to print this ther at this point.
value by typing

?TIMES
Square Root
you would get a different string each time. Try it! In
order to use this string for a seed number, it must The square root of a number can be found by using
be converted to an integer in some manner and then the BASIC function

27
SQR(X) Xen Ss radians
R
where X is a positive number. For example, to find ”
the square root of 16, type x 1 radian = angle for which S= R
? SQR(16) 57.3 degrees
as shown in Figure 3.27a. To find the hypotenuse,
R, of the right triangle shown in Figure 3.28 you could a radians = 180 degrees
use the program shown in Figure 3.27b. 7 3.141593
Figure 3.29 Definition of a radian.
(a) Figure 3.27 Use of the square root function, SQR.
Ok
amples of using the trigonometric functions are shown
?SOR (14)
4 in Figure 3.30.
Ok

Figure 3.30 Examples of using the trigonometric functions


(b) Ok SIN, COS, TAN, and ATN.
eatcsils
10 X = 3 Ok
20 Y = 4 FI = 3.141592
=O Rn = SER GXS2 + Y°2) Ok
ACW rai atiie ive Ge NUSE en EOWALS iG] wk
®SIN(4SxXF 1/180)
» 7071068
Ok Ok
RUN COS (60*kF 1/180)
27000001
hHE AYPOFENUSE IS EB@UAE TO 3
Ok Ok
STAN CGOXPT/180)
Hy REOetint
Figure 3.28 Finding the hypotenuse of a right triangle. Ok
SATN CS)
1,107149
Ok

R= \ x2
+Y?
Natural Logarithm
and the Exponential Function

Consider the equation

vires
In this expression x is called the logarithm of y to
Trigonometric Functions
the base b and is written

x = logpy
The IBM PC contains the following built-in trigono-
If the base b is equal to e = 2.718281 . . ., we say
metric functions:
that y is the exponential function y = e* and x is
Computer function Value of function the natural logarithm of y:
SIN(X) sine of X
COS(X) cosine of X
x=Iny
TAN(X) tangent of X
In BASIC ex can be computed using the function
ATN(Y) arctangent of Y
EXP(X), and In x can be computed using the function
In the above expressions, X is a numeric constant, LOG(X).
variable, or expression that represents the value of an The following properties of logarithms are illus-
angle in radians. The value of ATN(Y) is expressed trated in the examples shown in Figure 3.31:
in radians in the range £1.57, and Y is a numeric
constant, variable, or expression. LOG(A*B) = LOG(A) + LOG(B)
The definition of a radian is shown in Figure 3.29. LOG(A/B) = LOG(A) — LOG(B)
To convert degrees to radians, multiply by 7/180. Ex- LOG(AAK) = K*LOG(A)

28
Figure 3.31 Illustrating properties of logarithms. Note that In(e) = 1 (try typing ? LOG(2.718281)).
Ok Ok In order to see how long this doubling time is type
7LOG (3x4) PGi nr a)
2.484907 2.748872 ? 100*LOG(Q)
Ok Ok
?PLOG (3) +LOG6 (4) PoakLOG CS.) as shown in Figure 3.32. We therefore see that the
2.484907 Wega Ahi doubling time is approximately 70 divided by the per-
Ok Ok centage growth rate, or
PIS BIE Se)
1.504077
Ok
FLO Gy) SS
-LGGt2) Thus, for example, a 10% inflation rate will double
1.504077 prices every 7 years!
Ok

When the rate at which a quantity grows is propor-


tional to the amount of the quantity then we have USER-DEFINED FUNCTIONS
exponential growth. The amount of money in a savings
account that is compounded continuously grows expo- Sometimes it is convenient if you can define your own
nentially. Thus D dollars invested at P percent annual BASIC function. For example, suppose you want to
interest compounded continuously will yield X dollars calculate the area of a circle for different values of
after T years where the circle radius. You can define a function FNA(R)
that is equal to the area of a circle of radius R using
X = DePT/ 100
the DEF FN statement as follows.
For example, to find the amount of money you would 5 PI = 3.141593
earn in 7 years by investing $3000 at 9.5% interest 10 DEF FNA(R) = PI*RA2
compounded continuously, type
Later in the program any reference to the function
? 3000*EXP(9.5*7/100) FNA(R) will cause the expression PI*R/2 to be calcu-
as shown in Figure 3.32. lated. For example, the statement
Note that the answer is more than $5833 or almost 20 PRINT FNA(3), FNA(S5)
double your original investment. A characteristic of
exponential growth is a constant doubling time Ta. will print the areas of circles of radius 3 and 5. This
From the above equation for X we see that X will example is shown in Figure 3.33.
be equal to 2D in the time Ta where
Figure 3.33 The defined function FNA(R) computes the
area of a circle of radius R.
or Ok
LSS
i ePTq/100 o PI = 3.141593
10 DEF FNAC(R) = FIRS
Taking the natural logarithm of both sides of this equa- 20 PRINT FNACS),FNACS)
tion and using the third property of logarithms illus- Ok
trated above we obtain RUN
28.27424 78.53983
In(2) = PT4/100 In(e) Ok

= PT,/100
The general form of the define function statement
or
is
pagete
100 In(2
DEF FNuame (arglist) = expression
The name can be any valid variable name. This name,
Figure 3.32 Examples related to the exponential function. preceded by FN, becomes the name of the function.
Ok The type of the function (integer, real or string) is
PZOQOOKEXF (9. S%7/100) determined by the last character in the name of the
S8235,472 function. If the last character is a $-sign, the function
Ok
P1O0x*xLOG (2)
will return a string value; if the last character is a
69, 21471 %-sign, the function will return an integer value; any
Ok other last character will cause the function to be of

29
type real. The expression can be any expression con- Use the IBM PC to evaluate the following expressions:
taining constants and variables that results in a value (@ 0.5
that is compatible with the type of the function being (a) X= (a= )
evaluated. The arglist is a list of one, or more, variable
names separated by commas. These variables will be _ A(B—-C)
replaced by values when the function is called. aaa D(B4—1)
2 Aer B)s
EXERCISE 3.1 he Sie aes
Let the variables A, B, C and D have the following
values:
(d) R=+/(A+B)/(D—A)
© se eA =ec
A=2, B=3, C=4, D=5

30
ENTERING DATA
FROM THE KEYBOARD:
LEARNING ABOUT
INPUT AND INKEY$

In earlier chapters of this book you have learned how When the first INPUT statement above is executed
to use the PRINT statement to make the IBM PC the computer will print a question mark and then wait
output various forms of data on the screen. In this for you to enter some numerical value from the key-
chapter you will learn how to make the computer ac- board. When you press the ENTER key the value
cept various forms of data that you type on the key- that you typed on the screen will be stored in the
board. You do this by using the INPUT statement memory cell R. The next statement in the BASIC pro-
in a BASIC program. You will learn how to use this gram will then be executed.
INPUT statement by studying the following sample When the second INPUT statement above is exe-
programs: cuted the computer will expect you to enter two numer-
ical values, separated by a comma. If you press EN-
1. add two numbers,
TER after entering only one value, the computer will
. compute the area of a rectangle, print out the message Redo from start and wait for
. compute the area of a circle, you to enter both values. These two values will then
. calculate gas mileage, be stored in the two memory cells A and B.
. display your name and address, and The third form of the INPUT statement shown
above will print the message ENTER 3 VALUES fol-
An
Pwr
make sounds with the IBM PC.
lowed by a question mark and the blinking cursor.
The computer will then wait for you to enter three
THE INPUT STATEMENT values separated by commas. These three values will
then be stored in the three memory cells X, Y, and
The INPUT statement can only be used in the indirect Z. You should always prompt the user so that he or
mode of execution. The following are valid forms of she will know what to enter. This can be done either
the INPUT statement: as shown in the third example above, or by using a
PRINT statement just before the INPUT statement.
10 INPUT R The fourth form of the INPUT statement shown
10 INPUT A,B above will store whatever you type on the screen in
10 INPUT “ENTER 3 VALUES”; X,Y,Z the string variable NOW$. You do not normally need
10 INPUT NOWS to type the quotation marks when entering a string

31
with the INPUT statement. (See Figure 4.7 for an This program will continue to ask you for two more
exception to this rule.) numbers. The only way to stop the program is to
The use of the INPUT statement will be illustrated BREAK it, by simultaneously depressing both the
in the following sample programs. CTRL and BREAK keys.
You should try experimenting with this program
to see how it behaves. Study the program carefully
SUM OF TWO NUMBERS and make sure you understand what every statement
does.
Figure 4.1 shows a listing and sample run of a program
that will add two numbers entered from the keyboard
and display the sum. You should type in this program AREA OF A RECTANGLE
and run it.
Lines 20 and 25 print the message ENTER 2 NUM- Figure 4.2 shows the listing and a sample run of a
BERS SEPARATED BY A COMMA. Line 30 prints program that computes the area of a rectangle where
a question mark on the next line and then waits for the lengths of the two sides are entered from the key-
you to enter two numbers. In the first example after board. You should type in this program and run it.
RUN the two numbers 5 and 9 were entered from
the keyboard. Line 40 then prints the value stored in
A (5) followed by a plus sign, followed by the value Figure 4.2 Sample program to calculate the area of a
stored in B (9), followed by an equal sign, followed rectangle.
by the sum A+B (14). Line 50 is a PRINT statement ma ‘a)
with nothing following the word PRINT. The only [Belcan
purpose of this statement is to skip a line on the screen. 10 REM FROGRAM TO COMPUTE TWrte
20 REM AREA OF A RECTANGLE
Line 60 causes the program to branch back to line
SO) INN) ISIN ISIE 22 GOSS oC. Vy
20 which asks for another two numbers to be entered. 40 PRINT "THE AREA OF A RECTANGLE"
In the second example following RUN the value SO) (TARGUN DS SMa) Salas, Ue
8 is entered for the first number. But then the ENTER SODENINT Xs eANDy Uy
70 FRONT UTS ERAUAL TO oe xXoKy
key was pressed. Note that the IBM PC responds with
80 PRINT
Redo from start asking you to enter both numbers. 90 GOTO 20
In this example 8 and —3 were then entered. Ok

Figure 4.1 Sample program to add two numbers. Ok


RUN
(a) Ok
Ei Sil ENTER 2 SIDES=. 4,a
10 REM FROGRAM TO SUM TWO NUMBERS THE AREA OF A RECTANGLE
2060 PRINT "ENTER TWO NUMBERS" WITH SIDES 4 AND &
25 PRINT "SEPARATED BY A COMMA" IS EQUAL TO 20
30 INFUT A,B
40 PRINT Ag"+"3B3"="sAt+KR ENTER 2 SIDES? 4,
SO PRINT THE AREA OF A RECTANGLE
60 GOTO 20 WITH SIDES 6 AND 90
Ok IS EQUAL TH 0

(b) Ok ENTER 2 SIDES?


RUN
ENTER TWO NUMBERS
SEPARATED BY A COMMA The main difference between this program and the
75,9
5+ 9 = 14 previous one is that the prompt message is included
in the INPUT statement in line 30. Note that when
ENTER TWO NUMBERS you do this, the question mark follows the prompt
SEPARATED BY A COMMA
ks) message and the cursor remains on the same line as
Reda fram start the message. Thus, you enter the data on the same
Glass line as the prompting message.
84-5 = 5S
Note that in the second example after RUN the
ENTER TWO NUMBERS ENTER key was pressed after the comma had been
SEPARATED BY A COMMA typed. This caused the computer to assign a value of
zero to the numerical variable Y.

32
AREA OF A CIRCLE . Sage Redo from start, after which the value 6 was
entered.
The area of a circle of radius r is given by In the third example after RUN a value of 2.5E19
was entered. But this results in a value of the area
area = ar? A that is larger than 1.701412E38 and therefore the
where 7 (Pi) is approximately equal to 3.141593. Fig- message
ure 4.3 shows the listing and a sample run of a program Overflow
that computes the area of a circle whose radius is en-
tered from the keyboard. You should type in this pro- is printed indicating that the overflow occurred in the
gram and run it. calculation of the area A. The value output is the larg-
This program shows that the PRINT statement in est possible value the IBM PC can output, and is in
line 20 and the INPUT statement in line 30 behave error, due to the overflow. (See Figure 3.8 for an exam-
the same way as the single statement ple of overflow error.)

30 INPUT “ENTER A RADIUS ”; R


The cursor is displayed on the same line as the message. GAS MILEAGE
This is because the PRINT statement in line 20 ends
with a semi-colon which always leaves the cursor at The program shown in Figure 4.4 computes gas mile-
its present position. When a PRINT statement does age in miles per gallon (MPG). The odometer (the
not end with any punctuation then the equivalent of device that displays the mileage on the dashboard)
an ENTER is inserted at the end of the PRINT state- reading at the last fillup is stored in memory cell M1
ment. in line 25. The odometer reading at the present fillup
Line 35 calculates the area of the circle. The value is stored in memory cell M2 in line 35. The number
of PI has been defined in line 15. of gallons it takes to fill the tank is stored in memory
Note that in the second example after RUN two cell GAL in line 45. The total miles traveled since
values, 6 and 3, were entered. But the computer was the last fillup is equal to M2 — M1. Therefore, the num-
expecting only one value. It therefore printed the mes- ber of miles per gallon is given by (M2 — M1)/GAL.
This is calculated in line 5O and stored in the memory
Figure 4.3 Sample program to calculate the area of a circle. cell MPG. It is printed on the screen in line 60.
(a) Ok
ECS;
Figure 4.4 Program for computing gas mileage.
9 REM FROGRAM TO COMPUTE THE
10 REM AREA OF A CIRCLE Ok
15 PI = 2,141592 roi
20 PRINT “ENTER A RADIUS "3; 10 REM GAS MILEAGE FROGRAM
ZO UNEUT oR 20 FRINT"ENTER LAST ODOMETER READING"
30 A= PI kX R°2 ee) UINTEALE siti
40 PRINT "THE AREA OF THE CIRCLE IS "3A 20 PRINT"ENTER NEW QDOQMETER READING"
20 PRINT seer) MNT AE | Ges
60 GOTO 20 40 PRINT"ENTER GALLONS SINCE FILLUF”
Ok 45 INPUT GAL
oO MPG = (M2 — M1) /GAL
(b) Ok 60 FPRINT"GAS MILEAGE: u" ~ MFGs iu MFG"

RUN Ok
ENTER A RADIUS P ZE.2
THE AREA OF THE CIRCLE IS 2892.56
A sample run is shown in Figure 4.5a. The answer
ENTER A RADIUS ? 6,3
is printed as 19.55696 MPG. This answer contains
?Redo from start many more digits after the decimal point than is mean-
PAG ingful. After all, because of variations in filling the
THE AREA OF THE CIRCLE IS 113.0974 tank it probably only makes sense to compute the MPG
ENTER A RADIUS ? 2.5E19
to the nearest tenth. How can we have the computer
Overflow display the MPG to the nearest tenth? The following
steps will do it:
Overflow
1. Multiply the present value by 10
THE AREA OF THE CIRCLE IS 1.701412E+28 19.55696X10 = 195.5696
2. Add 0.5
ENTER A RADIUS ? 195.5696+0.5 = 196.0696

33
Figure 4.5 Sample runs of gas mileage program. NAME AND ADDRESS
(a) Ok
RUN The INPUT statement can be used to enter string data
ENTER LAST QDOMETER READING
oy aNeata into the computer as well as numerical data. The state-
ENTER NEW ODOMETER READING ment
? 12654
ENTER GALLONS SINCE FILLUF INPUT A$
Bats)
GAS MILEAGE: 19.355696 MPS
will assign whatever characters you type to the string
Ok variable A$. As an example consider the program
shown in Figure 4.6. Line 15 clears the screen. Line
30 will assign whatever you type for your name to
(b) Ok the string variable NAM$. (Note: NAME is a reserved
RUN
ENTER LAST ODOMETER READING
word, so NAMES cannot be used!) Line 50 will assign
? 12245 whatever you type for your street address to the string
ENTER NEW QDOMETER READING variable STREET$. Line 70 will assign whatever you
? 12654
type for your city, state, and zip code to the string
ENTER GALLONS SINCE FILLUF
abe ees
variable CITY$. Lines 80-100 will then print these
GAS MILEAGE: ea) eetiets three strings on three separate lines.
Ok
Figure 4.6 Program to display your name and address.
Ok
(c) Ok Ero
RUN 10 REM NAME AND ADDRESS
ENTER LAST ODOMETER READING Se Glos
? 12345 20 PRINT "ENTER YOUR NAME”
ENTER NEW ODOMETER READING 30 INFUT NAMS
? 12654 40 PRINT "ENTER YOUR STREET ADDRESS"
ENTER GALLONS SINCE FILLUF 30 INPUT STREETS
60 FRINT "ENTER CITY, SAVES AND Zire
Division by zera 7O INFUT CITYS
80 FRINT NAMS
Overflow 90 PRINT STREETS
LOGOS RT Niel.
GAS MILEAGE: 1,701412E+27 MFG Ok
Ok

A sample run of this program is shown in Figure


4.7. Note that a Redo from start error message was
printed out when CITY, STATE and ZIP were en-
3. Take the integer part of the result tered. This is because the comma typed after ROCH-
INT(196.06962) = 196 ESTER was interpreted as a separator between differ-
4. Divide by 10 ent input data and only one data item, CITY$, was
196/10 = 19.6 specified in the INPUT on line 70. Therefore, the IBM
PC thought that too many data items were being en-
Although this may look complicated, it can all be done
tered. In order to include a comma as part of a string
with the following single BASIC statement.
55 MPG = INT(MPG*10+0.5)/10 Figure 4.7 Sample run of program shown in Figure 4.6.
An entered string containing a comma must be enclosed
Note that the result is stored back in memory cell between quotation marks.
MPG. Therefore, if you add this statement to the pro- ENTER YOUR NAME
gram shown in Figure 4.4 and run the program with ° JOHN DOE
the same values used in Figure 4.5a, the result will ENTER YOUR STREET ADDRESS
te OM ell ee eka es
be as shown in Figure 4.5b.
ENTER Clty, SrAne ANDS Ze
The example shown in Figure 4.5c shows that if ? ROCHESTER, MI 48063
you mistakenly press ENTER when the INPUT state- Reda fram start
ment is waiting for a value for the gallons GAL in He WINGnS srnsiner, Iaith ahevovs aah
JOHN DOE
line 45, the computer will assign the value zero to
1234 COMFUTER DRIVE
GAL. This will cause a Division by zero error in line ROCHESTER, MI 48065
50, and the answer that is output is incorrect. Ok

34
it is necessary to include quotation marks around the 3 seconds. Type in the program and try it. The program
string as illustrated in the sample run shown in Figure is an infinite loop, and can be stopped only by BREAK-
4.7. ing it.
Type in and run the program shown in Figure 4.6
entering your own name and address. 10 F = 37 + RND(J) * 2000
You can avoid having to put the quotation marks 20 D = 18 + RND(J)* 18 *2
around the city, state, and zip code as in Figure 4.7
30 SOUND F,D
by changing line 70 in Figure 4.6 to
40 GOTO 10
70 LINE INPUT CITY$
On the IBM PC, once a given SOUND statement
The LINE INPUT statement will assign an entire
line (including commas and quotation marks) to the has initiated a tone the BASIC interpreter continues
string variable CITY$. Only a single string variable executing the statements that follow that SOUND
such as CITY$ can be used with the LINE INPUT statement until another (possibly the same) SOUND
statement. statement is encountered. If the previous tone is still
Make this change and re-run the program. Note being generated, and the duration of the second
that no question mark is displayed while the LINE SOUND statement is not zero, the system waits until
INPUT statement is waiting for you to enter a line the previous tone has finished before it generates a
from the keyboard. new one. This is the case in this program. If the second
SOUND statement does have a duration of zero, the
first tone is terminated when the second SOUND state-
ment is encountered.
MAKING SOUNDS

You can make a single tone on your IBM PC speaker


by using the statement THE FUNCTION INKEY$
SOUND F,D
Up to this point the only method you know for entering
where F specifies the frequency of the tone and D data from the keyboard is to use the INPUT statement.
specifies the duration. F is specified in hertz (cycles One potential disadvantage of using the INPUT state-
per second) and can have values from 37 to 32767. ment is that the data are not accepted by the computer
D is specified in “clock ticks,’ and can have values until you press the ENTER key. Sometimes you would
from 0 to 65535. It takes 18.2 clock ticks for one sec- like the computer to accept a single character from
ond. the keyboard as soon as the key is pressed. The function
If you wish to generate a sound that is a middle INKEYS$ will do this.
C on the music scale with a duration of two seconds, When the function INKEY$ is encountered in a
you should type in SOUND 262,36. Try it. BASIC program, it checks the keyboard to see if
In order to try out different notes, type in and run a key is being pressed. If a key is being pressed the
the following program: value of INKEY$ is the key being pressed. If no key is
being pressed then the value of INKEY$ is the null
10 REM MAKING SOUNDS
string “”’.
20 PRINT “ENTER FREQUENCY (37-32767)” Inasmuch as the IBM PC will not know when you
30 INPUT FREQ are going to press a key, and therefore when to call
40 PRINT “ENTER DURATION (0-65535)” the INKEY$ function, you must program a special
50 INPUT DURATION loop whenever you want to input a character from
60 SOUND FREQ, DURATION the keyboard. This loop can be written as follows:

70 GOTO 20 10 A$ = INKEYS: IF AS=“ ” THEN 10


Try several different values for frequency and dura- When this line is executed the value of INKEY$ is
tion. What is the longest time that the sound can be assigned to the string variable A$. If no key is being
kept on? pressed then A$ will be assigned the null string “”.
An interesting program to run when using the If this is the case then line 10 will just branch to
SOUND statement is one that will generate random itself and assign A$ the new value of INKEY$. This
tone frequencies with random length durations. The loop will continue until you press a key, at which point
program below generates random frequencies from 37 A$ will be assigned the value of the key pressed, and
to 2037 hertz, and random durations between 1 and the statement following line 10 will be executed.

35
In order to test the INKEY$ function, type in line
10 above followed by the line

20 PRINT A$;: GOTO 10


If you run this two-line program the computer should
print on the screen any key that you press as shown
in Figure 4.8. SlzEsaus
Dez

Run this program and try lots of keys. You should we


TPUT. Z
23
oh
find that all character keys will be printed and that Fu L GIVE A WHOLE |
WO E PROGRAM PRESS _
pressing a function key will result in a word being BO D BREAK KEYS LIKE
printed. Try all the keys. Some will not be printed, 2728 wns

while others will give rather mysterious results! oOo


|

EXERCISE 4.1
The temperature in degrees Celsius (°C) is related to
the temperature in degrees Fahrenheit (°F) by the for-
mula Figure 4.8 This program accepts a single character from
the keyboard and displays it at the next screen location.
ACPD)
5
°C ==(F—32
color. Modify the program so that the user does not
Write a program that will input a temperature in °F have to press the ENTER key after a color number
and print on the screen the temperature in both °F is pressed.
and °C.
EXERCISE 4.3
EXERCISE 4.2 Modify the program in Exercise 4.2 so that a sound
Write a program that will ask the user to enter a color with a pitch equal to 40 times the color number is
number and will then clear the screen to that color. played for a short time each time a new color number
Have the program continually loop to ask for a new is selected.

36
A REPETITION LOOP:
LEARNING ABOUT FOR . . . NEXT

In Chapter 2 you learned how to use the GOTO state- If M3<0, then when statement 50 is executed the
ment to form a continuous loop. There is a looping value of I is decremented by M3, and statements 20,
structure available in BASIC that is called a FOR 30, and 40 continue to be executed until I becomes
... NEXT loop which is particularly useful when you less than M2.
know the number of times you want to go through a
Figure 5.1 General form of the FOR . . . NEXT loop.
loop.
In this chapter you will 10 FOR I=M1 TO M2 STEP M3
20
1. learn how to form a FOR ... NEXT loop,
30
2. learn to draw dashed lines using the FOR ...
NEXT loop, and 40
3. learn how to use nested FOR ... NEXT loops. 50 NEXT I
60

Direct Mode Execution


THE FOR ... NEXT LOOP
of the FOR ... NEXT Loop

The general form of a FOR ... NEXT loop is shown


In order to see how the FOR ... NEXT loop works
in Figure 5.1. When statement 10 is executed the value
try typing in the following examples in the direct mode.
of I is equated to MI and statements 20, 30, and 40
are executed. If M3>0, when statement 50 is executed FOR I=1 TO 10: ?I;:NEXT I
the value of I is incremented by M3, and if I is less FOR I=1 TO 10 STEP 2: ?1;: NEXT I
than or equal to M2 then statements 20, 30, and 40 FOR I=1 TO 10: ? “O”;:NEXT
are executed again. This process continues until I be-
FOR I=10 TO 1 STEP -—2: ?1;: NEXT I
comes greater than M2, at which point the program
branches to line 60. Every time around the loop I is These examples are shown in Figure 5.2.
incremented by M3. In line 10 the phrase STEP M3 Note from the third example that the index variable
is optional. If it is omitted then an increment of 1 is I on NEXT I is optional, and NEXT I can be written
assumed. simply as NEXT.

37
Figure 5.2 Examples of using the FOR . . . NEXT loop in Figure 5.4 Drawing a horizontal line using PRINT and
the direct mode. LOCATE.
(a)
Ok Ok
Ce aaa. Le Cl Chis aa esteshe eeNE: Xotiuel LIST.
1 EW GRE IEE ther = Tales eed isTEINSf Berdetaad8) 1 REM HORIZONTAL LINE
Ok 5 DEFINT R,C
uaiay dh A GR fla) ARO AEN eles ey ee eRe IN|
aeCae ae 10 KEY OFF
eee cy 72. SD 20 CLS
Ok 25 ROW = 1
FGt tele aL) apres (lineee INO 30 FOR COL = 4 TO 30
0000000000 ZS LOCATE ROW, COL
Ok 40 PRINT "X"
FORD = vO fo v SiER jH=2e 2 Tee INE XE 50 NEXT COL
tay fey eye i ae 60 GOTO 60
Ok Ok

Drawing Lines Using


PRINT and LOCATE
HK KIKI KIM KKH K HK KHER HK

Recall from Figure 3.18 that the screen has 25 line


positions numbered 1 through 25, and 40 column posi-
tions numbered 1 through 40. By including the state-
ments

LOCATE ROW,COL
PRINT “X”
in a FOR ... NEXT loop, we can print a series of
X’s on the screen. The position of the X’s will depend
upon whether you fix ROW and increment COL in
the FOR ... NEXT loop, or fix COL and increment
ROW. In the first case the X’s will be in a row, while
the second case would put them in a column.
For example, Figure 5.3 shows horizontal, and verti-
cal lines drawn on a screen layout.
The horizontal line can be drawn by setting ROW =
10 KEY OFF
1 and making COL vary from 4 to 30 in steps of 1
as shown in Figure 5.4. is used to remove the prompt line from the screen.
The statement Press CTRL and BREAK to stop the program.
The vertical line can be drawn by setting COL =
60 GOTO 60
1 and letting ROW vary from 4 to 15 in steps of 1
is used to prevent the “Ok” prompt and the cursor as shown in Figure 5.5.
from returning to the screen. The statement Vertical and horizontal lines can be combined to
form a border as shown in Figure 5.6. Note that two
Figure 5.3 Horizontal, and vertical lines to be drawn using X’s are put on the screen on each pass through a FOR
PRINT and LOCATE. ... NEXT loop.
1 5 10 15 20 25 30 35 40

Seeegseeegsueeeeaueeeaune H EXERCISE 5.1


1 Pe XDD IX KD TKD DDD xDDD [

Draw a border around the message


see +—} ial jetaiede
+++ WELCOME
KI Ht = en + 1 + T
&s + 4 = =f
10 ae L [ | BESESERaui Ssst { TO THE
H [
+ IBM PC
Jett

shown in Figure 3.18.

EXERCISE 5.2
Draw your name in block letters using asterisks and
| | the PRINT and LOCATE statements.

38
Figure 5.5 Drawing a vertical line using PRINT and Figure 5.6 Drawing a border using PRINT and LOCATE.
LOCATE.
Ok
(a) OF Si ;
LIST 1 REM HORDER
1 REM VERTICAL LINE S DEFINT R,C
= DEFINT R,C Ua hl Se A
10 KEY OFF 20 CLS
me) |Lees 20 FOR ROW = 1 TO 25
SoG = oi Sa LOCATE ROW, 1:"°LEFT SIDE
sO FOR ROW = 4 To 15 26 PRINT "X"3
=5 LOCATE RQW, COL 38 LOCATE ROW, 29:"* RIGHT SIDE
49 (PRINT "xX" 40 PRINT "X"s5
30 NEXT ROW 30 NEXT ROW
60 GOTO 460 60°F0R, COE = 2° 7G 38
Ok 6a) LOCATE 1,€0L3° TOP CINE
fai; ARRAN Gude
(b) 68 LOCATE 25, COL:* BOTTOM LINE
VAS) VeIRAUINT ER SOE
80 NEXT COL
90 GOTQ 90
x Ok
x
xX
x
x
x
4
xX
x KOIKE HHH KKK HK HM KK KKH KKK EK KK KKM III
x b
x x
x D4
x
x
x
4
x
x
x
x
xX
xX
x
x
xX
x
x
x
xX
x
xX
x SESS
OE
DC
DEO
SOC
DT
SS
IS
ES
KAKKMKR KK KKK RK KK KKK KKK KKK KKK KKK MK KKK KR =<

NESTED FOR ... NEXT LOOPS

FOR ... NEXT loops may be nested. This means


that we can put one FOR ... NEXT loop completely
within another one. When this is done the inner FOR A line of eight asterisks spaced five positions apart
... NEXT loop is executed completely during each should appear on row 20 of the screen as shown in
pass through the outer loop. This makes it easy to Figure 5.7.
perform fairly complex operations. If you now let ROW vary from 1 to 21 in steps
of 4 you can plot six rows, each containing eight aster-
isks. The program shown in Figure 5.8 will do this.
Plotting an Array of Points Lines 25-50 form the FOR ... NEXT loop used to
plot a single row of asterisks as shown in Figure 5.7.
Type in the following program and run it. The outer FOR ... NEXT loop starting at line 20
plots six of these rows as ROW varies from 1 to 21
in steps of 4.
Ok Note that every time through the outer FOR ...
LIST
NEXT loop (lines 20-60) the inner FOR ... NEXT
Seep?
1905ELG loop (lines 25-50) is executed completely. That is, the
15 ROW = 20 inner loop loops eight times (and therefore plots eight
CO. -aR Gee =. t) 18 36 STEP. 5 asterisks) every time the outer loop loops once. Since
LOCATE ROW,COL
the outer loop loops six times, a total of 6<8=48 aster-
PRINT "x"
ch NEXT
ono COL isks will be plotted on the screen.
OW
Nh ce
AN Type in this program and run it. You should obtain

39
Figure 5.10 Program to change the color of the
screen every second.
Ok
Lebo
5 “PROGRAM TO CHANGE SCREEN COLORS
7o DERINE ae
10 SCREEN ©,1:"° TURN ON COLOR OFTION
20 FOR C = 0 T0 7
SOPCOROK. .G: GES
40 FOR I = 1 TO 1400: NEXT I
BO) NEXF €
60 GOTO 2o
Ok

Changing Screen Colors

Before color can be generated on the graphics monitor


from a BASIC program, the color option must be en-
abled. On the IBM PC this is done using the SCREEN
Figure 5.7 Plotting a single row of eight asterisks. statement. Execution of SCREEN 0,1 will turn on
the color option, while the execution of SCREEN 0,0
will turn it off. The zero in the first argument is for
Figure 5.8 Program to plot an array of points. setting the mode of operation to “text” (which is the
Ok mode you are presently in—and thus isn’t changed).
esis The second argument is the color switch (called the
1 REM ARRAY OF FOINTS
S DEFINT R,C “burst” argument by IBM) which actually turns the
1O_-ELS color option on and off. The SCREEN statement is
20 FOR ROW = 1 TO 21 STEF 4 used in line 10 in the program in Figure 5.10, which
a [SOY AOE a ae pe eeyet Tey pis ek ss contains another example of nested FOR ... NEXT
ZO LOCATE ROW, COL
40 PRINT "x"
loops. This program will continually change the color
TOaNEXa COs of the screen every second.
60 NEXT ROW The outer FOR ... NEXT loop (lines 20-50)
Ok changes the screen color code from 0-7. Line 30 actu-
ally changes the screen to the color code. Line 40 is
the array of asterisks shown in Figure 5.9. Modify an inner FOR ... NEXT loop that just uses up some
this program by changing the number of rows, the time. Letting the integer variable I increment from 1
number of points plotted in each row, and the spacing to 1400 will use up about one second. To make a longer
between the points. delay just change 1400 to a larger number. To make
a shorter delay, change 1400 to a smaller number.
Line 60 branches back to line 20 which runs the pro-
gram again.
Type in this program and run it. Press the CTRL
and BREAK keys to stop the program. Change the
time that each color is displayed. To get the screen
back to the state you were in before the program in
Figure 5.10 was executed, enter the following statement
in the direct mode:
SCREEN 0,0
The SCREEN statement will be discussed in detail
in Chapter 7.

SOUND EFFECTS

Type in the following line in the direct mode.


Figure 5.9 Array of points plotted using the program in FOR F = 37 TO 2037 STEP 50 : SOUND F,18 :
Figure 5.8. NEXT F

40
You will hear the speaker produce a sequence of pitch Figure 5.12 Program for making a “phaser’’ noise.
values one after the other. This should give you an Ok
idea of how to add sound effects to your programs. TST
Let’s look at some examples. iG Dede Ate Slay (NIM
UMey Ss
Se ING Nee wl Fae LR
20 * Pil = STARTING FPITCH(FRE®)
40 * P2 = ENDING FITCH
Producing Multiple Clicks 209 DF = PITCH INCREMENT
60 INFUT "ENTER NO. OF CYCLES"; NC
79 INFUT "ENTER STARTING PITCH";P1
The program shown in Figure 5.11 will produce N 80 INFUT "ENTER ENDING FITCH";F2
clicks with a frequency F and repeating every S sec- 90 INPUT "ENTER PITCH INCREMENT";DF
onds. Lines 70-100 loop N times and a click is pro- 100 D= 1
duced each time line 80 is executed. Line 90 is a delay 110 FOR J = 1 TO NC
WAY [PUR Ee AIBN lees Sehr IR)
equal to S seconds.
120 SOUND F,D
140 NEXT F
Figure 5.11 Program to produce N clicks with 150 NEXT J
frequency F and repeating every S seconds. 140 PRINT
170 GOTQ 60
Ok Ok
Bs
10 “PRODUCE N CLICKS WITH A
20 “SPACING S AND FRE@ F
Producing a Siren Sound
2a, DERUINDG (ini
SON toe ENTER REO Or Cenk ore sr
40 INPUT "ENTER TIME INTERVAL S"35 A siren noise can be produced by repeatedly executing
30 INFUT "ENTER NO. QF CLICKS N"3:N SOUND F,D first with increasing values of F and
60 D= 2 then with decreasing values of F as shown in Figure
70 FOR I = 1 TON
80 SOUND F,D 5.13. The outer FOR ... NEXT loop from lines 110—
90 FOR J = 1 TO 1400xS: NEXT J 160 produces NC complete cycles of the siren sound.
190 NEXT I The loop in lines 120-130 produces the increasing
110 PRINT sound and the loop in lines 140-150 produces the de-
120 GOTO 30
Ok creasing sound. Each of these loops executes SOUND
RUN F,D that produces a tone with frequency F and dura-
ENTER FRE@ OF CLICK FP 1000 tion D.
ENTER TIME INTERVAL S? 0.5 Type in this program and run it for values of NC=2,
ENTER NOs OF CLICKS N? 10
P1=300, P2=600, DP=1, and D=1. Try changing the
ENTER) FREQ GF CLICK F? values of NC, P1, P2, DP, and D to produce different

If F is set to 1000, S to 0.5 and N to 10, you should Figure 5.13 Program to produce a siren sound.
hear 10 clicks, one every half second. Enter different Ok
values of N, S, and F to produce different clicking ELsr
effects. Press the CTRL and BREAK keys to stop i0 * STIREN SOUND
20) &9) NGe= NG Or, CYCEES
the program.
20° Fi = STARTING PITCH(CFRE®)
40 * F2 = ENDING FITCH
SO ° DF = PITCH INCREMENT
Producing a Phaser Noise ic ae D = HOLDING TIME
60 INEUT CENTER NO. OF IGVEEES@sNe
70 INFUT "ENTER STARTING FITCH":P1
If you repeatedly execute SOUND F,D with different RO INPUT “ENTER ENDINT FITCH";P2
pitch values F, you can produce a variety of effects. 90 INPUT "ENTER PITCH INCREMENT" s DP
For example, the program shown in Figure 5.12 pro- 100 INFUT "ENTER HOLDING TIME"sD
110 FOR J = 1 TO NC
duces a “phaser” noise consisting of NC cycles of a
Oy Teles (eC ley Pee Keyl let Ds
sound in which the pitch varies from P1 to P2 in steps UO) YONI) fay INSP |=
of DP. TAO RGR) eee eee sie 9D
To hear what this noise sounds like, type in the 150 -SGUND F,D: NEXT F
program and run it for values of NC=6, P1=1500, 140 NEXT J
170 PRINT
P2=4000, and DP=300. Try a variety of different val- 186 GOTO 60
ues for NC, Pl, P2, and DP. Press the CTRL and POO) SST
BREAK keys to stop the program. Qk

41
siren sounds. Press the CTRL and BREAK keys to dom. Also make the pitch of each sound played a
stop the program. random value. (Hint: Use the RND function described
in Chapter 3 to obtain random numbers.)
EXERCISE 5.3
Modify the program in Figure 5.11 so as to produce EXERCISE 5.5
a different tone each time a different color is displayed. Write a program that will draw a diagonal line of
““*°?s from the top left corner of the screen to the bottom
EXERCISE 5.4 right corner. Repeat this by having the line go from
Modify the program in Exercise 5.3 so that the time the top right corner to the bottom left corner.
that a color is displayed (and a tone is played) is ran-

42
MAKING, CHOICES:
LEARNING ABOUT IF... THEN
AND IF... THEN... ELSE

Up to this point all of the programs that we have 50 IF logical expression THEN statement
written have consisted of a sequence of instructions 50 IF logical expression THEN statement 1: state-
and simple loops. However, the thing that makes com- ment 2:...
puters appear to be smart is the ability to make a 50 IF logical expression THEN line number
decision based on the current state of affairs. The pri-
mary decision making statements in IBM PC BASIC In each of these forms the logical expression is some
are the IF... THEN and the IF... THEN... ELSE BASIC expression that is either true or false. These
statements. These statements allow a program to expressions will normally contain relational operators
branch to one of two possible statements depending (such as <) and/or logical operators (such as OR).
upon the truth or falsity of a particular logical expres- These operators will be defined and discussed in detail
sion. A logical expression is an expression that can below.
be either true or false. In the first form of the IF ... THEN statement
In this chapter you will learn shown above, if the logical expression is true then the
statement following the word THEN is executed. This
1. to use the IF... THEN and IF... THEN... can be any BASIC statement that can be executed
ELSE statements to make simple choices, conditionally. If the logical expression is false then
2. the meaning of relational operators, the statement with the next line number is executed.
3. the meaning of logical operators, and The second form of the IF ... THEN statement
4. about flowcharts and structured flowcharts. shown above behaves in a similar way to the first form.
However, if the logical expression is true, then all of
the statements following the word THEN are executed.
Remember that if the logical expression is false then
THE IF ... THEN STATEMENT the statement with the next line number is executed.
In the third form of the IF ... THEN statement
The IF. . THEN statement in IBM PC BASIC allows shown above, if the logical expression is true then the
your program to execute some statements conditionally program will branch to line number. This form is
or to branch to some other statement conditionally. equivalent to the first form where the statement is a
The following are three different forms of the IF ... GOTO statement. Thus, for example, the following
THEN statement. two statements are equivalent.,

43
50 IF A<0 THEN 90 Figure 6.2 Program will check to make
sure that M2 is greater than M1.
50 IF A<0 THEN GOTO 90
Ok
In fact, the word THEN can be omitted in the second RUN
form and you can write ENTER LAST QDQMETER READING
eee her
50 IF A<0 GOTO 90 ENTER NEW ODOMETER READING
° 1265 :
We will illustrate the use of the IF ... THEN state- READING TOQ SMALL
ment by adding some conditional statements to the ENTER LAST ODOMETER READING
° 12345
programs we wrote in Chapter 4. ENTER NEW ODOMETER READING
7° 12654
ENTER GALLONS SINCE FILLUPF
Gas Mileage Program “eka te}
GAS MILEAGE: OT oy MES
Ok
In the gas mileage program shown in Figure 4.4 of
Chapter 4, M1 is the old odometer reading and M2 an extra digit) and therefore it’s better to re-enter both
is the new odometer reading. Now to make any sense odometer readings.
M2 must be greater than M1 (i.e. M2>M1)). It is always
a good idea when writing computer programs to check
the data entered through the keyboard to try to detect Circle Program
any typing errors. For example, if after entering the
value of M2 in line 35, MI is greater than M2 then In the circle program shown in Figure 4.3 the radius
a typing error has probably been made. In any event should obviously be positive. Actually, if you only want
M2 is too small to make sense. Thus, we could add to calculate the area of the circle given by ar?, then
the statements a negative radius will give the same answer as the
37 IF M1>M2 THEN PRINT “READING TOO same positive radius. On the other hand, if you also
SMALL”: GOTO 20 calculate the circumference of the circle given by 2ar
then the radius must be positive. We can calculate
to the program in Figure 4.4 as shown in Figure 6.1. the circumference by adding the two statements
A sample run of this new program is shown in
Figure 6.2. Note that during the first execution the 45 C= 2*PI*R
last digit of the new odometer reading was omitted. 47 PRINT “CIRCUMFERENCE=”; C
This made M2<M1 and statement number 37 caught
to the program in Figure 4.3. We can then test to
it, and printed the message READING TOO SMALL
see if the radius is negative by adding the statement
and then branched back to statement number 20 where
the program started over again. 32 IF R<0 THEN PRINT “RADIUS MUST BE
In statement number 37 you might have branched POSITIVE”: GOTO 20
back to statement number 30 and only asked to enter
If the value of R entered in the INPUT statement
the new odometer reading. However, the error may
on line 30 is less than 0, then the message RADIUS
have occurred when entering M1 (you may have typed
MUST BE POSITIVE will be printed and the pro-
gram will branch back to line 20 and ask for another
Figure 6.1 Gas mileage program containing an IF. . .
radius to be entered.
THEN statement.
We saw in Figure 4.3 that if the radius is too large
Ok
an overflow error will occur when the area is computed
ELSi:
10 REM GAS MILEAGE FROGRAM in line 35. Inasmuch as the value of the area A can
20 PRINT"ENTER LAST ODOMETER READING" not be greater than 1.7E38 then the largest radius R
209 INPUT Mi that will not result in an overflow can be found as
20 PRINT"ENTER NEW ODOMETER READING"
follows:
Sch LING tite is
=/7 IF Mi>M2 THEN PRINT "READING TQQ SMAL
A = tr? < 1.7E38
Gene 20
40 PRINT"ENTER GALLONS SINCE FILLUPF" r2 < 1.7E38/7
45 INPUT GAL r</1.7E38/7
oO MPG = (M2 —- M1)/GAL
so MPG = INT (MPGX*10+.5)/10 Thus, if
60 PRINT"GAS MILEAGE: ie MEGeae ie
Ok R > SQR(1.7E38/PI)

44
Figure 6.3 Modified circle program that checks the value Figure 6.5 The IF. . . THEN statement in line 35 contains
of the radius R. a compound logical expression.
Ok (he
LSESa EISt
3S REM FROGRAM TO COMFUTE THE 1o REM FROGRAM TO COMPUTE THE
10 REM AREA OF A CIRCLE 20 REM AREA OF A RECTANGLE
13 PI = 3.141593 SA GUNUDS UNSINSIRy eh sin) Seat) Cay
20 PRINT "ENTER A RADIUS "5 Sap ie eC) Mey Veto) Tala) Tete ey "VALUES MUST
20 INPUT R last (RAG WAS ene) ete)
s2 IF R<O THEN FRINT "RADIUS MUST BRE POS 40 FRINT "THE AREA OF A RECTANGLE"
PPIVE2s GOLG 20 SO mee WH Tries DOES sess
23 IF R > SOR(1. 7E+38/PI1) THEN PRINT "RA 60 FRINT Xs" AND "TY
DIUS TOO LARGE": GOTO 20 7O FRINT "IS EQUAL TO " gXxky
309 A = PI k* R“2 80 FRINT
40 FRINT "THE AREA OF THE CIRCLE IS "SA
90 GOTO 20
45 C = 2xXFIXR Ok
47 PRINT "CIRCUMFERENCE = He te
50 PRINT
60 GOTO 20 message and ask for new inputs. We can do this by
Ok adding the following single IF ... THEN statement:
35 IF X<0 OR Y<0 THEN PRINT “VALUES
the area will be greater than 1.7E38 and cause an over-
MUST BE POSITIVE”: GOTO 30
flow. We can test this by adding the following state-
ment to the program. The resulting program is shown in Figure 6.5 and
a sample run is shown in Figure 6.6. Note from this
33 IF R>SQR(1.7E38/PD THEN PRINT “RADIUS
sample run that the computer will not allow the pro-
TOO LARGE”: GOTO 20
gram to continue if either value entered is negative
The complete revised program is shown in Figure or if both are negative. Thus, the meaning of the logical
6.3 and a sample run is shown in Figure 6.4. Note expression is that it is true if either X<O or Y<O is
the use of the two IF ... THEN statements in lines true, or if both are true.
32 and 33. The first IF ... THEN statement checks In the above logical expression the symbol < is
to see if R is less than 0. If this is false (i.e. if R is one of the relational operators. The word OR is one
positive) then the next IF ... THEN statement on of the logical operators. Relational operators and logi-
line 33 is executed. If R is not greater than cal operators will be discussed in more detail in the
SQR(1.7E38/PI) then the program will continue on following two sections.
line 35.

RELATIONAL OPERATORS
Rectangle Program
A relational operator is used to form a logical expres-
As another example of using the IF ... THEN state- sion by comparing two arithmetic expressions. (An
ment to check data entered with the INPUT statement arithmetic expression can be a numerical constant,
consider the program shown in Figure 4.2 that com- variable, or expression.) Thus, for example,
putes the area of a rectangle. It is clear that both sides
A<O
of a rectangle must be positive. Thus, if either of the
two values entered in the INPUT statement on line
30 is negative, then the program should print an error Figure 6.6 Sample run of program in Figure 6.5.
Ok
RUN
Figure 6.4 Sample run of program in Figure 6.3. ENTER 2 SIDES? -2,6
Ok VALUES MUST BE POSITIVE
RUN ENTER 2 SIDES? 2.-6
ENTER A RADIUS ? —3 VALUES MUST BE POSITIVE
RADIUS MUST BE POSITIVE ENTER 2 SIDES? —S.,-7
ENTER A RADIUS ? 2.5E20 VALUES MUST BE POSITIVE
RADIUS TOO LARGE ENTER-2 SIDES? 6,8
ENTER A RADIUS ? 5.6 THE AREA OF A RECTANGLE
THE AREA OF THE CIRCLE IS ?78.52036 WITH SIDES 6 AND 8
CIRCUMFERENCE = 35.18584 IS EQUAL TO 48

ENTER A RADIUS ? ENTER 2 SIDES?

45
is a logical expression (it is either true or false) formed LOGICAL OPERATORS
using the relational operator < (meaning less than).
If the contents of memory cell A is less than zero In addition to the relational operators (=< >,<>,
then this logical expression is true; otherwise, it is false. <=,>=) the IBM PC uses the six logical operators
The IBM PC stores the logical value “false” as a NOT, AND, OR, XOR, EQV and IMP. The meanings
zero (0). It stores the logical value “true” as —1. You of these operators are shown in Table 6.2.
can see this by typing
A=3
? A<O NOT (Complement)

and The logical operator NOT is a unary operator, i.e. it


A=-3 operates on a single logical expression, A. If A is true,
then NOT A is false. If A is false, then NOT A is
2 A<0 true. Examples of using the logical operator NOT are
as shown in Figure 6.7. Note that you can print the shown in Figure 6.9.
value of logical expressions such as A<0.

Figure 6.7 The IBM PC stores ‘‘true’’ as —1 and ‘‘false’’ AND (Conjunction)
as 0.
Ok The logical operator AND is a binary operator that
A=3 operates on two logical expressions. Note from Table
Ok
PALO 6.2 that A AND B is true only if both A-and B are
oO true. It is false if either A or B is false, or if both
Ok are false. Examples of using the logical operator AND
A=-3
are shown in Figure 6.10.
Qk
PALO
ial
Ok OR (Disjunction)

The relational expressions used in the IBM PC are The logical operator OR is, like AND, a binary opera-
given in Table 6.1. Figure 6.8 shows some examples tor. Note from Table 6.2 that A OR B is false only
of using these relational operators. You should try if both A and B are false. It is true if either A or B
some examples of your own. is true, or if both are true. Examples of using the logical
operator OR are shown in Figure 6.11.
TABLE 6.1 Relational Operators.
Note that the third example in Figure 6.11 is false
Operator Meaning while the fourth example is true. The only difference
= equal to between the two is the inclusion of the parentheses
<>or>< not equal to in the third example. The reason that the fourth exam-
a less than
ple is true is that the AND operation is performed
> greater than
<=or=< less than or equal to before the OR operation. There is thus an order of
>= or => greater than or equal to precedence for logical and relational operators as well
as arithmetic operators (see Chap. 3). When the IBM
Figure 6.8 Examples of logical expressions formed using PC evaluates an expression it uses the order of prece-
the relational operators. dence shown in Table 6.3.
Qk Within each level of precedence the expression is
26-2= evaluated left to right.
mai
Ok
POKS4 210
oO XOR (Exclusive OR)
Ok
ae The logical operator XOR is a binary operator that
=
is similar to OR. The only difference between the two
Ok
P4e25/5
being that A XOR B is false if both A and B are
[?) true. In fact, A XOR B is true only when either A,
Ok or B, but not both is true.

46
TABLE 6.2 Logical
Operators

A and B are
Logical
Expressions

A NOTA
=
true | false
false | true

A B A AND B}|} AORB | AXORB | AEQVB | AIMPB


= Se

false | false | false false false true true


false | true | false true true false true
true | false | false true true false false
true | true | true true false true true

Figure 6.9 Examples of using the logical operator NOT. TABLE 6.3 Order of Precedence for Evaluating Expressions
Ok Operator Meaning
PNOT S=3
o Ge) Parenthesis
Ok
; Exponentiation
SNOT Se2 aia Unary Negative or Positive
=I 7 Multiplication and Division
Ok
a Addition and Subtraction
SNOT 1O< sSx2 =<><>,<=>= Relational Operators
= NOT Logical Complement
Ok AND Logical AND
?NOT 1x2 OR Logical OR
Oo XOR Logical XOR
Ok EQV Logical EQV
IMP Logical IMP

Figure 6.10 Examples of using the logical operator AND. EQV (Equivalence)
Ok
?2=2 AND S=5 The logical operator EQV is also a binary operator.
=f
A EQV B is true when A and B are the same value
Ok
72=2 AND 224 (both true, or both false), otherwise A EQV B is false.
i?) Examples of XOR and EQV are given in Figure
Ok 6512;
?72=5 AND 8210
(8)
Ok
Figure 6.12 Examples of using logical operators XOR and
2425 AND NOT 725 EQV.
a Ok
Ok Piet a FSGING fits7.
cai}
Ok
BI thee Sa BLY 729
Figure 6.11 Examples of using the logical operator OR. Q

Ok Ok
ey Lee OR 7-597
ca oO
Ok Ok
? NOT 6=6 OR 7437 CEA SAG Fees7
QO =A
Ok Ok
2 (P=? OR S=3) AND 1=2 ? B=S XOR 4=4 OR 7:9
oO oO
Qk Ok
>? @=? OR F=S AND 1=2 °? (R= XOR 4=4) OR 739
e)
=a
Ok Ok

47
IMP (Implication) Figure 6.13 Listing of weekly pay program.
Ok
IMP is a logical binary operator that is not used very Era
10 REM PROGRAM TO COMPUTE
often by beginning programmers. It will not be used
iS REM WEEKLY WAGES
in this text. 20 PRINT "ENTER NQ. OF HOURS WORKED"
20 INFUT H
40 IF H>60 THEN PRINT “INVALID DATA": GO
TO 20
THE IF ... THEN ... ELSE STATEMENT 50 IF H<O THEN PRINT "INVALID DATA": GOTO
20
60 IF H<=40 THEN M=H*4 ELSE OV=H-40:M=40
In addition to the IF ... THEN statement described
X¥440VK6
earlier in this chapter, IBM PC BASIC also includes 7O M = INT (Mk100+.5) /100
an IF ... THEN ... ELSE statement. All BASIC 80 PRINT "WEEKLY PAY = # "3M
languages have an IF ... THEN statement but most 90 END
Ok
do not have an IF ... THEN ... ELSE statement.
This is too bad because, as you will see, an IF ...
THEN ... ELSE statement is very useful. 40 hours and at $6.00 per hour for any hours over
40, and,
The general form of the IF ... THEN ... ELSE
5. print the total amount of pay.
statement is
50 IF logical expression THEN _ statement!: The program to do this is shown in Figure 6.13. Lines
statement2:... ELSE statementA: statementB:...
20 and 30 ask for the number of hours to be INPUT
and the value is stored in H. Line 40 checks to make
When this statement is executed, if the logical expres- sure that H is not greater than 60. Line 50 checks
sion is true then the statements following THEN are to make sure that H is not negative.
executed (statement!: statement2: ...), after which the Line 60 is an IF ... THEN ... ELSE statement
program continues with the statement at the next and will compute the total pay to be M=H*4 if H
higher line number. If the logical expression is false is less than or equal to 40.
then the statements following ELSE are executed If H is greater than 40 then the logical expression
(statementA: statementB:...), after which the pro- H<=40 in line 60 will be false and the statements
gram continues with the statement at the next higher following ELSE will be executed. The statement
line number. The use of the word ELSE is optional. OV=H—40 computes the number of overtime hours
If it is omitted then this statement reduces to the IF (to be paid at $6.00 per hour), and the statement
... THEN statement discussed earlier in this chapter. M=40*4+OV*6 computes the total pay, M, consisting
We will illustrate the use of the IF... THEN ... of the first 40 hours at $4.00 per hour plus the remain-
ELSE statement in the following two programs. ing overtime hours at $6.00 per hour. Line 70 rounds
the value of M to two places after the decimal point
(see the gas mileage program in Chap. 4). Line 80
prints the amount of pay.
Weekly Pay Program Sample runs of this program are shown in Figure
6.14. Note that trailing zeros are not printed on the
As an example of using the IF ... THEN ... ELSE
statement consider the problem of calculating the Figure 6.14 Sample runs of the program in Figure 6.13.
weekly pay of an employee whose hourly rate is $4.00
Qk
per hour and who receives time and a half for overtime. RUN
Suppose that the total hours worked per week can ENTER NO. OF HOURS WORKED
not exceed 60 hours. Thus, we want to write a program
WEEKLY PAY = $ 128
that will Ok
RUN
1. ask for the number of hours worked to be entered ENTER NO. OF HOURS WORKED
from the keyboard, Gd aps Sea)
WEERLY FAY = $ 232.5
2. check to make sure that the number of hours Ok
entered is not greater than 60, RUN
3. check to make sure that the number of hours ENTER NO. QF HOURS WORKED
7 47,34
entered is not negative,
WEEKLY FAY = $ 294,04
4. compute the pay at $4.00 per hour for the first Ok

48
sr

aH *
}
eos
Figure 6.15 Weekly pay program using the PRINT USING © Figure 6.17 Finding the area of a triangle.
statement.
Ok
ES
10 REM PROGRAM TO COMPUTE
Cc
15 REM WEEKLY WAGES
20 PRINT "ENTER NO. OF HOURS WORKED"
30 INPUT H
40 IF H=60 THEN PRINT “INVALID DATA": GO
Semi-perimeter, S HA+B+C)
TO 20
90 IF H*O THEN PRINT "INVALID DATA":GOTQ Area [S(S—A)(S—B)(S—C)]°*
20
690 IF He=40 THEN M=H*4 ELSE OV=H-40:M=40
K44+0VK6 AREA = [S(S — A) (S — B) (S— ©)]°*
70 PRINT "WEEKLY PAY = ";
=/S(S — A) S— B) (S—C)
80 PRINT USING "$$##. ##"3M
90 END where A, B, and C are the sides of the triangle and
Qk
1
S= 7 (ATBIC)
screen. Thus, for example, $233.50 is printed as $233.5.
You can easily correct this problem by using the is the semi-perimeter.
PRINT USING statement to print the pay. Change In BASIC the formula for the area can be written
lines 70 and 80 to as
70 PRINT “WEEKLY PAY”; AREA = (S*(S-A)*(S-B)*(S-©)A0.5
80 PRINT USING “$$##.4+#”;M
or
as shown in Figure 6.15. The result of running this
program is shown in Figure 6.16. AREA = SQR(S*(S-A)*(S-B)*(S-O©))
Remember that the multiplication symbol * must al-
Figure 6.16 Sample runs of the program in Figure 6.15. ways be explicitly typed and every left parentheses,
Ok
(, must have an accompanying right parentheses, ).
RUN We want to write a program that will ask the user
ENTER NO. QF HQURS WORKED to enter the three sides of the triangle from the key-
Grsz2 board, and then display the area of the triangle on
WEEKLY PAY = $128.00
Ok the screen. It should be clear that not all combinations
RUN of three numbers can represent the sides of a triangle.
ENTER NO. OF HOURS WORKED For example, a triangle cannot be formed having the
? 32.25 ; three sides 10, 5, and 3 as shown in Figure 6.18. From
WEEKLY PAY = $233.50
Ok
this figure you can see that to form a triangle the
RUN sum of the two sides A+B, must be greater than C,
ENTER NO. OF HOURS WORKED where C is the longest side. This is equivalent to requir-
? 47.34 ing C to be less than the semi-perimeter S = (A+B+C)/
WEEKLY PAY = $204.04
2. Note that if this were not true then the above formula
Ok
for the area would involve taking the square root of
a negative number which is not a real value.
The PRINT USING statement in Figure 6.15 will
Therefore, our program should check to make sure
automatically round the value of M to two decimal
places and display two decimal places including trailing Figure 6.18 To form a triangle the following relations must
zeros. It will also print the dollar sign just in front
be true: A+B>C; or C<S = 4(A+B+C).
of the amount of pay. A complete description of how
the PRINT USING statement works is given in Ap-
pendix F.

5
Area of Triangle

The area of the triangle shown in Figure 6.17 can be


calculated from the formula

49
that the three numbers entered from the keyboard can Figure 6.20 Sample run of the program in Figure 6.19.
really represent the sides of a triangle. Thus, we need Qk
to check to make sure that C<S. But which side is RUN
ENTER THREE SIDES OF A TRIANGLE
C? It is the longest side. But the longest side may be
fo Tega
the first, second, or third number to be entered from NO TRIANGLE FOSSIBLE
the keyboard. If the program uses the INPUT state- ENTER THREE SIDES OF A TRIANGLE
ment Sen aaa
THE AREA OF THE TRIANGLE IS
INPUT A,B,C 6.495191

then the longest side may actually be stored in memory ENTER THREE SIDES OF A TRIANGLE
cell A, B, or C. Therefore, the program must find ?. 5, Sa?
the longest side, L, and then make sure that L is less NO TRIANGLE POSSIBLE
ENTER THREE SIDES OF A TRIANGLE
than the semi-perimeter, S.
We can determine the largest number stored in
memory cells, A, B, and C by using the following of C in L. Therefore, by the time that line 60 is exe-
procedure: cuted L will contain the largest number stored in A,
1. Compare A and B B, and C.
if A>B Line 60 computes the semi-perimeter, S, and line
then set L=A 70 compares L and S to see if a triangle is possible.
else set L=B If L is greater than S then the message NO TRIAN-
2. Compare C and L GLE POSSIBLE is printed and the program branches
eee L back to line 20 and asks for three new sides. On the
then set L=C other hand, if L is less than or equal to S then line
80 is executed which computes the area of the triangle.
You should convince yourself that this algorithm, or Line 90 prints the result. Line 100 skips a line and
step-by-step procedure, will, in fact, result in the mem- line 120 branches back to line 20 to run the program
ory cell L containing the largest value. This value of again. A sample run of this program is shown in Figure
L can then be compared to the semi-perimeter S to 6.20.
see if a triangle is possible.
The BASIC program to do all this is shown in Fig-
ure 6.19. Line 20 asks for the three sides of the triangle FLOWCHARTS AND PSEUDOCODE
to be entered and line 30 stores these three values in
A, B, and C. Line 40 is an IF... THEN ... ELSE In this chapter we have used the BASIC IF... THEN
statement that compares A and B. If A>B, then it and IF ... THEN ... ELSE statements in the form
stores the value of A in L, otherwise it will store the of an if... then... else statement. For example, in
value of B in L. Thus, when line 50 is executed, L the program to find the area of a triangle we used
will contain the larger of A and B. Line 50 compares the following algorithm to find the largest value in
C and L and if C is greater than L, it stores the value A, B, and C and store it in L.

Figure 6.19 Program to find the area of a triangle. if A>B


then L=A
Ok
Sh else L=B
190 *“FROGRAM TO FIND THE
if C>L
15 * AREA OF A TRIANGLE
20 PRINT “ENTER THREE SIDES OF A TRIANGL. then L=C
a

30 INFUT A,B,C In Chapter 8 we will use the BASIC IF ... THEN


40 IF AEB THEN L statement to form various loops. The if... then...
a AS ey TSN ths else statement is one of these “good” statements that
60 S=(A+KH4+C) /2
(AQ) Ais TE ala) Teresi "NO TRIANGLE FOSSIEB is available in structured programming languages such
TSO (eS iit) sake) as PASCAL.
80 AREA = (Sk (S-A) k(S-B)*(S-C))".5 In Chapter 2 we said that a computer. program is
90 PRINT "THE AREA OF THE TRIANGLE [S's like a train going on a trip. The seats in the train
PRINT AREA
100 PRINT are like memory locations with unique names or ad-
Pow soie 20 dresses that distinguish one seat from another. The
Ok seats may contain strings (like the name of the person

50
sitting in the seat) or numerical values (like the age Figure 6.22 Flowchart representation of the if. . . then
of the person sitting in the seat). . else statement.
As the train goes along the track it can come to a
station where new people can get on, some people can
get off, or others can exchange seats or add things
to their seats. This is equivalent to executing BASIC logical
statements such as PRINT, INPUT, and A=B+C. expression

The if... then ... else statement is like a switch


in the track that allows the train to go on one of two
different paths as shown in Figure 6.21. These two
then
paths lead to two different stations and then recombine
on the other side of the stations. If the logical expres- statements A statements B

sion following if is true then the train follows the track


to station 1 where the then statements are executed.
If the logical expression following if is false then the
train follows the track to station 2 where the else state-
ments are executed. Note that the train can only go
to station 1 or station 2. It can not go to both stations.
Flowcharts have traditionally been used to express
a flowchart as shown in Figure 6.22. The similarity
a computer algorithm. The if... then... else state-
to Figure 6.21 is obvious. If the logical expression in
ment illustrated in Figure 6.21 can be represented as
the diamond shaped box is true then the path to state-
ments A is followed. Otherwise, the path to statements
B is followed.
Figure 6.21 The if. . . then. . . else statement takes the The algorithm given above for finding the largest
train to one of two possible stations. value in A, B, and C is expressed as a flowchart and
in pseudocode (i.e. using if... then... else) in Figure
‘= 6.23. Many people find the pseudocode representation
shown in Figure 6.23b to be simpler and just as easy
to understand as the flowchart shown in Figure 6.23a.
In addition, it is easy to generate flowcharts that end
up looking like “bowls of spaghetti.” For these reasons
the use of flowcharts has declined in recent years.
For those who still like to have some type of graphi-
cal representation of an algorithm without creating a
ERRRSERERE
AKERS “bowl of spaghetti” that is hard to understand, struc-
tured flowcharts are available.

STATION 1 STATION 2 Figure 6.23 (a) Flowchart and (b) pseudocode for algorithm
to find the largest value in A, B, and C.

if A>B
then L=A
else L=B
if C>L
then L=C

(b)

51
Figure 6.24 Two forms of a structured flowchart that The structured flowchart and pseudocode for the
represents the /f. . . then. . . else statement. weekly pay program discussed earlier in this chapter
are shown in Figures 6.26a and 6.26b. The BASIC
if logical expression listing of this program is shown in Figure 6.26c. You
should carefully compare these three representations
of the same program.
(a) The advantage of the structured flowchart represen-
tation is that it clearly displays the logic of the program
statements A statements B in a graphical form. The advantage of the pseudocode
is that it describes the algorithm in a simple and
straightforward manner. Note the importance of the
indentation in the pseudocode description. The advan-
if logical expression

(b) Figure 6.26(a) Structured flowchart of weekly pay


program.

statements A statements B if H>60


then else
print “too many hours" if H<O

then else
Structured Flowcharts
a print “invalid data”

A structured flowchart, also called a Nassi-Schneider-


man chart, after the people who introduced it, is an M=40*4+0V"6
alternate representation of an algorithm that consists M=INT(M*100+0.5)/100
of various nested “‘boxes” without the connecting lines print “weekly pay=$ ";M
shown in Figure 6.23. Two alternate representations
of the if... then... else statement are shown in Figure
6.24. We will use the form shown in Figure 6.24a. Figure 6.26(b) Pseudocode of weekly pay program.
Using this structured flowchart the algorithm shown if H>60
in Figure 6.23 can be represented as shown in Figure then print “too many hours”
6.25. else if H<0
Flowcharts and pseudocode are just different ways
then print “invalid data”
of representing an algorithm to try to make it easier
to understand. When first developing a computer pro- else if H<=40
gram it is generally easier to first express the program then M=H*4
in the form of a flowchart, structured flowchart, or else OV=H—40
pseudocode, and then convert this algorithm to BA- M=40*4+O0V*6
SIC. M=INT(M*100+0.5)/100
Figure 6.25 Structured flowchart representation of print “weekly pay =”’;M
algorithm to find the largest value in A, B, and C.
Figure 6.26(c) BASIC listing of weekly pay programs.
Ok
tsi
10 *PROGRAM TO COMPUTE
15 “WEEKLY WAGES
20 PRINT "ENTER NUMBER OF HOURS WORKED"
20 INFUT H
40 IF H+60 THEN PRINT "TOQ MANY HOURS":G6
OTO 90
20 IF Ht£O THEN PRINT "INVALID DATA": GOT
O 90
60 IF He= 40 THEN M=H*4 ELSE OV=H-40:M=4
OX4+0VK6
7O M = INT(MK1004+,5)/100
BO PRINT "WEEERLY FAY = "aM
90 END
Ok

52
tage of the BASIC representation is that it can be Figure 6.27(a) Structured flowchart of program to find the
executed on the IBM PC! area of a triangle.
Some people have devised a variety of indentation print “Enter the three sides of a triangle
conventions that will make a BASIC program easier input A, B, C
to understand. You can use indentation in your pro-
grams on the IBM PC at the expense of using up
more memory (since blanks in a program line have
to be stored in memory as part of the program). You
should always keep a written version of your programs
on a piece of paper. This version can include indenta-
tion, pseudocode, structured flowcharts or anything
else that will help you to understand the program.
The complete structured flowchart for the program
to find the area of a triangle is shown in Figure 6.27a. print “no triangle possible” calculate & print area
The BASIC listing of this program is shown in Figure
continue this loop forever
6.27b. You should compare carefully the structured
flowchart with the BASIC listing. Note that the GOTO
statement in line 90 is represented in the structured
flowchart as an “outer loop” that continues forever Figure 6.27(b) BASIC listing of program to find the area
(or until the program is stopped by pressing the CTRL of a triangle.
and BREAK keys). Ok
In Chapter 8 we will take a closer look at loops. Lup
In particular you will learn how to stop a loop anytime 10 “PROGRAM TQ FIND THE
15 “AREA OF A TRIANGLE
you want.
20 PRINT "ENTER THREE SIDES OF A TRIANG
Wet
20 INFUT A,B,C
EXERCISE 6.1 40 IF A?EB THEN L=A ELSE L=B
For married taxpayers filing joint returns with a taxa- 20° 0F Gel THEN 42=¢
ble income between $20,200 and $24,600 the Federal 60 S=(A+R+C) /2
income tax is $3,273 plus 28% of the amount over 70 IF LsS THEN PRINT "NQ TRIANGLE FPOSSIEB
LE" ELSE AREA = (S*(S-A) k(S-B)*(S-C0))".5
$20,200. Write a program that will input a taxable FRINT "THE AREA OF THE TRIANGLE IS "3A
income, check that it is between $20,200 and $24,600, REA
and then compute and print the income tax on the 80 FRINT
90 GOTO 20
screen.
Ok

EXERCISE 6.2 Security, Federal and state income taxes, and the take-
Write a program to compute take-home pay. The pro- home pay.
gram should input an hourly wage and the number
of hours worked. Assume that 6.65% of the gross pay EXERCISE 6.3
is deducted for Social Security taxes, 14.8% of the Write a program that will continuously input a series
gross pay is deducted for Federal income taxes, and of test scores. When a negative score is entered, the
4% of the gross pay is deducted for state income taxes. program should print the number of scores entered,
The program should print out the wage rate, the num- the largest score, the smallest score, and the average
ber of hours worked, the amount deducted for Social of the test scores.

53
LEARNING TO USE
MEDIUM RESOLUTION GRAPHICS:
DISPLAYING THE FLAG

In this chapter you will learn how to draw colored ture. Although you have used color in some of the
pictures on the screen using the medium resolution programs, the color involved characters, rather than
graphics capability of the IBM PC. A separate high lines or shapes. In this chapter you will expand your
resolution graphics feature that is available will be de- capabilities to include programming constructs that
scribed in Chapter 13.* can be used to generate graphical results.
In this chapter you will learn
1. how to use the SCREEN statement for medium
resolution graphics, SCREEN Statement
2. how to plot various colored dots by using the
statement PSET (X,Y), color, The SCREEN statement is used on the IBM PC to
3. to draw colored lines, shift the mode of operation to one of three possible
4. to draw areas and arrays of points using the choices: text, medium resolution graphics and high
LINE statement, and resolution graphics. The simple form of the SCREEN
statement is:
5. how to display the American flag on the TV
screen. SCREEN mode, burst

where:
THE SCREEN, COLOR
AND LINE STATEMENTS mode =a numeric expression resulting in values of 0,1 or
2. O is text mode (the default value), 1 is medium
resolution graphics mode and 2 is high resolution
Up to this point all programs have been run in what
graphics mode.
is termed the “text”? mode. This means that you have
burst =a numeric expression with integer values of 0 or
been running programs that are non-graphical in na- 1. This value either enables, or disables, color. In
the text mode a O disables and a 1 enables color.
* To execute the programs in this chapter you must have a color/ In medium resolution graphics the opposite is true:
graphics monitor adapter on your system. If you have a black/ a 0 enables color while a non-zero value will disable.
white monitor the colors described in the chapter will show up as High resolution graphics has no color capability so
different levels of gray. this parameter has no meaning in that case.

54
a
- 319,0 steps. First, the background color and the palette num-
ber must be selected by using the COLOR statement.
Then the foreground color for the dot, or line, or shape
must be picked from the current palette by chosing
Center point is
(x,y) = (160,100) the correct color code number. It should be remem-
y mr bered that you have only three choices for the fore-
ground color. The default foreground color code is
3. These points will be illustrated by several examples
in the next few sections.
0,199 319,199

Es
—_____ Hs
Figure 7.1 Medium resolution graphics generates a PSET Statement
320X200 grid of pixels.
Assume that you wish to draw one pixel (point) on
When either a SCREEN 1,0 or a SCREEN 1,1 state- the color monitor at a given location, with a given
ment is executed the IBM PC will be placed into the color and a given screen background color. This can
medium resolution graphics mode. The medium reso- be done by using the SCREEN, COLOR and PSET
lution graphics mode turns the TV screen, or color statements. The PSET statement is used to actually
monitor, you are using for display into a grid of draw the point at a given location on the screen. The
320X200 points. Each of these points, called pixels, general form of this statement is
is under programmer control and can be turned on
or off individually in either color or black and white. PSET (x,y),color (color argument is optional)
Figure 7.1 shows the way that the pixels are addressed.
where x and y are the coordinates of the point you
Note that x coordinate values range from 0 to 319
wish to draw. The color argument is the color code
going from left to right and y values range from 0
of the color chosen from the present active palette
to 199 going from top to bottom.
(set by the COLOR statement).
As a specific example, assume you wish to do some
medium resolution graphics work with a green back-
COLOR Statement
ground. In particular you wish to place a white dot
at location (200,150) on the screen. You can do this
The COLOR statement in the medium resolution
with the following short program
graphics mode has a slightly different meaning than
the COLOR statement in text mode. While in medium 10 SCREEN 1,0
resolution graphics the general form of the COLOR
15 CLS
statement is
20 COLOR 2,1
COLOR background, palette 30 PSET (200,150),3
where:
In statement 10 the first argument in the SCREEN
background = a numeric expression in the range 0-15 that statement sets the mode to medium resolution graph-
specifies the background color. These colors ics. The second argument enables the use of color.
are the same as found in the text mode and
Statement 20 sets the background color to green (2)
are listed in Chapter 3.
and makes palette 1 the active palette. Palette 1 is
palette =a numeric expression resulting in values of
0 or 1 which will select one of two palettes picked since it contains white as a possible foreground
of colors. The palettes and the three colors color. Statement 30 plots the point at x=200, y= 150
within each palette are shown in Table 7.1. with the color of the dot set to white (3). (Remember
white is color code 3 on palette 1!) Try this program.
The specification of a given color to be used for a
Use different colors for the dot and for the background.
dot, or line, or shape on the screen involves several
You may have to adjust the color intensity on your
monitor to get the correct color. Additionally, the color
TABLE 7.1 Palettes and the color codes of colors
in each palette of single dots is hard to perceive, so don’t be too
Color Code Palette O Palette 7
disturbed if the dot color isn’t quite what you think
it should be. The colors will be easier to perceive when
1 Green Cyan
2 Red Magenta larger shapes are generated. To return to text mode,
3 Brown White enter SCREEN 0 from the keyboard.

55
Figure 7.3 Drawing a horizontal line using PSET.
DRAWING LINES (a)
Ok
: oaks LIST
By placing the PSET statement inside of a FOR... . 10 REM DRAW A HORIZONTAL WHITE LINE
NEXT loop you can draw a line as a series of points. 20 REM ON A BLUE BACKGROUND
Assume you wish to draw a white line on a blue back- 39 a eee 1,9
: : P ect 3)
ground. The program in Figure 7.2a will draw the 40 COLOR 1,1:°RLUE BACKGROUND-PALETTE=1
line vertically down the middle of the screen asshown = sq FoR x = 0 TO 219
in Figure 7.2b. The program in Figure 7.3a willdraw 60 PSET(X,100),3: *S=WHITE DOT
a horizontal line across the middle of the screen, as - NEXT X
shown in Figure 7.3b. You will note that the horizontal
line appears to be “clearer’’ than the vertical line. This (b)
is because the dots are slightly closer together in the
horizontal direction than they are in the vertical direc-
tion.

LINE Statement

Straight lines are drawn so often that a LINE statement


has been added to IBM PC BASIC. This statement
will enable you to do several things:
1. Draw a straight line between any two points on
the screen;
2. Draw a rectangle given the coordinates of the
opposite corners of the rectangle;
3. Color the line, or fill in the rectangle, with a
solid color.
When used to draw a line between two points on
the screen the form of the LINE statement is either
Figure 7.2 Drawing a vertical line using PSET. LINE (xJ,y1) — (x2,y2)
(a) OF

rSt or
10 REM DRAW A VERTICAL WHITE LINE
20 REM ON A BLUE BACKGROUND LINE (x/,y1) — (x2,y2), color
SOMO ie Ei ali) F
=5 CLS where (x/,y1) and (x2,y2) are the coordinates of the
40 COLOR 1,1:° BLUE BACKGROUND-PALETTE=1 end points of the line to be drawn. The first form
SOF ORGY =O TO 199 will draw the line in the default foreground color. The
Be Bee £LOG Win an “S=WHITE DOT second allows you to pick the color from the active
OK palette.
The lines drawn by the programs in Figure 7.2 and
Figure 7.3 can be drawn in a much simpler fashion
by the program in Figure 7.4. This program will put
both lines on the screen, resulting in a large “+” sign.

Figure 7.4 Drawing a large ‘’+’’ using LINE statements.


Ok
LCIsT
10 REM THIS PROGRAM WILL DRAW A LARGE
290 REM "+" IN WHITE ON A BLUE BACKGROUND

30 SCREEN 1,90
pital LELE
40 COLOR 1,1
90 LINE (0, 100)-(319,100),3
60. LINEKV6S510) = 16On Leo as
Ok

56
Try it. Change the last 3 in line 50 to a 2 and rerun _ Figure 7.6 Program to plot a solid rectangle.
the program. The horizontal line should now be ma- Ok
genta while the vertical line stays white. ERIS RE
10 SCREEN 1,0
ila CLS
20 COLOR 1,1
DRAWING RECTANGLES =O LINE (50,50)-(150,100),3,BF
Ok
The LINE statement can be used to draw to rectangles
as well as lines. To draw a rectangle using the LINE
Statement you add a new argument, B, at the end of
the statement as shown below.
LINE (xJ,y1) — (x2,y2),color,B

The values x1,yJ and x2,y2 specify opposite corners


of the rectangle while color is the palette color in which
the lines which make up the rectangle are to be drawn.
For example, the short program
10 SCREEN 1,0
15 CLS
20 COLOR 1,1
30 LINE (50,50) — (150,100),3,B
will draw a white rectangle on a blue background.
The upper left hand corner of the rectangle will be
at 50,50 and the lower right hand corner will be at
150,100. Type in the program and try it. The result the B in the LINE statement. Change line 30 in the
should be as shown in Figure 7.5b. To fill in the rectan- program above to
gle with a solid color that is the same color as the 30 LINE (50,50) — (150,100),3,BF
border, you need to append an F immediately after
and rerun the program. You should find a solid white
rectangle is generated on the screen as shown in Figure
Figure 7.5 Program to draw a rectangle. 7.6. Change the color value (3) in line 30 to 1 or 2
(a) Ok and rerun the program. The color of the rectangle
isd should change with the color code. Check the color
10 SCREEN- 1,0 of your rectangles with the colors given on the palette
to EIS 1 chart in Table 7.1. Change the x and y values given
Ore Oe OReet et
30 JEENE 2(50,00)—€150,
100) ,2,.8
in statement 30 to draw rectangles of different sizes
Ok at different locations on the screen. Remember that
x values must be in the range 0-319 and y values
must be in the range 0-199 or the rectangle will go
“off the screen.”

ARRAY OF POINTS

Figure 7.7a outlines a desired layout for an array of


points to be displayed on the screen. The dots start
in the upper left hand corner at location (10,10) and
are placed uniformly in steps of 20 grid units in each
direction over the whole screen. This array can be
generated with the nested FOR .. . NEXT loops
shown in Figure 7.7b. In this program the variable
X is set to some value in the outer loop, say 30, and
then Y is varied from 10 to 190 with the value of X
held fixed. At each value of Y a point is plotted using

57
Figure 7.7 Plotting an array of points. Figure 7.8 Plotting an array of boxes.
(a) x (a)

i
(b) Or Ok
LSP
LIST
5 REM PLOTTING AN ARRAY OF BOXES
3 REM PLOTTING AN ARRAY OF FOINTS
1@ SECREEN 1,0
10 SCREEN 1,0
HO) SEALS)
top (HES)
20 COLOR 1,1:*° BLUE BACKGROUND-PALETTE 1
30 COLOR 1,1:* BLUE BACKGROUND-FALETTE 1
40 FOR X ey Te) etey seis es
40 FOR X = 10 TO 310 STEF 20
aha) {mls}ee yy ey TOys abet; Sst? seta
DOmmOR@Y a= stlOmTolel On Sie e320
60 LINE(X,Y)-(X+5, Y+tS) , 3, Bs * COLOR=WHITE
exo) [REST
Gia oes) BAOUTRREIS toes}
7O NEXT -¥
790 NEXT Y
80 NEXT X
80 NEXT X
Ok
Ok

og

:$

18 16
o>
Oo
(ee
70
Of
9S
Go)-ah
oo.
BDe
O87
o "8
2a
O.50"..8-o
-o
Oe.eee
eB
CeOQO
O
Oo
0O©
9
0
ogo aOo
68
©
8
ago
ooO48
ok
Det
oO.
ase)
a Ce
oo
8
1o
Go
pA
oo Bo
Ase
Oo)
COS
elt
Boole
oy
a
eet
=)
ares
ake}
hades
=ae)
tmp
fe}

the PSET statement. The points are thus plotted by than points. The boxes are made 5 units square by
columns moving in a top-bottom, left-right manner. adding 5 to both the X and Y values used to specify
You should be able to see this action visually when the first corner of the square. ( (X,Y) specifies one
the program is executed. Try it. The result of running corner and (X+5, Y+5) specifies the opposite corner).
the program is shown in Figure 7.7c. Try this program as it is given to assure yourself that
it runs as indicated above. Your result should be as
shown in Figure 7.8c. After you have done this append
ARRAY OF BOXES an F to the end of the LINE statement (to make it
BF) so that the boxes will be filled with color. This
The program given in Figure 7.8b will plot the array will give an output as shown in Figure 7.9.
of square boxes shown in Figure 7.8a. The only differ- The program given in Figure 7.10a will generate
ence between this program and the one given in Figure three concentric squares. The outer square will have
7.7 is that the LINE statement is used in place of a color of white, the inner one will be cyan and the
the PSET statement so that boxes are drawn, rather one in the middle will be magenta. These will all appear

58
Figure 7.9 Plotting an array of solid squares. Figure 7.10 Drawing concentric squares.
(a) Ok
Ok
ET LIST
3 REM FLOTTING AN ARRAY OF BOXES 3 “CONCENTRIC COLORED SQUARES
1G SCREEN 1,0 Poe DERINY hk
2) ERS PaaSeReeN et. Of. CLS
20 COLOR 1,1:° BLUE BACKGROUND-PALETTE 1 t7 (E0EGOR 1454
40 FOR X = 10 TO 310 STEF 20 20 DEFINT KF
30 FOR Y = 10 TQ 190 STEF 20 SU Ona eee tipi a)
60 LINE(X,Y)-(X , %, +5,Y+5
BF: * COLOR=WHITE
) 40 J = ZOKK
30) LENE (1690—J), 100-—J)—(€160+J, 10043) ,K, 8
JOO NEXT Y: 60 NEXT E
NEXT . X Ok
Qk

(b)

on a yellow background. Type in the program and PLOTTING THE STAR FIELD
execute it. The results should be as shown in Figure
7.10b. In order to turn the squares into solid blocks When we display the flag later in this chapter we will
of color, you merely have to append an F at the end need to plot the star field. The star field will be simu-
of the LINE statement. Make this change and execute lated by the pattern of small squares shown in Figure
the program. This program makes use of a FOR. . . 7.12. Note that this pattern is nothing more than the
NEXT loop in which the steps are negative. The FOR upper left hand corner of the checkerboard pattern
. . . NEXT variable, K, is used to change both the that was generated by the program in Figure 7.11.
size of the squares and their colors. Review the method In fact, the only change that needs to be made in
used to draw the different size squares by plotting the that program, in order to display the star field, is that
corners specified in the FOR . . . NEXT loop on a the upper limits on the FOR . . NEXT loops must
sheet of graph paper. be lowered to hold the stars in the upper left hand
corner. These reductions have been in the program
given in Figure 7.13. The colors in this program are
A CHECKERBOARD OF SQUARES set to give white stars on a blue background. The results
of running this program are shown in Figure 7.14.
Assume you wish to generate a checkerboard pattern
similar to that shown in Figure 7.1la. In order to
generate a display that covers the whole screen with Drawing Stripes
this pattern, with each square being five units on a
side, you should run the program shown Figure 7.11b. The last thing we need to learn in order to display
The result should be as shown in Figure 7.11c. In the flag is how to make stripes of alternating colors.
this program a set of FOR. . . NEXT loops are used In this section we will develop a general program that
to help generate the figure. The program will result will display stripes of two alternating colors in which
in a set of red squares on a black background. you can choose the:

59
Figure 7.11 Plotting a checkerboard pattern.
0 20 40 60 80 100 120
ee aka Boe ial ie

“TIA TTA TTA |


T
N
“TCIM ATT AT AITTeA
eae ZAI ALTA TT
y 304 : : tr Prec eet tt
Meme ceeack pescsas sae ai? zi NN
soft
; { |
nageZa
oe AllA
Saaaa + Lissa

80 +—> La
eee 4

05h
ERs
S REM PLOTTING A CHECKERBOARD
5
» Het tH ;
Aude 7.12 Pattern used to display the star field in the
feat
: :

10 SCREEN 1,0 ag.


29 CLS
20 COLOR ©,9:* BLACK BACKGROUND-PALETTE ©

40 FOR X =
Figure 7.13 The program to generate the star field for the
10 TO 310 STEP 20 flag.
SO FOR Y = 10 TO 190 STEF 20
60 LINE(X,Y)—-(X+5,Y+5), 2, BF: * COLOR=RED Ok
79 NEXT Y ST
BO NEXT X 3 REM PLOTTING A STAR FIELD
990 FOR X = 20 TO 300 STEP 20 10 SCREEN 1,9
100 FOR Y = 20 TO 180 STEF 20 20 CLS
110 LINE(X, Y)—-(X+5, ¥Y+5) , 2, BF 30 COLOR 1,1:* BLUE BACKEGROUND-FALETTE 1
120 NEXT Y 40 FOUR X = 1O how Dio Sibi 2
130 NEXT X 20 ROR Y = 10 70 90 STEF 20
Ok 690 LINE (X, Y)—(X+5, Y+S) , 3, BFs * COLOR=WHIT
7Q NEXT Y
80 NEXT X
70 (FOR X= 20) TG foo rSiTers 20
1OONE ORGY = 29) GO) SORrsierr2o
WOUG) TENTS TORR AN) Osan Vers) 6 i ELE
120 NEXT Y
130 NEXT X
Ok

Figure 7.14 The star field for the flag.

1. number of stripes, N;
2. width (horizontal) of the stripes, W;
3. height (vertical) of the stripes, H;
4. background color, B;
5. palette number, PN, and palette colors, Cl &
C2, for the stripes.

60
The algorithm for displaying the stripes, after the vari- be one, the difference between yl and y2 must be zero
ous values have been entered, is given in Figure 7.15. (to get one line drawn on the screen!). Thus, we need
It is assumed that the height and width of the stripes the “—1” in the LINE statement to get exactly the
were entered in medium resolution graphics screen grid right number of lines drawn to display a stripe with
units, so that O0<W<319. and 0<H<200. the correct height.
In this algorithm the left and right borders (LB The IF... THEN... . ELSE statement is used
and RB) for the stripes are calculated so that the stripes to switch the value of C from Cl to C2, or C2 to
will be centered horizontally on the screen. Then the Cl, each time around the loop. This causes the color
color for the first stripe is set at Cl. of the stripes to alternate.
Figure 7.16 is the final program used to display
Figure 7.15 Algorithm for displaying N stripes of width W the stripes of alternating color. Figures 7.17 and 7.18
and height H with colors C1 and C2 from palette PN. show the results of two runs using this program. You
clear screen to background should enter the program yourself and experiment with
color B,PN set background and palette +. different values. This program could use several more
LB = (320-W)/2 set left border of stripes. “error checks” on the input data. What are some
RB = 319-LB set right border of stripes.
checks that should be made?
Cc =Cl start with first color.
for K=0 to N-1 Figure 7.17 A typical run using the program in Figure 7.16.
LINE (LB,K*H) — (RB,(K+1)*H — 1), C, BF Ok (a)
if C=C1 change RUN
then C=C2 to opposite NUMBLER OF STRIPES? 8
else C=C1 color. HETGHT GF STRIPES? 13
next K WIDTH OF STRIPES? 200
BACKGROUND COLOR CODE? ©
The FOR. . . NEXT loop runs from K=0 to N—1 PALETTE NUMBER? 1
for a total of N passes through the loop. During each TWO PALETTE COLOR CODES? 2
ago=

pass one stripe is put on the screen. The height of


each stripe that is plotted is one more than the differ-
ence between the y2 and yl arguments in the LINE
statement:
1 + y2—-yl = [(K+1)*H—1] — [K*H] + 1
= [K*H+H-—1] — K*H+1 IMM
=H “aa i
It may appear that the height is off by one line. How-
ever, remember that if we wished to have the height a
Figure 7.16 Program to display N stripes of alternating
color.
Ok
LIST
10 *DRAWING COLORED STRIPES
15 DEFINT B,C,E.N,L,P,RW
20 INPUT "NUMBER OF STRIPES";N
=O INPUT “HEIGHT OF STRIPES"3H
40 IF N*W = 200 THEN GOTO 20
45 INPUT "WIDTH OF STRIPES";W DISPLAYING THE FLAG
50 INPUT "BACKGROUND COLOR CODE";B
60 INPUT "FPALETTE NUMBER" ;FN
7O INPUT "TWO PALETTE COLOR CODES";C1,C2 The American flag has 13 stripes. The top and bottom
stripes are red and all other stripes alternate in color
80 SCREEN 1,90 between red and white. The star field on the flag is
90 COLOR &,PN: CLS
blue.
100 LB = (320-W)/2: *LEFT BORDER
SLAMOD Te 3 2. aRIG ES SA "RIGHT BORDER In displaying the flag on the IBM PC we are limited
20 € = Cl to using colors from only one palette. We will thus
120) FOR Kk = GO TG N=21 use palette 1 and from this palette use the colors ma-
1490 LINE (LB, E*H)—(RB, (K+1) XH-1),C, BF genta (close to red) and white for the stripes. We will
150 IF C=Ci- THEN C=C2 ELSE C=Cl
use a blue background which will stay in the star field,
160 NEXT FE
Ok and use the white from the palette for the stars.

61
Figure 7.18 A second r
run using the program inn Figure Yi:16. program segments; one segment will display the 7
(a) Ok
¢ ¥7 stripes to the right of the star field and the other seg-
RUN ment will display the 6 stripes below the star field.
NUMBLER OF STRIPESS 15 The program given in Figure 7.20 is the final pro-
HetGhl Gr SIRIPES? 42
WIDTH OF STRIPES? 300
BACKGROUND COLOR CQDE? oO
Figure 7.20 Program to display the American flag.
PALETTE NUMBER? 0 10 “DISPLAY THE AMERICAN FLAG
TWO PALETTE COLOR CODES? Sat 15 DERINT BVG.RaN.<Lwl. RaW
SC SERS EW ara
40° COMGR 1ets EES
SQ Ci = 3: *MAGENTA
60 GS = 3S: “WHITE
70 Heston SHEIGHE OP ealnitee
Fa me i ns ee a ee te eS

wo pire IN STRIFES TO RIGHT QF STARS


Fe a To ee
S80 N = 72° FIRST SEVEN STRIPES
90 C = €1l:*FIRST STRIPE IS MAGENTA
POOD ER eS eos Ver be BOUR DEER
TSR = leas "RIGHT BORDER
130 FOR K = Q TQ N-1
140 LINE (LB, E*H) -(RRB, (8t+1) KH-1),C, BF
150 IF C=Ci THEN C=C2 ELSE C=Cl
140 Aes K
a
170 “PUT IN STRIPES BELOW STARS
YF
Le0 LB = os) ~*~RORDER, GGES TOV REET SLE
LEORNG ase SA MARE = Shh ets
SORQRhRR R= eee IN=4
210 LINE(LRE, LOS+KXH) —-(RE, 1OS+(K+1) ¥H-1), C,.BF
If you look at the diagram of the star field given 220 IF C=C1l THEN C=C23 ELSE C=Ci
in Figure 7.12, you will note that the lower right hand 250 NEXT K
“star” has its outer corner at coordinate point x=115
and y=95. The stripes must be kept to the right of 240 PUT IN THE SPAR BLEED
Se I
x=115 at the top of the flag and below y=95 at the 200 FOR X = LOT Ste STEE 20
bottom of the flag. Additionally, there are 7 stripes 260 FOR) Yo =--20° [O39 SHEP sea
to the right of the star field and 6 stripes below it. 2 OST NEU , YO 8 Niblett eee aie ieee ED ES
Taking these facts into consideration, the block dia- 280 NEXT Y
290 NEXT X
gram layout of the flag given in Figure 7.19 was chosen
Sew EGR X= sO, Le Stee ee
as the one to use for display. The height of the stripes etG PUR VY =] 20) GcdOe Sree
was picked at 15 vertical grid units so that the stripes Se OE NENG Xa VR cat ee eens
would fit into the space indicated. SSOnNES ey
S40 NEXT X
The program to generate the star field has already
been developed in Figure 7.13. The program to gener-
ate alternating rows of colors of any height has also
been developed. This program needs to be altered only
slightly so that the left and right borders can be picked Ok
Sec alee 8
specifically. The stripes will be displayed using two
ve
Figure 7.19 General layout for displaying the flag. Each wee es
Ee zs &
stripe is 15 grid units high.
0,0 125,0 319,0
ce |||||
co
A a
Star Field 7 Stripes
IN HN
0,115
UA

319,195 Figure 7.21 Display of the American flag.


gram. This program has four main segments, each very © checkerboard (8X8) on the screen suitable for playing
short, that have been outlined with comment headers. a game of checkers.
Each section contains segments that are exactly like
ones you have seen before in this chapter. Section one
EXERCISE 7.2
(lines 10 to 20) defines constants to be used; section
Write a program that will generate a small checker-
two (lines 75 to 160) places the stripes to the right
board pattern (3X3 with each element in the pattern
of the star field; section three (lines 170 to 230) places
6 grid units wide and 4 grid units high). The location
the stripes below the star field; and finally, section
of the upper left hand corner of the pattern, and the
four places the star field in the upper left hand corner.
colors to be used should be entered from the keyboard
You will be able to see the items placed in the display
when the program executes.
in this order when you run the program. The output
from the program is shown in Figure 7.21.
You should enter this program into your IBM PC EXERCISE 7.3
and run it. You will have to adjust the color intensity Write a program that will generate a set of randomly
to get the colors correct, since magenta is being used colored vertical bars. Place a delay loop of about one
in place of red. second in the program, and have the color pattern
change randomly at these one second intervals. Note
EXERCISE 7.1 that you can change palette number, as well as palette
Write a program that will draw a large red and green color code, during the execution of the program.

63
LEARNING MORE ABOUT LOOPS

In Chapters 5 and 7 we used the FOR and NEXT In this chapter you will learn
statements to form simple loops. In this chapter we
1, to repeat a loop while an affirmative answer is
will investigate other types of loops, and other ways
given to a question,
of making loops. In Chapter 6 we used the IF...
THEN statement to make choices between two alterna- 2. to use the IF . . . THEN statement to form a
tives. In this chapter we will use the IF . . . THEN repeat while loop,
statement for a completely different purpose—as a 3. to use the WHILE and WEND statements to
method of forming loops. Inasmuch as you will be create do while loops,
using the same IF. . . THEN statement to form loops 4. to make nested loops using the IF . . . THEN
as you did to form if... then. . . else constructs, or WHILE. . . WEND statements,
you may be inclined to think that there is no difference 5. the difference between a repeat while, a repeat
between the two. But this is not so. There is a funda- until, a do while, and a do until loop and how to
mental difference between a loop and an if. . . then implement all of these loops in BASIC, and
. . else statement. An if... then... else state- 6. how toimplement a loop. . . exit if. . . endloop
ment is not in itself a looping statement. It merely and a loop. . . continue if. . . endloop construct
makes a decision between taking one of two paths. in BASIC.
A loop, on the other hand, implies repetition in which
the same set of statements are executed over and over
again until (or while) some condition is met. The IF THE REPEAT WHILE LOOP
. . . THEN statement can be used as a tool to imple-
ment repetition. Very often you will have a sequence of BASIC state-
Repetition is such an important programming con- ments that you will want to repeat as long as a particu-
cept that IBM PC BASIC has been extended to include lar logical expression is true. For example you may
WHILE and WEND statements which make looping wish to do the following:
possible without the use of either FOR . . . NEXT,
or IF . . . THEN statements. As you will see, there S| eee oe
are many ways to implement looping in IBM PC BA- 40),
SIC. SUS es

64
60 ’ Figure 8.1 BASIC listing of modified triangle program.
repeat lines 30-60 while A>0 Ok
TUESTE
You can do this with the following statement: 10 “PROGRAM TO FIND THE
15 * AREA OF A TRIANGLE
70 IF A>0 THEN 30 20 PRINT "ENTER THREE SIDES OF A TRIANGL
Ee"

Lines 30-70 form a loop that is exited only when 20 50NeFUT AH,
A>0 becomes false; i.e. when A<=0. Obviously, in 40 IF AstB THEN L
aay is (eset syle ite
order to get out of the loop there must be something
60 S=(AtH+C)/2
in lines 30-60 that will eventually cause A to become 7O IF L=S THEN PRINT "NO TRIANGLE POSSIRB
less than or equal to zero. SM fala
epay 8)
Later in this chapter we will look at other types 80 AREA = (Sk (S-A) k(S-B) k(S-CO))*.5
90 PRINT "THE AREA OF THE TRIANGLE IS":
of loops. For now, let’s look at some examples.
FRINT AREA
100 PRINT
110 INFUT "DO YQU WANT TO CONTINUE CY,N) "
TRIANGLE PROGRAM 3AG
1ZO TR VAS) = YY" THEN 26
130 END
The program to find the area of a triangle was discussed Ok
in Chapter 6 and the BASIC listing is given in Figure
6.19. Because of the GOTO statement in line 110 this
statement in line 110 to ask the user if he or she wants
program executes over and over again until the
to continue the program. The user must press Y or
BREAK and CTRL keys are pressed in response to
N followed by ENTER to answer. The INKEY$ func-
the INPUT statement. A better way to end the pro-
tion (see Chap. 4) can be used to eliminate the need
gram would be to ask the user if he or she wants to
to press ENTER.
continue. This can be done by replacing the GOTO
Substitute the following two statements for line 110
20 statement on line 110 with the following statements
in Figure 8.1.
110 INPUT “DO YOU WANT TO CONTINUE
110 PRINT “DO YOU WANT TO CONTINUE
(Y,N)”;A$ (Y,N)?”;
120 IF A$S= “Y” THEN 20
115 AS=INKEYS$ : IF A$=“ ” THEN 115
130 END
Note that after the message in line 110 is printed on
Line 110 displays the message DO YOU WANT the screen, the program will wait in line 115 for a
TO CONTINUE (Y,N) and then waits for a response key to be pressed. While the program is looping in
to be entered from the keyboard. This response is line 115 no blinking cursor will appear. As soon as
stored in the string A$. Line 120 compares this string any key is pressed the program will go on to line 120.
to “Y” and if A$S=“Y” the program branches back If the key pressed is a “Y” then the program will
to line 20 and the area of another triangle is found. branch back to line 20. Otherwise the program will
Any other response will terminate the program. end.
The BASIC listing of this modified program is Type in this program and run it. Note that pressing
shown in Figure 8.1 and a sample run is shown in any key other than “Y” in line 115 will stop the pro-
Figure 8.2. Remember that if the response to an IN-
PUT statement is expected to be a non-numeric value,
then a string variable must be used in the INPUT Figure 8.2 Sample run of program shown in Figure 8.1.
statement. If the INPUT statement contains a numeri- Ok
RUN
cal variable and the user types in a letter or other ENTER THREE SIDES OF A TRIANGLE
non-numeric value the IBM PC will respond with the Clea weet
message THE AREA OF THE TRIANGLE IS
6
?Redo from start
DO YOU WANT TO CONTINUE(Y,N)? Y
It will then wait for a numerical value to be entered. ENTER THREE SIDES OF A TRIANGLE
An INPUT statement containing a string variable will ? 5,6.7
accept any input but will treat it as a string. Thus,
THE AREA OF THE TRIANGLE IS
14. 69694
in line 120 in Figure 8.1 the variable A$ must be com-
pared to the string “Y”’. DO YOU WANT TO CONTINUECY,.N)? WN
The program shown in Figure 8.1 uses an INPUT Ok

65
gram. Also note that the key pressed is not displayed The variable COUNT is used to specify the number
on the screen. If you want to display the key pressed (0-19) of the stripe that is to be drawn.
on the screen, add the statement Each time through the inner repeat while loop a
single stripe that is 10 vertical grid units high is drawn
117 PRINT A$
using the LINE statement. The stripe will start at y
coordinate 10*COUNT and end at 10*COUNT*+9.
The stripe number, COUNT, is increased by one each
RANDOM STRIPE PATTERNS time through this loop. The color of each stripe is
determined by the value of a random number C. The
In this section we will write a program that will draw
value of this random number is either 0, 1, 2 or 3. This
a random horizontal stripe pattern. The pattern will
value is used in the LINE statement to choose the
contain 20 horizontal stripes each 320 grid units wide
color code. Values of 1, 2 or 3 will result in the stripe
and 10 grid units high. In other words the picture
color being picked from the palette. A value of 0 will
will take up the entire 320 < 200 screen area in the
result in the stripe being drawn in the background
medium resolution graphics mode. Each stripe that
color. This loop is repeated while Y<=19. Therefore,
is plotted will have a 25% chance of being one of
a total of 20 stripes will be drawn.
four possible colors. Three of the four colors will be
After the stripe pattern is plotted the user is asked
determined by the choice of palette, while the fourth
if another picture is wanted. If so, then the screen is
color will be determined by the background color.
cleared and the entire program is executed again. Oth-
A pseudocode description and a structured flowchart
erwise, the screen is cleared and the program termi-
for this program are shown in Figure 8.3. After clearing
nates.
the screen the user specifies the background color, B,
A BASIC listing of this program is shown in Figure
and the palette number, PN, in an INPUT statement.
8.4. Compare this listing carefully with the pseudocode
and structured flowchart representations of the pro-
Figure 8.3(a) Pseudocode of program to draw random
stripes.
gram shown in Figure 8.3. Note in particular how
the repeat while and if. . . then. . . else constructs
clear screen in medium resolution graphics are implemented in BASIC. Line 125 will cause the
loop1: input background color, B, and palette number, PN screen to be cleared of the previous stripe pattern.
clear screen to background color
COUNT=0
Figure 8.4 BASIC listing of program to produce a random
loop2: stripe pattern.
generate random number, C, in range 0-3
Ok
display one stripe in color C Lusi
COUNT = COUNT+1 10 “PROGRAM TQ DRAW STRIFES WITH
repeat while COUNT<=19 20 “RANDOM COLORS
input “another picture?”;A$ ei) SA (SlatN) ih Gi
clear screen to background color. SD LIN Titi enh
repeat while A$ = “Y” 40 INPUT "BACKGROUND COLOR CODE";B
set screen to text mode and clear screen HO INPUT "PALETTE NUMBER"; FPN
aivety (EXO(LIG}ES fain tein!
60 CLS
Figure 8.3(b) Structured flowchart for program to draw 70 COUNT = 0
random stripes. 80 C =-INT(4XRND(1))
9Q LINE (QO, 1OXCOUNT) —(319, LOXCOUNT+9) ,C,B
clear screen
———— F

input background color, B, and palette number, PN 100 COUNT = COUNT + 1


clear screen to background color 110 IF COUNT <= 19 GOTO ao
COUNT =0 120 INPUT "ANOTHER FICTURE";A%
Teeter (OS)
C = INT(4*RND()) 130 IF A$ = "Y" GOTO 40
Draw a horizontal stripe of color C with upper edge 140 SCREEN ©
at 10*COUNT 150 END
Ok
COUNT = COUNT+1
repeat while COUNT < = 19 You should type in this program and run it. A
input “another picture?”;A$ sample run is shown in Figure 8.5.
clear screen to background color
repeat while AS=“Y”
EXERCISE 8.1
Use a FOR. . . NEXT loop to implement the inner
Clear screen to text mode
loop in the random stripe algorithm in Figure 8.3.

66
Figure 8.6(b) Structured flowchart for program to plot a
random checkerboard pattern.
clear screen

input background color, B, and palette number, PN


clear screen to background color
COUNT=0
x=0
C=INT(4*RND(1))
plot one 10X10 square with
upper LH corner at (10*X,10*COUNT)
=X+1
repeat while X<=31
COUNT=COUNT+1
UMA
repeat while COUNT <= 19
input “another picture?”;AS$
clear screen
Figure 8.5 Sample run of program shown in Figure 8.4.
repeat while A$ = “Y”

clear screen to text mode


Run the program and compare your result with Figure
8.5.
program. Note that for each stripe that was plotted
on the screen in the previous program there is another
RANDOM CHECKERBOARD PATTERN nested repeat while X<=31 loop. This inner loop will
plot 32 squares (with random color) moving across
In this section we will modify the program in Figure the screen from left to right. Thus the old stripe is
8.4 to plot a random checkerboard pattern rather than now a sequence of multi-colored squares. Note that
a random stripe pattern. This can be done by adding the value of X must be initialized to zero at the begin-
another inner loop that will plot a row of squares rather ning of this inner loop (i.e. at the beginning of each
than a horizontal stripe. Each square will be 10 grid new line).
units on a side and will have a 25% chance of having The BASIC listing of this program is shown in Fig-
one of four possible colors. ure 8.7. Compare this listing carefully with the pro-
Pseudocode and structured flowchart representa- gram descriptions shown in Figure 8.6. Make sure you
tions of this program are shown in Figure 8.6. Compare
these algorithms with the corresponding program de- Figure 8.7 BASIC listing of program to plot random
scriptions given in Figure 8.3 for the random stripe checkerboard pattern.
LIST
Figure 8.6(a) Pseudocode for program to plot a random 10 *PROGRAM TO DRAW SQUARES
checkerboard pattern. 20 "OF RANDOM COLORS
25 SCREEN 1,0
clear screen
30 DEFINT B,C,F,X
loop1: input background color, B, and palette number, PN
40 INPUT "BACKGROUND COLOR CODE";B
50 INPUT "PALETTE NUMBER";PN
clear screen to background color
55 COLOR B,PN
COUNT=0 60 CLS
loop2: 70 COUNT = 0
x=0 BOX =o)
loop3: 90 C = INT(4RND(1))
C = INT(4*RND(1)) 100 LINE (10X, LOXCOUNT) —(10%X+9, LOXCOUNT
plot one 10X10 unit square moving left to right
+9) .C, BF
110 X = X41
X=X+1
120 IF X 4= 31 GOTQ 990
repeat while X<=31
126 COUNT = COUNT + 1
COUNT=COUNT+1 140 IF CQUNT <= 19 GOTO 80
repeat while COUNT < =19 150 INPUT "ANOTHER FICTURE";A%
input “another picture?”; AS isa CLS
clear screen to background 160 IF At = "YY" GOTO 40
repeat while A$S=“Y” 170 SCREEN ©
set screen to text mode and clear screen Ok

67
expression is evaluated again. If the logical expression
is still true, the statements between the do while and
PICTURE? @ enddo will be executed again. This action continues
ANOTHER

aa until the logical expression is false, at which time con-


trol goes to the statement following the enddo.
In IBM PC BASIC the do while pseudocode is rep-
resented by the word WHILE and enddo by WEND.
A typical IBM PC BASIC implementation of a do
while construct is:

5 DEFINT N
10N=0
20 WHILE N<=5
30 PRINT N;
40 N=N+1
50 WEND
Figure 8.8 Sample run of program shown in Figure 8.7.
60 END
understand clearly how each of the nested repeat while When this program is executed the integers 0 1 2 3
loops is implemented in BASIC and what its function 4 5 will be printed. The program begins with N being
is in the execution of the program. Type in this pro- set to 0. With N=0, the logical expression N<=5 is
gram and run it. A sample run is shown in Figure true, so the statements in between WHILE and WEND
8.8. are executed. (These statements are called the “body”
of the loop.) When the body is executed the first time
a 0 will be printed (statement 30) and then N is incre-
THE DO WHILE TRUE LOOP mented to 1 (statement 40). When statement 50 is
reached control automatically goes back to statement
Most of the “newer” programming languages, such 20. Since N=1 at this time, N<=5 is still true, so
as ALGOL, PASCAL and PL/I, have a set of state- the loop is executed again. This time through the loop
ments that allow for looping repetitively through a a 1 gets printed and N gets incremented to 2. The
group of statements according to the logic given below: looping continues until N gets incremented to 6, which
means N<=5 is false, and control goes to statement
do lines 10-50 while A<12
60 which terminates the program. Enter this program
10 and run it.
20 In the program above statements 30 and 40 have
30 been indented slightly so that the body of the do while
40 loop is easy to spot. This type of indentation on loops
50 makes program logic easier to understand, and should
be used whenever possible. Unfortunately, indentation
In this form of looping the logical expression is checked is rather difficult to do on a 40 character per line screen,
at the start of the loop, rather than at the end. The but relatively easy to do when there are 80 characters
pseudocode for this types of construct is or more per line.
do while: logical expression In the last program you could have achieved the
same results with a program using a FOR. . . NEXT
loop, rather than the WHILE . . . WEND loop:

Body of loop 10 FOR N=0TOS5


20 PRINT N;
enddo: 30 NEXT N

The mechanics of how this construct executes are as However, the similarity between the FOR ...
follows: If the logical expression is true, then the state- NEXT and WHILE . . . WEND loops in this one
ments between the do while and enddo will be exe- program should not be construed to imply that they
cuted. When execution reaches the enddo statement, are equivalent—they are not! The WHILE ...
control goes back to the do while where the logical WEND is much more general. As an example, the

68
following program cannot be generated using a simple ‘a more general loop structure in which the test of
FOR . . . NEXT loop. the logical expression is done in the middle of the
loop. Depending upon whether the loop is exited when
10 INPUT “ENTER A NUMBER”; N
the logical expression is true or false we will call these
20 WHILE N<=100 AND N>=--100
two general loop structures the loop... exit if. . .
30 PRINT NA2 endloop and the loop . . . continue if . . . endloop
40 INPUT “ENTER A NUMBER”; N loops.
50 WEND
Figure 8.9 Drawing random colored stripes using
This program will keep printing out the square of the WHILE. . . WEND statements.
number entered, as long as the number entered is in
clear screen in medium resolution graphics (a)
the range —100<N<100. Any other values will cause AS

the program to terminate. A FOR . . . NEXT con- do while AS=“Y”


input background color, B, and palette number, PN
struct is designed to go around its loop a fixed number
clear screen to background color
of times; the WHILE . . . WEND loop is executed COUNT = 0
as many times as it takes to make the logical expression do while COUNT<=19
generate random number, C, in range 0-3
finally be false.
display one stripe in color C
In the last program above, note that the exact same COUNT = COUNT+1
input statement appears twice: once in line 10, which enddo
input “another picture?”; A$
gives a value of N to get you into the loop the first
clear screen to background color
time, and once in line 40, which yields a value of N enddo
that either keeps you in the loop, or gets you out of set screen to text mode and clear screen
the loop. A duplication of this type is not unusual in (b)
looping-type logic. clear screen
As a larger example of the logic used in do while
AS=“YV~”

constructs, the program in Figure 8.4 to generate ran- do while AS=“Y”


dom colored stripes has been rewritten using this form input background color, B, and palette number, PN
of logic. Figure 8.9 contains three forms of this pro- clear screen to background color
gram: pseudocode; structured flowchart; and IBM PC COUNT=0
BASIC implementation. Enter this program and try do while COUNT< = 19
it. oa C=INT(4*RND())
You should be aware of the fact that many BASIC iat display one stripe in color C
implementations do not have the WHILE and WEND | COUNT = COUNT+1
statements. IBM PC BASIS does, and you will find input “another picture?”; A$
them quite useful. clear screen to background color
set screen to text mode and clear screen
EXERCISE 8.2
Use WHILE. . . WEND loops to implement the ran- 10 *FROGRAM TO DRAW STRIPES (c)
dom checkerboard algorithm given in Figure 8.6. Run 20 *OF RANDOM COLORS USING

the program and the compare your result with Figure S0 She WHiCe.. END EONS tRueT
46 SCREEN 1,0
8.8. SO DEFINT B,C.F,X
66 4% = "y"
ZO Wee As =, ye
86 INPUT "BACKGROUND COLOR CODE";B
DIFFERENT TYPES OF LOOPS 90 INFUT "FALETTE NUMBER"; FN
166 COLOR B,FN
There are really four different elementary loop struc- GaGa (SyWas
1206 CQUNT = 6
tures that you can have. You can test the logical expres- 130 WHILE COUNT «<=i19
sion at the beginning of the loop or at the end of 140 C = INT(4*RND(1i))
the loop. In addition you can branch out of the loop 156 LINE (O, 1OXCOUNT) —(219, 16*COUNT+9) ,C, BF
140 COUNT = COUNT + i
when the logical expression is either true or false. We
170 WEND
will call the two loops with the test at the end of 180 INFUT “ANOTHER PICTURE";A%
the loop the repeat while and the repeat until loops. TSere UE AS

We will call the two loops with the test at the beginning i96 WEND
206 SCREEN ©
of the loop the do while and the do until loops. In 210 END
addition to these elementary loops it is possible to use Ok

69
loop. = 10
All of these loop structures can be implemented
in IBM PC BASIC. As we will see some are easier 20

to implement than others. Most good programmers 30

only use two or three of these loop structures in all repeat until logical exp. 40 IF logical expression THEN 60

of their programs. The choice of which ones to use 50 GOTO 10

depends on the programming language being used and 60


to some extent personal preference.

The Repeat While Loop

This is the loop that we have used in some of the


programs in this chapter. Its general form is shown
in Figure 8.10. In this figure logical exp. is any logical
expression that is either true or false. This loop is re-
peated while the logical expression is true. Figure 8.10
shows what this loop looks like in our train track model repeat until logical exp.

of a computer program. Note that the train continues


to loop around through the station as long as the logical
expression is true. (c)
Figure 8.11 The repeat until loop: (a) Pseudocode; (b)
looper eee ee 10
BASIC implementation; (c) Structured flowchart; (d) Train
20 track equivalent.
30
repeat while logical exp. 40 IF logical expression THEN 10 quires an additional GOTO statement. For this reason
(a) (b) any time we form a loop with the test at the end of
the loop we will make it a repeat while loop. After
you finish this book you can use whichever loop struc-
ture you want.

repeat while logical exp. The Do While Loop

The do while loop is one of those “good”’ programming


statements that has been implemented in IBM PC BA-
SIC, and was introduced earlier in this chapter. It’s
general form is shown in Figure 8.12. In this loop
Figure 8.10 The repeat while loop: (a) Pseudocode; (b) the test of the logical expression is done at the begin-
BASIC implementation; (c) Structured flowchart; (d) Train
ning of the loop. This means that if the logical expres-
track equivalent.
sion is initially false, then the train will never go to
The Repeat Until Loop the station. That is, the statements within the loop
will never be executed.
The general form of the repeat until loop is shown
in Figure 8.11. Note in this case that the loop is exited
if the logical expression is true. That is, the loop is The Do Until Loop
repeated until the logical expression is true. In general
you should choose to use either the repeat while or The fourth elementary loop structure is the do until
the repeat until loop in your programs. This will help loop whose general structure is shown in Figure 8.13.
you avoid logical errors because you will always be In this loop the test of the logical expression is also
thinking either while or until. Many people prefer the done at the beginning of the loop. However, the state-
repeat until and some languages implement this loop ments within the loop are only executed if the logical
directly. expression is false, i.e. until the logical expression is
However, by comparing Figures 8.10 and 8.11 you true. Note that if the logical expression is initially
can see that it is easier to implement a repeat while true, then the train will never get to the station and
loop in BASIC. The repeat until implementation re- the statements within the loop will never be executed.

70
do while logical exp. 10 WHILE logical exp. do until loop when we need a test at the beginning
20 of the loop.
30 People who write structured programs using a
40 “good” structured programming language use the do
enddo 50 WEND _ while and the repeat until loops. As we have seen it
will save us some code (and therefore some memory)
if we use the repeat while, rather than the repeat until
loop. However, any of these loops we have discussed
can be used without much difficulty.

The loop. . . exit if . . . endloop Loop


logical exp.
do while logical exp.

[-] false
Occasionally it is convenient to use a more general
looping structure. Such a loop is the loop . . . exit
if. . . endloop construct whose general form is shown
in Figure 8.14. This is really a generalized UNTIL
loop. That is, if the exit if statement is at the top of
the loop, then it reduces to the do until loop. If the
exit if statement is at the bottom of the loop, then it
(c) reduces to the repeat until loop.
Figure 8.12 The do while loop: (a) Pseudocode; (b)
BASIC implementation; (c) Structured flowchart; (d) Train
track equivalent. The loop. . . continue if . . . endloop Loop

Note also that the BASIC implementation of the In order to complete the discussion of loops the general
do until loop requires a GOTO statement at the end form of the loop. . . continue if. . . endloop is shown
of the loop, while the do while loop ends with a in Figure 8.15. This is really a generalized while
WEND. For most people the logic of a WHILE...
WEND statement is easier to spot than is the logic Figure 8.14 The /Joop.. . exit if. . . endloop loop: (a)
generated using GOTO’s. For this reason we will nor- Pseudocode; (b) BASIC implementation; (c) Structured
flowchart; (d) Train track equivalent.
mally implement the do while loop rather than the
loop a=
eee 10
Figure 8.13 The do unti/ loop: (a) Pseudocode; (b) BASIC 20
implementation; (c) Structured flowchart; (d) Train track 30
equivalent. exit if logical exp. 40 IF logical expression THEN 80
do until logical exp. 10 IF logical expression THEN 60 50
20 60
30 endloop 70 GOTO 10
40 80
enddo 50 GOTO 10

60

logical exp.

do until logical exp.


exit if logical exp.

(c) (d)

71
logpyass tse 10 Modify the program shown in Figure 8.1 to calculate
20 the acreage of this tract of land. The total acreage
30 can be found by computing the area of each of the
continue if logical exp. 40 IF logical expression THEN 60
four triangles, adding these results, and using the fact
that 1 acre = 43,560 square feet.
50 GOTO 90

as Stee 60

endloop 70 EXERCISE 8.4


Suppose that the tract of land shown in Exercise 8.3
80 GOTO 10
contains a circular pond 200 feet in diameter com-
90
pletely within its boundaries. Write a program that
will compute the acreage of the land not counting the
water.

EXERCISE 8.5
The Fibonacci sequence
TeLE2 SaDiS0
lS Zino |
has the property that each number in the sequence
(starting with the third) is the sum of the two immedi-
continue if logical exp.
ately preceding numbers. Write a program that will
false
display on the screen all numbers in the Fibonacci
sequence that are less than 1000.

EXERCISE 8.6
You decide to deposit an amount of money, D, in a
(c) (d) savings account each month. The account pays P per-
Figure 8.15 The /oop. . . continue if. . . endloop loop: cent interest compounded monthly. Write a program
(a) Pseudocode; (b) BASIC implementation; (c) Structured that will input D and P and then determine the number
flowchart; (d) Train track equivalent.
of years (and months) that it will take for you to ac-
cumulate a million dollars.
loop. That is, if the continue if statement is at the
The amount of interest added to the account each
top of the loop, then it reduces to the do while loop.
month is determined in the following way. If B is the
If the continue if statement is at the bottom of the
balance in the account at the beginning of the month,
loop, then it reduces to the repeat while loop.
then at the end of the month an amount of interest
Any of the loops described above can be used in
B*MR is added to the account, where MR is the
your programs, but as we have seen, the easiest ones
monthly interest rate (equal to 0.01*P/12). Thus, the
to implement in IBM PC BASIC are the repeat while,
total amount of money in the account at the end of
the do while, and the loop. . . exit if. . . endloop
the month will be equal to B+ B*MR.
structures.
Run the program for the following cases:
EXERCISE 8.3 (a) deposit $500 per month at 8% interest
The dimensions, in feet, of a tract of land are shown (b) deposit $1,000 per month at 10% interest
in the following figure:
" . {su W5 (c) deposit $1,000 per month at 12% interest

EXERCISE 8.7
Manhattan Island was purchased from the Indians in
1626 for $24. If that $24 had been deposited in a bank
in 1626 paying 4% interest compounded annually,
what would it be worth today?

EXERCISE 8.8
If you deposit $100 each year in a bank account paying
5% interest compounded annually, how much money
will you have after 10 years?

ri
EXERCISE 8.9 ’ the ground at any time T is given by
Population growth. In 1980 the U.S. birth rate was
H=-—16.2 T?+ VT
16.2 births per 1000 population, the death rate was
8.9 deaths per 1000 population, and the immigration Write a program that will
rate was 2.0 per 1000 population. Assume that these
(a) input a value of V,
rates will remain constant in the future and that the
population of the United States at the beginning of (b) print the letters T and H for a table heading,
1980 was 226,504,825. Also assume for the purpose (c) compute H for values of T starting at 0 and
of simulating this process on the computer that all increasing by 1 second until the rocket hits the
births, deaths, and migrations take place on the last ground, and
day of each year. Write and run a program that will (d) print the values of T and H in the form of a
determine in which year the population of the U‘S. table.
will reach 300,000,000.
Run the program using a value of V = 200 ft/s.
EXERCISE 8.10
A rocket is fired vertically into the air with an initial
velocity of V (ft/s). The height H of the rocket above

73
LEARNING TO USE
GOSUB & RETURN:
SUBROUTINES

Often you will have a sequence of BASIC statements 2. to write subroutines for plotting horizontal and
that you would like to execute at several different loca- vertical stripes and equilateral triangles,
tions within a program. Instead of having to repeat 3. to plot the same figure at different locations on
this same sequence of statements every time you want the screen,
to use it, you can write the statements only once as 4. to plot figures of varying sizes, and
a subroutine and then call the subroutine each time
5. how to display your name anywhere on the
you want to execute these statements.
screen.
Subroutines are also useful as a means of writing
programs in a modular fashion. This becomes more
and more important as the size cf a program grows. THE GOSUB & RETURN STATEMENTS
Program segments that perform particular functions
can be written as subroutines and then called when The general form of the GOSUB statement is
that function needs to be performed. Inasmuch as the GOSUB line number
IBM PC screen can display a maximum of only 24
When this statement is executed the program branches
program lines (leaving the line at the bottom for the
to the statement at the designated line number. For
prompt), then if you can keep your main program
example, the statement GOSUB 500 will cause the
and all subroutines less than 24 screen lines long, you
program to branch to line 500. It looks as if GOSUB
will be able to read and study a complete program
500 behaves the same way as GOTO 500. However,
segment without having to scroll the screen. This tech-
there is an important difference. The IBM PC remem-
nique of modularizing your program will greatly sim-
bers where the statement GOSUB 500 is located in
plify the process of debugging and modifying your pro-
the program. Line number 500 is the first line of a
gram. It is the secret that allows you to write long
subroutine that is just a collection of BASIC state-
programs with almost the same ease that you write
ments that perform a particular task. At the end of
short programs.
this subroutine you must include the statement
In this chapter you will learn
RETURN
1. how to use the GOSUB and RETURN state- When the RETURN statement is executed the pro-
ments, gram will then branch back to the next statement fol-

74
lowing GOSUB 500. This process is shown in Figure _ will branch to the subroutine at line 500 then RE-
9.1. TURN to line 70.
However, the statement
Figure 9.1 Forming a subroutine using GOSUB and
RETURN. 90 GOSUB 500
will also branch to the subroutine at line 500 but will
50 then RETURN to line 100. Recall that the computer
60 GOSUB 500 always remembers from where it branched to a sub-
routine and it will always return to that point.
70 .
80 Figure 9.3 One subroutine can call another subroutine.

50 eo
60 GOSUB 500
500 Leen 70
Subroutine— 2 510 80
520 RETURN

500
SUS peite
eee ae
Now it looks as if you would accomplish the same 510 GOSUB 600
result in Figure 9.1 by using the two statements 520 RETURN
60 GOTO 500

and

520 GOTO 70 600


Although this would be true in Figure 9.1 it would 610 ee
not work if you wanted to call the same subroutine 620 RETURN
from two different locations in the program as shown
in Figure 9.2. In this case the statement You can even call a subroutine from within another
subroutine. The IBM PC will always find its way back
60 GOSUB 500 by retracing its steps as shown .in Figure 9.3. Line
60 branches to the subroutine at line 500. Line 510,
Figure 9.2 Calling a subroutine from two different locations which is within this subroutine, branches to a second
within a program. subroutine at line 600. The RETURN statement on
line 620 will branch back to line 520, the statement
following the GOSUB 600 statement. This happens
50 Pita wes
to be the RETURN statement of the subroutine that
60 GOSUB 500 begins at line 500. It will then branch back to line
70 70, the statement following the GOSUB 500 statement.
80 eee te
90 GOSUB 500
PLOTTING RECTANGLES
100 AND TRIANGLES
110
As an example of using subroutines we will write two
subroutines—one to plot rectangles of any size and
color anywhere on the screen, and one that will plot
equilateral triangles anywhere on the screen. We will
500 first look at the problem of drawing rectangles that
Subroutine— ¢ 510 can be either filled, or left empty, depending on the way
520 RETURN we call the subroutine that will draw the rectangle.

75
In Chapter 7 we saw that the LINE statement could 200 210 240 a
be used to draw a rectangle. If the LINE statement I | | I |
was written in the form
140 -
LINE (X1,Y1) — (X2,Y2),C,B
then a rectangle of color, C, was drawn with opposite
corners located at grid points (K1,Y1) and (X2,Y2).
If an F was appended to the B at the end of the state-
ment, then the rectangle was filled with color C.
Assume we wish to generalize the use of this state-
ment by including it in a subroutine which will make
use of the information shown in Figure 9.4. 180-
y7> XR,YR aa 190 -
HR Figure 9.6 Defining a square to be plotted.
ee eat
SCREEN 1,0 : COLOR 1,1 : CLS
XR+WR,YR+HR
and then type
WR
XR = 200: YR = 140: WR = 50: HR= 10: F=
1: C=3: GOSUB 1000
Figure 9.4 Defining a rectangle by the upper left hand
corner and its width, WR, and height, HR. (The number as shown in Figure 9.7. Note that you can execute
of horizontal points plotted is WR+1 and the number of the statement GOSUB 1000 in the direct mode. This
vertical points plotted is HR+1.)
is very useful for testing subroutines.

In this figure the rectangle’s location is determined


by the coordinates of the upper left hand corner, and
the size is determined by the height and width. Figure k-209: ¥YR-14@:WR-5@:HR=1@: F=-1:C=3: GOSUB
9.5 contains an IBM PC BASIC subroutine that will 1666
Ok
draw a rectangle given the values XR, YR, WR, HR and a
C. The reason there are two LINE statements in the
subroutine, rather than one, is that we have allowed
for the rectangle to be either filled with color, or left
empty. If F=0 when the subroutine is “called” the
rectangle will be empty. If FO then the rectangle
will be filled. In either case the color is specified by
C3
Figure 9.5 Subroutine to plot a rectangle at a given location.
Ok
TS
1000 *THIS SUBROUTINE WILL DRAW
1001 *RECTANGLES GIVEN THE LOCATION OF
Figure 9.7 Drawing a horizontal bar using the subroutine
1002 *THE UPPER LEFT HAND CORNER AND
in Figure 9.5.
1002 *THE WIDTH, HEIGHT AND COLOR.
1004 *IT CAN BE FILLED OR LEFT EMPTY.
Loos" = Now to draw the bottom horizontal bar in Figure
TOTO ae) elie 9.6 type
LINE (XR, YR) —-(XR+WR, YR+HR),C,B
BESE
YR = 180 : GOSUB 1000
LINE (XR, YR) -(XR+WR, YR+HR) .C, BF as shown in Figure 9.8. Note that the values other
16020 RETURN
than YR are still as defined in the first line, thus they
Ok
don’t have to be changed to draw the bottom bar.
As an example of using this subroutine, to plot the To draw the left vertical bar that fits between the
top horizontal bar of the square shown in Figure 9.6 two horizontal bars, we must change YR, HR and
in white on a blue background, clear the screen to WR from their present values. Therefore, to plot the
blue by typing left vertical bar enter

76
2x 499: ¥R-14G: WR=50:HR=10: F=1:C=3:COSUB
1668
YR-180: GOSUB 1486
ok 1se@:cosuB 1000
Ok i5@:WR=1G:HR-3@:GOSUB 1088
? i88G

Figure 9.8 Drawing the bottom horizontal bar using the Figure 9.10 Drawing the right vertical bar of the ‘‘square.”’
subroutine in Figure 9.5.

RETURN without GOSUB in 1020


YR = 150 : WR = 10 : HR = 30 : GOSUB 1000
This would occur because the RETURN statement
as shown in Figure 9.9.
in line 1020 was executed, but the program got there
without first executing a GOSUB statement. It got
there because you forgot to include an END statement
at the end of the main program, so when the program
Qe 59g: ¥R=140: WR=5G:HR=10: F=1:C=3:GOSUB finished it just started executing the subroutine at line
1608
1000. You could also have used a STOP statement
$h-189: GosuB 18@@
in line 80 to terminate execution at that point. How-
¥YR-15@:4E2-i8:HE-36:GOSUR i@G8
Ok ever, the STOP statement would cause the message
BREAK in 80
to be printed on the screen when statement 80 was
executed. You should change the END to a STOP
and try this.

Figure 9.11 Program to plot a square.


10 *PLOTTING THE SQUARE GIVEN IN
20 *FIGURE 9.4
=O SCREEN 1,0: COLOR 1,1:CLS
40 XR=200: YR=140: WR=50; HR=10:F=1:C=3:
Figure 9.9 Drawing the left vertical bar of the ‘‘square.”” GOSUBR 1000
30 YR=180: GOSUB 10060
50 YR=150:WR=10;HR=30; GOSUR 1000
Similarly, to plot the right vertical bar, you only 79 XR=246; GOSUB 1000
have to type 80 END
ABs
XR = 240 : GOSUB 1000 100
1000 *THIS SUBROUTINE WILL DRAW
as shown in Figure 9.10. The program given in Figure 1001 *“RECTANGLES GIVEN THE LOCATION OF
9.11 includes all of the statements given above, and 1002 *THE UPPER LEFT HAND CORNER AND
100% *THE WIDTH, HEIGHT AND COLOR.
will plot the square when run. You should enter the 1004 *IT CAN BE FILLED OR LEFT EMPTY.
program and try it. 1005 *
In Figure 9.11 the END statement in line 80 is 1010 IF F = © THEN
required to prevent the program from continuing past LINE (XR, YR) —(XR+WR,
YR+HR) .C,B
ELSE
that point, which would execute the subroutine at line LINE (XR, YR) -—(XR+WR, YR+HR) .C, BF
1000. If the END statement in line 80 were omitted 1020 RETURN
you would obtain the error message Qk

77
XT = 160 : YT = 50 : HT = 100 : GOSUB 1500

This will place an equilateral triangle of height 100


in the center of the screen as shown in Figure 9.14.
The short length of program statements used to “call
the subroutine,” compared to the length of the state-
ments present in the subroutine itself, illustrates one
of the advantages of using subroutines; namely, that
the calling sequence is usually much shorter than the
subroutine. Thus you only write the subroutine once
and then call it as often as you like with shorter state-
ments.

F160: ¥1=50:HT=1@@: GOSUB 1588


Ok
Figure 9.12 Result of running the program in Figure 9.11.

Figure 9.13a is a second example of a subroutine.


This subroutine will draw an equilateral triangle given
the location of its vertex (XT,YT) and its height, HT,
as shown in Figure 9.13b. The subroutine contains
three LINE statements with each statement drawing
in one side of the triangle. The triangle is drawn in
the current foreground color.
To test this subroutine, enter it into the computer,
then in the direct mode of execution enter
SCREEN 1,0 : CLS
Figure 9.14 A sample run of the equilateral triangle
to get into medium resolution graphics. Now enter
subroutine.

Figure 9.13 Subroutine to draw an equilateral triangle given The graphic figure shown in Figure 9.15a can be
its vertex and height.
plotted using the subroutine given in Figure 9.15b.
Ok
All points in this figure are defined relative to the X,Y
Parcs)
1500 “THIS SUBROUTINE WILL DRAW AN coordinates of the “peak of the roof” and the height
1501 "EQUILATERAL TRIANGLE GIVEN THE of the roof. Lines 140-150 draw in the roof using the
1502 “LOCATION QF THE VERTEX triangle subroutine in Figure 9.13a. Lines 160-170 put
1503 "AND THE HEIGHT OF THE TRIANGLE.
in the side of the house, and lines 180-190 put in
1504 “THE TRIANGLE IS DRAWN IN THE
1505 “CURRENT FOREGROUND COLOR the door, both using the subroutine in Figure 9.5. Note
P5O6. = that line 200 is a RETURN statement. Study the sub-
1510 B = HT/TAN(S.141593/23) routine given in Figure 9.15b carefully and make cer-
taco RINE (XT. ¥ ti) Cxt+e, ¥ ith)
tain you understand how it draws the picture in Figure
PSO eer MEG ie, Yale Nie licteeai be)
1540 LINE (Xt—B, YT+HT) —(XT+B, YP+HT 9.15a.
1350 RETURN This subroutine must have valid values for X, Y,
Ok H and C before it is called. In order to test this subrou-
HT
tine, type it in as shown in Figure 9.15b. Add the
2 XT B= TAN 60° rectangle and triangle subroutines in Figures 9.5 and
wae 9.13. Then clear the screen to black by typing
~ TAN(7/3) SCREEN 1,0 : COLOR 0 : C=3 : CLS. Now type
X = 100 : Y = 50: H = 20 : GOSUB 100
HT This should display the figure shown in Figure 9.16
in white on a black background. You should save this
<0) [co program unit for reference later in the chapter.
XT-B,YT+HT — |-— 8B —+|{“~ xT+B,YT+HT Now that you know that the subroutine works, you

78
Figure 9.15 (a) Definition of graphic figure (b) Subroutine NEXT loop. This loop will produce the following
to plot the figure in (a). twelve pairs of values for X and Y:
(a) yen KY Xx Y

50 0
100 0
150 0
200 0
250 0
300 0
50 100
H 100 100
150 100
200 100
250 100
ae 250 100
4 300 100

These twelve pairs of values will correspond to the


\ | coordinates of the peaks of the roofs for all twelve
houses.
b}—H— |
Figure 9.17 Program to plot twelve houses on the screen.
Ore 1 “FROGRAM TO DRAW TWO ROWS OF HOUSES
LIST —200 2 *WITH SIX HOUSES IN EACH ROW
1900 *“DRAW A SMALL HOUSE WITH THE 2) SSERE EIN os CeCe
CH ey alee
esi mes
110 "PEAK OF THE ROOF AT X,Y. PMP evairk toes acs
P20 ideo ee Or THe HOUSE DEPENDS UPON = FOR Y = © TQ 100 STEP 100
ThESG) TG Se Acre et te aels 10 FOR xX = 50 TO 200 STEP 5a
140 XT=X:s YT=Y: HT=H: 12 GOSUR 100
150 GOSUB 1500: “FUT ON ROOF 15 NEXT Xx
160 XR=X-H/2: YR=Y¥+H:WR=H: HR=HK2:s F=0 17 NEXT Y
(A ELC EIS US TS, PEAae IN SB te 20 END
180 XR=X-H/4s YR=Y+tHK2: WR=H/2: HR=Hs F= ey °
iL fe. 3
190 GOSUB 1000: “FUT ON THE DOOR 1900 “DRAW A SMALL HOUSE WITH THE
290 RETURN 1160 “PEAK OF THE ROOF AT X.Y
Ok 140 XT=Xs YT=Y: HT=H:
: : : F 150 GOSUB 1500: “FUT ON ROOF
can plot multiple houses by simply calling this subrou- 160 XR=X-H/2: YREY+H:WREH: HR=HK2: F=0
tine several times with different values for X and Y. 170 GOSUB 1000: “PUT ON SIDE
The program shown in Figure 9.17 calls the statement 180 XR=X-H/4: YR=Y+Hk2: WR=H/2: HR=H: F=1
GOSUB 100 twelve times using a nested FOR... Bie Sone and ON ne ae

Figure 9.16 Test of subroutine given in Figure 9.13b.


You should type in the program shown in Figure
9.17, add the rectangle and triangle subroutines, and
186
run it. (If you saved the program used in Figure 9.16,
2*, aa: ¥=50:H=20: GOSUB
Ok sd you only need to add lines 1-25.) The result of execut-
ing this program is shown in Figure 9.18. Modify this
program so as to plot only four houses.

Plotting Different Size Figures

In addition to making the location of a figure variable,


you can also change the size of a figure. For example,
in Figure 9.15a the size of the house is completely
determined by the value H. If H is changed, the size
of the house will change. As we have seen in Figure
9.18, the location of the house can be changed by vary-

79
Figure 9.20 Program to plot different size houses.
1 *DRAWING HOUSES OF DIFFERENT SIZE
2H=8
% SCREEN 1,0: COLOR 0,1: CLS
4 FOR Y = 0 TO 110 STEP 55
5 FOR X = 50 TO 300 STEP 50
190 GOSUB 100
15 NEXT X
16 H = H+t8
7 NES,
20 END
100 “DRAW A SMALL HOUSE WITH THE
110 “PEAK OF THE ROOF AT X,Y
140 XT=X: YT=Y: HT=H:
150 GOSUB 1500: “FUT ON ROOF
160 XR=X-H/2: YR=Y+H:WR=H: HR=HX2: F=0
170 GOSUB 1000: “FUT ON SIDE
180 XR=X-H/4: YR=Y+HK2: WR=H/2: HR=H: F=1
190 GOSUB 1000: “FUT ON THE DOOR
200 RETURN
Figure 9.18 Result of executing the program given in Figure
SM 1000 IF F=0 THEN
LINE (XR, YR) -(XR+WR, YR+HR), 48
ELSE LINE CXR, YR) —(XR+WR, YR+HR). , BF
ing the values of X and Y. Thus, it is possible to place
1010 RETURN
a house of any size at any location on the screen. 1500 “THIS SUBROUTINE WILL DRAW AN
To try this, load the program given in Figure 9.15 1501 “EQUILATERAL TRIANGLE GIVEN THE
back into memory. Now clear the screen to blue in 1502 “LOCATION QF THE VERTEX
1503 *“AND THE HEIGHT OF THE TRIANGLE.
medium resolution graphics by entering:
1504 “THE TRIANGLE IS DRAWN IN THE
SCREEN 1,0: COLOR 1,1: CLS 1505 “CURRENT FOREGROUND COLOR
1506 *
Now enter 1510 B = HT/TAN(S3. 141593 /53)
1320 LINE (XT, YT) —(XT+H, YEU+HT)
C=3: X=100: Y=30: H=48: GOSUB 100 1380 LINE CXT.AYT)—(XT—BaYI+HT)
1540 LINE (XT—-H, YT+HT) —(XT+H, YT+HT)
This should display the large white house on a blue 1550 RETURN
background as shown in Figure 9.19. Ok
You can plot multiple houses of different sizes by
calling the subroutine in Figure 9.15b with different will be different. This is accomplished by changing
values of H. For example, the program shown in Figure H to H+8 each time a new row is displayed.
9.20 will plot three rows of houses. Each row will You should type in this program by adding lines
have 6 houses, and the size of the houses in each row 1-20 to the subroutine in Figure 9.15b. When you

Figure 9.21 Result of running the program shown in Figure


Figure 9.19 Drawing a larger house. 920)

2k, - x-100: ¥=30: H=48 : GOSUB 1@@


Ok

80
run the program you should obtain the figure shown Lines 10 through 200 in Figure 9.23 give the sub-
in Figure 9.21. routine that will plot the name HAL. This subroutine
calls the rectangle program from Figure 9.5, which
EXERCISE 9.1 is included in Figure 9.23 in lines 1000 to 1020. The
Write a program that calls the triangle subroutine in subroutine in lines 10-200 has comments at the end
Figure 9.13 in such a manner that you generate concen- of each GOSUB statement to indicate which of the
tric triangles. nine rectangles is being plotted by that particular call.

PLOTTING YOUR NAME Figure 9.23 Program to plot the name HAL at different
locations with different sizes.
You can use the ideas described in the previous sections 10 "THIS SUBROUTINE WILL DRAW THE NAME
20 ""HAL" ON THE SCREEN. THE SIZE AND
of this chapter to plot your name anywhere on the 20 “LOCATION QF THE NAME CAN BE CHANGED
screen using letters of varying sizes. The trick is to 40 *BY CHOOSING DIFFERENT VALUES FOR
define the location of the name in terms of the X,Y SO) 7 ieline CAINPOD AN) Seteatilei=s qe ise) (yay
ei iStp)
60 *
coordinate of its upper left-hand corner, and define
65 COLOR 0,1:C=3
the size of the name in terms of the width and height 7O XR=X: YREY:M=2¥N: H=2RM+N
of each letter. Then you can plot the name wherever 74 ¥
you want by using subroutines. TAS *FLOT VERTICAL BARS
7& 5
As an example, Figure 9.22 shows the layout that
80 XR=X: YR=Y:HR=H:WR=N:GOSUB 10060: “#1
can be used to write a subroutine that will draw the 90 XR=XR+M4+N: GOSUBR 1000: *#3
name HAL using only rectangles. The rectangles will 100 XR=XR+M+N: GOSUR 1000: *#4
be drawn using the subroutine in Figure 9.5. It takes 110 XR=XR+M+N: GOSUB 1000: *#7
a total of nine rectangles to draw the name. Each of 120 XR=XR+RM+N: GOSUB 1000: "#3
120
these rectangles has been labeled in its upper left hand 140 *NOW FLOT HORIZONATL BARS
corner so that it can be referred to in the program A Oy s
that will draw it. Note that the coordinates of the 155 HR=N: WR=M
upper left hand corner of any rectangle can be obtained 160 XR=X+N: YR=Y+M: GOSUB 1000: “#2
170 XR=XR+2*(M+N) =GOSUB 1000: *#6
by knowing the single coordinate (X,Y). For instance 180 YR=Y:GOSUB 1000: "#5
point #6 (the middle bar in the A) is located at:
190 XR=XR+2% (M+N) s YREYR+24M: GOSUB 1000:
X coordinate of point 6: X+3*N+2*M *#8
Y coordinate of point 6: Y+M 200 RETURN
1000 *THIS SUBROUTINE WILL DRAW
Note also that the size of each letter is proportional 1061 *“RECTANGES GIVEN THE LOCATION OF
to N: 1002 *THE UPPER LEFT HAND CORNER AND
1603 *THE WIDTH, HEIGHT AND COLOR.
Height of all letters = 2*M+N = 7*N 10045 it CAN) BE VE TERED GReEERT Ene RY -
Width of H and A = 2*N+M = 5*N 1005
Width of L =M+N =4*N 1010 IF F = 0 THEN
LINE (XR, YR) —(XR+WR,
YR+HR) ,C,B
Thus, the location of the upper left hand corner of ELSE
the name is determined by (X,Y) and the size of the LINE (XR, YR) -(XR+WR, YR+HR) ,C, BF
1020 RETURN
name by N.
Ok

Figure 9.22 Layout of pattern for drawing the name HAL


All vertical rectangles are drawn first, and then the
using rectangles.
horizontal ones. To plot the name at a given location
(X,Y)
you must specify the following items before a call to
1 3 4 5 7p 8
line 10 is made:
M ] M = 3*N
| | 2
1. The X and Y coordinates of the upper left hand
N corner of the name.
Wa Mie 9 2. The value of N, which will determine the size
bly of the name.
= 3. The value of F, which will determine
the name is solid (F=1) or merely outlined (F=0).
whether

81
o* 1g: v-7@:N=5:F=1:GOSUB 19
ok F=@: GOSUB 1@
Q* ga: ¥=15@:N=3:
¥-1 80: N=1 :F= 1:GOSUB 18
Oy s@:
Ok

Figure 9.24 Drawing the name HAL in solid rectangles. Figure 9.26 Adding a much smaller HAL.

As a specific example, if you enter the subroutine given and you'll get the output shown in Figure 9.26. You
in Figure 9.23 into your IBM PC and then enter should enter the program from Figure 9.23 and make
certain this works as indicated. You should also review
SCREEN 1,0 : CLS
the way that each rectangle was positioned to form
followed by the name HAL, so that you can draw other names
as well.
X=10: Y=70:N=5:
F=1: GOSUB 10
You could write a main program that would draw
you will get the output shown in Figure 9.24. If you the three names shown in Figure 9.26 by starting the
now enter main program at line 2000 and adding the statement

X = 100: Y= 150: N=3: F = 0: GOSUB 10 5 GOTO 2000


you will get a smaller version of HAL that is below (see Exercise 9.5).
and to the right of the first one. This one will be out-
lined (F=0), rather than filled. This output is shown
in Figure 9.25. If you want a small version of HAL, A COMMENT ON SCALING FIGURES
enter
In Figure 9.15 the house was defined as having a door
X = 250: Y = 180: N=1: F= 1: GOSUB 10 of width H/2 and height H located at XR=X—H/4,
YR=Y+H*2. Thus, both the size of the door, and
Figure 9.25 Adding a smaller version of HAL in outline its location, were completely specified by the values
form.
of X, Y and H. However, if a value of H is picked
that is not evenly divisible by both 2 and 4, then the
size of the door could be off, and its location could
be “out of place.” This is due to the fact that points
2, g: v=70:N=5:F=1:GOSUB 19
designated in the screen units must be integers. If they
2% ga: v=150:N=3: F=@: GOSUB 18
Ok aren’t, they are rounded to the nearest integer when
used. If you would call the subroutine in Figure 9.15

HAL
with H=15, you would find that the door is not in the
center of the house, but is to the left side of the house.
A better plan is to make the smallest dimension
on the figure an integer and then scale upward from
that point. For instance, if the width of the door were
chosen as K (an integer), then the height of the door,
HAL and the height of the roof, and the width of the house
would all be H=2*K. The height of the side of the
house would be 4*K. The subroutine that draws the
house could then be written in terms of K, so that

82
when the subroutine is called K is specified as an in-
teger and all other dimensions and locations will also
be integers. This method was used in Figure 9.22,
where all dimensions were scaled upward from the
width of a side of a character, N.

EXERCISE 9.2
Write a program that will plot your name at two differ-
ent locations on the screen. The size of the two names
should be different.

EXERCISE 9.3
Rewrite the subroutine in Figure 9.15 using the follow-
ing scaling:
Jy] an | an |an |an ||
Door width = K
Roof height = 2*K
Side width = 2*K
Side height = 4*K
EXERCISE 9.5
EXERCISE 9.4 Add a main program at line 2000 to the subroutines
Write a program using the subroutines in this chapter in Figure 9.23 that will plot the name HAL four times,
that will draw the following figure. each a different size.

83
MAKING BAR GRAPHS:
LEARNING ABOUT READ . . . DATA

You know three ways to assign a value to a memory ment (in the indirect mode) and then using the READ
cell name. One is to use an assignment statement such and RESTORE statements in the direct mode.
as A=3. The second is to use an INPUT statement Type in the following statement
such as INPUT A. The third is to use the INKEY$
10 DATA 5,10
function as in AS=INKEYS$. In the last two cases the
value is entered through the keyboard. and then type
In this chapter you will learn another method of
READ A
assigning values to memory cell names. The values
to be assigned are stored in the program in DATA 2A
statements. They are assigned to memory cell names READ A
by using a READ statement. 2A
In this chapter you will learn
READ A
1. to use the READ, DATA, and RESTORE state-
as shown in Figure 10.1. The first time you typed
ments,
READ A the first data value in the DATA statement
2. to make horizontal bar graphs,
(5) was stored in A. The second time you typed READ
3. to make vertical bar graphs containing multiple A the second data value in the DATA statement (10)
bars, and was stored in A. The third time you typed READ A
4. to scale and label bar graphs. an error message, Out of DATA, was displayed. This
error message was generated because there were no
more data values in the DATA statement to use.
THE READ, DATA, When a program is executed a pointer points to
AND RESTORE STATEMENTS the first data value in the DATA statement. (More
than one DATA statement in a program are treated
The DATA statement must be used in the indirect as a single long DATA statement.) As data values
mode. Although the READ and RESTORE state- are “used up”’ by being read in READ statements the
ments are normally used in the indirect mode, we will pointer keeps moving along to the next unused data
illustrate their use by storing data in a DATA state- value. If the pointer gets to the end of the data values

84
Figure 10.1 The READ statement reads successive values in B and C respectively. Note that the value of A
from a DATA statement.
remains unchanged and is still equal to 5.
Ok
190 DATA 5,10
Now add the second DATA statement
READ A
20 DATA 20,25,30
This will automatically restore the pointer to the first
data value (5) in line 10. Type the following statements
as shown in Figure 10.3.
READ A,B,C,D
? A,B,C,D
READ A,B,C
Qut af DATA
Ok
Figure 10.3 There must be data values for a//
variable names in a READ statement.
Ok
in the DATA statement and another READ statement SiESt
is executed, then the Out of DATA message will be 10 DATA 5,10,15
20 DATA 20,25,
20
displayed.
Ok
At any time the pointer can be reset to the first READ 4,8,C,D
data value in the DATA statement using the statement Ok
?0,8,C,D
RESTORE 5 10 ile
20
Also, more than one value can be read with a single Ok
READ statement. In order to see this, type in the READ 4,8,C
following statements Out of DATA
Ok
10 DATA 5,10,15
READ A,B,C
Note that the two DATA statements are treated as
? A,B,C one long DATA statement. DATA statements may
RESTORE occur anywhere in a program. They are effectively
READ B,C combined into one long DATA statement in the order
? A,B,C in which they occur in the program. In the last READ
statement in Figure 10.3, although there are values
as shown in Fig. 10.2. for A and B (25 and 30), there is no value for C and
Note in this case that the first READ statement therefore the Out of DATA message is displayed.
stores the values 5, 10, and 15 in A, B, and C respec- Strings can be included in a DATA statement. In
tively. The RESTORE statement then moves the this case the corresponding variable name in the
pointer back to the first data value (5). Therefore, the READ statement must be a string variable. For exam-
next READ statement will store the values 5 and 10 ple, change the DATA statement in line 20 to
20 DATA ACE, “ROCHESTER, MI”
Figure 10.2 The RESTORE statement moves
the pointer to the first data value in the DATA and then type
statement.
Ok
READ A,B,C,A$,B$
10 DATA 53,16,15 ? A,B,C,A$,BS
READ A,B,C
Ok as shown in Figure 10.4. Note that the string ACE
ee TAN ele in the DATA statement does not have to be enclosed
La 16 bey
between quotation marks. However, strings containing
Ok
blanks, commas, and colons must be enclosed between
RESTORE
Ok quotation marks. Note also that the numerical varia-
READ B,C bles A and B are completely different memory cells
Ok from the string variables A$ and B$. The IBM PC
= (Aire sal
5 = Lo will not get these mixed up.
Ok The IBM PC has a second version of the RESTORE

85
Figure 10.4 String variables can be used in If you do this and then type
a READ statement to read strings ina DATA
statement. READ A,B,C
Ok ? A,B,C
List
190 DATA 35,10,15 You will get 20, 25 and 30 as the output values. This
20 DATA "ACE", "ROCHESTER, MI" sequence is shown in Figure 10.5.
Qk
READ A,#B,C,AS,BS
The READ and DATA statements are particularly
Ok useful when you have a list of data whose values are
7A,B,C, AS, RF known prior to program execution, and do not vary
ra) 10 1S from one execution of the program to another. Exam-
ACE ROCHESTER. MI
Ok
ples of using the READ and DATA statements will
be given in the following sections.
statement that allows you to move the DATA pointer
to the beginning of any particular DATA statement HORIZONTAL BAR GRAPHS
rather than just the first one. This statement has the
form Bar graphs are very useful for providing a quick visual
picture of the relative sizes of various quantities. You
RESTORE line can plot a bar graph on the IBM PC by plotting a
where line is the line number of the data statement
horizontal bar (rectangle) whose length is proportional
where you wish the pointer moved. As an example,
to the quantity of interest. The bars can be drawn
enter the following statements: using a rectangle subroutine similar to that developed
in Chapter 9 (see Figure 9.5).
10 DATA 5,10,15 As an example, suppose you want to compare graph-
20 DATA 20,25,30 ically the four values 120, 250, 50, and 170. You can
READ A,B,C,D plot four horizontal bars with lengths 120, 250, 50,
? A,B,C,D and 170 using the program shown in Figure 10.6.
In this program line 20 is a DATA statement that
The READ statement will read the values 5, 10, 15 and contains the lengths of the four bars to be plotted.
20 from DATA statements 10 and 20 and assign them Line 30 sets the height of each bar at 10 grid units.
to variables A, B, C and D. The DATA pointer is left Line 40 sets the color C to white. Line 45 sets F to
pointing to the value 25 in statement 20. If a RE- 1 so the bars will be filled, rather than just outlined.
STORE statement were executed at this point, the Line 50 defines the beginning of each bar to be at
pointer would go back to the beginning of the first XR=0. Lines 60-90 form a FOR . . . NEXT loop
DATA statement in the program, or line 10 in this that is executed once for each bar to be plotted (4 in
program. If, however, you wish the pointer to go to this case).
the start of line 20, you should enter Within this loop line 70 reads the next length from
RESTORE 20 the values given in the DATA statement and stores
this length in the memory cell WR. A bar containing
WR grid units is then plotted in line 80 by using the
Figure 10.5 Example of using a RESTORE /ine
statement. subroutine at line 1000, which is a slight modification
Ok of the rectangle subroutine that we introduced in Chap-
EUS ter 9. Note that the horizontal length of the bar is
10 DATA 5,10,15 (XR+WR-1)—XR+1=WR. In general, a rectangle
20 DATA 20,25,20
Ok
plotted using the LINE statement that has a side speci-
READ 4,8,C,.D fied as going from XR to XR+WR, has WR+1 grid
Ok units in its composition. Thus if we actually want only
7A,8,C,D WR units we must subtract one. For this same reason,
= 16 1S
20
line 1007 was added so that we don’t draw a bar one
Ok unit high when the bar should be zero units high. If
RESTORE 20 WR=0, then a RETURN is made with no LINE state-
Ok ment getting executed.
READ 4,8,C
Ok
Note that the END statement in line 100 is neces-
7AARAC sary to prevent the program from executing line 1000
20 Saal} SO again. (This would produce the error message ?RE-
Ok TURN without GOSUB in 1020.)

86
Figure 10.6 (a) Program to plot four bars of lengths 120, ’ TABLE 10.1 Population of
250, 50, and 170 (b) Result of running the program in (a). the New England States
‘10 *PROGRAM TO DRAW A BAR GRAPH
15 SCREEN 1,0:COLOR 0,1:CLS State Population
20 DATA 120,250,50,170 ME 993663
25 DEFINT C,FaHsWy X,Y NH 737681
30 HR = 10: "HEIGHT OF BARS VT 444732
40 C = 3: *COLOR OF BARS IS WHITE MA 5689170
45 F = 1s "BARS WILL BE FILLED CT 3032217
TO XR = Os “LEFT BORDER FOR BARS RI 949723
60 FOR YR = SO TO 140 STEP Zo
7QO READ WR
80 GQOSUR io0o
Lines 200-250 are six DATA statements containing
90 NEXT YR the information in Table 10.1. Note that each DATA
100 END statement contains a string (the name of the state)
1000 "THIS SUBROUTINE WILL DRAW A and a numerical value (the state’s population). For
1OO1 “BAR THAT IS A GIVEN NUMBER OF
1002 “GRID UNITS
each pass through the FOR . . . NEXT loop (lines
IN LENGTH. THE CALLER
1003 “MUST SPECIFY THE UPPER L-H CORNER 60-90) line 70 stores the next state name in STATES
1004 *“AND THE WIDTH,HEIGHT AND COLOR. and its population in P.
1005 "IT CAN BE FILLED OR LEFT EMPTY. Each bar plotted by the subroutine starting in line
1006 *
1000 will represent a certain number of people. In
100? IF WR il QO THEN RETURN
order to insure that the longest bar will fit on the
1007 IF WR = © THEN RETURN screen, the length of each bar must be scaled so a
MOO = Oe TEN given number of people is equivalent to a given number
LINE (XR, YR) -(XR+WR-1, YR+HR),C,B
EBESE
LINE (XR, YR) -(XR+WR-1,YR+HR) .C, BF Figure 10.7 Program to produce a bar graph of the data
1020 RETURN in Table 10.1.
Qk 10 *FLOT FOPULATION BAR GRAFH
la SCREEN 1, Os GOROR OL sees
20 LOCATE 1,5
21 PRINT "POPULATION OF NEW ENGLAND STATES”
25 DEFINT CaF aHadyNaWaXe¥
20 HR = 8: “HEIGHT OF BARS
490 C = S: "COLOR OF BARS IS WHITE
45 F = 1: "BARS WILL BE FILLED
oO XR = 193 “LEFT BORDER FOR BARS
a3 N = 6: “NUMBER OF BARS TQ FLOT
60 FOR J = 170 N
7O READ STATES,F
74 WR = F/1000000!*48
7s LQCATE Jk2+1,1
76 PRINT STATES
77 YR = Jk*24
80 GOSUB 1000
90 NEXT J
1600 GOTO 100
200 DATA ME, 992663
210 DATA NH, 737681
220 DATA VT,444732
220 DATA MA, 3689170
240 DATA CT, 3032217
The basic ideas shown in Figure 10.6 can be used 250 DATA RI,949725
1000 “THIS SUBROUTINE WILL DRAW A
to produce useful bar graphs of real data as illustrated
1001 “BAR THAT IS A GIVEN NUMBER OF
in the following section. 19002 *GRID UNITS IN LENGTH. THE CALLER
Loos “MUST SPECIFY THE UPPER LE-H CORNER
1904 *AND THE WIDTH,HEIGHT AND COLOR.
HaoSe 2 CANS RE A reEEE DOR TERT EME.
Population
1ODS ~*
of the New England States 1907 TF WR = © THEN RETURN
OMG S (Sta ee dials]
The populations of the six New England states are LINE (XR, YR) -(XR+WR-1, YR+HR),C,B
BESE
shown in Table 10.1. The program given in Figure
LINE (XR, YR) -(XR+WR-1, YR+HR) ,C, BF
10.6 has been modified as shown in Figure 10.7 to 1020 RETURN
plot six bar graphs of the data in Table 10.1. Ok

87
of horizontal grid units. The state name will be printed
to the left of each bar. This will use two character
POPULATION OF NENW ENGLAND STATES
positions or sixteen horizontal grid units. We will start
the bars in position 19. Therefore, the longest possible
bar is 300 units long. The maximum population is
that of Massachusetts, 5689170. Therefore, each grid
unit must represent more than 5689170/300=18964
persons. Looking ahead to the next section, where a
printed scale will be added to the bottom of the screen,
it is important that an even number of millions of
population corresponds closely with an even number
of character positions on the screen. Since each charac-
ter position takes eight grid units, the population scale
factor was chosen as
48 grid units/1000000 population
or Figure 10.8 Result of running the program shown in Figure
1OX7:
6 character positions/1000000 population

or with the places where state names could be printed.


You must keep in mind that characters must be printed
20833 population/grid unit
in fixed screen locations.
This means the longest bar in the bar graph will be
5689170/20833=273 grid units long, which will go
nearly all the way across the screen. Adding a Scale
Given a population P, line 74 calculates the number
of grid units to be plotted (i.e. the length of the bar), Although the bar graph shown in Figure 10.8 illus-
WR. In the equation trates the relative size of the six state populations, it
does not provide any information on the actual values
WR = P/1000000
* 48
of these populations. We can correct this by adding
WR will be rounded to the nearest grid unit, inasmuch a scale to the bottom of the graph.
the IBM PC automatically rounds off when a real num- Since each 48 horizontal grid units represent a popu-
ber is assigned to an integer. Note that the number lation of 1000000, then six character positions will
of grid units plotted in the subroutine starting at line represent one million people. A subroutine that prints
1000 will be equal to the value of WR generated by such a scale is shown in Figure 10.9. This subroutine
this equation. In line 74 the BASIC system placed is called in line 95 of the revised main program shown
an exclamation point (!) after the number 1000000 to in Figure 10.10. The result of executing this new pro-
indicate that this number was stored as a single preci- gram is shown in Figure 10.11.
sion number rather than as an integer. Integers must
have a magnitude less than 32768 in order to be stored Figure 10.9 Subroutine to display scale.
in integer format. Ok
Line 15 clears the screen to black. Lines 20 and LIST 400-320
21 print the title to the graph. During each pass 400 °
410 * SUBROUTINE TO ADD SCALE
through the FOR . . . NEXT loop (lines 60-90) lines
75 and 76 print the name of the state on the left hand
420 *
425 LOCATE 21,3
border, and then lines 77 and 80 place the bar for NSSON TaN | Hepsi
that state just to the right of the name. The result 440 FOR J = 1 TO 6
of running this program is shown in Figure 10.8. 450 PRINT "--+--+";
Before leaving this problem, it should be pointed
460 NEXT J
480 LOCATE 22,3
out that the height of the characters printed was corre- 490 PRINT "O "s
lated with the height of the bars. Each character SOG) ei fai) ccaminet ment (ly ccorsibs Reunite AAS
ST EO CIE cl;
printed on the screen takes up space that is eight grid
os10 LOCATE 24,10
units high (as well as eight grid units wide). The height
a20 PRINT “MILELTONS OF PEOPLE";
of each bar (HR+1) was set in line 30. The location o20 RETURN
of the bars (J*24 in line 77) was picked to coincide Ok

88
Figure 10.10 Revised main program that calls
subroutine to add a scale.
Plot 2 horizontal grid lines,
10 *PLOT POPULATION BAR GRAFH @ y=145 and y=146
15 SCREEN 1,0:COLOR O,1:CLS
20 LOCATE £,5
Plot 1 horizontal grid line,
21 PRINT "POPULATION OF NEW ENGLAND STATES" eoa} @ y=146
fe

22) DER Nie Cae atta ag Wika Os 8


BC
20 HR = 8: “HEIGHT OF BARS eo
ee Oe Plot no horizontal grid lines
40 C = Bs “COLOR OF BARS IS WHITE =
om)
oO
te o +
4.5)- fenroeenls “BARS WILL BE FILLED Lo
6 £ ya { Plot 1 horizontal grid line,
oO XR = 193 “LEFT BORDER FOR HBRARS @ y=147
oo Mrs Gs “NUMBER OF BARS TO FLOT
60 FOR J = 1 TO N Plot 2 horizontal grid lines,
790 READ STATES,F @ y=147 and y=148
74 WR = F/1000000!*48
7a LQCATE JxS+i,1
76 PRINT STATES
Figure 10.12 Screen layout for plotting a vertical bar with
77 YR = 9*24
length proportional to the value V made with horizontal
86 GOSUR 1000
grid lines.
90 NEXT J
95 GOSUB 400
100 GOTO 100 Figure 10.12 shows the ranges of values for which
200 DATA ME, 993643
210 DATA NH, 737681
various numbers of grid units will be plotted. The bot-
220 DATA VT, 444732 tom of grid row 146 on the screen will define the “zero”
220 DATA MA, 5689170 value of V. From Figure 10.12 you see that a value
240 DATA CT, 3032217 of V between 0.5 and 1.5 will result in a bar one grid
2590 DATA RI,949723
line high being plotted in row Y= 146. Similarly, a
value of V between -0.5 and -1.5 will result in a bar
one grid line high being plotted in row Y=147.
The subroutine to plot a vertical bar of color C
POPULATION OF NEW ENGLAND STATES
the correct number of grid units high at X=XR is
given in Figure 10.13. In order to make certain the
subroutine does what we think it does, we will check
several values. If V=O the IF statement in line 2010
will RETURN to the calling program without printing
anything, which gives a bar of zero height. If V=3,
the THEN side of the IF. . . THEN. . . ELSE con-
struct in line 2020 will draw a rectangle with Y coordi-
nates going from Y=147—V=147—3=144 to Y=146.
This is three grid units high (144,145,146), as it should
f-—$-—~4~~—4#-——4--4--4--—4-—-4
~~ 4-4 be. If V=—3, the ELSE side of the IF . . THEN
8 i 2 3 4 es 6 . . . ELSE statement in line 2020 will be executed.
MILLIONS OF PEOPLE This will draw a rectangle with Y coordinates going
from Y=146—V=146+3=149 to Y=147, which is

Figure 10.11 Result of running the program shown in Figure


Figure 10.13 Subroutine to plot positive and negative
10.10.
vertical bars of length V and width 8.
Ok
Elen
VERTICAL BAR GRAPHS 2000 *“SUBROUTINE TO PLOT VERTICAL BARS
2001 *THAT CAN BE EITHER FOSITIVE OR
In addition to the horizontal bar graphs described 2002 “NEGATIVE. THE BAR WILL BE V
200s sUN EES! EN EENGTE LN, Celene
above, you can draw vertical bars by using a minor
2004 *LOCATED HORIZONTALLY AT X = XR
variation on the same rectangle subroutine. The sub- ZOOceas
routine needs to be changed so that the width of the 2010 IF VY = © THEN RETURN
bar stays fixed, but its height varies from call-to-call. AUTO) IGS WE BO) Vite)
LINE (XR, 147-V) -(XR+7,146),C,BF
Suppose you want to plot a vertical bar with a length
ELSE LINE (XR, 146-V) -(XR+7,147),C,BF
proportional to the value V. The value of V can be
either positive or negative. For a negative value of V 2030 RETURN
the bar should be plotted in the negative direction. Ok

89
again three units high (147,148,149) and in the negative
direction. It is negative since it is below the Y=146
line on the screen. ok, - R= 200; V=16@0: GOSUB
2806

To check on the effects of round-off if V is not an Sheers -U-- 28:G OSUB 2608
Ok
integer, assume that V=—1.3. In this case, the Y coor-
dinates of the rectangle generated in the ELSE side
of the IF ... THEN .. . ELSE statement in line
1020 would be Y=146—V=146—(-1.3)=147.3 to
Y=147. The 147.3 will be rounded off to 147, so the
Y coordinates of the upper and lower side of the rectan-
gle are both 147. This is simply a line, or a rectangle
one unit high and negative. This, again, is as it should
be.
In order to test this subroutine type it in as shown
in Figure 10.13. Then clear the screen to black in me-
dium resolution graphics by typing
Figure 10.15 Adding a negative bar to Figure 10.14.
SCREEN 1: CLS : COLOR 0,1
Then type To add a negative bar, type
=3:XR=200:V=100: GOSUB 2000 XR=XR+8: V=—20: GOSUB 2000
You should obtain the result shown in Figure 10.14. as shown in Figure 10.15.
We will now use this subroutine to plot a “multiple”
bar graph that will display five years of economic data.

ok,. wR=200:U=100:GOSUB 2080


Ok
Multiple Bar Graph
for “The Economy”

In this section we will develop a program to plot a


“multiple” bar graph of the economic data given in
Table 10.2. For each year we will plot four bars, one
for each economic factor. The four bars will be plot-
ted in three different colors. Colors to be used are given
in Table 10.3. The background will be black. The main
program for plotting this bar graph is shown in Figure
10.16.
Line 20 clears the screen to black. Lines 30-50 de-
Figure 10.14 Testing the subroutine given in Figure 10.13.
fine the three colors C1—C3 given in Table 10.3. Lines

TABLE 10.2 Economic Data

1976 1977 1978 1979 1980


Inflation 4.7 6.8 9.0 13.3 18.2 Jan. change at
% change in C.P.I. compound an-
nual rate
Unemployment 7.8 7.0 6.0 5.8 6.2 Jan.
% of civilian labor
force
Growth 4.8 5.8 4.9 0.8 lez, Projected 1st Q.
% change in real
G.N.P.
Personal Income 2.8 4.5 3.4 —0.8 ==On Projected 1st Q.
% change per capita
SOURCE: 7/ME, March 10, 1980, p. 67.

90
TABLE 10.3 Colors Used in Economy Bar Graph Figure 10.17 Subroutine to plot the next four bars of the
graph.
Color
Inflation 200 "PLOT FOUR VERTICAL BARS
GA: Cyan
216 "WITH A SCALE INCREASE OF 3S
Unemployment C22 Magenta 220 READ I,.U,G,M
Growth C3 White Say = Daas C=) Gi
Personal Income Cr Cyan 240 KR=XR+8
250 GOSUB 2000
260 VY=UKS: C = C2
Figure 10.16 Main program for plotting economy bar 270 XR=XR+8
graph. 280 GOSUR 2006
Ok 290 V=GkS: C = Cs
EISt, =Ta0 200 XR=XR+8
10 *THE ECONOMY 216 GOSUB 20600
13) DEFIANT €, 52x 220 VYV=MkKS: C = Cl
20 SCREEN 1,0:€LS: COLOR 0, 1 230 XR=XR+8
20 Ci=i: *CYAN 240 GOSUBR 2000
40 C2=2: *MAGENTA 256 XR=XR+32
30 CS3=3: “WHITE 260 RETURN
60 DATA 4.7,7.8,4.8,2.8 Ok
70 DATA 6.8,7.0,5.8,4.5
80 DATA 9.6,6.6,4.9,2.4
ee MEET Ese Vin he tte Cle tte Ao each bar is 8 vertical grid units wide.) Lines 260-280
SACI be i ei ee Lee go al plot the magenta unemployment bar. Line 300 moves
Pie xn. —) aes OSE LER T RARDER
to the next column and lines 290-310 plot the white
PAGER. So Ee
130 GOSUB 260: “PLOT 4 BARS
growth bar. Lines 320-340 plot the cyan income bar
1406 NEXT J } in the next column. Line 350 increases the column
150 GOSUB 466:*PLOT HEADINGS number XR by 32. This will leave a four-column (four
160 GOTO 160 character) space between each group of four bars.
Qk
The subroutine to display the years and heading
is shown in Figure 10.18. Lines 410 and 420 print
60-100 are DATA statements containing the data the five years under the appropriate bar graphs. Lines
given in Table 10.2. Note that each DATA statement 430 and 440 print the title of the graph and lines 450—
contains the data for one year starting with 1976. The 520 print a scale along the left side of the screen. Lines
value of XR is initialized to 11 in line 110. This is 530-560 place a legend under the title to explain the
the column number in which the first bar will be plot- bar colors.
ted. The FOR . . . NEXT loop in lines 120-140 is The entire program to plot the economy bar graph
executed five times (once for each year). Each time is given by the statements in Figures 10.13, 10.16,
through this loop four bars are plotted, corresponding
to the data for that year. This is done in a subroutine Figure 10.18 Subroutine to display heading and scale.
starting at line 200. Line 150 calls a subroutine at LIST 400-570
line 400 that prints the heading and scale for the graph. 400 *DISPLAY YEARS AND TITLE
Line 160 branches on itself to prevent the cursor from 410 LOCATE 21,1
being displayed. 420 PRINT " 1976 UBS EEL 1978 197
9 1980";
The subroutine to plot the next four bars of the 430 LOCATE 1,15
graph is shown in Figure 10.17. The READ statement 440 PRINT "THE ECONOMY";
in line 220 reads the next four values of inflation, unem- 450 LOCATE 19,1
ployment, growth, and income, and stores these values 460 PRINT "0"
470 LOCATE 14,1
in the memory cells I, U, G, and M. The cyan inflation 480 PRINT "8";
bar is plotted in lines 230-250 using the subroutine 490 LOCATE 9,1
at line 2000 shown in Figure 10.13. Note that the 500 PRINT "16"
value of V has been equated to the inflation value times 510 LOCATE 7,1
520 PRINT "%"'5
5,(1*5). This is done because the maximum data value S30 LOCATE 4,46:PRINT "INFLATION: CYAN";
in Table 10.2 is 18.2, and 18.2*5=91, which will fit 540 LOCATE 5,6:PRINT “UNEMPLOYMENT: MAGE
nicely on the screen above line 147 and still leave some NTA":
room for a title. Five is the scale factor which will 550 LOCATE 6,6:PRINT "GROWTH: WHITE":
560 LOCATE 7,6:PRINT "PERSONAL INCOME: C
be used on every bar drawn. Line 270 increases the YAN":
column number by eight so that the next bar will be 370 RETURN
plotted in the next adjacent column. (Remember that Ok

91
10.17, and 10.18. The result of running this program
is shown in Figure 10.19.
THE ECONOMY
Although this entire program is relatively long, you
can see that by breaking the program up into functional ION: CYAN
modules you can more easily keep track of what is ANEMPLOY MENT: MAGENTA
GROWTH, MYNCOME: CYAN
going on. This will also make it easier for you to modify % PERS
this program to suit your own needs.

EXERCISE 10.1
The following table shows the amount of gasoline re-
quired to fill the gas tank of a certain station wagon:
ff

Speedometer Reading Gallons to Fill Tank see 1977 1978 1979


93769.3 1I5)55)
94034.6 15-2)
94249.1 14.8
94376.6 9.0
go a8.0 Ae Figure 10.19 Bar graph of economic data given in Table
94778.2 12.8 10.2
95037.0 14.9 a
95258.0 14.7
95499.3 15.3
95732.7 20.3 Nation Population Area
aero is0 Australia 14,620,000 2,965,368
Write and run a program that will Britain 56,235,500 94,500
Canada 23,940,000 3,851,809
(a) store the above data in DATA statements, China 1,027,000,000 3,691,502
(b) compute the gas mileage in miles/gallon for India 667,326,000 1,178,995
each fillup, , and plot the results as a bar graph : pepae Ne pei
Soviet Union 266,670,000 8,649,489
and United States 226,504,825 3,615,122
(c) compute and print out the average miles/gallon
for all fillups shown in the table. ,
(a) Store the above data in DATA statements,
EXERCISE 10.2 (b) compute the population density for each nation
Each entry in the following table gives a nation, its in persons per square mile, and
population, and its area (in square miles): (c) plot the results as a bar graph.

92
LEARNING TO

You have learned that numerical values are stored in memory cells. We printed the state name and plotted
memory cells with names like A and STATE. Simi- a bar with a length proportional to the population.
larly, strings are stored in memory cells with names Then we read another state name and population which
like A$ and STATES. Sometimes it is desirable to replaced the previous ones in STATES and P.
identify a collection of memory cells by the same name. Some programs, however, require that all of the
Such a collection of memory cells is called an array state names and populations be stored in different
and the individual memory cells within the array are memory cells at the same time. We would therefore
identified by means of a subscript. need twelve different memory cells—six for the state
In this chapter you will learn names and six for the populations. This will require
twelve different memory cell names. It is convenient
1. how to represent arrays in BASIC,
to store all the state names in an array which we will
2. the difference between one-dimensional and call S$, and all the populations in an array called P.
multi-dimensional arrays, The individual memory cells within the array are dis-
3. how to use the DIM statement, tinguished by a subscript I. An individual element
4. how to use arrays when plotting bar graphs, and within the array is sometimes called a subscripted vari-
5. how to sort data stored in a one-dimensional able P(1) or S$(1). The arrays S$ and P are shown
array. in Figure 11.1.
Note in Figure 11.1 that in BASIC subscripts are
enclosed in parentheses. The variable name P(2), for
ARRAYS example, is just the name of a memory cell that con-
tains the value 444732. You can use these subscripted
You will often encounter data that are related in some variables any place that you would use a simple varia-
way. For example, Table 10.1 in Chapter 10 lists the ble name. For example, type
six New England states and their populations. In the
S$(2)=“VT”
program in Figure 10.7 we read each state into
2S$(2)
the memory cell STATES and each population into
the memory cell P. This means that at any one time P(2)=444732
only one state name and one population were in named ?P(2)

93
The DIM Statement
P(0) 993663

P(1) 737681 Whenever a BASIC program first encounters a sub-


scripted variable, such as A(3), it automatically assigns
P(2) 444732
11 memory locations to the array. These memory loca-
P(3) 5689170 tions are assigned the names A(0)-A(10). Thus, if you
try to use the name A(11), as in the example above,
P(4) 3032217
there is no such memory cell name reserved in the
P(5) 949723 computer, and you therefore get the error message
Subscript out of range.
(b) If you want to use an array with more than 11
Figure 11.1 (a) The six subscripted variables S$(I), I=0,5 memory cells, then you must explicitly define the array
contain the state names. (b) The six subscripted variables
with a DIM (for DIMension) statement. For example,
P(|), I=0,5 contain the state populations.
to assign 16 memory cells to the array B you would
type
as shown in Figure 11.2. The names S$(2) and P(2)
are just the names of two memory cells. They happen DIM B(15)
to be elements of an array but individually they can
You could then use the 16 memory cells B(O)—B(15).
be treated like any other memory cell name.
The constant 15 in the above DIM statement (this
could also be a variable or an expression) represents
Figure 11.2 Subscripted variables can be used just like
the upper subscript limit of the array. The lower sub-
simple variables.
script limit is always assumed to be zero.
Ok
S$(2)="VT" You can define more than one array with a single
Ok DIM statement. For example, you can write
Posi)
VT DIM B(15), A(3), SPEED(24)
Qk
F¢2)=44732 which defines three arrays containing 16, 4, and 25
Ok memory cells respectively.
Ede WED) Although it is not necessary to use a DIM statement
44732
when the array contains 11 or fewer memory cells,
Qk
it is usually a good idea to always use the DIM state-
ment to define arrays. For one thing it gives you a
Having a memory cell name contain a subscript,
convenient place to define what the array means (by
however, can be very useful. For example, type the
following the DIM statement with a REM statement).
following two statements as shown in Figure 11.3.
Also, if you only need five memory cells in an array
FOR I=0 TO 10: A(D=2*I;: NEXT then by using the statement DIM A(4) you will save
FOR I=0 TO 10: ?A();: NEXT memory because otherwise the computer would auto-
matically reserve 11 memory cells rather than 5. This
The first statement fills each of the 11 memory cells saving is bigger than it may appear because the IBM
A(1), I=0,10 with the value 2*I. The second statement PC uses four bytes of memory for each single precision
prints these 11 values. memory cell such as B(3).
Other than using up memory it does not hurt to
Figure 11.3 Filling the array A(l) with the value 2*1. reserve more memory locations (by using the DIM
Ok statement) than you use in the program. For example,
FOR I=0 TO 10: ACT) =2%Is NEXT you will reserve 100 memory cells with the statement
Ok
FOR f=0 TQ 10: PACT)3: NEXT
DIM C(99). In your program you may only refer to
Opes eae? Pee rol nts) ae) ee A Len UeLich weet the first 20 of these memory cells. This is O.K. How-
Qk ever, if you try to refer to C(100) you will obtain the
error message Subscript out of range.
Try changing the first statement to The DIM statement may occur anywhere in the
program, but it must occur before you refer to the
FOR I=0 TO 11: A()=2*I: NEXT
corresponding subscripted variable. An array can only
You will obtain the error message Subscript out of be dimensioned once in a program. If you try to dimen-
range. The reason for this error will be explained in sion it more than once you will obtain the error mes-
the following section. sage

94
Duplicate Definition The maximum number of elements in an array of
Remember that if a subscripted variable such as A(3) the type we have been using is 32767. The maximum
dimension may also be limited by the amount of mem-
is encountered before a DIM statement has been exe-
ory in your IBM PC. If the total amount of memory
cuted, then the IBM PC will automatically dimension
used by your program, variables, and arrays exceeds
the array equivalent to DIM A(10). If it then encoun-
the amount of memory in your IBM PC you will obtain
ters a DIM statement, the above error message will
the error message
be displayed.
For example, try typing the following Out of memory
FOR I=0 TO 11: A()=2*I: NEXT Any time you want to know how many bytes of
free memory you have left, type
(You may have already done this above.) If you haven’t
DIMensioned the array A, you will obtain the error ?FRE(O)
message Subscript out of range as shown in Figure
For example, Figure 11.5 shows that an array contain-
11.4a. The problem, of course, is that you tried to
ing 100 single precision elements uses 409 bytes of
refer to A(11) and the IBM PC had automatically
memory (4 for each of the 100 elements in the array
dimensioned the array equivalent to A(10). But if you
and 9 for an array header), while an array containing
try to correct this by typing
100 integer elements uses only 209 bytes of memory.
DIM A(11)
you will obtain the error message Figure 11.5 The statement ?FRE(O) will print the number
of free bytes of memory left.
Duplicate Definition Ok
(a)
CLEAR
as shown in Figure 11.4a. This means you tried to Ok
redimension the array. This is because the array is ?PFRE (0)
already dimensioned (automatically) to A(10)! What 613574)
can you do? Type CLEAR as shown in Figure 11.4b. Ok
DIM AC99)
This clears, or sets to zero, all numeric variables; it Ok
also clears, or sets to null, all string variables; and it SRRECO)
removes all DIMension declarations. You can then 60962
Ok
type

DIM A(11)
Ok (b)
FOR I=0 TO 11: A()=2*I: NEXT CLEAR
FOR I=0 TO 11: ?A();: NEXT Ok:
PFRE (0)
without errors as shown in Figure 11.4b. 61271
Qk
DIM AX(99)
Figure 11.4 Examples of using the DIM and CLEAR Ok
statements. TFRE (O)
(a) Ok 61162
FOR I=0 TO iis ACTI)=2%I: NEXT Ok
Subscript out of range
Ok
DIM Aili) Multi-dimensional Arrays
Duplicate Definition
Ok
An array that contains a single subscript is called a
one-dimensional array. An array that contains more
(b) Ok than one subscript is called a multi-dimensional array.
CLEAR For example, the DIM statement
Ok
DIM At11) DIM A(2,3)
Ok
FOR I=0 TO lis ACI) =2xXI: NEXT defines a two-dimensional array containing 12 ele-
Ok ments. It can be thought of as a two-dimensional ma-
FOR =O TO lis PACT)s:2 NEXT trix containing 3 rows and 4 columns as shown in
Omens een R Oem etree Ties | Les rt)
22
oe Figure 11.6.
Ok In the array A(I,J) the first subscript I is the row

95
Figure 11.7 Bar graph example using arrays.
10 “PROGRAM TQ DRAW A RAR GRAPH
15 SCREEN 1,0:COLOR ©,1:CLS
18 DATA 1,2,3,1
20 DATA 120,250,50,170
25 DEFINT C,FaHsIsWaXsY
26 DIM C(4),WR(A)
=O HR = 10: “HEIGHT OF BARS
45 F = 1: “BARS WILL BE FILLED
SO XR = O: “LEFT BORDER FOR BARS
55 FOR I=1 TQ 4: READ C(I): NEXT I
56 FOR I=1 TQ 4; READ WR(T): NEXT I
Figure 11.6 The array A(I,J) containing 12 elements. 60 FOR I = 1 TO 4
65 C = Ctl): WR = WR(I)
7O YR = SO+(I-1)*30
number in Figure 11.6 and the second subscript J is @o GOSUB 1000
the column number. Thus, for example, in Figure 11.6 90 NEXT I
the value of A(1,2) is 8 and the value of A(2,1) is 100 END
Pe 1000 “THIS SUBROUTINE WILL DRAW A
A three-dimensional array containing a total of 1001 “BAR THAT IS A GIVEN NUMBER OF
7X 9 X 3 = 189 elements can be defined by the DIM 1002 “GRID UNITS IN LENGTH. THE CALLER
statement 100s “MUST SPECIFY THE UPPER EHS CoRNER
1004 “AND THE WIDTH, HEIGHT AND COLOR.
DIM F(6,8,2) Loos
1006
= it
*
EAN) BES TRE Doi see Ral eMicatares

We will begin by writing some programs using one- 1007 IF WR = © THEN RETURN
dimensional arrays. 1010 IF F = © THEN
LINE (XR, YR) —(XR+WR-1,
YR+HR) ,C,B
ELSE
LINE (XR, YR) -(XR+WR-1,
YR+tHR) ,C, BF
BAR GRAPHS USING ARRAYS 1020 RETURN
Ok

The program shown in Figure 10.6 in Chapter 10 plots


four bars of lengths 120, 250, 50, and 170. Review plotted in line 80. Note how the subscript I gets incre-
that program and make sure you understand how it mented from | to 4 each time through the loop. Also
works. Line 80 plots a bar of color C of length WR note that the subscripted variable WR(I) (and C(I)
using the subroutine at line 1000. In this section we and the simple variable WR (and C) are not confused
will modify this program to plot the same length bars by the IBM PC and are treated as separate memory
but using a different color for each bar. cells.
The modified program is shown in Figure 11.7. Line The result of executing the program in Figure 11.7
18 is anew DATA statement that contains the 4 color is shown in Figure 11.8.
codes from palette 1 (cyan, magenta, white, cyan) that
will be used for the 4 bars. Line 26 is the DIM state- Figure 11.8 Result of running the program shown in Figure
ment UEP ee

26 DIM C(4),WR(4)
This statement defines an array C(I) that will contain
the four color codes and an array WR(I) that will
contain the four lengths. Although this DIM statement
defines five elements for each array, we will only use
the elements C(1)-C(4) and WR(1)-WR(4) and just
ignore C(O) and WR(0).
Line 55 reads the four color codes in the DATA
statement on line 18 into the four subscripted variables
C(1)-C(4). Line 56 reads the four values 120, 250,
50, and 170 from line 20 into the four subscripted AAA
variables WR(1)-WR(A4) respectively.
The loop defined by lines 60-90 plots the four bars.
Each time through the loop a new length WR(I) and
a new color C(I) are assigned to WR and C to be

96
Suppose you would like to plot the bars shown in - Figure 11.10 Pseudocode representation of sorting
Figure 11.8 in increasing order of length—that is, the algorithm shown in Figure 11.9.
shortest bar first, the next to shortest second, etc. You for I=1 TO N-1
can do this if you rearrange the array WR(I) so that for J=I+1 TON
the elements are in increasing order. One simple
if WR(D<=WR(J)
method of sorting an array in increasing order will
then do nothing
now be described.
else interchange WR(I) and WR(J)
nextJ
Sorting an Array nextI
in Increasing Order
The algorithm shown in Figure 11.10 looks like it
There are many algorithms that have been devised will be fairly easy to write in BASIC. The only problem
for sorting an array of elements into increasing order. is how to interchange the contents of WR(I) and
Some are more efficient (i.e. execute faster) than others. WR(J). Note that the two statements
Some (not necessarily the same ones) are easier to un-
derstand than others. The method of sorting the array WR(D = WRU)
WR illustrated in Figure 11.9 is fairly easy to under- WR(GUJ) = WRU)
stand.
will not work because the original value in WR(I) will
The method begins by comparing the first element
be destroyed when the value of WR(J) is put in WR(I)
in the array (I=1) with all succeeding elements. Any
in the first statement. This means that the second state-
time a succeeding element is found that is smaller than
ment will really be assigning the value in WR(J) to
the first element, it is interchanged with the first ele-
itself! Thus, WR(1) and WR(J) will end up with the
ment. Thus, after the first element (whose value may
same value. It requires three statements to interchange
have changed a few times) is compared with all suc-
the values of WR(I) and WR(J) as shown in Figure
ceeding values, we will have moved the smallest value
1 Was be
to the first position in the array.
If we repeat this procedure starting with the second
element (I=2), then after comparing the second ele- Figure 11.11 Three statements are required to interchange
WR(I) and WR{).
ment with all succeeding elements and interchanging
the values if the succeeding element is smaller than WR() = se will not interchange WR(I) and
the second one, the next to smallest value will end WR(J) = WR) } WRG)
up in the second position in the array. T = WR)
will interchange WR(1I) and
This process continues until we have compared the WR(D = WR(UJ) WR(J)
next to last element with the last element in the array. WR(UJ) = T
At this point the array is sorted in increasing order
as shown in Figure 11.9. The algorithm for this proce- The value in WR(I) must temporarily be stored
dure is shown in pseudocode in Figure 11.10. Compare in another memory cell T before the value in WR(J)
Figures 11.9 and 11.10 and make sure you understand is put in WR(I). Then the value in T (that used to
how this sorting algorithm works. be in WR(I)) can be put in WR(J).
The sorting algorithm shown in Figure 11.10 is writ-
Figure 11.9 Sorting an array by moving the smallest ten as a BASIC subroutine in Figure 11.12. Note that
succeeding value to location |, I=1 TO N—1 (N=number line 2040 interchanges the values in WR(I) and WR(J).
of elements in array).
Add this subroutine to the program shown in Figure
Array M7:
I=1 l=2 I=3 sorted
Figure 11.12 BASIC subroutine to sort array WR(I)
WR(1) 12 5 5 5 5 containing N elements in increasing order.
2000 “SORT WRT)
20TOUEO0R I = 2 TG N=-1
WR(2) 25 a 12 7 7 OCR te = eG) aN
2050 TF WR(T) <= WRCJ) THEN 2050

WR(3) 5 12 25 a 12 2040
AMO)
TH=WRCI)d:
NET
WRCT)=WR(J):
ais, ME xT « f
WROD ST

2060 RETURN
WR(4) 7 7 25 Ok

97
Then add the statement

58 N=4: GOSUB 2000: REM SORT WR()

to the main program as shown in Figure 11.13. The


result of running this program is shown in Figure
11.14. Line 58 sets the number of elements in the array
WR to 4 and then sorts this array by calling the
subroutine shown in Figure 11.12.

Figure 11.13 Main program to plot bar graphs in increasing


order using the subroutine in Figure 11.12.
10 “PROGRAM TO DRAW A BAR GRAPH
15 SCREEN 1,0:;COLOR ©,1:CLS
12. DATAgl «fecha t
20 DATA 120,250,50,170
25 DEFINT CyaFaHy lay TaWaXe¥
26 DIM C(4),WR(4)
SO UHR = 10s “HEIGHT OF BARS Figure 11.14 Result of running the program shown in Figure
45 F = 1s BRAM SmWil toe etines eitele Eyl) Ut S33
SO XR = O¢ "LEFT BORDER FOR BARS
so FOR T=1 TO 4: READ C(I): NEXT I
36 FOR I=1 TO 4: READ WR(T): NEXT I
98 N=4: GOSUB 2000: “SORT WRCT)
60 FOR I = 1 Ta 4
Figure 11.15 Sorting subroutine that interchanges
65 C = C(I): WR = WRC)
C(!) and CJ) each time that WR(I) and WR()) are
DG) Sylie Gat teh ce al MS aR)
interchanged.
80 GOSUBR 1000
90 NEXT I Ok
100 END LIST 2000-
2000 “SORT WRC)
1000 "THIS SUBROUTINE WILL DRAW A 2010 FOR I = 1 TQ N-1i
1001 “BAR THAT IS A GIVEN NUMBER OF 2020 FOR J = I+i TON
TOOL GRID TUNITS IN LENGTH. THE GALLER 29030 TF WR¢LT) «<= WR(J) THEN 2050
OKGSS OUMIURSE ARIST UTS Vite(ee Udell (IRINYeal 2040 T=WR(I): WRCID=WROD)s WROJ)=T
1004 “AND THE WIDTH,HEIGHT AND COLOR. 2045 TCI): CCl)=CUI): ChI)=T
(Gite AT TYAN) Jets Teugikiiisioy (iin. (atsip Tales 2050 NEXT ds NEXT I
TORR Ss |& 2060 RETURN
1007 IF WR = © THEN RETURN Ok
10160 IF F = © THEN
LaDUNIES CC etry NAR co Geet aaal Veen ina canted
Bese
LINE (XR, YR) -(XR+WR-1, YR+HR) .C, BF
1020 RETURN Figure 11.16 Result of running the bar graph program
Qk (Figure 11.13) using the sorting subroutine given in Figure
UA BedSS

If you compare Figure 11.14 with Figure 11.8 you


will notice that the four colors are plotted in the same
relative order. That is, the colors did not get sorted
as the data did. However, it probably makes more
sense to associate a particular color with a particular
data value (such as inflation, growth, etc.) so that if
the data are rearranged (sorted) the corresponding
color should also be rearranged. lh
We can do this by adding the statement
CACAO
2045 T=C(D: CD=CW): C(N=T
to the subroutine given in Figure 11.12 as shown in HANNA
Figure 11.15. This statement will cause C(I) and C(J)
to be interchanged each time that WR(I) and WR(J)
are interchanged. This will cause a given data value
to “keep” its particular color as shown in Figure 11.16.

98
Sorting an Array EXERCISE 11.2
in Decreasing Order Write a program that

The subroutine in Figure 11.15 can easily be modified (a) stores N test scores in DATA statements, with
to sort the array WR(I) into decreasing order rather the value of N stored as the first entry of the
than increasing order by changing line 2030 to first data statement,
(b) reads the test scores into an array S(I), and
2030 IF WR(D>=WR(J) THEN 2050
(c) computes and prints out the average of the N
test scores.
Figure 11.17 Subroutine to sort array WR(|)
containing N elements in decreasing order. EXERCISE 11.3
Ok If AV is the average of the N test scores stored in
LIST 2000-
the array S(1), then the standard deviation is defined
2000 “SORT WRI)
2010 FOR f = 1 TQ N-1 as
2020 FOR J-= f+1- TON
2030 IF WR(T) == WRI) THEN 2050 sD=4 Fe> (S(I) — AV)?
2040 TSWR(I): WROD) =WROJ): WROJ)=T
cet Cs (Ce ee mC (etal ee oN i=) N

2050) NEXT J: NEXT I where the notation } means the sum from I = | to
I=1
2060 RETURN
Ok
N. Modify the program in Exercise 11.2 to compute
and print out the standard deviation of the test scores.
Run the program for the following test scores:
as shown in Figure 11.17. Running the main program
with this subroutine will produce the result shown in Test Scores
Figure 11.18. 75 36 60 92 80 72 68 48
65 82 88 Tf92 76 85 72 98
EXERCISE 11.1 48 57 TES 66 76 88 73 82
44 90 70 56 81 Us; 87 90
Write a program that

(a) stores the six New England states and their pop- EXERCISE 11.4
ulations in the arrays S§$(I) and P(1) as shown The weights shown below are the weights of a group
in Figure 11.1, of males and females. Write a computer program that
(b) plots a vertical bar graph of the populations will compute and print out the means and standard
using medium resolution graphics, deviations of the two groups of weights. Modify the
(c) sorts the populations in increasing order, and program so as to compute and print the mean and
standard deviation of all weights (both male and fe-
(d) plots a second bar graph (after pressing key
male). (See Exercise 11.3.)
“S”’) with the populations in increasing order.
Weights
Figure 11.18 Plotting bar graphs in decreasing order using Male Female
the subroutine in Figure 11.17. 200 103
185 105
185 (2
125 102
140 160
195 120
190 TS
55) 130
185 140
140 118
138
205
159
230
150
140
170
145
169
DAliS;

99
EXERCISE 11.5
A person makes the following monthly deposits in a
savings account paying 5% interest compounded
monthly.

Month 1 2 3 4 5 6 7 8 Sy AKG) UL
Deposit
(dollars) 2S ae O mae Ome tl Spee? > a4 Oe Ow 30 35at Dae eee

The identical pattern of deposits is repeated for a sec- If the coefficients a; are stored as subscripted variables
ond and third year. Write a computer program that A(1), then the polynomial P can be evaluated, using
will compute the amount of money the person has the nested form, by the algorithm:
deposited and the total amount in the account at the
P = A(1)
end of 6, 12, 18, 24, 30, and 36 months. Read in the
monthly deposits as an array D(l). (Note: If R is for 1=2to5
the annual interest rate and it is compounded monthly, P=AQ+X*P
then each month the added interest is equal to R/12 nextI
times the amount in the account.)
Write a program that will use a similar nesting algo-
rithm to evaluate the polynomial
EXERCISE 11.6 P(x) = 3x5 + 4x4 — 2x3 + 5x —7
The polynomial
for values of x between —2 and +2 in steps of 0.2.
P(x) = a, x4 + agx3 + agx? + agx + a5 Print out a table of x and P(x). Make your program
general so that the coefficients are stored in DATA
can be written in the following nested form:
statements and the program can handle a polynomial
P(x) = as + x(ag + x(az + x(a2 + x(a1)))) of any order.

100
You have learned in previous chapters of this book THE STRING FUNCTIONS
that memory cells with names like A$ and C3$ contain LEFT$S, RIGHTS, MID$, AND LEN
strings. The dollar sign, $, is used in BASIC to identify
string-related names. IBM PC BASIC has a number The string functions LEFT$, RIGHTS, and MID$
of special functions and statements which make it easy are used to extract some portion of a string. The func-
for you to manipulate strings. Learning how to use tion LEN is used to determine the length of a string.
these constructs will permit you to write many interest-
ing programs. In this chapter you will learn
1. to use the string functions LEFT$, RIGHTS, LEFT$
MID$, and LEN,
2. to use the numeric/string functions STR$ and The function
VAL,
LEFTS(A$,D
. to use the MID$ statement,
. to use the ASCII code functions ASC and CHR$, is a string that contains the left-most I characters of
. to use the STRINGS function, the string A$. For example, if AS=“ABCDE”, then
. how to display dollars and cents on the screen, LEFTS(A$,2) will be the string “AB”. To verify this,
W
>
Non
type
7. how to write a program to shuffle and display
a deck of playing cards, A$=“ABCDE”
8. how to write a program to deal a hand of playing ?LEFTS(A$,2)
cards, and
9. how to use the INSTR function. as shown in Figure 12.1a.

101
Figure 12.1 Examples of using the string functions LEFT$, as shown in Figure 12.1b. Note carefully the difference
RIGHT$, MID$, and LEN. between MIDS$(A$,2) and RIGHTS(A$,2). The former
(a) Ok
is a string containing the right-most characters starting
AS="ARCDE"
Ok
at position 2 of A$ while the latter is a string containing
FLEFTS (AS, 2 the right-most 2 characters of A$.
AR
Qk
PRIGHTS (AS, 2) LEN
DE
Ok The function

(b) O- LEN(AS)
PMIDS (AS, 3,2) is equal to the length of the string A$. Note that it
CD
Qk
is a numerical value (not a string). For example, if
PMID$ (AG, 2 A$=“ABCDE”, then the value of LEN(A$) is 5. To
BCDE verify this, type
Ok
LEN (AS) ?LEN(AS)
oa
Ok as shown in Figure 12.1b.

RIGHTS
THE MIDS STATEMENT
The function The statement
RIGHTS(AS$,D MIDS$(V$,N,M) = Y$
is a string that contains the right-most I characters replaces M characters in V$ beginning at position N
of the string A$. For example, if A$S=“ABCDE”, then with the first M characters from Y$. As an example
RIGHTS(A$§,2) will be the string “DE”. To verify this, type in the following
type
K$ = “IJKLMNOP”
?RIGHTS(A$,2) A$ = “ABCDE”
as shown in Figure 12. la. MIDS(K$,3,2) = A$
?KS

MID$ as shown in Figure 12.2. The MID$ statement replaced


the 3rd and 4th characters in K$ with the first two
The function characters from A$.
Now enter
MIDS(A$,I,J)
MIDS(K$,5) = AS
is a string that contains the J characters of A$ that ?KS
start at position I (the first character of A$ is position
1). For example, if A$S=“ABCDE”, then MIDS
Figure 12.2 Using the MID$ statement.
(A$,3,2) will be the string “CD”. To verify this, type
Ok
2MIDS$(A$,3,2) Ré=" TORLMNOF”
Ob:
as shown in Figure 12.1b. A¢G="ARCDE"
Ok
The function MID$ can also be written with only
MIDS (KS, 3,2) =A
two arguments. In this case Ole
PES
MIDS(A$,D TJABMNOF
Ok
is a string that contains the characters of A$ starting
at position I and continuing to the end of the string MIDS (ES, 5) =AS
A$. For example, if AS=“ABCDE”, then MIDS$(A$,2) Ok
will be the string “BCDE”. To verify this, type TRS
ITJABABCD
2MIDS(A$,2) Ok

102
also as shown in Figure 12.2. In this case the third ‘Figure 12.3 Examples of using the numeric/string function
argument in MID$ is missing. What is being asked VAL.
by this statement is that characters in K$ beginning Ook (a)
with the Sth character be replaced by all of A$. How-
AS="456"
Ok
ever, K$ cannot end up being longer than it was origi- PAS
nally, so the “E” from A$ doesn’t get used. 456
Ok
?VAL (A$)
454
THE NUMERIC/STRING FUNCTIONS Ok
VAL AND STRS$
Ok (b)
It is important that you understand the difference be- ?PVAL (AS) +10
tween a numerical value such as 456 and the string 466
Qk
“456”. It is like the difference between BOSTON and
PAS+10
“BOSTON”. BOSTON is a city in Massachusetts con- Type mismatch
taining buildings, roads, etc. “BOSTON” is a six-letter Ok
word that is the name of a city. Similarly, 456 is a VAL CUR")
oO
number that you can add to other numbers. “456”
Ok
is just the three characters 4, 5, and 6 sitting next to B¢="726 CAMBRIDGE DR."
each other. Sometimes you will need to convert a string Ok
like “456” to its corresponding numerical value 456. ?VAL (BS)
736
The function VAL will do this. You may also need
Ok
to convert a numerical value such as 456 to its corre-
sponding string “456”. The function STR$ will do
the string A$ to the number 10 will produce the error
this.
message
Type mismatch
VAL
Finally, type

The function 2?VAL(“K”)


VAL(AS)
BS = “736 CAMBRIDGE DR.”
2?VAL(BS)
is equal to the numerical equivalent of the string A$.
If A$ does not have a numerical equivalent then as shown in Figure 12.3b. This shows that the value
VAL(AS) is equal to zero. If A$ is a string with leading of the function VAL is zero if the string does not
numeric symbols followed by nonnumeric symbols, have a numerical equivalent. However, VAL will peel
VAL(AS) will peel off the leading symbols and ignore off leading characters from a string and convert them
the rest. to their numeric form, if it is possible to do so.
As an example of using the VAL function, clear
the screen and type
STR$
A$=“456”
2A$ The function
?VAL(AS) STRS(A)
as shown in Figure 12.3a. Note that ?A$ prints the
string 456 starting in column number 0, while is the string equivalent of the numerical value A. As
2?VAL(A$S) prints the number 456 with the usual lead- an example of using the STR$ function, clear the screen
ing blank. and type
In order to further see the difference between A=456
VAL(A$) and A$, type 2A
2?VAL(AS)+10 ?2STRS$(A)
2?A$+10 as shown in Figure 12.4a. Note that both print state-
as shown in Figure 12.3b. Note that the number ments print the number 456 with the leading blank.
VAL(AS$) can be added to 10, whereas trying to add This means that the string STRS$(A) actually contains

103
Figure 12.4 Examples of using the numeric/string function 2STRS(VAL(“246”))
STR$.
(a) Ok
2VAL(STRS(246))
A=456 as shown in Figure 12.5.

Ok THE ASCII CODE FUNCTIONS


PSTRE CA) ASC, CHR$ AND STRING$
454
Ok The name ASCII stands for ““American Standard Code
PLEN (STR (A) )
4 for Information Interchange.” In this standard code
Ok a certain number is associated with each character
(letter, digit, or special character). This code is used
Ol: extensively throughout the computer industry for send-
GUNS: Sdrhesh fate Nhl jemi yA Gs ing information from one computer to another or for
$ 456.00
sending data from a terminal to a computer. The BA-
Ok
P'S" 4+M IDES (STRE(A),2)4+".,00" SIC function ASC can be used to find the ASCII num-
$456.00 ber associated with any character, and the function
Ok CHR$ can be used to find the character associated
with any ASCII number.
the leading blank; i.e., STR$(A) is the string “ 456”.
To verify this type
ASC
?LEN(STRS(A))
as shown in Figure 12.4a. This shows that STR$(A) The function
really does contain 4 characters (blank, 4, 5, 6).
ASC(A$)
Strings can be added together (concatenated) to
form longer strings. For example, type returns a numeric value that is equal to the ASCII
code of the first character in the string A$. To find
2*$”+STRS(A)+*.00” some ASCII codes, clear the screen and type
as shown in Figure 12.4b. The total string consists
2ASC(“A”)
of the dollar sign, “$,” plus “ 456” plus “.00”; that
2?ASC(“?”)
is, ““$ 456.00.”
Suppose you wanted the total string to look like 2ASC(“ABC”)
“$456.00” without a blank between the dollar sign 2?ASC(“7”)
and the first digit. Can you think how to do this? as shown in Figure 12.6. Letters, digits, and special
You want to include all but the first character in the character keys all have ASCII numbers. Note that
string STR$(A). Try typing the ASCII number for a digit is different from the
2°$” + MIDS(STRS(A),2) + “00” digit itself (55 is the ASCII code for 7). Also note
that the function value of ASC(“ABC’’) is the ASCII
as shown in Figure 12.4b. Do you see how this works? code of the first character A.
Remember that MIDS$(STRS(A),2) is the string con-
taining all of the characters in STR$(A) after the first
(i.e. starting at position 2). We will look in more detail Figure 12.6 Examples of ASCII codes of characters on the
at how to display dollars and cents later in this chapter. IBM PC.
The functions STR$ and VAL are reciprocal func- Ok
FASC CUA")
tions as you can verify by typing 65
Ok
TASC CNP")
Figure 12.5 STR$ and VAL are reciprocal functions. 65
Ok Ok
FSTRS$(VAL ("246") ) FASC C'ARC")
246 6s
Ok Ok
VAL (STR$ (246) ) TASC ("7")
246 peli
Ok Ok

104
Figure 12.7 Program to find the ASCII codes of each key STRINGS(N,M)
pressed.
Ok which will return a string of length N where each
LIST character in the string will have the ASCII code of
30 AS=INKEYS: IF AS="" THEN =O M. As an example, enter
40 PRINT A; ASC(AS);: GOTO Sa
Qk ?STRINGS(10,55)
RUN
M6509 BSD S68 Fo 7056471. 4) 49.2 50° SS which will print out ten 7’s, since “7” is the character
452059 Sa * SS = SF 0 91-$ 36% 37 & 38 associated with ASCII code 55. This is shown in Figure
12.8.
If you want to see what some other ASCII values
are, try typing the following two-line program.
Graphic Character Codes
30 AS=INKEYS: IF AS=“ ” THEN 30
40 ?AS ; ASC(AS);: GOTO 30 In addition to the standard ASCII codes related to
characters on the keyboard, the IBM PC has many
This program will print any character you type fol-
special graphical character codes that can be used to
lowed by its ASCII code. A sample run is shown in
output special effects to the screen. For instance, the
Figure 12.7. The ASCII codes for all of the characters
ASCII code 1 has been assigned to the popular graphic
are given in Appendix B.
smiling face in a circle. The ASCII code 251 is for
the square root symbol, and ASCII codes 3, 4, 5 and
CHRS 6 are for the symbols for all the suits in a deck of
playing cards. You can check these by typing in the
If you know the ASCII code of a character you can following sequence:
generate the string of that character using the function
?CHRS(1)
CHRS(A) ?CHRS(251)
where A is the ASCII code of the character. FOR I = 3 TO 6: ?CHRS(D;: NEXT
Using the results in Figure 12.5, try typing the fol- as shown in Figure 12.9. You should review Appendix
lowing statements B to see what special ASCII symbols are available.
2?CHRS(65) These include items such as letters from the Greek
alphabet.
?CHRS(63)
2CHRS(55)
PRINTING DOLLARS AND CENTS
as shown in Figure 12.8.
Lots of practical programs involve money and require
STRINGS you to display dollars and cents on the screen. IBM

The STRINGS function is similar to CHRS, the differ- Figure 12.9 Checking some special ASCII codes.
ence being that it returns a string that has multiple
occurrences of the character whose ASCII code is spec-
ified. The function form is

Figure 12.8 Examples of printing characters using their §


ASCII codes.
Ok
PCHRS (45)
2 2—3 FO 6: ?CHRSCI>: NEXT

A
Ok yl
?PCHRS (4&3)

Ok
?PCHRS (S55)
ZT.
Ok
?STRINGS (10,55)
FFITIITITII7T
Ok

105
PC BASIC allows you to do this rather easily using Figure 12.11 A2$ is a string representation of the dollar
the PRINT USING statement. If you did not have amount.
this statement then the problem of printing out dollars Ok
AZ=INT (AL)
and cents is not a trivial one. We will investigate the
Ok
problem without using PRINT USING and then with PAZ
PRINT USING. First of all, if you compute some 208
monetary value such as interest in a savings account, Qk
AZSE=MIDS$(STR (AZ) , 2)
you will want to round to the nearest cent. One way
Ok
you can do this is to multiply the original value by TALS
100; assign the real number to an integer to round it 208
off; and then divide it by 100 to move the decimal Ok
point back where it belongs. In order to try this scheme,
type as shown in Figure 12.11. Note that A2 is the dollar
value and A2$ is the string representation of this value
A=208.4978 with the leading blank eliminated.
B% = A*100 In order to obtain a string representation of the
2B% cents value, type
?B%/100 A3=A1—A2
as shown in Figure 12.10. An alternate scheme that 2?A3
uses all real numbers involves the use of the INT func- A3$=MIDS$(STRS(A3),3,2)
tion. To illustrate this scheme enter the following as 2A3$
shown in Figure 12.10.
as shown in Figure 12.12. Note that the cents value
A3 is found by subtracting the dollar value from the
Figure 12.10 Rounding a monetary value to the nearest total rounded amount. A string representing the cents
cent.
amount consists of the third and fourth characters in
Ok Qk
the string STR$(A3) (the first character is a blank
A=208,.4978 2A
Ok 208.4978 and the second character is a decimal point).
BAF=AK1LOO Ok The total dollars and cents can be displayed by typ-
Ok AL=A+,. 005 ing
td nA Ok
2O8SO ZAI 2$5A2$;."3;A3$
Qk 208, 5028
?BA/ 160 Ok which will display
208.5 TINT CALK1IO0O)
7/100
Ok 208.5 $208.50
ed
Ok A2$ A3$

as shown at the bottom of Figure 12.12.


2A
The statements shown in Figures 12.10, 12.11, and
Al = A+ .005 12.12 can be combined to form the subroutine shown
?Al in Figure 12.13a. This subroutine should print the
2INT(A1*100)/100

Note that although both schemes rounded to the near- Figure 12.12 A3$ is a string representation of the cents
est cent, the IBM PC does not display trailing zeros. amount.
Ok
Therefore, 50 cents is printed as .5. This would look
strange if you printed the amount of a check this way.
One way to print the .5 as .50 is to convert the
dollars and cents separately to their string equivalents » JOS T7924
Ok
and then display these strings. To investigate this possi- AZ$=MIDS
(STR (CAS) . 3,2)
bility, type Ok
TABS
A2=INT(A1) BC
2?A2 Ok
SUSU sA2Hs PASS
A2$=MIDS(STR$(A2),2) $2098.50
2?A2$ Ok

106
Figure 12.13 This subroutine for displaying dollars and Figure 12.14 Modified subroutine that displays correct
cents will not work for cents values less than 0.01. dollars and cents value.
(a) Ok (a)
Ok
aS etal
900 “PRINT A AS #XX.YY 900 “FRINT A AS XX. YY
910 AL=At+S,. OOOOOLE-O38:AZP=INT (Al) sAS=A1L-A 910 AL=AtS. OOOOOLE-O3: AZ=INT (A1) sAZ=A1—-A

920 AZS$=MID$
(STR (AZ) ,2) 920 AZS=MIDE(STRE(AZ),2)
930 AS$=MIDS
(STR# (AB), 2,2) 925 IF AS< .0O1 THEN ASS="00":G60TO 940
940 PRINT"S"sA2Si"."3 ARS; 930 ASS=MID$(STRE (AS), 3,2
950 RETURN 940 PRINTS" syA2Gs". "se ARG:
Bye 930 RETURN
Ok
Ok
A=208.4978: GOSUBR 900 Ok (b)
€208. 50 A=208.4978: GOSUBR 900
Qk $208, 50
A=159.994: GOSUR 900 Qk
SOW a A=159.994: GOSUBR 900
Qk $140.00
PAL Ok
160,001
A=9999.999: GOSUB 900
Ok
TAS Qk
1.00708E-02
Ok

12.15b. Note that spaces are reserved for five dollar


value of A in the form $XX.YY. For the first value digits plus the dollar sign. In the last example in Figure
of A shown in Figure 12.13b the subroutine works 12.15b more spaces are needed and so a % sign is
well. However, for a value of A=159.996 the subrou- printed in front of the dollar value to indicate a space
tine prints $160..0! The problem can be found by look- overflow. Run this program and try different values.
ing at the values of Al and A3 as shown in Figure Try changing the form of the PRINT USING state-
12.13b. If the fractional part of Al (the cents value, ment in line 30. A more detailed description of the
A3) is less than 0.01 then A3 will be stored in scientific format of the PRINT USING statement is given in
notation. This really messes things up because now Appendix F.
the third and fourth characters in STR$(A3) are “.0” The last example shown in Figure 12.15b rounds
rather than ‘00’. The subroutine shown in Figure 999,999.999 to $1,000,000.00. When writing a check
12.13a can be fixed by adding the statement for this value (or any value over $1,000.00) it would
look better and make the value easier to read if you
925 IF A3<.01 THEN A3$=“00”: GOTO 940
included the commas in the dollar amount. A method
as shown in Figure 12.14a. Note that this modified of doing this will now be explained.
subroutine prints the correct dollars and cents values
for all of the examples shown in Figure 12.14b.
As was noted at the start of this section you can Figure 12.15 Printing dollars and cents using the PRINT
use the PRINT USING statement to print dollars and USING statement.
Ok (a)
cents with the cents value automatically rounded. For
EsSoits
example, the statement
10 *DOLLARS AND CENTS WITH FRINT USING
2O INFUT “ENTER VALUE "“; A
PRINT USING “SSH#H#H#.FF#"A
20 PRINT USING "“S#H###H.
#H' SA
will print dollar values of A up to 99999.99 with the 40 GOTO 20
Ok
dollar sign placed just before the dollar amount. (The
double dollar sign in the PRINT USING statement (b)
Ok
produces a floating dollar sign. It also produces one RUN
more dollar position in addition to the four produced ENTER VALUE ? 33.4978
by the four # signs to the left of the period.) Cesta bate
ENE Vales hae
oo
The program shown in Figure 12.15a will allow
$160.00
you to see how this version of the PRINT USING ENTER VALUE °? DOO
DDS 5 S77.
statement works. A sample run of this program, using
the same values as in Figure 12.14b, is shown in Figure ENTER VALUE *

107
Adding Commas Figure 12.16 Subroutine that includes commas when
to the Dollar Amount displaying dollars and cents.
Ok
ES Usa f
Suppose that you want to add commas to the value 900 “PRINT A AS $XX,XXX.YY
2=INT(AL) sAZ=A1-A
$57829.49
YO “ea 2
A2$ A3$ 920 AZ$=MID$ (STR# (AZ) .2)
925 IF ASS .O1 THEN AS$="00"2GOTO 940
First of all, we must remember that numbers to be P30 ASS=MID$(STR S
(AS). 3,2)
printed out in dollars and cents form must be small 940) L = LEN(A2$)
enough so that they are not stored in scientific notation. 945 PRINT "$"5
950 IF L <= 3% THEN A4$=A2$:G0TO 980 ELSE
A bigger problem is that single precision real numbers A4% = RIGHTS (A2S%, 5)
on the IBM PC are stored with only seven digits of 960 AS® = LEFTS(A2$,L-3)
precision. Thus, if we don’t wish to go to double preci- 970 PRINT AS#; "4 "3
sion numbers we must limit the dollar values to 99,- 980 PRINT A4S;". "SASS;
999.99. Therefore, at most we need to insert one
990 RETURN
Ok
comma. We will therefore divide the string A2$ into
the two sub-strings A4$ and A5$ as follows Ok
A=9999 999: GOSUB 900
$57,829.49 $10,000,G0
LOGS SSS,
Ok
A5$ A4$ A3$ A=2245., 7289: GOSUB 900
$2,245.79
That is, if L=LEN(A2$), then
Qk
A4$= are (L<=3) A=24, 3433 GOSUB 900
RIGHTS(A2$,3) (L>3) $34.24
Qk
and

A5$= LEFTS(A2$,L—-3) (L>3) ing system shown in Figure 12.17. For example, the
seven of hearts is number 33, the jack of diamonds
The algorithm for adding the commas will then
is number 24, etc.
be
The value of a card (A-K) has a value number V
if L<=3 and the four suits have a suit number S as defined
then print $A2$.A3$ in Figure 12.17.
else print $A5$,A4$.A3$ It is usually easier to use the card number, C, as
much as possible in a program to distinguish cards
and then use C to find the value and suit of the card
Figure 12.16a shows how this algorithm can be added
to the subroutine shown in Figure 12.14a. Lines 940—
980 implement the algorithm described above. Three Figure 12.17 Each card in the deck is associated with a
examples of using this subroutine are shown in Figure number between 1 and 52.
12.16b. Value No.
IBM PC BASIC will let you include the commas Club Diamond Heart Spade V
r =55
directly by substituting the following PRINT USING
A 1 14 Qi 40 1
statement in the program in Fig. 12.15a. Z 2 15 28 41 2
PRINT USING “83+, #+##.4##75A 3
4
3
4
16
17
XS)
30
42
43
3
4
5 5 18 31 44 5
6 6 19 32 45 6
i 7 20 338) 46 7
PLAYING CARDS 8 8 2 34 47 8
9 9 22 35 48 9
As another example of using string functions we will Ts 10 23 36 49 10
J 11 24 By 50 tli]
now develop some subroutines that will be useful in
Q 12 25 38 51 12
card game programs. The first thing to decide is how K 13 26 3) 52. 13
to represent a deck of cards within the computer. It
is convenient to associate a number between 1 and Suit
52 with each card in the deck. We will use the number- No. S 1 2 3 4

108
when needed. Given a card number C, the correspond- Figure 12.18 Subroutines to set up deck (line 3000) and
ing suit number S is given by pick card at location P (line 3100).
Ok
S=INT((C—1)/13)+1 LIST 3000-
2000 “PLAYING CARD SETUP
You should verify this by trying some examples from SOLO DIM CCs2)
Figure 12.17. For example, if C=26 (king of diamonds) sO20 POR I = 1 TO-S2:C(L)=1sNeExT I
S030 VB="ALZ4I567389T IO"
S=INT(25/13)+1 2040 S$=CHRS (S) +CHRS (4) +CHRS (3) +CHRE (46)
=1+1=2 S050 RETURN
S100 “PICK CARD AT LOCATION F
Once you know S then the value number V can be ab1o°0S = INTM (G(R) Als) +t
determined from the equation seta rer) ND eas TE ema tet) ei heed
S130 VYis = MID#$(V$,V,1)
V=C—(S—1)*13 2140 Sis = MID#(S,S,1)
S150 RETURN
For example, if C=26, then S=2 and Ok

V=26—(2—1)*13=13
12.17. Therefore, the single suit character S1$ corre-
It is convenient to store all of the card numbers sponding to the suit number S is given by
in an array C(I). This array can be initialized with
S1$=MIDS&(S$,S,1)
the following statements
The above ideas are incorporated in the two subrou-
DIM C(52)
tines shown in Figure 12.18. The subroutine given by
FOR I=1 TO 52: C()=I: NEXT lines 3000-3050 sets up the deck by dimensioning and
Thus, for example, C(47)= 47 and represents the eight initializing C(I) and defining V$ and S$. This subrou-
of spades. tine should be called once at the beginning of any
Suppose you want to display the 19th card in the program involving playing cards.
deck. The card number is C(19)=19. The suit number The subroutine given by lines 3100-3150 in Figure
is 12.18 will find the value string V1$ and the suit string
S1§ of the card located at position P in the array C,
S=INT((C(19)—1)/13)+1
i.e. the card with card number C(P). Lines 3110-3120
=INT(18/13)+1
define the suit number S and value number V using
=2 the formulas given above. Lines 3130-3140 find the
and the value number is single character strings V1$ and S1$§.
In order to test these subroutines, type
=C(19)—(S—1)*13
=19—1*13 GOSUB 3000
=6 P=33: GOSUB 3100: ?V1$;S1$
Therefore, from Figure 12.17 the card is the six of P=52: GOSUB 3100: ?V13;S1$
diamonds. To display this value define the two strings
Figure 12.19 Testing the subroutines given in Figure 12.18.
V$ and S$ as follows.
V$=“A123456789TJQK”
S$=CHRS$(5)+-CHRS$(4)+-CHRS$(3)+-CHR$(6)
eSsun 3688
In S$, CHR§(5) is the character value for the club Gk
310@; 2U15;S815
symbol and CHR$§(4) is the value for the diamond
S10: FULS; Sis
symbol. The other two values are for the heart and
spade symbols. All these symbols are detailed in Ap-
pendix B. Note that the position of each value character
in V$ corresponds to the appropriate value number
V in Figure 12.17. Therefore, the single value character
V1$ corresponding to the value number V is given
by
V1$=MIDS(V$,V,1)
Similarly, the position of each suit character in S$
corresponds to the appropriate suit number S in Figure

109
Figure 12.20 Program to display entire deck of cards. Shuffling a Deck of Cards
Qk
Sige In order to shuffle a deck of cards all you have to
10 “DISPLAY DECE do is to scramble the order of the card numbers stored
2OVGOSHURSAUOOe Sei aet ik
Fae (Spa NTP
in the card array C(I). The following simple algorithm
30 FOR P = 1 TO 52 will do this:
40 GOSUB 3100: *GET NEXT CARD
SOMMER UMMA ero pis etsse ea SPRAY CARD for I=1 TO 52
60 NEXT FP find random number J between 1 and 52
100 END
2000 *“FLAYING CARD SETUF
interchange C(I) and C(J)
JOVIAE (es Garey, next I
POR ly Oma Gr) = TisiNEOX ie eb
V$="A2Z45467R89T JOR" This algorithm interchanges each element in C(I) in
S$=CHRS (5) +CHRS (4) +CHRS (3) +CHRS (4) turn with another element selected at random. Recall
ZOSO RETURN
that
2100 “PICK CARD AT LOCATION P
Se LOS esti VGC Rad e/ Ds) eal J = INT(RND(1)*52) + 1
cA CE) ea UG Rah Ok Ges
S120 Vis = MID#(V$,V,1) will be a random integer between 1 and 52.
2140 Si = MIDS(S$,S,1) A subroutine that will shuffle the deck is shown
2150 RETURN
Ok
in Figure 12.22. The FOR ... NEXT loop in lines
3220-3260 corresponds to the for... next loop given
above. Line 3240 finds a random number J between
as shown in Figure 12.19. Note that card number 33 1 and 52. Line 3250 interchanges C(I) and C(J).
is the seven of hearts and card number 52 is the king
of spades as shown in Figure 12.17. Figure 12.22 Subroutine to shuffle a deck of cards.
You can display the entire deck by running the Ok
ES Seto
program shown in Figure 12.20. Line 20 sets up the 3200 “SHUFFLE THE DECK.
deck and line 25 skips a line. The FOR ... NEXT : PRINTs PRINT" SHUFFLING"
loop in lines 30-60 increments P from 1 to 52, finds FOR I = 1 7T0 S2
V1$ and S1$ for the card at position P (line 40), and J = INTCRND(1) x52) +1
THC (I) CCI) HCCI) C(I) =T
prints these values and suit characters in line 50. The NEXT I
result of running this program is shown in Figure RETURN
12.21. Note that the cards are printed in the order
shown in Figure 12.17. In order to print them in a Add line 22 shown in Figure 12.23 to the main
random order you must first shuffle the deck. program given in Figure 12.20. This new program will
shuffle the deck and then display all of the cards. A
sample run is shown in Figure 12.24.
Figure 12.21 Result of running program shown in Figure
2220:
Dealing a Hand of Cards

The program shown in Figure 12.23 can easily be modi-


fied to deal a hand of cards. All you have to do is

Figure 12.23 Main program to display shuffled deck of


cards.
Ok
ELST SLO 1AG
10 *DISPLAY DECK
20 GOSUE S000: “SETUP DECK
22 GOSUB 3200: “SHUFFLE DECK
25 PRINT
SO) FORSE = 17 iO" a2
40 GOSUR 2100: “GET NEXT CARD
DO CPRIUNT Vs e Sle ee "s:" DISPLAY CARD
60 NEXT P
100 END
Ok

110
_ Figure 12.25 Program to deal a hand of cards.
Ok
Ok LIST -140
RUN
10 * DEAL HAND OF CARDS
SHUFFLING 20 GOSUB 2000; “SETUP DECK:
i) 22 GOSUR S200; “SHUFFLE DECK
J te 25 PRINT
he
.
30 INPUT “ENTER NUMBER OF PLAYERS ": NF
38 40 INPUT "NUMBER OF CARDS FER HAND "3NC
20) F = tePRINT
a oO oo
7Q FOR J = 1 TO NF
80 GOSUB 2100: “DEAL NEXT CARD
90 nN TE WALe Sp eye 3R 0s LD
100 FHP+l
TO NEXT J
120 PRINT
120 NEXT I
140 END
Ok
Figure 12.24 Sample run of program shown in Figure
12-23.
the cursor to the beginning of the next line after each
round of cards is dealt.
divide the cards among a number of players and limit Two sample runs of this program are shown in Fig-
the number of cards dealt to the desired number. ure 12.26. It would be nice if you could sort each
Let hand by suit. This is easier to do than you may think.

NP=number of players
Sorting a Hand by Suit
and

NC=number of cards per hand Suppose that a hand contains the cards shown in Figure
12.27a where the card number for each card is also
The first card to each player can be displayed on a given (see Figure 12.17). If the card numbers are sorted
single line with the statements in increasing order, then the cards will be sorted in
50 P=1 increasing order by suit as shown in Figure 12.27b.
This illustrates the advantage of using card numbers
70 FOR J=1 TO NP
to represent playing cards inside the computer.
80 GOSUB 3100: REM DEAL NEXT CARD In order to sort a hand we will therefore need to
90 PRINT V1$;S1$;“ ”; store the card numbers for each card in the hand.
100 P=P+1 We can store these in an array. For convenience we
110 NEXT J will use a two-dimensional array, H(I,J), in which each
column will contain the card numbers for a different
Note that P points to the next card in the deck and player as shown in Figure 12.28. To sort all hands
subroutine 3100 finds the card at C(P).
we will need to sort each column in increasing order.
To deal NC cards to each player and display them The array H(I,J) needs to contain NC rows (number
on succeeding lines, add the statements
of cards per hand) and NP columns (number of play-
60 FOR I=1 TO NC ers). Since we don’t know what these values are until
120 PRINT lines 30-40 in Figure 12.25 are executed, we will add
the following dimension statement at line 45.
130 NEXT I
45 DIM H(NC,NP)
as shown in Figure 12.25. In this program lines 30—
40 allow the user to input the values NP and NC.- Every time a card is dealt we need to add the card
Line 50 points to the top card of the deck and skips number to the array H(I,J) by adding the statement
a line. Lines 60-130 are the outer FOR ... NEXT
75 HL,J=C(P)
loop that prints NC rows of cards. Lines 70-110 are
the inner FOR ... NEXT loop that deals NP cards as shown in Figure 12.29. Note that this statement
and displays them on one line. Line 100 points to the is inside the two nested FOR ... NEXT loops and
next card in the deck after each one is dealt. The will be filled up one row at a time. In Figure 12.29
PRINT statement in line 120 is necessary to move we have added the one additional statement

111
Figure 12.28 Each column of the two-dimensional array
HiI,J) contains the card numbers for one player.

Two-dimensional array
H(I,J)

Figure 12.29 Main program to deal a hand of cards and


then display the sorted hand.
Ok
LIST -140
10 * DEAL HAND OF CARDS
20 GOSUB 3000: “SETUP DECK
very (EMIS USD SO OILS: (gS s
25 PRINT
30 INPUT "ENTER NUMBER OF PLAYERS "; NP
40 INPUT "NUMBER OF CARDS PER HAND "3NC
Ok 45 DIM H(NC, NP)
RUN
20 F = 1sPRINT
SHUFFLING
60 FOR I = 1 TO NC
OF PLAYERS ? 4 70 FOR J = 1 TQ NF
RDS PER HAND 7 &
7S HCI, J =CCP)
80 GOSUB 3100: *“DEAL NEXT CARD
90 FRR GTA NUS ecole ee
1900 PHF+1
110 NEXT @
120 PRINT
adebate
Bo
aTo
Hat
Wad
COs
ed
ll
sid
Bs
120 NEXT I
125 GOSUBR 200; *DISFPLAY SQRTED HAND
140 END
Ok

the corresponding cards. This subroutine is shown in


Figure 12.30. Line 205 prints the word “SORTING”
Figure 12.26 Sample runs of program shown in Figure
so that if it takes a little time (it will) the user will
W225:
know what is going on. Line 210 will sort each column
in H(I,J). In the interest of putting off what we haven’t
135 GOSUB 200: REM DISPLAY SORTED HAND figured out how to do yet for as long as possible, we
where we will hide everything that we haven’t figured will just let the subroutine at line 2000 do this. The
out how to do yet! nested FOR ... NEXT loops in lines 220-260 are
This subroutine at line 200 will have to sort each similar to the ones in lines 60-130 in Figure 12.29
column in H(I,J) in increasing order and then display that displayed the original hand. The subroutine at

Figure 12.27 A hand of cards can be sorted by suit by Figure 12.30 Subroutine to display the sorted hands of
sorting the card numbers in increasing order. cards.
Ok
Card Card No. Card No. Card
LIST 200-270
6H 32 2 2C 200 *DISPLAY SORTED HAND
4D 17 3 3G 205 PRINT: PRINT "SORTING": PRINT
8D 21 6 6C 210 GOSUB 2000: “SORT COLUMNS OF H
4S 43 17 4D 220 FOR I = 1 TO NC
Xe. 3 21 8D 230 FOR J = 1 TO NP
JS 50 32 6H 240 P=0:C(0)=H(I,d)
6C 6 35 9H 245 GOSUB 3100: *NEXT CARD
9H 35 43 4S 250 PRINT ViesS1$3" "3
2C 2 50 JS PHEAD) IND UA ite Ce INS Sp ae
270 RETURN
(a) (b) Ok

112
line 3100 will find the card at position P in the array
C; i.e. the card with card number C(P). This was useful
HUMBER OF PLAY Fs)Ss 7 6
in line 80 in Figure 12.29 where we were incrementing KUMBER OF CARDS PER D ?
P each time through the loop. However, in Figure # Et§ 3
12.30 we don’t know P but we do know the card num- Fe
¢
ber directly—it is just H(I,J). Therefore, we would
like to use the subroutine at line 3100 to find the value
ied
SMD ZiOOS
OCON
WIR
>
6S
of the card with card number H(I,J). We must make
C(P) contain the value H(I,J). Inasmuch as the array
element C(O) is not normally used but available, then 3
=
we will use this location to store H(I,J) as shown in J
a
line 240 in Figure 12.30. Note that we must set P=0 av

so that the subroutine at line 3100 shown in Figure oy
64 ee
W
VON
Hh
OOOO
12.18 will use C(O) which will be equivalent to using
H(1,J).
We're finally to the point where we must figure
out how to sort the columns of H(I,J) in increasing Figure 12.33 Sample run of the program shown in Figure
order. If you go back and study the sorting algorithm 12.29.
that we developed in the last chapter given in Figure
11.10, you will note that all we have to do is apply
this same algorithm to each column of H(I,J). The THE INSTR FUNCTION
resulting algorithm is given in Figure 12.31. The BA-
SIC implementation of this algorithm is written as a The function
subroutine in Figure 12.32.
INSTR(AS,B$)
We have now written all of the subroutines needed
to run the program shown in Figure 12.29. A sample searches string A§ for the first occurrence of substring
run is shown in Figure 12.33. Note that each hand B$ and returns the position at which the match is
is sorted by suit with the suits displayed in the order found. If there is no match, a value of zero is returned.
clubs, diamonds, hearts, and spades. For example, enter

A$ = “I AM A MAD SCIENTIST”
Figure 12.31 Algorithm for sorting each column of HiI,J)
in increasing order. ?INSTR(AS,“A”)
for J=1 TO NP
?INSTR(AS$,“MAD”)
for I=1 TO NC-1.
BS = “TIST”
for K=I+1 TO NC
2INSTR(AS,BS)
if HU,J)<=HK,J)
2INSTR(AS, “JOE”)
then do nothing
2INSTR(7,AS, “A”)
else interchange H(I,J) and H(K,J) as in Figure 12.34. In the first three cases, it is found
nextK that the first “A” in A§ is at position 3; “MAD” begins
at position 8; and ““TIST” at position 17. In the fourth
next I
example “JOE” is not present so the value returned
next J by INSTR is zero. The last example in Figure 12.34
indicates that INSTR can have three arguments, with
Figure 12.32 Subroutine to sort each column of the array
H(1,J). the first argument in this case being the position in
Ok A$ where the search for the substring B$ is to begin.
LIST 2000-2070 The first “A” in A§ at, or after, position 7 is found
2000 *SORT EACH COLUMN OF to be at position 9.
2008 *“H(NC, NF)
2010 FOR J = 1 TO NP
As a larger example of the use of this function as-
2020 FOR IT = 1 TO NC~-1 sume we wish to print out the position of all the A’s
2020 FOR kK = [+1 TO NC in any string A$. A program that will do this is given
2040 IF H(I,J0) «<= H(K,d) THEN 2060 in Figure 12.35. In line 50 the search for the first A
2050 T=H(1I,d) sH¢(1 , J) tHCR JET
J) =H(E,
starts at the beginning of A$. Once an A is found
20450 NEXT Ks NEXT Is NEXT Js
2070 RETURN the search for the next one begins at one position after
Ok the location where the current A was found. This con-

113
Figure 12.34 Using the INSTR FUNCTION. Figure 12.36 Sample run with the program in Figure 2e3 5s
Ok Ok
A$="T AM A MAD SCIENTIST" RUN
Ok ENTER A®
SINSTR (AS, "A") > & LONG TIME AGO I WAS AN ACTOR.
1
Qk 1S
FINSTR
(AS, "MAD" ) 20
to Seen
8 Seaigoa

Ok 26
BS="TIST" Ok
Ok
PINSTR (AS, BS)
ey sponds to the first character in A$.) If no match is
Ok found, set P=0.
SINSTR (AS, "JOE" )
oO
EXERCISE 12.2
Ok
PINSTR(7,A$,"A") Modify the program in Exercise 12.1 to find all occur-
9 rences of B$ in A$. Store the locations of all matches
Ok in the array P(I). A value of P(I)=0 will indicate no
more matches in the string.
Figure 12.35 Printing out the position of all the A’s in A$.
Ok EXERCISE 12.3
Si Write a program that will replace all occurrences of
10 *FIND THE LOCATION OF ALL the substring B$ in A$ with the substring C$. The
20 *THE A*s IN STRING AS
program should input the string A$ and the two sub-
ZO PRINT "ENTER A$"
40 INPUT AS strings B$ and C$.
sO kK = INSTR(AS,"A")
60 WHILE Ft? 0 EXERCISE 12.4
70 PRINT EF
Write a program that will shuffle a deck of cards and
80 kK = INSTR(R+1,A$,"A")
90 WEND deal a bridge hand. The four hands are to be sorted
100 END with the ace as the high card in each suit.
Ok
EXERCISE 12.5
tinues until there are no more A’s, in which case K=0 Some card games require the players to cut for deal,
and we drop out of the WHILE loop. A sample run with either the high card or low card winning the
of this program is given in Figure 12.36. deal. Write a program that will allow NP players to
cut for deal and assign the deal to the player cutting
EXERCISE 12.1 the highest card.
Write a program that doesn’t use INSTR that will
input a string A$ and a substring B$, and then search EXERCISE 12.6
for the first occurrence of the substring B$ in A$. If Write a program that will print a check. The program
a match is found, the value of P should be set to the should input a name, address, date, and the check
position in A$ of the first character of B$. (P=1 corre- amount. Print the check in the form

PAY TO THE ORDER OF DATE PAY THIS AMOUNT


12/13/83 #***1 250.41
JOHN DOE
1234 COLOR COURT
ROCHESTER, MI 48063
Check to make sure that the amount is in the range 0-99,999.00 and
print leading asterisks in the amount box on the check.

114
LEARNING TOUSE
HIGH RESOLUTION GRAPHICS

The medium resolution graphics mode was described X,Y on a 320 X 200 grid. Your IBM PC actually
in Chapter 7 and you have used it in many of your has a second graphics mode that you can use. This
programs in earlier chapters. IBM PC BASIC also mode, called high resolution graphics, differs in two
has a high resolution graphics mode that allows you major ways from the medium resolution graphics
to plot figures on the screen with considerably more mode. First, the screen in high resolution graphics is
detail.* In this chapter you will learn an array of 640 (horizontal) < 200 (vertical) grid
points. Secondly, high resolution graphics can use only
1. how to use the high resolution graphics mode
black and white as colors.
available with IBM PC BASIC,
You move into the high resolution graphics mode
2. how to plot figures in a dot-to-dot fashion by by executing the SCREEN statement.
storing the coordinates of the vertices in DATA
statements, SCREEN
3. how to draw figures of varying size,
In Chapter 7 we introduced the general form of the
4. how to plot figures at different locations on the
SCREEN statement as
screen,
5. how to plot figures whose coordinates can be SCREEN mode, burst
calculated, and where
6. how to use the statement DRAW to draw figures
of various shapes. mode =0 for text
1 for medium resolution graphics
2 for high resolution graphics
USING SCREEN AND PSET
IN HIGH RESOLUTION GRAPHICS and burst was used to enable, or disable, color. For
example, the statement
In Chapter 7 you learned how to use the statement
PSET(X,Y),C to plot a spot of color C at location SCREEN 1,0
will switch the screen to medium resolution graphics
* The programs in this chapter can only be run with a Color/Graph-
ics Monitor Adapter. (from text) and will enable the use of color. The actual

115
choices for colors for foreground and background must on itself. This statement is necessary to prevent the
then be set with the COLOR statement. cursor from reappearing. The SCREEN 2 statement
To move into the high resolution mode you must in line 20 will automatically clear the screen if the
execute the statement screen mode was other than high resolution graphics
when that statement was executed. If the mode was
SCREEN 2
already high resolution, then the SCREEN 2 statement
Only one parameter is needed in this case, since the will not clear the screen. Thus, line 30 with a CLS
second parameter (burst), which enables color, has no was added to insure the screen gets cleared before the
meaning in the high resolution mode. spot is plotted.

PSET PLOTTING SQUARES


IN HIGH RESOLUTION GRAPHICS
The general form of the PSET statement is
To illustrate the increased resolution obtained in high
PSET(X,Y),C
resolution graphics, we will plot several squares. To
where X and Y are the horizontal and vertical grid begin, enter and execute the short program given in
positions on the page where a spot is to be placed Figure 13.2a. This program uses the LINE statement
and C is the color code for the spot. In high resolution introduced in Chapter 7 to draw a rectangle as shown
graphics C=O specifies black and C=1 (the default in Figure 13.2b. Note that although the figure is 100
value) specifies white. grid units wide and only 50 grid units high, it appears
As an example, the program shown in Figure 13.la to be square. This is because the horizontal points
plots a single white dot near the center of the screen on the screen are much closer together than are the
as shown in Figure 13.1b. Line 20 selects mode 2 (640 points in the vertical direction. Additionally, the width
Xx 200 grid). Line 30 clears the graphics screen to the of the screen display area is larger than the height
default background color (black) and line 40 plots a of the display area.
white spot at location (320,100). Line 100 just branches To determine the exact ratio of horizontal grid units
per inch to vertical grid units per inch on your particu-

Figure 13.1 Plotting high resolution points using PSET


xe @): Figure 13.2 Line 40 plots a rectangle with the upper left
Ok corner at (100,50) and the lower right corner at (200,100).
EES Ok
Sy) SEVISETP UN EL Yay Uae site fei Lacs
Cee Shot RES wit ON VGRAFPAIES UO) STLUIN Ce RECTANGLES
20 SCREEN 2 Cle Ste ves Nie
= (GES =O CLS
40 PSET CABO, 100) 40 LINE (100,50)~(200,100),1,B
100 GOTO 100 100 GOTO 100
Ok Ok

116
lar display, add line 80 to the program in Figure 13.2a that the scale factor on the width must be 2.4, rather
as than 2. In this chapter we will use the factor of 2 in
all those programs that require scaling to maintain
80 LINE (0,0) - (639,199),1,B
proper shape. You can easily change this value to 2.4
and run the program again. This will draw a rectangle if your screen has the 8/6 ratio.
around the outermost perimeter of your screen display The width/height ratio of the screen display area
area as shown in Figure 13.3. If you measure the width is called the aspect ratio. In some cases there are IBM
and height of this rectangle with a ruler you should PC BASIC statements that assume your screen has
find that the 8/6 ratio. If your screen display differs from this,
you can easily override the default value involved and
width in inches _ $758
insert your own aspect ratio. This will be noted as
height in inches 5 ee the cases arise.
Assume for the moment that the ratio is 8/5. Since To illustrate the use of this type of scaling, assume
there are 640 horizontal grid units in the display area we wish to define a square in terms of its center point
and only 200 vertical grid units, this means that (XC,YC) and its width. If the width of a square is
2*W-+1 grid units and its height is W+1 grid units
: : 640 : then the upper left corner will be at X1,Y1 where
One horizontal unit of length = a = 80 grid units
X1 = XC— W
and
and
: : 200
One vertical unit of length = — = 40 grid units Yl = YC — W/2

as shown in Figure 13.4. Similarly, the lower right


Thus, to maintain normal symmetry in drawing ob-
corner will be at X2,Y2 where
jects, the width must be twice as many grid units wide
as would normally be the case. (This was exactly the X2 = XC
+ W
case in Figure 13.2 where the width was made twice
and
the height.) If this same calculation is made with a
screen that has a width/height of 8/6, you will find Y2 = YC
+ W/2

Note that both X1 and X2 have been scaled so that


Figure 13.3 Plotting the largest possible rectangle. they are twice the size of Yl and Y2. The program
Ok: shown in Figure 13.5 will plot a square centered at
IeSHe
10 *PLOTTING RECTANGLES
PESOS) OS24mloa es Figure 13.4 Defining a square centered at XC,YC in high
Oy Ces resolution graphics.
40 LINE (100,50)—(200,100),1,8
Feet ed IN sac os) enieonl ) ly (X1,Y1)
100 GOTO 100
Ok

(X2,Y2)

+ 2*W+1

117
Figure 13.5 Plotting a square of width 2*W+1=101 Figure 13.6 Plotting a series of concentric squares.
centered at (320,100). Ok
(a) Ok ERS
Eis 5 * PLOT A SQUARE
ao * PLOT A SQUARE 1c) SGREENT 2
19 SCREEN 2 ZONES
205CES ZO XC=320: YC=100
SO XC=B20; YC=100 Ate (aaler (Heste) ain). wtexoy fsyileiee alte)
40 W=SO SO Xi=XC-W: Yi=YC-W/2
20 X1=XC-W: Y1=YC-W/2 60 X2=XCt+W: 2=YCtW/2
60 X2=XC+W: Y2=YC+W/2 TO MGINES CRD I OX ee Ve) he
TAB) VAINEs COCil aeWEI ol) Cee yae Aes! 80 NEXT W
100 GOTTA 100 100 GOTO 100
Ok Qk

(320,100) with width 2*W=100 (width is really example, in Figure 13.7 a star is shown plotted in
2*W+1 = 101) and a height of W (really W+1=S1). such a coordinate system. Note that the Y coordinate
By making lines 40-80 into a FOR ... NEXT loop is plotted in its “normal” upward direction which is
that varies the width W, a series of concentric squares opposite to the Y screen coordinate. We will let the
can be plotted as shown in Figure 13.6.

EXERCISE 13.1 Figure 13.7 Defining a star centered on a new X,Y


Plot a square that is 100 horizontal points wide and coordinate system.
has its upper left-hand corner at the coordinates X=90,
Y=30.

EXERCISE 13.2
Write a program that plots a sequence of squares on
the screen. All squares should have the same width
2*W+1=101, but the values of the center coordinates
XC and YC should vary from 50 to 150 in steps of
4. That is, the first square should be centered at (50,50),
the second square at (54,54), etc.

Plotting Line Figures

Suppose you want to draw some arbitrary figure made


up of a sequence of straight line segments. It is conve-
nient to plot the figure on a new X-Y coordinate system
that is centered on the screen coordinates XC, YC. For

118
computer take care of this difference. Also note that ‘Figure 13.8 Program to plot a star.
we have located the origin of our new coordinate sys- LIST
tem near the center of the star and that the horizontal 10 * PLOT A STAR
values have not been doubled to take into account 20 SCREEN 2
=O CLS
screen scaling. We will scale the horizontal values as 40 GOSUB 200: “FILL ARRAYS
they are used. . 5O XCSB20: YC=S100
Having the origin of the coordinate system near 60 LINE (XOX CO), YERY CO) >= OXC+X (1), YErY ¢
the center of the star means that the coordinates of Teeth
the vertices of the star may contain negative values
70 FOR I=2 TO M
BO LINE —(XC#X(1),YC+HY(1))41
as shown in Figure 13.7. For the star to fit on the 90 NEXT I
screen it is necessary for the value of XC to be in 190 GOTA 100
the range 100-539 and the value of YC to be in the 200 *FILL X,Y ARRAYS
210 M=S: DIM X(M),Y CM)
range 50-159. (Remember that the horizontal values 215 HSF = 2
must be doubled.) 220 FOR [=O TO MsREAD X(T): X(T) =HSFXRX (CI
For any center point XC, YC the star is completely sae XT it
defined by the (X,Y) coordinates of its vertices 250 FOR T=0 TO MEREAD Y CID: YCIJ==Y Cr):
NEXT? fT
(—40,—40) 240 RETURN
220 DATA -406,0,40,-50, 50, -40
(140; %50) 260 DATA -—40,50,-40,
20, 20,-40
Ok
( 40,—40)
(—50, 20)
star to be at the screen coordinates (320,100). Line
(550;..20) 60 plots the first line from
We will store these vertex coordinates in two DATA
(XC + X(0), YC + Y(0)) = (320 — 80, 100 + 40)
statements, with all of the X coordinates in the first
= (240, 140)
DATA statement and all of the Y coordinates (in the
same order) in the second DATA statement. to
The vertex coordinates will be stored in the order (XC + X(1), YC + Y(1)) = G20 + 0, 100 — 50)
you would use to draw the figure in a dot to dot fashion. = (320, 50)
If you return to the starting position then the first
(X,Y) coordinate must also be the last one. Thus, the Remember that all of the X(I) values were doubled
two DATA statements in line 220 and that all of the signs in Y(I) were inverted
in line 230. The statements
250 DATA —40, 0, 40, —50, 50, —40
260 DATA —40, 50, —40, 20, 20, —40 70 FORI=2TOM
80 LINE —(XC + xX(@), YC + Y(@), 1
will be used in Figure 13.8 to plot the star shown in
90 NEXT I
Figure 13.7. Statement 250 contains all of the X coordi-
nates and statement 260 contains the corresponding shown in Figure 13.8 will plot the remaining four lines
Y coordinates. of the star. In line 80 the LINE statement has the
The program shown in Figure 13.8 will plot this general form
star. After setting up our high resolution graphics
LINE —(X2,Y2), 1
screen in line 20, the subroutine at line 200 is used
to fill the arrays X(1) and Y(I) with the vertex coordi- where the first coordinate point (X1,Y1) is missing.
nates. These arrays are DIMensioned in line 210 and In this case the line is drawn to the point (X2,Y2)
then the vertex coordinates stored in the DATA state- specified in this statement from the last point refer-
ments are read into the arrays X(I) and Y(IJ) in lines enced in the previous LINE statement. This allows
220 and 230. Note that in line 220 each value stored us to work our way around the star in a point-by-
in X(1) is multiplied by the horizontal scale factor point fashion.
HSF (defined to be 2 in line 215), and that in line The result of running the program given in Figure
230 each value stored in Y(I) is changed in sign. This 13.8 is shown in Figure 13.9.
is done because X values must be scaled and because
the Y coordinate shown in Figure 13.7 (from which EXERCISE 13.3
the DATA coordinates were determined) is opposite Write a program that will plot the sailboat shown in
in direction to the Y screen coordinate. Figure 13.10 with the center coordinates XC,YC lo-
Line 50 in Figure 13.8 defines the center of the cated at the screen coordinates (300,120).

119
Figure 13.11 Program to plot a star with scale factor S.
Eto
LOR AOA EeSilrars
20 SCREEN 2
SAG) Ass:
40 GOSUB 2oOO: “FILL ARRAYS
SO XC=520: YC=100: S=1.8
60 LINE (XC+X (0) *S, YC+Y (0) #S)—-(CXC+XC1) KS
HV ABREN oel ye Ces a
7O® FOR. T=2°7O°™M
BO LINE —¢(XC+X (I) *S, YC+Y (1) kS),1
SAG) INSEE
100 GOTO 100
200 “FILL X.Y ARRAYS
S10 Maas. OGM xh. YOR?
205 HSh =
220 FOR I=0 TO M:READ X(1): X (1) =HSF
XX CT
Ys NEXT if
250 FOR I=0 TQ MsREAD YCI): Y(T)=-Y¥CI)
NEXaiest
Figure 13.9 Result of running the program shown in Figure 240 RETURN
13.8. 250 DATA —-40,0,40,-50, 50, -40
260 DATA —40, 50, -40, 20, 20,—-40
Ok
Scaling Figures

If the coordinates of the points in a figure are stored using the scale factor S, it is a simple matter to plot
in the arrays X(I) and Y(I) as described above, then the figure at different locations on the screen by chang-
it is a simple matter to plot the figure a different size. ing the values of the center coordinates XC and YC.
All you have to do is to always use
EXERCISE 13.4
X(D*S Write a program that will plot nine stars in a 3 X 3
and arrangement on the screen. The size of each star should
be half the scale shown in Figure 13.7 and the stars
YD *S should not overlap.
in your LINE statements where S is the scale factor.
For example, a value of S=2 will cause the figure to EXERCISE 13.5
be plotted double size and a value of S=0.5 will cause Write a program that will plot five stars on the screen
the figure to be plotted half size. at random locations. Take care to insure that no part
As an example, the program shown in Figure 13.11 of any star ever can extend beyond the edge of the
will plot the star shown in Figure 13.7 with the scale screen.
factor S defined in line 50. The result of running this
program for a value of S=1.8 is shown in Figure 13.12. Figure 13.12 Result of running the program shown in Figure
(Sette
In addition to plotting a figure different sizes by

Figure 13.10 Picture to be used in Exercise 13.3.

120
EXERCISE 13.6 ‘AR = AD*PI/180
Modify the program in Exercise 13.5 such that the
is the same angle expressed in radian where PI =
size of each star as well as its position is random.
3.141593 (see Figure 3.29).
A program for plotting circles is shown in Figure
13.14. Line 20 clears the screen and lines 30—SO print
Plotting Circles
an initial message. The user can specify the vertical
radius R and angular step size S in lines 60 and 80.
How can you plot a circle in high resolution graphics?
Line 90 switches to the high resolution graphics screen.
There is an easy way to do it using the CIRCLE state-
Line 100 defines PI. The center of the circle will be
ment in IBM PC Advanced BASIC. Before we look
located at the screen coordinates XC,YC defined in
at this statement, however, we will show you how to
line 110. The first line segment of the circle is plotted
plot a circle using only the LINE statement. This will
(in line 140) from the screen coordinates (XC +
give you a better understanding of how circles are
HSF*R, YC) to (XC + X1, YC + Y1) where X1
drawn. It will also give you a greater feeling of value
and Y1 are calculated in line 130. In lines 130, 140
for the CIRCLE statement.
and 170 HSF*R was used, rather than just R, because
Figure 13.13 shows a circle of radius R with its
the horizontal distances must be scaled up by the hori-
center at the origin of a local X-Y coordinate system.
zontal scale factor HSF in high resolution graphics
Recall from trigonometry that for the triangle OPQ
in order to maintain symmetry. If this were not done
the sine of the angle A is defined as
we would get an ellipse, rather than a circle. The FOR
SIN(A) = Y/R ... NEXT loop in lines 150-200 plots the rest of the
circle. Notice that the angle AD increases from S de-
and the cosine of the angle A is defined as
grees to 360 degrees in steps of S degrees. Line 160
COS(A) = X/R converts AD to an angle AR in radians. Lines 170—
180 calculate the next values of X and Y on the circle.
Therefore we see that any point P on the circle has
Note that line 180 inverts the Y value because the
the (X,Y) coordinates
positive Y direction in Figure 13.13 is opposite to the
X = R*COS(A) Y screen axis. The next segment of the circle is plotted
Y = R*SIN(A) in line 190.
You should type in this program and run it. Some
We can therefore plot the circle by letting the angle sample runs are shown in Figure 13.15. Note that if
A increase in steps, calculate new values for X and the angle step size gets too big, then a polygon is plotted
Y from the equations above, and plot LINEs from
the last points to the new points. If we let A increase
from 0 to 360 degrees we will plot the entire circle. Figure 13.14 A program for plotting a circle of radius R
We must remember that when using the built-in func- using high resolution graphics.
tions SIN(A) and COS(A) the angle A must be in 10> {PLOTTING GLRELES
2OwEkS
radians. If AD is the angle in degrees then 30 PRINT "AFTER CIRCLE IS PLOTTED
40 PRINT "PRESS A CAFITAL *Y* TO FLOT"
SO PRINT "A NEW CIRCLE. "sFRINT
Figure 13.13 Relationship between a point (X,Y) on a circle 60 INPUT "ENTER RADIUS (1-95) "sR
and the radius R and angle A. 70 IF R21 OR R298 THEN 60
Ne 80 INPUT "ENTER ANGLE STEF SIZE (DEG) "3S
90 SCREEN 2: CLS
100 PI = 3, 141593
105 HSF = 2
110 XC=320: YC=100
120 SR = SxPI/180
130 X1SHSFARXCOS(SR): Y1=-RxXSIN(SR)
< 140 LINE (XC+HSF*R, YC)—-(XC+X1,YC+Y1),1
i 150 FOR AD=S TO 360 STEP $
H Be x
160 AR = ADKPI/180
170 X=HSFRR*XCOS (AR)
180 Y=-R*kSIN(AR)
190 4CINE —(X€+xX, YC+tY), 1
200 NEXT AD
210 PRINT "ANOTHER CIRCLE? (Y,N)"
215 AS = INKEY$: IF AS=""" THEN 2105
S20 UR Ase EY GOTOs ao
220 END

121
Figure 13.15 Examples of running the program shown in rather than a circle. This suggests an easy way to plot
Figure 13.14. some interesting multiple polygon figures. The next
section will describe such a program.
As mentioned above, IBM PC Advanced BASIC
makes it easy to plot circles (faster) by using the CIR-
CLE statement. This statement can be used in either
high, or medium, resolution graphics modes, but is
available only in Advanced BASIC. (Remember you
load Advanced BASIC from disk into main memory
by typing BASICA, rather than BASIC, when you
initialize the system.) The general form of the CIRCLE
statement is

CIRCLE (XC,YQ), R,C,ST,EN,AS


where (XC,YC) are the center coordinates and R is
the radius of the circle. The remaining parameters are
optional. C is the color parameter. In medium resolu-
tion graphics C is chosen from the current palette.
In high resolution graphics, C=0 gives black and C=1
gives white. The default value in high resolution is
white.
AS is the aspect value. This parameter allows you
to draw ellipses, as well as circles. The AS value to
use to get a perfect circle will depend upon the proper-
ties of your particular display. However, a value for
AS in the range of 0.45 to 0.5 should give a perfect
circle (in high resolution). Values less than this will
give a “horizontal ellipse” while larger values will give
a “‘vertical ellipse.’ For all values of AS<1, R is the
X radius. For values of AS>1, R is the Y radius.
The parameters ST(start) and EN(end) specify the
starting and ending points on the circle. They both
must be specified in radians in the range —2*PI to
+2*PI. Specifying ST and EN will allow you to draw
arcs of circles. If ST is omitted its value is 0; if EN
is omitted its value is 2*PI.
In order to see how powerful the CIRCLE state-
ment is, note that we can replace lines 120-200 in
Figure 13.14 with the single statement

120 CIRCLE (XC,YO), R,1,,,AS


as shown in Figure 13.16. We have also replaced line
80 with

80 INPUT “ENTER ASPECT RATIO”;AS


Not only will the circles be plotted much faster than
in Figure 13.14 but we can easily change the aspect
ratio as shown in Figure 13.17.

EXERCISE 13.7
Modify the program in Figure 13.16 so that the user
can enter values for ST and EN. Run the program
and plot various portions of a circle.

122
Figure 13.16 Program for plotting circles using the EXERCISE 13.8
CIRCLE statement. Write a program to plot the “ball” shown in Figure
ae 13.18. Think of looking at the end of the ball and
10 "PLOTTING CIRCLES then plotting a series of circles at different angles B,
20 CLS as shown in Figure 13.18. Let B increase from 0 to
ZO PRINT “AFTER CIRCLE IS PLOTTED 60 degrees in equal increments and note that the aspect
40 PRINT "PRESS A CAPITAL *Y*° TO FLOT" ratio of the plotted ovals is COS(B)/HSF.
SO PRINT "A NEW CIRCLE, "sPRINT
60 INPUT "ENTER RADIUS (1-95) "ER
7O IF Rei OR R295 THEN 40
80 INPUT "ENTER ASPECT RATIO";AS Plotting Polygons
90 SCREEN 2: CLS
100 PI = 3.141593, Suppose you would like to plot the picture shown in
110 XC=320: YC=100 49 You cou ld
120 CIRCLE (XC,YC)«Relss.AS Figure 13.19. How would you go about it?
210 PRINT "ANOTHER CIRCLE? (Y,N)" start at the vertex X(1), Y(1) and draw the four lines
215 AS = INKEY$: IF AS="" THEN 215 to X(K), Y(K) (K=2 to 5) as shown in Figure 13.20a.
SG
S20 £
oes a aaad Next you could add the three lines P from: X(2),¥(2)
Ae to X(K), Y(K) (K=3 to 5) as shown in Figure 13.20b.

Figure 13.17 Examples of running the program in Figure


13.06:
(a)

QMOTHER CIRCLE? (¥,)

(d)

GMOTHER CIRCLE? (YN) ANOTHER CIRCLE? (¥,N)

123
Figure 13.18 Plotting a 3-D ball (Exercise 13.8). Next you could add the two lines from X(3),Y(3) to
(a) X(K), Y(K) (K=4 to 5) as shown in Figure 13.20c.
Finally you would add the line from X(4),Y(4) to
quormme CIRCLE? (¥,10 X(5),Y(5). Note that the four steps shown in Figure
13.20 can be carried out by the algorithm

for J=1 to N—-1


for K =J+1toN
plot line from X(J),Y(J) to X(K), Y(K)
next K
next J

where N is the number of vertices in the polygon (5


in Figure 13.20).
Think of a circle that passes through all of the ver-
tices of the polygon. If R is the radius of this circle
then the N coordinate pairs X(I), Y(I) can be calculated
from the following algorithm.

for IT=1toN
AD = I*360/N
AR = AD*PI/180
X(D = R*COS(AR)
Y(D = R*SIN(AR)
next I

Note that this algorithm divides the circle into N pie-


shaped wedges where the angle of each “pie piece”
CIRCLE
is 360/N degrees. The coordinates X(I), Y(I) are then
calculated using the equations of the circle.
A program that will plot this polygon figure for
polygons with from 3 to 15 sides is shown in Figure
13.21. The center of the polygon will be at XC,YC
which are specified to be 320,100 in line 80. The radius
Figure 13.19 A polygon with a line drawn between all of the circle that would pass through the polygon verti-
vertices. cies is set to 90 in line 60. After entering the number
Y of sides N in line 50 and checking to make sure that
N is between 3 and 15 in line 55, the subroutine at
line 200 is called in line 65. This subroutine calculates
the N coordinates X(I), Y(1) as described above. Note
that line 240 contains the horizontal scale factor, HSF
(2.4 defined in line 205), and that line 250 inverts the
Y coordinates as usual.
X(5), ¥(5) Lines 100-130 actually plot the polygon figure using
the nested for... next loops described above. Notice
that the LINE statement in line 120 will cause the
polygon to be centered at XC, YC. After plotting the
figure, line 190 will wait for a key to be pressed before
determining in line 195 whether to branch back to
line 20 or to end the program.
Type in this program and run it. Two figures that
X(3), ¥(3) X(4), Y(4)
can be generated by this program are shown in Figure
13.22. Try some different values of N.

124
X(1)¥ (1)

(a) (b)

Figure 13.20 Steps in generating the


(c) (d) picture shown in Figure 13.19.

Figure 13.21 Program to plot a polygon figure with from Plotting Functions
3 to 15 sides.
10 *PLOTTING POLYGON FIGURES The graphics capability of the IBM PC makes it a
15 DIM X¢13),.Y (1S)
20 CLS
useful tool for studying the behavior of mathematical
30 PRINT "AFTER POLYGON IS PLOTTED" functions. For example, the function
re] PRINT "PRESS A CAFITAL *Y* TQ"
40 PRINT "PLOT ANOTHER POLYGON": PRINT y(x) = A sinQQzx/T + o )
=i18) INFUT"ENTER NUMBER OF SIDES(3-15) "aN
ate IF N23 OR Ne1S THEN So
defines a sine wave with amplitude A, period T and
cat) Place tadog ssh =. 70) phase angle $. You can define this function by using
6S GOSUB 2OO: "CALCULATE POINTS the BASIC statement
70 SCREEN UZ FCS
ao XG = 320: YC = 100 DEF FN Y(X) = A*SIN(2*PI*X/T + PH)
100 FORSJ = o1 10: N-1
110 FOR & = J+1 JON where PI = 3.141593 and PH is the phase angle in
120 LINE (XC+X(J),YC+Y (J) )—-(XC+X (BK) YOHY (KD) aD radians.
130 NEXT Ki NEXT J A program that will plot this function is shown
185 PRINT "PLOT ANOTHER FOLYGON?"
in Figure 13.23. The subroutine at line 200 that is
186 PRENTOUPRESSS ey OR. NG
190 AS=INEEY$; IF AG=""" THEN 190 called in line 90 will plot the axes shown in Figure
195 Tape fey THENE 20) 13.24a. Each grid mark on the axes represents an incre-
198 END ment of 10 screen units. Lines 50-60 allow the user
200) “CALCULATE FOINTS
to enter values for the amplitude A, the period T,
20
210 and the phase angle PH (in degrees). Line 70 switches
220 TkS60/N to the high resolution graphics screen. Line 100 con-
2350 ADKFI/180 verts the phase angle from degrees to radians. Line
BAC HSFkXR*COS (AR)
110 defines the sine wave as a function Y(X). (The
20) —-RXSTN CAR)
2&0
negative sign in line 110 is our usual inversion because
270 the positive Y screen coordinate points downward.)

125
Figure 13.22 Examples of polygon figures that can be Figure 13.23 Program to plot a sine wave.
generated by the program shown in Figure 13.21. 10 * PLOT A SINE WAVE
(a) 20 CLS
=O PRINT “AFTER SINE WAVE IS PLOTTED"
35 PRINT "PRESS A CAPITAL *Y’TO PLOT”
40 PRINT "@ NEW SINE WAVE": PRINT
45 PRINT "“Y=AXSIN(2kKPIXX/T+PHAS E"
s PRINT
SO INPUT "ENTER AMPLITUDE A (0-95) "5A
55 INPUT "ENTER PERIOD T"3T
60 INPUT "ENTER PHASE ANGLE "3PH
65 PI =3.141593
70 SCREEN 2: CLS
90 GOSUER 200: * PLOT AXES
100 PH=FH*FI/180
105 HSF = 2
110 DEF FN Y(X)=-AKSIN(2XPIXX/T+PH)
120 X1=-160: Y1=FN Y(X1)
130 X2=-159: Y2=FN Y(X2)
140 LINE (XC+HS F*X
YC+Y1) —(XC+HSFRX 2,1,YC+Y2) 1
150 FOR X = -158 TO 159
160 Y = FN Y(X)
170 LINE -—(XC+HSFXX,YC+Y),1
180 NEXT x
190 PRINT "PLOT ANOTHER SINE WAVE?"
192 PRINT "PRESS Y OR N"
194 AS=INKEY$: IF A$="" THEN 194
195 IF At = "Y" THEN 20
197 END
200 *FPLOT AXES
2IOiKC = S20: YEr= 100
220 LINE (0,YC)-(639,YC)41
230 LINE (XC,0)-(XC,199)41
240 FOR X = 20 TO 620 STEF 20
250 LINE (X,YC) - (X,YC-S)ql
260 NEXT X
270 FOR Y = 5 TO 195 STEP 5
280 LINE (XC-5,Y) — (XC+5,Y),1
290 NEXT Y
295 RETURN
Type in this program and run it. A sample run is
shown in Figure 13.24b. By entering different values
of the amplitude A, period T, and phase angle PH
you will be able to get a good idea of how this function
The origin of the coordinate system plotted in the behaves.
subroutine at line 200 is located at the screen coordi-
nates XC,YC (defined to be 320,100 in line 210). The EXERCISE 13.9
first line segment of the function that is plotted (in Write programs that the user can use to plot the follow-
line 140) will be from the left-most value of X ing functions for different values of the parameters
(X1=—160) to the next larger value of X (X2=—159). A, C, and N:
These values together with the corresponding values
1. Y = A*LOG(X/C) X >0
of Y = FN Y(X) are assigned in lines 120-130. Line
140 multiplies the values of X1 and X2 by the horizontal 2. Y = A*EXP (—X/©)
scale factor HSF (2), so that the first X value used 3. Y=XAN/C
is really —320 (rather than —160). There are several 4. Y= A*SQRQX/C) X>0
ways that the horizontal scale factor could have been
entered. In fact, in this case, since no values are placed
on the axes, we could have left the figure unscaled! PLOTTING SHAPES
The FOR . . . NEXT loop in lines 150-180 plots USING THE DRAW STATEMENT
the rest of the curve. Notice that the value of X is
increased from —158 to +159 and for each value of Earlier in this chapter you learned how to store the
X the value of the function Y(X) is calculated in line vertices of a graphic figure in DATA statements and
160. then use the LINE statement to draw the figure in a

126
Figure 13.24 (a) Axes plotted by the subroutine at line 200 _ Figure 13.25 The letters U, D, L, R define moves Up,
in Figure 13.23. (b) Example of sine wave that is plotted Down, Left, and Right, and the letters E, F, G, H define
by the program shown in Figure 13.23. the four 45-degree moves.
U

H E

YS eee SS SSS SSS

G F

Figure 13.26 Defining a shape in terms of basic motion


commands.

START HERE

D7 means ‘‘move Down 7 units”

L$="D7;R8”

dot-to-dot fashion. The IBM PC has another way of


drawing graphic figures. It is possible to define a
; — END HERE

graphic figure in terms of basic motion commands and R8 means “move Right 8 units”
to store these commands in a string. The basic motion
commands include Up, Down, Left, Right, as well
as the four intermediate directions in Figure 13.25.
For example, the L-shaped figure shown in Figure
13.26 can be defined as the string L$=“D7;R8”. Figure 13.27 Preceding a move command with the letter
If you precede one of the move letters with a B B will cause a move without plotting.
pei HERE
(Blank) then the movement will occur without plotting.
For example, the cross shape in Figure 13.27 can be
defined as the string C$= “D8;BH4;R8”.
Another way to draw the cross in Figure 13.27 is
END HERE
to start at the center of the cross and plot the four Nr
arms, each time returning to the center. This can be
done by preceding each move command with the letter
N (No position update). Thus the string
move to here
F ;
\\ C$="'D8;BH4;R8”
Ci$=“NU4;NR4;ND4;NL4” without plotting N

127
Figure 13.28 Preceding a move command with the letter 30 LS$= “D7;R8”
N will cause a plot followed by a return to the starting 40 MS$= “BM300,50”
position.
50 DRAW M$-+L$
NL4 (plot 4 units as shown in Figure 13.29.
Left and return to NU4 (plot 4 units Up
starting point) and return
to starting point)

Relative Moves
NR4 (plot 4 units
Right and return
to starting point) After drawing one shape you may want to move to
C1$ = “NU4; NR4; ND4; NL4”
START AND a new position to begin drawing a new shape. You
END HERE
ND4 (Plot 4 units
will often know this new position relative to where
Down and return you finished the first shape rather than its absolute
to starting point)
screen location. If you include a plus or minus sign
before the X location in the M command, the computer
can also be used to define the cross as shown in Figure
will interpret the move as a relative move. For example,
13.28.
“BM+5,7” will move 5 units right and 7 units down
The M command is used to move to a starting posi-
on the screen from its current position. Similarly,
tion on the screen. This command must be preceded
“BM—10,—5” will move 10 units left and 5 units up
by a B to prevent unwanted lines from being drawn.
from its current position.
For example, the string M$=“BM300,50” will move
As an example, Figure 13.30 shows a program that
to location (300,50) on the screen.
plots the three figures defined in Figures 13.26—13.28
The DRAW statement is used to draw the figure.
using relative moves between each figure. Line 25 de-
It consists of the word DRAW followed by a string
fines C$ given in Figure 13.27 and line 35 defines C1$
expression that defines all of the move commands to
given in Figure 13.28. After drawing the L in line
be carried out. For example, to plot the L shown in
Figure 13.26 at location (300,50) on the screen you
Figure 13.30 Using relative moves to plot multiple shapes.
could use the following statements Ok (a)
ers
Figure 13.29 Plotting an L shape using the DRAW 10 “PLOTTING SHAPES
statement. 1S “USING THE DRAW STATEMENT
) Ok 7ho) eels) an [RLS
Sra eo CS = "D8; BH4;R8"
10 “PLOTTING SHAFES 2O LS = "D7ERB"
15 “USING THE DRAW STATEMENT oo ClS = "NU4sNR4:ND43 NL4"
2OROeREENi = SEIS 40 M$ = "BMEOO, 30"
SO he = 7 Rea sO DRAW M$+Ld
40 MS = "RBMSOO, 50" 60 DRAW "RM+O, 20"4+C$
so) DRAW MS+L.$ 70 DRAW "BM+20,0"4+C14
60 GOTQ 46 86 GOTO &o
(Mle

(b)

128
50, line 60 moves down 30 units and plots the cross. - Figure 13.31 The size of the shapes can be changed by
Line 70 then moves 20 units to the right and plots using the scale command ‘‘Sx.””
the second cross. Note that C$ and C1$ are two ways Ok (a)
of defining the same cross. assy
TOSS EE GT eth SHAr es
15 “USING THE DRAW STATEMENT
20 SCREEN 2: CLS’
Scaling Shapes 25 C#® = "DS8;BH4;R8"
sO L® = "D73Re"
SS C1# = "NU4;NR4;ND4;NL4"
If you include the string “Sx” in your DRAW state- 40 M$ = "BMSOO,50"
ment, where x is anumber from | to 255, all subsequent 20 DRAW M$+Ls
moves (until another “Sx” command) will be scaled S55 DRAW "Se"
according to the scale factors in Table 13.1. 60 DRAW "BM+0, 20"+CS
65 DRAW "Si2"
70 DRAW "BM+20,0"4+C1$
TABLE 13.1 Shape scale factors, Sx 80 GOTO go
Ok
x Scale Factor = x/4
is =- =|

1/4 scale
2/4=1/2 scale
4/4 = 1 = full scale
8/4 = 2 = double scale
12/4 = 3 =triple scale
===-=0OfN
lon) 16/4 = 4 = quadruple scale

eter:

Note that ‘‘S4” is full scale. That is, this is the scale
that you used to define the shape. If you don’t use
“Sx”, then the computer will use “S4’’.
In order to see how the scale factor works, add
the following two statements to the program in Figure
13.30a.

55 DRAW “S8”
65 DRAW “S12” program is shown in Figure 13.32. Note that the entire
screen has been rotated. This is because the “A1” com-
The result of doing this is shown in Figure 13.31. Note mand will stay in effect until a new “Ax” command
that the change in scale in line 55 causes the cross is given. Try changing line 50 to
drawn in line 60 to be double size, while the change
in scale in line 65 causes the cross drawn in line 70 50 DRAW MS+“S8; A1” + L$ + “A0”
to be triple scale. and see what happens.
When a figure is rotated either 90 or 270 degrees,
the horizontal and vertical values are automatically
Rotating Figures rescaled so that they have about the same shape in
their new orientation.
If you include the string ““Ax”’ in your DRAW state-
ment, where x is a number from 0 to 3, you will cause
all subsequent move commands to be rotated 0, 90,
180, or 270 degrees according to Table 13.2. TABLE 13.2 Angle rotation factors, Ax
For example, change line 50 in Figure 13.31 to
x | Angle of Rotation
50 DRAW M$+“S8;A1”+L$
O degrees
This should scale the shape L to double size (after 90 degrees (counter-clockwise)
180 degrees (counter-clockwise)
the move M$) and then produce a counter-clockwise
270 degrees (counter-clockwise)
Wnyo-o
rotation of 90 degrees. The result of running this new

129
Figure 13.32 Shapes can be rotated by using the angle Figure 13.33 Definition of cross to be plotted in Exercise
command ‘‘Ax.”’ 13.10.
(a) Ok R2
a
yg
TOM Rie OintiehMGgeortareS
15 “USING THE DRAW STATEMENT U2 D2
2Or SSREENEes. CES
25 CS = "D8; BH4;R8" R2 R2
30 LS = "D7sR8"
395 Cis = "NU4sNR45ND43NL4"
40 MS = "BMSOO, SO" U2 START D2
20 DRAW M$+"S8; AL" + LH
oo DRAW "Se"
60 DRAW "BM+O0, 20"+C$ L2
eg DRAW? Si" L2 BD3
79 DRAW "BM+20,0"4+C14 U2 D2
80 GOTTA 8oO
Ok

(b) L E

can write “S=K;” and “U=K;” where K is a numeric


variable.
For example, Figure 13.34 shows a program that
plots 35 crosses on the screen by using two nested
FOR . . . NEXT loops. Notice how the location of
the center of each cross is determined by the move
string in line 60 and how the size of each cross is
determined by the value of K in C1$. Since K is in-
creased in line 75 by 2 after each row is plotted, the
size of the crosses plotted in any row is larger than
the crosses in the previous row.
As an example of one additional DRAW command,
line 60 in Figure 13.34a
60 DRAW “BM=x;,=Y;”+C1$

can be written as
EXERCISE 13.10
60 DRAW “BM=x;,=Y;XC1$;”
Write the string that defines the cross shown in Figure
13.33. Write a program that plots this cross at location In this version the string C1$ has been moved inside
320,100 on the screen. Change the program so that the string containing the move (M) command, rather
the cross is plotted eight times its normal size. than being concatenated to it, by using the X com-
mand. A string of DRAW commands (such as C1$)
can be executed within another string by using the
Plotting Multiple Shapes command form
Xstring;
Sometimes when using the DRAW statement you
would like to move to location (X,Y) on the screen, The philosophy behind this command is that a string
where X and Y are variables. You cannot just use of commands to do some special graphic can be devel-
the string ““BMX,Y” because X and Y are numerical oped and stored as a separate string. This string can
variables and not string variables. However, IBM PC then be executed from within another string through
Advanced BASIC has a variation of the “BMX,Y” use of the X command. You should change line 60
command which will allow you to use X and Y as in Figure 13.34 to the second version shown above
numerical variables within the string. To do this X and execute the program. The results should be identi-
and Y must be replaced by =X; and =Y; giving cal to those shown in Figure 13.34b.
“BM=x;,=Y;”
EXERCISE 13.11
The same general method can be used in all the com- Write a program that plots a series of nested crosses
mands such as “S3” and “U5”. In these cases you (defined in Figure 13.33) all centered at (320,100) with

130
Figure 13.34 Line 60 moves to location x,y before drawing The drawing of the shape will always start in the upper
C1$. left-hand corner of the 5 X 7 grid and end in the
(a) Qh:
LIST lower right-hand corner. This will make it easy to plot
10 "PLOTTING MULTIPLE SHAPES multiple digits because you will always know where
15 "USING THE DRAW STATEMENT you stop after plotting a digit. You can then use a
20 SCREEN 2: CLS relative move to get to the starting location of the
25 Kk = 5 next digit.
SO C1S = "NUFKsNR=kKyND=KsNLSk3 "
40 FOR Y=20 TO 180 STEF 40 As an example, Figure 13.35 shows the definition
SO FOR X= 40 TO 560 STEP 80 of the digit 6. We will store the string in a DATA
60 DRAW "BM=X;,=V¥s" + C1$ statement to be read later into a string variable with
7O NEXT xX a READ statement. The semi-colon between different
75K eK +2
BO NEXT Y motion commands is optional, and we have omitted
90 GOTO 90 them in Figure 13.35 and just written all of the move
Ok commands next to each other in the DATA statement.
(The only places where semicolons are mandatory is
in the X command and any command that contains
an =variable, rather than a constant.) Note that the
drawing process starts at the upper left-hand corner
and first moves 5 right and 1 down without plotting.
It then plots the 6 in the same order you would write
it with a pencil, ending along the left side—3 units
from the bottom. The last two commands in the string
move down 3 and right 5 without plotting in order
to end at the lower right corner of the grid.
The DATA statements for all of the digits from
0-9 are given in lines 1000-1100 of the program shown
in Figure 13.36. These strings are stored in the array
N&$(I) using the subroutine at line 400 which is called
in line 30. The subroutine at line 300 will plot all 10
digits in a row. Note that line 330 will move right 3
and up 7 between the drawing of each digit. Lines
40-110 call this subroutine four times with different
the scale factor SF varying from 4 to 24 in steps of scale factors and starting locations. The result of run-
4. Hint: The scaling string can be defined as S=SF;. ning this program is shown in Figure 13.36b.
It should be clear that by using the DRAW state-
ment with prestored strings you can include any size
Plotting Numbers

You have seen that the size of the text that can be Figure 13.35 Defining the digit 6 on a 5x7 grid.
displayed in medium and high resolution graphics is me UA ol
[3
fixed. This means that if you wish to PRINT some G1 H1
standard text on a high resolution graphics figure you
are stuck with one size of character. Sometimes, how-
ever, you would like to include some text in your high
or medium resolution graphics displays and have the
freedom to vary text size. For example, you may want G1
to label the scale on a graph that you plot and pick
a character size that is visually appealing. You can D5
do this by defining shapes for the letters and digits
you want to use and then using the DRAW statement
to draw the shapes. Using the S command the letters
and digits can be adjusted to the desired size. F1 EI
R3 ““~ END HERE
We will illustrate the procedure by defining shapes
for the ten digits 0-9. Most of the digits (with the
exception of 1 and 4) will be defined on a 5 X 7 grid. DATA BR5BD1H1L3G1D5F1R3E1U2H1L3G1BD3BR5

131
Figure 13.36 Using the DRAW statement to plot numbers
in high resolution graphics.
(a) 10*PLOTTING NUMBERS USING DRAW (b)
LISDEREN I I
20 SCREEN es CLs
30 GOSUB 400: * DEFINE NUMBERS
40 DRAW "S4;BM10,30"
SQ GOSUB 300: * PLOT NUMBERS
60 DRAW "S8;BM10, 60"
70 GOSUB 300
B80 DRAW "S12;BM10, 100"
90 GOSUB 300
100 DRAW "S16;BM10, 150"
110 GOSUB 300
120 GOTO 120
299 °
300 *PLOT 10 NUMBERS
S01
310 FORGIS="O10 9
320 DRAW NS (TI)
330 DRAW "BM+2,-7"
340 NEXT I
=50 RETURN
399
400 * STORE NUMBER STRINGS
401 *
410 FOR I = 0 7T0 9
420 READ N#(TI)
430 NEXT I
440 RETURN
999
1000 * NUMBER STRINGS
1005 70
1010 DATA BR4BD7E1USHILSG1IDSFIRSBR1
1015 *1
1020 DATA BDIE1ID7NLIR1
1025 72
1030 DATA BDIEIRSFIDIGILSG1IDSRS
1035 °3
1040 DATA BDIEIRSF1IDIGINLZFID2G1LSHLBRSBD1
1045 °4
1050 DATA BRSGSRSNRINUSD2ER1
1055 °5
1060 DATA BRSLSD3R4F 1D2G1LSHIBRSBD1
1065
1070 BRSBD1HILIG1DSFIRSELU2ZHIL3G1BDSBRS
1075
1080 BDIU1IRSD7
1085
1090 BRIBDSHIUIELRSFIDIGILSGID2FIRSEIU2ZHIBD4BRI
1095
1100 BRSBDSGILSHIUZELRSF1DSGILSHIEBRSBD1

of text you wish on the high resolution graphics screen. This causes the screen to be placed into medium resolu-
This can be very useful for labeling graphs. You can tion, rather than high. If you rerun the program, you
even rotate the letters 90 degrees (using “‘A1’’) to write will find that the digits are the same height, but are
up the edge of a graph. The shape definitions for the twice as wide, because the spacing of horizontal points
26 upper case letters and 10 digits are given in Table in medium resolution is twice that present in high reso-
13.3. You can, of course, define your own lower case lution.
letters or other font types if you wish.
To illustrate the difference in resolution between
medium resolution and high resolution graphics,
EXERCISE 13.12
change line 20 in Figure 13.36 to
Modify the program shown in Figure 13.23 so as to
20 SCREEN 1: CLS label the axes and print SINE WAVE above the graph.

132
TABLE 13.3 Shape definitions for letters and digits Figure 13.37 Painting the digits 8 and 6 using the PAINT
statement.
BRS5BD3LS5ND4U2E1R3F1D6 (a)
Ok
ND3R4F1D1G1L4D4R4E1U2H1BD4BR1
LIST -120
BR5BD1H1L3G1D5F1R3E1BD1
10 “PLOTTING NUMBERS USING DRAW
ND7R4F1D5G1L4BR5 15 DEFINT I
NRSD3NR4D4R5 20 SCREEN 2: CLS
NRSD3NR4D4BR5 30 GOSUR 400; * DEFINE NUMBERS
BR5L4G1DS5F1R3E1U2L2BD3BR2 40 DRAW "BM100, 20;S603 XN#(8) 3"
D3ND4RSNU3D4 5O PAINT (120,50)
RINRID7NLIR1 60 DRAW "BM400, 2035603 XN# (5) 3"
BDSD1F1R3E1U6BD7 70 PAINT (420,120)
D3NE3ND4F4 120 GOTO 120
D7R5 Ok
ND7F3E3D7
ND7F7NU7
BD1D5F1R3E1U5H1L3G1BD6BR5
ND3R4F1D1G1L4D4BR5
BD1D5F1R3E1U5SH1L3G1BD4BR3F2
ND7R4F1DIGIL4F4BR1
BRSL4G1D1F1R3F1D2G1L4BR5
R3NR3D7BR3
D6F1R3E1U6BD7
D4F3E3U4BD7
D7E3F3U7BD7
F3NE3D1NG3F3
F3NE3D4BR3
R7G7R7
BR4BD7E1USH1L3G1D5F1R3BR1
BDIE1D7NLIRI1
BDIEIR3F1D1G1L3G1D3R5
BD1E1R3F1D1GINL3F1D2G1L3H1BRSBD1
BRSGSRSNRINUSD2BR1
BRSLSD3R4F1D2G1L3H1BRSBD1
BRS5BD1H1L3G1D5F1R3E1U2H1L3G1BD3BR5
BD1U1RSD7
BR1BD3H1U1E1R3F1D1G1L3G1D2F1R3E1U2H1BD4BR1
Line 70 will then paint the lower part of the 6 white.
LOmMMOIODP
AGH
HDPOVOZEAOC
SCH
CHIRAURLONHONKME
BR5BD3G1L3H1U2E1R3F1D5G1L3H1BRSBD1
The result of running this program is shown in Figure
13.37b. You should run this program and try painting
different digits by changing the number in N§(8) or
N3$(6) in lines 40 and 60. What do you think will
Painting the Figures happen when you paint a 3? Try it.

Now that you have learned how to plot almost any


shaped figure you want on the graphics screen, you PAINTing in
should know how to paint in areas of the screen with Medium Resolution Graphics
either black, or white, or a color. The PAINT state-
ment will make this easy. In high resolution graphics The PAINT statement can be used to paint with colors
the form of the PAINT statement is only in the medium resolution graphics mode. In me-
dium resolution graphics the form of the PAINT state-
PAINT(X,Y)
ment is
Starting at screen location (X,Y) this statement will
PAINT(X, Y),C,B
either fill a black area with white until a white border
is reached, or fill a white area with black until a black X and Y have the same meaning here as before; namely
border is reached. In order to see how this statement they are the coordinates of a point within the area
works, change the main program in Figure 13.36 to to be painted. C is the color code of the color with
that shown in Figure 13.37. which the area is to be painted, and is chosen from
The DRAW statement in line 40 will plot a large the current active palette. B is the color code of the
8 in the upper left portion of the screen. Line 50 will border to which the color C is to be painted. B must
then paint the upper part of the 8 white. Line 60 places also be picked from the current active palette.
a large 6 in the upper right portion of the screen. As an example of the use of the PAINT statement

133
Figure 13.38 Using PAINT in color in medium resolution in medium resolution graphics, the main program in
graphics. Figure 13.37 has been modified to that given in Figure
(a) oO}: 13.38. Several changes have been made. Line 20 now
See)
switches the screen to medium resolution and enables
10 *FLOTTING NUMBERS USING DRAW
ay JORIS it color. Line 25 has been added to select the background
SOS SEREEN Tl. tian eles color as black and to select palette number one.
fur) AOL Oiaual In lines 40 and 60 the move (M) commands in the
=0 GOSUBR 400; DEFINE NUMBERS
DRAW statement have been altered to place the 8
40 DRAW "BMSO, 20; 960; C23 XNS(S) 3"
30 FPAINT(70,50),2,3 and the 6 correctly on the medium resolution screen.
60 DRAW "BM2OO, 2039560; Cl5 XN#S(46) 5" These statements also have an addition in the form
79 FAINT (220,120),1,35 of a C (color) command. The C command selects the
ES) (EAGTES Geeks) color, from the current active palette, that the DRAW
Ok
statement is to use in drawing lines. In both cases
C3 has been used, indicating the letters will be drawn
in palette color code 3 (white).
In line 50 the painting of the upper part of the 8
will be in palette color code 2 (magenta) and in 70

) the painting of the bottom part of the 6 will be in


palette color code 1 (cyan). In each case the painting
will stop at a border with palette color code 3 (white).
The white border was chosen since this was the color
in which the 8 and the 6 were drawn.
When the program is run it should give a result
as shown in Figure 13.38b.

EXERCISE 13.13
Add PAINT statements to the program used in
Chapter 7 to draw a house. Paint the roof green, the
door red and the sides brown.

134
LEARNING O PEEK AND POKE

You have learned that the IBM PC contains a large . to use the PEEK and POKE statements,
number of memory locations that are used to store . to POKE characters in color and reverse video,
the program and data. Some of this memory is read/ . to POKE graphic figures, and
write memory (RAM), some is read-only memory
N . to produce
WwW
a> animated graphics.
(ROM) and some is special input/output memory that
allows communication to the outside world. Examples
of communication with the outside world include get-
THE STATEMENTS PEEK AND POKE
ting data from the keyboard and writing and reading
data to and from a diskette.
The 8088 microprocessor (see Figure 2.1) that is the
When writing a program in BASIC you refer to a
“brain” of the IBM PC can address over a million
memory cell by its name, such as A$, or C3. You
memory locations. The reason the 8088 microprocessor
do not know exactly which memory location within
can address so many memory locations is that the
the IBM PC contains the data in C3. The computer’s
8088’s addressing mechanism is somewhat more com-
BASIC interpreter automatically takes care of assign-
plex than those used on most microcomputer systems.
ing these locations. However, in order to use the full
Like most microprocessors the 8088 has what could
power of the IBM PC, you must sometimes read and
be called 16 “standard address lines.’’ Each of these
write data to specific memory locations within the com-
lines can be high or low (0 or 1). Thus a typical address
puter. In order to do this with maximum flexibility
might be represented by 16 bits.
and speed you must write the program in assembly
language. Learning how to do this will be covered in 0011010111000001
a second book entitled ““8088-IBM PC Assembly Lan-
This binary number is equivalent to the decimal num-
guage TUTOR.”
ber 13761. Since each of the 16 bits in the address
You can, however, read and write data to specific
can be either a 1 or 0, then the total number of ad-
memory locations even in BASIC. You do this by using
dresses possible with these address lines is
the PEEK and POKE statements. In this chapter you
will learn how: 216 = 65536
1. data are stored in memory locations in the IBM On many microprocessors 65536 is the maximum
iW@Ge amount of directly addressable memory. However, on

135
Actual a brief discussion of hexadecimal numbers is given in
Address Memory
0000
Appendix D.
In addition to address lines the 8088 microprocessor
has 8 data lines.* These lines connect the microproces-
DS —— 4096 0 A relative address of sor to all of the memory chips in the IBM PC. Thus,
: 350 gives an actual
DS points to address of 4096 + 350 = 4496 data are moved between memory locations in groups
location 4096 of 8 bits called bytes. The total number of different
4496 350 values that a data byte can have is

28 = 256
Figure 14.1 Relative 8088 addresses must be added to a
Thus, data in a single memory location in the IBM
segment register to get the actual address.*
PC can store a value between 0-255. This relationship
between addresses and data is shown in Figure 14.2.
the 8088 the address developed from these “standard In this figure memory location 1024 contains a data
address lines” is not the final address, but rather this value of 255 (8 ones), and memory location 1025 con-
address is added to the address contained in a segment tains a data value of 5.
register to get the actual physical address. Since the
i
address generated by this second register has a maxi- \
mum value of 983040, the final address can be as large 255
as 1025 00000101 uy
Data=5
Address 1024
0000010000000000 1026
983040 + 65535 = 1048575 15 :

As an example, when you “boot” your IBM PC


and the disk operating system (DOS) is loaded into
memory, the system automatically sets a value in a
special segment register called the Data Segment Regis- 1030

ter (DS). The value placed in this register is chosen 1031 |


!
|
|
so that it “points to” the lowest address present in
Figure 14.2 Each address points to a memory location
the area of memory called the user workspace. Assume containing data in the range 0-255.
for the moment that this register points to memory
location 4096. From this point on, when you specify
You can find the data value stored in a particular
an address—e.g. 350—you really mean address 350 +
memory location by using the PEEK statement. You
4096 = 4446! (See Figure 14.1.)
can store a particular data value in a given memory
Normally you will never change the value in DS,
location by using the POKE statement.
and normally you don’t even care what value is in
DS. The only exceptions are when you wish to use a
subroutine written in assembly language, or when you
PEEK
wish to PEEK and POKE in memory in the manner
to be discussed in this chapter. Although the 8088
The function
can effectively address over a million memory loca-
tions, your IBM PC will contain considerably less than PEEK (N)
this maximum amount of memory.
returns the data value stored in the memory location
When working with binary numbers such as the
with an address equal to N plus the address pointed
address given above it is convenient to represent these
to by DS. The value of N must be in the range 0 to
binary numbers as hexadecimal numbers. This is not
65535. If you wish to look at the values in memory
necessary when using BASIC because the PEEK and
locations with actual addresses in the range 0 to 65535,
POKE statements can use decimal numbers. However,
you must first set DS to zero. After doing this,
if you want to program in assembly language, then
PEEK(N) will return the contents of location N (since
the use of hexadecimal numbers is essential. Although
N+0=N). DS can be set to zero by the statement
you do not need to know anything about hexadecimal
numbers for anything in this book, if you are curious, DEF SEG = 0

* The value stored in DS is actually multiplied by 16 before it is * These are really the same physical lines as 8 of the address lines.
added to the offset address. Thus in this case if DS is meant to The data are put on these lines at a different time than the address.
“point to” 4096, it will contain 256. This is called time multiplexing.

136
Figure 14.3 Memory location 3033 contains the value 12 Figure 14.4 PEEKing into a location that was assigned an
and memory location 5100 contains the value 180. integer value in BASIC.
Ok (a)
DEF SEG = 0
Ok
PPEEK (3033)
i
Qk D =~ ll VARPTR (BX)
?PEER (S100)
180
Ok 3655
Ok
?PEER (AZ)
Enter this in the direct mode from the keyboard (be
25
sure you leave a space between DEF and SEG) and Ok
then enter PBL
el
?PEEK(3033) Ok
?PEEK(5100)
(b)
as shown in Figure 14.3. The output shown indicates
that memory location 3033 contains 12 and memory Ok
location 5100 contains 180. (Your IBM PC may have PFEEE (AZ)
el—d a
£5u
different values in these locations, so don’t be disturbed
Ok
if you don’t get these same results!) PEEK in other
locations, if you wish.
To illustrate that you can PEEK into locations that
Ok
have meaning to your BASIC program, we must first
PPEEE (AX)
introduce the function oO
Ok
VARPTR(variable)

If variable is the name of a variable in a BASIC


? PEER (A%4+1)
program, which has been assigned a value, then 1
VARPTR (variable) will return the address in memory Qk
where the value assigned to variable is stored. This
address is relative to the original value of the DS regis-
ter. Once you know the address where a variable is in memory is obtained by VARPTR(B%) and stored
stored, you can determine its present value using as A%; the value of A% was next printed out (as
PEEK. 3655 here, but may be something else on your system);
Start by entering the PEEK(A%) statement printed out the contents
of memory location 3655 (A%), which is found to
DEF SEG hold the value 25 which had been assigned to B%.
The DEF SEG statement (without an = value at the Conceptually, you have looked at the contents of a
end) signals the BASIC interpreter to place into DS location whose address = 3655 and found its contents
the value that was originally there. (DS will now point to be 25.
to the user workspace area, which is the same reference Now enter the following
point used by VARPTR, and is the area in memory B% = 255
where your BASIC program is stored.) Now enter
?PEEK(A%)
B% = 25
and you will find that location A% holds 255—as
A% = VARPTR(B%) expected. Next enter
2A%
B% = 256
?PEEK(A%)
?PEEK(A%)
2?B%
as shown in Figure 14.4b, and you will find that the
as shown in Figure 14.4a.
location where you expected to find 256 instead has
The sequence of events here can be described as
zero! Continue by entering
follows: First, B% (an integer) is assigned the decimal
value 25; next the relative address where B% is located ?PEEK(A%+1)

137
Memory Figure 14.7 Returning the whole integer value via
locations —> A%+1 = 3656 A% = 3655 2PEEK(Addr)+256* PEEK(Addr-+1).
8 bits =— B% is stored in Ok
two bytes OPEEK (AZ) + 2S6*PEEK (AZ+1)
High byte Low byte 257
Ok
00000000 00011001 B% =25

00000000 114111111 B% = 255


?PEEK(A%) + 256*PEEK(A%+1)
00000001 00000000 B% = 256
as shown in Figure 14.7.
00000001 00000001 B% = 257

Figure 14.5 BASIC uses two bytes to store integers.


POKE
which will return the contents of the location immedi-
ately following the one where we thought we should Whereas PEEK allows you to read the data value in
find 256. Here you will find a 1 (see Figure 14.4b). a particular memory location the statement
To explain what occurred here we need to note POKE Addr, Data
that in IBM PC BASIC two contiguous bytes are used
to store each integer. If we place these bytes side-by- allows you to store the value Data in the memory
side as shown in Figure 14.5, we see that when B% location whose address is Addr plus the location
is assigned values of either 25 or 255 (or in general pointed to by DS. (Addr is again relative to DS.) For
any value in the range 0-255), the low byte holds the example, type
value and the high byte is zero. If the value is greater DEF SEG = 0
than 255 then some of the number is stored in
A% = PEEK (2800)
the high byte and some in the low byte. For instance
B% = 257 will place the binary value 00000001 in POKE 2800,75
location A% and also in A%-+1. This is because ?PEEK(2800)
POKE 2800,A%
0000000 100000001 2 = 25710
ee ee

ea as as shown in Figure 14.8. The first statement saves the


high byte _low byte original contents of memory location 2800 as A%.
The POKE 2800,75 places the value 75 into memory
To check this enter
location 2800 and the 7PEEK(2800) verifies that the
B% = 257 75 was actually stored there. The last statement re-
?7PEEK(A%) stores the original value back into memory location
?PEEK(A%+1) 2800. Extreme caution must be taken in POKEing
values into memory. If you should POKE a value into
as shown in Figure 14.6. an operating system memory location, unpredictable
results might occur!
Figure 14.6 The decimal integer 257 is stored with 1’s in The IBM PC has 16K bytes of special memory loca-
both the high and the low byte of its storage locations.
tions called the display buffer. Two thousand of these
Ok
memory locations contain special codes corresponding
BY = 257
Ok to the 1000 characters (40 X< 25) that are currently
_ PREER (AX) being displayed on the TV screen in the text mode.
1
Ok
PEEK (A%+1) Figure 14.8 POKEing values into memory.
1 Ok
Ok DEF SEG = ©
Ok
AZ = PEEK (2800)
If you want to get the true decimal value of a number Ok
stored as an integer, you must use the following method FORE 2800,75
Ok
?PEEK(Addr) + 256*PEEK(Addr+ 1) “PEER (2800)
aes
where Addr is the address of the low byte where the Ok
integer is stored. (VARPTR always returns the low PORE 2800,A%
byte address.) To verify this enter Ok

138
(Blanks have their own special code.) To PEEK and Figure 14.9 POKEing the character code for an ‘’A’”’ (a)
POKE values into this area of memory you must first and a “‘C’”’ (b) into the display buffer.
assign the value 47104 to the Data Segment Register. Ak

This value will set DS to the memory location whose DEF SEG = 47104
Ok
contents are being displayed in the upper left hand POKE 0,65
corner of the screen. If you now POKE a value into Ok
relative memory location zero, the character corre-
sponding to this code will be displayed in the upper Ck
left hand corner of the screen. To verify this, enter DEF SEG = 47104
Ok
the following in the direct mode
FOKE 0,65
CLS Qk
PORE 0,67
DEF SEG = 47104 Ok
POKE 0,65
The character codes for other characters displayed
as shown in Figure 14.9a. After doing this, you will
on the screen are located in display buffer locations
find a capital “A” in the upper left hand corner of
0,2,4....,1998 as shown in Figure 14.10. In general
the screen (where the “O” in Ok used to be). The
the memory location for the character code being dis-
reason an “A” was placed there is because 65 is the
played at a given location on the screen can be deter-
character code for an A. The code for the character
mined by the equation
B is 66, the code for C is 67, and so forth. To check
the C, enter (row*40-+col)*2.
POKE 0,67 For instance, the center of the screen is at row=12
and col=19, or memory location
and check the upper left hand corner of the screen.
You should find a C as shown in Figure 14.9b. (12*40+19)*2 = 998

Figure 14.10 Display buffer locations and their associated screen positions.
Buffer Memory Buffer Memory
location 0 location 78

_fuerananey
5 20 30 39
0 Se
EEeCSEES
|_|Z2En88 Seca aes COLE
mslabseetesclste oleate alate) sk CECE eee Cer (5*40+30)*2
a
SRGERREATS = 460

10

139
Thus, if you enter places the square root symbol in the middle of the
screen. Entering
CLS
POKE 998,66 POKE 1000,127

you will get a B displayed in the middle of the screen. will place the symbol for a little house right next to
Try it. the square root sign. Try it.
To cover the top half of the screen with all A’s,
you need to place the character code for an A in mem-
ory locations 0,2,4..., up to (12*40+39)*2 = 1038. CHARACTER ATTRIBUTE CODES
To do this enter
Character codes for characters being displayed on the
CLS screen are located in the screen display buffer with
and then, using the | key, move the cursor into the offsets of 0,2,..,1998 (even numbers). The contents
bottom half of the screen. Now enter of the odd numbered memory locations in this area
(1,3,5. .. ,1999) are the attribute codes for each charac-
FOR K% = 0 TO 1038 STEP 2: POKE K%,65: ter. In particular, the memory location for the attribute
NEXT code, for any character being displayed, is the memory
You should end with the results shown in Figure 14.11. location immediately following the location where the
character code is stored. For example, if a character
PEEK/POKE Character Codes code is stored in location N (N must be an even num-
ber) then the attribute code for that character is stored
If you know the row and col coordinates where you at N+1 (an odd number).
want to print a character, or symbol, you can calculate The attribute code determines the following display
the address using the formula given above, and then properties of the character associated with it: blinking
POKE the character code at this address. The IBM or nonblinking; high or low intensity; and foreground
PC has 256 character codes with numerical values 0- and background color. (Again, this is done on a charac-
255. The codes for all the characters that can be dis- ter-by-character basis.) Before we discuss attribute
played are given Appendix B. codes in general, enter the following:
To test a few of these, assume you want to place CLS
a square root sign in the middle of the screen. From
POKE 998,65
above, the memory location for the center of the screen
is 998, and from Appendix B the character code is POKE 999,15
found to be 251. Entering You will find that the first POKE puts an A in the
CLS center of the screen in the normal manner. The second
POKE, which affects the attributes of the A displayed,
POKE 998,251
makes the A have higher intensity. Entering

Figure 14.11 Placing A’s over half the screen. POKE 999,143
AAAAAAAAAAAAAAAAAAAAAARAAAAAAAAARAAAAAABA
will make the A be blinking (still with high intensity)
AAAAAAARAAAAAARAARAAAAARAARAARAAAARAAAARAA
AAARAAAAAARAAAAAAAAAAAAAAAAAARAAARAAAAAARAAARA while entering
AAAAAAAAAAAAAAAAAAAAAAAARAARAARAAAAAAAABA
AAR AARAAAARAAAABRAAAAAAABAARAAAAARAAAAAAAAA POKE 999,112
AAARAAAAAAAAAAAAAAAAAAAAAAARARAARAAAAAAA
A AAA BRARAAAAAAAAABRAAAAAARAAAARAAAAAARAAARA
will make the A be displayed in reverse video. These
AAARAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAA series of steps are shown in Figure 14.12.* Note that
AA AAR AAAAARAAAAARAAARAAAAAAAAAAAAAAAAAAAAAA memory location 998=N contains the character code,
RARAAAAAARAAARAAARAAAARAAAAAAAAAARAAAAAAAABA while location 999=N+1 contains the attribute code
AAARAAARAAABAAAAARAAAAAAAAAAARAAARAARAARAAAA
for that character. (No other characters on the screen
AAAARAAAAAAAAARAARAAABRARAAAAAAAAAARAAAARAA
AA ARAAAAAAAAAAARAARAAAARAAAAARAAAAAABAAARAAA blinked, or went to high intensity, when we POKE’d
into location 999.)
The general form of the attribute code byte is shown
in Table 14.1.

FOR RA=0 TQ 1OS8 STEP 2S FORE 24,608" NEXT * Remember these POKE’s will go into the display area only if
you have previously entered DEF SEG=47104, Every time you
Qk “boot” the system the DS register value gets changed.

140
Figure 14.12 Displaying the character A in: (a) normal TABLE 14.1 The Attribute Byte Code
intensity; (b) high intensity; (c) reverse video.
7 Oey 4a es Bit number

Bits RaleGasl Beat Bit symbol

Bit values of O or 1
i
SS -——"

|____» Foreground Color


Bits
Intensity Bit
0 = normal
1 = high
Background Color
Bits
Blinking Bit
0 = not blinking
1 = blinking

Color Codes for Bits 6,5,4 & 2,1,0

Roe Glebe | Color


= —
Ot Ones Ome Black An additional 8 shades of
0 O 1| Blue color can be obtained by
0 1 =O} Green setting the I-bit to 1.
OF een eGyan
1 O O| Red
1 O 1 | Magenta
1 1 O | Yellow
1 1 1 | White

To illustrate the use of the attribute byte codes we


will discuss several examples in detail. The first exam-
ple will work with the character position in the middle
of the screen. This is character code byte position 998
and attribute code byte position 999.
To begin with you should make certain that the
system is set to the correct operating mode. Enter
DEF SEG = 47104
SCREEN 0,1
COLOR 7,0
These statements set DS to point to the display buffer;
enable color in text mode; and set the foreground to
white and the background to black.
Assume you now wish to place the character X
in the center of the screen with the following attributes:
1. Non-blinking
2. Background color = Blue
3. Normal intensity
4. Foreground color = Black
To place the X in the center of the screen you must
look up the character code for an X in Appendix B.
You will find this is an 88. Therefore enter
POKE 998,88

141
and the X should appear in the center of the screen The only change that is required in the attri-
as a white letter on a black background. bute code to make the X be blinking, while leaving
To give the X the desired attribute code you must all other aspects the same, is to make the BI bit a
check how each bit in the attribute byte should be 1. This means the attribute code byte should be
set, and from these bits determine the decimal value 100100002 = 14410 (128+16). If you enter
the byte should have. This byte can then be POKE’d POKE 999,144
at location 999. Looking at Table 14.1 you can deduce
that to get the desired attributes: you will find the X blinks. If you would rather
have a white X, the foreground RGB bits must
Bl = 0 (Not blinking) makes the attribute code byte be
be set to 111. This
Background RGB bits = 0 0 1 (Blue) 10010111. = 1519 (128: + 16 + 4 + 2 + 1). Entering
I = 0 (Normal intensity)
POKE 999,151
Foreground RGB bits = 0 0 0 (Black)
will change the color of the X to white, and still have
These define the eight bits of the attribute code byte it blinking on a blue background.
for the X. Moving from left-to-right As a final example, assume you wish to place a
high intensity B in the upper right hand corner of
the screen in yellow on a green background. You must
sifejc|e|i|e|c]s first calculate the memory locations related to this
screen position. This is display buffer row 0, col 39,
ojololijolololo
SO
character code location = (0*39+39)*2 = 78
attribute code location = 78+1 = 79
25Lor 7.9
Ok The character code for B = 66, which means a
POKE 998,88
Ok
POKE 999,16 CLS
Ok
POKE 78,66
will place a B in the upper right hand corner of the
screen. The attribute code bits must be:
Bl =0 (not blinking)
Background RGB bits = 010 (green)
I=1 (high intensity)
Foreground RGB bits = 110 (yellow)

The attribute code byte thus is 00101110. or 464


(32 + 8 + 4-4 2). Entering
Figure 14.13 Testing an attribute byte code.
POKE 79,46
The eight bits 00010000 represent a binary number
(base 2) whose decimal equivalent (base 10) can be will give B the desired attributes. This sequence of
determined from the positions of the 1’s in the binary entries is shown in Figure 14.14.
number as follows:
Figure 14.14 Placing a high intensity yellow B on a green
background in the upper right hand corner of the screen.
Qk R
FORE 78,66
Qk
PORE 79,46
Thus, the attribute byte 000100002 is equivalent to
Ok
the decimal number 16,0. If you enter
POKE 999,16
EXERCISE 14.1
the background color around the X will turn to blue Place a white lower case “a” on a red background
and the foreground will be black. (You will get a black in the lower left hand corner of the screen. (row =
X on a blue background. See Figure 14.13.) 24, column = 0.)

142
How to POKE a Picture Figure 14.16 Subroutine that POKEs a WxH picture at
location X,Y.
In order to POKE a picture on the screen you simply Ob:
LIST os
must POKE each graphic symbol into the appropriate HOO
display buffer location and POKE the attribute code 4001 "“POKE A H X W FICTURE
desired for each symbol into the following location. 4002 "“PC(I,J) WITH ATTRIBUTES
Suppose that you want to draw a rectangular picture 4005 "“PACI,I) AT X,Y
4004 *
that is H rows high and W columns wide as shown 40035 DEF SEG = 47104!
in Figure 14.15. The PEEK/POKE character codes 4010 FOR IT = 0 TO H-1
for each element in the picture are stored in a two- 4018 FOR J = © TQ W-1
dimensional array PC(I,J) where I has values between 4020 PORE ¢€(Y+1I) *404+X+J) *2,PC(1,J)
4025 NEXT J: NEXT I
0 and H-1 and J has values between 0 and W—1. The 4030 7
PEEK/POKE attribute codes are stored in a similar 4025 FOR I = 0 TO H-1
array PA(I,J). 4040 FOR J = 0 TO W-1
4045) FORE (¢(Y+I) X¥404+X+J) x2+1,PACI,7)
x Base Address BA=(Y*40+X)*2 4050 NEXT J: NEXT I
4055 DEF SEG
J=0 J=W-1
Pe sen Oe eS Le 4060 RETURN
Y —> |=0 —— Ok

(K|/alal|alalalala
A eee ee

ro Yl yy vy hs
co)

PSS
[eee ae
—— W columns ——
alee E7773
eae:ZAG |
Screen Address SA=((Y+1)*40+X+J)*2

Figure 14.15 The array PC(I,J) contains the PEEK/POKE


character codes for a picture of width W and height H.
The array PA(I,J) contains the corresponding attribute codes.

The upper left hand corner of the picture is to be


located at position X,Y on the screen. Therefore, the
base address, BA, where the character code for this
symbol will be placed (relative to DS) is
BA=(Y*40+X)*2 Figure 14.17 Sketch of KING playing card to be
The screen address, SA, for any character code in the POKEd on the screen.
picture, including the one in the upper left hand corner,
can be calculated by using the formula Each row in Figure 14.18a can then be stored in
a DATA statement and read into the array PC(I,J)
SA=((Y+D*40+X+))*2 and each row in Figure 14.18b can be stored in other
as shown in Figure 14.15. The location for the attribute DATA statements and read into the array PA(I,J),
code for any character stored at SA is merely SA+1. as shown in lines 30-120 of the program in Figure
Drawing the picture then involves POKEing all values 14.19. The DATA statements to be used with this
of PC(I,J) and PA(I,J) into the appropriate screen ad- program are given in Figure 14.22a. Line 135 draws
dresses. A subroutine to do this is shown in Figure this picture at location X=10, Y=5 by calling the sub-
14.16. Note that the picture can be moved anywhere routine shown in Figure 14.16. The result of running
on the screen by changing the values of X and Y. this program is shown in Figure 14.20.
As an example of using this subroutine let’s POKE Multiple pictures can be stored in a three-dimen-
the KING playing card shown in Figure 14.17. The sional array with one picture being stored in each
first step is to look up the PEEK/POKE character “plane” of the array as shown in Figure 14.21. The
codes and attribute codes for each element in the pic- corresponding attribute codes for each picture can be
ture from Appendix B and Table 14.1. Enter these stored in a second three-dimensional array. The POKE
codes into matrices in the shape of the picture as shown codes used to draw a KING, QUEEN, and JACK
in Figure 14.18. are shown in Figure 14.22.

143
Figure 14.18 The POKE codes for the KING: (a) Character
code (b) Attribute code.

(a) 75,32,;32,32;32:32,32,32
4222.15 :155153155221 532
S22;
22 SejS2592,52,52
327222,32,52,32;32,;92,52
32532532532; 32,025;92;02
$2332,32,32,32,32,32,52
32732332,32,32,32,221,32
32}32;32;32,52,22 1,392,952
32,222,15,15,15,15,221,4
SZ;92;52,02;52,52;
02,19

ID) 32232 32732,32,52,92,52


32,6,96,96,96,96,6,32 Figure 14.20 Result of running the program in Figure 14.19.
32,757,16,16,16,7,32
32,4,64,64,64,64,64,32
32,64,64,64,64,7,64,32
32,64,7,64,64,64,64,32
32,64,64,64,64,64,4,32
32,7,16,16,16,7,7,32
32,6,96,96,96,96,6,32
32532752,32,32;32,32,32

Figure 14.19 Main program to POKE a


KING.
Ok
LIST ~-140
1 "PORE A KING
J
S SIERSISN, Gin ale (oaleley 7/e teins tellers
10 DEFINT P,1,d,X,Y¥sHsW Figure 14.21 The three-dimensional array PC(I,J,K) can
15 H = 10: W= 8 store a different picture for each value of K. PA(I,J,K) would
20 DIM FPACH-1,W-1) ,POCH-1,W-1) store the corresponding attribute codes.
=O FOR I = 0 TO 9
40 FOR J = 0 TO 7
30 READ FCC(I,J)
60 NEXT J DATA!” because it takes a few seconds to read all of
FO NEXT 1 the DATA statements before any picture is displayed.
BOmRGR ete Opie? The result of running the program in Figure 14.24.
90 FOR Jd = 0 TO 7
100 READ FACI,J)
is shown in Figure 14.25.
110 NEXT J
120 NEXT I EXERCISE 14.2
120 X=10:Y=5 Write a program that will POKE a picture of a house
125 GOSUB 4000
140 END
on the screen.
Ok

THE IBM PC’s MEMORY MAP


The subroutine shown in Figure 14.16 must be mod-
ified to POKE the values in PC(I,J,K) and PA(I,J,K) The 8088 microprocessor used in the IBM PC can
as shown in Figure 14.23. The main program shown address a maximum of 1,048,576 bytes of memory.
in Figure 14.24 reads all of the data in Figure 14.22 This number is equal to 1,024K where 1K=1,024. This
and then draws the JACK (K=2) in line 130, the memory space is divided among read-write memory
QUEEN (K=1) in line 135 and the KING (K=0) in (RAM), I/O or Input/Output memory, and read-only
line 140. Line 22 prints the message “I7M READING memory (ROM). Figure 14.26 shows how this memory

144
Figure 14.22 (a) POKE codes for the KING stored 699 *JACE CHARACTER CODES (c)
in PC(1,J,0) and PA(I,J,0); (b) POKE codes for the FOO, DATA: 74, 32, 32s S2e S252, 22152
QUEEN stored in PC(I,J,1) and PA(I,J,1); (c) POKE 710 DATA 4, 32,32, 233, 253, 255, 225, 52
codes for the JACK stored in PC(I,J,2) and PA(|,J,2). 720 DATA S25 32s See Sey S24 52, cerae
(@)399 *KING CHARACTER CODES 730 DATA 32,32, 221,32, 32,221, 32,32
200 DATA
eeby
Pagers oey Nes cag oes Seg
tan) FAQ MDATA Sle Soy eee vse, 82,221. B2a82
310 DATA A. ee
222 et ae ey eel Se TBO DATAMSEL So Aer RO, Spool oe, Se
320 DATA Zo
Seg
39
Sq
99
FENEa) PERE
749
acted cs
She
TIO
eh Eye
760 DATA 32,32, 222, 32, 32, 222, 52,52
330 DATA
spar
Sg
la eedrier
a
ah
Sg Sea
EN
eee
SReR
alg
OSD
as
rey,
pee
TIO! ORT S2) 32, 32,52: 82) 22, 52,32
340 DATA S252, sa S2y5e
tig Sea 52, S252
Sara Sa
780 DATA 32,235, i dey
250 DATA re
eg
SRR
a
Satie
Sal
a ae ecb ae Sal
Say Vag
dereWanedae
Sa
Iaye)ee 790 DATA 32, 32,22, 52, 32, 32,52,74
360 DATA
raat
aly
onsen
ey
oat
mal Ve See
San)
O2s FEN RS
De
799 *JACK ATTRIBUTE CODES
270 DATA Low Whoor-tued
Siig agate a
2
eR
FO"
aE eR
cy es G00 DATA 32,32, 32,32, 32, 32,3255
280 DATA SS Pes aye a Beg
ra een 810 DATA 32,112,7,16,16,16, 16,32 53rh

390 DATA
a
32,52, 32,32, 32, 52, 52,75 820 DATA 32,112, 64,64, 64,64,7.
399 “KING ATTRIBUTE CODES ASQ DATA 32,112,965 9h, 945 Oy oe
400 DATA EC SYS BS Oe
Wo
aie SEY
TQ OTT
akg
TN
ae
G40 DATA S22112,6.75 945657552
410 DATA BP Oy Pn POe Phy Pig Oy BE B50 DATA 3247565 POs 7005 112, 52
420 DATA SE. 7 Pps iG, 14, 7.52 Q60 DATA 32; 7.6, 96,96, 976;112, 52
430 DATA 32, 4,64, 64,64, 64,64, 32 970 DATA 32,7,64,64,64,64,112, 32
440 DATA 32,64, 64,64,64,7,64, 352 G80 DATA 32,16,16,16,16,7,112,22
450 DATA 32, 64,7, 64, 64, 64,64, 32 890 DATA 32,52, 32,52, 32, 32,232,352
469 DATA 32,64, 64,64, 64, 64, 4,32 Ok
470 DATA 3707016, 16016, 7.7552
480 DATA 3216, 965 9b 965 96,65 52
490 DATA te
oa
ee
| Sean
alg
= =
og 2:
San
Sal
ator
eg
oe) Figure 14.23 Subroutine to POKE picture K in the arrays
Qk PC(1,J,K) and PA(I,J,K).
Ok
LIST 4000-4060
(b) 499 "QUEEN CHARACTER CODES 4000 *
3 TOOTS OF ae cele, Gee
300 DATA 81, 32, 32, 33, 32452, 52,52 4001 *PORKE A&A H X W PICTURE
S10 DATA 4,194, 194,194,194,194, 22,52 4002 *PC(I,J,E) WITH ATTRIBUTES
520 DATA 32,194, 32, 32, 52, 32,52, 32 400% *PACI,J,E) AT X.Y
S30 DATA 32,194, 52,248, 32, 52,52, 52 4004
=40 DATA 32,194, 248, 32, 248, 32,32, 32 4005 DEF SEG = 47104!
550 DATA 32_ 32, 52, 248, 32,248,193, 32 4010 FOR I = © TO H-1
560 DATA 32 Se,32, 248,352,195
a = 29 ~O7 = 7 4015 FOR J = 06 TQ W-1
2370 DATA SS Des, ao, Ne ee 193, eal ie
4020 PORE (¢(CY¥+I) ¥404+X+J)*2,PC(I,d,E)
=80 DATA Be eee ee ate nt on 4025 NEXT J: NEXT I
590 DATA ton Yio ee ac
Sl ag a
te Wiae
a
er
ag eteaie
,B1
4020
399 “QUEEN ATTRIBUTE CODES 4025 FOR I = 0 TO H-1
TO 7 Ta erie eae wo) FO
6400 DATA Bog Soy Sey ey ey eg ey Oe
4040 FOR J = © TO W-1
610 DATA 32,64, 64,64,64, 64,7, 32
4045 PORE (¢(Y+I) *404X+J) #24+1,PACI,0,F)
420 DATA 32,64, 96,96, 96, 16,7, 32 4050 NEXT J:NEXT I
620 DATA 32 O42 7112-16, 16,7, 52
4055 DEF SEG
640 DATA 32,44. Hie ioei eaTyee 4060 RETURN
6350 DATA Bead @ N12,Jie GA, oe Qk
660 DATA 32,7, 16,16,112,7,64, 32
4670 DATA B2575 1h PO5 95 964 64,52
680 DATA B2471 645 645 64,64, 64, 32
= = = 2H = >
690 DATA alg tag 32,3 og S02, 32, Ss 5

Qk
Memory in the Range 0-64K

When someone says they have an IBM PC with 64K


is allocated for an IBM PC with 64K bytes of RAM
of RAM, they are speaking of the amount of RAM
and a color/graphics monitor. Notice from the left-
that is located in the low end of memory. In Figure
hand side of the figure that locations 0-64K (65,535)
14.26 this is the RAM with addresses running from
are the 64K bytes of RAM, locations 736K-—752K are
0 to 64K. As can be seen from Figure 14.26 this RAM
16K bytes of RAM associated with the color/graphics
holds many items in addition to your BASIC program.
monitor, and locations 976K—1024K are 48K bytes
The items in this area of memory will be discussed
of ROM. Regions shown as being blank are areas that
briefly, in order, going from address zero to address
are empty and could be used for further memory
65535.
expansion. (One exception to this is the address
range from 704K to 720K. This is the area reserved System Area: This is an area used by the operating
for the display buffer associated with a monochrome system to store special addresses it needs for its
monitor.) operation.

145
Memory Memory Contents Size in
Figure 14.24 Main program that displays a JACK, Address Bytes
QUEEN, and KING.
000 np
1 *FOKE A JACK,QUEEN & EING ie System Area 96
SCREEN tee COLOR 7 7O Gls
POR DE UNS Pi en loaihea Xaey atta DOS e eK
15 H = 10: W = 8
ZO DIM PASH WW de). MEH =i, Wo. 2) sepeistee 4096
22 PRINT "I*M READING DATA! "s; - --
Aaay (ORY Ipeeet 40) p(B) 8K 13K
BASIC for for
SO) (Eley, 1s So Oe TBE 7 Extensions Disk Advanced
40 FOR J = 0 TO 7 BASIC BASIC
BOmOREAD SEC D oe Data Segment ale
Register points Interpreter Work Area 4K Baty
60 NEXT J
CAS INS at here BASIC
Program
SORPER t=) Orang ~40K ~35K
Scalar Variables for for
970 FOR J = oO TO 7
Disk Advanced
1900 READ FPACI,d7,#) Mee BASIC BASIC
110 NEXT J String Variables
Teen NE xin me
BASIC Stack 512
eta (Sp oh 64K + =
120 X=S:Y=S:k=2:GOSUB 4000
13S X=17:Y=S:k=1:GOSUBR 4000
736K 4 pate
140 X=29:Y=SsE=0:GOSUR 4000
Color/Graphics
150 END Display Buffer | Tens RAM
Ok 752K a

zt 4
976K 4 ae
}
M READING DATA?
System ROM | 48K ROM
Ok
1024K

Figure 14.26 Memory Map of an IBM PC with 64K of


RAM, a color/graphics monitor and DOS.

Interpreter Work Area: Another “scratch pad.”


BASIC Program, Scalar Variables, Arrays and String
Variables: This area of memory holds your BASIC
program and all the variables associated with it.
Note that all BASIC variables of one type (scalar,
string, array) are stored in the same general area.
BASIC Stack: This stack is used by the operating
system in transferring control to and from subrou-
Figure 14.25 Result of running the program in Figure 14.24. tines. The stack begins at memory location 65535
and is built downward in memory as the stack grows
in size.
DOS: This is the software read into memory from
your DOS diskette that has the programs required The actual memory locations where your current BA-
to use the disk operating system. It is this set of SIC program resides can be obtained from the program
programs that gives the A> prompt when you first itself. The starting address is stored in locations 48
turn on the IBM PC. (low byte) and 49 (high byte), and the ending address
DOS Work Area: This is a “scratch pad” area re- is at 856 (low byte) and 857 (high byte). The starting
served for DOS’s variables. and ending addresses are placed in these locations by
the operating system and are continually updated as
BASIC Extensions: This area holds the software
you change the size of your program. The actual start-
needed to execute those BASIC statements that are
ing address can be obtained as
available only in Disk, or Advanced, BASIC. This
software is read into these locations from the DOS PEEK(48)+-256* PEEK(49)
diskette when you type in either BASIC, or BA-
and the ending address as
SICA, in response to A> when the IBM PC is
“booted.” PEEK(856)+256* PEEK(857)

146
Address (Relative to DS) amount of memory required by the new program. (See
Memory Figure 14.28b.) You will find that it took two more
bytes for the second version. This is because each char-
PEEK(48)+256*PEEK(49)—__| Storage acter in a program takes one byte to store (even blanks,
Space for
which are characters). Thus, if you are using a system
your
BASIC that is short on memory, you can save some memory
by not using extra blanks in program statements.
Program
PEEK(856)+256* PEEK(857) ——_—__~
Figure 14.27 BASIC program storage locations relative to
Ds. USING PAGES
IN THE GRAPHICS DISPLAY BUFFER

As always, these addresses are relative to the DS regis- The graphics display buffer contains 16K bytes of
ter. See Figure 14.27 for an illustration. RAM. In the text mode it takes only 2K bytes of
To illustrate this fact enter this area to hold all the information necessary to dis-
NEW play one screen image. There is thus enough memory
in the display buffer to hold eight full screens of data
to clear out all old programs and then enter and run at one time. The display buffer memory is considered
the program to be made up of eight 2K blocks, each called a page,
5 DEFINT A,B as shown in Figure 14.29.
10 A = PEEK(48)+256* PEEK(49) By default we have been using only page 0 of the
display area in our text mode programs. It is possible
15 B = PEEK(856)+256* PEEK(857)
to write data in other pages in the display buffer, and
20 PRINT A,B,B—A+1 then switch the display from page to page. In this man-
as shown in Figure 14.28a. This is a program that ner you can quickly switch the information being dis-
prints out the starting point where it is stored in mem- played. In fact, it is possible to be writing on one page
ory; its ending point; and its size (in bytes). In this while at the same time displaying the information con-
example the program was stored from location 3649 tained on another page. To illustrate how you can
to location 3733 for a size of 85 bytes. write on, and display, several pages, we will alter the
To check the effect that adding characters to a BA-
SIC program statement has on its storage size, EDIT Figure 14.29 There are eight pages of screen data in the
line 10 by placing an extra blank both before and after graphics display buffer in text mode.
the + sign. Now rerun the program and check the DS Reg Value Actual Memory

Figure 14.28 Checking the location and size of a BASIC Base = 47104 =— 736K (753664)
program.
(a Ok Base
+ 128 ————
LSLSir
3 -DERINT AaB
19 A = PEEE (48) +256x%xFPEER (49) Base + 256 —__~
15 HB = PEER (8S46) +25 6xPEER (857)
2O FRINT A,B, B-At1
Ok
Base
+ 3*128 ——~
FUN
2649 37 oo 85
Ok

Ok
jSsoeap hie)
10 A = PEEE(48) + 256xPEEK (49)
er Si
a) JOSIP Ayets!
10 QA = PEEK (48) + 2S56*xFPEEK (49)
15 B = PEER (8546) +2a6*FEER (857)
20 PRINT A,B, B-At1
Ok
Base + 7*128 ——~
RUN
2649 Beene 87
Ok

147
program that displays the Jack, Queen and King so Figure 14.30 Program to POKE and display in pages 1,
that each card is stored on a different page. You can 2, and 3: (a) Mainline;
(b) Subroutine.
CLS (a)
then instantaneously (almost) jump from card to card = SCREEN Onno: mem Oh acn.
10 DEFINT P,1I,0,KyX.Y¥:HsW
by displaying different pages from the display buffer. 1S Ho=- Os UW =
There are two ways you can write to a given page. 20 DIM PA(H—1,W-1,2),PC(H-1,W-1,2
One is to POKE data after moving the DS register 2? FRINT "I°M READING DATA!"|
to point to that page. The other is through a variation ee, FOR EF tO seta (ilies
m0 FOR I Oe icles:
of the SCREEN statement. 40 FOR J a URE #4
The full form of the SCREEN statement is 0) READ fet
mee
tT PC(I,d,K)
60 NEXT J
SCREEN mode, burst, apage, vpage 70) NEXT I
ao POR o Ta 9
You are already familiar with the parameters mode 90 FOR J iil =o 707
and burst. apage and vpage (in the text mode) can 1oO0 READ PA(I,J,K)
have integer values from 0 to 7. apage picks the page 110 NEXT J
in the display area in which you wish to read or write 120 NEXT I
(using INPUT or PRINT statements). vpage picks the
NEXT
127 A 47104'!+128
page in the display area which you wish to have dis- 15% rY=S:K=2:GQSUB 4000
played on the screen. For instance, the SCREEN ,,1,2 122 A
i :
statement indicates that you wish to be writing into 135 xX
127 A
page 1 and displaying page 2. (A note of caution: If
140 rY=5:K=0:GQSUB 4000
you are not displaying the page you are trying to IN- 145 LOCATE 1,1
PUT data to, the computer will appear to be dead!) 147 INFUT "WHICH FAGE? (Oc 142,
0) DSP
To illustrate the use of both POKE and SCREEN 148 SCREEN ..P,F
statements with pages in the display buffer, the main 149 IF P <> O THEN 145
150 END
program Figure 14.24 and the subroutine from Figure
14.23 have been altered in the following manner. (See
4000 *
(b)
Figure 14.30.)
4001 "*“POKE A H X W PICTURE
In the subroutine statement 4005 has been changed 4002 *PC(I,J,k) WITH ATTRIBUTES
to 4003 "“PACI.J,E) AT X,Y
4004 *
4005 DEF SEG =A 4005 DEF SEG = A
4010 FOR I O TO HSt
so that the address in DS can be changed from call 4015 FOR J Oo TO W-1
to call by changing A. In the mainline statements 127, 4020 PORE (¢(Y¥Y+I) *40+X+I) *2,PC(1,0,-)
132 and 137 have been added. Statement 127 sets A 4025 NEXT Js NEXT I
to 47104+128, which is the value required in DS to 4030 *
4035 FOR I (Oe Tie) deka
make it point to page 1 in the graphics display buffer 4040 FOR J o TO W-1
(see Figure 14.29). Statements 132 and 137 change 4045 FORE (¢(Y¥+1) K404+X47) kK2+1, PACT, J.E)
A to make DS point to page 2 and then page 3. When 4050 NEXT J:NEXT I
the call to the subroutine at 4000 is made in line 130 4055 DEF SEG
49060 RETURN
the Jack will be placed in page 1. (You won’t see this
happen because page 0 is being displayed.) Likewise,
the calls at 135 and 140 will place the Queen on page the apage and vpage values both at zero—which is
2 and the King on page 3, respectively. where you want to end.
Lines 145-149 have also been added. After the cards Figure 14.31 shows what should be on the screen
have been placed into the three different pages, lines after entering a 1,2 or 3.
145-146 will ask which page you wish to display. As-
sume you enter a 2. Line 148 then becomes equivalent
to ANIMATED GRAPHICS
SCREEN ,,2,2
Animated graphics can be generated on the IBM PC
which indicates to display page 2 (from the last param- by quickly replacing one figure with another figure
eter) and make all screen input and output also be that is offset from the first by a small amount. If this
on page 2 (from the first 2). This will display the Queen. procedure is repeated over and over, the figure appears
Line 149 allows you to continue as long as you don’t to move. In order for this process to be effective you
enter zero. Entering a zero will end the program with must have the capability to erase one figure quickly

148
Figure 14.31 Output of the program from Figure 14.30 -and replot it equally quickly. On the IBM PC this
after entering a 1(a), 2(b) or 3(c). can be done via GET and PUT statements.
(a) The GET statement allows you to store an image
that you have created on the screen in a two-dimen-
sional array. The PUT statement will then let you
WHICH PAGE? (@,1,2,3)? — erase and replot this image anywhere you want on
the screen. We will illustrate the use of GET and PUT
by making a sailboat sail across the screen.
Figure 14.32 defines a sailboat that we will initially
plot using the DRAW statement. The shape string
for this sailboat, starting at the base of the mast, is
given by

S$ = “U18NU2NR4F16L16BD2L8F4R6F2R4E2
NL8R6E2D4R2E2L4BU2E2L2U1NL4BD1L18”
The statement

DRAW “BM 50,50; XS$;”


will plot this sailboat with the base of the mast at
screen position (50,50).

WHICH PGGE? €@,1,2,397 .

ore

aA 5 is

Figure 14.32 Definition of a sailboat to be plotted using


the DRAW statement.

The GET statement can now be used to store this


sailboat image in a two-dimensional array V(I,J).
The statement

GET (X1,Y1) — (X2,Y2), V


WHICH PAGE? (@,1,2,30? —
will store the image within the rectangle of width (X2-
X1) and height (Y2—Y1) in the two-dimensional array
V(I,J). The coordinates (K1,Y1) and (X2,Y2) are the
screen coordinates of the upper-left and lower-right
corners of the rectangle respectively as shown in Figure
14.33.
The array V(I,J) must be dimensioned so that the
number of bytes contained in V(I,J) is at least
4+INT(((X2—X1)*B+7)/8)*(Y2—Y1)
where B = 2 in medium resolution graphics and 1
in high resolution. In the case of the sailboat the coordi-

149
Figure 14.34 Program to produce a moving sailboat.
TV Screen Qk
ES
io “DRAW A SAILBOAT
2 DE FAUN keane rans
1S SEREEN PGES
(X1, Y1) 20 DIM V(10,4)
ZO S$="U1SNU2NR4F16L16RD2LE2R4E2NLB F4RGF
R6E2D4R2E2L4BUSESL SUINL4RDIL18"
40 DRAW "BMSO, 50; XSS;"
50 GET(50-8,50-20) - (S0+235,50+6),V
60 FOR I=1 TO 800:NEXT I
CORES
80 Y=100: XS=250:
(X2, Y2) SS SeUMmGXSieylisa,
90 FOR X = XS TQ XP STEP =sS
100 PUT(X,.Y).V
10S FUTCX-—Sa¥o,V
110 FOR I = 1 TO 100:NEXT I
Figure 14.33 GET (X1,Y1)—(X2,Y2),V will store the image 140 NEXT X
within the shaded rectangle in the array V(I,J). eye) {e/LS'
160 GOTO 83
Ok
nates X1,X2,Y1,Y2 to be used are

XLT=50—8 =42
for X = XS to XF STEP —S
X2 =50 + 23 = 73 PUT (X,YS),V to erase the current picture;
Y1=50—20=30 PUT (X-—S,YS),V to place a new picture
Y2=50+ 6=56 S units to the left;
Delay for a short time;
The minimum number of bytes required to store the
next X
picture is (in medium resolution)
The size of S and the length of the delay will determine
4+INT(((73—42)*2+7)/8)*(56—30)
how fast the figure moves across the screen.
= 4+ INT((31*2+7)/8)*26
In the program in Figure 14.34, line 15 places the
= 4+8*26 = 212 bytes
screen in the medium resolution graphics mode. Line
In IBM PC BASIC an integer requires 2 bytes to store 20 dimensions V so that it is large enough to hold
and a single precision variable takes 4 bytes. Since the picture. Lines 30 and 40 define the sailboat and
V(I,J) is a single precision array, each element will draw it on the screen at location (50,50). The GET
have 4 bytes. Thus, V(I,J) must have 212/4 = 53 ele- statement in line 50 places the picture into array V
ments. V(10,4) will contain 55 elements and 220 bytes, and line 60 provides a short delay that will allow you
which is large enough to hold the screen data. to view the sailboat on the screen. Line 70 clears the
The program in Figure 14.34 will produce a sailboat screen again. The program is now at the point where
that sails across the screen from right to left. Before it can plot the sailboat anywhere on the screen with
discussing this program in detail the characteristics the PUT (X,Y),V statement.
of the PUT(X,Y),V statement will be discussed in Line 80 sets the starting coordinates as (250,100),
greater detail. First, remember that the array V holds the ending coordinates as (50,100) and the step size
all the information required to place a picture on the for movement as S=3. Line 85 puts the first picture
screen. When PUT (X,Y),V is executed, the picture on the screen. The FOR ... NEXT loop from lines
stored in V will be placed on the screen with its upper 90-140 continually erases the current figure and places
left-hand corner at screen location X,Y. However, if a new one on the screen at fixed intervals of time.
PUT (X,Y),V is executed a second time with the same Line 100 erases the last figure (since its coordinate
value of X,Y, the second execution will erase the pic- values are always the same as the last PUT) and line
ture. With this fact in mind the algorithm for making 105 plots a new figure. Line 110 is a short delay. Line
a picture “move” from right to left is: 150 clears the screen after the sailboat has sailed all
the way across the screen, and line 160 causes the
DRAW the picture at some location on the screen; boat to sail again. Type in this program and run it.
GET the picture into array V(I,J); A picture of the sailboat when it is half-way across
clear the screen; the screen is shown in Figure 14.35. Remember that
PUT the picture at its starting location (XS, YS); the DRAW statement is available only in Advanced

150
' Figure 14.36 Result of running the program with PSET.
Ok (a)
Lon
10 *DRAW A SAILBOAT
Mec DUEstoiel (MiNi eiUa 2s
to SCREEN 1sCLs
20 DIM V(10,4)
20 $$="U18NU2NR4F16L16BDSLEF4R4F 2R4E2NL8
R6ESD4RZSESL4ABUSESLAUINL4ARDIL18"

aN
40 DRAW "BMSO, SO; XSsq "
SHS Grails cere) CSO Hetil CIAO)aVi
60 FOR T=1 TO 800:NEXT I
70 CLS
80 Y=100: XS=250: XF=50: S=%
@5 PUT (XS, Y) «V. FSET
90 FOR X = XS TO XF STEF -§
100 FUT (X,Y) .V,FSET
108 PUT (X-S,Y) .V.PSET
WaMO) (SIGIR: al cae RINE CI
140 NEXT X
Figure 14.35 Result of running the program in Figure 14.34. 150 CLS
160 GOTO &s

BASIC. You will get the error message Advanced fea-


ture if you run this program in Disk BASIC.
To change the speed at which the sailboat moves
you can alter two items. First, you can make S larger,
or smaller. Second, you can change the length of the
delay inside of the FOR ... NEXT loop by changing
the value 100 (in line 110). Try first changing S and
then the delay time. Note how the amount of “‘flicker”’
and “‘jerkyness” are affected.
There are some other options that you can use with
the PUT statement. The general form of this statement
is
PUT (X,Y),V, action

where action can be

PSET
PRESET
XOR
OR duces an exact copy of the original picture. This means
that the PUT statement in line 100 does not erase
AND
the last sailboat. It merely puts a new copy over the
If action is not specified, the default value is XOR, old, which leaves it unchanged. (In fact you can delete
which is the case we have been using. PSET is a true line 100 from the program in Figure 14.36a and the
opposite of the GET statement. It will always place results will be the same. Try it.) When the PUT state-
an exact copy of the picture on the screen. PRESET ment in line 105 is executed, it places a new copy of
produces a negative image of the picture stored in the sailboat (including the blank background) three
VJ). units to the left of the sailboat that is currently being
To illustrate how these affect the animation process, displayed. This erases all of the last picture with the
let’s first look at the use of PSET. In lines 85,100 and exception of the three units on the right hand side
105 in Figure 14.34 append a ,PSET to the end of of the picture, which is a blank space plus the end
each PUT statement. This will give the program shown of the rudder. (You must take note of the fact that
in Figure 14.36a. Now run the program. The result X2 in the GET statement was 23 which means one
is shown in Figure 14.36b. blank space past the end of the rudder is plotted with
Note that the sailboat now leaves a wake behind each PUT.) Thus what appears to be the wake is really
it as it moves across the screen. Can you see why? part of the rudder left over from previous pictures.
Remember that the PUT statement with PSET pro- To prove this to yourself, change S to 8 in Figure

151
14.36a and rerun the program. You'll find that all of
the rudder now gets left behind with each additional
PUT.
Now change the word PSET to PRESET in Figure
14.36a and run the program. You will get the result
shown in Figure 14.37.
There are two other words that you can use at the
end of a PUT statement—AND and OR. If you use
AND then only points which are set in both the origi-
nal rectangle (now stored in the array V) and in the
destination rectangle on the screen will be set. The
use of OR at the end of a PUT statement allows you
to superimpose the image in V(I,J) on the image that
is presently on the screen.

EXERCISE 14.5
Write a program using GET and PUT that causes
Figure 14.37 Using PRESET in a PUT statement will reverse
an airplane to fly across the screen. all points stored in V.

EXERCISE 14.6 V(1,J) at different locations at the same time. Experi-


Write a program using GET and PUT to produce ment with different colors by using the COLOR state-
computer art. Try PUTing back the shape stored in ment.

152
LEARNING TO PUT ITALL TOGETHER

In the previous 14 chapters you have learned how to


HANGMAN
use the various features of IBM PC BASIC. You have
learned how to write short programs that draw pictures We will now develop a program to play the word-
and make sound. Now that you know the BASIC lan- guessing game HANGMAN. The following six steps
guage you will want to write your own programs. How will help you develop a program with the minimum
do you go from an idea of something you would like amount of grief. We will follow these six steps in devel-
the IBM PC to do to a working BASIC program that oping HANGMAN.
does it? That is what this chapter is all about.
In order to illustrate the various steps involved in STEP 1: Define what you want the program to do;
STEP 2: Give a word-description of the program;
developing a program we will write two complete pro-
STEP 3: Define program variable names;
grams in this chapter. Although both of the programs STEP 4: Write and test the main program and essential
are useful and fun to run, it is the process of developing subroutines;
the programs that we are trying to illustrate in this STEP 5: Write and test the remaining subroutines;
chapter. STEP 6: Test the entire program and make improvements.
The first program is a popular word-guessing game
called HANGMAN. The second is a program that
converts your IBM PC into an electronic organ. Defining What HANGMAN Will Do
In this chapter you will learn
1. how to define what you want to do and give a This is the most important step in developing a pro-
word-description of the program, gram, but it is a step that is often omitted or not
2. to define the variables you will need in the pro- © carried out adequately. There is an almost irresistible
gram, temptation to start writing BASIC code immediately.
You must resist this temptation at all costs. You should
3. the technique of top-down programming,
not write any BASIC code until STEP 4!
4. how to write a program to play HANGMAN, Poor programming, like poor writing, is usually a
5. how to store data sequentially on a floppy disk, sign of poor and confused thinking. If you don’t have
and a clear idea of what you want the program to do,
6. how to play music on your IBM PC. you will have little chance of writing a program to

153
do it. Now you may not know all of the features that an incorrect letter is guessed, then the phrase NO x
your program will eventually have. Indeed, program- (where x is your letter) will be printed along the left
ming is an iterative process in which you will improve side of the screen, and another part of the body will
a program by rewriting it several times. However, you be added.
must understand enough about what you want the If you guess the word correctly then the word will
program to do to get started. be flashed and the words YOU ARE SAVED! will
Hangman is a word-guessing game in which the be printed. If you fail to guess the word, then the
IBM PC thinks of a word and displays a blank for correct word will be displayed above the blanks, and
each letter in the word. You guess a letter. If the letter the words YOU ARE HANGED! will be printed. The
occurs in the word, it is inserted at all locations where words Play Again? enclosed in a box will then be dis-
it occurs in the word. If the letter does not occur in played at the left side of the screen.
the word, then another part of your body is added Having laid out what you want the screen to look
to the hanging gallows. You keep guessing letters until like and having thought about how the game is to
you either guess the word, or you guess six wrong be played you are ready to write a word-description
letters, at which time your body is complete and you of the program.
are hanged.
The first thing to decide is what you want the screen
to look like and how you want the screen to respond A Word-Description of HANGMAN
to various inputs and conditions. The best idea is to
sketch the screen to scale. Figure 15.1 shows the screen At this point you should write a word-description of
layout for the HANGMAN game where we will use the program that will completely describe its logic.
medium resolution graphics to display the gallows. We Use pseudocode, flowcharts or whatever you find use-
use medium resolution because we can both draw lines ful. A word-description for the HANGMAN program,
and rectangles easily in that mode, as well as use text. written in pseudocode, is shown in Figure 15.2. You
When the program is first executed the name should study this word-description carefully. Note that
HANGMAAN is written at the top left of the screen. it follows closely the screen layout we made in Figure
The program then displays the gallows in medium reso- 15.1 and our ideas on how the program should work.
lution graphics, the blanks for the word, and the words Developing the word-description shown in Figure 15.2
GUESS A LETTER. As each correct letter is guessed, is the most creative part of writing the program. At
it is filled in at the appropriate blank position(s). When this point most of the hard work is done! This is why

Figure 15.1 Screen layout for HANGMAN program.

100 LS 2001 | | | | tT ttt |300_[319tL Grid Unit

BSR
10 2098 40 Garter
rn BERS ae elo ol er
Vee[ex3esbshecs of TF:2RE ere i a ea
SER SRSA oO eaeSAee
BERBERS 22="==“CRR eC oR ae eeeasO
PEG ae Bale -— + ae Gia i
haha So-o -+ cee a
ra B Gil ESREBRESS
Z oa baale ae |
Bene ai we wee
Blll-<———_— Bae eee
po 1alcalico i Te ec La a ch
Bae Shee BAY eee
eT TePe a MT ER ks ae
| BERR Baer
es ad Baalelcellhe
ral Perea Gls halen ESR Tas

FEEEEEEE SEEEEEEEEEE EE
| Pt fades EP} ARR}

Do ARE aN rt tH

FEP E EESEEE
[Ul JA[RIE| [HJAIN|G/E[D]'T
|||
fe ale
|_| fe Kl (hi ak cs] he [
Rah essere eat {
be |at — pel a ee a r + —— 4 Biel fae | chee rae

154
Figure 15.2 Pseudocode word-description of HANGMAN ’ Figure 15.3 Definition of initial variables to be used in
program. HANGMAN program.
loop: Clear screen WS = word to be guessed
Display HANGMAN L=length of word to be guessed
G$ = letter guessed
Display gallows NL = number of correct letter positions guessed
Display the words GUESS A LETTER NH = number of incorrect guesses
x lfif G$ isinW$
Find a random word
0 if G$ is not in W$
Display blanks for word
do until Word is guessed or you are hanged track of the number of blanks that have been correctly
Guess a letter filled in. We will call this value NL. You will also
need to keep track of the number of incorrect guesses.
Search for letter in word
We will call this value NH. Each letter guessed will
if letter is in word
be stored in the string G$. You can determine if a
then display letter at proper position guessed letter G$ is in the word W$ by comparing
else display NO “letter” G$ with each letter in W$ and noting where any
add part to body matches occur. You will also need to know if any
enddo match occurred. For this purpose define a flag R and
if word is guessed
set R to 1 if any match occurs and set R to 0 if G$
is not in W$. At this point we have therefore defined
then blink word
the variable names given in Figure 15.3. We can now
display YOU ARE SAVED! use these variable names to put a little more detail
else display correct word in the pseudocode description of the program given
display YOU ARE HANGED! in Figure 15.2. For example, the do until loop can
Ask to PLAY AGAIN? be rewritten in the form shown in Figure 15.4. Note
repeat while answer is “Y” that the word is guessed when NL=L, and you are
hanged when NH=6. The algorithm to search for a
letter in the word is given by the for ... next loop.
it is so important that you understand how to write Note that this algorithm displays each letter that is
word-descriptions like the one in Figure 15.2. Study found in its proper position so that nothing more needs
it again. Note particularly how the do until loop is to be done in the then part of the following if...
used to include the entire process of guessing a word. then ... else statement. Also note that the flag R is
Being able to identify the appropriate looping structure used to tell if a letter is in the word.
for a particular problem (think do until, do while,
Figure 15.4 More detailed version of do until loop used
or for .. . next) is one of the important skills you will in HANGMAN program.
need to develop in order to become a good program-
NL=0
mer.
NH=0
do until NL=L or NH=6
Defining Program Variables Guess a letter G$
R=0
At this stage in the development of the program you for I=1 to L
should define names for those variables that you know
if GS=MIDS(W$,1,1)
you will need. You won’t know all of the variables
that you will end up using, but don’t worry about then print G$ in proper position
that. Define the important ones that you do know. NL=NL+1
This will help you to focus in on how you will imple- R=1
ment various little algorithms. Be particularly con- next I
scious of defining appropriate string variables and ar- if R=1
rays.
then do nothing
In the HANGMAN program we will store the word
else NH=NH+1
to be guessed in the string W$. The length of this
string (the number of letters in the word) will be L. display NO “letter”
How can you tell when the word is guessed correctly add part to body
or when it’s time to be hanged? You will need to keep enddo

155
You have now developed the program to the point in Figure 15.4. (The initialization of S$ to the null
where you can begin to write some BASIC code. Since string in line 70 was added when the subroutine to
you have already done most of the work, at this point guess a letter in line 400 was written.) Line 90 calls
the BASIC code will practically write itself. subroutine 400 to guess a letter. The words GUESS
A LETTER that appear on the screen will be written
in this subroutine. Line 100 sets the flag R to 0. Lines
Writing the Main Program 110-130 implement the for... next loop given in Fig-
ure 15.4. Note how the LOCATE statement in line
Your next step should be to write the main program 120 is used to print a guessed letter G$ in the proper
in BASIC following the pseudocode description given location on the screen. Lines 140-150 implement the
in Figures 15.2 and 15.4. Your goal should be to write last if... then... else statement in Figure 15.4 Sub-
this entire program so that it fits on a single page routine 900 called in line 150 will display NO “letter”
and you can read it all at once. To do this use subrou- and add a part of the body.
tine calls for anything that takes a lot of coding or Lines 160-180 implement the last if... then .
that you haven’t figured out how to do yet. else statement in Figure 15.2. We have actually inter-
The main program for HANGMAN is shown in changed the roles of then and else. That is, line 160
Figure 15.5. Line 20 clears the screen in medium reso- is equivalent to if word is not guessed. Subroutine
lution graphics and sets the background color to black 300 called in line 160 will display the correct word.
with the active palette set at 1. Line 30 displays the Subroutine 700 called in line 170 will blink the word.
word HANGMAN and the gallows in subroutine 600. Line 180 will ask to Play Again??? and line 182 places
Line 40 finds a random word W$ in subroutine 1000. a box around this so that it stands out. Line 185 erases
Line 50 finds the length, L, of the word W$. Line the message GUESS A LETTER. Lines 190-200 will
60 prints the L dashes for the word to be guessed. then wait for a key to be pressed and cause a new
Each letter position will be separated by a space. There- game to be played if the answer to Play Again??? is
fore, by starting at character location 20-L on the line He

and displaying a dash followed by a blank for each We have therefore written a complete main program
character position, each word will be centered on the that implements the HANGMAN algorithm given in
screen. Figure 15.2. We have also identified all the subroutines
Lines 80-150 implement the do until loop shown that must still be written. These are summarized in
Figure 15.6.
Figure 15.5 Main program for HANGMAN.
The next step is to write the minimum amount of
10 *HANGMAN code in each subroutine that will allow you to run
15 DEFINT I,L,N,R
20 SCREEN 1,0:COLOR 0,1:CLS and test the main program. Each stub could be just
ZO GOSUB 600:*’DISPLAY HANGMAN AND GALLOW a RETURN statement that does nothing but return
S to the main program. Once you are certain that the
40 GOSUR 1000: "FIND WORD WS main program is behaving properly, you can then write
50 L=LEN (Ws)
40 LOCATE 24,20-L:FOR I=1 TO L:PRINT "- and test each subroutine separately. They can then
"NEXT I be tested, of course, by running the main program
7O NL=O:NH=0:S¢=""" which calls the subroutine. This technique of top-down
80 IF NL=L OR NH=6 THEN 1460 programming allows you to plan the entire program
90 GOSUB 400: “GUESS A LETTER
iGO) (eee) and begin to test it before you have to get involved
110 FOR I=1 TO L in all the details of every subroutine. It also keeps
20 IF G#=MID#(W$,1I,1) THEN LOCATE 24,1 your program well modularized which will make it
8-L+2kI:FRINT G#;:NL=NL+1:R=1 much easier for you to debug and modify the program.
130 NEXT I In subroutine 600, it will take some thought to figure
140 IF R=1 THEN 80
150 NH=NH+i: GOSUB 900: GOTO 80
140 IF NH=6 THEN LOCATE 21, 21:PRINT NAGY)
ARE HANGED!"";:GOSUBR 300: GOTO 180 Figure 15.6 List of subroutines called from main program.
170 LOCATE 21,21: PRINT "YOU ARE SAVED!" Line No. Subroutine
;:GOSUB 700
180 LOCATE 19,23:FRINT “Play Again???" 600 Initial display (HANGMAN, gallows)
182 LINE (10,140)-(124,1460),,B 1000 Find a word, W$
TSalOCADE RS ner LINihee. Ws 400 Guess a letter, G$
190 AS=INEEY$: IF As="" THEN 190
200 IF At = "Y" THEN 20
900 Wrong guess-NO “‘letter,” add to body
SUG) (esataNp) 300 Print correct word
Ok 700 Blink word

156
out how to draw the gallows. Therefore, for now, just
type

600 REM INITIAL DISPLAY


610 PRINT “H ANGM AN”
620 RETURN GUESS f LETTER

for subroutine 600 and worry about the details later. NO P


In order to test the main program you should store NO I

a known word in W$. Therefore, for subroutine 1000


type

1000 REM FIND A WORD


1010 WS$= “HANGMAN”
1020 RETURN
which will assign the word HANGMAN to WS. It
is a good idea to pick a test word that contains multiple
occurrences of a single letter in order to make sure Figure 15.7 Testing the main program of HANGMAN.
that the main program displays all letters in their
proper locations. Later, you can come back and make With this much of the program written you can
subroutine 1000 produce random words. run the main program and test that it is working prop-
Subroutine 400 will display the words GUESS A erly. Figure 15.7 shows what the screen might look
LETTER and will then have the player guess a letter, like during such a test.
G$. At first it looks as if this is just a statement using After you have debugged the main program (it
the INKEY$ function. However, you do not want to won’t work the first time—Figure 15.5 was not our
allow letters that have already been guessed. (Other- first version) you are ready to tackle the remaining
wise, you could hang yourself by typing the same subroutines one by one.
wrong letter six times.) Therefore, subroutine 400 must
keep track of all letters that have been typed and only
return new values for G$. We'll figure out how to Writing the Remaining
do this later. For now just type Subroutines

400 REM GUESS A LETTER You can now go through and finish the subroutines
410 LOCATE 8,3: PRINT “GUESS A LETTER”; listed in Figure 15.6. Figure 15.8 is a listing of subrou-
420 GS = INKEYS: IF G$ = “ ” THEN 420 tine 600. Lines 620-630 draw the cyan gallows. The
430 RETURN result of running the main program after adding the
subroutine given in Figure 15.8 is shown in Figure
For subroutine 900 type 15.9:
900 REM WRONG GUESS The guess a letter subroutine 400 is shown in Figure
910 LOCATE 10+NH,3: PRINT “NO ”; G$; 15.10 where lines 430-460 have been added to ensure
that no letter is guessed more than once. Line 460
920 RETURN
keeps track of all letters that have been guessed by
This will print all wrong guesses along the left side adding each new letter to the string S$. (This is why
of the screen in character column 3 beginning at char- we initialized S$ to the null string “” in line 70 of
acter line 11. You can figure out how to add a new the main program.) Each time that line 420 gets a
part to the body later. new letter G§ it is compared with all previous letters
For subroutines 300 and 700 just type the stubs
Figure 15.8 Initial display subroutine that plots the word
300 REM PRINT CORRECT WORD HANGMAN and draws the gallows.
310 RETURN Ok
LIST 600-646
and 600 "INITIAL DISFLAY
610 FRINT "“HANGMAN"
700 REM BLINK WORD
(PNB) TASTES CUETO) ty) Pose eis mares) oy let
710 RETURN 6390 LINE (280,24)-(304,167),1,8BF
640 RETURN
and worry about these later. Ok

157
Figure 15.11 The wrong guess subroutine prints NO
“letter’’ and adds a part to the body.
900 “WRONG GUESS
910 LOCATE 10+NH,2:PRINT "NO "36%;
920 ON NH GOTO 930, 940, 950,960,970,980
920 *DRAW THE HEAD
931 LINE (200,40)-(232,72).,.B
GUESS & LETTER 922 LINE (192,48) -(200,64),,8
t) O25 LINE (222,48)~(240,64),,8
934 LINE (208,48)-(212,52),,BF
935 LINE (220,48)-(224,52),,BF
936 LINE (210,60)-(222,64),,BF
938 RETURN
940 *DRAW THE BRODY
942 LINE (212,72)—-(220,80),,B
944 LINE (200,80)-(232,128),,5
946 RETURN
950 "DRAW RIGHT ARM
952 LINE (168,80)-(200,88),,BF
954 LINE (168,89)-(175,128),.,BF
Figure 15.9 Result of running the HANGMAN program 956 RETURN
after adding the initial display subroutine. 9460 “DRAW LEFT ARM
962 LINE (222,80)—-(264,88),.,BF
964 LINE (256,89)-(264,128),.,BF
(stored in S$) in the loop in lines 430-450. If a match 966 RETURN
is found in line 440 then the program goes back and 970 “DRAW RIGHT LEG
gets a new letter in line 420. 972 LINE (184,120)-(200,148),,B
The “wrong guess” subroutine 900 is shown in Fig-
975 LINE (184, 148)-(200,150),,BF
974 RETURN
ure 15.11. Line 910 prints NO “‘etter’”’ along the left 980 “DRAW LEFT LEG
side of the screen. Lines 930-988 add the appropriate 982 LINE (222,120)-(248,148).,5
parts of the body to the hanging person. Line 920 is 9Q% LINE (232,148)-(248,150),,BF
984 “DRAW ROPE
the ON ... GOTO statement ON NH GOTO 930,
hea) ENS KORO, Pia a ara Tas 6 lel
940, 950, 960, 970, 980. This statement will branch SS8G USINED 2S 4 ke Ua CeO / eae
to line 930 if NH=1; to line 940 if NH=2; to line 9987 LINE (218, 20)—(256, 52), , BF
950 if NH=3, and so on up to NH=6.* Lines 930— 988 LINE (216,24)-(218,40),,BF
989 RETURN
938 plot the head (first wrong guess); lines 940-946
plot the body (second wrong guess); lines 950-956 plot
the right arm (on your left—third wrong guess); lines correct word above the blanks when the person is
960-966 plot the left arm (fourth wrong guess); lines hanged. Note the use of the function MID$ in the
970-974 plot the right leg (fifth wrong guess); lines PRINT statement in line 330 to print each letter of
980-983 plot the left leg (sixth and last wrong guess); the word W$§ at its proper location.
lines 984-988 plot the rope that does the hanging! In Subroutine 700 shown in Figure 15.13 blinks the
all the LINE statements used in drawing the body word by alternately printing a field of blanks and then
parts the color field was left empty. This means that the normal version of the word six times. Lines 720—
all parts will be drawn in white, the default foreground 740 insert a space between each letter of W$ and store
color. Any palette color could be used here. (See Exer- the resulting string in R$. These lines also build B$
cise 15.1.) into a string of blanks that is the same length as R$.
Subroutine 300 shown in Figure 15.12 prints the Lines 750-810 alternately print out the string of blanks
stored in B$, and the word stored in R$. Each of
Figure 15.10 The subroutine to guess a letter.
Ok
LIST 400-470 Figure 15.12 This subroutine prints the correct word above
400 “GUESS A LETTER the blanks.
419 LOCATE 8,23:FRINT "GUESS A LETTER";
420 GS=INKEY#: IF GH= "" THEN 420 Ok
430 FOR I=1 TO LEN(S$) LIST 300-240
440 IF Gt=MID#(S%,1I,1) THEN 420 S00 "“FRINT CORRECT WORD
450 NEXT I
460 St = S#+6%
210 LOCATE 23, 1isPRINT "WORD:":
470 RETURN £20) EGCATE 720-—
Ok 230 FOR T=1 TO LePRINT MIDS(WS,1,1)3" "sy
NEXT I
* The ON ... GOSUB statement works in a similar fashion but S40 RETURN
uses GOSUB rather than GOTO. Ok

158
Figure 15.13 This subroutine blinks the word. Figure 15.15 Sample run of HANGMAN program.
Ok (a)
LIST 700-820
700 *BLINK WORD
710 R$s""sRg=""
720 FOR I = 1 TOL
730 RS=RS+MIDS(WS,I1,1)+" "
735 BS=Bs+"
740 NEXT I
750 FOR I = 1 T0 6 He
760 LOCATE 24,20-L
770 PRINT BS: RE
Ne
780 FOR J=1 TO 200:NEXT J Hi
785 LOCATE 24, 20-L
790 PRINT RSs [Flau Again??? |
800 FOR J=1 TO 200:NEXT J
YOU ARE SAVED*t
810 NEXT I
820 RETURN EMPIRE
Ok

these strings is left on the screen for a short delay (b)


that is determined by either line 780 or 800. After
the word in B$ is flashed six times, the flashing stops
and B$ is left on the screen.
If all of the above subroutines are working properly,
then you can start adding some new random words
in subroutine 1000. There are several ways to do this.
One possibility is shown in Figure 15.14. Line 1005
sets a random seed for the random number generator.
Line 1010 defines the number of words NW stored
in the DATA statement starting at line 1050. You
can add more words and increase the value of NW.
In line 1020 X is assigned a random number between YOU ARE HANGEDt/
1 and NW. Line 1025 moves the “pointer” to the begin- WORD: i a
-UR-E
ning of the DATA statement. Line 1030 reads the
first X words. Therefore, word number X will end
up in W$. Note that with this subroutine the same
word can occur more than once. If you want to avoid
A sample run of this program is shown in Figure 15.15.
this you will have to keep track of the values of X
It is clear that to make this game really interesting
that have been used and not use the same ones more
you need a large dictionary of possible words so that
than once. (See Exercise 15.2.) Of course, you will
you will use different words each time you play. One
then only be able to play ten times before having to way to do this is to store a large number of words
re-run the program. in a floppy disk file and then read in a random group
of words each time the game is played.

Figure 15.14 Subroutine that finds one of ten words at


random.
Ok
STORING DATA
LIST 1000-1060 IN A SEQUENTIAL DISK FILE
1000 *“FIND A WORD
1005 RANDOMIZE VAL (RIGHTS (TIMES, 2) ) You have been using a floppy disk to save and load
1010 NW=10
1020 X=INT CRND (NW) XNW+1)
your BASIC programs. It is also possible for you to
1025 RESTORE include statements in your programs that will allow
1030 FOR I=1 TO Xs READ Wt: NEXT I you to store data on a floppy disk and later read back
1040 RETURN this data. You do this with the WRITE# and IN-
1050 DATA HIPPOPOTAMUS, NURSE,FAMOUS, EMPI
PUT# statements. However, in order to use these
RE,ELKE., DIGNITY
1060 DATA CONDITIONAL,
BRIBE, PAPER, QUAIL statements you must first use the OPEN statement
Ok and afterward the CLOSE statement.

159
The OPEN and CLOSE Statements File not found

Sequential disk files always begin WRITEing at the


Before you can write sequential data to a floppy disk
beginning of the file and place the data in the file in
on the IBM PC your program must execute the state-
exactly the order they are written. Sequential files al-
ment
ways begin INPUTting from the beginning of the file
OPEN filename FOR OUTPUT AS #filenum and items can only be read in the same order they
were entered. If you wish to have the ability to store
and before you can read data from a floppy disk your
and read data at any location in a file, that file must
program must execute the statement
be a random access file. These files are OPENed in
OPEN filename FOR INPUT AS #/filenum a different, and more complex, manner than indicated
above.
The meanings of the parameters in the OPEN state-
After a program has written data to (or read data
ment are shown in Figure 15.16.
from) a disk file the file that was opened with the
When a program executes the statement
OPEN statement must be closed with a CLOSE state-
OPEN “DATA” FOR OUTPUT AS #1 ment of the form
the IBM PC will create a file on disk A (the left disk) CLOSE #filenum
and associate this file with #1. This means that future
In this statement the filenum must be the same number
WRITE statements using #1 as a parameter will
that was used in the OPEN statement. In the examples
write data to this file for storage. (If a file with name
with “DATA” this would mean CLOSE #1.
“DATA” was already on this disk, it will be destroyed!)
DATA is used here as an example. Any legal file name
can be used. A legal file name is of the general form
The WRITE # Statement
d:filename.ext where d is optional and can be either
a or b, (corresponding to drive 1 and 2), filename After the statement
can be up to 8 characters long, and ext is an optional
OPEN “DATA” FOR OUTPUT AS #1
3-character extension.
When the program executes the statement is executed, your program can write either string or
numerical data to the file DATA with the statement
OPEN “DATA” FOR INPUT AS #1
WRITE #1, list-of-expressions
the IBM PC will search the directory on disk drive
A and look for the file “DATA.” When it finds it, it where /ist-of-expressions are the names of the variables
will associate this file with #1, so that future IN- you wish to store separated by commas.
PUT# statements with argument #1 will read data The program shown in Figure 15.17 can be used
from this file. If the file “DATA” doesn’t exist you to store a list of words in a floppy disk file for later
will get an error message use in the HANGMAN program. Line 30 opens a
file named TESTFL for writing. Lines 40-50 remind
the user that data are to be entered and that the pro-
Figure 15.16 Meanings of the parameters in the OPEN gram will terminate when an exclamation mark is en-
statement. tered instead of a word. Line 60 waits for a word to
ae” means open for writing by typed in and assigns this word to the string variable
pia mie
OPEN filename FOR OUTPUT AS #filenum
Figure 15.17 Program to store words on a floppy disk
as they are typed on the keyboard.
filename is a file name in filenum is an Ok
quotes (e.g., “DATA”) or a integer 1,2 or 3 een
string variable that contains 10 “CREATE A SEQUENTIAL FILE
20 “OF WORDS FOR HANGMAN
a file name.
20 OPEN "“TESTFL"” FOR OUTPUT AS #1
40 FRINT "ENTER WORDS ONE AT A TIME"
SO FRINT "ENTER AN ! TO TERMINATE"
OPEN filename FOR INPUT AS #filenum 60 INPUT WS
7O IF We = "'" THEN CLOSE #1:sEND
80 WRITE #1,W%
90 GOTO 60
INPUT means open for reading Ok

160
W$. If you type an exclamation point (!), then line © Figure 15.19 Program to read data that were stored using
70 CLOSEs the file and stops the program. the program in Figure 15.17.
Line 80 writes the word stored in W$ to the disk Ok
isi
file. Actually it stores this word in a buffer (a section 10 “READING FROM A SEQUENTIAL FILE
of memory) and waits until this buffer is full (or until SOPOrPEN RITES TEES POR. CNEUT TA Seid 4d)
a CLOSE statement is executed) before writing all SO WHILE NOT EQF (1): INFUT #1,W%s PRINT
characters in the buffer out to the disk file. WH: WEND
40 CLOSE #1
Line 90 branches to line 60 which waits for another oO END
word to be entered. You will notice that you can type Ok
in many words before the system writes anything to
the disk file. This is because no writing is done until As an example of using the INPUT # statement,
the buffer is full. If you do not fill up the buffer before the program shown in Figure 15.19 will read back
you type the exclamation point, !, then the remaining the data that was stored in Figure 15.18. Line 20 opens
contents of the buffer are written to the disk file when the file “TESTFL” for reading. Line 30 is a WHILE
the CLOSE statement is executed. This statement will statement that reads in a word from the file and prints
also add an end-of-file mark (EOF) on the disk at it out. It repeats this action until there are no more
this point. words in the file.
A sample run of the program given in Figure 15.17 The function EOF(1) used in line 30 is a logical
is shown in Figure 15.18. Once a long list of words function that is true if the next item on the disk is
is stored in a disk file, the file can be used with the the End of File (EOF) mark. It is false if there are
HANGMAN program to retrieve a different random more data in the disk file. Line 30 will therefore test
set of words each time the program is run. A method the EOF and see if it is true. If it is, then NOT EOF(1)
of modifying the HANGMAN program to accomplish will be false and control will drop to line 40 which
this will be described next. closes the file. If EOF(1) is false then NOT EOF(1)
is true and the INPUT #1,WS statement will read
in a word and the PRINT WS statement will print
The INPUT # Statement it out. This action repeats as long as EOF(1) is false.
It is important to test for the EOF mark before the
After the statement INPUT #1 statement is executed. Otherwise, you may
get an Input past End of file error. The result of execut-
OPEN “DATA” FOR INPUT AS #1
ing the program given in Figure 15.19 using the disk
is executed, your program can read data that have file created in Figure 15.18 is shown in Figure 15.20.
previously been written in disk file DATA with the Suppose that you have created a data file containing
statement a large number, NT (say 1000), of HANGMAN words
using the program given in Figure 15.17. How can
INPUT #1, list-of-variables
you input a different random set of N (say 50) of these
The list of variables must be of the same type, and words each time HANGMAN is run? One possible
in the same order, as the type of data that was written method is suggested in Figure 15.21. N words from
to the file. If, as in the case above, you wrote string the file will be stored in the array W§(I). In order to
data to the file, the statement required to read these store a different set of words each time, then a random
data one string at a time would be number of words R will be skipped after each word
that is actually stored in the array W(I) as shown in
INPUT #1,WS
Figure 15.21.
In order to skip a word you must read the word
and just throw it away. You can do this with a state-
Figure 15.18 Sample run of program in Figure 15.17 that
stores five words in a disk file. ment such as
Ok
RUN
Figure 15.20 Result of running the program in Figure 15.19
ENTER WORDS ONE AT A TIME using the disk file created in Figure 15.18.
ENTER AN ! TO TERMINATE Ok
? HORSE RUN
DOG HORSE
RANDOM DOG
CONDITIONAL RANDOM
ICE CONDITIONAL
coteecs
Sal)
ee)
ee eS
Qk

161
Figure 15.21 To produce a new random set of words skip Figure 15.22 Modified HANGMAN subroutine that will
R (a random number) words between each word stored find a word from a collection of words stored in a disk
in the array W§$(I). data file.
words stored in 1000 “FIND A WORD
data file 1010 IF N220 THEN 1150
1020 NT=25: N=10: =2x (NT/N-1)
1050 LOCATE 19,3
pies HOUSE 1060 INPUT "ENTER FILE NAME"sFS
err #1, WS ~ 1065 OPEN FS FOR INPUT AS #1
CAR INPUT #1, W$(1)
and throw 1070 FOR I=1 TON
away —— COMPUTER 1075 R=INT(RND(1) kW+1)
Skip R words 1080 FOR J=1 TO R
BOAT 1085 IF EOF (1) THEN N=I-1: GOTO 1120
1090 INPUT #1,W4
EXCELLENT=— INPUT #1, W$(2) 1095 NEXT J
1100 IF EQF(1) THEN N=I-i: GOTO 1120
1105 INPUT #1,W#(T)
{iO NEXT tf
1120 LOCATE 19,53
1125 FOR I=1 TO 30: PRINT " "“seNEXT I
1120 CLOSE #1
1150 I = INT(RND(1) XN+1)
1160 WH=WH(I):s WH(T)=WH CN)
1170 N=N-1
1180 RETURN
Ok
INPUT #1,WS
To keep a word, input it into the array with the state-
ment in the string F$. Line 1065 opens disk file F$ for read-
ing.
INPUT #1,WS(D)
The loop in lines 1070-1110 will read N words into
What range of values should the random number the array W3(I) (line 1105). In between each word
R have? If you pick N words (50) equally spaced from stored in the array WS$(I), R words will be read and
a total of NT (say 1000) words then you will pick thrown away in the loop in lines 1080-1095. A different
one out of every NT/N words and there will be NT/ random value of R between 1 and W is computed in
N-—1 words between each one selected. If you picked line 1075 every time through the outer loop.
a random number R between 1 and NT/N-1 you Inasmuch as R is “random” you can’t be sure that
would seldom get much beyond the middle of the list it won’t have large enough values often enough to get
before N words are selected. This is because the average to the end of the data file before N words are stored
of all the R values will be about (NT/N—1)/2. There- in W$(I). In order to test for this possibility the EOF
fore, in order to spread the N words out over all of mark is checked for in lines 1085 and 1100 before
the NT words you can let R be a random number each word is read. If an end-of-file (EOF) mark is
between 1 and 2*(NT/N-—1). detected then the number of words read to that point
To incorporate these ideas into the HANGMAN (I—1) is stored in N and the program branches to
program add the line line 1120. Lines 1120 and 1125 erase the message asso-
ciated with entering the filename. Line 1130 closes
17 N=0: RANDOMIZE VAL(RIGHTS(TIMES,2)):
the data file and the subroutine continues at line 1150.
DIM W5S(50)
Once N words are read into the array WS§(I) then
to the main program shown in Figure 15.5. Then up to N HANGMAN games can be played before
change the “find a word” subroutine given in Figure the disk file has to be read again. If the value of N
15.14 to the subroutine shown in Figure 15.22. The is not O when subroutine 1000 is entered then the pro-
first time this subroutine is called (or after N words gram branches immediately to line 1150 where a ran-
have been used) the value of N will be O and lines dom number I between 1 and N is computed. The
1020-1130 will be executed. These lines read another new word W$ to be used in HANGMAN is the word
N random words from the data file. stored in WS$(I). Line 1160, after assigning W$(I) to
Line 1020 computes the value W=2*(NT/N-1) W$, replaces the word in location I (which has just
which will be the maximum value of the random num- been used) by the word in location N. The value of
ber R corresponding to the number of words skipped N is then decremented by one in line 1170. This will
in the file. Line 1060 asks the user to enter the filename insure that no word is used more than once since each
of the file containing the words. This filename is stored word is effectively removed from the list as it is used.

162
Figure 15.23 Sample run of HANGMAN program using
words stored in a disk data file. ~ PC ORGAN
(a)
As another example of developing a BASIC program
we will turn the IBM PC into a musical instrument.
First we will learn how to play the notes of the scale
by pressing keys on the keyboard and then we will
develop a complete program that will display the musi-
cal keys on the screen.

Playing a Tone
When a Key Is Pressed

You should review the sections in Chapters 4 and 5


on making sounds with the IBM PC. Recall that the
statement

SOUND P,L
will produce a single tone on the TV speaker of fre-
quency (pitch) P and length L. Using this statement
you must specify the length of the tone L before the
statement SOUND P,L is executed. This means that
we will not be able to keep playing a note as long as
a key is pressed. Rather, each note will be played for
a fixed length of time L. We will use a value of L=3
which corresponds roughly to an eighth note. Our or-
gan will therefore play staccato music.
Type in the following short program and run it.
10 P=89:L=3
ARE HANGED? 20 A$ = INKEYS: IF A$ = “ ” THEN 20
30 SOUND P,L : GOTO 20
This program should play a short note each time any
key is pressed. (Note that if you do not lift your finger
after pressing a key the note will repeat. If you hold
the key down a long time before releasing it, the note
will continue for a considerable length of time. This
A sample run of the modified HANGMAN pro- is because the keyboard buffer stores a series of values
gram using the subroutine in Figure 15.22 is shown of the key you have depressed. You must lift your
in Figure 15.23. finger immediately after pressing the key.) We must
now make different keys play different notes.
EXERCISE 15.1
Modify the LINE statements in the “WRONG
GUESS” subroutine in Figure 15.11 so that some of
the body parts are drawn in solid colors. For instance, Screen Layout
leave the face and arms as they are, but make the
body cyan, the legs white and the shoes magenta. The program we will write will display 10 white keys
(Note: If you switch from palette 1 to palette 0 the and 7 black keys in medium resolution graphics ac-
characters displayed will be in brown, rather than cording to the layout shown in Figure 15.24. The keys
white.) A through ; on the computer keyboard will be the
“white” keys of the organ and the keys in the row
EXERCISE 15.2 above will be used for sharps and flats (black keys).
Modify the subroutine to find a word in Figure 15.14 The IBM PC keys corresponding to each key on the
so that no word is selected more than once. screen will be printed on each key using a shape defini-

163
0 40 80 120 160 200 240 280 320
4 zz eel es | | | | te

0
sm tact

Ee |

ANY 7 noe UA | | yoA- eg |


120 (lLBAILY Li U, We U YU GY, ag Wi,We Wi:

160 z I

EEE :

ORE EMSS)
Figure 15.24 Screen layout for the PC Organ.

tion string for each letter. The words PC ORGAN 15.25. Note that the A above middle C has a frequency
and OCTAVE 2 will also be plotted using shape strings. of 440 hertz. This value is used as the starting point
When a note is played an eighth note will be dis- by many piano tuners. The pitch values shown in Fig-
played on the key being pressed for as long as the ure 15.25 will be stored in a two-dimensional array
tone continues. Thus, as a song is played this note P(1L,J) where I (1-17) corresponds to the white and
will move from key to key. The shape of this note black keys being displayed on the screen and J (0-3)
will be defined by a shape string. corresponds to the octave number minus one.
The PC Organ will start out in octave 2. Pressing
key 1 will change it to octave 1 (one octave lower),
pressing key 3 will change it to octave 3 (one octave Word Description of Program
higher) and pressing key 4 will change it to octave 4
(the next higher octave). Thus, the total range of the The program for the PC Organ can be understood
PC Organ will be over four octaves. For example, from the pseudocode word-description given in Figure
pressing key A on the computer keyboard when in 15.26.
the octave 2 mode will produce the same note as press-
ing key K when in the octave 1 mode. The octave
number that is active at any time is displayed near Variable Definitions
the bottom of the screen.
The major variables used in the PC Organ program
are defined in Figure 15.27. Using these variables the
Frequency Values pseudocode program shown in Figure 15.26 can be
for the Musical Scale refined to that shown in Figure 15.28. Note how the
do until loop is used to find the index I corresponding
The frequency values for each note in the four octaves to the key that was pressed. This value of I is then
corresponding to our screen layout are given in Figure used to find the proper frequency value stored in P(I,J).

164
80¢

LLE
SZI S8l 961 Occ €€?e Lye c9e Llée v6e O€€

UY, (IY ly | |
ZY

-
rie:
yY
LA Y

Yj
Y
A
7

Y y
A, Yj,
Oo oOfe:<x > fa a 1,

fel
Lu

Ee MIDDLE
ba B
e|
i

OCTAVE 2

WWCWW
AYN

SZIL
WC6011
LC eg
6s9
5

vel 088 886 Zv0l S¢el


A €26
WW
Ov

OCTAVE3
Tt
Bea

WWW
4
Xa

|
ADMM_|
WN
Zv0l

Ran

6vEC
ae Osrl

O9Z1
Se oe

6011 6lEL Z6EL L99L S98l 9261 €60¢ 8lée


Wea lolals

SZLL Svcl 89S1


wees)

WV
BER

N\\\
N
SSS
ee

Tt Ni
Tt

OCTAVE 4 NN
NI
BE2

Figure 15.25 Frequency values corresponding to all notes that can be played on the PC Organ.

165
Figure 15.26 Pseudocode word-description for PC Organ Figure 15.28 Pseudocode description of PC Organ
program. program.
Initialize variables; store shape strings Fill arrays K$() and P(,J) with appropriate values
Display keyboard Store shape strings
loop: Wait for key to be pressed Display keyboard
Identify key T=1:L=3
if key is a note key loop: Wait for key AS to be pressed
then play note I=1
else if key is 1, 2, 3, or 4 do until AS=K$(1) or I=18
then change octave number I=I+1
repeat forever enddo
Figure 15.27 Major variables used in PC Organ program. if 1<18
K$(18) —An array containing the IBM PC key characters: then P=P(I,T)
—A,S,D,F,G,H,J,K,L,; for the white keys play note
—W,E,T,Y,U,O,P for the black keys
else I=VAL(AS)
P(17,3)—a two-dimensional array containing the pitch values
for the corresponding keys in KS$(I). The columns if I=0 or I>4
of the array correspond to the four octaves. then do nothing (invalid key)
—octave number minus one
—pitch (frequency) value being played else
—duration of note being played Display I
$
rPrus —character value corresponding to computer key
T=I-1
pressed
repeat forever

If key 1, 2, 3, or 4 is pressed then no match will occur


in the do until loop and L will equal 18. (Note that tine 1400 that is called in line 130 will play the note.
this is why K$(I) must be dimensioned to K$(18).) Eventually this subroutine will display the eighth note
In this case I is changed to VAL(A$) which will on the screen keyboard before playing the note. How-
be 1, 2, 3, or 4 (for valid keys) and T is changed to ever, for now you can test out the playing of the PC
I-1 so as to select the proper frequency values in Organ by typing
PUT):
We are now at the point where the BASIC program 1400 REM PLAY NOTE
will practically write itself. 1450 SOUND P,L
1470 RETURN

The Main Program which just plays the note. You will also need to write
the following stub for the keyboard display subroutine:
The main program for the PC Organ is shown in Figure
600 REM DISPLAY KEYBOARD
15.29. It follows closely the pseudocode description
shown in Figure 15.28. Lines 20-50 fill the arrays with 610 RETURN
the appropriate data. Note that all of the “white” keys Try running the program now.
are stored first in K$(I). Also note that the order of
the pitch values stored in P(I,J) is the same as the
corresponding key values in K$(1) according to Figure Remaining Subroutines
£5325:
Lines 35 and 50 store tab data that will be used Once you have the musical part of the PC Organ work-
later (in subroutine 800) to plot the key labels. Line ing you can finish the Display Keyboard subroutine
55 stores the shape strings by calling subroutine 2000. as shown in Figure 15.30. This subroutine will produce
For now simply type the keyboard shown in Figure 15.31 where the title
2000 REM STORE SHAPES and lettering on the keyboard are printed using subrou-
tine 800 shown in Figure 15.32.
2010 RETURN
To get the octave number displayed at the bottom
Lines 70-160 are a direct implementation of the of the screen, two lines must be added to the main
loop. . . repeat forever loop in Figure 15.28. Subrou- program.

166
Figure 15.29 Main program for the PC Organ.
10 * PC ORGAN
12 SCREEN 1,0
15 DIM K$(18) .P (17,3), TR(7) »N$(4) , L$ (22)
20 DATA A,S.DsFaGeHadg kg lig "§"aWeEa Ty Yas
O.F
25 DATA 131,147,165, 175,196, 220, 247, 262,
294,330,139, 156, 185, 208, 233,277,311
2B DATA 262,294, 330, 349,392, 440,494,523,
587,659, 277,511,370, 415, 466,554,622
ZO DATA 523,587,659, 698, 784, 880, 988, 1047
11175,1319, 554, 622, 740,831,923, 1109, 1245
B2 DATA 1047,1175, 1319, 1397, 1568, 1760,19
76, 2093, 2349, 2657, 1109, 1245, 1480, 1661,18
65,2218, 2489
35 DATA 18,435,93,118,145, 195, 218
40 FOR I=1 TO 17:READ K#(I): NEXT I
45 FOR J=0 TO 3: FOR [=1 TO 17: READ PCI
sJ)s NEXT IT: NEXT J Figure 15.31 The keyboard for the organ produced by the
30 FOR T=1 TO 7: READ TR(I): NEXT I subroutine shown in Figure 15.30.
55 GOSUB 2000; "STORE SHAPES
60 GOSUBR 400; *“DISFLAY KEYBOARD
65 T=1: L=3
L$(I) using subroutine 2000 (called in line 55 of the
70 AS=INKEYS: IF Ags" THEN 70
75 IF Ag="X" THEN CLS: END main program) shown in Figure 15.33.
80 I=1 The eighth note shape is displayed when a note is
90 IF AG=K$(I) OR I=18 THEN 110 played using subroutine 1400 shown in Figure 15.34.
100 I[=I+1: GOTO 90
The value of I in line 1410 is the value found in the
110 IF I=18 THEN 1406
1135 P=P(1,7T) do until loop in lines 90-100 of the main program.
120 IF P=0 THEN 70 If this value is greater than 10 then a “black” key
120 GOSUB 1400: GOTO 70 was pressed and the coordinates XN,YN at which the
140 I=VAL (AS): IF I=0O OR 134 THEN 70 note will be plotted are determined by the ELSE clause
145 “STATEMENTS TO FLACE OCTAVE NUMBER
150-—"ON THE SCREEN WILL-GO HERE
in line 1410. The X-position at which the note is
T60.T=1—-1: GOTO 70 DRAWpn in line 1440 is determined by the value in
Ok the tab array TB(I-10) (line 1410) that was initialized
in lines 35 and 50 in Figure 15.29.

145 LINE (192,162) — (220,198),0,BF Figure 15.32 Subroutine to display the lettering on the
150 DRAW “C3;S8;BM208,168;XN$(1);” organ keyboard.
800 “TITLE AND LABELS
Line 145 erases the old octave number by “blacking 810 M$="BM+2,-7"
it out” and line 150 writes in the new number using B20 DRAW "BM70,0;C3"
the shape table for the correct number (N§(I)). 820 DRAW "Sil23XbL6¢17) 3 XMS; XL$(18) 5"
840 DRAW "BM1IS0O,0"
The shape definitions used in this program are given
845 DRAW "XL$(16) ; XMS; XLS(19) 5 XMH5 XLS)
in Table 15.1 and are stored in the arrays N$(I) and pXMBsXLS(1L) ¢XMSs3XLHS(ZO) 3"
850 DRAW "CO;S4;BM12, 1443 XL$(1) 3"
855 FOR I=2 TO 10
Figure 15.30 Subroutine to display the keyboard 860 DRAW "RM+27,-73XL6(1I)3"
for the PC Organ. 865 NEXT I
Ok 870 DRAW "C3"
LIST 600-695 S75 FORD f=) (a) 7
600 * DISPLAY KEYBOARD 880 M$="ERM"+STR#(TR(I))+",104"
610 FOR I=0 TG 288 STEF 32 882 L#=L#(I+10)
620 LINE (1,32)-(1+30,160),,BF 885 DRAW "XM#s; XL; "
sO NEAT I 890 NEXT I
640 FOR 1=16 TO 276 STEP ©32 895 DRAW "S8;BM100, 168"
650 IF I=80 OR I=208 THEN I[=I+32 900 M$="RM+2,-7"
660 LINE(I,32)—-(1+1 4,BF
120) ,0, 905 DRAW "XL$(146) 3 XM#s XL$(18) sXM$sXLS(15
670 NEXT I DRA ESH ILE SGD) Hq ESR fe Se re db Sty gk (Cole)
675 GOSUR 800 910 DRAW "BM+12,-73 XN#(2) 5"
695 RETURN 20 RETURN
Ok Ok

167
TABLE 15.1 Shape definitions used in the PC organ program.
Shape No.
1 A: BR5BD3L5ND4U2E1R3F1D6
2 S: BR5L4G1D1F1R3F1D2G1L4BR5
3 D: ND7R4F1D5G1L4BR5
4 F: NRS5D3NR4D4BR5
5 G: BR5L4G1D5F1R3E1U2L2BD3BR2
6 H: D3ND4R5NU3D4
7 J: BD5D1F1R3E1U6BD7
8 K: D3NE3ND4F4
a Ea DRS
10 3: BR4L2D2R2U2BD4L2D2R2NU2G2BR3
ie VV DZ7ESESU7BD7.
12 E: NRS5D3NR4D4R5
13 T: R3NR3D7BR3
14 Y: F3NE3D4BR3
15 U: D6F1R3E1U6BD7
16 O: BD1D5F1R3E1U5H1L3G1BD6BR5
17 P: ND3R4F1D1G1L4D4BR5
18 C: BRSBD1H1L3G1D5F1R3E1BD1
19 R: ND7R4F1D1G1L4F4BR1
20 N: ND7F7NU7
21 Note: H2L3G2D3F1NUS5FINU7ZR1NUZ7R1NUZ7R1NU7ZE1NU5E1U18F5
22 V: D4F3E3U4BD7

After displaying the eighth note in line 1440 the note puter programs. Programming is a skill that still re-
is played in lines 1450 and 1452. The eighth note is quires insight, creativity, a knack for problem solving,
then erased in line 1460. The reason that the SOUND and practice.
statement was split into two parts in lines 1450 and If you have read this entire book, typed in all the
1452 is that after a SOUND statement begins making examples on your IBM PC, and worked a good number
a sound, execution continues with the next statement. of exercises, then you will have a good understanding
Thus the DRAW statement in line 1460 could erase of how to write BASIC programs on an IBM PC. It
the note on the screen while the sound was still being is now time for you to start writing your own programs.
generated. However, when the second SOUND state- Many useful programs can be written using the IBM
ment is encountered, it won’t begin execution until PC. Pick an area in which you are an expert. How
the first sound has stopped. In this way the note should can the IBM PC help you in this area? Start by writing
stay displayed as long as the sound exists. a short program, and then expand it into a longer,
The coordinates XN,YN for plotting the note on more complex program. You will find that writing
the white keys are given in the THEN clause in line computer programs is challenging, rewarding, and fun.
1410. Since the spacing of the white keys is uniform Good Luck!
the position of the note on the line can be calculated
by the equation XN=(I—1)*32+16 as given in line
1410. Examples of the eighth note that is displayed EXERCISE 15.3
when the PC Organ is played are shown in Figure Write a program to play the game MASTERMIND.
15:35: The computer thinks of an N digit number where each
digit can be in the range 1-M. The player is allowed
to select N and M at the beginning of the game. The
CONCLUSION player guesses a number (all N digits) and the computer
responds with two numbers P and W. P is the number
The HANGMAN and the PC Organ programs were of digits that were correctly guessed that are in the
developed using the six steps outlined at the beginning correct position in the number, and W is the number
of this chapter. This is not the only way to develop of digits guessed that are in the number but were
a program and these steps may not always be appropri- guessed in the wrong position. The player continues
ate for all programs that you write. However, they to guess numbers until the number is guessed (or the
are a good guide to use when you get stuck and don’t player gives up and asks for the answer). When the
know how to proceed. In the last analysis you will number is guessed the computer displays the number
have to develop your own approach to writing com- of tries that it took to guess the number.

168
Figure 15.33 Subroutine to store
shape strings.
2900 *STORE SHAFES
2010 FOR I=1 TO 4:READ N#®(1I): NEXT I
2020 FOR I=1 TO 22:READ L#(1L): NEXT I
SURO. > :
2035 DATA BDIEIDZNLIRI
2040 "2
2045 DATA BDIEIRSFIDIGILZG1DSR5
2050
2055 DATA RDIEIRSFIDIGINLSFID2G1ILSHIBRSED1
2060 *4
2965 DATA BRSGSRSNRINUSD2RR1
2070 "A
2075 DATA BRSRDSLSND4UZE1RSFIDS
2080 °S
2085 DATA BRSL4G1IDIFIRSF1ID2ZGIL4BR5
2090 °D
2095 DATA ND7R4F1D5G1L4BR5
Sere 2S
2105 DATA NRSDSNR4D4BR5
2110 "G
2115 DATA BRSL4G1DSFIRSE1UZLZRDSBR2
2120 °H
2125 DATA DEND4RSNUSD4
2150 "D
21iZS5 DATA BDSDIFIRSE1U6BD7
2140 °K
2145 DATA DSNESND4F4
2150 °L
2155 DATA D7R5
2160 "3
21465 DATA BR4L2D2R2UZRD41_2D2R2NUZG2ERE
2170 7W
2175 DATA D7ESF3U7BD7
2180 °E
2185 DATA NRSDZNR4D4R5
2190 °T
2195 DATA RENRZD7BRS
2200 °¥
2205 DATA FSZNEZD4BRS
2210 7U
2215 DATA D6éFIRSE1U6BD7
222070
2225 DATA BDIDSFIRSE1USHILSG1BD6BRS.
2250 °P
2225 DATA NDZR4F1D1G1L4D4BR5
22740- °C
2245 DATA BRSEDIHILSG1DSFIRZE1BD1
2250 °R
2255 DATA ND7R4F1D1G1L4F4BRi1i
2260 "N
2265 DATA ND7F7NU7
2270 "NOTE
2275 DATA HSLIG2D2FINUSFINU7RINU7ZRINUZRINUZEINUSELULSFS
ee
2285 DATA D4FSE2U4BD7
2290 RETURN

EXERCISE 15.4 a higher count than the computer without going over
Write a program to play the card game BLACKJACK 21. Face cards count 10 and an ace can count either
against the computer. The player first places a bet. 1 or 11. Being dealt an ace and a face card is a blackjack
Two cards are dealt to the player and two cards are and is an automatic winner. If the player’s count goes
dealt to the computer (one face up and one face down). over 21 it is a bust and the player loses. After the
The player can ask for a hit (another card) as many player stops taking hits (with the card count less than
times as he or she wants. The player’s goal is to have or equal to 21) the computer turns over its face down

169
Figure 15.34 Subroutine to display the eighth note and Figure 15.35 (a) PC Organ when playing a white note (key
produce the tone. F); (b) PC Organ when playing a black note (key 7).
1400 *PLAY A NOTE
1410 IF I<ii THEN YN=137: XN=(I-1)k32+16:

PE. ORGAN
Cis="CO"sC2$="C3" ELSE YN=80s XN=TBCI-10)
+6:C1$="C3"3C2$="C0"
1420 M$="BM"+STRS (XN) +", "+STRS CYN)
1430 DRAW "S4"
1440 DRAW "XM%3 XC1i#s XL#(21)5"
1450 SOUND P,L
1452 SOUND P,1
1460 DRAW "XC2HaXM#s XLS (21) 5"
1470 RETURN
Ok

card and can then take additional cards to try to beat


the player. The computer will always take a hit if its
card count is less than 17. The computer will always
stand for a card count of 17 or greater. No money
is won or lost on a tie. Have the program continue
playing and keep a running total of the player’s win-
nings.

EXERCISE 15.5
Write a program to play tic-tac-toe. The player should
have the option to play against a second player or
the computer.

UE EVE ce

170
APPENDIXES
MOTOR’ POS SAVE THEN
APPENDIX A
NAME PRESET SCREEN TIME$
RESERVED WORD
NEW PRINT SGN TO
NEXT PRINT# SIN TROFF
IBM PC BASIC uses certain words for special pur-
poses, such as CLS for the Clear Screen command, NOT PSET SOUND TRON
and WHILE for signalling the beginning of a do while OCT$ PUT SPACE$ USING
OFF RANDOMIZE SPC( USR
construct. These words are called reserved words and
ON READ SQR VAL
cannot be used as variable names in a program. The
OPEN REM STEP VARPTR
following list includes all reserved words in IBM PC
OPTION RENUM STICK WAIT
BASIC. You should not attempt to use any of these
OR RESET STOP WEND
words as variable names.
OUT RESTORE STR$ WHILE
PAINT RESUME STRIG WIDTH
ABS CSNG ERR KEY PEEK RETURN STRINGS WRITE
AND CSRLIN | ERROR KILL PEN RIGHTS SWAP WRITE#
ASC CVD EXP LEFT$ PLAY RND SYSTEM XOR
ATN CVI FIELD LEN POINT RSET TAB(
AUTO CVS FILES LET POKE RUN TAN
BEEP DATA FIX LINE
BLOAD DATES FNXxxXxxxxx LIST
BSAVE DEF FOR LLIST APPENDIX B
CALL DEFDBL FRE LOAD ASCII CODES
CDBL DEFINT GET LOC
CHAIN DEFSNG GOSUB LOCATE ASCII ASCII
CHR$ DEFSTR GOTO LOF value Character value Character
CINT DELETE HEX$ LOG 000 (null) 009 (tab)
CIRCLE DIM IF LPOS
001 © 010 (line feed)
CLEAR DRAW IMP LPRINT
002 @ 011 (home)
CLOSE EDIT INKEY$ LSET
003 v 012 (form feed)
CLS ELSE INP MERGE
004 4 013 (carriage return)
COLOR END INPUT MID$
COM EOF INPUT# MKD$ 005 & 014 Je
COMMON EQV INPUTS MKI$ 006 o 015 x
CONT ERASE INSTR MKS$ 007 (beep) 016 >
COS ERL INT MOD 008 ie 017 «

171
ASCII ASCII ASCII ASCII
value Character value Character value Character value Character
018 t 066 B 114 r 162 }
019 I 067 Cc 115 s 163 di
020 T 068 D 116 t 164 A
021 § 069 E 117 u 165 N
022 os 070 F 118 v 166 a
023 $ 071 G 119 w 167 0
024 4 072 H 120 x 168 é
025 { 073 | 121 y 169 =
026 > 074 J 122 z 170
027 _— 075 K 123 { 171 Y,
028 (cursor right) 076 L 124 172 %
029 (cursor left) 077 M 125 } 173 i
030 (cursor up) 078 N 126 eS
031 174 «
(cursor down) 079 O 127 (a 175
032 »
(space) 080 P 128 G 176 ce
033 ! 081 Q 129 ui 177 oot
034 a 082 R 130 é 178
035 # 083 S 131 4 179 oy
036 $ 084 i 132 4 180 4
037 % 085 U 133 a 181 al
038 & 086 V 134 a
039 182 |
; 087 Ww 135 ¢ 183 a
040 ( 088 x 136 e 184 =
041 ) 089 Y 137 é
042 = 185 =I
090 7. 138 é
043 + 186 I
091 [ 139 i
044 ; 187 =)
092 \ 140 j
045 : 188 a
093 ] 141 i
046 189 ot
094 A 142 A
047 ji 190 =
095 = 143 A
048 0 191 a
096 ‘ 144 E
049 1 192 L
097 a 145 e
050 2 193 aL
098 b 146 A
051 3
194 Se
099 c 147 6
052 195 -
4 100 d 148 6 196 —
053 5 101 e 149 5 197 +
054 6 102 f 150 0 198 f
055 7 103 g 151 u 199 Ir
056 8 104 h 152 y 200 CS
057 9 105 153 fe) 201 IF
058 : 106 j 154 U 202 at
059 ; 107 k 155 é 203 ae
060 < 108 | 156 £ 204 F
061 = 109 m 157 es 205 =5
062 > 110 n 158 Pt 206 at
063 ? 14 Oo 159 f 207 ok
064 @ 112 p 160 a 208 aL
065 A 113 q 161 i 209 =

172
ASCII ASCII Error Error
value Character value Character
Number Message
210 +r 233 aa 13 Type mismatch
211 Hes 234 Q 14 Out of string space
15 String too long
212 fs 235 6 16 String formula too complex
PINS? = 236 fo) 17 Can’t continue
214 rr RE) (4) 18 Undefined user function
215 tt 238 € 19 No RESUME
20 RESUME without error
216 = 239 N 7H) Missing operand
2a, 4 240 = 23 Line buffer overflow
218 ia 241 ot: 24 Device Timeout
25 Device Fault
219 ® 242 2
26 FOR without NEXT
220 = 243 S 27 Out of Paper
221 | 244 ( 29 WHILE without WEND
30 WEND without WHILE
222 a 245 J 50 FIELD overflow
223 a 246 = 51 Internal error
224 a 247 ~ 52 Bad file number
225 6B 248 : 53 File not found
54 Bad file mode
226 if 249 ° 55 File already open
227 1 250 ‘ 57 Device I/O Error
228 > 251 Ni 58 File already exists
61 Disk full
229 o 252 n 62 Input past end
230 u 253 63 Bad record number
231 25 254 a Correct the PUT or GET statement to use a
valid record number.
232 © 255 (blank ‘FF’)
65 Bad file name
Courtesy of IBM Corporation 66 Direct statement in file
67 Too many files !
68 Device Unavailable
APPENDIX C 69 Communication buffer overflow
ERROR MESSAGES 70 Disk Write Protect
71 Disk not Ready
When a fatal error is encountered during the execution 72 Disk Media Error
of a BASIC program an error message related to that 73 Advanced Feature
— Unprintable error
error is printed on the screen and execution is termi-
nated. It is possible to use an ON ERROR statement
that will transfer control to an error handling routine
when an error is encountered. This routine could check
the error number for the current error and respond APPENDIX D
with some type of predetermined logic. All error mes- HEXADECIMAL NUMBERS
sages and their related numbers are listed below.
Consider a box containing one marble. If the marble
Error Error is in the box, we will say that the box is full and
associate the digit 1 with the box. If we take the marble
Number Message
out of the box, the box will be empty, and we will
NEXT without FOR
Syntax error
then associate the digit O with the box. The two binary
RETURN without GOSUB digits 0 and 1 are called bits and with one bit we
Out of data can count from zero (box empty) to one (box full)
Illegal function call as shown in Figure D.1.
Overflow
Out of memory
Undefined line number Figure D.1 You can count from 0 to 1 with one bit.
Subscript out of range
HNMNPWNHE
OWI
Duplicate Definition
Division of zero 0 = empty box 1 = full box
oO
NK
——=— Illegal direct Number of marbles = 0 Number of marbles = 1

173
Figure D.2 This box can either contain two marbles (full) box must contain 8 marbles. The binary number 8
or no marbles. would then be written as
S Hs 8@ /
1000
0 = empty box 1 = full box
Remember that a 1 in a binary number means that
the corresponding box is full of marbles and the num-
Consider now a second box that can also only be ber of marbles that constitutes a full box varies as
full (1) or empty (0). However, when this box is full 1,2,4,8 starting at the right. This means that with four
it will contain 2 marbles as shown in Figure D.2. With bits we can count from 0 to 15 as shown in Figure
these two boxes (two bits) we can now count from D5;
zero to three as shown in Figure D.3.
Figure D.5 You can count from 0 to 15 with four bits.
Figure D.3 You can count from 0 to 3 with two bits. No. of Marbles Total no.
in each full box (bit= 1) ofmarbles Hex Digit
Total number of marbles
ts) ez eae ee

OR Oe OO 0 0
OR Oe Olea 1 1
Oa Olen tee yD, 2
Oe Oh =I 3 3
Oa ORO) 4 4
\@e/’ \e@/ 3 OM sly 0) al 5 5
Onesie 0 6 6
Oe sel aol 7 7
(ORO 20 8 8
Note that the value of each two-bit binary number LO OMerrit 9 9
shown in Figure D.3 is equal to the total number of lie OP Solan 10 A
marbles in the two boxes. LY ees ee 11 B
1 erOF 0 ie C
We can add a third bit to the binary number by
Lie wee OE 13 D
adding a third box that is full (bit=1) when it contains Tee Pee elie ae) 14 E
4 marbles and is empty (bit=0) when it contains no A te affnoe ili ae 15 F
marbles. It must be either full (bit=1) or empty (bit=0).
With this third box (3 bits) we can count from 0 to It is convenient to represent the total number of
7 as shown in Figure D.4. marbles in the four boxes represented by the four bit
binary numbers shown in Figure D.5 by a single digit.
We call this a hexadecimal digit and the sixteen hexa-
Figure D.4 You can count from 0 to 7 with three bits.
decimal digits are shown in the right-hand column
in Figure D.5. The hexadecimal digits 0-9 are the same
as the decimal digits 0-9. However, the decimal num-
bers 10-15 are represented by the hexadecimal digits
A-F. Thus, for example, the hexadecimal digit D is
equivalent to the decimal number 13.

a vhguananamrd : In order to count beyond 15 in binary you must


add more boxes. Each full box you add must contain
twice as many marbles as the previous full box. With
eight bits you can count from 0 to 255. A few examples
are shown in Figure D.6. Given a binary number the
corresponding decimal number is equal to the total

Figure D.6 You can count from 0 to 255 with eight bits.

ose 08-8 7 Total no.


No. of marbles in each full box (bit= 1) of marbles

26" 64 332) i626) 4 lat


If you want to count beyond 7 you must add another
0 1 1 Onasledeod oO 52
box. How many marbles should this fourth box contain 1 0 1 0 OO” OnpH tal 163
when it is full (bit=1)? It should be clear that this 1 1 1 1 i mean (amet | 21) 255
number of marbles in all of the boxes. To find this ' is equivalent to the decimal number 34,761 (i.e., it
number just add up all of the marbles in the full boxes represents 34,761 marbles). This can be seen by ex-
(the ones with binary digits = 1). panding the hexadecimal number as follows:
As the length of a binary number increases it be-
8X 163= 8 X 4,096 = 32,768
comes more cumbersome to work with the binary num-
ber. We then use the corresponding hexadecimal num- 7X 16?= 7X 256= 1,792
ber as a shorthand method of representing the binary Cx164=12X 16= = 192
number. This is very easy to do. You just divide the 9X 16°= 9X 1= 9
binary number into groups of four bits starting at the 32,761
right and then represent each four-bit group by its
corresponding hexadecimal digit given in Figure D.5. You can see that by working with hexadecimal num-
For example, the binary number bers you can reduce by a factor of 4 the number of
digits that you have to work with.
1001 1010
eS o”
The following table will allow you to conveniently
S A convert up to four digit hexadecimal numbers to their
decimal equivalent. Note, for example, how the four
is equivalent to the hexadecimal number 9A. You terms in the conversion of 87C9 given above can be
should verify that the total number of marbles repre- read directly from the table.
sented by this binary number is 154. However, instead The function HEX$, available in IBM PC, will com-
of counting the marbles in the “binary boxes” you pute the hexadecimal value of a decimal number. For
can count the marbles in “hexadecimal”? boxes where example, if you type
the first box contains A*1=10 marbles and the second
box contains 9 X 16 = 144 marbles. Therefore, the ?7HEX$(34761)
total number of marbles is equal to-144 + 10 = 154. the IBM PC will print the hexadecimal value 87C9
A third hexadecimal box would contain a multiple on the screen.

Hexadecimal and Decimal Conversion


15 BYTE Sr 7 BYTE 0
IS CHAR. 2a Tl CHAR -8|.7° ) CHARIS “Aigrs sai CHAR SO
HEX DEC | HEX DEC | HEX DEC | HEX DEC
0 0 | 0 0 | 0 OF z0 0
1 4,096 | 1 256 | 1 HOw 1
a: SO 2s 2 aA | 2 yal 72 2
3 12,288 | 3 768 | 3 48 | 3 3
4 16,384 | 4 1,024 | 4 64 | 4 4
5 20,480 | 5 1,280 | 5 SOMO 5
6 24,576 | 6 17536)\86 96 | 6 6
7 28j;0725)\ 97. A277; 2 eZ, 7
8 32,768 | 8 2,048 | 8 128 | 8 8
9 36,864 | 9 2,304 | 9 144 | 9 9
A 40,960 | A 2,560 | A 160 | A 10
B 45,056 | B 2,816 | B 176 | B 11
G AQ 1525 G 37307256 (G2 12
D 53,248 | D 3,328 | D 208 | D 13
E 57,344 | E 3,584 | E 224 | E 14
F 61,440 | F 3,840 | F 240 | F 15
Le

of 162=256 marbles and a fourth hexadecimal number APPENDIX E


would contain a multiple of 163=4,096 marbles. As THE EDIT COMMAND
an example the 16 bit binary number
1000 0111 1100 1001 One way to make corrections in a given line of a BASIC
program is to first LIST that portion of the program
Sy oC 49 that contains the statement. You can then move the

175
cursor (using the cursor keys |,—,],<) to the line ahead of the A in the order you type them. To get
and character position you wish to edit. After the edit- out of the insert mode press INS again (you'll note
ing has been completed, you must move the cursor the size of the cursor is larger in the insert mode)
to the end of the listing on the screen before RUNning and then press ENTER. You must press ENTER to
the program. lock in your changes. The editing is now complete,
An easier way to edit a line is to use the EDIT and you can RUN the program.
command. if you want to edit, say, line 50, enter
EDIT 50
The END Key
Line 50 will be displayed and the cursor will be placed
at the beginning of the line. You can now make correc- In the EDIT mode pressing the END key will move
tions on this line; “fix” the corrections by pressing the cursor to the end of the line being EDITed. This
ENTER; and immediately RUN the program. is much quicker than using the — cursor key.
As an example of using the major editing function
keys, assume you have a line 50 in your program that
has been entered as The Backspace Key and Space Bar

50 AX = A—B*C:ADD
If you press the backspace key while EDITing a line,
which is supposed to be the cursor will move back one space, but delete the
character to the left in the process. This is a legitimate
50 AX = B+C:REM ADD
editing command. If you wish to move the cursor to
The editing requires three changes: the left without deletion, you must use the left cursor
key. In a similar fashion if you use the space bar to
1, Delete “A—”’;
move the cursor to the right, the character under the
Z.scnange ine.’ toa “+”: bar will be replaced by a blank.
3. Insert “REM” after the “‘:’’. For further editing features you should read the
IBM PC BASIC Manual.

The DEL (Delete) Key

To begin the editing process enter EDIT 50.


To delete the “A—” use the — and <— cursor keys
to place the cursor under the ‘“‘A”’ (the leading charac- APPENDIX F
ter in the string you wish to delete). Now press DEL. PRINT USING STATEMENT
The “A” will disappear and all the characters to the
right of this point will move left to fill in the “hole” The PRINT USING statement, available in IBM PC
left by the deletion. The ““—” is now above the cursor. BASIC, allows you to print data in a variety of useful
Press DEL again and the “—” will disappear and all formats. The general form of the PRINT USING state-
characters to the right of the cursor will move left ment is
again. You will now have
PRINT USING format; item-list
50 AX = B*C:ADD
In this statement format is a string containing various
with the cursor under the B. field specifiers, and item-list is the data (generally varia-
To change the * to a + move the cursor to the * ble names separated by commas) to be formatted. The
and press the + key. The * will disappear and the + possible field specifiers that can be used in the format
will be in its place. You now have string are the following:
50 AX = B+C:ADD

Field
The INS (Insert) Key Specifier Meaning
Bae The number of # signs included in the format
To insert the word REM ahead of ADD move the string determines the width of a numeric
field. Ex: PRINT USING “###' A
cursor to the A in ADD. Press the INS key to get
If numeric value is too large to fit into the for-
into the insert mode. Now type REM followed by a matted field, the number will be displayed
blank. As characters are typed they will be inserted with a leading % sign.

176
Field
Specifier
APPENDIX G
Meaning
INTEGER OPERATORS
A decimal point can be placed between # signs
to indicate the location of the displayed deci- IBM PC BASIC has two integer mathematical opera-
mal point. ;
Ex: PRINT USING “###+.##A tors that can be used to advantage in programs of a
scientific nature. These are the operators for integer
division (\) and for modulo arithmetic (MOD).
A comma inserted anywhere to the left of the
decimal point will cause a comma to be in-
In integer division the two operands are first
serted after every third digit. It is preferable rounded to integers, then the division is performed
to insert a comma at every desired location and the answer trunctated to an integer. Thus 3.6\2.2
because each comma will establish an addi- would give a value of 2 and 3.2\1.8 would give 1.
tional position in the numeric field. The MOD operator gives the integer remainder that
Ex: PRINT USING “##,###,###A
is left over from integer division. In the examples given
above 3.6 MOD 2.2 would be 0, since 4/2 is 2 with
Places a dollar sign at the beginning of the nu- no remainder, while 3.2 MOD 1.8 would give 1 since
meric field.
Ex: PRINT USING “$####.##A
3/2 is 1 with a remainder of one. Examples of these
are shown in Figure G.1.
$$ Places a dollar sign just to the left of the first
displayed digit. Figure G.1 Examples of integer division and modulo
Ex: PRINT USING “SSH #H#H.HH#'%A arithmetic.
Ok Ok
**
Fills all unused positions to the left of the deci- Binal
een ee EGS LEVON a
mal point with asterisks. .
Ok Ok
Establishes two more positions in the numeric
Bh aN ae te Sas Kar Sly On) aCL eee hh
field.
1 oO
Ex: PRINT USING “**##4##.4#A
Ok Ok
Be Gy
BING ST)ote:
¥*9
Places a dollar sign just to the left of the first Biefay [HIBVOY Pea ool
displayed digit, and fills all unused positions co) Ok
to the left of the dollar sign with asterisks. Ok EE A [M(GNO) That)
Ex: PRINT USING “**$####.4##’3A Bag OPO BY AS ake: a
1 Qk
Qk
Displays + for positive numbers and — for nega-
tive numbers. Can be used at the beginning
or end of the numeric field. The order of precedence for integer division and
Ex: PRINT USING “+####A modulo arithmetic comes after real division and multi-
plication and before real addition and subtraction.
A minus sign (—) placed at the end of the nu-
meric field will display a negative sign (—)
after negative numbers and a blank after posi-
tive numbers.
APPENDIX H
Ex: PRINT USING “####.##-''A USING MACHINE LANGUAGE
SUBPROGRAMS WITH BASIC
AAAA
Print number in exponential form
Ex: PRINT USING “###.###°°™°'A This appendix assumes that you know how to write
8088 assembly language programs.
Print only the first character of a string. If you are writing a machine language subprogram
Ex: PRINT USING “!”;A$ to be called from an IBM PC BASIC program, you
have the choice of considering the subprogram as a
\spaces\ Displays n characters of a string where n is 2 function and calling it with a USR statement, or of
plus the number of spaces between the \ considering it as a subroutine and calling it with a
signs. CALL statement. We will assume you wish to use a
Ex: PRINT USING “\ \”;A$
subroutine and that arguments will be passed back
and forth between the BASIC program and the ma-
Variable length format will display all of a
string.
chine language subroutine.
Ex: PRINT USING “&”;AS$ When using a machine language subroutine called
will display all of A$, regardless of its length. from a BASIC program, you are faced with the prob-

177
lem of setting aside an area of memory in which to Figure H.1 BASIC Program Calling a Machine Language
store the subroutine and then the additional problem Subroutine.
Ok
of placing the subroutine in that area of memory. If
eis
you have a color/graphics monitor adapter (which this 5 "CALLING & MACHINE LANGUAGE SUBROUTINE
text assumes you do) the easiest place to locate the 10 DEFINT A~-Z
subroutine is in one of the unused pages in the graphics 20 DEF SEG = &HEIOO
ZO FOR I=O TO 21
display buffer. If the subroutine is not too long, the
40 READ J
simplest way to put the machine code in the display is) [za na)
buffer is to store the machine language program in 60 NEXT I
DATA statements in your BASIC program and then 70 SUB=O
80 X=5:Y¥=6: Z=0
READ and POKE these values into the display buffer
90 CALL SUEB(X,Y,Z)
before the subroutine is called. These two steps will eK) Tele 74
be illustrated with a specific example below. 110 END
The subroutine CALL statement in IBM PC BASIC 120 DATA &HSS, &HBE, &@HEC, &@HBR, &H76, &HOA
120 DATA &H8B, &HO4, @HBR, &H76, &HOS
is of the form 140 DATA &H2E, &HO4, KHER, &H7E, &HOS
150 DATA &H89,&%HOS, &@HSD, &HCA, &HO6, &RHOO
CALL name (var, vare,.. .)
Ok
where name is an integer variable whose value indi- RUN
=i
cates the byte offset to the first executable statement
Ok
in the subroutine (with respect to the address pointed
to by the Data Segment register). The var, are the
names of the variables to be passed as arguments to the POKEs are made. Since the first executable state-
the subroutine. The BASIC CALL results in an “‘intra- ment in the subroutine begins with the first byte of
segment” (FAR) call in 8088 assembly language, with machine code, SUB (the name of the subroutine) is
the following items on top of the stack. assigned the value zero — indicating zero offset to the
first executable statement. The return is RET 6, since
there are six bytes of parameter addresses on the stack.

APPENDIX I
SUMMARY OF BASIC STATEMENTS
requires
The following summary gives examples of the syntax
for various statements and commands in IBM PC BA-
SIC. For a more detailed discussion of each statement
refer to the pages cited, or the IBM PC BASIC.
I/O Statements Page Reference
BEEP —
CIRCLE (x,y),r 121
CLOSE #f 159
CLS 3
COLOR foreground, background, border 24
The return is of the form COLOR background, palette 55
DATA list of constants 84
RET bsize DRAW string 126
where bsize is two times the number of arguments FIELD #f,width AS stringvar... —_
GET #f,number fas
being passed to the subroutine. GET (xl,yl)-(x2,y2),arrayname 149
As a specific example, the program given in Figure INPUT “prompt”;variable list 33
H.1 involves a machine language program that accepts INPUT #f, variable list 161
three arguments X,Y and Z; subtracts Y from X; and LINE (x1,y1)-(x2,y2) 56
returns the difference as Z. The machine code is stored LINE INPUT “prompt” ;stringvar _—
LINE INPUT #f,stringvar —
in DATA statements and is POKEd into page four
LOCATE rovw,col 22
of the graphics display area. This is accomplished by LPRINT list of expressions —
setting the DS register to the hex value B900 before LPRINT USING v5$;list of expressions —

178
I/O Statements Page Reference ~ V/O Statements Page Reference
LSET stringvar=x$ STRIG ON/OFF
OPEN filespec FOR mode AS #f STRIG(n) ON/OFF/STOP
OPEN mode, #f,filespec,recl _ SWAP variablel,variable2
OPEN “COMn:options” AS #f TIMES = x$
OUT n,m WAIT port,n,m
PAINT (x,y),paint,boundary WEND
PLAY string WHILE expression
PRINT list of expressions
PRINT USING V3, list of expressions Commands
PRINT #f,list of exps AUTO number, increment
PRINT #f, USING v$;list of exps BLOAD £(filespec, offset
PRESET (x,y) BSAVE (filespec, offset,length
PSET (x,y),color CLEAR,n,m
PUT #f,number CONT
PUT (x,y),array,action DELETE line1-line2
READ variable list EDIT line
RSET stringvar=x$ FILES filespec
SCREEN mode, burst,apage, vpage KILL filespec
SOUND freq,duration LIST line1-line2,filespec
WIDTH size LLIST line1-line2
WRITE list of expressions LOAD (filespec
WRITE #f, list of expressions MERGE filespec
NAME filespec AS filename
Non-I/O Statements
NEW
CALL numvar(variable list) RENUM newnum,oldnum, increment
CHAIN filespec RESET
COM(n) ON/OFF/STOP RUN filespec
COMMON ist of variables RUN line
DATES = x$ SAVE filespec
DEF FNname(arg list)=expression SYSTEM
DEFtype ranges of letters TRON,TROFF
DEF SEG=address
FUNCTIONS AND VARIABLES
DEF USR=offset
DIM list of subscripted variables Arithmetic Function
END ABS(x)
ERASE arraynames ATN(x)
ERROR n CDBL(x)
FOR variable=x TO y STEP z CINT(x)
GOSUB line COS(x)
GOTO line CSNG(x)
IF expression THEN clause ELSE clause EXP(x)
KEY ON/OFF/LIST FIX(x)
KEY n,x$ INT(x)
KEY(n) ON/OFF/STOP LOG(x)
LET variable=expression RND(x)
MIDS(v$,n,m)=y$ SGN(x)
MOTOR state SIN()
NEXT variable SQR(x)
ON COM(n) GOSUB line TAN(x)
ON ERROR GOTO line
ON n GOSUB line list String-Related Functions
ON n GOTO line list ASC(x$) 104
ON KEY(n) GOSUB line CVI(x$), CVS(X$), CVD(x$)
ON PEN GOSUB lize INSTR(,x$,y$) 113
ON STRIG(@) GOSUB line LEN(x$) 102
OPTION BASE n VAL(x$) 103
PEN ON/OFF/STOP
POKE n,m I/O and Miscellaneous Functions
RANDOMIZE n
REM remark CSRLIN
RESTORE line EOF(f)
RESUME line/NEXT/0 ERL
RETURN line ERR
STOP FRE(x)

179
Page Reference Page Reference
INP({) RIGHTS(x$,n) 102
LOC(f) SPACES\(n)
LOF(f) STRINGS(n,m) 105
LPOS(@) STRINGS(n,x$)
PEEK(n)
PEN(@) I/O and Miscellaneous Functions
POINT(x,y)
DATES$
POS(n)
HEXS$(m) 175
SCREEN(rovw,col, z)
INKEYS
STICK()
INPUTSS(,#f)
STRIG(n)
MKIS(x), MKSS(x), MKDS(x)
USRn(x)
VARPTR(variable)
OCTS(n)
SPC)
VARPTR(#f)
STRS(x)
General Function TAB)
TIMES
CHRS(N) 105 VARPTRS(v)
LEFTS$(x$,n) 101
MIDS$(x$,n,m) 102

180
INDEX

ABS, absolute value, 25-26 multiple, 90-92 Character attribute code (See Attribute
Acreage, 72 of economic data, 90-92 Code)
Addition, 16 using arrays, 96-99 Character code, 139-41
Algorithm, 50-52 vertical, 89-92 Checkerboard pattern, 59-60
ALT key, 10 BASIC, 8, 10-11 random, 67-68
American flag (See Flag) advanced, 2, 8, 11, 122 CHR$, 104-105
AND, 46-47, 151 cassette, 2, 8 Circle (See also area; circumference; plot-
Angle rotation factor, 129 disk, 2, 8, 11 ting)
Animated graphics, 148-52 interpreter, 2, 8, 146 CIRCLE statement, 121-23
Apple II, 1, 9 memory map, 146 Circumference of circles, 44
Arc tangent, 28 program, 9, 13, 146-47 CLEAR, 95
Area: ROM, 2 Clearing the screen, 3
of a circle, 29, 33, 44 stack, 146 Clicks, 41
of a rectangle, 32, 45 statements, 178-80
CLOSE statement, 159-60
of a triangle, 49-50, 53, 65 CLS, 3
BASICA, 11
Areas, (See plotting) Colon, 13
Binary number, 3, 173-75
Arithmetic expressions, 17 COLOR, 24-25, 54-55
Blackjack, 169
Array of points, (See plotting) Color codes, 24, 55, 141
Blinking characters, 24-25
Arrays, 93-100 Colors, 24, 55
Booting the computer, 10
multi-dimensional, 95-96 Comma:
Border, 24
one-dimensional, 93-95 adding to dollars and cents, 108
BREAK, 12-13 in PRINT statement, 21
three-dimensional, 96, 143-44
two-dimensional, 95-96, 112
Key, 12 Complement, 46
ASC, 104-105 Buffer, 161 Compound interest, 72, 100
ASCII codes, 104-105, 171-73 (See also Display buffer) Concentric squares, (See Plotting)
Aspect ratio, 117, 122 Built-in functions, (See Functions) Conjunction, 46
Assembly language, 8-9, 178 Burst (See Graphics) CONT, 12
Atari, 1, 9 Byte, 3, 136 ’ COS, 28, 121
ATN, 28 Cosine, 28, 121
Attribute codes, 140-42 Calculator mode, 16-18 CTRL key, 10, 12
Average, 54, 99 CALL, 177-78 Cursor keys, 176
CAPS LOCK key, 3
Background, 24, 55 Card number, 108-109, 112 Data segment register, 136-38, 178
Backspace key, 2, 5, 176 Cards, (See Playing cards) DATA statement, 84-86
Bar graphs, 86-92, 96-99 Cassette BASIC (See BASIC) Date, 10
adding scale, 88-89, 91 Celsius, 36 Dealing hand of cards, (See Playing cards)
horizontal, 86-89 Cents (See Dollars and cents) Debugging, 12

181
Decimal constants, 18 File (See Sequential file; Random access Jack, 143-45
Deck of cards, (See Playing cards) file)
DEFINT, 20 File name, 160 KEY OFF, 5
DEF FN statement, 29-30 File number, 160
KEY ON, 5
DEF SEG, 136 Keyboard, 1-2
FIX, 25-26
DELETE, 14-15 King, 143-45
Fixed point constant, 18
DIM statement, 94-96 Flag, American, 59, 61-63
Direct mode, 3
LEFT$, 101-102
Floating point constant, 18 LEN, 102
Disjunction, 46 Floppy disk, (See Disk) LET, 6
Disk, 9-11 Flowchart, 50-53 LINE, 54, 56-59
file, 159 structured, 51-53 LINE INPUT, 35
storing data, 159-62 FOR . . . NEXT loop, 37-42 Line length, 6
Diskette, (See Disk) Lines, (See Drawing)
nested, 39-42
Display buffer, 138-39, 146 LIST, 4, 14-15
Foreground, 24
graphics, 147-48 function key, 5
FRE, 95
Display screen, 139 LOAD, 11
Frequency, 35, 41, 163
Division, 17 LOCATE 20, 22-23, 38
Frequency values for musical scale
Do until (See Loops) LOG, 28-29
(See Musical Scale)
Do while (See Loops) Logarithms, 28
Function keys, 2, 5
Dollar sign (See string functions, string Logical expression, 43
variables, and Dollars and cents) Functions:
Logical operators, 43, 45-48
Dollars and cents built-in, 25-29 Loop. . .continue if. . . endloop, 69, 71—
printing, 105-108 user-defined, 29 2
DOS, 9-10 Loop . . . exit if. . . endloop, 69, 71
Double precision, 19 Gas mileage program, 33-34, 44 Loops, 11-12, 37-42, 64-73
Doubling time (See exponential growth) bar graph, 92 do until, 69-71
DRAW statement, 126-34, 149, 167-68 GET, 149-52 do while, 68-70
relative moves, 128-29 GOSUB, 74-75 FOR. ..NEXT (See FOR. . . NEXT
rotating figures, 129-30 GOTO, 11 loop) i
scaling figures, 129 Graphic figures, 105 nested, 39-42, 66-68
Drawing: (See also Plotting) Graphic patterns (See Plotting) repeat until, 69-70
border, 38-39 Graphic character codes, 105 repeat while, 64-68, 70
playing card, 105 WHILE... WEND (See WHILE...
flag (See Flag)
WEND)
lines, 38-39, 56-57 Graphics, 54-63
rectangles, 57 animated (See Animated graphics)
Machine language, 177-78
your name, (See Plotting) apage, 148
Manhattan Island, 72
colors, 55
Mastermind, 168
Economic data (See Bar graphs) display buffer (See Display buffer) Matrix, 95
EDIT, 5, 175-76 high-resolution, 115-34 Medium-resolution graphics (See Graph-
Editing a statement, 5, 175-76 medium-resolution, 54-63, 133 ics)
END, 12 modes, 54, 115, 148 Memory, 15
END key, 176 vpage, 148 for storage of decimal constants, 18
End of file (EOF), 161 map, 144-47
ENTER key, 2-3 Hangman, 153-59, 162-63 required for graphics, 117
EOF, 161 Hexadecimal: Microprocessor, 9
Equivalence, 47 numbers, 136, 173-75 8088, 9, 135
EQV, 47 to decimal conversion, 175 6502, 9
Error handling routine, 153 HEX$, 175 Z80, 9
Error High-resolution graphics, (See Graphics) MID$, 102-103
advanced feature, 151 Monochrome monitor, 2
Horizontal bar graphs (See Bar graphs)
division by zero, 34 Multiple statements, 13
Horizontal scale factor (HSF), 119-21
duplicate definition, 95 Multiplication, 17
Hypotenuse, 28
file not found, 160 Music on the IBM PC, 163-68
illegal function call, 15, 23 Musical scale, 164-65
IBM PC, 1-2
input past end, 161
If. ..then. . . else, 48-52 Name and address, 34
messages, 173
IF . . . THEN statement, 43-45 Names, (See Drawing)
out of data, 84-85
IF ...THEN.. . ELSE statement, 48 Nassi-Schneiderman chart, 52
out of memory, 95
IMP, 47-48 Nested loops, (See Loops; also FOR. . .
overflow, 19, 33-34
Implication, 47-48 NEXT loops)
RETURN without GOSUB, 77, 86
INKEY$, 35-36 NEW, 5
subscript out of range, 94-95
Income tax, 53 NEXT (See FOR . . . NEXT loop)
syntax, 3, 6
Indirect mode, 3-4 NOT, 46-47
type mismatch, 103
INPUT statement, 31-34 Notes, (See musical scale)
ESC key, 2, 5
INPUT#, 159, 161-62 Numeric precision, 18
Exclamation point with numbers, 19 Numerical variables, 19-20
EXP, 28-29 INS (Insert) key, 176
types, 20
Exponential function, 28-29 INT, 25-26, 34
Exponential growth, 29 Integer constants, 18
ON ERROR statement, 173
Exponentiation, 17 Integer operators, 177 ON . . . GOSUB statement 158
Intel 8088 (See Microprocessor) ON . . . GOTO statement, 158
Fahrenheit, 36 Interest (See compound interest) OPEN statement, 159-60
Fibonacci sequence, 72 Interpreter, (See BASIC) Operating system, 2

182
OR, 46-47, 151 PRINT statement, 3, 16 SIN, 28, 121
Order of precedence, 17, 47 comma, 21 Sine, 28, 121
Organ, PC, 163-68 semicolon, 21 Sine wave, (See Plotting)
Out of data error (See Error) PRINT USING, 49, 107-108, 176-77 Single precision, 18
Overflow error (See Error) Printer, 3 Siren sound, 41
Prt Sc key, 3 Sorting:
PAINT, 133-34 .PSET, 55, 115-16, 151 in increasing order, 97-98
Painting figures, 133-34 Pseudocode, 50—52, 70-72, 155, 166 a column of a 2-D array, 111-15
Palette, 55 PUT, 149-52 in decreasing order, 99
PASCAL, 9, 50 a hand of cards by suit, 111-15
Pay program, 48-49, 52-53 Queen, 143-45 SOUND, 35, 40-41, 163
PEEK, 135-38, 146-47 Question mark, 4 Sound effects, 40-42
PEEK/POKE character codes, 140 SQR, 28
Percent sign, 20 RAM (Random access memory), 2-3 Square root, 27-28
PET, 1 Random access file, 160 Stack, 146, 178
Phase angle, 125-26 Random checkerboard, (See Checkerboard Standard deviation, 99
Phaser noise, 41 pattern) Star field (See plotting)
Pi, 28 Random numbers, 26-27 STOP, 12
Pitch (See Frequency) Random stripe pattern, 66-67 String functions, 101-103
Playing cards, 108-113 RANDOMIZE, 27, 162 String variable, 5-6
dealing hand, 110-113 Radian, 28 Strings, 3-6, 101-114
graphics, 105, 109 Read only memory (See ROM) STRING$, 104-105
shuffling deck, 110 READ. . . DATA, 84-86 Stripes, (See plotting)
sorting by suit (See Sorting) READ statement, 84-86 Structured flowcharts (See Flowchart)
Plotting: (See also Drawing) Real numbers, 18-19 Structured programming, 9
American flag, 61-62 Rectangles, (See Area; Plotting) STR$, 103-104
Relational operators, 43, 45-46 Stubs, 156
array of boxes, 58-59
REM, 13 Subroutines, 74-83
array of points, 39-40, 57-58
Repeat until (See Loops) Subscripted variable, 93-94
axes, 125-27
Repeat while (See Loops) Subscripts, 93-96
ball, 123-24
Reserved words, 6, 171 Subtraction, 17
circles, 121-23
RESTORE, 84-86 Substrings, 113-14
concentric squares, 58-59, 118
RESTORE line, 86 Suit, (See playing cards)
dots, 55, 116
RETURN statement, 74-75 Syntax, 9
ellipses, 122-23
Reverse video, 24-25 Syntax error, (See Error)
functions, 125-26
Right triangle (See Triangle)
house, 78-80
RIGHTS$, 27, 102 TAB, 20, 22
line figures, 118-20
RND, 26-27, 42 TAN, 28
lines, (See Drawing) Temperature, 36
ROM, 2
multiple figures, 80, 130-31 RUN, 3, 5 Tic-tac-toe, 170
numbers, 131-32 function key, 5 Time, 10
polygons, 123-26 TIME$, 27
random checkerboard (See Checker- Sailboat, 120, 149-52 Top-down programming, 156
board pattern) SAVE, 11 Train model of program, 15, 51
random stripes (See Random stripe pat- Saving programs, 9-11 Triangle (See area; plotting)
tern) Scale, (See musical scale) right, 28
rectangles, 75-77, 79-82 Scaling factor, 129 Trigonometric functions, 28
sailboat, 119-20 Scaling figures, 82-83, 120 TRS-80, 1, 9
shapes, 126-34 Scientific notation, 18 Two-dimensional array, (See Arrays)
sine wave, 125-27 SCREEN, 24, 40, 54-55, 115-16, 148
square, 116-18 Screen color, 24, 40 USR, 177
star, 118-20 Screen layout, 23
star field, 59-60, 62 hangman, 154 VAL, 27, 103
stripes, 59-62 organ, 165 Variables:
triangles, 75, 78-80 Segment register, 136 numerical (See numerical variables)
your name, 81-82 Semantics, 9 string (See string variables)
Pointer, 85 Semicolon, 21 subscripted (See subscripted variable)
POKE, 135, 138-44 Semiperimeter, 49 VARPTR, 137
POKE a picture, 143-46 Sequence number, 13 Vertical bar graphs (See Bar graphs)
Polygon, (See Plotting) Sequential file, 159-62
Polynomial, 100 reading words, 161-62 Weekly pay program (See Pay program)
Population storing words, 159-62 WHILE... WEND, 64, 68-69, 71
density, 92 SGN, 25-26 WIDTH, 6
growth, 73 Shape definitions, 133, 168 WRITE, 159-61
New England states, 87-89, 93-94, 99 SHIFT key, 2
PRESET, 151 Shuffling deck of cards, (See Playing cards) XOR, 46-47, 151

183
5 r ac i
: é. row

Ae Fi
ag ad "
stre4 ~ Sa aoe

f Cee fas P
Ais 7
“a > ‘

fox;
4 e 4 a ;

« A ™
mt >» < ae

—~ We Oe oats een
Mabie afl aly ;
a a he ae ie
é si, he, ‘ }

ve hh. « ~

w-*) ed
ae )

* =e.3 72
oz
i b

+ a. Paral +
ns ‘a ¥ hy’ 1
Mes a
? »? te i Stet

iv $ s 7 . :
(é.yirdy a oe ra 4 a2 ‘ ese
anh

Rp aypecharal '-Actseatt ’ } Su tiea edfaa 7 et d ; * i bunv = ory DR


PM) ioe haat A )
as ‘vip bo ARR ry 5 wee = WeyPa sila)iy 3eh
‘ dsiee
goiter

, j batt
0 c Yad
NN \ *

tt = i =

Hite Ravaia
rie sabePoh Bea uate0s
co) ie 6 S te ae
Ar.
a “k puie a Boe Pate ae
Alas «BT, Aiaene eee he os eG
2 ERSL bonny
= if et al-irT ‘
cs ea |
: 5
5 : ’ Sea
=
oP i
“thay i. ies arate 4
: se | Sy
’ 4
b, :
y Mey \
i °

mg
2 y 7 = i tis P
E nhl | ee er
vane WS aie ia estab hy id soda Peas Hk
J waved = eh et Ae ’ Pi ot a
et tel, Haas = oJ Sa-T 9! ated Opole aya oe an
a ae | LD ee’ i - of. "tT pow bate oe 7 aa >
>) WRU ae ae ae ies Le
es ~
ATR te rt ere et LE scat, * thsey EOF
a wee 7 ees ie
.

, a Soae)
Soh echetteat
Tha .
Ja

PRENTICE-HALL, Inc.,-Engle is, New Jersey


LOOK FOR THESE OTHER
BEST-SELLING
BOOKS FROM PRENTICE-HALL:
COMMODORE 64"/VIC 20” BASIC
aicarcigem atst).(iies alee Maleleatctomsaigre(s) qalcxeqalt
fo [=¥-] MNco] gumtals ol-leiialaiiare Mmr-lalemmr-LehvZ-laver-ve mmelcole|e¢-lialeil-1amr-11 (mm Cal Mmmallele] gm) (=) bd ohoa-1 (19)
F-Yo)olcey-(e] smcomm elaelele-lailuillare Mr:MmOrolarlintere(ola-Mmor Mol am 4 (Cmr-10MN(alm 701 Omorelial-mrerel ile) (a (maha
examples illustrated’ by actual photographs taken from the computers’ video screens.
Ovo (-1e-me-j(alae Mc: laceleli-t-me-lale madtale MmiUlaren ((olat-oem (ele) os-Me-laleM-1ae- ha-mm el-Lame e-|e)t-em-jole (ale mlatteto
operation of the cassette tape recorder:and floppy disk drive, and more.

pN =)=)oti = Yo)| Oa
Richard Haskell «.
Now beginners, students, and experts can make the most. of their Apple computers with
this timely and informative guide. Gives a thorough introduction to BASIC programmingon -
EVaMe-Ve)o)i-mmerelaslel0i(-1ame-lale mmlaled(0(o(-\-mer- | Mmr-]a-t-- Mme)mmolcelele-latlaatiale nmm-\0(ela Mml-Mmea-]elal(or-mmm alo) gts)
financial management, games, math programs, and more, each applopnaly ie] atedi-T-S-ygerelig)
use or Self-instruction. _ :

ATARI” BASIC
Richard Haskell
Toy T-1 1 ol-\Volulom dale)a'ar- tale m-jalehy'c-ma-1-(e(-e-Mareh MmCom- lente linmny el(cwelcelele-liit-m gk =): <>) (Om Malls)
3 (Jobs hVar-1 (=) ome] ¢]olcel:[olan comm co)obre(onZam ecole le-latlealiare Metal |e](1mm Ut-t-1amComme-Te]eo)ham fale l-Tiat-vaye-)|
concepts and program their Ataris with ease and expertise in practically no time at all. Ideal
fo) mmcles iamol-tollalaliare m-lavem-leh-laler-teM o)gelele-lanliil-1e- Mm(alm olele) qoxelint-s-mexelailoli-1¢o MUUidam» ¢-lin) e)(21>
ITOK) Ce-1 (cto ohVam lato)Corel e-|elar-me-L¢-laMmiceliimmtal-merelat)elU)(-)me-m ale (-Le (el g-1-10B

ZB z +4 SS »

| a : ISBN O-13-448432-0

You might also like