UNIT ONE: A calculator that can do algebra

Section A: The computer in calculator mode.

The computer, as the name implies, was originally designed as a machine for performing calculations. Since a pocket calculator can also do that, we want to know what the advantages are of using BBC BASIC for this job. There are three main points to note:

1) If you have a long list of items to add up on a calculator, and you find yourself interrupted for some reason, you lose your place and have to start again. To avoid errors, you either need a perfect memory or you have to write a list on paper. BBC BASIC, however, not only performs calculations, but can print out a record in both figures and text of the task in hand.

2) If you wish you can use brackets, as in algebra, to perform a series of interlinked calculations in one go.

As promised in the introduction, we will assume you are an absolute beginner in BBC BASIC and have never succeeded in doing anything with the blank screen showing the BASIC prompt. Perhaps you have tried, in the absence of a tutor, to use BASIC like a calculator, by typing in figures and linking them together with the signs for addition or subtraction. Nothing happens. Perhaps you have tried typing in letters from the keyboard, just like a typewriter, and have been even more discouraged to get the error message MISTAKE! Or perhaps, if you are a "restart" beginner, you once tried to teach yourself BBC BASIC from the BBC Micro User Manual, and found, in the absence of a tutor, that every program you tried to follow seemed to pre-suppose that you were at home with commands that you had never seen before! All of these are common problems which can be easily surmounted. What you need to appreciate at the outset is that there is a difference between cataloguing the material to be learnt and managing your personal learning strategies. Successful cataloguing follows on from successful understanding, and no definition needs to be learnt just for the sake of learning it.

BASIC keyword: PRINT

The key to the door of BBC BASIC lies in the BASIC keyword PRINT. It's a multi- function command, so we have to be careful not to presuppose that it refers simply to the printer. Since we are talking about communication, we can take an illustration from direct, physical communication between humans beings. Suppose somebody says to you: "OK, let's get down to brass tacks and do some computing. What's two and two?" You have a range of options for getting your answer across: you can hold up four fingers, you can write either the figure 4 or the word "four" on a piece of paper, or you can simply say: "four". In other words, you as a human person can in this case use three separate physical devices for the job of getting the message across - of giving information.

Similarly, the BASIC keyword PRINT can send the result of a calculation to a number of hardware devices controlled by the computer: the screen, the printer or the disk drive. The default destination in BBC BASIC is the screen, not the printer, and extra commands are needed to send the answer to the printer or to save it to disc. So in practice the simple command PRINT means: "Print the results of my keyboard operation on screen." We can now put this into practice with arithmetic. Locate the instructions for accessing BBC BASIC on the web page, and don't forget to type *BYE when you want to quit.

Example 1.

When we access BASIC on the computer, the monitor shows that we're in Command Mode, indicated by the > sign and the flashing cursor. Type the following command:

PRINT 2+2 [Enter]

The answer is worked out and printed on the screen. Realists will at this point object that no sane person on Earth needs to know how to work out the sum of two and two. True. But there are millions of people who do indeed need to make a breakthrough in computer programming, by appreciating that success follows on from seeing not only that the numerical operation 2+2 can be represented by the single figure 4, but that this single figure can be assigned to a letter such as A, that algebraic operations can be performed on this letter by the computer, and the numerical result delivered automatically.

However, we shall come to algebra when we have finished with simple arithmetic. To take the next step, type in a whole row of figures to add together. Start your row with the command PRINT, join your figures with the plus sign, and finish by pressing the [Enter] key.

The genie of the lamp produces the answer - but so does a pocket calculator. So what is the advantage of a computer? The initial answer is that BBC BASIC gives greater security in adding up a long list. The computer displays a memo of what you are doing as you go along and saves you the added task of making jottings. Now let's put this new knowledge into practice with some real-life accounting.

Example 2.

Let's assume you are reconciling your bank statement with your cheque book. Your statement will look something like this:


Current Account

DateTransaction DescriptionDebit CreditBalance
3OCTCHEQUE50.00 924.01

