0% found this document useful (0 votes)
86 views111 pages

Beginning Basic With The ZX Spectrum

The document is a guide for learning BASIC programming using the ZX Spectrum, aimed primarily at Upper Primary and Lower Secondary students. It provides clear explanations, examples, and self-assessment activities to ensure comprehension of programming concepts. The book is suitable for both classroom use and self-study, with solutions included for checking understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views111 pages

Beginning Basic With The ZX Spectrum

The document is a guide for learning BASIC programming using the ZX Spectrum, aimed primarily at Upper Primary and Lower Secondary students. It provides clear explanations, examples, and self-assessment activities to ensure comprehension of programming concepts. The book is suitable for both classroom use and self-study, with solutions included for checking understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 111

Another hook on learning BASIC?

It is, but with a difference —here


the reader is taken step-by-step through the use of the Spectrum, with
each programming concept being explained clearly and accompanied
by examples of its use.

The author, herself an experienced teacher, has written her book


primarily as a text for Upper Primary/Lower Secondary level; she
provides numerous examples and self-assessment activities, all of
which are designed to ensure that the reader is fully acquainted with
each concept before moving on to the next. The book is therefore also
ideally suited for self-study.
SIC
wit , thc
Solutions are provided as an appendix, which allows the reader to
check his/her own performance, while gaining additional insight into
the program logic and design.

No unnecessary mathematics is involved in any of the examples or


problems, and anyone completing the book will be certain to have the
basis of an extremely sound knowledge of programming in BASIC.
ZX Spectrum
A small introductory section indicates the differences between using
the `calculator-style' keyboard of the ZX Spectrum and the full-travel
conventional keyboard of the ZX Spectrum +.

As well as appealing to the young learner, the author's approach and


treatment will provide anyone. of any age, with sound. easily followed.
explanations of how to program in BASIC.

Judith Miller is a teacher of Geography and Computer Programming


at the Convent of The Sacred Heart. Woldingham, Surrey.

ISBN 0-333-37995-0
Judith Miller
Beginning BASIC with the ZX Spectrum
• •
Macmillan Microcomputer Books
General Editor: Ian Birnbaum (General Adviser (Microelectronics in Education),
Education Department, Humberside County Council)

Advanced Graphics with the Acorn Electron


Ian 0. Angell and Brian J. Jones
Beginning BASIC
Advanced Graphics with the BBC Model B Microcomputer
Ian 0. Angell and Brian J. Jones
with the
Assembly Language Programming for the Acorn Electron
Ian Birnbaum ZX Spectrum
Assembly Language Programming for the BBC Microcomputer (second edition)
Ian Birnbaum
Using Your Home Computer (Practical Projects for the Micro Owner)
Garth W. P. Davies
Beginning BASIC with the ZX Spectrum
Judith Miller
Using Sound and Speech on the BBC Microcomputer
Judith Miller
Martin Phillips
Convent of the Sacred Heart
Woldingham
2 6 2— 3 6 1 2
• •
© Judith Miller 1985
All rights reserved. No part of this
publication may be reproduced or
transmitted, in any form or by any Dedicated to nzy parents
means, without permission

Cartoons (in text and on cover)


by Keith A. Miller

First published 1985 by


Higher and Further Education Division
MACMILLAN PUBLISHERS LTD
Houndmills, Basingstoke, Hampshire RG21 2XS and London
Companies and representatives throughout the world
Typeset in Great Britain by
RDL ARTSET LTD. Sutton, Surrey
Printed in Great Britain by
Camelot Press Ltd, Southampton

British Library Cataloguing in Publication Data


Miller, Judith
Beginning BASIC with the ZX Spectrum
(Macmillan microcomputer books)
1. Sinclair ZX Spectrum (Computer)—Programming
2. Basic (Computer program language)
I. Title
001.64'24 QA76.8.S625
ISBN 0-333-37995-0

(TT'Cr'_NISCHE/

rt
;. ^?71 1T .l Y e
Contents

Preface ix
Using the SPECTRUM + keyboard xi'

Introduction 1

Unit 1: Using the keyboard 3


Keyword mode, Letter mode, Capitals mode, Delete,
Shifted keys, Upper and lower case letters
Unit 2: Correcting mistakes 7
Moving the cursor to the left and the right
Unit 3: Making a program 9
RUN, NEW, LIST
Unit 4: More about numbering lines 11
Unit 5: Editing a program 13
Moving the cursor up and down
Unit 6: Extended mode. Using the cassette recorder 15
LOAD, SAVE, VERIFY
Unit 7: Testing your knowledge — questions on the Introduction
and Units 1-5 18
Unit 8: Numeric or simple variables 21
LET
Unit 9: String variables 25
Concatenation
Unit 10: Extracting parts of strings 29
Unit 11: Using the computer as a calculator 32
Unit 12: Controlling the print position 37
Print zones, commas and semicolons. TAB
Unit 13: Beginnings and ends of programs 41
REM, STOP
Unit 14: INPUT statement 42
Input prompts

vii
viii Beginning BASIC with the ZX Spectrum
• •
Unit 15: Program descriptions — algorithms 46
Flowcharts
Unit 16: Loops — using GOTO
Using the colon for multistatements
51
Preface
Unit 17: Comparisons 56
IF-THEN, Equals and not equals
Unit 18: More comparisons 65
Greater and less than, greater or equal to, The aim of this book is to teach programming in the BASIC language, as used by
less than or equal to, AND, OR the ZX Spectrum, to the complete beginner. It is not an `0' level or C.S.E. text-
book, although it does cover practically all the programming skills required at
Unit 19: Adding a counter 77 those levels. Mathematics has been kept to a minimum and therefore arithmetic
Unit 20: FOR-NEXT loops 82 functions such as ABS, EXP, LN, PI, SGN and SQR together with trigonometrical
functions SIN, COS, TAN, ASN, ARC and ATN have not been included.
Unit 21: READ and DATA statements 92 Each unit is written so that it relies only on information already covered in
Unit 22: Nested loops 99 previous units. This means that if the reader works through each unit in turn, he
or she will not need to have any knowledge other than that already encountered
Unit 23: Graphics using PRINT statements, colour and moving graphics 105 in earlier units. lf, however, the reader covers the units out of order, then
Graphics mode, PRINT AT, Colour — BORDER, PAPER, difficulties may be experienced unless he or she has previous experience.
INK, Moving graphics — PAUSE, INKEY$, FLASH, The book is best used with a microcomputer at hand as it is recommended
BRIGHT, INVERSE that the sample programs are typed in. The program listings are direct copies of
Unit 24: Arrays — DIM statement 116 the screen, thus providing an easy check that the program has been correctly
One-dimensional arrays, Two-dimensional arrays entered. Each unit gives plenty of opportunity to practise the skills just acquired
and solutions to the activities are included at the back of the book. It should be
Unit 25: Subroutines 132 remembered, however, that in programming there may often be several solutions
GOSUB and RETURN to a problem and therefore if the reader's program works successfully it is just as
Unit 26: Making music 140 acceptable as the solution given.
BEEP Woldingham, 1984 JUDITH MILLER
Unit 27: Some useful functions — RND, RAND and INT 150
Unit 28: High-resolution graphics — PLOT, DRAW, CIRCLE
and INVERSE 155

Unit 29: User-defined characters 170


BIN, POKE, USR
Unit 30: Some interesting string functions 173
LEN, CHRS, CODE, VAL
Unit 31: Using the printer 177
LPRINT, LLIST, COPY

Solutions 179

ix
• •
Using the ZX Spectrum + Keyboard

Although this book is based on the standard version of the ZX Spectrum, all
of the pro g rams and references to BASIC apply equally to the ZX Spectrum +.
If you are using a ZX Spectrum +, there will be minor variations in the steps
to follow to obtain certain of the symbols on the keys. Therefore, please dis-
regard the instructions in the text of this book on how to obtain certain
`Extended Mode' and other functions; instead follow the instructions in the
Spectrum + User Guide or the summary below. You will find that, in all cases,
the modifications will make it much easier to enter and manipulate information
from the keyboard.
The ZX Spectrum + is essentially a ZX Spectrum, provided with a real key-
board. All software that works on the ZX Spectrum will be compatible with
the Spectrum +, and interfacing with other items should be unchanged.
The obvious difference that the user will encounter is that of the feel and
use of the full-travel keyboard, which will make keying-in of material much
easier.
Earlier criticisms of the keyboard colouring has been taken into account, and
the positioning of many of the legends has been subtly altered to increase
readability.
There are several differences between the old and new keyboards — 18 extra
keys are added to the original 40 keys and, for the first time, there is a RESET
button and a conventional space bar.
The RESET button, situated on the right-hand side of the computer, should
be used with care — its effect is to switch the computer off and then on, thus
losing any program or data in the computer's memory. You will probably want
to use it only when the computer has `crashed' — that is, when the computer
fails to respond to any of your instructions.
The main difference between using the Spectrum and the Spectrum + lies in
the location and pressing of the following keys: `EXTEND MODE', 'GRAPH',
`DELETE', `EDIT', `SYMBOL SHIFT', `CAPS SHIFT', `CAPS LOCK', and
`SPACE'. The operation and principles of use remain unchanged.
See pages 8,20 and 21 of the ZX Spectrum + User Guide for full
information on the use of the keys.
Other changes requiring specific mention are:

1. The `arrow keys' which are used for moving the cursor when editing or when
playing many games have been moved from the number keys, and are to be

xi
xii Using the ZX spectrum + keyboard
• •
Using the ZX spectrum + ke y board xiii
found on either side of the space bar — with `up' and `down' to the right,
Number Keys
and `left' and `right' to the left.
Number keys operate in much the same way, and a couple of examples are
2. A welcome addition is the provision of a separate key to provide the
shown here.
quotation marks — which are used at the beginning and end of most
PRINT statements.
— Lower keyword
3. `DELETE', `EDIT', `CAPS LOCK' and `GRAPH' together with the ,' and Press EXTEND MODE and then
`;' keys each now get a key of their own, and `CAPS SHIFT' and `SYMBOL hold down SYMBOL SHIFT
and press the key
SHIFT' have a key on each side of the keyboard.
Upper keyword
Press EXTEND MODE
and then press the key

How to obtain the different functions on each key


OPEN #
Letter keys
These keys generally have five separate legends on them. On the moving part of
the key you will find three items — the letter itself, and either one word and a
symbol, or two words.
Just above the moving part of the key, you will find two words or
abbreviations.
To obtain the different words and symbols you need to press one or two Number
Press the key
other keys at the same time as you press the key on which the item is found.
A couple of sample keys are shown below. Symbol
Hold down SYMBOL SHIFT
-- Lower keyword or symbol and then press the key
Press EXTEND MODE, then
hold down SYMBOL SHIFT — Graphics symbol
and press the key Press GRAPH and then press the key
To obtain a reverse image of the graphics
Top keyword symbol, press GRAPH and then hold down
Press EXTEND MODE CAPS SHIFT and press the key
and then press the key

GOTO
THEN

Letter
Press the key
(with CAPS SHIFT
for capitals)

Lower keyword or symbol —


Hold down SYMBOL SHIFT
and then press the key

Upper keyword
Press the key

Note that the letter can only be obtained when the screen cursor is
an 'L', and that keywords can only be obtained when the cursor
is a'K'
• •

Introduction

The Microcomputer System

The system is composed of three main parts as illustrated below:

CENTRAL
INPUT OUTPUT
PROCESSING
DEVICE DEVICE
UNIT

The input device allows The Central The output device enables
you to enter either Processing Unit you to receive the result
instructions or information (usually shortened of the processing. The
into the computer. The to CPU) carries out device may be a television
device is usually a keyboard the instructions screen or a printer or both
which looks rather like a and deals with the
typewriter information to give
a result

1
• •
2 Beginning BASIC with the ZX Spectrum

OUTPUT DEVICE —
BACKING STORE Television
INPUT AND OUTPUT
DEVICE Unit 1: Using the keyboard

CENTRAL PROCESSING
UNIT

OUTPUT DEVICE —
Printer
Cassette player — 00000, OUTPUT
stores programs 00000,
on tape 0000 DEVICE —
Loudspeaker
j k\
INPUT DEVICE —
Keyboard

A computer is a machine that enables us to solve certain kinds of problem. It


uses symbols or characters such as are used in everyday life; for example, the
letters of the alphabet, the numbers 0 to 9, punctuation marks and some special
characters such as +, —,< and *. The ZX Spectrum uses a language called BASIC
which stands for Beginners' All-purpose Symbolic Instruction Code.

Turn on the computer.

After a few seconds the screen will look like this:

© 1982 Sinclair Research Ltd

Press the key marked ENTER.

A flashing K, called the cursor, appears on the screen. It is a signal from the
computer that it wants something to do; it is asking for a command. A command
must begin with a keyword. Keywords are written in white on all the letter keys.

3
Beginning BASIC with the ZX Spectrum
• •
4 Unit 1: Using the Keyboard 5

For example Now the computer is ready to obey the command.


letter A has the keyword NEW Press ENTER.
letter P has the keyword PRINT
letter R has the keyword RUN Your line of letters now appears at the top of the screen; the computer has
obeyed your command. The computer also gives you a message: 0 OK, 0 = I.
When the cursor is a K the computer is telling you that it is in keyword mode and This means that everything is OK; there are no mistakes and one line has been
if any letter is pressed a keyword will appear on the screen, not a letter. If you executed.
want the computer to print something you must begin the command with the
keyword PRINT found on key P. Press ENTER.

Press PRINT. (Notice that the whole word appears; on many computers the The letters disappear and the flashing K returns to the screen. The computer is
keywords have to be typed in.) back in keyword mode.
The Spectrum can print small letters, as you have already seen, called lower
(If you press the wrong word remove it by pressing CAPS SHIFT (bottom left- case letters or capital letters called upper case letters. When the keys are pressed
hand corner) and DELETE (top right-hand corner) at the same time.) lower case letters are automatically printed. To obtain upper case letters CAPS
The cursor has now changed to a flashing L which is a signal from the com- SHIFT must be held down while the required letter is pressed.
puter that it wants to know what it is to print. The computer wants some letters
or other characters to print and is now in letter mode. The Spectrum will print TYPE: PRINT " (remember inverted commas are SYMBOL SHIFT and P).
letters (text) only if they begin with inverted commas or quote marks ("). These TYPE: The alphabet using alternate upper and lower case letters. (If you make a
are also on key P and are obtained by pressing SYMBOL SHIFT and key P at the mistake remove the wrong letter by pressing CAPS SHIFT and DELETE.)
same time. At the end of the alphabet finish with inverted commas.
Press ENTER.
Press SYMBOL SHIFT and P at the same time.
The alphabet will appear at the top of the screen and the same message as before
The screen will now look like this: will be written at the bottom of the screen.
Press ENTER.
When writing a sentence the words need to be spaced out correctly; this is
achieved by using the key marked BREAK/SPACE. Practise this by typing in the
next sentence.
PRINT" ^
TYPE: PRINT " I am learning to program on a ZX SPECTRUM using the
language BASIC "
If you look at the keys you will notice that most have words or symbols written
on them in red. For example Press ENTER.
key M has a full stop or decimal point When writing sentences it is possible to use the correct punctuation marks. For
key N has a comma example
key X has a pound sign
(,) comma — shifted key N
Like the inverted commas these can only be obtained by pressing SYMBOL (;) semi-colon — shifted key 0
SHIFT at the same time as the key required. For convenience, in future, these (:) colon — shifted key Z
red symbols will be referred to as shifted keys. (.) full stop — shifted key M
Type in a short line of letters. (?) question mark — shifted key C
(!) exclamation mark — shifted key 1
Inverted commas are also needed at the end of the line. (') apostrophe — shifted key 7
Press SYMBOL SHIFT and P. Practise using the keyboard by trying any of the following exercises. Remem-
• •
6 Beginning BASIC with the ZX Spectrum

ber to start each line with the keyword PRINT followed by inverted commas.
Finish each exercise with inverted commas and then press ENTER. If you forget
either the keyword or the inverted commas and try to enter a line of text, the
computer will give you a question mark which indicates an error. Unit 2: Correcting mistakes
1. TYPE: a,B;C:d,e!F?gH,i;J.
2. Type in the numbers 1 to 20 with a comma separating each number (note
that number 0 is on key marked DELETE and looks like this: 0. A capital
letter 0 cannot be used in its place).
3. Type this sentence: i
THE quick BROWN fox JUMPED over the LAZY dog.

4. Write a short letter to a friend.

If you wish to type in upper case letters for several words the computer can be
put into capitals mode. This is done by pressing CAPS SHIFT and CAPS LOCK
(key 2) at the same time. The cursor changes to a flashing C reminding you that
the computer is in capitals mode. Try this.

TYPE: PRINT "COMPUTER PROGRAMMING IS FUN"


Press CAPS SHIFT and CAPS LOCK again; this puts this computer back into
letter mode.
Press ENTER.

At the end of each exercise always clear the screen or remove the old program In unit 1 you learned that a letter could be removed by pressing CAPS SHIFT
from the computer. At the moment all you need to do is to press ENTER. Unit and DELETE. Sometimes mistakes are not noticed immediately and you may
3 explains how to remove a program. have typed in a whole sentence before realising that a mistake has been made. In
order to correct this mistake it is not necessary to delete the whole sentence.

Type in this sentence as it is written including all the mistakes

PRINT "Their are five speling inisteakes inn this sentence."

Do not press enter.

To correct the sentence the L cursor has to be moved. CAPS SHIFT and key 5
moves the cursor to the left and CAPS SHIFT and key 8 moves it to the right.
The word `sentence' should be spelt `sentence'.

Using the correct keys move the cursor so that it lies to the right of the wrong
letter: sentaLnce. (When you move the cursor hold CAPS SHIFT down firmly
otherwise you will have 5s and 8s appearing in your sentence.)
Now press CAPS SHIFT and DELETE and the `a' will disappear. Press key E and
the word is now correct.

The word `speling' has an `1' missing.


Move the cursor into the position of the missing letter and then press key L.

7
8

Beginning BASIC with the ZX Spectrum

Now correct the rest of the sentence which should read: "There are five spelling
mistakes in this sentence."
Press ENTER.
The correct sentence now appears at the top of the screen. Unit 3: Making a program
Other examples to try.
(a) The whether tooday is dul and cloudie; I fink it will reign.
Correct version: The weather today is dull and cloudy, I think it will rain.
(b) The hair jumpped over the fense. TYPE: 10 PRINT "This is a program."
Correct version: The hare jumped over the fence. Press ENTER.
(c) The preist preyed four woride piece.
Correct version: The priest prayed for world peace. The whole sentence plus the number and the keyword PRINT appears at the top
of the screen. The computer is now making a program by storing the information
for later use.
TYPE: 20 PRINT "A program consists of a list of instructions or statements."
Press ENTER.
TYPE: 30 PRINT "Program lines are numbered in tens."
Press ENTER.
Notice that at the end of every line you had to press ENTER. This transferred
the line to the top of the screen and made it part of the program. You cannot
type in another statement until this has been done.
Press the keyword RUN on key R followed by ENTER.
The computer now executes or performs the program and gives a similar message
to the one it gave before. Each statement will be printed in the same order as that
in the original program. In other words the numbers at the beginning of each line
tell the computer in which order to follow the instructions.
Press ENTER.
The program has returned to the screen. It can be executed as many times as you
wish but the computer will only do this if you give it the command or keyword
RUN followed by ENTER. This should be done every time a program is typed in.
It is the only way of telling if the program is correct. The computer will not
execute a program that has mistakes or bugs in it. Also it is the only way of
obtaining the result of your program.
Press the keyword NEW on key A followed by ENTER.
The program has now gone. It has been removed from the computer's memory.
Try the following exercises. Remember to RUN each program and then
remove it from the computer before you start the next.
(1) Type in a program that prints out your name and address as it would appear
on an envelope.

9
10 Beginning BASIC with the ZX Spectrum

(2) Type in a program that prints your name, age and date of birth.
(3) Type in a program that prints out information about your family.

Unit 4: More about numbering lines


The program list can be returned to the screen by pressing ENTER. Later on as
your programs get longer they will not necessarily fit on to the screen; you should
then press LIST (key K) followed by ENTER. This will give you as much pro-
gram as will fit on to the screen and the message `scroll'. You then press any key
Program lines are usually numbered in intervals of ten; for example, 10, 20, 30,
other than N for `no' or BREAK/SPACE and the next part of the program will
40 etc. The reason for this is that when a program is first made lines are often
appear. This can be repeated until you reach the end of the program. If you only
missed out by mistake. Having intervals of ten between lines enables a further
want a certain section of the program then press LIST and the line number you
nine lines to be inserted later if necessary. For example
require, followed by ENTER.
10 First line of program
11
12
13
14
15 Space for nine more lines if needed
16
17
18
19
20 Second line of program
Type in the following instructions which were given to a girl who did not know
how to change her socks.
10 PRINT "How to change socks"
20 PRINT "Take off shoes"
30 PRINT "Put on clean socks"
40 PRINT "Put on shoes"

Like a computer the girl is very stupid and will only do exactly what she is told
to do, so one day she finds that she cannot get her shoes on as nobody told her
to take off her dirty socks! Therefore the program must be improved.
TYPE:
25 PRINT "Take off dirty socks"

Press ENTER.
You will notice that line 25 is automatically inserted into the correct place in
your program. If the program had been numbered 1, 2, 3 and 4 this would not
have been possible as the computer only accepts whole numbers at the beginning
of lines; you cannot use 1.5 or 1.75.

11
12 Beginning BASIC with the ZX Spectrum

TYPE:
10 PRINT "How to wash hands"
20 PRINT "Put plug in basin"
30
40
PRINT
PRINT
"Turn off taps"
"Rub soap between hands"
Unit 5: Editing a program
50 PRINT "Take plug out of basin"
60 PRINT "Dry hands"

At least four instructions have been deliberately left out.

Type in the missing instructions using the correct line numbers. Editing enables the programmer to alter a mistake in a line or improve a line that
is already part of a program.
Type in this program including all the deliberate mistakes.
10 PRINT "Helo fred."
20 PRINT "Doyou like computing

30 PRINT "No,not MUCH."


40 PRINT "never mind,you will
to like it."

There are one or two mistakes in each line of this program.


Line 10 — 'helo' is spelt wrongly and fred does not begin with a capital letter.
Line 20 — there is no space between 'Do' and `you' and the question mark has
been missed out.
Line 30 — the word 'much' is written in capital letters.
Line 40 — the sentence does not begin with a capital letter and a word is missed
out.
These grammar mistakes will not be noticed by the computer; it has never been
given English lessons so it will accept an y punctuation or spelling. You could
write a sentence of complete rubbish and the computer would print it if com-
manded to do so.
RUN the program; you will see that the mistakes are just ignored. The program
is printed exactly as it was typed in. Return the program to the screen by
pressing ENTER.
However, as we progress to more complicated programs it will be necessary to
correct mistakes especially if they are in BASIC which the computer does under-
stand, so we will learn how to do this.
To correct or edit the program we need to bring each line that has a mistake
in it back to the bottom of the screen. Look at line 40, you will see a> sign
known as the program cursor lying between the number and the keyword
PRINT.
Press the key marked EDIT (key 1) and CAPS SHIFT at the same time.

Line 40 should have returned to the bottom of the screen where it can be

13
14 Beginning BASIC with the ZX Spectrum
• •
corrected in the normal way. (There is still a copy of this line left in the
program.)
Correct line 40 (see unit 2). When it is correct press ENTER.
Unit 6: Extended mode. Using the
The correct line now takes the place of the incorrect one. You do not finish up
with two lines 40. cassette recorder
Next we have to correct line 30. In order to do this we must move the program
cursor (>) up to this line.
Look at key 7, it has a small white arrow pointing upwards above it. Press key 7
and CAPS SHIFT at the same time. This moves the program cursor up one place;
it should now be between 30 and PRINT. Extended mode
Press EDIT and CAPS SHIFT at the same time — line 30 is now at the bottom of
the screen. Correct and then return to the program. Some of the commands used in this lesson require the computer to be in extend-
Move the program cursor up to line 20 (key 7 + CAPS SHIFT). ed mode. This is because we need to use some of the green and red words written
Bring line 20 to the bottom of the screen (key EDIT + CAPS SHIFT). above and below the keys. For example, we will need VERIFY, written in red
Return to program. below key R, and LLIST, written in green above key V. The computer is put
Edit line 10. into extended mode by pressing CAPS SHIFT and SYMBOL SHIFT at the same
time which changes the flashing cursor to an E. Once in extended mode any
If you move the program cursor too quickly by pressing key 7 more than once word in green above a key can be obtained; for example, pressing key A will
you may pass the line you wish to correct. produce READ. To obtain the red words below the keys SYMBOL SHIFT has
The program cursor can be moved downwards by pressing key 6 and CAPS to be pressed again at the same time as the required key; for example, SYMBOL
SHIFT. SHIFT and key X will produce INK.
Sometimes it is necessary to remove or delete a whole line from a program.
This is easily done by typing in the number of the line followed by ENTER. Try
this on the previous program. Using the cassette recorder
TYPE: 10
Press ENTER. Programs recorded on cassette takes are known as software. Only software
prepared for the Spectrum can be used on this machine. If you buy a tape, such
as a game, make certain that your computer has enough memory for that pro-
gram. Your Spectrum will either have a 16K or a 48K memory; you cannot run
Activity:
a 48K program on a 16K machine.
Type in a program that prints out four sentences about your school. Each
Loading a program
sentence must contain one or two deliberate mistakes. RUN the program. Correct
1. Using the lead provided connect the EAR socket of the computer to the EAR
or edit the program. RUN the corrected program.
socket of the cassette recorder. Use the same coloured leads. Do not connect
(Remember to remove the old program from the computer — keyword NEW
the MIC leads.
followed by ENTER.)
2. Turn the volume control on the cassette recorder up to almost full. Do not
touch this control while the program is loading. If you have a tone control,
move this to almost full.
3. Insert the tape into the cassette recorder with the side that you require
uppermost.
4. Type into the computer the keyword LOAD (key J) followed by the name of
the program in quotation marks. For example, if you are loading the tape

15
16

Beginning BASIC with the ZX Spectrum

Unit 6: Extended Mode. Using the Cassette Recorder 17

Horizon supplied with your Spectrum type: LOAD "sidea". (Notice the way Checking that your program has been recorded
"sidea" is written, you must type in the name in exactly the same manner. 1. Rewind the tape back to the place where you started.
"SIDEA" is not the same as "sidea".) 2. Connect the EAR socket on the cassette recorder to the EAR socket on the
5. Press ENTER. computer. Use the same coloured leads. Disconnect the MIC leads.
6. Press the PLAY button on the cassette recorder. 3. Type in the keyword VERIFY (below key R — extended mode and then
7. Now wait. If you are loading your own program then the name of the program symbol shift + R.) followed by the name of the program in quotation marks.
will appear on the screen. With bought tapes other messages and pictures may For example VERIFY "Robots".
appear. Moving horizontal lines are visible around the border of the screen; 4. Press ENTER.
this is quite normal. If the program is not loading you will be given an error 5. Press PLAY button on cassette recorder.
message such as R Tape loading error. In this case stop and rewind the tape. 6. Wait. The name of the program should appear together with the moving
Loading errors are usually caused by: horizontal lines if the program has been recorded successfully. When the
computer has finished checking it will give the message OK. This means that
(a) The volume control being too high or too low. If it is too low the computer your program is on the tape. If the name does not appear or the message R
cannot pick up the signals and if it is too high the signals will be distorted. Tape loading error does appear then something has gone wrong. Try saving
Vary the level slightly, as appropriate. the program again.
(b) The wrong leads being connected.
(c) The wrong name being typed in. Reasons why the program may not have recorded are:

Check all of these things before you try again. (a) Volume control is too high or too low.
(b) Wrong leads are being connected.
8. When the message OK appears your program has loaded so stop the tape. (c) You may have tried to record on the coloured leader at the beginning of
With bought tapes you are sometimes told when to stop the tape. the tape.

Saving a program If your cassette recorder has a counter make a note of the number before you
Any program that you have typed into your computer can be saved or save a program. This can be very useful if your program is in the middle of a
recorded on to a tape. tape as it takes the computer a long time to search through a tape looking for a
program. However, if you use the fast forward button and go to approximately
1. Using the lead provided connect the MIC socket on the computer to the MIC the right place on the tape, finding the program will be much quicker.
socket on the cassette recorder. Use the same coloured leads. Do not connect
the ear sockets.
2. Turn the volume control on the cassette recorder up to almost full if you do
not have automatic-level recording.
3. Insert an empty tape or any tape that has space on it into the cassette recorder.
4. Type into the computer the keyword SAVE (key S) followed by the name of
the program in quotation marks. You can call your program anything you like
provided that the name consists only of numbers and letters and is not longer
than ten characters. For example:
SAVE "Robots".
5. Press ENTER.
6. A message appears on the screen: Start tape, then press any key. Press the
PLAY and RECORD buttons on the cassette recorder and then any key on
the computer.
7. Now wait. Moving horizontal lines appear around the border of the screen.
8. When the end of the program is reached you will be given the message OK:
stop the tape. Unfortunately OK does not necessarily mean that your program
has been recorded; you need to check this.
• • Unit 7: Testing your Knowledge 19

17 . Quote marks are written in red on key P; give another example of a symbol
written in red on a key.
18. What is meant by a shifted key?
Unit 7: Testing your knowledge- 19. What is the difference between lower and upper case letters?
20. How is an upper case letter obtained?
questions on the Introduction 21. How is a space between words achieved?
22. Can the letter 0 be used in the place of the number nought?
and Units 1-5 23. (a) What is meant by capitals mode?
(b) How do you put the computer into this mode?
(c) How do you get the computer out of this mode?

Try to answer from memory as many questions as you can. Look up those you
do not know in the appropriate unit - the questions are divided into sections. Unit 2: Correcting mistakes
Check your answers at the back of the book.
24. The flashing L can be moved to the right or to the left by pressing key 5 or
key 8. Which other key has to be pressed at the same time?
Introduction: The microcomputer system 25. Look at the word below, which has the flashing L placed in the centre of it.
If CAPS SHIFT and DELETE were pressed which letter would be removed,
1. Name an input device. the `u' or the `t'?
2. Name two output devices.
3. Name a device that can be used for both input and output. compuLter
4. What happens in the Central Processing Unit?
5. (a) What is a character?
(b) Give examples of characters. Unit 3: Making a program
6. (a) What is the language used by this computer?
(b) What is the full meaning of this word? 26. What must be typed in at the beginning of a line if you wish the statement
or instruction to become part of a program?
27. If you have finished typing in a line of a program how do you transfer it to
Unit 1: Using the keyboard the top of the screen?
28. What does a program consist of?
7. What mode is the computer in when a flashing K is on the screen? 29. How do you make the computer perform or execute your program?
8. What mode is the computer in when the computer is first switched on? 30. When a program is performed do the line numbers and commands appear
9. What is the flashing K called? on the screen?
10. In which mode does the computer have to be in before you can use a 31. After a program has been performed how do you return the program listing
command such as PRINT? to the screen?
11. Do commands appear on the screen as one word or do you type in each 32. Can a program be performed more than once?
letter separately? 33. How do you remove the program from the computer's memory?
12. On which letter key would you find PRINT?
13. How do you remove or rub out a letter?
14. What mode is the computer in when a flashing L is on the screen?
15. When does the flashing K change to a flashing L? Unit 4: More about numbering lines
16. (a) Quote marks are part of the computer's language; when are they used?
(b) How are the quote marks obtained? 34. Why are program lines usually numbered in tens?
35. What is wrong with the program that follows:
18
20

Beginning BASIC with the ZX Spectrum

10 PRINT "Hello."
20 PRINT "How are you?"
40 PRINT "I'm sorry to hear that."
30 PRINT "Not too well." Unit 8: Numeric or simple variables

Unit 5: Editing a program

36. What does editing a program mean?


37. (a) What is the > sign which appears by a line in a program called?
(b) How is this sign moved up or down?
38. How do you return a line to the bottom of the screen when it is already
part of a program?
39. Having corrected a line in a program and returned it to the program do you
have two versions of the line — a correct one and an incorrect one?

General

40. Rewrite the program below correcting all the mistakes.

1 PRINT "Do you like robots?


20 PRINT Yes.
15 PRINT "I don't."
30 LET "I think they are great big metal idiots."

If there were many questions you could not answer you probably need to
read through these units again. If you answered correctly from memory 30 or A numeric or simple variable is a storage space in the computer's memory which
more questions then you now know how to handle the Spectrum and are ready is given a name. The storage space stores only numbers, hence its name. The
to proceed to more advanced programming. easiest way to imagine this is to think of a box that has a name and contains a
number. The example below shows a box called `A' storing the number 15.

BOX OR VARIABLE CALLED 'A'

The computer uses the keyword LET (key L) and the equals sign (_), which
is shifted key L, to set up the variable. For example

LET A = 15

21
• • Unit 8: Numeric or Simple Variables 23
22 Beginning BASIC with the ZX Spectrum
Edit lines 40, 50 and 60
The computer now knows that every time `A' is used in the program it is really
referring to the contents of the box. The next program illustrates this point. 40 PRINT a
50 PRINT b
TYPE: 10 LET A = 15
60 PRINT c
20 PRINT A
RUN DO NOT REMOVE RUN DO NOT REMOVE
The program shows that in the PRINT statement in line 20 there are no quote The result is the same. The computer does not distinguish between capital and
marks because we are not asking the computer to print letter A but the contents small letters when using variables. Other names can also be used for variables but'
of `A' and therefore 15 appears on the screen. If we wanted the letter printed there are two rules to remember:
then quotes would have to be used in the normal way. This can be shown by
adding one line to the program. (1) The name must begin with a letter.
(2) The name can consist only of letters and numbers.
Add to the program:
For example the following names are allowed:
15 PRINT "Box or variable A contains the number"
apples
RUN the program and then remove CAR all begin with letters
ZX81 all consist of letters and numbers only
There may be several variables in a program provided that they each have
Spectrum spaces between words are also allowed
different names.
total 2
Two cats
The following names are not allowed
2 apples (begins with a number)
Spectrum ! (exclamation mark is not a letter or a number)
CAR + TON (plus sign is not a letter or a number)
The last important thing to know about a numeric variable is that the box or
storage space can remember only one number at a time. It will always store the
Here there are three boxes or numeric variables. Box `A' remains the same and is last number that it is given.
unaffected by adding two more boxes. Box `B' contains 20 and box `C' 25. A Add to the previous program:
program using these variables would need three LET statements:
TYPE: 70 LET A=150
80 LET B =200
10 LET A=15 90 PRINT A
20 LET B =20 100 PRINT B
30 LET C=25 110 PRINT C
40 PRINT A
50 PRINT B
60 PRINT C RUN
RUN DO NOT REMOVE The result is: 15 (first value of box A)
The result is simply: 15 20 (first value of box B)
20 25 (first value of box C)
25 150 (second value of box A)
The name of the variable does not have to be a capital (upper case) letter, it 200 (second value of box B)
could equally well be a small (lower case) letter. Try this: 25 (first value of C — this box has remained unchanged.)
24 Beginning BASIC with the ZX Spectrum
• •
It is not possible to appreciate the real value of numeric variables at this stage
and you may be thinking: why not print out the numbers straight away (for
example, PRINT 15, PRINT 20 etc.)? However, they are a very important part
of programming and gradually you will see that they have many uses. You will Unit 9: String variables
meet them next, in greater detail, in unit 11.

