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

Computer Programming Text

This document provides an introduction to computer programming using the BASIC language. It explains that to make a computer perform tasks, one must write a program consisting of precise instructions in a language the computer understands. It then gives an overview of the main components of a computer and how BASIC programs work, using short example programs to demonstrate different BASIC commands like PRINT. The document is intended to teach programming basics and get readers started writing their own simple programs.

Uploaded by

Kjartan Olason
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)
16 views

Computer Programming Text

This document provides an introduction to computer programming using the BASIC language. It explains that to make a computer perform tasks, one must write a program consisting of precise instructions in a language the computer understands. It then gives an overview of the main components of a computer and how BASIC programs work, using short example programs to demonstrate different BASIC commands like PRINT. The document is intended to teach programming basics and get readers started writing their own simple programs.

Uploaded by

Kjartan Olason
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/ 51

INTRODUCTION TO £

COMPUTER
PROGRAMS
INTRODUCTION TO

COMPUTER
PROGRAMMING
Brian Reffin Smith
Edited by Lisa Watts

Designed by Kim Blundell


Illustrated by Graham Round
and Martin Newton
Contents
4 How computer works
a
6 Giving the computer instructions
8 Writing programs
10 First words in BASIC
12 Giving the computer information
14 Using INPUT
16 Doing things with PRINT
18 How computers compare things
20 Programs with lots of BASIC
22 Drawing pictures
24 Playing games
26 Making loops
28 Tricks with loops
30 Subroutines
32 Doing things with words
34 Graphs and symbols
More graphics
36
38 Funny poems program
42 Programming tips
44 Puzzle answers
46 BASIC words
48 Going further and Index
About this book
This is a guide to writing computer
programs in BASIC for absolute
beginners. BASIC is the language
used on most home computers. It is

a way of writing instructions for a


computer in a form the computer
can understand,
To give you some practice in
writing programs there are
program puzzles to solve and
suggestions for programs to write
and for useful alterations you can
make to the programs in this guide.
The answers to the program
puzzles are on pages 44-45.
At the end of the guide there is a
list of BASIC terms and other

computer words with brief


explanations- There are also some
You do not need a computer to
guidelines to help you write
use this guide, though of course it
programs, and a list of "bugs" - the
helps you to understand the
mistakes in programs which stop
programs if you can try them out on
a computer. Different makes of
them working - with hints to help
you recognize them.
computer use slightly different
versions of BASIC, Nearly all the
terms in this book, though, will
work on most microcomputers, and
the few that are not standard are

If you have a micro, try out the

programs in this guide, then, to finti


out more about how your micro
works, look up the BASIC terms in
your manual, You may find that
some of the rules given here are
At the beginning there are some not necessary on your micro. The
guidelines to programming a best way to learn BASIC is to try out
computer. Then, as you read lots of programs from books and
through the book, the main BASIC magazines, then alter them a little
words are introduced one by one. to see what happens, From there
with short programs to show how you will soon be writing your own
they work, programs.
How a computer works
You can do all kinds of different things with a
computer. You can draw pictures, write funny poetry,
draw graphs, play games and do lots of things with
words and numbers, some of them useful and some
just for fun. A computer is sometimes described as
an "information processor". Its task is to
take the information you give it, work
on it according to your instructions,
and show you the results. Divi DE 999
BY 27

/ ?mi MY NAME
v m times
LOAD
’missile
Commanb'^

To make a computer do what you want work on is called data. The program has to
you have to give it very precise be written in a language, such as BASIC,
instructions. A list of instructions fora that the computer can understand, and it
computer is called a program and the 1
'
must follow all the rules of the language
information you give the computer to

Microcomputers

Most micros consist of a


keyboard which you plug into
a TV set. You give the micro
instructions and information by
typing on the keyboard and
everything you type, along with the
computer’s results, is displayed on the
TV screen. The keyboard of a micro looks
Some micros have a small, built-in like a typewriter keyboard with some
display screen, like a pocket calculator . A extra keys. On some micros each key
few use a special screen called a monitor, gives the computer a separate instruction
A monitor is like a TV but it cannot pick up in BASIC so you do not have to type the
the signals from TV stations. words in letter by letter.

Spelt like this when used for a computer.


Inside a micro
A micro is made up of two main pans:
the centra] processing unit (CPU)
where all the work is done, and the
memory where programs and data are
stored.

ROBOTRjOBOT robot
R.Q BOT ROBOT F?jO BOT
RD BOTRO BOT £0 Bffl

R£AW computer has two


In fact, the
memories. One, called ROM, contains a
TWEET
program which controls all the
TWEET operations of the computer. The other,
called RAM, is an empty memory
where your programs and data are
stored When you switch off the micro
all RAM is lost, but
the information in
the ROM program is permanent.

Printer -*
A TV screen is the most usual way to
display the information from a micro. You Another way to store information from a
can also print it out on paper, using a micro is with a cassette recorder. You can
printer. This is useful as the information in store programs and data on a cassette,
the micro and on the TV screen is lost then load them back into the micro when
when you switch them off. you want to use them.
Giving a computer instructions
DO THIS
f PRJNT
\

LATER ON
"robots
m
QREAt"

10 PRINT 'ONE ROBOT


' 1
IS
ooo
GREAT
20 PRINT "TWO RO&OT3 ARE
GREAT”
3ti PRINT ''THR^i ROBOTS
AHt LANTASTIC'
40 £NQ

To make the computer do something, you straight away, or it can be a program of


have to type in an instruction it instructions which it stores in its memory
understands. This instruction can be a and does not cany out until you give it the
direct command which carries out
it go-ahead.

The instructions in a program have to be The computer cannot understand


very carefully worked ou:. The computer instructions written in our language, so
will attempt to cany out your instructions you have to write them in one of the many
precisely, even if they are wrong. computer languages Some of these
languages are described opposite.

All the work inside the computer is done Each piece of information in computer
with a code of tiny pulses of electricity. code is represented by patterns of pulses.
Your instructions are translated into Computer code can be written down
computer code by a special program using 1 to represent a pulse and 0 to show
inside the computer called the there is no pulse.
6
interpreter.
Computer languages
You could write programs in computer code but it would be very difficult. Instead .there
are special computer languages, called high level languages, which the computer can
translate into its own code.
There are hundreds of different high level languages, many of them specially
designed to do one particular kind of work. BASIC is one of the most common
languages. The letters stand for Beginner's All-purpose Symbolic Instruction Code. It is

not just used by beginners though. Below there are examples of three different
languages.

.rogravtt
1

Oeogi^P^^ CAPITA °fF


£
^rr A- *» *
* lf L, ota, W:C
tiueih«>
1C-
" *

isss®** AGAIN
l|J h
JY- -vn/1 , iffiLSH®

This is a short program in This program is written in Thisis a language called

BASIC, Line 10 tells the Pascal, a language named PILOT. It is used to write
computer to print “What is after a famous French programs to help people
your name" on the screen. mathematician. It is part of a learn new subjects. In this
Then the computer stores program to work out details language, the computer can
your answer in its memory about money Many people recognize answers even if
and if your name is Brian or think it is easier to write they are not exactly right.
George it prints out a
K
good, neat programs in
message to you. Pascal than in BASIC,

TALTAA OL LA VKSlTOtSTA
ASTETTA FAKKA5TA’

11. Bb3,Ne5
12. 0-0-0, Nc4
13. Bxc4, Rxc4
14. h5, NxhB

At first glance, computer languages seem instance, in mathematics a special


very strange and difficult, but then, so do notation is used to write down ideas and
other languages such as the Finnish formulae which would need a lot of
shown on the right, until you get to know ordinary words to explain them and other
them. There are lots of other subjects too, kinds of notation are used to write down
in which special languages are used. For chess moves or music.

Minus fifteen I guess


Writing programs
A program is like the rules for a game, or the recipe for a cake. If there is a
mistake in the rules, or the recipe, you will not be able to play the game
properly, orbake a good cake. In the same way, the results you get from a
computer depend on the instructions you give To write a program for a
it.

computer you first need to study what you want to do very carefully and
workout the main steps needed to achieve the result you want.

Imagine trying to write a program to tell a You ne ed to work out exactly what the
robot to post a letter. A simple instruction robot needs to do to post the letter. Its
as shown above would be too difficult for computer needs instructions telling it
the robot's computer brain to understand. what to do at every stage,

I MUST POST
THIS LETTER.

Qpe^
Go out a
f\ndP°

IE
MJm
it

To write the program you need to break The robot will attempt to follow your
down the instructions for each stage into instructions even if they arewrong, or
even smaller steps which can be incomplete. Mistakes in a program are
translated into a language the robot can called bugs and they can sometimes lead
8 understand. to unusual results from the computer.
Program diagrams
When you are writ ing a program it sometimes helps to draw a diagram like the one

below, showing the main steps you need to solve the problem. A diagram like this is
called a flowchart It shows each of the steps the computer needs to carry out and the
. ,

order they should come in.

^^OKflow chaIt

Are you.
arobc^

Answer
oi

print
“ttoboe

This is a flowchart
for a program
telling the computer
to print a message
only to robots.

A flowchart has different shaped boxes rectangular boxes and decision boxes,
The
for different steps in the program. where the computer can do different
beginning and end of the program have things depending on the information it
round boxes, instructions telling the receives, are in diamond-shaped boxes.
computer to do something are in The lines show the possible routes the
computer can follow.

After working out all the details of the the computer, or errors of logic in your
program you can translate it into BASIC program. Before you can get the program
and test it on the computer. The program to work you have to find all the bugs and
* Sometimes, a bug makes a
willprobably not work straight away correct them
though, as there will probably be some program produce a slightly different
bugs in it. These may be typing mistakes result which you may prefer. Useful bugs 9
made when you typed the program into like this are called "pugs ".

‘There are some tips to help you find bugs on pages 42-43.
First words in BASIC
Lots of thewords in BASIC are
based on English words and it is
quite easy to guess what they
mean. For instance, PRINT means
display on the screen RUN ",

means "carryout this program" and


INPUT means "give the computer
information". On these two pages
you can find out how to use the
word PRINT.
Most home computers have a When you switch on a micro some words
are usually displayed on the screen
BASIC language interpreter inside automatically, along with a small symbol
them already and when you switch called the cursor. The cursor shows
them on they are ready to be where the next letter you type will appear.
programmed in BASIC. *

READY
PRPtSIT "SNAILS">

To tell the computer to display words on The computer will not carry out your
the screen you use PRINT with the words instruction, though, until you press
you want in quotation marks. For instance, NEWLINE (or RETURN or ENTER - it
PRINT “SNAILS" tells it to display the word varies on different computers) to tell it the
SNAILS on the screen. instruction is complete.

Remember
to press
PRINT “SNAILS” NEWLINE J PRINT "1-2-3"
SNAILS after each ) 1-2-3
PRINT "XYZ" instruction./
PRINT "RUBBISH
XYZ RUBBISH
PRINT "1-2-3" PRINT 999
1-2-3 999
PRINT "RUBBISH PRINT 123
RUBBISH 123

The computer will display on the screen To display numbers by themselves, you
whatever you type between he quotat ion
t do need to use quotation marks. Now,
not
marks. It can be letters, numbers, words screen you type CLS on most
to clear the
or symbols. Note that it does not display micros. (Check this in your manual if you
the quotation marks themselves. have a computer.)

'Some computers have to have a special program loaded from cassette tape be fore they
understand BASIC.
A program in BASIC
In a program, each line of instructions starts with a number This tells the computer to
store the instructions in its memory and not to carry them out until you give the
go-ahead. On the opposite page, the Instructions to the computer did not have numbers,
so the computer carried them out straight away. Here is a short program which makes
the computer display symbols in the shape of a face on the screen.

On some computers n
10 PRINT ffff/r Line numbers usually go up in
thefigure 0 has a tens so you can add extra
line through it,
20 PRINT "I T instructions without
11

like this. 30 PRINT "It. JI renumbering the whole


40 PRINT "1 -L I" program.
SO PRINT “VWV” Many computers"
60 END do not need
this line.

