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

Commodore 64 An Introduction To BASIC - Part 1

.

Uploaded by

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

Commodore 64 An Introduction To BASIC - Part 1

.

Uploaded by

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

AN INTRODUCTION

TO BASIC - PART 1
THE COMPREHENSIVE TEACH YOURSELF
PROGRAMMING SERIES

t commodore
COMPUTER
CONTENTS
Related Cassette
Subject Programs

Tracing: Tracking down errors. UNIT8PROG

Unit 9 Programmed Co/our; Normal and quote UNIT9QUIZ


screen modes; Screen representation of
conlrol characters; Use of position and colour
conlrol characters in progroms; The internal
clock Tl$.

InputofData: The INPUT command; UNIT10QUIZ


Relationships between programmer and user.

Flow-charts: Conditional commands in UNIT11 PROG


programs; Data validation; Flow-charts;
Glossaries; Program design.

Advanced Loop Control: The FOR UNIT12QUIZ


and NEXT commands; Program structure.

Sounds: The 64 voices; Control of pitch, SOUND DEMO, PIANO 103


volume and duration.

Unit 14 Data Reduction Programs: Terminating a HEADS


stream of data; Program robustness.

Computer Games: Reaction lime; the GET REACTION


command; the internal limer Tl; the RND
function; Structuring games of chance.

Afterword

Appendix A Mathematical aspects of 64: Expressions


Precision of working
Standard functions

Appendix B Answers to selected problems

Appendix C Common errors


Welcome to the COMMODORE 64 you. (Yes—there is a computer inside.) The level I

also a complete modern computer in its own right. activities, industrial or medical applications, or
Computers are extraordinarily versatile; more even games to amuse you..

so, in fact, than anything except a human. The 64, To have this power over your computer, to
for instance, can be switched to be a teaching make it into a fast, accurate obedient and willing
machine, a calculator, an aid to the handicapped, slave, you must be able to program the machine.
□ machine for financial records and stock control, Programming is the key to becoming a pilot.
a monitor for a patient in an intensive care unit, a This course isall about programming. It

computer used by engineers to design building-.,


power stations and aircraft. simple to transferto any other computer, large or
Computers and the systems they control are small.
The more programming you do, the easier it

the scenes. This trend will continue for most of our you. You do not need to know much abou!
lifetimes. The world is passing through a mathematics, but you will find it useful to have a
computer revolution, which will be as profound in quiet place to read, think and use the 64, and it is
its effects as the Industrial Revolution was in its
own time.
course. Don't rush!
The Computer Revolution can't be stopped; The course is split into fifteen 'units'. Each unit
but all of us can, if we like, have some influence will take you one or two solid evenings' work, on
on the way it goes. The world is becoming average. Most of the units include some reading,
divided into two sorts of people — the some practical work on the 64, some
programming, and a 'self-test' questionnaire to

based products, or they may hate computers, or Every unit contains some 'experiments' which you
both. Tney often make their views known, but should tick off as you do them.
without any real effect — they can't reach the When the units ask you questions, they
controls, and wouldn't know how to use them if generally give you spaces to write your answers.
they could.
Use them. Write with a soft pencil, and have a

of the whole revolution. They invent new types of rubbed out if you pass the 64 course on to
computers, and think up original and useful ways someone else. If your copy of the course already
of using them. The pilots have a heavy has the answers written in, go through it and
responsibility, since it rests on them to steer the erase them before you start studying.
world towards peace, freedom and plenty, and Programming is a tight-knit subject in which
□way from the nightmare society often depicted ideas depend closely on each other. Topics you
in Science Fiction.
learn about in earlier units are mentioned and
Whatsetsapartapilotfroma passenger? used in the later ones without any further
Only one thing: understanding the way a explanation. For example, you won't be able to
computer works. Of course there are different make head ortail of unit 10 unless you have read
levels of understanding. Most people understand and understood all of units 1 to 9. This makes it
how to use a "Space Invaders" machine even important that you follow the units in the order
though they couldn't explain the mechanism to they are given.
When you start work on a new unit, begin by
reading quickly right through it from beginning to
end. You won't get much of the detail, but you will
form an idea of the kind of topics you are going to
study.
Next, work through the unit in detail. Every
part matters, and the parts which seem the
hardest matter the most. Don't skip anything, but
fry to understand every point. When you feel
you've learned something, repeat it to yourself in
your own words. Don't be upset if you find you

or even go back to an earlier unit to clear up


some awkward point. This is quite usual with a
technical subject.
Programming is like playing a musical
instrument: you can only learn it by practice. You
must therefore complete all the programming
problems in the course. As soon as you can, start
making up and solving problems of your own.
WTien you complete the course, you'll be
able to use the 64 for many different purposes.
For instance, you can have it administer tests or
quizzes, you can make it play games which you
invent yourself, and you may find it useful for
sums and accounts. The games or other applica
tions can include coloured pictures to your own
design, and sounds to emphasise your meaning —
beautiful tunes or rude noises!
Programming is, however, a very large sub
ject, anano one could do it full justice in a single
course. After a while you will probably want to
take your programming further. You may, for
instance, be interested in solving more compli
cated problems, or in using the 64 as a con
troller for a model railway or private telephone
exchange. The second volume in thisseries,
entitled An Introduction to Basic: - Part 2 will
heipyou achieve these complex and
sophisticated aims.
Well — enough talk. It is time you started on
Unit 1. Good luck!
This unit helps you get started with your gentle steady pressure. Never use force, but look
COMMODORE 64. It explainsa number of rather carefully at the pin arrangements of the plugs and
ordinary matters; practical questions which often sockets before you try to join them.
raise serious problems when people buy their first The COMMODORE 64 is an extremely robust
computers. machine, but plugs and sockets do get worn or
To learn programming you need the right damaged if they are plugged and unplugged too
surroundings. Find a quiet comfortable place, many times. Once your 64 is set up, aim to leave it
and timetable yourself long periods (at least 2 undisturbed as long as you can.
hours) at a time of day when you are not too tired If your TV set does double duty as a broad
to concentrate. Do everything you possibly can to cast receiver, get an aerial switch unit which lets
avoid disturbance — put a notice on the door, you keep the 64 and the ordinary aerial both
take the telephone receiver off the hook, and tel I connected all the time.
everyone in your family that you are busy: there is Both the 64 and the TV can be run from a
nothing that makes programming more difficult single extension power lead with twin power
than constant interruptions!
If you have already installed your 64 and deciding how to arrange your home computer
used it, you can skip straight through to experi system.
ment 1.1. Otherwise, read quickly through the Now you are ready to switch on.
unit even if you know what it is all about; you may Turn on the TV, ana select a channel which is
still find it useful. not normally used for broadcast reception.
First, arrange your equipment and connect it to (For example, if your set is tuned to receive the BBC
the mains. The 64, power supply and cassette (or and ITV stations on channels 1,2,3 and 4, you
floppy disk drive if you have one) go on the desk or could use channel 5). The set wi II make a lot of
table in front of you, and the TV should be at least 6 noise, and you may turn down the sound.
feet (2 metres) away if it is a small one, or even Next, power up the 64, using the switch on the
further if it has a large screen. The pictures and texi side at the right. If all is well, the red power lamp
produced by the 64 are quite large enough to be will glow, but unless you are very lucky, the TV set
read at normal viewing distance, and you will find will still not show a picture.
— if you try it—that working with a screen close to Now go back to the TV, and adjust the tuning
yourface is very irritating and tiring. of the channel you have selected. The exact
The various units connect together as shown method of tuning varies according to the make of
in the diagram. the set, and is always explained in the manufac
All plugs should slide into their sockets with turer's instructions; but in most cases there is

Cartridge Modulctor Audio/Video Seriol Porl Cassette port User port Joystick, Paddle, On/Off Power
Slol QuipirtforTV Connector forPririler Lighfpen Switch Connector
and /or Disk Dnv¥
either a small knob or a screw associated with is measured in 'bytes', each of which can hold just
each channel. Sometimes the tuning controls are one symbol or character of information. The
hidden behind a small panel. If you have to use a more memory, the more complex the task the
screwdriver, don't poke it inside the set, as you machine can handle.
could easily get a nasty electric shock. If the number on the screen is different from
As you turn the tuning control, a picture will 38911, it is a sign that the COMMODORE 64 is
suddenly appear: broken. It must be returned to your dealer for
repair.
The third line tells you that the machine is now
ready to obey commands which you type on the
keyboard.
... * COMMODORE 64 BASIC V2 .... The next line displays a flashing square.
64K RAM SYSTEM 38911 BASIC BYTES FREE This is called the cursor. When you type a
READY command on the keyboard, the cursor shows you,
in advance, exactly where each character will be
displayed. For example, try the following:

PRINT 5 + 8
(This takes 10 key depressions:

PRINT 5 + 8 and press the

key. This is the targe key on the


right of the keyboard.) (Before you start typing,

The central square is blue with a light blue touch the Mm} key to make sure it is not locked
border. You may have to adjust the line hold and
down.) As you type each symbol, (except
frame hold controls to get a steady picture.
If you don't get this picture, or if the picture
comes up in black and white only, turn the 64 off ) it appears on the screen and the
For a few seconds and try again. cursor moves on by one place. The prime
If you have any difficulty, check the following
points: function of the ^mmm^g kev [s jo md^ the
9 Is the TV set working? Try it on ordinary computer carry out an instruction. In this instance
broadcast reception, and have it repaired if to print (that is to display) the result of adding
need be. 5 and 8!
• Is the 64 power light on? If not, check:
(a) That there is no general power failure
[b) That some other device (table-lamp or
hair-dryer) will run from the socket you
are using. If not, try changing the fuse in
the extension lead plug.
(c) That the fuse in the 64 power supply plug
is intact (try a new fuse).
[d) That the power supply is firmly plugged in
to the 64.
• Is the 64 properly connected to the aerial
socket on the TV?
If your system still doesn't work, take it back
to your dealer for advice and repair.

The message now on your screen consists of


a number of 'characters' including letters,
numbers and symbols such as *. These
characters are always the same size, and when
the screen is full it holds 1000 characters.
The first line on the screen identifies the
product: a BASIC system designed and manu
factured by Commodore Business Machines. The
'V2' is a version number which may change from
lime to time.
The message on the next line of the screen
tells you how much memory there is in your
machine. Every computer needs a 'memory' to
store details of the job it is doing for you. Memory
To do anything useful the COMMODORE 64

EXPERIMENT
must have a program. Programs are stored on
cassette tapes orfloppy disks, and this first
experiment will give you practice in loading a
irogram from a tape or disk into the 64. If you

H
have a cassette unit follow the instructions
immediately below. If, on the other hand, you are
fortunate enough to be equipped with a disk drive,
skip to Experiment 1.2, which is designed specially
foryou.

u-

Loading programs from tape


?
1. Make sure that the cassette unit is plugged into
the COMMODORE 64.
2. Press STOP on the cassette unit.
3. Open the holder on the cassette unit, take out
any tape which might be there already, and
put in the first of the two tapes provided with
the course. It is labelled TAPE 1. You can load
it either way up since both sides are the same. M-
In any case, the tape window should be facing
towards you. Close the holder. If it does not
close flat do not force it but make sure you
have put the tape in the right way.
H-
4. Press the REWIND key on the recorder. Watch
the cassette through the window, and if you
see it spinning, wait till it stops. Please make
£^
sure you are at the beginning of the tape.
w>
5. Press the STOP key on the recorder.
6. Now type the following message:

LOAD "TESTCARD" ^^BB


This takes 15 key strokes in all, counting " as a
single stroke. To produce the "symbol, you will
need to find one of the two

HUH keys (either will do) and hold il

down while you hit the key marked WM


R

Remember to release the HUHi key as


soon as (but not before) the " appears on the
screen.

You have to get the message right. Some very


common faults which you should avoid are:
I?
Typingwiththe IUU keydown.Youwillgeta
strange pattern with lines, hearts and spades,
and nothing will happen.

Using two single primes'' instead of a double


quote ".
The64willreply
?SYNTAX ERROR
READY.
and you can try the command again on the
next line.
Putting a space between " and T, TEST and back to your dealer for a check-up.
CARD, or D and". When the program is finally loaded, the
Typing the letters RETURN instead of using machine will say
READY.
Start the program by typing
Nothing will happen.
[4 key depressions]
Using digit 0 instead of letter O in the word
LOAD.

If you make a mistake, you can always 'rub

ouf bytappingthe HUB key. Each depression


erases one character and moves the cursor
back one place.
7. If you give the message correctly (or even if
you make a mistake in spelling the word
TESTCARD) the machine will reply
PRESS PLAY ON TAPE
giving a piclure like this:

■ -..COMMODORE 64 BASIC V2.


64<RAMSYSTeM38911 BASIC BYTES FREfc

READY

LOAD "TESTCARD"
PRESS PLAY ON TAPE

Press the PLAY key on the cassette unit. The


screen will go completely blank and you will see
the tape spin. After about half a minute the
message will come up:
FOUND TESTCARD
and the tape will slop. This means that the
cassette unit has wound the tape up to the
beginning of the section on which the TESTCARD
program is stored. To load the program, you
must hit the Commodore key, which is marked

and is near the bottom left-hand corner of


the keyboard. When you have pressed this key
the screen will go blank again. The program will
take about three minutes to be loaded.
If, after waiting all this time, the computer
comes up with the message
FOUND HANGMAN
this means that you misspelled the name
TESTCARD when you typed the original message.

Stop the computer by pressing flliii and go back


to step 1.
In most cases this procedure will work
perfectly. If it doesn't and the tape just runs on and
on without anything happening, it is possible that
your tape has been damaged in some way. Turn it
over and try loading the program from the other
side. If you still can't manage to load the
TESTCARD program, take the cassette and the 64
do) and hold it down while you hit the key
marked 2.

EXPERIMENT Remember to release the SHIFT key as soon as


you have typed the" (but not before!).
You have to get the message right. In particular,
• The first character is letter O (not digit zero).
O is found in the second line of keys between
land P.
• The fifth character is digit 1 (not letter I). 1 is at
the left of the top row ofkeys.
• The ninth character is also a digit 1.
• The thirteenth character is letter I. The right
key to use is between UandO in the second
row down.

Ifyouhita wrong key, usethe WM key to


rub out what you have written. Make sure
everythini
is right before you press
(For readers with disk drives)
Important: Read these instructions all the way standsforthe single large key
through before you follow any of them. on the right. Don'ttypethe letters RETURN.
1. Make sure that the disk drive is plugged into the If you type everything correctly, the disk drive
COMMODORE 64, and connected up to the will clatter and the red light will come on briefly,
mains electricity supply. At this stage c/on'/try only to go out again. The screen will display the
putting a disk into the machine! word READY. If you make a mistake, several
2. Switch on thedisk drive, using the switch at the things might happen:
back. Both the green and the red lights al the (a) Thescreendisplaysthemessage
front will come on. For a second or so, the drive ?SYNTAX ERROR
tests itself to make sure that it is working Just retype the message and try again,
correctly. If all is well the red light goes off, fbl Nothing
[b] Nothina happens at all. This is probably
leaving only the green one glowing. because you began the message with a
Ifthe red light doesn't turn itself off, or starts zero instead of the letter O. Type the
flashing, this is a sign that the disk drive may be

and ifthe trouble doesn't go away take it back to on. This could occur for two reasons:
yourdealerfor repair. et'fheryour message is wrong (for example,
3. Open the drive by pushing the lever in and up. "1" instead of "I")
(Seethediagram). orthe disk has been wrongly loaded.
Take the disk out, and switch both the
computer and the disk off. Then start the „
load process all over again,
(d) If you get the numbers 1,8, or 15 wrong, the
red I ignt may flash and you may get the
message ? DEVICE NOT PRESENT ERROR.
Remove the disk, switch everything off and
start again.
Let's suppose you get the correct reply to your
message.

The next stage is to type:

LOAD"TESTCARD",8
This takes 17 key depressions in all. Again, the
message has to be absolutely right, so check it
Push your program disk into the slot gently but carefully before you hit.
firmly, making sure that itgoes all the way in.
The machine responds to your message by
The white COMMODORE label should be searching the disk for the program caTled
uppermost, towards you and on the right. Press TESTCARD, and transmitting it into the 64. It tells
down the lever until it springs forward. Your disk you what it's doing, so eventually the screen will
ts now loaded. look like this:
4. Type the following message on the keyboard:

OPEN 1,8,15, "I" BjUBM


