The Essential Guide I0 Timex/Sinclair - Home: Puters
The Essential Guide I0 Timex/Sinclair - Home: Puters
HOME ÇA PUTERS
to-understand language, about hardware, software and programming
skills. The Essential Guide to Timex/Sinclair Home Computers covers
all aspects of operating and programming Timex/Sinclair home com-
puters, including: turning the machine on (not as obvious as you
think!); the basics and the five points of Sinclair BASIC; designing
programs incorporating subroutines, loops and nested loops; using Ever Need to Become an
strings, lists and arrays; generating graphics on the T/S 1000 and color
graphics on the T/S 2000; addressing the computer's memory with
Sinclair 1000 and 2000
PEEK and POKE commands; and special tips on editing and debugging
techniques. It also includes a complete program library, as well as Games
many exercise and game programs to use while you learn, a section
on applications, a simple guide to error codes, a special summary of Graphics
Sinclair BASIC commands, an explanation of character sets and codes,
and much more. This is the only book you will ever need for your
Subroutines
Timex/Sinclair 1000 or 2000, and the perfect tool for building program-
ming confidence no matter what kind of computer you own.
Applications
Prigram Library
instruction in BASIC
A Touchstone Book Cover by Zimmerman
complete Users Guide
Foyster Design
iô^ç^ ^^^^ra Sound
Published by Simon & Schuster, Inc.
New York
TIMEX/SINCLAIR
HOME COMPUTERS
by
PETER MORSE, IAN ADAMSON
BEN ANREP and BRIAN HANCOCK
UNIVERSI T ÄTSBtBLIOTHEK
HANNOVER
TECHNISCHE
INFORMATIONSBIBLIOTHEK
A TOUCHSTONE BOOK
Published by Simon & Schuster, Inc.
NEW YORK
• •
711C
UB T B Hannover 89
100 541 208
)111143 Ill II I
5TY3
• •
IMPORTANT NOTE FOR ALL READERS
PART ONE
FIRST STEPS xvii
B1 Connecting Up 7
B2 The Keyboard 9
B3 Cursors 10
B4 The Different Character Types 12
FIRST STEPS
1
Figure 1
• speed constant. The cheapest solution to this in the long term
( especially since if you're not sure about the state of the batteries you
ZX 81 SYSTEM DIAGRAM have to put in new ones) is to buy nickel-cadmium batteries and a
charging unit. All recorders have automatic level controls for
a.c. household power supply recording, but some cause problems with their continual variation
around the correct level ('hunting'). Get a model that has been shown
to be compatible with the Sinclair computers.
Having a TV for exclusive use with your computer system is a good
idea, to avoid having to unplug and move around elements of your
system (it also avoids arguments with non-computing members of the
AERIAL
family!).
SOCKET
Some problems can interfere with the operation of your computer
(leaving to one side things like spilling coffee on it or otherwise abusing
it!). The first is overheating. After the computer has been on for some
time, it may heat up to such an extent that it `whites out' and wipes out
the program you have just finished, except for that last line. This is
very irritating, to say the least. Some ZX81s seem to suffer from this
more than others. If it is a persistent problem, it can be helped by
placing a fairly hefty chunk of metal on top of the case to radiate heat
away more effectively. It should be approximately 3 x 2 inches and 0.5
inch deep, have a fl at surface to sit on the ZX81 case, and should be
placed on the case, above the keyboard, on the left-hand side of the
16k RAM
case.
The corollary to this problem is that you should SAVE a long
I ^ I❑ program being developed or keyed in at intervals, and/or take listings
ZX81 PRINTER from the printer, to avoid a total loss if you do get a white out. The
MIC. 000000000 same problem can also be caused by two other factors, and this
O00000000
om000mo procedure will protect against the worst results from these problems as
procedur
1 m130000 0 well. first is that household power supplies are sometimes
interrupted, or occasionally have brief large voltage fluctuations.
NOTE: U.S. USERS MAY HAVE ANTENNAE ON/OFF SWITCH FITTED IN AERIAL
Computers are sensitive to such things, and a crash may be caused.
LEAD, SHOWN AS DOTTED BOX IN DIAGRAM. Other than buying a stabiliser which will continue to supply power
during such an interruption (of very short duration, but computers
memory is needed. RAM memory of up to 48k is available for the work fast!) we cannot protect against a.c. supply fluctuations, but
ZX81, but 16k is more than enough for our purposes. Independently similar results can sometimes be caused by appliances connected to the
produced RAM packs are usually just as good as those produced by same local power circuit switching on and off, and this should be
Sinclair. investigated if the problem is frequent.
The cassette recorder should be mono, since stereo tape deck The other main source of problems is the connector to the RAM
recording heads can cause problems, even used on one channel only. pack and printer via the edge connectors at the back of the ZX81.
The cheaper recorders work somewhat better (due to the less Movement can be caused in this connector by flexing the system whilst
sophisticated audio circuits being better for handling the crude form of keying in programs. This can be minimised by always pushing the
the computer's signals) than more expensive ones, but try to get one connectors home firmly before switching on, but a better solution is to
with a tape counter, as finding programs without one can be attach the components to a board, fixing them down to a suitably rigid
irritatingly time consuming. You should always use the same recorder, base with `Blu-Tack' or the double sided adhesive pads that are now
as problems can be encountered when playing back tapes recorded on a available. Fix the printer down as well – the process of tearing off
different machine. Battery-operated recorders actually avoid some printout can move printer and connector if you are not careful. Note
potential problems, but must always have good batteries, to keep tape that the method of fixing cannot be permanent, which is why Blu-Tack
2 3
or a similar plastic fixative is recommended.
• • impulses on cassette tapes. They
The edge connectors themselves are gold plated, but they connect to can be played back (loaded) at
the printed circuit board edges which may become oxidised, causing any time for use again. The
circuit problems (not necessarily white-outs or crashes – the keyboard computer reads the data from
may cease to work, or the printer miss lines, for example). Proprietary the tape.
(non-abrasive) contact cleaners should be used to ensure clean
contacts.
ZX printer Output device, to provide a
Other than the problems above, the only maintenance that should be permanent printed record of the
needed is the brushing away of the dust that accumulates in the printer screen display, program listings
from the burnt-off particles of paper. After removing the paper holder, or information in the computer
use a soft small brush (e.g. a small paint brush) to clear away the dust. memory. Prints on
Pay particular attention to the slot in which the electrode runs, but if, electrosensitive paper.
as sometimes happens, the electrode is visible, do not disturb it. (The
electrode is a small piece of wire which is normally not visible, but if Add-on memory enabling large
16k RAM pack
BREAK has been used it can be left in the middle of the printer slot.) programs to be stored and run.
K stands for kilobyte. One byte is
eight bits, which are the binary
digits (0 and 1, represented by
A2: Function of Components on-off switches in the computer)
computers work with. A kilobyte
This is a programming text, not a manual on computer architecture or is roughly 1000 bytes, hence the
computer science. However, we thought it might be useful to provide name. (It is actually 2 1 °, 1024).
you with a brief rundown of the functions of each of the components of
your microcomputer system. Supplies the d.c. current (9 volts
Power supply
at 1.2 amps) to run the
Device Function computer, RAM pack and
printer, from the household
ZX81 computer board Data processing and control of power supply.
(inside case) information handling. Input
from keyboard or cassette. To interconnect the devices
Cables
Output to TV screen and which make up the system. The
printer. printer uses the same socket as
the memory pack and has an
Keyboard Input of information. Programs, extension socket to allow this.
data and commands are keyed
in. On-line control.
The printed circuit board inside the ZX81 holds and connects the IC
TV set Used as V.D.U. (visual display (integrated circuit) microchips which provide the computing facilities.
unit) monitor. Provides on-line
These are:
output of information – visual 1 Z80A CPU (Central Processing Unit) microprocessor chip
display of programs, results which is the heart of the system. It is used in many other
(data, graphs, pictures) and microcomputers, and performs the arithmetic manipulations.
control commands. 2 ROM (Read Only Memory) chip holds the 8k BASIC
interpreter which translates BASIC instructions into the
Cassette recorder Off-line storage of information. machine code instructions that the Z80A operates with. The
Program data are stored (written) data in this chip is fixed, hence the name, and also stable – it
as coded electromagnetic remains when the power is switched off.
4 5
3 RAM (Random Access Memory) chip provi es a 1k" memory
store. When the memory pack is fitted it blocks off this memory
•
SECTION B: GETTING TO KNOW THE ZX81
and substitutes its own 16k of memory. This memory is
volatile – the data is stored as electrical impulses and is lost when
the power is switched off. This memory stores the BASIC B1: Connecting Up
programs,.the values of variables (including some system variables
1 Lay out the ZX81 system devices on your work area as on page
that the computer uses to organise its own affairs), a memory
2. It is far better to have an area where the system can be set up
picture of the TV screen display, and the stacks which hold the
permanently. Failing this, a board can be used to mount the
numbers whilst they are being manipulated. This is covered in
components.
more detail in Section U.
4 The Logic chip co-ordinates the operation of the other chips. 2 Place the a.c. power supply plugs of the power supply, TV and
Also mounted on the board are: the stabiliser for the 5 volt supply the tape recorder next to the sockets. A plug board with multiple
computer takes from the power supply, the TV signal modulator and sockets mounted on it is better than an extension socket fitting.
the sockets for the connecting cables to the TV and cassette recorder. 3 Connect the printer socket into the 23 pin edge connector at the
back of the ZX81. Get the slot in the ZX81 board and the block
in the printer socket aligned and push in gently but firmly.
4 Connect the 16k RAM pack socket into the extension connector
at the back of the printer socket in the same way. This is better
done with the ZX81 fl at on the table to avoid too much stress on
the connectors, which might occur if you are holding up the
ZX81.
5 With both connectors inserted, push the RAM pack firmly in to
ensure the connectors are fully seated home.
6 Connect the power supply cable into the socket marked DC on
the left-hand side of the ZX81.
7 Connect one end of the twin jack-plug leads, placing one jack-
plug into each of the MIC and EAR sockets on the cassette
recorder.
,Place the other jack-plugs into the ZX81 sockets. It is very
useful to have the EAR and MIC sockets marked on the top of
the ZX81 case, where the marks can be seen. Use sticky labels of
some type to mark which is which, and also the exact centre of
the plug socket. This will save much probing of sockets (there
are no guides to ensure you get the socket) and peering at the
markings on the side of the ZX81, which are scarcely visible
when the ZX81 is flat on a surface.
The yellow banded plugs should go to both MIC sockets. You
can also mark the other jack-plug with E or EAR as a helpful
aid. Push the jack-plugs gently in, making sure the tips are in the
sockets (which has to be done by feel) until a resistance is felt,
then push until they click into place. Waggle them slightly to
ensure they are well-seated.
8 Connect the aerial lead into the TV aerial socket at the rear of
the TV and into the TV socket on the ZX81. A slight twisting
motion may be needed if the fit is tight.
'2k on the TS 1000. US Users will find that the TV connects to the antenna lead with
standard terminals, and an antenna ON/OFF switch is fitted between
the antenna lead and the antenna lead that plugs into the
6
7
• •
Timex/Sinclair 1000 version of the ZX81. This switch must of course memory reserved for the programs by pressing the NEWLINE
be ON. (ENTER) key. The program lines will then appear on the
printer when the COPY command is given.
9 Straighten the interconnecting cables on your work area at this 14 Press characters at random on the ke board. They will appear at
point. Make sure that the cassette leads are not in contact with the bottom of the screen. Press and I EDIT keys
any a.c. power leads. together to clear the screen.
SWITCHING ON
15 If the ® cursor will not appear on the screen switch off the
power supply and adjust the 16k RAM pack and printer
connections. Switch on the power supply again and retune the
I Ensure that the TV receiver is off and that no cassette recorder TV.
keys are depressed. N.B. Never adjust or pull out the RAM pack when the power
2 Plug the power supply, TV, and cassette recorder plugs into the supply is ON, you may damage it.
a.c. power supply. 16 Other components failing to work will probably be caused by
3 Switch on the a.c. power sockets (if they have switches). plugs not switched on, or fuses blown. Alternatively, it could be
4 There are no ON/OFF switches on the ZX81 or on most cassette that some connections are not being properly made. You should
recorders – they are now powered up. remove and re-insert jack-plugs and connectors.
5 Switch on the TV.
17 On leaving your computer:
6 Turn the volume control on the TV to zero. a Leave it connected up
7 Turn the brightness control to MAXIMUM. b Switch OFF a.c. power supply plugs and TV
8 Turn the contrast control to MINIMUM. Disconnect plugs from sockets.
c
9 Tune in the TV. With a rotary tuning control, turn to channel
36. Otherwise select a channel, using the pushbutton or other
channel select switch, and tune this channel in. When the TV is B2: The Keyboard
at the right setting, a small black square with a white K inset
The ZX81 keyboard has 40 touch sensitive keys arranged in 4
appears. This is the K-cursor, and appears on the bottom left-
hand side of the screen. rows of 10 keys.
U.S. Users should note that the Timex/Sinclair 1000 version of the At first sight it looks like a typewriter keyboard, but a closer look
ZX81 has a channel select switch for Channel 1 or Channel 2 fitted reveals that some keys have five functions or characters written on
underneath the case. Choose whichever channel is not transmitting in them. In fact:
your area, and select this channel on the TV and the computer.
Six different characters can be obtained from some keys!
10 Adjust the tuning: brightness and contrast until the cursor is
distinct, and the white K clear. The keyboard contains:
11 Check that the cassette recorder keys function. Insert a blank
cassette, and try all the controls. (1) The digits 0 to 9
12 Insert a roll of silver printing paper into the printer and press the The letters of the alphabet printed in upper case
(2)
button on the right-hand side of the printer to feed some paper (3) The complete BASIC language
through. Check the paper does not rub on either side of the – instructions
printer as it comes through. – commands
13 Press the I COPYJ key and then the INEWLINE (ENTER) key.
– arithmetic, conditional and logical operators
The printer will start to copy what is on the screen. About 3 – arithmetic functions
inches of paper will be fed through. There will be nothing (4) ` Grammatical signs and symbols
printed on it as there is nothing on the screen. A message 0/0 (5) Special control keys
will appear at the bottom of the screen. (6) Graphics symbols
N.B. The bottom two lines of the screen are never printed
and are used for keying in program lines and commands. These These are all called characters.
program lines, when correct, are transferred into an area of Notice that words like PRINT, RUN, SLOW, LET, INKEY$ are
8 9
•
written on the keys and are printed on the screen when we press that key
in the correct mode. w
The facility of complete words in the BASIC language being printed 1-
w
• z
at the press of a single key is called w Z Z
D
SINGLE KEYSTROKE BASIC z CO 4
ir ^ ^ Lu
w ^
On most other computers you have to key in each letter of, for m
CC
example, the instruction PRINT. This is inefficient. The ZX81 is very -J J N
^
powerful in this respect. w
w
The keyboard contains most of the characters in the ZX81 character o W •
x w w
set and a few special keys. Some 202 different characters are available. H zw
Some print on the screen, others are non-printing, e.g. RUBOUT O) N
J J A
(DELETE). ^-- W
Each of the different types of character is described in Section B4.
z ô
U
^
The ZX81 keyboard layout is reproduced in the diagram on the next 0 d
4 -J
page. o
J ^
-A- V
B3: Cursors CC ^X ^o
K
^ _
U
C O
(_O.1) ^
W
z Z z
L fGl II a
N ^
6! C D
CC
w
symbol or name should be typed in next. They appear in inverse video ^
CJ
W z
(a white letter in a black square).
A o ^
F-
U
K Keyword mode. V o
z
ZX81 expects a command H CC
N
'FJ
a line number O ^
z
or a keyword (D
N
^
Keywords are the symbols printed on the keyboard
o ^-
above the keys (see keyboard). SHIFTed keys also ^
zo
function in this mode.
^ z 3
0
J
N
z
U
U U
w CC
Letter mode.
w
1--
O 0 4
Ln CC
Occurs at most other times. z 7W z 4
w
ZX81 expects a letter
a number
w
1---/ ^ 11J
W
N
o
U
U
-J
U X w
W
^
an operator N 4
or a special command o u-) w
z o
SHIFTed keys function in this mode. 4 U 0 å
O
U N z
J
F Function mode.
N w
z
Obtained by pressing FUNCTION key (SHIFT, z
NEWLINE/ENTER). ^
11
10
Only one function can be obtained each time
^ KEYWORD
•
FUNCTION is pressed.
G Graphics mode. On top of the R key is the word RUN. This is a KEYWORD
Obtained by pressing GRAPHICS key (SHIFT, 9). character.
Mode lasts until the GRAPHICS key is pressed again.
In the graphics mode 36 different characters are All characters printed on the keyboard in this position are
obtained by pressing the keys with the SHIFT key KEYWORDS. KEYWORDS will be printed on the screen if the
depressed as well. These are shifted graphics characters. desired key is pressed when the ZX81 is in KEYWORD MODE (i.e.
38 different characters (mainly letters printed in the the K cursor is on the screen).
inverse mode) are obtained by pressing the keys.
S Syntax error cursor. Exercise
This cursor appears in a statement line at the bottom of
the screen if the computer finds that there is an error in
it. It appears when we try to enter an incorrect line of If the K cursor is at the bottom left-hand side of the screen then enter
program into memory (i.e. after we press NEWLINE a keyword. Press the PRINT (P) key. Notice that PRINT appears on
(ENTER) when at the bottom of the screen). the screen but the © cursor has changed to an j L I cursor and the
The I S I cursor appears next to the last error in the computer is in the letter mode. This means that it is expecting a letter
line. (There can be more than one). Editing on the line to be keyed in next, e.g. A.
can take place immediately. The IS cursor disappears If we try to key in another keyword, e.g. I PLOT I , the keyword
when an edit operation is performed. It will re-appear PLOT does not appear. Instead the letter Q is printed. So the rule is:
(if necessary) when NEWLINE (ENTER) is pressed
again. No two keywords may be entered in succession.
Current line cursor.
When entering statements into the program the last line To clear the screen and return to K mode press SHIFT I EDIT
to be entered is called the current line and is indicated keys together. Try it. Print different keywords on the screen. Which
by this symbol placed after the line number. The one does not print?
movement of this cursor up and down the screen,
pointing to different lines, is controlled by the 4 and LETTER
t keys (SHIFT 6 and 7).
If EDIT (SHIFT 1) is pressed, the current line is The LETTER characters (or QWERTY characters as they are
brought down to the bottom of the screen and can be sometimes called) are the bold type letters on each key. They are
edited. identical to those on a typewriter keyboard. It is worth trying to
B4: The Different Character Types memorise these. Do it by lines, and in groups of five.
Letter characters may be keyed in when the computer is in the letter
THE 6 CHARACTER TYPES ON A KEY mode and the I L I cursor appears in the entered program line, or at the
If we examine a particular key, say R
types, as seen in the diagram below.
I I , we can classify the 6 character bottom left-hand side of the screen. Certain letters may be entered in
the I K I mode as default when there is no keyword on that key, e.g. the
digits 0-9 and the full stop • BREAK is also an exception. A space
is printed in the I K mode.
I KEYWORD
RU N
I SHIFT I
I LETTER
<= <-
INVERSE
GRAPHIC
R GRAPHICS I
INT
1:1
I FUNCTION
S
12 13
Exercise
• •
What happens on the Screen
Keys to Press
Key in 1 PRINT to obtain the mode. Then key in the letters,
starting from 1 1.
What happens with NEWLINE (ENTER) and SPACE
I
I
D
PRINT I
PRINT Q
SHIFT
There are 39 SHIFT characters on the keyboard. These may be I SHIFT l "I PRINT "
obtained in the K or J L I modes, i.e. when 1K or I L I is on the
screen. GRAPHICS PRINT "
SHIFT
To obtain these characters or symbols e.g. <_ in our diagram,
press the SHIFT key and the desired (CHARACTER key at the^
Exercise , R I
PRINT " e
Start keying in the SHIFT characters starting with EDIT on the top "NM
I SHIFT I GRAPHICS PRINT
line of the keyboard.
Notice what happens with:
EDIT SHIFT I 11
PRINT " No" Q
THE ARROW KEYS ( t F^
GRAPHICS
RUBOUT (DELETE) NEWLINE (ENTER) at top of screen
FUNCTION
0/0 at bottom of screen
GRAPHICS
(NEWLINE (ENTER) © (clears screen)
INVERSE GRAPHICS
These characters are the inverse video letter characters, and are
obtained in the GRAPHICS mode, i.e. cursor on the screen, when
the desired key is pressed.
14 15
Exercise • Exercise
•
not the shift characters when in the
What happens when you press I SPACE ?
mode. 1G
Key in the characters as before, but this time only press the letters and
Using the above table, obtain all the modes and key in example
character types.
FUNCTION
ALPHABETIC CHARACTER/KEY TABLE
There are 24 Function characters that are obtained only in the
Function mode, when the U cursor is on the screen. The !cursor is The following table locates the letter or number key which provides
obtained by pressing the !SHIFT and I FUNCTION I keys together. each character (keyword, function, or symbol) on the keyboard. Use
Only one Function character may be entered. The mode changes to this table when entering programs until you are familiar with the
after entry. To input another Function character we need to get placing of all the commands. An * indicates a non-printing character.
back to the F mode again.
Exercise
BASIC Word Keyword (K), Function
or Shift and Key to Press
Get into the FUNCTION mode and key in all the function characters.
Key in – PRINT ABS Function G LPRINT Shift S
!SHIFT I !FUNCTION I ACS Function S NEW (K) A
Tt AND Shift 2 NEXT Shift N
!NEWLINE (ENTER) I ASN Function A NOT Function N
Function C OR Shift W
What happens? Press NEWLINE (ENTER) again to clear the screen. AT
ATN Function D PAUSE Shift M
Function U PEEK Function O
CHR$
HOW TO OBTAIN THE DIFFERENT CHARACTER TYPES PI (n) Function M
CLEAR (K) X
CLS (K) V PLOT Function Q
Character Number of Mode CODE Function I POKE Function O
To Obtain To Obtain the
Type Chars, the Mode: Character: CONT (K) C PRINT Function P
If we have asked it to do something it can't do, or forgotten to Statements may be keyed in via the keyboard in any order. The
include an instruction the computer will tell us what is wrong and give computer sorts them into the correct sequence. Statements are usually
us an ERROR MESSAGE. If the program runs without error numbered in tens so that additional statements are easily inserted later.
messages but doesn't do what we wanted it to then it is the For example:
programmers' fault. In either case we need to correct or EDIT or
DEBUG the program. We do this whilst the program is in the 10 INPUT A
computer, using the editing facilities of the computer. 20 INPUT B
Editing or revising a program is called PROGRAM 125 INPUT Cl (Inserted line)
DEVELOPMENT. When the editing is finished and the program 30 LET S=A+B
works we take a LISTING of the program on the PRINTER. We can
also SAVE a copy of our program on cassette tape and STORE it so The computer runs the program in order of statement numbers.
that we can LOAD it back into the computer.
The complete exercise of designing, coding, developing and
C5: Instructions
documenting a program is called PROGRAMMING.
to the computer. In this
A statement gives an instruction
C3: A Statement
example it is LET.
30 LET S = A + B
This is a BASIC statement:
10 INPUT A because they identify a type of
Instructions are called statement types
statement. In our example the statement is a LET statement. It tells
A statement is also called a LINE. A statement can: S have a value equal to the sum of the
the computer to let the variable
(1) instruct the computer to do something
(2) state something values of variable A and variable B.
A statement is composed of: a line number, e.g. 10
an instruction, e.g. INPUT C6: Numeric Variables
some variables, e.g. A
Statements are either: Executable – those which specify a program A numeric variable is the name given to a storage location
action, as with our INPUT A, or Non-Executable – those which which holds a number in the computer ' s memory.
provide information for the user of the program. A numeric variable can have a name which is:
All variables (e.g. A in our example) must be initialised to a start A letter from A-Z
value before being used in a program. In this case the statement: or A letter followed by a number
10 INPUT A A group of letters and numbers
or
tells the computer to request the user to input a value for the variable A Variable names must start with a letter.
from the keyboard. Examples of numeric variables: A
NUMBER 1
C4: Statement Numbers B2
X136
Each BASIC statement or line must begin with a statement TOTAL
number, as with 20 in this example.
20 INPUT B
Numeric variables are used to represent numbers inside the computer.
The number 20 is called a statement number or line number. The different values to a variable. The numbers we
We can give (or assign)
statement number is chosen by you, the programmer. It may be any give to variables are used in calculations.
number from 1 to 9999 inclusive. The computer uses the numbers to Variables are symbols or names given to parameters or quantities.
keep the statements in order. Each statement has a unique statement They represent the VALUE of the parameter, i.e. the number stored
20 21
•
in the named memory location. We can use variable names which
C7: Strings and String Iriables
remind us of the parameter concerned, but they should not be too long STRING
or you will find them tiresome to key in (which is why single letters are
usually used).
A STRING is a group of characters enclosed by quotation
For example, we could use:
marks.
S – Speed The following are examples of strings:
PRICE – Price of fish "PETER"
SUM 1 – Sum of the first set of numbers "12345"
R3 – Resistor Three "JANUARY 1ST, 1982"
In our program the statement ''!$..,,
10 INPUT A "REF:A2"
sets up a variable in the computer's memory with the symbolic name
A. We could have called it NUM1, or even FIRSTNUMBER.
As well as numbers, computers can also handle text or groups of
The statement tells the computer to ask us to input a value for A
characters. To define a group of characters as a string, we have to place
when we run the program. If we key in the number 3 the memory cell
quotation marks at the beginning and end. This tells the computer, for
allocated to A will contain the number 3. This value is then used in all
calculations involving A until we change its value. example, that the string "TOTAL" means the characters T,O,T,A,L,
In the statement: and not the numeric variable TOTAL, which is a number.
30 LET S = A + B Strings can contain any character which prints on the screen, plus
spaces, but a string cannot contain quotation marks, because the
S, A and B are the variables in the algebraic equation S = A + B. S is
our `unknown' and will take the sum of the values of A and B. The computer thinks it has got to the end of the string when it gets to the
computer will work out the value of A + B and put the result in the second quotation mark.
memory cell it has allocated to the variable S. The computer will not let Now that you know what a string is, we can tell you that strings can
us input LET A + B = S (it will give us a syntax error), because the be handled by string variables, just as numbers can be manipulated
variable to be given a value must come first. A + B is not a valid with numeric variables.
variable name.
Variables are so-called because their values can vary or change,
according to the values we input, or in the course of a program, when STRING VARIABLE
we instruct the computer to do something which causes the value to
change. For CONSTANTS, which are quantities which do not change A string variable is used to store strings. It consists of a single
their value, we set up a variable in the same way, by giving it a name letter (A to Z) followed by the $ sign. For example:
and a value with a LET statement and let it keep the same value – a A$, Z$, M$
variable that doesn't vary!
Variable names may be of any length, but they must start with a We allocate (or assign) strings to string variables with LET statements,
letter, and must only contain the alphanumeric characters (the letters A
as with numeric variables. For example:
to Z and the numbers 0 to 9). They can have spaces included, but this 10 LET A$ = "STRING 1"
is unwise, as it is easy to key in PRICEI, for example, when you 20 PRINT A$
initialised a variable as PRICE 1. The computer will consider them to The memory store allocated to A$ will contain the string `STRING l'
be two different variables. The inverse video (white on black)
characters also cannot be used in variable names. (line 10).
When we RUN the program the computer will print the contents of
memory store A$ on the screen (line 20), i.e. STRING 1. Note the
string is printed without the quotation marks. The string is just the
characters inside the quotes.
23
22
C8: Operators and Operands Cursor Keys to What appears
Character or
Press on the Screen
instruction
OPERATORS to key in
10 INPUT A
A
OPERANDS
NEWLINE
Operands are the variables or numbers which are (ENTER)
manipulated (i.e. operated on) by the operators.
In the line: Entered line is
transferred to top
30 LET S=A+B of screen
the variables S, A and B are operands.
*
on Spectrum in CAPS mode
BASIC is a `free format' language. The computer will ignore PRESS NEWLINE (ENTER) AFTER EACH STATEMENT
extra blank spaces in a statement.
The following statements are equivalent: The )NEWLINE (ENTER) I key must be pressed after each
10 INPUT A statement has been entered.
10 INPUT A ^ NEWLINE (ENTER) I
10 INPUT A
10 INPUT 20 INPUT B NEWLINE (ENTER) I
A
30 LET S = A + B j NEWLINE (ENTER)
The computer will automatically leave spaces after each line number 40 PRINT S NEWLINE (ENTER) I
and a space after keywords. It will list programs with all the other
spaces you include between instructions and variables. It will ignore
them when you run the program.
Pressing the NEWLINE (ENTER)1 key informs the computer that the
statement is complete. The computer checks the line for mistakes then
transfers the statement to the top of the screen and returns the I kl
C10: Keying in a Statement cursor to the left-hand side of the screen, ready for us to enter the next
program line.
Statement to be keyed in: Notice that the line at the top of the screen now contains the
10 INPUT A Press CURRENT LINE CURSOR:
NEWLINE (ENTER)
1>1
This indicates the last program line entered and accepted by the
If your computer system is set up and ready for use (see Section B I) the
computer. It appears immediately after the line number:
( I{ cursor will be in the bottom left-hand corner of the screen. You can
now key in the first statement. 10 I > I INPUT A
24 25
C11: Correcting Errors • If you are keying in the first ine of a program and there are no existing
lines at the top of the screen, pressing EDIT will clear the line.
RUBOUT (DELETE) If there are program lines at the top of the screen, pressing EDIT
clears the current line and brings down the program line marked with
The RUBOUT (DELETE) key acts as a backspace, deleting the > cursor. Pressing NEWLINE (ENTER) sends this line up
the character symbol or keyword immediately preceding (to again and clears the current line.
the left of) it.
Exercises
As we type in a line we may press the wrong key. For example, we 1 Start keying in the first line of the program. Don't press
might get: NEWLINE (ENTER).
10 INPUT S L I Play around with the cursor control keys and RUBOUT
where we pressed S instead of A. To correct this we press RUBOUT (DELETE).
(DELETE) and we get: 2 Delete the complete line.
10 INPUT I L I 3 Key in the first line and press NEWLINE (ENTER).
We may now continue and type in A. Key in the second line.
4 Delete the second line using EDIT and NEWLINE (ENTER).
5 Key in the second line. Key in the third line to read:
30 LET X = A + B. Press NEWLINE (ENTER)
I Use EDIT to bring this line down again. Use the cursor control
The horizontal arrow keys move the cursor one character or keys to put the cursor to the right of X and delete it. Insert S.
keyword to the left or right along a line as indicated. Leave the cursor where it is, and press NEWLINE (ENTER) to
send the line to the top of the screen.
6 Key in the complete program.
For obvious reasons, these keys are also referred to as cursor control
keys.
C12: Commands
To correct an earlier mistake on a line
COMMANDS are direct instructions to the computer. They
(a) Use the arrow keys to move the cursor to a position immediately are executed immediately. They do not need line numbers, as
to the right of the character to be changed. they are not part of a program.
(b) Press RUBOUT .(DELETE) to delete the incorrect character, Commands give us direct control over the computer.
and key in the correct character. Examples are:
(c) Use the arrow key to return the cursor to the end of the line, if RUN
you have more to key in. Otherwise, you may press NEWLINE LIST
(ENTER) immediately. It does not matter if the U cursor is in BREAK
the middle of the line. SAVE
To delete a complete line To execute a command, we key it in. If it is a command that is printed,
it will appear on the bottom line of the screen. This area of the screen
This can be done by using the key to get the cursor to the end of the must be empty. Then press I NEWLINE (ENTER) I. Some commands
line, if you are not there already, and then using RUBOUT are executed instantly, without pressing NEWLINE (ENTER) (e.g.
DELETE) repeatedly until the line is completely deleted and just the BREAK), and are not printed on the screen.
K cursor remains. This is tedious on a ZX81, without the Most commands are also used as instructions in programs. Some of
Spectrum's repeat key, especially on a long line. A better way is: the commands that can be used as direct commands are not actually
(1) Press EDIT very useful in this role. Equally, some that could be used in programs
(2) Press NEWLINE (ENTER) never are. However, each command has a key role to play in the
26 27
BASIC language and we will deal with the indivAuual commands as we
encounter them in the text.
•
of the screen just type the line number and press NEWLINE
You have already met the NEWLINE (ENTER), RUBOUT (ENTER).
(DELE TE), t- and - ^ commands, and the mode commands For example:
10 INEWLINE (ENTER)!
(GRAPHICS and FUNCTION). Together with EDIT, RUBOUT will delete line 10 in the program. You will see it disappear from the
(DELETE) and BREAK, plus the i and 4 arrow keys, these are the
commands that don't print, and act instantly. All the others need screen.
NEWLINE (ENTER) to be activated.
C14: Listing a Program on the Screen
slightly, i.e. perhaps only the line number and a variable are different. our program will be listed from line 30.
If you can save keystrokes by bringing down a line and revising it, then
do so. The technique is as above, but after (5) you must use the cursor
control keys to shift the L-cursor along the line and use RUBOUT
(DELETE) to erase the variable (or keyword) that needs to be We key in LIST, then the line number we want the listing to start at. If
changed. Insert the new character, and press NEWLINE (ENTER). we have a program that is longer than will fit on the screen, we use the
LIST (line number) command to display successive screenfuls of the
program. If the bottom line on the first screen is 210, for example, we
T would use LIST 220 to get the next set of program lines. Listing a
program on the Spectrum which is larger than a screenful produces a
These commands move the! > I cursor in the entered program SCROLL? prompt. Answering this with anything other than `N' or
at the top of the screen from one line to another. This enables BREAK scrolls the listing up so that the next screenful of statements
us to then copy down any line in the program for editing using can be seen.
I EDIT!
C15: Running the Program
Deleting a line in the entered program Our simple program has been keyed into the computer line by line and
entered into memory.
To delete a given program line which has been entered and is at the top Let's see if it works. We give the computer the command RUN.
28 29
RUN
• The screen is now blank.
easily:
e can get the program listing back very
RUN1
^ (NEWLINE (ENTER) I
The RUN command starts execution of a program at the Press NEWLINE (ENTER)
lowest numbered statement.
After running the program, the program listing re-appears at the top of
the screen if the NEWLINE (ENTER) key is pressed. The program
Run is a command and is keyed in. It appears at the bottom of the can now be edited if necessary.
screen. It will not be executed until (NEWLINE (ENTER) is pressed.
When we do this the program starts operating. The screen will go C16: Error Messages
blank and the L-cursor will appear at the bottom. (This will be a
C-cursor if you are using a Spectrum in CAPS (capital letter) mode, Our computer tells us it has finished running the program by giving us
using CAPS LOCK as we advised.) The computer is now running the a message. On the ZX81 this will be:
program and asking us to input a number for the variable A.
Key in the number 1 3 I and press I NEWLINE (ENTER) ] . The 0/40
L-cursor appears again at the bottom of the screen. The computer
requests another number, to be assigned to the variable B. Key in the at the bottom of the screen. The Spectrum gives an expanded version
number I I and press 1 NEWLINE (ENTER) of the message:
Our result (the number 8) is printed at the top left of the screen.
Notice the message that appears on the bottom of the screen. We can 0 OK, 40:1
also run the program from a line other than the first program line:
This tells us that no errors were found and the program finished at line
40 (the last line). The number after the colon can be ignored in most
RUN N Spectrum error messages, as it refers to multiple-statement lines. We
shall not use these in this text. There is one case where it is 2, as we
RUN (Line Number) shall see later.
This command starts execution of the program from the These special diagnostic messages appear at the bottom of the screen
specified statement (line) number. every time a program is run. If the program does not work a message
RUN 20 appears with the form:
will start a program at line 20.
E/N
Note that when the RUN N command is used all statements before the E is a number or a letter indicating the type of error that has caused the
specified statement number (N) will be ignored and any variables program to stop, and N the line number where the program halted due
defined in these statements will be considered by the computer to be to the error. The Spectrum adds a message briefly stating the cause of
undefined because it has not RUN the lines. The program will not
the error.
work and an error message will result. All values of variables are We look up the meaning of E in the list of Error Codes in Appendix
wiped out by the RUN command. II. This helps us to correct or debug the program, since we know what
We can RUN the program as many times as we wish: sort of problem has occurred and which program line it happened at.
If the program has been run once and the message is at the bottom of 1 Run the program on page 19 a number of times keying in
the screen, to rerun the program key in RUN. This overwrites the different values for A and B.
message and pressing NEWLINE (ENTER) starts the computer 2 Press NEWLINE (ENTER) to get the listing. Change line 30 to
operating the program. The L-cursor appears to prompt for an input read:
again (C-cursor for Spectrum in CAPS mode). 30 LET S=A+C
30 31
Now RUN the program.
•
The error message 2/30 (on the ZX81) appears. On the
and placed in cell S. The computer goes to the next
line.
Line 40 instructs the computer to output the 40 PRINT S
Spectrum we get 2: Variable not found 30;1. So we have a type
2 error and the program stopped at line 30. A type 2 error means value of S to the screen. The computer looks for the
we have forgotten to define a variable. We are now using the next line.
variable C instead of B, but we have not yet given C a value, and The computer can find no more statements to
the computer could not complete the operation of line 30 due to execute in the program and gives a message 0/40
insufficient information. on the screen telling us that the program finished
Insert a new line: with zero errors at line 40. The Spectrum gives the
25 INPUT C same message, in the form 0 OK, 40:1.
and run the program again. It now works. The computer now waits for more commands.
Why did the program originally stop at line 30?
Why do we now have to key in 3 numbers to make it work? C18: Naming the Program
3 Add an extra line at the beginning of the program. Key in:
5 PRINT "PROGRAM ADDS 2 NUMBERS" 5 REM "NAME"
RUN the program, starting from different lines by using: Programs are named in a REM statement. The program name
RUN is enclosed in quotation marks. The program is usually named
RUN 10 in the first statement in the program.
RUN 15
Why do you think RUN 15 does not work? We need to give our program a name in order to:
4 Edit the program to obtain the original version. Differentiate it from other programs
(1)
(2) Store it permanently on cassette tape (SAVE it)
(3) Put it back into the computer from cassette tape in order to run it
(LOAD it).
C17: How the Program Works The program name can be any combination of characters and any
length on the ZX81. On the Spectrum, program names for use with the
only
Line 10 tells the computer that a number must be
10 INPUT A SAVE and LOAD instructions must start with a letter, and can
input and given the name A, (i.e. assigned to the have 10 characters in the name.
variable A). The computer reads the line and prints It is sensible to keep the program name short and relevant to the type
an L_ I at the bottom of the screen,* reminding us of program, although some programmers name programs after
to input a number. The computer will wait until we themselves:
key in a number. The" number is then stored in "PETER 1"
memory cell A. The computer goes to the next line. "PETER 2" etc.
Line 20 tells the computer that another number, Programs which undertake various kinds of statistical analysis could be
20 INPUT B
to be assigned to the variable B, must be input. L named:
appears at the bottom of the screen* and the "STATSI"
computer waits until we key in a second number, "STATS2" etc.
which is stored in memory cell B. The computer Programs which perform calculations for experiments in the laboratory
goes to the next line. could be named:
Line 30 tells the computer that a variable S is to "OPTICS 3"
30 LET S=A+B
be assigned the value of the sum of the variables A "FRICTION"
and B. The numbers in cells A and B are added "TITRATION " etc.
If spaces are used in program names, it is easy to misread them, or
'This will be a C-cursor if using a Spectrum with the CAPS LOCK facility used, as forget that there should be a space. If the program name is not one
Spectrum users must do throughout this text to get program listings which appear the word, we can use an asterisk:
same as the ones in the text. Use the CAPS SHIFT and CAPS LOCK keys
"PETER* 1"
simultaneously on switch-on, and remember that the C-cursor will appear instead of
the L-cursor. We will not mention this again. "FOCAL*LENGTH " etc. ("FOCAL*LEN " for the Spectrum)
32 33
Program names and cassette tape codes should be recorded in a
DIRECTORY which enables us to access a PROGRAM LIBRARY
•
SECTION D: SAVING, LOADING AND LISTING
of programs stored on tape.
We need to name our program: List the program and add a line
which names the program. For example: Dl: Saving the Program on Cassette Tape
5 REM "SUMPROG"
We need to save programs on to cassette tape (the off-line storage medium
or 5 REM "PROG*1"
the Sinclair computers use) because when the power supply is switched
could be used. We will call our program "ADDER", so key in
off (or disrupted – variations in the mains supply can affect the
5 REM "ADDER"
computer) the RAM memory and the registers in the CPU are cleared
and we lose the program. The memory is said to be volatile. This means
we have to key it in again – not too bad for a 5 line program, but a 50
liner will take you an hour!
If we had made a copy of the program on to magnetic cassette tape
using the SAVE command we could have reloaded it into the computer
quickly, using the LOAD command. Tape storage is not the quickest
or most reliable method used for off-line storage, but it works, and has
the advantage of low cost. The ZX81 reads and writes tape fairly slowly
in computer terms, and a large program will take some minutes to
LOAD or SAVE. The Spectrum loads programs several times faster.
Software (programs) stored on tape is available for use when needed,
making it PERMANENT.
Software also has to be PORTABLE. Programs we write can be
used by other people with the same computer, or software available on
cassette can be bought.
SAVE
SAVE "NAME"
The SAVE command outputs the program and variables to
the cassette recorder. If the cassette recorder is in record mode
then a copy of the program will be made on the tape.
Spectrum users please note that the program name for SAVEing must
be 10 letters or less. The name can be in either upper or lower case (or
a mixture) but exactly the same name must be used to LOAD. It is
safer to choose to use capitals only.
34
35
•
3 Set the TONE control on the cassette recorder to HIGH.
4 Set the volume control on the cassette recorder to 3/4 of
10 Key in SAVE "ADDER".
•
11 Press ENTER. The Spectrum will print a message on the
MAXIMUM. screen which tells you to `Start tape', i.e. press RECORD
5 Insert a new C12 computer cassette tape into the (or record and play, depending on your cassette
recorder. Short cassettes are more convenient than long recorder), and `then press any key'. Do so.
ones for our purposes. 12 Blue and red lines (black and grey on a black and white
6 Run the tape through on FAST FORWARD and then TV) will scroll up the border area of your TV screen. This
REWIND to ensure equal tension. happens twice as the name of the program is recorded.
7 Set the tape counter to zero and run the tape forward five When the program is copied, narrow yellow and
revolutions (about 20 or 30 seconds). blue/black lines roll up the border area. When the
8 List the program on the screen and printer. recording is complete an `0 OK' report appears on the
9 Check the program is named (e.g. "ADDER") in a REM screen. Stop the recorder. Note the tape counter reading.
statement.
Your program should now be correctly recorded.
13 On the Spectrum, you can check this without wiping out
ZX81 Sequence
the program in memory first. Connect the EAR lead from
the Spectrum to the cassette player EAR socket. Rewind
10 Type SAVE "ADDER" don't press NEWLINE
the cassette to before the start of your recorded program.
(ENTER) yet.
Get into the E mode, and key in VERIFY, then enter the
11 Press RECORD and PLAY
buttons on the recorder. program name between quotes. Press ENTER and start
12 Press INEWLINE (ENTER)1
the cassette on PLAY. The Spectrum displays on the
13 Watch the screen.
screen any other programs before the specified one that it
a) For five seconds it will be grey inversed by diagonal finds on the tape, printing their names on the screen.
white lines and if the sound on the TV is turned up 14 When the program has finished playing back, an `0 OK'
it will be a monotone.
message means the program was correctly SAVEd, and
This is the SILENT LEAD IN
`R Tape loading error' means the recording is faulty and
b) For ten seconds a horizontal striped pattern appears you should SAVE the program again.
on the screen. This is the program going in. A 15 Run the cassette on five more revolutions of the tape
warbling sound is first heard, then half second counter, ready for the next program.
pulses.
c) The screen goes white and the message 0/0 appears, The sequence above assumes a tape counter on your cassette recorder.
telling us the computer has transmitted the program Without a counter, the process of finding a program is more difficult.
to the cassette recorder. To place a voice message on the tape, so that the tape is searched for
The ZX81 does not know whether the recording is the voice giving the program name, will prevent the tape being
successful.
searched automatically by the computer, but it is one possible method.
We can only tell by later loading the program back If used, you should record your voice (most cassette machines have a
in.
built-in microphone) stating the program name several times, then the
Stop the recorder
program name should be spelt out, the name stated again, and some
14 Note the counter reading at the end of the program. cue statement (`saving starts now') to let you know that after that point
15 Run the tape forward five more revolutions of the only computer-generated noises exist. This will make finding the
counter, ready for the next program.
program much easier, as the voice cues occupy a larger length of tape
than a single statement of program name.
Spectrum Sequence The other alternatives are to place only one program on each tape (a
bit uneconomical!) or to leave very large gaps between tapes (30
IMPORTANT NOTE: YOU MUST ALWAYS seconds at least), so that you can search using fast forward/reverse and
TAKE THE
JACK-PLUG OUT OF THE EAR SOCKET OF THE are unlikely to miss the gap. This has the advantage that you can set
SPECTRUM BEFORE the computer to search through the tape program by program if you do
ATTEMPTING TO SAVE A
PROGRAM. miss it. Larger programs should be placed if possible on a side of a
36
37
•
cassette by themselves. Short length cassettes are available (5 minutes a
side) to make this a viable option.
•
CLEAR is similarly useless in the middle of a program – we would
merely have to re-define all variables.
Exercises With our program, if we RUN it, at the end of the run it will have in
the variables store the values of A, B and S. If we then SAVE it, these
1 Try a dummy run first. Do not press the recorder keys. Turn up values are SAVEd also. In our case this is irrelevant, since the INPUTs
the sound on the TV until you can hear a hum. Awful, isn't it! will change them when it is used but often it is useful. We can store
Key in SAVE "ADDER" and press NEWLINE (ENTER). data as variables in a program, and not have to re-input values (as long
(Press a key in response to the message if using a Spectrum). as certain procedures are followed, as we will see later). This enables us
Watch the screen and listen to the different sounds. When the to have, for example, a telephone directory stored in variables. We
screen clears and the 0/0 message appears (0 OK, 0:1 on a might then use CLEAR to wipe one list, and re-input new data or use
Spectrum), key in LIST NEWLINE (ENTER) to get the listing CLEAR before SAVEing the program to send to a friend for his use.
back. CLEAR acts slightly differently on the Spectrum (see page 458), but
2 Now SAVE the program on to the tape. for our purposes at this point the difference is insignificant. The major
function is the same. It is very easy to key CLEAR by accident on the
Spectrum, so be careful!
D2: Deleting the Program from Memory
Exercises
A sure way is to switch off the power – this is not recommended. This
should only be done if the computer needs to be re-set because it will not 1 RUN "ADDER". Enter CLS NEWLINE (ENTER) to clear
respond to commands keyed in. It is much better to use the command the screen. Enter GOTO 40, then press NEWLINE (ENTER).
NEW. The computer will print the value of S. Now enter CLEAR
1N E W L I N E (ENTER) and then GOTO 40 (NEWLINE/
ENTER) again. We then get an error message 2/40 (2 variable
NEW not found, 40:1 on the Spectrum) indicating an undefined
variable, because the computer has wiped the value of S. We will
The NEW command deletes any current program and deal with GOTO in due course. Just follow the instructions for
variables from the computer and clears the screen. now.
2 LIST the program "ADDER" on the screen. Press NEW and
NEWLINE (ENTER)! . The listing will disappear and the 1K
We use the NEW command before we LOAD a program into the cursor appears. On the Spectrum, when NEW is followed by
computer from cassette tape, to erase old programs and data from ENTER, the screen will go black for a moment then become
memory. It is also used to do the same thing, if we have a program in white, with the words `© 1982 Sinclair Research Ltd' at the
the computer and wish to clear it out to enter another. bottom of the screen.
There is another command that only affects the variables store, and 3 Press I LIST and then ! NEWLINE (ENTER) . What happens?
not both this store and the program store, as NEW does. Why?
4 Key in the first line of the program and press NEWLINE
(ENTER). Switch off the power supply (by pulling out the jack-
CLEAR plug). Switch it on again (by re-inserting the jack-plug). What
happens?
The CLEAR command erases all the variables in the current 5 Re-enter "ADDER" .
memory.
D-3
38
39
D3: Loading the Program from Cassette Tape
• •
10 LIST and RUN the program.
11 Remove the tape when finished.
LOAD "NAME"
LOADING PROCEDURE ON THE SPECTRUM
The command LOAD "NAME" waits for the cassette to play
the portion of tape with the program called "NAME" and 1 Place the tape with the desired program in the cassette
copies the program, with its variables into the computer's player.
memory. 2 Position the tape via the counter to just before the
location of the required program.
3 Clear the computer's memory using the NEW command
This means that we can start the tape, give the command LOAD if there's a program in memory.
"NAME", and the computer loads nothing into its memory until the 4 Set the TONE control on the tape recorder to nearly
signal it recognises as NAME appears on tape. We can thus search a MAX (High), and the VOLUME control to 3/4 MAX.
tape for a program. The Spectrum will print on the screen the names of 5 Key in LOAD "ADDER", but don't press ENTER yet.
any programs it finds on tape, before it encounters the specified 6 Press the PLAY button on your cassette recorder.
program. 7 Press ENTER.
8 When the Spectrum has found a program it will scroll
blue and red bands of colour up the border area. The
LOAD " " name of the program will be printed to the screen and
then the blue and red lines repeated again. If the correct
The LOAD " " (nothing between the quotes) command program has been located, then it will LOAD with a finer
LOADs the first program it finds on the tape. set of blue and yellow lines scrolling up the border area.
If not, the border area will flash blue and red alternately
LOADING PROCEDURE ON THE ZX81 as it carries on to the next program on the tape.
9 When the program is correctly loaded, the phrase:
1 Place the tape with the desired program in the cassette 0 OK, 0:1
player. will appear at the bottom of the screen to indicate that all
2 Position the tape via the counter to just before the is well.
location of the required program. 10 Stop the recorder.
3 Clear the computer's memory using the NEW 11 LIST and RUN the program.
command if there's a program in memory. 12 Remove the tape when finished.
4 Set the TONE control on the tape recorder to nearly
Maximum (High), and the VOLUME control to 3/4
Maximum. CAUSES OF FAILURE TO LOAD
5 Key in LOAD "ADDER" or the appropriate name.
Don't press NEWLINE (ENTER). 1 Volume too low.
6 Depress the PLAY key on the cassette recorder. 2 Volume too high.
7 Press NEWLINE (ENTER). 3 Tone too low.
8 A thin diagonal pattern will appear on the screen with a These indicate that the program has been played at the wrong
single tone sound. settings. New volume and tone adjustments will have to be
The pattern changes to broad horizontal stripes with made. Some indications of these problems are visible on the
thinner diagonal stripes and half second sound pulses arc screen display of the ZX81, although systems vary in their
heard as the program is loaded in. response. Appendix IV has a procedure for adjusting tone and
The screen clears and a 0/0 message indicates the volume settings for the ZX81, as well as some general hints on
loading is a success. tape use. Experiment and get to know the patterns produced
9 STOP the recorder. during LOAD on your ZX81.
40 41
•
4 Loading started in the middle of the program. If a mistake has
•
patterns change when you change the settings while the program
been made with the start position, rewind the tape completely is loading. Read Appendix IV.
and let the computer search for the program name.
5 The program is not on the tape. Check your directory, and the
D4: Listing the Program on the Printer
writing on the cassette.
6 The program name is incorrect. Try again, making sure you
have spelt it correctly in the LOAD instruction. If you fail again,
LLIST
run through the tape using the LOAD " " command. This will
load the first program each time. Stop the cassette player after
LLIST lists the program currently in the computer memory
each load and LIST the program to check. (This is not necessary
on the printer, starting from the first program line.
on the Spectrum.) If it's not the program you want, repeat for
the next program on the tape. The Spectrum will print the name
of all programs on tape if you use a LOAD "ZZZ" instruction, LLIST N
i.e. a name that does not exist as a program name.
7 Pick up from stray electromagnetic fields. LLIST N lists the program on the printer starting from line
This will show as violent interference on the screen, distorting
N.
the patterns together with excessive hum on the sound. It could
originate from the TV itself, feedback between the recorder and
the computer or an external field. Switch off any radio that is in We can stop the listing by pressing BREAK (BREAK needs CAPS
the vicinity. Take out the jack-plug from the MIC socket of the SHIFT on the Spectrum). This stops the listing with an error message
cassette player, as this will break the feedback loop that can exist D/line number on the ZX81 and D BREAK – CONT repeats 0:1 on
between the computer and the cassette player. the Spectrum.
It is important that you keep a listing or printed record of all the
The Spectrum has fewer LOADing problems than the ZX81. It will programs you write or use. The listings are a great help in debugging
accept a much greater variation in both the volume and tone of the programs (both under development and if there are problems
signal. However, it is worth noting that if there are great differences discovered later). We can key the program back in from this listing, if
between the recorder the tape was recorded on and the one it is played
necessary.
back on (variations in tape-head azimuth is often the main source of the Printouts also form part of the documentation for a program and
problem), then LOADing can be almost impossible, even on the should be pasted into a notebook. Printed records of program results
Spectrum. can also be kept using the COPY command.
As we noted at the beginning of the book, the Spectrum, unlike the
ZX81, offers a choice of upper and lower case letters. Ensure that if
you have used lower case ones in the program's name, then you use
them again in the LOAD "xxx" command. The same applies if you Exercises
use upper case letters to name a program. Thus, a program named
"MATHS" will not LOAD with the statement: LOAD "maths". 1 LLIST the program "ADDER" on the printer.
Some further information concerning the use of cassette tapes, and 2 Try stopping the listing with the BREAK key. The listing cannot
be continued by pressing CONT (try it). On the Spectrum,
advice for the ZX81 if problems are encountered is given in Appendix
IV. despite what it says, this doesn't work. The screen just goes
blank. Don't worry. Press BREAK again.
Exercises 3 List the program on the screen. Use the COPY command to list
the program on the printer.
1 Load the program "ADDER". LIST and RUN it.
What is the difference between the two listings obtained with
2 Delete it from memory, using NEW. LLIST and COPY?
Try loading it with different volume and tone setting.
Estimate the volume and tone ranges for which it will not load. If
you have a ZX81, you can do this by watching how the screen
42 43
D5: Program Libraries and Directories
• •
We will introduce flowcharts in Section G.
DIRECTORY LAYOUT
LIBRARY
A typical layout for the Directory Section of your notebook
A collection of programs stored on cassette tape. For example: would be:
COMPUTERLAB PROGRAM LIBRARY Program Name: MOONLANDER
or Your own program library. Cassette Name: GAMES 3
Location: 100-120
Program Length: 30 lines
Notice that programs can also be stored on magnetic discs and in Date Created: 18.5.82
ROM memories. Author: PAUL NIXON
Function: Lands a spaceship on
the moon
DIRECTORY
DOCUMENTATION
PRINT When we insert line 50 into our program we can see that, after printing
the result on the screen, line 50 sends the computer back to line 7 to
In our simple program we will use the PRINT statement: execute the program again from that line, and as soon as the computer
a) To print messages and instructions to the user on the reaches line 50 again it is sent back to line 7 once more.
screen: We have constructed a LOOP. The program is going to carry on
7 PRINT "INPUT TWO NUMBERS" looping forever unless we can pull out of it.
The message INPUT TWO NUMBERS is a string, and
will be printed without the quotes.
46 47
Our program now is:
5 REM "ADDER"
•
Key in CONT NEWLINE(ENTER) to continue the program. Note
the Spectrum prints CONT in full as CONTINUE.
6 REM **THIS PROGRAM ADDS TWO NUMBERS
KEYED IN AND PRINTS THE RESULT**
Exercise
7 PRINT "INPUT TWO NUMBERS"
8 PRINT
10 INPUT A Run the program "ADDER".
20 INPUT B STOP the program when the first LIcursor appears.
30 LET S=A+B CONTinue the program, and input a value for A.
40 PRINT A;" + ";B;" = ';S STOP the program when the second I L I cursor appears. Note that
50 GOTO 7 the line number is different in the message that appears on the bottom
60 REM **END OF PROGRAM** of the screen.
Key in line 50. RUN the program. When you are tired of inputting CONTinue the program.
numbers, read on.
E5: Testing for a Condition
On the ZX81 the STOP command stops a program with the Conditions are tested and the next action determined by the result of
message: D/line number, and on the Spectrum we get H the test with the IF and THEN statements used together.
STOP in INPUT (Line number):1.
The line number refers to the program line the computer
was executing when it was stopped. IF — THEN
Our program will give D/10 as the message (H STOP in INPUT 10:1 An IF — THEN statement has the form:
IF (condition) THEN (instruction)
on the Spectrum). We can cancel the STOP command and continue
the program with the CONT command. For example: IF A = B THEN PRINT "EQUAL"
IFA=0 THEN LET A=3
The instruction can be any valid instruction. The statement
CONT means:
IF (the condition is TRUE) THEN (perform as instruction).
The CONT command used after the STOP command will IF (the condition is FALSE) the computer ignores the
continue the program from the line the program was stopped instruction after THEN and goes to the next line of the
at. program.
48 49
•
In our simple program we can use the IF – THEN statement to insert
•
When the program gets to line 50 it will print out the message, and
in the program a conditional test which will stop the loop, without then put the IL I cursor at the bottom of the screen. Because it has been
using the direct commands which we used in the last Unit. To STOP told
that a string input is to come, the cursor has quotes either side:
the program in the same way as with a direct command we can insert " I I". There is no need to type quotes. Whatever characters are
L
another line: typed in will be stored as A$. The string is entered by pressing
15 IF A = 0 THEN STOP NEWLINE (ENTER) after keying in the characters. Line 56 tells the
This tells the computer that IF A = 0 (if it is TRUE that A is equal to 0) computer to check if the characters in A$ are the same as the characters
THEN it should STOP. IF A is any other value (if it is FALSE that of the string "YES". If they are it goes to line 7. If they are not the
A = 0) it ignores the THEN STOP instruction and moves to line 20. program will continue to line 60. Notice that any string other than
Enter this line into the program. RUN the program. "YES" will cause the program to continue to line 60.
Enter different non-zero values for A to see that if A is not zero then
the program continues as before. Enter .000000001 to see that only if Exercises
A is exactly zero will the STOP instruction be executed. Input 2 for B,
and notice that the result is given as 2. This is due to the fact that 1 Delete line 15 in our program, which we no longer need.
calculations are only performed to a certain degree of accuracy. 2 Insert the new lines 50, 55 and 56.
Enter .0000001 for A, and input B as 2. The computer returns 3 RUN the program. Enter "YES" in response to the string input
2.0000001 as the value of S – the number is within the limits of cursor and see that the program loops back to line 7.
accuracy. 4 Next enter "NO" to see that the program goes to line 60 and
Now enter 0 for A. The program will stop, just as when we entered gives the message 0/60 (0 OK, 60:1 on the Spectrum). Run the
STOP as a direct command. Notice, however, that the message at the program again. This time enter anything other than "YES" or
bottom of the screen is different. We get the message 9/15 on the ZX81 "NO", to see that the program goes by default to line 60 if
(a STOP statement, 15:2 on the Spectrum).' The message is different anything other than "YES" is entered.
because STOP in a program means `if the CONT command is 5 Experiment with the string input. What happens if you press
received, proceed with the next program line', since if it continued with NEWLINE (ENTER) without inputting anything? What
the same line it would just STOP again! As a direct command, happens if you try to key in quotes around the string?
however, STOP means `if the CONT command is received, start with 6 LLIST the program on the printer. The development of our
the same program line', so that the computer does not miss out a program is complete, and we have run it to see that it works. It
program line. remains to renumber the-lines, and this is easier to do if we have
Now we have some extra control over the program, but it is still not a listing.
satisfactory. We used IF A = 0 because in this program it is not a value
we are interested in seeing added to B (a value used in this way is
known as a DUMMY or SENTINEL VALUE – a value just used as a E6: Final Edit and Saving
signal to the computer which would not need to be entered in the
course of normal inputs). This stops the program and we can continue Our program "ADDER" is complete and works. We need, however,
it, but the program just goes back into the loop. We need a method of to renumber the lines. The procedure for this is as follows:
proceeding out of the loop to end the program, or continuing with more 1) Using the listing from the printer, renumber the statement lines
program lines. in tens at the side of the old number. You can also count the
We can do this with a STRING CONDITION. The conditional number of lines in the program on the screen display, and
operators can also be used to express relations between strings – either multiply by ten to get the new highest line number. For our
string variables or simple strings. program, this will be 120.
We insert the following lines: a) List the program on the screen.
2)
50 PRINT "RUN PROGRAM AGAIN ?(YES/NO)" Use the ' and 4, cursor control keys to bring the current
55 INPUT A$ b)
line cursor l> Ito line 60 (the bottom line of the program).
56 IF A$ = "YES" THEN GOTO 7 c) Press EDIT and pull line 60 down to the bottom of the
'On the Spectrum, the statement after the THEN in an IF — THEN statement is screen.
treated as the second statement in the program line. This is why we get 15:2, meaning d) The new HIGHEST line number is 120.
line 15, statement 2. This is the only instruction used in the main text of this hook
(before Unit W2) where the statement number will not be 1 in an error message. e) Change 60 to 120.
50 51
f)
•
Press NEWLINE (ENTER). Line 60 remains, but it is
•
SECTION F: A GAME INTERLUDE
duplicated by the new line 120
g) Delete the old line 60 by entering 60 and pressing
NEWLINE (ENTER).
h) Change each line number in this way, going from highest to F1: The Program Library
lowest.
In addition to the many programs and subroutines in the main body of
i) Lines that contain other line numbers must have these
the text, there arc additional applications and games programs in the
changed to their new numbers. In our program we must
remember to change line 56 to: Program Library (Appendix VI). Our main objective is to enable you
90 IF A$ = "YES" THEN GOTO 30 to write your own programs, and the programs in the text have been
where 30 is the new line number corresponding to the old used to illustrate the use of techniques. Some are functional (do
line 7. something significant) and some are just illustrative. You don't have to
j) Rename the program "ADDER2", at the same time as you key all the programs in the text into the computer, but you must
change the line number of line 5 to 10. This program is understand them. However, you should key in all the shorter programs
different from the original version, and must be given a since it's important to see how different types of program operate in
different name both for our reference, and the SAVE and practice. Analysing the longer programs is vital, even if you don't key
LOAD operations. them in. The use of flowcharts (to come in Lesson G) is helpful for this.
k) Run the program to check that it still works, and that we There are also suggestions for programs you should write, to get
have all the lines, with any GOTO (line number) practice in writing programs to perform tasks, after units dealing with
statements correctly renumbered. specific techniques.
1) LIST and LLIST the program. The programs in the library are examples of applications and games
m) SAVE "ADDER2". programs, plus a number of subroutines for some of the manipulations
n) Write the name of the program on the tape cassette, along commonly required in programs. You can key these in at any time if
with the tape counter readings. you want to see how the program works, find the program useful, or
o) Put details of the program in your directory. want to play the game. Once keyed in you can SAVE them on cassette
p) Stick the listing of the program in the notebook you are and LOAD them back in quickly. None of the programs are very long,
using for documentation. since it is difficult to analyse long programs, and this is what we want
you to do. Keying in a program from a listing doesn't teach you
anything about programming, nor does running it. Writing or
modifying a program does! We hope you find the programs
entertaining or useful, but please treat them as a source of ideas and
illustrations about programming, not as a fixed set of optimum
solutions. Programs can always be improved!
Be careful when keying in programs, especially if you don't
understand how they work. (It might be better to work this out
first – because, to labour the point, that way you'll learn something.)
The S-cursor will mark some errors in lines for you and stop you
entering them, but there are always other problems you can introduce.
Check through your listing for errors and missing lines (surprisingly
easy to do, even with numbered lines) before you run the program.
You must also be careful to check that any necessary alterations have
been made to the program if you are going to run it on a Spectrum, as
noted in Unit W2. These are mostly minor but can be crucial.
You have now spent a lot of time working through the essentials of your
I
computer system and its BASIC, and you probably have the feeling
52
53
•
that thus far you haven't seen anything to persuade you that computers
•
white, back. If you don't return to normal video, the quotes will be in
are particularly exciting machines. Far from being impressed by their inverse, and so will everything after it.
capabilities, you may well be thinking, `What's so good about a Line 190 has the unshifted G mode graphic on the 6 key, and then
computer if you need to do all this to get it to do something that I could the CAPS SHIFT graphics on the 8 key and the 6 key as the graphics
do in my head when I was six?' Well, the following program may not string.
be earth-shattering, but it does in fact reveal a fairly complex set of
computer operations, as well as providing amusement. The program is REM "BUG"
called "BUG" and it enables you to play a game that consists of 10 LET 3=0
20 LET B=10
dropping bricks from a height to squash the 'spider' (an asterisk) 30 FOR N=1 TO 12
scurrying along below. If you have a militaristic or SF streak in your 40 LET C=:3
50 PRINT AT 20,C-2;" *" [2 '_;pace,*]
nature, or are an arachnid lover, feel free to change the name to C" SP, .=.',.- SP]
60 PRINT AT 0,B-3;" _ "
"BOMBER" or whatever (in line 5). Whether you will enjoy it more 70 IF INK:EY$ ="6" THEN OC'TO
by pretending you're napalming Venusians is your affair. It won't 150
alter how the program works! 80 LET B=B+(3 AND INKEY$ _
AND B-'(28)-(3 AND INK:EY$ =
To play the game, however, you first have to key it in. You won't AND B>3)
understand at this point how it works (and won't for a few chapters 90 LET C=C+ INT ( RND *24.1)
yet), so you have to rely on keying it in exactly as listed. Like all the 100 IF C:30 THEN LOTO 50
110 CLS
programs in the text, this one will look somewhat different on the 120 NEXT N
screen or in a printer listing, since for clarity we have not reproduced 130 PRINT "YOU SCORED ",_; [SCORED, & 3P,iiIIT]
the printer listings exactly, since printouts tend to contain broken " OUT OF 12"
140 STOP
words (when one line on the screen is full and the computer runs on to
the next) and other possible confusions. Check each line carefully 150 FOR F=4 Ti O 20 STEP 4
before you press NEWLINE (ENTER), and pay special attention to 160 PRINT AT F,B+1;"0"; AT [Inverse *]
F,B+1; ,
the punctuation. Notice that there are 2 spaces before the asterisk 170 NEXT F
(spider) in line 50, and 3 spaces either side of the < _ > (brick 180 IF B+1 ;> C THEN GiiTO 50 C 0 is one charaoter]
dropper/intergalactic space hod) in line 60. If you have any difficulty 190 PRINT AT 20,C-1;"0:19"; AT
21,1:-2; "5PLAT"
finding the right modes and keys for the characters you need, refer to 200 CLE.
the list in Section B (ZX81) and Unit W1 (Spectrum). It is very easy to 210 LET +1
end up typing a keyword instead of inputting it directly when you are 220 GOTO 120
keying in a listing (typing T,O instead of inputting TO, for example).
If you do this it is not clear why you get the I S cursor indicating an
error, since the line looks the same as the listing, so be warned.
When you've got it all keyed in, LIST it to check it through again.
ZX81 Users' Notes Check the first screenful, then (on a ZX81) LIST 170 to get the rest of
the program (with a line that was on the first screenful to keep your
The graphic character in line 160 is an inverse asterisk, (SHIFT B in place). LLIST it on the printer.
Graphics mode) and in line 190 the characters are the SHIFTed Key RUN then NEWLINE (ENTER) to play. The keys 5 and 8
graphic on the T key, the asterisk again, and the SHIFTed graphic on move you left and right respectively across the top of the screen. They
the Y key. The comments in square brackets are intended to be helpful, are chosen for the direction of the arrows printed on them. Key 6 will
not to be entered! drop the brick. If you hit the spider it goes splat and you score a point.
You have to hold the keys down to ensure that the computer will read
Spectrum Users' Notes the keys and perform the right operations. This is because it reads the
keys only once in each pass through the loop (lines 50 to 100), and
Line 60 has an inverse video asterisk. To get this, key CAPS SHIFT might miss the input otherwise.
and the 4 key to get INV. VIDEO. Then input the asterisk. Use CAPS When you've played the game a few times, SAVE it on to tape and
SHIFT and the 3 key to get TRUE VIDEO, i.e. normal black on catalogue it.
54 55
• •
PART TWO
ESSENTIALS OF
BASIC PROGRAMMING
SECTION G: PROGRAMMING METHODS I
G1: Programming
Now that you can operate your computer and have written a short
program we must look in greater detail at the activity we call
PROGRAMMING and study how:
The material in this Section may initially appear dense and difficult
EXAMPLES
to follow. Work through the text carefully, and refer back to this
Problem: Write a program which will print out the sum and
Section as often as you feel necessary, when each of the topics covered
average of five numbers input at the keyboard.
in the following Sections (dealing with the essential groundwork of the
Problem: Using the computer produce a telephone directory to
BASIC language) has been introduced. The exercises given in the text
contain up to fifty entries, which may be updated and
should be used to put into practice both the specific techniques involved
and the general approach to programming presented here. assessed in an enquiry mode.
In the first problem the input data, output data and operations are easy
G2: Problem Analysis to see. The second is much more complex and needs more researching
and information.
Producing the algorithm, or method of solving the problem, is often the What we are trying to do in 1.1.1 and 1.1 .2 is to initially specify the
most difficult part of programming because it involves the most work. problem as exactly as possible. When we analyse the problem further
From the start careful planning and organisation are absolutely we may have to go back and ask for more information i.e. a more
essential. The task is simplified when a structured design method is detailed specification.
used, coupled with a diagrammatic representation of the algorithm
60 61
1.2 Research the problem
• •
down, modular fashion, with step by step refinement of the solution
starting from the single statement of the problem which we place at the
1.2.1 RESEARCH AND ANALYSE THE PROBLEM TO highest level. We break the problem into sub-problems at successive
SEE HOW THE COMPUTER CAN HANDLE IT lower levels. Each sub-problem or module is one that can be solved
1.2.2 IDENTIFY ALL FORMULAE AND RELATIONS individually. Structure diagrams or tree diagrams are useful as a
INVOLVED representation of this refinement process.
1.2.3 IDENTIFY ALL DATA INVOLVED
G3: Structure diagrams
Here we start to determine how the computer may solve the problem.
We need to find out and write down: These enable us to break down the problem into distinct tasks and sub-
tasks which eventually become simple enough to be coded directly in
What formulae and expressions are to be used. BASIC instructions. One form of these diagrams is TREE
What kinds of data are involved – numeric, string, etc. DIAGRAMS. The tree diagram has its trunk at the top of the page.
What functions are involved. We call this BOX 1 and give it the title: TASK TO BE DONE. We
What is input and output data. could have called it `problem to be solved'.
What is the form of this data. For example, make a cup of tea or find the average of five numbers.
How much data there is. We next break down the task into things to do. These are sub-tasks
What processing is to be done and how many times. and each has its own box. For example:
It is useful at this stage to start to create a data table (a table of variables,
constants and counters), to record how we are going to store the data. BOX 1.1: First thing to do
Other questions we will ask when we are a little more experienced are: BOX 1.2: Second thing to do
Have I solved a problem like this before?
Can I use my solution or modify it? Each sub-task is broken down into further sub-tasks: 1.1.1, 1.1.2 etc,
Has anyone else solved it? each with their own boxes, the things to do placed in them becoming
Where can I find their algorithm or program? progressively more exact and simple.
Breaking down a task into a tree diagram:
ALL THE FACTS OBTAINED FROM RESEARCHING
THE PROBLEM SHOULD BE JOTTED DOWN 1
first "WHAT IS TO
We can now begin to design the algorithm in a structured manner. level BE DONE"
62 63
each other for example:
•
contain the tasks to be done in a straight line across the page next to
i
Each of these sub-tasks is still far too complicated for our robot to do.
We must break the problem down further. Breaking down 1.1 into sub-
tasks we get:
1.2.1 1.2.2 1.2.3
1.1
Boil
Water
The numbers contained within each box identify where the box is
placed on the tree. Take 11.2.31 for example:
The first digit shows it comes from the first level 1 `What is to be
done'. 1.1.1 1.1.2 1.1.3
The second digit `2' shows it has come from the second level box 1.2 Fill the Kettle Plug in Kettle Wait Until
`Second thing to be done'. with Water and Turn On Water Boiling
The third digit '3' shows this box 11.2.3 1 is the third sub-task in the
sequence derived from 11.2 which in turn is derived from 1 1 1 . Into
The robot also needs to be told how to fill the kettle so we break this
the boxes go brief statements of the actions needing to be performed. down as:
These are general statements at the top of the tree, e.g. `Get Sum of
numbers', but become more specific at each lower level, so that `Get
Sum' is broken down in the operations needed to produce the result 1.1.1
Fill the Kettle
`Get Sum', e.g. `Input first number', `Input second number', `Add with Water
the two numbers'. Finally the instructions become detailed enough to
form our English language `pseudocode' which can be written out,
ready to be translated into BASIC instructions.
1.1.1.1 1.1.1 2 1.1.1.3
AN EXAMPLE OF TREE DIAGRAM DESIGN Put the Kettle Turn on Wait Until
Under Tap Tap Full
Here is an example to try out. Suppose we have a robot with arms, legs
and eyes which we want to program to make a pot of tea. Our major
task for the robot is: On the next page is a complete tree diagram. Certain things are still
wrong with this algorithm for our robot, but it does show you how a
1 problem can he broken down.
Make a Pot
of Tea
G4: Classifying Program Modules
This can be broken down into sub-tasks which we put in order across Most computer programs involve:
the page:
INPUT
1 PROCESSING
Make a Pot and OUTPUT
of Tea
activities.
64 65
designated input, processing, and output functions or may have these
M functions nested as sub-modules.
• tM.^ O
M •.1 ro yJ o
• -1 a
^ cnE. 3(!] Module 1 Module 2 Module 3
DATA PROCESSING DATA
INPUT Module OUTPUT
Module Module
aJ (V f-i
o • L.(v O
M C 14 JJ JJ
• o ro C O OR
a) a)
JJ .0
ro^
O 4-)
M }J JJ O aJ a)
• 7 C , P-1
-1 a •-1 a 4J
M X a) 4-)
• it _C 0 v
E-+ 4 J -J
C
N •r1 ro
• v N G5: Control Structures
N aJE. 01
• C ro
rl CL (V p^
Control structures are the statements or groups of statements
(modules) in a program and algorithm by which the order of processing
is controlled. Using them properly is the most important part of
programming.
BASIC is a line numbered language. The order of processing in a
program is from the lowest line number in the program sequentially
through to the highest, unless this is changed by using a control
structure. Control structures link the different modules in a program
together and are themselves modules. They will be dealt with in depth
in the remainder of this section.
To make our algorithm language-independent we can write them
using a standard notation in pseudocode for the particular control
v v
r•-) structure together with its flowchart description. When we code the
• 014-) C
sa ^b structures into the BASIC language the instructions used and the order
•,-, C Q) C 7 C
^a • -+x roE-■ o of statements in the structure may be slightly different according to the
S.4
Pr 67
DECISION STRUCTURES
• •
There are three common loop structures:
Computers make decisions by comparing the value of one variable (i) Repeat (the process) forever!
against another. For example: (ii) Repeat (the process) until (a condition is met).
(iii) While (a condition holds) repeat (the process).
IF A = 0 THEN (do something) Structure (i) is of little use, except that we have to note it and make sure
IF AS _ "YES" THEN (do something) it does not occur.
In structure (ii) the condition is tested after processing.
To make decisions they use relational (or conditional) and logical In structure (iii) the condition is tested before processing.
operators, like the equals operator above. Sinclair BASIC uses a convenient and powerful set of statements for
Sinclair BASIC uses three decision structures: controlling repetition by counting called:
Simple decision
Double decision FOR — NEXT Statements
Multiple decision
SUBROUTINES
As a result of these decisions control may be transferred to another
program module, or local processing within the structure may take Structured programming involves breaking down a complicated
place. problem into subproblems which can be worked on separately.
SUBROUTINES are such separate independent program modules.
TRANSFER STRUCTURES They are distinct from SUBPROGRAMS which have similar
properties in that they are routines or groups of program statements
These structures involve: that are repeated more then once during a program run.
Subroutine modules have a unique address and can have a name
(i) UNCONDITIONAL TRANSFER (like a person who lives in a house). Transfer of control to the
subroutine from the MAIN PROGRAM, when the program runs is by
which is a direct transfer of control using a GOTO (line number) reference to the subroutine address through a special SUBROUTINE
statement. Transfer is to another program statement or a module CALL INSTRUCTION. This is the GOSUB (address of subroutine)
consisting of a group of statements. GOTO is a very powerful structure statement.
and must be used with care. A return of control to the main program to carry on processing from
where it left off is through a special instruction: RETURN.
(ii) CONDITIONAL TRANSFER Subroutine structures in Sinclair BASIC are explained in Section N.
in which transfer of control to another segment is made as the result of NESTED STRUCTURES
a decision: i.e. IF (condition is true) THEN GOTO (line number).
These program structures are discussed further in Section H. These are program modules or structures that lie entirely embedded
within each other (like a set of Russian dolls).
LOOPS A simple nested structure is
MODULE 1
The need for the repetition of simple tasks is one of the fundamental
MODULE 2
reasons computers exist. Loop structures are incorporated in most
MODULE 3
computer programs. A loop is a sequence of repeated steps in a
program. This repetition must be controlled. We shall see in Section L
that repetition is controlled by:
(i) COUNTING
(ii) TESTING FOR A CONDITION
69
68
In terms of program statements this would look like:
• •
The variable type will be either:
The flow of control is: Intermediate data is used in the body of the program, e.g. the value of
a loop counter, or the intermediate result of a calculation. Intermediate
START MODULE 1 data is useful for testing and debugging purposes when running the
program or algorithm, using machine or hand traces.
TRANSFER CONTROL START MODULE 2 The equations, functions and expressions that will use the variables
TO MODULE 2
will need to be known. When dealing with equations, functions and
TRANSFER CONTROL START MODULE 3 expressions the units of the variables or parameters concerned must be
TO MODULE 3
known and should be stated.
The first and simplest data table to construct is a descriptive list of
COMPLETE MODULE 3
TRANSFER CONTROL
variables to be used in the program. This is important for
BACK TO MODULE 2 documentation purposes. For example:
COMPLETE MODULE 2
TRANSFER CONTROL BACK VARIABLE DESCRIPTION TYPE
TO MODULE 1
70
71
VARIABLES
• •
period of time and cannot remember how you designed it! The
ALGORITHM program listing alone is often not enough, if the algorithm is complex,
STEP to show how the program works.
NUMBER B[ S COUNT I A$ etc 1 etc
A l I I
7`I
Remark* End of task 1.2*
Remark * Module – Put water in the pot – task 1.3 *
• •
diagrams. Their power comes from using them to help make visible
and describe the flow of control in the algorithm and the resulting
1.3.1 Take pot to kettle program. They are used to help code the program into BASIC
1.3.3 Stir tea with spoon instructions, and later form an important part of the
1.3.4 Put lid on tea pot DOCUMENTATION of a program. Note that flowcharts express the
Remark * End of task 1.3 * important control structures used in programming in diagram form.
Remark * * End of Algorithm – tea is made * * We give a selection of standard flowchart symbols here. There are
additional ones, but their usage varies. The conventions of use should
You can see that the tree diagram shows why each part of your be followed if you wish other people to understand your flowcharts. For
algorithm is included and why it is in the particular position in which your own use, in analysing programs, you may be less exact, but not
you have placed it on the tree. less systematic. Flow in a program can be illustrated by a selection of
The tree diagram contains information about three things: blobs and rectangles only, given that the lines of flow are correctly
given, and the right words are written in the blobs! Doing this is all
(1) The problem broken down into different levels of detail starting right for yourself, but not if your flowcharts are to be comprehensible to
from the general concept of what is to be done down to the others.
specific activities and instructions which will enable the problem
to be coded. FLOWCHART SYMBOLS
(2) The order in which instructions must be performed.
(3) The comments which must be included to explain what the Flow lines. These connect the program blocks.
program is doing. The arrows show the direction of flow, and are
very important.
Exercises
1 Our algorithm has the following mistakes in it: This symbol represents any kind of processing
a) Some instructions are wrong. They are spelt incorrectly function, that is general Programming
and the robot will not be able to recognise them. Statements, i.e. "Purchase Tea" or
b) Some instructions are in the wrong order. LET A = B + C.
c) Some instructions are missing in the algorithm.
d) Some instructions are missing on the tree diagram.
Find the mistakes! This represents a decision, with a Conditional
2 Correct the tree diagram and the algorithm. test, e.g. "Is there another shop open" or
3 Expand the tree diagram and the algorithm to a further sub-task IF A = 3 THEN ... It has a Yes/No branch,
level. For example: according to whether the condition is True or
1.1.1 Fill the kettle False, which determines the program flow.
becomes
1.1.1.1 Put kettle under tap
1.1.1.2 Turn on tap
This represents either Output in the program
etc.
to the screen or printer, or Input from the
4 Draw a tree diagram and write the algorithm in pseudocode for
keyboard, e.g. PRINT "HAVE YOU A
a robot to set up and switch on your microcomputer system.
PACKET OF TEA?" or INPUT B.
G9: Flowcharts
74 75
This represents an exit to or entry from another FLOWCHART PROGRAM
part of the flowchart, allowing one part of the 2. Decision and program branch
chart to be connected to another part. Used
^ when another direct line link would be
confusing, or to connect to a separate page. 40 IF Y=0 THEN GOTO 70
50 LET x =100
60 GOTO 80
This represents the Crossing of two Flow 70 LET X=0
Lines. They are not connected. 80 PRINT X
90 STOP
1. Simple sequences
10 LET X = 5 10 INPUT X
20 INPUT Y 20 IF X=0 THEN GOTO 50
30 PRINT X,Y 30 PRINT X
40 GOTO 10
50 REM **END**
76 77
Notice that the above flowcharts represent the programs line by line.
Flowcharts can also be less detailed, and the flowchart symbols used to
•
represent program blocks (sequences of program instructions) or
modules rather than one or two lines. They then describe a less detailed
flow structure. We might have a flow that was represented like this: Input loop in lines
40 to 60
J
(START )
t
PRINT
You will soon start to write short programs, and should draw up
flowcharts with each program line or instruction indicated separately.
Later, for longer programs with large numbers of lines, the flowcharts
must be condensed where the sequence is simple to follow in the program, to
INSTRUCTIONS keep them of manageable size. Any complex manipulations should still
be included in full.
t
INPUT
EXAMPLES
(1) Here is a flowchart for our robot. We are going to ask it to buy a
10 packet of tea.
NUMBERS
ir
FIND SUM,
AVERAGE GO TO
SMOTHEF
STOP
PRINT
RESULT
78 79
• which the robot
In the same way as our `making a pot of tea' problem
has to solve, each of these boxes must be broken down into simpler
(2)
•
Here is a flowchart of a program to input two numbers, output
the sum, and ask you if you want to run the program again.
instructions. On a simple flowchart it may not be possible to see how
the problem has been broken down. What we must do is either draw
the whole flowchart again with more detail or draw new expanded
flowcharts at specific points, e.g. "ENTER SHOP" could be replaced (START)
10 INPUT A
with the following: 20 INPUT B
30 LET S = A + B
40 PRINT S
FIND
/ INPUT /
A
50 PRINT "RUN AGAIN?
(YES/NO)"
60 INPUT A$
70 IF A$ = "YES" THEN
DOOR / INPUT / GOTO 10
80 STOP
f
ADD A+B
OPEN
DOOR
PRINT
S
WALK
IN
PRINT
/ RUN
GAIN ?
INPUT
At
Yes
( STOP )
80
81
AN EXAMPLE OF STRUCTURED DESIGN
•
Problem: Find the average of five numbers:
Find Average
of 5 numbers
Get each
Set counter number, add Find Print
& sum to 0 it to the sum Average Average
Let Sum = 0
Let Counter
=0
z .
Add 1 Input Add End of
to counter number number summing if
to sum counter = 5
z
Input Let If Counter Let Print
Let Average
Counter = X Sum = = 5 then Average
Counter+1 Sum+X end summing =Sum/5
Note that the flowchart and program test whether the counter value is
(2) FLOWCHART less than 5, using the < symbol.
(3) PROGRAM
10 REM "AVERAGE"
SET
20 REM ** PROGRAM FINDS AVERAGE OF FIVE
COUNTER NUMBERS INPUT **
=0 30 REM ** START **
40 LET SUM= 0
SET 50 LET COUNTER = 0
SUM = 0
60 LET COUNTER = COUNTER + 1
70 INPUT X
80 LET SUM = SUM + X
90 IF COUNTER < 5 THEN GOTO 60
82 83
100 LET AVERAGE = SUM/5
• •
and jumping to different parts of the program to happen, repetition of
110 PRINT AVERAGE
parts of the program to take place and how separate modules called
120 REM ** END **
subroutines and sub-programs can be called into action where
The operand `/' means `divided by' and is equivalent to the ` –
necessary – these are the language structures.
symbol. Let's go and meet them!
Exercises
84
85
• •
SECTION H: CONTROL The priority of conditional operators is 5. Priority will be
explained in Section J.
H1: Control in Programs They are executed in order left to right across a statement
unless in brackets.
The statements which make up a BASIC program are numbered.
BASIC is thus called a LINE NUMBERED LANGUAGE. Control in We often need to use the complements or opposites of these operators
all BASIC programs is carried out by reference to these line or in decision making. The complements are:
statement numbers. The ZX81 and Spectrum will normally run a Operator Complement
program from the lowest numbered statement through to that with the equality = inequality <>
highest number unless instructed to do otherwise. This is exactly what greater than > less than or equal to < =
concerns us here, and thus we need to recognise that we can control the greater than or equal to > less than <
order in which program statements are executed by using four The reverse operations are true in each case.
important instructions in Sinclair BASIC:
– GOTO (for direct transfer) H3: IF-THEN
– IF-THEN (for decisions and
branching) IF-THEN
– FOR-NEXT (for loops
(repetitions)) Conditional operators are used with:
– GOSUB-RETURN (for IF-THEN statements
accessing program modules
called subroutines) IF (CONDITION IS TRUE) THEN (PERFORM AN
These instructions are used singly or combined together with other INSTRUCTION).
instructions to form groups of program statements called CONTROL For example: 40 IF (A = B) THEN GOTO 10
STRUCTURES. There are four principal control structures: 50 IF C < = 6 THEN STOP
– DECISION AND BRANCH 60 IF J > K THEN PRINT "J"
– LOOPS The format of the statement is:
– SUBROUTINES IF (CONDITION) THEN (INSTRUCTION)
– NESTED STRUCTURES
In this Section we will discover how to take decisions and branch to
Any BASIC instructions can be used in this kind of statement,
other parts of the program. We will study the remaining structures
although a number are unlikely to be useful (e.g. NEW, CLEAR).
later in Part Three. The most important property of a computer is that
In general if the condition in the program line is TRUE then the
it can be programmed to make decisions, by using the relational or
instruction following the condition is obeyed. If the condition is not
conditional operators of BASIC.
TRUE (FALSE) then control passes to the next line.
This powerful facility enables us to branch and transfer control to
H2: Condition Testing
another line in the program.
CONDITIONAL OPERATORS
Equality:
Inequality: <>
Greater than:
Less than:
>= NO BRANCH (FALSE PATH)
Greater than or equal to: GO TO THE NEXT LINE
Less than or equal to: <_
87
H4: GOTO Instructions
• •
60 PRINT "SINCLAIR";
70 GOTO 40
80 GOTO 60
GOTO
Key it in and sort it out!
The normal control sequence in a program is via numbered This is called `spaghetti programming'. Structured programming
statements – from the lowest to the highest. GOTO (line techniques have been designed to avoid the excessive use of GOTO
number) switches control to the line number specified: statements.
100 GOTO 20
3 10 INPUT A$
200 GOTO (B + C)
20 PRINT A$;
As a command GOTO 30 executes a program from line 30.
Unlike RUN, with this method variables are not cleared 30 GOTO 10
The Spectrum includes a space between GO and TO when printing 4 Key in and run this example:
this instruction.
10 INPUT A
20 IF A = 1 THEN FOR I = 1 TO 10
Exercises
30 PRINT "CENTURY"
Key in and run this program which checks that only positive numbers 40 IF A = 1 THEN NEXT I
are input and gives a bad data error message as well as prompting for 50 STOP
the next input. Notice the use of IF-THEN and GOTO. INPUT both
positive and negative numbers. Line 10 asks you to input a number.
Line 20 examines if it is equal to 1. IF this condition is TRUE then a
10 REM*INPUT CHECK* FOR-NEXT loop is set up to print "CENTURY"ten times. If it is not
20 INPUT A TRUE then control passes to the next line.
30 IF A>0 THEN PRINT A
40 IF A<=0 THEN PRINT "NAD IN Line 30 "CENTURY" is printed once.
PUT" Line 40 the condition is tested again. If TRUE the loop continues
50 PRINT "HAVE YOU ANOTHER NUMB
ER? ANSWER YES OR NO"
and CENTURY is printed again. If not then control passes to line 50.
60 INPUT AS Line 50 stops program execution.
70 IF A$ = "YES"THEN GOTO 20 Can you understand it? If not wait until you have read the section on
80 STOP LOOPS.
90 REM*END INPUT CHECK*
88 89
^ •
module – decision
The flowchart for the Double Decision STRUCTURE is: if condition
then True Task
else False Task
end if
end module
End if and end module are bounds to the structure. In Sinclair BASIC
we code it as:
10 IF (cond) THEN (branch to True task)
20 (False task)
Note that in this case the only literal equivalent of BASIC from the
pseudocode is with the use of IF and THEN.
The branch to the true task is made with a GOTO instruction. For
i example:
10 IF A>0 THEN GOTO 100
20 REM * FALSE TASK *
30 ...
90 GOTO 120
100 REM * TRUE TASK *
110 PRINT A
If we did not branch to the true task starting at 100 and used:
10 IF A>0 THEN PRINT A
20 REM FALSE TASK
in line 10, the true task would be processed and control would then
pass to line 20 – the false task. In other words, both tasks would be
It is called a double decision as there are two alternative modules that processed! Watch out for this.
can be performed. EXAMPLE: Input two names as strings. The program compares
In the flowchart, if the indicated condition is true, then the program
them and prints them out in alphabetical order:
section representing the True task is carried out, otherwise the
program section representing the False task is performed. Only one of
the paths from the condition test is taken, and the program will
continue at the statement represented by the arrow at the bottom of the
flowchart.
Each task can be a single instruction or a statement or a group of
instructions.
The Double Decision Structure is known by the general name of the
"IF-THEN-ELSE Decision Structure". Its general form is:
IF (condition) THEN (true) ELSE (false)
This means: IF the condition tested is True THEN perform the True
task, and IF the condition is not true perform the False task.
Our algorithm description of it would look like:
1. Decision Module.
1.1 Do the test. If result is True then
1.2 Do True task
1.3 Otherwise do False task
We can write this formally in pseudocode as:
90 91
10 REM * ALPHA *
• •
A brief formal pseudocode description is:
20 INPUT A$ mod – Decision
30 INPUT B$ if Condition
40 IF A$<B$ THEN GOTO 80 Then P
FALSE 50 PRINT BS end if
TASK 60 PRINT A$ end mod
70 GOTO 100
TRUE 80 PRINT A$ Our BASIC statement is:
TASK 90 PRINT B$ IF (condition) THEN (TRUE)
100 STOP EXAMPLE: Input numbers and stop if a number greater than 10 is
110 REM * END ALPHA * input:
92
93
•
multiple decision structure. This kind of structure is especially useful in 30 IF
•A$ = "2" THEN i?LITO 8 O
40 IF A$ = "C" THEN i=OTO 100
breaking up larger tasks into smaller ones.
50 STOPF'
Multiple decisions are most conveniently handled by multiple logical
operations. This is covered in Section R. We will consider the 60 PRINT "YOU INPUT A"
70 STOP
conventional way of handling them.
As an example of multiple decisions consider a food vending 8O PRINT "YOU INPUT L."
machine. You put a coin in and press the respective button of the 90 STOP
article you wish to be delivered to you. Another example would be a set 100 PRINT "YOU INPUT C"
of arithmetic testing programs, with questions in each. The computer 110 STOP
would ask you which set of tests you required, you would key in the
reply and, from several alternatives, the required program would run.
The flowchart for such a structure is: The Pseudocode description of this structure is:
mod BASIC
case
if C 1
then P1 10 IF (C1) THEN (P1)
if C2
then P2 20 IF (C2) THEN (P2)
if C3
then P3 30 IF (C3) THEN (P3)
endcase
endmod
When programming in BASIC take great care in how you use the
GOTO statement. It takes two main forms. Used on its own it is called
an unconditional GOTO and when used with IF-THEN it is called a
conditional GOTO.
GOTO enables you to jump around in a program like a flea on a
blanket – don't do it! Try and code your program to execute in
sequence and avoid it becoming a bowl of spaghetti. Excessive use of
GOTO makes programs difficult to refine and debug. Relationships
between the program paths become difficult to follow. However – do
not take the other extreme and write awkward complicated code to try
and avoid GOTOs!
Ideally, unconditional GOTO statements should only be used to
Cl, C2, C3 are the conditions and P1, P2, P3 are the True skip over code and not to repeat code sections (i.e. they should only be
Where
used to transfer control forward in a program).
tasks.
Do not put an unconditional GOTO inside a loop or subroutine to
EXAMPLE: Input any of three letters A, B, C and print out a jump out of it. Do not jump inside a loop or subroutine, because you'll
corresponding reply. find that jumping in and out of loops can cause unpredictable results.
Do not jump to another GOTO. For example:
PRINT "ENTER A,C OF: C" 100 GOTO 200
10 INPUT A$ 200 GOTO 300
20 IF A$="A" THEN 00T0 60
n,1 95
or else:
• •
50 IFX<>2 AND X<>3 THEN PRINT
100 GOTO 100 ! " X NOT EQUAL TO 2 OR 3"
40 IFA =B ORB=C THEN LET F=F+1
Exercises The first example will be true if X is greater than 1 and X is also less
than 10, and the message will be printed. If X was 11, the first
1 Write a program to input integer numbers and stop if zero is condition would be true, but the second false. The whole expression
input. would then be false.
2 Write a program to input integers and count the number of Notice the danger with the second example, in that we say in English
times zero is input. `not equal to 2 or 3', but we must key in an expression using AND. It is
3 Write a program to input integers and calculate the percentage clear once you realise that two conditions are to be tested — `not equal
of zeros input. to 2 and not equal to 3'. If, for example, X were 3 when this line in the
4 Write a program which prints out the result of dividing any two program was reached, then the second condition would be false in this
numbers' input and gives a "bad data — try again" message if expression, and the whole expression would also be false.
any of the input values is zero. The third example would be true if either A was equal to B or if B was
5 Write a program which will print out on request a lunch menu equal to C. It is also true if both these conditions are true.
for the different days of the week. We can also combine more than two conditions:
20 IF A = B AND B = C AND C = 20 THEN STOP
will stop if all three conditions are true. If one or more is false then the
H6: Logical Operators: AND/OR whole expression is false.
Similarly:
We will only introduce you to simple logical operations here. Logic is 20 IF B = 2 OR B = 3 OR B = 4 THEN LET B = 1
dealt with fully in Section R. will make B = 1 if B is equal to 2 or 3 or 4.
Use of the AND and OR statements enables us to combine It is also possible to use combinations of AND and OR:
conditional statements in powerful ways to make more complex 30 IF (A = B AND B>2) OR (A = 2 AND B = 3) THEN GOTO 60
decisions in programs. The expressions in brackets are evaluated first. The first expression in
brackets will be true if B is greater than 2 and equal to A. The second
expression will be true if A is 2 and B is 3. The program will pass
AND
control to line 60 if either expression in brackets is true.
To summarise: where TI, T2 etc. are true conditional expressions
AND combines relations so that the expression:
and FI, F2 etc. are false conditional expressions:
(condition 1) AND (condition 2)
(T1) AND (T2) TRUE
e.g. (A = B) AND (B>1)
(TI) AND (F2) FALSE
is TRUE when BOTH conditions are TRUE.
(F1) AND (T2) FALSE
It is FALSE when one or both conditions are FALSE.
(FI) AND (F2) FALSE
(TI) OR (T2) TRUE
OR
(F1) OR (T2) TRUE
(T1) OR (F2) TRUE
OR combines relations so that the expression:
(F1) OR (F2) FALSE
(condition 1) OR (condition 2)
Each condition may also be another AND or OR expression.
e.g. (A = B) OR (B<>1)
is TRUE when EITHER condition is TRUE.
It is FALSE when both conditions are FALSE.
Exercises'
The expressions formed by the use of AND and OR are used with
Work out what will be printed by these programs, then key in and run
IF...THEN statements. For example:
them to check. The operator "I" means "divided by" (=) and "*"
means "multiplied by" (*).
20 IF X>1 AND X<10 THEN PRINT
" BETWEEN 1 AND 10"
97
96
1
• •
SECTION I: PRINTING
10 LET A=2
20 LET B=3
30 LET C=10
I1: PRINT LPRINT
40 LET X=15
50 IF X/B=A AND C/A=5 THEN PRINT PRINT
"LINE 50 TRUE"
60 IF X/B=A OR C/A=5 THEN PRINT
"LINE 60 TRUE" The PRINT statement is used to output information by
70 IF X/B=C/2 AND X>=15 THEN PRINT displaying it on the screen.
"LINE 70 TRUE"
2
10 LET A=20 It can take many forms. For example:
20 LET B=150
10 PRINT A prints out the value of
30 LET X=7.5
40 LET Y=2 numeric variable A
50 LET S=8/20 20 PRINT B$ prints out string variable BS
60 IF S=X AND X*A=B AND Y=2 THEN
30 PRINT "YOUR NAME?" prints out whatever is
PRINT "LINE 60 TRUE"
70 IF X=B OR X<20 OR X>2 THEN included within the quotes
PRINT "LINE 70 TRUE" (inverted commas)
80 IF (X=7.5 OR Y=10) AND (A,/Y=1
40 PRINT (B**2 – 4*A*C) prints out the calculated
0 AND B=150) THEN PRINT "LINE
80 TRUE" value of the expression
50 PRINT leaves a blank line
Make sure you have got the programs correct before you run
them. Work out both sides of each expression using a relational
operator first. Then, giving each expression a T or F value, work LPRINT
out the bracketed AND/OR expressions. This gives you a T or F
value for the whole bracket. Then work out whether the whole The LPRINT statement is used to output information by
expression will be true or false. printing it out on the printer.
3 Write some similar programs for yourself to experiment with all
the relational operators used with AND and OR.
The LPRINT statement is used in exactly the same way as the PRINT
statement, but produces printer and not screen output. If the printer is
not attached LPRINT statements are ignored.
98 99
CLS
• 40 PRINT
•
50 PRINT "NUMBER!","NUMBER2",
CLS erases all printing on the screen, and sets the new print "AVERAGE"
position at the start of the top line of the screen. 60 PRINT A,B,(A + B)12
The display is:
I2: Spacing Items on the Screen AVERAGE 8.16
NUMBER! NUMBER2
AVERAGE
7.65 8.67
A semicolon (;) between two items causes the printing of the
8.16
second item immediately after the first. Clearly the comma is useful if we wish to print a table with two
columns, but is unsuitable if we wish to have a table with more than
two columns.
For example:
10 PRINT A;B$
20 PRINT "AVERAGE";C It is important to remember the screen size when deciding the
Try the following program: form of your output. For your output the effective screen is 22
10 LET A = 6.89 lines each 32 columns wide.
20 LET B = 87.6
30 PRINT A;B
40 PRINT "AVERAGE";(A + B)/2 TAB
The display is:
6.8987.6 TAB C; moves the print position to column C. If this would
AV ERAGE47.245 involve back-spacing it moves on to the next line.
This does not give a very satisfactory display since values run into each
other. One simple way to overcome this is shown below.
10 LET A = 6.89 The following program (with printout) indicates how the TAB function
20 LET B = 87.6 can be used to improve the presentation of results.
30 PRINT A;" ";B
40 PRINT "AVERAGE ";(A + B)/2 10 LET A$ = "A.B.JONES"
The display now becomes: 20 LET B = 65
6.89 87.6 30 PRINT "NAME";TAB 6;A$;TAB 19;"AGE";
AVERAGE 47.245 TAB 23;B;TAB 27;"YEARS"
i nn 101
NO. SQUARE CUBE
•RECIP
•
The TAB function uses C = 0 to 31 only.
1 1 1 1 The AT function uses L = 0 to 21
2 4 8 0.5 and C = 0 to 31.
3 9 37 0.33333333
You should have noticed that the PRINT commands reinforce each
4 16 64 0.25
other, and provide alternative ways of achieving the aim of placing
5 25 125 0.2
characters, character strings or numbers at the desired positions on the
6 36 216 0.16666667 22 line, 32 column screen display.
7 49 343 0.14285714 For example, these three programs:
8 64 512 0.125
9 81 729 0.11111111 10 LET X = 3
10 100 1000 0.1 20 PRINT X,,,,
30 PRINT X*X
tno t n`3
• •
Put your computer in graphics mode and run through the keyboard,
" , so that line 10
strings will work; we add 4 spaces after "ZX81 noting the unshifted and shifted versions of each key. Note that
RUBOUT (DELETE) works with the 1G I cursor, but the cursor
becomes: 10 PRINT AT 10,10; "ZX81 control keys do not, and that the I I, I cursor must be on screen for them
use to work.
and for numbers, we (7 spaces)
PRINT AT 0,0;X; " By the time you fill one line and move on to the next, you will see
Using LPRINT also requires care. that all these graphics characters join up, with no gaps between the
cells. The difference between the grey cells on the A and K keys is that
For the LPRINT instruction, TAB works exactly as PRINT they join up with the half-shaded graphics cells on the S, D, F and G
keys in different ways. Experiment with these. If they join up properly,
TAB .
AT L,C is converted to LPRINT TAB C, and the you cannot see the join. If they do not, the join is visible as a chequered
LPRINT pattern. To check the characters across the screen, use the bottom lines
line number is ignored.
of the screen directly. To check the vertical joins, enter this program:
This is because the printer cannot go back to a previous line. Try this 10 INPUT A$
program. Input 1,2,3 14,,5. 20 PRINT A$
INPUT X 30 GOTO 10
20 LPRINT AT X,X;X Change the cursor to G I , then input the graphics character. You
30 GOTO 10 have to then press NEWLINE (ENTER) twice; the first time to change
will print 12345, as if line 20 had read LPRINT TAB X;X. e of G to , the second to input the character.
For any programmed screen format that is not a simple sequenc We can use the graphics characters to draw (crude!) pictures,
print lines, it is better to use COPY to produce output on the printer, enhance printout on the screen – by printing prompts in inverse video
once all the data is on the screen. for example – or putting titles inside surrounds, and use them in
diagrams or moving graphics. You'll have to wait a few more chapters
COPY prints the entire current screen display on the printer. before we can do anything interesting, but here are a few things to try:
than whol by Here's a program to put a border round a word in inverse video.
in aprogramn the Notice we store the graphics in string variables. This gives us better
If used as BREAK before dcomp letion , but lessused
pressing manipulative power than if we, just used literal strings. On the ZX81
whole screen will be copied. the graphics characters in A$ are the shift graphic on the E key, 11
times the one on the 7 key and the one on the R key. If you are using a
I4: The Graphics Characters on the ZX81* Spectrum, the relevant keys are `4', `3' and `7'. You can work the
other lines out for yourself.
The ZX81 character set includes a set of graphics characters, and you
were told how to access them in Section B. To recap:
5 HEM **OLOCK+x
k get
Graphics characters are accessed by using
the
cursor. Repeat to return to rsoG ra s hifted
fives o
yt
s
10 LET A$=••
20 LE T E$=..
30 LET C$="
d-0 LET =0
50 LET Y=0
^
then produce inverse video characters. (e.g. key Q give 60 PRINT AT X,Y; Ft$; F.T ?:+1,Y; B$
keys produce graphics cells, if shown on the keys: e.g. ;AT v +2, ;C$
g.
SHIFT R gives I
.If no graphics cell is shown,
form of normal shifted character (e.g. SHIFT U
inverse video Notice the combined PRINT AT statements in line 60.
gives 3 ). The production of inverse characters on the Spectrum (white
characters on a black background, unless colour is being used) can be
The inverse video characters and graphics cells can be used for
done in different ways. You can use CAPS SHIFT and the 4 key to put
enhancing displays and drawing bar charts, diagrams and pictures.
an INVerse VIDEO control character before a letter or other
They are manipulated as strings, by putting quotes round them, e.g.
character, but this will make all characters thereafter into their inverse
PRINT " " or PRINT " e " forms unless CAPS SHIFT and 3 is used to restore NORMAL
The Spectrum offers more extensive graphics facilities than the ZX81, and Spectrum
solid VIDEO. The alternative is to use INVERSE as part of a program
• graphics
owners not the shaded characters,on keys 1 to 8 t ine
of the ZX81 but ,h, in mind. 105
•
statement. INVERSE is obtained using SYMBOL SHIFT and the M
key in E mode. To get inverse video this must be followed by 1, so that
•
2 Add a routine to LPRINT name, address and age, without the
borders or titles, on the printer after deleting the COPY
to print HELLO in inverse video we key in: instruction.
10 PRINT INVERSE 1;"HELLO"
3 Input names, ages and occupations of three friends and arrange
This will appear normally in the program listing, but in inverse when them to be tabulated in a suitable form.
the instruction is carried out.
4 Experiment with ways to make the car move across the screen.
Now add the following lines, and you will see why the use of string
variables, and variables for the line and column numbers, can be
useful.
70 LET X = X + 1
80 LETY=Y+1
90 CLS
100 GOTO 60
Run the program, and you see we have a crude moving display. CLS
makes the screen `flash' a bit, but we could avoid this by overprinting.
Revise the program to erase by overprinting empty strings.
We can use the graphics characters for pictures. Try this:
10 PRINT AT 0,9; mow
20 PRINT AT 1,8; ==
30 PRINT AT 2,8;
Change the program to allow you to input a value for Line and
Column numbers, so that you can place the car in different places.
Then add a GOTO loop to allow multiple cars on the screen.
Exercises
NAME:
AGE:
ADDRESS:
107
ARITHMETIC AND FUNCTIONS
• understood, but there is no harm in using them to ensure correct
SECTION J: evaluation. Expressions may be tested by using PRINT as a direct
command, to check that you have them correct. For instance key in
PRINT (8*2.6/5)*2/3 and press NEWLINE (ENTER). The result will
J1: Arithmetic Operations be printed on the screen. If a sequence of direct assignments of values
to variables is keyed in first (using LET A = 4 (NEWLINE/ENTER),
A prime function of the computer is to evaluate formulae and LET B = 3 (NEWLINE/ENTER), etc.) then variable expressions may
expressions similar to those used in standard mathematical calculation. be evaluated.
Algebraic EXPRESSIONS are written in BASIC using the Using this facility you should experiment with a variety of
following OPERATORS with a set of variables or numbers as the expressions until you feel confident that you have understood the way
OPERANDS. in which expressions are evaluated, and the way you have to formulate
an expression in BASIC to ensure it returns the desired result.
EXAMPLE
ARITHMETIC OPERATOR
I MATHS
PRIORITY BASIC
SYMBOL NAME B* *3 A' EXAMPLES
exponentiation 10
**
(raising to a power)
(on the Spectrum)
AT3 A' 1 Evaluation of a + b — c
[ T] —A
9 —A In BASIC: A+B—C
— negation A x B (a.b)
8 A*B Operators have equal priority;
* multiplication
A=B (b) (1) Left to Right A+B
8 A/B
/ division (2) L —' R (A + B) — C
6 A+B A+B
+ addition
A—B
6 A—B 2 Evaluation of = b , (a x b) = c
subtraction c
In BASIC A*B/C
operand — a unary operation ( i.e.
Note that negation operates on one * has same priority as /
makes a variable negative, e.g. — A) and that the subtraction operator (1) L —* R A*B
binary operation.
uses two operands, e.g. A — B, a (2) L R (A*B)/C
s
J2: Priority 3 Evaluation of a. (b) , ax(b=c)
1 All arithmetic, conditional and logical operations are assigned a In BASIC A*(B/C)
number from 10 to 1. High priority is 10, low priority is (1) Brackets first (B/C)
priority
1. The priority numbers for the arithmetic operators are as (2) Multiplication A*(B/C)
shown in the previous Unit. But notice we could write the expression without brackets in
2 The priority of an operation determines the order in which it is BASIC as B/C*A
evaluated in a complex statement in which more than one This is evaluated:
operation is to be performed. High priority operations are (1) L R (B/C)
(2) L R (B/C)*A
performed earlier.
3 Brackets (parentheses) are used in BASIC algebraic expressions. which gives the correct result.
Brackets clarify which expressions constitute separate values to
be operated on. Expressions inside brackets are evaluated first 4 Evaluation of (b 2 — 6e) 2 + 5
. With multiple In ZX81 BASIC notation: (B**2 — 6*C )**2+5
before the quantity is used in further computation (1) Inside bracket;
nested) brackets the evaluation proceeds from the innermost
( exponentiation B**2
bracketed expression to the outermost.
4 For operations of equal priority in the same statement, (2) Inside bracket;
multiplication
evaluation is from Left to Right. 6*C
(3) Inside bracket;
Brackets can often be omitted when the sequence of evaluation is subtraction (B**2) — (6*C)
109
1nft
(4)
(5)
Exponentiation
Addition
((B*
*2) -•
( 6*C )) * *2
(((B**2) - (6*C))**2) + 5
Priority 9
Negation
• - 70
Priority 8 2 * 16 *3 3*7
In Spectrum BASIC notation: (B t 2 - 6*C ) T 2 + 5
(1) Inside bracket; L -^ R 96 21
exponentiation B T2 Priority 6 - 70 + 96 - 21
Inside bracket; 6*C
(2) Result
multiplication 5
(3) Inside bracket; Exercises
subtraction (B T 2) - (6*C)
(4) Exponentiation ((B t 2) - (6*C)) t 2 1 Write the order in which the following BASIC expression is
(5) Addition (((B t 2) - (6*C)) t 2) + 5 evaluated:
5 Computer evaluation of a. b - ci + (e
d g - A + ((B* *3/C) - (A**2/D))*(E + F)/G (ZX81)
A*B - C**3/D + (E - F)/G - A + ((B t 3/C) - (A t 2/D))*(E + F)/G (Spectrum)
In ZX81 BASIC notation:
(1) brackets E-F
C**3 2 Write down the BASIC expressions for:
(2) exponentiation
(3) multiplication/ (i) (u 2 + tas)
division L R A*B C**3/D (E-F)/G (ii) ut + + ate
(4) addition/ b + (4ac) iz
subtraction L -' R (A* B) - (C * *3/D) + (E - F)/G (iii) 2a
(iv) (X a) , e
In Spectrum BASIC notation: A*B - C t 3/D + (E - F)/G
E-F Work out the order in which each of the expressions is
(1) brackets evaluated. Test your results on the computer.
exponentiation C T3
(2)
(3) multiplication/
R A*B C T 3/D (E - F)/G J3: Number
division L
(4) addition/
subtraction L -' R (A*B) - (C t 3/D) + (E - F)/G A positive or negative decimal number whose magnitude is
between an approximate minimum of:
6 Evaluation of - 70 + 2 x 4 2 x 3 - 3 x 7 ±3 x10-3Y
In ZX81 BASIC notation: - 70 + 2 * 4**2 * 3 - 3 * 7 and an approximate maximum of:
Priority 10 4**2 ±2 x 1038
16 Zero is included in this range.
The smallest number the computer can handle is
Priority 9 - 70
2.9387359 x 10 -39
Negation The largest is:
Priority 8 2 * 16 * 3 3 * 7 1.7014118 x 1034
96 21 The computer stores and calculates numbers internally to an
L R
accuracy of nine or ten digits, but prints out the results of
Priority 6 - 70 + 96 - 21
calculations to eight significant figures only, rounding where
5 necessary.
Result
110
•
number of decimal digits. E should be taken to read: `times
ten to the power of'. For example:
• 10 LET A = 1
20 LET A = A*10
30 PRINT A
1.73 E5
40 GOTO 20
is With the ZX81 press CONT and NEWLINE (ENTER) when
1.73 times 10 to the power of 5
the screen becomes full, and the message 5/30 appears on the
= 1.73 * 10 "5 (1.73 ` 10 T 5 in Spectrum notation) bottom of the screen to indicate no more room on the screen.
= 173000. The Spectrum will display the `scroll?' prompt.
Similarly:
Notice the change to the E notation. Note that the program
3.8 E – 7
finally stops itself on the ZX81 with the error message `6/20',
is which indicates an arithmetic overflow (error code 6) as a result
3.8 times 10 to the power of – 7
of line 20, i.e. the number is too large for the computer to
= 3.8` 10" – 7 (3.8' 10 T – 7 in Spectrum notation)
handle. The Spectrum's response is more precise; the error code
= .00000038. in this instance will read: `6 Number too big, 20:1'.
The computer will accept any number keyed-in in this form
2 Change line 10 of the program to each of the following and run
and will print out numbers in this notation when their values
the program each time.
are outside a certain range.
a) 10 LET A = 1.00000000
b) 10 LET A = 1.1111111
For large positive and negative numbers the E notation is
c) 10 LET A = 1.7
automatically used by the computer for numbers
d) 10 LET A = 1.7014118
>= 10'`
Numbers up to this figure are first rounded to 8 significant figures and e) 10 LET A = 1.71
What conclusion do you draw?
trailing zeros are added until 10" is reached.
3 To show that negative numbers behave in the same way, change
Key in and run this program:
10 LET A = 9.9999993E12 line 10 to the following and run the program.
a) 10 LET A = – 1
20 PRINT A
30 LET A = A + 1E5 b) 10 LET A = – 1.7
c) 10 LET A = – 1.7014118
40 GOTO 20
d) 10 LET A = – 1.71
Change line 20 to read: 4 To show how small numbers are handled by your computer a
20 LPRINT TAB 10;A
similar program divides a number (A) by increasing powers of
to get a listing of the result on the printer.
10.
For small positive and negative numbers the E notation is
Key in the program and run it.
automatically used for numbers:
<= 10 6 10 LETA=1
To see this in action, key in and run the program below: 20 LET A = A/10
10 LET A = 1.000001E – 5 30 PRINT A
20 PRINT A 40 GOTO 20
30 LET A=A–(1E-12) Note the change of notation.
40 GOTO 20 Notice that after l E – 38 the computer prints zeros
indefinitely, i.e. it has reached the smallest number it can
Change line 20 to: 20 LPRINT TAB 10;A register.
5 Change line 10 to
if you want a printer listing of the changeover.
a) 10 LETA=3
b) 10 LET A = 2.9
Exercises
and re-run the program each time.
1 Key in and run the following simple program, which illustrates Notice that 2.9387359 E – 39 is the smallest number before
how numbers are printed, the E notation and the largest number zero.
Write this number out in full.
which may be obtained.
Can you think of any applications for very large and very
small numbers?
119 113
•
6 Change the values of A in the program to negative values and
•
PRINT 0.111111111 + 0.888888888
confirm that small negative numbers behave in the same way. the answer on the screen is 1.Try
PRINT 0.0000111111
PROGRAMS TO SAVE IN YOUR TAPE LIBRARY showing 10 digits can be held exactly.
Adding a one on the end forces the use of the E notation.
The following two programs should be keyed in, run, listed and saved
for your tape library. They both do what the previous programs did but
in addition give a printed copy of the results. ROUNDING DOWN
10 REM "LARGE NUMBERS" The INT function returns the nearest integer of the
20 REM** PROGRAM MULTIPLIES + expression X, which is < = X, i.e. it rounds down.
AND - NUMBERS INPUT FROM
e.g. INT 3.9 = 3
THE KEYBOARD BY POWERS 0
F 10 ** INT —2.8= —3
30 REM **KEY IN VALUES FOR A 0 INT (4-8.7+0.8)= —4
F +-1.,+-1.1111111,+-1.7, +
-1.7014118,4- 1.71.** Try printing these functions. Notice that for negative
40 INPUT A numbers — 6 is less than — 5, and so on. To round to the
50 LET N=0 nearest integer add 0.5 to the number first:
60 PRINT A*(10**N) e.g. INT (3.9 + 0.5) = 4
70 LPRINT TAB 10;A*(10**N)
80 LET N=N+1 INT (2.4 + 0.5) = 2
90 GOTO 60 INT (-1.7+0.5)= —2
INT(-2.3+0.5)= —2
Notice this assumes that 0.5 rounds to 1.
For the Spectrum, replace ** by t in lines 60 and 70.
INT (1.5 + 0.5) = 2
INT ( — 1.5 + 0.5) = —1
10 REM "SMALL NUMBERS"
20 REM**PROGRAM SHCWS PRINTING
OF SMALL NUMBERS**
M**INPUT VALUES OF A AS +
Notice we don't have to enter the zero before the decimal point on the
30 REM
-1, +-2.9,+-3.** computer (though it doesn't matter if we do), it's in that form here for
40 INPUT A clarity.
50 LET N=0
60 PRINT A*(10**N)
70 LPRINT TAB 10;A*(10**N) J6: How Numbers are Handled
80 LET N=N-1
90 GOTO 60 All computers perform their arithmetic and processing using
the BINARY NUMBER SYSTEM
In the binary system only two digits are used, 1 and 0. A group of 8
binary digits (bits) is called a BYTE, and we communicate with the
J5: Rounding
computer in Decimal Notation. This is rather more convenient than
using Binary. Conversion from Decimal to Binary and vice versa is
ROUNDING UP thus necessary and occurs inside the computer.
One BYTE is equivalent to a single character of the computer's
The computer will print out computed values to an accuracy character set. A byte represents a number between 0 and 255
of 8 significant figures, ignoring leading zeros. (decimal). This is why the character codes are in this range (see Section
Digits after the 8th significant one will be rounded up. For P). A group of 8 zeros and ones can have 2" (= 256) different states.
example, if we key in (as a direct command, followed by A digit or number is represented by one or several bytes according to
NEWLINE/ENTER): its context in the computer.
114 115
•
A character input to the computer or output to the screen or printer
The standard mathematical and trigonometric functions are
is held in one byte. Program line numbers, which are whole numbers 1
important timesavers for programmers. They are the same as the
to 9999, are held in two bytes.
function keys on scientific calculators. Other functions (utility
Numbers are held in a form which occupies five bytes. The point to
functions) control or monitor the handling of data by BASIC rather
be noted here is that conversion from decimal to binary and back is
than perform mathematics.
involved in the operation of the computer, and this conversion is not
If the functions were not available in BASIC we would need to write
always exact. This must be allowed for in certain circumstances,
separate programs to undertake their tasks every time we had need of
especially where the computer is asked to check whether two numbers them!
are equal. A difference in the binary form of the number, however small,
will cause the computer to decide they are not equal. In testing two
numbers for equality, therefore, if non-integer values have been J8: List of Functions used in Sinclair BASIC
utilised, and the value of one number arrived at by calculation, the
equivalence check should be replaced by assessing the difference. A In this list of functions X is the argument. X is a variable, a number or
statement such as: an expression. If an expression, X must be in brackets. Each of the
IF ABS(A – B) < 1 E – 4 THEN... individual functions will be discussed in more detail later in this
section.
which checks that the difference between the numbers is less than
.0001, can be used instead of IF A = B THEN...., if either A or B has
been calculated. 1. Standard Mathematical Functions:
The forms in which numbers are held in the computer are ABS (X) – gives the absolute value of X
considered in detail in Section U – the Computer Memory. EXP (X) – gives e x , value of e raised to the power X
INT (X) – gives the largest integer < = X, i.e. rounds down
LN (X) – gives natural logarithm (value of log e X)
J7: Function SQR (X) – value of fX or X % (X positive)
PI – 3.14159265 i.e. value of n, PI, which is how it
We define a FUNCTION as prints on screen
Y = F(X) SGN (X) – gives sign of X, i.e. whether X is + ye, – ye or
`Y equals some function of X, F(X)' zero.
A function is the mathematical relationship between two
variables X and Y such that for each value of X there is a 2. Trigonometric Functions
unique value of Y. SIN (X) – value of sine X (X in radians)
COS (X) – value of cosine X (X in radians)
TAN (X) – value of tangent X (X in radians)
Y takes the function value and is the DEPENDENT VARIABLE. ACS (X) – angle in radians whose cosine is X
X is the ARGUMENT – the INDEPENDENT VARIABLE. – arccosine X( – 1 < = X < = 1)
F is the function NAME, e.g. square root, sine, natural logarithm. ASN (X) – angle in radians whose sine is X
In a program statement we write, for example: – aresine X ( – 1 < = X < = 1)
100 LET Y = SQR(X) ATN (X) – angle in radians whose tangent is X
The argument X can be a single variable, a number or an expression. – arctangent X
If X is a single variable or a number it does not need brackets. If it is an
expression it requires brackets so that the expression is evaluated 3. Special Mathematical Functions
before the function is applied to it (so that SQR 9 + 7 gives 10, whilst RND A random number generating function; gives the
SQR (9 + 7) gives 4). For example: next pseudo random number N from a fixed series
100 LET Y = SQR 9 of random numbers (0 < = N < 1).
100 LET Y = SQR(B**2 – 4*A*C) (Bt2 on the Spectrum) RAND ( = RAND 0) starts the sequence of random
We see that a function is a mathematical operation which gives a numbers in an unknown position.
number. It is treated in BASIC as a numeric expression, with priority RAND N (0 < = N < = 65535) makes RND always return to
11. the same value, if N is the same.
117
• characters on the ZX81 is situated at the same position on
4. Character and String Functions each key, i.e. bottom outside.
CHR$(X) 0< = X < = 255 returns the single character To obtain the function the ZX81 must be in FUNCTION
whose code is X. MODE, with the F-cursor on the screen.
CODE A$ When applied to the string A$, it returns the On the Spectrum, all functions are obtained in the
code of the first character in the string or 0 if the Extended mode with the E-cursor on the screen (for further
string is empty (null string). details see Section W1). All FUNCTIONS treated here are in
LEN A$ Returns the number of characters in the string. green above the key on the Spectrum, with the exception of
VAL A$ Turns a string in number representation into ASN, ACS, ATN which are in red below the associated SIN,
the number for calculation (e.g. A$ _ "12.4", COS and TAN functions, although they are still obtained in
VAL A$ = 12.4). the E-mode.
STR$ N Turns the number N into the string "N". The F UNCTION/EXTENDED MODE only lasts for one
function. To obtain successive functions this mode must be
5. Printing Functions used in the form PRINT F(X) repeatedly entered.
TAB (X) Places the print position in column X. If X>32
then column number is the remainder when X is J10: The Function Character Set
divided by 32. If it involves back spacing, goes
on to next line. Rounds X to nearest integer.
Character Code Code
AT (X), (Y) Starts printing at line X, column Y
0 <= X <=21 0 <=Y <=31 (ZX81) (Spectrum)
Rounds X and Y to nearest integer. SIN 199 178
COS 200 179
6. Special Functions TAN 201 180
INKEY$ No argument. Reads keyboard and senses what INT 207 186
key is being pressed at that time. Returns key RAND 64 249
being pressed as a string, e.g. "A" or "8". If no STR$ 213 193
key is pressed the null string is returned. CHR$ 214 194
PEEK X 0 < = X < = 65535 Returns the value of the byte CODE 196 175
at address X in RAM or ROM memory. PEEK 211 190
USR N Returns the contents of a pair of CPU registers TAB 194 173
after running a machine code program from
address N. ASN 202 181
ACS 203 182
ATN 204 183
N.B. For the Spectrum's additional functions, see Section W. The
SGN 209 188
above functions, common to both the ZX81 and the Spectrum, are the
ABS 210 189
ones used in the main body of the text.
SQR 208 187
VAL 197 176
LEN 198 177
J9: The Function Characters
USR 212 192
Each of the functions in Sinclair BASIC is represented on the LN 205 184
keyboard as a single character word. EXP 206 185
You don't have to type the function name letter by letter (if AT 193 172
you try to it won't work), just press the particular function INKEY$ 65 166
key. NOT 215
Each function character has a special character code and is 195
n (PI) 66 167
part of the computer's character set. Each of the Function
119
•
These are the function characters as represented on the ZX81
•
2 Write a program which will calculate Q from the expression:
keyboard. NOT is dealt with in Section R and INKEY$ in Section K. Q= Qo.e -" « (In BASIC Q= QO* EXP(– T/R*C))
Note that ARCSIN, ARCCOS and ARCTAN are used on the ZX81 If you know anything about electricity, you might recognise this
keyboard but print as ASN, ACS, ATN, and n prints as PI. expression.
3 Key in this program. It calculates a value for e from the formula:
J11: The Standard Mathematical Functions e = (1 + 1/N)**N (T N on Spectrum)
where N is very large. Spectrum users should replace ** by t in
lines 30 and 40.
ABS (X)
10 REM "VALUE OF E"
Returns the absolute value or modulus of the valut X. 20 LET I = 1
X may be a number, variable or expression. 30 LET N = 10'I [ T Spectrum]
ABS(X) gives us the positive value of X. For example: 40 LET E = (1 + 1/N)**N
1A PRINT ABS( – 3.7) gives 3.7 50 PRINT TAB 1;N;TAB 12;E
10 PRINT ABS (4) gives 4 60 LET I=I+1
70 IF I = 5 THEN STOP
80 GOTO 30
Exercises
LN (X)
Key in and run this program:
10 INPUT A Gives the value of the natural logarithm.
20 INPUT B LN (X) = Log e (x)
30 PRINT TAB 3;A; TAB 10;B Note that log i0 (X) (common logarithm)
40 PRINT TAB 3; ABS (A – B) = (LN(X) )/( LN 10 )
50 GOTO 10 The LN function is the inverse of EXP
Input positive and negative values for A and B. So: If EXP (X) = Y
Now change line 40 to: Then (X) = LN(Y).
40 PRINT TAB 3; ABS (A*B)
**
and input some more values. Try replacing the * with
LN (Y) is the natural logarithm of Y. The antilog is EXP(LN(Y)). The
(t Spectrum), or using ABS (SQR A). normal log operations can be used if appropriate, as with common logs.
N.B. ABS (– 3**3) , or expressions in similar form will not work
For example EXP(LN (X) + LN (Y)) gives the product of X and Y.
as the * * (t Spectrum) operator only works for positive first operands.
Exercises
EXP (X)
1 10 LET Y = 1
Where X is a number or an expression EXP (X) gives the 20 PRINT TAB 3;Y; TAB 10;EXP (LN Y)
value of the constant e raised to the power of the value of X 30 LET Y = Y + 1
40 GOTO 20
e = 2.7183
e.g. 10 PRINT EXP (3.4) Key in and run this program which proves the relationship
between the EXP and LN functions.
i.e. 10 PRINT (2.7183**3.4) (2.7183 t 3.4 on Spectrum)
The function EXP is the inverse to LN. 2 Change 30 to: 30 LET Y = Y* 10 and run again.
SQR (X)
Exercises
The function SQR returns the square root of (X), /(X) or
1 Using log tables write a program to check the values of e' given X05 . For example:
in the log tables.
120
121
PRINT SQR 9 gives 3
•
gives 4.7958315
•
for every 20 degrees in the range 0 - 360 degrees.
2 Write a program to verify the trigonometric formula:
PRINT SQR 23
PRINT SQR (19 + 17) gives 6 SIN 2(X) + COS 2(X) = 1
PRINT SQR (ABS - 25) gives 5 1+ TAN 2(X) = SEC2(X)
3 Write a program to calculate the area of a triangle from a
knowledge of the length of 3 sides and an angle.
SGN (X)
SGN (X) returns + 1 if (X) is positive, 0 if (X) is zero, - 1 if ACS ASN ATN
(X) is negative.
SGN is short for Sign or Signum (Signum doesn't sound like The functions:
Sine). For example: ACS (X), ASN (X), ATN (X)
SGN 23 gives 1
give the arc cosine, the arc sine and the arc tangent,
SGN - 5 gives - 1
respectively, of (X).
SGN (3 - 3) gives 0
The returned value is the angle in RADIANS for which the
SGN 1 gives 1
cosine, sine or tangent would be given by the value of (X).
SGN (25 - (2*23)) gives - 1
To get the angle in degrees multiply by 180/PI e.g.
Y = 180/PI*ACS(X) gives arcsin (X) in degrees.
n PI
Notice these functions print as above, but appear on the ZX81
n (which prints on the screen as PI) is a function which has no keyboard as ARCSIN, ARCCOS, ARCTAN.
argument. It returns the value of n as 3.1415927.
J13: Special Functions
3.1415927 is what prints on screen for PI. How would you test whether Random number generators are useful for games and simulation in
the computer held any more digits of PI in memory? What happens statistics. The numbers generated are part of a very long sequence of
when you take away 3 from PI? numbers (there are 65536 of them) and are in fact only 'pseudo-
random', but good enough for our needs.
J12: Trigonometric Functions
RND
SIN COS TAN
RND gives a random number greater or equal to zero but less
The functions SIN (X), COS(X) and TAN(X) give the value of than one.
the sine, cosine, and tangent of the number or expression X, 10 LET A = RND
which is an angular measure. X must be in RADIANS. assigns a number in the range 0 < = N <1 to the variable A.
We normally express angles in DEGREES. Notice RND has no argument.
8^ RADIANS (1° = 180 radians)
1 DEGREE = 1
To convert degrees to radians multiply by PI/180. For If we key in PRINT RND we get a number like .0011251904 or
example, if Y is our measure of angle in degrees then: 0.43715682 which is eight or ten digits long and is not much use to
SIN (Y*PI/180) anybody in this form.
gives the correct value of Sine Y. We need to be able to generate random numbers within a useful
range, according to our purposes:
123
122
function by 10 and take the integer value.
• •
50 IF C<6 THEN GOTO 30
i.e. PRINT INT (RND*10) 60 GOTO 10
RND*10 gives random numbers between 0.00000000 and Not amazingly random after all!
9 . 9999999. INT( ) will round these values down to integers
0 . to 9. Exercises
2. Numbers 1-10 1 Write a program which throws three dice and prints the values
Although 0 to 9 gives us ten values the range 1 to 10 would be thrown across the screen.
more useful. This is obtained by adding one to the RND function: 2 Write a program to check that the number generated by RND
PRINT INT (RND*10 + 1) using RAND N is given by RND = (75*(N + 1) – 1/65536).
Suppose we wanted random numbers generated for simulating a 3 Modify the coin tossing program to count the number of times
dice roll, we would use: heads or tails have come up (you need one variable for each).
PRINT INT (RND*6 + 1) When you've stopped the program by pressing BREAK, you
can then access the values by keying in PRINT HEADS, or
3. Random Numbers for a Card Game whatever your variable name is, as a direct command.
4 Write a program to print four groups of three random numbers
There are 4 suits, with 13 cards per suit = 52 cards. So if we used:
in the range 1 to 52.
PRINT INT (RND*52 + 1)
we could select cards at random.
Think about how you could identify the suits and not deal the
same card twice.
4. Tossing a Coin
There are two outcomes, head or tails, so:
10 LET A = INT(RND*2 + 1)
20 IF A = 1 THEN GOTO 50
30 PRINT "TAILS"
40 GOTO 10
50 PRINT "HEADS"
60 GOTO 10
This program will toss coins until we use BREAK.
RAND N
124 125
SECTION K: STRINGS
• •
All other characters in your computer's character set can be used.
Run the program which checks this:
10 INPUT A$
K1: Strings 20 PRINT A$
30 GOTO 10
Now try and input some of the above characters.
A string is a set of characters enclosed by quotation marks,
Examples of the sort of text we may want the computer to handle
e.g. "THIS IS A STRING" or the null string (no characters
are:
(f"). —a telephone directory
Typical Strings: "BALL OF STRING"
—names and addresses
"JANUARY 1ST 1982"
—a timetable
"URGHH!"
"FAB ** — + /!3"
"1234"
"(String of spaces)
—expenses details
Computers store all this textual information as strings.
String manipulation by the computer would, for our first example,
need to deal with:
"" (Null string)
creating the telephone directory
sorting the names and numbers into the correct order
Computers handle two kinds of DATA:
searching the directory for somebody's number
NUMERIC — numbers revising the directory, i.e. updating or adding an entry
ALPHANUMERIC — names or TEXT. printing out the directory in whole or part.
The way a computer deals with text is called STRING HANDLING.
Strings deal with ALPHANUMERIC information. K2: Quotes and Quote Image
The sequence of alphanumeric characters is handled in a string as a
single unit of data.
Characters are defined as LITERALS when placed inside quotes QUOTES
" ". They are taken literally to represent themselves. Strings are
therefore literals. All strings are enclosed in quotes "" when:
Characters are IDENTIFIERS where they are not enclosed in (1) They are to be INPUT from the keyboard, as in a program
quotes. Thus, for example, A represents or identifies a numeric line such as: 10 INPUT A$ . When the line is run the I L1
variable and A$ identifies a string variable. cursor on the screen appears already enclosed in quotes " L I I
Strings can either be of FIXED LENGTH — e.g. always 10 You key in just the characters wanted in the string.
characters long — or VARIABLE LENGTH. The fixed length is (2) When used in programs with the PRINT instruction, e.g.
determined by the string dimension instruction: 20 PRINT "STRING".
DIM A$ (N) (3) When assigned in a program to a string variable, e.g. 30
where N is the length in characters. LET A$ _ "STRING".
126 127
•
When the line is run the double quotes will be printed on the screen as
•
The Spectrum returns the I CI mode character with INKEY$ if in the
CAPS mode.
single quotes:
SAY "HELLO " TOO We can spend as long as we want before we input a string with the
A special character is needed as two single quotes won't work. INPUT command, since the cursor will remain on screen. If we want
Key in and try to run each of the following lines: to take advantage of the fact that, unlike INPUT, INKEY$ does not
10 PRINT " SAY "HELLO" TOO" require NEWLINE(ENTER) to be pressed, we must arrange a delay.
10 PRINT "SAY"; "HELLO"; "TOO" Try this program:
10 PRINT " SAY ""HELLO "" TOO" 10 PRINT "PRESS A KEY WHEN READY"
The Spectrum has no QUOTE IMAGE character. Instead, you must 20 IF INKEY$ = "" THEN GOTO 20 (no spaces)
put two quotes for every one you want printed. For example, to obtain 30 LET A$ = INKEY$
double quotation marks you type in PRINT""" " '. Single quotes 40 PRINT "YOU PRESSED ";A$
are obtained with PRINT"" "". Program listings look the same for Line 20 sends the program back to the beginning of line 20 as long as
both machines. no key has been pressed. Line 30 makes A$ the single character string
returned by INKEY$ when a key is pressed.
Due to a design error the Spectrum has far less predictable keyboard
K3: String Input scanning using INKEY$ than the ZX81. If you type in the program as
above on the Spectrum it will work about half of the time. The rest of
On running 10 INPUT A$ the letter cursor appears at the the time it will skip over line 30. This program will work every time
bottom of the screen with quotes round it, prompting you to though:
key in characters for the string 10 PRINT " PRESS A KEY WHEN READY"
L ,, 20 PAUSE 0
On the Spectrum this can also be the C-cursor – " LJ ". 30 PRINT "YOU PRESSED ";INKEY$
Experiment with the two versions to see this problem in action. The
action of PAUSE 0 is to stop until a key is pressed. The first key
STOPPING STRING INPUT
pressed will be the INKEY$. PAUSE will be dealt with later, but
When keying in the characters for the string to be input notice remember this quirk of the Spectrum, and this method of dealing with
it. The rule is to use PAUSE 0 immediately before INKEY$ is used in
that BREAK and STOP have no effect. a program line, to wait for input.
To escape (1) Use the `– key to get I LI outside the quotes. Now enter and run this program:
(2) Press STOP, NEWLINE (ENTER) 10 PRINT "PRESS 6"
or 20 IF INKEY$ = ""
press RUBOUT (DELETE) I I STOP ^
19 1 129
K4: Length of a String
• •
20 PRINT A$
30 PRINT LEN A$
2 Key in and run this program:
LEN 10 LET A$="
20 PRINT A$
The length of a specified string A$ is obtained by using the 30 PRINT LEN A$
function: LEN A$. The length is given as the number of
characters and is the current length of the string. K6: String and String Array Variables
example:
LET A$ _ "" K7: String and String Array Dimension
The length of the string is 0.
13n 131
•
If strings of length <N (less than N characters) are assigned or input,
•
We can also use an INPUT instruction:
then space characters are added to make up the complete string of 10 INPUT A$(1)
length N. Spaces do not show up on the screen when they are printed! 20 INPUT A$(2)
To check they are in the string we can ask for their character set code 30 INPUT A$(3)
(
to be printed using the CODE instruction. We'll get to this later.)
Exercises
If more characters than the number allowed in the DIM A$(N)
statement are assigned from INPUT or LET statements they are
ignored. If strings are not dimensioned their length is effectively 1 Key in and run this program:
10 DIM A$(2,9)
unlimited.
The DIM statement fixes the length of a string until changed by 20 LET A$(1) = "PERSONAL"
another DIM statement. LEN is thus not useful when strings are 30 LET A$(2) _ " COMPUTING "
40 PRINT A$(1), A$(2)
dimensioned.
2 Now key in and run this. Input different strings of varying
length. The string length is set at 8 in line 10.
STRING ARRAY DIMENSION 10 DIM A$(3,8)
20 INPUT A$(1)
The DIM statement for string arrays has the form: 30 INPUT A$(2)
DIM A$ (N,L) 40 INPUT A$(3)
where N = number of strings and L = the fixed length of each 50 PRINT A$(1)
string. A may be any single letter A to Z, but must NOT be 60 PRINT A$(2)
the same as a simple string variable. Each string is set to 70 PRINT A$(3)
contain L spaces initially. 3 Key in and run this program:
For example, DIM A$(3,4) will reserve storage space for 3 10 DIM A$(6)
strings, A$(1), A$(2), A$(3), each of length 4, in the string 20 INPUT A$
array A$. 30 PRINT A$
40 PRINT LEN AS
50 PRINT A$;"END"
K8: String and String Array Assignment 60 GOTO 20
line 10 sets a length of 6 characters for A$
line 20 asks you to input a string
STRING ASSIGNMENT line 30 prints the string
line 40 prints the size of the string in terms of characters
Strings are assigned to string variables using the LET or
line 50 prints END starting directly after the 6th character in
INPUT instructions. For example: the string
LET A$ = "A STRING"
line 60 loops us back to input another string
or INPUT A$ a) INPUT less than 6 characters.
See that the remaining characters are spaces. Notice that
This establishes a value for the string. LEN A$ always gives 6 even though different numbers of
As we shall see later, the value may be a literal value in quotation characters are input for A$.
marks, or a string or substring value. b) INPUT 8 characters.
Notice the extra characters are ignored.
STRING ARRAY ASSIGNMENT
132 133
10 F:EM "SIMPLE1"
• •
20 PRINT "SEVEN TIMES TAFLE" COUNTER FLOWCHARTS
30 PRINT "UP TO TIME'_ 20"
40 LET N=0
50 LET N=N+1
60 IF N?20 THEN GOT! 100 (Start
70 PRINT N,7*N
30 ;OTC i 50
Counter =
Notice that the counting procedure in this program is set up differently Start
again. Line 50 increments the counter. Line 60 checks the counter Value
value. In this case, the IF — THEN statement has the effect of
transferring control out of the loop :f the counter exceeds 20, with the
GOTO 100 statement.
The procedure in this case is:
1 Initialise
2 Increment
3 Check counter. If greater than specified
value, jump to program end. No
4 Body of loop
5 Return to 2.
Counter =
Key in the program. Run it to check it loops exactly twenty times. Counter +
Then EDIT line 60, to insert: Step
75 IF N> 20 THEN GOTO 100
and delete line 60. Now run it. It is surprisingly easy to miss the
desired number of loops, if you are not careful with the structure of the
loop, and the exit conditions. (Change N>20 in line 75 to N> = 20 and Bod of loop
the program will loop the correct number of times).
Different procedures using counters give different program
structures. Look at the flowcharts of different counter procedures.
Remember that the conditional test can put to use the >, <, > = , < _ Exit Loop
= operators, as appropriate.
14;
• •
The GOTO statement in line 60 will cause the program to loop
Start
( continuously between lines 30 and 60.
This would continue indefinitely but line 40 is inserted so that the
program jumps out of the loop when N>20.
N is used as a counter. Line 20 initialises N and line 30 increments
Counter N by 1 each time the program goes round the loop.
= Start
Value
Write a program which calculates and prints the square and the cube
power of even numbers between 10 and 30. The counter will need to be
incremented by 2 each time the loop is executed by a GOTO
statement.
Write a program which loops 10 times (counter 1 to 10) but uses
another counter to print the squares of the ten numbers 5.25, 5.0, 4.75
Body of Loop .... 3.0.
146 147
•
NEXT F is the last line of the loop and increments
the counter F by the STEP value.
•
In the program, line 10 allows N to go from 1 to 15 with a step value
of 1. That is to say, N takes the values, 1, 2, 3, 4, 5, 6, 6, 8, 9, 10, 11,
We can also decrement the counter (decrease it). For example: 12, 13, 14, 15 each time performing the calculations within the loop.
10 FOR F = 100 TO 0 STEP – 2
The next program illustrates the use of different values for the step.
(where the decrement is 2)
The value can be positive or negative, integer or non-integer. In the
The loop will be exited in the first example when F>100 and in the
case of decimal increments or decrements there is the possibility of
second when F<0. F will take values 0, 2, 4 .... 98, 100 in the first
rounding errors if the loop is executed many times – it is therefore
case, and 100, 98 .... 4, 2, 0 in the second. Any program lines in the
advisable to use integer values for the step and divide by the
body of the loop will be repeated each time the program loops.
appropriate power of ten, if the loop variable is to be used in
Try these simple examples:
calculations. If this were done in the program below, lines 130 and 140
would read:
10 FOR F=2 TO 4 STEP 1.3 130 FOR N = 10 TO 56 STEP 7
20 PRINT F
140 PRINT N/10; TAB 8; (N/10)**2;
30 NEXT F
TAB 16; (N/10)**3 (t on Spectrum)
10 FOR F=4 TO —1 STEP —1
The program calculates squares and cubes for:
20 PRINT F
30 NEXT F 1, 4, 7, 31 (line 20)
120, 115, 110, 60 (line 70)
10 FOR F=-2 TO 4 STEP 2
20 PRINT F 1, 1.7, 2.4, 5.6 (line 130)
30 NEXT F Once again, Spectrum owners should remember that their machine
40 PRINT
uses the `up-arrow' (f) rather than the ZX81's stars (**) to represent
50 PRINT "F EQUALS ";F; " ON EXIT"
`to the power of'.
148
ian
14 •
program evaluates the average by dividing the total by the number of
• (START)
numbers input.
5 REM "AVERAGE"
10 LET T = 0
20 FOR N = 1 TO 10
30 INPUT X
40 LETT=T+X SET START
50 NEXT N VALUE OF
60 PRINT "AVERAGE = "; T/10 VARIABLE
This program illustrates a loop used to print a table. In this case a
heading is given (line 70) and this must be outside the loop as it is only
required at the beginning. We require all names and ages to be
tabulated so the print statement doing this (lines 140, 150) must be
within the loop. Finally, we require the average age, which is to be
printed underneath, and so the print statement (lines 170, 180) is
inserted after the loop has been completed. BODY OF'
LOOP
10 REM "IAOPS3"
20 PRINT "THIS PROGRAM PRINTS
OUT THE NAME AND AGE OF A
GROUP OF PEOPLE AND WORKS
OUT THE AVERAGE AGE"
30 PRINT
40 PRINT "INPUT NUMBER IN GROU
P"
50 INPUT X
60 LET T=0
70 LPRINT "NAME", "AGE"
80 FOR N=1 TO X
90 PRINT "INPUT NAME"
100 INPUT N$
110 PRINT "INPUT AGE"
120 INPUT A
130 LET T T+A
140 PRINT N$,A
150 LPRINT N$,A
160 NEXT N
170 PRINT "AVERAGE AGE="; T/X;"
YEARS" Yes
180 LPRINT "AVERAGE AGE"; T/X;"
YEARS"
EXIT
The flowchart of a FOR — NEXT loop would be drawn like this, if we
used the standard set of symbols as presented in the unit on
programming:
151
•
ENTRY
OUT OF LOOP
END LOOP
TO BODY OF LOOP
BODY
152 153
10 REM "VARLOOP"
• •
The procedure used in this program can confuse the flow of a program
15 PRINT "TYPE INITIAL VALUE" and must be used with care. It is useful on occasion, but it is preferable
2(1 I N PU'r I to have only one entry and one
25 PRINT "Y'YPE FINAL VALUE" exit from a loop. In this program, the
30 INPUT F loop may be exited from line 90 in addition to the normal termination,
35 PRINT "TYPE STEP" when N>100.
40 INPUT S
45 PRINT " X " , " X * * 2 + 4 * X - 3 " [ ?' Spectrum]
L5: Nested Loops
50 FOR N=I TO F STEP :i
60 LET Y=N**2+4*N-3 [ T Spectrum]
70 PRINT N,Y We can place one loop inside another loop, so that every time the
80 NEXT N
program goes through the outside loop, it will perform the inner loop
sequence. The inner loop must be entirely within the outer loop. Loops
It is important in such calculations to avoid the case where `division by
are said to be NESTED one inside the other. Loops can be nested to
zero' occurs. A simple example of how this may be done (line 40) is
any depth, i.e. we can have as many loops as we wish, as long as
shown below: they're correctly arranged.
5 REM "DIVZER"
30 FOR A = 1 TO 6
10 PRINT "X","1/(X-3)" 40 FOR B = 1 TO 3
20 PRINT
30 FOR N=-9 ro 15 STEP 3
40 IF N-3 = 0 THEN GOTO 80 Inner Loop
50 LET Y=1/(N-3) Outer Loop
60 PRINT N,Y 80 NEXT B
70 Garo 90
80 PRINT N,"INFINITY"
90 NEXT N 120 NEXT A
The final program in this section illustrates another way of having a To have a third loop correctly placed, it would have to be inside the B
variable loop size. The operator may use this program for any number (Inner) Loop, or outside the A (Outer) Loop.
of numbers between 1 and 100. A marker (in this case — 1) is set to Be careful to avoid crossing the loops:
indicate when the input is complete, allowing a jump out of the loop
10 FOR A = 1 TO 6
line 69). This is a `dummy value' — a value not normally entered.
( 20 FOR B = 1 TO 3
(N.B. DO NOT JUMP INTO THE MIDDLE OF A LOOP i.e. a
loop must always be entered from the FOR statement.)
70 FOR W= 1 TO 4
PRINT
TITLES
110 NEXT W
130 NEXT S
E E+1
10 REM *NESTED*
20 LPRINT "NAME"; TAE-: 6; "WEEK1
TAE 13; "WEEK"; TAL-. 20; "WEEK3
PRINT
TAL- 27;"WEEK4"
30 FOR 3=1 TO
N•'E
40 PRINT "INPUT _=ALESMAN3 NAME
50 INF'IlT N$
60 LF'R:INT N$;
70 FOR W=1 TO i 4
S0 F'RINT "TYPE WEEK "; W; " SALE
PRINT
BLANK
LINE
90 INPUT X
100 LF'RINT TAO (7*W- 1 ) ; X
110 NEXT W
120 LPR'INT
100 NEXT S
STOP
156 157
Exercises
• •
SECTION M: PLOTTING
159
1 MR
•
exactly the same way as on the ZX81, there is no UN PLOT statement
•
The variation from square on the screen is typically in a ratio between
on the Spectrum. To erase the dot again the OVER 1 facility is used. 1.1:1 and 1.2:1 (across screen/down screen). This means a `square'
Thus, to erase at X,Y you must enter a multiple statement line. that looks square will need to be 10 pixels across and either 11 or 12
OVER 1: PLOT X,Y – blanks out the pixel at co-ordinates X,Y pixels down.
Although it is perfectly possible to plot a horizontal line to the screen Most PLOTting is done utilising loops. To PLOT a circle we need
using a program similar to that used on the ZX81: to choose a suitable STEP value for a loop that runs either from 0 to
10 FOR N=0 TO 255 360 (degrees), or 0 to 2 PI (Radians). We also have to set a centre to
20 PLOT N,20 give us a circle where we want it, and a radius such that it will fit the
30 NEXT N screen. For a circle in degrees, code in this program:
it is far simpler on the Spectrum to use the following type of On the ZX81 On the Spectrum
formulation: 10 FOR D = 0 TO 360 STEP 10 10 FOR D = 0 TO 360 STEP 2
10 PLOT 0,20: DRAW 255,0 20 LET R = D*PI/180 20 LET R = D*PI/180
It is also possible to get some semblance of motion. The program below 30 LET X = 30 + 20* COS R 30 LET X = 120 + 80* COS R
moves a dot across the screen: 40 LET Y = 20 + 20* SIN R 40 LET Y = 80 + 80* SIN R
On the ZX81 On the Spectrum 50 PLOT X,Y 50 PLOT X,Y
10 FOR N = 0 TO 63 10 FOR N = 0 TO 255 60 NEXT D 60 NEXT D
20 UNPLOT N – 2,20 20 PLOT OVER 1; N – 2,20 Line 20 converts to radians, in which all the trigonometric functions of
30 PLOT N,20 30 PLOT N,20 the computer work. Line 30 calculates the horizontal component, and
40 NEXT N 40 NEXT N line 40 the vertical. The SIN and COS functions are multiplied by 20
(80 on the Spectrum) to give a radius of 20 pixels. The centre is set for
It is possible to construct simple shapes using PLOT. Here is a ZX81
the ZX81 at pixel 30, 20, and for the Spectrum at pixel 120, 80. In
routine to draw a (somewhat stylised) dog:
most cases, it is convenient to consider the PLOT screen to be 60 x 40
10 LET X=0 pixels (ZX81), rather than 64 x 44, in order to set scales and position
20 LET Y=10 plots on the screen, and 240 x 160 similarly for the Spectrum.
30 PLOT X,Y
40 PLOT X+1,Y-1 Having set the basic values, we can introduce variations within the
50 FOR N=2 TO 4 loop into the above program. We can calculate the radius value and get
60 PLOT X+2, Y-N a spiral plot. Alter the program to:
70 NEXT N
80 PLOT X+3,Y-2 For the ZX81 For the Spectrum
90 PLOT X+4,Y-2 10 FOR D = 0 TO 360 STEP 10 10 FOR D = 0 TO 360 STEP 2
100 FOR N=1 TO 4 20 LET Z = D*PI/180 20 LET Z = D*PI/180
110 PLOT X+5,Y-N
30 LET R = Z*3 30 LET R = Z* 10
120 NEXT N
130 PLOT X+6,Y 40 LET X = 30 + R*COS Z 40 LET X = 120 + R*COS Z
140 PLOT X+7,Y-1 50 LET Y = 20 + R*SIN Z 50 LET Y = 80 + R*SIN Z
60 PLOT X,Y 60 PLOT X,Y
It can sometimes be worth remembering that the PLOT pixels are not
70 NEXT D 70 NEXT D
exactly square. The visible variation from square will depend on the
type of plotting being done, and the particular TV screen in use. It is Calculating additional values, all within the loop, and using the loop
worth drawing what should be a square on the screen, and simply values as a basis, provides complex shapes fairly easily. Alter the first
measuring the variation with a ruler. Try running this program, and three lines of the program:
do this for different areas on the screen, so that you can check if the For the ZX81 For the Spectrum
variation is constant. Note the double loop, which is often useful in 10 FOR D = 0 TO 360 STEP 5 10 FOR D = 0 TO 360
PLOT routines. 20 LET Z = D*PI/180 20 LET Z = D*PI/180
On the ZX81 On the Spectrum 30 LET R = 20*SIN(Z*4) 30 LET R = 60*SIN(Z*4)
10 FOR F = 10 TO 30 10 FOR F = 10 TO 100
20 FOR L = 10 TO 30 20 FOR L = 10 TO 100
RUN it. From a simple circle, we now have the basis for a polar graph
30 PLOT F,L 30 PLOT F,L
plot and can identify a scale of values for PLOTting that will fit the
40 NEXT L 40 NEXT L
screen. Similarly using parametric equations for the ellipse on the
50 NEXT F 50 NEXT F
ZX81, X goes from 10 to 50 as COS goes from – 1 to 1 and Y from 10
1 Fn 161
•
to 30 as SIN goes from – 1 to 1 round the circle. Notice this uses
•
10 REM "HISTO"
20 DI.M M(12)
radians directly (2*PI radians = 360 degrees). Spectrum plot points are 30 LET 'Z=0
40 FOR N=1 TO 12
multiplied by 4. 50 INPUT M(N)
For the ZX81 60 IF M(N) > Z THEN LET Z =M(N)
70 NEXT( N
10 FOR N = 0 TO 2*PI STEP PI/20 80 REM **PLOT**
20 PLOT 30 + 20*COS N, 20 + 10*SIN N 90 FOR N=1 TO 12
30 NEXT N 10 PRINT N;'TAB 4;
110FOR L=1 TO :M(N) STEP Z/25
120 PRINT "*";
For the Spectrum 130 NEXT L
10 FOR N = 0 TO 2*PI STEP PI/180 140 PRINT
20 PLOT 120 + 80*COS N, 80+40*SIN N 150 NEXT N
30 NEXT N Result:
Try altering the multiplication factors in line 20 for different ellipses. 1 *** *** * ***
20 PLOT X, X*X/100 20 PLOT X, X*X/400 reproduced here for both the ZX81 and Spectrum.
the highest value for the Y pixel would be 36 on the ZX81, which
makes use of most of the screen. (For the Spectrum it would be 144.) In
most cases, however, it is not so easy to see what the scale factors
should be. We have a 44 x 64 screen to use on the ZX81 and a
256 x 176 screen on the Spectrum, and so in general, for positive values
only, suitable scale factors are given by:
ZX81 Spectrum
63 255
Largest value of X Largest value of X
43 175
Largest value for Y Largest value for Y
165
• •
THE ZX81 PRINT AND THE SPECTRUM PRINT&
PLOT SCREEN PLOT SCREEN
You cannot PRINT or PLOT
— on the bottom two lines.
4— Lines _ You cannot normally PRINT or PLOT
m vl A W c^ on the bottom two lines
o
C
3
VI
rn
IMEMINNEIMMUMMUMM
oximinnimmmonmmunmmul
I UHIIIIIIIIHIIIIIIIII
mumummmummumumn
vi LT,
0 NO m
"8 N m N
o A m ô `5' `8)-'m ô
0 8 16 24
^ ^ u In o m ,^^ ^
u ^ ^ <o ^ io , û in o t w°
7 15 23 31
31 40 48 56 64 72 50 88 96 104 112 120 128 136 144 152 160 168
39 47 55 63 71 79 87 95 103 1II 119 127 135 143 151 159 167 175
Pixel y-coordinates ---C Pixel y coordinates
166
17
^ •
SECTION N: SUBROUTINES
It is useful, when both PRINTing and PLOTting on the screen, to
work with one screen grid first, and then add the other grid. As an
N1: Subroutines
example, consider graph titles. We could, to get a title for a printout of
a graph, use a direct command: PRINT "GRAPH OF
A subroutine in BASIC is a program module performing an allotted
Y = X**2/100", then use COPY, BREAK the COPY routine after the
task and is entered using a GOSUB statement. The section of program
first lines printed, then PLOT the graph with our program and COPY
is completed and exited by a RETURN statement which sends the
that, but it's not very elegant. We want the title on the screen with the
computer back to the line following the GOSUB statement. A
plotted graph. We can first set the PLOT routine, for example:
subroutine must only be entered via a GOSUB statement and exited by
a RETURN statement.
ZX81 Spectrum
Two instructions arc used to create subroutines.
10 FOR N = 0 TO 60 10 FOR N = 0 T0 250 GOSUB (line number) – transfers control to the specified line
20 PLOT N, N*N/100 20 PLOT N, N*N/400 number
30 NEXT N 30 NEXT N RETURN – leaves subroutine and returns
control to the line immediately after
By inspection, after RUNning the routine, we can add a title where it
the GOSUB instruction which
will not interfere with the PLOT.
transferred control to the subroutine.
40 PRINT AT 0, 3; "2" Spectrum users have probably noted that their machine prints GO
50 PRINT AT 1,0; "Y = X /100 SUB with a space.
Here is an example of the program structure for these instructions:
This gives us a screen with everything on it, with the bonus of using
standard notation for X I , not the BASIC's * * (Ton Spectrum)
100 ...
notation. A different function might require the PRINTed strings to be
placed elsewhere.
110 GOSUB 500 (1)
Of• 120 ...
130 ...
Exercise
140 GOTO 600
500 REM *SUBROUTINE*
Write a program that will calculate the pixel co-ordinates of any
(3) 510 ...
PRINT square (character cell). Input L and C (for Line and Column), (4)
520 ...
with suitable prompts erased by an empty string, and output
530 ...
"Pixel";X;",";Y;"is top right", etc. For the ZX81, output the four 540 RETURN
pixels in any specified character cell. For the Spectrum, output the 600 STOP
X,Y co-ordinates of the four corner pixels.
169
168
•
procedures and may be
•
100 PRINT " AREA IS ";Z
110 GOTO 300
Subroutines are often used for repeated
120 REM *MUST NOT ENTER A SUBROUTINE
thought of as separate program structures: EXCEPT BY A GOSUB*
200 REM **SUBROUTINE TO CORRECT
SUBROUTINE TO
T40 DECIMAL PLACES**
MAIN ROUTINE 210 LET Z=INT (100*(Z+.005))
100 NE * 220 LET Z=Z/100
500 REM * SUBROUTI
110 GOSUB 500 230 NNE'ruRN
E--- 510 240 **END OF SUBROUTINE**
120 300 REM **END OF PRJGRAM**
520
130 530 REM * END OF SUBROUTIN E *
140 GOSUB 500 —T The second example is a program to evaluate the sum of the series
150 4— 540 RETURN 1 + 1/2! + 1/3! + .. + 1/10! to 6 decimal places. (The exclamation
160 mark (!) means `factorial'. Factorial 5 (5!) is 5x4 x 3 x 2x 1, etc.).
the GOSUB In this program there are two separate subroutines. The subroutines
The computer stores the line number of nstruction are both entered repeatedly. The first is to evaluate the factorial and
The RE
(whereas it doesn't with a GOTO). lates GOSUB the second corrects the answer to 6 decimal places. Although it is not
lin
transfer
sh enterhar subroutine repeatedly
the essential to use subroutines in such a program it does improve the
sho above, means we structure and make it considerably easier to follow the sequence of
course of a program. operations.
Results on screen:
to have line 110, which prevents the subroutine being
It is essential complete.
entered accidentally when the calculation is 1 TH TERM IS
2 TH TERM IS .5
10 REM "CIRCLE" 3 TH TERM :.1666666
20 PRINT "TYPE RADIUS" 4 TH TERM IS .041666666
30 INPUT R 5 TH TERM IS .0083333333
40 LET C=2*PI*R 6 TH TERM IS .0013888889
45 LET Z=C 7 TH TERM IS .0001964127
50 GOSUB 200 8 TH TERM IS .000024801587
";'L
60 PRINT "CIRCUMFERENCE IS [ T Spectrum! 9 TH TERM IS 2.7557319E -6
70 LET A=PI*R**2 10 TH TERM IS 2.7557319E -7
80 LET Z=A SUM OF SERIES 1.7182862
90 GOSUB 200
171
• (1)
•
Subroutine 1 is called at line 30.
Trace the program through for the first two terms to ensure that you
Enter first subroutine at line 300.
can follow the flow. (2) Start executing first subroutine.
(3) Subroutine 2 is called at line 320.
N3: Nested Subroutines Enter second subroutine at line 400.
(4) Execute second subroutine.
This technique is similar to nested loops in that a subroutine is entered (5) RETURN at line 420 returns program to line 330 (line
from another subroutine. following GOSUB call).
In the simple example given the program enters the First subroutine (6) Continue execution of first subroutine.
(line 300) and from within this calls up the second subroutine (line 320 (7) RETURN at line 340 returns program to line 40 (line following
calls up subroutine at line 400) which is completed and returns (line GOSUB call).
420) to the first subroutine which is then completed. See the diagram (8) Statement to avoid entering subroutines accidentally.
below of the program flow. The second example is typical of a computer games program. The
Hand trace this program to discover the result of running it. (N.B. nested subroutine ensures that the computer's move is printed out each
This program is only used to illustrate nested subroutines and the time before the player makes his move.
calculation carried out clearly can be done more easily without their
10 REM "NESTSUB"
use.) 20 REM **PART OF GAMES PROS**
30 LET X=3
10 REM "SUBROU'rINE1" 40 GOSUB 600
20 LET M=5 45 PRINT
30 GOSUB 300 50 PRINT "YOUR MOVE WAS ";M
40 PRINT M 60 PRINT "COMPUTERS MOVE ";X
50 GOTO 500 70 STOP
300 REM ****1ST SUBROUTINE**** 600 REM **SUBROUTINE PLAYER**
310 LET M=M+1 610 GOSUB 700
320 GOSUB 400 620 PRINT "YOUR MOVE?"
330 REM **RETURN TO MAIN PROGRAM** 630 INPUT M
340 RETURN 640 RETURN
350 REM 700 REM **SUBROUTINE CGMPUTER**
400 REM ****2ND SUBROUTINE**** 710 PRINT "COMPUTERS MOVE ";X
410 LET M=M* (M+1) **2 [ T Spectrum] 720 RETURN
"20 RETURN
430 REM Note that it would make no difference if the nested (called from a
500 PRINT "END OF PROGRAM"
subroutine) subroutine were to start at a lower line number than the
The diagram illustrates the procedure in the above program for two subroutine which called it. Subroutines are always discrete program
modules, wherever they are located in a program.
nested subroutines.
30 GOSUB 300
N4: Recursive Subroutines
^ 40 ....
50 GOTO 500
A recursive subroutine is a subroutine that calls itself. This facility is
(7) 300
not available in some versions of BASIC used on other computers. For
310
some purposes this can be a very useful program structure. From
r
320 GOSUB 400 within a subroutine, a GOSUB instruction is used to transfer control so
330 1:6) that the program re-enters the subroutine. The computer stores each
340 RETURN (3) GOSUB call, with the line number to RETURN to, just as if the
GOSUB call had been made to a different subroutine. The RETURN
350 •
instructions are executed in reverse sequence to the order in which the
(s) 400
GOSUB instructions were encountered.
410
The example program below evaluates the factorial of any number
420 RETURN
N, input as an integer less than 30. First the program, then the
430 explanation:
500 ....
173
172
10 REM "RECSUE-"
• 3
•
20 PRINT "TYPE NUMEER{30" GOSUB CALL 2
30 INPUT N N=2
40 IF N>30 THEN LOTO 200
50 GOSi iE 100 GOSUB CALL 3
60 PRINT F N=1
70 LOTO 210 RETURN CALL 3
80 REM F=2
90 REM ******************
100 REM ****SUERUUTINE**** N=2
110 IF N < 1 THEN '3i'TO 140 RETURN CALL 2
120 LET F=1 F=6
130 LOTO 180
N=3
140 LET N=N-1
150 GO SUE 100 RETURN TO MAIN PROGRAM
160 LET F=F*(N+1) 6
170 LET N=N+1
180 RETURN
185 REM ****END'=UE** If we draw up a trace using the data from this display (as below), we
190 REM will see that the GOSUB at line 150 is executed for each value of N from
200 PRINT "OBEY IN3TRUCTIONS. PP
E_=; RUN AND NEWLINE/ENTER.' 1 to N. The RETURN calls are then made for each value from 1 to N,
210 REM **END** calculating F each time (line 160) and incrementing N (line 170),
so
To help us decipher the program flow, we can insert PRINT that the value of factorial N is calculated as 1 x 2 x 3... x N. The
statements and add a counter, in order to code the GOSUB and flowchart of this program is quite simple, but the algorithm is not clear
RETURN instructions with a number to indicate the sequence in unless the sequence of GOSUB and RETURN calls is understood.
which the recursive calls are performed. Add the following lines to the The computer stores each GOSUB call in sequence in a portion of
memory called the GOSUB stack, and each RETURN instruction
program:
removes one of these stored GOSUBs, passing control to the line after
5 LET C=0 (sets counter to count
the GOSUB call. Confusion is possible with recursive subroutines
GOSUB calls) because the RETURN S are made to the same program line each time
35 PRINT N (prints first value of N) (line 160 in this case).
45 LETC=C+1 (first GOSUB call from main
program)
55 PRINT "RETURN TO MAIN "RECSUB" — Trace for N = 3:
PROGRAM" (final RETURN executed)
145 LETC=C+1 (increments counter each 50 GOSUB(1)
time GOSUB is used 60
recursively) 100 N=3 -ii•N =2 N=1
146 PRINT "GOSUB CALL ";C (prints each time GOSUB is 110 F= I
used recursively) 120
(value of N before each 130
147 PRINT "N = ";N
140 N W 2 N=l
recursive GOSUB call)
150 GOSUB(2) GOSUB(3)
155 PRINT"RETURN CALL ";C (prints each RETURN call as
160 F=1 . 2
made, corresponding to the 2"3
170
GOSUB call of the same N,2 N=3
180 r
number) RETURN(3) RETURN(2) RETURN(1) - (To main program)
Then run the program for N = 3. The resulting `machine trace' screen
display is:
174 175
Flowchart — "RECSUB"
• •
Notice that line 130 passes control to the RETURN statement of line
180. Check for yourself that line 130 could be a RETURN instruction
and the program would still run correctly. This is likely to result in a
less visible flow in the program, however.
The next program has a subroutine (starting at line 100) which calls
itself in line 150. As for the previous program, insert suitable PRINT
statements to print out the values of the variables and the number of
GOSUB calls made. Hand trace the program for suitable integers, e.g.
15 and 25. The program evaluates the highest common factor of the
two numbers input. Note that in this case there are no processing
statements between the GOSUB call in line 150 and the RETURN
instruction of line 160. The sequence of RETURNs will be executed
by control going repeatedly to line 160 (the line after the GOSUB call),
which does the next RETURN, until the last stored GOSUB is
encountered, which will pass control back to line 50 of the main
program.
5 REM "HCF"
10 PRINT "TYPE 'IWO POSITIVE INTEGERS"
20 INPUT M
30 INPUT N
40 GOSUB 100
50 PRINT " ANSWER IS"; P
60 GOTO 220
100 REM **SUBROUTINE**
110 LET P=N
120 LET Nt-N*INT (M/N)
130 LET M=P
140 IF N=0 THEN GOTO 160
150 GOSUB 100
160 RETURN
200 REM **ENDSUB**
210 REM
220 REM **END**
176 177
100
110
200
PRINT "FIRST SUBROUTINE"
RETURN
PRINT "SECOND SUBROUTINE"
•
100 PRINT "**************.,
110 PRINT " SUBROUTINE ONE"
120 PRINT "** * * * * ***,,
210 RETURN 130 RETURN
200 PRINT "** * * * * ***,,
210 PRINT " SUBROUTINE TWO"
2) 10 REM *NESTED SUBS FOR MENU**
220 PRINT "**************"
20 REM **INITIALISE MENU GOSUB**
230 RETURN
30 LET MENU=1000
40 REM **MAIN PROGRAM**
50 PRINT "MAIN PROGRAM"
Spectrum users should replace line 20 with
60 REM ..
70 PRINT "NOW TO MENU" 20 PAUSE 0
80 PRINT
90 GOSUB MENU N6: Subroutine Use: Example
100 PRINT "MORE MAIN PROGRAM"
110 PRINT "MENU OR END PROGRAM?"
120 PRINT "INPUT M OR E" As an example of the use of subroutines, here is a guess-the-number
130 INPUT N$
game. The program has three subroutines, one to get the number (lines
140 IF N$="M " THEN GJSUB MENU
150 GOTO 9999 150 – 190), one to check the guess (lines 210 – 300), and one for the
1000 PRINT TAB 3;"MENU" success message (lines 350 – 410), which sets the marker MARK to tell
1010 PRINT „"1. OPTION 1"„"2.
the main program, which is the loop between lines 50 and 140,
OPTION 2"
1020 PRINT "INPUT 1 OR 2” whether the number N (computer's number) is the same as G (the
1030 INPUT M player's guess). This defines whether the success subroutine has been
1040 GOSUB (M*1000)+100 called as a result of the conditional test in line 110.
1050 RETURN
1100 REM ****SUB 1******
1110 REM *************** 5 REM. "GUESSNLIM"
1120 PRINT "SUB 1 COMPLETED" 10 LET MARK=O
1130 PRINT 20 LET TRIES
1140 RETURN 20 PRINT "GUESS MY NUMBER. ",17
2100 REM ****SUB 2****** "NUMBER IS BETWEEN 1 AND 9'-"
2110 REM *************** 25 REM ** GET NUMBER: **
2120 PRINT "SUB 2 COMPLETED" 40 GO:;IIE: 150
2130 PRINT 50 LE- TRIE'-.=TRIE•_ +1
2140 RETURN 60 PRINT „'ENTES: YOUR GUESS"
9999 STOP TO INPUT G
_;0 LL•_
Notice the use of a variable ("MENU") to hold the line number 85 REM ** GOSUB CHECK **
(1000) of the Menu subroutine (Lines 20 and 30). This technique can 90 GOSUB 200
100 REM ** GOSUB SUCCESS **
be useful as a mnemonic in longer programs, and can help the user 110 IF RIFF=O THEN GOSUB 250
identify which program module has been called. 120 REM ** CHECK MARK **
120 IF MARK=1 THEN GOTO 500
This technique can be combined with the use of INKEY$ to give an
135 REM ** LOOP BACK **
instantaneous jump to the required subroutine. The program waits for 140 GOTO 50
a key to be pressed and then jumps to the required subroutine.
150 REM **********************
10 PRINT "PRESS 1 FOR SUB 160 REM ** GET NUMBER SUE' **
PRESS 2 FOR SUB 2"
165 REM **********************
170 LE T N= INT ( RND *99)41
20 IF INKEY$=" " THEN GOTO 20
ISO RETURN
30 LET A$=INKEY$
35 IF A$="1 " OR A$="2 " THEN GO
TO 60
190 REM ** END_:_IL-: **
40 PRINT "KEYS 1 OR 2 ONLY PLE
1 95 REM ************* *** ******
200 REM
ASE"
205 REM **********************
50 GOTO 10
210 REM ** CHECK SUE' *.*.
60 GOSUB VAL A$*100
220 REM *******+ I**************
70 PRINT "BACK TO MENU" 230 LET RIFF= AE:S (G--N)
80 GOTO 10
240 IF DIFF750 THEN PRIN T .,"FF,
EEZING"
178
179
250 IF DIFF`25 AND DIFF50 Module 3 (GET NUMBER Subroutine):
HEN PRINT „"CO D"
260 IF LIFT>10 AND RIFF !_' 25 T 1. Define random number 1 — 99 as number N
HEN FRINT ,,"*WARM*" 2. Return
270 IF DIFF:4 AND DIFF '0 TH
EN PRINT , , " ** HOT ** " Module 4 (CHECK Subroutine):
280 IF DIFF`O AND DIFF 4 THE 1. Set variable DIFF equal to ABS difference of guess and number
N PRINT ,," ** *BOILING* ** "
290 RETURN 2. Check value of DIFF, print appropriate message
3. Return
300 REM ** END CHECK_t E **
310 RFM ******* *************** Module 5 (SUCCESS Subroutine):
:320 REM 1. Print success message, number of guesses made
340 REM **********************
350 REM ** SUCCESS SUB ** 2. Set MARK equal to 1
360 REM ********************** 3. Return
370 PRINT AT 5,5;"$$$$$4$$2$$";
TAB 5;"$ SUC=ES_- $"; TAD 5;"$$$ Module 6 (END/RERUN module):
$$$$$$$$" 1. Print prompt for input
380 PRINT AT 10,5;"IT TOOK ;TR
IES;" TRIES. " 2. Input response to Another go? (A$)
: 390 LET MARI:::, 3. If replay required (A$ = "Y") then GOTO Module 1,3
400 RETURN 4. If A$ not "Y" then print end message
410 REM ** END ':UCCEE=< SUB ** 5. Stop
420 REM *************** * ******
430 REM Notice that (although this is a program that has been modularised
430 REM ********************** rather artificially to demonstrate the principles in a short program) the
490 REM ** END/RERUN MOD **
495 REM ************ *** * * **** * program consists of an introductory section, then a main program loop
500 PRINT ,,"ANOTHER 00? INPUT with both conditional and unconditional calls to subroutines, within a
Y OR N" short main program loop. This makes the structure of the program
510 INPUT 4$
clear, and minimises the use of GOTO statements, which would be
520 CL=:
530 IF 4$="Y" T HE N OOTO 40 required in profusion if the program were written in a linear, rather
540 PRINT , , "OK:, BYE" than modular fashion. It is perfectly possible to write the program in
550 =TOP
this linear manner, but the structure will not be as visible.
550 REM ** ** END ** ** You should also note that the END/RERUN module is not a
subroutine, but uses GOTO to pass control to this section from the
main program, with a conditional GOTO to pass control back to the
The structure of the program is thus: main program if required. Conditional GOTOs are preferable
Module 1: program structures to unconditional GOTOs, and whilst the END
1. Initialise success marker MARK and variable to store number module could be a subroutine, RETURNing to the main program
of guesses made (TRIES) loop, further conditions would need to be inserted to pass control to
2. Print Instructions Module 1 for a new number to be defined. The subroutine would also
3. Call GET NUMBER Subroutine need to be exited by a GOTO for the program to stop. There is another
solution, however, involving a nested subroutine, which we will set as
Module 2 (Main program loop): an exercise.
1. Increment TRIES
2. Input guess Exercises
3. Call CHECK Subroutine
4. Check if Guess equals Number. If it is, then call SUCCESS 1 Rewrite "GUESSNUM" with the END/RERUN module as a
Subroutine subroutine. The procedure should be as follows:
5. Check marker. If Success subroutine has been called
(MARK = 1), then GOTO END/RERUN module END/RERUN SUB
6. Loop back to Input guess again (1) Prompt for player input, and get response, as before.
180
181
• •
ii. If RERUN not required, bypass 3 and 4 below, by a GOTO
the RETURN line.
iii. GOSUB to GETNUMBER subroutine. This is a nested
subroutine. The new value of N will be set by this operation.
iv. Re-initialise TRIES as 0 and MARK as 0.
v. Return. PART THREE
The main program loop is then returned to. The main program
must then test whether it is to exit (rerun not required) or
A DVANCED BASIC PROGRAMMING
continue (new game started). We could set another marker to
test this, but in effect we have done this by re-setting MARK if a
rerun is required.
Rewrite the main program loop, so that on return from the
END/RERUN subroutine, the program loops back only if
MARK = 0. If MARK = 1 then the program will not loop back
and you can either insert a GOTO to bypass all the subroutines
to an end program procedure, or STOP the program before the
subroutines.
2 Insert an additional subroutine which prints 1;"ST",2;
"ND",3;"RD", and then "TH" for other numbers into the
"FACTORS" program (Unit N2).
3 Write a program which determines how many rolls of a die are
required to produce a total score greater than 100. Use
subroutines to produce the random numbers for the die rolls and
to print out the results.
4 Let the computer choose a four digit number with no two digits
alike. You try to guess the number chosen. The computer
indicates H (too high), L (too low) or R (right) for each digit in
turn and determines how many guesses are required to get the
correct number. Use subroutines to create the number, input
the operator's guess and give the response to each guess.
• SECTION 0: PROGRAMMING METHODS II
01: Résumé
WHAT'S NEXT?
186 187
•
flowchart structured into modules, i.e. flowchart groups for the
modules in the program.
DESIGNING PROGRAM LAYOUT
•
Take care with the control structures and avoid unnecessary You must make your program readable. The program design will be
branching, especially with GOTO instructions. Try to make your modular and contain specific identifiable segments, subroutines and
programs both readable and efficient - but first make them readable! modules. These should be labelled in the design of the algorithm and
transferred in the coding process.
USER FRIENDLY PROGRAMS (1) EACH MODULE SHOULD BE TITLED AND LABELLED
TO INDICATE ITS FUNCTION. FOR EXAMPLE:
Design your programs with the user in mind - and that includes you! 10 REM "AVERAGE"
Directions to users should be concise and as few as is necessary, both in 20 REM * PROGRAM AVERAGES ANY NUMBERS
the program and in the user guide if your program is large enough to INPUT *
merit one. 30 REM *
Where the user needs a number of instructions to operate the 40 REM * USER ROUTINE *
program then these can be built into an optional `help' module or 50 REM * CHOICE OF NUMBERS INPUT *
subroutine. 60 PRINT "HOW MANY NUMBERS DO YOU WISH
100 REM * USER INSTRUCTION * TO AVERAGE"
110 REM * DIRECTS USER TO HELP SUBROUTINE * 70 INPUT N
120 PRINT " FOR INSTRUCTIONS TYPE HELP 80 DIM A(N)
OTHERWISE TYPE C " 90 REM * INPUT ROUTINE *
130 INPUT A$ 100 REM * NUMBERS INPUT TO ARRAY *
140 IF A$ = "HELP"THEN GOSUB 1000 110 PRINT "INPUT NUMBERS"
150 REM * END USER INST * 120 FOR I = 1 TO N
130 INPUT A(I)
1000 REM * HELP SUBROUTINE * 140 NEXT I
150 REM
160 REM * PROCESSING ROUTINE *
1200 RETURN 170 REM * COMPUTES AVERAGE *
1210 REM * END HELP * 180 e LET SUM =
Users usually require to know: 190 FOR J = 1 TO N
- how to run the program 200 LET SUM = SUM + AU)
- what form of input data is required 210 NEXT J
- what output is produced 220 LET AVERAGE = SUM/N
Your program should check on the range and type of input data. If the 230 REM
input data is out of range or incorrect the program should not stop with 240 REM * OUTPUT ROUTINE *
an error, but continue with a message to input correct data. 250 PRINT "THE AVERAGE OF"
After you have designed a program to do a specific task it may be 260 FOR K = 1 TO N
worthwhile to change it to be as general as possible - i.e. do several 270 PRINT A(K);" ";
similar tasks. As you become more skilled and confident in 280 NEXT K
programming you will be able to generalise and write a subroutine that 290 PRINT "IS "; AVERAGE
enables users to select options from a menu. This is exactly similar to 300 REM
the exercise you have seen in multiple decision structures. See the 310 REM * END AVERAGE *
"CASSFILE" program in Section V, for a "menu-driven" program. (2) DESIGN YOUR PROGRAM SO THAT RELATED
More "user-friendly" tips are given in the section on documentation, STATEMENTS ARE TOGETHER
and some useful routines in Unit V2.
For example, input - processing - output statements:
(i) All input statements will be at the beginning of a simple
sequential program, processing in the middle, and
output normally at the end.
188 189
^
(ii) For a modular program, input, processing and output Indented statements are not possible on the ZX81 or Spectrum,
routines will be separate modules or groups of statements unfortunately!
within a single module.
(iii) Subroutine modules will usually be placed separately at
DESIGNING PROGRAM OUTPUT
the end of a program.
(3) INSERT REM STATEMENTS BETWEEN PROGRAM For the user the output is the most important part of the program.
MODULES AS SEPARATORS Take time planning it. The output instructions in Sinclair BASIC are:
Program modules are then easily identified. Use blank REM PRINT, PRINT AT, PLOT, LPRINT, COPY, TAB, plus graphics
lines or lines of asterisks. commands.
(t) RESULTS SHOULD BE OUTPUT WITH RELATED
(4) PLAN YOUR PROGRAM LAYOUT BEFORE CODING TEXT.
The printed listing of your program is important. Choose a Label all your numerical output:
maximum line width. Break longer lines into shorter ones in e. g. I YEAR) 1974 I NET INCOME' £5678.65
REM statements by using spaces. Compensate for overrun. For instead of 1974 5678.65
example: e.g. AVERAGE AGE OF BOYS IS 15 YRS 3 MONTHS
10 REM * AAAAA rather than 15 3
AAAAA
AAAAA * (ii) DISPLAY LARGE AMOUNTS OF OUTPUT AS A TABLE,
HISTOGRAM OR GRAPH, AND GIVE TITLES.
You will not be able to do this with other BASIC statement lines.
For example:
(5) YOUR LAYOUT SHOULD TRY TO REFLECT THE
MODULAR STRUCTURE OF YOUR PROGRAM TABLE 1: NET INCOME FOR B. JONES
FOR YEARS 1978-80
190 191
NUMBERS
• •
40 LET OUTPUT DATA = 3000
15.003 50 REM * END MODULE ASSIGN *
815.231 60 REM
– 4.000 70 REM * MAIN *
– 100.100 80 GOTO INPUT DATA
Fill in with zeros to get decimal placing correct. 90 GOSUB PROCESSING
(v) USE SPACE CAREFULLY 100 GOTO OUTPUT DATA
Sinclair computers use expensive printer paper! Print output 110 STOP
horizontally wherever possible. For example:
TABLE OF POWERS OF 2 1000 REM * INPUT DATA MOD *
2
4
8 1500 GOTO 90
16 1600 REM * END INPUT *
32 etc 2000 REM * PROCESSING SUBROUTINE *
should be:
2500 RETURN
TABLE OF POWERS OF 2 2600 REM * END PROCESSING *
2 4 8 16 32 3000 REM * OUTPUT DATA MOD *
64 128 256 512 1024
3500 GOTO 110
DO NOT OVERDO EXPLANATIONS 3600 REM * END OUTPUT MOD *
Be succinct! 4000 REM * END PROG.*
MAKE YOUR ABBREVIATIONS CLEAR
x = 25
NDTC = 25 There are good reasons for modular design and the use of subroutines
NUMBER OF DAYS TO CHRISTMAS = 25 and sub-program modules. The logic of the program, i.e. its flow, is
DISPLAY INPUT DATA AS AN OPTION easier to follow. The clarity of the structure of the main program is
Allow checking of input data before processing. improved whilst program design is proceeding by referring to the
Make your program check for incorrect or bad input data. number or name of the module initially, instead of starting to write out
the code of the module at that point. The module can be coded as a
separate entity.
MODULAR DESIGN
Independent testing of modules is possible, but care must be taken
We break problems down into sequences of steps to produce programs that all variables have been declared and have their correct values at
in which different kinds of activities are separated out. These the start of the module. Debugging is simpler with this approach, since
distinctive program modules are our SUBROUTINES or SUB- the module is isolated. You can leave the coding of a module until a
PROGRAMS. Each module has its own name and address, but in later stage, but you must know what it will do when coded.
BASIC we usually refer to program modules by address only, as with: If a module has to be used several times in a program from different
GOTO 100 and GOSUB 3300 places it need only be written once and called (into action) from these
where the address is the line number of the first statement in the points by reference to its line number or name.
module.
We can address sub-programs or modules by name by assigning the
name and address of the module at the start of the program. For
example:
10 REM * ASSIGN MODULE NAMES *
Yi
20 LET INPUT DATA = 1000
30 LET PROCESSING = 2000
192 193
This structure is convenient for longer, more complicated, programs
Program modules can be designed to run sequentially: with many modules and nestings.
START Subroutines automatically return to the next line in the main program
through the RETURN statement. Other modules are called by GOTO
(line number) and return by GOTO (line number) instructions.
GOTO MUST BE USED WITH THOUGHT AND CARE AND
NOT EXCESSIVELY. Use a GOSUB unless a return to a different
point in the main module is needed or a multiple return is possible as a
result of a decision to be made within the module.
Nested modules can be treated as other modules and called from
within the subroutine or sub-program, by GOSUB and GOTO
instructions. Nested loops must be contained within the same module,
however.
A) Decision Structures
(i) Single decision
IF-THEN structure
(ii) Double decision
IF-THEN-else structure
iii) Multiple decision
Case structure
195
^ •
B) Loop Structures (ii) DOUBLE DECISION: The IF-THEN-else structure
Meaning: IF (condition is true) THEN (do something)
(i) repeat-forever loop structure otherwise (if condition is false) do something else.
(ii) repeat-until structure
(iii) while-do structure Pseudocode Flowchart
(iv) FOR-NEXT structure
The names of the structures are implemented as actual
programming language structures in other languages and some
forms of BASIC. The FOR-NEXT structure is a special form of
the while-do loop, given a specific implementation in BASIC.
A. DECISION STRUCTURES
mod
(i) SINGLE DECISION: The IF-THEN structure if (cond)
Meaning: IF (condition is true) THEN (do something) then P1
else P2
Flowchart endif
Pseudocode
endmod
mod
if (condition)
then P
endif
endmod BASIC
I0 REM*START MOD*
20 IF (COND) THEN GOTO 50
30 (FALSE TASK P2)
40 GO TO 60
50 (TRUE TASK P1)
60 REM*ENDMOD*
BASIC
10 REM*START MOD*
20 IF (COND) THEN P
30 REM* ENDMOD* To perform the true task (P1 in the pseudocode) first, the BASIC
implementation of the structure would test the complement of
Example the condition, so that in the program below, for example, A>B
Input a number and if it is positive, print it. would be replaced by A<B, and lines 50 and 70 swapped. Note
BASIC the standard form of complement would be B< = A, but we have
Pseudocode
10 REM*START MOD* defined the input numbers as unequal in this case.
mod
input A 20 INPUT A
ifA>0 30 IF A > 0 THEN PRINT A
then print A 40 REM*END MOD*
endif
endmod
IqF 197
Example
•
Input two unequal numbers and print the largest.
BASIC
•
ltd i<Livi'S . I AR I MUD"
20 IF CI THEN P1
Pseudocode BASIC 30 IF C2 THEN 1'2
40 IF C3 THEN P3
mod 10 REM*STARTMOD*
50 REM*ENDMOD*
input A,B 20 INPUT A
if A > B 30 INPUT
Example
then print A 40 IF A > B THEN GOTO 70
else print B 50 PRINT B
60 GOTO 80 Test whether a number input is positive, zero, or negative, and
endif
print tlhe result.
endmod 70 PRINT A
80 REM*ENDMOD*
Pseudocode Flowchart
(iii) MULTIPLE DECISION STRUCTURE: The case structure
198
199
•
This structure is for demonstration only. Avoid using it in
BASIC
programs! It can sometimes occur in error. Use BREAK if you
10 REM*STARTMOD* suspect your program has entered such a loop (because nothing
20 INPUT A happens).
30 IF A < 0 THEN PRINT "NEGATIVE"
40 IF A = 0 THEN PRINT "ZERO" (ii) The repeat — until loop
50 IF A > 0 THEN PRINT "POSITIVE"
60 REM*ENDMOD* Meaning: Repeat processing until a condition is true.
These structures loop until a specific termination condition is
Alternatively, we can use conditional and unconditional GOTO
met, for example until a counter reaches a certain value or until
statements to implement this structure. This would be
a dummy or sentinel value is input. The important characteristic
appropriate if the processing section of a program after the
of this loop structure is that the repeat test (or exit test) is at the
decision were several statements long, rather than the single
bottom of the loop, after the processing `body'. The program
instruction available on the ZX81. Spectrum users can add more
lines making up the body of the loop (P) will be executed at least
instructions on the same line. They should be restrained in using
once. The repeat condition can use any conditional operator or
this facility. its complement (reverse).
e.g. equals 4 7 not equal
10 REM*STARTMOD*
<>
20 INPUT A Use of the complement often leads to a more elegant program.
30 IF A < 0 THEN GOTO 60
40 IF A = 0 THEN GOTO 80
Pseudocode Flowchart
50 IF A > 0 THEN GOTO 100
60 PRINT "NEGATIVE"
70 GOTO 110
80 PRINT "ZERO"
90 GOTO 110
100 PRINT "POSITIVE" mod
110 REM*ENDMOD* repeat
P
B. LOOP STRUCTURES until (condition is true)
endmod
(i) The repeal —forever loop
201
BASIC using complement
• Complement Version
•
10 REM*STARTMOD*
10 REM*STARTMOD* 20 INPUT AS
20 P 30 PRINT A$
30 IF (COMP COND) THEN GOTO 20
40 IF A$<>"LAST" THEN GOTO 20
40 REM*ENDMOD* 50 REM *ENDMOD*
Exit requires no specific instruction.
(iii) While – do structure
Example
Meaning: While a condition holds (TRUE) keep repeating the
Input and print strings until the sentinel value "LAST" is
process until the condition is broken (FALSE).
input. The condition can be, for example, that a loop-counter
variable value is not equal to its final value (IF N<10 THEN..).
Flowchart The process will then repeat until it is. The condition may also
Pseudocode
be set so that a sentinel value has not occurred (IF N<>6
THEN). These conditions are set so that the true pathway is the
process task, and the false is the exit.
The While – do loop is characterised by having the repeat test
carried out prior to the body of the loop (i.e. at the top). No
processing will happen if the repeat test is false at the first
encounter, i.e. the body of the loop is never entered.
mod
repeat Pseudocode Flowchart
input A$
print A$
until A$ = LAST
endmod
mod
while (condition is true)
do P
endwhile
endmod
BASIC
10 REM*STARTMOD*
BASIC 20 IF (COND) THEN GOTO 40
10 REM*STARTMOD* 30 GOTO 60
20 INPUT A$ 40 P
30 PRINT A$ 50 GOTO 20
40 IF A$ _ "LAST" THEN GOTO 60 60 REM*ENDMOD*
50 GOTO 20
60 REM*ENDMOD*
9(19
203
^
Using the complement of the repeat condition gives a neater
Ordinar
• Special
program.
Complement Version
10 REM*STARTMOD*
20 IF (COND) THEN GOTO 50
EXIT
30 P
40 GOTO 20
EXIT
50 REM*ENDMOD*
Example
Pseudocode
BASIC (complement)
10 REM*STARTMOD*
mod
n=1 20 LET N = 1
while n*n< = 100 30 IF N*N>100 THEN This is a condensed version. It groups together
GOTO 60 the FOR—NEXT—STEP instruction elements,
do print n*n which the standard form separates.
n=n+1 40 PRINT N*N This 'llustrates both a
45 LETN=N+1 While—do and a FOR—
NEXT structure.
end while 50 GOTO 30
endmod
60 REM*ENDMOD* 04: Program Development
Example
The Sinclair machines have good editing facilities and error messages.
Those on the Spectrum have brief statements of the error type, those on
Print the values of the first ten integers.
the ZX81 have just a number or letter.
BASIC Although it is inefficient to correct errors one at a time (because there
Pseudocode is seldom only a single error since programming mistakes tend to
mod 10 REM*STARTMOD*
compound one another), error messages on the machine are produced
20 FOR N = 1 TO 10
n=1 singly, since an error stops the computer from running. Thus we must
While n < = 10 30 PRINT N
deal with the errors as they occur in the program sequence. You may
do print n 40 NEXT N
notice a number of errors on carefully looking through the listing. Any
n=n+1 50 REM*ENDMOD*
you spot should be edited out at once.
end while GET TO KNOW YOUR COMPUTER ERROR CODES
endmod This will happen automatically in time (as you make mistakes!), but it
is worthwhile studying the codes. They define the ways in which 'run-
FOR – NEXT loops have their own special flowchart symbol,
time' errors occur, and an understanding of them will help you avoid
because they are used so extensively in BASIC: bugs.
nn4 205
Keep a note of mistakes you have made and how you
• PROGRAM LOGIC ERRORS
•
corrected them. This will be valuable for future reference.
This should become an automatic part of your personal These are the effect of bad logical design of the program. They can be
documentation. Keep a copy of old program listings. Record the errors avoided if care is taken in the design and coding of the program. If a
you have made, the corrections you tried but which did not work, and program produces incorrect results then there is an error in the flow of
what you learned in developing the program. logic in the program. This may only occur with certain values of data.
Trace the impact of any error through the program. If each program section or module has been tested independently
then the linking of the modules is incorrect. We can test program
sections as follows:
SYNTAX ERRORS
1) Insert a temporary breakpoint into the program, at the
These are caused by BASIC statements you key in which do not obey
appropriate point.
the precise language rules (syntax rules) of Sinclair BASIC. The syntax
2) Print out values of intermediate results, to the screen or printer.
errors are detected by the LINE INTERPRETER which
3) It is most important to print out the values of variables used in
automatically checks each line you key in when you press the
NEWLINE (ENTER) key. making a decision and those used in loops, either counter loops
or FOR – NEXT loops.
If there is an error the interpreter will place the SYNTAX ERROR
4) Go back to the pseudocode or flowchart and modify the steps
cursor just before the first error it detects on the line. This may be at
the end of the line if the interpreter finds that something else should which are in error. `Walk through' the algorithm, using a
have been placed there. To correct this type of error you must compare flowchart, to check the step sequence, and hand trace the
the syntax you have written with the rules of BASIC. program with selected values of data and/or variables. Be
Typing instructions incorrectly cannot occur on the Sinclair careful! Often changes in one part of the algorithm cause
computers as the BASIC is single key-stroke. In other BASICs you changes in the others. It is no use solving one problem if it causes
another!
must type P,R,I,N,T, for PRINT. Instructions in general are
5) Change the documentation if necessary. Note down the changes
automatically placed in the correct order along a line (i.e. the order of
line number – instruction – operand), since they are taken care of by you have made, or lines you have deleted. Keep program
listings.
the mode controller which sets the cursors in the correct sequence.
6) Re-test the complete program, using a variety of data.
Errors which can occur are:
1 Omission of line number
2 Line number too large (>9999) Each testing statement in a complex program should be headed by a
remark statement.
3 Line number negative
4 Line number non-integer 1000 REM – DEBUG
5 Omission of delimiters:
brackets (must be paired)
commas (Testing Statements)
semicolons
quotes
colons (on the Spectrum)
6 Typing in of improper variable names REM – END DEBUG
7 Incorrect logical expressions These temporary REM statements are later deleted by keying in their
There can be more than one error per line. The S-cursor will re-appear line numbers, as are the testing statements. It is very easy to leave in
in the line when you try to enter it into memory. The line edit facility is test instructions unless they are marked.
comprehensive and easy to use on the ZX81 and Spectrum.
You must correct your mistakes, and keep trying to `compile' the
line into correct BASIC syntax (to be entered into memory). When INSERTING BREAK POINTS
successful, the program line will appear at the top of the screen.
The syntax error check ensures no nonsense lines (from the We can stop a program at any point and obtain the values of variables,
computer's point of view) are entered. It cannot help you in coding expressions, etc. to test calculations or check for errors. We do this by
correct sequences of program lines, or prevent logical errors.
206 207
inserting a group of statements which will output the values we want
and then stop the program.
4)
•
failure to complete loop increment and subroutine section
statements
5) subscript out of range
Module 6) memory full
7) screen display file full
8) integer out of range
- ADD TEST OUTPUT OF VARIABLES
As we have seen, run-time errors cause diagnostic system messages to
be printed. These appear at the bottom of the screen and are called:
- INSERT STOP STATEMENT
ERROR CODES
These errors can then be traced through the type of error given by the
CONT will restart the program. code and the line number at which the program stopped.
Individual modules or sections of program can be tested this way.
We do, of course, have to RUN the program from the required module ERROR CODES
line number. Care should be taken when this is done that variables
needed in the module have been declared properly and that the values
Error codes or Report codes are presented on the screen when a
of parameters passed to the module are as required. Remember that
program stops for any reason, either as a result of successful
you can INPUT the values of variables directly if necessary, using the completion (no more program lines), an instruction or command
command mode, and using LET statements: (STOP, BREAK), or a run-time error.
LET X(2) = 20, etc. On the ZX81 the codes have the form E/N, where E is the code for
The value of any variable at the point the program crashed can also be the type of error and N is the line number where the program was
obtained by keying a statement without the line number, and again
stopped (STOP or BREAK), or where an error occurred. N is 0 for a
using the computer in command mode: direct command. This is an example of an error code on the ZX81
PRINT A$ which is printed on the screen when an arithmetic overflow (number
LPRINT X(3)
larger than about 10' generated) occurs in line 60 of the program:
The commands RUN N (where N is the line number we wish to run 6/60
the program from) and GOTO N enable us to run the program starting The Spectrum gives an extended error report code, with a brief
at any point. Using GOTO N does not negate the initialisation of statement in the form:
variables that occurs if the program has already run. For example, if E Statement N:S
we input: where E is the report code, the statement is the reason for stopping
(with BREAK or STOP or program completion) or type of error. N is
10 LET A = 1 the line number, but since the Spectrum can have multiple line
20 LET B = 2
statements, the S number indicates which statement on the line the
30 PRINT A,B report code refers to. We are not using multiple line statements in this
and then key in GOTO 30, we get the error report `2/30' (ZX81) or `2 text, so S will always be 1, meaning the first (and only) statement on
Variable not found 30:1' (Spectrum) meaning an undefined variable the line, unless after the THEN in an IF... THEN statement, which is
was found. If we RUN the program, we can then use GOTO 30, and treated, like a colon, as a statement separator.
the program signals successful completion. The Spectrum's version of the example given above (the ZX81's
arithmetic overflow error code) is:
RUN-TIME ERRORS 6 Number too big 60:1
Report codes are crucial aids to debugging programs. Without them
These are a result of programmer carelessness and do not prevent the we would know only that we had an error, but not where it occurred or
interpreter from translating the program. They make the program what type of error it was. The error reports indicate both of these items
crash when you attempt to run it, that is they prevent the program of information.
from running to completion. Common run-time errors are: It is important to understand that the cause of an error may come
1) undeclared or unidentified variables earlier in a program than the line where the program stopped. For
2) arithmetic overflow example, a code 2 error (variable not found), occurring in line 100 of a
3) lack of data for processing program might be caused by a mis-spelt variable name in line 100 (not
208
209
•
the same as the variable you meant it to be – putting GUES when you
•
4 Let your program stop elegantly
meant GUESS, for example). It could also be the result of not having (i) When there is no data input or data available, the
assigned the variable earlier in the program. If the error causing the program should tell you so.
program to halt is not apparent from the line given in the error report, (ii) Sinclair BASIC programs are interactive. The user can
the program flow must be traced backwards to find the prior cause. In control program continuation with:
some cases this can be extremely difficult to track down – for example,
where a numeric value wrongly defined or generated by the program 910 PRINT "PROCESSING ENDED – MORE
causes another expression to cause an arithmetic overflow. Tracing DATA? ANSWER YES OR NO"
techniques must be used. 920 INPUT A$
Lists of Error codes and their meanings for the ZX81 and Spectrum 930 IF A$ _ "YES" THEN GOTO 100
are given in Appendix II. 940 PRINT "GOODBYE"
950 STOP
TESTING AND VERIFICATION 960 REM PROGRAM END
Verify that your program works by testing it with Test Data 5 Rewrite the program until you are satisfied with it
Testing comes after debugging a program. Its purpose is to ensure that Remember the program should be – structured
the program is logically correct, produces correct answers and meets – easy to read
the specification of its purpose. – easy to understand
1 First test each module separately – handle exceptions
Each procedure and subroutine should be treated as if it were a – be as efficient as possible
– documented
separate program.
and it must solve the problem as specified!
Test for (i) good data – the expected type and range of inputs.
(ii) bad data – out-of-range and incorrect type inputs. 6 Put clarity before efficiency
Try to ensure each procedure `fails softly'. For bad data (particularly To be good a program algorithm does not have to be clever, difficult to
in any data entry module) following each input a check routine or understand or run super-fast. If you do not understand how the
procedure should be used to give an error message if range is incorrect algorithm works do not use it – rewrite and re-design or use another
method.
or check type of input and correct syntax. This is best done with
strings, which are more flexibly handled. See Unit V which deals with Programs will work correctly if the rules of the language are obeyed,
input checks at length. and the program will work to specification if the algorithm is properly
designed.
2 Combine the modules and test the complete program
If there is a logical error (i.e. program does not produce the intended
DOCUMENTATION
results) insert additional test statements which will:
(i) Output intermediate results.
(ii) Output values of variables at each stage. ANNOTATE AND DOCUMENT YOUR PROGRAM AND
(iii) Output results of expressions at each stage. CREATE A READABLE PROGRAM
iv) Output values of the loop counter at each pass.
(
(v) Output results of array manipulation after each Write an explanation for each program module or segment. At
operation. the beginning of each segment provide suitable comments which
explain:
(vi) Output values of parameters before and after subroutines
(1) the purpose of the algorithm
entry and return.
(2) the variables and their significance (the values they
3 Handle exceptions
store)
(i) Test all data in the program.
(3) the results expected.
(ii) Screen all data.
2 Use comments only where necessary:
(iii) Process only good data.
(1) don't comment each program line
(iv) Output bad data saying why it was bad.
(2) don't explain the obvious
(3) at the beginning of the program provide a block of
210 211
•
comments that explain the program at each module and
^
05: THE COMPLETE PROGRAMMING METHOD
provide a comment which explains what the module does
in relation to the program. SUMMARY: THE STRUCTURED PROGRAMMING METHOD
3 Clear comments should appear separated from program code.
The clearest comments are framed. For example I. I PRODUCE THE ALGORITHM
10 REM * * * * * * 1.1 State the Problem fully
20 REM " SUBROUTINE TO *
1.1.1 State the problem
30 REM * CALCULATE N TO 2 D.P. *
1.1.2 Understand what is to be done
40 REM * 1.2 Research the Problem
50 REM ' * * * 1.2.1 Research and analyse the problem to see how the
Lines of asterisks provide visible dividers between sections of
computer can handle it
program. 1.2.2 Identify all formulae and relations to be used.
4 Use comment in the program and in the output to the screen or 1.2.3 Identify all data involved
printer. 1.3 Design the algorithm
Use blank REM lines as separators in the program.
Use top down structured methods:
5 For large programs write a reference document:
1.3.1 Break the problem up into sub-problems or modules.
(i) Describe the algorithm you used. If it is not original you
1.3.2 Use a structure diagram or tree diagram to help in
should include a note of its source, author, version, and
breaking down the problem.
type of computer it was written on.
1.3.3 Start classifying modules or parts of modules as:
(ii) Explain how you wrote the program, the reasons for
INPUT
writing it, the type of computer used and memory
PROCESSING
required. OUTPUT
(iii) Make a note of areas that may need improving, or could
1.3.4 Utilise the fundamental control structures in the modules
be modified for different purposes. – Decision structures
(iv) Which modules are general (menus, subroutines), and
– Transfer structures
which require specific kinds of input. – Loops
(v) Explain the scope and limitations of the program. – Subroutines
(vi) Include your name, and the date of production. – Nested structures
6 List the tests you made and data used. Reproduce some of the – Subprograms
results of the tests. 1.3.5 Set up a DATA TABLE in which all data types are
7 List performance tests (e.g. how long it takes the program to classified as
run). Variables
8 Give user instructions and reproduce the output of a run and Constants
explain to the user how he uses the program. Counters
9 Give the program characteristics. Explain any abnormal
Functions – if using a Spectrum and the DEF FN
behaviour of the program (e.g. response to bad input). instructions
10 Write a brief USER GUIDE. This is not for the computer 1.3.6 Define the algorithm further until coding it into a BASIC
expert. It should explain: language program is an easy and obvious exercise.
– the purpose of the program 1.4 Describe the algorithm in Pseudocode and Flowchart form
– the algorithm 1.4.1 Write out the final algorithm (now in modular form) in
– how to run the program small steps in an abbreviated English style called
– what input is needed Pseudocode.
– what results are printed
Each module should be treated separately and labelled.
– how to use the menu (if included)
1.4.2 Illustrate the logical flow of control in the algorithm by
constructing a flowchart.
1.4.3 Test the algorithm, if necessary using a hand trace or
walk through.
212 213
2. I PRODUCE THE PROGRAM
• •
PROGRAMMING: SUMMARY OF METHOD IN FLOWCHART FORM
2.1 Code the Algorithm in SINCLAIR BASIC This provides a diagrammatic version of the summary of structured
2.1.1 Code on a direct basis from the pseudocode or flowchart programming:
description in line numbered BASIC statements, module
by module.
2.1.2 Implement the fundamental control structures, used in (START
/
WRITE
2.3.2 Detail the steps that producing the program involved. DESCRIPTION OF
THE ALGORITHM.
LGAORITHM.
2.3.4 Write a user guide.
PRODUCE A
FLOWCHART
215
214
i •
AN EXAMPLE OF STRUCTURED DESIGN
;!
1. Problem Statement
CODE INTO BASIC
Write a program that computes and prints the Average or Mean 1
(M) and Standard Deviation (S) of a collection of N data items.
FIND ERRORS AND
CORRECT To compute S use the formula:
St
Standard Deviation = /
(Sum of Squares of Items) - (Mean) 2
RUN A TEST
2. Find out what we have to do (research the problem)
This gives the detailed procedure for the steps needed to solve the
problem:
THIS PROBLEM NEEDS
a) INPUT
ERRORS Yes ,
A RE-THINK. PUT The numbers are going to be input into an array because they
EVERYTHING ELSE ASIDE,
AND DON ' T RUSH will be needed twice in the calculation module.
b) 1. Calculate: the Mean -
No Add all the numbers in the array and divide by N.
WRITE DOCOMENTATIO
2. Calculate: the Standard Deviation -
OF HOW IT WORKS, Total the squares of all the numbers in the array.
FLOWCHARTS
AND DOCUMENTATION Use the formula to calculate S.
OF HOW TO RUN THE
PROGRAM.
c) Output: the Results -
The results will be printed on new lines with the words
MEAN = and STANDARD DEVIATION =
END
followed by their values.
C
216 217
5. The Tree Diagrams
• •
1 2 2.
1. Compute and print
CALCULATE STANDARD
Standard Deviation DEVIATION
and mean
1.2.2.1. 1.2.2.2.
CALCULATE SUM OF USE FORMULA TO
THE SQUARES CALCULATE STANDARD
Each of modules 1.1, 1.2 and 1.3 will be subroutines. These will be DEVIATION
called in the appropriate sequence by the main program module.
1.1
INPUT 1.2.2 1.1. 1.2.2.1.2.
INITIALISE FOR EACH
VARIABLE ELEMENT GET
SQUARE, ADD
TO TOTAL
1.1.2 1.1.3
NUMBERS AND
INPUT N LET SUM LET SUM
FOR 1=1 S =SQR((SUMSQR/N)
SQR=O SQR=SUM
TO N MEAN**2 )
SQR+Y(I)
(t ONSPECTRUM
1.3
OUTPUT
RESULTS
FIND MEAN AND STANDARD
DEVIATION
1.3.1 1.3.2
1.2.2 PRINT "MEAN = , PRINT "STANDARD
MEAN DEVIATION = ";S
CALCULATE STANDARD
DEVIATION
1.2.1.2
DIVIDE SUM BY NUMBER
OF ELEMENTS
LET MEAN =
SUM DIVIDED BY N
219
010
• •
6. The Flowcharts The Input Subroutine
flowchart:
The Main Program
module flowchart:
ENTER
C
START
CREATE
ARRAY
Y(50)
GOSUB
INPUT
SUBROUTINE
PRINT
"HOW MANY
NUMBERS?"
GOSUB
PROCESS INPUT
SUBROUTINE N
GOSUB
OUTPUT
SUBROUTINE
I> N RETURN 1
STOP
INPUT
NUMBER Y(I)
221
The Processing
• The Output
Subroutine flowchart:
•
Subroutine flowchart:
ENTER
LET
SUM = 0
( ENTER
)
PRINT
= 1 "MEAN "
LET MEAN
I >N
= SUM /N
t
PRINT
MEAN
LET SUM
LET SUMSQR
= SUM +
_ 0
Y(I)
I
PRINT /
= 1 "STANDARD
>N
DEVIATION="
= I+1
I
PRINT
LET SUMSQR
= SUMSQR 2+
(Y(I))
S
/
I
LET S=SQR
((SUMSQR/N) SPECTRUM FORMULA
C RETURN )
-(MEAN**2)) USES I , NOT **.
( RETURN )
223
222
7. The Program
• •
440 F'RINT "STANDARD DEVIATION
450 RETURN
7.1 The Main Program Module
460 REM **END OUTPUT SUB **
5 REM "_'DEVIATION" **********************
10 REM **********************
**MAIN PROGRAM MOD ** 8. Documentation
20 REM **INPUT DATA **
30 i_0i5LIE: 100
40 REM **CALCULATE** 1) This program will compute and print the Mean and Standard
50 Gi51lE: 200 Deviation of a collection of data items (numbers).
60 REM **PRINT RESULTS**
2) It allows for a maximum of 50 items to be entered. You can
Iii GOSUE: 4011
_:il STOP increase the size of array Y if you wish to deal with more data.
3) The numbers can be of any size, positive or negative, to the
90 REM **END MAIN **
********************** limit of the computer's handling capacity. This is large – you
will not exceed it.
7.2 The Input Subroutine Module 4) To run the program key in RUN, and enter numbers one at a
REM **********************
**INPUT SUIBROUTINE **
time, pressing NEWLINE (ENTER) after each one has been
100 DIM Y(50) keyed in.
110 PRINT "HOW MANY NUMBERS7;
120 INPUT N
Sample run to find Mean and Standard Deviation of 30, 31,
130 PRINT N
140 FOR I=1 TO N 32, 5, 6, 7, 10, 13, 27, 3:
150 1 INPUT Y(I)
160 ) PRINT Y(I);"
HOW MANY NUMBERS ? 10
170 NEXT I
1 ;li RETURN 30 31 32 5 6 7 10 13 27 3
MEAN = 16.4
190 REM **END INF'UT 'SIB **
********************** STANDARD DEVIATION = 11.45603
225
224
SECTION Q: GRAPHICS
• •
10 LET A$="0000"
20 LET B$= STR$ X
30 FOR F=1 Tii 4
Ql: More Printing 40 IF LEN B$;F THEN GOTO 70
50 LET A$(F)=24(F)
60 NEXT F
Since we dealt with the PRINT instructions, you have been introduced 70 PRINT A$
to other statements that can be used with the PRINT statements for
will print the first four digits of any number, or follow the number with
format and manipulation.
Loops are of use in printing. For instance we can set up an empty zeros if less than 4 digits. Change the zeros to spaces, and you have a
number string that will overprint any other string however many digits
string with 32 spaces and use it to clear different areas:
are in the original.
LET A$ = "(32 spaces)" Code the program in with A$ = "(4 spaces)" and try it. As it is, you
20
30
will have to enter X as a direct command (LET X = 123, then
40
NEWLINE/ENTER) and then use GOTO 10, since RUN would
100 FOR X = 11 TO 21. clear the variables (in this case, the value of X you have just entered).
110 PRINT AT X, 0; A$ This principle can be expanded. Here is an example of a subroutine
120 NEXT X
used to justify numbers and print them in the position required for the
decimal places to be in the same column:
will clear the bottom half of the screen, and we could use it repeatedly, 10 REM "FORMAT"
as a subroutine, if we wished. We then avoid using CLS, which would 20 REM *FORMAT SUBRCILITINE FOR*
mean re-printing anything that we wanted to keep on the screen. *NUMBERS *
30 REM *COLUMN NUMBER FOR *
Except for numbers, anything we wish to print must be in the form *DECIMAL PLACE *
of a string, either between quotes, a string variable, part of a string 40 LET C=12
50 REM *INITIALISE GC-,IIE:*
array, or a CHR$(X) instruction. 60 LET Fi iF.:MAT=7000
Obviously any operations or functions used with strings may be 70 REM *NUMBER*
useful, and in the same way as: 30 INPLIT N1
90 REM *INITIALIZE NUMBER*
100 LET N=N1
10 PRINT (1 + 3) 110 GO•SLIE: FORMAT
200 REM •*MIF:E NUMBER=:*
210 FOR L=1 Ti I 4
prints 4, we can use: 220 INPUT N
230 GO SUBIB FORMAT
20 PRINT A$ (X TO Y) 240 NEXT L
S730 GO TO 9999 i
to extract the desired characters of A$. r:':r;,^ i REM **********************
**•3LIE:ROLITINE **
Enter and run this program 9000 LET N$= STR$ N
9010 LET F'=0
'9020 FOR F=1 TO LEN N$
10 LET AS="ABRACADAE-:RA" 9020 IF N$(F)="," THEN LET P=F
20 LET L= LEN A$ 9040 NEXT F
:30 FOR X=1 TD 6 7050 IF F'=1 THEN LET N$="ii"+N$
40 PRINT TAB 10+X;A$(X TO 7060 LET F=F'+(P=1
L+1-X) 9070 IF F'=0 THEN LET F'= LEN N$+1
50 NEXT X 9030 PRINT TAB (C-F+1) ; N$
7170 RETURN
Remember that numbers can always be treated as strings, and vice 9100 REM **ENEISUB**************
9999 :;TCIP
versa, using VAL and STR$. This is often useful for formatting
numbers. For example, with a number X, this program: Lines 10 to 240 are a main program to initialise and provide numbers
for the subroutine. Notice it adds a 0 if the number is a decimal. Line
234 235
•
9030 sets a marker for a decimal point in the first letter of the number
•
Using the E notation allows easy definition of the number of decimal
places, without the possibility of missing a zero as, for example, if we
string, and adding a 0 is done in line 9050. 9060 uses the logical value of
(P = 1) to add 1 if a zero was added, i.e. if P = 1 is true. This will be used INT(10000*(1/N)+ .5)/10000, since using 1E4 gives four d.p.,
explained in the Section on Logic, but the line is equivalent to IF P = 1 1E3 three d.p., etc. In using this, be careful with the bracket placing,
THEN LET P = 2. Check this by trying both versions of the line. Line as INT(1E4*(1/N)) + .5/1E4 will not round! Try both the correct and
9070 adjusts the length of the string if there is no decimal place found incorrect versions in the program.
(i.e. if the number was an integer). 9080 prints the number in the You should note that:
correct column.
With PRINT TAB C; or PRINT AT L,C instructions L and C
The next program shows a simple way of tabulating results, using a
can be dependent or calculated variables. For example:
loop:
PRINT TAB (X*2)/3;
PRINT AT 10, 20/X;
10 PRINT "NO.";TAB 4;"SQUARE";TAB 12;
"CUBE";TAB 20;"RECIP"
Try these:
20 FOR N = 1 TO 10
30 PRINT N;TAB 4;N*N;TAB 12;N* *3; (T on Spectrum)
10 FOR X = 1 TO 5
TAB 20;1/N
20 PRINT AT X, X * 2;X
40 NEXT N
30 NEXT X
237
236
•
To see the difference, RUN both these programs, use COPY to get a Exercises
•
printout, and compare the results.
1 Modify the FORMAT subroutine to round the number to 3
li, FOR X=0 TO 10
decimal places before determining the print position.
20 PRINT TAU X/2;X 2 Modify your result for the exercise above to print zeros for any
30 NEXT X decimal place not filled.
3 Write a program that displays the result of throwing three dice,
10 F O R X=0 TO 10 displaying the result for each die, and the total value for each
20 F'RINT TAE INT (X /2); X
throw. Overprint the last result with each new one, and store the
30 NEXT X
total values resulting. After the specified number of throws,
derive the average value for a throw.
You must also watch for arithmetic mistakes in calculating the PRINT
position. For instance: Q2: More Plotting
10 FOP: X=0 TO 10 Although the definition of the graphics on the ZX81 is low, the
20 PRINT TAB 20/X; X computer has the capacity to draw useful graphs, and most graphics
20 NEXT X
processes can be illustrated. This is a program that draws a line
between two specified points:
is not going to get past line 20 the first time round! Why? 10 INPUT X1
This next example illustrates the use of PRINT AT to give changing 20 INPUT Y1
display. 30 INPUT X2
A die is rolled and we wish to display its value for each of a series of 40 INPUT Y2
50 LET X=X(2) -X(1)
throws. In addition we require cumulative values after each throw. 60 LET Y=Y(2) -Y(1)
Thus each time line 90 is reached it overprints line 70 and vice versa. 65 LET A=(X AND ABS X>=ABS Y) +
Similarly line 120 overprints itself after each throw. (Y AND ABS X<ABS Y)
70 LET DX=0
B0 LET DY=0
F:EM "DICEROLL" 90 FOR F=1 TO ABS A
10 PRINT "NUMBER OF THROWS?" 100 PLOT DX+X(1), DY+Y(1)
20 INPUT X 110 LET DX"=DS+X/ABS A
0 DIM N(6) 120 LET DY=DY+Y/ABS A
35 CL'=. 130 NEXT F
40 FRINT AT 8,6;"CUMULATIVE VA
LUES" The logic in line 65 checks which is the greater of the distances to be
50 PRINT AT 10,4;"1***2***3***
covered between the points, and makes A equal to that, since the
4***5***."
60 FOP: M=1 TO X smaller value will be in a false statement, and will be evaluated as 0.
65 PRINT AT 1,8;"THROW"; TAB 1 You will have to wait until we deal fully with logical operations for the
4;"VALUE"
70 PRINT AT 2, 10; "*", "*"
explanation of the reason this works. The program library has an
80 LET A= INT (6* F:ND +1) expanded version of this program ("LINE").
90 PRINT AT 3,10;M,A Spectrum owners should relish the fact that their machine's ability to
100 LET N(A)=N(A)+1
110 FOE: U=1 TO 6 accept a simple DRAW X,Y statement makes this entire program
120 PRINT AT 12,4*B;N(U) redundant. Study the principle, however.
130 NEXT B Subroutines can be used for plotting. If you recall our dog-plot, here
140 NEXT M
is an example of a subroutine used to fill the screen with dogs. The
subroutine for this is between lines 300 and 430 and is based on a grid
(8 horizontal by 5 vertical):
(N.B. Choose a relatively small value for X (say 24-) or the program
will take a long time to run.) 10 REM "DOGS"
20 FOR X=0 TO 50 STEP 10
30 FOR 1=10 TO 40 STEP 10
40 GOSUB 300
238 239
45 NEXT Y
50 NEXT X
• Q3: Movement and Timing
60 GOTO 700
300 REM **DOG PLOT** We can deal with the two topics of time and motion together. We will
310 PLOT X,Y
320 PLOT X+1,Y-1 introduce and illustrate the new functions concerned, and then look at
330 FOR N=2 TO 4 them in combination.
340 PLOT X+2,1-N The first new commands (which only apply to the ZX81) are FAST
350 NEXT N
360 PLOT X+3,Y-2 and SLOW. If the screen display is to be continuous, the ZX81 has to
370 PLOT X+4,1-2 read and print on screen the contents of the display file fifty times a
380 FOR N=1 TO 4 second (sixty times a second in the U.S.). It can then only compute in
390 PLOT X+5,Y-N
400 NEXP N
the gaps between doing this. Up to now, we have used this continuous
410 PLOT X+6,Y compute and display mode exclusively. This is SLOW mode on the
420 PLOT X +7,Y-1 ZX81. The Spectrum works in the equivalent of the ZX81 FAST
430 RETURN
700 REM **END**
mode, and displays the screen at the same time:
For a function producing positive values of Y, we can use a routine FAST blanks out the screen, and the ZX81 computes faster,
as below. We set A and B as the values of X between which we want to not needing to break off to display the screen. Screen display
plot the value of Y, and store the largest number encountered in a is restored when
variable MAXY. The routine is for the ZX81. Spectrum users would (i) the program ends
need to use 240 in place of 60 (line 40), and 160 instead of 40 (line 80). (ii) the program stops to await input
(iii) the program goes into SLOW mode
10 LET A=(MINIMUM VALUE OF X) (iv) the program is instructed to PAUSE.
20 LET B=(MAXIMUM VALUE OF X)
The screen display is updated during FAST, but only printed
20 LET MAXY=O
40 FOR X=A TO B STEP (B-A)/60 at a break in the program.
50 LET Y= (FIJNCT I ON OF X)
60 IF Y>MAXY THEN LET MAXY=Y
FAST mode is used whenever it is necessary to perform a large number
70 NEXT X
80 LET SY=40/MAXY of calculations on the ZX81, and a screen display is not vital. To
illustrate the two modes, enter and RUN this program:
Adding the following lines gives us the plot:
10 SLOW
90 FOR X=A-A TO B-A STEP (E:-A)
20 FOR X = 1 TO 20
/60
100 LET Y=X*X 30 LET Z = X*X**X/X**X
110 FLOT X*60/(B-A),Y*=;Y 40 PRINT Z;
120 NEXT X 50 NEXT X
Spectrum: 240 not 60 in line 90.
Line 10 is redundant, the ZX81 will already be in SLOW mode. But
Notice that all the function values are calculated twice. It would be
now change it to:
neater to set up either two lists, or a two dimensional numerical array
(X(60) and U(60) or X(2,60)), and store the values the first time
round. Try this when we have dealt with numerical arrays. Run the 10 FAST
program, using different values of X in lines 10 and 20 and some
different equations in line 50 (and the same one in line 100). Try and RUN. Change it back and, by counting, see what the difference in
X**2 + 3X, X**3 - 6X + 2, etc. (Tin place of ** if using Spectrum). timing is between the two modes. You can also delete line 10, and shift
Revise the program to allow inputs in lines 10 and 20. between the modes by using direct commands. Note the flash of the
screen when you input lines from the keyboard in FAST mode. This
240
241
•
makes it easy to tell which mode you are in. The ZX81 computer is
always in SLOW mode at switch on, and if you are shifting between
•
10 PRINT "STAR'["
20 PRINT "2SECOND DELAY"
30 PAUSE 100
the two modes, using direct instructions, then the characteristic flash 40 PRINT "FOR...NEXT LOOP"
will let you know if FAST is the current mode. 50 FOR X = 1 TU 150
60 NEXT X
70 PRINT "END"
PAUSE
The next instruction can be used in a program line by the ZX81 only.
It does not exist for the Spectrum. The definition and discussion apply
PAUSE causes the execution of a program to halt for the time
only the the ZX81, but the method of achieving the same effect on the
specified. The screen display is shown on the screen during
the PAUSE. Pressing a key during a PAUSE will cut the Spectrum is given below.
PAUSE short and the program will continue.
PAUSE N gives a delay of N/50 seconds (N/60 seconds in SCROLL
the U.S.)
PAUSE 150 gives a delay of 3 seconds (2 %2 seconds in the SCROLL moves the whole screen up one line, deleting the top
U.S.) line, and sets a new PRINT position at the start of the new
If N>32767 the PAUSE will continue until a key is pressed bottom line.
on the ZX81.
If N = 0 the PAUSE will continue until a key is pressed on
the Spectrum. To see this work, try this program:
242 243
•
SCROLL instruction in a program, which can be useful, the procedure
•
80 PRINT "E:LA'_.TCIFF"
on the Spectrum is as follows: 90 FOR X=1 TO 22
1. The value of – 1 must be POKEd into a system variable at memory 100 SCROLL
address 23692. This is done with a program line 'POKE 23692, – 1'. 110 PRINT ," V"
120 NEXT X
2. Something must be printed on line 21. This can be just a space, or it
may be the first thing you wish to print in a sequence that will have all Spectrum users need to delete line 100, and insert 85 POKE
printing coming up from the bottom of the screen. 23692, – 1.
3. Scrolling will then occur, one line at a time, whenever another Whilst on the subject of scrolling, here is a routine that scrolls a line
PRINT instruction is given. of text across the screen from left to right. Input a name (inverse
A simple program illustrates this: characters look better), or a line of text, and fill out the line with some
graphics characters. Lines 20, 50 and 60 fill up the line to 32 characters
10 POKE 23692, – 1 with black squares. The technique can be used with several lines of
20 PRINT AT 21,0;"PRINT HERE TO CAUSE SCROLL" text, but is too slow to be useful if dealing with a full screen:
30 PAUSE 50
- REM *INPUT A NAME*
40 PRINT "SCROLL" *(NICER IN INVERi:E)*
50 PAUSE 50 6 REM *REPEAT IF LINE NOT*
*FILLED*
60 PRINT "SCROLL AGAIN"
10 INPUT A$
20 IF LEN A$<32 THEN GOTO 60
The PAUSE instructions merely cause a delay to enable you to see the 20 PRINT AT 10,O;A$
40 LET A$=A$( LEN A$)+A$(1 TO
process properly. The PRINT item in line 20 could be a space, as long
LEN A$-1)
as it is something printed on the bottom line. Try this program: 50 GOTO 20
40 LET A$=A$+"M"
10 POKE 23692, – 1 70 GOTO 20
20 PRINT AT 21,0;" (Single space)
When you have keyed in the program, try deleting "AT 10,0," in line
30 FOR F = 1 TO 10
40 PRINT "PRINT" 30. This gives an effective full-screen display.
50 NEXT F Games programs often utilise interactive graphics, via the INKEY$
function. A SKETCH program as below shifts the PRINT position
We can use SCROLL, or the Spectrum equivalent, to create a moving around. Note that on the Spectrum, INKEY$ is not totally reliable.
screen display. Try this: Add PAUSE 0 to ensure it works.
Spectrum users please note also that the POKE instruction will work if This uses logical values to do a multiple operation in lines 40 and 50,
it is given as line 5 in the program, and line 40 deleted. Try it. which both adds or subtracts 1 to the values of X and Y, and keeps the
Try this for a rocket launch: character within the screen limits. This could be done less efficiently by
:0 PRINT AT 18,17; "0" the following:
20 PRINT , "MU"
30 PRINT , "ME" 40 IF INKEY$ = "5" AND X>0 THEN LET X = X – 1
40 PRINT ,"®"
50 FOR C=10 TO 0 STEP' -1 50 IF INKEY$ _ "8" AND X<31 THEN LET X = X + 1
60 PRINT AT 1,1;C;" " 60 IF INKEY$ = "7" AND Y>0 THEN LET Y = Y – 1
70 NEXT C 70 IF INKEY$ = "6" AND Y<21 THEN LET Y = Y + 1
80 GOTO 30
244
245
•
In lines 40 to 70 both conditions have to be true to execute the change
•
10 FOR X = 25 TO 0 STEP - 1
20 PRINT AT 11,X;" W ";AT 12,X;" 1§7"9 ■15 "
in the values of X or Y. In the original example, these logical tests are 30 NEXT X
combined (in the brackets) and use is made of the fact that the
computer uses 1 for TRUE and 0 for FALSE. These logical values are The alternative, which is slower (and harder on the eyes), is to use
used to change X and Y appropriately, according to which keys are CLS, and reprint the screen. To see the effect, just add:
pressed, but only if the values of X are within 0 - 31 and the values of
Y are within 0 - 21 (i.e. within the PRINT AT range). 25 CLS
If, for example, X is equal to 0, then in line 40 above, the combined
conditions of INKEY$ = "5" (true, if it is being pressed) AND X>0 Or try this (which includes, to a rather distorted scale, a gravity effect)
(not true) will be false. The instruction following THEN will not be and imagine you are Galileo:
executed. Similarly, in the line LET X = X - (INKEY$ = "5" AND
1 REM GRAVITY DROP
X>0) + (INKEY$ = "8" AND X<31) each of the bracketed 10 LET T=0
expressions is evaluated for truth/falsity. Only one of the bracketed 20 LET H=0
expressions can be true, and if, for example, the first is true, X will 30 PRINT AT 0,5;1E1"
40 PRINT AT 21,1;"-
become X - (1(true)) + (0(false)). Logical operations, which are of
50 IF H>21 THEN GOTO 110
great importance, are fully covered in Section R. 60 PRINT AT H,10;"*"
We could add: 70 LET T AI'+, 25
80 LET H=INT 32*T*T/10
90 CLS
35 PRINT AT Y,X;" " 100 GOTO 30
110 PRINT AT 21,7;"*SMASH*"
247
n
14f UNPLOT 9, 12
150 PRINT AT 0,5;"* NPN TRAN'II3
Exercises
•
TOR *"; TAD ;"*****************
*" 1. For ZX81 users: Computer performance in terms of speed is
160 PRINT AT 5, 17; "E'A=E"; AT 7, compared by benchmark tests. Write a program that loops 500
17; "CURRENT ON"; AT 14,1; "COLLEC
TOR"; TAD 22 ;"EMITTER" times, performing a calculation each time. Run it in FAST and
170 PRINT AT 5, 10; "+VE"; AT 18, SLOW modes, and time it.
O; "+VE <:N*N*N*N><P,:'.:N*N*N*N' -VE
2. Revise the left to right scroll to work right to left.
180 REM **GF:APHIC STRINGS** 3. Write a program that draws a ship and moves it backwards and
190 LET A$-" forwards across the screen, automatically.
211f ) LET r-:$=^
t._ET S$=" p
4. Revise the program to move the ship in response to INKEY$
210
2 20 Fille. N-1 T O 15 input from the keyboard.
220 i Write a program that uses PAUSE to display minutes and
.4 0 REM **GRAPHICS LOOP**
FOR F=1 TO :_
5.
seconds. Check the clock against a watch and improve the
250 IF F=1 THEN PRINT AT 7,14;"
M. accuracy.
26(1 PRINT AT 16-F,14;1e"
270 PRINT AT 16,4;E$(F TO F+9); Q4: The Display File
AS (F TO F+10)
2„0 PRINT AT 7,13;5$(1 TO :3);
290 IF F=C: AND INKEY$ = THEN In order to talk about the display file, we must introduce some new
O ,3I I[: 400 concepts, which are dealt with more fully in a later section of the book
300 PRINT AT 7,14;" "; AT 16-F,
14; (Section U).
:310 NEXT F
320 NEXT N The DISPLAY FILE is the memory picture of the screen
:330 PRINT AT 21,0; "PROGRAM HALT
ED. RESTART?(Y OR N)" display stored in a sequence of memory locations or addresses
340 INPUT R$ in the computer RAM.
350 IF RS "Y" THEN GOT° 440
:361, PEINT AT 21,0;"
BYTE. Each memory location in the computer stores an 8 bit
370 i+OTO 220 (digit) binary number which has a decimal value between 0
and 255.
395 REM ***********************
**GASE CURRENT OFF '_;UP**
400 PRINT AT 5,10;" ; AT 7,1 To interact with the computer's memory, we use PEEK and POKE.
_ '3$(4 TO ); AT 7,25 ;"OFF" We are concerned here not with the general instructions (which are
410 IF INK:EY$ !.. "R" THEN GOTO
410
dealt with in Section U) but with some specific uses for these
420 PF.:INT AT 5,10; "+VE"; AT 7, 1 commands. We will give a definition of PEEK and POKE here, and
'3$(1 TO 3); AT 7,25;"ON then discuss the use of these only in terms of some simple techniques
430 RETURN
connected with the screen display that can be of use in graphics.
435 REM ** END'c:LiL-: ****
********************** PEEK (M) returns the contents of the memory address (M) (a
440 CLG binary number) in decimal form.
450 REM **END PROGRAM **
POKE (M),(N) inserts the value N (0 to 255) into the
specified memory address, M.
Spectrum modifictions: PAUSE 0 in line 40.
The program uses the `chunky' ZX81 plot squares to draw the outline The display files of the ZX81 and Spectrum are organised very
(lines 60 to 140). Spectrum plot points could be used, but strings of the differently. That of the Spectrum is much more complex, due to the
graphics characters on keys 1 to 8 would be better. Refer to the screen
high-resolution PLOT screen and colour on the machine. We will deal
diagrams in Unit M2 for the positions on screen requiring printing.
with the ZX81 display file in some depth below, and then describe the
Spectrum display file. Spectrum users should GOTO page 257, and
omit the ZX81 specific section below, unless they find it interesting for
248
249
•
general information. It is useful to know the ZX81 display file system if
•
Line 10 sets D to the values of the `D-FILE' system variable, which
you are interested in converting ZX81 programs for the Spectrum, as stores the memory location of the start of the display file. The address is
some programs use the techniques described below. always stored in two bytes (16396 and 16397) of memory and the
second is the more significant byte (i.e. stores the higher value). Hence
On the ZX81:
the *256 before the second memory location.
The ZX81 has done away with much of the use of POKE in connection 1 2 3 4 5...... 33 34
(Line 0)
with the display file, because the PRINT AT function actually uses a 35 36 37 38...... 66 67
routine in the computer that finds out where the display file starts and 101 102
then POKEs to it the required characters at the correct position.
To illustrate the work this saves, here is a program that puts ZX at 726 727
(Line 21)
line 1, column 10, on the screen. 759 760
(Line 22) 728 729
(Line 23) 761 762 792 793
10 LET D = PEEK 16396 + 256*PEEK 16397
20 LET Z = D + (32 + 1 + 11) So to use this technique we only need to find the start location of the
30 POKE Z, 63 display file once, and allocate a variable to it (D in the program above),
40 POKE Z + 1,61 or arrange to re-use a program line with the PEEK commands.
To try to make things a little clearer, try the following program:
Note that, even though we could write the routine above more
compactly (by missing out line 20 and using POKE D + 44, POKE 10 LET DFILE = PEEK 16396 + 256*
D + 45 as lines 30 and 40) it is still rather more complicated than: PEEK 16397
10 PRINT AT 1,10;"ZX" 20 PRINT "DISPLAY FILE START ADDRESS
IS", "MEMORY LOCATION "; DFILE
Thus we will not use it unless we have good reason. But let's run 30 FOR M = DFILE – 8 TO DFILE + 8
through what we are doing. Do not worry if you cannot fully 40 PRINT M;TAB 10; PEEK M; TAB 18;CHR$ PEEK M
understand all of this, you can return to this Section later, when the 50 NEXT M
memory has been covered.
250 251
•
Line 10 PEEKs the D-FILE memory locations, which store the
number of the address in which the first NEWLINE (ENTER)
•
10 REM "ARTIST"
20 PRINT "DRAWS A PICTURE BY M
OVING A CHARACTER IN 8 DIRE
character of the display file is located.
CTIONS"
If you have entered the program exactly as shown – including the 30 PRINT "TO MOVE IN THE FOLLO
space after "Memory Location" – line 20 will print: WING DIRECTIONS PRESS THE C
ORRESPONDING KEY"
40 PRINT TAB 10; "NORTH--W"
DISPLAY FILE START ADDRESS IS 50 PRINT TAB 10; "SOUTH--X"
MEMORY LOCATION 16694 60 PRINT TAB 10; "EAST-D"
70 PRINT TAB 10; "WEST--A"
80 PRINT TAB 10; "NORTHEAST--E"
This is followed by a printout like this: 90 PRINT TAB 10; "SOUTHEAST-C"
100 PRINT TAB 10; "SOUTHWEST--Z"
16686 110 PRINT TAB 10; "NORTHWEST--Q"
118 ?
120 PRINT
16687 0 130 PRINT
16688 50 M 140 PRINT "TO CHANGE THE CHARAC
16689 3 ■ TER PRESS S THEN THE CHARAC
TER THEN NEWLINE"
16690 0 150 PRINT
16691 243 NEXT 160 PRINT "DON'T GO OVER THE ED
16692 GE OF THE SCREEN"
50 M
170 PAUSE 400
16693 118 ? 180 CLS
16694 118 ? 190 LET T=120
16695 41 D 200 LET A$="*"
240 POKE PEEK 16396+PEEK 16397*
16696 46 I 256+T,CODE A$
16697 56 S 250 IF INKEY$=" " THEN GOTO 250
16698 53 P 270 LET B$=INKEY$
280 LET T=r+(32 AND B$="Z")+(33
16699 49 L AND BS="X")+(34 AND B$="C"
16700 38 A )-(34 AND B$="0")-(33 AND
16701 62 Y B$="W")-(32 AND BS="E")+(
1 AND B$="D")-(1 AND B$="
16702 0 A")
290 IF B$="S" THEN INPUT A$
This shows a memory address (16686) then the character code it 300 GOTO 240
contains (118) and its character string (in this case 118 is NEWLINE
(ENTER), and prints a `?'). Address 16687 is a space (character code The complex looking line 280 (be careful to input it correctly) uses the
0) and a space is printed. 16688 contains the number 50, which is the same logic as was mentioned with the "Sketch" program. If you
line number of the last program line, and prints M. Then there is a 3 inspect it, after we've dealt with logic properly, you will see that each
stored (which is the number of characters in the program line) and key that is pressed gives a different value. The equivalent lines without
which prints the graphic character, then NEXT (character code 243), this technique would be:
and M again, this time representing the variable M, not the number 50.
Then there is a NEWLINE (ENTER) character (118) marking the end 280 IF B$="Z" THEN LET 'r=T+32
281 IF B$="X" THEN LET Tir+33
of the program. The next NEWLINE (ENTER) is at 16694, the start IF B$="C" THEN LET 'r=T+34
282
of the display file, and then there are the codes and characters for 283 IF BS="Q" THEN LET T=T-34
DISPLAY (the first words to be printed on the screen). 284 IF BS="W" THEN LET Tir-33
285 IF B$="E" THEN LET 'r=T -32
To illustrate the use of PEEK and POKE with the display file, here 286 IF BS="D" THEN LET T =r +1
287 IF s$="A" THEN LET T=T-1
is a program to draw on the screen. This does essentially the same
thing as the sketch program we met earlier, but it uses the technique of
POKEing characters to the display file directly, instead of via the
PRINT AT function. We give a full listing here, but in fact to run it,
you need only enter lines 190 to 290.
252 253
•
–33
•
because DF-SZ returns to its normal value on completion of a
program. If we use COPY it will also not print the bottom two lines – it
—34 –32 is only set for a normal screen size of 22 lines.
I I J E l
We may also restrict the screen size. Key in this program:
–1 +1 10 POKE 16418,20
^ A ^
J D l 20 PRINT "TOP LINE"
30 PRINT "SECOND LINE"
40 PAUSE 150
z C 50 PRINT "NOW SCROLL"
+32 +34 60 FOR X=1 TO 4
70 SCROLL
^X I 80 PRINT "SCROLLED ";X
+33 90 NEXT X
If you look at the diagram above and the numbering of the display file, The SCROLL instruction now operates from the bottom line of a
you will see how it works. – 1 or + 1 move the position along a line, screen which is only 4 lines deep. This can be used to clear just the top
– 34 moves it up one line and to the left etc. All this numbering is part of the screen, leaving the rest undisturbed.
within the display file. Line 240 PEEKs the D-FILE memory Try this next program, which uses both these techniques together.
locations, adds the display file position number and POKEs into the (You don't need to input the text in lines 70, 90 and 110. Just PRINT
result (a memory address in the display file) the character code for AS. 1, 2 and 3 instead).
Notice the speed of this program. This gives us one reason to use
10 POKE 16418,0
PEEK and POKE: to provide speed of display. 20 FOR L=0 TO 23
Notice the warning about the edges of the screen in the program 30 PRINT "LINE NUMBER ";L
listing. When you have decided you have played with the program 40 NEXT L
50 POKE 16418,21
enough, try going off the edge of the screen. The results will not harm 60 SCROLL
the ZX81, but you will probably have to switch the power off to reset 70 PRINT "THESE LINES"
the computer. All manipulations of the display file must be done with 80 SCROLL
90 PRINT "NOW CLEARED AND
great care so as not to interfere with the NEWLINE (ENTER) 100 SCROLL
characters marking the end of each line. If these are altered the 110 PRINT "REST OF SCREEN LEFT
computer cannot keep track of where everything should be, the display AS IS"
120 FOR X=1 TO 300
will go crazy and the program will crash. Be warned! (And be careful in NEXT X
your programming!)
It is possible to increase the screen size of the display to give the If entered as above, the top portion of the screen would look like this:
capability to PRINT or PRINT AT on the bottom lines of the screen.
The system variable (DF-SZ) at memory location 16418 holds the THESE LINES NOW
number of lines in the bottom half of the screen, and is normally set at CLEARED AND REST OF
2. If we use POKE 16418,0, the bottom two lines can be used to SCREEN LEFT AS IS
PRINT AT. Try this program. LINE NUMBER 3
LINE NUMBER 4
10 POKE 16418,0 LINE NUMBER 5
20 FOR L = 0 TO 23 LINE NUMBER 6
30 PRINT "LINE NUMBER" ;L
40 NEXT L Unfortunately, we cannot choose a screen section in the middle of the
50 FOR X = 1 TO 300 screen (e.g. lines 6, 7 and 8) to do this with, and must use PRINT AT
60 NEXT X "(32 spaces)" with the lines we want to clear, or overprint directly, or
POKE spaces into the relevant positions, as in this program:
Notice that, after the delay caused by the FOR...NEXT loop, the 0/60
10 FOR F= 1 TO 9
message appears on the bottom line as usual, and that the next 20 PRINT "LINE NUMBER ";F;"
command from the keyboard clears the bottom two lines. This is (16 SPACES) END"
30 NEXT F
254 255
• •
40 PRINT "LINE NUMBER TO BE Notice lines 30 and 40. We must set the PRINT AT position in line
CLEARED ?"
50 INPUT LINE 30, then PEEK the DF-CC addresses, then PRINT the "*".
60 LET DFILE=PEEK 16396+256*PE The ASTEROIDS program in the program library uses the
EK 16397 technique of PEEKing the next PRINT position to determine whether
70 FOR X=1 TO 32
80 POKE (LINE-1)*33+DFILE+X,0 a black square occupies this position. The relevant lines are
90 NEXT X
Note that if we put: 130 PRINT AT 5,C;
140 IF PEEK (PEEK 16398 + 256*PEEK
70 FOR X = 32 TO 1 STEP – 1 16399) = 128 THEN GOTO 250
150 PRINT "*"
we get a reverse line clearance (right to left), and
Look up the program and work out how these lines relate to the rest of
the program. If you find line 140 confusing, remember that the ZX81
70 FOR X = 32 TO 30 STEP – 1
evaluates expressions in brackets first. It gets the value stored in the
clears END, but leaves the rest of the line. 16398/9 addresses, which returns the address of the PRINT position,
Another useful system variable concerned with the ZX81 display file then PEEKs this address.
is the DF-CC address, locations 16398 and 16399. This holds the We will now deal with the Spectrum display file, which does not
address of the current print position in the display file. If this address is have the straightforward structure of that of the ZX81, and to which
found by using PEEK 16398 + 256* PEEK 16399 then it can in turn be PEEK and POKE techniques have little application.
PEEKed, and will give the code of the character present at the current
print position. Note that the current print position is the next position to SPECTRUM DISPLAY FILE
be printed. A line like
The Spectrum display file is organised in a very different way to that of
10 PRINT TAB 8; "A" the ZX81. This is a consequence of the high-resolution screen display
on the Spectrum (256 * 176 points are plotable), compared to the
leaves the current print position set at the start of the next line of the `chunky' graphics of the ZX81, with only 64 * 44 plot squares. The
display, and pattern of squares in any character cell on the ZX81 can be defined as a
character code. On the Spectrum each individual point of the 8 by 8
10 PRINT TAB 8;"A"; grid of a character cell must be individually specified.
The Spectrum display file is fixed in memory, and does not vary its
gives as the current print position the next position after the A. To location. There is no need to PEEK a system variable to find its
illustrate, here is a variation on the basic screen movement program we position, as the start address is always 16384, and it is a fixed length of
derived from SKETCH which uses the DF-CC variable. 6144 bytes, occupying the memory addresses up to 22527.
The complex method of organisation means that it is not possible (as
10 LET X=10
it is with the ZX81 and other computers), to POKE character codes to
20 LET Y=10
30 PRINT AT Y,X; the screen and have the character specified by that code appear.
40 LET D=PEEK 16398+256*PEEK 16399 Similarly, we cannot PEEK the screen to find out what character, if
50 PRINT "*"
any, occupies a given location. Both these operations are theoretically
50 LET X=X-(INKEY$="5" AND X>0)
+ (INKEY$="8" AND X<31) possible, with much calculation, but not practicable. However, the
70 LET Y=Y-(INKEY$="7" AND Y>0) speed of the Spectrum's operations takes away much of the advantage
+ (INKEY$="6" AND Y<21)
of using PEEK and POKE on the ZX81, and we can use PRINT AT
80 POKE D, 0
90 GOTO 30 instructions to place characters on the screen, and two special
Spectrum functions for finding out what is on the screen. Before
Instead of setting two variables as equal to X and Y before their values introducing these instructions, here is a description of the way the
are altered (before line 50) in order to identify where to print the space
Spectrum display file is organised:
which blanks the "*", we use variable D to store the location of the Each character cell has an 8 by 8 dot matrix of points, which may be
print position (line 40) and then POKE a 0 (space) into it to overprint `set' (blacked or inked in) or not. These patterns of dots make up the
(line 80).
256 257
•
characters. We'll treat this in more detail later. For plotting, each point
•
Note the restriction on what SCREEN$ will recognise. The chunky
must be specified individually, and this means that the characters graphics characters on keys 1 to 8 are not recognised. An empty string is
available in the character set do not cover the whole set of possibilities returned. Run the following program to see SCREEN$ in action. After
for each cell. To cope with this, the Spectrum stores each pattern of you've tried other characters, try the graphics characters and inverse
points along a 32 character cell line on the screen in a sequence of video. Input PRINT LEN SCREEN$(10,10) as a direct command to
bytes. However, these are not stored in sequence down the screen. The see that the null string (no characters) is returned.
top point sequence of each of the first eight rows of characters (lines)
are stored one after the other. The second line of points in each of these 10 INPUT A$
8 lines of characters is then stored, and so on until the first eight lines of 20 PRINT AT 10, 10; A$
the screen display have been defined. The next eight lines on the screen 30 PRINT SCREEN$ (10,10)
are then stored in the same way, followed by the bottom eight lines of
the 24 line screen. There is another Spectrum specific instruction that can be used to find
To make this clearer, key in the following program and run it: out what is currently on the screen. This is POINT.
10 PRINT "
SCREEN$ is a Spectrum specific function. It returns the
20 PRINT POINT (0,175)
single-character string of the character printed at the specified
30 PRINT AT 10,10;"l"
line and column co-ordinates. It has the form:
40 PLOT OVER 1;84,90
SCREEN$ (L,C)
50 PRINT POINT (84,90)
PRINT SCREEN$ (2, 6) returns the character printed at Line
60 PRINT POINT (85,90)
2, Column 6 on the screen. The brackets cannot be omitted.
SCREEN$ will return the true video form of any inverse
Line 20 checks the upper left corner pixel of the character cell with the
character. It does not recognise either the true video or
exponentiation sign printed in inverse video. This returns 1, since the
inverse video forms of the Graphics characters.
pixel is set. Line 30 prints an inverse square (CAPS SHIFTed graphic
258 259
•
8), which SCREEN$ will not recognise. Line 40 unplots 1 pixel, using SECTION R: LOGICAL OPERATIONS
the OVER 1 statement, and line 50 checks this plot point, returning 0,
since it is unplotted, and line 60 checks roughly the centre point of the
black square, which returns 1. This offers us a way of checking inverse R1: Logic Values and Numeric Values
characters. You must, of course, make the correct calculations for the
transfer from the PRINT to PLOT screens. When using the logical capability of Sinclair BASIC we must
You should notice two points for future use, after Section W has distinguish between logical values and the numeric values produced by
introduced the other Spectrum functions not dealt with in the main logical evaluation. We have touched upon this earlier in the book, but
body of the text. One is that we referred to POINT returning 1 if the deferred a full explanation until now.
pixel was set or inked in, and when you start using colour, you should LOGICAL VALUE is the value of an expression using the criteria:
remember that POINT checks for the currently specified INK colour. any non-zero value of the expression – "TRUE"
For our purposes, this is black. The other is that the colour attributes a zero value of the expression = "FALSE"
that refer to a character cell when colour is used can be another source When an expression is logically evaluated it is assigned one of two
of information about the screen display. (This uses the ATTR numeric values:
function. See Unit W3.) "TRUE" 1
"FALSE" 0
AND A
Examples 100 IF (A = 10) AND (B<>3) THEN GOTO 60
200 PRINT (A AND B)
260 261
Truth Table for AND
• •
NOT (symbol 1 ) logically evaluates the complement (reverse) of a
A B A AND B
given expression.
TRUE TRUE TRUE In line 20, if A = 10 then A = "TRUE" and NOT A = NOT
TRUE FALSE FALSE "TRUE" = "FALSE".
FALSE TRUE FALSE So in line 20 if A is 10, NOT A is "FALSE" and control passes to
FALSE FALSE FALSE the next line.
If A = 0 ("FALSE") then NOT A = NOT "FALSE" = "TRUE"
A and B are conditional expressions.
and the program stops.
In line 30 if (A = B) is "FALSE", NOT (A = B) = NOT "FALSE"
R3: The OR Operator
= "TRUE", so program stops.
In line 100 if A = 0 = "FALSE" then NOT A = "TRUE" = 1
OR V
So 1 is printed.
Examples 100 IF (A>1) OR (B = 0) THEN STOP
If A = 29 then A is "TRUE" and NOT A = "FALSE", and 0 is
200 PRINT (C OR D)
printed.
966 267
5OR0 = 5
NOT 8 = 0
• R9: Priority
OPERATOR
• PRIORITY
NOT 0 = 1
Exercises =,<>,<,<=,>,>= 5
NOT 4
1 Key in the examples given above as direct commands, and verify AND 3
the rules of logical operations on numbers. OR 2
2 Key in and run the following programs:
Priority rules are strictly obeyed. If brackets are not used properly
LOGIC 1: when logical operators act on conditions the desired result will not be
achieved. For example:
5 REM "LOGIC 1"
10 INPUT A NOT ("FALSE" AND "FALSE")
20 INPUT B
30 PRINT "A=";A,"B=";B gives NOT "FALSE"
40 PRINT "A AND B=";A AND B = "TRUE"
50 PRINT "A OR 8=";A OR B BUT
60 PRINT "NOT B=";NOT B
70 GOTO 10 NOT "FALSE" AND "FALSE"
gives "TRUE" AND "FALSE"
Results: ="FALSE"
A = 77 B = 45
Completely the opposite!
A AND B=77
A OR B = 1 Exercises
NOT B=0
1 Key and and run this program, which checks priority.
A=77 B=0
10 LETA=1
A AND B = 0
20 LET B = 1
AORB=77
30 PRINT NOT (A = 0 AND B = 0)
NOT B = 1
40 PRINT NOT A = 0 AND B = 0
LOGIC 2:
2 What result would the following give?
5 REM "LOGIC 2" PRINT 5 AND 3 OR 0 OR NOT 7 AND 4
10 REM **THIS PROGRAM TESTS THE LOGICAL OR 3 Key in and run program "LOGIC 4", which tests priorities:
OPERATOR ACTING ON A NUMBER AND A
CONDITION TOGETHER** 5 REM "LOGIC 4"
30 PRINT "Y=10*(7 OR A=3)" 7 REM **THIS PROGRAM TESTS MU
35 PRINT LTIPLE LOGIC OPERATORS**
40 PRINT "INPUT A VALUE FOR A PLEASE" 10 LET A=5 AND 3 OR 0 OR NOT 7
45 PRINT AND 4
50 INPUT A 20 PRINT "5 AND 3 OR 0 OR NOT
55 LET Y=10*(7 OR A=3) 7 AND 4="; A
60 PRINT "IF A=";A,"THEN Y=";Y 30 PRINT
65 PRINT 40 PRINT
70 PRINT "WHAT ARE YOUR CONCLUSIONS??" 50 LET B=((4 AND 2) AND NOT (0
75 PRINT AND 3)) OR ((3 OR 0) AND (4
80 PRINT OR 0))
90 GOTO 30 60 PRINT "((4 AND 2) AND NOT
0 AND 3)) OR ((3 OR 0) AND
(4 OR 0))=";B
LOGIC 3:
REM "LOGIC ÿ
10 INPUT A
20 PRINT 77+ (10 AND A=3)
30 GOTO 10
269
268
R10: Logical Operations with Strings
• EXAMPLES:
•
1 Logical operations using AND, OR and NOT may be PRINT "A" AND 3 = 3 gives A
performed on conditional string expressions. For PRINT "A" AND 3 = 4 gives the empty (null) string
example: PRINT "A" AND "B" = "B" gives A
10 IF (A$ = B$) AND (C$ = D$) OR (D$ = E$) THEN... PRINT "A" AND "B" _ "C" gives the null string
50 PRINT NOT A$ = B$.
2 The AND operator may be used directly between a string Exercises
and a number. For example:
PRINT (A$ AND N) 1 Key in and run LOGIC 5, which illustrates string and condition
The result of this operation is given by the truth table. use.
5 REM " LJGIC 5"
A$ N A$ AND N 10 LET X$="AB"
20 LET Y$="AC"
A$ <>0 A$ 30 PRINT (2 AND X$>Y$)
A$ 0 cc >> 40 PRINT (7 AND X$<Y$)
50 PRINT (5 AND X$=Y$)
52 PRINT
i.e. A$ AND N returns A$ if N is non-zero 54 PRINP
and a null string if N is zero. 60 LET P$="1"
70 LET Q$="2"
3 Two strings cannot be directly operated on by any logical
80 PRINT (33 AND P$>Q$)
operator because strings cannot have logical values. For 90 PRINT (66 AND P$<Q$)
example: 100 PRINT (99 AND P$=Q$)
102 PRINT
A$ AND B$, A$ OR B$, NOT A$
110 PRINT "SO""Aö""<""AC"""
are meaningless expressions. 112 PRINT
120 PRINT "AND ""1""<""2"""
Exercises
Results:
1 Key in PRINT NOT "A" = "B" 0
and PRINT "A" = "B" AND "B" = "C" OR "G" = "E" 7
to test the rules of logical string operation. Try other 0
combinations.
0
2 Write a program which requests a name and then checks to see if
66
it corresponds to several strings stored in the program, printing
0
out a message to say if the word was found.
3 Write a program to test the truth table for A$ AND N. SO "AB"<"AC"
AND "1"<"2"
R11: Logical Operations Between Strings and Conditions
Only the AND operator may be used. 2 Alter the values of X$,Y$,P$ and Q$ and run the program again
The rule is the same as for strings and numbers. each time.
3 Alter the program to allow various strings and numbers to be
A$ AND C input, and print out the relationships.
A$ C
270 271
Where N is a number 1 Simple Conditional Tests
and C is a condition: IF (Logical Operation) THEN (statement).
If the logical operation is TRUE the statement is executed.
either a string condition e.g. A$ = "A"
or a numeric condition e.g. B = 7 AND, OR and NOT operators are used.
2 Multiple Conditional Tests
N C NANDC IF [(Condition 1) AND (Condition 2) OR (Condition 3)] THEN
NORC
(statement).
N TRUE N 1 If the multiple logical operations are TRUE the statement is
N FALSE 0 N executed.
AND, OR and NOT are used.
These are the same rules as with logical operations between
3 Multibranch GOTO Routines
numbers.
Using this technique, control may be transferred to any of a
N AND C gives N if C is "TRUE"
number of statement lines.
N AND C gives 0 if C is "FALSE" Here we use the AND routine, whose default value is zero:
N OR C gives 1 if C is "TRUE"
N OR C gives N if C is "FALSE" GOTO (100 AND C1) + (200 AND C2) + (300 AND C3)
272 273
or we could program this as
• •
and Y. We know that AND can be used so that if we code a
program line as LET M = X AND X>Y it will return the value
70 IF X >= Y THEN GUTO 60
40 PRINT "MAX=";Y;" MIN=";X of X if the condition is true. We want to use this to get the value
50 STOP of a maximum. The line above will produce zero if the condition
60 PRINT "MAX=";X;" MIN=";Y
is not true. So we can combine two such tests in one line to get
Which do you think is the best method? our maximum. We key in this sort of program (do it):
Finding the largest number in a list is another application. We 10 INPUT X
have a list of numbers A(1) to A(N). We can compare the first 20 INPUT Y
two, A(1) and A(2), and put the largest of these into a variable L 30 LET MAX = X AND X>Y + Y AND Y>X
by the statement: 40 PRINT MAX
LET L = (A(1)AND A(1)> = A(2)) + (A(2)AND A(2)>A(1)) Input some numbers and check the results.
We compare this value of L with the next number A(3) and Something is wrong. Looking at the program, we see we need
make L take the larger value of the two and so on through the some brackets. As it stands, line 30 is actually a sequence of
list. three conditions, joined by two AND operators. It reads `give
LET L = (L AND L> = A(3)) + (A(3) AND A(3)>L) MAX the logical value of (X) AND (X>Y + Y) AND (Y>X)'.
The program asks us to input how many numbers will be in our Since all three conditions have to be true for the whole
list (N). We then input the numbers A(I). These arc printed on expression to be true, and since (X>Y + Y) and (Y>X) cannot
the screen together with the largest value. Two loops are used, both be true, we get zero.
the first to input the numbers and the second to perform the We make the expression more sensible, we hope, by changing
comparisons. line 30 to read: LET MAX = X AND (X>Y) + Y AND (Y>X).
Key in this as a new line. Now try some inputs.
10 REM "LARGEST"
20 PRINT "INPUT HO4 MANY NUMBE If X is smaller than Y we get the value of X printed, and if X
RS" is greater than Y we get zero. We haven't got the brackets right.
30 INPUT N There arc still three conditions joined by two ANDs. We've
40 PRINT N
50 DIM A(N) changed the meaning, but not to what we actually want. If X
60 FOR I = 1 TO N and Y are non-zero, (X) is true, ((X>Y) + Y) is zero for smaller
70 INPUT A(I) X, one (TRUE) for larger X, added to Y. This is non-zero, so is
80 PRINT A(I);"
90 NEXT I TRUE. If the last condition is TRUE (i.e. Y>X) then the
100 LET L =(A(1)AND A(1)>=A(2) combined expressions give X as the result. If it's FALSE then
)+(A(2)AND A(2)> A(1)) the whole expression is FALSE and prints 0. Now we see what's
110 FOR I = 3 TO N
120 LET L = (L AND L>=A(I)) + wrong, we can put some more brackets in.
(A(I)AND A(I)> L) Edit line 30 to read: LET MAX = (X AND(X>Y)) + (Y AND
130 NEXT I (Y>X)).
140 PRINT "LARGEST NUMBER IS "
;L Now try some inputs. The greater of the two numbers is
returned, which is what we wanted. If we now look at our
Key in and run the program. working line, we can see (or should) that there are brackets we
This is an appropriate place to emphasise the care needed in don't need, although they don't do any harm. Edit line 30 to
programming logical operations. There are two things that read LET MAX = (X AND X>Y) + (Y AND Y>X) and check
cause problems. The first is the setting of conditions, and the the greater value is still returned. So we're finished – or are we?
second is the grouping of these conditions in a logical sequence Only if you didn't consider what happens if the numbers X and
that will produce the required result. Any line the computer does Y are equal. Input the two numbers as the same value and see
not reject because of a syntax error will produce a result. Care is what result you get. Both expressions are FALSE if the numbers
needed to get the right result. are equal, so we get zero printed.
This can be illustrated by the question of deriving the larger of The line should read: 30 LET MAX = (X AND X> = Y) + (Y
two numbers, using AND. The problems of non-rigorous use of AND Y>X). Just in case you're not convinced of the problems
the logical and relational operators can be illustrated by you can get into if you are not careful, enter the line as above
considering the following problem. We have two numbers X and check that it works. Then edit it to read: LET MAX = (X
274 275
2) 10 REM "STR*ARR2"
• •
out two elements in the array. Nested loops (line 90 to 140) print out
20 DI.M A$(3,4) the complete array.
30 LET A$(1)="ABCD"
40 LET A$(2)="EFGH" Why is line 130 required?
50 LET A$(3)="IJKL" In order to keep track of the elements of an array we need to have a
50 PRINT A$(2,4);" ";A$(3,2) system. In general it is easiest to use R to represent the Rows and C the
70 PRINT
80 PRINT A$(2,2 TO 4) Columns and to always access the rows before the columns.
90 PRINT
100 PRINT A$(1,3 TO 4)
Note the use of the TAB function to give a clear printout.
5 10 15 20 25 30 35 40 45
The simple array is one-dimensional, and contains just a linear
etc.
sequence of items. Arrays can have more than one dimension:
4 6 8
10 12 14
String arrays can also have more than one dimension.
16 18 20
22 24 26
This is a numeric array consisting of 4 rows of numbers in 3 columns. 2-D String arrays are dimensioned by a statement of the form
Storage would be reserved by the statement: DIM A$(R,C,L)
10 DIM A(4,3). where R is the number of Rows, C is the number of Columns
In an array A(R,C) we can access any element, so that in the array and L is the length of all strings in the array.
above:
A(2,1) = 10 A(3,2) = 18 etc. Try this program:
An array of two (or more) dimensions is also known as a MATRIX 10 REM "20STRING"
20 DIM A$(3,3,5)
(plural matrices).
30 PRINT "TYPE WORDS 5 LETTERS
The following program establishes an array and prints out two OR LESS"
selected elements and then the complete array: 40 FOR R=1 TO 3
50 FOR C=1 TO 3
REM "ARRAY" 60 PRINT AT 2,0;"R04 ";R;" COL ";C
20 DIM A(10,9) 65 INPUT A$(R,C)
s FOR R=1 TO 10 70 NEX'f C
FOR C=1 TO 9 80 NEXT H
40 LET A(R,C)=R*C 90 FOR R=1 'r0 3
5T i NEXT C 100 FOR C=1 TO 3
60 NEXT R 110 PRINT AT R*4,C*8;A$(R,C)
70 PRINT A(10,6),A(5,3) 120 NEXT C
PRINT 130 NEXT R
FOR R=1 TO 10
100 FOR C=1 TO 9 Key this in and run it. Try some appropriate entries for the rows and
110 PRINT TAD 3*C;A(F:,C); columns, as the routine in line 60 gives a cue for which entry is next.
1 20 NEXT C
1"c:i) PRINT TAD 4; This is a useful routine for use with multiple entry INPUT routines,
140 NEXT R since it is very easy to forget which entry is next. One run of this
program gave a final screen display like this:
Line 20 allocates the appropriate storage. Nested loops (line 30 – 60)
are used to allocate values to the elements in the array. Line 70 prints
284 285
TYPE WORDS 5 LETTERS OR LESS
• 104" "4DARRAY"
100 DIM A(2,3,4,5)
110 FOR B=1 TO 2
120 FOR P=1 TO 3
ROW 3 COL 3 130 FOR R=1 TO 4
140 FOR C=1 TO 5
150 LET A(B,P,R,C)=B*P*R*C
160 NEXT C
START 2ND THIRD
170 NEXT R
180 NEXT P
190 NEXT B
200 PRINT A(1,2,3,4);" ";A(2,2,3,3)
210 PRINT
FOUR FIVE SIXTH 220 FOR B=1 TO 2
230 FOR P=1 TO 3
235 PRINT "B00K";B;"/PAGE";P
240 FOR R=1 TO 4
250 FOR C=1 TO 5
SEVEN EIGHT FINAL 260 PRINT A(B,P,R,C);" ",
270 NEXT C
280 PRINT
Note also line 110, where both control variables of the nested loops are
290 NEXT R
used to format the printout using the PRINT AT instruction. 300 PRINT
310 NEXT P
320 PRINT
S7: Multidimensional Arrays 330 NEXT 8
Multidimensional arrays are available for both numbers and strings, Here's a 3-D string version to try. Input only two letters at a time.
although a 3-D string array is rarely something needed in a program! Actually it doesn't matter, the computer will ignore any characters in
The easiest way of thinking of these arrays is as follows: excess of 2, since that is the dimensioned length.
A (P, R, C) is a 3 dimensional array: page, row, column 5 REM "3D*S1R*ARR"
A (B, P, R, C) is a 4 dimensional array: book, page, row, column. 10 DIM A$(3,3,3,2)
A 5 dimensional array would be a library, on the basis of this analogy. 20 FOR P=1 TO 3
30 FOR R=1 TO 3
These arrays require DIM statements to reserve the necessary storage.
40 FOR C=1 TO 3
A simple example of a 3 dimensional array (which needs 3 nested 50 INPUT A$(P,R,C)
loops) is given below. 60 NEXT C
70 NEXT R
80 NEXT P
10 REM "3DLIST" 90 FOR P=1 TO 3
100 DIM A(3, 2, 4) 100 FOR R=1 TO 3
110 FOR P=1 TO 3 110 FOR C=1 TO 3
120 FOR R=1 TO 2 120 PRINT AT R*3, (P*10-10)+C*3;
130 FOR C=1 TO 4
A$(P,R,C)
140 LET A(P,R,C)=P*C*R 130 NEXT C
150 NEXT C 140 NEXT R
160 NEXT R 150 NEXT P
170 NEXT P
180 PRINT A(2,1,3) Work out how the PRINT AT expressions work.
190 PRI'!f
200 FOR P=1 TO 3
210 FOR R=1 TO 2 S8: Use of Arrays
220 FOR C=1 TO 4
230 PRINT A(P,R,C);" ',
240 NEXT C A simple example of the use of 2-D arrays is shown in the seat booking
245 PRINT program below. A small theatre consists of 10 rows of seats with 6 seats
250 NEXT R in each row. Some seats may already be reserved. These are input
255 PRINT
260 NEXT P
when the program is run. When a new booking is made the requested
seat, if available, is sold. If the seat is not available a seat in the same
The similar program below, extended by a dimension, shows a 4 row is offered. If no seat in that row is available the customer is asked
dimensional array printed out in a suitable form. to choose another row.
286 287
The sections of the program are as follows:
• •
100 IF S(R,C)=1 THEN PRINT "ROW
Initialise an array to represent the 10 rows of 6 seats (line 30). "; R; " SEAT " ; C; " ALREADY", "8C 10K:.
1 ED"
All elements in this array are 0, and represent unbooked seats. 110 LET S(R,C)=1
2 Input seats already booked (lines 40 — 130). 120 ';'TC' 50
2.1 Input row and seat number of booked seats. If input is 0 for the
130 CLS
row number, program goes to 2.3.
140 PRINT "INPUT C TO PROCEED T
2.2 If seat already booked (array element = 1), print message to O BOOKING."
user. Seat is booked by placing a 1 in the appropriate array 150 INPUT As
element. 1600 CLS
165 REM **CUSTOMER REQUEST FOR*
2.3 Program prints prompt, then halts until C is input. **'_EAT **
3 Customer request for seat is input (lines 165 — 240). 170 PRINT "TYPE ROW REQUIRED"
3.1 Row and seat required are input. If seat already booked (array 180 INPUT R
190 PRINT "TYPE SEAT NUMBER"
element = 1), program goes to 4. 200 INPUT C
3.2 Seat is booked. 210 IF S(R,C)=1 THEN GOTO 200
220 LET 3(R,C)=1
3.3 Menu is printed to enable user to choose to book another seat, 220 PRINT "THIS SEAT FREE. NOW L-
or to view seating plan. OOKED. "
3.4 If seat booking is requested, program returns to 3.1. If seating 240 PRINT "ROW "; F:; " SEAT ";C:
250 PRINT
plan option is chosen, program goes to 5. 260 PRINT "BOOK ANOTHER SEAT (S
4 Seat unavailable module (lines 300 — 450). )0R VIEW", "'=EATING PLAN (P)''INPU
4.1 Seat unavailable message is printed, then the variable SEATS T S OR P"
270 INPUT AS
is set at zero, and the loop checks if at least one seat is free in
280 IF A$="S" THEN GOTO 170
this row, setting SEATS = 1 if a seat is free (Current Row R, 290 GOTO i 500
checked for S(R,1) to S(R,6)).
300 REM ** SEAT UNAVAILABLE **
4.2 If no seats are free in this row (SEATS = 0), program passes to
310 PRINT "REQUESTED SEAT NOT A
line 440 and prints message, then returns to menu (3.3). VAILABLE"
4.3 If at least one seat is free, the loop at lines 390 to 410 prints out 320 LET SEATS=0
330 FOR N=1 TO 6
the numbers of the seats free, and the program returns to the 340 IF S(R,N)=1 THEN OUTO 360
menu. 350 LET SEATS=1
5 View Seat Plan Module (lines 500 — 600). 360 NEXT N
370 IF SEATS=0 THEN GOTO 440
5.1 Nested loops are used to display seat plan, row 10 being at the 380 PRINT "SEATS FREE:";
top, as 0's and l's. 390 FOR N=1 TO 6
5.2 Copy option is given, to print out seating plan. 400 IF S(R,N)=0 THEN PRINT N;"
5.3 Menu presented for end of program or return to book seats. 410 NEXT N
Program goes to 3.1, or proceeds to 6. 420 PRINT ". '
6 Program ends. Instructions given to restart if required without 430 OOTC' 450
288 289
590 PRINT ,,"INPUT C TO CiiPY,AN
• C
•
Loop variable for seats in seat plan printing. As with R
Y TO PROCEED" above, re-initialised as simple variable on return to seat
400 INPUT A$
610 IF A$= "C" THEN COPY selection routine.
620 F'RINT „"INPUT E Ti i END,S T Note that the use of variables in two ways, as with R and C in this
0 BOOK SEATS." program is only possible if the simple variables will be re-initialised
630 INP U T A$
every time they are used, otherwise problems can arise. A loop variable
640 IF A$="E" THEN OUTO 670
650 CL'ô erases a simple variable of the same name. It would be better practice
660 OUTO 170 to use different names for the two types of variables.
670 PRINT "PROGRAM STOPPED. US E
GOTO 170 TO" ,"RE S TART."
680 STOP
Screen display, at end of seat plan print routine (the first prompt has
been responded to with a user input):
ROW 10 000000
ROW 9 000000
ROW 8 000000
ROW 7 000000
ROW 6 000000
ROW 5 000000
ROW 4 000100
ROW 3 100000
ROW 2 111111
RON 1 000000
290 291
SECTION T: SORTING SEARCHING AND STORING ARRAYS
• 130 R' *SORTING ROUTINE****
140 FOR N=1 TO X-1
150 FOR M=1 TO X-N
160 LET C=A(M)
T1: Searching and Sorting 170 LET D=A(M+1)
180 IF C<=D THEN GOTO 210
190 LET A(M)=D
Searching a list of numbers (or strings) for specified values can 200 LET A(M+1)=C
obviously be done much more efficiently if the numbers (or strings) are 210 NEXT M
220 NEXT N
sorted according to some specified order, commonly alphabetical order 225 REM ******END SORT******
or ascending numerical order. In electronic data processing groups of 230 LPRINT "SORTED LIST"
records (files) can be handled more efficiently if the records are pre- 240 FOR N=1 TO X
250 LPRINT A(N);" ",
sorted into a specified order (e.g. by merging transaction files into a 260 NEXT N
master file). Various techniques have been developed to sort data and
several of the simpler methods are illustrated in this section together Sample printout:
with two simple methods of searching lists. UNSORTED LIST
There is a considerable difference in the efficiency of the various 129 267 56 41 69 43 99 90 4 8
sorting techniques depending on the type and volume of data to be
sorted. A technique which is good for a random list of numbers may SORTED LIST
not be appropriate for a list in which only one number is out of 4 8 41 43 56 69 90 99 129 267
sequence. For random lists the Quick Sort and Shell Sort techniques To illustrate the operation of the program, we'll take the first four of
are very much faster than a Bubble Sort. Deciding on which is the most these numbers and see how the program sorts them:
suitable method is largely a matter of experience and you should Bubble sort for 4 numbers A(1), A(2), A(3), A(4)
experiment using the different techniques for equivalent sets of input as 129, 267, 5 6 , 41
numbers, timing the sort procedures. Procedure:
Many sorting algorithms exist, and we will first deal with the (1) Go through the list comparing successive number
simplest. pairs. For example:
The BUBBLE SORT is used for sorting numbers (or strings with A(1) and A(2), then A(2) and A(3).
appropriate alterations) into ascending or descending order. The If A(1)>A(2) then they are swapped so that A(2)
principle of the bubble sort is to compare adjacent numbers and change becomes A(1) and A(1) becomes A(2). If A(1)
positions if they are in the incorrect order. This is done for elements 1 <A(2) then they are left as is.
and 2, then 2 and 3, 3 and 4...X – 1 to X at the end of which the We see that the largest number in the.list will
highest number is in the Xth position. This is repeated (and the next finally be in the highest position, i.e. A(4).
highest number bubbles up to the X – 1th position) and repeated (2) On the first pass we make three comparisons and
again, until the ordering is complete. the largest number will end as A(4).
The following program is a bubble sort to put numbers into On the second pass we make two comparisons,
ascending order. The sorting routine itself is in lines 130 to 225. and the largest number will be in position A(3).
On the third pass we make one comparison.
10 REM "BUBBLE"
20 PRINT "TYPE NUMBER OF ITEMS
The larger number will be A(2).
TO BE SORTED" No need for any more passes. Smallest number
25 PRINT "MAXIMUM NUMBER 50" will be A(1).
30 INPUT X
There are four numbers: so X = 4
35 IF X>50 THEN GOTO 25
40 DIM A(50) We need X – 1 passes: so N = 1 TO (X – 1)
60 PRINT "TYPE NUMBERS ONE AT = 1 TO 3 passes
A 'TIME" For each pass we need from 1 to X – N comparisons:
75 LPRINT "UNSORTED LIST"
80 FOR N=1 TO X so M = 1 to (X – N) comparisons
90 INPUT Z Here is a diagram in table form of the operations performed in the
100 LET A(N)=Z
course of the sort:
110 LPRINT A(N) ; ;
120 NEXT N
125 LPRINT
292 293
Table of Operations
• Exercise
•
Pass 1 Pass 2 Pass 3
Draw up the table of operations for this program, as was done for the
N= 3 N= 2 N= 3
"BUBBLE".
START M= 1 M= 2 M= 3 START M= 1 M= 2 START M= 1 FINISH
PASS PASS
T3: Alphabetic Sort
2 3
294
295
•
•
SORTED LIST Swap 3 2
123 21
45
,, 1
345 2 3
456 543
567 6 3 5
897 99
(ii) Correct use: Swap 5 4
HOW MANY STRINGS
1 1
4 5
MAXIMUM 10 CHARACTERS
UNSORTED LIST Swap 5 1
123 099 y 1
543 006 1 5
456 897 t -^
This is another type of sort which is more efficient than the Bubble Sort Consider the list A(1), A(2) . . . A(X). To insert item A(I + 1) in the
correct position:
and is also the basis of an even faster sort called a Shell Sort. Speed is a
prime consideration when sorting large amounts of data. Let T = A(I + 1), then
Consider the list of numbers: if T> = A(I) no swap is necessary and no further comparisons are
required.
3 2 5 4 1 if T<A(I) we let A(I + 1) = A(I) and we move on to A(I — 1), then
We start with the first entry in the list. Then we take the second item, if T> = A(I — 1),we let A(I) = T and insertion is complete
compare the two, and swap if necessary. Then the second is compared if T<A(I — 1), we let A(I) = A(I — 1), and so on down the list.
with the third, a swap performed if required, and if a swap was made
the first and second are compared again, and swapped if necessary. The various steps we will make in the program are therefore as follows:
Then the third item is compared with the fourth, and so on. The list
1) Set J = I and T = A(I + 1)
above will be sorted like this:
2) If T> = AU) let AU + 1) = T and stop
3) Let AU + 1) = A(J)
4) LetJ=J-1
5) If J<1 let AU + 1) = T and stop. If not, go to (2).
6) Repeat for each value of I (from 1 to N — 1) where
N = number in list.
297
Program Listing
• T5: Shell Sort
•
5 REM "INSERT" The procedure in this sort is to precede an insertion sort by a process
10 PRINT "HOW MANY NUMDERS?" which, if we consider a list of numbers to be placed in ascending order
15 PRINT
20 PRINT left to right, will move low values to the left and high values to the right
30 INPUT X more quickly.
40 DIM A(X) Consider an 8 element list A(8), holding the values: 74, 32, 59, 46,
50 PRINT "TYPE NUML-:ERS
FOR N=1 TO X 26, 9, 62, 42. The sort proceeds in the following stages:
6C)
70 INPUT A(N)
„0 NEXT N 1) Divide the 8 by 2 and compare elements 4 positions apart in the
91) PRINT
PRINT "UNSORTED LIST"
list, swapping if necessary:
100
110 FOR N=1 TO X
A(1) A(2) A(3) A(4) A(5) A(6) A(7) A(8)
120 PRINT A(N);"
130 NEXT N
140 PRINT
190 F:EM ***********************
** SORT INC MODULE **
A trace of the program, using our example list again, can be shown like g9 74
this:
42 (SWAP) 3'2
74 (SWAP) 62
I = 1 I = 2 I = 3 I = 4
J= 3 J= 2 J= 4 J= 3 J= 2 J= 1 J = a 42 32 46
Start J= 1 J= 2
A(5)=1 5
The steps we make in the program are as follows:
298 299
N = number of items in the list.
• Hand trace of Shell Sort •
b) Sort the lists of items S positions apart, by comparing and
swapping if necessary. Consider the 8 element list 74, 32, 59, 46, 26, 9, 62, 42.
If S<1 then stop, since the list is sorted. X = 8.
c)
d) If S> = 1 then pick a new value of S (usually INT(S/2)), and z=8
repeat steps b) to d) as often as necessary. Line No.
62
3 4
42
2
2
2
32
4
46
3
fi2
4
46
90 PRINT
100 PRINT "UNSORTED LIST"
110 FOR N=1 TO X
120 PRINT A(N); " ";
270 1
280 A(5)=74
l
A(6)=32 0(B)=46
l
290 J = -3 -2 0
130 NEXT N
140 PRINT
190 REM **SORTING ROUTINE**
300
1
310 A(1)=26
1
A(2)=9
.
A(7)=62 A(4)=42
4 A(6)=32
.
0(8)=46
.
A(7)= 2
.
A(8)=46
200 LET S=X 320
210 LET S=INT (S/2)
220 IF S<1 THEN GOTO 400 330
1
1 1
230 FOR K=1 TO S 340
240 FOR I=K TO X—S STEP K
250 LET J=I
260 LET T=A(I+S) At this stage (1) the list is 26, 9, 59, 42, 74, 32, 62, 46.
270 IF T>=A(J) THEN GOTO 310
—^ 210 5=2 s=t
280 LET A(J+S) =A(J)
290 LET J=J—S 220
At this stage (2) the list is 26, 9, 59, 32, 62, 42, 74, 46.
The final stage is the comparison of neighbouring elements using the
insertion sort technique, to which the Shell Sort routine is equivalent
when S = 1. This is perhaps more easily seen if we consider the trace
below of the operation of the Shell Sort program on a simple 5-item list,
in which only two passes need to be made.
300 301
Pass 1
2
Pass
s =
2
•
INT 2/2 = 1
1) Initialise two pointers, I and J, at opposite ends of the list. Let
X(I) be the reference number. In our example, this is 63.
S = INTS/2 =
K=1 K= 1 I J
I 1 I = 2 3 2 2 2 I = 3 63 27 43 96 72 31 82 43
J J = 2 J - 3 J - 2 J = 2 start .I = 1 J = 2 J = 4 'Finish
A(4)=3 4 4 4 4 4 4
A(5)=5 5 5 5 3) Move the pointer opposite the reference number one place
towards it.
I
43 27 43 96 72 31 82 63
The two methods of tracing a program illustrated here should show you 4) Repeat steps 2) and 3) until I = J.
the method by which a systematic analysis can be made of the changing
values of variables in a program as processing proceeds. This is a 43 27 43 96 72 31 82 63
procedure you should put to use when designing a program (i.e. in
checking that the algorithm will work as intended) and when checking I J
the operation of other people's programs that you wish to analyse. The 43 27 43 96 72 31 82 63
procedure is also a great help in debugging a program. Break points
inserted into the program (STOP commands), after which you can I J
print the values of variables by direct commands, or PRINT 43 27 43 63 72 31 82 96
statements, inserted as appropriate to print the values of variables at
each step in the program, will enable you to check that the values I J
occurring in the program are the same as the ones your trace diagram 43 27 43 63 72 31 82 96
shows. You can even LPRINT values to get a printout, if many passes
are to be made in the program. I J
43 27 43 31 72 63 82 96
I
43 27 43 31 63 72 82 96
T6: Quick Sort
This provides a fast sorting technique which works by subdividing the When this stage has been reached the list has been split into two
list into two sub-lists and then subdividing the sub-lists. The principle sub-lists. The reference number is now in its correct position in
of the Quick Sort is as follows: consider a list A(X) containing X the list, and the sub-lists are the numbers to the left and right of
numbers. We assume as an example that X = 8 and the numbers are as this position.
shown below. The following steps are carried out:
302 303
•
5) One of the lists is stored for future sorting (see below) and the
•
The array S is initially dimensioned as S(X,2) for a list with X
other is taken through steps 1 to 4 above. elements. P indicates the number of the sub-lists; S(P,1) the left-hand
[43 27 43 31] 63 [72 82 96]
element and S(P,2) the right-hand element of the sub-list. In the
example given, at step 5 we will have the first sub-list generated stored
continue with store by setting:
sub-list sub-list
in correct P = 1, S(P,1) = 6 and S(P,2) = 8
position
Thus each list to be stored is placed in sequence into the array, this
I J process being known as PUSHing on to the STACK.
43 27 43 31 When the sub-list that the program continues with finally has only
I J one number we must return to sort the stored lists. We retrieve a stored
31 27 43 43 sub-list (POP a list out of the STACK) by letting:
I J
31 27 43 43 L = S(P,1), R = S(P,2) and P = P – 1
New Sub-list
[31 27 43] 7/'' and continuing until all the lists are sorted.
31 27 43 in correct
position Program Listing
31 27 43
27 31 43 5, REM "QUICK"
10 PRINT "HOW MANY NUMBERS?'
20 INPUT X
in correct 20 DIM A(X)
position 40 DIM 5(X,2)
50 PRINT „"INPUT NUMBERS"
60 FOR N=1 Ti! X
6 ) This process is repeated, in each case storing a sub-list where 70 INPUT A(N)
necessary, and finally going back and sorting all stored sub-lists S0 NEXT N
so that eventually each number is in the correct position. 90 PRINT
100 PRINT' "UNSORTED LIST"
The left-hand and right-hand numbers of a list are denoted by sub- 110 FOP N=1 TO X
scripts L and R respectively. 120 PRINT A(N);"
The pointer positions are denoted by I and J and a flag S is set to 120 NEXT N
140 PRINT
indicate the pointer at the reference number, so that: 180 REM ***********************
* ** SORTING ROUTINE **
1'?0 LE T. P=0
S = 1 if reference number at pointer I 20t;, LET L=1
S = – 1 if reference number at pointer J 210 LET R=X
—20 LET I=L
—-y, LET J=R
If at the end of step 4 the reference number is at I (as in our example)
2 4 0 LET 5=-1
then the list has been split into: 250 IF A(I) <= AG!) THEN GUTO!
00
26O i LET T=A(I)
reference 270 LET A(I)=A(J)
sub-list sub-list 2 30 LET A(J)=T
304 305
';:= i i IF L<:R THEN GOTO 220
_;90 IF P=0 THEN LOTO 450
400 LET L==(P,1)
•
the same number of digits.
•
10, 20, 100, 200, using leading zeros to maintain the value, but giving
306
307
;ii INPUT C
• 1000 RETURN
•
40 PRINT „ "HOW MANY RECORDS?"
INPUT N 1010 REM ** ENDSUE **
r',i i PRINT ,,"HOW MANY ITEMS IN ***********************
EACH RECORD?'
70 PRINT For example, if we input a storage array of 4 records with 3 fields,
::i, INPUT L
REM *********************** maximum 6 characters in any item, and use as input data:
**INITIALISE $ ARRAY;**
90 DIM N$(N,L,C) SMITH, 460, OXFORD
100 DIM K$(N, C)
110 DIM X(N) JONES, 080 LEEDS
120 REM ********************** BROWN, 730, YORK
**INPUT RECORDS ** WHITE, 095, BATH
130 FOR R=1 TO N
140 PRINT "TYPE ";L;" ITEM=; FOR
RECORD ";R Results are as follows:
160 FOR I=1 TO L
160 INPUT N$(R,I)
170 NEXT I
(i) Using field 1 as key
180 NEXT R
190 PRINT Sorted records are:
200 PRINT "WHICH ITEM IS 'SOF:TIN
G KEY?'
210 INPUT J BROWN 730 YORK
220 FOR R=1 TO N JONES 080 LEEDS
230 LET K$(R)=N$(F:,J)
SMITH 460 OXFORD
240 NEXT R
iii c=;UE; 900 WHITE 095 BATH
260 FRINT
270i PRINT "SORTED RECORDS ARE:"
280 PRINT
(ii) Using field 2 as key
290 FOR R=1 TO N
300 FOR I=1 TO L Sorted records are:
310 PRINT N$(X(F:),I);" ";
_20 NEXT I
330 PRINT JONES 080 LEEDS
340 NEXT R WHITE 095 BATH
250 PRINT
SMITH 460 OXFORD
^F,ii PRINT "DO YOU WISH TO CONTI
NUE ^(Y/N)" BROWN 730 YORK
370 INPUT Y$
380 IF Y$="Y" THEN LOTO 200
390 STOP.
Using field 3 as key
308 309
• •
Our list is now:
number. This is in lines 40 — 60. The list is printed out in lines
70 — 110. The search routine is then carried out in lines 200 — 300. 16 18 20 24 28 30 36
Clearly a number near the beginning of the list is found quickly but one
at the end rather slowly. For a 50 element list the average number of and we choose 24 (middle).
searches will be 25. Our list is now:
5 REM "SEARCH1"
10 DIM A(100)
15 PRINT "TYPE NUMBER <100"
28 30 36
20 INPUT N
30 IF N>100 THEN GOTO 15 We select 30 (middle).
40 FOR M =1 TO N
Thus we have found the number in three searches (compared with
50 LET A(M)=INT (100*RND) +100
52 FOR R=1 TO M-1 fourteen using the linear search).
54 IF A(M)=A(R) THEN GOP° 50 In the program the following sections occur:
56 NEXT R
60 NEXT M
70 PRINT "UNSORTED LIST" (i) Setting up initial unordered list and printing out (lines
80 FOR M=1 TO N 10 — 150).
90 PRINT A(M);" "; (ii) Sorting this list into order and printing it out (lines 200 — 330).
100 NEXT M
110 PRINT (iii) Binary search with printout (lines 500 — 680).
200 REM **LINEAR SEARCH** 5 REM "SEARCH2"
210 PRINT "TYPE NUMBER BETWEEN" 10 DIM A(50)
220 PRINT "100 AND 199"
20 PRINT "TYPE NUMBER <50"
230 INPUT X
30 INPUT N
240 FOR I=1 TO N 40 IF N>50 THEN GOTO 20
250 IF X=A(I) THEN GOTO 300 50 FOR M=1 TO N
260 NEXT I 60 LET A(M)=INT (100*RND)+100
270 PRINT "NUMBER NOT IN LIST"
70 FOR R=1 TO M-1
280 PRINT "AFTER ";N;" SEARCHES"
80 IF A(M)=A(R) THEN GOTO 60
290 GOTO 400
90 NEXT R
300 PRINT "NUMBER ";X;" AFTER ";
100 NEXT M
I;" SEARCHES"
110 PRINT "UNSORTED LIST"
400 REM **END**
120 FOR M=1 TO N
130 PRINT A(M);" ",
140 NEXT M
150 PRINT
T9: Binary Search 200 REM **INSERTION SORT**
210 FOR I=1 TO N-1
This is a much faster search technique than the linear search but can 220 LET J=I
230 LET T=A(I+1)
only be used for a list that has already been put in order. In many 240 IF T>=A(J) THEN GOTO 280
applications you will be dealing with an ordered list and under such 250 LET A(J+1)=A(J)
circumstances this is the appropriate method to use. 260 LET J-J-1
270 LET J>=1 THEN GOTO 240
In the program the binary search technique is in lines 500 to 600. 280 LET A(J+1)=T
The basic idea is to compare the wanted number with the middle item 290 NEXT I
of the ordered list. The wanted item is then either smaller (in which 295 REM ***ENDSOR'f***
300 PRINT "SORTED LIST"
case we know it is in the first half of the list) or larger (in which case it is 310 FOR M=1 TO N
in the second half of the list) than the middle item, unless it is equal to 320 PRINT A(M);" ";
it — in which case we have completed our search. The process is 330 NEXT M
340 PRINT
repeated, in each case halving the list. Consider a search for 30 in the 350 PRINT "TYPE NUMBER REQUIRED"
following list: 360 PRINT "BETWEEN 100 AND 199"
370 PRINT "TO FINISH TYPE 999"
380 INPUT X
1 2 4 6 8 10 12 14 16 18 20 24 28 30 36 390 IF X=999 THEN GOTO 700
400 PRINT
We first choose 14 (middle).
311
410 PRINT "SEARCH ";N;" ITEM LI
• •
technique, here is a simple example that doesn't require you to INPUT
ST"
500 REM **BINARY SEARCH**
anything. Key in and run the first program to create A(N) and fill it
510 LET L=1 with random numbers. Edit the program, replacing the original lines
520 LET H4
with those of the second program. SAVE this program. LOAD it back
530 LET C=0
540 LET M=INT ((H+L)/2) in. If we used RUN it would clear all the variables, and wipe out the
550 LET Cß+1 array we have stored.
560 IF X =A(M) THEN GOTO 630
Program execution must be started with a GOTO statement, in this
570 IF L>-H THEN GOTO 660
580 IF X>A(M) THEN GOTO 610 case GOTO 10. The array will then print out.
590 LET H1-1
600 GOTO 540 10 DIM A(40)
610 LET L44+1 20 FOR N=1 TO 40
620 GOTO 540 30 LET A(N)=INT (100*RND)+100
630 PRINT "NUMBER FOUND ";X 40 NEXT N
640 PRINT "AFTER ";C; " SEARCHES"
10 REM "SAVED*ARRAY"
650 GOTO 350
660 PRINT "NUMBER NOT FOUND" 20 REM **EXECUTE PROGRAM**
670 PRINT "AFTER ";C;" SEARCHES" 30 REM **USING GOTO 10**
40 PRINT "LIST OF RANDOM NUMBERS"
680 GOTO 350
690 REM **END SEARCH** 50 PRINT "BETWEEN 100 AND 199"
60 FOR N=1 TO 40
700 REM **END**
70 PRINT A(N)
80 NEXT N
Results:
So this is the general procedure:
TYPE NUMBER <50 (1) Write an array creation program and run it, i.e. A(N) created
UNSORTED LIST and data inserted.
144 128 117 118 101 189 111 198 (2) Edit out lines and put in additional lines as required.
150 107 188 197 172 106 157 148 (3) SAVE the final program.
168 160 130 181 100 165 175 133 (4) LOAD program and execute using a GOTO statement.
186 190 155 167 199 138 122 163
To avoid the possibility of the user entering RUN, we can use a
131 142 113 143 154 194 119 153
structure which automatically initiates the program on loading. The
SORTED LIST program below for the ZX81 also illustrates the fact that one may use a
100 101 106 107 111 113 117 118 string variable as a program name.
119 122 128 130 131 133 138 142 Lines 10 to 80 create array and have the input routine. These lines
143 144 148 150 153 154 155 157 could be edited out as soon as the data was input, or left in to enable
160 163 165 167 168 172 175 181 (through the use of RUN) a different set of data to be input.
186 188 189 190 194 197 198 199 Line 90 onwards are the program to use the stored data.
TYPE NUMBER REQUIRED Line 9010 requests a string input to be used as the program name.
BETWEEN 100 AND 199 9020 gets the string, and 9030 and 9040 give you the chance to write it
TO FINISH TYPE 999 down before you forget.
9050 waits for a key to be pressed, and 9070 saves the program and
SEARCH 40 ITEM LIST its variables. One of these variables stores the line the computer had
NUMBER FOUND 198 got to in the program, and when loaded back it starts where it left off
AFTER 5 SEARCHES (9070) and goes to line 90 automatically.
10 REM **AUTO-RUN ROUTINE**
T10: Storing a List 20 REM AUTOMATIC RUN WILL
PRESERVE VARIABLES
30 REM AVOID STATEMENTS
We can store data in an array for use in a program via INPUT loops OR EDIT THEM OUT.
when there is more data to be inserted than we care to put directly in 40 REM ***DIMENSION/INPUT,10
STORE VARIABLES***
the program using LET instructions. There are progra ms in the text 50 DIM A(20)
that use this technique (e.g. "ELEMENT"). To illustrate the 60 FOR F=1 TO 20
312
313
70 INPUT A(F)
80 NEXT F
• •
100 DIM AS (704)
110 FOR I=0 TO 21
90 PRINT "PROGRAM TO USE DATA" 120 FOR J=1 TO 32
100 FOR F=20 TO 1 STEP -1 130 LET A$(J+32*I)=CHR$ PEEK (PEEK
110 PRINT A(F) 16396+256*PEEK 16397+J+33*I)
120 NEXT F 140 NEXT J
130 REM ......MORE PROGRAM 150 NEXT I
140 REM
8990 REM **SAVE AND AUTO-RUN**
9000 CIS 5 REM "PRETTY2"
9010 PRINT "INPUT PROGRAM NAME" 10 PRINT AS
9020 INPUT A$
9030 PRINT "PROGRAM NAME:";A$ Notice that we have stored the screen display in the array.
9040 PRINT "READY TO SAVE.NOTE P
ROGRAM NAME.PRESS A KEY TO Check you understand the process of PEEKing the display file.
SAVE PROGRAM","AFTER SETTI The Spectrum stores a screen display using a special form of SAVE.
NG CASSE TT E TO RECORD*****" This has the form: SAVE "PRETTY" SCREEN$, where PRETTY
9050 IF INKEY$=" " THEN GOTO 9050
9060 C LS can be any name. This is loaded back using LOAD "PRETTY"
9070 SAVE A$ SCREEN$.
9075 REM **GOTO LINE AFTER DIM/
INPUT ROUTINE IF NOT EDITED Try this procedure on your Spectrum. The program above can be
OUT** revised for the Spectrum. Enter just the following lines:
9080 GOTO 90
10 FOR J = 1 TO 40 STEP 4
The Spectrum has an automatic message and built in wait-for-key-
20 FOR N = 0 TO J* 12 STEP 4
press routine. It also has an automatic run-after-LOAD facility. If a
30 PLOT 125 +J*2*SIN(N/(J*6)*PI),88 +J*COS(N/(J*6)*PI)
line is entered in a program of the form:
40 NEXT N
50 NEXT J
9000 SAVE "program" LINE 200
Use SCREEN$ to save the picture as above. To continue with screen
and the program is saved with a GOTO 9000, the program will start
displays, the Spectrum can store a screenful of characters in much the
running after loading by going to the line stated (200 in the example).
same way as the ZX81 program above, using SCREEN$ to access each
For the Spectrum, this program needs modifying by deleting lines
character in turn, placing them in sequence in array A$(704). A
9070, 9075, 9080, changing 9040 to read PRINT"NOTE
screenful of characters is generated at random, using the single
PROGRAM NAME", 9050 to PAUSE 0, and 9060 to SAVE
A$ LINE 90. characters from the Spectrum character set, placing these along each
line.
The double loop (lines 60 to 100) uses SCREEN$ (F,N) to check
T11: Storing a String Array
each character along each line, placing it in the array AS.
The ZX81 program PRETTY draws a picture on the screen (slowly!)
which is stored in the array A$, dimensioned in line 100. If this ^ DIM A$(704)
10 FiiF: F =i, TO 21
program is run the array AS is created, and the screen display stored,
20 FOR N =0 TO 31
character cell by character cell, in A$. The lines in the program can be 36 PRINT AT F, N; CHR$ ( 32+ F:ND
edited out so that finally we have a program like PRETTY2. This may +97)
be SAVEd and includes the created array A$. To execute the program 40 NEXT N
50 NEXT F
PRETTY2 after loading we must use GOTO 5, to avoid the use of ,_-:^i FOR F =0 Ti i 21
RUN, which clears all arrays (and hence A$) before execution starts. 70 FOR N=i, TOi 31
S O LET A$(N +1 +32*F)= SCREEN$
5 REM "PRETTY" (F,N)
10 FOR J=1 TO 10 90 NEXT N
20 FOR N=0 TO J*12 100 NEXT F
30 PLOT 32+J*2*SIN (N/(J*6)*PI),
22+J*COS (N/(J*6)*PI)
40 NEXT N Now edit out all the lines, replacing 5 with 5 PRINT A$, and RUN the
50 NEXT J
program using GOTO 5.
314
315
•
The same program for the ZX81 needs to use PEEK to access the
•
The next program has the full names of the months, with varying
display file, just as in "PRETTY". Replace lines 5 to 50 in lengths. Full stops are used to make the principle clear, but spaces
"PRETTY" with the following, to print a random set of ZX81 between the months would be used in a practical program. (As it is, a
characters on the screen: full stop is printed after the month, rather than the useful space.) The
program stops the search after the required month has been found (line
5 REM "SCREENFULL" 100), but is a little slow on the ZX81 unless FAST is used (line 65).
10 FOR F=1 TO 704
20 PRINT CHR$ INT ( RND *64); 10 REM STRING DATA STORE
20 NEXT F 20 REM *A$ HAS DATA*
25 REM **USE SPACES,NOT FULL S
TOPS IN REAL PROGRAM**
30 LET A$=".JANUARY.FEBRUARY.M
The same principle holds good for any string array or numeric array. ARCH.APRIL.MAY.JUNE.JULY.AU
GUST. SEPTEMBER.00TOBER.NOVE
Once the program has been run and the data inserted into the array,
MBER.DECEMBER."
the data is safe as long as RUN is not used again, and can be accessed 40 REM *DATA INPUT*
as required. The ELEMENT program treated in Unit W3 uses this 50 PRINT "INPUT MONTH(1 TO 12)
procedure to store data required in the program.
60 INPUT MONTH
65 FAST
Exercise 70 LET P=0
80 LET A=1
90 IF A$(A)="," THEN LET P=P+1
Write the appropriate array creation program for the following 100 IF P=MONTH+1 THEN GOTO 140
program: 110 IF P=MCGTH THEN PRINT A$(A+
1);
120 LET A=A+1
10 REM "SAVE10" 130 GOTO 90
20 REM **THIS PROGRAM MUST BE** 140 SLOW
30 REM **EXECUTED USING GOTO10** 150 PRINT "IS THE MONTH INPUT"
316 317
s
25 REM *DATA INTO STRING*
30 FOR F=1 TO 10
•
SECTION U: THE COMPUTER MEMORY
40 INPUT NUMBER
50 LET A$=A$+STR$ NUMBER+"*" U1: Memory Organisation
60 NEXT F
70 REM
80 REM Digital computers operate with sequences of numbers in the binary
90 REM number system. Binary numbers are numbers to base 2, and our
95 REM *RESTORE START* `normal' number system is decimal (base 10).
100 LET NSTRING=0
110 FOR F=1 TO 5
120 GOSUB 1000 The BINARY system uses only two digits, 0 and 1. These are
130 LET A(F)=VAL Z$ binary digits (bits). The computer holds a bit as a voltage level
140 NEXT F
150 FOR F=10 TO 6 STEP -1 (+ 5v or 0v) in a switched pathway.
160 GOSUB 1000
170 LET A(F)=VAL Z$ In the decimal system, a number, for example 418, is coded as a number
180 NEXT F
190 REM using the digits 0 to 9. The coding is based on powers of ten. 418
200 REM means: (4 times 10 to the power 2) + (1 times ten to the power 1) + (8
210 STOP times ten to the power 0).
995 REM ***READ STRING SUB***
1000 LET Z5="" (4x10'2) + (1x10') + (8x10")
1010 LET NSTRING=NSTRING+1
1020 IF A$(NSTRING)="*" THEN RET 400 + 10 + 8 = 418
URN
1030 LET 2$=Z$+A$(NSTRING) The binary system of coding uses powers of two in exactly the same
1040 GOTO 1010 way.
The number 13 is represented as:
20 INPUT N
30 PRINT N;
40 LET B$=""
50 LET L=INT (N/2)
60 LET B=N_2*L
70 IF B=1 THEN LET A$="1"
80 IF B=0 THEN LET A$="0"
90 LET B$=A$+B$
100 LET N=L
110 IF L>0 THEN GOTO 50
120 PRINT " IS ";B$;" IN BINARY"
Input sequences of numbers to familiarise yourself with the binary
system. The program only deals with positive whole numbers. Trace
318 319
^ •
the progam to see how it works, using the examples 13 and 46 given Spectrum has 16k of ROM and either 16 or 48k of RAM. The memory
above as inputs. Non-integer numbers are dealt with by using an is organised as shown in the diagrams below (called memory maps).
exponent, as with the E notation system for decimals. Binary numbers The ZX81 and Spectrum have somewhat different memory
have a binary point, and bits to the left of the point are binary fractions, organisations. We will deal first with the ZX81, and then the
representing the reciprocal power of two. The binary number 1.101, Spectrum. Spectrum users should read through the ZX81 section,
for instance, represents: however, as definitions of the functions of various types of memory are
covered in this Unit.
1 0 1
(1x2°)+(2' )+)+(2') ZX81 MEMORY MAP
1 + .5 + 0 + .125 = 1.625
Address Contents
You may have noticed that binary numbers as seen above are all 12767
positive. Negative numbers are dealt with by using a particular form of GOSUB STACK
16384
Memory is of two types: Unused addresses. No memory
READ ONLY MEMORY (ROM) is fixed and cannot be
space exists for this area.
altered. It contains the BASIC interpreter program, and is 8192
built-in to the computer in manufacture. ROM memory area. BASIC
RANDOM ACCESS MEMORY (RAM) is variable, multi-
interpreter and operating
purpose memory that holds the current program and all the
system program.
other elements of data required to run the program. 0000
Data can only be extracted from ROM (`read'), and is permanent. The top of memory (RAMTOP) is usually set as shown on switch-on,
RAM memory can be both read from and written to. Inserting a value at 32767. The computer can be instructed to set RAMTOP at some
into a memory location in RAM (writing or storing) will wipe out or lower value, to leave spare memory locations which can be used to
store machine code programs, which are called (like subroutines) from
overwrite the existing data at that address.
Memory capacity is referred to as the number of Kilobytes (k) the BASIC program with the USR instruction. Machine-code
programming is outside the scope of this text.
involved. Kilo refers to one thousand, but this is only approximately
Some areas of memory are organised in the form of a stack. This is a
true, since a kilobyte is actually 1024 (2"') bytes. The ZX81 has 8k of
ROM memory and, with the memory expansion, 16k of RAM. The system such that the last item entered will be the first to be pulled off
320 321
•
the stack. A number may only be placed on the top of the stack of SPECTRUM MEMORY MAP
Address
•
Contents
existing numbers, and the only accessible number is the one on the top.
32767 (16k)
This creates an ordered sequence. In the GOSUB stack this is used to 65535 (48k)
USER DEFINED GRAPHICS
ensure that the RETURN instructions are followed in correct RAMTOP
sequence. Each GOSUB instruction causes the following line number GOSUB STACK
to be added to the stack. RETURN then takes the first line number off
MACHINE STACK
the stack to get the correct line number to pass control of the program
back. SPARE MEMORY
The machine-stack memory area is used to keep track of the
operation of the program. The spare memory area is that portion of the CALCULATOR STACK
allocated area not occupied by the program and other memory areas.
Although we referred to the lop of the stack, it is more correctly the free WORKSPACE (TEMP.STORAGE)
end of the stack on to which the numbers are placed. The free end of
the machine stack is at the bottom, in terms of the memory address VARIABLES STORAGE AREA
sequence, hence the spare memory is below the machine stack in our
RAM
diagram. PROGRAM AREA
program. They are held in various forms, and we shall deal with the 23734
SYSTEM VARIABLES
way numbers and variables are stored in the next Unit.
The display file has been covered in Section Q. The program area 23552
PRINTER BUFFER
contains the program lines. This area always starts at address 16509.
23296
All other memory areas ride on top of the program area, moving up or
ATTRIBUTES FILE
down as the program lengthens (has program lines added or inserted)
22528
or shortens (has lines deleted), apart from the GOSUB and machine
DISPLAY FILE
stacks, which are always at the top of memory.
16384
The systems variables area holds the special variables which store
information concerning the state of the computer for use by the
operating system. Certain of the system variables were introduced in ROM AREA. BASIC INTERPRETER
Section Q. Like the D-FILE system variable introduced there, some of
AND OPERATING SYSTEM PROGRAM
these variables hold the addresses of the divisions between the areas of
memory. Other variables hold values of addresses, line numbers, 0000
characters, etc., to keep track of what state of affairs is current in the The memory map of the Spectrum memory is somewhat different from
operating system. You have seen, for instance, that the DF-SZ variable that of the ZX81. The Spectrum also comes in two versions, one with
stores the number of lines on the lower part of the screen. Some other 16k of RAM, one with 48k. The ROM is also larger on the Spectrum,
system variables are dealt with in the next Unit. There are a fixed occupying 16k. Thus the first 16k of memory addresses (0000 to 16383)
number of system variables, and their values are always held at known are occupied by ROM on the Spectrum. A 16k version then has the
addresses between 16384 and 16508. The names of the system next 16k of memory as RAM, up to address 32767. The 48k Spectrum
variables are not recognised as BASIC variable names, but are just uses addresses 32768 to 65535 for the additional RAM memory. Apart
mnemonics for the system variable function. from the size of memory, the arrangement of memory is the same in
On the ZX81 there is no memory corresponding to addresses both Spectrum versions, as shown on the diagram. The fixed memory
8193-16383. Addresses 0 to 8192 contain the system software in ROM points are given as the memory address.
which holds the BASIC interpreter and operation program in machine The Spectrum memory requires more separate areas (reserved for
code. the additional functions of the Spectrum), and the organisation is
somewhat different. Working from the top of memory down, we notice
an area set aside for user-defined graphics. This occupies 168 bytes,
322 323
•
and is set at the actual top of the memory, which is referred to as
•
for program and operating areas, and illustrates the fact that high-
Physical RAMTOP. The bottom of the user-defined graphics area is resolution graphics take up large amounts of memory.
the RAMTOP that the computer recognises as the top of memory. Below 16384, the memory addresses are all ROM memory. The
This leaves the user-defined graphics area protected from any more complex operating system of the Spectrum demands more
interference by the operating system. On switch-on, the address of instructions in ROM than are required by the ZX81. There is no gap
RAMTOP is thus set at 65367 with a 48k Spectrum, 32599 on a 16k in memory at all on the 48k machine, all 64k of memory that the Z80A
version. This is the memory address of the last existing byte of memory chip (the central processing unit) can address being used. On the 16k
before the user-defined graphics area. Below this are the GOSUB stack Spectrum, of course, the memory addresses above 32767 are unused.
and the machine stack, with the area of free memory below this, as on
the ZX81. U2: PEEK and POKE
The calculator stack, work space for lines being keyed in or data
being processed, and the variables storage area are all in the sequence The PEEK and POKE instructions have been introduced for specific
followed by the ZX81 memory. Then we have a significant difference purposes in connection with the display file and character storage. This
between the two memories. The display file on the Spectrum is fixed, should have given you some understanding of their uses. Now that you
and does not appear above the program area, but at the bottom of have been introduced more generally to the way memory is stored in a
RAM. Between the program area and the display file are Spectrum- computer, you will notice that these instructions provide direct access
specific areas, concerned with input and output and colour. The to the memory of the computer.
channel information area has information required for the operation of
the printer, the keyboard, and the TV screen in terms of its division
PEEK N returns the value (in decimal notation) of the
into top and bottom screens, the bottom one expanding if necessary to
number stored in binary form in the memory byte of address
contain the required lines. This area is adjacent to an area of memory
N. In the ZX81, N must be in the range 0 to 8192 to return
that will be used to store data necessary for the operation of the Sinclair
the contents of ROM memory, and in the range 16384 to
microdrive disc system when it becomes available and is attached to a
32767 to return the contents of RAM. For the Spectrum,
Spectrum. This area `vanishes' without the microdrive and there is no
ROM extends from 0 to 16383, RAM from 16384 to 32767
sequence of memory bytes allocated to it. This area begins at address
(16k version) or 65535 (48k version).
23734. Without the microdrive, this address becomes the start of the
channel information area.
POKE M,N places into the memory address M the binary
System variables occupy 182 bytes of memory, from 23552 to 23733
form of the decimal number N. N must be in the range 0 to
inclusive. The printer buffer on the Spectrum is larger than that on the 255 (to fit in a single byte). For the ZX81, and 16k Spectrum
ZX81 because of the need to store information about each of the 8*8
M must be in the range 16384 to 32767. The 48k Spectrum
points in a character cell (where the ZX81 only needed to store
uses addresses up to 65535. ROM may not have values
character codes). The buffer, to store a full line for the printer, needs POKEd into it.
256 bytes. This is because each line of points in a 32 character line
needs 8*32 bits, and there are 8 of these lines needed to make up a line
on the printer. This buffer occupies the bytes from 23296 to 23551 In general, we use PEEK to extract from memory any values useful to
inclusive. our program, and POKE to insert values into memory. Remember
The colour attributes (see Section W for this) occupy one byte per that the values (entered and returned in decimal notation) can be
character cell, so the storage is 24*32 bytes from 22528 to 23295. These numbers, characters or instructions. Machine-code programming is
store the information about the colour (background and printing performed by POKEing into a specified sequence of addresses the
colour), brightness and flashing characteristics of each PRINT values which correspond to instructions which the Z80 central
position. This information, together with the display file, determines processor chip understands. This sequence of instructions is then called
the screen display. The display file holds the information about the from within a BASIC program, in a similar fashion to calling a
pattern of dots to be placed on the screen, and the attributes file the subroutine, and is executed. At the end of the machine-code program,
additional data for a colour display. The display file occupies the a return instruction passes back control to the BASIC program.
memory addresses from the start of RAM (16384) to 22527. This is We will use PEEK to investigate how numbers and program lines
6144 bytes, so we can note that on a 16k Spectrum some 42% of RAM are stored in the ZX81 and Spectrum. Different types of number have
is needed for the display and attributes files only. This leaves about 9k different formats in which they are held. The normal number in
324 325
^
memory is held in 5-byte floating point binary form. Each number is stored
•
16553 37 9
in 5 bytes of memory. 15554 22 -
16555 122 ?
The line numbers in a program are stored in 2 bytes of memory. 16556 107 7
Numbers in a program listing are stored as their printed characters, 15557 118 .
16558 0
then in 5-byte form. 16559 40 C
16560 15 .
Enter the program below if you are using a ZX81. It PEEKs the 16561 0
16562 241 LET
memory locations from address 16509 onwards, i.e. each address in 16563 38 R
16564 20 =
memory from the start of the program listing, after printing out the 16565 29 1
16565 34 6
numbers as instructed in the first three lines, and prints the address, 16567 33 5
16568 28 0
contents of the address as a decimal number, and the character string 16569 37 9
corresponding. The corresponding program and output for the
Notice first the way the ZX81 changes the format of the numbers. 23
Spectrum is given after the ZX81 has been dealt with, since the
prints as 23, but 123E8 is printed as 12300000000, and 123E-8 as
character codes are different.
1.23E-6. The operating routines put each number into a standard
5 REM "PROGLIST" format for printing to the screen. In order to present a listing of the
10 PRINT 23
20 PRINT 123E8 program, which is what you've typed in, the computer must hold two
30 PRINT 123E-8 forms of the number; first the literal characters and second the 5-byte
40 LET A=16509 floating point form.
50 PRINT A;TAB 10;PEEK A;TAB 1
5;CHR$ (PEEK A) Inspect the printout from the program. The first address printed is
60 LET A=A+1 16509, holding zero. This is the first of the two bytes holding the line
70 GOTO 50 number. Notice that the more significant byte comes first. This is the other
You will get a display (use COPY to get a printer listing, and CONT to way round from normal 2-byte values (those of the system variables,
for example). Since the line number is less than 255, the first byte holds
continue) that looks like this:
zero and the second (16510) holds 10.
23 16511 holds 10 again. This is the number of characters in the line.
12300000000
1.23E-6 16512 has zero, since these two bytes hold the line number as (First
16509 0
16510 10 byte value) + 256* (Second byte value), in the standard way.
16511 10
16512 0 16513 holds the value 245, representing the keyword character
16513 24-5 PRINT
16514 30 2 PRINT. Then come the characters 2 and 3 (codes 30 and 31). Bytes
16515 31 3
16516 126 `' 16516 to 16521 hold the values 126, which indicates that the next
16517 133 1
15518 55 5 sequence of bytes holds a number, and then 133,56,0,0,0. This is the
16519 0
16520 0 5-byte form of 23. We shall see in the next Unit the mechanics of this
16521 0
15522 115 . way of representing numbers.
16523 0
16524 20 = Check through the rest of the listing and make sure that you
16525 13 $
16526 0 understand how and why the memory addresses contain the values
15527 245 PRINT they do.
16528 29 1
16529 30 2
16530 31 3
16531 42 E SPECTRUM PROGRAM LISTINGS
16532 36 8
16533 126
16534 162
16535 55 R The program below for the Spectrum has a different form from that for
16536 72
16537 198 LEN the ZX81. This is a consequence of the strange results of the control
16538 192 "
16539 118 ? characters in the Spectrum character set if used as a CHR$ (see Unit
16540 0
16541 30 2 P2). We must avoid using a PRINT CHR$ instruction for these
16542 14 .
15543 0 control characters. The program sets a logical condition to test the
16544 245 PRINT
16545 29 1 value of A in lines 60 and 70 which prints "CONTROL CHR"
16545 30 2
16547 31 3 instead of the CHR$ form if the printing of the CHR$ would cause
16548 42 E problems.
18549 22 -
15550 35 8 10 PRINT 23
16551 126 ? 20 PRINT 123E8
16552 109 .
30 PRINT 123E-8
326 197
40 LET A=(PEEK 23635+256*PEEK automatically done by the operating system) the program prints the
23636) first address (23755), which is the first byte of the program area. It then
50 PRINT A;TAB 10;PEEK A;TAB 1 prints the value stored in this byte, followed by the character code (if
5;
60 IF PEEK A>23 OR PEEK A<15 T it's not a control character). Codes not corresponding to a character
HEN PRINT CHR$ (PEEK A) with a printed form produce a question mark.
70 IF PEEK A<=23 AND PEEK A>=1 The first two bytes hold 0 and 10. This is the line number, stored,
6 THEN PRINT "CONTROL CHR"
80 LET A=A+1
unlike all other two-byte numbers, with the more significant byte first.
90 GO TO 50 The next two bytes hold the number of characters in the line, stored in
normal fashion, with the least significant byte first. We then have code
The results will be as follows. (Use scroll to see the full listing. To get a
245, which is the keyword PRINT, the first instruction in the line. This
printout like the one here, you must BREAK the program when is followed by the characters 2 and 3, for printing in the program listing.
"Scroll?" appears, then use COPY, then CONT to get the next
This is followed by code 14, which is a control code indicating that the
screenful.) next 5 bytes are to be interpreted as a number. There are then five
23 bytes storing the number 23, in the special form in which the Spectrum
1.23E+10
1.23E-6 handles integers. We will deal with this in the next Unit. Notice that
23755 0 ?
23756 10 ? the code 14 defines for the Spectrum the way in which a character or
23757 10 'Z
23758 0 ? number (stored in the same binary form in a memory byte) is to be
2375 9 245 PRINT
23760 50 2 interpreted.
2 3 761 51 3
23762 14 After the five bytes of the number comes the ENTER character (13),
23763 0
23764 0 ? signifying the end of the program line. Addresses 23772 and 23773 hold
2376 2`= CNTROL.
O CHR
23766 y ? the next line number, then comes the number of character bytes in the
23767 0
line, and so on. Note that the number 123E8, which was input in this
23768 13
23769 0 form, is stored as this sequence of characters, even though it prints in a
23770 20 CONTROL CHR different form, due to the operating system using the five-byte form to
23771 13
23772 0 '' decide what number is to be printed.
23773 245 PRINT Trace the program further than the third line we have included in
23774 49 1
23775 50 2 the printout, and ensure you can follow the program line arrangement,
23776 51 3
23777 69 E as we will refer to this in connection with a program to renumber
23778 56 8
23779 program lines automatically later in the text. Although the Spectrum
1662 5
23781 55 7 and ZX81 character codes are different, the program line arrangement
23782 72 H
23783 198 AND is the same.
2784
3 192 U5R
23785 13 Because we know that the address at which a program listing starts
23786 0 ? can be found, and the format of the program listing in memory, we can
23787 30
23788 14 ? use PEEK to extract data from a program line. This can be useful to
23789 0 ?
23790 245 PRINT store data. Enter and run the program below. You should be able to see
23791 49 1
how it works. Remember that the first character after the line number
23792 50 2
23793 51 3 (two bytes) and the line length (two bytes) will be the REM statement.
23794 69 E
23795 45 -
The characters to be PEEKed will follow this. 5 bytes therefore need to
23.96 56 8
23797 14 ? be added to the start address of the program area.
23798 109 m
23799 37 % The Spectrum user needs to use the PEEK expression to find the
23800 22 CONTROL CHR
23801 122 start of the program (the address given by M):
23802 107 P.
23803 13
10 REM RIALCNI'=.
The PEEKs in line 40 set A to the value of the first memory address of 20 LET M= PEEK 23635+256* PEEK
the program storage area. (See the description of the System Variables 23'..36
30 F'RINT AT 10, 10
in the next Unit.) Unlike the ZX81 the Spectrum program area moves 40 FOR F=7 TO 0 STEP -1
around in memory. 50 PRINT CHR$ PEEK (M+5+F);
After printing the numbers, in a revised notation, setting the 6.0 NEXT F
exponent values to have the decimal point after the first digit (a task
329
•
On the ZX81, the start of the program area is fixed. 5 can be added to
•
9020 LET LINE=10
9030 LET STEP=10
this to give the address of the first byte of memory we are interested in 9040 POKE RAM,INT (LINE/256)
(16509 + 5 = 16514). 9050 POKE NAM+1,(LINE-256*PEEK R
AM)
10 REM RIALCNIS 9060 LET RAM=RAM+1
20 PRINT AT 10,10; 9070 IF PEEK RAM<>118 THEN GOTO
30 FOR F=7 TO 0 STEP -1 9060
40 PRINT CNRS PEEK (16514+F); 9080 LET RAM=RAM+1
50 NEXT F 9090 IF 256*PEEK RAM+PEEK (RAM+1
)=9000 THEN GOTO 9120
The reverse procedure is also possible, using POKE. Try this 9100 LET LINE=LINE+STEP
9110 GOTO 9040
program. 9120 LIST
ZX81: 9130 STOP
10 REM ABCDEFG
20 FOR F=0 TO 6 Modifications for the Spectrum are required as follows: Line 9010
30 POKE (16514+F),29+F must be edited to read LET RAM = PEEK 23635 + 256* PEEK 23636.
40 NEXT F Line 9070 must be changed to 9070 IF PEEK RAM<>13 THEN
GOTO 9060.
Spectrum: Line 9010 sets a variable RAM equal to the start of the program
10 REM ABCDEFG area. LINE (the line number to start the new listing) and STEP (the
20 LET M=PEEK 23635+256*PEEK 23636 increment of the line numbers) are both set at 10, but could take any
30 FOR F=0 TO 6
40 POKE (M+5+F),48+F desired values. 9040 and 9050 POKE into the first and second bytes,
50 NEXT F which hold the line number, the value 10. Into the first byte goes the
line number divided by 256, the INT function turning this to an
The Spectrum program again uses a PEEK to find the program area
integer value. If non-integer values are POKEd into an address, they
start address, and the different character codes require different values
are automatically rounded, but to the nearest whole number, which
added to F to give the same result.
does not give us the desired result if the remainder is 0.5 or greater.
Run the program, then LIST it and see what has happened to the
Into the second byte goes the line number less the value in the first
REM statement. If you want an illustration of the care needed when
byte, obtained by PEEKing the byte and multiplying by 256.
POKEing into programs, try setting F = 0 TO 8 and run the program Lines 9060 and 9070 increment the address and check if the address
again. LIST it, and then try to edit your listing. The ZX81 may crash,
contains the NEWLINE (ENTER) character (code 118 on the ZX81,
and if your screen blanks out or produces other strange effects you will
code 13 on the Spectrum), repeating until a new line is found, which
have to reset it by pulling out the power supply plug and re-inserting it.
marks the end of a program line. 9080 adds 1 to RAM, giving the start
The Spectrum is more tolerant of this sort of treatment, and will just address of the next program line.
give an error message, but the program listing is corrupt, and NEW
Line 9090 checks the value (line number) held in this and the next
will have to be used. byte, to see if the process has reached the start of the renumber
Storing information in a REM statement in this fashion, given that program, passing control to 9120 for listing if it has. 9100 increments
as you have seen it can be accessed with PEEK and updated with the line number by the step value and control is then passed back to
POKE, can provide a useful alternative to storing data in variables.
line 9040, and the new line number POKEd into the first bytes of the
The layout of the program listing in memory, starting at a known next program line.
address, enables us to write a program which will renumber the Notice that the program checks each byte in turn. Another way to
program lines. Here's the program for the ZX81: find the address of the end of the program line, which prevents the need
1 REM "RENUM" for this, is to use the data about line length stored in the third and
2 REM REPLACE LINE AND STEP
30 REM VALUES IF START LINE fourth bytes of the program line. To do this, delete line 9080 and
45 REM OR STEP VALUE TO BE replace lines 9060 and 9070 as follows:
DIFFERENT
50 REM RUN IN FAST MODE FOR
121 REM LARGE PROGRAMS 9060 LET LENGTH = PEEK(RAM + 2) + 256*PEEK(RAM + 3)
1001 REM **YOU MUST REMEMBER** 9070 LET RAM = RAM + LENGTH + 4
1002 REM ***GOSUBS AND GOTOS***
9000 REM ***RENUMBER***
This finds the line length, and adds this, plus 4 for the bytes holding
9010 LET RAM=16509
331
•
line number and line length, to the current RAM value, giving the
address of the first byte of the next line.
•
significant byte) + 256* (value of most significant byte). Except in the
case of line numbers for program lines, the first byte is the least
significant byte of any two-byte number.
Remember, to use a program like this on the ZX81, you should
LOAD it before you start to program, and use RUN 9000 when you The set of system variables we will look at are those variables which
have developed your program. You will also need a STOP instruction hold the addresses of the boundaries between areas of memory. Since
before line 9000 to prevent your program renumbering itself every time some memory areas move around, the computer must know where
you run it. The REM statements are not necessary to the program in each area starts. We can also use this information to find out what the
the listing, of course, but do give the program something to renumber current state of memory organisation is for use in various ways. Below
as a test. Note that GOSUB and GOTO destination line numbers are are tables of the ZX81 and Spectrum memory maps with the system
variables and their addresses. Note that the system variable names are
not renumbered, and you must edit the lines affected to suit the new
numbering. Take a printer listing or note down the relevant lines before just mnemonics. They are not recognised by the computer.
renumbering! On the Spectrum, a program can be MERGEd with one
already in memory, and added at any time. See Unit W2 for this ZX81: MEMORY MAP WITH SYSTEM VARIABLES
facility. Memory Area System Variable Addresses Contents Returned by:
Loading useful programs, joined into a subroutine or sub-program
toolkit, is worthwhile if you are developing a large program. This
might include, for instance, a sorting routine, error message and (Fixed) (16384)
format subroutines. As with the renumber program, which is deleted System
after use, any unwanted routines can be edited out. Variables
(Fixed) (16509)
A utility program like this should obviously have line numbers
Program
9000 + , and the variables used should not be single letter variables, or Listing
even variables such as A9, which might be needed in the main D-FILE 16396/7 PEEK 16396+256*PEEK 16397
Display
program. File
The program "TOOLS" in the program library illustrates the VARS 16400/1 PEEK 16400+256*PEEK 16401
principle, and provides a basis for you to add further useful Variables
44`) 333
^
program can be mostly data (although it must have program lines).
•
by POKE 16388,32662 - 256*INT(32662/256). Of course you could
use the computer to work these out beforehand, and POKE the values
However, this method will work on the Spectrum, and shows the
directly. NEW the computer, then enter this program and run it. On
technique of moving information around in memory. If you progress to
the Spectrum, RAMTOP is set with CLEAR, and can be done simply
machine-code programming, this is one way in which you can store by using:
machine code.
RAMTOP may be moved so as to reserve space at the top of
CLEAR (PEEK 23730 + 256*23731 - 106)
memory. On the ZX81, this area will not be affected by NEW or
CLEAR, or the automatic NEW that occurs with LOAD. It can be 5 REM "DSTORE"
used to store data for use by another program, after the data have been 10 REM **DATA ABOVE RAMTOP**
defined by a previous program. This procedure, available with less 20 DIM D(20)
30 FOR F=1 TO 20
complications on some computers, is performed as follows on the
40 LET D(F)=F*F
ZX81. 50 NEXT F
60 LET VARS =PEEK 16400+256*PEE
K 16401
i) New values are POKEd into the RAMTOP system variable, so
70 LET RAMTOP=PEEK 16388+256*P
that the system considers the top of RAM to be lower than EEK 16389
address 32767. This reserves space above the new RAMTOP 80 FOR F=0 TO 105
value. NEW is then used. POKEing RAMTOP has no effect 90 POKE (RAMTOP+F),PEEK (VARS +F)
100 NEXT F
until NEW has been used. How much space is reserved depends
on the number of bytes of data we require to store. (Spectrum: The first active line (20) dimensions the storage array. The loop of lines
See above for resetting RAMTOP.) 30 to 50 merely insert some values into the array. Lines 60 and 70 find
ii) The program to use the data must have been written and stored the values of VARS and RAMTOP. The loop of lines 80 to 100 stores
on cassette. This has instructions to copy into the variables area each byte of the variables store that contains array D above
the data stored. It must initialise the same variables or arrays for data in RAMTOP. Spectrum users must insert the correct PEEKs in lines 60
the same sequence as the program which provides the data. and 70 to get the values of the VARS and RAMTOP system variables.
iii) The program to store the data intialises the arrays or variables The same must be done with the data retrieval program below.
for the data first, before any other variables. The program is then Now use NEW, and enter the program to retrieve the data. This
run. The required number of bytes are taken from the start of reverses the procedure. After initialising D(20), and finding VARS
the variables area (found using VARS), and copied to the area and RAMTOP, it POKEs the value of each byte stored above
above RAMTOP (found using RAMTOP). RAMTOP into the bytes of the variables area containing the array.
iv) Program 2 is then loaded. It initialises the variables as did Lines 70 to 80 print out the array values.
program 1, finds VARS and RAMTOP, and reverses the 1 REM "DFETCH"
procedure, PEEKing RAMTOP and POKEing the values 5 REM **RETRIEVE STORED DATA
found into the variables area. It can then proceed to use the **FROM MEMORY ******
10 DIM D(20)
data. 20 LET VARS =PEEK 15400+256*PEE
K 16401
The amount of memory needed for storage is calculated from the 30 LET RAMTOP=PEEK 16388+256*P
EEK 16389
information given above about the method of storage of variables. As 40 FOR F=0 TO 105
an example, let us assume we want to store an array D(20) for use by 50 POKE (VARS +F),PEEK (RAMTOP+F)
another program. We will use this as a short example program. In 60 NEXT F
70 FOR F=1 TO 20
practice, the technique will require a second program to use the data to 80 PRINT D(F)
have been written and SAVEd, but the examples are short enough to 90 NEXT F
key in.
On the ZX81 only, you can use CLEAR: the array will be wiped from
Reference to the information about variables shows us that an array
memory, but remains safe above RAMTOP. Running the program
D(20) requires 106 bytes. On a ZX81, we must set RAMTOP as
again will retrieve the data once more. This is obviously a technique
32768 - 106 = 32662. This is the address of the first non-existent byte,
useful not only for passing data between programs, but also for
and will be the address of our first storage byte. To set RAMTOP to
allowing CLEAR to be used and still having current data (i.e. that not
this value, we POKE 16389,INT(32662/256) as a command, followed
343
•
assigned by LET statements) preserved. This does not apply to the accurately represented in the decimal system, however many decimal
Spectrum, since CLEAR re-sets RAMTOP. places are used. The same goes for many numbers in both decimal and
The complete list of system variables for both the ZX81 and the binary notation. If you study the display it should be apparent that
Spectrum is given in Appendix V. The timing variable FRAMES is with the binary system, only numbers equal to certain decimal values
used in the "REACT" program analysed in Unit V3. are accurately represented. Decimal .6875, equal to 1/2 + 1/8 + 1/16 is
accurately represented by binary .1011, for example, but with a single
MORE ON NUMBERS AND COMPUTERS byte (8 bits), any number varying by .001953125 (2 - s ) above or below
the value represented in the byte will appear the same to a computer
The way in which numbers are manipulated by the operating system in reading this byte.
a computer does not concern us here, but the way numbers are held, To increase the accuracy of representation of numbers, a larger
and their form, are important in computing, even if the precise manner number of bytes is needed. This also allows larger numbers to be dealt
in which calculations are carried out is a separate topic. We will deal with. The ZX81 and Spectrum use "5-byte floating point"
here with enough detail of the binary system to enable 5-byte floating representation of numbers. The "FLOAT" program gives the decimal
point to be understood. value held in each byte of the five by PEEKing the variables area:
We briefly introduced the binary system earlier. To explain further
1 REM *FLOAT*
the use of a system using powers of 2, and how any number can be
2 REM PRINTS FLOATING POINT
represented to a certain level of accuracy, key in this program: FORM OF A NUMBER
10 PRINT "ENTER A NUMBER"
10 REM "POWERS OF TWO" 20 INPUT N
20 PRINT "POWERS OF T40" 30 F'RINT "THE NUMBER "; N; " IS
30 PRINT " HELD", "IN THE ZX81 AS:-"
40 PRINT "2**N";TAB 10;"N";TAB 40 FOR F=1 TO
16;"2** -N" 45 REM PEEKS START OF VAF:IAE:LE
50 PRINT STORE (VARS) AREA IN MEMORY
60 PRINT TAB 6;"1 0 1.0" 50 PRINT PEEK ( PEEK 16400+256
70 FOR F=1 TO 16 * PEEK 14401+F);"
80 PRINT TAB( 17-LEN STR$ (2**F 60 NEXT F
));2**F;TAB 10;F;TAB (14+(F
>3));2**_F On the Spectrum you should change Line 50 to read PRINT PEEK
90 NEXT F (PEEK 23684 + 256*PEEK 23685 + F). Input only non-integer values
(we'll explain why this is the case a little later).
(Replace * * by T for the Spectrum at each occurrence in the program).
If you input 2.4, you will get a screen display of:
You will get a display like this:
344 345
100 PRINT "MANTISSA BYTE'S:-"
110 FOR F=2 TO 5
• •
floating point notation are positive, and an equivalent to the ` – ' sign is
needed to show negation.
120 PRINT TAD (F-2)*8 PEEK (F+
PEEK 16400+256* PEEK 16401); Input 0.75 into the computer when prompted. The display will be
130 NEXT F like this:
140 FOR F=2 TO
150 LET D= PEEK I (F+ PEEK 16400+
256* PEEK 16401) INPUT NUMBER
160 LET D$="" NUMBER = 0.75
170 LET L= INT (0/2)
180 REM LET A$=("1" AND D-2*L)+ EXPONENT = 128
("0" AND D-2*L=0) 2**0 = 1 (t on Spectrum)
181 LET A$= STR$ (D-2*L) MANTISSA BYTES:
190 LET B$=A$+E$
200 LET D=L 64 0 0 0
210 IF Li>0 THEN OUTO 170 01000000
220 IF LEN t-:$(8 THEN LET E:$="00 00000000
000000"(1 TO (8- LEN F$))+D$
220 PRINT TAD (F-2)*8; D$ 00000000
240 NEXT F 00000000
(Once again, on the Spectrum change ** to t at every appearance.
Line 50 needs to be changed to read LET EXP = PEEK (1 + PEEK The evaluation is as follows. The first bit is a zero in the mantissa. This
23684 + 256*PEEK 23685) to give the start of the Spectrum variables indicates a positive number. The first bit is changed to a 1, and the
area. Change 16400 to 23684 and 16401 to 23685 in lines 120 and 150 value of the mantissa is now .11000...0. The trailing zeros are ignored.
also.) Binary .11 is decimal 0.75 . The exponent value is 0, and 2 raised to
A number stored in 5-byte floating point notation has an exponent the power 0 is 1. So we have a value of 0.75*1 = 0.75. If you input
byte, which acts, as with the decimal E notation, to shift the binary – 0.75, the display is identical except for the first mantissa byte ( + 128)
point along to the correct place. because of the first bit now being 1, and the first mantissa bit, changed
The exponent value is stored as exponent plus 128, and can hence be to 1 to indicate a negative number. This is left as 1, and evaluation
negative or positive. It works in powers of two, and the value of this then proceeds as before.
(exponent raised to the power of two) is given in the program. The Now input 3.75. The exponent is 130, 2**2 ( Ton Spectrum) is 4,
representation of zero has a special form, such that the exponent is 0, and the mantissa bits hold the sequence 01110... The first bit changes
and the values of all the other bytes is also zero. The value stored in the to 1, and this gives .1111 binary, 0.9375 decimal. 4*0.9375 = 3.75 .
exponent byte is thus between 1 and 255, giving possible exponent The alternative way of viewing the process is to consider the exponent
values between – 127 and + 127. The range of numbers covered is as moving the binary point along. In this example, we have the
then what would be presented if our "POWERS OF TWO" program sequence .1111, and since the exponent value is 2, the binary point
went on to 127 rather than just 16. moves the same number of places to the right, to give 11.11 , which is
The mantissa value (represented in the next four bytes) is converted 3.75 in decimal. In the previous case, with 0.75, the exponent value
to the numeric value by multiplying it by 2 raised to the power of the was 0, so the point was not moved, and the bits were .11 . Negative
exponent: N = M*2`, where M is the mantissa value and e is the exponents move the binary point to the left, adding zeros.
exponent (value stored in exponent byte less 128). This process can The Spectrum has a special representation for integers in the range
also be considered as moving the binary point the number of bits given + 65535 to – 65535, in which the first byte (exponent byte) is zero, as
by the exponent. is the fifth byte. The second byte acts as a sign byte, holding 0 if the
The mantissa bytes are considered as a single sequence of binary number is positive, and 255 if the number is negative. The third and
digits, with the binary point at the beginning. The program gives the fourth byte hold the number (least significant byte first). You can use
values stored in each byte (as with the "FLOAT" program), and then the "FIVEBYTE" program to investigate this representation if you
converts to binary to give the mantissa sequence. Since the first bit of are using a Spectrum.
the mantissa sequence is always 1 (the mantissa is always between .5 To illustrate rounding errors and an otherwise puzzling aspect of the
decimal and 1 decimal, but never reaches 1, i.e. 0.5< = m<1) the first representation of numbers, input 1/2 into the "FIVEBYTE"
bit is used as a sign bit. If the number is positive, the first bit is changed program. We get exponent byte = 128, exponent 128 – 128 = 0, and a
to 0. If it is negative, the first bit is set to 1. This is used as a means of zero in the first bit. This changes to a 1, and we have .100.... Exponent
handling negative numbers, since all the numbers generated in the is zero, so we don't move the binary point and get .100...., which is
346 347
•
0.5, and equal to a half. Thus far all is well. If we like, we can consider
•
Hexadecimal system (often abbreviated to Hex) is primarily used in
that we got .100.... and multiplied it by zero to get our half. As we said machine-code programming which is beyond the scope of this text.
above, the two processes are identical. But now input 0.5. This should Whereas binary is base 2, and decimal base 10, hexadecimal is base 16.
be the same, but instead we get exponent equalling 127, and 0111....1 This is a convenient system for computers using 8-bit words, since
(thirty-one l's)! We seem to have an error. However it is a pretty small 16 x 16 = 256. Any value which is held in a single byte can thus be
one, though it explains why the computer rounds its numbers. To represented by a two-digit hexadecimal code. The system uses the
avoid considering 1/2 as not equal to 0.5 it has to take into account the digits 0 to 9, and goes on with A, B, C, D, E and F, to represent the
fact that the decimal to binary conversions have these inaccuracies. numbers 1 to 16. Here is how the system counts:
Binary addition of two l's causes a 0 to be placed in that byte, and a 1
Decimal Hexadecimal
is placed in the next column to the left. (If you're interested, the other
rules for addition are: 1 and 0 give 1, 0 and 0 give 0, three ones (1, 1
and a carried 1) give 1, carry 1 to next column on the left. Try a few 0 0 (QIx 16^)
simple sums!) This means that if a 1 is added to the least significant bit 1 1 (1 x 16 o )
of our sequence of ones:
9 9 (9 x 16 0z
10 A (10 x 160)
11 B (11 x 16°)
15 F (15 x 16^)
16 10 ( 1 x 16 11 ) + ( 0 x 16 0 )
(carry) 17 11 ( 1 x 16 ) + ( 1 x 160)
0
25 19 ( 1 x 16 1 ) + ( 9 16 0 )
1
(carry) 26 lA ( 1 x 16 ) + (10 x 16 ^ )
0
31 1F ( 1 x 16 1 ) + (15 x 16 0 )
(carry)
32 20 ( 2 x 16 1 ) + ( 0 16 0 )
etc
all the l's will become zeros, and the last carry would put 1 in the first 154 9A ( 9 x 161) + (10 x 16^)
bit, which would make it the same representation as the 1/2 sequence, 155 9B ( 9 x 16 ' ) + (11 x 16°)
but this also has a 1 in it. This forces a carry to a non-existent bit to the
left of the mantissa. This gives us 1.0 as our binary, and the exponent 159 9F ( 9 x 161) + (15 x 16^)
shifts this (exponent = – 1) to .100...., which is correct. Or we can 160 AO (10 x 16 1 ) + ( 0 x 16 )
consider this as 1.0 binary (1 decimal) multiplied by 2-'(0.5). So the
error is in the least significant bit. The size of the error is thus 2 " the
value of the right-hand 1. This is fairly small! The computer rounds 250 FA (15 x 16 1 ) + (10 x 16°)
numbers to ensure these inaccuracies do not cause errors. It considers
254 FE (15 x 161) + (14 x 16^)
numbers equal if the difference between them is less than a certain
255 FF (15 x 16 ) + (15 x 16°)
amount. Rounding errors can still build up under some circumstances,
however, and it is important to note that no computer performs totally As with any number system, we could go on (256 is 100 hex, etc.), but
accurate arithmetic, except with integer values. the use of hexadecimal is in representing binary numbers in a more
You may be a little overwhelmed by numbers at this point, but convenient form than strings of l's and 0's, which are difficult to read
before we give them a rest we should introduce you to another and easy to make mistakes with (unless you are a computer!).
numbering system – Hexadecimal. The advantage of hexadecimal notation is that any 8-bit binary
This is another numbering system much used in computing, number is convertible to hex far more easily than into decimal, due to
although it has no practical application for us at present since the the relationship of base 2 and base 16 numbers. Base 16 is base 2 4 , and
348 349
^
this means the 8 bits of a byte can be divided into two sets of four bits
(remember 1111 binary = 15 decimal = F hex) and converted to the
corresponding two hex digits. For example, the number 116 decimal is
in binary 01110100. Split into two groups of four bits, 0111 and 0100,
we convert each group to a hex digit.
PART FOUR
0111 binary (7 decimal) is 7 hex
0100 binary (4 decimal) is 4 hex
APPLICATIONS PROGRAMS AND
The number in hex is 74. Check this: (7 x 16') + (4 x 16') = 112 + 4 = 116.
Again, 93 decimal is 01011101 binary: GAMES
0101 binary (5 decimal) is 5 hex
1101 binary (13 decimal) is D hex
Exercises
350
• •
SECTION V: APPLICATIONS PROGRAMS
You have been introduced to the full set of ZX81 BASIC instructions.
Spectrum users have some additional instructions in the Spectrum
superset of BASIC, but we have attempted to show how all necessary
operations can be performed on the ZX81 and the Spectrum merely
makes some operations easier to implement. We have covered a range
of operations, involving loops, lists, array manipulation, sorting,
subroutines etc., and the implementation of control structures. These
are the raw material of programming. The combination of what you
have learned about algorithms, design, program structures,
manipulations and methods with the task you wish the computer to
perform produces an applications program.
There are no rules to derive algorithms. If there were, they could be
coded into a master program that would write our programs for us! We
have illustrated ways of thinking about a problem that can help, but
each program we wish to write presents a unique problem. Familiarity
with the language and control structures, and with existing solutions to
a variety of problems, either other people's or your own, make it easier
to program. As with most things, the art and craft of programming
becomes easier with practice. The importance of keeping notes about
programs you have written, and on solutions to problems you have
found in analysing other programs, is that it will prevent you re-
inventing the wheel. As you write more programs for yourself, you will
find that you come to recognise the method (or methods – there is
seldom only one way to perform a given task!) by which you can
implement and code each module of your program.
Modular, structured program design methods help to break down a
programming problem to these recognisable chunks, and you will
recognise more aspects of a problem as having been met (and solved!)
before as you gain experience.
You will also become familiar with the types of data structure
required in a program to make it possible to manipulate the data
efficiently, and grasp more quickly and clearly that, for example, a
given set of data is more efficiently (i.e. easily) handled in a multi-
dimensional array than in separate lists, or that a similar routine in
different program modules could be handled by a single subroutine if
suitable variables were initialised before calling the subroutine.
Experience cannot be transferred, and there is no substitute for
practice, but examples can be given. After the important topic of
writing user-friendly programs has been dealt with in the next Unit, we
give examples of programs written to perform specific tasks, to
illustrate the process of designing applications programs. Games
programming is briefly dealt with in the following Units, since games
353
•
are a good testing ground for problem-solving and programming 20 INPUT A•
techniques. 30 INPUT B
40 INPUT C
V2: Instructions and Input Checks 50 INPUT D
If you have written your own program, you know which inputs the 10 DIM A(10,3)
program requires, in what form and when. You know, for example, 20 PRINT "INPUT MATRIX"
that when "ANOTHER GO?" appears on the screen, you must press 30 FOR F = 1 TO 10
the Y key to run the program again. 40 FOR N = 1 TO 3
Now consider what happens if someone else wishes to use the 50 INPUT A(F,N)
program (or if you return to it after some weeks). There is not enough 60 NEXT N
information available to the user. The term user-friendly is applied to 70 NEXT F
programs which have sufficiently clear and precise instructions to tell It is very easy for the user to forget which of the inputs is currently
someone who has never seen the program running exactly what to do. required. The information also fails to include the units of the values
We should always attempt to make our programs at least reasonably required, and does not print the input values on the screen. We should
user-friendly. To continue the example of running a program again, use a format like this:
the line: 10 PRINT "INPUT CURRENT IN AMPS"
60 PRINT "AGAIN?" 20 INPUT A
could be followed by 30 PRINT "CURRENT = "; A;" AMPS"
70 INPUT AS 40 PRINT "INPUT P.D. IN VOLTS"
80 RUN 50 INPUT B
or 60 PRINT "P.D = "; B;" VOLTS "
70 IF INKEY$ _ " " THEN GOTO 70 This provides both clear instructions and visible input values.
80 RUN A look at any reasonably complex user-friendly program will show
or you that a significant portion of any application program is
70 IF INKEY$ _ " " THEN GOTO 70 instructions. Instructions should be concise, but only to a degree that
80 IF INKEY$ = "Y" THEN RUN still provides adequate information.
or Expanded instructions can form part of the documentation of a
70 PAUSE 40000 program, but the program itself must contain the basic instructions
80 RUN required to ensure correct input and manipulation.
These need different responses. We should use for the first "PRESS The program "MATMULT" in the program library has a better
NEWLINE (ENTER) TO RUN AGAIN", for the second and fourth approach to the array entry problem. Try to write one yourself, then
"HIT ANY KEY TO RUN AGAIN", for the third "AGAIN? compare the two routines.
(PRESS Y OR N)" or similar instructions appropriate to the program. The combination of good instructions and input checks is the best
We can assume that the user recognises that an input prompt method of reducing user error. The human being is less reliable than
requires string or numeric input, according to its form, but (as we shall the computer, and far more inaccurate results or program crashes
see later) there may be reasons for requesting a number in string form, occur due to input error than happen due to bugs in the program,
and in any case we must make it clear what is required. We should be assuming it has successfully completed a sequence of dry runs.
careful to use, for example: Checks to reduce the possibility of human error, or prevent bad
"INPUT FIRST WORD" and not "INPUT AS" effects from it, are the means by which a program is `idiot-proofed' or
"ENTER A NUMBER 1 TO 10" and not "INPUT X" `mug-trapped'. Commercial programs designed for inexperienced
"MONTH (1 TO 12)" and not "MONTH?" users with no programming knowledge often have as much space
since if the user does not know what A or AS are in the context of the devoted to input checks as to the program proper. We can assume some
program he or she is unlikely to respond correctly, and might try awareness in the users of our programs, and trust that they will enter 2
entering JAN or MARCH for the month. and not TWO, for example, but check routines can ensure that simple
We should also avoid the use of instructions grouped together: keyboard errors are not passed over. Subtle errors or straightforward
10 PRINT "INPUT CURRENT, P.D , KNOWN AND mistakes are less easy to deal with.
UNKNOWN RESISTOR"
354 355
•
It is a simple matter to check that an entered value is within an
•
90 IF M>=1 AND M<=12 THEN GOTO
120
acceptable range: 100 GOSUB 500
10 PRINT "INPUT MONTH (1 TO 12)" 110 GOTO 70
20 INPUT M 120 PRINT "YEAR? (AS LAST 2 DIG
ITS)"
30 IF M>12 OR M<1 THEN GOTO 10 130 INPUT Y
Since the month is to be input as an integer we could add a line to check 140 IF Y>10 AND Y<99 THEN GOTO
170
this:
150 GOSUB 500
40 IF INT M<>M THEN GOTO 10 160 GOTO 120
In fact one line will do it all: 170 REM *CHECK DAY US MONTH*
30 IF INT M<>M OR M>12 OR M<1 THEN GOTO 10 180 REM *LEAP YEAR*
190 IF INT (Y+1900) /4) <> (Y+190
Note that if there is an error, using GOTO 10 rather than GOTO 20 at 0)/4 AND M=2 AND D=29 THEN
least indicates to the user that something has happened by re-printing GOTO 220
"INPUT MONTH (1 TO 12)" on the screen. If we used GOTO 20 200 REM *SHORT MONTHS*
210 IF NOT ((M=2 AND D>29) OR
the user would wonder what had happened, and maybe think that the M=4 OR M=6 OR M=9 OR M=11 A
year was now required. It is better to have a statement specifically ND D=31) THEN GOTO 240
stating that there was an error in input. To continue our example, we 220 GOSUB 500
230 GOTO 10
could have these lines: 240 REM .....PROGRAM
30 IF INT M = M AND M< = 12 AND M> = 1 THEN GOTO 60 250 PRINT D;"/";M;"/19";Y
40 PRINT "INPUT ERROR:RE-INPUT MONTH" 260 REM
270 REM ......
50 GOTO 20 400 GOTO 999
60 PRINT "INPUT YEAR (AS 82 FOR 1982, ETC.)" 490 REM **ERROR NOTICE**
70 (Rest of program) 500 PRINT "***INPUT ERROR***","
PLEASE FOLLOW INSTRUCTIONS"
The user is informed what is wrong, and told what to do. Make sure
,"RE-INPUT REQUESTED DATA".
you see why the new line 30 had to have both the relational and logical 510 PAUSE 200
operators switched round to make the program work. 520 CLS
To enable re-use of check or error routines it is convenient to place 530 RETURN
999 REM*END*
them in subroutines. The following date entry routine uses a
subroutine to print an error message for a few seconds (line 500) which The program "INDATE" in the program library uses much the same
is used if any of the checks shows an error. The routine checks the routines, but set up as two nested subroutines, so that it can be used in
following: any program requiring multiple date entries, such as an accounting
i) Day of month between 1 and 31 (line 40) program.
ii) Month between 1 and 12 (line 90) It is also a simple matter to put in input checks that print the input,
iii) Year between 1911 and 1998 (line 140) and invite the operator to check if it is correct, and to re-input if an
iv) Whether the year is a leap year, and if it is not, that 29 February error has been made. This is important where multiple data entries are
has not been entered (line 190) being made, since an error would otherwise require entering
v) That days which do not exist in some months have not been everything again. As an example, here is a check routine for string
entered (line 210). input:
Check the logic used in these lines to see how it works. The lines are
good examples of how multiple conditions can be combined, but for 40 FOR N = 1 TO X
50 PRINT "INPUT SIRING";N
that reason they are a little difficult to follow. 60 INPUT W$(N)
70 PRINT W$ (N)
10 PRINT "ENTER DATE" 80 PRINT "IF INCORRECT PRESS E
20 PRINT "DAY?" TO RE-ENTER."; TAB 0; "PRES
30 INPUT D
S ANY OTHER KEY TO CONTINUE
40 IF D>=1 AND D<=31 THEN GOTO
IF OK."
70
90 IF INKEY$ ="" THEN GOTO 90
50 GOSUB 500 100 IF INKEY$ = "E" THEN GOTO 5
60 GOTO 20 0
70 PRINT "MONTH? (1 TO 12)" 110 NEXT N
80 INPUT M
356 357
•
Rather than check each value, it is sometimes better to wait until all
entries have been made, and then print them out for checking. This
•
150 PRINT VAL N$
160 GOTO 10
routine does this for a list of numbers: Spectrum users need to change the character code checks in lines 60
10 REM INPUT,PRINT,C.HECK AND C and 70. Change 27 in line 70 to 46. Change line 60 to read IF CODE
ORRECT ROLUTINE FOR LIST
20 PRINT "ENTER NUMBERS" N$<46 OR CODE N$ = 47 OR CODE N$>57 THEN GOTO 100.
190 DIM A(24) Change line 140 to read 140POKE 23692, – 1 and line 150 to read 150
200 FOR L=1 TO 24 PRINT AT 21,0;VALN$.
210 INPUT A(L)
220 PRINT AT 3+L-12*(L>12),10*( Line 20 inputs the string. Line 30 sets a variable to store the number
L>12);A(L) of decimal points. Line 40 checks that NEWLINE (ENTER) alone was
230 NEXT L not pressed, and passes control to line 100 to print an error message if it
300 PRINT AT 21,0;"ALL CORRECT?
(Y OR N)"
was. Lines 50 and 80 set a loop for the number of characters in N$, and
310 INPUT E$ line 60 uses CODE to check whether characters other than numbers
320 IF E$="Y" THEN GOTO 1000 and the decimal point are present, and goes to 100 for an error message
':30 CLS
340 PRINT "EACH VALUE WILL DE P
if they are. Line 70 adds 1 to the variable DP for each decimal point
RINTED", "ENTER NEWLINE IF 0K. NEW found in N$. After the loop, line 90 sends control to 100 for an error
VALUE" , " IF WRONG." message if there is more than one decimal point. Line 95 bypasses the
350 FOR F=1 TO 24
error routine, and line 150 uses VAL to return the number for
360 PRINT AT 21,0;A(F)
370 INPUT N$ printing. At this point, if the number were needed for calculation, a
380 IF N$="" THEN OOTO 410 variable could be set (LET N = VAL N$) to store the value.
:90 LET A(F)= VAL N$
Note that an input error causes (line 120) the input routine to be
400 PRINT AT 21,0;A(F);"
/2
repeated, after indicating for 1 1 seconds that an error exists.
410 SCROLL
420 NEXT F V3: Example Programs
1000 F:EM *REST OF PROGRAM*
Spectrum users should delete line 410, inserting 410 POKE 23692, – 1. This Unit presents some examples of applications programs of various
The virtue of using string input is that instead of stopping the program types, as follows:
with an error message if an invalid entry is made (a letter, character
that is non-numeric, or more than one decimal point), as occurs with a 1 "REACT": Reaction time testing.
numeric input, the string input can be accepted whatever the 2 "BINGO": Creation, calling and checking the cards for playing
characters input. The inputted string must be checked, however, or Bingo on the computer.
else we just get an error message when using VAL to convert to a 3 "REF. INDEX": The calculation of refractive indices from the
numeric value. This requires a routine like the following: angle of deviation and prism angle data produced by
5 REM "STRINGNUM" spectrometer experiments.
10 PRINT AT 0,5;"INPUT NUMBER" 4 "SERIES": The summing of a convergent series to a given
20 INPUT N$
30 LET DP=0
degree of accuracy.
40 IF N$="" THEN GOTO 100 5 "GRAPH": Calculation and plotting of functions, with titles
50 FOR F=1 TO LEN N$ and scales, to give a hard-copy printout.
60 IF CODE N$(F)<27 OR CODE N$
(F)>37 THEN GOTO 100
6 "ELEMENT": The calculation of empirical chemical formulae
70 IF CODE N$(F)=27 THEN LET D from the percentage composition of compounds, or the
P=DP+1 percentage composition from the numbers of atoms of each
80 NEXT F
element in the molecule.
90 IF DP>=2 THEN GOTO 100
95 GOI'O 130 7 "CASSFILE": Cassette file storage and manipulation, with
100 PRINT AT 0,5;"ERROR IN INPU printout of cassette files and cassette label printing.
T"
110 PAUSE 75
120 GOrO 10 None of these programs arc particularly complex (although CASSFILE
130 REM ...REST OF PROGRAM.... is lengthy), and they deal with fairly straightforward applications.
140 SCROLL
However, the principles involved are valid for any size of program, and
358
359
• •
The timing module will require the address bytes to be set at a
the programs themselves demonstrate many of the techniques and
procedures introduced earlier in the text. More examples of known value (the maximum, 255) by POKEing values in, and the
applications programs and useful subroutines are to be found in the values returned by PEEKing these bytes will be used to calculate the
program library provided in the Appendix, but they are not as fully time according to the expression T – ((256*(255 – PEEK
annotated. The programs here are presented as problems and 16437)) + 255 – PEEK 16436)/50. (U.S. users must use 66, not 50 in
solutions, with some discussion of the approach to the problem. The the expression and the program.) For the Spectrum the first address
procedure is then presented, and the derived program. will be 23673 and the second 23672.
Please remember that any program can be written in different ways, Our procedure in this simple linear program is as follows:
even given that the algorithm is exactly the same. This variety of
solutions means that there is never only one correct program. 1 Input Module 1 Give instructions
Spectrum users should note that we have indicated some instances 2 Input number of tests required (A)
where the additional functions of the Spectrum can be put to use. 3 Initialise array for timings, B(A)
These functions are described in the next Section. After you have 4 Initialise variable for total timings, X
explored the new functions, you should return to these programs and 5 Initialise FOR – NEXT Loop (1 TO A)
modify them for practice in the use of these facilities.
2 Timing Module 1 Give "get ready" message
1. "REACT" 2 Provide random delay to prevent antici-
pation
Problem: To use the computer to assess response times in reaction to a 3 Set timing function by POKEing 255 into
signal. An average should be taken of a number of timings. the FRAMES addresses
Research the problem: The timing function can use the system 4 Give signal
variable FRAMES. A start signal will be required, which should be 5 Wait for key to be pressed
preceded by a random delay to prevent anticipation. Computing time 6 Calculate reaction time. Allow for
must be allowed for in the result. The number of timings desired computing time
7 Store result as B(A)
should be input and used to set up a loop.
On the ZX81 FRAMES is a system variable held in 2 bytes, 16436 8 Add B(A) to X
and 16437. On the Spectrum it is 3 bytes, 23672, 23673 and 23674. 9 Repeat 1 – 8, A times
The program can use both bytes on the ZX81 and the two less
3 Output Module = 1 Calculate average reaction time
significant bytes (the first two) on the Spectrum (since we do not need
to time hours!). This will give a timing period of up to 2 Print average time
((256 x 255) + 255)/50 seconds in the U.K. and ((256 x 255) + 255)/60
seconds in the U.S., or about 22 and 18 minutes respectively, before The timing module could be coded, run and tested as follows:
the FRAMES counter, which counts backwards by decrementing by 1 Timing Module Program Listing
every 1/50 (or 1/60) seconds, reaches zero. This will allow the program 1 REM REACT CORE PROGRAM
to be used as a timer for longer periods, or modified for use as a 160 PRINT "-ON YOUR MARKS-"
170 P4LII;E 75
stopwatch program. 180 C:L
Procedure: The program will have a loop structure, determined by the 190 PRINT "<G ET SET>"
input of the number of tests required. Outside this loop will be the 210 FOR L=0 TO RND *500
210 NEXT L
instructions at the beginning of the program, and the output of average 220 POKE 16436,255
reaction time. 230 POKE 16427, 255
This timing module is the core of the program. The input module 240 F'RINT AT 10,10;"*G0*"
250 IF INK:EY$ _ " THEN 00TO 250
(instructions, `get ready' messages and an input for the number of 260 LET T=(255- PEEK 1i,486)/50+
timings required) and the output module (average time) are easily built (256* (255-
PEEK 16437))/50-0. 12
around this. We may proceed to code in a version of this module, 270 F'RINT "REACTION TIME ";T;"
SECONDS"
having decided our structure for the program, and test/debug the
timing module, before using the editing facilities to modify this module Spectrum users should note the problem with INKEY$, and the fact
as required and code in the input and output modules. that we cannot use PAUSE 0 since the PAUSE instruction uses
nrn 361
•
FRAMES also. The solution is to use the ENTER key as the key to be
•
Flowchart "REACT"
pressed. Change line 250 to INPUT A$. As long as only the ENTER
key is used, this works. Change .12 to .03 (the time allowed for
computing) in line because of the faster response of the Spectrum.
When satisfied that the timing module works, we go on to code in the
rest of the program, editing any changed lines. (Only 260, since we
kept the same numbering.) You would have to change line numbers in
developing the program, unless you coded your program accurately
with line numbers before keying anything in.
For the Spectrum, modifications are required in the following lines:
200 FOR L = 0 TO RND * 1000
220 POKE 23673, 255
230 POKE 23672, 255
260 LET T = (256 * (255 — PEEK 23673))/50
+ (255 — PEEK 23672)/50 — .03
If there are problems with the INKEY$ operation on the Spectrum (as
we noted earlier, it doesn't always work), the program should be
modified to:
i) Instruct the user to hold his finger over, then press the ENTER
key (lines 60 and 70).
ii) Change line 250 to read INPUT A$. The null string will then be
entered when ENTER is pressed and the program will go to the
next line, to derive the reaction time.
Users in the U.S. must replace the 50 which appears twice in line 260,
by 60 to get an accurate timing result.
Spectrum users can use the DEF FN, FN functions for timing. See
the Sinclair Spectrum manual, Chapter 18, for a good description of
this method.
362 363
• • Program listing
5 REM "REACT"
10 PRINT "REACTION TEST"
20 PRINT "*************"
PRINT
20 PRINT
N >A AVERAGE STOP 40 PRINT "THE SCREEN WILL SHOW
TIME
N=N +I A "" GET SET "" "
50 PRINT "MESSAGE. PLACE A FING
ER OVER"
60 PRINT "THE "" F: "" KEY. WH
EN *GO* APPEARS"
70 PRINT "PRESS R. EACH REACTIO
PRINT N TIME AND"
PROMPTS
80 PRINT "THE AVERAGE WILL BE
DISPLAYED"
90 PAUSE 600
100 PRINT ,,"ENTER NUMEEP OF TE
STS REOUIRED"
SET 110 LET X=0
TIMING 120 INPUT A
VARIABLES 120 DIM E(A)
140 PRINT
145 REM
**TEST LOOP**
215 REM
**SET TIMER EYTES**
220 POKE 16437,255
230 POKE 16436,255
240 PRINT AT 10,10;"*00*"
250 IF INKEY$ ="" THEN GOTO 250
LET B (N) 260 LET E(N)=(256*(255- PEEK 16
TIME 437))/501-(255- PEEK 16436)/50-0.
12
270 PRINT "REACTION TIME ";5(N)
SECONDS"
280 LET X=X+E(N)
PRINT 290 PRINT "PRESS NEWLINE/ENTEF:
TIME TO CONTINUE"
300 INPUT A$
310 ):LS
320 NEXT N
325 REM
ADD TIME
**ENDLOOF**
TO X
330 PRINT
:340 PRINT "AVERAGE TIME WAS ";X
/A;" SECS"
INPUT 350 STOP
/ NEWLINE
360 REM **END**
365
364
• •
Comments: The use of an array (B(A)) gives us the flexibility to add 1.3 The players' cards require 4 sets (cards) of 15 random integers in
further manipulations (full printout or standard deviation, for the range 1 to 99 (i.e. different numbers). The cards should have
example) if we wished, by adding a further module to the program. an ordered list of numbers and each list is a different set of
We could use the same principle to time other processes. The numbers. These will be put into arrays Q(15), R(15), S(15) and
accuracy of the allowance for the delay due to computing time becomes T(15).
less important as the time being measured increases. To derive a stop- 1.4 Display the players' cards on the screen and allow time for the
watch program (timing less than 65535/50 secs – about 21 minutes in players to take down the numbers.
the U.K.) we would need a start and stop routine, built around the 2.1 Display the caller's numbers one at a time on the screen in large
POKE and PEEK lines. Write such a program. Notice how the form.
program is set so that the computer waits until a key is pressed in line 2.2 Allow the display to be interrupted when a player calls `house'
250. Remember we cannot use PAUSE in the form of PAUSE 40000 (i.e. thinks that all the numbers on his card have been displayed).
(ZX81) or PAUSE 0 (Spectrum) since that uses the FRAMES system 3.1 Repeats 1.4 for players to check their numbers.
variables also, and would reset the timer. 3.2 The numbers called (i.e. those actually displayed in 2.1) are
sorted into numerical order (and put into array P(99) which
2. "BINGO" contains between 15 and 99 numbers) and displayed on screen.
3.3 The `winning' card is selected and the numbers on this card are
Problem: In the game of BINGO the caller shouts out the numbers put into the array V(15). These numbers are then compared with
between 1 and 99 in a random order and each player has a card with a the numbers called [in P(99)] to check that they are correct.
set of numbers (say 15) in this range. The cards for each player contain
different sets of numbers. The winner of the game is the player whose Algorithm Description
list of numbers is called first.
The program should play the game for up to four players and check 1.1 This section gives the minimum instructions required to play.
the validity of the winning player's card. You may want to key in fuller details of the game of BINGO.
(Lines 10 to 110 in program).
Outline Procedure: Modules are required as follows: 1.2 Set up caller's numbers
Flowchart:
1 Set up game 2 Play game 3 Result of game
1.1 These are the instructions needed to start the game. At each stage
in the program it is essential to give clear directions to the user on
how to proceed.
1.2 The caller's numbers require a random list of the integers 1 to 99
(each number occurring only once) which will be put in array
A(99).
366 367
•
This routine starts at line 120, clearing the screeand going into fast
mode on the ZX81 for the calculation. The above routine is contained
•
In the program this routine begins at line 320. Note array P(99), which
is used in the sorting routine (although containing only 15 numbers)
within the caller's numbers subroutine (lines 2500 to 2590), but note
and is then used again later for the caller's numbers.
this could be a subprogram sequence as part of the main program as it
Lines 480 — 540 carry out the selection of the 15 random numbers.
is only executed once. Subroutine 3000 — 3170 is the sorting routine which is the SHELL
1.3 Setting up (the BINGO cards) SORT given in Section T. (A fast sort is needed as at a later stage we
Flowchart: are sorting nearly 100 numbers.)
Subroutine 3500 — 3560 puts the numbers into the appropriate
array.
1.4 This subroutine (lines 1600 — 1650) displays the numbers on the
cards in a tabular form.
DIMENSION 2.1/2.2 Display caller's numbers and interrupt if `House' is called
ARRAYS
FOR
U=1 EACH
>4 CARD
U=U+1
J FOR 15
NUMBERS
J=I +1
X = RANDOM NC LET Y = 0
O - 99
GOSUB
P(J) = X ARRAY
CHOICE
368
369
•
This subroutine takes numbers generated and (in FAST mode on
the ZX81) displays them 16 times their normal size and places
them in an array P. Variable Z counts the number of numbers
called. At the end of this subroutine the numbers called have
been put into the array P (which will contain Z numbers).
3.1 This repeats step 1.4. M=l COUNTER FOR
LIST P
3.2 This routine (lines 960 — 1070) calls a sort subroutine at line 3000
which sorts the list P (Z) into numerical order and prints them out J
on the screen.
3.3 This subroutine (lines 4000 — 4260) has two parts.
COUNTER FOR
(1) Select the `winning' card and arrange for the `winning' list N>15 LIST V
of numbers to be put in the array V(15) (lines 4000 — 4120) N =N+ 1
PRINT
CARD NOT
COMPLET
RETURN
TO GAME
PRINT
CONGRAT-
ULATI ONS /
♦
1
STO P ))
(
370 371
Data Table
• •
Change line 5070 to 5070 LET E = PEEK (15360 + 8*C + R)
The following variables are used:
Change line 5200 to 5200 LET F = PEEK (15360 + 8*D + R)
Q(15), R(15), S(15), T(15) are the arrays containing the players
numbers. Flowchart `BINGO'
A(99) is the array containing the numbers for the caller.
P(99) is the array containing the numbers actually called, and is also
used as a temporary storage in setting up the players' numbers and in GOS UB
Edit line 835, renumber as line 830, to read 830 CLS BIG PRINT
372
373
e20 REM **LIST COPIED IF **
Program Listing °* PRINTER **
640 COPY
T REM "BINGO" 650 PRINT ,,"PRESS ANY KEY TO P
1^ REM °°*=°**°°°°°°°°°°***** Rucsso^
*1.1*IwoTnurTIcma 660 IF zwcc,$ ="" THEN OUTO 660
670 cLa
20 PRINT TAP 10;^ozxoo^/ TAB 1 620 PRINT "THE CALLER WILL GIVE
o/.*****. THE NUMBERS ONE A T A TIME"
oo PRINT ,,"FOUR DINGO CARDS A 690 PRINT
RE PRODUCED" 700 PRINT "WHEN ,nun CARD IS CO
40 PRINT ,,"AS T HE LISTS AND
^^
^^ MPLETE PRESSANY KEY WHEN NUMBER
^^ . ^^
R ^^ . ^^ a ^^ IS ON SCREEN"
T ^^ ^
710 PRINT
50 PRINT ,,"THEY ARE COPIED ,u 720 PRINT "PRESS ANY KEY Tc PRO
A p nzwrE p ^,,,^ IF comwsrTso,cTes cEco"
RWISE YOU MUST" 730 IF zwKEY$ ~^" THEN ooTo zo^
60 PRINT .."NOTE DOWN YOUR cyo 725 CLS
SEN LIST WHEN" 740 REM
7 0 PRINT ,,"THEY A pp EAn ' woTc T *2.1* PRINT OUT CALLS *
HE LETTER ALSO" °°°°*°*°*°*°*°***°°****
oo PRINT ,,"WHEN YOU ARE READY 745 LET Z=1
PRESS ANY KEY" 750 DIM a*(99,2)
90 PRINT ,,"TO STAeT.r*ERs NIL 755 cLa
L as A DELAY" 760 PRINT " PRESS ANY KEY WHEN
100 PRINT ,,"WHILST THE NUMBERS YOUR CARD IS COMPLETE"
ARE SET UP." 7 70 FOR N=Z TO 99
110 IF INKEY$ ="" THEN ooTo 110 7 80 noaua 5000
120 CLS 790 LET P(N)=A(N)
200 RAND 795 PAUSE 200
'7 vv FAST 800 Rsm **************"********
000 p sm **°°**°°*"**°*°*°*****° *2,2* pLAvsR INTERRUPT *
*1.2*ncT up CALLcno ******************"****
* NUMBERS * 810 IF zwKEv* "" THEN ooro a
*°*°*°***°*°°°=°**°°**
310 ooaua 2500 815 LET z~z+z
320 Rcm *********************** 820 NEXT N
*1.3°asT u p PLAYERS *
aan SLOW
* NUMBERS * 835 cLa
°*°°*°°°°°°°°°*°°°°*°*° o*^ FOR w=1 ro 10
*20 DIM o(15) 850 PRINT TAB w/^<*ozwoo*><*aIw
430 DIM n(15) oo*r
440 DIM a(15) 860 NEXT N
450 DIM T(15) arv PRINT ,,"CHECK voue CARDS"
460 DIM p(99) aav nEm ***********************
470 FOR U=1 TO 4 *3.1*oza p LAv PLAYERS *
480 FOR J=1 TO 15 * NUMBERS *
490 LET X= INT (99* RND )+1 °°**°***°**°***********
500 FOR z~1 TO 1'1 avo PAUSE
ua 100
510 IF X=P(I) THEN ooTo 490 poo c^a
520 NEXT I 910 LET Y=Z
530 LET p(J)=x 920 PRINT "YOUR NUMBERS WERE"
540 NEXT J 930 PRINT
550 LET v~15 935 REM ***********°***********
560 ooSuo ovvo *PRINT OUT CARD NUMBERS*
570 ooaoa 3500
580 NEXT u 940 ooauu 1600
585 SLOW 945 REM
590 PRINT 950 REM ***********°***********
600 PRINT ^3.2*oIa p LA, womo F Ra *
610 Rsm °°°°°°**°°°************ * CALLED *
*1.4*ozo p LAv PLAYERS * °°*°*°*******°°*°°`°°*°
* NUMBERS *
°***°°°*°°*°*°*°*°°****
620 ooauo 1600
375
960 PRINT ^ p PES5 ANY KEY TO GET
LIST OF", "THE NUMBERS CALLED."
2550
25e0
•
LET X= INT (99* ewo )+1
IF m(x) 0 o THEN ooro 2550
970 PRINT "THERE WILL oc n SHOP 2570 LET Am/=w
T DELAY FOR SORTING." 2580 NEXT N
vnv IF zwKsv$ ~^^ THEN GOTO 980 2590 RETURN
990 OLO
1005 FAST 2600 REM ** cwoauo **
1010 000ua 000v °**°*°*°*°**********°°°
1020 cLa
1025 SLOW 2990 REM ***********************
1*30 PRINT "CALLERS LIST" **SORT SUBROUTINE **
1040 PRINT *******°**°°°~*****°***
1050 FOR N=1 TO z oovv LET a~,
1060 PRINT p(w).^ ^. 2010 LET S. INT (5/2)
1070 NEXT N 0000 IF a >= 1 THEN OUTO 2050
1080 PRINT 000^ ooro 3170
1085 Rcm ******+****x*****,*****
*o.o°cosc y WINNING * 3050 FOR K=I TO a
* CARD * 3060 FOR A=K -o Y-5 STEP K
°°°°°***°**°**°*****°°° 3070 LET B=A
1090 ooauo 4000 onav LET T~p(A+m
1100 LET z~7.+1 :3vvo IF T >= p (o) THEN OUTO 2130
1110 PRINT .,^om YOU WISH ro cou o1vo LET p(a+a)~pm,
TINUE THE GAME? (v/x)^ 3110 LET B=B-a
1120 zw p ur c* 3120 IF o >~ 1 THEN OUTO 3090
1120 IF c*~^m^ THEN STOP o1ov LET p(o+a)=r
1140 IF c$~^Y^ THEN ooro 755 3140 NEXT A
1150 PRINT "INPUT Y OR N nnL,.n- :3150 NEXT K
EAsE^ o1ao ooTo o*10
1160 ooTo 1120
3170 RETURN
1190 REM *°***°*°***************
* END PROGRAM 2180 REM ** Ewnauo
°°**°"°°°*°°°~°°**°°*~° **
`°°°*°**°***°°°°*°°°^=*
1200 STOP
nzs* REM
1210 REM ao p o REM ***********************
**SUBROUTINE Fon FOUR**
15o0 nFm *********************** **NUMBER ARRAYS' **
* SUBROUTINES °°°**°*****°°****°°**°*
°°°°***°*°***********°* e500 FOR J~1 TO 15
1590 REM o510 IF u=1 THEN LET o(J)~p(J)
1600 REM ******°*°****°°****°*"* 35u0 IF U=2 THEN LET R(J)=P(J)
**SUBROUTINE TO p R:xr * oF,00 IF U=3 THEN LET s(,../=pu>
**our PLAYERS CARDS * 3540 IF U=4 THEN LET T(J)=P(J)
"****°***°°**°°****"°*° 3550 NEXT J
1610 PRINT ^o^, TAO s^n^; TAO 1 3560 RETURN
2.^e^, TAB za,^r
1620 FOR J~1 TO 15 3570 REM ** cwoaoo **
1680 PRINT o(U)/ Too un(J), Too ***°******°°°**°***°***
12;a(J). TAB 1o.T(J)
1640 NEXT J 3580 REM
1650 RETURN uvvo REM **********°a***********
**SUBROUTINE ro CHECK**
1660 REM ** cwocuo ** **eEsm' T5 **
°*°°°°**************°°° °°°**°°°*°°°*°***°*°*°*
2490 REM 4^*0 PRINT
2500 REM **°******°*°**°**°***** 4010 REM ***********************
**SUBROUTINE TO SET ** *3.2,z*oELscT WINNING *
**CALLERS NUMBERS ** * CARD *
°°°°°°°°°°**°°°*°°°°*** ***********************
2520 DIM A'99) 4020 PRINT "TYPE WINNING CARD (o
2540 FOR N=I TO 99
376 377
4030 INPUT A$ 5050 LET D- CODE D$(N)(2 TO 2)
"0" AND A$
uq" 5(t6(t FOR R=0 TO 7
4040 IF 4$
AND 4$ <: _" AND A$ :. "T" THEN 5070 LET E= PEEK (76=0+8*C+R)
GOTO 4020 5Ù_;1i LET W=120
4051 t CL' : FOR 0=0 TO 7
4060 DIM V(15) 5100 IF E<W THEN GOTO 5150
4070 FOR N=1 TO 15 5 110 PRINT AT 2*R+5, 2*G+1 ; "11.
40:50 IF A$="0" THEN LET V(N)=i_!(N 5120 PRINT AT 2*R+6, 2*0+1 ; "1"
51a(i LET E=E-W
4090 IF 4$="R" THEN LET V(N)=R(N 5140 GOTO 5170
378 379
^
prisms, so that, for example, Z(3) can represent the average refractive Error 4.2
•
Return
index of the third prism. Subroutine
Angles will be input in degrees. Since the formula for the calculation
requires the use of the Sine function SIN, we will need to convert to Note: Subroutine called after each input. All entries can be re-input if
radians. This will have to be done before the refractive index is incorrect. See program listing.
calculated. We can provide a simple input check in a subroutine. Zero
entries in the input loops will signify end of prisms or end of readings. Data Table
=
90 FOR N=1 TO 6
M>4 100 LET 2=0
110 PRINT "INPUT PRISM NUMBER,I
M=M+1
NPUT 0","TO FINISH"
120 INPUT P(N)
130 PRINT "PRISM NUMBER ";P(N)
140 GOSUB 700
150 IF A$ <> "C" THEN GOTO 110
160 IF P(N)=0 THEN GOTO 500
INPUT 165 REM ***********************
GOSUB
INPUT ANGLE **START READINGS LOOP**
CHECK
170 FOR M=1 TO 4
18') PRINT "INPUT PRISM ANGLE IN
DEGREES, INPUT 0 TO FINISH"
190 INPUT A(N,M)
200 PRINT "ANGLE OF PRISM ";A(N
,M)
Yes 210 GOSUB 70)
220 IF A$ <> "C" THEN OUTO 180
230 IF A(N,M)=0 THEN GOTO 410
240 PRINT "INPUT MIN. DEV. IN DE
OREES"
250 INPUT D(N,M)
CALCULATE 260 PRINT "MIN. DEV. ['(N, M)
AVERAGE 270 GOSUB 700
CONVERT R. FOR 280 IF A$ <> "C" THEN GOTCI 180
TO RADIANS PR ISt1 290 REM **CONVERT DEGREES TO**
**RADIANS **
300 LET A=A(N,M)* PI /180
310 LET D=D(N,M)* PI /180
320 REM **REFRACTIVE INDEX**
330 LET N(N,M)=( SIN ((A+D)/2))
/ SIN (A/2)
CALCULATE 340 LET N(N,M)= INT (1000*N(N,M
R.I., ADD )+.5)/1000
TO Z 250 LET Z=Z+N(N,M)
360 NEXT M
370 REM **END READINGS LOOP **
**********************
280 REM
390 REM **AVERAGE TO 2 DEC.**
** PLACES **
382 383
400 REM
• Sample Printout:
•
410 LET Z=Z/(M-1)
420 LET Z(N) = INT (100*Z+. 5)/10
760 REM
**END 3UBROLiT INE** 4. "SERIES"
******************
Problem: We are asked to sum the series that gives us the value of e
770 STOP
raised to the power x. This is:
7.0 REM ** END **
x2 x3
e' = 1 + x + + + .... x" + ... for any Yvalue of x, with an accuracy
2! 3! nl
of 1 part in 100,000 (i.e. 10- 5 , .00001).
184 385
•
Research the problem: This is the EXP function on your computer,
evaluated as a series. The resulting value of, e.g., e`, will be 1.2
•First term – easily input
approximately the value of EXP 3 if you used it on the computer. This 1.3 Accuracy – easily input
is a convergent series, the value of each term gets smaller. For example, if 1.4 Value of X – easily input
2 Sum 2.1 Initialisation – set 1st term equal to given
2 1 = 2, whilst 3! = 3x2x1 – 1.333.... At a certain
we take x = 2, 3 is z
^ value which in turn is the sum of the series at
point, the effect of adding the value of another term is to increase the this stage.
sum by less than the accuracy we require. The summing is then 2.2 Next term – may be calculated by multiplying
finished. first term by common ratio.
Procedure: This requires a procedure which allows any term in the 2.3 Sum – may be calculated by adding this term
series to be calculated from the previous term. This is the basic to previous sum
algorithm for summing many series. 3 Comparison 3.1 Compare this sum with previous value then
At this stage we need to consider if it is a specific problem or whether EITHER go to 4.1 if the difference is less than
we could extend it to deal with other similar series-sum problems. It is that required or go back to 2.2 if difference is
important to make this decision before the program is written as it is more than that required.
often very time consuming to modify a program at a later stage. The 4 Output 4.1 Name of series
answer is yes. We can then restate the problem as: a program is Results 4.2 Accuracy
required which will sum a convergent series to any desired accuracy 4.3 First term
(subject to the limitations of the computer's arithmetic), provided that 4.4 Value of X
any term may be expressed as a function of the previous term, with the 4.5 Sum of series
information needed being the first term and the common ratio. The 4.6 Number of terms
common ratio is the equation that enables us to calculate any term
from the previous one. Variables Table
For our problem: take the exponential series: Input
x zx"-' A$ Name of Series
e"=1+x+—+....+ + ..
2! (n – 1)! A Value of first term in series
n 'h term X Value of X
D Accuracy required (difference between terms, such
In this series the first term is 1.
that program terminates when difference smaller
The common ratio = (n n h1)" term. The n'h term is (ri 1)i and the than this).
– Processing and Output
(ri 2
-' (n 2)! x
T Value of current term being processed
(n – Iy h term is 2)i . The ratio is
(ri" 1) x" 1 – n 1 •
N Number of terms
We require an accuracy of one part in 100,900 (101. When the S1 Value of Sum of series of N – 1 terms.
effect of adding another term increases the sum by less than this, the
S Value of Sum of series to N terms.
program should stop processing and output the result. SI – S Difference between the sums of the series to the Nth
and (N – 1) 'h terms, checked against value of D.
Outline Procedure: T = T*X/(N – 1) Calculates value of next term in series from current
term.
1 Input necessary information
2 Sum series term by term The common ratio is set in line 260. This line must be changed for
3 Compare sum with previous value different series. Spectrum users could use the DEF FN instruction in
4 Print out result when sums differ by less than required value initialisation, and the FN instruction to evaluate the expression in line
260. Try this when you have familiarised yourself with this function.
Detailed Procedure:
386 387
Program listing
Flowchart "SERIES"
10 REM "SERIES"
START
( 20 PRINT " ** SERIES ** ",,,,"
THIS PROGRAM SUMS ANY SERIES"
30 PRINT „"WHICH IS CONVERGEN
T AND WHERE"
PRINT
FO
I INPUT DATA
**IN LINE 70
70 PAUSE 40000
**
80 CLS
90 PRINT "INPUT NAME OF SERIES
(
S T OP )
320 PRINT "SUM OF ";A$;" SERIES
389
388
330 PRINT "********************
390
441
• 3
•
Search Array for Maximum and Minimum values of Y.
Detailed Procedure
3.1 Set Maximum value and Minimum value variables
The descriptive algorithm (with user notes) for obtaining the best (MAXY and MINY) equal to first Array element.
possible plot within defined scales is as follows. The user must be (MINY = N(1),MAXY = N(1)). Start search loop.
presented with the information required to make decisions as to 3.2 FOR each element in array (N(2) to N(End)).
3.3 If array value is less than minimum value variable (N(F) <
suitable values for the X and Y axis scales.
MINY) then set minimum Y variable equal to array
Define range of values of X for which values of Y are to be element (MINY = N(F)).
1
3.4 If array value more than maximum value variable, set this
obtained.
variable equal to array element (MAXY = N(F)).
1.1 Input minimum value of X (MINX).
3.5 NEXT array element.
1.2 Input maximum value of X (MX).
4 Inspect Range of Y.
Note: Values of X should be chosen such that the scale divisions 4.1 Print maximum, minimum Y values (MAXY,MINY).
correspond to values of X that will fit the defined purpose of the graph 4.2 Present menu choice of: (i) Recalculating for a different
(range of X required). Thus the range of X would be chosen to suit the range of X. Program returns
major scale divisions of the `graph paper' drawn by the program. We to 1.1 if selected.
would choose X to be plotted on a scale running from 0 to 5, to give (ii) Choosing Y axis values.
scale divisions of:
2 3 4 5 Note: The user must now select the scale values for a range of Y such
0 1
along the X axis, even though we were primarily interested in the plot that all values of Y are within the range chosen and maximum vertical
of Y with X in the range, say, 0.5 to 3.9, adapting the X values to the spread of plot points is achieved to avoid a cramped plot. This latter is
constraints of the graph scales drawn on the screen. (See the sample the same decision as was made for the X axis values. A suitable scale
printout for these.) Similarly, we might choose X axis scale values of must be chosen to conform with the scale divisions presented on the
0.6 0.7 0.8 0.9 screen. The Y axis has three scale sections, requiring four scale values
0.4 0.5
at the vertical divisions of the graph.
to fit within the constraints of the display, even when the prime concern
was the plot of Y when X runs from 0.5 to 7.9. If MINY were 0.12 and MAXY were 3.6 for a given range of X, for
example, we might choose to set the minimum scale value for Y as 0,
1.3 The scale factor for X (DX) to be used in the calculation and the maximum as 4.5, allowing intermediate values of 1.5 and 3.0,
loop to derive values of Y is then (Number of points to be which correspond to the scale divisions, so that the Y axis will be
labelled:
plotted on X axis/(Maximum X - Minimum X)). DX =
50/(MX - MINX) for the ZX81 and 200/(MX - MINX) 4.5
3.0
for the Spectrum.
1.5
2 Calculate values of Y for each value of X.
2.1 Set X equal to minimum value of X (MINX). Start 0
This gives the maximum vertical spread of plot points.
calculation loop.
2.2 FOR each plot division on X axis (1 to 50 on ZX81, 1 to 200 Having made this decision, the user can input the maximum and
minimum Y axis values. The decision can also be made to return to the
on Spectrum).
start of the first module and re-define the values of X, choosing a
2.3 Calculate Y = (Function of X). Use VAL to calculate value
different range (choosing to calculate for X = 1.5 to 7.5, for example,
of function input as string.
rather than the original choice of 0 to 6 for the range). This re-
2.4 Store value in array N (N(F) = Y).
2.5 Increment X for next plot point (X = X + DX). calculation can be done repeatedly until the best possible Y values for
2.6 NEXT plot point on X axis. End of calculation loop. placing on the graph have been found, within the constraints of the
ranges of X that are acceptable.
Note: The values of Y are now stored in array N. We now require to
know the minimum and maximum values of Y that have been 5 Derive scale factor for Y axis.
produced by the calculation. We must search the array N for these 5.1 Input minimum Y for scale (Y1).
values. 5.2 Input maximum Y for scale (Y2).
393
•
Note: These values are the same as will be inserted as scale values in L
•
Loop variable
string form for printing on the display. F$ Function input as string
X Value of X
5.3 Scale value for Y plot is number of plot points on Y axis MINX Minimum value of X (Input)
divided by maximum Y minus minimum Y. This is MX Maximum value of X (Input)
(DY = 30/(Y2 — Y1) for ZX81, 120/(Y2 — YI) for Spectrum.) DX Step value for X value in calculation
Y
Value of Y calculated. Each value stored in Array N(50)
Note: Next module of program inputs scale values as strings and the MAXY Maximum value of Y
strings for titles to be printed to the screen. MINY Minimum value of Y
M$ Menu choice (Input)
6 Input scale values and titles.
Y1 Minimum value of Y axis scale (Input)
6.1 Input Minimum Y.
Y2 Maximum value of Y axis scale (Input)
6.2 FOR each remaining Y axis scale division (2 to 4).
DY Scale factor for plot of Y values
6.3 Input scale value to be printed.
6.4 NEXT Y axis scale division.
6.5 Print maximum and minimum X value (MINX and MX) Flowchart "GRAPH"
as reminder of X axis values.
6.6 FOR each X axis scale division (1 to 6).
6.7 Input scale value to be printed.
6.8 NEXT X axis division.
6.9 Input Graph title, Function or subtitle, X axis and Y axis
titles.
Variables Table
394 395
• Spectrum modifications:
•
The different plot screen of the Spectrum must be taken into account.
This affects scale factors and the actual plot routine, and requires a
larger array for the data (values of Y for the function of X).
In the same area of the screen, where the ZX81 has 50 X axis plot
points, the Spectrum has (4 x 50), 200. The array N must thus be
initialised as N(200). The scale factors for Y and X also need to be
calculated according to this changed plot resolution. Line changes
needed are as follows:
80 DIM N(200)
360 FOR F = 1 TO 200
370 PLOT F + 40, (N(F) – Y1)*DY + 52
1120 LET DX = 200/(MX – MINX)
Delete lines 1135 and 1265
1150 FOR F = 1 TO 200
1230 FOR F = 2 TO 200
1380 LET DY = 120/(Y2 – Y1)
1390 Delete 30, Insert 120
Input Y 1520 Delete 30, Insert 200
Scale
Values
Spectrum users can also use the DEF FN and FN instructions to define
the function to be plotted (in line 1050) and to evaluate the function
within the calculation loop (line 1160). Revise the program to utilise
these functions when they have been dealt with in Section W.
Sample printout
Calculate
scale 4..S +---- ----+----+---- ----+
T ^
factor for + +
Y ++
±+
L_ -
+ ^+ + + +
+ + ^ +
YRXIL +
+
+■f
■ +
+ +
+
+
+
+
+
t-
+
+
C
i a ` +-- s' +--- - +--- - +--- - +--- -^
+ iq + + + + 4-
+ ■ + + + + 4
+ u + + 4- é- 4-
4-411
. ^ ----} ----t----i
0 1 .0 2.0 3.0 4.0 5 .0
X
ORRPH PLOT OF EOUAT ION
Return SIN X+X
Program listing
1 0 REM "GRAPH"
20 REM *PRODUCES GRAPH OF
20 REM *FUNCTION WITH TITLES
40 REM *AND SCALES FOR +VE
*QUADRANT
397
396
50 DIM X$(6,4)
60 DIM Y$(4,5)
• •
1150 FOR F=1 TO 50
1160 LET Y= VAL FS
70 DIM T$(4,25) 1170 LET N(F)=Y
80 DIM N(50) 1180 LET X=X+(1/DX)
90 REM **GOSUB INPUTS** 1190 NEXT F
100 GOSUB 1000 1200 REM **GET MAX,MIN Y**
110 CLS 1210 LET MAXY=N(1)
120 REM **PRINT PAPER** 1220 LET MINY=N(1)
130 FOR: F=5 TO 30 STEP 5 1230 FOR F=2 TO 50
140 FOR L=0 TO 15 1240 IF N(F)<MINY THEN LET MINY=
150 PRINT AT L,F;"+" N(F)
160 NEXT L 1250 IF MAXY<N(F) THEN LET MAXY=
170 NEXT F N(F)
200 FOR L=0 TO 15 STEP 5 1260 NEXT F
205 FOR F=6 TO 29 1265 SLOW
206 IF F/5= INT (F/5) THEN NEXT 1270 PRINT "MINIMUM VALUE FOR Y
F IS:",MINY
210 PRINT AT L,F;"-" 1280 PRINT "MAXIMUM VALUE FOR Y
220 NEXT F IS:",MAXY
230 NEXT L 1290 PRINT „"CHOOSE SLIITABLE VA
240 REM **TITLES** LUES FOR Y ";"AXIS (Y) OR RESTAT
250 FOR F=1 TO 6' E RANGE OF X ","(X)^ INPUT X OR
260 PRINT AT 16,(F*5-1);X$(F) Y."
270 NEXT F 1300 INPUT M$
280 FOR F=1 TO 4 1310 CLS
290 PRINT AT 20-F*5,0;Y$(F) 1320 IF M$="X" THEN GOTO 1070
300 NEXT F 1330 REM **SCALE FACTOR Y**
310 PRINT AT 17,5;T$(3) 1340 PRINT "INPUT NUMERIC VALUE
320 PRINT AT 18,0;" OF MIN.Y","( <= ";MINY;")FOR SCIA
LE"
330 PRINT AT 19,5;T$(1); AT 21, 1350 INPUT Y1
8;T$(2)(1 TO 20) 12260 PRINT "INPUT NUMERIC VALUE
340 PRINT AT 8,0;T$(4)(1 TO 5); OF MAX Y","( >= ";MAXY;")"
TAB 0;T$(4)(6 TO 10) 1370 INPUT Y2
350 REM **PLOT FROM ARRAY ** 1380 LET DY=30/(Y2-Y1)
360 FOR F=1 TO 50 1385 REM ** Y AXIS SCALES **
370 PLOT F+10,(N(F)-Y1)*DY+13 1390 PRINT "Y AXIS HAS 3 SCALE D
380 NEXT F I V I'_ I ONE:, ", "AND 30 PLOT POINTS."
390 GOTO 9999 1400 PRINT "INPUT THE 4 SCALE VA
LUES FOR Y", "AXIS. MAX 5 CHR:'S. "
1000 PRINT "GRAPH OF FUNCTION" 1410 PRINT "NEWLINE FOR BLANK."
1010 PRINT „"CALCULATION ROUTIN 1420 PRINT "MINIMUM(1)'-"
E" 1430 INPUT Y$(1)
1020 PRINT "INPUT FUNCTION TO BE 1440 FOR F=2 TO 4
GRAPHED, IN","FORM Y=FUNCTION X. 1450 PRINT "VALUE ";F;"?"
1460 INPUT Y$(F)
1030 PRINT "FUNCTION IS INPUT AS 1470 NEXT F
STRING.","ERROR MAY RESULT IN E 1480 CLS
VALUATION","OF SOME FUNCTIONS.I 1485 REM **X AXISS SCALES**
F THIS","HAPPENS,REPLACE STRING 1490 PRINT "INPUT X AXIS SCALES"
INPUT","AND EVALUATION WITH INSE 1500 PRINT "LOW X IS ";MINX
RTED","PROGRAM LINES" 1510 PRINT "HIGH X IS ";MX
1050 INPUT F$ 1520 PRINT „ "6 SCALE DIVISIONS,
1060 CLS 50 FLOT POINTSON X AXIS."
1070 PRINT ,,"LOW VALUE OF X?" 1530 PRINT "SCALE VALUES MAX.4 C:
1080 INPUT MINX HRS.","FIRST INPUT IS LOW VALUE.
1090 PRINT „"HIGH VALUE OF X?"
1100 INPUT MX 1540 FOR F=1 TO 6
1110 REM **SCALE FACTOR X** 1550 F'RINT "SCALE VALUE ";F;"?"
1120 LET DX=50/(MX-MINX) 1560 INPUT X$(F)
1130 REM **CALCULATE ** 1570 NEXT F
1135 FAST 1580 REM **TITLES**
1140 LET X=MINX 1590 CLS
398 399
1600 PRINT "INPUT GRAPH TITLE (M
•
atoms of any of the elements) elemental proportion. We can check this
AX 25 CHRS)"
1610 INPUT T$(1) through another loop. The number of atoms of each element is then the
1620 PRINT "INPUT FUNCTION OR SU proportion of each element divided by the smallest proportion. We
ETITLE(20","C: HRS MAX)"
1630 INPUT T$(2)
could round this to integers, but will do so to two decimal places
1640 PRINT "INPUT X AXIS TITLE because the actual molecular formula may be a multiple of the derived
20 CHRS MAX)" formula. We should also indicate this possibility to the user.
1650 INPUT T$(3) Zero inputs will be required when elements do not occur in the
1660 PRINT "INPUT Y AXIS TITLE(2
*5 OHRS)"
compound concerned.
1670 INPUT T$(4) For a common organic analysis the following data will be stored via
1680 RETURN
the input routine:
9990 REM **END**
9999 STOP HYDROGEN H 1.008
CARBON C 12.01
6. "ELEMENT" NITROGEN N 14.008
OXYGEN O 16.00
Problem: To calculate for a chemical compound: (i) Percentage PHOSPHOROUS P 30.98
elemental composition and molecular weight or (ii) molecular formula SULPHUR S 32.06
from inputs of, for (i), Number of atoms each element and for (ii) CHLORINE CL 35.457
Percentages of each element. These are complementary calculations. BROMINE BR 79.916
Research Problem: We require a program that performs two separate The data entry module is keyed in and the data input as above. The
operations. The common requirements will be the Element names, lines 15 to 160 could then be deleted if required, leaving the data stored
symbols and molecular weights. We choose to input and store these as in the arrays and available for access, as long as RUN is not used (or
data in arrays on the computer. This will require an input routine that CLEAR). Spectrum users should replace line 3000 with: 3000 SAVE
is not used every time the program is run, and could be edited out. The "ELEMENT" LINE 3010. The program is then SAVEd to tape by
elements involved should be capable of being changed to facilitate using GOTO 3000, when it stops at line 1990, or run again by keying
different analyses, and this must be allowed for in our program. This is in GOTO 200 as a command.
an advantage over the alternatives of either defining all data with LET You may like to derive an additional user dialogue to ask if the user
statements or the use of DATA and READ (which are only available wishes to SAVE or re-run the program, and according to the response,
on the Spectrum). send control to the relevant line number. The procedure for the
The program must be split into two processing sections. The first of program is given below.
these (percentage elemental composition and molecular weight)
requires an input for the number of atoms of each element. We can use
a loop for this, using the loop variable to access the stored element Detailed Procedure:
names. Molecular weight equals the number of atoms of each
compound multiplied by the atomic weight. This can be calculated 1 Data Entry Module
within the input loop. Molecular formulae are then derived from the 1.1 Dimension arrays for data: Element Names, Element
atomic symbol, plus the number of atoms, for each of the elements Symbols, Atomic Weights
concerned. 1.2 FOR each input (1 to 8)
Percentage composition for each element is the number of atoms of 1.3 Input Name, Symbol, Atomic Weight
the element, times the atomic weight of the element, divided by the 1.4 GOTO subroutine to justify atomic weight (5 below)
molecular weight. 1.5 NEXT input
The second section of the program requires an input loop for the 1.6 Print user warning about the use of RUN
percentage of each element. The proportion of atoms of each element 2 Menu
will then be the percentage divided by atomic weight. This can be 2.1 Print Instructions and Menu
calculated within the input loop. To calculate the molecular formula, 2.2 If second calculation required, GOTO 4
we require to know the minimum (to give us the smallest number of 2.3 If first calculation required, proceed to 3
400
401
^ •
3 Percentage Element Calculation 5 Subroutine to Round and Justify
3.1 Input: (Input of number of decimal places (P) and number to be
3.1.1 Reference for compound
justified (N) from data defined in main program modules)
3.1.2 Initialise arrays, molecular weight variable 5.1 X$ set to contain P zeros
3.1.3 FOR each Element (1 to 8) 5.2 Integer value set as XN
3.1.4 Input number of atoms present 5.3 Decimal value set as XD
3.1.5 Calculate total molecular weight (Molecular weight
5.4 Define X$ as rounded number string
plus (number of atoms * atomic weight))
5.5 X$ returned to main modules for printing
3.1.6 NEXT Element
6 Auto-run. An automatic RUN routine using GOTO 200 is used to
3.2 Processing/Output: prevent the user entering RUN accidentally after LOADing
3.2.1 Print Reference, Molecular Weight
3.2.2 FOR each Element (1 to 8) Variables Table
3.2.3 Print Symbol, number of atoms
3.2.4 NEXT Element 1) Input and main program sections:
3.2.5 FOR each Element (1 to 8) E$(8,10) Holds element names
3.2.6 If no atoms present, GOTO 3.2.10 S$(8,2) Holds element symbol
3.2.7 Calculate percentage as (Number of atoms times M(8) Holds atomic weight
atomic weight) divided by molecular weight of E Loop variable in main program
compound, times 100 X Loop variable in input routine
3.2.8 GOSUB (5) for rounding and justification of results A$ Menu choice
3.2.9 Print Element symbol, percentage R$ Reference for compound
3.2.10 NEXT Element MOLWT Molecular weight
4 Molecular Formula Calculation A(8) Holds input of number of atoms of element
4.1 Input: P(8) Holds input or calculated percentage of element
4.1.1 Reference for compound N(8) Holds calculated number of atoms of element
4.1.2 Initialise Arrays C Constant for calculating percentages
4.1.3 FOR each Element (1 to 8)
4.1.4 Input percentage present 2) Round and justify subroutine:
4.1.5 Calculate proportion of Element as percentage N Holds number for operation of subroutine
present divided by atomic weight X$ Holds string form of number returned by subroutine
4.1.6 NEXT Element XN Holds integer value of N
4.2 Processing/Output: XD Holds decimal value of N
4.2.1 Print reference F Loop variable in subroutine
4.2.2 Set C = 100 for percentage calculation
4.2.3 FOR each Element (1 to 8)
4.2.4 If proportion is zero, GOTO 4.2.6
4.2.5 If proportion less than current value of C, then let C
equal proportion of element
4.2.6 NEXT Element
4.2.7 FOR each Element (1 to 8)
4.2.8 If proportion is zero, GOTO 4.2.12
4.2.9 Number of atoms equals proportion divided by
smallest proportion present, C
4.2.10 GOSUB (5) for rounding and justification to 2 d.p.
4.2.11 Print Symbol, number of atoms
4.2.12 NEXT Element
4.2.13 Print user warning that multiples of this calculated
formula may be the actual formula
402
403
• •
Flowchart "ELEMENT" Program Listing
10 REM "ELEMENT"
15 REM ***********************
START 1. DATA ENTRY. ROUTINE
CAN BE DELETED WHEN
ENTRY COMPLETE.
***********************
DIMENSION
DATA ARRAYS 20 DIM E$(8,10)
30 DIM S$(8,2)
40 DIM M(8)
50 PRINT " ELEMENT SYMBOL
MOL. WT.
55 PRINT
INPUT 60 FOR X=1 TO 8
DATA 65 REM ** ELEMENT NAME **
70 INPUT E$(X)
75 REM ** ELEMENT SYMBOL **
80 INPUT S$(X)
INPUT 85 REM ** ATOMIC WEIGHT **
FOR EACH
ELEMENT 90 INPUT M(X)
INPUT PERCENTAGE
95 REM *INITIALISE FOR GOSUE**
CHOICE 100 LET P=3
110 LET N=M(X)
120 GO SUE 2000
130 PRINT X; TAB 3;E$(X); TAB 1
FIND
4;S$(X); TAB (27- LEN X$);X$
i
YES LOWEST 140 PRINT
PERCENTAGE
150 NEXT X
160 REM
NO **LINE:: 15 TO 160 CAN BE
DELETED AFTER DATA ENTRY
INPUT CALCULATE AND REST OF PROGRAM ENTERED
FOR EACH MUST LISE *GCITO 200* TO LISE
NUMBER OF - ELEMENT NUMBER
PROGRAM/NOT RUN/TO PRESERVE
ATOMS OF ATOMS DATA.
FOR EACH
ELEMENT 170 REM **END 1. **
***********************
PRINT
PRINT REF, 180 REM
SYMBOL, NO 200 REM ***********************
MOL. NT, 2. PROGRAM MENU TO
OF ATOMS
FORMULA CHOOSE CALCULATION
***********************
404
^ 640 Fi** END C. **
295 F:EM ** END 2. ** ************************
***********************
650 REM
************************ 990 REM ***********************
3.FERCENT ELEMENT 4. MOLECULAR FORMULA
************************ ***********************
407
A/1G
• •
1220 REM clearing of the stored data by the use of RUN. However, since more
** END 4.
*********************** data may be required to be stored than will fit in one set of arrays, there
should be also a facility to clear the file data arrays deliberately, to
1780 REM allow a new file system to be set up. Any other variables must be
1790 REM
**ENDRUN INSTRUCTIONS** defined by LET statements, and all variables re-initialised after
CLEAR has been used.
1800 PRINT AT 20,0; "USE GOTO 200 The best method of setting up a structure for this type of program is
TO RUN AGAIN.","USE GOTO 2000 T
i i SAVE" to have a menu presented to the user. From the menu, control can be
1810 :.TGIF passed to a separate module of the program which will perform the
appropriate manipulations. After each set of operations have been
1820 REM
**** END PROGRAM **** performed, control will pass back to the menu module, which is the
1830 REM main program, looping back after each call (via a GOSUB or GOTO
instruction) of the other program modules.
2000 REM ***********************
-. SLIEROUTINE TO ROUND
AND JUSTIFY Outline Procedure:
***********************
3020 REM ** END PROGRAM LIST ** Define the data to be held, its form, variables needed in the
program, and strings to be used by one or more program sections
7. "CASSFILE"
to print titles for data. Initialise arrays, variables, strings. (See
data table below.) This module is processed only once for each
file system.
Problem: To write a program which will store and manipulate the data
concerned with cassette program listings and print out lists of these 2.1 Present Menu: 1 Create File
files. The data must be able to be updated. Cassette labels should be 2 View/Print File
printed out, taking advantage of the fact that the Sinclair printer paper 3 Revise File
is the correct width for this. 4 Delete File
Research the problem: The program must have data entry and 5 Print Cassette Label
and storage for relevant data. This data must be displayed on screen 6 Save Files
and printed out if required. There must be a facility to add, delete and 7 Erase all Files
revise each portion of data separately. Data must be stored in string 2.2 Loop back to start of Menu. If CLEAR has been used in 4.7,
and numeric arrays, and there should be protection from accidental loop to (1).
408 409
3
•
Go to chosen program section. Use subroutines unless this causes
•
the ZX81 do not operate from within subroutines properly, so control
problems. must be passed with GOTO instructions. This procedure is modified
4.1 Create File. for the Spectrum (see notes below).
4.1.1 Define file number (existing files + 1)
4.1.2 Input data 4.7 Delete all files
4.1.3 Increment file count 4.7.1 Confirm deletion
4.1.4 Sub-menu: View created file (GOSUB 4.2) 4.7.2 Use CLEAR to delete data
Create another file (GOSUB 4.1) 4.7.3 Set marker for re-initialisation of variables on Return to
Menu (RETURN) Menu
4.1.5 Return to Menu 4.7.4 Return
4.2 View/Print File This cannot be a subroutine on the Spectrum (see notes below).
4.2.1 Get file number to view The marker informs the main program loop that control must be
4.2.2 Print file contents on screen passed to module (1) for re-initialisation.
4.2.3 Sub-menu: Print file to printer (COPY) Each section of the program must then have the detailed procedures,
View next file (GOSUB 4.2) including input checks, defined. Each area of the program can be
Menu (RETURN) treated as a program module for coding purposes. The sections must
4.2.4 Return to Menu operate on the same data structures, so the first task is to define the
4.3 Revise File arrays for the data, variables required, and strings for printing, so that
4.3.1 Get file number to revise a table of these may be used in developing each section of program.
4.3.2 Print each item on screen
4.3.3 Input new data if required, leave if correct Data Table
4.3.4 Print new data if input
4.3.5 Return to Menu C$(10,4) Holds cassette reference (any four characters)
4.4 Delete File N$(10,15) Holds cassette name (15 characters)
4.4.1 Get file number to delete P$(10,10,15) Holds for each cassette file 10 program names (15
4.4.2 Print basic file data (name, reference) characters)
4.4.3 Confirm deletion T(10,10,2) Holds for each program on each cassette tape
4.4.4 Delete file contents counter readings (Start and Finish, numbers
4.4.5 Swap data from files of higher number to maintain file assumed to be in range 0 – 999)
numbering as sequence File number of file being manipulated in
4.4.6 Print new file numbers and basic data (reference and processing
name) TF Total number of files (up to 10)
4.4.7 Sub-menu: Copy new file listing (COPY) M$ String input from menus
Menu (RETURN) M Numeric input from menus
4.4.8 Return to Menu S$ Current file program name
4.5 Print Cassette Label N,L Used as loop control variables
4.5.1 Get file number E$ Set as empty string for overprinting
4.5.2 Print file contents on printer in suitable form A$, B$, F$,G$
4.5.3 Return to Menu H$,I$,X$,Y$,Z$ Used as string literals for printing
4.6 Save Files X Marker to show CLEAR has been used and hence
4.6.1 Allow revision of program name (string) that re-initialisation of variables and arrays is
4.6.2 Allow return to menu if error required.
4.6.3 Stop program until cassette ready
4.6.4 Save `program name string' Another consideration is whether recursive or nested subroutines
4.6.5 GOTO Menu (prevent use of RUN) should be used. Care must be taken in the use of these facilities, and
unnecessary complication should be avoided, since all control is passed
Note that this module cannot be a subroutine. Auto-run routines on back to the Menu, from which all modules can be accessed. However,
410 411
•
in the program recursion is used in the Create File routine to allow a
•
Flowchart "CASSFILE"
sequence of data entries to be made (Line 1280), and (Line 2300) in the
View File routine to allow stepping through the files. 1. Main Program Flowchart
The View File routine is also available as a nested subroutine from
the Create File routine to allow a newly created file to be viewed (Line C START
2020). Apart from these instances a simple GOSUB – RETURN
pattern of control has been followed, and the control flow in the Save DIMENSION
Files routine has the same structure, but using GOTO instructions for ARRAYS,
NITIALISE
the reason stated above. The different action of the CLEAR instruction
on the Spectrum requires a GOTO instruction for the Erase All Files
module (see below).
Ten files are set up and manipulated in this program. Reference to PRINT
the way variables are stored (Section T) will enable you to discover the MENU
memory required for this. The same section has the PEEK routine to
discover program size. Work these out. You will find that the program
could in fact store and manipulate up to 30 such files on the ZX81. INPUT
Display file size will restrict the 16k Spectrum user to ten files, as in the MENU
CHOICE (M)
program.
The main program flow is illustrated in the first flowchart. The
nested and recursive structures in the program are illustrated in the
second, with the sub-menu control structures also shown. Sub-menus
include a "Return to Main Menu" option. SAVE FILES
CONTINUES SAVED
PROGRAM ON
MODULE
LOADING
GOSUB
(M•1©0Q)
200p
VIEW/
PRINT FILES
3 000
REVISE
FILE
58
PRINT
LABEL
7QQg
ERASE LOTO MODULE
FILES ON SPECTRUM
412 413
•
2. Recursion and Nesting the Create File and View File Subroutine
MENU
ENTER CREATE
FILE NUMBER FILE SUB-
= FILES +1 ROUTINE
(LINE 10001
RESPONSE
PRINT "V"= VIEW
FULL CREATED FILE
FILES
INPUT
NEW FILE CALLS VIEW
DATA FILE MODULE
AS NESTED
SUBROUTINE
INCREMENT
NO. OF
FILES
PRINT
LINE 1230
MENU
INPUT
MS
No RESPONSE "F"
= CREATE
ANOTHER FILE
INCREMENT
FILE
NUMBER
GOSUB RECURSIVE
1020 GOSUB
414
• •
MENU
/ FILE
NUMBER
`I
FILE SUBROUTINE
(LINE 2000)
1 ENTRY FROM
CREATE FILE
"F"=VIEW NEXT
FILE
MODULE
FILE Yes
EXISTS
No
INPUT
MS
\ Ys "V"=VIEW
ANOTHER FILE
CHECKS IF FILE
"M" = RETURN EXISTS
TO MENU
RETURN
ITO LAST
GOSUB CALL)
LINES 2120 TO
PRINT 2185
FILE RECURSIVE
GOSUB
INPUT
MS
Spectrum Modifications:
COPY
416 417
•
without the jump at line 6100. The placing of the auto-run
routine at the end of the program is done so that it is more visible
•
350 CL_;
IF X=1 THEN GCiTO 20
360 GOTO 210
to the user, since there is not a STOP or Program End.
2 Replace SCROLL in lines 3090, 3150, 3170, 3230, 3250, 3265, 990 REM **********************
** CREATE FILE SUE-: **
3420 and 3495 by POKE 23692, – 1. **********************
3 The Spectrum wipes the GOSUB stack when CLEAR is used. 1000 LET F=TF+1
This means it will not have a location stored to RETURN to. 1010 IF F <= 10 THEN GOTO 1020
1015 PRINT "**NO SPACE FOR ANOTH
The Erase All Files module must therefore use GOTO
ER FILE**",,, "ON RETURN TO MENU
statements: CHOOSE SAVE","OPTION TO KEEP CUR
325 IFM=6ORM=7 THEN GOTO M*1000 RENT FILES","THEN ERASE FILES AN
D START NEW", "FILE ARRAY."
7090 GOTO 350 1016 PAUSE 300
Program Listing 1017 RETURN
418 419
**
2020 CLS
•
2015 REM **ENTRY FROM OTHER SUBS
•
::080 PAUSE 150
3090 SCROLL
3100 PRINT AS;C$(F)
2030 IF TF <> 0 AND F <= TF AND 3110 INPUT MS
F >= 1 THEN GOTO 211-0 3120 IF MS="" THEN GOTO 3170
2040 PRINT "NO FILE WITH THAT NU 3130 LET C$(F)=MS
3140 CILS:
MEER"
3150 SCROLL
2050 PRINT "MENU (M) OR VIEW 0TH
3160 PRINT "NEW ";AS;C$(F)
ER FILE (V)"
3170 SCROLL
2060 INPUT MS
3180 PRINT ES;" ”;NS(F)
2070 IF M$="V" THEN GOTO 2000
2080 IF M$="M" THEN RETURN 3190 INPUT MS
2090 PRINT "FOLLOW INSTRUCTIONS 3200 IF M$="" THEN GOTO 3285
PLEASE." 3210 LET NS(F)=M$
`:220 CLS
2100 GOTO 2050
3230 SCROLL
3240 PRINT AS;C$(F)
2110 C:LE:
2120 PRINT FS;F 3250 SCROLL
2130 PRINT „A$;CS(F) 3260 PRINT "NEW CASS.NAME ";N$(F
2140 PRINT "********************
************" 3265 SCROLL
2150 PRINT 0$; TAB 20;H$; TAB 20 3270 FOR N=1 TO 10
;I$ 3380 PRINT "FROG.";N;" NAME ";PS
(F,N)
2160 PRINT "
3390 INPUT MS
2170 FOR N=1 TO 10 3400 IF MS <> "" THEN LET F'S(F,N
2180 PRINT N;".";PS(F,N); TAB 20 )=M$
;T(F,N,1); TAB 26;T(F,N,2) 3410 PRINT AT 21,0;"FROG.";N;" N
AME ";PS(F,N)
22185 NEXT N
2190 PRINT AT 21,0;"PRINT(F'),NEX 3420 SCROLL
T FILE(F),OR MENU(M)" :=430 PRINT AT 21,0;"TAPE FROM:";
2200 INPUT MS T(F,N,1)
2210 PRINT AT '"21,0;E$ 3440 INPUT MS
2220 IF MS="P" THEN COPY 3450 IF M$ <> "" THEN LET T(F,N,
2230 IF MS <:> "F" THEN GOTO 2310 1)= VAL MS
2240 LET F=F+1 3460 PRINT AT 21,0;"TAPE FROM:";
2250 IF F <= TF THEN GOTO 2300 T(F,N,1);" TO:";T(F,N,2)
2255 CLS 3470 INPUT MS
2260 PRINT "**NO FILE OF HIGHER 3480 IF MS <' "" THEN LET T(F,N,
NUMBER**" 2)= VAL MS
2270 PAUSE 150 3490 PRINT AT 21,0;"TAPE FROM:";
2280 CLS T(F,N,1);" TJ:";T(F,N,2)
2290 GOTO 2310 349 5 SCROLL
3500 NEXT N
2300 GOSLIB 2020 3510 RETURN
2310 RETURN 3990 REM ******************.**
4000 REM **DELETE FILE SUB**
2980 REM ******************* 4001 REM ********************
2990 REM **REVISE FILE SUE** 4010 PRINT "WHICH FILE DO YOU WI
2995 REM *******************
SH TO","DELETE ? (1 TO 10)"
3000 PRINT "WHICH FILE TO REVISE 4020 INPUT F
?(1 TO 10" 4030 IF F <= TF AND F >= 1 THEN
3010 INPUT F GOTO 4070
3020 IF F <= TF THEN OOTO 3060
4040 PRINT "**NO FILE OF THAT NU
=030 PRINT "NO SUCH FILE" MBER**"
3040 PAUSE 150 4050 PAUSE 150
3050 RETURN 4060 OUTO 4430
3060 CLS 4070 PRINT F$;F,,A$;C$(F)
=:070 PRINT "FILE ";F;" DETAILS W
4080 PRINT BS:" ";N$(F)
ILL BE FEINTED.",,,"PRES„S NEWLIN
E IF CORRECT","INPUT NEW DETAILS 4090 PRINT AT 10,0;"INPUT D TO C
ONFIRM DELETION",,,"0R M FOR MEN
IF REQUIRED." U."
420 421
4100 INPUT M$
•
4110 IF M$ <> "D" THEN LOTO 4430
4120 PRINT AT 14,0;"ALL FILES WI
•
5140 LPRINT Z$;X$;"1";G$; TAB 20
"1";H$; TAD 31;"1"
TH NUMBERS >":F,"WILL HAVE THEIR
FILE NUMBERS","REDUCED BY ONE." 5150 LPRINT "I "; TAB 20; "1 "; I$;
4125 IF F=TF THEN GOTO 4220 TAB: 31 ; ' 1"
4130 FOP N=F TO TF-1 5160 LPRINT X$
4140 LET N$(N)=N$(N+1) 5170 FOR N=1 TO 4
4150 LET C$(N)=C$(N+1) 51:0 LPRINT "1";N;" " ;P$(F,N); T
A L-B '21;T(F,N,1); TAD 25;T(F,N,2);
4160 FOR L=1 TO 10
4170 LET P$(N,L)=P$(N+1,L) TAB 31;"1";Z$
5190 NEXT N
4180 LET T(N,L,1)=T(N+1,L,1)
4190 LET T(N,L,2)=T(N+1,L,2) 5200 LPRINT Y$; X$
4200 NEXT L 5210 LPRINT "1";A$;C$(F); TAB 20
;F$;F; TAB 31;"I"
4210 NEXT N
4220 LET C$(TF)=E$ 5220 LPRINT Z$;"1";8$;" ;N$(F);
TAL :31; "I"
4230 LET N$(TF)=E$
5230 LPRINT Y$;X$
4240 FOR N=1 TO 10
5240 FLOR: N=7 Ti i 10
4250 LET P$(TF,N)=E$ 5 250 LPRINT "I";N;" ;P$(F,N); T
4260 LET T(TF,N,1)=0
4270 LET T(TF,N,2)=0 AB 21;T(F,N,1); TAB 25;T(F,N,2);
TAD 31;" 1 ";Z$
4280 NEXT N
5260 NEXT N
4290 LET TF=TF-1
5270 LPRINT Y$
4300 CLS 5280 RETURN
4310 PRINT "FILE DELETED"
4320 PRINT „"NEW FILE LISTING:" 5990 REM *********************
433.0 PRINT 6000 REM ** SAVE FILES PRO **
4340 FOR N=1 TO TF 6001 REM *********************
4350 PRINT F$;N;" ";A$;C$(N) 6005 CLS
4360 NEXT N 6010 PRINT "SAVE FILES ON TAPE R
4370 PRINT AT 21,0;"COPY NEW LIS OUTINE"
T (C) OR MENU (M)"
6020 PRINT „"CURRENT PROGRAM NA
4380 INPUT M$ ME IS"
4390 IF M$ <> "C" THEN LOTO 4430 6030 PRINT „ ;S$;
4400 PRINT AT 21,0;E$ 6040 PRINT ,,"INPUT A NEW NAME F
4410 COPY OR THIS " ,"PROGRAM FILE OR PRESS;
4420 CLS NEWLINE","ONLY TO SAVE WITH CUR
4430 RETURN RENT NAME."
6050 PRINT , , "INPUT M FOR MENU"
4990 REM ********************* 6060 INPUT M$
5000 REM ** PRINT LABEL SUB***
6070 IF M$="M" THEN RETURN
5010 REM *********************
6080 IF M$="" THEN GOTO 9900
5020 PRINT "WHICH FILE DO YOU WA 6090 LET S$=M$
NT TO PRINT",,,"AS A CASSETTE LA 6100 GOTO 9900
BEL?( 1 TO 10 )"
5030 INPUT F 6990 REM ***********************
5040 IF F >= 1 AND F <= TF THEN
7000 REM **DELETE ALL FILES SUB*
GOTO 5090 ***********************
5050 PRINT "**NO FILE OF THAT NU 7010 PRINT "INPUT D TO CONFIRM A
MBER**" LL FILES","ARE TO BE DELETED."
5060 PAUSE 150 7025 PRINT „"INPUT M TO RETURN
5070 CLS TO MENU."
5080 LOTO 5280 7030 INPUT M$
7040 IF M$ <> "D" THEN LOTO 7080
5090 PRINT ,,"FILE ";F;" WILL NO 7050 CLEAR
W BE PRINTED.",,,"CHECK PRINTER, 7060 PRINT ,,"INPUT NEW NAME FOR
HIT A KEY TO START" THIS FILE"
5100 IF INKEY$ ="" THEN GOTO 510 7070 INPUT 8$
0 7080 LET X=1
5120 LPRINT X$;"1";A$;C$(F); TAB 7090 RETURN
20; F$; F; TAB 31 ; " I"
5130 LPRINT Z$;"1";L-$;" ;N$(F); 9890 REM *********************
TAD 1;"1" 9900 REM ** AUTO-RUN ROUTINE *
9901 REM *********************
422
• Comments:
9910 CLS
9920 PRINT "PROGRAM NAME IS "
This is a fairly long program. Work through the listing, checking you
9930 PRINT " "" ";S$;"
9940 PRINT "**NOTE IT DOWN**" understand the operation of the algorithm within each program
9950 PRINT ,,"SET CASSETTE TO RE module. The individual manipulations of arrays and lists have all been
CORD, AND THEN" , "PRESS A KEY TO
encountered before, and each program module performs a different
SAVE." r ^; F.
9960 IF INKEY$ _ " THEN GOT! operation on the arrays and lists holding the data. The program is not
0 by any means `idiot-proof', although it is reasonably `user-friendly'
9970 SAVE S$ and you should note the various input checks used. The program can
9980 CLS
9 990 GOTO 200 be crashed by inputs of bad (non-numeric) data into the numeric array
holding the tape counter listings, and the main menu. Any file number
request is checked.
The input (string or numeric) from menus is checked, in different
Sample Printout:
ways. Either another input is requested, or a default return to the main
FILE NO.1 menu operates. Data correction is dealt with by the View File and
CASSETTE REF: RPP1 Revise File modules.
*********,-*********************4
PROGRAM NAME
PROGRAM The program could be improved in two obvious ways. The first
FROH TO
improvement would be a search routine to find and display the cassette
1.GRRPHPLOT s35 25
60 file containing a desired program. A new module, 8 in the main menu
2. RESIST dtZ
3.5TRINGSORT 65
lt a^ and line 8000 onwards in the program listing, could be added to
4.
5. perform this operation.
6.
The second is that you cannot both print a file (in the View/Print
s. File module) and then step through for the next file, since after printing
1 0.
the program automatically returns to the menu. Consider how you
would modify the flow of control in lines 2190 to 2310 to allow this.
!
Notice as a final point that data manipulation programs are long, not
CASSETTE REF,RPP1 FILE NO.1 necessarily because of the processing manipulations themselves, but
CR55ETTE NAME RPPLICRTION6f1 due to necessary input checks and user dialogue.
The program can be easily revised for use with your audio cassette
PROGRAM NAME library, or other filing purposes.
1 GRRPHPLOT 5 25
35 60 The program examples included in this Unit have been selected to
2 RESIST
65 ae illuminate the various structured programming techniques discussed in
3 STRINGSORT
the rest of the book. In order to demonstrate the maximum number of
4 O O
these techniques being used in practice, it proved necessary to give the
s 0 0
programs a strong scientific applications bias. Home users will
6 0 0
doubtlessly be dismayed to discover that there is little in this part of the
book which will be of practical use to them. However, it is important
CASSETTE REF:RPP1 FILE NO.1 that they understand the principles behind the programs in this Unit,
CR55ETTE NAME RPPLICRTIONS*1 even if they do not actually key them in.
7
0 0 As far as games and home applications programs are concerned, the
e e Program Library at the end of the book (Appendix VI) should provide
a
0 0 readers with enough examples to enable them to write their own
9
0
programs tailor-made to their particular interests.
10 0
Games are applications programs which are not of a type which fulfils a
425
• ^
To implement this on the computer, it is obvious that array
specific purpose in a functional context; that is to say they are not manipulation will be involved since a grid is a 2-D array. It is also
l or data-manipulation
written to do a specific scientific, educationa necessary to have more than one such array, since the grid of
task. This does not mean that, as programming tasks, they are Generation (n + 1) is defined from the grid of Generation (n), and none
of playing the game on or with the computer
frivolous. The enjoymen t of the cells of Generation (n) can be altered until the checking process is
is the application for which the program is written, but the task of complete.
programming a game is often difficult. Games programming is good The array of Generation (n) must have each grid position checked,
practice for finding, deriving and coding algorithms and producing and the number of neighbours counted. In accordance with the rules,
efficient and user-friendly programs. Graphics manipulation plays a the future of the cell at that position is determined and, if empty,
larger part in games programming than in most applications programs, whether a cell will be born. This data is stored in one array, and then
and such programs are also more interactive, requiring repeated inputs the other array is updated to take account of the changes. Spectrum
and outputs. users should delete lines 220 and 390.
BASIC, an interpreted language, is often slow for games purposes.
Fast action graphics games (SPACE INVADERS and their spawn), Program Listing
are written in machine code for speed of operation, as are tactical
games where exhaustive exploration of possible moves is required (such REM "LIFE"
10 PRINT TAB 12;"*LIFE*"
as chess). Effective games can be programmed in BASIC, however, if 20 PRINT
the amount of calculation is not too great. 30 DIM A(16,16)
Application
An area of interaction between Games and App 40 DIM 11(16,14)
50 DIM A$(6,6)
programming is the question of simulation. A program, given data and
60 LET OEN=0
rules for manipulating the data, simulates a situation. In a serious 70 REM *ENTER START COLONY*
application, this would be a real situation, with the manipulations _'i FRINT "ENTER START COLONY",
performed as known or hypothesised relations from scientific "ON A 6X6 GRID",,,,"INPUT 6 ..TRI
Ni__; OF SPACE'. AND ","ASTERISKS (
knowledge. A game simulation would use invented relationships, or *),,
perhaps simplified formulae, if it dealt with a `real' situation. The 90 PRINT
101 FOR F=1 TO 6
techniques would be essentially the same, and are used in a program in
110 PRINT "STRING ";F;
the same fashion. From the point of view of this book, games may be 120 INPUT A$(F)
t echniques you have 130 PRINT " ";A$(F)
considered as programming exercises. All the
140 NEXT F
learnt can be put to use in writing games programs. 145 REM *PLACE COLONY IN ARRAY*
150 FOR F=1 TO 6.
160 FOR Z=1 TO rL
V5: Example Programs
170 IF A$(F,Z:!="*" THEN LET E•(F
+6,Z+5) =1
program we will examine is a classic computer simulation, or 1:30 NEXT Z
The first
rather implementation, of Life. This is not really a game, but a process 190 NEXT F
that the user sets into operation, and observes. Invented by John 200 GOe3UB 1000
205 REM *INCREMENT GENERATION*
Conway, the game simulates a colony of cells, which grows from the 210 LET OEN=GEN+1
initial colony according to three simple rules. Cells are placed on a 220 FAST
grid, and in each generation the succeeding generation is determined 230 FOR X=2 TO 15
2410 FOR Y=2 TO 15
by the number of neighbouring grid squares which contain a cell. The 250 REM *=,E T, COUNTER*
260 LET C=0
rules are these: 265 REM *CHECK NEIGHBOUR CELLS*
270 IF A(X-1,Y)=1 THEN LET C=C+
If a cell possesses, in the 8 adjacent grid squares, either two or 1
1
three neighbour cells, it survives into the next generation. 2S0 IF A(X-1,Y-1)=1 THEN LET 0=
2 A cell dies (is removed from the grid for the next generation) if it 0+1
290 IF A(X•-1,Y+1)=1 THEN LET C=
has (i) 4 or more neighbouring cells (overpopulation) or (ii) 0 or 0+1
1 neighbours (isolation). 300 IF A(X,Y+1)=1 THEN LET C=C+
3 Each grid square which is empty, but has exactly three 1
310 IF A(X,Y-1)=1 THEN LET C =c+
neighbours is a birth cell, and a cell will appear in this position in 1
the next generation.
427
•
220 IF A(X+11Y-1)=1 THEN LET C:=
C+1
•
Flowchart of "LIFE"
I
360 IF A(X,Y)=1 AND (0>3 OR C<:2
THEN LET E(X,Y)=0
PRINT
370 NEXT Y INSTRUCTIONS
380 NEXT X
390 SLOW
400 GOTO 200
F=1
1000 IOLS
>6
1005 PRINT AT 0,1;"GENERATICIN F=F
GEN
1010 FOR X=1 TO 16
1020 FOR Y=1 TO 16 PRINT
1025 REM *UPDATE ARRAY A* STRING
NUMBER
1030 LET A(X,Y)=2(X,Y)
1035 REM *PRINT ARRAY*
1040 IF A(X,Y)=1 THEN PRINT AT X
+21Y+6;.*.. INPUT
1050 IF A(X,Y)=0 THEN PRINT AT X STRING F
+2,Y+6;" "
1060 NEXT Y
1070 NEXT X INPUT
1080 COPY
STRING F
1090 RETURN
F=1
F>6
F-F+1
^
Z=1
Z>6 ^
Z=Z+1
PLACE IN
ARRAY B
GOSUB
1000
428 429
• •
Flowchart of "LIIFE" - Subroutine 1009
C ENTRY l
INCREMENT
GENERATION PRINT
t
GENERATION
FAST
X=2
X>15 X=1
X=x+1 X > 16
X=X+1
Y=2
Y >1 5
y-y+1
Y=1
>1
Y=Y+1
COUNTER C
U
COUNTER C
= No. of A(X,Y)
NEIGHBOURS
=B(X,Y)
FOR A(X,Y)
NO NO
PRINT
SPACE
B(X,Y)=0
(DEATH)
COPY
SCREEN
'
SLOW
(RETURN
430 431
PROGRAM STRUCTURE
• •
only. This version uses one side of the screen for a graphic display, and
prints the data on the other. Spectrum users must replace line 40 with
The program breaks down into the following sections.
40 PAUSE 0.
(i) Initialisation (lines 30 – 60). Two 2-D arrays, 16 x 16 are set up, 5 REM "LANDER"
10 PRINT TAB 10; "*LANDEF:*"; AT
with a 6 string array to hold the start colony. The generation
4,0; "LUNAR LANDING GAME. YOU ARE
counter is set as 0. ","INITIALLY 500 METRES ABOVE T
(ii) Input of start colony (lines 70 – 140). 6 strings of 6 characters are HE", "SURFACE OF THE MOON. YOU I HAV
E "1"100 FUEL UNITS "
entered and printed out. 20 PRINT "PRESS R TO FIFE ROCK
(iii) Start colony is placed in array. The lines 150 – 190 place 1 ET_: TO SLOW DESCENT. EVERY FIRING
(representing a cell) in array B when an asterisk is present in the USES 5 FUEL UNITS. YOU MUST LAND
SLOWER THAN 8 TO SURVIVE. 000D L
string array entered in (ii), in the central 6 x 6 block. i_K. „
(iv) Print Subroutine. Line 200 sends control to the subroutine. This =0 PRINT , , "F'F:ESS A KEY Ti STA
uses a double loop to set array A as array B, then prints asterisks RT"
on the grid for each I found in array A. Note that at the end of 40 PAUSE 40000
this subroutine arrays A and B hold the same data. The screen is 45 REM **INITIALISE**
50 CLS
copied, and control returned to line 210.
60 PRINT AT 20, 15; "
(v) Checking of population to determine next generation. The
generation is incremented and the computer put into FAST 70 LET F=100
mode. The double loop is set up, and each cell in array A is 80 LE T H=500
90 LET 5=15
checked in turn for the number of neighbours it possesses. The
95 REM **START OF LOOP**
counter C is incremented by 1 for each neighbour. Line 350 100 LET V=0
places a `born' cell into array B if the cell in array A is blank, 110 IF H<;40C' THEN PRINT AT 20-H
/30,20;"
and the number of neighbours is three. Line 360 kills any cell
120 F'RINT AT 1,0;"FUEL: ";F;" "
with more than 3 or less than two neighbours. The TAB i,; "HEIGHT: "; H; " "; TAB 0;"
corresponding array B element is set to 0. At this point array B SPEED: " _, "
holds the revised population for the next generation. Array A 135 REM **CHECK ROCKETS **
140 IF INKEY$ ="R" AND F 5T
must be left alone during the check procedure. This is the reason HEN LET V=5
why the two arrays are made equivalent in (iv) above. 150 IF V THEN PRINT AT 21--H/20,
20;"V V"
(vi) Control is returned to line 200, and steps (iv) and (v) repeated.
160 IF F`.5 THEN PRINT AT 1,7;"*
EMPTY*"
170 LET F=F-V
The pattern of asterisks input initially determines how the population 180 LET S+2-V
develops. Some patterns die out, after a number of generations, some 190 PRINT AT 20-H/30,20;"
TAB 20;" "
enter a stable sequence that repeats, and there is a general tendency
195 REM ** CHECK: IF LANDED **
towards symmetry if a population survives long enough. 200 IF H:30 THEN GOTO 230
210 LET H=H-S
220 LOTO 11)1,
The next game is also an implementation of a favourite game for
computers, which has existed since the days of printout-only terminals
(which is where the instruction PRINT in BASIC comes from, as a 225 REM ** LANDING RESULT **
2:30 IF =;:::4 THEN PRINT AT 21,10;
hangover from hard-copy terminals transferred to implementation on a "PERFECT LANDING"
screen). The basic idea, upon which many variations have been 240 IF (8 AND S>4 THEN PRINT A
created, is that a landing must be made on the lunar surface at a speed T 21, 10; "DUMPY DUT SAFE"
250 IF S >= 8 THEN PRINT AT 21,
low enough to prevent a crash. Rockets can be fired to slow the craft, 10;"CRASHED AND SMASHED"
but the fuel supply is finite. If the fuel supply is exhausted, a crash is 260 PRINT AT 12,0;"ANOTHER GAME
"(INPUT Y OF: N)"
inevitable. The game was originally played with a printout of the data 270 INPUT A$
432
433
2_:0 IF AS="Y" THEN GUTii 50
290 REM *END*
•
put to work the techniques we have shown you in this text to analyse
...
some of the tactical games in the popular computing magazines, if this
area interests you. In order to start learning to appreciate the problems
Lines 10 to 30 print instructions, and line 40 stops the program until a involved, you could start by writing a program to play Noughts and
key is pressed. Lines 50 to 90 clear the screen, print the `lunar surface' Crosses. You may think this is a very simple game, but it is a
and set the variables: F is fuel units, H is height above surface, S is surprisingly difficult one to program!
speed of descent.
The main program is in the loop between lines 100 and 220. V is set
to zero as a flag, and the craft is printed by line 110 if the scale set
allows it to be on screen. The craft disappears off the top of the screen if
the height is greater than 600 since the PRINT AT instruction scales so
that 1 print line = 30 metres of height. Line 120 prints the current data.
Note the spaces after the variables to overprint if the values decrease,
or in the case of the speed becoming positive after being negative.
(Negative descent speed means ascent.)
Line 140 checks if the R (for rockets) key is being pressed. If it is, V
is set to 5. Line 150 prints rocket exhausts below the craft if the R key
was pressed (evaluated by V = 0 = False if not pressed, V = 5 = True if
pressed). The fuel is checked (line 160) and reduced by the value of V if
not empty. The speed is adjusted by increasing it, then reducing it by
the value of V if the rockets have been fired. Line 190 overprints the
craft and rockets, and 200 checks if the surface is near enough for
landing to be assumed. If it is, control is transferred to the landing
message section. If not, the height is adjusted and the program loops
back to repeat the process.
Notice that the variable V is used in three ways within the loop, and
that the loop structure, using INKEY$ to see if the player has input
instructions, is common in interactive games. It provides a simulation
of a real-time process. In this game, the speed is assumed to be metres
per second (hence the simple LET H = H – S of line 210). It is actually
nominal `metres' per program loop! Other games can wait for inputs,
but the use of a loop allows the inexorable attraction of gravity to go on
its way unless the player does something. Spectrum users, with their
faster computing, may wish to insert a PAUSE instruction in the loop.
Programming for this type of game can show the programmer that
certain structures of programs are inefficient in program execution,
since conditional branches to routines requiring calculation will
noticeably slow the loop. In the interests of a good game, structured
programming practice may be set aside and speed of execution can
become a goal in itself. However, remember not to transfer these
techniques to serious programs!
Games programming can become extremely complex when we
consider the strategy and tactics which must be built into the response
from the computer. We have dealt with only the simplest form of game,
and have not included any of this type of game. We suggest that you
434
435
• •
PART FIVE
439
•
programming techniques just as well. It is extremely useful, however, FUNCTION OF COMPONENTS
•
to have a printer both for hard-copy printouts of results and, more
importantly, for program listings for documentation purposes. Here is a brief rundown of the function of each of the components of
The cassette recorder should preferably be mono, since stereo tape the Spectrum microcomputer system.
deck recording heads can cause problems, even used on only one Device Function
channel. The cheaper recorders work somewhat better (due to the less
Spectrum computerboard Data processing and control of inform-
sophisticated audio circuits being better for handling the crude form of
ation handling.
the computer's signals) than more expensive ones, but get one with a
Input from keyboard or cassette. Output
tape counter, as finding programs without one can be an irritatingly
to TV screen and printer. Also holds the
time-consuming process. 16k or 48k of RAM memory. K stands
FIGURE 3 for kilobyte. One byte is eight bits, which
are the binary digits (0 and 1, represented
SPECTRUM SYSTEM DIAGRAM by on-off switches in the computer)
a.c. household power supply computers work with. A kilobyte is
roughly 1000 bytes, hence the name. (It
is actually 2 10 , 1024).
Keyboard Input of information. Programs, data
and commands are keyed in.
On-line control.
TV Set Used as V.D.U. (visual display unit)
monitor. Provides on-line output of
O
information – visual display of programs,
O TV A RIAL
results (data, graphs, pictures) and
CORN ECTION
O control commands.
Cassette recorder Off-line storage of information Program
1
data are stored (written) as coded
electromagnetic impulses on cassette
POWER tapes. They can be played back (loaded)
SUPPLY
at any time for use again. The computer
TELEVISION
reads the data from the tape. The
Spectrum will also be able to use the
microdrive, storing the coded impulses
9V d.c. on a magnetic-coated disc, when it
becomes available.
Printer Output device, to provide a permanent
MIC printed record of the screen display,
program listings or information in the
PRINTER
TV EARn nMIC computer memory. Prints on electro-
EAR
[0 0
sensitive paper.
Power Supply Supplies the d.c. current (9 volts at 1.2
amps) to run the computer, RAM pack
J CASSETTE
- ----- ----
^
M
IIIII ON EI MIll IN M S
II
and printer, from the household power
supply.
RECORDER MI IN . . IN IN MI M Cables To interconnect the devices which make
up the system.
U.S. Users may have antennae on/off switch The printed circuit board inside the Spectrum holds and connects the
fitted in aerial lead , shown as dotted box in diagram
440 441
•
IC (integrated circuit) microchips which provide the computing
•
as is in the EAR socket of the cassette recorder and place it in the
facilities. These are: Spectrum EAR socket. Place the other in the MIC socket.
1 Z80A CPU (Central Processing Unit) microprocessor chip Inset the jack-plug leading from the power supply into the
which is the heart of the system. It is used in many other socket marked 9 V d.c. on the back of the Spectrum. Connect
microcomputers, and performs the arithmetic manipulations. the TV aerial/antenna lead to the aerial socket of the TV.
2 ROM (Read Only Memory) chip holds the 16k BASIC Your system is now set up. Check the TV is turned off, and no
interpreter which translates BASIC instructions into the cassette keys are depressed. Plug the ZX power supply and
machine-code instructions that the Z80A operates with. The cassette leads into the a.c. (household) power supply sockets,
data in this chip is fixed, hence the name, and also stable – it and switch them on if they have switches.
remains when the power is switched off. 3 Switch on the TV. Choose a channel with the push button or
3 RAM (Random Access Memory) chips provide the memory other channel select control, and tune the TV until the display:
store. This is either 16k or 48k, depending on which version of
the Spectrum is owned. This memory is volatile – the data is © 1982 Sinclair Research Ltd
stored as electrical impulses and is lost when the power is
switched off. This memory stores the BASIC program, the appears on the screen. Adjust the tuning until the display is
values of variables (including some system variables that the clear, and the brightness, contrast and colour (if you're using a
computer uses for to organise its own affairs), a memory picture colour TV!) controls to get a good picture without it being too
of the TV screen display, and the stacks which hold the numbers bright (since you are going to spend some time looking at it from
whilst they are being manipulated. The memory organisation is close up).
described in Section U. Note for U.S. users: In the U.S., the antenna lead connects
4 The Logic Chip co-ordinates the operation of the other chips. with standard terminals to the TV. An antenna on/off switch is
Also mounted on the board are the stabiliser for the 5 volt supply the provided between the computer and the TV. The computer has
computer takes from the power-supply socket, the colour TV signal a channel select switch to select channel 2 or 3. Whichever
encoder and modulator circuits and the sockets for the connecting channel is not transmitting should be selected, and the TV
cables to the TV and cassette recorder. There is also a small speaker for tuned until the computer display is obtained.
the sound output. 4 Press a few keys to get some characters printed on the
screen – these should appear at the bottom of the screen. Then
press the CAPS SHIFT and 1 (EDIT) keys together, to clear the
CONNECTING UP screen.
5 Press the Z key. The screen will print COPY at the bottom.
1 Set aside an area to work in and set up your television, Then press ENTER. The printer will start operating, feeding
Spectrum, cassette recorder, printer (if you have one) and the paper through. There will be nothing printed on it because there
Spectrum's power supply, as shown in the diagram of the system is nothing printed on the screen. Check that the printer paper
(Fig. 3). does not rub against the side of the printer as it is fed through. If
2 Always remember to connect the printer to the back of the it rubs, pull it gently away from the side as the paper is fed
Spectrum before you switch the power on for the ZX power through.
supply. With the printer connected, the TV aerial lead You now have an operating microcomputer system. The system needs
connected to the TV socket on the Spectrum, and the `EAR' no maintenance other than the occasional cleaning of the printer and
and `MIC' leads correctly set up as below, you can then plug into the tape heads on the cassette player. Clean the printer with a small
and switch on the a.c. power (household) supply. brush to clear away the black dust that accumulates. Be careful not to
Connect the printer into the socket at the rear of the damage the electrode (a small piece of wire running in the slot visible
Spectrum. Make sure the gap in the board at the rear of the when the paper carrier is removed). Blow away the dust when you've
Spectrum connects with the plastic piece in the printer socket, brushed it from this slot. Keep your cassette tape heads clean and de-
then push firmly home. magnetised.
Connect one end of the twin cassette leads into the EAR and If the printer doesn't work, first turn off the power. Then remove
MIC sockets of the cassette recorder. Push firmly home and and re-insert the printer socket. Switch the power on again and try
twist slightly to get good connections. Take the same colour plug once more. The contacts on the printed circuit boards that the printer
442 443
• •
socket connects with may need cleaning if the printer doesn't work or Figure 4
prints incorrectly. Clean the contacts with a proprietary contact cleaner SPECTRUM KEYBOARD DIAGRAM
or a pencil eraser. DO NOT use abrasives to clean these contacts.
These are the only problems you should encounter with your system, CC
as long as all plugs are well seated in their sockets. With the need to W
1–
r-
remove and re-insert the EAR socket when saving programs on _ z z
w LU
^ Y U
cassette tape, you must take care to always re-insert the jack-plug a.
m W^
properly each time. Y I
0_
I- CC
å II W CO
Uw ^
THE KEYBOARD as ô Ô . W a CC
H
N I-
The Spectrum keyboard has 40 keys arranged in 4 rows of 10. At first
^ J ^
û LLJ
I-
O
sight, it might appear similar to a typewriter keyboard, but on closer w o 44- co
å a + N z
inspection you will see that keys have 5 or 6 functions or characters. In J W
^ ^- z
w
fact: U å W
^
U W
Eight different characters and functions z ^ . N
can be obtained with some keys!
^
a aa cr
z I c w
o >
The keyboard contains: J IA- a z
1 The digits 0 to 9 I-
.
2 The letters of the alphabet printed in upper and lower case
(capitals) ^ 44
^
_
m >
N
w
X
w
z ^
w
3 The complete BASIC language: a
^
U
^
w
J
U
z Z >
o
– instructions w o^ ^
– commands U
CC
– arithmetic, conditional and logical operators ^-
w ^
– arithmetic functions > z
4 Grammatical signs and symbols o m
^
5 Special control keys w
^
6 Graphics symbols n 0 a
w
z w ^
z n ^ a ^ ^
These are all called characters, and are on, below or above the keys o J
used to access them. U U ^ z z
U
Notice that words like PRINT, LIST, RUN, etc are all printed on ^ r ^
the keyboard and also appear on the screen with a single key press. a f- ^ ^
z ^ W z
The Spectrum's ability to print complete words in the BASIC z > ir
a
language at the press of a single key is called:
SINGLE KEYSTROKE BASIC
ô a
^
0
^
J
On most other computers you have to key in each letter of, for
example, the instruction PRINT. This is obviously inefficient. The
^ tt z
a
W
Spectrum is very powerful in this respect. The keyboard contains all z_ w z
J
the characters in the Spectrum's character set, together with a few
special keys. Some 200 or so different characters are available. Some N
print to the screen, others are non-printing (e.g. DELETE). o a 3
O W -
o
U
o z z
w
W
z a
J m
W I1 p
v J w
a ^
z
!n C'S
W
^ O •••■
CD W
444
445
THE CHARACTER TYPES ON THE SPECTRUM KEYS
• • E Mode UNSHIFTED CHARACTER (green)
and microdrive functions which are present on the Spectrum but not on PLOT
C Mode CAPS SHIFT K Mode UNSHIFTED CHARACTER
the ZX81. The Spectrum has an enhanced character set also, with CHARACTER ASN (White)
additional text characters (@, ©, [, J, etc.) not in the ZX81 (upper case)
character set.
As this book deals with the ZX81 computer as well as the Spectrum,
the treatment of additional facilities of the Spectrum is kept to this E Mode SHIFT CHARACTER (red)
separate Spectrum Section, although some comments are made in the
general text about these facilities where appropriate. However, you
must learn how to access all the characters on the keyboard as a first OTHER KEYS Example is Q key
priority.
The keyboard is very complex and it will take some time for you to
find your way around it with ease. It is best described in terms of how There are also the keys for ENTER, CAPS SHIFT, SYMBOL
the characters are accessed and the cursors that indicate which mode SHIFT, and the SPACE key (with BREAK printed above SPACE).
the computer is in. The mode determines how the pressing of a key (a See the keyboard diagram. We must now describe the modes the
keystroke) is interpreted. Each key has multiple meanings for the computer can be in, and the cursors that indicate the mode. There are
computer, depending on the mode and whether either of the SHIFT also two other cursors which we will deal with here.
keys (CAPS SHIFT and SYMBOL SHIFT) is being pressed at the
same time as the keystroke occurs. MODES
You will notice that more characters are available from the top row
of keys. These incorporate the colour control and graphics characters. When inputting (keying in) program lines the position for the next
(The inverse graphics are not shown on the key.) Here are examples of entry is indicated by a cursor on the screen. The mode is indicated by
the two types of key: the flashing cursors _EK Q IGI n
E Mode CAPS SHIFT The I K mode (Keywords) and n (Letters) may be used unshifted,
CAPS SHIFT BLUE 4- COLOUR CONTROL CHARACTER
(in appropriate colour)
with CAPS SHIFT or with SYMBOLS SHIFT. Letters of the
CHARACTER---, EDIT alphabet are lower case unless the CAPS SHIFT key is used or the I I
(white) G Mode. Unshifted mode used. The U mode (Capitals) is obtained by pressing CAPS
L- Graphics Character
K and MODES G Mode Shift gives SHIFT and CAPS LOCK simultaneously and is identical to the L
UNSHIFTED DIGIT €_ Inverse Character ( in this case) mode apart from producing capitals (upper case) instead of lower-case
CHARACTER letters. To return to I LI mode press CAPS SHIFT and CAPS LOCK
DEF FN K and L Modes SYMBOL
SHIFT CHARACTER (red) simultaneously. All letter inputs (REM statements, string inputs and
assignments) in this text are in Capitals. You must use C-mode
1
E Mode SYMBOL SHIFT
exclusively to get listings and printout of letters that correspond to
those in this text.
CHARACTER (Red)
446, 447
•
The I E I mode (Extended) provides the equivalent of the function
•
Note that DELETE works in G mode without CAPS SHIFT being
mode of the ZX81. It is obtained by pressing CAPS SHIFT and pressed.
SYMBOLS SHIFT simultaneously and lasts for one character only.
It may be used unshifted, with CAPS SHIFT or with SYMBOLS E mode — Extended mode, accessing the function
SHIFT. characters in green above the keys in
bottom 3 rows, colour control characters
EFFECTS OF SHIFT KEYS ON MODES on the top row,and the function or
symbol characters in red below all keys.
K mode — expecting a command i.e. Keyword mode. E mode lasts for one character only.
Unshifted — keyword (white word on 3 bottom rows of Unshifted — function or symbol (in green above key
keys) for 3 bottom rows)
—digit (white digit on top row of keys) —colour control (in colour above top row)
CAPS SHIFT — keyword (white word on 3 bottom rows of CAPS SHIFT — function or symbol (in red below key for 3
keys) bottom rows)
—keyword (white word above top row of —colour control (in colour above key for top
keys) row)
SYMBOLS SHIFT — keyword or symbol (red symbol or word SYMBOLS SHIFT — function or symbol (in red below key for 3
on key) bottom rows)
—function (in red below key for top row).
L mode — expecting a letter or a number i.e. Letters
mode, giving the lower case letters. The colour control characters print in a program line as the digit of the
Unshifted — letter (white letter on 3 bottom rows of key that accesses them, i.e. they are coded 1 — 7 and 0. If they are
keys) accessed in E mode without INK or PAPER before them, the effect is
—digit (white digit on top row of keys) to put colour control characters into the display. When unshifted, the
CAPS SHIFT — letter (capitals) (white letter on 3 bottom colour control characters change the background (PAPER) colour of
rows of keys) what is placed on the screen thereafter, and when CAPS SHIFT is
— keyword (white word above top row of pressed, the colour of the character (INK) is changed.
keys) Note: the main body of this text assumes no colours are used, since
SYMBOLS SHIFT — keyword or symbol (red symbol or word the ZX81 cannot produce colour. Colour on the Spectrum is dealt with
in Unit W3. Experiment with colour all you want, but this text is
on key)
primarily about BASIC programming, and it doesn't matter what
colour is on the screen for this!
C mode — identical with L mode but Capital letters
are obtained with Unshifted letter keys. Exercise
G mode — for accessing Graphics symbols. Access all the modes, i.e. get each different cursor on the screen. Key
Unshifted — graphics character (in grey/white on keys in all the characters in each mode, first unshifted, then with CAPS
1 to 8) SHIFT, and finally with SYMBOL SHIFT. You will have to enter the
—user defined graphic on keys A through E mode again after each character. Watch what happens with TRUE
U. (Not shown on keyboard.) VIDEO and INV VIDEO. Notice they reverse each other. Notice you
CAPS SHIFT — inverse graphics character (reverse of can't see a SPACE. Don't press ENTER, just play around on the
symbol on top row of keys) bottom lines of the screen. Notice that the line moves up the screen
SYMBOL SHIFT — same as CAPS SHIFT when it is filled. Press EDIT with CAPS SHIFT to clear the screen.
You can't harm the computer whatever you enter. Note that two words
User defined graphics are dealt with in Unit W2. They are initially are abbreviated on the keyboard, but print in full — RAND and
set as the capital letters A to U, which is what appears on the screen. CONT.
448 449
SYNTAX ERROR CURSOR I
• Character
•
Position
on Keyboard
Mode(s) To Obtain Code
Press
Row, Column
This cursor appears flashing in a line input at the bottom of the screen
if the computer detects an error in the syntax of the line (i.e. finds an A 3,1 L CAPS SHIFT A 65
error in the `grammar' of the BASIC language instruction input). It C A
a 3,1 L A 97
appears when ENTER is pressed to enter the line of program or the ABS 3,5 E G 189
command into memory. The cursor appears before the last error in the ACS 2,2 E SHIFT W 182
line. There may be more than one error, but only one will be indicated AND 2,6 KLC SYMBOL SHIFT Y 198
at a time. Editing (making any change in the line) causes the cursor to ASN 2,1 E SHIFT Q 181
disappear. It will reappear if necessary (error not corrected) when AT 2,8 KLC SYMBOL SHIFT I 172
ATN 2,3 E SHIFT E 183
ENTER is pressed once again. ATTR 3,9 E SHIFT L 171
This table, which is in alphabetical order, will enable the Spectrum D 3,3 L CAPS SHIFT D 68
user to quickly reference any character for: C D
d 3,3 L D 100
its position on the keyboard in terms of a row and column
DEF FN 1,1 E SYMBOL SHIFT 1 206
`parent key' address (e.g. A is in the third row and first column DELETE 1,10 KLCG CAPS SHIFT 0 12
of keys (3,1)) CG 0
- the mode in which the function may be used (indicated by the DIM 3,3 K D 233
flashing cursor on the screen) DRAW 2,2 K W 252
- which keys to press to obtain the function (here SHIFT means
E 2,3 L CAPS SHIFT E 69
that either the CAPS SHIFT or the SYMBOL SHIFT key will C E
give the character) e 2,3 L E 101
- the CODE of the character. EDIT 1,1 KLC CAPS SHIFT 1 7
ENTER 3,10 ENTER 13
ERASE 1,7 E SYMBOL SHIFT 7 210
EXP 4,3 E X 185
450 451
Character Position Mode(s) To Obtain Code Character Position
•
on Keyboard
Mode(s) To Obtain
Press
Code
on Keyboard Press
Row, Column
Row, Column
453
Position Mode(s)
•
To Obtain Code
^
Character
on Keyboard Press Character Position Mode(s) To Obtain Code
Row, Column on Keyboard Press
Row, Column
SQR 3,6 E H 187
STEP 3,3 KLC SYMBOL SHIFT D 205 1,1 KLC SYMBOL SHIFT 1 33
STOP 3,1 KLC SYMBOL SHIFT A 226 2,10 KLC SYMBOL SHIFT P 34
STR$ 2,6 E Y 193 1,3 KLC SYMBOL SHIFT 3 35
SYMBOL SHIFT 4,9 SYMBOL SHIFT 1,4 KLC SYMBOL SHIFT 4 36
% 1,5 KLC SYMBOL SHIFT 5 37
T 2,5 L CAPS SHIFT T 84 1,6 KLC SYMBOL SHIFT 6 38
C T 1,7 KLC SYMBOL SHIFT 7 39
2,5 L T 116 1,8 KLC SYMBOL SHIFT 8 40
TAB 2,10 E P 173 1,9 KLC SYMBOL SHIFT 9 41
TAN 2,3 E E 180 4,6 KLC SYMBOL SHIFT B 42
THEN 3,5 KLC SYMBOL SHIFT G 203 3,8 KLC SYMBOL SHIFT K 43
TO 3,4 KLC SYMBOL SHIFT F 204 3,6 KLC SYMBOL SHIFT H 44
3,7 KLC SYMBOL SHIFT J 45
U 2,7 L CAPS SHIFT U 85 4,8 KLC SYMBOL SHIFT M 46
C U 4,5 KLC SYMBOL SHIFT V 47
u 2,7 L U 117 4,5 KLC SYMBOL SHIFT Z 58
USR 3,9 E L 192 2,9 KLC SYMBOL SHIFT O 59
2,4 KLC SYMBOL SHIFT R 60
V 4,5 L CAPS SHIFT V 86 3,9 KLC SYMBOL SHIFT L 61
C V > 2,5 KLC SYMBOL SHIFT T 62
V 4,5 L V 118 4,4 KLC SYMBOL SHIFT C 63
VAL 3,7 E J 176 4,2 KLC SYMBOL SHIFT Z 64
VAL$ 3,7 E SHIFT J 174 2,6 E SHIFT Y 91
VERIFY 2,4 E SHIFT R 214 2,7 E SHIFT U 93
\ 3,3 E SHIFT D 92
W 2,2 L CAPS SHIFT W 87 3,6 KLC SYMBOL SHIFT H 94
C W 1,10 KLC SYMBOL SHIFT 0 95
w 2,2 L W 119 4,3 KLC SYMBOL SHIFT X 96
3,4 E SHIFT F 123
X 4,3 L CAPS SHIFT X 58 3,5 E SHIFT G 125
C X 2,3 E SHIFT S 124
x 4,3 L X 120 3,1 E SHIFT A 126
© 2,10 E SHIFT P 127
Y 2,6 L CAPS SHIFT Y 59 <_ 2,1 KLC SYMBOL SHIFT 199
Q
C Y >_ 2,3 KLC SYMBOL SHIFT E 200
2,6 L Y 121 <> 2,2 KLC SYMBOL SHIFT W 201
Y
1,5 KLC CAPS SHIFT 5 8
Z 4,2 L CAPS SHIFT Z 90 1,8 KLC CAPS SHIFT 8 9
C Z 9 1,6 KLC CAPS SHIFT 6 10
z 4,2 L Z 122 T 1,7 KLC CAPS SHIFT 7 11
: (space) 1,8 G 8 128
0 1,10 K LC 0 48 1,8 G SHIFT 8 143
1,1 K LC 49 ❑ 1,1 G 129
2 1,2 K LC 2 50 ri 1,1 G SHIFT 142
3 1,3 K LC 3 51 1,2 G 2 130
4 1,4 K LC 4 52 a 1,2 G SHIFT 2 141
5 1,5 K LC 5 53 1,3 G 3 131
6 1,6 K LC 6 54 6 1,3 G SHIFT 3 140
7 1,7 K LC 7 55 1,4 G 4 132
8 1,8 K LC 8 56 ^ 1,4 G SHIFT 4 139
9 1,9 K LC 9 57 r 1,5 G 5 133
Cl 1,5 G SHIFT 5 138
1,6 G 6 134
454
dFF
Character Position Mode(s)
•
To Obtain Code
•
SUMMARY OF ADDITIONAL SPECTRUM FACILITIES
on Keyboard Press
The following are the significant differences between the ZX81 and the
Row, Column
G SHIFT 6 137 Spectrum which have not been dealt with in the main body of the text:
1,6
1,7 G 7 135 (i) The Spectrum gives a colour signal to the TV – see COLOUR
A G SHIFT 7 136
1,7 in Section W3. Of course, it is still possible to use the machine
on a black and white TV, where different shades of grey will be
obtained when the colour commands are used.
(ii) The Spectrum's character set differs from that of the ZX81 and
Colour control characters have no special codes. They have the codes
includes lower case as well as capital letters – see
of, and print as, the digit of the key that accesses them.
CHARACTER SET and USER DEFINED GRAPHICS.
They are on keys 1 to 7 and 0. (iii) The Spectrum's keyboard has additional characters and
is on key 1,3. This gives INK on PAPER functions. You should now be familiar with the functions
TRUE VIDEO
colours (black on white on switch-on). treated in the main text. Extended functions are dealt with a
is on key 1,4. This gives INVERSE, i.e. little later in this Unit.
INV. VIDEO
PAPER colour on INK colour (iv) Simple sound production is available using the Spectrum's
background (white on black if not BEEP command – see SOUND in Section W3.
coloured). (v) The tape storing facilities represent a considerable
These use CODE 20 (a control code), and improvement on those offered by the ZX81 – see TAPE
swap the current INK and PAPER STORAGE below. The tape LOAD and SAVE speed is
colours. roughly 16k words in 100 seconds, and there is a facility to
merge a program stored on tape with one in memory using
Other control codes are as follows: MERGE. The VERIFY facility can be used to check that a
Code program has saved correctly, as has been noted.
Control Character
6 (vi) Disc storage and file-handling capability with the microdrive
Comma for print spacing
Number (in memory) 14 will eventually be available on the Spectrum, loading 16k
16 words per second – see OTHER KEYS below.
Ink control
17 (vii) Additional graphics commands are available to enable straight
Paper control
18 lines, arcs and circles to be drawn simply – see GRAPHICS in
Flash control
19 Section W3.
Bright control
20 (viii) The INPUT statement has additional features and
Inverse control
21 instructions. READ, DATA and RESTORE are added – see
Over control
22 below: PUTTING DATA INTO PROGRAMS.
Print At control
23 (ix) On the Spectrum it is possible to define your own numeric and
Print Tab control
string functions in a program – see USER DEFINED
These control characters are used to store required information in the FUNCTIONS below.
attribute file (colour commands and characteristics of screen display), (x) The Spectrum operates in a `fast mode' at all times and is
and the display file. They are followed by the values they take. roughly four times faster than the ZX81.
User-defined graphics have codes 144 to 164 inclusive, and are set, (xi) Multiple statements on a line are possible on the Spectrum
unless redefined, as the capital letters A to U in sequence. See Unit W3 with a colon(:) as a statement separator. For example:
for more information on this.
10 LET X=4: LET Y=6: LET Z=8
W2: Additional Spectrum BASIC Functions Whilst this is a useful addition, multiple line statements can
also be very confusing and their use should be minimised. This
This Unit covers the additional instructions and functions that are said, they can be useful for additional REM statements,
available in the Spectrum superset of Sinclair BASIC. First we will assignments of related variables and conditional program
indicate the major differences. sequences, and for the combination of graphics and colour
commands.
•
The facility of being able to place a sequence of instructions
•
simply multiply by a factor of four to any PLOTted points in a ZX81
after a conditional test is valuable. The sequence of BASIC program to obtain a working Spectrum version. Hence PLOT 4,10 on
instructions following an IF...THEN will be executed IF the the ZX81 becomes PLOT 16,40 on the Spectrum.
condition is TRUE. Control passes directly to the next line of The Spectrum has no FAST and SLOW modes, as it runs in the
the program if the condition is false. We can write: equivalent of the SLOW mode all the time (always a screen display)
but at the speed of a fast mode. Just omit program lines that contain
10 INPUT a the instructions FAST or SLOW.
20 IF a<1 OR a>9 THEN PRINT "Out of Range":
The Spectrum does not have SCROLL as a program instruction as
GOTO 10
the ZX81 does. To SCROLL the screen in a Spectrum program you
30 PRINT a
need to POKE the location 23692 with a number greater than 1, or
It is important to remember that you can only GOTO a line with — 1. This temporarily disables the `SCROLL?' request, and
number and start at the beginning of that line. You cannot when followed by PRINTing AT the last line (line 21) on the screen the
access the second or subsequent statements of a line with display will SCROLL.
multiple statements. Thus the ZX81 line:
(xii) There is no SCROLL key on the Spectrum, but scrolling is
200 SCROLL
done automatically by pressing any key (except N, STOP,
BREAK) when `Scroll?' appears on the screen. Making the is replaced by
Spectrum SCROLL in the same way as the ZX81 SCROLL
200 POKE 23692, — 1 : PRINT AT 21,0;
command has been covered in the text.
(xiii) It is important to note that CLEAR operates differently on the Raising a number to a power on the ZX81 uses the symbol `**'
Spectrum than on the ZX81. CLEAR not only erases all whereas on the Spectrum we use ` t '. RAND in ZX81 programs is
variables in memory, but also resets RAMTOP and that instruction on the Spectrum keyboard, but prints as
RESTOREs as well as clearing the GOSUB stack. In fact you RANDOMISE.
can use CLEAR on the Spectrum to reserve protected memory POKEing to the display file cannot be easily done, and the same is
space above RAMTOP: using a command like CLEAR 23800 true of PEEK used to identify a character on the screen. To get around
sets RAMTOP to 23800. This cannot be done on the ZX81. this we recommend using PRINT AT instead of POKEing the display,
and SCREEN$ to replace PEEKing the display. Hence you will have
You have seen the modifications required for the ZX81 programs to to calculate what character cell position corresponds to any address in
run on the Spectrum. Here is a summary for reference, to convert any the ZX81's display file which is used in a program. Read the
programs you may come across in books or magazines. All programs in description of the ZX81 display file in Unit Q4 in order to find out how
the text and the program library (Appendix VI) are annotated with any to do this.
required Spectrum changes. PEEKing the character table in RAM is done equally simply on the
Spectrum, with the start of the character table being given by the
ZX81 TO SPECTRUM PROGRAM CONVERSION following PEEKs, plus 256:
458 459
•
long program with the smaller machine it is worth making a crude
(ii) VERIFICATION of Information on Tape
estimate of the program length, if the information is not given in the
documentation. The number of lines in the listing (total, not numbered The VERIFY key is used to check the information saved on the
lines only), multiplied by 15 will give you a reasonable estimate (biased tape against the information in the computer.
on the high side) of the program length in bytes. VERIFY "filnam" – checks programs and variables
VERIFY "alpha" DATA a() – checks numeric array
specified
We will now go on to cover the additional Spectrum facilities and
functions, other than those connected with Colour, Graphics and VERIFY "beta" DATA b$() – checks string array specified
VERIFY "gamma" CODE 16384, 6912 – checks bytes
Sound, which are treated in Unit W3.
specified (first number – address of first byte, second
number – number of bytes).
TAPE STORAGE
460 461
Program "delta" on tape:
10 PRINT "no"
• •
This will result in the inputs being placed on separate lines (note
what these co-ordinates mean). The lower part of the screen will
20 PRINT "yes" move up to allow all input lines to be on screen. (The upper part
60 PRINT "repeat" remains unaltered until the lower part would start to write on the
same line – the upper part then starts to scroll.)
MERGE "delta" results in the program: 10 INPUT LINE a$ allows input of a string without the
10 PRINT "no" computer inserting quotes around the
20 PRINT "yes" cursor.
30 PRINT "goodbye"
40 PRINT (ii) READ and DATA
50 PRINT "end"
60 PRINT "repeat" These keys allow data to be stored internally within the
Note the restriction on the use of MERGE. It can only be used for program. For example:
numbered program lines. These can have defined arrays or variables
that are transferred with the program, but direct data (array values or 10 READ a,b,c
bytes) is not MERGEable. See Units T11 and T12 for storing data, 20 PRINT a,b,c
and remember that as long as there is one program line, MERGE will 30 DATA 10,20,30
work.
The computer looks at all lines containing DATA statements
and puts them sequentially into a data bank. A pointer is
PUTTING DATA INTO PROGRAMS
associated with the data bank and is initially set to the first item.
New keywords: READ, RESTORE and DATA 10 20 30
Extended function for INPUT key T
When the program reaches a line with a READ statement, the
(i) INPUT Statement first data item is allocated to the variable (i.e. a = 10) and the
pointer moves to the second item and so on. So b = 20 and
10 INPUT A$ allows input of one string c = 30.
20 INPUT A,B,C,D allows input of four Note (i) DATA items are separated by commas
numbers (ii) variables in READ statements are separated by
30 INPUT "Enter your name", N$ allows the part within commas
inverted commas to be (iii) string data items must be in inverted commas
printed at the bottom of For example:
the screen.
10 READ a$,b,c$,d
If we key in: 20 PRINT a$,b,c$,d
30 DATA "smith", 90
10 LET M$ = "SPECTRUM" 40 DATA "jones", 60
20 INPUT ("I am" ;m$;"."); "Your name?", y$
these two lines will produce at the bottom of the screen: I am RESTORE
SPECTRUM. Your name? " cursor "
It is also possible to use INPUT AT in a similar way to The RESTORE statement may be used to alter the position of
PRINT AT: the pointer. For example:
462 463
40 PRINT a$,b,c$,d
• •
5 LET a = 10: LET b = 20
50 DATA "smith", 90, "joues", 60
10 DEF FN p(x,y,z) = a*x T 2+ b*y T 2+ z
20 PRINT FN p(1,2,3)
The effect of line 20 is to reset the pointer to the first item. Thus
30 PRINT
a$ = "smith", b = 90, c$ = "smith", d = 90. It is also possible to
40 PRINT FN p(3,2,1)
use RESTORE with a line number in which case the pointer is
reset to the first item of the data statement of that line (or
Note that any constants occurring (in this case a,b) are not included in
following lines). For example:
the FN; only the variable values are specified (in this case x, y and z).
Thus line 20 gives 93 and line 40 gives 171.
10 READ a$,b
20 RESTORE 100
30 READ c$,d CHARACTER SET AND USER DEFINED GRAPHICS
40 PRINT a$,b,c$,d
50 DATA "smith", 90, "jones", 60 (t) Character Set
100 DATA "brown", 100, "white", 120
200 DATA "black", 8, "yellow", 6 The character set consists of 256 characters each having a code
between 0 and 255. The set consists of:
This will allocate a$ = "smith", b = 90 and c$ = "brown",
d = 100 (whereas 20 RESTORE gives c$ = "smith", d = 90 Control characters (code 0 to 31)
and 20 RESTORE 200 gives c$ = "black", d = 8). ASCII characters (plus the non-standard £ and (D)
If CLEAR is used on the Spectrum, it also does a RESTORE Spectrum graphics symbols
on the data. User-defined graphics
USER DEFINED FUNCTIONS The program given below will print out the complete character
set (excluding the control characters):
New keywords: DEF FN and FN 10 FOR n = 32 TO 255: PRINT CHR$ n; : NEXT n
The user can define up to 26 numeric and 26 string functions in any (ii) User defined graphics
program.
A numeric function is named FN followed by a single letter — e.g. These are the letters A to U in graphics mode. They initially
FN Z. print as these letters (in capitals), until defined. They enable one
A string function is named FN followed by a single letter and $ — e.g. to print a given shape in a character cell by pressing a single key.
FN A$. EXAMPLE: Fill the screen with dogs. Begin by producing a
It is necessary to define the function using a DEF FN statement (i.e. dog shape which fills a character cell when GRAPHICS D is
by pressing the DEF FN key). For example: pressed and then display the dogs across the screen.
(i) Fill in appropriate squares in 8 by 8 cell
10 DEF FN a(x) = x T 3 (ii) Allow 1 for ink, 0 for paper
20 PRINT FN a(3) (iii) Put appropriate numbers in data statements
Line 10 defines the function and line 20 would give 3' = 27. For strings: Binary Decimal
x x x x 11100001 225
10 DEF FN q$(a$) = a$ (2 to 6) x x x x 11100010 226
20 PRINT FN q$("harrison") x x x x x x 11111100 252
x x x x 00111100 60
Line 10 defines a string function and line 20 would give `arris'. x x x x 00111100 60
You may also use functions with several variables: x x x x 00111100 60
x x 00100100 36
x x 00100100 36
464
465
10 REM USE,- defined 9=aphic_
• 2 red
20 REM de f i nadc•9
30 FOR n=0 TO 7 3 magenta
40 REND 4 green
50 POKE USR •D"tn,>c
60 NEXT n
70 DRTA 225, 226, 252,60, 60, 60,3 5 cyan
6,36 6 yellow
50 REM screenfUl of dc9 s.
a0 BORDER 4: PAPER E. INK 0: C 7 white
L_
100 FOR l=0 TO 20 STEP 2
110 FOR c=0 TO 30 STEP 2
120 PRINT AT l , c ; "D'" Magenta is a purple colour, and cyan is light blue.
130 NEXT c
140 NEXT l Unless otherwise specified, both BORDER and PAPER are
white. The colour of border and paper can be changed to any of
The BIN key allows you to enter binary numbers – i.e. BIN the eight normal colours. For example:
11100001 is equivalent to 225 in the DATA statement (line 65). BORDER 4: the border becomes green on pressing the
ENTER key
The plot of the user-defined graphic in the 8 x 8 grid, expressed
PAPER 2: no change occurs on pressing the ENTER
in binary form, can thus be centred directly with the use of BIN
key (it merely cancels PAPER command
into the DATA statement:
already existing). Press the ENTER key
70 DATA BIN 11100001, BIN 11100010, etc.
again and the centre becomes red.
(On a black and white TV the above numbers correspond to
OTHER KEYS the order of brightness).
Both instructions can be used in programs:
The following keys will only operate when the Sinclair microdrive and 10 BORDER 2: PAPER 6
the RS 232 (standard printer) interface become available: These are global commands defining the whole border and
paper areas. PAPER may be used as a specific command (see
OPEN # , CLOSE # , MOVE, ERASE, CAT and FORMAT. below).
The keys IN and OUT are associated with I/O ports (input and output (ii) PICTURE
ports) and enable the SPECTRUM to communicate with peripheral
devices. The equivalent commands used by the operating system run 'The picture area affected by the global PAPER instruction
the ZX Printer. They are beyond the scope of the present text. The use consists of 24 lines each of 32 positions, i.e. 24 x 32 = 768
and format of these instructions will be specified in the documentation character cells. The screen that can normally be printed to is 22
of any equipment using them. lines of 32 character cells. The character cells have printing
characteristics (attributes) which may be specified.
Each character cell consists of 8 x 8 dots and has two colours
W3: Colour, Graphics and Sound associated with it:
466 467
•
the ink and paper colours. In addition, 8 can be used with all
•
EXAMPLE 1
four statements meaning transparent (i.e. left as previous); 9
can be used with PAPER and INK meaning contrast. PAPER This is a simple program to display the colours available and to show
will be dark (black) if INK is specified as a light colour (colours 0 the effect of the transparency and contrast commands.
to 3), light (white) if INK specified as a dark colour (colours 4 to
7). INK produces contrasting PAPER in the same way. 5 REM colours
10 FOR n =1 TO 22: FOR p=0 TO 7
20 PAPER P: PRINT " ,
(iii) INVERSE, OVER AND ATTR 30 NEXT p: NEXT n
40 PAUSE 100
45 REM transparency and contra
The statements INVERSE and OVER may also be used to st
control the dot pattern printed in the character cells. 50 INK 9: PAPER 6: PRINT AT 0,
0;
60 FOR n=1 TO 66: PRINT "colou
inverse or normal i.e. INVERSE 1 (inverse video) or rings";: NEXT D: PRINT
INVERSE 0 (normal video) 70 PAPER 7: INK 0: BRIGHT 0
80 PAUSE 100
over or normal i.e. OVER 1 (overprints the new
character on top of the old)
OVER 0 (normal) EXAMPLE 2
All the statements in (ii) and (iii) may be used in conjunction This is a simple program drawing coloured straight lines with different
with PRINT and INPUT commands and also with graphics separations.
commands such as PLOT and DRAW. For example: Line 30 — gives a black border.
Line 320 — gives paper and ink colours (selected at random,
10 INPUT INK 2; FLASH 1; "What is your name?"; N$ excluding black and white).
20 PRINT PAPER 6; NS Line 200 — resets paper and border to white, ink to black for listing
etc. after program has been run.
which will result when run in `What is your name?' flashing in Notice how colours are character cell dependent not pixel dependent.
red and white and the name input (in black and white) is then This program clearly shows this effect.
printed out in black on yellow. If not specified, the PAPER 30 BORDER 0
instruction assumes the contrasting INK, FLASH 0 and 40 FOR x=0 TO 254 STEP 2
BRIGHT 0. 50 PLOT 128,88: DRAW -127+x,-8
7
The attributes of any character cell (i.e. PAPER, INK, 60 NEXT x
BRIGHT and FLASH) on the screen may be determined using 65 GO SUB 300
70 FOR y=0 TO 174 STEP 3
the ATTR key, which returns a number made up as follows:
80 PLOT 128,88: DRAW 127,-87+y
90 NEXT y
FLASH on (128), normal (0) + 95 GO SUB 300
BRIGHT on (64), normal (0) + 100 FOR z=0 TO 254 STEP 2
110 PLOT 128,88: DRAW 127-z,87
PAPER (8*colour) + 120 NEXT z
INK (colour) 125 GO SUB 300
130 FOR a =0 TO 174 STEP 3
140 PLOT 128,88: DRAW -127,87 -a
Thus, 10 PRINT ATTR (19,20) would give the number 162 if 150 NEXT a
the character cell at (19,20) is flashing (128), normal (0), green 200 PAPER 7: INK 0: BORDER 7
paper (32) and cyan ink (2). 210 STOP
300 LET i=(5*RND+1): LET p=INT
The TRUE VIDEO instruction gives the INK colour on (5*RND)+1
PAPER colour background. This may be changed to 310 IF i=p THEN GO TO 10
INV.VIDEO (PAPER colour on INK colour). All succeeding 320 PAPER p: INK i
330 RETURN
printed character squares have the attributes shifted as if
INVERSE had been used.
acn
• •
the point X1 pixels to the right and Yl pixels up from
it. For example:
10 PLOT 30,30
GRAPHICS 20 DRAW 60,60
30 DRAW 80,80, PI
New keywords: DRAW, CIRCLE, POINT
CIRCLE X,Y,A draws a circle centre (X,Y) and radius A
The screen is 22 lines by 32 columns – i.e. 704 character cells for POINT (X,Y) will give 0 if pixel at (X,Y) is paper colour and 1 if ink.
graphics use. Each character cell consists of 8 by 8 dots (called pixels). For example:
Thus the pixel co-ordinates go from (0,0) bottom left-hand corner to (255, 10 CIRCLE 40,40,30 – draws circle centre (40,40) and radius 30
175) the top right-hand corner. 20 PRINT POINT (40,40)– pixel paper – 0
30 PRINT POINT (70,70)– pixel ink – 1
Colour Graphics
The commands INVERSE and OVER may be used with the graphics
You can do graphics in colour but remember that the pixels in any commands. For example:
one character cell can only be either of the two colours corresponding to
the current ink and paper values for the character cell. PLOT INVERSE 1 will put paper colour at pixel
For example, let's attempt to draw three circles one black, one blue and PLOT OVER 1 will change ink to paper at pixel
one red:
There is no UNPLOT on the Spectrum. We must use INVERSE or
10 INK 2 : CIRCLE 40,40,30 (red circle) OVER. PLOT OVER 1 or PLOT INVERSE 1 effectively unplot the
20 INK 1 : CIRCLE 60,60,40 (blue circle) pixel. DRAW OVER 1 may be used to rubout a line while preserving
30 INK 0 : CIRCLE 50,50,40 (black circle) the original information; compare result of program 1 with that of
program 2.
This example shows that colour graphics is possible but can only be
handled with great care. It is important to be clear about character cells
10 FOR n=1 TO 22
as opposed to pixels. For example, you can draw three circles one black,
2.141r1441
one blue and one red: 30 NEXT n
40 PLOT 0,0: DRRU 255,175
45 STOP
10 INK 2 : CIRCLE 70,70,70 (red circle) 50 PLOT 0,0: DRRU INVERSE 1;25
5,17 5
20 INK 4 : CIRCLE 70,70,50 (blue circle)
30 INK 0 : CIRCLE 70,70,30 (black circle) 10 FOR n=1 TO 2 2
20 PRSNT
30 NEXT n
Graphics Commands 40 PLOT 0,0: DR R U 255,175
45 STOP
50 PLOT 0,0: DRU INVERSE 1;25
– inks in the pixel at the point (X,Y) 5,175
PLOT X,Y
DRAW X1,Y1 – inks in the line from the point specified previously to
471
Try this one-line program:
• •
2 Use of DRAW command (arcs of circles)
10 PLOT 65,27: DRAW OVER 1; 120,120,49*3*PI This program produces a pattern by drawing four sets of
Try different values in place of 49. semicircles. The basic plotting line is illustrated by the diagram
of the effect of line 40. This is repeated within a series of four
loops.
EXAMPLES
- W
10 LET a=0
20 FOR n=129 TO 254 STEP 3
30 LET a=a+1
40 PLOT n,0: DRAW*a,O,PI
—h h 50 NEXT n
60 LET b=0
70 FOR n=129 TO 254 STEP 3
80 LET b=b+1
90 PLOT n,175: DRAW -6*b,0,-PI
100 NEXT n
X,y0 110 LET c=0
120 FOR n=90 TO 174 STEP 3
130 LET c=c+1
10 REM Histogram using DRAW 140 PLOT 0,n: DRAW 0,-6*c,-PI
20 READ x0,y0: LET x=x0 150 NEXT n
25 REM Coordinates of LHS 160 LET d=0
30 READ w,n 170 FOR n=90 TO 174 STEP 3
35 REM Width and number of uni 180 LET d=d+1
is 190 PLOT 255,n: DRAW 0,-6*d,PI
40 FOR j=1 TO n 200 NEXT n
50 READ h
60 REM Unit height
70 PLOT x,y0
80 DRAW w,0: DRAW 0,h: DRAW
,0: DRAW 0,-h
90 LET x=x+w
100 NEXT j
105 DATA 5,5,20,12
110 DATA 12,45,67,98,134,167,17
0,136,124,87,46,20
472 473
•
Try inserting the following lines to see the effect of colour (note
•
in sequence again. Note the capability to define a function using
graphics is pixel but colour is character cells). variables, and then define the values of the variables as
appropriate. In this case, two values (COSx and SINx) are given
5 INK 2 to b, and the amplitude a is defined as first 5, then 15. Four plots
55 INK 5 are produced from the one user-defined function of line 5.
105 INK 6
5 DEF FN y (X) =b*3
155 INK 3 10 GO TO 120
14
15 REM **FUNCTION ONE PLOT **
**SUBROUTINE **
3 Use of CIRCLE command 16
This command draws a circle and by varying the position of the 20 FOR x=0 TO 25 STEP .1
30 LET b=CO5 x: GO 508 200
centre and the radius of the circle we can obtain an acceptable 40 NEXT X
50 RETURN
drawing of a cone: 55 REM **END FN ONE SUB **
56
5 REM Draw a cone 57
60 REH **FUNCTION TUO PLOT **
10 READ i,p,b **SUBROUTINE
15 REM ink,paper,border 61 **
20 READ cr 70 FOR X=0 TO 25 STEP
80 LET b=5IN x, GG SUE 200
25 REM radius of cone ?0 NEXT x
30 CLS : INK i: BORDER b: PAPE 100 RETURN
105 REH **END FN TUO SUE **
R p: CIS ***********************
40 LET x=50 106
110 REH **********************
50 FOR r=cr TO 1 STEP -1 **HRIN PROGRRM
120 LET R=5 **
60 CIRCLE x,90,r
70 LET x=x+3
130 GO SUE 20
140 GO SUE 70
80 NEXT r 150 LET a=15
90 DATA 1,4,6
160 GO SUB 20
170 GO SUB 70
100 DATA 50,3 180 STOP
185 REM **END MRIN PROcRRM**
186
190 REH *SUBROUTINE-CRLCULRTE**
**USING FN RND PLOT **
200 LET y=FN y(X)
210 PLOT x*10,y*3+60
220 RETURN
229'
230 REH **END5UB FUNCTION USE**
OPERATING COMMANDS
INPUT/OUTPUT INSTRUCTIONS
OTHER INSTRUCTIONS
476 477
DIM V[$] (n[,m])
^
Dimensions array n by m (numeric), n strings of 4 NOT
• logical inversion
length m if string 3 AND logical AND
RAND [n1 Random number seed 2 OR logical OR
RND Function returns a random number n. 0< = n<1
Transfers control to line n ZX Spectrum Basic Summary
GOTO n
GOSUB n Go to Subroutine at line n
RETURN Return from subroutine to line after last GOSUB CONVENTIONS
IF e THEN <s> If e is true THEN statement s is done, if e is
false then s is not done. For e see expressions. n, m or p numeric expressions
Evaluates as TRUE = I, FALSE = 9 string expression
FOR V = n TO m [STEP pl V is any single letter control variable. e expression (string or numeric)
m,n,p any numeric expressions. STEP 1 is V variable name
<s>
assumed if STEP not specified <s> statement
[<s>]
NEXT V Increments V by STEP. Goes to next line if [] indicates an optional item
V>m (m>n) or V<m (n>m).
Numeric variables are first character a letter then any alphanumeric characters.
TRIG FUNCTIONS String variables are a letter followed by $.
478 479
•
followed by the name (single letter) of the string
or numeric function and the definition – e.g.
ATTR (n,m)
•
Picture is divided into 768 (24 lines of 32 columns) character cells.
481
LN n
PI
•
natural logarithm of n (i.e. log n or In n)
n, 3.1415927
• APPENDIX Il
4O0
483
C The text of the (string) argument of VAL does not VAL
form a valid numerical expression.
• 5
Code Meaning
Out of screen
• Situations
INPUT, PRINT AT
D (i) Program interrupted by BREAK. At the end of any An INPUT statement has tried to generate more
statement as the program than 23 lines in the lower half of the screen. Also
runs or in LOAD, SAVE, occurs with PRINT AT 22,...
LPRINT, LLIST or
6 Number too big Any arithmetic. Division
COPY.
Calculations have led to a number greater than by zero is common cause.
(ii) The INPUT line starts with STOP. INPUT about 10's.
F The program name provided is the empty string. SAVE 7 RETURN without GO SUB RETURN. No STOP
There has been one more RETURN than there were statement before a
Spectrum Error Codes GO SUBs. subroutine is common.
8 End of file Microdrive, etc,
The report has a code number or letter (so that you can refer to the following table), a
operations only.
brief message explaining what happened and the line number and statement number
within that line where it stopped. (A command is shown as line 0. Within a line, 9 STOP statement STOP
statement 1 is at the beginning, statement 2 comes after the first colon or THEN, and After this, CONTINUE will not repeat the STOP,
so on.) but carries on with the statement after, or next line
The behaviour of CONTINUE depends very much on the reports. Normally, after, STOP.
CONTINUE goes to the line and statement specified in the last report, but there are A Invalid argument SQR, LN, ASN, ACS,
exceptions with reports 0, 9 and D. The argument for a function is no good for some USR (with string
Here is a table showing all the reports. It also tells you in what circumstances the reason. argument)
report can occur. B Integer out of range RUN, RANDOMIZE,
When an integer is required, the floating point POKE, DIM, GO TO,
Code Meaning Situations
argument is rounded to the nearest integer. If this is GO SUB, LIST, LLIST,
outside a suitable range then error B results. PAUSE, PLOT, CHR$,
0 OK Any
PEEK, USR (with
Successful completion, or jump to a line number
numeric argument)
bigger than any existing. This report does not
change the line and statement jumped to by C Nonsense in BASIC VAL, VAL$
CONTINUE. The text of the (string) argument does not form a
valid expression.
1 NEXT without FOR NEXT
The control variable does not exist (it has not been Jumping into a loop is a D BREAK - CONT repeats LOAD, SAVE, VERIFY,
set up by a FOR statement), but there is an ordinary common cause. BREAK was pressed during some peripheral MERGE, LPRINT,
variable with the same name. operation. LLIST, COPY. Also
The behaviour of CONTINUE after this report is when the computer asks
2 Variable not found Any
normal in that it repeats the statement. Compare scroll? and you type
For a simple variable this will happen if the variable
with report L.
is used before it has been assigned to in a LET,
READ or INPUT statement, loaded from tape or E Out of DATA READ
set up in a FOR statement. For a subscripted You have tried to READ past the end of the DATA
variable it will happen if the variable is used before it list.
has been dimensioned in a DIM statement or loaded F Invalid file name SAVE
from tape. SAVE with name empty or longer than 10
3 Subscript wrong Subscripted variables characters.
A subscript is beyond the dimension of the array, or (arrays), G No room for line Entering a line into the
there are the wrong number of subscripts. If the Substrings There is not enough room left in memory to program
subscript is negative or bigger than 65535, then error accommodate the new program line.
B will result. H STOP in INPUT INPUT
4 Out of memory LET, INPUT, FOR, Some INPUT data started with STOP, or - for
There is not enough room in the computer for what DIM, GO SUB, LOAD, INPUT LINE - BREAK was pressed.
you are trying to do. If the computer really seems to MERGE. Sometimes Unlike the case with report 9, after report H
be stuck in this state, you may have to clear out the during expression CONTINUE will behave normally, by repeating the
command line using DELETE and then delete a evaluation. INPUT statement.
program line or two (with the intention of putting I FOR without NEXT FOR
them back afterwards) to give yourself room to There was a FOR loop to be executed no times (e.g.
manoeuvre with - say - CLEAR. FOR n = 1 TO 0) and the corresponding NEXT
statement could not be found.
484 485
Code Meaning
2. SHIFT CHARACTERS
486
dR7
^
4. GRAPHICS CHARACTERS
CHARACTER CODE CHARACTER CODE
488 489
•
INVERSE
• APPENDIX IV
INVERSE
CODE CHARACTER CODE Use of Cassette Tapes
CHARACTER
166 Z 191
A The following information concerns the use of cassette tapes for program storage and
184 X 189
S retrieval. Other details of personal tape library practice can be found in the main text.
169 C 168
D 1 New tapes: Always 'fast forward' and 'rewind' a tape completely before use for
171 V 187
F program storage. This ensures an even winding and tension. If you have the
172 LINE 4 B 167
LINE 3 G patience, running the tape one way in 'play' mode after fast forward and reverse is
173 N 179
H desirable.
175 M 178
^ 155 2 Do not use the first 15 or 20 seconds of any tape. Most tape problems of coating
K 176 loss and stretch occur in this portion of the tape.
177 128
L 3 Always rewind tapes fully after use, so as to not leave tape with program data
(SPACE)
exposed. Never touch the surface of the tape. Before inserting a tape in the cassette
player, take up the slack in the tape (using a finger or a pencil) by turning one
TOTAL 38 Characters. drive wheel until the other moves.
May be entered in ® mode obtained by SHIFT I I GRAPHIC I keys. 4 Always replace tapes in the correct library boxes immediately after use. Leave the
label side (if only one label) showing.
Obtained by pressing desired keys.
5 Tapes with programs meant to be permanent should have the tags removed to
prevent accidental erasure. The holes can always be covered with sticky tape if you
decide in the future to record over a program.
6 Clean the tape-recorder heads after 2 or 3 hours' running time with a head cleaner
6. FUNCTION CHARACTERS
cassette or head cleaner fluid. De-magnetise heads every 10 or 12 hours' running.
CODE 7 Leave long gaps (at least 20 seconds) between programs, if more than one program
CHARACTER CODE CHARACTER
is on a tape. Note the tape counter readings for beginning and end of each
199 LN 205 program. Remember that the tape counter is not highly accurate. You can use the
SIN
EXP 206 TV screen to find a gap between programs, watching for the thick black lines of a
COS 200
201 AT 193 program load display change to the thin diagonal lines of a 'blank tape' display.
TAN
207 INKEY$ 65 8 Loading problems. These are notes for the ZX8I user. No problems should be
INT
64 LINE 4 NOT 215 encountered with the Spectrum in this respect. For each individual ZX81/cassette
LINE 2 AND
213 tt(PI) 66 system, no problems should be encountered with SAVEing and LOADing
STR$
214 programs with the TONE control set high, and the VOLUME at 3/4 volume. The
CHR$
196 characteristics of tape recorders vary somewhat, however, and problems may be
CODE
211 encountered in LOADing programs which have been SAVEd on a different
PEEK
194 recorder. Here is a sequence to be followed if a program proves difficult to LOAD.
TAB
A Set the TONE control for maximum treble ('High').
ARCSIN 202
B Set the VOLUME to about three-quarters of the maximum.
ARCCOS 203
C Rewind tape to the beginning.
ARCTAN 204
209 D Type: LOAD "A" – i.e. any letter/word except the program name.
LINE 3 SGN
210 Press PLAY on the cassette, then NEWLINE (ENTER) on the ZX8I.
ABS
208 When the thin, slightly sloping black lines change to the programs' typical
SQR
197 thick black and white lines, with approximately equal black and white
VAL
198 bands, with the white crossed by vertical black lines:
LEN
(a) DECREASE THE VOLUME until this changes back to the THIN
USR 212
lines.
(b) Now INCREASE THE VOLUME, noting where the THICK black
TOTAL 25 Characters.
May be entered in E mode obtained by pressing I SHIFT FUNCTION and white program lines eventually seem to become more unsettled
or predominantly black.
key. Also if you listen to the recording you may be able to notice when the
Characters obtained by pressing desired character key.
volume is too high and causes distortion.
The ® mode operates for only one character input.
E Set the VOLUME midway between these two points (a) and (b).
Rewind tape.
Type: LOAD "(The program name)".
Press PLAY on the cassette, then NEWLINE (ENTER) on the ZX8I.
If the screen suddenly clears before the program should end, this may
mean volume is still too low.
nnn 491
• APPENDIX V
The ZX81 may need to be re-set by pulling out the d.c. supply plug and
re-inserting it if the cursor does not return to the screen, either by itself or System Variables – ZX81
when BREAK is used.
LOAD again, slightly increasing the volume, after rewinding the tape. Notes:
If you cannot get a definite, THICK black and white line pattern even at X The system may crash if the variable is poked.
full volume then your recorder may not be powerful enough to load from N Poking the variable will have no lasting effect.
the signal strength on this specific tape. Test this by using another S The variable is saved by SAVE.
recorder, or recorder/ZX system. Once the program has LOADed, SAVE
it on to a tape in your own recorder. The number in column I is the number of bytes storing the variable. For two bytes,
Turn off cassette recorder and take the EAR/MIC leads out of the ZX81 the first one is the less significant byte. To poke a value M to a two-byte variable at
before swapping recorders, or else you may cause the system to crash address N use:
whilst taking out and re-inserting the plugs.
9 NEVER place a tape on top of the TV monitor. This can affect the signals stored POKE N (M = 256"INT(M/256))
on the tape because of the electromagnetic field generated by the TV. POKE N + I, INT M/256
PEEK N + 256"PEEK(N + 1)
492 493
S2 16408 X_PTR
•
Address of the character preceding the
marker.
a System Variables – Spectrum
•
SX2 16410 STKBOT Notes:
See Unit U2.
SX2 16412 STKEND X The system may crash if the variable is poked.
SNI 16414 BERG Calculator's b register. N Poking the variable will have no lasting effect.
SN2 16415 MEM Address of area used for calculator's The number in column 1 is the number of bytes in the variable. For two bytes, the
memory. (Usually MEMBOT, but not first one is the less significant byte. To poke a value M to a two-byte variable at address
always.) N use
S1 16417 not used
SX1 16418 DF_SZ The number of lines (including one blank POKE N(M – 256" INT(M/256))
line) in the lower part of the screen. See Unit POKE N + 1, INT M/256
Q4.
S2 16419 S_TOP The number of the top program line in and to peek its value, use the expression
automatic listings.
SN2 16421 LAST_K Shows which keys pressed. POKE N + 256"PEEK (N + 1)
SNI 16423 Debounce status of keyboard.
SN1 16424 MARGIN Number of blank lines above or below Notes Address Name Contents
picture: 55 in Britain, 31 in America.
N8 23552 KSTATE Used in reading the keyboard.
SX2 16425 NXTLIN Address of next program line to be executed.
N1 23560 LAST K Stores newly pressed key.
S2 16427 OLDPPC Line number to which CONT jumps.
1 23561 REPDEL Time (in 50ths of a second – in 60ths of a
SN1 16429 FLAGX Various flags.
second in N. America) that a key must be
SN2 16430 STRLEN Length of string type destination in
held down before it repeats. This starts off at
assignment.
35, but you can POKE in other values.
SN2 16432 T_ADDR Address of next item in syntax table (very
1 23562 REPPER Delay (in 50ths of a second – in 60ths of a
unlikely to be useful).
second in America) between successive
S2 16434 SEED The seed for RND. This is the variable that
repeats of a key held down: initially 5.
is set by RAND.
N2 23563 DEFADD Address of arguments of user-defined
S2 16436 FRAMES Counts the frames displayed on the
function if one is being evaluated; otherwise
television. Bit 15 is 1. Bits 0 to 14 are
0.
decremented for each frame sent to the
N1 23565 K DATA Stores 2nd byte of colour controls entered
television. This can be used for timing, but
from keyboard.
PAUSE also uses it. PAUSE resets to 0 bit
N2 23566 TVDATA Stores bytes of colour, AT and TAB controls
15, and puts in bits 0 to 14 the length of the
going to television.
pause. When these have been counted down
X3g 23568 STRMS Addresses of channels attached to streams.
to zero, the pause stops. If the pause stops
2 23606 CHARS 256 less than address of character set (which
because of a key depression, bit 15 is set to 1
starts with space and carries on to the
again.
copyright symbol). Normally in ROM, but
S1 16438 COORDS x-coordinate of last point PLOTted.
you can set up your own in RAM and make
S1 16439 y-coordinate of last point PLOTted.
CHARS point to it.
S1 16440 PR_CC Less significant byte of address of next
1 23608 RASP Length of warning buzz.
position for LPRINT to print at (in
1 23609 PIP Length of keyboard click.
PRBUFF).
1 23610 ERR NR 1 less than the report code. Starts off at 255
SX1 16441 S_POSN Column number for PRINT position.
(for – 1) so PEEK 23610 gives 255.
SX1 16442 Line number for PRINT position.
X1 23611 FLAGS Various flags to control the BASIC system.
S1 16443 CDFLAG Various flags. Bit 7 is on (1) during compute
X1 23612 TV FLAG Flags associated with the television.
and display mode.
X2 23613 ERR SP Address of item on machine stack to be used
S33 16444 PRBUFF Printer buffer (33rd character is
as error return.
NEWLINE).
N2 23615 LIST SP Address of return address from automatic
SN30 16477 MEMBOT Calculator memory area; used to store
listing.
numbers that cannot conveniently be put on
N1 23617 MODE Specifies K, L, C, E or G cursor.
the calculator stack.
2 23618 NEWPPC Line to be jumped to.
S2 16507 not used 1 23620 NSPPC Statement number in line to be jumped to.
Poking first NEWPPC and then NSPPC
forces a jump to a specified statement in a
line.
2 23621 PCC Line number of statement currently being
executed.
494 495
1 23623
Notes Address Name
SUBPPC
Contents
•
Number within line of statement being
Notes
1
Address
•
Name Contents
executed. 23681 Not used.
BORDCR Border colour ' 8; also contains the attributes 2 23682 ECHO E 33-column number and 24-line number (in
1 23624
normally used for the lower half of the lower half) of end of input buffer.
screen. 2 23684 DF CC Address in display file of PRINT position.
Number of current line (with program 2 23686 DFCCL
2 23625 E PPC Like DF CC for lower part of screen.
cursor). XI 23688 S POSN 33-column number for PRINT position.
Address of variables. XI 23689 24-line number for PRINT position.
X2 23627 VARS
Address of variable in assignment. X2 23690 SPOSNL Like S POSN for lower part.
N2 23629 DEST
Address of channel data. 1 23692 SCR CT
X2 23631 CHANS Counts scrolls: it is always I more than the
X2 23633 CURCHL Address of information currently being used number of scrolls that will be done before
for input and output. stopping with scroll?
Address of BASIC program.
1 23693 ATTR P Permanent current colours, etc. (as set up by
X2 23635 PROG
X2 23637 NXTLIN Address of next line of program. colour statements).
DATADD Address of terminator of last DATA item. 1 23694 MASK P Used for transparent colours, etc. Any bit
X2 23639
X2 23641 E LINE Address of command being typed in. that is 1 shows that the corresponding
2 23643 K CUR Address of cursor. attribute bit is taken not from ATTR P, but
X2 23645 CH ADD Address of the next character to be from what is already on the screen.
interpreted: the character after the argument N1 23695 ATTR T Temporary current colours, etc (as set up by
of PEEK, or the NEWLINE (ENTER) at colour items).
the end of a POKE statement. N1 23696 MASK T Like MASK P, but temporary.
2 23647 X PTR Address of the character after the Syntax 1 23697 P FLAG More flags.
error marker. N30 23698 MEMBOT Calculator's memory area; used to store
X2 23649 WORKSP Address of temporary work space. numbers that cannot conveniently be put on
X2 23651 STKBOT Address of bottom of calculator stack. the calculator stack.
STKEND Address of start of spare space. 2 23728 Not used.
X2 23653
N1 23655 BREG Calculator's b register. 2 23730 RAMTOP Address of last byte of BASIC system area.
N2 23656 MEM Address of area used for calculator's 2 23732 P -RAMT Address of last byte of physical RAM.
memory. (Usually MEMBOT, but not
always.)
1 23658 FLAGS2 More flags.
X1 23659 DF SZ The number of lines (including one blank
line) in the lower part of the screen.
2 23660 S TOP The number of the top program line in
automatic listings.
2 23662 OLDPPC Line number to which CONTINUE jumps.
1 23664 OSPCC Number within line of statement to which
CONTINUE jumps.
N1 23665 FLAGX Various flags.
N2 23666 STRLEN Length of string type destination in
assignment.
N2 23668 T ADDR Address of next item in syntax table (very
unlikely to be useful).
2 23670 SEED The seed for RND. This is the variable that
is set by RANDOMIZE.
3 23672 FRAMES 3 byte (least significant first), frame counter.
Incremented every 1/50th second (U.K.) or
1/60th second (U.S.).
2 23675 UDG Address of 1st user-defined graphic.
1 23677 COORDS x-coordinate of last point plotted.
1 23678 y-coordinate of last point plotted.
1 23679 P POSN 33-column number of printer position.
1 23680 PR CC Less significant byte of address of next
position for LPRINT to print at (in printer
buffer).
496
497
• APPENDIX VI
PROGRAM LIBRARY
This appendix contains applications and utility programs and routines, and games.
Some of these have been referred to in the main text. Due to lack of space, the
programs are not fully documented.
1. Polar
Program produces a polar coordinate graph of the function entered as A$. This must be
an expression using A as the dependent variable. Since a common cause of failure of
the VAL function (giving the error code A) on the ZX81 is the exponentiation function,
this is noted and a way of avoiding it given. The angle increment (in radians) is entered
as DA. The appropriate scale factor can be experimented with. If you get a small
cramped plot (or even a single pixel), increase the scale factor. If the plot goes off the
screen, you are informed that the scale factor needs reducing (line 250). Polar
coordinate plots can be thought of as an X,Y plot with the X axis bent into a circle, and
the Y axis plot point defined as a distance R (radius) away from the centre point. Y is
then positioned by the COS and SIN functions in lines 190 and 200.
Spectrum: For use on the Spectrum change " to T in line 30, and delete line 160.
Change line 70 to read 70 PAUSE 0. In lines 190 and 200 the centre point must be set
as plot co-ordinates 84, 82, with LET X = 84 + (R"COS A*SC) and LET
Y = 82 + (R'SIN A • SC). Line 210 must have the limits of X and Y set at 255 and 176
respectively. Line 270 should read PAUSE 0. The program will then run, but you can
also modify it to use the DEF FN and FN instructions: Define the function in line 50,
with a DEF FN aO = SIN A • 3 or whatever the derived function is, and use LET
R = FN aO in line 180. Change the instructions in line 40 to suit.
10 REM "POLAR"
20 PRINT TAB '8; "*POLAR PLOTS";
Tab 3;"************- _
30 PRINT "PLOT ROUTINE - i`
C.LAR"' "" COORDD INRTES, ENTER FLtNCTS
ON TO"."BE PLOTTED UITHOUT USE O
F **-,"(RAISED TO POWER? FUNCTIO
t•J.USE " "5IN*SIt•t+SIN,t'iOT SIt•i++3,F
OR" , "EXAMPLE. USE R FOR ANGLE,","
YOU MUST ALSO ENTER SCALE . , "FA's'
TOR AND ANGLE INCREMENT,"
40 PRINT "ENTER EXPRESSION 't
O 8E PLOTTED"
50 INPUT R$
50 PRINT "ENTER AS'tGLE It'SCREMEt't
70 INPUT DA
50 PRINT "ENTER SCALE FACTOR"
90 INPUT SC
100 CLS
109 REM *PRINT AXES AND PLOT
INFORMATION+
110 FOR F=1 TO 20
120 PRINT AT 11,F;"."
130 PRINT RT F,10;-,"
140 NEXT F
150 PRINT AT 0,12;R$;AT 1,1E;" -
. F. ="; SC; TRB 13; "RNHLE 13•FC, ="; DA
160 FAST
169 REM *ROUND THE CIRCLE,STEP
?NGLE+
170 FOR A=0 TO 2*PI STEP DR
179 REM *EVALUATE FUNCTION*
180 LET R =VAL AS
139 REM *NEXT LINES GET 'i,
CONVERTED TO POLAR (COS AND SIN•t?
COORDINATES.TIME'S SCALE FACTOR,
AND SET WITH CENTRE AT 20,20*
190 LET X=20+tR*COS R*SC?
200 LET Y=20+iR+SIN A+30?
210 IF X.>60 OR X:0 OR ',':.41-3 OR 'i..
O THEN! LOTO 250
220 PLOT X,Y
499
230 NEXT H
240 GOTO 290
250 PRINT RT I9,0,-OUT OF PLOT
• 82 PRINT AT 7,2;"A"; AT 7,10;"
TO ADD AN ENTRY"
RRNGE.REDUCE SCRLE","FRCTOR."
260 PRINT "PRESS R ).E, THEN ENT 83 PRINT AT 9,2;"S"; AT 9, 10; "
ER NEU S.F. FOR ACCOUNT STATEMENT"
270 PROSE 4E4 84 PRINT AT 11,2;"C"; AT 11,10
260 LOTO 90
290 REM *FINISH* "FOR CODE L-:REAKDOWN"
85 PRINT AT 13,2;"X"; AT 13,10
;"TO EXIT"
86 PRINT AT 15,8;"OPTION
87 INPUT Q$
88 IF Q$="A" THEN GOTO 310
SIN U',-43 89 IF Q$="S" THEN GOTO 610
3.F.=10
ANGLE INC.=.05 90 IF Q$="C" THEN GOTO 805
100 IF Q$="X" THEN STOP
120 PRINT AT 15,8;"UNKNOWN OPTI
ON: ";0$
130 PAUSE 100
140 PRINT AT 15,8;"
150 GOTO 85
500 501
410 GOSUB 1000
• ^
610 CLS
620 PRINT TAD' 5;"STATEMENT OF A
420 PRINT AT 16,5;"EXPENSE CODE CCOUNT"
630 PRINT TAB: 5;"
430 INPUT I$(I)
431 IF I$(I)="" THEN LOTO 430 640 PRINT
434 GOSUB 2000
650 PRINT "DATE"; TAB 8;"TYPE";
436 FOR J=1 TO 6 TAB 15;"CR"; TAB 25; "DB"
437 IF I$(I)=C$(J) THEN GOTO 44 660 PRINT "----"; TAB 8;"----";
2 TAB 15;"--"; TAB 25;"--"
438 NEXT J 670 FOR I=1 TO C
439 PRINT AT 7,5;"UNKNOWN EXPEN
680 F'RINT D$(I); TAB 8;I$(I);
SE CODE: ";I$(I) 690 IF A(I)>0 THEN GOTO 720
440 PAUSE 100 700 PRINT TAL-: 25; ABS A(I)
441 GOTO 410 71O GOT'i 730
442 PRINT AT 7,5;"EXPENSE CODE: 720 PRINT TAB 15;A(I)
";K$(J) 730 LET TOTAL=TOTAL+A(I)
444 PRINT AT 11,5;"CORRECT (Y/N 740 PRINT
)? 750 NEXT I
446 INPUT 0$ 753 PRINT TAB 20;"
447 PRINT AT 11,5;" 755 PRINT "BALANCE"; TAB 20;TOT
AL
448 IF Q$="N" THEN OUTO 410 766 PRINT AT 21,2;"COPY TO PRIN
449 IF 0$ <> "Y" THEN LOTO 444 TER (Y/N) ?
460 PRINT AT 13,5;" 767 INPUT 0$
768 IF Q$="N" THEN LOTO 72:
470 PRINT AT 9,5;"AMOUNT (- FOR 769 IF 0$ <> "Y" THEN GOTO 767
EXPENSE) ? 770 PRINT AT 21,2; "SET UP PRINT
480 INPUT A$ ER AND PRESS A KEY"
485 IF A$="" THEN GOTO 480 773 IF INKEY$ ="" THEN LOTO 773
487 PRINT AT 9,5;" 775 PRINT AT 21,2;"
490 PRINT AT 9,5;"AMOUNT: ";A$ 780 COPY
500 PRINT AT 13,5;"CORRECT (Y/N 790 GOTO 73
510 INPUT 0$ 800 REM **BREAKDOWN OF **
520 IF Q$="N" THEN LOTO 460
**ACCOUNT BY CODE **
530 IF 0$ <> "Y" THEN LOTO 510
805 CILS
532 PRINT AT 13,5;"
810 PRINT "STATEMENT OF ACCOUNT
BY CODE"
534 PRINT AT 9,5;"
820 PRINT
536 PRINT AT 7,5;"
830 PRINT "CODE"; TAB 15; "TOTAL
538 LET A(I)= VAL A$
540 LET I=I+1 840 PRINT
550 LET C=C+1 850 LET J=1
560 GOTO 350 855 LET TOTAL=O
860 FOR I=1 TO C
570 PRINT AT 10,3;"DO YOU WISH 870 IF I$(I)=C$(J) THEN LET TOT
TO SAVE THESE"; AT 11,2;"ENTRIES AL=TOTAL+A(I)
:38(0 NEXT I
(Y/N)
575 INPUT 0$ 890 PRINT K$(J); TAD 15;TOTAL
580 IF Q$="N" THEN GOTO 73 900 LET J=J+1
585 IF 0$ <> "Y" THEN GOTO 575 910 IF J <= 6 THEN LOTO 855
590 PRINT AT 10,2;"SSET LIP CASSE 926 PRINT AT 21,2; "COPY TO PRIN
TTE RECORDER, WHEN READY PRESS A TER (Y/N)
NY KEY" 927 INPUT 0$
595 IF INKEY$ ="" THEN GOTO 595 928 IF 0$="N" THEN GOT0 73
598 SAVE "HOME ACCOUNTS" 929 IF 0$ <: "Y" THEN LOTO 927
599 GOTO 72 930 PRINT AT 21,'2;
- "SET LIP PRINT
ER AND PRESS A KEY"
600 REM *STATEMENT OF ACCOUNT* 940 IF INKEY$ ="" THEN LOTO 940
503
5n2
950 PRINT AT 21,2;"
• •
The array creation program and data values (of resistors with ±10% tolerance) are
given below. This program is then edited out, and RESVAL entered. Alternatives to
960 COPY storing the data in an array would be to assign each value of the array X with a LET
990 GOTO 73 statement, or, if using a Spectrum, to place the values in a DATA statement. Both
1000 REM ********************* these methods would eliminate the problem of avoiding the use of RUN.
**EX PENSE CODE MENU**
**SUBROUTINE ** Spectrum: Change " to T in lines 220, 240 and 270.
********************* Change line 340 to read 340 SAVE "RESVAL" LINE 10
1020 PRINT AT 7,5;"*EXPENSE CODE Delete line 350
MENU* As noted, the program could be modified to use the DATA and READ
1030 PRINT AT 8,5;" statements. Insert a line 340 with the data as given below, and insert
215 READ X. Change X(N) to X in lines 220 and 240.
1050 PRINT AT 9,5;"G"; AT 9,15;"
GROCERY" 10 REM **RESISTOR VALUES INTO
1060 PRINT AT 10,5;"P"; AT 10,15 ARRAY**
"PETROL" 20 REM **LINES EDITED OUT RFTE
R ENTRY OF VALUES**
1070 PRINT AT 11,5;"C"; AT 11,15 30 REM **THEN RESVAL PROGRAM E
;"CAR REPAIRS" NTEPED * *
40 DIM X(13)
1080 PRINT AT 12,5;"R"; AT 12115 50 LPRINT "'ARRAY ::SLUE"
"RATES" 60 LPRINT
70 FOR L=1 TO 13
1090 PRINT AT 13,5;"M"; AT 13,15 80 LPRINT "X ("; L; ") ";
;"MISCELLANEOUS" 90 INPUT X(L)
1100 PRINT AT 14,5:"I"; AT 14,15 100 LPRINT TR6 7;X(L)
110 NEXT L
"INCOME"
1110 RETURN
ARRAY VALUE
2000 PRINT AT 16,5;"
X (1) 10
X (2) 12
2010 PRINT AT 14,5;" AT 14,15 X (3) 15
'! (4) 10
2020 PRINT AT 13,5;" "; AT 13,15 X (5) 22
X (6) 27
X (7) 33
2030 PRINT AT 12,5;" "; AT 12,15 X (6) 39
X (9) 47
X(10) 56
2040 PRINT AT 11,5;" "; AT 11,15 X (11) 56
X (12) 92
X (13) 100
2050 PRINT AT 10,5;" AT 10,15
10 REM *RESURL*
2060 PRINT AT 9,5;" "; AT 9,1`;"
20 PRINT "RESVAL"
30 PRINT
40 PRINT "PROGRAM DERIVES PREF
2070 PRINT AT 8,5;" ERRED VALUE";TR6 0; - OF RESISTOR
FROM INPUT"; TR6 0;-VOLTAGE RND C
URRENT VALUES"
2080 PRINT AT 7,5;" 50 PRINT
60 PRINT "PREFERRED VALUE'S ST)]
RED IN ' ;TR6 0; "RRR.RY.D0 NOT RUN
2090 RETURN PMOGRRf-t.USE";TAS 0;"GOTO 100."
79 PRINT "SAVE UITH GOTO 340."
60 PAUSE 600
3. Resval 90 CLS
100 PRINT "VOLTAGE 7-;
110 INPUT V
Program derives the preferred resistor value (i.e. the closest standard resistance) from 120 PRINT TAB 12;0;" VOLTS"
130 PRINT
inputs of the voltage and current required in a circuit. From these inputs (in volts and 140 PRINT "CURRENT
150 INPUT 2
amps) the actual resistance is calculatead by Ohms Law (R = V/I). This value, rounded 160 PRINT TR'S 12;I;" AMPS"
to two significant figures, is then used to calculate the value L, 10 to the power L being 170 LET R=INT (V*100îI)/100
160 PRINT
the multiplier for the resistor value. The values stored in the array X(13), entered as 190 PRINT "ACTUAL RESISTANCE ,
shown in the first program, are then compared with the calculated resistance. The first
p :- OHM..
200 LET L=INT (LN R/2.303)-1
value stored in the array which gives a value greater than R is then used to print out the 210 FOP N=1 TO 13
220 IF R:=X(N)*10**L THEN GOTO
preferred value for the component. The current and power using a resistor of this value 240
are then printed. The user may then choose to run the calculation again with different 230 NEXT N
241 LET X=X(N)*10**L
inputs until the best solution is achieved. This illustrates the basic principle of 250 PRINT "PREFERRED RESISTOR:
computer-aided design (CAD) of circuits, where the derived theoretical values are ...X:" OHM..
26(7 PRINT "GIVES CURRENT ; INT
modified to suit the actual components available. (U*I00!X) 1100; " AMR"
504 505
270 PRINT "AND ",INT (U**2*100/
X)•'100;" UATTS"
200 PRINT
• 340 G05U0 500
3. 50 CL5
290 PRINT "RGRIN? (Y/N) " 360 PRINT "MATRIX 1 * MATRIX 2
300 INPUT O$ GIVES:
310 IF O$="N" THEN STOP 3--0 FOR F=1 TO 5
320 CL5 380 FOR N=1 TO •5
330 GOTO 100 390 FOR L=1 TO 5
340 S AVE "RESU`" 400 LET C (F, N) =C (F , N) +A (F, L) *E
350 GOTO 10 _:N)
410 LET C(F,N)=INT rC(F,N)*1E5+
1E5
420 PRINT AT F*3,N*6-6;C(F,N)
4. Matmult 430 NEXT L
440 NEXT N
450 NEXT F
Program multiplies two square matrices. A two-dimensional matrix is stored as a two- 450 PRINT RT 21.0;"INPUT C(COP'Y
dimensional array, with the size input. Matrix multiplication requires the number of
),A(RUN) OR E(END)"
470 INPUT 2$
columns in one matrix to be equal to the number of rows in the other. The matrices are 480 IF Z$=-C- THEN COP'i
490 IF Z$= " R" THEN RUN
set up as square arrays of equal size in this program, and nonsquare mtrices may be
495 GOTO 700
multiplied by entering 0 for the elements of a row or column which is unused. Users 499 REM *ERROR SUBROUTINE*
familiar with matrix arithmetic will be able to derive from this program the routines to 500 PRINT AT 21,0;R$
510 PRINT AT 20,0 .; "ARE ALL ENTP
handle other matrix operations. The method involves nested FOR-NEXT loops, in CORECT "(Y OR N)"
T 20
- INPUT B$
conjunction with three arrays in this program, the third array holding the resultant 5:30 IF B$="Y' THEN RETURN
matrix. 540 PRINT PT 21., 0; ""HOU MANY INC
ERECT ENTRIES?"
Other points to be noted are the input and error routines. The input routine prompts 550 INPUT EN
for inputs by row and column number, and when all elements have been entered the 560 FOR F=1 TO EN
5 7 0 PRINT RT 20; 0; A$; RT 21 , 0; R $
error check subroutine is called, so that the user can check the whole matrix at once. ;AT 21,0;"ERROR ;F"; ROW .
This avoids the possibility of confusion over row/column numbers.
5 00 INPUT R
5 90 PRINT AT 21,7;"COLUMN
800 INPUT C
5 REM "MATMULT" 610 PRINT AT 21,0.; A$; AT 21,0-E
6 REM *BETTER IN FAST* NTER
NTER CORRECT NUMBER
FAST 520 INPUT N
10 PRINT "20 MATRIX MLtLTIPLICA 630 IF M=1 THEN LET A (R, C) =N
TION", "*************+*******4**" 640 IF M=2 THEN LET BtR,C'i=N
20 PRINT RT 3,0; "MULTIPLIEa '30 550 PRINT AT R*3,C*6-5;"
URRE MATRICES. " ,RT 5,0;"TO USE F _T P*3,C*6-6;N
OR NONSOURRE MATRICES " , "ENTER HA 660 NEXT F
TRIX SIZE TO RCCOMODATE" , "RND EN 6. 70 PRINT RT 21,0;R$
TER ZEROES.E.G TO MULTIPL'i"„" (1 680 GOTO 510
2 3) BY"' - (å.l ”' "' (51- " (6) "" 700 REM *END*
30 PRINT "USE A MAfRI',: -arZE
. ENT ERING", "1 COLUMN AND I ROH t1
NLY, REST 0.", , , "ENTER MATAICOS R ENTER HATRIX 1
OU BY ROU. " ENTER 0 FOR UNUSED ELEMENTS
40 LET R5=" 2 3
53 PROSE 200
50 PRINT AT 21 . $(; " i 3Et'TEP. „•PTfi
TX SIZE**" L 0 0
TO INPUT 3
50 REM *DIMENSION 1ST,2HC. AND
RESULT MRTRICES*
90 DIM A(5,5)
100 DIM 5(5,5)
110 DIM C(5,5)
120 CL5 MRTRIX 2
130 PRINT "ENTER MATRIX 1", , "EN
TER 0 FOR UNUSED ELEMENTS"
140 FOR F=1 TO 5 ^ a
150 FOR N=1 TO 5
160 PRINT AT 21,0; "ROU ",F," CO
LUt^.N ",N," ," Q, 0 5
170 INPUT R(F,N)
150 PRINT AT F*3,N*6-5,P(F,N)
190 NEXT N O 6
200 NEXT F
210 REM *M IDENTIFIES MATRIX FO
R SUBROUTINE*
220 LET M=1 F-tATRIX 1* MRTRIX 2 GIVES:-
230 GOSUB 500
240 CL5
250 PRINT "MATRIX 2" O 32
250 FOR F=1 TO 5
270 FOR N=1 TO 5
260 PRINT AT 21 , 0; "ROU ",F," CO _. 0 Q
LUMN ; N; " 7 "'
290 INPUT B(F,N)
300 PRINT AT F*3,N*6-5;B(F,N) O 0 0
310 NEXT N
320 NEXT F
330 LET M=2
INPUT C (COPY) , R (RUN) OR E(END)
506
507
5. Fruit
• 6. Lissajous
•
Program simulates a fruit machine. The program allows you to continue playing until
A program to produce the intricate, interesting and delightful patterns, named after the
your money runs out (which it will eventually) and you can then "borrow" more. mathematician who discovered the equation that produces them. You merely enter the
Points to be noted in the program are the overprinting of a string to simulate the
values of A, B and C in response to the prompts and watch the patterns develop.
spinning of the wheels (lines 200 to 230), and the logic used to check wins and amount Spectrum users can generate more complex patterns than ZX81 users, because of the
(if any) won, in lines 250 and 260. The program loops back from line 290 to line 140
higher resolution PLOT screen.
unless the money has all gone.
Spectrum: Change line 80 to read 80 FOR F = 0 TO 200 STEP 2. This defines the
Spectrum: Change line 60 to read 60 PAUSE 0.
number of points to be plotted. You can experiment with different values for STEP if
10 REM "FRUIT" you want more or fewer points plotted. Line 90 needs the two 30s changing to 120, and
20 PRINT
30 PRINT , . "YOU HRC%E £2 TO GRC-. line 100 the two 20s changing to 80. A and B can both be input with values up to about
BLE.","ERCH ROLL COSTS 10 PENCE. 10 on the Spectrum, so change the Input prompts to suit.
40 PRINT "PRYOUTS: 2 THE SAME
PAYS 10P" TÀB 8: "3 THE 5RME PRY 1 REM +LI_SA,JOUS-
3 40P";TR6 8; "EXCEPT ***,WHICH P 2 REM PLOTS LISSRJOUS PATTER)')
AY5 f.1'
SO PRINT ,,"PRESS R KEY TO STR 3 REM R 15 RELRTIUE FREOUE)'iC'
RT' Y,6 15 REL. FREO. X,C 15 Y PHA3
60 IF INKEY$="" THEN LOTO 60 OF PI.
70 CL5 E 10 PRINT "INPUT R (INTEGER 1 T
74 REM 5)"
75 REM **INITIALISE.PRINT* 20 INPUT R
76 REM 30 PRINT "INPUT B (INTEGER 1 T
80 LET C$="52 00" 0 si"
90 LET R$="- 40 INPUT B
100 PRINT " 50 PRINT "INPUT C (ANY NUMBER
110 PRINT AT 3,0;"YOU HAVE C$¢ '6 TO 3) "
120 PRINT AT E,12;" ;TRE- 60 INPUT C
12; "IIIf SUL ♦ ";TAB 12; 70 CL5
130 PRINT RT 19,0.; "PRESS 5 Tu E- 50 FOR F=0 TO 200
RIN" 90 LET Y =30+30*SIN (C +A+PI*F%1
140 IF INt<EY$<>"S" THEN LOTO 14 00)
O 100 LET X=20 +20*SIN (B*PI *F,•loi_
141 REM
142 REM **SET WIN LINE** 110 PLOT Y,>;
143 REM 120 NEXT F
145 LET 5$=""
150 FOR F =1 TO 3
160 LET R=INT (RND*6)+1
■a ■ ■■
170 LET 8$=6$+">i"+A$ (A:
160 NEXT F f ■ ■• ■
184 REM ti %de
185 RCM **SPIN WHEELS** ^åe å aa ■• • • a• % 1'
186 REM RR • • ■ • aa
190 LET F$="/* ENV a aa me a
200 FOR F=1 TO 10 a • • • ■
210 PRINT AT 9,12FZ(1 TO 6) a • ■ • ■ • ■
^ .
220 LET F$=F$(3 TO )+F;è1 TO 2 a • ■ ■ • • • ■
230 NEXT F
234 REM a • • • ■
235 REM **PRINT WIN LINE** a • a • •
236 REM • a • a
240 PRINT AT 9;12;6$ a ■ • a
245 REM **CHECK WINS *r.
250 LET W=(6$(2)=B$(4))+l8$(2)= a ^
6#(6)1+(65(4)=65(6)) aa a •
254 REM å a• • • ■ ■
255 REM **AMOUNT LION**
256 REM a• a•ti •
260 LET C=(.10 RNG W =1) +(.40 RN ^•^• a a a ■
G U=31+(1.0 AND U=3 AND 6$2)="*
270 LET C$=C5 (1) +5TR$ CURL 05 (2
TO 1 +C- .10)
274 REM
275 REM **CHECK IF SOL V ENT** 7. Line
276 REM
280 PRINT AT 3, 9; C$
290 IF UAL 05(2 TO ):=.10 THEN
?TO 140 This program gives the computer the capacity to draw a line between specified plot co-
294 REM ordinates. The Spectrum possesses a LINE instruction that does this automatically, but
295 REM ** MONEY SPENT**
2 96 REM Spectrum users may be interested in the method, which is the way the LINE instruction
300 PRINT RT 3,0; "*YOU ARE 6ROY. automatically calculates the points to plot. The program will run on the Spectrum if
E.* ";TRB 0) "BORROW 52 7C'Y OR N)
line 85 is deleted. As it stands, the program prompts for two sets of X, Y points, giving
310 INPUT M$
320 CL5 an error message if the points are out of range. Lines 110 and 120 calculate the X and Y
330 IF M$="Y" THEN LOTO 50 axis differences between the specified points. Line 130 defines the variable A as the
E 34-0 PRINT "BETTER LUC;. NEXT TIM greater of these. DX and DY are the increments added to the values of X(1) and Y(1)
aQU STOP
508 509
•
for plotting. In the loop (F = I to ABS A, since A may be negative) DX and DY are
^
70 GOSUB 500
80 LET GOES=0
decremented or incremented (as X and Y are positive or negative) by the distance to be 90 PRINT RT 15,0;"INPUT NUMBER
covered between points, divided by the number of steps needed. The program will TO REVERSE ?"
100 INPUT R
accept further inputs as required, but does not provide input prompts (lines 210 to 110 IF R<1 OR R>9 THEN GOTO 100
280). 120 GO5U6 300
130 REM **LOOP NEXT GO**
S REM "LINE" 140 GOTO 100
10 REM DRRW5 LINE BETWEEN POIN 150 REM *********************
T, (X(1),Y(1))RND POINT (X.(2)..'i (2 160 REM
)) 300 REM **REVERSE AND CHECK**
20 DIM X(2) 310 REM **SEQUENCE **
25 DIM Y(2) 315 REH
320 FOR F.1 TO INT (R!2)
30 FOR F=1 TO 2 'Z LET T =qtr)
40 PRINT "COORDINATES POINT 340 LET A (F) =R (R-F+1)
350 LET R (R-F+1) =T
50 PRINT „"X VALUE 360 NEXT F
60 INPUT X(F) 370 LET CORRECT.O
70 PRINT „"Y VRLUE 380 PRINT RT 5,5;
80 INPUT Y(F) 390 FOR F=1 TO 9
PRINT "®
85 IF X (F) > 53 OR Y(F)43 THEN
90 NEXT F
RUN PROGRRM RGRIN
400 PRINT R(F);'
410 IF A(F)=F THEN LET CORRECT
=CORRECT+1
100 CL5 420 NEXT F
110 LET X=X (2) -X (1) 430 LET GOES=GOES+1
120 LET Y=Y (2) -Y (1) 440 IF CORRECT=9 THEN GOTO 2000
130 LET R= (X AND AES X>=AB5 ''i 3 + 450 RETURN
('Y AND ABS X (ABS Y) 460 REM *************+********
140 LET DX=0 470 REM
150 LET DY=0 500 REM **SET SEQUENCE**
160 FOR F=1 TO R65 R 505 REM
170 PLOT DX+X (1) , DY+Y (1'( 510 LET R(1)=INT (RND*9) +1
180 LET DX=DX+X,R&5 R 520 FOR F=2 TO 9
190 LET DY=DY+'Y/ABS R 530 LET R (F) =INT (RND+9) +1
200 NEXT F 540 FOR N=F -1 TO 1 STEP -1
210 REH *FOR OTHER LINES* 550 IF R(F)=A(N) THEN LOTO 530
220 REM *********EE*****f. 560 NEXT N
230 INPUT X(1) 570 NEXT F
240 INPUT Y(1) 580 FOR F.1 TO 9
260 INPUT X(2) 590 PRINT R(F);"
270 INPUT Y(2) 600 NEXT F
280 GOTO 110 610 RETURN
620 REM ***************
630 REM
1000 REM **INSTRUCTIONS**
1010 REM
1020 PRINT"COMPUTER GENERATES
JUMBLED","SEQUENCE OF DIGITS 1
TO 9."
*.t
1030 PRINT "YOU MUST INPLIT A NUM
BER 1 TO 9,"
1040 PRINT "AND THIS NUMBER OF D
IGITS,","STARTING FROM THE LEFTM
'7ST,","WILL REVERSE.YOU MUST GET
THE"
1050 PAINT " DIGITS IN ORDER LEFT
TO RIGHT."
7.060 PRINT „"PRESS A KEY TO STR
1070 PRINT „"THERE WILL BE A DE
LAY WHILE","SEQUENCE IS CREATED.
1080 PAUSE 40000
1390 RETURN
1100 REM ********************
1'.10 REM
2000 REM **END ROUTINE**
2005 REM
2¢10 PRINT AT 20,0;"**SUCCESS IN
8. Reverse ";GOES;" GOES**","RNOTHER GO?(Y
CR N)-
2020 INPUT M$
The computer jumbles up a sequence of 9 numbers, and prints these (subroutine line 2030 IF M$<>"Y" THEN LOTO 2050
2040 LOTO 40
500) after giving the instructions, by calling subroutine 1000. After each input by the 2050 CL5
2060 PRINT "PLAY AGAIN SOMETIME.
player the subroutine at line 300 is called to print the altered sequence and check if the BY E ........
ordering is complete. If the sequence is correct, control is passed to line 2000 for the end 9999 S TOP
routine, which gives the option of playing again.
10 REM "REVERSE" 9. Tools
20 PRINT TAB 10;"*REVERSE*"
30 GOSUB 1000
40 CL5 The program shows the principle of a programmer's toolkit program containing useful
45 DIM R(9) program modules. You should add to this basic version any further subroutines or
50 PRINT TRB 10;"*REVERSE*"
60 PRINT RT 5,5; modules you want to have available. The inclusion of the BLOCKDEL program makes
510 511
•
editing out any modules not required for a specific program very easy. You may wish to
add, for example, a round/justify subroutine for numbers, or a sorting subroutine.
10. Blockdel
•
Note the mnemonic for the error subroutine line number. When you add modules, Program enables blocks of program lines to be deleted by a single line entry after the
however, use variable names that you are unlikely to use in the program you are line numbers of the first and last lines of the block (ST and END) to be deleted have
developing. Load the program before starting a program on the ZX81 . been entered (the program can also delete itself!). This is done by taking (line 9550) the
start address of the program storage area (RAM) then finding (line 9560) the line
Spectrum: For the Block delete module see BLOCKDEL. For Renumber module and number of the first line (LNUM). If this is the line number of the start line, the address
Memory left see Section U of the text. Remember you can use MERGE to enter this of the first byte of the line length storage bytes (= RAM + 2) is stored as LRAM (line
program at any point (hence the high line numbers). 9570). The line length bytes are then PEEKed (line 9580) to find the line length in bytes
(LLEN), before the line number is checked in line 9590 to see if it is the last line to be
deleted. If it is, control is passed to line 9620. If it is not, RAM is incremented by the
1 REM "TOOLS"
2 REH **ILLUSTRRTES TOOL'eIT** line length and four bytes for the program length and line number bytes, to get the
3 REM **LOAD BEFORE STRRT** address of the start of the next line stored in the memory, and the process is repeated.
**INPUTTING PROGRAM**
4 REM **GOSUB ERROR FOR ERROR When the end line number has been located and control passes to 9620, the line length
**MESSAGE ** variable LLEN is made equal to the number of bytes between the first and last lines for
5 REM **GOTO 9500 FOR BLOCK**
**DELETE ** deletion (this is why LLEN was found before checking if the current line was the last of
6 REM **GOTO 9700 FOR RENL(M*
7 REM **GOTO 9450 FOA t1t1GRY the block) by setting RAM to be RAM + LLEN, i.e. the address of the end byte of the
**LEFT last line to be deleted. This value, less the address of the line length byte of the first line
? REM **ADD YOUR OWN ROUTINES
*4*44******444::4:!*** (stored as LRAM), plus 2 for the program line number bytes of the last line gives the
LET ERROR=9400 number of bytes to be inserted by the POKEs of lines 9630 and 9640 as the new line
9400 REM **ERROR MESSAGE SUB**
9410 REM ******************** length of the first line requiring deletion. The computer now thinks that the lines for
9420 PRINT TRB 7;"***INPUT ERROR
***";TRB 7;"*****************" deletion are all one huge line, and keying in this line number and pressing NEWLINE
9430 PAUSE 120 (ENTER) will delete the whole block. The program should be loaded for use on a ZX81
9440 RETURN
9450 REM **MEMORY LEFT ** from tape before you start working on a program. Spectrum users can use MERGE.
9460 REM **+********4**4*****
9470 CLS
9480 PRINT "MEMORY LEFT=";PEEK 1 Spectrum: Line 9550 (giving the start of the program area) must be changed to read:
6386+256*PEEK 16387-PEEN: 1541-2
56*PEEK. 16413;" APPROX."
9490 STOP 9550 LET RAM = PEEK 23635 + 256`PEEK 23636
9500 REM **BLOCK DELETE**
9505 REM ***********+****
9310 PRINT "FIRST LINE TO DELETE 10 REM "BLOCKDEL"
9500 REM **BLOCK. DELETE**
9520 INPUT ST 5505 REM ***************4
9530 PRINT "LAST LINE TO RE DELE 9510 PRINT "FIRST LINE TO DELETE
TED?"
9540 INPUT END 9520 INPUT ST
9550 LET RRM=16509 9530 PRINT "LAST LINE TO 8E OELE
9560 LET LNUM=256*PEEK RAH+PEEN:
(RRM+1) 9540 INPUT END
9570 IF LNUM=ST THEN LET LRRM=RR 9550 LET RRM=16509
M+2 9560 LET LNUM=256*PEEN: RAH+PEEtti
9530 LET LLEN=PEEK (RAH+2!+2564F (RRt•1+1)
EEK (RRM+3) 9570 IF LNUM=ST THEN LET LRAM=RA-
9590 IF LNUM=END THEt'Y LOTO 9620 M+2
9500 LET RRM=RRM+4+LLE(•i 9530 LET LLEN=PEEK RRM+2! +c5c *r'
9610 GOTO 9560 EEK (RRM+3)
9630 LET LLEN=RRM+LLEt•i+2 - LRAM 9590 IF LNUM=END THEN GOTO 9620
9640 POKE LRAM+*,INT (LLENj2556! 9600 LET RRM=RAM+4+LLEN
9650 POKE LRAM,LLEN-256*PEEN: iLR 9510 GOTO 9560
AM+1) 9520 LET LLEN=RRM+LLEN+2 - LRAM
9660 PRINT "INPUT FIRST,I•t,'L TO D- 9630 POKE LRAM+1, INT (LLEt4.:256!
ELETE BLOCK" 9640 POKE LRAM,LLEN-256*PEEN, ILR
9670 STOP RM+1)
9700 REM **RENUMBER** 9550 PRINT "INPUT FIRST,N,'L TO î
9710 REM ************ ELETE BLOCK"
9720 LET RAM=16509 9660 STOP
9730 LET LINE=10
9 7 40 LET 5TEP=10
9750 POKE RRM,INT (LINE..2561
9760 POKE RRM+1,(LINE - 256*PEEN: R-
AM) 10 REM "BLOCKDEL"
9770 LET RRH =RRA +1
9780 IF PEEK RAM<>11B THEN LOTO 9500 REM **BLOCK DELETE**
9770 9505 REM *********?(* * st ***
9790 LET RAM=RAM+1 9510 PRINT "FIRST LINE TO DELETE
3500 IF 256*PEEK RRH+PEEK CRAt1+L
)=9000 THEN GOTO 9830
9810 LET LINE=LINE+STEP 9520 INPUT ST
9820 GOTO 9750 9530 PRINT "LAST LINE TO BE DELE
9830 PRINT "RENUMBERED.NOU DO GO
5UB,GOTO","LINES." TED'
9340 STOP 9540 INPUT END
9550 LET RAM=165,09
512 513
9560 LET LNUM=254* PEEK RAM+ FEE 450 IF NOT MARK THEN RETURN
460 PRINT AT GUE5S+3,0;
K (RAM+1 ) -WHAT T -;G$;"? TRY AGAIN."
9570 IF LNI!M = ST THEN LET LRAM=RA PAUSE
430 PRINT AT GUE55+3,0;" •
M+2
9500 LET LLEN = PEEK (R M+2)+256* 490 RETURN
4.95 REM *****************
PEEK (PAM+3) 496 REM
9590 IF LNUM = END THEN GOTT i 9620 500 REM **FIND n NUMBER*:*
505 REM
9600 LET RAM=RAM+4+LLEN 506 LET A$=C$
9410 GOTO 7540 510 LET AST=0
520 FOR F=1 TO 4
530 IF A$(F)<>G$(F) THEN G070
960 LET LLEN=RAM+LLEN+2-LRAM 570
9640 POKE LRAM+1, INT (LLEN/256) 540 LET AST=A5T+1
550 LET G$(F)="O"
9650 POKE LRAM,LLEN-254* PEEK (L 560 LET A$(F)="X"
RAM+1) 57 0 NEXT F
9660 PRINT "INPUT FIRST,N/L TO D
580 RETURN
590 REM ***********+*****
ELETE BLOCK" 595 REM
500 REM **FIND fi NUMBER**
9670 STOP 410 REM
620 LET DOLLRR=O
630 FOR F=1 TO 4
540 FOR N=1 TO 4
11. Coder 650 IF A$(F) <>G$ (N) THEN GOTO
690
660 LET DOLLAR=DOLLAR+1
670 LET A$(F)="X"
The computer chooses a four digit code sequence comprised of the digits 1 to 6. You 630 LET G$(N)="0"
590 NEXT N
input your guess for this code sequence. The computer prints your guess, checks for the 700 NEXT F
710 RETURN
number of digits in the correct place which correspond to the code, storing this as AST 7 20 REM ****************
(for asterisk), and then checks through the remaining digits for numbers which occur in 730 REM
1000 REH **INSTRUCTIONS**
the code sequence, but are not in the correct place (DOLLAR). These values are then 1010 REM
printed. This information helps you to refine your next guess. 15 goes are allowed, and 1020 PRINT TAB 12;,'*******";TAB
12; "*CODER*"; TAB 12;-*******-
if you haven't got the code in 15 tries, it is printed out for you. The program is 1030 PRINT "COMPUTER CHOOSES
structured with a sequence of calls to subroutines. Note that the code can include S EQUENCE OF".-4 NUMBERS. 1HI5 I`
MADE UP OF - , " ANY OF THE DIGITS
repeated digits, and analyse the checking procedures to see how this is dealt with. 1 TO 5" , " INCLUSIUE.DIGITS MA`/ 5E
REPERTEDSO THAT SEQUENCE COULD
BE 1663,"."FOR EXAMPLE."
1040 PRINT ."'YOU INPUT SEQUENCE
5 REM "CODER" TO TRY AND","MATCH THE CODE."
10 GOSUB 1000 1050 PRINT 'COMPUTER ((ILL PRI1'1.
20 REM **INITIALISE AND** T NUMBER OF ' D SIGNIFYING CORRECT
**CHOOSE CODE ** DIGIT IN "RIGHT POSITION, AND t.
30 LET GUE55=0 UMBER OF )•j; MEANING A DIGIT IN
40 LET C$="" UE55 WW HICH "
50 LET N$="123458" 1060 PRINT "OCCURS IN THE COMPUT
60 FOR F=1 TO 4 ERS CODE," : "BUT IS NOT IN THE RI
70 LET C$=C$+N*(INT (RND*E)+1, GHT PLACE.'
80 NEXT F 1070 PRINT .,"PRESS R KEY TO PLR
90 CLS
100 PRINT "INPUT YOUR GUESS 1080 IF INKE'Y $ "' THEN 6070 106e
TRB 0; "t J D fl' 1090 RETURN
110 INPUT G$ 1100 REM ****************
120 LET 1110 REM
130 GOSUB 400 2000 REH **END ROUTINE**
140 IF MARK=1 THEN GOTO 110 2010 REM
150 LET GUE55=GUE55+1 2020 IF R5T=4 THEN GOTO 2050
160 PRINT AT GUESS+2,1.;G$;iAS 2030 PRINT "15 TRIES AND NO SUC
ESS.CODE" • "WAS ";C$
170 GOSUB 500 2040 GOTO 2050
130 GOSUB 600 2050 PRINT '< SUCCESS IN ;GCESS;
190 PRINT A'ST;TAB 9.;DOLLAR " TRIES>"
200 REM **SEE IF 15 T RIES ** 2060 PRINT " ANOTHER GAMET (INPUT
**OR CODE CRACKED** OR N)"
210 IF PST=4 OR GUESS=15 THEN 2070 INPUT M$
GOTO 2000 2080 IF M$="Y" THEN GOTO .4.J
220 REM **LOOP TO NEXT GUESS** 2090 CLS
230 GOTO 110 3000 PRINT "OK.BYE."
240 REM ********************c-* 9980 REM
250 REM 9990 REH ******END******
260 REM 9999 STOP
400 REM **CHECK INPUT**
405 REH
410 FOR F=1 TO LEN G$
420 IF CODE G$(F)>34 OR CODE INPUT YOUR GUESS
G$(F)<29 THEN LET MARY.=1 KNAAR D 0
430 NEXT F
440 IF LEN G$<>4 THEN LET MARY. 1122 1 1
=1 2345 0 3
1345 0 3
514 515
5432 1
2342 1 1
6122 1 1
• •
cannot handle numbers input in the course of a program, or generated by a program,
in which case a routine of this type is required.
3162 2 1 BIDEC`2
1353 0 3
5132 1 2
1362 1 2 Spectrum: T not • in line 50.
4632 1 1
5332 1 2
4352 1 2 1 REM *BIDEC*
3342 2 0 2 REM CONVERTS BINARY NUMBERS
3512 4. 0 INTO DECIMAL
'SUCCESS IN 15 TRIES:. 100 PRINT "ENTER BINARY FORM"
ANOTHER GAME?(INPUT Y OR tJ) 110 INPUT A$
1 . Q PP'rNT
130 PRINT A$;" IN BINARY I5"
14.0 LET R=LEN A$
12. Plot 150 LET N=UAL A$(1)
160 FOR F=2 TO R
170 LET N=2*N+VRL R$(F)
A simple program to plot a graph of data points, with X and Y values input on the 130 NEXT F
190 PRINT
screen. Prompts for X and Y axis minimum and maximum values are made, and string 200 PRINT N;" IN DECIMAL"
inputs for the axis titles. These are then printed, and the data input is prompted. X and
Y values for each data point are entered, which is then plotted, and more data is 5 REM "6IDEC*2"
10 PRINT INPUT BINARY NUMBER"
requested. 20 INPUT 6$
30 LET N=0
4-0 LE T P=0
Spectrum: Change line 310 to read PLOT 12 + 244 (X - A)/(B - A), 50 FOR F=LEN B$ TO 1 STEP -1
12+156`(Y-C)/(D-C) 60 LET N=N+VAL 8$ ;Ft *23*P
70 LET P=P+1
66 NEXT F
PEN r *PL OT 90 PRINT 6$;"=DECIMAL ":N
10 PRINT TRB B;"
20 PRINT
30 PRINT "SET AXIS RANGES"
40 PRINT "INPUT X AXIS MIN.VRL 15. Hexdcc
IJ E
50 INPUT R
60 PRINT R Program converts hexadecimal numbers up to FFFF (65534 decimal) into decimal. As
70 PRINT INPUT X AXIS HRX.UAL with DEC HEX, the straightforward conversion of a character code to a decimal value
UE ,
B0 INPUT 6 which is possible on the ZX81 is more complex on the Spectrum. Line 130 in the ZX81
90 PRINT B
100 PRINT "INPUT Y AXIS MIN.LkRL version uses the value of the loop variable K directly to get the decimal value from the
IIIE
110 INPUT C
character code. On the Spectrum a counter loop is set up to hold and increment the
120 PRINT C value of K, and a new variable Z is used to hold the number by which K is to be
130 PRINT 'INPUT Y AXIS HR'.X.VRL reducecd to give the correct decimal value from the hexadecimal character.
UF
140 INPUT D
150 PRINT D
160 PRINT INPUT X AXIS TITLE Spectrum: Line 50 needs T , not •
170 INPUT X$ Insert 55 PRINT ' ` LETTERS MUST BE CAPITALS."
180 PRINT X$ Insert 115 LET K = 48: LET Z = 48
190 PRINT "INPUT Y AXIS TITLE Change 120 to read 120 FOR Y = 0 TO 15
200 INPUT Y$ Change 130 to read 130 IF A(F) = K THEN LET N = ((K - Z)`X) + N
210 PRINT Y$
220 CL5 Insert 135 LET K = K + 1
230 PRINT AT 21,5;X$ Insert 136 IF K = 58 THEN LET K = 65: LET Z = 55
240 FOR 1=1 TO LEN ''i $
516 517
170
180
PRINT
PRINT "RGRIN?(N OR Y)"
• •
100 PRINT RT 3,20;"YOU,^, GUESS,-
190 IF INKEY$="Y " THEN GOTO 30 - ,RT 5,20,-ACROSS?"
200 STOP 110 INPUT R
120 PRINT AT 5,26," ';A;AT20 ,
..D0(,iN?"
130 INPUT D
131 FOR X=1 TO 5
16. Dechex 132 PRINT AT 2+0*2,1+R*2; jj
133 PRINT RT 2+D*2,1+At2;" 1"
134 NEXT X
Program converts decimal (base 10) numbers up to 65534 to their four-figure 135 PRINT RT 2+D*2;1+R*2;"1"
hexadecimal/(base 16) equivalents. Hexadecimal numbers use the digits 0 to 9 plus the
140 PRINT AT 7,24; ";D;RT 9,20
letters A to F. This requires a means of deciding which character is to be printed, after 145 LET M=M+1
150 LET C=(R-1)*8+D
the decimal number has been broken down. On the ZX81 this is simple, since the 160 IF C=G THEN GOTO 300
(capital) letters A to F follow directly after the digits in the character code sequence. 165 PRINT "I RM
170 IF N=D THEN GOTO 210
This is not the case on the Spectrum, and the gap in the sequence must be bypassed. 190 IF N>D THEN PRINT "5";
CHR$ can then be used to change the decimal values (0 to 15), into which lines 120 to 200 IF N<D THEN PRINT "N";
210 IF E>R THEN PRINT "E",
170 break down the input number, to the appropriate character.
22 0 IF E<A THEN PRINT "ü";
230 PRINT " ";TRB Ç "OF YOU"
240 PAUSE 200
Spectrum: Change 190 to read 190 LET X = 48
250 FOR X=3 TO 10
260 PRINT AT X,20;"
Insert 205 IF X = 58 THEN LET X = 65 270 NEXT X
280 GOTO 100
290 STOP
1 REM DECHEX 300 PRINT "GOT ME"; TAB 52;"IN
10 DIN R(4) ; H; " MOVES"
20 DIM R$(4) 310 PRINT RT 20,2;"PRES3 R KEY
Se, PRINT -DECIMAL OR
r TO PLAY"
DECIMRL BRSENUHBER SE To HE'XA 320 IF INKEY$="" THEN GOTO 320
40 PRINT 330 PRINT RT 20,0;"
50 PRINT "NUMBERS x:65535 ONL'i"
60 PAUSE 350 340 CL5
70 CL5 350 GOTO 10
80 PRINT "INPUT DECIMAL VALUE"
90 INPUT N
100 PRINT
110 PRINT N; 18. Rescodc
120 LET A t 1) =INT lN/ 40967
130 LET E=N-A(1)*4096
140 LET A (21 =INT (6/25£.)
150 LET C=B-A(2)*256 Program calculates resistor values from inputs of the colour bands on the resistor.
FÜ LET A (3) =INT (0î15i Three bands are input, end band first, using the abbreviations given. The first two
170 LET R (4) =C-A (3) *16
130 FOR F=1 TO 4 bands define the basic value and the third the multiplier.
190 LET X=26
200 FOR =0 TO 15 10 REM RE5CODE
210 IF AtF)=Y THEN LET AbtF)=CH 20 PRINT "ENTER COLOUR ERN05,E
220 LET X=X+1 NOBAND FIRST"
230 NEXT Y 30 PRINT
240 NEXT F 40 PRINT "USE CODES RS BELOW:'.
2 50 PRINT " IS -;k$; - IN HEX 50 PRINT TRB 6; "RED RE"; TA:-
260 PRINT PT 12,0; "HIT NEULINE ;
TO RUN AGAIN" ;TR5 5;' ORRNGE OR", TR6B 6;"YELLOW
2 0 INPUT B$ YE";TA3 5: " GREEN GR";TAB 6,"BL
280 LOTO 70 UE BL";TRB 5; " VIOLET UI";TAB 6
.' GREY OY"; TA3 0; - (,'HITS UH"; T
1-16 6; GOLD GO";TAS 6-- SILVER 5
I"
17. Gridhunt
60 FOR A=1 TO 3
70 PRINT "COLOUR
80 INPUT C$
The computer hides itself on an 8 by 8 grid, which is displayed on the screen. You input
90 PRINT C$
100 IF C$="BK" THEN LET V=0
your guesses of the co-ordinates, the guessed square is marked, and if not correct the 110 IF C$=-BP" THEN LET 0=1
120 IF C4="RE' • THEN LET 0=2
computer gives a prompt for its direction from this square, using compass directions. 130 IF C$="OR" THEN LET 0=3
140 IF C$=-YE" THEN LET 0=4
150 IF C$="GR" THEN LET 0=5
1 REM *GPIDHUNT* " 160 IF C$=-8L- THEN LET V=5
10 PRINT 170 IF C$="VI" THEN LET U=7
30 FOR X=2 TO 10 STEP 2 180 IF C$="GY" THEN LET V=8
IF X • 2=9
34 PRINT THEN GOTO 40 190 IF C$="(JH" THEN LET V=9
RT 2,X+1;X:2,AT X+2,1 200 IF C$="GO" THEN LET V=10
.:X/2
210 IF C$="SI" THEN LET 0=100
40 PRINT RT 3,X;"+ - ;RT 19,X;"+ 220 IF R=1 THEN LET F=U
230 IF R=2 THEN LET F=F*10+V
45 PRINT RT X+1,2;"+',RT X+1,1 240 NEXT R
8;"+- 250 PRINT "RE?.ISTANCE .$RLUE I5
50 NEXT X 260 IF U>0 THEN GOTO 350
50 LET E=INT (RNDa8)+1
70 LET N=INT (RND*6)+1 270 PRINT F;
250 FOR R=1 TO U
80 LET G= tE- 1)*8+N 290 PRINT "0
90 LET M=0 300 NEXT R
518
r n
310 PRINT " OHMS"
• •
64-0 PRINT S$(J);TAB 15;M(I,J);T
320 STOP AB 20;0$
360 PRINT F/U; 650 NEXT J
370 PRINT " OHMS - 665 PRINT "'.
666 PRINT "AVERAGE= ";A(I)J5
667 PAUSE 500
668 COPY
659 CL5
19. Marker 670 NEXT I
700 PRINT "GRADE BRERKDOUN BY S
UBJECT"
Program produces a marksheet for the pupils in a class after exam results are entered in 710 PRINT
five subjects, set in this program as English, Maths, French, Computing and Biology. 7 20 PRINT "SUBJECT"; TRB 15; "DIS
The average mark for each pupil is calculated, and a grade breakdown of the results is T.";TRB 2 "'PASS"; TAB 27; "FAIL"
725 PRINTS""
printed, giving the total number of pupils in each grade. The grades are defined as: 730 FOR J=1 TO 5
740 PRINT 5$(J);TAB 15;,D(J);TAB
22;P ; F (J)
45% or less FAIL 750 LET T1=T1+D (J)
760 LET T2=T2+P(J)
45 to 75% PASS 770 LET T3=T3+F(J)
More than 75% DISTINCTION 800 NEXT J
810 PRINT ""
820 PRINT "TOTAL";TRB 15; Tl; TAB
As initialised, the program allows up to ten pupils in each class. A pupil name is
22; T2; TAB 27; T3
030 COPY
entered with the results in each of the subjects, and the average calculated. When all 850 STOP
1000 REM INPUT DATA
entries have been made, END is entered and the subjects, results and grades for each 104.0 FOR J=1 TO 5
pupil are printed. The grade breakdown is then given of the number of pupils in each 1050 PRINT "SUBJECT ";S$(J);" HA
RK:
grade for each subject. 1060 INPUT M ( I.J)
1070 PRINT M(I, J)
1 REM "MARKER- 1030
S LET T1=0 1100 RETURN
6 LET T2=0 2000 REM DISTINCTION
LET T3=0 2010 LET G$=-DISTINCTION-
2020 LET D(J)=D(0)+1
8 LET Z$="END 2030 RETURN
2200 REM FASS
10 DIM RS (1.0,20) 2210 LET G3=-PASS"
2 0 DIM A (10) 2220 LET P(J)=P(J)+1
25 DIM D (5) 2230 RETURN
26 DIM P (5) 24-00 REM FAIL
27 DIM F(5) 2410 LET G$=-FAIL"
30 DIM 5$(5,10) 2420 LET FiJ)=F(J)+1
4-0 DIM M (i0,5) 24'30 RETURN
50 PR INT "HARK SHEET"
50 PRINT "**********"
70 PRINT '•"
80 PRINT "'"
100 LET I=1 20. Indate
110 LET C=0
120 LET 5$ (1) ="ENGLISH"
130 LET 5å(2)="MATHS" Program is a date entry routine, with the input subroutine starting at line 10, and,
140, LET 33 (3) ="FRENCH"
150 LET 5$ DS) ="COMPUTING" nested within this, an error notice subroutine at line 250. On running the program,
160 LET 5$(5)="BIOLOGY" control passes to line 300, which has a short example of the manner of use of the
200 PRINT "ENTER NAME (ENTER EN
D TO FINISH)r ". subroutines. Subroutines are usually grouped at the end of a program, but they can
210 INPUT RS (I)
22 0 PRINT R$ (I) equally well be put at the beginning, as shown here. With long programs, using the
230 IF R$(I)=Z$ THEN GOTO 500 subroutines repeatedly, this can speed execution, since the computer counts from the
240 GO. SUB 1000
250 LET I=I+1 start of a program to find the line number corresponding to a GOSUB or GOTO
252 LET C=C+1 destination.
253 COPY
255 CLS
260 GOTO 200 1 REM "INDRTE"
500 REM CRLC AVERAGES 2 REM *DATE INPUT ROUTINES
501 COPY 3 REM *DATE ENTRY/CHECK SUBRO
505 CLS UTINES.ENTRY GOSUB 1O,ERR0R MESS
510 FOR I=1 TO C AGE GOSUB 250*
520 FOR J=1 TO 5 5 GOTO 300
530 LET A (I) =41 t I , J) +R (I) 8 REM *********************
54-0 NEXT J 9 REM **DATE ENTRY SUB**
550 NEXT I 10 PRINT "ENTER DATE"
600 FOR I=1 TO C 20 PRINT "DA''?"
610 PRINT "NAME : '; R$ (I) 30 INPUT D
615 PRINT "" 40 IF D>=1 AND D<=31 THEN LOTO
620 PRINT "SUBJECT"; TAB 15; "MAR 70
K";TAB 20; "GRADE" 50 GOSU6 250
625 PRINT " 60 GOTO 20
70 PRINT "MONTH?(1 TO 12)"
630 FOR J=1 TO 5 80 INPUT T"
635 IF M(I,J))75 THEN GOSUB 200 90 IF M>=1 AND M<=12 THEN LOTO
0 120
636 IF M(I,J)>45 AND M(I,J);=75 100 GOSUB 250
THEN GOSUB 2200 110 GOTO 70
637 IF MtI,J)<=45 THEN GOSUB 24 120 PRINT "YEARRS LAST 2 DIGI
00 TS)-
V)n
130 INPUT Y
140 IF Y,10 AND Y<99 THEN LOTO
•
170 REM GET EINRRY INTO ARRAY
180 F OR B=1 TO 6+
170 IF L-2*INT (L/2) =1 THEN GOT
150 GO5U6 250 0 220
160 OUTO 120 208 LET R(8*C+B)=0
170 REM *CHECK DRY US MONTH* 210 GOTO 230
160 REM *LEAP YEAR* 220 LET R(8*C+S)=1
190 IF INT ((Y+1905).-4)<>(Y+190 230 LET L=INT (L/2)
0)/4 AND M=2 AND D=29 THEN GOTO 240 NEXT B
220 250 NEXT C
2 00 REM *SHORT MONTHS* 260 00500 500
210 IF NOT ((M=2 AND D>29) OR 270 NEXT F
(M=4 OR M=6 OR M=9 OR M=11) AND 280 STOP
D=31)) THEN GOTO 2.20 500 REM PRINT SUBROUTINE
220 GOSU6 250 510 REM REVERSE LOOPS
230 GOTO 10 520 FOR X=6 TO 1 STEP -1
240 RETURN 530 LET R$=""
248 REM ********************** 540 FOR Y=7 T O 0 STEP -1
249 REM +*ERROR NOTICE SUB** 50 REM REVERSE IF CHR INUERTED
250 PRINT "***INPUT ERROR***"," BEFORE
PLEP.SE FOLLOW INSTRUCTIONS " , " RE- 560 IF CODE 05(F)>63 THEN LET P.
INPUT REQUESTED DATA." (Y*G+X) =NOT R (Y *5+X
260 PAUSE 180 570 REM PUT ONE ROt-O OF CHR INTO
270 CL a$
200 RETURN 560 IF RtY*8+X)=1 THEN LET R$=R
300 REM ***PROGRAM HERE TO USE 5+"'-"
INPUT ROUTINES*** $ 590
+.. IF R (Y*8+X) =0 THEN LET R$=A
310 REH *EXAMPLE*
320 PRINT "YOUR BIRTHDAY" 600 NEXT Y
330 GOSUB 10 610 LPRINT AS
340 LET BD=D 620 LPRINT AS
350 LET BM=M 630 NEXT X
360 LET BY=Y 640 RETURN
370 CLS
380 PRINT "BIRTHRATE: ";BD;"/";5
M;-/19-;BY
22. Input
21. Headliner Program checks a number input as a string. This is a useful way to input numbers, as
an error will not cause a program halt, as will happen, for instance, if a numeric input
Program prints banner headlines on the printer, using the character arrays stored in contains more than one decimal point. The program is listed as an input check for
ROM. As listed, the program allows the inverse characters of the ZX81 to be used, decimal currency, but is easily modified to suit any numeric input of a known form.
accessing the normal character (line 130) to get the pattern of bits, but reversing this The string input is checked by the subroutine at line 200, each character in turn
(i.e. swapping black for white) for printing (line 560). This procedure is not possible on being checked by means of its code to ensure it is either a digit or a decimal point. To
the Spectrum, since the inverse forms are not included in the character set. The basis of
check for multiple d.p.'s the counter S is incremented each time one is encountered. M
the program is the reading of the character arrays (as with the BIG PRINT program in is set equal to the number of digits before the d.p. A check is then made for S being
Unit U3 of the main text), but with the additional complication of reading the first bit greater than 1 (non-numeric character or'more than one decimal place), 0 (no d.p.),
of each byte, then the second bit of each byte, and so on, in order to print a character and for more than two digits after the d.p. Any error sends control to the error
with a sequence of printer lines. subroutine at line 400. This requests a re-input the number. The error check
subroutine is then called recursively to check this input. A correct input will pass
Spectrum: Delete lines 40, 120. 130, 550, 560 control back to the main program, where the user is given the opportunity to check that
Change line 160 to read: 160 LET L = PEEK (15360 + the input value is correct.
C + 8 * CODE L$)
1 REM -INPUT-
REN *HEADLINER* 5 REH STRING INPUT CHECKED A5
C10 PRINT TAB
...=21=1=.. 6:-Mim-;TAB NUMBER
9 REM *MARKERS*
20 PRINT„;"PROGRAM TO PRODUC 10 LFT S=0
E LARGE PRINT”,"AS HEADLINES ALO 15 LF_T M=8
NO PRINTER PAPER" 19 REM *EMPTY LINE*
30 PRINT ,,,"INPUT ANY LENGTH 20 LET E$="
3TR ING." 30 PRINT "ENTER A MOUNT.ENTER P
40 PRINT "YOU MAY USE ALL L OUNDS , " , "F ULLSTOP,PENCE.-
ETTERS,NUMBERS" "AND GRAPHICS." 40 INPUT N$ 99,99"
50 REM DIM ARRAY TO STORE LETT 50 GOSUB 200
FR
60 DIM A(64) 59 REM *OFFER L'RLUE CHECK*
70 INPUT US 60 PRINT AT 20,0; "ENTRY VAL/D.
80 FAST ENTRY WAS £";N$,"INPUT C TO CONF
90 FOR F=1 TO LEN US IPM : E TO RE-ENTER"
100 REM TAKE LETTER 70 INPUT 9$
110 LET L$=U$(F) 80 IF R$=-C" THEN GOTO 170
120 REM IF CHR INVERSE THEN 90 IF R$="E" THEN GOTO 120
SWAP FOR NORMAL FORM 100 PRINT AT 20,0; "FOLLÇJU INSTR
1730 IF CODE L$>63 THEN LET L$=C UCT IONS. "
MRS (CODE US(F)-126) 110 GOTO 70
140 REM GET ROM CODES 120 PRINT AT 20,5; ES; AT 21,5; E$
150 FOR. C=0 TO 7 130 PRINT RT 20,0; "ENTER CORREC
160 LET L=PEEK. (7680+C+8*CODE L T 1 ! RLUE . "
$) 140 INPUT N$
150 PRINT AT 20,0; 0$: E$
522 523
160 GO5UB 200
170 CL'
250
260
•PRINT S
PAUSE 250
lee PRINT "END OF PROGRAM- 270 CLS
190 LOTO 999
199 REM *ERROR CHECK* 280 PRINT "PRESS NEWLINE FOR"
200 LET L=LEN N$ 290 PRINT "ANOTHER GAME"
210 FOR F=1 TO L
219 REM *CHECK NON-NUMERIC CHR5 300 INPUT A$
* 310 IF A$="" THEN OOTO 80
220 IF CODE N$(F)'.27 DR CODE N$
(F)>37 THEN LET 5=2
229 REM *CHECK FULLSTOP*
230 IF N$(F)="." THEN LET 5=5t-1
240 IF N$(F)_"." THEN LET N=F
250 NEXT F
260 IF L-M(2 OR 5>1 OR 5=0 THE
N GOSUE 400
270 RETURN
393 REM *ERROR FOUND*
400 PRINT RT 21,0. " *INP)JT INURL
ID*RE-ENTER URLUE"
410 INPUT N$
411 LET 5=0
412 LET M=0
420 GO5U6 200
430 RETURN
999 REM *END*
23. Asteroids
The program puts you at the helm of a Mars shuttle disguised as an asterisk. Avoiding
the Nova Heat you have to weave through the strangely square low albedo asteroids
that look surprisingly like inverse squares. Your controls are fairly minimal - not much
money on the Mars run smuggling algae these days, so you have a button marked 1 to
go left and one marked 0 to go right.
The program cannot be simply modified for the Spectrum so this listing applies to the
ZX81 only.
5 REM "ASTEROIDS"
10 PRINT "**ASTEROID=:**"
20 PRINT
3O PRINT "AVOID BLACK ASTEROID
525
524
•
Peter Morse is Professor and Head of Computer Science at the •
Polytechnic of Central London. He has wide ranging teaching,
research and consultant activities in the fields of digital
systems, software engineering and computer education.