When you type in a program you have to you tell it to by typing RUN. Be careful not
press NEWLINE (or the computer's word) to mix up the letter O and the figure 0 as
atthe end of each line. The lines are this will cause a bug. Most computers
displayed on the screen but the computer have a RUBOUT or DELETE key for
does not carry out the instructions until correcting typing mistakes

The computer displays (


RUN
exactly what you typed You type LIST (ant
MISSING" NEWLINE) to see
between the
LIST program again.
quotation
marks,
\
Error message
including the
spaces.

When you have typed m all the lines, program does not work, or the
If the

check them caiefuly to make sure there picture does not look right, you need to
are no mistakes. Then, to teU the computer display the program again to find the bug.
to carry out the program, you type RUN, To do this you type LIST. The computer
followed by NEWLINE. may give you an error message telling you
what the bug is.

Debugging programs RUN


J MISSING'
RUM
LIST
MISSING”
10 PRINT
LIST
20 PRINT
10 PRINT tuur 30 PRINT
20 PRINT I I

40 PRINT
30 PRINT If H PRINT
50
40 PRINT -t J

vvw 60 END
50
SO
PRINT
END
No quotes 50 PRINT WW
The computer will give you an error the program altogether, just type the line
message for most bugs The error number, followed by NEWLINE Each
messages are explained in the computer s computer also has its own way for
manual The easiest way to correct a correcting or altering parts of lines, using
mistake is to type the whole line again. words such as EDIT or COPY. This is
The computer will replace the old line explained in the computer's manual.
with the new one To get rid of a line from
II

Program puzzle - Tty changing the program to give the face different features.
Giving the computer information
To make the computer do something more useful than just displaying
things on the screen you have to give it information or "data" to work on.
The computer stores this information in its memory until you tell it to use it.

10 LET A=6
30 LET B=7
30 LET C=33
40 LET D=4

When you put a piece of data into the can use the word LET, as shown above. A
computers memory you have to give it a labelled memory space is called a
label so you can find it again. You can use variable because it can hold different data
alphabet as labels. To label a
letters of the at different times in the program.

memory space and put a number in you it

2 10 LET A=3
20 LET A$= “SNAILS"
30 LET B=43
40 LET BS= “ROBOTS"

You use a different kind of label w store You put a string in a memory space
letters and symbols in memory spaces. using LET jn the same way as for a number
Letters and symbols are called “strings” variable, but the letters and symbols must
and you use letters of the alphabet with be enclosed in quotation marks, as shown
dollar signs to label them, e.g. C$.' above.

3 10 LET B-365
20 LET DS=“DAY£ IN THE YEM"
30 LET L$- “EXCEPT LEAP YEAR
1

40 PRINT B
SO PRINT DS
60 PRINT L$
70 END * Many computers do
not need an END-

To display the information on the screen You can run the program as many times
you use the word PRINT with the name of as you want. Each time the computer will
the variable, e.g, PRINT A$. This short print out the same information. The data in
program prints out the information from the variables stays the same until you
variables B, DJ and LS. change it.

This is pronounced “G dollar” or


ll
G string”.
Another way to store information is with When you run the program the
the words READ and DATA, as shown comput er puts each piece of data in a
above The READ lines tell the computer memory space, taking them in order. The
to label memory spaces and the DATA items of data must have commas in
line contains the information. between so the computer knows how long
Some programs each one is/

WX 10 READ
Rl Q Comma Quotes
'
1 20 READ
Rl XS
30 DATA 24. vCHEESE BURGERS 10 LET AS = "ROBOTS ARE GREAT"
40 PRINT G -
v '

20 LET BS-"I'F YOU LIKE


^

50 PRINT XS This is one item 30 LET C$= "GREAT METAL IDIOTS"


& END
60 of data including
,
40 PRINT AS
RUN
R the space.. 50 PRINT B3
24
* 60 PRINT CS
L CHEESE BURGERS 70 END
RUN
Here are two programs, one using READ ROBOTS ARE GREAT
and DATA and the other using LET to IF YOU LIKE

store information in the computer’s GREAT METAL IDIOTS


memory,

More about variables You cannot use these


words as va rlabJe label
Number vartable as they contain
BASICwords ^

Siring variable

Variables are labelled spaces in the called a string variable. The contents of
computer's memory where information is variables can change during the program
stored. A variable containing numbers is Some computers can use words as labels
called a number variable and one words which contain
for variables, but not
which contains letters and symbols is BASIC words as this would confuse the
computer. 13

You cannot use I his met hod on the ZX8 1 computer.


Using INPUT
Another way to give the computer data is with the word
INPUT This lets you put in information while the program
is running, and you can use different data each time

you run the program,

20 INPUT A
30 INPUT A$

For words

Y ou use INPUT with a laJbe such as A for a


1 printing a question mark, or other symbol,
numb er and AS for a string. When the on the screen. Then you type in the data
computer meets the word INPUT in a and the computer stores it in the memory
program it puts the label on a memory space and goes on with the rest of the
space and asks you for the data, usually by program.

me
INPUT programs Your a mmzw
J RUN number and
750 words.
Computer's
10 INPUT G ^tion 7FIFTY-SIX SIXTY
20 INPUT BS marks 56 TWO
30 PRINT G FIFTY-SIX
40 PRINT BS ALLOWED,
50 END f
You have to
press NEWLINE rYou cannot puH
efter each input astringina
number variabJe

Picture 2 shows what happens when you prints another question mark for the
run this program. When the computer INPUT instruction in line 20. This time you
meets the word INPUT in line 10 it prints a have to type in words or symbols as the
question mark on the screen and waits for label B$ told the computer to expect a
you to type in a number for G. Then it string.

10 PRINT "WHAT IS YOUR NAME’ RUN

F 20
30
40
50
INPUT NS ]
PRINT “HOW OLD ARE YOU”
INPUT A
PRINT NS
WHAT IS
7RUSTY ROBOT
YOUR NAME

HOW OLD ARE YOU


?77
60 PRINT “IS" RUSTY ROBOT
70 PRINT A IS

END 77
Li 60

Ifyou have a computer, try typing in this inthe sample run above. Try it lots of times
program, then press RUN to start it off. with different data, pressing RUN to start
When the computer asks you for theprogram again each time. The
information, type in your name and age, or computer always prints exactly what you
a silly name and crazy number, as shown putin N$ and A.
Poetry writing program

Now you know enough BASIC to write a poem on a computer. Here is a poetry writing
program which uses PRINT and INPUT.

10 PRINT “WHAT IS YOUR NAME'


20 INPUT N$
30 PRINT "A POEM BY" This line prints ;um
40 PRINT NS] out your name. WHAT IS YOUR NAME
?SAL
50 PRINT "TYPE IN A WORD" A POEM BY SAL
60 PRINT "THAT RHYMES WITH ME" TYP£ IN A WORD
70 INPUT AS THAT RHYMES WITH ME
00 PRINT IS THE POEM"
“HERE ?BEE
HERE IS THE POEM
90 PRINT "COMPUTERS USED TO COMPUTERS USED TO
FRIGHTEN ME" FRIGHTEN ME
100 PRINT "BUT NOW I’M HAPPY AS NOW M HAPPY AS
J

BUT l

1 10 PRINT AS ]— E
120 END KL
This line prints V~^You type run to try it

