0% found this document useful (0 votes)
107 views

Applesoft II BASIC Programming Reference Manual

Uploaded by

Marcos F. M.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
107 views

Applesoft II BASIC Programming Reference Manual

Uploaded by

Marcos F. M.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 186
BASIC PROGRAMMING REFERENCE MANUAL NOTICE Apple Computer Inc. reserves the right to make improvements in the product described in this manual at any time and without notice. DISCLAIMER OF ALL WARRANTIES AND LIABILITY APPLE COMPUTER INC. MAKES NO WARRANTIES, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS MANUAL OR WITH RESPECT TO THE SOFTWARE DESCRIBED IN THIS MANUAL, ITS QUALITY, PERFORMANCE, MERCHANTABILITY, OR FITNESS FOR ANY PARTICULAR PURPOSE. APPLE COMPUTER INC. SOFTWARE |S SOLD OR LICENSED “AS IS.” THE ENTIRE RISK AS TO ITS QUALITY AND PERFORMANCE IS WITH THE BUYER. SHOULD THE. PROGRAMS PROVE DEFECTIVE FOLLOWING THEIR PURCHASE, THE BUYER (AND NOT APPLE COMPUTER INC., ITS DISTRIBUTOR, OR ITS RETAILER) ASSUMES THE ENTIRE COST OF ALL. NECESSARY SERVICING, REPAIR, OR CORRECTION AND ANY INCIDENTAL OR CONSEQUENTIAL DAMAGES. IN NO EVENT WILL APPLE COMPUTER INC. BE LIABLE FOR DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT IN THE SOFTWARE, EVEN IF APPLE COMPUTER INC. HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF IMPLIED WARRANTIES OR LIABILITY FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THE ABOVE LIMITATION OR EXCLUSION MAY NOT APPLY TO YOU. This manual is copyrighted. All rights are reserved. This document may not, in whole or part, be copied, photocopied, reproduced, translated or reduced to any electronic medium or machine readable form without prior consent, in writing, from Apple Computer Inc. © 1978, 1981 by APPLE COMPUTER INC. 10260 Bandley Drive Cupertino, California 95014 (408) 996-1010 The word Apple and the Apple Logo are registered trademarks of APPLE COMPUTER INC. APPLE Product #A2L0006 (030-0013-E) WARNING: This equipment has been certified to comply with the limits for a Class B computing device, pursuant to Subpart J of Part 15 of FCC Rules. Only peripherals (computer input/output devices, terminals, printers, etc.) certified to comply with the Class B limits may be attached to this computer. Operation with non-certified peripherals is likely to result in interference to radio and TV reception. TABLE OF CONTENTS xi OVERVIEW CHAPTER GETTING STARTED 2 Immediate-Execution Commands 2 Deferred-Execution Commands 4 Number Format 5 Color Graphics Example 6 Print Format 7 Variable Names 9 Fes. THEN 19 Another Color Example 11 FOR...NEXT 14 Arrays 15 GOSUB. . .RETURN 17 READ. . -DATA.. .RESTORE 18 Real, Integer and String Variables 19 Strings 23 More Color Graphics 25 High-Resolution Color Graphics DEFINITIONS 30 36 36 36 Syntactic Definitions and Abbreviations Rules for Evaluating Expressions Conversion of Types Execution Modes CHAPTER 2 CHAPTER 3 SYSTEM AND UTILITY COMMANDS LOAD and SAVE 38 NEW 38 RUN 39 STOP, END, ctrl C, reset and CONT 4@ TRACE and NOTRACE 49 PEEK 41 POKE 41 WAIT 43° CALL 43 HIMEM: 44, LOMEM: 45 USR CHAPTER 4 EDITING AND FORMAT-RELATED COMMANDS In Chapter 3, also see ctrl C. 48 LIST 49 DEL 5 REM SQ VTAB 50 HTAB 51 TAB 51 POS 52 SPC 52 HOME 52 CLEAR 53 FRE 53 FLASH, INVERSE and NORMAL 54 SPEED 54 esc A, esc B, esc C and esc D 55 repeat 55 right arrow and left arrow 55 ctrl x Nv CHAPTER 5 ARRAYS AND STRINGS 58 DIM 59 LEN 59 STRS 59 VAL 69 CHRS 69 Asc 69 LEFTS 61 RIGHTS 61 MIDS 62 STORE and RECALL CHAPTER INPUT/OUTPUT COMMANDS 66 67 68 69 0 70 7 72 72 3 In Chapter 3, also see LOAD and SAVE; in Chapter 5, see STORE and RECALL. INPUT GET DATA READ RESTORE, PRINT Int PRE LET DEF FN vi CHAPTER 7 COMMANDS RELATING TO FLOW OF CONTROL 76 coro 76 IF..-THEN and IF...GOTO 78 FOR...10...STEP 79 NEXT 79 GOSUB 89 RETURN 89 POP 81 ON..-GOTO and ON...GOSUB 81 ONERR GOTO 82 RESUME vil CHAPTERS GRAPHICS AND GAME CONTROLS Low Resolution Graphics 84 GR 85 COLOR 85 PLOT 85 HLIN 86 VLIN 87 SCRN High-resolution Graphics 87 HGR 88 HGR2 89 HCOLOR 89 HPLOT Game Controls 99 PDL vill CHAPTERO HIGH-RESOLUTION SHAPES How to Create @ Shape Table 7 Saving a Shape Table 97 Using a Shape Table 98 DRAW 98 XDRAW 99 ROT 99 SCALE 99° SHLOAD Xx CHAPTER 1 0 SOME MATH FUNCTIONS 192 The built-in functions SIN, COS, TAN, ATN, INT, RND, SGN, ABS, SQR, EXP, LOG 193 Derived Functions 196 ug 11s 118 120 a2. 122 124 126 128 138 14g 142 144 1s 162 Appendix Appendix Appendix Appendix Appendix Appendix Appendix Appendix Appendix Appendix Appendix Appendix Appendix Appendix Appendix INDEX A B c D: E F G APPENDICES Getting APPLESOFT BASIC up Program Editing Error Messages Space Savers Speeding Up Your Program Decimal Tokens for Keywords Reserved Words in APPLESOPT Converting BASIC Programs to APPLESOFT Memory Map (see also page 137) PEEKs, POKEs and CALLS ASCLI Character Codes APPLESOFT Zero Page Usage Differences Between APPLESOFT and Integer BASIC Alphabetic Glossary of Syntactic Definitions and Abbreviations Summary of APPLESOFT Commands Inside Back Cover: Alphabetized Index of APPLESOFT Commands OVERVIEW INTRODUCTION APPLESOFT II BASIC is APPLE’s very much extended BASIC language. BASIC has been extended because there are many features on the APPLE II computer that just aren’t available on other computers that use BASIC. By adding a few new words to the BASIC language, these features are immediately available to anyone using APPLESOFT. Among the features supported by APPLESOFT are APPLE’s color graphics, high-resolution color graphics and the direct analog inputs (the game controllers). Another feature of APPLESOFT is this manual. It is not a self-teaching manual, since APPLE provides a separate manual (the APPLE IT BASIC Programming Manual) which will help you learn to program even if you have never touched a computer before. This manual assumes that you know how to program in BASIG and just wish to learn the additional features offered by APPLESOFT. Chapter 1 (GETTING STARTED) is a quick run-through of what the language has to offer. The rest of the manual is a careful and exact description of every statement in the language and how each statement works. To help save you the frustration and annoyance that some manuals can cause, this manual points out places where programming errors can cause you difficulty. Special symbols call your attention to these points. The method used to describe APPLESOFT is almost a simple language in itself. You will find that, after a few moments getting used to it, it will speed your understanding of exactly what is legal and illegal in the language. You will not be left with any nagging doubts about the interpretation of a sentence, as can happen with pure English descriptions. Advanced programmers will find this manual especially helpful. Beginning programmers are reminded that they will soon no longer be beginners, and will appreciate the extra effort APPLE has made to provide an unusually complete manual. To be sure, a thicker manual looks more formidable, but when you need the information, you will be glad that we took the time and space to put it in. USING THIS MANUAL This reference manual assumes you have @ minimal working knowledge of the programming language BASIC. If youre unfamiliar with BASIC, the APPLE II BASIC Programming Manual can provide an introduction: it covers a version of BASIC which is much like APPLESOFT II, but simpler. We recommend that you have APPLESOFT II BASIC (usually referred to as APPLESOFT) up and running when you consult this manual, so that you can try out on your computer anything the manual describes or suggests. If APPLESOFT is running on your system, the APPLESOFT prompt character (] ) will be displayed. See Appendix A for an explanation of how to get APPLESOFT loaded into your computer. Xi There are two terms you’ll need to know when reading this manual. The word “eyntax" refers to the structure of a computer command, the order and correct form of the conmand’s various parts. The word "parse" refers to the way in which the computer attempts to interpret what you type, picking out the various parts of the computer commands in order to execute them. For example, APPLESOFT’s syntax allows you to type 12K5=44372 When APPLESOFT parses this input, it first picks out 12 as the program line number, then interprets X5 as an arithmetic variable name. Finally, APPLESOFT evaluates 32 as 9, then multiplies by 4, and assigns the value 36 to the variable whose name is X5. Chapter 1 provides an overview of many APPLESOFT commands, for those who have had little experience programming in BASIC. Many primary concepts are introduced, using examples that you can type into the computer. Appendix B gives pointers on editing APPLESOFT prograns. The notation introduced at the beginning of Chapter 2 is used to describe APPLESOFT’s syntax concisely and unambiguously. It will save you time and effort in understanding how the commands must be structured. You don’t need to use this notation yourself, but it will help you answer many questions not specifically discussed in the text. For instance, square brackets ( [ and] ) are used to indicate optional portions of a command; curly brackets ({ and } ) are used to indicate those portions that may be repeated. So {LET} ¢ = 3 indicates that the word LET is optional and may be omitted. And REM [{character}] indicates that the REMark command consists of the word REM optionally followed by one or more characters. The syntactic abbreviations and definitions in the first part of Chapter 2 are presented in a logical order for those who want to see how we’ve built up our system of symbols and definitions. You may prefer to ignore these symbols and definitions until you encounter one in the text. At that tine, you can refer to the alphabetized glossary of syntactic terms given in Appendix N. Chapters 3 through 19 present detailed explanations of APPLESOFT’s commands, grouped by subject matter. If you’re interested in finding out about a specific command, the alphabetized index on the inside of the back cover will tell you where to look. Additional reference material not covered in the chapters can be found in the appendices. At_some places you’1l see the symbol Preceding a paragraph. This symbol indicates an unusual feature to which you should be alert. The symbol © precedes paragraphs describing situations from which APPLESOFT may be unable to recover. You will lose your program and will probably have to re-start APPLESOFT. xi RADIO AND TELEVISION INTERFERENCE The equipment described in this mamual generates and uses radio frequency energy. If it is not installed and used properly, that is in strict accordance with our instructions, it may cause interference to radio and television reception. This equipment has been tested and complies with the limits for a Class B computing device in accordance with the specifications in Subpart J of Part 15 of FCC rules. These rules are designed to provide reasonable protection against such interference in a residential installation. However, there is no guarantee that the interference will mot occur ina particular installation. You can determine whether your computer is causing interference by turning it off. If the interference stops, it was probably caused by the computer. If your computer does cause interference to radio or television reception, you can try to correct the interference by using one or more of the following measures: - Turn the TV or radio antenna until the interference stops. - Move the computer to one side or the other of the TV or radio. - Move the computer farther away from the TV or radio. - Plug the computer into an outlet that is on a different circuit from the TV or radio. (That is, make certain the computer and the TV or radio are on circuits controlled by different circuit breakers or fuses.) If necessary, you should consult your dealer or an experienced radio/television technician for additional suggestions. You may find the following booklet prepared by the Federal Communications Commission helpful: “How to Identify and Resolve Radio-TV Interference Problems" This booklet is available from the U.S. Goverment Printing Office, Washington, DC 29492, Stock mmber 994-GG9-99345-4. GSEIGECSevavann cuaprer GETTING STARTED Immediate-Execution Commands Deferred-Execution Commands Number Format Color Graphics Example Print Format Variable Names IF... THEN Another Color Example FOR. . .NEXT RETURN DATA. . -RESTORE. Real, Integer and String Variables Strings More Color Graphics High-Resolution Color Graphics IMMEDIATE—EXECUTION COMMANDS ‘Try typing the following: PRINT 19-4 and then press the key marked RETURN. APPLESOFT I1 will immediately print 6 ‘The PRINT statement you typed was executed as soon as you pressed the RETURN key. APPLESOFT evaluated the formula after the PRINT and then typed out its value, in this case 6. Now try typing this: PRINT 1/2, 3419 (* means multiply, / means divide). When you press the RETURN key, APPLESOFT will print: 5 39 As you can see, APPLESOFT does division and multiplication, as well as subtraction. Note how a comma ( , ) was used in the PRINT command to print two values instead of just one. The use of the comma with the PRINT command divides the 49-cheracter line into 3 columns or "tab fields." See the discussion of tab fields in Chapter 6, under the PRINT command. DEFERRED —EXECUTION COMMANDS Commands such as the PRINT statements you have just typed are called "immediate-execution" commands. There is another type of command called a "@eferred-execution" command. Every deferred-execution command begins with a "line number". A line number is an integer from # to 63999. ‘Try typing the following lines: 19 PRINT 243 2G PRINT 2-3 (Remenber, each line must be terminated by pressing the RETURN key.) A sequence of deferred-execution commands is called a "program." Instead of executing deferred-execution statements immediately, APPLESOFT BASIC stores deferred-execution commands in the APPLE’s memory. When you type RUN, APPLESOFT first executes the stored statement having the lowest line number, then the statement with the next higher line number, etc-, until the complete progran has been executed. Suppose you type RUN now (remember to press the RETURN key at the end of each Line you type): RUN APPLESOFT will now display on your TV: 5 -1 In the previous example, we typed line 19 first and line 29 second. However, it makes no difference in what order you type deferred-execution statements. APPLESOFT always puts them into correct numerical order according to their line numbers. To see a listing of the complete program currently in memory, with the statements arranged in their correct order, type LIST APPLESOFT will reply with 1 PRINT 243 20 PRINT 2-3 Sometimes it is desirable to delete a line of a program altogether. This is accomplished by typing the line number of the line you wish to delete, followed only by a press of the RETURN key. Type the following: 1 LIST APPLESOFT will reply with: 29 PRINT 2-3 You have now deleted line 19 from the program. There is no way to get it back. To insert a new line 19, just type 19 followed by the new statement you want APPLESOFT to execute. Type the following: 1 PRINT 2*3 LIST APPLESOFT will reply with 1 PRINT 243 20 PRINT 2-3 There is an easier way to replace line 19 than deleting it and then inserting a new line. You can do this by just typing the new line 10 (and pressing the RETURN key, of course). APPLESOFT automatically throws away the old line 1 and replaces it with the new one. Type the following: 1 PRINT 3-3 LIST APPLESOFT will reply with: 19 PRINT 3-3 2G PRINT 2-3 It is not recommended that program lines be numbered consecutively: it may be necessary, later on, to insert a new line between two existing lines. An increment of 1 between line numbers is generally sufficient. If you want to erase the complete program currently stored in memory, type NEW If you are finished running one program, and are about to begin a new one, be sure to type NEW first. This should be done to prevent a mixture of the old and new programs. Type the following: NEW APPLESOFT will reply with the prompt character: 1 : Now type LIST APPLESOFT will reply with J showing that your previous program is no longer stored in memory. NUMBER FORMAT We will digress for a moment to explain the format of numbers printed by APPLESOFT BASIC. Numbers are stored internally to over nine digits of accuracy. When a number is printed, only nine digits are shown. Every number may also have an exponent (a puver-of-ten scaling factor). In APPLESOFT BASIC, "real precision" (also called "floating point") numbers mist be in the range from -1#19738 to 1*16738, or you risk getting an error message. Using addition or subtraction, you may sometimes be able to generate numbers as large as 1.7#19738 without the error message. A number whose absolute value is less than about 3417-39 will be converted to zero by APPLESOFT. In addition to these limitations, true integer values must be in the range from ~32767 to 32767. When a number is printed, the following rules are used to determine the exact format: 1) Lé the number is negative, a minus sign (-) is printed. 2) If the absolute value of the number is an integer in the range @ to 999999999, it is printed as an integer. 3) Lf the absolute value of the number is greater than or equal to 1 and less than 999999999.2, the number is printed in fixed point notation, with no exponent. 4) If the number does not fall under categories 2 or 3, scientific notation is used. Scientific notation is used to print real precision numbers, and is formatted as follows: ‘SX. XXXKXKXKESTT where each X is an integer # to 9. The leading $ is the sign of the number, nothing for a positive number and a minus sign (- ) for a negative number. One non-zero digit is printed before the decimal point. This is followed by the decimal point and then the other eight digits of the mantissa. An & is then printed (for Exponent), followed by the sign (S) of the exponent; then the two digits (IT) of the exponent itself. Leading zeroes are never printed; i.e. the digit before the decimal is never zero. Also, trailing zeroes are never printed. If there is only one digit to print after all trailing zeroes are suppressed, no decimal point is printed. The exponent sign will be plus ( + ) for positive and minus ( - ) for negative. Two digits of the exponent are alvays printed; that is, zeroes are not suppressed in the exponent field. The value of any number expressed in the form of scientific notation as described above is the number to the left of the E times 19 raised to the power of the number to the right of the E. The following are examples of various numbers and the output format APPLESOFT will use to print them: NUMBER OUTPUT FORMAT +1 1 -1 1 6523 6523 23.468 23.46 45.7265 4572008 1819720 1429 12. 34567896*19716 -1.2345679E+11 199g990aa 1E+99 999999999 999999999 A number typed on the keyboard, or a numeric constant used in an APPLESOFT program, may have as many digits as desired, up to the maximum length of 38 digits. However, only the first 1 digits are usually significant, and the tenth digit is rounded off. For example, if you type PRINT 1. 23456787654321 APPLESOFT responds with 1. 23456788 COLOR GRAPHICS EXAMPLE Type aR This will black out the top twenty Lines of text on your TV screen and leave only four lines of text at the bottom. Your APPLE is now in its low-resolution “color GRaphics" mode. Now type COLOR = 13 APPLESOFT will only respond with the prompt character: and the flashing cursor, but internally it remembers that you have selected a yellow color. Now type PLOT 29, 26 APPLESOFT will respond by plotting a small yellow square in the center of the screen. If the square is not yellow, your TV set is not tuned properly: adjust the tint and color controls to achieve a clear lemon yellow. 5 Now type HLIN §,36 AT 20 APPLESOFT will draw a horizontal line across the leftmost three-quarters of the screen, one-quarter dow from the top. Now type COLOR = 6 to change to a new color, and then type VLIN 19,39 AT 39 You will learn more about color GRaphics later. To get back to all text mode, type TEXT The character display on the screen is APPLE’s way of showing color information as text. When PRINTing the answers to problems, it is often desirable to include text along with the answers, in order to explain the meaning of the numbers. Type the following: PRINT "ONE THIRD IS EQUAL TO", 1/3 APPLESOFT will reply with: ONE THIRD IS EQUAL TO + 333333333 PRINT FORMAT As explained earlier, including a comma ( , ) in a PRINT statement causes it to space over to the next tab field before the value following the comma is printed. If we use a semicolon ( ; ) instead of a comma, the next value will be printed immediately following the previous value. Try it. Try the following examples: PRINT 1,2,3 1 2 3 PRINT 13253 123 PRINT ~1525 $1263 The following is an example of a program that reads a value from the keyboard and uses that value to calculate and print a result: 1g INPUT R 29 PRINT 3.14159*RAR RUN ne 314.159 Here’s what happens. When APPLESOFT encounters the INPUT statement, it displays a question mark (7) on the screen, and then waits for you to type a number. When you do (in the above example, 19 was typed), the variable following INPUT is assigned the typed value (in this case, the INPUT variable R was set to 19). Then execution continues with the next statement in the program, which is line 29 in the above example. When the formula after the PRINT statement is evaluated, the value 19 is substituted for the variable R each time R appears in the formula. Therefore, the formula becomes 3.14159410419, or 314.159. If you haven’t already guessed, the program above calculates the area of a circle with the radius R. If we wanted to calculate the area of various circles, we could keep re-running the program for each successive circle. But there’s an easier way to do it, simply by adding another line to the program, as follows: 34 GoTo 19 RUN 119 314.159 23 28.27431 24.7 69.3977231 BREAK IN 19 1 By putting a GOTO statement on the end of your program, you have caused it to go back to line 1§ after it prints each answer. This could go on indefinitely, but we decided to stop after calculating the area for three circles. Stopping was accomplished by typing a control C (type C while holding down the CTRL key) and pressing the RETURN key. This caused a "break" in the progran’s execution, allowing us to stop. Using control C, any program can be stopped after executing the current instruction. Try it for yourself. RIABLE NAMES The letter R in the program we just ran was termed a "variable." This is simply a memory location in the computer, identified by the name R. A variable name must begin with an alphabetic character and may be followed by any alphanumeric character. An alphanumeric character is any letter from A through Z, or any digit from 9 through 9. A variable name may be up to 238 characters long, but APPLESOFT uses only the first two characters to distinguish one name from another. Thus, the names GOOD4NOUGHT and GOLDRUSH refer to the same variable. In a variable name, any alphanumeric characters after the first two are ignored unless they contain a "reserved word." Certain words used in 7 APPLESOFT BASIC commands are "reserved" for their specific purpose. You cannot use these words as variable names or as part of any variable name. For instance, FEND would be illegal because END is a reserved word. The reserved words in APPLESOFT BASIC are listed and discussed in Appendix F. Variable names ending in § or % have a special meaning, as discussed later in this chapter under REAL, INTEGER, AND STRING VARIABLES. Below are some examples of legal and illegal variable names: LEGAL ILLEGAL iy 70 (variable names cannot PSTGS be reserved words) COUNT RGOTO (variable names cannot contain Nix reserved words) Besides assigning values to a variable with an INPUT statement, you can also set the value of a variable with a LET or assignment statement. Try the following examples: Ass PRINT A, AX 5 iW LET Z=7 PRINT Z, Z-A 7 2 As can be seen from the examples, the LET is optional in an assignment statement. BASIC “remenbers" the values that have been assigned to variables using this type of statement. This "remembering" process uses space in the APPLE’s memory to store the data. The values of variables are thrown away and the space in memory used to store them is released when one of four things occurs: 1) A new line is typed into the program or an old line is deleted. 2) A CLEAR command is issued. 3) A RUN command is issued. 4) NEW is typed. Here is another important fact: until you assign them some other value, all numeric variables are automatically assigned the value zero. ‘Try this example: PRINT Q, Q+2, Q42 8 2 4 Another statement is the REM statement. REM is short for remark. This statement is used to insert comments or notes into a program. When BASIC encounters a REM statement the rest of the line is ignored. This serves mainly as an aid to the programmer, and serves no useful function as far as the operation of the program in solving a particular problem. IF... THEN Let’s write a program to check whether a typed number is zero or not. With the statements we've discussed so far, this can not be done. What we need is a statement that provides a conditional branch to another statement. The IF...THEN statement does just that. ‘Type NEW, then type this program: 19 INPUT B 29 IF B = 9 THEN GoTo 50 39 PRINT "NON-ZERO" 49 Goro 1 50 PRINT " 69 GOTO 19 ERO" When this program RUN, it will print a question mark and wait for you to type a value for B. Type any value you wish. The computer will then come to the IF statement. Between the IF and the THEN portion of the statement, there is an “assertion.” An assertion consists of two expressions separated by one of the following symbols: SYMBOL MEANING EQUAL TO > GREATER THAN < LESS THAN © or >< NOT EQUAL TO <= LESS THAN OR EQUAL TO >= GREATER THAN OR EQUAL TO ‘The IF statement is either true or false, depending upon whether the assertion is true or not. In our present program, for example, if # is typed for B the assertion B= is true. Therefore, the IF statement is true, and program execution continues with the THEN portion of the statement: GOTO 59. Following this command, the computer will skip to line 59. ZERO will be printed, and then the GOTO statement in line 69 will send the computer back to line 19. Suppose a 1 is typed for B. Since the assertion B = @ is now false, the IF statement is false and program execution continues with the next line number, ignoring the THEN portion of the statement and any other statements in that line. Therefore, NON-ZERO will be printed and the GOTO in line 49 will send the computer back to line 10. Now try the following program for comparing two numbers (remeber to type NEW first, to delete your last program): 19 INPUT A,B 29 IF A <= B THEN GOTO 59 30 PRINT "A IS LARGER" 4 GoTo 19 5@ IF A < B THEN GOTO 80 69 PRINT “THEY ARE THE SAME" 70 GOTO 19 80 PRINT "B IS LARGER" 96 GoTo 19 When this program is RUN, line 19 will print @ question mark and wait for you to type two numbers, separated by a comma. At line 26, if A is greater than B, A<*B is false and THEN GOTO 59 is ignored. Program execution then skips to the statement following the next line number, printing A IS LARGER, and finally line 49 sends the computer back to line 19 to begin again. At line 29, if A has the same value as B, A<-B is true so THEN GOTO 59 is executed, sending the computer to line 59. At line 5, since A has the same value as B, ACB is false. Therefore, THEN GOTO 89 is ignored and the computer goes on to the following line number, where it ie told to print THEY ARE THE SAME. Finally, line 7@ send the computer back to the beginning again. At line 20, if A is smaller than B, A<=B is true so program execution continues with THEN GOTO 59. At line 5G, A 39 THEN NX = 39 : XV = -XV 198 IF NX < 9 THEN NX = 9 : XV = -xV 200 IF NY > 39 THEN NY = 39: YV = -YV 210 IF NY = 1 THEN GoTO 26 Notice that we are now checking to see that I is greater than or equal to the final value. The reason is that we are now counting by a negative number. In the previous examples it vas the opposite, so we were checking for a variable less than or equal to the final value. The STEP statement previously shown can also be used with negative numbers to accomplish this same purpose. This can be done using the same format used in the other program, as follows: 19 FOR 1 = 19 TO 1 STEP -1 2@ PRINT I 30 NEXT 1 13, FOR loops can also be "nested". An example of this procedure follows: 1g FORT = 1705 29 FOR J = 170 3 39 PRINT I, J 49 NEXT J 59 NEXT 1 Notice that the NEXT J comes before the NEXT I. This is because the J-loop is inside of the I-loop. The following program is incorrect; RUN it and see what happens. 19 FOR 1 = 1705 20 FOR J = 1 T0 3 39 PRINT I, J 40 NEXT I 50 NEXT J It does not work because when the NEXT I is encountered, all knowledge of the J-Loop is lost. ARRAYS It is often convenient to be able to select any element in a table of numbers. APPLESOFT allows this to be done through the use of arrays. An array is a table of numbers. The name of this table, called the array name, is any legal variable name, A for example. The array name A is distinct and separate from the simple variable A, and you could use both in the same program. To select an element of the table, we give A a subscript: that is, to select the I’th element, we enclose I in parenthesis (I) and then follow A by this subscript. Therefore, A(I) is the I’th element in the array A. NOTE: In this section of the manual we will be concerned with one-dimensional arrays only; for additional discussion of APPLESOFT commands relating to arrays, see Chapter 5, "Arrays and Strings.” AC) 4s only one element of array A. APPLESOFT must be told how much space to allocate for the entire array; that is, what the maximum dimensions of the array will be. This is done with a DIM statement, using the format DIM A(15) In this case, we have reserved space for the array index I to go from @ to 15. Array subscripts always start at J; therefore, in the above example we have allowed for 16 numbers in array A. If A(I) is used in a program before it has been DIMensioned, APPLESOFT reserves space for 11 elements (subscripts @ through 19). 14 ‘As an example of how arrays are used, try the following program, which sorts a list of 8 numbers typed by you. 99 DIM A(8) : DIMENSION ARRAY WITH MAX. 9 ELEMENTS 199 REM ASK FOR 8 NUMBERS 119 FOR I = 1 70 8 129 PRINT "TYPE A NUMBER: "; 139 INPUT A(T) 149 NEXT I 159 REM PASS THROUGH 8 NUMBERS, TESTING BY PAIRS 169 F = 9 : REM RESET THE ORDER INDICATOR 179 FOR I = 1 107 189 IF A(L) <= A(I+1) THEN GOTO 149 199 REM INTERCHANGE A(I) AND A(I+1) 209 T = ACI) 219 A(1) = A(I41) 229 ACH) = T 239 F = 1: REM ORDER WAS NOT PERFECT 249 NEXT 1 259 REM F = @ MEANS ORDER IS PERFECT 269 IF F = 1 THEN GOTO 169 : REM TRY AGAIN 279 PRINT : REM SKIP A LINE 289 REM PRINT ORDERED NUMBERS 299 FOR I = 1 T0 8 399 PRINT A(I) 319 NEXT I When line 99 is executed, APPLESOFT sets aside space for 9 numeric values, AG) through A(8). Lines 119 through 149 get the unsorted list from the user. The sorting itself is done in lines 179 through 249, by going through the list of numbers and interchanging any two that are not in order. PF is the "perfect order indicator": F = 1 indicates that a switch was done. If any were done, line 269 tells the computer to go back and check some more. If a complete pass is made through the eight numbers without interchanging any (meaning they were all in order), lines 299 through 319 will print out the sorted list. Note that a subscript can be any expression. GOSUB ... RETURN Another useful pair of statements are GOSUB and RETURN. If your program performs the same action in several different places, you can use the GOSUB and RETURN statements to avoid duplicating all the same statements for the action at each place within the program. When a GOSUB statement is encountered, APPLESOFT branches to the line whose number follows GOSUB. However, APPLESOFT remembers where it was in the program before it branched. When the RETURN statement is encountered, APPLESOFT goes back to the first statement following the last GOSUB that was executed. Consider the following program: 15 29 PRINT "WHAT IS THE FIRST NUMBER 39 GOSUB 199 497 =N: REM SAVE INPUT 5@ PRINT "WHAT IS THE SECOND NUMBER"; 69 GOSUB 109 7@ PRINT "THE SUM OF THE TWO NUMBERS IS " 8G STOP : REM END OF MAIN PROGRAM 199 INPUT N : REM BEGIN INPUT SUBROUTINE 119 IF N = INT(N) THEN GOTO 140 120 PRINT "SORRY, NUMBER MUST BE AN INTEGER. TRY AGAIN." 139 GOTO 199 149 RETURN : REM END OF SUBROUTINE, This program asks for two numbers which must be integers, and then prints the sum of the two. The subroutine in this program is lines 199 through 149. The subroutine asks for a number, and if the number typed in response is not an integer, asks for a number again. It will continue to ask until an integer value is typed in. ‘The main program prints WHAT IS THE FIRST NUMBER, and then calls the subroutine to get the value of the number N. When the subroutine RETURNs (to line 4), the number that was typed (N) is saved in the variable T. This is done so that when the subroutine is called a second time, the value of the first number will not be lost. WHAT IS THE SECOND NUMBER is then printed, and the subroutine is again called, this time to get the second number. When the subroutine RETURNs the second time (to line 76), THE SUM OF THE TWO NUMBERS IS is printed, followed by the value of their sum. T contains the value of the first number that was typed, and N contains the value of the second number. The next statement in the program is a STOP statement. This causes the program to stop execution at line 89. If the STOP statement were not included at this point, program execution would "fall into" the subroutine at line 19. This is undesirable because we would be asked to type still another number. If we did, the subroutine would try to RETURN; and since there was no GOSUB which called the subroutine, an error would occur. Each COSUB in a program should have a matching RETURN executed later, and a RETURN should be encountered only if it is part of a subroutine which has been called by a GOSUB. Either STOP or END can be used to separate a program from its subroutines. STOP will print a message saying at what line the STOP was encountered; END will terminate the program without any message. Both commands return control to the user, printing the APPLESOFT prompt character } and a flashing cursor. 16 READ ... DATA... RESTORE Suppose you want your program to use numbers that don’t change each time the program is run, but which are easy to change if necessary. BASIC contains special statements for this purpose, called the READ and DATA statements. Consider the following program: 1 PRINT "GUESS A NUMBER" 2g INPUT G 30 READ D 49 IF D = ~999999 THEN GoTO 99 59 LF D <> G THEN GOTO 39 69 PRINT “YOU ARE CORRECT" 79 END 99 PRINT "BAD GUESS, TRY AGAIN." 95 RESTORE 199 GoTO 16 119 DATA 1,393,-39, 28, 391,-8,0,3.14,90 129 DATA 89,5, 19,15,-34,-999999 This is what happens when the program is RUN: when the READ statement is encountered, the effect is the same as an INPUT statement, but instead of getting a number from the keyboard, a number is read from the DATA statements. The first time a number is needed for a READ, the first number in the first DATA statement is returned. The second time one is needed, the second number in the first DATA statement is returned. When the entire contents of the first DATA statement have been read in this manner, the second DATA statement will then be used. DATA is always read sequentially in this manner, and there may be any number of DATA statements in your program. The purpose of this program is to play a little game in which you try to guess one of the numbers contained in the DATA statements. For each guess that is typed in, the computer reads through all of the numbers in the DATA statements until it finds one that matches the guess. If READ returns ~999999, all of the available DATA numbers have been used, and a new guess must be made. Before going back to line 19 for another guess, we need to make the READ begin with the first piece of data again. This is the function of the RESTORE. After RESTORE is encountered, the next piece of data READ will again be the first item in the first DATA statement. DATA statements may be placed anywhere within the program. Only READ statements make use of the DATA statements in a program, and any other time they are encountered during program execution they will be ignored. 17 REAL, INTEGER AND STRING VARIABLES There are three different types of variables used in APPLESOFT BASIC. So far we have just used one type -- real precision. Numbers in this mode are displayed with up to nine decimal digits of accuracy and may range up to approximately 19 to the 38th power. APPLESOFT converts your numbers from decimal to binary for its internal use and then back to decimal when you ask it to PRINT the answer. Because of rounding errors and other unpredictables, internal math routines such as square root, divide, and exponent do not always give the exact number that you expected. ‘The number of places to the right of the decimal point may be set by rounding off the value prior to PRINTing it. The general formula for accomplishing this ist X = INT (K#19D4, 5) /INT (19-D+. 5) In this case, D is the number of decimal places. A faster way to set the number of decimal places is to let P-197D and use the formula: X = INT(X#P+.5)/P where P=1G is one place, P=199 is 2 places, P=1699 is 3 places, etc. The above works for X>=1 and X<999999999. A routine to limit the number of digits after the decimal point is given in the next section in this chapter. ‘The table below summarizes the three types of variables used in APPLESOFT BASIC programming: Description Symbol_to Append Example to Variable Nane Strings $ As (@ to 255 characters) ALPHAS Integers (must be in range x BE of ~32767 to +32767) cig Real Precision none c (Exponent -38 to +38, BOY with 9 decimal digits) An integer or string variable must be followed by a % or $ at each use of that variable. For example, X, X% and X$ are different variables. Integer variables are not allowed in FOR or DEF statements. The greatest advantage of integer variables is their use in array operations wherever possible, to save storage space. ALI arithmetic operations are done in real precision. Integers and integer variable values are converted to real precision before they are used in a calculation. The functions SIN, COS, ATN, TAN, SQR, LOG, EXP and RND also convert their arguments to real precision and give their results as such. When a oumber is converted to an integer, it is truncated (rounded down). For example: 122.999 Alea. 01 PRINT 1% PRINT A% 8 -l 18 If you assign a real number to an integer variable, and then PRINT the value of the integer variable, it is as if the INT function had been applied. No automatic conversion is done between strings and numbers: assigning a number to a string variable, for instance, results in an error message. However, there are special functions for converting one type to the other. STRINGS A sequence of characters is referred to as a "literal". A "string" is a Literal enclosed in quotation marks. These are all strings: "BILL APPLE’ “THIS IS A TEST" Like numeric variables, string variables can be assigned specific values. String variables are distinguished from numeric variables by a $ after the variable name. For example, try the following: AS = "GOOD MORNING" PRINT AS GOOD MORNING In this example, we set the string variable A$ to the string value "GOOD MORNING". Now that we have set A$ to a string value, we can find out what the length of this value is (the number of characters it contains). We do this as follows: PRINT LEN(AS), LEN("YES" 12 3 The LEN function returns an integer equal to the number of characters in a string: its LENgth. The number of characters in a string expression may range from @ to 255. A string which contains 9 characters is called a "null" string. Before a string variable is set to a value in the program, it is initialized to the null string. PRINTing a null string on the terminal will cause no characters to be printed, and the cursor will not be advanced to the next column. Try the following: PRINT LEN(Q$)3 Q$3 3 93 Anothe: Qs = or the equivalent statement LET Q$ =" way to create the null string is to use Setting a string variable to the null string can be used to free up the string space used by a non-null string variable. But you can get into trouble assigning the null string to a string variable, as discussed in Chapter 7 under the IF statement. 19 Often it is desirable to retrieve part of a string and manipulate it. Now that we have set A$ to "GOOD MORNING", we might want to print out only the first four characters of AS. We would do so like this: PRINT LEFT$(AS,4) coop LEFTS(A$,N) is a string function which returns a substring composed of the leftmost N characters of its string argument, A$ in this case. Here’s another example: FOR N = 1 TO LEN(A$) : PRINT LEFT$(A$,N) : NEXT N G co Goo coop coop Goon coop Mo GOOD MOR GOOD MORN GOOD MORNT GOOD MORNIN GOOD MORNING Since A$ has 12 characters, this loop will be executed with N=l, 2, 3,s00s 11, 12. The first time through, only the first character will be printeds the second time the first two characters will be printed, etc. There is another string function called RIGHTS. RIGHT$(A$,N) returns the rightmost N characters from the string expression A$. Try substituting RIGHTS for LEFT$ in the previous example and see what happens. There is also a string function which allows us to take characters from the middle of a string. Try the followin; FOR N = 1 TO LEN(A$) : PRINT MID$(AS,N) : NEXT N MID$(A$,N) returns a substring starting at the Nth position of A$ to the end (last character) of AS. The first position of the string is position 1 and the last possible position of 2 string is position 255. Very often, it is desirable to extract only the Nth character from a string. This can be done by calling MID$ with three arguments: MID$(A$,N,1). The third argument specifies the number of characters to be returned, beginning with character N. 20 For example: FOR N=1 TO LEN(AS): PRINT MID$(A$,N,1), MID$(A$,N,2):NEXT N co 00 op D M MO oR, RN NI IN NG 6 wooo Oznarox See Chapter 5 for more details on the workings of LEFT$, RIGHT$ and MIDS. Strings may also be concatenated (put or joined together) through the use of the plus (+) operator. Try the following: BS = AS +" "+ "BILL PRINT BS GOOD MORNING BILL Concatenation is especially useful if you wish to take a string apart and then put it back together with slight modifications. For instance: C$ = RIGHTS (B$,3) + "=" + LEFTS$(BS,4) + "=" + MIDS$(BS, 6,7) PRINT C$ BILL~GOOD-HORNING Sometimes it is desirable to convert a number to its string representation and vice-versa. The functions VAL and STR$ perform these tasks. Try the following: STRINGS = "567.8" PRINT VAL (STRINGS) 567.8 STRINGS = STRS(3.1415) PRINT STRINGS, LEFT$(STRINGS,5) 3.1415, 3.141 The STR$ function can be used to change numbers to a certain format for input or output. You can convert a number to a string and then use LEFTS, RIGHTS, MID$ and concatenation to reformat the number as desired. The following short program demonstrates how string functions may be used to format numeric output? 199 INPUT 119 PRINT "TYPE ANY NUMBER: "3 X REM SKIP A LINE 12 PRINT "AFTER CONVERSION TO REAL PRECISION," 139 INPUT "HOW MANY DIGITS TO RIGHT OF DECIMAL? "3 D 149 GOsUB 1999 15@ PRINT "ax 168 GOTO 198 1989 XS = STRS(X) : REM CONVERT INPUT TO STRING 1919 REM FIND POSITION OF E, IF IT EXISTS 1929 FOR I = 1 to LEN(X$) 1939 IF MIDS(X$,1,1) <> "E" THEN NEXT T 1940 REM I IS NOW AT EXPONENT PORTION (OR END) 1959 REM FIND POSITION OF DECIMAL, IF IT EXISTS 1969 FOR J = 1 TO I-1 1979 IF MIDS$(X$,J,1) <> "." THEN NEXT J 1989 REM J IS NOW AT DECIMAL (OR END OF NUMBER PORTION) 1999 REM DO D DIGITS EXIST TO RIGHT OF DECIMAL? 1199 IF J4D <= I-1 THEN N = J4D : GOTO 1136 : REM YES 1119 N = I-L : REM NO, SO PRINT ALL DIGITS 1129 REM PRINT NUMBER PORTION AND EXPONENT PORTION 1139 PRINT LEFT$(X$,N) + MID(XS, 1) 1149 RETURN : REM SEPARATOR The above program uses a subroutine starting at line 199 to print out a predefined real variable X truncated, not rounded off, to D digits after the decimal point. The variables X$, I and J are used in the subroutine as local variables. Line 1999 converts the real variable X to string variable x$. Lines 192 and 1939 scan the string to see if an E is present. I is set to the position of the E, or to LEN(X$) + 1 if no E is there. Lines 1960 and 1970 search the string for a decimal point. J is set to the position of the decimal point, or to I-I 1f there is no decimal. Line 1109 tests whether there exist at least D digits to the right of the decimal. If they do exist, the number portion of the string must be truncated to length J+D, which is D positions to the right of J, the decimal position. The variable N is set to this length. If there are fewer than D digits to the right of the decimal, the entire number portion may be used. Line 1119 sets the variable N to this length a-b. Finally, line 1139 prints out variable X as the concatenation of two sub-strings. LEFI$(X$,N) returns the significant digits of the number portion, and MID$(X$,1) returns the exponent portion, if it was there. STR$ can also be used to conveniently find out how many print=positions a number will take. For example: PRINT LEN(STRS(33333.157)) 9 22 If you have an application where a user is typing a question such as WHAT IS THE VOLUME OF A CYLINDER OF RADIUS 5.36 FEET AND HEIGHT 5.1 FEET? you can use the VAL function to extract the numeric values 5.36 and 5.1 from the question. Additional information on these functions and CHR$ and ASC is in Chapter 5. ‘The following program sorts a list of string data and prints out the alphabetized list. This program is very similar to the one given earlier for sorting a numeric list. 199 DIM A$(15) 119 FoR T= 1 70 15 16 =G:1=1 139 IF AS(1) <= AS(I+1) THEN GoTo 189 149 TS = AS(I+1) 150 AS(I41) = AS(I) 169 AS(I) = TS 179 F=1 189 I = I+] : IF I <= 15 THEN GOTO 139 19 IF F = 1 THEN Goro 129 209 FOR I = 1 TO 15 : PRINT AS(I) : NEXT I 229 DATA APPLE, DOG, CAT, RANDOM, COMPUTER , BASIC 239 DATA MONDAY, ""*2*ANSWER*#8", "FOO: " 249 DATA COMPUTER, FOO, ELP, MILWAUKEE, SEATTLE, ALBUQUERQUE READ A$(L) : NEXT I MORE COLOR GRAPHICS In two previous examples, we’ve explained how the APPLE II can do color graphics as well as text. In GRaphics mode, the APPLE displays up to 1696 small squares, in any of 16 possible colors, on a 4 by 4@ grid. It also provides 4 lines of text at the bottom of the screen. The horizontal or x-axis is standard, with @ the leftmost position and 39 the rightmost. The vertical or y-axis is non-standard in that it is inverted: § is the Eopmost position and 39 is the bottommost. 23 19 GR : REM INITIALIZE COLOR GRAPHICS; SET 49X49 TO BLACK. SET TEXT WINDOW TO 4 LINES AT BOTTOM 26 HOME ; REM CLEAR ALL TEXT AT BOTTOM 39 COLOR = 1 : PLOT 9, : REM MAGENTA SQUARE AT 0,0 49 LIST 36 : GOsUB 1908 59 COLOR = 2: PLOT 39,0: REM BLUE SQUARE AT X-39,Y=0 69 HOME : LIST 59: GOSUB 1998 7 COLOR = 12 : PLOT 9,39 : REM GREEN SQUARE AT X=,Y=39 89 HOME : LIST 7 : GOSUB 1990 99 COLOR = 9 : PLOT 39,39: REM ORANGE SQUARE AT X=39,¥=39 199 HOME : LIST 99 : GOSUB 1999 119 COLOR = 13: PLOT 19,19: REM YELLOW SQUARE AT CENTER OF SCREEN 129 HOME : LIST 119 : GOSUB 1999 139 HOME : PRINT "PLOT YOUR OWN POINTS" 149 PRINT "REMEMBER, X & Y MUST BE >=9 & <=39" 159 INPUT "ENTER X,Y: "; X,Y 169 COLOR = 8 : PLOT X,Y : REM BROWN SQUARES 17G PRINT "TYPE “CTRL C’ AND PRESS RETURN TO STOP" 189 GoTo 159 199 PRINT ‘SAHIT ANY KEY TO CONTINUE***";: GET A$: RETURN After you have typed the program, LIST it and check for typing errors. You may want to SAVE it on cassette tape for future use. Then RUN the program. The command GR tells APPLE to switch to its color GRaphics mode. The COLOR command sets the next color to be plotted. That color remains set until changed by a new COLOR command. For example, the color plotted in line 169 remains the same no matter how many points are plotted. The value of the expression following COLOR must be in the range # to 255 or an error may occur. However, there are only 16 different colors, usually numbered from @ through 15. Change the program by re-typing lines 159 and 169 as follows: 159 INPUT "ENTER X, ¥, COLOR: "3 X, Y, Z 169 COLOR = Z: PLOT X,Y Now RUN the program and you will be able to select your own colors as well as points. We will demonstrate the APPLE’s color range in a moment. The PLOT X,¥ command plots a small square of color defined by the last COLOR conmand at the position specified by expressions X and Y. Remember, X and Y mast each be a number in the range @ through 39. The GET instruction in line 199@ is similar to an INPUT instruction. It waits for a single character to be typed on the keyboard, and assigns that character to the variable following GET. It is not necessary to press the RETURN key. In line 1099, GET A$ is just used to stop the program until any key is pressed. Remember: To get from color graphics back to all text mode, type TEXT and then press the RETURN key. The APPLESOFT prompt character will then reappear. 24 Type the following program and RUN it to display the APPLE’s range of colors (remember to type NEW first). 14 GR: HOME 29 FOR I = 9 To 31 39 COLOR = 1/2 4G VLIN 9,39 AT 1 59 NEXT I 69 FOR I = @ TO 14 STEP 2 : PRINT TAB(I*2 + 1); Tj : NEXT T 79 PRINT 89 FOR I = 1 TO 15 STEP 2 : PRINT TAB(I*2 + 1); Ts : NEXT I 9G PRINT : PRINT "STANDARD APPLE COLOR BARS"; Color bars are displayed at double their normal width. The leftmost bar is black as set by COLOR=9; the rightmost, white, is set by COLOR=15. Depending on the tint setting on your TV, the second bar as set by COLOR=1 will be magenta (reddish-purple) and the third (COLOR=2) will be dark blues Adjust your TV tint control for these colors. In Europe, color tints may be different. In the last program a command of the form VLIN Yl, Y2 AT X was used in Line 49. This command plots a vertical line from the y-coordinate specified by expression YI to the y-coordinate specified by expression Y2, at the horizontal position specified by expression X. Yl, Y2 and X must evaluate to values in the range @ through 39. Y2 may be greater than, equal to, or smaller than Yl. The command HLIN Xl, X2 AT Y is similar to VLIN except that it plots a horizontal line. Note: The APPLE draws an entire line just as easily as it plots a single point! HIGH-RESOLUTION COLOR GRAPHICS Now that you are familiar with the APPLE’s low-resolution graphics, you will find that understanding high-resolution graphics is easy. The commands have a similar appearance: usually they are formed by just adding an H (for High resolution) to the ones you already know. For instance, the command HGR sets high-resolution graphics mode, clears the high-resolution screen to black, and leaves 4 lines for text at the bottom of the screen. In this mode, you are plotting points on a grid that is 289 x-positions wide by 169 yrpositions high. This lets you draw on the screen with much more detail than the 4 by 49 grid of low-resolution graphics. Typing TEXT returns you to the normal text mode. In addition to the HGR screen, there is also a second high-resolution screen you can use if your APPLE contains at least 24K bytes of memory. Wigh-resolution graphics mode for the "second page" of memory is invoked by the command HGR2 This clears the entire screen to black, giving you a plotting surface that is 289 x-positions across by 192 y-positions high, and no text at the bottom. Again, type TEXT to see your program. 25 Sound wonderful? It is; but you do have to make some sacrifice for this new ability: there are fewer colors. The color for high-resolution graphics is set by a command of the form HCOLOR = where N is a number from § (black) to 7 (white). See Chapter 8 for a complete list of the colors available. Because of the construction of color televisions, these colors vary from TV to TV and from one plotted line to the next. Finally, there is one easy instruction for all plotting in high-resolution graphics. To see this in action, type HCOLOR = 3 HGR HPLOT 139, 160 The last command plots a high-resolution dot in the color you set with HCOLOR (white) at the point x=130, y=100. As in low-resolution graphics, x=f is at the left edge of the screen, increasing to the right; y= is at the top of the screen, increasing downward. Maximum value for x is 279; maximum y is 191 (but in HGR’s mixed graphics-plus-text mode, y values are only visible down to y=159). Now type HPLOT 29,15 TO 145,89 Like magic, a white line is drawn from the point x=2, y=15 to the point x=145, y=89. HPLOT can draw lines between any two points on the screen ~~ horizontal, vertical, or any angle. Do you want to connect another line to the end of the previous one? Type HPLOT TO 12,80 This form of the conmand takes its starting point from the Jast point previously plotted, and also takes its color from that point (even if you have issued a new HCOLOR command since that point was plotted). You can even "chain" these commands in one instruction. Try this: HPLOT 9,0 TO 279,@ TO 279,159 TO 9,159 T0 9,9 You should now have a white border around all four sides of the scree Here’s a program that draws pretty "moire" patterns on your screen: 80 HOME : REM CLEAR THE TEXT AREA 199 VTAB 24 : REM MOVE CURSOR TO BOTTOM LINE 129 HGR : REM SET HIGH-RESOLUTION GRAPHICS MODE 149 A = RND(1) * 279 : REM PICK AN X FOR "CENTER" 16GB = RND(1) * 159 : REM PICK A Y FOR "CENTER" 189 1% = (RND(1) * 4) +2: REM PICK A STEP SIZE 298 HTAB 15 : PRINT "STEPPING BY "; I%5 229 FOR X = @ TO 278 STEP I% : REM STEP THRU X VALUES 24g FOR S = @ TO 1: REM 2 LINES, FROM X AND X+1 269 HCOLOR = 3 * S : REM FIRST LINE BLACK, NEXT WHITE 289 REM DRAW LINE THROUGH "CENTER" TO OPPOSITE SIDE 399 HPLOT X+S,9 TO A,B TO 279-X-S,159 329 NEXT S, X 26 58 STEP 1% : REM STEP THRU Y VALUES : REM 2 LINES, FROM Y AND Y41 : REM FIRST LINE BLACK, NEXT WHITE, THROUGH "CENTER" TO OPPOSITE SIDE TO A,B TO 9,159-¥-s 349 FOR ¥ = § TO 369 FOR S = g TO 389 HCOLOR = 3 * 499° REM DRAW LIN 420 HPLOT 279,45 449 NEXT s, ¥ L 1 s E 469 FOR PAUSE = 1 TO 1599 : NEXT PAUSE : REM DELAY 480 GOTO 129 : REM DRAW A NEW PATTERN This is a rather long program; type it in carefully and LIST it in portions (LIST 9,329 for instance) to check your typing. We've added a space between some lines to make the program easier to read. Your LISTing will not show those spaces. When you are sure it is correct, RUN the program. VEAB and HTAB are cursor-moving commands, used to print a character at a pre-determined position on the text screen. VTAB 1 places the cursor in the top line; VIAB 24 places it in the bottom line. HTAB 1 puts the cursor in the leftmost position on the current line; HTAB 49 puts it in the rightmost position. In a PRINT instruction like the one at line 209, you may need a final semicolon to avoid a subsequent “line feed" that displaces your message. The function RND(N), where N is any positive number, returns a random number in the range from @ to .999999999 (see Chapter 19 for a complete discussion of RND). Thus line 189 assigns to the integer variable 1% a random number from 2 to 5 (a number is always rounded down when it is converted to an integer). The STEP size in a FOR...NEXT loop does not have to be an integer, but it may be easier to predict the results for an integer STEP. As you saw in lines 326 and 449, one instruction can provide the NEXT for more than one FOR statement. Be careful that you list the NEXT variables in the right order, though, to avoid crossed loops. Line 469 is just a "delay loop" that gives you @ moment to admire one pattern before the next one begins. Each time line 489 sends the computer back to the HGR command in line 129, HGR clears the screen for the next pattern. To go back to programming, stop the pattern by typing ctrl © and then type TEXT Can you think of ways to change the program? After SAVEing this version on your cassette recorder or disk, try making the value of HCOLOR change randomly. Try drawing first white, then black Lines, or only white lines. HAPPY PROGRAMMING! 27 28 CHAPTER 2 DEFINITIONS SYNTACTIC DEFINITIONS AND ABBREVIATIONS (for an alphabetic list of these definitions, see Appendix N) ‘The following definitions use metasymbols such as { and \ -- characters used to unambiguously indicate structures or relationships in APPLESOFT. The netasymbols are not part of APPLESOFT. In addition to the true metasymbols, the special symbol := indicates the beginning of a complete or partial definition of the term that is to the left of metasybol used to separate alternatives (note: an item may also be defined separately for each alternative) [.] := metasymbols used to enclose material which is optional { } := metasymbols used to enclose material which may be repeated \ z= metasymbol used to enclose material whose value is to be used: the value of x is written \x\ i= metasymbol which indicates a required space metasymbol ee EEOC DIA lower-case letter r= albleldlelf/glhlilslk!1/minlolplqirisltlulvlwlxty lz metasymbol, lower-case letter 112131415161718 1918 metaname {metasymbol} [digit] metasymbol r= a single digit concatenated to a metaname special symbol used by APPLESOFT IT := special special t#lsiztar’ | Cd) Als lat lel+s 121 / ld b= O>d<= CONVERSION OF TYPES When an integer and a real are both present in a calculation, all numbers are converted to reals before the calculation takes place. . The results are converted to the arithmetic type (integer or real) of the final variable to which they are assigned. Functions which are defined on a given arithmetic type will convert arguments of another type to the type for which they are defined. Strings and arithmetic types cannot be mixed. Each can be converted to the other by functions provided for the purpose. EXECUTION MODES imm Some instructions may be used in immediate-execution mode (im) in APPLESOPT. In immediate-execution mode, an instruction must be typed without a line number. When the RETURN key is pressed, the instruction is immediately executed. def Instructions used in deferred-execution mode (def) must appear in a line that begins with a line number. When the RETURN key is pressed, APPLESOFT stores the numbered line for later use. Instructions in deferred-execution mode are executed only when their line of a program is RUN. 36 CHAPTER x SYSTEM AND UTILITY COMMANDS LOAD imm & def SAVE imm & def LOAD SAVE These LOAD a program from a cassette tape and SAVE a program on a cassette tape, respectively. There is no prompting message or other signal issued by these commands; the user must have the cassette tape recorder running in the proper mode (play or record) when the command is executed. LOAD and SAVE do not verify that the recorder is in the proper mode or even that the recorder is present. Both commands sound a "beep" to signal the beginning and the end of recordings. Program execution continues after a SAVE operation, but a LOAD deletes the current program when it begins reading new information fron the cassette tape. Only reset can interrupt a LOAD or a SAVE. If the reserved word LOAD or SAVE is used as the first characters of a variable name, the reserved-word command may be executed before any ‘7SYNTAX ERROR message is given. The statement SAVERING = 5 causes APPLESOFT to try SAVEing the current program. You can wait for the second "beep" (and the ?SYNTAX ERROR message) or press reset. The statement LOADTOJOY = 47 hangs the system, while APPLESOFT deletes the current program and waits indefinitely for a program from the cassette recorder. Only by pressing reset can you regain control of the computer. NEW inm & def NEW No parameters. Deletes current program and all variables. RUN im & def RUN [linenum) Clears all variables, pointers, and stacks and begins execution at the line number indicated by linenum. Tf Linenum is not indicated, RUN begins at the lowest numbered line in the program, or returns control to the user if there is no program in memory. In deferred execution mode, if linenum is given but there is no such line in the program, or if linenum is negative, then the message QUNDEF’D STATEMENT ERROR 38 appears. If linenum is greater than 63999, the message ‘SYNTAX ERROR appears. You are not told in which line the error occurred. In immediate execution mode, on the other hand, these two messages become QUNDEF’D STATEMENT ERROR IN xxxx and ‘2SYNTAK ERROR IN xxxx where xxxx can be various line numbers, usually above 65900. If RUN is used in an immediate-execution program, any subsequent portion of the immediate-execution program is not executed. STOP imm & def END imm & def ctrl C imm only reset imma only CONT imm & def STOP END ctrl ¢ reset CONT STOP causes @ program to cease execution, and returns control of the computer to the user. It prints the message BREAK IN linenum where linenum is the line number of the statement which executed the STOP. END causes a program to cease execution, and returns control to the user. No message is printed. ctrl C has an effect equivalent to the insertion of a STOP statement immediately after the statement that is currently being executed. ctrl C can be used to interrupt a LISTing. It can also be used to interrupt an INPUT, but only if it is the first character entered. The INPUT is not interrupted until return is pressed. reset stops any APPLESOFT program or command unconditionally and immediately. The program is not lost, but some progtam pointers and stacks are cleared. This command leaves you in the system monitor program, as indicated by the monitor’s prompt character ( * ). To return to APPLESOFT without destroying the current stored program, type ctrl C return. If program execution has been halted by STOP, END or ctrl C, the CONT conmand causes execution to resume at the next instruction -~ not the next line number. Nothing is cleared. If there is no halted program, then CONT has no effect. After reset ctrl ¢ return the program may not CONTinue to execute properly, since some program pointers and stacks will have been cleared. 39 If an INPUT statement is halted by ctrl C, an attempt to CONTinue execution results ina ‘2SYNTAX ERROR IN linenum message, where linenum is the line number of the line containing the INPUT statement. Executing CONT will result in the 2CAN’T CONTINUE ERROR message if, after the program’s execution halts, the user a) modifies or deletes any program line. b) attempts any operation that results in an error message. However, program variables can be changed using immediate-execution commands, as long as no error messages are incurred. & If DEL is used in a deferred execution statement, the specified lines are deleted and then program execution halts. An attempt to use-CONT under these circumstances will cause the ‘2CAN’T CONTINUE ERROR message. If CONT is used in a deferred execution statement, the program’s execution is halted at that statement, but control of the computer is not returned to the user. The user can regain control of the computer by issuing a ctrl C command, but an attempt to CONTinue program execution in the next statement merely relinquishes control to the halted program again. TRACE imm & def NOTRACE imm & def TRACE NOTRACE TRACE sets a debug mode that displays the line number of each statement as it is executed. When the program also prints on the screen TRACEs may be displayed in an unexpected fashion or overwritten. NOTRACE turns off the TRACE debug mode- Once set, TRACE is not turned off by RUN, CLEAR, NEW, DEL or reset; reset ctrl B turns off TRACE (and eliminates any stored program). PEEK inm & def PEEK (aexpr) Returns the contents, in decimal, of the byte at address \aexpr\. Appendix J contains examples of how to use PEEK. 40 POKE inm & def POKE aexprl, aexpr2 POKE stores an eight bit quantity, the binary equivalent of the decimal value \aexpr2\, into the location whose address is given by \aexprl\. The range of \aexpr2\ must be from @ through 2553 that of \aexprl\ must be from 65535 through 65535. Reals are converted to integers before execution. out of range values cause the message ‘ILLEGAL QUANTITY ERROR to be printed. \aexpr2\ will be successfully stored only if the appropriate receiving hardware (menory, or a suitable output device) is present at the address specified by \aexprl\. \aexpr2\ will not be successfully stored at non-receptive addresses such as the Monitor ROMs or unused Input /Output ports. In general, this means that \aexpri\ will be in the range @ through max, where max is determined by the amount of memory in the computer. For instance, on an APPLE II with 16K of memory, max is 16384. If the APPLE II has 32K of memory, max is 32768; and if the APPLE II has 48K of memory, max is 49152. Many memory locations contain information which is necessary to the functioning of computer system. A POKE into these locations may alter the operation of the system or of your program, or it may clobber APPLESOFT. WAIT imm & def WAIT aexprl, aexpr2 [, aexpr3] Allows user to insert a conditional pause into a program. Only reset can interrupt a WAIT. \aexprl\ is the address of memory location; it must be in the range -65535 through 65535 to avoid the TILLEGAL QUANTITY ERROR message. In practice, \aexpri\ is usually limited to the range of addresses corresponding to locations at which valid memory devices exist, from 0 through the maximum value for HIMEM: in your computer. See HIMEM: and POKE for more details. Equivalent positive and negative addresses may be used. \aexpr2\ and \aexpr3\ must be in the range 9 through 255, decimal. When WAIT is executed, these values are converted to binary numbers in the range 9 through 11111111. If only aexpri and aexpr2 are specified, each of the eight bits in the binary contents of location \aexpri\ is ANDed with the corresponding bit in the binary equivalent of \aexpr2\. For each bit, this gives a zero unless both of the corresponding bits are high (1). If the results of this process 4a are eight zeros, then the test is repeated. If any result is non-zero (which means at least one high (1) bit in \aexpr2\ was matched by a corresponding high (1) bit at location \sexprl\), the WAIT is completed and the APPLESOFT program resumes execution at the next instruction. WAIT aexpri, 7 causes the program to pause until at least one of the three rightmost bits at location \aexprl\ is high (1). WAIT aexprl, 9 causes the program to pause forever. If all three parameters are specified, then WAIT performs as follows: first, each bit in the binary contents of location \aexpr!\ is XORed with the corresponding bit in the binary equivalent of \aexpr3\. A high (1) bit in \aexpr3\ gives a result that is the reverse of the corresponding bit at location \aexprl\ (a 1 becomes a 93 a B becomes al). A low (G) bit in \aexpr3\ gives a result that is the same as the corresponding bit at location \sexprl\. If \aexpr3\ is just zero, the XOR portion does nothing. Second, each result is ANDed with the corresponding bit in the binary equivalent of \aexpr2\. If the final results are eight zeros, the test is repeated. If any result is non-zero, the WAIT is completed and execution of the APELESOFT program continues at the next instruction. Another way to look at WAIT: the object is to test the contents of location \aexpri\ to see when any one of certain bits is high (1, or on) or any one of certain other bits is low (B, or off). Each of the eight bits in the binary equivalent of \aexpr2\ indicates whether you are interested in the corresponding bit at location \sexprl\: 1 means youre interested, 0 means ignore that bit. Each of the eight bits in the binary equivalent of \aexpr3\ indicates which state you are WAITing for the corresponding bit in location \aexprl\ to be in: 1 means the bit must be low, zero means the bit must be high. If any of the bits in which you have indicated interest (by a 1 in the corresponding bit of \aexpr2\) matches the state you specified for that bit (by the corresponding bit of \aexpr3\) the WAIT is over. If aexpr3 is omitted, its default value is zero. For instance: WAIT aexprl, 255, @ means pause until at least one of the 8 bits at location \aexprl\ is high. WAIT aexprl, 255 Identical to the above, in operation. WAIT aexprl, 255, 255 means pause until at least one of the 8 bits at location \aexpr!\ is low. WAIT aexprl, 1, 1 means pause until the rightmost bit at location \aexprl\ is low, regardless of the states of the other bits. WAIT aexprl, 3, 2 means pause until either the rightmost bit at location \aexprl\ is high, or the next-to-rightmost bit is low, or both conditions exist. 42 This program pauses until you type any character whose ASCII code (see Appendix K) is event 190 POKE -16368, 9 : REM RESET KEYBOARD STROBE (HIGH BIT) 195 REM PAUSE UNTIL KEYBOARD STROBE IS SET BY ANY KEY. 119 WAIT -16384, 128 : REM WAIT UNTIL HIGH BIT IS ONE. 115 REM PAUSE SOME MORE UNTIL KEY STRUCK IS EVEN. 129 WAIT -16384, 1, 1 : REM WAIT UNTIL LOW BIT IS ZERO. 139 PRINT “EVE! 149 GOTO 1969 CALL imm & def CALL aexpr Causes execution of a machine-language subroutine at the memory location whose decimal address is specified by \aexpr\. \aexpr\ must be in the range -65535 through 65535 or the message ILLEGAL QUANTITY ERROR is displayed. In practice, \aexpr\ is usually limited to the range of addresses for which valid memory devices exist, from @ through the maximum value for HIMEM: in your computer. See HIMEM: and POKE for more details. Equivalent positive and negative addresses may be used interchangeably. For instance, “CALL -936" and "CALL 64699" are identical. Appendix J contains examples of the use of CALL. HIMEM: in & def HIMEM: aexpr Sets the address of the highest memory location available to a BASIC program, including variables. It ig used to protect the area of memory above it for data, graphics or machine language routines. \aexpr\ must be in the range -65535 through 65535, inclusive, to avoid the ‘ILLEGAL QUANTITY ERROR message. However, programs may not execute reliably unless there is appropriate memory hardware at the locations specified by all addresses up to and including \aexpr\. In general, the maximum value of aexpr is determined by the amount of memory in the computer. For instance, on an APPLE II with 16K of memory \aexpr\ would be 16384 or less. If the APPLE II has 32K of memory, \aexpr\ could be as high as 32768; and if the APPLE Il has 48K of memory, \sexpr\ could be as high as 49152. Normally, APPLESOFT automatically sets HIMEM: to the highest memory address available on the user’s computer, when APPLESOFT is first invoked. 43 The current value of HIMEM: is stored in memory locations 116 and 115 (decimal). To see the current value of HIMEM:, type PRINT PEEK(116)*256 + PEEK(115) If HIMEM: sets a highest memory address which is lower than that set by LOMEM:, or which does not leave enough memory available for the program to run, the 20UT OF MEMORY ERROR is given. \aexpr\ may be in the range @ increasing to 65535, or in the equivalent range ~65535 increasing to 1. Equivalent positive and negative values may be used interchangeably. HIMEM: is not reset by CLEAR, RUN, NEW, DEL, changing or adding a program line, or reset. HIMEM: is reset by reset ctrl B return, which also erases any stored progran. LOMEM: imm & def LOMEM: aexpr Sets the address of the lowest memory location available to a BASIC program. This is usually the address of the starting memory location for the first BASIC variable. Normally, APPLESOPT automatically sets LOMEM: to the end of the current program, before executing the program. This command allows protection of variables from high-resolution graphics in computers with large amounts of memory. \aexpr\ must be in the range ~65535 through 65535, inclusive, to avoid the 2ILLEGAL QUANTITY ERROR message. However, if LOMEM: is set higher than the current value of HIMEM:, the message 20UT OF MEMORY ERROR is displayed. This means that \aexpr\ must be lower than the maximum value that can be set by HIMEM: (See HIMEM: for a discussion of its maximum value.) IE LOMEM: is set lower than the address of the highest memory location occupied by the current operating system (plus any current stored program), the 20UT OF MEMORY ERROR message is again displayed. This imposes an absolute lower limit on \aexpr\ of about 2951 for firmware APPLESOFT. LOMEM: is reset by NEW, DEL, and by adding or changing a program line. LOMEM: is reset by reset ctrl B, which also deletes any stored program. It is not reset by RUN, reset ctrl C return or reset 0G return. The current value of LOMEM: is stored in memory locations 196 and 195 (decimal). To see the current value of LOMEM:, type PRINT PEEK(196)#256 + PEEK(105) Once set, unless it is first reset by one of the above commands, LOMEM: can be set to a new value only if the new value is higher (in memory) than the old value. An attempt to set a lower LOMEM: than the value still in effect gives the 20UT OF MEMORY ERROR message. Changing LOMEM: during the course of a program may cause certain stacks or portions of the program to be unavailable, so that the program will not continue to execute properly. Equivalent positive and negative addresses may be used interchangeably. USR imm & def USR (aexpr) This function passes \aexpr\ to a machine-language subroutine. The argument aexpr is evaluated and put into the floating point accumulator (locations $9D through $A3), and a JSR to location $9A is performed. Locations $@A through $9C must contain a JMP to the beginning location of the machine-language subroutine. The return value for the function is placed in the floating point accumulator. To obtain a 2-byte integer from the value in the floating-point accumulator, your subroutine should do a JSR to SE1@C. Upon return, the integer value will be in locations $a@ (high-order byte) and $Al (low-order byte). To convert an integer result to its floating-point equivalent, so that the function can return that value, place the two-byte integer in registers A (high-order byte) and Y (low-order byte). Then do a JSR to $E2F2. Upon return, the floating-point value will be in the floating-point accumulator. To return to APPLESOFT, do an RTS. Here is a trivial program using the USR function, just to show you the format: ] reset * GAL4C 99 93 return * 9300:69 return * ctrl C return ] PRINT USR(8)*3 24 At location $9A, we put a JMP (code 4C) to location $300 (low-order byte first, then high-order byte). At location $309, we put an RTS (code 69). Back in APPLESOFT, when USR(8) was encountered the argument 8 was placed in the accumulator, the Monitor did a JSR to location $@A where it found a JMP to $399. In $399 it found an RTS which sent it back to APPLESOFT. The value returned was just the original value 8 in the accumulator, which APPLESOFT then multiplied by 3 to get 24, CHAPTER y.| EDITING AND FORMAT-RELATED COMMANDS LIST imm & def LIST [1inenuml) [+ 1inenum2) LIST [1inenuml) [, linenum2] If neither linenum! nor linenum2 is present, with or without a delimiter, the entire program is displayed on the screen. If linenuml is present without a delimiter, or if linenuml=linenum2, then just the line numbered Linenum! is displayed. If linenuml and a delimiter are present, then the program is listed from the line numbered linenum! through the end. If a delimiter and linenum2 are present, then the program is listed from the beginning through the line numbered linenum2. If linenuml, a delimiter and Linenum? are all present, then the program is listed from the line numbered linenuml through the line numbered linenum2, inclusive. When more than one line is to be listed, if the line numbered linenuml in the LIST statement does not appear in the program, the LIST command will use the next greater line number that does appear in the program. If the line numbered Linenum? in the LIST statement does not appear in the progran, the LIST command will use the next smaller line number that does appear in the program. These all LIST the entire program: List @ = LIST [,]-1 9 LIST 9 [,|-1 9 LIST linenum, 9 lists from the line with line number linenum through the end of the program. LIST , Q Lists the entire program, then gives the ‘SYNTAX ERROR message. APPLESOFT "tokenizes" your program lines before storing them, removing unnecessary spaces in the process. When LISTing, APPLESOFT "reconstitutes the tokenized program lines, adding spaces according to its own rules. For example, 1 C=45/-6:B=-5 becomes Wo= +5 / -6:B= -5 when LISTed. LIST uses a variable line width and various indentations. This can be a problem when you are trying to edit or copy a LISTed instruction. To force LIST to abandon formatting with extra spaces, clear the screen and reduce the text window to width 33 (maximum): HOME POKE 33,33 APPLESOFT truncates a line to 239 characters, then LIST adds spaces liberally. So you can enter many extra characters by leaving out spaces when typing -- LIST adds them back. An attempt to copy your expanded statement from the screen results in truncation to 239 characters again, including the spaces added by LIST. LISTing 1s aborted by ctrl C. 48

You might also like