Extended BASIC Versions 5 & 6 for Stand-alone Disc Systems and Network Stations Reference Manual PN 11006, Revision 2 Copyright © 1983 by Research Machines Limited. All rights reserved. Copies of this publication may be made by customers exclusively for their own use, but otherwise no part of it may be reproduced, transmitted, transcribed, stored in a retrieval system, or translated into any language or computer language without the prior written permission of Research Machines Ltd., Post Office Box 75, Oxford OX2 OBW, England. Tel. Oxford (0865) 249866. The policy of Research Machines Ltd is one of continuous development and improvement of its products and services, and the right is therefore reserved to revise this document or to make changes in the computer software it describes without notice. Research Machines endeavour to ensure that the products described perform correctly according to their descriptions. However, Research Machines Limited do not accept liability for the consequences of any error or omission. The original labelled distribution disc is regarded as the only proof of purchase and must be produced in order to qualify for an update at a reduced rate. Keep it safe and always work from copies. Additional copies of this publication may be ordered from Research Machines at the address above. Please ask for "Extended BASIC Versions 5 and 6 for Stand-alone Disc Systems and Network Stations, Reference Manual, PN 11006". If you would like to comment on any of our products or services please use the reply paid form provided at the end of this manual. RELEASE NOTE In order to keep it up to date, the Release Note is not bound in with the manual but is supplied both as a printed sheet and as file RELEASE.PRN on the Distribution disc (the disc version probably being in a condensed form). The Release Note contains details of the memory addresses used by BASIC together with information about any improvements and additions since the Manual was published. To display the Release Note on the screen, follow the instructions in Chapter 2 for loading BASIC but instead of typing "BASIC" in response to the "B>" prompt, type: TYPE RELEASE.PRN If you wish to print it as well as displaying it, select a printer option first, as described in Appendix D, and type (hold down the CTRL key while typing the letter P) prior to pressing . The text of this manual was produced with the aid of word-processing software on a Research Machines 380Z computer, and transmitted to The Hazell Press of Wembley for photo-typesetting in Century Schoolbook and OCR-B. CONTENTS Chapter 1 Introduction 1.1 Differences Between Extended BASIC Versions 5 & 6 1.1 Versions of CP/M 1.1 How to Use This Manual 1.1 Making a Working Disc 1.2 A Note About The Keyboard 1.2 A Note About The Display Screen 1.3 Chapter 2 Getting Started with BASIC 2.1 A First Look at the Print Instruction 2.2 Using Basic as a Calculator 2.3 The Importance of the Return Key 2.4 Correcting Keying Mistakes 2.4 Getting Started with Graphics 2.5 A Simple Program 2.6 Controlling Screen Output 2.7 Interrupting a program 2.8 Program Modification 2.8 Using a Printer 2.9 Saving and Loading Programs on Disc 2.10 Ending a Session 2.11 Some Common Problems 2.11 Chapter 3 Elements of BASIC 3.1 Format of Numbers 3.1 Literal Strings 3.2 Numeric Variables 3.2 String Variables 3.3 Array Variables 3.3 Storage Requirements 3.4 Use of Memory 3.5 Assignment of Values 3.5 Expressions 3.6 Form of a Basic Program 3.7 Internal Representation of Numbers 3.8 Chapter 4 General Purpose Utility Commands 4.1 AUTO 4.1 The "." form of line number 4.2 CONT 4.3 DELETE 4.3 COPY 4.3 DIR 4.4 ERASE 4.4 FSAVE 4.5 LIST 4.5 LLIST 4.5 LOAD 4.5 LOAD? 4.6 LOADGO 4.6 MERGE 4.7 MERGEGO 4.7 NEW 4.8 PRINTER 4.8 LOCAL PRINTER 4.8 NETWORK PRINTER 4.8 RENAME 4.9 RENUMBER 4.9 RESET 4.10 RUN 4.10 SAVE 4.11 Chapter 5 Editing 5.1 380Z Editing 5.1 EDIT 5.1 RETURN 5.2 ESC 5.2 nSPACE 5.2 A 5.2 nD 5.2 E 5.2 nFc 5.3 H 5.3 I 5.3 nKc 5.3 L 5.3 Q 5.3 nR 5.4 X 5.4 nDELT 5.4 480Z Editing 5.5 Line Editing 5.5 EDIT 5.6 Chapter 6 Data Transfer Commands 6.1 CLEAR 6.1 DATA 6.2 DIM 6.2 EXCHANGE 6.3 LET 6.3 READ 6.4 RESTORE 6.4 Chapter 7 Console and Printer I/O 7.1 INPUT 7.1 INPUT LINE 7.2 PRINT 7.3 LPRINT 7.4 SPC 7.4 TAB 7.4 POS 7.4 LPOS 7.5 WIDTH 7.5 LWIDTH 7.5 NULL 7.5 LNULL 7.5 USING 7.6 Chapter 8 Program Control and Structural Commands 8.1 Unconditional Transfer 8.1 GOTO 8.1 GOSUB 8.1 RETURN 8.1 Conditional Transfer 8.2 IF...THEN 8.2 ELSE 8.2 Selection 8.3 ON...GOTO 8.3 ON...GOSUB 8.4 Loop Control 8.4 FOR...TO...STEP 8.4 NEXT 8.4 Error Handling 8.6 ON ERROR 8.6 RESUME 8.6 ERR 8.6 Error codes 8.7 ERL 8.8 ERROR 8.8 Keyboard Interrupt Control 8.8 ON BREAK 8.8 Chapter 9 Numeric, String & User-defined Functions & Procedures 9.1 Numeric Functions 9.1 SIN 9.1 COS 9.1 TAN 9.1 ATN 9.2 SQR 9.2 EXP 9.2 INT 9.2 ABS 9.3 SGN 9.3 RND 9.3 MAX 9.4 MIN 9.4 MOD 9.4 XOR 9.5 Predefined Variables 9.6 PI 9.6 EE 9.6 String Functions 9.6 ASC 9.7 CHR$ 9.7 VAL 9.7 STR$ 9.8 LEN 9.8 LEFT$ 9.8 RIGHT$ 9.8 MID$ 9.8 HEX$ 9.9 INSTR 9.9 FIX$ 9.10 SPACE$ 9.10 STRING$ 9.11 Single-line User-Defined Functions 9.11 Multiline User-Defined Functions 9.13 Local and Global Variables 9.14 Functions Calling Functions 9.16 Multiline Function Definition 9.16 Further notes on Multiline Functions 9.17 User-Defined Procedures 9.18 Procedure Definition 9.20 Further Notes on Procedures 9.20 Using Strings as Arguments or Local Variables 9.22 Error Messages 9.22 Example Recursive Procedure 9.23 Example Multiline Functions and Procedure 9.24 Chapter 10 Miscellaneous Commands 10.1 STOP 10.1 END 10.1 BYE 10.1 REM 10.1 ' Comment 10.1 LVAR 10.2 LLVAR 10.2 TRACE 10.2 LTRACE 10.3 RANDOMIZE 10.3 KILL 10.3 PUT 27,... 10.3 Chapter 11 Low-Resolution Graphics 11.1 GRAPH 11.1 TEXT 11.2 PLOT 11.2 LINE 11.4 POINT 11.5 POINTS 11.5 ATTRIB 11.5 Example 11.5 Chapter 12 File Handling and Extended I/O 12.1 General File-Handling Commands 12.2 CLOSE 12.2 CLOSE INPUT 12.2 CREATE 12.3 LOOKUP 12.3 OPEN 12.3 Input and Output commands 12.4 INPUT # 12.4 INPUT LINE # 12.4 GET 12.5 GET$ 12.5 PRINT # 12.6 PUT 12.6 DIR 12.7 LIST 12.7 LVAR 12.7 TRACE 12.7 Input Control Commands 12.7 ON EOF 12.7 EOF 12.7 Output Control Commands 12.8 NULL 12.8 POS 12.8 QUOTE 12.8 WIDTH 12.9 Examples 12.9 Chapter 13 Multiple File Channels and Random Access Files 13.1 Multiple File Channels 13.1 CLEAR 13.1 ON EOF # 13.2 EOF # 13.2 CLOSE # 13.2 CLOSE INPUT # 13.2 Random Access Files 13.2 RANDOM Command 13.4 READ # Command 13.6 WRITE # Command 13.8 LOCK function 13.8 UNLOCK command 13.9 CLOSE for Random Access files 13.10 CLOSE INPUT for Random Access files 13.10 Random Access File Utility Functions 13.10 TYP 13.10 FPOS 13.11 FLEN 13.11 RLEN 13.12 RPOS 13.12 Sample programs 13.13 Chapter 14 Formatted Output 14.1 Format Characters 14.3 Numeric Format Items 14.4 i-Format Item 14.4 f-Format Item 14.4 Character Replacement 14.4 e-Format Item 14.5 Comma Insertion 14.6 Sign Insertion 14.6 Dollar Sign 14.6 Large Numeric Output 14.7 Formatted String Output 14.7 Literal Output 14.8 Repetition 14.8 Termination 14.8 Image 14.9 Errors 14.9 Chapter 15 Getting Started with High Resolution Graphics 15.1 Getting Started 15.2 Clearing the Screen 15.2 Setting the Resolution 15.3 Plotting Points and Lines 15.4 Range of XY Coordinates 15.5 Moving the Origin 15.5 Block Fill 15.6 The Intensity Argument 15.6 Pen Up Movement 15.8 Modifying the Displayed Intensity 15.8 Setting the Colour 15.10 Programming More Than One Picture 15.10 Using a Reduced Number of Bits/Pixel 15.11 Multiple Views in Medium Resolution 15.12 Clearing a View 15.13 Displaying More than one View 15.13 Sample programs 15.17 Chapter 16 HRG Routines - Reference Section 16.1 CLEAR 16.2 COLOUR 16.3 DISPLAY 16.5 FILL 16.6 GREAD 16.7 GWRITE 16.8 LINE 16.9 OFFSET 16.10 PLOT 16.11 RESOLUTION 16.12 SETCOL 16.13 UPDATE 16.14 VIEW 16.15 Chapter 17 HRG Level 2 Graphics 17.1 Introduction 17.1 CHARSIZE 17.3 COPY 17.4 DEFCHAR 17.5 DUMP 17.7 PATSIZE 17.9 PRINTER 17.13 RDOUT 17.14 SHADING 17.15 STPLOT 17.16 Example Programs 17.17 Excopy 17.17 Sine 17.17 Chapter 18 Machine and Assembly Language Support 18.1 Memory Layout 18.2 Where to Put Machine-Code Subroutines 18.3 Finding the Address Limits of Cache Memory 18.3 Function and Command Definitions 18.4 PEEK 18.4 POKE 18.4 INP 18.4 OUT 18.4 WAIT 18.4 VARADR 18.5 USR 18.7 CALL 18.8 Machine Language Routine Initialization 18.9 Adding and Saving Machine Language Routines 18.10 Other Useful Basepage Addresses 18.14 Examples 18.16 Appendix A Quick Reference Guide A.1 Commands and Functions A.1 HRG Calls A.4 HRG Calls (Level 2 only) A.4 Predefined Variables A.5 Operators A.5 Control Characters A.5 Appendix B Error Messages B.1 Appendix C Changes from Previous Versions C.1 Changes from DBAS9 C.1 Changes from Version 4 C.3 Changes from Version 5.0 A C.4 Differences Between Versions 5 & 6 C.5 Appendix D Selecting a Printer D.1 Setting up a Printer D.1 Examples D.2 Appendix E Colour Lookup Table E.1 High Resolution, 2 Bits/Pixel (HR2) E.1 High Resolution, 1 Bit/Pixel (HR1) E.1 Medium Resolution, 4 Bits/Pixel (MR4) E.1 Medium Resolution, 2 Bit/Pixel (MR2) E.2 Medium Resolution, 1 Bit/Pixel (MR1) E.2 Appendix F Escape Sequences F.1 Characteristic Features F.1 Errors in Escape Sequences F.1 Escape Sequences F.2 CHAPTER 1 INTRODUCTION This is a Reference Manual for Research Machines Extended BASIC, Versions 5 & 6, for both the network and stand-alone Computers. It is not a teaching manual and is not intended to teach you how to write good programs in the BASIC language. For this, one of the many text books on the market must be consulted. "Illustrating BASIC" by Donald Alcock, Cambridge University Press, 1977, is a concise, entertaining little book and may prove to be a good starting point. In addition "Computing Using BASIC" by Tonia Cope, Ellis Harwood, 81, is an excellent introduction to the use of BASIC on Research Machines computers. Although this manual contains many examples, these are intended only to clarify the items described in the text, and do not necessarily illustrate how they should be used in real programs. Information in this manual applies equally to Stand-alone disc systems and the 480Z when used as a network station except where otherwise stated. Differences Between Versions 5 and 6 of Extended BASIC The descriptions of those features of Extended BASIC Version 6 that are not implemented in Extended BASIC Version 5 are shown in this publication in half tone, and summarized in Appendix C. Versions of CP/M Both versions of BASIC described in this publication can be run on a stand-alone disc system running under the control of versions 1.4 or 2.2 of the CP/M operating system. Note, however, that the random-access file management facilities implemented in Extended BASIC Version 6 cannot be used when running under CP/M version 1.4. If you wish to use Random Access File facilities and do not have CP/M 2.2, then contact the sales office for details of upgrades. Both versions of BASIC can be used when running under CP/NOS on a network system. How to Use this Manual Chapter 2 is an introduction to BASIC for both network and stand-alone operation and is intended mainly for the new user. Its aim is to build up his or her confidence to the level that simple programs can be written, run, saved and reloaded from disc. In the course of this, some topics are covered that are of value to the more experienced user. Chapters 3 to 18 form the main work of reference. The various commands and keywords are arranged roughly according to function, commands with similar functions being grouped within each chapter. Depending on your inclination, you may prefer to read through these chapters from end to end, or merely refer to them as needed, using the contents list, index, and Quick Reference Guide. The Quick Reference Guide is in Appendix A and is also provided as a Reference Card. Appendix B is a list of error messages, with a brief explanation of each. Appendix C lists the differences between Extended BASIC Versions 5 and 6 and previous versions. Appendix D gives instructions on setting up a printer. Appendix E is a listing of the colour lookup table used by various of the high resolution graphics routines, and Appendix F describes "Escape Sequences" which provide means of controlling from within a program certain system parameters. Making a Working Disc Details of making working discs for network systems is given the Network Manager's Guide. For stand-alone systems the distribution disc on which you receive BASIC from Research Machines should not be used routinely. The programs on it should be copied to a working disc and the distribution disc put away in a safe place. You may need it if your working disc becomes damaged or lost, or, if an upgrade becomes available, to return to Research Machines as proof of purchase to qualify for a reduced price for the upgrade. The procedure for making a copy of the disc is outlined in the User Guide. There may be several versions of BASIC on the distribution disc. To conserve space on your working copy, especially on systems with 5-inch single-density discs where you will be supplied with two distribution discs, we suggest that you erase all but the version you need and that you rename that version as BASIC.COM. Refer to the Release Note for details of the various versions. The disc also contains a number of sample BASIC programs of varying complexity. A Note About the Keyboard The keyboard for your system is described in the User Guide. Some brief notes are included here to minimize any cross-referencing that maybe needed. However, from time to time the model of keyboard supplied with the 380Z or 480Z might change, so the User Guide should be consulted should the information given herein refer to a keyboard that differs from your own keyboard. Beginners should note that the computer keyboard differs from that of a typewriter in that there are three sets of characters - the normal lower case letters, the capital letters, (obtained by holding down while typing a letter), and the control characters, generated by holding down while pressing a letter or other character key. If you need to key in a quantity of text in upper case, a convenient way to do this without having to keep pressing is to press once. This causes the letter keys to generate upper case characters whilst the other keys generate the unshifted characters. Thus the key marked A generates capital A whilst the key marked with numeral 1 and the exclamation mark generates 1 when pressed alone, or ! when pressed with held down. Pressing again allows the letter keys to generate lower case characters. Some of the older Research Machines keyboards include two keys whose markings may prove confusing. may be marked with a pound sign but in fact it generates the hash or sharp symbol (#), used in association with file handling. On some keyboards, generates the rubout code and will delete one character, but in its non-shift mode it may appear to generate a hash while in fact generating an underscore. is used to signal the end of a line to the computer. is used only within the EDIT command. Some keyboards have marked , while on others actually generates this character. If you are unsure of your keyboard in this or any other respect, experiment. The other special keys may or may not be connected, depending on the model of the keyboard. is equivalent to and clears the screen while is equivalent to and suppresses output. repeats the last key pressed. is disabled and has no use, and , , and are ignored. The 480Z keyboard includes an additional set of special function keys on the right hand side of the keyboard. In BASIC these are mostly used for editing lines. The key on the 480Z keyboard stays down when pressed and is released by pressing it again. A Note About the Display Screen Some 380Z and 480Z systems have the ability to display text in either 40 or 80 character mode with the consequence that the number of characters per line on the screen can he changed. Where this difference may be significant is indicated within the text of the manual. Full details are given in the appropriate User Guide supplied with your system. CHAPTER 2 GETTING STARTED WITH BASIC This chapter is intended mainly for those meeting BASIC for the first time. It takes you on a short guided tour of some of the facilities of Research Machines Extended BASIC and is intended to be intelligible to those who have not yet learned the BASIC language. If you are such a person, we suggest that you work through this chapter step by step at the computer. You will then need to turn to one of the textbooks on BASIC programming which were mentioned in the previous chapter, using the rest of this manual for reference. Those already familiar with BASIC but who have not yet used it on the 380Z or 480Z computer may find it helpful to scan through this chapter. It introduces many aspects of this particular dialect of BASIC. More details will be found in the later chapters. For a network station, details of loading BASIC are given in the Network Station User's Guide. For a Stand-alone Disc System, switch on the computer or press the RESET button if it is already on. Insert a CP/M system disc in drive A and a BASIC disc in drive B, making sure that the discs are the right way up -- the user guide will tell you which way this is - and that the drive doors are properly closed. Press to start the operating system: the computer will display: Research Machines Release 1.1M 31K CPM vers 2.2 C A> or something very similar. Then select drive B. This is done by entering: B: in response to the "A>" prompt. Then enter the name of the BASIC interpreter followed by pressing If you followed the advice in chapter 1, this will be BASIC; otherwise, check in the Release Note, When BASIC has been loaded in, it prints a message on the screen, such as: RML Extended BASIC V5.0 L Copyright (C) 1982 by Research Machines Ready: "Ready:" means that BASIC is waiting for you to enter a BASIC program line or command. A FIRST LOOK AT THE PRINT INSTRUCTION Enter: PRINT "HELLO" The computer will display word HELLO on the next line, like this: HELLO Ready: If you make a mistake, such as misspelling the word PRINT, the computer displays the error message: Syntax error Ready: If you miss out the quotation marks, the computer will display a zero: 0 Ready: Notice that you can tell the difference between a capital letter O and the number 0 on the screen by their shapes. What you have just entered into the computer is called a BASIC statement. PRINT is an instruction to the computer telling it to display on the screen the characters between the quotes. You can enter up to 128 characters before pressing . If you try to enter more characters than this, the computer will ignore them. In the case of numbers, the number does not necessarily have to be enclosed in quotation marks. Enter the statement: PRINT "99" This instructs BASIC to print the number 99 on the next line, as expected. But if you enter: PRINT 99 the computer again displays the number like this: 99 Ready: Despite the missing quotation marks, the value is correct and there is no error message. In fact, BASIC will let you use the PRINT command for most numbers without enclosing them in quotation marks. Here are a few for you to try: 3 -5 3.14159 1001 .303 +1.5 As you can see, a number can have a decimal point and a plus or minus sign. USING BASIC AS A CALCULATOR Without further study, the computer can be used as a simple desk calculator. Try entering: PRINT 3+4 The answer, 7, appears on the next line. BASIC can perform five different elementary arithmetic operations: Addition Indicated by the usual plus sign (+). Subtraction Using the minus sign (-). The minus key on most keyboards is the one to the right of the number 0, shared with =. Multiplication Here an asterisk (*) must be used; there is no cross symbol on the keyboard. Also, multiplication is never implied by leaving out the multiplication symbol - where in mathematics we can write "ax", in BASIC we must enter "A*X". To find 12 times 9 enter: PRINT 12*9 Division Using the slash sign (/). To divide 108 by 12, enter: PRINT 108/12 Exponentiation It is often necessary to multiply a number by itself a given number of times. Instead of entering. PRINT 2*2*2*2*2 you can enter: PRINT 2^5 The upward pointing arrow is usually the key marked with a circumflex sign, to the right of the minus sign. Notice that you can use a number of arithmetic operations on the same line. For example, you can enter: PRINT 1+2+3+4 or PRINT 1-3+6 The exact rules for combining operations will be given in Chapter 3 but you can try some experiments now if you wish. THE IMPORTANCE OF THE RETURN KEY So far you have been pressing after every line without much thought. It is worth realising why this key is used so much. The reason is simple: without the computer does not know when you have finished an instruction. Suppose you started entering: PRINT 5+6 If the computer decided at this point that you had finished entering the statement and printed 11, it would not be very helpful if you had in fact planned to enter: PRINT 5+6+7+8 which gives a completely different answer. Since the computer cannot tell when you have finished, you must tell it. You do this by pressing . You always have to do this after entering an instruction. Pressing key should be a habit by now, if you have been doing all the examples. CORRECTING KEYING MISTAKES No one is a perfect typist. BASIC has two features that aid in correcting keying errors. The first is ; it acts rather like the backspace key on a typewriter and often saves you the effort of re-entering a whole line when you make a mistake. Suppose you have accidentally entered: PRINT "GOOD MORNIG" By pressing twice you rub out the last two characters (G"): PRINT "GOOD MORNI and you may correct the message. Each time you press the cursor moves one place to the left and the character it rubs out is lost. The second special key is which is entered by holding down the key marked CTRL while pressing U. The 380Z computer responds with ^U, and then begins a new line. The whole of the line you were entering before you entered is considered rubbed out. Thus, a second way of correcting the mistake in GOOD MORNING is: PRINT "GOOD MORNIG"^U PRINT "GOOD MORNING" GOOD MORNING Ready: Sometimes you will find that it is quicker to delete a whole line with and start again than to rub out most of it with . When is entered on the 480Z, the current line is deleted from the display screen and its cursor returns to the beginning of the line. Also on a 480Z, pressing key followed by the function key (on the righthand end of the keyboard) has the same effect. GETTING STARTED WITH GRAPHICS As well as characters, the computer can display dots. To use these, you need a way to describe what you want to display and where you want it. To specify where a dot goes, you divide the screen into columns. In 40-character mode, the screen is divided into 80 columns numbered from 0 to 79. In 80-character mode there are 160 columns numbered from 0 to 159. Column 0 is at the left and the numbers increase to the right. To simplify this introduction, it is assumed that you have a 40-character screen. The screen is also divided into 72 rows, numbered -12 to 59, starting at the bottom and increasing upwards. Your screen is probably now full of the commands and responses you produced earlier. To clear it and make it ready for graph plotting, enter the instruction: GRAPH When you use this instruction, the upper twenty lines of the screen are cleared to create a "graphics area" leaving four lines for text at the bottom. To display a dot in the middle of the graphics area (column 40, row 30), you enter: PLOT 40,30,2 The digit 2 indicates to BASIC that you want to display a white dot. You can change it to a grey dot, enter: PLOT 40,30,1 To rub out a dot at column 40, row 30, enter: PLOT 40,30,0 To put a dot in the lower right corner, you must specify column 79, row 0: PLOT 79,0,2 Notice that you specify the column first, as you do the X coordinate in graph plotting. Now try missing out the third number: PLOT 0,59 The brightness you last specified (white) has been remembered; a white dot is plotted in the top left corner of the screen. You have probably noticed that the last few instructions that you have entered have moved up the screen for four lines and then disappeared. To put things back as they were before you entered the GRAPH instruction, enter the instruction: TEXT This instruction moves the lines you enter up to occupy the whole screen. A SIMPLE PROGRAM So far, the PRINT and PLOT commands have been acted on immediately, as soon as was pressed. This way of using BASIC is called direct mode or immediate mode. It is also possible to hold a series of commands in the computer's memory and then execute them later. In this mode, the sequence of stored statements forms a BASIC program. The program can be executed once or many times, and can be later stored on a disc to be reloaded and executed at some time in the future. Clearly, program mode is far more useful than direct mode. To enter a number of lines of commands as part of a program, you must start each of them with a line number. To make sure the computer's memory is cleared, enter: NEW and then enter the statement: 10 PRINT 99 This time nothing happens except that the cursor moves to the beginning of the next line; the number 99 is not printed on the screen. Now enter RUN (followed by ): RUN 99 Ready: The RUN command causes the program currently being "looked at" by BASIC to be executed. To see the program on the screen, use the LIST command: LIST 10 PRINT 99 Ready: NEW, RUN and LIST are called utility commands. They are described in Chapter 4. Now try a more ambitious program: 10 LET X=0 20 LET X=X+1 30 PRINT X 40 GOTO 20 If you make a mistake while entering these lines, use or as described previously. When you have entered in the four statements, use LIST to make sure they are all correct. If you have made a mistake in one of them, you need only re-enter the whole line. BASIC holds the most recent version of a line with a given line number. Notice that you did not need to enter NEW before keying in this example as line 10 of the previous example was automatically replaced with the new line 10. Having checked that the program is correct, enter RUN. The program should print a sequence of numbers, starting from 1, the numbers being the current values taken by the variable X. A variable is the term used to refer to a place in the computer memory where a number is stored. In BASIC, variables are given names of one or two letters; they are described in more detail in Chapters 3 and 6. When you run this program, it is probable that it will pause after displaying the number 22 with the cursor blinking on the bottom line. If not, press . CONTROLLING SCREEN OUTPUT We assume that you have run the previous example and that the cursor is blinking at the bottom of the screen. This demonstrates the auto-paging function of the computer. After the LIST command has been used for a long program, output to the screen pauses as soon as the screen has been filled. To see the next lines in the program press the space bar. Try this a few times. Auto-paging is turned on and off by , which acts like a switch. Press once and observe that BASIC no longer pauses at the end of each page. Press again to resume auto-paging. There is another way of stopping output to the screen which is useful when you want to stop output at a specific point. Turn off auto-paging, then press to stop output. Note that pressing the space bar no longer causes output to resume; instead you must press . and do not alter the auto-paging switch. INTERRUPTING A PROGRAM It will probably be evident by now that if we did nothing, the example program would continue printing a series of increasing numbers for ever, or very nearly so. There is a need for a method of interrupting a running program without having to press the RESET button. Press to achieve this. Try it, and observe that BASIC displays: Interrupted at line n Ready: where "n" is the number of the line that was about to be executed when was pressed. The keyboard is checked for at the beginning of every statement. This means that a BASIC program can be interrupted at any time. If necessary, an interrupted program can be resumed by entering: CONT This continues execution from the point of interruption. Try this, and then interrupt the program again with . PROGRAM MODIFICATION The program example is clearly rather unmanageable. We would rather it stopped after printing a defined number of values of X. To make sure that the program is interrupted, enter the additional statement: 25 IF X>15 THEN STOP Although we have not yet met the IF command, the meaning of this statement should be fairly clear. This addition illustrates a number of points. Enter LIST and observe that although line 25 was the most recently typed, BASIC has inserted it in the correct place, between lines 20 and 30. Gaps of 10 were left in the original numbering of the program lines, just in case we needed to add an additional line. It is common practice to number BASIC statements in increments of 10. The numbering may be tidied up at any time by the RENUMBER command. See Chapter 4 for more details. We have now modified the program by adding an additional statement. It can no longer be continued by the CONT command, Try out the modified program and make sure that it stops after the number 15 has been displayed. USING A PRINTER You should skip this section if you do not have a printer attached to your computer. Once a program is working correctly, it is usually desirable to make a permanent record of it and of its output on a printer. If using BASIC on a stand-alone system it is first necessary to select a printer option. The computer supports various types of printer and the user must inform the computer which type is attached. If no printer option is selected, output intended for the printer is sent to the screen. A number of ways of selecting a printer option are available. Connecting and setting up a printer on a new system can be difficult, particularly if the printer was not purchased through Research Machines. Beginners are therefore advised to leave this until they are more familiar with the rest of the system. If the equipment is already operational, refer to chapter 4 and appendix D for setting printer options. Once a printer option has been selected, the LLIST command can be used. LLIST is similar to LIST but its output goes to the printer rather than the screen. Similarly, PRINT statements can be replaced by LPRINT, with similar effect. An alternative and often more convenient method is to press . After , all output to the screen is also sent to the printer, until is next entered. Thus, a program can be tested with its output sent to the screen and then run again without modification, merely by entering to produce a fair copy on the printer. is equivalent to . If you have a printer connected to your system, test these new commands on the modified program. If you are using a network system your output will be sent to a file on the network server, and printed only after you indicate that a suitable quantity has been produced. You do this by issuing the command CLOSE #2. See Network Users Guide for further details. SAVING AND LOADING PROGRAMS ON DISC Now that you have a working program, you may want to save it on disc so that it can be run on another occasion without the effort of keying it in again. The SAVE command is used. Assuming that you would like to call the program TEST1, enter: SAVE "TEST1" Ready: On a stand-alone disc system the light on one of the disc units will come on for a few seconds before "Ready:" is displayed. On a network system the light on one of the disc units attached to the Network Server will come on for a few seconds before "Ready:" is displayed. You can confirm that the program has been saved by using the DIR command: DIR B: TEST1 BAS Ready: The letter before the colon is the logical disc unit containing the disc on which the program has been saved. BAS is the extension of the filename (secondary filename) which is given automatically by BASIC if none is supplied. Saved programs are reloaded by the LOAD command. Before trying LOAD, delete the existing program from memory by using the NEW command and confirm that you have done so by using the LIST command. It is not necessary to do this as BASIC automatically deletes existing programs from memory before loading a program, but doing so at this stage will help to confirm that you can save and reload programs correctly. Having cleared memory, reload TEST1 by entering: LOAD "TEST1" Ready: Again the disc unit light will come on and there will be a short pause before BASIC displays "Ready:". You can now confirm that TEST1 has been reloaded by using the LIST or RUN commands. ENDING A SESSION At the end of a BASIC session, after any new programs have been safely saved on disc, you will want to leave BASIC. In fact all you need do on a stand-alone system is to take your discs out of the disc drives and turn the computer off. However, you may wish to return to the CP/M Operating System (CP/NOS for the network user) to use one of the other system programs. In this case you either enter or the BYE command. Because can be used accidentally, the warning message: ^C--Are you sure (Y/N): is displayed. Enter Y or y to leave BASIC or N to continue using BASIC. SOME COMMON PROBLEMS This section refers to stand-alone disc systems. Two problems can arise whilst saving programs in Extended BASIC, neither of which is dealt with in a particularly elegant manner at present. On a stand-alone disc system you may decide that you wish to save the current BASIC program on a different disc. You change the disc, then issue the SAVE command. Instead of saving the program, the system displays an error message such as: BDOS ERROR ON A: R/O If you press any key except , you might lose your program. Refer to the descriptions of the RESET and SAVE commands in Chapter 4 for the recovery procedure. Remember always to issue the RESET command after changing a disc. Alternatively, all is going well during a SAVE operation until a message such as: A 00 15 0A 31F0 BDOS ERROR ON A: BAD SECTOR appears. This sort of message means that there is an unreadable sector on the disc. Probably the safest thing to do is to remove that disc for later investigation, replace it with another disc and enter , followed by J>103. This restarts BASIC at its recovery address. Your program should be intact. Now issue the RESET command because you have changed discs) and try the SAVE command again. If problems arise when saving Extended BASIC programs on the network, refer to Appendix B, and if the error is not described there, refer to the Network Station Users Guide for details of system error messages. CHAPTER 3 ELEMENTS OF BASIC This chapter discusses some of the elements from which a BASIC program is constructed. Some knowledge of the BASIC language is assumed, so it is probably best to skim through this chapter on the first reading and then study it more carefully after reading some of the later chapters in this manual. FORMAT OF NUMBERS When a number is supplied to BASIC from the keyboard, either as a constant that forms part of a program or in response to an INPUT instruction, it may take a variety of forms. For example: 3 -5 3.14159 1001 .303 +1.5 As can be seen, a number may consist of an integer part (before the decimal point) and a fractional part (after the decimal point), either of which may be omitted, and may be preceded by a plus or minus sign. If no sign is supplied, the number is assumed to be positive. BASIC displays or prints numbers in a similar form. If the number is positive, it is preceded by a space, and by a minus sign if it is negative. Numbers larger than 999999 or smaller than 0.01 are printed in scientific (or "exponential") notation. For example, the number 1234567 is printed: 1.23457E+06 This number should be read as "1.23457 times 10 to the power 6". Similarly, the value 0.0001 is printed: 1E-04 meaning "1.0 times 10 to the power minus 4". Numbers may be input to BASIC in normal or scientific notation. In scientific notation, lower case "e" is also recognized as indicating an exponent. The change in format for large or small numbers applies only on output. In Extended BASIC version 6, the format of numbers can be changed by use of the USING command (see chapter 14). Numbers are stored to a precision of approximately 6 significant digits. The range of values allowed is approximately -1E38 to 1E38, with values whose magnitudes are less than approximately 1E-38 being indistinguishable from zero. Checks are made for meaningless exponents in numerical constants. Very large positive exponents cause arithmetic overflow while large negative exponents generate zero. A number may also be supplied in hexadecimal, in which case it is preceded by an ampersand (&) and consists of a sequence of hexadecimal digits (0-9, A-F). For example: &1A &0D &FC00 The value of the constant must lie within the range 0 to &FFFF. LITERAL STRINGS A "literal string" is a sequence of characters enclosed in quotation marks ("). The characters must not include a quotation mark but may include any other printable character. In a DATA statement, the quotation marks are optional if the string does not contain commas, colons, or leading spaces. NUMERIC VARIABLES "Variable" is the term used to refer to a named entity whose value can change during execution of a program. A numeric variable holds a numeric value that may change during execution of a program. A variable name must begin with an alphabetic character (A to Z). This allows the computer to distinguish it from numeric constants (which always start with a number). After the first letter, the variable name may consist of any alphanumeric character (A to Z, 0 to 9). Examples of variable names are: B B3 ZP X Y5 To improve program readability, you can use variable names that are meaningful, such as: SUM MEAN AVERAGE Only the first two characters are used to distinguish one variable name from another. Thus the names COUNT and COCOA refer to the same variable. CAUTION: variable names must not contain embedded BASIC instruction names. For example, the variable name LONG would give rise to a syntax error since it contains the BASIC instruction ON. Furthermore, since Extended BASIC Version 6 supports more instructions than Version 5 (such as MIN, MAX, TYP), it is possible that programs that run under Version 5 will fail under Version 6 unless certain variables are renamed. STRING VARIABLES All the variable names described in the previous section are used to hold numeric values that are to be used in calculations. A variable may also hold a string of alphabetic, numeric, or special characters, such as "HELLO" "100,57", or "25%"; these variables are called string variables. A string variable name has a dollar sign ($) appended. For example: A$ B9$ MESSAGE$ Note that the last example would be indistinguishable from ME$. A string variable may hold from 1 to 255 characters, or it may be empty. An empty string variable is said to contain the null string. It is not possible to use string variables in arithmetic operations to calculate new values. ARRAY VARIABLES The numeric and string variables described above are referred to as simple variables, since each can hold only one numeric value or one string of characters. A numeric or string array can hold a series of numeric values or strings. An array variable is a member of such an array and has the form of a simple variable name followed by a list of subscripts enclosed by parentheses. Each subscript is a number or an arithmetic expression that evaluates to a number in the range 0 to 65535. There can be any number of subscripts, up to a limit of 255. Smaller limits will in practice be imposed by the amount of available memory. Examples of array variables are: B(2) B3$(4) SUM(5,3) MESSAGE$(10) If there is a single subscript, as in the first example, the array variable can be thought of as a member of a single row of simple variables. Thus B(2) is a member of the array B(0), B(1)...B(n). Similarly, array elements with more than one subscript form part of a matrix containing two or more rows of variables. The number of rows in an array and the number of elements in each should be established by a DIM statement before referring to one of its elements (see Chapter 6). Thus the statement: DIM B(20) defines numeric array B to have one row containing 21 elements numbered 0 to 20. If an element of an array is referred to before the array has been defined by a DIM statement, BASIC creates it automatically with as many dimensions as there are subscripts and with eleven elements in each dimension (allowing subscripts in the range 0 to 10). If any subscript value exceeds the number of elements defined for its row, the error message: Subscript out of range results. A simple variable can have the same name as a subscripted variable without confusion (by the BASIC interpreter, at least). Note that a subscripted string variable represents an element of a string array, and is itself a complete string. A simple string must not be defined with a DIM statement to reserve storage for the characters in it, as is the case with many other BASICs. STORAGE REQUIREMENTS A simple numeric variable occupies six bytes of storage, the first two holding the name and the last four holding the internal representation of the number (see below). A string variable also occupies six bytes, again using two bytes for the name and four for the internal representation of the string, In addition to these six bytes, one byte of memory is required for each character in the string. These bytes may be located in the program itself, for example after statements such as: 100 LET A$="HI THERE" or in "string space", described below. A numeric array element occupies just the four bytes necessary to hold the internal representation of the number. The entire array occupies five bytes plus two bytes per dimension plus the four bytes per element. String arrays require the same amount of storage as numeric arrays, plus space to store the actual strings. String space is an area at the top of memory which is used for storing the characters held in strings. The size of string space is fixed by the CLEAR command (see Chapter 6), or 100 bytes by default. Where possible, literal strings occurring within the program are used in place, to reduce storage requirements. When string space becomes exhausted, a "garbage collector" is used to recover the space released when strings are reassigned. This process can cause an observable delay of up to a few seconds or so. If there is still insufficient space the error message: No string space is produced. USE OF MEMORY Extended BASIC Version 5 uses the first 13K bytes or so of memory for the interpreter itself and some workspace. The Extended BASIC Version 6 interpreter is about 20K long. Above this come in turn the program, the simple variables, and the arrays. Next is a gap (of a size determinable by the function FRE) which is unused. Above the empty space is the stack, which is used to store return addresses for GOSUB statements and information about FOR loops, etc. Above the stack is the string space, the area used for storing the characters held in strings. At the top of memory is "cache", an area that BASIC does not use at all and that is set to a size of zero bytes when BASIC is started. Cache memory is intended for use with machine language routines, especially the routines GLOAD and GSAVE used in the High Resolution Graphics package. See also Chapter 13. ASSIGNMENT OF VALUES During the execution of a BASIC program, values can be stored in either numeric or string variables by means of the LET instruction. Examples are: LET A=2 LET M$="HALLO" LET B(5)=3.14159 This process is referred to as assigning a value to a variable. Many different values may be assigned to a variable during the course of a program. The LET command is described in Chapter 6. Extended BASIC automatically assigns the value zero to numeric variables and a null string value to string variables on their first occurrence in a program. Thus, if variable C has not yet been used in a program, the statement: LET A=C assigns zero to A. However, it is a dangerous programming practice to assume that this will occur, for not all dialects of BASIC used on other computer systems work the same way. You are urged to assign values to all variables before using them. Note that a statement of the form: LET M$="" assigns a null string to a string variable. Extended BASIC Version 6 assigns non-zero values by default to certain variables. See chapter 9. EXPRESSIONS In addition to consisting of a numeric or string constant, the right hand side of a LET statement, and indeed most other places where such a constant can occur, can consist of an expression. An expression is composed of operators and operands, which must alternate and end with an operand. An operand is either a constant, a variable, a function call, or an expression enclosed within parentheses. An operator is an arithmetic operator, a relational operator, a logical operator, or the string concatenation operator. Examples of arithmetic operators are LET A=B+2 addition LET C=D-5 subtraction LET P = 5*1.5 multiplication LET X=100/3 division LET E=2^3 exponentiation Relational operators are usually used in conditional statements of the form: IF A>3 THEN PRINT "A GREATER THAN 3" The IF instruction and the available relational operators are described in chapter 8. Relational operators can be applied to either numeric or string operands, but the operands must be of the same type. The relationship between two strings is decided by the ASCII value of the first pair of differing characters starting from the left. Thus "APPLE" is considered to have an ASCII value that is less than that of "AXIOM". The logical operators AND, OR, and NOT are normally used to decide the truth or otherwise of a series of relationships, such as in the statement: IF A>3 AND B=2 THEN ... where the AND operator combines the results of the two relational operators. However, the mechanism used is to combine the values of the operands, expressed as 16-bit binary values, with a non-zero result being regarded as "true" and a zero result as "false". Thus you can write statements, such as: IF A AND 1 THEN PRINT "A IS ODD" The effect of the AND operator is to perform a logical AND operation on the corresponding bits of its operands, in this case A and 1. The result of this operation is either 0 or 1 depending on whether A is even or odd. 0 is false, and 1 is treated as true. Relational operators can be used as part of non-relational expressions. A true result is returned as -1, and false as zero. For example, the following statement adds one to the variable B if A is negative: LET B=B-(A<0) The string concatenation operator is the plus sign (+). It is used to join one string to another. For example, the statement: PRINT "ROSE" + " " + "BUSH" joins three strings to print: ROSE BUSH The order of priority of the operators is: + String concatenation ^ Exponentiation - Unary minus * / Multiplication Division MOD Modulo arithmetic + - Addition Subtraction MIN Minimum Value MAX Maximum Value < <= > >= = <> Relations NOT Logical NOT AND Logical AND OR Logical OR XOR Logical XOR with the highest priority operators in an expression evaluated first. Operators of equal precedence are evaluated from left to right as given in an expression. These rules of operator priority may be modified when necessary by parentheses. Expressions in parentheses are evaluated first. Thus: LET A=3+4*5 assigns 23 to A, while: LET B=(3+4)*5 assigns 35 to B. For the description of functions MIN, MAX, MOD and XOR see Chapter 9. FORM OF A BASIC PROGRAM A BASIC program is made up of lines, each of which consists of a line number and one or more statements. The line number is a number between 1 and 65529. Note that line 0 is not permitted. It is normal to have one statement on each line. However, when space is short it is permissible to put more than one statement on a line, the statements being separated by colons (:) as in line 20 below: 10 LET A=3 20 LET B=4 :LET C=5 There can be as many statements on a line as will fit, the length of a line being limited to 128 characters. Spaces may be included freely to improve readability but in this version of BASIC their use is not required. The last example could be keyed in as: 20LETB=4:LETC=5 but is much more difficult to read than when spaces are used. Spaces are not allowed within the names of BASIC keywords. BASIC statement lines can be added to a program in in any order. BASIC rearranges them internally into ascending line number order. When a program is executed, the statements are executed in ascending line number order unless control is transferred to another line number by a statement such as GOTO. Only the most recent version of a line with a particular line number is retained. Entering a line number of a line already present in a program followed immediately by causes that line to be deleted, including its number. INTERNAL REPRESENTATION OF NUMBERS Numeric constants and the values of numeric variables are input and output by BASIC in decimal form and are held internally in a special binary floating-point (exponential) format. In Extended BASIC, 24 bits are assigned to the binary fraction and its sign, and 8 bits to the sign and magnitude of the binary exponent. This form is similar to the "scientific" format in which BASIC prints large and small numbers, except that the fraction always lies between a half and one and is raised to a power of two rather than ten. Futher details are given in the description of the VARADR command in chapter 18. The format allows a precision of somewhat better than 6 significant decimal places; when converted back to the decimal system, numbers are output to 6 significant figures with the last figure rounded. Thus the fraction 2/3 (two-thirds) is represented as 0.666667. As mentioned above, the range of numbers that can be represented is approximately 1E+38 to 1E-38. Numbers less than the lower limit are rounded down to zero whilst numbers greater than the upper limit result in the error message: Arithmetic overflow and cause program execution to stop. This form of representation can sometimes give unexpected results. Although such results are not usually a problem in day to day work, the programmer should be aware of the possibility of an apparently erroneous result occurring. The following examples illustrate what can happen. Some numbers, although they can be represented exactly in the decimal system, cannot be held exactly in the computer. The fraction 1/10 is an example. In decimal this is 0.1 and you know that if you multiply it by 1000, the result win be 100. This is also true in the computer. The program: 10 LET T=1/10 20 PRINT T*1000 prints 100. You also know that if you were to add 0.1 to itself a thousand times you would still get the result 100. But this is not so in BASIC. The program: 10 LET T=1/10 20 LET S=0 30 FOR I=1 TO 1000 40 LET S=S+T 50 NEXT 60 PRINT S prints 99.9991 instead of 100. What has gone wrong? The answer lies in the fact that the fraction 1/10 cannot be held exactly. When we multiplied it by 1000, BASIC's automatic rounding mechanism took care of the slight residual error and gave the correct result. But when you added in the slightly incorrect value of T a thousand times, you compounded the error a thousand fold; automatic rounding was insufficient to compensate. In a program you might need all the intermediate values of S. If so, a solution is to recalculate S each time through the loop, so that each intermediate value of S contains only one error. For example: 10 FOR 1=1 TO 1000 20 LET S=I*0.1 30 NEXT I 40 PRINT S The PRINT statement in line 40 shows that the final value of S is now correct. The problem can be summed up as an error due to the accumulation of many smaller errors. It can occur in the majority of implementations of computer languages, particularly on mini and microcomputers. The second example is less obvious. Several of the operations in BASIC convert numbers from their internal binary floating-point form to an exact whole number before use, a particular example being the evaluation of array subscripts. In Extended BASIC, as in the majority of dialects of BASIC, this is done by truncation rather than by rounding. Thus A(2.5) refers to A(2), not A(3). The situation is made more confusing by the fact, already mentioned, that the PRINT instruction carries out slight rounding. It is thus possible for a variable to have one value when printed and another when used as an array subscript, the second value being one less than the first, as the following example shows: 10 LET T=1/10 20 LET S=0 30 FOR I=1 TO 30 40 LET S=S+T 50 NEXT I 60 PRINT S When printed, S is 3 70 DIM A(3) 80 LET A(2)=2 90 LET A(3)=3 100 PRINT A(S) But this prints 2! The internal value of S is in fact fractionally less than 3; when printed it is rounded up to 3, but when truncated to a whole number yields 2. Fortunately the problem is rare, tending to happen only with very large numbers and with smaller numbers when there have been many intermediate calculations, as in this case. A simple solution is to force rounding rather than truncation to take place by adding 0.1 to the subscript. Changing line 100 to: 100 PRINT A(S+0.1) prints 3, as expected. Users may be reassured to know that Extended BASIC follows Dartmouth BASIC in using truncation to evaluate array subscripts. The problem is not confined to the 380Z and 480Z computers. CHAPTER 4 GENERAL PURPOSE UTILITY COMMANDS In response to the "Ready:" prompt, the user can enter a command either with a line number (program mode) or without a line number (immediate or direct mode). In program mode, the user enters a sequence of BASIC command lines, each prefixed with a unique line number, and when all requisite lines have been entered, the program can be run (executed) by entering RUN . In immediate mode, a command is entered without a line number prefix and is executed as soon as is pressed. Most of the commands in this section are normally used without line numbers, in direct mode. However, some commands, ERASE and RENAME for example, are often used within programs. Commands which are only available with Extended BASIC Version 6 are shown in half tone. Several of the commands described in this section require a file specification, which may be supplied within quotation marks, or in a string variable or expression. Examples are: LOAD "CIRCLES" ERASE F$ The file specification comprises a filename of up to 8 characters drawn from the character sets A-Z, a-z, 0-9 and $. Lower case letters are converted to the corresponding upper case letters. The filename may optionally be preceded by the name of the disc drive containing the disc onto which the file is to be written followed by a colon, as in the following example: SAVE "B:GRAPH" If the disc drive name is omitted, the drive used when BASIC was loaded is assumed. A three-character extension to the filename (secondary filename) may be supplied, preceded by a full stop. If omitted, .BAS is assumed. In addition, the output of commands such as LIST and DIR can be redirected to the printer or to a file. The mechanism for doing this is described in Chapter 12. AUTO AUTO AUTO 5,15 AUTO ,20 AUTO 100 Each line of a BASIC program must be preceded by a line number. The AUTO command provides a method of generating line numbers automatically. Once an AUTO command has been entered, a new line number appears on the screen each time is pressed. The sequence of line numbers required may be defined by the user. If the user enters AUTO without a numeric value, the first line number to appear will be 10 and the value of each subsequent line number generated will be incremented by 10. The user may choose an alternative initial line number and/or incremental value by specifying the required values within the AUTO command. The command AUTO 5,15 will generate the sequence of line numbers: 5 20 35 50 .... The command AUTO ,20 generates the sequence 10 30 50 70 .... An incremental value of 10 is assumed when the AUTO command does not specify an incremental value. Thus the command AUTO 100 generates the sequence 100 110 120 130 .... To warn the user that a line number generated by the AUTO command is the same as a line number that currently exists in the program, a + (plus sign) is prefixed to it. If the user does not wish to overwrite the existing line, it is necessary to press to generate the next line number in the sequence without deleting the existing line. Any line number in the range 1 to 65529 is valid. Exceeding this range causes the error message "Arithmetic Overflow" to be displayed. The AUTO command is terminated by pressing , which also has the effect of cancelling the line currently being entered. The AUTO command must be terminated, for example, before entering the RUN command in order to execute the program. The "." form of line number In direct mode commands, a period (".") can be substituted anywhere that a line number is normally used. The period represents the last line accessed by a program editing or execution command. For example, to correct an erroneously-entered line that has just been entered, use the EDIT command with the period: 10 A$=MID$(B$,5,6 EDIT. 10 In response to the immediate command EDIT, the line most recently referred to is copied into the edit buffer ready for correction by the user, as described in chapter 5. After an execution error, the period is set to the number of the line on which the error occurred, so that the erroneous line may be listed by the command: LIST. Note that an attempt to substitute "." for a line number in program mode produces the error message "Undefined Statement". CONT CONT CONTINUE After pressing , or after a program has executed a STOP or END instruction, the message: Interrupted is displayed. You may resume execution by entering CONT. While the program is stopped, PRINT, LVAR or LET may be used to display or change the values of variables. CONT cannot be used after program modification or a runtime error. DELETE DELETE 25 DELETE 25-75 DELETE 25- DELETE -75 These commands cause the deletion of lines 25, 25 to 75, 25 to the end, and lines up to line 75 respectively. COPY 10 COPY 170,15=40-60 Any group of program lines from one part of a BASIC program can be copied to another specified part of the program by means of the COPY command. The form of the COPY command is: COPY n1[,n2] = n3-n4 The right hand side of the "=" sign specifies the range of line numbers to be copied (i.e. n3 and n4 are the first and last line numbers of the group of lines to be copied). The left hand side of the "=" sign indicates where the copied lines are to be placed in the program and, optionally, the increment to be used for the line numbers of the copied lines. If no increment is specified, an increment of 10 is assumed by the COPY command. The group of program lines are copied in the same format as produced by the LIST command. Before lines are copied the new line numbers are validated to ensure that they do not fall within the range of line numbers being copied. If such overlapping of line number values occurs, the error message "Illegal Function" is displayed. Any references to other line numbers displayed within the block of lines to be copied (e.g. within GOTO statements) are not renumbered by the COPY command. Example: 10 I=I+1 20 IF I=10 THEN 50 30 PRINT I 40 GOTO 10 50 END To copy lines 10 to 40 of the original program to line 200 onwards of a new program (and to use a line increment of 5 for the copied program lines) the following command is used: COPY 200,5=10-40 New Program: 10 I=I+1 20 IF I=10 THEN 50 30 PRINT I 40 GOTO 10 50 END 200 I=I+1 205 IF I=10 THEN 50 210 PRINT I 215 GOTO 10 Note that the line numbers within the copied statements in this example (50 in copied statement 205 and 10 in copied statement 215) have not been renumbered by the COPY command. DIR DIR DIR "B:*.*" This command lists a disc directory on the screen in CP/M format. The first form lists all files on the logged on disc which have an extension of .BAS. The second form can be used to perform other directory functions, the example listing all files on unit B. Note that on a Network, or when running under CP/M 2.2, files which have been given the $SYS attribute are not displayed. ERASE ERASE "STATS3" The specified file is erased. No error is reported if the file does not exist. The filename must be unambiguous, i.e. it cannot contain * or ?. You should not erase a file that is open, as this can cause odd results, particularly on a Network System. The command CLOSE INPUT can be used to close input files. The command CLOSE closes output files (See chapter 12). FSAVE FSAVE "CIRCLES" FSAVE acts like SAVE (described below), except that the program is saved in internal format. The advantage of internal format is that loading (see below) is very much faster, by a factor of five or more on large programs. However, programs saved using FSAVE are very much less portable than programs saved using SAVE and an internal format program saved using one version of BASIC cannot be loaded by another version of BASIC. The chances of recovering from a corrupted file are also very much less with internal format. Internal format files cannot be combined by the MERGE command. Because of these restrictions, it is suggested that FSAVE be used sparingly, and that you should never leave yourself in the situation where your only copies of a program are in internal format. (Recreating a BASIC program in ASCII format from its internal format version can sometimes be done using LOAD and SAVE, but the success of this depends upon the version of BASIC being used to read the internal format file being identical to that used in the original FSAVE.) LIST LIST LIST 25 LIST 25-75 LIST 25- LIST -75 The specified lines of the program are to be displayed on the screen. The various forms display the whole program, line 25, lines 25 to 75, from line 25 to the end, and from the beginning to line 75. The display may be interrupted by pressing , or stopped temporarily by pressing and resumed by pressing . Automatic paging is turned on and off by . When it is turned on, the display stops after the screen has been filled with lines of program. The cursor blinks to indicate that further lines can be displayed; press the space bar to display the following lines. LLIST LLIST LLIST 25 LLIST 25-75 LLIST 25- LLIST -75 Similar to LIST but the program is listed on the printer. A printer is normally selected by the PRINTER command (see below). If no printer option has been selected, the listing is displayed on the screen. On a network system the output will be sent to the network printer unless a local printer has been selected (see below). You must terminate this listing with CLOSE #2 (See chapter 12). LOAD LOAD "STATS1" LOAD "B:STATS1.BAS" The LOAD command loads a program from disc storage. This command must include the name of a program, either enclosed in quotation marks or as a string variable or expression. This enables the disc directory to be searched for the desired program. If the program, which can be in either internal format or the normal ASCII format, is found, it will be loaded and BASIC will display the prompt "Ready:". Any program previously being entered or run is lost unless saved. Not finding the program on the disc results in the message: File not found and finding the program in the wrong internal format gives: Wrong internal format LOAD? LOAD? "CIRCLES" LOAD? will verify that a file on disc is the same as the program held in memory. It will only work on internal format files, and an attempt to use the LOAD? command to load an ASCII file will generate the message: Can't verify ASCII files Any difference between the files on disc and in memory results in the message: Files different otherwise BASIC merely displays the prompt: Ready: In neither case will either program be altered in any way. LOADGO LOADGO "CIRCLES" LOADGO "PROG",100 LOADGO loads the specified file, in either internal or ASCII format, and starts executing it. If no line number follows the filename, execution of the new program is started at the lowest numbered line, otherwise at the specified line. If no filename is given, the error message: Missing file name is produced. LOADGO is also available as a CP/M command line. Thus, from CP/M, the command: BASIC CIRCLES would load and run the program CIRCLES. In this case, no line number line number is permitted. If the program is in the wrong internal format, the message: Wrong internal format is displayed. Note that the file name must not be enclosed in quotation marks when given from the CP/M command line. Like all commands which modify a program, LOADGO initializes all variables and user-defined functions before executing it. MERGE MERGE "STATS2" The MERGE command allows you to combine lines of a program from a file on disc with a program already in memory. The command has a form similar to the LOAD command, in that it is followed by the name of the program to merge, enclosed in quotation marks or held in a string variable or expression. MERGE is similar to LOAD except that a pre- existing program line is only replaced when an incoming line has the same number. Otherwise the new lines are added. The RENUMBER command is useful for changing existing line numbers in order to prevent lines being inadvertently deleted when merging in additional ones with the same line numbers. The file must not have been previously saved using the FSAVE command. Attempting such a merge results in the message: Can't MERGE internal files MERGEGO MERGEGO "FUNX" MERGEGO "CIRCLES",100 The MERGEGO command is a combination of the LOADGO and MERGE commands described above. The specified file is merged into the current program and the new combined program is executed, starting at the specified line number if one is given, otherwise at the lowest line number. As with MERGE, MERGEGO cannot cope with an internal format file, and if presented with one produces the error message: Can't MERGE internal files Also as with MERGE, any lines in the memory resident program with the same line numbers as lines in the program to be merged into it are overwritten. As with all commands that modify the program, MERGEGO initializes all variables and user-defined functions before executing it. The following program exemplifies the use of MERGEGO: 10 INPUT "Function"; A$ 20 ERASE "TEMP" 30 CREATE #10, "TEMP" 40 PRINT #10, "70 DEF FNY(X)="; A$ 50 CLOSE #10 60 MERGEGO "TEMP", 70 80 GRAPH : TEXT 90 FOR X=0 TO 79 100 PLOT X, FNY(X), 2 110 NEXT X 120 INPUT "Another"; A$ 130 IF A$="Y" OR A$="Y" THEN 10 These commands are explained in Chapters 6, 7, 9, 11, and 12. NEW NEW The program, if any, is deleted. All variables are lost. The command is used to clear the program area prior to keying in a new program. PRINTER PRINTER 3 PRINTER 4,6 LOCAL PRINTER LOCAL PRINTER 2,4 LOCAL PRINTER NETWORK PRINTER NETWORK PRINTER The PRINTER command allows you to select a printer option directly from BASIC, without entering the Front Panel (see the System manual). It also allows printer selection under program control. The first argument selects which printer type to use, and the second, if present, is the baud code for serial devices. If a baud code is supplied for an option which does not require it (e.g. the parallel interface) then it is ignored. If the baud code is omitted for an interface which requires one (e.g. an SIO-4) then baud code 0 will be assumed. See Appendix D or the System manual for details of the significance of the terms "printer type" and "baud code". On a network system there exists the possibility of connecting a local printer to a station as well as a central printer serving the whole network. PRINTER sets options for a local printer only. LOCAL PRINTER directs all printed output to the local printer instead of the network printer, and may be followed by "printer type" and "baud code" parameters as in the PRINTER command. NETWORK PRINTER directs all printed output to the network printer instead of the local printer, and may not be followed by printer options. To set network printer options, use the program called CONFIG on your Network Maintenance disc, as described in the Network Users Guide. RENAME RENAME "NEWFILE", "OLDFILE" The file OLDFILE.BAS is renamed to NEWFILE.BAS. The error message "File not found" is reported if OLDFILE.BAS is not found. If NEWFILE.BAS already exists, BASIC prompts: File Exists--replace (Y/N): Enter Y to execute the rename. Care should be taken not to rename an open file, otherwise erroneous errors can occur on subsequent access to the channel on which the file was open, particularly on a network. RENUMBER RENUMBER RENUMBER 100,20 RENUMBER 100 RENUMBER ,20 This command is used to tidy up programs after editing. All line numbers, and internal references such as GOSUB 115, are adjusted. RENUMBER may be followed by two arguments: the new first line number and the line number interval. If either is omitted the default of 10 is used. Thus the examples renumber the program from line 10 at intervals of 10, from 100 at intervals of 20 respectively, from 100 at intervals of 10, and from 10 at intervals of 20. Line numbers in REM lines, after MERGEGO, or in expressions (e.g. in comparisons with the ERL function described in Chapter 8) are not affected. Extended BASIC Version 6 provides an additional facility to the RENUMBER command. An optional third argument, separated from the first two arguments by a comma, specifies the line number in the existing program from which renumbering is to start. (When only the first two arguments are used, renumbering begins at the first line of the existing program). For example: Command: RENUMBER 200,10,50 Initial program: Resulting program: 10 FOR I = 1 TO 10 10 FOR I = 1 TO 10 20 GOSUB 50 20 GOSUB 200 30 NEXT I 30 NEXT I 40 END 40 END 50 REM Subroutine Square 200 REM Subroutine Square 60 LET J = I 210 LET J = I 70 LET J = J*J 220 LET J = J*J 80 PRINT J 230 PRINT J 90 RETURN 240 RETURN This facility allows the partial renumbering of the program. It enables gaps to be inserted between any two existing program lines to provide space for additional lines of program. In the example, note that the internal references on line 20 have been suitably modified by the RENUMBER command. Before altering a program, the RENUMBER command validates the new line numbers to ensure that existing line numbers will not be overwritten. In such a case, the error message "Illegal function" is displayed and renumbering will not take place. RESET RESET RESET string RESET "ADC" This command may be issued after changing a disc (on either a stand- alone or a network system) instead of having to issue an equivalent CP/M or CP/NOS command. Any data files currently open for input or output will be discarded. A series of checks is built into the CP/M operating system to prevent inadvertent overwriting of programs and data if you accidentally change a disc while a data file is open for writing. If you do try to write to a changed disc you will get an error message of the form: BDOS ERROR ON B: R/O Do not press or you might lose your program. You can recover by pressing , which enters the Front Panel, followed by J>103. This restarts BASIC. Issue the RESET command, then inspect your program with the LIST command to make sure it is intact before proceeding. On a network system the RESET command will be denied if another user has a file open on the disc drive(s) to be reset, and the optional string parameter can be used to specify the names of the drives to be reset. For example: RESET "ADBC" will attempt to reset logical drives A, D, B and C. In this case, a warning message is given for any drives for which the reset operation is denied. If issued without a parameter, RESET will attempt to reset all drives, and will not produce any warning messages. Note that RESET, RUN and LOADGO will cause any open files belonging to the user issuing that command to be discarded without being closed. This helps to avoid certain unnecessary errors, but does result in any output files that have not been closed being lost. (This does not apply to spooler files). RUN RUN RUN 100 All variables are initialized and the program is started at the lowest numbered line if none is given, or at the specified line number (100 in the second example). SAVE SAVE"STATS3" SAVE "B:STATS3.BAS" The SAVE command saves a program on disc. Like the LOAD command, it must be followed by a program name, enclosed in quotation marks or held in a string variable or expression. When the program is saved, BASIC returns the prompt "Ready:". On a stand-alone system it is important to check, before issuing a SAVE command, that there is a disc in the selected unit and to make sure that you have not changed the disc in the unit since starting BASIC. If you have, issue the RESET command before the SAVE command, otherwise you will get a BDOS Read Only error (see RESET). CHAPTER 5 EDITING The editing facilities described in this chapter are equally applicable to both stand- alone and network operation. This chapter deals in turn with the editing facilities available to the 380Z and 480Z computers. Simple editing can be accomplished by retyping the corrected line, but use of the editing facilities of BASIC will usually be easier and more reliable. On the 480Z the function keys are used for editing and any text typed will automatically be inserted at the cursor position. With the 380Z editor and are used to move the cursor along the line and insertion must be specifically requested. 380Z EDITING This Section describes the use of the 380Z EDIT command. EDIT EDIT 55 When the EDIT command is executed, the specified line (55 in the example) is copied into the edit buffer. Commands can be issued to modify the line, and to put the corrected line back into the program. In Extended BASIC Version 6 the form EDIT. is allowed. This will edit the line last referred to (see Chapter 4). While operation of EDIT is quite simple, it is rather different from most character- and line-oriented text editors, so learning EDIT can prove difficult. However, a familiarity with at least some of the commands, especially , , , and , does speed program development. Most of the commands do not reflect the typed characters, and some cause no change at all on the screen, which can cause confusion to novices. EDIT maintains a pointer within the buffer. Under normal circumstances all of the characters to the left of the pointer are displayed on the screen, whilst those to the right are not. However, this simple scheme can get out of step following the and commands, so the current position of the pointer should always be kept in mind. Many of the commands take an optional numeric argument, which causes the command to be repeated the specified number of times. The number, which should lie in the range 1-255, must be typed before the command. There is no effect on the screen while a number is being typed. The numeric argument defaults to 1. In the detailed description of the commands below, such numeric arguments are denoted by "n". The commands are in alphabetical order: a short example appears at the end of this Chapter. Illegal commands are ignored. RETURN The line to the right of the pointer is displayed and the original line is replaced with the edited version.. This is the normal way to end an edit session. ESC terminates any command sequence. In particular, it resets any partly-entered number to 1, and it terminates Insert mode. nSPACE 6 Pressing the space bar will move the pointer right, reflecting the character it steps over. 6 will move the pointer six characters, reflecting the skipped characters. A Pressing causes the current attempt at editing the line to be abandoned. The buffer is refilled from the original program line, and the pointer is reset to the beginning of the line. This command is useful if an edit has become confused. nD 7 The n characters after the pointer are deleted. The deleted characters are echoed between backslashes (\). These characters may appear as a half (½) with some versions of COS, or as forward slash (/) with others. E exits the editor and implements the changes but the amended line is not typed out. This command was designed for use with very slow output devices in mind, and is probably not useful on the 380Z using the normal screen. nFc 3 3A Find the nth occurrence of character c and move the pointer to just before it. If there are fewer than n occurrences of c, the pointer is moved to the end of the line. H Everything to the right of the pointer is deleted and Insert mode entered. See command for details of Insert mode. I Enter Insert mode. Subsequent characters are entered directly into the buffer. Insert mode is terminated either by , which merely terminates Insert mode, or , which leaves EDIT and updates the line. will remove incorrect characters, even those to the left of the position of the pointer when Insert mode was entered. However, the line number cannot be changed. Insert mode can thus be used to delete or replace faulty text only. nKc A 40 Kill (delete) all characters from the pointer up to but not including the nth occurrence of character c. The pointer is left positioned just before this character. The command has no discernible effect on the screen. If there are fewer than n occurrences of the character c to the right of the pointer then the remainder of the line will be deleted. L The line to the right of the pointer is displayed and the pointer returned to the beginning of the line. Q The Edit is abandoned without implementing the changes made. Control is returned to command level (the "Ready:" prompt). This command is useful after an edit has become totally confused. nR 3 The n following characters in the buffer are replaced by the next n characters from the keyboard. and are treated as in Insert mode, i.e. aborts the R command and leaves EDIT and implements the changes. The other control characters and are ignored. X moves the pointer to the end of the line and Insert mode is entered. In effect, new characters are appended to the line, nDELT 8 will move the pointer to the left, backing the cursor over the skipped character. 6 will back over 6 characters. is essentially the reverse of . Note that in Insert mode, removes characters from the buffer. will not move the cursor past the line number. As an example of 380Z editing, we will change BROWN to RED in: 10 DATA THE QUICK BROWN FOX In the following, only , , and the command are used: User types EDIT 10 Computer 10 User types 20 Computer 10 DATA THE QUICK BROWN User types I Computer 10 DATA THE QUICK User types RED Computer 10 DATA THE QUICK RED FOX The usual sequence in editing is: 1. Enter EDIT 2. Move pointer and enter Insert mode 3. Delete and/or insert 4. Exit from Insert mode and from EDIT We recommend that you practice thoroughly with this subset of the EDIT commands before attempting to add the more complex ones to your repertoire. 480Z EDITING This Section describes the use of the line editing capabilities of BASIC on a 480Z and the EDIT command. Line Editing It is possible to move the cursor backwards in the line to carry out alterations as long as has not been pressed. Non-printing characters are used to perform these editing functions. These control characters are obtained by holding down the CTRL key and typing a character but most of the commonly used characters are available on the function and arrow keypad. Some of the functions also require the use of the SHIFT key. A plastic overlay is available to fit around the function and arrow keypad, showing the effects of the keys during line editing. As characters are typed to BASIC, printing characters are entered into the buffer at the cursor position if there is room in the buffer. If there is insufficient room, BASIC sounds the beeper. The following list describes the available editing functions: Cursor left Cursor right Cursor up Cursor down Delete character backwards Delete character forwards Find next character typed (backwards) Find next character typed (forwards) Cursor to beginning of line Cursor to end of line Delete line or restart line in EDIT mode Delete line (from buffer only in EDIT mode) Delete to beginning of line Delete to end of line Delete to next character typed (backwards) Delete to enxt character typed (forwards) or Terminate line Erase line, halt execution of program Clear screen, cursor bottom left Clear screen, cursor top left Toggle printer echo (see text) Toggle printer echo (see text) Enter Front Panel (after check) Enter operating system (after check) This editing mechanism is available for both entry of program lines and for data entered in response to INPUT LINE or LINE INPUT. At all times except after the clear screen commands, the current state of the line is displayed, with the cursor symbol flashing over the character after the cursor position. If the cursor is at the end of the line it will flash or be steady depending on the state of the monitor. An attempt to move the cursor beyond the start or end of the line moves it to that boundary. The functions obtained by , , and require that a character is entered at the keyboard. For the find commands, the cursor is moved to lie on top of the next occurrence of the designated character in the specified direction. For the delete commands, characters are deleted up to and including the designated character. During line editing in this manner, the printer echo process, set with or , is disabled and the effect of the WIDTH statement is suspended. If printer echo is set, the line is reflected to the printer after the terminating is pressed. The effect of WIDTH is only available for material typed by the computer, usually as the result of a program running. Pressing or during line editing switches the state of the printer echo flag which will be used after editing is complete, but no visible indication is provided for these keys. It is possible for a program to alter the effects of the function and arrow keys with the PUT command. Although EDIT (q.v.) resets these keys to suitable values, normal line entry does not. Attempts to enter a line after a program has altered the function and arrow keys may therefore become confused. Strange effects will be produced if a window is defined which is too small to hold the line being edited. The EDIT Command The EDIT command can be used to alter a line after has been pressed. The format of the command is: EDIT In Extended BASIC Version 6 the form EDIT. is allowed. This will edit the line last referred to (see chapter 4). The specified line is transferred to the line editing buffer and the cursor is placed after the line number. Thereafter, editing proceeds much as for normal line editing. The only exceptions are: restarts edit with fresh copy of line abandons edit without affecting the line The function and arrow keys are also initialized. will work until the line is terminated by either or . The line number is treated like any other part of the line and can be altered in the same way. Line edit mode is terminated by or . On exit, the old line will be left intact and the new line inserted into the program, overwriting any existing line with that number. CHAPTER 6 DATA TRANSFER COMMANDS As described in Chapter 3, variables are the names of spaces in memory reserved for the storage of data, which may consist of numbers, strings of characters, arrays of numbers, or arrays of strings. Enough string space should be reserved by a CLEAR statement to hold all the characters that will be stored in string variables during execution of the program. Numeric and string arrays should be dimensioned with a DIM statement before use. If a DIM statement is omitted, or if a value is assigned to an array element before a DIM statement for that array is executed, BASIC assumes limits of 0 to 10 (11 elements). For these reasons, it is usual for CLEAR and DIM statements to be among the first in a program. CLEAR should occur before DIM. In Extended BASIC Version 6 the KILL command can be used to delete an array which is no longer required (see chapter 10). CLEAR 10 CLEAR 20 CLEAR 2000 All variables and arrays are cleared. If a number follows, as in the second example, space is reserved to store that number of characters in string variables. Thus the second example reserves storage for up to 2000 characters. If the number is omitted, the string area is not changed. When BASIC starts, space for 100 characters is reserved. If a program runs out of string space during execution, the error message: No string space is displayed and program execution stops. You can discover the current size of string space by the statement: PRINT FRE(X$) and the current amount of free memory by the statement: PRINT FRE(X) Neither X$ nor X are altered by these statements. String space can be increased by the CLEAR statement until free memory becomes quite small, but some free memory will be needed for statements such as FOR and GOSUB, depending on the program. Another form of the CLEAR statement is permitted in Extended BASIC, of the form: CLEAR 200,,1024 in which the second number adjusts the size of cache memory. Cache memory is used in conjunction with machine language routines. Note the peculiar syntax with the two commas. These are required to allow for an extension in BASIC Version 6 (see Chapter 13). DATA 50 DATA 5,4,3 20 DATA BLUE,RED 30 DATA "BLUE,RED" Numeric or string constants can be specified in a DATA statement ready for assigning to variables by means of a READ statement. Special care is needed if string data is to contain spaces or commas. The safest way to deal with this is to place the strings between quotation marks, for example: 20 DATA " GONE AWAY, BACK SOON" is taken as a single string with a space before GONE. Spaces may be inserted in a string without quotes after the first character, for example: 20 DATA GONE AWAY, BACK SOON would be taken as two strings without a space before GONE or after the comma. DIM 10 DIM A(20), B(30,5), A$(40), D(J) Ordinary variables take the forms A, A7, X9 (numeric) or A$, A7$, X9$ (string). Array variables require a DIM statement to reserve space for them. For example, DIM A(20) would reserve 21 array elements A(0), A(1), A(2)...A(20). As shown in the example. a single DIM can dimension more than one array. A value would have to have been assigned to J before the DIM statement was executed. If an attempt is made to DIMension an existing array, the error message: Re-dimensioned array is produced and program execution halts. In Extended BASIC Version 6 the KILL command can be used to delete an array which is no longer required (see chapter 10). EXCHANGE 25 EXCHANGE A$,B$ 35 EXCHANGE C,D(I,J) The EXCHANGE command swaps the values of two variables. The format of the EXCHANGE command is: EXCHANGE v1,v2 v1 - one of a pair of variables whose values are to be exchanged. v2 - the other of a pair of variables whose values are to be exchanged. Both of these variables must be of the same type. An attempt to swap a constant value (e.g. EXCHANGE A$,"NO" or EXCHANGE X,4) generates the message "Syntax Error". A single array element (but not a whole array) may be used as either of the variables. Example: EXCHANGE F$(3), G$ The value of the fourth element (arrays have a base of zero) of the string F$ is exchanged with the value of the string variable G$. Note that the swapping of values can be carried out by the use of three assignment statements and another variable: LET T$ = A$ LET A$ = B$ LET B$ = T$ The EXCHANGE command is, however, considerably faster, particularly where strings are concerned, as it is only the pointers to the strings that are swapped, instead of multiple copies of the strings being made. LET 10 LET A=B+2 10 A$="HELLO" The word LET is optional. The expression on the right hand side of the = sign is evaluated and the result is assigned to the variable on the left hand side. The reader is advised to think of assignment (LET) commands as: A (left arrow) B+2 which should be read as "A becomes equal to the value of B plus 2 , although, of course, the = notation must be used. For example, the statement: LET A=A+1 will increase by 1 the value stored in A. If an attempt is made to assign a string to a numeric variable, or vice versa, the error message "Type mismatch" is displayed and program execution is halted. For example, the statement: LET A = "123" is not acceptable. READ 30 READ A,B,C 40 READ A$,B$ The READ instruction collects values from DATA statements and assigns them to the specified variables. Data is picked up from DATA statements in strict order. If there is more than one line of DATA, the lowest line number is taken first. Attempts to READ more data than exists will cause the error message: Out of data at line n where n is the line number of the READ instruction currently executing. Numeric DATA can be READ into a string variable because it is also string data. String DATA cannot be READ into a numeric variable. Bearing this in mind, and noting that there is only one data pointer, the programmer must ensure that the DATA matches the READ statements exactly. The data pointer can be placed at any position in the program by means of the RESTORE command (see below). The READ # command, for reading information from a random access file, is described in Chapter 13. RESTORE 80 RESTORE 50 RESTORE 100 The data pointer is reinitialized to point to the start of the data so that it can be used again. If no line number is given, RESTORE leaves the data pointer at the first DATA statement in the program. If a line number is supplied, as in the second example, it is left at the first DATA statement after the specified line. CHAPTER 7 CONSOLE AND PRINTER INPUT/OUTPUT This chapter describes INPUT and PRINT, the two main commands used in BASIC for reading the keyboard and outputting to the screen. Some variants of these are also described, together with a group of commands that help in formatting output. Consideration of data transfer to and from data files is deferred until Chapter 12. INPUT 50 INPUT A 50 INPUT A,B 50 INPUT "ANSWER"; A$ The program pauses to allow the user to enter data at the keyboard which will be assigned to the specified numeric or string variables. When BASIC executes an INPUT command, a question mark is displayed on the screen. Taking as an example the program fragment: 10 INPUT A 20 PRINT A the following would appear on running the program: RUN ? BASIC waits for the user to enter some data and press : RUN ? 2 2 Ready: If is pressed without any data being entered, either a numeric value of zero or a null (empty) string is assumed. More than one variable can be specified in an INPUT command. In this case, the entered items should be separated by commas. If insufficient items are entered, BASIC prompts the user to enter the remainder with a double question mark. If too many are entered, the error message "*Extra lost" appears. Using the earlier example: RUN ? 3,4 *Extra Lost 3 Ready: If a number is expected and characters which cannot form part of a number are typed in, the error message "*Invalid input" is displayed and all data for that INPUT statement must be retyped. Again using the example program: RUN ? 1/4 Invalid input ? 0.25 .25 Ready: An explanatory string is allowed after INPUT, enclosed in quotation marks and terminated by either a semicolon (;) or a comma (,). It is printed before the program pauses, instead of a question mark if the terminating character is a comma, else as well as the question mark. If an INPUT statement is interrupted by entering and the program then continued, the prompt is repeated. An alternative method of prompting is to use the PRINT statement (see below). It is important that data should be entered from the keyboard in a form that matches the variables in the INPUT statement. Wrong data or too much data causes the error messages already described. Special care is needed when string data is required to contain commas or leading spaces. One way of dealing with this is to type the string between quotes. For example, the response: ? " GONE AWAY, BACK SOON" is regarded as a single string with a space before GONE. The INPUT LINE instruction provides another way of achieving this. Spaces may be inserted in a string without enclosing it in quotes, if they occur after the first character. Thus: ? GONE AWAY, BACK SOON counts as two strings, each containing exactly one space. The spaces immediately after the question mark and the comma are ignored. INPUT LINE 50 INPUT LINE "Please type your name: ", N$ The INPUT LINE instruction differs from INPUT in that only a string variable can be specified. The whole of the entered data is transferred to the variable, including spaces and commas, without the need to enclose the data in quotation marks, If more than one variable is present, BASIC prompts for additional input with a double question mark. INPUT LINE can be used in writing "safe" programs that are less likely to be stopped by invalid data; the process of validating the data can be carried out by programmed instructions rather than being left to the BASIC interpreter. This statement may take the alternative format LINE INPUT. PRINT 50 PRINT 50 PRINT "ANSWERS ARE";A,B Values of variables or messages are printed on the screen. The word PRINT is followed by a sequence of variables, expressions, or strings enclosed in quotation marks. Each item except the last in the sequence should have a semicolon or comma after it. The instruction PRINT by itself merely outputs a blank line. A number or the result of a numeric expression is output with a space preceding it if it is positive, or a minus sign if negative, and with a space following it. A quoted string, string variable, or string expression is output with no spaces added. When two numbers are separated by a semicolon, they are always separated by at least one space. For example, the program fragment: 10 LET A=2 20 PRINT A;A 30 PRINT -A;-A would produce: RUN 2 2 -2 -2 Ready: When two strings are separated by a semicolon, they are output without any intervening spaces: 10 LET M$="MARY" 20 LET J$="JANE" 30 PRINT M$;J$ RUN MARYJANE Ready: Commas between items cause the items to be printed in columns spaced 14 positions apart. The form: PRINT A,,B is allowed and results in the value of B being printed at column 28. A semicolon or comma after the last item suppresses the new line which would otherwise follow the printing of that item. Rather than being at the beginning of a line, the output from the next PRINT statement will start where the current one leaves off. The symbol ? may be used as a synonym for PRINT. Its use in programs does not improve their readability but it is often convenient for inspecting the value of a variable in direct mode. Output from the PRINT statement may be echoed to the printer by pressing or . See Chapter 2. LPRINT 50 LPRINT 50 LPRINT "ANSWERS ARE";A,B This instruction is the same as PRINT except that its output goes to the printer, not the screen. Note that the comman