out your word. (again with another


ar word
The program makes the computer ask you the poem at line 1 0. If you have a
1

your name then store your reply in N$ and


,
computer try running the program lots of
print it out at line 40. It stores the word you times, inputting different words at line 70.
choose in AfE, then prints it out as part of

* Program puzzle
Can you write a program to get the computer to ask you your name and then print hello,
followed by your name and a message to you?

Checklist for typing in programs


1. Before typing in a new program type NEW. This clears anyold
programs and variables out of the computer's memory.
2 . W hen you are typing in he program re membe r to press
t ,

NE WLINE, or your computer's word, at the end of each line.


3. After typing in the program, check all the lines on the screen to
see if there are typing mistakes. Make sure none of the lines are
missing, too.

4. Next you can type CLS (or your computer's word) to clear the
program off the screen. Then type RUN to start the program.
5. To get the program listing back again to check it or alter a line,
type LIST, To display one particular line you can usually type
LIST with the line number, but check this command as it
varies slightly on different computers.

6. To stop the program while it is running type BRE AK or


ESCAPE- Check this command in your manual, though,
as it varies on different computers, On some computers
ESCAPE wipes the whole program out of the computer's
memory. To start the program again type RUN-
Doing things with
These were
PRINT PRINT A
HELLOS
^ stored In
memory
34
IWISH WAS AS I
spaces X$
and A,
CLEVER AS A ROBOT
X* *X

VSkt'i
f
YH*H WAs AS
>
^ PRINT

OFtE*. ASA ROBOT

Bo you have seen how to use PRINT to


far PRINT to do calculations on a computer
display words and numbers on the Y ou can find out how at the bottom of the
screen, and to print out the contents of page. On the opposite page you can find
variables. Below you can find out how to out more about doing things with
use commas and semi-colons to space variables.
things out on the screen. You can also use

Commas and semi-colons


10 PRINT 1 AM SPACED
H 11

; 1_ -
r t AM SPACED OUT
"i
30 PRINT 'OUT ^ Comma J

10 PRINT "I AM SQUASHED" - | AM squashedup


20 PRINT UP Semi-colon,

10 PRINT 1 AM REALLY" l
AM REALLY The word PRINT
20 PRINT by itsell made
30 PRINT “SPACED OUT’ SPACED OUT this empty line.

These lines show how you can use is The picture above shows how the lines
commas and semi-colons to tell the would be printed on the screen. The word
computer where to print the next letter, A PRINT on a line by itself tells the computer
comma tells it to move along the screen a to leave an empty line.
bit and a semi-colon tells it to stay where it

Doing sums
PRINT 83-5 PR^KT 3GR-Cl£l)
78
PRINT 83*5
,4 means 415
/ multiply, PRINT SQR(121>
11
>/ means divide
and SQR means PRINT 85/5 PRINT
uare rool 17 &S is

You use PRINT like this to tell the


computer to do sums. You use the normal The computer can also do more
signs for addition and subtraction and * complex mathematical calculations such
for multiplication and / for division. as sines, cosines, square roots, etc.
More about variables On most computers you A
need to leave a space
either side of the
yaria bfe, inside t he
Spaces quotes.

PftllNT 'i
/\
ATE ".X:“ PEANUT BUTTER AND AS: SANDWICHES
! ATE 6 PEANUT BUT'EB AND CHEESE SANDWICHES

PRINT "I ATE Z



PEANUT BUTTER AND " CS. " SANDWICHES
;
11

I AT£ 12 PEANUT SUTTER AND JAM SANDWICHES

Printing variables by themselves is not the variable must have a semi-colon either
very useful. You usually need some words side of it, as shown above. If you want to
with them to say what they are To print space out the information you can use
words and a variable together the words commas instead of semi- colons.
must be in quotation marks as usual and

Spaces

PRINT "I
-A
" X " PEANUT
ATE ; ;

BUTTER AND ";C$;" SANDWICHES"


I ATE 7 PEANUT BUTTER AND
JAMMY SANDWICHES

J
During a program you can change the Next time you ask the computer to print
contents of memory space s like this To the variables it will display the new words
the computer these statements mean add and numbers stored in the memory

add W
one to the figure in memory space X and
to the letters in C$.
spaces.

Program puzzles
10 LET A=9 Multiply Write a program to add numbers to
1.
20 LET B=7 Z' the variables in the program on the left
30 PRINT A*B so that it would print out the answers
40 PRINT A/B 100 and 1 on one line with a space

50 END v between.

RUN Dr
Divide
2.Change lines 30 and 40 so that they
63 pnnt out the numbers, what you are
1.28571 doing to them and the answer e.g. ,

times 9 is 63".
You can do sums with variables too, as
3. Change your answer to the program
shown in the program above. The
puzzle on page 15 so it prints your name
computer finds the numbers in the
and the message on one line.
memory spaces, then works out the sums.
How computers compare things Of rr is coufcsr

One of the most useful things a computer can do is to compare/^™^


pieces of information and then do different things according wear tm
v scm.
(
to the results. To do this you use the words IF THEN.. . . .

IF A=B THEN PRINT "THEY ARE EQUAL 1

If A>S THEM PRINT "A IS BIGGER"


IF A<8 THEN PRINT "A 1$ SMALLER"
IF AoB THEN PRINT 'THEY ARE NOT
EQUAL"
>
Greater than

The computer can do several different These lines show how you use the
testson information to compare it. The symbols with IF and THEN' to make the
symbols for the tests are shown above. It computer compare two pieces of data.
can test to see if two pieces of data are You can compare any kind of data -
equal, different* or if one is greater or less words, numbers and variables, i.e. the
than the other. cent ents of memory space s too ,

^ Weather program
10 PRINT "WHAT'S THE WEATHER LIKE TODAY"
w
f *1 RUN
WHAT'S THE WEATHER
20 INPUT W$ liketoday
30 IF W$ -"RAIN'' THEN PRINT "UMBRELLA TIME' 7SUNNY
40 IF WS- "SUNNY" THEN PRINT "GOOD" GOOD
RUN
50 END WHAT'S THE WEATHER
UKE TODAY
7 RAIN
k
,

UMBRELLA TIME

Here is a program using IF and THEN. At out one of the responses. If you put in a
line20 the computer stores the word you different word at line 20 nothing will
input in variable W$. Then, at lines 30 and happen. You could change the words in
40 checks to see if the word in W$ is the
it lines 30and 40, though, then try inputting
1

same as "rain” or “sunny If it is> it prints . one of the new words.

rs Age program g French lesson


10PRINT 'HOW DO YOU SAY RED
^
OLD ARE YOU
10 PRINT “'HOW
1 '
IN

20 INPUT A
FRENCH 1 '

20 INPUT AS
30 IF A:M6 THEN PRINT "QLD" J,

40 IF A< 1 6 THEN PRINT "YOUNG 1 ' 30 IF AS RQUGE" THEN PRINT ''CORRECT 1

40 IF ASo^ROUGE' THEN PRINT "NO.


SO IF A 16 THEN PRINT 'MUST RIGHT 1 '

ROUGE"
RUN RUN
HOW OLD ARE YOU HOW DO YOU SAY RED IN FRENCH
?1G ?B1EU
JUST RIGHT NO. ROUGE
age program, the computer
In the right". In the other program the computer
compares input A with the figure 1 6, If it is prints out one of two different responses
bigger than 16 it prints "old”. If it is smalle r depending on whether AS equals “rouge 11

it prints “young" and if it is 16 it prints 'just ornot-


18

r V ogram puzzle ~ Can you write a program to get the


1

correct' or give you the right answer?


computer to ask you sums, then either prim
/ These two lines
Branching programs make the computer
\

{
branch to other pa rts\
IF A=6 THEN LET A$-“SDT vot the program.
to INPUT K$
J IF K$="YES" THEN
20 GOTO 100
IF X=Y 2 THEN LET Z=0 30 IF K*="NO" THEN GOTO 200

IF S = T THEN STOP
100 PRINT YOU TYPED YES
IF R< 10 THEN GOTO 30
110 STOP

200 PRINT YOU TYPED NO"


210 END

You can give the computer almost any not the ZX81 ,
you can leave out the word
instruction after the word THEN, as shown GOTO.) You usually need a STOP
above, A useful instruction is to make it go programs with GOTO, or the
instruction in
to another line. (On most computers, but computer will go on repeating the
program endlessly.

Maths program RUN


TYPE IN A NUMBER
71?
10 PRINT “TYPE IN A NUMBER TYPE IN ANOTHER NUMBER
20 INPUT A 71B4I

30 PRINT “TYPE IN ANOTHER NUMBER'" DO YOU WANT TO


ADD, SUBTRACT, MULTIPLY
40 INPUT B
DIVIDE OR STOP
YOU WANT TO"
m
SO PRINT “DO
PRINT “ADD. SUBTRACT. MULTIPLY"
7ADD
2 oi * — Computer's
65 PRINT "DIVIDE OR STOP"
TYPE IN A NUMBER answer
70 INPUT CS
80 IF CS "ADD" THEN PRINT A-B
In this program the numbers you type in
90 IF CS 'SUBTRACT" THEN PRINT A B
are stored in A and B and your instructions
!0D IF CS MULTIPLY” THEN PRINT A*B are stored in CS, At lines 80 to 120 the
110 IF CS “DIVIDE" THEN PRINT
-
AB computer compares CS with five different
120 JF C$="STOF THEN STOP words, and when it finds the right word, it
m GOTO ]0 carries out the instruction. It passes over
all the lines which are not True.

Age guessing program f CAN YOU WRTTE


'

l the program -

FOR THIS
rr
;
10 PRINT "GUESS MY ACE ' GUESS MY AGE
1
20 INPUT G 71

30 IF GOU THEN PRINT YOUNGER THAN THAT


"TRY AGAIN"
713
40 IF G<> 14 THEN GOTO OLDER THAN THAT
20
714
SO PRINT "'CORRECT'
i

|£0 END

This program will go on repeating itself


J 11
CORRECT

"correct Can you alter the program so


.

until G- 14, When G- 14 the computer will that it gives you some clues, as shown in
pass over lines 30 and 40 and print the picture on the right?

19
Programs with lots of BASIC
The programs on these two pages use most of the BASIC
covered so far. The first program is a space game for two
people to play with the computer, If you do not have a computer,
study the programs and try and follow how they work,

Space commando

10 PRINT “ALIEN’S SQUARE ALONG”


20 INPUT A Lines 10 to 40 store alien's

30 PRINT '
ALIEN'S SQUARE UP"
co-ordinates in and B, A
40 INPUT B
Line 50 dears alien’s numbers
SO CIS ]
offscreen
60 PRINT 'COMMANDOS SQUARE ALONG"
Lines 60 to 90 store
70 INPUT C commando s co-ordinates
80 PRINT "COMMANDO'S SQUARE UF r

in C and D,
90 INPUT D
This line works out
100 CL$ how far apart they are
110 LET X = SQR(( A-C) * (A-C) + (B D) * and stores the answer
inX.
120 PRINT ,l
YOU ARE NOW 11

130 PRINT X; SPACE UNITS APART IfX is less than 1.5 the
X<1.5 THEN PRINT "ALIEN FOUND"!
— program stopslf it is

%
140 IF
more than LSthe
150 IF X<LS THEN STOP j program repeats,
155 PRINT “WHAT ARE YOUR NEW POSITIONS"
160 GOTO 10
170 END

In this game, one person is a hostile alien


and the other is a space commando trying co-ordinates of their positioiCand the
to catch the alien. Each piayer draws a computer then works out ho w far apart
secret map on which they plot their they axe. The players use the computer's
positions {you can find out how to do this figures to help them work out their next
below). They give the computer the grid moves.

1 "

How to play 20 ' .


!

i.i
|
18

For their secret map, each player


1,5
draws a grid of 20 x 20 squares and
numbers them as shown on the right. U
. ®
The alien starts in the left side of the Alien

grid and the commando starts in the
right. Each turn, they can move two ]o

squares up, down, sideways or B

diagonally and then give the computer


£
their new positions. When they are less
than 1.5 space units (i.e squares) apart, *
ll
the commando has caught the alien 2 Commando
I

20 0 2* £ S Id 12 ]* 16 1# 30
How to make the computer look clever
program the computer appears to respond to your answers to its questions. You
In this
can see how the program works in the pictures at the bottom of the page. The program
uses INPUT in a slightly different way which makes the program shorter and easier to
read.
the ZXS1 you have to type
||F 10 PRINT 'GJVE ME A NUMBER

wjuT^
10INPUT "GIVE ME A NUMBER" N
Nj&IWPirr N .

;
|
RUN
20 INPUT "AND ANOTHER" M "
30 PRINT N;' TIMES ";M;
1
;

GIVE ME A NUMBER?10 S
AND ANOTHER78 J
^
™ r
BC rrT^roB EJ
10 TIMES 8 IS 80 CT2 Sf*
fdoes n otnee d a se riicocmj
On most computers (not the ZX8 1 ) you can When you run the program the input
make the INPUT line clearer by putting question mark appears after the words.
words in quotes before the variable name.
The program
S LET C=Q
10 PRINT 1 WOULD LIKE TO TALK TO YOU’’ This is the new input way. Your
20 INPUT 'TELL ME ANYTHING SILLY THAT reply is stored in AS
HAPPENED TO YOU THIS WEEK”; A$ At line 30 the computer looks
30 READ B$ ] for the first line with DATA and
40 PRINT B$; * — This makes the computer stay on the same line.
takes the first item and puts
BS.
it in

50 INPUT c$y Your reply is stored in C$.


60 LET C=C+ 1
Variable C in lines 60 and 70 is
a counter. It keeps count of the
70 IF C-6 THEN GOTO 100
number of times the program is
60 GOTO 30 > repeated When C = 6 all the
90 DATA WHY, WHY IS THAT data items have been used and
95 DATA WHY, CAN YOU EXPLAIN the computer moves on to line
100
SB DATA CAN YOU SAY WHY, WHAT WAS THE REASON .

100 PRINT ”SG THE REASON YOU TYPED" *“


Line 80 makes the computer go
PRINT H AS back to line 30 and replace the
Wo PRINT WAS REALLY GIVEN BY YOUR ANSWER”
l
data in BS with the next item in
the data list.
130 PRINT “ ";C$
140 PRINT HOW ODD! '
h

The spaces in lines 1 10 and 130 leave

150 PRINT 'RUN ME AGAIN FOR FURTHER spaces on the screen before your
ENLIGHTENMENT” replies. It does not matter how many
spaces you leave in the program.
160 END
How it works
RUN
1 WOULD LIKE TO
^ WHY
TALK TO VQU
TELL ME ANYTHING
SILLY THAT
HAPPENED TO YOU
THIS WEEK?
BP WASNt|

MJD0KW5 WHf fte


I wa'j qoiNfi

I WAS LKKlNQ BECAUSE WAS HIDING

r iOTHE REASON YOU TYPE131


1 IT.
IT OFF MY F- INCURS FELL DOWN A HOLE
I
ile’
WHAT WAS THE WAS REALLY GIVEN HY
REASON YOUR ANSWER
DIDN'T WANT MY
I
BECftU&t FRIEND TO SEE I

IT MELTED. I WANT MY~


DIDN’T HAD AN ICECREAM
FRLEMD TQSff |
HOW ODD'
HADAN ICECREAM RUN ME AGAIN FOR
FURTHER ENLIGHTENMEN
21
Drawing pictures
A computer makes pictures by
lightingup little rectangles on the
screen. Each rectangle is called a
pixel and each pixel needs a
separate instruction from the
computer to switch it on. Most
computers can also make the
pixels different colours.
On these two pages you can find
outhow to use BASIC to make L
You can usually see the pixels in a
J
simple pictures on the screen. The computer picture. A computer with a
instructions given here are for large memory, though, can make pictures
single colour pictures only with thousands of very small pixels. These
pictures are called high resolution graphics.

The instruction for lighting up a pixel On a computer with high resolution


varies on different computers, but it is graphics you may be able to plot 1000
usually something like PLOT {X, Y). X and points along the screen and 1000 up. A
Y are the pixel’s co-ordinates and X is less powerful computer has about 60 x 40.
the number of pixels along and Y is the (If you have a computer, check the size of

number of pixels up. your screen as you may get a bug if you
plot outside its range.)

5 Remember™ some
computers need a
general graphics
instruction, £

Pictures made by a computer are usually You can also switch a pixel off with a
called graphics. Some computers need a command such as UNPLOT (X, Y). In the
special command before you do graphics. programs in this book we use PLOT and
For instance, on the BBC micro you need UNPLOT. If you have a computer check
the word MODE with a number. *
these commands in your manual.