On your statement, pencil in the additional cheques you have drawn since the statement was issued, as well as standing orders and direct debits due on the calendar. Then pencil in additional credits such as cheques you have paid in, or your salary if you have received the usual slip from your employer. At a later stage you will learn how to simulate a bank statement, but for the moment let us simply use BBC BASIC as a combination of calculator and jotter.

BASIC keyword: REM

In order to separate the notes you make for yourself from the operations carried out by the computer, you need to type in the keyword REM - a token for "REMARK"- followed by your jottings. The computer disregards the entire contents of a line preceded by REM, so that you can use the line for making any marginal notes you like: they won't go into the program. Type the following:


Now type PRINT, followed by all the credits you have pencilled into your statement since the last entry. Use the + arithmetic operator between each keyboard entry. Don't forget to press [Enter] at the end of your row of entries. This will total your credits and you can then check each entry for accuracy. Do the same with your debits (typing in REM DEBITS at the start) to add up the total. Working out the final balance is a simple matter of subtracting the sum of the debits from the existing balance, and adding the sum of the credits. The combination of REMarks and figures on screen should ensure that you don't make a mistake.

In the course of Unit 1 you will learn how to write a program so that the computer can carry out a series of calculations in separate stages. But by using BASIC in calculator mode, with jottings entered after the keyword REM, an enormous amount of rapid and accurate work can be done with figures without any need for programming.


You can use the PRINT command to carry out every operation you could possibly need to do in arithmetic. Long division and long multiplication are effectively instantaneous. But note that the signs for these are different in BBC BASIC from the traditional operators: for multiplication you use an asterisk ("star" for short), and for division you use the forward oblique stroke, or "forward slash", e.g. 5*2: 9/3

Example 3.

Try the following, then do some examples of your own:

PRINT 567*567 [Enter]
PRINT 999/9 [Enter]


Suppose we have several different arithmetical operations to carry out on the same line? There is no problem as far as addition and subtraction are concerned. After the PRINT command we can add and subtract whatever numbers we like. However, when we move on from addition and subtraction to multiplication and division, individual calculations sometimes have to be done separately if we're doing them on paper. Here the convention is to use brackets to mark off the internal routines of subsidiary calculations, before the results of these are put into a single formula to give the final result. Just as a reminder, here's an example:


You no doubt remember that in order to arrive at x, you have to add a and b, then divide c by d, then subtract the answer in the second set of brackets from the answer in the first. The use of BASIC as a machine for handling letters as algebraic symbols will be considered later. For the moment we want to examine the question of brackets purely for arithmetic in BASIC. There are two points to make:

1) Although the above operation will work successfully as shown, using the brackets given, it is a point of interest to note that BBC BASIC adheres to the normal rules of arithmetic, and does not technically need the brackets shown in the example above. To illustrate this, carry out the calculation below, first on a pocket calculator, then using BBC BASIC:


If you divide 9 by 5 on the calculator, it gives you 1.8.
Subtract 6 from 1.8 and you get -4.2
Multiply -4.2 by 7 and you get -29.4

However, now type the following into BBC BASIC

PRINT 9/5-6*7[Enter]

it returns an answer of -40.2, the same answer that you will get if you use brackets, as follows:

PRINT (9/5)-(6*7)[Enter]

If you find this confusing, don't worry: the author also found it a hard nut to crack at first. So a word needs to be said here about the successful management of learning strategies. The student of BBC BASIC needs to distinguish between essential and optional routines. Programming can be laborious when it gets complicated, and so short cuts save time and effort in the long term. However, if in the immediate term a short cut requires tricky technical definitions which complicate matters for you as a beginner, then it can be shelved for now and then re-examined at a later stage. The technical definitions are a means to an end, not an end in themselves. So if you clearly understand how the omission of brackets works, and feel confident about leaving them aside, then go ahead. If you can't quite see how it works, you can be assured that the conventional use of brackets in both arithmetic and algebra will work in BBC BASIC.

Powers and Roots

