Reference / Paper · 1983
Learn BASIC: A Guide to Programming the TI Compact Computer 40
David Thomas's guide to programming the TI CC-40 in BASIC.
Reference / Paper · 1983
David Thomas's guide to programming the TI CC-40 in BASIC.
the Texas Instruments Compact Computer 40 DAVID THOMAS COMPACT COMPLITEF . TI99IUC.it . McGraw-Hill/VTX Series Buchsbaum and Mauro Microprocessor-Based Electronic Games (1983) (A BYTE Book) Buffington Your First Personal Computer (forthcoming, 1983) (A BYTE Book) Chiu and Mullish © CRUNCHERS: 21 Simple Games for the TIMEX/ SINCLAIR 1000 2K (1982) (A BYTE Book) Kimberley | MICROPROCESSORS: An Introduction (1982) Mullish — BASICS: A Guide to the TIMEX/SINCLAIR 1000 (forthcoming, 1983) (A BYTE Book) Thomas _ LEARN BASIC: A Guide to Programming the Texas Instruments Compact Computer 40 (1983) (A BYTE Book) Wells Building Stereo Speakers (1983) A Guide to Programming the Texas Instruments Compact Computer 40 David Thomas with the assistance of Texas Instruments McGraw-Hill Book Company New York St. Louis San Francisco Auckland Bogota Guatemala Hamburg Johannesburg Lisbon London Madrid Mexico Montreal New Delhi Panama Paris San Juan Sao Paulo Singapore Sydney Tokyo Toronto LEARN BASIC: A Guide to Programming the Texas Instruments Compact Computer 40 Copyright © 1983 by McGraw-Hill, Inc. and Texas Instruments. All rights reserved. Printed in the United States of America. Except as permitted under the United States Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a data base or retrieval system, without the prior written permission of the publisher. McGraw-Hill/VTX Series. A BYTE Book. McGraw-Hill edition. 1234567890SEMSEM89876543 ISBN O-07-O0b425?-S LIBRARY OF CONGRESS CATALOGING IN PUBLICATION DATA Thomas, David, date Learn BASIC. Includes index. 1. TICC 40 (Computer)—Programming. 2. Basic (Computer program language) |. Title. Downloaded from www.ti99iuc. it QA76.8.T136T48 1983 001.64'24 82-24905 ISBN 0-07-064257-5 The editors for this book were John A. Aliano and Jeffrey McCartney; and the editing supervisor was Charles P. Ray. Book design by Roberta Rezk. Contents Preface vii Acknowledgments ix Lesson 1 The Tl Compact Computer 40 1 Lesson 2 Numeric Constants and Variables 6 Lesson 3 DISPLAYing Information 11 Lesson 4 Beginning Programming 16 Lesson 5 Strings—Alphanumeric Information 23 Review Test 1 27 Lesson 6 INPUTing Keyboard Information 29 Lesson 7 More on the PAUSE Statement 36 Lesson 8 Program Branching—The GOTO Statement 39 Lesson 9 The NUMBER and RENUMBER Commands 44 Lesson 10 Decision Making—The IF THEN Statement 49 Review Test 2 55 Lesson 11 Order of Calculations 57 Lesson 12 Higher-Order Mathematical Functions 63 Lesson 13. The INT and SGN Functions 66 Lesson 14 Simulating Chance Occurrences 72 vi / Contents Review Test 3 78 Lesson 15 FOR TO NEXT Looping 80 Lesson 16 REM Statements 88 Lesson 17 Storing DATA in a Program 91 Lesson 18 Arrays and Subscripts 99 Lesson 19 The GOSUB and RETURN Statements 110 Review Test 4 118 Lesson 20 More on DISPLAYing Information 120 Lesson 21 Multiple Statement Lines 127 Lesson 22 More on Decision Making 132 Lesson 23. More on FOR NEXT Looping 135 Review Test 5 141 Lesson 24 String Comparisons 143 Lesson 25 String Manipulations 150 Lesson 26 Logical Operations 158 Lesson 27 The ON GOTO and ON GOSUB Statements 164 Lesson 28 Subprograms 170 Review Test 6 179 Appendix A Table of ASCII Codes and Characters 182 Appendix B List of Compact Computer BASIC Reserved Words 190 Appendix C Answers to Review Questions 192 Index 208 Preface The objective of this book is to help you learn BASIC and to show you how to use that language to program the Texas Instruments Compact Computer 40. This book assumes that you have the Com- pact Computer 40 User's Guide supplied with the CC-40 and that you have read the discussions regarding the operation of the com- puter and the functions of the keys. The book does not assume that you understand everything in that manual, or that you have had previous computer programming experience. On the contrary, it assumes that you are now making your first efforts to learn how to program a computer. If you have had previous programming ex- perience, this book will help you utilize the full capabilities of the CC-40. There are 28 lessons in this book. Each lesson covers an important programming concept or BASIC statement or command and is short enough to be easily read in one session. The lessons gradually build on the information discussed in the preceding lessons, so read the lessons in sequence. At the end of each lesson is a sum- mary section. Use this section for a quick review and reinforcement of the contents of the lesson. The only way to learn to program is to write programs and to run them. This book makes that easy. It contains example programs to illustrate every BASIC statement and command discussed. The example programs, however, are designed to do more than just vii viii / Preface show how a statement or command works. They also are intended to arouse your interest and provide you with a core of useful pro- gramming applications that you can adapt or expand to suit your own needs. After reading the lessons and entering the given pro- grams, try to write alternate versions. There are few things as flexible as programming, and there are many ways of making the computer perform the same actions. By composing programs of your own design, you will more quickly develop your programming skills. You will find a review test after every fourth or fifth lesson. The questions in these tests have been selected to reinforce what you have learned in the preceding lessons and challenge you to write programs using that information. Take the time to work these exer- cises. Complete answers to all questions are provided in Appendix C at the back of the book. The explanations accompanying many of the answers make additional points that were not specifically detailed in the text. One of the remarkable things about computer programming is that you can learn to program from reading a book. The only require- ments are enthusiasm, a desire to learn, and your own computer. As you learn the BASIC programming language, one of today’s most useful tools, | trust that you will discover, as | have, that there are few activities more fascinating or rewarding than computer pro- gramming. David Thomas Acknowledgments The author wishes to express his gratitude to Mark R. Waldin, whose idea made this book possible; to Robert E. Whitsitt Il for the support needed to write this book; and to Tom M. Ferrio and Floyd R. Gerwig for their patient reading and many valuable sugges- tions and criticisms. For their help in proofreading the manuscript, | wish to thank Frank Dever, Jeff Gray, Millie Hammond, Ken- neth Edward Heichelheim, Ben Korte, and Walter L. Wdowiak. Ps l Fig. 1-1 Texas Instruments Compact Computer 40 and peripheral de- vices; (right background, top to bottom): TI four-color Printer/Plotter, Tl Wafertape™ Digital Tape Drive, and Tl RS232 Communication In- terface; (right foreground): Wafertape™ digital tape cassettes; (center foreground, left to right, top to bottom): cartridges for 8K Constant Memory™ RAM and Solid State Software™ programs in electrical engineering, finance, and mathematics. Lesson The Tl Compact Computer 40 The Texas Instruments Compact Computer 40 is a remarkably pow- erful computing system. The textbook size of the computer makes it ideal for “on-the-spot” applications that require immediate solu- tions anywhere you go. Its usefulness, though, extends beyond its portability. With its powerful BASIC programming language, expand- ability, and calculating accuracy, the CC-40 can do many things that previously could be done only by large, immobile “main-frame” computers. (See Fig. 1-1.) The CC-40 is equipped with 6144 bytes of random access memory (6K RAM). This is enough memory and power to write sophisticated programs, work complex business and science problems, or store several pages of data. If more memory is needed, the computer can be expanded to as much as 22,528 bytes of memory by installing a 16K RAM expansion cartridge in the computer’s cartridge port. The cartridge port can also be used to run TI Solid State Software™ preprogrammed application cartridges. Directions to the computer and information to be stored in memory are entered by means of a standard typewriter-like keyboard. Al- though the compact size of the computer results in keys that are smaller than those found on a normal typewriter, with a little practice, it is still possible to touch type. To the right of the main keyboard is a block of keys known as a “numeric keypad.” Besides duplicating the number keys on the top row of the keyboard, the numeric keypad 1 “Aska pue xOINb Adqua eyep puke xa} puke SUONE|ND|ed ayeW SAB JOIJUOD 4OSIND yum pedday Syawnu pue pseoghay ALYIMO PsepurIs Op-DD sluawinasul sexe] e4. Z-L “Bld f=ellos welt, [revere fe felts he OF YSLNWOS LoedWO | | aces / jonuoo ne ' ysenuo> Aejdsiq Aejdsip | | yiod jeysAud pnb) jaydepe DY jesaydued saqaeseyr-1 € jeuondo 4s0y yog wiSM9-X3H saspuyed Aaqua eyep wiuoisuedx3 Aioway pue spaads pedAay WLAIEMYOS a}PIS POS suonduny jeidads 404 pseoqgiay Suan ayesedas 40} od aspuyeD ajqeuaisse shay O1 0) dQ ajAis-saymadA) |jN4 *sjoquiAs pue ‘su8is ‘syzew uonenjound ‘siaya] ase2aMo] puke asedieddn Yo jo aBueI {IN} B Jo Aejdsip smoyje Aejdsip jeysAs9 pinbij $,Op-DD siuawnsysuy sex] a4) JO UBISap xUyeW-JOp ay) E-f “BIy Aay (vonun4) [Na] ped Aax Quawny (young) Aay yasay (Aeyaao uo) shay promAay DISVE shay [30] pue [No] JaMOg OF YWILNdWOD LOVdWOD SLNIWNYILSNI SVX3L Aay (289[D) SABPUVED y,IEMYOS IES POS JO WY waAsoway juesuo> 191 4osin> Aay (jonUoD) [71D] Shay JaIUMAdA | Aejdsig 4/ Lesson 1 contains editing keys and the mathematical calculation keys of addi- tion, subtraction, multiplication, and division. The numeric keypad permits calculations and data entry to be performed more quickly than is possible with a typewriter keyboard. (See Fig. 1-2.) The results of programs and calculations, as well as the contents of memory, are viewed through the 31-character liquid crystal display built into the computer. (See Figs. 1-3 and 28-1.) The dot-matrix design allows you to display both uppercase and lowercase letters, as well as various punctuation marks, signs, and symbols. You can even define your own symbols by specifying which dots the computer is to turn on. The computer is powered by four AA-size batteries that maintain the contents of memory even when the computer is turned off. The advantage of this feature is that programs and data can be conveniently stored in the computer without the fear of loss. The power consumption of the computer is low enough to permit up to 200 hours of continuous operation before new batteries are needed. This allows several hours of daily use for up to 6 months between battery changes. Additionally, the computer is equipped with a port for an optional AC adapter. The heart of the computer is a new Texas Instruments 8-bit micro- computer known as the TMS70C20. The microcomputer performs the operations entered through the keyboard or specified in a pro- gram and places the results in the display. If requested, it also sends and receives information from other devices such as the Wafertape™ Digital Tape Drive or the RS232 Communications Inter- face. (See Fig. 1-1.) These devices, known as peripherals, are con- nected to the Compact Computer 40 through the HEX-BUS™ Intelli- gent Peripheral Interface located in the rear of the computer. Each peripheral has its own computing power provided by a built-in dedi- cated microcomputer. The availability of such powerful peripherals as the Wafertape™ Digital Tape Drive, Tl RS232 Communications Interface, and TI Printer/Plotter expand the usefulness of the computer enormously. The Wafertape™ Drive allows you to store programs and data on inexpensive, endless-loop tape cartridges. These tape cartridges The Tl Compact Computer 40 / 5 are available in several storage capacities, up to a maximum of 49,152 bytes (48K). Since the tapes never require rewinding, they permit all storage operations to be completely controlled by the computer. The Wafertape™ Drive unit is powered by four AA batter- ies operating independently of computer console power, and is fully portable. The RS232 Communication Interface allows the CC-40 to be con- nected to a whole range of standard computer equipment, including devices which allow the CC-40 to communicate with other appropri- ately programmed computers throughout the world over regular tele- phone lines. This allows you to use your CC-40 as a remote terminal from your home, office, or even a motel room. The RS232 Interface can be purchased with an optional parallel printer port that allows you to print programs and data on most 80-column printers. The Printer/Plotter peripheral can draw four-color X-Y graphs and make permanent hard-copy printed records of your programs, data, and solutions. With a printing speed of up to 11 characters per second, the Printer/Plotter can print in 10 different type sizes and even permits words to be printed upside down or vertically, if desired. The Printer/Plotter uses standard 2%-inch plain paper rolls and prints in red, blue, green, and black. Power for the Printer/Plotter is supplied from rechargeable AA batteries. The Texas Instruments Compact Computer 40, with its advanced calculation capability, enhanced built-in BASIC language, and flexi- ble peripherals, provides you with the ideal opportunity to learn the BASIC programming language. As computers become increasingly important in our daily lives, it is becoming just as important to acquire a familiarity and understanding of computers. Learning the BASIC programming language is the first step in acquiring that proficiency. The following lessons offer a practical, hands-on approach to learn- ing BASIC, one of the most popular computer programming lan- guages. Lesson atte Numeric Constants and Variables The Compact Computer’s BASIC language allows all but extremely large or small numbers to be entered exactly as they are written. Decimal numbers are entered with a decimal point, if needed, and negative numbers are entered with a minus sign preceding the num- ber. To acquaint yourself with the entry of numbers, work the following problems with the computer. The computer does not need an equals key [=] to perform a calculation; simply type in the problem and press the key. To clear the result of a previous calculation from the display, just start typing the next calculation. Enter Display 1214121 242 7.123—9 -1.877 629+*5.2 3278.8 3/17 ~1764705882 (Note that the [«] key performs multiplication and the [7] key performs division.) Numbers such as those illustrated above are known as numeric constants, since their value cannot vary. In programming, you will more often use numeric variables to represent numbers. A numeric variable is a “name” assigned a number value that can be used in place of a numeric constant. 6 Numeric Constants and Variables / 7 sm ie, The Texas Instruments CC-40 keyboard design allows easy keyboarding for touch-typists. Variables are assigned number values in BASIC using the equals (=) sign. For example, type x=14 into the computer. Before pressing [ENTER], consider the above sequence carefully. It illustrates an important difference between the use of the equals sign in BASIC and the use of the equals sign in standard mathematics. In mathematics, the equals sign indicates that two values or expres- sions are equal. For example, 2 + 3 = 5 is a familiar mathematical equation indicating that 2 + 3 and 5 are equal. The equals sign in this usage simply states a fact, that the two sides of the equation are equal. 8 / Lesson 2 In BASIC, the equals sign performs an action: it defines or changes the value of a variable. In the example that you just typed in, the equals sign assigns the value 14 to the variable name “x”. The variable may have had no previous value, or it may have had any other value. In any case, after the execution of this sequence, x will have a value of 14. Now press to execute the sequence. The computer responds by clearing the display and performing the assignment operation, although it gives no indication of the latter action. The value assigned to x can be checked by typing x and pressing [ENTER]: Enter Display x i4 As the word “variable” implies, the value of a variable can be changed by simply assigning it a new value using the equals sign. This flexibility makes variables extremely useful in programming. Type X=x+x and press [ENTER]. Then perform the check again. Enter Display The new value of x is 28. It was obtained by assigning x the value of x + x. Notice that the “old” value of x was used in assigning a new value to x. A BASIC sequence such as x = x + x cannot be confused with a mathematical sequence, since it makes no sense as an equation: it would be like saying 1 = 1 + 1. When assigning a value to a variable, always place the variable name on the left side of the equals sign and the value on the right side. This is a fundamental rule of BASIC programming. Technical Note: Some BASICs require that assignment sequences be preceded by the BASIC statement LET (for example, LET x=14 Numeric Constants and Variables / 9 or LET x=x+x). Compact Computer BASIC leaves this choice to you. You can use or not use LET (or let) as desired. However, since dropping the LET reduces your typing effort and makes no difference in the computer’s operation, it is not used in this book. The initial value of any numeric variable is zero. This is a convention of BASIC that you will find useful and convenient. Once the variable has been assigned a nonzero value, the variable retains that value until altered by another BASIC instruction or until the computer is turned [OFF]. Turning the computer or allowing the Automatic Power Down™ to occur sets the value of all variables to zero. The BASIC command new also sets the value of all variables to zero, as well as erasing any program currently in the computer's memory. The primary advantage of this command is that it allows you to quickly prepare the computer for a new program by clearing all information, including the values of variables, from memory. In Compact Computer BASIC, a variable name can be almost any sequence of letters and digits up to 15 characters in length, as long as the first character of the name is a letter, an underline (_) character, or an at (@) sign. For example, x @payroll count12 first_new_date a7c3 _cost are all valid variable names. However, 3x percentconcentration test 1 b12? interest-costs are invalid names because they either begin with a number, are too long, or contain characters that are not valid (in these examples, the space, question mark, or hyphen, respectively). 10 / Lesson 2 A list of names that would otherwise be valid, but cannot be used because they represent BASIC program commands and statements, is given in Appendix B. For example, the assignment sequence “let = 5” is invalid because let is part of the BASIC language of the computer. Unlike some BASIC languages, however, Compact Computer BASIC allows variables to contain BASIC words as part of a variable name. For example, run is a BASIC word and therefore cannot be used as a variable, but “prune”, which contains run, can be used. LEARNED IN THIS LESSON Numbers entered into the computer can be of two types: constants and variables. Specific values such as 3.313 are referred to as constants. “Names” assigned to numbers are called variables. Vari- able names must begin with a letter of the alphabet, the underline (_) character, or the @ symbol, and cannot be on the reserved word list. The reserved word list is given in Appendix B of this book. The equals sign is used to assign values to variables. The variable name must always be on the left side and the value on the right side of the equals sign. Until assigned another value, all numeric variables are equal to zero. Once assigned a nonzero value, a numeric variable retains that value in memory until it is replaced or cleared. The value of a variable can be replaced by assigning it a new value. It can be cleared by turning the computer or executing the new com- mand. The new command instructs the computer to set all numeric variables to zero and to erase any program currently in memory. Lesson “sss” DISPLAYing Information The CC-40 is equipped with a 31-character liquid crystal display (LCD). This display is your means of observing the entry of informa- tion into the computer, monitoring its operation, and viewing the contents of memory and the results of calculations and programs. The computer automatically displays the results of calculations. This groatly increases the convenience of using the computer as a pocket calculator, but is unusual for a BASIC language computer. To see the results of other types of actions, you must use a specific instruc- tion. The display statement is Compact Computer BASIC’s primary method of placing information in the display. For example, enter cost 10.25 Now display the value of the variable using the display statement: Enter Display display cost 16.25 The value is displayed with a nonflashing underline in the left side of the display. The underline cursor indicates the computer is in the “pause” state. The purpose of the pause state is discussed in Lesson 4. For the moment, be aware that when you see a non- flashing underline you must press or before you can proceed with another operation. 11 12 / Lesson 3 The display statement is extremely powerful and offers several optional parameters. For example, you can display information at any character position with the at(co/umn) option. A comma must separate the at parameter from the information being displayed. Enter Display display at(5),cost 16.25 This form of the display statement instructs the computer to display the value beginning at the fifth column position. If you look closely, however, you will observe that the number actually begins in the sixth column position. This apparent discrepancy occurs because BASIC places a “character space” in front of a positive number. This space corresponds to the position occupied by the minus sign of a negative number and is added for consistency. The “leading” space in front of a positive number ensures that the digits of both negative and positive numbers begin in the same relative location: Enter Display display at(5),—10.25 -16.25 In addition to adding a leading space before positive numbers, BASIC also adds a space after every number. This “trailing” space is intended to separate the number from any information that may be displayed following the number. The valid range for column positions is 1 through 80, inclusive, but only the first 31 positions correspond to physical locations in the display. For example, try Enter Display display at(32),cost The underline cursor is displayed as usual, but no value is visible. To see the value, hold down the right arrow [>] key. The underline cursor moves toward the right side of the display. If you continue to hold the right arrow key down, the value scrolls into view 1 character at a time. Since the display is physically limited to 31 characters, it is not possible to see information displayed beyond column 31 unless the information is scrolled into view. DISPLAYing Information / 13 Technical Note: The computer has what is known as an 80-charac- ter display buffer. Since the display is only 31 characters wide, it is impossible to see the entire buffer at one time. The display can be viewed as a “window” that can be shifted right or left as needed to view the contents of the display buffer. When the display buffer contains information to the right of the viewing window, the triangular indicator in the upper right corner of the display is lighted. When the display buffer contains information to the left of the viewing window, the triangular indicator in the upper /eft side of the display is lighted. To see information to the right of the viewing window, hold down the right arrow key. To see information to the left of the viewing window, hold down the left arrow key. The display statement also allows you to display more than one value at a time. Enter Display markup= 1.75 display cost;markup 16.25 1.75 display cost;markup;cost+ markup 18.25 1.75 12 display at(7),1;—2;3 1-2 3 When multiple values are display-ed, the values are known as a print-list. A print-list can contain both constants and variables, but must use a semicolon or a comma to separate the items of the list. The display statement operates differently depending upon the punctuation selected: ¢ When a semicolon print-list separator is used, the computer displays the items adjacently, as in the examples above. Remember, however, that BASIC automatically adds a space after every number and before each positive number. ¢ When a comma print-list separator is used, the computer displays the items beginning at certain column locations known as the display zones. These zones are 15 columns apart and correspond to display buffer positions 1, 16, 31, 46, 61, and 76. For example, try Enter Display display cost,markup 14.25 17D 14 / Lesson 3 The comma instructs the computer to display the next item in the print-list beginning at the next print zone (in this example, column 16). To view information displayed in the third, fourth, fifth, and sixth print zones, you must scroll the display window to the right using the [>] key. Enter Display display 1,2,3,4,5,6 1 2 (Hold down the [>] key to view the information in print zones 3, 4, 5, and 6.) The semicolon and comma separators can be mixed as desired in a print-list: Enter display 1;cost,2;markup an 2 1.79 Another option offered by the display statement is the beep parame- ter. The beep parameter can be used with or without a print-list and instructs the computer to sound an audible tone when executed. A comma must separate the display parameters from the informa- tion being displayed. Enter Display display beep display at(12) beep,12 12 The beep and at parameters must precede the print-list, if one is used, but can be entered in either order. The at parameter can be used only once in a display statement, but beep can be repeated as often as desired: display beep beep beep beep beep Other options available when using display are discussed in Lesson 20. Technical Note: The print statement provides an alternate way of displaying information. Because the print statement has fewer options than the display statement, it is not discussed in this book. DISPLAYing Information / 15 For many examples of the print statement, refer to the User’s Guide supplied with your computer. LEARNED IN THIS LESSON The display statement is used to place information in the display. The statement offers several options. You can display information starting at any column location up to 80 positions, sound a tone as information is displayed, and display more than one item of infor- mation at a time. If multiple items are displayed (a print-list), they must be separated by semicolons or commas. The semicolon in- structs the computer to place items adjacently, and the comma instructs the computer to place items beginning at specific display locations called zones. When the computer is in a pause state, the or key must be pressed to allow the entry of additional instructions. (The computer shows a nonflashing underline cursor when you must press or to proceed.) Lesson Beginning Programming The preceding lessons illustrate using the computer in what is known as immediate execution or command mode. Such actions require the correct use of BASIC commands and statements, but they are not “programming.” Programming consists of storing a set of in- structions in the computer’s memory. The stored instructions, or program, are not executed when you enter them, but only after you command the computer to run the program. To store an instruction in memory, you must precede the instruction with a /ine number. A line number directs the computer to remember, but not execute, the BASIC instructions that follow. Clear the computer's memory by typing new and pressing [ENTER]. Then type the following sequence exactly as shown: 100 score=14 Before pressing [ENTER], check that you have typed a space be- tween the line number and the variable name. If not, press and retype the sequence. When the line seems correct, press (ENTER). The computer will store the “line” in memory and clear the display. Technical Note: Compact Computer BASIC requires spaces after line numbers and between BASIC words. Spaces between other program elements are generally optional. The policy of this book 16 Beginning Programming / 17 is to show spaces only where absolutely required. If you feel uncom- fortable with sequences such as score=14, enter score = 14, Extra spaces do not affect the computer's operation since it removes all unnecessary spaces when the program line is stored in memory. Be certain, however, that you enter spaces wherever you see them in the text. To confirm that the assignment statement has not yet been exe- cuted, display the value of score: Enter Display display score cs) Now execute the program by typing run, or pressing the key, and pressing [ENTER]. Enter Display run Although the computer's only apparent response is to clear the display, the statement has been executed (assuming no error mes- sage was displayed). Check this by displaying the value of score again. Enter Display display score 14 This program, although very short, clearly illustrates the difference between command mode and programming. In command mode, instructions are executed when is pressed. In programming, execution is deferred until the program is run. The distinction between command mode and programming is also the basis for separating BASIC words into commands and state- ments. Commands are BASIC words that can be executed only in command mode. Statements are BASIC words that can be exe- cuted in a program, and usually, in command mode as well. The one-line program that you have just executed can be added 18 / Lesson 4 to and made more useful by entering more program lines. For exam- ple, enter 110 display score Notice that this line has a larger line number than the first. The computer uses the size (or magnitude) of the line numbers that you enter to determine the order in which program lines are exe- cuted. Since 110 is larger than 100, line 110 will be executed after line 100 when you run the program. Run the program again. Enter Display run Rather unexpectedly, the computer does not display the value of score. Why not? Actually the number 14 was displayed, but so quickly it was not visible. The computer automatically clears the display just before and immediately after running a program. There- fore, since the display statement is the last instruction in the pro- gram, its effect is automatically cleared when the program ends. To instruct the computer to hold a value in the display until you have had an opportunity to see it, you must use the pause statement. The pause statement causes the computer to temporarily halt pro- gram execution without clearing the display. The computer remains in the pause state until you press or to signal that program execution is to continue. Add the following line to the program and run it again. The larger line number ensures that the pause statement will be executed after the display statement. Enter Display 120 pause run i4 This time the program works as expected, assigning and displaying the value of score. The computer then halts in the pause state with the underline cursor displayed, which indicates that you are expected to press or [CLR]. Program execution continues Beginning Programming / 19 when you press one of these keys. In this case, of course, no additional program lines follow and the program ends (which clears the display). Technical Note: Some BASICs require the use of an end state- ment at the end of a program. With Compact Computer BASIC, this statement is optional when the end of the program is the last line of the program. It is possible, however, to design a program to end at a line number other than the last. When this occurs, an end statement is no longer optional. In this book, end statements are omitted except where required as explained above. See Lesson 19 for an example of a program that requires an end statement. The preceding program illustrates one of the main advantages of programming your instructions over executing them in the command mode: they can be easily executed more than once. To reexecute these instructions, run the program again. The program will remain in memory until you clear it by executing a new command. Even turning the computer and will not erase it. (Of course, the contents of memory will be lost if power is removed as a result of discharging or removing the batteries.) As you work through this book, you will write programs that are longer and more complicated. When a program grows beyond five or six lines, it becomes difficult to remember what instructions you have already entered. Fortunately, BASIC has a command to allow you to view or list program instructions. The list command has two forms: list and list /ine-group. When list is executed, the computer displays the lowest numbered pro- gram line and halts. You can then display the next program line by pressing or [¥], or clear the display and end the listing operation by pressing [CLR]. The sole difference in executing list with a line-group parameter is that the listing begins with the line number specified by the line- group. A line-group can be either a single line number or a range of line numbers specified by a beginning line number, a hyphen, and an ending line number. If only a beginning line number and a hyphen are entered, the ending line number is assumed to be the last line in memory. (The hyphen is entered with the minus key.) 20 / Lesson 4 You still press or [¥], to advance to the next line number and to end the listing. To illustrate the list command, list the score program. Enter Display list 144 SCORE=14 114 DISPLAY SCORE 126 PAUSE Notice that the computer automatically translates BASIC words and variable names from lowercase letters into capital letters. Before ending this lesson, it is important to cover several additional points regarding BASIC line numbers. First, observe that we began this program with line number 100 and incremented each line by 10. The actual numbers selected were unimportant. A functionally equivalent program could have been written using any three line numbers in the valid range of 1 through 32766, as long as the lines remained in the same relative order. Line numbers should not normally follow each other in increments of 1, however. By selecting line numbers with unused values or “gaps” between them, you make it easy to insert additional program lines. Simply enter the new line with a line number between the existing line numbers. For example, suppose you want to increase the value of score by 7. This is accomplished by entering the following line: 105 score=score+7 Confirm that the line has been inserted between lines 100 and 110 by listing the program again. Enter Display list 166 SCORE=14 145 SCORE=SCORE+7 114 DISPLAY SCORE 129 PAUSE Beginning Programming / 21 Another important point regarding line numbers is the ease with which they allow program instructions to be replaced or deleted. To replace a program line, simply enter a new line with the same line number. Since BASIC does not allow a program to have two lines with identical line numbers, the computer automatically re- places the original line with the new line. Test this feature by replac- ing line 105 with 105 score=score+14 List the program again. Enter list 5 114 DISPLAY SCORE 120 PAUSE The original line has been replaced with the new one. Program lines are deleted by the delete /ine-group command. (As with the list command, a line-group can be either a single number or a range of numbers separated by a hyphen.) This command, which can be shortened to del to reduce typing, instructs the com- puter to erase a line or a range of lines. For example, del 100 will erase line 100; del 100-120 will erase lines 100 through 120; del -200 will erase all lines from the beginning of memory to line 200; and del 200- will erase all lines from 200 to the end of memory. You can test this command by entering: del 100- If you now enter list, no lines will be displayed. LEARNED IN THIS LESSON Every BASIC program, from the simplest to the most complicated, consists of one or more numbered “lines” of BASIC instructions. The numbers that precede each line serve three purposes: 22 / Lesson 4 1. They allow the computer to distinguish between instructions to be stored in memory (a program) and instructions to be executed immediately (command mode). 2. They determine the order in which program instructions are executed. 3. They provide a method of identifying program instructions that you can use when listing or editing a program. Line numbers must be whole numbers in the range 1 through 32766. As a rule, select line numbers that are 10 or more units apart. This practice makes it easy to insert additional lines. The list command is used to display program lines. The command can be used singularly or with a line-group parameter. When list is used by itself, the listing begins with the lowest numbered program line. When used with a line-group parameter, the listing begins and ends with a specified line number. To advance to the next program line, press or [¥]. To clear the display and end the listing, press [CLR]. The delete line-group command is used to delete specific program lines. The command can be abbreviated del, if desired. The pause statement should be placed in a program whenever you want displayed information to remain in the display. The pause statement instructs the computer to halt program execution without altering the display until or is pressed. Lesson ‘“se." Strings—Alphanumeric Information The most significant feature of a computer is not its capability to manipulate numbers, since a pocket calculator can do that, but its additional capability to manipulate letters, symbols, signs, words, sentences, and, in general, textual information of any type. To enable the computer to distinguish between textual information and num- bers, textual information must be entered into the computer en- closed in quotation marks. Such information, which can consist of any collection of alphabetic letters, signs, symbols, or digits from 0 to 255 characters in length, is referred to as a string. For example, enter Enter Display display "CC-40" CC-46 (Use the [SHIFT] key to enter the capitals and the minus [=] key to enter the hyphen.) Observe that the computer displays exactly what you enter between the quotes, but not the quotes. Notice also the familiar underline cursor in column one that indicates the computer is in the pause State. As you might suspect, a string such as that illustrated above is referred to as a string constant. Like a numeric constant, it can be changed only by retyping. You can create string variables, how- 23 24 / Lesson 5 ever, by simply assigning a string to a variable name that has as its /Jast character a dollar ($) sign. Enter Display c$="Computer” display c$ Computer If you attempt to assign a string to a variable name that does not end in a dollar sign, you will get an error message. Other than this requirement, the rules governing the creation of string variable names are the same as those for numeric variable names: they must begin with a letter, underline, or @ symbol; they cannot be more