'For the programs in thisbookuse MODE Son the BBC micro with the plot command PLOT 69, X, Y.
For unpbtting use PLOT 71, X. Y,
Plotting program
varies on
different
10 PRINT "TYPE IN l computers. J fa RUN
TWO NUMBERS" S ,
'
TYPE IN TWO NUMBERS
20 INPUT X -U a 724
30 input y Jmamm 724 .^ lSlpiXel
40 PLOT (X,Y) UV_ jtl
TYPE IN TWO NUMBERS
SO GOTO 10
730 •
/'t'ou have to press <; 715 ^ 2nd pixel
NEWLINE or RETURN after
(
V inputting each number ./A JU ^
This short program asks you for two Line 50 makes the program repeat itself
numbers* then plots the pixel with those endlessly and the only way to stop it is
numbers as co-ordinates. If you try this withBREAK (or the computer's own
program make sure the numbers you type word). Can you insert a counter (see page
in are within the range of your computer. 21) to make it run, say, six times.

Plotting a picture

10 LET X-10
20 LET Y=1G This plots
30 PLOT (X,Y) I
a diagonal
hne g°mg down,
40 LET X-X+ 1 |

SO LET Y-Y-l J
60 IF X<14 THEN GOTO 30

100 LET Y=Y+ T_


1

110 LET X-X+l rJ^Kup.


y y P
130 PLOT (X,Y) J
130 IF X<20 THEN GOTO 100

First you need to draw the Then you can work out he program to plot all the
t

picture on squared paper squares. By giving X and Y starting values, then adding
and work out the to them or subtracting from the m, and repeating parts of
co-ordinates of the the program, you can make the computer plot
squares. sequences of pixels as shown above.

X-5.Y+10 X*3, Y *3
moves picture makes an
up and left . exploded
image.

'm
Original
picture -
M You can really only make very simple
pictures with PLOT. To make more
After writing the program it is easy to complicated ones you need special
change the picture by altering the equipment such as a graphics tablet. You
numbers. You can move It to a different place a drawing on the tablet and trace
place on the screen by changing the over it with a special device called a
starting values, or multiply all the numbers “puck". This automatically reads the co-
by three to make an "exploded image'
1

.
ordinates into the computer,

Program puzzle - Can you write a program to plot your initial on the screen? There is a sample
program on page 44.
Playing games

When you throw a pair of dice you cannot The computer contains a special
predict what the numbers will be. The program for producing random numbers.
chances are equal that the numbers will Sometimes it repeats the same number
be anything from one to six. You can several times, but in sequences of lots of
produce unpredictable numbers on a random numbers, the number of times
computer. They axe called random each number is picked is about even.
numbers.

RND(O)
PRINT RND
.662741814
RND{1) PRINT RND(99)

Or RND(O), or
{ND11 on some^
}

computers.
i__.
To make the computer produce a random The R ND instruction always produces a
number you use the word RND. Some number below one. On some computers
computers need a or 0 in brackets after
1 you can put a number in brackets after
the word. you have a computer, check
If RND, e.g. RND(99) This makes it produce
your manual for the correct command. a whole number between and the1

number in brackets.

IT R m(RMHl)*fcOdj

On other computers you need the word This instruction means pick a random
1NT (short for integer, meaning whole number and store it in variable R. In the
number) followed by the RND instruction programs in this book we use
(either RND( 1) or RND(Q) on different INT(RND(1}*60+ 1) to mean pick a
computers). Then you multiply by the random number between 1 and 60. You
highest number you want and add one so may need to convert this instruction for
24 the number is above one. some computers.
Program puzzle Can you work out how to make the computer pick a random number
between 10 and 20?
Space attack
This is a program for a game using

random numbers In the game you are on


a star ship being attacked by a wave of
Your ship's computer
alien fighters.
locates the aliensand gives you their
coded positions. To hit each alien you
have to work out the firing range by
multiplying the codes and typing in the
answer-

10 LET C-0 ] - C is a counter to count the number of times


theprogram i$ repeated. Each time, line 60
20 LET A=INT(RND(1)*20+ 1)
adds ItoC.
30 LET B=INT(RND(l)+20+ 1)
40 PRINT "ALIEN SHIPS These two lines produce random numbers
46 PRINT ’ARE
" for the alien ship's codes and store them in

50 INPUT X
AandE.
60 LET C=C+1 Your number is stored in X.
70 IF X=A*R THEN PRINT "ALIEN SHIP In lines 70 and 80 the computer
DESTROYED’ 1

checks to see if you got the


X<>A*B THEN PRINT ’MISSED"
30 IF
90 IF
END
C<6 THEN GOTO 20 ]— — right answer.
This line repeats the program if
100 C is less than 6,

Running the program RUN


The picture on the right shows what ALIEN SHIP'S CODES
ARE 1? 3 FIRE The comma in
happens when you run the program. If you line 45 spaced
?41
type m the correct answer for the two out the numbers
MISSED
numbers multiplied together the ALIEN SHIP'S CODES like this.
11

computer will print "alien ship destroyed .


ARE 11 6 FIRE
If your answer does not equal A x B the ?55
computer prints “missed
11

,
ALIEN SHIP DESTROYED
ALIEN SHIP'S CODES
ARE 13 6 FlFte
Program puzzle
Can you add another counter to the program to count your number of hits and print
out your score at the end of the game? You need to set up a variable called S andgive
it a value of 0 to start with, then add 1 for eachhit

'Computers
Random pattern program commands
This clears the program off the forCLS,RNDandj
5 CLS -
J screen before the ptxeis are plotted. PLOT may vary
10 LET X — INT(RND( 1)* 30 + 1) and some wi ll

The random numbers must fit on the need a graphics


20 LET Y=INT(RND(1)*30+1) computer’s screen. A

30 PLOT (X Y)n

This line makes the program repeat


40 GOTO 10 ] endlessly.

This program uses random numbers to you see less pixels appearing as many of
on the screen Lines 10
plot spots of light them are already plotted. To stop the
and 20 produce random numbers program you have to type BREAK or
between 1 and 30 and store them in X ESCAPE, or another word on different
and Y. Line 30 then plots the pixel with computers,
co-ordinates X,Y. As the screen fills up
25
Making loops
You often need the computer to do the same thing several times in a
program. On page 2 1 you can see how to make it repeat part of a program
using GOTO and a variable which acts as a counter. Another way is to
repeat the same lines several times using the words FOR TO and . .
.

NEXT. This is called making a loop.

Hello loop
J
10 FOR J= 1 TO 6 v
20 PRINT "HELLO") Loop
30 NEXT J
*
40 END
This program has a loop from lines 10 to
30 which makes t he computer repeat
line 20 six times. The letter ] is a
variableand line 10 tells the computer
1 on the first run through the
to set] at hello and line 30 tells it to go back and
program, 2 the next time, then 3, etc., up find the next value for]. When J = 6 the
to 6. Line 30 tells it to print the word computer goes on to line 40.

In this program, the loop from lines 10 to sum. After doing it eight times the
30 makes the computer repeat line 20 computer carries on with the rest of the
eight times. Each time it passes through program. Line 40 just makes it leave an
line 20 it prints out the same silly empty line.

Eight t imes table program


J
10 PRINT "THE EIGHT TIMES TABLE'
TABLE
20 FOR
J= l TO 12
30 PRINT J* 8
40 NEXT - J Lo°P
J

SO END

This time J is used to count the number


of loops and also as part of the sum
J*8.
Line 20 tells the computer to set J at 1,
then 2. 3, etc, up to 1 2. Line 30 takes the
current value of J, multiplies it by Sand
prints out the answer. Then line 40
sends the computer back to line 20 to
find the next value of J.
Making patterns

FOR . NEXT loops are useful for making 10 FOR 1 = 1 TO 45


patterns, like this, of a simple shape 20 Draw a rectangle and change its
repeated lots of times. The program for position a little each time,
this pattern is too long to write out here in 30 NEXT I

full, but it would look something like this: 40 END

Steps
Sometimes it is useful to change the value of] by amounts other than For instance, you 1 .

may want to go up in 3s or down in 7s, To do this you use the word STEP. In the following
program STEP - 1 makes J go down by each time the computer passes through the
1

loop in lines 10 to 40.

Greedy computer program


rThe figure 2 stops the loop after
THERE ARE PIES LEFT ”1
yj= 3 (Le.wheti therein one pie THERE ARE PIES LEFT
5 CLS
left) ' THERE ARE PIES LEFT
,10 FOR J-? TO 2 STEP -1 ^ LEFT / Some computers
THERE ARE PIES
20 PRINT “THERE ARE PIES LEFT’
THERE ARE PIES LEFT
ares l° wer than
I
I

30 NEXT J THERE ARE PIES LEFT/


