with a Special Section on the Timex/Sinclair 2000 THE ESSENTIAL GUIDE TÜ TIMEX/SINCLAIR HOME COMPUTERS ! The Only Book You'll Ever Need to Become an | Expert at the Timex/Sinclair 1000 and 2000 li ЖДД ЕТП : f "d cundo 3H YIVIINIS/KIWIL ñ. E 1 ' Е E МУГ ы ЕК ie L E S M 4 % 5 | а \ ( ' “ [| | li ( ү ж | я , TY 7 ` ` | E 4 є d] j = у | et Ties | А | E ч т, d x I ^ ; s a | - EN А Gs > i E»: "A "v 4 y "4p". THE ESSENTIAL GUIDE TO TIMEX/SINCLAIR HOME COMPUTERS The Only Book You'll Ever Need to Become an Expert at the Timex/Sinclair 1000 and 2000 by PETER MORSE, IAN ADAMSON BEN ANREP and BRIAN HANCOCK A TOUCHSTONE BOOK Published by Simon & Schuster, Inc. NEW YORK We are grateful to Sinclair Research for their cooperation This book was published in England under the title The Century Computer Programming Course Copyright © 1983 by Eosoft All rights reserved including the right of reproduction in whole or in part in any form A Touchstone Book Published by Simon & Schuster, Inc. Simon & Schuster Building Rockefeller Center 1230 Avenue of the Americas New York, New York 10020 Published by arrangement with Century Publishing Company, England TOUCHSTONE and colophon are registered trademarks of Simon & Schuster, Inc. Manufactured in the United States of America 10 98 765 43 2 1 Pbk. Library of Congress Cataloging in Publication Data Main entry under title: The Essential guide to Timex/Sinclair home computers. (A Touchstone book) British ed. published as: The century computer programming course. 1. Timex 1000 (Computer)—Programming. 2. Timex Sinclair 2000 (Computer)—Programming. 3. Basic (Computer program language) I. Morse, Peter (Peter L. R.) II. Title. QA76.8.T48E77 1983 001.64'2 83-9090 ISBN 0-671-47069-8 Pbk. IMPORTANT NOTE FOR ALL READERS This book uses the Sinclair version of single keystroke BASIC as featured on the ZX81 and Spectrum microcomputers. In the States the ZX81 has been marketed as the Timex/Sinclair 1000 and the Spectrum is known as the Timex/Sinclair 2000. American readers should note that throughout the text we refer to these machines by their UK names. There are a few minor differences between the UK version of the ZX81 and the US TS 1000. The first is that the TS 1000 has more ‘on board’ memory (2k) than its UK equivalent. However, this is still insufficient for the scope of this text, and the majority of the programs occurring in the book will require a 16k RAM pack. The second difference is that two keys, which do exactly the same thing, are labelled differently. Thus, NEWLINE and ENTER are equivalent on the ZX81 and the TS 1000, as are RUBOUT and DELETE. On each occasion that these commands occur in the text, readers will find either NEWLINE (ENTER) or RUBOUT (DELETE). For the sake of clarity we have used the ZX81/TS 1000 version of BASIC as the foundation of the book, and have noted those instances where Spectrum (TS 2000) BASIC differs from that used by the ZX81 (TS 1000). Functions and commands exclusive to the Spectrum (TS 2000) BASIC superset are fully explained at the end of the book (Units W2 and W3). In short, the book has been designed to enable its readers to learn how to program using any of the Sinclair machines. Users of the Spectrum should note that all programs are listed in capital letters throughout. To get program results and listings that look identical to those given here the capital letter (CAPS) mode must be used on the Spectrum for all letters input or printed. The first two Units of Part One deal only with the ZX81. The Spectrum user should read instead Unit W1 (page 439) of the Spectrum dedicated Section which forms Part Five of this text. TE РЧ КЛ АЙ oie SOT TOM ГИЛ ГАГИ í; FAD iin “ger former үніне” wh еи фе” ИЯ? = ez deus qo +. теі Craft
eet 7 bonua «canted
‘Hee Kets?
volut. йй ay aint arrests ПОЛО grieved bets) tao tari ed gn
deabus nord бы? чый oe sura age Tiber: iron «М. заз (eo m £
-GA < ihe и ж ула % «©.» {кулан Ya кзжсжттер bgr
там, ъз + Min Pí Г ұлығ | nus зыр“ iai паз 1 D нұйуі,
АТИ
PART ONE
FIRST STEPS
Important Note: The first two units of this part are
specific to the ZX81. Spectrum users should ignore these
pages and directly GOTO the first Spectrum specific
section (W1 on page 439) before returning to the main
text (Section C on page 19).
Зин ERAS
LI
рч
SECTION A: ZX81 MICROCOMPUTER SYSTEM
A1: ZX81 Description
We assume you have in front of you the components of your ZX81
computer system.
It consists of:
1 Тһе ZX81 microcomputer with its touch-sensitive keyboard.
2 The Sinclair 16k RAM pack (Random Access Memory) or a
RAM pack of at least 16k produced by one of the other
manufacturers for the ZX81.
3 The ZX power supply, with a lead and plug, for connection to
the a.c. power supply, and the lead, ending in a jack-plug, to
connect the power supply unit to the ZX81.
4 The ZX printer and its connector socket.
A domestic UHF ТУ set to be used as a TV monitor.
6 А mono cassette recorder, with power supply lead if not battery
powered.
The aerial cable which connects the ZX81 to the TV monitor.
8 A pair of cassette recorder leads fitted with 3.5mm jack-plugs оп
each end.
сл
I
These components make up a complete system. As far as this text is
concerned, the least crucial component is the printer. Without it you
can simply ignore the printer-related portions, and will be able to work
through the book and learn the BASIC programming techniques just
as well. However, it is extremely useful to have a printer both for hard-
copy printouts of results, and more importantly for program listings for
documentation purposes.
There are a large number of ‘add-ons’ and accessories available for
the ZX81. None of these are of any interest as far as this book is
concerned, and most should be considered only when you have
absorbed the text and are going to write programs for specific purposes,
which might require the facilities provided by some of these units. A
noteworthy exception is a workstation to hold the components of the
system securely. There are types available which have on/off switches
for the d.c. power supply from the power supply unit, which saves a lot
of plug pulling and re-insertion, since pulling the power plug out of the
ZX81 is the only way to re-set the computer if it ‘crashes’ (i.e. will not
respond to keyboard commands).
What ¿s vital is enough memory. RAM memory is measured by
kilobytes (‘k’). The basic ZX81 has only 1k of RAM built in (2k on the
Timex/Sinclair 1000), and, without an add-on, RAM memory has
very little space available for programs. Computers are essentially
devices which store and manipulate data, and since programs, data,
and the manipulations all take up memory space, an add-on RAM
1
Figure 1
ZX81 SYSTEM DIAGRAM
ас. household power supply
AERIAL
TV MONITOR SOCKET
POWER
EAR а CASSETTE SUPPLY
МІС | RECORDER
NOTE: U.S. USERS MAY HAVE ANTENNAE ON/OFF SWITCH FITTED IN AERIAL
LEAD, SHOWN AS DOTTED BOX IN DIAGRAM.
memory is needed. RAM memory of up to 48k is available for the
ZX81, but 16k is more than enough for our purposes. Independently
produced RAM packs are usually just as good as those produced by
Sinclair.
The cassette recorder should be mono, since stereo tape deck
recording heads can cause problems, even used on one channel only.
The cheaper recorders work somewhat better (due to the less
sophisticated audio circuits being better for handling the crude form of
the computer’s signals) than more expensive ones, but try to get one
with a tape counter, as finding programs without one can be
irritatingly time consuming. You should always use the same recorder,
as problems can be encountered when playing back tapes recorded on a
different machine. Battery-operated recorders actually avoid some
potential problems, but must always have good batteries, to keep tape
2
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
have to put in new ones) is to buy nickel-cadmium batteries and a
charging unit. All recorders have automatic level controls for
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 1s 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
family!).
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 flat surface to sit on the ZX81 case, and should be
placed on the case, above the keyboard, on the left-hand side of the
case.
lhe corollary to this problem is that you should SAVE a long
program being developed or keyed in at intervals, and/or take listings
from the printer, to avoid a total loss if you do get a white out. The
same problem can also be caused by two other factors, and this
procedure will protect against the worst results from these problems as
well. The first is that household power supplies are sometimes
interrupted, or occasionally have brief large voltage fluctuations.
Computers are sensitive to such things, and a crash may be caused.
Other than buying a stabiliser which will continue to supply power
during such an interruption (of very short duration, but computers
work fast!) we cannot protect against a.c. supply fluctuations, but
similar results can sometimes be caused by appliances connected to the
same local power circuit switching on and off, and this should be
investigated if the problem is frequent.
The other main source of problems is the connector to the RAM
pack and printer via the edge connectors at the back of the ZX81.
Movement can be caused in this connector by flexing the system whilst
keying in programs. This can be minimised by always pushing the
connectors home firmly before switching on, but a better solution is to
attach the components to a board, fixing them down to a suitably rigid
base with ‘Blu-Tack’ or the double sided adhesive pads that are now
available. Fix the printer down as well- the process of tearing off
printout can move printer and connector if you are not careful. Note
that the method of fixing cannot be permanent, which is why Blu- Tack
3
or a similar plastic fixative is recommended.
The edge connectors themselves are gold plated, but they connect to
the printed circuit board edges which may become oxidised, causing
circuit problems (not necessarily white-outs or crashes — the keyboard
may cease to work, or the printer miss lines, for example). Proprietary
(non-abrasive) contact cleaners should be used to ensure clean
contacts.
Other than the problems above, the only maintenance that should be
needed is the brushing away of the dust that accumulates in the printer
from the burnt-off particles of paper. After removing the paper holder,
use a soft small brush (e.g. a small paint brush) to clear away the dust.
Pay particular attention to the slot in which the electrode runs, but if,
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
BREAK has been used it can be left in the middle of the printer slot.)
A2: Function of Components
This is a programming text, not a manual on computer architecture or
computer science. However, we thought it might be useful to provide
you with a brief rundown of the functions of each of the components of
your microcomputer system.
Device Function
ZX81 computer board Data processing and control of
(inside case) information handling. Input
from keyboard or cassette.
Output to TV screen and
printer.
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 information — visual
display of programs, results
(data, graphs, pictures) and
control commands.
Cassette recorder Off-line storage of information.
Program data are stored (written)
as coded electromagnetic
impulses on cassette tapes. They
can be played back (loaded) at
any time for use again. The
computer reads the data from
the tape.
ZX printer Output device, to provide a
permanent printed record of the
screen display, program listings
or information in the computer
memory. Prints on
electrosensitive paper.
16k RAM pack Add-on memory enabling large
Power
Cables
programs to be stored and run.
K stands for kilobyte. One byte is
eight 22/5, which аге the binary
digits (0 and 1, represented by
on-off switches in the computer)
computers work with. A kilobyte
is roughly 1000 bytes, hence the
name. (It is actually 29, 1024).
supply Supplies the d.c. current (9 volts
at 1.2 amps) to run the
computer, RAM pack and
printer, from the household
power supply.
To interconnect the devices
which make up the system. The
printer uses the same socket as
the memory pack and has an
extension socket to allow this.
The printed circuit board inside the ZX81 holds and connects the IC
(integrated circuit) microchips which provide the computing facilities.
These
1
are:
Z80A CPU (Central Processing Unit) microprocessor chip
which is the heart of the system. It is used in many other
microcomputers, and performs the arithmetic manipulations.
ROM (Read Only Memory) chip holds the 8k BASIC
interpreter which translates BASIC instructions into the
machine code instructions that the Z80A operates with. The
data in this chip is fixed, hence the name, and also stable — it
remains when the power is switched off.
3 RAM (Random Access Memory) chip provides a 1k* memory
store. When the memory pack is fitted it blocks off this memory
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
programs, the values of variables (including some system variables
that the computer uses to organise its own affairs), a memory
picture of the ТУ screen display, and the stacks which hold the
numbers whilst they are being manipulated. This is covered in
more detail in Section U.
4 The Logic chip co-ordinates the operation of the other chips.
Also mounted on the board are: the stabiliser for the 5 volt supply the
computer takes from the power supply, the TV signal modulator and
the sockets for the connecting cables to the ГУ and cassette recorder.
*2k on the TS 1006.
SECTION B: GETTING TO KNOW THE ZX81
B1: Connecting Up
1
Lay out the ZX81 system devices on your work area as оп page
2. It is far better to have an area where the system can be set up
permanently. Failing this, a board can be used to mount the
components.
Place the a.c. power supply plugs of the power supply, ТУ and
tape recorder next to the sockets. A plug board with multiple
sockets mounted on it is better than an extension socket fitting.
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.
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 flat on the table to avoid too much stress on
the connectors, which might occur if you are holding up the
LAB,
With both connectors inserted, push the RAM pack firmly in to
ensure the connectors are fully seated home.
Connect the power supply cable into the socket marked DC on
the left-hand side of the ZX81.
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.
Connect the aerial lead into the ТУ 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.
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
7
Timex/Sinclair 1000 version of the ZX81. This switch must of course
be ON.
Straighten the interconnecting cables on your work area at this
point. Make sure that the cassette leads are not in contact with
any a.c. power leads.
SWITCHING ON
оомо C
10
11
12
13
Ensure that the TV receiver is off and that no cassette recorder
keys are depressed.
Plug the power supply, TV, and cassette recorder plugs into the
a.c. power supply.
Switch on the a.c. power sockets (if they have switches).
There are no ON/OFF switches on the ZX81 or on most cassette
recorders - they are now powered up.
Switch on the TV.
Turn the volume control on the ТУ to zero.
Turn the brightness control to MAXIMUM.
Turn the contrast control to MINIMUM.
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 ГУ is
at the right setting, a small black square with a white K inset
appears. This is the K-cursor, and appears on the bottom left-
hand side of the screen.
U.S. Users should note that the Timex/Sinclair 1000 version of the
ZX81 has a channel select switch for Channel 1 or Channel 2 fitted
underneath the case. Choose whichever channel is not transmitting in
your area, and select this channel on the TV and the computer.
Adjust the tuning, brightness and contrast until the cursor is
distinct, and the white K clear.
Check that the cassette recorder keys function. Insert a blank
cassette, and try all the controls.
Insert a roll of silver printing paper into the printer and press the
button on the right-hand side of the printer to feed some paper
through. Check the paper does not rub on either side of the
printer as it comes through.
Press the key and then the [NEWLINE (ENTER) | key.
The printer will start to copy what is on the screen. About 3
inches of paper will be fed through. There will be nothing
printed on it as there is nothing on the screen. A message 0/0
will appear at the bottom of the screen.
N.B. The bottom two lines of the screen are never printed
and are used for keying in program lines and commands. These
program lines, when correct, are transferred into an area of
8
memory reserved for the programs by pressing the NEWLINE
(ENTER) key. The program lines will then appear on the
printer when the COPY command is given.
14 Press characters at random on the keyboard. They will appear at
the bottom of the screen. Press and [EDIT | keys
together to clear the screen.
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
TV.
N.B. Never adjust or pull out the RAM pack when the power
supply is ON, you may damage it.
16 Other components failing to work will probably be caused by
plugs not switched on, or fuses blown. Alternatively, it could be
that some connections are not being properly made. You should
remove and re-insert Jack-plugs and connectors.
17 On leaving your computer:
a Leave it connected up
b Switch OFF a.c. power supply plugs and TV
c Disconnect plugs from sockets.
B2: The Keyboard
The ZX81 keyboard has 40 touch sensitive keys arranged in 4
rows of 10 keys.
At first sight it looks like a typewriter keyboard, but a closer look
reveals that some keys have five functions or characters written on
them. In fact:
Six different characters can be obtained from some keys!
The keyboard contains:
(1) The digits 0 to 9
(2) The letters of the alphabet printed in upper case
(3) The complete BASIC language
— instructions
— commands
— arithmetic, conditional and logical operators
— arithmetic functions
(4) Grammatical signs and symbols
(5) Special control keys
(6) Graphics symbols
These are all called characters.
Notice that words like PRINT, RUN, SLOW, LET, INKEY$ are
9
written on the keys and are printed on the screen when we press that key
in the correct mode.
The facility of complete words in the BASIC language being printed
at the press of a single key is called
SINGLE KEYSTROKE BASIC
On most other computers you have to key in each letter of, for
example, the instruction PRINT. This is inefficient. The ZX81 is very
powerful in this respect.
The keyboard contains most of the characters in the ZX81 character
set and a few special keys. Some 202 different characters are available.
Some print on the screen, others are non-printing, e.g. RUBOUT
(DELETE).
Each of the different types of character 1s described in Section B4.
The ZX81 keyboard layout is reproduced in the diagram on the next
page.
B3: Cursors
is] [>]
Cursors indicate what operational mode the computer is in and what
symbol or name should be typed in next. They appear in inverse video
(a white letter in a black square).
Keyword mode.
ZX81 expects a command
a line number
or a keyword
Keywords are the symbols printed on the keyboard
above the keys (see keyboard). SHIFTed keys also
function in this mode.
Letter mode.
Occurs at most other times.
ZX81 expectsa letter
a number
an operator
ora special command
SHIFTed keys function in this mode.
Function mode.
Obtained by pressing FUNCTION key (SHIFT,
NEWLINE/ENTER).
The functions obtainable are printed under each key
in white.
10
Figure 2
ZX81 KEYBOARD
ГЫ 86791 s e Se a e
M
CODE PEEK
IT
ap ж
JE es DS Mei ш ч"
AG БЕЙ K [ENTER]
ARCSIN = Ж: DS
COPY CLEAR fis
Only one function can be obtained each time
FUNCTION is pressed.
Graphics mode.
Obtained by pressing GRAPHICS key (SHIFT, 9).
Mode lasts until the GRAPHICS key is pressed again.
In the graphics mode 36 different characters are
obtained by pressing the keys with the SHIFT key
depressed as well. These are shifted graphics characters.
38 different characters (mainly letters printed in the
inverse mode) are obtained by pressing the keys.
[s | Syntax error cursor.
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
program into memory (i.e. after we press NEWLINE
(ENTER) when at the bottom of the screen).
The [S | cursor appears next to the last error in the
line. (There can be more than one). Editing on the line
сап take place immediately. The [5 | cursor disappears
when an edit operation is performed. It will re-appear
(if necessary) when NEWLINE (ENTER) is pressed
again.
Current line cursor.
When entering statements into the program the last line
to be entered is called the current line and is indicated
by this symbol placed after the line number. The
movement of this cursor up and down the screen,
pointing to different lines, is controlled by the { and
^ keys (SHIFT 6 and 7).
If EDIT (SHIFT 1) is pressed, the current line is
brought down to the bottom of the screen and can be
edited.
B4: The Different Character Types
THE 6 CHARACTER TYPES ON A KEY
If we examine a particular key, say [R ] , we can classify the 6 character
types, as seen in the diagram below.
RUN
LETTER
<=
ec
=
INVERSE GRAPHICS
GRAPHIC
INT -
KEYWORD
On top of the R key is the word RUN. This is a KEYWORD
character.
All characters printed on the keyboard in this position are
KEYWORDS. KEYWORDS will be printed on the screen if the
desired key is pressed when the ZX81 is in KEYWORD MODE (1.е.
the cursor is on the screen).
Exercise
If the | К | cursor is at the bottom left-hand side of the screen then enter
a keyword. Press the | PRINT | (P) key. Notice that PRINT appears on
the screen but the cursor has changed to an cursor and the
computer is in the letter mode. This means that it 1s expecting a letter
to be keyed in next, e.g. A.
If we try to key in another keyword, e.g. , the keyword
PLOT does not appear. Instead the letter O is printed. So the rule is:
No two keywords may be entered in succession.
To clear the screen and return to mode press
keys together. Try it. Print different keywords on the screen. Which
one does not print?
LETTER
The LETTER characters (or OWERTY characters as they are
sometimes called) are the bold type letters on each key. They are
identical to those on a typewriter keyboard. It is worth trying to
memorise these. Do it by lines, and in groups of five.
Letter characters may be keyed in when the computer is in the letter
mode and the cursor appears in the entered program line, or at the
bottom left-hand side of the screen. Certain letters may be entered in
the mode as default when there is no keyword on that key, e.g. the
digits 0-9 and the full stop[ e] [BREAK] is also an exception. A space
Is printed in the mode.
13
Exercise
Key in | PRINT | to obtain the mode. Then key in the letters,
starting from [1].
What happens with | NEWLINE (ENTER)| and |SPACE |?
SHIFT
There are 39 SHIFT characters on the keyboard. These may be
obtained in the Or modes, 1.e. when Or is on the
screen.
To obtain these characters or symbols e.g. in our diagram,
press the | SHIFT | key and the desired | CHARACTER | key at the
same time.
Exercise
Start keying in the SHIFT characters starting with on the top
line of the keyboard.
Notice what happens with:
EDIT
THE ARROW KEYS (^4 | e>)
GRAPHICS
RUBOUT (DELETE)
FUNCTION
GRAPHICS
There are two types of graphics characters, the characters like Bll as in
our diagram below, and the letter and shift characters printed in
INVERSE (i.e. white letter on black background) on the screen ( Ia).
Exercise
To print the graphics characters on the screen key in:
14
Keys to Press What happens on the Screen
PRINT
E] PRINT
PRINT
ГЕ | PRINT
[К | PRINT
PRINT
[Эй] PRINT
NEWLINE (ENTER) ББЗ at top of screen
0/0 at bottom of screen
NEWLINE (ENTER) [3 (clears screen)
Notice the mode cursor changes.
Note that to come out of the mode, you need to press
again, to get the cursor back. To clear the screen
press |
Repeat the exercise and obtain all the graphics characters. Where no
graphics character is printed on the key then the inverse of the shift
character is obtained by default. ‘Test this out.
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.
Exercise
Key in the characters as before, but this time only press the letters and
not the shift characters when in the mode.
What happens when you press |SPACE] ?
FUNCTION
There are 24 Function characters that are obtained only in the
Function mode, when the [F ] cursor is on the screen. The ГЕ |cursor is
obtained by pressing the |SHIFT | and | FUNCTION | keys together.
Only one Function character may be entered. The mode changes to
after entry. To input another Function character we need to get
back to the mode again.
Exercise
Get into the FUNCTION mode and key in all the function characters.
Key in -
Lr]
What happens? Press NEWLINE (ENTER) again to clear the screen.
HOW TO OBTAIN THE DIFFERENT CHARACTER TYPES
Character Number of To Obtain | To Obtain the
Type Chars. the Mode: | Character:
mmm f 26 | [E] | лонае
SHIFT 39 [K ] Automatic SHIFT
CHARACTER
LETTER 39
Automatic CHARACTER
K]
(sometimes)
mt = =
GRAPHICS CHARACTER
INVERSE
GRAPHICS
Е
GRAPHICS
CHARACTER
SHIFT
FUNCTION
CHARACTER
Exercise
Using the above table, obtain all the modes and key in example
character types.
ALPHABETIC CHARACTER/KEY TABLE
The following table locates the letter or number key which provides
each character (keyword, function, or symbol) on the keyboard. Use
this table when entering programs until you are familiar with the
placing of all the commands. An * indicates a non-printing character.
BASIC Word Keyword (K), Function
or Shift and Key to Press
ABS Function G LPRINT Shift S
ACS Function S NEW (K) A
AND Shift 2 NEXT Shift N
ASN Function A NOT Function N
AT Function C OR Shift W
ATN Function D PAUSE Shift M
CHR$ Function U PEEK Function O
CLEAR (K) X PI (m) Function M
CLS (K) V PLOT Function О
CODE Function I POKE Function O
CONT (K) C PRINT Function P
COPY (K) Z RAND Function T
COS Function W REM Function E
DELETE Shift Ø * RETURN Function Y
DIM (K) D RND Function T
EDIT Shift 1 * RUBOUT Shift @ *
EXP Function X RUN Shift R
FAST Shift F SAVE Shift S
FOR (K) F SCROLL Shift B
FUNCTION Shift NEWLINE(ENTER) SGN Function F
GOSUB (K) H SIN Function Q
GOTO (K) G SLOW Shift D
GRAPHICS Shift 9 * SOR Function H
IF (K) U STEP Shift E
INKEY$ Function B STOP Shift A
INPUT (K) I STR$ Function Y
INT Function F TAB Function P
LEN Function K TAN Function E
LET (K) L THEN Shift 2
LIST (K) K TO Shift 4
LLIST Shift G UNPLOT Function W
LN Function Z USR Function L
LOAD (K) J VAL Function J
17
SYMBOLS
Symbol Cursor and Key Symbol Meaning
K or L, Full stop or dec-
imal point (Separate key)
š K or L, shifted Full stop. Comma
; K or L, shifted X. Semicolon
z К or L, shifted 2. Colon
? К or L, shifted C. Question mark
`y K or L, shifted P. String quote
iis K or L, shifted О. Quote image
( K or L, shifted I. Open bracket
) K or L, shifted O. Close bracket
£ K or L, shifted SPACE. Pound
$ K or L, shifted U. Dollar
+ K or L, shifted K. Plus
- K or L, shifted J. Minus
7 K ог L, shifted В. Times
/ K or L, shifted V. Divide
те K or L, shifted Н. To power
= K or L, shifted L. Equals
> K or L, shifted M. Greater than
< K or L, shifted N. Less than
© = К or L, shifted К. Less than or equal to
> = K or L, shifted Y. Greater than or equal to
<> K or L, shifted T. Not equal to
“= K or L, shifted 5. Cursor left
{ К ог L, shifted 6. Cursor down
T K or L, shifted 7. Cursor up
Т” K or L, shifted 8. Cursor right
18
SECTION C: BASIC BASIC
C1: The BASIC Language
This book is all about BASIC, which is the world's most commonly
used computer language. Just as English is a natural language used to
communicate with people, BASIC is a formal language used to
communicate with COMPUTERS. Like natural languages BASIC
has grammatical rules which, although they are fairly simple, must be
strictly followed to ensure that the computer understands exactly what
it is being instructed to do.
BASIC stands for Beginners All-Purpose Symbolic Instruction
Code. It was invented in 1964 in the USA and is a combination of
simple English and algebra. BASIC is the language we will use
throughout this book to write PROGRAMS. Programs instruct the
computer what to do, and the sequence in which particular operations
are to be performed.
BASIC is a high-level programming language. The instructions we write
in BASIC are interpreted by a built-in program into the low-level
programming language (the MACHINE CODE) that directly controls
the switching of the electrical impulses inside the MICROCHIPS
which store and manipulate the data. High-level languages like BASIC
are far easier to write programs in than the low-level languages, and
the simple language and structure of BASIC was designed to be easy to
learn. The Sinclair version of BASIC also has single-keystroke entry of
BASIC words, which makes mistakes in spelling impossible.
C2: A Simple Program
A sequence of BASIC statements is called a PROGRAM. Here
is an example of a program:
10 INPUT A
20 INPUT B
30 LETS=A+B
40 PRINT S
The simple program above adds two numbers keyed in on the
keyboard and prints the results on the screen. A program is keyed (or
typed or input or entered) into the computer by you, the programmer,
line by line, from the keyboard.
Before we key a program in we design it to make the computer do
exactly what we want. We first write a program down line by line on a
piece of paper. This is called CODING.
After coding the program we key it into the computer and RUN it.
To RUN it we give the computer a COMMAND to RUN the program
to see if it works. It probably won't work the first time, unless it's as
19
simple as our example. A program which doesn’t work as intended is
said to contain ERRORS or BUGS.
If we have asked it to do something it can’t do, or forgotten to
include an instruction the computer will tell us what is wrong and give
us an ERROR MESSAGE. If the program runs without error
messages but doesn’t do what we wanted it to then it is the
programmers’ fault. In either case we need to correct or EDIT or
DEBUG the program. We do this whilst the program is in the
computer, using the editing facilities of the computer.
Editing or revising a program is called PROGRAM
DEVELOPMENT. When the editing is finished and the program
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
that we can LOAD it back into the computer.
The complete exercise of designing, coding, developing and
documenting a program is called PROGRAMMING.
C3: A Statement
This is a BASIC statement:
10 INPUT A
A statement is also called a LINE. A statement can:
(1) instruct the computer to do something
(2) state something
A statement is composed of: a line number, e.g. 10
an instruction, e.g. INPUT
some variables, e.g. A
Statements are either: Executable — those which specify a program
action, as with our INPUT A, or Non-Executable — those which
provide information for the user of the program.
All variables (e.g. A in our example) must be initialised to a start
value before being used in a program. In this case the statement:
10 INPUTA
tells the computer to request the user to input a value for the variable A
from the keyboard.
C4: Statement Numbers
Each BASIC statement or line must begin with a statement
number, as with 20 in this example.
20 INPUT B
The number 20 is called a statement number or line number. The
statement number is chosen by you, the programmer. It may be any
number from 1 to 9999 inclusive. ‘The computer uses the numbers to
keep the statements in order. Each statement has a unique statement
20
number. If you use the same statement number twice, the second line
will replace the first.
Statements may be keyed in via the keyboard in any order. The
computer sorts them into the correct sequence. Statements are usually
numbered in tens so that additional statements are easily inserted later.
For example:
10 INPUT А
20 INPUT B
25 INPUT C (Inserted line)
30 LET S=A+B
The computer runs the program in order of statement numbers.
C5: Instructions
A statement gives an instruction to the computer. In this
example it is LET.
30 LETS=A+B
Instructions are called statement types because they identify a type of
statement. In our example the statement is a LET statement. It tells
the computer to let the variable S have a value equal to the sum of the
values of variable A and variable B.
C6: Numeric Variables
A numeric variable is the name given to a storage location
which holds a number in the computer's memory.
A numeric variable can have a name which is:
A letter from A-Z
or A letter followed by a number
or A group of letters and numbers
Variable names must start with a letter.
Examples of numeric variables: A
NUMBER 1
Numeric variables are used to represent numbers inside the computer.
We can give (or assign) different values to a variable. The numbers we
give to variables are used in calculations.
Variables are symbols or names given to parameters or quantities.
They represent the VALUE of the parameter, i.e. the number stored
21
in the named memory location. We can use variable names which
remind us of the parameter concerned, but they should not be too long
or you will find them tiresome to key in (which is why single letters are
usually used).
For example, we could use:
S — Speed
PRICE - Price of fish
SUM 1 - Sum of the first set of numbers
R3 - Resistor Three
In our program the statement
10 INPUT A
sets up a variable in the computer's memory with the symbolic name
A. We could have called it NUM1, or even FIRSTNUMBER.
The statement tells the computer to ask us to input a value for À
when we run the program. If we key in the number 3 the memory cell
allocated to A will contain the number 3. This value is then used in all
calculations involving À until we change its value.
In the statement:
30 LETS=A+B
S, A and B are the variables in the algebraic equation S= A + B. Š is
our ‘unknown’ and will take the sum of the values of A and B. The
computer will work out the value of A + B and put the result in the
memory cell it has allocated to the variable S. The computer will not let
us input LET A+ B = S (it will give us a syntax error), because the
variable to be given a value must come first. A + B is not a valid
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
we instruct the computer to do something which causes the value to
change. For CONSTANTS, which are quantities which do not change
their value, we set up a variable in the same way, by giving it a name
and a value with a LET statement and let it keep the same value — a
variable that doesn't vary!
Variable names may be of any length, but they must start with a
letter, and must only contain the alphanumeric characters (the letters A
to Z and the numbers @ to 9). They can have spaces included, but this
is unwise, as it is easy to key іп PRICEI, for example, when you
initialised a variable as PRICE 1. The computer will consider them to
be two different variables. The inverse video (white on black)
characters also cannot be used in variable names.
22
C7: Strings and String Variables
STRING
A STRING is a group of characters enclosed by quotation
marks.
The following are examples of strings:
“PETER”
“12345”
“JANUARY 1ST, 1982”
sot “Жы А,
“REF:A2”
As well as numbers, computers can also handle text or groups of
characters. Го define a group of characters as a string, we have to place
quotation marks at the beginning and end. This tells the computer, for
example, that the string ‘“TOTAL’’ means the characters T,O,T,A,L,
and not the numeric variable TOTAL, which is a number.
Strings can contain any character which prints on the screen, plus
spaces, but a string cannot contain quotation marks, because the
computer thinks it has got to the end of the string when it gets to the
second quotation mark.
Now that you know what a string is, we can tell you that strings can
be handled by string variables, just as numbers can be manipulated
with numeric variables.
STRING VARIABLE
A string variable is used to store strings. It consists of a single
letter (A to Z) followed by the $ sign. For example:
A$, Z$, M$
We allocate (or assign) strings to string variables with LET statements,
as with numeric variables. For example:
10 LET A$=‘‘STRING 1"
20 PRINT A$
The memory store allocated to A$ will contain the string ‘STRING 1’
(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.
22
C8: Operators and Operands
OPERATORS
Operators perform arithmetic, logical or conditional
operations on variables or numbers.
In our program the line:
39 LETS=A+B
uses the two arithmetic operators
= and +
OPERANDS
Operands are the variables or numbers which are
manipulated (i.e. operated on) by the operators.
In the line:
30 LET S=A+B
the variables S, A and B are operands.
C9: Format of Statements
BASIC is a ‘free format’ language. The computer will ignore
extra blank spaces in a statement.
The following statements are equivalent:
10 INPUT A
10 INPUT A
10 INPUT A
The computer will automatically leave spaces after each line number
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.
C10: Keying in a Statement
Statement to be keyed in:
10 INPUTA Press
If your computer system is set up and ready for use (see Section B1) the
cursor will be in the bottom left-hand corner of the screen. You can
now key in the first statement.
24
Character or Cursor Keys to What appears
instruction Press on the Screen
to key in
[к]
2 2 19 [к]
ж
INPUT I 19 INPUT
A [z]. A i mera [Z]
*
NEWLINE
(ENTER)
Entered line is
transferred to top
of screen
*
on Spectrum in CAPS mode
PRESS NEWLINE (ENTER) AFTER EACH STATEMENT
The |NEWLINE (ENTER)| key must be pressed after each
statement has been entered.
10 INPUT A
20 INPUT В
30 LET S =A+B[NEWLINE (ENTER) |
40 PRINTS
Pressing the | NEWLINE (ENTER) | 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
cursor to the left-hand side of the screen, ready for us to enter the next
program line.
Notice that the line at the top of the screen now contains the
CURRENT LINE CURSOR:
This indicates the last program line entered and accepted by the
computer. It appears immediately after the line number:
10 [>] INPUT A
25
C11: Correcting Errors
RUBOUT (DELETE)
The RUBOUT (DELETE) key acts as a backspace, deleting
the character symbol or keyword immediately preceding (to
the left of) it.
As we type in a line we may press the wrong key. For example, we
might get:
10 INPUTS
where we pressed S instead of A. To correct this we press RUBOUT
(DELETE) and we get:
10 INPUT
We may now continue and type in A.
The horizontal arrow keys move the cursor one character or
keyword to the left or right along a line as indicated.
For obvious reasons, these keys are also referred to as cursor control
keys.
To correct an earlier mistake on a line
(a) Use the arrow keys to move the cursor to a position immediately
to the right of the character to be changed.
(b) Press RUBOUT (DELETE) to delete the incorrect character,
and key in the correct character.
(c) Use the arrow key to return the cursor to the end of the line, if
you have more to key in. Otherwise, you may press NEWLINE
(ENTER) immediately. It does not matter if the cursor is In
the middle of the line.
To delete a complete line
This can be done by using the > key to get the cursor to the end of the
line, if you are not there already, and then using RUBOUT
DELETE) repeatedly until the line is completely deleted and just the
cursor remains. This is tedious on a ZX81, without the
Spectrum’s repeat key, especially on a long line. A better way is:
(1) Press EDIT
(2) Press NEWLINE (ENTER)
26
If you are keying in the first line of a program and there are no existing
lines at the top of the screen, pressing EDIT will clear the line.
If there are program lines at the top of the screen, pressing EDIT
clears we current line and brings down the program line marked with
the cursor. Pressing NEWLINE (ENTER) sends this line up
again г. clears (һе current line.
Exercises
1 Start keying in the first line of the program. Don’t press
NEWLINE (ENTER).
Play around with the cursor control keys and RUBOUT
(DELETE).
Delete the complete line.
3 Key in the first line and press NEWLINE (ENTER).
Key in the second line.
4 Delete the second line using EDIT and NEWLINE (ENTER).
5 Кеуіп the second line. Key in the third line to read:
30 LET X =A + B. Press NEWLINE (ENTER)
Use EDIT to bring this line down again. Use the cursor control
keys to put the cursor to the right of X and delete it. Insert S.
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.
N
C12: Commands
COMMANDS are direct instructions to the computer. They
are executed immediately. They do not need line numbers, as
they are not part of a program.
Commands give us direct control over the computer.
Examples are:
RUN
LIST
BREAK
SAVE
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
must be empty. Then press [NEWLINE (ENTER). Some commands
are executed instantly, without pressing NEWLINE ie i (e.g.
BREAK), and are not printed on the screen.
Most commands are also used as instructions in programs. Some of
the commands that can be used as direct commands are not actually
very useful in this role. Equally, some that could be used in programs
never are. However, each command has a key role to play in the
27
BASIC language and we will deal with the individual commands as we
encounter them in the text.
You have already met the NEWLINE (ENTER), RUBOUT
(DELETE), < and -” commands, and the mode commands
(GRAPHICS and FUNCTION). Together with EDIT, RUBOUT
(DELETE) and BREAK, plus the f and $ arrow keys, these are the
commands that don’t print, and act instantly. All the others need
NEWLINE (ENTER) to be activated.
C13: Editing the Program
EDIT
The EDIT command copies the program line indicated by the
cursor at the top of the screen, to the bottom of the screen,
replacing any current line. The line brought down can then
be edited or changed.
EDIT may also be used for entering lines that are similar where only
the line number changes:
(1) Key in the line.
(2) Press NEWLINE (ENTER) - line goes to top of screen.
(3) Press EDIT - line copied to bottom of screen.
(4) Use RUBOUT (DELETE) to delete the line number.
(5) Key in new line number.
(6) Press NEWLINE (ENTER) - new line goes to top of screen.
The same procedure can also be useful with lines which only vary
slightly, i.e. perhaps only the line number and a variable are different.
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
changed. Insert the new character, and press NEWLINE (ENTER).
These commands move the cursor in the entered program
at the top of the screen from one line to another. This enables
us to then copy down any line in the program for editing using
[EDIT].
Deleting a line in the entered program
To delete a given program line which has been entered and is at the top
28
of the screen just type the line number and press NEWLINE
(ENTER).
For example:
10 |NEWLINE (ENTER
will delete line 10 in the program. You will see it disappear from the
screen.
C14: Listing a Program on the Screen
LIST
The program has been entered into memory. To produce a
listing on the screen of all lines accepted by the computer key
in:
LIST NEWLINE (ENTER
LIST is a command that prints on the screen. It appears on the bottom
of the screen, and is executed when NEWLINE (ENTER) is pressed.
LIST N
Will list a program starting from program line N.
For example, if we key in:
LIST 30 NEWLINE (ENTER
our program will be listed from line 30.
We key in LIST, then the line number we want the listing to start at. If
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
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
SCROLL? prompt. Answering this with anything other than ‘N’ or
BREAK scrolls the listing up so that the next screenful of statements
can be seen.
C15: Running the Program
Our simple program has been keyed into the computer line by line and
entered into memory.
Let's see if it works. We give the computer the command RUN.
29
RUN
NEWLINE (ENTER
The RUN command starts execution of a program at the
lowest numbered statement.
Run is a command and is keyed in. It appears at the bottom of the
screen. It will not be executed until [NEWLINE (ENTER)] is pressed.
When we do this the program starts operating. The screen will go
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,
using CAPS LOCK as we advised.) The computer is now running the
program and asking us to input a number for the variable A.
Key in the number and press [NEWLINE (ENTER)] . The
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
number | 5 | and press .
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
also run the program from a line other than the first program line:
RUN N
RUN (Line Number)
This command starts execution of the program from the
specified statement (line) number.
RUN 20
will start a program at line 20.
Note that when the RUN N command is used all statements before the
specified statement number (N) will be ignored and any variables
defined in these statements will be considered by the computer to be
undefined because it has not RUN the lines. The program will not
work and an error message will result. All values of variables are
wiped out by the RUN command.
We can RUN the program as many times as we wish:
Key in [| NEWLINE (ENTER) | again
If the program has been run once and the message is at the bottom of
the screen, to rerun the program key in RUN. This overwrites the
message and pressing NEWLINE (ENTER) starts the computer
operating the program. The L-cursor appears to prompt for an input
again (C-cursor for Spectrum in CAPS mode).
30
The screen is now blank. We can get the program listing back very
easily:
Press NEWLINE (ENTER)
After running the program, the program listing re-appears at the top of
the screen if the NEWLINE (ENTER) key is pressed. The program
can now be edited if necessary.
C16: Error Messages
Our computer tells us it has finished running the program by giving us
a message. On the ZX81 this will be:
0/40
at the bottom of the screen. The Spectrum gives an expanded version
of the message:
0 OK, 40:1
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
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
shall see later.
These special diagnostic messages appear at the bottom of the screen
every time a program is run. If the program does not work a message
appears with the form:
E/N
E is a number or a letter indicating the type of error that has caused the
program to stop, and N the line number where the program halted due
to the error. The Spectrum adds a message briefly stating the cause of
the error.
We look up the meaning of E in the list of Error Codes in Appendix
II. This helps us to correct or debug the program, since we know what
sort of problem has occurred and which program line it happened at.
Exercises
1 Run the program on page 19 a number of times keying in
different values for A and B.
2 Press NEWLINE (ENTER) to get the listing. Change line 30 to
read:
30 LETS-A-«C
31
Now RUN the program.
The error message 2/30 (on the ZX81) appears. On the
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
we have forgotten to define a variable. We are now using the
variable C instead of B, but we have not yet given C a value, and
the computer could not complete the operation of line 30 due to
insufficient information.
Insert a new line:
25 INPUT C
and run the program again. It now works.
Why did the program originally stop at line 30?
Why do we now have to key in 3 numbers to make it work?
3 Add an extra line at the beginning of the program. Key in:
5 PRINT “PROGRAM ADDS 2 NUMBERS"
RUN the program, starting from different lines by using:
RUN
RUN 10
RUN 15
Why do you think RUN 15 does not work?
4 Edit the program to obtain the original version.
C17: How the Program Works
Line 10 tells the computer that a number must be
input and given the name A, (i.e. assigned to the
variable A). ‘The computer reads the line and prints
an at the bottom of the screen,* reminding us
to input a number. The computer will wait until we
key in a number. The number is then stored in
memory cell A. The computer goes to the next line.
Line 20 tells the computer that another number,
to be assigned to the variable B, must be input.
appears at the bottom of the screen* and the
computer waits until we key in a second number,
which is stored in memory cell B. The computer
goes to the next line.
Line 30 tells the computer that a variable 5 18 to
be assigned the value of the sum of the variables A
and B. The numbers in cells A and B are added
10 INPUT A
20 INPUT B
30 LETS=A+B
*This will be a C-cursor if using a Spectrum with the CAPS LOCK facility used, as
Spectrum users must do throughout this text to get program listings which appear the
same as the ones in the text. Use the CAPS SHIFT and CAPS LOCK keys
simultaneously on switch-on, and remember that the C-cursor will appear instead of
the L-cursor. We will not mention this again.
32
and placed in cell S. The computer goes to the next
line.
Line 40 instructs the computer to output the 40 PRINT S
value of Š to the screen. The computer looks for the
next line.
The computer can find no more statements to
execute in the program and gives a message 0/40
on the screen telling us that the program finished
with zero errors at line 40. The Spectrum gives the
same message, in the form 0 OK, 40:1.
The computer now waits for more commands.
C18: Naming the Program
5 REM “NAME”
Programs are named in a REM statement. The program name
is enclosed in quotation marks. The program is usually named
in the first statement in the program.
We need to give our program a name in order to:
(1) Differentiate it from other programs
(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).
The program name can be any combination of characters and any
length on the ZX81. On the Spectrum, program names for use with the
SAVE and LOAD instructions must start with a letter, and can only
have 10 characters in the name.
It is sensible to keep the program name short and relevant to the type
of program, although some programmers name programs after
themselves:
“PETER 1”
“PETER 2" ete.
Programs which undertake various kinds of statistical analysis could be
named:
"STATS
“STATS2” etc,
Programs which perform calculations for experiments in the laboratory
could be named:
"OPTICS З”
“FRICTION”
“TITRATION” etc.
If spaces are used in program names, it is easy to misread them, or
forget that there should be a space. If the program name is not one
word, we can use an asterisk:
“FETTER?”
“FOCALLENGTH” etc. ((FOCAL*LEN"' for the Spectrum)
33
Program names and cassette tape codes should be recorded in a
DIRECTORY which enables us to access a PROGRAM LIBRARY
of programs stored on tape.
We need to name our program: List the program and add a line
which names the program. For example:
5 КЕМ “SUMPROG”
or S REM “PROGI”
could be used. We will call our program “АПОПОЕК”, so key in
5 REM “ADDER”
34
SECTION D: SAVING, LOADING AND LISTING
D1: Saving the Program on Cassette Tape
We need to save programs on to cassette tape (the off-line storage medium
the Sinclair computers use) because when the power supply is switched
off (or disrupted - variations in the mains supply can affect the
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.
SAVING THE PROGRAM
1 Check that the cassette recorder is plugged in (or has
good batteries).
2 Ensure it is connected to the computer, with the MIC-
MIC sockets being connected. See the important
Spectrum note below.
35
мы GO
Set the TONE control on the cassette recorder to HIGH.
Set the volume control on the cassette recorder to 3/4 of
MAXIMUM.
Insert a new C12 computer cassette tape into the
recorder. Short cassettes are more convenient than long
ones for our purposes.
Run the tape through on FAST FORWARD and then
REWIND to ensure equal tension.
Set the tape counter to zero and run the tape forward five
revolutions (about 20 or 30 seconds).
List the program on the screen and printer.
Check the program is named (e.g. ‘‘ADDER’’) іп a REM
statement.
ZX81 Sequence
10
11
12
13
14
15
Type SAVE “ADDER” don't press NEWLINE
(ENTER) yet.
Press RECORD and PLAY buttons on the recorder.
Press [NEWLINE (ENTER) ].
Watch the screen.
a) For five seconds it will be grey inversed by diagonal
white lines and if the sound on the TV is turned up
it will be a monotone.
This is the SILENT LEAD IN
b) For ten seconds a horizontal striped pattern appears
on the screen. This is the program going in. A
warbling sound is first heard, then half second
pulses.
с) Тһе screen goes white and the message 0/0 appears,
telling us the computer has transmitted the program
to the cassette recorder.
The ZX81 does not know whether the recording is
successful.
We can only tell by later loading the program back
in.
Stop the recorder
Note the counter reading at the end of the program.
Run the tape forward five more revolutions of the
counter, ready for the next program.
Spectrum Sequence
IMPORTANT NOTE: YOU MUST ALWAYS TAKE THE
JACK-PLUG OUT OF THE EAR SOCKET OF THE
SPECTRUM BEFORE ATTEMPTING TO SAVE A
PROGRAM.
36
10 Key in SAVE “ADDER”.
11 Press ENTER. The Spectrum will print a message on the
screen which tells you to ‘Start tape’, i.e. press RECORD
(or record and play, depending on your cassette
recorder), and “then press any key'. Do so.
12 Blue and red lines (black and grey оп a black and white
TV) will scroll up the border area of your TV screen. This
happens twice as the name of the program is recorded.
When the program is copied, narrow yellow and
blue/black lines roll up the border area. When the
recording is complete an *0 OK" report appears on the
screen. Stop the recorder. Note the tape counter reading.
Your program should now be correctly recorded.
13 On the Spectrum, you can check this without wiping out
the program in memory first. Connect the EAR lead from
the Spectrum to the cassette player EAR socket. Rewind
the cassette to before the start of your recorded program.
Get into the E mode, and key in VERIFY, then enter the
program name between quotes. Press ENTER and start
the cassette on PLAY. The Spectrum displays on the
screen any other programs before the specified one that it
finds on the tape, printing their names on the screen.
14 When the program has finished playing back, an “0 OK’
message means the program was correctly SAVEd, and
*R Tape loading error' means the recording is faulty and
you should SAVE the program again.
15 Run the cassette on five more revolutions of the tape
counter, ready for the next program.
The sequence above assumes a tape counter on your cassette recorder.
Without a counter, the process of finding a program is more difficult.
To place a voice message on the tape, so that the tape is searched for
the voice giving the program name, will prevent the tape being
searched automatically by the computer, but it 1s one possible method.
If used, you should record your voice (most cassette machines have a
built-in microphone) stating the program name several times, then the
program name should be spelt out, the name stated again, and some
cue statement (“saving starts now’) to let you know that after that point
only computer-generated noises exist. This will make finding the
program much easier, as the voice cues occupy a larger length of tape
than a single statement of program name.
The other alternatives are to place only one program on each tape (a
bit uneconomical!) or to leave very large gaps between tapes (30
seconds at least), so that you can search using fast forward/reverse and
are unlikely to miss the gap. This has the advantage that you can set
the computer to search through the tape program by program if you do
miss it. Larger programs should be placed if possible on a side of a
37
cassette by themselves. Short length cassettes are available (5 minutes a
side) to make this a viable option.
Exercises
1 Try a dummy run first. Do not press the recorder keys. Turn up
the sound on the ТУ until you can hear a hum. Awful, isn’t it!
Key in SAVE “ADDER?” and press NEWLINE (ENTER).
(Press a key in response to the message if using a Spectrum).
Watch the screen and listen to the different sounds. When the
screen clears and the 0/0 message appears (0 ОК, 0:1 оп а
Spectrum), key in LIST NEWLINE (ENTER) to get the listing
back.
2 Now SAVE the program on to the tape.
D2: Deleting the Program from Memory
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
respond to commands keyed in. It is much better to use the command
NEW.
NEW
The NEW command deletes any current program and
variables from the computer and clears the screen.
We use the NEW command before we LOAD a program into the
computer from cassette tape, to erase old programs and data from
memory. It is also used to do the same thing, if we have a program in
the computer and wish to clear it out to enter another.
There is another command that only affects the variables store, and
not both this store and the program store, as NEW does.
CLEAR
The CLEAR command erases all the variables in the current
memory.
CLEAR can be used as an instruction in a program, as can NEW, but
since NEW would merely wipe the program its use would be self-
defeating. Try it, if you like the idea of a program that self-destructs!
38
CLEAR is similarly useless in the middle of a program - we would
merely have to re-define all variables.
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
values are SAV Ed also. In our case this is irrelevant, since the INPUTSs
will change them when it is used but often it is useful. We can store
data as variables in a program, and not have to re-input values (as long
as certain procedures are followed, as we will see later). This enables us
to have, for example, a telephone directory stored in variables. We
might then use CLEAR to wipe one list, and re-input new data or use
CLEAR before SAV Eing the program to send to a friend for his use.
CLEAR acts slightly differently on the Spectrum (see page 458), but
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!
Exercises
1 RUN “ADDER”. Enter NEWLINE (ENTER)| to clear
the screen. Enter GOTO 40, then press NEWLINE (ENTER).
The computer will print the value of 5. Now enter
and then GOTO 40 (NEWLINE/
ENTER) again. We then get an error message 2/40 (2 variable
not found, 40:1 on the Spectrum) indicating an undefined
variable, because the computer has wiped the value of S. We will
deal with GOTO in due course. Just follow the instructions for
now.
2 LIST the program ‘‘ADDER”’ on the screen. Press and
. The listing will disappear and the
cursor appears. On the Spectrum, when NEW is followed by
ENTER, the screen will go black for a moment then become
white, with the words ‘© 1982 Sinclair Research Ltd’ at the
bottom of the screen.
3. Press and then [NEWLINE (ENTER) ]. What happens?
Why?
4 Key in the first line of the program and press NEWLINE
(ENTER). Switch off the power supply (by pulling out the jack-
plug). Switch it on again (by re-inserting the jack-plug). What
happens?
5 Re-enter ‘‘ADDER’’.
D-3
39
D3: Loading the Program from Cassette Tape
LOAD “NAME”
The command LOAD “МАМЕ” waits for the cassette to play
the portion of tape with the program called “NAME” and
copies the program, with its variables into the computer’s
memory.
This means that we can start the tape, give the command LOAD
“МАМЕ”, and the computer loads nothing into its memory until the
signal it recognises as NAME appears on tape. We can thus search a
tape for a program. The Spectrum will print on the screen the names of
any programs it finds on tape, before it encounters the specified
program.
LOAD “”
The LOAD “” (nothing between the quotes) command
LOADS the first program it finds on the tape.
N
LOADING PROCEDURE ON THE 4Х81
Place the tape with the desired program in the cassette
player.
Position the tape via the counter to just before the
location of the required program.
Clear the computer’s memory using the
command if there’s a program in memory.
Set the TONE control on the tape recorder to nearly
Maximum (High), and the VOLUME control to %
Maximum.
Key in LOAD “ADDER” or the appropriate name.
Don’t press NEWLINE (ENTER).
Depress the PLAY key on the cassette recorder.
Press NEWLINE (ENTER).
A thin diagonal pattern will appear on the screen with a
single tone sound.
The pattern changes to broad horizontal stripes with
thinner diagonal stripes and half second sound pulses are
heard as the program is loaded in.
The screen clears and а 0/0 message indicates the
loading is a success.
STOP the recorder.
40
10
11
COND л
10
11
12
LIST and RUN the program.
Remove the tape when finished.
LOADING PROCEDURE ON THE SPECTRUM
Place the tape with the desired program in the cassette
player.
Position the tape via the counter to just before the
location of the required program.
Clear the computer’s memory using the NEW command
if there’s a program in memory.
Set the TONE control on the tape recorder to nearly
MAX (High), and the VOLUME control to % MAX.
Key in LOAD ‘‘ADDER’’, but don’t press ENTER yet.
Press the PLAY button on your cassette recorder.
Press ENTER.
When the Spectrum has found a program it will scroll
blue and red bands of colour up the border area. The
name of the program will be printed to the screen and
then the blue and red lines repeated again. If the correct
program has been located, then it will LOAD with a finer
set of blue and yellow lines scrolling up the border area.
If not, the border area will flash blue and red alternately
as it carries on to the next program on the tape.
When the program is correctly loaded, the phrase:
0 OK, 0:1
will appear at the bottom of the screen to indicate that all
is well.
Stop the recorder.
LIST and RUN the program.
Remove the tape when finished.
CAUSES OF FAILURE TO LOAD
1
3
Volume too low.
Volume too high.
Tone too low.
These indicate that the program has been played at the wrong
settings. New volume and tone adjustments will have to be
made. Some indications of these problems are visible on the
screen display of the ZX81, although systems vary in their
response. Appendix IV has a procedure for adjusting tone and
volume settings for the ZX81, as well as some general hints on
tape use. Experiment and get to know the patterns produced
during LOAD on your ZX81.
41
4 Loading started in the middle of the program. If a mistake has
been made with the start position, rewind the tape completely
and let the computer search for the program name.
5 The program is not on the tape. Check your directory, and the
writing on the cassette.
6 Тһе program name is incorrect. Try again, making sure you
have spelt it correctly in the LOAD instruction. If you fail again,
run through the tape using the LOAD ““””' command. This will
load the first program each time. Stop the cassette player after
each load and LIST the program to check. (This is not necessary
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 оп tape if you use a LOAD “ZZZ” instruction,
i.e. a name that does not exist as a program name.
7 Pick up from stray electromagnetic fields.
This will show as violent interference on the screen, distorting
the patterns together with excessive hum on the sound. It could
originate from the ГУ itself, feedback between the recorder and
the computer or an external field. Switch off any radio that is in
the vicinity. Take out the jack-plug from the MIC socket of the
cassette player, as this will break the feedback loop that can exist
between the computer and the cassette player.
The Spectrum has fewer LOADing problems than the ZX81. It will
accept a much greater variation in both the volume and tone of the
signal. However, it is worth noting that if there are great differences
between the recorder the tape was recorded on and the one it is played
back on (variations in tape-head azimuth is often the main source of the
problem), then LOADing can be almost impossible, even on the
Spectrum.
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 “ххх” command. The same applies if you
use upper case letters to name a program. Thus, a program named
“MATHS” will not LOAD with the statement: LOAD ‘‘maths’’.
Some further information concerning the use of cassette tapes, and
advice for the ZX81 if problems are encountered is given in Appendix
IV.
Exercises
1 Load the program “ADDER”. LIST and RUN it.
Delete it from memory, using NEW.
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
patterns change when you change the settings while the program
is loading. Read Appendix IV.
D4: Listing the Program on the Printer
LLIST
LLIST lists the program currently in the computer memory
on the printer, starting from the first program line.
LLIST N
LLIST N lists the program on the printer starting from line
N.
We can stop the listing by pressing (BREAK needs CAPS
SHIFT on the Spectrum). This stops the listing with an error message
D/line number on the ZX81 and D BREAK - CONT repeats 0:1 on
the Spectrum.
It is important that you keep a listing or printed record of all the
programs you write or use. The listings are a great help in debugging
programs (both under development and if there are problems
discovered later). We can key the program back in from this listing, if
necessary.
Printouts also form part of the documentation for a program and
should be pasted into a notebook. Printed records of program results
can also be kept using the COPY command.
Exercises
1 LLIST the program ‘‘ADDER”’ on the printer.
2 ‘Try stopping the listing with the BREAK key. The listing cannot
be continued by pressing CONT (try it). On the Spectrum,
despite what it says, this doesn't work. The screen just goes
blank. Don't worry. Press BREAK again.
3 List the program on the screen. Use the COPY command to list
the program on the printer.
What is the difference between the two listings obtained with
LLIST and COPY?
43
D5: Program Libraries and Directories
LIBRARY
A collection of programs stored on cassette tape. For example:
COMPUTERLAB PROGRAM LIBRARY
or Your own program library.
Notice that programs can also be stored on magnetic discs and im
ROM memories.
DIRECTORY
The list of program names in the library together with
important information about them. Another name for a
directory is CATALOG.
You should keep, in your notebook, or a special book, a directory of all
programs you have entered and saved on tape. This will seem a bit
pointless when you only have a dozen or so, but you will appreciate the
need to be systematic when you accumulate a large number.
PROGRAMS YOU WRITE
Each program you write should be
Named.
Saved on a cassette tape.
Listed on the printer.
Documented.
Catalogued into the Directory of your own program
library.
Gm wm G3 N =
DOCUMENTATION
The complete collection of information about the program or
file, written on paper. The information should include:
1 What the program does.
How it does it.
A listing.
A flowchart.
How to use it.
When it was written and by whom.
Q3 Gr мы CS N
44
We will introduce flowcharts in Section G.
DIRECTORY LAYOUT
A typical layout for the Directory Section of your notebook
would be:
Program Name: MOONLANDER
Cassette Name: GAMES 3
Locatton: 100-120
Program Length: 30 lines
Date Created: 18.5.82
Author: PAUL NIXON
Function: Lands a spaceship on
the moon
WRITING ON THE CASSETTE
There is a label on each side of the cassette. Write on each
side:
1) Cassette name or code.
2) Date.
3) Program names as they are copied into it. Make sure
these are correctly spelt!
Your directory should provide you with the more detailed
information, such as precisely where the program is to be
found.
45
SECTION F: IMPROVING THE PROGRAM
E1: Adding Comments
REM
The REM statement is used for adding comments to a
program. All REM statements are ignored by the computer
when the program is RUN.
These comment statements are for the users’ benefit only.
They contain information in the text of the program which
explains what the program is doing. For example:
REM **THIS PROGRAM ADDS TWO NUMBERS
KEYED IN AND PRINTS THE RESULTS**
Notice the use of the asterisks to separate the text from the
instruction.
100 REM ** END OF PROGRAM**
The complete program including all REM statements appears on the
screen or printer when using the LIST and LLIST commands.
Our saved program so far looks like this:
5 REM “ADDER”
10 INPUTA
20 INPUT B
30 LET S=A+B
4) PRINTS
Let us add some additional REM statements:
6 REM **THIS PROGRAM ADDS TWO NUMBERS
KEYED IN AND PRINTS THE RESULT**
60 REM **END OF PROGRAM**
Key these extra statements in. LIST the program and RUN the
program.
Do not worry about the line numbers not being in intervals of 10.
We will renumber the program when we have added all the extra lines.
E2: Using the Print Statement
PRINT
In our simple program we will use the PRINT statement:
a) To print messages and instructions to the user on the
screen:
7 PRINT “INPUT TWO NUMBERS"
The message INPUT TWO NUMBERS is a string, and
will be printed without the quotes.
46
b) To print the numbers keyed in and the result:
40 PRINT A; ‘‘ + ’’;B;‘* = ?°;5
A and B are the names of the variables to which the
numbers keyed in are assigned, and S is the variable that
stores the sum of A and B, i.e. the result. Variables do
not need quotes to be printed.
The semicolons (;) tell the computer that we want close
printing, with each print item (character or variable)
directly after the last, with no spaces between. The
inverted commas (quotes) enclosing the symbols + and
= means we want those symbols printed.
c) To leave spaces between lines printed on the screen:
8 PRINT
The PRINT instruction used on its own prints an empty line
on the screen.
Note that we have changed line 40 from what it was previously. Our
program now looks like this:
5 КЕМ “ADDER”
6 REM **THIS PROGRAM ADDS TWO NUMBERS
KEYED IN AND PRINTS THE RESULT**
7 PRINT “INPUT TWO NUMBERS”
8 PRINT
10 INPUT A
20 INPUT B
30 LET S=A+B
40 PRINT А‘ + ‘В; = > 58
60 REM **END OF PROGRAM**
Key in the new lines and RUN it.
E3: Adding a Loop
GOTO N
The statement GOTO N transfers program execution to the
specified line number, N. For example:
50 GOTO 7
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
execute the program again from that line, and as soon as the computer
reaches line 50 again it is sent back to line 7 once more.
We have constructed a LOOP. The program is going to carry on
looping forever unless we can pull out of it.
47
Our program now is:
5 REM “ADDER”
6 REM **THIS PROGRAM ADDS TWO NUMBERS
KEYED IN AND PRINTS THE RESULT**
7 PRINT “INPUT TWO NUMBERS”
8 PRINT
10 INPUT A
20 INPUT B
30 LETS-A-«B
40 PRINT A;" &'B;"UeCUNS
50 GOTO 7
60 REM **END OF PROGRAM**
Key in line 50. RUN the program. When you are tired of inputting
numbers, read on.
E4: Stopping the Program
We need to know how to get out of the input loop between lines 7 and
50. The program will wait for an input of a number at line 10 INPUT
A. The cursor will appear on the screen.
To pull out or stop the program at this stage key in [STOP |
[NEWLINE (ENTER)]. STOP is a command we input directly, like
RUN.
STOP
On the ZX81 the STOP command stops a program with the
message: D/line number, and on the Spectrum we get H
STOP in INPUT (Line number):1.
The line number refers to the program line the computer
was executing when it was stopped.
Our program will give D/10 as the message (H STOP in INPUT 10:1
on the Spectrum). We can cancel the STOP command and continue
the program with the CONT command.
CONT
The CONT command used after the STOP command will
continue the program from the line the program was stopped
at.
48
Keyin ICONT | INEWLINE(ENTER)| to continue the program. Note
the Spectrum prints CONT in full as CONTINUE.
Exercise
Run the program “АОПЕК”.
STOP the program when the first | L | cursor appears.
CONTinue the program, and input a value for A.
STOP the program when the second cursor appears. Note that
the line number is different in the message that appears on the bottom
of the screen.
CONTinue the program.
E5: Testing for a Condition
In a program we can make decisions which will affect what the
computer does next. A decision is made on the basis of whether a
CONDITION is true or false.
CONDITION
A condition has the form (X) (condition) (Y) where X and Y
are numbers, variables or expressions and the condition is a
conditional operator. We shall use only the = (equality)
operator for the moment. The following are all conditions:
X=Y
A = 23
B = 2*3
Conditions are tested and the next action determined by the result of
the test with the IF and THEN statements used together.
IF - THEN
An IF - THEN statement has the form:
IF (condition) THEN (instruction)
For example: IF А = B THEN PRINT “EQUAL”
IF A=@ THEN LET A= 3
The instruction can be any valid instruction. The statement
means:
IF (the condition is TRUE) THEN (perform as instruction).
IF (the condition is FALSE) the computer ignores the
instruction after THEN and goes to the next line of the
program.
49
In our simple program we can use the IF — THEN statement to insert
in the program a conditional test which will stop the loop, without
using the direct commands which we used in the last Unit. To STOP
the program in the same way as with a direct command we can insert
another line:
15 IF A«9 THEN STOP
This tells the computer that IF A = 0 (if it is TRUE that A is equal to 0)
THEN it should STOP. IF A is any other value (if it is FALSE that
A = 0) it ignores the THEN STOP instruction and moves to line 20.
Enter this line into the program. RUN the program.
Enter different non-zero values for A to see that if A 1s not zero then
the program continues as before. Enter .000000001 to see that only if
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
calculations are only performed to a certain degree of accuracy.
Enter .0000001 for A, and input B as 2. The computer returns
2.0000001 as the value of S- the number is within the limits of
accuracy.
Now enter 0 for A. The program will stop, just as when we entered
STOP as a direct command. Notice, however, that the message at the
bottom of the screen is different. We get the message 9/15 on the ZX81
(a STOP statement, 15:2 on the Spectrum).* The message is different
because STOP in a program means “f the CONT command is
received, proceed with the next program line', since if it continued with
the same line it would just STOP again! As a direct command,
however, STOP means ‘if the CONT command is received, start with
the same program line', so that the computer does not miss out a
program line.
Now we have some extra control over the program, but it is still not
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
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
it, but the program just goes back into the loop. We need a method of
proceeding out of the loop to end the program, or continuing with more
program lines.
We can do this with a STRING CONDITION. The conditional
operators can also be used to express relations between strings - either
string variables or simple strings.
We insert the following lines:
30 PRINT “RUN PROGRAM AGAIN ?(YES/NO)"
55 INPUT A$
56 IF АЗ - ““ҮЕ58” THEN, GOTO 7
“Оп the Spectrum, the statement after the THEN іп an IF- THEN statement is
treated as the second statement in the program line. This is why we get 15:2, meaning
line 15, statement 2. This is the only instruction used in the main text of this book
(before Unit W2) where the statement number will not be 1 in an error message.
50
When the program gets to line 50 it will print out the message, and
then put the cursor at the bottom of the screen. Because it has been
told that a string input is to come, the cursor has quotes either side:
"[L]". There is no need to type quotes. Whatever characters are
typed in will be stored as A$. The string is entered by pressing
NEWLINE (ENTER) after keying in the characters. Line 56 tells the
computer to check if the characters in A$ are the same as the characters
of the string ‘‘YES’’. If they are it goes to line 7. If they are not the
program will continue to line 60. Notice that any string other than
“YES” will cause the program to continue to line 60.
Exercises
1 Delete line 15 in our program, which we no longer need.
Insert the new lines 50, 55 and 56.
3 RUN the program. Enter “YES” in response to the string input
cursor and see that the program loops back to line 7.
4 Next enter “МО” to see that the program goes to line 60 and
gives the message 0/60 (0 OK, 60:1 on the Spectrum). Run the
program again. This time enter anything other than ‘ҮЕ’ or
“МО”, to see that the program goes by default to line 60 if
anything other than ''YES"' is entered.
5 Experiment with the string input. What happens if you press
NEWLINE (ENTER) without inputting anything? What
happens if you try to key in quotes around the string?
6 LLIST the program on the printer. The development of our
program is complete, and we have run it to see that it works. It
remains to renumber the lines, and this is easier to do if we have
a listing.
E6: Final Edit and Saving
Our program ‘‘ADDER”’ is complete and works. We need, however,
to renumber the lines. The procedure for this is as follows:
1) Using the listing from the printer, renumber the statement lines
in tens at the side of the old number. You can also count the
number of lines in the program on the screen display, and
multiply by ten to get the new highest line number. For our
program, this will be 120.
2) a) List the program on the screen.
b) Usethe ^4 and | cursor control keys to bring the current
line cursor to line 60 (the bottom line of the program).
c) Press EDIT and pull line 60 down to the bottom of the
screen.
d) The new HIGHEST line number is 120.
e) Change 60 to 120.
31
g)
h)
J)
Press NEWLINE (ENTER). Line 60 remains, but it 1s
duplicated by the new line 120.
Delete the old line 60 by entering 60 and pressing
NEWLINE (ENTER).
Change each line number in this way, going from highest to
lowest.
Lines that contain other line numbers must have these
changed to their new numbers. In our program we must
remember to change line 56 to:
90 IF A$=‘‘YES’’ THEN GOTO 30
where 3@ is the new line number corresponding to the old
line 7.
Rename the program ‘‘ADDER2’’, at the same time as you
change the line number of line 5 to 10. This program is
different from the original version, and must be given a
different name both for our reference, and the SAVE and
LOAD operations.
Run the program to check that it still works, and that we
have all the lines, with any GOTO (line number)
statements correctly renumbered.
LIST and LLIST the program.
SAVE “АОПЕК2”.
Write the name of the program on the tape cassette, along
with the tape counter readings.
Put details of the program in your directory.
Stick the listing of the program in the notebook you are
using for documentation.
52
SECTION F: A GAME INTERLUDE
F1: The Program Library
In addition to the many programs and subroutines in the main body of
the text, there are additional applications and games programs in the
Program Library (Appendix VI). Our main objective is to enable you
to write your own programs, and the programs in the text have been
used to illustrate the use of techniques. Some are functional (do
something significant) and some are just illustrative. You don’t have to
key all the programs in the text into the computer, but you must
understand them. However, you should key in all the shorter programs
since it’s important to see how different types of program operate in
practice. Analysing the longer programs is vital, even if you don't key
them in. The use of flowcharts (to come in Lesson G) is helpful for this.
There are also suggestions for programs you should write, to get
practice in writing programs to perform tasks, after units dealing with
specific techniques.
The programs in the library are examples of applications and games
programs, plus a number of subroutines for some of the manipulations
commonly required in programs. You can key these in at any time if
you want to see how the program works, find the program useful, or
want to play the game. Once keyed in you can SAVE them on cassette
and LOAD them back in quickly. None of the programs are very long,
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.
F2: A Game to Key In
You have now spent a lot of time working through the essentials of your
computer system and its BASIC, and you probably have the feeling
53
that thus far you haven't seen anything to persuade you that computers
are particularly exciting machines. Far from being impressed by their
capabilities, you may well be thinking, ‘What’s so good about a
computer if you need to do all this to get it to do something that I could
do in my head when I was six?’ Well, the following program may not
be earth-shattering, but it does in fact reveal a fairly complex set of
computer operations, as well as providing amusement. The program is
called **BUG"' and it enables you to play a game that consists of
dropping bricks from a height to squash the 'spider' (an asterisk)
scurrying along below. If you have a militaristic or SF streak in your
nature, or are an arachnid lover, feel free to change the name to
“BOMBER” or whatever (in line 5). Whether you will enjoy it more
by pretending you're napalming Venusians is your affair. It won't
alter how the program works!
To play the game, however, you first have to key it in. You won't
understand at this point how it works (and won't for a few chapters
yet), so you have to rely on keying it in exactly as listed. Like all the
programs in the text, this one will look somewhat different on the
screen or in a printer listing, since for clarity we have not reproduced
the printer listings exactly, since printouts tend to contain broken
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
before you press NEWLINE (ENTER), and pay special attention to
the punctuation. Notice that there are 2 spaces before the asterisk
(spider) in line 50, and 3 spaces either side of the <=> (brick
dropper/intergalactic space hod) in line 60. If you have any difficulty
finding the right modes and keys for the characters you need, refer to
the list in Section B (ZX81) and Unit W1 (Spectrum). It is very easy to
end up typing a keyword instead of inputting it directly when you are
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 cursor indicating an
error, since the line /ooks the same as the listing, so be warned.
ZX81 Users! Notes
The graphic character in line 160 is an inverse asterisk, (SHIFT B in
Graphics mode) and in line 190 the characters are the SHIFTed
graphic on the T key, the asterisk again, and the НІЕТеа graphic on
the Y key. The comments in square brackets are intended to be helpful,
not to be entered!
Spectrum Users’ Notes
Line 60 has an inverse video asterisk. Го get this, key CAPS SHIFT
and the 4 key to get INV. VIDEO. Then input the asterisk. Use CAPS
SHIFT and the 3 key to get TRUE VIDEO, i.e. normal black on
54
white, back. If you don't return to normal video, the quotes will be in
Inverse, and so will everything after it.
Line 190 has the unshifted G mode graphic on the 6 key, and then
the CAPS SHIFT graphics on the 8 key and the 6 key as the graphics
string.
5 КЕМ "BUG"
10 LET 5-0
20 LET B=10
30 FOR N-1 TO 12
40 LET C23 L
SQ PRINT AT 2O»C-2;" +" [2 Spaces #]
60 PRINT AT (ЗЕ-2;" <=> и [3 5р, =>, 35 Sp]
70 IF INKEYS ="6" THEN GoTo
150
80 LET B=B+(3 AND INKEY$ -"&"
AND B<28)-(3 AND ІМКЕҮФ =
"=" AND B»3)
90 LET C=C+ INT ( ЕМО *2+1)
100 IF C<30 THEN GOTO 50
110 CLS
120 NEXT N
ie ERE np 1g RER "9! — DSCUREDIEM % SRATI
140 STOF
150 FOR F=4 TO 20 ЕТЕР 4
160 FRINT AT Е,Б+1;"Ш" AT [Inverse %1
FsB*1;" "
170 NEXT F
180 IF E+1 <> C THEN GOTO 50 Г <> іс one character]
190 PRINT AT 20»C-1; "EF"; AT
2130-2; "SPLAT"
200 CLS
210 LET S=54+1
220 GOTO 120
When you've got it all keyed in, LIST it to check it through again.
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
place). LLIST it on the printer.
Key RUN then NEWLINE (ENTER) to play. The keys 5 and 8
move you left and right respectively across the top of the screen. ‘They
are chosen for the direction of the arrows printed on them. Key 6 will
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
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), апа
might miss the input otherwise.
When you’ ve played the game a few times, SAVE it on to tape and
catalogue it.
55
|
——————— ph
wrt
- ot 740 | 7% 03:
2. -— ` 1484 4973
^c, з
I E
á ja %
“4: 5
i э pis * Ж | c
° m L
474 f ° I
TL à
é ” ' /
F | L 1%
и.
i í
í А б =,
i ` Wf i r ; 4 ъ
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:
COMPUTERS SOLVE PROBLEMS
To enable them to do this we engage in the two main activities of
programming:
1 PRODUCE THE METHOD FOR SOLVING THE
PROBLEM
2 PRODUCE A WORKING PROGRAM
The method for solving our problem is called an ALGORITHM. An
algorithm 1s like a cookbook recipe, and is written down in steps in a
brief English style we call PSEUDOCODE, and the method by which
we arrive at the recipe is called STRUCTURED PROGRAMMING.
We break the problem up into smaller sub-problems or sub-tasks in
a step by step, modular fashion, starting from the simple initial
statement of the problem and working down to lower levels of greater
complexity (i.e. in a TOP DOWN manner). As we refine our problem
our steps become more like the operations the computer can perform.
Our final description of the lower level of the algorithm will be in terms
of the control and other structures of the language.
To help us produce the algorithm we use STRUCTURE
DIAGRAMS. The simplest of these is a TREE diagram. The
pseudocode description of the algorithm is easily written down from the
descriptions of tasks in the tree diagram. We cannot
key the pseudocode description of the algorithm into the ZX81 or
Spectrum because it will not understand it, and there is no means of
doing it anyway. We have to translate each section of the pseudocode
into its equivalent in the BASIC language, which the computer
understands, to produce a PROGRAM.
For the computer to be able to run the program successfully and
produce the results we require, there has to be a LOGICAL FLOW to
the program. This is often difficult to see from the structure diagram,
and so we use another diagrammatic technique to illustrate the flow of
control through the program, i.e. determine the order in which the
program modules or sub-programs are processed and the order of
coding the specific instuctions within a module.
This technique uses FLOWCHARTS. These are important for
documentation purposes and are in common use. We will describe
them shortly.
59
Producing a working program involves running and DEBUGGING
(correcting errors in) our first effort. We then have to TEST the
program with sample data and finally DOCUMENT it. In this first
section on methodology we shall consider problem solving and coding
the algorithm in BASIC in more detail.
You will see that the first half of the activity we call programming is
LANGUAGE INDEPENDENT. Having produced our problem
solving method - the algorithm — we can code it into any computer
language we wish. We need to know the language thoroughly and how
the fundamental programming structures we have used in the
algorithm - decisions, loops, subroutines, subprograms,
functions — can be implemented in that version of the language which
runs on the computer we are going to use.
In this book we are using the ZX81 or Spectrum computers. The
versions of BASIC are slightly different. All that this means is that
whilst the algorithms to be coded for both machines will be the same,
the final programs may be slightly different.
Our algorithms and their representation in pseudocode and
flowchart form are thus PORTABLE from one machine and language
to another.
Good coding habits are also important. There are good and bad
ways of turning the solution to a problem into a working program.
Style, presentation, ease of understanding, modularity, efficiency are
all important. Throughout our book the emphasis will be on correct
problem solving techniques and good programming practice, while you
gain a thorough knowledge of BASIC.
Here is our first rule of programming:
PROGRAM CORRECTLY FROM THE START
Remember - bad habits die hard!
The material in this Section may initially appear dense and difficult
to follow. Work through the text carefully, and refer back to this
Section as often as you feel necessary, when each of the topics covered
in the following Sections (dealing with the essential groundwork of the
BASIC language) has been introduced. The exercises given in the text
should be used to put into practice both the specific techniques involved
and the general approach to programming presented here.
G2: Problem Analysis
Producing the algorithm, or method of solving the problem, is often the
most difficult part of programming because it involves the most work.
From the start careful planning and organisation are absolutely
essential. The task is simplified when a structured design method is
used, coupled with a diagrammatic representation of the algorithm
60
using a structure diagram or flowchart. The actual coding of the
program in BASIC using the available language instructions is then a
straightforward matter.
To produce the Algorithm we must:
STATE THE PROBLEM
RESEARCH THE PROBLEM
DESIGN THE ALGORITHM
DESCRIBE THE ALGORITHM IN PSEUDOCODE
AND FLOWCHART FORM
= һі = =
A GO м м
Let us now consider each of these steps.
1.1 State the problem fully
1.1.1 STATE THE PROBLEM
1.1.2 UNDERSTAND WHAT IS TO BE DONE
To solve any problem we must know what the problem is and what is to
Бе done. We later work out how to do it. A complete statement of the
problem should include:
(i) What information or data is to be input.
(i) What answers or results are to be output.
(uni) What operations аге to be performed on the data.
At this stage a precise description of (111) may not be available.
EXAMPLES
Problem: Write a program which will print out the sum and
average of five numbers input at the keyboard.
Problem: Using the computer produce a telephone directory to
contain up to fifty entries, which may be updated and
assessed in an enquiry mode.
In the first problem the input data, output data and operations are easy
to see. The second is much more complex and needs more researching
and information.
What we are trying to do in 1.1.1 and 1.1.2 is to initially specify the
problem as exactly as possible. When we analyse the problem further
we may have to go back and ask for more information 1.e. a more
detailed specification.
61
1.2 Research the problem
1.2.1 RESEARCH AND ANALYSE THE PROBLEM TO
SEE HOW THE COMPUTER CAN HANDLE IT
1.2.2 IDENTIFY ALL FORMULAE AND RELATIONS
INVOLVED
1.2.5 IDENTIFY ALL DATA INVOLVED
Here we start to determine how the computer may solve the problem.
We need to find out and write down:
(1) What formulae and expressions are to be used.
(п) What kinds of data are involved - numeric, string, etc.
(ui) What functions are involved.
(iv) What is input and output data.
(v) What is the form of this data.
(vi) How much data there is.
(vii) What processing is to be done and how many times.
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.
Other questions we will ask when we are a little more experienced are:
Have I solved a problem like this before?
Can I use my solution or modify it?
Has anyone else solved it?
Where can I find their algorithm or program?
ALL THE FACTS OBTAINED FROM RESEARCHING
THE PROBLEM SHOULD BE JOTTED DOWN
We can now begin to design the algorithm in a structured manner.
1.3 Design the algorithm using structured methods
1.3.1 BREAK THE PROBLEM DOWN INTO
SUB-PROBLEMS
1.3.2 USE A STRUCTURE OR TREE DIAGRAM TO
HELP
1.3.3 CLASSIFY MODULES OR PART MODULES AS
— INPUT
— PROCESSING
– OUTPUT
USE FUNDAMENTAL CONTROL STRUCTURES
SET UP A DATA TABLE
REFINE THE ALGORITHM UNTIL CODING
INTO BASIC IS AN OBVIOUS EXERCISE
кі = =
92 G3 Go
HD Qv >
Structured programming means designing the algorithm in a top
62
down, modular fashion, with step by step refinement of the solution
starting from the single statement of the problem which we place at the
highest level. We break the problem into sub-problems at successive
lower levels. Each sub-problem or module is one that can be solved
individually. Structure diagrams or tree diagrams are useful as a
representation of this refinement process.
G3: Structure diagrams
These enable us to break down the problem into distinct tasks and sub-
tasks which eventually become simple enough to be coded directly in
BASIC instructions. One form of these diagrams is TREE
DIAGRAMS. The tree diagram has its trunk at the top of the page.
We call this BOX 1 and give it the title: TASK TO BE DONE. We
could have called it ‘problem to be solved’.
For example, make a cup of tea or find the average of five numbers.
We next break down the task into things to do. These are sub-tasks
and each has its own box. For example:
BOX 1.1: First thing to do
BOX 1.2: Second thing to do
Each sub-task is broken down into further sub-tasks: 1.1.1, 1.1.2 etc,
each with their own boxes, the things to do placed in them becoming
progressively more exact and simple.
Breaking down a task into a tree diagram:
first
level
second
level
її 1.2 145
FIRST THING SECOND THING LAST THING
pO TO DO
third
level
ERE И Е. 1.2.1 1.2.2 3.253 4,2,2 L. 39
Sub- Sub- Sub- Sub- Sub- Sub- Sub-
task task task task task task | task
The sort of programs you will start to write in BASIC are sequential,
that is to say things are done one after another, so you need to be able
to indicate that the program should first do one thing, then a second,
then a third . . . and so on. You do this by drawing the boxes which
63
contain the tasks to be done in a straight line across the page next to
each other for example:
The numbers contained within each box identify where the box is
placed on the tree. Take for example:
The first digit shows it comes from the first level 1 ‘What is to be
done’.
The second digit ‘2’ shows it has come from the second level box 1.2
‘Second thing to be done’.
The third digit ‘3’ shows this box is the third sub-task in the
sequence derived from which in turn is derived from . Into
the boxes go brief statements of the actions needing to be performed.
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
‘Get Sum’, e.g. ‘Input first number’, ‘Input second number’, ‘Add
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.
AN EXAMPLE OF TREE DIAGRAM DESIGN
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:
1
Make а Pot
of Tea
This can be broken down into sub-tasks which we put in order across
the page:
1
МаКе а Ров
of Tea
Les
Put Water
in Pot
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.1.2 11.3
Fill the Kettle Plug in Kettle Wait Until
with Water and Turn On Water Boiling
The robot also needs to be told how to fill the kettle so we break this
down as:
1.2.1
Fill the Kettle
with Water
у 9000. Т МИК:
Wait Until
Full
L. L La L
Put the Kettle
Under Tap
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
problem can be broken down.
G4: Classifying Program Modules
Most computer programs involve:
INPUT
PROCESSING
and OUTPUT
activities.
As we are designing our programs and forming modules, it becomes
evident from our pseudocode description of the algorithm which of the
above functions the modules should have. Depending on the problem
and the result of our algorithm design, modules may be separately
65
99
T La
Boil Water Put Tea
the Pot
Loan әш,
Wait Get Tea
Until Pot
Water
Boiling
i E:
Put Water
into the Pot
Lk ЖЕ!
Take
the Pot
to the
Kettle
designated input, processing, and output functions or may have these
functions nested as sub-modules.
Module 2
PROCESSING
Module
OR
Module І
Module 2
PROGRAM
G5: Control Structures
PROCESSING OUTPUT
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
structure together with its flowchart description. When we code the
structures into the BASIC language the instructions used and the order
of statements in the structure may be slightly different according to the
version of BASIC and how ‘structured’ it is (i.e. how easily it
accommodates these control structures). The structures we will study
in BASIC are:
(i) DECISION STRUCTURES
(ii) TRANSFER STRUCTURES
(iii) LOOPS
(iv) SUBROUTINES
(v) NESTED STRUCTURES
(vi) SUB-PROGRAMS
67
DECISION STRUCTURES
Computers make decisions by comparing the value of one variable
against another. For example:
IF А-0 THEN (do something)
IF AS = “YES” THEN (do something)
To make decisions they use relational (or conditional) and logical
operators, like the equals operator above.
Sinclair BASIC uses three decision structures:
Simple decision
Double decision
Multiple decision
As a result of these decisions control may be transferred to another
program module, or local processing within the structure may take
place.
TRANSFER STRUCTURES
These structures involve:
(i) UNCONDITIONAL TRANSFER
which is a direct transfer of control using a GOTO (line number)
statement. Transfer is to another program statement or a module
consisting of a group of statements. GOTO is a very powerful structure
and must be used with care.
(п) CONDITIONAL TRANSFER
in which transfer of control to another segment is made as the result of
a decision: i.e. IF (condition is true) THEN GOTO (line number).
These program structures are discussed further in Section H.
LOOPS
The need for the repetition of simple tasks is one of the fundamental
reasons computers exist. Loop structures are incorporated in most
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
68
There are three common loop structures:
(i) Repeat (the process) forever!
(ii) Repeat (the process) until (a condition is met).
(ui) While (a condition holds) repeat (the process).
Structure (i) is of little use, except that we have to note it and make sure
it does not occur.
In structure (11) the condition is tested after processing.
In structure (iii) the condition is tested before processing.
Sinclair BASIC uses a convenient and powerful set of statements for
controlling repetition by counting called:
FOR - NEXT Statements
SUBROUTINES
Structured programming involves breaking down а complicated
problem into subproblems which can be worked on separately.
SUBROUTINES are such separate independent program modules.
They are distinct from SUBPROGRAMS which have similar
properties in that they are routines or groups of program statements
that are repeated more then once during a program run.
Subroutine modules have a unique address and can have a name
(like a person who lives in a house). Transfer of control to the
subroutine from the MAIN PROGRAM, when the program runs is by
reference to the subroutine address through a special SUBROUTINE
CALL INSTRUCTION. This is the GOSUB (address of subroutine)
statement.
A return of control to the main program to carry on processing from
where it left off is through a special instruction: RETURN.
Subroutine structures in Sinclair BASIC are explained in Section N.
NESTED STRUCTURES
These are program modules or structures that lie entirely embedded
within each other (like a set of Russian dolls).
A simple nested structure 1s
MODULE 1
MODULE 2
MODULE 3
69
In terms of program statements this would look like:
module 1
Inn 222 s,
20
module 2
40
. —
BE ыз шч
module 3
SEL CIIM 2
80
IUD
Ш.
120. — ———
ГІП...
140. 1.
The flow of control is:
START MODULE 1
TRANSFER CONTROL ——— 9» START MODULE 2
TO MODULE 2
TRANSFER CONTROL —————» START MODULE 3
TO MODULE 3
ү? COMPLETE MODULE 3
TRANSFER CONTROL
BACK TO MODULE 2
COMPLETE MODULE 2
TRANSFER CONTROL BACK
Subroutines, subprograms, loops and decisions may be nested in
programs. Nesting is dealt with more fully in Sections H, L and N.
G6: The Data Table
When designing a program it is important that our knowledge of the
data and information pertaining to the problem is complete. All data
will need to be assigned a VARIABLE name, unless it is a numeric
constant used in a formula.
70
The variable type will be either:
NUMERIC - numbers - A, N1, COUNT, A(I,J)
STRING -characters - A$, AS(I,]J)
LOGICAL - numbers or characters - A, A$, NOT B
Numeric variables will be integers, fractions, real and imaginary
numbers.
Strings will be names, characters and symbols.
Logical variables will be the values TRUE or FALSE, 1 or 0 as
appropriate to their use. Logic is dealt with in Section R.
We also require to know whether our data is:
INPUT
OUTPUT
or INTERMEDIATE
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
data is useful for testing and debugging purposes when running the
program or algorithm, using machine or hand traces.
The equations, functions and expressions that will use the variables
will need to be known. When dealing with equations, functions and
expressions the units of the variables or parameters concerned must be
known and should be stated.
The first and simplest data table to construct is a descriptive list of
variables to be used in the program. This is important for
documentation purposes. For example:
VARIABLE DESCRIPTION ITPR
A First number Input
B Second number Input
SUM Sum of A and B Output
A$ User response to Input
‘RUN AGAIN?’
For program design purposes the value ascribed to each variable at
different points through the programs can be added. This forms a data
table that is useful for checking the algorithm before and after coding it
into BASIC, and is also a way of analysing errors in your own
program, and understanding how other programs work.
71
ALGORITHM VARIABLES
MODULE N
N. 1
Loop counters are included in the list of variables. If their values are
used for calculation inside the loop, this should be stated. There are
some examples of this type of data table in the text.
REFINING THE ALGORITHM
The tree diagram should be further broken down and refined until the
final sub-modules correspond to recognisable BASIC statements and
structures. As you get more experienced, you will recognise more
complex structures, and the solution to a problem wil become
apparent at an earlier stage.
G7: Describe the Algorithm
1.4.1 WRITE OUT YOUR METHOD OF SOLVING
THE PROBLEM (THE ALGORITHM) IN STEPS
ІМ А SIMPLE ENGLISH STYLE
(PSEUDOCODE).
1.4.2 DRAW A FLOWCHART SHOWING HOW THE
PROGRAM WILL RUN FROM START TO
FINISH.
1.4.3 TEST THAT THE ALGORITHM WILL WORK
BEFORE CODING IT INTO BASIC.
Having broken our problem down into distinct things to do, or
subproblems, to a stage where we are able to write a BASIC program,
we need to do at least two things before we code. These enable us to
write programs that work and that other users can understand.
The algorithm description in pseudocode or flowchart form is an
important point of the documentation of your programs. This is not
written as part of the program but as a separate document which will
also include a listing of the program. This is important for other
programmers who may want to modify your program or use it as part
of a larger program, and for you yourself if you come back to it after a
72
period of time and cannot remember how you designed it! The
program listing alone is often not enough, if the algorithm is complex,
to show how the program works.
G8: The Pseudocode Description
In the structure or tree diagram - which we draw out in rough on a
piece of paper as we design our solution — each block or module right
down to the lowest level has an English description of the task to be
done inside it. (The very lowest level tasks will be described in
sentences that are very similar to the BASIC program statements
themselves, as you will see in Programming Methods II.)
Our algorithm will be written out, in a step-by-step fashion, and will
include all the descriptions in the boxes. The highest or first level
description (simple box) will be the algorithm and program title. The
second level will be the titles of the program sections. Each of these
major sections will encompass a further group of modules, all of which
will be named in our description of the solution.
The lowest level of our tree diagram will be the specific instuctions
the computer has to perform. These will be translated into the BASIC
language on an almost one to one basis, and will contain the important
and easily recognised language structures, for making decisions,
branching and jumping, and repetition that we have previously
mentioned. (A summary of pseudocode descriptions of some control
structures and their flowcharts with BASIC program equivalents is
given in Section 0, Programming Methods II.) If you imagine turning
the tree diagram on its side and taking away the boxes, the descriptions
that are left constitute a pseudocode description of the algorithm.
As an example, let’s look at the tree diagram and the algorithm
description for the problem of asking our robot to make a pot of tea.
Using our tree diagram we can write down our algorithm for making
a pot of tea as a sequence of instructions (to be coded later into a
computer language). We use the English language as our pseudocode
and our program is written directly from the sub-tasks in the bottom
line of boxes in the tree diagram.
We use the boxes at higher levels in the tree to define distinct
modules. Comments or REMARK statements identify each module
and explain what is being done in each algorithm section:
Remark * * Algorithm for robot to make pot of tea * *
Remark * Boil water - task 1.1*
1,4,4 ЕШ the Кеше with water
1,1-4 Walt until the water is boiling
1.3 Plug in the kettle and turn it on
Remark * End of task 1.1*
Remark* Module - Put tea in the pot — task 1.2 *
Ix Get toe pot
1.2.2 Put 200 tea bags in the pot
73
Remark” Епа of task 1,2%
Remark * Module - Put water in the pot - task 1.3 *
1,2,1 Take pot to kettle
1,2,2 Stir tea with spoon
1.54 Put lid on tea pot
Remark * End of task 1.3 *
Remark * * End of Algorithm - tea is made * *
You can see that the tree diagram shows why each part of your
algorithm is included and why it is in the particular position in which
you have placed it on the tree.
The tree diagram contains information about three things:
(1) The problem broken down into different levels of detail starting
from the general concept of what is to be done down to the
specific activities and instructions which will enable the problem
to be coded.
(2) ‘The order in which instructions must be performed.
(3) The comments which must be included to explain what the
program is doing.
Exercises
1 Our algorithm has the following mistakes in it:
a) Some instructions are wrong. They are spelt incorrectly
and the robot will not be able to recognise them.
b) Some instructions are in the wrong order.
c) Some instructions are missing in the algorithm.
d) Some instructions are missing on the tree diagram.
Find the mistakes!
2 Correct the tree diagram and the algorithm.
3 Expand the tree diagram and the algorithm to a further sub-task
level. For example:
„л Fill the kettle
becomes
1.1.1.1 Put kettle under tap
1.1.1.2 ‘Turn on tap
etc.
4 Draw а tree diagram and write the algorithm in pseudocode for
a robot to set up and switch on your microcomputer system.
G9: Flowcharts
Flowcharts are a second graphical method used in designing programs.
They consist of linked boxes of different shapes. Each shape has a
different use and, as with tree diagrams, each contains a brief
description of what the program should do at a particular point.
It is harder to design programs using flowcharts than with tree
74
diagrams. Their power comes from using them to help make visible
and describe the flow of control in the algorithm and the resulting
program. They are used to help code the program into BASIC
instructions, and later form an important part of the
DOCUMENTATION оға program. Note that flowcharts express the
important control structures used in programming in diagram form.
We give a selection of standard flowchart symbols here. There are
additional ones, but their usage varies. The conventions of use should
be followed if you wish other people to understand your flowcharts. For
your own use, in analysing programs, you may be less exact, but not
less systematic. Flow in a program can be illustrated by a selection of
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
right for yourself, but not if your flowcharts are to be comprehensible to
others.
FLOWCHART SYMBOLS
Flow lines. These connect the program blocks.
Y “pes The arrows show the direction of flow, and are
very important.
This symbol represents any kind of processing
function, that is general Programming
dinis Statements, i.e. ''Purchase Tea'' or
LET A- В + С.
This represents а decision, with а Conditional
— test, e.g. “Is there another shop open” or
<> IF A=3 THEN ... It has a Yes/No branch,
No according to whether the condition is True or
False, which determines the program flow.
This represents either Output in the program
m" to the screen or printer, or Input from the
keyboard, e.g. PRINT “HAVE YOU A
PACKET OF TEA?” or INPUT B.
This represents a named process that is
specified elsewhere, e.g. Subroutine GOSUB
1000. The subroutine would have a separate
flowchart.
75
This represents an exit to or entry from another
part of the flowchart, allowing one part of the
chart to be connected to another part. Used
when another direct line link would be
confusing, or to connect to a separate page.
This represents the Crossing of two Flow
Lines. They are not connected.
This represents the Junction of Flow Lines.
The two lines of flow join.
STOP Terminal Point, e.g. Start, Stop, Pause.
A flowchart does not branch out like a tree diagram. It always
converges to the stop point. It has a direct relationship to the program
it describes. Writing down a flowchart is rather like drawing a diagram
of the program itself. Below are some examples of simple flow
structures, with the program and the flowchart.
FLOWCHART PROGRAM
1. Simple sequences
10 LET X = 5
20 INPUT Y
30 PRINT X,Y
FLOWCHART PROGRAM
2. Decision and program branch
40 IF Y-0 THEN GOTO 70
50 LET X=100
60 GOTO 80
70 LET Х-0
80 PRINT X
90 STOP
Notice that we have omitted a flowchart symbol for line 60. This
GOTO is indicated by the flow lines. The same is true of the GOTO in
the conditional statement of line 40.
10 INPUT X
20 IF X-0 THEN GOTO 50
30 PRINT X
40 GOTO 10
50 REM **END**
PRINT X
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:
INSTRUCTIONS
INPUT
10
NUMBERS
FIND SUM,
AVERAGE
This is like a flowchart of a higher (less specific) level of a tree diagram.
Each section could have a more detailed flowchart drawn up to show
the individual lines of the program, or comments could be added to the
blocks above, relating the program lines to the blocks:
78
INPUT Input loop in lines
10 а Г
40 t
NUMBERS o 69
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
keep them of manageable size. Any complex manipulations should still
be included in full.
EXAMPLES
(1) Here is a flowchart for our robot. We are going to ask it to buy a
packet of tea.
ENTER
SHOP
HAVE
YOU A PACKET
OF TEA
LS
THERE ANOTHER
SHOP
PURCHASE
TEA
79
In the same way as our ‘making a pot of tea’ problem which the robot
has to solve, each of these boxes must be broken down into simpler
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
with the following:
80
(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.
81
INPUT À
INPUT B
LETS = A+B
PRINT S
PRINT ‘‘RUN AGAIN?
(ҮЕ5/МО)”
INPUT A$
IF A$ = ‘‘YES’’ THEN
GOTO 10
STOP
AN EXAMPLE OF STRUCTURED DESIGN
Problem: Find the average of five numbers:
(1) TREE DIAGRAM
Find Average
of 5 numbers
Get each
Set counter number, add Find Print
& sum to Q it to the sum Average Average
Let Sum =
Let Counter
Add 1 Input
to counter number
End of
summing if
counter = 5
Let Let If Counter Let Print
Counter = Sum = = 5 then Average Average
Counter +łŁ Sum+X end summing =Sum/5
(2) FLOWCHART
START
SET
COUNTER
-0
92
ADD
COUNTER
Note that the flowchart and program test whether the counter value is
less than 5, using the < symbol.
(3) PROGRAM
REM “AVERAGE”
REM ** PROGRAM FINDS AVERAGE OF FIVE
NUMBERS INPUT **
REM ** START **
LET SUM = 0
LET COUNTER = @
LET COUNTER = COUNTER + 1
INPUT X
LET SUM = SUM + X
IF COUNTER < 5 THEN GOTO 60
83
100 LET AVERAGE = SUM/5
110 PRINT AVERAGE
120 KEM ** END **
The operand “” means ‘divided by’ and is equivalent to the ‘+’
symbol.
Exercises
1 Design an algorithm (using tree diagram) and write a BASIC
program with a flowchart to find the sum and average of ten
numbers to be input at the keyboard.
2 Produce the tree diagram, flowchart and program which
calculates the area of any rectangle.
3 Design the algorithm, BASIC program and flowchart which
calculates the total volume and weight of three boxes to be
airfreighted from London to New York. Use the following data:
BOX LENGTHCM BREADTHCM HEIGHTCM WEIGHT KG
1 20 4 2 2
2 40 3 6 2.5
3 70 10 15 20
Test that it works!
G10: Testing the Algorithm
It is always best to make sure your method of solving the problem
actually works before coding it into BASIC. This pre-coding check is
known in the programming trade as a DRY RUN or WALK
THROUGH.
Using the DATA TABLE, we check through, module by module,
the values of all the variables, expressions and counters step by step
through the algorithm. This will uncover errors in the logic and
method and will save time when debugging the finished product later
on. Professional programmers always do this as they have to work to
very tight time schedules, and by doing things properly at the start they
save time later on. We would like you to try a few walk throughs on the
simple programs you will be designing at first, just to get the hang of
the idea.
We have now covered the first essential steps in designing a program
and have seen a simple coding process. We have talked about methods
and concepts and introduced some new terminology. After concepts we
go to detail.
The algorithm is ready to be coded into a BASIC program. In doing
this we are going to put into the program the fundamental
programming tools, which are language structure and control
structures. We have to know what these structures or tools are before
we can use them. This requires a look at how Sinclair BASIC, through
small groups of instructions, enables decisions to be taken, branching
94
and jumping to different parts of the program to happen, repetition of
parts of the program to take place and how separate modules called
subroutines and sub-programs can be called into action where
necessary — these are the language structures.
Let’s go and meet them!
85
SECTION H: CONTROL
H1: Control in Programs
The statements which make up a BASIC program are numbered.
BASIC is thus called a LINE NUMBERED LANGUAGE. Control in
all BASIC programs is carried out by reference to these line or
statement numbers. The ZX81 and Spectrum will normally run a
program from the lowest numbered statement through to that with the
highest number unless instructed to do otherwise. This is exactly what
concerns us here, and thus we need to recognise that we can control the
order in which program statements are executed by using four
important instructions in Sinclair BASIC:
- GOTO (for direct transfer)
- IF-T HEN (for decisions and
branching)
- FOR-NEXT (for loops
(repetitions))
- GOSUB-RETURN (for
accessing program modules
called subroutines)
These instructions are used singly or combined together with other
instructions to form groups of program statements called CONTROL
STRUCTURES. There are four principal control structures:
- DECISION AND BRANCH
- LOOPS
- SUBROUTINES
- NESTED STRUCTURES
In this Section we will discover how to take decisions and branch to
other parts of the program. We will study the remaining structures
later in Part Three. The most important property of a computer is that
it can be programmed to make decisions, by using the relational or
conditional operators of BASIC.
H2: Condition Testing
CONDITIONAL OPERATORS
Conditional operators are also called relational operators as
they determine the logical relationship between two
expressions, numeric or string, as:
Equality: =
Inequality: «<>
Greater than: >
Less than: <
Greater than or equal to: >=
Less than or equal to: <
The priority of conditional operators is 5. Priority will be
explained in Section J.
They are executed in order left to right across a statement
unless in brackets.
We often need to use the complements or opposites of these operators
in decision making. The complements are:
Operator Complement
equality = inequality <>
greater than > less than or equal to < =
greater than or equal to > = less than <
The reverse operations are true in each case.
H3: IF-THEN
IF-THEN
Conditional operators are used with:
IF-THEN statements
IF (CONDITION IS TRUE) THEN (PERFORM AN
INSTRUCTION).
For example: 40 IF (А = B) THEN GOTO 10
50 IF C <=6 THEN STOP
60 IF J > K THEN PRINT “J”
The format of the statement is:
IF (CONDITION) THEN (INSTRUCTION)
Any BASIC instructions can be used in this kind of statement,
although a number are unlikely to be useful (e.g. NEW, CLEAR).
In general if the condition in the program line is TRUE then the
instruction following the condition is obeyed. If the condition is not
TRUE (FALSE) then control passes to the next line.
This powerful facility enables us to branch and transfer control to
another line in the program.
IS YES BRANCH
THE CONDITION
(TRUE PATH)
TRUE?
NO BRANCH (FALSE PATH)
GO TO THE NEXT LINE
87
H4: GOTO [Instructions
GOTO
The normal control sequence in a program is via numbered
statements — from the lowest to the highest. GOTO (line
number) switches control to the line number specified:
100 GOTO 20
200 GOTO (B + C)
As a command GOTO 30 executes a program from line 30.
Unlike RUN, with this method variables are not cleared
before execution.
The Spectrum includes a space between GO and TO when printing
this instruction.
Exercises
Key in and run this program which checks that only positive numbers
are input and gives a bad data error message as well as prompting for
the next input. Notice the use of IF-THEN and GOTO. INPUT both
positive and negative numbers.
10 REM*INPUT CHECK*
20 INPUT A
30 IF A»0 THEN PRINT A
40 IF A«-0 THEN PRINT "BAD IN
PUT"
50 PRINT "HAVE YOU ANOTHER NUMB
ER? ANSWER YES OR NO"
60 INPUT AŠ
70 IF А5 ="YES"THEN GOTO 20
88 STOP
90 REM*END INPUT CHECK*
Now try these exercises which demonstrate the power of GOTO:
1 10 PRINT “CENTURY”;
20 GOTO 10
Run this program
2 10 GOTO 80
20 PRINT “COMPUTERS'”';
30 GOTO 10
40 PRINT ‘‘PERSONAL”’;
50 GOTO 20
88
60 PRINT ''SINCLAIR'';
70 GOTO 40
80 GOTO 60
Key it in and sort it out!
This is called ‘spaghetti programming’. Structured programming
techniques have been designed to avoid the excessive use of GOTO
statements.
3 10 INPUT A$
20 PRINT A$;
30 GOTO 10
INPUT some graphics characters
and watch the patterns!
4 Кеуіп and run this example:
10 INPUT A
20 IFA = 1 THEN FORI = 1 TO 10
30 PRINT “CENTURY”
40 IF A=1 THEN NEXT I
50 STOP
Line 10 asks you to input a number.
Line 20 examines if it is equal to 1. IF this condition is TRUE then a
FOR-NEXT loop is set up to print “CENTURY” ten times. If it is not
TRUE then control passes to the next line.
Line 30 “СЕМТГКҮ” is printed once.
Line 40 the condition is tested again. If TRUE the loop continues
and CENTURY is printed again. If not then control passes to line 50.
Line 50 stops program execution.
Can you understand it? If not wait until you have read the section on
LOOPS.
H5: Decision Structures
DOUBLE DECISIONS
The simplest decision involves the evaluation of a LOGICAL
CONDITION - i.e. a condition that may have the value of either
TRUE or FALSE. A result of this evaluation decides which part of a
program is executed next. These parts of the program are called
TRUE TASK and FALSE TASK.
89
The flowchart for the Double Decision STRUCTURE is:
It is called a double decision as there are two alternative modules that
can be performed.
In the flowchart, if the indicated condition 1s true, then the program
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 1s:
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.22 По True task
1.3 Otherwise do False task
We can write this formally in pseudocode as:
90
module - decision
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
example:
10 IF A»0 THEN GOTO 100
20 REM * FALSE TASK *
ЗӨ uus
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 A20 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
processed! Watch out for this.
EXAMPLE: Input two names as strings. The program compares
them and prints them out in alphabetical order:
91
14 REM * ALPHA *
20 INPUT A$
30 INPUT B$
40 IF A$10 THEN STOP
30 GOTO 10
5ТОР
Note the abbreviation of True to Т апа False to F.
MULTIPLE DECISIONS
There is often the need in programs to perform several tasks based on
the result of a set of conditions. To solve these problems we use a
93
multiple decision structure. This kind of structure is especially useful in
breaking up larger tasks into smaller ones.
Multiple decisions are most conveniently handled by multiple logical
operations. This is covered in Section R. We will consider the
conventional way of handling them.
As an example of multiple decisions consider a food vending
machine. You put a coin in and press the respective button of the
article you wish to be delivered to you. Another example would be a set
of arithmetic testing programs, with questions in each. The computer
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:
START
Where C1, C2, C3 are the conditions and Р1, Р2, P3 are the True
tasks.
EXAMPLE: Input any of three letters A, B, C and print out a
corresponding reply.
= FRINT "ENTER AoE üR C"
10 INFUT ñ$
20 IF АФ-"А" THEN GOTO 60
94
30 IF А%Ф-"Е" THEN GOTO ЕО
40 IF AS="C" THEN GOTO 100
20 STOP
60 PRINT “YOU INFUT A"
70 STOP
S0 FRINT “YOU INPUT Е"
90 STOP
100 PRINT “YOU INPUT C"
110 STOF
The Pseudocode description of this structure is:
case
if Cl
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
PROGRAMMING WITH GOTO
When programming in BASIC take great care in how you use the
GOTO statement. It takes two main forms. Used on its own it 1s called
an unconditional GOTO and when used with IF-T'HEN 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 GOTOSs!
Ideally, unconditional GOTO statements should only be used to
skip over code and not to repeat code sections (i.e. they should only be
used to transfer control forward in a program).
Do not put an unconditional GOTO inside a loop or subroutine to
jump out of it. Do not jump inside a loop or subroutine, because you'll
find that jumping in and out of loops can cause unpredictable results.
Do not jump to another GOTO. For example:
100 GOTO 200
200 GOTO 300
95
or else
100 GOTO 100 !
Exercises
1
2
H6: L
Write a program to input integer numbers and stop if zero is
input.
Write a program to input integers and count the number of
times zero 15 input.
Write a program to input integers and calculate the percentage
of zeros input.
Write a program which prints out the result of dividing any two
numbers’ input and gives a “Һай data - try again” message if
any of the input values is zero.
Write a program which will print out on request a lunch menu
for the different days of the week.
ogical Operators: AND/OR
We will only introduce you to simple logical operations here. Logic is
dealt with fully in Section R.
Use
of the AND and OR statements enables us to combine
conditional statements in powerful ways to make more complex
decisio
ns in programs.
AND
AND combines relations so that the expression:
e.g.
(condition 1) AND (condition 2)
(A = B) AND (В>1)
is TRUE when BOTH conditions are TRUE.
It is FALSE when one or both conditions are FALSE.
OR
e.g.
OR
combines relations so that the expression:
(condition 1) OR (condition 2)
(A = B) OR (B<>1)
is TRUE when EITHER condition is TRUE.
It is FALSE when both conditions are FALSE.
The expressions formed by the use of AND and OR are used with
LE ua d.
HEN statements. For example:
20 IF Х>1 AND X«10 THEN PRINT
'* BETWEEN 1 AND 10”
96
50 IFX<>2 AND X<>3 THEN PRINT
< A МОТ EQUAL TO 2 ОҚ”
40 IF A=B OR B=C THEN LET F=F+1
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
condition would be true, but the second false. The whole expression
would then be false.
Notice the danger with the second example, in that we say in English
‘not equal to 2 or 3’, but we must key in an expression using AND. It is
clear once you realise that two conditions are to be tested — ‘not equal
to 2 and not equal to 3’. If, for example, X were 3 when this line in the
program was reached, then the second condition would be false in this
expression, and the whole expression would also be false.
The third example would be true if ezther A was equal to B or if B was
equal to C. It is also true if both these conditions are true.
We can also combine more than two conditions:
20 IF A=BANDB=CANDC = 20 THEN STOP
will stop if all three conditions are true. If one or more is false then the
whole expression is false.
Similarly:
20IFB-20R B-3ORB-4THEN LET B- 1
will make B - 1 if B is equal to 2 or 3 or 4.
It is also possible to use combinations of AND and OR:
30 IF (A = BAND B>2) ОК (A = 2 AND B = 3) THEN GOTO 60
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
control to line 60 if either expression in brackets is true.
To summarise: where T1, T2 etc. are true conditional expressions
and F1, F2 etc. are false conditional expressions:
(T1) AND (T2) TRUE
(T1) AND (F2) FALSE
(F1) AND (T2) FALSE
(F1) AND (F2) FALSE
(T1) OR (T2) TRUE
(F1) OR (T2) TRUE
(T1) OR (F2) TRUE
(F1) OR (F2) FALSE
Each condition may also be another AND or OR expression.
Exercises
Work out what will be printed by these programs, then key in and run
them to check. The operator ‘‘/’’ means ‘‘divided Бу” (+) and “%”
means ''multiplied Бу” (*).
97
Make sure you have got the programs correct before you run
them. Work out both sides of each expression using a relational
Then, giving each expression a T or F value, work
out the bracketed AND/OR expressions. This gives you a T or F
value for the whole bracket. Then work out whether the whole
operator first.
LET A=2
LET B=3
LET С-10
LET X=15
IF X/B=A AND C/A=5 THEN PRINT
"LINE 50 TRUE"
IF X/B-A OR C/A=5 THEN PRINT
"LINE 60 TRUE"
IF X/B=C/2 AND X>=15 THEN PRINT
"LINE 70 TRUE"
LET A-20
LET В-150
LET X=7.5
LET Y-2
LET 5-В/20
IF S=X AND X*A-B AND Y-2 THEN
PRINT "LINE 60 TRUE"
IF X-B OR X«20 OR X>2 THEN
PRINT "LINE 70 TRUE"
IF (X=7.5 OR Ү-10) AND (A/Y-1
@ AND В-150) THEN PRINT "LINE
80 TRUE"
expression will be true or false.
Write some similar programs for yourself to experiment with all
the relational
operators used with AND and OR.
98
SECTION I: PRINTING
I1: PRINT LPRINT
PRINT
The PRINT statement is used to output information by
displaying it on the screen.
It can take many forms. For example:
10 PRINT A prints out the value of
numeric variable A
20 PRINT B$ prints out string variable B$
30 PRINT “YOUR NAME?" prints out whatever is
included within the quotes
(inverted commas)
40 PRINT (B**2 — 4*A*C) prints out the calculated
value of the expression
50 PRINT leaves a blank line
LPRINT
The LPRINT statement is used to output information by
printing it out on the printer.
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.
The screen size for printing is 22 PRINT lines down the
screen, and each line is 32 columns (character spaces) wide.
The actual screen size is 24 lines by 32 columns, but the
bottom two lines are reserved for commands and operating
messages. The lines are numbered @ to 21 down the screen
and the columns 0 to 31 across.
The PRINT statements shown above each commence at the left-hand
side of the screen, and each PRINT statement moves the printing
position to the start of the next line after it prints whatever it was told
to. Lines of greater than 32 characters will go on to the next line
automatically.
To clear the screen of printing we use the CLS (Clear Screen)
statement.
99
CLS
CLS erases all printing on the screen, and sets the new print
position at the start of the top line of the screen.
I2: Spacing Items on the Screen
Е
А semicolon (;) between two items causes the printing of the
second item immediately after the first.
For example:
10 PRINT A;B$
20 PRINT “АУЕКАСЕ”;С
Try the following program:
10 LET A=6.89
20 LET B=87.6
30 PRINT A;B
40 PRINT ''AVERAGE"'';(A + B)/2
The display is:
6.8987.6
АУЕКАСЕ47.245
This does not give а very satisfactory display since values run into each
other. One simple way to overcome this is shown below.
10 LET A= 6.89
20 LET B=87.6
30 PRINT A;" "В
40 PRINT “AVERAGE ”;(А+В)/2
The display now becomes:
6.89 87.6
AVERAGE 47.245
ci
A comma (,) between two items causes the print position to be
shifted on (at least one place) to either column 16 or to the
next line column 0.
For example:
10 PRINT A,B
20 PRINT A$,B$
30 PRINT “АУЕКАСЕ”,С
Try the following program:
10 LET A= 7.65
20 LET B= 8.67
30 PRINT “AVERAGE” (А + B)/2
100
40 PRINT
50 PRINT ‘‘NUMBER!1’’,‘‘NUMBER2’’,
“АУЕКАСЕ”
60 PRINT A,B,(A + B)/2
The display is:
AVERAGE 8.16
МІ/МВЕК1 NUMBER2
AVERAGE
7.65 8.67
8.16
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.
It is important to remember the screen size when deciding the
form of your output. For your output the effective screen is 22
lines each 32 columns wide.
TAB
TAB C; moves the print position to column C. If this would
involve back-spacing it moves on to the next line.
The following program (with printout) indicates how the TAB function
can be used to improve the presentation of results.
10 LET А$ = “А.В.ЈОМЕЅ”
20 LET B= 65
30 PRINT “NAME”;TAB 6;A$; TAB 19:“АСЕ”:
TAB 23;B;TAB 27; “YEARS”
NAME A.B.JONES AGE 65 YEARS
Note the semi-colons between TABs and print items. It is important to
remember that each line has 32 columns, numbered 0 to 31.
The next program shows a simple way of tabulating results.
10 PRINT “МО.”;ТАВ 4;“5ОСАКЕ”;ТАВ 12;
“СІУВЕ”;ТАВ 20;*RECIP"
20 INPUT N
30 PRINT N;TAB 4;N*N;TAB 12;N*N*N;
TAB 20;1/N
40 GOTO 20
101
NO. SOUARE CUBE RECIP
1 1 1 1
2 4 8 0.5
3 9 9/ 033333333
4 16 64 0.25
5 25 125 0.2
6 36 216 @.16666667
7 49 242 0.14285714
8 64 512 0.125
9 81 729 0.11111111
10 100 1000 0.1
It is important to remember that numbers are output with up to 8
figures and allow the appropriate space. An alternative is to decide how
many figures you want and use the INT function (see Section J).
I3: PRINT AT
AT L, C moves the print position to line L and column C.
For example:
10 PRINT AT 10,12“ CENTRE"
will cause the string specified to be printed starting at line 10, column
12, i.e. roughly in the centre of the screen - since L goes from 0 to 21,
counting down the screen, and C goes from 0 to 31, counting left to
right.
EXAMPLE
The program below sets up a symmetrical pattern using the character
of your choice. Note the use of the command CLS to clear the screen of
your input.
10 PRINT AT 5,4;"WHICH CHARACTER?"
20 INPUT AŠ
30 CLS
40 LET L=INT (RND*10)+1
50 LET C=INT (RND*15)+1
60 PRINT AT 11%,,164С;А65
70 PRINT АТ 11-L,16-C;A$
80 PRINT AT 114L,16-C;A$
90 PRINT AT 11-L,16+C;A$
100 GOTO 20
Try adjusting the parameters in lines 60-100.
The important feature to remember is:
Number of character cells is 32 horizontally by 22 vertically,
i.e. 32 x 22 altogether.
The TAB function uses C = @ to 31 only.
The AT function uses L = 0 to 21
and C = 0 to 31.
You should have noticed that the PRINT commands reinforce each
other, and provide alternative ways of achieving the aim of placing
characters, character strings or numbers at the desired positions on the
22 line, 32 column screen display.
For example, these three programs:
19 LET X = 3
20 PRINT X,,;,
30 PRINT X*X
10 LET X = 3
20 PRINT X
30 PRINT
40 PRINT X*X
10 LET X= 3
20 PRINT X,TAB 32;" "TAB 32;X*X
would give the same printout on screen. The number of keystrokes
(count them) is what determines which statement usage is efficient in
any instance. You will soon come to recognise which to use if you
experiment.
PRINT AT instructions will overprint anything already printed at
the position specified. We can use this to replace on the screen one set
of data, or one string, by another.
10 INPUT X
20 PRINT AT 0,0;X
30 GOTO 10
overprints one X by the next X each time. If we input 1,2,3...10 it
works fine. But if we input 10,9,8...1 we get:
etc.
Similarly,
ZU ЕТТІ”
40 PRINT AT 10, 10; “SINCLAIR”
works, but not if we swap the two strings around - we end up with
ZX81LAIR, and we have the same problem with numbers, which can
be between one and eight digits long.
We can blank out something on the screen by overprinting an empty
string. For the simple problems above, the addition of appropriate
103
strings will work; we add 4 spaces after “27Х81”, so that line 10
becomes:
10 PRINT AT 10,10; “ZX81 E
and for numbers, we can use:
20 PRINT AT 0,0;X; *“ id (7 spaces)
Using LPRINT also requires care.
For the LPRINT instruction, TAB works exactly as PRINT
TAB.
LPRINT AT L,C is converted to LPRINT TAB C, and the
line number is ignored.
This is because the printer cannot go back to a previous line. Try this
program. Input 1,2,3,4,5.
10 INPUT X
20 LPRINT AT X,X;X
30 GOTO 10
will print 12345, as if line 20 had read LPRINT TAB X;X.
For any programmed screen format that 1s not a simple sequence of
print lines, it is better to use COPY to produce output on the printer,
once all the data is on the screen.
COPY prints the entire current screen display on the printer.
If used as direct command, we can COPY less than a whole screen by
pressing BREAK before completion, but if used in a program, the
whole screen will be copied.
14: The Graphics Characters оп the ZX81*
The ZX81 character set includes a set of graphics characters, and you
were told how to access them in Section B. To recap:
Graphics characters are accessed by using |Graphics| to get
the cursor. Repeat to return to cursor. Unshifted keys
then produce inverse video characters. (e.g. key Q gives |.)
Shifted keys produce graphics cells, if shown on the keys: e.g.
SHIFT R gives "W .If no graphics cell is shown, result is
inverse video form of normal shifted character (e.g. SHIFT U
gives В ).
The inverse video characters and graphics cells can be used for
enhancing displays and drawing bar charts, diagrams and pictures.
They are manipulated as strings, by putting quotes round them, e.g.
PRINT “ ER or PRINT “ B”.
* The Spectrum offers more extensive graphics facilities than the ZX81, and Spectrum
owners should refer to Unit W3 for details. The Spectrum has the solid graphics
characters of the ZX81, but not the shaded characters, on keys 1 to 8 in graphics mode.
Read through this section bearing this in mind.
104
Put your computer in graphics mode and run through the keyboard,
noting the unshifted and shifted versions of each key. Note that
RUBOUT (DELETE) works with the cursor, but the cursor
control keys do not, and that the cursor must be on screen for them
to work.
By the time you fill one line and move on to the next, you will see
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
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,
you cannot see the Join. If they do not, the Join is visible as a chequered
pattern. To check the characters across the screen, use the bottom lines
of the screen directly. To check the vertical Joins, enter this program:
10 INPUT A$
20 PRINT A$
30 GOTO 10
Change the cursor to [G], then input the graphics character. You
have to then press NEWLINE (ENTER) twice; the first time to change
to [L], the second to input the character.
We can use the graphics characters to draw (crude!) pictures,
enhance printout on the screen — by printing prompts in inverse video
for example —or putting titles inside surrounds, and use them in
diagrams or moving graphics. You'll have to wait a few more chapters
before we can do anything interesting, but here are a few things to try:
Here’s a program to put a border round a word in inverse video.
Notice we store the graphics in string variables. This gives us better
manipulative power than if we just used literal strings. On the ZX81
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
Spectrum, the relevant keys are ‘4’, ‘3’ and ‘7’. You can work the
other lines out for yourself.
A
s
ie
zu
зә
46 i
се
e
Notice the combined PRINT AT statements in line 60.
The production of inverse characters on the Spectrum (white
characters on a black background, unless colour is being used) can be
done in different ways. You can use CAPS SHIFT and the 4 key to put
an INVerse VIDEO control character before a letter or other
character, but this will make a// characters thereafter into their inverse
forms unless CAPS SHIFT and 3 is used to restore NORMAL
VIDEO. The alternative is to use INVERSE as part of a program
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
to print HELLO in inverse video we key in:
10 PRINT INVERSE 1; "HELLO"'
This will appear normally in the program listing, but in inverse when
the instruction is carried out.
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 LET Y=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; “аша ` _
20 PRINT AT 1,8; === =
30 PRINT AT 2,8; “ "EE"
(it’s supposed to be а car).
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
1 Write a program that puts:
ADDRESS:
on the screen, then prompts for inputs on line 20 (INPUT
NAME etc), and prints the responses on the screen.
Each prompt should overprint the previous one. Allow four
separate lines for the address. Blank out the last prompt, then
have the screen copied on the printer.
106
Add a routine to LPRINT name, address and age, without the
borders or titles, on the printer after deleting the COPY
Instruction.
Input names, ages and occupations of three friends and arrange
them to be tabulated in a suitable form.
Experiment with ways to make the car move across the screen.
107
SECTION J: ARITHMETIC AND FUNCTIONS
Ji: Arithmetic Operations
A prime function of the computer is to evaluate formulae and
expressions similar to those used in standard mathematical calculation.
Algebraic EXPRESSIONS are written in BASIC using the
following OPERATORS with a set of variables or numbers as the
OPERANDS.
ARITHMETIC OPERATOR EXAMPLE
SYMBOL NAME PRIORITY BASIC MATHS
in exponentiation 10 А**3 А?
(raising to a power)
[^1] (on the Spectrum) А13 A?
- negation 9 -А -А
и multiplication 8 A*B AxB (a.b)
/ division 8 A/B A+B e
+ addition 6 A+B A+B
_ subtraction 6 А-В А-В
Note that negation operates on one operand ~ a unary operation ( i.e.
makes a variable negative, e.g. — A) and that the subtraction operator
uses two operands, e.g. А-В, a binary operation.
J2: Priority
1 All arithmetic, conditional and logical operations are assigned a
priority number from 10 to 1. High priority is 10, low priority is
1. The priority numbers for the arithmetic operators are as
shown in the previous Unit.
2 The priority of an operation determines the order in which it is
evaluated in a complex statement in which more than one
operation is to be performed. High priority operations are
performed earlier.
3 Brackets (parentheses) are used in BASIC algebraic expressions.
Brackets clarify which expressions constitute separate values to
be operated on. Expressions inside brackets are evaluated first
before the quantity is used in further computation. With multiple
(nested) brackets the evaluation proceeds from the innermost
bracketed expression to the outermost.
4 For operations of equal priority in the same statement,
evaluation is from Left to Right.
Brackets can often be omitted when the sequence of evaluation is
108
understood, but there is no harm in using them to ensure correct
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
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),
LET B = 3 (NEWLINE/ENTER), etc.) then variable expressions may
be evaluated.
Using this facility you should experiment with a variety of
expressions until you feel confident that you have understood the way
in which expressions are evaluated, and the way you have to formulate
an expression in BASIC to ensure it returns the desired result.
EXAMPLES
1 Evaluation ofa+b-c
In BASIC: A+B-C
Operators have equal priority;
(1) Left to Right A+B
(2) L-*EK (A+B)-C
2 Evaluation of ab , (axb) +c
In BASIC A*B/C
* has same priority as /
H LR A*B
(2) L*R (A*B)/C
3 Evaluation of a.(2) ‚ах (b+c)
In BASIC A*(B/C)
(1) Brackets first (B/C)
(2 Multiplication — A*(B/C)
But notice we could write the expression without brackets in
BASIC as B/C*A
This is evaluated:
H LR (B/C)
(2) L= Е (B/C)*A
which gives the correct result.
4 Evaluation of (b° - 6c)*+5
In ZX81 BASIC notation: (B**2 = GG )**24 5
(1) Inside bracket;
exponentiation B**2
(2) Inside bracket;
multiplication 6*C
(3) Inside bracket;
subtraction (B**2) - (6*C)
109
(4)
(5)
Exponentiation ((B**2) - (6*C))**2
Addition (((B**2) – (6*C))**2) +5
In Spectrum BASIC notation: (B 2 - 6*C )#2+5
(1)
(2)
(3)
(4)
(9)
Inside bracket;
exponentiation Bez
Inside bracket; 6*C
multiplication
Inside bracket;
subtraction (В%2)-(6“С)
Exponentiation (В t 2). – (6*C))4 2
Addition (((B f 2) – (6*С)) # 2) +5
2
Computer evaluation of a.b- © + (e - f)
d g
In ZX81 BASIC notation: A*B - C**3/D +(E-F)/G
(1) brackets E-
(2) exponentiation Er
(3) multiplication/
division L — R А“В C'"3/D (Е-ЕУС
(4) addition/
subtraction L > R (A*B) - (C**3/D) + (Е – Е)/С
In Spectrum BASIC notation: А*В - С \ 3/0 +(E-F)/G
(1) brackets Е-Е
(2) exponentiation OTs
(3) multiplication/
division L > R A'B Ct3/D (E-FyG
(4) addition/
subtraction L > R (A*B) - (C ^3/D) + (E - FG
Evaluation of —70 +2х ^ x3-3x7
In ZX81 BASIC notation: 40 +2 "4702 "3.8."
Priority 10 4#**2
16
Priority 9 - 70
Negation
Priority 8 2°. te *23 377
LR 96 1
Priority 6 - 70 + 96 — Д1
Result 5
In Spectrum BASIC -70 +2*442*3-3%*7
Priority 10 412
16
110
Priority 9 - 70
Negation
Priority 8 2> 15 "TET
L — R 96 21
Priority 6 - 70 + 96 - 21
Result 9
Exercises
1 Write the order in which the following BASIC expression 1s
evaluated:
— А + ((B**3/C) - (A**2/D))*(E + Е)/С (ZX81)
— А + ((B 13/C)- (A ^ 2/D))*(E+ F/G (Spectrum)
2 Write down the BASIC expressions for:
(i) (и? + 2аѕ)^
(ii) ut + Тағ
жа b + ac)"
(111) 2a
(iv) (xy
Work out the order in which each of the expressions is
evaluated. Test your results on the computer.
J3: Number
À positive or negative decimal number whose magnitude is
between an approximate minimum of:
t3x10 ?
and an approximate maximum of:
+2 x 10”
Zero is included in this range.
The smallest number the computer can handle is
2.9387359 x 10 `”
The largest is:
1.7014118 x 10°
The computer stores and calculates numbers internally to an
accuracy of nine or ten digits, but prints out the results of
calculations to eight significant figures only, rounding where
necessary.
J4: The E Notation
The E or EXPONENT or scientific notation is the notation
computers use for input and output of numbers having a large
111
number of decimal digits. E should be taken to read: ‘times
ten to the power of’. For example:
1.73 E5
is
1.73 times 10 to the power of 5
1.73%10%%5 (1.73*10 ^ 5 in Spectrum notation)
= 173000.
Similarly:
3.8E-7
is
3.8 times 10 to the power of — 7
= 3.8*10** 7 (3.8*10 41 — 7 in Spectrum notation)
= .00000038.
The computer will accept any number keyed-in in this form
and will print out numbers in this notation when their values
are outside a certain range.
For large positive and negative numbers the E notation is
automatically used by the computer for numbers
> = 10?
Numbers up to this figure are first rounded to 8 significant figures and
trailing zeros are added until 107 is reached.
Key in and run this program:
10 LET A = 9.9999993E12
20 PRINT A
30 ІЕТА =А + 1Е5
40 СОТО 20
Change line 20 to read:
| 20 LPRINT TAB 10;A
to get a listing of the result on the printer.
For small positive and negative numbers the E notation is
automatically used for numbers:
<= 10^?
To see this in action, key in and run the program below:
10 LET A-1.000001E — 5
20 PRINT A
30 LETA-A -(1E- 12)
40 GOTO 20
Change line 20 to:
20 LPRINT TAB 10;A
if you want a printer listing of the changeover.
Exercises
1 Key in and run the following simple program, which illustrates
how numbers are printed, the E notation and the largest number
which may be obtained.
112
10 LETA=1
20 LET A=A*10
30 PRINT A
40 GOTO 20
With the ZX81 press and when
the screen becomes full, and the message 5/30 appears on the
bottom of the screen to indicate no more room on the screen.
The Spectrum will display the ‘scroll?’ prompt.
Notice the change to the E notation. Note that the program
finally stops itself on the ZX81 with the error message ‘6/20’,
which indicates an arithmetic overflow (error code 6) as a result
of line 20, i.e. the number is too large for the computer to
handle. The Spectrum's response is more precise; the error code
in this instance will read: ‘6 Number too big, 20:1’.
Change line 10 of the program to each of the following and run
the program each time.
a) 10 LET A=1.00000000
b) 10 LET A=1.1111111
c) 10 LET A=1.7
d) 10 LET A=1.7014118
e) 10 LET A =1.71
What conclusion do you draw?
To show that negative numbers behave in the same way, change
line 1@ to the following and run the program.
a) 10 LET A= -1
b 10 LET A= -1.7
c) 10 LET A= -1.7014118
d) 10 LET A= -1.71
To show how small numbers are handled by your computer a
similar program divides a number (A) by increasing powers of
10.
Key in the program and run it.
10 LET A=1
20 LET A=A/10
30 PRINT A
40 GOTO 20
Note the change of notation.
Notice that after 1E – 38 the computer prints zeros
indefinitely, i.e. it has reached the smallest number it can
register.
Change line 10 to
а) 10 LETA=3
Ы) 10 ІЕТА = 2.9
апа ге-гип the program each time.
Notice that 2.9387359 E — 39 is the smallest number before
zero.
Write this number out in full.
Can you think of any applications for very large and very
small numbers?
113
6 Change the values of À in the program to negative values and
confirm that small negative numbers behave in the same way.
PROGRAMS TO SAVE IN YOUR TAPE LIBRARY
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.
10 REM "LARGE NUMBERS"
20 REM** PROGRAM MULTIPLIES +
AND - NUMBERS INPUT FROM
THE KEYBOARD BY POWERS O
F 10 **
30 REM **KEY IN VALUES FOR A O
P +-1,,4-1.1111111,4-1..7,. +
-1.7014118,%- 1.71.**
40 INPUT A
50 LET N=0
60 PRINT А%(10%%у)
70 LPRINT TAB 10;A*(10**N)
80 LET N=N+1
90 GOTO 60
For the Spectrum, replace ** by in lines 60 and 70.
10 REM "SMALL NUMBERS"
28 REM**PROGRAM SHOWS PRINTING
OF SMALL NUMBERS**
30 REM**INPUT VALUES OF A AS +
-1, +-2.9,+-3.**
40 INPUT A
50 LET N=0
60 PRINT A*(10**N)
70 LPRINT TAB 10;A*(lQ**N)
80 LET М-М-1
99 GOTO 60
J5: Rounding
ROUNDING UP
The computer will print out computed values to an accuracy
of 8 significant figures, ignoring leading zeros.
Digits after the 8th significant one will be rounded up. For
example, if we key in (as a direct command, followed by
NEWLINE/ENTER):
11%
PRINT 0.111111111 + 0.888888888
the answer on the screen is 1.Try
PRINT 0.0000111111
showing 10 digits can be held exactly.
Adding a one on the end forces the use of the E notation.
ROUNDING DOWN
The INT function returns the nearest integer of the
expression X, which is < = X, i.e. it rounds down.
e.g. INT 3.9= 3
INT -2.8- -3
INT (4 -8.7 +0.8)= - 4
Try printing these functions. Notice that for negative
numbers - 6 is less than - 5, and so on. To round to the
nearest integer add 0.5 to the number first:
e.g. INT (3.9+0.5) = 4
INT (2.4 + 0.5) 2
ІМТ(-1.7-0.5)- -2
ІМТ(-2.3-0.5)- -2
Notice this assumes that 0.5 rounds (о 1.
INT (1.5-0.5) = 2
INT (-1.5+0.5)= -1
Notice we don’t have to enter the zero before the decimal point on the
computer (though it doesn’t matter if we do), it’s in that form here for
clarity.
J6: How Numbers are Handled
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
computer in Decimal Notation. This is rather more convenient than
using Binary. Conversion from Decimal to Binary and vice versa is
thus necessary and occurs inside the computer.
One BYTE is equivalent to a single character of the computer’s
character set. A byte represents a number between 0 апа 255
(decimal). ‘This is why the character codes are in this range (see Section
P). A group of 8 zeros and ones can have 2° ( = 256) different states.
A digit or number is represented by one or several bytes according to
its context in the computer.
115
A character input to the computer or output to the screen or printer
is held in one byte. Program line numbers, which are whole numbers 1
to 9999, are held in two bytes.
Numbers are held in a form which occupies five bytes. The point to
be noted here is that conversion from decimal to binary and back is
involved in the operation of the computer, and this conversion is not
always exact. This must be allowed for in certain circumstances,
especially where the computer is asked to check whether two numbers
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
utilised, and the value of one number arrived at by calculation, the
equivalence check should be replaced by assessing the difference. A
statement such as:
IF ABS(A - В) < 1E-4 THEN...
which checks that the difference between the numbers is less than
.0001, сап be used instead of IF = B THEN ...., if either A or B has
been calculated.
The forms in which numbers are held in the computer are
considered in detail in Section U — the Computer Memory.
J7: Function
We define a FUNCTION as
Y = F(X)
‘Y equals some function of X, F(X)’
A function is the mathematical relationship between two
variables X and Y such that for each value of X there is a
unique value of Y.
Y takes the function value and is the DEPENDENT VARIABLE.
X is the ARGUMENT - the INDEPENDENT VARIABLE.
F is the function NAME, e.g. square root, sine, natural logarithm.
In a program statement we write, for example:
100 LET Y SOR(X)
The argument X can be a single variable, a number or an expression.
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
before the function is applied to it (so that SOR 9 + 7 gives 10, whilst
SOR (9 + 7) gives 4). For example:
100 LET Y = SOR 9
100 LET Y = SOR(B**2—4*A*C) (B42 on the Spectrum)
We see that a function is a mathematical operation which gives a
number. It is treated in BASIC as a numeric expression, with priority
I.
116
The standard mathematical and trigonometric functions are
important timesavers for programmers. They are the same as the
function keys on scientific calculators. Other functions (utility
functions) control or monitor the handling of data by BASIC rather
than perform mathematics.
If the functions were not available in BASIC we would need to write
separate programs to undertake their tasks every time we had need of
them!
J8: List of Functions used in Sinclair BASIC
In this list of functions X is the argument. X is a variable, a number or
an expression. If an expression, X must be in brackets. Each of the
individual functions will be discussed in more detail later in this
section.
1. Standard Mathematical Functions:
ABS (X) - gives the absolute value of X
EXP (X) - gives e", 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. X)
SOR (X) -value of V X or X* (X positive)
PI -3.14159265 i.e. value of n, PI, which is how it
prints on screen
SGN (X) -gives sign of X, i.e. whether X is + ve, – ve or
Zero.
2. Trigonometric Functions
SIN (Х) - 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)
ACS (X) -angle in radians whose cosine is X
-arccosine Х( - 1 «- X < = 1)
ASN (X) -angle in radians whose sine 18 X
-arcsine X ( -1 <= X < = 1)
АТМ (X) -angle in radians whose tangent is X
- arctangent X
3. Special Mathematical Functions
RND A random number generating function; gives the
next pseudo random number N from a fixed series
of random numbers (0 < = N < 1).
RAND ( RAND 0) starts the sequence of random
numbers in an unknown position.
RAND N (ü0 < = N < = 65535) makes RND always return to
the same value, if N is the same.
117
4. Character and String Functions
CHR$(X) 0<-Х <=255 returns the single character
whose code is X.
CODE A$ When applied to the string A$, it returns the
code of the first character in the string or 0 if the
string is empty (null string).
LEN A$ Returns the number of characters in the string.
VAL A$ Turns a string in number representation into
the number for calculation (e.g. A$ = “12.4”,
VAL А$ = 12.4).
STR$ М Turns the number N into the string “N”.
5. Printing Functions used in the form PRINT F(X)
TAB (X) Places the print position in column X. If X>32
then column number is the remainder when X is
divided by 32. If it involves back spacing, goes
on to next line. Rounds X to nearest integer.
AT (X), (Y) Starts printing at line X, column Y
бжделлбе21. = Y <= 31
Rounds X and Y to nearest integer.
6. Special Functions
INKEY$ No argument. Reads keyboard and senses what
key is being pressed at that time. Returns key
being pressed as a string, e.g. “А” or ‘‘8’’. If no
key is pressed the null string is returned.
PEEK X 0 < = X < = 65535 Returns the value of the byte
at address X in RAM or ROM memory.
USR N Returns the contents of a pair of CPU registers
after running a machine code program from
address N.
N.B. For the Spectrum’s additional functions, see Section W. The
above functions, common to both the ZX81 and the Spectrum, are the
ones used in the main body of the text.
J9: The Function Characters
Each of the functions in Sinclair BASIC is represented on the
keyboard as a single character word.
You don’t have to type the function name letter by letter (if
you try to it won’t work), just press the particular function
key.
Each function character has a special character code and is
part of the computer’s character set. Each of the Function
118
characters on the ZX81 is situated at the same position on
each key, i.e. bottom outside.
To obtain the function the ZX81 must be im FUNCTION
MODE, with the F-cursor on the screen.
On the Spectrum, all functions are obtained in the
Extended mode with the E-cursor on the screen (for further
details see Section W1). All FUNCTIONS treated here are in
green above the key on the Spectrum, with the exception of
ASN, ACS, ATN which are in red below the associated SIN,
COS and TAN functions, although they are still obtained in
the E-mode.
The FUNCTION/EXTENDED MODE only lasts for one
function. To obtain successive functions this mode must be
repeatedly entered.
J10: The Function Character Set
Character Code Code
(7Х81) (Spectrum)
SIN 199 178
COS 200 179
TAN 201 180
INT 207 186
RAND 64 249
STR$ 213 193
CHR$ 214 194
CODE 196 175
PEEK 211 190
TAB 194 173
ASN 202 181
ACS 203 182
ATN 204 183
SGN 209 188
ABS 210 189
SQR 208 187
VAL 197 176
LEN 198 177
USR 212 192
LN 205 184
EXP 206 185
AT 193 172
INKEY$ 65 166
NOT 215 195
п (PI) 66 167
These are the function characters as represented on the ZX81
keyboard. NOT is dealt with in Section R and INKEYS in Section K.
Note that ARCSIN, ARCCOS and ARCTAN are used on the ZX81
keyboard but print as ASN, ACS, АТМ, and п prints as РІ.
J11: The Standard Mathematical Functions
ABS (X)
Returns the absolute value or modulus of the value X.
X may be a number, variable or expression.
ABS(X) gives us the positive value of X. For example:
10 PRINT ABS( - 3.7) gives 3.7
10 PRINT ABS (4) gives 4
Exercises
Key in and run this program:
10 INPUT A
20 INPUT B
30 PRINT TAB 3;A; TAB 10;B
40 PRINT TAB 3; ABS (A - B)
30 GOTO 10
Input positive and negative values for A and B.
Now change line 40 to:
40 PRINT TAB 3; ABS (A*B)
and input some more values. Try replacing the * with **
( ^ Spectrum), or using ABS (SOR А).
N.B. ABS (- 3**3) , or expressions in similar form will not work
as the ** ( ^ Spectrum) operator only works for positive first operands.
EXP (X)
Where X is a number or an expression EXP (X) gives the
value of the constant e raised to the power of the value of X
e — 2.7183
e.g. 10 PRINT EXP (3.4)
i.e. 10 PRINT (2.7183* *3.4) (2.7183 1 3.4 on Spectrum)
The function EXP is the inverse to LN.
Exercises
1 Using log tables write a program to check the values of e* given
in the log tables.
120
2 Write a program which will calculate O from the expression:
Q = Qo.e-"* (In BASIC Q = QO* ЕХР(-Т/К“С))
If you know anything about electricity, you might recognise this
expression.
3 Key in this program. It calculates a value for e from the formula:
e=(1+1/N)**N (^N оп Spectrum)
where N is very large. Spectrum users should replace ** by # in
lines 30 апа 40.
10 REM “VALUE OF E"
20 ІЕТІ- 1
30 LET N=10**I [^Spectrum]
40 LET E=(1+1/N)**N
50 PRINT TAB 1;N;TAB 12;E
60 LET I=I1+1
70 IF l=5 THEN STOP
80 GOTO 30
LN (X)
Gives the value of the natural logarithm.
LN (X) = Log, (x)
Note that log, (X) (common logarithm)
= ( LN(X) )/( LN 10 )
The LN function is the inverse of EXP
So: If EXP (X) = Y
Then (X) = LN(Y).
LN (Y) is the natural logarithm of Y. The antilog is EXP(LN(Y)). The
normal log operations can be used if appropriate, as with common logs.
For example EXP(LN (X) + LN (Y)) gives the product of X and Y.
Exercises
1 10 LEFY=1
20 PRINT TAB 3;Y; TAB 10; ЕХР (LN Y)
30 LET Y=Y+1
40 GOTO 20
Key in and run this program which proves the relationship
between the EXP and LN functions.
2 Change 30 to: 30 LET Y = Y*1@ and run again.
SQR (X)
The function SQR returns the square root of (X), V (X) or
Х95, For example:
121
PRINT SQR 9 gives 3
PRINT SQR 23 gives 4.7958315
PRINT SQR (19 + 17) gives 6
PRINT SOR (ABS - 25) gives 5
SGN (X)
SGN (X) returns + 1 if (X) is positive, 0 if (X) is zero, — 1 if
(X) is negative.
SGN is short for Sign or Signum (Signum doesn’t sound like
Sine). For example:
SGN 23 gives 1
SGN - 5 gives - 1
SGN (3 – 3) gives Q
SGN 1 gives 1
SGN (25 - (2*23)) gives — 1
п PI
T (which prints on the screen as PI) is a function which has no
argument. It returns the value of r as 3.1415927.
3.1415927 is what prints on screen for PI. How would you test whether
the computer held any more digits of PI in memory? What happens
when you take away 3 from PI?
J12: Trigonometric Functions
SIN COS TAN
The functions SIN (X), COS(X)and TAN(X) give the value of
the sine, cosine, and tangent of the number or expression X,
which is an angular measure. X must be in RADIANS.
We normally express angles in DEGREES.
PI
= өй. 9... dE. Š
1 DEGREE 180 RADIANS (1 180 radians)
To convert degrees to radians multiply by PI/180. For
example, if Y is our measure of angle in degrees then:
SIN (Y*PI/180)
gives the correct value of Sine Y.
Exercises
1 Generate a table of values for SIN (X), COS (X) and TAN (X)
122
for every 20 degrees in the range 0 — 360 degrees.
2 Write a program to verify the trigonometric formula:
SIN(XX)+COSXX) =1
1+ TAN XX) =SEC*X)
3 Write a program to calculate the area of a triangle from a
knowledge of the length of 3 sides and an angle.
ACS ASN ATN
The functions:
ACS (X), ASN (X), ATN (X)
give the arc cosine, the arc sine and the arc tangent,
respectively, of (X).
The returned value is the angle in RADIANS for which the
cosine, sine or tangent would be given by the value of (X).
To get the angle in degrees multiply by 180/PI e.g.
Y = 180/PI*ACS(X) gives arcsin (X) in degrees.
Notice these functions print as above, but appear on the ZX81
keyboard as ARCSIN, ARCCOS, ARCTAN.
J13: Special Functions
Random number generators are useful for games and simulation in
statistics. The numbers generated are part of a very long sequence of
numbers (there are 65536 of them) and are in fact only ‘pseudo-
random’, but good enough for our needs.
RND
RND gives a random number greater or equal to zero but less
than one.
10 LET A = RND
assigns a number in the range 0 < = N <1 to the variable A.
Notice RND has no argument.
If we key in PRINT RND we get a number like .0011251904 or
0.43715682 which is eight or ten digits long and is not much use to
anybody in this form.
We need to be able to generate random numbers within a useful
range, according to our purposes:
1. To obtain a Random Number 0 - 9
To obtain a random number from 0-9 we must multiply our
123
function by 10 and take the integer value.
i.e. PRINT INT (RND*10)
RND*10 gives random numbers between 0.00000000 and
9.9999999, IN'T( ) will round these values down to integers
0 to 9.
2. Numbers 1-10
Although @ to 9 gives us ten values the range 1 to 10 would be
more useful. This is obtained by adding one to the RND function:
PRINT INT (RND*10 + 1)
Suppose we wanted random numbers generated for simulating a
dice roll, we would use:
PRINT INT (RND*6 + 1)
3. Random Numbers for a Card Game
There are 4 suits, with 13 cards per suit = 52 cards. So if we used:
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
aD PRINT “TAILS”
40 GOTO 10
50 PRINT “HEADS”
60 GOTO 10
This program will toss coins until we use BREAK.
RAND N
RAND is a keyword and is used for controlling the
randomness of RND.
The computer has a fixed sequence of 65536 jumbled up
numbers. RAND N will start RND reading numbers from the
Nth number in the sequence.
Key in and run this program to prove the above:
10 RAND 7
20 LET Ce=1
30 PRINT RND
40 LET C-C-«1
124
50 IF C<6 THEN GOTO 30
60 GOTO 10
Not amazingly random after all!
Exercises
1 Write a program which throws three dice and prints the values
thrown across the screen.
2 Write a program to check that the number generated by RND
using RAND N is given by RND = (75*(N + 1) - 1/65536).
3 Modify the coin tossing program to count the number of times
heads or tails have come up (you need one variable for each).
When you've stopped the program by pressing BREAK, you
can then access the values by keying in PRINT HEADS, or
whatever your variable name is, as a direct command.
4 Write a program to print four groups of three random numbers
in the range 1 to 52.
125
SECTION K: STRINGS
K1: Strings
A string is a set of characters enclosed by quotation marks,
e.g. “THIS IS A STRING” or the null string (no characters
Typical Strings: “BALL OF STRING"
“JANUARY 1ST 1982”
“URGHH!”
“FAB ** — +/!3”
E " (String of spaces)
1234”
ore (Null string)
Computers handle two kinds of DATA:
NUMERIC - numbers
ALPHANUMERIC - names or TEXT.
The way a computer deals with text is called STRING HANDLING.
Strings deal with ALPHANUMERIC information.
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
“> They are taken literally to represent themselves. Strings are
therefore literals.
Characters are IDENTIFIERS where they are not enclosed in
quotes. Thus, for example, A represents or identifies a numeric
variable and A$ identifies a string variable.
Strings can either be of FIXED LENGTH-e.g. always 10
characters long - or VARIABLE LENGTH. The fixed length is
determined by the string dimension instruction:
DIM A$ (N)
where N is the length in characters.
Characters which cannot be used in strings
A string cannot contain a character that is a line terminator:
NEWLINE (ENTER) or TAB. Nor can it contain any of the
following:
EDIT
GRAPHICS
RUBOUT (DELETE)
FUNCTION
BREAK
ee
(single quotes)
126
All other characters in your computer’s character set can be used.
Run the program which checks this:
10 INPUT A$
20 PRINT A$
30 GOTO 10
Now try and input some of the above characters.
Examples of the sort of text we may want the computer to handle
are:
— a telephone directory
- names and addresses
- a timetable
- expenses details
Computers store all this textual information as strings.
String manipulation by the computer would, for our first example,
need to deal with:
creating the telephone directory
sorting the names and numbers into the correct order
searching the directory for somebody's number
revising the directory, i.e. updating or adding an entry
printing out the directory in whole or part.
K2: Quotes and Quote Image
QUOTES
All strings are enclosed in quotes ‘‘’’ when:
(1) They are to be INPUT from the keyboard, as in a program
line such as: 10 INPUT A$ . When the line is run the
cursor оп the screen appears already enclosed in quotes |1 |”.
You key in just the characters wanted in the string.
(2) When used in programs with the PRINT instruction, e.g.
20 PRINT ‘‘STRING’’.
(3) When assigned in a program to a string variable, e.g. 30
LET А$ = * STRING".
THE QUOTE IMAGE KEY
ON THE ZX81
The QUOTE IMAGE is a special single character on the shift
keyboard of the ZX81.
6699
It is used to write ordinary quotes in the middle of a string.
eg.10 PRINT "SAY “BELLO” TOO]
127
When the line is run the double quotes will be printed on the screen as
single quotes:
SAY “HELLO” TOO
A special character is needed as two single quotes won’t work.
Key in and try to run each of the following lines:
10 PRINT '' SAY “НЕТО”? ТОО”
10. PRINT “БАУ”; "HELLO"; "TOO"
10 PRINT “ SAY "HELLO" TOO"
The Spectrum has no QUOTE IMAGE character. Instead, you must
put two quotes for every one you want printed. For example, to obtain
double quotation marks you type in PRINT“ °>, Single quotes
are obtained with PRINT**** ’’’’. Program listings look the same for
both machines.
K3: String Input
On running 10 INPUT A$ the letter cursor appears at the
bottom of the screen with quotes round it, prompting you to
key in characters for the string
= [L] =
On the Spectrum this can also be the C-cursor - ‘‘ me
STOPPING STRING INPUT
When keying in the characters for the string to be input notice
that BREAK and STOP have no effect.
To escape (1) Use the < key to get outside the quotes.
(2) Press STOP, NEWLINE (ENTER)
or
press
|
There is a special form of string input, using the INKEYS instruction:
INKEYS$
When INKEYS is encountered by the computer it reads the
keyboard to determine if a key is being pressed. It does not
wait for input like the INPUT instruction. If a key is being
pressed it returns the string containing the mode
character of the key being pressed. If no key is being pressed
it returns the empty string ‘‘’’.
128
The Spectrum returns the mode character with INKEYS$ if in the
CAPS mode.
We can spend as long as we want before we input a string with the
INPUT command, since the cursor will remain on screen. If we want
to take advantage of the fact that, unlike INPUT, INKEYS does not
require NEWLINE(ENTER) to be pressed, we must arrange a delay.
Try this program:
10 PRINT “PRESS A KEY WHEN READY”
20 IF INKEY$-''"" THEN GOTO 20 (no spaces)
30 LET AS-INKEYS$
40 PRINT “YOU PRESSED ”;А$
Line 20 sends the program back to the beginning of line 20 as long as
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
scanning using INKEYS 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
the time it will skip over line 30. This program will work every time
though:
10 PRINT “ PRESS A KEY WHEN READY"
20 PAUSE 0
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
pressed will be the INKEY$. PAUSE will be dealt with later, but
remember this quirk of the Spectrum, and this method of dealing with
it. The rule is to use PAUSE 0 immediately before INKEYS is used in
a program line, to wait for input.
Now enter and run this program:
10 PRINT “PRESS 6”
20 IF INKEY$ =“
THEN GOTO 20 (on the Spectrum 20 PAUSE 0)
30 IF INKEY$ = “6” THEN GOTO 60
40 PRINT “FOLLOW INSTRUCTIONS"
50 GOTO 20
60 PRINT “ENDING PROGRAM NOW"
70 STOP
Line 20 does the same as before, but line 30 now checks that the right
key has been pressed. Notice the 6 must be enclosed in quotes, because
INKEYS returns a string. If 6 was pressed, the program goes to line 60.
If any other key was pressed, it goes to 40, prints the message, and then
is sent back (line 50) to line 20, which waits for another key to be
pressed.
Games programs, which require interaction, often use INKEY$ in a
loop, so that every time the program loops, it checks which key, if any,
Is being pressed.
129
K4: Length of a String
LEN
The length of a specified string A$ is obtained by using the
function: LEN A$. The length is given as the number of
characters and is the current length of the string.
Spaces are included in the length of a string.
EXAMPLES
1 10 LET A$=‘‘SINCLAIR”’
20 PRINT LEN A$
Check that the result is 8.
2 10 LET AS= “А B’’ (9 spaces between A and B)
20 PRINT A$
30 PRINT LEN A$
Key in and run.
3 10 LET A$- “PRINT”
20 PRINT A$
30 PRINT LEN A$
Key in the program first with PRINT formed from separate keys, and
then change line 10 so that PRINT is formed by pressing the
key.
Why are the answers different?
4 10 INPUT A$
20 PRINT A$, LEN A$
30 GOTO 10
K5: Null Strings
A string with no characters is called a null string. For
example:
LET A$ — 6699
The length of the string is 0.
A string which contains spaces is not a null string. A space is a character
obtained by pressing [SPACE] . The null string is returned by
INKEYS if no key is being pressed.
Exercises
1 Key in and run the following program:
10 ТЕГА"
130
20 PRINT A$
30 PRINT LEN A$
2 Key in and run this program:
іё LET A$e!' ”
20 PRINT A$
30 PRINT LEN A$
К6: String and String Array Variables
AS
is a string variable used to store strings. It consists of a single
letter (À to Z), followed by the dollar sign.
Twenty-six variables of this type are thus possible.
The Spectrum accepts upper and lower case letters, but treats, e.g. k$
as the same string as K$.
AS(N)
is a string array variable or string list variable where N refers to
the number of strings in the list. String lists must be
dimensioned as an array before the string array variable can
be used, by the DIM (DIMension) instruction.
Using the array notation, an unlimited number of string
variables are possible.
Again, the Spectrum accepts upper and lower case letters, but does not
differentiate, e.g. b$(N) and B$(N) are the same.
Caution: A$(N) can have two meanings in a program.
(1) It can refer to the N’th character in a string A$.
(2) It can refer to the N'th string in a list or array of strings. In this
case the string array must previously have been dimensioned with a DIM A$(N)
instruction.
K7: String and String Array Dimension
STRING DIMENSION
DIM AS(N)
sets a fixed length of N characters for the string. For example:
10 DIM А$(6)
sets a length of 6 characters for the string А8.
131
If strings of length 25 AND DISF <= 50 T
HEN PRINT 95 "COLD"
260 IF DIFF>10 AND DIFF <= 25 T
HEN PRINT у» "xWARIME" |
270 IF DIFF>4 AND DIFF <= 10 TH
EN PRINT +," ж НОТ жж "
280 IF DIFE>O AND DIFF <= 4 THE
N PRINT ss" жж #BCILING# жы"
290 RETURN
700 REM жж END CHECESZLUE xx
210 REM ххх хз ЖЖЖ ЖЕК
220 REM
240 REM 33 CC 30 KHER HEHE HEH
GEO БЕМ жж зи Sup ++
SEQ REM хажы ғ HH ED
370 PRINT AT 9.95; "%%%%%7%%%7%%";
TAB 5: "$ SUCCESS %": TAB Si "$5
HEEE ESE"
380 PRINT АТ 10%5: "ІТ TOOK “ITR
IES?" TRIES. “
390 LET MARK =1
400 RETJEN
410 REM жж END SUMCESS Sie жж
420 REN X3X33X3 939 0 HE EK EE Y
430 СЕМ
470 REM жж ЖЖЖ
490 REM жж END/RESUN MOD xx
495 БЕМ 3*3 9 X 3 X 3 30 Ж Жы
200 PRINT ,$4"ANUTHE SO? INPUT
Y OR N"
SiO INFUT A$
CL
930 IF A$z"Y" THEN GOTO АО
940 PRINT +. "Ok. BYE"
wool STOP
Se REM xx xx END хх жж
The structure of the program is thus:
Module 1:
1. Initialise success marker MARK and variable to store number
of guesses made (TRIES)
2. Print Instructions
3. Call GET NUMBER Subroutine
Module 2 (Main program loop):
1. Increment TRIES
2. Input guess
3. Call CHECK Subroutine
4. Check if Guess equals Number. If it is, then call SUCCESS
Subroutine
5. Check marker. If Success subroutine has been called
(MARK = 1), then GOTO END/RERUN module
6. Loop back to Input guess again (1)
180
Module 3 (GET NUMBER Subroutine):
1. Define random number 1-99 as number N
2. Return
Module 4 (CHECK Subroutine):
1. Set variable DIFF equal to ABS difference of guess and number
2. Check value of DIFF, print appropriate message
3. Return
Module 5 (SUCCESS Subroutine):
1. Print success message, number of guesses made
2. Set MARK equal to 1
3. Return
Module 6 (END/RERUN module):
1. Print prompt for input
2. Input response to Another go? (A$)
3. If replay required (A$ = ‘‘Y’’) then GOTO Module 1,3
4. If A$ not “Ү” then print end message
5. Stop
Notice that (although this is a program that has been modularised
rather artificially to demonstrate the principles in a short program) the
program consists of an introductory section, then a main program loop
with both conditional and unconditional calls to subroutines, within a
short main program loop. This makes the structure of the program
clear, and minimises the use of GOTO statements, which would be
required in profusion if the program were written in a linear, rather
than modular fashion. It is perfectly possible to write the program in
this linear manner, but the structure will not be as visible.
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
main program if required. Conditional GOTOs аге preferable
program structures to unconditional GOTOSs, and whilst the END
module could be a subroutine, RETURNing to the main program
loop, further conditions would need to be inserted to pass control to
Module 1 for a new number to be defined. The subroutine would also
need to be exited by а GOTO for the program to stop. There is another
solution, however, involving a nested subroutine, which we will set as
an exercise.
Exercises
1 Rewrite /GUESSNUM"' with the END/RERUN module as a
subroutine. The procedure should be as follows:
END/RERUN SUB
i. Prompt for player input, and get response, as before.
181
п. If RERUN not required, bypass 3 апа 4 below, by a GO TO
the RETURN line.
ш. 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.
The main program loop is then returned to. The main program
must then test whether it is to exit (rerun not required) or
continue (new game started). We could set another marker to
test this, but in effect we have done this by re-setting MARK ifa
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.
Insert an additional subroutine which prints 1;‘‘ST’’,2;
“ND”,3;*°* RD”, and then “ТН” for other numbers into the
“FACTORS” program (Unit N2).
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.
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.
182
PART THREE
ADVANCED BASIC PROGRAMMING
ТАРЫ s ДАЧ
ОЛА мМАЯООЯЯ MEAN LOW ATTO А
SECTION O: PROGRAMMING METHODS II
O1: Résumé
Before we enter the arena of advanced BASIC programming let us
recap on what we have examined and accomplished so far.
The method to design the solution or algorithm to a computational
problem using ‘top down’ analysis has been explained. We have seen
how to break our problem up into sub-problems which form our
program modules (using tree diagrams). We know how to describe the
algorithm in concise English sentences that we call pseudocode and
how to determine and illustrate the flow of control in the problem
solution by drawing a flowchart. When designing our solution we
recognise the need to use the fundamental programming tools of:
(1) decision making
(п) branching as a result of decisions
(iii) direct transfer from one point in the algorithm to another
(iv) repetition
These control structures, as they are called, which are present in all
computer languages, have been discussed in some depth, together with
other important BASIC language fundamentals. The techniques of:
(1) decision making
(п) numeric processing
(iii) character handling with strings
(iv) looping through counting and condition testing
(v) handling of output by printing and plotting
and the realisation of modular techniques in programming by using
subroutines have all been covered.
WHAT'S NEXT?
We must now consider the second phase of the programming
method - producing the program itself.
It 1s important to do so at this stage in the book, so that our
programming tool kit is complete enough to investigate and use the
more sophisticated information handling facilities to be introduced
later in this section:
(1) logical operations on data
(1) character codes
(uni) moving graphics
(iv) graph plotting
(v) constructing and searching lists and data arrays
(vi) how to sort information into order
Once these skills have been mastered our complete programming
expertise can then be applied to real applications.
Let's now see in this section of the text how to code our algorithms
into BASIC language programs, and then debug, test and document
them.
185
Further important design rules will be given, and finally a summary
of our complete programming method will be provided with a
flowchart and worked example.
O2: Producing the Program
We now consider the method by which a well designed, tested and fully
documented program is produced.
Given our algorithm - which we have written out in steps in a
description we call pseudocode — together with our flowchart — which
shows how the steps of the solution are combined in sequence for the
computer to solve the problem - we must now:
1. CODE THE ALGORITHM IN SINCLAIR BASIC
2. DEBUG AND TEST THE PROGRAM
3. DOCUMENT THE PROGRAM
O3: Coding and Design
CODE ON A ONE TO ONE BASIS
If the description of the algorithm is correct then coding on an almost
one to one basis from statements in the pseudocode or the flowchart is
possible. If you cannot code from the flowchart or pseudocode then
further refinement of the algorithm is necessary.
Pseudocode descriptions in formal mode of the BASIC language
control structures for decisions and loops are given later in this section.
You will notice that the description itself is indented and concise, with
the terms almost the same as BASIC statements. This is not unusual as
BASIC was designed to do this very thing and 1s English-like in its
syntax.
To be able to code at all you must of course:
KNOW THE BASIC LANGUAGE AND ITS RULES
Hopefully it is the right language for the job. On the ZX81 and
Spectrum you don't have much choice! Actually it is a question of ease
of programming specific applications that generates different
languages. Most things can be done in BASIC, although perhaps not
efficiently or elegantly. It is often useful to identify the kind of
processing that will be required. When designing the algorithm
consider whether the problem is a scientific or a business application,
whether extensive calculations will be performed or large amounts of
list processing done, whether the data is extensively numeric or string
and whether the program will be interactive with much user dialogue.
When coding, avoid spelling and formatting mistakes. Sinclair
BASIC is powerful in that it is one of the few available single keystroke
186
BASICs, hence you cannot make spelling mistakes on instructions or
commands because the whole instruction is keyed in at once. However,
mistakes can still be made when assigning variable names and in
PRINT and REM statements.
DEFINE AND CONTAIN EACH MODULE
WITH REM STATEMENTS
For example:
100 REM * SORT MODULE *
200 REM * THIS MODULE SORTS STRINGS *
500 REM * END SORT *
TERMINATE YOUR PROGRAM PROPERLY
You may have noticed that Sinclair BASIC does not need a special
end-of-program statement. We can, however, put one in using a REM
statement. For example:
500 REM * END OF PROGRAM *
Тһе 7Х81 and Spectrum do not process but only note REM
statements. When the above line runs, the program will finish
elegantly with a 0/500 message.
We can also stop a program with the STOP statement. Main
modules should finish like this with subroutines programmed at higher
line numbers terminated with a REM * END * statement. When
terminated with STOP a message 9/line number (a 9 Stop (Line
number): 1 statement on Spectrum) will be given.
REM * NAME OF PROG *
10 REM * MAIN MODULE *
20 GOSUB 500
30 STOP
40 REM * END MAIN *
500 REM * SUBROUTINE *
600 RETURN
700 REM * END SUBROUTINE *
800 REM * END OF PROGRAM *
We could also use a GOTO 800 at line 30 to terminate execution on
the last program line.
ALWAYS CODE ACCORDING TO THE LOGICAL ORDER
OF PROCESSING
This is usually ensured if you code from a flowchart, with your
187
flowchart structured into modules, i.e. flowchart groups for the
modules in the program.
Take care with the control structures and avoid unnecessary
branching, especially with GOTO instructions. Try to make your
programs both readable and efficient — but first make them readable!
USER FRIENDLY PROGRAMS
Design your programs with the user in mind - and that includes you!
Directions to users should be concise and as few as is necessary, both in
the program and in the user guide if your program is large enough to
merit one.
Where the user needs a number of instructions to operate the
program then these can be built into an optional ‘help’ module or
subroutine.
100 REM * USER INSTRUCTION *
110 REM * DIRECTS USER TO HELP SUBROUTINE *
120 PRINT “ FOR INSTRUCTIONS TYPE HELP
OTHERWISE TYPE C "
130 INPUT A$
140 IF A$ - *HELP''THEN GOSUB 1000
150 REM * END USER INST *
1000 REM * HELP SUBROUTINE *
1200 RETURN
1210 REM * END HELP *
Users usually require to know:
~ how to run the program
— what form of input data is required
— what output is produced
Your program should check on the range and type of input data. If the
input data is out of range or incorrect the program should not stop with
an error, but continue with a message to input correct data.
After you have designed a program to do a specific task it may be
worthwhile to change it to be as general as possible — i.e. do several
similar tasks. As you become more skilled and confident in
programming you will be able to generalise and write a subroutine that
enables users to select options from a menu. This is exactly similar to
the exercise you have seen in multiple decision structures. See the
"CASSFILE'' program in Section V, for a ‘‘menu-driven’’ program.
More “‘user-friendly’’ tips are given in the section on documentation,
and some useful routines in Unit V2.
188
DESIGNING PROGRAM LAYOUT
You must make your program readable. The program design will be
modular and contain specific identifiable segments, subroutines and
modules. These should be labelled in the design of the algorithm and
transferred in the coding process.
(1) EACH MODULE SHOULD BE TITLED AND LABELLED
TO INDICATE ITS FUNCTION. FOR EXAMPLE:
10 REM “AVERAGE”
20 REM * PROGRAM AVERAGES ANY NUMBERS
INPUT *
3 REM *
40 КЕМ * USER ROUTINE *
50 REM * CHOICE OF NUMBERS INPUT *
60 PRINT “HOW MANY NUMBERS DO YOU WISH
TO АУЕКАСЕ”
70 INPUT N
80 DIM A(N)
9) REM * INPUT ROUTINE *
100 REM * NUMBERS INPUT TO ARRAY *
110 PRINT “INPUT NUMBERS"
120 FORI=1TON
130 INPUT A(I)
140 NEXT I
150 REM
160 REM * PROCESSING ROUTINE *
170 REM * COMPUTES AVERAGE *
180 LET SUM-0
199 FORJ=1TON
200 LET SUM = SUM +A(J)
210 NEXT J
220 LET AVERAGE - SUM/N
230 REM
249 REM * OUTPUT ROUTINE *
250 PRINT “THE AVERAGE OF"
260 FOR K=1 TON
270 PRINT A(K); ”’;
280 NEXT K
290 PRINT “IS ”; AVERAGE
300 REM
310 REM * END AVERAGE *
(2) DESIGN YOUR PROGRAM SO THAT RELATED
STATEMENTS ARE TOGETHER
For example, input — processing — output statements:
() All input statements will be at the beginning of a simple
sequential program, processing in the middle, and
output normally at the end.
189
(3)
(4)
(9)
(üu) For a modular program, input, processing and output
routines will be separate modules or groups of statements
within a single module.
(ш) Subroutine modules will usually be placed separately at
the end of a program.
INSERT REM STATEMENTS BETWEEN PROGRAM
MODULES AS SEPARATORS
Program modules are then easily identified. Use blank REM
lines or lines of asterisks.
PLAN YOUR PROGRAM LAYOUT BEFORE CODING
The printed listing of your program is important. Choose a
maximum line width. Break longer lines into shorter ones in
REM statements by using spaces. Compensate for overrun. For
example:
10 REM * AAAAA
AAAAA
AAAAA *
You will not be able to do this with other BASIC statement lines.
YOUR LAYOUT SHOULD TRY TO REFLECT THE
MODULAR STRUCTURE OF YOUR PROGRAM
190
Indented statements are not possible on the ZX81 or Spectrum,
unfortunately!
DESIGNING PROGRAM OUTPUT
For the user the output is the most important part of the program.
Take time planning it. The output instructions in Sinclair BASIC are:
PRINT, PRINT AT, PLOT, LPRINT, COPY, TAB, plus graphics
commands.
() RESULTS SHOULD BE OUTPUT WITH RELATED
ITEAL
Label all your numerical output:
єн. 1974 £5678.65
instead of 1974 5678.65
e.g. AVERAGE AGE OF BOYS IS 15 YRS 3 MONTHS
rather than 15 3
(i) DISPLAY LARGE AMOUNTS OF OUTPUT AS A TABLE,
HISTOGRAM OR GRAPH, AND GIVE TITLES.
For example:
TABLE 1: NET INCOME FOR B. JONES
FOR YEARS 1978-80
Box your tables if possible.
The user should not have to look up the program listing to see
what the numbers in the output mean.
au) DESIGN YOUR OUTPUT TO BE EASY TO READ
Plan it to be attractive to any user of your program and, of
course, yourself. Graphics is a powerful tool for this.
(iv) ALIGN, SPACE AND JUSTIFY THE OUTPUT
Plan your output with reference to the screen size and divisions.
For tables — align information central to the heading
align signs
right justify numbers
left justify characters.
(There are routines in the text for doing this). For example:
876-340 JIM SMITH
27-210 HUNG FO
453-003 SARAH JAY
1-025 DRACULA
NUMBERS
15.003
815.231
- 4.000
– 100.100
Fill in with zeros to get decimal placing correct.
(v) USE SPACE CAREFULLY
Sinclair computers use expensive printer paper! Print output
horizontally wherever possible. For example:
TABLE OF POWERS OF 2
2
4
8
16
32 etc
should be:
TABLE OF POWERS OF 2
2 £ 8 16 32
64 128 256 512 1024
(vi) DO МОТ OVERDO EXPLANATIONS
Be succinct!
(уп) MAKE YOUR ABBREVIATIONS CLEAR
x = 25
NDTC =25
NUMBER OF DAYS TO CHRISTMAS = 25
(vii) DISPLAY INPUT DATA AS AN OPTION
Allow checking of input data before processing.
Make your program check for incorrect or bad input data.
MODULAR DESIGN
We break problems down into sequences of steps to produce programs
in which different kinds of activities are separated out. These
distinctive program modules are our SUBROUTINES or SUB-
PROGRAMS. Each module has its own name and address, but in
BASIC we usually refer to program modules by address only, as with:
GOTO 100 and GOSUB 3300
where the address is the line number of the first statement in the
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 *
20 LET INPUT DATA = 1000
30 LET PROCESSING = 2000
192
40 LET OUTPUT DATA = 3000
59 REM * END MODULE ASSIGN *
60 REM
70 REM * MAIN *
80 GOTO INPUT DATA
90 GOSUB PROCESSING
100 GOTO OUTPUT DATA
110 STOP
1000 REM * INPUT DATA MOD *
1500 GOTO 90
1600 REM * END INPUT *
2000 REM * PROCESSING SUBROUTINE *
2500 RETURN
2600 REM * END PROCESSING *
3000 REM * OUTPUT DATA MOD *
3500 GOTO 110
3600 REM * END OUTPUT MOD *
4000 REM * END PROG.*
There are good reasons for modular design and the use of subroutines
and sub-program modules. The logic of the program, i.e. its flow, is
easier to follow. The clarity of the structure of the main program is
improved whilst program design is proceeding by referring to the
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.
Independent testing of modules is possible, but care must be taken
that all variables have been declared and have their correct values at
the start of the module. Debugging 1s simpler with this approach, since
the module is isolated. You can leave the coding of a module until a
later stage, but you must know what it will do when coded.
If a module has to be used several times in a program from different
places it need only be written once and called (into action) from these
points by reference to its line number or name.
193
Program modules can be designed to run sequentially:
START
MODULE 1
INPUT
MODULE 2
PROCESSING
MODULE 3
OUTPUT
STOP
This structure is convenient for simple programs. However, programs
can be structured in terms of subroutines and sub-programs being
called from a short and simple main program module.
START
MAIN
a MODULE
MODULE 2
MODULE 3
194
This structure is convenient for longer, more complicated, programs
with many modules and nestings.
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.
CONTROL STRUCTURES IN SINCLAIR BASIC
(1) Each control structure is a program module.
(2) A formal pseudocode description of each structure is given of the
general form of the control structure.
(3) A flowchart description is given of the general form.
(4) The BASIC version is given of the general form.
(5) A simple example illustrates the BASIC form of the control
structure.
(6) Structures will be written in indented form in the pseudocode
version for clarity. You cannot indent in Sinclair BASIC
program listings. REM statements must be used to show the
start and stop lines for program modules.
(7) P is a processing operation. It can be a single instruction, a
statement or a group of statements.
(8) In the formal pseudocode each structure will commence with the
title module (abbreviated to mod), and end with the statement
endmodule (abbreviated to endmod).
(9 In BASIC cach structure will be bounded by
REM*STARTMOD* and REM*ENDMOD* statements.
(10) Flowcharts will be bounded by START and STOP symbols.
The structures summarised are:
A) Decision Structures
(1) Single decision
IF-T HEN structure
(п) Double decision
IF-T'HEN-else structure
(ш) Multiple decision
Case structure
195
B) Loop Structures
(i) repeat-forever loop structure
(ii) repeat-until structure
(iu) while-do structure
(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
() SINGLE DECISION: The IF-THEN structure
Meaning: IF (condition is true) THEN (do something)
Pseudocode Flowchart
mod
if (condition)
then P
endif
endmod
BASIC
10 REM*START MOD*
20 IF (COND) THEN P
30 REM* ENDMOD*
Example
Input a number and if it is positive, print it.
Pseudocode BASIC
mod 10 REM*START MOD*
input A 20 INPUT A
If A > Q 30 IF A>@ THEN PRINT A
then print A 40 REM*END MOD*
endif
endmod
196
(i) DOUBLE DECISION: The IF-THEN-else structure
Meaning: IF (condition is true) THEN (do something)
otherwise (if condition is false) do something else.
Pseudocode Flowchart
START
mod
if (cond)
then P1
else P2
endif
endmod
BASIC
10 REM*START MOD*
20 IF (COND) THEN GOTO 50
30 (FALSE TASK P2)
40 GO TO 60
50 (TRUE TASK P1)
60 REM*ENDMOD*
To perform the true task (P1 in the pseudocode) first, the BASIC
implementation of the structure would test the complement of
the condition, so that in the program below, for example, A>B
would be replaced by AB 30 INPUT B
then print A 40 IF A» B THEN GOTO 70
else print B 50 PRINT B
endif 60 GOTO 80
endmod 70 PRINT A
80 REM*ENDMOD*
(ш) MULTIPLE DECISION STRUCTURE: The case structure
With this structure we want the program to select and perform
one of several alternative tasks.
The conditions in this case structure are sequential, not
nested and mutually exclusive.
Pseudocode Flowchart
mod
case
if (condition 1 is true)
then P1
if (condition 2 is true)
then P2
if (condition 3 is true)
then P3
end case
endmod
198
BASIC
10 REM*STARTMOD*
20 IF Cl THEN P1
30 IF C2 THEN P2
40 IF C3 THEN P3
320 REM*ENDMOD*
Example
Test whether a number input is positive, zero, or negative, and
print the result.
Pseudocode Flowchart
mod
input A
case PRINT
if A<0 NEGATIVE
then print “МЕСАТІУЕ”
If А = 0
then print “ZERO”
if А>0
then print “POSITIVE”
endcase
endmod
PRINT d
PRINT
POSITIVE
199
BASIC
14 REM*STARTMOD*
20 INPUT A
30 ЕА < 0 THEN PRINT “NEGATIVE”
40 IF A-0 THEN PRINT “ZERO”
5) IF A>@ THEN PRINT “POSITIVE”
60 REM*ENDMOD*
Alternatively, we can use conditional and unconditional GOTO
statements to implement this structure. This would be
appropriate if the processing section of a program after the
decision were several statements long, rather than the single
instruction available on the ZX81. Spectrum users can add more
instructions on the same line. They should be restrained in using
this facility.
10 REM*STARTMOD*
20 INPUT A
30 IF A< 0 THEN GOTO 60
40 IF A-0 THEN GOTO 80
50 IF A>@ THEN GOTO 100
60 PRINT “NEGATIVE”
70 GOTO 110
80 PRINT “ZERO”
90 GOTO 110
100 PRINT “РОБІТІУЕ”
110 REM*ENDMOD*
В. LOOP STRUCTURES
(1) The repeat — forever loop
Meaning: None. The only conceivable result is the program
halting with an arithmetic overflow report.
Pseudocode Flowchart BASIC
(такт) 10 REM*STARTMOD*
START
20 P
30 GOTO 20
mod
40 REM*ENDMOD*
repeat
P
forever
endmod
200
(i)
This structure is for demonstration only. Avoid using it in
programs! It can sometimes occur in error. Use BREAK if you
suspect your program has entered such a loop (because nothing
happens).
The repeat — until loop
Meaning: Repeat processing until a condition is true.
These structures loop until a specific termination condition is
met, for example until a counter reaches a certain value or until
a dummy or sentinel value 1s input. The important characteristic
of this loop structure is that the repeat test (or exit test) is at the
bottom of the loop, after the processing ‘body’. The program
lines making up the body of the loop (P) will be executed at least
once. The repeat condition can use any conditional operator or
its complement (reverse).
e.g. equals 4—0 not equal
- <>
Use of the complement often leads to a more elegant program.
Pseudocode Flowchart
mod
repeat
P
until (condition is true)
endmod
BASIC
10 REM*STARTMOD*
20 P
30 IF (COND) THEN GOTO 50
40 GOTO 20
50 REM*ENDMOD*
201
BASIC using complement
10 REM*STARTMOD*
20 P
30 IF (COMP COND) THEN GOTO 20
40 REM*ENDMOD*
Exit requires no specific instruction.
Example
Input and print strings until the sentinel value “LAST” is
input.
Pseudocode Flowchart
START
mod
repeat INPUT Ag
input A$
print A$
until A$ = LAST
endmod
PRINT Ag
Ag-LAST ?
BASIC
10 REM*STARTMOD*
20 INPUT A$
30 PRINT A$
40 IF A$=‘‘LAST’’ THEN GOTO 60
50 GOTO 20
60 REM*ENDMOD*
202
Complement Version
10 REM*STARTMOD*
20 INPUT A$
30 PRINT A$
40 IF A$<>‘‘LAST’’? THEN GOTO 20
50 REM *ENDMOD*
(ш) While — do structure
Meaning: While a condition holds (TRUE) keep repeating the
process until the condition is broken (FALSE).
The condition can be, for example, that a loop-counter
variable value is not equal to its final value (IF N<10 THEN..).
The process will then repeat until it is. The condition may also
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.
Pseudocode Flowchart
START
mod
while (condition is true)
do P
endwhile
endmod
BASIC
10 REM*STARTMOD*
20 IF (COND) THEN GOTO 40
30 GOTO 60
40 P
50 GOTO 20
60 REM*ENDMOD*
203
(iv)
Using the complement of the repeat condition gives a neater
program.
Complement Version
10 REM*STARTMOD*
20 IF (COND) THEN GOTO 50
P
40 GOTO 20
50 REM*ENDMOD*
Example
While the value of the square of consecutive integers is less than
100, print them on the screen.
Pseudocode BASIC (complement)
mod 10 REM*STARTMOD*
п = 1 20 LETN=1
while п*п< = 100 30 IF N*N>100 THEN
do print n*n GOTO 60
n=n+1 40 PRINT N*N
45 LET N=N+1
end while 50 GOTO 30
endmod 60 REM*ENDMOD*
FOR - NEXT Loops
FOR - NEXT loops are a special BASIC structure for repeating
a process a stated number of times. They are in fact While — do
loops and have the repeat test at the top of the loop.
Example
Print the values of the first ten integers.
Pseudocode BASIC
mod 10 REM*STARTMOD*
n= 1 20 FOR N=1 TO 10
While n < = 10 30 PRINT N
do print n 40 NEXT N
п=п+1 50 REM*ENDMOD*
епа while
епатоа
FOR - NEXT loops have their own special flowchart symbol,
because they are used so extensively in BASIC:
204
Ordinar Special
This is a condensed version. It groups together
the FOR — NEXT — STEP instruction elements,
which the standard form separates.
This illustrates both a
While do and a FOR-
NEXT structure.
O4: Program Development
Program Development involves the activities of DEBUGGING your
program of errors, TESTING to see if it behaves as specified and gives
the desired results, and DOCUMENTATION which tells users how to
run the program.
DEBUGGING
The Sinclair machines have good editing facilities and error messages.
Those on the Spectrum have brief statements of the error type, those on
the ZX81 have just a number or letter.
Although it is inefficient to correct errors one at a time (because there
is seldom only a single error since programming mistakes tend to
compound one another), error messages on the machine are produced
singly, since an error stops the computer from running. Thus we must
deal with the errors as they occur in the program sequence. You may
notice a number of errors on carefully looking through the listing. Any
you spot should be edited out at once.
GET TO KNOW YOUR COMPUTER ERROR CODES
This will happen automatically in time (as you make mistakes!), but it
is worthwhile studying the codes. They define the ways in which 'run-
time' errors occur, and an understanding of them will help you avoid
bugs.
205
EXIT
Keep a note of mistakes you have made and how you
corrected them. This will be valuable for future reference.
This should become an automatic part of your personal
documentation. Keep a copy of old program listings. Record the errors
you have made, the corrections you tried but which did not work, and
what you learned in developing the program.
Trace the impact of any error through the program.
SYNTAX ERRORS
These are caused by BASIC statements you key in which do not obey
the precise language rules (syntax rules) of Sinclair BASIC. The syntax
errors are detected by the LINE INTERPRETER which
automatically checks each line you key in when you press the
NEWLINE (ENTER) key.
If there is an error the interpreter will place the SYNTAX ERROR
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
have been placed there. To correct this type of error you must compare
the syntax you have written with the rules of BASIC.
Typing instructions incorrectly cannot occur on the Sinclair
computers as the BASIC 15 single key-stroke. In other BASICs you
must type P,R,I,N,T, for PRINT. Instructions in general are
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
the mode controller which sets the cursors in the correct sequence.
Errors which can occur are:
1 Omission of line number
Line number too large (29999)
Line number negative
Line number non-integer
Omission of delimiters:
brackets (must be paired)
commas
semicolons
quotes
colons (on the Spectrum)
6 Typing in of improper variable names
7 Incorrect logical expressions
There can be more than one error per line. The S-cursor will re-appear
in the line when you try to enter it into memory. The line edit facility is
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
successful, the program line will appear at the top of the screen.
The syntax error check ensures no nonsense lines (from the
computer's point of view) are entered. It cannot help you in coding
correct sequences of program lines, or prevent logical errors.
сл ны оо ho
206
PROGRAM LOGIC ERRORS
These are the effect of bad logical design of the program. They can be
avoided if care is taken in the design and coding of the program. Ifa
program produces incorrect results then there is an error in the flow of
logic in the program. This may only occur with certain values of data.
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:
1) Insert a temporary breakpoint into the program, at the
appropriate point.
2) Print out values of intermediate results, to the screen or printer.
3) It is most important to print out the values of variables used in
making a decision and those used in loops, either counter loops
or FOR - NEXT loops.
4) Go back to the pseudocode or flowchart and modify the steps
which are in error. ‘Walk through’ the algorithm, using a
flowchart, to check the step sequence, and hand trace the
program with selected values of data and/or variables. Be
careful! Often changes in one part of the algorithm cause
changes in the others. It is no use solving one problem if it causes
another!
3) Change the documentation if necessary. Note down the changes
you have made, or lines you have deleted. Keep program
listings.
6) Re-test the complete program, using a variety of data.
Each testing statement in a complex program should be headed by a
remark statement.
1000 REM - DEBUG
— (Testing Statements)
- REM - END DEBUG
These temporary REM statements are later deleted by keying in their
line numbers, as are the testing statements. It is very easy to leave in
test instructions unless they are marked.
INSERTING BREAK POINTS
We can stop a program at any point and obtain the values of variables,
expressions, etc. to test calculations or check for errors. We do this by
207
Inserting a group of statements which will output the values we want
and then stop the program.
qM < ADD TEST OUTPUT OF VARIABLES
МШ < INSERT STOP STATEMENT
CONT will restart the program.
Individual modules or sections of program can be tested this way.
We do, of course, have to RUN the program from the required module
line number. Care should be taken when this is done that variables
needed in the module have been declared properly and that the values
of parameters passed to the module are as required. Remember that
you can INPUT the values of variables directly if necessary, using the
command mode, and using LET statements:
LET X(2) = 20, etc.
The value of any variable at the point the program crashed can also be
obtained by keying a statement without the line number, and again
using the computer in command mode:
PRINT A$
LPRINT X(3)
The commands RUN N (where N is the line number we wish to run
the program from) and GOTO N enable us to run the program starting
at any point. Using GOTO N does not negate the initialisation of
variables that occurs 2 the program has already run. For example, if
we input:
10 LET A=1
20 LET B = 2
39 PRINT A,B
and then key in GOTO 30, we get the error report ‘2/30’ (ZX81) or ‘2
Variable not found 30:1' (Spectrum) meaning an undefined variable
was found. If we RUN the program, we can then use GOTO 30, and
the program signals successful completion.
RUN-TIME ERRORS
These are a result of programmer carelessness and do not prevent the
interpreter from translating the program. They make the program
crash when you attempt to run it, that is they prevent the program
from running to completion. Common run-time errors are:
1) undeclared or unidentified variables
2) arithmetic overflow
3) lack of data for processing
208
4) failure to complete loop increment and subroutine section
statements
5) subscript out of range
6) memory full
7) screen display file full
8) integer out of range
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:
ERROR CODES
These errors can then be traced through the type of error given by the
code and the line number at which the program stopped.
ERROR CODES
Error codes or Report codes are presented on the screen when a
program stops for any reason, either as a result of successful
completion (no more program lines), an instruction or command
(STOP, BREAK), or a run-time error.
On the ZX81 the codes have the form E/N, where E is the code for
the type of error and N is the line number where the program was
stopped (STOP or BREAK), or where an error occurred. N is @ fora
direct command. This is an example of an error code on the ZX81
which is printed on the screen when an arithmetic overflow (number
larger than about 10% generated) occurs in line 60 of the program:
6/60
The Spectrum gives an extended error report code, with a brief
statement in the form:
E Statement N:S
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
the line number, but since the Spectrum can have multiple line
statements, the S number indicates which statement on the line the
report code refers to. We are not using multiple line statements in this
text, so S will always be 1, meaning the first (and only) statement on
the line, unless after the THEN in an IF... THEN statement, which 15
treated, like a colon, as a statement separator.
The Spectrum's version of the example given above (the ZX81’s
arithmetic overflow error code) is:
6 Number too big 60:1
Report codes are crucial aids to debugging programs. Without them
we would know only that we had an error, but not where it occurred or
what type of error it was. The error reports indicate both of these items
of information.
It is important to understand that the cause of an error may come
earlier in a program than the line where the program stopped. For
example, a code 2 error (variable not found), occurring in line 100 of a
program might be caused by a mis-spelt variable name in line 100 (not
209
the same as the variable you meant it to be — putting GUES when you
meant GUESS, for example). It could also be the result of not having
assigned the variable earlier in the program. If the error causing the
program to halt is not apparent from the line given in the error report,
the program flow must be traced backwards to find the prior cause. In
some cases this can be extremely difficult to track down - for example,
where a numeric value wrongly defined or generated by the program
causes another expression to cause an arithmetic overflow. Tracing
techniques must be used.
Lists of Error codes and their meanings for the ZX81 and Spectrum
are given in Appendix II.
TESTING AND VERIFICATION
Verify that your program works by testing it with Test Data
Testing comes after debugging a program. Its purpose is to ensure that
the program is logically correct, produces correct answers and meets
the specification of its purpose.
1 First test each module separately
Each procedure and subroutine should be treated as if it were a
separate program.
Test for (i) good data - the expected type and range of inputs.
(1) bad data — out-of-range and incorrect type inputs.
Try to ensure each procedure ‘fails softly’. For bad data (particularly
in any data entry module) following each input a check routine or
procedure should be used to give an error message if range is incorrect
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
input checks at length.
2 Combine the modules and test the complete program
If there is a logical error (1.e. program does not produce the intended
results) insert additional test statements which will:
(i) Output intermediate results.
(11) Output values of variables at each stage.
(iii) Output results of expressions at each stage.
(iv) Output values of the loop counter at each pass.
(v) Output results of array manipulation after each
operation.
(vi) Output values of parameters before and after subroutines
entry and return.
3 Handle exceptions
(1) Test all data in the program.
(11) Screen all data.
(111) Process only good data.
(iv) Output bad data saying why it was bad.
210
4 Let your program stop elegantly
(1) When there is no data input or data available, the
program should tell you so.
(1) Sinclair BASIC programs are interactive. The user сап
control program continuation with:
910 PRINT “PROCESSING ENDED - MORE
DATA? ANSWER YES OR МО”
920 INPUT A$
930 IF A$ = “YES” THEN GOTO 100
940 PRINT “GOODBYE”
950 STOP
960 REM PROGRAM END
5 Rewrite the program until you are satisfied with it
Remember the program should be - structured
— easy to read
— easy to understand
— handle exceptions
— be as efficient as possible
— documented
and it must solve the problem as specified!
6 Put clarity before efficiency
To be good a program algorithm does not have to be clever, difficult to
understand or run super-fast. If you do not understand how the
algorithm works do not use it — rewrite and re-design or use another
method.
Programs will work correctly if the rules of the language are obeyed,
and the program will work to specification if the algorithm 1s properly
designed.
DOCUMENTATION
ANNOTATE AND DOCUMENT YOUR PROGRAM AND
CREATE A READABLE PROGRAM
1 Write an explanation for each program module or segment. At
the beginning of each segment provide suitable comments which
explain:
(1) the purpose of the algorithm
(2) the variables and their significance (the values they
store)
(3) the results expected.
2 Use comments only where necessary:
(1) don't comment each program line
(2) don't explain the obvious
(3) at the beginning of the program provide a block of
211
10
comments that explain the program at each module and
provide a comment which explains what the module does
in relation to the program.
Clear comments should appear separated from program code.
The clearest comments are framed. For example
19 REM * * * * * * * *
20 REM * SUBROUTINE TO *
30 REM * CALCULATE N TO 2 D.P. ы
40 КЕМ * i
50 REM * * * * * * * *
Lines of asterisks provide visible dividers between sections of
program.
Use comment in the program and in the output to the screen or
printer.
Use blank REM lines as separators in the program.
For large programs write a reference document:
(1) Describe the algorithm you used. If it is not original you
should include a note of its source, author, version, and
type of computer it was written on.
(ii) Explain how you wrote the program, the reasons for
writing it, the type of computer used and memory
required.
(ii) Make a note of areas that may need improving, or could
be modified for different purposes.
(iv) Which modules are general (menus, subroutines), and
which require specific kinds of input.
(v) Explain the scope and limitations of the program.
(vi) Include your name, and the date of production.
List the tests you made and data used. Reproduce some of the
results of the tests.
List performance tests (e.g. how long it takes the program to
run).
Give user instructions and reproduce the output of a run and
explain to the user how he uses the program.
Give the program characteristics. Explain any abnormal
behaviour of the program (e.g. response to bad input).
Write a brief USER GUIDE. This is mot for the computer
expert. It should explain:
— the purpose of the program
— the algorithm
— how to run the program
— what input is needed
— what results are printed
— how to use the menu (if included)
O5: THE COMPLETE PROGRAMMING METHOD
SUMMARY: THE STRUCTURED PROGRAMMING METHOD
1. | PRODUCE THE ALGORITHM
State the Problem fully
1.4
1.3
1.3
1.4
1.1.4
1,2,2
State the problem
Understand what is to be done
Research the Problem
1.2.1
1,24%
15,4
Research апа analyse the problem to see how the
computer can handle it
Identify all formulae and relations to be used.
Identify all data involved
Design the algorithm
Use top down structured methods:
152,1
1,5,2
1.5.3
1.3.4
1.2.9
1.3.6
Break the problem up into sub-problems ог modules.
Use a structure diagram or tree diagram to help in
breaking down the problem.
Start classifying modules or parts of modules as:
INPUT
PROCESSING
OUTPUT
Utilise the fundamental control structures in the modules
— Decision structures
— Transfer structures
— Loops
- Subroutines
- Nested structures
— Subprograms
Set up a DATA TABLE in which all data types are
classified as
Variables
Constants
Counters
Functions - if using a Spectrum and the DEF ЕМ
instructions
Define the algorithm further until coding it into a BASIC
language program is an easy and obvious exercise.
Describe the algorithm in Pseudocode and Flowchart form
1.4.1
1.1.2
1.4.3
Write out the final algorithm (now in modular form) in
small steps in an abbreviated English style called
Pseudocode.
Each module should be treated separately and !abelled.
Illustrate the logical flow of control in the algorithm by
constructing a flowchart.
Test the algorithm, if necessary using a hand trace or
walk through.
213
2.
2.1 Code the Algorithm in SINCLAIR BASIC
2.1.1 Code on a direct basis from the pseudocode or flowchart
description in line numbered BASIC statements, module
by module.
2.1.2 Implement the fundamental control structures, used in
their SINCLAIR BASIC versions.
2.2 Debug and Test the Program
2.2.1 Debug the Program. Check the program variables against
your algorithm test. Correct syntax, run time, and logical
errors.
2.2.2 Test the program for further logical errors. Run the
program with sample data.
2.3 Document the Program
For a full documentation, you should:
2.3.1 Produce a programmers’ guide consisting of:
pseudocode
flowchart
variable table or data table
program listing
test results or sample printout.
2.3.2 Detail the steps that producing the program involved.
2.3.4 Write a user guide.
214
PROGRAMMING: SUMMARY OF METHOD IN FLOWCHART FORM
This provides a diagrammatic version of the summary of structured
START
FIND OUT WHAT YOU
HAVE TO DO.
programming:
STATE THE PROBLEM
DRAW A STRUCTURE
DIAGRAM OF HOW YOU
ARE GOING TO SOLVE
THE PROBLEM.
(THE ALGORITHM )
WRITE A
DESCRIPTION OF
THE ALGORITHM.
PRODUCE A
FLOWCHART
CONDUCT A
WALKTHROUGH
ERRORS
?
No
В)
215
CODE INTO BASIC
FIND ERRORS AND
CORRECT
RUN A TEST
ERRORS
?
No
TEST FOR RUN TIME
& LOGIC ERRORS
DOES IT
DO WHAT YOU
WANT IT TO DO?
No
Yes
IS THERE
MORE YOU NEED TO
KNOW ABOUT THE
PROBLEM?
TEST FOR EXCEPTIONS
& GET SOMEONE ELSE TO
TRY IT OUT.
THIS PROBLEM NEEDS
A RE-THINK. PUT
EVERYTHING ELSE ASIDE,
AND DON'T RUSH
ERRORS
2
No
WRITE DOCUMENTATIO
OF HOW IT WORKS,
FLOWCHARTS
AND DOCUMENTATION
OF HOW TO RUN THE
PROGRAM.
END
AN EXAMPLE OF STRUCTURED DESIGN
5
2.
2.
4.
Problem Statement
Write a program that computes and prints the Average or Mean
(M) and Standard Deviation (S) of a collection of N data items.
To compute SŠ use the formula:
Standard Deviation = Sum of Š A of Items) _ (Mean)
Find out what we have to do (research the problem)
We are given most of the information in the question but we are
missing some. It does not tell us how to compute the Mean or
Average. This is given by the formula:
(Sum of all numbers)
Mean = N
We now have all the information, we need to start designing the
algorithm.
What is involved in this problem
The outline procedure we can now define:
a) We have to INPUT the numbers, and
b) Perform two calculations on these numbers. First we calculate
the Mean and then use the Mean value to calculate the
Standard Deviation, then
c) Output the results.
Design the algorithm
This gives the detailed procedure for the steps needed to solve the
problem:
a) INPUT
The numbers are going to be input into an array because they
will be needed twice in the calculation module.
b) 1. Calculate: the Mean —
Add all the numbers in the array and divide by N.
2. Calculate: the Standard Deviation -
Total the squares of all the numbers in the array.
Use the formula to calculate S.
c) Output: the Results —
The results will be printed on new lines with the words
MEAN = and STANDARD DEVIATION =
followed by their values.
217
5. The Tree Diagrams
1. Compute and print
Standard Deviation
and mean
Results
Each of modules 1.1, 1.2 and 1.3 will be subroutines. These will be
called in the appropriate sequence by the main program module.
INPUT
1.14.2 1.143
ASK HOW MANY INPUT N NUMBERS
NUMBERS AND
INPUT N
1.1.1.1
DIMENSION 1.1.3.2
ARRAY ; FOR I-1 TO N,
Y(50) INPUT Y(I)
FIND MEAN AND STANDARD
DEVIATION
1.2.4 1.25.34
^
c
CALCULATE STANDARD
FIND MEAN
DEVIATION
1, 2.1. 2
SUM ALL DIVIDE SUM BY NUMBER
ELEMENTS OF ELEMENTS
FOR I = 1 TO N LET MEAN =
SUM DIVIDED BY N
LET SUM = SUM + Ү(І)
218
1.2.2.
CALCULATE STANDARD
DEVIATION
1.2.2.1; ls£s2. 2.
CALCULATE SUM OF USE FORMULA TO
THE SQUARES CALCULATE STANDARD
DEVIATION
ГЕ ТУРУР PI UM PX
INITIALISE FOR EACH
VARIABLE ELEMENT GET
SQUARE, ADD
TO TOTAL
LET SUM
HN FOR I=] SQR-SUM
TO N SQR«Y(I)
**?
( f ON
SPECTRUM)
Led
OUTPUT
RESULTS
lesel
PRINT "MEAN = ";
MEAN
1.3.2
PRINT "STANDARD
DEVIATION = '5S
219
6.
The Flowcharts
The Main Program
module flowchart:
GOSUB
INPUT
SUBROUTINE
GOSUB
PROCESS
SUBROUTINE
GOSUB
OUTPUT
SUBROUTINE
220
The Input Subroutine
flowchart:
ENTER
CREATE
ARRAY
Y(50)
PRINT
"HOW MANY
NUMBERS?"
INPUT
N
INPUT
NUMBER Y(I)
RETURN
The Processing
Subroutine flowchart:
ENTER
LET SUM
= SUM +
LET SUMSQR
LET SUMSQR
ET S=SQR
(SUMSQR/N)
(
- (MEAN**2) )
SPECTRUM FORMULA
USES 7, NOT **,
RETURN
222
The Output
Subroutine flowchart:
ENTER
PRINT
MEAN
PRINT
"STANDARD
DEVIATION="
PRINT
RETURN
223
7. The Program
ед
The Мат Program Моаше
REM "SDEVIATIDN"
FEM 339 9 3 3 9 ЗЕ ЗЕ ЗЕ C 3 9€ 93639963
жҰМАТМ FROGRAM MOLD жж
REM **INFLUT DATA жж
GOSUE 100
REM **CALCILATE*
GOSUE zoo
REM ##FRINT RESLULTS3*
BOSE 400
= TOF
КЕМ **ENI! MAIN жж
5 ы ЭЕ ЗЕ ЗЕ ЗЕ ЭЕ
7.2 The Input Subroutine Module
95
100
110
120
130
140
SQ
160
170
120
190
КЕМ жж А ЗЕ ЭЕ ЭЕ ЭЕ ЖЕ Ж
X*INFUT SUBROUTINE жж
DIM Y(S05
FRINT “HOW MANY NLMEEFRZ?'":
INFLIT N
FRINT N
FOR Ізі ТОМ
INPUT YLI)
PRINT ҮСІЗ;" "3
NEXT I
RETURN
REM *#*#END INFUT SUE жж
аз
7.3 The Calculation Module
200
210
220
220
240
220
260
270
290
290)
300
210
—O
FEM 339 3 € € 3C 9€ 9€ 9€ 9€ 9€ 3€ 303030 3E 3E HE
XxCOLCULATION SUE жж
SUM=0
FOR Ісі ТОМ
LET SUM=SUM+Y C1)
NEXT I
LET MEAN=SUIM/N
LET СИМЕПК-О0
ЕПЕ Ісі TON
LET ФШИМЕОПЕ-СИМФОЕ-һ
(Y (I) X 2
NEXT I
LET $= Sik
(MEAN жж
ЕЕТМЕМ
LET
[ ^ Spectrum]
2⁄2
ССӘПМЕШЕ/М2-
29)
FEM **END CALC ‘Sue мен
JC 3 3C 3C 30 3636 Ж 9C EE EE
7.4 The Output Module
400 REM 33939 9c X X 3€ 9€ 3C € 9€ 9€ 3€ EHH
#*H0UTFUT SUBROUTINE жж
410 PRINT
420
FRINT "МЕАМ-“?МЕАМ
430 PRINT
224
440 PRINT “STANDARD DEVIATION
450 RETURN
460 REM **END OUTPUT SUB жж
333€ CICERO JEDE E EXER ЭН
8. Documentation
1) This program will compute and print the Mean and Standard
Deviation of a collection of data items (numbers).
2) It allows for a maximum of 50 items to be entered. You can
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
limit of the computer's handling capacity. This is large — you
will not exceed it.
4) To run the program key in RUN, and enter numbers one at a
time, presing NEWLINE (ENTER) after each one has been
keyed in.
Sample run to find Mean and Standard Deviation of 30, 31,
22, 5, бу 7, 30, 12. 22, 3:
HOW MANY NUMBERS ? 10
20 31 325 6 7 10113 27 5
MEAN = 16.4
STANDARD DEVIATION = 11.45603
Exercise
The example program to compute and print the standard deviation of a
set of data items does not include a pseudocode description of the
algorithm, and the documentation process is incomplete in other ways
too.
i
2,
Complete the programming procedure by doing the following:
Write out a pseudocode description of the algorithm.
Perform a pre-coding walk through, checking the values of
the variables, counters and expressions for each subroutine
module.
Key in the program and debug it.
Insert breakpoints in each subroutine and perform a program
trace. Insert PRINT statements to print out values of
variables, counters and expressions.
Obtain a program listing from the printer and run the
program for a sample set of data. Keep a copy of the printer
output.
Document the program fully in your notebook.
225
SECTION P: THE CHARACTER SET AND CODES
Pi: The ZX81 Character Set and Codes
CODE/CHR$ CODE/CHR$
Ü - K] 49 L
1 F] 50 M
E ГЛ 51 N
3 = 52 O
4 kl 53 P
5 D 55 r0
от 55 R
7 P 56 S
o B 57 ў
9 ШЫ 58 U
uw m 59 V
11 n 60 W
12 £ 61 x
13 $ 62 Y
14 : 63 2
15 ? 64 RND
16 ( 65 INKEY£
17 66 PI
18 67
19 68
20 - 69
21 4 70
22 = 71
23 * 79
24 / 73
95 74 МОТ
26 75 USED
27 | 76
28 0 77
29 1 78
30 2 79
31 2 80
32 + 81
33 5 82
34 6 83
35 7 84
36 8 85
37 9 86
38 A 87
39 B 88
40) С 89
41 D 90
42 E 91
43 F 99
44 * 93
45 H 94
46 I 95
47 J 96
48 K 97
226
CODE/CHR$
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
NOT
USED
+ Å <>
GRAPHICS
EDIT
NEW LINE (ENTE
RUBOUT (DELET
K/L Mode
FUNCTION
NOT
USED
NUMBER
CURSOR
БЕЙБЫТ” лы | ТЫШ
inverse ``
Inverse £
Inverse $
Inverse :
Inverse ?
Inverse (
inverse )
inverse >
CODE/CHR$
147 inverse <
148 inverse =
149 inverse +
150 inverse —
151 inverse *
152 inverse /
153 inverse ;
154 inverse ,
155 inverse .
156 inverse 0
157 inverse 1
158 inverse 2
159 inverse 3
160 inverse 4
161 inverse 5
162 inverse 6
163 inverse 7
164 inverse 8
165 inverse 9
166 inverse À
167 inverse B
168 inverse C
169 inverse D
170 inverse E
171 inverse F
172 inverse G
173 inverse H
174 inverse I
175 inverse J
176 inverse K
177 inverse L
178 inverse M
179 inverse N
180 inverse O
181 inverse P
182 inverse О
183 inverse R
184 inverse S
185 inverse T
186 inverse U
187 inverse V
188 inverse W
189 inverse X
190 inverse Y
191 inverse Z
192 тар
193 АТ
194 ТАВ
195 (МОТ USED)
196 CODE
197 VAL
198 LEN
199 SIN
200 COS
201 TAN
202
ASN
CODE/CHR$
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
227
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
ACS
ATN
LN
EXP
INT
SOR
SGN
ABS
PEEK
USR
STR$
CHR$
NOT
жж
OR
AND
< =
> =
<>
THEN
TO
STEP
LPRINT
LLIST
STOP
SLOW
FAST
NEW
SCROLL
CONT
DIM
REM
FOR
GOTO
GOSUB
INPUT
LOAD
LIST
LET
PAUSE
NEXT
PI
PRINT
PLOT
RUN
SAVE
RAND
IF
CLS
UNPLOT
CLEAR
RETURN
COPY
Of the non-printing characters, those that are used, but print a question
mark, are the following:
116-121 inclusive
126-127 Inclusive
(NOTE: 5 1s the question mark.)
192 is the Quote image character, which prints a single quote. The
character set is coded with the numbers 0 to 255. This, you may recall,
is the number of values held in a single byte. The characters can thus
be accessed with a single byte identification code. This is also the
reason why some codes are listed, but have no character associated
with them. The same is true of the Spectrum character set, which
follows.
P2: Spectrum Character Set and Codes
Code Character Code Character Code Character
0 35 ж 70 Е
1 36 $ 71 G
2 37 % 72 H
3 not used 38 & 73 I
4 39 | 74 Ј
5 40 ( 75 K
6 PRINT comma 41 ) 76 ІР
7 EDIT 42 it M
8 cursor left 43 + 78 N
9 cursor right +} ; 79 О
10 cursor down 45 — (minus sign) 80 P
11 cursor up 46 ; 81 о
19 DELETE 47 / 82 R
13 ENTER 48 0 83 5
14 number 49 1 84 d
15 not used 50 2 85 U
16 INK control 51 3 86 V
17 PAPER control 52 4 87 W
18 FLASH control 53 5 88 x
19 BRIGHT control 54 6 89 Y
20 INVERSE control 55 7 90 Ж
21 OVER control 56 8 91 [
22 AT control 57 9 92 /
23 TAB control 58 : 93 ]
24 59 š 94 f
25 60 < 95 aa
26 61 = 96 £
27 not used 62 > 97 a
28 63 ? 98 b
29 64 @ 99 C
30 65 A 100 d
31 66 B 101 e
52 space 67 C 102 f
33 ! 68 D 103 g
34 69 Е 104 h
228
Code Character Code Character
105 i 159 (p) 213 MERGE
106 j 160 (q) 214 VERIFY
107 k 161 (r) 215 BEEP
108 l 162 (s) 216 CIRCLE
109 m 163 (t) 217 INK
110 n 164 (u) 218 PAPER
111 о 165 RND 219 FLASH
112 p 166 INKEY$ 220 BRIGHT
113 q 167 PI 221 INVERSE
114 r 168 FN 222 OVER
115 S 169 POINT 223 OUT
116 t 170 SCREENS 994 LPRINT
117 u 171 ATTR 295 LLIST
118 у 172 АТ 226 STOP
119 w 173 TAB 227 READ
120 x 174 VAL$ 228 DATA
121 y 175 CODE 229 RESTORE
122 2 176 VAL 230 NEW
123 { 177 LEN 231 BORDER
124 | 178 SIN 232 CONTINUE
125 } 179 COS 233 DIM
126 ~ 180 TAN 234 REM
127 © 181 ASN 235 FOR
128 т 182 ACS 236 GO TO
129 а 183 ATN 237 GO SUB
130 P| 184 LN 238 INPUT
131 = 185 EXP 239 LOAD
132 n 186 INT 240 LIST
133 e 187 SOR 241 LET
134 a, 188 SGN 242 PAUSE
155 ШТ 189 ABS 243 NEXT
136 m 190 PEEK 244 POKE
137 =" 191 IN 245 PRINT
138 B 192 USR 246 PLOT
139 p 193 STR$ 247 RUN
140 == 194 CHR$ 248 SAVE
141 all 195 NOT 249 RANDOMIZE
142 L. 196 BIN 250 IF
143 Kj 197 OR 251 CLS
144 (a) 198 AND 252 DRAW
145 (b) 199 = 253 CLEAR
146 (c) 200 = 254 RETURN
147 (d) 201 <> 255 COPY
148 (e) 202 LINE
149 (0) 203 THEN
150 (g) 204 ТО
151 (Һ) 205 STEP
152 (i) 206 DEF FN
153 (j) 207 CAT
154 (k) { user 208 FORMAT
155 (1) ( graphics 209 MOVE
156 (m) 210 ERASE
157 (n) 211 OPEN #
158 (o) 212 OPEN #
229
There is an important point to be noted with regard to the Spectrum
character set, which does not apply to the ZX81. Among the Spectrum
character set, codes 16 to 23 are control characters which are
used to specify certain attributes of the character cell for printing
purposes. These require arguments within a certain range (0 to 9 for
colours, or 0 and 1 for on or off, etc.). Codes 6 to 14, 22 and 23 are also
control characters for printing and editing. The problem with using
CHR$ with these control characters is that they can be used in
programs, and are then called by inserting, e.g. CHR$ 20, followed by
the argument. This means that a simple call to PRINT one of these
CHRS will cause the computer to think it is being given an instruction,
and the syntax demands an argument. If this is not forthcoming after
the CHR$, or the argument is in the wrong range, an error message
results when the Spectrum cannot do what it thinks it is being asked to
do.
Some of these control characters, however, for colour (dealt with in
Section W), and also for print control can be usefully placed in
programs. If we take CODE 8, which is a cursor control character, we can
write a program like this:
10 PRINT ‘‘SIN”’;
20 PAUSE 50
30 PRINT CHR$ 8;CHR$ 8; “АСКЕПр”
The CHRS 8 instructions in line 30 backspace the cursor twice, re-
setting the PRINT position, so that “АСКЕР” overprints “ТМ”, The
upshot of this is that we cannot print out the character set of the
Spectrum completely, but must start from CODE 24, after the control
characters. This is no great loss, since they print (or would print, if you
could get them to!) either a space or a question mark. Remember these
control characters, though, as they can sometimes be useful in a
program, although mostly it is far more convenient to use the BASIC
instructions. For example, we can use CHR$ 23 instead of TAB:
10 PRINT CHR$ 23;10; “ТАВ CONTROL"
This is not an advantage over using TAB! However it does show how
these characters are used by the computer- it inserts them into
program listings where the control function (e.g. T'AB), has been used.
TAB itself does not have a control function, and needs CHR$ 23 placed
after it to work.
P3: Characters
The ZX81 and Spectrum have a character alphabet consisting
of 256 items which include numeric characters, alphabetic
characters, keywords, instructions, commands, operators,
graphics and inverse graphics symbols and other symbols. As
230
seen in the tables in the previous Units, of these 256 items
some are not used at all, and some are non-printing (i.e.
control characters).
In Appendix III the ZX81 character codes are laid out by
character type and their position on the keyboard. Spectrum
codes are referenced alphabetically in Unit W1.
The CODE (occupying a single byte) identifies each
character uniquely for input/output purposes – i.e. input
from the keyboard and output to the screen or printer.
The ZX81 has a non-standard character set unique to the machine.
The Spectrum has a character set in which the characters used have the
codes of the ASCII character set (an internationally agreed standard)
for the most part. Non-standard ASCII characters are the symbols for
£ and ©, and the graphics characters.
Р4: CHR$ and Code
The purpose of the instructions CODE and CHR is to convert from
the code to the character and vice versa. The ZX81 and Spectrum have
different character sets and codes, but the instructions work in the
same way.
CODE
CODE is a function that takes a character or string and gives
as a result the numeric code that the character (a single
letter string, or first character in a string) cor-
responds to. For example:
CODE S gives 56 on the ZX81, 83 on the Spectrum
CODE “ABCD” gives CODE А, 38 on the ZX81, 65 on the
Spectrum
CODE X$ gives the code of the first (or only) character
in X$
CODE D$(3) gives the code of the third character in D$.
CHR$
CHR$ (N), where N is a numeric expression with a value
0 < = N < = 255, is a function that gives as a result the single
character whose code is N. CHR$ does the opposite of CODE.
For example:
CHRS (A + B + C)
CHRS$ (X/Z)
CHR$ (INT(RND * 255))
CHR$ 36 gives 8 on the ZX81, $ on the Spectrum
231
To see the inverse relationship of CHR$ and CODE, key in the
following as direct commands:
PRINT CHR$ 50 will print M on the ZX81, 2 on the
Spectrum
PRIN T CODE 52" ° will print 30 on the ZX81, 50 on the
Spectrum
PRINT CODE CHR$ 50 will print 50
PRINT CODE “A” will print 38 on the ZX81, 65 on the
Spectrum
PRINT CHR$ 38 will print A on the ZX81, & on the
Spectrum
PRINT CHR$ CODE “А” will print A
The next program will print out all the characters used on the ZX81.
10 FOR Е=0 TO 255
20 SCROLL
20 PRINT Е, CHR F
40 NEXT F
For the Spectrum, as noted above, we must miss out some CHR$ and
line 20. Line 10 must read FOR F = 24 TO 255. Key it in and run it.
Add:
3:9 LPRINT F; TAE à: CHF F
to get a printer listing. A better program (since it uses less printer
paper!) but one with an expression you won't understand until we
cover logic, is this one:
10 REM ##CHARACTER ЕТЖ
20 LFRINT "CODE/CHE$": TAB 10;
"CODE/ICHR$":; TAB zZO:"CODE/CHRE$"
30 FOR Е=0 To 85
40 LFRINT F? ТАЕ 4; CHES F;
ТАБ 10;F+sé; TAE 14; CHES$
CF+ie); ТАЕ 20% (F+172 AND
F+172<25693; TAE 24; CHES
(F+17Z AND Е+172<256)
ou NEXT F
Use these lines for the Spectrum version:
20 FOR Ғ-24 To 77
40 LPEINT F; TAE 4; CHES F;
TAE 10:F*77: ТАР 14: CHES
(Е%773; TAB 20:Е+154; TAE 24:
CHES (F+154)
Exercises
1 Key in and run the following programs. You may find some
surprising results, due to the control characters, on the
232
Spectrum. No harm will be done.
(a) 10 FOR F = 0 TO 255 (Spectrum: FOR Е = 24 ТО 255)
20 PRINT CHRS F;
30 NEXT F
Notice that the word characters print with the spaces that
your computer automatically inserts in program lines.
(b 10 RAND
20 PRINT CHR$ INT (128* RND + 128)
30 GOTO 20
(c) 10 INPUT A$
20 PRINT A$, CODE A$
30 GOTO 10
(d) 10 PRINT “INPUT STRING OF 6 CHARACTERS"
20 INPUT A$
30 FOR F =1 TO 6
40 PRINT A$(F), CODE АЖЕ)
50 NEXT F
(e) 10 RAND
20IF INT (RND*2)=1 THEN PRINT CHR$ INT
(RND*128)
30 IF INT (RND*2)-0 THEN PRINT CHR$
(INT(RND*128) + 128)
40 GOTO 20
(f 10 RAND
20 LET A$ = CHR$ INT (RND* 255)
30 SCROLL
40 PRINT CODE A$, A$
50 GOTO 20
In this last program, Spectrum owners can omit line 30 and
simply respond to the Scroll? prompt by pressing ENTER.
Write a program that given a number (code), will check that
0 < = code < = 255, and will print out the character. On the
Spectrum, the program should print “CONTROL
CHARACTER” if the CODE is between 6 and 23.
Write a program that when given an alphabetic character as an
input will print out the next in the alphabet. If the character
input was ‘Z’ then ‘A’ should be printed.
SECTION О: GRAPHICS
Q1: More Printing
Since we dealt with the PRINT instructions, you have been introduced
to other statements that can be used with the PRINT statements for
format and manipulation.
Loops are of use in printing. For instance we can set up an empty
string with 32 spaces and use it to clear different areas:
20 LET A$ = ‘‘(32 врасев)”
ЖІТІ
ӘЛГІ
100 FOR Х-11 ТО 21
110 PRINT АТ X, 0; A$
120 NEXT X
will clear the bottom half of the screen, and we could use it repeatedly,
as a subroutine, if we wished. We then avoid using CLS, which would
mean re-printing anything that we wanted to keep on the screen.
Except for numbers, anything we wish to print must be in the form
of a string, either between quotes, a string variable, part of a string
array, or a CHR$(X) instruction.
Obviously any operations or functions used with strings may be
useful, and in the same way as:
10 PRINT (1 + 3)
prints 4, we can use:
20 PRINT A$ (X TO Y)
to extract the desired characters of A$.
Enter and run this program
10 LET A$-"ABRACADAEEA"
20 LET L= LEN ñ$
30 FOR X=1 TO 6
40 PRINT TAE 10+X;ASCX ТО
Lela}?
20 NEXT X
Remember that numbers can always be treated as strings, and vice
versa, using VAL and STR$. This is often useful for formatting
numbers. For example, with a number X, this program:
234
10 LET A$="0000"
20 LET BS= STRS X
ЗО FOR F-1 Tü 4
40 IF LEN B$4F THEN GOTO 70
20 LET A$(CFD-E$CF?
&O NEXT F
70 PRINT A$
will print (һе first four digits of any number, ог follow (һе number with
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
are in the original.
Code the program in with A$ = (4 spaces)’ and try it. As it is, you
wil have to enter X as a direct command (LET Х= 123, then
NEWLINE/ENTER) and then use GOTO 10, since RUN would
clear the variables (in this case, the value of X you have just entered).
This principle can be expanded. Here is an example of a subroutine
used to justify numbers and print them in the position required for the
decimal places to be in the same column:
10 REM "FORMAT"
20 REM *FORMAT SUBROUTINE For
*NUMEERS ж
30 REM #COLUMN NUMBER ЕСЕ +
*#DECTMAL РАСЕ +
40 LET t=12
S0 REM *INITIALISE GOSUB*
ео LET ҒОЕМАТ-УООО
70 REM *NUMBER*
во INPUT М1
7O REM #*#INITIALIZE NUMEER*
100 LET N=N1
110 GOSUE FORMAT
200 REM *MORE NUMBERS +
210 FOR ісі TQ 4
220 INFUT N
220 GOSWE FORMAT
240 NEXT L
2020 GOTO 999
2770 REM HHH EEE
Xe SIE ROUT INE жж
7000 LET N$- STF$ М
9010 LET Р=0
7020 FOR F=1 TO LEN МФ
ЭО20 IF МФ(ҒО-"." THEN LET F-F
7040 NEXT F
2050 IF F=1 THEN LET N$="O"+N%
7060 LET F=F+(P=1)
7070 IF F=0 THEN LET F= LEN N$+1
7020 FRINT TAE (C-F+1)7N%
vOTO FETLIFN
7100 REM ЖЖЕМПЕПЕ ЕЕ € 3€ 9€ 3€ 9€ 3€ 3€
92999. SIUF
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
235
9030 sets a marker for a decimal point in the first letter of the number
string, and adding а 0 is done in line 9050. 9060 uses the logical value of
(Р = 1) to add 1 if a zero was added, i.e. if P = 1 is true. This will be
explained in the Section on Logic, but the line is equivalent to IF P = 1
THEN LET P = 2. Check this by trying both versions of the line. Line
9070 adjusts the length of the string if there is no decimal place found
(i.e. if the number was an integer). 9080 prints the number in the
correct column.
The next program shows a simple way of tabulating results, using a
loop:
10 PRINT “МО.”;ТАВ 4;‘SSOQUARE”’; TAB 12;
"CUBE -TAB 20“ RECIP”
20 FOR N=1 TO 10
30 PRINT N;TAB 4;N*N;TAB 12;N**3; ( 1 on Spectrum)
TAB 20;1/N
40 NEXT N
NO. SQUARE CUBE КЕСІР
1 1 1 1
2 4 8 0.5
3 9 27 0.33333333
4 16 64 0.25
3 25 125 0.2
6 36 216 0.16666667
4 49 343 0.14285714
8 64 512 0.125
9 81 {29 0.11111111
10 100 1000 0.1
It is important to remember that numbers are output with 8 figures and
allow the appropriate space. An alternative is to decide how many
figures you want and use the INT function.
For example, we can replace 1/N in line 30 by INT(1E4*(1/N) +
.5)/1E4 , and get a printout like this:
NO. SQUARE CUBE КЕСІР
1 1 1 1
2 4 8 0.5
3 9 87 0.3333
4 16 64 0.25
5 25 125 0.2
6 36 216 0.1667
7 49 343 0.1429
8 64 212 0.125
9 81 729 0.1111
10 100 1000 0.1
236
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
used INT(10000*(1/N) + .5)/10000, since using 1E4 gives four d.p.,
1E3 three d.p., etc. In using this, be careful with the bracket placing,
as INT(1E4*(1/N)) + .5/1E4 will not round! Try both the correct and
Incorrect versions in the program.
You should note that:
With PRINT TAB C; or PRINT AT L,C instructions L апа С
can be dependent or calculated variables. For example:
PRINT TAB (X*2)/3;
PRINT AT 10, 20/X;
Try these:
10 FOR X=1 TO 5
20 PRINT AT X, X. * 2:X
30 NEXT X
10 FOR X -1 TO 5
20 PRINT TAB X * 2X
30 NEXT X
An automatic INT function operates with PRINT AT
instructions.
For PRINT AT (L), (C); if (L) and (C) > nand < n +1,
(1) and (C) = n
For example:
PRINT АТ 3/2, 10.5;°°...”’
equals PRINT АТ 1,10;°°...”’
Try this:
10 FOR X - 1 TO 10
20 PRINT AT X, X/2; X
30 NEXT X
The AT function rounds down, exactly as if we had used PRINT AT
X, INT (X/2); X as line 20.
PRINT TAB(N), where N is non-integer, rounds to the nearest
integer.
TAB N, where N is between X and X + 1, gives TAB X if
N< X+ .5 and TAB X+ 1 if N2- X + .5. For example
TAB (1.3) =TAB 1
TAB (1.5) = TAB 2
237
To see the difference, RUN both these programs, use COPY to get a
printout, and compare the results.
10 FOR X=0 TO 10
20 PRINT TAB X/2;:X
30 NEXT X
10 FOR Х=0 TO 10
20 PRINT ТАЕ INT (X/2);X
30 NEXT X
You must also watch for arithmetic mistakes in calculating the PRINT
position. For instance:
10 FOR X=0 TO 10
ZO PRINT TAB 20/Х%Х
20 NEXT X
is not going to get past line 20 the first time round! Why?
This next example illustrates the use of PRINT AT to give changing
display.
A die is rolled and we wish to display its value for each of a series of
throws. In addition we require cumulative values after each throw.
Thus each time line 90 is reached it overprints line 70 and vice versa.
Similarly line 120 overprints itself after each throw.
> REM "DICEROLL"
10 PRINT "NUMBER OF THROWS?"
го INPUT X
20 DIM NCE)
sm CLS
40 PRINT АТ 2.27 "CUMULATIVE VA
LUES"
o0 FRINT АТ 10,47 "1929639639696
43x d T a жан
60 FOR M=1 TO X
é5 PRINT AT 1:3; "THROW"? ТАЕ 1
4; "VALUE"
70 PRINT АТ 32107 "ж". "ж"
SO LET ñ= INT (ёж RND +1)
20 PRINT АТ 3:103MsA
100 LET NCA =NCAI+1
110 FOR Есі TO é
120 PRINT AT 12:4*E;N(B)
120 NEXT Б
140 МЕХТ М
(М.В. Choose a relatively small value for X (say 24) or the program
will take a long time to run.)
238
Exercises
1 Modify the FORMAT subroutine to round the number to 3
decimal places before determining the print position.
2 Modify your result for the exercise above to print zeros for any
decimal place not filled.
3 Write a program that displays the result of throwing three dice,
displaying the result for each die, and the total value for each
throw. Overprint the last result with each new one, and store the
total values resulting. After the specified number of throws,
derive the average value for a throw.
Q2: More Plotting
Although the definition of the graphics on the ZX81 is low, the
computer has the capacity to draw useful graphs, and most graphics
processes can be illustrated. This is a program that draws a line
between two specified points:
10 INPUT Xl
20 INPUT Yl
30 INPUT X2
40 INPUT Y2
50 LET X=X(2) -X(1)
60 LET Y=Y (2) -Y(1)
65 LET A=(X AND ABS X>=ABS Y) +
(Y AND ABS X
FOR V =n TO m [STEP p]
[]
NEXT V
TRIG FUNCTIONS
SIN n
COS п
TAN n
ASN n
ACS n
ATN n
NUMERIC FUNCTIONS
EXP n
LN n
SOR n
INT n
ABS n
SGN n
PI (m)
STRING FUNCTIONS
LEN s
CHR$ n
CODE s
STR$ n
VAL s
+
EXPRESSIONS
PRIORITY
12 ()
11 any function
10 жж
9 -в
8 ж
?4
6 +-
5 -,<>,<,>,<«,>-
Dimensions array n by m (numeric), n strings of
length m if string
Random number seed
Function returns a random number n. f = n<1
Transfers control to line n
Go to Subroutine at line n
Return from subroutine to line after last GOSUB
If e is true THEN statement s is done, if e is
false then s is not done. For e see expressions.
Evaluates as TRUE = 1, FALSE = 0
V is any single letter control variable.
m,n,p any numeric expressions. STEP 1 is
assumed if STEP not specified
Increments V by STEP. Goes to next line if
V>m (m2n) or V&m (n2m).
Sine n
Cosine n
Tangent n
Arc Sine n (ARCSIN on keyboard)
Arc Cosine n (ARCCOS on keyboard)
Arc Tangent n (ARCTAN on keyboard)
n evaluated as radians
Exponent n or е"
Log. nor ln n
Square root of n
Integer of n (rounds down)
Absolute value of n
1 if n is positive, 0 if zero, — 1 if negative
3.1415927
Length of string s
Character of code n (single character string)
Code of first character in string s
Convert numeric expression to String
Convert string to numeric expression
String concatenation
bracketed expressions
functions
exponentiation
unary minus
multiplication
division
addition & subtraction
equality & inequality
478
4 NOT
3 AND
2 OR
ZX Spectrum Basic Summary
CONVENTIONS
n, m or p
5
е
V
[ ]
logical inversion
logical AND
logical OR
numeric expressions
string expression
expression (string or numeric)
variable name
statement
indicates an optional item
Numeric variables are first character a letter then any alphanumeric characters.
String variables are a letter followed by $.
OPERATING COMMANDS
BREAK
CLEAR
CLEAR n
CONT
DELETE
EDIT
ENTER
GRAPHICS
LOAD s
LOAD s CODE n,m
LOAD s DATA V()
MERGE s
NEW
RUN [n]
SAVE s
SAVE s LINE n
SAVE s CODE n,m
SAVE s SCREEN $
SAVE s DATA V()
STOP
VERIFY s
VERIFY s CODE n,m
VERIFY s DATA V()
OTHER INSTRUCTIONS
BIN n
DATA el, ЖЗ,
DEF FN
interrupts operation e.g. execution, printer
clears variables
changes position of RAMTOP
continues execution after BREAK or STOP
allows deletion of character
allows editing of current line
line entered into program
puts into graphics mode
clears program and existing variables and loads
program specified from tape. (string may be ‘‘”’
in which case the first program is loaded)
loads m bytes into memory starting at address n
loads specified array (string or numeric) into
memory
merges program s with the one already in
memory
clears program and variables
runs program [starting at line n]
Saves program and variables on tape
saves program so that a LOAD is automatically
followed by a GOTO n
saves m bytes starting at address n
saves the picture on tape
saved specified array (string or numeric) on tape
stops program execution
verifies that program specified has been saved
on tape
verifies bytes specified have been saved on tape
verifies array specified has been saved on tape
puts binary number n into decimal
separates multiple statements on a line
gives data items within a program
user-defined function definition. It must be
479
FN
DIM V[$](n[,m])
FOR V =n TO m [STEP p]
NEXT V
GOSUB n
RETURN
GOTO n
IF e THEN
IN n
OUT n,m
LET VI$] = е[$]
PAUSE n
PEEK n
POKE n,m
READ У1[$], V2I$], ...
USR n
GRAPHICS
followed by the name (single letter) of the string
or numeric function and the definition - e.g.
FNa(x,y,z)=xP3+y$44+z45
calls up the user-defined function. Arguments
enclosed in brackets — e.g. FNa(3,5,7)
dimensions array V. Numeric arrays of n rows
[and m columns]. String array of n strings each
of length m characters. Multi-dimension arrays
possible
V a single letter, initiates a loop
V a single letter, completes loop
go to subroutine at line n
returns from subroutine to main program
transfers control to line n
executes statement when the condition is met.
(There may be several numeric and logical
conditions)
returns the byte read from I/O port n
writes value m to I/O port n
assigns value e to variable V
makes program wait a specified time (n = 0 waits
for ever, n=1 to 65535 waits n/5@ seconds in
UK and п/60 seconds in US)
returns the value stored in the memory location
n
stores value m in memory location n
allocates variables the values specified in DATA
statements.
calls the machine-code routine starting address n
22 lines with 32 columns available.
Each character cell consists of 8 by 8 pixels.
256 horizontal points and 176 vertical points.
CIRCLE n,m,p
DRAW n,ml,pl
PLOT n,m
POINT (n,m)
COLOURS:
- black
— blue
— red
- magenta
green
— cyan
— yellow
— white
- O: сл > Ó rO в
|
draws а circle centre (n,m) and radius р
draws line [arc] from previous specified point to
a point relative n horizontal and m vertical
[turning through angle p radians (anticlockwise
if p positive)]
Plots a pixel
@< = n< = 255 horizontal
0< = m< = 175 vertical
returns 0 (paper colour) or 1 (ink colour) of the
pixel (n,m)
480
Picture is divided into 768 (24 lines of 32 columns) character cells.
ATTR (n,m)
BORDER n
BRIGHT n
FLASH n
INK n
INVERSE n
OVER n
PAPER n
SOUND
BEEP n,m
INPUT/OUTPUT INSTRUCTIONS
CLS
COPY
INKEY$
INPUT VI$]
INPUT LINE V$
LIST [n]
LLIST [n]
LPRINT [е][,е][;е]ГТАВ n]
PRINT [elL,el[;elLATp,ml][ TAB m]
TRIG FUNCTIONS
ACS n
ASN n
ATN n
COS n
SIN n
TAN n
(n evaluated in radians)
NUMERIC FUNCTIONS
ABS n
EXP n
INT n
gives colour attributes of the character cell (n, m)
@< = n< = 23 lines
0< = m< = 31 columns
makes border specified colour (n = 0 to 7)
controls brightness (n = 0 normal, п = 1 bright,
n = 8 transparent)
controls flashing (n = 0 normal, п = 1 flash, п = 8
no change)
makes ink (foreground) specified colour (n = 0 to
7, n=8 transparent, n = 9 contrast)
controls dot pattern (п= 0 normal, n=1
inverse)
controls overprinting (п= 0 normal, n=1
mixing)
makes paper (background) specified colour
(n = to 7, n = 8 transparent, n = 9 contrast)
produces sound of duration n seconds and pitch
m semitones above (or below) Middle C.
clears the screen
prints out copy of screen on the printer
reads current input character. Does not wait for
key to be pressed.
input numeric [or string] variable from
keyboard
allows string variable to be input without quotes
displays program [starting from line n]
lists program on printer [starting from line n]
prints out on line printer
prints on screen
22 lines @© = p< = 21
32 columns 0< = т< = 31
Arc cosine п
Arc sine n
Arc tangent n
Cosine n
Sine n
Tangent n
absolute value of n
exponential n (i.e. e")
integer of n (rounds down)
481
LN ñ
PI
RAND [n]
RND
SGN n
SOR n
STRING FUNCTIONS
CHR$ п
CODE s
LEN s
STR$ n
VAL s
VALS s
natural logarithm of n (i.e. log n or In n)
n, 3.1415927
random number seed
function returns a random number between 0
and 1
returns 1 if n is positive, 0 if zero, — 1 if negative
square root of n
character of code n
code of first character of string s
returns length of string s
converts numeric expression into string
converts string expression into numeric
converts s to a string expression (strips off
quotes)
PRIORITY see table for ZX81.
482
APPENDIX II
ZX81 Error Codes
Code Meaning
0
Successful completion, or jump to line number
bigger than any existing. A report with code @ does
not change the line number used by CONT.
The control variable does not exist (has not been set
up by a FOR statement) but there is an ordinary
variable with the same name.
An undefined variable has been used.
For a simple variable this will happen if the variable
is used before it has been assigned to in a LET
statement.
For a subscripted array variable it will happen if the
variable is used before it has been dimensioned in a
DIM statement.
For a control variable this will happen if the variable
is used before it has been set up as a control variable
in a FOR statement, when there is no ordinary
simple variable with the same name.
For a numeric INPUT, will occur if non-numeric
input received.
Subscript out of range.
If the subscript is negative, or bigger than 65535
then error B will result.
Not enough room in memory. Note that the line
number in the report (after the /) may be incomplete
on the screen, because of the shortage of memory:
for instance, 4/20 may appear as 4/2.
No more room on the screen. CONT will make
room by clearing the screen.
Arithmetic overflow: calculations have led to a
number greater than about 10,
No corresponding GOSUB for a RETURN
statement.
You have attempted INPUT as a command (not
allowed).
STOP statement executed. CONT will not try to
re-execute the STOP statement, but continues from
next line.
Invalid argument to certain functions.
Integer out of range. When an integer is required,
the floating point argument is rounded to the nearest
integer. If this is outside a suitable range then error
B results.
483
Situations
Any
NEXT
Jumping into a loop.
Any
Subscripted variables
(Lists and arrays)
Substrings
LET, INPUT, DIM,
PRINT, LIST, PLOT,
UNPLOT, FOR,
GOSUB. Sometimes
during function
evaluation.
PRINT, LIST.
Any arithmetic. Division
by zero is common cause.
RETURN. No STOP
statement before
subroutine is common
cause.
INPUT
STOP
SOR, LN, ASN, ACS,
VAL
RUN, RAND, POKE,
DIM, GOTO, GOSUB,
LIST, LLIST, PAUSE,
PLOT, UNPLOT,
CHR$, PEEK, USR
С The text of the (string) argument of VAL does not VAL
form a valid numerical expression.
D (i Program interrupted by BREAK. At the end of any
statement as the program
runs or in LOAD, SAVE,
LPRINT, LLIST or
COPY.
(ii) The INPUT line starts with STOP. INPUT
F . The program name provided is the empty string. SAVE
Spectrum Error Codes
The report has a code number or letter (so that you can refer to the following table), a
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,
statement 1 is at the beginning, statement 2 comes after the first colon or THEN, and
so on.)
The behaviour of CONTINUE depends very much on the reports. Normally,
CONTINUE goes to the line and statement specified in the last report, but there are
exceptions with reports 0, 9 and D.
Here is a table showing all the reports. It also tells you in what circumstances the
report can occur.
Code Meaning
0
ОК
Successful completion, ог jump ќо а line number
bigger than any existing. This report does not
change the line and statement jumped to by
CONTINUE.
NEXT without FOR
The control variable does not exist (it has not been
set up by a FOR statement), but there is an ordinary
variable with the same name.
Variable not found
For a simple variable this will happen if the variable
is used before it has been assigned to in a LET,
READ or INPUT statement, loaded from tape or
set up in a FOR statement. For а subscripted
variable it will happen if the variable is used before it
has been dimensioned in a DIM statement or loaded
from tape.
Subscript wrong
A subscript 1s beyond the dimension of the array, or
there are the wrong number of subscripts. If the
subscript is negative or bigger than 65535, then error
B will result.
Out of memory
There is not enough room in the computer for what
you are trying to do. If the computer really seems to
be stuck in this state, you may have to clear out the
command line using DELETE and then delete a
program line or two (with the intention of putting
them back afterwards) to give yourself room to
manoeuvre with — say - CLEAR.
484
Situations
Any
NEXT
Jumping into a loop is a
common cause.
Any
Subscripted variables
(arrays),
Substrings
LET, INPUT, FOR,
DIM, GO SUB, LOAD,
MERGE. Sometimes
during expression
evaluation.
Code Meaning
5
Out of screen
An INPUT statement has tried to generate more
than 23 lines in the lower half of the screen. Also
occurs with PRINT AT 22,...
Number too big
Calculations have led to a number greater than
about 1055.
RETURN without GO SUB
There has been one more RETURN than there were
GO SUB.
End of file
STOP statement
After this, CONTINUE will not repeat the STOP,
but carries on with the statement after, or next line
after, STOP.
Invalid argument
The argument for a function is no good for some
reason.
Integer out of range
When an integer is required, the floating point
argument is rounded to the nearest integer. If this is
outside a suitable range then error B results.
Nonsense in BASIC
The text of the (string) argument does not form a
valid expression.
BREAK - CONT repeats
BREAK was pressed during some peripheral
operation.
The behaviour of CONTINUE after this report is
normal in that it repeats the statement. Compare
with report L.
Out of DATA
You have tried to READ past the end of the DATA
list.
Invalid file name
SAVE with name empty or longer than 10
characters.
No room for line
There is not enough room left in memory to
accommodate the new program line.
STOP in INPUT
Some INPUT data started with STOP, or- for
INPUT LINE - BREAK was pressed.
Unlike the case with report 9, after report H
CONTINUE will behave normally, by repeating the
INPUT statement.
FOR without NEXT
There was a FOR loop to be executed no times (e.g.
FOR n=1 TO 0) and the corresponding NEXT
statement could not be found.
485
Situations
INPUT, PRINT AT
Any arithmetic. Division
by zero is common cause.
RETURN. No STOP
statement before a
subroutine is common.
Microdrive, etc,
operations only.
STOP
SOR, LN, ASN, ACS,
USR (with string
argument)
RUN, RANDOMIZE,
POKE, DIM, GO TO,
GO SUB, LIST, LLIST,
PAUSE, PLOT, CHR$,
PEEK, USR (with
numeric argument)
VAL, VAL$
LOAD, SAVE, VERIFY,
MERGE, LPRINT,
LLIST, COPY. Also
when the computer asks
scroll? and you type
READ
SAVE
Entering a line into the
program
INPUT
FOR
Code Meaning
J
K
Invalid I/O device
Invalid colour
The number specified is not an appropriate value.
BREAK into program
BREAK pressed, this is detected between two
statements. The line and statement number in the
report refer to the statement before BREAK was
pressed, but CONTINUE goes to the statement
after (allowing for any Jumps to be done), so it does
not repeat any statements.
RAMTOP no good
The number specified for RAM TOP. is either too big
or too small.
Statement lost
Jump to a statement that no longer exists.
Invalid stream
FN without DEF
User-defined function
Parameter error
Wrong number of arguments, or one of them is the
wrong type (string instead of number or vice versa).
Tape loading error
A file on tape was found but for some reason could
not be read in, or would not verify.
486
Situations
Microdrive, etc.,
operations only
INK, PAPER,
BORDER, FLASH,
BRIGHT, INVERSE,
OVER; also after one of
the corresponding control
characters
Any
CLEAR; possibly in
RUN
RETURN, NEXT,
CONTINUE
Microdrive, etc,
operations only
FN
FN
VERIFY, LOAD or
MERGE
APPENDIX III
ZX81 Character Codes by Keyboard Arrangement
Note: Character codes for both the ZX81 and the Spectrum are listed in order of code
number in Section P, and an alphabetic list for the Spectrum is included in Unit W-1.
1. KEYBORD CHARACTERS
CHARACTER CODE CHARACTER CODE
PLOT 246 NEW 230
UNPLOT 252 SAVE 248
REM 234 DIM 233
RUN 247 FOR 235
LINE2 RAND 249 LINES GOTO 236
RETURN 254 GOSUB 237
IF 250 LOAD 239
INPUT 238 LIST 240
POKE 244 LET 241
PRINT 245
COPY 255
CLEAR 253
CONT 232
CLS 251
LINE4 SCROLL 231
NEXT 243
PAUSE 242
BREAK —
TOTAL 26 Characters.
May be entered when mode cursor appears.
Obtained by pressing desired key.
2. SHIFT CHARACTERS
CHARACTER CODE CHARACTER CODE
EDIT 117 ж 5 192
AND 218 OR 217
THEN 299 STEP 224
TO 223 <= 219
LINE1 «€ 114 LINE2 <> 221
113 >= 220
À 112 $ 13
> 115 ( 16
GRAPHICS 116 ) 17
RUBOUT 119 es 11
487
CHARACTER CODE CHARACTER CODE
STOP 227 : 14
LPRINT 223 қ 25
SLOW 228 ? 15
FAST 229 / 24
LINE: 3 LLIST 226 LINE4 * 23
“. 216 < 19
- 22 > 18
+ 21 i 26
= 20 £ 12
FUNCTION 121
TOTAL 39 Characters.
Obtained by pressing and keys together.
3. LETTER CHARACTERS
CHARACTER CODE CHARACTER CODE
1 29 А 38
2 30 S 56
3 31 D 41
4 32 F 43
LINE 1 5 33 LINE3 G 44
6 34 H 45
7 35 J 47
8 36 K 48
9 37 L 49
0 28 NEWLINE 118
(ENTER)
о 54 SHIFT
W 60 Z 63
F 49 K 61
R 55 C 40
LINE? Т 57 LINE4 V 59
Y 62 B 39
U 58 N 51
I 46 M 50
O 52 27
Р 53 SPACE 0
TOTAL 39 Characters.
May be entered when mode cursor appears.
Obtained by pressing the desired key.
488
4. GRAPHICS CHARACTERS
CHARACTER CODE CHARACTER CODE
F| 1 ЕЕ 8
[4 2 FS 10
Lal 135 ы 9
а) 4 ЫШ 138
ІЛМЕ 1 u 5 LINE 3 E 137
ыш 131 ES 136
= 3 inverse — 150
. 133 inverse + 149
Inverse = 148
ma 129 inverse : 142
М 130 Inverse ; 153
F 7 Inverse ? 143
LINE 2 = 132 LINE 4 inverse / 152
= 6 Inverse * 151
Fg 134 inverse < 147
inverse $ 141 inverse > 146
Inverse ( 144 Inverse , 154
Inverse ) 145 Inverse £ 140
inverse "' 139
TOTAL 36 Characters.
Entered in mode, obtained by pressing |SHIFT| |GRAPHICS | keys.
Character obtained by pressing [SHIFT] [CHARACTER
5. INVERSE GRAPHICS CHARACTERS
INVERSE INVERSE
CHARACTER ` CODE CHARACTER CODE
1 157 Q 182
2 158 W 188
3 159 E 170
4 160 R 183
LINE 1 5 161 LINE2 Т 185
6 162 Y 190
7 163 U 186
8 164 I 174
9 165 О 180
0 156 P 181
489
INVERSE INVERSE
CHARACTER CODE CHARACTER ` CODE
A 166 Z 191
S 184 x 189
D 169 C 168
F 171 V 187
LINE3 G 172 LINE4 B 167
H 173 N 179
J 175 M 178
K 176 | 155
i, 177 128
(SPACE)
TOTAL 38 Characters.
May be entered in mode obtained by keys.
Obtained by pressing desired keys.
6. FUNCTION CHARACTERS
CHARACTER CODE CHARACTER CODE
SIN 199 LN 205
COS 200 EXP 206
TAN 201 AT 193
INT 207 INKEY$ 65
LINE2 AND 64 LINE4 NOT 215
STR$ 213 n(PI) 66
CHR$ 214
CODE 196
PEEK 211
TAB 194
ARCSIN 202
ARCCOS 203
ARCTAN 204
LINE 3 SGN 209
ABS 210
SOR 208
VAL 197
LEN 198
USR 212
TOTAL 25 Characters.
Мау be entered іп [Е] mode obtained by pressing [ SHIFT |
key.
Characters obtained by pressing desired character key.
The mode operates for only one character input.
490
APPENDIX IV
Use of Cassette Tapes
The following information concerns the use of cassette tapes for program storage and
retrieval. Other details of personal tape library practice can be found in the main text.
1
New tapes: Always ‘fast forward’ and ‘rewind’ a tape completely before use for
program storage. This ensures an even winding and tension. If you have the
patience, running the tape one way in ‘play’ mode after fast forward and reverse is
desirable.
Do not use the first 15 or 20 seconds of any tape. Most tape problems of coating
loss and stretch occur in this portion of the tape.
Always rewind tapes fully after use, so as to not leave tape with program data
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
drive wheel until the other moves.
Always replace tapes in the correct library boxes immediately after use. Leave the
label side (if only one label) showing.
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.
Clean the tape-recorder heads after 2 or 3 hours’ running time with a head cleaner
cassette or head cleaner fluid. De-magnetise heads every 10 or 12 hours’ running.
Leave long gaps (at least 20 seconds) between programs, if more than one program
is on a tape. Note the tape counter readings for beginning and end of each
program. Remember that the tape counter is not highly accurate. You can use the
TV screen to find a gap between programs, watching for the thick black lines of a
program load display change to the thin diagonal lines of a ‘blank tape’ display.
Loading problems. These are notes for the ZX81 user. No problems should be
encountered with the Spectrum in this respect. For each individual ZX81/cassette
system, no problems should be encountered with SAVEing and LOADing
programs with the TONE control set high, and the VOLUME at 3/4 volume. The
characteristics of tape recorders vary somewhat, however, and problems may be
encountered in LOADing programs which have been SAVEd on a different
recorder. Here is a sequence to be followed if a program proves difficult to LOAD.
A Set the TONE control for maximum treble (‘High’).
B Set the VOLUME to about three-quarters of the maximum.
С Rewind tape to the beginning.
D Type: LOAD “A” - i.e. any letter/word except the program name.
Press PLAY on the cassette, then NEWLINE (ENTER) on the 7Х81.
When the thin, slightly sloping black lines change to the programs' typical
thick black and white lines, with approximately equal black and white
bands, with the white crossed by vertical black lines:
(a DECREASE THE VOLUME until this changes back to the THIN
lines.
(b Now INCREASE THE VOLUME, noting where the THICK black
and white program lines eventually seem to become more unsettled
or predominantly black.
Also if you listen to the recording you may be able to notice when the
volume is too high and causes distortion.
E Setthe VOLUME midway between these two points (a) and (b).
Rewind tape.
Type: LOAD “(Тһе program name)”.
Press PLAY on the cassette, then NEWLINE (ENTER) on the ZX81.
If the screen suddenly clears before the program should end, this may
mean volume is still too low.
491
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
when BREAK is used.
LOAD again, slightly increasing the volume, after rewinding the tape.
If you cannot get a definite, THICK black and white line pattern even at
full volume then your recorder may not be powerful enough to load from
the signal strength on this specific tape. Test this by using another
recorder, or recorder/ZX system. Once the program has LOADed, SAVE
it on to a tape in your own recorder.
Turn off cassette recorder and take the EAR/MIC leads out of the ZX81
before swapping recorders, or else you may cause the system to crash
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
on the tape because of the electromagnetic field generated by the TV.
492
APPENDIX V
System Variables — ZX81
Notes:
X The system may crash if the variable is poked.
N Poking the variable will have no lasting effect.
S The variable is saved by SAVE.
The number in column 1 is the number of bytes storing the variable. For two bytes,
the first one is the less significant byte. To poke a value M to a two-byte variable at
address N use:
To peek its value, use the expression
Notes
X1
X2
N1
N2
Address
16384
16385
16386
16388
16390
16391
16393
16394
16396
16398
16400
16402
16404
16406
POKE N (M - 256*INT(M/256))
POKE N + 1, INT M/256
PEEK N + 256*PEEK(N + 1)
Name
ERR_NR
FLAGS
ERR_ SP
RAMTOP
MODE
PPC
VERSN
Е PPC
D FILE
DF CC
VARS
DEST
E LINE
CH ADD
Contents
1 less than the report code. Starts off at 255
(for — 1), so PEEK 16384, if it works at all,
gives 255. POKE 16384, N can be used to
force an error halt: N < = 14 gives one of the
usual reports, 15 <=N<=34 or 99
< = N<127 gives an non-standard report,
and 35 < = N < = 98 may disrupt the display
file.
Various flags to control the BASIC system.
Address of first item on machine stack (after
GOSUB returns).
Address of first byte above BASIC system
area. You can poke this to make NEW
reserve space above that area or to fool CLS
into setting up a minimal display file. Poking
RAMTOP has no effect until one of these
two is executed.
Specified K, L, F or G cursor.
Line number of statement currently being
executed. Poking this has no lasting effect
except in the last line of the program.
Q Identifies ZX81 BASIC in saved programs.
Number of current line (with program
cursor).
See Unit O4.
Address of PRINT position in display file.
Can be poked so that PRINT output is sent
elsewhere.
See Unit U2.
Address of variable in assignment.
See Unit U2.
Address of the next character to be
interpreted: the character after the argument
of PEEK, or the NEWLINE (ENTER) at
the end of a POKE statement.
493
16408
16410
16412
16414
16415
16417
16418
16419
16421
16423
16424
16425
16427
16429
16430
16432
16434
16436
16438
16439
16440
16441
16442
16443
16444
16477
16507
X PTR
STKBOT
STKEND
BERG
MEM
not used
DF SZ
5 TOP
LAST K
MARGIN
NXTLIN
OLDPPC
FLAGX
SIRLEN
T ADDR
SEED
FRAMES
COORDS
PR CC
S POSN
CDFLAG
PRBUFF
MEMBOT
not used
Address of the character preceding the §
marker.
See Unit U2.
Calculator's b register.
Address of area used for calculator's
memory. (Usually MEMBOT, but not
always.)
The number of lines (including one blank
line) in the lower part of the screen. See Unit
Q4.
The number of the top program line in
automatic listings.
Shows which keys pressed.
Debounce status of keyboard.
Number of blank lines above or below
picture: 55 in Britain, 31 in America.
Address of next program line to be executed.
Line number to which CONT jumps.
Various flags.
Length of string type
assignment.
Address of next item in syntax table (very
unlikely to be useful).
The seed for RND. This is the variable that
is set by RAND.
Counts the frames displayed on the
television. Bit 15 is 1. Bits @ to 14 are
decremented for each frame sent to the
television. This can be used for timing, but
PAUSE also uses it. PAUSE resets to 0 bit
15, and puts in bits @ to 14 the length of the
pause. When these have been counted down
to zero, the pause stops. If the pause stops
because of a key depression, bit 15 is set to 1
again.
x-coordinate of last point PLOTted.
y-coordinate of last point PLOTted.
Less significant byte of address of next
position for LPRINT to print at (in
PRBUFF).
Column number for PRINT position.
Line number for PRINT position.
Various flags. Bit 7 is on (1) during compute
and display mode.
Printer buffer
NEWLINE).
Calculator memory area; used to store
numbers that cannot conveniently be put on
the calculator stack.
destination in
(33rd character is
494
System Variables — Spectrum
Notes:
X The system may crash if the variable is poked.
N Poking the variable will have no lasting effect.
The number in column 1 is the number of bytes in the variable. For two bytes, the
first one is the less significant byte. To poke a value M to a two-byte variable at address
N use
and to peek its value, use the expression
Address
23552
23560
23561
23562
23563
23565
23566
23568
23606
23608
23609
23610
23611
23612
23613
23615
23617
23618
23620
23621
POKE N(M - 256% INT(M/256))
POKE N + 1, INT M/256
POKE N + 256* PEEK (N + 1)
Name
KSTATE
LAST K
REPDEL
REPPER
DEFADD
K DATA
TVDATA
STRMS
CHARS
RASP
PIP
ERR NR
FLAGS
TV FLAG
ERR SP
LIST SP
MODE
NEWPPC
NSPPC
PCC
Contents
Used in reading the keyboard.
Stores newly pressed key.
Time (іп 50ths of a second - in 60ths of a
second in N. America) that a key must be
held down before it repeats. This starts off at
35, but you can POKE in other values.
Delay (in 50ths of а second - in 60ths of a
second in America) between successive
repeats of a key held down: initially 5.
Address of arguments of user-defined
function if one is being evaluated; otherwise
0.
Stores 2па byte of colour controls entered
from keyboard.
Stores bytes of colour, AT and TAB controls
going to television.
Addresses of channels attached to streams.
256 less than address of character set (which
starts with space and carries on to the
copyright symbol). Normally in ROM, but
you can set up your own in RAM and make
CHARS point to it.
Length of warning buzz.
Length of keyboard click.
1 less than the report code. Starts off at 255
(for - 1) so PEEK 23610 gives 255.
Various flags to control the BASIC system.
Flags associated with the television.
Address of item on machine stack to be used
as error return.
Address of return address from automatic
listing.
Specifies K, L, C, E or G cursor.
Line to be jumped to.
Statement number in line to be jumped to.
Poking first NEWPPC and then NSPPC
forces a jump to a specified statement in a
line.
Line number of statement currently being
executed.
495
Notes
N2
N2
кі ка к ка М)
Address
23623
23624
23625
23627
23629
23631
23633
23635
23637
23639
23641
23643
23645
23647
23649
23651
23653
23655
23656
23658
23659
23660
23662
23664
23665
23666
23668
23670
23672
23675
23677
23678
23679
23680
Name
SUBPPC
BORDCR
E PPC
VARS
DEST
CHANS
CURCHL
PROG
NXTLIN
DATADD
E LINE
K CUR
CH ADD
X PTR
WORKSP
STKBOT
STKEND
BREG
MEM
FLAGS2
DF SZ
S TOP
OLDPPC
OSPCC
FLAGX
STRLEN
T ADDR
SEED
FRAMES
UDG
COORDS
P POSN
PR CC
Contents
Number within line of statement being
executed.
Border colour * 8; also contains the attributes
normally used for the lower half of the
screen.
Number of current line (with program
cursor).
Address of variables.
Address of variable in assignment.
Address of channel data.
Address of information currently being used
for input and output.
Address of BASIC program.
Address of next line of program.
Address of terminator of last DATA item.
Address of command being typed in.
Address of cursor.
Address of the next character to be
interpreted: the character after the argument
of PEEK, or the NEWLINE (ENTER) at
the end of a POKE statement.
Address of the character after the Syntax
error marker.
Address of temporary work space.
Address of bottom of calculator stack.
Address of start of spare space.
Calculator's b register.
Address of area used for calculator's
memory. (Usually MEMBOT, but not
always.)
More flags.
The number of lines (including one blank
line) in the lower part of the screen.
The number of the top program line in
automatic listings.
Line number to which CONTINUE jumps.
Number within line of statement to which
CONTINUE jumps.
Various flags.
Length of
assignment.
Address of next item in syntax table (very
unlikely to be useful).
The seed for RND. This is the variable that
is set by RANDOMIZE.
3 byte (least significant first), frame counter.
Incremented every 1/50th second (U.K.) or
1/60th second (U.S.).
Address of 1st user-defined graphic.
x-coordinate of last point plotted.
y-coordinate of last point plotted.
33-column number of printer position.
Less significant byte of address of next
position for LPRINT to print at (in printer
buffer).
string type destination in
496
Notes
Address
23681
23682
23684
23686
23688
23689
23690
23692
23695
23694
23695
23696
23697
23698
23728
23730
23732
Name
ECHO E
DF CC
DFCCL
S POSN
SPOSNL
SCR CT
ATTR P
MASK P
ATTR T
MASK T
P FLAG
MEMBOT
RAMTOP
P-RAMT
Contents
Not used.
33-column number and 24-line number (in
lower half) of end of input buffer.
Address in display file of PRINT position.
Like DF CC for lower part of screen.
33-column number for PRINT position.
24-line number for PRINT position.
Like S POSN for lower part.
Counts scrolls: it is always 1 more than the
number of scrolls that will be done before
stopping with scroll?
Permanent current colours, etc. (as set up by
colour statements).
Used for transparent colours, etc. Any bit
that is 1 shows that the corresponding
attribute bit is taken not from АТ ТК P, but
from what is already on the screen.
Temporary current colours, etc (as set up by
colour items).
Like MASK P, but temporary.
More flags.
Calculator's memory area; used to store
numbers that cannot conveniently be put on
the calculator stack.
Not used.
Address of last byte of BASIC system area.
Address of last byte of physical RAM.
497
|
a en a E
Е Bd inte Е. BL SANE -
ion wt
Е | т ys - y
rw б» А e ° я Е
* - TIN» Ë "ae © ee et
j* E. g “Hee oa’ 7 90°
та) * gs s тыр “ma =
41 те vv
v vas? dt 27» a Е e" s».
o mE eL = “
ауа B Be
“,.”.-
*(* T i
Tor D
““ “us т game ч © c Z
Е "> 5 9
“p Н & a
e 5
А Р Bn A LIS š - 2 g’
E f LU
Е еу =, E UE Sis
Ae F: og
е. da ^g
s ç =: % J ер с
2 * š 8 4 e
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 Бу the COS and SIN functions in lines 190 апа 200.
Spectrum: For use on the Spectrum change ** to À in line 30, and delete line 160.
Change line 70 to read 70 PAUSE 0. In lines 190 апа 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 a() - SIN A * 3 or whatever the derived function is, and use LET
R = FN a() in line 180. Change the instructions in line 40 to suit.
ле REM “POLAR”
Ба PRINT TAB 8; “4FOLAR ғістат;
TAB а; жж аа ааа”
Зе PRINT ,,"FLOT ROUTINE FOR б
OLAR" , "COORGDINATES ENTER FUMCTI
ON TO^,"BE PLOTTED WITHOUT USE О
Б #4", "(RAISED ТО POWER! FLUMCIIO
M.USE^,"SINsSINsSIN,NMOT SXMsa3,7
OR" “EXAMPLE.USE A FOR ANGLE.“ ,”
YOU MUST ALSO ENTER SCALE “ , "FRc
TGR ANG ANGLE INCREMENT.” -
42 PRINT ,, ENTER EMPRESATON 1
о BE PLOTTED”
S@ INPUT AS
ба PRINT “ENTER ANGLE IMCREMENM
7a INPUT РЯ
aae PRINT “ENTER SCALE ҒОСҒОЭНЭС”
а INPUT 5С
imo СЫЗ
269 КЕМ ЖРБІМТ RAES RHE PLOT
INFORMAT ION +s
i120 FOR F=1 ТО 282
120 PRINT AT 11,Ғ,;”,%”
250 PRINT AT F,28;":”"
142 NEXT F
icd PRINT AT @,32;R3;RT 32,393; “2
.F.2'"; SC; TAB 18; "RMGLE INC. =” ; еЗ
15а FAST
369 REM #ROUND THE CIRCLe, SYES
iFa FOR я-а TO 2xPI STEP OR
i179 REM #EVALUATE FUNCT IQI H
ізе LET R-URL RS
139 REM sNEXT LINES GET J,"
CONVERTED TO POLAR СОБ RM SIM:
COORDINATES, TIMES SCHLE ғостовк,
AND SET WITH CENTRE AT 22 224
290 LET X-204iRxCOS Bs5cCi
200 LET Yz204 iR 351N nasci
210 IF x»60 OR XQ OR Yia OR у
сә THEN сото 252
220 PLOT X,Y
499
=5@ NEXT R
24e сото 292
250 PRINT AT 19,2,’ "OUT оғ BLUT
RANGE. REDUCE SCALE”, “ғастов,”
=68 few NE ‘PRESS B KEY, THEM ЕВР
289 GOTO өе
290 REM #FINISH#
+5.
Set. =; a
ANGLE INC., =, G=
2. Home Accounts
Program allows household expenses for each day for a month to be entered under
various headings, which may of course be changed to suit your needs. Income is
entered, and credits may also be input under any heading. After entries have been
made, a statement of account is derived, which may be printed out. A breakdown of
account by heading can also be printed, and the program and data saved to tape so that
future entries may be added.
The data is stored in string arrays, and these could be increased up to the limits of
memory if a longer period were to be catered for. The program is menu-driven, and all
inputs allow the user to check for errors and re-enter if necessary.
> REM "HOME ACCOUNTS"
10 REM *INITIALISATION*
ZO LET TOTAL=0
ЗО LET I=1
40 LET C=0
50 LET Z$="END "
61 REM жАККАҮ DECLARATION*
е2 DIM D$(3156)
é3 DIM I$(31,1)2
65 DIM АСЗ1›
ее DIM A$C10)
67 DIM (%(631)
ев DIM К%(6315)
&v GOSUB 170
70 REM *MAIN МЕМ
3 CLS
75 PRINT АТ 0%8: "HOME ACCOUNTS
77 PRINT АТ 1%8:"---- --------
80 PRINT АТ 4:10: «MAIN MENU*"
£1 PRINT AT 5%11:"---- ----
500
82 РКІМТ AT 7»2: "А"; АТ 7,103"
TO ADD AN ENTRY"
ӨЗ PRINT АТ 9:2: "5";
FOR ACCOUNT STATEMENT"
84 PRINT АТ 112: "С";
;"FOR CODE BREAKDOWN"
83 PRINT AT 13,2; "X";
;"TO EXIT"
AT 9310:"
AT 11310
AT 13:10
86 PRINT АТ 15%8: "ОРТІОМ 2"
87 INFUT 0%
88 IF 0Ф-"А" THEN GOTO 310
8? IF ü$-"S" THEN GOTO 610
90 IF G$-"C" THEN GOTO 805
100
IF 0%-"Х" THEN STOP
120 PRINT АТ 1538: "UNKNOWN OPTI
ON: "70$
130 PAUSE 100
140 PRINT АТ 15:8;"
150 GOTO 95
160 КЕМ
170 LET
180 LET
190 LET
200 LET
210 LET
215 LET
220 LET
230 LET
240 LET
жж
жж
ЖЖЕХРЕМБЕ CODE
*#INITIALISAT ION
C$cioz"o"
K$(1)="GROCERY"
C$C2)z"P"
{$(2)="PETROL"
C$(s9="C"
K$(3)="CAR REPAIRS“
C$Cc45z"R"
K$(4)="RA TES"
С$%$(5)="М"
250 LET K$(S5)="MISCELLANEQUS"
260 LET C$cé)="I"
270 LET K$(6)="INCOME"
280 RETURN
300 REM #INFUTTING ПАТАж
310 CLS
320 PRINT AT 0:8; "НОМЕ ACCOUNTS
330 PRINT АТ 1:38; "---- --------
350 PRINT АТ 5:57" T
360 PRINT AT 4,2; "ENTER DATE (E
б. 25 NOV: OR PA VEND. ae
FINISH)"
370 INFUT D$(1)
380 IF 0%(1)="" THEN GOTO 370
387 PRINT AT 4927"
386
390
392
)?";
394
395
396
398
IF П%(12-7% THEN GOTO 570
РКІМТ AT 5,5; "DATE: ";D$(1)
PRINT АТ 1035; “СОЕКЕСТ (Y/N
INPUT Q$
IF @$="N" THEN GOTO 250
IF 0% <> "Y" THEN GOTO 394
PRINT AT 10.53"
399 PRINT AT 11557"
501
439
GOSUB 1000
PRINT АТ 16,5; "EXPENSE CODE
INPUT I$CI)
IF I$(I)z"" THEN GOTO 430
GOSUB 2000
» FOR J=1 TO é
IF 1%(12-С%(.1) THEN GOTO 44
NEXT J
PRINT AT 7:95; "UNKNOWN EXFEN
SE CODE: ";I$CID
440
441
442
FAUSE 100
GOTO 410
РКІМТ АТ 739:"EXFENSE CODE:
"PES CJ)
444
)?"
446
447
448
449
460
470
PRINT AT 11:5; "CORRECT (Y/N
INPUT 0%
PRINT AT 11953"
IF @$="N" THEN GOTO 410
IF Q$ <> "Y" THEN GOTO 444
РКІМТ AT 13,53"
PRINT AT 9,9; "AMOUNT (- FOR
EXPENSE) 7"
480
483
487
490
500
22";
510
220
530
932
534
536,
эзе
540
550
560
970
INFUT A$
IF A$="" THEN GOTO 480
PRINT AT 9357"
FRINT AT 9:5; "AMOUNT: “FAG
PRINT AT 13,5; "CORRECT (Y/N
INPLIT Q$
IF Q$="N" THEN GOTO 460
IF 0% 4» "Y" THEN GOTO 510
PRINT AT 12,5; "
PRINT AT 9557"
PRINT AT 7,55"
LET ñ(I)= VAL A$
(ЕТ IsI-*1
LET C=C+1
GOTO 350
PRINT AT 10,3; "00 YOU WISH
ТО SAVE THESE": AT 11,2; "ENTRIES
(Y/N) 7"
575
380
INPUT 0%
IF Q$="N" THEN GOTO 73
589 IF 06 <> "Y" THEN GOTO 575
590
PRINT АТ 10,2;"5ЕТ UP CASSE
TTE RECORDER: WHEN READY PRESS A
NY КЕҰ"
595
596
999
IF ІМКЕҮ% ="" THEN GOTO 595
SAVE “HOME ACCOUNTS"
GOTO 73
600 REM *STATEMENT OF ACCOUNT
902
610 CLS
620 PRINT TAB 5: "ЗТАТЕМЕМТ OF A
CCOUNT"
630 PRINT TAB 5%"-------- -- --
640 PRINT
650 PRINT "DATE": TAB 8% "ТҮРЕ"?
TAB 15: "СК"; TAB 25; "DB"
660 PRINT "eese" TAB Bi "е7
TAB i357 "-<-"3. TAB 257 "=="
670 FOR I=1 TOC
630 PRINT В%(10: TAB 2:1%С12;
690 IF А(12>0 THEN GOTO 720
700 PRINT TAB 25; ABS ACT)
710 GOTO 730
720 PRINT TAB 15;А(1)
730 LET TOTAL=TOTAL+ACI)
740 PRINT
750 NEXT I
793 PRINT TAB 2ОҒ”------ "
755 FRINT "BALANCE"; TAB 20; TOT
766 PRINT AT 2132: "COPY TO PRIN
ТЕК СҮМ) 7"
767 INPUT Q$
768 IF ü$-"N" THEN GOTO 73
769 IF 0% <> "Y" THEN GOTO 767
770 PRINT AT 21,23 "ЗЕТ UP PRINT
ER AND FRESS A KEY"
773 IF INKEY$ ="" THEN GOTO 773
775 PRINT АТ 21927"
780 COFY
790 GOTO 73
S00 REM **BREAKDOUWN OF жж
XACCOUNT BY CODE жж
905 CLS
810 PRINT “STATEMENT OF ACCOUNT
830 PRINT "CODE"; TAB 15% "TOTAL
840 PRINT
250 LET J=1
255 (ЕТ TOTAL=0
860 FOR Ісі TO C
$70 IF I$(I)=C$(J) THEN LET TOT
AL=TOTAL+A(T)
280 NEXT I
990 PRINT K$(J); TAE 15; TOTAL
900 LET J=J+1
910 IF J <= 6 THEN GOTO 855
926 PRINT АТ 2192: "COPY TO PRIN
TER (Y/N? ?"
927 INPUT Q$
928 IF ü$-"N" THEN GOTO 73
929 IF 0% <> "Y" THEN GOTO 927
эзо PRINT AT 21,23 "БЕТ UF PRINT
ER AND FRESS A KEY"
940 IF INKEY$ ="" THEN GOTO 940
503
PIO FRINT AT Z1s27"
veo COPY
990 GOTO 73
1000 REM 33433) )9 9 09 9 ! ) 9 09 X 9 * 99€
X*EXFENSE CODE МЕМІІжж
*#*SUBROUT INE жж
3C EIE ЗЕ ЗЕ ЕЕ ЗЕ ЗЕ ЭЕ ЭЕ ЭЕ ЗЕ ЕЕ EHR
1020 PRINT АТ 7,5;"*ЕХРЕМ5Е CODE
МЕМИ+ :
1090 PRINT AT бұз!” eee m ne
1050 PRINT AT 9*5;"G"; AT 2157"
GROCERY "
1060 PRINT AT 10,93 "Е"; АТ 10,15
т КЕТКЕШ."
1070 PRINT АТ 11:5;"C"3 AT 115915
;"CAR REPAIRS"
1080 PRINT AT 12,5; "Е"; AT 12,15
; "RATES"
1090 PRINT AT 12:5;:"M": AT 13515
; MISCELLANEOUS"
1100 PRINT AT 14,53 "1"; AT 14515
; "INCOME"
1110 RETLIRN
2000 PRINT AT 16,5;"
2010 PRINT AT 14957" "; АТ 14515
2020 PRINT АТ 13,93" "; AT 13315
2050 PRINT АТ 12957" "; AT 12,15
= d
y
2040 PRINT AT 11,5;" "Ó"; AT 11,15
ә 41
y
2050 PRINT AT 10957" "; AT 10,15
= и
,
2060 PRINT AT 9,9:" "; AT 9?,15;"
2070 PRINT АТ 3.93"
2080 PRINT AT 7,93"
2090 RETURN
3. Resval
Program derives the preferred resistor value (i.e. the closest standard resistance) from
inputs of the voltage and current required in a circuit. From these inputs (in volts and
amps) the actual resistance is calculatead by Ohms Law (R = V/I). This value, rounded
to two significant figures, is then used to calculate the value L, 10 to the power L, being
the multiplier for the resistor value. The values stored in the array X(13), entered as
shown in the first program, are then compared with the calculated resistance. The first
value stored in the array which gives a value greater than R is then used to print out the
preferred value for the component. The current and power using a resistor of this value
are then printed. The user may then choose to run the calculation again with different
inputs until the best solution is achieved. This illustrates the basic principle of
computer-aided design (CAD) of circuits, where the derived theoretical values are
modified to suit the actual components available.
504
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
storing the data in an array would be to assign each value of the array X with a LET
statement, or, if using a Spectrum, to place the values in a DATA statement. Both
these methods would eliminate the problem of avoiding the use of RUN.
Spectrum: Change ** to ^ in lines 220, 240 апа 270.
Change line 340 to read 340 SAVE ‘‘RESVAL”’ LINE 10
Delete line 350
As noted, the program could be modified to use the DATA and READ
statements. Insert a line 340 with the data as given below, and insert
215 READ X. Change X(N) to X in lines 220 апа 240.
1@ REM ##RESISTOR VALUES INTO
ARRAY * x
20 REM жы ІМЕЗ EDITED GUT RFTE
R ENTRY OF URLUES ==
ЗӨ REH жжТНЕМ RESURL PROGRAM Е
NTERED xx
да DIM X113? ue
50 LPRINT “ARRAY VALUE
60 LPRINT
TO XA. VL oam
ве LPRINT a te TE
зе INPUT X tL.
18090 LPRINT TAB т;хаз
110 NEXT L
ARRAY VALUE
"ТЕГҮ
отын о
$
“
RRMA KKK KX
май a? uà чн
m
0
19 REM xRESURL x
20 PRINT "RESURL"
48 PRIN! "PROGRAM DERIVES PREF
ERRED VALUE"; ТАБ Ө; “OF RESISTOR
FROM INPUT"; TAB ә; “VOLTAGE AND C
URRENT VALUES"
50 PRINT _ >
$09 PRINT “PREFERRED UALULECS STO
RED IN ";THB е; “ARRAY . DD NOT REUN
PROGRAH.USE"'; TRB в; “сото 100."
79 PRINT “SAVE WITH GOTO 340.'
ба PAUSE быб
180 PRINT SYOLTAGE ws
ise PRINT TAB 128;U;" VOLTS"
140 PRINT “CURRENT т”;
160 PRINT TAB 12,;,1;" AMPS”
170 LET R-INT (.Мх106/1) 7100
1500 PRINT
"RD = зан “ACTURL RESISTANCE ";
t's .. H +:
әде LET L=INT (LM Rz2. 303} -1
210 FOR N=1 FO is
220 IF Ri=X (Ы) 108x*x«L THEN СОТО
230 NEXT N
243 LET x=X (N) z10 жж
258 Ре "PREFERRED RESISTOR:
53 >- Ж? . а. C ..
260 PRINT “GIVES CURRENT "; INT
(Uuxl28Q^7X)7100;" AHF
505
27m PRINT "BND “ІМТ iíUxsecÉelg.
ы), „ез. cO атте
232 PRINT
сай PRINT “AGAIN? (У мә ``
see INPUT Q
310 IF @$="N" THEN STGP
320 CLS
330 сото заг
340 SARVE “RESURS
350 GOTO 1@
4. Matmult
Program multiplies two square matrices. À two-dimensional matrix is stored as a two-
dimensional array, with the size input. Matrix multiplication requires the number of
columns in one matrix to be equal to the number of rows in the other. The matrices are
set up as square arrays of equal size in this program, and nonsquare mtrices may be
multiplied by entering 0 for the elements of a row or column which is unused. Users
familiar with matrix arithmetic will be able to derive from this program the routines to
handle other matrix operations. The method involves nested FOR-NEXT loops, in
conjunction with three arrays in this program, the third array holding the resultant
matrix.
Other points to be noted are the input and error routines. The input routine prompts
for inputs by row and column number, and when all elements have been entered the
error check subroutine is called, so that the user can check the whole matrix at once.
This avoids the possibility of confusion over row/column numbers.
REM "MRTHULT'"
REM #BETTER IN FRSTs
> FAST
10 PRINT "2D MATRIX вич T IP ICA
TION", жен ннн ннен + жя +++ ж +++ ++"
20 PRINT AT 3,0; “MULTIPLIES SQ
HARE MATRICES." : AT „А; "TO USE F
OR NONSQUARE MATRICES” , ENTER e
TRIX SIZE ТО ACCOMOLATE”, "ANE ЕМ
TER ZEROES.E.G ТО MULTIPLY", Мг
= 3) ET". = Жы ” 23 әзі %
38 PRINT’ "use NS ps Haters зге
NTERING","1 COLUMN AND i ROW O
REST @.",,,ENTER HATAICES 8
ITN
=a PRUSE 200
се PRINT AT 21,2,” 43EMTER MRI
aa REM 4D INENS TOM ISF 2 оны
RESULT MATRICES+
зе DIM Я(5,53
зап DIM B(5,5)
1210 DIM С(5,5)
128 CLS
іза PRINT "ENTER MATRI” 3°, , ЕРІ
TER @ FOR UNUSED ELEMENTI”
249 FOR F=1 ТО 5
ісе FOR N=1 TO 5
158 sarc AT 21,0; “ROU ";F." со
179 INPUT AIF, м)
50 PRINT AT Ғаз, NxOG-O6,mpmpmifF,Ma
150 NEXT М
2220 NEXT F
210 REM ҰМ IDENTIFIES MATRIA FG
adi SUBROUTINE +
=зё GOSUB See
2590 PRINT "MATRIX 2”
250 FOR Ғ=1 те 2
270 FOR М1
2580 PRINT Ar 317 5%; “ROW “;F; ”7 со
омм ‚м;
239 INPUT ӛсе, м:
39090 PRINT AT Fe3, N#6-6;,8 TF,
506
34g u səə
oo. ыы “MATRIX 1 + MATRIX 2
=1 TO Š
Poe TG 5
` на TO S
404 LET СР, М =C Р. МУ eR iF Li ғы:
+1@ (ЕТ СР, М) SINT (Clr. N} +1E= +
di SLES
428 coon AT ҒұЗ,ыіұб-б; C tF Р
dix
339 mr
450 NE
_ +58 PRINT AT 21.8; "INPUT Cicory
|; RIRUN) OR ECE мб)"
i70 INPUT 2%
IF Z$z"C" THEN COPY
IF Z$="R" THEN RUN
GOTO 786
REM «ERROR SUBROLUTINE:x
HE
PRINT AT $0.0." QRE ALL ENTE
: OR NJ)"
Gl
ШІ
л
Ci
n
4-2,
"zr
GUOJ Go
Hl
БФ
F Бф-“Ү” THEN RETURN
PRINT AT 21.9; "RON нен INT
CT ENTRIES?"
INPUT EN
QR F=1 TO EN
PRINT RT 20, n NS AT zi. 9; F $
21,0; "ERROR “;Ғ; ROW
INPUT R
puri zd 21.7; COLUMN т“
PRINT AT 21.0. R$: 22.8; “E
SEBUT M NUMBER
IF M=1 THEN LET R:!R,Ciz
IF Mz2 THEN LET EiR,.Z;z
PRINT AT ntes Cx#6-6; * E
BRx2.C*5-6,N
NEXT F
PRINT AT 21,0:R$
сото S10
REM #END
Gams
«LO Uf 33 4 co po eat Qc C
т
“.
ew
<..
DU n en em gu cn A C c on Tt cr fl inen enm pe p. eq
mp C d D СД f D FE SiC CO <А
AOS әәболоцоюш бу
ENTER MATRIX 1
ENTER @ FOR UNUSED ELEMENTS
i = 5
3 о e
a ә ә
MATRIX 2
© ә 4
ә a =
a a e
HARTRIX 1 ж MATRIX 2 GIVES: -
e e a32
e а е
о e e
INPUT CICOPY) ,RIRUN: OR E (END
507
5. Fruit
Program simulates a fruit machine. The program allows you to continue playing until
your money runs out (which it will eventually) and you can then ‘‘borrow’’ more.
Points to be noted in the program are the overprinting of a string to simulate the
spinning of the wheels (lines 200 to 230), and the logic used to check wins and amount
(if any) won, in lines 250 and 260. The program loops back from line 290 to line 140
unless the money has all gone.
Spectrum: Change line 60 to read 60 PAUSE 0.
10 REM "FRUIT"
NT 1i rh
зә PRINT "YOU HAVE SAP
BLE.", “EACH ROLL COSTS 10 PENSE.
ай PRINT +anPRVOUTS: = THE Sane
PHYS 10Р"; S:°S THE SAME Ege
s 40P"; TAB SS "ЕХбЕРТ REROMHICH E
SO PRINT ,,"PRESS A HEY TO STA
INKEY S$=""" THEN GOTO 6&8
-
-
14 4 4 CTI
mao
th
Том
Т
Qz
(SS STN P
DM тог гон
# x INITIALISE «PRINT +Q +
mi fui co
3)! 20 P Pm mmm ПІГ ТТІ
HHH x i
EBER; T Б | ;
RINT AT 19.8; 55 5 То £
+
HQ IF INKEYS<¢>°S" THEN GOTO 34
RHEE EEE
Gg
ә 7)
4 2.0010
1
2 REM ##5ЕТ WIN LINE + +
=
LET Bnga"t
1-0 FOR Ғсі ТО 3
162 LET A=INT RND +Ë x +:
179 LET Б%-В%- Ж” +A 18:
155 AME #*SPIN WHEELS%
186 RE
1989 LET fs) pw.
200 FOR к=1 TO 1
210 PRINT AT 9.12;F$i01 TG ©)
220 LET F*$=F$íŠ TO »?«rF&il TO ZS;
230 NEXT F
234 REM
235 REM *##PRINT WIN LINES +
256 REM
249
3:
PRINT AT 9.12: 5$
+
14393 +484425 =
245 REM #xCHECK WIN:
250 LET U-(BE$£(2)zE$
3 3
BS 16 (6) Li (Bs (4) =E $ (63
255 REH AMOUNT BONE £
eod LET C=(.18 AND 15-і) 541 +0 &
4,45 3) 4+(1.8 AND W=S AND БЕШ =”
те LET C$=C$ (1) STARAS (Vet Ciz
\+Сс-.1а)
REH
Y
ңғ.
du
GDG DAG JIC
өпаьовбайь
(i SHOE Se олы
=]
O
D
EL XxCHECH IF SOLVENT +E
RINT RT 3. C$
N Е Cs (Š 9:5 ) >ш.10 THEN
FIOI
F. + +МОМЕҮ SPENT z £
Eri AT 3,.,0;"' xYOU ARE ERU.
TAB ә; “BORRÓ ом £2 TIY OR м!
a Mg
LS
MS="Y"' THEN GOTO әт
INT "BETTER LUCK NEXT ТІМ
G;
s QIU fü FO fO nano TO
:m
POP ж
rho CI Сау
nur
rm
о 990
un
i
508
6. Lissajous
A program to produce the intricate, interesting and delightful patterns, named after the
mathematician who discovered the equation that produces them. You merely enter the
values of A, B and C in response to the prompts and watch the patterns develop.
Spectrum users can generate more complex patterns than ZX81 users, because of the
higher resolution PLOT screen.
Spectrum: Change line 80 to read 80 FOR F = 0 TO 200 STEP 2. This defines the
number of points to be plotted. You can experiment with different values for STEP if
you want more or fewer points plotted. Line 90 needs the two 30s changing to 120, and
line 100 the two 20s changing to 80. A and B can both be input with values up to about
10 on the Spectrum, so change the Input prompts to suit.
REM #*#LIssAvouar
REM PLOTS LISSATQUS PRTTERHN
$
2
З REM Я IS RELATIVE FREQUE HC?
B IS REL. FREQ. Х,С 15 Y PHRI
BIG MENT “INPUT A (INTEGER 1 T
2@ INPUT A
oe FRAN “INPUT E {INTEGER 1 T
в
SO PRINT "INPUT C (ANY HUMBER
Ба INPUT С
50 FOR ғ-о TO 20a
90 LET Y=S3@+S04S5SIN (ConaPIaPsi
те LET Xz20420*5IN (BxPIsT»igc
110 PLOT v,x
120 NEXT F
"v заза, E ап = 1а ur"
= = gd 2" я " N E ie а т
> x to `. a в .. "ag "er
7. Line
This program gives the computer the capacity to draw a line between specified plot co-
ordinates. The Spectrum possesses a LINE instruction that does this automatically, but
Spectrum users may be interested in the method, which is the way the LINE instruction
automatically calculates the points to plot. The program will run on the Spectrum if
line 85 is deleted. As it stands, the program prompts for two sets of X, Y points, giving
an error message if the points are out of range. Lines 110 and 120 calculate the X and Y
axis differences between the specified points. Line 130 defines the variable A as the
greater of these. DX and DY are the increments added to the values of X(1) and Y(1)
509
for plotting. In the loop (F = 1 to ABS A, since A may be negative) DX and DY are
decremented or incremented (as X and Y are positive or negative) by the distance to be
covered between points, divided by the number of steps needed. The program will
accept further inputs as required, but does not provide input prompts (lines 210 to
280).
5 REM "LINE" "
iO REM DRAWS LINE BETWEE POIR
T.,(XC1),VYCLIIAND POINT ах+ш v 1E
3 1
20 DIM X12)
25 DIM Y (2)
50 FOR Ғ-1 TO 2 ©. --
40 PRINT “COORDINATES POINT “i
со PRINT "A UGPLUSE Т"
50 INPUT Р)
70 PRINT
^
(
"Y VALUE Т”
(F)
>
К 1355 THER
PROGRAM AGRIN ``
DY =@
16568 FOR F=1 ТО 65 n
179 PLOT ОРТАҒЫ DY £w ££
180 LET DX=DX+X/ABS F
190 LET DY= DT te CABS e
2BO NEXT F
219 REM FOR OTHER LINES
220 REH M ркан жїл
230 INPUT X(1)
ТОЧНИОТ HS ИШИН
8. Reverse
The computer jumbles up a sequence of 9 numbers, and prints these (subroutine line
500) after giving the instructions, by calling subroutine 1000. After each input by the
player the subroutine at line 300 is called to print the altered sequence and check if the
ordering is complete. If the sequence is correct, control is passed to line 2000 for the end
routine, which gives the option of playing again.
18 REM “REVERSE”
20 PRINT TAB 10; "#REVERSEs"
зе GOSUB 1000
CLS
45 DIN
R (9)
50 PRINT TAB 10;"'xREUERSEx'
во PRINT AT 5,5;
510
ге GOSUB See
өс LET GOES=Ə
ae PRINT AT 15,0; “INPUT NUMBER
TO REVERSE 77"
100 INPUT R
110 IF R:1 OR R»9 THEN GOTO 100
120 GOSUB 380
136 REM xxLOOP NEXT GO#*
148 GOTO 100
150 REM =#=# += # +++ + +++ + * + + +++ +++ Ж
160 REH
5020 REM rx*xREUERSE AND СНМЕСКЖжЖ
310 REM +#SEQUENCE xx
315 REM
320 FOR F=1 TO INT (R72)
USO LITT T=A tF)
S4@ LET ЯР) =A (R-F+1)
3550 LET AC(R-F+1) =T
360 NEXT F
370 LET CORRECT =
3882 PRINT AT 5,5;
390 FOR Fz1 "T 9
400 PRINT atF2); T
410 IF AIFI =F THEN’ LET CORRECT
=CORRECT +1
429 NEXT F
4232 LET GOESzGOES—-«41
440 IF CORRECT=9 THEN GOTO 2009
450 RETURN
460 REM #++ ++ +++ ++ +++ +++ ++ ++ +++
500 REM ##S5ET SEQUENCE #*¥
510 LET ACL) =INT (RND «933 +1
TO 9
S30 LET R (F) 2INT (RND#9) 41
540 FOR N=F-1 TO 1 STEP -1
550 IF ACF) =яМ) THEN СОТО S30
550 FOR F=1 TO 9
S90 PRINT R(tF),;" ”;
600 NEXT F
6180 RETURN
620 REM =з» ++» ++» ++ +++
6380 REM
19006 Бен *£*INSTRUCT IONS жж
1820 PRINT COMPUTER GENERATES
JUMBLED", "SEQUENCE OF DIGITS 1
TO 9.
1030 PRINT “YOU MUST INPUT A NUM
BER 1 ТО 9,
1040 PRINT “AND THIS NUMBER OF D
IGITS,","STRHRTING FROM THE LEFTM
OST a's "UILL REVERSE.YOU MUST GET
2858 PRINT DIGITS IN ORDER LEFT
TO RIGHT.'
БЕРЕ PRINT ,, "PRESS R KEY TO STR
1 @ PRINT s "THERE WILL BE A DE
TU WHILE”, “SEQUENCE IS CREATED.
10628 PAUSE 4ee00
123290 RETURN
4100 REM #= FF EXF FSH + + +++ +++ +1 ++
REM
5000 REM sxEND ROUTINE
2005 REM
AT 20,0; "##SUCCESS IN
2619 WES; GOES#s", "ANOTHER GO? CY
м
2030 IF Hao ye THEN сото 2050
SYE
9939 STOP
9. Tools
The program shows the principle of a programmer’s toolkit program containing useful
program modules. You should add to this basic version any further subroutines or
modules you want to have available. The inclusion of the BLOCKDEL program makes
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
Note the mnemonic for the error subroutine line number. When you add modules
however, use variable names that you are unlikely to use in the program you are
developing. Load the program before starting a program on the ZX81.
Spectrum: For the Block delete module see BLOCKDEL. For Renumber module and
Memory left see Section U of the text. Remember you can use MERGE to enter this
program at any point (hence the high line numbers).
m gj & Umm
00
S480
S33S6+256*#PEEK 163387-PEEK
SexPEERKR 16413;
S540
9550
REM
REM
REM
"TOOLS"
£slLLUSTRHTES TOOLPRIT a
езі ОНД) BEFORE START ++
Fe INPUTTING PROGHHRIX:X
*xGO0SUB ERROR FOR =н
+ *KHESSAGE
##GOTOQ ашаа FOR aL Ock ++
#*#DELETE
xxGOTO 9700 ғоя BENUM
*xGüOTO S458 FOR MEMORY
*LEFT
ADO YOUR QUNM ROUTIN£ZI
£ £ £ £ £ + £ $ £ + AHA $ $ HAAHA RABE
ЕКРОВК =94.00
ERROR MESSAGE 508+ 4
* * Xx X X 3 3 Д < 3 HHH
PRINT TAB 7, “#844 INPUT ERROR
T); RERSRERHRHH4HHHHH ES”
PAUSE 120
REM #xHEMORY LEFT із
are SHH HHeHAH HAHAH ++ +++ HSH SSS
PRINT “MEMORY LEFT ="; PEE
264325 —;3
"1
=
—
=
ae
APPROX,”
STOP
REM x*BLOCK DELETE::
REM 3 * s š 3*3 š € € s£ š š
PRINT “FIRST LINE TO DELETE
INPUT ST
PRINT "LAST LINE ТО БЕ DE: =
INPUT END
LET RANM=16589
9560 LET LNUM=2564PEERK RAMNSPEER
(НАМ +1)
3570
+2
3530
ЕЕК
9
9560
SLETE BLOCK
ауа
3500 IF 25б%РЕЕК БКИМФРЕЕК
1 =9000 THEN GOTO 3832
3512
3520
93530
SUB , сота",
354ea@
IF LNUMZST THEN LET LRBH=RA
LET LLEN=PEEK S iRHlh-2!4286037
(RAM +3)
um “Бына END THEN GOTO ЭББ
RAM=RAN4+¢4+LCEN
GOTO 3568
LET LLENsSRAM-*LLEN 2-154
PORE LRAM+I1, INT YILLEN.2986561
POKE LRRHM,LLEN-2SOGsPEER ILR
PRINT “INPUT FIRST tei TO >
=
STOP
REM #x#RENUMBER #+#
REM ££ £ * * š * $ GR +++
LET mRhüM-zilesaa
LET LINE =2@
LEIL ӘТЕРсіе
POKE RAM, INT (LINE.2wU6
POKE RAM*«1,i!LINE-z296643P££NH
LET RAM=RAM+1
IF PEEK RAMI >o4148 THEN GOTO
=RAM+1
=
3770
LET RAN
URBI +S
LET LINE-LINE-«STEP
GOTO 9750
PRINT | SRBEUBEREBA NOW DO Go
“LINES
STOP
512
10. Blockdel
Program enables blocks of program lines to be deleted by a single line entry after the
line numbers of the first and last lines of the block (ST and END) to be deleted have
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
number of the first line (LNUM). If this is the line number of the start line, the address
of the first byte of the line length storage bytes (= RAM + 2) is stored as LRAM (line
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
line length and four bytes for the program length and line number bytes, to get the
address of the start of the next line stored in the memory, and the process is repeated.
When the end line number has been located and control passes to 9620, the line length
variable LLEN is made equal to the number of bytes between the first and last lines for
deletion (this is why LLEN was found before checking if the current line was the last of
the block) by setting RAM to be RAM + LLEN, i.e. the address of the end byte of the
last line to be deleted. This value, less the address of the line length byte of the first line
(stored as LRAM), plus 2 for the program line number bytes of the last line gives the
number of bytes to be inserted by the POKEs of lines 9630 and 9640 as the new line
length of the first line requiring deletion. The computer now thinks that the lines for
deletion are all one huge line, and keying in this line number and pressing NEWLINE
(ENTER) will delete the whole block. The program should be loaded for use on a ZX81
from tape before you start working on a program. Spectrum users can use MERGE.
Spectrum: Line 9550 (giving the start of the program area) must be changed to read:
9550 LET RAM = PEEK 23635 + 256* PEEK 23636
ле REM “BLOCK CEL
3508 214 **8LOCK CELETES4
3505 R * * +++ т
3510 PRINT "FIRST LINE TO DELETE
S528 INPUT ST | к
S530 PRINT “LAST LINE ТО Sr Prise
S54@ INPUT END
assa LET ВАМ=16509
S580 LET LNUM-2SBsPEEK Янә
422” IF LNLIH=ST THEN LET ЬЯ =
ssaa LET LLEN=PEER (8816523 PRSA 3=-
ЕЕК (RAM+33
S590 IF LNUM=END THEN GOTO Q822
зеса LET RAN=RAN+44+LLEN
2610 GOTO 9560
3620 LET LLEN=RANF+LLEN22-L RM
зеза POKE LRAMS1, INT ЕЧ soa
29649 POKE LRAN,LLEN- 256 4PEEA tLe
+1)
$630 PRINT “INPUT FIRST MG TO Z
ELETE BLOCK"
S668 STOP
10 REM "“BLOCKDEL"
9500 REM ##ELOCK DELETE жж
2505 REM EEE EH HE жы Ж
2510 PRINT "FIRST LINE TO DELETE
$520 INPUT ST
9530 PRINT “LAST LINE ТО BE DELE
TED?"
2540 INPUT END
9550 LET RAM=146509
513
2560 LET LNUM=275e% PEEK RAM+ FEE
қ CRAM+1 >
9570 IF UNUM=ST THEN LET LRAM=RA
M+2
7550 LET LLEN= PEEK (RAM+2)4+254.%
PEEK CERAM)
2590 IF LNUM=END THEN GOTO 2620
7400 LET RAM=FRAM+44+LLEN
9510 GOTO 60
7630 LET LLEN=RAM+LLEN+2-L RAM
7640 РОКЕ LFñM+1: INT (LLEN/226)
9650 РОКЕ LRAM:+LLEN-256% PEEK xL
RAM+ 1)
9660 PRINT “INPUT FIRST»N/L Tü D
ELETE BLOCK"
76470 STOF
11. Coder
The computer chooses a four digit code sequence comprised of the digits 1 to 6. You
input your guess for this code sequence. The computer prints your guess, checks for the
number of digits in the correct place which correspond to the code, storing this as AST
(for asterisk), and then checks through the remaining digits for numbers which occur in
the code sequence, but are not in the correct place (DOLLAR). These values are then
printed. This information helps you to refine your next guess. 15 goes are allowed, and
if you haven’t got the code in 15 tries, it is printed out for you. The program is
structured with a sequence of calls to subroutines. Note that the code can include
repeated digits, and analyse the checking procedures to see how this is dealt with.
REM “CODER "
GOSUB 1006
REM ТАНА а-а AND xx
(Жы
LET Neo" 22 345
- 1i! = в“
FOR F=1
LET Z n DENS сават «БҰМҒГАн6,ҙ €i:
fos
IF MARK=1 THEN GOTO 1:38
LET GUESS=GUESS+21
PRINT RT GUESS +2. 1i Gg: TRE
GOSUB сос
GOSUEB 608
PRINT AST; TAB : DOLLAR
REM ж%ҰЗЕЕ IF 15 TRIES жи
+ xOR CODE CRRCHEDxrxE*
F pe yku e e
HUGO бб SEeaqQgqao был
Sod J OAM mu vu e» Ct
Тае
219 IF AST=4 OR GUESS=1Z> THEN
GOTO 2868
220 REM ab icr adi TO NEXT GUESS
езе GOTO 11
240 REM ^o наказание най
258 REH
222 REN
E *xCHECH INPUTrEE
$95 BEN á
: I F-L TO LEN &G
аша Gg (F) аз THEN 24 om TODE
< N
аза ЫШТ LET MARAH = 1
440 IF LEN 5Ф<>4 THEN LET ter.
514
450 IF NOT MARK THEN RETORN
4603 Gn 2 NB AT GUESS-«3,.0;
7 ";G$;"7? TRY AGRIN.*
a7 PAUSE
480 PRINT AT GUESS-T3,0;"
42a RETURN
435 REM хжхжжғғжхжкжғккккккк
ЕМ
5020 REM *=*=F IND NUMBER x +
520 FOR F=1 TO 4
530 IF AS(F)I<>GeiFs THEN ТГ
570
қой REM SSH x yx x z£ x x x x k x EEE
520 REM xxFIND fj HRHUPIEEEE y x
еге LET DOLLRARRzO
өзе FOR F-1 TO 4
FOR N=1 TO 4
550 z g eth) rop On THEN GOÜTOG
LET DOLLAR= DOLLAR +2
LET AS(F) ="X
44 4 CL Qn
e guo
OGOOGO
r
m
-f
G)
2
11
ext
RETURN
22 REM хжххккккжккккккк
730 REH
1oo00 EE *3x INSTRUCT IONS + +
EM
іга PRINT TAB 12; VN SEEKER" | TRE
12; “+СООЕК +; TAB 123;' ‘SEER ER К“
1@38 PRINT .. “COMPUTER CHOOSES =
SEQUENCE ОҒ“,%4 NUNBERS.THIS I=
MADE UP OF", "аму OF THE DIGITS
i TO а”. “INCLUSIVE. DIGITS MEN EE
R LE
1 "YOU INET SEGUENCE
5 TO TRY i Nb “MATCH THE CODE."
1050 PRINT ,..^COMPUTER HILL PRIN
T NUMBER OF B.SIGNIFYING CORRECT
DIGIT IN". "RIGHT POSITION . CPU, ғ
UMBER OF = ,HERNING € DIGIT Із G
HESS WHICH
19509 PRINT “OCCURS IN THE гомгазт
ERS CODE, , BUT IS NOT IN THE БТ
GHT PLACE.‘
41070 PRINT ,.," PRESS A KEY TS Ek, =;
1280 IF ІМКЕУФ-““ THEN GOTG LGE
1090 RETURN
1192 REM EEEIEE 3 38 ККЕ
5228 REM END ROUT
: шо INE x x
5929 НЕМ ast 4 THE?
282 = ч GOTO 205
2023090 PRINT "15 TRIES AND NO Sr:
ESS.CODE"."uns "209
5058 ERENT Mec
сый: - " e E > è £z.
na RTRS CESS ІМ í GUESS,
cuo T “ANOTHER Ge Ti i
т OR NOS GAME IMPLT
2UTO INPUT MS
zasa IF Мф-“У" THEN GOTG Zu
2290 CLS
заво ERUNT "DC BYE.”
2350 RE
292930 REM *xx«xxxrxENDEEXExEeEk
3999 STOP
"BB GUESS
E
1
3
3
GG ts
515
S432 1:2
2342 32 X
5122 т.
siloa е 1
13923 | 9 3
бізг i =
1362 1 2
4532 s uk
S332 12
4352 з 2
3342 г е
3512 4 0
SUCCESS IN 15 TRIES?
RNOTHER GAME? { INPUT Y OR H
12. Plot
A simple program to plot a graph of data points, with X and Y values input on the
screen. Prompts for X and Y axis minimum and maximum values are made, and string
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
requested.
Spectrum: Change line 310 to read PLOT 124244 * (X- AYy(B- A),
12 + 156 * (Y — C)/(D - С)
2 REM PLOT se
дё PRINT TAB 6: BSR SE rei сут ET
2à8 PRINT
3@ PRINT "SET AXIS RANGES"
40 PRINT “INPUT X AXIS MIN. vat
SQ INPUT A
SA PRINT A
70 PRINT “INPUT X AXIS MECN Ue
se INPUT Б
за PRINT Б
© PRINT “INPUT Y AXIS MIM. UAL
а” INPUT с
€ PRINT “INPUT Y AXIS MAX. VAL
14@ INPUT D
D
i58 PRINT “INPUT X AXIS TITLE "
IT a P
іза PRINT X$
152 PRINT “INPUT Y AXIS TITLE `
“ора INPUT Y$
210 PRINT Y$
220 5
230 PRINT AT 21,6;:X$&
249 FOR I-1 TO LEN Y$
250 PRINT AT I«5,.0;Y&1I1j
592 PRINT AT ә.
228 ERENT S ©; INPUT N
т NT AT @,0;" v
266 таат 9 O; “INPUT `
UE. p I rius X-A Z CE; — € y , Seay
зда GOTO 279
13. and 14. Bidec
Program converts binary numbers to their decimal equivalents. Two programs are
given, differing in the conversion procedure applied to the binary number, which is
input as a string. The algorithm of BIDEC*2 is more transparent than that of BIDEC.
Spectrum users have the facility to input binary numbers directly (using BIN), but this
516
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.
BIDEC*2
Spectrum: À not ** in line 50.
š REM #BIDECs
REM CONVERTS BINARY NUMBERS
INTO ee tee
18 "ENTER BINARY FORM"
110 INBUT A$
158 PRINT Өй IN BINARY I2"
348 LET R=LEN AS
150 (ЕТ NSURL & was
160 FOR Fz2 ТО
17@ LET М S ема. F$ IF)
ico NEXT
RINT.
әде PRINT N;" IN DECIMAL”
o REN "BIDECx2"
180 PRINT “INPUT BINARY NUMBER"
SØ FOR F=LEN БФ TQ 1 STEP -1
БӘ LET es иши BS i Fl £ xP
Та LET P=P+
зе NEXT F
oa PRINT B$; “=DECIMNAL “iN
15. Hexdec
Program converts hexadecimal numbers up to FFFF (65534 decimal) into decimal. As
with DECHEX, the straightforward conversion of a character code to a decimal value
which is possible on the ZX81 is more complex on the Spectrum. Line 130 in the ZX81
version uses the value of the loop variable K directly to get the decimal value from the
character code. On the Spectrum a counter loop is set up to hold and increment the
value of K, and a new variable Z is used to hold the number by which K is to be
reduced to give the correct decimal value from the hexadecimal character.
Spectrum: Line 50 needs À , not **
Insert 55 PRINT ‘‘ LETTERS MUST BE CAPITALS."
Insert 115 LET K = 48: LET Z = 48
Change 120 to read 120 FOR Y =0 TO 15
Change 130 to read 130 IF A(F) = К THEN LET N = ((K- Z)*X)+N
Insert 135 LET K=K+1
Insert 136 IF K = 58 THEN LET K = 65:1ЕТ Z = 55
Change 140 to read 140 NEXT Y
КЕМ x*HEXLDECrx
4)
INT
50 PRINT "ENTER HEXADECIMAL NG
"rr
omm
DA-
хх I
11 И
wu
+°:
++ OO
о
LEN Ar
ODE H$IF;
„ЕН ris F}
K THEN LET N=i t -2E
“Wr TP I T
жи
X Gia p eu A
` (S € 9 баб) (3
Ж
m
4
II Qo
-.
ээк Бараа л
42 NEXT
=
(Ji
б
1
D
H
z
"n
WX Th
I9 ";N;" IM DECIMAL.
517
@ PRINT
© PRINT "RHGRHIN'?7íN OR Y`
© IF INKEYS$="Y" THEN GJOTG SS
а STOP
16. Dechex
Program converts decimal (base 10) numbers up to 65534 to their four-figure
hexadecimal/(base 16) equivalents. Hexadecimal numbers use the digits 0 to 9 plus the
letters A to F. This requires a means of deciding which character is to be printed, after
the decimal number has been broken down. On the ZX81 this is simple, since the
(capital) letters A to F follow directly after the digits in the character code sequence.
This is not the case on the Spectrum, and the gap in the sequence must be bypassed.
CHRS can then be used to change the decimal values (0 to 15), into which lines 120 to
170 break down the input number, to the appropriate character.
Spectrum: Change 190 to read 190 LET X = 48
Insert 205 IF X = 58 THEN LET X = 65
TO 19
IF FiiF)=y THEN LET AR&iF;-5H
LET жн x+1
Jj
PRINT " IS “AS; IN HEX"
PRINT AT ENR т NEWLINE
UN AGAIN"
Ces p. cana
mor iU TO EO EG e [Ú [U R9 ei i RP ро RS F2
1 REM DECHEX
аа DIM Aig)
сә DIM АФ (4) С
за PRINT “DECIMAL BASE TO HENA
DECIMAL BASENUMBER CONVERS TION™
4а PRINT
БӘ PRINT "NUMBERS «85555 Gni“
ge PAUSE 35
76 CLS
S0 PRINT “INPUT DECINGL UD 0E"
ай INPUT М
аа PRINT
12 PRINT N;
ЕФ LET ACIVI=SINT (Ne 4 O58’
За LET B=N-A(1) £4636
4@ LET ACBi=INT (8-258;
ей LET C=E-F (2) +258
ео LET Alsi SINT (O-26s
79^ LET Aid) s=C-A(Ss £16
зе FOR ғ-і TG 4
acd LET X=26
eo FOR Yzà
із
x
e
e
e
e
o
m
a
a
%0-.|
17. Gridhunt
Тһе computer hides itself on ап 8 Бу 8 grid, which is displayed оп the screen. You input
your guesses of the co-ordinates, the guessed square is marked, and if not correct the
computer gives a prompt for its direction from this square, using compass directions.
4 REM ¥*¥GRIDHUNT ж
із PRINT —""iaekütal*sgs
зә FOR Xz2 TO 18 STEP 2
24. IF srana TREN COTO 46
ху»
40 PRINT AT 3,X; -";HÍi 14,х; "+
45 PRINT AT 441,22: "+"; RT xX+1l ,1
G3 а.
БО NEXT X
60 LET E=INT (t(RND#53) +1
78 LET М-ІМТ (RND zx: + 1
Зб LET G=lE-1} +N
ga LET H=@
518
108 PRINT AT 3.28; "YOuR GUESS: —
"AT 3,20; a ae ia
Li@ INPUT
128 PRINT Ят 5,26," ";яЯ; АТ 2,29
з “DOWN?”
130 INPUT D
131 FOR Xz1 TO S
152 PRINT RT 2-«Dzx2,1-24a0*2; Ж.
133 PRINT AT 2+0%+2,1+я+2; "Y
134. NEXT X
135 PRINT AT 2t042,71+AR2S; “ж
14@ PRINT AT 7,24;" ";г;ат 9,20
145 LET М=М+1
150 LET С= 9-1) #642
160 IF C-G THEN сото зай
2
=
190 IF N>D THEN PRINT "S";
2OD IF N:D THEN PRINT "N";
216 IF EYR THEN PRINT "E";
220 IF Е‹А THEN PRINT "UW";
әзе PRINT " “;TRS S2,"OF YOU"
222 PAUSE 2080
250 FOR X=3 TO із
Р
300 PRINT “GOT HME";ThB S2,;"IN ~
19 PRINT AT 20,89; “PRESS A KEY
TO PLAY“
see IF INKEYS$="" THEN GOTO S2@
330 PRINT AT 20,8;
349 CLS
358 GOTO 1G
18. Rescode
Program calculates resistor values from inputs of the colour bands on the resistor.
Three bands are input, end band first, using the abbreviations given. The first two
bands define the basic value and the third the multiplier.
32 BRYBESEOPE
"ENTER COLOU У
NDEAND FIRST" ee MESS
3e INT
айд PRINT “USE CODES AS БЕ ОШ:
во PRINT ТАВ 6; “RED RE'; Тағ
6; "BLACK 6L"; TAB 5:"BROUN BR"
; TAB 6; “ORANGE OR’; TAS 65; "YELLOW
"YE"; ‚таз 5; “GREEN GR’; TAB 6; “BL
МЕ BL"; TAB 6; "UIOLET VI’; TAB &
; GREY Gv" TAS o; "WHITE UH",T
nb Б; "GOLD GO"; TPE ё; “SILVER 5
X^
вә FOR A=1 TO 3
Ж. PRINT "COLOUR ";A; "7 n2
ве INPUT C$
өй PRINT C$
100 IF C$-2"BK" THEN LET U=@
110 IF CS$-"BR" THEN LET Uzi
12@ IF Сф= “НЕ” THEN LET Uz2
130 IF C$-"0R" THEN LET Uz3
140 IF C#="VYE" THEN LET V=d
150 IF C#="GR" THEN LET Ч=5
160 IF С%-"Еі. THEN LET V=s
170 IF Сж-"МИІ" THEN LET М-?
48@ IF cCH="GY" THEN LET УӘ
190 IF C$-"UH' THEN LET Uz9
оаа IF C#="GO" THEN LET U-i0
210 IF Cs” SI" THEN LET іші
эра IF n-i THEN LET F=
2:30 IF R=2 THEN LET FoF He LG+u
24G NEXT A
250 METNT “RESISTANCE VALUE IS
bea IF U9 THEN БОТО Зва
519
S10 PRINT " OHNS"
S6Q PRINT Fev;
370 PRINT " OGHHS
19. Marker
Program produces a marksheet for the pupils in a class after exam results are entered in
five subjects, set in this program as English, Maths, French, Computing and Biology.
The average mark for each pupil is calculated, and a grade breakdown of the results is
printed, giving the total number of pupils in each grade. The grades are defined as:
45% or less FAIL
45 to 7596 PASS
More than 75% DISTINCTION
As initialised, the program allows up to ten pupils in each class. A pupil name is
entered with the results in each of the subjects, and the average calculated. When all
entries have been made, END is entered and the subjects, results and grades for each
pupil are printed. The grade breakdown is then given of the number of pupils in each
grade for each subject.
1 REM “MARKER”
5 LET Ti-e
S LET Te=8
7 LET Ta=e
, 8 LET Z$-z"END
да DIM AB$ir18,20)
20 DIM RIID)
25 DIM Di5!
вв DIM PS:
27 DIM F (Š
За БІН S$1í5,1i0)
да DIM H(3i@ S)
52 PRINT “MARK SHEET"
GE PRINT “аға,
т^ PRINT ""
зә PRINT “С
100 LET Ісі
іле LET Com
РО КЕТ SEII: "ENGL FSH”
АЗА LET ss te) =" МАТН"
TES КЕТ 59:95 =“FRENCH"
150 LET S$ it? -“СӘМРОТІМС"
160 LEFT S$tS) ="BIOLOGY"
22020 PRINT “EN ЕН NAME CENTER Ef
p TO FINISH): ^"
21ı1@ INPUT RSet
ере PRINT REL
ONHH
а” ғ»
езе IF mn$i1?
езе SOSUE ive
250 LET Ісізі
ese LET C=C+1
255 CLS
268 сота гае
Sag REM CALC RVERAGES
элт соғу
THEN бОТО See
2) +R t L)
ос
өзе PRINT "МАМЕ :"; ABET?
6249 PRINT "SUBJECT"; TAB iS; “HAN
K"; TAR 2@; “GRAPE”
сест eater ortega
638 FOR U=1 TO 5
6535 IF М(І,о3575 THEN GOSUB 2ee
626 IF MET, 42 245 AND MOI, N 275
THEN GOSUR 222080
" ad YF Mi, <=45 THEN GOSUR 24
520
GEA PRINT ASE; TAS i15; MCI, iT
AB 22; =s
6S@ NEXT <
665 PRINT ""
666 PRINT “AVERAGE= “JANS
667 PAUSE sae
668 COPY
өзе CLS
67e NENT X
700 PRINT “GRADE BREAKDOWN BY =
UBJECT “
ТЇЙ PRINT “--------------------
?29 PRINT “SUBUECT'; TAB 25; "PD IS
T.“ FRB PZ; PRSS“, TRE 27; “FRILL”
725 PRINT ~”
тз БОК (u=: FO
740 PRINT 23 (49; TTAB ір TRB
5e LET Ті-тізб cay
Zëw LET Fe=TesP U.i)
тта LET TAs Farr 522
S20 PRINT “TOTAL”; TAS 15; 74; TAS
22;T2; TAS 27,T3
ase STOP
BBR ROM INPUT гата
ӘӘ FOR =i TO 3
ДЕР. қ аын "USUBRBJECT “;5%%0»;” MR
1858 INPUT Hr.)
Өте PRINT Hül,.)
Loan NEXT М
11 RETURN
зала REM DISTINCTION
SQUIB LEF G$= DISTINCTION"
2020A LET о =O tt + 1
203a RETURN
2200 REH PASS.
гїї LEF G$ =“ PRES”
2220 LET FP XG =P (=1 AND D<=5>1 THEN СОТО
со GOSUB 250
TO 20
ге SEN ` ¿pra AL то 3203
Әй IF M>=1 AND М<-іг THEN сото
іре GQOSUB 250
110 сото 74
i209 PRINT “YEAR?T‘AS LAST 2 DIGI
521
130 INPUT Y
140 IF vY»10 AND Y<9S THEN GOTO
ісе GOSUB 2560
169 GOTO 12€
170 REM CHECK DRY М5 MONTHS
180 REM xLERHP ‘EARS |
1a! IF ІМТ (t¥4i3@8) 24) <> (Y +1ƏG
о) /4 AND M=2 AND с=з THEN GOTO
сб REM SHORT MONTHS
210 IF NOT ({M=2 AND D:28) OR t
OR M=6 GR M-9 OR hH-11) AND
Б-311: THEN GOTO 249
220 GOSUB 250
238 GOTO 19
240 RETURN
245 REM #=# =s X 3 + Xx x zy x x x Z= 3 3 % + X ЖЖ
249 REM szszsERROR NOTICE SUBS
250 PRINT “*###INPUT ERRORSss","
PLERSE FOLLOW INSTRUCTIONS", "ВЕ –
INPUT REQUESTED DATA.”
260 PAUSE 180
270 CLS
250 RETURN
зой REM *¥##PROGRAM HERE ТО USE
INPUT ROUTINESs*x
318 REM #EXAMPLEs E
320 PRINT “YOUR BIRTHDAY"
3360 GOSUE 10
2
lI
b.
PRINT “BIRTHDATE: "`; BD; "+"; Б
21. Headliner
Program prints banner headlines on the printer, using the character arrays stored in
ROM. As listed, the program allows the inverse characters of the ZX81 to be used,
accessing the normal character (line 13@) to get the pattern of bits, but reversing this
(1.е. swapping black for white) for printing (line 560). This procedure is not possible on
the Spectrum, since the inverse forms are not included in the character set. The basis of
the program is the reading of the character arrays (as with the BIGPRINT program in
Unit U3 of the main text), but with the additional complication of reading the first bit
of each byte, then the second bit of each byte, and so on, in order to print a character
with a sequence of printer lines.
Spectrum: Delete lines 40, 120. 130, 550, 560
Change line 160 to read: 160 LET L = PEEK (15360 +
C+8 * CODE L$)
L REM *#HEADLINER:
10 PRINT TRE 5; "im
ез PRINT ,,; PROGRAM TO PRODUC
E LARGE PRINT", "AS HERCLINES ALG
NG PRINTER PAPER”
GO PRINT ,,;" "INPUT ANY LEN&TH
STRING."
40 PRINT ,,;" YO: MAY USE ALL L
ETTERS , NUMBERS", “AND GRAPHICS.”
Se REM CIM RRRRY ТО STORE LETT
во DIM Яќ54.)
70 INPUT U$
ва FAST
Эе FOR Е-і TO LEN U$
100 REM TRKE LETTER
118 LET Іі %-ііФІҒ)
124 REH IF CHR INVERSE THEN
SURF FOR NORMAL FORM
азе IF CODE L$»63 THEN LET L§$=C
HR* (CODE ЦР) -126)
140 REN SET кәм COGOZ3
156 FOR с-а YO 7
¿150 LET L-PEEK (7680«C45sCODE L
j
e
522
170 REM GET BINARY INTO BERRY
180 FOR B-1 TO Gg
190 IF L-exsINT (iL^2)-1 THEN GOT
200 LET AIiSsC+B)} =o
210 GOTO 238
22 LET RíOGxc-5)-1
230 LET L-IN!T (1/23
240 NEXT B
254 NEXT С
рес GOSUB саз
278 NEXT F
сазда REM PRINT SUSROUT INE
510 REM REVERSE LOOPS
52 FOR X=8 TO 1 STEP -1
S3@ LET niz fe
540 FOR @ STEP -1
550 REM REVERSE IF CHR INVERTED
ВЕРОНЕ
See IF CODE U$ (F?) 5655 THEN LET A
{т €*5O-X) =NOT ACY x€ +X:
2; REM PUT ONE ROR GF CHR INTO
Ag
оза LF R (Y*S+xXx)=1 THEN LET A$=A
S90 IF RO xG4X)-0 THEN LET AS=R
AS
S20 LPRINT RS
Do0 NEXT X
64@ RETURN
22. Input
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
contains more than one decimal point. The program is listed as an input check for
decimal currency, but is easily modified to suit any numeric input of a known form.
The string input is checked by the subroutine at line 200, each character in turn
being checked by means of its code to ensure it is either a digit or a decimal point. To
check for multiple d.p.’s the counter S is incremented each time one is encountered. M
is set equal to the number of digits before the d.p. A check is then made for S being
greater than 1 (non-numeric character or more than one decimal place), @ (no d.p.),
and for more than two digits after the d.p. Any error sends control to the error
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
control back to the main program, where the user is given the opportunity to check that
the input value is correct.
1 REM "INPUT'"
STRING INPUT CHELNED RS
REM *#MARKERS x
16 LET 5-0
E ken ss
М EMPTY LINE:
20 LET E&-" £
**
30 PRINT “ENTER BHOUNT . ENTER
OUNDS.","FULLSTOP,P E E
аа INPUT NG SPR Tec
ET
OFFER VALUE CRECH E
entry Бай SMS SQ тысы Ut ID.
Vt < ^ x` :yT x Г. ГЕ
ТЕМ,Е TO RE-EN ж Т тнт
78 INPUT аф
SQ IF Ag="C" THEN GOTO 178
30 IF A$="E" THEN GOTO асс
,480 PRINT AT 20,9; “FOLLOM INSTR
116 GoTo за
120 PRINT AT 29.9;EF&: ES
130 PRINT AT 20.0. “ENTER ЗІ ЕЕЕ
T UBLUE."
140 INPUT N$
150 PRINT AT зә.о;ғе:ғе
923
160 GOSUB 200
170 Crs
150 PRINT “END OF PROGRAM
130 GOTO 999
133 REM *ERROR CHECK +
200 LET L=LEN N
210 FOR F=1 TG L
219 REM *CHECK NON-NOÜMEDRIL CRET
220 IF CODE a. oa” OGR СТИХЕ ME
F)»37 THEN LET S22
2293 REM xCHECH ҒІҢА ЕТЕ
ә: IF МФХЕЗ =". THEN LET 5-е еі
240 am £L. p^ z"," THEN LET rtzF
B= ЗЕ Ж OR 5,2 Gh £=& THE
ы GOSUE 486
333 REM sERROR FOUND:
ғас PEINT AT 23, Oi“ £IMFLIIT INURL
IDsRE-EMTER URLUÉ"
418 INPUT H$
LET ©
412 E = =
412 LET Мб
420 GOSUB 200
430 RETURN
299 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.
= REM "ASTERDIDS"
10 PRINT "x«ASTERDIDZ3«"
20 PRINT
Р 30 FRINT “AVOID BLACK ASTEROID
40 PRINT “YOU STEER YOUR SHIF
сж)"
SO FRINT "BY PRESSING 1 TO GO
LEFT"
во РЕІМТ “AND 0 TO GO RIGHT"
70 PAUSE 400
во CLS
90 РПКЕ 1641538
100 LET 50
110 LET C=10
120 SCROLL
130 PRINT AT 9230;
140 IF PEEK ( PEEK oe M ыы F'
ЕЕК 16399)<125 THEN GOTO 220
150 PRINT "же
160, LET L=C
170 IF INKEY$ ="" THEN GOTO 190
180 LET Г-С- (C>1 AND INKEY$ ="1
"y+(C 212 AND ІМКЕҮФ ="0")
190 PRINT АТ 8» ЕМО *20; "m"
200 LET 3-241
210 PRINT AT Soli" "
220 GOTO 120
524
250
260
270
220
290
300
210
РЕІМТ 5
PAUSE 250
CLS
PRINT “PRESS NEWLINE FOR"
PRINT "ANOTHER GAME"
INFLIT A$
IF AS="" THEN GOTO ВО
525
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.
Ian Adamson is an educational consultant active in the design
of technical and scientific courses, and the associated buildings,
laboratories and equipment, working mainly on overseas
projects.
Ben Anrep is a Senior Programmer working оп
microprocessor system development and software with the
Computer Centre of the PCL.
Brian Hancock is Senior Lecturer in Computer Science. His
teaching and research activities include programming methods
and the operation of computer courses for schoolteachers.
The Essential Guide to Timex/Sinclair Home Computers is the only
comprehensive guide to the world's best-selling and most inexpensive
home computer, the Timex/Sinclair 1000 (also known as the Sinclair
ZX81) and the new Timex/Sinciair 2000. The authors, highly respected
computer science prolessors and consultants, take you beyond any
instruction manual and present everything you need to know, in easy-
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
strings, lists and arrays; generating graphics on the T/S 1000 and color
graphics on the T/S 2000; addressing the computers memory with
PEEK and POKE commands; and special tips on editing and debugging
techniques. It also includes a complete program library, as well as
many exercise and game programs to use while you learn, a section
on applications, a simple guide to error codes, a special summary of
Sinclair BASIC commands, an expianation of character sets and codes,
and much more. This is the oniy book you will ever need for your
Timex/Sinclair 1000 or 2000, and the perfect tool for building program-
ming confidence no matter what kind of computer you own.
oe Д |01/005і0Пе Book Cover by Zimmerman
Я Published by Simon & Schuster, Inc. Foyster Design
New York
“Timex” is a trademark of Timex Computer Corporation. “Sinclair” is a trademark of Sinclair
Research Ltd. Neither the author nor the publisher is affiliated with Timex Computer Corpora-
tion or Sinclair Research Ltd., and neither Timex Computer Corporation nor Sinclair Research
Ltd. has authorized the publication of this book.
0553-0550 $8.95 0-671-47069-8