This takes 15 key strokes in all, counting "as a
single stroke. To produce the" symbol, you will
need to find one of the two shift keys (either will
(Readers with cassette recorders join here)
The first program shows you something of
.... COMMODORE 64 BASIC V2 ■
the range of colours, sounds and sprites the
64K RAM SYSTEM 38911 BASIC BYTES FREE
COMMODORE 64 con handle. It also lets you
READY
make fine adjustments to your TV set.
OPEN1,8,15,"I When you have watched TESTCARD for long
READY. enough, you can stop the program by pressing
LOAD"TESTCARD,"8
SEARCHING FOR TESTCARD When you hit this key (or whenever a
LOADING program stops for any reason) the screen shows
READY a message like

BREAK IN 560

The red light should be'off'. READY,


If this process doesn't work, there are three
likely reasons: The 560 in the example could be any number.
[a) You have loaded Ihe wrong disk. The reply BREAK doesn't mean the 64 is broken; it just tells
on the screen will be you that there has been a break in the sequence
SEARCHING FORTESTCARD of commands which makes up the program.
?FILE NOT FOUND ERROR Sometimes, when the TESTCARD program is
READY. stopped in the middle of a tune, the 64 goes on
and the red light will flash. Take out the disk, sounding the note it played last. You can stop the
switch everything off, and start all over
again. note playing by holding down the key and
[b) You have spelled TESTCARD wrong (or
perhaps put a space between TEST and pressing mfjym which is the key near the
CARD). The red light flashes, and the screen top right of the keyboard.
shows something like.
SEARCHING FOR TESTCRAD
?FILE NOT FOUND ERROR
READY. Experiment 1.2 Completed
Retype the message and try again:

LOAD"TESTCARD",8
[c) You have misspelled the word LOAD (or
perhaps left out the double quote signs).
The machine replies
?SYNTAX ERROR
or ?TYPE MISMATCH ERROR
Typethe message correctly, and try it again.
Once you get used to the loading process, you
can work through it in just a few seconds. If you
have difficulty, look at the screen and decide
exactly where you are going wrong. Common
errors are:

Mixing up letter O and I with digits 0 and 1


Using two single'' instead of a double quote"
Putting extra spaces into words like LOAD,
OPEN or TESTCARD
Before going on, we should draw your altention
to some important points about handling disks:
Never switch the disk drive on or offlrthere is
a disk inside it. Always load offer switching
on, and unload before switching off.
• Handle the disks as little as possible; keep
them away from dust, heat, cold or damp, and
never touch the surface of the disk which
shows through the slot in the paper cover.
When the program is loaded, start it by typing

(4 key depressions).
EXPERIMENT .... COMMODORE 64 BASIC V2 • • - •
64K RAM SYSTEM 38911 BASIC BYTES FREE

READY

OPEN1,8,15,"I"
READY
LOAD"HANGMAN,"8

[for disk]

When the program is loaded and the READY,


message comes up,
Experiment 1.4 is a word-guessing game
RfTUHN
designed to help you get the feel of the keyboard.
The program is called HANGMAN. You can loac and the game will start. If you don't know how to
it either from cassette tape or disk, using the play, just keep try ing letters and watch (and listen)
commands. to what happens. You will quickly pick up the idea.
RETURN
Play the game as long as you like, and use
LOAD "HANGMAN" |fortape] the opportunity to get accustomed to using the
letters on the keyboard.
i
RfTJRN
OPEN 1,8,15, "1" (for disk; Notefordiskusers:lfyouhovealreadyruna
R.11HN
program (like TESTCARD) and have notturned the
LOAD"HANGMAN",8 macnine off, you may om/Zthe OPEN
Thescreen displays look like this COMMAND.

.... COMMODORE 64 BASiC V2 . . . •


Experiment T.3 Completed
64KRAM SYSTEM 38911 BASIC BYTES FR[E

READY

LOAD "HANGMAN"
PRESS PLAY ON TAPE

[for tape]

To ensure the HANGMAN program is

loaded you will have to press the iSi keytwice.


Once to skip over TESTCARD and once to load
HANGMAN.
Welcome back. This unit is about the

EXPERIMENT
COMMODORE 64's keyboard, and tells you
how to use it to write messages and draw
pictures on the screen.
If you have ever used an ordinary typewriter,
the computer keyboard will look familiar. You
will find the letters, the numbers and most of the
signs in their accustomed places, and there are
the usual shift and shift lock keys—although they
work a little differently on the 64.
On the other hand, don't be put off if you
have never done any typing. You will need a little
more time to get used to the 64' keyboard, but
that is all the difference it makes.
For this unit only, please don't use the

key unless we say you should. As


you saw in Unit 1, this key is the one which mokes
me machine actuolly do something for you, such
as loading a program or adding up some The 66 keys on the keyboard are divided into
numbers. At present, just to use the screen, you two categories:
don't need the computer's help. If you do press A 50 Symbol keys, which make the 64 draw
characters on the screen.
, the 64 will only try to obey the # 16 Function keys, which control the way the
message or picture you have just typed, characters are drawn.
misunderstand it and spoil its appearance. The function keys are:
Another symbol you should avoid just now is
I SHIFT ■ £E
(he double quote mark {"). This sign has a special
meaning, and alters the way the screen reacts to
CRSfilCRSRl SHIFT
many ofthe other keys on the keyboard. If a
double quote is showing on the screen it can be
f 8
much more difficult to draw useful pictures. You
will learn all about this character in a later unit; but
for now, keep off I The ten symbol keys marked 1 to 0 also have
You may find this list of "don'ts" quite certain control functions.
alarming. Here is another one: Don't Worry! Compare the keyboard with the chart
Unlike computers in Science Fiction, the 64 has below, and identify the various control keys.
no 'self destrucf command. It is absolutely
impossible to damage the machine by typing on Press the |UU several times and note that it has
the keyboard. Some patterns of characters which two positions — up and down. Finally, make
sure that it is in the 'up' position.
contain " or ^_m^^ will make it behave
quite strangely, and a few sequences, which you
might hit by chance if you are careless, will stop the
computer from responding to you at all. These
troubles are only temporary: you can a/ways cure
them by switching the computer off for 30
seconds, and then on again.

I I I I I ' I I I I I 1*1
» '■ I I I I I I
I I I I I I I I I
111111111
SHIFT ■ CRSfl ■ CRSft
Now start your machine in the normal way.
Just below the READY, message you will see the
;■; flashing cursor. EXPERIMENT

The COMMpDORE 64 has some 50


In this experiment we examine how the cursor symbol keys, but it can display a much larger
moves when symbols are drawn on the screen. number of different symbols. They include

the next typed character will appear. Type a few symbols, and a wide range of'graphics' or
letters, and watch the cursor move across the simple shapes which canibe combined to make
screen. Notice that every character rep/aces the up different pictures. All these different
cursor, which then shifts to the next position. characters can be selected by using either
Now fill up the whole line with letters, until the
cursor is at the extreme right of the blue area. ofthetwo HUMP keys (they are connected
Type one more letter and watch whal happens: together inside the ComputerLand the special
the cursor jumps to the beginning of the nexl line,
oil by Itself. 'Commodore' key labelled
Before going on, count the number of letters
across the screen, and fill in the box: Restart your machine and type the line
There are spaces for characters in «-l 234 56 7890 +-EQWERTYU IOP@
* t ASDFGHJKLr;=Z
each line on the screen. (These are all the symbol keys in the top
Next, type some more lines, and keep going three rows, and Z in the bottom row. Be careful
until you reach the bottom line of the screen. Count not to hit any of the function keys as you type!)
the number of lines showing and write the number
in the box below. Remember to include the blank
lines above and below the message:

38911 BYTES FREE


There ore lines in a screenful of
characters.

Now fill in the last line until the cursor


reaches the lower right-hand corner of the screen.
Type one more character and watch the cursor.
The whole screen moves up and the cursor moves
lo the beginning of the next blank line which
appears at the bottom. Any blank lines are
bought at the expense of the top-most ones,
which have now vanished. The top lines have
gone for good, and there is no way of bringing
them back, unless copies are stored somewhere Now hold one of the ■■!■ keys down
else. and type the line again. You will get an almost
Fill in a few more lines, and confirm that the completely different line of symbols (including a ",
system always gives you room at the bottom of but this will not trouble you if you follow the
the screen for more text. instructions). Copy the symbols into the second
row of the table below, and notice how some of
the graphics (for example those on U and I) fit
Experiment 2.1 Completed together. If your TV picture isa bit smudged it may
help you to look at the signs embossed on the
keys themselves.
SYMBOL

SYMBOL XCVBNM, . /

Notice how the graphic symbols usually reach


the edges of the little squares they occupy, so that Press Ui and ^ff^ down together.
they can be made to touch each other. Many of the capitals on the screen will change
Next, type the line yet a third time, but this into lower-case letters. Press the keys together
again and the capitals come back. In general,
Hme holding down the KH key. Many of the you can use either a full set of graphics, or a
signs are different again. Copy the line into the restricted set and lower-case letters, but not both
third row of the table. at the same time. The use of small letters will be
To examine the other graphics, repeat the explained in the second volume of this course.
experiment with the line
XCVBNM.,/
followed by 31 spaces, which will take you to the
edge of the screen.
Fill up the last line with spaces.
Note and remember that the digit 0 is different
from letter 'O'. You should always use the 0 to
show that you mean the number, not the letter.

k.

Experiment 2.2 Completed


k.

T1l
k.

i_

k.

k_

IL.

1_
anything underneath it.

EXPERIMENT
Try moving the cursor to the first * on the
right, and then putting in four = signs. The top line
becomes
= = = = COMMODORE 64 BASIC V2 = = = =

COMMODORi 64BASiCV2
64K RAM SYSMM 38911 BASIC RVTFSf RLL
READY

So far you have been limited to displaying


characters strictly in sequence, left-to-right and
from the top down. This is a tedious way to draw a
picture, and it would be far more convenient if
you could place your text and graphic symbols ai If you hold the KB key down continuously,
any position you chose. then after a short pause the cursor moves by itself
This can be done with the cursor control keys. at a rate of about 10 places a second, line after
line. This is useful to move around quickly.
of which there are three
When the 191 key is struck while '
When you type UliiU by itself, it moves the is held down, the cursor moves backwards. When
cursor back 'home', which is the top left-hand it reaches the beginning of one line it moves up to
corner of the screen. Restart your machine (just in the end of the previous one.
case the previous experiment left it in a funny Next try going back to the first line, and
mood) and strike this key. You will see the cursor changing the = signs back to *s.
move to the * at the top left of the screen. The Move the cursor down to the bottom line of
* remains visible because the cursor is the screen ond watch what happens when you
transparent; but if you type another character (or move past the end of the line: the whole screen
moves up just as if you had added another
character.
Now go bock 'home' and try to move the
cursor backwards. The screen does nof move
down as you might have expected; nothing
happens at all, and the cursor stays in the same
place.

The HSjH key moves the cursor up or down


a whole line at a time. Try some experiments with
it, and make sure you understand how it works.
Next, fill up the screen with a few characters

and graphics,and then press UiUJ whileholding


down the shift key. The cursor moves home and
the screen is cleared, giving you a fresh screen to
a space) the symbol under the cursor is replaced work on.
by the new one. Try putting an = instead of the *. Fill in the following table:
Type = three more times, giving you
= = = - COMMODORE 64 BASIC V2 • * * *
Key ., , ., Effect „, ,
as the top line of the screen. No shift Shift
You may now want to alter the * * * * on
1■ home!
CLH 1 Moves cursor
the right to = = = =, so as to keep the line
home
symmetrical. If you move the cursor along by
typing spaces, you will rub out the title in the Moves cursor 1
centre of the line. The correct way is to use the place backwards
1
key. Every time you hit this key, the cursor 1 CRSR 1
B ■>- Bl
moves one place right, but without spoiling
Now practice making drawings on the screen Now draw some playing cards, with curved
using the graphics symbols and cursor control corners and the right symbols (we suggest you
keys. Start with some simple geometrical shapes keep to black cards worth 10 or less).
like squares, oblongs, triangles and small circles. Finally, if your artistic talent is up to it, trying
If you make a mistake, move the cursor back and something like an animal, a space-ship or a
type the right character. 'Space' will get rid of human face.
characters which are in the wrong place.
Plan your picture first, using the grid below.
When you have got the feel of using the
graphics,drawabox,likethis,withyournameinit.

CHRIS
1
BLOGGS

Experiment 2.3 Completed


changing AUSTRIA into AUSTRALIA.

EXPERIMENT type
Clear the screen ( ■MMI and

AUSTRIA
Move the cursor back over the I.

Hold down the shift key and strike I!


twice. Each time the IA moves one place to the
right. The cursor stays in the same place, so after
two moves you get
-,-— 2 spaces

AUSTR-

cursor '

Now finish by filling in AL. Move the cursor


past the end of the word.
Everyone makes mistakes when typing. If
you get a single letter wrong in the middle of a To practise using the lilfl key, clear the
word, you can correct it with the cursor control. screen, fill it up with the list of words on the left,
For example, if you type AUSTRAPIA when you and then change each one to the corresponding
mean AUSTRALIA, you can move the cursor back word on the right:
over the P and change it to an L. Try it! HOTEL MOTEL
Unfortunately, if you get the wrong number MICROPHONE MICROCOMPUTER
of letters (too few or too many} this method won'1 PLYWOOD WOOD
help you. A more powerful facility is provided by ANGLE ANGEL
CHAP CHEAP
the 110 key, which lets you insert or remove WRITER WRITTEN
characters from the screen. ACTOR AUTHOR
BALL BARREL
When you type litil by itself, it rubs out the WIRE REWIRE
character to the left of the cursor and shuffles all FLOWER FLOUR
the other characters on the line one place left so MOON MORON
as to fill in the empty space. PIDGIN PIGEON
For example, suppose that you mistakenly TACT TACIT
type INXDIA when you mean INDIA. You want to HORSE HOARSE
get rid of the X, so put the cursor over the D, and WING WARRING
TAXI TAX
. ,TheXdisappears,andDIAallmoveup RED READY
to the left, leaving INDIA (without a space in the MERRY MERCURY
middle). JOVE JUPITER
PAL PASCAL
BACK BASIC
corrections, as follows: JAVA JAMAICA
CHAINA to CHINA And now change them all back again.
EEGYPT to EGYPT
FINLANDIA to FINLAND
AUSTRALIA to AUSTRIA Experiment 2.4 Completed
In practice, the most common use of the 1!
key is to get rid of the character or characters you
have just typed. The key will remove the last
symbol and reposition the cursor, all in one
movement. You will soon get accustomed to hitting
whenever you make a typing mistake.

The other function of the liitf key can be The Unit 2 program is entitled SPEEDTYPE. H
called up by typing it as a shifted character: that helps you to get familiar with the keyboard.
Load it from your cassette recorder by typing
is, holding down the ^jgUB |<ey when MUM LOAD "SPEEDTYPE"
is struck. This function is used to insertspaces into or from your disk drive by typing
Ihe middle of words or lines. These spaces can OPEN 1,8,15, T
then be filled up with characters in the ordinary LOAD"SPEEDTYPE",8
way. start it with the RUN command and practise
Try the following example, which involves using it as much as you feel is necessary.
The COMMODORE 64 is a colour

EXPERIMENT
computer. This unit introduces you to some of
the ways you can get the machine todraw
many-coloured pictures on your TV screen.
If your TV set is a black-and-white model, do
not expect brilliant results from Unit 3! You should
work through it just the same.

Use the TESTCARD program (unit 1) to make


sure that your TV receiver is properly adjusted.

Stop the program by holding down (jjjjj and

You will see that the cursor at this stage is light


grey. Now the cursor can change colour, and as
well as telling you where the next symbol will be
placed, it also indicates what colour it is going to

be.Trytypingasequenceof 1^1 symbols{


and I keys) and note that they appear in grey,
which is the present colour of the cursor.
[Where a character has a lot of fine detail the
apparent colour may not always be correct. This
is a consequence of using an ordinary TV set,
which has a narrow RF bandwidth. The difficulty
can be cured by buying a more expensive colour
monitor, but it is hardly worth it unless you plan to
display a great deal of text in different colours.]

Figure 1

blue

green

black

yellow
The colour of the cursor can be changed ai

EXPERIMENT
any time by typing one of the eight colour keys

while holding down the ■HHi key. The colour


keys are marked 1 to 8, and also carry
abbreviations of the colours they control.

Mold down HHHB and strike the colour


keys in succession.
When you hit 1 (BLK) the cursor changes to
black.
When you hit2(WHT) the cursor turns whife.
The other keys change the cursor to red,
cyan, purple, green, blue and yellow
respectively. When the cursor is blue, it is
invisible against the blue background: itjusi
seems todisappear.
You can get another range of eight colours
You have seen how the 64 looks afterthe
by using the l23 key instead of ^m^
colours of individual symbols on the screen. It
ley are the less brilliant pastel shades:
can also control the shades of the outer frame
and the background against which the symbols
and BLK gives orange
appear. The machine doesn't have any
dedicated keys to control these colours, and the
and WHT gives brown
way to change them is to give special
commands.
and RED gives light red
Type POKE 53280,0. Check it carefully,
and CYN gives dark grey
correct it if necessary, and then hitthe
key. The frame of the TV screen immediately
and PURgives medium grey
turns black.
This special command has three parts:
and GRN gives light green
POKE: This is called a keyword.
53280: This is called an address. It identifies
and BLU gives light blue
that part of the 64 which looks after
the colour of the frame. Any special
: and YEL gives lightgrey-the 'usual'
command to change the frame
colour otthe cursor.
colour must always refer to this
Now try making some coloured pictures. A
address.
good way to start is to make some coloured bars
0 : This is a colourcode, which means
"black".
of various lengths. Use the 1 I graphic)
To select anotherframe colour, you simply
and U) to build up each bar. For example, to
use the right code. The code table is:
make a red bar 5 symbols long, first hold down

Colour Black White Red Cyan_


and type 3 (RED); this will change the
Code
cursor to red. Then hold down hSf and strike
Ufive times. Colour I _ Purple Green Blue Yellow
When you have got the feel of the colour Code ;
keys, try drawing an "election results chart" as
shown in Figure 1. Keep the lettering black to Colour Orange Brown L. Red D.Grey
emphasise the colours of the bars. Code

Colour M. Grey L. Green L. Blue L Grey


Code 1
Experiment 3.1 Completed

If you want a yellow frame, you type

POKE 53280,7
Similarly,

POKE 53280,11
will give you a dark grey frame.
It is worth noting that the code number for Choosea few colour combinations, POKE
each of the brighter colours is one less than the them with the special commands, and find one
number on the Key used to choose that colour
for the cursor. (For instance, the PUR key is
marked "5", and the code for purple is 4). The seem to respond, you can always get the cursor
pastel colour codes are each seven more than
the key numbers.

The colour of the symbol background is


controlled in exactly the same way, using
Experiment3.2 Completed
address 53281. To get a light grey background
with a purple frame you'dtype:

POKE 53280 A

POKE 53281,11
The best way to fill up the screen with blocks
of colour is to use reversed spaces. The space bar
EXPERIMENT is a 'repeating' key, and if you hold it down it will
generate a sequence of spaces at about 10 per
second.
Drawing national flags makes a good way
of getting practice in the use of colour. The
easiest type of flag to reproduce is one with hori
zontal stripes, such as that of The Sudan.

purple

You may have noticed some strange gaps in


the graphics characters; for instance we have

but not B 1; we have v , and 1__5 bui

not l^Hl or HWJ . Furthermore it seems impos


sible to fill a complete square with colour and To paint this flag, set the frame to a suitable
therefore to build up large areas of the same hue. colour (say black) and the background colour to
The reverse field facility comes to our help. the same as the bottom right hand corner of the
When a character is displayed in reverse flag (green). This is done by
field, the colours of the characters and of its
background are swapped. Try the following POKE 53280,0
experiment:
POKE 53281,5
Restart the COMMODORE 64, select white
as the cursor colour, and type a few characters, Next move the cursor home, select purple and
including
reverse mode (hold down ^m^ ancj type PUR
EIH, V I , I ^ and a space. Now hold down and then RVS ON). Then hold down the space bar
and fill up 8 lines with reversed purple spaces.
and the 9 key (also labelled RVS ON). Next, select yellow and fill up 9 lines with
yellow reversed spaces.
Then releaseWH and type a few more charac Lastly, change the colour to green. This will
ters. They will appear in blue on a white back make the cursor disappear and leave an 8-iine
ground, instead of white on blue. In particular green area at the bottom of the flag.
It is important to set the background colour
comes out as t^\ , y and | _j are to oneofthe colours which appear on the picture,
otherwise you will be unable to hide the cursor
changed to L^fl and IkJ , and a space when the drawing is complete. Likewise the
appears as a solid block of white. We say the 64 frame colour should be differentfrom any colour
is in reverse mode. which appears in the flag itself.
To bring the following characters back to
When you have mastered horizontal flags,
normal mode, hold down WlVand type the 0 try one with vertical stripes, such as Italy. Those
key (labelled RVS OFF). with crosses (Switzerland or Iceland) are also
The cursor does not show whether the worth drawing.
machine is reverse or normal mode. If you are Even more difficult are flags with diagonal
using many reversed symbols it is easy to forget, elements such as Czechoslovakia. The
and to be in some doubt as to how the next parts of the flag near the sloping lines musl
character will appear. This difficulty can be
resolved in two ways: be made with the graphics ,^fl or ^^
(a) Type the next character and look at it. If it is
wrong, erase it, change the mode, and try suitably reversed if necessary. If you think about it
again. you'll see that the background colour must be
[b) Type the RVS ON or RVS OFF key, as chosen so that it is on one side of every sloping
appropriate, before you type the next symbol. line. In the case of the Czechoslovakian flag, a
If the machine is already in the right mode this suitable background colour is blue; red -say-
will not make any difference. wouldn't do because there would be no way of
green white red

yellow
ITALY TANZANIA

21

red

white

SWITZERLAND

white white

red

white white

ST. GEORGE ST. ANDREW

1 I white
blue blue
] blue r

white
red

blue blue

white' ICELAND whHe GREECE


drawing a blue and white element on the upper
diagonal.
If a flag has a diagonal bar right across it II EXPERIMENT 1

[_ 3-4J
[such as the flag of Tanzania) it is better to use
only 25 of the 40 columns, and to fill in the rest i
with the 'frame' colour. Assuming a black frame,
atypical line halfway down the Tanzanian flag
would be entered as:

andGRN,

andisH* , and£,
CTRL cm
and BLACK,
22
SHIFT SPACE I SPACE
and£,
Draw Ihe best coloured picture you can,
using the full scope of the COMMODORE 64.
cm
You may find it useful to plan your picture first,
and BLUE, using a sheet of squared paper and some
SPACF SPAC!
coloured crayons.
and£,
SPACE
andBLK, Experiment 3.4 Completed

The commas as well as the word "and"


shown above are simply to show you the differenl TheprogramwhichgoeswithUnit3isaquiz,
and can be loaded by typing
should, of course, not actually be used when
drawing Ihe flag.
LOAD "UNIT3QUIZ"
If you feel sufficiently patriotic, you might try
the flags of St. Andrew, St. David, St. George or or

St. Patrick. The Union Jack is formidably difficult


todraw (even without a computer) and could well OPEN1,8,15,"I"
be omitted. LOAD"UNIT3QUIZ",8

Experiment3.3 Completed
J
In the hrsl three units of th& cOurtt we have

EXPERIMENT
cantenlrated almost wholly on ihe
COMMODORE 64 keyboard, and on using it to
display lex* and pai nl pictures on 1h* TV £Cr*tn.
Thi s is sound oreparolion forth* ri*>rt port oFthe
course, whftre we look oi somt of ihe functions the
64 con do an your behalf.
As you ajready knOwr ihe 64 will dc- various
inbs when it is conwr"nd™ 1o dfr $o The neces
sary commands are wrrffcn in QASbC, a pimple
nrd popular cornpuier nnyfcjriQP t r^f lieviswl by
Kemeny and Kurtz oi the Dorlmouih Collegej
USA_ BA9Chas fts own rule* of grommar just like
any other lanq iu« bulyOti moy Im glad ^ hear
mal ihey are simpTc to ltarflr and rhat yuu will
easily mem on s6 tWn throuf^i pracMce, i^iihout
25 any special effort
Ev*f> BASIC command atuns wiih g 'keyword1
s«ch as LOAD of POKE Of PfflNT.Thrs tells Hw
computer wholtyp* oJ«rtw<ind is mea^^ the fflosl us*lul on<f lle^ible com
mands it PRINT lr moketihe compuler work au*
Similarly,, tilery c^nvmnd ends with [Kb
Something for you ond display rhn reaull on ihe
[ dd b
up iyi ny 16A5IC □oftfiKXjm relied an
|F Ihg keyword it the fir jt word on me linex bdl p reel ly did pnmthe
OH roll* of pope'.
l d in three
1$ o k iftd- of filorting gun "Wowgc
g g

and do if'_ For j i(yc«j1>pe

INftnl we discuss fhe features of me command


which hove thown up ir Jhe examples- and fina lly;
weexorniriesome new PRINT cemmondi, and Hy
the actual loading vtcrts vhen if
10 pffCd^Cf wtiQf me cenputftr w 11 do wLth mem.
key is pressed. Thegth**" interpretation of
The cmsw*r& con heihecttd by using iKe
is dltOJ&sed in the nthJ unit, bul computer iImII
by typing rhese zq*- mends.
hfirt i« a ^hori p^avSfr^-
If frit keyword Ln a BASIC command hot a
b front of it —iuchog each one with M~ic ^■■■I^B ksy B
qei the cc»m mend a right, using ihe cursor confnsl
ku-c lo correel youf typing iF need be_ Wake a
3PRINT5+7
carefiri note of the responses m the boxes
thenthe yg iiravuled Ihe f irsl twa boxes are a Ireody f i lied in
the command^ buMOSWe il away for later usa_ aryou

ki this umiP w* <on-:enlrate on the Fret inter


pretation Our commends wiJI nol have numbers PRIhJTW9 999

in RFADT.
for me 64 lo immediore action.

PPIfJTrJMELLOrJ HEUO

READY.

PftlMT—5i

PRINTS ■ 4 h4

PRINTS
L
rake awoy multiply and divide Thfl signs
mean multiplication
tiplic and
PRINT 37/7 respectively |llyauare irriftf«t*d in using
thecompuler lap moft advontfld mamo-
4naaics cakulalioriE, you wth bsglad
that hisseewprassicms can
as /du nocd. Thuycan
PRINT "COlMMODOftfc
all thaspcaal runctiois vuuwOuld txpeO >0
64 COMPUTED fill
advirtd to look tr Appends AF^riiCh
txira unih-d«si^A«d special fo
PBINTtOMMODOftEM A ihrtg is a^y s#ciu*ncfto+
q _The PRINT
simply regurg.naies.sijGh
oS il -rfiigiveiv wimoyl hryinfl 1a

PPINT15 were

"RABBITS-DOG'1, "CAT". "FISH". "3 + 5"


ond "LIONS'1,
Ncili<etlicifJr3 I y i£ jin^nri expneaa ion, even
PRINT 3j5 Ihaugh il looks. Me ooe, il is enclosed m
Quotes., io il musl be a string
It you worn la displays stringr but forget Ta
Eulquotes round it, you wjII probably gel 0
ilfhovqh von might sometimas ge^ome-
PfllHT"RAEBrrr/1DOG" thinqelse).
TKb PPtNT commend can handls two o*
mofe quantities or stri ngs aHhe some time If
the two are separated by cummasj l> i me
scoond ntsult is fipated well aaoss ihe
PRINT "OOV'FISH" scrfiftfi (|u*l o^er a quarter) IF a semicalan is
U£4dj Ihfl itpdrrtlirtrt IK IKS Irt Bfirii oul^tf,
SFrirgAnre imF separaled a1 all (hSis is kow
we gei riCflTfIShH. Numbers displc^ej by
hpeefn ro be MparoteJ because
FRIUT"3-5" number is ol ways preoaded by a
>i i (af by Q - rjn if it is negalivel and
qhway* fa llcwed hy another space llyour
rerardsi cfcon^ Iihaw this; very clearly, repeal
Jhe command
PRINT 29-1 V'LIONS"

and 'iroasurn-'ih* result by iiKHving ihe


curses over it.
PRWTl,a;3pl 3. Nt>:i we look 01 spates inside i
jlfiCtf. The keywerfd PRINT mMSP I
its lefle^ must not be ^epfjrailed by
_. and any spuce which i i ibrddu
Sh belongs to thot shying and will fae
Befort r*adi ng <f\. 4+udy your nafces carefully Omerwiser spaced behnveen
and SM hiOwnXiny difterent leat-jres af PRMT or nu nibers ore i gnarad. Thus
you can pick Our. One common aspHcf dP rti*
answBraisil*riheyarefoHowHd by READY, but PRIN1 J +5;7: 3
thps is tnrt cJany command obeyed directly fr
the screen, ao it hardly counts as a special wiM give esuidSy Ihe same result
property d PBffJT1
Here I lie* i are the most important points a-f
the PRINT commond;
1. T hfr convrw nd tan handle both snjmib«r3 spaces !n commands ate
S^jnajs.and il does so- in differ*™1 woyi= ignored everywhere except mside ke^or
A jiLmbercan either b* giv*ri*Kplic:itly ( ond m EilnngEi — is gerwfol ly 1rue lar tne
999\ or in thefarm of an euppisUOni or J'i
which the com putar wohVb oul The II you make a mistake tn the keyword
sians in our trials wens 3 ^ 4 ^ 5H 5*7, or if you supply an expression which doe?nH1
so make sense (suoh as ^"* * ■ 1I-5 computer
you r command wilh lhe comment Ched< ycujr ons^ers on Ihe.a4_ Hyow hove
iy mJstofceir and conJl see why you'vs
SYNTAX ERGO* made ihem, go back a nd repeat the whole
e*pen menfr untih me bdeas become clear m your
Thr* n computer jargon fee saying that you jTiind
hart broken ihf rules of BASIC Pwre is
Nole Ihpl the 64 always carries out calcu In
nothing far it bfrt to rarretl me-command
involving multiplication and dwisicn before
oncj Iry ^ again.
i and subtraction. As examples:
Now run mrough the following Usl o'PHNT
commands and predict whal Wit 64 will do #iHi
PRINT 5+2*7 will give 19
sach one_ Sli-Hv ftow the rt^ufrs will he
j

hor»drclonri bother and


m rhemitlves- On
writing doivri READV.
Some Fh
deliberate
11

Command ycKHrprBdJcTion COMMODORE 64% mult

PPINTE-5

PfllNTOHDeAR"

PRINT ENOUGH

PRINT "l*/^

PRIUT3,J7

PftlMT^i?^ 2:2*2.2/7

PRIMT "CLOUD", "BURSr'

PRIhJTS-7

PRINT"18", "MlCF"

FPINT63**?

PRINT-1s-3i-a

Experiment 4 1 Completed
When the final whistle blows, use the score-
board to display the names of the teams

EXPERIMENT together with the (latest) numbers inside the


boxes, thus:

BOLTON UNITED

KELSO CITY

In this example the boxes are variables; the


numbers in the boxes serve to remember the
current state of play, and change from time to
h'me as necessary; but the labels remain the same
for the duration of the match. The instructions for
usinq them are very simple, but foolproof.

If a computer could only do one command a1 38911 bytes-remember?) is a bit like a large
a time, it would not be specially valuable to blackboard. When the machine is first switched on
anyone. At best, it would be about as good as a' the board is wiped completely clean. Then,
(non-programmable) calculator. Most useful whenever a variable is first mentioned the
computer jobs consist of whole sequences of computer "draws a box" by setting aside part of
commands, controlled by sets of instructions the memory, and labels it with a name chosen by
called "programs". As the commands in the the human user. Then it "writes a number in the
sequence are obeyed, there has to be some way box" by storing the appropriate value in the
of 'keeping the score', of remembering how far memory which has been set aside.
me job has gone, and of passing the results of one The BASIC command which makes the com
command on to the next. The memory which puter do all this has the keyword LET. Let's
serves to link commands is provided in the form examine such a command in detail:
of variables.
Before discussing BASIC variables, we shall LETX = 5
give you a human analogy. Suppose you are the
score-keeper at a football match. Your instruc Here,thevariablenameisX.The64willset
tions could be as follows: up a box called X (if it has not already done so)
and will put the number 5 inside it. If a variable X
Before the match starts, draw two boxes, already exists, then no more space is set aside;
label them with the names of the teams, and me 5 merely rep/aces the previous value. Study
write zeros inside them, thus: me following cases:

X does not exist X already exists


(Case 1) (Case 2)

BOLTON KELSO Before (Memory empty)


UNITED CITY

Whenever either side scores a goal, replace


the most recently written number in the
corresponding box by the same numbers, ResultofLETX=5
plus one. Rub out (or cross out) the old
number.
Part-way through the match, the state could
When you give a LET command, the computer
just says

READY.

There is no evidence on the screen that the


machine has done anything at all. Fortunately, we
BOLTON KELSO are helped by the PRINT command, which
UNITED CITY displays the value of a variable whenever it is
mentioned by name. Try the following sequence
of commands:
r
Now look at the following sequences and
Your results predict the outcome of the PRINT statement in
each case:
LETZ= 14
LETAA= 15
PRINT Z
LETB=33-AA
LETZ = 31
PRINT AA,B r
PRINT Z
LET D = 3

LETE=D*D+7
If you keep the right order, the first value of Z
lobe printed will be 14, and the second, 31. The
LETF=E-D
first LET command both creates a variable called
Z, and gives it the value 14; the second one
PRINT F;E;D
29 merely changes its value to 31.
At this stage we hove to give you a few LETF=4
simple rules about variables and their names.
There are two kinds of variables in BASIC: LETF=F+1

• Numeric variables, for storing numbers. PRINT F I


• String variables, for storing strings (e.g. words Did you get the last one right? Some people
or phrases). might find it a bit tricky.
There is no limit to the number of different
The choice of names for variables is quite values a variable can hold, as long as it only
restricted. A numeric variable can be called by a holds one at a time. A command like
single letter, a letter followed by a digit, or by two
letters. Some examples of possible names for LETF =
numeric variables are
means: First work out the expression (by taking
A,X,Z,B5,TX,PQ the value of F and adding 1)
Then put the result in box F, replacing the
Names for string variables always end in previous value.
the $ sign, but otherwise the rules for string
variables are the same as for numeric variables. In other words, the command makes the 64
Examples are add J to the current value of F.
The signs which allow us to combine numbers
C$, Z$, P7$, DB$ in various ways are called arithmetic operators.
They are +, -, *and/. BASIC also allows strings
To show the use of string variables, try typing to be manipulated in various ways by using string
operators. Only one of them combines two
LET T$= "GOOD " strings; it is called "concatenation" and is written
as a + sign. The operator simply attaches the
PRINT T$; "MORNING" second string to the end of the first, so that

The value which follows the = sign in a LET "DOG" + "ROSE" = "DOGROSE"
command doesn't need to be a simple number or
string; it may be an expression, and furthermore it Look at the following sequence of commands,
can use the current values of variables by and predict the outcome of the PRINTs. Then try
referring lo their names. For example, look at the the sequence on the computer; remember to put a
following sequence of commands: space before each of the closing quotes:

LETQ = 5 LETB$="DOG

LETS = Q+3 LETC$="BITES

The first one creates a variable called Q (it is LET D$="MAN


a number variable because of its name) and sets
its value to 5. The second one makes a variable LETE$=B$+C$+D$
called S. It then takes the value of Q, adds 3, and
puts the result into S. To illustrate the point, try LETF$=D$+C$+B$
running these two commands, and inspect the I
result by typing: PRINT E$

PRINT Q; S PRINT F$
PRINT and LET are the two most frequently
used commands in BASIC. It is worth remember
ing that when you use the 64 you are allowed to
replace the word PRINT by a single symbol: the
query (?). LET can be omitted altogether. A valid
sequence is

B=17

The program which comes with this unit is


designed to give you plenty of practice with PRINT
and LET commands. It is called UNIT4DRILL.

You can stop the program when you are sure


you fully understand the use of numeric and string
variables.

Experiment4.2 Completed
The computer is still to tell us what 13+59 is! To
find out, we type

EXPERIMENT GOTO 10
remembering to use letter Oh's (not digit zeros) in
GOTO.
This tells the 64 to execute the command
labelled "10". It does so, and the answer finally
appears. You con do this as many times as you
like. It does not destroy a command to have i1
listed or executed.
The 64 can remember many commands at
the same time. (The limit is set by the size of the
memory: ittakesonebyteto hold each character
in a command, plus a little bit of overhead for
the command as a whole.) Every command must
have its own label in front of it, and all the labels
must be different. The machine always stores
and lists commands in increasing order of label,
The lime has come to look at stored and obeys them in this order too unless it is
commands. Lefs begin by showing that the commanded not to.
COMMODORE 64 really can put commands Try typing NEW
away in its memory, and then fetch them out again 10 PRINT "FIRST LINE"
later.
Start up your machine (or if it is already 20A=5
running another program such as SPEEDTYPE,
30B=10
stop it by typing Hjjtf ) and give the command
40 PRINT A;B;A+B
NEW (followed, as usual by the
50 STOP

Remember to end each command with


This command makes the 64 wipe its memory
clean, just as a teacher cleans the blackboard at
the start of a lesson. You won't see anything Now try a LIST, and then a GOTO 10, and
happen except the READY, response, because check that the results are those which you expect.
the memory is all inside the computer. The STOP will make the 64 stop and display a
Next, fype the labelled command READY when it reaches the end of the sequence
of commands.
10PRINT13+59 The sequence in which commands are stored
is kept right even if you type them in a different
(NOTE: "one zero", not "eye oh"] order from their label numbers. For instance, if
you had typed:
and follow it by pressing the ^^^^^^w Key.
The only visible result is that the machine moves 30B=10
the cursor to the beginning of the next line. The
10 PRINT "FIRST LINE"
result of the sum 13+59* is nor worked out or
displayed on the screen. Instead, something invis
40 PRINT A;B;A+B
ible has happened: the 64 has remembered the
command and put it away in its internal memory.
To verify this, first clear the screen (using the 50 STOP

keys) and then give the 20A=5


command these five commands would still have been listed
ond obeyed in the order 10,20,30,40,50. Clear
the machine with a NEW, and try it for yourself.
If you have done everything the right way, a copy Always start by making numbers go up in
steps of 10. If you decide later to slide some extra
screen. This proves that it was in the machine all commands in between the others, this rule makes
the time. it much easier: you can then use intermediate
So far,our PRINT command has been stored label numbers such as 15 or 38.
and retrieved, but it hasn't actually been obeyed. Why bother storing commands at all? There
are two good reasons:
There is nothing special about the sum 13+59.
Any other PRINT command would have done • Commands which are fetched out from the
equally well for this example. 64's own internal memory are executed
much faster than if they are typed in. 25 PRINT "SOUTH-WEST"

• Commands which have been typed in once 35 PRINT "SOUTH-EAST"


can be obeyed many times over. Practically
every useful job done by a computer involves 45 PRINT "NORTH-EAST"
repetition, and it is only sensible to put the
commands into the computer's memory, Now LIST your program, and check that your
where they are easy and fast to get at. new lines have been inserted between the old
ones, in the right places. Run the program and
Perhaps the easiest way to get repetition is to see what happens.
store a labelled GOTO command. Consider the Now write and testyourown program on the
following program: same lines. If you use graphics characters in the
strings instead of letters, you can get some
interesting patterns on the screen.
10 PRINT "NORTH" The GOTO 10 command you have been
using to start your program has a more con
20 PRINT "WEST" venient equivalent: RUN. RUN simply makes the
64 start obeying commands at the one with the
30 PRINT "SOUTH" lowest number.
When you put a semicolon oftera string, the
40 PRINT "EAST" 64 doesn't take a new line between that string
and the next one when it runs your program (bu1
50 GOTO 10 of course you must still end each command with

the ^mmii^B kev) Instead, it starts a new line


When it is started at label 10, the 64 obeys across the screen only when it reaches the
the first four commands in sequence. The next right-hand edge. A simple program like the one
command sends it back to label 10, so that it starts below will quickly fill the whole screen with
the sequence all over again. It just keeps going curious designs; try it, and explain its action.
round and round, and only stops when you type
10 PRINT"'
9 or turn the machine off.
Now clear the machine and type in the 20 GOTO 10
program. Start it by giving the initial command

GOTO 10 Experiment 5.1 Completed

You will see the machine obeying the lines of your


program, much faster than you can read them.
You can slow the machine down by pressing and

holding [try it), or you can stop it in the

usual way with the


At this point, we will actually show the
advantage of using label numbers separated by
10. Suppose you want to alter your program so
that it includes the diagonal directions

NORTH

NORTH-WEST

WEST

SOUTH-WEST

You need four new instructions in between


the existing ones. If you number them 15,25,35
and 45 they will go in just the right places. Type
the following:

15 PRINT "NORTH-WEST"
Now enter the program and run it, holding

EXPERIMENT down the^^^H key to slow it down. (But don't


touch HI until you have typed _
after RUN.)
I'm sure you found this problem quite easy,
but here is an explanation of what you saw.
The program begins by obeying the com
mand labelled 10, which gives the variable A the
value 1. The next command displays this value on
the screen.
Command '30' replaces A by A+l .This is the
same as adding 1 to the old value of A, so the
result (this time) is 2. The next command is a
GOTO, and makes the 64 return to command
20! The value of A is displayed again, but now it is
2. The machine again works through the sequence
20,30,40 and again, and again, but each time
A sequence of commands which is repeated round the value of A is increased by 1. This gives
over and over again is called a loop. A loop may the sequence 1,2,3 ...
include many different sorts of commands, To give you some practice, try predicting the
including a LET, which gives a new value to a first few lines displayed by these two programs
variable. Look at this program, and try to predict (remember, * means "times"):
its action:

10LETA=1 10A = 1
10B-0

20 PRINT A 20 B = A*A
20 PRINT B

30LETA=A+1 30B=B+3 30 PRINT A,B

40 GOTO 20 40 GOTO 20 40A=A+1

50 GOTO 20
Pretend you are the computer and do exactly
what the computer does, patiently, step by step.
Write down what happens to the variable A and
its values. Don't read on until you have thought
hard and filled in your answer.

And now check to see if you were right.


You can do the same kind of thing with
strings. Try this program:

10X$ = "*"

20 PRINT X$

30 X$ = X$ + "#"
[and so on)
40 GOTO 20
The successive values of X$ as the program The self-test quiz for this unit is called
goes round the loop will be *, +■#■, *■■#■■#; UNIT5GUIZ.
+■##&; and so on. The string X$ gets longer and
longer, and uses up more space on the screen
each time it is printed. After some 40 seconds, the
string gets so long that it won't fit in the machine's
memory (the largest number of characters
allowed is 255), and the machine reports a fault:

? STRING TOO LONG ERROR IN 30

The line ERROR in 30 means thai the


command which tried to store the offending string
was the one labelled 30.
Here are some more programs for you to
predict.

Remember that if a letter comes inside a


string, it is just a letter and not a variable name.
So "X" has nothing to do with variable X or X$.
As a final exercise, write a program with a
simple loop, and run it for exactly one minute,
liming it with your watch. Then stop it, see how far
It has gone, and calculate how many commands
the machine has obeyed in the time. Reduce your
figure to the number of commands per second,
and write your answer here:

Experiment5.2 Completed
The purpose of this whole course is to help disk is clear-not stuck over with a silver label*
you learn how to design and build your own like the ITB PROGRAMS disk.
programs. To back up your growing knowledge
of programming you will need a collection of * The label makes it impossible for the disk drive
techniques or "tools" to organise your work, and to record anything on the disk, and is a way of
to help in putting things rignt if they go wrong. preventing the course programs from
This unit is a tool kit ond puncture outfit. It isn't accidentally being destroyed. Since you will
about programming as such, but the contents will eventually be recording your own programs
be useful in an emergency. Read the unit on the newdisk, you don't need protection!
carefully, get to know the techniques it describes,
and give it a permanent place in your mind as you Turn on the drive, and load the disk. Then
go further into the course.
If you have a disk drive, we would like you to
format a newdisk before storting Experimental. CLOSE 1
If you are using a cassette recorder to load
your programs you can skip this section. OPEN 1,8,15, "N: disk name,01"
As you already know, a single disk can be
used to store many different programs. Every where "disk name" stands for any title you want
disk has an extra item; it is an index or to give your disk, such as JOE'S PROGRAMS. In
'directory'which lists the names and sizes of the this case you'd type:
programs on that disk.
Try the following experiment. Load the OPEN 1,8,15, "N: JOE'S PROGRAMS,01"
program disk supplied with the course and
initialise it in the usual way. Then type Wait about a minute, until the red light stops
flashing; then type:
LOAD "$",8
LOAD"*",8 '
These commands will fetch the directory
from the disk into the 64 and display it on the You will get an empty directory. It just says
screen. It will read something like:
0 "JOE'S PROGRAMS "01 2A
M 0 "ITS PROGRAMS DT2A 664 BLOCKS FREE
12 "TEST PROG" PRG
10 "HANGMAN" PRG You have just formatted a disk. Every new
13"SPEEDTYPE" PRG disk you buy has to be formatted just once in its
lifetime,although it needs to be initialised every
and so on, down to time it is loaded. If you format a disk which has
already been usedto store programs, you will
470 BLOCKS FREE destroy everything recorded on it. You nave
been warned!
This list is worth studying. The top line, which Take your formatted disk out of the drive,
appears in reversed characters, gives the write its title on the label, and set it aside.
ntity of the disk itself. In this case the name,
ITB PROGRAMS, was chosen by Commodore.
The "DT2A" is a serial number which also
belongs to thedisk.
Next there is a line for each program. The
first entry gives the size of the program in
blocks. Each block holds 128 bytes, so that you
canseethat-forexample-HANGMANisl280
bytes long. The second entry gives the name of
the program, and third, "PRG", is the same for
every program.

The line at the end of the directory tells you


how many blocksare still left unused. ITB
PROGRAMS has room for another 47
HANGMAN-sized programs, or more if they
are smaller. The capacity of a completely empty
disk is 664 blocks.
Now you understand how program disks
are arranged, you can go on to the next step.
Get a new blank disk of the right type,
preferably from your Commodore dealer.
Make sure that the slot on the left as you load the
Finally you can list all the commands between

EXPERIMENT
any two numbers by quoting both numbers:

UST2000-2090

Now use some of these types of LIST com


mand to look at various parts of the program.
You will quickly notice that the label numbers
don't always go up in steps of 10; this is because
me program was altered manytimes afteritwas
first written.
At the head of the program and in several
other places you will see commands with the key
word REM, followed by descriptive statements in
English. REM is short for "remark". These lines
play no part in the program itself, but are included
to make the program easier for people to read.
When you begin to write complicated programs
you should always use plenty of REMs to explain
Load and run the Unit 6 program, called
what you are doing.
SENTENCES. Take a look at the 'random'
When you are satisfied that you have fully
sentences it displays. These absurd statements
are constructed by a form of internal 'conse-
understood the various forms of the LIST

happens if:
by chance from a short list of possibles. Here we
shan't worry about how the program works
(a) The command you refer to isn't there.
(although it is quite simple in principle) bul we'll
use it as an example in showing you how to list,
(try LIST 650)
alter and preserve large programs.
When you have seen enough of the sentences,
(b) The label numbers are in the wrong order.
stop the program with the fcllili key, and do a
(tryLIST1100-1000;
LIST. The program is far too long to fit on the

from the top of the frame. At the end, only the last
eleven commands can be seen.
The BASIC language includes some special
versions of the LIST command to allow for this
situation. There are five possibilities, which you
should try out as you read about them:

You can list the whole program by typing LIST.


This, as is now clear to you, has certain draw
backs if the program is too long.

You can list a selected command by giving its


number. For example

LIST 1100

will display command 1100 (and no other).

You can list all the commands up to a given


label number by putting a - signinfrontofthe
number. Thus

LIST-80

shows all the commands from the beginning


of the program up to the one labelled 80.

You can ask for all the commands from a


given label number up to the end of the
program by putting a - sign orterthe number:

LIST 9090-
the label numbe..

EXPERIMENT
We have already practised inserting com
mands in Unit5, but you can take this opportunity
to insert a few REM commands. Make sure you
don't replace any existing statement, or the
program won't work.

Altering Existing Commands


The most drastic way of altering a command
is to retype it, using the same label number.
Let's try an alteration. Begin by replacing the
copyright line (label 5) with a Fine containing your
own name. The dialogue might go:

r^ LIST 5

5 REM COPYRIGHT © ANDREW


This experiment discusses how programs COLIN 1981
can be altered and modified. At present you will
be making changes to a program originally You type-*-5 REM CHRIS BLOGGS
written by someone else, but later most modifica
tions you make will be to your own programs.
There are three kinds of change you can
make to a program: 5 REM CHRIS BLOGGS

(a) Removing existing commands Try altering a few more lines, but keep to
those with REM keywords, otherwise you will
(b) Adding new commands almost certainly damage the program and
prevent it from working properly. A program is
[c} Amending or replacing existing commands. like a living cell; random mutations are nearly
always baa and usually fatal.
When a line needs only a minor change, it is
Removing Existing Commands often easier to alter the original {which is already
There are five ways to get rid of a label led on the screen) than to type a new version. This is
command in the 64's store, but three of them
involve deleting or changing the entire program done with the cursor and possibly with the Ij
key. When the changes are complete, the

A whole program can be deleted by ■■■■ key will make the 64 register the
new command in place of the old.
• Switching the machine off. Suppose you want to alter line 100, so that it
reads
or • Typing NEW

or • Loading a new program from cassette


tape or disk. LIST command 100, put the cursor on the S of

An individual command can be removed SENTENCE, and insert 7 blanks (use

• By typing its label number alone and WM ). Then type the word STUPID, check

• By typing another command with the that all is correct, and strike
same label number. another LIST 100 as a check.
Try a few more alterations of this type,
Reload the SENTENCES program and delete always keeping to REM commands. Remember
a few lines which have the REM keyword. Check
that the deletion has worked by LISTing an iryoudont strike ^^^^BH atter
appropriate port of the program both before and changing a line with the cursor, the machine
after. won't register your changes!
Now type RUN at the end of the program. If ii
doesn't work any more, you must have made a
Adding New Commands mistake in editing, such as erasing or altering a
A new command can be added to a program statement without noticing. Don't Toe upset — this
by typing it, with a suitable label number. The is quite common. Just reload the program from
command is inserted at the place determined by me cassette tape on floppy disk.
You must have observed that the SEN 9050 A list of adverbs and adverbial phrases,
TENCES program makes statements about well- describing actions that people do with
known figures. The lists of possible choices are each other.
very short: they are in commands 9070 (for men]
and 9100 (for ladies). For the final part of this 9060 A list of adverbs and adverbial phrases,
experiment you are invited to alter these lists so describing actions that people do by them
that the program makes up sentences about your selves
Family and friends instead.
Each of the two commands 9070 and 9100 9070 Men's names
has the keyword DATA. This is followed by the list
of names, separated by commas. The last name is 9080 Adjectives describing men
followed by a comma and the letter 2.*
There can be as many names as you like. If 9090 Various sorts of men
the names run to more than 2 lines, use a second
DATA command (with a label number one up on 9100 Ladies'names
the first one). Third and fourth commands can
also be used. Only the last DATA command in 9110 Adjectives describing ladies 42
each group needs the Z at the end.
Some possible alternatives for lines 9070 9120 Various sorts of ladies
and 9100 could be:
Alter the lists in any way you like. Remember
to keep them consistent. If you alter 9020 to
9070DATABILL,GEOFFREY,PERCEVAL,MR.SOPHOC
actions dealing with food, you must alter 9030
LESJHE HEADMASTERS
9100DATAGRANNY,SUSAN,VIOLET,MRS.PINKERTO
and 9040 accordingly, otherwise you may get
NJHEGYM MISTRESS, AUNTIE FLO, RACHEL
sentences like
9101 DATAPENNY,KATE,LAURA, FRANCES, NORAH,V
ICKY^ SUSAN ATE HER WELLINGTON BOOTS

When you've made these changes, run the


program again. If it comes up with complete Experiment6.2 Completed
nonsense check that you have put a comma
between each name (but not two commas) and
that the lost name is followed by a Z.
Once you've got the feel of making changes,
you can apply your imagination to the other lists
of words in the program. They are:

9000 Actions that people do by themselves


(intransitive verbs)

9010 Actions that people do with each other


(transitive verbs)

9020 Actions that people do with clothes (transi


tive verbs)

9030 Items worn by men

9040 Items worn by ladies

Theuseo/Zaffheendofa DATA command is a


feature of this program only, not of BASIC in
general. DATA commands in mostotherpro
grams don't need the Z at the end.
protect important recordings which mustn't be
destroyed, so get yourself another tape.

EXPERIMENT If all is well, the machine says

SAVING FAMILY

and a moment later,

READY.

In theory, your program is now recorded, but


it is better to check. Various things may have gone
wrong: you may have forgotten to rewind the
tape, or to press the RECORD button, or the tape
itself could have a small bald patch which
prevents it from making a correct copy of the
program. These things shouldn't happen, but in
practice they do!
When you have altered the SENTENCES To check your tape, rewind it, and then type
program to say amusing things about your
friends, you may want to keep the new version to VERIFY "FAMILY"
show at parties, etc. This section explains how to
preserve the program on a cassette tape. The machine replies
If you posess a disk drive, skip this section
and read the next one instead. PRESS PLAY ON TAPE
Get hold of a blank tape, or one with nothing
on it thai you need to keep. It should be of good Press the PLAY button (but not RECORD this
quality, and as short as possible: you are only time). The machine then looks for your program
going to use up about one minute's worth of tape, on the tape, and checks it against what is in the
and there is no point in paying for more. The memory. Naturally you mustn't make any altera
special cassettes made by Commodore are ideal. tions between the SAVE and VERIFY commands.
Load the new tape into the cassette unit in If all is well, the messages you will see are:
place of the SENTENCES cassette, and rewind it.
Release all the keys on the cassette unit. Then stop
the SENTENCES program, and type
VERIFY ■'FAMILY"
SAVE "FAMILY"
PRESS PLAY ON TAPE
(you can use any name you like instead of
OK
FAMILY).
The machine replies SEARCHING FOR FAMILY

PRESS RECORD AND PLAY ON TAPE FOUND FAMILY

VERIFYING
Follow these instructions, pressing both keys
on the recorder at the same time. OK
If the RECORD key won't go down, check
that the tape you are using hasn't had its 'write
permit' tabs taken away. These tabs are at the
back of the cassette, like this: If the machine finds an error, or doesn't get
as far as FOUND FAMILY, you must go back to
the beginning and try the SAVE command all over
again. If the trouble persists, try another tape (or
the other side of the first one). If you still can't
make the system work, take the VIC and the
cassette unit back to your dealer for a check-out.
Once a program has been SAVEd, it can be
stored away and LOADed at any time, with a
command such as

LOAD "FAMILY"

To save your program on a disk, remove the


ITB PROGRAMS disk and load the one you
If the tabs are broken off, it is impossible to formatted at the start of the unit. Initialise it by
put any new material on the tape. The idea is to typing
break down, but other accidents can happen.
Thunder storms have been known to corrupt the
CLOSE 1
information in a computer store: there may be a
power cut, or your baby sister can trip over the
OPEN1,8,15,T'
mains lead and jerk the plug out of the wall. If you
Now record your version of the program lose six hours of work through such an incident,
you may feel a little upset. If you have been taking
with the command ^^^^^^^
regular half-hourly dumps you can reload the
,1 most recent version and go on with only a small
SAVE "program name ,8^^^^^^
where "program name" is a title you choose for loss of your time.
yourself. For example,^^^^^^ To make the system absolutely safe, you
should SAVE on two different tapes or disks
alternately. Then even if the machine stops
If all is well, the machine says during a SAVE, with half the old version
SAVING FAMILY
obliterated by half of the new one, you are still
and a moment later protected.
READY.
To make quite sure that the program has
been recorded correctly, type Experiment 6.3 Completed

VERIFY "program name" ,8


(where "program name" is your program.]
The machine replies
SEARCHING FOR program name
VERIFYING
OK
READY.
This process will practically always work as it is
described; but if it doesn't try;it again carefully,
from beginning to end. If it still fails get advice
from your Commodore dealer.
When you have SAVEd the program and
VERIFYed it, load and list the directory. Your
program should now be included.
Once o proqram has been SAVEd, it can
i i H ,r . .!■ i „„.

like

LOAD "FAMILY" ,8 -
Now thatyou have a formatted disk, you
can keep on storing more programs on it, until
the space runs out. Occasionally you will want
to get rid of a program and replace it by a
newer version with the same name. If you jus1
give the command
SAVE "program name" ,8
and a program of that name is already on the
disk, the red warning light will flash and nothing
else will happen. To dispose of the old program
you must uselwo extra characters in front of the
program name: @ and : (colon). The save
command now looks like
SAVE "@: program name" ,8
It is best to follow this kind of SAVE with the
special command
OPEN 1,8,15,"V"
and wait until the red light goes off. This gives
the machine a chance to collect up the space
freed by the removal of the program so it can
be used again.
A program doesn't need to be perfect to be
SAVEd If you are writing a very long program
(or even copying one from a book) it pays to
SAVE yourwork every half-hour or so. This is
because the 64's memory isn't as reliable as a
tape in a drawer. The machine itself is unlikely to
H RFTlflN HUH 1

EXPERIMENT Ifyou fell into the trap (as you were supposed
to), here is what happened:
You typed the first command (which was care
fully designed to fill up the whole of a screen line).
You then found the cursor at the beginning of the
next line and naturally typed the next command,
.. .. .,, ■BlfHW
ending it with a ^^ggg^^ .Sinceyou didn't -

endtherirstlmewitha ^H%%%%%%%%%%9 ,tnesystem mm

thought that both lines were part of the same


command, namely

10 PRINT "A FRIGHTFUL AND APPALLING


TRAP" 20 GOTO 10

This "command" is not correct BASIC, and


In this section we point out a subtle and
gives rise to a syntax error when the machine tries
dangerous trap which lies in wait for
COMMODORE 64programmers,and tell you to execute it.
how to clamber out ifyou do fall in.
This type of error is particularly difficult to find
To begin, we'll try to drop you straight in to a
unless you know what you are looking for. You
simple example of the trap, type NEW to clear
are most unlikely to notice the mistake as you type
the store, and then enter the following program,
the program — even experienced programmers
inserting all the spaces shown carefully, and
often forget to end their commands with
watching the screen as you type.

^^■■^H if the cursor is at the beginning of


Z
a new fine. If you LIST the program, or even the
Now do a LIST and check the program, which section which includes the error, the faulty
should appear exactly as shown. command looks exactly like two correct ones,
You would expect the program, when typing and the fault is invisible.
RUN, to display the message Fortunately, the error can be pinpointed by
LISTing just the command in which the error is
A FRIGHTFUL AND APPALLING TRAP reported. Ifyou type LIST 10, out come lines 10
and — apparently — 20! This must be wrong,
over and over again until it is stopped. Try it and since you only asked for 10. To correct the
see. It is likely to come up with trouble, retype both commands completely,

AFRIGHTFULANDAPPALUNGTRAP20 remembering to end each one with M


I
W\m

? SYNTAX ERROR IN 10 In summary:

READY. (a) Always end every command with l_

Even if your program does work correctly, ^HJBlllH , no matter where the cursor
read on ana find out just why you managed to may be.
avoid the pitfall. L.

The reason the machine failed to run your (b) If the 64 reports an error in a command and
program (assuming that is what it did) is by no you can't see anything wrong with it, LIST it
means obvious. You could show the program to out by itself and check whether it runs on into
the world's greatest experts on BASIC, and they the next command in the program.
L_

wouldn't see anything wrong with it.


The difficulty arises because of the screen
width of the 64. Inside the machine, any BASIC
Experiment 6.4 Completed
command may be up to 88 characters long. The
screen is only 40 characters wide, so the
displayed version of a command can spread
over anything up to 3 screen lines.
When you type a command and the cursor
reaches the end of a screen line, the system c
moves it on to the beginning of the next line; but it
still assumes that you are typing the same L_

command. A command is only ended by the


The programs we wrote in Unit 5 were N$ actually is "JIM".
The full set of relationships you can use in
drastic action to stop them and most, if left to BASIC are these:
themselves, would have gone on and on for ever.
= (is the same as)
This unit is about how to control programs, and
make them stop when they have gone far enough.
< (is less than]
The topics described in this unit are funda
mental to computing. When you master them, you
> (is more than)
take the biggest single step towards being a
programmer. Read the unit slowly and carefully, <> (is different from)
andif you are in any doubt about some point, go
back and read about it again. It is well worth <= (is not more than)
doing because these ideas, once you understand
them, will take you a long way forward. >= (is nof less than]
The control of programs depends on a key
The relationships <>, <= and >= are each

may be more familiar to you in the forms ¥=, =£


statements which are true, or which are at least
and Ss, but the designers of BASIC had to a<
supposed to be taken as true:
the fact that computer keyboards don't usual ly
have keys marked with these signs.
"My train broke down on the way in." The relationships can all be used either
between pairs of numbers, or between pairs of
"I love you." strings to make conditions. Numbers and strings
can be represented by appropriate variables.
A condition is a special kind of statement Thus
which is not necessarily true, but might equally
well be false. In English we use conditions after 5> 4 is true becouse 5 is greater than 4
the word 'if. In the following sentences the
conditions are printed in bold type: 7 <=6 is faise because 7 is more than 6

"If the last train has left, you'll have ta


spend the night in Aviemore."
A>=Bisfrue, andsoisB<=7.
"If the program doesn't work, find the
fault and fix it."
When relationships are used between strings
they imply alphabetical (dictionary) order, so thai
The speakers of these sentences are not
"DOG" > "CAT" is true,
insisting that the last train has gone, or that the
program really doesn't work; they simply don'1 and "JIM" > "JIMMY" is false.
know, and are making plans accordingly. In
English, a condition can turn out to be true or
false, without the speaker being called a liar.
In BASIC, conditions also come after the
keyword IF. They involve the various 'objects'
used in programs: number variables, string vari
ables, numbers and strings. The conditions, which
can be either true or false in any instance, are
built round one of six relationships. This is best
illustrated by example:

Consider the BASIC condition:

A<5

[where < is a sign which means "is less than").


This condition is true if the value of the variable A
really is less than 5 (say 0 or 3 or 4.98). It is fa/se if
A is worth 5 or more.
Another example, this time using strings, is

N$o"JIM"

[where <> means "is different from").


This condition is true if the variable N$ has
any value except "JIM"; thus it is true if
N$="JACK" or N$="JIMMY". It is only false if
EXPERIMENT
Condition Value (true or false]

A$+"NE"<>"JOANNE"

5>X

X + Y<>13

X + 2 = Y

Now check your answers, which are given in


Appendix B.

Experiment 7.I Completed

Suppose that the computer has obeyed the


following three statements:

LETA$ = "JOAN"

LETX = 5

LETY = 7

Work down the following table, and mark


each condition as false or true:

Condition Value (false or true]

X<7

X>=5

A$o"X"

YoX

A$< "FRANCES"
%

A$ > "JOAN"

Y = 8

The quantities on either side of the relation


ship can be expressions, just as in LET
commands. The expressions can be as complex
asyou wish, but the important thing is to compare
like with like: a condition which had a number on
one side and a string on the other would make the
COMMODORE 64 stop and report a fault.
Assume the values of A$, X and Y are the same
as above, and work out each of the following
conditions:
Putting an IF statement in a loop gives a good
wayofstoppingitwhenithas gone round enough

EXPERIMENT times. Type in and run the following:

10X$ = "A"

7-2
20PRINTXJ

30 X$=X$ + "B"

40 GOTO 20

50 STOP

This program runs on, filling the screen with


ever-lengthening strings of Bs until it runs out of
space. Tne STOP at line 50 is never reached.
49 Now stop it and replace line 40 with

The chief instrument of control in BASIC is the 40 IF X$ <> "ABBBB" THEN 20


IF command. It consists of the keyword IF, a
condition, the word THEN, and a label number. II When you run it, it displays
is very like a GOTO, but with one difference: the
jump only happens if the condition is true.
An example of an IF command is

IFX$o"ABBBB"THEN20

Here the condition is X$ <> "ABBBB" and


ABBB
the whole command tells the machine to jump to
20 ifX$isdifferentfrom "ABBBB". If this condition
and stops!
is false, the machine continues obeying com
The reason lies in the condition
mands in their numerical order.
If you are like most people, your first reaction
and round the loop, the condition is at first true
to this command is that it is a bit absurd. "Either
(because X$ is AB, and then ABB, and then ABBB,
X$ is different from that string with the A and Bs" allofwhicharedifferentfromABBBB).lneachof
you say "Or it isn't. It all depends on what comes
these cases the IF command behaves like a
before, but in any case when the programmer
simple GOTO 20 and sends the machine round
wrote that IF command, he must have known!"
the loop another time. Eventually, X$ gets to
Your view is understandable, plausible, bu1
ABBBB. The condition is now false; the jump
wrong. There could be two entirely different
doesn't happen and the machine drops through
reasons:
\o the end of the program where it stops.
# Suppose the IF command is in a loop where Now try altering the condition in various
some variable has its value changed every ways, and observe the effect when you run the
time round. The condition could well be true program. Whatever string you use, make sure
for some of the values, but not others. that the condition eventually becomes false,
otherwise the program will never stop.
Possible conditions to try are:
• Suppose again that you are writing a program
for someone else to use. Then you won't know X$o"AB"
in advance what the user is going to do with it,
but the actions of the program must stil I X$o"ABBBBBBBBBBB"
depend on what he or she actually does. If you
want a good example, the author had to make X$<"ABBA"
the various quiz programs respond in a
sensible way to your answers even though he The same control technique can be used with
had no idea how you were going to reply ta numerical variables.
any of the questions.
Typeinl0P = 0

20 PRINT P,P*P

30P=P+1

40 GOTO 20

50 STOP
Run this program, see what it does, stop it,
and change line 40 to read (1)

40 IF P< 11 THEN 20 10X$="A"

Now run the program again. It displays two 20 PRINT X$


columns of figures which look familiar, and could 30 X$=X$+"B"
be useful to someone who didn't know the
squares of the numbers by heart. Asa working 40 IF X$ <>"ABBBB"THEN 20
program there is only one thing wrong: the
display isn't labelled, and its meaning is not 50 STOP
immediately obvious to anyone but you.
heac
We can fix this defect by adding a heading, (2)
or line at the top which identifies each column,
like this: 5 PRINT "NUM'V'SQUARE"

NUM SQUARE 7 PRINT 50


10P=0 ■

20 PRINT P,P*P ■

30P=P+1

401FP<11THEN20

50 STOP

If we forget about the heading commands (5


and 7) in !he second program, both programs
seem to follow a set pattern. In each case,
Clearly the heading has to be displayed
before any of the numbers or squares, so the 1. There is a variable which changes regularly
command which displays it must come first. Since as the (oop is repeated. You'll see that it is X$
label 10 is already used, and it would be pointless in the first program and P in the second. In
to change all the labels in the whole program, a general, this is called a control variable, and it
sensible decision would be to use label 5. The can be either a string or a number.
command itself is a PRINT, with two strings;
"NUM" and "SQUARE". The comma between 2. There is a command which gives the control
the strings ensures that the spacing corresponds variable its starting value. This command is
to the spacing between the columns of figures. outside the loop (that is, it is not repeated but
The whole program now reads: only obeyed once).

5PRINT"NUM","SQUARE"
3. There isa command which is obeyed for every
value of the control variable. In our examples,
10P=0
these are the PRINT commands
20 PRINT P,P*P
PRINT X$
30P=P+1
and PRINT P,P*P
40IFP<11THEN20
In practice, this part of the loop can be
50 STOP expanded to include any number of com
mands, all of which are obeyed for each value
Run the. program in this form, and examine of the control variable. This group is called the
me output. body of the loop.
Do you want a blank line between the head-
ures? The command 4. There is an increment or quantity by which the
control variable grows each time round the
follow) will give you an empty line, so try adding loop. In our examples, X$ grows by adding a
the command "B", and P is increased by 1. Other increments
are possible; for instance a string could grow
7 PRINT
by 5 symbols at a time, or a number could go
In a few minutes you will be asked to write up in steps of 2 or any other number. It could
some programs of your own. Before you start, also start with a high value and go down.
let's take a careful look at the programs we have The loop always includes a command which
already run, and draw some general moves the control variable one step further
conclusions. The example programs are: each time it is obeyed.
5. There is a final value for the control variable. In the table which follows, examine each
When the loop has been executed with this program and fill in the name of the control
value, the repetition must cease. The last variable, the starting value, the final value, the
command in the loop is an IF command, with a increment and the number of times the loop is
condition which is true if the loop is still due to obeyed. To work this out, it often helps to jot
be executed, but false when the control down the value of the controlled variable on the
variable has passed its final value. first, second, third time through the loop, and
to see how many values there are until the final
value is reached.

No. of
times
Control Starting Final round
value value Increment loop

10X$="A" "ABBB" 'B" 4

20 PRINT X$

30 X$=X$+"B"

40 IF X$o"ABBBB"THEN 20

50 STOP

10P=0 11

20 PRINT P,P*P

30 P=P+1

40IFP<11THEN20

50 STOP

10Y$="Z"

20 PRINT Y$

30 Y$=Y$+"XY"

40 IF Y$ <>"ZXYXYXY"THEN 20

50 STOP

10R=5

20 PRINT R,R/8

30 R=R+3

40IFR<17THEN20

50 STOP

10C=27

20 H=30-C

30 PRINT C,H

40C=C-5

50IFC>2THEN20

60 STOP
When you have completed the table, check
your answers against those given in the back of
the book (Appendix B).
EXPERIMENT
Experiment 7.2 Completed

When you construct a program, you should


begin by doing some design.and then writing oui
Ihe whole program on a piece of paper. Use
pencil ana ruooer! Some people compose their
programs directly on the computer keyboard, bu1
this method is only for geniuses or morons — it is
definitely not recommended for ordinary people.
The reason is quite plain: if you start without
plans you have about as much chance of success
as a builder who puts up a house without any
drawings, making up thearchitecture as he goes
along. He might just produce an architectural
jewel, but he is much more likely to end up with a
leaky hovel which will blow open at the first storm.
When you design a loop for a program, you
havetodecideall the essential itemsforyourself.
They include the name and type of the controlled

. etails of the body of the loop.


When you have made up your mind on these
points, you can put them together in the standard
pattern.
Here is a worked example.
One pound sterling (£1) is worth 2350 Italian
Lire at today's rate of exchange. We need a table
which gives the Italian equivalent of Sterling
amounts from £5 to £75, going up in steps of £5.
The display is to start:

11750

23500

ond so on.

Let's think aboutthe loop first. The control


variable will clearly be a number, and we can
call it PS (this stands for "Pounds Sterling" and is
as good as any other name). The starting value
willbe 5, the final value 75, and the increment 5.
The body of the loop is to print a value in£s, and
the corresponding value in Lire, which is 2350
times more.
People who like school Mathematics and are ships between quantities. Examples of its use are
ood at it sometimes get confused by the way that
i, a ■ ■ i-r*ArM/~ir.i_:_j '* I..
IFX=Y+2THEN100
to you, you can safely skip this section.
In Mathematics, "=" is used in equations, to IFN$="YES"THEN150
assert that two different expressions really have
the same value. The equation tells you something Again, there is no implication that the condi
which is true. For instance, if the Maths teacher tion actually is true; instead the command is an
writes on the board order to work out whether the condition is true,
andtotakecertain action if it is. In conditions "="
"2x + 5 = 9" has the same logical force as any other relation
ship such as < or >=. It is best to avoid the word
you can be sure that for the particular x the "equals" and to call the symbol "is the same as".
teacher has in mind, the statement is right. If this
weren't so, you can imagine the following To summarise:
conversation:
BASIC uses "=" in LET commands, where it means
Pupil puts hand up. "becomes", and in conditions where it means "is
the same as", but what it says isn't necessarily
Teacher: Yes? true. Got it?

Pupil :x is two The self-test program for this unit is called


UNIT7QUIZ.
Teacher: No. The answer is seventy eight

Pupil :Eh? I don't understand.

Teacher: I lied when I said 2x + 5 = 9!

In BASIC "=" is used in two different senses,


neither of which is the same as the mathematical
one.

In a LET command, the sign means


"becomes". It's an instruction to calculate the
value of the expression on the right, and to put this
value into the variable on the left. Instructions
aren't statements, and it doesn't make sense to
say that they are, or aren't true. (They may be
wrong in a particular context, but that is a
different matter.) The trouble is that if LET is left
off, the command looks like an equation. It isn't.
Let's make this clear:

In BASIC

Y=X+2

doesn't inform the computer that Y equals X+2; it


orders it to work out the value of X+2 and put the
result in variable Y. Here are some points to
ponder:

Q=Q+5 is a reasonable and useful


BASIC command

• P=Q Are not the same in their


and Q=P effects

X+l=5 isnora legal BASIC


command

In each case do you see why? Try to explain it


to yourself in your own words.
The other use of "=" is in conditions. You'll
remember that = is one of six possible relation
At this point in the COMMODORE 64 course The second type of program error arises
you are just beginning to write your own when the 64 finds a particular command impos
programs. The first ones ore short and simple. sible to obey. Suppose the machine came to the
Later, as you develop your knowledge, experience command
and skill, you are certain to design and write
programs of ever greater complexity and interest. 130 GOTO 500
The table gives you some idea of how far you can
go: but there was no command labelled 500. This
would make the machine stop and display an
error message:

Program Number of UNDEFINED STATEMENT IN 130


Commands
Unfortunately the error messages tend to be
Converting Italian Lire to in programmer's jargon ratherthan plain English,
7
£ Sterling (Unit 7) but they are fully explained in Appendix C.
59 The third sort of program fault is the most
Unit 3 quiz program about 100 difficult of all to find and put right. There are no
error messages; instead, the computer simply
displays the wrong answer to your problem or
Chess playing program about 5000 bogs down in a loop without displaying anything
at all. The first and most obvious thing to do is to
stop the machine, LIST the program and examine
Program to control an
about 25000 it carefully. This will usually help you pin-point the
industrial robot error. However, suppose it doesn't; let's imagine
that you have spent a good few minutes
Program which runs a
computerised airline about 5000000
examining each command, and you still can'tfind
booking system anything wrong.
At tnis stage you need a more powerful
method of investigating the workings of your
Naturally, any program with more than
program. The method is called 'program tracing'
about 5000 commands is always the result of a
and consists of pretending that you are the
team effort (it would take too long for one person
computer. You start at the beginning of the
to write) but there is still plenty of scope for the
program and work through it, command by
individual programmer.
As you work at programming, you will often
find yourself stuck. A program you have just
cause of the trouble. You will need to be patient
and methodical, and above all you'll need to
written and keyed in with great care simply
switch of/your intelligence, and work through the
doesn't do what you expect. This unit describes
set of instructions like a stupid robot, without
some of the ways you can get over this difficulty.
r* 1 .. 1 1 .1 1 . 1
^M.<r' + \*W\m*'*J"M*\* *W* *■■■' J . l < Ji4t' — M».■!■! - nl- ■■!• J^
tions, or use any other type of short cut.
that you can always refer back to it again when
To imitate the computer, you must first have a
[not if] the need arises.
good idea of how it works. Suppose you could
When people come to their first program-
minq difficulty, they react in different ways. Some
feel angry and insulted; some immediately give mands in the middle of running a program, open
up in despair, and decide that programming is it up and look inside. You would discover*:
First, the program itself, stored in the memory
not for them; and some pretend that the program
in much the same form as it was originally typed.
is "ninety nine percent right" and go on to the next
Second, the variables the program has used
problem! None of these reactions makes good
up to this point. Each variable occupies some
sense. The only thing to do is to find the mistake
room in the memory, and has a value, which
and put it right. It can be a great comfort to
could be a number or a string.
remember that every programmer sometimes
Third, you find that the computer has kepi
gets stuck, even those who have been working
track of its place in the program. Somewhere
with computers for 25 years.
Program errors fall into three groups. The
(actually, in a special variable called the
first and most common type is the one which
"program pointer") it remembers the label
number of the next command it is due to execute.
comes up with SYNTAX ERROR when the
computer tries to obey a particular command. Now let's unfreeze the computer just a little,
This means that the command doesn't follow the long enough for it to execute one command. The
rules of the BASIC language. For instance, it might command the machine chooses will naturally be
have a spelling mistake in a keyword, or there
may be too many (or too few) double quote signs. If you took the cover off the 64 you wouldn't
Most syntax errors are caused by typing mistakes actually see these things, but only a few silicon
and are obvious once you know they are there; chips and other components. However, the
but Appendix C gives a checklist of the kind of appropriate electronic instruments would
error to look for if you are in difficulty. certainly show you the items we mention.
the one remembered by the program pointer.
To imitate the computer accurately, you'll
When you look again, there will be certain need to see all these parts clearly; the program,
a mey aepenu
the variables, the display and the program
counter. A good method is to use a "program
w cthp*>nnhRvec trace chart" which you draw on a piece of paper.
possibilities:
Arrange it like this:
(a) a PRINT command will make something
appear on the screen. PROGRAM POINTER 10

(b) a LET command will create a new variable if VARIABLES


one is needed, and put a new value into it. DISPLAY PROGRAM

Both the PRINT and the LET commands will 10A=5


also move the program pointer on to the next
command in sequence, so that when the 20PRINT"ALPHA=";A
computer is restarted it 'knows' which
command to obey next. 30 A=A*3

(c) a GOTO will not display anything or alter 40 B=A+37


any variables. It will simply reset the program
pointer so that it indicates the command men 50 PRINT "BETA=";B
tioned in the GOTO. For example, the
command 60 STOP

130 GOTO 270


The program you plan to trace is filled in oi
will put 270 in the program pointer.
the right, and the starting value of the program
pointer — that is, the label number of the first
command to be obeyed — is at the top. Make

a GOTO. If it is false, the program counter is will be a waste of time.


Now you are ready to start. The program
simply moved on to the label of the next
counter says '10', so take and interpret the com
command in sequence.
mand labelled'10'. It says A=5, so it must be a LET

Lookat:120IFX = 5THEN170 command. Look in the box marked VARIABLES


for an A. There isn't one, so write down an "A", a
colon and the value 5. Finally, move the program
130 PRINT "NO"
pointer on to the next command in sequence,
If X does have the value 5, the condition is putting a line through the previous value:
true, and the program counter is changed to
PROGRAM POINTER -JT20
170. Otherwise, if X has some other value, the
program counter is simply advanced to 130.
VARIABLES A: 5
[e) the STOP command indicates that the pro DISPLAY PROGRAM
gram has ended, by displaying a BREAK
message. There is no point in continuing the
program beyond this point. 10A=5

20PRINT"ALPHA=";A

30 A-A+3

40 B=B+37

50 PRINT "BETA=";B

60 STOP

The next command is interpreted in the same


way. You forget the 'purpose' of the program, or
any knowledge you may have about sequencing,
and take command 20 only because the program
pointer says so. The command is a PRINT, and
you can work out that itwill display "ALPHA - 5"
Put this down in the DISPLAY section, and PROGRAM COUNTER X&2fr3RrW
advance the program counter, giving:
VARIABLES P: -+* 2
PROGRAM COUNTER Jfr-30- 30 PROGRAM
DISPLAY

VARIABLES A: 5
10P=1
PROGRAM
DISPLAY
20 PRINT P;P*P*P

10A=5 30P=P+1
ALPHA = 5

20 PRINT "ALPHA=";, 40 IF P<4 THEN 20

30 A=A+3 50 STOP

The next command at 40 is an IF. To imitate


40 B=A+37
the computer, evaluate the condition P<4. Since
50 PRINT "BETA=";B the current value of P is 2 (that's what it says in the
VARIABLES section), and 2 is clearly less than 4,
the condition is true. All you do, therefore is to put
60 STOP
20 as the new value of the program counter. You
The next command gives a new value to an
existing variable A. You first work out the expres PROGRAM COUNTER Mr3ar3&M"l$
sion A*3 using the old value (5} and record it,
crossing the old value out, like this: VARIABLES P: Jr 2
DISPLAY PROGRAM
A:-*-15

The command after that creates a new vari


able. Continue tracing until you reach STOP. The
20 PRINT P;P*P*P
final result is:

PROGRAM COUNTER 4fr-30--30--40--S0- 60 30P=P+1

VARIABLES A: -5-15 B: 52 40 IF P<4 THEN 20

DISPLAY PROGRAM
50 STOP

The trace continues this way, until at last the


ALPHA = 5 10A=5 condition is false, and the program reaches
STOP. The final result is:
BETA = 52 20 PRINT "ALPHA="; A
PROGRAM COUNTER Wa&MrM-WlSr
BREAK IN 60 30A=A*3
VARIABLES P:+.2*3-4
READY. 40 B=A+37
DfSPLAY PROGRAM
50 PRINT "BETA=";B
10P=1
60 STOP
20 PRINT P;P*P*P
The next example involves a simple loop:
3 27 30P-P+1
10P=1
BREAK IN 50 40 IF P<4 THEN 20
20 PRINT P;P*P*P
READY. 50 STOP
30P=P+1

40 IF P<4 THEN 20

50 STOP

The irace of this program as far as line 30 is


straightforward:
EXPERIMENT

Now practiceyourtracing with the following


programs. Use a pencil, and have a rubber
handy in case you make a mistake: 62

PROGRAM COUNTER 10

VARIABLES

DISPLAY PROGRAM
10X=5

20Y=7

30Z=X+Y

40W=Y-X

50 PRINT X;Y;Z;W

60 STOP

PROGRAM COUNTER 10

VARIABLES

DISPLAY PROGRAM
10Q=1 i
I

20 PRINT "SHE LOVES ME"


j

30 PRINT "SHELOVES ME NOT"


i

40Q-Q + 1 i

50 IF Q<3 THEN 30

60 STOP 1

When you have completed these two


experiments check your answers against those Experiment 8.1 Completed
given in Appendix B.
EXPERIMENT

Your program has all the right parts: a loop,


a command to display a heading, and a PRINT
command to display each line of the table. It
reads:

10 PRINT "TWELVE TIMES TABLE"

20P=1
How can tracing be used to find mistakes? It
depends on switching between a state of robol 30P=P+1
obedience, and a state of human intelligence.
First you become a robot and trace a command 40IFP<13THEN30
exactly as the computer would have executed it.
Then you go back to being a person, and ask, "Is 50 PRINT P;"*12=";P*12
this what I expected?" If so, you carry on the
trace. If not, you will have a good clue as to why 60 STOP
the program is going wrong.
Here is a simple example. Suppose you've When you run this program, the results are a
written a program to display the 12 times table. bit disappointing. All you get is
The display you expect is
TWELVE TIMES TABLE
TWELVE TIMES TABLE
13*12=156
1 *12=12
BREAK IN 60
2*12 = 24
READY
3*12 = 36
Not what you expected! The mistake may be
[and so on down to] perfectly obvious, but let's pretend you can't spol
it. You begin to trace, and after a few steps you
12*12=144

PROGRAM COUNTER -W-30--30--40-.3fr-.40- 30

VARIABLES P:-fcfl-3-4

DISPLAY PROGRAM

TWELVE TIMES TABLE 10 PRINT "TWELVE TIMES TABLE'

20 P=l

30P=P+1

40IFP<13THEN30

50 PRINT P;"*12=";P*12

60 STOP
and you suddenly realise that the value of P is When he runs this program, it displays
working its way up to 12 without anything being
displayed. It is now dearthat the PRINT command A = 34
ought to be inside the loop, not outside. The right
place is between commands 20 and 30. The IF B = 19
command also needs to be changed to jump
back to the PRINT. A quick edit produces A PLUS B= 15

10 PRINT "TWELVE TIMES TABLE" BREAK IN 60

20P=1 READY

25 PRINT P;"*12=";P*12 which is clearly wrong. On the other hand,


when he traces it, he finds that command 50
30P=P+1 gives

40IFP<13THEN25 A PLUS B = 53

60 STOP which is what he expects. As long as he really


believes that"—" means "add", he will
Program tracing is an extremely useful tech never find the error!
nique if you have the patience to do it step by step.
If you make guesses about whole sections of Of course most misunderstandings are much
program, you are likely to make the same more subtle than this one. Nevertheless, if your
mistake as you did when you wrote the program trace comes out differently from the result dis
in the first place, and the trace won't reveal your played by the 64, and keeps coming out differ
error. ently when you repeat the trace, this is clear
There are a few circumstances under which evidence that there is something about the art of
rfie tracing method as described doesn't work, programming you haven't understood correctly.
and you should know what they are: If you can, get advice from someone who knows
• If a program is very large, a straightforward BASIC better than you do'; but otherwise go back
trace would just take too long. More appro to the beginning of the text-book, and check
priate methods wil I be described later on in every single item of your knowledge against
the course, at the time you moy actually need what it says. This will nearly always bring the fault
them. to light.
■ If you simply don't believe that you can make Sometimes—very very rarely—your difficulty
a mistake, then tracing won't be much help. may be caused by a mechanical fault in the com
Most people, when they write down the last puter. Modern machines like the 64 are extremely
line of a program, experience a strong moral robust and reliable, and when they do break
certainty that 'This time it's right". The feeling down, it is usually obvious: the cursor won't come
only comes because you haven't been up when you switch on, or you find it impossible
conscious of making any mistakes, and is to load programs from your cassette recorder or
extremely misleading. It is much bettertosoy disk drive. In practice you should never blame the
to yourself'This time it's wrong. Let's find the computer for not running your program until you
mistakes". But you'll need to swallow your have examined every other possibility two or three
pride! times over. When you send your machine to be
# If you have misunderstood some fundamental repaired, you must explain exactly whyyou think ii
aspect of BASIC, a trace will again be of little is broken, and include a copy of the program
help. To take a crude example, imagine which it refuses to run correctly.
someone who believes, firmly but mistakenly,
that in BASIC the sign " - " means
"addition." He writes a program to add two
numbers like this:

10A=34
he thinks this means
"plus"!
20B=19

30PRINT"A=";A\

40 PRINT "B=";B
There are now plenty of people who understand
50PRINT"APLUSB=";A-B
advertisement in a local shop window will
60 STOP usually find help.
Here are two programs with mistakes for
you to find and correct.

[a) This program is supposed to display a con


version table for gallons to litres, starting at 1
gallon and ending at 10 gallons (1 gallon
4.5 litres)

10 PRINT "GALLONS", "LITRES"

20G=1

30 PRINT G,4.5*G

40G=G+1

50IFG>11THEN30

60 STOP
The program on tape UNIT8PROG is sup
posed to display the 7-times table, but contains
[b) This program is supposed to be a solution to
problem 1 in Unit 7, to display a triangle of
several errors. Load it, find and correct the
mistakes. Check your answers in Appendix B.
stars. It was actually written by someone
learning BASIC:

Experiment 8.3 Completed


10A$ = "*"

20 PR I NT A$

40IFA$o"*********"THEN20

50 STOP

Experiment8.2 Completed
EXPERIMENT 1
k

9-1
k

r 1
k

Let's draw some more pictures. This time, we'll Do you remember that in Unit 2 we said,
make the COMMODORE 64 do all the hard work "Don't use the double quotes, they're funny!" k
and drudgery for us. Now you are going to find out what effect they
If you think back to units 2 and 3 (look to really have, and why they're so useful.
I L
remind yourself if you like) you'll remember thai When you start typing a command (say after
when you draw on the screen you can use a
number of control 'functions': a READY or a ^^^^ ) the 64 is in i.

'normal' mode. Control functions like colour


• Cursor movement in four different directions selection or cursor movement work in the way *

you have come to expect. As soon as you type a


• Selection of sixteen different colours double quote character to mark the beginning of k

a string, the machine changes to quote mode.


• Colour and background reversal (on and off) Ordinary characters such as letters or graphics
are still treated in the normal way, but control
9 Moving the cursor'home'to the top of the functions are not obeyed: instead they are put L
left-hand corner into the string as 'special' characters, mostly
letters, signs or graphics on a reversed back j*

k
• Clearing the screen. ground. The machine switches back to normal
mode when you type a second double quotes
These functions share keys on the keyboard. character (so ending the string) or if you give a L

so that you often have lo use k

Start up the 64, type a double quote and


to choose the function you really need. then give all the control functions, one by one. k

You won't have forgotten that you can set the See how each one looks on the screen, and fill in
frameand background colours using 'POKE' rhe table.
instructions and code numbers from the table on See how each one looks on the screen, and
page 19. fill in the table on the next page. k
The 64 can also make drawings on the
screen under the control of a program. Every
>rogram has the use of all the screen control
unctions: it can select any colour for its charac
ters, it con clear the screen whenever it needs to, k

and it can move its own cursor (which is invisible


\o you) to any position using the cursor control l~

functions.
Of course the 64 only does these things k.
when obeying the commands you have given it.
To put screen control functions into a command is ki
easy: we simply include them in strings alongside
the other characters to be displayed. You might
find this a bit puzzling atf irst. Surely, if you type a
string and include a screen-clear function in it, the
whole screen will disappear as you type? In foci
this does not happen, as the next experiment is
designed to show. w
Function Key Struck Symbol displayed

Clear Screen and GEE

Cursor home

Cursor up and

Cursor down

Cursor left and

Cursor right

Black and

White and

Red and

Cyan and

Purple and

Green and

Blue and

Yellow and

Orange and 1

Brown and 2

Light Red and 3

Greyl and 4

Grey 2 and 5

Light Green and 6

Light Blue and 7

Grey 3 and 8

Reverse on and

Reverse off and Mffl


Now let's try some of these controls in action.
First make sure your TV set is properly adjusted When you strike gmm|||^^ , the control
for colour, by using the TESTCARD program if functions are actually obeyed. The screen is
need be. Get a white background by typing the cleared, the cursor is moved three places down
command POKE 53281,1 and three along, and the word PARIS appears in
red half-way towards the middle of the screen.
Next get the computer to display the word Try it for yourself.
"EDINBURGH" in yellow. Type in the command In general, you can get the 64 to paini
words and symbols anywhere you like by
PRINT1 and fl&EDINBURGH including the right number of cursor shifts in a
string.
When you get the computer to draw a picture
hold down
you type on the screen, you don't want to spoil everything
by displaying READY and the flashing cursor. A
What actually appears on the screen (all still way out of this difficulty is to use a 'loop stop', or a
in blue) is GOTO which jumps to itself. Once the computer
reaches this command, it will start chasing its own
PRINT" 0 EDINBURGH". The reversed n tail, and it won't display READY until someone

hits the UUi key. This program, for example,


reversed will display LONDON in white in the centre of a
black screen: ,_,.
12 times
symbol is the code for "yellow". 10 POKE 53281,0 —"^
Now hit the ^^■■■■^^B key. The word 20 PRINT
EDINBURGH appears on the screen, in yellow.
This experiment illustrates the principle quite
and ESSk LONDON'
clearly: when a control function is typed inside a
string, it is not put into effect when it is typed, but
only obeyed when that string is displayed by the 17 times
computer.
You will see that the flashing cursor has been 30 GOTO 30
left yellow. Change it to black or blue, whichever
you prefer, by typing the correct control function
— without quotes.
A PRINT command which gives you a colour
Key this program in, run it, and then stop it
change can be made part of a program, just like
any other command. Key in and run the
with the IJlUJl key. The screen will still be
following:
black and the cursor white, but you can quickly
get back to the normal state of affairs by holding
10 PRINT" GLASGOW"

down BBi and hitting BmHB .You'll remember


20 PRINT" and MHH INVERNESS'
you can always do this if the machine gets stuck
for any reason; it is better than switching on and
30 PRINT "
off because your program isn't lost when you do
it.
and 1331 ANDREWS" As a short exercise, get the 64 to display
words and patterns of different colours at various
40 STOP
positions on the screen. Remember that the
Command 30 shows that you can put more
than one control function into a string.
■HiH and mm function clears the screen,
Screen and cursor control functions can also so if your program has a sequence of PRINT
be put into strings. Type thefollowinr- statements, only the first one should begin with
this function — although some of the others could
CRSH I CHSfl
PRINT
well start with by itself.
ICRSR ICRSR | CTRL

On the screen this comes up as

PRINT i^QQQ J J J £ PARIS'

reversed symbols
Experiment 9.1 completed
Stop this program, wait a few minutes, and
restart it. You will see that the time is still correct,

EXPERIMENT and that the clock has been running all the time.
This method of displaying the time is not
attractive. You can make the 64 into a respect
able digital clock by a program as follows:

command 10: Selects a purple frame

command 20: Selects a yellow background

command 30: Clears the screen

command 40: Moves the machine's cursor home,


then down 9 lines and across 6
spaces; no new line needed

command 50: Displays Tl$


You will know that modern clocks and
watches are controlled by quartz crystals, and command 60: Jumps back to command 30.
are extremely accurate over long periods of time.
The COMMODORE 64 also incorporates a Write down the code for this program in the

second, and it is used — among other purposes — try it out. If you get really stuck, look up the correct
to control an internal diqital clock. This clock version in Appendix B, but don't go on until you

like a string variable, so that you can display the


time on the screen whenever you need. The name
of the clock variable is Tl$.
When you first start up any clock, you have to
set it to the right time. The 64 is no exception. You
can adjust the clock from the keyboard, by typing
a command like

Tl$ = "193746"

Thfs"would set the clock to 7.37 and 46


seconds in the evening.
If you want to set the clock very accurately, it
is best to wait for — say — the nine o'clock news
on the radio. Just before it starts type

Tl$ = "090000"

and then hit ^^HUHill^^B as you hear the last


'pip' of the time signal.
Once the 64's clock has been adjusted, it
will keep time, to within a few seconds a day, until
the machine is switched off. There is no need for
you to reset it or to change it from within a
program.

To display the time, you simply mention Tl$ in


a PRINT command.
Now set up the 64's clock, using your own
watch (it doesn't matter if the setting isn't very
accurate). Then display the value of Tl$ several
times, using a PRINT command. See how the
seconds change from one time to the next.
k i i-. i ii .- .■ ..ii.

running the program

10 PRINT Tl$
Experiment 9.2 Completed
20 GOTO 10
and run the program again.
What happens if we want more than one

EXPERIMENT block of colour in the same picture? The trick is to


move the machine's cursor to the first line of the
area, and then to fill it in, without interfering with
the colour already on the screen. We'll look al
two examples:

(a) To paint a blue 10 x 10 block just below the


red one:

The lower half of the screen is empty, so we


don't need to worry about spoiling anything
else. Furthermore, after drawing the red
block, the cursor will be in the right place. We
can extend the program by adding

Controlled loops are often useful in drawing 70 PRINT and


shapes on the screen. Suppose you want a 10 x 10 10 spaces
block of red dols in the top left-hand corner. This
can be done by displaying ten lines, each with ten 80J=J + 1
• graphics:
90IFJ<11THEN70
10 PRINT"
100 GOTO 100
20J=1
Notice that the loop stop has been moved to
30 PRINT' the end of the program where it belongs. J is
used as control variable in both the red and
blue loops: this is perfectly alright because
40J=J+1 the red block is completely finished before
the blue one is started, and J isn't asked to do
50IFJ<11THEN30 two jobs at the same time.

60 GOTO 60 [b) To paint a 10 x 10 black block beside the red


one.
This program combines several of the ideas
we have already met in previous units. The semi The starting line is the top one, so in drawing
colon at the end of command 10 prevents the the black area we have to be careful not to
machine from starting a new line after clearing damage the red block which is already there.
me screen, so that the first line of red dots This can be done by moving the cursor home,
appears at the top. Statements 20 to 50 form a and displaying 10 lines, each of which begins
controlled loop and 60 is a loop stop. with 10 "cursor right" movements to jump
Enter the program and run it as it stands. over the red. The program extension is
Then stop it, and try for yourself the effects of
100 PRINT -10 times
(a) removing the semicolon after"
110J=1

(b) changing the 11 in command 50 to some 120 PRINT


other value (say 15]

(c) removing command 60

You can of course make these changes by LISTing


and editing. Remember to get the cursor colour 130J=J + 1
back to white or grey before you start!
To get a solid block of colour we use 140IFJ<11THEN120
reversed spaces. Try changing line 30 to
150 GOTO 150
PRINT

10 spaces
Now assemble this program, type it in and We arrive at
try it out. Note that it has three separate loops
which are executed one after the other. 10 POKE 53280,0
Try extending the program to put a purple
block under the black one... 20 POKE 53281,2
As a final exercise, try writing programs to
display some simple flags, or other patterns 30 PRINT" ^Di and B ";
which fill the whole screen. You will need your
wits about you, because various pitfalls lie in 40J = 1
wait.
50 PRINT " ^M and Jil ^MonH
• The normal meaning of a semicolon at the
end of a PRINT command is "Don't start a |!Wft *-13 spaces -»^^^J and
new line". If the 64 is made to put a charac
ter into the right-most position of a line, it
automatically moves its cursor to a new line.
Displays which are meant to fill complete 60J=J + 1 72
lines should therefore be followed by
semicolons unless you actually want a blank 70IFJ<25THEN50 ^^^
line to follow.
80 PRINT "^^|andi^BBand
• There is no way of using a PRINT command
to write a character into the lower right-hand USA- 13 spaces - ^^B °nd
corner of the screen without making the
whole screen move up.
The way to get this square the right colour is
to select the entire background colour
accordingly. 90 GOTO 90

You should plan your painting carefully, Run this program and study it carefully until
you understand every symbol. Now try some of
to write your programs, be prepared to make your own flags, but keep off from ones with
plenty of mistakes, and don't be upset if it takes diagonal elements! Try the Iceland flag which is
shown on page 21. You can check your answer
with the one shown in Appendix B.
lust give up!
To start you off, we'll give you a program for
the French flag.
Experiment 9.3 Completed

The self-test program for this unit is called


UNIT9QUIZ.

blue white red

Vve"ll make the central white stripe 14


characters wide,and the other two 13 each.
13 + 14 + 13 = 40.
Appropriate starting colours are a red
background and a black frame.
We can build up the flag by displaying 25 lines,
each with thirteen white squares and fourteen blue
ones. Rememberthat the last one must be
different, because it mustn't be followed by a new
line. We can put the first 24 lines into a controlled
loop, but the last will need a command on its own.
In the previous units we came across the idea Suppose you are designing a program for
that commands can be written once, but obeyed someone else to use. You begin by deciding which
many times over. This happens whenever you put quantities you are going to leave undefined, and
a command in a loop. your program is going to ask the userto supply. In
On a much larger scale, a similar thing our example the rate of exchange is clearly one
occurs with complete programs. Most programs such quantity: it must be unknown to the pro
are designed to be useful, which means that they grammer, but known to the user! You allocate the
are stored and distributed on tapes or ROM- unknown quantities to variables, and give them
packs and used many times by different people. If names accordingly. For instance, a suitable name
you want an example, look at the various taped for the rate of exchange could be RE. You can
programs which form part of this course. then write your program using symbolic names
Let's begin by considering all the programs instead of the actual values (which you canno)
which you personally have written so far. The know in advance). Thus line 40 of the exchange
drawback with every one of them is that no matter program could read
how many times you run it, it always produces the
same result. Hardly very useful! 40PRINTPS,RE*PS
To give a specific example, let's go back to
the program which calculates and displays a Of course there is something missing from
conversion table between £UK and Italian Lire. H this description. You may not know the values of
the variables, but the machine must do so when it
runs your program. The command which lets the
10 PRINT "£", "LIRE" user put in the missing information has the key
word INPUT. This is followed by the name (or
20 PRINT names) of the variables needed. When the INPUT
command is obeyed it waits for the user to typea
30 PS-5 value, which it then stores in the named variable.
The rest of the program, which uses this variable,
40 PRINT PS, 2350* PS can now be obeyed.
Before giving an example, we stress one vital
50 PS=PS+5 point: every program with an INPUT command
must tell the user exactly what is wanted of him.
60IFPS<80THEN40 This can usually be done with PRINT statements.

70 STOP

On the day Ihe Unit was written, the rate of


exchange really was 2350 Lire to the Pound, so
the program would hove given correct results. By
today, however, the rate has fallen to 2175. Any
bank which used this original program to sell Lire
in exchange for Pounds would be seriously out of
pocket.
How could matters be improved? If you are
a programmer one obvious approach would be
to alter line 40 to read

40PRINTPS,2175*PS

Unfortunately this idea won't take you very far.


Most people who use computers aren't program
mers, or even if they are, they are just not interested
in the guts of your program!
To make programs more flexible, more
adaptable to everyday needs, we need a new
facility: one which lets the usersupply information
which the programmer couldn't have known
when the program was written. A program which
allows this can be used by lots of different people,
and lets each one solve their own particular
version of a problem. For instance, suppose thai
the money conversion program allowed the user
to tell it the current rate of exchange every time it
was used; it would immediately become useful to
banks all over the world, and it would work
properly for any imaginable exchange rate.
his information, it was actually obeying the INPUT

EXPERIMENT
command.
The INPUT command comes in several
slightly different forms. We'll look at some
examples, and mention a few general rules.

1. Clear the 64 by typing NEW, and type in

10 PRINT "WHAT'S YOUR NAME"

20 INPUT N$

30 PRINT "HELLO

Run this program and see what happens. The


example shows how the INPUT command
works with strings as well as numbers. You
Study the following program carefully: could use this sequence— or something like
it — near the beginning of any program
3 PRINT "TYPE TODAY'S" where you wanted the computer to be
'friendly' to the user. If the program was o
4 PRINT "RATE OF EXCHANGE" quiz of some kind, you could use the value of
N$ in commands like
5PRINT"BETWEEN£ANDURE"
40 PRINT "NO^^fl "; N$;". YOU
6 INPUT RE CAN DO BETTER THAN THAT"

10 PRINT "£","URE" (If you are in any doubt about what this
command displays, tack it on to the end of
20 PRINT the program already in the 64, and run the
program again.)
30PS=5

40PRINTPS,RE*PS
10INPUT"NAME";N$
50 PS=PS+5
20 PRINT "GOODBYE
60IFPS<80THEN40
This example shows how a short piece of
70 STOP descriptive information can be included in
the INPUT command itself. The information
shows upon the screen as a guide to the user,
Notice how the program doesn't assume any just before the ?.
particular rate of exchange, but uses the variable Command 10 in the example is equivalent to
RE to represent it wherever it is needed. The the sequence
program begins by telling the user what is needed
and asking him to supply a value. PRINT "NAME";
Enter the program, check it carefully, and
lypeRUN. Now pretend you are a user: a money INPUT N$
changer who knows nothing about program
ming. On the screen the machine is asking you to Notice that the string of descriptive words
type something, so you enter the appropriate must be less than 70 characters long, and
that it must be followed by a semicolon.
figure, and then strike the ^mm^J key.
As soon as you do this, the screen fills with a Lastly, try
conversion table that lets you start business today.
Run the program many times, and notice 10 PRINT "GIVE TWO NUMBERS TO
how well it can handle different rates of BE ADDED"
exchange. Even if the Lira were to be revalued to 20INPUTA,B
a level of 23.7 to the £, the program would still
produce sensible answers. 30 PRINT "SUM=";A+B
Now switch back to your personality as pro
grammer. When the program was running, 40 STOP
showing a cursor and waiting for the user to type The INPUT command now expects two
values, and the user must type them separated

by a comma or by pressing tne^^M^^M


key. (That is, he or she could type either —
EXPERIMENT
say 43, 19

or { 19

In general, the INPUT command may ask the


user for any number of variables, but it is better to
11 keep the number down to two to prevent confu
sion. In the command itself, the names of the
variables are separated by commas.
Writing useful programs is easy provided
When you have run this program a few times,
you remember that the programmer and the user
pretend you are a really stupid user and try typing
□re two different people. The user can't be
nonsense — for example assumed to understand programming (so he
cannot be expected to LIST your program to find
out what it does). In general the programmer may
DONALD,DUCK
not 'talk to' the user except by making the 64
display messages on its screen, and the user can't
The computer will accept anything at all as a
get back to the programmer at all, so the
string, but if it is trying to input a number, and is program had better not leave any questions
given something which couldn't possibly be a
unanswered!
number, it will display the message When you are designing a program, pretend
you are a fly on the wall watching someone trying
? REDO FROM START
to use it. Try to imagine everything that could go
wrong, and prevent it by making sure the
and give you another try.
sometimes you want to stop a program wnen
When your program is written, you <
it is obeying an INPUT command and displaying exercise it by pretending you are a user; later, as

acursor.Undertheseconditionsthe Uili key by


itself is disabled. You must hold it down and strike
your guinea-pig has to ask you any questions
about what to do, or what the answers displayed
the liilifl key at the right of the main
actually mean, your test has failed and you
keyboard. Try it! should redesign your program accordingly.

Experiment 10.1 Completed


Write programs to do the following jobs: (b) To ask the user (who is assumed to be a
married man) for his surname, and then for
[a) To display any multiplication table selected his wife's Christian name; and then to display
by the user. his wife's full name.

Solutions are given in Appendix B, but don't


look at them until you have done everything you
can to write these programs by yourself.

Experiment 10.2 Completed

The quiz for this Unit is called UNIT10QUIZ.


One of the most interesting features of
programming is its richness and variety. The
same computer, if properly programmed, can be
made lo serve as a calculator, a teaching
EXPERIMENT
machine, a musical instrument, a monitor to look
after a sick patient in hospital, or almost anything
else useful you can think of. This power comes
from the huge number of ways that a few basic
types of command can be put together.
So far, our total vocabulary of commands
used within programs is only seven:

PRINT, LET, GOTO, IF, INPUT, STOP and POKE

Of course there are other BASIC commands you


still have to learn about; but in this unit we'll
explore the potential of the commands we
already know.
The most flexible command of all is the IF. In Let's imagine you are setting up a computer
previous units it's been used to control loops, bul ised marriage bureau, and the first facility you
it is also useful in many other ways. For instance it plan to provide is a program to advise on the
can test data or items of information supplied by ages of the partners your customers should look
the user, so as to steer the computer along the for. By tradition a man should marry a girl of half
right course of action. his age, plus seven. This implies, if you think
about it, that a girl should look for a husband who
is double her age, less 14.
Clearly, the advising program must begin by
asking for the client's age. Then, to give the right
advice, it has to find out whether the cl ient is a
man or woman. The program will be used both by
men and women, so it must include a separate
group of commands to give advice to each of the
two sexes. Finally there must be an IF command
to select the group actually needed on a
particular occasion.
A first version of the advising program is
given below. Study it carefully and work out
exactly why each command is included:

10 INPUT "WHAT IS YOUR AGE";AG

20 INPUT "MALE OR FEMALE";SX$

30IFSX$="MALE"THEN70

40 PRINT "YOU SHOULD LOOK FOR"

50 PRINT "A MAN OF";2*AG-14

60 STOP

70 PRINT "YOU MUST FIND"

80 PRINT "A GIRL AGED"; AG/2+7

90 STOP

You will have spotted that the variable AG is


used to hold the client's age, and SX$ his (or her]
sex. The condition SX$="MALE" is true if the
client answers MALE to the question "MALE OR
FEMALE?". The expression AG/2+7 is BASIC'S
way of saying "half your age plus seven", and
2*AG-14 means "twice your age less fourteen".
When you have looked at the program, tesi
your understanding by predicting as accurately
□syou can what will appear on the screen (a) for
a man of 20, and (b) for a girl of 22. Use the boxes
below. The first box is partly filled in for you.

WHAT IS YOUR AGE? 20

MALE OR FEMALE?

Now enter the program into the 64. Try it out,


on behalf of various sorts of client, and check thai
both your predictions are right.
This simple example shows you that the
action of the compuler needn't be fixed in advance
by the programmer, but can be made to depend
on the information supplied by the user.
Programs often have complicated sets of
decisions to make, so to plan them we use a
special type of diagram called a flow chart. The
flow chart for the advising program is like this:

INPUT AGE

INPUT SEX

DISPLAY: "YOU DISPLAY: "YOU


TRUE FALSE
MUST FIND A SEX- SHOULD LOOK FOR
GIRL AGED MALE" A MAN OF
'A AGE + 7" 2*AGE-14"

STOP STOP
A flow chart consists of a number of blocks one playing a board game. At the beginning Ihe
connected by arrowed lines. There are four kinds player's token (motor-car, top hat or whatever]
of blocks: goes on the first block. Whenever the action
described in a block has been completed, the
(a) A square or rectangular box. The box holds token is moved along the arrowed line to the next
the description of a simple action, which can block.
later be translated into one or two BASIC When the token lands on a diamond, the
commands. In our sample flow chart, the top player looks at the condition and decides whether
two blocks are examples of this type. The it is true. If it is, then he moves his token to the box
arrowed lines show that the program starts at the end of the TRUE line, but otherwise, he
by obeying the first block, and then goes on follows the FALSE line. Eventually he reaches a
to the second one, in that order. STOP block, which is the end of the game.
The point of this illustration is to help you see
[b} A diamond holds a condition, which may be two very important things about computers:
either true or false. The diamond has one line
going into it, but two coming out, labelled A computer can do only one thing at a time
TRUE and FALSE (or sometimes YES and [not several)
NO). The diamond corresponds to an IF
command. It instructs the computer to test the The order in which the computer does things
condition, and to follow either the TRUE or is determined by the program.
the FALSE line according to the result.
It often surprises people that there is no flow
(c) The termina/block, which tells the computer chart symbol fora simple GOTO command. This
to stop obeying the program. It is a small is because the GOTO doesn't specify ony action
circle with the word STOP. at all; it only affects the order in which commands
are obeyed. It is wel I represented by a connecting
[d) The cloud (which doesn't appear in our line. For instance:
example). This is a symbol for an action
which is too complicated to be described in 10Q=1
detail. Usually, the cloud can be expanded
into another complete flow chart, just as a 20 PRINTQ;Q*Q
country-wide road map is backed up by
detailed plans of different towns. 30Q=Q+1

40 GOTO 20
A flow chart is really a 'map' of a program. A
computer running a program is a little like some has the flow chart

LETQ-1

DISPLAY Q
ANDQ2

ADD 1 TO Q
u
Now draw a flow chart for the following
program. Use the plastic stencil for your blocks:

10S=1

20 PRINT S,12*S

30S=S + 1

40IFS<13THEN20

50 STOP

84

[Check your answer in Appendix B

Expenmenf 1U Completed
Let's do some more exploring. One feature of

EXPERIMENT
our marriage guidance program was that if you
give it incorrect data, it gives you silly answers.
The name for this fact is "GIGO", which stands
for "Garbage In, Garbage Out". For instance, a
qirl who gave her age as 6 would be told to find a
lusband aged -2: not even a gleam in his
parents' eyes! Furthermore, if the user gives any
answer other than MALE to the second question,
the program assumes she is female. Someone
who replies "M" or "MAN" or "MASCULINE" or
"BOY" will be told to find a man as partner.
There are plenty of programs which do
behave in this idiotic way, and they have given
computing something of a bad reputation. In
practice you can avoid the worst of these troubles
by passing the user's information through a filter
to make sure that it is at least sensible.
To begin with, we'll draw a new flow chart
for the whole program, replacing the detailed
input boxes with a cloud:

GET SENSIBLE
VALUES FOR
AGE AND SEX

DISPLAY: "YOU TRUE FALSE DISPLAY: "YOU


MUST FIND A SEX = SHOULD LOOK FOR
GIRL AGED 'MALE' A MAN OF
Vi AGE + 7" 2* AGE— 14"

STOP STOP

We use a cloud because we haven't yet fixed


the details of what we actually mean by
"sensible". The cloud is useful because it allows
us to plan the program as a whole unit, but it
involves an obligation to work out the action in
greater detail. At the stage we have reached now
trie planning is not complete, but that doesn't
mean that the main flow chart is useless or wrong!
Well, what does "sensible" mean? First let's
Ihink about the age of the user. The lowest likely
value is 18, because people under 18 don't often
come to marriage bureaux. The upper limit is
harder to decide, but according to the Guinness
Book of Records the oldest living person is 115.
We'll take this figure as a guide.
We'll design the program so that when the
computer asks for the client's age, it decides
whether to accept it as reasonable. If not, it
displays a reason, and invites the client to give a
more realistic figure. Look at this flow chart:

INPUT AGE

\ FALSE DISPLAY "YOU ARE


AGE> = 18? >-£— TOO YOUNG TO
/ GET MARRIED"

TRUE

FALSE
DISPLAY "I DONT
AGE<=115?
BELIEVE YOU"

When it comes to the second question, there


TRUE
are lots of ways the client could indicate whether
fhey're male or female. In fact there are so many
rfiat we could never think of them all. Instead we'll
make the program "understand" only two
words: MALE and FEMALE. If the reply is given in
any other way, the program will ask for it to be
repeated. The correct bit of flow chart is

INPUT SEX

SEX =
'MALE'

FALSE

FALSE DISPLAY "YOU MUST


SEX =
>-•— ANSWER MALE OR
'FEMALE'
FEMALE"

TRUE
Now we can pot these two fragments
together to give a complete flow chart for the
cloud which is to get sensible values for AG and
SX$. r—

INPUT AGE

\FALSE DISPLAY "YOU ARE


AGE> = 18? >-*— TOOYOUNGTO
/ GET MARRIED-

DISPLAY "I DON'T


AGE <=115? BELIEVE YOU"

-N

IJ'
TRUE
SEX =
)
'MALE" i

FALSE

SEX =
FALSE
DISPLAY "YOU MUST
ANSWER MALE OR
I1JI
'FEMALE' FEMALE"

Once a set of flow charts has been carefully TRUE


drawn, Iranslating them into a program is a
straightforward job. We start at the main flow
chart, but the first block there is a cloud, so we
refer lo the subsidiary flow chart and translate it.
Then we go back to the main chart for the rest of
the program.
You will notice that two of the diamonds in
the subsidiary chart have a TRUE line which goes
straight to the end. The simplest way of filling in 2. Study Ihe problem carefully, ond work out
labeTnumbers of the corresponding IF command one or two simple examples yourself. Keep
is to put a REM at the end of the cloud and use its the answers to check against the computer.
label number. The REM does nothing but act as a
convenient anchor point: 3. Begin by deciding what variables you need.
Jot down their names, types and purposes in
We get: a "glossary". For instance, the variables for
the advisory program would have been
10 INPUT"WHAT IS YOUR AGE"; AG noted down as:

20IFAG> = 18THEN50 Name Type Purpose

Number Age of Client


30 PRINT "YOU ARE TOO YOUNG TO BE
MARRIED" String Sex of Client, as
"MALE" or "FEMALE'
40 GOTO 10

50IFAG< = 115THEN80 4. Draw a flow chart for the program. Be


nrepared to make lots of mistakes, and don'l
60 PRINT "I DON'T BELIEVE YOU!" oe surprised if you redraw the chart half a
dozen times over. Keep on until you are satis
fied. Programming is hard work, and this
70 GOTO 10
part of the job — flow charting — is where
80 INPUT "MALE OR FEMALE"; SX$ most of Ihe effort comes.

90 IFSX$="MALE"THEN 130 5. Now translate your flow chart into BASIC.


This should be easy. If it isn't, it means thai
100 IFSX$="FEMALE"THEN 130 you haven't done your flow charting
properly, so go back and do it again.
110 PRINT'YOU MUST SAY MALE OR FEMALE"
6. Now — at last — switch on your 64, and
enter the program. Apart from a few typing
120 GOTO 80
mistakes, ft should run without any bother.
130 REM AG AND SX$ HAVE SENSIBLE VALUES Test it out on as many different examples as
you can, including one you worked oul
This is followed by the rest of the program as earlier. Finally, preserve the program on
before (but with adjusted label numbers]. tape (if you want to keep it] and file away
your flow chart and variable glossary.
140IFSX$="MALE"THEN180
I have just described the way a good profes
150 PRINT "YOU SHOULD LOOK FOR" sional sets about programming. Lots of people
don't do it that way at all — they sit down in front
160 PRINT "A MAN OF"; 2*AG-14 of their computers and compose their programs
straight on to the keyboard. This method some
times works for very small problems, but usually il
170 STOP
leads to long, uncomprehensible programs
180 PRINT"YOU MUST FIND" which only work some of the time, and which the
programmer finds impossible lo alter or put right.
190 PRINT"A GIRL AGED"; AG/2 + 7 It also takes much longer to gel anything working
at all. However, this fact isn't at all obvious — it
200 STOP
seems quicker to ignore all Ihe planning and gel
on with the job. This, in truth, is why so many
people program so badly.
Enter this program into the 64 and try it out.
For sensible values of age it will behave just like You have a choice; you can either do as
advised and quickly become a competenl
the first version, but ii will be much better at
programmer, or you can learn the hard way,
detecting and refusing silly answers. It has the
which will take you very much longer.
important quality of robustness, or the ability to
stand up to abuse.
To end this unit, you will write a program of
your own. Before you start, here are some points
of advice:

1. Get plenty of clean paper, a pencil and a


rubber. Switch off your computer.
Now plan, flow chart, write ond test a
program for the following problem:

In Ruritania the house-tax is levied as follows:

For each door: £57

For each window: £12

For each thatched roof: £38

For a tiled roof: £94

Assuming all houses must be either thatched


or tiled, write a program to ask for the details of
any house and display the house-tax payabl-
For instance, the right answer for a thatched
cottage with one door ond two windows would be
£(38+57+2*12}= £119.
Get your program to display the rates for the
following houses (assume all the doors and
windows are atthefront): t
EXPERIMENT

91
Load and run the program UNITl 1 PROG.
When you have listed it, examine the code, and
draw up a flow chart and a glossary for it.
92

Experiment 11.3 Completed


You don't have to look deep into any The NEXT command mentions the name of
program to find a loop somewhere. Loops are so the control variable, as a check to help you read
common, and so important, that the BASIC the program.
language gives you a short-hand method of Every FOR command must have a corres
writing down the essential details. ponding NEXT, and between them they enclose
You'll remember that there are four vital the body of the loop.
parts to the control of any loop: In flow charts we show loops in a special
way, using blocks which can't easily be mistaken
The choice of control variable for other kinds of action:

The starting value for the control variable

The last or final value for the control variable

• The increment, or amount by which the


First
control variable grows every time round the
value
loop. Control
variable
All these parts can be fitted into one special
command which uses the keyword FOR. This is
all that is needed to set up a loop except for a Final
NEXT command to mark the end of the loop body. FORJ value
Compare the following two programs, which
give exactly the same result;

Increment
10J=4 10FORJ=4TO20STEP2

20 PRINT J,J*7 20PRINTJ,J*7


Loop body
30J=J+2 30 NEXT J

40IFJ<22THEN20

(Using IF .... THEN) (Using FOR.... NEXT] NEXTJ

In both cases:

Control variable is J

First value is 4
The computer goes
Last value is 20 back along this line
Increment is 2 as long as the loop
has still to be ,
The example shows how the FOR command repeated. /
is built up When the loop body
ends (that is, when the
control variable reaches
its final value) the
Always TO and
computer goes down this
Keyword STEP
line.

FOR J TO 20 STEP

First
value Last
Control value
variable
Incremeni
Now translate the following program into
FOR—NEXT notation. Check your answer by

EXPERIMENT running both versions on the 64 and ensuring


that they give the same answers:

10 PRINT "NINE TIMES TABLE"

20S=1

30 PRINTS; "TIMES9 =";

40 PRINT 9*5

50S=S+1

60 IF S<13 THEN 30

70 STOP

To help fix the details of the FOR command in Your translation:


your mind, look at the following short programs
and write downwhatyou think they will make the
COMMODORE 64 display. Then check your
answers on the machine itself:

(i) 10FORQ=1TO16STEP5

20 PRINT Q;

30 NEXT Q

There are a few points about the FOR and


40 STOP
NEXT commands which you ought to remember:
Your prediction:
(a) If the increment or step size is 1, the "STEP 1"
at the end of the FOR command can be left
off. The 64 understands what is meant.

(b) The loop control can be made to count back


wards by using a negative step size. The
program

(ii) 10FORR=38TO50STEP3
10FORX=10TO5STEP-1
20 PRINT R;50-R
20 PRINT X;
30 NEXT R
30 NEXT X
40 STOP
will display: 10 9 8 7 6 5
Your prediction:
in that order.

(c) The body of the loop is always obeyed at


least once, even if the final value is less than
the starting value. For example,

10FORR=5TO3

20 PRINT R

30 NEXT R

will display

(d) The values in the FOR command needn't be


numbers but can be expressions which
include other variables. For example, the
following program will display the number the body of a loop needn't be short and simple,
of heart symbols requested by the user. Try it but can be as complex as you like —the thing to
out and study it carefully: remember is that it gets executed every time the
computer goes round the loop.
Suppose you've been asked to build a
10 INPUT "HOW MANY HEARTS"; H
square-based pyramid, out of cannon-balls.
We'll number trie layers 1,2,3, starting from
2GFORK=1TOH
the top. Layer 1, being the point, will need just one
cannon-ball. Layer 2, the second one, will need
30 PRINT "
four balls arranged like this:
40 NEXT K

50 STOP

[e) The control variable can't be a string. For


instance, the "command"

/FOR X$ = "A^rtV'A&BBtf" STEP "B"


- NOT BASIC
Layer 3 will need nine balls, layer 4 — sixteen,
would give a SYNTAX ERROR, and you and soon.
aren'l allowed to use this construction. Clearly the number of cannon balls you need
Using this knowledge, predict the outcome for the whole pyramid depends on how many
of the following programs, and check your layers you plan to build. A three-layer pyramid
results on the computer: needs 1 +4+9 or 14 cannon balls; one with four
layers will require 1+4+9+16 or 30.
If you plan a very large pyramid, these sums
will get ratner long and boring, and you might
decide to write a computer program to do them
(i) 10FORA=1TO4
for you. This program will answer the question,
20 PRINT A*A;
"How many cannon balls will I need for a
30 NEXT A
pyramid of 'so many' layers?".
40 STOP r
In designing the program, a key factor is the
number of cannon balls in each layer. The
numbers 1 4 9 16 and soon look familiar,
and in fact you soon spotthat the number of balls
[ii) 10FORB=3TO0STEP-1 in each layer is the square of the layer number.
20 PRINT B; For instance, layer 7 will need 7 * 7, or 49 cannon
30 NEXT B balls.
40 stop r Now for the detai Is of the program. Let's
begin by thinking about the variables we'll need.
Our overall plan will be to consider the
layers one by one. We will get the computer to
work out how many balls are needed for that
10FORC = 5TO4 layer, and add this number to a 'running total'. Al
20 PRINT C; the beginning the running total must be set to
30 NEXT C zero. At the end, when all the layers have been
40 stop r taken into account, the running total will show the
number of cannon balls wanted for the whole
pyramid. This is the answer to the problem.

A suitable name for the running total is RT.


20Y-9
30Z=2 We need two other variables:
40FORW=XTOYSTEPZ
50 PRINT W; |i) The number of layers in the pyramid.
60 NEXTW Remember that the programmer doesn'l
70 STOP F know this number; it is up to the user to
supply any value he wants. A good name for
this variable is L.

So far we've been concentrating hard on the [ii) As the program runs it will deal with layer 1,
detailsofFORandNEXTcommands,sowehave then layer 2, then layer3,and soon. We
carefully chosen the bodies of the loops being need a variable to indicate which of the L
controlled to be as simple as possible. In practice different layers the program is dealing with
at any moment. A suitable variable name is so the PRINT command can only come offer the
V. Since V is going to take all the values loop lias ended.
between 1 and L, the number of the bottom Now we've got far enough to draw a flow
layer, we can guess that it will be the control chart. It is
variable in a FOR command, thus:

FORV=1TOL

INPUT L

NEXTV

The glossary for our program is thus:

Name Purpose
RT=Q
To keep running total of cannon balls

Number of layers in pyramid

Number of layer being dealt with a\ FORV


any moment.

1 L 1
Next, we'll write down some of the actions
our program needs to take:

Add V squared (This adds in the number of


to RT cannon balls for layer number V) ADDV*V
TORT
Print RT (Displays result]

Set RT=0 (Starts RT off from zero)


NEXTV
Input L (Asks user how many layers
there are in his pyramid)

FORV=1 TO L (Loop control for taking every


DISPLAY
NEXT V layer into account)

STOP

These are all the fragments of program we


need, but they have still to be put together in the
right order. We have already decided that there STOP
must be a loop, and it will greatly help us if we
can say, for each command, whether it should be
executed
And the corresponding program is
before the loop starts
10 INPUT "NUMBER OF LAYERS"; L
or inside the loop (as part of the loop body)
20 RT=0
or after the loop has ended.
30FORV=1TOL
We can use various clues. The program has
to know how many times to go round the loop 40RT=RT+V*V
before the loop itself can start, so input L must
come before the loop. So must the command 50 NEXTV
which sets RT to zero.
The total number of cannon balls for the 60 PRINT RT;"CANNON BALLS NEEDED"
whole pyramid includes at least some for each
layer. The command to add a layer's worth to RT 70 STOP
has to be repeated many times, and so it goes
inside the loop. Enter this program and try it out.
Finally, the computer can't give you the righl Now here is a problem for you. In the game
answer until it's taken ah the layers into account, of cricket, a player can have a number of separote
'innings' during the season. Each time he scores

EXPERIMENT
some 'runs': many if he is a good player or lucky,
or only a few (or even none) if he isn't so skilful. If
you want to know how well someone has played
over the whole season, you work out the average
number of runs per innings. You get it by adding
up all the runs he gains over the season and
dividing by the number of innings. For instance, if
he plays three times and scores 20,30 and 70, his
average is (20+30+70)+3 or 40 runs per innings.
Consider a program which does this calcula-
Hon for you. It has to ask you for the number of
innings, and then the score for each one, so that if
can add them up together. The overall display
would be like this:

NUMBER OF INNINGS?
We end this section with a problem which
you must solve without any help. If you go to the
SCORE? (20V_ Numbers Post Office, you ore quite likely to get stuck in a
typed by queue just behind someone buying a huge
SCORE? (30;
amount of stamps. You hear her saying:
SCORE? (70!
"Eighty-three at 12Vip
AVERAGE = 40
and One hundred and seventeen at 15l6p
Your job is to write the program for this
and Thirty-five at 75p"
problem. To make it easier, we'll give you a
glossary and all the commands, but in jumbled
and so on. When all the stamps have been
order and with their labels stripped off. Begin by
counted out, the clerk spends ages working out
drawing a 'skeleton' with the loop commands,
how much it all costs.
and then slot in the other commands in the right
Write a program to help the clerk. The
places. Finally, run the program on the 64 and
display should be something like this:
make sure that it works. If you get really stuck,
look up the correct answer in Appendix B, but
remember: this is an admission of failure!
The glossary and jumbled commands are:
NUMBER OF BATCHES?
ame
Name Purpose
BATCH 1
J Number of innings during season
NUMBER OF STAMPS? 20
) Control variable for loop
VALUE (EACH)?
..j Used to add up the total runs scored
BATCH 2
S Score for each separate innings
NUMBER OF STAMPS?
NEXTQ
VALUE (EACH)?
INPUT"NUMBER OF INNINGS"; J

INPUT"SCORE"; S BATCH 3

PRINT"AVERAGE=";RS/J NUMBER OF STAMPS?

STOP VALUE (EACH)?


RS=0
BATCH 4
FORQ=1TOJ
NUMBER OF STAMPS? Q00
RS=RS+S
VALUE (EACH)? (l4
Experiment 12.I Completed TOTAL DUE=2079 PENCE
The program should be 10 commands long
[including STOP). Four of ihese commands will
rorm the Body of a loop, obeyed once for each
batch. However, don't try to write the program
yourself until you have a proper design, with
glossary and flow chart. Take plenty of time.
If, after spending a good deal of effort, you

uniis to a place where you feel confident, and


work through the course material again.
Finally compare your answer with that given
in Appendix B.

Experiment 12.2 Completed

The self test quiz for Unit 12 is called


"UNIT12QUIZ".
or putting V instead of W) you might corrupt the
control program and make the machine behave

EXPERIMENT strangely until it has been switched off and on

Onefinal point: the machine will only make


sounds ifyou switch on the sound generator
first. This is done by the command

POKE 54295,0: POKE 54296,15

which should be included at the beginning of


every program which uses the synthesizer. The
prog ram should always end by turning the
sound off again. The right command is

POKE 54296,0

Here is a very simple example. The


program is designed to ask the user a question.
One of the many striking features of the If he gives the right answer, he hears a cheerful
COMMODORE 64 is its ability to make a huge 'pip', and gets an approving message. If the
variety of musical sounds and other interesting reply is wrong, the machine blows a raspberry
noises. The machine is fitted with a synthesizer and makes him try again. The flow chart is:
like those used by modern bands, with sound
generators, filters and special facilities which
can be controlled by a program written in
BASIC.
The synthesizer is a complex device, and Switch on sound
even a professional musician would find it a
challengetouseittoitsfull extent. Fortunately
you can doa great deal with a simple
approach, and this is what we'll concentrate on Display question:
in this unit. A more complete discussion of the "How much isl+1+1+1?"
.ynthesizer will appear in book 2 of the series.
To get some idea of the range of sound
effects you can create, load the program called
"SOUND DEMO" and run through its selection Input reply to X
of noises. Make sure the volume control on your
TV is turned up, or you might not hear anything!
Ifyou like any of these sounds and decide to
use them in a program of your own, this is quite
simple to do. Acomplete listing of SOUND
DEMO is given at the end of this unit, and all you
need do is to pick out the group of commands

1
Display Display
which correspond to your chosen sound and
"Wrong. Try again" "Well done"
copy them into your own program. You'll find
'I i i ■ r*r-ki i i. . ■._ l:l._
each (

t
M
this:

2000 REM *** HEARTBEATING *** Sound Sound pip to.

Raspberry
1 Ia

1 .
2150 REM *** END OF HEART BEATING*** Switch off
Sound
Commands to be copied ^i

Don't copy the REM commands themselves,


W
orthe RETURN which follows the final REM. You (Stop)
will usually be able to keep the line numbers
unaltered, but ifyou mustchangethem
Hi

remember to look out for IFs and GOTOs which


have to be altered accordingly. You don't need
to understand the details of the commands you
copy, but get them right! If you make a mistake
[especially in copying long numbers like 54272
□nd the corresponding code is: The pitch of any note you hear is directly
connected to its frequency, which is the number
10 POKE 54295,0: POKE 54296,15 of vibrations which reach your ear every
second. Middle C has a frequency of about 256
(Turn on sound] vibrations per second, and trie frequency
doublesforeveryoctaveyougoup(and halves
20 PRINT"HOWMUCHISl+1+1+1"; for every octave down).
30 INPUTX
40IFX<>4THEN3080 (b) The duration. Some notes go on sounding
50 PRINT "WELL DONE" for longer than others. In a musical score the
length of a note is usually shown by the
3010 W=54272 symbol used:
30 20 POKE W+6,8: POKE W+5,31
3030 POKEW+1,180: POKEW+4,33
3040 FORMM=1 TO 100: NEXT MM A long note
3050POKEW+4,0

[Commands to make a 'PIP', copied from


the listing of SOUND DEMO)
Asnorfnote

3060 POKE 54296,0 (Turn off sound)

3070 STOP In practice a musical symbol doesn't always


indicate exactly the same length, and we'll
(End of program] find it more convenient to measure the
duration of a note in milliseconds (units of
3080 PRINT"WRONG.TRYAGAIN" 1/1000 ofasecond).
4010 W=54272: POKE W+6,240
40 20 POKE W+1,4: POKE W+5,0: POKE (c) Some musical notes are sustained: that is,
W+4,33 they go on, at the same degree of loudness,
4030 FORNN = 1024TO512STEP-8 as long as they are being played. Wind
4040 POKEW+1,NN/256:POKEW,NNand instruments and members of the violin
255 family generally make sustained notes.
4050 NEXT NN Other sounds, such as are made by hitting
4060POKEW+4,0 or plucking, are called /rans/en/. Tney start

[Commands to make a 'RASPBERRY' nothing can be heard. A piano is a good


copied from the listing of SOUND DEMO] example of an instrument with a transient
note; once you've hit a key the sound dies
4070 GOTO 20 away even though you are still holding the
key down.
Now we'l I look at the way sounds are
actually generated. We have to get slightly (d) Every note has an attack rate, which
technical, and if the discussion doesn't appeal describes how quickly it builds up to its
loyou, you can safely skip to the next unit. loudest volume. A string which is plucked
Let's start with musical notes. Every note has with a hard object such as a plectrum
five main qualities or attributes which make it sounds at full volume almost
sound different from any other note: instantaneously, as does a percussion
instrument hit with a metal hammer. If a
(a) The pitch. Some notes are high, and some string is httwith a soft hammer or plucked
are low. In musical notation the pitch is with a finger it takes a little longer, and if the
usually indicated by the name of the note sound comes from a wind instrument it takes
[E^or F#) or by ils position on the stave: longer still to get the air vibrating. Of course
even the longest attack lasts only a small
fraction of a second, so you aren't conscious
A/ownote of it happening as the note starts; but it
makes a considerable difference to the
quality of the sound you hear.

(e) Transient notes have a decay rate, which is a


A high note measure of how long the volume takes to
die away when the note has been sounded.
Decay takes very much longer than attack,
and is usually measured in seconds. A shod
decay makes a note sound muffled, whilst a
long decay gives it a clear bell-like tone.
Information about the sustain level, attack
and decay rate is often shown on a graph called 1024,followed by a MmiH. You'll hear the
an 'envelope'. This is a technical term, and pitch go up by an octave (because 10 24 is
exactly twice 512). Change the frequency to -
throughout the time it is being played. Three say-700and the pitch will go down again. You
typical envelopes are shown below: can vary the pitch between 20 and 4000
vibrations per second.
Short attack
long decay Next, try changing the duration. The
volume /1 (e.g. triangle) program will accept any value between 1 and
5000 milliseconds. If the duration is shorter than
the decay ti me, the envelope wil I be cut short,
and you won't hear the full sound quality of the
attack decay time ». note. Try reducing the duration of your note to
50 milliseconds to hear this effect.
The 'sustain level' really has only two
Slow attack interesting vaiues:0for a note which decays,
no decay (sustained sound) and 15 for a note which is sustained. Try the
[e.g. trumpet) effect of both settings.
The attack value works differently from
what you might expect: the larger the number
volume
the s/owerthe attack. Attack values of 0 to 2
sound like real musical instruments, but higher
values let you hear the build-up of sound and
attack time
have a distinctly 'electronic' feel about them. Try
sustained sound 'A=6'for example!
Next, try out various decay values between
6 (which sounds muffled) and 11. For the longer
decay times, increasethedurationofthenoteso
fast decay
volume that you still hear the whole envelope.
(e.g.pluckedviolin
\ string) Finally, you should explore the four timbres
of'waveforms', as they are often called. They
attack decay
are:
• "Triangular" (which you get by typing "T")
[e) Finally, every note has a timbreor sound
- a rounded sound.
quality. It might be smooth like a harp, or
strident like a trumpet. • "Sawtooth" (type'S")
-astrident sound.
In the course of a page or so, we've
mentioned eight technical terms: pitch, "Pulsed" (type"P")
Frequency, duration, sustain level, attack, decay, - a raucous sound, which you may further
envelope and timbre. You could be forgiven for change by varying the 'pulse width' between 8
fd h hl lihl fi
and 999. Information about the pulse width
appears as soon as you select the pulsed
waveform.
designed to help you find your way around
these ideas, and to hear for yourself how • "Noise" (type"N")
changes in frequency, decay rate, and so on - this waveform doesn't produce a musical note
really affect the sounds produced. Load the at all, but a rushing noise you can use for
program and hit the space bar, as many times as
explosions, jets, breathing and similar effects.
youlike. The note you hear has the attributes The other controls still work, so you can 'tailor'
displayed on the screen: the noise to your own needs.

Frequency: 512 vibrations per second We suggest that you spend sometime
Duration: 250 milliseconds
changing fne values of the attributes and trying
Sustain level: 0 out the results, so that you get a 'feel' for the
Attack value: 0 (Attack is instantaneous)
various effects. Then have a try at designing
Decay value: 9 (Decay lasts about Va second)
your own sounds, using the foflowing table
Waveform type: Triangular
(where a few lines have already been filled tn by
(This is the name of one kind of way of example):
timbre —a smooth sound.)

Now you can change the attributes, one by


one,, and listen to what happens.
pp Fi rst change
g

the frequency by typing F, and then the number


TYPE OF FREQUENCY DURATION SUSTAIN ATTACK DECAY WAVEFORM PULSE
SOUND LEVEL VALUE VALUE WIDTH

iHARP 11 TRIANGULAR
SHIP'SSIREN 0 PULSED
EXPLOSION 12 NOISE
JET PASSING 13 NOISE
TRUMPET 0 PULSED
OBOE
PIZZICATO
{plucked violin
string)
POUCEWHISTLE
TRIANGLE
DRUM

When you've designed a sound by FF = 16+F


specifying its attributes, {frequency, duration, POKE 54273, FF/265
etc.)youwillnormallywanttoputitintoa POKE 54272, (FF-32768) AND 255
program you are writing. The synthesizer is
controlled by POKE instructions, rather like the [b) Thepu/sew/c///?(ifyouneedit) is set in
frame and background colours. The flow chart address 54275. For a pulse width value of P,
to make a single sound is this: the right command is

POKE54275,P/8

[c) The sustain level is set in 54278. For


Prepare details sustained sounds put
of sound POKE 54278,240
For decaying sounds, use
POKE 54278,0
[d) The attack and the decay levels are both
controlled by 54277 The number you poke
Start sound is sixteen times the attack rate, plus the
decay rale. For values A and D you'd put:
POKE 54277,16*A+D

These commands complete the preparafion


of the sound, and you can write them in any
Waitforduration
order. The sound is actually stor/ec/byPOKEing
of sound
a special number into 54276. The number
controls the waveform, as fol lows:

for Triangular waveform, POKE 54276,17


for Sawtooth waveform, POKE 54276,33
Stop sound for Pulsed waveform, POKE 54276,65
forNoisewaveform, POKE54276,i29

Now the program has to wait for the


duration of the note-say T milliseconds. This is
The rules for converting attributes into easily done by a FOR-NEXT loop which does
commands are straightforward, and they will nothing except count:
soon stick in your mind: FORC=1TOT
NEXTC
(a) The frequency is control led by addresses Finally the sound must be stopped, by
54272 and 54273. If the frequency you need POKEingO into address 54276:
(in vibrations per second) is a variable POKE 54276,0
called F, the commands needed are:
Lei's wrap up all these details in an An even more complex sound pattern can
example. Suppose you want to write a prograrr be obtained by putting the control loop into
which at some point imitates a ship's siren. The another loop, so that the starting and ending
values you need are given in the second line of values change with time:
the table on page 106:
10 POKE 54296,15
500FF=16*8O 20 POKE 54278,240
510 POKE 54273,FF/256 30 POKE 54277,0
520 POKE 54272, (FF-32768) AND255 40 POKE 54276,33
530 POKE 54275,999/8
540 POKE 54278,240 50FORO1TQ20
550 POKE 54277,16*7 + 0
560 POKE 54276,65 70 POKE 54273,N
570 FORC = 1TO2500 80 NEXT N
580 NEXTC 90 NEXTC
590 POKE 54276,0 100 GOTO50

Again, you can adjust the circled values, or


Sets frequency (lines 500-520] you can make either or both the loops go in the
Sets pulse width (line 530) opposite direction.
Sets sustain level (line 540) I hope this unit has awakened your interesi
Sets attack and decoy values (line 550] in making sounds with the COMMODORE 64
Starts note (line 560) synthesizer. This area of programming is
Waits 2500 milliseconds (line 580] unique, because there are no 'correct answers';
Stops note (line 590) the only thing that counts is whetherthe sounds
you produce are worth hearing.
The line numbers (500 to 590) are quite To end the unit, try programming a siren or
klaxon, which goes up anaaown in pitch. If you

sound generator at the beginning of the future use.


program!

To end this unit, we'll discuss some sound SOUND DEMO


effects which are in no sense musical notes.
They all depend on changing the frequency of
rhegenerator while the sound isactually being
produced. The effect is indescribable in words, 10 REM COPYRIGHT (C) ANDREW COLIN
and simply has to be heard. 1982
Key in and run the following program. 20 PRINT"

10 POKE 54296,15 30PRINT"M"***SOUND


20 POKE 54278,240 DEMONSTRATION PROGRAM •*•
30 POKE 54277,0 40 PRINT
40 POKE 54276,33 n 50 PRINT "HIT A LETTER BETWEEN A ANDM
50 FOR N =(p TO"
60 POKE 54273 ,N 60 PRINT
70 NEXT N 70 PRINT"HEARASOUND EFFECT"
80 GOTO 50 80 POKE 54296,15: POKE 54295,0
100 PRINT
When you've heard enough,you'll need to 110 PRINT "A: HEAVY BREATHING"
120 PRINT"B: HEARTBEAT"
press yUl and HlillHtogethertostopthe 130 PRINT "C: PIP"
program. 140 PRINT "D: RASPBERRY"
You can alter the quality of sound by 150 PRINT"E: WOLF WHISTLE"
changing the circled numbers, or by using 17 or 160 PRINT "F: UFO VISIT"
129 instead of 33 in command 40. 170 PRINT "G: EXPLOSION"
180 PRINT"H: GNATS"
190 PRINT "I: POLICE SIREN"
200 PRINT "J: MANDOLIN-RISING SCALE"
210 PRINT "K: VIOLIN - FALLING SCALE"
220 PRINT "L BUGLE CALL"
230 PRINT"M:TRIANGLE"
300 GET A$: IF A$ =" "THEN 300
310G=ASC(A$)-64
320 IF G<1 OR G>13THEN 300
330GG=1024+201+40*G
340 POKE GG, PEEK (GG) + 128
350 ONGGOSUB 1000,2000,3000,4000, 5040 FORNN = 80 TO 140STEP4: POKE
5000,6000,7000,8000,9000,10000, W+l,NN: NEXTNN
11000,12000,13000 5050 POKE W+4,0: POKE W+5,74
360 POKEGG, PEEK (GG) AND 127 5060 FOR NN= 1TO 120: NEXTNN
370 GOTO300 5070POKEW+4/I7
1000 REM*** HEAVY BREATHING*** 5080 FOR NN = 100 TO 120: POKE
1010W=54272 W+1,NN: NEXTNN
1020 POKE W+6,0 5090 FORNN= 120TO60 STEP-0.4: POKE
1030FORMM=1TO10 W+1,NN: NEXTNN
1040POKEW+1,24:POKEW+5,138 5100POKEW+4,0
1050 POKE W+4,129: FORNN = 1 TO500- 5110REM***ENDOFWOLFWHISTLE***
25*MM: NEXTNN 5120 RETURN
1060POKEW+4,0:FORNN = 1TO100: 6000 REM*** UFO VISIT***
NEXTNN 6010 W=54272: POKE W+l,40
1070 POKE W+1,20: POKE W+5,155 6020 POKE W+6,0: POKE W+5,204: POKE
1080 POKE W+4,129: FORNN = 1 TO W+4,0: POKE+4,129
1500-75*MM: NEXTNN 6030 FORNN =0 TO 2500: NEXTNN
1090 POKE W+4,0: FORNN= 1 TO200: 6040 POKE W+6,240: POKE W+5,0: POKE
NEXTNN W+4,0
1100NEXTMM 6050 POKE W+4,17
1110 REM*** ENDOF HEAVY BREATHING 6060FORMM=20TO6STEP-1
*** 6070 FOR NN=MMTO50-MM
1120 RETURN 6080POKEW+1,NN
2000 REM *** HEART BEATING *** 6090 NEXTNN,MM
2010W= 54272 6100 POKE W+l,3: POKE W+4,0
2020 POKE W+ 24,31: POKE W+6,0: POKE 6110FORNN-1TO10
W+22,10:POKEW+23,1 6120 POKE W+4,33: FORMM= 1 TO 50:
2030FORMM=1TO20 NEXTMM
2040 POKE W+l ,24: POKE W+5,51 6130POKEW+4,0:FORMM=1TO200:
2050 POKE W+4,129: FORNN= 1 TO 50 NEXTMM
-MM: NEXTNN 6140 NEXTNN
2060 POKE W+4,0: FORNN = 1 TO 100: 6150 POKE W+6,0: POKEW+5,5: FOR
NEXTNN NN=3TO100STEP5
2070 POKEW+1,16: POKE W+5,21 6160 POKE W + 1, NN: POKE W + 4,33
2080 POKE W+4,129: FORNN= 1 TO 6170 FORMM= 1TO40-0.25 * NN: NEXT
400-10*MM: NEXTNN MM
2090 POKE W+4,0: FORNN= 1TO200: 6180POKEW+4,0:FORMM=1TO120-NN:
NEXTNN NEXTMM
2100NEXTMM 6190 NEXTNN
2110 POKE W+24,15: POKE W+23,0 6200 POKE W+5,31: POKE W+4,129
2120 REM *** END OF HEART BEATING 6210FORNN=40TO200STEP0.1
*** 6220 POKE W+1,NN
2130 RETURN 6230 NEXTNN
3000 REM*** PIP*** 6240 POKE W+4,0
3010W=54272 6250 REM *** END OF UFO VISIT***
3020 POKE W+6,0: POKE W+5,31 6260 RETURN
3030 POKE W+l,180: POKE W+4,33 6500 RETURN
3040 FORNN =1 TO 100: NEXTNN 7000 REM *** EXPLOSION ***
3050 POKE W+4,0 7010 W=54272: POKEW+6,0: POKE
3060 REM*** END OF PIP*** W+5,12
3070 RETURN 7020 POKE W+1,20: POKE W+4,129
4000 REM *** RASPBERRY ** + 7030 FORNN = 1 TO2500: NEXTNN
4010 W=54272: POKE W+6,240 7040 POKE W+4,0
4020 POKE W+l ,4: POKE W+5,0: POKE 7050 REM *** END OF EXPLOSION +**
W+4,33 7060 RETURN
4030 FORNN = 1024TO512STEP-8 7070 POKE W+4,0
4040 POKE W+1, NN/256: POKE W, NN 7090 RETURN
AND 255 8000 REM *** GNATS ***
4050 NEXTNN 8010W=54272
4060 POKE W+4,0 8020 POKE W+6,0: POKE W+5,205
4070 REM*** END OF RASPBERRY*** 8030POKEW+1,48+2*RND(0)
4080 RETURN 8040 POKE W+4,33
5000 REM*** WOLF WHISTLE*** 8050 FORNN = 1 TO 200: POKE W+l,
5010W=54272 48 + INT(2*RND(0))
5020 POKE W+6,0: POKEW+5,9 8055 FORMM - 1 TO 10: NEXTMM
5030POKEW+4,17 8060 NEXTNN
12030 POKE W+6,0: POKEW+5,45
8070 POKEW+4,0
12040 POKE W+3,99: PP-2500
8090 RETURN
12050 READ WW: IF WW=0 THEN POKE
9000 REM ••* POLICE SIREN ***
54276,0: RETURN
9010 W=54272: POKE W+6,0: POKE
12060 RR=INT(WW/10):QQ=(WW-10
W+5,237
*RR)*PP
9020 POKE W+2,200: POKEW+3,0
12070 POKE 54273, QQ/256: POKE 54272,
9025AA=55:BB=42
QQ AND 255
9030 POKE W+1,60: POKE W+4,65
12080 POKE 54276,0: POKE 54276,65:
9040FORNN=1TO12
FORNN= 1 TO70 * (RR+1): NEXTNN
9050POKEW+1,AA
9060 FORMM = 1 TO 300: NEXTMM 12090 GOTO 12050
12100 DATA25,6,24,5,3,3,3,4,5,6,25,6,24,
9070POKEW+1,BB
5,3,3,3,64,3,3,5,4,4,5,3,3,5,4,5,6
9080 FORMM= 1 TO300: NEXTMM
9085IFNN=6THENAA=53:BB=40
12110 DATA 15,6,24,5,3,3,3,4,5,6,25,6,24,
5 3 3 3 94 0
9090 NEXT NN 12120 REM*** END OF BUGLE CALL***
yl00POKEW+4,0
9110 REM*** ENDOFPOUCESIREN*** 13000 REM***TRIANGLE ***
13010W=54272 nur
9120 RETURN
10000 REM*** MANDOLIN***
13020 POKE W+6,0: POKE VV + 5,12: POKE
10010 W=54272: POKE W+6,0: POKE W+1,200
13030 POKEW+3,40
W+5,8
13040 FORNN=1TO5
10020 PP=1000:QQ=2T (1/12]
10030 FOR KK-0TO4
13050 POKE W+4,0: POKE W+4,65
13060 FORMM=1 TO500: NEXTMM
10040FORJJ=0TO11
10050 IF JJ = 1ORJJ = 3ORJJ=6ORJJ-8OR 13070 NEXTNN
JJ=10THEN 10080
13080 POKEW+4,0
10060POKE W+l.PP/256: POKE W,PPAND 13090 REM *** END OFTRIANGLE ***
13100 RETURN
255
10070 POKEW+4,0: POKEW+4,33:
FORNN=1 TO 50: NEXTNN
10080 PP=PP*QQ Experiment 73.7 Completed
10090 IFKK-4THEN 10110
10100 NEXT JJ,KK
10110 FORNN=1 TO200: NEXTNN
10120 POKEW+4,0
10130 REM *** END OFMANDOLIN ***
10140 RETURN
11000 REM *** VIOLIN ***
11010 W-54272: POKE W+6,32: POKE
W+5,106
11020 PP=20000:QQ=2| (1/12;
11030 POKE W+3,50
11040 FOR KK=1TO3
11050 FORJJ-12TO1 STEP-1
11060IFJJ=1ORJJ = 4ORJJ = 6ORJJ = 9
ORJJ = 10 THEN 11150
11070 POKE W+4,0: POKE W+4,65
11080 FORNN=1TO4
11090ZZ=1.005*PP: POKE W+l,ZZ/256:
POKEW,ZZAND255
11100 FORMM=1 TO25: NEXTMM
11120 ZZ=0.995*PP: POKE W + 1,ZZ/
256:POKEW,ZZAND255
11130 FORMM=1 TO 25: NEXTMM
11140 NEXTNN
11150 PP=PP/QQ
11160 IFKK-3THEN 11180
11170NEXTJJ,KK
11180 FORMM= 1TO500: NEXTMM: POKE
W+4,0
11190 REM *** ENDOF VIOLIN ***
11200 RETURN
11300 FORMM=1 TO 50: NEXTMM
12000 REM *** BUGLE CALL ***
12010 RESTORE
12020 W=54272
In this unit we'll look at an extremely common A very simple example is this program which
type of computer application: one where the Inputs 10 numbers and finds their average value:
machine is made to input and digest a large
number of separate items of information, and to 10S=0
display a summary of its results. For instance, if Initialise
r ' . i. ■ ..__i -r i I . 20P=1
you could feed in the details of every cheque you
write, and every credityou pay in to the bank, and 30 INPUT X
the machine would tell you your balance at the Read and digest an item
end of the week. To give another example, a 40S=S+X
school teacher could give the computer all the
exam marks gained by the pupils in the class, and 50P=P+1
S the computer would display the overall average Any more items?
mark. 60IFP<11THEN30)
All programs of this type conform to the
same basic pattern, which has a flow chari 70PRINT"AVERAGE = '
summary
111 something like this:
80 STOP

Glossary
Initialise
S: Used to add up values of items
P: Used to count the items
X: Used to input individual items

Input and digest


an item of If you don't understand how this program
works, trace it with the input values 3,6,2,7,0,9,
information
8,3,12,10.
In this example, we've used an IF-THEN for
the loop control to make the construction of the
program more clear. In practice we would write
the program with a FOR .. NEXT, like this:
Any
more items 10S = 0
z
20FORP=1TO10

30 INPUT X

40S = S+X
Display
summary
50 NEXT P

60 PRINT "AVERAGE IS"; S/l 0

70 STOP

Let's think about the part of the program


which says "any more items". In the first example
the question was answered by keeping a simple
count, and using the condition P < 11, which was
true until the tenth item was input and added to
the running total. This method depends on the
programmer knowing in advance how many
items there are going to be. The method isalmost
useless in practice because it is so inflexible: you
would need different programs to find the
average of 11, or 20 or any other number of
numbers.
You can write a much better program if you
assume that the user con lell the computer how Glossary
many items to expect. The following program will
work for any number of items:
S: Used to add up values of items

N: Used to count items


20 INPUT "HOW MANY NUMBERS"; N
X: Used to input individual items
30FORP-1TON,
M$: Used to hold answer to question
"Any more items"?
40 INPUT X
Note use of N
50 S = S + X instead of 10 If you ran this program, the display might be:
60 NEXT P
NEXT NUMBER? [J]
70 PRINT "AVERAGE IS"; S/N
ANY MORE NUMBERS? [YES,
80 STOP
NEXT NUMBER? 7

ANYMORE NUMBERS? I YES I

NEXT NUMBER? 10

ANY MORE NUMBERS? [NO

AVERAGE IS 7

BREAK IN 90

READY

The drawbacks ofthisschemeareclear. The


unfortunate user has to keep typing YES after
So far we have been on familiar ground; but every number except the last. This takes double
what about the case where the user has to feed in the time, and doubles the risk of mistakes. A
□ large number of items (like o thousand or better method is to mark the end of the stream of
more)? It is unfair to make him count the items in items with a special value called a terminator. A
!_._._. .1 . I. ill . _ .
good choice for a terminator is a value which
the number right. couldn't possibly occur as one of the items. For
A different way of controlling a loop is not to instance, if you plan to use the program to
usea predetermined count at all, but simply to tell average football scores, you could use the
the computer when the stream of items has number 1000000, because you may be sure thai
ended. We could, for example, get the user to no team can ever score a million goals in one
answer the question "any more items" each time match.
round the loop. This would lead to a program like

10S=0

20N=0

30 INPUT "NEXT NUMBER"; X

40S=S+X

50N = N + 1

60 INPUT "ANY MORE NUMBERS"; M$

70IFM$ = "YES"THEN30

80 PRINT "AVERAGE IS"; S/N

90 STOP
The display produced by a program written The corresponding program for finding an
on these lines could be: overage is quite straightforward:
10PRINT"USE1000000TO"
USE 1000000 TO
20 PRINT "END INPUT"
END INPUT
30S=0
NEXT NUMBER? [5
40N = 0
NEXT NUMBER? \J
50 INPUT "NEXT NUMBER"; X
NEXT NUMBER? [fl_
60IFX=1000000THEN100
NEXT NUMBER? [2
70S=S+X
NEXT NUMBER? 1

NEXT NUMBER? 110000001


90 GOTO 50
AVERAGE IS 3
100 PRINT "AVERAGE ="; S/N
BREAK.. .

110 STOP
To use this system we have to re-arrange the
overall flow chart; in particular, the question
"any more data" must come be/ore the block Glossary
which digests each data item — otherwise the
terminating value would be treated as an
S: Used to add up values of items
ordinary item and would upset the summary.

N: used to count items

X: Used to input individual items


Initialise
To summarise, we have looked at four dif
ferent ways of indicating how many items of
information are to be input by a program. They

Input item 1. Number of items is specified by the


programmer. Used only by beginners and
useless in practice.

2. Number of items is specified in advance by


the user. Agood method if thereare20 items
or less.
Is it the
terminator? 3. User indicates aftereach item if there are any
more to follow. Intolerably tedious.

4. Stream of items ends with special value. A


good method, generally better than the
others.
Digest
item

Display
summary
Hint: Your display section will be a little more
complex than usual. If B is a variable which

EXPERIMENT gives the current balance, then it will be


negative (or less than zero) if you are over
drawn at the bank. The right condition to
check this possibility is B < 0. Your solution
should include a flow chart and a glossary.
Check it against the answer in Appendix B.

Experiment 14.J Completed

Write a simple banking program which


inputs your old balance, and details of all the
chequesyou have written, and then displays your
new balance or overdraft. Use the number zero
as a terminator, because you will never write a
cheque for £0.00. Don't worry about credits.
Design your program so that il could produce
either of the two displays which follow:

(a) OLD BALANCE? 5.24

TYPE DETAILS OF

CHEQUES, USE 0 TO END

AMOUNT? 1.73 --^


Typed by
AMOUNT? 2.00

AMOUNT? 0 ^
YOUR BALANCE IS £1.51

(b) OLD BALANCE? 4.02 v

TYPE DETAILS OF

CHEQUES. USE 0 TO END

AMOUNT? 3.50
Typed by
AMOUNT? 1.50

AMOUNT? 3.00

AMOUNT? 0

YOUR OVERDRAFT IS £3.98


In some problems the various items in the Next we can work out the initialisation section
stream have to be treated in different ways. The of the program. There are two things to do:
corresponding programs generally have 'IF'
commands inside their main loops. For example, Set variables H and T to zero
let's suppose that after a run of very bad luck in
gambling you became suspicious that a coin was Display the heading message.
biased, so that it came up 'heads' much more
often than 'tails'. You could follow up your hunch Next we turn to the cloud inside the main

counting the number of heads and tails which the 'E' will have been filtered out, and every item
came up. You mightwant the COMMODORE oughf to be an H or a T. The basic job the cloud
64 to help you keep the score, so you would has to do is to add! eithertothe heads total, or to
write a program which produced a display like the tails total. One possible approach would use
this one: theargument"lsitanH?lf not, it must be a T".
This would result in a flow chart like
TYPE H FOR HEADS

T FOR TAILS
Is item Add I to
E FOR END an"H"?

NEXT THROW? H Typed by


user
NEXT THROW? H

Add I to
NEXTTHROW? T

and so on for 547 lines

NEXTTHROW? E

OUT OF 547 THROWS


In practice, this method would never be used
THERE WERE 490 HEADS by a good professional programmer, because it
doesn't allow for the user's typing mistakes. If the
AND 57 TAILS user hits a J instead of an H (they are next to each
other on the keyboard) the program would count
READY. it as a T, which is most unlikely to have been what
the user wanted.
It is much better to allow for the possibility of
And you could draw your own conclusions errors, like this:
about the bias of the coin.
Let's design and write this program, from
glossary and flow chart down to BASIC
commands.
The sample output shows that we use a
special value, E, to terminate the stream of data Is item Add I to
items. The outline flow chart will be the same as an "H"?
ihe one on page 109, and all one need do is -
expand the clouds.
The program obviously needs three
variables:

Is item Add I to
H: To count number of heads
a "T"?
T: To count number of tails

l$:To input an item

[As usual, the names H and T are freely chosen.)


Display an
error message.
Some people might be tempted to include a
fourth variable to count the total number of
tosses, but there is hardly any point; the total is
always given by the expression H -I- T (the
number of heads plus the number of tails).
A program which allows the user to make
mistakes without disastrous consequences is
called robust.
Finally, we can expand the "summary" cloud
to give the three-line report at the end of the
display. The expanded flow chart looks like this:

Set: H=0
T=0

Display:
Type H for Heads
T for Tails
E for End

Input 1$

I$="E"
2

I$="H' H=H+1
2

I$="T" T=T+1
2

Display:
Wrong item
Display:
Out of (H+T) Throws
Ihere were H Heads
and T Tails
The corresponding program is written out
below. Notice that the code for the main loop is a
bit tangled. This is unavoidable since we have to
force a two-dimensional flow chart into a single
EXPERIMENT
stream of instructions.

10H=O

20T=0

30 PRINT "TYPE H FOR HEADS"

40 PRINT "T FOR TAILS"

50 PRINT "E FOR END"

60 INPUT "NEXT THROW"; 1$

70IFI$="E"THEN160
[a) If a program has a great deal of input, the
user may stop looking at the screen as he
80IFI$="H"THEN120
types. It is a good idea to make the program
react with sounds as well as displayed
90IFI$="T"THEN140
messages. You could, for instance, use a
cheerful 'pip' for an item which is acceptable,
100 PRINT "WRONG ITEM"
and a rude noise for one which isn't.
Look at the heads and tails program. Every
110 GOTO 60
time the user types an H the machine obeys
the commands at lines 120 and 130. We
120H = H + 1
could insert a suitable noise by adding the
commands:
130 GOTO 60
121 POKE 54272+ 24,15
140T=T+1
122 POKE 54276,0 : POKE 54278,255:
150 GOTO 60 POKE 54277,0 : POKE 54272,90:
POKE54273/150
160 PRINT "OUT OF"; H+T; "THROWS"
123 POKE 54276,17
170 PRINT 'THERE WERE"; H; "HEADS"
124 FORM = 1 TO 100
180 PRINT "AND"; T; "TAILS"
125 NEXT M
190 STOP
126 POKE 54276,0

Load the HEADS program from the cassette


tape (this saves you keying it in for yourself]
and edit itsothat it answers each input (right
or wrong) with a suitable sound.

[b) At one time, clocks were liable to a curious


form of tax, which was calculated as follows:
If the price of the clock was less than £12, the
tax was one-third of the cost.
If the price was between £12 and £16, the tax
was £4.

If the price was over £16, the tax was one-


quarter of the cost of the clock.
Write a program which inputs a list of clock
prices, ended by 0, and displays the total to
be charged for each clock (including cost
and tax).
Note that this program will have one or more
PRINT commands inside the loop, and
doesn't need a summary block. You will find
a good flow chart indispensable.
This unit is about three important features of
Commodore BASIC which are useful in games,
quizzes and other programs where the machine
and its user work closely together.
EXPERIMENT
We'll beginbyhavinga look ot "REACTION",
one of the programs you'l I find on the cassette
tope. A person's "reaction time" is o measure of
how quickly they can respond to an unexpected
event. A sofe driver should have a fast reaction
time, so that he or she can put the brakes on
quickly when a child runs out into the road in front
of the car. A good reaction time is also useful in
most sports and many professions.
Most people, if they are paying attention,
have reaction times between 0.2 and 0.3 of a
second (twenty to thirty hundredths of a second).
A time of less than 0.2 suggests someone who is
quick on the uptake, whilst a reaction time of
more than 0.3 is usually due to a few drinks too Load the REACTION program, and use it
many! to measure your own reaction time. Run the
program several times, and ignore the first two or
three results, since they will not be typical. Keep
trying the program until you are satisfied that you
understand it thoroughly, and could confidently
use it to measure the reaction time of a friend who
had no knowledge of computing.
You may notice three aspects of the program
which are not immediately obvious;
First, when the instructions say "any key",
they really mean it. You will find that function keys
INST

like it.1 DiL ■■■•;.]<:«


as letters or numbers.
Second, the time you must wait before
hearing the tone is always different: it varies
between 1 and 6 seconds in a way you cannot
predict in advance.
Third, if you press a key before the tone
starts, you get a message, "TOO SOON".
Now we'll examine the program in detail,
and explain how it works. Let's start by examining
the flow chart and BASIC program, which are
shown opposite:
110 REM WAIT FOR ANY KEY

120 GET AS
Clear screen and
Cloud 1
give instructions
130IFA$ = ""THEN120

140 REM WAIT A RANDOM TIME

Wait for user to 143 PRINT


Cloud 2
v hit a key
145PRINT"WAITFORIT!"

148 PRINT
Wait a random time ) _. ,„
-, between land 6 / CloudJ 150 Q = Tl + INT (60 + 301 * RND (0))
V seconds ,—-^
160 GETAI

170 IFA$<>""THEN340
Start tone. Record) Qoud4
V current time ) 180IFTI<QTHEN160

Wait for user to


Cloud 5 200 POKE54295,0
* hit a key >
202POKE 54296,15

20 5 POKE 54278,240
' Record current time ) Cloud 6
S. Stop tone r
207POKE 54277,16

210 POKE 54273,100


Display user's
212 POKE 54276,33
, reaction time)

220 X = Tl

230 REMWAITFORANYKEY
STOP
240 GET AS

250IFA$ = ""THEN240
5 REM COPYRIGHT (C) ANDREW
COLIN 1981

10 REM REACTION TIME PROGRAM


270 R = Tl
20 print" mmm and mm"
280 POKE 54276,0
30 PRINT "TO MEASUREYOUR"
290 POKE 54296,0
40 PRINT "REACTION TIME"
300 REM DISPLAY RESULT
50PRINT"HITANYKEY"

310 PRINT "YOUR REACTION TIME IS"


60 PRINT "THEN WAIT FORTHE"
320 PRINT (R-XJ/60; "SECONDS"
70 PRINT "TONE. WHEN YOU"

80 PRINT "HEAR IT, HIT ANY" 330 STOP

90PRINT"KEYASFASTAS" 340 PRINT'TOO SOON"

100 PRINT "YOU CAN. GOOD LUCK!" 350 STOP


The program has been marked so that the 3. The GET command doesn't treat certain
commands which correspond to each cloud in the
flow chart are clearly visible. control characters like
The first cloud (lines 10 to 100) consists or cursor controls as special cases, but deals
entirely of PRINT commands and is quite straight with them all in the same way, except for
forward. STOP, which interrupts the program.
The second cloud, lines 110 to 130, makes
the program wait until the user types a key. The 4. Any character which is detected by the GET
cloud uses a command with a new keyword: command is nof displayed on the screen.

GETA$ With these points in mind, you can now begin


to make some sense of line 120 and 130 in the
This command is in some ways like INPUT; il REACTION program. Command 120 examines
transfers information from the keyboard to the the keyboard and delivers a string in A$ which is
computer. However, there are same very null unless a key has been pressed. Command
important differences: 130 tests A$, and makes the computer loop back
to 120 until the user types any key, at which the
1. The keyword GET must be followed by program is allowed to drop through to line 140.
exactly one string variable name. The names The point of this cloud is to hold the program
of number variables are not allowed. For up until the user shows he is ready to have his
example reaction time tested. Why do we use a loop with a
GET, instead of a single command like

INPUT "READY"; A$ ?
GETX$ but
There are two reasons. First, INPUT always
GETPRS J GET Y$,Z$>»-Nol BASIC
expects a ^HHHWB after the user's message.
[allowed) I (forbidden) I This implies a minimum of (wo characters to be
typed.
Second, GET treats nearly all the characters
The GET command doesn't wait for the user in the same way, so there is much less chance of
fo do anything; it simply examines the key the program being spoiled if the user hits a
board at that instant and indicates which key function key instead of a letter or number.
has been typed since the last GET or INPUT Cloud number 3 makes the machine wait a
command was obeyed. If a key has been random (that is, an unpredictable) time between
struck, it is made into a one-character string Ihe user's 'ready' signal and the tone. The waiting
and pul into the variable mentioned in the lime must be variable, because if it were always
GET command. If no key has been newly the same, the user would soon learn how long to
struck, the variable is set to the null string. wait before the tone was due, and this would no
This is a string with no characters, and is longer be an 'unexpected' event.
normally written as " ". The cloud uses fwo facilities which you
To illustrate this rule, imagine that we start off haven't met before: the random function and the
the computer on the following looped internal timer.
program, and watch what happens inside
the machine:

10GETX$

20 GOTO 10

The computer will go round this loop about


50 times a second. As long as the user
doesn't touch the keyboard, X$ will be set to
the null string:" ".
Now suppose the user presses down a key —
say the one marked U. As soon as the GET
command is obeyed (i.e. within a fiftieth of a
second) X$ will be set to the string "U".
However, this only happens once for each
key depression; the next time round the loop
X$ will again be set to " ", and this will
continue until the U key is let go and another
key (or possibly the same key) is pressed.
The only exceptions to this rule are the so-
called repeating keys like space.
The random function is a way of making the An expression of this sort can be included in
machine produce an unpredictable* number. a loop, so that it is worked out many times. Type
Every lime the machine works out the expression the following program, which imitates 120 throws
RND (0) it gets a different value somewhere of a die:
between 0 and 1.
In most practical cases, we don't need a NEW
random fraction between 0 and 1, but a random
whole number within limits which depends on the 10FORJ = 1TO120
problem to be solved. For instance, if you make
the machine imitate someone throwing a 6-sided 20 S = INTO +6* RND(0)j
die**, you expect a number between 1 and 6; or if
you model a (European) roulette wheel, you need 30 PRINTS;
a number which is between 0 and 36.
To get a whole number in any specified 40 NEXTJ
range, we use a slightly different expression:
50 STOP
INT(x + y * RND(0))
Run this program, and count the number of
where x is the lowest number we need 1 's, 2's ... 6's which appear on the screen. Enter
your results in the first row of the table below:
y is the number of different possibilities

So, to get a number between 1 and 6, we 1 2 3 4 5 6


would put

No. of throws 0)

Lowest number expected No. of throws (2)


1
-

Is the program a good imitation of a fair (or


INT(1 + 6*RND(0)) unbiased) die?
Now run the program again, and fill in the
second row. Examine the results and note that
Or, for a number between 0 and 36
they are different from the first run, just as you
would expect with a real die.
37*RND(0)| The other important feature in cloud 3 is the
internal timer, Tl. We have already met the clock
Tl$, which keeps time in hours, minutes and
Number seconds; but the special variable Tl (which is not
of different values a string but a number) is intended to measure
much shorter periods of time. Tl is set to zero
when the 64 is started up, and from then on, no
matter what else happens, it has 1 added to it
every 60th of a second. This interval, a sixtieth of
a second, is called one "jiffy". You can get the
current value of the internal timer at any time in
jiffies by using the name Tl in an expression; but
you can't alter the value in the way you can set Tl$.
Give the command

PRINT Tl

The machine will respond by displaying a


fairly large number (60*60 or 3600 jiffies for
every minute you've had the machine switched
'The number isn't really unpredictable because on). Now try the command again, and observe
everything which happens in a computer that the value has gone up by a few hundred or
depends on what happened previously. so. Finally, try to reset the value of Tl and see what
However, each new 'random' number is derived happens!
from the previous one by a complicated process Tl can be used to measure periods of time in
of squaring it and shuffling thedigits of the result, two different, but related ways. In neither of them
and unless you know exactly how it is done you are we interested in the number of jiffies since the
cannot tell what number is coming next. 64 was switched on; instead, we use the fact that
the duration of any length of time is given by the
'*Thatis: one of a pair of dice. difference between Tl at the end of it, and the
5 seconds. This is between 60 and 300 jiffies, to be
value it had at the beginning. For instance, at the
decided by the machine in an unpredictable way.
end of a period of 5 seconds, Tl will be 5 * 60 or
The appropriate expression is
300 more than it was at the beginning. This is true
whether the machine has been switched on for 5
INT(60+301 *RND(0)1
seconds or 5 years.
In the first way of using the internal timer, we
The waiting period is decided just before the
make the machine measure a period of time
period starts, so it is known in advance (although
which is known in advance, and tell us when
not to the user). We use the first method of timing,
that time has elapsed. The method is simple. At

passesJthatvalue.Thisisverylikewhatyoudom If this were all that were needed, the entire

boil for 25 minutes. Now it's ten past four, so I'll


150 Q = TI+INT(60+301 *RND(0)!
take them off at 4.35".
To illustrate the point, here is a general
160 IF TKQ THEN 160
purpose timer program, which you could use in
the kitchen, the laboratory, etc. As it is, we have to check that the user doesn't
hit a key before the tone is sounded. Commands
10 INPUT "HOW MANY MINUTES"; M
160,170,340 and 350 are included simply to
check for this possibility.
20R=TI+M*3600 The rest of the program is now completely
straightforward. The value of Tl at the beginning
30 IF TKR THEN 30
of the reaction time period is stored in X, and
commands 240 and 250 are used to wait for the
40 PRINT "TIME UP!"
user to hit a key.
Study the program carefully and make sure
50 STOP
you understand every command.
If you try this program out, use a small
number of minutes, otherwise you'll spend a lot of
time waiting. As you study the program,
Experiment 15.1 Completed
remember that Tl is moving up all the time, so that
eventually, after M*3600 jiffies, the condition
TI<R will be false.
In the second variant, we want the computer
to tell us how long it takes from a given moment
until some event occurs. We get the machine to
record the value of Tl at the beginning of the
timing period. When the event comes, the differ-
ence _
recorded is a measure of the length of time, in
jiffies. It is rather like the mountaineer who says,
"I remember that I started climbing this hill at 5
o'clock. I have just got to the top at eleven o'clock,
so it must have taken me six hours."
A program which measured time in this way
...ijl m^.n^lc o-imatkinn likp this:

R=TI (Stores value of Tl at beginning of


period]

and later

E=TI Gets value of Tl at end of period

D=E-R Gets difference of times (in jiffies]

S=D/60 Gets time difference (in seconds)

PRINT'THATTOOK"; S; "SECONDS"

Now we can piece together the commands in


cloud number 3.
We want a watting period of between I and
EXPERIMENT EXPERIMENT

1. Write a 'stopwatch' program. When the user Random numbers are useful in program
hits the 'B' key, the program starts timing. ming games of chance, such as dice, fruit
When he slrikes 'S', it stops and displays the machines, and so on. All these programs follow
time taken, in seconds. the same basic pattern, which for one 'throw' or
Your program should display instructions, so 'spin' is like this
that it can be used by anyone without further
explanation.

Hint: use GET and Tl.


Ask user for details
2. Write a program which imitates someone of his bet
tossing a coin. Every time the user presses a
key, the program displays either "HEADS"
or "TAILS" at random.

Experiment 15.2 Completed


Use random numbers to
imitate throw, spin

Decide if player has


won or lost, and
tell him so

Let's illustrate this idea with the old game of


crown and anchor*. This is played with three dice
and a board divided into six squares*:

• •
• •
• •

• • • • • •
• • •
• • • • • •

*Crown and anchor dice usually have different


symbols, but this doesn't affect the principle of
Now check your answers in Appendix B. the game.
The player puts his bet on any one of the

squares. For instance he might back ' *l with


£5. Then the banker throws all three dice. If one

of them shows I *l , the player gets back


double his stake money: if two of the dice come

up with , the player gets triple the original

stake, and if I *l shows on all three dice, the


player is rewarded with four times his stake. All
these rewards include the original stake. On the

Other hand, if no I *l comes up, the player


loses his stake.
The program for playing one throw of crown
and anchor is given below. Using the glossary
you should hove no trouble in following it:

S: Player's stake

N: Number backed by player

Results of throwing 3 dice

C: Number of dice showing N, the player's


number.

10 INPUT "STAKE"; S

20 INPUT "NUMBER BACKED (1 -6)"; N

30 Dl =INT(1+6*RND(0))

40 D2 = INT(1 +6*RND(0}] Throw 3 dice

50D3 = INT(1+6*RND{0))

70IFDloNTHEN90

80C = C+1 Count number of dice

90IFD2oNTHEN110 showing number backed

100C = C+1 by player

110IFD3oNTHEN130

120C=C+1

130 PRINT "DICE THROWN:"; Dl; D2;D3

140 IF C<>0 THEN 170

150 PRINT "YOU LOSE" Display results

160 GOTO 180

170 PRINT "YOU RECEIVE"; S*(C+1);"POUNDS"

180 STOP
Very few gamblers stop short at a single
throw. Usually people slart with a certain amouni
of capital and keep playing until they are broke
or—very rarely—the banker runs out of money.
Gambling programs on the 64 are better if
hey imitate complete sessions of this type.
Initially the player is given a certain amount of
"money" (like£l 00), and is then allows to play as
long as he likes, or until his money is used up. A
flow chart for such a game is shown below:

Give player his


slanting capital

Display amouni
of capital
remaining

Display: "YOU CAN'T


Ask player for
BET MORE THAN
his bet YOU'VE GOT!"

Can he
afford it?

Imitale -•
one spin/throw/deal

Adjust capital
according to win
or loss

Display:
YOU'RE BROKE!

Use this flow chart to modify the crown and


anchor program so that it starts the user off with a
capital of £100, and lets him play as long as he
likes. When your program is complete, run il
several times, and decide for yourself whether
you would rather be a player or a banker!

Experiment 15.3 Completed


EXPERIMENT

15-4
Write a program to imitate any other game
of chance you know: craps, pontoon, etc.
Embellish your program with pictures of dice or
of cards, suitable sounds, and so on.

Experiment 15.4 Completed

fa

Appendix B contains a 'craps' program for


you to try out.
Congratulations on reaching the end of the
course! By now you have gained a good
knowledge of the principles of programming,
and you'fi be able to design and wrile programs
for a wide range of interesting problems and
computer applications. I hope that you've also
cultivated the habit of careful, thoughtful design,
of keeping and filing flow charts, glossaries and
notes tor your programs. It is this quality of
planning and self-organisation that sets apart the
really competent programmer from the others.
At this stage, you have reached a half-way
point in your study of BASIC. There are many
important problems which need parts of the
language you haven't yet covered. For instance,
you may want to program moving pictures on the
screen, or to sort people's names into alphabetical
order, or to store them on a cassette tape. These
topics, and many others are fully explained in the
second book of this series, entitled

AN INTRODUCTION TO BASIC (Part 2)

This book is in the same styleas the one you have


just finished, and will complete your knowledge
of the BASIC language.
Programming — as we said in the introduc
tion— iso very broad subject. Now that you have
made a start, you should broaden your
knowledge in three ways:

(a) Read as widely as you can. Most of the


popular computer magazines are worth
looking at. Books on programming are also
worth reading, even if they don't refer
specifically to theCOMMODORE 64.

(b) Join a local computer club. There are


COMMODORE usergroups being set
up all over the country and details may be
obtained from the Commodore Information
Centre.

(c) Work at your programming. Practice


constantly, and aim for perfection. Design
your programs so that they are robust, and
usable by anyone without special instruction.

Write them so that you can be proud, not


ashamed, to display the inner workings to
another computer expert.

One last point. You have found a fascinating


hobby, and perhaps a life-long profession.
Remember that with the advantages of knowing
about computers, there also comes a responsi
bility to see that they are used humanely and
wisely. No one wants a computer-controlled
society with little work and no freedom, and it is
now up to you — among others — to avoid it.
APPENDIX

A
! 133

The COMMODORE 64 is a computer Expressions in BASIC are written in the same


way as in ordinary algebra, and have the same

can do arithmetic considerably faster than mos1


large-scale computers installed before 1960! BASIC expressions are in capitals instead of
This appendix outlines some of the mathe small letters.
matical facilities of the 64. You only need to read
the appendix and understand the material in it if Exponentiation ("raising the power") must
you plan to use the computer for calculations in be shown with the | sign, because the 64
Mathematics, Science or Engineering. Some of screen doesn't let you write small numbers
the features described are quite simple, and can above the line. Instead of "32", you would
easi ly be grasped by anyone who remembers the put"3T2".
elementary arithmetic they learned at school.
Other features need some more background Multiplication must always be shown using
knowledge, such as that covered by an A-level the * sign. In BASIC, you would write "3*A",
course in Mathematics. You need only go as far not "3A" as in conventional algebra.
as your knowledge and confidence will take you, This rule can be a source of mistakes which
but you are expected to have read all the units in are hard to find. If you put BA where you
the body of the course. mean B*A,the machine will assume that you
□re talking about a new variable called BA.
1. Expressions It won't report a syntax error, but it will
produce the wrong answer!
The expressions first mentioned in Unit 4 are
very simple examples of a more general facility.
Thus in the commands • Division is written A/B, not—. If either the
D

numerator or the denominator of the fraction


is a complicated expression, you must
delimit it with brackets. The correct way

C = ((X + Y) - 34.7/(Q-3) )*(Z-3)|2 of writing |^| in BASIC is (3+5)/(7+8|. If


7+8
the underlined portions are all expressions which you leave out the brackets and put 3 +5/7 +8
the 64 works out on your behalf. me rules of precedence (which are given in
Expressions are built up of three types of me next paragraph) will make the machine
element:
treat this expression as 3+ — + 8.
Values: numerical variables or numbers
such as When the 64 works out an expression, it
takes the ] signs first, then the multiplications and
B,X,Y,34,34.7
divisions, and lastly the additions and subtrac
tions, working from left to right in each case.
Operators: the signs + - * / and ] Anything in brackets is worked out first. These are
called the rules of precedence, and they give the
{] means "raised to the power")
same results as ordinary school algebra.
The value of numbers in expressions do not
Brackets: (and) hove to be integers (i.e. whole numbers) but can
be decimals. The 64 works to an accuracy of
about 8 decimal digits, which means lhat many
fractions (such as Vs or V?) can't be represented
exactly. You can expect small 'rounding' errors in
some arithmetic commands, so that a result which
you expected to be exactly 7 may come out as
"6.99999998".
To test your understanding of expressions,
work through the following examples, and
predict what the 64 will display in each case.
Assume that X = 3 and P = 7.

COMMAND PREDICTED RESULT ACTUAL RESULT

PRINT3 + 12-6-4
1

1 PRINT4 + 3*2

PRINTX + P-3

PRINT5 + 12/6-3

PRINT11/5-7/4

PRINT4 t 2-2 f 4

PRINT3 + 2 t 3-3 t 2

PRINT2 TX-P

-(6-4!

PRINT5 + 12/(6-3)

print(p + x) t (i -

PRINT4 T 2-3 T 0

PRINT(P | 2-X t 2)/3

Now check your results on the 64.


Remember to set the values of P and X before
you start.
In BASIC, expressions are most commonly
used in PRINT and LET commands. Here is a
simple program which inputs two numbers U
and V, and displays a value F calculated
according to the 'lens' formula:

111 .I
= — 4- — , or r = ■ ■

V U
10 INPUT "V";V

20 INPUT "U";U

30 PRINT"F=";l/(1/V+1/U]

40 STOP

Example 1
Write a program which reads two values V
and R, and which displays the value of the
V2
formula A = -

Example 2
Write a program which disploys the values

of the formula y = ■ for values of x between

0 and 2, going up in steps of 0.2

[Hint: use a FOR loop like this:

FORX = 0TO2STEP0.2

NEXTX

[The actual answers are given at the back of Appendix B.]


2 Standard Functions
Like most calculators, the COMMODORE Some of the more important mathematical
64 has a set of scientific'functions. A useful one functions are given below. Read through them,
is the square root This is abbreviated to SQR, but do notfeeTobligedto learn them by heart —
and can be included in expressions like these: you can always refer back to the list later.

PRINT SQR(5) SIN(X)


Trigonometrical functions. The
or PRINT SQR(BT2+CT2) COS(X) ! arguments must be in radians.
(1 degree = ~/180 radians]
The quantity in brackets is called the TAN(X)
argument of the function. In the case of SQR the j

argument must be zero or positive. ATN(X) The arc-tangenl of X. The result is in


Here is a program which displays the square radians, between —nil and n/2.
roots of all numbers between 100 and 115.
LOG(X) The natural logarithm of X (Log to the
10 PRINT "N";"SQR(N)" base e).

2GFORN = 100TO115 X must be positive

30 PRINT N;SQR(N; EXP(X) Equivalent toe*

40 NEXT N ABS(X) The modulus of X (X if X > 0;


otherwise — X)
50 STOP
INT(X) The largest whole number equal to or
less than X. Note that:

Example 3 INT (3.5) =3


If the lengths of three sides of a triangle are INT{-3.5) = -4
a, b and c, the area a of the triangle ts given by the

Ihe semi-perimeter, (a + b+c]/2.


Write a program which inputs three
numbers. Ifthey can be the sides of a real triangle
the program displays the area of the triangle;
otherwise (e.g. if the numbers are 1,1,10) the
program displays an appropriate message.
(Hint: if the lines don't forma triangle the
valueofs(s-a) (s - b) (s - cj is negative!]

Now check your answer in Appendix B.


You can also use the keyboard symbol v A number is a prime if it has no divisors
instead of the number 3.14159265 except itself and 1. The following program calcu
Here is an example lo show the use of some lates and displays prime numbers from 3 up to
of these functions. any value set by the user:
A ladder con have its length changed from 4
metres to 5 metres in steps of 20 cms. It is placed 10 INPUT "HIGHEST VALUE"; H
with its base 2.5 metres from a vertical wall, and
its top againsl the wall. Write a program to 20FORN = 3TOH
displaytneangle of the ladder with the horizontal
for each of ils 6 possible lengths. 30FORJ = 2TON-1
First we do the mathematics, using a
diagram. We use x to indicate the length of the 4GIFN/J = INT(N/J)THEN7G
ladder, and h to be the height of the top of the
ladder, and a to be the angle with the horizontal. 50 NEXT J

60 PRINT N;

70 NEXT N

80 STOP

h=Vx2-(2.5)2 (by Pythagoras!

a = arc tan fh/2.5) (in radians]

or a = (180/ir} • arc tan (h/2.5) in degrees.

Next we write the program, which has a


simple looped structure:

10 PRINT" LENGTH"," ANGLE"

20 FOR X=4 TO 5 STEP 0.2

30H = SQR(X|2-2.5T2]

40A = (180Ar)*ATN(H/2.5)

50 PRINT X, A

60 NEXT X

70 STOP

One of the most useful functions is INT. We


can use it to tell whether one number divides
another exactly. IfX is an exact multiple of Y, then
the condition

X/Y - INT(X/Y)

will be true; otherwise It won't.


Example 4
Study the prime number program (by tracing
if necessary) and work out how it works. Run it,
and time it for some value of H (say 500).
This method of calculating primes is actually
very slow. Design and incorporate some
improvements to make it run faster.

Hints: (a) No even numbers apart from 2


can be primes.

[b) In testing for possible factors, it is


enough to go as far as the square
root of the number.

Now check your answer in Appendix B.


Experiment 7.3:

APPENDIX (1) 10 P$= "+"


20 PRINT P$
30 P$= P$+"*"
40 IF P$<> "*******■**■*•"
THEN 20
50 STOP

(2) 10 PRINT "POUNDS", "DOLLARS"


20 PRINT
30P=10
40PRINTP, 1.77*P
50P=P+2
60 IF P< 32 THEN 40
70 STOP

(3) 10PRINT"CENT","FAHR"
20 PRINT
30C=15

UNIT:7 40F=1.8*C+32
50 PRINT C,F
60C=C+1
70 IF C< 31 THEN 40
Experiment 7.1
80 STOP

a) T,T,T,T,F,F,F
b) F,F,T,T

Experiment 7.2:
^^^^

Control Starting Final Increment No. of frmes


variable value value round loop

X$ "A" "ABBB" "B" 4


P 0 10 +1 11
Y$ "Z" "ZXYXY" "XY" 3
R 5 14 3 4

C 27 7 -5 5
Experiment 9.2:

10 POKE 53280,4
15 POKE 53281,7

20 PRINT"

30 PRINT " 9 limes

6 times

40 PRINT Tl$

50 GOTO 30

Experiment 9.3:

5 REM FLAG OF ICELAND 120 PRINT"


10 POKE 53280,14
15 POKE 53281,6

20 PRINT " _ 4 spaces —»

30 J = l 23spaces^";

40 PRINT 130J=l

140 PRINT

4 spaces—* - l space'

50J=J + 1

60IFJ<11THEN40

70 PRINT " 150J=J+1

160IFJ<1OTHEN140

4 spaces—* 170 PRINT "

<— 23 spaces—-";

80 J=l

90 PRINT"

40 spaces—*";

100J=J + 1 180 GOTO 180

110IFJ<4THEN90
DNIT UNIT:
Experiment 10.2: Experiment 11.1:

a) 10 PRINT "TABLE PROGRAM"


20 INPUT "TIMES"; N
30X=1
40 PRINT X; "TIMES"; N; "IS"; N*X
50X=X+1
60IFX<13THEN40 LETS=1
70 STOP

b) 10 PRINT "WHAT IS YOUR"


20 INPUT "SURNAME"; S$
30 PRINT "WHAT IS YOUR WIFE'S"
40 INPUT "CHRISTIAN NAME"; C$
50 PRINT "HER FULL NAME IS"
60 PRINT C$+" "+S$ DISPLAY
70 STOP S,12*S

ADD 1 TO

TRUE

FALSE

STOP
Experiment 11.2:

Glossary:
DISPLAY: HOW
D: Number of doors
MANY DOORS?
W: Number of windows
R$: THATCHED or TILED

INPUT D

DISPLAY: HOW
MANY WINDOWS?

INPUT W

DISPLAY: IS YOUR
HOUSE THATCHED OR
TILED?

INPUT R$

'THATCHED

FALSE

FALSE
DISPLAY: ANSWER
THATCHED OR TILED TILED"

DISPLAY: RATES ARE DISPLAY: RATES ARE


94+57*D+12*W 38+57*D + 12*W

STOP STOP
f
10 REM RURITANIAN RATES
20 PRINT "RATING PROGRAM"
30 INPUT "HOW MANY DOORS"; D
t
40 INPUT "HOW MANY WINDOWS"; W
T = 0
50 PRINT "IS YOUR HOUSE"
60 PRINT'THATCHED OR"
70 INPUT'TlLED"; R$ i

80 IF R$= "THATCHED" THEN 140


90 IF R$= 'TILED"THEN 160
100 PRINT "PLEASE ANSWER"
110 PRINT'THATCHED OR" INPUT "NUMBER OF
120 PRINT'TILED" BATCHES"; N
130 GOTO 50
140 PRINT "RATES ARE"; 38+57*D+12*W
150 STOP
160 PRINT "RATES ARE"; 94+57*D+12*W
t
170 STOP FORQ 144

1 N 1
Correct answers to three sample problems are:

b) 155
t
a) 95

DISPLAY:
"BATCH"Q

UNIT t
i
i

Experiment 12.1: INPUT "NUMBER OF


STAMPS"; S

10RS=0 \
20 INPUT "NUMBER OF INNINGS"; J /
t
30FORQ = 1TOJ
40 INPUT "SCORE"; S 0-g- INPUT
50RS=RS+S "VALUE (EACH)";
60 NEXT Q V
70 PRINT "AVERAGE="; RS/J
80 STOP

Experiment 12.2: T=T+S*V

Glossary ♦

N: Number of batches
/
4 Next Q \\
S: Number of stamps in a batch
V: Value of each stamp in a batch t
T: Running total due
Q: To count batch number
DISPLAY:
'TOTAL DUE-";
T; PENCE

(stop)
10T=0
20 INPUT "NUMBER OF BATCHES"; N
30FORQ=1TON
40 PRINT "BATCH"; Q
50 INPUT "NUMBER OF STAMPS"; S
60 INPUT "VALUE (EACH)"; V
Input: "OLD
70 T=T+S*V BALANCE"; B
80 NEXTQ
90 PRINT "TOTAL DUE="; T; "PENCE"
100 STOP
Display:
TYPE DETAILS
OF CHEQUES.
USE 0 TO END

Input:
"AMOUNT"; V
Glossary

B: Current balance
V: Each new transaction

10 REM BANKING PROGRAM


20 INPUT "OLD BALANCE"; B
30 PRINT "TYPE DETAILS OF"
40 PRINT "CHEQUES. USE 0 TO END'
50 INPUT "AMOUNT"; V
60IFV=0THEN90 SetB=B-V
70B=B-V
80 GOTO 50
90 IF B<0 THEN 120
100 PRINT "YOUR BALANCE IS£"; B
110 STOP
120 PRINT "YOUR OVERDRAFT"
130 PRINT "IS £";-B
140 STOP

Display: YOUR Display: YOUR


OVERDRAFT IS; BALANCE IS; B

STOP STOP
Experiment 14.2:

Display
descriptive
heading

Glossary
Input "NEXT
PRICE"; P
P: Net price of clock
T: Total to be charged

N. True ^s*"
Stop ) <T P=0

T=P+V3P

T=P+Y4P

Display:
TOTAL TO BE
CHARGED IS; T
10 REM CLOCK TAX

20 PRINT "■«■ and UM CLOCK TAX PROGRAM


30 PRINT "GIVE NET PRICES"
40 PRINT "USE 0 TO END"
50 INPUT "NEXT PRICE"; P
60 IF P=0 THEN 180
70IFP>=12THEN100
80T=P+(1/3)*P
90 GOTO 140
100IFP>=16THEN130
H0T=P+4
120 GOTO 140
130T=P+{1/4)*P
140 PRINT "TOTALTO BE CHARGED"
150 PRINT "IS ";T
160 PRINT
170 GOTO 50
180 STOP
Experiment 14.2:

Display descriptive
heading

Input L

Display: "YOU MUST


GIVE AT LEAST ONE
I NON-ZERO NUMBER"

Glossary:
Input X
L: Largest number so far
X: Next number to be input

10 REM FIND LARGEST NUMBER


20 PRINT "GIVE NUMBERS ENDED"
30 PRINT "BY 0"
40 INPUT "NEXT"; L
50IFL=0THEN130
60 INPUT "NEXT"; X
70IFX=0THEN110
80IFX<LTHEN60
90L=X
100 GOTO 60
110 PRINT "LARGEST IS"; L
120 STOP
130 PRINT "YOU MUST GIVE AT LEAST"
140 PRINT "ONE NON-ZERO NUMBER"
150 GOTO 20

(Note: The following "solution" won't work


if all the numbers are negative — that is, less than
Display: "LARGEST zero.)
NUMBER IS"; L
10L=0
20 INPUT "NEXT"; X
30 IF X=0 THEN 70
40 IF X<L THEN 20
50L=X
60 GOTO 20
70 PRINT "LARGEST IS"; L
80 STOP

Why not?
Glossary:
UNIT-.15 A$: Keyboard character
X: Internal time at start of interval
Experiment 15.2(1): (jiffies)
T: Elapsed time (seconds)

Display

instructions

5 REM STOPWATCH

10 PRINT" ■■ and .
20 PRINT "STOPWATCH PROGRAM"
GETA$ 30 PRINT
40 PRINT'TO START THE STOPWATCH'
50 PRINT "HIT THEBKEY"
60 PRINT 'TO STOP IT, HIT S"
70GETAS
A$="B"
80IFA$o"B"THEN70
90X=TI
95 PRINT 'TIMING STARTED"
100 GET A$
Display:
■TIMING
110IFA$o"S"THEN100
STARTED" 120T=(TI-X)/60
130 PRINT "ELAPSED TIME WAS"
140 PRINT T; "SECONDS"
150 PRINT
160 PRINT "NOW HITANY OTHER KEY"
170 PRINT "FOR ANOTHER TIMING"
180 GET A$
190IFA$=""THEN180
200 GOTO 10
GETA$

A$="S"

T=(TI-X)/60

Display
elapsed time
time T.

GETAS
Experiment 15.2 (2):

S$ Keyboard character
M: Usedinlooptowait2seconds
T: 0 (forTails) or 1 (for Heads)
Display
heading

10 REM COIN TOSSING


Waitfo.
any key 20 PRINT" HUB and
30 PRINT "HIT ANY KEYTO TOSS'
40 PRINT "YOUR COIN"
50GETSS
60 IF S$="" THEN 50
70 PRINT "WAIT FOR IT!"
Display: 80 PRINT
"WAIT FOR IT!' 90 FOR M=l TO 2000
100 NEXTM
110T=INT(0+2*RND{0)]
120 IFT=1 THEN 150
130 PRINT'TAILS"
140 GOTO 160
Wait 2 150 PRINT "HEADS"
seconds 160 PRINT
170 PRINT "HIT ANY KEY FOR"
180 PRINT "NEXT GO"
190 GET S$
200 IF S$="" THEN 190
210 GOTO 20
T=0orl
at random

Display: Display:
"HEADS' 'TAILS"

Display i
instructions and
wait for any
440FORJ-1TO5
Experiment 15.4: 450 PRINT B$
460 NEXTJ
470 PRINTCS
READY 475 REMSHOW 10-59 DIFFERENTFACE PAIRS
480 Q= INT (10 +50 * RND (0))
5 REM CRAPS 490FORZ = 1TOQ
10W = 212*256 500A=INT(1+6*RND(0)]
15 POKE W +24,15 510B=INT(1+6*RND(0))
20 POKE 53281,1 515 REM SOUND ANOTE WHICH DEPENDS
25 POKE W +6,0 ONAANDB
520 POKE W+4,0
30 PRINT" HHand UMJ 13iand5" 525 POKE W+5,7+1,10
40 PRINT"THEGAMEOFCRAPS IS PLAYED 530 POKEW+,10+(A*A+2*B*B]
WITH" 535 POKE W+4,33
I r( o 1 * ' I *' I ' > I '" I1' I ■ ■ 1
50 PRINT" TWO DICE. FIRST YOU BETAND H0MtlCRSR|CHSH I CRSR I CRSH I CRSR I CRSR
THEN YOU
60 PRINT"THROW.IFYOUGETASCORE
chspIchsrIcrsh
OF7OR11,
70 PRINT "YOU WIN.IFYOUTHROW2,3
OR 12, YOU
80 PRINTTOSE.IFYOU THROW ANY
CRSRlCRSRlCRSR
OTHER NUMBER,
90 PRINT "YOU DON'TWIN OR LOOSE
STRAIGHTAWAY; ;
10 0 PRINT "YOU KEEP ON THROWING
545REMWAITABIT
UNTILYOU
550 FOR M=l TO 30
110 PRINT"THROWTHESAMEASYOUDID
555 NEXTM
FIRST
560 NEXTZ
120 PRINT "TIME (AND WIN)
565 REM STOP SOUND
130 PRINT "OR
570 POKE W+4,0
140 PRINT"THROWA7(ANDLOSE).
585 REM USE LAST VALUES OF A, B
150 PRINT
590T=A+B
160 PRINT"HITANYKEYTOCONTINUE
595 REM JUMP IF PLAYER WINS OUTRIGHT
240 GET AS
600IFT=7THEN1000
250IFA$ = ""THEN240
610 IFT=11 THEN 1000
255 REMSETA$,B$,C$,TO LINES OF DICE
615 REM JUMP IF PLAYER LOSES OUTRIGHT
PICTURE
620 IFT=2THEN 1100
260 A$ = "^- 4 spaces— r ^
630 IFT=3THEN 1100
<- 2 spaces -» r \ " 640 IFT=12THEN 1100
270 B$ = "*— 4 spaces ~* I «— 3 spaces —» 650 PRINT
660 PRINT
I <— 2 spaces —* I «— 3 spaces —* I "
670 PRINT
280 C$ = "<- 4 spaces — ^. j
<-2 spaces—* ^ j "
680 PRINT "YOU HAVE TO MAKE"; T;
"BEFORE 7"
285 REM GET STARTING CAPITAL
CRSfl I CRSH | CRSft | CHSH
700 PRINT" 1
290 PRINT" ■MHand
300 INPUT "STARTING CAPITAL"; C
305 REM NOW START NEXT BET ^m^3 spaces-HIT ANY KEYTO GO ON"
310 PRINT"HITANY KEY FOR NEXT BET" 710 GET R$
330 GET R$ 720IFR$=""THEN710
340IFR$=""THEN330
350 PRINT "YOUR CAPITAL NOW IS"; C 730 PRINT" ^^| andBS^3 spaces-
370 INPUT "HOW MUCH DO YOU BET"; W NEXT THROW (BET=";W;")"
390IFW<=CTHEN420 740 PRINT'%- 3 spaces -MAKING";T
400 PRINT "YOU CAN'T AFFORD IT" | CRSR | CRSR | CRSR | CRSR |
410 GOTO 310 750 PRINT"
415 REM ORGANISE FIRST THROW 76Q PRINT A$
770FORJ = 1TO5
CflSR I CRSH ICRSR
420 print" mmmandwiiwmwmwm 780 PRINT B$
^3 spaces-FIRSTTHROW(BET = ";W;")" 790 NEXTJ
800 PRINTC$
CRSR I CRSR I CRSR I CR3R I CRSR I CRSR
430 PRINT" 805 REMSHOW 10-19 DIFFERENTFACE
PAIRS
810Q=INT(10 + 10*RND(0)]
APPENDIX A 1
820FORZ-1TOQ
830A=INT(1+6*RND(0}]
840B=INT(1+6*RND(0))
845 POKE W+4,0
850 POKEW+5,7 PROBLEM SOLUTIONS ||
855 POKE W+1,10+3*(A*A+B*B)
Example 1:
860POKEW+4,33 -

Qhg Mi|L
ISR |c 1SH IC 1SR I CHSR 1 CRSR 1 crshI
370 PRIN - ^ ■
10INPUTV
CRSR CRSR CRSR CHSR CRSR CHSH ICRSR ICRSR ICRSR
20 INPUT R
30 PRINT "A=";V|2/R
CHSR CHSR CHSR CRSR CHSH
40 STOP
"■A

ii CRSR CRSH cr'sr CRSR CRSR CRSH ■ CHSR IcRSR IcRSH Example 2:
^^"

CRSR CRSfr
";B 10 PRINT"X FORMULA"
880FORM=1TO30 20 FOR X=0 TO 2 STEP 0.2
890 NEXTM 30 PRINT X; 1/(1 +X|2)
900 NEXTZ 40 NEXT X er
905REMSILENCE 50 STOP
910POKEW+4,0
925 REM IF A+B=T PLAYER WINS
930IFA+B=TTHEN1000 Example 3:
935 REM IF A+B=7 PLAYER LOSES e?
940IFA+B=7THEN1100 10 PRINT "GIVE THE THREE SIDES"
^.
945 REM ELSE PLAYER THROWS AGAIN 20 INPUT "A"; A
950 GOTO 700 30 INPUT "B";B
990REMPLAYERWINS 40 INPUT "C";C
CRSR I CRSR I CRSR I CRSH I CHSH I CRSR I CRSR i 50S=(A+B+C)/2
1000 PRINT" 1 60 X= S*(S - A)*(S - B) + (S-C] w

^3 spaces->YOUWIN" 70IFX<0THEN100
1005 REMADDWINNINGSTO CAPITAL 80 PRINT "AREA IS"; SQR(X]
1010C=C+W 90 STOP
1015 REM PAEAN OF PRAISE 100 PRINT "THESE ARE NOT THE"
1020POKEW+l,n0 110 PRINT "SIDES OF A TRIANGLE"
1025POKEW+5,8 120 STOP
1030POKEW+6,0
1040FORJ=1TO8
Glossary:
1050POKEW+4,33
1060FORK=1TO70
A, B, C: Three "sides" of triangle
1065 NEXT K
S: Semi-peri meter
1070POKEW+4,0
X: Square of area (if any)
1075FORK=1TO80
1080 NEXT K
1085 NEXT J
10 95 GOTO 310
1100 REM PLAYER LOSES
I CRSR I CHSR I CRSR I CRSR I CRSR I CRSR I CRSR I
1110 PRINT" I I 1 1 1
5?"
CRSH I CRSH ICRSR
mm in ni <- 3 spaces -* YOU
yo LOSE"
1115 REM CHIRPOFTRIUMPH"
1120 POKE W+5,0 Example 4:
1125POKEW+6,240
1130 POKE W+1,100
10 REM SLIGHTLY FASTER VERSION
1140 POKE W+4,33
20 INPUT "HIGHEST VALUE"; H
1150 FORJ = 100TO5STEP-0.3
30FORN=3TOHSTEP2
1160 POKE W+1,J
40 Q= SQR (N)
1170 NEXTJ
50FORJ=2TOQ
1180 POKE W+4,0
60IFN/J=INT(N/J)THEN90
1190 POKE W+6,0
70 NEXTJ
1195 REM TAKE LOSS FROM CAPITAL
80 PRINT N; is-
1200 C=C-W
90 NEXT N
1210 IFO0 THEN 310
1220 PRINT "YOU ARE NOW BROKE" 100 STOP
1230 STOP
APPENDIX

Error Messages Next Without For


The FOR-NEXT structure of your program is
This list covers errors which can arise if you wrong.
use the BASIC facilities described in this book.
Other errors can occur if you run programs of a
more advanced nature. Out of Memory
The computer has run out of space in the
memory. This only happens with very long
programs, or ones which use large amounts of
Division by Zero data.
Dividing a number by zero is not allowed.
The error may arise in commands like
Redo from Start
10 A = 5/0 If an INPUT command expects a number,
and you type something which isn't a number, the
or 20B = Q/(J-J] computerwill display this message ond let you try
again.

Extra Ignored
If you type too many items (numbers or
String Too Long
strings) in reply to an INPUT command, the extra A string formed by concatenation is larger
ones will be ignored. The program doesn't stop. than 255 bytes.

Illegal Quantity Syntax Error


A number used in a command is loo large (or A "command" has broken the rules of BASIC
too small}. For instance, any number you POKE rommor. Possible causes are mismatched
into a location must be in the range 0 to 255. _ rackets, mis-spelled keywords, or elements of
This error can occur in commands like expressions in the wrong order.

10 POKE 36878,1234
Type Mismatch
or 20J = 300 This means that a number has been used
instead of a string, or vice versa.
30 POKE 36876, J

Verify Error
Load Error The verification process has failed. Try
Your program is not loading correctly from SAVE'ing the program again.
fhe cassette recorder or the floppy disk. If using
a cassette, try cleaning the reading head.
Alternatively, the program may not have been
recorded correctly in the first place, or the tape
or disk may have been damaged by a magnetic
field.
commodore
COMPUTER

You might also like