othersandihey {
Loop n eed a ewer fig u re
40 PRINT j
I

SHALL EXPLODE suchasBOGor


“I SHALL EXPLODE”
(
50 PRINT
I

V 250 in line 60.


60 FOR K= 1 TO 1000 s BANGSPLATT
70 REM: DO NOTHING J

( 80 NEXT K *io0p
90 PRINT
100 PRINT "BANGSPLATT
There are two loops in this program. The have to do anything. It just runs through all
one from lines 10 to 30 makes the the values forK from 1 to 1000 and this
computer print line 20 six times. Each time, makes it pause for a moment. Lines which
the value of J is reduced by one and the stan with REM (short for remark) are
figure for J is printed in line 20. In the loop ignored by the computer and are useful to
from lines 60 to 80 the computer does not remind you what the program is doing.

Program puzzles
L Can you alter the eight times table need to get he computer to ask you for
t

program on the left to make it display a number N. Then use a loop to work
:

1 x 8-
11
” as well
as he ans we r?
t out and display the tables. If you want,

2.Can you write a program forthe "W include some lines at the end of t he
times table, that is, a program which program so it asks you if you want the
works out the tables for any number tables for another number and the
you type into the computer? First you program repeats itself.
27
Tricks with loops
Here are some more programs using loops. Below you can find out how
you can use loops within loops to repeat several things at the same time.
These are called nested loops.
Nested loops
|
5 PRINT T T p

,10 FOR 1=1 TO 3


*20 FOR J =1 TO 3\
30 PRINT Ip I J loop
;
4G NEXT ] -r
Hoop
v
50 NEXT I
*
60 END
This program has an loop and a J loop. I each time. The picture
out the value for J
The J loop is nested inside the I loop and above shows the result of this program.
for each time that the I loop is earned out, The commas spaced the figures out like
the J loop is repeated three times, printing this.

Computer clock 0:45 ^ugsin loops


CL5 5
10 LET M=0
10 FOR 1^1 TO 4
/to time
set the FOR J=1 TO
m LET S=Q usethis delay loop:
L20
30 PRINT 1
4

30 FOR M=0 TO
^ 40 PRINT
*40 FOR S=0 TO 50 x \ 54 FOR Z -1 TO 100 i
J
SO NEXT 1

f
50 PRINT } V5 S NEXT Z NEXT J

^60 CLS Seconds


70 NEXT S loop /J
'BO NEXT M ’^Minutes ylBoth parts of a
90 END loop \
nested loop must
( be inside the other
Inside a computer there is an electronic
“dock" which sets the rhythm for all the The seconds loop is carried out S3 times
computer s work. The clock pulses at for each minute loop. If you try this
between one and four million pulses a program on a computer it might run very
second. This program makes the fast at first. You need to put in an extra
1

computer behave like a digital clock. “delay loop then set it by changing the
,

It has nested loops, one to count the figure in the loop so your computer dock
seconds and one to count the minutes. "ticks" at the same rate as a real one,

Random number tester


10 FOR 1=1 TO 1-000 RUN
20 LET R=INT(RND<1)*6+1) FINISHED
30 IF R- THEN LET A=A+I
1
162 168 167
40 IF R=2 THEN LET B-B+I
160 187 156
50 IF R =3 THEN LET C=C+1
60 IF R ~4 THEN LET D-D+l
:

70 IF 1=6 THEN LET E-E+ This program shows if RND really


80 IF R-6 THEN LET F-_£±I works. The loop from lines 10 to 90
90 NEXT I makes the computer pick a random
This program takes
100 PRINT 3 Jong longtime.
r
number between 1 and 6 a thousand
110 PRINT A, B, C You can makeit times. It keeps count of how often each
120 PRINT D ( E, F shorter bychanging number is picked in the variables A to
130 END thenumberin line 1 F, then prints out the results.*
23 Xp 500 or even 250. ^
j

*On some computers, e.g. ZXB 1 and BBC micro, you need some extra lines at he beginning of the t

program to set each variable toO.


Pattern repeat program
'or computers which
have high resolulion
This program uses nested loops to repeat a small pattern ail over the
graphics use farger
screen. The program looks quite complicated but if you read it through random numbers,
carefully and work out what each line does, you will soon see how it on BBC micro
e g.
works. The shape of the pattern is decided by random numbers and change figure in
will be different each time you run the program. Jines 10 to 40, to GO,

5 CL5
10 LET A = INT(RND(1)*G+ 1)
These lines choose the random
20 LET B=IOT(RND{1)*7+1)
numbers for the pattern and
30 LET C=INT(RND(1)*6 + 1) store them in A, B, C and D.
40 LET D=INT(RND(1)*4+1}
Lines 50 and 60 ask (or t he width ( W) and
50 INPUT 'HOW MANY POINTS
height (V) of y our screen.
ACROSS THE SCREEN" W ;

60 INPUT ‘HOW MANY UP V The 1 loop counts the number of times the
'

pattern is repeated up the screen. Each time,


m CLS is increased by the height of the screen (V)
I

70 FOR 1=0 TO V STEP V/6


divided by 6, so the pattern is repeated six
3Q FOR J=0 TO W STEP W/6
f

f
times up the screen
90 PLOT J+AJ + B)
Each time the loops are repeated, lines 90 to
100 PLOT (J+AJ+C) 1 20 tell t he computer to plot four pixels using

110 PLOT 0+0,1+D) (he current values for I and f plus the random
120 PLOT (J+B,I+D) numbers.
1

130 NEXT J The J loop counts the number of limes the


'
140 NEXT I pattern is repeated across the screen. It works
ISO END in the same way as the I loop.

How works it O
6
1
6
5 • 2,5 12,5*
4 First pattern Second pattern
3 • 3.3 12,3#
2
1 3, 1 ® • 5.1 13,1# *15,1

0 4 4 6 8 10 12 "14 16 IB 20

Imagine that the computer On the first run through the program and) are 0 so the I

has chosen the random computer plots the first pattern of dots using only the
numbers 2, 6, 3 and 1 and random numbers. Line 130 sends it back to find the next
that the width and height of value fox J which is J + 60/6, i.e, 10. Then it plots the
the screen axe both 60. second pattern using the random numbers plus 10 for J.
This repeats the pattern along the screen.

The computer repeat s the J loop six times , is 1 0. J is set to 0 again and the computer
each time adding 10 to J and so plotting he t plots the next line of patterns using 10 for i
pattern further along the screen. It then and increasing J by 10 each time as before,
goes back to find the next value for I which 29
Program puzzle Can you write a pattern repeat program which repeats a space invader
-
shape over the screen? There are some hints to help you on page 45.
Subroutines
A subroutine is a sort of mim-program within a program. It carries out a
particular task, such as addingnumbers or keeping a score, and you can
send the computer to it whenever you want this task carried out, This
saves writing out the program lines each time and makes the program
shorter and easier to read and type into the computer.

Shopping routine /GO OUT OF THE. ODOR /SEE SHOPPING,


i 2 r turn left, left Again SUfeftflUTWJE
BISCUITS
.

COME
BUY
go INTO SHOP, ftUY f ,

V^PLUMS.COME /
^7 HOME Ar

you had a robot helper whom Each time you wanted the robot to buy
you could program to run errands for you. something you would have to give it the
If you wanted something from the shop same instructions. It would be much
you would have to give it precise simpler to give the robot a shopping
instructions telling it how to get there. subroutine and tell it to refer to it each time.

4 Shopping program
10 PRINT “WHAT DO YOU WANT FROM THE SHOP”
20 INPUT X$
Line 30 sends he e

30 GOSUB 100 computer to the first


line of t he subrout me.
PRINT “ANYT
50 INPUT MS You need the word
= STOP at the end of the
60 IF M$ “YES” THEN GOTO 10
main program to stop
70 STOP the computer
carrying on into the
subroutine.
100 REM: SHOP SUBROUTINE Ii is useful to label a
PRINT “GO OUT, TURN LEFT
1

110 subrout ine with a


REM line so you know
120 PRINT “LEFT AGAIN, ENTER SHOP” what it is for.
130 PRINT “BUY X$ ;“ COME HOME”
This sends the
RETURNS-
140
^ Ifyouforg etthe
computer back to ltne
40 - the line after
/RETURN line you get a bug GOSUB.

InBASIC, to tell the computer to go to a number. The computer automatically


subroutine you use the word GOSUB with goes back to the instruction after the one
the word RETURN at the end of the where it left the main part of the program.
subroutine. GOSUB should be followed by You can send the computer to a
the number of the first line of the subroutine anywhere in the program as
30 subroutine. RETURN doe s not need a line many times as you like.
Gosub programs
A subroutine is useful for carrying out any task which you want to repeat several times at
different stages in the program. Here are some more programs with subroutines.

Numbers program Conversion program


50 INPUT A 100 INPUT 'DISTANCE ;M
50 INPUT B 110 INPUT "TIME” T :

70 GOSUB 250 120 GOSUB 200


HN
50 PRINT "A DIVIDED BY B ;AB 130 PRINT 'AVERAGE'
50 GOTO 50 140 PRINT MT“ MFH AND " K/T
; ; ;

250 REM; SUBROUTINE TO STOP 150 STOP


260 IF A-0 AND B~0 THEN STOP 200 REM: SUBROUTINE TO CONVERT MILES
iC 270 RETURN 210 LET K=M*LG09
I \

This subroutine provides an escape from


( 220 RETURN

the program. If you want to stop dividing this is a subroutine to convert miles to
you input 0 at lines 50 and 60 This kilometres. Y ou can often use the same
program does not need STOP before the subroutine in lots of different programs.
subroutine as line 90 sends it back. Check that you use the same variable
names, though.
Circles program
1 Centre of circle = X,Y
2 Radsus of circle =R
3 Colour - X ^^
4 Gosub 10
5 Goto 1
f 10 Rem; Subroutine to draw circles
II Draw a circle with centre X.Y;
radius R and colour X.
L
12 Return
Subroutines are useful in graphics the program. With this program you could
programs like this to draw diagrams with draw lots of different circles by givingthe
numbers worked out in the main part of computer different information in lines 1 to 5
Quiz program
At line 20 the computer looks
5 LET C=0 for the data line and puts the
WERE THESE THINGS
1

10 PRINT 'WHEN INVENTED?’ first word item in G$ and he I

20 READ CS. F ] first number item in F.

30 PRINT CS ] This prints out the word in CS.


40 INPUT A
50 LET C=C-kl The counter C stops (he program
60 IF C=Z THEN STOP afterit has repealed three times as

70 GOSUB 100 there are only three data items for


80 GOTO 10 CSandF.

100 REM: ANSWERS SUBROUTINE This is the subroutine


110 IF ABS(A-F)<10 THEN PRINT '“OK" Each time the program is
ABS(A - F)>10 THEN PRINT "NO
1 ’

120 IF repeated the words and numbers


130 PRINT 'TRY ANOTHER ONE’ tnCS and F are replaced by (he
140 RETURN next pair of data items.

200 DATA TELEPHONE, 1576, PRINTING 1450, BICYCLE, 1791 ]


1

This program uses a subroutine to check


the answers to questions The correct it makes ihe computer check the
answers are stored in F and the person's difference between the numbers in A and
answers go in A. In lines 100 and 1 10 of the F(it ignores any minus signs). If the
H
subroutine the computer compares A with difference is less than 10 it prints OK". If it
F. The word MS
stands for "absolute’' and is more than 10 it prints NQ
L, la
. 31
Doing things with words
Most computers can examine the words stored in variables and do
various things with them. They can check the contents of a variable and
see if it contains a particular word or letter. This is useful for checking the
words input by someone using the program. Computers can also
rearrange the letters or words in a different order and add them to letters
in other variables. Below you can find out how you do these things in
BASIC.

On most computers,
butnottheZXSI,

V—
MLWHHH v° uca
10 A$="l AM STUPID" . - PRINT LEFT${B$,4)
20 BS="ONLY FOOLS THINK" word LET. ONLY
30 C$=B$+" "+A$ * PRINT LEFT$(B$,4) + " "+A$
RUN
ONLY FOOLS THINK AM STUPID I ONLY I AM STUPID

You can add the contents You can also add pans of
of two variables like this. variables, like this,
You need the space LEFT5(E$,4) means take the
between quotation first four letters from the left
marks to leave a space of B$.
between the words.

PRINT RIGHT$(A$,6) PRINT MID$(B$,6,5)


STUPID FOOLS

To tell the computer to use This tells the computer to take


letters from the right you the middle letters. The first
^When you
use RIGHTS with the name number tells it where to start
counting letters,
and the
of the string and the second tells it how
count spaces
numbers of letters you want and punctuation too many letters to take.

Note for Sinclair


users
10 K$="DING DONG
20 PRINT LENIKS) PRINT AS(6 TO 111
RUN STUPID
10 PRINT 8S(14 TO 1 G)
fNK ..

This means take


You can also find out the
letters numbers
length of a string - the
Stoll.
number of letters spaces
f

and symbols it contains. To


The Sinclair computers do
do this you use LEN short
not use LEFTS, RIGHTS and
1

for length.
MID$, but you can tell the
computer to take any letters
IF A$= COMPUTER BOOK
'
you want as shown above.
32
what is LEFTS A$ < r 8)?
RIGHTS EAS10J7
MlD$[AS^ 8|? r ^
Codemaker program
This program automatically puts words into code. Similar, but much more complex
programs are used by intelligence services to write and crack codes.
The easiest way to understand this program is to write a secret message on a piece of
paper, then work through the lines of the program carrying out the computer's tasks on
your message and writing them down.

LET C$=‘"’ 1
5
l
Sets up empty string variables.
LET D5=‘ " J
7
10 PRINT "TYPE IN A SHORT MESSAGE"
20 INPUT M$
This means the length of your
30 PRINT "NOW TYPE IN A SECRET
message minus 1.
NUMBER BETWEEN 2 AND”;LEN(M$)-1
N (your secret number) letters from
40 INPUT N
the right of M£.
50 LET A$=RIGHT$(M$,N) }
length of MS minus N number of
60 LET B$=LEFT$(M$ LEN(M$}-N)} n
” " Theletters from the left of MS (i.e. the rest
70 LET M$— A$+B$ ]— of the letters).