Before we leave arithmetic, we need to know how to take such traditional short cuts as raising a number to a given power, or finding a given root. The obvious way to square a number is to multiply it by itself. But there is an additional sign in the upper case of the figure 6 on the keyboard. This means "raise to the power of". Try the following:

PRINT 2^2[Enter]
PRINT 2^3[Enter]

To find a square root, use the abbreviation SQR, as in the following example:

PRINT SQR 16 [Enter]

To those who are familiar with geometry, this evidently promises to be useful in calculations involving Pythagoras' theorem. Later in this tutor, you will learn how to use BBC BASIC to produce both geometrical diagrams and technical drawings.

Section B: Algebra Made Easy

Now that we have established the power of BASIC to do arithmetic, we can start speeding up the process by using algebra. We have noted that we can use brackets, as in algebra, to do arithmetic in BBC BASIC. Now we can transfer this skill directly to algebra. Here we can use letters and even words to represent numbers, and the computer will perform calculations on the letters or words as if they were numbers. In fact the microprocessor, at heart of the computer hardware, handles everything you see on the screen, whether figures, words or graphics, in numerical codes.

If you are a restart beginner, and have been foxed up to now by the use of letters to represent variables in BBC BASIC, then here is a useful piece of advice written sixty years ago by John Davidson in Teach Yourself Mathematics: "...if the student makes up his mind to see in algebraical operations only arithmetical processes generalised, he ought to find little difficulty"(p.19). Applied to BBC BASIC, that means that the computer will work out any unknowns in algebra, provided you key in the known figures at the outset, and you state what arithmetical functions have to be performed between the known figures and the unknown figures.

Nothing will be achieved by typing in an algebraic formula at the outset, such as the following:


When you as a human being write such a formula, you know from experience that you can work out the value of x once you have assigned values to the other letters. But that experience is stored knowledge, whereas nothing is stored by the computer in BBC BASIC, in terms of values, until you key them in, or "assign" them, by means of the equals sign. This sign is a command, which can be summed up as follows: "Note the figure displayed on the right of the equals sign, and store it in the letter(s) on the left of the sign, when I press [Enter]." Any calculations which are performed on this letter will then be performed on the numeric value which it represents. This value can be updated at any time by typing in a new value. Because it can be updated at any time, the letter itself is called a variable, and because it represents a number it is called a numeric variable. Once you have grasped this fact, it is equivalent in programming to learning to keep your balance on a bicycle!


Example 4.

To illustrate this, let's assume we're doing the weekly shop, and want to buy a few packets of half a dozen eggs @ 50p per packet.

We have to tell the computer what one packet costs. Type the following:

LET EGGS=50 [Enter]

Here we have assigned a value to a word. As soon as we press the [Enter] key, the computer stores the value. This is called an ASSIGNMENT STATEMENT. (We will assume that by now you have made a habit of pressing the [Enter] key after a keyboard statement or command, and from now on it will be omitted in the text! ) To check that the value has been committed to memory, tell the computer to print it out, as follows:


The computer returns (on screen) the figure we have assigned to the word EGGS. Suppose we want two packets of eggs. We can instruct the computer to add 50 and 50 or multiply 50 by 2, using EGGS as the code-word for 50. Try it, using the PRINT command to mean "calculate and print on the screen", as follows:


In each case, the answer is given as 100. We know it is 100p, and that 100p=£1.00, but the computer has simply added 50 and 50. How do we get it to convert pence to pounds? In the long run we can use the command IF, followed by the command THEN, to deal with ifs and buts. But for the moment we shall learn how to get the computer to carry out two commands in sequence: to multiply the cost of a packet of eggs by the number of packets we want, then to convert the sum from pence into pounds. Logically enough, a sequence of two or more commands is called a program. Hence the origin of the word!

BBC BASIC requires the steps in a program to be numbered. Not all programming languages do - but the real beginner is helped by numbering statements, because it makes it easier to edit anything that goes wrong. For editing purposes also we number our lines in steps of 10: line one is 10, line two 20, and so on. The reason for this is that if you need to put finer detail into a program when you're revising it, you can add lines in between each step of 10. Now let's get back to our program.


