Professional Documents
Culture Documents
ACORNSOFT
Acknowledgements
The production of this manual, in the time scale required could only have been
achieved with the support of our families, the encouragement of friends
including Mark Taylor, Andy Tonks and Graham Noble, and with the
extensive assistance of the implementers of Acornsoft COMAL.
Thanks are also due to the staff of Optimus Graphic Design, Cambridge, for
their invaluable efforts.
ISBN 0 907876 90 0
Copyright © Acornsoft Limited 1984
All rights reserved
No part of this book may be reproduced by any means without the prior
permission of the copyright holder. The only exceptions are as provided for by
the Copyright (photocopying) Act or for the purposes of review or for the
software herein to be entered into a computer for the sole use of the owner of
this book.
FIRST EDITION
Re-mastered by dv8 in 2020
First revision, October 2020
For the latest revision of this book go to:
stardot.org.uk/forums/viewforum.php?f=42
Note: Within this publication the term ‘BBC’ is used as an abbreviation for
‘British Broadcasting Corporation’.
First published by Acornsoft Limited, Betjeman House, 104 Hills Road,
Cambridge CB2 1LQ, England. Telephone (0223) 316039
Contents
Introduction 1
About this manual 1
2 Keyboard introduction 6
2.1 Getting going 6
2.2 Caps and shift 7
2.3 Into COMAL 9
2.4 PRINT, addition and subtraction 10
2.5 Syntax errors 11
2.6 Enter 11
2.7 More arithmetic 11
2.8 Printing numbers 14
2.9 Printing messages 14
2.10 End of section exercise 15
2.11 End of section summary 15
5 Programs 39
5.1 Preparing for a program 39
5.2 Program lines 39
5.3 RUN 40
5.4 LIST 40
5.5 RENUMBER 40
5.6 Order of execution 41
5.7 Editing 41
5.8 OLD 43
5.9 Abbreviations 43
5.10 Deleting several lines 44
5.11 AUTO 44
5.12 Comments 45
5.13 Modifying a program 46
5.14 Variables in listings 48
5.15 End of section exercise 48
5.16 End of section summary 49
6 Simple loops 50
6.1 Repeating statements 50
6.2 Control of the loop 51
6.3 Helpful additions 51
6.4 STEP 52
6.5 Impossible loops 53
6.6 Introduce variables first 53
6.7 The :+ notation 54
6.8 The :- notation 55
6.9 Doubling up 55
6.10 End of section exercise 55
6.11 End of section summary 56
13 PROCedures 99
13.1 Creating a program 99
13.2 Example program 100
13.3 Changing MODE 102
13.4 CLEAR 102
13.5 EDIT 103
13.6 EXEC 103
13.7 Listing longer programs 103
13.8 Using procedures from direct mode 104
13.9 End of section exercise 104
13.10 End of section summary 105
19 Arrays 139
19.1 Introduction 139
19.2 Dimensions 139
19.3 Storing arrays 140
19.4 DIMensioning arrays 140
19.5 Example program 142
19.6 Cursor on and off 144
19.7 End of section exercise 146
19.8 End of section summary 146
24 WHILE 178
24.1 The possibly not loop 178
24.2 Examples 178
25 CASE 180
25.1 OF 180
25.2 The CASE format 181
28 ELIF 185
28.1 Format for ELIF 185
28.2 Demonstration program 185
29 Substrings 187
29.1 Selection of a substring 187
29.2 Substring specifiers 187
29.3 Precedence 188
29.4 Single element substrings 189
29.5 Elements of a string array 190
29.6 Replacing substrings 190
30 FUNCtions 193
30.1 Example programs 193
30.2 Use of FUNCtions 194
31 Parameters 195
31.1 Calling a FUNCtion with parameters 195
31.2 Local variables 196
31.3 Global variables 196
31.4 Main block variables 196
31.5 CLOSED PROCedures and FUNCtions 197
31.6 IMPORT 197
31.7 Using the same actual and formal parameter 199
31.8 REFerenced parameters 199
31.9 String parameters 200
31.10 Passing arrays by REFerence 201
Index 429
Introduction
COMAL is modern, as computer languages go. It has its ancestry in Pascal and
BASIC, combining the simplicity of the operating environment of BASIC with
the power of Pascal. COMAL has been developed considerably in recent years
and now has an elegance and structure to rival any language available for a
microcomputer. COMAL is a general purpose language encouraging the
writing of well structured programs. It should be possible for a program or
procedure written by one author to be understood and used by another.
1
Part I – for the absolute
beginner
1 Learning a new language
5
2 Keyboard introduction
In this section we shall learn to use some of the keyboard controls and the
keyword PRINT.
There is a symbol pointing to the right. This is called the ‘prompt’ and means
that the computer is waiting for you to do something. Alongside the prompt is a
short flashing line, which is called the ‘cursor’. The shape of the prompt may be
one of the following.
>_ or →_ or ]_
The prompt and cursor indicate that the computer is waiting for an instruction.
For simplicity, the prompt shaped > will be shown in the first few examples.
You will not do any harm to the microcomputer by typing at the keyboard.
Don’t worry if you make a typing error: it’s easy to make a correction.
The keyboard is similar to that of a typewriter, but with some extra features.
Find the key at the bottom right of the keyboard marked with the word
DELETE. If you make a typing mistake, then press this key to remove the
error.
Now find the letter G (near the middle of the keyboard) and lightly press it
down a few times. Notice its appearance on the screen, with the cursor always
moving on to the next place.
>GGGGG_
6
Find the DELETE key and press it lightly to delete one of the Gs. The cursor
moves back as well.
>GGGG_
The long unmarked key nearest you is called the ‘Space Bar’. Press it once. An
ordinary typewriter moves across when the Space Bar is pressed, but on a
computer a blank appears.
>GGGG _
If you now hold down the key G for about two seconds you will find that the
letter is repeated automatically whilst the key is pressed. Try it.
>GGGG GGGGGGGGGGGGGGGGGGGGGGGG_
On a simple typewriter when you come to the end of a line, you hear a bell and
the carriage stops. However, when we come to the edge of the screen the letters
typed will appear at the beginning of the next line.
Keep pressing the G key until the Gs appear on the next line.
>GGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG
GGGGGGGGGGGGGGGG_
A similar effect happens with the DELETE key, which will move back into the
previous row. Try holding it down for a while.
>GGGG GGGGGGGGGGGGGGGGGGGGG_
You can use the DELETE key whenever you want to remove one or more
letters. It may be pressed once or kept pressed down to repeat the deletion.
Hold it down and continue to delete all the Gs. If you continue to hold down the
DELETE key you will find that you cannot delete the prompt.
>_
7
At the front left of the keyboard there are three keys that we need to use.
CAPS
LOCK
SHIFT
SHIFT
LOCK
Now press the key marked 6 with an & sign above it. You should find that you
just get a figure 6.
>gggggggggggggggg6666_
To get capital letters (or the upper symbols), you can hold down the SHIFT key
(rather than the SHIFT LOCK) with one finger and press a key with another
finger. Try to get a capital H using the SHIFT and H key.
>gggggggggggggggg6666HHHHH_
This is just like using an ordinary typewriter. Try to get the * by using the
SHIFT and colon key marked :
>gggggggggggggggg6666HHHHH******_
Use the DELETE key to remove all the symbols that you have typed, right the
way back to the prompt.
>_
8
2.3 Into COMAL
Type *COMAL and then press the key on the right, which is marked RETURN.
The word COMAL should now have been printed on the next line to confirm that
the computer is ready in the language we are going to use.
COMAL or COMAL
→_ ]_
Notice the shape of the prompt symbol, which is a distinctive feature that
identifies COMAL. Whenever you switch on there will be a message on the
screen which identifies the language you are using. If the language is not
COMAL then type *COMAL and press the RETURN key.
When using Acornsoft COMAL you may type in capitals or small letters.
If you want to type in capital letters then you may press the SHIFT LOCK key,
switching on the matching light. All the letters of the alphabet will appear in
upper case and the upper symbols on the number and punctuation keys will be
used.
The CAPS LOCK key can be used to give you a mixture of upper case letters
and the lower case (unshifted) character for the other keys. Press it to switch
on the matching caps lock light.
Press the key G a few times.
>GGGGGG_
The G will be in capitals, but the 6, which is the lower symbol on the key will
appear. CAPS stands for CAPITALS. The capital letters, only, are locked ON.
To get the upper symbols on all the other keys, one of the SHIFT keys will need
to be pressed. Try getting the !, which is on the 1 key.
>GGGGGG66666!_
9
2.4 PRINT, addition and subtraction
PRINT is the keyword for displaying on the screen. A keyword is a word that
forms part of the computer vocabulary. PRINT should be followed by a space,
then the item which is to be printed (displayed).
Complicated calculations can be carried out on a computer, but let us start with
something simple that we can check: such as adding 2 and 2.
We will need the plus sign, +. To get it we shall use the SHIFT key and press
the ; key, but first delete all the symbols back to the prompt.
→_
The normal pocket calculator has only one thing it can do with its answers, that
is to display them, whereas a computer has many options. We have to tell it to
display the answers by using the keyword PRINT. When you type the
command that follows, do not leave out the word PRINT and make sure you
type a space after the word PRINT and before the 2. The prompt sign is shown
for you.
→PRINT 2 + 2_
So far, nothing should have happened because the computer doesn’t know that
you have finished giving it all of the calculation. We have to be able to say
‘Now, over to you!’. We do that by pressing the RETURN key which is on the
right of the keyboard. Press the RETURN key.
In the instructions that follow, the prompt symbol and the cursor will not be
shown.
Now type the following command after the prompt symbol and don’t forget the
space after the word PRINT.
PRINT 2 + 2 + 3
10
2.5 Syntax errors
If you type a letter O where you intend a figure nought the computer will
produce an error message. Type the same command with an incorrect entry
using the letter O instead of a figure nought and press the RETURN key.
The result is:
Syntax error
PRINT 1o + 1o
^
A Syntax error occurs when the computer cannot make any sense out of
your command.
If you do make an error in the way you give a command then you will find that
the command is reprinted for you with an arrowhead pointing to the place
where the mistake was discovered. You may then try to enter the correct
command.
To make the computer do subtraction we must use the minus sign - which is
next to the 0 in the top line. Beware of the longer line _ which is just above the
RETURN key. It is an underlining character and does not represent
subtraction.
Type
PRINT 56 - 45 and press the RETURN key,
then
PRINT 56 - 45 - 2 and press RETURN.
If you got a syntax error, did you use the wrong sign?
2.6 Enter
So that you don’t need to be told to press the RETURN key after every
instruction, we shall use the word ‘enter’ to mean: type the instruction and
press the RETURN key. If you forget to press the RETURN key there will be
an embarrassing pause while you look at the computer and wonder why
nothing is happening.
11
Enter
PRINT 3 * 4
On the right hand side at the front of the keyboard you will find the symbol /.
Don’t get mixed up with \ which is near the top, on the right and also don’t
forget the space after PRINT.
Enter
PRINT 8 / 2
then
PRINT 15 / 3
Precedence in calculation
Enter
PRINT 3 + 4 * 5
The result is 23 because the multiplication 4 times 5 is done before the addition
of the 3.
If we want addition to be done before multiplication then we must use round
brackets (the shifted 8 and 9 keys).
12
Enter
PRINT (3 + 4) * 5
Using the square brackets [ and ] or the curly brackets { and } will not have
the same effect.
Decimals
The symbol . (which is next to / at the front of the keyboard) is used for both a
decimal point and a full stop.
Enter
PRINT 1.23 * 4.56
then
PRINT 9.87 / 0.654
Powers
Powers of a number can be calculated using the symbol ^ which is next to the -
in the top row. Don’t be surprised, when you press this key, if you find a slightly
different symbol appearing on the screen.
Enter
PRINT 2 ^ 3
Enter
PRINT 2 * 5 ^ 3
The computer has multiplied 2 by 5 and then taken the result, 10, to the power
3 (ie 10*10*10).
13
The computer will accept any proper calculation with +, -, * or / together with
^ and round brackets ( ) provided that the numbers used are not too big or too
small. (The range is ample for any normal calculation.)
There should always be a closing bracket to match each opening bracket. If not,
a syntax error will result.
Numbers are normally printed to fit as far right as possible in the current zone.
If you want the answer to be printed as far left as possible then the symbol ;
(semi-colon) must be used.
Enter
PRINT ;2 + 2
and then
PRINT ;3 * 4
and then
PRINT "HOW DO YOU DO ?"
The computer is not being polite. It isn’t maintaining a conversation but doing
exactly as it is told. The symbols in quotations will be printed exactly as they
appear inside the quotations.
14
A set of symbols placed in quotation marks after a PRINT command will be
printed as far left as possible.
Enter
PRINT "TWO AND TWO MAKE FIVE"
The computer will PRINT what is in the quotations without seeing if it makes
sense.
It will produce nonsense if the person at the keyboard instructs it to.
15
produces
LIKE THIS
16
3 Variables and assignment
In this section we shall learn how to store numbers in the computer memory. We
shall use the keywords INT and FREE, and meet PI.
In the last section we typed in capital letters (upper case). However, in COMAL
we could just as easily use small letters. So, for a change, press the CAPS LOCK
key until all the lights are switched off.
3.1 Variables
The computer can store numbers ready for use when required. Each number
that we store in this way must have a name to identify it and, conversely, each
name will refer to a number (once it has been introduced).
We may change the number value associated with each name as and when we
wish, ie the value may be varied. The name associated with each number is
known as a ‘variable’ and a value may be ‘assigned’ to that ‘variable’.
3.2 Assignment
Look for the : symbol, which is on the same key as * and look for the = symbol,
which is next to the nought.
Enter
a := 5
Nothing will appear to happen. However, the value 5 has been ‘assigned’ to the
label ‘a’.
17
To get the number as far left as possible, enter
print ;a
The computer has searched its memory for the value of ‘b’ and cannot find it.
Not too surprising really! We haven’t told it about ‘b’ yet!
Enter
b := 6
and
print b
This time the computer can oblige because it has been introduced to ‘b’ and can
find it in its memory. We must ‘assign’ a value to a ‘variable’ before it can be
used.
18
Enter
a := 7
and
b := 8
then
print a
and
print b
The computer can do arithmetic with the variables. The calculation is done and
the result printed out.
Enter
print a + b
and
print a * b
We can also introduce new variables based on existing ones. For example, the
values of ‘a’ and ‘b’ could be added together and the total assigned to the
variable ‘c’.
Enter
c := a + b
and
print c
The assignment symbol is correctly := but if we wish we may type only the =
sign.
Enter
c = a * b
and
print c
The variable to which we are making the assignment must always be on the left
hand side of the := (or =).
19
If we try to reverse the number and variable then we shall receive an error
message.
Enter
2 := c
We can, however, assign a new value to a variable based on its old value.
Enter
c := c + 2
ie take the value of ‘c’, add on 2, then assign this new value to the variable ‘c’.
Enter
print c
The semi-colon ; causes ‘c’ to be printed as far left as possible, in its zone (ie
next to the message).
Errors
The only words that we must not use are the keywords that the computer
recognises as part of COMAL. They are reserved for the computer and we
cannot use them as variables. Let’s see what happens if we try.
Enter
print := 7
20
The computer is trying to carry out the print instruction. It cannot cope with
the : sign because it is not a number, variable or anything allowable.
Syntax error
PRINT := 7
^
The arrowhead points to the place where the computer has realised there is an
error. This may not be the exact position of the syntax error.
Try leaving out the final quotation mark in a command to print a message.
Enter
print "Testing
The arrowhead is pointing at the first quotation mark even though it is the
second one that is missing. Leaving out a bracket can have a similar result.
Enter
print (3 + 4 * (5 - 2)
The arrowhead is pointing at the first bracket. This is because the computer
cannot know where we intended the matching closing bracket to go.
Acceptable variables
Apart from using keywords, any word or collection of letters and numbers can
be used as a variable, provided that they start with a letter.
Any of the following would be valid variable names: superman, k9, rocky1,
rocky2, rocky3, r2d2, c3po. However, because they begin with a number
the following may not be used: 3d, 2001, 9lives.
After every variable name it is a good idea to type a space to separate the
variable from what follows, so as to make the command easily readable.
Although we cannot use a keyword as a variable we can use variable names that
contain a keyword.
For example
printer := 2
sprint := 99
21
This gives us plenty of scope to use variable names that describe what the
number represents.
eg price, cost, amount, total, vat, discount.
Enter
number := 42
and then enter the incorrect command with no space after the word print.
printnumber
Longer variables
There is another symbol that we can use as part of a variable name. It is the
underline symbol _ which is next to the upward pointing arrow. It is not the
same as the minus sign, which is shorter.
The underline symbol _ can be used to create longer variable names consisting
of several words.
eg number_on_dice := 6 or moves_made := 23
If we use a space instead of _, then the computer considers that it has come to
the end of a variable name when it reaches the space and doesn’t know what to
do with the extra letters.
22
Try entering
number on dice := 6
then enter
number_on_dice := 6
Commas are not used when entering numbers. For example: do not place
commas in 1000 or 1000000.
Enter
print 1000 * 1000
then
million := 1000000
and
print million * million
The result is surprising and is the computer’s way of representing very large
numbers. 1E12 means:
1 times 10^12 or 1 times 1000000000000
Very large numbers can be written in a compact way using this method, but we
won’t normally meet it .
23
3.8 Accuracy
Numbers are printed in Acornsoft COMAL accurate to the ninth figure. The
number may be stored in the same way that we have just seen: as two parts – a
number from 1 up to 10 together with a power of 10.
If the result of a calculation is neither very large nor very small then it is
printed out in the usual way.
The word ‘real’ is used to refer to numbers that may have fractional parts.
Integer and real numbers may be positive, negative or zero.
Enter
five# := 5
Enter
print five#
then
print five# / 2
The result is just the same as if any other variable had been used. The only
difference comes if you try to assign a decimal value to an integer variable.
Enter
five# := 5.899
and
print five#
24
The part after the decimal point is removed and five# takes only the whole
number part. This process is called ‘truncation’.
Enter
ten# := 10
then
print ten# / 3
and
print number#
A value is printed out for us even though we have not assigned a#. The integer
variables a# through to z# are always resident in the computer. We may
assign values to them if we wish.
3.10 Functions
We shall come across many functions. A function uses one or more values,
called the ‘arguments’, to calculate another (related) value. We shall always
use the word ‘return’ for the process of producing a value from a function.
3.11 INT
INT is an example of a function.
Enter
number = 5.678
and
print int(number)
25
number is the ‘argument’ and the value 5 was ‘returned’.
Enter
print int(-number)
then
print int(number*10)
The value inside the bracket, the argument, is calculated first and if it is not an
integer then the integer immediately below it is returned. If the argument is
already an integer then it is returned.
FREE is a system function. We can print the value of the variable FREE, but we
cannot assign values to it. We can’t give our computer more or less memory
using FREE. If we assign a new variable then we should see that FREE returns
a different value.
Enter
d := 123456789
and
print free
3.13 PI
PI is a constant used in many mathematical calculations for example, in
finding the area enclosed by a circle or the volume taken up by a sphere. It is
usually represented by the Greek symbol π. To find out what value is given to
PI enter
26
print pi
PI has a constant value and may be used whenever required. It isn’t a variable
and so cannot be assigned. The computer has a value for PI correct to ten
significant figures. It will normally print the value correct to nine significant
figures.
Enter
radius := 7
circumference := 2 * pi * radius
and
area := pi * radius * radius
Then
volume := 4/3 * pi * radius ^ 3
27
7. What is the value of int(7/2)?
8. What is the value of int(pi)?
4. Variable names can contain keywords anywhere inside them as part of the
complete name.
Examples: printout, sprint, pick.
5. A space must be typed after a keyword so that it is clear to the computer that
a variable is not being used.
6. The variable being assigned is on the left of :=
7. Commas must not be used when entering numbers.
8. 7.5E9 means 7.5 multiplied by 10^9 ie 7500000000
7.5E-9 means 7.5 divided by 10^9 ie 0.0000000075
28
4 Strings and CLEAR
In this section we shall learn about strings of symbols, how to handle them, and
how to use the keywords LEN, IN, DIM and CLEAR.
Let us again use lower case letters for our typing. Press the CAPS LOCK key, if
necessary, to turn off the caps lock and shift lock lights.
The symbols we assign to the string are placed in quotation marks. Use the
underline symbol and both quotation marks as you enter
any_old$ := "ABCDEFG"
The quotation marks are essential to mark the beginning and end of the string.
We may read the assignment as:
‘any old string becomes quote ABCDEFG unquote’
Enter
print any_old$
and
print any_old$
Because we can vary the symbols that we place inside the string, it is known as
a string variable. Its name must obey the same rules as for numeric variables.
29
It can contain a keyword as part of the name. For example, printout$ is
acceptable, but print$ is not.
and
print len(this$)
We should have got the value 5. It isn’t too hard to think of LEN( ) as
standing for length.
and
print len(try$)
Null string
In the following line the two quotation marks are placed next to each other,
with no space between.
30
Enter
blank$ = ""
and
print len(blank$)
The computer can cope with a string that has no symbols inside it. Such a
string is called a ‘null’ string.
4.3 IN
Here’s a good bit of typing practice.
Enter
alpha$ = "abcdefghijklmnopqrstuvwxyz"
Making sure you leave a space after print, use both quotation marks and
leave a space after in:
enter
print "c" in alpha$
and
print "z" in alpha$
Enter
test$ = "m"
and
print test$ in alpha$
and
print test$ in "lmn"
IN tells us where the first string starts to appear in the second string.
Enter
print "+" in alpha$
If the part in quotes is not in the string then the value 0 is returned.
31
Enter
print "cdef" in alpha$
and
print "cdefgh" in alpha$
Long strings
If we want to use a string containing more symbols (up to 253 are allowed)
then we must have a way of reserving more room. The process is called
dimensioning.
DIM is the keyword for reserving the space we need for a string.
Enter
dim long$ of 200
The keyword DIM is followed by a space, the string name, a space, the keyword
OF, a space and then the number of places that are to be reserved for the string.
32
Short strings
If the computer is likely to run out of available memory and we don’t need as
many as 40 places for the string then we can reserve less.
Enter
dim short$ of 5
and
short$ := "exact"
We must think ahead when dimensioning a string and anticipate the greatest
length we shall need.
Enter
short$ := "bigger"
We receive the error message that the string is too long for the space reserved.
The error message indicates that the variable has already had a space reserved
for it. We are not allowed to redimension that space.
and now we should find that the computer does not recognise the existence of
short$.
Enter
print short$
33
and we receive the Not found message.
Enter
print a#
and a value is printed because the resident integer variables a# to z# are not
cleared.
Enter
dim short$ of 10
Once CLEAR has been used a string may be dimensioned afresh to the length
required (up to 253).
and
c$ = "HARRY"
When we printed out numbers they appeared in zones of ten places, either on
the left or right depending on whether we used a semi-colon before the number.
There is a way in which we can make the strings appear in these same zones,
though they will be as far left as they can in each zone.
Having printed a$ the comma is the element of syntax that tells the computer
to move over to the next zone and then do the next bit of printing there. The b$
is then printed as far left as possible in that zone. The following comma
indicates that the next item, c$, is to appear in the next zone.
The comma is the instruction to PRINT in the next available zone. If the print
position is already at the beginning of a zone then a comma will not cause the
print position to change to another zone.
34
Using the semi-colon
Enter
print a$;b$;c$
The semi-colon has the same effect for strings as for numbers. The item that
follows is printed as far left as possible. In this case DICK follows TOM with no
gap. Similarly, HARRY follows DICK.
The semi-colon is the instruction to PRINT in the next available print position.
One important point to note is that after c$ there is no comma, to say move
across to the next zone; and there is no semi-colon to say print in the next space.
If there is no special symbol at the end of a PRINT command then the next
print position is at the beginning of the next line.
In a PRINT command the ' causes the print position to move to the beginning
of the next line.
Enter
print a$,b$'c$;
The symbols , ; ' are called print ‘separators’ and one of them must be used
between items that are to be printed.
Notice where the prompt and cursor are flashing. Having printed c$ the
semi-colon is the instruction to carry out the next print instruction in the next
available print position (ie alongside the end of c$). The next thing to be
printed is the prompt and then the cursor. If you want the prompt and the
cursor on the next line, all you have to do is press the RETURN key.
35
Making space
Meanwhile, we haven’t printed out TOM DICK HARRY in the way that we
might have expected with a space between their names. A space can be placed
inside a set of quotation marks and then be treated as a string. The semi-colons
are used as print separators.
Enter
print a$;" ";b$;" ";c$
Each string is added on to the end of the previous string and then the result is
printed. Adding strings in this way is called ‘concatenation’.
and
print d$
b$ := "DICK "
c$ := "HARRY."
36
Now enter
print a$;b$;c$
and
print a$ + b$ + c$
In computing there are often many ways of achieving the same result. There is
not necessarily a right or a wrong way.
Enter
quote$ := "this quote "" does work"
and
print quote$
2. ACORN Microcomputer
3. ACORN
Micro
computer
37
What would be the result of the following commands?
5. print reply$ IN "YyNn"
6. print reply$ IN "Nn"
7. print reply$ in "RGYBMCW"
8. print reply$ in "YYYYYYY"
9. print LEN(reply$)
What dimension statements would be needed to reserve
10. 100 places for ton$?
11. 40 places for test$?
12. 10 places for ten$?
38
5 Programs
In this section we shall learn how to construct a simple program and extend our
vocabulary of keywords.
So far we have given ‘direct’ commands, ie commands which are entered at the
keyboard and carried out immediately. To be useful, the computer needs to be
able to store a series of commands, and then to carry them out when we tell it
to.
The series of commands are stored as ‘program’ statements. (That is the
correct spelling for computer program.)
NEW is the keyword to instruct the computer to prepare for a new program to be
entered.
If you forget to start with a line number then the computer will take your
instruction as a ‘direct’ command and try to carry it out. That’s enough of the
theory! Let’s see how it works.
Use the CAPS LOCK key to switch off all the lights.
Now enter
1 print "I think"
Nothing should have happened unless you made an error in typing, in which
39
case, check what you should have entered and try again until the entry is
accepted.
The computer has remembered the statement and is waiting to see if there are
any more.
5.3 RUN
Enter
run
To make the computer carry out the instructions which it has stored, we give it
the direct command RUN.
It doesn’t matter whether the statements are in lower case or upper case.
Now enter
2 print "I am"
5.4 LIST
If we want to see all the lines of the program then we may use the direct
command LIST.
Enter
list
Program lines must begin with a whole number, so if we want to add extra
statements into the middle of a program then there must be room for them.
It was a bad idea to number the program lines 1 and 2, because there is now no
space left to place another program line between them.
5.5 RENUMBER
Enter
renumber
and
40
list
We can now add an extra program line between our existing lines.
Enter
15 print "therefore"
and
renumber
Enter
40 print "intelligent"
5.7 Editing
Sometimes we want to remove one of the lines from a program.
To remove a line from a program, type its line number and press RETURN.
41
Type
20
If we want to replace one line by another then all we need do is to type the new
line.
Enter
40 print "here"
Copy cursor
If we want to make a small change to an existing line then we can use an
editing facility. On the right there are four arrow keys and at the bottom right
of the keyboard there is a key marked COPY.
Press the upward pointing arrow once.
A marker block is left behind where the cursor used to be.
Use the arrow keys to move the cursor up (and down, if necessary) until it is
positioned in front of line 10 as shown below.
_ 10 PRINT "I think"
Now use the right (and left, if necessary) pointing arrows to move the cursor
under the 1 of the 10.
10 PRINT "I think"
42
not forgetting the closing quote, and press RETURN.
The complete line
10 PRINT "I know"
should now have been entered and the cursor should be back in its normal
place.
List and run the program to check it.
Now enter new and list the program.
You should find that nothing happens. The command NEW has made the
computer prepare for a new program. It makes it appear that you have lost
your previous work.
5.8 OLD
If you change your mind and want the previous program back again then you
may enter OLD.
Enter
old
and
list
The direct command OLD may restore the previous program provided that a
new program has not been started and that no new variables have been
introduced. OLD may also be used when the BREAK key has been pressed.
Provided that the program has not been corrupted it may be listed and run.
5.9 Abbreviations
Enter
20 p."that"
and
list
43
Enter
.
and you should get a listing of the program. This abbreviation certainly makes
for increased speed. There are short forms of most keywords. In the keyword
summaries given in Part III the abbreviations are shown at the top right of
each page.
Enter
new
5.11 AUTO
Enter
auto
producing
→auto
10 _
44
→auto
10 x := 3
20 _
AUTO is the direct command to produce line numbers in the sequence 10, 20,
30, …
Enter
y := 4
producing
100 _
The automatic numbering has restarted at 100 and will continue at intervals of
5. Complete the line by entering
print x*x + y*y
5.12 Comments
There is a way in which we can leave useful comments in a program by using
the keyword symbol // consisting of the division sign used twice. A long
program can be made much easier to understand by using comments.
Remarks or notes may be stored at the end of almost all program lines, or on a
line by themselves, using the keyword //.
45
Enter
110 print x + y // sum of values
Press ESCAPE to break out of the numbering sequence and then list and run
the program.
and
auto 100
END is a keyword that usually marks the physical end of a program. Its use is
optional and has no effect other than that no more program lines will be
executed once the END command has been encountered.
46
and press RETURN, producing
100 first$ := "ACORNSOFT "
line 120 to
120 second$ := "COMAL"
line 130 to
130 PRINT second$
producing
150 PRINT first$
then copy
+ second
producing
150 PRINT first$ + second
then type
$
47
The renumber command has caused the program listing to start at line 200
and go up in twenties.
Enter
renumber 200
7. Use a program line to assign the value 111 to the variable x, and then print
out the values of x, its square and its cube in zones across the screen.
48
5.16 End of section summary
1. A program is a stored set of statements that are carried out when the direct
command RUN is given.
2. Each program line consists of a whole number followed by a statement or
comment.
3. AUTO is a direct command to display line numbers in the sequence 10, 20, 30,
40 … waiting after each line number for a statement and the press of the
RETURN key before showing the next line number. AUTO 200 would start the
numbering at 200 going up by tens. AUTO 100,5 would produce the sequence
100, 105, 110, 115 etc.
4. ESCAPE can be used to break out of AUTO.
5. LIST is the direct command to display the program in the sequence of its line
numbers. An individual line of the program, such as line 80, can be shown by
using LIST 80. A continuous sequence of lines, such as from line 80 to 120,
can be displayed by the command LIST 80,120.
6. When a COMAL program is LISTed the keywords are shown in upper case
and the user variables in lower case. The abbreviation for LIST is a full stop.
7. P. is the abbreviation for PRINT.
8. // indicates that what follows is not a statement to be carried out by the
computer. Comments or remarks may follow the // symbol.
9. RENUMBER is the direct command to take the stored statements in the
sequence of their existing line numbers and renumber the lines in the sequence
10, 20, 30, 40 etc. RENUMBER 200,5 would start at 200 and go up in fives.
10. A line can be removed from the program by typing its line number and
pressing the RETURN key or by entering DEL and the line number.
11. A continuous sequence of program lines, such as from 50 to 100 can be
removed by using DEL 50,100.
12. The direct command NEW prepares for a new program to be entered.
13. A previous program may be recovered by the direct command OLD, provided
that a new program has not been started and no new variables have been
assigned.
14. END may be used to mark the physical end of a program. No more program
lines are carried out once END is encountered. Its use is optional.
49
6 Simple loops
In this section we shall learn how to repeat a set of statements using the
keywords FOR and NEXT.
and
auto
then complete the following program lines, taking care to use spaces where
shown.
10 print "Start here"
20 for number := 1 to 5 do
30 print "***************"
40 print "At line 40"
50 print "***************"
60 next number
70 print "All done"
80 end
Indentation
When a program is LISTed the statements between the lines containing FOR
and NEXT are ‘indented’ by two places. These are the statements that are
repeated.
50
6.2 Control of the loop
Notice that the variable number is in lower case, whereas FOR and NEXT are
in upper case.
In line 20 the value 1 is assigned to the variable number and then lines 30, 40
and 50 are carried out.
When line 60 is reached, the NEXT number has the effect of adding 1 on to
number, making it become 2.
Since 2 is in the range 1 TO 5 (as given in line 20), the lines 30, 40 and 50 are
carried out again.
The NEXT number is 3 and the loop is repeated; and so on until number is set
to 5, which is at the limit of the range. This value is allowed and the print
statements are carried out for the fifth time.
The NEXT number statement then sets number to 6, which is outside the
range 1 TO 5 and so the loop is finished and the computer continues into line
70.
Confirm this by entering the direct command
print number
After a program has run, the values of the variables are still stored and can be
used if required.
Loop variables
The variable that we use to count our way round the loop is called the ‘loop
variable’.
We can make use of a loop variable inside the loop.
Enter
40 print "This is loop ";number
then
51
auto 100
If the : or DO are left out of a FOR... statement then they will be inserted
automatically.
6.4 STEP
Negative STEP
52
List and run the program.
The value 1 is not printed. The series moves from 2, which is printed, to 0 which
brings the loop to an end.
Then enter
90 print "Start"
and
130 print "Finish"
In COMAL, the computer will bypass any FOR... NEXT... loop which
cannot be carried out properly and will carry on with the rest of the program.
53
and run it.
In line 40 we need to know the value of total before we can add on the value
of number and then reassign the new value back to total. That is why line 10
is needed: it assigns a value to total before we start the loop.
Any user variable appearing on the right of an assignment, must have been
introduced previously.
54
6.8 The :− notation
A command such as
money := money - cost
6.9 Doubling up
Enter new, auto and then the following:
10 dim star$ of 130 // space needed
20 star$ := "*"
30 print star$'
40 for go := 1 to 7
50 star$ :+ star$
60 print star$'
70 next go
80 end
55
What programs will produce the following sets of numbers?
1. 21 2. 10 3. 1
22 20 3
23 30 5
24 40 7
25 50 9
26 60 11
27 70 13
28 80 15
29 90 17
30 100 19
4. 2 5. 99 6. 2
4 88 2.5
6 77 3
8 66 3.5
10 55 4
12 44 4.5
14 33 5
16 22 5.5
18 11 6
20 0
What programs will produce the following?
7. *
*!
*!!
*!!!
*!!!!
*!!!!!
*!!!!!!
*!!!!!!!
8. ABAD
ABADABAD
ABADABADABADABAD
ABADABADABADABADABADABADABADABAD
56
2. When a program is LISTed the statements inside a FOR... NEXT... loop
are indented by two places.
3. STEP is used if the increment in a FOR... NEXT... loop is not 1.
Non-integral and negative steps may be used.
4. An impossible FOR... NEXT... loop is ignored and the program bypasses
it.
5. Any variable appearing on the right of an assignment must have been
introduced previously.
6. :+ is an abbreviation for adding on to an existing variable.
Examples: a$ :+ b$ is short for a$ := a$ + b$
x :+ y is short for x := x + y
8. After a program has been RUN the variables are still stored and may be
printed if required.
57
7 More about PRINT
In this section we shall learn how to print in various places on the screen.
CLS can be used at any stage of a program where we want to remove printing
from the area in which we display our typing (or text).
Enter new and then the following short program:
10 cls
20 for go := 1 to 16
30 print "*"
40 next go
Look closely to see that there is no space between the B of TAB and the open
bracket (. There should be a semi-colon after the close bracket.
List the program and notice that a space has been inserted between the TAB(
and the 15. This space will always appear in a listing.
Run the program.
58
Change line 30 to
30 PRINT TAB( 30);"*"
PRINT TAB( a); is the statement to start printing at the position numbered
‘a’ in the row. If the print position is already greater than ‘a’ printing occurs in
the next available position.
Variables in tabulation
We can get some patterns by using the loop variable inside the TAB( );
command.
Change line 30 to
30 PRINT TAB( go);"*"
Run and list. Examine the listing carefully and think why the asterisks appeared
in a diagonal line.
Change line 20 to
20 FOR go := 16 TO 1 STEP -1
Run and list then check the program to see how a negative STEP changed the
direction of the asterisks.
59
A program that is structurally unsound will not run and instead a list of the
errors will be displayed.
This same feature may also be obtained by using the direct command DEBUG,
which causes a test of the structure of a program and a report of any errors.
Enter
debug
and the same error message should be obtained. To repair the program we must
put back the NEXT statement. We can now discover another feature of Acornsoft
COMAL.
Did you notice that we didn’t put the variable go at the end of the statement?
Now list the program.
The loop variable go has been inserted in line 40. If the computer can tell that
the structure is unsound, then it can also work out which variable should follow
the NEXT statement and add it for us.
The loop variable need not be stated after a NEXT statement. The computer will
deduce the variable and will insert it automatically.
Enter
debug
DEBUG reports structural errors in a program. If there are no errors then there
is no report.
60
Notice that a prompt and the cursor appear in the line immediately after the one
in which Here was printed.
Now enter
print tab(10,8);"There"
7.5 Codes
The computer displays each symbol on the screen by keeping in its permanent
memory a record of the shapes. The computer uses numbers to refer to each
symbol. Since A and a have different shapes the computer refers to them by
different numbers. We can get the computer to tell us what number it uses.
Enter
cls
and
print ord("A")
The ORD stands for ‘Ordinal’ which is a mathematical word for the number
value. 65 is the code number for the letter A. ORD must be given a string value
to work on. That is why quotation marks are needed.
Enter
print ord("B")
ORD returns a number, which will be printed to the right of the zone, unless we
use a semi-colon. If ORD is applied to a string then the code given is that of the
first element of the string.
61
Enter
x$ := "ZEBRA"
and
print ord(x$) // no quotation marks.
and
print ord("z")
ASCII code
These numbers are part of an internationally known code for the characters used
on computers. This ensures that computers can communicate with each other in
the same number language. The code is called ASCII, short for American
Standard Code for Information Interchange.
ORD is the function that returns the ASCII code of a string element.
7.6 Characters
We can reverse the process just as easily. We can get the computer to tell us the
character it associates with a particular number.
Enter
print chr$(90)
The chr$ stands for ‘the character whose string is’ and may be read as
‘character string’.
CHR$ is a function that returns the symbol associated with a given ASCII code.
and
print chr$(49)
62
and
print chr$(48)
Notice that CHR$ returns a string. The number symbols are strings rather than
pure numbers. They are printed at the left of the zone.
Enter new and then the following program.
10 cls
20 for code := 65 to 90
30 print chr$(code), // note comma
40 next code
Number codes
Change line 20 to
20 FOR code := 48 TO 57
and change 30 to
30 PRINT ;code,CHR$(code)
63
Create programs to:
5. Display on the top nine rows, the word here with four spaces in front of it.
6. Display on the top nine rows, the integers from 1 to 9 with four spaces in front
of the numbers.
7. Display on the top nine rows, the integers from 1 to 9 with the first number
having one space in front of it and so on until the ninth number has nine spaces
in front of it.
8. Display at the beginning of rows 11 to 19 the characters whose ASCII codes
are 81 to 89.
3. A program that is structurally unsound will not run but will display the errors
detected in a pre-run test.
4. The loop variable need not be stated after a NEXT command. The computer
will deduce the variable and will insert it automatically, when the program is
listed or run.
5. PRINT TAB(across,down); is the command to print at place across
in the line given by the value of down.
6. CHR$ is a function which returns the character whose ASCII code is given.
7. ORD is a function which returns the ASCII code of the first element of its
string argument.
64
8 Modes and text colours
In this chapter we shall use some of the modes available and print in colour.
MODE is a system variable used to select the type of screen display. It may be
assigned a value from 0 to 7 (although 7 will give the same result as 6 on the
Acorn Electron). We can find its value as well as assign it. In a listing MODE will
be in capitals.
You should get 7 if you are using a BBC Microcomputer or 6 if you are using an
Acorn Electron. The range of modes available is from 0 to 7 (0 to 6 on the Acorn
Electron) though the BBC Microcomputer Model A uses only modes 4 to 7
unless it has had extra memory added.
65
Mode information table
MODE 0 1 2 3 4 5 6 7
Places
per line 80 40 20 80 40 20 40 40
Number
of lines 32 32 32 25 32 32 25 25
Text
colours 2 4 8 2 2 4 2 8
Graphics Yes Yes Yes No Yes Yes No Ltd
Changing mode
Enter
mode := 5
The screen is cleared when the mode is changed. The prompt may change shape
and printing starts at the top left.
In mode 5 we have four colours available of which we are using two already.
The background is black and the prompt and cursor are shown in white. Notice
that they are much larger than before. The other colours that we can use easily
in this mode are red and yellow.
If you are using a black and white television or a monochrome display then the
‘colours’ will appear as shades of the display colour.
Enter the following program, but don’t worry if the typing is continued on into
the next screen line. The line and its command will still be accepted when you
press RETURN.
100 mode := 5
110 colour 1
120 print "RED"
130 colour 2
140 print "YELLOW"
150 colour 3
160 print "WHITE"
170 end
66
and list.
The program is not lost when we change mode. Line 100 changes mode which
also clears the screen.
The symbol | is read as ‘control’ and when followed by an m or M has the same
meaning as pressing the RETURN key. There are other ‘control codes’
available, and a full list is given in section 40.2.
Press the key f0 (on the Acorn Electron use FUNC key and 0).
67
The screen should have been cleared as the MODE := 6 command was briefly
displayed and then carried out.
Now enter
*key 0 MODE := 6 |m LIST |m
68
Change 130 to
130 COLOUR yellow
and 150 to
150 COLOUR white
Now add
40 black := 0
170 colour black
180 print "BLACK"
190 colour white
200 end
Background colours
Add the line
105 colour 129
69
Now we can see the black lettering but the red print on a red background is a
bit difficult! The command colour 129 has set the background of our
printing to red instead of the more normal black.
It would be neater if the whole screen could have a red background instead of
just the part on which we have printed. This is easily achieved if we clear the
screen, because the colour used to wipe the screen is always the background
colour.
Press the f0 key then enter
107 cls
Selecting a number for COLOUR which is 128 greater than its normal value will
cause the background colour to change. This only works for printing that is to
follow. A CLS command will fill the screen with that colour.
or
colour 128 + white
Reverting to normal
If you want to get back to the normal colouring of white on black then a change
of mode will always reset the colours and clear the screen.
Enter
mode := 6
70
If you get back the message Bad Mode then your computer hasn’t enough
memory for the next program. (You can try it if you use MODE := 5 in line
10.)
Enter
new
71
Press the f0 function key then place a semi-colon at the end of line 50 obtaining
50 PRINT "********************";
8.4 No comment
After a program line which contains a * command you may not add a comment
using //. Try adding a comment to line 20 and then running the program.
Remove the comment from the end of line 20.
72
Assuming that you are using mode 2:
6. What command would be needed to set the print colour to green?
7. What commands would set the background colour to cyan across the whole
screen?
8. Create a program using a FOR... NEXT... loop to print the numbers 1 to
9 in green on a cyan background. The numbers should be printed in a column at
the end of the first zone. The print colour should then be reset to white.
9. What command should be entered so that when function key f2 was pressed
RENUMBER appeared on the screen?
10. What command should be entered so that when function key f2 is pressed a
program in the computer is renumbered?
11. What command should be entered so that when function key f2 is pressed a
program in the computer is renumbered and then lists in mode 6?
73
9 Getting information from
the keyboard
In this section we shall learn to take in values from the keyboard using the
keywords INPUT, GET and GET$.
line 120 to
120 input breadth
and add
102 print tab(0,5);
74
These statements will allow us to put in the numbers we choose for length
and breadth, then work out the area.
Start the program running and then read on.
A question mark is printed to let us know that an entry is expected. Type 12
and press RETURN.
The number 12 has been assigned to length.
Another question mark is printed to tell us that another entry is expected. Type
6 and press RETURN.
INPUT is the keyword for entering the value of a variable using the keyboard.
A question mark is printed to indicate that a reply is expected.
The program works very well, but we should need to be very inspired if we were
to guess what was wanted by the question mark when we first saw it.
and
115 print tab(5,5);"Breadth ";
Run the program again using new values for length and breadth.
75
Did you notice that this time there was no question mark? If you want a prompt
symbol such as ? or > then type it inside the prompt message.
Run the program a few times with, at first, very easy numbers that you can
check. It is important that you test that a computer program is behaving as you
were anticipating. Sometimes an error of typing or logic may give rise to the
unexpected. The computer will always do what you have told it, as far as it is
able.
Line 50 ensures that the message appears in the middle of the screen.
76
This program will run satisfactorily provided that name$ uses no more than 40
symbols. Try it.
If we want to use more than 40 symbols then we must use a DIMension
statement such as:
5 dim name$ of 60
x := GET is the instruction to wait until a key is pressed. The ASCII code for
that key is then assigned to x (provided that we do not press the ESCAPE key).
Run this program a few times. Notice that the RETURN key is not needed and
that the key symbol is not shown.
To decide what key has been pressed we can use CHR$( ).
Enter
50 print tab(5,9);"The key was ";chr$(x)
77
Enter
40 print tab(5,7);"The key was ";x$
and
50 print tab(5,9);"Its code is ";ord(x$)
to calculate and print out the value of i. This is the way of calculating simple
interest on a principal p, at a rate r% per annum for a time t years.
5. What amendments would you make to the average program in section 9.2 so
that you are asked ‘How many numbers are there?’ and the computer takes in
the number of values, the values and then averages them.
Check your solutions with those shown in chapter 43.
78
4. TAB( ); and INPUT cannot be combined in the same statement. If you
want to INPUT at a particular place on the screen then a PRINT TAB( a,d);
and an INPUT statement will achieve the required result.
5. When input is being taken from the keyboard, then x := GET assigns to
the variable x the ASCII code for the symbol which is next pressed on the
keyboard (provided that the ESCAPE key is not pressed).
6. When input is being taken from the keyboard, then x$ := GET$ assigns to
the variable x$ the symbol of the key which is next pressed (provided that the
ESCAPE key is not pressed).
79
10 Creating random
numbers
In this chapter we shall learn how to create random numbers and to make use of
TIME and NULL.
10.1 RND
Enter and run the following program, taking care not to type a space between
the rnd and the bracket.
10 for go := 1 to 10
20 print rnd(999)
30 next go
The values given are not the same every time. RND( ) is a keyword for the
process of finding a random number.
RND( 999) will produce a whole number from 1 to 999 inclusive.
80
Decimal values are only produced by RND( 1).
To produce a decimal random number between 0 and 100 we need only multiply
RND( 1) by 100.
Change 20 to
20 print 100 * rnd(1)
Displaying randomness
We can make it easier to see the number of ones, twos, threes etc if we use a
TAB( ); command.
Change line 40 to
40 print tab(5 * number);number
81
Uneven spread
That looks reasonable, but delete line 20 and change 70 to
70 print tab(2 * score);score
Change line 60 to
60 score := rnd(6,12)
10.5 TIME
Enter the direct command
print time
TIME is a system variable that measures the passage of time. It increases every
hundredth of a second.
That is why the second value of TIME was slightly greater than the first.
82
Now enter the direct commands
time := 0
and
print time
Run the program and notice how quickly it has been carried out. If you run the
program again you may not get exactly the same values. There may be small
differences depending on the exact moment at which the program starts and
what the computer was doing at that time.
83
The main reason for using NULL is clarity. If at a particular stage of a program
you want the computer to do nothing, then you may use the keyword NULL.
We shall discover a neater way of pausing in a later section.
84
11 Graphics
In this section we shall learn how to use some of the graphics facilities available
in Acornsoft COMAL.
11.3 DRAW
Change mode to 5 by entering
mode := 5
Starting from the bottom left of the screen a ‘line’ has been drawn to the point
which has coordinates 1000 across and 800 up. The graphics marker starts at
the bottom left of the screen after a change of mode.
Enter
draw 1200,400
85
The line has been drawn from the last point of the previous line to the point
1200 across and 400 up.
DRAW x,y is the command to draw a line to the point with coordinates x units
across the screen and y units up the screen. Each line is drawn from the last
position visited.
Change to mode 6.
Enter new and then
10 left := 0
20 right := 1279
30 bottom := 0
40 top := 1023
50 *key 0 mode := 6 |m list |m
60 mode := 5
70 draw right,bottom
80 draw right,top
90 draw left,top
100 draw left,bottom
11.4 MOVE
We don’t get the neat rectangle, because the first line starts in the wrong place.
We need to start our drawing from the point with coordinates 0,200. We need to
MOVE our graphics marker to that point before starting to DRAW.
MOVE x,y is the command to transfer the graphics marker (cursor) to the
point x,y without drawing a line.
Enter
65 move left,bottom
86
11.5 Graphics colours
We can easily use the colours that are available in each mode. The graphics
colours are changed quite independently of the colours in which we print text.
GCOL
The command GCOL is used to control the choice of graphics colours. Two
numbers then follow the command. For the moment we shall use nought, then
a comma, then the colour number we choose.
In mode 5, red is colour 1, so enter
67 GCOL 0,1
GCOL 0,n will set the graphics colour to the number n where n is any number
in the list of colours available for the mode being used.
The more experienced BBC Microcomputer user can refer to the section on
GCOL in Part III for the meaning of GCOL statements other than GCOL 0,n.
Random example
Change 30 to
30 bottom := 0
and add
110 move 640,512 // centre screen
120 for line := 1 to 20
130 x := rnd(1279)
140 y := rnd(1023)
150 number := rnd(3)
160 gcol 0,number
170 draw x,y
180 next line
87
11.6 Clearing graphics
Now enter the direct command
clg
and
64 clg
change 150 to
150 number := rnd(0,2)
The command CLG clears the graphics display area and leaves it in the current
graphics background colour.
Text background colour is set by a COLOUR command. CLS clears the text area
using text background colour.
Run the program again and then enter CLS to see the screen cleared in current
text background colour black.
producing
10 left := 0
20 right := 1279
88
30 bottom := 0
40 top := 1023
50 *key 0 mode := 6 |m list |m
60 MODE := 2
62 GCOL 0,128 + 7 // background white
65 MOVE left,bottom
67 GCOL 0,2
70 DRAW right,bottom
80 DRAW right,top
90 DRAW left,top
100 DRAW left,bottom
110 MOVE 640,512 // centre screen
120 FOR line = 1 TO 20 DO
130 x := RND( 1279)
140 y := RND( 1023)
150 number := RND( 0,6)
160 GCOL 0,number
170 DRAW x,y
180 NEXT line
Now run the program.
PLOT 69,x,y marks the point with coordinates x,y in the current graphics
foreground colour.
11.10 POINT(
It is possible to reverse the process and find out what colour is being used at any
position on the screen. Taking care not to use a space before the bracket, enter
print point(640,512)
89
Enter
print point(2000,2000)
The position is off the screen. The value -1 indicates that there is no colour
displayed.
POINT( x,y) returns the colour number at the point x,y on the screen. If
the point is off the screen then -1 is returned.
PLOT 85,x,y draws a line to the point x,y in the current graphics colour and
fills in a triangle made by the point x,y and the last two points visited.
Other shapes can be filled in using triangles. If the sequence of points is chosen
carefully then only four points need be visited to fill a quadrilateral.
Press f0, enter new and then the following program.
10 mode := 5
20 gcol 0,1 // red
30 move 400,700 // visit point A
40 move 800,700 // visit point B
50 plot 85,200,300 // fill triangle ABC
60 plot 85,1000,300 // fill triangle BCD
A B
C D
You will need to watch closely to see the individual triangles being drawn.
90
11.12 Windows
It is possible to define rectangular areas of the screen which may have text and
rectangular areas that may contain graphics. These areas (or ‘windows’) may
overlap. The text and graphics windows are both set to the complete screen
when there is a change of mode.
VDU commands
There is a set of visual display unit (VDU) commands, which affect the output
from the computer to the screen or a printer. They are listed in Part III. For the
moment we will learn how to use the ‘window’ commands only.
Text windows
The command to define a text window is VDU 28, it is followed by the TAB
position of the bottom left corner of the window then the TAB position of the top
right of the window. The TAB positions are the across and down values
separated by commas.
Example: VDU 28,2,24,17,16
will define a text window with the bottom left corner at position 2 across and 24
down. The top right of the window will be at position 17 across and 16 down.
If you define a window that will not fit on the screen then the text area is taken
to be the whole screen.
Press f0, enter new and the following program.
10 mode := 5
20 print tab( 2,5);"Colour choices"
30 print tab( 2,7);"1. Red"
40 print tab( 2,9);"2. Yellow"
50 print tab( 2,11);"3. White"
60 print tab( 2,14);
70 input "Choice 1-3 > ":choice
80 vdu 28,2,24,17,16
90 colour 128 + choice
100 cls
110 colour 0
120 print "Text window"
130 end
Printing will only take place in the text window. If the TAB( ) position cannot
occur in the window then the instruction is ignored and the printing occurs
without regard to the TAB( ) part of the command.
Enter
print tab( 20,20);"Can't"
The position does not occur in the window so the TAB( ) part of the command
has no effect and printing occurs on the next line.
VDU 28, is the command to set up a text window. It must be followed by four
values separated by commas. The first two values give the position of the
bottom left corner of the window. The last two values give the position of the
top right corner of the window.
When a text window is defined, a CLS command clears only the area defined by
the window.
Graphics windows
The command to define a graphics window is VDU 24,. It is followed by four
numbers each of which has a semi-colon after it. The first two numbers are the
coordinates of the bottom left of the graphics area and the last two numbers are
the coordinates of the top right of the graphics area.
Example:
VDU 24,400;200;900;800;
This command defines a graphics window with the bottom left hand corner at
the point 400 across and 200 up. The top right corner is at 900 across and 800
up.
A comma follows the VDU 24, but all the other numbers must be followed by
semi-colons. The reason for this is explained under VDU in Part III.
If you define a graphics window which will not fit on to the screen, then the
graphics window will be set to the whole screen.
92
Press f0, enter new and the following program.
10 red := 1
20 yellow := 2
30 white := 3
40 mode := 5
50 vdu 24,400;200;900;800;
60 gcol 0,128 + red
70 clg // set background to red
80 gcol 0,yellow
90 for y := 0 to 1000 step 40
100 move 0,y // left side of screen
110 draw 1000,500
120 next y
130 end
When a graphics window is defined, a CLG command clears only the area
defined by the window.
93
4. Write a program to draw a set of vertical lines down the screen at intervals of
100 units.
5. Write a program, making use of the PLOT 69, command to plot a set of
points at intervals of 80 units across the middle of the screen.
6. Write a program, making use of the PLOT 85, command, to draw a red
square of side 200 in the middle of the screen on a yellow background.
7. What command would define a text window which takes up the top half of
the screen?
8. What command would define a graphics window taking up the bottom half of
the screen?
94
12. The CLS command clears the area defined by a text window using the
current text background colour.
13. VDU 24, is the command to set up a graphics window. It is followed by the
coordinates of the bottom left and top right of the window. Each coordinate
should be followed by a semi-colon.
95
12 STOP and CONT
In this section we shall use the statement STOP and discover when a program
may be continued.
STOP is the statement that causes a program to stop and report the line on
which it stopped.
When the program is run the value 1 is given then the message
STOP at line 30 is displayed.
12.2 CONT
Enter
cont
96
CONT after ESCAPE
In certain circumstances a program can be continued after use of the ESCAPE
key.
Change 30 to
30 INPUT "Enter a word > ":word$
Don’t enter a word when you run the program. Instead press ESCAPE.
Look at the last value printed and notice what happens when you enter CONT
and INPUT a word.
The program should have continued from the line indicated by the ESCAPE
message. If the line was not fully executed when ESCAPE was pressed then
that line will be repeated.
Complete the program or press ESCAPE again.
Changing variables
Run the program and ESCAPE again. Now enter the direct commands
x := 45 and j := 0.5 then enter
cont
New and existing variables may be assigned during a break in the program.
and enter
cont
97
Now try to continue the program by entering
cont
Run the program and ESCAPE again. Whilst in this direct mode press
ESCAPE a second time.
Now enter
cont
98
13 PROCedures
99
1070 PRINT TAB( 10,20);
1080 INPUT "Your Choice 0-3 > ":choice
1090 COLOUR 128 + choice
1100 END PROC select_background_colour
The procedure begins with the keyword PROC and then the name of the
procedure. The procedure ends with the keywords END PROC and the name of
the procedure. There must be spaces between the END, the PROC and the
procedure name.
When a procedure is called, the flow of the program is diverted into that
procedure and back again. Indeed, the same procedure may be called into use
several times in the program.
The procedure has only one entry point and only one exit point. The flow of the
program is in at the beginning and out at the end.
When a program is listed the commands inside the procedure are indented by
two places.
A procedure name need not be entered after END PROC. It will be inserted
automatically. Leaving out the procedure name after END PROC is
particularly useful when you have long names for the procedures.
The program lines within the PROC definition are only carried out when the
procedure is called by name.
100
Below is a program example of a reaction timer which demonstrates the use of
procedures. It makes frequent use of the comment symbol // to break up the
program into sections and to add extra comments.
When a program listing is given it should include enough comments to enable
you (and anyone else) to see the structure of the program and what is
happening. Whilst this does take up computer memory, we have plenty and it is
better to write good programs which are clear, rather than incomprehensible
programs which might use a little less memory. A well structured program
with clear comments is, in fact, easier to write and usually very much faster to
correct if it does have an error (or bug) in it.
The program makes use of a *fx command. These commands control many of
the internal features or effects of the BBC Microcomputer. They are features of
the machine and not COMAL. See the BBC Microcomputer System User Guide
or the selection of *fx commands given in Part III.
Enter auto and then the following program.
100 // REACTION TESTER
110 //
120 MODE := 6
130 //
140 // Main program structure
150 //
160 display_instructions
170 pause
180 show_symbol
190 measure_response_time
200 display_result
210 //
220 // That's all!
230 // Now for the procedures.
240 //
1000 PROC display_instructions
1010 PRINT TAB( 3,5);"Press SPACE when you see a *"
1020 END PROC display_instructions
1030 //
1100 PROC pause
1110 delay := RND( 1500,3500)
1120 FOR pause := 1 TO delay DO
1130 NULL
1140 NEXT pause
1150 END PROC pause
1160 //
101
1200 PROC show_symbol
1210 PRINT TAB( 18,12);"*"
1220 TIME := 0
1230 END PROC show_symbol
1240 //
1300 PROC measure_response_time
1310 // next line removes any stored key presses
1320 *fx 21,0
1330 response$ := GET$
1340 wait := TIME
1350 END PROC measure_response_time
1360 //
1400 PROC display_result
1410 PRINT TAB( 5,21);"You reacted in ";
1420 PRINT ;wait / 100;" seconds"
1430 END PROC display_result
1440 //
1500 END
Run the program but don’t enter new just yet.
Enter LIST ,999
Notice that by using line numbers from 1000 upwards, we can easily separate
the main program structure from the procedures.
Note: some of the points in the following sections are designed to be used with
this program.
13.4 CLEAR
If you press ESCAPE and interrupt the program or if a STOP is encountered
inside a procedure, you will not be allowed to change mode until you have
entered CLEAR. This is so that it is possible to use CONT to continue the
program, if required. The command CLEAR removes all of the user variables
from the computer’s memory except the resident integer variables a# to z#.
102
13.5 EDIT
Enter
edit
EDIT is the command to list a program without the indentation. It may be used
with line numbers to restrict the range displayed, eg
EDIT 1100,1150 will show lines 1100 to 1150 inclusive.
EDIT 1340 will show just line 1340.
EDIT 1000, will show lines 1000 onwards.
Enter
EDIT ,210
13.6 EXEC
Technically the statement EXEC procedure_name should be used to call a
procedure into action. All the EXECs in a program are shown when EDIT is
used.
An EXEC is automatically inserted as the line is entered. However, when a
program is listed, that EXEC is not displayed. If you enter EXEC in a program
line, then that EXEC will always appear in the listing.
103
the listing at a particular page. To turn off this ‘paged mode’ listing you can
hold the CTRL key down and press the letter O key then release both keys.
Turn off the paged listing.
and then
show_symbol
4. What command will list a program with no indentation and with the EXEC
commands showing?
5. What variables are not removed when the command CLEAR is entered?
6. If a program is interrupted in the middle of a procedure what command
would you use before trying to change mode?
104
7. If you use CTRL N to turn on the page mode for listing, and then enter list,
how do you get the following page to list?
8. How is paged listing turned off?
9. How can you interrupt and hold a listing?
What is wrong with the following program lines?
10. 200 proctest
11. 200 PROC EDIT
12. 300 endproctest
105
14 Saving, loading and
running programs
If you have typed in a long program such as the reaction timer given in
chapter 13, then you will probably want to save it for future use.
14.1 Cataloguing
The *CAT is the command to give a CATalogue of the programs that are on
your tape or disc. It can be used if you want to work your way through a tape
seeing what programs are saved on it. A good index on your cassette cover is
also helpful and it saves time if you can use the tape counter numbers.
14.2 Filenames
A ‘filename’ is used for any program or set of data stored on cassette or disc.
The filename is the title by which you save or load the program. On a disc
system the filename can be up to seven letters whereas on cassette the filename
can be up to ten letters. It should not include spaces or punctuation marks.
When saving, no quotation marks are needed around the title, though they
may be used.
When the prompt appears on the screen, press the PLAY and RECORD
buttons and then press the RETURN key.
When the computer has finished its display of the number of blocks of program,
it gives a set of symbols that represent the program length.
106
You may now press STOP on the cassette recorder and rewind. You can test if
the program has saved properly. If you have a tone control, set it as high as
possible.
Enter
*cat
and
*cat
The title does not need quotations around it. A program title is considered to be
the same whether it is typed in capitals or small letters or a mixture.
107
Enter
*disc
Place the floppy disc fully inside the drive unit, but don’t close the door yet.
Enter
*cat
and whilst the disc is being spun inside the unit, close the door.
The catalogue of programs saved on the disc should appear on the screen.
Enter
save Title
No warning
If you choose a filename that already exists on your catalogue of programs then
you will lose the original program when you save the new one. No warning
message is given that the filename already exists, unless the file is locked.
Refer to the Disc Filing System User Guide under *ACCESS for details of
locking and unlocking files.
The command delete Title will remove the program called Title from
the catalogue of programs, unless that program is locked.
108
14.8 Combined loading and running
The command
run Title
109
15 Decisions
15.2 Relations
A decision must be based on a ‘condition’ which may be true or false. When we
write a program we do not know what the decision will be, but our program
must cope with the various possibilities. The ‘condition’ is a relation between
two values. We may compare in many ways. The following symbols are used.
Symbol Meaning
= The item on the left of the symbol is equal to the item on the
right of the symbol. Notice that this symbol represents equality,
and, therefore, does not have a : in front.
< The item on the left of the symbol is less than the item on the
right.
> The item on the left of the symbol is greater than the item on
the right.
<= The item on the left of the symbol is less than or equal to the
item on the right.
>= The item on the left of the symbol is greater than or equal to the
item on the right.
<> The item on the left of the symbol is not equal to the item on the
right.
IN The string on the left of the symbol is contained in the string on
the right.
110
15.3 Using conditions
Enter the direct command
if 2 < 3 then print "I believe that"
Use the arrow keys and COPY key to help you enter
if 2 > 3 then print "I believe that"
Nothing should have happened this time because the condition 2 > 3 is false
and therefore the computer did not carry out the print command.
A single line IF... THEN... command can be used, when there is only one
action to carry out.
Now use the copy facility again with each of the symbols
>= <= and <>
and
if "AAA" < "AAa" then print "True"
and
if "TOM" < "TIM" then print "True"
111
30 print ''"In which city is the Tower of London?"''
40 input "Your answer is > ":reply$
50 print ''"You have ";
60 if reply$ <> "LONDON" then print "not ";
70 print "passed the test."'
Now make sure the CAPS LOCK is on and run the program a few times with
right and wrong answers.
Omitting THEN
Now change line 60 to leave out the THEN producing
60 IF reply$ <> "LONDON" PRINT "NOT";
112
180 mark_and_respond
190 NEXT question
200 give_score
210 //
1000 PROC make_up_question
1010 first := RND( 2,9) // random number 2 to 9
1020 second := RND( 2,9)
1030 answer := first * second
1040 END PROC make_up_question
1050 //
1100 PROC ask_question
1110 CLS
1120 PRINT TAB( 5,5);"What is ";
1130 PRINT ;first;" times ";second;" ?"
1140 END PROC ask_question
1150 //
1200 PROC take_in_answer
1210 PRINT TAB( 5,8);
1220 INPUT "Your answer > ":reply
1230 END PROC take_in_answer
1240 //
1300 PROC mark_and_respond
1310 IF reply = answer THEN
1320 PRINT 'TAB( 5);"Correct"
1330 correct :+1
1340 END IF
1350 IF reply <> answer THEN PRINT 'TAB( 5);"Sorry,
it should be ";answer
1360 PRINT 'TAB( 5);"Press Space Bar"
1370 pause$ := GET$
1380 END PROC mark_and_respond
1390 //
1400 PROC give_score
1410 CLS
1420 PRINT TAB( 5,5);"You got ";
1430 PRINT ;correct;" right out of 5."
1440 END PROC give_score
1500 END
List the program and notice that the commands on lines 1320 and 1330 have
been indented by two further places.
Run the program and then list it again.
113
15.6 ELSE
In line 1350 we are using the opposite test to the one used in line 1310. The
commands are alternatives. We can make that clearer using the keyword ELSE.
Make the following changes and additions:
1340 else
1350 print 'tab(5);"Sorry, it should be ";answer
1355 end if
List the program. Notice that the ELSE occurs in line with the IF and the
END IF and that the lines between ELSE and END IF are further indented by
two places.
Run the program to prove that it still works.
2.
180 IF reply < answer THEN PRINT "Too low"
190 wrong :+ 1
200 END IF
3.
220 ELSE PRINT "Wrong"
4.
170 IF reply$ = answer$ THEN PRINT "correct"
180 ELSE
190 PRINT "wrong"
200 END IF
5.
150 IF reply > 9 THEN
160 PRINT "Too high"
170 END IF
180 ELSE
190 PRINT "OK"
114
6.
140 IF this = that THEN PRINT "Correct"
150 END IF
In the questions that follow, the answer programs should be short and don’t
need procedures.
7. Write a program to input two strings and print them out in alphabetical
order.
8. Extend the program in question 7 so that before or after is printed
between the words as appropriate, eg
CHICKEN before EGG
NIGHT after DAY
115
The END IF, which must have a space between END and IF, marks the end of
the statements that are to be carried out if the condition is met.
All the statements inside the structure will be indented by two places.
Multi-statement lines are not allowed.
4. When an alternative set of instructions is to be carried out if the condition is
not met then an ELSE statement may be used. ELSE must have a line to itself.
A single line IF... THEN... cannot precede an ELSE. The ELSE statement
will appear in line with the IF and END IF.
IF... THEN
...
ELSE
...
END IF
116
16 A conditional loop
In this chapter we shall learn how to use the REPEAT UNTIL... loop and
encounter TRUE and FALSE.
In chapter 6 we met the FOR... NEXT... loop which carried out a set of
statements a precise number of times.
Sometimes, when we are writing a program, we are not sure exactly how many
times we may need to carry out a set of statements. For example, we may not
know how many times we will need to take in an answer before it is correct.
In this situation a ‘conditional loop’ is needed. The loop will be carried out over
and over again UNTIL the condition is satisfied. As an example let us print out
random numbers from 1 to 6 until we get a 6. We don’t know how many we
shall print, other than that we shall print at least one.
16.1 REPEAT
REPEAT is the keyword to start a conditional loop, with a test at the end of the
loop. The test is given after the keyword UNTIL. REPEAT must be on a line of
its own.
In line 50 the test is whether x equals 6. The x is not being assigned the value 6.
List the program.
117
At least once
The condition that ends the loop is not encountered until we have passed
through the loop the first time. This is not the same as with the
FOR... NEXT... loop, which will not be carried out at all, if the FOR
command sets an impossible loop.
and
35 total :+ x // increase by x
Change 40 to
40 PRINT x,total
and 50 to
50 UNTIL total > 50
and change 50 to
50 UNTIL TIME > 50
118
Enter new and then the following program.
10 mode := 5
20 repeat
30 number := rnd(3)
40 colour number
50 across := rnd(0,19)
60 down := rnd(0,29)
70 print tab(across,down);"*"
80 until across + down
Any condition that is not FALSE will end a REPEAT UNTIL... loop.
and
print true
TRUE and FALSE are system functions that return the values -1 for TRUE and
0 for FALSE. They will list in capitals.
119
Run the program.
Press the ESCAPE key when you want that to stop.
The loop kept on running because the condition at the end was FALSE.
Change line 10 to
10 enough := true
Truncation
Change line 50 to
50 until 0.5
120
The ESCAPE key will be needed this time.
If UNTIL is followed by a real value (ie a number which may have a decimal
part) then the value is truncated (ie has its decimal part removed) and the
integer remaining is examined to see if it represents a true or false condition.
-0.5 would truncate to -0 (or 0) representing FALSE
+1.5 would truncate to 1 representing not FALSE ie true
-1.5 would truncate to -1 representing TRUE
Not FALSE
If the key Y or N is pressed, reply$ in "YyNn" will produce 1, 2, 3 or 4,
depending on whether we have the CAPS LOCK set on or off.
1, 2, 3 and 4 are all not zero and so would bring a REPEAT UNTIL... loop to
an end.
If any other key is pressed, reply$ in "YyNn" will produce 0 and so the loop
will continue.
Run the program.
Try pressing the number and letter keys other than Y and N.
Although the key press is detected, GET$ does not cause the symbol to be
printed.
Now try Y.
Repeat the program with y, N and n.
121
16.6 End of section exercise
1. Print out a random number from 1 to 26 until 26 is printed.
2. Amend the program in question 1 to print out a random number from 65 to
90 until 90 is produced.
3. Amend the program in question 2 to print random letters of the alphabet
until a letter Z is printed.
4. Create a program to print random letters of the alphabet in random positions
on the screen until a letter Z is printed.
5. Amend the stars program of section 16.2 to work in seven colours in mode 2.
6. Amend question 5 to print a random letter of the alphabet instead of a star.
Then amend further to print a random character whose ASCII code is from 32
to 126.
7. Write a program to ask a question which requires a Yes/No answer, accepts a
press of the Y or N key and then prints Yes in full or No in full.
8. Write a program to test multiplication of two random whole numbers (each
from 2 to 9), allowing as many questions as possible to be answered in 30
seconds and then giving a score.
Suggested solutions are given in chapter 43.
122
17 Storing information in a
program
In this section we shall learn how to use the READ statement, the DATA statement
and EOD.
In an earlier section we learnt how to take in values from the keyboard using
the INPUT and GET statements. They were particularly useful where we
wanted to control some part of the program, eg the colour to be used. However,
the statement INPUT can be very inefficient: every time we run the program
we have to enter the information. There is an alternative way in which we may
give information to the computer using data statements.
17.1 DATA
Data can be thought of as ‘a collection of values that may be referred to’. The
items of data can be stored on a program line.
The values stored on a DATA line must be separated by commas, but strings
need not normally have quotation marks.
17.2 READ
The READ statement is used whenever we require to take in a value from the
list of DATA and assign it to a variable, eg READ number or READ name$.
123
Run the program.
Change 60 to
60 DATA 5,4,3,2,1
17.3 EOD
When there is no more data, we don’t normally want the computer to produce
an error message and decline to continue.
In COMAL we have a marker to indicate when we have come to the End Of
Data (EOD).
EOD is a system function that returns one of two values, TRUE, -1 or FALSE,
0. Whilst there is more DATA to be READ, EOD is set to FALSE. When all the
data has been READ, EOD is set to TRUE.
Change line 50 to
50 UNTIL eod
17.4 RESTORE
It is sometimes useful to be able to refer to the same set of data whenever it is
needed. We need to be able to set the pointer back to the beginning of the list.
The keyword RESTORE can be used to reset the pointer to the beginning of the
DATA in the program.
124
Change lines 20 and 50 to
20 for item := 1 to 7
50 next item
and add
70 restore
80 read number
90 print number
Labels
We can store several sets of quite different DATA in a program. If we need to
refer to a particular set then we must be able to reset the pointer to the
beginning of that set of DATA. We can do this by using ‘labels’ that mark the
beginning of a set of DATA.
A ‘label’ may be placed anywhere in a program on a line of its own. The label is
indicated by placing a colon : immediately after a name. The label name must
obey the same rules as for a variable.
125
Change 70 to
70 RESTORE second_set
RESTORE can be used with a label to indicate the place from which DATA is to
be read next.
or
READ a$,b$,c$
or
READ name$,code,tel_number
126
100 DATA "Newton St. Thomas",SOMETOWN,SO11 1CE
110 DATA "Sir Edwin Drood, M.P.",The Manor
120 DATA Littleton,Nr ROCHESTER,RO1 5TE
Add your own data lines and run the program.
This is a most useful feature. Without it we would be limited in our use of data
items or we should have to go through some unpleasant programming to enter
quotations into our strings.
127
140 PRINT'"What is ";x;" times ";y'
150 INPUT "Your answer is > ":answer
160 IF answer = x * y THEN
170 PRINT ',good$'
180 ELSE
190 PRINT ',bad$'
200 END IF
210 UNTIL EOD
220 //
230 DATA 7,9,Good,Sorry
240 DATA 12,8,Splendid,Incorrect
250 DATA 23,76,Excellent,Not quite
260 DATA 2,2,Well done,Oh dear !
Now, test the program using right and wrong answers.
Run the program. The data is taken to be string data if the READ command is to
read a string.
Change 20 to
20 PRINT '"Numeric x"
40 to
40 READ x
and 50 to
50 PRINT x
and run the program again. This time the data is taken to be numeric because
the READ statement indicates that numeric DATA is expected.
128
17.10 End of section exercise
Suggested answers are in chapter 43.
What is wrong with the following parts of programs?
1.
100 here
120 DATA 1,2,3,4,5,6
130 READ x
140 PRINT x
150 RESTORE here
2.
100 DATA 9,10,Jack,Queen,King,Ace
110 FOR card = 1 TO 3
120 READ number
130 PRINT number
140 NEXT card
3.
100 DATA 2 3 4 5 6 7 8 9
110 REPEAT
120 READ number
130 PRINT number
140 UNTIL EOD
4.
100 suit:
110 DATA Clubs,Diamonds,Hearts,Spades
120 FOR choice := 1 TO RND( 4)
130 READ suit$
140 RESTORE suit
150 NEXT choice
160 PRINT suit$
129
17.11 End of section summary
1. String and numeric DATA may be stored on a program line which begins with
the keyword DATA.
2. The values may be assigned to a variable by the keyword READ.
3. The values stored on a DATA line must be separated by commas, but strings
do not normally need quotes.
4. A double quotation mark ("") may be used to indicate the position of a single
quotation mark when a string has quotes around it.
5. A pointer to the next unread DATA item is kept by the computer.
6. The pointer can be reset to the beginning of the DATA by the command
RESTORE.
7. A label may be placed on its own line in a program. The label is indicated by a
colon following immediately after any name which meets the requirements of a
variable.
8. The pointer can be set to a particular place by the command RESTORE
followed by the name of a label. Example: RESTORE here, where here: is a
label in the program.
9. EOD is a system function which returns either -1, TRUE or 0, FALSE
depending on whether the End Of Data has been reached. EOD can be used as a
condition to end a REPEAT UNTIL... loop.
130
18 More functions, operators
and variables
In this chapter we shall encounter the system functions POS, VPOS, COUNT, ABS
and SGN. We shall also use the operators DIV and MOD and control printing
with WIDTH.
POS is a function which returns the number of the current cursor position
across the screen. It is the position at which printing will continue.
VPOS is a function which returns the number of the current cursor position
down the screen. It is the position at which printing will continue.
The computer can tell us the position of the cursor using POS for position across
the screen and VPOS for the vertical position down the screen.
Enter (in the direct mode)
print pos
and
print vpos
POS is zero because when the RETURN key is pressed the POSition at which
printing will continue is at the beginning of the next line.
You cannot move the cursor by trying to assign values to POS and VPOS. They
are functions that return values. Any attempt to assign values will produce a
Not allowed error message. Try it if you like.
131
18.2 Examples of POS and VPOS
Enter the following program to show the effect of POS
10 mode := 6
20 repeat
30 print "*";
40 until pos = 19
132
feed. When a PRINT command finishes without a comma or semi-colon then a
carriage return is used to make the next print position move on to a fresh line.
A carriage return is not considered to have occurred if the printing overflows
from one line into the next.
The terms carriage return and line feed are still in use. They also apply to the
actions of a printer when the print head moves to the beginning of a line and
when the paper is moved up.
18.4 COUNT
The computer keeps a record of how many characters it has printed since the
last ‘carriage return’.
COUNT is the function which returns the number of characters printed since a
carriage return.
When printing ‘overflows’ into the next line COUNT does not reset to zero, but
continues to count on.
Change line 40 to
40 UNTIL COUNT = 100
18.5 WIDTH
Add the line
15 WIDTH := 15
133
Entertaining, but not very helpful in a listing.
Enter the direct command
WIDTH := 0
18.6 ABS
ABS is a function which returns the ‘absolute’ value of a number, ie its size
disregarding sign, eg ABS(3) and ABS(-3) both return 3.
18.7 SGN
Change line 30 to
30 PRINT j,SGN(j)
134
18.8 DIV
DIV is a binary operator that has an effect similar to division, except that it
expects to work with integers and it produces an integer.
The whole number which is to be divided, goes in front of DIV and the whole
number by which we are dividing, follows DIV.
6 DIV 3 gives 2, but 7 DIV 3 also gives 2 because DIV returns only the
whole number result.
If we apply DIV to a decimal value then, in Acornsoft COMAL, the decimal
fraction part is ignored, for example: 6.2 DIV 3 returns 2.
If we use a non-integral value for DIV to divide by, then that has its fractional
part ignored, for example: 6 DIV 2.9 returns 3.
DIV returns the whole number of times that one whole number may be divided
by another whole number.
Change 30 to
30 PRINT j,j DIV 3 // Notice spaces
The spaces are needed so that the keyword DIV is not thought to be part of a
variable jdiv3.
List and run.
Notice how the negative numbers are treated.
18.9 MOD
MOD is a binary operator that returns the integral remainder when one integer
is divided by another. If MOD operates on non-integral values then, in Acornsoft
COMAL, it removes the fractional parts and returns the whole number
remainder of the division, for example:
24 MOD 6 returns 0 24 MOD 5 returns 4
6 MOD 6 returns 0 24.5 MOD 5 returns 4
5 MOD 6 returns 5 24 MOD 5.2 returns 4
MOD returns the whole number remainder of dividing one whole number by
another.
Change 30 to
30 PRINT j, j DIV 3, j MOD 3
MOD and DIV have a higher precedence than + and - but the same as * or /.
Enter
PRINT 2*5 MOD 3
136
Using the functions ABS, SGN, DIV, MOD and INT what programs would
produce the following sets of numbers?
10. 5 11. 1 12. 3
4 1 3
3 0 3
2 -1 2
1 -1 2
0 -1 2
1 -1 1
2 1
3 1
13. 4 14. 2 15. 2
3 1 2
2 0 1
1 2 1
0 1 0
4 0 0
3 -1 -1
2 -2 -1
1 0 -2
0 -1 -2
137
7. MOD is an operator that returns the whole number remainder when one
whole number is divided by another.
8. MOD and DIV have a higher precedence than + or - and the same precedence
as * or /.
138
19 Arrays
In this section we shall learn how to use an array to store a set of similar items
and how to dimension the array.
19.1 Introduction
Imagine a squad of servicemen being given drill instruction. The instructor
sees a fault in the way an arm is positioned and snaps out a command.
‘Straighten your arm: rear rank, number three!’
The whole squad is being told, but the instruction is directly addressed to one
member of the squad who is identified by the rank and by position along that
rank.
We can use a similar method to handle sets of information in the computer. We
can use one variable to refer to the ‘squad’ of values and then identify
individual items by using numbers that indicate the row and position in that
row.
The computer squad is called an ‘array’ and the numbers that identify
individual items are called ‘subscripts’. For example, if we want to keep a
record of pieces on a chess board then piece$(5,4) could represent the
name of the piece which is in the fifth row and on the fourth place. The 5 is the
first subscript and the 4 is the second subscript.
19.2 Dimensions
The array need not have two ‘subscripts’, it could have just one, or in Acornsoft
COMAL it could have as many as eight. Each subscript represents a
‘dimension’ of the array.
total(9) could be assigned as, say, the total marks scored by candidate
number 9. total( ) is a one-dimensional array.
item$(3,2,12) could refer to the name of the component which is stored in
tray 12 of level 2 of the store cabinet 3. item$ is a three dimensional array.
139
19.3 Storing arrays
The computer memory is certainly not eight dimensional. How can it cope with
the storage of array elements?
If we go back to the ‘squad’ idea then we can see what happens. Imagine that
the instructor wants to take his squad into a classroom for a lesson. He cannot
march them into the room as a squad, because only one person at a time can go
through the doorway. However, if the instructor turns the squad to face the
side, he can tell the front rank to march off into the classroom followed by the
centre rank and finally the rear rank.
***********
***********
***********
becomes
***********
***********
***********
which becomes
***********
***********
***********
and finally
*********************************
A continuous list of values can be stored in the computer quite easily, but how
does the computer then find the fifth item in the second row?
If the computer knows how many items are in each row then it can go past that
number of items and then start counting the second row until it gets to the fifth
item and similarly for other rows.
To store and identify items in an array the computer must be told the number
of dimensions and the number of elements in each dimension.
140
DIM price(20) will set aside space for the array of items referred to as
price(0) through to price(20), ie 21 elements in total.
When a numeric array is dimensioned all the elements are set to zero. When a
string array is dimensioned, all the elements are null strings, ie ""
Now add
45 price(number) := rnd(99)
and list.
This program will place a random number from 1 to 99 into each of the
elements of the array. The computer then obtains the value from the element
and prints it out.
Run the program.
We can find an individual element of the array by using a direct command.
Enter
print price(20)
141
The lower and upper bounds of a subscript can be set when the array is
dimensioned. For example:
DIM diagonal#(-7:7) will create a one dimensional integer array from
diagonal#(-7) to diagonal#(7).
When a string array is dimensioned, the room reserved for each element is the
same as for an ordinary string, ie 40 places.
We may reserve more or less space if we wish by using the OF command, for
example: DIM initial$(1:100) OF 5. This command would reserve five
places for each of the elements initial$(1) through to initial$(100).
This would represent a saving of 100 times 35 memory places, ie 3500 in total –
a most significant saving.
An existing array cannot be redimensioned, nor can the length of the string
array elements be changed once they are set.
Lines 140 to 170 call the procedures which form the program.
If we can now write each procedure then the program is complete.
142
We can place the procedures on predetermined lines, usually beginning on a
round number.
Enter
1000 proc initialise
It would be more interesting to see the scores build up as they are ‘shaken’.
Add
1110 print tab(0,20);"Score.2..3..4..5.
.6..7..8..9..10.11.12"''"Total"
and
1310 vdu 23,1,1;0;0;0; // cursor on
1320 print tab(0,5); // park cursor
145
1260 NEXT shake
1280 END PROC display
1290 //
1300 PROC finish
1310 VDU 23,1,1;0;0;0; // cursor on
1320 PRINT TAB( 0,5); // park cursor
1380 END PROC finish
1390 //
1400 END
146
4. Up to eight dimensions may be used in an array. Example:
DIM coins#(1:2,1:2,1:2,1:2,1:2,1:2,1:2,1:2)
5. When a numeric array is dimensioned, all its elements are set to zero. When
a string array is dimensioned all its elements are set to null strings.
6. 40 spaces are reserved for each element of a string array unless the keyword
OF is used to set the length. Example: DIM postcode$(100) OF 9 will
reserve nine spaces for each of the 101 elements of the array postcode$(0)
to postcode$(100).
7. An existing array cannot be redimensioned. Nor can the length of the string
array elements be changed once they are set.
147
20 More on the keyboard,
loops and functions
In this chapter we shall learn about timed tests for key presses. We shall READ
data into an array using loops and also encounter VAL and STR$.
In earlier sections we used GET or GET$ to wait until a key was pressed. We
also used TIME to measure a delay. They can be combined in one statement.
20.1 INKEY
The internal ‘clock’ works in hundredths of a second so a delay of 200
represents a pause of two seconds.
148
20.2 INKEY$
Change the following lines so that we can use INKEY$. The changes are
underlined.
40 answer$ := INKEY$ (200)
50 IF answer$ = "" THEN
80 PRINT TAB( 25,8);answer$
100 x$ := INKEY$ (100) // to see comment
INKEY(-n) is a function that tests whether the key with ‘keyboard scan
number’ n is being pressed. There is no time delay used. If the key is being
pressed at the time when the test is made then the value TRUE (-1) is given,
otherwise FALSE (0) is produced.
We can use the keyboard scan number to test for normal as well as special keys.
Enter new and then
10 mode := 6
20 print ''"Press the RETURN key"
30 delay := inkey(100) // pause for title
40 repeat
50 test := inkey(-74)
60 print test
70 until time<0 // loop for ever
149
ESCAPE, list, delete lines 20 and 30 and change line 50 to
50 test := inkey(-99)
Now run the program and see if you can find which key on the keyboard has a
scan number of 99.
97 17 34 35 52 36 69 54 38 55 56 72 57 41 58 42
65 2 66 82 51 68 84 85 70 71 87 88 73 89 74
99
The scan codes for 1 and ! are the same. To distinguish between them we should
need to test for the SHIFT or SHIFT LOCK.
65 17 34 35 52 36 69 54 38 55 56 58 42 106
2 66 82 51 68 84 85 70 71 87 88 73 74
99
The ‘function’ key being used is found by testing for both the FUNC key and
the appropriate number key being pressed at the same time.
150
20.7 Example program
Enter this inkey minus program.
100 // Movement
110 //
120 MODE := 4
130 initialise
140 REPEAT
150 test_keys
160 test_off_screen
170 show_star
180 UNTIL FALSE
190 //
1000 PROC initialise
1010 across := 19 // Start Mid Screen
1020 down := 15
1030 VDU 23,1,0;0;0;0; // Cursor off
1040 left := -26 // Inkey values
1050 right := -122
1060 up := -58
1070 back := -42 // down already used
1080 END PROC initialise
1090 //
1100 PROC test_keys
1110 IF INKEY (left) THEN across:-1 // take one off
1120 IF INKEY (right) THEN across:+1 // add one on
1130 IF INKEY (up) THEN down:-1 // TAB down less
1140 IF INKEY (back) THEN down:+1 // TAB down more
1180 END PROC test_keys
1190 //
1200 PROC test_off_screen
1210 // if off sides then swap
1220 IF across < 0 THEN across := 39
1230 IF across >39 THEN across := 0
1240 // if off top/bottom then swap
1250 IF down <0 THEN down := 29
1260 IF down >29 THEN down := 0
1280 END PROC test_off_screen
1290 //
1300 PROC show_star
1310 PRINT TAB( across,down);"*"
1320 FOR delay := 1 TO 28 DO
1330 NULL // slow to our speed
151
1340 NEXT delay
1350 // Now wipe off
1360 PRINT TAB( across,down);" "
1380 END PROC show_star
1390 //
1400 END // Change mode to get cursor
Now run the program using arrow keys to move the star. Try pairs of keys to
see if you can get diagonal movement.
152
Inner loop completed first
List the program.
Notice that the stars are printed as a series of columns.
The inner loop is carried out fully and will be carried out every time the outer
loop increases by one.
Change line 40 to
40 print tab(k,j);"*"
and run.
This time the rows are completed first.
Mixed up loops
FOR and NEXT k are ‘nested’ inside the FOR and NEXT j (one loop is inside the
other). If you mix up the loop variables, then you will receive a set of error
messages when you try to run the program. Try swapping the j and k by
entering
60 NEXT j
70 NEXT k
The variables will be inserted correctly. List to see that the structure is now
correct.
Enter new and the following array reading program.
10 DIM array(3,5)
20 MODE := 6
30 FOR j:= 1 TO 5 DO
40 FOR k := 1 TO 3 DO
50 READ array(k,j)
60 PRINT TAB( k,j);array(k,j)
70 delay:= INKEY (10) // slow down
80 NEXT k
90 NEXT j
100 DATA 1,1,1,2,2,2,3,3,3,4,4,4,5,5,5
153
Now change line 60 to
60 PRINT TAB( j,k);array(k,j)
20.11 VAL
The point has been made that we cannot carry out a calculation with a string.
However, we do have a function which can evaluate a suitable string.
VAL is a function which returns the value that a string would have produced, if
it had been a mathematical expression.
and then
print val(this$)
VAL takes the string called this$ and tries to work out its value as if it had
been a normal calculation.
Enter
that$ := "len nonsense"
154
and
print val(that$)
20.12 STR$
There is a process for converting numeric elements to strings.
Change 30 to
30 INPUT "Enter a number > ":reply
and 40 to
40 PRINT 'reply,STR$ (reply)'
155
20.13 End of section exercise
Make a note of your answers and check them in chapter 43.
1. What commands will have the following effects?
a) Waiting for a key to be pressed for up to one second and to assign the symbol
of the key to a$.
b) Waiting for a key to be pressed for up to two seconds and to assign the ASCII
code of the key to b.
c) Testing to see if the key C is being pressed and printing -1 if it is.
2. What is wrong with the following program?
10 FOR j := 1 TO 5 DO
20 FOR k := -5 TO 1 DO
30 PRINT j*j - k*k
40 NEXT j
50 NEXT k
156
21 Logical operators
In this chapter we shall extend the scope of the conditions we may use in IF
structures and REPEAT loops. We shall use the logical operators OR, AND, EOR
and NOT.
21.1 OR
In the section on the REPEAT UNTIL... loop we placed a condition at the end
of the loop. If the condition is met then the loop ends. We sometimes wish to end
a loop when either one OR other of two conditions is met.
The logical operator OR may be used to provide a true or FALSE result after
examining two conditions. If one OR other of the conditions is true then the
result is true.
The logical operator AND is used to test two conditions. If both conditions are
TRUE then TRUE is returned. If either of the conditions is FALSE then FALSE
is returned.
21.3 EOR
The logical operator EOR (Exclusive OR) can be used to test whether one or other
(but not both) of two conditions is true.
In the following program we shall print a star if the row is less than 12 OR if
the column is less than 19, but not if both conditions apply.
Enter new and
10 MODE := 6
20 FOR down := 0 TO 23 DO
30 FOR across := 0 TO 39 DO
40 IF down < 12 EOR across < 19
THEN PRINT TAB( across,down);"*"
50 NEXT across
60 NEXT down
158
For example: if statement 1 is T(RUE) but statement 2 is F(ALSE)
then T OR F will have the result T(RUE)
T AND F will have the result F(ALSE)
T EOR F will have the result T(RUE)
Statement 2
OR T F
Statement T T T
1 F T F
Statement 2
AND T F
Statement T T F
1 F F F
Statement 2
EOR T F
Statement T F T
1 F T F
159
Each binary digit of one number is compared with the corresponding binary digit
of the other number according to the rules of OR, AND and EOR. 1 or 0 is then
used in the appropriate place of the returned value.
As an example using just two binary digits we can see how the operator OR
works.
1 OR 3 will return the value 3. Comparisons are made for each of the columns
and if there is a 1 in either one OR other of the places then a 1 is used in that
column of the result.
Binary digits
Number
(base 10) Column values
2 1
1 0 1
OR
3 1 1
Result 3 1 1
The binary number 11 (decimal 3) is returned by the operation 1 OR 3.
If the value returned by the OR operator is 0 then it represents a FALSE
condition. Any other (integer) value represents a true condition.
The logical operator AND will give a 1 in the result if there is a 1 in the
corresponding places of both the arguments.
Binary digits
Number
(base 10) Column values
2 1
2 1 0
AND
1 0 1
Result 0 0 0
The binary number 00 (decimal 0) is returned by the operation 2 AND 1.
The operator EOR gives a 1 in the result place only if there is a 1 in one or other
of the corresponding places of the argument but not in both.
160
Binary digits
Number
(base 10) Column values
2 1
2 1 0
EOR
3 1 1
Result 1 0 1
The binary number 01 (decimal 1) is returned by the operation 2 EOR 3.
21.6 NOT
The keyword NOT reverses the values of TRUE and FALSE.
Enter
PRINT NOT TRUE
and
PRINT NOT FALSE
The computer considers any value which is not zero to represent a true condition.
For example, neither 5 nor -6 is FALSE, so they both represent a condition that
will be taken to mean true.
161
Enter new and the following program.
10 MODE := 6
20 PRINT TAB( 5,5);"Press any number key"
30 REPEAT
40 x$ := GET$
50 UNTIL x$ IN "1234567890"
60 PRINT x$'"Finished"
The brackets are needed so that the IN function is carried out before the NOT.
NOT cannot act on a string. Now run the program and press the 5 key.
162
NOT has the highest precedence.
If OR and EOR are encountered in the same expression then they are applied in
the order in which they occur.
Example:
2<3 EOR 3<4 AND 5<4
is treated as
2<3 EOR ( 3<4 AND 5<4 )
that is
TRUE EOR FALSE returning TRUE
whereas
( 2<3 EOR 3<4 ) AND 5<4
that is
FALSE AND FALSE returns FALSE
163
What numbers are represented by
9. NOT 0
10. NOT -1
11. NOT 1
The answers are given in chapter 43, but they can also be checked by instructing
the computer to PRINT the statements given in the questions.
164
Part II – for the more
experienced programmer
22 Summary of Part I
167
Keyword Brief outline Section
168
Keyword Brief outline Section
169
2. A pre-run check tests whether there are any errors in the structure of the
program. If any are found, then they are reported and the program does not
run.
3. Multi-statement lines are not allowed. This makes programs slightly longer,
but they are much clearer to read, understand and edit.
4. Keywords will list in upper case and user variables in lower case. This makes
the actions of a program stand out.
5. Statements which are inside loops or other structures are indented when a
program is listed. The overall structure of the program is then clearly visible.
6. Many of the formal details of syntax are entered automatically.
7. Spaces are stripped off the front and end of a line on entry and spaces after
keywords are cut down to one.
8. Procedures may be called by their name without use of an EXEC. The
procedure is defined between statements PROC and END PROC each of which is
followed by the procedure name.
Statements
A null FOR... NEXT... loop in which the end is before the start is ignored.
The loop will be bypassed.
The loop variable need not be stated in a NEXT statement. The variable will be
deduced and inserted automatically.
NULL is the statement to do nothing.
170
When several statements are to be carried out following an IF condition then a
multi-line structure must be used. The structure is closed by END IF which
must have a space between the words. The format is
IF... THEN
Command 1
Command 2
etc
END IF
Constants
TRUE has the value -1 and FALSE has the value 0. In a test of a condition, any
non-zero value is considered to represent true. Note, however, that real values
are truncated to integers before being tested in conditions.
PI returns the value 3.141592653.
Variables
The proper symbol for assignment is := though if the : is omitted it will be
inserted automatically and shown in listings, eg 10 number = 2 becomes
10 number := 2.
Any user variable appearing on the right of an assignment must have been
introduced previously.
Apart from using keywords, any word or collection of letters, figures and the
underline symbol may be used as a variable provided that it starts with a letter.
A variable may contain a keyword anywhere as part of its name. The following
are valid variable names:
k9 r2d2 me_and_u printer_on total cost
OF is the keyword used when indicating the amount of memory to reserve for a
string, for example:
DIM my$ OF 60
171
The maximum number of places reserved for a string may not be altered once
set.
An attempt to assign more characters to a string than have been reserved, will
produce an error message.
A quotation mark may be placed inside a string by using a double quotation
mark "" to indicate its position.
MODE is a system variable which can be assigned a value from 0 to 7 (although
on the Acorn Electron assigning the value 7 will give mode 6). It may be used in
the same way as any other variable. For example, the mode currently in use
can be found from PRINT MODE and the mode may be changed by a statement
such as MODE := 6.
EOD, which stands for End Of Data, is set to TRUE when all data has been read,
but otherwise is set to FALSE.
System variables may only be assigned directly and not, for example, by using
INPUT.
Labels
A label may be placed anywhere in a program on a line of its own. It is indicated
by placing a colon immediately after any name which meets the requirements
of a numeric variable name, for example: here: or prices:. The colon is not
used when the label is indicated, for example: RESTORE here.
Arrays
Real, integer and string arrays are all allowed and may have up to eight
dimensions. The array must be dimensioned before being used, for example:
DIM this$(3,4,5)
The bounds of a subscript may be set in the dimension statement and can
include negative values.
Example: DIM this$(1:3,-4:-2,4:5)
If no lower bound is given then it is assumed to be 0.
Example: DIM whole#(7) gives whole#(0) to whole#(7).
When a string array is dimensioned, 40 places are reserved for each element of
the array, unless more or less are reserved by using OF. For example,
DIM a$(3,4) OF 5 would create a string array from a$(0,0) to a$(3,4)
with five places reserved for each element.
172
Filenames
Quotations are not needed around filenames when loading, saving, deleting or
running. The filename is considered to be the same irrespective of case. For
example: MYPROG is the same filename as myprog or MyPrOg.
Data
Quotations are not needed around strings in data statements except when the
string contains punctuation or is required to start or finish the DATA statement
with spaces.
The data pointer can be reset to the first item of data by the command
RESTORE.
RESTORE can be used with a label to restore the data pointer to the first
element of data that follows the label, eg RESTORE prices.
VAL returns the value that the string argument would have produced if it had
been a numerical expression.
:+ is the command to increment the variable on the left of the sign by the
amount on the right. For example, price_of_fish :+ change has the
same effect as the longer statement price_of_fish = price_of_fish +
change. It is particularly useful when long variable names are included.
:- is the instruction to decrement the variable on the left of the sign by the
amount on the right. For example, total :- discount has the same effect
as the longer statement total := total - discount.
173
:- may not be used with strings.
Syntax
Print separators (, or ' or ;) are required between all items in a PRINT list.
Example: PRINT TAB(9);"here"
or: PRINT this$,that#'other
If a prompt message is used in an INPUT statement then a colon is required
between the message and the variable. No question mark is given if a prompt
message is used.
174
23 Output to printers and
PRINT USING
The results of a program or its listing can be output to the screen and, if
required, to one of two printer connectors (known as ports).
Note that the Acorn Electron needs a Plus 1 expansion unit to interface to
printers. Reference should be made to the Acorn Electron Plus 1 User Guide for
details of using printers.
Characters may be sent to printers in two ways: serially, where the eight bits
forming the one-byte character are sent one after another down a single wire,
or in parallel, where the eight bits are sent simultaneously down eight wires.
The RS423 port, which is at the rear of the BBC Microcomputer, is used for
serial output. The parallel (Centronics) printer port is situated underneath the
BBC Microcomputer.
175
23.3 ZONE
ZONE is usually assigned a hexadecimal (base 16) value built up in three parts.
For example ZONE := &020309 sets the printing to take place according to
format 02 (which is with a fixed number of decimal places) 03 indicates three
decimal places and 09 indicates a zone width of nine characters. The & indicates
a base 16 number.
23.4 ~
We can find the current value of ZONE by instructing the computer to print its
value. First look for the symbol ~ which is the shifted ^ key (next to the = sign).
The ~ sign (often pronounced ‘twiddle’) is placed in front of a numeric variable
to convert the output from a decimal number to a string containing the
hexadecimal representation. When using mode 7 ~ is represented on the screen
by the division symbol, ÷.
Enter
PRINT ~ZONE
The value of number will be rounded to two decimal places before it is printed
with three places before the decimal point and two after it.
Strings may be printed as part of a PRINT USING command.
Example:
PRINT USING "#####.##":"Price is ";price
which will print the value of price with five places before the decimal point
and two after it.
The string must contain exactly one decimal point if the format is to be
correctly defined. The # symbol is the standard symbol for use inside the string,
though any other symbols would do.
176
Example:
PRINT USING "1234.123":length
would have four places before the decimal point and three after it. The length of
the string and the position of the decimal point are the only significant
features.
If a number is too large to fit into the format then it will be printed with the
extra places before the decimal point, but with the required number of decimal
places.
Example:
PRINT USING "#####.###":0.3'34.5'345.6'-345.6789
produces
0.300
34.500
345.600
-345.679
177
24 WHILE
Following the WHILE a condition is given. If the condition is satisfied (ie it has a
true result) then the statements inside the loop are carried out. The loop
continues until the condition becomes false.
The keyword DO may be omitted on entry. It will be inserted automatically.
The statements inside the loop will be indented by two places.
The END WHILE must contain a space.
24.2 Examples
10 WHILE NOT EOD
20 READ text$
30 PRINT text$
40 END WHILE
50 PRINT "That's all folks."
60 DATA What's up Doc ?
178
210 INPUT "Enter a number of pence ":amount
220 INPUT "Enter cost of an apple in pence ":cost
230 number := 0
240 WHILE amount >= cost DO
250 amount :- cost
260 number :+ 1
270 END WHILE
280 PRINT "You have enough for ";
290 PRINT ;number;" apples"
179
25 CASE
CASE is the introductory statement for a decision. It is best used when a whole
series of alternatives has to be considered and use of the IF command would be
untidy. The different CASEs are tested and then acted on.
25.1 OF
CASE must be followed by a variable or an expression which can be evaluated
and should be followed by the keyword OF. The value is then compared with a
set of alternatives. The format of the command is shown by this example. If OF
is omitted on entry then it will be inserted automatically.
10 MODE := 6
20 PRINT''"I am thinking of an integer 1-99"
30 PRINT''"Try to guess it"''
40 actual := RND( 99)
50 REPEAT
60 INPUT "Your guess > ":guess
70 PRINT TAB( 18);
80 difference := ABS(actual-guess)
90 CASE difference OF // OF need not be typed
100 WHEN 0 // a single value
110 PRINT "Exactly"
120 WHEN 1,2 // a list of alternative values
130 PRINT "White Hot"
140 WHEN < 5 // a condition
150 PRINT "Red Hot"
160 WHEN < 10
170 PRINT "Warm"
180 WHEN < 20
190 PRINT "Cool"
200 WHEN < 40
210 PRINT "Freezing"
220 OTHERWISE
230 PRINT "Get thermal underwear"
240 END CASE
250 UNTIL difference = 0
180
25.2 The CASE format
There must be a space between END and CASE.
The statements inside WHEN and OTHERWISE are indented by two places.
Following the WHEN there may be:
– A set of precise values, separated by commas.
Example: WHEN 0,1,2 or WHEN "A","B","C"
– A single expression. Example: WHEN 2*x-3
– A condition. Example: WHEN IN "YyNn"
or
– A combination of precise values and conditions.
Example:
WHEN 5, < -5
or
WHEN >5, <-5, 99
181
26 Short forms
Where only one instruction has to be carried out there are single line forms of
the FOR... NEXT... and the WHILE... loops.
No indenting occurs with any short form.
The single line version of the FOR loop may be given as a direct command and
the DO need not normally be included.
FOR j := 1 TO 100 array(j) := j
In a program statement the DO can also normally be left out on entry, its
position will be deduced and it will be inserted automatically.
100 FOR k := 20 TO 15 STEP -1 PRINT k
will list as
100 FOR k := 20 TO 15 STEP -1 DO PRINT k
The only exceptions are with the use of ? and ! where there could be possible
confusion. Example:
FOR i = 1 TO n DO ? node(i) = 0
The single line version of the WHILE... loop may be given as a direct
command and the DO need not be included because it will be inserted
automatically.
WHILE INKEY(-99) = 0 PRINT ".";
182
If there is an error in the command then the position of the DO can be seen
when the error message is reported.
In a program statement the DO can also be left out on entry, its position will be
deduced and it will be inserted automatically.
100 WHILE n <= 0 INPUT "Enter a positive number":n
will list as
100 WHILE n <= 0 DO INPUT "Enter a positive number":n
26.3 Exceptions
Short form FOR, IF or WHILE statements cannot be combined so that one is the
result of the other. For example the following command is Not allowed.
IF reply = 5 THEN FOR j := 1 TO 10 DO a(j) := j
^
183
27 Multiple assignments
and dimensions
27.1 Assignments
The assignments must be separated by semi-colons, for example:
100 red := 1; yellow := 2; white := 3 // assign colours
110 r$ := "Red"; a$ := "Amber"; g$ := "Green"
120 temp := this; this := that; that := temp // swap
A mixture of variable types may be assigned on the same line, for example:
130 a# := 1; b$ := "two"; c := 3; MODE := 4
27.2 Dimensions
When placing several dimension statements on a line they must be separated
by commas, but DIM need only be given once, for example:
100 DIM this$ OF 5, that$ OF 10, other$ OF 200
184
28 ELIF
ELIF is the statement which has the same effect as ELSE combined with IF. It
can only be used inside an IF structure and is designed to avoid further nested
IF conditions inside the IF loop.
185
80 leap := TRUE
90 ELIF year MOD 400 <> 0 THEN
100 //year/100 not by 400
110 leap := FALSE
120 ELSE
130 leap := TRUE
140 END IF
150 //
160 PRINT year;" is";
170 IF NOT leap THEN PRINT " not";
180 PRINT " a leap year"
Each ELIF condition is only reached if all previous conditions are not met.
186
29 Substrings
A substring is any part of a string from a null string up to the complete string
itself.
In Acornsoft COMAL operations may be performed using a substring,
including the replacement of that substring using an assignment.
Enter
town$ := "EDINBURGH"
and
PRINT town$(5:8)
The substring starts at the fifth letter from the left, which is B and continues
up to and including the eighth letter from the left.
Left substrings
Enter
PRINT town$(1:5)
187
The command can be simplified by leaving out the 1 if a leftmost substring is
being specified.
Enter
PRINT town$(:5)
Enter
FOR j := 1 TO 9 DO PRINT town$(:j)
Right substrings
Enter
PRINT town$(6:9)
Whilst this has produced the rightmost set of four letters, the ‘substring
specifiers’ are not so easy to find. There are two ways of easing the problem.
Enter
PRINT town$(6:)
If the right substring specifier is omitted then it is assumed that the substring
continues to the end of the string.
producing a string starting at the third element on the left and going up to the
third element from the right.
29.3 Precedence
Substring specifiers have a higher precedence than string addition. For
example:
188
PRINT "DUN" + "DEER"(1:3)
will produce DUNDEE.
Brackets have the highest precedence so
PRINT ("LIME" + "RICKMANSWORTH")(:8)
will print a$ on the right of a six-element string with spaces padding out any
gaps on the left.
An example for the more advanced programmer is
PRINT (label$ + " ")(:7);("000" + ~x)(-4:)
Leave a space between the string symbol and the bracket as you enter
PRINT town$ (5)
town$ (-5) is the single symbol which is the fifth from the right in town$.
Enter
town$ := "AMSTERDAM"
and
town$(:3) := "ROT"
and
PRINT town$
190
and
PRINT town$
Short measure
Now enter
town$ := "PORTSMOUTH"
and
PRINT LEN (town$)
Now enter
town$(:5) := "PLY"
and
PRINT town$
and
PRINT LEN (town$)
In this case five symbols are replaced with only three. The resulting string is
closed up to leave no gap and the length of town$ is accordingly decreased to
eight characters.
Excess
Now enter
town$(4:) := "NLIMON"
and
PRINT town$
and
PRINT LEN (town$)
191
Summary
In general, a substring assignment may not increase the length of a string, but
a string may decrease when there is a deficiency in the assignment.
Substring assignment is extremely versatile and may be used with string
expressions.
Example:
a$(:m) := (b$(x,y)(n:p) + c$(z)(-q:))(:n)
is a valid assignment.
192
30 FUNCtions
193
You will have to provide the missing procedures if you want to run this
program.
10 REPEAT
20 make_up_question
30 ask_question
40 take_in_answer
50 UNTIL more$ = "N" // until TRUE
60 //
100 FUNC more$
110 PRINT '"Another question ? Y/N > ";
120 REPEAT
130 reply$ := GET$
140 UNTIL reply$ IN "yYnN"
150 //
160 IF reply$ IN "yY" THEN
170 RETURN "Y" // loop again
180 ELSE
190 RETURN "N" // end the loop
200 END IF
210 END FUNC more$
FUNC more$ returns either Y or N (which brings the REPEAT loop to an end).
194
31 Parameters
195
Actual parameters may be variables
Change and add lines 10 and 20 to produce:
10 a := 6; b := 5
20 PRINT average(a,b) // actual parameters
100 //
110 FUNC average(x,y)
120 sum := x + y
130 RETURN sum / 2
140 END FUNC average
The formal parameters x and y are ‘local’ variables. When the function is
called, the variables x and y are created. When the function RETURNs a value,
those local variables are no longer available.
196
The variable sum, which was created inside the function, is available outside
the function.
Change line 30 to:
30 PRINT c
and add:
115 c := a
producing
10 a := 6; b := 5
20 PRINT average(a,b) // actual parameters
30 PRINT c
100 //
110 FUNC average(x,y) CLOSED
115 c := a
120 sum := x + y
130 RETURN sum / 2
140 END FUNC average
31.6 IMPORT
Main block variables can be used in a CLOSED function or procedure following
an IMPORT statement.
Enter
112 IMPORT a
197
List and run the program.
The value of c is not available at line 30. When the program was run, c was
stored in the local variable block because it was created in a CLOSED
environment. Any variables which are first assigned inside a CLOSED function
or procedure are not available outside it.
Change 30 to:
30 PRINT c#
The only main block variables that may be accessed from inside a CLOSED
function or procedure are those that are passed to it as parameters or
IMPORTed.
Change 30 to
30 print a
and 115 to
115 a :+ 1
producing
10 a := 6; b := 5
20 PRINT average(a,b)
30 PRINT a
100 //
110 FUNC average(x,y) CLOSED
112 IMPORT a
115 a :+ 1
120 sum := x + y
130 RETURN sum / 2
140 END FUNC average
198
Several variables or arrays can be brought in with a command such as:
IMPORT a,b$,c#,d(,)
Great care must be taken if the same variable is used as the formal parameter
in a function and also as the actual parameter outside the function. Although
the same symbol is used, it refers to distinct variables.
Run the program.
This result needs some explanation.
The initial main block value of x is 5.
The value, 5, is given to the local parameter of the function, which happens to
have the same name as one of the main block variables. The value is stored in
the local variable block and is subsequently increased to 15 and RETURNed.
The function has now been completed and so the original main block variables
are now made available.
When x is required in line 30, it is the original x and not the value used in the
function.
If you wish to avoid any confusion as to the value of a variable, then use
different names for the actual and formal parameters.
199
the keyword REF must be placed in front of the parameter. The variable is
passed by REFerence.
Enter new and the following
10 a := 3; b := 4
20 print a,b
30 swap(a,b)
40 print a,b
100 //
110 proc swap(ref x,ref y) closed
120 temp := x; x := y; y := temp
130 end proc swap
The only variables that may be used for the length of a string parameter are
resident integer variables and the system variables. The reason is that they are
global variables and will be available inside the closed dimensioning process.
200
Any other variable would not be found when the program was run.
Enter new and try this string parameter example.
100 REPEAT
110 INPUT "A word of up to 10 letters > ":word$
120 UNTIL LEN(word$) < 11
130 //
140 REPEAT
150 INPUT "Number of copies > ":n
160 UNTIL n>0
170 //
180 string(word$,n)
190 //
200 PROC string(name$ OF 10,number)
210 FOR go := 1 TO number
220 PRINT name$;
230 NEXT go
240 PRINT
250 END PROC string
If string variables are passed by REFerence then the length must not be
dimensioned in the PROC or FUNC declaration, for example: PROC
reverse(REF a$,REF b$). Any use of a REFerenced string variable will
apply to the value held in the main block of variables where its length has been
established so that OF is not needed (or allowed). Any attempt to use OF in this
situation will be rejected at line entry.
The same method is used to indicate the type of array in an IMPORT statement.
201
The following procedure could be used to carry out a scaling of an array.
2000 PROC scale(REF matrix(,),factor,dimension)
2010 FOR j := 1 TO dimension DO
2020 FOR k := 1 TO dimension DO
2030 matrix(j,k) := matrix(j,k) * factor
2040 NEXT k
2050 NEXT j
2060 END PROC scale
which would scale the two dimensional 6 by 6 array called mat by a factor of 3.
202
32 File handling
203
32.3 Filenames
Every file has a name, which on disc can be up to seven letters and on cassette
can be up to ten letters. The symbols should not include a space. On disc a
filename should not include punctuation. See the Disc Filing System User
Guide for details. The filename need not have quotation marks around it,
unless it also happens to be a keyword.
will prepare to write information into a file with the name Tapes starting at
the beginning of the file. If we are using a disc then a check is made as to
whether such a file already exists. If not, then a new filename will be created on
the disc directory and a new file with that name will be opened on the disc. Note
that any existing file of the same name will be overwritten unless it is locked, in
which case a message to that effect will be generated. Spaces are required after
the keywords OPEN and FILE.
204
A command such as:
OPEN FILE 2, Discs, READ
will prepare to read information from the file with the name Discs starting at
the beginning of the file.
A command such as:
OPEN FILE 3, Books, APPEND
can only be used with a disc system to add information to the file Books
continuing from the last item entered in the file.
If you want to place several items into the file at the same time then the items
are separated by commas, for example:
PRINT FILE 4:name$,address$,town$,code$
WRITE FILE can be used instead of PRINT FILE but only when storing the
values of variables and not constants and expressions, for example:
WRITE FILE 5:a$,b,c#
Enter this program which creates the file Randcol which contains 50 sets of
three numbers:
10 OPEN FILE 1, Randcol, WRITE
20 FOR set := 1 TO 50 DO
30 c := RND( 7)
40 x := RND( 1279)
50 y := RND( 1023)
60 PRINT c,x,y // screen display only
70 PRINT FILE 1:c,x,y // into file
80 NEXT set
90 CLOSE FILE 1 // MUST close file
and save it under the name COL_IN ready for later use.
205
If you are going to use this program with cassette, then prepare a blank section
of cassette tape in the recorder. When line 10 is reached a prompt to press
RECORD then RETURN will be given in just the same way as with saving a
program. There will be pauses between the blocks as they are saved. A further
prompt will appear when the program is complete.
Run the program.
Here is the matching program that will retrieve the information saved on file
and perform a multicolour drawing sequence.
10 MODE := 2 // or 5 if BBC Model A
20 MOVE 640,512 // Middle of screen
30 OPEN FILE 1, Randcol, READ
40 FOR set := 1 TO 50 DO
50 READ FILE 1:c,x,y
60 GCOL 0,c // Graphics colour
70 DRAW x,y
80 NEXT set
90 CLOSE FILE 1 // MUST close file
If you are using a cassette recorder, rewind the tape until you have wound back
to the beginning of the file Randcol.
Run the program (and press PLAY if you are using tape).
206
32.9 EOF
The function EOF (End Of File) is available. The function must be followed by
the number of a file. If there is no more information available in the file, then
EOF returns TRUE. If the end of the file has not been reached, then EOF returns
FALSE.
(Rewind the cassette, if appropriate) and run again. Save this program under
the name COL_OUT.
207
(If you receive a Can’t extend message then there is insufficient additional
space available at this point of the disc. Enter CLOSE to close the file.)
Load the program COL_OUT and run it to test the effect of appending. If
COL_IN has just generated a Can’t extend error then it is very likely that
Randcol will end with an incomplete set of data, so line 70 of COL_OUT will
generate an EOF error when that point is reached. Again, CLOSE should be
entered to close the file.
208
32.13 Opening random access files
The keywords OPEN FILE must be followed by a file number (from 0 to 5), a
comma, then the filename, a comma, the word RANDOM and the number or
logical expression for the record length. For example:
OPEN FILE 1, Invoice, RANDOM 40
Read or write
Once a random access file is opened, it may be used to read or write, unless the
keywords READ ONLY (with exactly one space) are added to the end of the
open file command in order to allow access to locked files. For example:
OPEN FILE 2, Payment, RANDOM 40 READ ONLY
No comma is needed (or accepted) between the record length and the
READ ONLY command.
PRINT FILE allows use of variables and expressions for the record number
and the items. WRITE FILE may be used if the values of variables, only, are
being placed in the file rather than expressions.
In this example we shall write some data into a random access file for use later.
Enter
10 DATA 12345678,Jones,ABC,111.11
20 DATA 13579135,Smith,DEF,222.22
30 DATA 24680246,Brown,GHI,333.33
40 DATA 56789012,Evans,ACV,123.45
50 //
60 OPEN FILE 1,Bills,RANDOM 40
70 record# := 0
80 REPEAT
90 READ refer#,name$,initial$,amount
100 record# :+ 1
110 PRINT FILE 1,record#:refer#,name$,initial$,amount
120 PRINT name$;" ";initial$;TAB( 20);refer#,amount
209
130 UNTIL EOD
140 CLOSE FILE 1 // MUST close file
Run the program.
210
Delete line 170 and add the following
220 PRINT '"How much extra > ";
230 INPUT extra
240 owing := amount + extra
250 PRINT '"New balance >";owing'
260 PRINT FILE 2,record#:refer#,name$,initial$,owing
270 CLOSE FILE 2
Run the program a few times seeing how the same account is being updated.
In practice, when carrying out such a procedure, careful records would need to
be kept of the original amount and the transactions that caused the change.
A file of transactions could be built up and a new file created showing the
updated amounts. This could be done with either a random access file or a
sequential file.
If the transactions are placed in the same sequence as the records then
continuous processing can be carried out with a sequential file. The original file
can be read through and records either copied directly into the new file or
amended and then written into the file.
will create a file called BILLS and ensure that space is reserved for records 0 up
to 100. Record 100 will contain the dummy information shown in line 20 above.
211
33 Other functions and
facilities
33.2 Sound
The BBC Microcomputer has extensive facilities to generate sounds using the
keywords SOUND and ENVELOPE. (The Acorn Electron has similar, but less
extensive facilities and reference should be made to the Acorn Electron User
Guide for details.) For simple effects the SOUND statement can be used on its
own, but greater control is given by using the ENVELOPE statement. At its
simplest SOUND is followed by four arguments, for example:
SOUND c,a,p,d
212
The channel number determines which of the four ‘voices’ is to be used.
Channel 0 produces only ‘noise’ whereas channels 1, 2 and 3 produce purer
notes.
The amplitude can be varied from 0 (off) to -15 (loud).
The pitch selects notes in intervals of a quarter of a semi-tone. Middle C is
produced when the pitch is set to 53, and the other notes are generated with the
values given below, spanning a full five octaves.
The duration determines the length of the note and is given in twentieths of a
second. Those used to reading music will find that ‘Moderato = 60’ will be
about right with the following settings for the duration.
5 10 20 40
Octave number
Note 1 2 3 4 5 6 7
B 1 49 97 145 193 241
A# 0 45 93 141 189 237
A 41 89 137 185 233
G# 37 85 133 181 229
G 33 81 129 177 225
F# 29 77 125 173 221
F 25 73 121 169 217
E 21 69 117 165 213
D# 17 65 113 161 209
D 13 61 109 157 205 253
C# 9 57 105 153 201 249
C 5 53 101 149 197 245
The SOUND facility may be extended in two main areas. Firstly, an ‘envelope’
can be selected to vary the amplitude and pitch of the note while it is playing;
213
secondly it is possible to ensure that notes are synchronised so that chords start
together.
These methods of controlling the sound are very powerful, but also somewhat
complex. A detailed description is given in Part III under SOUND and
ENVELOPE.
214
34 Low level aspects of
COMAL
PAGE specifies the first location that COMAL uses for storing the text of
programs. As its name suggests, it must be set to the start of a page of memory
in the machine (ie it must be an exact multiple of 256, &xx00). Its default value
depends on the precise configuration of the BBC Microcomputer but a few
sample values are:
Tape filing system &E00
Disc filing system &1900
Disc and Econet &1B00
6502 Second Processor &800
PAGE is a system variable – it can be both read and assigned. The main use of it
is to protect machine code, as described in the section below on using machine
code from COMAL.
SIZE is a read only function that returns the size of the program currently in
memory. The program actually occupies the locations PAGE to
PAGE + SIZE - 1 inclusive, which is a total of SIZE bytes. Note that the
start- and end-of-program bytes are always present in memory so that, after a
NEW, SIZE is always 2.
FREE is a system function that returns the number of bytes of free memory
available at the instant the keyword is interpreted. Note that the free memory
is defined as the memory between the top of the global variable space and the
bottom of the software stack (see memory map, below) and so this varies
throughout a calculation as intermediate results are stored on the stack. This
means that PRINT FREE + SIZE will give a different answer to
PRINT SIZE + FREE.
215
34.2 Using machine code from COMAL
The user can call machine code routines from COMAL by means of the USR
function. This takes a single argument, the address of the machine code to be
called, and returns a value taken from the 6502’s Accumulator, X register, Y
register and Processor status register in the order AXYP lo-byte to hi-byte. On
entry to the machine code, the accumulator, X and Y registers are set to the
LSBytes of a#, x# and y#, and the carry flag is set to the LSBit of c#. No
assembler is included in COMAL, but machine object code can be called from it.
The code can either be placed in ROM or one of the unused OS buffers (eg
RS423 buffers on a disc system), or it can be placed in user RAM and protected.
In the latter case it should be loaded into the bottom of memory and PAGE set
above the last required location. For example, if 4K of machine code is required
in a disc-based machine which initially has PAGE set at &1900 then a two-part
program can be run:
10 // Part One
20 //
30 PAGE :+ 4096
40 RUN "part2"
10 // Part Two
20 //
30 *load code 1900
40
50 rest of program
..
130 a:=USR &1900
216
34.3 Memory organisation and map
The overall memory map for Acornsoft COMAL is as follows:
Locations Contents
217
Useful locations in zero page are:
&00,01 HIMEM
&02,03 LOMEM
&04,05 AESTKP
&06,07 PAGE See memory map
&08,09 VARTOP for explanation
&0C,0D PRGTOP
&0E,0F LOCALL
&10,11 LOCALH
&12 CLOSED Flag – &FF if inside CLOSED PROC
or FUNC
&13,14 TXTPTR Two byte pointer to current text
&15 TXTOFF One byte offset to TXTPTR
&3F ERFLAG Most recent error number
(Though reset very frequently)
&68 PDBUGD Non-zero if program structure
correct. Corrupt with care only.
&6F LSTKP Loop stack pointer
HI and LO are the hi- and lo- bytes of the line number.
LL is the length of the line (including header).
IN is the indentation of the line in structures (2 spaces per structure).
The end of program is marked by HI being set to &FF. Tokens for keywords are
represented by bytes in the range &80 to &FE. Substring specifiers are
preceded by a 01 byte. Anyone writing ‘toolkit’ or similar utilities for the
language should bear in mind that, since syntax is checked at line entry, the
run-time interpreter has been written assuming that the line syntax is correct.
No trapping of incorrect syntax will occur at run time, and introducing any into
the program text is likely to cause fatal crashes. Any modifications to the
program text should also reset PDBUGD (see memory map) to indicate to the
interpreter that the structure needs to be re-checked before running or listing.
218
Implementers of utilities should note that subroutines exist inside the
interpreter to perform the following functions.
– List a single line of program.
– Decrunch a single byte.
– Relink the program and update size pointers.
– Search the program for a given character.
– Crunch a single line of program text.
– Check the syntax of a crunched program line.
Any other functions that the user implements in machine code should be
implemented in a similar style, ie if they are used more than once then the
individual users should call a procedure or function that sets up and performs
the USR call.
219
35 Merging COMAL
programs
Method 1
Step Command
1 load part2
2 renumber 20000,1
3 *spool temp
4 list
5 *spool
6 load part1
7 renumber 1,1
8 *exec temp
9 renumber
Method 2
Step Command
1 load part1
2 oscli("LOAD part2 "+ ~(PAGE+SIZE-2))
3 old
4 renumber
220
36 Converting programs to
COMAL
Enter
*WORD to change to VIEW
and
READ temp to load the file.
221
At this point the file temp may be edited to split multi-statement lines and to
produce the necessary COMAL structures by, for example, placing ELSE on its
own line and completing IF structures with an END IF. The powerful
REPLACE facility can be used to make changes using the Y or N keys.
Example:
REPLACE = := for assignment but not in a condition
REPLACE % # for integer variables
REPLACE :REM // for comments
Then
SAVE temp to save VIEW file
*COMAL to change language
*EXEC temp to load the file into memory as a program
When the program runs satisfactorily in COMAL you may save it by entering
SAVE comtest
222
37 Error messages
In this section all the error messages that can be generated by COMAL are
listed alphabetically, along with their error numbers (which may be of use to
low level programmers), and indications as to their cause.
All error messages generated while a program is being run or debugged will be
followed by a listing of the line where the error was detected.
Bad DIM 36
This message indicates that an attempt has been made to DIMension an array
or string with bounds that are not allowed.
Bad GOTO 29
This is generated if an attempt is made to jump out of or into a structure where
this is not permitted.
Bad program 21
If the section of memory containing the program has been corrupted and an
attempt is made to perform some operation on that program (eg OLD, RUN,
SAVE etc) then this error will be generated.
Bad type 23
This error is generated if an attempt is made to perform an operation which
requires one variable type with another (in CASE structures, when reading
data from files or with RETURN).
Bad value 32
This message indicates that an operation has been attempted for which the
numeric argument given was not in the valid range (eg SQR(-1)).
Can’t CONT 18
CONT will only work if program execution has been halted by a STOP command
or by the ESCAPE key being pressed, and if the program has not since been
corrupted. An attempt to CONT otherwise will give this error.
223
EOD 33
When attempting to READ from DATA statements, this error will be generated
if there is no more data available in the program.
EOF 41
This error will be generated if an attempt is made to READ or INPUT items
from a file after the end of the file has been reached.
Escape 17
This indicates that the ESCAPE key has been pressed.
File open 38
If an attempt is made to open a file which is already open then this error will be
generated.
Name mismatch 25
This error is generated by the prerun structure checker if the name or variable
at the end of a structure does not agree with that at the beginning. For
example, if the name following a PROC statement is not the same as that after
the corresponding END PROC.
No (keyword) 28
This error is generated by the prerun structure checker if an end of structure
statement is found without a corresponding start of structure.
No RETURN 39
If when a function is executed, the END FUNC is reached before a RETURN is
encountered then this error is generated.
No room 20
This message indicates that there is insufficient memory available for the
operation attempted.
Not allowed 26
This error will be generated when the interpreter encounters an instruction
which, although it may be syntactically correct, is not allowed at that point.
224
Not found 31
This error will be generated either if an attempt is made to access a file which is
not present on the current filing system, or if an operation is attempted on a
variable which has not been previously assigned or on a procedure or function
which has not been defined.
Not open 35
If an attempt is made to access a file which is not open then this error is
generated.
Record overflow 34
This error will be generated if an attempt is made to WRITE or PRINT more
information to a random access file than may be accommodated in the record
length assigned.
STOP 19
If a STOP command is encountered by the program interpreter then this
message is generated, and execution halts with a report of the line number.
Syntax error 22
If the line input syntax checker detects an error in the syntax of a line then this
message is generated. A type mismatch error is reported as a Syntax error.
Too complex 27
This error will be generated if the level of ‘nesting’ either of parentheses or
structures is too great for the interpreter to cope with.
225
Unclosed at 24
The prerun structure checker generates this error if it does not find an end of
structure statement where one is required. It is followed by either the line itself
or END, indicating where the omission was detected.
Variable exists 37
This error will be generated if an attempt is made to redimension an array or
string.
226
Part III – reference section
38 Guide to the reference
section
This reference section is designed for anyone who needs to check the details of
the use of some keyword or operator.
Description
The purpose and method of use of the keyword is described in normal computer
terminology. For certain of the mathematical functions this description will
have no significance unless users are familiar with the concepts involved.
Reference
A reference is given to the section in the earlier parts of the manual where the
keyword is first introduced, and sometimes to other keywords or chapters if
they are likely to be useful.
Syntax
A syntax diagram is given. This is the clearest way of displaying the many
alternative and syntactically correct constructions.
The diagram is interpreted from left to right, starting with the keyword or the
line from the left hand side (indicating that some other element must precede
the construction). The end of the construct is indicated either by an end of line
(eol), a carriage return (cr) or a line to the right indicating that some further
construction is required.
229
Any path which takes you towards the end of the diagram represents an
allowable syntax.
Arrowed paths indicate where the flow may take alternative routes or involve
repetition.
An arrowed path with a star indicates that if the element which is bypassed is
omitted, then it will be inserted automatically.
The syntax diagrams for the expressions, elements, lists, constants, variables
and other terms used in the individual diagrams are given at the beginning of
the keyword and operator summary.
Examples
One or more short examples are given to indicate possible uses of the keyword.
Both direct mode and program line examples are given where appropriate, and
reference is sometimes made to other keywords where further relevant
examples may be found. Note that for a number of operators brackets have
been used in the examples where they are not specifically required by the
syntax, but may be an aid to comprehension.
Associated keywords
A list is given of other keywords used in the same structures or with related
effects.
OPERATORS
Operators are described in essentially the same way as keywords, but in some
cases are grouped together under a single entry. See the first page of chapter 39
for the order and grouping of the operators.
Note that the term ‘binary operator’ is used to describe many operators. It is
the term used for describing an operator which takes two arguments, one
before it and the other after (eg 1 + 2, or a AND b).
The precedence with which operators act is given in section 40.6.
230
3. *FX/OSBYTE calls, a summary of some of the more useful Operating
System calls available with *FX or OSBYTE.
4. A list of all the keywords and operators along with their minimum forms
and tokens (where appropriate).
5. A list of the possible error messages along with their error numbers.
6. A precedence list showing the order in which operators will act in the
absence of brackets, as well as the valid ranges for arithmetic operations and
their accuracy.
231
39 Keyword and operator
summary
232
Subdefined elements for syntax diagrams
This section contains the definitions of all the subdefined elements used in the
syntax diagrams in terms of basic elements that may be entered from the
keyboard.
The subdefined elements are listed in alphabetical order for ease of reference.
The notation used in the syntax diagrams is as follows:
indicates that the element is a keyword which
must be followed by a non-alphanumeric
character.
indicates that the item is a subdefined element.
binary operator
MOD DIV
+ - * / ? ! ^
constant
+ +
- -
/ / character cr
233
file designator
filename
string expression
any character
except ‘,’ or ‘"’
head appendix
( identifier # ) CLOSED
REF identifier ( , )
, $
identifier
letter
letter underline
digit
logical expression
logical operator
numeric expression
>
<
>=
string expression <= string expression
<>
=
IN
234
logical operator
> = < = =
number
digit
number list
number , number
, number
numeric element
numeric variable
constant
VAL
ORD
system function
standard function
- numeric element
( logical expression )
& 0 —— F
235
numeric expression
binary operator
numeric element
numeric list
numeric variable
system variable
parameter list
string expression
( )
logical expression ,
236
simple statement
A syntactically correct version of any one of the following keywords or elements
will be a valid simple statement.
* character cr
eol
specifier
: logical expression
237
standard function
string constant
" "
string element
GET$
string variable
string constant
INKEY$
STR$
numeric element
CHR$
( string expression )
string expression
238
string variable
,
system function
system variable
variable list
numeric variable
string variable ,
239
:= :+ :- Assignment operators
Description
These operators are used for assigning values to numeric and system variables,
the contents of specific memory locations, and (:= :+ only) for assigning
strings to string variables.
:= is used to assign the expression following it to the variable preceding it. The
: is optional on entry and will be inserted automatically if omitted.
:+ is used with numeric variables to add the value of the expression following it
to the existing value of the variable, and assigning the result back to the
variable. With string variables it is used to add the string expression following
it to the end of the current content of the variable. It cannot be used with a
substring on the left of the assignment symbol.
:- is used only with numeric variables. It takes the value of the expression
following it and subtracts it from the current value of the variable. The result is
assigned back to the variable.
Note that, for example:
a :+ b AND c is equivalent to a := a + (b AND c) not
a := (a + b) AND c
Reference
Sections 3.2, 6.7, 6.8 and the precedence table (40.6).
Syntax
+
? -
? numeric element
eol
! numeric element
240
Examples (see also sections 6.7, 6.8)
a := number1 * number2
b# := a / d
c$ := message$
MODE :=6
d(i#) :+ i#
e$(2) :+ "end of string"
f :+ g ^ 2
g :- 17.5 * const1
h(6) :- d(4) * 6
?x :- 1
241
+ - * / ^ Arithmetic operators
Description
These are the standard arithmetic operators.
+ is either a binary operator which returns the result of adding the two
operands, or a unary operator indicating that the following argument is not to
have its sign changed (ie having no effect).
- is either a binary operator which returns the result of subtracting the second
operand from the first, or a unary operator indicating that the following
argument is to have its sign changed (ie multiplied by -1).
* is a binary operator which returns the result of multiplying the two operands
together.
/ is a binary operator which returns the result of dividing the first operand by
the second.
^ is a binary operator which returns the result of raising the first operand to
the power of the second. Note that, for example, 2^3^4 is (2^3)^4.
Known problem
In the first release of Acornsoft COMAL a slash (/) immediately followed by a
point (.) will be interpreted as the minimum form of the comment delimiter.
When dividing by constants between 0 and 1 it is, therefore, necessary either to
put a space or a zero before the decimal point.
Reference
Sections 2.4, 2.7 and the precedence table (40.6).
Syntax
See numeric element, constant, binary operator.
Examples
twenty_three := 3 + 4 * 5
twenty_five := 5 * 20 / 4
plus_one := -1 ^ 4
242
= < > IN Relational operators
Description
These are all binary operators used in specifying a logical relationship which
will return a result which is either true or FALSE. They may be used either
singly or in pairs as follows.
Note that ‘true’ means not FALSE (ie non-zero), whereas TRUE has the value
-1.
= will return TRUE if the two operands evaluate either to equal numbers or
identical strings, and FALSE otherwise (but beware of rounding errors).
< compares the values of numerical expressions or the ASCII codes of string
characters. With numerical expressions < returns TRUE if the first expression
evaluates to less than the second, and FALSE otherwise. With strings the two
operands are evaluated and compared letter by letter until the ASCII codes of
the two characters are different. If the code for the character from the first
string is lower than that from the second then < returns TRUE, otherwise it
returns FALSE. If the end of one string is reached before any differences are
found then the shorter string is taken to have the lower ASCII code.
<= compares the two operands and returns TRUE if the first is less than or
equal to the second, and FALSE otherwise. The result obtained will be the
opposite to that returned by >.
> compares the two operands in the same way as <, but returns TRUE if the
first expression is greater than the second, and FALSE otherwise. It will return
the opposite result to <=.
>= compares the two operands and returns TRUE if the first is greater than or
equal to the second. The result obtained will be opposite to that returned by <.
<> returns TRUE if the two operands are not equal numbers (or identical
strings), and FALSE otherwise. The result will be opposite to that returned by
=.
Reference
Sections 15.2, 15.3, 15.4 and the precedence table (40.6).
243
Syntax
See logical operator, logical expression, WHEN.
Examples (see also chapter 15, IN and all examples of conditional structures)
100 IF x < 0 THEN PRINT "Negative"
244
(:) Substring specifiers
Description
It is possible to perform operations on portions of a string or string expression
by using substring specifiers.
A substring is specified by giving the string identifier (which may be an
element of a string array or a string expression) followed by an expression of
the form (start:finish) where start and finish are the positions of
the first and last characters of the substring in the string. Either specifier may
be omitted and they will default to the beginning and end of the string
respectively.
With positive arguments the position is counted from the start of the string
(the first character being at position 1).
With negative arguments the position is counted from the end of the string
back towards the beginning (the last character being at position -1).
If the first position is after the second then the substring is returned as a null
string.
Assignments to substrings may either reduce the length of the substring or
leave it unchanged. It is not possible to extend a substring. If this is attempted
the string being assigned to the substring is truncated from the right until it is
the same length.
Note that single character substrings (eg a$(x:x)) may be specified with just
a single value in the brackets (eg a$ (x)), but a space is usually necessary
before the brackets to avoid confusion with string arrays.
Reference
Chapter 29.
Syntax
: logical expression
245
Examples (see also chapter 29)
PRINT a$(3:6)
200 b$ :+ a$(-6:-3)
600 d$ := a$(x:y)(2:3)
246
& ~ Hexadecimal operators
Description
These operators are employed when numbers are used in their hexadecimal
form.
& is used to immediately precede a numeric constant to indicate that it is
expressed in hexadecimal notation. The number is then used in exactly the
same way as any other.
~ is used to precede a numeric element to indicate that the number should be
expressed in hexadecimal form as a string.
Note that both these operators have the highest level of precedence.
Reference
Precedence table (40.6).
Syntax
See numeric element, string expression.
PRINT ~FREE
ffffffff$ := ~(-1)
zero$ := ~0.1
247
? ! Indirection operators
Description
Indirection operators are used to read and write directly at specific memory
locations.
? (pronounced query) operates on a single byte. ?x means ‘the contents of
memory location x’. It may be used to read the contents of that location
(PRINT ?x) or to set them (?x := y).
! (pronounced pling) operates on four successive bytes, that is the one indicated
by the argument and the three successive bytes. Four bytes is the amount of
memory used to store an integer variable, so pling may be used to manipulate
them. The least significant byte of the integer variable is stored in the byte
indicated by the argument, and the other bytes are stored in order of
significance up to the most significant byte in the highest number location.
Additionally both query and pling may be used as binary operators (with
variables or constants as the operands). For example, x?8 is taken as the
contents of (memory location x+8)’.
Reference
Precedence table (40.6).
Syntax
See numeric element, binary operator, assignment.
Examples
PRINT ~?&3000
35 !y := i#
248
// Remark //
Description
// is used to preface a comment in the program. All characters between the //
and the end of the line are ignored by the interpreter.
A remark may be placed on a separate program line or at the end of any valid
program line except after: DELETE LOAD RUN SAVE SELECT OUTPUT or
Operating System * commands.
Reference
Section 5.12.
Syntax
// any character cr
Example
100 x_coord:=640; y_coord:=512 // centre of screen
Associated keywords
None.
249
ABS Absolute value AB.
Description
This function returns the absolute value of its argument. For example, the
absolute value of -3.67 is 3.67, while the absolute value of 1.72 is 1.72.
Reference
Section 18.6.
Syntax
Examples
PRINT ABS (speed# - 30)
Associated keyword
SGN
250
ACS Arc-cosine AC.
Description
ACS returns the principal value of the angle whose cosine is the argument. The
value returned is in radians in the range 0 to PI. DEG may be used to convert
this value to degrees.
Reference
Section 33.1.
Syntax
Examples
PRINT ACS (0.5)
Associated keywords
ASN ATN SIN COS TAN RAD DEG
251
ADVAL Analogue to digital converter value AD.
Description
Note that on the Acorn Electron this function is not the same as the BBC
Microcomputer version described here. Reference should be made to the Acorn
Electron User Guide for details of ADVAL which performs exactly as in BASIC.
ADVAL performs three different functions depending on whether the argument
following it is positive, zero, or negative.
With arguments in the range 1 to 4 ADVAL returns the most recently converted
value of the analogue to digital channel with that number. The number
returned has 12 bit resolution, but is scaled to 16 bit (ie it has a range of 0 to
65520 in steps of 16).
ADVAL (0) can be used to indicate which ‘Fire’ buttons are pressed on the
games paddles, and also to indicate which was the last A-D channel to complete
conversion. The information can be determined as follows:
(ADVAL (0)) AND 3 will return 0 if no button is pressed, 1 if the left side
fire button is pressed, 2 if the right side fire button is pressed or 3 if both fire
buttons are pressed.
ADVAL (0) DIV 256 will return the number of the last A-D channel to
complete conversion, 0 indicating that no channel has yet done so.
With negative arguments ADVAL is used to determine how full any of the
internal buffers are.
ADVAL (-1) returns the number of characters in the keyboard buffer.
ADVAL (-2) returns the number of characters in the RS423 input buffer.
ADVAL (-3) returns the number of free spaces in the RS423 output buffer.
ADVAL (-4) returns the number of free spaces in the printer output buffer.
ADVAL (-5) returns the number of free spaces in the SOUND channel 0 buffer.
ADVAL (-6) returns the number of free spaces in the SOUND channel 1 buffer.
ADVAL (-7) returns the number of free spaces in the SOUND channel 2 buffer.
ADVAL (-8) returns the number of free spaces in the SOUND channel 3 buffer.
ADVAL (-9) returns the number of free spaces in the speech buffer.
Reference
Section 33.3 and the BBC Microcomputer System User Guide.
252
Syntax
100 *FX 2 1
105 // line 100 takes input from RS423
110 REPEAT
120 message$ :+ get$
130 UNTIL ADVAL (-2) = 0
140 *FX 2
145 // line 140 returns to keyboard input
Associated keyword
SOUND
253
AND AN.
Description
AND is a logical operator which performs a bitwise AND on the two operands, ie
it looks at each bit of the binary representations of the two operands in turn
and, for each of them, sets the corresponding result bit to 1 if both are set or to
0 otherwise (giving a 32-bit number).
Reference
Section 21.2.
Syntax
Examples
210 IF a<>FALSE AND b<>FALSE THEN
220 PRINT "Both a and b"
230 ELSE
240 PRINT "At least one is false"
250 END IF
Associated keywords
OR NOT EOR
254
APPEND AP.
Description
APPEND is a qualifying keyword used when OPENing a file which already exists
for sequential writing from the current end of that file.
Reference
Section 32.10 and OPEN.
Syntax
See OPEN.
Associated keyword
OPEN
255
ASN Arc-sine AS.
Description
ASN returns the principal value of the angle whose sine is the argument. The
value returned is in radians in the range -PI/2 to +PI/2. DEG may be used to
convert this value to degrees.
Reference
Section 33.1.
Syntax
Examples
PRINT ASN (-0.7)
Associated keywords
ACS ATN SIN COS TAN RAD DEG
256
ATN Arc-tangent AT.
Description
ATN returns the principal value of the angle whose tangent is the argument.
The value is in radians in the range -PI/2 to +PI/2. DEG may be used to
convert this value to degrees.
Reference
Section 33.1.
Syntax
Examples
PRINT ATN (-1)
Associated keywords
ACS ASN SIN COS TAN RAD DEG
257
AUTO Automatic line numbering A.
Description
This command facilitates the input of programs from the keyboard by
automatically generating the number of the next line each time RETURN is
pressed. AUTO cannot be used as part of a program line.
Two arguments may be used, the first specifying the starting line number and
the second the increment to be used. Both arguments default to 10 if omitted.
If a syntax error is found on a line that is entered then AUTO reprompts with
the same line number.
AUTO mode may be left either by pressing ESCAPE or by generating a line
number greater than 32767.
Reference
Section 5.11.
Syntax
Examples
AUTO 100,20
AUTO 100
AUTO ,20
Associated keyword
RENUMBER
258
CASE CA.
Description
This is the declaration statement for the multiple choice CASE structure.
The argument after the CASE statement is evaluated and used to select one of
the blocks of statements on subsequent lines which are declared using WHEN or
OTHERWISE. To find which block is to be executed the argument is tested with
each of the expressions in the WHEN clauses in turn until a true relation is
found. The block of statements between that WHEN clause and the next
structure element (WHEN, OTHERWISE or END CASE) is executed, after which
the program continues from the line following the END CASE statement.
If no match for the argument is found in the WHEN clauses then the block of
statements after the OTHERWISE clause is executed, if present. If no
OTHERWISE statement is found then no case has been satisfied and execution
proceeds from after the END CASE statement.
Note that only one of the blocks of statements is ever executed. This is the block
nearest to the top of the structure that satisfies the CASE selector.
An OF statement will be inserted at the end of the CASE line since this is
required by the language definition. It is always optional on entry.
Reference
Chapter 25.
Syntax
logical expression
CASE OF eol
string expression
259
Examples (see also chapter 25)
10 CASE MODE OF
20 WHEN 0,3
30 max_col := 79
40 WHEN 2,5
50 max_col := 19
60 OTHERWISE
70 max_col := 39
80 END CASE
Associated keywords
WHEN OTHERWISE END CASE
260
CHR$ Character string CH.
Description
CHR$ is a string function requiring a single numeric argument. It returns a
single character string which is the ASCII character corresponding to the least
significant byte of the numeric argument.
CHR$ is needed to construct strings containing characters which are not
available from the keyboard (for example, CHR$(10), a line feed). It should
be noted that it is often easier to use VDU for outputting control codes to the
screen or other output stream.
Reference
Section 7.6 and table of ASCII codes (40.1).
Syntax
Examples
message$ := CHR$ (7) + text$ // CHR$ (7) = "sound bell"
Associated keywords
ORD VDU VAL STR$
261
CLEAR CLE.
Description
CLEAR deletes all variables from the memory except for the system integer
variables a# to z# and the system functions and variables, eg TIME, MODE etc.
Reference
Section 4.6.
Syntax
CLEAR eol
Examples
CLEAR
100 CLEAR
Associated keyword
NEW
262
CLG Clear the graphics screen CLG
Description
CLG clears the current graphics area and leaves it in the current graphics
background colour. The graphics cursor is moved to the graphics origin (0,0)
(which is at the bottom left of the graphics screen unless it has been reset using
VDU 29).
Reference
Section 11.6 and GCOL.
Syntax
CLG eol
Examples
CLG
125 CLG
Associated keywords
CLS GCOL
263
CLOSE CLOSE
Description
CLOSE is used to close files. It may be followed by FILE and a single argument
giving the number of the file to be closed.
If used without any qualifiers CLOSE closes all open files on the current filing
system, including, for example, *SPOOL and *EXEC files, as well as COMAL
files.
Reference
Section 32.5.
Syntax
CLOSE
Associated keywords
FILE OPEN
264
CLOSED C.
Description
CLOSED is used to declare that all variables used in a PROCedure or FUNCtion
are local unless IMPORTed or passed by REFerence. It appears at the end of the
declaration line.
Reference
Section 31.5.
Syntax
See PROC and head appendix.
Examples
10 PROC zap(a$) CLOSED
Associated keywords
PROC FUNC IMPORT REF
265
CLS Clear the text screen CLS
Description
CLS clears the current text area and leaves it in the current text background
colour. In addition, the text cursor is moved to the ‘home’ position at the top left
of the text area.
Reference
Section 7.1 and COLOUR.
Syntax
CLS eol
Examples
CLS
135 CLS
Associated keywords
CLG COLOUR
266
COLOUR COL.
Description
COLOUR sets the logical colours which are to be used for the background and
foreground of the text area in MODEs 0-6.
The default actual colours for each of the logical colours in the different modes
are as follows.
MODE 0, 3, 4 or 6
Foreground Background Colour
0 128 black
1 129 white
MODE 1 or 5
Foreground Background Colour
0 128 black (normal background)
1 129 red
2 130 yellow
3 131 white (normal foreground)
MODE 2
Foreground Background Colour
0 128 black (normal background)
1 129 red
2 130 green
3 131 yellow
4 132 blue
5 133 magenta
6 134 cyan
7 135 white (normal foreground)
8 136 flashing black-white
9 137 flashing red-cyan
10 138 flashing green-magenta
11 139 flashing yellow-blue
12 140 flashing blue-yellow
13 141 flashing magenta-green
14 142 flashing cyan-red
15 143 flashing white-black
267
Note that the actual colours referred to by the logical colours may be changed
by using VDU 19. The actual colour numbers are the same as the default
logical colours in MODE 2.
Reference
Section 8.3 and chapter 11.
Syntax
Examples
COLOUR 3
110 COLOUR 5
Associated keywords
GCOL VDU 19
268
CONT Continue CO.
Description
CONT resumes execution of a program after it has been halted by either a STOP
command, a run-time error, or ESCAPE being pressed.
Execution recommences with the line on which the error occurred or, in the
case of a STOP command, from the following line.
If the program is altered, or an error is generated while in direct mode, then
continued execution may not be possible, in which case a Can't CONT error is
generated.
Note that it is not possible to CONTinue if a procedure or function has been
called while in direct mode.
Reference
Section 12.2.
Syntax
CONT eol
Example
CONT
269
COS Cosine COS
Description
COS returns the cosine of the argument, which is taken to be in radian
measure. RAD may be used to convert degrees to radians.
Reference
Section 33.1.
Syntax
Examples
PRINT COS (RAD (30))
Associated keywords
ACS ASN ATN SIN TAN DEG RAD
270
COUNT COU.
Description
COUNT is a system function which returns the number of characters sent using
a PRINT command since the last carriage return. Note that VDU commands do
not alter the value of COUNT.
Reference
Section 18.4.
Syntax
COUNT
Examples
PRINT COUNT
Associated keywords
POS TAB SELECT OUTPUT
271
DATA DA.
Description
DATA is used at the beginning of a program line to indicate that the
information which follows is to be assigned using a READ statement. Data
items are separated by commas.
Leading or trailing spaces on numeric data items are ignored.
String data items may or may not be enclosed in quotes, but they are only
necessary if the string itself includes commas. However, it is advisable to put
the string in quotes if the string itself contains quotation marks, in which case
double quotes ("") should be used (see example). If quotes are to be used round
data items then there should be no spaces between the preceding comma and
the opening quotation mark.
If quotes are not used round string items then all the characters between the
preceding and following commas are taken to be part of the string, including
leading and trailing spaces.
Note that it is only possible to read ‘hexadecimal’ data items such as &FFE0 as
strings.
Reference
Chapter 17.
Syntax
constant
any character
except ‘,’
Examples
265 DATA 1,4,9,16,25,36,49
Associated keywords
READ RESTORE
272
DEBUG D.
Description
DEBUG reports structural errors in a program, such as unclosed structures,
crossed loops and non-existent labels. It is performed automatically before
programs are RUN.
Note that DEBUG clears all user variables.
Reference
Section 7.3.
Syntax
DEBUG eol
Example
DEBUG
Associated keywords
LIST RUN
273
DEG Radians to degrees DEG
Description
DEG converts angles from radian measure to degrees. 1 radian is (180/PI
degrees (ie about 57.3 degrees).
Reference
Section 33.1.
Syntax
Examples
PRINT DEG 1
Associated keyword
RAD
274
DEL Delete program lines DEL
Description
DEL deletes the program lines specified by one or two arguments. As a safety
measure, two parameters are necessary to delete more than one line. No action
results if the second parameter is lower than the first, but otherwise all the
program lines between the two arguments are deleted (inclusively).
DEL followed by a single parameter will delete one program line. Typing the
line number followed by RETURN will have the same result.
Reference
Section 5.10.
Syntax
Examples
DEL 10,30
DEL 25
Associated keywords
LIST OLD NEW
275
DELETE Delete file DEL.
Description
This command deletes the specified file on the current filing system.
It will not work on cassette files, but will not generate an error if this is
attempted. Trying to delete a file which does not exist will also not give an error
message.
Note that attempts to use keywords in specifying filenames without using
quotation marks will not produce the normal results since they are not
recognised as keywords (eg DELETE STR$2 will delete the file str$2).
Note also that if a string variable name is used in specifying the filename then
it must be in lower case.
Reference
Section 14.7.
Syntax
DELETE filename cr
Examples
DELETE myprog
10 DELETE fname$
Associated keywords
SAVE LOAD RUN
276
DIM Dimension DI.
Description
Both numeric and string arrays must be declared before the first assignment to
them is made. Additionally, the maximum length of strings may be declared
using OF if the default value of 40 characters is not suitable. DIM performs
these operations.
For arrays, upper and lower bounds may be placed on each dimension. The
lower bound defaults to 0, but the upper bound must always be specified. If the
lower bound is declared to be greater than the upper bound then a run-time
Bad DIM error results.
Reference
Sections 4.5, 19.2.
Syntax
Examples
DIM name$ OF 12
25 DIM image(-3:4,3:8,-3:-2)
35 DIM output$(1:5) OF 20
45 DIM a$ OF 5, b$ OF 10
55 DIM c$(a,b#) OF c
65 DIM d#(6,p)
Associated keyword
OF
277
DIV Integer division DIV
Description
DIV is a binary operator which truncates the two operands to integers before
dividing the first by the second. The result is also truncated to an integer.
Reference
Section 18.8.
Syntax
Examples
PRINT 17 DIV 3
Associated keyword
MOD
278
DO DO
Description
DO is used in the FOR and WHILE structures, it is optional on entry except in a
few cases, such as:
FOR loc = &7C00 TO &8000 DO ?loc = 0
Reference
FOR and WHILE.
Syntax
See FOR and WHILE.
55 FOR i := 1 TO 10 DO PRINT i
Associated keywords
FOR WHILE
279
DRAW DR.
Description
This facility enables lines to be drawn on the screen in any of MODEs 0, 1, 2, 4 or
5. The line is drawn in the current graphics foreground colour from the current
position of the graphics cursor to the point specified by the x- and y-coordinates
following the DRAW statement.
The x- and y-coordinates are relative to the current graphics origin (0,0). The
default origin is at the bottom left of the graphics area, but this may be changed
by using VDU 29. The screen is 1280 units wide (x-axis) and 1024 units high
(y-axis) irrespective of which graphics mode is in use.
DRAW x,y is identical in effect to PLOT 5,x,y.
Reference
Section 11.3 and PLOT.
Syntax
Associated keywords
MODE PLOT MOVE GCOL CLG VDU
280
EDIT List program without indentation E.
Description
EDIT lists the specified range of program lines without any indentation of
structures. The parameters default to the start and end of the program. The
entire program is listed if no parameters are given. Unlike LIST, EDIT
displays EXEC before all procedure calls where none are already present.
Reference
Section 13.5.
Syntax
Examples
EDIT
EDIT 100,200
EDIT ,150
EDIT 300,
Associated keyword
LIST
281
ELIF Else if EL.
Description
ELIF is a statement that may be used in the long form of the IF structure. It
declares another condition to be tested if the condition after the initial IF or
any previous ELIF statement fails.
Reference
Chapter 28 and IF.
Syntax
Associated keywords
IF THEN ELSE END IF
282
ELSE ELS.
Description
This statement is used in the long form of the IF structure. The block of
program lines following it is executed if none of the IF or ELIF conditions
earlier in the structure is satisfied.
Reference
Section 15.6 and IF.
Syntax
ELSE eol
Associated keywords
IF THEN ELIF END IF
283
END EN.
Description
END indicates that the end of the program has been reached. It is optional and
may be used as many times as required in a program, although it is not good
practice to have more than one.
In Acornsoft COMAL the end of structure statements (END IF, END PROC
etc) are each stored as two separate keywords and, therefore, require a space
after END.
Note that END is not allowed inside structures, where STOP must be used to
halt execution.
Reference
Section 5.13.
Syntax
END eol
Example
1000 END
Associated keyword
STOP
284
END CASE END CA.
Description
This indicates the end of a CASE structure. Note that the space between END
and CASE is obligatory.
Reference
Chapter 25 and CASE.
Syntax
Associated keywords
CASE WHEN OTHERWISE
285
END FUNC END FU.
Description
This indicates the end of a FUNCtion declaration. Note that the space between
END and FUNC is obligatory.
Reference
Chapter 30 and FUNC.
Syntax
#
Associated keywords
FUNC CLOSED REF IMPORT RETURN
286
END IF END I.
Description
This indicates the end of a long form IF structure. Note that the space between
END and IF is obligatory.
Reference
Section 15.5.
Syntax
END IF eol
Associated keywords
IF THEN ELSE ELIF
287
END PROC END PRO.
Description
This indicates the end of a PROCedure declaration. Note that the space between
END and PROC is obligatory.
Reference
Section 13.1 and PROC.
Syntax
Associated keywords
PROC CLOSED REF IMPORT
288
END WHILE END W.
Description
This indicates the end of a long form WHILE structure. Note that the space
between END and WHILE is obligatory.
Reference
Chapter 24 and WHILE.
Syntax
Associated keywords
WHILE DO
289
ENVELOPE ENV.
Description
Note that on the Acorn Electron this function is not the same as the BBC
Microcomputer version described below. Reference should be made to the
Acorn Electron User Guide for details of ENVELOPE which performs exactly as
in BASIC.
ENVELOPE is used with SOUND to provide greater control over the sounds
produced. It is a very powerful, but somewhat complex command, and reference
should be made to the BBC Microcomputer System User Guide for a more
detailed description than the parameter list given below.
ENVELOPE is followed by 14 parameters as follows:
ENVELOPE N,T,PI1,PI2,PI3,PN1,PN2,PN3,AA,AD,AS,AR,ALA,ALD
290
Reference
Section 33.2 and the BBC Microcomputer System User Guide.
Syntax
Associated keywords
SOUND ADVAL
291
EOD End of data EOD
Description
EOD is a system function which indicates whether the end of the available data
statements has been reached. While there is still data in the program that can
be read it returns FALSE (0). After reading the last available data item it
returns TRUE (-1).
Reference
Section 17.3.
Syntax
EOD
Examples
10 a:=0
20 WHILE NOT EOD
30 READ array(a)
40 a:+1
50 END WHILE
Associated keywords
DATA READ
292
EOF End of file EO.
Description
EOF is a function which shows whether the end of a file has been reached. It is
followed by a single argument indicating the number of the file which is to be
checked. EOF returns TRUE (-1) if no more data can be successfully read from
the file, and FALSE (0) otherwise. If no file is open with the specified number
then a Not open error is generated.
Reference
Section 32.9.
Syntax
Examples
80 OPEN FILE 1,"Test",READ
90 i:=0
100 REPEAT
110 READ FILE 1:a(i)
120 i:+1
130 UNTIL EOF 1
140 CLOSE FILE 1
Associated keywords
OPEN FILE READ RANDOM READ ONLY CLOSE
293
EOR Exclusive-OR operator EOR
Description
EOR is a logical operator which performs a bitwise exclusive-OR on the two
operands, ie it looks at each bit of the binary representations of the two
operands in turn and, for each of them, sets the corresponding result bit to 1 if
one or the other is set, but to 0 if they both have the same value (giving a 32-bit
number).
Reference
Section 21.3.
Syntax
Examples
310 IF a <> FALSE EOR b <> FALSE THEN
320 PRINT "Either a or b, but not both"
330 ELSE
340 PRINT "Either both a and b, or neither"
350 END IF
Associated keywords
AND OR NOT
294
EXEC Execute procedure EX.
Description
EXEC is used to call procedures. It is always optional on entry, and if it is
omitted then an ‘invisible’ EXEC is inserted. EDIT shows invisible EXECs, but
LIST does not.
Procedures may be called from direct mode, but only if the program has been
LISTed, EDITed, DEBUGged or RUN.
Reference
Section 13.6.
Syntax
Example
EXEC myproc
Associated keyword
PROC
295
EXP Exponent EXP
Description
EXP is a mathematical function which returns e (2.718281828) raised to the
power of the argument.
Reference
Section 33.1.
Syntax
Examples
PRINT EXP (3.5)
Associated keywords
LN LOG
296
EXT Extent EXT
Description
EXT is a function which returns the length in bytes of the file with the file
number specified by the argument. If there is no file open with that number
then a Not open error is generated.
Reference
Section 32.17.
Syntax
Examples
PRINT EXT 2
35 size_of_file := EXT 1
Associated keywords
OPEN FILE CLOSE
297
FALSE FA.
Description
FALSE is a system function which returns the value 0.
Reference
Section 16.3.
Syntax
FALSE
Example
65 UNTIL FALSE // infinite loop
Associated keyword
TRUE
298
FILE FI.
Description
FILE is used as a qualifying keyword to indicate that the expression which
follows is the file number to which the qualified keyword is to be applied. When
a file is OPENed the file is assigned to a number given by the expression
following the FILE statement. All operations on that file until it is next
CLOSEd refer to it by this number. See the file handling commands (OPEN,
CLOSE, WRITE, READ) for further details of the use of FILE.
Reference
Chapter 32.
Syntax
See OPEN and CLOSE.
Examples
Refer to the keyword which is being qualified.
Associated keywords
OPEN CLOSE WRITE READ PRINT INPUT
299
FOR F.
Description
FOR is used to initialise an unconditional loop structure.
There are two forms: the short form (single line), and the long form (multi-line).
In both cases FOR is followed by a loop variable assignment which has lower
and upper bounds separated by a TO statement. Additionally there may then
be a STEP statement to indicate the loop variable increment. The default value
is 1.
In the short form this is followed by the simple statement to be repeated.
If more than one command is to be executed in the loop then each must be
entered on the lines following the FOR statement, and, finally, a NEXT
statement entered to indicate the end of the loop.
In both cases a DO statement is automatically inserted if not present at entry.
Note that if the values taken by a loop variable are always going to be whole
numbers then it will make execution much faster if an integer variable is used.
Note also that if the start and end values of the loop variable and the increment
are incompatible (eg FOR i := 1 TO 10 STEP -1) then the loop is not
performed at all and execution moves to the line after the end of the FOR
structure.
It is advisable, if possible, to use integral step sizes and divide down the loop
variable if required, since inaccuracies may result with fractional step sizes.
Reference
Chapter 6.
Syntax
300
Examples
Short form:
FOR i# := 1 TO 10 DO PRINT i#
Long form:
10 FOR j := 2 TO 10 DO
20 PRINT j
30 myproc(j2)
40 NEXT j
Associated keywords
TO STEP DO NEXT
301
FREE Free memory FR.
Description
FREE is a system function which returns the number of bytes of free memory
available.
Reference
Section 34.1 and memory map in section 34.3.
Syntax
FREE
Examples
PRINT FREE
Associated keywords
SIZE PAGE
302
FUNC Function FU.
Description
FUNC is the first word used on a function declaration line. It is followed by the
name which identifies the function, the formal parameter list (if any) and,
possibly, CLOSED to denote a closed (local) function. The body of the function is
between this line and the next END FUNC statement, and must contain a
RETURN statement to indicate the value to be returned by the function.
FUNC can only appear at the start of a program line and not inside any other
structures.
Reference
Chapter 30.
Syntax
Associated keywords
CLOSED REF IMPORT END FUNC RETURN PROC
303
GCOL Graphics colour G.
Description
GCOL sets the logical colours to be used for the background and foreground of
the graphics area in all subsequent operations.
Two arguments follow the GCOL command. The first specifies the method of
displaying the colour on the screen, as follows:
0 plot the specified colour
1 OR the specified colour with that already there
2 AND the specified colour with that already there
3 EOR the specified colour with that already there
4 invert the colour already there
The second argument specifies the logical colour to be used. Numbers less than
128 define the foreground colour, while those greater than 127 define the
background colour. Note that although the second argument in GCOL 4,x has
no effect on the result a number must be entered.
Reference
Section 11.5 and COLOUR.
Syntax
95 GCOL 0,4
Associated keywords
COLOUR CLG MODE PLOT DRAW MOVE VDU
304
GET GET
Description
GET is used to make execution wait until a key is pressed. It returns the ASCII
code of the key pressed, but the character typed is not printed on the screen.
See section 40.1 for details of ASCII codes.
Note that GET reads the buffer corresponding to the current input stream.
Thus, the key may be pressed prior to the GET being executed provided that
some other command does not remove it from the buffer.
If the input stream is changed (*FX 2 command or *EXEC) then GET may be
used to take characters from sources other than the keyboard.
Reference
Section 9.5.
Syntax
GET
Examples
PRINT CHR$ GET
Associated keywords
GET$ INKEY INKEY$ INPUT
305
GET$ GE.
Description
GET$ makes execution wait until a key is pressed. It returns a string
containing the key pressed, but the character is not displayed on the screen.
Note that GET$ reads the buffer corresponding to the current input stream.
Thus, the key may be pressed prior to the GET$ being executed provided that
some other command does not remove it from the buffer.
If the input stream is changed (*FX 2 command or *EXEC) then GET$ may be
used to take characters from sources other than the keyboard.
Reference
Section 9.6.
Syntax
GET$
Examples
q1$ := GET$
25 q2$ := GET$
30 PRINT q2$
Associated keywords
GET INKEY INKEY$ INPUT
306
GOTO GO.
Description
GOTO causes program execution to jump unconditionally to a named label (not
a line number). See RESTORE for details of label definition. Note that prolific
use of GOTOs tends to destroy the structure of a program and is not
recommended.
Syntax
Examples
10 i := 0
20 again: //label
30 i:+1
40 PRINT "This is appalling style"
50 GOTO again
Associated keywords
None.
307
IF I.
Description
The IF structure is used to make the execution of some program lines
dependent on whether some logical expression is true. It can be used in two
forms, the short form and the long form.
The short form is a single line structure allowing only a simple statement (or a
multiple assignment) to be executed if the condition is true.
The long form allows the block of lines following the IF statement to be
dependent on it, and also allows the ELIF and ELSE commands to be used.
These introduce other blocks of statements to be performed if the original
condition in the IF statement is not met. The long form IF is terminated by an
END IF statement.
Note that THEN is optional on entry, except in a few cases, such as:
IF x = 10 THEN ? y = x
Reference
Sections 15.3, 15.5.
Syntax
30 IF x = 1 THEN
40 MOVE x,y
50 ELSE
60 DRAW x,y
70 END IF
Associated keywords
END IF ELSE ELIF THEN
308
IMPORT IM.
Description
IMPORT is used to declare which global variables are accessible from inside a
closed procedure or function. This is equivalent to passing these variables by
reference to the procedure or function, in that assignments to them inside the
structure will change their values globally.
Note that IMPORT may be used anywhere within a structure, provided that a
variable with the same name as that to be IMPORTed does not already exist
within the structure.
Reference
Section 31.6.
Syntax
Associated keywords
PROC FUNC CLOSED REF
309
IN IN
Description
IN is a binary operator which returns the position of the first string in the
second.
If no match is found then IN returns 0. If the first argument is a null string
then it returns 1.
Reference
Section 4.3.
Syntax
Examples
PRINT "345" IN "12345"
145 DIM a$ OF 10
150 REPEAT
155 PRINT "Answer Yes or No >>"
160 a$ := GET$
165 UNTIL a$ IN "YNyn"
Associated keywords
None.
310
INKEY INKEY
Description
INKEY has two forms depending on whether the argument following it is
positive or negative.
With a positive argument INKEY is used to halt program execution for up to a
specified time whilst waiting for a key to be pressed. If a key is pressed within
the specified time then INKEY immediately returns the ASCII code of the key
pressed (see section 40.1 for ASCII codes). Otherwise it returns -1 and
program execution continues. The time for which INKEY waits is specified by
the argument, in hundredths of a second (in the range 0 to 32767). INKEY
reads the keyboard buffer so the key may be pressed at any time before the
statement occurs, so long as it is not removed from the buffer by some other
command in the mean time.
With a negative argument INKEY looks at the keyboard (not the buffer) to see
whether a particular key is pressed at the instant the command is invoked. The
argument determines which key is to be tested according to the table at the end
of this keyword. Note that the codes for the Acorn Electron are different in a
few cases, so reference should be made to the Acorn Electron User Guide where
appropriate.
Known problem
In the first release of Acornsoft COMAL for the BBC Microcomputer (but not
for the Acorn Electron), INKEY needs arguments in the range -255 to 255 to
give the expected result. In order to achieve the correct results with values
outside this range, for example, to perform INKEY &PQRS (where P, Q, R and
S are any hexadecimal digits), INKEY &PQ0000RS should be used. See
chapter 42 for an example function to perform the required manipulation.
Reference
Sections 20.1, 20.4.
Syntax
311
Examples
PRINT INKEY (200)
75 x := INKEY (100)
Associated keywords
INKEY$ GET GET$
312
Key Number Key Number
f0 −33 1 −49
f1 −114 2 −50
f2 −115 3 −18
f3 −116 4 −19
f4 −21 5 −20
f5 −117 6 −53
f6 −118 7 −37
f7 −23 8 −22
f8 −119 9 −39
f9 −120 0 −40
A −66 - −24
B −101 ^ −25
C −83 \ −121
D −51 @ −72
E −35 [ −57
F −68 __ −41
G −84 ; −88
H −85 : −73
I −38 ] −89
J −70 , −103
K −71 . −104
L −87 / −105
M −102 ESCAPE −113
N −86 TAB −97
O −55 CAPS LOCK −65
P −56 CTRL −2
Q −17 SHIFT LOCK −81
R −52 SHIFT −1
S −82 SPACE BAR −99
T −36 DELETE −90
U −54 COPY −106
V −100 RETURN −74
W −34 h −58
X −67 i −42
Y −69 f −26
Z −98 g −122
313
INKEY$ INK.
Description
INKEY$ returns a string containing the key pressed within the time
specified by the argument. It scans the keyboard buffer rather than the
keyboard itself.
If no key is pressed within the specified time limit then a null string is
returned. The argument specifies the time limit in hundredths of a second (in
the range 0 to 32767).
Known problem
In the first release of Acornsoft COMAL for the BBC Microcomputer (but not
for the Acorn Electron), INKEY$ needs arguments in the range 0 to 255 to give
the expected result. In order to achieve the correct results with values outside
this range, for example, to perform INKEY$ &PQRS (where P, Q, R and S are
any hexadecimal digits), INKEY$ &PQ0000RS should be used. See chapter 42
for an example function to perform the required manipulation.
Reference
Section 20.2.
Syntax
Examples
PRINT INKEY$ (100)
Associated keywords
INKEY GET GET$
314
INPUT IN.
Description
This statement takes data from the current input stream and assigns it to a
variable. If there is no message then a question mark prompt is generated. A
prompt message may immediately follow the INPUT command, in which case
no additional prompt is supplied.
If insufficient data is supplied then a ?? prompt is generated for more. If string
data is supplied when numeric is required then Bad value is printed and ??
prompts for re-entry.
If the string supplied is longer than the maximum length possible for the
string variable to which it is to be assigned, then a String too long error
is reported and execution stops. If any other error occurs then input starts
again, including the prompt, and from the first item in the list.
INPUT FILE may be used to input data from files and is identical to
READ FILE.
Known problem
In the first release of Acornsoft COMAL any string beginning with a valid
numeric constant (including .) will be accepted when a numeric input is
required and taken as having the value of that constant (as in BBC BASIC).
No error is generated.
Reference
Section 9.1.
Syntax
file designator
INPUT variable list eol
string constant :
Associated keywords
GET GET$
315
INT Integer part INT
Description
INT returns the largest whole number equal to or less than the argument.
For example, INT (2.5) is 2, but INT (-2.5) is -3.
Reference
Section 3.11.
Syntax
Examples
PRINT INT (-15.36)
Associated keywords
None.
316
LEN Length of string LE.
Description
LEN returns the number of characters in the string argument which follows it.
Reference
Section 4.2.
Syntax
Examples
PRINT LEN (x$)
Associated keywords
None.
317
LIST .
Description
This command lists the program from the line given by the first argument to
that given by the second. The two arguments default to the beginning and end
of the program. If only one argument is given then just that line is listed.
Line numbers are ranged right in a five character field and are followed by a
space. Two extra spaces are inserted after the start of each structure and
removed before its last line. Keywords are given in upper case and variables in
lower case, although both may be entered in either case.
CTRL N and CTRL O will switch ‘paged mode’ listing on and off respectively,
with SHIFT to move to the next page.
Pressing SHIFT and CTRL together will cause scrolling to stop until one of
them is released.
Reference
Section 5.4.
Syntax
Examples
LIST
LIST 100,200
LIST ,50
LIST 300,
LIST 75
Associated keywords
EDIT NEW OLD
318
LN Natural logarithm LN
Description
LN returns the logarithm to the base e (the Natural or Napierian logarithm)
of the argument.
Reference
Section 33.1.
Syntax
LN numeric element
Examples
PRINT LN (0.5)
Associated keywords
EXP LOG
319
LOAD LO.
Description
LOAD loads a program from the current filing system. Quotes round the
filename are optional (except where a keyword is used as a filename). Any
string expression may be used as the argument. The maximum length of the
filename is dependent on the filing system in use.
Note that if a string variable is used in specifying the filename then it must be
in lower case.
Reference
Sections 14.4 and 14.6.
Syntax
LOAD filename cr
Examples
LOAD "myprog"
LOAD myprog
a$ := "my"
LOAD a$ + "prog"
Associated keywords
SAVE RUN
320
LOG Common logarithm LOG
Description
LOG returns the common logarithm (ie to the base 10) of the argument. Anti-
logarithms are calculated using:
a_log := 10^logarithm
Reference
Section 33.1.
Syntax
Examples
PRINT LOG (2)
Associated keywords
LN EXP
321
MOD Modulus MOD
Description
MOD is a binary operator which returns the signed remainder obtained by
dividing the first argument by the second. Both arguments are first truncated
to integers, as is the result.
Note that, for example, -14 MOD 5 is -4.
Reference
Section 18.9.
Syntax
Examples
PRINT (TIME/100) MOD 60
Associated keyword
DIV
322
MODE MOD.
Description
MODE is a system variable containing the current screen mode which may be
read as well as assigned. Note, however, that MODE may only be altered by
using an assignment statement and not, for example, by using INPUT.
It is not possible to change mode inside a procedure or function unless using a
6502 Second Processor. Changing modes clears the screen. Attempting to
change to a mode for which there is insufficient memory available will result in
a No room error.
Reference
Section 8.1.
Syntax
MODE
323
Examples
MODE := 6
PRINT MODE
115 MODE :+ 2
Associated keywords
CLS CLG FREE
324
MOVE M.
Description
MOVE moves the graphics cursor to the position specified by the two arguments.
These will be the x- and y-coordinates relative to the current graphics origin.
MOVE is identical in effect to PLOT 4.
Reference
Section 11.4.
Syntax
Associated keywords
DRAW PLOT VDU CLG
325
NEW NEW
Description
NEW clears the program and variables (except the system integer variables a#
to z#) from the memory and resets the relevant system functions (SIZE and
FREE).
The program (but not the variables) may be retrieved by typing OLD provided
that it has not been corrupted.
Note that NEW will not close any files which are open on the current filing
system. This is to enable the user to employ *EXEC files which contain the
keywords NEW or *COMAL. Correct use of OPEN and CLOSE statements will
ensure that no problems result from this feature.
Reference
Section 5.1.
Syntax
NEW eol
Example
NEW
Associated keyword
OLD
326
NEXT N.
Description
NEXT declares the end of a FOR loop. The loop variable is optional on entry and
is automatically inserted if omitted. NEXT is not used in short form loops.
Reference
Section 6.1 and FOR.
Syntax
Associated keywords
FOR STEP DO
327
NOT NO.
Description
NOT performs a logical bitwise inversion on its argument. It is often used to
reverse the result of some test in a conditional structure, but may also be used
for numerical calculations.
Reference
Section 21.6.
Syntax
Examples
minus_six := NOT 5
Associated keywords
AND OR EOR
328
NULL NU.
Description
NULL is an operation which has no effect, but is useful in, for example, delay
loops or elsewhere to indicate that no action results.
Reference
Section 10.6.
Syntax
NULL eol
Example
495 WHILE INKEY (-1) DO NULL
Associated keywords
None.
329
OF OF
Description
OF is a qualifying keyword used in DIM statements and formal parameter lists
to declare the amount of memory to be reserved for strings if the default of 40
characters is not suitable. The maximum length of string allowed is 253
characters.
OF is also used for syntactic completeness in CASE statements, but may always
be omitted on entry.
Reference
Section 4.5, DIM and CASE.
Syntax
See DIM and CASE.
Associated keyword
DIM
330
OLD O.
Description
OLD recovers a program which has been deleted using NEW or by pressing the
BREAK key. It will only work if no program lines have been entered and no
new variables created since the program was deleted.
A Bad program error will result if OLD fails and NEW should be typed to clean
up the memory. If the first line of the program is numbered greater than 255
then OLD will result in this line only being given the wrong number.
Reference
Section 5.8.
Syntax
OLD eol
Example
OLD
Associated keyword
NEW
331
OPEN OP.
Description
OPEN opens a file with the specified name on the current filing system. The file
is later referred to by the number following FILE which may be in the range
0 to 5.
After the filename is the file type specifier, which is one of: READ, WRITE,
APPEND or RANDOM.
Reference
Sections 32.6, 32.13.
Syntax
READ
WRITE
APPEND
332
Examples (see also chapter 32)
OPEN FILE 3, "myfile", APPEND
Associated keywords
FILE CLOSE READ WRITE APPEND RANDOM READ ONLY
333
OR OR
Description
OR is a logical operator which performs a bitwise OR on the two operands, ie it
looks at each bit of the binary representations of the two operands in turn and,
for each of them, sets the corresponding result bit to 1 if either or both of the
two bits are set and to 0 otherwise (giving a 32-bit number).
Reference
Section 21.1.
Syntax
Examples
PRINT 5 OR 7
710 IF a OR b THEN
720 PRINT "Either a or b or both"
730 ELSE
740 PRINT "Neither a nor b"
750 END IF
Associated keywords
AND EOR NOT
334
ORD Return ASCII value ORD
Description
ORD returns the ASCII code of the first character of the argument, which must
be a string expression. If the argument is a null string then -1 will be returned.
See section 40.1 for a table of ASCII codes.
Reference
Section 7.5.
Syntax
Examples
number_65 := ORD ("A")
Associated keyword
CHR$
335
OSCLI OS command line interpreter OS.
Description
OSCLI is a function which evaluates its string argument and passes it to the
Operating System command line interpreter. The argument should evaluate to
one of the OS * commands (without the *).
Syntax
Associated keywords
None.
336
OTHERWISE OT.
Description
OTHERWISE is used in the CASE structure to declare a block of program lines
to be executed if all the previous conditional tests in the structure fail.
Reference
Chapter 25 and CASE.
Syntax
OTHERWISE eol
Associated keywords
CASE OF WHEN END CASE
337
PAGE PA.
Description
PAGE is a system variable containing the address of the start of the program in
memory. It may be set by the user, and its default value will depend on the
particular machine configuration (disc, Tube etc). The least significant byte of
PAGE is automatically set to zero so PAGE can only be adjusted by multiples of
100 bytes hex (256 decimal). NEW should be performed after adjustments to
PAGE to avoid Bad program errors and to give the correct value of SIZE.
Note that PAGE may only be changed using an assignment statement and not,
for example, using INPUT.
A memory map is given in section 34.3.
Reference
Section 34.1.
Syntax
PAGE
Examples
PRINT PAGE
Associated keywords
FREE SIZE
338
PI PI
Description
PI is a system function which returns the value 3.141592653. It is, amongst
other things, the ratio of the circumference of a circle to its diameter.
Reference
Section 3.13.
Syntax
PI
Examples
PRINT SIN (PI/3)
Associated keywords
None.
339
PLOT PL.
Description
PLOT is used to put points, lines or triangles on the graphics screen. It requires
three arguments, the first determining the method of plotting to the point
which has the second and third arguments as its x- and y-coordinates relative
either to the current graphics origin or to the present position, depending on
the first argument.
The effects corresponding to the values of the first argument are as follows:
0 move relative to last point
1 draw line relative in current graphics foreground colour
2 draw line relative in the logical inverse colour
3 draw line relative in current graphics background colour
4 move to absolute position
5 draw line absolute in current graphics foreground colour
6 draw line absolute in the logical inverse colour
7 draw line absolute in current graphics background colour
Higher values have similar effects to 0-7 as follows:
8-15 as 0-7 but with the last point in the line omitted in ‘inverting actions’,
eg when using GCOL 4
16-23 as 0-7 but with a dotted line
24-31 as 0-7 but with a dotted line and without the last point on the line
32-63 reserved for the Graphics Extension ROM
64-71 as 0-7 but only a single point is plotted
72-79 as 0-7 but plot points left and right until non-background colour
80-87 as 0-7 but plotting and filling the triangle formed by the point given
and the last two points visited
88-95 as 0-7 but plot points to the right until background colour
96-255 reserved for future expansion
PLOT 4 is identical in effect to MOVE, and PLOT 5 to DRAW.
Reference
Section 11.9.
Syntax
340
Examples (see also chapter 11)
PLOT 2,640,512
Associated keywords
MODE MOVE DRAW CLG GCOL POINT VDU
341
POINT( PO.
Description
POINT returns the logical colour present at the point whose x- and
y-coordinates are specified by the two arguments. Brackets are obligatory
round the coordinates and there must not be a space before the open bracket. If
the point specified is off the screen then POINT returns -1.
Reference
Section 11.10.
Syntax
Examples
PRINT POINT(640,512)
Associated keywords
PLOT DRAW MOVE GCOL
342
POS Position POS
Description
POS returns the number of the screen column containing the text cursor. The
left hand column is numbered 0 and the number of columns on the screen
depends on the MODE selected.
Reference
Section 18.1.
Syntax
POS
Examples
65 horiz_distance := column_distance * POS
Associated keywords
COUNT TAB VPOS
343
PRINT P.
Description
PRINT is used to send characters to the current output device(s). The items to
be sent follow the PRINT statement in the ‘print list’.
Items in the print list surrounded by quotes will be printed exactly as they
appear in the list. Items without quotes are evaluated before printing. The
format in which the items are printed depends on the separators used in the
list. The screen is divided into ‘zones’ which are initially ten columns wide (use
ZONE to adjust this).
Using a comma (,) as the separator will result in the next item being printed in
the next zone after that in which the print marker currently resides unless it is
already at the start of that zone. If it is a string it will be ranged left in the zone,
and if it is a number it will be ranged right.
Using a semi-colon (;) as the separator will result in the next item being
printed immediately after the previous item.
Using an apostrophe (') will result in the next item being printed on a new line.
Note that to obtain a quotation mark when a string constant is PRINTed it is
necessary to put two quotation marks in the string (see example) or use a
CHR$ 34.
Numeric formatting is possible with PRINT USING where the string following
USING is of the form "##.####" . The length of this string specifies the field
width and the position of the decimal point indicates the accuracy to which the
following numbers are to be printed. ZONE is a more versatile formatting
command.
PRINT FILE is similar in operation to WRITE FILE, except that PRINT
FILE may be followed by expressions rather than just a variable list. Any
separators may be used between the items in the list.
Reference
Section 2.4 and WRITE FILE.
344
Syntax
logical expression ,
string expression ;
eol
logical expression
,
eol
Examples
PRINT a,b#;c$'(" "+a$)(-6:);
PRINT x$(number)(3:8)
65 PRINT ;message$(:35)'message$(36:70)
Associated keywords
TAB POS WIDTH INPUT VDU ZONE VPOS
345
PROC Procedure declaration PRO.
Description
PROC is the first word used on a procedure declaration line. It is followed by the
name which identifies the procedure, the formal parameter list (if any), and,
possibly CLOSED to denote a closed (or local) procedure. The body of the
procedure is between this line and the END PROC line.
PROC can only appear at the start of a program line, and not inside any other
structures.
Reference
Chapters 13 and 31.
Syntax
Associated keywords
CLOSED REF IMPORT END PROC EXEC FUNC
346
RAD Radian RA.
Description
RAD converts angles from degree to radian measure. 1 radian is (180/PI)
degrees (ie about 57.3 degrees).
Reference
Section 33.1.
Syntax
Examples
PRINT RAD 30
Associated keyword
DEG
347
RANDOM RAN.
Description
RANDOM is a qualifying keyword used when OPENing a file for random access
reading or writing. It is followed by an expression which must evaluate to the
length of record used in the file. There may then be the qualifier READ ONLY
which allows a file which is locked to be read.
The number of bytes used for file storage is as follows:
Floating point (real) numbers 6 bytes
Integers 5 bytes
Strings (Number of characters + 2) bytes
Reference
Section 32.2 and OPEN.
Syntax
See OPEN.
Associated keyword
OPEN
348
READ READ
Description
READ may be used either to read DATA items from program lines, or to read
information from files. It is also used to qualify OPEN when opening a
sequential file for reading.
When used with DATA items READ assigns the data to the variables which
follow it. If the data item is a not a valid number when the variable to which it
is to be read is numeric then a Bad value error results. See DATA for more
details of data format.
When used with files READ is followed by FILE and a numeric argument to
specify the file from which the information is to be read. If the file to be read is
a random access file then there may follow a numeric argument to specify the
number of the record to be read. If the record number is not specified then
READ reads the next item of data from the file (the first record if the file has
just been OPENed). At the end of a READ statement the internal file pointer is
moved to the start of the next record. This means that when using random
access files, all the items in a single READ list must be contained in a single
record, and that it is not possible to selectively read fields from the middle or
end of a record except by reading the earlier fields into dummy variables.
After the file designator there follows the list of variables to which the
information is to be assigned, which are separated by commas. If the data to be
read is not of the same type as the variable then a Bad type error is
generated.
Note that attempting to read items from a sequential file which has been
opened for writing or appending will generate a Not allowed error.
Reference
Section 17.2, DATA and OPEN.
Syntax
349
Examples (see also OPEN and chapter 17)
READ FILE 1:a$
Associated keywords
WRITE INPUT FILE OPEN CLOSE READ ONLY RANDOM
350
READ ONLY R.
Description
READ ONLY is a qualifying statement used when OPENing a random access file
so that writing to that file is not possible. It also allows a locked file to be
accessed.
Note that READ ONLY will not be accepted with more than one space between
the words.
Reference
OPEN and section 32.13.
Syntax
See OPEN.
Associated keyword
OPEN
351
REF REF
Description
REF is used in a PROCedure or FUNCtion declaration statement to indicate a
parameter which is to be passed by reference rather than by value. Note that
arrays must always be passed by reference.
Reference
Section 31.8.
Syntax
#
REF identifier ( , )
Associated keywords
PROC CLOSED IMPORT
352
RENUMBER REN.
Description
This renumbers a program according to the two arguments following it. The
first specifies the first line number to be used, and the second the increment for
the numbers. Either parameter defaults to 10.
Reference
Section 5.5.
Syntax
Examples
RENUMBER
RENUMBER 100
RENUMBER 1000,30
RENUMBER ,20
Associated keywords
LIST EDIT
353
REPEAT REP.
Description
REPEAT is used to declare the start of a REPEAT UNTIL... loop structure.
The lines between the REPEAT and UNTIL statements are executed repeatedly
until the logical expression in the UNTIL statement becomes true. Program
execution then continues from the line after the UNTIL statement.
Note that the loop will always execute at least once. (Use WHILE if this is not
suitable.)
Reference
Section 16.1.
Syntax
REPEAT eol
Associated keyword
UNTIL
354
RESTORE RES.
Description
RESTORE is used to reset the data pointer to some item of data in the program.
If it is followed by a label then the pointer is reset to the first data item after
that label. Otherwise the pointer is reset to the first data item in the program.
Labels are defined by typing them on their own on a program line and
terminating them with a colon.
Reference
Section 17.4.
Syntax
Examples
RESTORE
35 RESTORE
45 RESTORE second_set
Associated keywords
DATA EOD
355
RETURN RET.
Description
RETURN is used in FUNCtion declarations to indicate the value that is to be
returned by the function. All functions must return a value which is obtained
by evaluating the expression following the RETURN statement. Immediately
after the RETURN statement, program execution returns to the statement
which called the function.
Reference
Chapter 30 and FUNC.
Syntax
logical expression
RETURN eol
string expression
Associated keyword
FUNC
356
RND( Random number RN.
Description
RND is used to generate psuedo-random numbers.
It functions as follows:
RND( -x) returns the value -x and resets the random number generator to a
number based on x.
RND( 0) repeats the last number given by RND( 1).
Reference
Chapter 10.
Syntax
Examples
PRINT RND( 1,10)
Associated keywords
None.
357
RUN RU.
Description
RUN is used to run a program. If no filename is supplied then the program run
is that currently in the machine memory. If a filename is supplied then that
program is first loaded from the current filing system.
RUN clears all variables except the system integer variables.
Note that if a string variable is used in specifying the filename then it must be
in lower case.
Reference
Sections 5.3 and 14.8.
Syntax
RUN filename cr
Examples
RUN
RUN myprog
RUN "myprog"
a$ = "myprog"
RUN a$
Associated keywords
LOAD NEW OLD LIST EDIT
358
SAVE SA.
Description
SAVE is used to store the program in the machine memory on the current filing
system. The filename need not be in quotes. A string expression which
evaluates to the filename may be used (except one which uses substring
specifiers).
Note that if string variables are used in specifying the filename then they must
be in lower case.
Reference
Sections 14.3 and 14.5.
Syntax
SAVE filename cr
Examples
SAVE myprog
SAVE "myprog"
SAVE :2.$.name$
Associated keywords
LOAD RUN
359
SELECT OUTPUT SE.
Description
This is used to select which of the three possible output streams are to be used.
SELECT OUTPUT is followed by a string, the effect of which is as follows.
Reference
Section 23.1.
Syntax
Examples
SELECT OUTPUT "S"
Associated keywords
None.
360
SGN Sign of argument SG.
Description
SGN is a function which returns -1, 0 or 1 when its argument is less than zero,
zero or greater than zero respectively.
Reference
Section 18.7.
Syntax
Examples
PRINT SGN (change)
Associated keyword
ABS
361
SIN Sine SI.
Description
SIN returns the sine of the argument which is taken to be in radian measure.
Use RAD to convert degrees to radians.
Reference
Section 33.1.
Syntax
Examples
PRINT SIN (RAD (45))
Associated keywords
ACS ASN ATN COS TAN DEG RAD
362
SIZE SIZ.
Description
SIZE is a system function which returns the number of bytes of memory
currently occupied by a program. With no program it will return the value 2
since the beginning and end of program markers are still present.
See also the memory map in section 34.3.
Reference
Section 34.1.
Syntax
SIZE
Examples
PRINT SIZE
Associated keywords
PAGE FREE
363
SOUND S.
Description
Note that on the Acorn Electron this function is not the same as the BBC
Microcomputer version described below. Reference should be made to the
Acorn Electron User Guide for details of SOUND which performs exactly as in
BASIC.
SOUND is used to instruct the sound generator to activate one of its synthesis
channels to give an audio output through the internal loudspeaker. It is a very
powerful, but also somewhat complex command, and reference should be made
to the BBC Microcomputer System User Guide for a more detailed description
than that given below.
There are four sound channels which are added together to give the audio
output. Channels 1 to 3 can each generate a square wave of programmable
frequency, while channel 0 can produce psuedo-random noise or a pulse
waveform.
SOUND may be used by itself to produce simple sounds, but ENVELOPE allows
the user to have greater control over the quality of the sounds.
SOUND is followed by four parameters, the first of which is a four-digit
hexadecimal number, thus:
SOUND &HSFC,A,P,D
Range Function
H 0 or 1 Continuation
S 0 to 3 Synchronisation
F 0 or 1 Flush
C 0 to 3 Channel number
A -15 to 4 Amplitude or envelope number
P 0 to 255 Pitch
D 1 to 255 Duration
The H parameter is set to 1 to indicate a dummy note (ie the amplitude and
pitch parameters will have no effect). This feature may be used to allow the
previous note to complete in full its release phase before the next note starts.
The S parameter is used to control synchronisation of sound on the different
channels. If it is set to 0 the sound will be played as soon as it reaches the head
of the queue for that channel. If it is set to 1, 2 or 3 the sound is not played until
that many other channels have a sound waiting for synchronisation.
364
The F parameter is normally set to 0 meaning that the sound will be put in the
queue and will only be played when those preceding it have been completed.
However, if it is set to 1 then the queue will be flushed and the note played
immediately.
The C parameter sets the channel number to be used.
The A parameter controls the amplitude of the sound. This may be done either
by selecting an envelope to be used using the envelope number (1 to 4 or 1 to 16
if the RS423 and cassette buffers are unused), or by setting the amplitude
directly with a number in the range -15 (loudest) to 0.
The P parameter determines the pitch of the note. Values in the range 0 to 255
may be used.
The D parameter sets the duration of the sound in twentieths of a second. If the
amplitude has been given explicitly by a negative or zero value of the A
parameter then this is the total length of the note, otherwise it will be the
length of the attack, decay and sustain periods only (not the release period).
When used with channel 0 (the ‘noise’ channel) the P parameter has a different
effect from that described for channels 1 to 3. The results of using the various
values for P are as follows:
0 High frequency periodic noise
1 Medium frequency periodic noise
2 Low frequency periodic noise
3 Periodic noise of frequency determined by the pitch setting of channel 1
4 High frequency ‘white’ noise
5 Medium frequency ‘white’ noise
6 Low frequency ‘white’ noise
7 Noise of frequency determined (continuously) by the pitch setting of
channel 1
Reference
Section 33.2 and the BBC Microcomputer System User Guide.
Syntax
365
Examples (see also section 33.2 and the BBC Microcomputer System User
Guide)
SOUND 1,-5,53,128
Associated keywords
ENVELOPE ADVAL
366
SQR Square root SQ.
Description
SQR returns the square root of the argument. A negative argument results in a
Bad value error.
Reference
Section 33.1.
Syntax
Examples
PRINT SQR (5)
Associated keywords
None.
367
STEP STE.
Description
STEP is used in the FOR structure to indicate the increment for the loop
variable, if omitted it defaults to 1. The increment may be positive or negative.
If the start and end values of the loop variable and the increment are
incompatible (eg FOR i := 1 TO 10 STEP -1 DO) then the loop is not
performed at all and execution moves to the line after the end of the FOR
structure.
Reference
Section 6.4 and FOR.
Syntax
See FOR.
Associated keywords
FOR TO DO NEXT
368
STOP ST.
Description
STOP interrupts program execution and displays the message:
Execution may be restarted by using CONT provided that the program has not
been altered or an error generated while in the direct mode.
Note that STOP may not be used in short form loops.
Reference
Chapter 12.
Syntax
STOP eol
Examples
3010 STOP
Associated keywords
CONT END
369
STR$ String STR.
Description
STR$ returns a string containing the numeric argument as it would have been
printed. The form of the string created is affected by the field width and format
imposed by ZONE.
Reference
Section 20.12 and ZONE.
Syntax
Examples
PRINT STR$ (a+b#)
Associated keywords
VAL ZONE
370
TAB( Tabulation TAB.
Description
TAB is used to format PRINT output. There are two forms of the statement.
Reference
Sections 7.2 and 7.4.
Syntax
Examples
PRINT TAB( 15,20); "Hi There!"
Associated keywords
PRINT INPUT POS VPOS COUNT
371
TAN Tangent TA.
Description
TAN returns the tangent of the argument which is taken to be in radian
measure. Use RAD to convert degrees to radians.
Reference
Section 33.1.
Syntax
Examples
PRINT TAN (RAD (210))
Associated keywords
ACS ASN ATN SIN COS DEG RAD
372
THEN TH.
Description
THEN is a keyword used in the long and short forms of the IF structure. It is
optional on entry, except in a few cases such as:
IF x = &6000 THEN ? x = 0
Reference
Section 15.3 and IF.
Syntax
See IF.
Associated keyword
IF
373
TIME T.
Description
TIME is a system variable which is used to set or read the internal elapsed time
clock. The clock returns the elapsed time in hundredths of a second. Pressing
BREAK or SHIFT BREAK does not reset the clock (but CTRL BREAK does).
Reference
Section 10.5.
Syntax
TIME
Examples
PRINT TIME
Associated keywords
None.
374
TO TO
Description
TO is used in the FOR structure to separate the lower and upper bounds of the
loop variable.
Reference
Section 6.1 and FOR.
Syntax
See FOR.
Associated keyword
FOR
375
TRUE TR.
Description
TRUE is a system function which returns the value -1 (ie &FFFFFFFF).
Reference
Section 16.3.
Syntax
TRUE
Example
95 IF user$ = answer$ THEN answer(i#) := TRUE
Associated keyword
FALSE
376
UNTIL U.
Description
UNTIL is used to declare the terminating condition in a REPEAT structure.
Reference
Chapter 16 and REPEAT.
Syntax
377
USING USI.
Description
USING is used with PRINT statements to provide (fixed format) numeric
formatting. It is followed by a string of the form "###.##" where the length of
the string determines the field width, and the number of characters after the
decimal point indicates the accuracy to which numbers are to be printed. Any
characters may be used in the string provided that there is one decimal point,
but to be compatible with other systems ‘#’ should be used.
Note that ZONE may be used for this and for other formatting.
Reference
Section 23.5, ZONE and PRINT.
Syntax
Associated keywords
PRINT ZONE
378
USR User US.
Description
USR is a standard function which is used to call the machine code subroutine at
the address specified by the argument.
USR enters the subroutine with the Accumulator, X and Y registers set to the
least significant bytes of a#, x# and y# respectively, and the carry flag set to
the least significant bit of c#. It returns with a value which is a four byte
integer set up from the A, X, Y and P registers (in the order least significant to
most significant).
Reference
Section 34.2.
Syntax
Associated keywords
None.
379
VAL Evaluate string VA.
Description
VAL takes the string which follows it and interprets it as if it were an
expression entered at the keyboard. Hence it can access variables, call
functions, etc. It is often used to pass a function into a program from a user
input.
Reference
Section 20.11.
Syntax
Examples
PRINT VAL (a$)
Associated keyword
STR$
380
VDU V.
Description
Note that on the Acorn Electron this function is not the same as the BBC
Microcomputer version described below. Reference should be made to the
Acorn Electron User Guide for details of VDU which performs exactly as in
BASIC.
The VDU statement is equivalent to PRINT CHR$, but is generally used to
generate the ASCII control codes. These codes are interpreted by the VDU
driver and are summarised on the next page and in section 40.2. Those which
require no extra arguments are generally obvious in their effect and are not
discussed further here. Those which require more parameters are described in
detail after the table. If the arguments are separated by commas then single
bytes are sent. If any argument is followed by a semi-colon then that argument
is sent as two bytes, with the least significant byte being sent first. Reference
should be made to the BBC Microcomputer System User Guide for further
details of the operation of VDU codes.
Reference
Section 11.12 and the BBC Microcomputer System User Guide.
Syntax
Associated keywords
CHR$ PRINT
381
VDU code summary
Code CTRL Bytes Operation
needed
0 @ 0 no effect
1 A 1 send next character to printer only
2 B 0 enable printer
3 C 0 disable printer
4 D 0 write text at text cursor
5 E 0 write text at graphics cursor
6 F 0 enable VDU drivers
7 G 0 sound bell
8 H 0 backspace cursor one character
9 I 0 forwardspace cursor one character
10 J 0 move cursor down one line
11 K 0 move cursor up one line
12 L 0 clear text area (CLS)
13 M 0 move cursor to start of current line
14 N 0 page mode on
15 O 0 page mode off
16 P 0 clear graphics area (CLG)
17 Q 1 define text colour (COLOUR)
18 R 2 define graphics colour (GCOL)
19 S 5 define logical colour
20 T 0 restore default logical colours
21 U 0 disable VDU drivers or delete line
22 V 1 select screen mode (MODE:=)
23 W 9 reprogram display character
24 X 8 define graphics window
25 Y 5 PLOT
26 Z 0 restore default windows
27 [ 0 no effect
28 \ 4 define text window
29 ] 4 define graphics origin
30 ^ 0 home text cursor to top left of area
31 _ 2 move text cursor to x,y (TAB(x,y))
127 DELETE 0 backspace and delete
382
Detailed descriptions
1 This code sends the character immediately following it to the printer only
and not to the screen. The printer must already have been enabled using
VDU 2. This facility enables control characters to be sent to a printer if it
requires them to access certain features. It also allows characters to be sent to
the printer which would otherwise be ignored because the *FX 6 facility (see
section 40.3) had been used.
Example: VDU 1,14
18 This code functions exactly like the COMAL statement GCOL. It is followed
by two arguments specifying the method by which the colour is to be plotted
and the colour itself. See the entry under GCOL for further details.
Example: VDU 18,2,129
19 This code enables the user to change the actual colour referred to by a
logical colour. The first argument specifies the logical colour and the second the
actual colour which is to be assigned to it. There then need to be three
arguments of 0 which are reserved for future expansion. The actual colour
numbers are given in the entry for COLOUR.
For example, in a four colour mode:
VDU 19,2,6,0,0,0 or VDU 19,2,6;0;
will reset colour 2 from its default of yellow to cyan.
383
requires nine further arguments. The first specifies the character to be
redefined and the other eight give the contents of each row of dots, as shown in
the following example.
To generate a character as shown in the following grid and assign it to ASCII
code 245 the VDU command is:
VDU 23,245,128,192,224,240,248,252,254,255
= 128
64 + 128 = 192
32 + 64 + 128 = 224
... = 240
... = 248
... = 252
... = 254
... = 255
128
64
32
16
24 This code is used to define a graphics window, ie to change the area of the
screen in which graphics operations are possible. Four arguments follow the
VDU 24 and they must each be followed by a semi-colon. The arguments
specify the x- and y-coordinates of the bottom left corner of the window,
followed by the x- and y-coordinates of the top right corner.
Example: VDU 24,200;250;1080;774;
384
28 This code is used to define a text window, restricting the area in which text
operations are possible. The four arguments following the VDU 28 give the x-
and y-coordinates of the bottom left corner of the window, followed by the x-
and y-coordinates of the top right corner. The arguments specify the column or
row as appropriate, and the maximum values will depend on the screen mode in
use. The origin (0,0) is at the top left of the screen.
Example: VDU 28,10,20,30,10
29 This code is used to move the graphics origin to the position specified by the
two arguments following the VDU 29. The first gives the new x-coordinate,
and the second the new y-coordinate. Both arguments should be followed by
semi-colons.
Example: VDU 29,640;512; moves the origin to the centre of the screen.
31 This code is used to position the text cursor on the screen at the position
given by the arguments following it. The first gives the x-coordinate and the
second the y-coordinate. The maximum values allowable depend on the screen
mode in use. Note that the coordinates specified are relative to the top left of
the current text window. VDU 31 is identical in effect to the COMAL command
TAB( x,y).
385
VPOS Vertical position of cursor VP.
Description
VPOS returns the vertical position of the text cursor. The top of the screen
returns VPOS = 0.
Reference
Section 18.1.
Syntax
VPOS
Examples
PRINT TAB( POS,VPOS + 5);
Associated keyword
POS
386
WHEN WHE.
Description
WHEN is used to declare a block of statements in a CASE structure which are to
be executed when the variable in the CASE statement satisfies the condition
after the WHEN statement.
The condition after the WHEN statement may use any of the following
operators: > < >= <= = <> or no operator at all (indicating equality).
Additionally if a string is being tested then the IN operator may be used. More
than one condition may be used after the WHEN statement (see example), in
which case the block of program lines will be executed if any of the conditions is
true.
Reference
Chapter 25 and CASE.
Syntax
>
<
>=
<=
logical expression ,
=
<>
WHEN eol
>
<
>=
<= string expression ,
=
<>
IN
Associated keywords
CASE OF END CASE OTHERWISE
387
WHILE W.
Description
WHILE is used to declare a conditional structure which is executed while the
condition is true. There are two forms: the short form on a single program line,
or in direct mode, which consists of a simple statement to be repeated WHILE
the condition is true, and the long form consisting of a block of program lines
between a WHILE statement and an END WHILE command.
In both cases, since the condition is at the beginning of the structure, the loop
need not be executed at all, unlike REPEAT loops which are always executed at
least once.
Note that DO is optional on entry (except in a very few cases such as:
WHILE x DO ? y = 0) and is inserted automatically if omitted.
Reference
Chapter 24.
Syntax
Long form:
95 WHILE NOT finished DO
100 update_screen
105 display_menu
110 END WHILE
Associated keywords
DO END WHILE REPEAT
388
WIDTH WI.
Description
WIDTH is a system variable which contains the number of characters that may
be printed on a line either on the screen or the printer before a carriage return
and line feed is automatically generated. If WIDTH is set to 0 (the default) then
no carriage return/line feeds are printed automatically.
Note that it is only possible to change WIDTH with an assignment statement
(not, for example, from an INPUT).
Reference
Section 18.5.
Syntax
WIDTH
Examples
PRINT WIDTH
65 WIDTH :- 10
Associated keywords
COUNT ZONE
389
WRITE WR.
Description
WRITE is used to write data items to a file. It is also used as a qualifier when
OPENing a sequential file for writing.
Reference
Sections 32.7 and 32.14.
Syntax
Associated keywords
OPEN RANDOM READ PRINT FILE APPEND CLOSE
390
ZONE Z.
Description
ZONE is a system variable used for setting the format, precision, and field width
for the PRINT statement. It is essentially the same as the @% system variable
in BBC BASIC, although B4 is not implemented, and reference should be made
to the BBC Microcomputer System User Guide for a fuller discussion than that
below. Note that STR$ always uses ZONE.
The argument following ZONE is normally expressed as a hexadecimal number,
and so is preceded by the & operator. The argument consists of three bytes,
each of which is specified by two hex digits. The most significant byte (ie the
leftmost) is called B3, and the others are B2 and B1, the least significant byte.
B2 sets the total number of digits printed in the selected format. If this number
is too large or too small for that format then it is taken to be 9. The number to
be printed is rounded to fit the B2 field.
In E format B2 specifies the total number of digits to be printed in the mantissa
(ie not including those after the E). It may be in the range 1 to 9.
In F format B2 specifies the number of digits to follow the decimal point. It may
be in the range 1 to 9.
In G format B2 gives the maximum number of digits that may be printed before
returning to E format. It may be in the range 1 to 9.
B1 sets the overall print field width and may have any value in the range &00
to &FF (0 to 255 decimal).
391
The default value of ZONE is &00090A.
Leading zeros may, of course, be omitted.
Note that ZONE may only be changed using an assignment statement (not, for
example, from an INPUT statement).
Reference
Section 23.3 and the BBC Microcomputer System User Guide (@%)
Syntax
ZONE
Examples (see also section 23.3 and the BBC Microcomputer System User
Guide)
ZONE := &02040A // F format, 4 dec places, 10 field
Associated keywords
PRINT USING WIDTH
392
40 Reference tables
393
40.1 ASCII codes
394
Action/character Code Action/character Code
F 70 c 99
G 71 d 100
H 72 e 101
I 73 f 102
J 74 g 103
K 75 h 104
L 76 i 105
M 77 j 106
N 78 k 107
O 79 l 108
P 80 m 109
Q 81 n 110
R 82 o 111
S 83 p 112
T 84 q 113
U 85 r 114
V 86 s 115
W 87 t 116
X 88 u 117
Y 89 v 118
Z 90 w 119
[ 91 x 120
\ 92 y 121
] 93 z 122
^ 94 { 123
_ 95 | 124
£ 96 } 125
a 97 ~ 126
b 98 Backspace and delete 127
395
40.2 VDU code summary
0 @ 0 no effect
1 A 1 send next character to printer only
2 B 0 enable printer
3 C 0 disable printer
4 D 0 write text at text cursor
5 E 0 write text at graphics cursor
6 F 0 enable VDU drivers
7 G 0 sound bell
8 H 0 backspace cursor one character
9 I 0 forwardspace cursor one character
10 J 0 move cursor down one line
11 K 0 move cursor up one line
12 L 0 clear text area (CLS)
13 M 0 move cursor to start of current line
14 N 0 page mode on
15 O 0 page mode off
16 P 0 clear graphics area (CLG)
17 Q 1 define text colour (COLOUR)
18 R 2 define graphics colour (GCOL)
19 S 5 define logical colour
20 T 0 restore default logical colours
21 U 0 disable VDU drivers or delete line
22 V 1 select screen mode (MODE:=)
23 W 9 reprogram display character
24 X 8 define graphics window
25 Y 5 PLOT
26 Z 0 restore default windows
27 [ 0 no effect
28 \ 4 define text window
29 ] 4 define graphics origin
30 ^ 0 home text cursor to top left of area
31 _ 2 move text cursor to x,y (TAB(x,y))
127 DELETE 0 backspace and delete
396
40.3 *FX call summary
Below are given selected *FX calls of use to the COMAL programmer. For
other calls see the BBC Microcomputer System User Guide.
*fx 0 Print version number of the operating system
*fx 2 Enable/Disable input device
,0 enable keyboard input and disable RS423
,1 enable input from RS423
,2 enable keyboard input and enable RS423
*fx 3 Select output device(s)
,0 Printer Screen
,1 Printer Screen RS423
,2 Printer
,3 Printer RS423
,4 Screen
,5 Screen RS423
,6
,7 RS423
*fx 4 Reset/Disable COPY and arrow keys
,0 reset system for normal cursor editing
,1 disable editing, keys generate codes 135-139
,2 keys become user definable keys, 11-15
*fx 5 Select type of printer output
,0 lose output without ‘hang-up’
,1 parallel output
,2 serial (RS423) output
,3 select user defined printer driver
*fx 6 Set code to be ignored by printer driver
,10 ignore line feed
*fx 7 Set RS423 baud receive rate
,1 75
,2 150
,3 300
,4 1200
,5 2400
,6 4800
,7 9600
,8 19200
397
*fx 8 Set RS423 baud transmit rate
,1 75
,2 150
,3 300
,4 1200
,5 2400
,6 4800
,7 9600
,8 19200
*fx 9 Set flash period of first colour
,p where p is number of fiftieths of a second
*fx 10 Set flash period of second colour
,q where q is number of fiftieths of a second
*fx 11 Set auto repeat delay
,r where r is number of hundredths of a second
*fx 12 Set period before auto repeat starts
,s where s is number of hundredths of a second
*fx 15 Flush internal buffers
,0 flush all internal buffers
,1 flush currently selected input buffer
*fx 16 Disable/Enable analogue to digital channels
,0 disable all ADC channels
,1 enable channel 1
,2 enable channels 1 and 2
,3 enable channels 1, 2 and 3
,4 enable channels 1, 2, 3 and 4
*fx 17 Select channel and initiate A/D conversion
,n where n is number of the channel
*fx 18 Clear user defined keys
*fx 19 Wait for screen refresh before next display
398
*fx 21 Select and flush buffer
,0 flush keyboard buffer
,1 flush RS423 (serial) input buffer
,2 flush RS423 (serial) output buffer
,3 flush the printer output buffer
,4 flush sound channel 0 (white noise)
,5 flush sound channel 1
,6 flush sound channel 2
,7 flush sound channel 3
,8 flush speech synthesis buffer
*fx 200 Enable/Disable ESCAPE key
,0 enable ESCAPE
,1 disable ESCAPE
*fx 210 Enable/Disable sound
,0 enable sound
,1 disable sound
*fx 229 ESCAPE key action
,0 normal action
,n (n>0) treat as ASCII code
399
40.4 Keywords, operators and tokens
:= = 150 =
:+ :+ 150 followed by +
:- :- 150 -
+ + —
- - —
* * —
/ / —
^ ^ —
= = —
< < —
> > —
: : —
& & —
~ ~ —
? ? —
! ! —
// // 206
ABS AB. 179
ACS AC. 165
ADVAL AD. 180
AND AN. 133
APPEND AP. 139
ASN AS. 166
ATN AT. 167
AUTO A. 245
CASE CA. 239
CHR$ CH. 186
CLEAR CLE. 196
CLG CLG 198
CLOSE CLOSE 220
CLOSED C. 253
CLS CLS 199
COLOUR COL. 227
CONT CO. 249
COS COS 168
COUNT COU. 154
DATA DA. 207
400
Keyword etc Minimum form Token
DEBUG D. 250
DEG DEG 169
DEL DEL 205
DELETE DEL. 211
DIM DI. 214
DIV DIV 134
DO DO 140
DRAW DR. 221
EDIT E. 247
ELIF EL. 236
ELSE ELS. 234
END EN. 229
END CASE END CA. 229 + 239
END FUNC END FU. 229 + 237
END IF END I. 229 + 241
END PROC END PRO. 229 + 238
END WHILE END W. 229 + 242
ENVELOPE ENV. 226
EOD EOD 155
EOF EO. 181
EOR EOR 135
EXEC EX. 203
EXP EXP 170
EXT EXT 182
FALSE FA. 151
FILE FI. 141
FOR F. 243
FREE FR. 159
FUNC FU. 237
GCOL G. 222
GET GET 156
GET$ GE. 161
GOTO GO. 204
IF I. 241
IMPORT IM. 232
IN IN 138
INKEY INKEY 183
INKEY$ INK. 187
INPUT IN. 217
401
Keyword etc Minimum form Token
402
Keyword etc Minimum form Token
403
40.5 Error messages and numbers
Message Number
Bad DIM 36
Bad GOTO 29
Bad program 21
Bad type 23
Bad value 32
Can't CONT 18
EOD 33
EOF 41
Escape 17
File open 38
Name mismatch 25
No ... 28
No RETURN 39
No room 20
Not allowed 26
Not found 31
Not open 35
Parm block error 40
Record overflow 34
STOP 19
String too long 30
Syntax error 22
Too complex 27
Unclosed at ... 24
Variable exists 37
404
40.6 Precedence of operators and valid numeric ranges
The operators available in COMAL are divided into eight groups, as follows,
with group 8 having the highest precedence and group 1 the lowest.
Operators in the same group are applied in the order in which they are
encountered.
Group 1: OR EOR
Group 2: AND
Group 3: = < > <= >= <> IN
Group 4: + - (binary)
Group 5: * / DIV MOD
Group 6: ^ substring specifiers
Group 7: ? !
Group 8: unary functions NOT ( ) & ~
The term ‘unary function’ covers all the operators and keywords which take a
single argument and return a value. These are:
& ~ (unary) - ABS ACS ADVAL ASN ATN CHR$ COS DEG EOF INKEY
INKEY$ INT LEN LN LOG ORD RAD SGN SIN SQR STR$ TAN USR
VAL
Accuracy
All arithmetic values are stored with 32-bit accuracy.
405
Part IV
41 History of COMAL
409
42 Supplementary programs
920 // ****************************
930 // * This function overcomes *
940 // * the known INKEY problem *
950 // * on the BBC Microcomputer.*
960 // * For example *
970 // * code := new_inkey(300) *
980 // ****************************
990 //
1000 FUNC new_inkey(n)
1010 a:=n MOD 256
1020 b:=n DIV 256
1030 RETURN INKEY (a+&01000000*b)
1040 END FUNC new_inkey
1050 //
920 // ****************************
930 // * This function overcomes *
940 // * the known INKEY$ problem *
950 // * on the BBC Microcomputer.*
960 // * For example *
970 // * key$ := new_inkey$(300) *
980 // ****************************
990 //
1000 FUNC new_inkey$(n)
1010 a:=n MOD 256
1020 b:=n DIV 256
1030 RETURN INKEY$ (a+&01000000*b)
1040 END FUNC new_inkey$
1050 //
410
70 UNTIL turn<>180
80 PRINT "TURN ";turn;" degrees"
90 PRINT "SCALE ";scale
100 VDU 19,1,RND( 6),0,0;// COLOUR
110 VDU 29,640;512; // MOVE ORIGIN
120 x:=0;y:=-512 // START POINT
130 MOVE x,y
140 a:= scale*COS (RAD (turn))
150 b:=-scale*SIN (RAD (turn))
160 REPEAT
170 x1:=x;y1:=y
180 x:=x1*a+y1*b;y:=y1*a-x1*b
190 DRAW x,y // TURN AND SCALE
200 UNTIL ABS (x)+ABS (y) < 80
210 delay:=INKEY (100)
220 UNTIL FALSE
411
1090 anag(word$(:letter#-1) + word$(letter#+1:),
result$)
1100 END IF // Short form IF could be used
1110 NEXT letter#
1120 END PROC anag
1130 //
1140 END
412
1370 END PROC get_amount_offered
1380 //
1500 PROC give_change
1510 change# := amount# - cost# // pence
1520 PRINT ''"Change ";
1530 PRINT USING ".##":;change#/100'
1540 choose_coins
1550 END PROC give_change
1560 //
1600 PROC choose_coins
1610 WHILE change# > 0 DO
1620 READ name$,unit#
1630 number# := change# DIV unit#
1640 change# := change# MOD unit#
1650 IF number# > 0 THEN PRINT number#;" ";name$
1660 END WHILE
1670 DATA Fifty Pound,5000,Twenty Pound,2000
1680 DATA Ten Pound,1000,Five Pound,500
1690 DATA One Pound,100,Fifty Pence,50
1700 DATA Twenty Pence,20,Ten Pence,10
1710 DATA Five Pence,5,Two Pence,2
1720 DATA One Penny,1
1730 END PROC choose_coins
1740 //
1800 FUNC value
1810 value$ := ""
1820 REPEAT
1830 key$ := GET$
1840 IF key$ IN "1234567890." THEN
1850 PRINT key$;
1860 value$ :+ key$
1870 END IF
1880 UNTIL key$ = CHR$ (return_key)
1890 value# := 100 * VAL (value$) + 0.5
1900 RETURN value#
1910 END FUNC value
413
43 Suggested answers to
exercises
This chapter contains suggested answers to the exercises set at the end of the
chapters in Part I. Where variable names are used in these answers they may,
of course, be replaced by any other suitable variable of the same type. In many
cases there will be a number of alternative ways of producing the required
results which may be just as good as that given, although you should ensure
that you understand the suggested method.
Section 2.10
1. PRINT 6 + 7
2. PRINT 1 + 2 + 3 + 4 + 5
3. PRINT 4 * 5 * 9 / 6
4. PRINT 7 * 7 - 6 * 6
5. PRINT 24 / (5+3)
6. PRINT 12345679 * 7 * 9
7. PRINT 1 / 0.11
8. PRINT 3.142 * 3.5 ^ 2 / 3
9. PRINT 5.40 * 120
10. PRINT 450 / 120
Section 3.14
1. 2u begins with a number
tax paid has a space in the middle
print and free are both keywords
414
7. 3 the integer below 3.5
8. 3 the integer below 3.141592653
Section 4.11
1. PRINT a$,b$,c$
2. PRINT a$;" ";b$;c$ or PRINT a$ + " " + b$ + c$
3. PRINT a$'b$'c$
4. PRINT b$;" ";b$;" ";b$ or PRINT b$+" "+b$+" "+b$
5. 1 Y is the first element in YyNn
6. 0 Y is not in Nn
7. 3 Y is the third element in RGYBMCW
8. 1 the first place at which Y occurs
9. 1 the length of reply$ is 1
10. DIM ton$ OF 100
11. A dimension statement is not needed. 40 places will be reserved when
test$ is first assigned. No error would arise from entering
DIM test$ OF 40
Section 5.15
1. AUTO 200,5
2. Press the ESCAPE key.
3. RENUMBER 100 or RENUMBER 100,10
4. NEW
5. OLD
6. 10 a$ := "SUPER"
20 b$ := "CALI"
30 c$ := "FRAGI"
40 d$ := "LISTIC"
50 PRINT a$,b$,c$,d$
415
then either
60 PRINT a$,b$,c$;d$
70 PRINT a$,b$;c$;d$
80 PRINT a$;b$;c$;d$
or
60 PRINT a$,b$,c$+d$
70 PRINT a$,b$+c$+d$
80 PRINT a$+b$+c$+d$
followed by either
90 PRINT a$'b$'c$'d$
or
90 PRINT a$
100 PRINT b$
110 PRINT c$
120 PRINT d$
7. 10 x := 111
followed by either
20 PRINT x,x*x,x*x*x
or
20 PRINT x,x^2,x^3
Section 6.10
1. 10 FOR number := 21 TO 30 DO
20 PRINT number
30 NEXT number
40 END
416
4. 10 FOR number := 2 TO 20 STEP 2 DO
20 PRINT number
30 NEXT number
40 END
7. 10 star$ := "*"
20 PRINT star$
30 pling$ := "!"
40 FOR go := 1 TO 7 DO
50 star$ :+ pling$
60 PRINT star$
70 NEXT go
80 END
8. 10 silly$ := "ABAD"
20 PRINT silly$
30 FOR go := 1 TO 3 DO
40 silly$ :+ silly$
50 PRINT silly$
60 NEXT go
70 END
Section 7.7
1. PRINT TAB( 4,2);"here"
2. PRINT TAB( 8,14);"now"
3. PRINT ORD ("G")
4. PRINT CHR$ (70)
In the following, the loop variable need not be row. The particular variable
name is a matter of choice. row# could be used to point out the use of an
integer. It is possible to use the loop variable as part of a TAB( , ) command
as shown in the alternative answers to questions 5 and 8.
417
5. 10 CLS
20 FOR row := 1 TO 9 DO
30 PRINT TAB( 4);"here"
40 NEXT row
or
10 CLS
20 FOR row := 0 TO 8 DO
30 PRINT TAB( 4,row);"here"
40 NEXT row
6. 10 CLS
20 FOR row := 1 TO 9 DO
30 PRINT TAB( 4);row
40 NEXT row
7. 10 CLS
20 FOR row := 1 TO 9 DO
30 PRINT TAB( row);row
40 NEXT row
8. 10 CLS
20 PRINT TAB( 0,10);
30 FOR row := 11 TO 19 DO
40 PRINT ;CHR$ (70 + row)
50 NEXT row
Section 8.6
1. COLOUR 1 or red := 1
COLOUR red
2. 100 MODE := 5
110 FOR code := 65 TO 90 DO
120 PRINT CHR$ (code);
130 NEXT code
140 END
3. COLOUR 3 or white := 3
COLOUR white
4. 100 red := 1
110 white := 3
120 MODE := 5
418
130 COLOUR red
140 FOR code := 65 TO 90 DO
150 PRINT CHR$ (code);
160 NEXT code
170 COLOUR white
180 END
5. 115 yellow := 2
123 COLOUR 128 + yellow
126 CLS
6. COLOUR 2 or green := 2
COLOUR green
8. 100 green := 2
110 cyan := 6
120 white := 7
130 MODE := 2
140 COLOUR 128 + cyan
150 CLS
160 COLOUR green
170 FOR number := 1 TO 9 DO
180 PRINT number
190 NEXT number
200 COLOUR white
210 END
9. *key 2 RENUMBER
10. *key 2 RENUMBER |m
11. *key 2 RENUMBER |m MODE := 6 |m LIST |m
Section 9.7
1. 10 INPUT "Enter a number please > ":first
20 INPUT "and another please > ":second
30 total := first + second
40 product := first * second
50 PRINT ''"Their total is ";total
60 PRINT ''"Their product is ";product
419
2. 10 INPUT "Length > ":length
20 INPUT "Breadth > ":breadth
30 INPUT "Height > ":height
40 volume := length * breadth * height
50 PRINT ''"The volume is ";volume
3. Add
60 base := length * breadth
70 front := length * height
80 side := breadth * height
90 area := 2*(base + front + side)
100 PRINT ''"The surface area is ";area
Section 10.7
1. PRINT RND( 40)
2. PRINT RND( 0,39)
3. PRINT RND( 11,20)
4. PRINT RND( 0,1279)
5. PRINT RND( 640,1279)
6. PRINT RND( 512,1023)
7. Add the following lines
5 total := 0
65 total :+ score
90 PRINT '"The average was "; total/20
420
Section 11.13
1. No. Only modes 0, 1, 2, 4 and 5 have graphics.
2. MOVE 0,1023
DRAW 1279,0
3. 10 MODE := 5
20 FOR height := 0 TO 1000 STEP 100 DO
30 MOVE 0,height
40 DRAW 1279,height
50 NEXT height
4. 10 MODE := 5
20 FOR over := 0 TO 1200 STEP 100 DO
30 MOVE over,1023
40 DRAW over,0
50 NEXT over
5. 10 MODE := 5
20 FOR across := 40 TO 1240 STEP 80 DO
30 PLOT 69,across,511
40 NEXT across
6. 10 red := 1 // Assigning
20 yellow := 2 // values to
30 left := 539 // variables
40 right := 739 // makes the
50 top := 611 // program
60 bottom := 411 // MUCH EASIER
70 fill := 85 // to read.
80 MODE := 5
90 //
100 GCOL 0,128 + yellow
110 CLG // to fill background in yellow
120 GCOL 0,red // set graphics colour
130 MOVE left,top
140 MOVE right,top
150 PLOT fill,left,bottom // Uses last 3
160 PLOT fill,right,bottom // points.
170 END
7. VDU 28,0,15,19,0
Bottom left corner at position 0 across, 15 down
Top right corner at position 19 across, 0 down
421
8. VDU 24,0;0;1279;511;
Bottom left corner at coordinates 0,0
Top right corner at coordinates 1279,511
Section 13.9
1. 1203 across := RND( 0,39)
1206 down := RND( 6,20)
1210 PRINT TAB( across,down);"*"
2. 120 MODE := 1
122 red := 1
124 yellow := 2
126 white := 3
3. assign_variables
display_instructions
ask_question
input_answer
mark_answer
display_response
4. EDIT
5. a# to z# the resident integer variables (and the system variables).
6. CLEAR
7. With a single press of the SHIFT key.
8. By holding down the CTRL key and pressing the letter O key.
9. By holding down the CTRL and the SHIFT key at the same time.
10. No space between PROC and TEST.
11. EDIT is a keyword and so cannot be used for a procedure name.
12. No spaces between END PROC and TEST.
422
Section 15.7
1. endif should have a space inside. END IF will list in capitals.
2. This is not suitable for a single line IF command. There are two actions to
carry out. The print "Too low" should be on a separate line.
3. ELSE must have a line to itself. The PRINT "Wrong" should be on a
separate line.
4. When an ELSE condition is used the IF command cannot be a single line
statement. The PRINT "correct" should be on a separate line.
5. Line 170 should occur after line 190. The END IF must come after the
ELSE.
Section 16.6
1. 10 REPEAT
20 number := RND( 26)
30 PRINT number
40 UNTIL number = 26
8. 10 TIME := 0
20 correct := 0
30 REPEAT
40 CLS // or MODE := 6
50 first := RND( 2,9)
60 second := RND( 2,9)
70 PRINT ''first;" times ";second;" is ";
80 INPUT answer
90 IF answer = first * second THEN correct :+1
100 UNTIL TIME > 3000
110 PRINT ''"You got ";correct;" right."
Section 17.10
1. Line 100 should be 100 here:
A label must have a colon immediately after it.
2. Line 120 should be 120 READ number$
Line 130 should be 130 PRINT number$
The DATA contains strings.
3. There should be commas between the DATA
4. RESTORE is inside the FOR... NEXT... loop.
The only value that will be READ is Clubs
Swap 140 and 150 to get a random suit choice.
424
5. 10 MODE := 6
20 //
30 READ question$
40 PRINT ''question$
50 //
60 FOR offer := 1 to 4
70 READ answer$
80 PRINT ';offer;". ";answer$
90 NEXT offer
100 //
110 READ correct$ // note use of string
120 //
130 PRINT '"Which number is correct ";
140 REPEAT
150 choice$ := GET$ // note string
160 UNTIL (choice$ IN "1234") <> 0
170 PRINT choice$ // to display it
180 //
190 IF choice$ = correct$ THEN
200 PRINT 'choice$;" is Correct"
210 ELSE
220 PRINT '"Sorry ";choice$;" is Wrong"
230 END IF
240 //
250 DATA What does a car run on ?
260 DATA Tyres,The Road,Petrol,Hedgehogs,3
6. Add lines
125 REPEAT
235 UNTIL choice$ = correct$
7. Add lines
25 REPEAT
237 UNTIL EOD
Section 18.12
1. 5
2. 3
3. 1
4. 0
425
5. 1
6. 2
7. 3
8. 8
9. 12 – * is evaluated before DIV
These programs are not the only right answers. If you have a program that
successfully prints out the values then it may well be just as good an answer.
10. 10 FOR number := 5 TO -3 STEP -1
20 PRINT ABS (number)
30 NEXT number
Section 19.7
1. DIM name$(50)
2. DIM points#(10:80)
3. DIM grid(1:3,1:3)
4. DIM ref_number(1:3,1:50)
5. DIM item$(5,5,5)
6. DIM item$(5,5,5) OF 5
426
7. 10 // Name and Cost
20 //
30 MODE := 6
40 //
50 initialise
60 read_data
70 //
80 PROC initialise
90 DIM name$(1:5)
100 DIM cost#(1:5)
110 END PROC initialise
120 //
130 PROC read_data
140 FOR item := 1 TO 5 DO
150 READ name$(item)
160 READ cost#(item)
170 NEXT item
180 PRINT TAB( 11,10);"All values read."
190 END PROC read_data
200 //
400 DATA Fish,87,Cheese,152,Peas,30,Beans,22,Bread,45
410 END
427
Section 20.13
1. a) a$ := INKEY$ (100)
b) b := INKEY (200)
c) PRINT INKEY (-83)
2. The loops are not properly nested. The j and k after the NEXT commands
should be reversed.
3. 14
4. 5
Section 21.10
1. TRUE OR TRUE will produce TRUE (-1)
2. TRUE EOR TRUE will produce FALSE (0)
3. TRUE AND TRUE will produce TRUE (-1)
4. TRUE OR FALSE will produce TRUE (-1)
5. TRUE EOR FALSE will produce TRUE (-1)
6. TRUE AND FALSE will produce FALSE (0)
7. NOT TRUE will be FALSE (0)
8. NOT FALSE will be TRUE (-1)
9. -1
10. 0
11. -2
428
Index
Abbreviation for keyword 43,229,400 Arrow key 42
ABS 134,250 ASCII 62,111,148,394
Absolute value 134 ASN 212,256
Access Assignment 17,19,77,123,148,149,
direct 203 171,184
random 203 operator 240
sequential 203 substring 190
serial 203 Assembly language call 216,219
*ACCESS 108 ATN 212,257
Accuracy 24,27,405 AUTO 44,258
Acorn Electron – see Electron automatic
ACS 212,251 line numbering 44
Actual parameter 195,199 insertion 52,60,100,103,112,153,
Addition 10,54 170,171,180,182
ADVAL 214,252 repeat 7
AESTKP 217 repeat delay 398
Algorithm 221 repeat rate 398
Amplitude 212 Available memory 26,216,302
Analogue to digital converter 214
AND 158,159,162,254 Background colour
Apostrophe 35 graphics 88
Appendix text 69
head 234 Bad DIM 223
APPEND 204,255 Bad GOTO 223
Arc-cosine 212 Bad program 223
Arc-sine 212 Bad type 223
Arc-tangent 212 Bad value 223
Argument 25 BASIC 109, 221
Arithmetic 10,11,19,23 *BASIC 221
operators 242,405 Baud rate
Array 139,172 input 397
bound 141,172 output 398
dimension 139,140,172,184 Beep 382
element 140,141,190 Bell 382
integer 139 BGET 219
passing by reference 201 Binary operator 32,135,157,158,173,
string 141,201 233
subscript 139,140,154 Bit 175
429
Bitwise Channel 212
AND 159,162 Character 62
EOR 159,162 control 382
OR 159,162 user defined (VDU 23) 383
Blocks 106 set 394
Bound 141 CHR$ 62,261
BPUT 219 CLEAR 33,102,262
Brackets 12 Clear
Branch instruction graphics area 88
CASE 180,181,259 memory 33,102
GOTO label 307 screen 58
IF...THEN 111,112,170,183,308 text window 91
BREAK 43 CLG 88,263
Buffer flushing 398 Clock 82,118,374
Bypass 53 CLOSE 264
Byte 175 CLOSE FILE 204
Bytes FREE 26,216,302 CLOSED 197,218,265
CLS 58,266
Call Code 61,111,148
function 193 machine 215,216,219
procedure 99 Colon 17,52,75
machine code 216,219 COLOUR 267
USR 216,219 actual 383
Can't CONT 223 background text 69
Can't extend 207 background graphics 88
Capitals 8,9,30,112,119 graphics 87
CAPS LOCK 8,9 logical 383
Carriage return 132,133 number 68,89
Case lower/upper 8,9,18,30,48,62, palette 68
107,112 text 68
CASE 180,181,259 *COMAL 9,221
Cassette COMAL Standard 409
filing system 215 *command 72
loading 107 Combinational logic 158,159,161,
saving 106 162,405
sequential file 203 Comma 34,123
running program 109 Command line interpreter 220,336
*CAT 106,108 Comment 45,101,170
Catalogue 106,108 Compare
CHAIN 109 numbers 111
Changing string 111
language 9,221 Concatenation of strings 36
mode 66,70,102,172 Condition 110,157
430
Conditional loop 117 Decrunch 219
Constant 26,171,233 Default value 52,133
string 238 Defining
CONT 96,102,269 character (VDU 23) 383
Continue function 193
after STOP 96 procedure 99
after ESCAPE key 97 DEG 212,274
Continuous processing 210 Degrees
Control 67 equivalent of radians 212
code 382 conversion to radians 212
key 103,382 DEL 44,170,275
Converting program 221 Delay 83,96,103,148
Coordinates 85 DELETE 108,276
COPY cursor 42 DELETE key 6
key 42 Delete
COS 212,270 file 108
Cosine 212 line 41,44
COUNT 133,271 program 108
Crossed loops 153 Designator
Crunch 219 file 234
CTRL DIM 32,34,277
G bell/beep 382 Dimension 139,184
N page mode on 103 array 140,184,201
O page mode off 103 string 32,77,171,172,184,200
SHIFT 103 Direct access file 203
Cursor 6,35 command 39
copy 42 mode 39,97,104
editing 42 Directory 106,108
key 42 *DISC 108
off/on 144 Disc
position 58,60,131 access 108
catalogue 108
D 175 direct access file 203
DATA 123,126,128,173,272 filing system 108,215
Data loading 108
file 203 locked 108
pointer 124 processing 210
processing 203 random access file 203
DEBUG 60,273 saving 107
Decimal sequential file 203
place 176 DIV 135,278
point 13 Division 12,135
random values 80 DO 50,52,178,279
431
Dotted line 340 structural 59
DRAW 85,280 syntax 11
DS 360 ESCAPE 45,97,102,120
Duration 212 Evaluate string expression 405
Exclusive-OR 158,159,162,294
EDIT 103,281 EXEC 22,103,295
Editing *EXEC 221
line 41 Executing procedures 103,104
keys 42 EXP 212,296
program 103 Exponent 23
Effects 101,397 Exponential 212
Element Expression
array 141,190 logical 234
numeric 235 numeric 236
Electron EXT 211,297
function key 67 Extent of file 211
keyboard 7
keyboard scan 150 FALSE 110,119,149,158,159,161,298
plus 1 214 FILE 299
ELIF 185,282 close 204
ELSE 114,171,283 creation 204,209
END 46,284 direct access 203
END CASE 180,181,285 designator 234
END FUNC 193,286 extent 211
END IF 112,287 name 106,108,173,234
END PROC 100,288 number 204,209
END WHILE 178,289 open 204,209,224
End of Data 124 random access 203
End of File 207 saving 106
End of line 233 sequential 203
End of program 218 serial 203
Enter 11 type 203
ENVELOPE 212,290 Filing system 215
EOD 124,173,224,292 Filling areas 90
EOF 224,293 triangles 90
Eol 233 Fixed
EOR 158,159,162,294 length record 208
Equality 110 point 405
ERFLAG 218 Flash rate 398
Error code 404 Flashing colours 267,398
in direct mode 97 Floating point 405
message 20,153,223,404 Flush buffer 101,398
number 404
432
FOR... TO... DO 50,182,300 coordinates 85
step 52 modes 65,85
Foreground origin 85
text colour 66 window 91
graphics colour 87 Greater than 110
Formal parameter 195,199
Format Hard reset 374
line 218 Hexadecimal operators 247
print 175 HIMEM 217
FREE 26,216,302 Head appendix 234
Frequency 212 Header
FUNC 193,303 line 218
key 67 label
Function 25,32,173,193
argument 25 Identifier 234
call 193 IF... THEN 308
definition 193 short form 111,170,183
key 67 long form 112,171
mathematical 212 IMPORT 197,309
read only 215 Impossible loop 53,170
return 25 IN 31,110,121,310
RETURN 193 Indentation 50,112,114,117,170
standard 238 Indicator lights 7,8
system 26,119,124,131,133,239 Indirection operator 248
*FX call 101,397 Inequality 110
summary 397 INKEY 148,311
minus 149,311
GCOL 87,304 INKEY$ 149,314
GET 77,305 INPUT 74,174,315
Get INPUT FILE 206
byte 219 Input
code 77 numeric value 74
symbol 77 stream 397
GET$ 77,121,306 string 76
Global Insert automatically 52,60,100,103,
variable 196 112,148,170,170,180,182
variable space 215 INT 25,316
GOTO label 307 Integer 24
Graphics arithmetic 405
area 91 division 135
background 88 remainder 135
colour 87
commands 85,86,87,88
433
resident variable 25,33,102,196 format 218
variable 24,33,171 number 39
Invisible EXEC 103 overflow 7,132,133
removal 41,44
Joystick 214 Line input syntax checker 11
LIST 40,318
Key line 41,219
COPY 42 number 235
DELETE 6 numeric 236
ESCAPE 45,97,102,120 variable 239
RETURN 10,67,132 LN 212,319
SHIFT 7,8,103 LOAD 107,320
function 67 Loading
pressed 77,121,149 machine code 216
Keyboard program 107
empty buffer 398 Local
scan code table 150 variable block 197,199
scan number 149 variable 196
Keyword 1,10,21,170,229,400 LOCALH 217
summary 229,232 LOCALL 217
Locked 108
Label LOG 212,321
definition 125,172 Logarithm
GOTO 307 base 10 212
RESTORE 125 base e 212
Language Logical
change 9,221 colour 383
low level 216 condition 162
machine code 216,219 expression 234
LED (indicator) 7,8 operator 159,235
Left$ 187 LOMEM 217
LEN 30,317 Long form IF 112,183
Length of file 211 Loop 50,178
record 208 conditional 117
sound 212 impossible 53
string 30,32,34,200 nested 152
program 106 null 53
Less than 110 stack pointer 218
Line variable 51,59
auto number 44 Low level programming 216
dotted 340 Lower
editing 41 bound 141
feed 132,133 case 8,9,18,30,48,63,112
434
LSTKP 218 NOT 161,162,328
Not allowed 102,131,183,224
Machine code 215,216,219 Not found 18,34,225
Main block variable 196,199 Not open 225
Map Nothing 83
memory 217 NULL 83,170,329
Marker block 42 Null
Mathematical functions 212 loop 53,170
Matrix 201 string 30,141
Memory Number 235
clear 33 binary 159
map 217 error 404
Merging programs 220 file 204,209
Message list 235
prompt 75 Number of
Mid$ 187 colours 65
Minimum form 229,400 columns on screen 60,65
MOD 135,322 files open 204
MODE 65,323 rows on screen 60,65
changing 102,172 Number to string conversion 155,370
graphics 65,85 Numeric
Modulo arithmetic 136 accuracy 405
MOVE 86,325 array 141,201
Multiple data 128
assignment 184 element 236
dimension 184 expression 236
Multiplication 11 input 74
list 236
Name range 405
mismatch 224 variable 236
program file 106 :+ 54,173
Negative :- 55,173
argument 134
bound 141 OF 32,34,142,172,180,330
inkey 149 OLD 43,331
number 177 One’s complement 161
Nested loops 152 Online processing 210
NEW 326 OPEN 332
NEXT 50,327 file 204
No <keyword> 224 Operating system 217
No RETURN 224 Operator 230
No room 224 arithmetic 242,405
Non-alphanumeric 170 assignment 240
435
binary 32,173,230 line 340
indirection 248 triangle 340
logical 235 Point plotting 89
precedence 12,136,162 POINT( 89,342
relational 243 Pointer to data 124
OR 157,158,159,162,334 Poke 248
ORD 61,173,335 POS 131,343
Ordinal 61,173,335 Position of cursor 131
Origin change 385 Positive argument 134
OS call 231,397 Powers 13
command line interpreter 220 PP 360
version number 397 Pre-run structure check 59,170
OSCLI 220,336 Precedence 12,136,162,188
OTHERWISE 180,181,337 operator 12,136,162
Overflow 7,132,133 table 405
PRGTOP 217
P 175 PRINT 10,20,344
PAGE 215,338 format 34,175
zero 217 number 10,14,17,20
Page mode listing 103 separator 34,174
Parallel printer port 175 string 14
Parameter PRINT FILE 205
actual 195,199 Print separator 34,174
block 225 PRINT USING 176
formal 195,199 Printer
list 236 buffer 398
referenced 199 connection 175
string 200 off 382
Parm block error 225 on 382
Pascal 221 output to 175
Pass by reference 199,201 select output 175
Pause 83,148 Priority of operators 405
in program 96 PROC 99,346
in listing 103 Procedure 99,142,152
PDBUGD 218 direct mode 104
Peek 248 Procedural parameter 195,199,
PI 26,171,339 200,201
Pitch 212 Program
Pixel 383 continue 96,102,269
Pling indirection operator 248 conversion 221
PLOT 340 environment 169
point 89 line 218
436
loading 107 Relation 110
stopping 96,369 Relational operator 243
storage 107,108 Relative file 203
structure 100,142,218 Relink 219
Prompt Remainder 135
symbol 6,35 Remark 45
input 75 Remove line 41,44
Put byte 219 RENUMBER 40,353
Repeat key 7
Query indirection operator 248 Repeating commands 50
Question mark 74,75 REPEAT UNTIL... 117,354
Quotation mark 37,106,123,126, Replacing substrings 190
127,172 Reset
hard 374
RAD 212,347 soft 374
Radian Resident integer variable 24,33,
equivalent of degrees 212 102,196
conversion to degrees 212 RESTORE 124,355
RANDOM 209,348 to a label 125,173
Random access file 203,208 RETURN 193,356
Random number 80 RETURN key 10,67,132
Range of Right$ 188
analogue input 214 RND( 80,82,173,357
digital output 214 RS 423,175
line numbers 41 RUN 40,358
numbers 405 program 109
random numbers 82
READ 349 S 175
FILE 206 SAVE 106,359
file qualifier 206,209 Saving
from DATA statement 123,126 file 106
ONLY 209,351 single character 219
Read only function 215 Scientific notation 23
Real Screen
number 24 coordinates 85
variable 24 mode 65
Record position 131
length 208 size 61,65
overflow 225 wrap around 7,132,133
Redimension error 142 Search 219
REF 199,352 Second Processor 102,215
Reference 199,201 SELECT OUTPUT 175,360
table 230,393 Semi-colon 14,20,35
437
Separator 34,174 String 29
Sequential file 203 addition 36,54
append 207 array 141,201
close 204 constant 238
open 204,209 concatenation 36
read 204 data 126,128
write 204 dimension – see dimension
Serial expression 238
access file 203 function 193
port 175 indirection operator 248
printer 175 input 76
SGN 134,361 length 30,32,34
SHIFT key 7,8 multiple copies 200
CTRL SHIFT 103 null 30
LOCK 7,8 parameters 200
Short form 43,111,182,183 position in 31
Simple statement 237 REFerenced parameter 200
SIN 212,362 search 31,310
Sine 212 to number conversion 154,173,380
SIZE 215,363 too long 225
Size pointer 219 variable 29,239
Soft :+ 54,173
key 67 Structure
reset 374 check 59,170,218
Software stack 215 error 59
SOUND 212,364 Structured program 100,142
SP 360 Subdefined elements 233
Space 10,36,135,170,172 Subscript 139,140,154
Specifier 187,188,189,190,238 Substring
*SPOOL 221 assignment 190
SQR 212,367 specifiers 187,188,189,190,245
Square root 212 Subtraction 10
Stack Synchronisation
software 215 sound 214
Standard function 238 Syntax 1,169
Statement diagram 229
simple 237 error 11,20,21,225
STEP 52,368 check line 218
STOP 96,102,225,369 System
Stored data 123 cassette 215
variable 51 disc filing 215
STR$ 155,370 function 26,119,124,131,133,239
438
network filing 215 USING 176,378
variable 65,82,133,172,215,239 USR 216,219,379
439
*WORD 221 ; 14,20,35
Wrap around screen 7,132,133 < 110
WRITE 204,390 = 19,110
Write character 219 <= 110
WRITE FILE 205 > 110
>= 110
Zero <> 110
argument 134 ? 74,248
page 217 ^ 13,23,242
ZONE 176,391 _ 22
print 34 | 67
~ 176,247
*ACCESS 108
*BASIC 221
*CAT 106
*DISC 108
*EXEC 220,221
*FX 101
*KEY 67
*LOAD 216
*SPOOL 220,221
*TAPE 106
*WORD 221
! 248
" 14,29,37,126
"" 30,37,127
# 24,176
$ 29
& 247
' 35
() 12
* 11,242
+ 10,36,242
, 34,123
- 10,177,242
. 13,176
/ 12,242
// 45,72,170,249
: 17,52,75,176
:+ 54,173,240
:- 55,173,240
:= 17,240
440
COMAL
on the BBC Microcomputer and Acorn Electron