*30 FOR 1=1 TO LEN(M$) STEP 2 Replaces the letters in M$ with AS+ BS.
90 LET C$= C$ + M1D$(M$, 1, 1) From 1 to the number of letters in your message
(
' 100 NEXT I going up in twos, Le. 1, 3,. 5, etc. Each time the I
loop is repeated hue 90 takes one letter from
f1 10 FOR J=2 TO LEN(M$) STEP 2
position I of MS and puts ii in CS-
120 LET D$=D$+MID$(M$, J. 1)
( From 2 to the number of letter® in your
\ 130 NEXT J message, going up in twos, Le. 2 4 6 etc. ¥ ¥ S

140 LET M3 = C$ + D$ ] Works in the same way as the I loop.


150 PRINT "CODED MESSAGE IS” Replaces the letters in MS again.
160 PRINT MS
170 END

In lines 50 and 60 the computer uses your secret number


“Move tonight" and your to divide the message. At line 50 it takes four letters from
secret number is 4. These t he right of the message and puts them in AS At line 60 it
are stored in M$ and N. puts the rest of the letters in B$.

At line 70 it adds A$ and B$. Each time the loop repeats


I it puts an odd-numbered
This puts the letters from the letter in C$ (e g. I, H, M, etc ). Each time the J loop
end of the message at the repeats it puts an even numbered letter in D$ (e g. G> T,
front. O, etc.). Then it adds CS and D§ to make the coded
33
message.
Graphs and symbols
You can program a computer to present information in all kinds of
different ways, for instance, as words, numbers, pictures or graphs.
Complicated information can be made much easier to understand if you
illustrate it with graphs, picturesand symbols.

1 Drawing a graph

Imagine a peach tree whose yield of fruit With a computerit is very easy to draw a
increases each year in relation to its age .
graph of the way Y changes in relation to
This can be expressed as an equation, say X. To plot the grap h you need to find t he
Y=3X+ 2 (Y is the yield and X is the age). It value of Y for each value of X You can do
is hard to grasp what this means, though, this very easily in a program using the
and drawing a grap h would help . statement LET Y *= 3 * X + 2.

Thisis the program for drawingthis calculate Y and line 30 plots X and Y on the
graph The loop sets X at all the values
. screen. In graphs programs, you must
from 1 to 14. Each time the loop is make sure the maximum values for X and
repeated, line 20 uses the value of X to Y will fit on the screen or you will get a bug-

Computers and maths


which have several
Ln calculations Program puzzle
such as 3 x X+ 2, the computer
parts,
THINK OF A NUMBER
always does the multiplications or
DOUBLE ADD 4 IT.
divisions before adds or subtracts.
it
DIVIDE BY 2ADD 7 r

This means that the computer would MULTIPLY BY S SUBTRACT 12 r

give the same answer for these two sums: DIVIDE BY 4 AND TAKE AWAY 11
TELL ME THE RESULT.
PRINT 4*6 + 8 PRINT 8+4*6
THE NUMBER YOU FIRST THOUGHT
OF IS ,

Ifyou want the computer to do the sum


in a different order you use brackets,
like this:
Can you write a program to get the
PRINT <8+41*6 computer to carry out this well known
72 numbe r trick? (To find the number you
first thought of you subtract 4 from the
This time the computer adds 8 and 4,
result, then divide by 2.)
then multiplies by 6.
34
Birthdays program
This program uses another way to display information on the screen. It uses symbols to
compare the number of people who were bom in different seasons of the year. You
could use a program like this to compare, say sightings of a certain b ird in different
,

seasons, or thenumber of wins of different football teams. Before writing a long


program like this it is a good idea to write a program plan
Program plan
Ainu To compare the number of people with birthdays in winter, spring, summer and
autumn.
WINTER SPRING SUMMER AUTUMN

4
December September
January February October November |

1. Give the computer the data (Le. the


seasons when the people were bom)
Sample run
fora survey of 20 people.
2. Store the data in the computer.
RUN
3. Present the data on the screen.
WINTER TOTAL* ******
The prog ram SPRING TOTAL***
5 LET A=0 SUMMER TOTAL*****
Empty variables ready to AUTUMN TOTAL** * * *
6 LET B-0 use for running totals for
7 LET C=0 each season.
8 LET D=0
10 FOR 1=1 TO 20 ] Loop to make computer ask
20 PRINT PERSON
'

WAS BORN IN 1 ’
question once for each person in

! 30 PRINT "WINTER, SPRING, SUMMER OR AUTUMN" survey.


40 PRINT 'TYPE W. SP, SU OR A"
SO INPUT BS
60 IF B$= W” THEN LET A=A+1
,l
Lines 60 to 100 check the answer
70 IF B$= $F” THEN LET B=B+1
ll
in BS and add one to the variable

80 IF B$='W THEN LET C=C+I for that season.

\ 90 IF B$- A“ THEN LET D-D+l


lh

100 NEXT I ] Sends computer back to repeat question.


PRINT 'WINTER TOTAL *;
1

110
115 LET N= A The subroutine makes the computer print a
GOSUB number of stars equal to the number in each
120 200 }
variable.
PRINT 'SPRING TOTAL ’;
]——
1

130
135 LET N=B
140 GOSUB 200 By putting the total intoN each tune, the
computer can use he same routine for each
PRINT "SUMMER TOTAL’ t
1

150 ;

season.
155 LET N=C ]
160 GOSUB 200
Makes the computer slay on the same line to
170 PRINT 'AUTUMN TOTAL”; *
print the stars.
175 LET N=D
1B0 GOSUB 200
190 STOP
200 REM; SUBROUTINE TO PRINT STARS Line 210 checks in case no-crne was bom in a
'
particular season.
210 IF N-G THEN GOTO 250 j—
,220 FOR 1-1 TO N The main program sets N to the total for A, B, C
230 PRINT or D.The loop makes the computer carry out
^240 NEXT I line 230 “IT times.
250 PRINT
260 RETURN 35
More graphics
These two pages show how you can use PLOT and UNPLOT to make
moving pictures on the screen. Moving pictures are called animated
graphics and they are useful for games programs, or to illustrate
programs which explain, say, the principles of gravity or ballisticsand
flightpaths.

The pictures for video and arcade games A general purpose microcomputer
are controlled by a small computer. The programmed in BASIC makes slower,
computer is programmed to play only the simpler pictures. It cannot handle all the
games and the programs are in the instructions for the screen quickly enough
computer's own code, not in BASIC. to make really fast moving graphics.

Plot/unplot program

1
10 LET X=1
20 LET Y= I

30 PLOT (X,Y)
40 UNPLOT (X, 1

50 LET X=X +1
60 LET Y=Y+
70 GOTO 30
This short program makes a spot of light When the spot reaches the edge of the
move across the screen. Remember, the screen the program may stop with an
commands for PLOT and UNPLOT vary on error message as the values for X and Y
different computers. are outside the screen range of the computer,

Bat and hall video games use programs When the ball reaches the top of the
like the one above tomove the ball on the screen t he amount to be added to Y is
screen. There are simple program rules to subtracted instead. In the same way, when
keep the ball moving when it reaches the it reaches the right edge, the amount is

edge of the screen. subtracted from X.


36
Line pattern program
This program plots a line across the
screen and when it reaches the sides 1

sends it back again in another direction. It


does not use UNPLOT so the lines leave a
pattern on the screen. The picture on the
right shows what happens when you run
the program. The program is set by line
100 to plot 10,000 pixels. You can change
this figure to make it shorter, or BREAK the
program at a pattern you like.

10 REM; SET UP GRAPHICS MODE HERE IF NECESSARY


20 PRINT HQW MANY PIXELS ACROSS?
bl

Lines 20 to 50 ask for the height and width


30 INPUT H of the screen. The semi-colon puts your
H
40 PRINT AND UP?"; reply on the same line a$ the question.
50 INPUT V
55 CLS
60 LET X=H/2
This makes X and Y start at the centre of the screen.
70 LET Y=VY2
60 LET S= 1 Sand T are the amountsthat will be added to X and
90 LET T= 1 Y to make the line move.
100 FOR 1= 1 TO 10000 ]- Theloop from lines 100 to 150 is repeated 10,000 times
110 LET S=S+(INT(RND(1) * 10 + 1)-5)/50 Each time, X and Y are changed by a small amount.
120 LET X=X+S This gives a very small number to add to X. The
130 LET Y=Y+T number varies each time the loop is repeated.
140 IF X<5 THEN LET S= -£
150 IF X>H-S THEN LET S=-S These lines test for the edges and
160 IF Y<5 THEN LET T=-T reverse S and T when X and Y come
within five pixels of an edge.
1 170 IF Y>V~5 THEN LET T^-T
1 180 GOSUB 300 ] Sends the computer to the subroutine to plot the line
'190 NEXT ]

200 STOP
SCO REM: PLOT LINE
310 PLOT (X,Y) ] Plots the pixel with the current value for X and Y.
320 RETURN
Experiments

bine 10 adds a very small random amount


1 Try changing the numbers in lines 30 and
to Xeach time and this makes the line 90 to, say, 5 or 10 (or larger on a computer
wiggle across the screen If you have a with high resolution graphics). This
computer, try deleting this line. The lines makes the computer plot the pixels at
on the screen should become parallel intervals.
Funny poems program
The next few pages show you how to write a program which can compose
lots of poems. A version of this program first appeared in the Usbome Guide
to Computers That book showed how to make a "paper computer" which
used a simple version of this program Here you can find out how
—— —
——
.

""

" " —
to write the same program in BASIC.

^
I"
Data lines
'

Program for the paper computer from


\
—— Aw \jyi AS A

Paper computer, umber


Spinner words
TASHKENT TRENT
^OandB^O GHENT
1 WRAPPED HP
2 Add Ho A HEAD
RAJNTED
fastened
A^6go tolme.
1
HAND
3 It FOOT
4 Wnie THAT WAS BENT
g AddlwB I

Twrirl spinet «>* ITturned blue


6
word with A BARK
, Wnte daw WHERE IT WENT \

column N VVHAT IT MEANT


oiSgolo 1 here wa^ mSS Vrom
a itB= 3
up Vushea4
Go t<>lil'e ®
\c\
9
Ooe aftw* dark
10 Stop
y
1

It “doe lo
l

n-jt ubare it went

This is the program for the paper program tells you which to select. The
computer. looks a little like B ASIC, but it
It number spinner is a random number
would not work on a real computer. The generator to give random numbers
words and phrases fox the poem are between one and four
“stored” on pieces of paper and the

Translating the program into BASIC Thrswon'twork


on a computeryet
10 LET A=G 1
20 LET B=0 J These lines set up empty variable spaces.
30 LET A=A+1 Lines 30 and 40 keep count of the number of
40 IF A=6 THEN STOP data lines the computer has selected.
50 Write data line A} Lines 50 and 80 are not in BASIC yet.
60 LET B=B+1 ] Line 60 keeps count of the number of data words
70 LET N— INT(RND(1)*4 + 1) Gives a random number between 1 and A
80 Write data words from row B
column N
90 IF B=3 THEN GOTO 60 Lines 90 and 100 send it back to select another
100 IF B-5 THEN GOTO 60 data line.
110 GOTO 30
120 END
Most of the program is easy to translate storing and picking out the data lines and
into BASIC, but lines 50 and 80 are more words which are needed for each line of
difficult. The computer needs a way of the poem.
Giving the computer data
2
50 READ AS

180 DATA THERE WAS A YOUNG MAN FROM,


WHO, HIS
190 DATA ONE NIGHT AFTER DARK, AND HE
NEVER WORKED OUT

To give the computer the data lines and


trn
You can store all the data items in one big
words you can use READ DATA. Each . . . variable called A$. A variable containing
time the computer carries out the READ more than one data item is called an array
instruction it takes another item from the and each item is referred to by a number,
DATA line and stores it in the variable. e g, READ A$£3) gives HIS. *

rp&vr
p
" —— ,

&RAPPE& UP

//V A TENT Hrm teMFAfT A


vK'b BBKT 1

/T OFF , r rr qLQWEb VT ftl-EVI W —J


L
r /a/ ~nv£ pap*4 *LHC£ a GUAM
/TS WTEA/T V4UN n VICKY

A variable can also hold several rows of in. So READ B$(4


column it is ) gives,

data and you can store all the data words WITH CEMENT and READ B$(6,3) gives
in a variable like this. It is called a two- FOR A LARK. Y ou can store numbers in
dimensional array. Here, each data item is arrays too, using a number variable
p ,

referred to by the number of the row and eg. N(5J).

Putting the data in the variables


^
10 FOR 1=1 TO 7 I is the row number

20 FOR J= 1 TO 4
J is the column
30 READ BS(I, J) number
40 NEXT J
50 NEXT J

60 DATA TASHKENT, TRENT, KENT, GHENT m ™


70 DATA WRAPPED UP, COVERED, PAINTED, FASTENED PAINTED 1

L
50 DATA HEAD, HAND, DOG, FOOT
90 DATA IN A TENT, WITH CEMENT, WITH SOME SCENT, THAT WAS BENT
100 DATA IT RAN OFF, IT GLOWED, IT BLEW UP, IT TURNED BLUE
110 DATA IN THE PARK, LIKE A QUARK, FOR A LARK, WITH A BARK
120 DATA WHERE IT WENT, ITS INTENT, WHY IT WENT, WHAT IT MEANT

To read each data item into the variable and a J loop for the column number. Each
you need to be able to alter the numbers in time the I loop is carried out the J loop is
brackets after READ. You can do this with repeated four times - once for each of the
loops. B$ needs nested loops as shown columns in a row.
above with an I loop for the row number 39
^Sinclair computers deal with variables in a different way and this program will not run or a
Sinclair. You can find out more about this over the page.
Making space for variables
5
S DIM KS(5) >— This is the size of the variable,
i.e, 5 items in a row.
10 FOR 1= 1 TO 5
This line puts the data in KS
20 READ K$(I)1
each time the loop is repeated.
30 NEXT I,

40 STOP

60 DATA DOG, CAT, FROG, BUG


At the beginning of the program you have For a two dimensional array you give the
to tell the computer how big you want the computer the number of rows and
variable to be. You do this with the word columns in the variable, e,g DIMC$(6,3).
r

