Reproductionoruse, without express written permission from
Tandy Corporation,ufany portion of this manualisprohibited.
While reasonable efforts have been taken in the preparationofthis
manualtoassure its accuracy, Tandy Corporation assumes
liability resulting from any errors or omissionsinthis manual, or
you've used your TRS-80 Model 100 just once, you know how simple, versatile,
to
and powerful a computer it is. Its built-in application programs allow you
normally complex computer operations with ease. This includes data manipulation,
computer-to-computer communications, word processing, and more.
as
However,
computer even more useful by customizing it to suit your own special needs. This
done through BASIC, the built-in programming language.
For instance, from BASIC, you can:
• Re-define the Function Keys
• Communicate with information services and other computers.
• Write programs for a wide range
performing interest or mortgage calculations.
• Make use
and a host
This course will show you how
detail the BASIC section
time you've finished this course. you'll be writing your own programs and using the
built-in application programs more effectively.
Since most
since BASIC interacts with the other built-in programs, you'll find it
your advantage
you become more familiar with your Model 100, you can make the
(fj)
through
of
of
the computer's graphic and sound capabilities.
of
other operations!
to
perform operations suchasthese by explaining in
of
your Model 100 Owner's Manual. This means that by the
of
the application programs not built-in will be writteninBASIC, and
to
become familiar with BASIC.
(lID.
applications suchasforecasting sales trends and
is
perform
definitely to
is
So sit back and get ready to enjoy your Model
out how powerful a computer it really
is!
100 even more. You're about to find
1
it'
Lesson
To use the BASIC capabilities of the Model 100, you must first learn how to
communicate with your Computer. Essentially, this involves typing instructions on the
keyboard and watching the display for responses from the Computer.
While you can type anything you wish on the keyboard, the Model 100 only responds
to words written in its own
something which the Model
with an error message.
In this lesson, you will learn a few BASIC commands
Computer and write simple programs.
It should be mentioned at this point, that even when you type a BASIC word, the
Model
keyboard)
for processing by the Computer.
Throughout this Manual, the phrase "enter this command" will be used often. This
simply means that you should press
Also, when
together.
100 will not respond until the ENTER key (located in the right side of the
#1
is
pressed. After pressing
we
tell youtopress
Introduction
"language." This "language"
100
to
BASIC
is
BASIC.Ifyou type
does not recognizeasa BASIC word, it will respond
to
communicate with your
(ENTER),
~
~,
the line just typed is placed in memory
after typing the command or instruction.
you should press both
(SHIFT)
and
(PAUSE)
Accessing BASIC
Priortotyping or editing a BASIC program, you must access the BASIC interpreter
the Model 100.
When you Power-Up the Computer, you will see the Main Menu, which shows all the
''files'' that exist in the Model 100's memory. Think
file folders that may hold text or programs.
If
you haven't created any files, the Main Menu displays the built-in application
programs:
11:06:08
TEL
COM
20897
On initial Power-Up, the Main Menu Cursor -the large, dark rectangle -is
positioned over the word
word by pressing the Cursor Movement Keys
"BASIC."
The Cursor can be placed on any other Menu
«(3
of
these computer files simply
(C)Microsoft
ADDRSS
Bytes
, G , rn ,or rn).
free
of
as
3
To access the BASIC interpreter, simply position the Cursor over the word BASIC
and press
CEmR.l.
The Display will then look like this:
TRS-8~
(cpr.
21190
Ok
The number 2119QIindicates the number of free bytes for creating any programs and
it may vary depending upon the capacity
have been created and saved.
The word 0
Command Mode
Experiment
A commandisan instruction to the Computer ordering it todosomething
immediately. In this experiment you will learn how to enter a simple command.
First you will attempt to have the Model
the name:
JOHN
Model
1983
Bytes
k and the flashing cursor symbol below it, indicate that you are in the
of
100
Software
Microsoft
free
of
your machine and whether any other files
BASIC and ready to begin programming.
#1
Entering a Command
100 print out a name on the display. Type
SMITH
You may use any other name. Now, press
Computer displays the message:
?8N
Error
This message indicates that an error, specifically a syntax error, has been made. The
syntax error occurred because the Computer doesn't recognize John Smith
its vocabulary (also knownasthe Instruction Set).
The correct way to instruct the Computer to print the name
PRINTIIJOHN
Be
sure to press
quotation marks enclosing the name are recognized as part
vocabulary. This way no syntax error occurs and the name appears printed right below
the command.
~
8MITH
at the endofthe line. The key word PRINT and the
II
~.
(ENTER)
As soon as you do this, the
as
is
to type:
of
the Computer's
part
of
4
PRINT "JOHN SMITH"
JOHN
Ok
SI'1
I
TH
•
Use the PRINT command to print your own name if you haven't already done so.
Also, try printing other phrases. For example, to print How now brown cow, type:
PR
I NTIIHOW
Notice that the phrase is printed exactly as it appears within the quotation marks,
including spaces.
NOW
BROWN
COWII(ENTER)
Experiment
A BASIC
executes, one at a time, in a
in
that it is precededbya line number.
Here is a simple BASIC program:
This program, consistingofonly one statement, the PRINT statement, accomplishes
the same thing
But because the word PRINT is being used in a program and preceded by a line
number, it is now called a statement. The number
statement is called a line
number, even
Type line10as it appears above. Notice that nothing happens this time when you
press
immediately, a program does nothing until the Computer is instructed to execute it.
This is accomplished with the command:
Type the RUN command.
After entering the RUN command, the program
programisa listofinstructions (or statements) that the Computer
10
PRINT
PRINT
(ENTER).
RUN
#2
"JOHN
as
the command:
"JOHN
What is a BASIC Program?
sequential order. An instruction differs from a command
SMITH"
SMITH"
number.
CENnID
H'J
which is typed before the PRINT
Every lineina BASIC program must have a line
ifthe program contains only a single line.
Unlike a command, which instructs the Computer to perform a task
Don't
forget to press
(ENTER)
is
after typing it.
executed and the nameisdisplayed.
5
10
PRINT "JOHN SMITH"
RUN
JOI·-lNSMI
A more economical wayofinstructing the Computertoexecute your programisto
press the RUN Function Key,
(ENTER).
Now
try
a slightly more ambitious program. Enter the following two-line program:
TH
~.
This accomplishes the same thingastyping RUN
10 PRINT
20
GDTO
The second statement in this program begins with line number 20, indicating that this
instruction should
is
There
thing
instruction.
Execute the program with the RUN command or
As
name within quotation marks repeatedly. This is known
program because the GOTO statement in the second line of the program simply
transfers control back to the first line which prints the
and/or numbers) again on the next line.
Because of this continuous transfer, the program has
must be terminated manually by you. To
«(SHIFT)
When you press
program stopped when it was "broken." For example:
nothing special about the line numbers used in this program. The important
is
that the PRINT instruction has a smaller line number than the GOTO
you can see, unlike the first single line program, this second program prints the
~).
"RADIO
SHACK
MODEL
100"
10
be
executed after the first line which has a smaller line number.
by
in
~,
pressing
no
"break"
the Computer will display a messagetoshow where the
10
the program, press
~.
as
an "infinite
"string"
wayofterminating and so it
(a group of characters
loop"
(BREAK)
6
Note that the program you wrote "scrollsupand off" the screenasthe program
If
began printing.
command:
you wish to see the programasyou wroteitagain, enter the
LIST
or simply press the
on the Display again.
List
10
PRINT "RADIO
20
GOTO
Ok
LIST
10
Function Key,
SHACK
CEID.
In either case, the program will appear
MODEL
100"
•
Execute this program again with the RUN command or by pressing (f!l.
After letting
This time after pressing
CONT
As
you can see, the program resumes execution. The CONT command is used
CONTinue execution after the program has been
same place where the program was interrupted.
the
program run a few seconds, terminate it by pressing
~,
enter the command:
"broken."
~.
Execution will start at the
to
Experiment
Here's the program from the previous experiment:
1121
PRINT
2121
GOTO
Suppose you want to change line10so that the message reads:
I
LOVE
This can be done by retyping line 10 entirely:
1121
PRINT
"RADIO
1121
MY
"I
#3
Simple Editing
MODEL
LOVE
SHACK
1121121
MY
MODEL
MODEL
1121121"
7
1121121"
(ENTER)
Now, when you list the program with the LIST command or with the (f5) Function
Key, the following is displayed:
10
2l2l
Ok
PRINT
GOTO
1l2l
"I
U)VE
MY
110DEL 101Zl"
•
Execute this programtoverify that the new phraseisdisplayed. Now, instead
pressing
program
again. Pausing a program may be useful when you want
displayed before it scrolls off view.
pressing
Try a
program:
Run this program. The output should
(BREAK)
to
(BREAK)
few
10
20
M\/
LEE
Ok
to
interrupt execution, press the
stop momentarily. To continue execution, simply press the
Of
course this program must still be terminated by
because it stillisin an infinite loop.
other experiments with the PRINT command. Type in the following
PRINT
PRINT
NAJvIE
"MY
"LEE"
IS
NAME
IS"
be:
(PAUSE)
key. This will cause the
to
read what is being
(PAUSE)
•
of
key
Now, retype line10to
Also, add a semicolon
this
10
20
PRINT
PRINT
"MY
"LEE"
insert a space between the word
at
the endofline
NAME
IS
10.
The changed program should look like
";
8
"IS"
and the quotation mark.
Execute this program. The output should appear
MY
NAME
Ok
IS
LEE
•
as:
The printing appears all in one line because the semicolon instructs the Computer
continue printing immediately after the first line is printed. The space after
was
the first line
If
you wantedtospace the name further apart, you could add more spaces after
or you could add spaces before
Another way
10
line
Now list the program and it should read:
Run this program. The output should appear
so thatitreads:
10
LIST
10
20
Ok
added so that the words
"LEE"
to
space the printing istouse a comma insteadofa semicolon. Retype
PRINT
PRINT
PRINT "LEE"
"MY
"MY
NAME
NAME
IS
IS
"IS"
in line 20.
",
"
as:
and
"LEE"
would not run together.
"IS"
to
in
"IS"
NAME
This time
line means "begin printing in the next field" (more on fields later).
"IS"
IS
and
"LEE"
L.EE
are spaced several columns apart. The commainthe first
9
Enter the following program:
1121
2121
PRINT
PRINT
"HOW
",
"BROWN";
"NOW
"COW"
";
Would you guess what the outputofthis program will produce? When executed, the
display will show:
Hm~
Ok
1\IOlr-J
BFWWI\ICOW
The comma in line10caused the two strings HOW and NOW to be spaced several
columns apart. The semicolon between the two words
"BROWN"
and
"COW"
caused themtoprint without a space. Nowifline10is retypedsothat the comma
changedtoa semicolon and the semicolon at the end of the statementisomitted,
1121
PRINT
2121
PRINT
the output would
HOW
NOW
BROWNCOW
"HOW";
"BROWN";
be
"NOW"
"COW"
is
The second PRINT statement produces output on the second line because the carriage
return after the first PRINT statement has not been suppressed with a semicolon or
If
comma.
you could rewrite your program
you wantedtoprint the words on one line, neatly spaced one column apart,
as
follows:
1121
2121
PRINT
PRINT
"HOW";
"BROWN";
"NDW
"CDW"
";
10
When it is executed, it produces,asexpected, the following:
NOW
BROWN
COW
A BASIC program can be edited a line at a time simply by retyping the entire line
you have been doing.
To delete an entire line from a program, all you have
to
of the statement you wish
delete and press
~.
todoistotype the line number
For example, list the current program:
PRI NT
PRINT
Now
type
20~
If
you list the program again, you will
"HOW
"BROWN
"?
"NOW
";
";
"COW"
see
that line 20 has been effectively deleted:
as
1~
PRINT
"HOW";
"NOW";
Ok
I
Retype line 20 to restore your programtoits previous form:
10
20
PRINT
PRINT
"HOW
"BROWN
";
"NOW";
"j
"COW"
11
A
new
line can be added to a BASIC program at any time simply by typing it with the
If
appropriate line number.
number less than
10
you wanttoadd
(the smallest line number allowedis1).Ifyou wanttoadd a line
between the two lines, give it a number between
10
Line numbers
numbers had been used, for example
inserted.
5).
It
and 20 were usedtoallow insertionofnew lines.Ifsuccessive line
15
is a good practicetouse line numbers that
a statement before line
10
and 20 (e.g., 15).
and 16, thennonew lines could have been
are
multiplesof10
Here's your program again:
10
20
PRINT
PRINT
"HOW"j"NOW"
"BROWN
II
j
"COW"
j
Suppose you want to insert a line between10and 20. Simply type:
15
PRINT
"SPLENDID
";
~
When you list the program now, it will show:
10,
give it a
(or at least
PRINT
PRINT "SPL.ENDID
PRINT
"HOW";
"BROWN
"NOW";
"i
!I;
"COW"
Even though line15was typed after lines10and 20, it takes its correct place in the
10
program because its line number falls between
and 20.
Execute this program. The following output will result:
NOW
SPL.ENDID
BROWN
COW
It should be clear by now that any BASIC program can be edited easily with the use
of
the line numbers. You can add, delete, insert, and change lines and that is all you
to
ever need
do.
12
Experiment
By
now you should be able to write simple BASIC programs using the two
instructions PRINT and GOTO.
#4
Writing Your Own Programs
Before you go on experimenting with the spacing
comma and the semicolon, you should be aware
NEW command.
When you enter the NEW command, any program that has been previously typed and
is
currently residing in working memory will be erased automatically.
Before you begin typing in a new program, you should always use the NEW
command to clear out the old program. Otherwise, you may end
combination
Assume that your old program still resides in memory:
10 PRINT
is
20 PRINT
Now, without deleting this program, enter the following new program:
10 PRINT
of
your new and old programs.
"HOW";
PRINT "SPLENDID
"BROWN
"MY
";
COMPUTER
"NOW";
";
"COW"
IS
in PRINT statements using the
of
another useful command, the
-up
with a
A
";
20 PRINT "TOOL."
If
you list the program, you will find it
is:
LIST
10
15
20
PRINT
PRINT
PRINT
K
"MY
COMPUTER
"SPLENDID
"TOOL."
";
IS
A
";
Note that line15still exists because that line number was not usedinthe new
program.
command NEW. This won't be necessary, however,
exists
So
remember, before typing a new program, clear the memory with the
if
you are certain that no program
in
memory.
What you have learned:
In this lesson you have learned some commandstowrite and execute a simple BASIC
program. The PRINT and GOTO statements have been used to display simple
messages. Editing a BASIC program can be
typing new lines. The NEW command is used
memory.
13
accompli~hed
to
deleteanentire program from
by retyping existing
line~
or
Lesson
In this lesson you will learn howtosave programs in memory and on cassette tapes.
You will
program with another program.
IJ.lso
#2
learn how to recall a program from storage and how to merge a stored
Saving Programs
Experiment
As
it was mentioned before, the Model 100 can hold several files, many9fwhich can
be
program files, In Lesson 1 you learned to write simple BASIC programsinthe
BASIC system
use repeatedly, it is a good idea
Random Access Memory). When you save a program in RAM, in effect, you create a
program file.
The following program serves to demonstrate how any program can be saved in RAM:
10 PRINT "THIS
20 PRINT
Access BASIC. Clear working memory with the NEW command and then type the
program
Execute the program, The following will be displayed:
asitappears above.
THIS
OF
Uk
1::'1
THE
#1
of
the Computer. When you have written a program that you intend to
"OF
A TEf3'T
MODEL
Saving a Program In
to
save it in memory (also knownasRAM, for
IS
A TEST"
THE
100
MODEL
COMPUTER
100
COMPUTER"
RAM
II
The first step for saving a program in RAMisto decide upon a filename. This
filename appears listed as a file in the Main Menu and it serves to identify the
program. Filenames cannot exceed six characters in length.
You may use any combination
character in a filename must always be a letter. The following are examples
filenames:
MYPROG
SKETCH
ACCNT2
of
letters and digits for a filename. However, the first
of
15
valid
The following are examplesofillegal filenames:
1PROG
MICROCOMPUTER
(must begin with a letter)
(exceeds the maximum of six
name)
c,haracters in any file
Suppose you want to save the program above under the filename
PROG1
Todothis, simply type:
SAVE
IPROG1"
~
The Display will show the prompt OK to indicate that the program has been SAVEd.
Use the command NEW to clear the program from working memory. To verify that
the program no longer exists in working memory, enter the command:
LIST
or press
LIST
(ENTER)
~,
the LIST Function Key. The computer will respond with:
OK
and nothing else, indicating that there isnoprogram currentlyinworking memory.
It
The program has not been wiped out.
in
now exists
FILES
RAM. To confirm that thisistrue, enter the command:
(ENTER)
has been erased from working memory but it
or press the FILES Function Key,
the
file~
storedinRAM, including all BASIC programs, will be displayed. In this
if
case,
you haven't SAVEd any other programs or files, the name
®.
In responsetothis command, the namesofall
PROG1.BA
willbedisplayed.
is
This
your program. The
that this file is a BASIC program. The Computer automatically appends this extension
to the name
of
any BASIC program whenitis
If you want more proof that your program was indeed saved as a file, press the Menu
Function Key,
CEB).
below.
Jun
22,1983
BASIC
SCHEDL
Select:
characters"
.BA"
form a
"file
extension" which indicates
saved in RAM.
You will see PROG1.BA displayedinthe Main Menuasshown
Wed
10:34:17
TEXT
TEL
COM
PROG1.BA.
.....,...
21350
""'.
Bytes
---
free
16
A simpler way to save a program in RAM,isto use the SAVE Function Key,
After typing a program you wish to save, simply press
prompt you with the message:
~.
The Computer will
~.
Save
All you have to do thenisto type a name for the fileasyou did before and press
(illEID.
The numberoffiles which can be saved is limited only by the amountofRAM
available.
up
used
Experiment
After you have saved a program in RAM, you may execute it simplybypositioning
the Cursor over the word identifying it in the Main Menu and pressing
However,ifyou wish to modify or alter the program in any way, itisvery convenient
to LOAD
Let's use PROG
BASIC system.
You can do that with the command:
LOAD
Another way to LOAD the programisto
pressing
Load
"
If
you continue to add files to RAM, eventually all available RAM will be
andnomore programs can be saved.
#2
it
into the BASIC system.
1 which you SAVEd in the last experiment and LOAD it into the
"PROG1"
~
the message
"
Loading a Program From RAM
(ENTERJ.
~
press
the
LOAD Function Key.
CE2l.
After
appears on the Display. All you shoulddothenisto type
PROG
1"
(ENTER)
After Loading PROG1 with the LOAD command or (f2), LIST the program to verify
that it is indeed in working memory. The following should be displayed:
List
10
PRINT
20
PRINT "OF
Ok
"THIS
THE
IS
MODEL
A
TESTH
100"
I
If you execute the program with the RUN command you will see that the outputisthe
same
as
before.
Enter the command FILES or press
(11).
17
You will see that the program PROG1.BA is still listed, indicating that itisstill saved
in RAM, Loading a program from RAM does not erase it from storage.
Notice, however, that an asterisk appears to the right of PROG1.BA. The asterisk
indicates that the program
Use the NEW command to delete the program PROGI from working memory. Use
the LIST command to verify that working memory does not contain the program. Now
type the command
RUN
"PROG1"
The following should appear on the LCD:
is
currently in working memory.
CEHnID
THIS
OF
Ok
THE
IS
MODEL
A TEST
100
COMPUTER
11
This illustrates a useful optionofthe RUN command.Ifthe RUN command is
of
followed by the name
quotes), then the program will be loaded into working memory and executed
immediately. Thus the command:
RUN
"PROG1"
is equivalent to the two commands:
LOAD
RUN
Use the LIST command to verify that the program now resides in working memory.
The program will be modified by adding a third line. Type the following line:
30
List the program to verify that it
"PROG1"
CEHnID
PRINT
a program stored in RAM (the name must be enclosed in
00£!lID
mEID
"AND
ITS
is:
AB
I LI
TV
TO
STORE
FILES"
CEBllID
LIST
PRINT
PRINT "OF
PRINT
"THIS
"AND
THE
ITS
IS
A TEST"
MODEL
ABILITY
100
TO
18
COMPUTER"
STORE
FILES
When you LOAD a program from RAM into working memory, you may add, delete,
or insert new lines as you wish. The changes you make are immediately incorporated
into the program.
Delete the program from working memory with the NEW command. Use the LOAD
command to recall program
"PROGI"
from RAM. Type:
LOAD
List the program with the LIST command. You should
The new line was effectively incorporated in
"PROG1"
PRINT
PRINT "OF
PRINT
"THIS
"AND
mEID
IS
THE
ITS
A TEST"
MODEL
ABILITY
see:
1~0
COMPUTER"
TO
STORE
FILES
"PROGI"whichisstored in RAM.
You can also LOAD and execute a BASIC program directly from the Main Menu.
(fI) to exit BASIC and return to the Main Menu. You should see something
Press
similar to
(
C:>
jvli
Cl
....
[)!::·CJf·
Jun
!
SCHEDL
22.1983
Wed
.10=37:07
TEXT
TEL
PROG1.BA.
COM
(\
DD
i:~
:::\
t
~:j
21350
Bytes
tree
Move the cursor over the filename PROGl.BA as indicated below.
TEL..C()!V!
5CHEDL.
._0.
n
•...•
.••-II--
19
If
you press
loads and executes PROG1.BA. You will see
(ENTER),
several things will happen: the computer enters BASIC and then
THIS
OF
AND
Ok
THE
ITS
IS
MODEk
A TEST
1~~
ABILITY
COMPUTER
TO
STORE
FILES
•
with the Ok prompt indicating that you are in BASIC.Ifyou list the program you will
see that PROGl.BA is in working memory.
Experiment
Itispossible to change a file name using the command:
NAME
where oldfilenameisthe nameofthe programasit now exists, and new filename
the.
new program name you wishtoassign to it.
For example, if you wish to change the filename "PROG
NAME
Verify the name change with the FILES command orbypressing
"old
"PROG 1 •
#3
Changing a Filename
filename.extension"
BA"
AS
AS
"TEST
"new
filename.extension"
1 •
BA"
(ENTER)
1"to"TEST!,"
CEf).
is
typc:
Now, using the NAME
NAME
Again, you may confirm that the name was changed to PROGI with the FILES
command.
"TEST1.BA"
Experiment
Whileitis convenient to save your programs in RAM, thereisonly a finite amount
space available. Eventually, there willbeno
An alternate method
cassette recorder. Using cassettes, you can store essentially an unlimited number
programs.
...
AS
command, change the file name back to
AS
"PROG1.BA"
#4
Saving a Program on Cassette
room left for new programs to be saved.
of
saving your filesisto store them on cassette tapes using a
20
~
"PROGl."
of
of
PROGI should still be in working memory. Use the LIST commandtoconfirm that it
It should appear
is.
as:
LIST
10
PRINT
PRINT
PRINT
If
it is notinmemory you should LOAD it from RAM or type itinas shown above.
"THIS
"OF
"AND
THE
ITS
IS
A TEST"
MODEL
ABILITY
100
TO
COMPUTER"
STORE
FILES
To save a program on cassette, it is first necessary to connect the Model
suitable cassette recorder. For optimum results
we
recommend the Radio Shack
100 to a
CCR-81 Computer Recorder (catalog number 26-1208) with connecting cable and
instructions supplied. Be sure that the proper connections are made before proceeding
further.
Place a blank tape in the cassette recorder and rewind it,
if
necessary. Then advance
the tape past the leader. (If you use Radio Shack Leaderless cassettes, catalog number
26-3019, this isn't necessary.)
Press the RECORD (red key) and PLAY keys down together. They should stay down,
but the tape will not move.
If
it does, youdonot have the remote jack inserted. Insert
the jack.
Now you are ready to save the program onto the tape. Enter the following command:
CSAVE
"PROG1"
The recorder will run briefly and then stop. The RECORD and PLAY keys, however,
will stay down. After the tape stops, you may press the STOP key and rewind the
tape.
1.
The program now has been saved with the filename .'PROG
to
Another way
save the program on tape, insteadofusing CSAVE
"
"PROG1"isto
use the command:
SAlJE
"CAS
:filename
II
where CAS: specifies the device to be used for the saving operation,inthis case the
cassette recorder, and filename
is
the nameofthe program to be saved. Using this
command, you would specify:
SAIJE
"CAS:
PROG
1"
~
21
Experiment
#5
Loading a Program from
Cassette
The program you just saved on tape in the previous experiment, PROG1, will now be
loaded back into working memory. But first, delete PROGI from working memory
with the NEW command.
Verify that it has been deleted with the LIST command or
Function Key,
Be sure that the cassette recorder is properly attached to the Computer. Insert the
cassette containing the program into the recorder and rewind
Press PLAY on the recorder. The key will stay down, but the tape will not advance.
Enter the following command:
CLOAO
As soonasyou press
into the Computer.
FOUI\ID:
Ok
If
the tape was not read successfully, an
displayed.
the CLOAD command again to read the tape.
~.
"PROG1"
(ENTER),
If
thisisaccomplished successfully, the computer will display:
Pf{OG
1
If
this happens, rewind the tape and adjust the volume control. Then use
the tape will start turning and the program will be read
110
(InpuUOutput) error message will be
by
pressing the LIST
if
necessary.
If the tape is read successfully, you may verify that the program
memory by listing it with the LIST command (or with
displayed:
LIST
10 PRINT
20
PRINT "OF
30
PRINT
Ok
"THIS
"AND
THE
ITS
IS
A TEST"
MODEL
ABILITY
10m
COMPUTER"
TO
~).
STORE
The following will be
FILES
•
22
is
in working
When the command CLOAD
until a program stored under the name
into working memory.
The command
"PROGI"is entered, the Computer searches the tape
"PROGI"is found. This programisthen read
LOADIICAS
may be used in place of CLOAD "filename". Remember that filename specifies the
name
of
the program you wish to LOAD from the cassette.
Delete the program from working memory with the NEW command and verify that it
has been erased by using the LIST command.
Rewind the cassette and press the play key. This time type the command:
CLOAD
When this commandisentered, the cassette recorder will run briefly and then stop.
Also, the computer will display:
FOUND:
Ok
:jilename"
COOfR)
PROGl
(ENTER)
II
indicating that the program was read successfully. List the programinmemory with
the LIST command. You will see that the same program was loaded from the tape.
This illustrates another option
program is omitted, the first program encountered on the tape
Since your program PROGI was the first program on the tape, it was loaded into the
Computer.
Experiment
Your Model 100 allows you to verify that a program has been saved successfully (i.e.
without any errors) on cassette tape. Another option
to accomplish this.
#6
of
the CLOAD command. When the filenameofthe
is
loaded into memory.
Verifying a Stored Program
of
the CLOAD commandisused
23
Verify that the program still resides in working memory with the LIST command.Ifit
has been deleted, load it from the cassette tape or type it in from the keyboard. Here
is
the listing again:
LIs'r
10
PRINT
20
PRINT "OF
30
PRINT
Rewind the cassette tape containing the program and press the PLAY key on the
recorder.
Type the command
"THIS
"AND
THE
ITS
IS
MODEL
A TEST"
100
ABILITY
COMPUTER"
TO
STORE
FILES
CLOAD?IIPROG
The recorder will run briefly and then stop. The Computer will display:
Found:
OK
In this case, the program stored on tape was not SAVEd into working memory, but
was compared, character by character, with the program already in working memory.
If
an inconsistencyisfound at any point, an error message will be displayed,
indicating that the prugram
working memory.
If
an error has occured, you can reSAVEthe program and use the CLOAD? command
again to check the saved program.
As
with the CLOAD command,ifthe file name is omitted from the CLOAD?
command, the first program encountered on the tape is compared with the program in
working memory.
List the program in working memory. You should see:
LIST'
10
PRINT
PRINT "OF
PRINT
PROGl
"THIS
"AND
1"
(ENTER)
saved on the cassette tape
IS
A TEST"
THE
ITS
MODEL
ABILITY
10121
was
COMPUTER"
TO
STORE
not the sameasthe one in
FILES
,
24
7
Delete line 30 by entering the line number. Now list the program to verify thatitis:
List
10
PRINT
20
PRINT "OF
Ok
"THIS
THE
IS
MODEL
A TEST"
100
COMPUTER"
I
Thisisnot the program that was saved on the cassette (line 30ismissing). The
be
CLOAD? command will
program saved on cassette. Since they are not the same, an error message will be
displayed.
Rewind the cassette and press the play key. Enter the command
CLOAD?
This time, the message:
usedtocompare the program in working memorytothe
Verify
will be displayed, indicating that the two programs are not the same.
Don't forget the question mark (?) after CLOAD since otherwise the program saved on
tape will
CLOAD? command indicates a
can be used again to resave it.
be
Experiment
Rewind the cassette tape containing the saved program and press the PLAY key. Then
load the program back into memory with the CLOAD command. List the program to
confirm that it
LIST
10
20
30
failed
loaded into working memory, replacing the resident program there.Ifthe
#7
is:
PRINT
PRINT "OF
PRINT
~THIS
"AND
"bad"
Merging two Programs
IS
THE
MODEL
ITS
program on tape. then the CSAVE command
A TEST"
100
COMPUTER"
ABILITY
TO
STORE
FILES
25
The program will now be savedinRAMin"ASCII"
"compressed" format. This means that the program will be saved exactly
format, rather than the usual
asitwas
written. Ordinarily, programs are saved in compressed form.Incompressed form, key
as
words such
PRINT, are replaced by a single charactertoconserve storage space.
Type the following command:
The
SAVE
"A"
"PROG2"
tA
(ENTER)
following the name indicates that the programistobesaved in ASCll
mode.
to
Another way of saving a program in ASCII format, is
to
of the SAVE command. For example,
SAVE
"PROG2.00"
CEJIIER)
SAVE PROG2 in this way you could type:
use the extension .DOaspart
Delete the program from working memory with the NEW command.
Confirm that it has been saved in RAM with the FILES command.
PROG2 will be listed
PROG2.00
The extension
"DO"
with the ASCII option. There are several reasons why you might want
as:
(for DOcument) will be attachedtoany BASIC program saved
to
save a file
the ASCII format. As it will be illustrated later in this experiment, merging files is
one of the main ones.
Delete the program from working memory with the NEW command, and type the
following one line program.
S
PRINT
"HELLO
MODEL
100
USER"
(ENTER)
Merge PROG2, which is saved in RAM with the ASCII option, with this one line
program, by typing the command:
in
MERGE
List the program in working memorytoconfirm that it
S
10
20
30
Merging a programinworking memory with one that
only be done
PRINT
PRINT
PRINT
PRINT
if
"PROG2"
(ENTER)
is
"HELLO
"THIS
"OF
"AND
THE
ITS
MODEL
IS
A
MODEL
ABILITY
100
TEST"
100
USER"
COMPUTER"
TO
STORE
has
FILES"
been savedinRAM, can
the programinRAM was saved with the A (ASCll) option.
Delete lines 20 and 30 by entering just the line numbers and then rewrite line
follows:
10
PRINT
"HERE I S A MESSAGE
26
FOR
YOU"
(ENTER)
10
as
List the program in working memory to confirm that it
LIs·r
5
PRINT
10
PfHNT
Ok
PROG2 will now be merged with this two line program. Remember that PROG2isin
RAM and consists
10
PRINT
20
PRINT
30
PRINT
"HELLO
"H[RE
of:
MODEL
IS
100
A MESSAGE FOR YOU"
"THIS IS A TEST"
"OF
THE
MODEL
"AND
ITS ABILITY
USER"
100
TO
is:
COMPUTER"
STORE
FILES"
Note that the program in working memory and PROG2 both have a line
two programs with the command
MERGE
List the program.Itwill
•.
1::::([
5 PRINT "HELLO
Line10of
resident in working memory. This will always happen.
MERGEd have any line numbers
RAM will replace the lines
Programs saved on cassette tape may also be merged with a program
memory
CSAI,JE
"PROG2"
P RI
f\IT
"Ti-n~3n':; A
PRINT
PRINT
the program (PROG2) saved in RAM replaced line10of the program
as
longasthey are saved with the A option. The appropriate command
"OF
","1\.10
"PROG2"
CENTER)
be:
MODEL
THE
ITS
of
the program in working memory.
100
USER"
lEST
"
MODEL
A:BH
in
100
COMPUTER"
..
ITY
TO
common, the lines of the program SAVEd in
tA
STORE
If
FILES
two programstobe
in
10.
Merge the
working
is:
or
SAVE
"CAS:PROG2"
tA
27
Then, to merge a program in working memory with one stored on tape, use the
command:
MERGE
Once you have MERGEd PROG2 with the program in working memory, SAVE the
newly formed program in the conventional way (without the A option) using the
SAVE "PROG
If
you returntothe Main Menu by pressing
have been SAVEd:
.-
-
-.
-
Se
Experiment
Often times you'll need to eliminate files and programs that are no longer useful, or
that you have SAVEd on tape
"CAS:PROG2"
1"
22,1983
-
·
-
·
-
·
--
·
:
lec:t
CEtll'EB)
command.
~,
Wed
11:~1:52
TEXT
PROG1.BAPROG2.BA.
.-
-
·
..
-
-
·
._.
--
·
_.
.-
·
#8
Deleting a file from
to
TEL
COM
-
-
·
._
.
.-
·
_.
..
-
·
.-
--
·
2fZJ8t:,<:1
free additional memory space.
you will see the two programs that
(C)Microsoft
ADDRSS
_.
.....
·
--.
-
·
...
.-
·
._-
..
-
·
:B~tes
RAM
You can delete a file from the RAM storage area with the KILL command. The
of
general form
K
ILL
where filename is the nameofthe program you wishtodelete, and extension specifies
the characters .BA, in the case
SAVEd with
language program.
Use the KILL command
KILL
The prompt Ok and the blinking cursor will appear on the Display after the program
has been deleted.
Use
the FILES command (or
that PROGl.BA is no longer listed. This is because the program has been deleted
from RAM.
To summarize, the KILL command deletes a file from RAM storage. The NEW
command deletes a program from working memory, but does not affect the file in
RAM storage.
the KILL commandis:
"filename.extension"
of
a BASIC program, .DO, in the caseofa program
the
A option or a text document, and .CO,inthe caseofa machine
to
delete PROG1 from RAM:
"PROG 1 •BA"
CENTER)
(fj))
to
list the files in RAM storage. You will notice
28
Also, you should be aware that a file cannot be deletedifthe same file is also in
working memory. That is,ifyou LOAD a program from RAM into working memory
and then attempt to KILL this file, you will get an error message. You should first
delete the program in working memory with the NEW command and then proceed to
KILL the file in RAM.
What you have learned:
You have learned how to SAVE BASIC programs in RAM and on cassette tape. You
learned how to LOAD a program from RAM or from tape and how to verify that a
program has been saved correctly. You also learned how to MERGE a SAVEd .
program with a program in working memory. You found out that in MERGE
operations,ifline numbers in RAM are in common with line numbers in working
memory, the line numbersofthe RAM file take precedence over those in working
memory. Finally, you learned how to delete files from working memory and from
RAM.
29
Lesson
This lesson illustrates the useofvariables and the assignmentofvalues to variables.
Applications to the calculation
examples
The programs used in this and all the following lessons will be explained line
to give you a thorough understanding
of
#3
the useofvariables in BASIC programs.
Interest Calculations
of
interest and mortgage payments will serve as useful
of
the operations and the concepts involved.
by
line
Experiment
If
P dollars are borrowed at the simple interest rater,then the amount S that must be
repaid after
S is called the sum and P is the principal. The first program in this lesson calculates S
for the following values
CarefUlly enter the following program into the Computer:
After the program is entered, execute it by entering the
RUN
t years is given
S =
P(l
P = $10,000
r = 18%
= 10 years
t
P
10
2
3
L10
50
Function Key, (fj).
THE
Ok
III
III
=
R
=
T
=
5
=
PRINT
SUM
+ rt)
per
1111000
•
18
10
P
IS
#1
year
( 1
*
"THE
$
Simple interest
by
the fonnula
ofP,rand
+ R
SUM
The
28000
t:
T>
*
$"
IS
output from the program should
;
5
RUN
commandorpressing the
be:
•
If
$10,000 is borrowed for 10 years at the simple interestof18%, you will have to
pay back
$28,000.
31
How the simple interest program works:
Line18assigns the valueof10000 to the variable P. This is called an assignment
statement.
assigned to it. Note that the principal, $10,000, is written without the dollar sign ($)
or
comma (,). In general, numeric constants shouldbewritten without
dollar signsinBASIC.
The letter P is called a numeric variable because numerical values can
commas
be
or
Line28assigns the valueof.18
the 18% interest rate. The conversion to decimal form is necessary because BASIC
does not allow numeric constants to be written with a percent
Line
38 assigns the value
allowed to repay the loan.
Line48computes the
Note that the expression,
P *
(1
+ R *
looks very much like the formula previously seen for calculating the sum.
"*,,
is used to denote multiplication and, as usual, + denotes addition.
Line58printsanexplanatory message and the valueofS.
The variables
variable can be
a)any letter
b)any two letters
c)a letter followedbya number.
For example, the following are all valid numeric variables:
A
But the following are not valid numeric variables:
P,R,T and S are all valid examplesofnumeric variables. A numeric
or
AA
sumofprincipal and interest and assigns it to the variable S.
T),
B2
to the variable R. This is the decimal equivalent
(%) symbol.
of
10 to the variable T. This is the lengthoftime (10 years)
The
CQ
Y9
symbol
of
IS
The ftrst four linesofthe program are assignment statements. In general, an
assignment statement follows the form:
$5
A?
variable = expression
where "variable" is any valid numeric variable and "expression" is any valid
The
numeric expression.
expression is assigned to the variable.
The
arithmetic operators in BASIC are:
right hand side canbea constant. The valueofthe
+addition
subtraction
*
I
"
multiplication
division
exponentiation
32
Line 40 contains an exampleofa valid expression containing arithmetic operators.
Here are some more:
a)A*B/C
b)Q
c)
+ A4 - 6.5
F * H8 + J9
You should note that spaces
this type. For example, the expression in a) could have been written
A*B/C
This allows you
However, it is important to note the order in which expressions such as c) are
evaluated.
In BASIC, mathematical operations always follow a hierarchical order. Exponentiaton
has the highest priority, multiplication and division are next, and finally. addition and
subtraction have the lowest.
Therefore, expression c) above, is interpreted
to
J9."
However, if you wanted to add H8 and J9 together before multiplying their
sum times F, you would have to place parentheses around H8
F * (H8 + J9)
In this case the addition is performed first because the operation inside the parentheses
is
carried out before the outside multiplication.
Multiplication and division have equal priority and will
right. The same is trueofaddition and subtraction.Ifyou look at line 40 again
40 S = P *
it should be clear that the parentheses are needed. However, inside the parentheses,
the expression:
orA*B / Cor
to
space out the symbols so that they can be easily read.
(1
+ R *T)
or
blanks are not significant in arithmetical expressions
A * B/C
as
"the
productofF times H8 is added
+ J9:
be
performed from left
to
of
+ R * T
1
is
calculated correctly because the multiplication has higher priority than addition.
Experiment
If
you invest P dollars at an annual interest rate r, compounded k times a year, then
t years, your investment will have grown to the amount
after
S =
PO
A program will be written to calculate the value
other variables:
Pis
$ 5,000
r is 12% per year
tis
5 years
k is 4 (i.e. interest is compounded 4 times a year.)
#2
+ r/k)tk
Compound Interest
of
S, for the following valuesofthe
33
S:
Enter the command NEWtoclear the previous program from memory. Then type the
following program:
P
10
20
30
40
50
80
After the programisentered, execute it by entering the RUN commandorpressing
~.
The output frum this program will be:
=
R
=
T
=
K
=
S
=
PRINT
5000
.12
5
4
P
*
"TOTAL
( 1
K)
~
$"
(T
;
S
+
R /
IS
K)
*
TOTAL
Ok
IS
$
9030.5561733465
•
Even though the totalissupposed to represent dollars and cents, the computer has
to
displayed the number with 14 significant digits, including 10
of
decimal place (because this is the precision
BASIC). You will see later how to display numbers in dollars and cents format.
The expression in line
P *
(l
+ R /
uses addition, multiplication and exponentiation operators. The exponentiation operator
has the highest priority and will be performed before multiplication or division and
course before addition and subtraction. Becauseofthis priority, it was necessary to
place parentheses around the exponent
T*K
Otherwise, the computer would have calculated
50
K)'(T*K)
numeric variables in Model 100
the rightofthe
of
P *
(l
+ R / K) A T
and then multiplied this expression by K.
Experiment
#3
Compound Interest with
Keyboard Input
If
you wantedtorun the compound interest program with different values for the
variables, you would have to retype the appropriate lines in the program. Obviously
that isn't very practical, specially
values.
if
you just wanted to figure the interest for several
34
It
would be more convenientifyou could simply type in the values for the variables
as
the program is being executed.
The program will be changed so that the value for P, the principal, can be entered
as
during execution. The values for the other variables will be assigned,
assignment statements.
Change line10to
10
PRINT
"ENTER
.
THE
PRINCIPAL";
before, with
and insert line
15
List the program to verify thatitis:
10
15
20
30
40
508=
60
Execute the program.
When the program executes, the following message (called a
displayed:
ENTER
and the computer will wait for youtoenter the value for P. When a value for P is
entered, for example
Be sure to press
Here is what the output looks like:
ENTER
TOTAL
15
INPUT
PRINT
INPUT
R = •
T = 5
K = 4
P
"ENTER
P
12
P * (1 + R /
PRINT
THE
CENTER)
THE
18
THE
PRINCIPAL";
"TOTAL
18
K)h(T
$";
*
K)
8
PRINCIPAL?
5000, the program will executeasbefore
after typing the amount for P.
PRINCIPAL?
$
8030.5561733465
5000
"prompt")
and
print out the total.
will be
Line
10 prints the prompt message. The semicolonatthe endofthe line suppresses
so
the carriage return
Line
15 is the INPUT statement. When this statementisexecuted, a question mark
printed and the computer will wait for youtoenter a number from the keyboard. After
you type the number and press
which appears after
The remainderofthe programisthe sameasbefore.
If
the semicolon is left out in line 10, then the question mark and the number you type
be printed on the next line below the prompt.
will
that the next character printed will be on the same line.
(ENTER),
INPUT.
the number willbeassignedtothe variable P
35
is
Experiment
The
INPUT.
value
printed without using a separate PRINT statement.
Delete line
statementisusually preceded by a prompt messagetoremind you what
to
enter.
15
10
INPUT
#4
An
optional formofthe INPUT statement allows the prompttobe
(by entering just the line number
"PRINCIPAL";
Another Way to INPUT
P
15)
and retype line10as
follows:
This single line is equivalenttothe previous lines10and
will be printed immediately followed by a question mark. Then the Computer will
wait for you to enter the value for P. The ending quotation mark must be followed
a semicolon, a comma cannot be used.
It
List the program.
10
INPUT
20
R = •
30
T
40
K = 4
50
S = P *
60
PRINT
Execute the program. The following output occurs when you type 1000 for the
principal:
PRINCIPAL7
TOTAL
Ok
should read:
"PRINCIPAL";
12
;;;
5
"TOTAL
IS
$
(1
+ R /
1000
1806.1112346693
IS
K)~(T
$";
P
*
K)
S
15.
The word PRINCIPAL
II
by
Run the program several times, entering different values for
Experiment
#5
Compound Interest with More
the
principal.
Keyboard Input
In this experiment, the compound interest program will be changedsothat the rate,
wellasthe principal, can be input from the keyboard.
20
Delete line
Retype line
10
by entering just the line number.
10
as:
INPUT
"PRINCIPALtRATE";
36
P t R
(ENTER)
as
Now list the program to verify that it is:
10
INPUT
30
T = 5
110
K = II
50 S = P * (1 + R /
60
PRINT
When you execute this program, the following prompt willbedisplayed
"PRINCIPAL, RATE";
K)h(T
"TOTAL
IS
$"
j S
P,
R
*
K)
PRINCIPAL,
In response, you should enter two numbers separated by a comma. For example:
PRINCIPAL,RATE?
and again the amountofthe investment will be printed. The complete output will be:
This program illustrates another optionofthe INPUT statement. Values for more than
one variable can be assigned with a single INPUT statement. The variables should be
separated by commas and listed after the prompt. When the INPUT statement is
executed, you must type a value for each variable, separating the values with commas.
After the last value has been typed, you should press
Two separate INPUT statements could have been used, the first for the principal P and
the second for the rate R as follows
RATE?
2000,
RATE?
3979.577"7269318
20lc10,
.111
.14
(ENTER).
113
INPUT
213
INPUT
However, it is more convenient to use just a single statement as was done in the
program.
Experiment
"PRINCIPAL";
"RATE";
#6
R
Compound Interest with All
P
Variables Input
The previous program will be rewritten so that the values for all the variables can be
entered from the keyboard. The program will also be changed so that it will not
terminate after the total is printed. Instead, the program will ask again for values for
the variables so that the amount
different values.
of
the investment can be calculated for any number
37
of
s
Delete line 40 by entering just the line number and retype line 30asfollows:
30
INPUT
Then add two new lines:
70
PRINT
80
GOTO
"TIME,
(ENTER)
10
~
NUMBER
OF
PERIODS"
iT,
K
~
List the program to verify that it
INPUT
10
INPUT
30
50
5
60
PRINT
PRINT
70
GOTO
80
The program will prompt you for values for all four variables, Hereisan example
the outputofthe program with the following inputs:
PRINCIPAL,
TIME,
TOTAL
PFHNCI
The program will continue to ask for values for the variables until you terminate the
program manually by pressing
"PRINCIPAL,
"TIME,
= P
*
"TOTAL
10
NUMBER
IS
$
PAL.
( 1
RATE?
3979.5777269318
RATE?
NUMBER
R /
+
IS
OF
PERIODS?
(BREAK).
is:
$"
2000,
RATE";
OF
K)"(T
;
5
.i
P,
PERIODS";
K )
*
L
5,
4
R
T,
K
of
Line18prints a prompt and allows youtoenter values for the principal P and
the rate
Line 38 prints a prompt and allows you to enter values for the time T and the number
of
Line
principal and interest at the endofT years.
Line
output so that it doesn't run together vertically.
Line
allows you to input a variety
command each time.
R.
periods K. Lines 10 and 30 could have been combined into one line if desired.
68
prints out the message
78
skips a line on the display after the output from line 60. This spaces the
88 transfers control back to line 10, where the program starts over again. This
"TOTAL
of
values for the variables without entering the RUN
IS
$"
38
and the value
of
S, the total
of
Experiment
#7
Printing a Name
·Personalizing the Output -
The compound interest programasit currently exists
10
INPUT
30
INPUT
50
S = P *
60
PRINT
70
PRINT
80
GoTo
Add line 40asfollows:
£10
INPUT
and change line 60
60
PRINT
Add line
List the programtoconfirm it
65
65
1121
3121
£10
50
PRINT
INPUT
INPUT
INPUT
S = P *
60 PRINT
65
PRINT
7121
PRINT
80
GoTo
"PRINCIPAL, RATE";
"TIME,
(1
"TOTAL
10
"NAME";
to
"TOTAL
N$;"
NUMBER
+ R /
IS
N$
FOR
IS
$";
is
Klh(T
$";
"
S
OF
S
"PRINCIPAL, RATE";
"TIME,
"NAME";
(1
"TOTAL
N$;"
NUMBER
N$
+ R /
FOR"
IS
$";
OF
K)h(T
S
1121
PERIODS";
*
PERIODS";
*
P,
Kl
1',
K)
is:
R
T,
K
R
T,
K
When you execute the program you will be prompted,asbefore, for the principal,
of
rate, time and number
this data is entered, the name and the amount of the investment will
the program and enter the data
name you wish):
PRINCIPAL,
TIME,
NAME?
TOTAL
Execute the program several times with various numeric values and names. To
tenninate execution,
Lines
ut
NUMBER
JANICE
IS
. 38 allow you
periods. In addition, you will be prompted for a name. After
be
as
indicated below (of course, you may enter any other
RATE?
$
17618.22531759
(BREAK)
2000,
OF
PERIODS?
SMITH
must be pressed.
to
enter values for the numeric variables in the program.
.13
39
10,
2
printed. Run
Line40is another
name instead
This variable, N$, is an example
example.,
Line
JANICE
58 calculates the total
of
a number.
SMITH,
INPUT
statement. This time, however, you are expected to enter a
The
is called a
of
principal and interest.
name which you enter is stored in the variable N$.
ofa"string
"character
variable."
string."
The name that you type, for
Line60prints the message
Line
65 prints the name stored
amount
Line70skips a line (PRINTs a blank line).
Line
A
In some cases the string may consist entirely
considered a string as well as a numerical constant.
A
following are all valid examples
In line
numeric variable, the computer would continue to ask for data until a numeric constant
was entered.
of
the investment.
80 transfers control
string
is any sequenceofkeyboard characters, for example
SMITH
JOHN
1023 N.
1982
MACROCORP
MARCH
$120.95
valid
N$, A3$,
MAIN
12, 1984
string
variable
DA$,
40,
it is essential that the variablebea string variable.Ifyou tried to use a
"TOTAL
back
to line 10.
STREET
is any numeric variable followed by a dollar sign ($). The
AD$,
ST$
FOR."
in
N$ followedbythe word IS, the symbol $, and the
of
digits (e.g. 1982), but it can still be
of
string variables:
of
The assignment
statement.Itis possible to use assignment statements with string variables and
constants
statement:
assigns the string
assignment statement, it is necessary to enclose the string
Each string variable
assigned to string variables exceeds 256, you must set aside additional space. This is
done with the
the program:
This particular instruction allocates space for
more than
When the Computer is turned
just
11Z11Z1
A$
5
CLEAR
300
the name to the string variable N$ was made with the
as with numeric variables and constants. For example, the following
=
"RADIO
RADIO
CLEAR
can
statement.
SHACK"
SHACK
hold up to 256 characters.Ifthe total numberofcharacters
to the string variable A$. When using an
in
quotes, as shown above.
For
example, the following line couldbeadded to
31Z11Z1
300
characters.Ifyou attempt to store
charactersinN$,
an error will result and the program will terminate.
on,
space for 256 characters is allocated automatically.
40
INPUT
If
you require more, then the CLEAR statement must be used. Since itisunlikely a
name will be longer than 256 characters, the above program should not need the
CLEAR statement.
If,
on the other hand, your program had twenty string variables, each of which is used
to
hold a name, then the maximum of 256 would probably be exceeded. In this case,
the CLEAR statement would be needed.
Experiment
Clear working memory with the NEW command and type the following program from
the keyboard:
1121
INPUT
2121
R=R /
3121
INPUT
ill2l
INPUT
5121
8121
7121
8121
9121
When you execute this program, you will be prompted for the interest rate, the
amount
12
should be entered, not .12. Hereisan example of the execution of the program.
INTEREST
AMOUNT
NUMBER
MONTHLY
=
N
I
=
MP
MP
PRINT
of
the loan and the lengthinyearsofthe loan. If the interest rateis12%
#8
"INTEREST
1121121
"AMOUNT
"NUMBER
12
R /
=
= A /
OF
OF
PAYMENT
T
*
12
( 1
-
MP
"MONTHLY
RATE
LOAN?30000
YEARS
Mortgage Payment Calculation
(
121
1121121
A
) " ;
R
T
$"
j
MP
( 1
(0
RATE
OF
LOAN
OF
YEARS";
I)~(-N»
+
PAYMENT
-100)?
?
25
IS
$
-
II
;
/I
IS
12
315.967242659281
then
Line10allows the interest rate to be entered and stores it in variable
Line 20 converts the interest rate to a decimal value.
It
is
importanttonote that the equals symbol
the value computed on the right side to the variable on the left side."
is
mean the right side
assignment statement:
R = R
means to compute the right side, R / 100, and then store the result backinR.
Line 30 allows the amount of the loan to be entered and stored in numeric variable
Remember that numeric values are entered without a comma.
/100
equaltothe left side as in an algebraic equation. Thus the
41
(=)
in
a BASIC program means "assign
R.
It
does not
A.
Line40allows the lengthofthe loan (in years)tobe entered and storedinvariable T.
50 computes the numberofpayment periods (months) of the loan and stores the
Line
value in variable
N.
Line 60 computes the interest rate per month and stores it in variable
Lines 70 • 80 compute the monthly payment. The computation
to
rather than one,
Recall that the equals symbol
to
side
then stored in MP.
Line
Run the program several times with your own data. Have you ever wondered what
effect a change
the program and vary the interest rate while keeping the other variables constant.
the variable on the left side. In line 80 the value
90 prints the amount of the monthly payment.
Experiment
avoid having a long, complicated expression in a single line.
(=)
meanstoassign the value computed on the right
of
AlMP
in
the"
interest rate would have on your mortgage payment? Just run
#9
Calculation
of
Total Amount
1.
was
done in two lines
is computed and
and
Loan Balance
In additiontocalculating the monthly mortgage payment,asin
to
you might wish
multiplying the numberofpay periods N by the monthly payment MP. Type in lines
100
and 110asfollows:
100
110
compute the total amount you havetopay. Thisisdone
TA
= N *
PRINT
MP
"TOTAL
AMOUNT
PAID
IS
the last experiment,
$";
TA
by
Another calculation that can be made is the determinationofthe loan balance or
of
outstanding principal, after a certain number
120
INPUT
"CURRENT
YEAR
payments. Enter the following lines:
OF
LOAN"; Y
130 M = 12 * Y
140
B = (1 -(1 +
150 B =
MP
* B
160 PRINT "PRINCIPAL
Hereisa listing of the the complete program:
10
INPUT
20
R
INPUT
30
40
INPUT"NUMBER
50N
60
I
70
MP
80
MP
80PRINT
100
TA
110 PRINT
120
INPUT
130
M
"INTEREST
R /100
=
"AMOUNT
12 * T
=
R /12
=
(1
=
=
-
A /
"MONTHLY
= N *
"TOTAL
"CURRENT
= 12 * Y
MP
MP
OF
(1
+
AMOUNT
l)h(M-N»
REMAINING
RATE
OF
LOAN";
YEARS";
I)h(_N))
PAYMENT
YEAR
OF
(0
PAID
/I
IS
100)
-
A
T
/I
$"
IS
IS
LOAN";
;
$";
$";
" ;
MP
Y
B
R
TA
42
140
B =
(1
-
(1
+
I)~(M-N»
150
B =
MP
* B
180
PRINT
Here is an exampleofthe execution of this program:
"PRINCIPAL
REMAINING
/I
IS
$";
B
INTEREST
AMOUNT
NUMBER
MONTHLY
TOTAL
CURRENT
PRINCIPAL
This example would be typicalofan
80% mortgage
The discouraging result
over the
the principal remaining unpaid after
10
toward the original amount borrowed.
30 years
years you have paid
$71,200-$66,883.23=$4,316.77
RATE
OF
OF
PAYMENT
AMOUNT
YEAR
at
12.5% over 30 years. The amount of the loan would be $ 71,200.
is
(0
-100)7
LOAN
YEARS7
REMAINING
$ 273,559.51.
?
71200
30
IS
$
PAID
OF
of
IS
LOAN?
running this exampleisthat the total you will havetopay
By
12.S
759.88752679191
$
273559.50964509
10
18
S
66883.232623196
$ 89,000 home purchased with a conventional
entering a current year of 10, you can see that
10
years is still $ 66,883.23. This means that in
What you have learned:
In this lesson, the use of string and numeric variables has been illustrated. Arithmetic
in
expressions have been used
INPUT statement was found
Computer.
the calculation of interest and mortgage rates. The
to
be a very convenient method of entering data into the
43
Lesson
It
is often necessarytowrite programs that will do one taskifa conditionistrue and
another if the condition
why this concept
#4
is
Sales Commissions
is
false. This is called branching. In this lesson you will learn
important and how to implement branching in your programs.
Experiment
A salesman is to receive a flat rate commission of
the total salesisover $2000, thenhewill receive an additional
$2000.
over
The formulas areasfollows:
Commission
Commission = .15 * sales + .20 * (sales - 2000)
Clear memory with the NEW command and type the following program:
1121
INPUT
ZI2I
CM=ST
3121IFST
4121
PRINT
Execute this program.
The program begins by asking you to enter the amount of sales. Type:
1121121121
to compute the commission on one thousand dollars sales. Note that a dollar sign is
not entered. The computer will respond with the message
COMMISSION
indicating a commission of $150.
~
#1
= .15 * sales
"AMOUNT
>
Sales Commissions
if
OF
*
.15
2121121121
THEN
"COMMISSION
IS
15121
15%
of his total sales. However,
sales are less than 2000
if
SALES";
ST
CM=CM+.20
IS";CM
20%
of the amount
sales are over 2000
* (ST -
2121121121)
if
Since the sales were less than
RUN the program again and this time when you are askedtoenter the amount of
sales, type:
3121121121
to
compute the commission on three thousand dollars sales. The computer will respond
with the message:
~
COMMISSION
indicating a commission of $650. Since the sales exceed $2000, the commission will
15%
be
Try running the program using your own sales data and confIrm that the program
computes the commission properly.
of $3000 plus 20%of$1000 (the amount exceeding $2000).
$2000, the commission is a straight fIfteen percent.
IS
85121
45
How the Sales Commissions Program Works
20
.--
__
'--_--,
COMPUTE 15%
COMMISSION
AMOUNT
OF SALES?
COMPUTE
ADDITIONAL
COMMISSION
COMMISSION IS
END
Figure
4-1.
FlowchartofSales
Commission
Program
When you execute the program, you will be prompted for the total sales. The
commission then will
ut
Line
Line
allows you to enter the total sales, which is stored in the variable ST.
28
computes the flat rate sales commission and stores it in the variable eM.
Line38contains a new statement, the
be computed according to the above scheme and printed.
IFITHEN
statement.Ascan be seen from the
flow chart in figure 4-1, the program must'branchafter line 20.
If
the sales exceed $2000,anadditional computation must be performed. However, if
this is not the case, then the sales commission is already calculated in line 20 and no
additional computation is required.
46
To accomplish this, the program must be able to test whether or not sales (ST) is
greater than
IFITHEN statement.
The
inequ~lity
ST>
$2000, and branch accordingly. This can be done with the useofthe
2000·
appearing in line 30 (between IF and THEN) is called a
is false, then the next statement to be executed is in line 40. On the other hand,
is
condition
CM
will be executed before control passes on to line 40. In other words,iftotal sales are
not greater than
sales are greater than
original flat rate commission.
The general format of the IF/THEN statement is
true, then the statement following THEN:
= CM + .20 * (ST - 2000)
2000, no additional calculations are performed in line 30. But,iftotal
2000, the additional commissioniscalculated and added to the
"condition."
If
this condition
if
the
IF "condition" THEN "statement"
where "statement" is executed only when "condition"istrue. In either case, the
next line executed is the one following the IFITHEN statement.
of
The condition is usually the comparison
numeric expressions are compared with the use
..
>"
in line 30 is the relational operator.
Here is a table
numeric operatormeaning
of
numeric relational operators:
two numeric or string expressions. Two
of
a relational operator. In this case,
>greater than
<less than
< > or > <not equal to
> = or =>greater than or equal to
<= or =<less than or equal to
Assuming the variable A has the value
given below.
condition
A>l
A < - 1
A
< > 1
A
>=
2
<=
A
Here are some more examples
55 IF A
65 IF 5.6
75 IF CD/AC
0
of
valid IF/THEN statements
* B - C < D THEN A = B
< >
AB-4.6
< > 1 THEN CD = AC
THEN STOP
2, the logical values
logical value
true
false
true
true
false
47
of
some conditions
are
Each condition can contain only one relational operator. Thus the following condition
is not allowed:
A<>B<>C
It
should be clear that IF/THEN is a very powerful statement because it allows the
program to carry out different tasks and functions, depending upon the value or values
of
numeric expressions.
Experiment
One unsatisfactory aspectofthe Sales Commision program is that the value printed for
the commission does not directly indicate dollars in the customary fashion.
Run the program and enter the value 1763.89 for the total sales. You will see that
264.5835 is printed out for the amountofthe commission. The outputofthe program
is a decimal number that sometimes contains more than two digits to the rightofthe
decimal point.
It
would be much neaterifthe commission were printed to the nearest cent each time.
One wayofaccomplishing this is to use a different print statement. Insteadofusing
PRINT, the PRINTUSING statement can be used to format the output.
Make the following changes to the program:
Change line 40 as follows:
40
PRINT
and add a new line 50
50
PRINTUSING
Line 40 will display the message
COMMISSION
and line 50 will print the valueofthe commission. Nowifyou execute this revised
program you will see that the commission is printed, as desired, rounded to the nearest
cent.
#2
Printing Dollars and Cents
"COMMISSION
"####.##";
IS
IS
";
CM
For example, run the program and enter 1763.89 as the sales amount. This time the
commission amount prints as 264.58.
The string enclosed in quotes,
####.##
is called a format specifier, and it indicates how a number is to be printed.
Since twoofthe # symbols appear to the rightofthe decimal point, exactly two
digits will be printed to the rightofthe decimal point.
of
four digits to the left will be printed. (Fewer than four digits to the leftofthe
decimal point maybeprinted, depending on the sizeofthe number.)
48
By
the same token, a maximum
Since there are six # symbols and one decimal point specified, a totalofseven
of
columns will be used for the printing
"right justified" in this seven column field, meaning that there may be some blanks in
the left most columns, but not in the right-most.
the number. The number will be printed
Instead.ofusing a constant string, such as
string variable for the format specifier. For example, the program can be changed as
follows
as
A$
=
"####,##"
S0 PRINTUSING A$;
This will give the same outputasbefore. Again, the value printed for the commission
will be rounded to the nearest
string or a string variable, is always followed by a semicolon.
For some more examples, suppose CM
this is printed out with line 50 above. The following table gives the output for various
format specifiers
format specifler
A$ =
A$ =
A$
Experiment
There are other possibilities for format specifiers. Change line 45 in the program so
that it is:
A$ =
=
"####.##"
"####.#"
"#####.###"
"####.#####"
#3
eM
cent. Note that the format specifier, whether it is a
Dollar Signs
"####.##",
it is permissibletouse a
= 1416.3812 (actual value as computed) and
output
1416.38
1416.4
1416.381
1416.38120
as
A$
=
"$######,##"
Now run the program and input a varietyofvalues for the sales. In each case there
will be a dollar sign
will be some blanks between the
Now change line 45 so that it
as
A$
Run the program with a sales amountof1111.Asyou can see, the $isnow printed
just to the left
numeric field specifier instructs the computer to print a dollar sign immediately to the
of
the leading digit.
left
Experiment
Many times, payroll checks are printed with asterisks padding the leftmost columns
the field.
Change line
as
45
A$
($) printed to the left
$ and the left most digit
is:
=
"$$######,##"
of
the number $166.65. The useoftwo dollar signs to the leftofthe
#4
in the previous program to:
=
"**$######,##"
Checks
of
the field (9 column). In many cases there
of
the number.
of
49
Run the program with a sales amount of 1111. In this case you can see that in the
of
output
the commission
..........
the unused positions are, indeed, padded with the
Large dollar amounts are usually printed with commas. Try changing line
45
Run the program with a sales amountof123456. In the output of the commission,
***$42,809.60
the digits are now separated with a comma to make the readingofthe number easier.
If
your number requires more columns than you have specified, for example printing
34.56 with
be
printedtothe left of the numbertoindicate the field overflow.
Experiment
Change the sales commission program so that it is computed accordingtothe
following scheme:
if
if
The program must now make two different computations depending upon the total
sales.
$166.65
"*,,
symbol.
A$
=
"**$###,###.##"
"#.###",
sales are $2000 or under, commission is
sales are over $2000, commission is 20%ofsales
the number willbeprinted anyway, but the symbol
#5
Sales Commission Revisited
15%
of sales
45
to
"%"
will
The program is illustrated with the flow chart in figure 4-2. The branching can
accomplished with the useofa variationofthe IF/THEN statement, called the
IF/THENIELSE statement.
be
50
~-
AMOUNT
OF SALES?
20
COMPUTE
COMMISSION
30,40,50
YES
15%
END
NO
COMPUTE 20%
COMMISSION
COMMISSION
IS
Figure 4-2. Flowchart of Experiment 5
Modify the program by deleting line 20 and replacing line
3121
IF
ST
<-
2121121121
-
.2121*ST
Since this line requires more than 40 columns, it will not fit on a single lineofthe
display of your Model 100, but will overflow
to
255
may contain up
display.
characters, in which case it will extend over several linesofthe
THEN
CM-.15
to
the next line. A line in your program
51
30:
*
ST
ELSE
CM
A lineisterminated only when you press
to
List the program
10
INPUT
20
IF
40
PRINT
45
A$
50
PRINTUSING
Execute the program.
When prompted for the amount
computed as
Run the program again and enter a sales
computed
The IF/THEN/ELSE statement is used to execute one
depending upon the logical value
If
sales are less than or equalto2000, the commissioniscalculated as
and control passes
following ELSE is executed instead, so that the commission is calculated as 20% of
sales and again control passes
as
confirm that it
"AMOUNT
ST
<=
2000
OF
THEN
"COMMISSION
=
"**$###,###.##"
A$
;
of
$150.00, which is a straight 15%.
$600.00 which is a straight 20%.
of
to
line 40. However,ifsales are over 2000, then the statement
to
line 40.
(ENTER)
is:
SALES";
CM
and notatthe endofa display line.
ST
=
.15
*
ST
ELSE
CM
IS";
CM
sales, enter 1000. The commission will be
of
3000. This time the commission will be
of
two different statements
the condition.
15%ofsales
=
.20
*
ST
The general format of the IF/THEN/ELSE statement
IF
"condition" THEN "statement
"statement
"condition" is false
if
In either case, control passes
can be any valid BASIC statements. Here are some more valid examples
IFITHEN/ELSE statement:
100 IF A = 0 THEN A = B + 1 ELSE A =
200 IF A + B < 100 THEN A = B ELSE A = 0
Experiment
]"
is executedjf "condition"istrue, but "statement2"is executed
to
the next line in the program. The statements executed
#6
Computing Commissions for
]"
ELSE "statement
is:
B-1
2"
of
the
Several Salesmen
The Commission Sales program,asit currently exists, will compute the commission
for one salesman and terminate. To compute the commissions for several salesmen, it
must be modified.
List the programtoconfirm that it still looks like this:
10
INPUT
20
IF
CM
40 PRINT
45
A$
50
PRINTUSING
"AMOUNT
ST
<=
2000
=
.20
*
"COMMISSION
=
H**$###,###.##"
ST
A$
OF
THEN
;
CM
SALES";
CM
=
IS";
ST
.15
*
ST
ELSE
"
52
Line10will be changedsothat the nameofthe salesman can be entered along with
the sales amount.
10
INPUT
The name will be placed in the string variableN$and the sales amount in the numeric
variable ST. Line 20 will correctly calculate the commission, but line 40 must be
altered so that the name
40
PRINT
If
the name entered is SMITH, then line 40 will print
"NAME,
SALES"; N$,
is
printed. Change line 40
"COMMISSION
FOR
";
ST
to:
N$;"
IS
";
COMMISSION
and
line 50 will print the amountofthe commission after the word IS.
Here is a listing of the program after the changes have been made:
10
INPUT
20
IF
ST
CM
=
40 PRINT
45
A$
=
50
PRINTUSING ASi
If this program were executed, it would compute the commissionofa single salesman
and execution would terminate.
commission, it must branch back
a
GOTO
Now the programiscomplete:
statement after line 50. Type in a new line:
G0
GOTO
10
INPUT
20
IF
ST
CM
=
40 PRINT
45
A$
=
50
PRINTUSING A$i
G0
GOTO
FOR
SMITH
"NAME,
(=
.20
SALES"; N$,
2000
*
THEN
ST
"COMMISSION
"**$###,###.##"
If
10
"NAME,
<=
.20
SALES" i NS,
2000
*
ST
"COMMISSION
"**$###,###.##"
10
IS
CM
=
FOR
"i
CM
the programisto
to
line
10.
This can be accomplished with the use
THEN
CM
=
FOR"
CM
ST
.15
*
ST
ELSE
N$i"
IS
";
compute more than one sales
ST
.15
*
ST
ELSE
iNS;"
IS
";
of
This program illustrates a concept in programming called
a block of statements are repeated several or perhaps many times
program above, the entire program is repeated, each time with a different salesman
It
and sales total.
it
means
Try running the program and entering several names and sales amounts. Be sure to
press
will not terminate and must be manually terminated by pressing
~
should be noted that the program is an "infinite loop," which
when you wishtoterminate execution.
53
"looping."
in
This means that
a program. In the
(BREAK).
Experiment
#7
How to Escape From
an
Infinite
Loop
It is easy to add some statements so that programs that contain infinite loops will
terminate upon request.
be
In the Sales Commission program, for example, the sales total will never
But you can modify the program so that it terminates whenever a negative value for
sales is entered.
new
Type the
15
The
STOP
~.
Run the program.
When prompted to do so, enter a dummy name (such as END) and a negative sales
amount (such as
computing any commission.
The dummy name was necessary because the INPUT statement in Line 10 requires
you to enter two input quantities. Since a negative sales amount terminates execution,
the name you enter will not be used.
You can have more than one
program need not have any STOP statements in it at all.
line:
IF
ST
< 0
THEN
statement, terminates execution and has the same effect as pressing
The program will terminateifST
-1).
Note that the program terminates immediately without
STOP
STOP
(ENTER)
is negative, but continueifit is not.
statement in your program.Ofcourse your
negative.
Experiment
#8
Individual Commissions for the
Salesmen
The Sales Commission program calculates every salesman's commission using the
same
rate. Nowwewill modify the program so that each salesman has his
commission rate. Here is a listofsalesmen and their commission rates:
Name
ADAMS
JONES
LEE
SMITH
VINSON
of
When any
the corresponding rate before the commission can
changes to the program:
Retype line 20 as follows
20
the above names is entered, the program must lookinthe table to find
READ
NU
t
CR
Rate
15%
16%
18%
20%
14%
be
calculated. Make the following
own
S4
and add lines 24, 26 and
24
IF
Nl$
28
CM=ST
28
RESTORE
Delete line 30.
Now the only remaining change
line:
70
DATA
ADAMS,.15,JONES,.18,LEE,.18,SMITH,.20,
<>
28
N$
THEN
*
CR
GOTO
is
to add the table to the program. Type the following
VINSON,.14
List the programtoconfirm that you have:
10
INPUT
15
IF
20
READ
24
IF
28
CM=CR*ST
28
RESTORE
40 PRINT
45
A$
50 PRINTUSING A$;
80
GOTO
70
DATA
"NAME,
ST
< 0
Nl$,
Nl$
<>
"COMMISSION
=
"**$###,###.##"
SALES"; N$,
THEN
STOP
CR
N$
THEN
GOTO
FOR
CM
10
ADAMS,.15,JONES,.18,LEE,.18,SMITH,.20,
VINSONt.14
";
20
20
ST
N$;"
IS
";
Run this program.
Be
sure to enter one of the five names listedinthe table. The program will compute
in
any
and print the commission for that salesman. Continue to input names
their corresponding sales totals. To end the program enter a dummy name and
negative value for the sales amount.
20 reads the first name (ADAMS) listed in the DATA statementinline 70 and
Line
It
places it in the string variable NI$.
it in the variable CR.
Line 24 compares the name in N$, which was entered in line 10,
they are different, the program jumps back to line 20 which then reads the next name
in
and commission rate
way until a match is found. When this happens,
commission rate for the salesman.
Line 26 computes the commission for the salesman.
is
the
Line 28
will go back to the first item in the data list. Therefore the next time a READ
statement
Without RESTORE, the reading of the
time before.
from
the beginning each time.
The remainder of the program is the sameasbefore, with the exception of line 70.
Line 70 contains the DATA statement from which the names and rates are read. This
RESTORE
is
executed,itwill use the first iteminthe DATA list.
If
the names are entered in an arbitrary order, the data list must be read
the DATA statement. The program continues looping in this
statement. When this statementisexecuted, the computer
reads the first commission rate (.15)
to
that in NI$.
CR
will contain the correct
data would continue where it left off from the
order and
and
places
If
55
statement can be placed anywhere in the program, butitis
at the beginning or the end of the program.
is
What would happen if a name
Run the program and enter the name CARTER and a sales amount
program continues reading names
program terminates and displays the error message:
?OD
ERROR
indicating that an OUT OF DATA error occurredinline 20. The program triedtoread
past the last name and rate in the list.
Additional names and rates can be added
statement. The computer treats multiple DATA statements
IN
entered, whichisnot in our list?
in
the DATA list until it runs out of data. The
20
to
line 70 or placedinanother DATA
traditional to place it either
of
1000. The
as
one continuous list.
What you have learned:
In this lesson you have learned how a program can be madetoBRANCH and
accomplish different tasks depending upon the value of a variable or expression. This
by
can be done
to
format the output so that it was presentedina more reasonable fashion than would
be the case with just the PRINT statement. You saw
to terminate execution under program control. You also learned that the READ/DATA
statements often provide a convenient method of inputing data
especially frequently referenced data like tables and lists.
using the IFffHEN statement. The PRINTUSING statement was used
howtouse the STOP statement
to
the program,
56
Lesson
Your Model 100 has a numberofstring functions which allow you to manipulate
string constants and string variables in various ways.
#5
Day, Time and Date
In this lesson you will learn how to use some special string functions that
the day, time and date. Also, other string functions will be used to extract information
from string constants and string variables and to output character data.
Experiment
DAY$ is a string function which returns the dayofthe week.Ifyou type:
PRINT
you will see that the first three lettersofthe present day are displayed. For example,
today happens to be Thursday, the Computer will display
DAY$
#1
What Day is it?
wrnID
"return"
Thu
Note: You must initialize the day sometime prior to using the DAY$ function. Once
initialized, the day will be automatically updated.
If
you have not already initialized the day, this can be done by entering the following
command:
DAY$ =
where
"xxx"
Monday, enter
DAY$
While the DAY$ function returns the first three lettersofthe dayofthe week, it is
often desirable to print the full nameofthe day (e.g. Thursday, not Thu).
"xxx"
are the first three lettersofthe current day. For example,iftoday is
=
II
M
ON"
CEBIEID
if
The following program, which we'll call DAY, accomplishes this. Refer to Figure 5-1
for a flowchartofthe program.
Clear working memory with the NEW command and type the following program in
from the keyboard.
10
READ
20
IF
30
GOTO
40
PRINT
50
DATA
60
DATA
Execute this program.
The program will output the dayofthe week. Hereisan exampleofthe output:
TODAY
0$
LEFT$(D$,3)-
10
"TODAY
Sunday,
Thursday,
IS
Thursday
DAY$GOTO
IS
";
Monday,
Friday,
0$
Tuesday,
57
40
Wednesday
Saturday
How program
DA
10
Y works:
READ DAY
ASSIGN TO
D$
TODAY IS
END
Figure 5-1. Flowchart of Program DAY
Line
18
A string from line 60 or 70 is read and assigned to the string variable
The first time line 10 is executed, the string Sunday will be assignedto0$,
second time line 10 is executed, Monday will
Line
28
The IF / THEN statement compares DAY$ with the first three characters
stored
in
0$.
DAY$ contains the first three charactersofthe current day (SUN,
MON, etc.). LEFT$(D$,3) returns the three leftmost letters
If
a match occurs, the program jumpstoline
Note that the IF statement does not contain the keyword THEN.
optional
Line
be
in
an IF statement when it is followedbya GOTO statement.
38
The GOTO statement transfers control back to line10where the next day will
read from the data list.
Line 48 The PRINT statement displays the message
day
of
the week.
be
assigned to
40,
otherwise line 30 is executed next.
"TODAY
0$,
etc.
of
the string stored in
The
keyword is
IS"
followed by the
0$.
the
0$.
58
Lines 58 • 68 These DATA statements contain the listofthe days of
the
week.
Lowercase letters must be used for the second and third characters to correctly match
of
DAY$, which stores the first three characters of each day
the week (an uppercase
and two lowercase letters).
This program uses two string functions,
of
the first three letters
the day of the week.
DAY$and LEFT$. Recall thatDAY$
The function LEFT$(D$,3) returns the first three characters of the string stored
D$
For example, if
has Thursday assigned to it, then
PRINT LEFT$(D$,3)
would display
Thu
of
The number 3 indicates the number
D$
contains Thursday, then
Command
PRINT LEFT$(D$,1)
PRINT LEFT$(D$,2)
PRINT LEFT$(D$,5)
characters to be returned. Again assuming that
Displays
as
T
Th
Thurs
etc.
is
LEFT$
characters
a string functionoftwo arguments, the string (D$) and the number of
to
be returned. The first argument need not be a string variable, it can also
be a string constant. For example,
PRINT
would display
Mod
LEFTS(
as:
"Model
100"
,3)
returns
in
D$.
When a string constantisusedasthe argument, it must be enclosedinquotation
marks.
DA
The last character in the name of both functions, LEFT$ and
($)
because the quantity returned,inboth cases,isa string.
Experiment
Program DAYisto
centered in the line with an equal number
#2
Centering the Day
be changed so that the output will consistofthe day of the week,
of
asterisks (*) printed on both sides.
Y$,isa dollar sign
Make the following changes:
40
Retype line
1I0 L = LEN·(
as:
OS)
and type four new lines:
5CLEAR
1I1i
AS =
~G
OS
LIB
PRINT
100
STRINGS(
= AS +
OS
OS
(1I0 -
+ AS
L)/2,
59
u*U)
Now list the program to confirm that it is:
5
CLEAR
10
READ
20
IF
30
GOTO
40
L =
44
A$
48
0$
48
PRINT
50
DATA
80
DATA
Execute the programbyentering the RUN command.Ifthe current dayisThursday,
the following will be output:
100
D$
LEFT$(D$,3)
10
LEN(O$)
=
STRING$(
=
A$
+
D$
D$
SundaY,
Thursday,
=
DAY$
(40
+
A$
Monday,
Friday,
-
L)/2,
THEN
Tuesday,
Saturday
GOTO
"*")
40
Wednesday
****************Thursday****************
If
the current dayisFriday, then the output will appear
*****************Friday************~~***
In
each case, the wordiscentered in the line and an equal number of asterisks are
printed on both sides to fill the line.
16
characters, then
The function
constant. For example if
value 6, and LEN("Friday") also returns a
Since
the
value returned by the function LENisan
attachedtothe function name. In line 40, the number of characters of the string stored
in0$is
a<;signed
asterisks are printed on both sides so that39columns are used.
LEN
returns the numberofcharacters in a string variable or string
0$
contains Friday, then the function LEN(O$) returns the
to
L.
If
the current dayisFriday, then L has 6 assigned to
If
the current dayisTuesday, which has 7
6.
as:
integer, thereisno dollar sign ($)
it.
60
Since each line has 40 print columns, the number of asterisks to be printed on each
side
of
the day
is
(40 - L)/2.
For example,
if
the current day is Friday, 17 asterisks must be printed before and after
the word Friday.
In line 44, the function STRING$ is used to construct a string of asterisks
if
correct length and assign it to the variable A$. Again,
(40 -
and STRING$( (40 - L)/2,
L)12=17
"*")
will be a string of17asterisks.Ifthe current day
L has the value 6, then
of
the
Tuesday, then L = 7 and
(40 - L)/2
This value will be truncated to
= 16.5
16
in the STRING$ function so thatA$will have
length 16.
gener~
The
STRING$(r,
formofthe STRING$ function
"x")
is
which constructs a string consisting of r repetitions of the character x.
The argument r can be a numeric constant, variable or expression. For example, if
J=3
and
M=2
Command
PRINT STRING$(5,
PRINT STRING$(J,
"#")
"X")
PRINT STRING$(J-M,"&")
Displays
#####
XXX
&
as
is
Line 46 illustrates the concatenation operator +. The strings A$,
joined together to form a new string which is then assigned
concatenation operator can
be
used with string constants or string variables. For
to
the variable
example:
A$="RADIO"+"SHACK"
concatenates the two strings
"RADIO"
and
"SHACK"
together to form a new string
"RADIO SHACK"
and assigns
Note that
Thus the old value which was assigned to
ittothe string variable A$.
in
line 46,
0$
appears both on the left and the right side of the equal sign.
0$isreplaced by the new string, which
printed in line 48.
D$
andA$are
0$.
The
is
61
Experiment
Another useful featureofyour Model 100 Computeristhe string function TIME$,
which returns the time
hh:mm:ss
#3
What time
as
a stringofthe form
is
it?
For example, if the time
PRINT TIME$
would print
13:05:00
The first two digits indicate the hour(lPM), the second two digits the minutes;
minutes after 1), and the last two digits the seconds.
The clock is a 24 hour clock,
indicating midnight.
Note: The time must be initialized prior to using the TIME$ function. Once set,
keep the correct time just like a clock.
you may do so by entering the following command:
TIME$
where hhisthe hour, mm the minute, and ss the seconds. The hourisin 24 hour
format,
TIME$
The following program will convert the string returnedbyTIME$, for example
14:18:00, to the customary format, 2:18 PM.
Clear the previous program from memory with the NEW command and then type the
following program:
= "hh:mm:ss"
so
that 3 PMishour 15. For example, if the current time is 3:05 PM, type
=
is
exactly 1:05 PM, then the following command:
"15:05:00"
so
the hours will range from 00to23, with 00
If
you have not already initialized the time,
(ENTER)
(5
it
will
10
HH$
=
LEFT$(TIME$,2)
20
HH=VAL<
30
IF
HH>=
40
IF
HH
50
HH$
= STR$(HH)
60
MMS=MID$(TIME$,4,2)
70
T$
=
80 PRINT
After the program has been entered, execute it with the RUN command. An example
of the output is
THE
TIME
LineHtThe first two characters in TIME$ are assigned to the string variable HH$.
These two characters designate the hour. For example, if it
contain the two characters 13. Since LEFT$ returns a string, these two characters form
a string even though they are numerical digits. Thus they cannot be assigned to a
numeric variable.
> 12
HH$
"THE
IS
HH$)
12
+
1:05
THEN
THEN
":"
TIME
PM
A$
= "
HH=HH
+
MM$+AS
IS";
62
T$
PM"
- 12
ELSE
A$
= "
AM"
is
1:05 PM, then HH$ will
Line 28 The string assigned to HH$ is convertedtoa numerical valuebythe
VAL
function. This numerical valueisassignedtothe numeric variable HH. Using the
13
previous example, HH would have the number
to
function, it would not be possible
make this assignment.
assignedtoit. Without the VAL
38 This statement determines whether it
Line
to
string value
A$. The value stored in HHiscomparedtothe numeric constant
is
AMorPM
and assigns an appropriate
12.
Only a numeric variable can be usedinthis way. The useofHH$ would have
was
produced an error and it was for this reason that the string stored in HH$
to
a numeric constant and assignedtothe numeric variable HH.
48
Line
example, hour
previous line, the variable must
is
Line 58 This line uses the STR$ function
back
The hour value is converted from a 24 hour format to a12hour format. For
13
would be converted correctlyto1 (PM). In this line,aswell in the
be
a numeric variable. The statement:
HH$
= HH$ -
12
illegal and would produce an error.
to
convert the numeric value storedinHH
to
a string whichisthen assigned backtothe string variable HH$. This will
changed
be
concatenated later with another string. In order todothis, a string variable must be
used.
Line 68 This line uses the MID$ function
to
read the two minutes digits from TIME$
and stores this two-character string in the string variable MM$. Note that the minutes
are the 4th and 5th characters in the string:
13:05:00
MID$(TIME$,4,2) returns two characters starting with the 4th from the left.
Line 78 In this line, the string to
variables HH$ (hour), MM$ (minutes), and
be
printedisconcatenated together from the
A$
(AM or PM). A colonisinserted
between the hour and minutes.
Line
88
The message
Here are some examples of TIME$ and the resulting output
TIME$
10:15:12
17:08:55
03:18:43
"THE
TIME
IS"isdisplayed followed by the time.
OUTPUT
THE TIME
IS
THE TIMEIS5:08 PM
THE TIME
IS
10:15
3:18
AM
AM
of
the program:
Note that a leading zero is not printed for the hour. This leading zeroislost when the
VAL function
is
applied.
The function VAL converts a string constant or variabletoa numeric value. The
following examples illustrate this function:
string
123ABBA
2.3CA987
567.4
The leftmost characters, up
are converted to a number. This function
VAL
123
2.3
567.4
to
the first character which cannot be partofa number,
is
useful when it is necessarytouse a
63
numeric string constant in a numeric expression. The number in string form must be
converted to a numeric constant before it can be used in a numeric expression.
is
The STR$ function
or variable to its string form. This
with another string
the inverseofthe VAL function.Itconverts a numeric constant
is
useful when you want to concatenate the number
as
was done in this program.
MID$(string,p,n) returns the sub-string
The
character. This is illustrated with the following examples:
string
ABCDEFGH
JUNE 18, 1983
RADIO SHACK
Experiment
The program in Experiment 3 did not print the seconds even though they are returned
by TIME$. The program will be changed so that the output will appear
THE
TIME
Make the following changes to the program:
Type a new line:
65
55$
and change line 70 to
70
TS =
SSS
List the program to confirm that it
#4
IS
=
RIGHT$(TIME$,Z)
HHS
+ " SECONDS"
p
5
10
7
Printing the Seconds
1:05
+
":"
PM
AND
+
MMS+AS
is:
of
length n starting with the p-th
n
3
2
5
28
MID$(string,p,n)
EFG
19
SHACK
SECONDS
+ "
AND"
as:
+
10
HHS
=
LEFTS(TIMES,2)
20
HH
= VAL(HHS)
30
IF
HH
>=
12
THEN
40
IF
HH
>
12
THEN
50
HHS
=
STRS(HH)
60
MMS=MIDS(TIMES,4,2)
65
SSS
=
RIGHTS(TIMES,2)
70
TS =
+ " SECONDS"
80
PRINT "THE TIME
Execute this program.
The output will depend on the time.
displayed:
THE
Line 65 The RIGHT$ functionisusedtoreturn the two rightmost characters stored in
TIME$. These characters are the seconds and are assigned to the string variable SS$.
The RIGHT$ function is similar
TIME
HHS
IS
+
5:23
":"
AS
= "
PM"
ELSE
HH=HH
+
MMS+AS
IS";
If
TIME$ = 17:23:56, then the following will be
PM
AND
to
LEFT$, except that the digits are counted from the
TS
56
64
-
12
+ "
SECONDS
AS
AND"
= "
+
AM"
SSS
right instead of the leftofthe string.Ofcourse, the MID$ function could have been
65
used instead. Using MID$, line
65
SS$ =
It
is usually easiertouse
leftmost or rightmost
MID$(TIME$t7t2)
LEFf$
of
the string.
would appear
or RIGHT$ insteadofMID$ if the characters are the
as:
Experiment
The string function DATE$ returns the date in the form
mm/ddlyy
For example,
PRINT
will display
if
#5
What's the date?
the present date is October 23, 1983, then the command:
DATE$
10/23/83
Note:
The date must be initialized priortousing the DATE$ function. Once entered,
If
the date will be automatically updated.
maydoso by entering the following command:
you
=
DATE$
where
mm
yy the year. For example,
DATE$
Delete the previous program from memory with the NEW command. The following
program will print the date in the usual form, (i.e., the name
and the year.) For example:
DECEMBER
"mm/dd/yy"
is the numberofthe current month (e.g.03for March),ddis
if
todayisDecember 25, 1983, enter
=
"12/25/83"
25t
1983
you have not already initialized the date,
the day, and
of
the month, the day
Type the following program:
10
MM$
= LEFT$(DATE$t
20
MM=VAL<
30
READ
110
CT=CT
50
IF
CT
80
DD$
= MID$(DATE$,
70
YY$
= RIGHT$(DATE$,
80 PRI
90
100
110
RefertoFigure 5-2 for the flowchartofthis program.
Execute the program. The output will be today's date in the usual format: month, day,
and year.
NTMM$;
DATA
DATA
DATA
MM$)
MM$
+ 1
<
MM
THEN
"
JANUARY,
MAYt
JUNEt JULYt
OCTOBERt
";
FEBRUARY,
2)
GOTO
ll,
30
2)
2)
DD$;",19";YY$
MARCHt
AUGUSTt
NOVEMBERt
65
DECEMBER
APRIL
SEPTEMBER
How Program
"What's
the
10
20
30
40
date?"
Works
SETMM$
TO MONTH
CONVERT
MM$TO
NUMERIC MM
READ MONTH
FROM DATA
LIST
INCREMENT
COUNTER
NO
60
SETDD$
70
80
DAY
SETYV$
TO YEAR
TO
--0
Figure 5-2. Flowchart of Program "What's the date?"
66
Line18The left two charactersofDATE$ are stored in the string variable MM$. This
is
the month. For example,ifthe monthisOCTOBER, then
"10"
assigned to it. Itisimportanttoremember that LEFT$ returns a string, not a
numeric constant.
MM$
will have the string
28 The string stored in
Line
function. This must be done because it will
to
number
Line 38
fIrst time, JANUARY is assignedtoMM$. Since the string originally stored in
will no longer be needed, the string variable MM$isreused in this line.
Line
the value 1 because the computer initializes all numeric variables to zero when the
program is executed.
Line
program will jump back to line
Eventually, CT will equal MM. When this happens,
assigned
into MM$, until the present month
loop (lines
Line
by
the 4th and 5th characters of the string stored in DATE$.
Line
that the year is given by the last two characters.
Line
followedbya semicolon which means that no columns aretobe skipped.Itwas
necessary
printed immediately after the month.
another numeric constant in line 50.
The next month is read from the DATA statements and placed in MM$. The
48 This line increments a counter CT. After the first month is read, CT
58Ifthe counter CT is less than the numberofthe current month; then the
to
it and line 60 will be executed next. Thus, the months
30, 40 and 50).
68 The MID$ function is used to extract the day from DATE$. The day is given
78 The RIGHT$ functionisusedtoobtain the current year from DATE$. Recall
88
The date is printed in this line. Note that each item in the print list
to
print a blank space after the month, or otherwise the day would be
MM$isconvertedtoa numeric constantbythe VAL
be
necessary to compare the month
MM$
w~ll
30, where the next month is read from the data list.
MM$
will have the current month
are
read repeatedly
is
reached, and then the program jumps out of the
is
have
98 - 118 These DATA statements contain the months of the year which are read
Lines
by the READ statement in line
30.
What you have learned:
In this lesson the three special string functions DAY$, TIME$, DATE$ and some of
their uses have been illustrated. Various other string functions have been used
extract information from string variables andtoprint out certain string quantities.
67
to
Lesson
In this lesson you will learn how to use the built-in Editorofthe Model 100sothat
changes
Until now, you have been able
following three ways:
I)
2)
3)
While any change
they can be time consuming. For example,
character
move one linetoanother location in the program, the old line must be deleted and the
line retyped with a new line number.
to
An
existing lineischanged by retyping it.
An
existing lineisdeletedbyentering just the line number.
A new line is added by enteringitwith the appropriate line number.
in
#6
a BASIC program can be made quickly and easily.
a lineofyour program, the entire line must be retyped.Ifyou want·
Using the Editor
to
make changestoyour BASIC programsinthe
to
your program can be accomplished using these three procedures,
if
you only wanttochange a single
to
An easier and more efficient way to make changes
to
Editor. The Editor allows changes
line. It also allows a line number
There are other convenient features
examined in detail.
Experiment
Enter the following program from the keyboard exactlyasitisprinted here:
10
INPUT
20
READ
30IF
00PRINT
50
DATA
80
DATA
This program prompts you for a name.Ifoneofthe names in the DATA statements
entered, (i.e. BETTY), the corresponding age (35) willbedisplayed. If the name
entered is not found in the DATA statements,
is
how the programissupposedtowork).
that
A$,
A$
DAN,
BETTY,
#1
Inserting a Character
~NAME";
AG
< >
N$
~AGE
IS",
32,
be made to a line without retyping the entire
to
be changed without retyping the line.
of
the Editoraswell. These features will be
N$
THEN
GOTO
A
RON,
35,
38,
RALPH,
of
this type istouse the built-in
20
LINDA, 02
29,
SKIP,
an
outofdata error will result (at least
3
is
69
Run the program. If you enter the name LINDA, the output will look like this:
i'M\ME?
AGE
Ok
1....
I~"3
I
NDf\
~~
II
Obviously, the programisnot working correctly. The correct ageis42, not 0. The
problem
Line 40 should appear
This error could be corrected by retyping the lineasshown above. But instead, we'll
use
after A. Type the command
You will see the following displayed:
isinline 40. Variable A at the endofthis line should be changed to AG.
as
£10
PRINT
the
Editor to change the variable name to
ED
I T
(ENTER)
10
INPUT "NAME";
2~:J
I~EAD
30
IF
40
PRINT
S0
DATA
60
DATA
"AGE
1'~'S
'j
A$<>N$
"AGE
DAN,
BETTY,
,·\G
THEN
32,
15",
IS",
35,
NS.
GOTO
A.
RON,
RALPH,
AG
AGbyinserting the single character G
20
38,
LINDA,
29.
424
SKIP,
3
The Computer enters the editor mode and the programisdisplayed. The cursorison
the
first character of the program. The symbol
at the end
when
To insert the
is
directly over the .... in line 40.
The cursor
of
(ENTER)
is
each lineisused to display the carriage return character thatisgenerated
is
pressed. The
"G"
after the variable A in line 40, the cursor must be movedsothat it
..,..
displayed after line 60isan end-or-file marker.
moved using the four Cursor Movement Keys in the upper right comer
of the keyboard. The arrows indicate which way the cursor will be moved when the
key
is
pressed.
70
Press the down arrow key three times. This should place the cursor on the 4 in line
40. The display should appear
I:~!
E~
l·:j
D
(-~i
~i~
.,
IF
A$~::>N%
PP I
i\~T
II
l,\(;;iE:
DATA
DATA
DAN,
BETTY,
,t;
(;~<{f
THEN
I
~:.~
32,
35.
as:
II
OJ
RON,
GO"f'O
l~
RALPH.
38,
LINDA,
29,
SKIP,
42~
3~
The cursor must now be moved to the right until itisover the last character (the
triangle) in line 40.
move to the right until the key
move the cursor to the desired position.
If
the right arrow keyispressed and held down; the cursor will
is
released. Using the right arrow keyinthis fashion,
If
you go too far, use the back arrow key to
back up to the correct position.
Once the cursor
done simply by pressing
notice that the letter G
is
correctly positioned, you are ready to insert
CID.
Do NOT press
is
displayed in the correct place and the carriage return
(ENTER)
after
the
letter G. This is
CID
is
pressed. You will
character moves one column to the right. At this point, the display should appear
INPUT "NAME";
j~E:tlD
IF
.<+~~
PF~INT
DATA
DATA
1",
:;;
~
A$<>NS
"l\(::iE:
DAN,
BETTY,
,1\6
When the Editor is used, the systemisalways in the
if
a keyboard characteristyped, this character will be inserted in the line where the
cursor was placed. Characters
THEN
I~:)",
32,
35,
to
Ns4
GOTO
RON,
20
It:;G~
38,
RALPH,
LINDA,
29,
SKIP,
42~
"insert"
mode. This means that
the rightofthe cursor move over to make room for
the inserted character.
You must remember to use the arrow keys
space bar or
Now that
CENllID.
"G"
has been inserted, you must exit from the Editor before you can
to
move about on the display, and not the
execute the program. To exit from the Editor:
as:
PRESS
THE
ESCAPE
PRESS (lID once
KEY
(ESC)
TWICE
71
or
After this is done, you will be back in BASIC with the updated program. Listitto
verify that it
10
20
30
l10
50
80
Note that line 40 contains the correct variable AG. Execute the program. Hereisan
exampleofthe
is:
INPUT
READ
IF
AS
PRINT
DATA
DATA
output:
"NAME";
AS,
AG
< >
"AGE
DAN,
BETTY,
NS
32,
THEN
IS",
35,
N$
AG
RON,
RALPH,
GOTO
38,
20
LINDA,
2S,
SKIP,
l12
3
NAME?
AGE
Ok
LINDA
IS
42
II
Run the program several times entering different names to verify thatitis
correctly.
Experiment
Lines10and 40ofthe previous program will be changed to
10
INPUT
l10
PRINT
The word YOUR must be insertedinboth linesasshown above. This will be done
using the Editor.
Type the command
ED
IT
(ENTER)
#2
"YOUR
"YOUR
Inserting a Word
NAME";
AGE
IS";
NS
AG
executing
to enter the Edit Mode.
72
The following will be displayed:
10
20
30
40
50
60
INPUT
READ
IF
PRINT
DATA
DATA
"NAI"IE";
AS, AG-4
A$<>N$
"AGE
DAN,
BETTY,
THEN
IS",
32,
35,
NS4i
GOTO
RON,
38,
RALPH,
LINDA,
29,
SKIP,
42~
3~
The cursorisplaced over the 1 in line
cursor is directly over the letter N in the word NAME.
Line
10
should appear
Type in the word YOUR followed by a space. Line10should now appear
10
INPUT
Line10is
A
of
careful nottopress any other keys while you are moving the cursor. When you have
the cursor positioned correctly, line 40 should appear
The cursor is positioned correctly for the insertion,sotype the word:
nowinthe desired form. Next, the cursor mustbepositioned on the letter
the word AGEinline 40. This can be done using the Cursor Movement keys.
'+0
F'R II\IT
as
"YOUR
NAME";NS
IS";
10.
Move the cursortothe nght so that the
as:
AG'-
as:
YOUR
followed by a space. Line 40 should now appear
l10
PRINT
At this point editing is finished, so you can exit from the Editor. Press
go
backtoBASIC or simply press
"YOUR
AGE
IS",
CfID.
AG
as:
(ESC)
twice to
Be
List the programtoconfirm that it is:
10
INPUT
20
READ
30
IF
l10
PRINT
50
DATA
8~
DATA
Note that lines10and 40 contain the desired changes.
AS,
AS
DAN,
BETTY,
"YOUR
AG
< >
"YOUR
NAME";
N$
AGE
32,
35,
THEN
RON,
RALPH,
IS",
N$
GOTO
AG
38,
73
20
LINDA,
29,
l12
SKIP,
3
Execute the program. You will have to enter one of the names listed in the Data
statements, or an
N
,0.
1'1
f:::
YOUR
Ok
?
RON
AGE
OutofData
If3
error will occur. Hereisan exampleofthe
~.m
output:
•
Execute the program several times, entering different names.
Experiment
In
additiontoinserting a character, the Editor can be used to delete a character. This
is
easily done and will be illustrated in this experiment. The variable AG in lines 20
and 40 of the previous program will be changed
Type the command
ED
I T
(ENTER)
to
invoke the Editor. The following should be displayed:
10
INPUT "NAME";
30
IF
40
PRINT
50
DATA
60
DATA
The Ainthe variable
arrow keys so that it is over the letter
#3
AS<>N$
"YOUR
DAN,
BETTY,
Deleting a Character
to
the single letter G.
N$
THEN
32,
AGinline 20 will be deleted first. Position the cursor with the
AGE
35,
GOTO
IS",
RON,
RALPH.
20~
AG
38,
LINDA,
29,
SKIP,
G.
Line 20 should appear
42~
as
Note that the cursor is positioned to the right of the character to be deleted. Now press
CIKSf).
Notice that the letter A has been deleted
to
that the cursor
Line 20 will now appear as
as
desired and that the characters which were
the rightofthe deleted letter A have been movedtothe left one position. Also note
is
still positioned over the letter G.
74
Using the arrow keys, position the cursor over the letter Gofthe variable
40. When you have done this, line 40 should appear
40
Press
PRINT
(BKSP)
"YOUR
to
delete the letter A. Line 40 now should appear
AGE
IS!I~
as:
as
AG
in line
At this point, the editing is finished. Press
program to confirm it is:
10
INPUT
20
READ
30
IF
a0
PRINT
50
DATA
80
DATA
Execute the program to confirm that itisworking correctly.
It
should be clcar that characters can bc easily deleted with the use of the Editor. You
need only remember to position the cursor one character to the right
be deleted.
Another very similar way to delete characters consists
positioning the cursor right over the character you wish to delete and then pressing
(DEL)
(CSHIFT)(BKSP)).
As with
vacant space.
(BKSP),
Experiment
Hereisthe previous program againasit
"YOUR
NAME";
A$, G
A$
< >
N$
THEN
"YOUR
DAN,
BETTY,
characters to the right of the deletion will shift to the left to fill the
#4
AGE
32,
RON,
35,
Changing a Character
(ESC)
twice to exit from the Editor. List the
N$
GOTO
IS",
RALPH,
20
G
38,
LINDA,
28,
SKIP,
of
currently existsinmemory:
42
3
of
the character to
entering the Editor,
10
INPUT
20
READ
30
IF
a0
PRINT
50
DATA
80
DATA
The commainline 40 will be changed to a semicolon so that the age will be printed
closer to the phrase
printed in the next field. The use
space before the age. The change will be made with the Editor.
Enter the Editor with the command
ED
IT
(ENTER)
A$, G
A$
DAN,
BETTY,
"YOUR
< >
"YOUR
"YOUR
NAME";
N$
THENGOTO
AGE
32,
RON,
35,
AGE
of
N$
20
IS",
RALPH,
IS."
a semicolon, however, will eliminate all but one
G
38,
LINDA,
28,
The comma specifies that the age will be
75
a2
SKIP,
3
Again you will see displayed:
,1~
2L'l
30
40
50
60
INPUT
F~EAD
IF
PRINT
DATA
DATA
"NAME";
A~i.
A$<>N$
"YOUR
DAN.
BETTY,
(";:j
4!l
TI-·lE!\1
AGE
32.
35.
N$<IIi
GUrU
IS".
RON,
RALPH,
2(;.~1Ili
G
38.
LINDA,
29,
42
SKIP,
]~
....
Position the cursor so that itison the space preceding the variable Ginline 40. When
this
is
done, line 40 should appear
·4«:1
PRINT
Press
COkSP)
cursor. After this is done line 40 will appear as
40
PRINT
Note that the cursor IS still on the space which precedes G, thus itisin the correct
position
to
insert the semicolon. Type a semicolon. Line 40 should now appear
"YOUR
on the keyboard. This will delete the character justtothe leftofthe
"YOUR
A<:iE
AGE
as
IS".
IS"
·4
4
as:
£10
PRINT
This is the desired formofline 40. You must remember that when
character deleted will be the one just to the left
ftrst, then the cursor will be positioned correctly for the insertion
The operation can be carried out in the reverse order, but after the insertion, the cursor
must be moved one position to the right before the deletion
Exit from the Editor by pressing the Escape key twice, or just hit
Execute the program several times to conftrm that itisworking correctly.
Experiment
List the previous program. You should see:
10 INPUT
20
READ
30
IF
£10
PRINT
50
DATA
80
DATA
A$t
A$
DANt
BETTYt
"YOUR
#5
"YOUR
G
< >
"YOUR
AGE
15";
G
of
the cursor.Ifthe deletionisdone
Changing a Word
NAME"·;
N$
THENGOTO
AGE
32t
RONt
35t
N$
15";
38t
RALPHt
20
G
LINDAt
29t
SKIPt
is
£12
COKSP)
of
the new character.
done.
(fS).
3
is
used, the
76
In this experiment, the name RALPH in line 60 will be changed to MORT, with the
use
of
the Editor. Enter the command
ED
IT
COO!ID
,
to activate the Editor.
it
is
Position the cursor in line 60 so that
60 should appear
60
DATA
Press
(BKSP)
appear
The cursoriscorrectly positioned for the insertionofthe new name. Type in the name
MORT. Line 60 should appear as
Line 60 isinits desired form; RALPH has been replaced by the name MORT. Exit
from the Editor.
60
60
as:
DATA
DATA
as:
BETTY,
five times to delete the name RALPH. After thisisdone, line 60 will
BETTY,
BETTY,
35,
35,
35,
on the comma after the name RALPH. Line
RALPH.
MORT,
29,
29,
SKIP.
SKIP,
List the program to confirm that it is:
10
INPUT
20
READ
30
IF
a0
PRINT
50
DATA
60
DATA
Execute the program. Here is an exampleofthe output:
N/",ME? 1'10RT
YOUR AGE
Ok
These experiments have illustrated how the Editor allows a character or characters to
be inserted, deleted or changed in a program without retyping any lines. With a little
practice you will become quite adept at using the Editor to make necessary changes to
your program.
A$, G
A$
DAN,
BETTY,
"YOUR
< )
"YOUR
IS
29
NAME",
N$
AGE
32,
35,
THEN
RON,
MORT,
N$
GoTo 20
IS";
38,
G
LINDA,
28,
SKIP,
az
3
77
Experiment
#6
Changing Line Numbers
Delete the previous program from working memory with the NEW command.
The following program allows
keyboard. When a zero in entered, the average
an
arbitrary listofnumbers to be entered from the
of
the non-zero numbersiscomputed
and displayed. (At least that is what the program should do.)
Type the program exactly
10
INPUT
20
CT
=
CT
30
40
50
80
AI) =
IF
GOTO
PRINT
Al,l
N=0
10
as
it is listed:
"NUMBER";
+ 1
+ N
THEN
"At,lERAGE
GDTO
N
IS";
80
AI)/CT
The program accumulates the sumofthe numbers in the variable AV. The variable
CT
is
a counter that records the numberofvalues entered.Ifthe number entered
then the averageisprinted in line
Hereisan
exampleofthe executionofthe program:
NUMr.ER?
NUMBt::rp
NUMBE:F~?
AVE
H/7iGE
'i-
~2
el
IS
:2
6@.
Ok
is
@,
Obviously, the programisnot working correctly. The averageofthe two numbers is
3, not 2. The reason for the inaccuracy is that the number
0 was counted by the
variable CT.
be
The program can
check for a zero value for N is done before the number N
correcled by inlerchanging lines 20 and 40. In this way, the
is
counted. One way
of
changing the orderofthe statementsisto retype the two lines. However,aneasier
methodisto
use the Editortochange the line numbers.
Use the command
ED
I T
(ENTER)
to enter the Edit Mode.
78
Thc following will be displayed:
10
20
30
40
:)(2)
60
INPUT
CTCT
f\'V
IF
GOTO
PRINT
"NUMBER";
"-:::
,I;'..}
N :0
1
"AVERAGE
,;"
+-
THEN
1
GOTO
IS";
60~
A'V/CT
The line number 20 must be changed to 40 and the old line number 40 must be
to
changed
appear
20. Movc the cursor to the 0 in line 20. When this is done, line 20 should
as:
CT
::"
CT
+-
The cursorispositioned correctlytochange the 2toa 4. Delete the 2 by pressing
~.
appear
Then insert the 4 by pressing
as:
CIJ
on the keyboard. Now the program should
10
1.1-121
:]
(Z!
40
5(;~
60
INPUT
CT
/':'.o,'..)
IF
ClOTO
PRINT
"NUMBER";
(:'1"
:::::
Nt
N =
:I.
"AVERAGE
+ l
+-
(2)
THEN
GOTO
IS";
60
AV/CT
Next, move the cursor down two lines so that itisover the zeroofline 40. The line
should then appear
as
79
Delete the 4 by pressing (IKIf), then insert a 2 by typing
appear
Although the lines are not listedinthe correct order, theydohave the correct line
numbers.
Exit from the Editor.
List the program. You will see:
as:
10
INPUT "NUMBER"; N
.t.~0
CT
-",
CT'
'+
:3~!l
i~
I,.)
::::
A
',,/
+ N
20
IF
SQ)
(,01'0
6(21
PRINT'
10
INPUT
20 IF
30
AV=AV
40
CT
:'50
GO
60
PRINT
N = 0
N=0
=
TO
THEN
l(;.i)·~
"I\'·/ERASE
"NUMBER";
THEN
+ N
CT
+ 1
10
"AVERAGE
1.
~
GoTo
GOTO
It3";
N
IB";
604
AV/Cr
60
AV/CT
tIl.
The program will
The programislistedinthe correct order, because BASIC always lists the lines in
your program according to their line numbers.
Here is an example of the execution of the program:
l\,IUMBER7
"JlJM]~,E:R?
NUI"IBER7 0
AVEH/,(;[
L~
::;::
IS
2
Ok
•
The program seems to be working correctly. Execute the program several times to
verify that it will work correctly in every case.
You
will find that the abilitytomove a line in your programtoa different position by
is
changing the line number
very useful and convenient.
80
Experiment
It
is possibletomove a word or even a phrase from one place in your program
another with the Editor. This can be very useful when you wanttoadd a line, or a
portion of a line to another line.
List the last program
10
INPUT
20
IF
30
AV=AV
£10
CT
50
GOTO
PRINT
60
The statement in line 40 will be placed in line 20, and line 40 eliminated. The revised
program will be
10
INPUT
20
IF
30
AV=AV
50
GOTO
PRINT
60
Enter the EDIT command.
#7
to
"NUMBER";
N=0
THEN
=
CT
10
"AVERAGE
as
follows:
"NUMBER";
N=0
THEN
10
"AVERAGE
Changing a Phrase
confirm thatitis:
N
GOTO
+ N
+ 1
GOTO
+ N
60
IS";
N
IS";
60
AV/CT
ELSE
AV/CT
CT=CT
to
+ 1
l"i·~
1<4
THEN
THEN
as:
N~
GOTO
1i
IS
GOTO
GOTa60
604
;
6~~
AV/
as:
as
ELSE.
The program will be displayed
10
INPUT "NUMBER";
20
IF
N = 0
31~~
t;V
"'"
'+0
CT
:::::
::~i(21
GOfO
6~
PRIN'r
First the word ELSE will be added to line 20. Position the cursorinline 20 over the
carriage return character. Line 20 should appear
20
IF
N =
The cursorisnow positioned for the insertionofthe word ELSE. Type a space and
then the word ELSE. Line 20 should appear
20
IF
N =
Next, the statementinline 40 must be inserted after the word ELSE in line 20. This
accomplishedasfollows: Position the cursorinline 40asfollows
THEN
l'lV +
CT
-+
:l
IIAVERA(3E
(2)
(2)
is
'"
cr
+.
:l
81
The cursor is placed on the first character (a space)tobe moved. Press the
SELECT
Function Key (Cfl)) on the top row of the keyboard. Move the cursortothe right
by pressing
8until
itisover the carriage return characteratthe endofline 40.
As
the cursor moves, you will note that the characters are printed in reverse video (light
to
on dark). This indicates which characters are going
appear
as
be moved. Line 40 should
Press the CUT Function Key
disappear from the screen. Line 40 should now appear
(~).
When youdothis, the characters marked will
as:
The characters to be movedtoline 20
CT
=
CT
+ 1
which no longer appear on the display have been movedtoa temporary storage area
the computer called the
done above,iscalled a
"PASTE
"cut."
buffer."
The operationofdeleting characters,
as
The remaining charactersinline 40, namely the number 40 and the carriage return,
to
will now be deleted. Position the cursor so that it is
the right of the carriage return
character.
£1121.
Press
(BKSPl
three times. This deletes what was leftofline 40. Since
of
instead
in
the "PASTE buffer."
using a
"SELECT"
Your program should appear
1.G1I !'.IPUT
20
IF
3~1
,':;\.,1
50
GOTO
60
PRINT
II
j\IU!'IBEr~
N = 0
~,
AI)
..;-
10~
"AVERAGE
THEN
N~.
as:
and
Ii;
GOTO
IS";
"CUT"
N
60
operation, these characters are not saved
ELSE
AV/CT.
(BKSPl
was
used,
in
The only remaining operationisto insert the characters savedinthe PASTE buffer
into line 20. Position the cursor in line 20 over the carriage return character. When
is
done, line 20 will appear
this
as
82
To insert the characters in the paste buffer, press the PASTE Command key on the
as
keyboard. When this is done, the characters will be inserted
now appear
20
:I.+-
.
IF
as:
N - 0
THEN
GOTO
60
ELSE
CT
desired. Line 20 will
-
CT
+
The movementofThe
SELECT, a
After the cut operation, the characters remain in the paste buffer and can be inserted
another partofthe programifdesired.
Exit from the Editor. List your program to confirm that it is correct:
10
20
30
50
60
Execute the program to confirm that it works as it did before.
CUT,
INPUT
IF
Alj
GDTD
PRINT
Experiment
characTers from one partofthe program to another requires a
and a PASTE.
"NUMBER";
N=0
THEN
=
AlJ
+ N
GOTO
N
60
ELSE
CT
=
CT
+ 1
10
"AljERAGE
IS";
AlJ/CT
#8
Copying a Phrase (without deleting it)
The previous program will be modified so that the sum of the numbers entered will be
as
printed before the average value is printed. The revised program will be
10
INPUT
20
IF
£10
AlJ=AV
50
GOTO
PRINT
60
70 PRINT
"NUMBER";
N=0
THEN
10
"SUM
"AljERAGE
+ N
GOTO
IS";
N
60
AlJ
IS";
ELSE
AlJ/CT
CT
=
CT
+ 1
follows:
in
Note that the previous line 60 is now line 70 and a new line 60 has been added. These
changes will be made with the Editor.
Enter the command
EDIT
83
The program will be displayedasusual:
10
INPUT "NUMBER";
20
IF
1,q~
30
40
50
61ll
N = 0
AV-AV+N,,:!
CT
--
CT
GOTO
PRINT
10#~
"AVERAGE
THEN
+ 1
<ilI1
N.
GOTO
IS";
60
ELSE
AV/CT.
CT-CT
+
Since the new lines 60 and 70 are very similar, the easiest waytorevise the program
istocreate a copyofline 60 and then make the necessary revisions.
Put the cursor on the 6 of line 60. Line 60 should appear
PRINT
Line 60isto
"AVERAGE
IS",
Al/lCT
....
be transfered to the paste buffer. Press the SELECT Function Key
as:
«(f7)).
After this is done, move the cursor down one line, so that it isonthe endoffile
marker. Line 60 will now appear
as:
Note that the entire line is in reverse video, indicating that itisreadytobe transfered
to
the PASTE buffer. This line should not be deleted when it is transferedtothe
so
buffer,
press the
deletes. Now line 60 appears
60
PfHNT
COpy
Function Key
as
II/WERAGE
ISII;
(~).
Remember that
A\lICT~
~
transfers and
The cursor is alreadyinthe correct place for the insertion,sopress the paste key. You
should
60
60
see:
PRINT
PRINT
IIAVERAGE
"AVERAGE
C:'"
,.j
I
ISH;
•
,
AV/CT'~
AV/CT~
The second line number 60 will now be changedtoa 70. Position the cursor over the
o
in
the second line number 60.
60
61
+.-
PRINT
PRINT
"AVERAGE
"AVERt\GE:
18";
IS";
AV/CT
A\,1./CT
84
Press
(BKSP)
and then
CD,
to change the 6 to a7.These two lines will now appear as:
60
PI~I!\IT
70
P!~~I!'rf"
"
.c'\'-v'ERl\(;;iE
"
AVEI~AGE
I
.,.
1
F~If~
f"'~
H u
~~
t.\)/
,6,"/
i
'J
cr~
Line 70 is in the desired form. Move the cursor to line 60 so that it is on the space
after AVERAGE. Line60will appear as:
6iZ!
PRI
NT
II AVE
!'I;~jl:::.!'!lF!j"
Press
(BKSP)
until the word AVERAGE is erased. Then type in the word SUM. Line
60
will be:
60
PRINT
"SUM
IS";
The last step is to delete the characters
~:;"
~
AV/
"/CT"
,tV).I
CT.
at the endofthe line. Move the cursor
to the endofthe line so that it is over the carriage return character 0
r
1>
FjR
I
I,.,oor
Press
6
60
l,(J
~
PRINT
"CUlv' I
i~
-...J
three times to erase the characters. Line 60 will be in the desired form
"8UM
Co".
A'
J i
11
•
~_,
~
IS";
.
\0'.'
Av4
('OOf".·"··
'-'
. .
Exit from the Editor. List the program to confirm that it is:
1121
INPUT
2121IFN=12I
1112l
AV=AV
5121
GOTO
SI2I
PRINT
7121
PRINT
"NUMBER";
THEN
GOTO
+ N
1121
"SUM
IS";
"AVERAGE
N
SI2I
AV
IS";
ELSE
AV/CT
CT
=
CT
+ 1
Execute the program. Here is an exampleofthe output:
NUMBER?
NUMBER'7 2
NlJl"IJ3ER? 0
SUi'1TE)
A\,JE
::-~ACiEI~3
·4
6
3
Recall thatifa BASIC program isSAVEd in RAM but changes are made to it when
the program is LOADed in working memory, the program SAVEd in RAM will
reflect those changes0
85
This is true alsoofthe Editor.Ifthe Editorisused to modify a program which was
in
previously SAVEd
You should practice using the Editor to modify your programs.
a very convenient and quick way
RAM, then these changes also appearinthe SAVEd program.
Yau
will find that it is
of
making changes.
What you have learned:
You have learned how to use the Editor to modify your
cases,
it
is easier and quicker to make changes with the Editor, than to make them by
retyping entire lines.
BASTC
programs.Inmost
86
Lesson
In this Lesson, you will learn how to create a program loop with a predetermined
number
variables, which will also be introduced in this lesson.
of
#7
repetitions. This is a useful technique when combined with subscripted
Sales Trend
Experiment
The program below is a "Sales Trend" program. Its purpose istohelp predict future
sales based upon the trend
to
find a straight line which best fits the historical data and thentoproject this line
into the future.
Clear working memory with the NEW command and enter the following program:
10
CLS
20
INPUT
30
FOR
110
PRINT
INPUT
50
60
SX
70
SY
80
NEXT
80
100
110
120
Execute this program.
The program begins by asking you
data. Type 6 and press
The program then prompts you for the sales data for each of the six time periods.
Enter the following sales data:
;;;
B
A
PRINT
PRINT
#1
Sales Trend
of
previous sales. The concept underlining this program is
"NUMBER
X
1
=
"SALES
TO
OF
N
FOR
Y
SX
+
=
=
SY
+
X:XX
Y:XY
X
(N*XY-SX*SY)
;;;
(SY
-
B*SX)
"FORECAST
A;
(ENTER).
II
"
+
PERIODS";
N
PERIOO";X;
XX
+
=
XY
=
/N
FOR
;
B;
..
to
enter the numberofperiodsofhistorical sales
+
/
(N*XX
PERIOD
X"
*
X*X
X*Y
SX*SX)
-
X IS"
SALES
SALES
SALES
SALES
SALES
SALES
The formula for a straight line
Y = A +
where Y stands for Sales and X for the time period number. Aiscalled the
"intercept"
FOR
FOR
FOR
FOR
FOR
FOR
B*X
and B the
PERIOD
PERIOD
PERIOD
PERIOD
PERIOD
PERIOD
"slope"ofthe line. The program uses the sales data which
is:
17
27
37
117
57
6?
103
110
108
120
118
133
87
you have just entered to compute the valuesofA and B.Ifyou entered the data
exactly as shown above, the program will print:
FORECAST
86.86666666666
You can now use this formulatopredict any future period sales by plugging an
appropriate value for X. For example, to predict period 7 sales, enter the following
from the keyboard:
PRINT
The resulting number, 134.467, represents the trend line forecastofperiod 7 sales.
You can use the program to calculate the trend line formula for any number
periods and any sales data. Try running the program again with your own data. You
can use any convenient time period you wish, such as day, week, month, quarter, or
year.
How the Sales
Look at the listingofthe Sales Trend program and compare it to the flowchart in
Figure 7-1.
Line
18 The CLS statement clears the display.
Line
28 The INPUT statement displays the prompt message "NUMBER OF
PERIODS?" and then waits for data to be entered. The question mark is automatically
added by the INPUT statement and should not be inserted within the quotes
prompt message. When
to
assigned
the numeric variable N.
FOR
86.8667
PERIOD X
+
5.371QZ8571QZ86*X
+
5.371Q3
Trend
IS
* 7
Program
Works
of
of
time
the
mEID is pressed, the number which has been typed will be
Line
38 The
with successive values for the index variable X. You can think
saying:
Perform the following statements with X equal to I. Then repeat the same
statements with X equal to 2. Continue repeating these same statements with
successively incremented values
statements when X becomes equaltothe upper limit N.
Since the variable N is INPUT during execution, this program can be used to compute
a trend line for any number
The end
When the NEXT X statement is encountered, the loop is repeated with the next value
ofX.If
following the NEXT statement.
In general, the FOR statement has an
The index variable must be a numeric variable. The start and stop values may be
constants, variables
30 FOR A = U TO
FOR
statement defines the beginningofa loop whichisto
of
of
X
(l,
2, 3, etc.). Stop repeating this loop
of
sales periods.
of
the loop is determined by a matching NEXT statement (see Line 80).
the upper limit N has been reached, execution continues with the statement
index variable, a start value and a stop value.
or
expressions. Another exampleofa FOR statement would be:
ZJ(Y
-2)
be repeated
this statement as
of
88
(Keyboard
)--
NUMBER OF
PERIODS?
Figure 7-1. Sales Trend Program Flowchart
89
In this case, the loop of statements would be executed first with the index variable A
equal to the start value stored in the variable U. The loop would then be repeated with
the index variable A incremented by 1, i.e. A
with increasing values for the variable A until the upper limit, determined
computing the valueofthe expression Z/(Y - 2),isreached.
to
There would have
statement to determine the end of the loop. After the last cycle through the loop with
A having the value Z/(Y - 2), execution continues with the statement immediately
after the NEXT A statement.
Lines
40 - 50 The PRINT statement prints the prompt message
SALES FOR PERIOD X
where the value of X
first time through the loop, X has the value 1,
be a NEXT A statement located in the program after the FOR
is
determined by the previous FOR statement (Line 30). The
= U+
1.
The loop would be repeated
so
the prompt message prints
by
as:
SALES
The second time through the loop, X has the value 2, so the prompt message prints
SALES
Each time through the loop, the prompt message requests the appropriate period
number because the variable X is being incremented in the FOR statement.
Note the use
period number (X) will print immediately after the word
semicolon tells the Computer not to move the cursor after printing the period number.
This means that the question mark
statement, will appear immediately after the period number.
The INPUT statement waits until a number
this number in the variable
the current period's sales amount.
60 • 70 These lines actually include two statements each. Line 60, for instance,
Lines
includes two assignment statements separated by a colon(:). Line
written
The two statements were put on the same line strictly as a matter of convenience and
to illustrate that
number
in
60 SX = SX + X
65
FOR
PERIOD
FOR
PERIOD
of
semicolons in this statement. The first semicolon ensures that the
an equivalent manner with two separate line numbers
XX
= XX + X*X
Multiple Statements (two or more statements) can share the same line
if
they are separated with a colon.
1
2
"PERIOD."
(?), automatically printed by the following INPUT
is
entered from the keyboard and stores
Y.
The variable Y actsasa temporary storage location for
The second
60 could have been
as:
as:
The formula for a straight line requires the summationofseveral quantities:
• the variable SX
• the variable XX
X*X)
• the variable
• the variable XY
All variables in a program are initially set to zero by the RUN command. Each time
through the loop, the variable X is incremented
read in as that period's sales.
is
usedtostore the sum of the X values,
is
used to store the sum of the squared X values, (Le. sum of
SY
is usedtostore the sum of the Y values, and
is
usedtostore the sum of X times Y (i.e., the sum of X*Y.)
to
the next period number, and Y is
90
The first time through the loop, therefore, SX will be replaced with the sum of zero,
the initial value stored in the variable SX, and one (the first period number).
Similarly, XX will be replaced with the sum of zero and one times one. The variable
is
XX now has the value one. The variable SY
period'~
first
sales (103 in the example above), and the variable XYisreplaced with
the sum of zero and one times the first period's sales (again,
7-1
Table
below illustrates how the four variables SX,
replaced with the sum of zero and the
103
in the example).
XX,
SY
and XY sumupthe
appropriate quantities on each repetition of the loop:
Loop cycle
0
1
22
3
44120
5
66
Line
80
The NEXT X statement determines the end of the loop of statements which
to
be repeated with successive values for the index variableX.So longasthe
are
X
00
I
Y
103
X*X
X*Y
0000
1
103
1104220
31099
16
119
5
133
Table 7-1. Sales Trend Line Calculations
25
36
327
480
595
798
SX
11
3
6
10
15
21
XX
5
14
304421130
55
91
SY
XY
00
103
213
103
323
322650
561
1725
6942523
value of X is less than the upper limit specified in the matching FOR X statement, the
loop will start over again with the next value for
When X reaches its upper limit(Nin
this case), execution transferstothe statement
immediately following the NEXT X statement (line
There must be a NEXT statement to match every FOR statementina program; without
a NEXT
therefore no way to know when
Lines 90 . 100 The assignment statements compute the slope, B, and intercept, A,
:statement, there would be no way to determine the endofthe FOR loop. and
to
repeat the loop.
X.
90 in this case).
which define the straight line which best fits the sales data. The use of parentheses
was
necessary in the expressiontoproperly compute the ratios:
B=
*XY
N<XX
SX * SY
SX *SX
N
and
A=
SY
B *SX
N
Using the sample data entered above, A and B are computed
B
6 * 2523
21
* 694
5.37143
21*21
and
91
as:
)'
Lines
A=
118.128
694 -5.37143 *
6
The PRINT statements display the resulting trend line equation:
21
96.8667
FORECAST FOR PERIOD X
96.86666666666 + 5.3714285714286 *X
Line 110 prints the text contained within the quotes:
"FORECAST FOR PERIOD X
Line 120 then prints the equation for the predicted salesinperiodX.Note the use of
to
the semicolons
also that the A and B in this statement are not enclosed
stored in the variables A and B are printed. All other items
enclosed in quotes and are therefore string constants, which print out
specified within the quotes.
Since Line 120
print.
The FOR / NEXT statement pair introduced
to
need
situation comes up regularly in computer programming, you will
the FOR / NEXT pair quite often in your own programs.
The following experiments will give you a few more ideas for its application and show
you that the FOR statement offers even more flexibility.
repeat the same set of procedures a predetermined number of times. Since this
the last statement in the program, execution terminates after the
#2
Arrays
IS
IS"
in
quotes,sothat the values
in
this statement are
eXflctly
in
this lesson is very useful when you
no
doubt wanttouse
as
This experiment will store the sales dataaspart of the Sales Trend program, rather
to
than ask you
This will make it easier
it each time the program
Change the Sales Trend program
20
25
input it during execution.
to
try
is
run.
N
24
=
DIM
Y(24)
several experiments on the data without havingtoretype
by
entering the following lines:
40
50
70
200
210
220
230
240
250
READ
BY
=
DATA
DATA
DATA
DATA
DATA
DATA
VeX)
BY
160,
155,
215,
225,
275,
300,
vex)
+
175,
215,
265, 220,
270,
350,
330,
:XY
140,
155,
265,
255,
315,
=
XY
X*Y(X)
+
230
225
325
280
3a5
380
92
LIST the program; you should now have:
10
CLS
20
N
;;
24
25
DIM
Y(24)
30
FOR
X
;;
1
TO
N
50
READ
60
SX
70
SY
80
NEXT
90
B = (N*XY - SX*SY)/
100
110
120
200
210
220
230
240
250
Suppose the data in lines 200 through 250 represent quarterly sales figures for six
consecutive years. RUN the program to compute the trend line on the 24 quarters
data. You will not have to enter any data during execution, since the program reads
the data from the DATA satements.
correctly, you will see the trend line equation:
Y(X)
=
SX
=
+ X:XX =
SY
+
Y(X):XY
XX
=
X
A = (SY - B*SX) /N
PRINT "FORECAST
PRINT
DATA160,
DATA
DATA
DATA
DATA
DATA
Aj"
155,
215,
225,
275,
300,
+
175,
215,
265, 220,
270, 265,
350,
330,
"j6j"
FOR
*
1.40,
155,
255,
315,
If
you have entered the program changes and data
+
X*X
XY
+ X*Y(X)
(N*XX
PERIOD X
X"
230
225
325
290
345
380
- SX*SX)
IS"
of
FORECAST FOR PERIOD X IS
148.22463768116
Of
course, the time period assumed here is a quarter, so that the equation will predict
the sales for a specified quarter in the future. For example, to predict the first quarter
of
year seven (period 25), enter:
PRINT
(The numbers are rounded
which is displayed represents the trend line projection
future.
A new type
experiment. While this experiment could have been performed without the use
subscripted variable, including it now will make the next experiment much easier.
The DIM Y(24) statement in line
having a maximum
can be thought
YO),
The number within the parentheses is called the SUbscript, and refers to the relative
position
corresponding DIM (for
called the Y
position X within the Y array.
148.225
of
variable, the
of
Y(2), Y(3),
of
the variable within the blockofstorage locations set aside by the
array.
+ 8.4086956521739 * X
+
8.4087
off
to three or four decimal places.) The result, 358.4425
subscripted
25
of
24 storage locations allocated to it. These 24 storage locations
as 24 separate variables:
....
Y(24)
"DIMension")
Thus, the variable Y(X), used in lines50and 70, refers to
*
25
of
sales to the next period in the
variable,
defines the variable Y as a subscripted variable
statement. The blockofstorage locations is
has been introduced in this
of
a
93
Line 50 will read the next data item from the OATA statements and store it in position
X of the Y array. Since the FOR statement repeats line
from 1 to 24, the data items will be stored in positions 1 through 24
50 with X assuming values
in
the Y array.
Each time through the loop, the assignment statements in line
-in
stored
the next location in the Y arraytocompute the sums SY and XY.
70 will use the value
Note that the Y array will contain all 24 data values when the program terminates.
The next experiment will make use of this feature.
Experiment
#3
Seasonal Data
Frequently, sales data exhibit seasonal characteristics. For example, the first quarter
might traditionally be slow compared to the rest of the year.
to
might be useful
modify the trend line forecast by the amount that the quarter
If
this is the case, it
is
typically above or below the trend.
The amount above or below the trend is called the
"ratio to trend" and
is
determined
by comparing the historical (actual) sales for the quarter to the amount which the trend
line would have predicted for that period.
Since there are six years of data,
and take the average (sum the ratios and divide by six). This
ratio to trend
and is the amount that sales in the first quarter differ, on the average,
we
compute the ratio for each of the first quarters
is
called the average
from the trend line.
Figure 7-3 illustrates the ratio to trend for quarter I using the example data introduced
in Experiment 2 above.
Legend
*
Y.
Actual Sales
• Y,Computed Trend Sales
+ Seasonally Adjusted Forecast
YR Ratio to Trend
$ SalesY
R Average Ratio to Trend
~
,
400
300
200
148.2
100
156.6
I
R-1.02
1
YEAR 1
5
YEAR 2
9
YEAR 3
13
YEAR 4
17
YEAR 5
Figure 7·3. Illustration of Ratio to Trend
94
21
YEAR 6
25
Period
Number
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.