Brian D. Hahn
True BASIC
by Problem Solving
DO FORMA
DO NUM ROM DO PAGE KEY TO DO RENUM LIST DOTRACE LOAD DOUNNUM LOCATE
bo VCH
True BASIC by Problem Solving
True BASIC is a trademark of True BASIC Inc., 39 South Main St, Hanover, NH 03755, USA
© VCH Verlagsgesellschaft mbH, D-6940 Weinheim (Federal Republic of Germany), 1988
Distribution: Worldwide (South Africa excepted): VCH Verlagsgesellschaft: P.O. Box 1260/1280, D-6940 Weinheim (Federal Republic of Germany)
Switzerland: VCH Verlags-AG, P.O. Box, CH-4020 Basel (Switzerland)
Great Britain and Ireland: VCH Publishers (UK) Ltd., 8 Wellington Court, Wellington Street, Cambridge CB1 1HW (Great Britain)
USA and Canada: VCH Publishers, Suite 909, 220 East 23rd Street, New York, NY 10010-4606 (USA)
ISBN 3-527-26863-4 (VCH Verlagsgesellschaft) ISBN 0-89573-814-7 (VCH Publishers)
GY 20}+
True BASIC
by Problem Solving
Brian D. Hahn
Author:
Dr. Brian D. Hahn
Department of Applied Mathematics University of Cape Town
over illustration: True BASIC Commands
Editorial director: Dr. Hans D. Junge Production manager: Myriam Nothacker
British Library Cataloguing in Publication Data:
Hahn, Brian D.: True BASIC by problem solving. 1. Computer systems. Programming languages : Basic language I. Title 005.1373 ISBN 3-527-26863-4
Deutsche Bibliothek Cataloguing-in-Publication Data:
Hahn, Brian D.: True BASIC by problem solving/Brian D. Hahn. - Weinheim ; Basel (Switzerland) ; Cambridge ; New York, N.Y. : VCH, 1988
ISBN 3-527-26863-4
VCH Verlagsgesellschaft mbH, D-6940 Weinheim (Federal Republic of Germany), 1988
All nights reserved (including those of translation into other languages). No part of this book may be reproduced in any form — by photoprint, or any other means — not transmitted or translated into a machine language without written permission from the copyright owner. Registered names, trade- marks, etc. used in this book, even when not specifically marked as such, are not to be considered unprotected by law.
Printing: betz-druck gmbh, D-6100 Darmstadt 12 Bookbinding: Verlagsbuchbinderei Georg Krank], D-6148 Heppenheim Printed in the Federal Republic of Germany
PREFACE
This book is one of the first to explore the problem-solving potential of True BASIC (Version 2.0), an entirely new and structured version of BASIC, developed by the originators of the BASIC programming language, and published in 1985. True BASIC retains all the simplicity of the earliest versions of BASIC, and has superb machine- independent graphics, making it arguably the best high level language for beginners. On the other hand, it has features which will be quite unrecognizable to old-time BASIC addicts: modern control structures (DO-WHILE, DO-UNTIL, Block IF, SELECT CASE), named subroutines with arguments and local variables, modules, pictures (graphics subroutines) and optional line numbers. These features enable it to take its place as a serious scientific problem-solving language of the first degree.
The approach taken in this book is one developed over many years of teaching
programming, in FORTRAN, Pascal and other versions of BASIC, to first-year
university students with no computing experience. It can therefore be used as a “teach
yourself” guide by anyone wishing to learn True BASIC, and who has access to a
computer which will run the True BASIC Language System. The computer is presented as a tool for solving interesting, real-world problems, and examples from many areas, as wide apart as business and biology, but particularly science and engineering, are discussed. The technicalities of each new programming construction are therefore generally presented only after a motivating example. Since the objective of this book is to enable you to solve problems using True BASIC, the earlier chapters are in a sense a preparation for later ones, where you will be introduced to some modern computer applications, such as simulation, modelling and numerical methods. There are also a large number of exercises, taken from a variety of areas. Most of these have solutions provided. Some of those for which solutions have not been given have been successfully used as class projects in teaching situations.
siructured programs are developed throughout the book. The notorious GOTO statement, the target of most of the criticism of earlier versions of BASIC, is rendered entirely unnecessary by the control structures of True BASIC.
Emphasis 1s also laid on programming style, and guidelines for writing clear, readable programs are presented.
It must be stressed that this book is not a technical reference manual, but rather an exposition of how to use True BASIC to solve problems, so new constructions are generally introduced as the problems presented require them. All the details of particular statements will not therefore always be found in the same place. However, there are exhaustive syntax summaries in the appendices, and although the treatment of the language in this book is almost complete, you are referred to the True BASIC Reference Manual in the few instances where some details have been omitted. The version of the language used is 2.0.
True BASIC conforms closely to the proposed American National Standard for BASIC (ANS BASIC). Any differences from this standard are mentioned in the text. The True BASIC screen editing facilities described in this book are for the IBM PC and most compatibles, although the formal language definition is machine-independent.
vl PREFACE
No specialized mathematical background is needed to follow most of the examples. There are occasional forays into first-year university mathematics, but these are self-contained and may be glossed over without loss of continuity (you may even find them interesting!).
It is hoped that this book will give you some insight into the ways that computers in general, and True BASIC in particular, may be used to solve real problems, and that after working through it you will be better equipped to solve problems for yourself.
Acknowledgements
Some of the examples and exercises in the text are similar to ones appearing in another book of mine, Problem Solving with FORTRAN 77 (1987), published by Edward Arnold (London), and are reprinted here by kind permission of the publisher. I wish to thank my wife, Cleone, for her continual love and support over the years, and particularly during the writing of this and other books, and my children, Lyndall, Andre and David, for their interest and encouragement. I want to acknowledge a debt to present and past students and colleagues in the Departments of Applied Mathematics at the University of the Witwatersrand, Johannesburg, and at the University of Cape Town, for providing the stimulating environment required to produce a book of this nature. A number of programs from the True BASIC User’s Guide and Reference Manual have been used; acknowledgement is made in the text. I have also tended to use similar notation and phraseology in language element definitions. Finally, I would like to thank the authors of True BASIC for developing a language about which it has been a pleasure to write a book.
Brian D. Hahn January 1988
CONTENTS
1. GETTING GOING
1.1 Computers 12 BASIC 1.3. Running True BASIC Programs Introducing Yourself to the Computer Adding Two Numbers Compound Interest 1.4 Editing a Program 1.5 Handling Program Files on Diskettes 1.6 True BASIC Demonstration Programs Summary EXERCISES
2. FUNDAMENTALS OF TRUE BASIC
ak 2.2
Compound Interest Again Program Format Program Lines Long Lines The END and STOP Statements Comments Line Numbers Numeric Constants Variables Vertical Motion under Gravity Programming Style Arithmetic Expressions Arithmetic Operators Precedence of Operators The LET Statement Examples The PRINT Statement Basic Rules for PRINT Printing Output on the Printer The INPUT Statement INPUT with a Prompt INPUT with a Trailing Comma The FOR-NEXT Statement Square-rooting with Newton Differential Interest Rates Final Course Mark Deciding with IF-THEN-ELSE The READ-DATA Statements
viii CONTENTS
2.15 Strings 29 String Constants 29
String Variables 30
Concatenation of Strings 31
2.16 Advanced Editing 3] Editing Keys 3]
Editing Commands 33
2.17 Using True BASIC Statements as Commands 33
2.18 Odds ’n Ends 33 Representation of Information in a Computer 33
Compilers and Interpreters 34
Operating Systems 35
Summary 35 EXERCISES 36 3. PROGRAM PREPARATION 39 3.1 Flowcharts SY
3.2 Quadratic Equation: Flowchart 4]
3.3. Newton’s Method: Flowchart 42
3.4 Structure Plans 43
3.5 Quadratic Equation: Structure Plan 44
3.6 Structured Programming del Bitiinry 45 EXERCISES 45
4. BUILT-INFUNCTIONS
47
4.1 Projectile Motion 47
4.2 Some Useful Built-in Functions 46
Summary SO
EXERCISES 50)
9. CONTROL STRUCTURES |: DECISIONS a2
5.1 The IF statement 53
Bending Moment in a Beam 53
Top of the Class 54
The ELSEIF Construct 55
The General Form of IF-THEN-ELSEIF 55
Logical Expressions 57
Spaghetti 58
5.2 The SELECT CASE Statement 59
Summary 61 EXERCISES
CONTENTS
6. CONTROL STRUCTURES II: REPETITION
6.1 Deterministic Repetition: FOR-NEXT Plotting a Sine Curve General Definition of FOR-NEXT Vertical Motion Again Damped Oscillations Factorials! The Binomial Coefficient Computing the Limit of a Sequence Nested Loops: Loan Repayments The Telephone
6.2 Non-deterministic Repetition: The DO Statement Reaction Time Test Doubling Time of an Investment The General Form of the DO Statement Testing for More Data Taylor Series for Sine
Summary
EXERCISES
7. ERRORS es Compilation Errors Is Run-time Errors Debugging with DO TRACE Intercepting Errors with Error Handlers
l 7
/.3 Errors in Logic /.4 Rounding Error Summary XERCISES
8. ADVANCED INPUT/OUTPUT 5.1 Rabbit Breeding the Fibonacci Way 5.2 The PRINT USING Statement $.3. PRINT USING with Numbers The Digit Characters (* % #) The Leading Characters (+ — $) Other Characters (, . *) 8.4 PRINT USING with Strings 8.5 Files : Updating Student Marks Files in General Examples Text Files in Particular Output to a Printer
Summary
EXERCISES
1X
63 63 63 63 64 65 66 67 67
69 69 710 70 71 T2 73 74
719
719
31 81 ol 83 84
85 85
CONTENTS
noe
9. SUBSCRIPTED VARIABLES: ARRAYS 9.1 Mean and Standard Deviation
General Rules for Arrays
Bar Charts and Frequency Distributions
Sorting a List: the Bubble Sort
Order of Merit List
Top of the Class
Updating Student Marks Again
SO SO OO OO SAO mW bo
Summary EXERCISES
10. ADVANCED STRINGS 10.1 Sorting Strings 10.2 String Expressions and Substrings 10.3. Record Files Multiple Items in a Record A Binary Search for Students 10.4 Byte Files 10.5 String Functions 10.6 Music
Summary EXERCISES
11. FUNCTIONS AND SUBROUTINES
11.1 Functions Newton’s Method in General Rotation of Co-ordinate Axes Bending of a Beam Parameters and Arguments External Functions: the Factorial Internal Functions Local and Global Variables General Rules for Functions Recursion 11.2 Subroutines Swopping Two Variables Mean and Standard Deviation Largest Item in a List General Rules for Subroutines 11.3. File Handling Copying Text Files Safely A General File Opener with Error Handler 11.4 A Basic Budget
11.5 11.6
A Xhosa—English Translation Test A Binary Search Subroutine
11.7 Graphs without Graphics
11.8 The INCLUDE Command
11.9 Saving a Compiled Program
11.10 Libraries
11.11 The LOAD Command and Workspaces
101 101 103 105 106 108 110 11] 115 116
119 119 120 121 122 125 129 131 132 133 133
CONTENTS
xl
11.12 The CHAIN and PROGRAM Statements 165
11.13 Modules 166
11.14 Calling MS-DOS from True BASIC 167
11.15 The GOSUB Statement 167
Summary 167
EXERCISES 168
12. GRAPHICS 171
12.1 Some Examples 171
Sinusoidal Graphs 171
Tangents to a Curve 172
Fourier Approximation to a Square Wave 173
Capacitor Charge and Discharge 174
Angle of Launch for Maximum Range 175
Fractals with Turtle Graphics 175
12.2 Graphics Statements 177
The SET WINDOW Statement 177
The PLOT Statements 177
The BOX Statements 179
Animation 180
The Aspect Ratio 182
The FLOOD Statement 183
Graphic Input 183
12.3. Windows 184
12.4 Pictures and Their Transformations 186
Drawing a Snowflake 188
Recursive Pictures 190
12.5 True BASIC Colour Graphics 190
12.6 IBM PC Modes 192
Monochrome Mode 192
Text Modes 193
“MEDRES” Mode 194
“HIRES” Mode 194
12.7. ‘True BASIC Graphics Demonstration Programs 195
12.8 Printing the Graphics Screen 195
Summary 195
EXERCISES 195
13. SIMULATION 197
13.1 Spinning a Fair Coin 197
13.2 Rolling a Fair Die 198
13.3. Bacteria Division 199
13.4 A Random Walk 199
13.5 Dealing a Bridge Hand 201
13.6 Traffic Flow 204
13.7 Queues 207
Summary 211 EXERCISES
211
X11
CONTENTS
Sa ———————
14. MATRICES AND THEIR APPLICATIONS 14.1 Tables: a Concrete Example 14.2. Matrices |
Matrix Multiplication Examples 14.3. Handling Matrices with True BASIC Explicit Redimensioning The MAT PRINT Statements Array Parameters The MAT PLOT Statements Matrix Assignments Matrix Arithmetic Implicit Redimensioning Built-in Array Values Built-in Matrix Functions 14.4 Networks A Spy Ring The Reachability Matrix Cycles Postscript 14.5 Leslie Matrices Rabbits Again The American Robin 14.6 Markov Chains Weather ‘‘Prediction’’ A Random Walk 14.7. Solution of Linear Equations The Direct Method Gauss Reduction 14.8 Volume of Excavation 14.9 Area ofa Site 14.10 Rotation of a Co-ordinate System
Summary
EXERCISES
15. INTRODUCTION TO NUMERICAL METHODS
15.1 Equations Newton’s Method The Hire Purchase Rip-Off The Bisection Method
15.2 Integration The Trapezoidal Rule
15.3. Numerical Differentiation
15.4 First-Order Differential Equations Euler’s Method for Parachutes Euler’s Method in General Euler’s Method for Bacteria Growth A Predictor-Corrector Method
15.5 Runge-Kutta Methods Runge-Kutta Fourth-Order Formulae
213 213 214 215 216 216 217 217 218 218 219 219 220 220 221 221 222 224 ZL 226 226 226 230 231 231 233 234 235 236 2359 24] 243
244 244
24
245 245 247 248 250 250 252 255 256 29 259 261 262 262
CONTENTS
A Predator-Prey Model Driver Program to Solve Differential Equations Summary
EXERCISES
EPILOGUE. PROGRAMMING STYLE
APPENDIX A. QUICK REFERENCE
A.1. Commands
A.2. Cursor Movement Keys A.3. Editing Keys
A.4. Formatting Characters A.5. Function Keys
A.6. Special Key Combinations A.7. Statements
APPENDIX B. TRUE BASIC COMMANDS
B.1. General B.2. Summary of Commands
APPENDIX C. SUMMARY OF BUILT-IN FUNCTIONS
C.1. Scalar Functions C.2. String Functions ©.3. Matrix Functions .4. Miscellaneous
APPENDIX D. CHARACTER CODES D.1. The ASCII Character Codes D.2. Additional Codes
APPENDIX E. RESERVED WORDS
APPENDIX F. TRUE BASIC LIBRARY FILES
F.1. Mathematical Functions F.2. Graphics Procedures AIC Graphlib Relplot
Xill
262 263
267 267
2/1
273
273 2/4 2195 2715 2/6 2/6 2/6
283
283 284
295
295 301 302 303
305
305
306
309
311]
311 312 312 313 313
CONTENTS
XIV APPENDIX G. SOLUTIONS TO SELECTED PROBLEMS 315 REFERENCES 331
INDEX 333
CHAPTER 1
GETTING GOING
As little as 20 years ago computers were still regarded with a great deal of suspicion. However, at this late stage of the 20th century it is surely not necessary to justify the need to learn computing. The last few years have seen a flood of microcomputers into offices, factories, schools, hospitals, supermarkets, homes, farms, game parks, and even universities! Apart from the interest factor, anyone who 1s “computer literate”’ is better equipped for a wide range of careers than someone who is not.
1.1. Computers
You are probably familiar with using an electronic calculator to find numerical answers to arithmetic problems. The simplest sort can only do basic arithmetic and display an answer. [he next step up is one with a single memory location, where an intermediate result may be stored, and with function keys, such as sin, cos, log, etc. Even better calculators may have more memory locations, so that different intermediate results may be stored during a long and involved calculation.
tlowever, if you have to perform the same sequence of arithmetic operations on a calculator many times for different sets of data, it can become extremely tedious. So even more sophisticated calculators allow you to store, in some suitable coded form, the sequence of operations (or instructions) needed to calculate the solution of the problem. This sequence of instructions is called a program. To carry out the entire set of calculations you need only load the program into the calculator, press the “run” key, provide the necessary data, and sit back while the machine churns out the answers. A calculator like this is called programmable. A computer, whether it is a ‘“‘micro” (or personal computer) like the IBM PC, ora large ‘“‘mainframe”’ like the IBM 370, is really only an advanced programmable calculator, capable of executing and storing sets of instructions, called programs, in order to solve specific problems.
1.2. BASIC
The particular set of rules or conventions for coding instructions to a computer is called a programming language. There are many such languages, e.g. BASIC, FORTRAN and Pascal. BASIC, which stands for Beginners All-purpose Symbolic Instruction Code, was developed by John Kemeny and Thomas Kurtz at Dartmouth College, New Hampshire, U.S.A. The first BASIC program was run on a General Electric 225 computer at 4 a.m. on Ist May 1964, and the world of computing has never been the same since! The major advantage of BASIC is that it is by far the easiest “high level” programming language to learn, as is evidenced by the vast number of children who use
2 CHAPTER 1
| ee SSS it successfully. In 1978 Kurtz estimated that five million school children had learnt BASIC; Galanter (1983) reports that seven and eight year-olds are learning to write simple BASIC programs at his computer school for children. Another advantage of BASIC is that it can be used on virtually any kind of microcomputer.
The first microcomputers to appear in the early 1970s used a primitive version of BASIC, and it was this version that for various reasons was modified into the versions available on present microcomputers. These versions are extremely machine-depen- dent (e.g. a BASIC program written for a ZX-80 will not run as it stands on an Apple) and have a number of ugly features, which have in fact largely contributed to the bad name that BASIC has among many serious programmers. These versions have been dubbed ‘‘Street BASIC — a horrible dialect of a beautiful language” by the originators of BASIC, Kemeny and Kurtz (1985a), in their highly readable description of the history and philosophy of BASIC, Back to BASIC.
While Street BASIC was infecting the microcomputer world in epidemic proportions, Kemeny and Kurtz, with a team of enthusiasts, were at work correcting some of the valid criticisms of the earliest forms of BASIC, viz. its lack of structure. The results of their labours, ‘““True’’ BASIC, was published in 1985. It has many outstanding features. It retains the simplicity and clarity of the original BASIC, so that statements like PRINT, FOR-NEXT, IF-THEN-ELSE, INPUT, READ-DATA, etc., which you may already know from other versions of BASIC, will work just the same. Yet True BASIC has powerful control structures, modular programming features, superb graphics, library facilities and is hardware-independent (1.e. the same True BASIC program can be run on any computer that supports the language). This makes it a scientific problem solving language in its own right, and a serious contender with languages such as Pasca! and FORTRAN. The aim of this book is to enable you to solve problems in a variety of areas using True BASIC.
1.3. Running True BASIC Programs
Your ultimate aim will be to write your own program coding for whatever problem you want to solve, and you will be eager to get on with this task. However, the greatest hurdle facing you at the moment, if you are a computer novice, is getting the computer you are using to do some work for you. The examples in this chapter are therefore very easy, and are given without much explanation (this will follow in the next chapter). You should run these examples on your computer as soon as possible. Do not stop trying until you have succeeded!
Introducing Yourself to the Computer
Seat yourself comfortably in front of the computer. If you have your own personal copy of the True BASIC Language System ona floppy diskette, it is assumed that you have followed the instructions in the True BASIC User’s Guide for installing the system on your own computer. Put the diskette into drive A. (Throughout this book it is assumed that your computer has two disk drives, which are called A and B. If this is not the case, mentally delete all references to B from now on, and swop diskettes in the drive when
GETTING GOING 3
necessary.) The power switch is usually in some inaccessible place, like behind the machine. This is deliberate, so that you cannot accidentally switch it off and lose everything in your current session that you might not have saved. The computer should display the “‘system prompt”
A>
which means it is ready for you to do something. Type the word HELLO and press the - Return (Enter) key. This calls up the True BASIC System.
If you are using some sort of menu-driven student system, carefully follow the instructions on the screen for calling up True BASIC. Remember to press Return after every response you make, to communicate that response to the computer.
If something goes wrong, and all else fails, “‘reboot’’ the system by holding down the Ctrl and Alt keys (on the left of the keyboard) simultaneously with the fingers of one hand (preferably the left) while pressing the Del key (on the right of the keyboard) briefly with any free finger. Incidentally, you can’t damage the computer by pressing the wrong keys, so don’t worry!
Once you are in True BASIC, the screen will look as shown in Figure 1-1, except that the area above the solid line should be blank. The screen is divided into two sections.
Figure 1-1. Layout of Windows
Line Tags Program Statements
o PRINT "What is your name”; Editing . . gaINPUT N$ Window “aPRINT "Hi there, "; NS
pEND
: Untitled
True BASIC here. Version 2.01
Copyright (c) 1987 by True BASIC, Inc. All rights reserved. Type SPLIT to see a menu of the function keys.
Ok. | é History Command Line
Window
The upper section is called the editing window (it will be completely blank until you have entered a program, as described below). The lower section is called the history (or command) window. The cursor should be in the history window initially. Press the function key F1 on the left of the keyboard. The cursor moves to the top of the editing window, and a small rectangular blob, called a line tag, appears in the top lefthand corner. Press the function key F2. The cursor moves back to the command line of the
history window. The keys Fl and F2 therefore “toggle” the cursor between the two windows.
You are now ready to enter your first True BASIC program. Press F1 to get into the
4 CHAPTER 1 Sg 8
editing window. Type the following four-line program one line at a time (use the Shift key to get uppercase letters):
PRINT "What is your name’;
INPUT N$
PRINT "Hi there, "; NS
END
Note that the cursor moves as you type each line. At the end of a line, press Return, and a new line tag will appear on the line below.
If you make a mistake, the easiest way to correct it at this stage is to use the Backspace key, which deletes characters to the left of the cursor. If you miss out some letters, move the cursor (using the left and right arrows on the righthand side of the keyboard) to the place where you want them, and type the letters. All the text to the right will be automatically shifted to make room for the new letters.
If you miss out an entire line, move the cursor to the extreme left until it is below the line tag of the line in front of which you want to insert the missing line. Press Return, and a new line will appear. If you want to delete an entire line, position the cursor under the line tag of the offending line, and press the Del key. The whole line disappears. (If you do this by mistake, you can retrieve the most recently deleted line by pressing F7.)
The editing window should now look as shown in Fig. 1-1. Each line in the editing window is called a program statement, and the whole set of four statements is called a program. When the program 1s correct, get back into the history window (with F2). The cursor is now at the command line (the line with ““Ok”’ and nothing else) waiting for you to issue a command. To run (or execute, or carry out) the program, press F9, or type the word “‘run”’ followed by Return. The effect is the same, and the computer should ask you for your name. Type your name (still in the history window), press Return, and it should politely greet you by name. Note that the results, or ““output’’, from the program appear in the history window. This type of program is called “‘interactive”’, because you interact with the computer: it waits for you to do something before it proceeds.
At this stage, the ““Ok”’ prompt should be displayed again in the command line. Run the program again (with F9), giving a different name, and see what happens. To print the program on the printer, make sure the printer is connected, and type the command LIST (you may use either upper or lower case letters) on the command line. To print the output of the program (1.e. the results) type
RUN >>
In the command line. To print whatever appears on the screen, hold down a Shift key, while pressing PrtSc (on the right). As a final experiment, type
PRINT N$ in the command line, followed by Return, and observe what happens. To save the program on a diskette, place a formatted diskette in drive B, and type
SAVE B:greet
GETTING GOING )
in the command line. The red light next to drive B will go on momentarily, and the computer will respond with
4 lines saved.
The program has been saved on the diskette as a file with the name “GREET.TRU” To check that it is there, type
FILES B:
in the command line, and the names of all True BASIC files on the diskette 1n drive B will be displayed in the history window. Note that an extension ‘‘. TRU” has been added to indicate that the file was produced by the True BASIC system. To load a copy of the program from the diskette back into the editing window, first use the NEW command to clear the editing window (this is not strictly necessary), and then type (in the command line)
OLD B:greet
The program should reappear in the editing window. You should be getting the idea by now that the editing window is for the program, while the history window 1s for commands and output. When you have finished the session, and want to get out of True BASIC, type the command
BYE
If you have not saved your current program before issuing the BYE command, True BASIC takes the precaution of asking you whether you want to save it before returning you to the system.
Adding Two Numbers
The next program adds any two numbers and prints their sum. Use the NEW command to clear the editing window (if there is already a program there) and then enter the following four lines:
INPUT A, B
LET SUM = A+B
PRINT "The sum of’; A;"and"; B;"is’; SUM
END
Run the program (F9) and the computer will display a ‘‘?” indicating that it is waiting
for some information (input) from the keyboard. Type the two numbers to be added, on the same line, separated by a comma, so that the whole line looks like this:
f2, 3
Don’t forget to press Return, or you will wait forever! The output of the program 1s:
The sum of 2 and 3 Is 5
Run the program a few more times, using different data each time. Experiment with negative numbers and decimals. (For a minus sign use the hyphen or the minus symbol
on the extreme right. Computers use decimal points, not commas; use the full-stop for this. )
6 CHAPTER 1 a
The way you type the input is important. Run the program and give the input as
2 3,4
(i.e. with a space between the first two digits). Note that it doesn’t like the space. The same response occurs if you type a letter instead of a number for the input. Also try giving it only one number for input and see what happens.
Compound /nterest
Suppose you have $1000 saved in the bank, which compounds interest at the rate of 9% per year. What will your balance be after one year? You must obviously be able to do the problem in principle yourself, if you want to program the computer to do it. The logical breakdown, or structure plan, of the problem is as follows:
1. Get data (initial balance and interest rate) into computer 2. Calculate interest (9% of $1000, i.e. $90)
3. Add interest to balance ($90 + $1000, i.e. $1090)
4. Print out new balance.
Enter the following program into the editing window (type NEW on the command line, if necessary, to clear the editing window):
LET BALANCE = LET RATE = 0.09 LET INTEREST = RATE * BALANCE
LET BALANCE = BALANCE + INTEREST PRINT BALANCE
END
Run the program, and observe that no input is required now (why not?). The output should be the number 1090. Save this program on your diskette under the name “B:MUNNY” for further use later on.
1000
Another way of naming the program is first to type the command NEW B:MUNNY
This names the program you are about to enter (which is called the current program) with the name “B:MUNNY.TRU”. The name appears on the title line between the two windows. When you have finished the program, and want to save it, the command SAVE by itself will save the program on the diskette.
1.4. Editing a Program
By this stage you should be able to enter a short program (designed by someone else) and run it. So far, editing the program has been limited mainly to the use of the Backspace key. In this section we look at some features of the True BASIC Editor.
Before we get started, if you have a colour monitor you might like a change of scenery. Hold down the Ctrl key and press the letter F. The colour of the text changes. Press F again (still holding down Ctrl). The colour changes again. In this way you can cycle
GETTING GOING 7
through all the available colours until you find the one most pleasant to work with. Ctrl-B changes the background colour in the same way, while Ctrl-E changes the colour of the screen edge. Note that the colours in the two windows operate independently.
You may have noticed that the text in the history window soon disappears from view. There are two ways of dealing with this.
Firstly, you can change the relative sizes of the two windows with the SPLIT command. E.g.
SPLIT 10
will cause the line separating the windows to be drawn in line 10 (from the top) of the screen. There are 25 lines on the screen. The default split is at line 18 (the “default” situation in computing is what happens if you do nothing).
Secondly, you can ‘‘scroll’”’ the history window up and down with the PgUp and PgDn keys on the right of the keyboard. The same applies to the editing window when the program gets too long to see all at once.
Get a program into the editing window (e.g. “MUNNY’”’) to experiment with the following editing features.
Cursor Movement Keys
Left arrow left one character
Right arrow right one character
Up arrow up one line
Down arrow down one line
Home top of current window
End bottom of current window
PeUp up One “page” in current window PeDn down one “‘page”’ in current window Tab
Shift-Tab Cirl-Left arrow Cirl-Right arrow
Start of next word or number Start of previous word or number beginning of current line
end of current line
Editing Keys
Backspace delete previous character
Del delete current character Ctrl-Home delete previous word
Ctrl-PgUp delete current word
Esc delete from cursor to start of line Ctrl-End delete from cursor to end of line Del (on line tag) delete current line
F7 restore last deletion or insertion
If you keep an arrow pressed down, the cursor moves continuously. This also applies to most of the other keys, and 1s called key cycling.
If you position the cursor under the last character of the /ongest line of a program, and
S CHAPTER 1 Sn A a then press the up or down arrow, the cursor jumps to the end of the statement in each line.
If the cursor is under a line tag and you press Backspace, the current line is joined to the one above it. If Return is pressed anywhere in a line, the line is split at that point. To get the cursor past the last character in a line use the space bar.
If a character is typed at any point, the characters on its right are all moved to the right. This is the default (usual) mode. If the Ins key is pressed, the cursor changes shape, and characters are overwritten and not moved to the right. This overwrite mode persists
until Ins is pressed again.
When the computer detects an error in a program during execution, an error message is printed in the history window, and the cursor stops at the position of the error in the editing window so that you can begin correcting immediately.
Some more advanced editing features, such as moving or deleting whole blocks of a program, and making global changes, are discussed in section 2.16. As soon as you begin to feel at home in True BASIC you should start to work through these features as they will make your programming much more efficient and enjoyable.
1.5. Handling Program Files on Diskettes
As we have seen, a program may be saved on the diskette in drive B with the command SAVE B:Name
The entity in which it is saved is called a file. The filename may be up to eight characters long, with an extension of up to three characters. The following characters may be used for filenames and extensions:
" the letters of the alphabet:
* the digits 0 to 9:
" the following special characters: !@#$%&()—__{}’
Note that the space is not a valid character. If an extension is used it must be added after the filename and separated from it with a full-stop, e.g.
Name. Ext
Lowercase characters are automatically translated into uppercase. If you do not specify an extension, [rue BASIC assumes ‘“‘.. TRU” for an extension. If you specifically do not want an extension, type a full-stop after the filename, e.g.
SAVE B:NoExt. OLD B:NoExt.
If you try to save a program on a diskette under a filename which already exists, the following message appears:
File already exists. Do you want to overwrite it?
GETTING GOING 9
The response “Y”’ in upper- or lowercase will cause the previous contents to be lost and
replaced by the current program. The response “‘N”’ will protect the diskette file from being overwritten.
To replace an existing diskette file with the current program in the editing window, one usually uses the REPLACE command:
REPLACE B:Name
The previous contents of Name is irretrievably lost, as in the case of SAVE. If you use REPLACE or SAVE without a filename, True BASIC assumes the name of the current program.
The UNSAVE command will delete the named file irrevocably from the diskette.
We have already seen the OLD command, which calls up a file from the diskette into the editing window. Note that OLD will delete the current contents of the editing window
before loading the required program. However, the copy of the file on the diskette remains intact.
NB: When entering (or editing) a long program (i.e. more than about 20 lines) it is wise to SAVE or REPLACE it after every 20 lines or so. This way your work is saved on the diskette In case of power failure, or even a voltage drop, which may cause your computer to
“hang up”’.
NB: Itis wise to make frequent" backup" copies of all your important programs on a separate backup diskette to guard against diskette failure, damage or loss. There are at least two ways of doing this. Once you have saved the current program on the “master’’ diskette (1.e. your usual working diskette), remove the master diskette from drive B, and insert the backup diskette, remembering to lock the drive. Then use SAVE or REPLACE to make a copy of the current program on the backup diskette. Alternatively, you can make a backup copy of a file as follows: call it up from the master diskette with OLD, replace the master diskette with the backup diskette, and use SAVE.
(V5: NEVER touch the diskette in a drive when the red drive light is on. ALWAYS wait for the red light to go off before removing the diskette. Removing the diskette while the light
is on is like removing a record from a gramaphone turntable while the needle is still in the groove! You can corrupt diskette files in this way.
1.6. True BASIC Demonstration Programs
There are a number of demonstration programs on the True BASIC diskette. Use the FILES command to list them in the history window (use PgUp and PgDn to scroll the window if necessary), OLD to call them up into the editing window, and F9 to run them. Listing files often clutters up the history window, and new commands must be issued on the command line, which is the last line of the history window. Use End to get to the end
of the history window. summary
* You can get into True BASIC with HELLO, or HELLO filename, which gets into True BASIC, runs the program filename, and returns to the system.
10 CHAPTER 1
* A program is a set of statements for solving a particular problem.
* Programs are entered in the editing window.
* Commands are entered on the last line of the history window.
* A program may be saved as a file on a diskette, and subsequently loaded back into
the editing window. * An up-to-date backup diskette of all important files should be kept at all times.
* Some useful True BASIC commands are summarized below. These must all be typed
in the command line of the history window, and followed by Return. They may all be abbreviated down to their first three letters. A complete description of all the commands is given in Appendix B.
BYE Gets out of True BASIC.
ECHO Echoes screen output to the printer.
ECHO OFF Turns off the echo.
ECHO TO filename Echoes screen output to a file.
ENTER B: Switches to drive B. ENTER can also be used to change directories. The command CD has the same effect.
FILES Displays names of True BASIC files on diskette in drive A.
FILES >> Echoes FILES listing on the printer.
FILES B:,LEN Displays names and lengths (in bytes) of True BASIC files on diskette in drive B.
EIEES) ** Displays names of all files (IBM PCs and compatibles only) in the default drive.
HELP (or F10) General explanation of HELP.
HELP Topics Gives the list of topics for which HELP is available.
LIST Prints current program on printer without headings or page numbers.
NEW Deletes current program from editing window.
NEW filename OLD filename RENAME newname
RENAME old, new
Clears window and names new current program.
Calls up copy of program from diskette.
Changes current program name, but doesn’t affect any files on diskette.
Changes name of saved diskette file from old to new, but does not change current program name.
REPLACE Saves current program under same name on disk. SAVE
REPLACE filename Saves current program under name filename on SAVE filename disk, overwriting existing file if necessary.
RUN Runs current program,
FQ
RUN >> Runs current program, echoing output to printer.
RUN >> filename SPLIT
SPLIT n
Runs current program, echoing output to file.
Turns display describing meanings of function keys on and off.
Divides screen between editing and history windows at line n (IBM PC and compatibles only).
GETTING GOING 11
UNSAVE filename Deletes file from diskette.
* Apart from cursor movements and editing, the following key combinations are useful:
Ctrl-Alt-Del Reboots system.
Ctrl-Break Stops execution of program.
Ctrl-Scroll Lock
Ctrl-NumLock Suspends execution. Press any key to continue. EXERCISES
1.1 Write a True BASIC program to compute and print the sum, difference, product and quotient of two numbers A and B (supplied by you). The symbols for multiplication and division are the asterisk (‘‘*’’) and forward slash (‘‘/’’) respectively. Use this example to discover how True BASIC reacts to being asked to divide by zero.
1.2 The energy stored on a condenser is CV7/2, where C is the capacitance and V is the potential difference. Write a program to compute the energy for some sample values of C and V.
Solutions to most exercises are given in Appendix G.
CHAPTER 2
FUNDAMENTALS OF TRUE BASIC
We now begin to look in detail at how to write True BASIC programs to solve particular problems. There are two essential requirements for successfully mastering this art:
I. The exact rules for coding instructions must be learnt; 2. A logical plan for solving the problem must be developed.
This chapter is devoted mainly to the first requirement: learning some coding rules. (Appendix A has a “‘quick reference”’ to all True BASIC statements.) Once these are mastered we can go on to more interesting problems.
2.1. Compound Interest Again
In Chapter One you ran the program ‘‘MUNNY” to compute compound interest: LET BALANCE = 1000
LET RATE = 0.09
LET INTEREST = RATE * BALANCE
LET BALANCE = BALANCE + INTEREST
PRINT BALANCE
END
We will now discuss exactly what each line in the program means. When you enter a program, the program lines are stored in part of the computer’s “random access memory’ (RAM). When the program is executed, a different part of this memory is used to store the numbers that are generated by the program. This part of the memory may be thought of as a bank of boxes, or memory cells, or memory locations, each of which can hold only one number at a time. These memory locations are referred to by symbolic names in the program statements. So the True BASIC statement
LET BALANCE = 1000
means “‘put the number 1000 into the memory location named BALANCE”’. Since the numbers in the memory locations may be changed by the program, the names of the locations are called “‘variables’’. The statements in our compound interest program can now be interpreted as follows:
1. Put the number 1000 into memory location BALANCE
2. Put the number 0.09 into memory location RATE
3. Multiply the contents of RATE by the contents of BALANCE and store the answer in INTEREST
4. Add the contents of BALANCE to the contents of INTEREST and store the answer in BALANCE
CHAPTER 2
14
* Print the contents of BALANCE
* Stop.
When the program is executed, all the memory locations are initially set to zero by True BASIC (some versions of BASIC do not do this). The program statements are then executed in order from the top down. After execution, a snapshot of the memory will
show the contents of the variables used as follows:
BALANCE :_ +600/1090
INTEREST : 90
RATE ; 0.09
Note that the original contents of BALANCE (1000) is lost.
Exercises
1. Run the program as it stands. 2. Change the first line to read
LET BALANCE = 2000 and make sure you understand the answer when you re-run the program. 3. Leave out the line
LET BALANCE = BALANCE + INTEREST
and re-run. Can you explain the answer? 4. Rewrite the program so that the original contents of BALANCE is not lost.
A number of questions immediately arise, for example:
* What names may be used for memory locations?
* How can numbers be represented?
* What happens if a statement won’t fit into one line? * How can we organize the output more neatly?
These questions, and many more, will be answered in the following sections.
2.2. Program Format
This section covers the general physical layout of a True BASIC program.
Program Lines
Every Irue BASIC statement starts with a keyword. Keywords used so far are LET, INPUT, PRINT and END. There are two kinds of statements: simple statements, which occupy only one line, and control structures, which may take up many lines.
FUNDAMENTALS OF TRUE BASIC 15
Spaces in lines may be used to improve the readability of a program (spaces do not take up more storage, or use more computer time, as they do in some other versions of BASIC), and blank lines may be used to separate logical sections of a program. However, spaces may not appear in the middle of keywords (e.g. IN PUT is not allowed), and a keyword must always be followed and preceded by at least one space. SO
LETX = 1
is not allowed, but
LET X= 1
is finé. The difference between upper- and lowercase is ignored, except within string constants, which we will come to later in the chapter.
Long Lines
If a statement is too long to fit on the screen, don’t worry: just go on typing! The editor will move the rest of the program to the left as you type. Remember not to press Return until the line is logically finished, no matter how long it is (in fact, it can be up to 32767 characters long).
The END and STOP Statements
Every program must have exactly one END statement, which for the time being must be the last statement in the program. When END is executed, the program stops. There is also a STOP statement, which can be used to stop a program at any point. However, it 1s not generally recommended, since the best place to stop is at the end!
Comments
You may add comments to a program in two ways. Anything following an exclamation mark is ignored, and so is anything on a line which starts with the keyword REM. You may not use REMARK instead of REM, as in other versions of BASIC. E.g.
REM rhubarbrhubarbrhubarb | Youcanwritewhateveryoulikehere ... Cet aS 7 |... Or here
The compound interest program could be made clearer with comments as follows: REM Compound Interest
LET BALANCE 1000 |! Opening balance LET RATE = 0.09 | Interest rate LET INTEREST = RATE * BALANCE
LET BALANCE = BALANCE + INTEREST | New balance PRINT BALANCE
END
16 CHAPTER 2 You should develop the habit of using comments wherever possible to make the logic of your programs clearer fo anyone else reading them. You will also find them helpful yourself, because after a month or so you will have forgotten how a particular program worked.
Line Numbers
If you have had some experience with another version of BASIC already, you will have been immediately struck by the total absence of line numbers! This is because the notorious GOTO statement is no longer necessary in True BASIC (and should in fact never be used). Line numbers were also needed in the bad old days in order to edit a program, but True BASIC’s screen editor enables you to edit very easily without line numbers. However, line numbers are occasionally useful for reference, and for certain types of editing.
In True BASIC, either all or none of the lines must be numbered. Line numbers can be typed immediately after the line tag, and must be entered in the right order. The DO NUM and DO UNNUM commands may be used to insert line numbers into all the lines of a program, or to remove them. DO RENUM renumbers the lines (see Appendix B for more details).
Numbered lines may also be entered directly from the command line, in which case they are automatically inserted at the correct place in the editing window. This can give rise to a curious error. Suppose you forget to enter the RUN command to run the program to add two numbers in Chapter One, and simply enter the data in the command line, so that it looks like this:
Ok. 2, 3
The program will not run. Instead, the line 2,3
will mysteriously appear at the end of the program in the editing window, because True BASIC thinks you have tried to enter a numbered line from the command line.
A numbered line may be deleted from the command line by typing the line number followed immediately by Return.
2.3. Numeric Constants
Numeric constant is the technical term that covers any number used as data in a program. A numeric constant may be expressed with or without a sign, and with or without a decimal point (not a comma). If it has a decimal point it is called a fixed point constant. [he following are all valid numeric constants:
0
1.0 —12345.6789 +0.00023
FUNDAMENTALS OF TRUE BASIC 17
A numeric constant may also be expressed in floating point notation as a number with two parts: the mantissa, which may have a decimal point, and the exponent, which must be an integer (signed or unsigned). Mantissa and exponent must be separated by the letter “e’’. The mantissa is multiplied by the power of 10 indicated by the exponent. E.g.
2.0e2 ( = 200 )
+2e2 ( = 200 ) 4.12e+2 (= 412 ) —7.321e—4 ( = —0.0007321 )
The largest and smallest constants allowed vary with computers, although True BASIC will process numbers in the range 1e—99 to 1e99 on any computer. The special built-in functions MAXNUM and EPS (see Appendix C) may be used to find these values on your computer. On an IBM PC the largest positive number is 1.79769e+308, while the smallest positive number is 5.56268e—308. Numbers are represented with an accuracy of about 14 figures.
2.4. Variables
A variable is the symbolic name used to represent a memory location. It is so named because the value can be changed by a program. In True BASIC, variable names may contain letters, digits, and the underscore character (““__’’). They may be up to 31 characters long, but must start with a letter. True BASIC does not distinguish between upper- and lowercase letters in a variable name.
Six of the True BASIC keywords (ELSE, ELSEIF, IF, NOT, PRINT and REM) are “reserved words”’, and may not be used as variable names. There are 14 other reserved words, listed in Appendix E. A reserved word may however be embedded in a variable name. Below are some examples of valid and invalid variable names.
Valid variable name Invalid variable name (why?) Xx $5
R2D2 | HP41—C
AMA104W REM
endofthemonth 2a
OPRINT
To promote good “‘programming style’, it is suggested that every variable used in a program be described in a comment line, at the start of the program, in alphabetical
order. Many of the examples in this book follow this practice, although not always, in order to save paper.
2.9. Vertical Motion under Gravity
Using simple dynamical laws one can show that if a stone 1s projected vertically upward with an initial speed u, its vertical displacement s after a time ¢ has elapsed 1s given by the formula
s= ut — 0.5g¢,
18 CHAPTER 2
where g = 9.8 m/s*, the acceleration due to gravity. Air resistance has been ignored (the effect of air resistance is discussed in Chapter 15). We would like to compute s, given u and t. Notice that we are not concerned here with how to derive the formula, but how to compute its value. The logical preparation of the problem is very simple:
1. Get values of g, u and ¢ into the computer
2. Compute the value of s according to the formula 3. Print the value of s
4. Stop.
The program Is as follows: |! VERTICAL MOTION UNDER GRAVITY
! DESCRIPTION OF VARIABLES: 1G: ACCELERATION DUE TO GRAVITY 1S : DISPLACEMENT IN METRES 1 T : TIME IN SECONDS |! U : INITIAL VELOCITY IN METRES/SECOND
PRINT “TIME”, “DISPLACEMENT”
LET G = 9.8
-ET U = 60
LET T = 6
LET. SO = U*T—G/2*T* 2 PRINT
PRINT T, S
END
Run this example as an exercise. It is discussed further in Ex. 2.6 at the end of the chapter.
2.6. Programming Style
Programs that are written any old how, while they may do what is required, can be difficult to follow when read again a month or two later. Throughout this book, therefore, attention has been paid to what is called programming style, by which is meant an emphasis on neat and clear physical and logical layout of programs. Guidelines for good style are laid out in the Epilogue.
2./. Arithmetic Expressions
An arithmetic expression is a formula combining constants, variables and functions, using arithmetic operators. It specifies a rule for computing a value.
Arithmetic Operators
There are five arithmetic operators, as follows:
FUNDAMENTALS OF TRUE BASIC 19
Operator Meaning Example + Addition A + 69 — Subtraction X—Y or negation =—— * Multiplication 2* A Division B / DELTA : Exponentiation X*3 (=X*X*X)
In addition, parentheses (brackets) may be used to control the order of evaluation (see below)
Operators may not be juxtaposed. A * — B is therefore not allowed. Write A * (— B) instead.
A* B with a non-integral exponent B is defined in the usual way as Exp( Log( A) * B ). This will cause an error if A is negative. 0 * 0 is defined to be 1. (See Chapter Four for the built-in functions Exp and Log.)
The precision with which expressions are computed varies from machine to machine. However, True BASIC computes expressions to at least 10 digits accuracy on all computers.
It is suggested that spaces be typed on either side of an operator, to make programs more readable. This is done throughout this book.
Precedence of Operators
Since an expression may contain many operators, it is necessary to know in what order the computer evaluates operations. The order of precedence is as follows: Order Operation
Ist Parentheses
2nd Exponentiation
3rd Multiplication and division
4th Addition, subtraction and negation
When operators with the same precedence occur in the same expression, an ambiguity could arise. For example, does A/B * 3 mean A/ (B * 3) or (A/ B) * 3? To resolve this, operations with the same precedence are always evaluated from left to right. So this expression is in fact evaluated as (A / B) * 3.
2.8. The LET Statement
This statement enables you to assign a value to a variable, usually after computing the
value of an expression. It is technically called an assignment statement. Its general form 1S
LET var = expr Or LET varl, var2, ... = expr
where var, varl, etc., stand for any variable, and expr stands for any expression. The
0) CHAPTER 2
ellipsis (...) means you can have as many items as you like in the line. Since every True BASIC statement must begin with a keyword, the LET is mandatory by default (unlike in most other versions of BASIC). The expression on the right 1s first evaluated, and then assigned to each variable in the list, from left to right. E.g.
LET X =A+B LET X, Y, Z = 1 The equal sign does not have the same meaning as in mathematics, and should be read
as “become”. So the first statement above should be read as “Let X become A plus B”’
or more literally “Let the contents of X become the contents of A plus the contents of B
Examples
The formulae
F = GME/r,
c= V(a? + b*)/(2a),
A = P(1 + 7/100)”
may be translated into the following True BASIC statements: LET F=G*M*E/R% 2
LETC =(A*2+B%°2)°05/ (2 * A)
LET A =P*(1+R/100)°*N
2.9. The PRINT Statement
To help you discover some of the rules for PRINT, call up the compound interest program “MUNNY” (discussed at the beginning of the chapter) and carry out the following experiments.
Replace the PRINT statement with
PRINT INTEREST, BALANCE
and see what happens when you run the program. Then try
PRINT INTEREST; BALANCE
to see what difference the semi-colon makes. Then try two separate PRINT statements,
as follows:
PRINT INTEREST, PRINT BALANCE
Then try
FUNDAMENTALS OF TRUE BASIC 2]
PRINT “Interest:”; INTEREST, "New balance:”; BALANCE Then see if the next two lines make any difference:
PRINT “Interest:”; INTEREST PRINT “New balance:”: BALANCE
Next try three lines:
PRINT INTEREST PRINT PRINT BALANCE
Finally try PRINT TAB( 5 ); BALANCE
Basic Rules for PRINT
The PRINT statement may include messages enclosed in double quotes (these are called strings), and/or variable names, and/or expressions (all of these will be referred to as items). For the purposes of PRINT, the screen has a margin, or maximum screen width (S80 columns on the IBM PC). The screen is also divided into five print zones, each 16 columns wide. A comma after an item means that the next item will be printed in the next print zone on the screen, and on the same line (if there is room), even if its PRINT statement 1s further down in the program. In other words, a comma at the end of a PRINT statement leaves the cursor “hanging” at that position waiting for the next PRINT. If the last print zone is full, the cursor moves to the start of the next line. You may have several commas in a row to skip past print zones, e.g.
PRINT 5.4: You can change the width of the print zones and adjust the margin with the statements
SET ZONEWIDTH expr
SET MARGIN expr
where expr is any numeric expression with a meaningful value. The changes take effect Immediately. You can find out the current widths with the statements
ASK ZONEWIDTH var ASK MARGIN var
where var is a variable. These statements may also be issued as commands on the command line of the history window (see section 2.17).
A semi-colon after an item in a PRINT statement holds the cursor at that position, 1.e. it does not move to the next print zone.
The absence of a comma or semi-colon after the last item in a PRINT statement means that the next item to be printed will be printed on a new line. An empty PRINT statement has the effect of printing a blank line, if the preceding PRINT does not have a comma or semi-colon after its last item.
Positive numbers are printed with a leading space. Negative numbers have a leading
22 CHAPTER 2
minus sign. All numbers have a trailing space, even if printed with a semi-colon. So a positive number in the second print zone will actually start in column 18.
If a number is an integer with 12 or fewer digits, it is printed in full. If the number can be represented with a decimal point and six or fewer significant digits, it will be. Otherwise it will be printed in standard scientific notation (floating point), 1.e. as ‘‘~—d.ddddde+dd”’, where each ‘‘d”’ stands for a digit, ““—”’ stands for either a space or a minus sign, and ‘“‘+”’ stands for either a plus or minus sign. The leading digit will be between 1 and 9. Numbers are rounded to six significant digits, if necessary, before printing. If you want greater accuracy, use the PRINT USING statement (Chapter Eight). PRINT USING also enables you to get neater output, like numbers which are right- justified.
The TAB function in a PRINT statement moves the cursor to the position on the print line indicated by its argument. E.g.
PRINT TAB( 23 );
moves the cursor to column 23 of the current output line. If the cursor is already past that position, it moves to the next print zone. If a semi-colon follows the TAB, the cursor remains at that position. If a comma follows, the cursor moves to the next print zone.
The two-dimensional TAB gives you more control over the cursor: PRINT TAB( row, column ): Rows are numbered from the top of the screen, starting at 1. The first such TAB clears
the screen, which “‘freezes”’ until you press (almost) any key. You can use this statement to put the cursor anywhere on the screen.
It is good programming style to type spaces after all commas and semi-colons In PRINT statements.
Printing Output on the Printer
There are a number ways of doing this. The easiest is to type “>>"’ after the RUN command to echo output on the printer (make sure that the printer is connected).
You can also print the contents of the screen at any time by pressing Shift-PrtSc. The problem with this is that you may get both editing and history windows in the printout, which is a bit messy. There are at least two other ways, which are more subtle. Enter the following program, and run it:
CLEAR
PRINT "This is a clean screen”
END
You should have a beautiful clean screen, with no cursor, and no history or editing windows. You have basically got into a third window, or full-screen mode (see Chapter 12). If you press Shift-PrtSc now, the screen will be printed. To get the history and editing windows back, press any other key.
The second way is to start your program with the statement
FUNDAMENTALS OF TRUE BASIC 23
OPEN #1: PRINTER and to use PRINT #1: whenever you want to print on the printer, e.g.
| Printing to printer and screen: connect the printer first! OPEN #1: PRINTER
PRINT “This will be on the screen”
PRINT #1:"But this will be on the printer’
END
Variables can be printed like this too: PRINT #1: X, Y; TAB( 43 );"The answer is:”; Z There is more about this in Chapter Eight.
2.10. The INPUT Statement
In the compound interest program ‘“MUNNY’” the data for the program was supplied with two LET statements:
LET BALANCE = 1000 LET RATE = 0.09
This is a rather inflexible way of supplying data, since to run the program for different balances or interest rates you would have to change these statements, and there may be many such assignment statements in a more complicated program. The INPUT state- ment, however, which we saw in Chapter One, allows you to supply the data while the program is executing, rather than before execution, as in the case of the assignment statement. One form of the INPUT statement is
INPUT varl, var2, ...
Change the ‘““MUNNY” program so that first two LET statements are replaced by the single statement
INPUT BALANCE, RATE
When you run the program, the computer prints a question mark on the screen in the history window and waits for you to type the two numbers, which must be separated by a comma, after which you must press Return. The line on the screen will look like this:
? 1000, 0.09
You can enter the numbers over two (or more lines) as long as you end each line with a comma to show that there is more data coming:
? 1000, ? 0.09
If you make a mistake with the input, like typing a letter instead of a number, True BASIC does not “‘crash”’ the program, but asks you to retype the errant data.
24 CHAPTER 2
INPUT with a Prompt Change the “‘MUNNY” program to look like this:
INPUT PROMPT "Old balance: ”: BALANCE
INPUT PROMPT "Interest rate: ”: RATE
LET INTEREST = RATE * BALANCE
LET BALANCE = BALANCE + INTEREST
PRINT "The new balance is”; BALANCE
END
Instead of a question mark, the prompts “Old balance: ” and “Interest rate: ” will appear on the screen. Each time, the computer will wait for your response. The general form is
INPUT PROMPT "Message": varl, vard, ...
INPUT with a Trailing Comma
If the last variable in an INPUT statement is followed by a comma, you may enter more data in response to the prompt than is needed. The leftover data will be kept and read
by subsequent INPUT statements. This is particularly useful if you want to avoid getting the output cluttered up with input prompts, e.g.
FOR | =1TO 5 INPUT X, PRINT X * 2:
NEXT |
END
Ok. run
? 1,.2,°3, 4, 5
1 4 9 16 24
2.11. The FOR-NEXT Statement
Square-rooting with Newton
The square root X of any positive number A may be found using only the arithmetic operations of addition, subtraction and division, with Newton’s method, which is explained more fully in Chapter 15. The structure plan of the algorithm, and the program with sample output for A = 2, is as follows:
1. Input A
2. Initialize X to 1
3. Repeat 6 times (say) 3.1. Replace X by (X¥ + A/ X)/2 3.2. Print X
4, Stop.
1 SQUARE-ROOTING WITH NEWTON
CLEAR INPUT PROMPT “Number to be square-rooted: ”: A
FUNDAMENTALS OF TRUE BASIC 25
LET X = 1
FOR | = 1 LET X =
PRINT X
NEXT |
END
TO 6 (X + A/X)/2
Output:
Number to be square-rooted: 2 15
1.41667
1.41422
1.41421
1.41421
1.41421
The values of X “‘converge”’ to a limit, which is the square root of A. Most computers and calculators use a similar method internally to compute square roots and other built-in mathematical functions (see Chapter Four).
The new statement used here is the FOR-NEXT, which is one of the most powerful
statements in any programming language. It is discussed more fully in Chapter Six. Its simplest form is:
FOR/ = JTO K
NEXT /
where / is any variable and J and K may be constants, variables, or expressions. All the statements between FOR and NEXT will be repeatedly executed. The numerical values of J and K determine how many repeats are made. On the first loop, J is given the value of J, and is then increased by 1 at the end of each loop. Looping stops once J has reached the value of K, and execution proceeds with the statement after NEXT. J will have the value K+1 after completion of the loop.
The next program is a variation on the compound interest problem. Suppose we have to service four different savings accounts, with balances of, say, $1000, $500, $758 and $12750 respectively. We want to compute the new balance in each of them after 9% interest has been compounded. Try the following program out. The results may look slightly different to what you have seen so far.
CLEAR LET RATE = 0.09
FOR | = 1 TO 4 ASK CURSOR LINE, COL INPUT PROMPT "Old balance: ”: OLDBAL LET NEWBAL = OLDBAL + RATE * OLDBAL PRINT TAB( LINE, 30 ); "New balance:’; NEWBAL NEXT | END
26 CHAPTER 2
The ASK CURSOR statement puts the current line and column number of the cursor into the variables LINE and COL, where the top line (row) on the screen is line 1, and the leftmost column is column 1. The TAB function positions the cursor in the row according to the value of the variable LINE. Since the value of LINE is set by the ASK CURSOR statement, the effect is to keep the cursor on the same line as the input prompt, with the result that the output is printed on the same line. The value of COL is not actually used in this example, but the syntax of the ASK CURSOR statement requires a variable there. To find out the maximum number of lines and columns on your screen, you can use the statement
ASK MAX CURSOR LINE, COL
Instead of the TAB function you can use the SET CURSOR statement to position the cursor:
SET CURSOR LINE, COL
You can switch the cursor off or on with
SET CURSOR “off” 'UPPER or lowercase or miXEd SET CURSOR "on"
or find out whether it is on or off with
ASK CURSOR var$
where var$ is a string variable (see section 2.15).
Note that good programming style requires that statements inside a FOR-NEXT loop be indented to the right a few columns. If you forget to indent, or get the margin looking somewhat ragged, the DO FORMAT command will indent the program neatly for you.
You can also find out in section 2.16 how to shift whole blocks of a program to the left or right.
Differential Interest Rates
Most banks and building societies offer differential interest rates. Suppose in the above example that the rate is only 9% for balances less than $5000, but 12% otherwise. We can easily amend the program to allow for this by deleting the second statement (LET RATE = 0.09) and Inserting a new statement after the INPUT statement, as follows:
INPUT PROMPT "Old balance: ": OLDBAL IF OLDBAL < 5000 THEN LET RATE = 0.09 ELSE LET RATE = 0.12 LET NEWBAL = OLDBAL + RATE * OLDBAL
Try this out to verify that it works. We will discuss the IF-THEN-c:LSE statement more fully below.
2.12. Final Course Mark
The final course mark of students attending a certain university course is calculated as follows. Two examination papers are written at the end of the course. The final mark
FUNDAMENTALS OF TRUE BASIC 27
is either the average of the two written papers, or the average of the two papers and the class record mark (all weighted equally), whichever is the higher. The following program computes and prints out each student’s final mark, with the result PASS or FAIL (50% being the pass mark).
100 ! FINAL MARK FOR COURSE BASED ON CLASS RECORD AND EXAMS 110
120 ! CRM ; CLASS RECORD MARK
130 ! EXMAVG : AVERAGE OF TWO EXAM PAPERS 140 | FIN ; FINAL MARK FOR COURSE
150 |! P1 ; MARK FOR PAPER 1
160 ! P2 ; MARK FOR PAPER 2
170 ! oTU : STUDENT COUNTER
180
190 CLEAR
200 PRINT "CLASS RECORD”, "EXAM AVERAGE’, "FINAL MARK” 210 PRINT
220
230 FOR STU = 1 TO 3
240 READ CRM, Pi, P2
250 LET EXMAVG = (P1 + P2) / 2
260 IF EXMAVG > CRM THEN LET FIN = EXMAVG ELSE LET FIN =...
.. (P1 + P2 + CRM) /3 270 PRINT CRM, EXMAVG, FIN,
280 IF FIN >= 50 THEN PRINT ”"PASS” ELSE PRINT “FAIL” 290 NEXT STU
300
320 DATA 40, 60, 43
330 DATA 60, 45, 43
340 DATA 13, 98, 47
350 END
Note that line numbers have been used for ease of reference. Line 260 is printed on two lines because it 1s too long to fit on the printed page; it should be one line in your editing window. Each student’s class record mark and two examination marks are entered ina DATA statement whence they get into memory by means of the READ statement when the program is run, instead of by means of INPUT. The READ-DATA statements are discussed more fully below. They are extremely useful when developing a program that requires a fair amount of test data, since the data does not have to be entered all over again each time the program is run.
Kun the program as it stands. Note that the trailing comma in line 270 ensures that the comment PASS or FAIL is printed on the same line as the marks.
2.13. Deciding with IF-THEN-ELSE
In the above example we see a situation where the computer must make decisions: whether or not to include the class record, and whether to pass or fail the student. The programmer cannot be sure which of these possibilities will occur when writing the program, so it must be designed to allow for all of them. We need a conditional branch
28 CHAPTER 2
instruction, which is another of the most powerful facilities in any programming language. Its simplest form in True BASIC 1s
IF condition THEN si ELSE s2
where condition is a logical expression having a truth value of either true or false, and sl and s2 are any True BASIC statements. If the condition is true, s/ is executed (and not s2), otherwise s2 is executed (and not s/). The ELSE part of the statement is optional, and may be left out. Execution continues in the normal sequential way with the next statement after the IF.
The condition may be formed from numeric expressions with the relational operators (<, <=, etc.), and from logical expressions with the logical operators (NOT, AND, OR). These are all discussed fully in Chapter Five.
For example, suppose we wanted to print out the class (grade) of each student’s final mark in the above program. We could replace line 280 by the following lines:
272 IF FIN >= 75 THEN PRINT “I”
274. IF FIN >= 70 AND FIN < 75 THEN PRINT "Il+” 276 IF FIN >= 60 AND FIN < 70 THEN PRINT "Il—” 278 IF FIN >= 50 AND FIN “Ill”
280 IF FIN <50 THEN PRINT "FAIL"
The PRINT in each statement is executed only if both conditions are true. The temptation is to write something like
274 IF FIN >= 70 AND < 75 THEN PRINT "II+”
since this is how we tend to say it in English. But this is wrong since AND must join two logical expressions, and ‘‘< 75”’ is not a logical expression (it doesn’t have a truth value).
2.14. The READ-DATA Statements
This is the third way of assigning values to variables (along with LET and INPUT). It is less flexible than INPUT but is better to use when large volumes of data are involved, or when the programmer is not sure how many numbers will appear in each DATA statement (the DATA part may be added by someone other than the person writing the main part of the program). The general form is
READ varl, var2, ... DATA consl, cons2, ...
When the program starts, the ‘data pointer” points to the first item in the first DATA statement, which is read into the first variable mentioned in the first READ statement. Each subsequent READ statement reads another item from the DATA statements, in order, as if all the DATA statements were in one huge DATA statement. The data pointer moves along one item at a time, no matter how many READ statements may have been involved. E.g¢.
READ A, B READ C, D PRINT A; B; C; D
FUNDAMENTALS OF TRUE BASIC 29 DATA 7, 13, —5 |! here are some data ...
DATA 17 |... here is the rest
END
Ok. run
7 13-5 17
If there are not enough DATA items to satisfy the READs, an error occurs. There are two statements (MORE DATA and END DATA) which can be used to detect if there is any more data before an attempt is made to read it. These are discussed in Chapter Six.
The DATA statements may be placed anywhere in the program before END. It is good practice to group them all together.
The RESTORE statement “‘rewinds” the spool of data, and sets the data pointer back to the first data item in the program. Its form is simply RESTORE
There is more about DATA in the next section.
2.15. Strings
A glaring problem with the student mark program above is that the students’ names are not printed out! To remedy this, we introduce the concept of a string variable. Make the following changes to the program in section 2.12. Add line 145:
145 | NAME$ — : STUDENT'S NAME
Then change the following lines:
200 PRINT "NAME", "CLASS RECORD”, "EXAM AVERAGE", "FINAL MARK”
240 READ NAMES, CRM, P1, P2
270 PRINT NAMES, CRM, EXMAVG, FIN,
320 DATA ABLE E.R., 40, 60, 43
330 DATA BOTHA B.J., 60, 45, 43 340 DATA SMITH Z.Z., 13, 98, 47
If you run the amended program you should get output like this:
NAME CLASS RECORD EXAM AVERAGE — FINAL MARK
ABLE E.R. 40 219 91.5 PASS BOTHA BJ. 60 44 49.3333 FAIL SMITH Z.Z. 13 72.9 72.5 PASS
string Constants
There are actually two fundamentally different types of constants and variables in True BASIC: numeric and string. A string constant must be enclosed in double quote (” ") marks. True BASIC distinguishes between lower- and uppercase letters only in the case of string constants. So “BASIC” is not the same “‘Basic’’. A string constant may be as long as 32000 characters (longer on some machines, e.g., 65528 on the IBM PC).
The null (empty) string has no characters in it: "". However, the space (blank) is
3() CHAPTER 2
different to the null string, and spaces in string constants are retained: ” ”. A double quote mark may be included in a string constant by typing it twice:
"He said, ’’Follow me.””"
String Variables
A string variable may only store a string constant, in the same way as a numeric variable stores a numeric constant. The rules for string variable names are the same as for numeric variables, except that the string variable name must end with a dollar (‘‘$’’) symbol. This symbol counts as one of the 31 allowable characters in the name.
String values may be assigned to string variables with LET statements:
LET John8_32a$ = "You will know the truth,”
LET John8__32b$ =” and the truth will make you free.” PRINT John8__32a$; John8__32b$
END
Ok. run
You will know the truth, and the truth will make you free.
Note that strings are printed exactly as they are with no leading or trailing blanks.
String values may also be assigned with INPUT and READ statements, as we saw in the amended student mark program above. Leading and trailing spaces are removed, unless the string constant is enclosed in double quotes. If you want to enter a comma in a string, the string must also be enclosed in double quotes. E.g. the program segment
READ D$
READ D
PRINT D; D$
DATA "November, 1946”, 21 END
will result in the output 21 November, 1946 but if the quotes in the DATA statement are removed, the output will be
1946 November
and the value 21 will be left to be read into the next numeric variable appearing in the next READ further down the program (which may not be what you intended!).
If a comment character (“‘!’”) is to be read as data from a DATA statement, the string containing it must also be enclosed in double quotes. Numbers enclosed in double quotes in DATA statements, such as ‘‘1946’’, may be read as either numeric or string values.
If double quotes are to be read or input, they must be repeated, and the string containing them must be enclosed in double quotes, e.g.
READ V$
PRINT V$
FUNDAMENTALS OF TRUE BASIC 31
DATA "Pilate Said, "What is truth?” END
Ok. run Pilate said, "What is truth?”
To read or input the null string, it must be enclosed in double quotes (“”’).
If null strings, or commas or double quotes in strings are going to occur frequently in response to INPUT statements in a program, it may be easier to use the LINE INPUT statement, which reads the whole line of input as a string, whatever it is. E.g.
LINE INPUT V$ END
Ok. run ? Pilate said, "What is truth?”
The general form is
LINE INPUT varl$, var2$, ... LINE INPUT PROMPT prompt$: varl$, var2$, ...
Consecutive lines of input are assigned to the string variables one at a time, from left to right. Note that the prompt in the (LINE) INPUT statement may be a string variable.
Concatenation of Strings
The only string operator is the ampersand (‘‘&’’), which concatenates (joins) strings. FE.g. the statement
LET NUTS ="”NA” &"POLE” & "ON" produces the string "NAPOLEON”.
There is more about strings in Chapter Ten.
2.16. Advanced Editing
In this section we discuss some of the more advanced features of the True BASIC screen editor. You should try out the commands and function keys described below on a test program, as they will increase your programming skill and enjoyment no end. To test the facilities that move blocks of lines around, it is suggested that you enter a dummy program with the integers 1, 2, 3, ... on separate lines, and nothing else. You will then easily be able to see what happens to the lines when you move them.
Editing Keys
We have already seen some of these features. Pressing Del when the cursor is on a line tag deletes that line, while pressing Backspace when the cursor is on a line tag joins the line on to the previous one. The Ins key toggles between inserting (the default mode) and overtyping.
32 CHAPTER 2
A whole block of lines can be marked for editing as follows. Move the cursor to the line tag of the first line of the block you want to edit, and press F4 (the MARK) key. The line tag is highlighted. Now move the cursor to the line tag of the last line in the block, and press F4 again. All the line tags in the block are highlighted, indicating that the whole block is marked. The block may be unmarked by pressing F4 with the cursor on any line tag in the block, or by marking another block (although in this case the highlighting of the previous block does not disappear on some computers).
If you press the Del key now, the entire marked block is deleted. The RESTORE key (F7) reinstates the deleted block.
You can copy the block as follows. Move the cursor to the line tag below which you want to copy the block. Press the COPY key, F5, and a copy of the marked block will appear immediately below the current line. F7, which undoes the most recent editing operation, will delete the copy. F5 also works in the history window. If you press F5 on the command line, the previous entry is copied to the command line, which can then be edited if necessary (you still have to press Return to activate the command). F5 on any other line in the history window copies that line to the command line.
A marked block can be moved, as opposed to copied, with the MOVE key (F6).
If the cursor is on a line tag in a marked block, the entire block will move one column to the right (left) every time you press the > (<) key.
The F3 key enables you to find text in the program. Suppose you want to find the word Name$. Move the cursor to the top of the editing window, and press F3 followed by the wanted word:
Find: Name$
After you press Return, the cursor will move to the first occurrence of Name$ beyond the current line. Each time you press F3 and Return, without entering new text to find, the next occurrence of Name$ is found. The distinction between upper- and lowercase IS ignored, unless you enclose the search string in double quotes, in which case you may also search for parts of words. The equivalent command to F3 1s LOCATE.
Shift-F1 and Shift-F2 are “vertical tab” keys which move the cursor up or down from the current line to the next line which has Jess indentation, or the next line with equal Indentation after an intervening blank line.
Shift-F4 sets a ‘‘bookmark” at the current line. changing the shape of the line tag. The previous position of the bookmark is lost. Shift-F3 will find the bookmark.
Pressing the ! key with the cursor on any line tag of a marked block will ‘‘comment out”’ the block by inserting a ‘‘!”’ at the beginning of each line in the block. Any marked lines which are comments will have the “‘!”” removed. If the marked block has a mixture of commented and uncommented lines the mixture will be reversed.
The special editing keys are summarized in Appendix A.
Instead of using the function Keys, you can use the COPY, LOCATE, MARK and MOVE commands, which are more general. They are described in Appendix B.
FUNDAMENTALS OF TRUE BASIC 33
Editing Commands
The commands mentioned briefly in this section are all discussed fully in Appendix B. The CHANGE command lets you change all occurrences of text:
CHANGE Name$, SurName$
This command is restricted to whole words or numbers unless you enclose the strings in double quotes, in which case the distinction between upper- and lowercase is observed.
TRY is similar to CHANGE, except that True BASIC stops after each match is found to ask whether or not you want to change that particular match.
All editing can be restricted to a particular block of lines, by marking the block, and then using the EDIT command.
DO FORMAT may be used to convert all keywords to uppercase, indent control structures and line up comments.
DO PAGE will print a program on the printer with page numbers headed with the time and date. If an optional heading is given, it is printed at the top of each page: DO PAGE, My First Program!
2.1/7. Using True BASIC Statements as Commands
Many True BASIC statements can be typed on the command line, and have immediate effect, e.g.
Ok. LET X OK LET Y= Ok. PRINT X 3
| +p -
Y
You can therefore use the computer directly as a calculator. After a program has executed, all the program’s variables are still active and available for use with immediate statements. This is particularly useful when debugging (finding and removing errors), since you can use PRINT as a command to print out any of the variables. Any variables that you may use in this way that were not used by the program are automatically all initialized to 0 or **”’. See Appendix B for more details.
2.18. Odds ’n Ends
This section contains various items of information which may be helpful at this stage of your programming development.
Representation of Information in a Computer
The basic unit of information inside a computer is the bit: something which has only two possible states, usually described as ‘‘on”’ and “‘off’’. Electronically this is very easy to represent, as a current can be either on or off, or a magnetic field can be orientated either clockwise or counterclockwise. The binary digits 0 and 1 can therefore be used
34 CHAPTER 2
to represent these two states mathematically (hence the term digital computer). The word “‘bit’’ is a contraction of “binary digit”.
Numbers in a computer’s memory must therefore be represented in binary code, where each bit in a sequence stands for a successively higher power of 2. The decimal numbers 0 to 15, for example, are coded in binary as follows:
Decimal Binary Decimal Binary 0 0000 8 1000 I QQ01 9 1001 2 0010 10 1010 3 0011 11 1101 0100 12 1100 3 Q101 13 1101 6 0110 14 1110 7 0111 15 1111
In the computer’s memory, bits are grouped together into words, usually of 32 bits. A byte is the amount of storage required for one character, and is eight bits long. Since each bit can be in two possible states, this gives 2°, i.e. 256, different combinations.
Microcomputer memory size (and diskette capacity) is measured in bytes, so 64K, for example, means about 64000 bytes (since 1K means 1024). This chapter takes up 74142 bytes on a diskette because it has that many characters in it. Microcomputers are sometimes referred to as 8- 16- or 32-bit machines. This describes the length of the units of information handled by their microprocessors, or ‘‘chips”. The longer these units, the faster the computer.
Compilers and Interpreters
Since the computer can only understand binary code, all instructions to it must ultimately be translated into this form. A compiler is a sophisticated program which translates your program statements (i.e. in True BASIC) into a machine readable form called machine code. This is collected together into a single entity, and stored in the memory. You may have noticed a slight delay after you press F9 before the results come onto the screen. This is the time taken to compile the program. If you don’t change the program, and run it again, it runs that much faster, because it doesn’t need to be recompiled. This is much more noticeable with larger programs. Compiling and executing are therefore two entirely different processes. When a program does not work, it is very important to know whether the error (or ‘“‘bug’’?) occurred during eee or run-time. This should be clear from the error messages generated by True
An interpreter also translates a program into machine code, but only one line at a time, and then again and again as each line is repeated in a FOR-NEXT loop, say. The machine code is not stored each time. This has two disadvantages. Execution time 1s longer, and error checking is only done line by line, and not globally, as is the case with a compiler. Sia of BASIC tend to use interpreters, whereas True BASIC uses a compiler.
There is more about errors in Chapter Seven.
FUNDAMENTALS OF TRUE BASIC 35
Operating systems
The operating system is a special program which controls the ‘whole show” while you are using the computer. It sits in the ‘‘system’’ tracks of the system diskette you are using, and is automatically loaded into memory when the computer is booted up. The operating system you are usin g is probably MS-DOS, which stands for Microsoft Disk Operating System, often simply called DOS.
All commands typed in response to the system prompts A> or B> are commands to DOS. So when you type HELLO to start True BASIC, DOS searches the diskette in drive A for a “‘command” file called HELLO.EXE, and loads it into the RAM (random access memory). When you enter a program, DOS puts it into another part of the RAM, together with all the variables generated by the program. You therefore have indirect control of the RAM, as opposed to the “read only memory” (ROM).
The ROM contains special programs, like the BIOS (Basic Input-Output System), which is responsible for all the built-in support of the PC’s input-output devices, such as the display screen and the diskette drives.
DOS also controls all the file handling and printing facilities.
summary
_F —
* Successful problem solving with a computer requires knowledge of the coding rules and a sound logical plan.
* All True BASIC statements start with a keyword.
o. 7
' Simple statements occupy only one line. Control structures occupy many lines.
* Comments may be typed after a comment character (“!’’). They help to explain what IS goIng ON In a program.
i. io
* Line numbers are optional.
Fr —_
* True BASIC has two types of constants and variables: numeric and string.
=F = -o
* Numeric expressions may be formed from numeric constants and variables with the tive arithmetic operators and the parentheses, which operate according to strict rules ot precedence.
oF a am:
* PRINT 1s used to print numbers and strings.
oF v.
Data may be entered from the keyboard while a program is running in response to an INPUT statement.
a a cy
‘ Data stored in a program in a DATA statement may be read with a READ statement.
a ow
* FOR-NEXT 1s used for repeating a set of statements.
Pp _
* IF-THEN-ELSE enables a program to decide between alternatives.
* The CLEAR statement enables you to get into full-screen mode.
* String constants are strings of characters enclosed in double quotes. * Concatenation is the only string operation.
* Many True BASIC statements may be used as commands (immediate statements).
= CHAPTER 2 EXERCISES 2.1 Evaluate the following True BASIC expressions, given that A = 2, B = 3, C = 4: LET X =A/2* 8B ( 3, not 1/3 ) LET X =A/B%2 ( 2/9 ) LET X = (A/ B) * 2 ( 4/9 ) LET X =A+B* C-—4 (10) LET X =A*%2*B/C+3 (6) LET X = A * (2*B)/(C +3) (64/7) LETX =A*B+C (10) LET X =A*B°*A ( 64 ) LET X == 4° A ( —16 )
Live
Ld
2.4
2.5
Decide which of the following constants are not acceptable in True BASIC, and
State why not: (a) 9.87 (b) .0 (c) 25.82 (d) 12,68 (e) 3.57*e2 (f) 3.57e2.1 (¢) 3.57e+2 (h) 3,57e—2
State, giving reasons, which of the following are not acceptable True BASIC variable names:
(a) A2 (b) 2A (c) 99$ (d) "A" (e) LET (f) MIN*2 (2) A+1 (h) pay day (i) $MONEY (j) PI (k) r2d2! (1) final_mark
Translate the following expressions into True BASIC expressions:
Ww Po wa 73 Ww : Ww uty Gee (b) pt aa (C) — (d) x oi u—y
(e) x25 (f) 0-5 (zg) yy tz (h) (x)? (i) 2)
aS Pe)
. ted (J) x 31 SI
—b + (b* — 4ac)*>
(k) =
Translate the following into True BASIC statements:
(a) Add 1 to the value of | and store the result in |.
(b) Cube |, add J to this, and store the result in |.
(c) Set G equal to the larger of the two values E and F. (d) IfD is greater than zero, set X equal to minus B.
(e) Divide the sum of A and B by the product of C and D, and store the result in X.
FUNDAMENTALS OF TRUE BASIC 37
2.6
2.1
2.8
£9 2.10
2.11 Bike
This question refers to the vertical motion example in section 2.5.
(a) Run the program as it stands. Try to work out whether the stone is moving up or down.
(b) Re-run for different values of ¢t. In particular, use the program to find out where the stone is after 20 seconds, and interpret your results physically.
(c) Rearrange the formula to compute when the stone returns to the ground.
(d) Rearrange the formula to compute when the stone is at any particular height, i.e. calculate ¢, given u and s. Interpret your results physically.
Try to work out the output of the following program before checking your results on the computer:
READ X, Y
READ N$, M$
PRINT X; Y; NS; M$
DATA 1.2
DATA 3, PLONK, "JONES, 1.”
END
Write some lines of True BASIC which will exchange the contents of two variables A and B, using only one additional variable T. Try Ex. 2.8 without using any additional variables!
What are the values of X and A after the following program has been executed? LET A = 0
LET | = 1 LET X = 0 LETA=AC+ | LET X =X+I1/A LET A=A+I LET X = X+1/A LET A=A +1 LET X = X+I1/A LET A=A + | LET X = X+I1/A
Rewrite the program in Ex. 2.10 more economically by using a FOR-NEXT loop.
Work out by hand the output of the following program:
LETN =4
LETS =0
FOR K=1TON
LETS =S+1/(K* K) NEXT K
PRINT (6 * S) * 0.5
END
If you run this program for larger and larger values of N you will find that the Output approaches a well-known limit.
fad
S
2.13
2.14
2.15
2.16
CHAPTER 2
Try to spot the syntax errors (1.e. mistakes in coding rules) 1n this program before running it on the computer to check your answers with the error messages generated by the computer:
READ A, B LETC +i1=A
B = (A + 1)(C + 2) LET D = (A + (B/ 2A) PRINT ‘THE ANSWER IS’: A:B
END. A student makes a regular deposit of $20 each month into his bank account. Interest is compounded at the end of each month, after the deposit has been made, at the rate of 1.5% per month. He starts with nothing in the account. Write a program which prints out, under suitable headings, the interest and month end balance each month for two years. The steady-state electric current J flowing in a circuit that contains a resistance, capacitance and inductance in series is given by
E V[R?+(2nFL - 1 )?]
2UFC
where E, R, L, C and F are the input voltage, resistance, inductance, capacitance and angular frequency respectively. Translate this formula into a True BASIC
statement.
Suppose Income Tax is calculated as follows:
Taxable Income Tax Payable
less than $10000: 10% of taxable income
between $10000 and $20000: $1000 + 20% of amount by which taxable income exceeds $10000
between $20000 and $40000: $3000 + 30% of amount by which taxable Income exceeds $200000
more than $40000: $9000 + 50% of amount by which taxable
Income exceeds $40000 Write a program which prints out neatly the taxable income and tax payable for the following taxable incomes: $5000, $10000, $15000, $22000, $30000, $38000 and $50000. You should use a FOR-NEXT loop, and READ-DATA for the data. Check some of your answers by hand.
CHAPTER 3
PROGRAM PREPARATION
Our examples so far have been very simple logically, since we have been concentrating on the technical aspects of writing True BASIC statements correctly. However, real problems are far more complex, and to program successfully we need to understand the program thoroughly, and to break it down into its most fundamental logical Stages. In other words, we have to develop a systematic procedure, or algorithm, for solving the problem. There are a number of methods which assist in this process of algorithm development. In this chapter we outline two: flow-charts, and structure plans (Ellis, 1982), which have already been mentioned briefly.
3.1. Flowcharts
The flowchart approach is rather old-fashioned, and tends to be frowned upon in ‘“‘with it’’ computing circles. However, for historical interest (and in case you actually prefer this visual method), some examples are given here.
Suppose we want to write a program to convert a temperature on the Fahrenheit scale (where water freezes and boils at 32° and 212° respectively) to the more familiar Centigrade (Celsius) scale. The flowchart for the problem is as follows (the symbols are explained below):
(Input)
eee STARTO Sg TempF
(Compute TempC)
TempC = 5(TempF — 32)/9
40 CHAPTER 3
The main symbols used in flowcharts, and their meanings, are:
———$—$<— a flow of logic
Start/Stop
Input (or assignment) of information
Processing (e.g. calculation of formulae)
) Header for loop structure Decision
End of loop structure Decision (two- or three-way branch)
Printed output
PROGRAM PREPARATION 41
3.2. Quadratic Equation: Flowchart Every schoolchild must have solved hundreds of quadratic equations of the form ax’ + bx +c=0.
The complete algorithm for finding the solution x, given a, b, and c, is flowcharted as follows:
START
a,b,c
YES
Solution indeterminate
! No solution
YES Complex Sal Roots
YES
x, =[—b + V(b? — dac) } / (2a) x2 =[—b — V(b> — 4ac) } / (2a)
STOP
42 CHAPTER 3
3.3. Newton's Method: Flowchart
In Chapter Two we wrote a program to find square roots with Newton’s method:
|! SQUARE-ROOTING WITH NEWTON
CLEAR
INPUT PROMPT “Number to be square-rooted: ": A
LET X = 1
FOR | = 1
LET X = PRINT X
NEXT |
END
There is no universally accepted way of flowcharting a FOR-NEXT loop, but one way is
to use the elongated diamond to give the conditions under which the body of the loop
is executed, with a small circle to mark the end of the loop, as follows:
START
(condition under which body of loop is executed)
YES
- DONE <6 TIMES?
LET X= (LX +- Al | X) / 2
(body of loop)
Ges (repeat)
Note that the contents of the boxes can be either True BASIC statements, Or more
general mathematical statements.
PROGRAM PREPARATION 43
ee EEE EE EE eee
3.4. Structure Plans
This 1s an alternative method of program preparation, which has advantages when the equivalent flowchart gets rather big. It is an example of what is called pseudo-code. The plan may be written at a number of levels, of increasing complexity, as the logical structure of the program is developed. For example, a first level plan of the temperature conversion problem above might be a simple statement of the problem:
1. Input Fahrenheit temperature 2, Calculate and print Centigrade temperature 3. Stop.
Step | is pretty Straightforward, but step 2 needs elaborating, so the second level plan could be something like this:
1. Input Fahrenheit temperature (TempF)
2. Calculate Centigrade temperature (TempC): 4.1. Subtract 32 from TempF and multiply by 5/9
3. Print the value of LempC
4. Stop.
There are no hard and fast rules about flowcharts and structure plans, and you should use whichever method you prefer (or even a mixture). The essential point is to cultivate the mental discipline of getting the logic of a program clear before rushing to the computer. The “top down” approach of flowcharts or structure plans means that the overall structure of a program Is clearly thought out before you have to worry about the details of syntax (coding), and this reduces the number of errors enormously.
One of the main criticisms of “Street” BASIC (the older forms of BASIC) ts that it is “unstructured”, and even Its most ardent proponents agree: “It may not be as efficient as the FORTRAN language for a scientific pr oblem, but it can solve the problem. BASIC is a loose and unstructured language, unlike Pascal which makes you think first and program later. But this freedom to roam around in the program makes the code friendlier.”’ (Galanter, 1983, p. 75)
It is precisely this “freedom to roam around in the program” which makes it so easy to get intO massive logical tangles, or ‘‘spaghetti’”, when writing complex programs in Street BASIC. Although True BASIC is perfectly well structured, as we shall see in the following chapters, it is still possible to write messy True BASIC programs, especially if you are a Street BASIC addict trying to kick the habit. It 1s therefore extremely Important to plan your programs carefully beforehand, although many programmers steadfastly resist such an approach, for example Galanter, who asserts: “In the opinion of a large and vocal minority of programming instructors, (Street) BASIC does not qualify as a really good programming language because it does not foster structured programming. To grasp the flavour of this criticism, you must understand that these instructors want more thinking before you sit down at the machine. Their notion is that ‘efficiency’ is improved by preplanning the form of the program. Such preplanning can be done using BASIC just as well as it can using a structured language like Pascal. But the critics’ point is that the language does not force you to plan in advance, which a language like Pascal does.” (Op. cit. p. 154).
I am definitely one of those instructors who “want more thinking before you sit down at the machine”’!
CHAPTER 3
44 | = Sn 3.5. Quadratic Equation: Structure Plan
The equivalent structure plan for the quadratic equation problem flow-charted above is as follows: 1. Start 2. Input data (a, b, c) 3. Ifa =0 then 3.1. If b = 0 then 3.1.1. If c= 0 then 3.1.1.1. Print ‘‘Solution indeterminate”’ Otherwise 3.1.1.2. Print ‘‘There is no solution’’ Otherwise 3.1.2. x = —c/b 3.1.3. Print x (one root: equation is linear) Otherwise 3.2. If b* < 4ac then 3.2.1. Print ‘“Complex roots”’ Otherwise 3.2.2. If b* = 4ac then 3.2.2.1. x = —b/(2a) 3.2.2.2. Print x (equal roots) Otherwise 3.2.2.3. x, =[—b + V(b? — 4ac) ]/ (2a) 3.2.2.4. x2 =[—b — V(b* + 4ac) | / (2a) 3.2.2.5. Print x), x2 4. Stop
Details of how to code the /f-then blocks are discussed in Chapter Five. There are many more examples of structure plans throughout the book.
3.6. Structured Programming
Many examples later in the book (particularly in the last three chapters) will get rather involved. More advanced programs like these should be structured by means of subprograms, or procedures, which are dealt with in detail in Chapter 11. A procedure is a self-contained program unit which can communicate with the main part of the program in specific ways, and which may be invoked or “‘called”’ by the main program. The main program will then look very much like a first level structure plan of the problem. For example, the quadratic equation problem may be structure planned at the first level as follows: |
1. Input the data 2. Find and print the solution 3. Stop.
PROGRAM PREPARATION 45
Using a particular procedure, called a “subroutine”, this may be translated directly into a True BASIC main program:
INPUT A, B, C
CALL QUADRATIC( X1, X2, A, B, C) PRINT X14, X2
END
The details of how to code this problem are left as an exercise in Chapter 11.
Summary
* An algorithm is a systematic logical procedure for solving a problem.
* An algorithm must be developed for a problem before it can be coded. * A flowchart is a diagrammatic representation of an algorithm.
A structure plan is a representation of an algorithm in pseudo-code.
EXERCISES
3.1 This structure plan defines a geometric construction. Carry out the plan by sketching the construction: 1. Draw two perpendicular x- and y-axes . Draw the points A (10; 0) and B (0; 1) 3. While A does not coincide with the origin repeat: 3.1. Draw a straight line joining A and B 3.2. Move A one unit to the left along the x-axis 3.3. Move B one unit up on the y-axis 4. Stop.
tO
3.2 Consider the following structure plan, where M and N are True BASIC variables: 1. Set M = 44 and N = 28 2. While M not equal to N repeat: 2.1. While M > N repeat: 2.1.1. Replace M by M—WN 2.2. While N > M repeat: 2.2.1. Replace N by N— M 3. Print M 4. Stop. (a) Work through the structure plan, sketching the contents of M and N during execution. Give the output. (b) Repeat (a) for M = 14 and N = 24. ’ (c) What general arithmetic procedure does the algorithm carry out (try more values of M and N if necessary)?
3.3. Write a structure plan for the conversion of a Centigrade ei ee a Fahrenheit one. Write the True BASIC program and test 1t on some sample data.
Also try to write structure plans for the following problems (don’t try to write i programs until you’ve worked through Chapter Five): Exs 5.2, 5.3,5.4, 5.6, 6.13.
CHAPTER 4
BUILT-IN FUNCTIONS
If you have mastered the contents of this book so far, you should be able to write a program which gets data into the computer, performs simple arithmetic operations on the data, and prints the results of the computation in a comprehensible form. However, more interesting problems are likely to involve special mathematical functions like sines, cosines, logarithms, etc. Just as most calculators have keys for these functions, True BASIC allows you to compute many functions directly. These functions are called built-in functions.
4.1. Projectile Motion
We want to write a program to compute the position (x and y co-ordinates) and velocity (magnitude and direction) of a projectile, given ¢, the time since launch, u, the launch velocity, a, the initial angle of launch (in degrees), and g, the acceleration due to gravity.
The horizontal displacement is given by the formula
x =u cos(a)t
and the vertical displacement by
y=usin(a)t — 0.5¢° .
The velocity has magnitude V such that
Ve= V(V." + Vy"),
where its horizontal and vertical components, V, and V,, are given by ‘. =u cos(a), y =u sin(a) — gt,
and V makes an angle 6 with the ground such that
tan(@) = V,/V,.
The program is:
! PROJECTILE POSITION AND VELOCITY
READ A, G, T, U
LET A = A * PI / 180 LET X = U* COS( A) *T LET Y= U * SIN( A) * T-05* G*T%* 2
LET VX = U * COS( A)
4§ CHAPTER 4
LET VY = U* SIN} A)-G*T LET V = SQR( VX * 24+ VY72) LET THETA = ATN( VY / VX ) * 180/ PI | CONVERT BACK TO DEGREES
PRINT "x:"; X, "y:"; Y
PRINT “V:”; V, CHRS$( 233 );":"; THETA; “degrees” DATA 60, 9.8, 10, 60
END
If you run this program with the data as given you will see from the negative value of 9 that the projectile is coming down.
The argument of a built-in function may be any valid True BASIC expression, including another function. So V could have been computed directly as follows:
LET V = SQR( (U * COS( A )) * 2 + (U * SINC A )—G * T) * 2 )
(The argument of SQR is always positive here (why?) so no problems can arise.) Angles for the trigonometric functions must be expressed in radians, by default. To convert degrees to radians, multiply the angle in degrees by PI/180, where PI is a built-in
function with the well-known value 3.1415926... If you want to impress your friends, however, you can cunningly exploit the mathematical fact that the arctangent of lis 7/4,
and use the ATN built-in function:
LET MYPI = 4 * ATN( 1 ) LET A = A * MYPI / 180 | CONVERT DEGREES TO RADIANS
Alternatively, all angles for the trigonometric functions will be treated as degrees if the statement
OPTION ANGLE DEGREES is used before any of the functions are called. For angles to be assumed in radian measure subsequent to this, use the statement
OPTION ANGLE RADIANS
The string function CHR$ with argument 233 enables you to print the Greek symbol “0” on the screen (see below and Appendix D, which also describes how to get special characters directly on the screen). To print the special symbols on your printer, however, you will need to consult your printer manual for any additional control characters required, and you may also need a special font for your printer.
4.2. Some Useful Built-in Functions
A complete list of the built-in functions supported by True BASIC appears in Appendix C. Some of the more common ones are given here. In the list below, N, X and X$ stand for any True BASIC numeric or string constant, variable or expression. The name ofa built-in function may be used a variable, but then that function is unavailable to the program.
ABS( X ) absolute value.
BUILT-IN FUNCTIONS
49
aoe
ANGLE( X, Y ) ATN( X ) CHRS( N )
COS( X ) DATE
DATES EXP( X ) FP( X ) INT( X ) IP( X )
LCASES( X$ )
LOG( X ° LOG10( X ) MAX( X, Y ) MIN( X, Y ) MOD( X, Y )
P| REPEAT$( X$, N )
RND
ROUND( X )
ROUND( X, N ) SIN( X )
SQR( X )
TAN( X )
TIME
counterclockwise angle between the positive x-axis and the point (X; Y), in the range -z to x.
arctangent of X
character with ASCII code N, e.g.
Ok. PRINT CHR$( 64 )
@
cosine of X.
current date in numeric form YYDDD, e.g. on the 2nd of February 1986, DATE had the value 86033 (the 33rd day of 1986).
current date in string form “yyyymmdd”’, e.g. on Christmas Day 1985, DATE$ had the value “19851225”
e*.
fractional part of X, e.g.
Ok. PRINT FP( 45.67 ); FP( —2.89 ) 67 —.89
largest integer not exceeding XA, e.g. Ok. PRINT INT( 45.67 ); INT( —2.89 ) 45 -3
integer part of X, e.g.
Ok. PRINT IP( 45.67 ); IP( —2.89 ) 45 -2
converts letters to lowercase, e.g. Ok. PRINT LCASE("R2D2” )
r2d2
natural logarithm of X.
logarithm to the base 10 of X. maximum of X and Y.
minimum of X and Y.
absolute value of the remainder when X is divided by Y, e.g.
Ok PRINT MOD( 13, 5 ); MOD( 4, 4 ) 3 0
value of m (3.1415926 ... ).
N repeats of the string X$, e.g. Ok. PRINT REPEAT("—", 8 )
“pseudo-random” number uniformly distributed over the interval [0; 1). rounds to nearest integer, e.g.
Ok. PRINT ROUND( 45.67 ); ROUND( —2.49 ) 46 -2
rounds to N decimals.
sine of X.
square root of X, where X > 0. tangent of X.
current time in seconds since midnight.
CHAPTER 4
TIME$ current time in string form “hAh:mmiss’’. E.g. the following program displays the time continuously in the middle of the screen until any key is pressed: CLEAR SET COLOR "black/white/blink” !see Chapter 12 DO SET CURSOR 12, 35 PRINT TIMES LOOP UNTIL KEY INPUT END truncates to N decimal places, e.g. Ok. PRINT TRUNCATE( 45.67, 1 ) 45.6 UCASE$( X$ ) converts letters to uppercase, e.g. Ok. PRINT UCASE( "r2d2” ) R2D2
TRUNCATE( X, N )
Summary «Built-in functions may be used to compute a variety of mathematical, trigonometric and other functions directly.
EXERCISES
4.1 A fruit co-operative wants a program which reads the number of apples (Box Ful) that can be packed into one box and the number of apples to be packed altogether (Apples), and prints out the number of boxes needed (Boxes) and the number of
apples left over (Leff). (a) Write the structure plan for the problem. (b) Write the program. 4.2 Write some True BASIC statements which will: (a) find the length C of the hypotenuse of a right-angle triangle in terms of the lengths A and B of the other two sides;
(b) find the length C of a side of a triangle given the lengths A and B of the other two sides and the size in degrees of the included angle 7heta, using the cosine
rule: (c) change the sign of X if J is even. 4.3 Translate the following formulae into True BASIC expressions: (a) log.(x + x* + a’) (b) logio(y) (c) [e* + fsin(4r)] cos?(3r) (d) 4tan~*(1) (e) sec?(x) + cot(y) (f) cot~}(|x/al)
BUILT-IN FUNCTIONS 51
4.4 A-sphere of mass m, impinges obliquely on a stationary sphere of mass mz, the direction of the blow making an angle « with the line of motion of the impinging sphere. If the coefficient of restitution is e it can be shown that the impinging sphere is deflected through an angle B such that
m2(1 + e)tan(«) tan(B) = : — (m, — emz) + (m, + m2)tan?(«)
Write a program to read values of mm, m2, e, and « (in degrees) and to compute and print out the angle 6 in degrees.
CHAPTER 5
CONTROL STRUCTURES I: DECISIONS
Apart from a computer’s ability to add numbers extremely quickly, its other major attribute is to be able to make decisions, as we saw in Chapter Two. It is this facility which gives the computer its great problem-solving power. The fundamental decision- making construction in True BASIC is the IF statement, of which the SELECT CASE Statement is another form.
0.1. The IF statement
We have seen the use of the simple one-line IF-THEN-ELSE statement in Chapter Two. However, it may be generalized by a control structure which spreads over many lines, as the next two examples show.
Bending Moment in a Beam
A light uniform beam 0 < x < L is clamped with its ends at the same level, and carries a concentrated load W at x =a. The bending moment M at any point x along the beam IS given by two different formulae, depending on the value of x relative to a, viz.
M = W(L—a)[aL —x(L+2a)/L2 (0<x Sa), M = Wa’[aL — 2L7 + x(3L —2a)//L? (a<x<L).
The following program computes the bending moment every metre along a 10 m beam, with a load of 100 Newtons at a point 8 m from the end x = 0:
! BENDING MOMENT
LET L = 10 LET W = 100 LET A = 8
LET M = W* (L—A) 7 2/L°*3* (A* L—X * (L + 2 * A))
ELSE LETM=W*A%2/L°3* (A*L-2*L%* 2 + X * (38 * L—2 * A)) END IF
PRINT X, M
54 CHAPTER 5
END
Note that the entire IF-THEN-ELSE structure covers five lines. Since only one LET statement must be executed for each of the two cases x S a and x > a, the IF-THEN-ELSE could have been written on one line, as in Chapter Two, but the line would have been very long; it is better to split it up as shown above. However, in the next example, it is
not possible to use a one-line IF-THEN.
Top of the Class
A class of 50 students write a test, and each student’s name and mark is typed in a DATA statement. Assume there are no negative marks. We want to write a program which prints out the name of the student with the highest mark, together with his/her mark. We are assuming that there is only one highest mark. The problem of what to do when two or more students share the top mark is discussed in Chapter Nine.
A first level structure plan for this problem could be:
1. Start 2. Find top student and top mark 3. Print top student and top mark.
Step 2 needs elaborating, so a more detailed plan might be:
1. Start 2. Initialize TopMark (to get process going) 3. Repeat 50 times: 3.1 Input Name and Mark 3.2 If Mark > TopMark then 3.2.1. Replace TopMark with Mark 3.2.2. Replace TopStudent with Name . Print TopStudent and TopMark 5. Stop.
The program is: ! FINDS TOP STUDENT IN CLASS
| | ; STUDENT COUNTER
|! MARK - GENERAL MARK
|! NAME$ >; GENERAL NAME
! TOP__MARK : TOP MARK
! TOP_STUDENT$: TOP STUDENT
LET TOPMARK = 0 | It can’t be less than that!
FOR | = 1 TO 50 READ NAME$, MARK IF MARK > TOP_MARK THEN LET TOP_STUDENT$ = NAMES | keep his/her name ... LET TOP_MARK = MARK END IF NEXT |
CONTROL STRUCTURES I: DECISIONS 55
PRINT "Top student: ” ; TOP_STUDENT$ PRINT "Top mark: ” ; TOP__MARK DATA JONES GR, 68
DATA SMITH lJ, 99
DATA THOMSON RE, 12
END Work through the program by hand for a few turns to convince yourself that it works.
Note that both LET statements between THEN and END IF are executed if the condition MARK > TOP__MARK is true, and that there is no ELSE in this example.
The ELSEIF Construct
Recall the final mark example in sections 2.12 and 2.13. Suppose we want not only to print the category of pass for each student, but also to count how many passed in the first class, how many in the second class, and so on. Let the variables FIRSTS, UPSECONDS, LOWSECONDS, THIRDS and FAILS represent the number of students in each of these respective classes. We could replace lines 272-280 by the following:
IF FIN >= 75 THEN
PRINT "I"
LET FIRSTS = FIRSTS + 1 ELSE IF FIN >= 70
PRINT "I]-”
LET UPSECONDS = UPSECONDS + 1 ELSE IF FIN >= 60
PRINT "II"
LET LOWSECONDS = LOWSECONDS + 1 ELSE IF FIN >= 50 THEN
PRINT "III"
LET THIRDS = THIRDS + 1 ELSE
PRINT "FAIL"
LET FAILS = FAILS + 1 END IF
This says in plain English what happens; further explanation is almost unnecessary.
The General Form of |F-THEN-ELSEIF
The most general form of this control structure is as follows:
IF condition] THEN
4 blockl
56 CHAPTER 5
ELSE IF condition2 THEN .. block2
ELSE IF... THEN
ELSE
. blockE
END IF
The action is straightforward. If conditionl is true, the statements in block] are executed, and True BASIC then branches to the statement after the closing END IF. If condition! is false, condition2 is examined. If it is true, the statements 1n block2 are executed, followed by the statement after the END IF. In this way, each ELSE IF clause is examined, until a true condition is found. As soon as a true one is found, no further ELSE IFs are examined. If none of the conditions is true, the statements in blockE after the ELSE are executed. The conditions should be arranged so that only one of them will be true at a time. The blocks of statements may contain any True BASIC statements, including more IF-THEN-ELSEs.
There may be any number of ELSE IF clauses. For compatibility with ANS BASIC, the ELSE IF keyword may be written as one word: ELSEIF. There may be no ELSE clause, but not more than one. The END IF keyword must be written as two words. Nothing must be typed on the lines after the keywords THEN, ELSE and END IF.
It is good programming style to indent blocks of statements inside IF statemenis.
When IF statements are nested, the positioning of the END IFs is crucial, as this determines to which IFs the ELSEIFs belong (by default an ELSEIF or ELSE belongs to the most recent IF). E.¢.
IF ... THEN IF ... THEN ELSE ‘belongs to 2nd IF
END IF END IF
IF ... THEN IF ... THEN
END IF ELSE belongs to 1st IF now
END IF
The END IF closes the most recent IF.
CONTROL STRUCTURES I: DECISIONS 57
Logical Expressions
These were mentioned briefly in Chapter Two, but need to be tidied up. Logical expressions can only have the values true or false, and can be formed in two. ways. The first is from expressions in combination with the six relational operators shown below:
Relational Operator Meaning
< less than
<= or =< less than or equal to
= equal to
>= or => greater than or equal to > ereater than
<> or >< not equal to
A space may not be typed between parts of the two-character operators, 1.e. you may nottype"< =".
Examples of logical expressions thus formed are:
Logical expressions may also be formed from other logical expressions using the three logical operators NOT, AND, and OR. Parentheses may also be used. Examples are’
B*2=4*A*CANDA <> 0 FIN >= 60 AND FIN < 70 A=0ORB=O0ORC=0 (NOTA =0ORB=C)ANDD>E
The effects of these operators on two logical expressions /ex] and /ex2 are shown in t following ‘‘truth” table (T = true; F = false):
lex] lex2 NOT lex1l lex1 AND lex2 lexl OR lex2 T T F T T [ F F F T F T aa F T fk F T EF F
The precedence of the logical operators is: parentheses, NOT, AND, OR. So if lex, lex2 and /ex3 are logical expressions, the following two expressions are logically equivalent:
lex] AND NOT Jex2 OR lex3 ( lexJ AND (NOT /ex2) ) OR lex3
The following two expressions are also equivalent, and are false only when A=B=C=0:
A <> 0ORB<>O0OORC <> 0 NOT( A = 0 AND B = 0 AND C = QO)
58 CHAPTER 5
It makes you think, doesn’t it?
True BASIC always “‘short-circuits” complex logical expressions once their truth value is known. E.g. in
1=10R3+2=6
the truth value of ‘3 + 2 = 6” is not computed since the ‘1 = 1” is true, and OR makes
the whole expression true whatever follows. A program can therefore often be speeded up by re-arranging the order of logical expressions.
True BASIC has no logical or ““Boolean”’ variables.
Spaghetti
Earlier versions of BASIC had a little four-letter statement which, more than anything else, has contributed to the bad name that BASIC has among many computer scientists.
The statement is
GOTO n
where n is any line number in the program. A few harmless looking GOTOs scattered throughout a decently structured program can reduce it to a shivering mass of tangled sphagetti in a few moments. Consider the following example.
lex] and /ex2 are two logical expressions. If /ex] is true, | and J are to be set to 1 and 2
respectively. If /ex] is false and /ex2 is true, | and J are to be set to 2 and 3. If /ex/ and lex2 are both false, | and J are to be set to 3 and 4. The flowchart is:
CONTROL STRUCTURES I: DECISIONS
The spaghetti version of the coding for this is:
10 IF NOT lex! THEN GOTO 50
20 LET | = 1
30 LET J = 2
40 GOTO 110
50 IF NOT /ex2 THEN GOTO 90 60 LET | = 2
70 LET J = 3
80 GOTO 110
90 LET | = 3
100 LET J = 4
110 ...
Although True BASIC has a GOTO statement, you should never use it! There are at least
two vastly better ways of coding this problem. One uses IF-THEN-ELSEIF:
IF lex] THEN
LET | = 1
LET J = 2 ELSE IF lex2 THEN
LET | = 2
LET J=3 ELSE
LET! = 03
LET J = 4 END IF
The other uses nested IFs:
IF lex] THEN LET | = 1 LET J = 2
ELSE IF /ex2 THEN
Beh ie LET J 3 ELSE LET | 3 LET J = 4 END IF END IF
Either version is acceptable, but the first one is probably easier to read.
5.2. The SELECT CASE statement
This control structure is similar to the IF-THEN-ELSEIF construct, and 1s sometimes more convenient, being less wordy. The segment above to analyse students’ marks may be
coded as follows with a SELECT CASE statement:
SELECT CASE FIN CASE |S >= 75
60 CHAPTER 5
LET FIRSTS = FIRSTS + 1 PRINT "I"
CASE 70 TO 74.99 LET UPSECONDS = UPSECONDS + 1
PRINT “II-+-"
CASE 60 TO 69.99 LET LOWSECONDS = LOWSECONDS + 1
PRINT “Il—"
CASE 50 TO 59.99 LET THIRDS = THIRDS + 1 PRINT “III”
CASE ELSE LET FAILS = FAILS + 1 PRINT “FAIL”
END SELECT
The general syntax of SELECT CASE is:
SELECT CASE expr CASE testl, test2, ...
.. block! CASE test3, test4, ... a block2 SASE ... CASE ELSE .. blockE END SELECT
The expression expr is evaluated and compared with the tests. If expr is numeric, the tests must all be numeric; if it is a string, all the tests must be for strings. [here are three
forms of tests:
constant low TO high (used in CASEs 2 to 4 above) IS operator constant (used in the first CASE above)
where constant, low and high are string or numeric constants, and operator is a relational operator. Expressions and variables are not allowed in the tests. More than one test may be listed for each CASE, provided the tests are separated by commas. If any of the tests succeed, that CASE is chosen.
When a matching test is found, the block of statements for that CASE are executed followed by the next statement after the closing END SELECT statement. If no test succeeds, the CASE ELSE part is executed. The CASE ELSE part is optional, and must be at the end, but if one is missing when needed, a run-time error occurs. The tests should all be mutually exclusive.
CONTROL STRUCTURES I: DECISIONS 61
The SELECT CASE statement is useful for “menu selection” programs. The user is presented with a number of choices, which are usually indicated by single letters. A SELECT CASE statement can be used to choose the appropriate action.
summary * Logical expressions can only have one of two values: true or false.
* Logical expressions are formed from arithmetic expressions with relational operators (<, =, =% <->, >, >=).
* The logical operators (NOT, AND, OR) may be used to form more complex logical expressions from other logical expressions.
* The IF-THEN-ELSEIF and SELECT CASE control structures may be used to choose between alternative actions.
EXERCISES
).1 Write a program which inputs two numbers and prints out the larger one with a suitable message, or if they are equal prints out a message to that effect.
5.2 Write a structure plan and program for the following problem: input 10 numbers and print out how many of them are positive, negative or zero.
5.3 Develop a structure plan to find the smallest number in a list of 10 numbers input irom the keyboard, and the position of the smallest one in the list. Write the program.
5.4 Design an algorithm (draw the flowchart or structure plan) for a machine which must give the correct amount of change from a R10 note for any purchase costing less than R10. The plan must specify the number and type of all notes and coins in the change, and should in all cases give as few notes and coins as possible.
5.5 Write a program for the general solution of the quadratic equation ax” + bx +c=0.
Use the structure plan developed in Chapter Three. Your program should be able to handle all possible values of the data a, b, and c.
5.6 Develop a structure plan for the solution of two simultaneous linear equations (i.e. two straight lines). Your algorithm must be able to handle all possible Situations, viz. lines intersecting, parallel, or co-incident. Write a program to implement your algorithm, and test it on some equations for which you know the solutions, e.g.
x+ty=3
2x—y=3
(x = 2, y = 1). Hint: begin by deriving an algebraic formula for the solution of the system
ax + by=c
dx + ey =f.
CHAPTER 6
CONTROL STRUCTURES I: REPETITION
In Chapter Two we introduced the powerful FOR-NEXT control structure to execute a block of statements repeatedly. This type of structure, where the number of repetitions may be determined in advance, is sometimes called deterministic repetition. However, it often happens that the condition to end a repeat structure (loop) is only satisfied during the execution of the loop itself. This type of repeat structure is called non-deterministic. In this chapter we will use both types of repeat structure to solve a range of interesting problems.
6.1. Deterministic Repetition: FOR-NEXT
In this section we see how to generalize the FOR-NEXT statement introduced in Chapter Two.
Plotting a Sine Curve
The following program draws a sine curve on the screen over two periods. The special graphics statements will only be discussed in detail in Chapter 12. The main point illustrated here is that the counter X in the FOR-NEXT loop may be incremented by any value, not only 1.
1 SINE CURVE SET WINDOW 0, 15, —4, 4
FOR X = 0 TO 4 * Pl STEP PI / 20 PLOT X, SIN( X ): NEXT X
END
General Definition of FOR-NEXT The general form is
FOR = JTOK STEP L - body of loop
NEXT /
64 CHAPTER 6
where / is a numeric variable, (also called the index variable) and J, K, and L may be any numeric expressions. The STEP part may be omitted, in which case L = 1 by default.
If the step-size L is positive, the statements between FOR and NEXT are executed repeatedly with / starting at J and increased by L each time until the body of the loop has been executed for J having its greatest value not exceeding K, e.g.
FOR | = 2 TO 7 STEP 2 PRINT |;
NEXT |
Ok. run
2 4 6
If L > 0 and J >K the body of the loop is never executed, e.g.
FOR! =5 704 1 L = 1 by default PRINT I;
NEXT |
Ok. run
Ok. (i.e. no output)
If L < 0 the body of the loop is executed until it has been executed with J having its
smallest value which 1s not less than K, e.g.
FOR | = 5 TO 1 STEP —1 PRINT |;
NEXT |
Ok. run
Soares oe. |
FOR | = 6 TO 1 STEP -2 PRINT |:
NEXT |
Ok. run
6 4 2
If L <Q andJ < K the body of the loop is never executed.
The index variable J should not be changed by any statements in the loop, 1.e. it should not appear on the lefthand side of an assignment statement in the body of the loop.
For the sake of completeness, the EXIT FOR statement should be mentioned. It enables control to be transferred out of a FOR-NEXT loop. Since this is almost as bad as GOTO its use is definitely not recommended. It is much better programming practice to use the
DO-LOOP structures described below.
Vertical Motion Again
The example in Chapter Two, where a stone is projected vertically, may be amended with a FOR-NEXT statement to print the stone’s displacement at regular intervals, of half
a second, say:
CONTROL STRUCTURES II: REPETITION 65
| VERTICAL MOTION UNDER GRAVITY PRINT "TIME”, “DISPLACEMENT”
LET G = 9.8
LET U = 60
FOR T = 0 TO 11 STEP 0.5
LET S =U * T=G L271 “ez PRINT T, S NEXT T END If you run this example, you will see that the stone goes up and comes down during this period. Use trial and error to find out more precisely when the stone reaches the ground again.
Damped Oscillations
The current flowing in a circuit consisting of a resistance, inductance and initially charged condenser, connected in series is given by
t= Aexp(—Rt/2L)sin(21f0) where A — 2nfo" Ofi, fo = VIWMLOV(2z), 1 = V{i1/(LC) — R?7/(4L7)]/(22), and the symbols have the meanings current (amperes) at time f; maximum current; time (seconds elapsed since circuit connected); resistance (ohms); inductance (henrys); frequency (cycles/sec) of undamped (R = 0) circuit; frequency of damped circuit; capacitance (farads) of the condenser; initial charge (coulombs) on the condenser.
OARS hat a
We want to compute the current over a period of CYCLES complete cycles, where PERCY evaluations per cycle are made. The current must therefore be computed CYCLES * PERCY times altogether. The time DT between successive evaluations will be given by the statement
LET DT = 1 / (PERCY * F1)
since the period of the oscillations is 1/f; seconds. The program, which uses high resolution graphics, is as follows:
66 CHAPTER 6
|! DAMPED OSCILLATIONS
SET MODE “hires” SET WINDOW 0, 0.3E-—2, —0.8E—1, 0.8E—1 READ Q, R, ©, L
LET CYCLES = 3 LET PERCY = 40
LET FO = SQR( 1/(L*C))/ (2 * PI
LET Fi = SQA(1/(L* C)-R*2/(4*L%* 2))/ (2 * Pl) LETA=2* PI *FO*2*Q/F1
LETT =0
LET DT = 1 / (PERCY * F1)
FOR K = 1 TO CYCLES * PERCY + 1 eR meee the UR SBSLERI INN Be SARh MPI re). PLOT T, |: LET T = T + DT
NEXT K
PLOT
PLOT 0O, 0; T, O
DATA 1E—5, 4, 1E-—5, 2E-3
END
Figure 6-1. Damped oscillations in a RLC circuit
(If your computer doesn’t have graphics facilities, replace the PLOT statement inside the FOR-NEXT loop with PRINT.) You should:see a series of oscillations which are smaller each cycle, as shown in Fig. 6-1. Thisis an example of a model: the program behaves like the real thing. You can “tune”’ the apparatus by fiddling with the values of O, R, Cand L. For example, changing R will change the amount of damping, but it will also change the frequency f;, whereas changing C will only affect the frequency. Do a few experiments with your model.
Factorials!
The index variable in a FOR-NEXT loop may be used in any expression inside the loop, as long as its value is not changed. The following program prints a table of n and n! (spoken as “n factorial”’, or ‘‘n shriek’’ ), where
= 1X2X3X ... X(n — 1)Xn.
CONTROL STRUCTURES II: REPETITION 67
REM N! LET FACT = 1
FOR N = 1 TO 25 LET FACT = N * FACT PRINT N; TAB( 5 ); FACT NEXT N
END
The Binomial Coefficient
This is widely used in statistics. The number of ways of choosing r objects out of n without regard to order is given by:
n’ n! _ B= l)\(n —2)...(n—rt+T1) ‘ | = ri(n—r)! r! n\- 10! _ 10X9X8 at ~ $Biseaah 12x:
If the first form is used, the numbers involved can get very big, and there could be an ‘overflow’ on some computers. But using the form on the right is much more efficient:
|! BINOMIAL COEFFICIENT (NcR) LET BIN = 1 INPUT PROMPT '"n and r? ": N, R
FOR K = 1 TO R LET BIN = BIN * (N—K + 1) /K NEXT K PRINT N;"c"; R;”="; BIN END
Computing the Limit of a Sequence
FOR-NEXT loops are ideal for computing successive members of a sequence. This example also highlights a problem that sometimes occurs when computing a limit. Consider the sequence
tn = a2 int n= 12,3, 2:
where a is any constant, and m! is the factorial function defined above. The question is: what is the limit of this sequence as n gets indefinitely large? Let’s take the case a = 10. If we try to compute x,, directly we could get into trouble, because n! gets large very rapidly as m increases, and a machine overflow could occur. However, the situation 1s neatly transformed if we spot that x,, is related to x,—-; as follows:
Xn — aX,—1/n “
68 CHAPTER 6 | |
There are no overflow problems now. The following program computes x,, for a = 10, and increasing values of n, and prints it for every tenth value of n:
| Limits
LET a LET x
FOR n = 1 TO 100 LETx=a*x/n IF MOD( n, 10 ) = 0 THEN PRINT n; TAB( 8 ); x NEXT n
END The output is as follows:
10 2755.73
20 41.1032
30 3.76999e—3 40 1.22562e—8 50 3.28795e—-15 60 1.20178e-—22 70 8.34824e-—31 80 1.39724e—39 90 6.73076e—49 100 1.07151e—-58
From these results it appears that the limit is zero, and this may be proved mathemat- ically. For some more examples of calculus with computers, see Bitter (1983).
10
ll fl
Note that the above program was typed in lowercase. The DO FORMAT command was used to convert keywords to uppercase and to indent neatly.
Nested Loops: Loan Repayments
The regular fixed payment P, made n times a year, to repay a loan of amount A over a period of k years, where the nominal annual interest rate is r, is given by
P = (r/n)A(1 + r/n)"*/[(1 + r/n)"* — 1).
The next program uses a nested FOR-NEXT loop to print a table of the repayments on a loan of $1000 over 15, 20 or 25 years, at interest rates that vary from 10% to 20% per annum. Since the formula is linear in the amount of the loan, the repayments on a loan of any amount may be found from the table generated by the program, by simple proportion.
! REGULAR LOAN REPAYMENT
LET A = 1000 ! Principal
LET N = 12 ! Number of payments per year CLEAR
PRINT “RATE”, “15 YRS", "20 YRS”, "25 YRS”
FOR R = 0.1 TO 0.2 STEP 0.01
CONTROL STRUCTURES II: REPETITION
PRINT 100 * R;"%",
FOR K = 15 TO 25 STEP 5 LETP =R/N*A* (1 +R/N)*(N* K)/ ((1+R/N)*(N*K) —1)
PRINT P, NEXT K PRINT
NEXT R
END
The output ts:
RATE 15 YRS 20 YRS 25 YRS 10% 10.7461 9.65022 9.08701 11% 11.366 10.3219 9.80113 19% 16.8288 16.2068 15.9768 20% 17.563 16.9882 16.7845
69
The Telephone
This example, from Kemeny and Kurtz (1985b), uses a nested FOR-NEXT loop to imitate the ringing of a telephone:
| Imitate ringing of a telephone. FOR ring = 1 to 8 | Ring 8 times
FOR i = 1 to 80 SOUND 600, .03 SOUND 1500, .03
NEXT }
PAUSE 2
NEXT ring END
| Each ring = 30 alternations ! Freq 600 for .03 sec. |! Then 1500 for .03 sec.
The statement SOUND freq, time
sounds the computer’s speaker. freq is a numeric expression which gives the frequency in Hertz, and time is also a numeric expression, giving the duration in seconds.
6.2. Non-deterministic Repetition: The DO Statement
The number of loops executed by a FOR-NEXT structure are determined in advance of its first execution by the program. This is not the case with the DO-LOOP construct.
70 CHAPTER 6
Reaction Time Test
The following program measures, to the nearest tenth of a second, the time that elapses between the moment that the computer sounds a musical note and the user presses any key on the keyboard. The note is sounded a randomly varying period after execution starts (RND and RANDOMIZE are fully discussed in Chapter 13). Try it out to test your
reaction time. ! REACTION TIME
RANDOMIZE
PAUSE 5 * RND SOUND 512, 0.1
LET TSTART = TIME
DO LOOP UNTIL KEY INPUT
LET TEND = TIME
PRINT “Reaction time:”; TEND — TSTART
END
The compound DO-LOOP statement executes repeatedly (doing nothing) until any key is pressed. Control then moves to the statement after the loop, and the reaction time is computed.
KEY INPUT is a logical function, which is true if the user has pressed a key since the last time input was entered from the keyboard, or since execution began. It is used to test if any key has been pressed.
Joubling Time of an Investment
The next example uses a different form of the DO-LOOP control structure to compute the time taken for an investment drawing 10% interest per year to double. The structure
plan for the problem 1s:
I, Start
2. Initialize balance, year, rate, interest
3, Print headings
4. While balance < twice original balance repeat: 4.1. Print year, interest, balance 4.2. Update balance according to interest rate
5. Stop.
! DOUBLING TIME OF AN INVESTMENT CLEAR
INPUT PROMPT "Original balance: ”: OLD LET RATE = 0.1
LET NEW = OLD
LET INTEREST = 0
LET YEAR = 0
PRINT Year’, “Interest”, "Balance”
CONTROL STRUCTURES II: REPETITION 71
DO WHILE NEW < 2 * OLD PRINT YEAR, INTEREST, NEW
LET INTEREST = RATE * NEW LET NEW = NEW + INTEREST LET YEAR = YEAR + 1
LOOP
END
The condition NEW < 2 * OLD 1s checked each time before the body of the loop (the statements between DO and LOOP) is executed. Execution takes place only if the condition is true. The output looks like this (for an opening balance of $1000):
Year Interest Balance OQ 0 1000 1 100 1100 2 110 1210 3 121 1331 4 133.1 1464.1 5 146.41 1610.51 6 161.051 1771.56 7 177.156 1948.72
Note that when the last loop begins, the condition is true, since the new balance ($1948.72) is less than $2000. This balance is printed, but by the end of the loop the new balance has exceeded $2000. This is never printed, because the condition to repeat is no longer irue. Note also that a FOR-NEXT loop cannot be used here because you don’t know how many repeats are going to be needed (eight in this case, since the first one 1s for year 0) until after the program has run.
If it is required to print the new balance until it first exceeds $2000, all that has to be done is to move the PRINT statement until it is the last statement in the loop (try it). Note that the starting balance is not printed now: this requires a separate PRINT statement before the loop starts. Alternatively, the DO-LOOP can be recoded as follows:
DO LET INTEREST = RATE * NEW LET NEW = NEW + INTEREST LET YEAR = YEAR + 1 PRINT YEAR, INTEREST, NEW LOOP UNTIL NEW > 2* OLD
Try this also. Either form is acceptable, although the purists might prefer the first form (DO-WHILE), since this states the condition for repeating clearly at the beginning of the loop. This condition is immediately apparent to anyone reading the program: you do not have to search for the end of the loop to find the condition to stop repeating.
The General Form of the DO Statement
There are a number of variations. The following two are recommended:
72 CHAPTER 6
DO WHILE condition ... body of loop
LOOP
and
DO : body of loop
LOOP UNTIL condition
The DO-WHILE structure repeats while its condition remains true. The condition therefore is the condition to repeat again. The condition is tested each time before the body of the loop is repeated. Since the condition is at the head of the loop, it is therefore possible to arrange for the loop not be executed at all under certain circumstances.
The DO-UNTIL structure repeats until its condition becomes true. The condition is therefore the condition to stop repeating. The condition is tested after each repeat before making another repeat. Since the condition is at the end of the loop, the body of the loop will always be executed atleast once. DO-UNTIL 1s useful for programming menu selection, where the menu Is always presented at least once.
In general it is possible to add a WHILE or UNTIL condition to either the DO or LOOP part, or to both (when the conditions may be different). It is, however, recommended that you stick to the two variations outlined above, which are identical to the While Do and Repeat Until structures in Pascal, for example.
It 1s also possible to jump out of a DO loop with an EXIT DO statement placed anywhere inside the loop. Control is transferred to the next statement after the LOOP statement. This is definitely not recommended, since it is almost as bad as GOTO. Principles of good structured programming require that either all or none of the statements in a loop are executed, but never only some.
Testing for More Data
The next program reads an unknown number of experimental observations from DATA statements and prints their mean:
|! MEAN OF EXPERIMENTAL READINGS LET NUM, SUM = 0
DO WHILE MORE DATA READ X LET SUM = SUM + X LET NUM = NUM + 17 LOOP
IF NUM > 0 THEN LET MEAN = SUM / NUM PRINT “Mean value of’; NUM; "readings:”; MEAN
CONTROL STRUCTURES II: REPETITION 73
ELSE PRINT "No readings, no mean!” END IF DATA 1, 2, 3, 4, 5, 6 END
The logical function MORE DATA is true only if there are more data items waiting to be read. The programmer does not therefore need to know how many data items there are (it may be a nuisance to have to count them exactly). MORE DATA also prevents a run-time error when there is no data, since in this case the body of the loop is never executed (and the IF statement prevents division by zero). END DATA is another logical function, which is the exact opposite of MORE DATA: it is true if there are no more data items waiting to be read.
Taylor Series for Sine
You may have wondered how the computer calculates functions such as sine and cosine. Really ancient computers actually used to look up tables entered in memory, but young up and coming ones are more cunning. Mathematically, it can be shown that sin(x), for example, is the sum of an infinite series (called a Taylor series), as follows:
sin(x) = x — x°/3! + 2/5! — x7/7! +...
We obviously can’t compute the sum of an infinite series (why not?), but we can at least arrange to stop after the terms in the series are all less than some prescribed value, say te—6. It can be shown that we can always get a term less than some arbitrarily small number by going far enough in the Taylor series. As an exercise you should try to draw the flowchart or structure plan before studying the program. The main idea here is to construct each term in the series from the previous one, as described in the limit example in section 6.11. In constructing the denominator each time, use has been made of the fact that if k is any integer, 2k is even and 2k+1 is odd. The program is as follows:
|! COMPUTES SIN(X) WITH TAYLOR SERIES
| ERR ; MAX ERROR REQUIRED / K : TERM COUNTER | SINE ;: SUM OF SERIES / TERM : GENERAL TERM | X ; ANGLE IN RADIANS
INPUT PROMPT "Angle (in degrees): ": X |
LET X = RAD( X ) | Converts to radians
LET TERM = X
LET SINE = TERM LET ERR = 1E-6 LET K = 0
DO WHILE ABS( TERM ) > ERR LET K = K + 1 LET TERM =— TERM * X * X/ (2 * K * (2 * K + 1)) LET SINE = SINE + TERM
LOOP
PRINT “After’; K; terms Tayor series gives:”; TAB( 41 ); SINE
74 CHAPTER 6
PRINT "Computer's built-in SIN function gives:”; TAB( 41 ); SIN( X )
END
Algorithms such as this can be used to compute other built-in functions on calculators and computers.
Summary
* A FOR-NEXT loop should be used to program a deterministic repeat structure, where the number of repeats is known to the program (i.e. in principle to the programmer) before the loop is encountered. This situation is characterized by the general structure plan 1. Repeat N times:
1.1 Statements to be repeated where N is known or computed before step 1 is encountered, and is not changed by step 1.1. The general syntax for FOR-NEXT Is:
FOR var = first TO last STEP size ... body of loop
NEXT var
* A DOloop should be used to program a non-deterministic repeat structure, where the exact number of repeats is not known in advance. Another way of saying this is that a DO loop should be used to repeat whenever the truth value of the conditioz for repeating 1s changed in the body of the loop. This situation 1s characterized by the following two structure plans:
1. While condition is true repeat: 1.1. Statements to be repeated (which should reset the truth value of condition)
Or
1. Repeat: 1.1. Statements to be repeated (which should reset the truth value of condition)
Until condition is true.
The syntax of these two forms is:
DO WHILE condition
... body of loop LOOP or DO
... body of loop
LOOP UNTIL condition
CONTROL STRUCTURES II: REPETITION 75
7. SF 6 oe
The body of a DO-WHILE structure may sometimes never be executed.
The body of a DO-UNTIL structure is always executed at least once.
FOR-NEXT and DO loops may be nested inside each other.
KEY INPUT is true if a key has been pressed since the last input was read from the
keyboard. MORE DATA is true if there is more data to be read, while END DATA Is true if there is no more data to be read.
“¥-
The computer’s speaker may be sounded with the SOUND statement.
EXERCISES
6.1 Write a program to compute the sum of the integers 1 to 100.
6.2. Write a program to compute the sum of the series LS Se © 100.
6.3 There are many formulae for computing x (the ratio of a circle’s circumference to its diameter). The simplest is
w4=1— WSF Wo YT te YD ee. (1)
which comes from the series
arctan(x) =x —x°'/3 + x/5 —x'/7+x7/9 —... (*)
by letting x = 1.
(a) Write a program to compute z using series (1). Use as many terms in the series as your computer will reasonably allow (start modestly, with 100 terms, say, and re-run your program with more and more each time). You should find that the series converges very slowly, i.e. it takes a lot of terms to get fairly close to x.
(b) Rearranging the series speeds up the convergence:
m/8 = 1/(1X3) + 1/(5X7) + 1/(9X11) ... (2)
Write a program to compute x using series (2) instead. You should find that
you need fewer terms to reach the same level of accuracy that you got in (a). (c) One of the fastest series for x is
m/4 = 6 arctan(1/8) + 2 arctan(1/57) + arctan(1/239) (3)
Use this formula to compute x. Don’t use the built-in function ATN to compute the arctangents, since that would be cheating. Rather use the series (*) above.
6.4 The following method of computing z is due to Archimedes. A derivation and discussion of it is given by Breuer and Zwas (1984):
1. LetA =landN=6 2. Repeat 10 times, say:
2.1. Replace N by 2N 2.2 Replace A by V[2 — V(4 — A*)] 2.3. Let L = NA/2
76
6.5
6.6
6.7
6.8
CHAPTER 6
2.4. Let U = L/V(1 — A?/2) 2.5. Let P = (U + L)/2 (estimate of z) 2.6. Let E = (U — L)/2 (estimate of error) 2./. Print N, P, E
3. Stop.
Write a program to implement the algorithm. Write a program to compute a table of the function
f(x) =x sin[ (1 + 20x)/2 | over the interval [—1; 1] using increments in x of (a) 0.2 (b) 0.1 and (c) 0.05. Use your tables to plot a graph of f(x) for the three cases, and observe that the tables for (a) and (b) give totally the wrong picture of f(x). When you have learnt some graphics get your program to draw the graph of f(x) for the three cases superimposed (see the solution to Ex. 12.1). The transcedental number e (2.718281828 ...) can be shown to be the limit of
1/(1—x)"”
as x tends to zero (from above). Write a program which shows how this expression converges to e as x gets closer and closer to zero.
A “square wave’ of period 7 may be defined by the function
f(t) =1(0<t<T), Spe <<),
The Fourier series for f(t) is given by 4 00 l f (2k + 1)at —- j&%&2 — sin | ——— mn k=0 2k+1 | ZL |
It is of interest to know how many terms are needed for a good approximation to this infinite sum. Taking T = 1, write a program to compute 7 terms of the series for t from 0 to 1 in steps of 0.1, say. Run the program for different values of n, e.g. 1, 3, 6, etc. (See Chapter 12 for the graphics version. )
If an amount of money A is invested for k years at a nominal annual interest rate r (expressed as a decimal fraction), the value V of the investment after & years is given by
V=A(1 + 7/n)"
where 7 1s the number of compounding periods per year. Write a program to compute V as n gets larger and larger, i.e. as the compounding periods become more and more frequent, like monthly, daily, hourly, and ultimately instanta- neously (?). Take A = 1000, r= 4% and k = 10 years. You should observe that your output gradually approaches a limit. Also compute the value of the formula
A alk
for the same values of A, r and k (use the built-in function EXP), and compare this value with the values of V computed above. What do you conclude?
CONTROL STRUCTURES II: REPETITION T7
6.9
6.10
6.11] 6.12
6.13
6.14
6.15
6.16
Write a program to compute the sum of the series
D2 ie
such that the sum is as large as possible without exceeding 100. The program should print out how many terms are used in the sum.
The compound interest program earlier in the chapter shows that an amount of $1000 will double in about seven years with an interest rate of 10%. Using the same interest rate, run the program with initial balances of $500, $2000 and $10000 (say) to see how long they all take to double. The results may surprise you. Write a program to implement the structure plan of Ex. 3.2.
Use the Taylor series
cos(x) = 1 — x7/2! + x4/4! — x°/6! + ...
to write a program to compute cos(x) correct to four decimal places (x is in radians). See how many terms are needed to get four-figure agreement with the built-in function COS.
A man borrows $10000 to buy a used car. Interest on his loan is compounded at the rate of 2% per month while the outstanding balance of the loan is less than $5000, and at 1% per month otherwise. He pays back $300 every month, except for the last month, when the repayment must be less than $300. He pays at the end of the month, after the interest on the balance has been compounded. The first repayment is made one month after the loan is paid out to him. Write a program which prints out a monthly statement of the balance (after the monthly payment has been made), the final payment, and the month of the final payment.
A projectile, the equations of motion of which are given in Chapter Four, 1s launched from the point O with an initial velocity of 60 m/s at an angle of 50° to the horizontal. Write a program which computes and prints out the time in the air, and horizontal and vertical displacement from the point O every 0.5 seconds, as long as the projectile remains above a horizontal plane through O.
When a resistor (R), capacitor (C) and battery (V) are connected in series, a charge Q builds up on the capacitor according to the formula
O(t) = CV(1 — e7"*S)
if there is no charge on the capacitor at time t = 0. The problem 1s to monitor the
charge on the Capacitor every 0.1 seconds in order to detect when it reaches a level of 8 units of charge, given that V = 9, R= 4 and C= 1. Write a program which prints out the time and charge every 0.1 seconds until the charge first exceeds 8 units (i.e the last charge printed must exceed 8). Once you have done this, rewrite the program to print the charge only while it is strictly less than 8 units.
Write a program which behaves like a primitive stop-watch (to the nearest second). It should prompt the user to hit any key to start, and any key to finish.
CHAPTER 7
ERRORS
Programs seldom run correctly the first time, even for experienced programmers! In computer jargon, an error in a program 1s called a bug, and the process of detecting and correcting such errors is called debugging. To assist us in this sometimes arduous task, the compiler prints various types of warning or error messages, called diagnostics. There are three main types of errors: compilation errors, run-time errors, and errors of logic. There is also a more subtle error — rounding error — which creeps in sometimes because of finite machine precision. In this chapter we deal with the sort of errors that can arise with the programming we have done so far. Other possible sources of error wi!" be pointed out in later chapters in the appropriate places.
7.1. Compilation Errors
These are errors of syntax and construction, like spelling mistakes, that are picked u
by the compiler during compilation, the process whereby your program Is translated into machine code. They are the most frequent type of error, and in True BASIC they are “‘fatal”’, 1.e. the program will not execute until the error has been corrected. True BASIC, unlike most versions of Street BASIC, generates compiler messages that are usually quite helpful. The cursor stops in the editing window at the place where the error was spotted, and an error message is printed in the history window.
Since True BASIC uses a compiler, it attempts to translate the whole program into machine code at one “‘pass’’. It therefore takes a global view of the program, and will remember up to five compilation errors at one pass. If an error is reported, you should correct it, and then press F2 to get the next error message. Continue like this until you have corrected all the reported errors, and only then should you press F9 to run again. This is in sharp contrast with an interpreter, which can only report one error every time you run the program, because it only translates one line at a time.
There are a large number of error messages, listed in Appendix B of the True BASIC Reference Manual, with some indications of the most likely cause of the errors. These should be consulted if you are unable to correct the error yourself. Some of the more common errors are discussed briefly below (you have probably come across most of them yourself by now!).
Disk full.
Although this usually means what it says, it also comes up if you type a space in a filename, as in
Ok. Save B: Plonk
S() CHAPTER 7
Remember that the drive name is part of the filename.
Doesn't belong here. The cursor points to some word or character in your program that doesn’t make sense (to True BASIC!), e.g. the comma (which should be a point) in the statement LET G = 9,8
Ending doesn’t match beginning. This usually means you haven’t ended a structure like IF-THEN-ELSE, or FOR-NEXT correctly (by leaving out the END IF or the NEXT). It also occurs with the following rather subtle error:
IF MARK >= 50 THEN PRINT "PASS" ELSE
PRINT "FAIL" END IF
The compiler assumes that the IF-THEN is meant to be a simple one-line statement. It thinks therefore that the ELSE doesn’t have a beginning IF. To correct it, the statement PRINT “PASS” should be typed on a separate line.
Expected fing.
thing stands for some word or punctuation mark that the compiler expects in that place. E.g. with the statement
INPUT PROMPT "Give me a number’; X the cursor stops under the semi-colon and True BASIC prints the message Expected ”:”
Illegal expression.
This usually means that an expression doesn’t follow True BASIC’s rules. E.g. it will occur with statements like
IF MARK >= 70 AND < 75 THEN PRINT "II-+”
with the cursor pointing to the “‘< since’, “‘ < 75” is not a logical expression. Illegal statement.
This usually occurs when a keyword has been left out, as in
X= 1
where the keyword LET has been omitted (if you are converting from Street BASIC
you will often do this!).
Must be a variable. This message comes up with the statement INPUT "Give me a number’: X
when the cursor will stop under the first double quote. This seems rather mysterious at first, since the actual error is that the word PROMPT was left out. The compiler,
ERRORS 81
however, expects a variable after the keyword INPUT. It-all goes to. show that error messages can sometimes be misleading because the compiler isn’t intelligent!
Name can’t be redefined.
This message is printed if you try to use a reserved word (see Appendix E) as a variable, e.g. in
LET TIME = O
7.2. Run-time Errors
If a program is successfully compiled, it runs. Errors occurring at this stage in the proceedings are called run-time errors, and are usually fatal, causing the program to ‘crash’’. An error message, such as “Division by zero’, or ‘““SQR of negative number” is printed. All the run-time error messages are listed alphabetically with the compilation error messages in the True BASIC Reference Manual. Run-time errors also have error
numbers. There is a separate list of errors in order of error number in the Reference Manual.
The BREAK and CONTINUE commands are very useful for debugging. BREAK enables you to interrupt execution of a program at any point, and examine and possibly change any variables. CONTINUE enables you to continue executing from that point (which 1s called a breakpoint). See Appendix B for details.
Sometimes an error occurs because of a misspelt variable name. To guard against this. use the OPTION TYPO and LOCAL statements, e.g.
OPTION TYPO
LOCAL Num, X, 2Z(20)
Any variables subsequently not listed in a LOCAL statement will cause the error message ‘Unknown variable’, and True BASIC will point to the misspelt name. Note that the dimensions of arrays must be given in full (see Chapter Nine).
Debugging with DO TRACE
This command lets you watch a program executing step by step. The syntax 1S DO TRACE, option (varl, var2, ...)
where option may be “‘step”’, “‘slow’’, “‘fast’’, or ‘‘break”’. Only the first letter of each is necessary. The program is traced highlighting one line at a time. Current values of the variables listed are displayed in a separate box. Up to eight variables may be traced at a time. See Appendix B for more details.
Intercepting Errors with Error Handlers
Sometimes it is very inconvenient (to say the least!) when a large program crashes leaving everything hanging. True BASIC therefore has a device called an error handler for intercepting otherwise fatal run-time errors.
82 CHAPTER 7
To illustrate this useful device, suppose we are given the time of flight 7F of a projectile ona horizontal plane, launched at an angle AL radians. We are required to compute the launch velocity UL, the time T at which the projectile will be a given height HT (less than its maximum height) above the ground on its way up, and the angle AV to the horizontal at which it is moving at time 7. Enter and run the following program as it
Stands:
! Example of Error Handler
LET TF = 10 LET G = 9.8 LET HT = 10
WHEN ERROR IN LET UL = G * TF / SIN( AL ) LET T = (2 * UL + SQR( 4 * UL* 2—8 * G * HT )) / (2 * G) LET AV = ATN( (UL * SIN( AL )—G * T ) / (UL * COS( AL )) )
USE PRINT “Error’; EXTYPE;": "; EXTEXTS PRINT "Occurred at line”; EXLINES END WHEN PRINT UL; T; AV END
The output should be:
Error 3001 : Division by zero. Occurred at line 8 in Main 0 0 0
The only error here is that the programmer forgot to assign a value to the launch angle AL. True BASIC automatically sets it to zero, and since the sine of zero is zero, this causes a division by zero in line 8 of the program. However, the error handler, described
in detail below, prevents a general crash. The general syntax of the error handler is: WHEN ERROR IN
_ protected block
USE
¢ error handler
END WHEN
The block of statements between WHEN and USE 1s called the protected block, and the block between USE and END WHEN 1s called the error handler. Normally True BASIC executes only the protected block and skips the error handler. However, if any run-time error occurs in the protected block, instead of crashing and printing the usual error message, True BASIC skips to the error handler and executes the statements there. Execution then continues with the next statement after END WHEN. You can therefore
ERRORS 83
write an error handler to take whatever action you want in the event of an error (you obviously have to be able to anticipate an error of some sort in advance).
For compatibility with ANS BASIC, the word EXCEPTION may be used instead of ERROR anywhere in a program.
Note that three new built-in functions were introduced in the error handler: EXTYPE, EXTEXT$ and EXLINES. These may be used anywhere in a program, but are most useful In an error handler.
EXTYPE returns the error number of the most recent error. Its value can lie in three different ranges:
Q: no error yet
1 to 999: available for your use (see below)
1000 and over: True BASIC error messages
EXTEXT$ returns the text of the last error message that occurred (if the error occurred in a protected block the message would not have been printed).
EXLINE$ returns the location, usually as a line number, in your program where the last error occurred.
Error handlers may be nested, and the EXIT HANDLER statement may be used to “‘pass”’ an error back up to a surrounding handler at a higher level. The general idea is that some errors can be fixed on the spot by appropriate user action, while others might require more drastic measures (such as rewriting the program!). You will only need to use this facility if you are a more experienced programmer.
You can define your own error codes using the range 1 to 999 for hitherto unknown errors that might crop up, with the statement
CAUSE ERROR expr, expr$
E.g.
CAUSE ERROR 123,”Some unknown disaster has struck!”
Used in an error handler, this will prevent a crash, but still print the message.
Error handlers are very useful in file handling programs, where one might accidentally attempt to read from files that aren’t there, or write to files that already are there. Examples of usage are given in Chapters Nine and 11.
7.3. Errors in Logic
These are errors in the actual algorithm you are using to solve a problem, and are the most difficult to find: the program runs, but gives the wrong answers! It's even worse if you don’t realize the answers are wrong. The following tips might help you to check out the logic.
* Try to run the program for some special cases where you know the answers.
* If you don’t know any exact answers, try to use your insight into the problem to check whether the answers seem to be of the right order of magnitude.
84 CHAPTER 7
* When debugging remember that the variables remain “active” after the program has run. You can then use PRINT statements as commands in the history window to print the values of intermediate variables, and this can sometimes help to track down the bug.
* Try working through the program by hand (or use DO TRACE) to see if you can spot where things start going wrong.
/.4. Rounding Error
At times the computer gives numerical answers to a problem which appear inexplicably different from what we know to be the correct mathematical solution. This can be due to rounding error, which results from the finite precision available on the computer, e.g. four or eight bytes (32 or 64 bits) per variable, instead of an infinite number. Run the following program (the PRINT USING statement is discussed in Chapter Eight, and is used here to print more decimal places): LET X = 0.1 DO
LET X = X + 0.01
PRINT USING "#.###4##4#FFFFFEFEFEEEEE. X;
LOOP UNTIL X = 0.2 END
You will find that you need Ctrl-Break to stop the program. X never has the value 0.2 exactly, because of rounding error. It would be better to replace the LOOP statement
with LOOP UNTIL X > 0.2
Consider also the following example:
LET A = 2
LET B = SQR( A) * 2
IF A = B THEN PRINT "NUMBERS EQUAL” PRINT A-B
END
Ok. run
4.44089e—16
Mathematically, A should be equal to B. But the test for equality fails because they have a non-zero difference, due to rounding error. The IF statement should be replaced by
something like
IF ABS( A-—B ) < 1E-—10 THEN PRINT "NUMBERS ARE PRACTICALLY EQUAL” or, even better, by
IF ABS( A—B ) <=EPS(A) THEN...
It is always better to use a test like this to compare two expressions, rather than a straight test for equality, which can often fail because of rounding error.
ERRORS 85
Rounding error may also be reduced by a mathematical rearrangement of the problem. If the well-known quadratic equation is written in the less usual form
x*— 2ax te =0
the two solutions may be expressed as
X¥; =a+ V(a? —e),
x2 =a— V(a* —e).
If eis very small compared with a, the second root is expressed as the difference between
two nearly equal numbers, and considerable significance is lost. E.g. taking a = 5e6 and € = 1 gives
X2 = 9.96515e—8
in True BASIC. However, the second root may also be expressed mathematically as x2 = ella + V(a* — e)] = e/2a.
Using this form in True BASIC gives
x2 = 1e-7,
which is more accurate.
Rounding error is also discussed in section 15.3.
summary
* Compilation errors are mistakes in the syntax (coding).
* Execution (run-time) errors occur while the program is running, and may be intercepted by an error handler.
* Breakpoints may be inserted into a program with the BREAK command.
* Logical errors are errors in the algorithm used to solve the problem.
* Rounding error occurs because the computer can store numbers only to a finite accuracy.
EXERCISES 7.1. The Newton quotient f(x + h) — f(x)|/h
may be used to compute the first derivative f’ (x) of a function f(x), if his “‘small’’. Write a program to compute the Newton quotient for the function
fle) =x at the point x = 2 (the exact answer is 4) for values of A starting at 1, and decreasing by a factor of 10 each time. The effect of rounding error becomes
apparent when h gets “‘too small’’, i.e. less than about 1e—12. (See section 15.3 for the solution.)
86
7.2
To
CHAPTER 7
The solution of the set of simultaneous equations
ax + by=c ax +ey=f
quoted in Ex. 5.6 is given by
x = (ce — Df) / (ae — bd),
y = (af — cd) / (ae — bd).
If (ae — bd) is small, rounding error may cause quite large inaccuracies in the solution. Consider the system (McCracken and Dorn, 1964):
0.2038x + 0.1218y = 0.2014, 0.4071x + 0.2436y = 0.4038.
Show that with four-figure floating point arithmetic the solution obtained is x = —1.714, y = 4.286. This level of accuracy may be simulated in the solution of Ex. 5.6 with some statements like
LET AE = ROUND( A * E * 1E5 ) / 1E5
and appropriate changes in the coding. The exact solution, however, which can be obtained with normal computer accuracy, is x = —2, y = 5. If the coefficients in the equations are themselves subject to experimental error, the “‘solution”’ of this system using limited accuracy is totally meaningless.
This problem, suggested by R.V. Andree (cited by McCracken and Dorn, 1964), demonstrates another numerical problem called ill-conditioning, where a small change in the coefficients causes a large change in the solution. Show that the solution of the system
x + 5.000y = 17.0 L.5x + 7.501ly = 25.503
Is xX = 2, y = 3, using the program in Ex. 5.6 with normal precision. Now change the constant term in the second equation to 25.501, a change of about one part in 12000, and observe that a totally different solution results. Also try changing this term to 25.502, 25.504, etc. If the coefficients are subject to experimental errors, the solution is again meaningless. One way to anticipate this sort of error is to perform a sensitivity analysis on the coefficients: change them all in turn by the same percentage, and observe what effect this has on the solution.
CHAPTER 8
ADVANCED INPUT/OUTPUT
So far we have concentrated on writing programs that give the right answers, without paying much attention to exactly how the numbers are printed (e.g. number of decimal places, number of spaces between items, right-justification of numbers, etc.). In this chapter we look at how to produce output that is neater and more pleasing to the eye with the PRINT USING statement. We will also discuss how to get input from, and send output to text files.
8.1. Rabbit Breeding the Fibonacci Way
To make the exercise more interesting, we will write a program to model a rabbit population using the following assumptions:
1. We start with one new-born male/female pair;
2. A new-born pair produce (instantaneously!) a male/female pair after two months;
3. Male/female pairs of age two months and older produce a male/female pair every month.
If we represent the number of male/female pairs after m months by the variable F,,, it can be shown quite easily that F,, takes the following values:
Month n Population F, ]
JI nn & Wi
8
The sequence {F,,} is called the Fibonacci sequence. We want to write a program that computes the total population for up to, say, 12 months. (Note that the model does not allow for deaths; this dreadful possibility is discussed in Chapter 14). It can be shown mathematically that each term in the series is the sum of the previous two, 1.€.
Fy — Py . fi.
We therefore need to have three variables in the program, FN, FN_1 and FN_2, which are updated each month. An interesting feature of the Fibonacci sequence 1s that
limit F,,/F,—-1 = (1 + V5)/2 = 1.6179...
hH— 0
88 CHAPTER 8
We will also compute this ratio, to verify that it has a limit (in fact the limit is the same whatever the two starting values in the sequence). The PRINT USING statement, which is discussed in detail below, is used to arrange the layout, or format of the output of the following program (note that in the line of output for month 3 the characters ‘““#”’ and “bh”? have been inserted into the text to aid the eye: they will not be printed literally).
| RABBIT BREEDING WITH FIBONACCI | FN; TOTAL AFTER N MNTHS / FN_1 : TOTAL AFTER N—1 MNTHS | FN2 : TOTALAFTERN-2MNTHS / J : MONTH COUNTER
LET FN_1, FN_2 = 1 PRINT “MONTH POPULATION RATIO”
PRINT FOR J = 3 10 12 LET FN = FN_.1 + FN_2 LET RATIO = FN / FN_1 PRINT USING" ## HEP .F #.HHHH": J, FN, RATIO LET FN_2 = FN_1 LET FN_.1 = FN
NEXT J END Output: MONTH POPULATION RATIO b#3bbbbbbbbbbb###2.0 bbbbbbbbbb2.0000 4 3.0 1.5000 5 5.0 1.6667 6 8.0 1.6000 7 13.0 1.6250 8 21.0 1.6154 9 34.0 1.6190 10 55.0 1.6176 11 89.0 1.6182 12 144.0 1.6180
8.2. The PRINT USING Statement
The PRINT USING statement is quite unlike the ordinary PRINT statement. Print zones are ignored, and output is printed according to a mask or image that you specify in the PRINT USING statement. The general syntax is
PRINT USING formats: item, item2, ...
PRINT USING format$: item, item2, ...;
where formats is a string expression, called a format string, which specifies exactly how the items in the statement are to be printed. If the statement ends with a semi-colon, the cursor Is left at the end of the output line, otherwise it moves to the start of the next line. Semi-colons may not be used between items since they do not have the same effect as in the ordinary PRINT.
ADVANCED INPUT/OUTPUT | id
The format string may contain a mixture of literal characters, and format items consisting of special formatting characters. The literal characters are printed with the output items exactly as they appear in the format string, but the formatting characters specify how the output will be formatted, and are not printed literally. The eleven special formatting characters are:
Pa" Fa He 35 SS
Most of the complications arise in printing numbers, so we will discuss this first.
8.3. PRINT USING with Numbers
The numeric formatting characters are divided into three classes: leading characters (+ — $), digit characters (* % #) and other characters (, .*). One or more digit characters must be present in each format item.
The Digit Characters (* % #)
The most common digit character is the number sign (#). Each number sign represents a digit position in the output field. A decimal point may be inserted in the format item. If the output item does not fill the field it is right-justified. If a PRINT USING statement has more output items than format items, the format string is re-used repeatedly. If there are more format items than output items, the leftover format items are ignored. However, any literal characters following the format item last used are always printed. Some examples follow.
LET X = 123.4567
PRINT USING "###.#": X; PRINT USING "#####": X END
Ok. run
123.5 123
Note that the output item is rounded (to an integer if necessary). Remember that the print zones are ignored, and that a comma should never be used after the last output item.
LET X = 12.3446 PET s¥-es" 193 PRINT USING "###.##": X, Y PRINT USING "#####": X, Y END Ok. run 12.34123.00 12 123
If you want to use the TAB function, it must be used in a PRINT statement on a separate line:
LET X LET Y
6.45 7.34
90) CHAPTER 8 I me i eS SS
PRINT USING "X=##.#": X; PRINT TAB( 10 )
PRINT USING 'Y=##.#": Y END
RUN
Ok. run
X= 65 Y= 7.3
Literal characters may be mixed with the format items:
LET A = 1.2
LET B = 3.4
PRINT USING "The sum of ##.# and ##.# is ##.#": A, B, A+B END
Ok. run
The sum of 1.2 and 3.4 is 4.6 If the output number is too large for the format item, the entire field is printed as asterisks:
LET X = 123.456
PRINT USING "##.4#": X
END
Ok. run
KKKKK
When the ‘‘#” digit character is used, leading zeros are printed as blanks. However, the ‘“*?” and ‘‘%”’ digit characters cause leading zeros to be printed as asterisks and zeros respectively (digit characters may not be mixed on the same side of the decimal point):
LET X = .12 PRINT USING "X: ##.4##": X
PRINT USING "X: **.**": X
PRINT USING "X: %%.%%": X
END
Ok. run
X: .12
X: **.12
X: 00.12
If the output item is negative, the minus sign takes up one position, so this must be allowed for:
PRINT USING "X: ##.##": -—1.2 X: —1.20
The Leading Characters (+ — $)
The printing of a plus or minus sign (and a dollar sign) may be further controlled by the use of one or two of the leading characters. A single plus leading character causes the number to be printed with a single plus or minus sign on the extreme left of the field, whereas a single minus leading character prints a leading space or a single minus sign on the extreme left of the field. The dollar sign may be mixed with either of the other leading characters to print a leading dollar sign.
ADVANCED INPUT/OUTPUT 9]
The first leading character may be repeated, and will be turned into leading spaces or leading digits if necessary. In other words, if you want the sign printed right up against the number, fill up the format item with the appropriate leading character from the left, and put only one “#”’ digit character before the decimal point. Examples:
PRINT USING "+####.#": 12.3 PRINT USING "++++#.#": —12.3 PRINT USING "$$$$#.##": 99.99 PRINT USING "———$#.##”: —99.99 PRINT USING "$****.##": 99.99 + 12.3
—12.3
$99.99 —$99.99 $**Q9_ 99
Other Characters (, . *)
We have already seen how to use the decimal point in a format field. A comma may be used to print acomma anywhere if the characters on either side are digits (otherwise the comma is turned into a space):
PRINT USING’ =-+—= S# ###.#F#": —123456.7 —$123,456.70
The circumflex (*) may be used to indicate the size of the exponent if scientific notation is required. The exponent field must come at the end of the format item, and must be at least three characters long, to allow for the ‘“‘e’’, a plus or minus sign, and at least one digit for the exponent. No leading zeros are printed in this format, so the three digit characters all have the same effect. E.g.
PRINT USING "###.###* **°": 123456.78 PRINT USING "-——-—-—-%%.### ***": —123456.78 123.457e+03
—12.346e+4
8.4. PRINT USING with Strings
Strings may be printed by any numeric format item. By default, strings are padded with spaces to be as long as the format item. Spaces are added to both sides of the string so as to centre it (if necessary, there will be one more space on the right than on the left). If the string is too long to fit, the entire field is printed as asterisks. A string may be left-justified by starting its format item with the symbol “<”’, and right-justified with a god ay,
PRINT USING "######": "UCT" PRINT USING "<###.##": "UCT" PRINT USING "$$—#.#>": "UCT" UCT UCT UCT
92 CHAPTER 8
8.5. Files
Output from a program may be sent to a file which resides permanently on a diskette, and input may also be fetched by a program from such a file. This facility provides a means of keeping records which constantly need to be updated or examined and analysed. A file may be thought of as a continuous stream of data, rather like a tape. There are three kinds of files in True BASIC: text files, record files and byte files. In this section we are going to look at an example using text files, which will carry through to the next chapter: initializing and updating a student mark file which contains a list of students’ names with their marks for various course offerings. Record and byte files will be discussed in Chapter Ten.
Updating Student Marks
A text file consists simply of lines of characters. They look just like program files, and may be viewed on the screen with the True BASIC editor. This makes them particularly easy to work with. We will begin with a program to write a list of names to a new text file in drive B called ‘‘MARKS.”’. Before a file can be used by a program, it must have a channel associated with it by means of an OPEN statement. This channel provides the communication link between the file and the program until the channel is closed at the end of the program. The OPEN statement also specifies the kind of file (handled by the ORGANIZATION part), and whether it is a new or existing file (handled by the CREATE part). In the example below, it is assumed that there is no file on the diskette with the name “MARKS.”’. If there is, the program will crash. Try the program, and type in a short list of names, as shown below:
! SENDING NAMES TO A TEXT FILE OPEN #1: NAME "B:MARKS.”, ORGANIZATION TEXT, CREATE NEW INPUT PROMPT "Name: ”: NAME$
DO WHILE NAME$ <> "SNOOPY” PRINT #1: NAME$ INPUT PROMPT "Name: ”: NAME$ LOOP CLOSE #1 END Ok. run Name: ABLE ER Name: BOTHA BJ Name: SMITH ZZ Name: SNOOPY When you run the program you should notice the red light going on next to drive B as the file “MARKS.” is created and written to. Note that a period must be inserted after its name in the OPEN statement to avoid having the ‘.. TRU” extension automatically appended by True BASIC (unless of course you want it).
The OPEN statement is discussed in detail below. It has several optional parts. Only the NAME part must be there.
ADVANCED INPUT/OUTPUT 93
The DO loop inputs names from the keyboard, until the dummy name “SNOOPY’”’ is read, which signals the end of the data. The PRINT statement for text files works exactly as it does for the screen, except that the channel number must be given. You can think of the text file as being a copy of the screen. It is divided into print zones, so commas, semi-colons, PRINT USING, etc. have exactly the same effect as on the screen.
The CLOSE statement at the end disconnects channel #1 from the file.
When the program has run, save it (if you want to keep it), and then get the file “MARKS.” into the editing window with the OLD command to see if the program worked. You should see some lines of text, each with one name on it. If the file has no
extension you must remember to type the period, otherwise True BASIC assumes the extension “.TRU”:
OLD B:MARKS. It will also not show up with the FILES B: command. Instead use FILES B:*.
Weare now ready to update the student file “MARKS” (the period will be omitted from now on) by writing some test results to it. Unfortunately, a text file cannot be updated directly with a program (this can be done with record and byte files), since you can only add new data on at the end of it, or erase it completely and start again at the beginning. You cannot simply replace an item somewhere in the middle of the file. Of course you can do this with the screen editor, or a word processor, but we are trying to do this from inside a frue BASIC program. The way out is to read the students’ names one at a time from “MARKS”, input a mark for each from the keyboard, and write the name with the mark to a new text file which we shall call “SCRATCH”. When all the marks have been typed in, “MARKS” must be erased, and “SCRATCH” copied back into it. Enter the following program, and try it out with some sample data:
| UPDATES STUDENT MARKS BY ADDING MARKS FOR ONE OFFERING
OPEN #1: NAME ”"B:MARKS.” | The current mark file OPEN #2: NAME "B:SCRATCH.”, CREATE NEW ! The updated mark file DO WHILE MORE #1
INPUT #1: NAME$
PRINT USING "<##########": NAMES:
INPUT PROMPT “Mark: ": MARK
PRINT #2: NAME$;”,”: MARK
LOOP
SET #2: POINTER BEGIN | Ready to read back
ERASE #1 | Delete contents of MARKS DO WHILE MORE #2 | Copy SCRATCH into MARKS
LINE INPUT #2: LINES PRINT #1: LINES LOOP
CLOSE #1 | Close all channels CLOSE #2
END
04 CHAPTER 8
Ok. run
ABLE ER Mark: 78
BOTHA BJ Mark: 0
SMITH ZZ Mark: 99
The two open statements connect channels #1 and #2 to the files “MARKS” and “SCRATCH” respectively. “MARKS” already exists, sono CREATE part is needed. If the file does not exist, the program will crash. However, “SCRATCH” should be a new file, so a CREATE part is needed in the second OPEN statement. If there is already a file with such a name, the program will also crash. In the next chapter we will see how to use an error handler to intercept these possible errors. The program context makes it clear to True BASIC that the files are text files, so the optional ORGANIZATION part is
left out, just to be different.
Input from a text file works more or less like input from the keyboard, except that the channel number must be given. This means that True BASIC expects to find data items on the same line in a text file to be separated by commas. The logical function MORE #1 is used to test if there is more data in the file. It works just like MORE DATA. END #1 could also be used: it is true only if you're at the end of the file.
After each student’s mark has been keyed in (in the first DO loop), his name and mark are sent to “SCRATCH”. Note that a comma has to be printed literally between the
name and mark:
PRINT #2: NAME$; ”,”; MARK This is so that the INPUT statement can be used to read them back again.
When all the marks have been entered, we want to read them back from “SCRATCH”, but we can’t do this immediately. A file has a pointer, which points to where the file is next going to be read from or written to. The pointer for “SCRATCH” must therefore be moved back to the beginning of the file, and this is done with the statement
SET #2: POINTER BEGIN
Since an existing text file cannot be overwritten (as a protection), ““‘MARKS”’ has to be erased before it can be rewritten. The ERASE statement deletes the contents of the file, which still exists, but is empty. The second DO loop then uses LINE INPUT #2 to read each line of “SCRATCH” and PRINT #1 to write it to “MARKS”.
Finally, both files are closed. “SCRATCH” could have been removed from the diskette with the UNSAVE statement, but it is better to leave it there as a backup until you have checked that ‘‘MARKS” has in fact been updated.
You can always view a text file on the screen, but the following program prints the names and marks in a more pleasing format:
! READS STUDENT MARK FILE AND PRINTS NEAT FORMATTED OUTPUT
OPEN #1: NAME “B:MARKS.”
CLEAR
LET N = 10
LET FORMAT$ ="<" & REPEATS("#”, N ) PRINT "NAME"; TAB( N + 2 );"MARK”
ADVANCED INPUT/OUTPUT 95
DO WHILE MORE #1 INPUT #1: NAME$, MARK PRINT USING FORMAT$: NAME$; PRINT USING "###": MARK LOOP
CLOSE #1 SET CURSOR 24, 1 PRINT "Hit any key to continue ...”
END
Ok. run
NAME MARK ABLE ER 78
BOTHA BJ 0
SMITH ZZ 99
The REPEATS$ function is used to construct a format item of N+1 formatting characters to print the name. Together with the TAB function, this ensures that the marks always fall under the heading ‘‘MARK” no matter what value N has.
Files in General
The information in this section applies to all three kinds of files. The general form of the OPEN statement is:
OPEN #expr: NAME expr$, ACCESS expr$, CREATE exprS, ... .. ORGANIZATION expr$, RECSIZE expr
where the strings may be constants, variables or expressions. The channel number must be a numeric expression which evaluates to a number in the range 1 to 1000. You may have up to 25 different files open at one time, if your computer system allows that many.
Channel #0 is the channel for the screen and keyboard, and is always open. It cannot be closed.
The only part of the OPEN statement that is compulsory is: OPEN #expr: NAME expr$
The other parts (ACCESS, CREATE, ORGANIZATION and RECSIZE) are syntactically optional, and can be in any order. If two or more are present, they must be separated by commas. The strings allowed after the first three are:
Option String Meaning ACCESS INPUT Read-only
OUTPUT Write-only
OUTIN Read and/or write (default) CREATE NEW Create new file
OLD Use existing file (default)
NEWOLD Use existing file or create new one
CHAPTER 8
96
ORGANIZATION TEXT Text file RECORD Record file BYTE Byte file
Examples
OPEN #1: NAME File$, ACCESS INPUT, ORGANIZATION RECORD OPEN #K: NAME ”B:INDEX”, ORGANIZATION TEXT, CREATE OPTIONS
Note that the string constants may be typed without quote marks. Mixtures of lower- and uppercase are allowed.
The meanings of the various options are fairly straightforward, and run-time errors will occur in obvious situations, like trying to erase or write to a read-only file, or trying to create a file that is already there. If you want more specific details, you should consult
the Reference Manual.
Different channels may be assigned to the same file at the same time only if access is INPUT.
If the ORGANIZATION option is left out, True BASIC checks the file and uses whatever Organization it has (if the file is empty, it is assigned an organization when the first statement which determines its organization is executed). The word ORGANIZATION may be abbreviated to ORG.
The RECSIZE option only applies to record and byte files (see Chapter Ten).
A channel is closed as follows:
CLOSE #expr
This statement disconnects the channel from the file, and finishes writing out the file to the diskette, 1f appropriate. It is a good habit to close all channels at the end of a program, even though all channels are automatically closed when the program
terminates.
The statement
ERASE #expr
deletes the contents of a file. The file still exists, but is empty. The pointer is set back
to the start of the file, and its organization is forgotten and can be changed by the next statement using the file. A read-only file cannot be erased, by definition, since ERASE
changes its contents.
A saved file may be removed from a diskette by the statement
UNSAVE name$ A file should always be closed before it 1s unsaved, or strange things may happen!
The ASK statement lets you find out information about open channels. The questions that apply to all kinds of files are:
ADVANCED INPUT/OUTPUT 97
ASK #expr: ACCESS var$
ASK #expr: FILESIZE var (size given in bytes or records) ASK #expr: NAME var$
ASK #expr: ORGANIZATION var$
See the Reference Manual for more specific details.
Text Files in Particular
A text file’s margin or print zone width may be set or ascertained in the same way as the screen's:
ASK #expr: MARGIN var
ASK #expr: ZONEWIDTH var SET #expr: MARGIN expr SET #expr: ZONEWIDTH expr
A text file’s pointer may be set to the beginning or end of the file with the SET POINTER Statement:
SET #expr: POINTER BEGIN SET #expr: POINTER END
These statements are compatible with ANS BASIC. True BASIC allows you to shorten them to
RESET #expr: BEGIN
RESET #expr: END
The position of the pointer may be ascertained with the statement ASK #expr: POINTER var$
If the pointer is neither at the beginning nor the end of the file, var$ is set to “MIDDLE”.
Text files may only be written to with the PRINT (USING) statement (note the comma after the channel number in PRINT USING):
PRINT #expr Ino colon for blank line PRINT #expr: iteml; item2, ...
PRINT #expr, USING formats: item], item2, ...;
A text file may not be overwritten, but data can be added on at the end (appended). To do this, the file’s pointer must first be set to the end of the file.
Text files may only be read with the INPUT statement, and the pointer must be set to the beginning of the file (i.e. you cannot start reading a text file from anywhere else). OPEN automatically sets the pointer to the beginning. The form of INPUT 1s
INPUT #expr: var, var$, ... LINE INPUT #expr: var$, ...
Data items on the same line in the file must be separated by commas. A line of data may end with a comma to indicate that more data for that INPUT may be found on the next
9§ CHAPTER 8
line (the same applies to keyboard input). The INPUT statement may have a trailing comma, but no prompt.
The two logical functions
END #expr MORE #expr
may be used to test for more input.
Text files are useful for storing program output