DIM followed by the variable name and You must always have the right number of
the number of data items, e.g, DIM K$(5). data items for the variable or you get a bug.

the data
0 Printing out
200 LET A=0
210 LET B=0 A keeps count of the number of times this
220 LET A=A+1 J— section of the program is repeated.
230 IF A=6 THEN STOP
B keeps count of the data word rows and
240 PRINT AS(AJ makes sure that the correct row is used with
250 LET B = B + 1 ] each data line.
260 LET N=INT(RND(1)*4+ 1)
Lines 280 and 890 make the computer print out
270 PRINT B$(B,N) words from another data word row before
280 IF B=3 THEN GOTO 250 '
printing the next data line.
290 IF B=S THEN GOTO 250
This sends the computer back to print t he next
300 GOTO 230 ]
data line-
310 END
The computer needs these lines to print computer prints out data line number A
out the data lines and words in the right and some data words from row number B.
order. This section of the program is The actual data words which are chosen
repeated five times. Each time, the are decided by random number N.

Sinclair computers and variables


This program does not work in its For two-dimensional arrays you have to
present form on Sinclair computers tell the computer the number of the row
because they handle strings in a as well as the numbers of the
different way. characters. For instance, R$(2 4 TO 6)
,

is PUG

At the beginning of a program you tell


To tell a Sinclair computer to pick out a the computer how many rows the array
particular data item from a variable you has, and how many characters there
have to give it the numbers of the first are in each row, e g. DIM AS(2,9}
and last characters of the item you means two rows, each with nine
want. This is the same system as the characters. All the rows in the array
Sinclairs use for LEFTS, RIGHTS, etc. must have the same number of
(See page 32 J characters.
The complete funny poems program
Now you can put the parrs of the program together and write the complete poetry
program. The first part of the program (lines 10 to 190) give the computer the data and
the second part (lines 200 to 3 10) prints out the poem. Each time you run the program
you get a different version of the poem because the random number N makes the
computer pick different words.

10 DIM A${5) I Lines 10 and 20 tell the computer how much space to leave for
20 DIM B$a4) j the variables - a row of 5 for AB and 7 rows of 4 forBS
30 FOR 1=1 TO 7
40 FOR J- 1 TO 4 These are the nested loops for putting the data mb$.
50 READ &$(], ])
60 NEXT J Lines 30 to 140
70 NEX T I contain all the data
90 DATA TASHKENT, TRENT, KENT, GHENT words to be stored
90 DATA WRAPPED UP, COVERED, PAINTED FASTENED in BS

100 DATA HEAD, HAND, DOG, FOOT


110 DATA IN A TENT, WITH CEMENT, WITH SOME SCENT, THAT WAS BENT
120 DATA IT RAN OFF, IT GLOWED, IT BLEW UP. IT TURNED BLUE
130 DATA IN THE PARK LIKE A QUARK, FOR A LARK, WITH A BARK
HO DATA WHERE IT WENT, ITS INTENT, WHY IT WENT. WHAT IT MEANT
ISO FOR 1=1 TO 61
160 READ A$(I) This is a loop to pufthe data into AS.
170 NEXT I J
130 DATA THERE WAS A YOUNG MAN FROM, WHO, HIS
ISO DATA ONE NIGHT AFTER DARK, AND HE NEVER WORKED OUT
200 LET A-0
210 LET B=G Lines 1B0 to 190 contain all the
data lines to be stored in AS.
330 LET A=A+
230 IF A=6 THEN STOP
This prints the data line stored
240 PRINT AS( A) ]
in AS compart ment number A.
250 LET B=B+
260 LET N=(RND(1)*4+ 1) This prims the data words
270 PRINT fiSffi.N) ] -
stored in BE row B, column N.
230 IF B=3 THEN GOTO 2S0
290 IF B=5 THEN GOTO 250 The program slops at line 230
when A -6, so never reaches
it
300 GOTO 220
line 3 10, but some computers
310 END need an END anyway.

Sample runs

there was a young man from THERE WAS A YOUNG MAN FROM
KENT GHENT
WHO WHO
WRAPPED UP PAINTED
HIS HIS
HEAD FOOT
IN A TENT WITH CEMENT
ONE NIGHT AFTER DARK ONE NIGHT AFTER DARK
ITGLOWED IT TURNED BLUE
LIKEA QUARK WITH A BARK
AND HI NEVER WORKED OUT AND HE NEVER WORKED OUT
WHY IT WENT ITS INTENT

Here are two of the 16,384 poss ible make the computer produce different
poem- If you try
different versions of the random numbers. Some computers
this program and always get the same produce the same sequence of random
poems, look in your manual for howto numbers each time they are switched on.
41
Programming tips
On these two pages there are some Writing programs
tips to help you write your own
programs, and a list of the most When you are writing programs it

helps to remember that the computer


common bugs you might get, and
can carry out three main activities:
what causes them. The most likely simple instructions, repeating things
bugs are listed first, so if you have a and making decisions. These are the
program which will not work, building blocks of all programs.
check through this list until you find
the reason
LET A=3
SIMPLE
LET N=N+1
INSTRUCTIONS
Finding bugs PRINT A/T
PLOT (X,Y)
Misspelt word
FRONT

REPEATING FOR J=1 TO 6


THINGS
20 LET A=1
30 IFA< 10 THEN
GOTO 100
Look for typing mistakes m BASIC words
If you misspell one of these words the

computer will not recognize it. IF X-Y THEN STOP


IF K$= “HELLO"
/MAKING \ THEN PRINT A
Figure 1 instead
DECISIONS
ofletterl.

This book has covered all the main


instructions you need in BASIC to tell
the computer to cany out these
activities. When you are writing a
program, work out what the computer
needs to do at each stage, then decide
Check Os and Os arid Is and Is to make
which instructions you want to use,
sure you have typed the right ones in the
right places.

Should have
used keyword

Make sure you have not left out any


Ifyou have a Sinclair computer, make sure quotation marks, or the commas between
you have not typed a word in letter by data items. Check complicated lines
letter instead of pressing the key for that which have lots of symbols especially
carefully.
Error messages

All computers print outsome sort of


There axe usually several different message when there is a bug in the
ways to write a program and some of program and the messages are explained
them may be neater and shorter than in the computer’s manual. Here are some
others. When yon are writing along of the most common messages you may
program it is a good idea to divide it up get,
into lots of sections withsubroutines to
carry out each activity. The central core ^ . < This means there are not
of the program may be a simple set of /O u t of 1
enou ^
^ ata iteiTls the
instructions, decisions and repeats { .
, ) computer to read in the
which controls when and how often the DATA lines. It may be
(A! ^
V because you have missed
computer carries out the subroutines.
out a comma between two
* m items so the computer has
,

T\ ) read them as one.

Calculating
The line with the number
given in a GOTO or GOSUB
statement does not exist.
You may have accidentally
Getting more
erased the line by typing in
information another line with the same
number, or you may have
mistyped the number.
just

Plotting

/ No such < You may get this report


