Applesoft II BASIC Programming Reference Manual
Applesoft II BASIC Programming Reference Manual
= 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: 1529 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. 16READ ... 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. 17REAL, 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 18If 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. 19Often 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. 20For 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 22If 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. 2319 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. 24Type 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. 25Sound 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 2658 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! 2728CHAPTER 2 DEFINITIONSSYNTACTIC 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. 36CHAPTER x SYSTEM AND UTILITY COMMANDSLOAD 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 38appears. 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. 39If 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. 40POKE 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 4aare 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. 42This 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. 43The 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 COMMANDSLIST 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