Let's develop our theme of buying eggs. They vary in price, so we'll start with six small eggs @ 70p and tell the computer to note what they cost. And since we're using algebra, so we'll shorten EGGS to E. Type the following:

10 LET E=70


This two-line program is a program, however short. The combination of the BASIC keyword LET and the equals sign stores the value of 70 in the letter E. To get the computer to execute the program we enter the BASIC keyword RUN. Sure enough, the figure we have entered for E is displayed on the screen. Now let's make the computer earn its keep by doing some computing. We want two packets of eggs. What do they cost? Type the following:

10 LET E=70
20 PRINT 2*E

We are told that the total cost is 140p. The computer cannot be expected to know that 140p=£1.40, but we can instruct it to convert the total pence into pounds as part of the program. Here we have a new variable called "total", which we shall abbreviate to T. So we now give the computer four instructions in sequence:

1) to store to memory the statement that one packet of eggs costs 70 p

2) to multiply the cost by two

3) to divide the total by 100 to give the cost in pounds and pence as a decimal fraction. (The pound sign can give problems, so we shall use the abbreviation GBP for sterling.)

4) to print out the total on screen.

Now that we are familiar with the assignment statement, we can note in passing that the BASIC keyword LET can be dropped. Type in the following program and RUN it:

10 E=70
20 T=(2*E)
30 GBP=T/100

More Numeric Variables

The calculation above is based on the assumption that half a dozen eggs cost 70p. But in real life, of course, the price depends on the size, the quality and where you buy them. The price varies according to each factor. In other words, the concept of "the price of a packet of eggs", which we have summed up in the letter E, is a variable. More precisely it is a numeric variable, because the item that can be varied is a number. How does the computer deal with variables? The short answer is that it remembers the LAST instruction that you give it, which updates any previous instruction, and then carries out any mathematical operation on the variable that you enter into your program.

To consolidate this, let us assume a range of three prices, from small eggs to extra large, @ 70p, 80p and 99p respectively. Type in the following assignment statements and PRINT commands:



Since the computer is supposed to save labour, then it stands to reason that if we have to keep typing out the whole program every time we update the value of half a dozen eggs, we might as well revert to our pocket calculator. The solution to this is to set up a skeleton program, into which we can input the value of E, once we have established that it is a variable.

Example 5.

To do this we use the INPUT command. Type out the program again as above, but this time substitute a new line - INPUT E as the first line. Before consulting the program below, see if you can work it out for yourself from the previous program. Then check it against the example given. If you do it correctly, you will find a question mark on screen when you run the program. This is where you INPUT the value, which can be any figure you like for your packet of eggs. When you enter your INPUT, the program will give the result in pounds and pence each time you run it. Once you have tried your own program, copy out and run the sample program below as a check.

20 T=2*E
30 GBP=T/100

The obvious drawback of entering the price of the eggs in pence is that we have to divide by 100 to convert into pounds. To avoid this, we will henceforth enter all pence values as decimal fractions of a pound.

Suppose we're doing the weekly shop, and we want small eggs for baking, medium eggs for omelettes and large eggs to boil. We want two packets of small, two of medium and three of large. How do we do it?


Having learnt that an assignment statement informs the computer what the content of a variable is, we need to assign monetary values to each packet. In this particular case we only have three values to assign - but what happens if we have a long list? How do we remember what the names of the variables mean? Here the BASIC Keyword REM, which we met at the beginning in the context of the bank statement, helps us out. Here again we type REM in front of each REMARK, and it instructs the computer to isolate the REM statements from rest of the program, so that they are not acted upon.

Type the following opening line:


We are now ready to calculate the cost of our eggs before we shop. Let's assume that half a dozen small eggs cost 70p, medium cost 80p and large cost 99p, and we want three packets of each. Even without starting our program, it's obvious that multiplying prices in pence will give a large total of pence, so we will enter each price as a decimal fraction of a pound.

