Sinclair QL Beginner's Manual

Sinclair QL Beginner's Manual

Hide thumbs Also See for QL:

Advertisement

QL
Beginner's Guide
© SINCLAIR RESEARCH LIMITED
By Roy Atherton (Bulmershe College Computer Centre)

Advertisement

Table of Contents
loading

Summary of Contents for Sinclair QL

  • Page 1 Beginner’s Guide © SINCLAIR RESEARCH LIMITED By Roy Atherton (Bulmershe College Computer Centre)
  • Page 2: Table Of Contents

    INDEX Chapter 1 - Starting Computing Self Test On Chapter 1 Chapter 2 - Instructing The Computer Self Test On Chapter 2 Problems On Chapter 2 Chapter 3 - Drawing On The Screen Self Test On Chapter 3 Problems On Chapter 3 Chapter 4 –...
  • Page 3 RESET This is not a key but a small push button on the right hand side of the QL. It is placed here deliberately, out of the way, because its effects are more dramatic than the break keys. If you cannot achieve what you need with the break keys then press the RESET Button.
  • Page 4 There are two SHIFT keys because they are used frequently and need to be available to either hand. Hold down one SHIFT key and type some letter keys. You will get upper case (capital) letters. Hold down one SHIFT key and type some other key not a letter. You will get a symbol in an upper position on the key.
  • Page 5 The left cursor together with the CTRL key acts like a rubber. You must hold down the CTRL key while you press the cursor key. Each time you then press both together the previous character is deleted. ENTER The system needs to know when you have typed a complete message or instruction. When you have typed something complete such as RUN you type the ENTER key to enter it into the system for action.
  • Page 6 UPPER AND LOWER CASE CLS  Cls  clS  These are all correct and have the same effect. Some keywords are displayed partly, in upper case to show allowed abbreviations. Where a keyword cannot be abbreviated it is displayed completely in upper case.
  • Page 7: Self Test On Chapter

    9. RUN  10. LIST  11. NEW  12. Do keywords have the proper effect if you type them in lower case? 13. What is the significance of the parts of keywords which the QL displays in upper case?
  • Page 8 Even if it were not necessary, a program line without proper spacing is bad style. Machines with small memory size may force programmers into it, but that is not a problem with the QL You can check that a pigeon hole exists internally by typing: PRINT dogs ...
  • Page 9 Of course, you could achieve this result more easily with a calculator or a pencil and paper You could do it quickly with the QL by typing: PRINT 9 * 28  which would give the answer on the screen. However the ideas we have discussed are the essential starting points of programming in SuperBASIC.
  • Page 10 1. Names such as dogs, days and tins are called identifiers. 2. A single instruction such as: LET dogs = 9  is called a statement. 3. The arrangement of name and associated pigeon hole is called a variable. The execution of the above statement stores the value 9 in the pigeon hole 'identified' by the Identifier dogs.
  • Page 11 If we had tried to print out the value of "pounds", the QL would have printed a * to indicate that "pounds"...
  • Page 12 RUN  and the output: should appear. The advantage of this arrangement is that you can edit or add to the program with minimal extra typing. EDITING A PROGRAM Later you will see the full editing features of SuperBASIC but even at this early stage you can do three things easily: replace a line insert a new line...
  • Page 13 35  It is as though an empty line has replaced the previous one. OUTPUT- PRINT Note how useful the PRINT statement is. You can PRINT text by using quotes or apostrophes: PRINT "Chocolate bars"  You can print the values of variables (contents of pigeon holes) by typing statements such as: PRINT bars ...
  • Page 14 4  Do not forget the ENTER key. The output will be: The INPUT statement needs a variable name so that the system knows where to put the data which comes in from your typing at the keyboard. The effect of line 30 with your typing is the same as a LET statement's effect.
  • Page 15 The symbols $, % have special purposes, to be explained later, but you can use the underscore to make names such as: dog_food month_wage_total more readable. SuperBASIC does not distinguish between upper and lower case letters, so names like TINS and tins are the same.
  • Page 16: Problems On Chapter

    18. Why are freely chosen identifiers important in programming? PROBLEMS ON CHAPTER 2 1. Carry out a dry run to show the values of all variables as each line of the following program is executed: 10 LET hours = 40  20 LET rate = 31 ...
  • Page 17 CHAPTER 3 - DRAWING ON THE SCREEN In order to use either a television set or monitor with the QL, two different screen modes are available. MODE 8 permits eight colour displays with a graphics resolution of 256 by 256 pixels and large characters for display on a television set.
  • Page 18 Colours have codes as described below. Code Effect 8 colour 4 colour black black blue black magenta green green cyan green yellow white white white For example, INK 3 would give magenta in MODE 8 and red in MODE 4. We will explain in a later chapter how the basic colours can be 'mixed' in various ways to produce a startling range of colours, shades and textures.
  • Page 19 The part of the screen in which you have drawn lines and create other output is called a window. Later you will see how you can change the size and position of a window or create other windows. For the present we shall be content to draw a border round the current window. The smallest area of light or colour you can plot on the screen is called a pixel.
  • Page 20 REPeat star END REPeat star and what lies between them is called the content of the structure. The use of upper case letters indicates that REP is a valid abbreviation of REPeat. This program should produce coloured lines indefinitely to make a star as shown in the figure below. The STAR program You can stop it by pressing the break keys: Hold down CTRL and then press...
  • Page 21: Problems On Chapter

    This is another very useful structure because it is a choice of doing something or not; we call it a simple binary decision. Its general form is: IF condition THEN statement(s) You will see later how the two concepts of repetition (or looping) and decision-making (or selection) are the main structures for program control.
  • Page 22 HINT: First find the co-ordinates of some of the corners, then put them in groups of four. You should discover a pattern.
  • Page 23 CHAPTER 4 – CHARACTERS AND STRINGS Teachers sometimes wish to assess the reading ability needed for particular books or classroom materials. Various tests are used and some of these compute the average lengths of words and sentences. We will introduce ideas about handling words or character strings by examining simple approaches to finding average word lengths.
  • Page 24 LENGTHS OF STRINGS SuperBASIC makes it easy to find the length or number of characters of any string. You simply write, for example: PRINT LEN(weekday$)  If the pigeon hole, weekday$, contains FIRST the number 5 will be displayed. You can see the effect in a simple program: NEW ...
  • Page 25 10 LET weekday$ = "FIRST"  20 LET word$ = "OF"  30 LET month$ = "FEBRUARY"  40 LET length1 = LEN (weekday$)  50 LET length2 = LEN (word$)  60 LET length3 = LEN (month$)  70 LET sum = length1 + length2 + length3  80 LET average = sum/3 ...
  • Page 26 Word$ Month FEBRUARY Phrase$ FIRSTOFFEBRUARY There is one more reasonable simplification which is to use READ and DATA instead of the first three LET statements. Type: NEW  10 READ weekday$, word$, month$  20 LET phrase$ = weekday$ & word$ & month$  30 LET length = LEN(phrase$) ...
  • Page 27: Problems On Chapter

    40 LET third$ = CHR$(RND(65 TO 67)) 50 LET word$ = first$ & second$ & third$ 60 PRINT ! word$ ! 70 IF word$ = "CAB" THEN EXIT taxi 80 END REPeat taxi Random characters, like random numbers or random points are useful for learning to program. You can easily get interesting effects for program examples and exercises.
  • Page 28 a) ; at the end of a PRINT statement. b) ! on either side of item printed.
  • Page 29 It is tedious to enter line numbers manually. Instead you can type: AUTO before you start programming and the QL will reply with a line number: Continue typing lines until you have finished your program when the screen will show: 100 PRINT "First"...
  • Page 30 To finish the automatic production of line numbers use the BREAK sequence: Hold down the CTRL and press the SPACE bar. This will produce the message: 130 not complete and line 130 will not be included in your program. If you make a mistake which does not cause a break from automatic numbering, you can continue and EDIT the line later.
  • Page 31 The following program sets borders, 8 pixels wide, in red (code 2), in three windows designated #0, #1, #2. 100 REMark Border 110 FOR k = 0 TO 2 : BORDER #k,8,2 You can save it on a microdrive by inserting a cartridge and typing: SAVE mdv1_bord The program will be saved in a Microdrive file called "bord".
  • Page 32 100 PRINT "First" 110 PRINT "Second" If you type: LOAD mdv1_prog1 followed by: MERGE mdv1_prog2 The two programs will be merged into one. To verify this, type LIST and you should see: 100 PRINT "First" 110 PRINT "Second" If you MERGE a program make sure that all its line numbers are different from the program already in main memory.
  • Page 33: Problems On Chapter

    PROBLEMS ON CHAPTER 5 1. Re-write the following program using lower case letters to give a better presentation. Add the words NEW and RUN. Use line numbers and the ENTER symbol just as you would to enter and run a program. Use REMark to give the program a name. LET TWO$ = "TWO"...
  • Page 34 CHAPTER 6 – ARRAYS AND FOR LOOPS WHAT IS AN ARRAY You know that numbers or character strings can become values of variables. You can picture this as numbers or words going into internal pigeon holes or houses. Suppose for example that four employees of a company are to be sent to a small village, perhaps because oil has been discovered.
  • Page 35 DIM high_st$(4, 3) ------ maximum length of string --------- number of string variables After the DIM statement has been executed the variables are available for use. It is as though the houses have been built but are still empty. The four 'houses' share a common name, high_st$, but each has its own number and each can hold up to three characters.
  • Page 36 This special type of loop, in which something has to be done a certain number of times, is well known. A special structure, called a FOR loop, has been invented for it. In such a loop the count from 1 to 4 is handled automatically.
  • Page 37 130 FOR number = 1 TO 4 : PRINT ! high_st$(number) ! 140 DATA "VAL", "HAL", "MEL", "DEL" Colons serve as end of statement symbols instead of ENTER and the ENTER symbols of lines 120 and 130 serve as END FOR statements. There is an even shorter way of writing the above program.
  • Page 38: Problems On Chapter

    think of the array, tally, as a set of pigeon-holes numbered 2 to 12. Each time a particular score occurs the tally of that score is increased by throwing a stone into the corresponding pigeon hole. In the second (short form) FOR loop, the subscript is number. As the value of number changes from 2 to 12 all the values of the tallies are printed.
  • Page 39 It does not matter if some of the four numbers are repeated. Use a second FOR loop to output the values of the five card variables. 2. Imagine that the four numbers 1,2,3,4 represent 'Hearts', 'Clubs', 'Diamonds', 'Spades'. What extra program lines would need to be inserted to get output in the form of these words instead of numbers? 3.
  • Page 40 CHAPTER 7 – SIMPLE PROCEDURES If you were to try to write computer programs to solve complex problems you might find it difficult to keep track of things. A methodical problem solver therefore divides a large or complex job into smaller sections or tasks, and then divides these tasks again into smaller tasks, and so on until each can be be easily tackled.
  • Page 41 Controlled cybernetic feedback Automated user-friendly transputers Synchronised parallel micro-chips Functional learning capability Optional adaptable programming Positive modular packages Balanced structured databases Integrated logic-oriented spreadsheets Coordinated file-oriented word-processors Sophisticated Standardised objectives ANALYSIS We will write a program to produce ten buzzword phrases. The stages of the program are: Store the words in three string arrays.
  • Page 42 DESIGN - PROGRAM 100 REMark ************ 110 REMark * Buzzword * 120 REMark ************ 130 DIM adjec1$(13,12), adjec2$(13,16), noun$(13,15) 140 store_data 150 FOR phrase = 1 TO 10 160 get_random 170 make_phrase 180 END FOR phrase 190 REMark ************************** 200 REMark * Procedure Definitions * 210 REMark ************************** 220 DEFine PROCedure store_data 230 REMark *** procedure to store the buzzword data ***...
  • Page 43 PASSING INFORMATION TO PROCEDURES Suppose we wish to draw squares of various sizes and various colours in various positions on the scale graphics screen. If we define a procedure, "square", to do this it will require four items of information: length of one side colour (colour code) position (across and up)
  • Page 44 Assuming that the procedure square is still present at line 200 then the following program will have the classical effect. 100 REMark Squares Pattern 110 PAPER 7 : CLS 120 FOR pair = 1 TO 20 INK RND(5) LET side = RND(10 TO 20) LET ac = RND(50) : up = RND(70) square side,ac,up LET ac=ac+side/5 : up = up+side/5...
  • Page 45: Problems On Chapter

    8. Some programs use more memory in defining procedures, but in what circumstances do procedures save memory space? 9. Name two ways by which information can be passed from main program to a procedure. (two points) 10. What is an actual parameter? 11.
  • Page 46 CHAPTER 8 – FROM BASIC TO SUPERBASIC If you are familiar with one of the earlier versions of BASIC you may find it possible to omit the first seven chapters and use this chapter instead as a bridge between what you know already and the remaining chapters.
  • Page 47 Most BASICs have numeric and string variables. As in other BASICs the distinguishing feature of a string variable name in SuperBASIC is the dollar sign on the end. Thus: numeric: count string: word$ high_st$ total day_of_week$ You may not have met such meaningful variable names before though some of the more recent BASICs do allow them.
  • Page 48 If the string cannot be converted then an error is reported. LOGICAL VARIABLES AND SIMPLE PROCEDURES There is one other type of variable in SuperBASIC, or rather the SuperBASIC system makes it seem so. Consider the SuperBASIC statement: IF windy THEN fly_kite In other BASICs you might write: IF w=1 THEN GOSUB 300 In this case w=1 is a condition or logical expression which is either true or false.
  • Page 49 are different and the LET helps to emphasise this. However if there are two or a few LET statements doing some simple job such as setting initial values, an exception may be made. For example: 100 LET first = 0 110 LET second = 0 120 LET third = 0 may be re-written as...
  • Page 50 SCREEN ORGANISATION When you switch on your QL the screen display is split into three areas called windows as shown below. Note that in order to fit these windows into the area covered by a television screen, some pixels around the border are not used in Television mode.
  • Page 51 The program below draws a green rectangle in 256 mode on red paper with a yellow border one pixel wide. The rectangle has its top left corner at pixel co-ordinates 100,100 (see QL Concepts). Its width is 80 units across (40 pixels) and its height is 20 units down (20 pixels).
  • Page 52 just separates - no formatting effect forces new line normally provides a space but not at the start of line. If an item will not fit at the end of a line it performs a new line operation. Allows tabulation to a designated column position. You will be familiar with two types of repetitive loop exemplified as follows: (a) Simulate 6 throws of an ordinary six-sided die 100 FOR throw = 1 TO 6...
  • Page 53 If you know other languages you may see that it will do the jobs of both REPEAT and WHILE structures and also cope with other more awkward, situations. The SuperBASIC REPeat loop is named so that a correct clear exit is made. The FOR loop, like all SuperBASIC structures, ends with END, and its name is given for reasons which will become clear later.
  • Page 54 FOR loop. The program below produces scores of two dice in each row until a seven occurs, instead of crosses. 100 REMark Dice rows 110 FOR row = 1 TO 4 120 PRINT 'Row number '! row 130 REPeat throws LET die1 = RND(1 TO 6) LET die2 = RND(1 TO 6) LET score = die1 + die2...
  • Page 55 150 END IF (ii) 100 REMark Long form IF...ELSE...END IF 110 LET sunny = RND(0 TO 1) 120 IF sunny THEN 130 PRINT 'Wear sunglasses' 140 PRINT 'Go for walk' 150 ELSE 160 PRINT 'Wear coat' 170 PRINT 'Go to cinema' 180 END IF The separator THEN, is optional in long forms or it can be replaced by a colon in short forms.
  • Page 56 The power and simplifying effects of procedures are more obvious as programs get larger. What procedures do as programs get larger is not so much make programming easier as prevent it from getting harder with increasing program size. The above example just illustrates the way they work in a simple context.
  • Page 58 CHAPTER 9 - DATA TYPES VARIABLES AND IDENTIFIERS You will have noticed that a program (a sequence of statements) usually gets some data to work on (input) and produces some kind of results (output). You will also have understood that there are internal arrangements for storing this data.
  • Page 59 The value of a floating point variable may be anything in the range: -615 +615 ± 10 to ± 10 with 8 significant figures. Suppose in the above program sales were, exceptionally only 3p. Change line 110 to: 110 LET sales = 0.03 This system will change this to: 110 LET sales = 3E-2 To interpret this, start with 3 or 3.0 and move the decimal point -2 places, i.e.
  • Page 60 The following examples show common uses of the INT function. 100 REMark Rounding 110 INPUT decimal 120 PRINT INT(decimal + 0.5) In the example you input a decimal fraction and the output is rounded. Thus 4.7 would become 5 but 4.3 would become 4.
  • Page 61 NUMERIC OPERATIONS SuperBASIC allows the usual mathematical operations. You may notice that they are like functions with exactly two operands each. It is also conventional in these cases to put an operand on each side of the symbol. Sometimes the operation is denoted by a familiar symbol such as + or *. Sometimes the operation is denoted by a keyword like DIV or MOD but there is no real difference.
  • Page 62 Basically numeric expressions in SuperBASIC are the same as those of mathematics but you must put the whole expression in the form of a sequence. becomes in SuperBASIC (or other BASIC): (5 + 3)/(6 - 4) In secondary school algebra there is an expression for one solution of a quadratic equation: + bx + c = 0 One solution in mathematical notation is: If we start with the equation:...
  • Page 63 210 IF suit = 1 THEN PRINT "clubs" 220 IF suit = 2 THEN PRINT "diamonds" 230 IF suit = 3 THEN PRINT "spades" There are new ideas in this program. They are in line 160. The meaning is clearly that the number is actually printed only if two logical statements are true.
  • Page 64 if the player is limited to a maximum of seven throws per game. if there is no maximum number of throws 2. Bill and Ben agree to gamble as follows. At a given signal each divides his money into two halves and passes one half to the other player.
  • Page 65 CHAPTER 10 – LOGIC If you have read previous chapters you will probably agree that repetition, decision making and breaking tasks into sub-tasks are major concepts in problem analysis, program design and encoding programs. Two of these concepts, repetition and decision making, need logical expressions such as those in the following program lines: IF score = 7 THEN EXIT throws IF suit = 3 THEN PRINT "spades"...
  • Page 66 Rules for AND In everyday life the word 'or' is used in two ways. We can illustrate the inclusive use of OR by thinking of a cricket captain looking for players. He might ask "Can you bat or bowl?" He would be pleased if a player could do just one thing well but he would also be pleased if someone could do both.
  • Page 67 NOT (red AND square) then for a red triangle the whole expression is true. There must be a rule in programming to make it clear what is meant. The rule is that NOT takes precedence over AND so the interpretation: (NOT red) AND square is the correct one This is the same as: NOT red AND square...
  • Page 68 rules for XOR PRIORITIES The order of priority for the logical operators is (highest first): OR,XOR For example the expression rich OR tall AND fair means the same as: rich OR (tall AND fair) The AND operation is performed first. To prove that the two logical expressions have identical effects run the following program: 100 REMark Priorities 110 PRINT "Enter three values"\"Type 1 for Yes and 0 for No"!
  • Page 69 CHAPTER 11 – HANDLING TEXT – STRINGS You have used string variables to store character strings and you know that the rules for manipulating string variables or string constants are not the same as those for numeric variables or numeric constants.
  • Page 70 You can see that the answer is defined by the numbers 6 to 9 which indicate where it is. You can abstract the answer as shown : 100 jumble$ = "APQOLLIONATSUZ" 110 LET an$ = jumble$(6 TO 9) 120 PRINT an$ REPLACE A STRING SLICE Now suppose that you wish to change the hidden animal into a bull.
  • Page 71 The problem now is that the value "56" of the variable, hist$ is a string of characters not numeric data. If you want to scale it up by multiplying by say 1.125, the value of hist$ must be converted to numeric data first, SuperBASIC will do this conversion automatically when we type: 120 LET num = 1 .125 * hist$ Line 120 converts the string "56"...
  • Page 72 130 INPUT "What is the animal?" ! an$ 140 IF an$ INSTR jumble$ AND an$(1) = "C" PRINT "Correct" 160 ELSE PRINT "Not correct" 180 END IF The operator INSTR, returns zero if the guess is incorrect. If the guess is correct INSTR returns the number which is the starting position of the string-slice, in this case 6.
  • Page 73 would give the output: WOOF We use the comparison symbols of mathematics for string comparisons. All the following logical statements expressions are both permissible and true. "ALF" < "BEN" "KIT" > "BEN" "KIT" <= "LEN" "KIT" >= "KIT" "PAT" >= "LEN" "LEN"...
  • Page 74 PROBLEMS ON CHAPTER 11 1. Place 12 letters, all different, in a string variable and another six letters in a second string variable. Search the first string for each of the six letters in turn saying in each case whether it is found or not found.
  • Page 75 CHAPTER 12 – SCREEN OUTPUT SuperBASIC has so extended the scope and variety of facilities for screen presentation that we describe the features in two sections: Simple Printing and Screen. The first section describes the output of ordinary text. Here we explain the minimal well established methods of displaying messages, text, or numerical output.
  • Page 76 However, by using various effects a variety of shades and textures can be achieved. If you are using your QL with an ordinary television set then the television set will not be able to reproduce any of these extra effects.
  • Page 77 512 pixels across numbered 0 to 511 256 pixels down numbered 0 to 255 4 colours COLOUR You can select a colour by using the following code in combination with suitable keywords such as PAPER, INK etc. Note that the numbers by themselves mean nothing. The numbers are only interpreted as colours when they are used with PAPER and INK, etc.
  • Page 78 180 END FOR colour If you wish to try different stipples you can add a third code number to the colour specification. For example: INK 2,4,1 would specify a red and green horizontal stripe effect. A block of four pixels would be: COLOUR PARAMETERS You can specify a colour/stipple effect as described above by using three numbers.
  • Page 79 PAPER PAPER followed by one, two or three numbers specifies the background. For example: PAPER 2 {red} PAPER 2,4 {red/green chequerboard} PAPER 2,4,1 {red/green horizontal stripes} The colour will not be visible until something else is done, for example, the screen is cleared by typing CLS.
  • Page 80 Suppose that we wish to create the file, numbers, on a cartridge in Microdrive 1. The device name is: mdv1_ and the appended information is just the name of the file: numbers So the complete file name is: mdv1_numbers CHANNELS It is possible for a program to use several files at once, but it is more convenient to refer to a file by an associated channel number This can be any integer in the range 0 to 15.
  • Page 81 You have seen one example of a device, a file of data on a Microdrive. We may say loosely that a file has been opened but strictly we mean that a device has been associated with a particular channel. Any further necessary information has also been provided. Certain devices have channels permanently associated with them by the system: Channel OUTPUT –...
  • Page 82 If you are using low resolution mode the QL will not allow you to select a character size smaller than default size.
  • Page 83 will give a red/green vertical striped strip. All the normal colour combinations are possible. OVER Normally printing occurs on the current paper colour. You can alter this by using strip. You can make further effects by using: OVER 1 1 prints in ink on a transparent strip OVER -1 -1 prints in ink over existing display on screen To revert to normal printing on current strip use:...
  • Page 84 RELATIVE MODE Pair of coordinates such as: across, up normally define a point relative to the origin 0,0 in the bottom left hand corner of a window (or elsewhere if you choose). It is sometimes more convenient to define points relative to the current cursor position.
  • Page 85 If you add two more parameters: e.g. CIRCLE 50,50,40,.5 You will get an ellipse. The keywords CIRCLE and ELLIPSE are interchangeable. The height of the ellipse is 40 as before but the horizontal 'radius' is now only 0.5 of the height. The number 0.5 is called the eccentricity.
  • Page 86 A straight angle is 180 degrees or PI radians, so you can make a pattern of ellipses with the program: 100 FOR rot = 0 TO 2*PI STEP PI/6 CIRCLE 50,50,40,0.5,rot 120 END FOR rot The order of the parameters for a circle or ellipse is: centre _across, centre_up, height [eccentricity, angle] The last two parameters are optional and this is indicated by putting them inside square brackets ([ ]).
  • Page 87 amount of curvature The first two items are straightforward but the amount of curvature is not so easy. You can do it by drawing accurately or by trial and error but you must decide what angle the arc subtends and then specify the angle in radians.
  • Page 88 SCROLL -8, 1 Will scroll the part above (not including) the cursor line and: SCROLL -8, 2 Will scroll the part below (not including) the cursor line. As scrolling occurs, the space left by movement of the display is filled with the current Paper colour. A second parameter 0 has no effect.
  • Page 89 CHAPTER 13 – ARRAYS Suppose you are a prison governor and you have a new prison block which is called the West Block. It is ready to receive 50 new prisoners. You need to know which prisoner (known by his number) is in which cell.
  • Page 90 This will output the values only: The zero at the top of the list appears because subscripts range from zero to the declared number. We will show later how useful the zero elements in arrays can be. Note also that when a numeric array is DIMensioned its elements are all given the value zero.
  • Page 91 The following program places the ten golfers in an array named flat$ and prints the names of the occupants with their 'flat numbers' (array subscripts) to prove that they are in residence. The occupants of flats 1 and 3 then change places. The list of occupants is then printed again to show that the exchange has occurred.
  • Page 92 Assuming DATA statements with 30 names, a suitable way to place the names in the flats is: 120 FOR floor = 0 TO 2 FOR num = 0 TO 9 READ flats$(floor,num) END FOR num 160 END FOR floor You also need a DIM statement: 20 DIM flat$(2,9,8) which shows that the first subscript can be from 0 to 2 (floor number) and the second subscript can be from 0 to 9 ( room number).
  • Page 93 ARRAY SLICING You may find this section hard to read though it is essentially the same concept as string slicing. You will probably need string-slicing if you get beyond the learning stage of programming. The need for array-slicing is much rarer and you may wish to omit this section particularly on a first reading. We now use the golfers' flats to illustrate the concept of array slicing.
  • Page 94 Represent a snakes and ladders game with a 100 element numeric array. Each element should contain either zero a number in the range 10 to 90 meaning that a player should transfer to that number by going 'up a ladder' or 'down a snake' the digits 1, 2, 3, etc.
  • Page 95 Set up six DATA statements each containing a surname, initials and a telephone number (dialling code and local number). Decide on a suitable structure of arrays to store this information and READ it into the arrays. PRINT the data using a separate FOR loop and explain how the input format (DATA), the internal format (arrays) and output format are not necessarily all the same.
  • Page 96 CHAPTER 14 – PROGRAM STRUCTURE In this chapter we go again over the ground of program structure : loops and decisions or selection. We have tried to present things in as simple a way as possible but SuperBASIC is designed to cope properly with the simple and the complex and all levels in between.
  • Page 97 Suppose that someone has secretly taken all the bullets out of the sheriff's gun. What happens if you simply change the 6 to 0 in each program? Program 1 100 REMark Western FOR Zero Case 110 FOR bullets = 1 to 0 PRINT"Take aim"...
  • Page 98 In addition the REPeat loop must normally have an EXIT amongst the statements or it will never end. Note also that the EXIT statement causes control to go to the statement which is immediately after the END of the loop. A NEXT statement may be placed in a loop.
  • Page 99 The program works properly as long as the sheriff has at least one bullet at the start. It fails if line 20 reads: 110 LET bullets = 0 You might think that the sheriff would be a fool to start an enterprise of this kind if he had no bullets at all, and you would be right.
  • Page 100 When we translate this into a program we are entitled not only to expect it to work but to know what it will do. It will plot a rectangle made up of rows of pixels. 100 REMark Rows of pixels 110 PAPER 0 : CLS 120 FOR up = 30 TO 80 FOR across = 20 TO 60...
  • Page 101 AII these are binary decisions. The first two examples are simple : either something happens or it does not. The third is a general binary decision with two distinct possible courses of action, both of which must be defined. You can omit THEN in the long forms if you wish. In the short form you can substitute : for THEN. EXAMPLE Consider a more complex example in which it seems natural to nest binary decisions.
  • Page 102 MULTIPLE DECISIONS - SELect Where there are three or more possible actions and none is dependant on a previous choice the natural structure to use is SELect which enables selection from any number of possibilities. EXAMPLE A magic snake grows without limit by adding a section to its front. Each section may be up to twenty units long and may be a new colour or it may remain the same.
  • Page 103 END SELect IF across < 1 OR across > 99 OR up < 1 OR up > 99 : EXIT snake POINT across,up END FOR unit 310 END REPeat snake 320 PRINT "Snake off edge" The syntax of the SELect ON structure also allows for the possibility of selecting on a list of values such as 5,6,8,10 TO 13 It is also possible to allow for an action to be executed if none of the stated values is found.
  • Page 104 Simulate the auction using the equivalent of a six-sided die throw to start the bidding. A 'six' at any of the starting prices will start it off. When the bidding has started there should be a three out of four chance of a higher bid at each invitation.
  • Page 105 CHAPTER 15 – PROCEDURES AND FUNCTIONS In the first part of this chapter we explain the more straightforward features of SuperBASIC's procedures and functions. We do this with very simple examples so that you can understand the working of each feature as it is described. Though the examples are simple and contrived you will appreciate that, once understood, the ideas can be applied in more complex situations where they really matter.
  • Page 106 In the main program actual parameters 3 and 4 are used. The procedure definition has a formal parameter num, which takes the value passed to it from the main program. Note that the formal parameters must be in brackets, but that actual parameters need not be. EXAMPLE Now suppose the working variable, "price", was also used in the main program, meaning something else, say the price of a glass of lager 70p.
  • Page 107 100 REMark LOCAL parameter 110 LET num = 70 120 item 3 130 item 4 140 PRINT ! num ! 150 DEFine PROCedure item(num) IF num <= 3 THEN LET price = 300 + 10*num IF num >= 4 THEN LET price = 12*num PRINT ! price ! 190 END DEFine Output...
  • Page 108 SQRT(9) computes the value, 3, which is the square root of 9. We say the function returns the value 3. A function, like a procedure, can have one or more parameters, but the distinguishing feature of a function is that it returns exactly one value. This means that you can use it in expressions that you already have.
  • Page 109 You do not want the mail order company to use your name and address or other information for other purposes. That would be an unwanted side-effect. Similarly you do not want a procedure to cause unplanned changes to values of variables used in the main program. Of course you could make sure that there are no double uses of variable names in a program.
  • Page 110 The main program should call procedures as necessary, get the total cost from procedure, waiter add 10% for a tip, and print the amount of the total bill. DESIGN This program illustrates parameter passing in a fairly complex way and we will explain the program step by step before putting it together.
  • Page 111 370 DEFine PROCedure compute(dish, total) LET total = 0 FOR k = 1 to 3 LET total = total + dish(k)*price(k) END FOR k 420 END DEFine The waiter also passes information to the cook who simply prints the number required for each menu item.
  • Page 112 490 DATA "Prawns",3.5,"Chicken",2.8,"Special",3.3 The output depends on the random choice of dishes but the following choice illustrates the pattern, and gives a sample of output. 3 Prawns 1 Chicken 2 Special Total cost is £20.40 COMMENT Obviously the use of procedures and parameters in such a simple program is necessary but imagine that each sub-task might be much more complex.
  • Page 113 Formal parameters do not have any type. You may prefer that a variable which handles numbers has the appearance of a numeric variable and which handles strings looks like a string variable, but however you write your parameters they are typeless. To prove it, try the following program. Program 100 REMark Number or word 110 waiter 2...
  • Page 114 1. Six employees are identified by their surnames only. Each employee has a particular pension fund rate expressed as a percentage. The following data represent the total salaries and pension fund rates of the six employees. Benson 13,800 6.25 Hanson 8,700 6.00 Johnson...
  • Page 115 27-39 are diamonds cards 40 52 are spades and you will know that 29 means that you have a "diamond". You can program the QL to do this with: LET suit = (card-1) DIV 13 This will produce a value in the range 0 to 3 which you can use to cause the appropriate suit to be printed.
  • Page 116 Ace of diamonds COMMENT Notice the use of DATA statements to hold a permanent file of data which the program always uses. The other data which changes each time the program runs is entered through an INPUT statement. If the input data was known before running the program it would be equally correct to use another READ and more DATA statements.
  • Page 117 150 END FOR num 160 CLOSE #6 Suppose that you wish to set up a simple file of names and telephone numbers. 678462 GEOFF 896487 249386 584621 482349 CATH 438975 WENDY 982387 The following program will do it. 100 REMark Phone numbers 110 OPEN NEW #6,mdv1_phone 120 FOR record = 1 TO 7 INPUT name$,num$...
  • Page 118 150 END FOR record 160 CLOSE #5 The data is printed, as before, but this time each pair of fields is held in the variable rec$ before being printed on the screen. You have the opportunity to manipulate it into any desired form. Note that more than one string variable may be used at the file creation stage with INPUT and PRINT but the whole record so created may be retrieved from the Microdrive file with a single string variable (rec$ in the above example).
  • Page 119 4. We now repeat the process but this time we are comparing green with magenta and we get: 5. Finally we move left again comparing green with blue. This time there is no need to move or change anything. We exit from the loop and place green in position 3. We are then ready to focus on the sixth item, cyan.
  • Page 120 red black blue magenta green cyan yellow white reveals the problem. We compare black with red and decrease p to the value, 1. We come round again and try to compare black with a variable colour$(p-1) which is colour$(0) which does not exist. This is a well-known problem in computing and the solution is to "post a sentinel"...
  • Page 121 3. Sort the array. 4. Pause to check that everything is in order 5. Delete file 'phone'. 6. Create new file 'phone'. This is all the program needs to do but the new file should be immediately checked using: COPY mdv1_phone TO scr Any further necessary checks should be carried out then: DELETE mdv2 phone COPY mdv1_phone TO mdv2_phone...
  • Page 122 The following procedure receives an array containing data to be sorted. The zero element will contain the number of items. Note that it does not matter whether the array is numeric or string. The principle of coercion will change string to numeric data if necessary. A second point of interest is that the array element, come(0), is used for two purposes: it carries the number of items to be sorted it is used to hold the item currently being placed.
  • Page 123 Since a substantial amount of character printing is involved it is best to start planning in terms of the pixel screen. You can see that you need to provide for twelve lines of characters with some space between lines and a total screen height of 256 pixels. It is useful to recall that the possible character heights are 10 pixels or 20 pixels.
  • Page 124 WINDOW 440 x 220 at 35,15 Green with black border of 10 units TABLE 100 x 60 at 150,60 Chequerboard stipple of red and green HANDS Room for at least eight card symbols Initial cursor positions are: north 150,10 east 260,60 south 150,130...
  • Page 125 ac,dn cursor position for characters current row for characters lin$ builds up row of characters highest card number points to card position current number of card PROCEDURES Shuffle shuffles 52 cards Split splits cards into four hands and calls sortem to sort each hand Sortem sorts 13 cards in ascending order Layout...
  • Page 126 REPeat compare IF comp >= sort(dart-1) : EXIT compare LET sort(dart) = sort(dart-1) LET dart = dart - 1 END REPeat compare LET sort(dart) = comp END FOR item 500 END DEFine 510 DEFine PROCedure layout PAPER #6,4 : CLS #6 BORDER #6,10,0 BLOCK #6,100,60,150,60,2,4 550 END DEFine...
  • Page 127 860 LET lin$ = lin$ & ch$ will correct this. The spaces between characters disappear but the larger sized characters enable the rows to be easily readable. The program thus works well in either graphics mode. CONCLUSION We have tried to show how you can use SuperBASIC to solve problems. We have shown how simple tasks can be performed in simple ways.
  • Page 128: Answers To Self Tests Answers To Self Test On Chapter

    17 - ANSWERS TO SELF TESTS ANSWERS TO SELF TEST ON CHAPTER 1 1. Use the BREAK sequence to abandon a running program because: a) something is wrong and you do not understand it b) it is longer of interest c) any other problem (three points) 2.
  • Page 129: Answers To Self Test On Chapter

    ANSWERS TO SELF TEST ON CHAPTER 2 1. An internal number store is like a pigeon hole which you can name and put numbers into. 2. A LET statement which uses a particular name for the first time will cause a pigeon hole to be created and named, for example LET count = 1 (1 point)
  • Page 130: Answers To Self Test On Chapter

    ANSWERS TO SELF TEST ON CHAPTER 3 1. A pixel is the smallest area of light that can be displayed on the screen. 2. There are 256 pixel positions across the low resolution mode. 3. There are 256 pixel positions from top to bottom in the low resolution mode. 4.
  • Page 131: Answers To Self Test On Chapter

    ANSWERS TO SELF TEST ON CHAPTER 4 1. A character string is a sequence of characters such as letters, digits or other symbols. 2. The term, 'character string', is often abbreviated to 'string'. 3. A string variable name always ends with $. 4.
  • Page 132: Answers To Self Test On Chapter

    5. The ENTER key must be used to enter a command or program line. 6. The word NEW will wipe out the previous SuperBASIC program in the QL and will ensure that a new program which you enter will not be merged with an old one.
  • Page 133: Answers To Self Test On Chapter

    ANSWERS TO SELF TEST ON CHAPTER 6 1. It is not easy to think of many different variable names for storing the data. If you can think of enough names, every one has to be written in a LET statement or a READ statement if you do not use arrays.
  • Page 134: Answers To Self Test On Chapter

    ANSWERS TO SELF TEST ON CHAPTER 7 1. We normally break down large or complex jobs into smaller tasks until they are small enough to be completed. 2. This principle can be applied in programming by breaking the total job down and writing a procedure for each task.
  • Page 135 Under 6 read chapter seven again. Take it slowly working all the programs. These ideas may not be easy but they are worth the effort. When you are ready, take the test again.

Table of Contents