ApplesoftLanguage SecondEdition
ApplesoftLanguage SecondEdition
APPLESOFT _
Second Edition
_ BY BRIAN D. BLACKWOOD
& GEORGE H. BLACKWOOD
Applesoft
Language
Second Edition
Dr. George H. Blackwood is a retired
Navy pilot and a former college professor
with bachelor’s, master’s, education special-
ist, and D.D.S. degrees. He now devotes full
time to writing.
SECOND EDITION
FIRST PRINTING — 1983
Unless the computer has a hardware problem, it does not make mistakes.
Many times the statement is heard, “It’s the computer's fault.’’ Don’t you be-
lieve it! If an error comes from a computer, it was caused by a person or per-
sons, and a person or persons must correct the error.
Computers are a great part of our daily lives and will be a greater part in
the future. The more you understand about computers, their operations,
and programming, the better you will understand the future. Much of the
future of the world is tied to computer operations.
GEORGE H. BLACKWOOD
Contents
SECTION II — Programming
LESSON 22
APPROACHING THE PROBLEM.... 0.2.0. e eee ee ec eee eee eee eee eas 161
LESSON 23
PROGRAM FLEXIBILITY ....... 0.0.00 cee eee eee ee eee eee eee eee 171
LESSON 24
CIRCULAR LISTS, STACKS, AND POINTERS .........
0000 ce cee eee eens 175
LESSON 25
SORTING, SEARCHING, AND DELETING .........
0.0000 eee eee eee 183
LESSON 26
FORMULAS .... 00 cc ee ee eee eee ee ne eee ee eee eee eee 205
LESSON 27
SECTION II — Supplement
LESSON 28
Introduction
10
The first section, Applesoft Language, assumes the reader can push the
OFF-ON switch to the ON position so the little light on the keyboard glows.
Once the light is glowing, Lesson 1 attempts to introduce the user to de-
tailed programming routines. The explanations may be tedious and repeti-
tious, but programming is exact and any detail affects the program. The ex-
planations use lay language and try to avoid ambiguous computer engineer-
ing phrases. There is an old computer cliche that covers this situation, “If
you cant dazzle them with brilliance, then baffle them with bs.”
The second section, Programming, deals with the logic, formulas, and
thought that enable interaction among the programmer, the program, and
the computer. This section brings the reader from the hand holding stage to
the thinking stage. The section stimulates those seldom used brain cells.
You can feel the rust breaking loose and the dendrites pull and strain.
The third section, Supplement, presents simulations, games, and
graphics.
We have written this book specifically for the Apple II microcomputer,
which uses microsoft (Applesoft) language. We are not connected directly
or indirectly with Apple Computer, Inc. or Bell and Howell.
SECTION |
Applesoft Language
LESSON 1
Load and Save Programs on Tape
VOCABULARY
CRT — This abbreviation stands for cathode ray tube. The picture tube in
your television is a CRT. The CRT can be used to display the output from
and the typed-in input to your Apple computer.
Cursor — This is a blinking square of white light on a black field in the NOR-
MAL mode. A blinking square of black light on a white field in the IN-
VERSE mode.
Input — This is the process of transferring data, or program instructions,
into memory from some peripheral unit. It also can denote the data itself.
The word “input” sometimes denotes the signal applied to a circuit or a
device, such as a timing signal.
Line Number — This is a positive integer that begins each program state-
ment.
LIST — This command displays the entire program on the screen. LIST
0,100 lists the program statements from 0 to 100 on the screen.
LOAD — This command reads a program from cassette tape and stores it in
computer memory. LOAD USA loads a program named USA from cas-
sette into computer memory.
NEW — This command deletes the current program and all variables from
computer memory.
Program — This is the set of statements or instructions that tells the com-
puter how to solve a given problem or accomplish some other task.
Program Statement — This is a discrete instruction to the computer, stored
in memory, that begins with a positive integer.
15
16 APPLESOFT LANGUAGE
RUN — This command clears all variables, pointers, and stacks, and begins
execution of the program. RUN generally begins at the lowest number
and executes the complete program.
SAVE — This command stores a program on cassette tape. SAVE USA
stores a program named USA on cassette. (Programmers describe this
action as a SAVE fo tape.)
VDM — This abbreviation stands for video display module, which is an elec-
tronic screen for displaying data or information.
DISCUSSION
The starting point of this lesson is after Applesoft is in place in the Apple
Il computer. When Applesoft is loaded into the computer from ROM (read
only memory), disk, or cassette tape, the prompt (]) and the cursor (MB)
appear on the left side of the screen.
The older version of the Apple II came with Integer BASIC as standard
equipment and Applesoft as an accessory available either on ROM or cas-
sette tape. The present Apple II Plus comes with Applesoft as a standard
ROM card and the Integer BASIC language as an accessory to be purchased
separately.
Programs typed on the keyboard are stored in memory. Programs of
value are SAVEd to cassette tape or disk. From your program library pro-
grams are LOADed from tape or disk into memory. Programs are also re-
ferred to as software.
After the screen has been cleared, type in the following program.
10 PRINT “‘THIS IS THE USA’’
20 ~PRINT
30 = PRINT “‘THIS IS THE”
40 PRINT ‘*UNITED STATES”
50 ~—~PRINT “‘OF AMERICA”
60 PRINT
70 —~PRINT “’THIS IS THE”,
80 = =PRINT “USA”
999 END
Type in RUN and press RETURN. The output from the program appears
on the screen. Study the output in relation to the program statements. Now
type LIST and press RETURN. The program is listed on the screen. To save
this program on cassette tape follow these steps.
1. Type in SAVE — DO NOT PRESS RETURN.
2. Place a cassette into the tape recorder and rewind until the tape
stops.
3. Press the stop-pause button.
4. Set the mechanical counter on the recorder to zero.
LOAD AND SAVE PROGRAMS ON TAPE 17
After each operation, the RETURN key must be pressed to complete the
operation. From this point when an operation is complete, you must press
the RETURN key. Enough said about the RETURN key.
In most cases a volume of 6 and a medium tone will produce a satisfac-
tory LOAD or SAVE. A volume and/or tone that is too low will produce an
ERR below the LOAD or SAVE on the screen. A volume that is too high will
produce a MEM FULL ERR below the LOAD or SAVE. Persistent difficulty in
LOAD or SAVE routines indicates the tape recorder should be checked to
determine if the frequency of the recorder synchronizes with the frequency
of the computer.
Tapes should be of the highest quality and low background noise. Low
quality tapes will give the user great difficulty in loading and saving pro-
grams.
LESSON 2
Save and Load Programs on Disk
VOCABULARY
Booting DOS — The process of loading disk operating system commands
into the Apple computer. Bootstrap is the technique of loading a pro-
gram into a computer by means of certain preliminary instructions which
in turn call in instructions to read programs, and/or data. The preliminary
instructions are usually preset on a device (a disk, in this case), and called
into action by the power “on” switch, or a special command from the key-
board, IN*6 or PR*6. Literally, the computer picks itself up “by its boot-
straps.”
Disk or Diskette — A magnetic disk is a storage device that consists of a flat
circular plate coated on both sides with some material (Mylar) that can be
magnetized. The Apple II uses a single density, soft sectored, 5% inch
diskette as its virtual storage medium. The 5% inch floppy disk has a
storage capacity of 118,000 bytes in the 3.2 disk operating system, and
146,000 bytes in the 3.3 disk operating system. The DOS 3.3 will store
between 100 and 120 pages of normal text. The disk is divided into thirty-
five (35) tracks, three (3) of these tracks are used for the disk operating
system, and one (1) track, #11, is used for the directory. The remaining
thirty-one (31) tracks are for the programmer's use. A number of sectors
19
20 APPLESOFT LANGUAGE
(13 on DOS 3.2, and 16 on DOS 3.3) are available on each track and data
is read from or written to these sectors by means of a READ/WRITE head.
Directory — A translation table used to specify the size and format of files
stored on the disk. Each record type and field type is identified by a data
file name.
DOS — The disk operating system consists of a disk drive, or drives, an in-
terface card that plugs into one of the eight input/output (I/O) slots in the
Apple motherboard. The DOS interface card plugs into any slot num-
bered one (1) through seven (7); slot #0 is reserved for the language card,
the Integer BASIC ROM card, or the Applesoft Language ROM CARD.
When the disks are used in any manner, a request for use is made to the
disk operating system. A software program handles the requests and is
on the master disk, or any initialized disk.
Interface — Refers to the electronic connections between the computer and
a peripheral unit such as a cathode ray tube (CRT), disk drives, modem,
or printer. The interface is commonly referred to as an interface board
that plugs into an input/output (I/O) slot. The cable from the peripheral
unit plugs into the interface board.
Motherboard — A large insulating circuit board on which component, mod-
ules, or other electronic assemblies are mounted. Interconnections
between board and components are made by welding, soldering, or other
means.
ROM — Read only memory. ROM is a fixed memory and is any type which
cannot be readily rewritten. The information in ROM is stored perma-
nently and is used repeatedly. Such storage is useful for programs such
as the disk operating system (DOS) boot program.
There are basically three configurations of the Apple computer that use
the disk operating system.
Configuration #1 — An Apple II Plus with autostart. This Apple has an
Applesoft language in read only memory (ROM) and the disk operating sys-
tem is automatically loaded when the power switch is turned to the ‘on’
position.
Configuration #2 — An Apple computer with a language card (the lan-
guage card has autostart). This type Apple has either Integer BASIC lan-
guage or Applesoft language in ROM, and reads the other language into the
language card, and boots DOS from the master disk (or a copy) when the
power switch is turned “on.” For clarity, we are going to have Integer BASIC
in ROM, and load Applesoft language into the language card. The master
disk (or copy) must be in the boot drive (slot #6, disk drive #1), and the disk
drive door must be closed when the power switch is turned “on.” When the
power is turned “on,” DOS is booted from the master disk and Applesoft
language is loaded into the language card.
SAVE AND LOAD PROGRAMS ON DISK 21
To boot (bring up) the disk operating system (DOS), the disk drive door is
opened gently, the master disk (or initialized disk) is placed in the disk drive
gently, and the disk drive door is closed gently.
Since we are dealing with the Applesoft language, the (]) prompt should
appear in front of the flashing cursor. If your computer comes up in the
Integer BASIC prompt (>), type “FP” (floating point), and press RETURN to
access Applesoft.
If you have an Apple without autostart, and the disk operating system
does not boot when the power is turned “on,” you should:
1. Open the disk drive door on boot drive — disk drive #1 (slot #6, drive
#1)
2. Place the master disk in the disk drive.
3. Close the disk drive door.
4. Type IN*6, or PR*6, and press RETURN.
While the disk operating system is booting, the red light on the disk drive
is turned “on,” and the cursor disappears from the screen. When the disk
operating system is loaded into memory, the red light on the disk drive
turns ‘off,’ and the cursor reappears on the screen.
INITIALIZE A DISK
If thisis the first time you have booted DOS from the master disk, it is im-
portant that you learn to initialize a disk for your own use. The master disk
is WRITE protected, so you cannot write to it, only read from it. A WRITE
22 APPLESOFT LANGUAGE
protected disk has no square cut out hole on the right side when you are fac-
ing the label on the disk.
To initialize a disk on a one disk drive system:
1. Take the master disk out of the disk drive.
2. Place the disk to be initialized into the disk drive.
3. Type the phrase, INIT HELLO, so it appears on the screen. (INIT is a re-
served word used to initialize a disk.)
4. Press RETURN.
To initialize a disk on a two disk drive system with the master disk in disk
drive #1 (boot drive):
1. For precaution, open the door on disk drive #1 (boot drive). Even
though the master disk is write protected, it is a good habit to open the
door on the disk drive that is not being used. Many times when you are
using DOS you will forget what you want to do. If the disk drive door is
open and you send information to the wrong disk, the DOS system will
print, I/O ERROR, on the screen. This I/O ERROR message makes you
think and realize what action should be taken to perform the correct
task.
2. Place the disk to be initialized in disk drive #2.
3. Type the phrase, INIT HELLO,D2, so it appears on the screen.
4. Press RETURN.
After RETURN is pressed, the red light on the #2 disk drive is turned “on,”
the cursor disappears from the screen, the stepper motor rotates the disk at
about 360 revolutions per minute, and the disk is initialized to thirty-five
tracks. Each track is broken into thirteen (13) sectors in DOS 3.2, and six-
teen (16) sectors in DOS 3.3.
After the disk is initialized, the red light on the disk drive is turned “off,”
and the cursor reappears on the screen.
The initialized disk has a directory which holds all the information about
programs or files that are stored on the disk. When a new program or file is
placed on the disk, the directory is updated to contain the information.
You can see what is on the disk by typing one of the following messages.
CATALOG A DISK
When you type CATALOG (CATALOG,D2) and press RETURN, the fol-
lowing information appears on the screen:
JCATALOG
DISK VOLUME 254
A 002 HELLO
|a
The “A” indicates the “HELLO” program is in the Applesoft language. The
“002” means the program takes up two (2) sectors.
FILE NAMES
In DOS the program must have a name that follows a certain pattern. A
legal file name in DOS must be from one (1) to thirty (30) characters in
length. The file name must begin with a letter from “A to Z,” followed by
any alphabetic character, anumber, or any other character except a comma
(,). A comma is the character reserved for the slot, drive, and volume op-
tions. The command takes everything preceding the comma as a file name
(even control characters).
Examples of some legal file names are:
LOOP JOHN DOE
LOOP 15 M1000
Here are some examples of illegal file names:
1001 — starts with a number.
JOHN DOE, PhD — contains a comma
A NAME LONGER THAN THIRTY CHARACTERS IS TRONCATED TO
THIRTY CHARACTERS
24 APPLESOFT LANGUAGE
and the program is listed to the screen. The LIST and EDIT functions are in
Lesson 16.
LOCK A PROGRAM
To LOCK the program named LOOP, type LOCK LOOP, and press RE-
TURN.
JLOCK LOOP
JICATALOG
DISK VOLUME 003
A 002 HELLO
*A 002 LOOP
When a CATALOG is commanded, an asterisk (*) appears to the left of
the “A.” This asterisk (*) indicates that the program LOOP is locked, and
cannot be deleted, or renamed.
JDELETE LOOP or (RENAME LOOP, LOOP1)
FILE LOCKED
26 APPLESOFT LANGUAGE
If the disk is reinitialized, the program named LOOP will be lost. Initiali-
zation destroys all data on the disk.
UNLOCK A PROGRAM
To unlock the program named LOOP, so that it can be deleted or re-
named, type UNLOCK LOOP.
JUNLOCK LOOP
JCATALOG
DISK VOLUME 003
A 002 HELLO
A 002 LOOP
When the disk is CATALOGed, the asterisk (*) has been removed, and the
program named LOOP can be deleted or renamed.
For more instructions on the DOS please refer to Apple II, The DOS
Manual, Disk Operating System, 1980, 1981, APPLE COMPUTER, INC.,
10260 Bandley Drive, Cupertino, California, 95014.
LESSON 3
Print Rules
VOCABULARY
Applesoft Ii BASIC — This is a more extended, comprehensive, and flexi-
ble language than INTEGER BASIC.
Command — Commands are executed immediately and do not require a
line number but can be used as program statements in certain cases.
Delimiters — These are the signals that tell the computer how closely the
results are to be printed, i.e., the comma and the semicolon.
Documentation — This is the total history of a program and its component
parts from inception to completion. Documentation enables another pro-
grammer to understand the program.
Format — This is the predetermined arrangement of data, the layout of the
printed document.
PRINT — This statement outputs data.
REM — This statement allows comment within the program but produces
no action in the program. In other words, “REM” reminds the program-
mer of what the program does. You can type any comment you like ina
REM statement.
Semicolon — This prevents the cursor from moving after output is com-
pleted. In other words, it inhibits the automatic repositioning of the cur-
sor.
Statement — Statements are instructions that require line numbers and tell
the computer what action to take.
DISCUSSION
The first objective of this lesson is to write a program using a PRINT state-
ment.
27
28 APPLESOFT LANGUAGE
The output is zero (O) because the computer recognizes THIS IS THE USA
as an uninitialized variable and the ending quote is ignored.
Retype line 10 again, this time spelling PRINT incorrectly, and see what
happens.
10 PUNT ‘'THIS IS THE USA”
999 END
RUN
SYNTAX ERROR IN 10
Now that you have all the errors out of your system — on to the PRINT
rules. This program was written and tested line by line so the student can
view the results produced by each program statement.
1. Anything in quotation marks is printed exactly as in the PRINT state-
ment when RUN.
10 ~=PRINT “‘THIS IS THE USA’
20 ~PRINT (this PRINT causes a line feed — a space between lines)
999 END
RUN
THIS IS THE USA
2. PRINT statements with no punctuation following the closing quote
cause the output to be printed on one line and cause the computer to
line feed (space down). Consecutive PRINT statements with no closing
punctuation cause the output to be printed vertically, one output
below the other.
30 PRINT ‘‘THIS IS THE’
40 PRINT ‘‘UNITED STATES’’
50 PRINT ‘‘OF AMERICA”
60 PRINT
RUN
THIS IS THE
UNITED STATES
OF AMERICA
3. A comma placed at the end of a print statement places the output in
separate fields on the same line. Applesoft is designed to divide each
line into 3 fields. The first field begins at column 1 and ends at column
16. The second field begins at column 17 and ends at column 33. The
third field begins at column 34 and ends at column 40.
70 PRINT ‘’THIS IS THE”’,
80 PRINT ‘’USA”’
90 PRINT
RUN
THIS IS THE USA
4. Asemicolon placed at the end of aPRINT statement causes the output
to be packed (no space).
30 APPLESOFT LANGUAGE
270 PRINT
RUN
)
10
15
300 PRINT A; B; C
RUN
51015
The same punctuation rules that apply to items enclosed in quotation
marks apply to variables.
1. No punctuation prints vertically.
2. Commas after variables print in three vertical columns.
3. Semicolons after variables pack the output leaving no space between
numbers.
The complete program and RUN follows.
5 REM — PRINT RULES
10 =PRINT ‘’THIS IS THE USA”
20 = =~PRINT
30 =~PRINT “’THIS IS THE’
40 ~PRINT “UNITED STATES”
50 =PRINT “OF AMERICA”
60 =PRINT
70 ~PRINT “‘THIS IS THE’ ,
80 PRINT “‘USA”
90 ~=—~PRINT
100 PRINT “’THIS IS THE”’ ;
110 PRINT “USA”
120 PRINT
130 PRINT “ THIS IS THE” , “USA”
140 PRINT
150 PRINT “’THIS IS THE” ; ““USA"
160 PRINT
170 PRINT “’XXTHIS IS THEX”’ ; “‘USA’’
180 PRINT
190 PRINT “‘THIS IS THE” ;
200 PRINT
210 PRINT “USA”
220 PRINT
230 A=5:B=10:C=15
240 PRINTA
250 PRINT B
260 PRINT C
32 APPLESOFT LANGUAGE
270 PRINT
280 PRINT A, B, C
290 PRINT
300 PRINT A; B; C
999 END
THIS
IS THE USA
THIS IS THE
UNITED STATES
OF AMERICA
THIS
IS THEUSA
THIS
IS THEUSA
XXTHIS
IS THEXUSA
THIS 1S THE
USA
5
10
15
3 10 15
51015
LESSON 4
HTAB, TAB, and VTAB Statements to
Format Output
VOCABULARY
CALL — This causes the execution of a machine language subroutine at a
memory location whose decimal address is specified in the call expres-
sion. CALL — 936 clears the screen. CALL — 936 causes the same results
as HOME.
Colon — The colon separates multiple statements that are on the same line.
The colon is also called the program statement separator.
HOME — This clears the screen of all data and moves the cursor to the up-
per left position within the scrolling window. Produces the same results
as CALL — 936.
HTAB — This moves the cursor from 1 to 40 spaces over on the current line
and prints data at the HTAB numeric expression. HTAB 20 prints data at
column 20 on the current line.
Program Statement Separator — This is the colon in Applesoft language
that allows multiple statements at the same line number.
TAB — This must be used in a PRINT statement and prints data one column
past the numeric expression. PRINT TAB(20) prints data at column 20 of
the current line.
VTAB — This moves the cursor to a line that is in the numeric expression.
VTAB 12 moves the cursor to row 12 on the screen. The numeric expres-
sion in VTAB can range from 1 to 24.
33
34 APPLESOFT LANGUAGE
DISCUSSION
HTAB is a function that allows the programmer to place information ona
specific vertical column on the VDM. The VDM has columns numbered
from 1 to 40.
VTAB is a function that allows the programmer to place information on a
specific horizontal row on the VDM. The VDM has 24 rows numbered from 1
to 24.
HTAB and VTAB are generally used together in the same program line
and are separated by a colon (:). The colon is used as a separator between
two or more program statements with the same line number.
TAB (26) is used only in a PRINT statement and is separated from other
statements by semicolons, and it accomplishes the same purpose as the
HTAB. |
HOME is a command that moves the cursor and the prompt to the upper
left-hand corner of the screen of all text. Call — 936 clears the screen in the
same way.
HOME and CALL — 936 are discussed because the following program
must clear the screen to see the HTAB and VTAB functions executed
properly.
10 HOME
20 VTAB 1: PRINT “A”
RUN
This clears the screen and prints “A” at VTAB 1 : HTAB 1 (see Fig. 4-1).
40 CHARACTERS
24 LINES
line of the screen, the present screen display must shift up one line to make
more room. That will cause us to lose “A” and “B” from the display, and it
will shift ““C” up one line. To avoid all that, we just tell the computer to move
the cursor up instead of down. Of course, if we weren't running this line by
itself, the next line could instruct the computer to put the cursor elsewhere.
And that’s just what we do in the next line, line 50.
50 VTAB 24: HTAB 39: PRINT “‘D”; : VTAB 10
RUN
This prints “D” at VTAB 24 : HTAB 39. Even though the screen is 40
columns wide it is not possible to print the “D” at VIAB 24 : HTAB 40 with-
out shifting the “A” and “B” characters off the screen, because, immedi-
ately after we print there and before we can do anything else, the cursor
jumps to the next line.
To clean up the program type LIST 40. Line 40 will be displayed on the
screen. Now retype the line.
40 VTAB 24: HTAB 1: PRINT “C";
That leaves out the last colon and the VTAB 10. The program still runs
properly because the “:” and VTAB 10 are not necessary with the inclusion
of line 50. (The edit function is discussed in further detail in Lesson 16.)
60 VTAB 12: HTAB 13: PRINT “E”’ ; TAB (26) ; “F”’
Line 60 causes the letter “E”’ to be printed at VTAB 12: HTAB 13. A TAB
function is used in a PRINT statement and the numerical expression is con-
tained in the parentheses. The TAB (26) expression is separated from the
PRINT by semicolons on each side. Notice that the “F’ does not have the
PRINT repeated but is enclosed in quotation marks.
Here is the program written as a unit.
10 HOME
20 VTAB 1: PRINT ‘‘A’’
30 VTAB 1: HTAB 40: PRINT ‘’B” ;
40 VTAB 24: HTAB 1: PRINT “‘C” ;
50 VTAB 24: HTAB 39: PRINT “‘D” ; : VTAB 10
60 VTAB 12: HTAB 13 : PRINT *’E’’ ; TAB (26); ‘’F’’
999 END
HERE WE GO
A BLANK LINE??
Fig. 4-2. PRINT program results. ONE MORE TIME
94 | NO BLANK LINE HERE!!!
HERE WE GO!
ONE MORE TIME!!!
WHATA DIFFERENCE!!!
36 APPLESOFT LANGUAGE
Type in and RUN the program in Fig. 4-2 to learn more about controlling
PRINT statements.
70 HOME
80 PRINT ‘‘HERE WE GO” ; TAB (40); ‘’H”
90 ~=PRINT ‘’A BLANK LINE??”’
100 PRINT : PRINT
110 PRINT ““ONE MORE TIME” ; TAB (40) ; ‘I’;
120 PRINT ““NO BLANK LINE HERE!!!’
130 PRINT ‘‘HERE WE GO!” ; : HTAB 40: PRINT ‘J’
140 PRINT ““ONE MORE TIME !” ;: HTAB 40 : PRINT ‘’K”’
150 PRINT ““WHAT A DIFFERENCE!!!”
160 END
Line 70 clears the screen.
Line 80 prints “H” in column 40 on the top line. After “H” is printed the
cursor went to the second line, first column to prepare for the next item.
Since the PRINT statement was complete, the second line was closed out.
Line 90 prints on the third line even though the second line is completely
blank. |
Line 100 leaves 2 blank lines.
Line 110 is almost a duplicate of line 80, except for the semicolon after
“Tl.” The semicolon does not close out the line.
Line 120 is printed immediately below “ONE MORE TIME” because the
line was not closed out.
Lines 130 through 150 do essentially the same things as lines 80 through
120 except the HTAB function is used instead of the TAB function. The
HTAB prints in the place where the HTAB value is assigned. HTAB 40 prints
at column 40. TAB (40) prints at column 40.
You cannot print at VTAB 24 : HTAB 40 without pushing the top line off
the screen.
You cannot print at VITAB 24 : PRINT TAB (40) without pushing the top
line off the screen.
LESSON 5
Variables
VOCABULARY
DEF FN — This allows the programmer to define functions within the pro-
gram.
Deferred Execution — This means that a line is to be executed at a later
time. BASIC statements with a line number are run in the deferred execu-
tion mode.
Immediate Execution — This means that a line is to be executed immedi-
ately. BASIC commands without a line number are run in the immediate
execution mode.
Integer — This is any whole number, its negative, or a zero. Integers never
include decimal points, unless they are being expressed as real numbers.
Literal — This is a sequence of characters enclosed in quotation marks. In
A$ = “HELLO,” A$ is a variable, HELLO is a string, and “HELLO” is a lit-
eral. See the definition of String.
Real — This is any number, including integers, that can be written with a
decimal.
Scientific Notation — This is the method of expressing numbers as a power
of ten. In scientific notation, the number 1234 is 1.234 X 10°, and the
number 0.001234 is 1.234 X 1073. Applesoft uses the symbol “E” to indi-
cate the number before the “E” is to be multiplied by ten raised to
the power indicated after the “E’. For instance, 1 X 101! is expressed by
Applesoft as 1E + 11.
eee
38 APPLESOFT LANGUAGE
DISCUSSION
A variable, according to Webster, is:
1. Something that is variable.
2. A quantity that may assume any one of a set of values.
3. A symbol representing a variable.
In Applesoft, a variable can be an alpha (alphabet) character (A through
Z), two alpha characters (AA), or an alpha and a numeric (0 through 9)
character, unless these characters are part of a word reserved specifically
for the Applesoft language.
LEGAL APPLESOFT VARIABLES — but only the first two characters are
recognized by the Applesoft language.
DOE SIM 5U3 PER
— 32767 32767
120 A% = 10
130 PRINT
140 PRINT “RESULTS ARE = "';A%
150 END
RESULTS ARE = 10
120 B% = 3.1416
130 ~=—PRINT
140 ~=—PRINT “RESULTS ARE = °';B%
150 END
RESULTS ARE = 3
RESULTS ARE = -1
Fig. 5-4. Program showing how a negative real number is truncated by the INT
function.
_ Fig. 5-5 is a program to demonstrate how the output results differ when
the area of a circle is calculated with integers or reals. A% = PI% * R%A2
(R% = 3) calculates the area of a circle using integers. The output of this
calculation is twenty-seven (27) square inches. A = PI * RA2 (R = 3) cal-
culates the area of a circle using real variables, and produces an output of
28.2744 square inches. The correct type of variable must be used to pro-
duce accurate results.
Fig 5-7 shows a program written to demonstrate how the INT (integer)
function is used to output real numbers with a specified number of deci-
mals. For example, if the variable “A” whose value is 28.2743343 is to be
rounded to two places, the rounding value is 100 (@ = 100). The formula
INT(100*A + .5)/100 is used to round to two places. The computation fol-
lows the rules of precedence. Precedence of operations is discussed in
Lesson 6.
130 P = 1000
140 Q = 100
150 R= 10
160 S = 1
170 PI = 3.1415927:RA = 3
180 A = PIl* RAA2
190 PRINT
200 PRINT “‘AREA OUTPUT AS INPUT = ";A
210 PRINT ‘‘AREA OUTPUT TO 3 PLACES = ”; INT (A * P + .5)/P
220 PRINT ‘‘AREA OUTPUT TO 2 PLACES = “"'; INT (A * Q + .5)/Q0
230 PRINT ‘‘AREA OUTPUT TO 1 PLACE = “; INT (A * R + .5)/R
240 PRINT ‘“AREA OUTPUT TO O PLACES = "; INT (A *S + .5)/S
250 PRINT ““AREA OUTPUT TRUNCATED = “; INT (A)
260 END
Fig. 5-7. INT function used to output real numbers with a specified number of
decimal places.
P=0
Pl = 3.1416:RA = 3
= Pi * RAA2
PRINT
PRINT ‘WHEN THE AREA IS DIVIDED BY ZERO AN”
PRINT ‘ERROR MESSAGE IS PRINTED’
PRINT ‘‘P = 0 THEREFORE WHEN INT(A*P +.5)/P IS”
PRINT ‘CALCULATED "’; INT (A * P + .5) / P;‘‘THE VALUE IS ZERO”:
PRINT
210 END
When the computed area is to be output to three places, the output func-
tion is written, FNA(A). The “A” outside the parentheses refers to the define
function, and the “(A)” inside the parentheses refers to the area of the circle.
The define function can be used to store formulas. In Fig. 5-10, line 150,
the formula for the area of a circle is stored in the form, DEF FNB(A) = PI *
R A 2. The value of PI was initialized in Fig. 5-10, line 130, as PI = 3.1416.
The function FNB(A) was then used in Fig. 5-10, line 170, to print out the
area of the circle each time the radius changed (FOR R = 1 TO 5). In Fig.
5-10, line 140, the define function was initialized to round a real number to
two decimal places. This rounding function, FNC(X), was used to embrace
the “AREA” function, FNB(A). To produce the area of a circle to two deci-
44 APPLESOFT LANGUAGE
mal places, FNC(FNB(A)). One function can be buried within another func-
tion to produce desired results.
130 PI = 3.1416
140 DEF FN C(X) = INT (X * 100 + .5) / 100
150 DEF FN B(A) = PI * RA2
160 FORR =17T0O5
170 PRINT ‘AREA OF A CIRCLE = "’; FN B(A)
180 NEXT R: PRINT
190 FORR =1TO5
200 PRINT ““AREA OF A CIRCLE “; FN C( FN B(A) )
210 NEXT R
220 END
determined by using the reserved word LEN. In Fig. 5-11, line 130, A$ =
“HI THERE SUE,” when LEN(AS) is used in line 170, the output shows the
number of characters in the string is twelve (12). When LEN(““SUE”) is used
in line 190, the output shows there are three (3) characters in the name
“SUE.”
130 A$ = ‘HI THERE SUE’’
140 PRINT
150 PRINT “A$ PRINT = “‘A$
160 PRINT
170 PRINT ‘NUMBER OF CHARACTERS IN THE STRING = "’; LEN (A$)
180 PRINT
190 PRINT ‘“NUMBER OF CHARACTERS IN THE NAME SUE = "; LEN ("‘SUE"’)
200 END
The Apple has an immediate execution mode that tells the number of
characters in a string and the length of a literal. After the program in Fig.
5-11 has been run, the immediate execution mode tells the length of the
string and the literal.
PRINT LEN (A$), LEN (“SUE”) (press RETURN)
12 3
In this immediate execution mode, no line number is needed.
LESSON 6
Precedence
VOCABULARY
Arithmetic Operators — These are symbols that instruct the computer to do
arithmetic operations, addition, subtraction, multiplication, division, and
exponentiation.
ASC — This is the function that converts one string character to a numeric
value. PRINT ASC (“A”) returns the American Standard Code for Informa-
tion Interchange (ASCII) value of A which is 65.
CHR$ — This is the function that converts a numeric value into one string
character. PRINT CHR$ (65) returns the character A which is the ASCII
value of 65.
Constant — This is an item of data that remains unchanged after each run.
Interactive Mode — This is a method of operation in which the user is in
direct communication with the computer and is able to obtain immediate
response to his input messages. A display where the user is allowed to
input data in response to information displayed is said to be in an inter-
active mode. Conversational mode (display) is synonymous with inter-
active mode (display).
LET — This is a replacement statement that allows the value on the right
side of the equals sign to be stored in the variable on the left side of the
equals sign. LET may be a real, an integer, or a string.
MODEM — This word is a contraction of modulator and demodulator. It
means a device that codes or decodes information to send or receive
from a remote computer over telephone lines.
47
48 APPLESOFT LANGUAGE
DISCUSSION
The order of precedence is very important in mathematic calculations.
Incorrect precedence produces incorrect answers. Correct precedence pro-
duces correct answers if all other procedures are correct. The order of prec-
edence of arithmetic operators from highest to lowest is
1. ( ) items enclosed in parentheses are operated on first — highest
priority.
2. NOT, +, -— NOT, POSITIVE, and NEGATIVE unary or monadic
operators.
3. Exponentiation.
4. Multiplication and division.
5. Addition and subtraction.
Operators listed on the same line have the same priority and are executed
starting at the left side of the formula and completed on the right side.
Integers and reals are classified as arithmetic variables. Strings are classi-
fied as nonarithmetic variables. When integers and reals are used in a
formula, the integers are converted to reals before the calculation takes
place. The final result can be converted either to an integer or left as a real.
String variables (nonarithmetic) cannot be converted directly to integers or
reals, but can be converted indirectly by other functions provided for that
purpose.
The following program converts a string variable to a numeric variable
and converts a numeric variable to a string variable.
10 A$ = “A”
20 B = ASC (A$)
30 PRINT B
40 D= 65
50 C$ = CHR$ (D)
60 PRINT C$
PRECEDENCE 49
70 END
RUN
65
A
Line 10 sets A$ = “A”. The computer uses coded numbers to represent
letters. “A” is converted to the ASCII number. Each letter, number, and
symbol on the keyboard has an ASCII number.
Line 20 B = ASC (A$) puts the ASCII number of A (65) into B.
Line 30 PRINT B produces B = 65 which is the conversion of A$ (a string)
to a real number.
ASC IS THE FONCTION THAT CONVERTS ONE STRING CHARACTER TOA
NUMBER.
Line 40 D = 65 places the ASCII value of the letter A into D.
Line 50 C$ = CHR$ (D) changes the value of D into a string character in
C8.
Line 60 PRINT C$ prints out the letter that was converted from the
numeric equivalent of (65) of the letter A.
CHR$ IS THE FUNCTION THAT CONVERTS A NUMBER INTO ONE STRING
CHARACTER.
The maximum length of a string is 255 characters.
Now for some examples of precedence.
1. Items enclosed in parentheses can either be variables or numeric
values. If the variable is not given a value — a value of zero (0) is re-
turned. The innermost set of parentheses is evaluated first.
15*(2+(3+2)*3) = 255
15*(2+ 34+2)*3 = 315
15* 2+ 3+2*3 = 39
Precedence can be modified by using parentheses as demonstrated by
the previous example.
2. The monadic or unary operator is the sign(+, —, or NOT) of the num-
ber.
+ 3+2=5 (number is positive when no sign is printed)
+3-2=1
—~3+2=-1
-3-2=-5
3. Exponentiation.
3A2 = 9
3A80 = 1.47808831 E + 38
4. Multiplication and division.
(10*5)(2*5)=5
(10*5) 2*5 =125
10*5/2*5 =125
50 APPLESOFT LANGUAGE
RUN
30 (D, no punctuation, line 70)
10 (E, no punctuation, line 70)
50 (F, no punctuation, line 70)
(line 70, PRINT skips a line)
50 (F comma) 4 (G comma) 25 (H comma)
(line 80, PRINT skips a line)
301050 ~~ (D; E; F, semicolons, line 90)
(line 90, PRINT skips a line)
5 (D = A) 10 (E = B) 20 (F = C)
Line 100 D = A replaces the existing value of D (30) with the value of A
(5). When D is printed, the replaced value 5 is printed. E = B replaces the
existing value of E (10) with the value of B (10). These values happen to
be the same, so no difference is seen. F = C replaces the existing value of F
(50) with the value of C (20).
INPUT is used to place values in the program on an interactive basis.
Type in the following lines but leave the rest of the program as it is.
6 INPUT “A = "7A
8 INPUT “’B = "';B
10 INPUT "C = ";C
RUN
A=5
B = 10
C = 20
The rest of the run is exactly the same as when the replacement statement
was used to input the values of A (5), B (10), and C (20).
Now RUN the program using any values that you choose, but do not
delete the program because the next step is to use the READ — DATA input
method.
When you are through experimenting with different numbers using the
INPQT statement type in
DEL 6, 10 (return)
This deletes the INPCT statements at lines 6, 8, and 10. Now type in:
10 READ A, B, C
120 DATA 5, 10, 20
The results of the run are the same as using a replacement statement, IN-
PUT statement, or a READ — DATA statement when the values are A = 5,
B = 10, andC = 20.
LESSON 7
Loops
VOCABULARY
Branch — This is a departure (or the act of departing) from a sequence of
program steps to another part of the program. Branching is caused by a
branch instruction that can be conditional (i.e., dependent on some previ-
ous state or condition in the program) or unconditional (i.e., always
occurring). It is also known as a transfer or jump.
Conditional Transfer — See Branch.
FOR-NEXT — This is a conditional branch instruction used to make the
computer jump to another part of the program.
GOTO — This is an unconditional branch (jump or transfer) to another part
of the program. It may be executed in the immediate or deferred mode.
Graphics — This is the art or science of drawing a representation of an ob-
ject on a two dimensional surface according to mathematical rules of
projection.
Increment — This is a fixed quantity that is added to another equivalent
quantity.
Initialization — This is a process performed at the beginning of a program
or program section or subroutine to ensure that all indicators and
constants are set to prescribed conditions and values before that sub-
routine is run.
Loop — This is a set of instructions that are performed repeatedly until
some specified condition is satisfied, whereupon a branch (jump or trans-
fer) instruction is obeyed to exit from the loop.
Nested Loops — These are loops that exist within other loops.
53
54 APPLESOFT LANGUAGE
STEP — Ina FOR-NEXT loop, STEP is that function that causes the loop to
increment by the value designated by the STEP. It may be positive or
negative.
Test — This means to examine an element of data or an indicator to ascer-
tain whether some predetermined condition is satisfied.
Unconditional Transfer — See Branch.
DISCUSSION
A loop is a series of instructions that are performed repeatedly until a
specified condition is satisfied.
Suppose a program was written to count from one to five. One variation
of the program could be
10 PRINT ‘1°"
20 PRINT ‘*2"
30 PRINT ‘'3"'
40 PRINT *’4”
50 PRINT °'5”
60 END
The program would not use the computer very efficiently; writing a pro-
gram this way to count to a thousand would take all day. A more efficient
way to use the computer would be to write a program to count from 1 to 5
by using a GOTO loop.
10 X= 1
20 = PRINT X
30 KX=X +1
40 IFX>5 THEN 60
50 GOTO 20
60 PRINT: PRINT “I’M THRU COUNTING!"
ized to one. Each time the loop is executed, the summing statement adds
one to the initialized value of the variable. In this case, when the summing
statement is equal to five, the program (at line 40) jumps out of the loop and
executes line 60.
Line 40 is a testing step, a conditional branch or transfer that says, IF the
loop has executed five times THEN jump out of the loop to line 60 in the
program.
Line 50 is an unconditional branch or transfer that makes the computer
go back to line 20.
When the loop has been executed five times and X > 5, line 40 checks that
X > 5 and THEN causes a branch to line 60 to print “TM THRU COUNTING!”
and the program ends.
The FOR-NEXT loop program to count from one to five follows.
10 FORX=1TO5 (replacement statement)
20 PRINT X
30 NEXT X
40 PRINT: PRINT “I'M THRU COUNTING!”’
999 END
RUN
1
2
3
4
5
I'M THRU COUNTING!
This is how the GOTO loop and the FOR—NEXT loop look when they are
placed side by side.
GOTO loop FOR - NEXT loop
10 X= 1 10 FORX=1TOS5
20 PRINT X 20 PRINT X
30 X=X +1 30 NEXT X
40 IF X>5 THEN 60 40 —~PRINT : PRINT “I’M THRU
COUNTING!”’
50 GOTO 20 999 END
60 PRINT: PRINT ‘I'M THRU
COUNTING!”’
END
The FOR-NEXT loop program is shorter and more efficient than the
GOTO loop program. The GOTO loop is used in cases where the number of
times of loop execution is not known beforehand. This will be explained
more clearly when the GOTO loop is used with the decision statement in
Lesson 8.
The FOR-NEXT loop is used when the number of times of loop execution
is known. The FOR-NEXT loop can use loop variables to determine the
number of times that the loop is to be executed. In FOR X = 1 TO 5, the
56 APPLESOFT LANGUAGE
number of times the loop will be executed is 5. In FOR X = 1 TON, the vari-
able “‘N’ determines the number of times the loop will be executed.
In the same FOR-NEXT loop program type in these lines.
5 INPUT ‘*COUNT TO #: ; N
10 FORX =1TON
RUN
COUNT TO #: 3
1
2
3
I'M THRU COUNTING!
Line 5 allows the user to input the highest number in the count.
Line 10 causes X to start at the number “1”, and go to “N’, the highest
number to be counted. In this case, X = 1 TO 3.
Now type these lines in the same program.
5 READN
60 DATA 3
RUN
1
2
3
I'M THRU COUNTING!
40 FORB = 2 TO 6STEP 2
50 HTAB (B — 1)*3 + 1: PRINT B;
60 NEXT B: PRINT
RUN
2 4 6
Line 40 starts with a value of 2, to change the learning experience. STEP 2
causes the loop to be incremented by 2 numbers on each execution. The
STEP can be any necessary value, positive or negative, to achieve the solu-
tion to the problem.
Lines 50 and 60 are similar to lines 20 and 30.
The next section of the program uses the loop to print the numbers back-
ward.
70 FORC = 6TO 1 STEP -1
80 HTAB (6 - C)*3 + 1: PRINT C;
90 NEXT C
100 PRINT
The first PRINT in line 130 closes out the line and the second PRINT causes
the program to skip a line between the previous section and the next section
of the program printout.
58 APPLESOFT LANGUAGE
A=7:B=8:C=0:D=0
The output from line 140 shows the next value of the variable after the
loop has completed its executions. In loop A, the values go from 1 to 6, but
the loop makes 7 the final value of A. In loop B, the values go from 2 to 6,
but the loop makes 8 the final value of B. In loop C, the values go from 6 to
1, but the loop makes 0 the final value of C. In loop D, the values go from 6
to 2, but the loop makes 0 the final value of D. This is a very important fact. It
is important to keep track of these final values because they can produce
incorrect results if the variables are used again and are not initialized. This
fact will be detailed in the CASH FLOW program in Lesson 27.
The complete program and RUN follow
30 =NEXT A: PRINT
40 FORB = 2TO6 STEP 2
50 HTAB (B —- 1) * 3 + 1: PRINT B
60 NEXT B: PRINT
70 FORC = 61701 STEP — 1
80 HTAB (6 — C) * 3 + 1: PRINT C
f
90 NEXTC
100 PRINT
110 FORD = 6TO2 STEP — 2
120 HTAB (6 — D) * 3 + 1: PRINT
D;
130 NEXT D: PRINT : PRINT
140 PRINT “A = "SA;":B = “5B;"':C
=/o"':Dp =":D
LOOPS 59
JRUN
1 2 3 4 5 6
2 4 6
6 5 4 3 2 1
6 4 2
A = 7:B = 8:C
= 0:D =0
Nested loops are a loop within a loop or loops within a loop. In Applesoft,
loops can be nested 10 deep.
10 FORS = 1T03
20 FORT = 110 5]
30 PRINTT: '’ ': INNER LOOP OUTER LOOP
40 NEXT T: PRINT —————_$—$—$—$—_____—
50 NEXTS
60 END
Line 20 sets the inner loop to execute 5 times. Line 30 causes the inner
loop to print out the value of T on each execution and the quotation marks
cause one space to be placed between each of the values in the printout. If
two spaces were left between the quotation marks, there would have been
two spaces created between the values as they were printed. This gives a
second method of spacing in a loop. The first method demonstrated was
with the HTAB.
Line 10 and line 50 cause the outer loop to execute three times.
Loops must never be crossed or the program will not execute. Reverse
lines 40 and 50 and observe what happens to the program.
10 FORS =1TO3
20 FORT =1TO5 : .
30 PRINT T; " "; CROSSED LOOP CROSSED LOOP
40 NEXT S: PRINT ————————— |
50 NEXT T
60 END
RUN
1 1 1
?NEXT WITHOUT FOR ERROR IN 50
Nested loops give the computer more power in computations and simpler
more efficient programming for the programmer. They are very useful in
graphics.
The following program uses nested loops and a graphic print to produce
the triangle shown in Fig. 7-1.
60 APPLESOFT LANGUAGE
10 FORS = 1T0 10
20 HTAB (19 — S)
30 FORT=1TOS
40 PRINT ‘'*";
50 NEXTT: PRINT
60 NEXTS
70 END
KKK
KKKK
kKkKKKK
KREKEKEK
KKKKKRKK
REKKKKKEK
KKKKKKEKKEE
KEKKKKRKKKK
VOCABULARY
Bug — This is a mistake or malfunction in a computer program.
Debug — This means to remove a mistake, or mistakes, from a computer
program or system.
Decision — This is an operation performed by a computer that enables it to
choose between alternative courses of action. A decision is usually made
by comparing the relative magnitude of two specified operands. A
branch instruction is used to select the required path according to the re-
sults.
Default — The rule of default states that a computer program runs sequen-
tially according to increasing line numbers unless a branch is executed.
Logical Operator — This is a word or symbol to be applied to two or more
operands (AND, OR, and NOT are logical operators).
Relational Operator — This is a method of comparing quantities to make
decisions.
DISCUSSION
Program statements have line numbers so the program can run sequen-
tially from the lowest line number to the highest. The program runs sequen-
tially until a program statement containing a relational or logical operator
is reached. The program then must weigh the decision. If the decision is
true (1 or YES), then the program branches to a line number out of se-
quence. If the decision is false (0 or NO), then the program continues in its
sequential run. The program ‘falls through’ or defaults to the next line
number. The rule of default states that unless a branch is executed, the
61
62 APPLESOFT LANGUAGE
statement with the next highest number is executed. With the computer
there are only two decision choices, true or false. There can be no other
answer to the decision.
The following relational operators compare two quantities. Based on the
result of the comparison, the computer can make a decision.
NOT. This is the logical negation of an expression.
l. = Left expression ‘equals’ right expression (in this case, equals is
not a replacement statement).
2. <> Left expression ‘does not equal” right expression.
3. > Left expression ‘is greater than’ right expression.
4.< Left expression “is less than” right expression.
5. >= Left expression “is greater than or equal to’ right expression.
6. <= _ Left expression “is less than or equal to” right expression. NOT
is a replacement symbol in an IF-THEN statement.
Relational operators are related to logical operators.
1. NOT. This is the logical negation of an expression.
2. AND-IF A>B and C>D THEN 999.
Expression A>B AND expression C>D must be true for the statement
to be true.
3. OR-IF A>B OR C>D THEN 999.
If either expression A>B OR C>D is true, then the expression is true.
AGE = 36
OPERATORS LICENSE
AGE = 18
JUNIOR OPERATORS LICENSE
AGE = 15
NO OPERATORS LICENSE
AGE = 0
] @
The program RUNs as planned. When age is input, the output shows the
eligibility of the applicant. The first program revision counts the number of
applicants. Change the program by typing in the following line numbers and
program statements.
40 NA = 0 (initialize summing variable to zero)
70 NA = NA + 1 (counting statement)
190 PRINT ““TOTAL APPLICANTS”
210 PRINT NA
RUN
AGE = 25
OPERATORS LICENSE
AGE = 0
TOTAL APPLICANTS
1
64 APPLESOFT LANGUAGE
The two program revisions complete the program and solve the problem
of totaling the number of applicants and total the applicants by age.
The program section pertaining to applicants UNDER 18 is
80 IF AGE < 18 THEN 130
130 UNDER,18 = UNDER 18 + 1
140 PRINT ‘‘NO OPERATORS LICENSE”
150 GOTO 50
The program section pertaining to those applicants who are 18 is
90 IF AGE = 18 THEN 160
160 1818 = 1S 18 + 1
170 PRINT ‘JUNIOR OPERATORS LICENSE”
180 GOTO 50
The program section dealing with those applicants OVER 18 is
90 ~=IF AGE = 18 THEN 160 (if the AGE is OVER 18 the statement is FALSE
and the program defaults to line 100)
100 OVER 18 = OVER 18 + 1
110 PRINT ‘“OPERATORS LICENSE”’
120 GOTO 50
Finally, the program section that deals with line 60:
60 IF AGE < = 0 THEN 190
190 PRINT **TOTAL NUMBER UNDER 18 IS 18 OVER 18”
200 PRINT
210 HTAB 5: PRINT NA; TAB (16); UNDER 18; TAB (25);
IS 18; TAB (33); OVER 18
220 END
In the operator’s eligibility program there are 3 age classifications,
CINDER 18, IS 18, and OVER 18. There are, however, only two decision
statements to select the 3 age categories. Line 60 does not select an age
category.
80 =IF AGE < 18 THEN 130
90 IF AGE = 18 THEN 160
As shown above, line 80 selects applicants UNDER 18. If line 80 is TRUE
it branches to line 130. If line 80 is FALSE the program defaults to line 90.
10 REM * PROGRAM TO DETERMINE
20 ~=REM * LICENSE ELIGIBILITY AND
30 REM * COUNT THE NUMBER OF APPLICANTS
40 NA = 0: UNDER 18 = 0:18 18 = 0: OVER 18 = 0
50 INPUT “AGE = "; AGE
60 IF AGE< = 0 THEN 190
70 NA =NA +1
80 IF AGE < 18 THEN 130
90 IF AGE = 18 THEN 160
100 OVER 18 = OVER 18 + 1
110 PRINT ‘‘OPERATORS LICENSE”
120 GOTO 50
66 APPLESOFT LANGUAGE
VOCABULARY
Hardware — This is the name for all of the physical units of a computer sys-
tem. Hardware is made up of the apparatus rather than the programs.
Logic Flowchart — This is a chart representing a system of logical elements
and their relationship within the overall design of the system or hardware
unit. It is the representation of the various logical steps in any program or
routine by means of a standard set of symbols. A flowchart is produced
before detailed coding for the solution of a particular problem.
Software — In its most general form, software refers to all programs that
can be used on a particular computer system.
DISCUSSION
When you write a computer program, you solve a problem. The most
basic approach to solving a problem is to first understand the problem. In
the program to compute the area of a circle, the formula was discussed and
thought out in high school math. The knowledge simplifies the program-
ming of the output. A program to compute and compare three types of de-
preciation somewhat changes the problem. The first problem in program-
ming is to understand the problem and its ramifications.
Once the problem is understood, the solution must be placed in the
proper order. The exact output format must be known. The precise formulas
to output the correct answers must be used. The exact language that the
computer understands must be programmed in the proper order, and the
idiosyncracies and normal operations of the machine must be understood.
The computer can only output according to specific input. The excuse is
67
68 APPLESOFT LANGUAGE
often heard, “It’s the computer’s fault.”” Computers seldom (if ever) make
errors, it’s the human input that is in error. Computers are stupid but exact-
ing. Many programmers pray for a program statement DWIT (do what |
think). The DWIT statement is not yet available in Applesoft, so we'll do the
best we can with what we have. Remember, the computer does exactly what
you tell it to do, nothing more, nothing less.
Once the problem, the language, and the computer are understood, all
other problems are relatively simple. The program can now be written to
solve the problem.
The output must be tested for correct results with as many different in-
puts as possible. Simple inputs may produce correct outputs, but are there
cases where the outputs are incorrect? The program should be tested and
debugged to produce the correct output under all circumstances. What if
the program to put a man on the moon had bugs in it?
Has the program been documented with REM statements and other
written records so another person could RUN the program and understand
the output? Have the variables been recorded so the computational
formulas can be easily understood? Has the program been properly indexed
so it can be easily located in the library? The answers to all these questions
should be yes. It is easy to forget what problem a program solves, what the
variables represent, and where the program can be located.
Flowcharting, or logic flowcharting, is a techique for representing in
symbolic form a succession of events. Flowcharting is the first step in
logical program development. It aids in thinking the program through, from
the problem to the computer stage.
In data processing, flowcharts may be divided into two types, system
flowcharts and program flowcharts.
System flowcharts, using symbols, show the logical relationship between
successive events using hardware. Such symbols include data input (on, for
example, magnetic tape, disks, and punched cards) and data output
(through, for instance, printers, magnetic tape, or disk).
SYSTEM SYMBOLS
Program flowcharts show diagrammatically the logical relationship be-
tween successive steps in the program. For most complicated programs, an
outline flowchart precedes a detailed flowchart before the program is
written.
The purposes of an outline or initial flowchart are to show:
1. All input and output functions.
2. How input and output are to be processed.
3. How the program will be divided into routines and subroutines.
PROBLEM SOLVING AND FLOWCHARTS 69
SYSTEM SYMBOLS
=
PUNCHED TAPE
LC)
MAGNETIC DRUM
©
MAGNETIC TAPE
JI TI
MANUAL INPUT DOCUMENT PUNCHED CARD
START
REM
INITIALIZE
VARIABLES
OEE
NA=NA
NO
+ 1
YES
PRINT
PRINT
PRINT
END
NO
YES 7 PRINT JR
Sia: { OPERATORS
LICENSE
NO
OVER 18 +1
PRINT
OPERATORS
LICENSE
30 FOR X = 0
40 PRINT X
Fig. 9-2. Sums of the integers 1
through 5 using a FOR-NEXT loop.
50 SUM = SUM + X
60 NEXT X
10 X=0
20 SUM
= 0
30 PRINT X
40 IFX =9
PRINT
SUM =;SUM
90 X = X+1 THEN 80
60 SUM = SUM + X
70 GOTO 30
80 PRINT ‘‘SUM = "’; SUM
99 END
DISCUSSION
This lesson deals with how to program more efficiently and how to make
the program run faster. Efficiency and speed may be well and good, but for
the average computer hobbyist speed is not that important. The important
thing is to enjoy the hobby and write programs that are readable and can be
deciphered six months from now. Place REM statements within the pro-
gram that will help you understand and remember what that variable repre-
sented. Did that single “R” variable stand for RUTH or RAIN? These points
are very important if the program is to be reused at a later date. A couple of
microseconds lost here and there isn't going to change the world. Write un-
derstandable programs. Write programs that jog your memory when you
pick them out of your library four months from now. The variable SUM
(even though Applesoft recognizes only the ist two letters) means some-
thing. The variable “S’’, now what did that stand for? Now back to speed and
efficiency.
There are three pairs of opposites that are used to reverse the logic of the
IF — THEN statement.
age 18, the statement is AGE < = 18. If the over 18 group is to include the
18 year olds, the statement is written AGE > = 18.
AGE less than 18 = AGE< 18
AGE less than 18 but
includes the 18 year
old group = AGE< = 18
AGE greater than 18 = AGE > 18
AGE greater than 18 but
includes the 18 year
old group = AGE > = 18
AGE is 18 = AGE = 18
AGE is not 18 = AGE <> 18
Decision statements (IF-THEN) operate on a TRUE (1 or YES) or FALSE
(O or NO) basis and are flowcharted as shown in Fig. 10-1.
IS
CONDITION Fig. 10-1. Decision statement flowchart.
TRUE
?
NO
VOCABULARY
Counting Variable — This is a variable used to count within a loop, e.g.,
C = C + 1. The variable is incremented by 1 on each loop execution.
Flag — This is an additional piece of information added to a data item which
gives information about the data itself. An error flag indicates that the
data item has given rise to an error condition.
Illegal Value — In Applesoft, this means using a reserved word for a vari-
able, e.g., using TO as a variable when it is a reserved word.
Legal Value — In Applesoft, this means using a variable that meets the re-
quirements of the language, e.g., X = 5.
Summing Variable — This is a variable used within a loop to sum the values
of the loop variable, e.g., FOR X = 1TO5. The summing statement SUM
= SUM + X sums the value of X.
DISCUSSION
Counting variables are used to count some function within the program
and are generally initialized to zero. The increment is one if each execution
of the loop is to be counted. C = C + 1 is the statement used to increment
the count by one and store the count in variable location “C”.
Summing, also known as totaling, variables are used to sum or total
within a loop. If “T” is the totaling variable, then T is usually initialized to
zero, the value at the beginning of the operation. A program that totals daily
and adds the daily total to the previous day’s total would not be initialized to
zero, but to the previous day's total. If the variable is “X’’, then the totaling
7/
78 APPLESOFT LANGUAGE
COUNT = 5
TOTAL = 15
Note that the counting and totaling statements are within the body of the
loop and the count and total change with every execution of the loop. When
the loop has completed its last execution, the computer prints out the total
count (line 70), prints out the total value of the variable T (line 80), and the
program ends.
A flag is a value stored in a variable. Flags are signals to the computer
used to start some programmed function. In the following program the flag
has a legal value of zero (0), one (1), or minus one(- 1). Flag = O causes the
program to print “* of adds’, “* of subtracts’, final total, and the program
ends. Flag = 1 causes a jump to the section of the program to input a
number to add. Flag = — 1 causes the program to jump to a section of the
program to input a number to be subtracted. After each addition and sub-
traction there is a GOTO 20 statement that is an unconditional jump to input
another flag value.
If an illegal value (any item other than O, 1 or — 1) is typed in the INPUT
(20 for instance) the program defaults to line 70. When Flag = 20, the deci-
sion in line 40 is false, and the program defaults to line 50. In line 50, the
decision is also false and the program defaults to line 60. The same thing
SUMMING, COUNTING, AND FLAGS 79
happens in line 60 and the program defaults to line 70. Line 70, GOTO 20, is
an unconditional jump to line 20 to input another flag value.
The variables used in the program are:
CA = count to be added. CS = count to be subtracted.
N = number F = flag
T =total
10 CA=0:CS =0:T=0
20 =~PRINT “’ENTER FLAG VALUE (0 TO QUIT : 1 TO ADD NUMBER :
—1TO SUBTRACT NUMBER)’’
30 ~=INPUT °’?”' ;F
40 IF F = 0 THEN 140
50 IFF = 1 THEN 80
60 JIFF= —1 THEN 110
70 GOTO 20
80 INPUT ‘‘NUMBER TO BE ADDED ”; N
90 CA=CA+1:T=T+N
100 GOTO 20
110 INPUT ‘“‘NUMBER TO BE SUBTRACTED “'; N
120 CS=CGS+1:T=T-N
130 GOTO 20
140 PRINT: PRINT “# OF ADDS = “; CA
150 PRINT : PRINT ““# OF SUBTRACTS = "’; CS
160 PRINT: PRINT “‘FINAL TOTAL = “’; T
170 END
RUN
ENTER FLAG VALUE (0 TO QUIT : 1 TO ADD NUMBER: —1 TO
SUBTRACT NUMBER)
? 1
NUMBER TO BE ADDED 34
ENTER FLAG VALUE (ALL OF LINE 20)
?-1
NUMBER TO BE SUBTRACTED 18
?0
# OF ADDS = 1
# OF SUBTRACTS = 1
FINAL TOTAL = 16
Line 10 initializes the variables to zero. Line 20 prints out the flag values
that control a specific part of the program. F = O outputs and ends the pro-
gram. F = 1 adds a number that has been input and keeps a total. F = — 1
subtracts a number that has been input and keeps a total. Line 30 allows the
user to input the flag value. The flowchart for the FLAG PROGRAM is shown
in Fig. 11-1.
GOTO lines in Fig. 11-1 are represented by lines from one symbol to
another but are not named on the flowchart. Unless F = O, all GOTO lines
return to input another flag value.
Lines 140, 150, and 160 print out the results and the program ends at line
170.
80 APPLESOFT LANGUAGE
10
PRINT
INSTRUCTION
VOCABULARY
Array (subscripted variable) — This is an arrangement of items of data, each
identified by a key or subscript. It is constructed in such a manner that a
program can examine the array in order to extract data relevant to a
particular key or subscript. The dimension of an array is the number of
subscripts necessary to identify an item. Reservations based on the day
of the month would need a( DIM R (31) ) subscripted variable R (D), while
reservations based on the day and the month would need a ( DIM R
(31,12) ) doubly subscripted variable R (D, M).
DIM — The DIM statement reserves memory locations for numeric or string
arrays, such as A$ (14), B(5), and C% (12). DIM A (15) reserves 16 strings
of 255 characters in length, starting from zero. DIM A (N) sets aside N +
1 number of arrays up to 255 characters in length. The DIM A (N) must be
placed in the program after N has been input. The DIM A (N) must not be
placed in a loop, except under very special conditions.
List — This is any printing operation in which a series of records on a file,
or in memory, are printed one after another.
Operate — This is a defined action by which a result is obtained from an
operand.
81
82 APPLESOFT LANGUAGE
DISCUSSION
Lesson 12 introduces a new type of variable, the subscripted variable for
numeric lists, or array.
SUBSCRIPTED VARIABLE
C(A) C(1)
SIMPLE VARIABLES CA X9 CX4 G3H
SUBSCRIPTED VARIABLES C(A) X(9) CX(4) G3(H)
The variables A, A(O), AB, and A(B) can all be used in the same program
successfully. A subscripted variable, like a simple variable, reserves a
memory location with a label and contents.
Table 12-1 shows five subscripted variables with the memory locations
labeled C(A) with no values in the locations.
L(1) P
L(2) O
M(3) R
M(4) S
L(1) = L(P) =
L(2) = O(R) =
M(R) = N(Q) =
M(S) = N(P) =
2 1 2
5 2 1
7 3 3
_9 —? 6
A DIM statement is necessary to reserve memory locations for a numeric
array. The array range goes from zero to the number dimensioned. DIM
A(15) reserves 16 elements for array A (0 to 15). Each element may be up to
255 characters in length. An array can be up to 11 (0 to 10) elements large
without a DIM statement.
Integer arrays A%(N) will not be presented separately because they are
handled in a manner similar to real arrays A(N).
In the following program there are only three numbers in the numeric list
so a DIM statement is not necessary. However, a DIM statement is used any-
way as a teaching example. A DIM statement should always be used in pro-
grams with subscripted variables to reserve specific memory locations.
The program allows the user to input N numbers into a list. The list of
numbers is printed as input, printed backwards, operated on, and totaled.
90 HOME: VTAB 3
100 REM: ARRAYS — SINGLE SUBSCRIPTED
110 REM : VARIABLES — USED FOR LISTS
120 REM : 4 WAYS TO USE THEM
130 REM: INPUT 4 NUMBERS
140 INPUT ““HOW MANY NUMBERS = ";N
150 DIM L(N)
160 FOR X = 1TON: L(X) = 0: NEXT X
170 FORK =1TON
180 PRINT ‘’“NUMBER"’;K; =";J
84 APPLESOFT LANGUAGE
4-52.5
2.5 - 5 4
In line 180, the K variable is placed between the ‘‘NUMBER” and the “’="’
to inform the user which of the numbers in the list is to be input. The K in
the PRINT statement begins as number 1 and increments by 1 with each
execution of the loop.
Lines 210 to 240 set up the list to be printed out as it is input. The loop is
used and the loop variable is A, so the subscripted variable is L(A).
210 PRINT ‘PRINT THE LIST AS INPUT’ : PRINT
220 FORA=1TON
230 PRINT L(A); “ ";
240 NEXT A: PRINT : PRINT
Line 230 prints the numbers in the list by placing them in the subscripted
variable ( L(1) = 4) and printing one number on each loop execution. The
represents 2 spaces enclosed in quotation marks. The “” causes two
66 09
spaces to be left between each printed number each time the loop executes.
Line 240 closes out the loop, and the first PRINT closes out the line after
all the numbers in the list have been printed. The second PRINT statement
leaves a blank line between program sections in the printout.
Lines 250 to 280 print out the list backward.
86 APPLESOFT LANGUAGE
STORE statement would reset the data and make it available for further pro-
gram executions.
Line 180 prints out the number of numbers in the list after it had been
READ from DATA.
Lines 190 and 200 are a loop that READS the list of numbers through the
subscripted variable L(K).
190 FORK = 1TON
200 READ L(K) : NEXT K
When the last number in the list is READ, the program defaults to line
210 to print out the list as it was READ.
Line 400 DATA 3(N), 4(K), — 5(K), 2.5(K) sets up the data to be READ in
the proper order.
READ statements may contain integer, real, and string variables. To be
read properly the READ variables must be aligned with the items in the
DATA statement.
10 READ A%, A, A$
20 DATA 4, 1.7, HELLO ( or ‘“HELLO’’)
A$ will print out HELLO or “HELLO” in either form as HELLO.
10 READ A%, A, A$, B$
20 PRINT A%, A, A$, B$
30 DATA 4.5, 2.5, HELLO, ‘’BYE”’
RUN
4 (input as a real but truncated to an integer)
4 2.5 HELLO
BYE
A string variable in a READ statement will READ a literal or a string ina
DATA statement but outputs only in the literal form.
LESSON 13
Double Subscripted Variables
DISCUSSION
Double subscripted arrays are arrays that have two subscripts. Double
subscripted arrays are used for outputting data or information in table form.
The following are examples of double subscripted arrays:
CF(1,4) X(0,0) JANE(R,C) FOB(L,S)
Tables and arrays have rows and columns. Columns are positioned verti-
cally on the screen. Rows are positioned horizontally on the screen. Fig.
13-1 shows how an array of three columns and three rows is arranged.
CF = array name
R = row subscript
C = column subscript
: )
89
90 APPLESOFT LANGUAGE
30 CF(C,1) = GI
40 CF(C,2) = EX
Whole columns or rows in an array can be added or subtracted the same
as ordinary variables. As a matter of fact, any arithmetic operator that can
be used on ordinary variables can be used on arrays. In the following exam-
ple, column 2 is being subtracted from column 1 to produce column 3 in
array CF.
CF(C,3) = CF(C,1) — CF(C,2)
Variables, single subscripted arrays, and double subscripted arrays can
be handled in a similar fashion.
The program written for this lesson is a very elementary business pro-
gram. The user inputs the amount of his gross income, expenses, and years
(months or days) to operate. From these three inputs is output the period of
operation, in this case years, the gross income, expenses, net income, and
the totals for each column.
A FOR-NEXT loop is used to compute and print the figures on a yearly
basis. After the yearly figures are output, double nested loops are used to
output the totals of each column.
Some large computers have the capacity to handle arrays with up to 16
subscripts. In the automobile industry, each style of automobile could have
15 items of optional equipment. The subscripted variable might look like
this.
From the subscripted variable, the manufacturer could keep track of what
is produced. The reports could then break down sales percentages into the
most popular models and options. This information could be fed back to the
computer to aid the production department to produce the cars the public
was buying.
Now back to our elementary program.
DOUBLE SUBSCRIPTED VARIABLES 91
Lines 100 and 110 are used to partially document the teaching objective
of the program, namely double subscripted variables.
Line 120 HOME clears the screen and prints on line 2 of the screen,
DOUBLE SUBSCRIPTED VARIABLES.
Line 130 places the string into H1$ for ease of output. This is especially
valuable if the same heading is to be printed many times during the pro-
gram.
Line 140 tabs to line 4 on the screen and prints out the heading.
Lines 150 and 160 ask for input below the subject in the heading, thereby
cluing the user as to what input is requested. In Applesoft, the statement
INPUT GI could be used, but it leaves a question mark on the screen in front
of the data. INPUT “ ”’; GI is used because it leaves no question mark on the
screen in front of the data.
The DIMension statement of line 170 would not be necessary if fewer than
11 array elements were needed, since Applesoft automatically sets aside up
to 10 array element memory locations. The DIM statement that we use
allows a variable number of rows (CF(YRS,3) ) to be allocated. If we knew
that the number of rows needed would never be more than five, we could
have written line 170: DIM CF (4,3). This version allocates 4 + 1 rows and
3 + 1 columns, or 20 real number elements to the array (don't forget that
the computer uses zero as a counting number, so that when you tell it four,
the computer counts five places including zero).
Lines 180 to 210 initialize the locations in the table to zero.
180 FORR = 1 TO YRS
190 FORC =1T03
200 CF(R,C) = 0
210 NEXT C,R
The double nested loop is the most efficient method to initialize the loca-
tions in the table to zero. The table locations could have been initialized by
listing every element in the array and setting them equal to zero.
CF(1,1) = 0
CF(3,3) = 0, etc.
Or a FOR-NEXT loop could have been used.
FORC
= 1TO3
DOUBLE SUBSCRIPTED VARIABLES 93
CF(4,C) = 0
NEXT C
Line 220 is the header to be printed before the output of data. The header
must be printed before the loop executes. If the header is within the loop, it
will be printed each time the loop is executed.
Line 230 prints out the header. There is no VTAB statement because the
table is printed below the input information. Two blank lines separate the
input information from the output data. The two PRINT statements in line
160 cause the two blank lines below the input.
In line 240, the number of years on which to compute the table was input.
In line 250, CF(C,1) = GI is a replacement statement that stores the input
variable on the left side of the equals sign into CF(C, 1), the column that is to
hold the yearly gross income. CF(C,2) = EX is a replacement statement to
place the expenses into the cash flow CF(C,2) column.
Line 260 is a replacement statement that sets up the third column of the
table. The column (C,3) is to hold the net income, which is the gross income
(C,1) less the expenses (C,2).
Line 2/0 places the results of each execution of the loop in the proper
location under the header. The CF(C,1) is used directly in the PRINT state-
ment to print out the results of that column.
Line 280 totals the number of years in the period. NEXT C is the ending
statement of the loop.
Lines 290 through 320 compute the totals for each column by using
double nested loops.
290 FORR = 1 TO YRS
300 FORC =1TO3
310 CF(O,C) = CF(O,C) + CF(R,C)
The elements (0,1), (0,2), and (0,3) have not been used in this table yet,
but are available in the dimension arrangement. The locations (0,1), (0,2),
and (0,3) are used to place the totals of (C,1), (C,2), and (C,3), respectively.
Line 310 inside the double nested loops is the totaling statement that totals
each of the columns.
Line 320 is the ending statement of the double nested loops.
Line 330 draws a line under the columns and the totals are placed below
the lines.
Line 340 prints the totals in the proper positions below the lines. Notice
that some of the semicolons between the TAB statements and the PRINT
statements are missing. Applesoft is flexible enough to accept the instruc-
tions without semicolons and still operate properly.
Line 350 ends the program.
LESSON 14
String Arrays
VOCABULARY
Concatenate — This means to link together in a set, series, or chain.
GOSUB — This is a string which contains no characters. Strings are initial-
ized with zero characters. A$ = “” isanull string anda PRINT A$ will not
print any characters on the screen, nor will the cursor advance on the
screen.
ON ERR GOTO 430, 440, etc. — This is a statement that causes an uncon-
ditional GOTO branch when a particular error is encountered. Error #1
jumps to line 430, error #2 jumps to line 440, etc. The equivalent state-
ment for a GOSUB branch is ON ERR GOSUB 430, 440, etc.
String Array — This is a complex variable used to manipulate all or part of
a string.
Subroutine — This is a discrete part of a program that performs a logical
section of the overall function of the program and that is available when-
ever the particular set of instructions is required. The instructions form-
ing the subroutine do not need to be repeated every time they are
needed, but can be entered by means of a branch from the main program.
Subroutines may be written for a specific program or they may be written
in general form to perform operations common to several programs. In
Applesoft, the statements GOSUB or ON (ERR) GOSQB direct the pro-
gram to the subroutines. The last line of a subroutine is a RETURN state-
ment, that jumps to the line in the main program directly below the
95
96 APPLESOFT LANGUAGE
GOSQUB (or ON (ERR) GOSUB). Subroutines can be called from the main
body of the program or from other subroutines. GOSUBs can be nested
25 levels deep in Applesoft.
DISCUSSION
String variables were introduced in Lesson 4 with the other simple vari-
ables, integers and reals. The complex variables, integer arrays and real
arrays were discussed in Lessons 12 and 13.
The complex variable (also known as the string array, or string sub-
scripted variable) is a variable with a subscript. The string array is used to
output alphanumeric information, such as lists of names and addresses.
A$ = a string variable.
HI SCE = a literal.
“HI SUE” = a literal enclosed in quotation marks (a string).
LEFTS(A$,J) = string function having 2 arguments.
RIGHT S$(A$,J) = string function having 2 arguments.
MIDS(A$,J,1) = string function having 3 arguments.
In a string array, a dollar sign ($) follows the name of the array. The Apple-
soft language uses three functions to retrieve all or part of a string, or to
print all or part of a string. A function is that part of a computer instruction
that specifies the operation to be performed. An argument is a variable fac-
tor, the value of which determines the value of the function. The three func-
tions used to manipulate strings are LEFT$, MIDS, and RIGHTS.
When string arrays are manipulated as single entities they are handled in
this manner.
LEFT$(A$,2)
MID$(A$, 1,2)
LEFT$(A$,2) = MID$(A$,1,2)
RIGHT$(A$,3)
LEFT$(A$,J)
function |
A string prints string from right to left, i.e., back-
wards.
98 APPLESOFT LANGUAGE
S PRINT MID$(A$,J,2)
10 A$ = “HI SUE”
20 BS = A$ +" + “AND JIM”
30 ~=PRINT A$
40 __—sCOPRINT B$
50 C$ = LEFT$(A$,3) + RIGHT$(B$,3) + ‘"HIN’
60 PRINT C$
999 END (3 includes the space after Hi — if 2 was used the output
RUN would be HUJIMI!!!)
HI SUE
HI SUE AND JIM
HI JIMI!
The balance of this lesson is on program development. The objective is to
produce a program that accepts a person's name and address for the pur-
pose of compiling and printing a mailing list. The program has error check-
ing to notify the input operator if the input is incorrect. Once the input is
correct the name and address is output in the proper format.
A correct program is not usually written on the first attempt. In this
example, an unusable program is written as a first attempt. The program is
then revised. The lesson presents an outline for program development and
shows some of the steps you should follow when writing usable programs.
The original program is inflexible. A$ holds the name and address of the
individual. If an individual with another name and address was placed in AS,
the output is not formatted correctly. As an extra, the program demon-
strates the use of MID$ to replace LEFT$, and RIGHTS.
15 REM: NEXT PROGRAM CHANGE — INPUT A$ AT LINE 20
20 A$ = “JOHN DOE 2200 MAIN ST. ANYTOWN USA 00000’
30 ~=PRINT A$
40 PRINT LEFT$(A$,8)
50 PRINT MID$(A$,10,13)
60 PRINT RIGHT$(A$,18) : PRINT
70 ~=PRINT MID$(A$, 1,8)
80 PRINT MID$(A$,10,13)
90 PRINT MID$(A$,24,19)
999 END
RUN
JOHN DOE 2200 MAIN ST. ANYTOWN USA 00000
JOHN DOE
2200 MAIN ST.
ANYTOWN USA 00000
JOHN DOE
2200 MAIN ST.
ANYTOWN USA 00000
When the program is typed and RUN, it can be readily understood that the
program is useful only if the name and address input is JOHN DOE 2200
MAIN ST. ANYTOWN USA _ OOO000.
When line 20 is changed to
100 APPLESOFT LANGUAGE
20 INPUT A$
the input must be the same number of letters and characters in the original
JOHN DOE name and address to be output in the correct format.
For a program to be valuable, it must be flexible. The name line of the
program must accept any name, no matter if it has three characters or 255
characters. The address field must be able to accept different numbers of
characters for different street numbers and street names. The city, state,
and zip line must also be able to accept different numbers of characters. To
achieve this flexibility, a delimiter (;) is used after each line of the name and
address.
JOHN DOE;2200 MAIN ST.;ANYTOWN USA OO0OOO(L)
As a step toward developing a flexible program, an inflexible formula is
first demonstrated.
20 INPUT A$
30 N=9:A1 = 23:L = LEN(AS)
40 PRINT A$
50 ~~PRINT LEFT$(A$,N — 1)
60 PRINT MID$(A$,N+1,A1 —(N+1))
70 ~~PRINT RIGHT$(A$,L—A1)
999 END
The semicolon (;) is used as a delimiter separating fields in A$. The vari-
ables locate the delimiters at the end of each field. No spaces are left be-
tween the contents of the field and the delimiter.
The following is an explanation of the expressions used in this program.
N=9 N = variable of the delimiter at the end of the first field.
Nine (9) is the column the delimiter occupies.
Al = 23 Al = variable of the delimiter at the end of the second
field. Twenty-three (23) is the column the delimiter oc-
cupies.
L = LEN(A$) _L points to the end of the third field. The column that L
occupies is determined by the length of the city, state,
and zip code.
Table 14-1. Where Lines Start and End
| Start | Symbol | End | Symbol
2
STRING ARRAYS 101
Line 1 LEFT$(A$,N — 1)
Line 2 MID$(A$,N+1,A1—(N+$1))
Line 3 RIGHTS(A$,L —-A1) (the closing delimiter should be A1+1, but Applesoft
picks up the delimiter position as A1)
length separated by a delimiter (;) to allow any length of name, any length of
street number and address, and any length of city, state, and zip code up to
255 characters each.
I. B. Detailed input format. Line of input = A$
JOHN DOE;2200 MAIN ST.;ANYTOWN USA 00000
I. C. Detailed ouput format.
JOHN DOE
2200 MAIN ST.
ANYTOWN USA _ 00000
I. D. Outline flowchart. (Shown in Fig. 14-1.)
I. E. Assignment of variables. The variables use the logic that a delimiter
(D) is used after line 1 to close the line, hence, D1C means the delimiter that
closes line 1. A delimiter (D) is used after line 2 to close the line, hence,
D2C. L = LEN(AS) is the delimiter used at the end of line 3. The entire list of
variables is as shown below:
ASSIGNMENT OF EXPRESSIONS
1 (st column) Beginning of line 1 — LEFTS(AS,
D1C Points to the delimiter at the end of line 1.
DiC-1 End of line 1.
DiC +1 Beginning of line 2.
D2C Points to the delimiter at the end of line 2.
D2C- 1 End of line 2.
D2C + 1 Beginning of line 3.
L End of line 3.
ERR Variable that is assigned a value when an input error has
occurred, and the value is used to print the type of error.
J - (J,J) Loop variable or subscript variable.
I. F. Start and end of lines. Once the delimiter variables are assigned, they
are placed at the start and at the end of the lines.
INPUT LINE
OF INFORMATION
CHECK INFORMATION
TO MAKE SURE IT’S
LEGAL & DETERMINE
3 LINES OF INFO
Fig. 14-1. Outline flowchart.
ERROR
INFORMATION MESSAGE
(START
J INPUT AS
vss
< MIDS (A$,D1C,1)
AU
WON
BWN
C MIDS(A$,D1C,1) >
. fey? 2. 2
T Yes
| o2c=Dtc |
ILLEGAL CONDITIONS
1. Delimiters — not exactly 2.
2. Length of lines
a. Length of line 1 = O characters.
b. Length of line 2 = O characters.
c. Length of line 3 = O characters.
I. H. 1. Number of delimiters. The input format has two, and only two
delimiters. If there are any more or any less than two delimiters, the input is
illegal.
106 APPLESOFT LANGUAGE
L = LEN (A$)
DiC
= DIC + 1
GOTO INPUT
| PRINT
‘OLLEGAL INPUT": |
IS
MID$(A$,D1C, 1
ee)
D2C = DiC
LS
=
3 ILLEGAL FOR J = D2C+1 TOL
IF MID$(A$,J,1) = 17;""
NEXT J
until DIC is greater than L. When D1C>L, the computer prints ILLEGAL
QUANTITY ERR because it is telling the machine to compare a nonexistent
character with “;”.
eo 93
.
ISDIC>L?
ISDiC=1?
ISD2C>L?
ISD1C + 1 = D2C?
ISD2C =L?
IS A 3rd DELIMITER FOUND
IN THE LAST PART OF THE INPUT ?
Cr)
| REM: INPUT NAME & ADDRESS
| WITH DELIMITERS |
NAME:ADDRESS:
CITY, STATE ZIP" ”
INPUT AS |
DIC
= DIC + 1 |
IS
< MIDS(AS,D1C,1),
N a_i?! ? J
D2C = DIC
D2C
= D2C + 1 |
“Is ,>
¢ MID$(A$,D2C,1
se,0a 9
[ER = 4: GOSUB
400 |
“| -:G0T0120.— |
ws
MIDS(A$,J,1) YES _ feRR = 6 : GOSUB 400]
i GOTO 120 |
NO
NEXT J
PRINT LEFT$(A,D1C — 1)
PRINT MID$(A$,D1C +1, D2C — (DIC + 1))
PRINT RIGHTS(A$, L_— D2C)
GOTO 120
ERROR SUBROUTINE
| PRINT
‘eet LEGAL
PRINT ‘'NO DELIMITER IN STRING’
> RETURN
PRINT ‘‘LINE 1 1S ZERO LENGTH’’
> RETURN
PRINT ‘‘ONLY 1 DELIMITER IN STRING’’
> RETURN
PRINT ‘*LINE 2 IS ZERO LENGTH’’
: RETURN
“LINE 3 1S ZERO LENGTH"
> RETURN
PRINT ‘‘MORE THAN 2 DELIMITERS
IN STRING"
> RETURN
RUN
The flowchart was written with normal logic. The program was coded with
expedient logic. Once the flowchart is developed, the sections are broken
down to determine the most efficient and fastest way for the program to
run. A flowchart is simply a tool to help clarify the logic involved in solving
a problem. When converting a flowchart to a program it is sometimes useful
to reverse the “IF” check to save memory. The common practice is to use
MIDS(A$,D1C,1) = “;’. The program must search for “;” until it is found.
When = “;” is not true the program must unconditionally branch (GOTO)
backwards to increment D1C. Expedient logic MID$(A$,D1C,1)<>*“;”
causes the program to search for <>";”. If it is not found, the program
conditionally branches to increment D1C, thus saving a GOTO statement
with each decision. This not only saves program statements, but makes the
program more efficient, run faster and uses less memory. Expedient logic
makes the program simpler and more efficient. It gets the job done better
and faster.
Lines 100 and 110 are REM statements that document the program to
print the name and address of an individual and to check for input errors.
Line 120 prints out the exact input format for the user. The user is soon
aware that the name and address must be input exactly the same way as the
input header. If the input is different, the user is given an error message why
the input is incorrect. The program will not accept the name and address
unless it is correctly input.
Line 140 is a programming convenience. It is much easier to type L than
it is to type LEN (A$). DIC = 0 initializes the first delimiter to zero. The
D2C and L delimiters are not initialized to zero, because in line 190 D2C =
D1C takes the value of D1C at the end of line 1 and stores it in D2C. This
value maintains the continuity of the program in checking for the relation-
ship with L (LEN (AS) ).
Line 150 is a counting statement that is incremented on each character of
line 1 of A$ until it detects the delimiter (;).
In line 160, if the counting statement increments until the value of D1C is
greater than L, the THEN is executed to send the program to ERR = 1. In
Applesoft when the statement (IF D1C > L) is true, all statements at that
line number are executed (unless there is an unconditional branch THEN
400). GOSUB 400 branches to the subroutine beginning at line 400.
***1T LEGAL INPUT*** is printed. The ERR = 1 sends the program to line
430. The error-line number relationship is shown in Fig. 14-7.
At the end of line 430 is a RETURN statement. A RETURN statement
must be placed at the end of a subroutine. The RETURN causes the program
to branch to the program statement immediately after the GOSUB.
The sequence of events that occur after ERR = 1 is
2. ERR = 1 ON (1) GOTO 430 to print the input error. RETURN fol-
lows the error printout.
3. RETURN GOTO 120—line immediately following GOSUB 400.
The ON—GOTO (ON—GOSUB) is a relationship programmed into
Applesoft. A specific ERROR number relates to a specific line number in the
program.
In line 170, the decision statement checks to see if the delimiter (;) at the
end of the first line has been reached. If the character is not the delimiter,
the program branches to line 150 to increment the value of DIC.
In line 180, if there is only one delimiter in A$, the ERROR = 2. The state-
ment GOSUB 400 sends the program to line 400 to print out ***ILLEGAL IN-
PUT*** and then to line 440 to print out the input error, LINE 1 IS ZERO
LENGTH.
In line 190, the value held in the delimiter D1C is stored in D2C. This
statement maintains the value relationship from one delimiter to the next.
This value relationship is continued as the program moves to L, the
delimiter at the end of line 3. |
In line 210, if the present value stored in D2C is greater than L, THEN
input error *3 is printed on the screen. The program executes GOSUB 400,
ON 2 GOTO 450, to print, ONLY ONE DELIMITER IN STRING. The RETURN
statement branches to the line immediately after GOSUB 400. The state-
ment is GOTO 120, and immediately branches to line 120, for more input.
In line 220, if the decision statement does not find the D2C delimiter, it
branches to line 200 to increment D2C.
In line 230, if the two semicolon delimiters are together with no char-
acters in between, line 2 is missing. ERR = 4. GOSUB 400 executes to line
400 to print out ***ILLEGAL INPUT***, ON 4 GOTO 460, prints out, LINE 2 1S
ZERO LENGTH. RETURN branches to GOTO 120 (line 230) to input the cor-
rect information.
In line 240, if D2C = L there are no characters in line 3, and ERR = 5,
causes a branch to the subroutine to print ***ILLEGAL INPUT***. ON 5
GOTO 470 prints, LINE 3 IS ZERO LENGTH.
Lines 250 to 270 are a loop to check the number of delimiters from D2C
to L. The program has checked that there are 2 delimiters to this point. Line
114 APPLESOFT LANGUAGE
170 checks the delimiter at the end of line #1. Line 220 checks the delimiter
at the end of line #2. If the loop FOR J = D2C + 1 TOL executes and finds
another semicolon delimiter then ERR = 6. The program branches to line
400, prints out ***ILLEGAL INPUT ***, ON 6 GOTO 480, MORE THAN 2
DELIMITERS IN STRING. The RETURN is executed to GOTO 120, and GOTO
120 branches to input information.
Lines 280, 290, and 300 print out the name and address of the individual
in the correct format.
Lines 301 and 302 are inserted to inform the user of the correct MID$
functions to replace the LEFTS and RIGHTS to print out lines #1 and #3.
Line 310 PRINT : INPUT “MORE INPUT (Y OR N)” ;Q$ queries the user, is
another name and address to be input, or does the user want to end the pro-
gram?
Line 320 IF Q$<>"N” THEN 120 is a decision statement to branch to
line 120 for more input, or to end the program. This line could be flow-
charted in either of two ways with equal efficiency as shown in Fig. 14-8.
GOTO 120
GOTO 120
Lines 400 to 480 are the subroutines and the ON (ERR) GOTO state-
ments. Subroutines placed after the main body of the program do not
clutter up the main body of the program. Applesoft indicates an END state-
ment is optional and need not be used. Experience shows that complicated
programs will not always run properly without an end statement. The sub-
routines perform better when the program branches past the end statement
of the program. The subroutine runs and the RETURN branches to the state-
ment immediately after the GOSUB in the main body of the program. Use
an END statement with all programs.
LESSON 15
Functions
VOCABULARY
Argument — This is a variable factor, the value of which determines the
value of the function.
Function — This is that part of the computer instruction that specifies the
operation to be performed.
Radian — This is a unit of plane angular measurement that is equal to the
angle at the center of a circle subtended by an arc equal in length to the
radius.
DISCUSSION
In this lesson, the arithmetic functions will be placed alphabetically in a
program to demonstrate their use, and they will be clarified by explanation.
A function, as explained in the vocabulary, is that part of the computer in-
struction that specifies the operation to be performed. Functions act upon
the input to a function. The function then performs some operation on the
argument, and outputs the result. The operation itself may involve many
program steps. Calling a function automatically makes use of these pro-
grammed steps.
The following program shows how functions work. The output of each
function is placed beside the function, rather than at the end of the pro-
gram, for clarity.
100 Mz= -4:N2=+2.5:P=3:Q=0
110 PRINT ABS (M) (4)
120 PRINT EXP (P) (20.0855369)
175
116 APPLESOFT LANGUAGE
VOCABULARY
DEL — This is a command to remove a line or lines from a program. DEL
20,70 removes lines 20 through 70 from the program.
Edit — This means to arrange data into a format required for subsequent
processing. Editing may involve deletion of data not required, conver-
sion of fields into a machine format (e.g., value fields converted to
binary), and preparation of data for subsequent output (e.g., zero sup-
pression).
Escape Cursor Moves Mode — In this mode, the ESCAPE key must be
pressed at the same time a cursor move key is pressed. If ESCAPE is not
pressed simultaneously with a cursor move key, the computer will not
move the cursor. Cursor move keys are A, B, C, and D. Escape cursor
moves mode is used by Apple computers supplied with Applesoft on tape
or disk.
LIST— This command lists all the line numbers and program statements in
a program. LIST 50,100 lists lines 50 to 100 of a program.
Prompt — This is any message given to an operator by an operating system.
Pure Cursor Moves Mode — In this mode, the ESCAPE key does not have to
be pressed at the same time as the cursor move keys. Instead, ESCAPE is
pressed only once to enable the cursor move keys. To leave this mode,
any character key but the cursor move keys must be pressed. Cursor
move keys are Il, J, K, and M. This mode can only be used by Apple com-
puters with Applesoft supplied by firmware, rather than by tape.
119
120 APPLESOFT LANGUAGE
DISCUSSION
In editing, probably the most used keys are the left arrow, the right arrow,
and the repeat keys. The left arrow key, when pressed, moves the cursor one
space to the left. The right arrow key, when pressed, moves the cursor one
space to the right. When the repeat key is pressed, the last character printed
is repeated on the screen. To prevent this undesirable reprinting, a shift
arrow key should be pressed and released. The repeat and shift arrow key
(or desired key) can then be held down simultaneously to move the cursor
(or chosen character). When the repeat key and any other key are pressed
simultaneously, the character is repeated until the keys are released.
Type in this program.
10 PRINT “’THIS IS THE USA”
20 END
To list the program, type LIST and the total program appears. To list only
one line of the program, type LIST and the line number.
LIST 10
10 PRINT “THIS IS THE USA”
To list a long section of a program, type LIST and the beginning line num-
ber, followed by a comma, and the last line number.
LIST 10,20 (for a long program LIST 50,100 — the screen only holds 24 lines of the program
statements)
10 PRINT “’THIS IS THE USA’’
20 END
In the list function, a minus sign (—) may be used to replace the comma
between the line numbers.
LIST 50,100 = LIST 50-100
To list those lines above 500 (program runs from 0 to 1000) type LIST
— 500. To list those lines below 500 type LIST 500 —-. This convenient fea-
ture saves a great deal of typing.
To delete a single line of the program, type in DEL and the line number,
followed by a comma, and the same line number.
DEL 10,10 — deletes line 10 of the program.
Another way to delete line 10 is to type 10, and press RETURN.
The minus sign (—) cannot be used to replace the comma (,) in the DEL
command.
Type in DEL 10 to delete line 10. The computer gives a ? SYNTAX ERR
for this illegal command, because the command did not include a comma
and the repeat of the line number.
Sections of a program can be deleted by typing in: DEL first line number,
comma, second line number.
DEL 100,200 deletes all lines from 100 to 200, including 100 and 200.
LIST AND EDIT 121
To delete the total program from memory, type NEW. To check that the
program has been deleted from memory, type LIST. If no program appears
on the screen, the program has been deleted from memory.
There are two types of edit functions, (1) escape cursor moves, and (2)
pure cursor moves.
The escape cursor moves require the escape key be pressed before the
key to move the cursor is pressed. To move the cursor again, the escape key
must be pressed before the key to move the cursor is pressed. The routine is
press the escape key and then press the cursor move key. The escape cursor
move mode works on Applesoft that is loaded from tape or disk.
The keys that control the cursor in the escape cursor moves mode are:
KEY DIRECTION
ESCAPE A RIGHT
ESCAPE B LEFT
ESCAPE C DOWN
ESCAPE D UP
If the escape key is not pressed before the A key, the letter A will be
printed on the screen. When the escape key is pressed and the A key is
pressed, no letter is printed on the screen; only the cursor is moved one
space to the right.
The pure cursor moves mode edit function is available on Applesoft firr-
ware, and does not work on Applesoft loaded from tape.
The pure cursor moves mode requires the escape key be pressed once
and the proper character key is pressed to move the cursor. The cursor can
be moved in any direction until some key other than I, J, K, or M is pressed.
The keys that control the cursor in the pure cursor moves mode are:
KEY DIRECTION
ESCAPE (pressed only once)
K RIGHT
J LEFT
M DOWN
I UP
To recover from the pure cursor moves mode, any key (other than I, J, K,
or M) may be pressed one time. The second time the key is pressed the
operator regains control of the computer.
For example, in editing line 10:
LIST 10
10 PRINT ‘’THIS IS THE USA”
ESCAPE is pressed and released. Key J is pressed one time to bring the
cursor to column 1 of the screen. Key | is pressed twice to place the cursor
over the 1 in line 10. The pure cursor moves mode is exited by pressing the
122 APPLESOFT LANGUAGE
right arrow key twice. The right arrow and repeat keys are then pressed to
place the cursor over the area to be changed. The changes are made by
typing in the proper character. The cursor is moved past the closing quote
to complete the edit. Did you print an incorrect character in the statement?
Go back and do it correctly.
There are three types of statements that can be edited. They are the state-
ments containing:
1. Characters enclosed in quotation marks that occupy one line on the
screen.
2. Characters not enclosed in quotation marks that occupy more than
one line on the screen.
3. Characters enclosed in quotation marks that occupy more than one
line on the screen.
In editing Applesoft loaded from tape or disk, only the escape cursor
moves mode can be used.
Statements with characters enclosed in quotation marks that occupy one
line and characters not enclosed in quotation marks that occupy more than
one line offer no editing problems. The cursor must be past the last
character in the line before RETURN is pressed. If the cursor is before the
last character and RETURN is pressed, all characters after the cursor are
deleted.
The editing problems come in statements with characters enclosed in
quotation marks occupying more than one line.
The LIST causes line 10 to break in the middle of STATES. If not edited
correctly, spaces will be left in the printout when the program is run. The
method to eliminate spaces is to use the escape cursor moves mode, in the
areas where spacing is possible.
Press ESCAPE and B. This moves the cursor to column 1 of the screen.
Press ESCAPE and D. This moves the cursor one row up. Pressing ESCAPE
and D moves the cursor over the 1 in line 10.
Press repeat and right arrow keys simultaneously. D is printed on the
screen over the 1. The repeat key repeats the last character key pressed. To
prevent printing D (or the last character pressed), the right arrow key must
LIST AND EDIT 123
first be pressed and released. The right arrow key and the repeat key can
then be pressed simultaneously without printing a character.
To erase the D, press the left arrow key and retype the number 1. Press
the right arrow key and the repeat key simultaneously until the cursor
moves past the ending quotation mark on the 2nd line. Now press RETURN
and type LIST 10.
10 PRINT ‘THIS IS THE UNITED STA
TES OF AMERICA”
The spacing between the A and the T in STATES has been changed. Now
type RUN.
RUN
THIS IS THE UNITED STA TES OF AMERICA
The spacing in the RUN has also been changed. To prevent this error the
line must be edited to look like this:
10 PRINT “'THIS IS THE UNITED STATES OF
AMERICA’’
RUN
THIS IS THE UNITED STATES OF AMERICA
LIST 10
10 PRINT “‘THIS IS THE UNITED STA
TES OF AMERICA”
The printed line now has the correct spacing. The ESCAPE and A must be
used to prevent changed spacing on statements with characters enclosed in
quotation marks that occupy more than one line.
For Apple computers with Apple firmware using the pure cursor moves
mode, editing is very simple. The same procedure is used for the pure cur-
sor moves mode as is used for the escape cursor moves mode, but ESCAPE:
is pressed once and then I,J,K, or M is used to place the cursor over the
character to be edited. After the statement is edited, the RETURN key must
be pressed twice for the operator to regain control of the computer.
To delete a character in an existing line using the escape cursor moves
mode, type in the line.
10 PRINT ’’THIS IS THE USA’
Place the cursor over the in IS. Press ESCAPE and A. The 1 is still visible
and the cursor moves over the letter S in IS. Move the cursor past the
closing quote. Another way to edit the I is to place the cursor over the | in IS,
and press the space bar. Type LIST 10.
10 PRINT “’THIS S THE USA” (the letter | has been deleted)
To insert the letter | in IS, type LIST 10.
10 PRINT ‘‘THIS S THE USA”
Place the cursor over the letter S. Press ESCAPE and B to prepare to in-
sert the word IS. Type IS THE USA. Press RETURN and type LIST 10.
10 PRINT “‘THIS IS THE USA"
To delete a letter using the pure cursor moves mode, type in line 10.
10 PRINT “'THIS IS THE USA”
Bring the cursor over the letter | in IS. Press ESCAPE and K. The cursor
moves over the S and the | is still visible. Move the cursor past the closing
quotation mark. Press RETURN and type LIST 10. The I can also be deleted
by placing the cursor over the | and pressing the space bar.
10 PRINT ‘THIS S THE USA"
To type in the letter I in the existing line, place the cursor over the letter
S. Back the cursor into the space between the THIS and the S. Press ES-
CAPE and B for escape cursor moves mode, or ESCAPE and J for the pure
cursor moves mode. Type in I. Press the right arrow once and release. Press
the right arrow and repeat keys simultaneously to place the cursor past the
closing quote. Press RETURN. Type LIST 10.
10 PRINT ‘’THIS IS THE USA"
The IS is in proper spacing in the literal again.
To insert text into an existing line, place the cursor over the letter where
the inserted item is to be placed. In the case of line 10, GOOD OLE is to be
placed before USA.
LIST AND EDIT 125
VOCABULARY
NOTRACE — This command turns off the TRACE mode (see TRACE
below).
Pass — This means the single execution of a loop, or the passage of
magnetic tape across the read or write heads of a recording device.
TRACE — This is an aid in following the sequence of execution of a pro-
gram. It is used as an aid in debugging programs. TRACE causes the line
number and output data to be printed on the screen in the sequence of
line number execution. TRACE is turned off by NOTRACE. TRACE and
NOTRACE are immediate commands.
DISCUSSION
The primary purpose of this lesson is to “think” like a computer. When
you think like a computer and run the program mentally and manually, you
will be able to determine what the actual output of the program will be,
rather than what you think it should be. You must think like a computer if
you are going to understand and outsmart this exacting machine. When you
play computer the program is RUN exactly as it is written. If the rule of de-
fault applies, use the rule of default. If the progam uses a decision state-
ment, you must make the proper decision to branch or default. Tables
should be made to determine how the variables change with each pass. RUN
127
128 APPLESOFT LANGUAGE
the program mentally several times to get the feel of the program. Com-
plete the chart to see if you think like a computer. The RUN and TRACE are
shown in Fig. 17-1.
RUN
6 10 -8
7 10 -6
8 10 —4
9 10 —2
10 10 0
10 8 1
10 8 -9
TRACE
RUN
#10 #20 #20 #20 #30 #40 #90 #100 #110 6
10 —8
#120 #30 #40 #90 #100 #110 7
10 —6
#120 #30 #40 #90 #100 #110 8
10 -_4
#120 #30 #40 #90 #100 #110 9
10 -—2
#120 #30 #40 #90 #100 #110 10
10 0
#120 #30 #40 #50 #60 #70 10
8 1
#80 #30 #130 #140 10 8
-9
#150
After the chart has been completed and you are satisfied you understand
how and why the program functions, RUN the program to get the correct re-
sults. Did you do as well as the computer?
Type in the immediate command TRACE. When the program is RUN, the
line numbers, and variable values, are printed on the screen. If a program
does not RUN, TRACE can aid in determining why it doesn’t run. The error
messages built into the language can also aid in debugging programs. If a
program stops at line 120, and no error message is given, many times the
TRACE mode can aid in correcting the problem.
TRACE function can be removed by typing NOTRACE on the screen. The
next program RUN will be without the line numbers on the screen to give an
example of how TRACE and NOTRACE are typed on the screen.
RUN
TRACE
RUN
NOTRACE
LESSON 18
Reserved Words
VOCABULARY
Reserved Words — These are words programmed into the language to aid in
carrying out the programming functions.
DISCUSSION
Reserved words are used to aid in programming. These words cannot be
used as variables. Applesoft tokenizes reserved words to a decimal number
similar to the decimal number that represents an ASCII symbol. For exam-
ple,
40 IF B= ATHEN 90.
When the program is RUN, the program is stopped at line 40 and
SYNTAX ERR is printed on the screen. When line 40 is LISTed it appears as:
40 IF B = AT HENQO.
The variable A attaches to T in THEN to become the reserved AT. To
overcome this problem and use the variable A in the same sequence, use
parentheses around B = A.
40 =IF (B = A) THEN 90
The list of reserved words is taken directly from Applesoft Il, BASIC PRO-
GRAMMING REFERENCE MANUAL, page 122, by Apple Computer, Inc.,
10260 Bandley Dr., Cupertino, California 95014.
131
132 APPLESOFT LANGUAGE
VOCABULARY
Code — This is the representation of data or instructions in symbolic form.
It is sometimes used as a synonym for instructions. Coding is the act of
converting data or instructions into program statements.
Comment — This is a written note that can be included in the coding of
computer instructions in order to clarify the procedures, but has no effect
on the computer itself.
GET A$ — This stops the program in order to view the output until any key
is pressed.
Menu Selection — This is a method of using a terminal to display a list of
optional facilities that can be chosen by the user in order to carry out dif-
ferent functions in the system.
DISCUSSION
Many people have little knowledge of computers. For these people, the
programs must be written to tell them what input is required, and in what
format. One way to aid these people with the correct selection is to use a
menu. A menu selection is a method of using a terminal to display a list of
optional facilities that can be chosen by the user in order to carry out differ-
ent functions in the system.
The following program computes depreciation by using either the
straight line method, double declining balance method (200%), or the sum
of the years digits method. The variables are shown in Fig. 19-1.
133
134 APPLESOFT LANGUAGE
The program shows the menu selection. The user selects which method
of depreciation is to be used for computation. The menu section of the pro-
gram is contained in lines 500 to 560.
500 HOME : VTAB 3: HTAB 8: PRINT ‘’***DEPRECIATION***” :
PRINT : PRINT
910 HTAB 5: PRINT “'1. STRAIGHT LINE DEPRECIATION” : PRINT
520 HTAB 5: PRINT ‘'2. DOUBLE DECLINING BALANCE” : PRINT
530 HTAB 5: PRINT ‘'3. SUM OF THE YEARS DIGITS” : PRINT
540 HTAB 8: INPUT “SELECTION PLEASE!”’ : PRINT
5950 IFS<1ORS> 3 THEN 500
560 ONS GOTO 1500, 2500, 3500
Line 500 clears the screen and sets the position at which ***DEPRECIA-
TION*** is to be printed. The two PRINT statements leave two blank lines
below ***DEPRECIATION***,
MENU SELECTION AND CODING FORMULAS 135
Lines 510 through 530 print out the three types of depreciation. The user
selects one choice.
Line 540 allows the user to select any number. The number does not
necessarily have to be 1, 2, or 3.
Line 550 is a decision statement that causes a branch to line 500 if a num-
ber other than 1, 2, or 3 is input. This is a form of error checking that limits
the input choices that will be accepted by the program. Since there are
three choices, the machine is programmed so only an input of 1, 2, or 3 will
allow the program to continue.
In Jine 560, the input value is placed in the variable S. When S = 1 the
program branches to line 1500. When S = 2 the program branches to line
136 APPLESOFT LANGUAGE
2500. When S = 3 the program branches to line 3500. The ON S GOTO type
of statement was discussed in Lesson 14 and was the method used to print
the input errors.
When a correct menu selection has been input, the program branches to
line 1500, 2500, or 3500. At each of these lines is aGOSUB 100. The GOSUB
100 causes a branch to line 100 of the program. Line 100 is the beginning of
the input subroutine. This subroutine is placed at the beginning of the pro-
gram because it is used by each type of depreciation. The program is more
efficient because fewer lines are searched before the input information is
found. The headings are printed, and the input information is requested.
100 INPUT ‘‘“GROSS AMOUNT = $" ;GA: PRINT
105 IF GA< 1 THEN 100
110 INPUT ‘SALVAGE VALUE = $” ;SV : PRINT
115 IF SV< 0 THEN 110
120 IF GA< SV THEN 100
130 INPUT ‘’LIFE OF ASSET = *' ;LA: PRINT
135 IFLA< 1 THEN 130
140 RETURN
In line 105, the gross amount of the asset cannot have a negative value to
be used in the formula.
In line 115, the asset may be valued at zero at the end of the depreciation
period, but the formula will not properly compute assets with a negative
salvage value.
In line 120, if the gross cost of the item is less than the salvage value, the
formula will not compute the depreciation properly.
In line 135, the asset must have a useful life of at least one year or some
period greater than zero.
The depreciation formula must compute positive real numbers greater
than zero. The error checks attempt to eliminate any input that would not
give a meaningful computation to the user.
Line 140 causes a branch to the section of the program that requested the
input information.
If 1 is input from the menu selection, the program branches to line 1500.
Line 1500 branches to the input subroutine. After input is received, line 140
causes a branch to line 1510 to begin calculation of straight line deprecia-
tion. The numbers have been rounded. The numbers used for all examples
are: cost of asset (GA) = $625, salvage value (SV) = $25, and life of the
asset (LA) = 3 years.
1500 GOSUB 100
1510 TD =0
1520 PRINT “YEAR DEP/YR TOTAL DEP.” : PRINT:
P = 100
1530 FORX = 1TOLA
1540 DY = (GA —- SV)/LA
MENU SELECTION AND CODING FORMULAS 137
1550 TD = TD + DY
1560 PRINT X; TAB (10); INT (DY*P + .5)/P; TAB (25);
INT (TD*P + .5)/P
1570 IF X = INT (X/8) * 8 THEN GET A$
1580 NEXT
2400 GOTO 9990
Line 1560 prints the year, the amount of each year’s depreciation, and the
total depreciation. Line 1560 is included within the loop, so the results will
be printed for each year’s computation.
Line 1570 performs the same function in lines 1570, 2570, and 3570. It
causes the loop to stop after every eight executions (as shown in Table
19-1). This is useful when the life of the asset is a long period (over 10 years)
of time and the user needs to study sections of the printout. The integers
could be any number such as 10, 12, or 20, as long as the number is less
than the number of lines on the screen.
GET AS, from line 1570, is a function to stop the program to allow the
user to view the output. GET A$ allows the user to press any key on the key-
board to continue the program. The key pressed does not print a character
on the screen. RETURN does not have to be pressed.
oe)
8
6
6
138 APPLESOFT LANGUAGE
Line 2512 initializes the total depreciation to zero, and line 2515 causes
the headings to be printed.
Line 2520 is the beginning statement of the loop for the computations.
Line 2530 computes the depreciation for one year and stores that value in
the variable DY (depreciation per year).
Line 2540 computes the reducing book value by subtracting off the de-
preciation each year.
Line 2545 is a summing statement that adds each year’s depreciation to
the previous year’s and stores the total in the total depreciation variable,
TD.
RUN
YEAR DEP/YR TOTAL DEP.
1 200 200
2 200 400
3 200 600
The third type of depreciation is the sum of the years digits. In this
method, the years of the asset’s life are listed numerically and totaled. The
highest year in the life of the asset is then divided by the total to compute
the depreciation constant for the first year. The changing yearly constant is
multiplied by a fixed gross amount of the asset less the salvage value. The
method is shown in the program lines 2500 to 3600 in Fig. 19-6, and the
RUN in Fig. 19-5.
RUN
YEAR CONSTANT DEP/YR TOTAL DEP.
1 me) 300 300
2 .33 200 500
3 17 100 600
DEPRECIATION
INFORMATION PROGRAM STATEMENTS
Total years3 + 2+1= 6 FOR X = 1TOLA:
T = T + X: NEXT X
T = LA * (LA + 1)/2
3/6 = lst year maximum FOR Y = LA TO 1 STEP -1:
depreciation K = Y/T
2/6 = 2nd year depreciation
1/6 = 3rd year minimum
depreciation
DY TD DY = K* BV
500 * $600 = $300 $300 TD = TD + DY
333 * 600 = 200 500
167 * 600 - 100 600
50 GOTO 500
100 INPUT ‘‘ GROSS AMOUNT = $” ; GA: PRINT
105 IF GA< 1 THEN 100
110 INPUT “SALVAGE VALUE = $” ;SV : PRINT
115 IF SV< 0 THEN 110
120 IF GA< SV THEN 100
130 INPUT “’LIFE OF ASSET = “ ;LA:: PRINT
135 IFLA< 1 THEN 130
140 RETURN
500 HOME: VTAB 3: HTAB 8: PRINT ‘‘***DEPRECIATION***" :
PRINT : PRINT
510 HTAB 5S: PRINT ‘’1. STRAIGHT LINE DEPRECIATION” : PRINT
520 WHTAB 5: PRINT ‘’2. DOUBLE DECLINING BALANCE” : PRINT
530 HTABS: PRINT ‘'3.SUM OF THE YEARS DIGITS” : PRINT : PRINT
540 HTAB 8: INPUT “‘SELECTION PLEASE!" ; S: PRINT
550 IFS<10ORS> 3 THEN 500
560 ONS GOTO 1500, 2500, 3500
1500 GOSUB 100
1510 TD =0
1520 PRINT ‘’YEAR DEP/YR TOTAL DEP.” : PRINT :
P = 100
1530 FORX = 1TOLA
1540 DY = (GA —- SV)/LA
1550 TD = TD + DY
1560 PRINT X; TAB (10); INT (DY*P + .5)/P; TAB (25);
INT(TD*P + .5)/P
1570 IF X = INT (X/8) * THEN GET A$
1580 NEXT
2400 GOTO 9990
2500 GOSUB 100
2510 K = (1/LA) * 2: BV = GA
2512 TD =0
VOCABULARY
Data — This is a general expression used to describe any group of oper-
ands that denote any conditions, values, or states (i.e., all values and
descriptive data operated on by a computer program but not part of the
program itself). The word data is used as a collective noun and is usually
accompanied by a singular verb: “data are’ may be pedantically correct
but is awkward to understand. Data is sometimes contrasted with
information, which is said to result from the processing of data, so that
information derives from the assembly, analysis, or summarizing of data
into a meaningful form.
DATA — This statement contains a list of items that can be used by a READ
statement. DATA statements can contain literals, strings, reals, and inte-
gers. The item in the DATA statement must contain the same relation-
ship and position as the item in the READ statement.
READ — This is a statement used by the program to read data into
memory.
DISCUSSION
The outline for program structure must be considered very general and
probably no program will rigidly comply with the outline. There must be a
starting point to writing a program. The logical start to writing a program
must exist within the framework of an outline.
Computer program general outline.
A. Start the program.
B. Initialize the variables.
1. C = O counting variable
2. S = O summing variable
143
144 APPLESOFT LANGUAGE
The loop runs from 1 to 5 and prints the next number in the series,
namely 6. This is a very important point to realize. Because the general out-
line was violated, the program did not produce the desired results, namely,
printing X at every iteration of the loop.
To the original program, make these changes:
DEL 60,60
45 PRINT “*SUM = “"’ ; SUM
The entire program is:
10 SUM =0
20 FORX =1TO5
30 PRINT X
40 SUM = SUM + X
45 PRINT “SUM = " ; SUM
50 NEXT X
70 END
146 APPLESOFT LANGUAGE
1
SUM
2
SUM
3
SUM
4
SUM
5
SUM 15
Since the SUM was within the loop, SUM = was printed with each execu-
tion of the loop. Make the following changes to the original program:
DEL 10, 10
25 SUM = 0
The entire program is now:
20 FOR X =1TO5
25 SUM = 0
30 PRINTX
40 SUM = SUM + X
50 NEXT X
60 PRINT “SUM = " ;SUM
70 END
RUN
SUM =5
In this case, the summing variable was initialized to zero each time the
loop executed, so the final SUM = 5. The initialized variable must be out-
side the loop or it will be reset to zero each time the loop executes.
LESSON 21
Cleanup
VOCABULARY
Print Field Definition — This is the technique of printing output to fit a stan-
dard pattern or form, thus making the output more readable.
Right Justify — This means to format output so the printed field is aligned
on a right hand boundary.
Zero Suppression — This is the elimination before printing of nonsignif-
icant zeros, e.g., those to the left of significant digits. The suppression is
a function of editing. It is also known as zero elimination.
DISCUSSION
This lesson “cleans up” many parts of the language not covered in the
first 20 lessons. Here we go with all the bits and pieces.
Applesoft does not align columns of different numbers to the power of
ten. All numbers are printed starting from one selected space and printed to
the right.
ft
284.6
98.3
2
3.47
The following program makes numbers align in the proper columns, so
the units are aligned, the tens are aligned, etc. The program causes the
printout to right justify by two methods, (1) by aligning the right hand num-
ber, and (2) by aligning the decimal point. Either method ofjustification can
147
148 APPLESOFT LANGUAGE
ENTER?234.69
R JUST = itiiti::234.69$$$$$$$234.69
ENTER?.5678
R JUST = srirritiis:.5678$$$$$$$$$$.5678
ENTER?3456789
ENTER?2123.5678
R JUST = 2:::::2123.5678$$$$$$2123.5678
ENTER?0
Lines 5 and 6 are used together to compute the magnitude of the number
to be printed. D holds a constant value which is 2.30258509. That is the
value used to compute the power to which base 10 is raised. The power is
used to right justify on the decimal point in lines 90 to 130.
DEF FN MA (X) = INT (LOG (M) /D ) is the function that computes the
magnitude of the number.
M = 2,34
D = 2.30258509
LOG (M) = 3.17805383
LOG (M)/ D = 3.17805383 / 2.30258509
INT (LOG (M)/D) = 1
Line 10 clears the screen. Line 20 asks the user to input a number. Line
30 is a decision statement that ends the program.
In this example, the number 2.34 will be input and the results will be dis-
cussed as it is justified.
In line 60, STR$ converts the number 2.34 into a string. This conversion
allows the string “2.34” to be evaluated. The number of characters (4) is
CLEANUP 149
then stored in the variable L. PRINT ‘‘R JUST ="’; prints out the header that
is printed in the first eight columns of the screen.
Line 70 computes the number of colons to be printed before the number
(M) is printed. FOR J = L TO 12 outputs 13 places (0-12) and subtracts off the
length of the string. R JUST = occupies the first eight columns. The string
contains four characters, so FOR J = 4 TO 12 will print nine colons before
printing the number.
COLUMN 8,9, ... 17...21
R JUST = tiii2.34
Line 80 prints the number after the colons so all numbers are right justi-
fied. The semicolon after the M keeps the line open to print the next section
that is to justify on the decimal point.
The right justification is based on adding the number of columns oc-
cupied by R JUST =, plus the number of colons to be added to RJUST =, less
the number of columns occupied by the string. All numbers are right justi-
fied to column 21 on the screen.
Lines 90 to 130 justify by placing the decimal in column 32 and aligning
the numbers in the proper columns in relation to the decimal point.
In line 90, the power of the number is determined by the formulas in lines
5 and 6. The value of the power is stored in the variable L. The value stored
in L, shown in Fig. 21-1, is then used to determine how many places to print.
Line 100 must handle a special case when the decimal input is less than
.O1 and greater than .099 (see Case #1, Fig. 21-1). This special case is
handled by (L< —1). FOR J = L TO 8 works in all cases where L is greater
than or equal to 1. When L is less than 1, a one has to be added back to align
the decimal points.
A simpler, but less effective, method of controlling the column printout is
to use decision statements. Using N as a variable to hold the value of the
number, the decision statements are as shown in Chart 21-1.
Line 10 is the loop that sets the number of times the program is to be exe-
cuted. The number 653 was selected at random. Any number could be used.
Line 20 randomly selects the column in which the character is to be
printed. The screen has a line 40 characters long. RND returns a number
from zero to less than one. RND (1) * 39 always returns a number less than
39, from zero to 38. RND (1) * 39 + 1 always returns a number greater than
zero and less than 40. The “+1” is used to prevent the illegal value zero
from being generated. The screen has 40 columns, from 1 to 40. If the RND
function generated a zero, the program would stop and an ILLEGAL
QUANTITY error would be printed. It is important to remember the para-
meters and limits of each function.
Line 30 randomly sets the limit of the rows on the screen. The screen has
24 rows, from 1 to 24. RND (1.) * 23 + 1 sets the limit to 22 + 1 which pre-
vents the screen from scrolling while the program is running. In line 20,
RND (1) is used. In line 30, RND (1.) is used. Either 1 or 1. can be used with-
out changing the function.
The program is designed so that no character is printed at column 40, nor
is any character printed in row 24. A print at column 40, row 24 causes the
screen to scroll.
In line 40, the positive argument of RND returns a different sequence of
numbers each time. RND (1.) * 3 returns the numbers O, 1, 2. The “+1”
changes this sequence to 1, 2, and 3.
The 1, 2, or 3 generated by the program in line 40 is used by line 50 to
send the program to line 60 for L = 1, line 70 for L = 2, and line 80 forL =
3.
Line 100 prints the characters and the video mode randomly according to
VTAB I (line 20), and HTAB K (line 30). The PRINT CHR$ (RND (1.) * 25 + 65)
changes the 26 characters of the alphabet (0 — 25) + 65, from the ASCII
numeric code to the alphabetic characters.
A = 65
B = 66
C = 67
D = 68
etc.
and over. NEXT J is the last statement in the loop, and NORMAL brings the
screen back to its normal mode. The program ENDs at line 120.
There is no RUN on this program because it would be impossible to type
this hypnotic eye blinker. You have to RUN it to see and believe.
The next program introduces ONERR GOTO, POKE, PEEK, and RE-
SUME.
10 ONERR GOTO 8000
20 PRINT ‘‘DISCO KID’ : STRIKESAGAIN
30 READ D, A, B
40 DATA 1007, 34.5
50 INPUT “‘LETTER?” ;A
60 POKE 216, 0
70 NEXT J
7999 END
8000 Y = PEEK (222): L = PEEK (218) + PEEK (219) * 256
8010 IF Y = 16 THEN PRINT ‘SYNTAX ERROR IN LINE” ;L : PRINT : GOTO 30
8020 IF Y = 42 THEN PRINT “OUT OF DATA IN LINE” ;L : PRINT : GOTO 50
8030 IF Y = 254 THEN PRINT ‘‘ANSWER THE CORRECT TYPE IN LINE”’ ;L : PRINT :
RESUME
RUN
DISCO KID
SYNTAX ERROR IN LINE 20
OUT OF DATA IN LINE 30
LETTER?A (letter E — reserved for exponentiation)
ANSWER THE CORRECT TYPE IN LINE 50
LETTER?5
NEXT WITHOUT ERROR IN LINE 70
Line 10 is a declaration statement that tells the computer what to do
when an error is detected. The computer handles errors in a normal fashion
until it executes an ONERR GOTO statement. The ONERR GOTO statement
is similar to TRACE in that it affects the entire program during its execu-
tion. After an ONERR GOTO statement has been executed, anytime an error
is detected, the program branches to the line specified. The computer
remembers line 10 for all errors. This program handles three error condi-
tions. Given time, all seventeen possible errors could be placed in the pro-
gram.
Line 60 places a zero into memory location 216. POKE 216, 0 is the state-
ment that clears the error flag so that normal error messages may occur.
When information is to be placed in a specific memory location the POKE
commana is used.
In line 8000, Y = PEEK (222) returns the contents of memory location
222. The value of Y is stored in a variable to make its use easier. L = PEEK
(218) + PEEK (219) * 256 sets the value of the line number in the program
where the error occurred.
In line 8010, the number 16 is the value for the error code SYNTAX
ERROR.
CLEANUP 153
In line 8020, the number 42 is the value that prints the OUT OF DATA
error.
_ In line 8030, the number 254 is the Y value that gives a bad response to an
INPOT statement.
Pause loops cause a delay in the program to allow the user to view the
information.
GET A$ pause loops were discussed in Lesson 19.
A simple pause loop that allows the program to continue without user
participation is:
FOR P = 1 TO 10000 : NEXT P
A nested loop pause that allows the program to continue without user
participation is:
FOR N = 1TO 1000
FOR P = 1 TO 100
NEXT P, N
A pause loop (similar to GET A$) that stops the program after a certain
number of printouts, 50 in this example, and requires the user to press RE-
TURN is:
FOR! = 1 TO 1000
IF | = INT (1/50) * 50 THEN INPUT Q$
NEXT |
HTAB and VTAB are used for spacing in loops. VTAB and TAB are used
for straight spacing not in loops. HTAB, TAB, and VTAB tab from the #1
position of the column or row. SPC (6) leaves six spaces between the items.
HTAB (I*2) + 1 leaves 2 spaces between items printed and the + 1 starts
in column *1. Zero is an illegal value.
The use of VITAB and HTAB in loops is illustrated in the following pro-
gram. Line 40 prints the numbers 1 through 5 beginning in column 1 of the
screen, with two spaces between each number. This printout is used as a
reference with which to compare the spacing in line 70. Line 70 produces
similar output and spacing as line 40. Line 72 causes the first print in
column 5 rather than in column 1, with two spaces between each number.
Line 74 produces the first print in column #1 with 5 spaces between each
number. This program RUN demonstrates that the times ( *5) produces the
number of spaces between printed items, while the plus ( + 1) determines in
which column the first item is to be printed.
10 HOME
20 FORX=1TO5
30 FORI=1TO5
40 VTAB 10: HTAB (Il-1)*2 +1
50 ~=—PRINT J;
60 NEXTI1: VTAB 12
70 HTAB (X —- 1) * 2 + 1: REM: 1ST RUN
154 APPLESOFT LANGUAGE
72 REM :HTAB (X —- 1) * 2 +5:REM: 2ND RUN
74 REM :HTAB (X — 1) * 5 + 1: REM: 3RD RUN
80 ~=PRINT X;
RUN — LINE 70
() 12 3 4 5
(X) 123 4 5
RUN — LINE 72
() 123 4 5
(X) 12 3 4 5
RUN — LINE 74
(I) 1234 5
(X) 1 2 3 4 5
The following three programs produce identical spacing results. Those
results are produced by three different methods:
1. Decision statements.
2. Loops.
3. HTAB formula.
The important line in the program for overcoming zero suppression and
printing the trailing zero is line 110.
110 IF (INT (A*100 + .5) — INT (A*10 + .5)*10) = 0 THEN PRINT °'0";
156 APPLESOFT LANGUAGE
CASE COLUMN 20
3.14
380.13
1385.45
3019.08
5281.03
-
8171.30***
11689.89
15836.81
20612.04
— os
ow 26015.59
***ZERO PRINTING
Fig. 21-3. If (INT(A* 100 + .5) -— INT(A* 10 +5)*10) = 10, then Print “O”.
Line 10 sets up to round the print to two decimal places.
The rudiments of print field definition involve printing a suppressed trail-
ing zero so the printout looks normal. The technique of printing the trailing
zero reenforces the print rules of Lesson 3. To print the zero and not disrupt
the printout format the print rules must be diligently applied. The value
held in A must be printed and the line left open for the possibility of printing
a zero. If the zero is printed the line must be closed. The option to close the
line after A is printed must be valid.
CASE #1—A printed, no zero printed, line closed.
Case #2—A printed, print zero, line closed.
The simplest way to handle both cases is:
1. PRINT FN A(A);—semicolon leaves the line open.
CLEANUP 157
Category
. No tire flat 1. Continue the trip
2. One flat tire — the spare is 2. Exchange the flat and spare
usable and continue trip
3. One flat tire — the spare is . Walk for assistance
unusable
. More than one tire flat . Walk for assistance
APPROACHING THE PROBLEM 165
SET COUNT
TO ZERO
IS
LEFT FRONT
YES
: INCREMENT COUNT
FLAT ?
NOL.
IS
YES
LEFT REAR INCREMENT COUNT
Nov.
IS YES .
RIGHT REAR INCREMENT COUNT
FLAT? |
NOT.
IS
YES
RIGHT FRONT INCREMENT COUNT
FLAT ?
NO
YES ,
©
OPEN TRUNK
IS
SPARE EXCHANGE FLAT
“USABLE ? | AND THE SPARE |
WALK FOR
ASSISTANCE
| OPEN THE
END DRIVER'S DOOR _|
GET IN
CLOSE THE DOOR
These are decisions and actions involved in the thought process. Most
humans do these actions naturally, but they must be completely detailed to
the computer.
The flowchart tests to determine if the flat count is zero or greater than
one. Since the flat count starts at zero (through initialization) and there are
three situations to check, only two decision statements are necessary (This
is the same as cutting a log in three pieces — only two cuts are needed). In
the first flat count decision statement in Fig. 22-1, there are two exit deci-
sion paths. If the flat count is zero the statement is true, and the decision is
made to continue the trip home. If the flat count is not zero the statement is
false, and the exit path goes to a second decision statement. Is the flat count
greater than one? This decision statement selects the path to follow if the
flat count is one, or if the flat count is greater than one. If the flat count is
greater than one the statement is true, the exit path flows to the walk for as-
sistance action. If the flat count is greater than one the statement is false,
the exit path flows to the open the trunk action, and to another decision
statement. Is the spare tire usable? The flowchart details the conclusion,
either walk for assistance or continue the homeward journey.
Flowchart steps can be detailed or general. Fig. 22-1 has both detailed
steps (stop the car, shut off the engine, etc.) and general steps (exchange the
spare for the flat tire). A flowchart can be on many different levels. It can be
along, complicated written tool to help the programmer keep the action in
proper sequence. Or the flowchart can be so simple that the programmer
doesn't have to write it down. The flowchart can help to clarify a complex
point. It can be a step-by-step set of instructions, complete with line num-
bers, that will be followed exactly when the program is keypunched. Since
the FLAT TIRE is not a programmable problem, the flowchart is used to
keep the action in program context.
The ability to break actions into minute, detailed steps is the essence of
programming. Breaking the action into small steps helps develop the ability
to process information in the same manner as the computer.
To verify that the flowchart works properly, a table of possibilities is con-
structed. The table of possibilities, Table 22-1, follows the flowchart logic to
determine that the problem is solved correctly.
168 APPLESOFT LANGUAGE
MAND
‘o)
=o
m Qo Cr)
‘o)
a)
™™"™nNQOOOO00000000000
OOCOmm-ATIATNTANOCODODOOCO ee
™nNOOMNNOOMNNOOMTNOOMTO
TMONOTOTNONOOONOTN
COO00Omm™TTNOOOOmMmTTNOOCO
TIRE STATUS (FLAT — F, O — OKAY)
CONTINUE — C, WALK FOR ASSISTANCE — W
EXCHANGE FLAT AND SPARE — E
Over half of the thirty-two possibilities are listed in Table 22-1. The table
shows the status of four tires, the spare, and the course of action to be
taken. Table 22-1 was produced by writing down different combinations of
tire status and determining the best possible action to take. Common sense
was used to confirm the algorithm and produce the table. If the “YES” or
“NO” decisions on the flowchart had been switched, the flowchart would
give incorrect results even though the logic was correct. For correct results
to be produced from the written program, logic, flowcharts, and program
coding must be correct.
The first two lines of the table of possibilities show the four tires, the
spare, and the action to be taken. Both lines show all four tires are okay, but
the first line shows the spare is okay, and the second line shows the spare is
flat. According to logic, if all four tires are okay, the spare does not need to
be checked.
There is at least one drawback in producing a table of possibilities to
check the flowchart logic. On a complex problem, a table of possibilities
may have so many entries, it may be unusable. In that case, five or ten com-
prehensive sample situations are used to try to catch all possible errors.
APPROACHING THE PROBLEM 169
To sum up, there are three basic steps in programming. The programmer
must:
1. Be able to completely describe the situation to be set in basic instruc-
tions.
2. Be able to outline the logical progression from one step to another,
especially where decisions need to separate actions into different sec-
tions.
3. Be able to change instructions from English to equivalent computer
form by understanding what the computer can process.
LESSON 23
Program Flexibility
The only thing permanent in life is change. This also applies to programs
and programming. The banking industry is highly regulated by the govern-
ment. Although the regulations are rigid, the bank computer programs
change constantly. The bank’s needs and equipment are constantly
changed and updated. Customer's relations with the bank and customer's
Situations constantly change. The government regulations constantly
change so the bank must revise and check their programs to maintain com-
pliance. This beehive of activity affects the bank’s programmers who must
constantly revise and rewrite the programs. The programmer also must
constantly upgrade his or her education to adapt to new methods and equip-
ment.
In programming, flexibility is a key word. Is the program flexible? Can the
program be easily and quickly changed to accommodate a new input situa-
tion, a new set of government tables, or a new output format, and produce
correct results? Using a programming team, a long complex program may
take a year to write. This program should be flexible enough so minor
changes do not make the program completely obsolete.
If a mailing list program has a three line input, can a fourth line of input
be easily inserted in the program to produce a four line output?
In an inventory program, can data be input both in the alpha and numeric
modes?
In an accounts receivable program, can customer information be easily
changed without having to rewrite the program and without having to
rewrite the whole business program package?
The programs used for this example of flexibility are the computation of
federal income tax and net income. The user inputs the adjusted gross
income and the program computes the tax due and the net income. The tax
table was taken from the 1979 Tax Rate Schedule for married taxpayers fil-
Ing joint returns and qualifying widows and widowers. For simplicity, only
one tax table was used in the program. In reality, the tax rate schedule has
171
172 APPLESOFT LANGUAGE
four separate tables, (1) for single taxpayers, (2) married filing joint returns,
(3) married filing separate returns, and (4) heads of households, etc. The
point is that an accountant filing income tax returns for the general public
needs all four tables. A flexible program could be easily changed to accept
revised tables, while an inflexible program could not accept new tables
easily.
The inflexible program in this example is written with IF statements. In
this program, it would be difficult to change one table, much less four
tables. The flexible program is written with the table inserted in DATA state-
ments. The flexible program would be relatively easy to change or add to by
a simple routine.
INPGT “ADJUSTED GROSS INCOME ”;AGI
MENC
1. SINGLE TAX PAYER
2. MARRIED FILING JOINT RETURN
3. MARRIED FILING SEPARATE RETURN
4. HEAD OF HOUSEHOLD
INPUT “STATUS °;STATCUS
ON STATUS GOSUB 2000, 3000, 4000, 5000
At 2000, 3000, 4000, and 5000 the tables could be placed in DATA state-
ments similar to the flexible tax computation program.
The variables used for both programs are:
range, the adjusted gross income is tested against the next higher upper
limit value. The processing continues until the adjusted gross income is less
than the upper limit value in the range. The correct range is found when the
adjusted gross income is equal to or greater than the base figure, but is less
than the upper limit value. The correct range then sets the base tax, tax
bracket, and base figure for this range. Both the inflexible and the flexible
program process the ranges in approximately the same manner.
The flexible program gets the base figure from the upper limit value of
the previous range. If the adjusted gross income is in the first range, zero to
3400, the base figure has been initialized to zero before the processing
begins (Line 1O40-—BF = 0).
If the adjusted gross income is greater than 215,400, the upper limit
value of the next range is zero. The zero indicates there is no upper limit to
this range. The upper limit value is zero, so that range applies to any
amount greater than 215,400.
Line 1060 tests the upper limit value for zero. If line 1060 is true, the pro-
gram branches to line 1080 to compute the tax. If the upper limit value is
zero, the adjusted gross income is greater than 215,400. This sets the base
figure as 215,400. Line 1080 computes the income tax.
The inflexible program is shown first, followed by the flexible program.
995 REM: INFLEXIBLE TAX PROGRAM
1000 HOME : VTAB 3
1010 INPUT ‘ENTER ADJUSTED GROSS INCOME "';AGI
1020 IF AGI < 0 THEN END
1040 BF =0
2000 IF AGI > 3400 THEN 2020
2010 BT = 0:TB = 0:BF = 0: GOTO 7010
2020 IF AGI > 5500 THEN 2040
2030 BT = 0:TB = .14:BF = 3400: GOTO 7010
2040 IF AGI > 7600 THEN 2060
2050 BT = 294:TB = .16:BF = 5500: GOTO 7010
2060 IF AGI > 11900 THEN 2080
2070 BT = 630:TB = .18:BF = 7600: GOTO 7010
2080 IF AGI > 16000 THEN 2100
2090 BT = 1404:TB = .21:BF = 11900: GOTO 7010
2100 IF AGI > 20200 THEN 2120
2110 BT = 2265:TB = .24:BF = 16000: GOTO 7010
2120 IF AGI > 24600 THEN 2140
2130 BT = 3273:TB = .28:BF = 20200: GOTO 7010
2140 IF AGI > 29900 THEN 2160
2150 BT = 4505:TB = .32:BF = 24600: GOTO 7010
2160 IF AGI > 35200 THEN 2180
2170 BT = 6201:TB = .37:BF = 29900: GOTO 7010
2180 IF AGI > 45800 THEN 2200
2190 BT = 8162:TB = .43:BF = 35200: GOTO 7010
2200 IF AGI > 60000 THEN 2220
2210 BT = 12720:TB = .49:BF = 45800: GOTO 7010
174 APPLESOFT LANGUAGE
BUFFER
IN
POINTER
CUSTOMER'S COMPANY 101 CELLS BUFFER
ORDERS PURCHASES OUT
OUT IN POINTER
TAIL HEAD
IF Bl = BO THEN THE
Bl +1 = BO BUFFER BUFFER |S EMPTY, IF
7 EMPTY THE BUFFER CONTAINS
100 CELLS THE
POINTERS CAN BE
EQUAL AT ANY
LOCATION FROM 0 - 100
AND THE BUFFER
A Cc IS EMPTY.
The FIFO (circular list) and the LIFO (stack) give the program flexibility.
The program could be used by a company that uses either the FIFO or LIFO
inventory method.
Lines 10 through 80 DIMension the variables and set up the initial menu
to select: 0. END THE PROGRAM, 1. FIFO, or 2. LIFO.
Lines 420 through 490 process the purchasing information for the circu-
lar list (FIFO). Line 430 detects the buffer full condition (Fig. 24-1, part A).
The buffer is DIMensioned to 101 cells. DIM A$(100) was arbitrarily
selected and could have been a smaller number or any number within
usable memory limits.
When BO and BI are located in adjacent memory cells there are no empty
cells. Therefore, the buffer is full. In line 430, a special case is used when BI
= 100 (Fig. 24-1, part D). This special case is used so the circle can con-
tinue uninterrupted. The BI = 100 portion of the formula is activated when
Bl = 100.
CIRCULAR LISTS, STACKS, AND POINTERS 177
DIM A$(100)
PULL OFF 3 1 BUFFER IN POINTER
PULL OFF 2 2 BUFFERIN POINTER
PULL OFF 1 3. BUFFER IN POINTER
ACTION SERIES
IN/IN/IN/OQUT/OUT/OQUT
Bl = 0 STACK EMPTY
Bl BI
+1
5 - 15 - 79 A$(5)
$1.39 PR(5)
Fig. 24-4. Individual cell and contents.
400 AO(5)
CELL #5
Line 460 IF T < 1 THEN 490. When T is less than 1, there are items back
ordered and the subroutine at line 1020 prints out a negative value for the
number of items in inventory.
Line 470 IF T< N THEN AQ(BI) = T. If there is a back order, the next pur-
chase may not eliminate the back order. When the next purchase does not
eliminate the back order, or when the purchase equals the back order, the
purchase does not go into the buffer. If the purchase is greater than the back
180 APPLESOFT LANGUAGE
purchases do not go to inventory. If the purchases are greater than the back
order, the excess purchases are stored in N. The excess in N is compared to
T before, and T after the purchase. If T after the purchase is greater than N,
the back order is eliminated and the excess purchases go into a cell in the
buffer.
Line 800 IF BI = 0 THEN PRINT “THERE IS NO INVENTORY STOCK”.
The BI pointer is set to the top cell in the stack (Fig. 24-3). Cell number 100
is the bottom cell in the stack. The top and the bottom of the stack is a
matter of semantics. The important aspect is how the stack is filled and
emptied.
Line 800 allows the user to enter the number of items ordered by the cus-
tomer.
Line 820 IF AO(BI) > NU THEN 860. If the number of items in inventory is
greater than the number of items ordered by the customer, the program
branches to line 860 to process the order and only this cell in the stack is
reduced.
If line 820 is false, the program defaults to line 830 to print out the
number of items purchased, subtract the number from inventory (NO = Nd
— AQO(BI)), decrement the stack pointer, BI = BI — 1, and goto the next cell
to try to complete the order. The order is processed against inventory buffer
cells until the order is filled. If there is not sufficient inventory to fill the
order, all inventory buffer cells are depieted and the balance is back
ordered. T is a negative number. Line 815 T = T — NU. AO(BI) is printed
out each time the inventory is reduced by the order. NG = NU — AQO(BI) up-
dates the number of items left on order that need to be filled. If NC is greater
than AO(BI), this cell is emptied, and adjacent cells are emptied, until the
order is filled. If the order is not completely filled, and there is no remaining
inventory, the remaining items are back ordered. The logic is implemented
in lines 820 through 850.
Line 830 IF NG = O THEN 870 is true the program prints an inventory
Status report of zero items.
When all purchases and orders have been completed, the program re-
turns to line 610 to print out the LIFO ENTRY SYSTEM. Zero selection from
this menu prints out an ending inventory report, and press RETURN returns
the program to the FIFO/LIFO DEMONSTRATION menu. A zero selection
from this menu ends the program.
LESSON 25
The program written for Lesson 25 (Fig. 25-1) prepares a list of names
and telephone numbers. The list is sorted and SAVEd to tape or disk. The
list may be loaded into the program, searched for a name or fragment of a
name, and searched for an area code and a phone number. Items on the list
may be deleted. There are many techniques to sort, search, and delete
items on a list. The techniques introduced in this lesson are a basis for
further study. The variables, as they appear in the program, are shown in
Fig. 25-2. The variables are given in Fig. 25-3 in alphabetical order.
2110 \VTAB 8: GOSUB 10000: PRINT : PRINT “ENTER ‘C’ TO CHANGE, ‘D’ TO
DELETE’’: PRINT : INPUT ““ELSE ‘RETURN’ 2':Q$
2120 IF Q$<> “'C’’ AND Q$ <> "'D” THEN 2240
2125 IF Q$ = "‘D’’ THEN DA$(K) = ‘‘DELETE’’ + LEFT$ (SP$,24) + ‘(000)—
000-0000‘: GOTO 2230
2130 VTAB 12: CALL —958: VTAB 12: PRINT ‘‘ENTER ‘N’-NAME, ‘P’-PHONE#,
‘B’-BOTH” : PRINT
2140 T$ = RIGHT$ (DA$(K),14): INPUT ‘‘LETTER PLEASE ?'’:C$: IF C$ <>
“N'’ AND C$ <> 'P’’ AND C$ < > “B”’ THEN 2130
2150 IF C$ = "'P’’ THEN 2170
2160 VT = 14: GOSUB 10010
2170 IF C$ = “'N’’ THEN 2190
2180 VT = 16: GOSUB 10080
2190 IF C$ = ‘‘N’’ THEN DA$(K) = DA$(K) + T$: GOTO 2230
2200 IF C$ = “P’’ THEN DA$(K) = LEFT$(DA$(K),30)
2220 DA$(K) = DA$(K) + “(" + TCH 4 ")—""
+ LEFT$ (PT$,3) + ‘’—'' + RIGHT$ (PT$,4)
2230 CH(0) = CH(1): PRINT : INPUT “ANY MORE CORRECTIONS (Y OR N)
?''-Q$: IF Q$ = “Y" THEN 2000
2240 K = 0:FORJ = 1 TO CH(0)
2250 ‘IF LEFT$ (DA$(J),6) = ‘‘DELETE’’ THEN 2280
2260 K=K + 1:IF K = J THEN 2280
2270 DA$(K) = DA$(J):CL(K) = CLU)
2280 NEXT)
2290 CH(0) = K
2300 GOSUB 1410: GOTO 20
3000 HOME : VTAB 3: INPUT “ENTER ’S’ TO SEARCH OR ‘L’ TO LIST ?':Q$:
IF Q$ <> “'L'’ AND Q$ < > “’S"’ THEN 3000
3010 IF Q$ = ‘’S’’ THEN 3100
3030 FORJ = 1 TO CH(0)
3040 IFJ<> INT (QU — 1)/5)*5 + 1 THEN 3070
3050 IF J <> 1 THEN PRINT : INPUT “!':Q$
3060 HOME: VTAB 3
3070 =PRINT ‘‘NAME = "'; LEFT$ (DA$(),30): PRINT SPC( 7);'"PHONE # = ";
RIGHT$ (DA$(J), 14): PRINT
3080 NEXT J
3090 ~=—PRINT : INPUT ‘'!’’:Q$: GOTO 20
3100 HOME: VTAB 3: HTAB 12: PRINT ‘’SEARCH SELECTION’: PRINT
3110 HTAB 12: PRINT ‘’1.NAME SEARCH”: PRINT :HTAB 12: PRINT ‘'2.NUMBER
SEARCH": PRINT : HTAB 12: PRINT ‘‘3.RETURN TO MAIN MENU”: PRINT
3120 INPUT ‘‘ENTER SEARCH KEY ?’'; MS
3130 ON MS GOTO 3150,3250,20
3140 GOTO 3100
3150 HOME : VTAB 4: PRINT ‘’ENTER NAME OR FRAGMENT ?”: PRINT :
INPUT NA$:L = LEN (NA$): IF L = 0 THEN 3100
3160 CO = 0: FORJ = 1 TO CH(0): IF L > CLU) THEN 3220
3170 FORK =1TOCLU) —-L+1
3180 IF NA$ <> MID$ (DA$(),K,L) THEN 3210
3190 CH(1) = CH(0):CH(0) = J — 1: PRINT : GOSUB 10000: PRINT:
INPUT Q$
Fig. 25-1-cont. Program written for Lesson 25.
186 APPLESOFT LANGUAGE
CA Array used to store to, and retrieve from, tape. AS language can-
not store string arrays directly. The string arrays are converted to
the numbered equivalent to store the number. CA(K) =
ASC(MID$(DA$(J),K,1)). Lines 4010-4050. STORE CA saves the file.
RECALL CA loads the file. The file is converted into a string — DA$
= DA$ + CHR$ (CA(K)) in lines 1110 — 1150.
CH CH(0) holds the number or records in the record count.
CH(1) Temporary storage for the record count.
DA$ String in which the name, area code, and phone number are
held.
CL Length of the name string before it is padded to exactly 30
characters.
SP$ Padding string that contains 30 blank spaces.
DC$ 713. Default string holds the area code. A comma input places
713 in the area code. A different area code can be inserted by
typing in the numbers.
Ms Menu selection.
Q$ String that holds ‘’Y‘’ for yes, ‘‘N”’ for no, or ‘’R’’ for return.
RECALL CA Retrieves a real or integer array that has been STOREd on tape.
The array must be DiMensioned in the program. Subscripts are
not used when storing or recalling arrays. CA(0), CA(1), CA(2),
etc., are stored and recalled as CA. CA(45) contains 45 characters
including the padded spaces.
44 CHARACTERS NAME STRING PADDED TO 30 CHARACTERS
(713) -— 688 —- 1212 = 44 + CL = 45
13 113 «41 4 1+
30 = 45
J,K Loop variables used throughout the program.
VT Sets up VTAB VT to VTAB to different rows according to program
structure.
CL(CH(0)+1) Holds the length of the name being input before padding in rela-
tion to the length of DA$ before it was padded.
GOSUB 10010 Inputs name into the 1st part of DA$ and pads the ‘st part of the
string to 30 characters.
GOSUB 10080 Inputs area code and phone number into the last 14 characters of
DA$. PT$ = STR$(VAL(PN$)) — checks that all phone numbers are
numeric characters and not’alpha characters.
PN$ Phone number string.
TC$ Temporary area code string to check numeric character input into
area code. TC$ = STR$(VAL(AC$)).
PT$ Temporary phone number string to check numeric character in-
put into the phone number string.
PT$ = STR$(VAL(PN$)).
Ac$ Area code string. A comma defaults to DC$ = 713.
M Minimum.
NA$ Name to be changed.
GOSUB 10000 Prints out name, area code, and telephone number before it is
changed.
STORE CA Stores real or integer numbers on tape. SEE RECALL CA.
2125 Delete line—see Fig. 25-4.
CHR$(7) PRINT CHR$(7) rings the bell on the computer—CONTROL G.
CH(0) =J—1 The name and phone number are placed in CH(0) +1.
Subroutines 10010 and 10080 input name and phone number.
CO Count of the number of times a match is found on the list.
WwW WTR
Wit ml]
NO EXCHANGE M = J
Ms—M AT SORT PASS
Ma—M AFTER CHANGE
CL = length of DA$
before it is padded.
DAS(J) In this example, CL CL(J)
is always 1 character.
T$ DA$(M) DAS$(J)
ORIGINAL
Ist PASS 1st EXC T$ = DA§$(5)
2nd EXC DA$(5) = DA$(1)
3rd EXC DA$(1) = T$
2nd PASS 1st EXC T$ = DA$(4)
2nd EXC DA$(4) = DA$(2)
3rd EXC T$ = DA$(2)
3rd PASS NO EXCHANGE—3rd ITEM IS IN THE CORRECT POSITION
Ath PASS NO EXCHANGE—4th ITEM IS IN THE CORRECT POSITION
often do you remember the last name of a person but not his first name? If
the name is on the list a search will reveal it. A search allows the user to pull
one record off the list by using a keyword with which to search.
A search can be made anytime the user needs information from the
records on the list.
Deletion is the act of removing a record or records from the list (Fig.
25-5). Deleting is used to keep the file as small as possible to use the least
memory and to keep the file current. A list containing unneeded names is
nonproductive and costly to most users.
Deletions should be made anytime names on the list become of no use to
the user. If the list is for subscriptions, each name on the list costs money in
production costs, mailing costs, and labor. Nonsubscribers names on the
list should be deleted.
192 APPLESOFT LANGUAGE
FILE:
DA$(1) = “JONES (713)-688-1212”
DA$(2) = “SMITH (713)-688-1213”" CH(0) = 4
DA$(3) = ‘DELETE (000)-000-0000’
DA$(4) = ‘‘ACTION (713)-688-1214”’
FILE:
DA$(1) = ‘JONES (713)-688-1212’'
DA$(2) = ‘SMITH (713)-688-1213"'
DA$(3) = ‘ACTION (713)-688-1214""
DA$(4) = ‘ACTION (713)-688-1214”
2290 CH(0) = K (K = 3)—LAST RECORD DA$(4) IS REMOVED
Line 1 DIMensions the variables. CA(45) is the array used to store to and
retrieve from tape. The record (name and telephone number) is input as a
string array. Each record is stored as 45 numbers because the store and
recall commands do not store string arrays. The conversion is shown in
lines 4010 through 4070 in Fig. 25-1.
4010 STORE CH
Line 4010 stores the number of records to be placed on the tape. In this
case, CH(Q) = 5 (5 is an arbitrary number).
4020 FORJ = 1 TO CH(0)
Line 4020 sets the beginning of the loop that stores five records on tape
(CH(O) = 5).
4030 FOR K = 1 TO 44
Line 4030 states there are 44 characters in each record plus CL = 1. CL
stores the length of DA$ before it is padded. Thirty characters are in the
name string, including padded characters (spaces) produced by SP$§.
(713) — 688 - 1212
Therearel +3 +1+1+23+ 1+ 4+ 30 = 44 characters in DA$. CL
= 1. CLis the length of DAS before it is padded.
SORTING, SEARCHING, AND DELETING 193
30 characters in DA$
14 characters in area code (AC$) and phone number (PNS$)
1 character for CL = length of DA$ before padding.
45 = CA(45)
4040 CA(K) = ASC(MID$(CA$(J), K,1))
Line 4040 converts the string array, DA$, into ASCII characters and
places it in CA numeric array to be stored on tape.
4050 NEXT K
Line 4050 completes the conversion of one record.
4060 CA(45) = CLUJ)
In line 4060, CL is the length of DA$ before it is padded and stored in
CA(45). CL(J) is one number. One added to the 44 characters produced in
line 4020 equals 45 numbers, thus, CA(4)).
4070 STORE CA
Line 4070 stores the real array, CA, on tape. The subscript of the array is
not indicated when STORE is used. This stores all 45 values from each
record.
4080 NEXT J
Line 4080 ends the J loop. In this loop, when one record is converted to a
numeric array and stored, the next record is processed. This processing
continues until all five records have been stored.
But returning to line 1, we see that CL holds the length of DA$ (name)
before it is padded. DA$(1000) can contain 1000 records stored in DAS.
10 SP$ = “' "> SP$= SPH + SPS + SP$
Line 10 contains the string that pads DA$ (name) to 30 characters. SP$
originally contained 10 blank spaces. SP$ concatenated contains 30 blank
spaces. SP$ is used in the subroutine 10010 through 10070, partially shown
below.
10060 DA$(CH(0)+1) = DA$(CH(0)
+ 1)+LEFT$(SP$, 30-CL(CH(0)
+ 1))
10070 RETURN
194 APPLESOFT LANGUAGE
which is the area code of Houston, Texas. The default area code is used to
save input time. The area code can be input directly, or the default area
code can be input by typing a comma followed by the phone number. The
default area code can be easily changed to any area code.
10100 IF LEN (AC$) = 0 THEN AC$ = DC$
In line 10100, we see that the comma input works successfully because
everything before the comma is put in AC$ and everything after the comma
goes into PNS.
Lines 20 through 90 present the PHONE LISTING menu that asks the user
to make a selection before proceeding. Based on that selection, the com-
puter goes to different parts of the program. Line 80 tells the computer to
where it must branch: to line 1000 if item 1 (line 30) is selected, to line 2000
if item 2 (line 40) is selected, to line 3000 if item 3 (line 50) is selected, and
to line 4000 if item 4 (line 60) is selected.
Lines 1000 through 1060, selected by item 1 of the PHONE LISTING
menu, make up the FILE MAINTENANCE menu. If item 1 of the new menu
is selected (items from the FILE MAINTENANCE menu are selected when
the computer reaches line 1040), the program jumps to line 1100 to load
tape into memory. We assume for the purposes of this explanation that the
user has prepared a tape containing names and phone numbers.
Let’s follow this path of the program to line 1100. After the tape is loaded,
line 1110, RECALL CH, obtains however many records from tape that CH
designates. We set that number to 5 earlier in line 4010.
1120 IF CH(O) = O THEN PRINT ‘THERE IS NO ARRAY ON TAPE” : GOTO 1000
Line 1120 tells us if there are no records on the tape to be recalled.
1130 FOR J = 1 TO CH(0)
Line 1130 is the beginning of the loop to load the records into memory.
1140 RECALL CA
In Line 1140, RECALL CA retrieves a real array which has been stored on
tape. Subscripts are not used with STORE or RECALL.
1150 DA$ = '': FORK = 1 TO 44: DA$U) = DA$(U) + CHR$(CA(K)) :
NEXT K : CLU) = CA(45) : NEXT J
DAS = “” sets DAS to a null value. There are no characters in DAS. It is
just initialized for later use. FOR K = 1 TO 44 sets the number of characters
to be retrieved and converted from a numeric array to a string array.
DA$ = DA$ + CHR$(CA(K)) converts the numeric arrays stored on tape to
string arrays used within the program.
SORTING, SEARCHING, AND DELETING 195
NEXT K completes the loop and CLV) = CA(45) completes the transfer
from tape to RAM by adding the length of DA$ before it is padded with
spaces.
NEXT J is the end of the loop and processes until all five records have
been loaded into memory.
If we had picked item 2 of the FILE MAINTENANCE menu (line 1020), the
program would have branched to line 1200.
1200 HOME: VT = 6; GOSUB 10010
In line 1200, HOME clears the screen. VT = 6 sets the vertical tab value
that is used in the subroutine beginning at 10010.
10010 VTAB VT: CALL —958 : VTAB VT : PRINT ‘’ENTER NAME (LESS THAN 31
CHARACTERS)’’
In line 10010, VTAB VT (tabs to line 6 on the screen). CALL — 958 is a
machine language call that clears the screen below the cursor.
10020 INPUT DA$(CH(0)+ 1)
Line 10020 allows the name to be input into a specific record number.
10030 CL(CH(0)+1) = LEN(DA$(CH(0)+1)) : IF CL(CH(O)+1) = O THEN RETURN
Line 10030 stores the length of DA$ for the current record being built.
This is held in CL array of the next position available (indicated by the + 1
added to CH(0)). The second part of line 10030, IF CL(CH(O)+1) = O THEN
1000, checks to see if no record is input. If there is no record input, the
program branches to line 1000. Line 10020 is related to line 10030.
10040 _ IF CL(CH(0)+1) > 30 THEN PRINT : PRINT “’NAME IS TOO LONG”
CHR$(7) : FOR J = 1 TO 1000 : GOTO 10010
DAS (name) can be a total of 30 characters. If the length of the name
string is over 30 characters it is disallowed because the file is not designed
to hold over 30 characters in the name part of DAS.
The pause loop FOR J = 1 TO 1000 delays for the count of 1000. CHR$(7)
rings a bell on the computer to attract the user's attention and GOTO 10010
causes the program to jump to 10010 to input a name of 30 characters or
less. If the DA$ is a correct entry, the program RETURNS to line 1260,
which merely changes the value of VI and begins another subroutine.
Line 1410 says, if there is only one record, there is no need to sort the list.
Lines 1420 through 1480 perform the sort routine. In this example, there
are five records in the list (Fig. 25-4A). The five records E, D, C, B, A repre-
sent a list of names, area codes, and telephone numbers. Fig. 25-4B shows
the details of program lines 1420, 1430, 1440, 1450, 1460, and 1480. The
details of the exchange produced by line 1470 are shown in Fig. 25-4D. The
number of records in the list is CH(O) = 5.
If the length of the name string is zero, the program branches to the main
menu.
2030 FOR K = 1 TO CH(0)
Line 2030 sets the beginning of the loop to process each record on the
list.
2040 IF NA$<>LEFT$(DA$(K), CL(K)) THEN 2060
If the name string that was input does not match any name on the list then
the computer goes to line 2060.
2060 NEXT K: VTAB 10: HTAB 6: PRINT “THIS NAME IS NOT ON THE LIST” :
PRINT CHR$(7) : FORJ = 1 TO 1000 : NEXT J : GOTO 2000
If line 2040 is false, the program defaults to line 2100.
2100 CH(1) = CH(0) : CH(O) = K —1: VTAB 6: PRINT ‘“CURRENT RECORD IS "’
> PRINT
CH(1) = CH(0) stores the value of the 5 records in the list in CH(1) for tem-
porary storage. CH(0) = K —1 stores the value of the record to be changed.
Each time the loop executes, it is incremented by one greater than the loop
value. K —1 decrements the loop value to correspond to the number of
records on the list.
GOSUB 10000 prints the current record on the screen.
2110 VTAB 8 : GOSUB 10000 : PRINT : ‘‘ENTER ‘C’ TO CHANGE, ‘D’ TO
DELETE’’ : PRINT : INPUT ‘ELSE ‘RETURN’ ?’';Q$
Line 2110 sets up the record to be modified, prints the heading to change
or delete the record, and requests the user input.
cliche about cutting a log in two places to get three sticks of wood? This
example demonstrates the use of the default value in programming. ‘’B"’
was the selection, but ‘’B’’ was not written into the program. Another point
to be reenforced is, when an IF statement is true, all following statements on
that line are executed. When an IF statement is false, no following state-
ments on that line are executed.
In line 2140, the user inputs the letter “"N’’ for a name change. The pro-
gram defaults to line 2150.
2150 IF C$ = ‘’P’’ THEN 2170
The letter ‘’N"’ was input, so line 2150 is false and the program defaults to
line 2160.
2160 VT = 14: GOSUB 10010
The subroutine at 10010 asks for the name change to be input. The sub-
routine at 10010 returns to line 2170.
2170 IF C$ = ‘’N’’ THEN DA$(K) = DA$(K) + T$ : GOTO 2230
The name change is concatenated to the area code and the phone number
stored in T$. Line 2230 sets CH(0) = CH(1) and asks for more corrections. If
there are no more corrections, the number of records in the list is stored in
CH(0), the list is sorted, and the program jumps to the PHONE LISTING
menu.
- If the user inputs the letter “’P’’ in line 2140, the program defaults to line
2150.
2150 IF C$ = ‘’P’’ THEN 2170
The letter “’P’’ is input. Line 2150 is true, so the program branches to line
2170.
2170 IF C$ = *‘N’’ THEN 2190
The letter ‘‘P’’ was input. Line 2170 is false. The program defaults to line
2180.
2180 VT = 16: GOSUB 10080
GOSUB 10080 allows input of the phone number to be changed and re-
turns to line 2190.
2190 IF C$ = ‘‘N’’ THEN DAS$(K) = DA$(K) + T$ : GOTO 2230
The letter ‘‘P’' was input, so line 2190 is false and the statement GOTO
2230 is not executed. The program defaults to line 2200.
2200 IF C$ = ‘‘P’’ THEN DA$(K) = LEFT$(DA$(K),30)
Line 2200 is true and sets up DAS$(K) so it contains the name in the
specific record. The program defaults to line 2220 to concatenate the name
and new phone number into DA$(K).
SORTING, SEARCHING, AND DELETING 201
ACTION OF
J J-1 INT(J-1)/5) INT((J-—1)/5)*5+1 3040 GOES TO 3050 3050
1 O 0 1 FALSE 3050 FALSE GOES TO 3060
PRINTS RECORD #1
PRINTS RECORD #2
PRINTS RECORD #3
PRINTS RECORD #4
PRINTS RECORD #5
3050 INPUTS *‘!'";Q$
PRESS RETURN TO
CONTINUE
PRINTS RECORD #6
PRINTS RECORD #7
PRINTS RECORD #8
PRINTS RECORD #9
Selection 1 causes the program to jump to line 3150 to begin the NAME
search.
3150 HOME: VTAB 4: PRINT “ENTER NAME OR FRAGMENT ?” : PRINT :
INPUT NA$ : L = LEN(NA$) : IF L = 0 THEN 3100
The name search is processed in lines 3160 through 3220. For this
example, variables are given specific values to make the learning easier.
Lines 3160 through 3220, using variables with specific values, are de-
tailed in Fig. 25-7. Fig. 25-7 should be studied in detail to learn the name
search routine. The record count is stored in a temporary location, CH(1). In
line 3220, CH(0) = CH(1), the record count is stored in CH(0). This step is
necessary to preserve the record count. This storage process occurs before
the GOSUB 10000, and after the GOSUB 10000. Fig. 25-7 should be more
explanatory than comment.
If at line 3100, the user had input 2, ‘*2.NUMBER SEARCH”, the program
would jump to line 3250 to search for a specific phone number.
3250 HOME : VTAB 6: HTAB 6: INPUT “ENTER AREA CODE,PHONE#
2"; AC$,PN$
3260 IF LEN(AC$) = 0 THEN AC$ = DC$
Line 3260 allows the user to enter a comma for the area code, if the user
wants the default area code of 713. The area code and the phone number
are always the last 14 characters of DA$. The phone number for a specific
record is RIGHT$(DA$(J), 14).
3270 TCS = ‘*(" + ACS + “)-—" + LEFT$(PN$,3)
+ ‘'—"' + RIGHT$(PN$,4)
204 APPLESOFT LANGUAGE
Line 3270 concatenates the area code and phone number in the proper
format and stores it in the temporary string variable, TC$.
3280 FORJ = 1 TO CH(0)
Line 3280 sets up the loop that will list the area codes and phone numbers
on the list.
3290 IF TC$<>RIGHT$(DA$(J),14) THEN 3310
All phone numbers are composed of 14 numeric characters located in the
last 14 places in DA$. The TC$ was formatted in the same places in DA$ as
RIGHT$(DA$(UJ),14), so the comparison is relatively simple. It is much
simpler than the name search, though not nearly as flexible.
3300 CH(1) = CH(0) : CH(O) = J —1: GOSUB 10000 : PRINT : CH(0) = CH(1) :
INPUT Q$ : PRINT
The record count is again stored in a temporary location, CH(1), so it will
not be lost during the execution of the subroutine at line 10000. The sub-
routine prints out both the name, area code, and telephone number pro-
duced from the number search. On returning from the subroutine, the
record count is again stored in CH(O) (CH(O) = CH(1)).
3310 NEXT J
Fach record on the list is searched for the phone number in question and
line 3320, GOTO 3100, causes the program to jump to the SEARCH SELEC-
TION menu. Selection 3, “"3.RETURN TO MAIN MENU”, causes a jump to
line 20, the PHONE LISTING menu. Selection 4, ““4.SAVE LIST AND END’’,
from the PHONE LISTING menu causes the program to end.
LESSON 26
Formulas
Lesson 26 contains three programs dealing with formulas for (1) decimal
to hexadecimal conversion (Fig. 26-1), (2) hexadecimal to decimal conver-
sion (Fig. 26-6), and (3) systematic and efficient output (Fig. 26-9).
‘Formula’ has many different meanings but a good definition is “the rule
for doing something.” A formula is a recipe or a prescription. Formulas
have been tried and have been demonstrated in almost every lesson of this
book.
The computer, which understands only binary (1 and 0), must use a
formula to convert binary input and output, which are in decimal form. This
formula is invisible to you because you wont see it on your program listing.
The visible ones are the formulas you write. The invisible ones are the
formulas that your computer needs to interpret your program. The invisible
formulas reside in the Applesoft interpreter.
The most efficient way to use a formula in programming is to input the
data in a variable. The variable or variables in the formula compute the data
and output the information in a variable. In this way, the input data and the
output information can be easily changed and the program remains rela-
tively constant.
In the first program (Fig. 26-1) decimal is converted to hexadecimal. In
the second program, hexadecimal is converted to decimal. The conversion
formulas encompass two important aspects of the Apple computer: (1)
humans speak decimal and computers speak hexadecimal, before it is con-
verted to binary, and (2) decimal contains numeric characters and hexadeci-
mal contains alpha and numeric characters. In the conversion process, deci-
mal is input as numerics and converted to string arrays. In converting hexa-
decimal to decimal, the hexadecimal is input as a string array and converted
to numerics.
205
206 APPLESOFT LANGUAGE
JRUN
ENTER DECIMAL INTEGER ?863
HEX DISPLAY IS 35F
The decimal system uses a base of 10. The hexadecimal system uses a
base of 16. The decimal figure 312 means
3 * 10? = 300
+1%*10' = 10
+2* 10° = 2
312
The hexadecimal system uses the decimal numbers from O to 9 as its first
ten digits, and usesA = 10,B = 11,C = 12,D = 13,E = 14, andF = 15
as its last 5 digits (Fig. 26-2). The hexadecimal number 35F means
3 * 167 = 768
+5* 16' = 80
+F* 16° = 15
863
Fig. 26-3 shows the manual system for converting decimal to hexadeci-
mal. Fig. 26-4 details the decimal to hex conversion program statements in
relation to the manual conversion to hex. Figs. 26-2 and 26-3 should be
studied closely before going to the conversion program.
Fig. 26-2 presents the relationship between the first 15 decimal numbers
and the first 15 hexadecimal numbers.
FORMULAS 207
HEXADECIMAL DECIMAL
AU
©
-
WON
BWN
O
|
T™IMONWPWOANAUBWN
Fig. 26-2. Comparing the first sixteen hexadecimal and decimal digits.
AU
©
—
WAN
HBWN
fo)Ww
7™AMUNAWPIOYVii
A-:
=
(Ooje) N
Fig. 26-3 shows the ASCII numerics and the character strings they repre-
sent. Conversion of string arrays to numeric arrays and conversion of
numeric arrays to string arrays were discussed in Lesson 6. The sequence of
ASCII characters for ten numerics and 26 alpha characters goes from 48
through 90. The character strings represented by the ASCI! characters run
from zero to zerba (Z). Between the numeric and the alpha characters is an
intervening group of characters (58-64) that interrupt the chain of con-
tinuity. This interruption is very important to understand. It is programmed
in line 100 of Fig. 26-1. The hexadecimal number is converted into a string
array to accommodate both the alpha and numeric characters.
HEX =
HX$ = HX$ + CHR$(6 + 48 + 0) = CHR$(54)
CHR$(54) = *‘6"'
HEX = 14
HX$ = HX$ + CHR$(14 + 48 + (1*7)) = CHR$(69)
CHR$(69) = ‘’E"’
In line 50 we see HX$ =“. This means HXS$ is initialized as a null string.
Fig. 26-5 shows three loop executions by each program statement in-
volved in converting decimal 863 to hexadecimal 35F. This was done to
show how the individual loop executions compared with the manual conver-
sion.
FORMULAS 209
JRUN
ENTER HEX VALUE ?35F
DEC = 863
HEXADECIMAL
NUMBER POSITIONAL VALUE MULTIPLY BY
35F F * 169 F* 1= 15
5 * 16! 9* 16 = 80
3 * 162 3 * 256 = 768
863
Fig. 26-7. Manual system for hexadecimal to decimal conversion.
Line 40 converts the hex input string array (Q$) into a numeric variable by
the ASC function. In conjunction with the loop beginning at line 30, line 40
processes the characters one at a time.
J = 1:HEX = 3 CHR8(51)
J = 2:HEX = 5 CHRS(53)
J = 3: HEX = F CHR8(70)
If the hexadecimal character is a numeric it must be between 48 and 58. If
the hexadecimal character is an alpha character it must be between 65 and
70.
The statement THEN DEC = DEC * 16 + HX —- 48 — (HX _ 58) * 7) is
similar to the summing statement DEC = DEC + HX. This statement con-
verts from hexadecimal display input to an actual numeric number (Fig.
26-8) in that it takes the sum of the computed DEC and adds it to DEC on
each loop execution. An input display string can be converted to an actual
numeric number and display the numeric number because of machine de-
sign or configuration.
Line 50 is the end of the loop, and line 60 displays the numeric number
that has been converted from hexadecimal input.
60 PRINT ‘’DEC = "';DEC
5 HOME: VTAB 5
10 INPUT ““ENTER HEX VALUE ?"; 35F — HEX is input in a string array. It
Q$ may contain alpha and numeric
characters.
20 IF LEN(Q$) = 0 THEN END
30 DEC = 0:FORJ =1TO Initialized DEC to zero. Sets up loop to
LEN(Q$) check each character.
Converts the string array to a numeric
array one character at a time. Picks off
the 1st, 2nd, and 3rd character. ASC
numerics 48 — 58 represent the numbers
zero to 9. ASC numbers 64 — 71 repre-
sent the letters A — F, Fig. 26-3.
40 HX = ASC(MID$(Q$,J,1)) : Positional value
IF (HX > 47 AND HX < 58) OR 35F
(HX > 64 AND HX < 71) THEN 16° * 15 = 15
DEC = DEC*16+HX — 48 —-(HX > 16'* 5 = 80
58)*7 162* 3 = 768
1. DEC=0*16+51-—48-(51 > 58) 863
=3
DEC=3 (0* 7)
2. DEC=3*16+ 48-53 -(53 > 58)
=53
DEC=53 (0* 7)
3. DEC=53*16=848
+ 70 — 48 -
(70 > 58)
DEC = 863 (1 * 7) _
50 NEXT J
60 PRINT: PRINT ‘’DEC = "':DEC DEC = 863
70 GOTO 10
JRUN
RANGE # BASE TOP COUNT
0 16 11
17 32 11
33 40 4
41 48 9
Wm
=
PWN 49 56 5
OGIVE COUNT =40 OF 80 =.5%
80
70
60
30
CUMULATIVE
FREQUENCY
30
20
00
16 32 40 48 56 64 72 80 88 96100
SCORE
— since the grades are produced by the RND function, NO TWO PROGRAM
RUNS OR GRAPHS WILL BE THE SAME. The ogive does not pattern itself in
the manner of the standard distribution curve.
Line 10 provides dimensions for 17 grade ranges.
Line 30 branches to the subroutine at 800, which produces the 80 student
grades. Lines 810 through 880 place them in the proper range.
In line 800, FOR J = 1 TO 80 is the beginning of a loop to produce the 80
student grades. SG = INT (RND(1.0) * 101) produces student grades from 0
to 100. The purpose of IF SG = 0 THEN SG = 1 is as follows: If the RND func-
tion produces a student grade of zero, the grade has to be modified to fit the
program pattern. The grade ranges have no place for a grade of zero, soa
zero grade is replaced with a grade of one.
Lines 810, 830, and 850 set up to divide the ranges into four divisions, (1)
two ranges containing 16 score points each, (2) four ranges containing 8
score points each, (3) six ranges containing 4 score points each, and (4) four
ranges containing 2 score points each (Figs. 26-11 and 26-12).
If line 810, IF SG >32 THEN 830, is false the program defaults to line 820
to tabulate the grades in the first two grade ranges from zero to 32.
820 CG((SG—1)/16 + 1) = CG((SG—1)/16 + 1) + 1: GOTO 880
If line 830 is false, line 840 increments the number of grades in the proper
grade range from 33 to 64 (Fig. 26-12).
If line 850 is false, line 860 increments the number of grades in the proper
grade range from 65 to 92. If line 850 is true, line 870 increments the
number of grades in the proper grade range from 93 to 100 (Fig. 26-12).
8
8
8
8
4
4
4
4
4
4
4
2
2
2
2
NEXT J completes the loop to input 80 student grades and to place them
in the proper range limit, and RETURN causes the subroutine to return to
line 40.
40 7T=0:FORJ =17T017
The totaling variable is initialized to zero, and the 17 grade ranges are
placed in a loop structure for processing.
40 FORJ =1TO17
80 R =J: GOSUB 900: UL = RL:R=J- 1
8 —
8 =
8 =
8 =
8 =
* Ae
* A=
* Aa
* A=
* A=
* Aa
* Qa
* A=
RL = (R — 13) * 2
14-13=1%* 2= 2 94 14
15-13=2%* 2= 4 96 15
16-13=3* 2= 6 98 16
17 -13=4* 2= 8 100 17
level, it returns to line 80, UL = RL, to store the range level computed into
the upper level variable.
R = J - 1 decrements the value of the loop variable stored in R, so the
upper level and the lower level will remain at the same value. The program
jumps to line 900 (GOSUB 900) to process the range level again. When the
subroutine at line 900 returns to line 80, the range limit is incremented by 1
(LL = RL + 1), to produce the lower limit (BASE) of the grade range. Line
80 and the formula at line 900 have now produced the upper and lower
limits of the grade range from 1 to 100. The grade ranges run from one to
100, so a special case must be accommodated to produce a grade range
from zero to 100.
IF LL = 1 THEN LL = 0 converts the lower level of the first grade range
from one to zero.
90 ~=PRINT SPC(3); J : HTAB 13 : PRINT LL; : HTAB 20 : PRINT UL; :
HTAB 30 : PRINT CGU)
Line 90 prints the output information under the proper headings.
100 T = T + CG(J) : NEXTJ
T = T + CG(J) totals the number of grades in each grade range, and NEXT
J completes the loop structure, so all 17 grade ranges are produced.
218 APPLESOFT LANGUAGE
40 FORJ = 1TO17
80 R= J: GOSUB 900: UL = RL: R = J — 1: GOSUB
900 :
LL = RL +1:IFLL = 1 THENLL = 0
IF LL = 1 THEN LL = O
R* 16 — (R> 2) LL = RL + 1 Jj-1
00
©
FF
F*+
OO
HOO
HPHAHAAHA
NNNNNI
7900 RETURN
8000 FORJ = 3TO 13
8010 CF(LL + 1,J) = 0
8020 NEXT J
8030 RETURN
9000 FORJ = 1TOLL
9010 DF = DF+1/(1+1)T4J
9020 NEXTJ
9030 RETURN
PURCHASE PRICE
LAND Jo. eee 50,000
BUILDING .. ns 750,000
TOTAL PURCHASE PRICE ....................004 800,000
SALVAGE VALUE ..............0. 00.0.0. eee ee 50,000
CASH EQUITY ... 0. ee 200,000
NET OPERATINGINCOME .......................0.. 80,000 per year
OUTSIDE INCOME ................ 0.00.0... 00000. 40,000 per year
MORTGAGE
LIFE OF THELOAN ... 1.0... .. cece 25 years
INTEREST RATE ....... 0... ccc eee 12 %
ANNUAL PAYMENTS (INTEREST & PRINCIPAL) ....... 76,500
DEPRECIATION
LIFE OF THE BUILDING.............
0.0... ee 40 years
DEPRECIATION METHOD ....................0 000 200 % double declining
balance
Fig. 27-2. Cash flow and tax benefits of investment property ownership.
The cash flow program was written to be used as an investment tool, and
is being used to evaluate income situations.
The cash flow program demonstrates the power of the double subscripted
array by producing 25 rows (the length of the loan) and 14 columns. Fig.
2/-3 shows 5 rows and 14 columns of the cash flow problem. The columns
are J,1 through J,14. Columns within the array are operated on to produce
other columns. The cash flow column (J,5) is produced by subtracting the
principal (J,4) and the interest (J,3) from the net operating income (J,2).
CF(J,5) = CFU,2) — (CFU,3) + CFU,4)). Net operating income is input as NOI,
and a replacement statement is used to place NOI into CF(J,2). CFU,2) =
NOI.
224 APPLESOFT LANGUAGE
CASH
AVAILABLE
AFTER TOTAL
MORT- CASH &
GAGE AMORTI-
TAXABLE TAX TAX TAX & TAX ZATION TAX
INCOME LOSS PAYABLE SAVINGS BENEFIT BENEFITS BRACKET
1,8 1,9 J,10 J,11 J,12 J,13 J,14
0 27,000 0 11,610 15,110 19,610 32
0 24,710 0 7,907 11,407 16,447 3/7
0 22,443 0 8,304 11,804 17,449 37
0 20,186 0 7,469 10,969 17,291 37
0 17,927 0 6,633 10,133 17,214 37
0 122,266 0 41,923 59,423 88,011
The variables used in the program are shown in Fig. 27-5, as they appear
in the program. The variables in Fig. 27-6 are placed in alphabetical order.
The double declining balance depreciation constant is computed in line
320, and applied to the remaining depreciation (line 462) as each year is
incremented during the life of the loan loop.
10 YR. 10 YR.
SUMMARY OF CASH & BENEFITS TOTAL AVG. YIELD
CASH FLOW (BEFORE INCOME
TAX EFFECT) 35,000 3,500 .018
TAX SAVINGS ...............
TAX PAYABLE
SUB TOTAL 63,023
TOTAL CASH BENEFITS AFTER TAXES 98,023 9,802 .049
ADD PRINCIPAL PAID ON MORTGAGE 78,969
TOTAL CASH & AMORTIZATION BENEFITS 176,992 17,699 .088
AFTER TAXES
H1$ = Header.
H2$ = Header.
H3$ = Header.
NOI = Net operating income.
PV = Loan amount.
| = Interest rate.
LL = Life of the loan.
CA = Cost of the asset.
LA = Life of the asset.
SV = Salvage value.
CF = Cash flow array.
CF(LL + 1,?) = Holds totals for the individual column.
RD = Rate of depreciation — 200% double declining balance.
Yl = Your personal yearly income.
CE = Cash equity.
DP = 1/LA —- depreciation factor.
DEP = (RD/100)*DP — depreciation per year.
BV = Book value.
TB = Total book value.
NE = Net income.
IRS = Tax bracket — CF(VJ,14) = IRS.
AN = Annual payment on the loan.
CF(J,2) = NOI — net operating income.
1 = Yearly interest.
CF(J,3) = /1
CF(LL + 1,3) = Total interest paid for the period of analysis.
PR = Principal remaining.
CF(J,4) = PR
CF(LL + 1,4) = Total principal paid for the period analyzed.
BR = Balance remaining.
CF = Cash flow.
CF(J,5) = CF
D1 = Total depreciation for one year.
CF(J,6) = D1
CF(LL + 1,6) = Total depreciation for the period analyzed.
TB = Total book value.
CF(U,7) = Total deductions — interest and depreciation.
CF(LL + 1,7) = Total deductions for the period of analysis.
CF(J,8) = Taxable income.
CF(LL + 1,8) = Total taxable income for the period of analysis.
CF(J,9) = Tax loss.
CF(LL + 1,9) = Total tax loss for the period analyzed.
CF(J,10) = Tax payable.
CF(LL + 1,10) = Tax payable for the period analyzed.
CFU,11) = Tax savings.
CF(LL + 1,11) = Total tax savings for the period analyzed.
CF(,0) = Yearly income and tax payable — CF(J,10)
— CF(J,11)
CF(J,12) = Cash available after mortgage payments and payment of
income tax effect.
CF(LL + 1,12) Total of cash available after mortgage payments and income
tax effect for period analyzed.
CF(J,13) Total cash and amortization benefits after taxes.
CF(LL + 1,13) Total of cash and amortization benefits after taxes for the pe-
riod analyzed.
YO = Years owned.
H1$(0) = See Fig. 27-7.
H1$(15) = See Fig. 27-7.
H4(0,0) = See Fig. 27-7.
H4(15,1) = See Fig. 27-7.
NUM(N) = Number of column to be printed.
N = Number of the column.
M = NUM(QJ) = Loop variable J, placed in column array NUM, stored in the vari-
able M.
DF = Discount factor.
CF(LL + 1,13) Total of cash and amortization benefits after taxes for the pe-
riod analyzed.
CF(J,14) = IRS = tax bracket.
DEP = (RD/100)*DP — depreciation for one year.
DP = 1/LA — depreciation factor.
D1 = Total depreciation for one year.
H1i$ = Header.
H2$ = Header.
H3$ = Header.
H1$(?) = See Fig. 27-7.
H4(0,0) = See Fig. 27-7.
J = Loop variable — FORJ = 1TON
LA = Life of the asset.
LL = Life of the loan.
M = NUMU) = Loop variable J, placed in array column NUM, stored in the vari-
able M.
N = Number of the column.
NOI = Net operating income.
NUM(N) = Number of the column to be printed.
PR = Principal remaining.
PV = Loan amount.
RD = Rate of depreciation — 200% double declining balance.
SV = Salvage value.
TB = Total book value.
YI = Your personal yearly income.
YO = Years owned.
H4(5,0)= 4
RELATES TO H1$(5)
H4(5,1)=4
arrays and the numeric arrays are related. The first subscript in the numeric
array relates to the string array, and the second subscript relates to the line
of the header. Some of the two line headers are incorrectly separated, as in
(H1$(6) — TOT. DEPRE---CIATION), but the technique produces the correct
results.
The logic of the algorithm stores the values to indicate a one line header
(H4(0,0)=6 — H4(0,1)=0) or a two line header (H4(5,0)=4 — H4(5,1)=4),
and indicates how many characters are contained in the first line and how
many characters are contained in the second line.
After all fifteen values are set, line 970 clears the screen and prints TABLE
LISTING and ENTER 3 VALUES FOR TABLE PRINT.
Line 980 prints the menu selection.
Line 990 sets up a loop to output to the screen three columns (0 to 2). The
user inputs the number of the column in a single subscripted array and the
array is checked to determine if it is between 1 and 15. If the column num-
ber is not between 1 and 15, the program jumps out of the loop to line 1010.
In line 1010, N = N — 1 decrements the column number to produce the
correct value of N. When the program jumps out of the loop, the loop value
is one more than the correct value. To produce the correct value of N, one
must be subtracted. This was discussed in Lesson 6.
If N< 0 THEN 3000. When the user is through working with the program,
an input of — 1 (less than zero) causes a branch to line 3000 to end the pro-
gram.
DOUBLE SUBSCRIPTED ARRAYS 229
LENGTH LENGTH OF
H1$ 1st LINE 2nd LINE 1st LINE 2nd LINE
H1$(0)=*' O.INCOME’’ INCOME NONE H4(0,0)=6 H4(0,1)=0
H1$(1)="" 1.TAX PAYABLE*’’ TAX PAYABLE H4(1,0)=3 H4(1,1)=7
H1$(2)=‘' 2.NET OP
INCOME” NET OP INCOME H4(2,0)=6 H4(2,1)=6
H1$(3)=‘" 3.INTEREST”’ INTEREST NONE H4(3,0)=8 H4(3,1)=0
H1$(4)=‘' 4.PRINCIPAL’’ PRINCIPAL NONE H4(4,0)=9 H4(4,1)=0
H1$(5)=‘' 5.CASH FLOW CASH FLOW H4(5,0)=4 H4(5,1)=4
H1$(6)="' 6.TOT
DEPRECIATION’ TOT DEPRECIATION H4(6,0)=9 H4(6,1)=7
H1$(7)="' 7.INC TAX
DEDUCTS"” INC TAX DEDUCTS H4(7,0)=7 H4(7,1)=7
H1$(8)="' 8.TAXABLE INC.’ TAXABLE _ INC. H4(8,0)=7 H4(8,1)=4
H1$(9)="’ 9.TAXABLE LOSS’’ TAXABLE LOSS H4(9,0)=7 H4(9,1)=4
H1$(10) =‘'10.TAX PAYABLE" TAX PAYABLE H4(10,0)=3 H4(10,0)=7
H1$(11)=‘'11.TAX SAVINGS” TAX SAVINGS. H4(11,0)=3 H4(11,1)=7
H1$(12)=‘'12.CASH
AVAILABLE”’ CASH AVAILABLE H4(12,0)=4 H4(12,1)=9
H1$(13) =‘'13.TOTAL
BENEFITS”’ TOTAL BENEFITS H4(13,0)=5 H4(13,1)=8
H1$(14) =''14.TAX BRACKET’’ TAX BRACKET H4(14,0)=3 H4(14,1)=7
H1$(15) =‘'15. ANNUAL
PAYMENT’ ANNUAL PAYMENT H4(15,0)=6 H4(15,1)=7
‘
Tst LINE OF HEADER 2nd LINE OF HEADER
5,0) =4 H4(5,1)
RELATED TO H1$(5)
Line 1020 is the beginning of the loop to compute the values in the
tables. LL is the variable used to hold the life of the loan value.
Program statements similar to lines 1030 and 1040 are detailed in Fig.
25-6 in Lesson 25, Line 1030 computes when 15 years of the table have
been printed on the screen.
The only function of line 1040 is to stop the program. On the first loop
pass L = 1. The program defaults through 1030, 1040, and prints the head-
ings in 1050 and 1060. On each subsequent loop pass, the program
branches from 1030 to 1080. When line 1030 is false the program defaults
to line 1040. If L is not one (L = 16) the program inputs ‘!"’ and stops. This
allows the user to view and study the 15 rows of the tables printed on the
screen. When the user is ready for the program to resume, RETURN is
pressed.
Line 1050 prints the first line of the column header on the screen and
clears the screen. In line 1050, N is the variable that holds the number of
columns, and HTAB (UJ + 1)* 10 sets the column in the correct position on
the screen. The column value is stored in the variable M.
HEADER ARRAY
COLUMN VALUE|
RELATED TO H1$(M)
In line 1060, second line of the header is printed. N is the variable that
holds the number of columns. The value of the column is placed in the vari-
able M.
When the column headings have been printed, the program defaults to
line 1080 to print L, which represents the year. The second statement in line
1080, FORJ = OTON, is the beginning of a loop that controls the number of
columns to be printed. Line 1090 tabs to the proper location on the screen
to print the columns. M = NUMU) stores the number of the column to be
printed in the variable M.
DOUBLE SUBSCRIPTED ARRAYS 231
RELATED TO 2nd
LINE OF H4(M,1)
IF THERE ISA
2nd LINE
RELATED TO H1$(M)
HEADER STRING
HEADER ARRAY
COLUMN VALUE
If line 1090 is true, the program branches to line 1110 to print out the
rounded (line 140) cash flow array values for row L, column M. If M = 14 is
false, the program defaults to line 1095. If line 1095 is true, the program
branches to line 1100 to print out the integer function (line 145) of the cash
flow array, row L, column M. If M <> 15 is false, the program defaults to line
1096. FNA (AN) is the integer (line 145) cash flow array of the annual pay-
ment. The annual payment on the loan is computed by dividing the loan
value by the discount factor (line 380), and is not computed by the loop
execution and placed in the table.
The SGN function (Fig. 27-9) is used in line 545. The SGN function re-
turns only three values +1, 0, and — 1. These values relate to greater than
zero, zero, or less than zero. In this case, if the tax loss is a positive number,
SGN(CF(J,9) ) = + 1, (SGN(CF(J,9) ) -— 1) = 0, and zero times CF(J,9)/2 =
zero. When the tax loss is a negative number, (SGN(CF(J,9) ) -— 1) = -2.
When —2 is multiplied by a negative (CF(J,9) /2, the factor (—2 /+2)
divides out leaving a negative value. A negative times a negative is a posi-
tive value. The purpose of the SGN function is to make all negative numbers
positive, leave zero numbers zero, and make all positive numbers zero. The
SGN function is used so a tax loss, which is a negative number, can be con-
verted into a positive number. The positive number is then multiplied by the
previous year’s tax rate, (CF(J — 1, 14) ), and the results are placed in the tax
savings column, CF(J,11).
CF(J-—1, 14) gives the tax rate for the previous year which is used to com-
pute this year’s taxes. CF(J, 14) gives the tax rate for the present year.
The cash flow program outputs the cash flow, tax benefits, and yields for
a single year or anumber of years. This information assists the prospective
buyer in determining how the purchase will affect his cash flow and future
net worth. This information will aid with the decision to buy the property or
not to buy the property.
232 APPLESOFT LANGUAGE
| Y COORDINATE
| QUADRANT|
X COORDINATE
TEXT SCREEN
QUADRANT I
GRAPHICS
SPLIT SCREEN
40
42 POKE — 16302,0
The full text mode has 24 rows, 1 to 24, and 40 columns, O to 39, to dis-
play text on the screen.
The split screen graphics mode contains 40 X positions, O to 39, and 40 Y
positions, 0 to 39, leaving four rows for text. The text rows are 21, 22, 23,
and 24. Each two rows of graphics equals one row of text.
The full screen graphics mode contains 40 X positions, 0 to 39, and 48 Y
positions, O to 47. In the full screen graphics mode, one X position is the
same width as one column of text, but one Y position is equal to one-half
row of text, Fig. 28-1, and Fig. 28-2.
Fig. 28-3 lists the low resolution graphics commands and statements.
Fig. 28-4 lists the color names and related values used in low resolution
graphics.
The LO-RES EXPLAINER program (Fig. 28-5) was written to explain and
demonstrate the use of low resolution graphics.
GRAPHICS 23/7
0 BLACK 8 BROWN
1 MAGENTA 9 ORANGE
2 DARK BLUE 10 GREY
3 PURPLE 11 PINK
4 DARK GREEN 12 GREEN
) GREY 13 YELLOW
6 MEDIUM BLUE 14 AQUA
7 LIGHT BLUE 15 WHITE
Fig. 28-4. Low resolution graphics color names and related numbers.
HOME : VTAB 10
HTAB 12: PRINT “‘LO-RES EXPLAINER”’
PRINT : PRINT
GOSUB 1000
GR : VTAB 21: PRINT ‘'——————— THIS IS THE BOTTOM
GOSUB 1000
TEXT : GOSUB 1000: GR
COLOR= 15: PLOT 0,0: PLOT 39, 0: GOSUB 1000
COLOR= 1: PLOT 0,39: PLOT 39, 39: GOSUB 1000
COLOR= 11: HLIN 2,37 AT 0: GOSUB 1000
HLIN 2,37 AT 39: GOSUB 1000
COLOR= 12: VLIN 2,37 AT 0: GOSUB 1000
VLIN 2,37 AT 39: GOSUB 1000
FOR K = 1 TO 4: GOSUB 1000: NEXT K
FOR X = 2 TO 36: COLOR= X — INT (X / 16) * 16
PLOT X,(37 — .122 * (K —- 19)t 2)
NEXT X: VTAB 22: HTAB 2: PRINT ‘'GRAPH OF Y = —.122 * (K-19) t
2 + 37°’: GOSUB 1000: GOSUB 1000: GOSUB 1000
PLOT 15,47: GOSUB 1000
POKE — 16302,0: GOSUB 1000
COLOR= 0
FOR K = 40 TO 47: HLIN 0,39 AT K: NEXT K: GOSUB 1000
COLOR= 1: VLIN 42,46 AT 0: HLIN 1,2 AT 41: HLIN 1,2 AT 47: VLIN
45,46 AT 3: PLOT 3,42: PLOT 2,44
COLOR= 3: VLIN 42,47 AT 5: HLIN 6,7 AT 41: VLIN 42,43 AT 8: HLIN
6,7 AT 44: PLOT 6,45: PLOT 7,46: PLOT 8,47
COLOR= 5: VLIN 42,47 AT 10: HLIN 11,12 AT 41: VLIN 42,47 AT 13:
HLIN 11,12 AT 44
COLOR= 7: VLIN 42,47 AT 15: HLIN 16,17 AT 41: VLIN 42,43 AT 18:
HLIN 16,17 AT 44
COLOR= 9: VLIN 41,47 AT 20: HLIN 21,22 AT 44: VLIN 41,47 AT 23
COLOR= 11: HLIN 25,27 AT 41: VLIN 42,47 AT 26: HLIN 25,27 AT 47
COLOR= 13: VLIN 42,46 AT 29: HLIN 30,31 AT 41: PLOT 32,42: VLIN
45,46 AT 32: HLIN 30,31 AT 47
COLOR= 15: HLIN 35,37 AT 41: HLIN 35,37 AT 47: PLOT 34,46: PLOT
38,46: PLOT 37,45: PLOT 36,44: PLOT 35,43: PLOT 34,42: PLOT 38,42
When the Apple computer is turned on, it comes up in the text mode. To
change the TEXT mode, GR is typed on the screen as an immediate execu-
tion, or GR is placed in a program statement to be executed in the deferred
mode. GR mode comes up with COLOR = O (black). The color must be
changed before a PLOT, VLIN, or HLIN execution. If the color is not
designated, it remains the same color as previously set.
line 10 clears the screen and VTAB’s to row 10 on the screen.
Line 20 indicates the program content.
Line 40 is a pause loop to allow the user time to view the printout. GOSUB
1000 is used throughout the program, and will not be mentioned again dur-
ing the discussion.
Line 50 sets the graphics mode and VTAB’s to line 21, which is the first
usable line inthe TEXT portion of the screen, and prints the line in the print
statement. This line remains on the screen as a reminder of the beginning of
the first portion of usable text, in split screen graphics.
Line 70 places the screen in the text mode and returns it to the GRaphics
mode to demonstrate what a graph looks like when the screen is changed
back to text.
In line 80, COLOR = 15 sets the color to white before the square is
colored. The computer retains the color designation in memory and sets all
lines and squares to that color, until the color designation is changed (Fig.
28-4),
PLOT 0,0 in line 80 sets the square at column QO, row 0 to white. The
column value is the first digit or digits, and the row value is the second digit
or digits (Fig. 28-6). PLOT 0,0 and PLOT 39,0 cause two white squares to be
placed at the outermost positions on the top row (Fig. 28-6).
In line 90, the color is changed to magenta (COLOR = 1), and PLOT 0,39
and PLOT 39,39 place two magenta squares on the outermost position of the
split screen graphics.
In line 100, the color is changed to pink and a horizontal line is drawn
from column 2 to column 37 at row O, across the top of the screen (Fig.
28-6). HLIN is the statement for a horizontal line.
Line 110 draws a horizontal line at row 39, across the bottom of the
screen. The line is pink.
In line 120, the color is changed to green, and a vertical line is drawn from
row 2 to row 37 at column zero. VLIN sets the column value to color the
GRAPHICS 239
The Apple screen is located in quadrant | of the graph. However, the nega-
tive Y and positive Y axes are reversed. This causes the Apple screen to bea
mirror image of quadrant | (Fig. 28-8).
Plotting Y = (X — 19) (Fig. 28-10) produces a graph with its apex point-
ing up, and the graph is centered on the screen. The graph has been moved
nineteen X positions to the right on the positive X axis.
The remaining usable screen is between the line 2,0 to 37,0, and the line
2,37 to 37,37 (Lines and squares created by the program fill the screen at
0,0 to 39,0, and 0,39 to 39,39). To fit the graph into the usable screen space,
the graph must be sized to the screen. We do this using the sizing factor. SF
stands for sizing factor.
LEFT EDGE SIZING FACTOR
37 = SF * (2 — 19) = 17? = 289
SF = 37/289 = .128
RIGHT EDGE SIZING FACTOR
37 = SF * (37 — 19)? = 187 = 324
SF = 37/324 = .114
The two sizing factors are averaged, (.128 + .114)/2 = .122, and the
constant .122 is the figure we use to size the graph vertically. The formula is
changed to include the sizing constant, Y = .122 * (X — 19)* (Fig. 28-11).
The next step is to place the apex of the parabola towards the bottom of
the screen. To invert the graph, a negative sign is placed before .122. The
formula, Y = —.122 *(X — 19)’, is shown in Fig. 28-12. The formula places
242 APPLESOFT LANGUAGE
the apex toward the bottom of the screen. The negative sign causes the
graph to disappear from the screen because it shifts to the true quadrant I.
The formula in Fig. 28-14 is coded to plot the graph. The program state-
ment at line 160 causes the parabola to be graphed on the screen with its
apex pointing down, thus solving the problem.
Line 170 completes the plot of the graph. VTAB 22 : HTAB 2 sets the loca-
tion for the print statement. GRAPH of Y = —.122 * (X -— 19) A 2) + 37 is
printed on line 22 of the TEXT area of the split screen graph (Fig. 28-6).
Line 180 plots the square at 15,47. The square is plotted inthe TEXT area
of the screen and shows as a light "@".
Line 190 causes the display to go to full screen graphics.
Line 200 sets the color to black.
Line 210 blacks out horizontal lines in the full screen graphics from lines
40 to 47.
Lines 220 through 360 produce the word GRAPHICS, each letter in a dif-
ferent color, at the bottom of the screen in lines 40 to 47 (Fig. 28-15).
40
At
42
43
46
47
48
Line 950 is a long pause loop. It gives the user time to view the demon-
stration.
In line 960, POKE — 16301,0 switches display from graphics mode back to
text mode. HOME clears the screen. VTAB 22 tabs to line 22 to print THAT’S
ALL.
The second program in Lesson 28 is OGIVE (Fig. 28-16). In Lesson 26,
FORMUCLAS, the OGIVE program was presented. The program randomly
input 80 student grades and placed them in 17 ranges. The output was infor-
mation on which to make an ogive of cumulative distribution. Lesson 28
adds graphics to the original program so the ogive is printed on the screen.
Lines 130 through 700 (Fig. 28-16) produce and print the ogiveon the
screen.
244 APPLESOFT LANGUAGE
In line 130 GR sets the split screen graphics mode. HOME clears the
screen. COLOR = 1 sets the color to white.
VLIN 0,39 AT O draws a vertical line in column zero. HLIN 2,39 AT 39 draws
a horizontal line at row 39. These lines highlight the left side and bottom
area in which the ogive is placed (Flg. 26-10). The student grades are ran-
domly input, so no two ogives will be the same.
GRAPHICS 245
~ Y¥COORDINATE
QUADRANT |
X COORDINATE
TEXT SCREEN
QUADRANT I!
Fig. 29-1. Text screen.
249
250 APPLESOFT LANGUAGE
resolution graphics rows represent one text row. There are 20 text rows and
160 graphics rows.
The full screen high resolution screen (Fig. 29-2) contains 280 columns
(0,279) and 192 rows (0,191).
159,279
160 — 167
HGR 2 — FULL SCREEN
192 X 280
0,191 191,279
The high resolution graphics screen is divided into two distinct sets of
lines. There are columns with odd numbered lines and columns with even
numbered lines. The color statement (HCOLOR = ) is related to the odd-
even line system. The odd number lines are colored by the odd numbered
colors (Fig. 29-3) and the even numbered lines are colored by the even num-
bered colors.
Fig. 29-3. High resolution graphics color names and related numbers.
Two programs are presented in Lesson 29, (1) HI-RES EXPLAINER (Fig.
29-7) and (2) ORBITAL WAR GAME (Fig. 29-9).
The HI-RES EXPLAINER details the use of the high resolution graphics
commands and statements (Fig. 29-4).
HIGH RESOLUTION GRAPHICS 251
Line 10 of the HI-RES EXPLAINER sets the TEXT mode, clears the
screen, and places the HI-RES EXPLAINER PROGRAM in the center of the
screen.
10 TEXT: HOME : VTAB 8: PRINT ‘’ HI - RES EXPLAINER PROGRAM”
20 GOSUB 1000 : HOME : HGR: VTAB 21 : PRINT ‘’-------- THIS IS
THE BOTTOM LINE-------- i.
In line 20, GOSUB 1000 is a delay loop to allow the user time to view the
results as the program progresses. HOME clears the screen. HGR is the
statement that places the screen in high resolution split screen’ graphics
(most high resolution graphics statements are prefaced with the letter “H”
to distinguish them from low resolution graphics statements). THIS IS THE
BOTTOM LINE is printed at line 21 in the text section of the graphics screen.
Line 20 is not usable because of computer design.
Lines 30 through 34 set up the basic data to plot rectangles, one in each
corner of the screen (Fig. 29-5).
252 APPLESOFT LANGUAGE
0,0
XP +2 =3
YP + =
PRINTS AS PRINTS AS
YP +2=2 YP= 0
GOES TO GOES TO
YP = 0 YP+2=2
XP = 1 XP +2 =
YP+2=2 YP+2=
31 XP = 1: YP = 0: GOTO 40
40 HCOLOR = 1: HPLOT XP,YP TO XP + 2,YP TO XP + 2,YP + 2 TO
XP,YP + 2, TO XP,YP : NEXT J : GOSUB 1000
271,157
9,158 271,158
9,159 c 271 186
33 34
160
- 167
168
- 175
176
- 183
184
- 191
Line 70 causes the graph of a parabola to be sized and printed, with its
apex toward the top of the screen. The parabola at line 70 is printed in the
upper half of the screen. Steps similar to those in Lesson 26 are used to size
and print the graph of the parabola.
HPLOT 9,79 designates the location of the first dot to be printed in the
graph. FOR J = 0 TO 130 prints 131 dots in the graph (Fig. 29-7).
X = J*2 + 11 is the formula used to compute the value along the X axis.
When J = O, the second dot is placed at 11, along the X axis. The first dot is
plotted at HPLOT 9,79. The last value of X is equal to 130*2 + 11 = 271.
The value along the Y axis is plotted by the formula INT(((( X — 139)A2)*
.00435)+ 4.5). The graph is plotted in the center of the screen by dividing
the range (0,279) by 2 = 139. The center of the X axis is X — 139.
The graph is sized to the usable space between columns 9 and 271, and
rows 4 to 79. The Y range = 7/5.
HIGH RESOLUTION GRAPHICS 255
X = 9:(9-139)2 * CONSTANT = 75
CONSTANT = 75/(130)2 = .00437
The constant, .004437 is reduced by guesstimate to .00435 to make
sure the graph does not extend past the screen limits. The formula is now
Y = (X — 139)? * 00435.
Vertical lines are printed along the left side of the screen to form a border.
Three vertical lines are printed from row 5 to 154, at columns 0, 1, and 2.
The left edge of the parabola starts at column 4. The 4 is added to the
formula.
Y = (X —- 139)? * .00435 + 4
To make sure the integer function is always rounded properly, .5 is added
to the formula. The final formula is
Y = (X — 139)? * .00435 + 4.5.
The formula is converted to a program statement, and the data is in Fig.
29-8.
J J*2411 — INT(((X—139)t2)*.00435)
+ 4.5)
74 159 6
75 161 6
76 163 7
77 165 7
78 167 7
79 169 8
80 171 8
81 173 9
82 175 10
83 177 10
84 179 11
85 181 12
86 183 12
87 185 13
88 187 14
89 189 15
90 191 16
91 193 17
92 195 18
93 197 19
94 199 20
95 201 21
96 203 22
97 205 23
98 207 24
99 209 25
100 211 27
101 213 28
102 215 29
103 217 30
104 219 32
105 221 33
106 223 35
107 225 36
108 227 38
109 229 39
110 231 A
111 233 42
112 235 44
113 237 46
114 239 48
115 241 49
116 243 51
117 245 53
118 247 55
119 249 57
120 251 59
121 253 61
Fig. 29-8-—cont. Data to plot graph.
258 APPLESOFT LANGUAGE
J J*2411 — INT(((X—139)t2)*.00435)
+ 4.5)
122 255 63
123 257 65
124 259 67
125 261 69
126 263 71
127 265 73
128 267 75
129 269 78
130 271 80
Fig. 29-8 — cont. Data to plot graph.
Line 80 VTAB's to row 22 and prints out the formula used to graph the
parabola.
90 FORJ = 129 TOO STEP —1: X = J*¥2 + 9: HPLOT TO X,
(INT(151 — ((X — 139) A 2) * .00435 + 4.5)) : NEXT J
Line 90 prints the graph of a parabola starting from the right hand side of
the screen. The parabola is in the lower half of the screen, with its apex
pointing down. FORJ = 129 TOO STEP —1, joins point 130,261 and plots the
graph clockwise to point 4,6.
100 VTAB 23: PRINT ’’PLOT: Y = 151 — .00435*(X-—139) A2 + 4.5”
; : GOSUB 1000
Line 100 VTAB’s to row 23 and prints out the formula to graph the
parabola in the lower half of the screen. |
Line 110 causes lines to be printed from the upper graph boundary,
through the center of the screen, to the lower graph boundary. The loop
causes 129 points to be plotted beginning at the junction of the graphs on
the left to the junction of the graphs on the right. Two sets of X points are
computed and plotted, X and X2. X is the point on the boundary of the
upper graph. X2 is the point on the boundary of the lower graph.
Two sets of Y points are computed, Y and Y2. Y is the point on the
boundary of the upper graph. Y2 is the point on the boundary of the lower
graph.
The two points, X,Y and X2,Y2, are the opposite ends of a series of clock-
wise lines filling the interior of the two graphs.
HIGH RESOLUTION GRAPHICS 259
X=J*2+9
Y = (((X — 139) A 2) * .00435 + 4.5)
X2 = 271 —J* 2
Y2 = INT (151 — ((X — 139) A 2) * .00435 + 4.5)
HPLOT X,Y TO X2,Y2 plots the lines related to the FOR J = 1 TO 129 STEP
2 loop.
The second program written for Lesson 29 is called ORBITAL WAR
GAME (Fig. 29-9). The game runs only on Apple computers with Applesoft in
ROM. It can be loaded from tape and saved to tape. The shape tables are
written into the program in data statements. The information necessary to
create and save shape tables is found in Applesoft Basic Programming
Manual, pages 91 to 100, published by Apple Computer Inc.®
150 IF ABS (VS(1,4) + SD(1,1,0) — WU,1) — SD(2,1,0)) < 9 AND ABS (VS(1,5)
+ S§D(1,1,1) - WQU,2) — SD(2,1,1)) < 5 THEN VS(1,0) = — 1: VTAB 24:
HTAB 1: PRINT ‘INTRUDER DESTROYED”’;:VS(1,16) = 0:DC = DC + 1:
GOTO 475
170 NEXT :VS(0,15) = PDL (0) * C(0,5):VS(0,14) = VS(0,14) + VS(0,8):
VTAB 23: HTAB 17: PRINT INT (VS(0,15) * C(1,5) + .5); SPC( 3);: RETURN
390 HCOLOR= 0: DRAW 4 AT W(4,1), W(4,2): IF VS(1,15) > VS(1,14) OR
VS(1,0) < 1 THEN W(4,3) = C(0,4):W(4,4) = C(1,4): FOR J = 0 TO 300:
NEXT : RETURN
VS(1,8) = (1 — VS(1,15) < VS(1,13)) * ((VS(1,15) - VS(1,13)) /
(VS(1,14) — VS(1,13))):W(4,5) = VS(1,6) — VS(0,6): IF ABS (W(4,5)) < .001
THEN W(4,5) = C(0,6) + (VS(1,7) > VS(O,7)) * Pl: GOTO 420
W(4,5) = ATN ((VS(1,7) — VS(0,7)) / W(4,5)) + (VS(1,6) > VS(0,6)) * PI
W(4,5) = W(4,5) + ( -1) tf INT (RND (1) + .5) * RND (1) * VS(1,8)
* PL / 5:W(4,6) = VS(1,15) + ( -— 1) TINT (RND (1) + .5) * RND
(1) * VS(1,8) * (VS(1,14) — VS(1,15))
W(4,3) = VS(1,6) + COS (W(4,5)) * W(4,6):W(4,4) = VS(1,7) + SIN
(W(4,5)) * W(4,6): IF W(4,3) < C(0,3) OR W(4,3) > C(0,4) OR W(4,4) <
C(1,3) OR W(4,4) > C(1,4) THEN FOR J = 0 TO 55: NEXT J: RETURN
FOR J = 1TO 6: HCOLOR= J — INT UJ / 2) * 2: HPLOT VS(1,6) +
SD(2,0,0),VS(1,7) + SD(2,0,1) TO W(4,3),W(4,4): NEXT : HCOLOR= 1:
DRAW 4 AT W(4,3),W(4,4):W(4,1) = W(4,3):W(4,2) = W(4,4)
VS(1,8) = SQR ((W(4,3) — (VS(0,6) + SD(0,1,0))) t2 + (W(4,4) -
(VS(0,7) + SD(0,1,1))) * 2)
VS(0,14) = VS(0,14) — (VS(1,14) — INT (VS(1,8))) * 6: IF VS(0,14) > 0
THEN 480
VTAB 24: HTAB 1: PRINT ‘‘DEFENDER DESTROYED ”’::
VS(0,0) = — 1:VS(0,16) = 0:VS(0,14) = 0:VS(0,8) = O:IC = IC + 1
HCOLOR= 0: DRAW 4 AT W(4,1),W(4,2): RETURN
W(4,3) = C(0,4):W(4,4) = C(1,4): RETURN
GOSUB 140
GOSUB 10: VTAB 22: HTAB 15: PRINT VS(0,14); SPC( 2);: HTAB 34: PRINT
INT (VS(1,15) + .5); SPC( 3);
IF VS(0,0) + VS(1,0) = 2 AND PEEK ( — 16287) > 127 AND VS(0,14) >
VS(0,13) THEN GOSUB 50: GOTO 740
GOSUB 100
GOSUB 140: IF VS(0,0) + VS(1,0) = 2 THEN GOSUB 390
IF VS(0,16) < 5 AND VS(1,16) < 5 THEN 610
IF VS(0,0) < 0 THEN VS(0,0) = 0
IF VS(1,0) < 0 THEN VS(1,0) = 0
FOR K = 0 TO 7: GOSUB 10: FOR D = 1 TO 500: NEXT D,K
RETURN
DIM VS(1,16),W(4,7): POKE 232,0: POKE 233,3:J = 0: SCALE= 1: ROT=
0:K =0
DIM C(1,6),SD(3,1,1),OV(1): Pl = 3.14159
FOR J = 0 TO 3: FOR K = 0TO 1: FORL = 0 TO 1: READ SDU,K,L):
NEXT L,K,J
FOR K = 0T0 1: FOR J = 0 TO 4: READ C(K,J): NEXT J,K: READ
C(0,5),C(1,5)
1040 OV(1) = 5 /57.2958:0V(0) = OV(1) / 1.5435
The program will not be explained in detail because this is the final
examination. The lessons in the book give sufficient information and detail
for all the sharp students to replicate the program. This program draws on
logic, graphics, mathematics, science, and programming ability to create
an interesting game.
The program creates four shapes: defender, intruder, defender’s missiles,
and intruder's space rays. The defender and intruder move in either of two
randomly selected orbits, an inner orbit, and an outer orbit.
The defender has four missiles to fire at the intruder that are controlled
and fired by the player through game paddle zero (Q). Each missile is
replenished when it leaves the screen, so the defender has an unlimited
number of missiles, within a controlled time frame.
The intruder automatically fires its space rays when the defender is in
range. The invader has an unlimited number of space rays to fire, but they
are only effective within a specified range.
The game ends when either adversary has five kills.
The game is written entirely in Applesoft BASIC for teaching purposes. In
Applesoft the game is a bit slow. If the orbital and firing routines were
written in assembly language, the game would be faster.
The variables in the program are shown in Fig. 29-10.
Line 2 GOSUB 1600 causes the shape tables to be loaded into memory.
1600 FOR K = 768 TO 1000: READ J: IF J = —1 THEN 1840
1610 POKE K, J: NEXT K : GOTO 1840
Line 1600 sets up the number of memory addresses (decimal) into which
the shape table data is placed. READ J reads the data.
HIGH RESOLUTION GRAPHICS 263
CONSTANTS
Orbit values — 2 orbits
DIM C(1,6)
C(A,B)
xX range
Y range
c(0,0), €(0,1), €(1,0), and C(1,1) = orbit values
(SCREEN LIMITS)
C(A,B)
A = 0 = X axis value
A = 1 = Y axis value
B = 2 = offset
B = 3 = minimum
B = 4 = minimum on selected axis
B = 5 = maximum on selected axis
C(1,3) = minimum on Y axis
C(1,4) = maximum on Y axis
C(0,5) = conversion factor of paddle zero (0-255) to radians (0, pi)
C(1,5) = conversion factor of radians to degrees (57.2958)
C(0,6) = conversion of paddle value to degrees on the screen
360 — North, 90 — East, 180 — South, and 270 — West
C(1,6) = # of times to draw space ship destruction
DC = defender count — the number of kills
IC = intruder count — the number of kills
J, K = loop and temporary variables
ORBITAL
OV(0) = angular velocity of outer orbit #0
OV(1) = angular velocity of inner orbit #1
Pl = 3.1417
ROT = 0 = HGR rotation value (value range from 0-64)
SCALE = 1 = HGR scaling factor — value range 0-255-1 smallest 0 largest
SHAPE DATA—four different shapes
0 = defender
1 = intruder
2 = missile (defender)
3 = space ray (intruder)
SD(3,1,1) = shape data
SD(A,B,C)
A = 0 to 3 shape number
B = 0 = range
B = 1 = offset—center of space ship to center position of the screen from
position 0,0
C = 0 = X axis value
C= 1 = Y axis value
$D(0,1,1) = Y axis, offset of the shape 0
SD(3,0,0) = X axis, range of shape 3
VEHICLE STATUS
VS(1,15)
Fig. 29-10. ORBITAL WAR GAME variables.
264 APPLESOFT LANGUAGE
VS(0,?) = defender
VS(1,?) = intruder
VS(A,B)
A = 0 = defender
A = 1 = intruder
B = 0 = status
VS(1,0) = O—intruder does not exist
VS(1,0) = 1—intruder functional
VS(1,0) = —1—Intruder damaged
B= 1 = orbit
VS(0,1) = O—defender is in the outer orbit
VS(0,1) = 1—defender is in the inner orbit
B = 2 = angle value
B = 3 = orbital velocity
B = 4 = X axis value
B = 5 = Y axis value
B = 6 = next X axis value
B= 7 = next Y axis value
VS(0,8) = energy increment
VS(1,8) = accuracy factor or distance to defender by intruder’s space rays
B = 9 = X range
B = 10 = Y range
B= 11 = X offset
B = 12 = Yoffset
VS(0,13) = defender’s energy base
VS(1,13) = intruder’s base firing distance
VS(0,14) = defender’s energy level
VS(1,14) = intruder’s maximum firing distance
VS(0,15) = defender'’s fire direction
VS(1,15) = intruder’s distance to the defender
VS(0,16) = defender’s damage count
VS(1,16) = intrucer’s damage count
WEAPON STATUS
W(4,6) = weapon data
W(A,B) = weapon data
A = 0, 1, 2, 3—defender has 4 missiles
A = 4—intruder has unlimited space rays at specified range
(DEFENDER’S WEAPONS)
B = 0 = HCOLOR= 0 (black) or HCOLOR = 1 (green)
W(1,0) = O—HCOLOR = 0 (black)
W(1,0) = 1—HCOLOR = 1 (green)
B = 1 = X position value
B = 2 = X positive value
B = 3 = next X positive value
B = 4 = next Y positive value
(INTRUDER’S WEAPON)—same B1 through B4
B = 5 = change in X value random value
B = 6 = change in Y value random value
The lines from 610 through 850 tie all actions together and create the
battle.
Lines 140 through 170 determine if the defender’s missile has destroyed
the intruder. This routine returns to 620, which begins with the statements
GOSUB 10.
Line 10 DRAWS and redraws both space ships at the old position. It also
draws the space ships at the new position.
Line 20 calculates the next position of the space ships.
Line 30 blacks out part of the damaged space ship and increments the
damage count which is held in VS(0,16) for the defender, and VS(1,16) for
the intruder.
Line 35 FOR D = 1 TO 180: NEXT D is a timing loop so projectiles and
space ships run at the same speed. This timing loop causes a delay before
the program can continue. If a space ship is damaged, its weapons will not
fire during this delay.
Line 40 calculates the distance between defender and intruder and
RETURNS to the second statement in line 620, to print out the defender’s
energy level, and the intruder’s distance to the defender.
In line 640, if both space ships are functional, if the paddle key is pressed,
and if the defender’s energy level is greater than the defender’s base energy
level, the program jumps to line 50.
Lines 50 and 60 determine if a missile is available to fire. If it is, and if the
paddle firing button was pressed, a missile is fired (if a missile is available,
go to line 70. If no missile is available, go to line 100).
Lines 70, 80, and 90 set the missile firing direction, give missile speed,
and fire the missile.
Lines 100, 110, and 120 move the defender’s missile toward the intruder.
The program returns to line 740, which is GOSUB 140.
Lines 140, 150, and 170 determine if the defender's missile has destroyed
the intruder. It the defender's missile has not, the program branches to line
390.
Lines 390 through 480 calculate the action, angle, range, and distance to
the defender. This information prepares the intruders space ray to fire on
the defender.
Line 440 creates a series of flashes and explosions when the intruder’s
space ray is fired and when it hits the defender. Line 440 plots an HCOLOR
= 1 three times, and wipes out the lines. This routine causes a flashing line
from the intruder at the point where the space ray is going to appear. The
area flashes three times, and then the space ray appears on the screen. This
is to simulate an explosion. This brings the program back to lines 610
through 998 to continue the action of the program.
This is a general outline of the program:
THERE ARE TWO ORBITS FOR THIS PROGRAM. BOTH YOUR VEHICLE AND THE IN-
TRUDER CAN BE IN EITHER ORBIT. IN ADDITION THE VEHICLES CAN MOVE IN A
CLOCKWISE OR COUNTER-CLOCKWISE DIRECTION. THIS IS DETERMINED RAN-
DOMLY BEFORE EACH ENCOUNTER. THE TWO CRAFT FOLLOW GRAVITATIONAL
FORCES AND CANNOT BE MANEUVERED.
YOU WILL HAVE TIME TO PREPARE FOR COMBAT BEFORE THE INTRUDER
APPEARS. ALSO, YOU WILL RECEIVE A MESSAGE JUST BEFORE THE INTRUDER RE-
TURNS FROM HYPERSPACE TRAVEL. THEN THE BATTLE WILL COMMENCE.
269
270 APPLESOFT LANGUAGE
D Fdit, 119
Efficient programming, rules for, 73-75
DATA, 143 END statement, 28
Debug, 61 Error
Decimal to hexadecimal conversion ‘am, check for line length, 107
program, 206 checking, 104-105
Decision, 61 detecting routines, 163
flowchart, 114 line number relationship, 113
statement flowchart, 74 no sense, 164
statements, 74 stop program running, 164
Default, 61 Escape cursor moves mode, 119, 121
Deferred execution, 37 Execution,
DEF FN, 37, 43-44 deferred, 37
Definition of formula, 205 immediate, 37
Definition, print field, 149 EXP, 116
DEL, 119, 120 Exponentiation, 49
Delete Expressions, assignment of, 102
a program on disk, 25
routine, 192 F
Delimiter(s), 27
number of, 106 FIFO, 175
semicolon, 163 File names, 23
Depreciation, straight line, 134 Final flowchart, 107
Detailed Flag, 77, 78
input format, 102 Flexibility, program, 171-174
output format, 102 Flexible tax program, 174
Detail, header, 229 Flowchart(s)
Development of a program, 99 and problem solving, 67-73
DIM, 81 basic, 103-104
statement for numeric array, 83 decision, 114
Directory, 20 statement, 74
Disk ; for flag program, 80
initialize, 21-22 logic, 67
load and save programs, 19-26 outline, 102, 103
or diskette, 19-20 Flowcharting, 68
Division Format, 27
and multiplication, 49 detailed
by zero, 42 input, 102
Documentation, 27 output, 102
DOS, 20 Formulas, 205-218
booting, 19 FOR-NEXT, 53
Double loop, 55, 144
declining balance, 134 FRE(O), 117
nested loop, 92 Function, 96, 115-117
subscripted ASC, 49
arrays, 89, 219-232 CHR$, 49
INDEX 271
Interface, 20
General outline
computer program, 143-145
for program development, 101
Justify, right, 147
GET A$, 133
GOSUB, 95
GOTO, 53 K
loop, 54-55
Key
Graphics, 53, 235-247
left arrow, 120
high resolution, 249-268
repeat, 120
screen, 236
right arrow, 120
Graph, standard, 240
M Pass, 127
Percent sign, 39
Manual system
Play computer, 127-129
decimal to hexadecimal! conversion, 208
Pointers, buffer, 175
for hexadecimal to decimal conversion,
POS, 117
210
Precedence, 47-51
Memory space, saving, 74
order of, 48
Menu selection, 133
Preprogramming, 161
and coding formulas, 133-141
PRINT, 27
Mode, interactive, 47
field definition, 147
MODEM, 47
rules, 27-32
Motherboard, 20
statements, punctuation in, 29-30
Multiplication and division, 49
Problem solving and flowcharts, 67-73
Program(s)
N a set of instructions, 28
cash flow, 219-223
Name search, 203
development, 99
Names, file, 23
general outline, 101
Nested loops, 53, 59-60
error checking, 99
Network of logic to write a program, 163
flexibility, 171-174
NEW, 15
flowchart symbols, 69-71
No sense errors, 164
HELLO, 23
NOT, 62
loading from cassette, 17
Notation, scientific, 37
LO-RES EXPLAINER, 237-238
NOTRACE, 127
OGIVE, 244
Numbering lines, 28
on disk,
Number of delimiters, 106
delete, 25
Numbers, line, 61, 62.
LOAD, 24
LOCK, 25
@) RENAME, 25
RUN, 25
OQIVE program, 212-213, 244
UNLOCK, 26
ON ERR GOTO, 95
outline, 143-146
Operand, 48
statement, 15
Operator(s), 48, 81
Prompt, 119
arithmetic, 47
types of, 21
logical, 61
Protected, write, 21, 22
relational and logical, 61-66
Punctuation in PRINT statements, 29-30
replacement, 48
Pure cursor moves mode, 119, 121
unary, 48
Options, slot, drive and volume, 23
ORBITAL WAR GAME program, 259-262
R
Order of precedence, 48
OR-IF, 62 Radian, 115
Outline Range, integer, 39
flowchart, 102, 103 READ, 143
program, 143-146 READ-DATA statement, 50
Output format, detailed, 102 Real, 37
Relational and logical operators, 61-66
Replacement
operator, 48
Parenthesis, 49 statement, 48, 50
INDEX 273
U Variable(s) — cont.
double subscripted, 88-93
Cnary operator, 48
for circular list, stack, and pointers, 180
Unconditional transfer, 54
in Applesoft, 38
Cninitialized variable, 29
initializing, 78
UNLOCK program on disk, 26
single subscripted, 81-87
Use of double subscripted arrays, 89
string, 44
summing, 77
V uninitialized, 29
VDM, 16
VAL, 117
VTAB, 33
Value
illegal, 77
legal, 77 Ww
Variable(s), 37-45, 134
Words, reserved, 131-132
assignment of, 102
Write, debug, modify program, 107
complex, 96
Write protected, 21. 22
counting,77
and totaling, 78
— SAMS APPLE® BOOKS
Many thanks for your interest in this Sams Book about Apple II®° microcomputing. Here are a few
more Apple-oriented Sams products we think you'll like:
3. My occupation is:
Scientist, Engineer _______ ~-D P Professional
Personal computerist Business owner
Technician, Serviceman _____—~ Computer store owner
_—« Educator Home hobbyist
Student Other
Name (print)
Address
Ce
ee
are
—
—-
_—