Activities

Write out the results of the following programs.


1. 10 LET x=32
20 LET y=44
30 PRINT x
40 PRINT X
50 PRINT "y"

2. 10 LET W=68
20 LET dogs=2
30 LET W2=53
40 LET w=72
50 PRINT W
60 PRINT "dogs"
70 PRINT W2

Which of the following names for numeric variables are allowed:


(a) ABC (b) 2ABC (c) abc (d) Two ABC (e) Abc !
(f) Abc (g) A+B+C (h) A(B)C (i) A2B2C (j) a b c
Revision: Characters are the letters of the alphabet, the numbers 0 to 9, punctua-
tion marks and special symbols such as +, —, *.
A group of characters is a string. Some examples of strings are:
dog (a word)
Queen Victoria (a name)
ZX81 (a mixture of letters and numbers)
12, W(2) (a mixture of characters)
A string can be any mixture of characters; even a space is counted as a character.
A string variable is a storage place in the computer that remembers groups of
characters or strings. It is very similar to a numeric variable except that the
storage place name must be a single letter of the alphabet with the sign for a
dollar ($) which is shifted key 4. The characters to be stored in the string variable
must be contained in inverted commas. For example
LET a$ = "Fred"
LET b$ = "dog"
LET z$ = "1,2,3,4,5."

25
26

Beginning BASIC with the ZX Spectrum
• Unit 9: String Variables 27

TYPE: 60 PRINT "My age is ";a$


70 PRINT "I live in ";t$;" whi
10 LET a$="This is a string" ch is in the county of ";c$
20 LET s$="A string is a group
of characters" RUN the program and notice the result.
30 PRINT a$
40 PRINT s$ If your program will not RUN examine it closely for any omissions; you may
have missed out a variable.
Notice that as for numeric variables no inverted commas are needed with the There are only 26 storage spaces in the computer for strings, one for each
PRINT statement as it is not a$ and s$ that are to be printed but the contents of letter of the alphabet.
a$ and s$.
Which of the following names can be used as storage places for string variables?
RUN the program. Notice the result. (a) a$, (b) M8, (c) T75, (d) B$ , (e) C$3, (f) 8P$
String variables can be combined with other words to make up parts of (g) 2$, (h) KS, (i) w$ ,. (j) aa$, (k) ax$ , (1) a
sentences. The variables are not contained within inverted commas, as previously
Think of all the variables that you have met so far and decide which of the
mentioned, but must be separated from the other words in the sentence by a
following are correct BASIC statements.
semi-colon (;). The semi-colon is part of the BASIC language and cannot be
(a) LET A = 87 (e) LET L17 = 38
omitted. For example
(b) LET R$ = "cat" (f) LET eggs = 50
10 LET a$ _ "Fred" (c) LET m$ = 1234 (g) LET milk = "twenty-two"
20 PRINT "Hello"; a$; "How are you?" (d) LET K8 = "Spectrum" (h) LET 8A = 6
The result of this program would be:
Programming activities (remember to type in and RUN each program)
HelloFredHow are you?
As you can see the words are all squashed together. This is because the semi- 1. a$ = "John"
colon also brings the next character to be printed right next to the previous one. s$ = "school"
Therefore, it is necessary to include spaces as part of the sentence. (Note that Write a program that prints out these two variables in a sentence.
spaces will be frequently used in future programs and will be represented in the 2. m$ = "Mary"
text by a small dash (-). In listings obtained via the computer printer, only the a$ = "Anne"
space itself will appear.) For example, b$ = "12 years"
c$ _ "13 years"
10 LET a$ = "Fred" Write a program, using the variables, that prints out the ages of Mary and
20 PRINT "Hello-"; a$; "-How are you?" Anne.
The result will now be: 3. Use string variables for the names of two friends and the places where they
live. Using these variables in the correct places, print two sentences that give
Hello Fred How are you? this information.
Notice that the spaces came inside the inverted commas as they are counted as 4. Print out a letter that invites a friend to a party. Use the following variables:
characters and are printed, although invisible, in the same way as any other n$ = name of friend.
character. d$ = date of party
w$ = name of day of the party
TYPE: t$ = time of the party.
10 LET n$="your name" Type in your own
20 LET a$="your age in years" personal details
30 LET t$="your home town or v
here: not the
illage"
40 LET c$="your county" words "your
50 PRINT "My name is ";n$ name" etc. String variables can be added together; this is known as concatenation
28

Beginning BASIC with the ZX Spectrum

TYPE:
10 LET a$="Miss "
20 LET b$="Miller"
30 PRINT a$+b$
40 LET c$="Con"
Unit 10: Extracting parts of strings
50 LET d$="vent"
60 PRINT a$+b$;" teaches at th
e ' ;c$+d$
RUN the program and notice the result.
TYPE:
10 PRINT "abcdefgh"
20 PRINT "abcdefgh"(1 TO 3)
Activities
shifted F — do not type in
5. Type in a program, using string variables, that adds your Christian name to
the letters T and 0 separately
your surname and then prints out the result. 30 PRINT "abcdefgh" (5 TO 8)
6. Using three string variables divide up the name of a town. Type in a program 40 PRINT "abcdefgh"(2 TO 6)
that adds up the name and prints it out. 50 PRINT "abcdefgh" (4)
7. THE GREEDY BOY ATE MANY CREAM BUNS AND JAM TARTS. RUN the program.
Use a variable for each word in the sentence. For example
The result is: abcdefgh
a$ = "THE" b$ _ "GREEDY" etc. abc
Write a program that adds together some or all of these variables to make efgh
different sentences. bcdef
d
You can see that any part of the string can be extracted (taken out) by using
numbers in brackets by the side of the string. For example (1 to 3) means print
all the characters from the first which is 'a' to the third which is 'c', so the result
is 'abc'. If there is only one number in the bracket, as in line 50, this means just
print the character at that number, in this case the fourth which is 'd'.
TYPE: 10 PRINT "aybxcwp"
Add lines that will produce these results using the method described above:
ayb
cwp
x
bxcw
RUN your program and check your results.
Instead of continually typing in the string of characters it is much quicker to
use a string variable.
TYPE:
10 LET a$="Father Christmas"
20 PRINT a$
30 PRINT a$(1 TO 6)
40 PRINT a$(8 TO 16)

29
30 Beginning BASIC with the ZX Spectrum Unit 10: Extracting Parts of Strings 31

RUN DO NOT REMOVE 2. Add lines so that the following are printed:
The result is: Father Christmas toe, pod, ate, pad, depot
Father
Christmas RUN the program. Check that your results are correct.
You may have wondered why `Christmas' was not (7 to 15) as `C' is the Remove the program.
seventh letter and `s' the fifteenth; but the space between the two words is also 3. Write a program that stores the words `ladle' and `spoon' and then prints out
a character so it is also counted. `paddle' and `lap'.
Add lines to your program to print out five more words taken from `ladle'
Add to the program so that the following extracts are printed: and `spoon'.
(a) her (d) Fat
(b) rist (e) C
(c) mas
Use this as a guide:
1 2345 678 9 10 11 12 13 1415 16
Fat he r Ch r i s t m a s
RUN the program and check your results.

Extracting and concatenation

This is simply taking away some parts of a word and adding it to parts of another
word. See lines 40 and 50 of the program below
TYPE:

10 LET b$="baked"
20 LET p$="potato"
30 PRINT b$+p$
40 PRINT b$(1 TO 2)+p$(3)
50 PRINT p$(3 TO 4)+b$(3 TO 4)

RUN DO NOT REMOVE


The result is: bakedpotato
bat
take
Each word is treated separately in this case as they are stored in two different
string variables, therefore the first letters in both words have the number one.

Activities

1. Alter line 30 so that `bakedpotato' is printed with a space between the two
words.
• •
Unit 11: Using the Computer as a Calculator 33

Where two operators are of equal importance (multiplication and division are
equal, and addition and subtraction are equal), the computer works out the
operations in the order from left to right. For example
Unit 11: Using the computer as a 10 * 10/5 = 100/5 = 20
10/l0*5 = 1 *5 =5
calculator 10-5+6=5+6=11
The computer will also work out parts of expressions contained in brackets first;
before multiplication and division. For example
3 + 2 * 4 = 11 but (3 + 2) * 4 = 20
For arithmetic you use four main operators: add, subtract, multiply and divide.
BASIC language has the same operators although two are printed differently. Activities

Everyday symbol Meaning Basic symbol Key 4. Calculate the following


+ add + shifted K (a) 6 + 4 * 2 (d) (10 — 2) * 3
subtract — shifted J (b) (6 + 4) * 2 (e) 6 + 18/2
x multiply * shifted B (c) 10 — 2 * 3 (f) (6 + 18)/2
divide / shifted V Type in a program that will check your answers.
Activities 5. If A has the value of 2, B has the value of 5 and C the value of 10 calculate the
following:
1. Write the following arithmetic expressions using BASIC symbols for the (a) A + B + C (d) C/A
operators. (b)B — A (e)A+C—B
(a) 3+ 7 (d) 5 x 2+ 8 (g) 5 x 6 x 7 (c)B*C (f)A*C
(b) 3 x 7 (e) 24 — 4 x 3 (h) 81 — 27 + 2
(c)8-4 (f) 30-3+2 (i) 23-2x9 TYPE:
2. The following arithmetic expressions have been written in BASIC. Calculate 10 LET A=2
the answers. 20 LET B=5
(a) 2 + 10 + 5 (d) 50/2 30 LET C=10
40 PRINT A+B+C
(b) 2 * 100 (e) 12 — 7 50 PRINT B—A
(c)2*5*10 (f) 6*5/10 60 PRINT B*C
70 PRINT C/A
A computer always performs multiplication and division before adding and 80 PRINT A+C—B
subtraction. 90 PRINT A*C
3. Which is the correct answer for each of the following? RUN the program and check your answers to the previous exercise.
(a)2+5*4 = 32 or 26? As you can see from the program that you have just typed in, arithmetic is usually
(b)3*6-5 = 13 or 3? done by the use of numeric variables and the keyword LET. Lines 10, 20 and 30
(c) 4 + 8/2 = 6 or 8 ? set up the variables, therefore the storage places in the computer looked like this:
(d) 6/2-2 = 1 or 2?
A C
Type in this program to check your answers. 2 5 10
10 PRINT 2 + 6 * 4 Now let us consider this program:
20 PRINT 3 * 6 — 5
30 PRINT 4 + 8/2 10 LET B = 15
40 PRINT 6/2 — 2 20 LET C = 10
30 LET A = B — C
32
•Unit 11: Using the Computer as a Calculator 35
34 Beginning BASIC with the ZX Spectrum

After lines 10 and 20 of the program the storage spaces in the computer look Programming activities
like this:
7. Type in a program that has two numeric variables and then prints out:
A
B 15 C 10 (a) their sum (addition)
(b) their difference (subtraction)
After line 30 has been executed the y look like this: (c) their product (multiplication)
(d) their quotient (division).
A
5 B 15 10 8. The length of a rectangle is 35 centimetres and the breadth is 16 centimetres.
Type in a program that uses variables for the length and breadth and then
calculates:
If we add to the program:
(a) the area of the rectangle (breadth * length)
40 LET A = B * C (b) the perimeter of the rectangle (the sum of all four sides).
the storage places will now look like this: Like string variables, numeric variables can be combined with words. Semi-
colons are used to separate the words from the variables.
e
A 150 15 C 10
TYPE:
Notice that the content of A has changed. Storage space `A' retains only the 10 LET c=100
latest piece of information. If we add another line to the program the contents 20 LET p=40
of the storage spaces change accordingly. 30 LET t=80
40 PRINT "My ZX Spectrum cost
50 LET B = A + C ";c;" pounds"
50 PRINT "The printer cost ";p
A
150 B 160 10 pounds"
60 PRINT " and the television
6. Copy the programs listed below and the storage boxes. cost ";t;" pounds"
70 PRINT "The total cost of my
Fill in the values at the storage spaces A. B and C after each line of these equipment was ";c+p+t;" pounds"
programs has been executed.
PROGRAM STORAGE SPACES RUN the program and notice the results.
A B C Add a line to the program that prints out the total cost of all the equipment in a
(a)
room that has six microcomputer systems. (Note: the computer should do the
10 LET A =12
calculating, not you!)
20 LET B = 5

Programming activities
30 LET C = A * B

9. The program below states that Mr Blake buys 9 bags of cement at 93 pence
40 LET A = C — B
per bag and then calculates the cost. Rewrite the program correcting all the
(b) mistakes.
10 LET A = 20
10 LET x = "Mr Blake"
20 LET B =A*3 20 LET b$ = 93
30 LET C="9"
30 LET C = A/4 I 40 PRINT A bag of cement costs-" ; b$ ; "-pence.
50 PRINT x$ "-ordered-" c "-bags."
40 LET B = A * C
60 LET "The cost of"; c ; "-bags is"; b$/c
• •
36 Beginning BASIC with the ZX Spectrum

10. The program below gives the names of three children and their examination
results. It prints out this information and then calculates the average mark.
Rewrite the program correcting all the mistakes.
10 LET a$ = Susan Smith Unit 12: Controlling the p rint position
20 PRINT b$ = "John Brown"
30 LET c = "Mary Turner"
40 LET a = "43"
50 RUN b$ = 68
60 LET c = "seventy-three"
70 PRINT "a$"; "-gained-"; aS; "-marks."
80 PRINT b$; -gained-; b ; -marks."
90 PRINT c "-gained;" c$; "marks."
100 LET "The average mark was-"; a$ + b$ + c/3
11. Complete the program below which calculates the length of a car journey.
The speed of the car is 65 miles per hour and it travels for 6 hours.
10 s=65
20 LET _=6
30 PRINT "Speed of car is" ; — ; "miles per hour."
40 PRINT "Time spent travelling is" ; — ; "hours."
50 "Length of journey is" ; . — — ; "miles."
12. Type in a program that uses variables for your: There are two print zones on the Spectrum screen. Zone 1 is on the left and
(a) age Zone 2 on the right. Zone 2 begins in the 16th space across the screen.
(b) weight
(c) height
(d) size of shoes
and then prints out this information in a descriptive paragraph. ZONE 1 ZONE 2
13. Type in a program that uses variables for all the different ages of people in
your family and then calculates and prints out:
(a) the sum of the ages of your family
(b) the average age of your family
14. A lorry carries 1154 kilograms of sand in one journey.
It makes 19 journeys every four weeks. Write a program that calculates and To move a PRINT statement into Zone 2 a comma is used.
prints out: TYPE: PRINT "Zone 1", "Zone 2"
(a) the amount of sand carried every four weeks Press ENTER and notice the result.
(b) the amount of sand carried in 48 weeks. Now TYPE: PRINT "Zone 1"; "Zone 2"
15. A loaf of bread costs 44 pence, a pint of milk 22 pence and a pound of bacon Press ENTER and notice the result.
104 pence. Write a program that calculates and prints out the price of 3 TYPE: PRINT 1;2;3;4;5;6
loaves, 5 pints of milk and half a pound of bacon and then gives the total Press ENTER
cost of all the purchases. Result on the screen is: 123456
TYPE: PRINT 1, 2, 3, 4, 5,6
Press ENTER

37
Unit 12: Controlling the Print Position 39
38 Beginning BASIC with the ZX Spectrum
RUN
Result on the screen is 1 2
3 4 The result is: I am on the top line
5 6
I am on the third line blank lines
Notice that the comma after 1 moves the 2 into Zone 2 but that the comma after left in between
2 moves the 3 back into Zone 1. In other words a comma does not just move
I am on the fifth line
PRINT statements into Zone 2 but into the next available zone.
On other occasions we may need to move the print position across the screen
TYPE: PRINT 1„ 2„ 3„ 4
but not necessarily into the next zone, so we cannot use a comma. To move the
Press ENTER
print position we use the function TAB. This is an abbreviation for tabulation
Result on the screen is: 1
which means to arrange in table-form. TAB is found above key P and is obtained
2
by putting the computer into extended mode (press CAPS SHIFT and SYMBOL
3
SHIFT at the same time). TAB is used with a number; the number indicates how
4
many spaces we want to move across the screen. Think of the spaces across the
Can you see why this has happened?
screen as columns beginning at 0 on the left-hand side and finishing at 31 on the
right-hand side. This makes 32 columns or printing positions. For example:
Activities
01234567890123456789012345678901
1. Say what will appear on the screen when you type the following: t t t T
5th column 11th column 19th column 27th column
PRINT 1, 2, 3; 4; 5,6
across across across across
PRINT 1; 2, 3„ 4,,, 5
Notice that as the columns begin at 0, TAB 4 moves the printing position to
PRINT 1„ 2„ 3„ 4, 5„ 6 column 5 and TAB 10 moves it to column 11.
2. Write a PRINT statement for the following result on the screen: TYPE:
1 2 10 PRINT "01234567890123456789
012345678901"
45 3 20 PRINT "a ";TAB 5;"b";TAB 10;
"c";TAB 15;"d";TAB 20;"e";TAB 25
3. Write a PRINT statement for the following result on the screen:
;"f";TAB 30;"g"
12 34 RUN
5 6
The result is:
Check your answers to the questions above by typing them into the computer.
01234567890123456789012345678901
a b c d e f g
Sometimes we will want to leave spaces between lines. This is achieved by
using just the PRINT statement on its own. So the important thing to remember is that when you type TAB 'n' (n represents
any number), the printing will start one column further across.
TYPE: The next program shows how a table of information can be produced.
10 PRINT "I am on the top line
TYPE:
20 PRINT 10 PRINT "NAME";TAB 10;"AGE";T
30 PRINT "I am on the third li AB 20;"HEIGHT"
ne" 20 PRINT
40 PRINT 30 PRINT "Sarah";TAB 10;"13";T
50 PRINT "I am on the fifth li AB 20;"153cros"
ne"
40 Beginning BASIC with the ZX Spectrum
• •
40 PRINT "Jane";TAB 10;"14 ";TA
B 20;"155cros"
50 PRINT "Susan";TAB 10;"12";T
AB 20;"147cros"
Unit 13: Beginnings and ends of
RUN
The result is a list of names, ages and heights in three columns under appropriate
programs
headings. Notice in this program and the previous one the use of the semi-colons
(;) to separate the TAB instructions from the words in quotation marks.

Activity Each program should begin with a remark statement which is abbreviated to
REM (key E). The REM statement simply states what the program is about and
4. Write a program that prints out the information in table-form as shown below. gives it a name which can be referred to later. The computer ignores REM state-
ments but it is good programming practice to include them. From now on each
Dav Temperature Rainfall of our programs will start with a REM statement. For example:
(degrees C) (inches)
Monday 10 0.2 10 REM Area of triangles
Tuesday 11 0.4 or
Wednesday 13 0.6 10 REM Names of countries
Thursday 11 1.0 REM statements can also be used anywhere in a program to show the beginning
Friday 6 0 of a new section. For example
10 REM Areas of triangles
20 LET height=10
30 LET base=8
40 LET area=base /2 *height
50 PRINT area
60 REM Areas of rectangles
70 LET width =15
80 LET length =25
90 LET area=width*length
100 PRINT area

It is also good programming practice to let the computer know when a program
has finished. We do this by adding a STOP statement (shifted A). For example
110 STOP

41
• • Unit 14: INPUT Statement 43

Using INPUT means that you can run the program as many times as you wish
and keep changing the content of the variables. In unit 11 you wrote a program
to find the area and perimeter of a rectangle. In this program the LET statement
was used so it was possible to run the program only once with one set of measure-
Unit 14: INPUT statement ments. However, by using INPUT the program can be run any number of times
using different measurements each time.

TYPE:
10 REM Area and perimeter of
Another way to give the computer information is with the keyword INPUT. This rectangles
lets you put information in while the program is running and enables you to use 20 PRINT "Give the length of a
different information each time that the program is run. The keyword INPUT is rectangle"
30 INPUT 1
found on key I and like PRINT and LET can be used only when the flashing 40 PRINT "Give the breadth of
cursor is a K (keyword mode). a rectangle"
50 INPUT b
TYPE: 60 PRINT "Area of rectangle is
10 REM Illustrating input ";1*b;" sq.cm"
20 PRINT "Type me a number" 70 PRINT "Perimeter of rectang
30 INPUT x le is ;(l+b) *2;" cm"
40 PRINT "You just typed ";x 80 STOP
50 STOP
RUN this program several times putting in different measurements.
RUN the program.
Lines 20 and 40 in the previous program are known as input prompts; in
On the screen you will see: `Type me a number'. other words they are telling you what information the computer wants.
At the bottom of the screen you will see the L cursor — this is the computer
asking you for information; the computer just waits until you type in a number.

Type in: 63 Press ENTER

On the screen now: Type me a number


You just typed 63

RUN the program several times putting in your own numbers.


INPUT can be used with string variables as well as numeric variables.

TYPE:
10 REM Input and string variab
les
20 PRINT "What is your name?"
30 INPUT n$
40 PRINT "My name is ";n$
50 PRINT "Where do you live?"
60 INPUT a$
70 PRINT "I live in ";a$
80 STOP
An input prompt can be written as a separate PRINT statement as in the previous
RUN the program. Notice that the cursor L is enclosed in inverted commas when
program or as part of the INPUT statement as illustrated in the two examples
information is being asked for, so reminding you that a string is required.
below.
42
44 Beginning BASIC with the ZX Spectrum
• • Unit 14: INPUT Statement 45

TYPE: 140 INPUT h$


10 REM Input prompts 150 PRINT h$
20 INPUT "Type in a number ";n 160 PRINT "Name of your road? "
1
30 INPUT "Type in a second num 170 INPUT r$
ber ";n2 180 PRINT r$
40 PRINT nl;" + ';n2;" = ';n1+ 190 PRINT "Name of your town or
n2 city? '
50 STOP 200 INPUT c$
RUN the program several times. Notice that the input prompt appears at the 210 PRINT c$
bottom of the screen with the cursor and not at the top of the screen as in the 220 PRINT "Name of your county?
previous example. 230 INPUT g$
TYPE: 240 PRINT g$
250 PRINT
10 REM Writing a poem 260 PRINT
20 INPUT "What is your name? " 270 PRINT
;n$ 280 PRINT "Thank you for your e
30 PRINT "A poem by ";n$ nquiry "
40 INPUT "Type in a word that 290 PRINT "Details of our servi
rhymes with ME ";a$ ces and products will be sent to
50 PRINT "Here is the poem" you"
60 PRINT "Computers used to fr 300 PRINT
ighten me" 310 PRINT "Your personal detail
70 PRINT "But now I 'm as happy s will remain confidential"
as a ";a$ 320 STOP
80 STOP
RUN the program several times altering the variables n$ and a$. Activities
You can imagine that in the not too distant future your TV set, telephone and
home computer will be linked together to form one 'intelligent' system so that Write programs for the problems given below. Test your programs on the
on seeing an attractive advertisement on TV you could dial a number and get computer.
the following response. 1. Input four numbers; print them; find their sum and their average. Print the
TYPE: results.
10 REM Information recording s 2. Using the variables listed below write a letter asking a person to attend an
ervice interview. Use input so that the letter can contain different information each
20 PRINT "Hello" time it is run.
30 PRINT "This is an informati Variables
on recording service"
40 PRINT n$ = name of person for interview
50 PRINT "Please enter informa d$ = date of interview
tion as requested" t$ = time of interview
60 PRINT p$ = place of interview
70 PRINT "Your name? ";
80 INPUT n$ m$ = name of interviewer
90 PRINT n$ s$ = name of person who has sent the letter
100 PRINT "Your telephone numbe 1$ = date of letter.
r? "; 3. Input a sum of money that you wish to save. Input the amount of money that
110 INPUT t$
you can save each week. Calculate the number of weeks that it will take to
120 PRINT t$
130 PRINT "Number or name of yo save the money. Change the number of weeks into months. Print out all the
ur house? ', information.
47

Unit 15: Program Descriptions — Algorithms

(d) For start (beginning of program) and stop (end of program).

Unit 15: Program descriptions— C


To see how these boxes are used let us take the problem of entering two
algorithms numbers into the computer, adding them together and printing the result.
FLOWCHART

An algorithm is a written description of a program. It is a way of expressing a (START START box


solution to a problem from which a program can then be written. There are two
main ways of writing algorithms t

1. by using words could be


I / Enter first number: a /
2. by drawing a plan or flowchart. put into y
INPUT boxes
one box I
It is method 2 that we are concerned with in this unit. / Enter second number: b /
Flowcharts Add first number

A flowchart uses different shaped boxes. t


to second number
= a +b
CALCULATION box

(a) For input (information going in) and output (information coming out).
Print: sum: t OUTPUT box

( STOP ) END box

(b) For decisions (deciding whether a statement is true or false).

A program can then be written using this flowchart as a guide.


true PROGRAM 10 REM Adding Numbers
20 INPUT "Enter first number"; a
30 INPUT "Enter second number"; b
40 LETt=a+b
50 PRINT t
false
60 STOP
(c) For calculations (working out the arithmetic expressions).

Activities

1. Enter the names of three girls and their ages and print the information in a
table.
46
48 Beginning BASIC with the ZX Spectrum
• •
Unit 15: Program Descriptions – Algorithms 49

Variables to use: n$ : first name Copy and complete the flowchart


g$ : second name
h$ : third name.
a : first girl's age
C )
b : second girl's age t
c : third girl's age. Enter name of book: n$
Enter name of author
Copy and complete the flowchart Enter price:
Ente r

C ^ t
t Print: n$,
Print:
Enter first name: n$, age: a Print.
Enter second name:—, age:—
Enter third name:_, age:_
1
/
Print: n$, a
Print:—,
Print_ , Copy and complete program

10 REM Book and author


20 – "Name of book?"; –
30 INPUT "– – –?"; –
Copy and complete the program 40 – "Price of book?" – p

10 REM Names and ages 60 PRINT –; "by"; –


20 INPUT "Name of first girl?"; n$ 70 -- "Price of book"; –
30 INPUT "Age of first girl?"; 80– – – – ;–
40 INPUT "Name of second girl?"; –
50 – "Age of -- girl?"; –
INPUT – Name of third girl? –; – 3. List the variables, draw flowcharts and write programs for each of the prob-
70– ----?" lems below. Supply your own information where necessary. Test your
80 PRINT "NAME", "AGE" programs on the computer.
90 PRINT n$, a Calculate the area of a triangle and print out the result (area of a
100--,- triangle = z base x height).
Enter the names of three people and their dates of birth and print out
120 – this information. (Will the dates of birth be numeric or string variables –
think about this before you start.)
2. Enter the name of a book, its author, its price and its date of publication. Enter a word of at least seven letters and print three other words using
Print out this information. only the letters in the original word.
Variables to use: n$ : name of book Enter the names of three towns and their populations. Print this informa-
a$ : name of author. tion. Calculate the total population and print the result.
p : price A boy has 216 marbles which he shares equally among his twelve friends.
d : date of publication. Print the number of marbles each friend receives.
• •
50 Beginning BASIC with the ZX Spectrum

(f) Enter a length measured in feet and change it into centimetres


(1 foot = 30.5 centimetres).
(g) A girl has £95 to spend. She buys a skirt for £26, a dress for £44 and a
pair of shoes for £16. Calculate the amount she spends and the amount Unit 16: Loops—using GOTO
she has left. Print out all the information.

GOTO is a command or keyword found on key G. As for other commands, it


can only be used when the cursor is a K (the computer is in keyword mode).
TYPE: 10 PRINT "Hello"
20 GOTO 10
RUN
The word `Hello' will fill the screen and then the message `scroll?' will be printed.
Press Y for yes.
The screen fills again with the same word. This can be repeated as many times as
you wish.
Press N for no.
The program will now stop with the message:
D BREAK- CONT repeats, 10:1
Press ENTER.
The program returns to the screen.
Jumping back to another part of the program is known as looping. The
example shown above could go on for ever so it is known as an infinite loop.
The GOTO command can be used to force the computer to carry out any line
of the program.
TYPE:
10 LET x=0
20 LET x=x+1
30 PRINT x
40 GO TO 20

RUN the program.


The screen fills with the numbers 1 to 22.
Press Y.
The screen fills with the numbers 23 to 44. As in the previous example this is
another infinite loop as it can be repeated any number of times.

51
52 Beginning BASIC with the ZX Spectrum
• • Unit 16: Loops — Using GOTO 53

How does the program work? Can you write an explanation? Flowchart for program

Press N for 'no' and remove the program from the computer.
TYPE: (START)
10 REM Running total of number
s
20 LET total=0 Set up variable
30 INPUT "Enter a number ";n total = 0
40 LET total=total+n
50 PRINT n,total
60 GO TO 30

RUN / Input a number: n

This is another infinite loop so when you have entered several numbers
press STOP (shifted A) followed by ENTER which will produce the message: Add number to 'total'
total = total + n
H STOP in INPUT, 30 : 1
Press ENTER and the program returns to the screen.
Print: n, total
This program is rather like the previous one where x began by being 0 and then 1
was added every time the program was sent back to line 20 by the GOTO com-
mand in line 40. In this program the variable called `total' also begins by being
equal to 0 but in line 30 an input prompt asks for a number which is then added
to `total' in line 40. The variable `total', therefore, changes its contents and is no Notice that there is no box for the GOTO statement. The command is indicated
longer 0. Line 50 prints the input number in one column and the contents of by the direction of the arrows.
`total' in the other column. The computer is then told to loop back to line 30
The GOTO statement can also be used to jump forward in a program; whole
for another number which once again is added to `total' so the contents of `total'
sections of programs can be missed out if required. The next program is an
changes again. example of this.
Let us consider this again by actually putting the numbers 5, 10 and 15 into
the program. TYPE:

Result of program 10 PRINT "The Spectrum is the


Line 20: variable called `total' is set up and is equal to 0 20 GO TO 40
Line 30. the number 5 is entered 30 PRINT "worst "
Line 40: the variable called `total' is changed as it becomes 0 + 5 = 5 40 PRINT " greatest ",
Line 50: prints 5 5 50 PRINT "computer"
Line 60: program loops back to line 30
Line 30: the number 10 is entered RUN the program. What has happened to line 30?
Line 40: the variable `total' is changed again and becomes 5 + 10 = 15
Line 50: prints 10 15 GOTO is always used with a line number. The line number can be written as
Line 60: program loops back to line 30 an arithmetic expression. For example
Line 30: the number 15 is entered
GOTO 20 + 40 means GOTO line 60
Line 40: the variable `total' is changed yet again and becomes 15 + 15 = 30
Line 50: prints 15 30 This can be quite useful if you wish to add a numeric variable to a number line;
Line 60: program loops back to line 30 see the following program.
Beginning BASIC with the ZX Spectrum
• • Unit 16: Loops — Using GOTO
54

TYPE: continues to save by adding money to his new account each month but he
does not save the same amount of money each month. His bank sends him
10 INPUT "Enter a month of the
year as a number between 1 and Notice that each of an account at the end of each month which states the date, how much he
12 ";m these lines has two has saved each month and the total. This arrangement continues for many
20 PRINT "Month ";m;" is "; keywords or commands — years. Draw a flowchart and write a program that displays and calculates all
30 GO TO 50+n
50 GO TO 10 PRINT and GOTO. This this information. Test your program on the computer.
51 PRINT "January": GO TO 10 is made possible by
52 PRINT "February": GO TO 10 using the colon (:) which
53 PRINT "March": GO TO 10 separates one statement
54 PRINT "April": GO TO 10
55 PRINT "May": GO TO 10 from the next. After
56 PRINT "June": GO TO 10 entering the colon the
57 PRINT "July": GO TO 10 cursor automatically
58 PRINT "August": GO TO 10 becomes a K again.
59 PRINT "September": GO TO 10
60 PRINT "October": GO TO 10
61 PRINT "November": GO TO 10
62 PRINT "December": GO TO 10

RUN
To escape from the program enter STOP followed by ENTER.
In this program, line 30 will cause a jump to line 51 if you enter the number
`I', to line 52 if you enter the number `2', and so on.
If the number 0 is entered by mistake, how does the computer cope with this?
If a number above 12 is entered by mistake what happens to the program?
Notice in this program that in lines 51 to 62 it was possible to give the computer
two commands or instructions in each line. For example, PRINT a word and
then GOTO another line. This was done by using the colon (:) which simply
separates one command from another. The colon is a signal to the computer to
return to keyword mode K, so that another keyword or command can be
entered.

Activities

1. Draw a flowchart for the program about:

"the Spectrum is the greatest computer"

2. Write a program that inputs two separate numbers, adds them together,
prints the result and then jumps back to the beginning of the program,
forming an infinite loop. Test your program on the computer.
3. A man has three different saving accounts which contain the following
amounts: £381.20, £623.65 and £127.84. He decides to transfer his savings
to one account and wishes to know the total amount that he has saved. He
Unit 17: Comparisons 57

the statement again; if it is true that x does not equal 10 + 15 then print
`wrong', the answer is 10 + 15'. If the statement is not true then ignore the
rest of the line.
Unit 17: Comparisons Question: Why was it possible to use the command PRINT in the middle of
lines 40 and 50? Why did not the letter P appear?

Flowchart for this program

A computer, unlike a calculator. can compare two pieces of information. It can


decide whether a statement is true or false and then act accordingly. In order to
do this the computer uses the command or keyword IF, found on key U, follow-
ed by the word THEN, on shifted key G. IF, like other commands, can be used
LINE 10
only when the computer is in keyword mode; the cursor is a K. The command is
simply saying that IF a certain statement is true THEN perform the next
instruction in that line. See the example below which compares information by
LINE 20
using the sign for equals (_) and the sign for not equals (<>).
TYPE:
LINE 30
10 PRINT "10+15=";
20 INPUT "Enter an answer ";x
30 PRINT x
40 IF x=10+15 THEN PRINT "Corr LINE 40
ect"
LINE 40
As you / key U shifted next instruction
type in / key G
these
lines the content
notice what of numeric
happens to LINE 50
variable x is
the cursor being compared
after you to the sum of
have 10 + 15
pressed in 50 IF x<>10+15 THEN PRINT "Wro LINE 60 ( STOP
the word ng, the answer is ";10 +15
THEN shifted key W
(do not use shifted T This next example shows that it is not only numbers contained in numeric
and shifted R) variables that can be compared but also the contents of string variables.
60 STOP
RUN the program; once with the correct answer and once with the wrong TYPE:
answer. 10 PRINT "What is my name? ",
20 INPUT "Enter a name ";n$
30 PRINT n$
In this program line 40 means that if it is true that x equals 10 + 15 then print 40 IF n$="Floribunda" THEN GO
`correct'. If it is not true and x does not equal 10 + 15 then ignore the rest of TO 70
the instructions in that line. The program then passes on to line 50 which tests 50 PRINT "No,it is Floribunda"
60 STOP
56
58 Beginning BASIC with the ZX Spectrum
• • Unit 17: Comparisons