Example 6.

Take a quick look at the specimen program below and try to reproduce the program for yourself. Then compare your own program with the sample. It may not be exactly the same, but it if works, it is correct.

10 S=0.7
20 M=0.8
30 L=0.99
40 T=(3*S)+(3*M)+(3*L)

BASIC keywords NEW and INPUT

If all has gone well in the above program, you will get the answer 7.47 when you type RUN. However, the program as it stands is no more than an illustration of how to put simple algebra into operation in BBC BASIC. It's not a labour-saving program, because of all the trouble you have to go to in typing in assignment statements for each of the three sizes of eggs! The program clearly needs editing, and later on we will learn how to do this on the PC version of BBC BASIC. (At this point, restart beginners should be warned that there is no COPY key as on the BBC Micro!) To clear the decks, type in the BASIC keyword NEW, then type in the following program:

60 T=(3*S)+(3*M)+(3*L)

When you RUN this program , the computer will present you on screen with three question marks, one after the other. You choose and then type in (i.e. INPUT) the figures (nothing else) for the separate values of a packet of small eggs, a packet of medium eggs and a packet of large eggs, in response to each of the question marks. Once you ENTER the final figure, the computer then returns the total cost in pounds and pence. Thus if you choose £0.50 for a packet of small, £0.60 for a packet of medium and £0.70 for a packet of large, your total cost comes to GBP 5.40.

The question might arise at this point why three different sizes of the same article can't be grouped under a single heading. This can in fact be done in the form of an Array, where E stands for eggs, and the three different sizes appear as E(1), E(2) and E(3). However, in order to take full advantage of this, we need to construct a program which goes round in numbered circles - doing a differentiated task each time round - and that will require a separate chapter. For the moment we can simply note the possibility of grouping like variables in sets - a facility to be elaborated later - so as to achieve the true economy of effort of which BBC BASIC is capable.

Section C: Introducing Text and String Variables.

When you ran the above program about pricing eggs, it may have occurred to you that the question marks which appeared on screen - three in all - depended on the reliability of your own short-term memory to bear in mind what each question mark was for. Similarly, the answers given in figures are only meaningful in the context of the above program sketch, in which the whole framework can be summed up in one recollection. If we start expanding beyond this, there is a clear need to add labels in text to the program.

This has often been confusing for beginners, but the key to getting it clear lies in the fact that the name of the variable, whether E or eggs, can have a numeric value assigned to it by means of the equals sign: the computer reads that letter as a token for a specific agreed number. When we start using text, however, we have to type in a command which changes the role of the keyboard. Once the command is issued, every key on the keyboard sends a code to the processor, which produces the letter represented by the key code on screen. In other words, it types it. That seems common sense enough, but it is a different deal from representing numbers.

The programming switch which changes over this function of representation, from numbers to text, is a "two-pole" switch: the variable name is followed by the dollar sign, and the text itself is enclosed in inverted commas, as follows:

10 N$= "Ebenezer Scrooge"

As soon as you RUN this program, it prints out the name Ebenezer Scrooge. Try it several times, substituting a different name for Dickens' celebrated character. From this it becomes clear that N$ is a variable, and because it represents a string of characters rather than a number, we call it a "string variable".

BASIC keyword CLS

So now we can expand our eggs program so as to print text labels on screen and make it clear what we are dealing with. In order to separate the mental notes we have made in setting up the program from the program itself, we clear the decks by clearing the screen - for which the BBC BASIC command is CLS. Type out the following:

30 L$= "Large eggs"
40 M$=" Medium eggs"
50 S$= " Small eggs"
100 PRINT L$
120 T=(3*S)+(3*M)+(3*L)
200 PRINT "The total cost is GBP";T

When you RUN this program, you will find that instead of being presented with three disembodied question marks for the INPUT, each question is labelled according to the size of the eggs. From this the obvious conclusion can be drawn that we have here, in outline, the beginnings of the dialogue box, which constitutes such a familiar feature of commercial software. In the next Unit we will enhance it with graphics and colour.

To draw together the threads of text and numbers under the PRINT keyword, we will reproduce a section of a supermarket till receipt. This is what language teachers call an "authentic text" - i.e. a text drawn from real life, for the purpose of obtaining and giving information, rather than a text that has been invented for the purpose of illustrating a grammatical principle - although the latter does sometimes have its uses!

1.770 kg @ £ 1.08 /kg
 APPLES 1.91
0.640 kg @ £ 1.08 /kg
0.650 kg @ £ 0.36 /kg

BASIC keyword TAB

There is no need to copy the spacing pedantically here, but we have to make a start on print formatting by using the TAB keyword. In order to indent either text or numbers, either on screen or printer output, we use the TAB keyword, followed by the number of blank spaces in brackets, then the item to be printed. So to indent "BANANAS" by seven spaces, we type


We then need to add the price, separated from the text. There is no need to add spaces, since BBC BASIC will print the figures flushed right. So type the following:


To familiarise yourself with this you can print the remainder of the items from the receipt in this way. We have now completed the lesson material of Unit 1. Before going on, it needs plenty of practice in the form of assignments, where the routines studied here can be repeated and adapted and thereby learnt from memory.

Assignment 1.

Suppose, however, you want to add up the total for the fruit and vegetables section of the shopping list? You have to write a program in which you assign a letter to each item, and a value to each letter, at the beginning. For this you will need to revise the eggs program above. Try it for yourself - then use your own supermarket shopping list for further practice.

Assignment 2.

At the time of going to press - or perhaps more correctly "spinning to web"? - there are fifteen shopping days to Christmas, so we can begin planning our Christmas dinner, using authentic prices jotted down at the supermarket:

Item:UnitUnit price
Mince pies61.09
Christmas pudding    454g   1.99
Brussels sproutskg1.08
Port 75cl6.69

Let's assume a family of four on a modest income. You might want, say, a 5kg turkey, four packs of mince pies, a pudding for Christmas and one for New Year, 1kg of parsnips, 500g of sprouts, two bottles of sherry, half a dozen bottles of hock and two bottles of port. All the items in the list begin with a different letter, so you can name each numeric variable by the first letter, e.g.T=2.89. Once the values are assigned, you can find the total by adding together the numeric variable letters. To print out the bill on screen, you will need to assign the name of each article as a string variable name, e.g. T$= "Turkey"

Assignment 3.

You are a student of Art & Design and you have invited your friends to an end-of-term party. On the morning of the party you receive a telephone call from your maiden aunt, who is exceptionally wealthy - but an absolute teetotaller - to let you know that she is passing through your college town and wants to visit you. You have already bought half a dozen two-litre bottles of cider. If your aunt sees them, she will disinherit you, but you have nowhere to hide them in your bedsit.

By chance, your college has just had a new central heating system installed, and the Principal has arranged with the Bursar to let the students use the surplus copper piping for project work. To save the situation you decide to make a sculpture out of 22 millimetre (internal diameter) copper piping, and to decant the cider into the sculpture to hide it. Write a program to work out what length of piping you will need. (The formula for the area of a circle in BASIC is PI*(R^2), where R is the radius. BBC BASIC automatically supplies the value of PI. You will naturally find the radius by halving the diameter of the cross-section of the piping.) In geometrical terms, the internal volume of the required piping will effectively be a cylinder, where the area of the cross-section is multiplied by the length. Since you know from the quantity of cider what the internal volume has to be, you can work out the overall length of piping you will need with the help of the formula.

Assignment 4.

After putting on weight at Christmas, you might want to take some exercise in the form of decorating. Take a trip to your local DIY superstore, have a look round at decorating materials and take home a catalogue. See if you can devise a program, using the principles you have studied, to work out the surface area of the walls to be papered or emulsioned and then to use the printed information supplied with the product on coverage to work out how much paper/paint you need. Finally, tot up the cost.


UNIT 2Right

Best viewed with Any Browser Valid HTML 3.2!
© Edmund Burke 1999