Commodore 64 An Introduction To BASIC - Part 1
Commodore 64 An Introduction To BASIC - Part 1
TO BASIC - PART 1
THE COMPREHENSIVE TEACH YOURSELF
PROGRAMMING SERIES
t commodore
COMPUTER
CONTENTS
Related Cassette
Subject Programs
Afterword
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
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
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:
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.
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-
READY
LOAD "TESTCARD"
PRESS PLAY ON TAPE
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.
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:
BREAK IN 560
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:
(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]
READY
LOAD "HANGMAN"
PRESS PLAY ON TAPE
[for tape]
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
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 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:
SYMBOL XCVBNM, . /
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
CHRIS
1
BLOGGS
EXPERIMENT type
Clear the screen ( ■MMI and
AUSTRIA
Move the cursor back over the I.
AUSTR-
cursor '
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.
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
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.
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
yellow
ITALY TANZANIA
21
red
white
SWITZERLAND
white white
red
white white
1 I white
blue blue
] blue r
white
red
blue blue
[_ 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
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
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
PPINTE-5
PfllNTOHDeAR"
PRINT ENOUGH
PRINT "l*/^
PRIUT3,J7
PftlMT^i?^ 2:2*2.2/7
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
BOLTON UNITED
KELSO CITY
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:
READY.
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
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
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
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
NORTH
NORTH-WEST
WEST
SOUTH-WEST
15 PRINT "NORTH-WEST"
Now enter the program and run it, holding
10LETA=1 10A = 1
10B-0
20 PRINT A 20 B = A*A
20 PRINT B
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.
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:
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.
EXPERIMENT
any two numbers by quoting both numbers:
UST2000-2090
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:
LIST 1100
LIST-80
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.
r^ LIST 5
(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
• 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
SAVING FAMILY
READY.
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"
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 -
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_
A<5
N$o"JIM"
A$+"NE"<>"JOANNE"
5>X
X + Y<>13
X + 2 = Y
LETA$ = "JOAN"
LETX = 5
LETY = 7
X<7
X>=5
A$o"X"
YoX
A$< "FRANCES"
%
A$ > "JOAN"
Y = 8
10X$ = "A"
7-2
20PRINTXJ
30 X$=X$ + "B"
40 GOTO 20
50 STOP
IFX$o"ABBBB"THEN20
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)
20 PRINT P,P*P ■
30P=P+1
401FP<11THEN20
50 STOP
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
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
11750
23500
ond so on.
In BASIC
Y=X+2
20PRINT"ALPHA=";A
30 A-A+3
40 B=B+37
50 PRINT "BETA=";B
60 STOP
VARIABLES A: 5
10P=1
PROGRAM
DISPLAY
20 PRINT P;P*P*P
10A=5 30P=P+1
ALPHA = 5
30 A=A+3 50 STOP
DISPLAY PROGRAM
50 STOP
40 IF P<4 THEN 20
50 STOP
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
40Q-Q + 1 i
50 IF Q<3 THEN 30
60 STOP 1
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
VARIABLES P:-fcfl-3-4
DISPLAY PROGRAM
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
20P=1 READY
40IFP<13THEN25 A PLUS B = 53
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.
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:
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.
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
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
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
Cursor home
Cursor up and
Cursor down
Cursor right
Black and
White and
Red and
Cyan and
Purple and
Green and
Blue and
Yellow and
Orange and 1
Brown and 2
Greyl and 4
Grey 2 and 5
Grey 3 and 8
Reverse on and
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:
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
Tl$ = "193746"
Tl$ = "090000"
10 PRINT Tl$
Experiment 9.2 Completed
20 GOTO 10
and run the program again.
What happens if we want more than one
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
70 STOP
40PRINTPS,2175*PS
EXPERIMENT
command.
The INPUT command comes in several
slightly different forms. We'll look at some
examples, and mention a few general rules.
20 INPUT N$
30 PRINT "HELLO
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
or { 19
30IFSX$="MALE"THEN70
60 STOP
90 STOP
MALE OR FEMALE?
INPUT AGE
INPUT SEX
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
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
STOP STOP
INPUT AGE
TRUE
FALSE
DISPLAY "I DONT
AGE<=115?
BELIEVE YOU"
INPUT SEX
SEX =
'MALE'
FALSE
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
-N
IJ'
TRUE
SEX =
)
'MALE" i
FALSE
SEX =
FALSE
DISPLAY "YOU MUST
ANSWER MALE OR
I1JI
'FEMALE' FEMALE"
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
Increment
10J=4 10FORJ=4TO20STEP2
40IFJ<22THEN20
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
20S=1
40 PRINT 9*5
50S=S+1
60 IF S<13 THEN 30
70 STOP
(i) 10FORQ=1TO16STEP5
20 PRINT Q;
30 NEXT Q
(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.
10FORR=5TO3
20 PRINT R
30 NEXT R
will display
50 STOP
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
Name Purpose
RT=Q
To keep running total of cannon balls
1 L 1
Next, we'll write down some of the actions
our program needs to take:
STOP
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
POKE 54296,0
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:
Raspberry
1 Ia
1 .
2150 REM *** END OF HEART BEATING*** Switch off
Sound
Commands to be copied ^i
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.)
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
POKE54275,P/8
Glossary
Initialise
S: Used to add up values of items
P: Used to count the items
X: Used to input individual items
30 INPUT X
40S = S+X
Display
summary
50 NEXT P
70 STOP
NEXT NUMBER? 10
AVERAGE IS 7
BREAK IN 90
READY
10S=0
20N=0
40S=S+X
50N = N + 1
70IFM$ = "YES"THEN30
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
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.
Display
summary
Hint: Your display section will be a little more
complex than usual. If B is a variable which
TYPE DETAILS OF
AMOUNT? 0 ^
YOUR BALANCE IS £1.51
TYPE DETAILS OF
AMOUNT? 3.50
Typed by
AMOUNT? 1.50
AMOUNT? 3.00
AMOUNT? 0
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"?
Add I to
NEXTTHROW? T
NEXTTHROW? E
Is item Add I to
H: To count number of heads
a "T"?
T: To count number of tails
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
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
120 GET AS
Clear screen and
Cloud 1
give instructions
130IFA$ = ""THEN120
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
20 5 POKE 54278,240
' Record current time ) Cloud 6
S. Stop tone r
207POKE 54277,16
220 X = Tl
230 REMWAITFORANYKEY
STOP
240 GET AS
250IFA$ = ""THEN240
5 REM COPYRIGHT (C) ANDREW
COLIN 1981
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
No. of throws 0)
PRINT Tl
and later
PRINT'THATTOOK"; S; "SECONDS"
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.
• •
• •
• •
• • • • • •
• • •
• • • • • •
S: Player's stake
10 INPUT "STAKE"; S
30 Dl =INT(1+6*RND(0))
50D3 = INT(1+6*RND{0))
70IFDloNTHEN90
110IFD3oNTHEN130
120C=C+1
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:
Display amouni
of capital
remaining
Can he
afford it?
Imitale -•
one spin/throw/deal
Adjust capital
according to win
or loss
Display:
YOU'RE BROKE!
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.
fa
A
! 133
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
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
FORX = 0TO2STEP0.2
NEXTX
60 PRINT N;
70 NEXT N
80 STOP
30H = SQR(X|2-2.5T2]
40A = (180Ar)*ATN(H/2.5)
50 PRINT X, A
60 NEXT X
70 STOP
X/Y - INT(X/Y)
(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:
^^^^
C 27 7 -5 5
Experiment 9.2:
10 POKE 53280,4
15 POKE 53281,7
20 PRINT"
6 times
40 PRINT Tl$
50 GOTO 30
Experiment 9.3:
30 J = l 23spaces^";
40 PRINT 130J=l
140 PRINT
4 spaces—* - l space'
50J=J + 1
60IFJ<11THEN40
160IFJ<1OTHEN140
<— 23 spaces—-";
80 J=l
90 PRINT"
40 spaces—*";
110IFJ<4THEN90
DNIT UNIT:
Experiment 10.2: Experiment 11.1:
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"
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
1 N 1
Correct answers to three sample problems are:
b) 155
t
a) 95
DISPLAY:
"BATCH"Q
UNIT t
i
i
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
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
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
Display descriptive
heading
Input L
Glossary:
Input X
L: Largest number so far
X: Next number to be input
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
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
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.
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