70 PRINT "Yes,you are quite ri 10 PRINT " Do you like cakes an


ght" d biscuits? '
80 STOP 20 INPUT "Enter yes or no ";a$
RUN the program several times trying different names. 30 PRINT a$
40 IF a$="yes" THEN GO TO 70
This program illustrates a GOTO loop which is set up in line 40. This line 50 PRINT "You will stay slim"
means that if it is true that nS equals `Floribunda' then go to line 70. If it is not 60 STOP
70 PRINT "You will get fat!!"
true then ignore the instruction to go to line 70 and pass on to line 50. 80 STOP

Flowchart of program Flowchart

(START)

t
LINE 10 Print: What is my name
/ Print:
Input n$ /
LINE 20
/ / / Enter Yes or No 7
/
t
Print: n$
LINE 30
/ / / Print:
/

LINE 40

LINE 50 Print: No, it is Floribunda


GOTO
LOOP

LINE 60

Print: Yes, you are quite right


LINE 70
/ / 7
/

LINE 80 ( STOP

Question: Why is the STOP statement in line 60 necessary?

Activities

1. Study the program that follows and then copy out and complete the flowchart.
60 Beginning BASIC with the ZX Spectrum Unit 17: Comparisons 61

2. Study the flowchart below and then write the program. 3. Draw a flowchart and write a program for the following problem.
Print an arithmetic expression where one number is subtracted from another.
Enter and print the answer. Print whether the answer is right or wrong. If the
(START) answer is wrong print out the correct answer. Test your program on the
computer.
f 4. Write a program that asks a person the colour of your eyes. Use a string
/ Print: What is my age? / variable to represent the colour of your eyes. Print out whether they guess
rightly or wrongly. Test your program on the computer.
t
/ Input a number: a /

/ Print: a /
The next program is a little more complicated as it compares information in
lines 30 and 80 and uses several GOTO loops.

TRUE

TYPE:
FALSE
5 REM TELL A JOKE
Print: Wrong 10 PRINT "Shall I tell a joke?

20 INPUT "Enter yes or no ";a$


STOP 30 IF a$="no" THEN GO TO 130
40 PRINT "How many legs has an
octopus?"
50 PRINT
/ Print: Correct / 60 PRINT
70 INPUT "Enter a number ";n
80 IF n=0 THEN GO TO 110
90 PRINT "No,you are wrong.It
( STOP ) has no legs only tentacles.Shall
I tell the joke again?"
100 GO TO 20
110 PRINT "Yes,shall I tell the
joke again?"
120 GO TO 20
130 PRINT "All right then,I won
"t"
140 STOP

RUN the program several times changing the input in lines 20 and 70.
How does the program work? Use the flowchart that follows to help you.
62 Beginning BASIC with the ZX Spectrum
• • Unit 17: Comparisons 63

Another useful technique can be learned here. It is the use of a dummy value
Flowchart
to stop an infinite loop which has been set up by a GOTO statement.

LINE 5

LINE 10

LINE 20

Print: How many legs has /


/ an octopus?
The next program, which changes marks gained by pupils in an examination into
percentages, illustrates this point.

TYPE:
10 REM CALCULATING PERCENTAGES
20 PRINT "Enter total marks of
examination ',
30 INPUT t
40 PRINT t
50 PRINT
60 PRINT "Enter mark gained by
pupil "
Print: No, you are wrong. It 70 INPUT m
LINE 90 has no legs, only tentacles. 80 IF m=-9999 THEN GO TO 140
Shall I tell the joke again? 90 PRINT m
100 LET p=(m/t)*100
110 PRINT p;"%"
120 PRINT
Print: Yes, shall I tell the 130 GO TO 60
LINE 110
joke again?
140 STOP
RUN the program and when you have entered enough marks enter —9999 and
/ notice what happens.
LINE 130
/ Print: All right then,
I won't
As you can see, if the dummy value - 9999 is entered in line 70 the computer
does not continue on through the program but jumps to line 140 and stops. If
line 80 did not exist the computer would continue to perform the program
LINE 140
(
STOP ) indefinitely as the loop set up by the GOTO statement in line 130 cannot be
stopped. The dummy value does not have to be —9999, it can be any value
64 Beginning BASIC with the ZX Spectrum
• i
which is unlikely to be entered as a pupil's mark. It would probably be useful
to add an extra line to the program, telling the user of the program what the
dummy value is. For example

65 PRINT "or —9999 if you wish the program to stop"


Unit 18: More comparisons
The dummy value does not have to be a number; a word can be used if the
program is using string variables. For example
10 REM LIST OF NAMES
20 INPUT "Enter a person ' s nam Apart from equals (_) and not equals (<>) there are other ways of comparing
e ";n$ information in an IF—THEN statement.
30 IF n$ = "sausages" THEN GO TO
60 Meaning >
Symbol Key
40 PRINT n$ greater than shifted T
50 GO TO 20 less than shifted R
60 STOP
greater than or equal to >= shifted E
Using a dummy value is not the only way of stopping an infinite loop, you will less than or equal to <_ shifted Q
learn another method in unit 19.
These four new symbols are used in the examples below.

Activities
Examples

5. Write a program that continually asks for the names of towns in Great Britain (5) Is 8
(1) Is 8 > 4? Yes. > = 9? No.
and prints them out in a list. Include a dummy value so that the program can Is 8 < 4? No. (6) Is 8 < = 8? Yes.
(2)
be stopped. Test your program on the computer. (3) Is 8 > = 8? Yes. (7) Is 8 < = 6? No.
6. Draw a flowchart and write a program that tests a person's multiplication (4) Is 8 > = 7? Yes. (8) Is 8 < = 9? Yes.
tables (such as, 6 x 7 = 42, 4 x 5 = 20 etc.). Numbers, using numeric variables,
must be entered to make up the sum and the sum printed. An answer must
then be entered and the person told whether they are right or wrong. If the
Activities
answer is wrong the person is allowed another try; therefore the correct
answer is not printed. If the answer is right the person should be given the 1. Give `Yes' or `No' answers to the following:
choice of having another turn so the computer needs to return to the begin-
(a) Is 10> 12? (n) Isa—b<=6?
ning of the program where another sum will be set up. Test your program on
(b) Is 12 < 15? (a = 10, b = 4)
the computer.
(c) Is 24 > = 24? (0) Isr*s>=7?
(d) Is 32 > = 31? (r=3,s=2)
(e) Is 15 > 9? (P) Is (10 + 2)/6 > 0?
(f) Is 17 < = 17? (q) Is (w + z)* 2 > 40?
(g) Is 102 > = 105? (w = 5, z = 10)
(h) Is 33 < = 43? (r) Isn*n<>64?
(i) Is 47 = 52? (n = 8)
(j) Is 53 <> 54? (s) Isc+d+e<24?
(k) Is 3* x= 15? (x = 5) (c = 7, d = 9, e = 11)
(1) Is4+5>9? (t) Is (f + g) * (10 — 3) < = 56?
(m) Is 6 + y < 19? (y = 6) (f=2,g=6)

65
Beginning BASIC with the ZX Spectrum Unit 18: More Comparisons 67
66