( variable on a BBC or Sinclair
Keeping computer. It usually means
count
you have not set up a
variable with a line such as
Ml
Breaking up programs into sections LETC-OorLETC = '

like this makes it much easier to find before using it.


any mistakes. Each section can usually
This means the NEXT line
be tested by itself without running FOR without
of a loop is missing. It may NEXT
through all the program. Remember to
be because you typed the
label each section with a REM line so
wrong variable name, or
you know what it is for.
even put a 1 instead of an I
so the computer did not
recognize it.

simo

Last word
Some bugs are very hard to find, but
the computer will not run the
if

program there must be a bug in it


somewhere. If you really cannot find
Make sure you use the correct RND, PLOT the bug, try typing in suspect or
and CLS commands for the comput er. complicated lines again you might ,

Check, too, that you have given the get them right the second time
computer a general graphics line if it without even noticing what the bug
needs one. was.
Puzzle answers
Page IS Page 23
Name and message program Plotting counter
10PRINT WHAT IS YOUR NAME"
'

5 LET C=0
20 INPUT N$ 45 LET C=C + 1
30 PRINT “HELLO" 50 IF C<6 THEN GOTO 10
40 PRINT NS
50 PRINT "HOW ARE YOU" Plotting your initial

Page 1 Here is an example of a program to plot


the letter L.
1. Sums program
10 LET X=15
10 LET A=9 20 LET Y=30
20 LET B=7 30 PLOT (X,Y)
30 PRINT A*B
40 LET Y=Y-
40 PRINT A/B
50 IF Y>5 THEN GOTO 30
50
3. LET A=A+1 60 LET X=X-t-
60 LET B=B+3 70 PLOT (X,Y)
70 PRINT A *B,A/B Comma 10 X<45 THEN GOTO
80 END ^—— . leave space
30 IF
90 END
60

2, Tables program ^Spaces


30 PRINT A TIMES ” B IS A*B Page 24
40 PRINT A :
“ DIVIDED B Y ”
;
B
;
" IS " ;
AB Random numbers
The formula for a random number
Name and message between 10 and 20 would be
alterations INT(RND( 1) *ll-t-9). On computers which
need only a number in brackets after
10 PRINT 'WHAT IS YOUR NAME" RND, would be RND( 11)+ 9. There are
it

20 INPUT NS eleven possible numbers between 10 and


30 PRINT “ HELLO ";N$;“ HOW 20 so you need to pick random numbers
ARE YOU between 1 and 11, then add 9,

Page 18
Page 25
Sums program
Space attack
10 PRINT "WHAT IS 7 TIMES 7”
These are the lines you need to add to
20 INPUT A
count the number of hits:
30 IF A=49 THEN PRINT “CORRECT"
40 IF A<>49 THEN PRINT “NO"; 7* 15 LET 5=0
f 75 IF X = A*B THEN LET S=S+1
You need a semi- colon after the 95 PRINT "YOU HIT "
quotes, like this.
;S;“ OUT OF 6 ALIENS”

Page 1
Age guessing game Page 27
1. Eight times table
Replace line 30 and add a new line 36;

30 IF G<14 THEN PRINT "OLDER 10 PRINT "THE EIGHT TIMES TABLE”


THAN THAT" 20 FOR J=1 TO 12
35 IF G> 14 THEN PRINT "YOUNGER 30 PRINT J;"x = ”;J*8
THAN THAT” 40 NEXT I
Page 27 Page 34
2. N times table Number trick program
10 INPUT "TYPE IN A NUMBER’ ;N PRINT
10 “THINK OF A NUMBER-
20 PRINT "HERE IS THE " 30 PRINT "DOUBLE IT, ADD 4"
;N;“ TIMES TABLE" 30 PRINT “DIVIDE BY 2, ADD T
30 FOR 1=1 TO 13 40 PRINT "MULTIPLY BY 8,
40 PRINT I;" TIMES ";N;" IS ”;I*N SUBTRACT 12”
SO NEXT I 50 PRINT "DIVIDE BY 4 AND TAKE
60 INPUT "ANOTHER NUMBER (Y or N)” AWAY 11"
60 PRINT "TELL ME THE RESULT”
70 IF M$— "Y” THEN GOTO 10 70 INPUT N
For the ZXB1 you need separate PRINT
80 PRINT "THE NUMBER YOU FIRST
and INPUT lines. THOUGHT OF IS";(N-4y2

Page 32 /
You need the brackets
Computer book string puzzle to make the computer

LEFT${A$,8) is "COMPUTER" do the sum in the order


you want.
RIGHT$(AS, 10) is "PUTER BOOK"
MID$(AS,5,8) is "UTER BOO”

Space invaders repeat program

P 1 , 2 4,5; 5,5; 6 5
P A
3 r 4; 5,4; 7,4
f

3
4,3; 5,3; 6,3
2

Draw a simple space invaders shape on Then work out the co-ordinates of all the
squared paper squares which make up the space
invader.

3
5CLS
50 INPUT 'HOW MANY POINTS ACROSS THE SCREEN"' ;
W
60 INPUT "HOW MANY UP :V n

65 CLS Change the 6 to a higher figure to increase the number of


70 FOR 1=0 TO V STEP V/6 times t he invader shape repeals on the screen. (If you
get a bug you have made the number too big.)
80 FOR J=Q TO W STEP W6
Put your plot lines here, e,g.
90 PLOT (J+3, 1+2}
92 PLOT (J+4, 1+2)
130 NEXT J two bottom left 1 hand squares of the
cor the
140 NEXT I
space invader shown above. You need a
160 END program line for each square.

Copy out the pattern repeat program, into the program between lines 80 and 140
excluding lines 10 to 40 and 90 to 140, as (you can renumber the lines in the
shown above. (These lines produce the program). For each pair of co-ordinates
random pattern for the program so you do you need to add J to the first figure and I to
not need them,) the second figure, to make the space 45
Now you need to put your own plot lines invader-repeat .
BASIC words
Here is a list of the BASIC words used in
book, with short explanations this
of what they mean. Some of the words, such as CLS,
are not standard on
all computers and these words have a small star beside them. If you have
a micro you should check these commands in your manual.

* BREAK On some computers this stops the program running. Be careful, though, on
others erases the whole program from the computers memory and you should use
it

ESCAPE, or some other word instead.


* CLS Clears the screen.

* DATA A list of items, e.g. words or numbers, to be stored by the computer in


variables. See READ-
DIM Tells the computer how many memory spaces should set aside for a var iab le. it

E g. DIM A$(5,4) means the variable needs five rows of four columns.
* EDIT Allows you to alter a line in a program without typing in the whole line again

* END Tells t he computer it is the end of a program Some computers must always have
an END statement, others, such as the BBC micro and Sinclair computers, do not need
one.

FOR k . . NEXT Makes the computer loop back through the program and repeat any
instructions inside the loop a feed number of times.
GOSUB Makes the computer leave the main part of the program and go to a part called
a subroutine to carry out a special task.

GOTO Tells the computer to go to another line in the program

IF , . . THEN Compares pieces of data ( e.g numbers or words or the contents of


.

variables) and does different things depending on the results.


INPUT A way of getting the computer to ask you for data while the program is running
1NT Converts a number with a decimal point to a whole number by ignoring all the
figures to the right of the decimal point E g. INT(3.4G) =3.

LEFTS Tells the computer to do something with a number of characters from the
left-hand side of a string. E g. LEFT$( AM) means take four characters from the left of A$.

LEN Gives the length of a string, i.e. the number of characters in a variable.

Computer words
Array A set of variables containing several pieces of data
Bug A mistake in a program.
CPU The central processing unit of the computer which controls all the operations and
does all the work, e.g. comparing variables, adding, etc
Cursor A small, sometimes flashing light, square or other shape on the screen which
shows where the next character will be printed
Flow chart A chart showing the main operations needed in a program. Often used as
an aid to writing programs.
Graphics Ways of producing information visually on the scree n.
Kilobytes (K) A unit of measurement for the memory of a computer. One kilobyte is
1034 bytes and in most micros each character takes up one byte-
Pr ompt A quest ion mark or ot her symbol which appears on the screen when the
computer asks for information after an INPUT statement.
46
LET Puts a variable label on a memory space and puts some information in it E .g. LET
N= 4 or LET BS -= 'CATS"

LIST Displays the program listing on the screen

MID$ Tells the computer to do something with characters from the middle of a string.
Eg MID$(A$,4,3) means take three letters starting from the fourth letter of A$.

NEW Wipes the program from the computer's memory to clear it for the next
program.

NE WLINE KEY Tells he computer that you have finished yp ing in a program line or
t t

piece of input. Some computers have keys marked RETURN or ENTER

NEXT See FOR.

PLOT Tells the computer to light up a pixel. E g. PLOT (X, Y) means light up the pixel
with co-ordinates X along and Y up.
PRINT Tells the computer to display something on the screen.
RE AD Tells the computer to read the information in a DATA line and store it in a

variable. See DATA.

READY Some computers say this when they are ready to be given another instruct ion.
REM T he computer ignores lines start ing with RE M but displays them in the program
listing. They are useful to remind you what different parts of the program do
RETURN At the end of a subroutine, tells the computer to go back to the instruct ion
after the one where it left. See GOSUB.
± RIGHTS Tells the computer to do something with the right-hand characters in a string.
Eg. R1GHTS(A$,4) means take the four characters from the right of AS

RND Picks a random number.

RUN Tells the computer to carry out a program.

SQR Tells the computer to find the square root of a number.

STEP Used with FOR . . . NEXT loops Tells the computer when to repeat the loop.
STOP Used within a program to tell the computer to stop running the program.
THEN See IF.

£ UNPLOT Tells the computer to switch off a pixel

Pixels Short for picture elements The small squares which the computer can light up
.

on the screen to make pictures.


Program A numbered list of instructions telling the computer how to carry out a
particular task.
RAM Random Access Memory The memory inside the computer where the program
.

and data are stored. All the information in RAM is automatically erased when the
computer is switched off,
ROM Read Only Memory. Permanent memory where information telling the
computer how to operate is stored by the manufacturers.
String A series of c har acter s for storing in a variable, e g. SAUSAGES or "ABC 123". .
1 11

Subroutine A section of the program for carrying out a particular task which is usually
repeated several times during the running of the program.
Syntax error A mistake in the B AS1 C in the program
Variable A labelled memory space which contains apiece of information.
47
Going further
The best way to learn to write programs is to try out your programs on a
computer If you do not have a computer, there may be somewhere
where you can go and use one, Try asking at your local school, or at the
library, or go along to a computer user’s group and see if you can borrow
some time on someone's computer
You can learn a lot about writing programs from reading and typing in
programs written by other people Here is a list of books about computers
and programming that you may find useful,
Usfaome Guide to Computers by Brian Reffin Smith, Usbome 198
Understanding the Micro by Judy Tatchell and Bill Bennett, Usbome, 1982
The Computer Book by Robin Bradbeer, Peter DeBono and Peter Laurie, BBC 1982
Illustrating Computers by Colin Day and Donald Alcock, Pan 1382
Illustrating BASIC by Donald Alcock, Cambridge University Press 1977
Computer Spacegames by Daniel Isaaman and Jenny Tyler, Usbome 1382
Computer Battlegames by Daniel Isaaman and Jenny Tyler, Usbome 1982
error messages, 1 1, 36, 43 pixels. 22-23, 25 r 29. 37
Index ESCAPE,
Face program,
15,36, 47
11
PLOT, 22-23, 25. 29,
poetry writing program, 15
34. 88, 37. 43. 47

The numbers m bold type show the flowchart, 9 PRINT. 10-1 1, 12,15*16-17,47
pages on which each term is first FQR NEXT, 26-29, 38, 34, 3S, 37, printer, S
explained. 39.41,48,47 program, 4. 6, 7, 89
French lesson program, 18 line numbers, 1 1, 30, 43
AES, 31 Funny poems program, 39- 4 plans, 9. 35* 42-43
addition, 16, 34 games programs, 20. 24-25, 36 puck, 28
Age guessing program, 19 GOSU1, 30-31, 35, 87, 43, 47 pugs, 9
Age program, 16 GOTO, 19. 39, 21,33, 35, 31, 88, M, Quiz program, 31
animated graphics, 36 41*48,47 quotation marks, 10, 12, 16, 17 42
r

arrays, 39, 40, 41 graphics, 22*23, 35, 29. 31, 36-37, 43 RAM (random access memory), 5
BASIC, 7, $, 10, 36, 39,43 graphs, 34 random*
BBC micro, 21, 22, 43 greater than, 10. 31. 37 numbers, 24-25,28, 29. 37*36, 40
Birthdays program, 35 Greedy computer program, 27 number tester program, 28
brackets, 34 Hello loop program, 26 pattern program, 26
BREAK, 15, 23, 25* 37, 47 high level languages, 7 HEAD, 13t 31, 31. 39, 40, 41. 43, 47
bugs* 8, 9* 1 1, 28, 40, 42-43 high resolution graphics* 22, 29, 37 REM, 27,30*31,35,37*43, 47
cassette recorder, 5, 10 IF. . THEN. 18-19* 20. 2 1, 23. 25. 28, RETURN, see GOSUB
Circles program, 3 31.35*37,38, 40,41, 47 key. 10, 47
Clever computer program, 2 INPUT, 19, 14-15,21,47 RIGHTS, 32,33.40, 47
CLE, 10, 15, 30, 35* 37, 23* 39, 84, 37. INT 24, 47 RND, 24-25, 28, 29, 37, 38, 40, 41, 43,
43,47 interpreter, 6. 10 47
Codemaker program. 33 keyboard. 4 ROM (read only memory ), 6
commas, 13 16 17, 2B, 42, 43
h 1
LEFTl 32-33,40. 47 RUB OUT key, 11
Computer clock program, 26 LEN, 33,33*47 RUN, 30-11, IS, 47
computer* less than. 18, SO, 23* 25, 31, 37 - semi-colons, 16.17*21, 35, 37
code, 6,7,36 LET. 12, 13, 17,32*47 Silly sums program* 26
languages, 4, Line pattern program, 37 Sinclair computers, 39* 40, 42, 43
Conversion program, 3 LIST, 11, 15,47 Space attack program, 26
COPY. 11 loops, 26-29, 33, 84, 85, 37, 89,41,43 Space commando program, 28
counters, variablesused as, 21 p 33, maths and sums* 16, 17, 34 spacing words on the screen, 16,21
25,36,31*85,38,49 Maths program* 19 square roots, 16
CPU (central processing unit), 5 memory, 5, 6, 12* 14, 15, 22 STEP, 27,29*33,47
cursor, 10 MIDJ, 32,83.47 STOP, 19, 30. 31, 35 p 38, 40, 41. 47
data, 4, 12-15, 16,88-39 MODE, 22 strings, 12-13, 14,32-33
DATA, 13. 31, 31, 39, 49* 41, 49, 47 multiplication* 16,84 subroulines, 80-31, 35, 37, 48
debugging programs, 11* 43-48 nested loops* 28-29, 39, 41 subtraction, 16. 34
delay loops, 27, 38 NEW* 15,47 THEN, see IF
DELETEkey.il NEWLINE key, 19. 15.47 UNPLOT. 22,36,47
DIM, 48,41, 42.47 NEXT, see FOR variables, 12- 15, 17, 18, 21, 27, 32,
division. 16, 34 Numbers program, 81 85.38. 89.40
EDIT. 11. 47 number variables, 12, 13, 14 as counters, 31, 23, 25, 26, 33, 33,
Eight limes table program. 28 Pascal, 7 39.40
END.il, 47 Pattern repeat program, 29 Weather program, 18
ENTER key, 10 Pilor, 7 ZX8J computer, 13, 19,21,32

First published in 1982 by Usbome Publishing Ltd, pari of this publication may be reproduced, stored in
20 Garnck Street London WC2E 9BJ, England.
.
a retrieval system or transmitted in any form or by
© 1982 Usbome Publishing any means, electronic, mechanical, photocopying,
The name Usbome and deviceTT are Trade Marks recording or otherwise, without the prior permission
of Usbome Publishing Ltd All rights reserved No of the publisher. =z=x&c^-rL t
Usborne Computer Books
Computers are fun You can play games with them, ask them questions, write
poetry wit h them a nd play music o n themtoo This colour ful new ser ies of books
,

shows you some of the exciting things computers can do and explains how they
work and how to use them, Written in clear and simple language with lots of
pictures, these books provide a fun introduction to computers and computing for
absolute beginners.

Computer Games
Understanding the Micro A colourful look at how Computer Programming
A colourful guide to computers play Space A step-by-step guide to
microcomputers, how they invaders, chess and other programming in BASIC for
work and what they can do, games, with lots of tips on absolute beginners With
with lots of ideas for things how to beat the computer. lots of programs to run on
you can do with a micro. any microcomputer.

Usborne Computer Fun


These two superbly
illustrated books are
packed with games
programs to play on a
microcomputer. Each game
is suitable for use on
the most common micros,
and there are lots of tips and
hints for writing your own
programs.

Pubiished in the USA by Published in Canada by


Hayes Books. 8141 East Hayes Publishing Ltd,
44th Street, Tulsa, 3312 Marnway, Burlington,
Oklahoma 74145, USA Ontario, Canada, L7M 1A7.

ISBN 0 86020 674 2 12 82

You might also like