2. Complete the following statements by putting in the correct symbol (do not Flowchart for previous program
use `not equals' (<>) or `equals' (_)).
Example 13 — 12 should be 13 > 12
5 — 5 should be 5 < = 5 or 5 > = 5 LINE 10 (START
12— 13 should be12<13
(a) 16 — 23 1
(g) x/2 — y + 4
(b) 14 __ 10 (x = 6, y = 2) LINE 20 Print: Number of items
(c) 10 — 10 (h) x * x — y/2
(d) 5+ 6_11-3 (x= 10,y =150) t
(e) 3*7_13+8 (i) (a+b)*3 —a +b*3 LINE 30 / Enter number of items: i /
(f) x (a = 3, b = 5)
(x = 0, y = 1) (j) a+b —c— a+c-10
(a = 1,b = 6,c=4) LINE 40

LINE 50
By studying the following flowcharts and programs it is possible to see how to
use these various symbols. You will notice that they are included with the IF-
THEN statements as in the previous unit.
LINE 60

LINE 70

TYPE:
LINE 80
10 REM SIZE OF SHOPPING BAG
20 PRINT " Number of items boug
ht is ' LINE 90
30 INPUT i
40 PRINT i
50 IF i>15 THEN GO TO 80
60 PRINT "Small bag needed"
70 STOP
80 PRINT "Large bag needed"
90 STOP

The next program involves entering the names of three children and the
amount of pocket money that they receive. It then calculates the average amount
RUN the program entering different numbers and study the flowchart that of pocket money and compares this with £10 and prints out an appropriate
follows. message.
68 Beginning BASIC with the ZX Spectrum
• • Unit 18: More Comparisons 69

Flowchart for previous program


TYPE:
10 REM POCKET MONEY
20 INPUT "Enter name of first LINE 10 (START)
child";f$
30 INPUT "Enter name of second I
child";s$ Enter Name of 1st child: f$
40 INPUT "Enter name of third LINES 20, 30, 40 Name of 2nd child: s'$
child";t$ Name of 3rd child: t$
50 INPUT "Enter pocket money o
f first child";pl
60 INPUT "Enter pocket money o
f second child";p2 Enter Pocket money of 1st child: p1
70 INPUT "Enter pocket money o LINES 50, 60, 70 Pocket money of 2nd child: p2
f third child";p3 Pocket money of 3rd child: p3
80 PRINT "NAME","POCKET MONEY"
90 PRINT TAB 16;"IN POUNDS"
100 PRINT f$,p1
110 PRINT s$,p2 Print: NAME POCKET MONEY
120 PRINT t$,p3 LINES 80 -120 f$ p1
130 PRINT P2
t$ p3
140 PRINT "Average pocket money
is 5"
150 LET a=(pl+p2+p3)/3
160 PRINT a LINE 140 Print: Average pocket money
170 IF a>6 THEN PRINT "Too much
money"
180 IF a<=2 THEN PRINT "Too lit
tle money" LINE 150 Let a = (p1 + p2 + p3)/3
190 STOP

RUN the program several times using different names and different amounts of LINE 160
pocket money.

See the flowchart that follows.


TRUE
Lines 20 to 120 just receive the necessary information and then print it out in LINE 170 Is a > 6? ^ /Print: Too much
two columns which are given the headings `NAME' and `POCKET MONEY IN
POUNDS'. Line 150 calculates the average amount of money while lines 170
and 180 compare this with £6 and £2 respectively.

TRUE
LINE 180 / Print: Too little

LINE 190 ( STOP


70 Beginning BASIC with the ZX Spectrum Unit 18: More Comparisons 71

Activities 4. Write a program for this flowchart.

3. Write a program for this flowchart.


(START)

(START) / Enter a number: x

/ Enter a number: x
Enter a second number: y TRUE

TRUE
LET y=x+10

FALSE
Prin : y
Print: y is bigger than x /
^/

STOP

LET w = x — 10
/ Print: x is bigger than y / <

Print: w
C STOP )
t
( STOP )

5. A salesman is paid a weekly salary of £65. If he sells goods to the value of


£200 or more he is given an extra bonus of £10. The program below calculates
the salesman's final salary using the following variables:

s = salary of £65
b = bonus of£10
x = value of goods sold

Draw a flowchart for this program:


72 Beginning BASIC with the ZX Spectrum Unit 18: More Comparisons 73

10 REM SALESMAN ' S SALARY Sometimes we need to compare two or more pieces of information in the same
20 LET s=65 IF-THEN statement. For example, if one thing is true and another thing is true
30 LET b=10 then do so and so, which translated into BASIC could be:
40 PRINT "Value of goods sold
by a salesman in a week " IF y = 10 AND x = 20 THEN GOTO 200
50 INPUT "Enter value of goods or
";x IF a$ = "John" AND b$ = "McEnroe" THEN PRINT "Tennis star"
60 PRINT x;" pounds"
70 IF x>=200 THEN GO TO 100 The only word we have added to the statement is AND (shifted Y).
80 PRINT "No bonus added.Final
salary is ";s;" pounds" TYPE:
90 GO TO 120
100 LET s=s+b
110 PRINT "Bonus added.Final sa 10 REM Using AND
lary is ";s;" pounds" 20 INPUT "Enter a number betwe
120 STOP en 1 and 100 ";n
30 INPUT "Enter another number
between 1 and 100 ";n2
40 IF n>50 AND n2<50 THEN GO T
List the variables, draw flowcharts and write programs for the problems in 0 90
6-11. Test each program on the computer. 50 PRINT n+n2
6. Enter the date of a year (for example. 1983) and compare it to the number 60 LET c=5
70 PRINT n*c
2000. If the year entered is greater or equal to 2000 then print `Next 80 STOP
century'; if the year entered is less than 2000 then print `This century'. 90 PRINT n-n2
7. Enter two separate numbers. If their product is greater than 81 then print 100 STOP
`Too great'; if it is less than 81 then print `Too little'; and if it is equal to 81
print `Just right'. RUN. Enter 20 and 70
8. If a boy earns less than £50 a week his father gives him an extra £10. If he Result is: 90
earns £70 or more he has to give his mother £15. Enter the boy's salary and 100
calculate and print the boy's final weekly income. RUN. Enter 70 and 20
9. A car holds 33 litres of petrol. A litre of petrol costs 45 pence. A car uses Result is: 50
1 litre of petrol to travel 14 km. A man puts some petrol in his car; calculate RUN. Enter 70 and 70
the cost of the petrol and the distance he can travel on that amount of petrol; Result is: 140
print out this information. If he can travel 380 km without refilling his tank 350
he will take a holiday in Cornwall, otherwise he will go to Dorset. Print out RUN. Enter 20 and 20
where he goes. Result is: 40
10. A baker's oven will hold 15 loaves of bread which take 52 minutes to bake. 100
He fills his oven 4 times a day. Calculate the number of loaves he bakes in a
day and the time it takes in hours. Print this information. The baker's bread Line 40 tests two conditions, both of which have to be true before the computer
is sold in the local supermarket. If all the bread is sold, a message is sent to will obey the rest of the instruction. Therefore, when n = 20 and n2 = 70, `n' is
the baker to bake more. Print out the message if required. not greater than 50 and n2 is not less than 50 so the computer ignores the GOTO
11. A milkman delivers milk to several blocks of flats. 18 families have 3 pints a statement and carries on to lines 50 to 80. When n = 70 and n2 = 20, `n' is
day, 17 families have 2 pints a day and 9 families have four pints a day. greater than 50 and n2 is less than 50 so the GOTO statement is obeyed and the
15 families vary the amount they have each day. A milk crate contains 12 computer jumps to line 90. When n = 70 and n2 = 70, `n' is greater than 50 but
pints of milk. Calculate the number of pints he delivers each day and the n2 is not less than 50, therefore both conditions are not true so the computer
number of crates he has to load on to his milk van. Print this information. If continues to line 60. When n is 20 and n2 is 20, `n' is not greater than 50 •
more than 13 crates are required he will have to return to the depot for more, although n2 is less than 50 so once again both conditions are not true so the
otherwise he can go home. Print out where he goes. next line to be executed is line 50.
74 Beginning BASIC with the ZX Spectrum Unit 18: More Comparisons 75

Activity RUN. Enter 155 and 5


Result is: Too small — you must grow
12. Using the previous program give the results if the following numbers were
RUN. Enter 266 and 5
entered:
Result is: Too large — you must shrink
(a) n=10,n2=20
RUN. Enter 155 and 12
(b) n = 80, n2 = 40
Result is: Too large — you must shrink.
(c) n = 80, n2 = 60
(d) n = 20, n2 = 10 When h = 155 and s = 5 neither of the conditions were true so the computer
Check your answers on the computer. ignored the rest of the statement but when h = 266 and s = 5 one of the con-
ditions was true, 266 was greater than 165, so "Too large — you must shrink"
AND can be used equally well with string variables which can be seen in the was printed. It did not matter that 5 was not larger than 6. Similarly when
next program. h = 155 and s = 12 one of the conditions was true.
TYPE:
10 REM Using AND
20 INPUT "Enter the Christian Activities
name of a male tennis star ";c$
30 INPUT "Enter the surname of 13. Write a program that inputs a number which is tested to see if it is greater
the same tennis star ";s$ or equal to 100 but less than or equal to 200. If the number fits the con-
40 IF c$="John" AND s$="McEnro
e" THEN PRINT "Number 1 player i dition then the message "Number between 100 and 200" should be printed.
n the world" If the number does not fit the condition then the message "Number not
50 IF c$="Jimmy" AND s$="Conno between 100 and 200" should be printed.
rs" THEN PRINT "Number 2 player 14. Write out the result of this program if the following numbers were entered
in the world"
60 STOP in line 30: (a) n = 40, (b) n = 60, (c) n = 80.
RUN. Enter John and McEnroe 10 LET x=50
Result is: Number 1 player in the world 20 LET y=70
RUN. Enter Jimmy and Connors 30 INPUT "Enter a number ";n
Result is: Number 2 player in the world 40 IF n>x AND n<y THEN GO TO 7
0
RUN. Enter John and Connors 50 PRINT n+n
Result is: neither message is printed. 60 STOP
70 PRINT x+y+n
This program works on exactly the same principle as the previous one; the 80 STOP
message will be printed only if both conditions are true.
The word OR (shifted key U) works in much the same way except that only 15. Write out the result of this program if the following ages were entered in
one of the conditions has to be true. line 30: (a) a = 13, (b) a = 21, (c) a = 17, (d) a = 6, (e) a = 19.
TYPE: 10 LET y=19
10 REM Using OR 20 LET x=13
20 INPUT "Enter your height in 30 INPUT "Enter your age ";a
centimetres ";h 40 IF a>=13 AND a<=19 THEN PRI
30 INPUT "Enter the size of yo NT "Teenager"
ur shoes ';s 50 IF a<13 THEN PRINT "Child
40 IF h>165 OR s>6 THEN PRINT 60 IF a>19 THEN PRINT "Adult"
"Too large-you must shrink": GO 70 STOP
TO 60
50 PRINT "Too small-you must g
16. Write out the result of this program if:
row" (a) w$ = hot, r$ = dry. (b) w$ = warm, r$ = wet.
60 STOP (c) w$ = cold, r$ = dry. (d) w$ = warm, r$ = dry.
76 Beginning BASIC with the ZX Spectrum

10 LET a$="hot"
20 LET b$="cold"
30 LET c$="wet"
40 LET d$="dry"
50 LET e$="warm" Unit 19: Adding a counter
60 INPUT "Is the weather hot,w
arm or cold? ";w$
70 INPUT "Is the weather wet o
r dry? ";r$
80 IF w$=a$ OR w$=b$ OR r$=c$
THEN PRINT "No walk today": GO T As you have already seen, a computer can be made to perform a program over
0 100 and over again by using a GOTO loop. Sometimes it is difficult to break out of
90 PRINT "Lets go for a walk"
100 STOP such a loop as the computer goes on indefinitely and this is not particularly
useful. However, by adding a counter we can make the computer execute a
program for a set number of times and then stop. This is illustrated in the
following program, which is performed five times.

TYPE:

10 REM COUNTING
20 LET counter=0
30 INPUT "Enter the name of a
car ";a$
40 PRINT a$
50 LET counter=counter+1
60 IF counter=5 THEN GO TO 80
70 GO TO 30
80 STOP

RUN the program. Do not remove from the computer.

Line 20 sets the numeric variable called `counter' to 0. A name is then entered
and printed. Line 50 adds 1 to the counter and so the variable now has the
value 1. Line 60 asks whether the value of 'counter' is equal to 5; as it is not
the computer ignores the rest of the line and continues on to line 70 where it
is told to go back to line 30 and start all over again. The program is then
executed a second time and the value of `counter' changes to 2 which once
again is not equal to 5 so the computer returns to line 30. This continues until
`counter' is equal to 5 and then the computer jumps to line 80 and stops.

Question: Why did line 70 say GOTO 30 and not to line 20?

77
78 Beginning BASIC with the ZX Spectrum Unit 19: Adding a Counter 79

Flowchart TYPE:
10 REM PRACTISING DIVISION
20 LET c=0
30 LET s=0
40 INPUT "Enter the number of
questions to be given ";n
50 INPUT "Enter a number betwe
en 12 and 100 ";a
60 INPUT "Enter a number betwe
en 2 and 12 ";b
70 PRINT a;"/";b;"= ;
80 INPUT "Enter an answer ";x
90 PRINT x
100 IF x<>a/b THEN GO TO 140
110 PRINT "That ' s right"
120 LET s=s+1
130 GO TO 150
140 PRINT "That ' s wrong.The ans
wer is ";a/b
150 LET c=c+1
160 IF c=n THEN GO TO 180
170 GO TO 50
180 PRINT "You scored out
of ";n
190 STOP

RUN

Lines 20. 40, 150 and 160 set up and deal with the counter which counts the
number of times that the program is performed. Line 30 sets up the counter 's'
for keeping the score, in this case the number of correct answers. Variable 's'
begins at 0 as no questions have been asked. If the first sum is answered correctly
then 1 is added to the score in line 120 and therefore variable 's' becomes 1. If
It is not necessary to state the number of times a program is to be performed
the sum is answered wrongly then line 100 sends the computer to line 140, thus
when the program is written. This can be entered into the program while it is
missing out line 120 where 1 was added to 's'. This sequence of events is repeated
being run. Modify the previous program by adding a line and by altering line 60.
each time that a new sum is answered and so 's' will increase by I every time that
a sum is answered correctly. When the program has run the required number of
ADD: 15 INPUT "Enter the number of
times you wish to perform the pr times line 180 prints the final score. The following flowchart will help you to
ogram ";n understand this program.
ALTER: 60 IF counter=n THEN GO TO 80

RUN the program again, entering a reasonably low number otherwise you will
have to input many names.

To make typing quicker the variable 'counter' is usually just called 'c' which is
what we will use in future.
A counter is not only used to count the number of times a program is per-
formed, it can also be useful in a quiz program to count the number of correct
or incorrect answers. See the example below.
80 Beginning BASIC with the ZX Spectrum
• Unit 19: Adding a Counter 81

Activities
Flowchart

Remember to try your programs on the computer.


LINE 10 (START) 1. Write a program that asks for the names of six flowers and prints them out
in a list.
LINE 20 LET c= 2. Modify the program that you have written for activity 1 so that the number
1
of flowers to be listed is decided as the program is run.
LINE 30 LET s = 3. Draw a flowchart and write a program where a person guesses a number
between 0 and 20. If the guess is wrong, then another attempt must be made
t until the right answer is given. The computer must record and print out the
LINE 40 / Enter number of questions: n
number of guesses made. Make certain that the person making the guesses is
told not to look when the number to be guessed is being entered!
Enter a number between 12 and 100: a
/ Enter a number between 2 and 12: b LINES 50 and 60

LINE 70 / Print: a/b =

LINE 80 /Enter an answer: x /

LINE 90 Print x

TRUE
LINE 100

FALSE
LINE 110 / Print: That's right /

LINE 120 LET s =s+1

LINE 140 / Print: That's wrong / 4

LINE 150 LET c = c + 1

TRUE
LINE 160

LINE 180 Print: You scored: s: out of n


t `
LINE 190 STOP )
Unit 20: FOR-NEXT Loops 83

This FOR-NEXT loop will run 6 times. Line 20 no longer asks the computer to
print out the value of `c' but to print the word `Hello', so this will appear on the
screen six times. You can see that any lines that lie between the FOR and the
NEXT statements are part of the loop and will be performed each time the com-
Unit 20: FOR-NEXT loops puter passes through the loop.

Activities
Using FOR-NEXT statements is another way of controlling the number of times
1. Study the programs below and write out what would appear on the screen
a program or part of a program is performed. FOR is a keyword found on key F
when they are run.
and NEXT is another keyword on key N; neither can be used unless the com-
puter is in keyword mode K.
(a) 10 FOR x=1 TO 12 (c) 70 FOR w=1 TO 4
TYPE: 20 PRINT x 80 PRINT "Goodbye"
30 NEXT x 90 NEXT w
10 FOR a=1 TO 10 (b) 40 FOR y=4 TO 16 (d) 100 FOR c=1 TO 3
50
5 PRINT y 110 PRINT c
Notice shifted F (do not type T and 0 as 60 NEXT y 120 PRINT "This is a loop"
that these separate letters) 130 NEXT c
two variables If you wanted a large space in a program between two written statements
must be 20 PRINT a then a FOR-NEXT loop could be used to create this space. See the program
the same 30 NEXT a below.
TYPE:
RUN 10 PRINT "I ' m at the top of th
As you can see. the result of this program is to print out a list of numbers from e screen"
20 FOR a=1 TO 9
1 to 10. In line 10 the FOR statement sets the counter to start at 1 and finish 30 PRINT
at 10. Line 20 then prints the value of `a' which on the first time round is 1. 40 NEXT a
Line 30 then sends the computer back to the FOR statement to collect the 50 PRINT "I'm in the middle of
NEXT value of `a' which will be 2. This loop is repeated until `a' has the value the screen"
60 FOR b=1 TO 9
10 and then it automatically stops. The loop is performed 10 times. 70 PRINT
80 NEXT b
TYPE:
90 PRINT "I 'm at the bottom of
10 FOR b=11 TO 20 the screen"
20 PRINT b 100 STOP
30 NEXT b
RUN
RUN In this program the loop set up by lines 20 and 40 is repeated nine times, so
This program will also run 10 times, the only difference is that the value of `b' nine empty lines are printed, and then the same thing happens again because of
will start at 11 and finish at 20. the loop set up by lines 60 and 80. This saves typing out nine PRINT statements.
For example
TYPE:
10 PRINT "I'm at the top of the screen"
10 FOR c=1 TO 6
20 PRINT "Hello" 20 PRINT
30 NEXT c 30 PRINT
40 PRINT
RUN
etc.
82
84 Beginning BASIC with the ZX Spectrum
• • Unit 20: FOR-NEXT Loops

A loop is set up by using a numeric variable, such as 7 should finish at 10 this is not
9 printed as after 9 a step of two
FOR a (numeric variable) = 1 to 10
would make the next number 11.
but other numeric variables may also be used in the statement — see below.
ALTER line 10:
TYPE:
10 INPUT "Enter number of time 10 FOR x=3 TO 21 STEP 3
s you wish loop to be repeated "
;n RUN
20 FOR x=1 TO n
30 PRINT x The result is: 3 1'
40 NEXT x 6
RUN the program several times, entering different numbers, and notice the 9 This program begins at 3 and then
results. If you enter a number greater than 22 the screen will fill up and you 12 counts in threes until 21 is
will be asked to `scroll'. 15 reached.
ADD to the program: 18
5 INPUT "Enter a number at wh 21
ich you wish the loop to start "
;s ALTER line 10:

ALTER line 10: 10 FOR x=10 TO 1 STEP -1


10 INPUT "Enter a number at wh
ich you wish the loop to finish RUN
";n
The result is: 10 T
ALTER line 20: 9
20 FOR x=s TO n 8 This program prints the highest number
7 first and then decreases by one each
RUN the program making certain that the first number entered is lower than 6 time until the lowest number is reached.
the second. 5 This program cannot be written:
4 FOR x = 1 TO 10 STEP —1
This last program shows that the whole of the FOR statement can be made up of
3
numeric variables. This enables the programmer to enter different numbers while
2
the program is runnin g so that the loop can be repeated any number of times.
1
Usually when a FOR-NEXT loop is used the counting is done in ones but it is
possible to make the computer count in twos, threes, fours etc. by using the ALTER line 10:
word STEP which is shifted D. The following programs illustrate this.
10 FOR x=20 TO -5 STEP -5
TYPE:
10 FOR x=1 TO 10 STEP 2 RUN the program.
20 PRINT x
30 NEXT x The result is: 20 1'
15 This loop starts at 20 and
RUN
10 decreases by 5 each time
The result is: 1 1' 5 until —5 is reached.
3 Only the odd numbers are printed. 0
5 Notice that although the loop —5
Beginning BASIC with the ZX Spectrum
• • Unit 20: FOR—NEXT Loops 87
86

ALTER line 10: TYPE:


10 FOR x=-10 TO —20 STEP —2 10 FOR x=1 TO 6
20 LET a=x+5
RUN 30 PRINT x,a
40 NEXT x
The result is: —10 T
—12 This is a similar program but RUN
—14 remember that —10 is a higher The result is: 1 6
—16 number than —20. 2 7
—18 3 8
—20 4 9
5 10
Activities 6 11
Lines 10 and 40 set up the loop to be repeated 6 times. Line 20 introduces a
2. Study the programs below and then write out the result of each. new variable `a' which is given the same value as `x' plus 5. Line 30 then prints
(a) 10 FOR x=2 TO 12 STEP 2 out the two variables in two columns. The first time round the loop `x' is 1 and
20 PRINT x therefore `a' is 6; the second time round `x' is 2, therefore `a' is 7. This continues
30 NEXT x until the last value of x is reached.
(b) 10. FOR x=15 TO 25 STEP 4
20 PRINT x TYPE:
30 NEXT x
10 FOR x=3 TO 12 STEP 3
(c) 10 FOR x=0 TO 100 STEP 20 20 PRINT x,x*x
20 PRINT x 30 NEXT x
30 NEXT x
(d) 10 FOR x=50 TO -25 STEP -25 RUN
20 PRINT x
30 NEXT x The result is: 3 9
(e) 10 FOR x=-2 TO -12 STEP -3 6 36
20 PRINT x 9 81
30 NEXT x
12 144
(f) 10 FOR x=-10 TO 26 STEP 5
20 PRINT x Explain how this program works.
30 PRINT "Stepping up"
40 NEXT x
Activities
3. Correct the following programs: 4. Study the programs and write out the results.
(a) 10 FOR x = 1 TO 10 (d) 10 FOR x=xTO10
(a) 10 FOR x=2 TO 4
20 PRINT x 20 PRINT x 20 PRINT x,x+4
30 NEXT y 30 NEXT x 30 NEXT x
(b) 10 FOR x = 1 TO 10 STEP —1 (e) 10 FOR x = 1 TO x (b) 10 FOR x=10 TO 16 STEP 2
20 PRINT x 20 PRINT x 20 LET a=x+2
30 NEXT x 30 NEXT x 30 PRINT x,a
(c) 10 FOR x$ = 1 TO 6 STEP 2 40 NEXT x
(f) 10 LET x = 1 TO 10
(c) 10 FOR x=12 TO 3 STEP -3
20 PRINT x$ 20 PRINT x
20 LET a=10
30 NEXT x$ 30 NEXT x 30 PRINT x,a
Variations on a theme. 40 NEXT x
88 Beginning BASIC with the ZX Spectrum
• • Unit 20: FOR-NEXT Loops 89

(d) 10 FOR x=100 TO 200 STEP 25 TYPE:


20 LET a=x-10 10 FOR x=1 TO 5
30 LET b=x+10 20 INPUT "Enter the name of a
40 PRINT x; ;a; ;b country ";c$
50 NEXT x 30 INPUT "Enter the population
Using a FOR-NEXT loop to print out multiplication tables: of the country ";p
40 PRINT "COUNTRY","POPULATION
TYPE:
10 REM MULTIPLICATION TABLES 50 PRINT c$,p
20 FOR x=1 TO 12 60 PRINT
30 PRINT x;"times 8=";x*8 70 NEXT x
40 NEXT x 80 STOP

RUN the program. The result is the eight times table. RUN the program using the information listed below:
This program can be altered so that it will give any table. Country Population
Denmark 5 000 000 (Do not put commas
ADD to program: 8 000 000 between the set of
Sweden
15 INPUT "Enter the number of U.K. 56 000 000 noughts. Do you
the table you require ";n France 53 000 000 know why?)
Belgium 10 000 000
ALTER line 30:
30 PRINT x;"times";n;"= ;x*n TYPE:
10 LET total=0
RUN the program; if the number 5 is entered the five times table will be printed; 20 INPUT "Enter number of pupi
if the number 9 is entered the nine times table will be printed and so on. is ";n
30 FOR p=l TO n
40 INPUT "Enter mark gained by
pupil ";m
50 LET total=total+m
60 NEXT p
Activities 70 LET a=total /n
80 PRINT "The average mark is
Write programs for each of the following and test them on the computer. ";a
90 STOP
5. Print out all the numbers from 13 to 23.
6. Print out all the odd numbers from 3 to 37. RUN the program varying the number of pupils entered in line 20 and the list
7. Print out the numbers from 5 to 35 counting in fives. of marks.
8. Print out all the even numbers from 10 to —6.
9. Print out the seven times table.
10. Print out three sentences which are five blank lines apart.
11. Print out the word `Spectrum' eight times.
12. Write a program that prints out all the leap years in this century. Leap
years occur every four years and the first one in this century was 1904.
13. Print out the value of x that begins at 10 and ends at 20. Print out in a
separate column the value of x + 3.
The next two programs show that the activity that lies in the loop between
the FOR-NEXT statements can be anything. It may be input statements asking
for and printing out information or calculations or both.
90 Beginning BASIC with the ZX Spectrum Unit 20: FOR-NEXT Loops 91

Flowchart for previous program Activities

Write programs for each of the following and test them on the computer.
(START) 14. Input the names of six people and their ages. Print this out in two columns
with headings.
I 15. Using the information given below input and print out the names of four
LINE 10 LET total = 0 cars and their prices. Calculate and print the average price.

Car Price
Ford Fiesta £4600
LINE 20 Enter number of pupils: n
Vauxhall Nova £5000

t (Beginning of FOR-NEXT loop —


Nissan Micra
Talbot Horizon
£4550
£5200
LINE 30 LET p = 1 counter 'p' is set to one)
16. The birth and death rates per 1000 people, for various countries, are given
below. Input this information and calculate the rate of natural population
increase (birth rate minus death rate). Print out all the information.
(Counter in the loop is Birth rate Death rate
compared to the number
entered in line 20; if it is India 43 17
greater than n then the Japan 19 7
loop is missed out and
m/ Britain 15 12
LINE 40 / Enter mark gained by pupil the computer goes to line 70) 9
U.S.A. 16
Malawi 49 25
Ghana 47 18
LINE 50 LET total = total + m Bolivia 44 19

LET p = p + 1
(One is added to
the counter p LINE 70
and the computer
goes back to the LET a = totalen
beginning of the loop)

/PRINT: average mark is: a / LINE 80

t
( STOP ) LINE 90

As you can see, the FOR-NEXT loop appears in the flowchart just like an
ordinary counter and so looks very similar to the diagrams drawn in unit 19.
• •Unit 21: READ and DATA Statements 93

Modify line 10
10 READ a,b,c,d

Unit 21: READ and DATA statements RUN


The result is the error message:
E Out of DATA, 10 : 1
So even though we did not ask the computer to print out the contents of variable
READ and DATA statements can be used only when the computer is in extended 'd' in line 30, because the computer could not find a value to put into 'd', the
mode (press CAPS SHIFT and SYMBOL SHIFT together). READ is above key A
program will not run.
and DATA above key D. String variables can also be used in READ and DATA statements.
READ and DATA statements provide another way of putting information
into a program. However, unlike the INPUT statement where information is fed TYPE:
into the program while it is running, information used in a DATA statement is 10 READ a$,b$,c$
actually written into the program at the beginning and cannot be altered as the 20 DATA "Happy","New","Year"
program is run. In this respect it is rather like a LET statement. 30 PRINT a$;b$;c$
A program will best illustrate how these new statements are used. 40 STOP

TYPE: RUN
10 READ a,b,c The result is:
20 DATA 10,20,30
30 PRINT a,b,c HappyNewYear
40 PRINT b,c,a
Exactly the same has happened as in the previous program; the only difference is
50 STOP
that in the DATA statement the information has to be in quotes, as you would
expect as we are now using string variables.
RUN DO NOT REMOVE
Notice that in all the programs the variables in the READ statement and the
The result is: 10 20 pieces of information (strings or numbers) in the DATA statement are separated
30 by commas (,). This is necessary as it is part of BASIC language.
20 30 READ statements can contain both string and numeric variables provided that
10 they match up with the correct types of information in the DATA statement.
The READ statement gives the names of the variables; in this case numeric
TYPE:
variables called 'a', 'b' and 'c'. The DATA statement supplies the information to
go into these variables, in this example the numbers 10, 20 and 30. 10 READ a$,b$,c$,a
20 DATA "Battle","of","Hasting
As soon as the computer reaches the first variable in a READ statement it s",1066
looks for the first piece of information in the first DATA statement. Thus the 30 PRINT a$;" ";b$;" ";c$;" ";
value 10 is stored in 'a'. As the computer reaches the second variable it searches a
for the second piece of information, therefore 'b' takes the value 20. This 40 STOP
continues until all the variables have been given values. RUN
Line 30 proves that the variable 'a' contains 10, the variable 'b' 20 and
The result is: Battle of Hastings 1066
variable 'c' 30. The contents of these variables do not change, as can be seen in
(Notice that spaces were added to line 30 to make the result of the PRINT
line 40, when the computer is asked to print out the variables in a different order.
statement more readable.)
Each variable in the READ statement must have a matching piece of informa-
There may be more than one READ statement in a program and more than one
tion in the DATA statement. Try the following program:
DATA statement.
92
94 Beginning BASIC with the ZX Spectrum
• r

• Unit 21: READ and DATA Statements 95

TYPE: The list of books reappears on the screen, so provided that the variable fits the
10 REM BOOKS piece of information the actual order is unimportant.
20 READ x,a$,b$,c$,d$ DATA statements often follow READ statements but they can be placed at
30 READ e$,f$,y,g$
40 READ h$
the end of a program.
50 DATA 2001,"Space","Odyssey" In a flowchart the READ statements are represented by input boxes
,"Little" "Women"
60 DATA I "Great","Expectations"
,1984,"Animal","Farm"
70 PRINT "NAME OF BOOK" (dashes — NOT spaces although the DATA statements are not represented but just assumed to be
80 PRINT " shifted I) present. The flowchart that follows is for the program we have just used.
90 PRINT x;" ";a$;" ";b$
100 PRINT c$;" ";d$
Flowchart
110 PRINT e$;" ";f$
120 PRINT y
130 PRINT g$;" ";h$
140 STOP
READ names of books
RUN DO NOT REMOVE g$, b$, Y, e$, c$, a$,
h$, f$, d$, x
As expected the result is a list of book titles but there are several points to
notice about the program. There are three READ statements but only two
DATA statements. This does not matter provided that the variables and
PRINT name of book
information match up correctly and there are enough pieces of information for x, a$, b$
each variable. Variables g$ (Animal) and h$ (Farm) belong together but they c$, d$
have not been written in the same READ statement; the important point is that e$,f$
y
they correspond to the correct information in the DATA statement. This pro- g$, h$
gram can be rewritten in a different order to prove that, provided the variables
and information match up, the result will be the same.
Alter lines 20 to 40 of the previous program. ( STOP
20 READ g$,b$,y,e$,c$
The following program shows how one READ statement may be used several
30 READ a$,h$,f$,d$
40 READ x times if included in a GOTO loop.
RUN TYPE:
10 REM READ STATEMENT IN A GOT
Result: error message: O LOOP
20 LET c=0
C Nonsense in BASIC, 20 : 1 30 INPUT "Enter a number betwe
en 0 and 12";n
This is because the variables no longer match up; for example, `g$' tries to take
40 READ a
the value of `2001' which is obviously not acceptable. 50 DATA 3,4,7,11,1,0,6,8,9,10
60 DATA 2,0,12,7,5,6,3,2,1,12
Now alter lines 50 and 60
70 DATA 1,5,3,7,9,3,11,2,4,-1
50 DATA "Animal","Odyssey",198 80 IF a<0 THEN GO TO 110
4,"Great","Little" 90 IF a=n THEN LET c=c+1
60 DATA "Space","Farm","Expect 100 GO TO 40
ations","Women",2001 110 PRINT "The number of times
";n;" appears is ';c
Leave the rest of the program as it is. 120 STOP
RUN RUN the program several times entering different numbers.
96 Beginning BASIC with the ZX Spectrum
• • Unit 21: READ and DATA Statements 97

This program inputs a number and calculates the number of times it occurs in a It is possible to combine numeric and string variables in a loop but once
list of numbers in the DATA statement. There is only one variable in the READ again the data must match.
statement so this changes its content every time the loop is completed. The first Alter lines 30, 40 and 50
time round `a' takes the value `3' which is then compared in line 90 with the 30 READ y$,w
number `n' which was input in line 30. If `a' = `n' then one is added to the 40 DATA "John", 6,"Mary", 7,"Ann
counter `c'; if they are not equal then the remainder of line 90 is ignored. The e",3,"Paul",10," Harry" ,8
computer is then sent back to the READ statement and as this is the second 50 PRINT y$,w
time round the loop `a' takes the value `4' which is again compared to `n'. This Leave the rest of the program as it is.
sequence of events is repeated until the last value, —1, is reached. When `a' is RUN
less than 0 the computer jumps to line 110 where the result is printed out. The
The result is: John 6
jump from line 80 to line 110 means that the GOTO statement in line 100 is
missed out so the computer does not pass through the loop again and the Mary 7
program stops. Anne 3
Paul 10
Question: What would happen to this program if the value —1 was not included Harry 8
as the last piece of information in the last DATA statement? This program has a string variable `y$' followed by a numeric variable `w' in
Remove this number from line 70 and see if you were right. the READ statement, therefore in the DATA statement the information is
READ and DATA statements can also be used in FOR-NEXT loops. arranged accordingly with a string first followed by a number. As the computer
will read `y$' first the first piece of data is a string `John'. The computer will
TYPE: then read `w' which takes the next item in the DATA list which is the number
10 FOR x=1 TO 7 `6'. This sequence is repeated each time that the loop is executed.
20 READ y
30 DATA 5,10,15,20,25,30,35
40 PRINT y
50 NEXT x
60 STOP Activities
RUN
Rewrite the following programs correcting the mistakes.
This program passes through the FOR-NEXT `x' loop seven times. Each time
1. 10 READ a$, b, c$
through the program the variable `y' takes a new value beginning at 5 and work-
20 PRINT a$, b, c$
ing through the data in the correct order until 35 is reached. As the program is
30 DATA 100, 200, 300
executed seven times there must be seven pieces of information, each being a
2. 10 READ x, y, z$
number since `y' is a numeric variable, in the DATA statement.
20 PRINT x, y, z$
A similar loop can be used with string variables.
30 DATA cat, dog, fish
TYPE: 3. 10 READ a$, b$, c
10 REM NAMES 20 PRINT c; a$; b$
20 FOR x=1 TO 5 30 DATA 3, "Blind", "mice"
30 READ y$
4. 10 READ x$yb$
40 DATA "John","Mary","Anne","
Paul" "Harry" 20 PRINT y; b$; x$
50 PRINT y$ 30 DATA bottles, "10", green
60 NEXT x 5. 10 FOR n = 1 TO
70 STOP 20 READ x
RUN DO NOT REMOVE 30 PRINT x
The program prints a list of five names. The DATA statement now contains 40 DATA 1, 2, 3, 4
strings so the variable used in the READ statement must also be a string. 50 NEXT n
98 Beginning BASIC with the ZX Spectrum
• •
6. 10 FOR n = 1 TO
20 READ x
30 PRINT x
40 DATA "man " "woman " "child" Unit 22: Nested loops
50 NEXT n
7. 10 FOR n = 1 TO 3
20 READ a$, b
30 PRINT a$, b
40 DATA 3. "ships", 2, "cars", 1, "train"
50 NEXT n
8. What would be the contents of variables `a$', `b$' and `e$' at the end of
this program?
10 READ a$,b$,c$
20 DATA "Tom","Dick","Harry","
Jack" "Tim"
30 PRINT a$,b$,c$

9. What would be the contents of variables 'a' and `b$' at the end of this
program?
10 FOR n=1 TO 3
20 READ a,b$
30 PRINT a,b$
40 DATA 1 ," France" ,2,"Britain"
,3,"Norway"
50 NEXT n

10. What would be the contents of variables `x', 'y' and `z' at the end of the
third loop?
This unit also deals with FOR-NEXT loops, but for those cases where one loop is
10 FOR n=1 TO 6
placed or nested inside another.
20 READ x,y,z
30 PRINT x,y,z
TYPE:
40 DATA 35,4,6,8,21,42
50 DATA 10,3,17,9,12,23
Inner or nested loop.
60 DATA 25,15,7,33,14,11
70 NEXT n
10 REM NESTED LOOPS Inside the outer loop.
X20 FOR n=1 TO 4 Repeated 3 times every
Write programs for the following using READ and DATA statements. 30 PRINT n;" OUTER LOOP"
time the computer
11. Print out in a list the seven days of the week. OUTER LOOP. 40 FOR x=1 TO 3 passes through the
50 PRINT x;" inner loop"_
12. Print out a list of 10 numbers taken from anywhere between 35 and 64. Repeated 60 NEXT x outer loop once
13. Input the sentence "The wicked witch cast many magic spells" using separate 4 times 70 PRINT "
variables for each word. Print out three different sentences using some or all -^80 NEXT n (dashes — NOT spaces)
of these words. 90 STOP
(shifted J)
14. Input and print a list of the following items of food and their prices (in
pence):

bread 36, soup 19, jam 58, beans 17, eggs 42, rice 88
RUN
Calculate and print the total cost of all these items in pounds.
99
100 Beginning BASIC with the ZX Spectrum
• • Unit 22: Nested Loops 101

i
The result is: 1 OUTER LOOP The next program shows how a whole set of.multiplication tables can be
1 inner loop printed out using nested loops.
} executed once
2 inner loop repeated 3 times
3 inner loop
2 OUTER LOOP
linnerloop
2 inner loop TYPE:
OUTER LOOP 3 inner loop
repeated 10 REM MULTIPLICATION TABLES
3 OUTER LOOP 20 FOR n =2 TO 12
4 times
1 inner loop 0 30 PRINT n;" TIMES TABLE"
2 inner loop U 40 PRINT " " (dashes — shifted J) (not spaces)
3 inner loop j 50 FOR =1 TO 12 I
E 60 PRINT x;"*";n;"= ;x*n N
4 OUTER LOOP R 70 NEXT x
— ^ 80 NEXT n
1 inner loop
90 STOP
2 inner loop
3 inner loop RUN the program. You will have to `scroll' several times.

Notice that lines 30 and 70 are printed only 4 times because they are part of the
outer loop.
An inner or nested loop must be contained entirely within the outer loop.
You cannot write:

20 FOR n = 1 TO 4 The inner loop 'x' gives the number by which the table is to be multiplied;
30 FOR x = 1 TO 3-. the first time round the loop it will give the 2 TIMES TABLE, the second time
40 PRINT x Loops overlap — round the loop the 3 TIMES TABLE, and so on up to the 12 TIMES TABLE.
50 NEXT n not allowed The inner loop 'x' gives the number by which the table is to be multiplied;
60 NEXT x for example, the first value of x is 1 so the line printed out is 1 x 2 = 2, the
second value of x is 2 so the next time round the loop 2 x 2 = 4 is printed. The
The following program fills the screen with numbers. inner loop finishes when x is 12 and the last line of the table 12 x 2 = 24 is
TYPE printed. Control then goes back to the outer loop, the value of n is increased
10 REM SCREEN OF NUMBERS by 1 so the 3 TIMES TABLE is printed. The whole program finishes when the
^ 20 FOR n=1 TO 22
12 TIMES TABLE has been printed.
30 FOR x=1 TO 20
Outer 40 PRINT x; We can now see how nested loops can be applied to a problem. A shop allows
Inner or nested loop
loop 50 NEXT x items to be purchased on special credit terms provided that 15 per cent of the
60 PRINT price is paid as a deposit. The buyer may then pay off the remaining amount in
.-70 NEXT n monthly instalments over a 6,9 or 12 month period. The program calculates the
RUN 80 STOP
deposits required on items ranging from £5 to £50 for every £5 and then calcu-
lates the monthly instalments. All the information is printed out. The variables
The nested loop 'x', lines 30 to 50, prints out the values of x from 1 to 20 across used are as follows:
the screen. The semi-colon (;) in line 40 makes sure that the numbers are printed p = price
next to each other. The outer loop 'n' is repeated 22 times so there are 22 lines d = deposit
of the numbers 1 to 20. Line 60 makes certain that each time the outer loop is n = number of months to pay off cost
executed a new line is started — see what happens if you remove line 60. m = amount of monthly instalment.
Unit 22: Nested Loops 103
102 Beginning BASIC with the ZX Spectrum
Flowchart for the previous program
TYPE:
10 REM CREDIT TERMS
20 PRINT "PRICE","DEPOSIT"
(STAR T)
• 30 FOR p=5 TO 50 STEP 5 //
40 LET d=0.15*p
50 PRINT p,d
(formula for calculating 15 per cent) f
/PRINT: PRICE DEPOSIT/
O 1 60 FOR n=6 TO 12 STEP 3 (3 monthly intervals)
U N 70 LET m= ( p-d ) /n (formula for calculating monthly payments)
80 PRINT "The monthly instalme Begin counting the price:
T N LET p = 5
nts over ";n;" months is ';m;" p
E E ounds"
R R 90 NEXT n
100 PRINT TRUE
110 NEXT p
120 STOP

RUN
Calculate deposit
LET d=0.15*p
The outer loop, using the variable `p' for price, calculates and prints the deposit
needed for each item beginning at £5. Each time the computer passes through i
this loop £5 is added to the price (STEP 5) until £50 is reached. Line 40 is PRINT: p, d
responsible for the actual calculation of the deposit at 15 per cent (0.15 * price).
In the inner loop, lines 60 to 90, the variable `n' is used for the length of time Begin counting number o
over which the monthly instalments can be paid. The amount of time allowed monthly instalments
LET n = 3
varies between 3, 6 and 12 months. STEP 3 is used because the difference in
time is 3 months. Line 70 calculates the amount of each monthly instalment —
the price minus the deposit divided by the number of months, (p — d)/n, which
is then printed out in line 80. The computer passes through this inner loop 3
times, and so calculates and prints three different amounts for `m'.

Calculate monthly instalments


LET m = (p -- d)/n

I
PRINT: number and amount of
monthly instalments

I
Increase number of monthly
instalments by 3
LET n = n + 3

/ PRINT: start a new line

Increase price of item by £5


LET p = p + 5

C STOP )
104 Beginning BASIC with the ZX Spectrum
^ •
Activities

Use nested loops to write the following programs. Test them on the computer.
1. Print out 10 rows of 10 stars (*).
Input the names of 5 people and the amount of money each has saved in a
Unit 23: Graphics using PRINT
bank account. Print out this information. Calculate the amount of interest statements, colour and moving
each would have gained if the interest rates were 6 per cent. 8 per cent and
10 per cent. Print out the amount of interest and the total amount saved on
graphics
each occasion. Use the following variables:
s = sum saved nS = name of person
r = interest rate
sum saved x interest rate
i = interest gained -
100 Until now we have controlled where the computer is to print a message or num-
n = counter for 5 people ber by using the semi-colon, the comma and the TAB statement. We have also
3. Print out five rectangles of stars (*). The length and width of the rectangles learned how to leave spaces in a program and how to start a new line by just
are to be entered while the program is being used. (This program needs three using the word PRINT (for example, 50 PRINT). However, we can control the
FOR-NEXT loops - each nested inside the other.) print position much more exactly by using PRINT AT. The word AT is on key I
and is obtained by using SYMBOL SHIFT. If you look at diagram 23.1, you
COLUMNS
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

2 2
3 3
4 4
5 5

78 7

9 9
10 10
11 11
12 12
13 13

14 14
15 15
16 16
17 17
18 18
19 19
20 20
21 21
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

Diagram 23.1 To show the number of rows and columns on a Spectrum screen
for use with PRINT AT statements.
will see that the screen is divided into twenty-two rows numbered 0 to 21 down
the screen and into thirty-two columns numbered 0 to 31 across the screen. By
using these numbers. rows first followed by columns, we can make the computer
print anywhere on the screen. For example

105
106

Beginning BASIC with the ZX Spectrum

Unit 23: Colour and Moving Graphics using PRINT statements 107

10 PRINT AT 10. 16: "*" These are not the only characters that we can produce. If, while in graphics
mode, we press CAPS SHIFT and any of the numbers 1 to 8 we get the character
will print a star almost in the centre of the screen. Notice that the two numbers
reversed. In other words the white becomes black and the black, white. For
are separated by a comma and that a semi-colon separates the second number
example
from the rest of the instruction. The program below prints stars at different
positions on the screen. 1 2 3 4 5 6 7 8

TYPE: ^ ® o 19 61 e
10 REM STARS
20 INPUT "Enter a number betwe Add to the previous program:
en 0 and 21";a
30 INPUT "Enter another number
between 0 and 31";b
40 PRINT AT a,b;"*"
20 PRINT AT 12, 9; "
^n o E n
50 GO TO 20
RUN this program a few times, it will go on indefinitely because of the GOTO
RUN
statement. To end the program enter STOP.
We can now use these characters to draw pictures. The program below produces
a bus.

Activity
TYPE:
1. On a copy of diagram 23.1 draw a simple picture or pattern in stars and then
produce it on the screen using the previous program. When your picture is 10 REM Drawing a bus
complete enter STOP. 20 PRINT AT 10,4;"
r
30 PRINT AT 11,4;"
L GI GI ❑ L ❑ "
Now if we are drawing pictures, we do not want to be confined to using stars. 40 PRINT AT 12,4." ^ ^
So let us now look at the graphic characters. They are on the keys 1 to 8 as ❑ ^ ^ __ ^ ^ "
50 PRINT AT 13,4;"
follows:
■■■ 11111.11"
1 2 3 4 5 6 7 8 60 PRINT AT 14,5 ; "00"
(capital letter 0)
❑ CI Mi ^ ❑
70 PRINT AT 14, 9; "00"
29 ©
RUN DO NOT REMOVE
Only the parts in black will appear on the screen; so, for example, number 8
will produce a blank space. To use these graphic characters we must move into
graphics mode; that is, change the flashing L cursor into a flashing G cursor. You may think this is rather an odd bus but it gives you the idea of how to build
This is done by holding down CAPS SHIFT and then pressing key 9 which has up a picture using the graphic characters. It is possible to modify this program so
GRAPHICS written above it. To move out of graphics mode just press key 9 that buses can be printed anywhere on the screen. Look at the following diagram
again. of the bus:
TYPE: 4 5 6 7 8 91011
10 PRINT AT 10,9;"
❑ ti ❑ n ❑ ❑ ❑ ® ❑ 10 .. t! .. 01111 .n
11 -... .ME .. ME .EE
12
13
fl.II 11 ■ 11
RUN DO NOT REMOVE
14 11r^^'^'■^'^^,^
\ J\ I \ I\
108 Beginning BASIC with the ZX Spectrum
• Unit 23: Colour and Moving Graphics using PRINT statements 109

The wheels of the bus are in row 14 (lines 60 and 70 of our program), so if we computer to colour the border or the screen or both. The border is the part of
call row 14, row `a', then row 13 will be `a — 1' and row 12 will be `a — 2' and the screen that is not printed on except for input statements.
so on. The left-hand edge of the bus is in column 4, so if we call this column `b' Add to the previous program:
then column 5 will be `b + 1', column 6 will be `b + 2' and so on. This is
illustrated in the next diagram: 16 BORDER 1

• N M RLO (D N
Delete line 80.
+ + + + + + + RUN the program. The border will remain blue until another command is given.
d _0 _O _0 '^ a d
Change line 16:
® 11 • • 16 BORDER 2
11 • 11 • • RUN the program.
Try as many colours as you like but eventually decide on one colour that you
'41:0••••
would like to use.
DO NOT REMOVE
We can now change lines 20 to 70 in our bus program using variables `a' and
To colour the actual bus we need to change the ink. We will make the bus red
Alter the previous program:
and the wheels black.
10 REM Drawing a bus
20 PRINT AT a-4,b Add to the program:
30 PRINT AT a-3,b The rest of these lines
40 PRINT AT a-2,b remain the same 19 INK 2
50 PRINT AT a-].,b 55 INK 0
60 PRINT AT a,b+1
70 PRINT AT a,b+5 RUN DO NOT REMOVE
Now all we need to do is to enter the numbers that `a' and `b' represent.
Finally we can colour the background by changing the colour of the paper.

Add to the program: Add to the program:

12 INPUT "Enter a row-"; a 17 PAPER 6


15 INPUT "Enter a column-"; b
RUN the program.
80 GOTO 12
Experiment with the INK and PAPER colours.
RUN the program so that nine buses fit on to the screen without touching each DO NOT REMOVE
other or going 6ff the edge of the screen. You will need to use diagram 23.1 to
It is also possible to make the bus move. We do this by using a FOR-NEXT
help you. If you go off the edge all sorts of odd things will happen. If you have
loop.
done this successfully, deliberately type in numbers that will cause one bus to
overlap another. Alter the program:
What happens? Delete line 10
DO NOT REMOVE Add:

To colour the picture we use the commands: 5 FOR r = 0 TO 31 Prints out a road for the
6 PRINT AT 12, r; " bus to travel along
INK (below key X) both used in extended mode
7 NEXT r
PAPER (below key C) with symbol shift
Edit line 12:
BORDER (keyword on key B) — entered in keyword mode
12 LET a = 11
The colours that can be used are written above and operated by the number
keys; for example, blue is number 1, red is number 2 and so on. We can tell the Delete line 15.
110 Beginning BASIC with the ZX Spectrum
• •
Unit 23: Colour and Moving Graphics using PRINT statements 111

Add: ship, aeroplane. Use different colours for the border, paper and ink.
Make your vehicle move across the screen.
18 FOR b = 1 TO 23
(b) Alter your program so that your vehicle crosses the screen six times.
80 NEXT b
Each time it crosses it should be printed in a different colour (set the
Edit lines 20 to 70 PAPER colour to white).
10 REM Drawing a bus Rest of line as before, but with the We will now look at moving objects in more detail. The next program moves a
20 PRINT AT a-4,b;" addition of a space before
30 PRINT AT a-3,b;" black square all the way round the edges of the screen. The only complicated part
40 PRINT AT a-2,b;" the first graphic character of the program is making sure that each square is rubbed out by a space as the
50 PRINT AT a-1,b;" on each line next square is printed. The two variables used are `a' for the rows and `b' for the
60 PRINT AT a,b+1;" 00" columns. Each section of the program begins with a PRINT statement, which
70 PRINT AT a,b+5;" 00"
tells you where the square will be moving. Lines 40, 130, 200 and 280 use a new
RUN DO NOT REMOVE command CLS (key V) which removes the writing off the screen before the
square begins to move. The PAUSE statement before each of these lines ensures
The bus will now rush across the screen from left to right. We can slow down the
that the message stays for 2 seconds, just long enough to be read, before being
movement of the bus by using the command PAUSE on key M. For example
cleared. (Do not confuse CLEAR (key X) with CLS. CLS stands for CLear
PAUSE 50 means wait for 1 second Screen, and just wipes away what is printed on the screen, whereas CLEAR
PAUSE 150 means wait for 3 seconds (could also be written removes all the variables from the computer's memory!)
PAUSE 50 * 3)
TYPE:
We do not want to slow the bus down too much so we will use only part of a
10 REM Moving square
second.
20 PRINT "Square moves down th
Add: e left-hand edge"
30 PAUSE 100
75 PAUSE 10 40 CLS
50 LET b=0
RUN DO NOT REMOVE 60 FOR a=0 TO 18
70 PRINT AT a,b;" "
The bus now travels rather disjointedly across the screen. The FOR-NEXT loop 80 PRINT AT a+1,b;"u"
is actually responsible for moving the bus. `b' is given the value 1 at the beginning 90 PAUSE 10
100 NEXT a
so the bus starts by having its left-hand edge in column 1; the next time round 110 PRINT "Square moves along t
the loop `b' is 2 so the bus moves along to the next column; the third time he bottom of the screen from lef
round the loop `b' is 3 so again the bus is printed one column farther in, and so t to right"
on until `b' is 22. As the bus moves the previous left-hand edge of the bus is 120 PAUSE 100
130 CLS
rubbed out by the space that was added to lines 20 to 70. If you want to alter
140 FOR b=0 TO 30
the speed of the bus simply change line 75 — remember PAUSE 50 is one second. 150 PRINT AT a,b;" i11
160 PAUSE 10
Edit line 75:
170 NEXT b
75 PAUSE 0 180 PRINT "Square moves up righ
t-hand edge"
RUN — the bus will not move until you press any key except the two shift keys. 190 PAUSE 100
200 CLS
REMOVE THE PROGRAM 210 FOR a=19 TO 1 STEP -1
220 PRINT AT a-l,b; "E"
230 PRINT AT a,b;" "
Activity
240 PAUSE 10
250 NEXT a
2. (a) Write a program that prints a picture of one of the following: car, train, 260 PRINT "Square moves across
112 Beginning BASIC with the ZX Spectrum
• •
Unit 23: Colour and Moving Graphics using PRINT statements 113

the top of screen from right to 0 1 2

left" first space


270 PAUSE 100 1 first square
280 CLS
2
290 FOR b=30 TO 0 STEP -1
300 PRINT AT a,b;" ■ "
310 PAUSE 10
320 NEXT b The second time round the loop `n' has the value 1 so the space is printed in
330 STOP 1, 1 (n, n) which rubs out the first square and the second square is printed in
RUN 22(n+1,n+1).

Activities
Moving the square downwards is done by adding 1 to the value of `a' (the
rows) every time the FOR-NEXT loop `a' is executed. `b' (the columns) remains
3. Study the program below and decide where the square is moving to and
constant as the column does not change, so `b' is set to 0 and remains at 0. from. Draw a diagram to show where the first space and square will be
Line 70 prints a space which will follow the square all the way down the edge,
printed.
so rubbing out the previous square. The first space is printed in 0, 0 (a = 0,
10 FOR n=0 TO 19
b = 0) and therefore the first square is printed in 1, 0 (a + 1 = 1, b = 0). The 20 PRINT AT n,20-n;" "
second time round the loop `a' is 1, so the space will be in 1, 0 (a = 1, b = 0) 30 PRINT AT n +1,19-n;"."
and the square in 2, 0 (a + 1 = 2, b = 0). 40 PAUSE 10
Moving the square across the screen from left to right has already been 50 NEXT n
60 STOP
discussed in the bus program. Moving the square back up the screen is a matter
of working backwards; `a' now begins at 19, so 1 is taken off instead of being 4. Write a program that moves a black square diagonally across the screen from
added on each time through the loop (STEP — 1 in line 210). The space must near the bottom right-hand corner to the top left-hand corner. Begin at row
continue to follow the square, so now it is placed below the square and is 20 and column 20.
printed in 19, 30 (a = 19, b = 30 as the square has moved from column 0 to 30
in the previous section of the program) and the first square is printed in 18, 30
(a — 1 = 18, b = 30). Finally the square moves back across the screen from right
to left by taking 1 from the value of `b' which is now 30. The row does not The following program enables you to draw a pattern by moving the square in
change so `a' remains constant. The space still follows on behind, so it is printed any direction that you wish. It uses the number keys 5, 6, 7 and 8 which show
on the right-hand side of the square. the direction of movement by the arrows drawn above them. In order to do this
The next program moves the square diagonally from the top left-hand corner the program uses the function INKEY$ (above key N-extended mode). This
to near the bottom right-hand corner. function allows us to press a key on the keyboard and get an immediate result.

TYPE: TYPE:
10 REM Square moves diagonally
20 FOR n=0 TO 20 10 REM Drawing with a square
30 PRINT AT n,n;" " 20 LET a=11 i (a = rows, b = columns)
40 PRINT AT n+1,n+1;"11" 30 LET b=16
50 PAUSE 10 40 PRINT AT a,b;"."
60 NEXT n 50 IF INKEY$="5" THEN LET b=b-
70 STOP 1
60 IF b<0 THEN LET b=0
70 IF INKEY$="6" THEN LET a=a+
RUN
1
Now the rows and columns are represented by `n' so both begin at 0. The space 80 IF a>21 THEN LET a=21
90 IF INKEY$=" 7" THEN LET a=a-
is first printed in 0, 0 (n, n) and the square in 1, 1 (n + 1, n + 1). See the diagram 1
that follows. 100 IF a<0 THEN LET a=0
114 Beginning BASIC with the ZX Spectrum
• •
Unit 23: Colour and Moving Graphics using PRINT statements 115

110 IF INKEY$="8" THEN LET b=b+ TYPE:


1
120 IF b >31 THEN LET b =31 10 FLASH 1
130 GO TO 40 20 PRINT "These characters are
flashing"
RUN 30 FLASH 0
40 PRINT "These characters are
The only way to stop this program is to press CAPS SHIFT and BREAK at the not flashing"
same time, followed by ENTER which returns the program listing to the screen. 50 STOP
This program draws a continuous thick black line because we have not
RUN
rubbed out the square as we have moved along. The first square is printed in 11,
16 as these are the values given to `a' and `b' at the beginning of the program. BRIGHT means make the characters appear on a brighter background, it is like
The value of `a' and `b' then changes according to the key pressed. If `5' is adding highlights. It operates in the same way as FLASH.
pressed the square moves one position to the left and therefore the number of
TYPE:
the column must decrease, so `b' becomes `b — 1; `a' remains the same since the
square is in the same row. If `6' is pressed the square moves down one place so 10 BRIGHT 1
20 PRINT "I am bright"
the number of the row increases by 1 and therefore `a' becomes `a + 1'. If `7' is 30 BRIGHT 0
pressed the square moves up one place so the number of the row decreases and 40 PRINT "I am dull"
`a' becomes `a — 1'. If `8' is pressed the square moves to the right so `b' becomes 50 STOP
`b + 1'. Lines 80 and 100 just make certain that `a' never gets smaller than 0 or
larger than 21, and lines 60 and 120 make sure that `b' never gets smaller than 0 RUN
or larger than 31. This keeps the square on the screen and stops an error message INVERSE reverses the inks just like the FLASH command but there is no flash-
appearing on the screen. ing from one to the other. Again the numbers 1 and 0 are used to turn the
command on and off.

Activity TYPE:
10 INVERSE 1
5. Alter the program so that as the square moves the previous one is rubbed out. 20 PRINT "My characters are wh
You will need to put spaces all round your square so that whatever direction ite on a black background - I'm
inverted"
it is moved in there is a space behind it to rub out the square. Also, since you 30 INVERSE 0
will have an `invisible' area all round your square you will need to adjust the 40 PRINT "My characters are no
size of your screen otherwise your spaces will be off the screen and error rmal"
messages will appear. 50 STOP

RUN
If FLASH, BRIGHT and INVERSE are not turned off at the end of the program
This idea of moving an object or character around the screen is a common
they will continue to affect ever y thing that follows (for example, the listing of
feature of most computer games.
the program).
To conclude this unit we will look at three other commands:
FLASH (key V) All used in extended mode
BRIGHT (key B) with
INVERSE (key M) } SYMBOL SHIFT

FLASH simply means, make the characters printed flash from black ink to white
ink on a black background, just like the flashing cursors used by this computer.
Number 1 starts the flashing and number 0 stops it.
Unit 24: Arra ys — DIM Statement 117

2 variable not found, 20 : 1

has appeared on the screen. This is because, before an array can be used, the
computer has to be told the name and size of the array so that it knows how
Unit 24: Arrays—DIM statement many storage spaces are needed. This is done by using the DIM statement which
is an abbreviation for dimension. DIM is found on key D.

TYPE: 10 DIM A(5)


T T size of array — number of elements
An array is a set or group of storage spaces all with the same name. The name of name of array
the array is just one letter of the alphabet (a lower or upper case letter). It is Now RUN DO NOT REMOVE
rather like a variable but instead of a single storage space, it is several, like a box
with many compartments. The result is now what you woulu expect:
Each storage space in the array is called an element and is referred to by a
100
number. For example, if we use an array named `A' to store five numbers then
the first number will be stored in the first element or storage space called A(1), 200
300
the second number in A(20) and so on until the last number is stored in A(5).
400
This would then be a numeric array with five elements — it will contain five
numeric variables. 500
However, it probably has occurred to you that this result could have been
100 C 300 C C achieved just as easily by using five different variables. For example

TIMMM. UM 20 LET A = 100


30 LET B = 200
40 LET C = 300
A(1) A(5) etc.
A(2) A(3) A(4)
70 PRINT A„ B„ C

Numeric a ray with five elements So the next program uses the same array but only prints the number required
by the person running the program. This could not be done if ordinary numeric
The array illustrated above shows that the number 100 is stored in A(1), the variables had been used.
number 200 in A(2) and so on. The computer can call on any of these numbers
Leave lines 10 to 60 as they are.
by simply referring to the name and number of its storage space. For example,
Delete line 70.
type PRINT A(1) and 100 appears on the screen.
TYPE:
TYPE:
70 INPUT "Enter a number between 1 and 5_”; n
20 LET A(1)=100
30 LET A(2)=200 80 PRINT A(n)
40 LET A(3)=300 90 STOP
50 LET A(4)=400
60 LET A(5)=500 RUN the program several times using different numbers.
70 PRINT A(1)„A(2)„A(3)„A(4
„A( 5) As you can see, the number `n' entered in line 70 is then used with the name of
RUN! the array `A' in line 80. So if number 2 is entered then A(n) is really A(2) and
You will be surprised to find that the program does not work although each 200 will be printed.
Another use of an array is to enter the numbers into the array while the
element in the array has been given a value. The error message
program is running.
118 Beginning BASIC with the ZX Spectrum
• Unit 24: Arra ys — DIM Statement 119

TYPE: TYPE:
10 DIM b(7) 10 DIM d(10)
20 FOR n=1 TO 7 20 FOR g=1 TO 10
30 INPUT "Enter a number ";b(n 30 READ d(g)
40 DATA 11,12,13,14,15,16,17,1
40 PRINT b(n) 8,19,20
50 NEXT n 50 PRINT d(g)
60 PRINT b(1) 60 NEXT g
70 PRINT b(3) 70 STOP
80 PRINT b(7) RUN
RUN the program. Check that lines 60 to 80 print the numbers you expect. Using the READ and DATA statements in a FOR-NEXT loop is a very quick
DO NOT REMOVE way of entering numbers into an array. It is a much better method than using
This program uses an array called `b' which has seven elements or storage spaces.
LET d(1) = 11
Lines 20 and 50 set up a FOR-NEXT loop `n' which will operate seven times. In
LET d(2) = 12
line 30 a number is entered which the first time round the loop will be stored in
LET d(3) = 13
`b(1)' as `n' has the value of 1. The second time round the loop `n' has the value
etc.
of 2 so the second number entered will be stored in `b(2)'. This continues until
the seventh number is entered into `b(7)' and the array is complete. Line 40 just So far we have dealt only with numeric arrays but obviously it must also be
prints out the value of each element or variable while lines 60 to 80 really prove possible to have string arrays. As for numeric arrays, only one letter can be used
that the variables `b(1)', `b(2)' etc. really do exist. for the name of the array — `a', `b', `c' etc. — but to distinguish the string array
It is possible to treat the elements of the array just like ordinary variables and from the numeric array the dollar sign (5) is again used. The size of the array
use them as we wish. If we extend the previous program we can print the values must be given as before but also the maximum length of any of the strings to be
of the elements in any order. stored in the array. For example
1 Dollar sign for a string array
TYPE: DIM a $ (5, 15)
T T '_Maximum length of any
100 PRINT Name Size
110 FOR s=7 TO 1 STEP -1 string. A string with more
of of
120 PRINT b(s) array array than 15 characters cannot
130 NEXT s be stored in this array
140 PRINT
150 FOR r=1 TO 7 STEP 2 TYPE:
160 PRINT b(r) 10 DIM a$(5,15)
170 NEXT r 20 FOR n=1 TO 5
180 STOP 30 READ a$(n)
40 DATA "Goodbye","Hello","Hap
py Christmas","Happy New Year","
If we entered the numbers Sleep well"
50 NEXT n
11,22,33,44,55,66,77 60 INPUT "Enter the number of
the message you wish to be print
could you write out the result of the program before running it? ed ";n
RUN the program and check your answer. 70 PRINT a$(n)
Add to the program so that the numbers 77, 44 and 11 are printed in that order. 80 STOP
(Remember to remove the STOP statement in line 180 first.) RUN the program several times entering different numbers.
RUN the program and check your answer. The DIM statement sets up the array called `a$'; it has five storage spaces and the
Numbers can also be entered into an array by using READ and DATA state- longest string to be used will have 15 characters which is `Happy Christmas'
ments. This is illustrated in the next program. (remember the space counts as a character). The FOR-NEXT loop `n' reads the
120 Beginning BASIC with the ZX Spectrum Unit 24: Arrays — DIM Statement 121

data into the five elements of the array. The message to be printed is decided by 70 to 90, feed the information in using READ and DATA statements. Notice
the number entered in line 60. that all the strings are contained in one DATA statement, this is possible because
The next program called a "FRUIT MACHINE GAME" uses two string arrays the first loop `n' takes the first ten items out of the DATA statement and puts
and many of the techniques learned in the last few units. them into a$(1), a$(2) etc. and then the second loop `m' takes the next ten
items and stores them in b$(1), b$(2) etc.
TYPE: The counter `s', to keep the score, is set up in line 110. The title and the rules
10 REM Fruit Machine Game of the game are printed by lines 120 and 130. Another FOR-NEXT loop using
20 DIM a$(10,6) the variable `a' (in no way connected with array `a$') is then set up to count to
30 DIM b$(10,6)
40 FOR n=1 TO 10 5, the number of turns the pla yer is allowed to have. In lines 160 to 190 numbers
50 READ a$(n) are entered which refer to two different storage spaces, one in each of the two
60 NEXT n arrays. The contents of these storage spaces are printed out, `a$(n)' and `b$(m)'.
70 FOR m=1 TO 10 Lines 200 and 210 compare the contents of `aS(n)' and `b$,(m)', if they are not
80 READ b$(m)
90 NEXT m
the same then the player loses and no points are scored and the computer jumps
100 DATA "orange" "lemon","oran to line 230. If the contents are the same then the player wins and scores 5 points
ge" "cherry" "bell","orange","ch which are added to the score `s' in line 220. The computer then continues
erry","lemon","bell","orange","c through the program by repeating the loop until it has been executed five times.
herry" "bell" "lemon","cherry","
The program finishes by printing out the final score.
orange" "bell","lemon","orange",
"bell" "lemon" Another important thing to note about string arrays is that, as the maximum
110 LET s=0 length of any of the strings to be stored has to be given, then any string put into
120 PRINT "FRUIT MACHINE GAME" one of the elements of the array will automatically be padded out with spaces if
130 PRINT "RULES-you cannot ent
it is less than the maximum length. See the example that follows.
er the same pair of numbers twic
e If we set up a string array: DIM a$ (6,7) then the computer's memory will
140 PRINT look like this:
150 FOR a=1 TO 5
160 INPUT "Enter a number betwe
en 1 and 10 ";n
170 PRINT a$(n);" Length of string
Array name and
A
180 INPUT "Enter another number number of element 1 2 3 4 5 6 7
between 1 and 10 ";m
190 PRINT b$(m) a$(1)
200 IF a$(n)<>b$(m) THEN PRINT
"You lose - no points scored": G a$(2)
O TO 230
210 IF a$(n)=b$(m) THEN PRINT " a$131
you win - 5 points scored"
220 LET s=s+5 a$(4)
230 PRINT
240 NEXT a a$(5)
250 PRINT
.260 PRINT a$(6)
270 PRINT "You scored ";s;" poi
nts"
280 STOP
This array is waiting to be filled with 6 strings, each of length 7 characters. If the
RUN
following strings are entered
Lines 20 to 100 put the information into the elements of the two arrays called dog, giraffe, camel, fish, hamster, kitten
`a$' and `b$'. Each array has storage spaces for 10 strings with a maximum
length of 6 characters. Two FOR-NEXT loops `n' and `m', lines 40 to 60 and 'the array will look like this (a dash represents a space)
122 Beginning BASIC with the ZX Spectrum
• • Unit 24: Arra ys - DIM Statement 123

DO NOT REMOVE
RUN
Length of string
A
Array name and
number of element 1 2 3 4 5 6 7 The computer now prints `0 K' because `b$' has been padded out with three
spaces which will now fit into a$(1). However, this is not a good way to over-
a$(1) d o
come the problem; it is much better to let b$ have an array of its own, also with
a$(2) g r a f f e a maximum length of five characters.

a$(3) c am e
Modify the program.
15 DIM b$(1,5)
a$(4) f i s h — — — 20 LET b$(1)="hi"
30 LET a$(1) =b$(1)
a$(5) h a m s t e r 40 IF a$ (1) =b$(1) THEN PRINT
0 K"
a$(6) k i t t e n — RUN the program

`b$(1)' is now automatically five characters long as the word `hi' will be padded
So what appears to be nothing is really a space, which is a character. Hence all of out with three spaces and so `0 K' will be printed. Let us see if this will work in
these strings are the same length. It is necessary to remember this because if you a more complicated program.
were writing a program and wished to enter a word and then compare it with TYPE:
words in an array, they have to be the same length. For example, imagine we
10 REM COMPUTERS
have set up the array as drawn in the last diagram and the program goes as 20 DIM a$(12,9)
follows: 30 DIM x$(1,9)
40 PRINT "COMPUTERS"
50 INPUT "Enter the name of an animal-"; b$ 50 INPUT "Enter the name of a
60 IF b$ = a$(1) THEN PRINT "Woof, woof" computer ";x$(1)
60 FOR n=1 TO 12
Even if the word `dog' is entered the computer will ignore the instruction to 70 READ aS(n)
print "Woof, woof" because `dog' contained in `b$' is only three characters long 80 IF x$(1)=a$(n) THEN PRINT
Yes,there is a computer called t
whereas the `dog' in a$(1) is seven characters long, therefore they are not the same
he ";x$(1): GO TO 120
string. In the Fruit Machine Game program, lines 200 and 210, the elements of 90 NEXT n
the two different arrays were compared but as both arrays had the same maxi- 100 PRINT "No,there is not a co
mum length (6) this was possible. If the second array had been called `b$ (10, 7)' mputer called the ";x$(1)
this program would not have worked. We can prove this point in the following 110 DATA "Spectrum","Oric","B.B
.0","Apple","Electron","Atari","
program. ZX81","Research","Acorn","Commod
ore" "I.B.M","Dragon"
TYPE:
120 STOP
10 DIM a$(3,5)
20 LET b$=" hi"
RUN
30 LET a$(1) =b$ The name entered in line 50, stored in the array x$(1, 9), is compared with the
40 IF a$(1) =b$ THEN PRINT "0 K contents of array `a$(12, 9)'. This is possible because both arrays contain strings
that are nine characters long. As array `a$' has twelve elements the content of
RUN DO NOT REMOVE x$(1) is compared with each element in turn, beginning with a$(1). The GOTO
Nothing happens except that the message 0 0 K, 40 : 1 appears. This is because statement in line 80 causes the computer to jump out of the FOR-NEXT loop
it is not possible for a$(1) to contain the word `hi' which is only two characters, `n' which is something we have not tried before. Can you think why this was
since the `a$' array states that all the elements must have five characters. necessary?
A program can contain both numeric and string arrays but these must be
Alter line 20 separate arrays. It is not possible to have a mixture of numeric and string
20 LET b$ = "hi ___" variables in the same array.
124 Beginning BASIC with the ZX Spectrum
• • Unit 24: Arrays — DIM Statement 125

TYPE: (b) Add another section to the program, in order to print this information in
two columns. Each column must have a heading.
10 REM MOUNTAINS
20 DIM a$(6,11) RUN your program.
30 DIM x(6) 2. Write a program that inputs eight numbers and then prints them out in reverse
40 FOR n=1 TO 6 order.
50 READ a$(n)
3. Write a program that inputs twelve numbers and then prints out every other
60 DATA "Everest" "Kilimanjaro
"Table" "Blanc","Matterhorn"," number.
Ben Nevis" 4. (a) Write a program that stores the names of the days of the week and then.
70 NEXT n prints the name of the day according to the number entered by the user.
80 FOR m=1 TO 6
(b) Modify the program so that if a number less than 1 is entered then
90 READ x(m)
100 DATA 8848,5895,1087,4807,44 "number too low" is printed or if a number above 7 is entered then
78,1347 "number too high" is printed and the computer goes back to the line
110 NEXT m where another number can be entered.
120 PRINT "MOUNTAIN","HEIGHT IN
(c) Modify the program so that it runs four times before stopping.
METRES"
130 PRINT 5. Write a program that inputs a word which is checked to see if it is the name
140 FOR Y=1 TO 6 of a month. If it is then the program should print out the number of that
150 PRINT a$(y),x(y) month (for example, May is month 5). If the word is not a month then the
160 NEXT y message "Not a month" should be printed. (You need two arrays, one to
170 STOP
store the names of the months and the other to store the word that is entered.)
RUN DO NOT REMOVE 6. Write a program that stores and prints the following information.
Lines 20 and 30 set up the two arrays, a$(6, 11) for strings and x(6) for numbers.
The first FOR-NEXT loop `n' enters the names of the mountains into six HOW ELECTRICITY IS PRODUCED IN THE U.K.
elements of the string array. The second FOR-NEXT loop `m' enters the heights Source of electricity Percentage of total produced
of the mountains into six elements of the numeric array. Notice that there is no Coal 79
connection between the two arrays. Line 120 prints out the headings for two Oil 8
columns. The third FOR-NEXT loop `y' prints out the information in two Nuclear 11
columns. Water 2

Why is the variable 'y' used with a$ and x in this last loop? Test your programs on the computer.

Activities All the arrays used so far are known as one-dimensional arrays. This is because
they contain only one set or list of elements. However, it is possible to have two-
1. (a) Add another string array to the previous program to store the names of dimensional arrays. For example, DIM a(6, 3) means that the array called `a' has
the countries in which the mountains are situated. Use the information eighteen elements, six rows of three columns. The names of the elements in the
given below. array are:

Mountain Country Column 1 Column 2 Column 3


Everest Nepal-Tibet Row 1 a(1,1) a(1,2) a(1,3)
Kilimanjaro Tanzania Row 2 a(2, 1) a(2,2) a(2,3)
Table South Africa Row3 a(3, 1) a(3,2) a(3,3)
Blanc France Row 4 a(4,1) a(4, 2) a(4, 3)
Matterhorn Switzerland Row 5 a(5,1) a(5,2) a(5,3)
Ben Nevis Scotland Row 6 a(6,1) a(6,2) a(6,3)
126 Beginning BASIC with the ZX Spectrum Unit 24: Arra ys — DIM Statement 127

the value 7.48; the inner loop is repeated again so the third
Notice that the first figure in the brackets refers to the row and the second
element is a(1, 3) which takes the value 8.04; the first row of
figure to the column:
the array is now complete. Control then returns to the outer
DIM a (6 , 3) loop so `n' becomes 2 and `m' returns to 1 so the next element
t t t is a(2, 1), and this takes the value 7.14. This pattern continues
Name Number Number until the outer loop has run six times and then all the elements
of of of
numeric row column will contain numbers.
array - Lines 140 and 150 — print out the headings in three columns.
6X3=an18
element array Lines 160 to 210 — two nested loops print out the information in columns and
rows. Loop 'x' counts the rows and loop 'y' the columns
The following program uses a two-dimensional numeric array.
hence the name of each element is now a(x, y).
TYPE: The next program stores the names of six pupils and their examination marks
10 REM TRAIN TIMES for English, French and Maths. It prints this information in a table and also
20 DIM a(6,3) calculates and prints the pupil's total marks and average marks.
30 FOR n=1 TO 6
40 FOR m=1 TO 3 TYPE:
50 READ a(n,m) 10 REM CLASS MARKS
60 DATA 7.01,7.48,8.04 20 DIM a(6,3)
70 DATA 7.14,8.03,8.19 30 DIM n$(6,7)
80 DATA 7.32,8.19,8.33 40 FOR n=1 TO 6
90 DATA 7.45,8.32,8.49 50 FOR m=1 TO 3
100 DATA 8.01,8.54,9.07 60 READ a(n,m)
110 DATA 8.13,9.03,9.19 70 DATA 42,52,61,12,23,34,67,7
120 NEXT m 2,'63,78,82,91,53,62,58,73,69,85
130 NEXT n 80 NEXT m
140 PRINT "BRIGHTON E.CROYDON 90 NEXT n
VICTORIA" 100 FOR z=1 TO 6
150 PRINT "DEPART ARRIVE 110 READ n$(z)
120 DATA "Smith","Allen","Brown
ARRIVE"
ey" "Davies","Cotton","Baker"
160 FOR x=1 TO 6
130 NEXT z
170 FOR y=1 TO 3
140 PRINT "NAME ENGLISH FRENC
180 PRINT a(x,y);"
H MATHS"
190 NEXT y
150 FOR x=1 TO 6
200 PRINT
160 'PRINT n$(x); ',
210 NEXT x
170 LET t=0
220 STOP
180 LET v=0
RUN 190 FOR y=1 TO 3
200 PRINT a(x,y);"
Points to note: 210 LET t=t+a(x,y)
Line 20 — sets up two-dimensional numeric array. 220 NEXT y
Line 30 — counts the number of rows — 1 to 6. 230 LET v=t/3
Line 40 — counts the number of columns — 1 to 3. 240 PRINT
250 PRINT "TOTAL MARKS ";t
Line 50 — reads the information into the elements of the array 260 PRINT "AVERAGE MARK ";v
a (n, m) 270 PRINT
280 NEXT x
name, row, column 290 STOP
Lines 60-110 — supply the train times. First time round the loop the first RUN the program.
element is a(1, 1), and this takes the value 7.01; the inner loop Study the result and the program.
is then repeated so the second element is a(1, 2), and this takes Write a description of how the program works.
128 Beginning BASIC with the ZX Spectrum
• • Unit 24: Arra ys — DIM Statement 129

We can now write a program to play the game of battleships. Battleships TYPE:
consists of a board 8 squares by 8 squares on which are secretly placed 4 sub- 10 REM BATTLESHIPS
20 DIM a(8,8)
marines, 2 destroyers, 2 cruisers and 1 battleship, as drawn on the diagram 30 LET n=0
below. Notice the shapes of the ships, it is important to remember these when 40 FOR p=1 TO 8
playing the game. 50 FOR q=1 TO 8
60 READ a(p,q)
1 2 3 4 5 6 7 8 70 IF a(p,q)<>0 THEN LET n=n+1
80 NEXT q
1 D D 90 NEXT p
2 C C 100 DATA 0,0,0,0,0,0,2,2
110 DATA 0,3,3,0,0,0,0,0
3 C B 120 DATA 0,0,3,0,0,4,0,0
S = submarine
4 S B S 130 DATA 1,0,0,0,0,4,0,1
D = destroyer
140 DATA 0,0,2,2,0,4,0,0
5 D D B C = cruiser
B = battleship 150 DATA 0,1,0,0,0,4,0,0
6 SI B 160 DATA 0,0,0,3,0,0,0,1
170 DATA 0,0,3,3,0,0,0,0
7 C S
8 C C The board for the battle is now stored in the array `a(8,8)'; for example, the
number 0 is stored in a(3, 1) and the number 4 in a(3, 6). The counter `n' has
The position of these ships has to be stored in a numeric array so it is necessary kept a record of the number of squares that have ships on them. Now the com-
to change the letters to numbers. Therefore submarines will be 1, destroyers 2, puter needs to know what 1, 2, 3 and 4 represent because if you hit a ship you
cruisers 3 and the battleship 4. Any square without a ship is a 0. So the board need to know what you have hit and to give a number as an answer is not good
now looks like this. enough. So we will use a one-dimensional string array, s$(4, 10), to store this
information. The array has four elements consisting of ten characters each.
1 2 3 4 5 6 7 8
0 0 0 0 0 0 2 2
2 0 3 3 0 0 0 0 0 TYPE:
3 0 0 3 0 0 4 0 0 0= no ship 180 DIM s$(4,10)
1= submarine 190 FOR b=1 TO 4
4 1 0 0 0 0 4 0 1 200 READ s$(b)
2 = destroyer
5 0 0 2 2 0 4 0 0 3 = cruiser 210 DATA "submarine","destroyer
4 = battleship "cruiser","battleship"
6 0 1 0 0 0 4 0 0 220 NEXT b
7 0 0 0 3 0 0 0 1
8 0 0 3 3 0 0 0 0 The computer now knows that s$(1) is a submarine, s$(2) is a destroyer, s$(3) a
cruiser and s$(4) a battleship.
This information can now be fed into a two-dimensional numeric array with To play Battleships it is necessary to enter two numbers, these will be called
64 elements -- 8 columns and 8 rows, we will call this `a(8,8)'. This is done by `x' and `y' in the program. The first number `x' refers to the columns and the
using nested loops, the outer loop `p' counts the rows and the inner loop `q' second number `y' refers to the rows. Numbers entered must be between 1 and 8,
counts the columns. The inner loop will run eight times every time that the outer anything smaller than 1 or larger than 8 is not allowed. The computer will check
loop is executed once. While this information is being read into the array it is this and print an appropriate message if necessary. If the numbers 5 and 6 are
necessary to count the number of squares that are 0; this gives us the number of entered then `a(5,61' is a 0 (see the next diagram), so the computer reports that
squares that contain ships which will be needed later to see when all the ships you have missed and then we need to return for another turn. If on the other
are sunk and the game ended. Variable `n' is used for this and then each element hand you enter 2 and 6 you will be told that you have hit a submarine (see the
of the array, `a(q, p)', will be compared with 0; if it does not equal 0 then 1 is next diagram). (When playing the game it is as well to keep a blank copy of the
added to the counter `n'. We can now write the first part of the game. board so that you can record your hits and misses.)
130 Beginning BASIC with the ZX Spectrum
• • Unit 24: Arra y s — DIM Statement 131

1 2 3 4 5 6 7 8 TYPE:
10 REM NAMES
0 0 0 0 0 0 2 20 DIM a$(4,2,6)
2 0 3 3 0 0 0 0 30 PRINT "GIRL","BOY"
0
40 FOR n=1 TO 4
3 0 0 3 0 0 4 0 0 a(5, 6) = 0 therefore a 50 FOR m=1 TO 2
4 1 0 0 0 0 4 0 1 'miss' is recorded 60 READ a$(n,m)
a(2, 6) = 1 therefore a 70 DATA "Anne","Paul","Jane"
5 0 0 2 2 0 4 0 0 'hit' is recorded Robert","Sarah","James","Susan",
6 0 0 0 4 0 0 "Mark"
80 PRINT a$(n,m),
7 0 0 0 3 0 0 0 1
90 NEXT m
8 0 0 3 3 0 0 0 0 100 PRINT
110 NEXT n
Now let us write this part of the program. 120 PRINT
130 PRINT "Examples of what som
TYPE: e elements contain"
230 INPUT "Fire at a ship by en 140 PRINT "a$(1,1)=";a$(1,1)
tering two numbers between 1 and 150 PRINT "a$(3,2)=";a$(3,2)
8.Press ENTER after each number 160 PRINT "a$(4,1)=";a$(4,1)
;x,y 170 STOP
240 IF x<1 OR x>8 OR y<1 OR y>8 RUN
THEN PRINT "Numbers not allowed
GO TO 230 As there are two columns in this array the FOR-NEXT loop `m' operates twice,
250 IF a(x,y)=0 THEN PRINT "You picking up the first two names, every time the loop `n' operates once. Loop `n'
missed": GO TO 230 is performed four times as there are four rows in the array. The names are printed
260 PRINT "You hit a ";s$(a(x,y (line 80) as the loops operate but just to prove that the elements of the array do
))
retain the names throughout the program lines 140 to 160 print three examples.
If you hit a ship all that now remains to be done is to take 1 off the counter `n'
which is storing the number of squares with ships on them. The counter must Activities
then be compared with 0 to see if there are any more ships to sink. Once `n'
equals 0 then the game must be over and all we need is a finishing message. 7. Using the program just used what names are contained in the elements:
a$(1, 2), a$(3, 1) and a$(4, 2)?
TYPE: 8. Using a two-dimensional string array print out in two columns, with headings,
270 LET n=n-1 the information given below.
280 IF n>0 THEN GO TO 230
290 PRINT Name Sport
300 PRINT "Well done,all ships J. Connors Tennis
sunk" Athletics
S. Cram
310 STOP
S. Davis Snooker
Now play the game: hopefully you will not remember too well where the ships Horse racing
L. Piggott
are. Do not look back at any of the diagrams.
F. Bruno Boxing
Finally we need to look at a two-dimensional string array. For example
9. Using a two-dimensional numeric array print in three columns, with headings,
DIM a$ (4, 2, 6) the information below.
T T T Share of world trade (per cent)
Name Number'
of of Year Developed Developing
array columns countries countries
Number Maximum
of length of 1950 68 32
rows strings 1960 79 21
1970 82 18
This is used like a two-dimensional numeric array with nested loops to feed in
the information. Test your programs on the computer.
• • Unit 25: Subroutines 133

MAIN
PROGRAM 0
Unit 25: Subroutines
GOSUB
R
t
MAIN
SUBROUTINE
PROGRAM

GOSUB RETURN

MAIN
PROGRAM

^^^f^i. Therefore, when the computer is sent to another part of the program by a

A^r
GOSUB statement it remembers where it has come from and returns to that
place. Subroutines are usually placed towards the end of the main program.
^^s There is no special word to indicate the beginning of a subroutine, so it is good
^ j°n° ^.üt^\ ^ TT
. ^r^ 20m ^
a I ` Op SuB ^jp '
practice to include a REM statement at that point; this has been done in the
following program.

TYPE:
10 REM Use of subroutines
20 INPUT "Enter your name ";n$
30 PRINT n$
40 GO SUB 200
50 INPUT "Enter first line of
address ";a$
60 INPUT "Enter second line of
address ";b$
70 INPUT "Enter third line of
address ';c$
80 PRINT a$„b$„c$
90 GO SUB 200
As programs tend to get longer there may be several lines of the program that are 100 INPUT "Enter age in years(n
needed more than once. It is not necessary to keep typing in these lines as they umber only) ';a
can be put into a subroutine, or subprogram as it is sometimes called. A sub- 110 PRINT "Age is ";a;” years”
120 GO SUB 200
routine, therefore, consists of several program lines making up one section of the
130 INPUT "Enter date of birth
main program which may be called upon more than once while the program is ";d$
running. To use or call a subroutine the statement GOSUB, on key H, is used. 140 PRINT "Date of birth is ";d
For example
150 GO SUB 200
GOSUB 200 160 STOP
200 REM Subroutine to draw a li
This means go to the subroutine that starts on line 200. When the lines in the ne
subroutine have been executed they must always finish with the statement, 210 FOR j=1 TO 32
220 PRINT "- "; (a dash — not a space)
RETURN, on key Y. This sends the computer back to the place where it has
230 NEXT j
just come from. For example, if GOSUB 200 was line 50 in a program then the 240 PRINT
computer will RETURN to this line and continue with the next line of the 250 RETURN
program. Look at the following illustration:
RUN, entering in the information as necessary.
132
•TV

Beginning BASIC with the ZX Spectrum


• Unit 25: Subroutines
134 135

This program prints out the name, address, age and date of birth of a person but
START
separates each piece of information with a dotted line. As the line is required a
number of times it has been placed in a subroutine beginning at line 200. Line 40
calls the subroutine for the first time, so when it has been executed the computer Input name
returns to this point and continues to line 50. Line 90 calls the subroutine for
the second time and so this time the computer returns to line 90 and continues
to line 100. The subroutine is called twice more, by lines 120 and 150. The STOP
statement, in line 160, is very important because if it was not there the computer
would automatically fall into the subroutine again; on reaching the RETURN
statement it would be confused, as it would not know where to return to since
it was not sent by a GOSUB statement.
Input address:
Delete line 160. a$, b$, c$

RUN
As a result of this an extra line is drawn as the computer falls into the subroutine Print: a$, b$, c$
again but then the error message

7 RETURN without GOSUB, 250: 1 z g


:i-
2
appears. The flowchart of this program shows that the subroutine is drawn as a
Input age: a
separate section.

Input date of birth: d$

Print: d$

The next program is about a machine which is operated by an automatic time


switch; it goes on and off every 5 seconds. The program gives a message that tells
whether the machine is `on' or `off'. The 5-second intervals are controlled by a
FOR-NEXT loop which is written in a subroutine. The main program is executed
five times; this is counted by the variable `c'.
• Unit 25: Subroutines 137
136 Beginning BASIC with the ZX Spectrum

10 INPUT "Enter a number ";n


TYPE:
20 IF n<5 THEN GO TO 40
10 REM Machine on or off 30 GO SUB 70
20 LET c=0 40 LET x=n*n
30 GO SUB 100 50 PRINT x
40 PRINT "MACHINE ON" 60 STOP
50 GO SUB 100 70 REM subroutine
60 PRINT "MACHINE OFF" 80 LET n=n+z
70 LET c=c+1 90 RETURN
80 IF c=5 THEN GO TO 140
Draw a flowchart for this program.
90 GO TO 30
100 REM Subroutine for timing i 4. Write a program that asks the users four questions about their home. The
ntervals question and the answer should be printed on the screen and separated from
110 FOR x=1 TO 900 the next by a row of stars, which are printed out by a subroutine.
120 NEXT x
5. Enter a number between 1 and 100, `n'. If `n' is less than 50 send the computer
130 RETURN
140 STOP to a subroutine where 25 is added to `n'. On returning to the main program
the numbers from 0 to `n' are printed out in steps of five.
RUN 6. Write a program for a number guessing game. Enter a number between 1 and
100 without the player looking. The player should then enter a guess and an
Activity appropriate message should be printed out if they are right. The program
should return to the beginning for another turn. If the guess is too high then
1. Draw a flowchart for the previous program. the computer should go to a subroutine that prints this fact and asks the
player to have another guess. If the guess is too low then the computer should
go to another subroutine that prints this and asks the player to have another
Sometimes a subroutine is called only if certain conditions are true and guess. The main program should form an infinite loop.
ignored if the conditions are not true. The next program is an example of this. 7. A robot has two sets of instructions for opening a wine bottle: one for a
bottle with a cork and another for a bottle with a screw top. Enter the type
TYPE: of bottle the robot is to open and then go to the right set of instructions that
are to be followed. The instructions should be printed on the screen. (Two
10 REM Subroutine used if n is
4 or 7 subroutines will be required, one for each set of instructions.) After the
20 INPUT "Enter a number betwe bottle has been opened the computer should return to the main program and
en 1 and 10 ";n print these messages:
30 IF n=4 OR n=7 THEN GO SUB 1
00 "Bottle opened"
40 LET n=n+2 "Shall I pour a glass?"
50 PRINT n
"Cheers!!"
60 STOP
100 REM Subroutine If the wrong type of bottle top is entered then the computer should print an
110 LET n=n*n
120 RETURN
appropriate message and send the user back to the beginning to enter another
bottle top.
Before you RUN the program try the following question. 8. It takes 0.15 litres of paint to paint one square metre of wall. Write a program
that:
2. What is printed in line 50 when the following numbers are entered: (a) 4,
(a) inputs the number of walls to be painted
(b) 2, (c) 7. Check your answers by running the program.
(b) inputs the length and height of each wall
(c) calculates the area of each wall
Activities (d) calculates the total area of all the walls to be painted
(e) calculates the amount of paint required — total area multiplied by 0.15
3. What is the value of x after this program has been run if: (a) n = 5, (b) n = 2.
138

Beginning BASIC with the ZX Spectrum
• Unit 25: Subroutines 139

(f) prints out the amount of paint required. 120 DATA 0,144,211,122,197,190,
168, 144, 0, 74, 180,203,237, 247, 211
Unfortunately all the measurements for the walls are entered in feet so these ,74,0,254,278,312,321,122,180,25
have to be converted to metres; this is done in a subroutine. The mathemati- 4,0,97,67,73,197,203,278,97,0,73
cal formula required is: ,128,190,237,312,67,73,0,55,168,
247,321,73,128,55,0
number of metres (m) = number of feet (f) divided by 3.208 130 NEXT s
140 NEXT m
In BASIC this is
150 INPUT "Enter city you are t
m = f/3.208 ravelling to ";c$(1)
The following variables should be used: 160 GO SUB 300
170 IF x=0 THEN PRINT "No infor
= litres of paint required to paint one square metre mation about ";c$(1): GO TO 150
n = number of walls to be painted 180 LET y=x
f = length of wall in feet 190 INPUT "Enter city you are t
also used in the subroutine ravelling from ";c$(1)
f = height of wall in feet
200 GO SUB 300
a = area of each wall (1 * h) 210 IF x=0 THEN PRINT "No infor
= total area of all the walls (t + a) mation about ";c$(1): GO TO 190
m = length of wall in metres 220 PRINT "The distance between
to be used in the subroutine ";t$(y);" and ';t$(x); is ';d(
m = height of wall in metres
y,x); miles"
I = length of wall in metres 230 STOP
h =height of wall in metres } to be used in the main program
300 REM Subroutine
p = quantity of paint required (t * r) 310 FOR x=1 TO 7
w = variable to count the number of walls. 320 IF c$(1)=t$(x) THEN RETURN
330 NEXT x
340 LET x=0
350 RETURN
The final example in this unit shows how even the RETURN statement can
be subject to a condition. In line 320 the computer RETURNS to the main RUN the program several times trying different cities.
program only if c$(1) = t$(x). If it does not the computer ignores the RETURN All the techniques used in this program except for the GOSUB and RETURN
statement and carries on through more of the subroutine until it reaches another statements have already been met in previous lessons so study the program
RETURN statement in line 350. carefully and:

TYPE:
Activity
10 REM Distances between citie
s 9. Write an explanation of how the program above works.
20 DIM t$(7,10)
30 DIM d(7,7)
40 DIM c$(1,10)
50 FOR n=1 TO 7
60 READ t$(n)
70 DATA "London","Taunton","Pl
ymouth","Nottingham","Liverpool"
,"Leeds" "Hull"
80 NEXT n
90 FOR m=1 TO 7
100 FOR s=1 TO 7
110 READ d(m, ^ )

^

• Unit 26: Making Music 141

Change line 10

10 FOR n = —30 TO 50

Unit 26: Making music RUN DO NOT REMOVE

It would also be possible to make the computer play alternate notes by altering
the size of the STEP.

Change line 10

10 FOR n = —30 TO 50 STEP 2

RUN. Experiment with this line by altering the size of the STEP.

So far all we have produced is a whole series of notes but we do not know
what notes we are playing. For this we need to look at the piano keys to see
which note has which number. There is not enough space to show all the keys
so the diagram just concentrates on the notes around middle C, the note which
is almost in the centre of the keyboard.

Ob Ev Gb Ab Bb Db Eb Ab Bb Db
Gyyb^^
C# DO F# G# AO Cy
^ D# Fi! G# A# C#

HI —9 —6 —4 —2 1 3 6 8 10 13

B C D E F G A C D E F G A B C D E
? —12 —10 —B —7 —5 —3 —1 0 2 4 5 7 9 II 12 14

As you may already know, the Spectrum has a loudspeaker built into it. This can Middle C
be made to play a single note by using the BEEP statement below key Z (extend- b = flat
ed mode and symbol shift). The program that follows gives you the opportunity = sharp
to hear the loudspeaker play.
TYPE:
As you can see, middle C is 0; all notes above this have positive numbers and all
10 FOR n=50 TO —30 STEP —1 those below have negative numbers. (Positive numbers have a plus sign although
20 BEEP 0.25,n
30 NEXT n
this is not usually written and all negative numbers have a minus sign.)

RUN DO NOT REMOVE


Activity
Look at line 20. BEEP, the command to play a note, is followed by two num-
bers. The first number is the length or duration of the note; the number 1 1. What numbers would the top E and the bottom B, marked on the diagram
represents a note one second long so in this program each note is a quarter of a with question marks, have?
second long (0.25). The second number is the actual note or pitch; this begins
here at 50, which is very high, and finishes at —30, which is very low. So the It is all very well having the numbers on the piano keys but if you are not a
larger the number the higher the note. The whole program plays 80 notes, each musician you may not know where these notes are on a written piece of music.
0.25 second long, going down the scale one note at a time. It would be just as The next diagram should help; it shows the key of C major (no sharps or flats)
easy to play these notes going up the scale. beginning on middle C and ending on the next C up. The scale consists of eight
notes, one octave.
142 Beginning BASIC with the ZX Spectrum
• • Unit 26: Making Music 143

Diagram to show the different lengths of notes

^• •
• • • •
+
C DE F G A BC semiquaver 2 semiquavers make a quaver •^
(0) (2) (4) (5) (7) (9) (11) (12) length 0.25

Scale of C major
(4 of a second) 4 semiquavers make a crotchet
JJJJ

The name of the note is written below the note and the corresponding number
quaver
length 0.5
(2 of a second)
2 quavers make a crotchet ^
for the computer is written in brackets. The following program plays this scale;
each note is half a second long.

J
crotchet 2 crotchets make a minim
TYPE: length 1.0
(1 second)
10 REM Scale of C major
20 BEEP .5,0: BEEP .5,2: BEEP
.5,4: BEEP .5,5: BEEP .5,7: BEEP J
.5,9: BEEP .5,11: BEEP .5,12 minim 2 minims make a semibreve
30 STOP length 2.0
(2 seconds)

RUN DO NOT REMOVE


semibreve
length 4.0
(4 seconds)
Notice that each BEEP statement is separated from the next by a colon (:), as A dot after a note makes it half as long again; for example
each one is a new command.
J•
length 3.0
(3 seconds)

Activities
Return to the program of the scale of C major.
2. Alter the program so that it plays the scale three times. Alter line 20
3. Add a PAUSE statement so that there is an interval of 3 seconds between each
time the scale is played. 20 BEEP .5,0: BEEP .25,2: BEEP
DO NOT REMOVE .5,4: BEEP .25,5: BEEP .5,7: BE
EP .25,9: BEEP .5,11: BEEP .25,1
We are almost ready to play an actual piece of music but as yet we have kept 2
each note the same length, which rarely happens. We now need to know the
length of different notes, so another music lesson is required. See the following RUN DO NOT REMOVE
diagram, which shows the various lengths of notes (there are additional notes to
those detailed in this diagram, but we do not need to know about these at this The program now plays the first note as a quaver, the second note as a semi-
stage). quaver, the third note as a quaver and so on.
144 Beginning BASIC with the ZX Spectrum
• • Unit 26: Making Music 145

Activity The next thing to notice is that one section of the tune is played three times,
bars 1 to 5. These bars are played twice at the beginnin g and then if you look
4. Using the C major scale program: carefully you will see that from the last note of bar 10 to the end of bar 14 is
(a) make all the notes in the scale semiquavers. exactly the same as bars 1 to 5. This means that this section of the tune can be
(b) make the scale play like this put into a subroutine and will therefore only have to be typed in once. We now
need to calculate the length of each note and add this to our computer music.

Bar 1 Bar 2 Bar 3 Bar 4 Bar 5 Bar 6


P 7 12,11,9,7,9 5,7,4,5 7,0,5,4 2,0 7

(c) make the scale play like this D 1 1,•5,•5,1,1 1,1,1,1 1,1,1,1 2,1 1

Bar 7 Bar 8 Bar 9 Bar 10 Bar 11

P 12,9,11,7 12,11,9,11,7 12,11,12,14,12,11 9,7,7 12,11,9,7,9

D 1, 1, 1, 1 1, •5, •5, 1, 1 1, .5, .5, 1, •5, •5 2, 1, 1 1, . 5, •5, 1, 1


We will now try a proper tune - The Vicar of Bra y . It is written in the scale
of C major but uses an extra note, top D, which if you look back at the diagram Bar 12 Bar 13 Bar 14
of the piano keys you will see is number 14. Each bar has been numbered and P = Pitch
P 5,7,4,5 7,0,5,4 2,0
D = Duration (length)
this corresponds to a line in the program. so that you can see what is happening. D 1, 1, 1, 1 1, 1, 1, 1 2, 1
For example. bar 3 is line 230 and bar 9 is line 70. The two dots at the end of
bar 5 mean go back to the beginning.

TYPE:
the Vicar of Bray
7 10 REM The Vicar of Bray
20 GO SUB 200
::J^^ 30 GO SUB 200
Bar 6 4 0 BEEP 1, 7
Bar? 50 BEEP 1,12: BEEP 1,9: BEEP 1
,11: BEEP 1,7
Bar 8 60 BEEP 1,12: BEEP .5,11: BEEP
.5,9: BEEP 1,11: BEEP 1,7
Bar 9 70 BEEP 1,12: BEEP .5,11: BEEP
.5,12: BEEP 1,14: BEEP .5,12: B
Using the diagram of the scale of C major on page 142 we can write out the EEP .5,11
number for each note. Bar 10 80 BEEP 2 , 9 : BEEP 1 , 7 (only two notes as the other G (7)
90 GO SUB 200 is the beginning of the subroutine)
100 STOP
Bar 1
200 REM Subroutine
Bar 2 Bar 3 Bar 4 Bar 5 Bar 6
Bar 1 210 BEEP 1,7
7 12, 1 1, 9, 7, 9 5,7,4,5 7, 0, 5, 4 7
Bars 2 220 BEEP 1,12: BEEP .5,11: BEEP
Repeated .5,9: BEEP 1,7: BEEP 1,9
and 11
Bar 7 Bar 8 Bar 9 Bar 10 Bar 11 Bars 3 230 BEEP 1,5: BEEP 1,7: BEEP 1,
12,9,11,7 12,11,9,11,7 12,11,12,14,12,11 9,7,7 12,11,9,7,9 and 12 4: BEEP 1,5
Bars 4 240 BEEP 1,7: BEEP 1,0: BEEP 1,
Bar 12 Bar 13 Bar 14 and 13 5: BEEP 1,4
5,7,4,5 7,0,5,4 2,0 Bars 5 250 BEEP 2,2: BEEP 1,0
Same as bars 1 to 5 and 14 260 RETURN
146 Beginning BASIC with the ZX Spectrum
• Unit 26: Making Music 147

RUN Good King Wenceslos


•1

The speed of the tune may seem a little slow, this is because we have taken a
crotchet
r
to be one second long for convenience; it should be slightly shorter, probably
:'^_^^.^^^_^ C^.^3^:^
^ ^^-^f ^La^ _`r
/ ^^^^
■^:^^^^

0.8 instead of 1. However, it is simpler to keep the crotchet as 1 as this makes it


much easier to calculate the values of the other notes. Typing in a line of music is rather tedious because of all the BEEP statements
needed. The following program uses READ and DATA statements in a FOR-
Activity
NEXT loop which cuts out all the BEEPs except one!
5. Write a program to play the tune London 's Burning. The music is provided TYPE:
below. Notice that each little phrase is repeated, so to save typing use
10 REM Nursery rhyme
FOR-NEXT loops. 20 FOR n=1 TO 38
30 READ a,b
London's Burning
40 BEEP a,b
wawa) mow wmiE.smiemAl■ w.w.w.m. ^^^1
MI/77M' MMINNI 50 NEXT n
M.s=IMM=M=MMIMM■MT.a..:/MM+MMIMM
0..■•WrMrr. a MUM r lY.MMIMIM. ME■IIMM.JJMMI•++1
. •- -iM..AMMMIMIM.. =M. M■M^.^^^■.^^ 60 DATA 1,0,1,0,1,7,1,7,.5,9,.
5,11,.5,12,.5,9,2,7,1,5,1,5,1,4,
1,4,1,2,1,2,2,0,1,7,.5,7,.5,7,1,
5,.5,5,.5,5,1,4,.5,4,.5,4,1.5,2,
.5,2,1,7,.5,7,.5,7,.25,5,.25,7,.
Let us look at one musical key that uses a sharp (#). Many pieces of music 25,9,.25,5,1,4,.5,2,.5,2,2,0
are written in the key of G major which has F sharp. Any tune written in this key 70 STOP
will look like this:
RUN. Do you know the tune? DO NOT REMOVE
^— key signature
There are 38 notes in the tune so the computer goes round the FOR-NEXT loop
`n' 38 times, playing a different note each time. The READ statement picks up
the first two values from the DATA statement which are 1 and 0, so the first
This key starts and finishes on a G and F# is played instead of an ordinary F. If
note is a crotchet on middle C. The second time round the loop the values I and
you look back to the diagram of the piano keys, you will see that the following
0 are picked up again as these are the third and fourth values in the DATA
numbers would play this scale beginning on the first G below middle C:
statement. The third time round the loop 1 and 7 are picked up. So each time
1 middle C through the loop two values are taken from the DATA statement which make
G A BCDEF#G up one note. This continues until all the DATA have been used.
—5, —3, —1, 0, 2, 4, 6, 7
Add to the program:
Activities 15 FOR m = I TO 2
65 NEXT m
6. (a) Type in a program to play the scale of G major.
RUN. What happens and why?
(b) Write out the numbers for the next octave of the scale beginning on the
first G above middle C. An error message results because the computer has run out of data. The first
(c) Add to your program the second octave of the scale. time round the loop the READ statement uses up all the values in the DATA
7. Write a program for Good King Wenceslas; the music is given on the next page. statement, so the second time round the `m' loop there is no data left. It is
Notice the key signature. Only notes that you used in activity 6 are needed. possible to make the computer play the tune twice which is what we were
Notice that the first four bars are repeated and bars 9 and 15 are also the same. hoping to do. What we want is to put the notes back into the DATA statement.
Can you save yourself some typing? We can do this by using the RESTORE statement above key S (extended mode).
148 Beginning BASIC with the ZX Spectrum Unit 26: Making Music 149

Try this tune: 1,3,2,4,3,5,3,1


Add to the program:
1,3,2,4,3,1
63 RESTORE 1,3,2,4,3,5,3,1
6,2,4,3,1
RUN the program again. DO NOT REMOVE
The only way to stop this program is to press CAPS SHIFT and BREAK.
RESTORE is an instruction that tells the computer to begin READing from the
start of the list of DATA. We can separate the two verses of the rhyme by using
the PAUSE statement. (Remember that PAUSE 50 is 1 second.)

Add to the program:

64 PAUSE 3 * 50

RUN

There is now a 3-second interval between the two verses.

Activity

8. Write a program using READ and DATA statements for four verses of The
Holly and the Iv y , with an interval of 2 seconds between the verses.
The holly and the ivy

r«r ^• =mug- 1■ ^
r^^^r ^^^ A. ^^^M^^
^^^r i ^i ir^^r^^^^^EMIIrT b.
■ s^es^Mo■^^N:^^^MMM^^°
..^^•^r-rrr^^Y^rr-_r^^^^^^^.r
^^•:-:^aW^ r^a^^=rr ^^ — ' ^ ^.
^i^^ – ^^ ^^^^^r

Using the INKEYS function, as we did in unit 23, we can make the key-
board keys act like piano keys. This final program uses the keys 1 to 8 for the
notes of the C major scale beginning with C on key 1, D on key 2 and so on.
The length of the note remains the same so variable `a' is used to store this
number.

TYPE:
10 REM Piano
20 LET a=.25
30 IF INKEY$="1" THEN BEEP a,0
40 IF INKEY$="2" THEN BEEP a,2
50 IF INKEY$="3" THEN BEEP a,4
60 IF INKEY$="4" THEN BEEP a,5
70 IF INKEY$="5" THEN BEEP a,7
80 IF INKEY$="6" THEN BEEP a,9
90 IF INKEY$="7" THEN BEEP a,1

100 IF INKEY$="8" THEN BEEP a,1


2
110 GO TO 30

RUN. Press any of the keys between 1 and 8. If you hold a key down too long
the note just repeats, it does not produce a longer note. Can you play any tunes?
• Unit 27: Some Useful Functions — RND, RAND and INT 151

Now you may be thinking that numbers from 0 to just under 1 are not very
useful and are rarely used, and that normally a much wider range of numbers is
required. We can produce higher numbers by multiplying RND by another

Unit 27: Some useful functions number. For example


6 * RND gives numbers from 0 to 5.999999
— RND, RAND and INT 64 * RND gives numbers from 0 to 63.999999

TYPE:
10 REM Random numbers
Random, abbreviated to RND above key T, is a function of the computer that 20 PRINT "6*RND","64*RND"
produces a mixed selection of numbers from a list of 65536 numbers. In other 30 FOR n=1 TO 10
words it chooses a number or numbers at random from this list. 40 PRINT 6*RND,64*RND
50 NEXT n
TYPE: 60 STOP
RUN the program several times. Notice that the number 6 will never appear in
10 REM Random numbers the first column and the number 64 will never appear in the second column.
20 FOR n=1 TO 10
30 PRINT RND So far all the numbers that have appeared on the screen have looked rather
40 NEXT n complicated because of the figures that have appeared after the decimal point.
50 STOP
Usually we want only whole numbers, so we need a function that will remove
all these unnecessary decimal places. The function that we use is INT, written
RUN. Make a note of the first 3 numbers that appear on the screen.
above key R (extended mode). INT is short for integer which means `whole
DO NOT REMOVE.
number'. INT chops off all the decimal places. For example
The result is a list of ten numbers ranging from 0 to 0.99999999; you will never
INT 1.4809143 becomes 1
get the number 1.
INT 5.9621567 becomes 5
RUN the program again — the list of numbers should be different from the INT 62.5132789 becomes 62
previous one — check the three numbers that you made a note of. Notice that all the numbers are being rounded down, even those that are nearer
Another list of numbers has appeared, once again none of the numbers will to the next highest number; 5.9621567 became 5 although it is nearer to 6. This
be below 0 and none above 0.99999999. The numbers look random enough but also applies to negative numbers. For example
in fact the computer is followin g a set sequence, although it would be difficult
INT —1.2678957 becomes —2
to work this out. However, this means that we can make the computer pick the
INT —10.6723142 becomes —11
same group of numbers every time by making it start at the same point in the
sequence. To do this we use the function RANDOMIZE which is abbreviated on Do not think that these numbers have been rounded up, remember that —2 is
key T to RAND. For example, RAND 35 will start picking numbers from the lower than —1 and —11 is lower than —10.
sequence starting at the 35th number. Look at the number line below to convince yourself that all these numbers
have been rounded down.
Add to the program;
—2 —1 0
15 RAND 35 (notice the whole word is printed)
RUN. Make a note of the first three numbers.
—1.5 —0.3 14
RUN the program again. Check that the numbers are the same.
—2 —1
Having checked your numbers you can see that RAND does fix the starting point
ALL NUMBERS ROUNDED DOWN
of the sequence. If RND is used on its own the computer will just start anywhere
in the list of 65536 numbers.
The next program proves this point.
150
152 Beginning BASIC with the ZX Spectrum Unit 27: Some Useful Functions — RND, RAND and INT 153

TYPE:
TYPE:
10 REM Guessing a number
10 REM Integers 20 LET c=1
20 PRINT INT 5.6 30 LET x=INT (21*RND)
30 PRINT INT 62.9 40 PRINT "Guess the number bet
40 PRINT INT 1.4 ween 0 and 20"
50 PRINT INT -1.2 50 INPUT "Enter a number ";n
60 PRINT INT -10.6
60 IF n=x THEN GO TO 100
70 STOP 70 LET c=c+1
80 PRINT n;" Wrong,try again"
RUN 90 GO TO 50
100 PRINT "Correct,you took ";c
The result is: 5
guesses"
62 110 STOP
1
RUN the program several times.
—2
—11 Line 30 produces a number between 0 and 20 which is then compared with `n',
the number entered in line 50.
Activity
Activity
2. Why was line 30 not written as follows?
1. What are the values of the following:
30 LET x = INT (20 * RND)
(a) INT 4.5 (e) INT —87.1
(b) INT 103.9 (f) INT —0.87
(c) INT 99.1 (g) INT 0.23
(d) INT —5.6 Sometimes in a set of random numbers 0 is not required but the next highest
number is. For example, if the numbers 1 to 6 are required at random, as in a
dice-throwing game, INT (6 * RND) produces 0 to 5 and INT (7 * RND) produces
0 to 6, neither of which is required. To overcome this problem we use
We will now use INT and RND together to give us random whole numbers.
INT (6 * RND) + 1; by adding one the noughts generated become ones and the
TYPE: fives become sixes, giving us the range 1 to 6.
10 REM Random whole numbers TYPE:
20 PRINT "INT (-10*RND)","INT 10 REM Random numbers 1 TO 6
(10*RND)"
20 FOR n=1 TO 10
30 FOR n=1 TO 10 30 PRINT INT (6 *RND)+1
40 PRINT INT (-10*RND),INT (10 40 NEXT n
*RND)
50 STOP
50 NEXT n
60 STOP RUN the program several times, checking that the numbers generated fall only
between 1 and 6.
RUN several times. Notice that 0 can never appear in the first column of negative
numbers and that 10 can never appear in the second column of positive numbers. The next program uses this idea to count the number of times that the
Producing random whole numbers can be useful when writing a games pro- number 3 occurs when a die (the singular of `dice') is thrown a hundred times.
gram. In units 19 and 25 you had to write a guessing-a-number game, where the TYPE:
number to be guessed had to be put into the program while it was running. This 10 REM Throwing a die a 100 ti
game would have been much better if the computer had secretly produced its mes
own number that nobody could see. Using INT and RND we will now improve 20 LET c=0
this game. 30 FOR x=1 TO 10
154 Beginning BASIC with the ZX Spectrum
• •
40 FOR y=1 TO 10
50 LET d=INT (6*RND)+1
60 PRINT d;" "
70 IF d=3 THEN LET c=c+1
80 NEXT y Unit 28: High-resolution graphics
90 PRINT
100 NEXT x — PLOT, DRAW, CIRCLE
110 PRINT
120 PRINT "The number of times and INVERSE
3 appeared was ";c
130 STOP

RUN the program. Check the answer.


DO NOT REMOVE.

No explanation of this program is required as all the other techniques used have
been met before.

Activities

3. Modify the previous program so that users can enter the number they wish
to be counted.
4. Write a program to print a list of 20 random whole numbers between 0 and High-resolution graphics involves the use of pixels. A pixel is a very small dot.
100. Each character position on the screen is made up of eight pixels across and eight
5. Write a program to print a list of 15 random whole numbers between 1 and pixels up the side. The diagram that follows, which has been enlarged, shows the
20. character position 21, 0 divided into 8 x 8 tiny squares - each tiny square is a
6. Write a program to print the same sequence of 10 random whole numbers pixel. Two examples of pixels have been marked in.
from 0 to 10 every time that the program is run.
7. Write a program to print 100 random whole numbers from 1 to 5 in ten 20
columns of ten rows and to record and print how many times each number
occurs. 5 PIXEL 5, 5
8. Write a program to test a person's multiplication tables between 2 and 12. 4
ROWS 21
3
The multiplication sum should be produced at random. The users should be 2
told if they are correct; if they are incorrect, the right answer should be given. PIXEL 3, 1
9. (a) Write a program to throw two dice 50 times and to print out the number 0
of times the total of 7 occurs. 01234567
Rows and pixels 0 1 2
(b) Add another loop so that the program is repeated 5 times and each time numbered in
the total is added to the previous total to give a grand total. The program opposite directions COLUMNS - columns and pixels numbered in the same direction
should finish by printing the average number of times that 7 occurs.
10. Write a program to count the number of times heads and tails occur when a There are 32 (0-31) columns so there are 32 x 8 = 256 pixel positions across
coin is tossed 80 times. Let heads equal 0 and tails equal 1. The result should the screen; these are numbered in the same direction as the columns. There are
be printed. 22 (0-21) rows so there are 22 x 8 = 176 pixel positions up the side of the
screen. These are not numbered like the rows as they begin at 0 at the bottom
of the screen. See diagram 28.1, which can be used as a guide for positioning
pixels. When referring to a pixel `x' and `y' coordinates are used, as for plotting

155
156 Beginning BASIC with the ZX Spectrum
• Unit 28: High-resolution Graphics 157

points on a mathematical graph. 'x' represents the number across the screen, TYPE:
remember 0 is on the left-hand side, and `y' represents the number up the
10 REM Plotting pixels
screen. Remember that 0 is at the bottom of the screen. The 'x' coordinate is 20 INPUT "Enter x coordinate(0
always given first, so the pixels drawn in diagram 28.1 are at 3, 1 and 5, 5. -255) ";x
Obviously the screen is not visibly divided up into tiny squares, so before plot- 30 INPUT ''Enter y coordinate(0
ting pixels and drawing lines it is necessary to use a copy of diagram 28.1. -175) ";Y
r x coordinates 40 PLOT x,y
0 6 16 24 32 40 48 66 fi4 72 80 88 96 104 112 120 128 136 144 152 160 1fi6 176 184 192 200 208 216 224 232 240 249 50 GO TO 20
168 168
160 160 RUN. Enter numbers and watch the pixels being plotted. Notice how small they
152 152
are.
144 144
d 136' 136
If you enter an x coordinate larger than 255 or a y coordinate larger than.
- 128 128 175, the program will crash and the error message
120 120
ö 112 112 B Integer out of range, 40 : 1
.0 104 104
96 96 will appear. To stop this happening add
88 88
ö ° 80 80 33 IF x> 255 THEN LET x = 255
72 72 36 IF y > 175 THEN LET y = 175
N 64 64
.2 56 This prevents the pixels going off the screen.
2 48 48
r 40 40
Notice that you cannot have negative coordinates.
32 32 Enter STOP to stop the program.
24 24
16 16 In the next program the computer plots 200 pixels at random all over the
8 screen; it is rather like a person coming out in measles.
0 0
0 8 16 24 32 40 48 56 64 2 80 86 96 04 12 120 128 136 144 52 60 68 76 164 192 200 206 216 224 232 240 240
(the numbers relate to the pixel to the right of the line)

Diagram 28.1 Diagram to show the numbering of the pixels TYPE:

Activity
10 REM Plotting at random
20 FOR p=1 TO 200
1. Give the x and y coordinates of the pixels drawn below: 30 LET x=INT (256*RND)
40 LET y=INT (176*RND)
50 PLOT x,y
16 60 NEXT p
15 ■ 70 STOP
\
iG •
RUN
• D7*-
8 is
7 •
A V''' F Using PLOT on its own is not very useful unless we are actually drawing a
^ graph but we need to understand the command in order to draw lines. For
r E
0 ■ • example, when we draw a line we need to plot the point where the `pencil' is
0 78 1516 23 24 31 32
going to start. The length and direction of the line is given by adding on the
r x
number of pixels across and up the screen, and by using the command
To place pixels on the screen we use the command PLOT (key Q). DRAW (key W).
^ 158 Beginning BASIC with the ZX Spectrum
• Unit 28: High-resolution Graphics 159

Example I: Drawing a line from A to B TYPE 10 PLOT 100, 50


ICI 20 DRAW 100, 50 (notice that this is not the finishing point of the
255 line which if plotted would be 200, 100)
175 RUN

150

100
Plot 0, 0 is the
B starting point of the Example 3: Drawing a line from E to F
"pencil"
80 pixels up
50
255
175
100 pixels back,
therefore subtract
100 pixels across 150 t
0
0 50 100 150 200 250
PLOT 200, 150 75 pixels down,
TYPE 10 PLOT 0, 0 is the starting therefore
point of the "pencil"
20 DRAW 100, 80 subtract
100
RUN

Example 2: Drawing a line from C to D

255 50
175

150

0
0 50 100 150 200 250

100 0

50
pixels up

50 TYPE: 10 PLOT 200, 150


PLOT 100, 50 is C 100 pixels across
the starting point 20 DRAW —100, —75
of the "pencil" RUN
This program shows that, unlike the PLOT statement, the DRAW statement
0 50 100 150 200 250 does use negative numbers.
160 Beginning BASIC with the ZX Spectrum
• Unit 28: High-resolution Graphics 161

Example 4: Drawing a line from G to H TYPE 10 PLOT 75, 50


20 DRAW 0, 75
255 RUN
175

150 Activity

2. (a) Diagram 28.2 shows a screen with six lines on it, A, B, C, D, E and F.
The arrows on the lines show the direction in which the lines have been
drawn. Write a program that draws these lines in approximately the
100
correct positions.
PLOT 50, 50 (b) Using PRINT AT, label each line so that its letter appears in an appropriate
is the starting point
place (remember with PRINT AT that the rows are numbered differently
of the "pencil"
and that the row and not the column is given first — see unit 23).
125 pixels across
50
LINE FROM G TO H
25 x coordinates

1 down, therefore H 0 B 16 24 32 40 48 56 64 72 90 98 96 104 112 120 128 136 144 152 160 169 176 184 192 200 208 216 224 232 240 248

subtract 168 168

I I 160 160
0
152 152
0 50 100 150 200 250
144 144
136 136
A
TYPE: 10 PLOT 50, 50 128
128
20 DRAW 125, —25 120 120

RUN 112 112


104 104
96 96
Example 5: Drawing a line from J to K 88 88
80 80
255 72 72
175 64 64
> 56 56
^ 48 48
150 c 40
40
32 32
24 24
K 16 16

0 8 8
H 0
100 75 pixels up, 16 24 32 40 48 56 64 72 80 88 96 104 112 120 120 136 144 152 160 1fi8 176 184 192 200 200 216 224 232 240 248

0 but no pixels
cr across Diagram 28.2
^
w
z
^
50 If we want to draw a rectangle it is not necessary to keep plotting the point of
the `pencil' at the beginning of each side. After the first side of the rectangle has
PLOT 75, 50 is the starting point
of the "pencil" been drawn the `pencil' remains at the end of that line, so we can automatically
draw the next side from that point; all we need is another DRAW statement.
The only point to be plotted is right at the beginning when we start the drawing,
0
0 50 100 150 200 250 which is point A on the following diagram:
162
• • Unit 28: High-resolution Graphics 163
150
We can draw any rectangle by putting the necessary information into the
125 program as it is run. The only information required is the starting point of the
'pencil', and the width and the height of the rectangle. The next program enables
100
the user to draw five rectangles.
75
TYPE:
50
10 REM Drawing any rectangle
25 20 FOR n=1 TO 5
30 INPUT "Enter x coordinate "
0
0 50 100 150 200 250 ;x
TYPE: 40 IF x<0 OR x>255 THEN PRINT
"Not acceptable": GO -'O 30
10 REM Rectangle ABCD 50 INPUT "Enter y coordinate "
20 PLOT 50,50 (beginning of drawing — plots pencil point.)
;y
30 DRAW 50,100 (draws AB, pencil now at B) 60 IF y<0 OR y>l75 THEN PRINT
40 DRAW 50,-25 (draws BC, pencil now at C) "Not acceptable": GO TO 50
50 DRAW -50,-100 70 INPUT "Enter wi dth of recta
(draws CD, pencil now at D)
ngle ";w
60 DRAW -50,25 (draws DA, pencil back at A) 80 IF x+w>255 THEN PRINT "Too
70 STOP wide": GO TO 70
RUN 90 INPUT "Enter height of rect
angle ";h
100 IF y+h>175 THEN PRINT "Too
Activity tall": GO TO 90
110 CLS
3. Write programs that draw the shapes given on diagram 28.3. Print the correct 120 PLOT x,y
letter in the centre of each shape. 130 DRAW 0,h
140 DRAW w,0
r x coordinates
i6 24 32 40 48 56 64 72 60 85 95 104 112 120 126 136 144 152 160 168 176 164 192 200 209 216 224 232 240 248
150 DRAW 0,-h
160 DRAW -w,0
168 168
170 NEXT n
160
152
^
I
160
152
180 STOP
144 144
136 136 RUN, putting in the required information.
128 128
120 120 Lines 40 and 60 make certain that the coordinates x and y will fit on to the
112 112 screen. Lines 80 and 100 check that the rectangle will fit on to the screen. For
104 104
96
example, if x is 200 and then the user enters 100 for the width 'w', then
96
88 88 obviously x + w must be greater than 255 and will therefore be off the screen.
S 80
80 Line 110 clears any messages or previous drawings from the screen. The rectangle
72 72
64
is drawn by lines 120 to 160.
64
D 56
> 56
A 48
48
40 40
S 32
32 ^ 44,

24 24
Activities
16 16
8 8
4. Write a program that allows the user to draw different sized isosceles triangles.
2 8 16 24 32 40 46 56 64 72 80 88 96 104 112 120 2B 136 144 152 160 168 176 184 192 200 208 216 229 232 240 246
(An isosceles triangle has two equal sides.) Use the diagram overleaf to help you.
Diagram 28.3 S = start
—r—direction in which shapes
have been drawn in the solutions
164 Beginning BASIC with the ZX Spectrum
• Unit 28: High-resolution Graphics 165

BI x coordinates
8 16 24 32 40 48 56 fi4 72 80 BB 96 104 112 120 128 136 144 152 160 168 176 184 192 200 208 316 224 232 240 246

168 168

1 ^1
AB = BC 160 160

II IIi \
AD = DC 152 152
h = height 144 ^ ^ ^^ ^ ^^ ^ _ 144
w = width 136 136
128 128

uh^
120

Iiii r
120
D —4— 112 112
164
104 ^ _
96 96
The program should check that the triangle will fit on to the screen. Begin , 88
88
the drawing at A. 80
6 80
5. Add a section to your program that asks users whether they would like to draw
triangles or pentagons. If the answer is triangles, then the computer should be
sent to the program that you have just written; if the answer is pentagons, then
ö
72

> 56
64
I
y 1,1 72
64
56

48 48
the computer should be directed to a new section of your program that will 40 I ^ 40
32
do this. The diagram below will help you to write this new section. 32
24
24
C 16
16
8
8
0 0
16 24 32 40 46 56 64 72 BO 88 96 104 112 120 120 136 144 152 160 168 176 104 192 200 208 216 224 232 240 248
AB = DE 0 6

CB = CD Diagra 72 28.4
AF = FE
AB and DE are half the height
h = height 7. Try writing a program for one of the following:
w = width
(a) a picture of your own using only straight lines
or
(b) a pattern using lots of overlapping shapes.
w

Notice that the information required is exactly the same as before (the start- Shading in a shape
ing point, the height and the width), so this part of the program will be
exactly the same as before, and there is no need to write it twice. It is possible to shade or colour in the inner area of a shape. It is easiest to see
6. Write a program that draws the picture shown in diagram 28.4. All the trees this with a rectangle. What we need to do is to draw in all the vertical lines that
are the same size. so they can be drawn by using a FOR-NEXT loop. The exist between the left-hand side and the right-hand side of the rectangle. Look
only different numbers to be entered are the coordinates needed for the at the following diagram:
starting point of the `pencil' for each tree; this information could be placed
in a DATA statement. The trees can each be drawn with one continuous line,
left-hand right-hand
as shown in the diagram below. a edge
edge

finishing point
If these vertical lines are placed closely together they give the impression of
colouring in.
starting point
TYPE:
The houses can be drawn in a similar way, as they are also all the same size. 10 REM Shading in a rectangle
The roads are a little more tricky but they too can be entered by one con- 20 INPUT "Enter x coordinate "
tinuous line, so it is necessary to plot the starting point only once. ;x
166 Beginning BASIC with the ZX Spectrum
• • Unit 28: High-resolution Graphics 167

30 INPUT "Enter y coordinate CIRCLE 120, 88, 20


;y f t f radius of the circle — number of pixels
40 INPUT "Enter width ";w
x and y (distance from the centre to the edge
50 INPUT "Enter height ";h
60 PLOT x,y coordinates of the circle)
70 DRAW 0,h for the
80 DRAW w,0 centre of
90 DRAW 0,-h
the circle
100 DRAW -w,0
110 REM Shading TYPE: 10 CIRCLE 120, 88, 20
120 FOR n=1 TO w-1 (number of vertical lines to be drawn)
130 PLOT x+n,y RUN
(start of `pencil' each time loop is
140 DRAW 0,h-1
executed — x is increased by 1 so the This gives us one circle near the centre of the screen. We can alter this program
150 NEXT n
160 STOP pencil moves across one place) so that the user can draw different sized circles anywhere on the screen, check-
ing at the same time that they will fit on to the screen.

RUN. Be careful to enter suitable numbers as we have deliberately missed out TYPE:
the lines that check the size in order to make the program shorter.
DO NOT REMOVE 10 REM Circles
20 INPUT "Enter x coordinate f
This program produces a black square as the vertical lines are placed so close or centre of circle ";x
together that they touch each other. However, to prove to yourself that the 30 IF x<0 OR x>255 THEN PRINT
shading does consist of vertical lines, try this: "Not acceptable": GO TO 20
40 INPUT "Enter y coordinate
Edit line 120 for centre of circle ";y
120 FOR n = I TOW-1 STEP2
50 IF y<0 OR y>175 THEN PRINT
"Not acceptable": GO TO 40
145 PAUSE 50 60 INPUT "Enter radius of circ
RUN le ";r
70 IF x+r>255 0R x-r<0 THEN PR
You can now see the vertical lines being drawn in. The rectangle could have INT "Off sides": GO TO 60
been shaded in by using horizontal lines beginning at the bottom. 80 IF y+r>175 OR y-r<0 THEN PR
INT "Off top or bottom": GO TO 6
0
90 CLS
100 CIRCLE x,y,r
110 GO TO 20
Activity

8. Try the suggestion made above — edit the previous program rather than RUN. Enter several different numbers, sometimes deliberately entering numbers
rewrite the whole thing. that you know will not be acceptable, and checking that all parts of the program
work. Use diagram 28.1 as a guide.

Drawing circles Drawing curves or arcs

For circles we use the command CIRCLE below key H (extended mode and Curves or arcs are parts of circles. They are not as simple to draw as circles. The
then symbol shift). For example commands PLOT and DRAW are used. For example
Beginning BASIC with the ZX Spectrum
• • Unit 28: High-resolution Graphics 169
168
x coordinates
PLOT 120, 88 — gives the starting point of the `pencil' 0 8 15 24 32 40 48 56 64 72 60 68 96 104 112 120 126 136 144 152 160 168 176 164 192 00 208 216 224 232 260 246

DRAW 64, 48, 2, of arc of circle, measured in radians 168 168


T T — not degrees 160 160
number number 152 152
of of 144 144
pixels pixels 136 136
across up 128 128
120 120
See the diagram below: 112 112
104 104
120 184
9s
96
88 88
v 80 BO
72 72
ö 64 64
angle of arc of circle finishing point !, 56
1 56
measured in radians of curve ^ 48 48
40 40
136 32 32
24 24
16 V K N G 8 H P
16
8 8
48 pixels up
0
0 8 6 24 32 40 48 56 64 72 BO 88 96 104 112 170 126 136 144 152 160 168 176 184 192 200 208 216 224 232 240 248

Diagram 28.5
88
64 pixels across
Rubbing out lines
starting point of
curve We can remove or rub out a line or circle by using the INVERSE command.
PLOT 88, 120
INVERSE (key M — extended mode and then SYMBOL SHIFT) was used to
reverse the ink and paper colours in unit 23 on low-resolution graphics.
TYPE: 10 PLOT 120, 88 INVERSE 0 will produce ink dots in the normal way but INVERSE 1 will
20 DRAW 64, 48, 2 change the ink dots to paper dots (white) and so appear to rub out the ink dots.
RUN
TYPE:
It is difficult to visualise an angle in radians but if you think of 5 radians as
10 REM Rubbing out
being almost equal to 360°, this gives you almost a full circle.
20 PLOT 24,40
TYPE: 10 PLOT 120, 88 30 DRAW INVERSE 0;180,112
40 PAUSE 30
20 DRAW 64, 48, 5
50 DRAW INVERSE 1;-180,-112
RUN 60 CIRCLE INVERSE 0;128,88,50
70 CIRCLE INVERSE 1;128,88,50
You will not find it easy to judge the size and shape of an arc, so it is best just 80 STOP
to experiment with the idea.
RUN

Activity

9. Write a program that draws the picture of the Viking ship shown in diagram
28.5.
• • Unit 29: User-defined Characters 171

Unit 29: User-defined characters

There are 21 characters on the Spectrum that you can alter and make into new Translated into binary numbers this character looks like this:
characters. The keys that can be altered are the letters A to U. As you know,
each character space is made up of 8 x 8 pixels. For example, the letter A can 0 0 0 0 0 0 0. 0
0 1 0 0 0 0 0 1
be made up as in the diagram below:
1 1 1 0 0 1 0 0
0 1 1 1 1 0 1 0
0 1 2 3 4 5 6 7 0 0 1 1 1
1 0 0
7 0 0 1 0 0
1 0 0
6 0 0 1 0 0 1 0 0
5 0 0 0 0 0 0 0 0
4 one character
space We now have to put this into the computer's memory. We use three commands
3
2 for this:
1 POKE (key 0) which means put or poke something into the memory
0
USR (above key L — extended mode) which tells the computer that the
USER is going to make a character
In order for this character to be understood by the computer the white spaces, BIN (above key B — extended mode) which gives the computer binary
known as paper dots, have to be given the value 0 and the black spaces, known numbers that it can understand.
as ink dots, have to be given the value 1. So to the computer the character A The only other thing is to decide which letter between A and U we are going to
looks like this: use for our character. I have chosen D for obvious reasons.

TYPE:
00000000
10 REM Dog
0 0 1 1 1 1 0 0 "D",BIN 00000000
20 POKE USR
0 1 0 0 0 0 1 0 30 POKE USR "D"+1,BIN 01000001
0 1 0 0 0 0 1 0 40 POKE USR "D"+2,BIN 11100010
0 1 1 1 1 1 1 0 50 POKE USR "D"+3,BIN 01111100
0 1 0 0 0 0 1 0 60 POKE USR "D"+4,BIN 00111100
0 1 0 0 0 0 1 0 70 POKE USR "D"+5,BIN 00100100
0 0 0 0 0 0 0 0 80 POKE USR "D"+6,BIN 00100100
90 POKE USR "D"+7,BIN 00000000
100 PRINT "D" Enter 'D' in graphics mode
A mathematician would know that numbers consisting of eight noughts or ones RUN
are binary numbers. We do not need to understand binary arithmetic but the
This program prints one dog. To print many dogs we must alter the program.
word, in its abbreviated form `BIN', will occur in the next program.
To make our own character we need to design the character first. The Edit line 100:
diagram that follows shows a dog!
100 FOR n=1 TO 20

170
17 Beginning BASIC with the ZX Spectrum
• • ^-

Add:
100 FOR n=1 TO 20
110 FOR m=1 TO 15
120 PRINT "D"; ;
130
140
NEXT m
PRINT
Enter 'D' in graphics mode
(dog character will appear)
Unit 30: Some interesting string
150
160
NEXT n
STOP functions
RUN

Points to notice:

1. Letter D is in quotation marks and entered in graphics mode (line 120).


2. Each row in the character is given a number. Therefore the top row is LEN
"D" + 0, but is just written as "D", the second row is "D" + 1, the third
row "D" + 2 and so on. D in these rows is entered in normal letter mode The function LEN, above key K — extended mode, is an abbreviation for length
(lines 20 to 90). and, as the name suggests, calculates the length of strings.
3. In lines 20 to 90 there is a comma before the BIN statement.
TYPE:
10 REM Using LEN
20 LET a$="cat"
Activities 30 PRINT LEN a$
40 LET b$="hippopotamus"
1. Write programs that produce the following characters: 50 PRINT LEN b$
(a) A fat little man 60 LET c$=""
70 PRINT LEN c$
80 STOP
RUN
The result is: 3
12
0
So the PRINT statements in lines 30, 50 and 70 do not operate in the normal
way by printing out the contents of the string variables, aS, b$ and c$, but give
instead the length or number of characters in the string. A string variable con-
(b) A house taining nothing, like c$ in line 60, will return the value 0.
A program can be written to calculate the length of any string that is in a list
of data.

TYPE:
10 REM Length of strings
20 FOR n=1 TO 6
30 READ a$
40 PRINT a$;" has ";LEN a$;" 1
etters"
50 DATA "LEN","ca lculates","th
e" "length","of","s trings"
60 NEXT n
2. Design your own character of a car. Write the program for the character and
70 STOP
then make the car travel across the screen. RUN

173
174 Beginning BASIC with the ZX Spectrum
• • Unit 30: Some Interesting String Functions 175

Activity will give the character at any given number. There are 256 characters in the com-
puter's memory and each one has a code between 0 and 255. There is a complete
1. Write a program where the user can input any eight words, and where the
list of the characters on pages 183-188 of the Spectrum's manual.
word and its length is printed out.
TYPE.
10
20 PRINT CHR$ 37
The next program uses LEN to set the number of times a FOR-NEXT loop 30 PRINT CHR$ 101
will run. It prints out the word that is entered and then prints out the same 40 PRINT CHR$ 135
word by adding one letter at a time until the word is complete. Line 50 uses the 50 PRINT CHR$ 198
technique of extracting parts of strings, met in unit 10. 60 PRINT CHR$ 237
70 STOP
TYPE: RUN
10 REM Printing a word letter
by letter The result is: %
20 INPUT "Enter a word ";a$ e
30 PRINT a$
40 FOR n=1 TO LEN a$
50 PRINT a$(1 TO n) AND
60 PAUSE 50 GO SUB
70 NEXT n You can check in the manual if these are the correct characters for those numbers.
80 STOP
Notice that keywords such as GO SUB are treated as single characters.
RUN. Enter the word `Spectrum'.
TYPE:
The result is: Spectrum 10 FOR n=32 TO 255
S 20 PRINT CHR$ n;
Sp 30 PAUSE 40
40 NEXT n
Spe
50 STOP
Spec
RUN
Spect
Spectr This program produces all the characters from 32 to 255. There . are two points
Spectru to notice:
Spectrum (1) Characters 0 to 31 were not included in the program because they do not
The word 'Spectrum' has eight characters so the FOR-NEXT loop 'n' will run
produce anything printable as they are control characters. Character 32 is a
eight times. Line 50 extracts the part of the string from the first character to the space, so on the screen you have a gap at the beginning of the first row.
'n'th character. The first time round the loop 'n' is 1 so 1 TO 1 is S, the second (2) The upper case letters A to U appear-twice; this is because, on their second
time round the loop 'n' is 2 so 1 TO 2 is Sp. and so on. appearance, they are representing the user-defined characters.
RUN the program again putting in different words. The CODE function (above key I — extended mode) does the opposite to
We can print out words (or sentences or characters) in reverse, in the same CHRS. It will give the number of the character.
way. Modify the previous program: TYPE:
10 REM Using CODE
40 FOR n = LEN aS TO 1 STEP — 1
20 PRINT CODE "A"
50 PRINT a$ (n TO n) 30 PRINT CODE "5"
40 PRINT CODE "INKEY$"
RUN the program again, entering different words or phrases. 50 PRINT CODE " CIRCLE "
CHR$ and CODE
60 PRINT CODE "hello"
70 STOP
The function CHRS (above key U — extended mode), an abbreviation of character, RUN
176 Beginning BASIC with the ZX Spectrum
• •
The result is: 65
96
166
216
104
Unit 31: Using the printer
Again you can check these in the manual if you wish. Notice that for CODE
`hello' the result 104 is the CODE for the letter `h', so if a normal word is used
only the CODE for the first letter is given. CODE `INKEYS' and CODE The ZX Printer is fixed along the edge connector at the back of the computer.,It
`CIRCLE' produce the CODE for the whole word as they are keywords. should not be attached or detached while the computer is on. The keywords
LPRINT, LLIST and COPY are used in connection with the printer.

VAL (not to be confused with VAL$)


LPRINT (above key C — extended mode)
The function VAL (above key J — extended mode), an abbreviation for
evaluate, can change a string to a number. TYPE: 10 LPRINT "The result of this program will be printed on paper"
20 LPRINT "The result will not appear on the screen"
TYPE: RUN DO NOT REMOVE
10 REM Using VAL
20 LET a$="1+2+3+4" The result is exactly as stated in the program so if for any reason you only want
30 PRINT a$ the result on paper then use LPRINT instead of PRINT.
40 PRINT VAL a$
50 LET b$="10*10"
60 PRINT b$
70 PRINT VAL b$ LLIST (above key V — extended mode)
80 STOP
RUN Add to the program
Lines 30 and 60 print out the contents of a$ and b$ in the normal way, but the 30 LLIST
VAL function in lines 40 and 70 makes the computer treat the contents of the
string variables as numbers. Therefore VAL a$ gives the value of 1 + 2 + 3 + 4 RUN REMOVE PROGRAM
and VAL b$ gives the value of 10 * 10. In response to LLIST the computer produces a list of the program on the paper.

TYPE: 10 PRINT "The result of this program will appear on the screen"
20 PRINT "A list of this program will also be printed out on paper"
30 LLIST
RUN DO NOT REMOVE

Now the result is printed on the screen and the program list on the paper.

COPY (keyword on key Z)

Change lines 20 and 30

20 PRINT "and will also be printed on paper"


30 COPY
RUN

177
17

Beginning BASIC with the ZX Spectrum

Solutions 3.
10 LET a$="Robert"
20 LET bS="Jane"
This time the result of the program is on the screen and on the paper. When 30 LET c$="London"
using COPY the printer runs on, unnecessarily wasting valuable paper; this can 40 LET d$="Liverpool"
50 PRINT a$;" lives in ";c$
be stopped by pressing CAPS SHIFT and BREAK. 60 PRINT b$;" lives in ";d$
It is possible to purchase special connectors (called interfaces) which allow Unit 3
the Spectrum to be connected to a wide variety of alternative printers. They are 1. 4-
usually accompanied by a short computer program which has to be loaded into 10 PRINT "Mr.J.Brown" 10 LET n$="Ralph"
20 PRINT "51,Bedford Square" 20 LET d$="12th September"
the computer in order to `translate' the signals before sending them to the 30 PRINT "LONDON" 30 LET w$="Saturday"
printer. In this way, quite sophisticated results can be obtained if a daisy-wheel 40 PRINT "W.C.l." 40 LET t$="8 o'clock"
printer or high-quality dot-matrix printer is used. You should decide on the 50 PRINT "Dear ";n$
60 PRINT " Please c
make of printer you require, and then check that an interface can be obtained, 2. ome to a party on" ;w$; " the ";d
10 PRINT "My name is Mary Jone $; at ";t$
before purchasing anything. 5" 70 PRINT " love f
20 PRINT "My age is 21 years" rom"
30 PRINT "My date of birth is 80 PRINT " Sall
2nd May 1962"
v"

3.
10 PRINT "There are five peopl 5.
e in my family" 10 LET a$="James"
20 PRINT "I have one brother a 20 LET b$=" Harriot"
nd one sister" 30 PRINT a$+b$
30 PRINT "My sisters name is
Janette"
40 PRINT "My brother s name is
Keith" - 6.
50 PRINT "My parents live in L 10 LET a$="Wall"
ondon" 20 LET b$="ing"
30 LET c$="ton"
40 PRINT a$+b$+c$
Unit 8
1. 2. 3.
32 72 a) ABC f) Abc 7.
32 dogs c) abc i) A2B2C 10 LET a$="THE"
y 53 20 LET b$="GREEDY"
d) Two ABC j) a b c
30 LET c$="BOY"
40 LET d$="ATE"
50 LET eS="MANY"
60 LET f$="CREAM"
70 LET gS="BUNS"
80 LET h$="AND"
Unit 9 90 LET i$="JAM"
100 LET j$="TARTS"
1. 110 PRINT a$;" ";c$;" ";d$;" ";
10 LET a$="John" g$
20 LET s$="school" 120 PRINT a$;" ";b$;" ";c$;" ";
30 PRINT a$;" goes to ";s$ d$;" ;e$; ;j$
130 PRINT a$; ;c$;" ";d$;"
f$; ";j$

2.
10 LET m$="Mary"
20 LET a$="Anne"
30 LET b$="12 years" Unit 10
40 LET c$="13 years"
50 PRINT m$;" is ";b$;" old" 1.
60 PRINT a$;" is ;c$;" old" 30 PRINT b$;" ";p$

179
180 Beginning BASIC with the ZX Spectrum
• •
Solutions 181

2. b) 11. Unit 12
60 PRINT p$(5 TO 6)+b$(4) 10 LET s=65
70 PRINT p$(1 TO 2)+b$(5) A B C 20 LET t=6 1.
80 PRINT b$(2)+p$(3)+b$(4) 30 PRINT "Speed of car is ";s; 10 PRINT "
90 PRINT p$(1)+b$(2)+b$(5) 20 " miles per hour"
100 PRINT b$(5)+b$(4)+p$(1 TO 3 40 PRINT "Time spent travellin 20 PRINT "DAY";TAB 10;"TEMPERA
g is ";t;" hours" TURE";TAB 23;"RAINFALL"
50 PRINT "Length of journey is 30 PRINT TAB 10;"DEGREES C";TA
20 60 ";s*t;" miles" B 23;"INCHES"
40 PRINT "
3.
10 LET a$ = "ladle" 50 PRINT "Monday";TAB 13;"•10";
20 LET b$ = "spoon" 20 60 5 TAB 25;"0.2"
30 PRINT b$(2)+a$(2 TO 3)+a$(3 12. 60 PRINT "Tuesday";TAB 13;"11"
TO 5) 10 LET a=21 ;TAB 25;"0.4"
40 PRINT a$(1 TO 2)+b$(2) 20 70 PRINT "Wednesday";TAB 13;"1
100 5 20 LET w=10
30 LET h=160 3";TAB 25;"0.6"
40 LET s=5 80 PRINT "Thursday";TAB 13;"11
50 PRINT "I am ";a;" years old ";TAB 25;"1.0"
and I weigh ";w;" stone.I am 90 PRINT "Friday";TAB 13;"6";T
7. h;" centimetres tall and take si AB 25;"0"
10 LET a=71
20 LET b=3 (any numbers here) ze ;s; shoes"
Unit 11
30 PRINT a+b
1 40 PRINT a-b
a) 3+7 d) 5*2+8 g) 5*6*7 50 PRINT a*b Unit 14
b) 3*7 e) 24-4*3 h) 81-27/2 60 PRINT a/b 13.
c) 8/4 f) 30/3+2 i) 23/2*9 10 LET a=21 ages of 1.
20 LET j=26 Ichildren 10 REM Numbers
30 LET k=43 20 INPUT "Enter a number ";n
2. 40 LET m=65 mother 30 PRINT n
8.
a) 17 c) 100 e) 5 10 LET 1=35 50 LET f=72 father 40 INPUT "Enter a second numbe
b) 200 d) 25 f) 3 20 LET b=16 60 PRINT "The sum of the ages r ";n2
30 PRINT "The area of the rect of my family is ";a+j+k+m+f 50 PRINT n2
angle is ";1*b;" sq cm" 70 PRINT "The average age of m 60 INPUT "Enter a third number
3. 40 PRINT "The perimeter of the y family is ";(a+j+k+m+f)/5 ";n3
a) 26 b) 13 c) 8 d) 1 rectangle is ";l+l+b+b 70 PRINT n3
80 INPUT "Enter a fourth numbe
r ";n4
4. 90 PRINT n4
a) 14 c) 4 e) 15 9. 14. 100 LET s=n+n2+n3+n4
b) 20 d) 24 f) 12 10 LET xS="Mr Blake" 10 LET 1=1154 110 PRINT "Sum of numbers=";s
20 LET b=93 20 LET j=19 120 LET a=s/4
30 LET c=9 30 PRINT "The amount of sand c 130 PRINT "Avera g e of numbers="
5. 40 PRINT "A bag of cement cost arried by a lorry in four weeks ;a
a) 17 c) 50 e) 7 s ";b;" pence" is ";1*j;" kilograms" 140 STOP
b) 3 d) 5 f) 20 50 PRINT x$;" ordered ";c;" ba 40 PRINT "The amount carried i
gs" n 48 weeks is ";1*j*48/4;" kilog
60 PRINT "The cost of ";c;" ba rams"
6. gs is ";b*c;" pence" 2.
a) 10 REM Letter for interview
20 INPUT "Enter name of intery
15. iewee ";n$
A 10. 10 LET b=44 30 INPUT "Enter date of intery
B C 10 LET a$="Susan Smith" 20 LET m=22 iew ";d$
12 20 LET bS="John Brown" 30 LET ba=104 40 INPUT "Enter time of intery
30 LET c$ = "Mary Turner" 40 PRINT "The price of three 1 iew ";t$
40 LET a=43 oaves is ;3*b; pence" 50 INPUT "Enter place of inter
50 LET b=68 50 PRINT "The price of 5 pints view ";p$
12 5 60 LET c=73 of milk is ";5*m ;" pence" 60 INPUT "Enter name of intery
70 PRINT a$;" gained ";a;" mar 60 PRINT "The price of half a iewer ";m$
ks' pound of bacon is ";ba/2;" pence 70 INPUT "Enter the name of th
12 80 PRINT b$;" gained ";b;" mar e person who is sending this let
5 60
ks" 70 PRINT "The total cost of th ter ";s$
90 PRINT c$;" g ained ";c;" mar e purchases is ";3*b+5*m+ba/2;" 80 INPUT "Enter date of letter
ks' pence" ;1$
55 5 60 100 PRINT "The average mark was 90 PRINT TAB 18;"Cogland Ltd"
";(a+b+c)/3 100 PRINT TAB 20;"Machine Rd"
182 Beginning BASIC with the ZX Spectrum
• • Solutions 183

10 REM Area of triangles 3. c) Variable:


110 PRINT TAB 22;"Manchester" 70 INPUT "Age of third girl "; 20 INPUT "Enter base of triang w$ = word of at least 7 letters
120 PRINT TAB 18;1$ c (elephant)
le ;b
130 PRINT "Dear ";n$ 80 PRINT "NAME","AGE" 30 INPUT "Enter height of tria
140 PRINT TAB 15;"Thank you for 90 PRINT n$,a ngle ";h Flowchart
your application for the vacanc 100 PRINT g$,b 40 LET a=b/2*h
y at our office.Please would you 110 PRINT h$,c 50 PRINT "The area of the tria
120 STOP (START)
attend an interview on ";d$;" a ngle is ";a;" sq cm"
t ";t$; 60 STOP
150 PRINT " The interview will
take place at ";p$; " and will be / Enter word: wS /
conducted by ";m$ 2. Flowchart 3. b) Variables:
160 PRINT TAB 15;"Yours sincere n$ = name of first person
ly, s$ name of second person
170 PRINT TAB 18;s$ t$ = name of third person Print: w$ 14) + w$ 16 TO 8)
180 STOP d$ = first date of birth Print: w$ )2 TO 3) + w$161+
START) a$ = second date of birth w$ )4)
( Print: w$ 15 TO 6) + w$ 18)
y$ = third date of birth
3. I
10 REM Saving money Enter name of book: n$ Flowchart 4
author of book: a$

/
20 INPUT "Enter the amount of STOP)
money you wish to save ";s price of book: p (
30 INPUT "Enter the amount you date of publication: d (START)
can save each week ;w 10 REM Words
40 LET n=s/w 20 INPUT "Enter a word of at 1
1 east seven letters ";w$
50 PRINT "The number of weeks /Print:n$, a / Enter name of first person: n$ 30 PRINT w$(4)+w$(6 TO 8)
it will take to save 6";s;" is "
;n
60 PRINT "The number of months
it will take to save £";s;" is
P
d
i
/ name of second person: s$
name of third person: t$
40 PRINT w$(2 TO 3)+w$(6)+w$(4
50 PRINT w$(5 TO 6)+w$(8)
60 STOP
;n/4 /Enter dates of birth
70 STOP STOP)
( first person: d$ 3. d) Variables:
second person: a$ a$ = name of first town
third person: y$ b$ = name of second town
Unit 15 c$ = name of third town
10 REM Book and Author a = population of first town
20 INPUT "Name of book? ";n$ b = population of second town
1. Flowchart 30 INPUT "Author of book? ";a$ Print: NAME DATE OF c = population of third town
40 INPUT "Price of book? ";p BIRTH t = total population
50 INPUT "Date of publication? n$ d$
a
s$ a$ Flowchart
(START) ";d (STAR-1)
60
PRINT n$;" by ";a$ t$ y$
PRINT "Price of book £";p
70
80 PRINT "Date of publication
Enter first name: n$, age: a

/ ";d l Enter names of towns:


Enter second name: g$, age: b STO P J a$, b$, c$
90 STOP (
Enter third name: h$, age: c
3. a) Variables:
T b = base of triangle 10 REM Names and dates of birt Enter populations of towns:
Print: n$, a h = height of triangle h a, b, c

/ g$,
h$, c
a = area of triangle

Flowchart
n
20 INPUT "Name of first person
";n$
30 INPUT "Name of second perso
;s$
LETt =a+b+c
( STOP ) 40 INPUT "Name of third person
;t$
50 INPUT "Date of birth of fir Print: TOWN POPULATION
10 REM Names and ages Enter base of triangle b/ a$ a
20
;n$
INPUT "Name of first girl " / height of triangle: h
st person ";d$
60 INPUT "Date of birth of sec
and person ";a$
b$
c$
b

30 INPUT "Age of first girl ', i 70 INPUT "Date of birth of thi


a Calculate area of rd person ";y$
40 INPUT "Name of second girl triangle 80 PRINT "NAME","DATE OF BIRTH
LET a =1b/2) * h / Print: t /
;g$
50 INPUT "Age of second girl " 90 PRINT n$,d$
;b 1 100 PRINT s$,a$
60 INPUT "Name of third girl " (STOP ) 110 PRINT t$,y$ ( STOP)
;h$ 120 STOP
184 Beginning BASIC with the ZX Spectrum
• • Solutions 185

10 REM Towns and populations 10 REM Feet into centimetres 10 REM Girl ' s shopping 30 LET s2=623.65
20 INPUT " Name of first town 20 INPUT "Enter length in feet 20 LET a=95 40 LET s3=127.84
;a$ ;1 30 LET s=26 50 LET t=sl+s2+s3
30 INPUT "Name of second town 30 LET c=30.5 40 LET d=44 60 PRINT "Total saved and tran
;b$ 40 LET t=1*c 50 LET p=16 sferred to one account is E";t
40 INPUT "Name of third town " 50 PRINT 1;" feet is " ;t; " cm" 60 LET t=s+d+p 70 INPUT "Enter amount to be s
;c$ 60 STOP 70 LET 1=a-t awed this month ";m
50 INPUT "Population of first 80 PRINT "Amount of money to s 80 INPUT "Enter date ";d$
town ;a Flowchart pend =E " ; a 90 PRINT "DATE";TAB 12;"MONTHL
60 INPUT " Population of second 90 PRINT Y";TAB 23;"TOTAL"
100 PRINT "ITEM","COST" 100 PRINT TAB 12;"SAVINGS";TAB
town ;b 23;"SAVED"
70 INPUT " Population of third 110 PRINT "skirt",s
town. ";c 120 PRINT "dress",d 110 LET t=t+m
130 PRINT "shoes",p 120 PRINT dS;TAB 12;m;TAB 23;t
80 LET t=a+b+c /Enter length in feet: 1/ 130 PRINT
90 PRINT "TOWN","POPULATION" 140 PRINT
100 PRINT a$,a 150 PRINT 140 GO TO 70
110 PRINT b$,b 160 PRINT "Total cost of items=
120 PRINT c$,c LET c = 30.5 E';t Flowchart
130 PRINT 170 PRINT
140 PRINT "The total population 180 PRINT "Amount of money left
is ";t =E";1 (START
150 STOP LETt=1.c 190 STOP

LET s1 = 381.2
3. e) Variables: / P nt: t / LET s2 = 623.65
m = number of marbles Unit 16 LET s3 = 127.84
f = number of friends
= total of marbles each 1.
friend receives ( STOP)
LETt= s1+s2 +s3
Flowchart Flowchart
3. g) Variables:
a = amount to spend
s = price of skirt Print: t
d = price of dress (START)
p = price of shoes
t = amount spent / Enter amount to be saved: m
LET m = 216
1 = amount left / Print: The Spectrum is/ date: d$
the greatest
LET f = 12
Flowchart /P r int: DATE MONTHLY TOTAL
/ Print: worst / SAVINGS SAVED
LET t = m/f
(START)
JJl
LETt =t - m
/ Print: greatest / •
LET a=95
LET S =26
LET d= 44 Print: d$, m, t
( STOP) /Print: co mputer/
LET p= 16

Print: new line


10 REM Sharing marbles LETt =s+d+p ( STOP)
20 LET m=216 LETI =a– t
30 LET f=12
40 LET t=m/f 2.
50 PRINT " The number of marble Print: a 10 REM Adding numbers
s that each friend receives is " 20 INPUT "Enter a number ";n
;t 30 INPUT "Enter another number Unit 17
60 STOP ;n2
Print: ITEM COST 40 LET t=n+n2
Skirt s 50 PRINT n;"+";n2;"= ;t
Dress d
Question.
60 GO TO 20 Why was it possible to use the
3. f) Variables: Shoes p
command PRINT in the middle of
1 = len g th in feet lines 40 & 50?
c = number of centimetres 3.
10 REM Savings account Why did not the letter 'P"
in a foot ( STOP ) appear?
t = length in centimetres 20 LET s1=381.20
186 Beginning BASIC with the ZX Spectrum
• • Solutions 187

Answer. 3. 6. Unit 18
After the word THEN the cursor 10 REM Testing multiplication
automatically changes from an tables 1.
L to a K, so the computer 20 INPUT "Enter a number betwe a) no f) yes k) yes P) yes
automatically goes back into en 2 and 12 ";n b) yes a) no 1) no c) no
keyword mode - which means 30 INPUT "Enter a second numbe c) yes h) yes m) yes r) no
that another keyword, such as LET x = 75 r between 2 and 12 ";n2 d) yes i) no n) yes s) no
PRINT, can be entered. LET y = 53 40 PRINT n;"*";n2;"= ; e) yes j) yes o) no t) yes
50 INPUT "Enter an answer ";a
60 PRINT a
70 IF a=n*n2 THEN GO TO 100
80 PRINT "No,try again"
1. 90 GO TO 50
100 PRINT "Correct,would you 1i 2.
Flowchart ke another turn?" a) 16 < 23
110 INPUT "Enter yes or no ";y$ b) 14 > 10
120 IF y$= " yes " THEN GO TO 20 c) 10 <= 10 or 10 >= 10
130 PRINT "O.K-goodbye" d) 5 + 6 > 11 - 3
140 STOP e) 3 * 7 >= 13 + 8
(STA RT) or

i
TART 3* 7 <= 13 + 8
(S J f) x < y
/ Print: Do you like cakes and biscuits?/ g) x / 2 < y + 4
h) x * x > y / 2
Enter a number : n i) (a+b) * 3 > a + b * 3
/Enter yes or no: a$
/ Enter another number: n2 J) a+ b— c> a + c— 10

/ Print: No, the answer is x — y

3.
1. /Enter an a nswer: a / 10 REM Which number is bigger
20 INPUT "Enter a number ";x
30 INPUT "Enter a second numbe
TRUE r ;y
10 REM Subtracting numbers
20 LET x=75 40 IF x>y THEN GO TO 70
30 LET y=63 50 PRINT y;" is bigger than ",
40 PRINT x;"-";y;"=";
50 INPUT "Enter an answer ";a 60 STOP
YES 70 PRINT x;" is bigger than ",
60 PRINT a
70 IF a=x-y THEN PRINT "Correc y
t": GO TO 90 80 STOP
80 PRINT "No,the answer is ";x
—y
90 STOP

4. 4
10 REM Colour of my eyes
Print: Correct, would 10 REM if x is greater or equa
20 LET b$="blue"
30 INPUT "Guess the colour of
my eyes ;e$
/ you like another turn? 1 to 10
20 INPUT "Enter a number ";x
30 IF x>=10 THEN GO TO 70
40 IF b$=e$ THEN PRINT "Yes,yo 40 LET y=x+10
u are right": GO TO 60 /Enter Yes or no 50 PRINT y
50 PRINT "No,you are wrong"
60 STOP
60 STOP 70 LET w=x-10
80 PRINT w
5. YES 90 STOP
10 REM Guessing my age 10 REM Names of towns
20 PRINT "What is my age?" 20 PRINT "TOWNS IN GT.BRITAIN"
30 INPUT "Enter a number ";a 30 INPUT "Enter the name of a
40 PRINT a town in Gt.Britain ";t$
50 IF a=21 THEN GO TO 80 40 IF t$="Timbuktu" THEN GO TO
60 PRINT "Wrong" 70 /Print: O.K. goodbye
70 STOP 50 PRINT t$
80 PRINT "Correct" 60 GO TO 30
90 STOP 70 STOP
( STOP)
188

Beginning BASIC with the ZX Spectrum
• Solutions 189

5. 10 REM Which century 8. Variable: 9. Variables:


20 INPUT "Enter the number of s = boy ' s salary p = price of petrol
the year ";y k = distance travelled on
30 IF y>=2000 THEN GO TO 60 Flowchart 1 litre of petrol
40 PRINT "This century" d distance travelled
50 GO TO 70 a amount of petrol
60 PRINT "Next century" c = cost of petrol
70 STOP

/ Print: value of goods sold


by salesman in a week
7. Variables:
Flowchart

x = one number START


y = second number
t = x * y
LET p 45
LET k = 14
Flowchart

/Enter amount of petrol


/Ente
into tank: a

TRUE /Print: Too much/


petrol in tank
/ Print: No bonus added
Final salary is: s
/ Let c=axp/100

/ Print: c /

/ Print: Bonus added. /


Final salary is: s
10 REM Boy ' s salary
20 INPUT "Enter boy ' s salary " /LET d = a /
;s
(STOP) 30 IF s<50 THEN LET s=s+10: GO
TO 50
. Variable: 40 IF s>=70 THEN LET s=s-15
= year to be entered 50 PRINT "Boy ' s weekly salary
is E";s
Flowchart 60 STOP

FALSE
/Print: Holiday in Dorset/

( STOP

10 REM Greater or less than 81


20 INPUT "Enter a number ";x
30 INPUT "Enter a second numbe 10 REM Distance travelled
r ;y 20 LET' p=45
40 LET t=x*y 30 LET k=14
50 IF t>81 THEN GO TO 110 40 INPUT "Enter amount of petr
60 IF t<81 THEN GO TO 90 of put into tank ";a
70 PRINT "Just right" 50 IF a>33 THEN PRINT "Too muc
80 GO TO 120 h petrol in tank": GO TO 40
90 PRINT "Too little" 60 LET c=a*p
100 GO TO 120 70 PRINT "The cost of petrol b
110 PRINT "Too great" ought is L";c/100
120 STOP 80 LET d=a*k
190 Beginning BASIC with the ZX Spectrum
• • Solutions 191

90 PRINT "The distance that ca 10 REM Baking bread 11. Variables: 10 REM Milkman ' s round
n be travelled on ;a; litres o 20 LET b=15 a = number of pints to the 18 20 LET a=18*3
f petrol is ";d;" kilometres" 30 LET t=52 families which take 3 pints a 30 LET b=17*2
100 IF d>=380 THEN PRINT "The m 40 LET n=b*4 day 40 LET c=9*4
an takes his holiday in Cornwall 50 PRINT "The number of loaves b = number of pints to the 17 50 INPUT "Enter number of pint
GO TO 120 baked is ":n families which take 2 pints a s taken by other 15 families ";d
110 PRINT "The man takes his ho 60 LET t2=t*4/60 day 60 LET e=15*d
liday in Dorset" 70 PRINT "Time taken to bake a c = number of pints to the 9 70 LET t=a+b+c+e
120 STOP 11 the loaves is ";t2;" hours" families which take 4 pints a 80 LET crate=t/12
80 PRINT "The number of loaves day 90 PRINT "The number of pints
sold is ' d = number of pints taken by the delivered in a day is ";t;" whic
10. Variables: 90 INPUT "Enter number ";s other 15 families h means that the milkman will ne
b = number of loaves held 100 PRINT s e = number of pints taken by the ed ";crate;" crates"
by oven 110 IF s=n THEN PRINT "Bake mor other 15 families at ' d ' pints a 100 IF crate>13 THEN PRINT "Bac
t = time taken to bake 15 loaves e bread" day k to depot": GO TO 120
n = number of loaves baked in 120 STOP crate = no.of crates required 110 PRINT "Go home"
a day 120 STOP
t2= time taken to bake all
loaves Flowchart
s = number of loaves sold
12.
a) 30 b) 40 c) 140 d) 30
Flowchart 50 400 100

(START) 13.
10 REM Number compared to 100
20 INPUT "Enter a number ";n
LET a=18"3 30 IF n>=100 AND n<=200 THEN P
LET b = 15 LET b= 17.2 RINT "Number between 100 and 200
LET 52 LET c=9"4 GO TO 50
40 PRINT "Number not between 1
00 and 200"
LET n = b 4 nu mbe r 5 pints
Enter 50 STOP
/ by oth er 15
by
t a ke n d
14.
/ The number of loaves baked
Print: n LET e = 15 • d a) 80 b) 180 c) 160

15.
LET t2= 4/60 LET t=a+b+c+e a) Teenager d) Child
b) Adult e) Teenager
c) Teenager
Print: Time taken to bake
all the loaves: t2 LET crate = t/12
16.
Print: The number of loaves Print: The number of pints a) No walk today
sold delivered in a day is: t: b) No walk today
which means that the c) No walk today
milkman will need: crate: d) Lets go for a walk
Input: s crates.

Print: s
Print Back to depo

TRUE FALSE
Print: Bake more bread /
/Print: Go home /

( STOP) 1
192 Beginning BASIC with the ZX Spectrum
• • Solutions 193

Unit 19 2. f)-10 5.
10 REM Flowers Stepping up 10 FOR x=13 TO 23
1. 20 PRINT "FLOWERS" —5 20 PRINT x
10 REM Flowers 30 LET c=0 Stepping up 30 NEXT x
20 PRINT "FLOWERS" 35 INPUT "Enter the number of 0
30 LET c=0 flowers to be listed ";n Stepping up
40 INPUT "Enter the name of a 40 INPUT "Enter the name of a 5 6.
flower ";f$ flower ";f$ Stepping up 10 FOR x=3 TO 37 STEP 2
50 PRINT ft 50 PRINT f$ 10 20 PRINT x
60 LET c=c+1 60 LET c=c+1 Stepping up 30 NEXT x
70 IF c=6 THEN GO TO 90 70 IF c=n THEN GO TO 90 15
80 GO TO 40 80 GO TO 40 Stepping up
90 STOP 90 STOP 20 7.
Stepping up 10 FOR x=5 TO 35 STEP 5
25 20 PRINT x
3. Stepping up
Flowchart 30 NEXT x

10 REM Guessing a number


(START 3.
20 PRINT "CLOSE YOUR EYE WHILE 8.
THE NUMBER TO BE GUESSED IS ENT a) 10 FOR x = 1 TO 10
20 PRINT x 10 FOR x=10 TO -6 STEP -2
ERED" 30 NEXT x 20 PRINT x
Print: close your eyes 30 INPUT "Enter a number betwe 30 NEXT x
while the number to be en 0 and 20";n
guessed is entered 40 LET s=0
50 INPUT "Enter a guess betwee
n 0 and 20 ";g b) 10 FOR x = 10 TO 1 STEP -1
20 PRINT x 9.
Enter the number to be 60 LET s=s+l 10 REM 7 TIMES TABLE

/ 70 PRINT g 30 NEXT x
guessed between 0 and 20 FOR x=1 TO 12
20: n 80 IF g=n THEN GO TO 110 30 PRINT x;"*";7;"=";x*7
90 PRINT "You are wrong" 40 NEXT x
100 GO TO 50 c) 10 FOR x = 1 TO 6 STEP 2
110 PRINT "You are right.You to 20 PRINT x
LET s = 0 ok ";s;" guesses" 30 NEXT x
120 STOP 10.
10 PRINT "I " m on the top line"
d) 10 FOR x = n TO 10 20 FOR x=1 TO 5
Enter a guess: g 20 PRINT x 30 PRINT
30 NEXT x 40 NEXT x
Unit 20 50 PRINT "I ' m five lines furth
er down"
1. e) 10 FOR x = 1 TO n 60 FOR x=1 TO 5
all b)4 c) Goodbye 20 PRINT x 70 PRINT
2 5 Goodbye 30 NEXT x 80 NEXT x
3 6 Goodbye 90 PRINT "I " m another five lin
4 7 Goodbye es further down"
5 8 f) 10 FOR x = 1 TO 10 100 STOP
6 9 20 PRINT x
TRUE 7 10 dl 1 30 NEXT x
8 11 This is a loop 11.
9 12 2 10 FOR x=1 TO 8
10 13 This is a loop 20 PRINT "Spectrum"
11 14 3 4. 30 NEXT x
12 15 This is a loop a) 2 6 b) 10 12
16 3 7 12 14
4 8 14 16
2. 16 18 12.
Print: you are right. You
a)2 b)15 c) 0 d.)50 e)-2 10 REM Leap years
took: s: guesses 4 19 20 25 -5 c) 12 10 20 FOR x=1904 TO 1984 STEP 4
6 23 40 0 -8 30 PRINT x
9 10
60 8 -25 -11 6 10 40 NEXT x
10 80 3 10 50 STOP
12 100
d) 100 90 110
125 115 135 13.
150 140 160 10 FOR x=10 TO 20
175 165 185 20 PRINT x,x+3
200 190 210 30 NEXT x
194 Beginning BASIC with the ZX Spectrum
• • Solutions 195

14. 3. 12.
10 REM Names and ages 10 READ c,a$,b$ 10 REM List of numbers 10 REM Saving accounts
20 PRINT "NAME","AGE" 20 PRINT c;a$;b$ 20 FOR x=1 TO 10 20 PRINT "Name","Amount saved"
30 FOR x=1 TO 6 30 DATA 3,"blind","mice" 30 READ n 30 FOR n=1 TO 5
40 INPUT "Enter a name ";n$ 40 PRINT n 40 INPUT "Enter person ' s name
50 INPUT "Enter that persons 50 DATA 35,42,57,39,48,64,44,5 ";n$
age ;a 0,61,54 50 INPUT "Enter amount saved "
60 PRINT n$,a 60 NEXT x ;s
70 NEXT x 4. 70 STOP 60 PRINT n$,s
80 STOP 10 READ x$,y,b$ 70 FOR r=6 TO 10 STEP 2
20 PRINT y;b$;x$ 80 LET i=s*r/100
30 DATA "bottles",10,"green" 90 PRINT "The interest gained
at a rate of ;r;"% is E ";i
15. 100 PRINT "Total saved is E";s+
10 REM Names and prices of car 13. i
s 10 REM Wicked witch 110 NEXT r
20 PRINT "NAME OF CAR","PRICE 5. 20 READ a$,b$,c$,d$ 120 PRINT
IN f 'S" 10 FOR n=1 TO 4 30 READ e$,f$,g$ 130 NEXT n
30 LET t=0 20 READ x 40 DATA "The","wicked","witch" 140 STOP
40 FOR x=1 TO 4 30 PRINT x ,"cast" "many" "magic" "spells"
50 INPUT "Enter name of car ', 40 DATA 1,2,3,4 50 PRINT a$;" " ;b$; ";c$;" ,
c$ 50 NEXT n d$;" ;e$;" ";f$;" ;gS
60 INPUT "Enter the price of t 60 PRINT a$;" ";c9;" ";d$;" ";
hat car ";p b$;" ;g$ 3.
70 PRINT c$,p 70 PRINT a$;" ";f$;" ";c$;" "; 10 REM Rectangles of stars
80 LET t=t+p 6. d$;" ;eS;g$ 20 FOR n=1 TO 5
90 NEXT x 10 FOR n=1 TO 3 80 STOP 30 INPUT "Enter length of rect
100 PRINT "Total price of the c 20 READ x$ angle ";1
ars isf";t 30 PRINT x$ 40 INPUT "Enter width of recta
110 PRINT "Average p rice of car 40 DATA "man","woman","child" ngle ";w
s is f ";t/4 50 NEXT n 50 FOR x=1 TO 1
60 FOR y=1 TO w
120 STOP 70 PRINT "*";
14. 80 NEXT y
10 REM Food and prices 90 PRINT
7. 20 READ 1$,1,s$,s, j$,j
16. 10 FOR n=1 TO 3 100 NEXT x
10 REM Natural population incr 30 READ b$,b,e$,e,rS,r 110 PRINT
20 READ b,a$ 40 PRINT "FOOD","PRICE"
ease 30 PRINT b,aS 120 PRINT
20 PRINT "COUNTRY";TAB 9;"BIRT 50 PRINT 15,1 130 NEXT n
40 DATA 3,"ships",2,"cars",1, 60 PRINT s$,s
H RATE";TAB 21;"DEATH RATE" train" 140 STOP
30 FOR x=1 TO 7 70 PRINT j$,j
50 NEXT n 80 PRINT b$,b
40 INPUT "Enter name of countr
y ;c$ 90 PRINT e$,e
50 INPUT "Enter birth rate ";b 100 PRINT r$,r
60 INPUT "Enter death rate ";d 110 DATA "bread",36,"soup",19," Unit 23
8.
70 PRINT c$;TAB 13;b;TAB 257d a$ = Tom b$ = Dick c$ = Harry jam",58,"beans",17,"eggs",42,"ri
80 LET n=b-d ce",88 2. a
90 PRINT "The natural increase 120 LET t=l+s+j+b+e+r 10 REM Moving car
per 1000 people is ";n 130 PRINT "The total cost of th 20 BORDER 6
9. 30 PAPER 1
100 PRINT a = 3 b$ = Norway e food is E ";t/100
140 STOP 40 LET a=10
110 NEXT x
120 STOP 50 FOR b=0 TO 24
60 INK 7
10. 70 PRINT AT a-2,b+1;" VMS"
x = 10 y = 3 z = 17 80 PRINT AT a-1,b;" Ot®vMIUMW
90 PRINT AT a,b+l;" 0" j 'La Gital 0
100 PRINT AT a,b+5; " 0" - rot zero
Unit 21 110 PAUSE 5
Unit 22
120 NEXT b
11. 130 STOP
10 READ a,b,c 10 REM Days of the week 1
20 PRINT a,b,c 20 FOR n=1 TO 7 10 REM Stars
30 DATA 100,200,300 30 READ d$ 20 FOR n=1 TO 10
40 PRINT d$ 30 FOR x=1 TO 10 2. b
50 DATA "Monday","Tuesday","We 40 PRINT "*"; 10 REM
2. dnesday " "Thursday","Friday","Sa 50 NEXT x 20 BORDER 6
10 READ x$,y$,z$ turday","Sunday" 60 PRINT 40 LET a=10
20 PRINT x$,y$,z$ 60 NEXT n 70 NEXT n 45 FOR i=1 TO 6
30 DATA "cat","dog","fish" 70 STOP 80 STOP 47 INK i
• • Solutions 197
196 Beginning BASIC with the ZX Spectrum

4. a 50 READ e$(x),p(x)
50 FOR b=0 TO 24 Unit 24
10 REM Days of the week 60 DATA "coal",79,"oil",8,"nuc
70 PRINT AT a-2,b+1;"0®Gm" 20 DIM d$(7,9)
80 PRINT AT a-1,b;" 1111U113 1. a & b lear",11,"water",2
30 FOR n=1 TO 7 70 NEXT x
90 PRINT AT a,b+1;" 0" 10 REM Mountains 40 READ d$(n)
100 20 DIM a$(6,11) 80 PRINT "HOW ELECTRICITY IS P
PRINT AT a,b+5;" 0" 50 DATA "Monday","Tuesday","We
30 DIM x(6) RODUCED IN"
110 PAUSE 5 dnesday " "Thursday","Friday","Sa
40 DIM c$(6,12) 90 PRINT TAB 13;"THE U.K."
120 NEXT b turday" "Sunday" 100 PRINT "SOURCE OF";TAB 16;"%
125 CLS - this is to remove Car 50 FOR n=1 TO 6
60 NEXT n OF TOTAL"
127 NEXT i from rioht-hand of 60 READ a$(n) 70 INPUT "Enter a number betwe 110 PRINT TAB 3;"ELECTRICITY";T
130 STOP the screen 70 DATA "Everest","Kilimanjaro
en 1 and 7 ";n AB 22;"PRODUCED"
"Table" "Blanc","Matterhorn", ;d$(n)
80 PRINT "Day ";n;" is 120 PRINT "
Ben Nevis"
90 STOP
80 NEXT n 130 FOR y=1 TO 4
3 90 FOR m=1 TO 6 140 PRINT e$(y);TAB 21;p(y)
100 READ x(m) 4. b - modified 150 PRINT
first space 110 DATA 8848,5895,1087,4807,44 10 REM Days of the week 160 NEXT y
78,1347 20 DIM d$(7,9) 170 STOP
120 NEXT m 30 FOR n=1 TO 7
130 PRINT "MOUNTAIN","HEIGHT IN 40 READ d$(n)
METRES" 50 DATA "Monday","Tuesday","We
140 PRINT dnesday " "Thursday","Friday","Sa
150 FOR y=1 TO 6 turday" "Sunday" 7. a$ (2,1) = Paul
160 PRINT a$(y),x(y) 60 NEXT n a$ (1,3) = Sarah
170 NEXT y 70 INPUT "Enter a number betwe a$ (2,4) = Mark
180 FOR c=1 TO 6 en 1 and 7 ";n
190 READ c$(c) 80 IF n<1 THEN PRINT "Number t
first square 200 DATA "Nepal-Tibet","Tanzani oo low": GO TO 70
a" "South Africa" "France","Swit 90 IF n>7 THEN PRINT "Number t 8.
zerland" "Scotland" oo high": GO TO 70 10 REM Sportsmen
210 NEXT c 100 PRINT "Day ";n;" is ";d$(n) 20 DIM s$(5,2,12)
220 PRINT "MOUNTAIN","COUNTRY" 110 STOP 30 PRINT "NAME","SPORT"
4. 230 FOR w=1 TO 6 40 FOR x=1 TO 5
10 REM S q uare moves from botto 240 PRINT a$(w),c$(w) 50 FOR y=1 TO 2
m right to top left 250 NEXT w 60 READ s$(x,y)
4. c 70 DATA "J.Connors " "Tennis"
20 FOR n=20 TO 1 STEP -1 260 STOP Add to above program: S.Cram","Athletics","S.Davis","S
30 PRINT AT n,n;" "
65 FOR y=1 TO 4 nooker" "L.Piggott " "Horse Racin
40 PRINT AT n-1,n-1;"l"
105 NEXT y g" "F.Bruno " "Boxing"
50 PAUSE 10
60 NEXT n 80 PRINT s$(x,y)
2 90 NEXT y
70 STOP
10 REM Reversing numbers 100 PRINT
20 DIM x(8) 5.
10 REM Names of months 110 NEXT x
5. 30 FOR n=1 TO 8 120 STOP
40 READ x(n) 20 DIM m$(12,9)
10 REM Moving a square 30 DIM w$(1,9)
20 LET a=11 50 DATA 10,20,30,40,50,60,70,8
0 40 FOR x=1 TO 12 0
30 LET b=16 50 READ m$(x)
40 PRINT AT a-1,b;" " 60 NEXT n 10 REM World trade
70 FOR y=8 TO 1 STEP -1 60 DATA "January" "February"
50 PRINT AT a+1,b;" " 20 DIM t(3,3)
80 PRINT x(y) March","April","May","June","Jul
60 PRINT AT a,b-1;" " 30 PRINT "YEAR SHARE OF WORLD
90 NEXT y y" "August" "September " "October
70 PRINT AT a,b+1;" " "November","December" TRADE IN
80 PRINT AT a,b;"I" 100 STOP 40 PRINT TAB 7;"DEVELOPED";TAB
70 NEXT x
90 IF INKEY$="5" THEN LET b=b- 19;"DEVELOPING"
80 INPUT "Enter a word ";w$(1)
1 50 PRINT TAB 7;"COUNTRIES";TAB
90 FOR y=1 TO 12
100 IF b<1 THEN LET b=1 3. 100 IF m$(y)=w$(1) THEN PRINT m 19;"COUNTRIES"
110 IF INKEY$="6" THEN LET a=a+ 10 REM Every other number 60 PRINT "
$(y);" is month ";y: GO TO 130
1 20 DIM x(12) 110 NEXT y
120 IF a>20 THEN LET a=20 30 FOR n=1 TO 12 70 FOR x=1 TO 3
120 PRINT w$(1);" is not a mont
130 IF INKEY$="7" THEN LET a=a- 40 READ x(n) 80 FOR y=1 TO 3
h"
1 50 DATA 5,10,15,20,25,30,35,40 90 READ t(y,x)
130 STOP 100 DATA 1950,68,32,1960,79,21,
140 IF a<1 THEN LET a=1 ,45,50,55,60
150 IF INKEY$="8" THEN LET b=b+ 60 NEXT n 1970,82,18
70 FOR y=1 TO 12 STEP 2 110 PRINT t(y,x);"
160 IF b>30 THEN LET b=30 80 PRINT x(y) 6. 120 NEXT y
170 GO TO 40 10 REM How electricity is prod 130 PRINT
90 NEXT y
100 STOP uced 140 NEXT x
20 DIM e$(4,7) 150 STOP
30 DIM p(4)
40 FOR x=1 TO 4
198

Beginning BASIC with the ZX Spectrum

Solutions 199

Unit 25 3. 90 GO TO 40
a) 49 b) 4 100 REM Subroutine
1. Flowchart 110 PRINT "Too high,try again"
Subroutine 120 RETURN
200 REM Subroutine
210 PRINT "Too low,try again"
4. 220 RETURN
10 REM Questions about your ho
me
20 PRINT "How many rooms has y
our house? 7.
30 INPUT "Enter a number ";n
40 PRINT n 10 REM OPENING BOTTLES
50 GO SUB 200 20 INPUT "Enter type of bottle
60 PRINT "What is the number top-cork or screw cap ";b$
f your house? ' 30 IF b$="cork" THEN GO SUB 20
70 INPUT "Enter a number ";x 0
80 PRINT x 40 IF b$="screw cap" THEN GO S
90 GO SUB 200 UB 300
100 PRINT "Does your house have 50 IF b$<>"cork" AND b$<>"scre
a garden? ' w cap" THEN PRINT "Wrong type of
110 INPUT "Enter yes or no ";a$ bottle top": GO TO 20
120 PRINT a$ 60 PRINT
130 GO SUB 200 70 PRINT "Bottle opened.Shall
140 PRINT "Does your house have I pour a glass?"
a garage? 80 PRINT
150 INPUT "Enter yes or no ";b$ 90 PRINT "Cheers!!"
160 PRINT b$ 100 STOP
170 GO SUB 200 200 REM Subroutine to open bott
180 STOP le with cork
200 REM Subroutine for stars 210 PRINT "1.Place corkscrew on
210 FOR n=0 TO 31 top of cork with left hand-hold
220 PRINT "* , firmly"
230 NEXT n 220 PRINT "2.With right hand to
240 RETURN rn handle of corkscrew clockwise
pressing downwards"
230 PRINT "3.With right hand to
rn handle of corkscrew anti-cloc
kwise pulling cork upwards"
5. 240 RETURN
10 REM Ex25.5 300 REM Subroutine to o p en butt
2. Flowchart Subroutine 20 INPUT "Enter a number betwe le with screw cap
en 1 and 100 ";n 310 PRINT "1.Hold bottle with 1
30 IF n<50 THEN GO SUB 100 eft hand"
40 FOR x=0 TO n STEP 5 320 PRINT "2.Grip bottle cap fi
50 PRINT x rmly with right hand"
60 NEXT x 330 PRINT "3.Turn cap anti-clot
70 STOP kwise"
100 REM Subroutine 340 RETURN
110 LET n=n+25
120 RETURN
8.
10 REM Painting walls
20 LET r=0.15
6. 30 INPUT "Enter the number of
10 REM Guessing a number walls to be _painted ";n
20 PRINT "Player guessing numb 40 LET t=0
er close your eyes" 50 FOR w=1 TO n
30 INPUT "Enter a number to be 60 INPUT "Enter length of wall
guessed between 1 and 100 " ;f
40 INPUT "Player enter a numbe 70 GO SUB 300
r between 1 and 100 ";n 80 LET 1=m
50 PRINT n 90 INPUT "Enter height of wall
60 IF n=a THEN PRINT "Correct" ;f
: GO TO 20 100 GO SUB 300
70 IF n>a THEN GO SUB 100 110 LET h=m
S-7
C 80 IF n<a THEN GO SUB 200 120 LET a=1*h
Solutions 201
200 Beginning BASIC with the ZX Spectrum

1 2 3 4 5 6 7
130 PRINT "Area of wall is ";a L ' ON T " TN P ' MTH N " HAM L ' PL LEEDS HULL
140 LET t=t+a
150 PRINT "Total area =";t
160 PRINT 1 LONDON 0 144 211 122 197 190 168
170 NEXT w
180 LET 0=t*r
190 PRINT "Amount of paint requ 2 TAUNTON 144 0 74 160 203 237 247
fired is ;p;" litres"
200 STOP
300 REM Subroutine for changing 3 PLYMOUTH 211 74 0 254 278 312 321
feet into metres
310 LET m=f/3.208
320 RETURN 4 NOTTINGHAM 122 180 254 0 97 67 73

5 LIVERPOOL 197 203 278 97 0 73 128


9.
Distances between cities 6 LEEDS 190 237 312 67 73 0 55

Line 20: Sets up a one-dimensional strin g array called t$ which has 7 HULL 168 247 321 73 128 55 0
seven elements, the ma, y imum length of any element being ten
characters. The data is supplied by lines 50 to 80. This array
stores the names of the cities.

Line 30: Sets up a two-dimensional numeric array called " d " which has
49 elements - 7 rows of 7 columns. The nested loops (Lines 90 to 140) Unit 26 5.
put the distances between the cities into this array. 10 REM London ' s Burning
1. Top E = 16 Bottom B = -13 20 FOR x=1 TO 2
Line 40: Sets up a one-dimensional string array with one element of 30 BEEP .5,2: BEEP .5,2: BEEP
maximum length ten characters, which matches the length of the t$ 2. Add: 1,7: BEEP 1,7
array. The information for this array is entered by the user in lines 15 FOR n = 1 TO 3 40 NEXT x
150 and 190. 25 NEXT n 50 FOR y=1 TO 2
60 BEEP .5,9: BEEP .5,9: BEEP
Line 150: City travelled to is entered into c$(1) and the computer 3. Add: 1,11: BEEP 1,11
then goes to the subroutine. 22 PAUSE 3 * 50 70 NEXT y
80 FOR w=1 TO 2
Lines 300-350: A subroutine compares the city entered into c$(1) with 90 BEEP 1,14: BEEP 2,14
all the cities contained in tSO . 100 NEXT w
If c$(1) matches up with one of the cities in t$)) then the 4. a
10 REM Scale of C major all in 110 FOR z=1 TO 2
computer returns to the main program. If no match is found, then the semiquavers 120 BEEP .5,14: BEEP .5,12: BEE
computer sets the value of x to 0 and returns to the main program. 20 BEEP .25,0: BEEP .25,2: BEE P 1,11: BEEP 1,11
P .25,4: BEEP .25,5: BEEP .25,7: 130 NEXT 2
Line 170: Returning from the subroutine if x = 0 then the city did BEEP .25,9: BEEP .25,11: BEEP . 140 STOP
not match, so "No information" is printed and the user is sent back to
line 150 where another city can be entered. 25,12 6. a
30 STOP 10 REM Scale of G major
Line 180: If a match was found, then x will have a value of between 1 20 BEEP .5,-5: BEEP .5,-3: BEE
and 7, dependin g on which element of t$O the match was found in. b P .5,-1: BEEP .5,0: BEEP .5,2: B
This value of x is given to y to be stored for later use, as x is used 10 REM Scale of C major with c EEP .5,4: BEEP .5,6: BEEP .5,7
a g ain and will therefore alter its value. rotchets and quavers 30 STOP
20 BEEP .5,0: BEEP .5,2: BEEP
Line 190: The city travelled from is entered into c$(1); the computer 1,4: BEEP .5,5: BEEP .5,7: BEEP b
then g oes to the subroutine where the process of checking the name of 1,9: BEEP .5,11: BEEP .5,12 G A B C D E F# G
the city is done a g ain. (For information, see lines 300-350.) 30 STOP 7 9 11 12 14 16 18 19

Line 210: This is almost the same as line 170; if x = 0 there is no c


information about the city in c$(1), so the user is sent back to line c 10 REM Scale of G major
190 for another city to be entered. 10 REM Scale of C major with 20 BEEP .5,-5: BEEP .5,-3: BEE
a variety of different length P .5,-1: BEEP .5,0: BEEP .5,2: B
Line 220: The distance between the cities is now printed out. This is notes EEP .5,4: BEEP .5,6: BEEP .5,7
done by looking up the names in the t$O array. One city is stored in 20 BEEP 2,0: BEEP .25,2: BEEP 30 BEEP .5,9: BEEP .5,11: BEEP
t$(y) - see line 180 - and the other in t$(x). The numbers contained .25,4: BEEP .25,5: BEEP .25,7: .5,12: BEEP .5,14: BEEP .5,16:
in y and x are then used to look up the distance in the d array. For BEEP .5,9: BEEP .5,11: BEEP 4,12 BEEP .5,18: BEEP .5,19
example, if y = 5 and x = 3 [t$(5) is Liverpool and t$(3) is 30 STOP 40 STOP
Plymouth] the element d(5,3) is looked up, riving a value of 278, as
can be seen from the following table.
202 Beginning BASIC with the ZX Spectrum
• • Solutions 203

7. 3. Add: 160 NEXT n 10.


10 REM Good King Wenceslas 65 INPUT "Enter number you 170 PRINT 10 REM Countin g heads and tail
20 FOR n=1 TO 2 wish to be counted ";n 180 PRINT "NUMBER","APPEARED"
30 BEEP 1,7: BEEP 1,7: BEEP 1, Alter: 190 FOR w=1 TO 5 20 LET h=0
7: BEEP 1,9: BEEP 1,7: BEEP 1,7: 70 IF d= n THEN LET c = c + 1 200 PRINT w,a(w) 30 LET t=0
BEEP 2,2: BEEP 1,4: BEEP 1,2: B 120 PRINT " The number of 210 NEXT w 40 FOR n=1 TO 80
EEP 1,4: BEEP 1,6: BEEP 2,7: BEE times ";n; " appeared was ";c 220 STOP 50 LET x=INT (2*RND)
P 2,7 60 IF x=0 THEN LET h=h+1: GO T
40 NEXT n 0 80
50 GO SUB 200 4. 70 LET t=t+1
60 BEEP 1,11: BEEP 1,9: BEEP 2 10 REM List of 20 numbers 80 NEXT n
,7: BEEP 1,4: BEEP 1,2: BEEP 1,4 20 FOR n=1 TO 20 8. 90 PRINT "The number of times
: BEEP 1,6: BEEP 2,7: BEEP 2,7 30 LET x=INT (101*RND) 10 REM Testing multiplication heads occurred is ";h
70 BEEP 1,2: BEEP 1,2: BEEP 1, 40 PRINT x tables 100 PRINT
4: BEEP 1,6: BEEP 1,7: BEEP 1,7: 50 NEXT n 20 LET x=INT (11*RND)+2 110 PRINT "The number of times
BEEP 2,9 60 STOP 30 LET y=INT (11*RND)+2 tails occurred is ',
80 GO SUB 200 40 PRINT x;"*";y;"="; 120 STOP
90 BEEP 2,7: BEEP 2,12: BEEP 4 50 INPUT "Enter an answer ";a
,7 60 PRINT a
100 STOP 70 IF a=x*y THEN PRINT "Correc
5. t": GO TO 90
200 REM Subroutine Unit 28
10 REM List of 15 numbers 80 PRINT "Incorrect,the answer
210 BEEP 1,14: BEEP 1,12: BEEP
1,11: BEEP 1,9 20 FOR n=1 TO 15 is ;x*y B 16,8
1. A 7,7
30 LET x=INT (20*RND)+1 90 STOP
220 RETURN C 0,15 D 31,11
40 PRINT x
E 0,0 F 21,0
50 NEXT n
G 11,9
60 STOP
8.
10 REM The Holly and the Ivy 9. a
20 FOR n=1 TO 4 10 REM Throwing 2 dice
30 FOR x=1 TO 29 20 LET c=0
30 FOR n=1 TO 50 2. a
40 READ a,b
40 LET d1=INT (6*RND)+1 10 REM Line A
50 BEEP a,b
50 LET d2=INT (6*RND)+1 20 PLOT 16,130
60 DATA 1,7,.5,7,.5,7,1,7,1,16
6. 60 LET s=dl+d2 30 DRAW 80,0
,1,14,1,11,1,7,.5,7,.5,7,1,7,1,1
10 REM Same sequence of random 70 IF s=7 THEN LET c=c+1 40 REM Line B
6,2,14,.5,14,.5,12,.5,11,.5,9,1,
numbers 80 NEXT n 50 PLOT 24,72
7,1,11,.5,4,.5,4,1,2,.5,7,.5,9,.
20 RANDOMIZE 600 90 PRINT "The number of times 60 DRAW 28,24
5,11,.5,12,1,11,1,9,2,7
30 FOR n=1 TO 10 7 occurred is ";c 70 REM Line C
70 NEXT x
40 LET x=INT (11*RND) 100 STOP 80 PLOT 183,40
80 PAUSE 2*50
50 PRINT x 90 DRAW -127,0
90 RESTORE
60 NEXT n 100 REM Line D
100 NEXT n
70 STOP 110 PLOT 116,167
110 STOP
120 DRAW 0,-103
130 REM Line E
b 140 PLOT 136,119
10 REM Throwing 2 dice 150 DRAW 111,-103
Unit 27 20 LET t=0 - 160 REM Line F
30 FOR x=1 TO 5 170 PLOT 231,88
7.ter imes 40 LET c=0 180 DRAW -79,71
1. a 4 b 103 c 99 occur 50 FOR n=1 TO 50
d -6 e -88 f -1 random numbers 60 LET d1=INT (6*RND)+1
g 0 20 DIM a(5) 70 LET d2=INT (6*RND)+1 b
30 FOR y=1 TO 5 80 LET s=dl+d2 190 PRINT AT 4,7;"A"
40 READ a(y) 90 IF s=7 THEN LET c=c+1 200 PRINT AT 10,4;"B"
50 DATA 0,0,0,0,0 100 NEXT n 210 PRINT AT 15,11;"C"
60 NEXT y 110 PRINT "The number of times 220 PRINT AT 8,13;"D"
70 FOR n=1 TO 10 7 occurred is ";c 230 PRINT AT 11,23;"E"
2. 80 FOR m=1 TO 10 120 LET t=t+c 240 PRINT AT 6,26;"F"
Line 30: LET X = INT(21*RND) was 90 LET s=INT (5*RND)+1 130 PRINT "The total number of 250 STOP
not written as 100 PRINT s;" ' times 7 has occurred is ";t
LET X = INT(20*RND) because INT 110 FOR x=1 TO 5 140 NEXT x
rounds down; 21 will 120 IF s=x THEN LET a(x)=a(x)+1 150 PRINT
automatically give numbers only 130 NEXT x 160 PRINT "The average number o 3.
up to 20, which is what is 140 NEXT m f times that 7 occurred is ";t/5 10 REM Shape A
required. 150 PRINT 170 STOP 20 PLOT 32,32
204 Beginning BASIC with the ZX Spectrum
• Solutions 205

30 DRAW 0,39 5. 410 DRAW -24,-40 Unit 29


40 DRAW 39,0 add to previous program: 420 DRAW -109,0
50 DRAW 0,-39 92 INPUT "What do you wish to 430 STOP 1. a
60 DRAW -39,0 draw? Enter t for triangle or p 10 REM Fat little man
70 PRINT AT 15,6;"A" for pentagon ";a$ 20 POKE USR " M " ,BIN 00011100
100 REM Sha p e B 94 IF a$="t" THEN GO TO 100 30 POKE USR " M"+1,BIN 00011100
8. 40 POKE USR " M " +2,BIN 00001000
110 PLOT 48,88 96 IF a$="p" THEN GO TO 160 Keep lines 10 - 110 50 POKE USR " M"+3,BIN 00111110
120 DRAW 23,71 160 CLS
Add: 60 POKE USR " M " +4,BIN 01011101
130 DRAW 24,-63 170 PLOT x,y 120 FOR n = 1 to h-1 70 POKE USR " M " +S,BIN 00011100
140 DRAW -47,-8 180 DRAW 0,h/2 130 PLOT x,y+n 80 POKE USR " M"+6,BIN 00100010
150 PRINT AT 7,9;"B" 190 DRAW w/2,h/2 140 DRAW w-1,0 90 POKE USR " M"+7,BIN 01000001
200 REM Shape C 200 DRAW w/2,-h/2 150 NEXT n 100 PRINT "M" (Entered in
210 PLOT 120,152 210 DRAW 0,-h/2 160 STOP 110 STOP graphics mode)
220 DRAW 15,15 220 DRAW -w,0
230 DRAW 80,-72 230 STOP
240 DRAW -15,-15
b
250 DRAW -80,72
9. 10 REM House
260 PRINT AT 6,21;"C" 10 REM VIKING SHIP
6. 20 POKE USE "H",BIN 00111000
300 REM Shape D 20 REM Hull of ship 30 POKE USR "H"+i,BIN 01111100
310 PLOT 96,24 10 REM picture 30 PLOT 72,72
320 DRAW 0,47 40 POKE USR 'H"+2,BIN 11111110
20 REM trees 40 DRAW 104,24,2.5 50 POKE USR '11"+3 ‚BIN 10101010
330 DRAW 31,32 30 FOR n=1 TO 20 50 DRAW 8,-4 60 POKE USR "H"+4,BIN 11111110
340 DRAW 48,-32 40 READ x,y 60 DRAW -8,-4
350 DRAW 0,-47 70 POKE USR "H"+5,BIN 10101010
50 DATA 20,96,24,52,40,40,54, 70 REM Shields 80 POKE USR "H"+6,BIN 11101110
360 DRAW -79,0 40,68,100,80,124,92,112,104,132, 80 LET y=68
370 PRINT AT 14,16;"D" 90 POKE USR " H"+7,BIN 00000000
114,112,124,132,132,112,100,48, 90 LET r=8 100 PRINT "H" (Entered in
400 REM Shape E 112,64,140,32,160,32,180,104,196 100 FOR s=1 TO 5 110 STOP graphics mode)
410 PLOT 192,39 ,96,216,128,236,124,244,52 110 READ x
420 DRAW 0,17 60 PLOT x,y 120 DATA 153,136,120,103,86
430 DRAW 15,15 70 DRAW 0,8 2.
130 CIRCLE x,y,r
440 DRAW 17,0 80 DRAW -7,0 10 REM Moving car
140 NEXT s
450 DRAW 15,-15 90 DRAW 7,32 20 POKE USR "C",BIN 00000000
150 REM Mast
460 DRAW 0,-17 100 DRAW 7,-32 30 POKE USR "C"+l,BIN 00000000
160 PLOT 120,76
470 DRAW -15,-15 110 DRAW -7,0 40 POKE USR "C"+2,BIN 00111100
170 DRAW 0,88
480 DRAW -17,0 120 NEXT n 50 POKE USE "C"+3,BIN 01010100
180 REM Flag
490 DRAW -15,15 130 REM houses 190 DRAW -20,-5 60 POKE USR "C"+4,BIN 11111111
500 PRINT AT 15,27;"E" 140 FOR h=1 TO 4 70 POKE USR "C"+S,BIN 11111111
200 DRAW 20,-5
510 STOP 150 READ x,y 80 POKE USR "C"+6,BIN 01100110
210 REM Sails
160 DATA 32,96,64,40,144,112,20 220 DRAW 0,-4 90 POKE USR "C"+7,BIN 00000000
8,72 230 DRAW 54,8 100 LET a=11
170 PLOT x,y 240 DRAW -8,-68 110 FOR b=0 TO 30
180 DRAW 0,24 250 DRAW -100,-12 120 PRINT AT a,b;" "
190 DRAW 12,12 260 DRAW 8,64 130 PRINT AT a,b+l;"C " (entered
140 NEXT b in graphics mcde)
10 REM Drawing triangles 200 DRAW 12,-12 270 DRAW 46,8
20 INPUT "Enter x coordinate " 210 DRAW 0,-24 280 REM oars 150 STOP
;x 220 DRAW -16,0 290 LET y=32
30 IF x<0 OR x0255 THEN PRINT 230 DRAW 0,16 300 FOR o=1 TO 5
"Not acceptable": GO TO 20 240 DRAW 8,0 310 READ x
250 DRAW 0,-16 320 DATA 64,82,100,118,136 Unit 30
40 INPUT "Enter y coordinate "
;y 260 DRAW -16,0 330 PLOT x,y
50 IF y<0 OR y>175 THEN PRINT 270 NEXT h 340 DRAW 19,28 1
280 REM roads 10 REM Length of words
"Not acceptable": GO TO 40 350 NEXT o
290 PLOT 0,40 360 PRINT AT 20,9;"VIKING SHIP" 20 PRINT "WORD","LENGTH"
60 INPUT "Enter width ";w
300 DRAW 103,0 30 FOR n=1 TO 8
70 IF x+w>255 THEN PRINT "Too 370 STOP
310 DRAW 37,56 40 INPUT "Enter a word ";a$
wide": GO TO 60
320 DRAW -84,0 50 PRINT a$,LEN a$
80 INPUT "Enter height ";h
330 DRAW 0,8 60 NEXT n
90 IF y+h>175 THEN PRINT "Too
high": GO TO 80 340 DRAW 91,0 70 STOP
100 CLS 350 DRAW 5,8
110 PLOT x,y 360 DRAW 8,0
120 DRAW w/2,h 370 DRAW -20,-32
130 DRAW w/2,-h 380 DRAW 68,0
140 DRAW -w,0 390 DRAW 0,-8
150 STOP 400 DRAW -74,0

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy