Programming in BASIC A Complete Course (1982)
Programming in BASIC A Complete Course (1982)
• - -- - - - - - -- - - - ~
-
- - -
(
.
L-
I
' .
- •• . -
-
-
---
.
-
" . -I .
-
-
.
~-
-,
.
- .. -
' .
= .
'.
"
~ r." :
.~ r.., : I 1' 1 ~ • •I
T
::::::I
•
l.U?
'-,
,"!
.$
--=-.
_0
,-
~
' I '~ ' ,'
( IL.,·l ll C'" l Err
:.:. rr -l)I:'-
)~)ulvIV"L
l__ __ _
PROGRAMMING IN BASIC
- - --
PROGRAMMING I
:,,-,~~ ~~ A COMPLETE COURSE
MARGARET McRITCHIE
L_
Copyright © 1982 by Holt. Rinehart and Winston of Canada. Limited.
McRitchie. Margaret
Programming in BASIC
Includes index.
!SBN 0-03 -920148-1
1. Basic (Computer program language) . I. Title .
OA76.73,B3M37 001.64 '24 C82-094168-9
Printed in Canada
2 3 4 5 86 85 84 83 82
Contents
PREFACE vi 6.2 Variations-Initial Value and Test Value 207
6.3 Variations - Step Clause 214
ONE COMPUTERS AND COMPUTER LANGUAGES 1 6.4 Nested Loops 222
1.1 The Electronic Computer 1 6.5 A Wage Program 233
1.2 The Microcomputer 4
A Short Summary 237
1.3 Computer Languages 6 Questions and Exercises 238
1.4 BASIC 9 Programming Problems 242
A Short Summary 9
Questions for Review 10 SEVEN ONE-DIMENSIONAL ARRAYS 251
7.1 Storing Data in Arrays 251
TWO INTRODUCING BASIC 12
7.2 Printing from Arrays 264
2.1 System Commands 12
7.3 Calculating with Arrays 276
2.2 A BASIC Program 17
7.4 A Sorting Program 290
2.3 Rowcharting 20
A Short Summary 293
2.4 The PRINT Statement 24
Questions and Exercises 296
2.5 The PRINT Statement with Commas or
Programming Problems 302
Semicolons 26
2.6 Integers, Roating-Point Numbers, Hierarchy of EIGHT TWO-DIMENSIONAL ARRAYS 313
Operations 35 8.1 Storing Data in Arrays 313
2.7 Converting from Arithmetic into BASIC and Vice 8.2 Printing from Arrays 335
Versa 40 8.3 Calculating with Arrays 351
2.8 Printing Numbers 42 A Short Summary 364
A Short Summary 46 Questions and Exercises 364
Questions and Exercises 47 Programming Problems 371
Programming Problems 50
NINE MATRIX STATEMENTS AND LIBRARY FUNCTIONS 382
THREE ENTERING DATA INTO THE COMPUTER 53 9.1 Matrix Statements 382
3.1 Variables 53 9.2 The INT Function 400
3.2 The LET Statement 54 9.3 The RND Function 412
3.3 The INPUT Statement 66 9.4 Other Library Functions 420
3.4 The READ/DATA Statements 79 A Short Summary 426
3.5 The RESTORE Statement 89 Questions and Exercises 427
3.6 A Wage Program 95 Programming Problems 432
A Short Summary 97
Questions and Exercises 99 TEN ADVAN CED OUTPUT FEATURES 443
Programming Problems 103 10.1 The TAB Function 444
10.2 The PRINT USING and IMAGE Statements 462
FOUR BRANCHING AND LOOPING I 107 A Short Summary 489
4.1 The GO TO Statement 107 Questions and Exercises 490
4.2 The IF/THEN Statement 114 Prog ramming Problems 496
4.3 The ON ... GO TO Statement 123
4.4 Counters 130 ELEVEN SUBPROGRAMS 5fJT
4.5 Terminology 136 11.1 Subroutines 508
A Short Summary 137 11 .2 User-Defined Functions 525
Questions and Exercises 138 A Short Summary 544
Programming Problems 142 Questions and Exercises 545
Programming Problems 554
FIVE BRANCHING AND LOOPING II 149
5.1 Terminating a Loop- Trailer Value 149 TWELVE STRINGS 573
5.2 Terminating a Loop - Special Value 155 12.1 String Variables 573
5.3 Sets of Data Read in a Loop 161 12.2 Entering Strings into the Computer 574
5.4 Summation 170 12.3 Processing Strings 585
5.5 A Wage Program 176 12.4 Extracting Substrings 597
A Short Summary 181 12.5 Other Functions 608
Questions and Exercises 184 A Short Summary 616
Programming Problems 188 Questions and Exercises 616
Programming Problems 619
SIX FOR/NEXT LOOPS 195
6.1 General Form 195 INDEX 631
vi
Preface
The prime purpose of this book is to teach the computer Sample programs, "Your Tum " problems, and assignment
language BASIC in the context of personal and practical problems are deliberately simple and are designed to help
real-life situations. Although a few mathematical problems are readers concentrate on leaming BASIC programming rather
presented, the reader need not have a mastery of than on deciphering a problem. Explicit instructions prevent a
mathematics in order to progress through the book. The reader from using a preferred method to perform a routine
approach is simple and well suited to those who have had no with the possibility of forgetting other options. Calculations to
experience with computers. The book is written for be performed in a program are clearly defined. With few
time-sharing , batch, and microcomputer systems and may exceptions, every program - whether rt be a sample
be used as a self-teaching text or as a text in a formal program, a "Your Tum" problem, or an assignment problem
instructional environment. This makes the book suitable to a - has its RUN shown. Beginning programmers feel more
wide audience of readers, from students in schools, confident and gain better programming skills when goals (the
colleges, and universities to the non-professional computer results) are clearly and concisely laid out for them. A simple
user who has a computer at home or in the office. flowchart using the basic symbols is introduced at the
The chapters are organized in the following manner: beginning of the book and is methodically developed as
other symbols become necessary. Rowcharts are given for
1. A list of objectives at the beginning of each chapter gives
some of the "Your Tum" problems and for the more difficult
the concepts that are to be introduced.
assignment problems at the end of a chapter.
2. The chapters are divided into sections. The majority of
I wish to express my thanks to Bob Kennedy and John
sections consist Of four parts:
Spisich of Computerland of Winnipeg and to the staff at
(a) A new concept is explained. This is accomplished by the Radio Shack Computer Centre, Winnipeg, for their willing
use of a short program in which the concept is help and advice and for providing the latest hardware and
incorporated. software products. Gratitude is also extended to the
(b) A sample program is listed with statements fully University of Manitoba and to the Superintendent's office of
explained. In many sections, several programs are given. the River East School Division No.9 for the loan of their
A RUN is shown for every sample program. hardware and software, and to the students who tested
(c) A "Your Tum" unit gives the reader the opportunity to portions of the manuscript. Finally, I wish to express my
experiment with the skill just learned by solving thanks to Mr. Anrep-Matthiesen for his thorough review of
exercises and writing programs. the manuscript and for his many helpful suggestions.
(d) Solutions are provided for the "Your Tum" exercises and
programming problems.
Another section is started and the process is repeated. Margaret McRitchie
3. A summary at the end of each chapter reviews the most
difficult concepts.
4. Questions, exercises, and programming problems
complete a chapter, depending on its content. The
majority include the three types.
~.
COMPUTERS AN D COMPUTER LANGU AG ES [ 1
,
o E COMPUTERS AND
COMPUTER LANGUAGES
Through the study of this chapter , you will become familiar with:
1. The functions of the analog computer and the digital computer.
2. The MARK I, ENIAC, and BINAC computers .
3 . The stored-program principle .
4. The advantages of transistors over vacuum tubes .
5. Large Scale Integration (LSI ) .
6. The generations of computers .
7 . The history of the microcomputer.
8. Software .
9. The fundamental units of a computer system .
10. Peripherals .
11 . External media for mass storage of information.
12 . The two main components of a microprocessor.
13. Registers in a microprocessor.
14. RAM, ROM, byte.
15. Serial and parallel interfacing.
16. Data bus, address bus, and control bus .
17 . The term microcomputer-on-a-chip .
18. The terms machine language, symbolic language , high-level
language .
19. Interpreters and compilers.
20 . The reasons for the development of ALGOL , FORTRAN, PLlI ,
COBOL, BASI C.
21. The history of the BAS IC language.
ers are now in the fourth generation (LSI) or even in the fifth genera-
tion (VLSI-Very Large Scale Integration).
1. Mass storage
Since memory boards have a limited capacity, mass quantities of
information must be transferred to external storage media, such as
B. External Devices
magnetic tapes and disks. This is accomplished by means of external (Peripherals)
devices (cassette tape recorders and disk drives). The external
device (peripheral) must be interfaced with the computer and is
driven by instructions issued from the computer. These instructions
are translated by a device controller that often resides on the same
printed circuit board as the interface.
2. Input/Output terminals
Input/output devices provide the means by which man can communi-
cate with the computer. These peripherals must also be interfaced
with the computer. The usual input device is a keyboard, while typical
output devices are video monitors and printers .
ALGOL is an algorithmic language especially oriented toward algebraic ALGOL (Algorithmic Oriented
and logical processes. It is not meant to handle large amounts of data Language)1
(although large amounts can be processed), and little attention is
given to the type of data involved. ALGOL concerns itself mainly with
the presentation of concise and well-defined procedures to solve
arithmetic and logical problems. It was developed by international
computer experts to standardize an algorithmic language.
FORTRAN is a mathematical and scientific language designed to solve FORTRAN (Formula Translation)
algebraic equations. First developed by International Business
Machines (IBM), it is now extensively used by other manufacturers.
Many versions of FORTRAN exist, however with minor changes, it can
be adapted easily to different computers.
PUI is a general-purpose language well suited to both commercial and PU (Programmi ng Language~)
scientific applications. It combines the mathematical notations of
FORTRAN with the desirable parts of ALGOL and the data processing
features of COBOL. It is characterized as being less English than
COBOL, simpler than FORTRAN, and incorporates fewer rules and
restrictions than either language.
A widespread, business-oriented language, COBOL was designed to COBOL (Common Business Oriented
process large quantities of data in a repetitive routine. Its near- Language)
English form provides a means of communicating its problem-solving
process with non-programmers. Its English-like notation also makes
for ease in training, promotes accuracy in programming, and reduces
programming time. With minimum modification, a program written in
COBOL can be used on a wide variety of makes and models of
computers. It is presently one of the leading commercial program-
ming languages.
BASIC is a FORTRAN-like language designed primarily for interactive BASIC (Beginner's All-Purpose
and time-sharing environments. 2 Most microcomputers use some Symbolic Instruction Code)
version of BASIC. It is considerably easier to learn than FORTRAN, yet
with its extensions, it is capable of solving scientific, mathematical,
and engineering problems. It can be used in a great variety of
commercial applications, such as accounting, inventory control, and
word processing. BASIC can also be employed in such diverse areas
as medicine; economics; the administration of student records in
schools, colleges, and universities; and in the maintenance of per'-
sonal records in the home. Because of the simplicity of the language,
coupled with the declining cost of computers, an increasing number
of educational institutions are becoming interested in BASIC as a
means of teaching programming. In addition, its interactive feature
makes it especially useful for individualized instruction.
1.4 BASIC
The introduction of time-sharing in the late 1950s soon revealed that
the programming languages in use at the time were too difficult for
this type of system. The language used in a time-sharing environ-
ment should be simple to write to enable a user sitting at a remote
terminal to correct a programming error easily. To rectify the situation,
in the mid-1960s, John Kemeny and Thomas Kurtz of Dartmouth
College developed a simpler version of FORTRAN which they called
BASIC. Since its introduction, many computer manufacturers have
incorporated this language into their machines.
At first the BASIC language was quite limited, consisting of approxi-
mately 20 words . This inadequacy caused manufacturers to expand
their compilers, thereby extending BASIC ' S vocabulary. BASIC that has
been extended is referred to as Extended BASIC or Level II , as
opposed to Levell. Unfortunately, the manufacturers did not consult
one another when writing their extensions , so that now there are
many "dialects " of BASIC. The net result is that there is no standard
version of the language , and this makes it difficult to RUN a particular
BASIC program on various makes and models of computers
A SHORT SUMMARY
The history of the electronic computer is divided into several genera-
tions . Each generation introduced a drastic change that resulted in
greater speed , greater reliabi lity, lower costs , and a reduction in size.
The first generation of computers used vacuum tubes (1946), the
second generation used transistors (1959) , and the third generation
used integrated circuits (1965) . Many people believe that computers
are now in the fourth generation (LSI - Large Scale Integration) or
even in the fifth generation (VLSI- Very Large Scale Integration) .
Microcomputers were first sold, in 1975, as computer kits. In 1977,
the first completely assembled microcomputer was introduced to the
general public . This opened up such new businesses as computer
shops that sell hardware and consulting services that provide soft-
ware. The internal structure of a microcomputer is basically the same
as that of a conventional computer, namely, the Control Unit and the
Arithmetic-Logical Unit (each is part of the Central Processing Unit),
memory , and input/output facilities. The outstanding feature of the
microprocessor is its programmability . Because of its versatility and
its reduced size and cost , a microprocessor can be considered a
peripheral to other electronic equipment. Today , technology has
advanced to such an extent that all of the functions of a simple
computer can be mounted on asingle chip-the microcomputer-on -
a-chip .
In the early 1950s , computer programs were written in machine
language and later in symbolic language . Most programmers now
write their programs in one of severa l high-level languages designed
to ease the programmer's task by being less machine-dependent
and by more closely resembling the human language. Symbolic and
10 PROGRAMMING IN BASIC
- -- - - -- - - -- - - - -- _.._ - - -- -- - -
2.1 SYSTEM COMMANDS1
To communicate with a computer, it is necessary to be familiar with
the system's commands. Only those most commonly used will be
1 These commands are for use in an interactive or time-sharing environment. If yo u
are not using thi s type of system (teletype. cathode ray tube . or microcomputer) . you
may ignore this section .
INTRODU C IN G BASIC 13
discussed , since there are many commands. After they have been
explained , you will be given a number of short programs to key into
the computer so that you can determine which commands are
required by your computer system . Consult your reference manual
for the required variation if you find that those given cannot be used .
The notations in this section represent two different ways of entering
the commands. A box around a command (representing a key)
means that only the key must be depressed, for example, the
I RETURNI key. If a command is not in a box, it must be typed out in full.
For example, NEW must have three letters typed: an N, an E, and a
W . Commands will be introduced in almost the same order as they
are used .
1. Cursor
Although this is not a command, you should know the meaning of the
word, since a cursor is used in an interactive computer system. A
cursor is a blinking light that appears on your screen in the form of a
square, an arrow, an underscore, or some other character. It indicates
the position of the next entry. Every time an entry is made , the cursor
advances one position to the right. On some computers , special keys
allow you to move the cursor up and down, as well as backwards and
forwards .
-- ---
c:NEW or SCR or CLEAR or START or SCRATCH or N. or NE
6r DELETE or DELETE ALL
On some systems, the command sets numeric variables currently in
memory to zero and string variables to the null string. A string, which
is a series of characters , is explained in Section 24 and variables are
explained in Chapter Three . Turning the machine off also erases
programs from memory , but this method is not recommended.
It is quite possible that not all of these commands can be used on your
computer. If not , you will need to refer to your manual for the required
variations.
7. Making corrections
(a) To correct a character in a line before the! RETURN! key is pressed,
press the left arrow key !-I or the I BACKSPACE! key or the [QgJ
key or the !RUBOUT! key. Each time the key is pressed, a charac-
ter is deleted from memory. After all the incorrect characters have
been erased, type the correct ones.
(b) To correct a character in a line after the !RETURN! key has been
pressed, type the original line number, key in the correct state-
ment, then press !RETURN!. On some systems the character
cannot be corrected as in Part (a) since the statement has already
been transmitted to the computer's memory. Some computers
have built-in EDIT programs that allow you to change lines after
they have been submitted to memory.
(c) To delete an entire line type the number of the line, then press
IRETURN!. On some computer systems, you can delete one or
more lines by typing the command DELETE or DEL, the line
number (or numbers) to be deleted, then pressing !RETURNI.
DELETE 50 erases line 50.
DELETE 50,51 erases lines 50 and 51.
DELETE 45 - 50 erases lines 45 to 50 inclusive.
DELETE - 50 erases all lines up to and including line 50.
DELETE 50- erases all lines from 50 to the end of your program
(including line 50).
To erase all the lines at once, use one of the commands listed on
page 13 under "Clearing the Computer's Memory."
INTR ODUCING BAS IC 15
(d) To insert a line, type the line with its appropriate line number
under your original program and the computer will insert the
statement in proper sequence .
8. Terminating a program
Sometimes a programmer may wish to terminate the execution of a
program before it has been completely processed . There are many
different commands for this function. Try the following, but remem-
ber, you may have to press I RETURNI after the com mand key has been
depressed , depending on your computer system .
(a) Press the I STOPI key.
(b) Hold the ~ key down , depress the [9 ke y.
(c) Press the I BREAKI key.
(d) Press the ~ key .
(e) Press the IALT MODEl key .
(f) Press the [§J key .
(g) Press the I PAUSEI key.
On many systems , execution may be resumed from the point where it
was stopped by typing CONT or CONTINUE .
9. READY or OK or DONE
These are not commands . One of them , or something similar, is
displayed on the screen to inform you that the computer is ready to
receive further instructions or commands.
RUN
1
. \
A.•
3
4
c·
,-,
1. To correct a character in a line before the I RETURNI key is II. Making Corrections
depressed:
(a) Erase the old program from memory .
(b) Key in the statement.
20 PRIMT A Do not! RETURNI
(c) Change PRIMT to PRINT. (Page 14)
2. To correct a character in a line after the I RETURNI key has been
depressed :
(a) Erase the above statement from memory.
(b) Key in the following program.
1~ LET A=l
2~ LET 8:-;2
3'-' PRJMT A
4~ PRINT B
99 END
(c) After you have typed the five statements , change PRIMT in
line 30 to PRINT. (Page 14)
3 . To delete a line:
(a) Delete lines 20 and 40 from the above program . (Page 14)
(b) LIST your program. Lines 20 and 40 should no longer be
included in your program.
4. To insert a line:
(a) In the same program , insert the line 15 PRINT A+2 . (Page
15)
INTRODUCING BASIC 17
(b) LIST your program. Notice how the inserted line has been
placed in proper sequence.
HI LET A= 1
15 PRINT A+2
30 F'R I NT A
99 END
3. LIST and RUN the program . Your RUN should produce the follow-
ing.
RUN
1
2
3
4
".w
6
7
999 END
RUN
67 67
81:',J 1""")
..J.:..
79 231
93 324
mayor may not be given. Check your computer manual for the
maximum number of characters allowed on your system .
3. Each statement must begin with a line number that is unique. (No
other statement may have the same line number.) These
numbers must be positive integers 2 and may range from 1 to
99999 inclusive, depending on the computer system being
used. Again, check your manual.
4. Unless there is a branch , statements are always executed
according to line number (from lowest to highest). On many
computer systems, statements are processed in this manner
regardless of the sequence of their entry ; on other systems , they
must be entered in the same order as their lines are numbered.
5. It is customary to number statements in multiples of a specific
number (say, 10) so that additional statements may be inserted at
a later time.
6. On many computer systems, programs must terminate with an
END statement. If required, most of these systems insist that it be
the highest-numbered statement in the program. If the END
statement is not required, execution terminates with the highest
numbered statement.
7. REM (REMARK) statements may be inserted anywhere in the
program. They are used to identify the program , to identify the
variables, and to describe a routine. REM statements are not
executable instructions but are merely comment statements that
documenP a program.
S. To distinguish between the number 0 and the letter 0, most
programmers place a slash through one of them. For example:
Number 0 ... ... 0, Letter 0 ...... O.
Turn to the sample program on page 18. It has been numbered and
documented in an extreme fashion, but this is the way it is often done
when programs are very long.
1. REM (REMARK) statements are placed at the beginning of the
program (numbered from 01 to 07) to identify the program and
the variables used.
2. Line numbers are segregated into groups of hundreds. Each
multiple of 100 is a routine different from the others and each is
headed by a REM statement. For example :
(a) The READ routine has statements numbered in the 200
range.
(b) The summation routine has statements numbered in the 300
range.
(c) The PRINT routine has statements numbered in the 600
range.
3 . For ease in reading, blank lines are inserted between the rou-
tines.
4. Throughout the book , a slash is drawn through the number zero
to distinguish it from the letter O.
999 END
220 E:EAD N
41.121 LET K:::Ktl
620 PRINT "THE AVERAGE IS:";A
There are a few terms you should know, before going on to some
simple BASIC programs. They are data, coding, and debugging.
Information entered into the computer to be processed is called data.
In the sample program, the data items are: 4,67,85,79,93. The
process of writing BASIC statements is referred to as coding, while
that of identifying and correcting errors is called debugging.
2.3 FLOWCHARTING
When a program is long and complicated, a chart of its steps is often
drawn before the program is written in order to give a pictorial
representation of the procedure it follows. This representation is
called a flowchart. Its purpose is to clearly define an overall plan so
that a programmer can more readily visualize the logical flow of the
program. Standard symbols of various shapes and sizes are used to
denote the different operations. These symbols are connected by
lines and arrows to show the direction of the flow.
I,
11 <
heads show the direction of programming
logic.
~
'I
22 PROGRAMMIN G IN BASIC
The program
The flowchart
Start
HI READ N1,N2
21?1 DATA 7,5
Calculate
Sum 30 LET S"':Nl+N2
S= N1 +N2
\lI
Print 4~ PRINT S
S
\lI
( End
) 99 END
INTRODUCING BASIC 23
READ Nl,N2
lli1
2~ DATA 12,5
3~ LET D::N 1--N2
40 PRINT [I
99 END
( start)
\!I
Read 1111 READ Nl,N2
N1,N2 2~ DATA 12,5
Calculate
Difference 30 LET D=NI-N2
D= N1-N2
Print 40 PRINT D
D
) <"19 END
24 PROGRAMMING IN BASIC
1. 10 PRINT 2. 10 F'R I NT
20 PRINT 3 20 PRINT 3
99 END 30 PRINT
40 F'R I NT 4
RUN4 99 ENP
3
< Blank line
RUN
4
< Blank line
10 PRINT ~--
( Placed just before the statement that prints the results.
20 PRINT 3
9<; END
RUN
(
~------ Blank line before the results.
3
Besides printing numbers and blank lines, a PRINT statement can also Printing messages
print messages which are referred to as strings. A message must
follow the word PRINT and must be enclosed in either double or
single quotation marks, depending on the computer system used.
The message may contain letters of the alphabet, digits, special
4. If you are not using an interactive system, ignore the word RUN shown before
each output.
INTRODUCING BASIC 2S
characters, and spaces, but not the quote that delimits the string. The
computer prints exactly what has been placed within the quotation
marks .
.-
ll-l PFnNT
2~ F'FdNT " HI"
99 END
RUN
HI ./
.......
H1f'RINT
2~PRIN T "6+7"
r-30 PRINT 6+7
99 END
RU N
./
6 + 7 .......
413
I
Statement 20 causes the computer to print 6+7 while statement 30
tells the computer to evaluate 6+ 7 then print the answer. You have
probably noticed by now that every time the computer encounters a
PRINT statement, output is printed on a new line. In the above program
there are three PRINT statements; in the RUN there are three lines of
output-a blank line, 6+7, and 13.
RUN
JOHN SMITH
12+:':i
17
2. Rewrite the above program so that a blank line is left after your
name, as well as before it. (Page 24)
RUN
,JOHN SMITH
12+~:)
17
1. tv.1
20 .
F'F\INT
PRINT .JOHN SMITH"
2. H'J PRINT
20 PRINT • .JOHN ~;MITH'
30 PRINT ·12+~)· 3111 PFn NT
40 PRINT 12+5 41!l PFdNT "12+5"
99 END 50 PRINT 12+5
99 END
ll'1 PRINT
2l'1 PRINT 1,22,333,4444,55555,666666
99 END
RUN
1
55555
I ~: " " I 333 I 4444
~~~
Zones of fixed widths
Notice that the zone widths are all the same. Spacing between items,
then, depends on the number of characters in each zone . Also, on
most systems the first position in a zone is reserved for the sign. If the
number is positive, the position is left blank ; if the number is negative,
5. If your compute r does not recognize a comma but treats it as a semicolon, your
output will always be closely spaced . The computer used for programs in this book
distinguishes a comma from a semicolon .
28 PROGRAMMING IN BASIC
PRINT
1.~
2~ PRINT 1,22,333,4444
30 PRINT -1,-22,-333,-4444
99 END
RUN
1 333 4444
I
-1 -'J'J
I --
-333
I I
-4444
1.0 PRINT
20 PRINT "HI,',"HOW","ARE","YOU?"
99 END
RUN
HI, HOW ARE YOU?
I I I I
10 PRINT Space
2~ PRINT "2+314',2+3
30 PRINT "2-6 =",2-6
99 END
RUN
"Space
2+3~ 5
2-6 = -4
Notice the space before the equals sign in line 20 and in line 30. Since
this space is part of the string, it is included in the output.
Depending on your computer system, semicolons in a PRINT list II. Semicolons in the
cause the computer to leave one. two, or possibly three spaces
between printed items. The number of zones in one line depends on PRINT Statement
the number of characters in a printed item and on the maximum ("-..
number of characters allowed in each zone (16 is the usual maxi mum -
INTRODUC ING BASI C 29
10 PRINT
20 PRINT 1;22;333;4444;55555
30 PRINT -1;-22; - 333; - 4444;-55555
99 END
RUN
333 4444
-333
I
-4444
I
RUN
f1l1221133311444411555551
~ 1-2211-33311-444411-555551
Other computers leave one space before and no space after each
signed or unsigned number. The output looks like this.
RUN
r1122133314444155555
~1-221-3331-44441-55555
6. In this book , regard less of the type of punctuation used in a PRINT statement, a
space is left before a positive number and a space is left after any number, whether it
is positive or neg ati ve . If the number is negative. the space before the number is filled
in with a minus sign .
30 PROGRAMMING IN BASI C
Hl PRINT
20 PRINT "HI,";"HOW";"ARE";"YOU?"
99 END
RUN
HI,HOWAREYOU?
I I I I
t
Space
t
Space
t
Space
--~~----------------------------------- --
INTRODUCING BASIC 31
RUN
10 PRINT
20 PRINT "NUMBER:";4
99 END
RUN
NUMBER: 4
Notice that the output has one space before the number 4. If the
number had been negative, the computer would either insert a minus
sign in this space or (as mentioned on page 29) leave a space before
the signed number.
Depending upon the computer being used, the output may be as
follows .
NUMBER: -4 or NUMBER: -4
t
Minus sign printed
t
Minus sign printed
in the first position in the second position
of a zone. of a zone .
A comma or a semicolon at the end of a PRINT list causes the items of III. Comma or Semicolon
the next PRINT statement to be printed on the same line as those of the
former PRINT statement. at the End of a PRINT
Statement
1. Using a Comma 2. Using a Semicolon
1111 PRINT
20 PRINT 4" NUMBER ";
3B PRINT j
99 END No space
RUN
NUMBER 4
i
Space
lB PRINT UI PRINT
2B PR I NT "H I" , Counteracts 2B PRINT "HI"; Counteracts the
30 PR I NT ( ~ the comma 3B F'RINT < ~semicolon
4B PRINT "THERE" 4B PRINT "THERE"
99 END 99 END
RUN RUN
HI HI
THERE THEr.:E
refer to them if you need help . The page numbers are given for easy
reference.
For each of the following problems, leave one blank line after the
word RUN . (It is assumed that your computer differentiates between
a comma and a semicolon .)
1. Write a BASIC program that prints the numbers 1,2,3,4 on one
line, then -1,- 2,- 3,- 4 on the next line . The items in both lines
of output are to be widely spaced. (Page 28)
2. Rewrite the above program so that the items in both lines are
closely spaced . (Page 29)
3. Write one BASIC program that prints COMMAS OR SEM-
ICOLONS in the three ways listed below. Each PRINT statement
must have three strings . (Pages 28 and 30)
(a) Widely spaced across the line
(b) With no spaces between the words
(c) With one space between each word
4. Write one BASIC program that calculates 6+ 3 and 6- 9 and prints
the results as follows . (Pages 28 and 31)
(a) First line - The string 6+3 = followed by the answer. Output
is widely spaced.
(b) Second line - The string 6-9 = fo llowed by the answer.
Output is widely spaced .
(c) Third line- The string 6+3 = followed by the answer . Out-
put is closely spaced .
(d) Fourth line- The string 6-9 = followed by the answer .
Output is closely spaced.
5 . Write a BASIC program that uses two PRINT statements (in addition
to the one that leaves a blank line) to print the words YOUR
TURN widely spaced on one line . (Page 31)
6 . Rewrite the above program so that your output is closely spaced .
Use the same number of PR INT statements as in Problem 5.
Leave one space between the words . (Page 31)
7. Modify the following program so that your output is printed on two
lines. Do not change lines 20 and 30 in any way. (Page 32)
HI PRINT
20 PRINT "LAST",
30 PRINT "QUESTION"
99 ENtl
RUN
LAST
OUESTION
34 PROGRAMMING IN BASIC
1. 10 PRINT
221 PRINT 1,2,3,4
321 PRINT -1, - 2,-3,-4
99 END
2. 121 PRINT
221 PRINT U2;3;4
30 PRINT --1;-2;-3;-4
99 END
3. 121 PRINT
20 PRINT 'COMMAS','OR",'SEMICOLONS'
30 PRINT 'COMMAS";'OR';'SEMICOLONS'
4111 PRINT "COMMAS " ; "OR 'j"SEMICOLONS'
or
40 PRINT "COMMAS";" OR' ; , SEMICOLONS"
99 END
4. 1111 PRINT
2111 F'R I NT "6+3 =",6+3
3111 PRINT "6-9 =",6-9
4111 PRINT "6+3 =";6+3
521 PRINT "6-9 =" ; 6-9
99 END
5. 1111 PRINT
2111 PRINT "YOUR",
3111 PRINT "TURN"
99 END
6. 10
20
PRINT
PRINT 'YOUR .., or 10
2111
PRINT
PRINT • YOUR' ;
30 PRINT "TURN" 30 PRINT " TURN"
99 END 99 END
7. 10 PRINT
2111 PRINT "LAST",
25 PRINT
30 PRINT 'QUESTION"
99 END
INTRODUCING BASIC 35
H'l PRINT
20 PRINT ~+1,0tl+2,~+1+2+3,0+1+2+3+4
99 END
RUN
1 3
14- 2
V
V
12
(b) 6+31'2/(5-2)-4 (d) 8- (2*(3+4)- 6)+ 1
V V
6+31'2/3- 4 8- (2*7- 6)+ 1
V V
6+9/3- 4 8-(14-6)+1
V V
6+3-4 8-8+1
V V
9-4 0+ 1
V V
5 1
INTRODUCING BASIC 37
15-(8-2)
V V
7+ 7
15-6
V V
14
V
9
2 . Now, key in and RUN the programs shown below . Do you get the
same answers on the computer as you did when the calculations
were done by hand?
RUN RUN
14 1
RUN RUN
5 9
RUN RUN
12 14
38 PROGRAMMING IN BASIC
18 -1
V
V
17
RUN RUN
14 14
RUN RUN
28 8
RUN RUN
17 10
40 PROGRAMMING IN BASIC
Arithmetic BASIC
BASIC Arithmetic
(a) 26 + 4(9- 3)
(b) _6_ + 42 - 8
4-2 3
6+2+8-(5+4)
()
c 4-2 7
2
(d) 3 +6 + 10-4
9-5 3
(e) (3+2)2 - 43 + 6
5-3
(f) 3 2 - 4(12-(7+3)+9)+ 52
7-1
(a) 2j3/4-10/5
(b) (6- 2H3+8/4+(5+ 7)/2
(c) (5+4)j3+8/(4+3)- (6-4) /2
(d) (7+(3+6)j2) /(4+3)-9/(7-4)
(e) ((6-2)j3+8)/(4+3)+(8-2) /(5+1)
(f) (2*(3+(7- 5)j2- 9)) /(4+5)- 7
(a) 6/2+4*(9-3)
(b) 6/(4 - 2) +(4j2 - 8)/3
(c) (6+2)/(4-2)+(8-(5+4))/7
(d) (3j2+6)/(9 - 5)+(10-4)/3
(e) ((3 + 2)j2 - 4j3)/(5 - 3) +6
(f) (3j2-4*(12-(7+3)+9))/(7-1)+5j2
10 PRINT
20 PRINT 132.00,01.20
99 END
Mantissa Exponent
8.12345678 E +09
4. There are several digits to the right of the decimal point, with the
last permissible digit usually rounded off. Suppose a computer
prints eight digits to the right of the decimal point, then
1 123 456 789 becomes 1 .12345679E+ 09,
.001987654326 becomes 1.98765433E- 03.
On some computer systems, all trailing zeros to the right of the
decimal point are dropped when the number is expressed in scientific
notation.
1, 234 500 000 becomes 1.2345E+09
12 000 000 000 becomes 1.2E+10
A number of computer systems print a sign before the exponent
(E+09 or E-09); others omit the sign when the power is positive
(E09) , Also, some computers print a two-digit power (E+09) ; others
print just one digit when the exponent is less than ten (E+9).
See how your computer prints a number in E format. RUN the
following program.
10 PRINT
20 PRINT 123456786666666666
30 PRINT .0000123456786666666666
40 PRINT 123000000000000000
99 END
t
9 moves Last permissible digit is rounded
13 moves
1~.
13 moves
(c) .009876543218
The decimal point is moved from the first position in the
number to the position immediately after the 9, a total of 3
moves.
.00987654322
-----
3 moves
10 moves
. 00000000081234
'--~
10 moves
A Short Summary
A number of system commands were introduced in this chapter.
These are required in order to operate a computer system and
INTRODUCING BASIC 47
9 . If you are not using an interactive system, you may ignore Prob lems 1 and 2.
48 PROGRAMMING IN BASI C
10 READ N1,N2
20 DATA 3,9
30 LET P=Nl*N2
40 PRINT
5~ PRINT P
99 END
(a) 10 PRINT
20 PRINT • I·; • SPEAK";" BASIC"
30 PRINT " I ";"SPEAK ";"BASIC"
40 PRINT "I";"SPEAK";"BASIC'
50 PRINT "I","SPEAK","BASIC'
99 END
INTRODUC ING BASI C 49
(b) HI PRINT
20 PRINT "8+4 =",8+4
321 PRINT "8-12 =" ,8-12
421 PRINT "8+4 =";8+4
50 PRINT "8-12 ,=" ; 8 -·12
99 END
(d) 10 PRINT
20 PRINT "MY",
3~ PRINT "PROGRAM"
99 END
(e) 10 PRINT
20 PRINT "MY";
321 PRINT "PROGRAM"
99 END
(g) 10 PRINT
221 PRINT " MY " ;
321 PRINT
421 PRINT "PROGRAM"
99 END
50 PROGRAMMING IN BASIC
(a) ~ - 3(6+4)
9 3+4
(b) 4-2 + 5+2
L (8-3)2
(c) 6+3 + 4
(d) 83 - (3(2+5)2 - 4)
4+ 6- 3(5- 2)2 6
(e) 7 + 5+ 1
(f) 8-(3(6-2)+4)
9-2
Programming Problems
Write BASIC programs to evaluate the following arithmetic problems.
42 - 2
1. 3+4
RUN
2
2. ~ + 9-9(~6 3)
RUN
6
INTRODUCING BASIC 51
5. 5(12-(3(9-7)2-6)+4)
RUN
50
6. 3~02 + 4(6- 3)2
RUN
4()
9. Write the program once more to make your output more legible
by leaving a space between each word. Use two different PRINT
statements to obtain two identical lines of output.
10. Write one BASIC program that prints the numbers 1,22,333,4444
widely spaced on the first line of output, then closely spaced on
the next line. Do the same for the negative numbers
-1,- 22,- 333,- 4444 on the following two lines of output .
11 . Write a BASIC program that evaluates 6+3. Use two PRINT state-
ments to produce two lines of output, each one starting with the
string 6+3 = , followed by the answer. The first line should have
the string and the answer widely spaced apart, while the second
line should print them closer together .
13. Write two BASIC programs to evaluate 13- 6. Each program must
use two PRINT statements (in addition to the one that leaves a
blank line) to print the string 13-6 = and the answer on one line.
One program prints the output widely spaced; the other prints
the output closely spaced .
14. Modify the following program so that your output is printed on two
lines . Do not change lines 20 and 30 in any way.
52 PROGRAMMING IN BASIC
10 PRINT
20 PRINT "LAST",
30 PRINT "PROGRAM"
99 END
RUN
LAST
PROGRAH
ENTERING DATA INTO THE COMPUTER 53
3,1 VARIABLES
A variable is a symbol that is used in programming to represent a
number or a string . It refers to that place in the computer 's memory
where the number or string is stored . In other words, a variable can be
thought of as an address that designates a location in storage. This
location contains a value which may vary as the program is being
executed. In this chapter, you will be working with numeric variables.
String variables are explained later on in the book.
54 PROGRAMMING IN BASIC
A
Al
All (The second character may be invalid,
since it is not a digit.)
AlIC (The third character may be ignored
by the computer, leaving this variable
the same as the previous one.)
stat:ment
number
i
Key word
i
Variable
i
Equals sign
i
Number
2. 30 LET A A+1
t
Expression
UI LET A= 1 -Initializes A to 1.
20 LET 5=0 -Initializes S to 0.
A 5
8 8
It doesn 't matter when these values are stored in the computer's
memory, just as long as they are stored in their respective addresses .
It was mentioned that the LET statement in the second example
(30 LET A=A+1) destroys the original contents of A. This is not
always desirable, since you may want to retain the original data item.
To do this , you can assign the value of the term A+1 to a different
variable, say B, then ask the computer to print the values of both A
andB .
RUN
24 25
56 PROGRAMMING IN BAS IC
Notice that the values of A and B are printed, not the letters A and B.
Also note that the variable A is assigned a val ue of 24 in line 10 prior to
its use in the expression in line 20. Remember, a variable must be
assigned a value before it is placed in a statement on the right-hand
side of the equals sign.
Data can also be transferred (copied) from one storage location to
another without altering the contents of the first location.
RUN
A =4
B =4
Suppose you want to print the values of A and B along with their
respective variables on one line. Your PRINT statement should look
like one of the following:
(a) 50 PRINT "A =" ;A,"8 =";B - The comma causes the item B = 4 to be printed
,in the next available fixed zone .
i A =4 B = 4
(b) 5£11 PRINT "A =" ;A;"B =";B - The semicolon leaves one, two, or possibly
three spaces after the item A = 4.
i
ENTERING DATA INTO THE COMPUTER 57
10 LET A=B=C=D=1
RUN
1.
,,-
~)
First A =1 A
Then A = A+ 1 A
= 1+ 1
=2
Finally A = A+ 1 A
=2+1
=3
RUN
1
2
3
First A= 1 A
Then B= A+ 1
8 B
=1+1 [:;\2
=2 V
Finally C = +2
A C
= 1+ 2 {:;'\3
=3 V
RUN RUN
B = 12 B = 6
ENTERING DATA INTO THE COMPUTER 61
RUN RUN
C = 9 C = 10
RUN
2
4
6
8
(a) Use one variable to store the initial value, then use other
variables to store the remaining values.
(b) Instead of incrementing A each time, increment the variable
that has just been assigned the latest number.
(c) Have the computer print the numbers horizontally instead of
vertically .
RUN
2 4 6 B
ITI 40 PRINT A
50 PRINT B
I I Print
A,B
RUN
Problem 7
C CURRENT
BALANCE
D DEPOSIT
W WITHDRAWAL
Add
Deposit
C=C+D
Subtract
Withdrawal
C=C-W
64 PROGR AMMING IN BAS IC
HI LET A=l
221 LET B=2
(b) The item on the left-hand side of the equals sign must be a
numeric variable , not an expression.
HI LET A=5
HI LET Al=l
2.
9 8 8
3 6 36
9
4.
5.
6.
HI LET A=2
2i!!
LET B=A+2
30 LET C=B+2
40 LET D=C+2
58 PRINT
68 PRINT A,B,C,D
99 ENII
66 PROGRAMMING IN BASIC
7.
Ie LET A=2
20 PRINT
30 PRINT A
99 END
RUN
...
')
In this program you entered and then printed just one value.
Suppose you want to input and print three values, the numbers 2, 31,
and 49. If you do not add any statements to the above program, you
would have to RUN the program three times and modify the LET
statement after each RUN. For the first RUN, line 10 would be
10 LET A=2; for the next RUN, line 10 would be changed to
10 LET A=31; and for the last RUN, line 10 would be changed to
10 LET A=49. Now, what if there were more than three values to be
10 PFU NT
2111 INPUT A
30 PRINT A
99 END
RUN
'i'
RUN
RUN
? 2
RUN
? 31
31
H1 LET A=2
2~ PRI NT - Placed just before the PRINT that prints the resu'lts.
30 PRINT A
99 END
RUN
<E-<-----~ Blank line
")
<-
The previous program used the INPUT statement to enter just one
value into the computer for each RUN . There may be a time when you
may want to enter several data items but RUN the program only once .
Let's write a program that INPUTS two numbers (12 and 4) , then
subtracts one number from the other. There are two ways (using the
INPUT statement) by which these two numbers may be entered into
the computer .
RUN
'? 12 - Enter 12, then press RETURN.
'i' 4 - Enter 4, then press RETURN.
r. :: 12 B = 4 C = 8
Lines 20 and 30 allow the user to ass ign two values-one to each
of the IN PUT variables A and B . However, the two question marks in
the RUN are not too informative since they do not tell you what type of
a response to make. To identify the values to be entered , you should
add two more statements to the above program so that the computer
will prompt you as to what it wants when it displays a question mark .
RUN
VALUE FOR A1 12 - Enter 12, then press RETURN.
VALUE FOR B? 4 - Enter 4, then press RETURN .
A = 12 B = 4 C = 8
Now when you RUN the program , the computer prints two messages
(VALUE FOR A? and VALUE FOR B?) , which tel l you what two data
values should be entered . Notice the semicolon at the end of line 20
and another at the end of line 40. The semicolon stops automatic line
spacing with the result that the question mark and the keyed-in item
are displayed on the same line as the prompt. The INPUT statement
makes the computer wait for the data to be entered . After the data is
keyed in and the RE TURN key is pressed , program executi on
resumes .
On some computer systems, the prompt is part of the IN PUT
statement. The two statements
40 PRINT "A =" ; A, "B ="; B, "C ='; C - Prints the values of A, B , and C.
99 ENII - Terminates program execution .
RUN
- En ter 12 and 4 then press RETURN .2
B = 4 C = 8
As in part 1, the question mark in the RUN tells you very little. This
program, too , should print an identifying message (a prompt) to
indicate to you what the computer expects. Here is the program
again , but with a prompt added.
RUN
VALUES FOR A,B? 12,4 - Enter 12 and 4, then press RETURN .
A = 12 B = 4 C = 8
Take another look at that last RU N. Notice that the values of A and B
are displayed twice-once after the prompt and again in the line
RUN
No commas here
2B INPUT A,B,C
~
'V
Commas here
No commas here
/~
VALUES FOR A,B.C? 2.4.6
V
Commas here
RUN
IJALUES
10 PRINT
20 PRINT "VALUES FOR A,B,C";
30 INPUT A,B,C
40 PRINT A,B,C
99 ENII
RUN
The value for C should now be typed right after the last question
mark .
RUN
5. When too much data is supplied, the computer either ignores the
extra data or terminates execution. Here is a RUN that one
computer system produces when a user supplies too much data
in response to an INPUT statement.
1121 PRINT
20 PRINT "VALUES FOR A,B,C";
3121 INPUT A,B,C
40 PRINT A,B,C
99 END
RUN
RUN
COATS--OTY,UNIT PRICE? 2,132
JACKETS--OTY,UNIT PRICE? 3,58
COATS: 264
.JACKETS: 174
TOTAL COST: 438
RUN
OTY,UNIT PRICE--COAT,JACKET? 2,132,3,58
COATS: 264
JACKETS: 174
TOTAL COST: 438
RUN
TOTAL AMOUNT,DAYS? 12.50,5
AVERAGE AMOUNT EACH DAY: 2.5
(c) INPUT T
(d) INPlJl lid
(e) INPUT T,D
RUN
HOURS? 8
PIECES PER HOUR? 6
TOTAL PIECES: 48
III. Modify the flowchart for Problem II and rewrite the program so
that you use one INPUT statement instead of two to enter your
data .
RUN
Problem II
H HOURS
P PIECES PER
HOUR
T TOTAL PIECES
( start)
\V
Input
H
\V
Print
Prompt
\V
Input
P
\V
Calculate
Total Pieces
T=H*P
\V
Print
T
\V
( End
)
78 PROGRAMMING IN BASIC
II.
III.
01 REM H--HOURS
02 REM P--PIECES PER HOUR
213 REM T--TOTAL PIECES
HI PRINT
2fl PRINT "HOURS,PIECES PER HOUR" ;
30 INPUT H,P
421 LET T=H*P
521 PRINT "TOTAL PIECES:";T
99 END
PROBLEM III
H HOURS T - TOTAL PIECES
P - PIECES PER
HOUR
( Start)
~
ENTERIN G DATA INT O THE COMPUTER 79
Calculate
Total Pieces
T=H*P
End
10 READ A,B,C
20 [lATA 24,25,26
10 REALI A,B,C
2B DATA 24,25,26
30 PRINT
40 PRINT A,B,C
99 END
No commas here
/'
10 READ A,B,C
'\
V
Commas here
No commas here
/' ~
20 nATA 24,25,26
V
Commas here
Suppose your computer allows two lines per statement and that a
program requires three lines of data . Two DATA statements are
used in the following program segment.
4. Some computer systems are not particular about where the DATA
statement is placed ; others insist that its line number be less than
that of the END statement. Try the following program to find out
what your computer does when the DATA statement is placed
after the END statement.
10 READ A,B,C
221 PRINT
30 PRINT A,B,C
4i! EN[I
50 DATA 24,25,26
3~
1\'
DATA 2 Ah25,26
- Same order .
- Same type . (In this case, all are numeric values, not strings .)
82 PROGRAMMING IN BASIC
HI READ A,B,C
2£'l [lATA 24,25,26,27 -Extra value.
30 PRINT
4~ PRINT A,B,C
99 END
RUN
24 25 26 -Number 27
is not printed .
10 READ A,B,C
28 DATA 24,25 -Insufficient data.
30 PRINT
40 PRINT A,B,C
99 END
RUN
10 READ A,B,C
20 DATA 24,25
3£'l DATA 26
40 PRINT
58 PRINT A,B,C
99 END
10 READ A,B
20 REAII C
ENTERING DATA INTO THE COMPUTER 83
DATA 24,25,26
~5fj
40 PRINT
50 PRINT A,(I,C
99 END
20 DATA X,D/2,1,000
'Invalid
V
RUN
COATS 2 132
COST PRICE: 264
JACKETS 3 58
COST PRICE: 174
2. How much cash does the grocer have if $431 was received
and $16.50 was paid out?
(a) Use the READIDATA statements to enter the amount of
change, the amount of cash received, and the amount of
cash paid out.
(b) Current Balance = Change
(c) Current Balance = Current Balance + Receipts
(d) Current Balance = Current Balance - Payments
(e) Fill in the missing lines.
ENTERIN G DATA IN TO THE COMPUT ER 85
01 REM C--CHANGE
02 REM R--RECEIPTS
03 REM P--PAYMENTS
04 REM B--CURRENT BALANCE
10 READ C,R,P
20
30 PRINT
40
50
6v.1
70 LET B=C
80
90 PRINT
100
110
120 PRINT "CHANGE,RECEIPTS,PAYMENTS:";B
999 END
RUN
CHANGE: 80
RECEIPTS: 431
PAYMENTS: 16.5
CHANGE,RECEIPTS: 511
CHANGE,RECEIPTS,PAYMENTS: 494.5
Here are two problems from the "Your Turn" unit of Section 3.3.
Write programs using the READ /DATA statements rather than the INPUT
statement to enter the data .
II. Suppose that you have set aside $12.50 for lunches for the next
five days . Find the average amount you can spend each day.
(a) Use the READIDATA statements to enter the total amount you
have set aside and the number of days that you will be
buying lunch .
(b) Average Amount Each Day = NTot~ Amf~nt
um er 0 ays
(c) Notice that the DATA statement is not included in the
flowchart .
RUN
RUN
HOURS: 8
PIECES PER HOUR; 6
TOTAL PIECES; 48
ENTERING DATA INTO THE COMPUTER 87
Problem II
T - TOTAL AMOUNT
D - DAYS
A - AVERAGE
AMOUNT
Read
T,D
Calculate
Average Amount
A=T/D
Print
Blank line
T
D
A
End
II .
HI READ T,D
20 DATA 12.50,5
30 LET A=T/D
40 PRINT
50 PRINT "TOTAL AMOUNT:";T
60 PRINT "NUMBER OF DAYS:";D
70 PRINT "AVERAGE AMOUNT EACH DAY: ";A
99 END
III.
01 REM H--HOURS
02 REM P--PIECES PER HOUR
03 REM T--TOTAL PIECES
HI READ H,P
20 DATA 8,6
3i'1 LET T=H*P
40 PRINT
50 PRINT "HOURS:";H
60 PRINT "PIECES PER HOUR:";P
70 PRINT "TOTAL PIECES:";T
99 END
Problem III
H HOURS
P PIECES PER
HOUR
T TOTAL PIECES
( Start
)
'V
Read
H,P
'V
[§
ENTERING DATA INTO THE COMPUTER 89
Calculate
Total Pieces
T= H*P
Print
Blank line
H
P
T
End
U, READ A,B
2" DATA 1,2,3,4,5
3ft PRINT
4" PRINT "A =" ;A, "Ei =";B
50 RESTORE
6" READ L, M d~
7~ PRINT "L =" ;L, "M =" ;H, "N = I ; N
99 END
RUN
A = 1 B = 2
L = 1 H = 2 N = 3
RUN
A = 1 EI = 2
L = 3 H = 4 N = 5
RUN
A = 10 B ::= 20 C == 30
A = 20 B ::;:
30 C ::= 40
X ::= 10 Y == 20 Z = 30
X = e Y ::= 10 Z ::= 20
99 END 99 END
50 RESTORE
60 READ P,Q,R
70 PRINT Ip =";P,"Q =" ;Q, oR =" ; R
99 END
(b) 10 READ A,8,C
20 DATA 3,6,9,12.15
30 PRINT
40 PRINT "A =" jA, "8 =" ;B, "C = I ; C
50 READ P,Q
60 PRINT "p =";P,"Q =" ; Q
99 EN.D
(c) 10 REAlI A,B
20 llATA 5.10,15,20
30 PRINT
40 PRINT "A =1;A,"8 =" ; B
50 RESTORE
60 READ P,(],R
70 PRINT "P =";P,"(] =";Q,"R =. ; R
80 READ A
90 PRINT "A = A I ;
99 END
RUN
FIRST STORE
CHAIR: B£'J LAMP: 60
REDUCED: 70 REDUCED: S0
SECOND STORE
CHAIR: 80 LAMP: 60
REDUCED: 60 REDUCED: 40
Problem 3
C1 - CHAIR IN FIRST STORE C2 - CHAIR IN SECOND STORE
L1 - LAMP IN FIRST STORE L2 - LAMP IN SECOND STORE
( Start
\!I
)
Read Print
Original Blank line
Prices Message
C1,L 1 Original Prices
C2,L2
Print
Blank line
Calculate
Message Restore Reduced Prices
Original Prices
C2=C2-20
C1,L 1
L2= L2-20
Read
Calculate Original
Reduced Prices Prices
C1=C1-10 C2 ,L2
L1=L1-10
94 PROGRAMMING IN BASIC
HI r~ EAD A,B,C
20 DATA 1,2,3
60 RESTORE
lD READ D,E,F
99 END
10 F,EAD A,B,C
20 DATA 4,8r12
60 RESTORE
7111 READ D,E,F
99 END
2.
A ::;: 3 B = 6 C = 9
p = 12 Q = 15
3.
1121READ Cl,Ll
20 DATA 80,6B
~50 PRINT
4~ PRINT "FIRST STORE"
50 PRINT "CHAIR:";Cl,"LAMP:";Ll
60 LET Cl=Cl-10
"70 LET L1=Ll-HJ
80 PRINT "REDUCED:o;Cl,"REDUCED:";L1
90 RESTORE
100 READ C2,L2
110 PRINT
120 PRINT "SECOND STORE"
130 PRINT "CHAIR:";C2,"LAHP:";L2
140 LET C2=C2-20
150 LET L2=L2-20
160 PRINT "REDUCED:";C2,"REDUCED:";L2
999 END
(a) Use the READ/ DATA statements to enter the number of hours
worked, the rate per hour, and the deductions.
(b) Remarks are placed in strategic spots to help you under-
stand the program.
(c) Blank lines have been inserted only for clarity.
(d) Calculations :
Gross Pay = Hours x Rate
Total Deductions = Income Tax Deduction + Union Dues +
Pension Deduction
Net Pay = Gross Pay - Total Deductions
96 PROGRAMMING IN BASIC
kH REM H--HOURS
~2 REM R--RATE
03 REM I--INCOME TAX DED. ( Start )
04 REM U--UNION DUES
05 REM P--PENSION FUND DED. W
06 REM G--GROSS PAY
07 REM D--DEDUCTIONS Read
08 REM N--NET PAY H,R,I,U,P
RUN
HOURS 37 RATE 11.54
GROSS PAY 426.98
INCOME TAX 75
UNION DUES 2
PENSION 2.5
TOTAL DEDUCTIONS 79.5
NET PAY 347.48
*******************************
105 READ H,R,I,U,P
110 DATA 37,11.54,75,2,2.50
ENTERING DATA INTO THE COMPUTER 97
*******************************
2~5 LET G=H*R
*******************************
305 LET [I=ItUtP
*******************************
405 LET N=G-[I
*******************************
515 PRINT 'GROSS PAY';G
*******************************
540 PRINT 'NET PAY';N
A SHORT SUMMARY
There are three ways by which data may be entered into a computer.
In a LET statement, the value on the right-hand side of the equals sign
is assigned to the variable on the left-hand side of the equals sign.
The LET statement may also be used to assign the result of an
expression to a variable. The INPUT statement allows data to be keyed
into the computer during execution of a program. When the
READIDATA statements are used, the values listed in the DATA state-
ment are assigned, in sequential order , to the variables listed in the
READ statement.
98 PROGRAMMING IN BASIC
HI LET A=l
20 LET £1=2
30 LET C::: 3
·40 PRINT
50 PRINT A;£I;C
60 PRINT AT2;BT2;CT2
99 ENIt
RUN
123
149
10 PRINT
20 PRINT ·VALUES FOR A,B,C";
30 INPUT A,B,C
40 PRINT A12;B12;CT2
99 END
rWN
HI READ A,£I,C
20 DATA 1,2,3
30 PRINT
40 PRINT A;B;C
50 PRINT AT2;BT2;CT2
99 END
RUN
ENTERING DATA INTOTHE COMPUTER 99
123
149
le READ A,B,C
20 DATA 1,2,3
3111 PRINT
40 PRIN'T "A =" ;A,"B =" ;B,"C =";C
RESTORE
5111
60 READ L,M,N
70 PRINT "L =";L,"M =";M,"N =";N
99 END
RUN
A -- 1 B = 2 C =3
L == 1 M == 2 N =3
3. Questions and exercises that involve the INPUT statement may be omitted if you are
not using an interactive system This applies to the remaining questions and
exercises in this book.
100 PROGRAMMING IN BASIC
HI LET A=l
20 LET A=A+1
3111 LET A=A+1
40 PRINT
50 PRINT "A ="; A
99 END
RUN
A = 1
A ::: 2
A = 3
10 LET A=l
20 LET C==A+B
30 PRINT
40 PRINT "C =";C
99 ENII
RUN
C = 1£1
HI PRINT
2B INPUT A
3e INPUT B
40 PRINT aAtB =a;AtB
99 EN[I
RUN
...
?. ')
'? -4
AtB = 6
13. Indicate the errors, if any, in the program segments and screen
messages shown below . Make the necessary corrections .
99 END 99 END
RUN
VALUES FOR X,Y,Z1 2,4
(c) HI LET lS=lB (g) 2fJ INPUT I,J,K
99 END 99 END
RUN
1 2,3,4
99 END
102 PRO GRAMMING IN BASI C
99 END
RUN
60 RESTORE I,J,K
99 ENIt
(Note : There are two errors.)
50 PRINT B 50 RESTORE
99 ENII 60 READ I,J,K
70 PRINT I =";I,"J =";J,"K
I = I ; K
99 END
99 END 99 END
20. Write three program segments, each of which assigns the four
values 1,2,3, and 4 to four variables. In each program , use one of
the three methods introduced in this chapter to enter data into the
computer.
Programming Problems4
For each of the following problems , write three separate programs,
each one entering data in a different way. One program uses the LET
statement, the second program uses the INPUT statement, and the
third program uses the READIDATA statements. Remember, the RUNS
for programs that use LET statements are the same as the RUNS for
programs that use READ/DATA statements.
1. Suppose you own 5 bonds, each having a par vaiue of $1000. If
the interest rate is 12%, what will be your annual interest
income?
(a) Interest Income = Number of Bonds x Par Value x Rate of
Interest (.12)
4. Throughout the book, flowcharts are drawn for the more difficult problems To
understand the flow of logic , yo u should draw flowcharts for the remaining problems
in the book . Always draw the flowchart before you write the program . Programs that
use the INPUT statement to enter data may be omitted in this chapter if yo u are not
using an interactive system.
104 PROGRAMMING IN BASIC
RUN RUN
NO. OF BONDS: 5 NO.,PAR VALUE,RATE? 5,1000,.12
PAR VALUE: 1000 INTEREST INCOME: 600
RATE OF INTEREST: .12
INTEREST INCOME: 600
RUN RUN
Problem 2
S - SALARY A AMOUNT OF SALES - INCOME
R - RATE C COMMISSION
( Start
) 8
w t Calculate
Commission
Print C=A*R
Prompt Income
I=S+C
W
Input
S,R
t
0
ENTERING DATA INTO THE COMPUTER 105
RUN
)
SALES,COST,EXPENSES: 31B0 2121121121 51210
GROSS PROFIT: 11121121
NET PROFIT: 61210
Calculate
Using the INPUT Statement Gross Profit
G=S-C
Net Profit
RUN N=G-E
SALES,COST,EXPENSES? 31BB,2BBB,5BB
Print
GROSS PROFIT: l1Ba
Blank line
NET PROFIT: 6121121
S,C,E
G
N
4 . Suppose you received $550 as your salary on May 1 . If you made
payments amounting to $350 to cover rent, food, clothes, and
miscellaneous items, what amount did you save? What amount is End
saved if you received another $550 on May 15 but spent only
$125? Initially you had no savings.
(a) Amount Saved = 0
(b) Amount Saved = Amount Saved + Salary - Payments
(c) In the flowchart , notice the preparation symbol that initializes
A to zero.
RUN RUN
Problem 4
A AMOUNT SAVED P1 - FIRST PAYMENTS
S - SALARY P2 - SECOND PAYMENTS
( Start
) 0)
\1.1
\lI Calculate
Calculate Amount Saved
Amount Saved
A=A+S-P2
A=A+S- P1
Print
Print Blank line
Blank line
S
S P2
P1
A
A
End
RUN RUN
FAHRENHEIT: 77 FAHRENHEIT'? 77
CELSIUS: 25 CELSIUS: 25
RUN
FOUR BRANCHING
AND LOOPING I
A. After completing this chapter, you should be able to write BASIC
programs and complete skeletal BASIC programs that use:
1. GO TO statements .
2. IFfTHEN statements.
3. ON . .. GO TO statements.
4. Counters (positive and negative).
B. In addition, you should be able to:
1. Differentiate between conditional and unconditional
branches.
2. Define
(a) A branch.
(b) A loop.
3. Summarize what happens when a decimal number is trun-
cated in an ON .. GO TO statement.
4. List the six BASIC relational operators and their meanings.
5. Terminate loops by means of
(a) IFfTHEN statements that test the data.
(b) IFfTHEN statements that test counters.
(c) ON .. GOTOstatements.
6. State the number of alternative transfers allowed in
(a) GO TO statements.
(b) IFfTHEN statements.
(c) ON ... GO TO statements.
7. State the differences in execution between
(a) GO TO statements .
(b) IFfTHEN statements.
(c) ON .. . GOTOstatements.
8. Find and correct errors in invalid
(a) GO TO statements.
(b) IFfTHEN statements.
(c) ON . . GOTOstatements.
9. Find errors in programs.
10. Produce the output of programs.
11. (a) State the restrictions that limit the index of an ON .. GO TO
statement.
(b) Explain how a computer may respond to an ON . GO TO
statement whose index is out of the range.
12. Summarize the purpose of each of the three statements
required to set up a counter that controls a loop .
[ ~~30
40 GO TO 10
99 END
Line 10 is executed, then line 20 and then line 30. On reaching line
40, control is transferred back to line 10 Lines 10, 20, and 30 are
executed a second time. Again, line 40 causes the computer to
transfer back to line 10. Lines 10,20, and 30 are executed for the third
time. Line 40 causes control to transfer to line 10. Notice that control
keeps going back to line 10, and that the execution of lines 10,20, and
30 never stops. We are in what is called a loop and the GO TO
statement is referred to as an unconditional branch, since there is
no alternative except to GO TO line 10. In other words, the GO TO
statement offers no conditions under which the computer may
choose another path .
A GO TO statement may also transfer control to a higher-numbered
statement, ignoring all the intervening statements in the process.
This transfer is called a branch . Here is an example .
UI
20
30
40
50
When the computer reaches line 20, control is transferred to line 50,
where execution resumes. Lines 30 and 40 are skipped .
In the first example, the GO TO transfers control to a lower-
numbered statement. In example two, control is transferred to a
higher-numbered statement. It should be noted that a GO TO state-
ment must not reference itself, since this results in a continuous loop.
1. If you are not using an interactive system. omit programs that use the INPUT
statement to enter data.
BR ANCH ING AN D LOO PING I 109
each of which enters data into the computer in a different way . The
first one uses the LET statement , the second one uses the INPUT
statement, and the third one uses the REAOIDATA statements . Trace
through the logic of each program, then key it in and RUN the program.
Compare the three RUNS .
1. Using the LET statement
F:LJN
A .- 1
I') ..-. r)
"'-
A -- 3
RUN
VALUE FOR A? 1
A 0: 1
l)ALUE FOR A? 2
I~ = 2
IJAL.UE FOR A? 3
A = 3
IJALUE FOR A?
The computer keeps asking for more datal How do you abort this
program? See Program 1 where you were in a continuous loop.
[ g READ A
DATA 1,2,3
PRINT
PRINT "A =";A
50 GO TO 10
-
-
-
-
-
Reads the values of A one at a time from the DATA statement.
Supplies the READ statement with data.
Leaves a blank line .
Prints the current value of A.
Transfers control to line 10. Execution resumes sequentially until
line 50.
99 END - Not executed, but may have to be included.
RUN
A = 1
A - 2
A =3
?OUT OF DATA ERROR IN 10
Problem 2
R - RETAIL PRICE
T - TAX
C - COST
Start
Calculate
Tax
T=R*.05
Total Cost
C=R+T
Print
Blank line
R
T
C
End
HI READ A
2£1 DATA 2,4,6
3£1 PRINT
4£1 PRINT " A = " ; A
5£1 GO TO HI
99 ENIt
2.
9£1 GO TO 1111
99 ENIt
114 PROGRAMMING IN BASIC
'1'7 END
30 IF A=6 THEN 99
99 END
30 IF A=6 THEN 99
99
~
END
BRANCHING AND LOO PING I 115
RUN
A = 1
A = 2
A = 3
V< 1I N
VALUE FOV~ A? 1
')ALUE FOR A? 2
A =2
VALUE FOR A? 3
A :;:: 3
VALUE FOR A? 4
Notice the number 4 that was entered as the last value for A. This
entry may be any number greater than 3 in order to stop the program.
An alternative method of testing A would be as follows.
HI
10 READ A -Reads the values of A one at a time from the DATA statement.
20 D AT Ai, 2 , 3 , 3 .5 - Supplies the READ statement with data .
321 IF A>3 THEN 99 -Tests the current value ofA.
(i) If A is greaterthan 3, control is transferred tothe END statement.
(ii) If A is not greater than 3 (less than 3 or equal to 3), the
computer proceeds to the next statement. Execution resumes
sequentially until line 60.
40 PRINT - Leaves a blank line.
50 PRINT • A =. ; A - Prints the current value of A .
60 GO TO 10 - Transfers control back to line 10.
99 END - Terminates program execution.
RUN
A -. 1
A _. 2
A = 3
10 READ A - Reads the values of A one at a time from the DATA statement.
20 DATA 1,2,3,4 - Supplies the READ statement with data.
30 IF A(=3 THEN 50 - Tests the current value of A.
(i) If A is less than 3 or A is equal to 3, control is transferred to line
50, where execution resumes sequentially until line 70.
(ii) H A is greater than 3, the computer proceeds to the next
statement .
4~ GO TO 99 - Transfers control to the END statement.
- Executable statements.
60
70 GO TO 110== - Transfers control back to line 10.
99 END - Terminates program execution .
4. The branch out of the loop does not necessarily have to be to the
END statement. Control may be transferred to another statement
outside the loop.
10 READ A
20 DATA 1,2,3,3.5
BR ANCHIN G AND LOO PIN G I 119
3~ IF A)3 THEN
90 GO TO 10
lIiH!ll
100 ~<--~------~
999 END
Statement number 100 could be the start of a new rout ine , such
as a routine that reads in another set of numbers and finds the
largest number in the set. The program terminates when the EN D
statement is reached .
5. In the sample programs and program segments just shown, the
test on A is performed before its value is printed. You may want to
perform the test after the value is printed. Here is an example .
Notice that the relationship is between A and 2 in order to
produce the same RUN as those produced in Programs 1 and 3
above .
RUN
A = 1
A = 2
A = 3
RUN RUN
VALUE FOR A? 6
A = 6
VALUE FOR A? 8
RUN RUN
RETAIL PRICE'? 70
Problem 2
R - RETAIL PRICE
T - TAX
C - TOTAL COST
Start
Calculate
Tax
T= R*.05
Total Cost
C=R+T
Print
T
C
122 PROGRAMM IN G IN BASIC
10 PRINT
20 F'RINT 'VALUE FOR A' ;
321 INPUT A
4£1 IF A)6 THEN 99
521 PRINT 'A =" ; A
60 GO TO 10
99 END
10 READ R 1~ pr\I NT
20 DATA 49,59,69,79 20 PRINT "RETAIL PRICE";
39 IF R)69 THEN 999 3~ INPUT R
40 LET T=R*.05 40 IF R)6fl THEN 99
59 LET C=RtT 5E1 LET T=R*.05
60 PRINT 66:'1 LET C=RtT
70 PRINT "RETAIL PRICE:";R 70 F'R I NT ·SALES TAX:";T
80 PRINT "SALES TAX:";T sa PRINT "TOTAL COST!";C
90 PRINT "TOTAL COST:";C 90 GO TO 10
lBB GO TO lB 99 ENII
999 END
/Keywords ~
1. 20 ON I GOTO 25,40,50 ,60 ,50
i
Statement
i
Variable
i
List of statement
number numbers
2. ON GO TO 60,45 ,60,80
30
r
J 2
Expression
124 PROGRAMMING IN BASIC
Hl LET A=13.2
20 LET B=13
30 LET C=(A-B)*ll11
40 PRINT
50 PRINT C
99 END
RUN
1.99999999
RUN the above program to find out what value your computer assigns
to C If the result is a decimal number , the digits after the decimal point
will give you an idea of how much the index should be increased.
2. Spaces before and aft er the index have been left onl y for clarit y.
3. ThiS is cove red in greater detail in Chapter Twet ve .
BRANCHING AND LOOPING I 125
The value of the index cannot be less than one (negative or zero) ,
nor can it exceed the number of statement numbers shown after the
words GO TO. In both cases , the index is considered to be out of the
range of the listed numbers. Depending on your computer system,
one of the following may occur.
1. Execution stops and the computer gives an error message.
2. The ON . . GO TO statement is ignored and the statement following
the ON . . GO TO is executed.
3. Control is transferred to the last statement number in the list
when the value of the index exceeds the number of statement
numbers .
4. Control is transferred to the first statement number in the list
when the value of the index is less than one.
Check your manual or experiment if you have the time.
Some computer systems may limit the number of branching
options offered by an ON . .. GO TO statement. In example one , there
are five choices; in example two, there are four , Also , some computer
systems use a different command to accomplish this many-way
branch. Here are several other versions of the ON . . . GO TO statement.
Extra spaces are inserted in the statements for clarity only.
1. 60 ON K THEN 15,12e,ae
2. 60 ON K G. 15r12e,a~
3. 60 ON K GOT 15,12e,80
4. 60 GO TO 15r12e,80, ON K
5. 60 GO TO K OF 15r120,80
20 ON I GO TO 25,4B,5~,6~,50
20 IF 1=1 THEN 25
21 IF 1=2 THEN 40
22 IF 1=3 THEN S~
126 PROGRAMMING IN BASI C
23 IF 1=4 THEN 60
24 IF 1=5 THEN 50
RUN
HI 12
HI 8
10 20
10 5
BRANCHING AND LOOPING I 127
Note that the output is single spaced. This is your first program that
single spaces output when the PRINT statements are in a loop. To
produce a blank line after the word RUN yet keep the rest of the output
single spaced, the statement PRINT must be outside the loop. In this
program, it has been numbered 10-the first statement in the pro-
gram.
10 READ P,F
20 [lATA 1,150
~H~
411
50 [lATA 4,85
60 ON P GO TO 70,100,120,999
7fl PRINT
80
<7'0 GO TO 10
100
110
120
130
999 END
RUN
RUN
STORE: 1
AMOUNT SAVED: 15
STORE: 2
AMOUNT SAVED: 12
STORE: 3
AMOUNT SAVED: 9
Problem II
M MARKED PRICE
S STORE NO. (INDEX)
A AMOUNT SAVED
BRANCHING AND LOOPING I 129
( Start )
W
Read
M
0 (0 0 8
Calculate Calculate Calculate
Amount Saved Amount Saved Amount Saved End
A= M*.25 A= M*.20 A=M*.15
1. 30 [lATA 2,275
4E1 DATA 3,400
130 PR O GRA MMING IN BASIC
10 f,[AD M
2i1 [lATA 60
30 f,EAD S
4£1 DATA 1,2,3,4
50 ON S GO TO 60,80,100,999
60 LET A=M*.25
70 GO TO 110
80 LET A=M*.20
90 GO TO 110
HH1 LET A=M*.15
lUl PRINT
12~ PfnNT "STORE:";S
130 PRINT "AMOUNT SAVED:";A
1.4£1 GO TO 30
999 END
4.4 COUNTERS
In some programs , it is necessary to count the number of data items
or to count the number of times a computer goes through a loop . The
latter is one of the ways by which a loop can be controlled. A counter
can also be used in calculations. A loop is controlled by using two LET
statements and a test statement. The first LET statement initializes the
counter (a variable), the second LET statement increments
(increases) or decrements (decreases) the counter within the loop ,
and the IFITHEN statement tests the counter within the loop.
BRANCHING AND LOOPIN G I 131
H1
2£1 LET K=l
30
4£1
~H'I
621 LET K=K+1
721 IF K) 5 THEN 99
821 GO TO 30
(?9 END ( 1
Line 20 initializes the counter to 1, line 60 increments the counter
by 1, and line 70 tests the current value of the counter . If K (the
counter) is greater than 5 , control is transferred to the END statement.
If K is not greater than 5 , the computer proceeds to the next state-
ment.
Remember, the branch out of the loop does not necessarily have to
be to the END statement. Control may be transferred to another
statement outside the loop.
RUN
1 5
2 12
3 9
4 14
,..
.J 17
132 PROG RAMMI NG IN BASIC
II. Here is another program . This one uses a counter in two ways .
1. It controls a loop .
2. It is used in the program ' s calculations .
The program multiplies a coun ter by five after the counter is
initialized and each tim e it is incremented (except the last time) .
(a) Use the LET statement to initialize the counter to one.
(b) Inside the loop , multipl y the counter by five, print the value of
the counter and the product , then increment th e coun ter by
one .
(c) Exe cu te the loop four tim es .
~1 F.:EM K--COUNTER
02 REM P--f'RODUCT
fWN
1 S
2 10
3 1""
.J
4 2f:'1
RUN
I::"
.J 5
4 12
.'J'
9
'""'
.-1 14
17
Each time the computer passes through the loop, the counter is
decreased by one. Once the counter has been reduced to zero, the
computer is out of the loop. The loop, therefore, is performed five
times (5, 4,3,2, 1) .
Counters may be increased or decreased by any number (whole or
decimal) or by a variable previously defined inthe program. However,
care must be taken in choosing the initial value and in choosing the
position (that is, the line number) of the initializing statement.
RUN
1 S0 15 65
2 10 3 13
3 30 9 39
RUN
1. 4~ DATA 5~,1~,30
2. (e) 5111 LET M=C*. 30
3. (c) 60 LET R=CtM
4. 80 LET K=I\t1
5. (d) 90 IF K)3 THEN 999
6. 100 GO TO 30
II.
HI PRINT
20 LET K=l
3111 LET D=K*600
40 PRINT "DEPENDENTS:";K,"DEDUCTION:";D
50 LET K=Ktl
60 IF K)3 THEN 99
70 GO TO 30
C; '.~ END
Notice the two paths leading from the decision symbol. Make sure
you understand what they represent. The Yes exit means that the
IFfTHEN test is true . The No exit, in this flowchart, is a GOTO statement.
The statement is executed when the IFfTHEN test is false.
136 PROGRAMMING IN BASIC
Problem II
K COUNTER
D - DEDUCTION
( Start )
K=1
Calculate
Deduction
D= K*600
Increment
Counter
K=K+1
>Y__
es __
~>C En,_d_ )
4.5 TERMINOLOGY
Two terms were used in the previous sections to indicate the alterna-
tive paths that can be taken during the execution of a program. These
were:
1. A branch The transfer of control to another statement in a
program. On some systems , the transfer may be to a non-
executable statement such as a REM statement or a DATA state-
ment.
2. A loop The transfer of control to a lower-numbered statement,
causing a series of instructions to be repeated .
BRANCHING AND LOOPING I 137
A Branch A Loop
10 F~ E A [I A 10 REA[I A
20 20
30 IF A=6 THEN 99 A branch 30 IF A=6 THEN 99
developing
A branch into a
loop
99 END 7~ GO TO 10
99 END
A Short Summary
The series of instructions that the computer follows can be altered in a
number of ways. One method is by using a GO TO statement. This
transfers control to another statement in the program . The GO TO is
considered an unconditional branch, since there is no other alterna-
tive than to GO TO a specific statement. The IF/THEN statement is
another method by which control can be transferred. This statement
is referred to as a conditional branch because control is transferred
only when a certain condition is met. It offers a two-way choice. If the
condition is true, control is transferred to the statement specified; if
the condition is false, the computer proceeds to the next line .
The third statement that transfers control is the ON ... GO TO state-
ment. It offers a many-way choice by allowing the computer to
transfer to one of several statements in the program, depending on
the current value of a certain variable or expression called the index.
The ON .. . GO TO statement is often used to replace a number of
consecutive IFITHEN statements.
Counters are frequently used to control loops. The counter (a
variable) is initially set at a specific value , then incremented (or
decremented) within the loop. An IFITHEN statement tests the value of
the counter. When the counter reaches a particular value, control is
transferred out of the loop.
Up to this point, three ways have been shown by which a loop can
be controlled. The three methods are listed below with an example for
each. The IFITHEN statement terminates a loop two ways.
10 LET A:::40
20 IF A)100 THEN
60 LET A=At20
138 PROGRAMMING IN BASIC
70 GO TO 20
80 ~(----------~
'199 END
5~ LET K=Ktl
60 IF K)3 THEN
7a GO TO 20 80~
80 (
999 END
(a) 80 GO TO 01
(b) 5~ GO TO END
(c) 40 GO TO B9
(d) Sf! GO TO r~9
(e) ~H~ GO TO 5*9
(a) 50 IF A THEN 70
(b) ~5a IF BO'D THEN 90
(c) 50 IF AlB THEN 80
(d) 50 IF A<=B THEN END
(e) 50 IF A*B>CUI THEN 80-10
(f) 50 IF A>=B THEN 85
HI F'RINT
20 LET A=l
30 IF A)10 THEN 99
40 PRINT A
140 PROGRAMMING IN BASI C
10 PRINT
20 LET A=4
3~ LET 8=A*2
40 IF B<U) THEN 6~
5£1 PRINT "A =" ;A, "8 ;; I ; 8
6£1 LET 8=8+A
/'£1 PRINT • [I ;;::. ; 8
8£1 IF 8>1~ THEN 3~
99 END
Be LET 1(=1(+1
913 GO TO 4e
(b) 213 IF 1(=1 THEN 513
313 IF K=2 THEN 713
413 IF 1'\=3 THEN 999
113 PRINT
21C1 LET 1'\=1
~H' LET A=3
40 PRINT A
~~ 0 ON K GO TO 60,6e,6~"99
6l'l LET A=A+3
7~ LET 1(=1(+1
80 GO TO 40
99 END
113 PRINT
2£1 LET 1(=1
31:'1 f~EAD A
4~ DATA 1l'l,8,12,4,6
5[l PRINT A
60 LET 1(=1(+1
70 IF 1()5 THEN 99
80 GO TO 30
99 END
142 PROGRAMMING IN BASIC
RUN
1~
B
12
4
6
Programming Problems 4
1. A store is offering a discount of 15% on any article purchased
between 5:00 p.m . and 6 :00 p.m. each day it is open during the
month of August. If you purchased three articles whose regular
prices were $40, $60, and $80, what was the amount of discount
and what was the reduced price of each article?
(a) Use LET statements to enter the data. Generate the data by
incrementing each regular price by $20.
(b) Terminate your loop by checking each data item for the final
amount.
(c) Discount = Price x .15
(d) Reduced Price = Price - Discount
RUN
REGULAR PRICE: 40
DISCOUNT: 6
REDUCED PRICE: 34
REGULAR PRICE: 60
DISCOUNT: 9
REDUCED PRICE: 51
REGULAR PRICE: 80
DISCOUNT: 12
REDUCED PRICE: 68
4. Replace the INPUT statement by the RE AO. OAT A statements in your programs if you
are not using an interacti ve system This applies to the remaining problems in this
book.
BRANCHING AND LOOPING I 143
Problem 1
P REGULAR PRICE
D DISCOUNT
R REDUCED PRICE
Calculate
Discount
D= P*15
Reduced Price
R=P-D
Print
Blank line
P
D
R
Increment
Regular Price
P= P+20
144 PROGRAMMING IN BASIC
I~UN
DEPARTMENT: 12 RATE: 2
I~ MP LOY E E: 1
~W. 0 r F' ART S: 2 12
INCOME: 424
EMPL.DYEE: 2
NO. OF PARTS: 213
INCOME: 426
EMPLOYEE! 3
NO. OF PARTS: 209
INCOME:. 418
RUN RUN
COIlE,AMOUNT? 1,250 CODE,AHOUNT: 1 250
BALANCE: 250 BALANCE: 250
CODE,AHOUNT? 2,150 CODE,AHOUNT: 2 150
BALANCE: 100 BALANCE: 100
CODE,AHOUNT? 1,301!1 COIlE,AHOUNT: 1 300
BALANCE: 400 BALANCE: 400
COIlE,AHOUNT? 2,200 CODE,AHOUNT: 2 201!1
BALANCE: 200 BALANCE: 200
COIlE,AHOUNT1 3,0
BRANCHING A ND LOOPING I 145
Problem 3
B BALANCE
C CODE (INDE X)
A AMOUNT
( start)
\lI
B=0
Input
C,A
8 (0
-.v
0
""
Calculate
Balance
Calculate
Balance End
B=B+A B=B ~ A
{
i
Print
B
146 PRO GRAMMING IN BASI C
4 Rewr ite the program for Prob lem 3. Th is time , use IFfT HEN state-
ments to check the code , rather than the O N GO TO statement
(a) Use the same method to enter th e data .
(b) Yo ur output should be the same.
(c) Is there any major difference between yo ur flowchart and the
one drawn for th e program in Problem 3?
5 . Find the semiannual interest and the new prin cipal for each of the
following amounts: $2000 , $3000, and $4000 . The rate of inter-
est is 14% .
(a) Use LET statements to enter the data (the amounts) Gene r-
ate the data by in crementing each amount by $1 000 .
(b) Terminate your loop by checking each data item for the final
amount.
(c) Time = 6/ 12
(d) Interest = Amount x Rate x Time
(e) New Prin ci pal = Amou nt + Interest
RUN
AMOUNT: 213130
INTEREST: 140
NEW PRINCIPAL: 2140
AMOUNT: 31300
INTEREST: 210
NEW PRINCIPAL: 3210
AMOUNT: 41300
INTEREST: 280
NEW PRINCIPAL: 4280
6 . Programs are often written to find the large st sale, or the highest
mark, or the highest number , etc. When writing the program for
the problem shown below , set a variable to a va lu e that is lower
than any of the data items to be entered, say, L= -1 , where L
represents LARGE . Ea ch time an item of data is entered , check to
see whether or not this data item is greater than the current value
of L. If it is , repl ace the val ue of L by the item Just entered. Print
th e value of L aft er the last data item is checked . The three main
statements in such a program are as follow s.
60 IF S>L THEN 813 - Te sts to see if the SA LE is greater than LARGE . If it is, co ntrol is
transferred to li ne 80
RUN RUN
THE LARGEST SALE IS: 94121121 THE LARGEST SALE IS: 94121121
Problem 6
K COUNTER
L LARGE
S SALE
- -
( Start
W
)
K=1
L=-1
8 i
Print
Prompt
W
Input
S
~
8
148 PROGRAMMING IN BASIC
Yes) L=S
Increment
Counter
K= K+ 1
No
RUN
LENGTH WIDTH AREA
3 2 6
3 12
'56" 4 221
5 321
7 6 42
r-------.---------------- ~ - - -.---- ~ --.- ~ ~ -.- - - - - - - - - - - - ---,-- - - - - ,
F VE BRANCHING
AND LOOPING II
10 UI READ A
20 2B DATA 1,2,3,4,99999
30 INPUT A 3B IF A=99999 THEN 99
:: ::D :~i_9_:_:_9_9_T_H_E_N_9_9_J_-,
4B
5B
60 GO TO 10
99 END ~----------------~
RUN
'JALUE FOr~ A7 2
A ::: 2
'')ALUE FOR A7 3
A =3
VALUE FOR A7 99999
In the RUN, notice that a flag of 99999 is entered after the last prompt.
In this way, you are able to terminate the computer's request for more
data.
1 k'l READ A - Reads the values of A one at a time from the DATA
statement.
21!! DATA 1,2,3,99999 - Supplies the READ statement with data. The last item in the
list is 99999.
3[1 IF A=99999 THEN 99 -Tests the current value of A.
(i) If A is equal to 99999, control is transferred to the END
statement.
(i i) If A is not equal to 99999, the computer proceeds to the
next statement.
40 PRINT - Leaves a blank line.
50 PRINT "A = I ; A - Prints the current value of A.
60 GO TO 10 - Transfers control back to line 10.
99 END - Terminates program execution.
RUN
A = 1
A = 2
A = 3
In this program, the trailer value is entered as the last item in the DATA
statement.
RUN RUN
RUN
1 50 15 65
2 10 3 13
3 30 9 39
BRANCHING AND LOOPING II 153
Problem 2
K COUNTER (ARTICLE NO.)
C COST PRICE
M MARKUP
R RETAIL PRICE
Calculate
Markup
M=C*.30
Retail Price
R=C+M
Increment
Counter
K= K+1
RUN
NO. OF DEPENDENTS; 1
DEDUCTION: 600
NO. OF DEPENDENTS: 2
DEDUCTION: 12021
NO. OF DEPENDENTS: 3
DEDUCTION: IS00
2.
10 PRINT
2~ LET K=l
~.t;~ READ C
4~ DATA 5B,10,3B,99999
5~ IF C=99999 THEN 999
6~ LET M=C*.31J
70 LET R=CtM
8~ PHINl K,C,M,R
90 LET K=Kt1
100 GO TO 3B
9?'i END
3.
1B F".;EAD N
20 DATA 1,2,3,99999
30 IF N=99999 THEN 99
4B LET D=N*600
:;e PRINT
6B PRINT 'NO. OF DEPENDENTS:";N
7~ PRINT "DEDUCTION:";D
8~ GO TO HI
99 END
10 READ N
[~40
HEAD A
30 DATA 4,67,85,79,93
5~
6e GO TO 20
data (67,85,79 ,93), this number must be 4. The remaining values are
assigned to A one at a time. (One number is assigned each time the
computer passes through the loop.)
30 DATA 4, 67,85,79,93
t ',,\t/,
Value of N Values of A
How does this work with a counter?
HI LET K=l
2~ READ N
30 f<EAD A
4~ DATA 4,67,85,79,93
5~
6~
70 LET K=Kt1
8111 IF K>N THEN 9 9 ,
90 GO TO 30 I
99 EN[I~<------------~
RUN
UNIT PRICE! 13.5
EXTENDED VALUE: 135
U~!ITPRICE: 1.25
EXTENDED VALUE: 12.5
UNIT PRICE! .45
EXTENDED VALUE: 4.5
Depositor Balance
1 $4000
2 2500
3 5700
If interest is paid at a rate of 10% once every six months, what
interest income does each depositor receive at the end of the
first six months? What would be the amount in each account if
the interest is deposited and no withdrawals were made?
(a) Use the READ statement to store the number of depositors in
a simple variable. The variable is used subsequently with a
counter to terminate the loop.
(b) Use another READ statement to enter the balance of each
account.
(c) Use one DATA statement.
(d) Print the counter as the number of the depositor.
158 PROGRAMMING IN BASIC
1~ LET K=l
20 LET R=.10
3~ READ N
4~ READ B
50
60 PRINT
70
B0
';'0
U;J~
110
120 LET K=Ktl
130
11H'1
")99 END
RUN
DEPOSITOR: 1 BALANCE: 41il~0
INTEREST: 41H'l
NEW BALANCE: 44~0
DEPOSITOR: 2 BALANCE: 2500
INTEREST: 250
NEW BALANCE: 275~
DEPOSITOR: 3 BALANCE: 5700
INTEREST: 570
NEW BALANCE: 6270
Month Kilowatt-hours
1 1000
2 950
3 930
If the consumption charge is 3.5 cents per kilowatt-hour, what
would be the amount of your electrical bill for each of the three
months?
(a) Use the READ statement to store the number of months in a
simple variable. The variable is used subsequently with a
counter to terminate the loop.
(b) Use another RE A D statement to enter the kilowatt-hours.
(c) Use one DATA statement.
(d) Print the counter as the number of the month.
(e) Bill = Kilowatt-hours x Rate (.035)
RUN
110NTH: 1
KILOWATT-HOURS: lBBe
ELECTRIC BILL: 35
MONTH: 2
KILOWATT-HOURS: 95B
ELECTRIC BILL: 33.25
160 PR OGRAMM IN G IN BASI C
i'lONTH: 3
KILOWATT-HOURS: 93~
ELECTRIC BILL: 32.55
Problem II
R - RATE PER KILOWATI-HOUR
K - COUNTER (MONTH NO )
N - NO . OF MONTHS
H KILOWATT-HOURS
B ELECTRIC BILL
( start)
Calculate
Electric Bill
R= .035 B= H*R
K=1
Print
Blank line
Read K
N H
B
Increment
Counter
K= K+1
II.
10 READ P,F
20 [lATA 1,150
30 DATA 2,275
40 DATA 3,400
50 DATA 4,85
162 PRO G RA MMING IN BASI C
HI READ P,F
2~ DATA 1,150,2,275,3,40~,-1,B
3~
4~
50
60 GO TO 1~
99 END
The second question is this : " How does the computer break out of
the loop?" Here is the program segment once more , but with an
additional statement.
10 READ P,F
20 DATA 1,150,2,275,3,40B,-1,0
30 IF P=-l THEN 99
40
5~
60 GO TO 1~
99 END ~---------'
BRANCHING AND LOOPING II 163
Notice that the last set of numbers is illogical for this program
segment (you cannot have - 1 people apply for membership to a
community club). In the above example , the first number of this last
set is used in an I FfTHEN statement, where a test is made to determine
whether or not the number has been assigned to its variable.
30 IF P=-l THEN 99
1. You must always satisfy the READ statement. If two variables are
to be assigned values each time the computer passes through a
loop, then you must have sets of data in the DATA statement with
two numbers in each set.
2. The dummy numbers need not be -1 ,0; they may be any values
you wish, except data values.
3. Any of the variables in the READ statement may be tested for its
dummy value; it does not necessarily have to be the first variable
in a set.
(a) Use the READ/ DATA statements to enter the amount of the sale
and the code for each of the three salespersons.
(b) Use an ON . GO TO statement to branch to the statements that
assign the appropriate rates of commission and to branch to the
END statement.
(c) Use a code of 4 to terminate the loop.
(d) Commission = Sales x Rate
(e) Trace through the log ic then RUN the prog ram . Explanat ions of
importan t conce pts are supplied at the end of the program.
10 READ S,K
20 DATA 350,2,290,1,467,3,0,4
30 ON K GO TO 40,60,80,999
40 LET R=.10
50 GO TO 90
t)0 LET R= .12
7iJ GO TO 90
80 LET R=.15
90 LET C=S*R
HHl PRI NT
lll!l prdNT "SALES:";S
12~ PRINT "RATE:";R
130 PRINT "COMMISSION:";C
140 GO TO 10
999 END
RUN
SALES: ~351!1
RATE: .12
COMMISSION: 42
SALES: 290
r,ATE: .1
CDMMISSION: 29
SALES: 467
F:ATE:.15
COMMISSION: 70.05
Two numbers in each set (the sales and the code) are assigned to the
variables Sand K respectively each ti me the computer passes
th ro ugh the loo p. The fir st t ime through the loop, 350 and 2 are
BRANCHING A ND LOOPING" 165
assigned to Sand K; the second time, 290 and 1; the third time, 467
and 3 ; and the last time , Q') and 4. The purpose of the last set of
numbers is to terminate the program . The number 4 (assigned to the
index K) causes control to transfer to the END statement. The zero (or
some other non-data value) must be assigned to S in order to satisfy
the READ statement . The ON GO TO statement results in multiple
branching as follows.
When the code (K) is 1, control is transferred to line 40, which assigns
.10 to R .
When the code (K) is 2, control is transferred to line 60, which assigns
.12 to R.
When the code (K) is 3, control is transferred to line 80, which assigns
.15 to R.
When the code (K) is 4, control is transferred to line 999, the END
statement.
Notice that immediately after R is assigned a rate , the computer goes
to line 90 , which calculates the commission . This is followed by the
required PRINT statements.
The program shown below prints the number of articles and the
rate of discount for each of the following purchases: 250 articles,
60 articles, and 140 articles.
H1 READ NdO;
20 DATA 250,3,60,1,140,2,0,4
30 ON K GO TO 4~,60,80,999
40 LET R=.06
50 GO TO 90
60 LET R=.08
721 GO TO 921
80 LET R=.10
9£1 PRINT
100 PRINT "NO. OF ARTICLES:";N
110 PRINT "RATE OF DISCOUNT:";R
1221 GO TO 10
999 END
RUN
NO. OF ARTICLES: 250
RATE OF DISCOUNT: .1
NO. OF ARTICLES: 60
RATE OF DISCOUNT: .06
NO. OF ARTICLES: 140
RATE OF DISCOUNT: .08
10 F'RINT
221 READ K,A
321 DATA 1,10,2,20,3,30
BRANCHING AND LOOPING II 167
40 ON K GO TO 7121,9121,999
5111 LET B=A+l
60 GO TO HH'l
7~ LET B=A+2
8121 GO TO 1121111
90 LET B=A+3
101!l PRINT I A =';A,"B =I ; S
1 HI GO TO 2 III
99<J END
RUN
I~ .... 10 B 11=
A .- 20 II 22=
A =
30 B = 33
lill PRINT
20 READ K,A
30 DATA 1,6,2,8,3,O
40 ON K GO TO 51ll,70,99
50 LET B=A*2
60 GO TO 81ll
70 LET B=A*3
80 PRINT K,'A =";A,"S =";B
9f' GO TO 20
99 END
HUN
NO. OF ARTICLES: 6B
GfWSS COST: 12111
RATE OF DISCOUNT: .1216
AMOUNT OF DISCOUNT: 7.2
NET COST: 112.8
(c) RUN
NO. OF ARTICLES: 60
RATE OF DISCOUNT: .1
30 DATA 1,10,2,20,3 d0, 4 ,555 - Last item may be any number, since the program
ends before it can be used .
3.
RUN
1 A = 6 B - 12
2 A = B B = 24
170 PROGRAMMING IN BASI C
4.
5.4 SUMMATION
How does a computer add a number of values and print subtotals?
Computers can add only two numbers at a time . If you want to add the
numbers 67 , 85 , 79 , 93 , the computer would add them in the follow-
ing manner .
Subtotal 0
+ 67
Subtotal 67
+ 85
Subtotal 152
+ 79
Subtotal 231
+ 93
Sum 324
A variable , say S , shou ld first be initialized to zero outside a loop .' It
is used subsequentl y inside the loop to accumulate the sum .
1. Some com pu ters au tomatically set all num eri c varia bles to zero when pro grams
are cleare d fr om me mory.
BRAN C HING AND LOOPING II 171
40 F,EAD N
5~ (tATA .. , -, .. - Reads the current number.
60 LET S==StN ~ Adds the subtotal to the current number and assigns the result
back to S.
70 PRINT S - Prints the subtotal .
S S S S S
0) 0) 8 §
Once we get a sum , many things can be done with it. The simplest
8
thing is to print it out. One of the most frequently used routines is the
one that finds an average.
01 REM K--COUNTER
02 REM S--SUM
~3 REM N1--"NUMBER" OF NUMBERS
04 REM N--NUMBERS TO BE AVERAGED
05 REM A--AVERAGE
2. This is the program that was shown to you in Chapter Two where BASIC rules we re
first discussed.
172 PROGRAMM IN G IN BAS IC
RUN
67 67
85 152
79 231
93 324
(a)
50 LET 5=0
6B READ D
7B DATA 1B,20,30
8B LET 5=S+[I
11B GO TO 50
999 END
BRANCHING AND LOOPING II 173
(b) (c)
3e LET K=1 20 LET S=.0
40 READ N 3e READ D
5.0 READ [I 4e DATA U3,2B,3B,3
60 DATA 6,69,82,46 50 IF D=3 THEN SB
6e LET S=S+D
<10LET K=K+1 7e GO TO 3.0
1~~ IF K) N THEN 999 se LET A=[l/S
110 GO TO 5.0
99 END
999 END
3. Write a program that finds your total sales for the first four weeks
of this year then calculates your commission based on this total.
The rate of commission is 15% and your sales are as follows.
Week 1 $4000 Week 3 4400
Week 2 3800 Week 4 4600
(a) Use the READ statement to store the number of weeks in a
simple variable. The variable is used subsequently with a
counter to branch to the statement that calculates the com-
mission .
(b) Use another READ statement to enter the sales.
(c) Use one DATA statement.
(d) Print the number of the week along with your sales and the
subtotal .
(e) Commission = Total Sales x .15
(f) Leave a blank line, then print your total sales and your
commission.
RUN
Problem 3
K COUNTER
T TOTAL SALES S SALES
N NUMBER OF WEEKS C COMMISSION
( Start
) 8t
W
Calculate
~
K=1
Commission
T=0
C=T*.15
Print
Blank line
T
C
End
Calculate
Total Sales
T=T+S
Print
K,S,T
Increment
Counter
K=K+1
BRANCHING AND LOOPING II 175
C
6~ RU~D D
70 DArA 10,20,30
80 LET 5=5+[1
1 HI GO TO 6a
999 END
(c) To find an average, you must divide the sum by the number
of data items; not the last data item by the sum.
80 LET A=5/[1
2.
UJ Ul 121 10
20 321 221 221
30 60 30 321
176 PROGRAMMING IN BASIC
3.
01 REM K--COUNTER
02 REM T--TOTAL SALES
IB f.:EM N-- - NUMBER OF WEEKS
04 f.:EM S--SALES
05 f.:EM C---COMMISSION
IE'! PRINT
2U l.ET K=1
3~ l.ET T=0
4~ READ N
50 READ S
60 DATA 4,4000,3800,4400,4600
70 LET T=T+S
80 PRINT "WEEK";K,S,T
9~ LET I\=K+1
100 IF K)N THEN 12~
110 GO TO 50
120 LET C=T*.15
130 Pf.:INT
140 PRINT "TOTAL SALES:";T
15ft PRINT "COMMISSION:";C
999 END
Employee No. Hrs. Worked Rate Income Tax Oed. Union Dues Pension Oed .
1 44 10.24 80 2 3.00
2 37 1154 75 2 2.50
3 39 12.34 90 2 4.00
01 REM K--COUNTER
~')
6- F~EM N1 -- - NUMBER OF EMPLOYEES
213 REM H--REGULAR HOURS
04 REM f,--REGULAR RATE
05 REM I--INCOME TAX [lED.
06 REM U--·UN I ON DUES
07 REM F'--F'ENSION FUND DED.
~8 REM Hl---OVERTIME HOURS
1t:'J? REM R1--0VERTIME RATE
10 REM V--OVERTIME
11 REM G--GROSS PAY
1 ~l F.:EM [I--··[lEDUCT IONS
4 .
999 ENII
RUN
EMPLOYEE 1 HRS 44 RATE 10.24
OVERTIME HOURS 5
OVERTIME RATE 15.36
OVERTIME PAY 76.8
GROSS PAY 476.16
INCOME TAX 8a
UNION DUES 2
PENSION 3
TOTAL DEDUCTIONS 85
NET PAY 391.16
EMPLOYEE 2 HRS 37 RATE 11.54
OVERTIME HOURS a
OVERTIME RATE a
OVERTIME PAY a
GROSS PAY 426.98
INCOME TAX 7S
- - -- ---.,.-- -
UI'H ON DUES 2
PENSION 2.5
TOTAL DEDUCTIONS 79.5
NET PAY 347.48
Wage Program
K - COUNTER
N1 - NUMBER OF EMPLOYEES H1 - OVERTIME HOURS
H REGULAR HOURS R1 - OVERTIME RATE
R REGULAR RATE V OVERTIME
I INCOME TAX DEDUCTION G GROSS PAY
U UNION DUES D DEDUCTIONS
P PENSION FUND DEDUCTION N NET PAY
180 PROGRAMMING IN BASIC
C~End)
[I] No
Print
Blank line
~
K,H,R
H1
R1
*****************************************
2UI READ N1
215 DATA 3
*****************************************
810 IF K)N1 THEN 999
BRANCHING AND LOOPING II 181
*****************************************
305 IF H) 39 THEN 5e~
*****************************************
The statements in the 500 range .
*****************************************
510 LET Rl=R:*1.5
*****************************************
420 LET G=H*R
52~ LET G=39*RtV
*****************************************
815 GO TO 225
A SHORT SUMMARY
Shown in this summary are five methods by which a loop may be
controlled. These include the three that were discussed in Chapter
Four. The first four programs print and read four data items. The last
program calculates three simple arithmetic expressions.
1. A counter
1~ PRINT
20 LET K=l
rI
30 F:EAII A
40 DATA 10,20,30,40
182 PROGRAMMING IN BASIC
L ~~ PRINT A
LET K=Kt1
If') IF K>4 THEN 9 9 ,
8~ GO TO 3~ I
':;9 END ~(--~~---'
A counter (K) keeps track of the data items. The counter is first
initialized to 1 outside the loop, and then incremented (or decre-
mented) by 1 each time the computer passes through the loop. In the
above program, as long as the value of the counter is less than or
equal to the number of data items (4), the computer continues to
execute the loop. Once the counter reaches a value greater than the
number of data items, the loop terminates.
2. A special value
111 Pf\lNT
20 LET K=l
30 f..:EAD N
40 READ A
50 DATA 4,10,20,30,40
60 PRINT A
70 LET K=Kt1
80 IF K>N THEN 99-]
9lJ GO TO 40
99 END ~(------..........I-
3. A trailer value
1£) PRINT
':10 READ A
30 DATA 10,20,30,40,99999
40 IF A=99999 THEN 99 J
[ 50 PRINT A
- 60 GO TO 20
99 END~<-----------------~
checked to determ ine whether or not the item is the trailer value . If it is
not the trailer value, looping continues ; if it is, the loop term inates.
4. A test on data
10 PRINT
20 LET A=10
5. A code
10 PRINT
~20 READ e,A
30 DATA 1.10.2,20.3,30,4,0
40 ON C GO TO 50,70,90,999
50 PRINT A.At2
~60 GO TO 20
70 PRINT A.A-2
E--80 GO TO 20
90 PRINT A,A/2
E-l.IiH' GO TO 20
999 EN [I <I!!...;.......---------.....I
1~ PRINT
2fJREAD A
30 [lATA
40
~:ifl PRINT A
6£1 GO TO 20
fl9 END
FWN
r)
"'"
4
6
U1
2') READ A
30 DATA 40,50,60,-1
4£1
5£1LET 1<=1<+1
60
70 PRINT
80
99 END
RUN
(a) GO TO 50
(b) 130 TO 70
(c) IF A=40 THEN 7121
(d) IF A=-l THEN 70
(e) IF A=-l THEN 99
1~
20 READ N
3~ F,EAII A
40 [lATA 5,11,22,33,44,55
50
60
7121
80 GO TO 30
99 EN[I
10 PRINT
2121 READ A,B
3121 [lATA 1,1121,2,20,3,3121,888,999
4121 IF A=888 THEN 99
5121 PRINT B
60 GO TO 2121
99 END
6 . Write a program that adds the numbers 10, 20, 30, 40 and prints
subtotals after each addition. Use the READ/DATA statements to
186 PROGRAMMING IN BASIC
RUN
10 10
2£1 3£1
30 6£1
40 1£10
100 GO TO 30
3£1 READ N
4£1 LET T=£1 999 END
50 READ B
6£1 {lATA 3,39,84,26
7£1 LET T=TtB
HHI GO TO 40
999 END
(b) 10 PRINT
20 LET T=0
30 READ A
4~ DATA 1,2,3,-1
~:;0 IF A=-l THEN 99
6£'1 LET T=TtA
70 PRINT A,T
80 GO TO 30
99 END
1.0 PRINT
2£'1 r~EAD A
30 DATA 10,20,30,4£'1,50
40 PRINT A
50 GO TO 20
99 END
(a) A counter.
(b) A special number assigned to a variable by means of a READ
statement. This variable is used subsequently with a counter
to terminate input.
(c) A trailer value (a flag).
(d) A test on each increased (or decreased) amount to deter-
mine whether or not the final value has been reached. Use
LET statements in this program.
188 PROGRAMMING IN BASI C
Programming Problems
1. Suppose you are one of the three employees of the XYZ Manu -
facturing Company mentioned in Problem 2 on page 142 of
Chapter Four . If your production of machine parts last week was
43,42,45,43 , and 40 for the five days of work, what total number
of parts did you produce? If the rate paid for each part produced is
$2 , what was your income for the week?
(a) Use the READ statement to store the number of days in a
simple variable . The variable is used subsequently with a
counter to terminate the loop .
(b) Use another READ statement to enter the number of parts.
(c) Use one DATA statement.
(d) Print subtotals along with the number of parts produced.
(e) Income = Total Number of Parts x Rate
RUN
Problem 1
K COUNTER N NUMBER OF DAYS
R RATE P PARTS
S SUBTOTAL I INCOME
( Start
'V
) (0
K=1
R=2
S=eJ
'V
(0
BRAN CHING AND LOOPING" 189
Calculate
Total Number
of Parts
S=S+P
Print
P,S
Increment
Counter
K=K+1
Calculate
Income
I=S*R
xx LET T=Ttl
Problem 2
K COUNTER
T TRUE N NUMBER OF ANSWERS
F FALSE A ANSWER (INDEX)
( Start
W
)
K=1 Calculate Calculate
T=0 No. TRUE answers No . FALSE answers
F=0 T=T+1 F= F+ 1
\lI
Read Increment
N Counter
K=K+1
No
End
Do the same for a variable , say F , for a FALSE answer. Use the
DATA statements shown below.
xx DATA 20,1,1,2,1,2,2,1,1,1,2
xx DATA 1,2,1,1,2,1,2,1,1,2
RUN
RUN RUN
QUANTITY,UNIT PRICE? 2,4.50 GUANTITY,UNIT PRICE: 2 4.5
EXTENDED COST: 9 EXTEN[IED COST: 9
GUANTITY,UNIT PRICE? 4,3.00 QUANTITY,UNIT PRICE: 4 3
EXTENDED COST: 12 EXTENDED COST: 12
OUANTITY,UNIT PRICE? 5,2.25 GUANTITY,UNIT PRICE: 5 2.25
EXTENDED COST: 11.25 EXTENDED COST: 11.25
OUANTITY,UNIT PRICE? 3,5.15 GUANTITY,UNIT PRICE: 3 5.15
EXTENDED COST: 15.45 EXTENDED COST: 15.45
OUANTITY,UNIT PRICE? 99999,0 TOTAL COST: 47.7
TOTAL COST: 47.7
FWN
Problem 4
N ONE-DOLLAR BILL T TEN-DOLLAR BILL
F - FIVE-DOLLAR BILL B BILL DEPOSITED
( Start
0
t
N= 0 Print
F= 0 Blank line
T=0 N
F
T
W
( End
)
.> _ _Y_e_s_~)0
Yes Calculate
No. of Ones
N=N+1
Calculate
Yes)
No. of Fives
F= F+1
Yes Calculate
No. otTens
T=T+ 1
BRANCHING AND LOOPING II 193
5. Write a program that enters the numbers 1,- 2,3, - 4 , and 5, then
finds the following :
(i) The number of positive numbers entered.
(ii) The sum of these positive numbers.
(a) Use the INPUT statement to enter the numbers.
(b) Use a counter to terminate your loop.
(c) If the number entered is less than or equal to zero,
transfer control to the statement that increments your
counter; if it is greater than zero, find the number of
positive numbers and the sum of the positive numbers.
(d) If the counter is greater than 5, print the results ; if it is not
greater than 5, input another number.
RUN RUN
(a) Use LET statements to enter your data. Generate the data by
incrementing each degree by 9.
(b) Terminate your loop by checking each data item for the final
degree.
(c) The conversion formula is: C = ~(F- 32)
RUN
FWN
10
20 FOR 1=1 TO 3 STEP 1
196 PROGRAMMING IN BASIC
3~
4~
5~ NEXT I
60
20 FOR
1 Value
t
1 TO
Value
~
3
Value
~
STEP 1
The above FOR statement consists of an index (I), an initial value (1), a
test value (3), and a step value (the 1 in the STEP clause).
Index Keeps track of the number of times the loop is performed. It
is similar to a counter.
Initial value The first value assigned to the index.
Test value The limiting value of the index. When the initial value
and the step value are 1, the test value indicates the number of times
the loop will be performed.
Step value Indicates the number of units the index is incremented
(increased) or decremented (decreased) each time the computer
passes through the loop. Some computer systems use the word BY.
STEP will be used in the programs throughout this book.
5~ NEXT I
10
1=4 20 FOR 1=1 TO 3 STEP 1 ~~~
1= 1 1=2 1=3
30
40
1= 2
50 NEXT I
1= 3
60 \It 1= 4
110 10
120 LET K=l 20 FOR 1=1 TO 3 STEP 1
130 30
140 40
150 LET K=K+1 50 NEXT I
160 IF K ) 3 THEN 18B 60
170 GO TO 130
180
Line 20 in program (b) replaces lines 120 and 160 in program (a). The
index 1 is initially set at 1 (this replaces line 120) and the test value (3)
limits the number of times the loop is performed. (This replaces line
160.)
198 PROGRAMMING IN BASIC
2. The NEXT statement must always have a higher line number than
its corresponding FOR statement, and its variable must be the
same as the one that is used as the index in the FOR statement.
~20
30
Higher line 40
number >50 NEXT 1
== >
FOR 1=1 TO 3 STEP 1
Same variable
FOR/ NEXT LOOPS 199
20 FOR 1=1 TO 3
10 GO TO 30oE("--------lnvalid
20 FOR 1=1 TO 3 STEP 1
30
40
50 NEXT 1
Programs are given for rules 7, 8, and 9. RUN each one to see how
your computer system executes the FOR/NEXT loop . Does each
RUN produce a result, or do you get an error message? If you do
get a result, how many values of I are printed and what are the
values?
7. If the initial value and the test value are the same and the step
value is any number, most computer systems will execute the
loop once .
200 PROGRAMMING IN BASIC
8. If the test value is greater than the initial value and the step value
is zero or negative, the loop may be executed once, not at all , or
continuously.
9. If the test value is less than the initial value and the step value is
zero or positive, the loop may be executed once, not at all, or
continuously.
10. When looping is complete, the value of the index is greater than
the test value. On some computer systems, it remains at this
number; on others, the value of the index reverts to the test value
(or the closest number to it when the step value is not one). Here
is an example.
10
221 FOR 1=1 TO 3 STEP 1
FOR / NEXT LOOPS 201
30
40
50 NEXT I
60
11. On some systems, you may omit the variable after the key word
NEXT. However, this is not advisable, as it may confuse you (and
your computer) if there is more than one FOR/NEXT loop in the
program.
12. This is not really a rule - it's merely a suggestion. Some pro-
grammers highlight the statements within a FOR/ NEXT loop by
indenting them several spaces .
(a) Use a FOR/NEXT loop to keep track of the input (the four numbers).
(b) Use the READ/DATA statements to enter the numbers (one at a
time).
Sum of the Numbers
(c) Average = "Number" of Nu mbers
RUN
67 67
85 152
79 231
93 324
THE AVERAGE IS: 81
HI
211 READ II
3tJ
40 LET [1=II*.02
5£11
6l~ PRINT
70
80
9~
HH'I
lUI
999 END
RUN
ACCOUNT: 1
BALANCE: 450
DISCOUNT: 9
AMOUNT REMITTED: 441
ACCOUNT: 2
BALANCE: 600
DISCOUNT: 12
AMOUNT REHITTED: 588
ACCOUNT: 3
BAL.ANCE: 240
DISCOUNT: 4.8
AMOUNT REMITTED: 235.2
Problem II
Using the INPUT Statement Using the READ/DATA Statements
)
204 PROGRAMMING IN BASIC
,I nput Calculate
Commission
S
C=S*.10
'V 'V
Calcu'late Print
Commission Blank line
C=S*10 I
S
'V C
Print
'!i
C
~
NEXT I
'V 203
~
NEXT I
203 .
RUN RUN
EQUIPMENT: 2 EQUIPMENT: 2
SALES PRICE~ 1500 SALES PRICE: 1500
COMMISSION: 150 COMMISSION: 150
206 PROGR AMMING IN BASIC
EQUIPMENT: 3 EQUIPMENT: 3
SALES PRICE? 13~~ SALES PRICE: 13~~
COMMISSION: 130 COMMISSION: 130
U~ L.ET A= 1
20 LET B=10
30 FOR I=A TO B STEP 1
40 LET A=A+3
50 PRINT I,A
60 NEXT I
9,' END
HI LET A=1
20 LET B=10
30 FOR I=A TO B STEP 1
40 LET 8=8+2
50 PRINT 1,8
60 NEXT I
99 END
208 PROGRAMMING IN BASIC
II. On many computer systems, the initial value and the test value
may be negative, zero , or fractional (decimal values). Here are
some examples .
III. An expression may be used as the initial value and/or test value.
Any variable in the expression must be assigned a value prior to
its use in the FOR statement , and on many computer systems it
must be different than the index. The following FOR statements
have the same initial value and the same test value.
RUN
o o
1 1
2 4
3 9
4 16
--- - - --- -- - - - - - - - - - - - - - - - - - - - - " T " ' " " - -
10 PRINT
20 READ A,II
30 DATA 6,10
210 PROGRAMMING IN BASIC
10 PRINT
2~ FOR 1=1 TO 3
30 REArl A
40 DATA 7,8,9
50 LET B=A-IT2
60 PRINT I,A,B
70 NEXT I
99 END
HI PRINT
20 READ X,Y
30 I1ATA 16,2£1
4£1 FOR I=X TO Y STEP 1
50 LET J=I-1
60 LET 1<=1-2
7£1 PRINT I,J,K
8£1 NEXT I
99 ENII
10 PRINT
2£1 FOR 1=-6.5 TO -4.5 STEP 1
321 LET J=I*2
4£1 PRINT J
5£1 NEXT I
99 END
FOR/N EXT LOOPS 211
(a) Use a FOR/NEXT loop to keep track of the input (the three
articles) .
(b) Use variables to represent the initial value and the test value .
(c) Use the index to print the number of the article .
(d) Use the READ/DATA statements to enter the marked price of
each article .
(e) Amount Saved = Marked Price x .20
(f) Reduced Price = Marked Price - Amount Saved
(g) Total Bill = Total Bill + Reduced Price
RUN
ICLE 1
f-Iln MARKED PRICE 1ge
AMOUNT SAVED 38
REDUCED PRICE 152
Problem 5
T TOTAL BILL
I INDEX (NO . OFTHE ARTICLE) S AMOUNT SAVED
M MARKED PRICE R REDUCED PRICE
( Start
'V
)
T= el
A=1
8=3
,1/
[§J
212 PROGRAMMING IN BASIC
Calculate
Amount Saved
S= M*.20
Reduced Price
R=M-S
Calcuiate
Total Bill
T=T+R
Print
Blank line
I,M
S
R
NEXT I
RUN
1 7 6
2 8 4
3 9 e
FOR/ NEXT LOOPS 213
(b) RUN
16 15 14
17 16 15
18 17 16
19 18 17
2~ 19 18
(c) 11
4. Answers will vary depending on whether or not the decimal
numbers for the initial value and the test value are truncated.
(a) Decimal Numbers Not Truncated (b) Decimal Numbers Truncated to Next Smaller Integer
RUN RUN
-13 -14
-11 -12
-9 -H'J
5.
HI LET C=l
2~ FOR 1=1 TO 3 STEP C
10 LET C=4
2~ FOR 1=1 TO 3 STEP C/4
In this FOR statement, the initial value is greater than the test value.
The index is set to 6 , then decreases by 1 each time the computer
passes through the loop. When the value of the index is less than 3
(6 ,5,4 ,3,2), the value is less than the test value and looping ter-
minates. It should be mentioned that going backward from 6 to 3
results in the same number of executions as going forward from 3 to
6. The loop is performed four times in each case.
I takes on the values 1,3,5,7 ,9,11. The loop is not performed when
1= 11 , since 11 is greater than the test value. This means that the loop
is executed five times (when 1= 1 ,3,5,7,9) . The formula is used below
to determine the number of times the loop is performed .
(n2~3 n, )+ 1 = CO; 1) + 1 = (~ ) + 1 = 4+ 1 = 5
Notice that the division operation does not give an integer result
(9...;- 2= 4.5) . In a case such as this , the decimal portion is dropped (.5
of 4.5) and the integer part (4) is retained .
RUN
AMOUNT: 4E1E10
RATE: .12
INTEREST: 4811!
RATE: .13
INTEREST: 5211!
RATE: .14
INTEREST: 56E1
With each pass through the loop, the required interest rate is
obtained in line 45 by the division of 100 into the current value of
J.
The first time through the loop J= 12. R=J/100= 121100 = .12
The second time through the loop J= 13. = 13/100 = .1 3
The third time through the loop J= 14. = 14/ 100 = . 14
2. This program prints numbers in a decreasing sequence from 25
to 10 in steps of 5.
FOR/ NEXT LOOPS 217
1e PRINT
2~ FOR 1=25 TO 1~ STEP -5
RUN
20 15 10
RUN
252015 HI
2. What values will the index take on in each of the following FOR
statements? Do not include the value that terminates the loop.
1. Exercises that use decimal numbers in the FOR statement may be omitted if your
computer system truncates these numbers .
218 PROGRAMMING IN BASIC
HI PRINT
20 FOR 1= _____ TO _ _ _ _- STEP _ _ __
30
40 NEXT I
99 END
FWN
10 6 2 -2 -6
10 PRINT
221READ A,B
321DATA 221d0
421FOR I=A TO B STEP 2
521 PRINT I
621NEXT I
99 END
HI PRINT
221 LET A=4
321 FOR 1=2 TO 8 STEP 3
421 LET B=AtI
521 LET A=B*2
60 PRINT B,A
70 NEXT I
99 ENII
2. Use whole numbers in the FOR statements of your programs if your computer
system truncates the decimal values, then convert the index to the required decimal
numbers as shown on page 216.
FOR/ NE XT LOOPS 219
FWN
AMOUNT: 4000
HATE: .1
INTEREST: 400
RATE: .12
INTEREST: 480
RATE: .14
INTEREST: 560
f~ UN
3fl
28
:26
24
,"),.)
1 _. A..
2. (a) 1= 450,500,550,600
(b) 1=7,10,13
(c) 1= .5,1,1 .5,2,2.5,3
(d) 1=-8,-5,-2,1,4,7
(e) 1= 14 ,12,10,8 ,6,4 ,2,0
220 PROGRAMMING IN BASIC
3.
5.
F<UN
6 12
17 34
42 84
6.
01 REM A--AMOUNT
02 REM X--INITIAL VALUE
03 REM Y--TEST VALUE
04 F,EM Z--STEP VALUE
05 REM R--RATE (IN[lEX) Decimal numbers truncated
06 REM I--INTEREST in the FOR statement.
HI LET A=4000
20 REA[I X,Y,Z
30 [lATA .10, .14, .02 ---~-~) 30 [lATA U"14,2
40 PRINT
50 PRINT "AMOUNT:";A
60 FOR R=X TO Y STEP Z ~ 1 60 FOR J=X TO Y STEP Z
70 LET I=A*R 65 LET R=J/100
80 PRINT
90 PRINT "RATE:";R
11210 PRINT "INTEREST:";I
110 NEXT R ) 110 NEXT J
999 EN[I
Problem 6
( Start )
A=4000
~__
End_)
End
NEXT R NEXT J
7.
10 PRINT
20 FOR 1=30 TO 20 STEP -2
30 PRINT I
48 NEXT I
99 END
222 PROGRAMMING IN BASIC
10 FOR 1=1 TO 3 - - - - - - - - - - - - - - -
20 PRINT I
30 PRINT "I =";1 I
4111 FOR J::::l TO 4 - - - - - - - - - - - I
C 50
60
70
PRINT IJ ::::";J;
NEXT J
I
~
I
:
F'RIN1· ~--------------
80 NEXT I 1
99 ENII ~----------------~--
RUN
I -- 1
J .- 1 J = 2 J :::: 3 J = 4
I :::: 2
J :::: 1 J :::: 2 J = 3 J = 4
I = 3
.J :::: 1 J :::: 2 J :::: 3 J = 4
First, look at the RUN . Notice thatJ changes much more often than I.
While 1 is equal to 1, J changes four times (from 1 to 2 to 3 to 4). Once
J reaches 4, I changes to 2 and the four values of J are printed once
more. The same thing happens when 1 is equal to 3.
How does this work in the program? There are two FOR/ NEXT loops,
one inside the other. In computer terms they are nested. The slow-
moving loop (in this case , I) is on the outside ; the fast-moving loop (J)
is on the inside . The first time through the outer loop, 1 is initialized to
1 in line 10. While I remains at this value, J is initialized to 1 in line 40
and its loop (lines 40, 50, and 60) causes J to change from 1 to 4.
Once J has reached its limit, control is transferred to line 70 and the
computer proceeds to line 80 . Now it's I's turn to change. 1 is
increased to 2 and the computer goes back to line 10. While I is equal
to 2, J reverts to 1 (line 40) and goes through its cycle once more
(J= 1 ,2,3,4). Again, when J's limit is reached, control is transferred to
line 70 and the computer proceeds to line 80. I is increased to 3 and
control is transferred to the top of the 1 loop (line 10). J reverts to 1
(line 40) and goes through its loop for the third time. When J has
reached its limit, I is increased to 4 and the computer branches back
to line 10. This time, the value of I is greater than the test value and
control is transferred to the statement following NEXT I, which is the
END statement.
The program segments below are labelled to show you what
happens each time the computer goes through the I loop .
FOR/NEXT LOOPS 223
10 FOR 1=1 TO 3
20
30
40 FOR J=l~TO
4 1=2
(
Sf) -- I J = 1,2,3,4
60 NEXT..vJ
70
80 NEXT 1
99 END
10 FOR 1=1 TO 3
20
30
1'40 FOR J=l~TO
4 1=3
\. S0 -- I J = 1,2,3,4
60 NEXT..vJ
70
80 NEXT 1
9'1 END
The program on page 222 has two loops, one nested inside the
other. It is possible to have several levels of loops. There is usually a
limit to the number of levels, depending on the version of BASIC being
used. Check your manual to see how many levels your computer
allows .
224 PROGR AM MIN G IN BASIC
I
In addition to the rules for single loops , there are a number of
restrictions that must be observed when using nested loops.
I
~ ~
- - - - - - - - -- -- - -- - - -- - -- - - - - - - - - -----.-- -
10 FOR 1=1 TO 3
20 FOR J=l TO 4
70 NEXT J
8[1NEXT 1
99 END
Each time the outer loop is executed, the inner loop is performed
four times. Since the outer loop is executed three times, the inner
loop will be performed 3 x 4 = 12 times. Using the formula:
- n1 ) + 1 = (3-1
Outer loop: ( n2 n3 -1- ) + 1 = (2)
"1 + 1 = 2+ 1 = 3 )
3x4=12
n - n1 4-1 3
Inn e rio 0 p: ( 2 n 3 ) + 1 = (-1-) + 1 = ("1) + 1 = 3+ 1 = 4
HH'I LET T=T+5 - Calculates the total yearly salary of each employee.
to apply what you learned in Chapter Two about commas and sem-
icolons placed at the end of PRINT statements . Statements are
explained after the RUN.
10 PRINT
20 PRINT 1 1 2 3"
30 PRINT
4fJ FOR R=1 TO 3
50 PRINT R,
60 FOR C=l TO 3
70 LET P=R*C
80 PRINT P;
90 NEXT C
HI0 PRINT
110 NEXT R
999 END
RUN
123
1 123
2 246
3 369
HI PRINT
2~ FOR 1=2 TO 4
3~ FOR J=l TO 4
40 LET I\=I+J
50 PRINT to
6~ NEXT J
70 PR I NT - Counteracts the semicolon in PRINT K;
80 NEXT I
99 END
RUN
3 4 5 6
456 7
5 678
10 FOR 1=2 TO 4
20 f'R I NT - Leaves a blank line before each row.
30 FOR J=l TO 4
228 PROGRAMMING IN BASIC
RUN
3 4 5 6
4 5 6 7
"".J 6 7 8
01 REM R--RATE
02 REM T--TOTAL NO. OF PARTS
03 REM N--EMf'LOYEE NUMBER
04 REM D--DAY
£15 REM f'--PART S PROIIUCED PER DAY
£16 REM I--INCOME
10 LET R=2
2e
31:'1 LET T=0
40
~:j Ii) READ P
60
70
80
90
100 NEXT II
110
12~ PRINT
130
14e
1.5£1
160
999 END
RUN
-EMPLOYEE: 1
PARTS: 212
INCOME: 424
EMPL.OYEE: 2
PARTS: 213
INCOME: 426
EMPLOYEE: 3
F' Ar.:T S: 209
INCOME: 418
(a) FOR N= 1 TO 5
(b) FOR D=l TO 3
(c) FOR T=1 TO 5
(d) F()R D=l TO 5
(e) FOR N=1 TO 3
(a) GO TO 28
(~ IF N)3 THEN 28
(c) NEXT N
(d) NEXT, N
(e) NEXT Nt3
RUN
SALESPERSON: 1
COMMISSION 1 1400
COMMISSION 2 12130
COMMISSION 3 1300
TOTAL COMMISSION: 39139
SALESPERSON: 2
COMMISSION 1 16130
COMMISSION 2 15130
COMMISSION 3 1200
TOTAL COMMISSION: 43013
Start
End
\V N<=2
t§
232 PROGRAMMING IN BASIC
Calcu'late
Totall
Commission
T=T+C
NEXTM
Calculate
Commission NEXTN
C=S* .20
Print
M,C
-w
8
6.4 NESTED LOOPS-Solutions for "Your
Turn"
I.
6. 13~PRI NT "EMPLOYEE:"; N
14~PRINT "PARTS:";T
150 PRINT "INCOME:";I
7. (c) 1.60 NEXT N
II.
le FOR N=l TO 2
211 LET T=12I
3121 PRINT
4121 PRINT "SALESPERSON:";N
50 FOR M=1 TO 3
6121 READ S
7121 DATA 7121121121,6121121121,65121121
80 DATA 8121121121,75121121,6121121121
ge LET C=S*.2121
1121121 PRINT "COMMISSION";M,C
11121 LET T=T+C
12£1 NEXT M
13121 PRINT "TOTAL COMMISSION:";T
14121 NEXT N
999 END
Employee No. Hrs. Worked Rate Income Tax Oed. Union Dues Pension Oed.
1 44 10.24 80 2 3.00
2 37 11 .54 75 2 2.50
3 39 12.34 90 2 4 .00
(a) Use a FOR/ NE XT loop to keep track of the employees.
(b) Use the READ/DATA statements to enter the hours, rates, and
ded uctions .
(c) Remarks are placed in strategic spots to help you understand the
program.
234 PROGRAMMING IN BASIC
999 END
RUN
EMPLOYEE 1 HRS 44 RATE Hl.24
OVERTIME HOURS 5
OVERTIME RATE 15.36
OVERTIME PAY 76.8
GROSS PAY 476.16
INCOME TAX 8e
UNION [lUES 2
PENSION 3
TOTAL DEDUCTIONS 85
NFT PAY 391.16
EMPLOYEE 2 HRS 37 RATE 11.54
OVERTIME HOURS e
OVERTIME RATE e
OVERTIME PAY 121
GROSS PAY 426.98
INCOME TAX 75
UNION DUES 2
PENSION 2.5
TOTAL DEDUCTIONS 79.5
NET PAY 347.48
EMPLOYEE 3 HRS 39 RATE 12.34
OVERTIME HOURS 121
OVERTIME RATE 121
OVERTIME PAY 121
GROSS PAY 481.26
INCOME TAX 9f1
UNION [lUES 2
PENSION 4
236 PROGRA MM ING IN BASIC
TOTAL DEDUCTIONS 96
NET PAY 385.26
Wage Program
E INDE X (EMPLOYEE NUMBER) H1 - OVERTIME HOURS
H REGULAR HOURS R1 - OVERTI ME RATE
R REGULAR RATE V OVERTI ME
I INCOME TAX DEDUCTED G GROSS PAY
U UNION DUES D DE DUCTIONS
P PENSION FUND OED . N NET PAY
Start
Gross Pay-with
Overtime
H1 = H- 39
R1 = R*1 .5
End V= H1 *R1
G= 39*R+ V
Net Pay
D= I+U + P
N= G- D
Gross Pay - No
Overt ime
H1 = Q'J
R1 = Q'J
V=Q'J
G= H*R
NE XT E
FOR/ NE XT LOOPS 237
****************************************
H'J5 FOR E=l TO 3
805 NEXT E
****************************************
105 LET K=l
210 READ Nl
215 DAHl 3
8~~j LET K=Ktl
81~ IF K)Nl THEN 999
****************************************
815 GO TO 225
A SHORT SUMMARY
FO R/NEXT statements provide another method of controlling loops .
The general form of a FOR /NEXT loop is as follows .
Hl FOR I =
~
1 TO
t3 STEP 1
t
20
30
40 NEXT I
5~
The initial value, test value, and step value may also be written as
variables or expressions. They may be positive , negative , fractional ,
and, except for the step value, may also be zero . However, some
computers truncate a decimal value in the FOR statement. If the STEP
clause is omitted , the increment is assumed to be one . The test value
should be less than the initial value when the step value is negative .
Although the index can be used inside a loop, some versions of BAS IC
do not allow its value to be altered within the loop . The same rule may
apply to the initial , test, and step values. Control can be transferred
from a point within the loop to a statement outside. However, the
238 PROGRAMMIN G IN BASIC
\ ~
i-'"
3. Questions and exercises that use decimal numbers in the FOR statement may be
omitted if your computer system truncates these numbers.
FOR/NEXT LOOPS 239
130 NEXT I
140
(c) UI FOR 1=3 TO 12 STEP 3 ( f) 10 FOR 1=.02 TO .08 STEP .02
20 FOR J=S TO 20 STEP S 20 FOR J=.01 TO .04 STEP .01
50 NEXT J 60 IF J<=.04 THEN 20
60 FOR K=l TO 6 70 NEXT I
90 NEXT K
100 NEXT 1
-- - -
11 . What values will the index take on in each of the following FOR
statements? Do not include the value that terminates the loop.
(a) U-, FOR A=3 TO 13 STEP 2 (d) HI FOR D=10 TO -20 STEP -5
60 NEXT A 60 NEXT D
(b) HI FOR B=15 TO 29 STEP 3 (e) 10 FOR E=-21 TO 9 STEP 6
60 NEXT II 60 NEXT E
(c) 10 FOR C=32 TO 16 STEP -4 (f) 10 FOR F=.2 TO .9 STEP .2
60 NEXT C 60 NEXT F
(a) 10 PRINT
20 FOR 1= TO STEP
30 PRINT I;
40 NEXT I
99 END
RUN
1 ')"-. 17 22 27
(b) 10 PRINT
20 FOR J= TO STEP
30 PRINT J;
40 NEXT J
99 END
RUN
6 3 0 -3
(c) 10 PRINT
20 FOR K= TO STEP
30 PRINT K;
40 NEXT K
99 END
RUN
13. How many times is the inner loop executed in the following
program segment?
60 NEXT J
70 NEXT I
(b) Ie PRINT
221 LET N=12
30 FOR I=N TO 1 STEP -1
40 FOR J=l TO I STEP 1
50 PRINT 0*0 ;
60 NEXT J
70 PRINT
80 NEXT I
99 END
Programming Problems 4
1. Write a program that converts weekly wages of $350 , $400,
$450 , and $500 to hourly rates based on a 40-hour week .
(a) Use a FOR/ NEXT loop to generate the weekly wages .
(b) Hourly Rate = Weekly w:%es (Index)
RUN
WEEKLY WAGES: 350
HOURLY RATE: 8.75
4. If your computer system truncates the dec ima l val ue s in the FOR statement, use
whole numbe rs then convert the index to the required decimal numbers as shown on
page 216.
FOR/NEXT LOOPS 243
Problem 1
W WEEKLY WAGES (INDEX)
H - HOURLY RATE
Start
W>500 ( _______
End -=--)
Calculate
Hourly Rate
H=W/40
NEXTW
RUN
SALES: HHH10
COMMISSION: 2000
RATE OF COMMISSION: .2
COMMISSION: 2200
RATE OF COMMISSION: .22
COMMISSION: 2400
RATE OF COMMISSION: .24
3. Suppose your yearly salary is $19 000 and that at the end of
every year your salary will be increased by $1 000. What will your
salary be after the sixth increase?
(a) Use the LET statement to enter the initial salary .
(b) Use a FOR/ NE XT loop to keep track of the increases .
(c) Salary = Salary + 1000
RUN
4 . To each of the numbers 3,4, and 5, add the numbers 1, 2,3, and
4.
(a) Use an outer FOR/NE XT loop to generate the numbers 3 , 4,
and 5.
(b) Use an inner FOR/ NE XT loop to generate the numbers 1, 2, 3 ,
and 4.
(c) Add the indexes of the two FOR statements and store the
result in another variable .
RUN
456 7
5 6 7 8
678 9
FOR/NEXT LOOPS 245
5 . Find the total sales for each of the three stores shown below .
RUN
STORE: 1
TOTAL SALES: 82ee
STORE: 2
TOTAL SALES: 8See
STORE: 3
TOTAL SALES: 7900
RUN
QUOTED PRICE: 4eBB
RATE: .04
DISCOUNT: 160
NET PRICE: 3840
246 PR OG RAMM ING IN BAS IC
RATE: .B6
DISCOUNT: 248
NET PRICE: 3768
RATE: .08
DISCOUNT: 320
NET PRICE: 3680
Problem 6
Q QUOTED PRICE D DISCOUNT
R - RATE OF DISCOUNT (INDEX) N NET PRICE
End End
\V J<=8
Calculate Calculate
Discount Rate
D=Q*R R= J/1 00
Net Price
N=Q-D I
I
Print
I
Blank line
I
R I
D
I
N I
I
NEXT R NEXT J
FOR/NE XT LOOPS 247
RUN
Problem 7
Q QUOTED PRICE (OUTER INDEX)
R DISCOUNT RATE (INNER INDEX)
D DISCOUNT
Start
B
248
End
248 PROGRAMMING IN BASIC
A
247 Decimal numbers truncated
in the FOR statement.
R>.OB
R<= .OB
Calculate Calculate
Discount Rate
D=O*R R= J/ 100
I
I
I
I
\lI
NEXTR NEXT J
NEXTO NEXT 0
B. Interest is often added to its principal. Suppose the next time the
interest is calculated it is based on the new (increased) principal
so that one is actually getting interest on interest. Interest worked
out this way is called compound interest, and the final principal
is known as the compound amount. There is a formula that can
be used to find the compound amount which greatly reduces the
work involved.
Compound Amount = Principal (1 + Rate of Interest)PeriOd of Time
Using an initial principal of $1000, find the compound amounts at
the end of 4 years at interest rates of 13%, 14%, and 15%.
(a) Use a FOR/NEXT loop to generate the interest rates.
(b) Compound Amount = 1000 (1 + R)4
(c) Notice that the output is not rounded off to the nearest cent.
Rounding off numbers will be discussed in later chapters
RUN
RUN
Problem 9
Y YEAR NO . (OUTER INDEX)
R - INTEREST RATE (INNER INDEX) C - COMPOUND AMOUNT
250 PROGRAMMING IN BASIC
'V Y<= 4
Print
Y Decimal numbers truncated
in the FOR statement.
NEXT R NEXT J
NEXTY NEXTY
ONE-DIMENSIONAL ARRAYS 251
S VEN ONE-DIMENSIONAL
ARRAYS
A. After completing this chapter, you should be able to write BASIC
programs and complete skeletal BASIC programs that:
1. Store data in one-dimensional arrays .
2. Print information from one-dimensional arrays
3. Perform calculations on data stored in one-dimensional
arrays .
4. Combine the above operations in a variety of ways within
FOR/ NE XT loops .
B. In addition , you should be able to :
1. Define
(a) A one-dimensional array.
(b) A subscripted variable.
2. Differentiate between a simple numeric variable and a sub-
scripted numeric variable.
3. Display and name the different parts of the DIM statement.
4. State the purpose of the DIM statement and the restrictions
imposed upon the DIM statement.
5 . Write program segments that:
(a) Print specific elements of an array.
(b) Perform calculations on specific elements of an array .
6. List data items various ways in DATA statements to produce
the same output.
7. State what is stored in each element of an array.
8. Find errors in programs.
9. Produce the output of programs.
wise to check your manual. ) You should understand that P(3) is not
the same as P3. The former is a subscripted numeric variable; the
latter is a simple numeric variable .
How is a number assigned to each location in the array ? It is usually
done by using a FO R/ NEXT loop. Suppose that you want to store, in
array P, the number of people living in each apartment. Shown below
is the information you will need .
Apartment Number Number of People
1 4
2 3
3 1
4 2
You can use either an INPUT statement or the RE A DIDATA statements
to enter the data. The following program uses the READ/ DAT A state-
ments .
HI DIM f'(4)
2fl FOR 1=1 TO 4
3fl READ f' ( I )
40 DATA 4,3,1,2
sa NEXT I
99 END
Here is the way each data item (the number of people living in each
apartment) is entered into the computer as an element of array P.
The first time through the loop I = 1 . In line 30 , P(I) is actuall y P(1) . The
number 4 is stored in P(1).
The second time through the loop 1=2. P(I) is actually P(2). The
number 3 is stored in P(2) .
The third time through the loop I = 3. P(I) is now P(3) . The number 1 is
stored in P(3) .
The fourth time through the loop 1= 4. P(I) is now P(4) . The number 2
is stored in P(4) .
Did you notice that no data item was destroyed as the numbers were
being stored? This is because each location has a unique
address-P(1) , P(2) , P(3) , P(4)-which , in effect , is the same as
four different variables . However, this time the computer , not the
programmer, named the variables by attaching a number to the array
name to identify a specific storage location. This was done each time
the computer passed through the loop. What you must remember is
that anytime you reference an item in the array, the number of the
storage location must be used along with the array name . In other
words , you must use a subscripted variable, such as P(3) . A simple
variable , that is , one without a subscript, may not be used with arrays.
Here is a precautionary note . Try not to have the variable that
represents an array name the same as the variable that represents
the index of a FO R statement . Not only may it confuse a reader of your
program, it may also confuse your computer .
10 [11M 1(4)
20 FOR 1=1 TO 4
30 REA[I I ( I) -Array name and' index the same.
40 [lATA -,-'" I
50 NEXT I
Refer to the first statement in the program that stored the number of
people living in each apartment.
10 DIM P(4)~ Number of storage
i t t locations to be
Statement Key word that in- Name of reserved.
number structs the com- the array
puter to reserve
storage locations
What is the purpose of this statement? The computer must know in
advance the maximum number of storage locations needed to store
all the data . The DIMENSION statement (usually abbreviated to DIM)
performs this function . It consists of a statement number ; the key
word DIM; the name of the array ; and , in parentheses, the number of
ONE-DIMENSIONAL ARRAYS 255
10 DIM P(4),RC20)
II. This prog ram uses the INPUT statement to enter the data into
array A.
(a) READ/DATA statements are used to enter the quantity and the
unit price of each item. The information is stored in two
arrays. Array 0 stores the quantities ; array U stores the unit
prices.
1. The first program uses two FOR/ NEXT loops and two DATA
statements.
2. The second program uses two FOR/NEXT loops and one
DATA statement.
3. The third program uses one FOR/NE XT loop and one DATA
statement.
First Loop Stores the Quantities Second Loop Stores the Unit Prices
Q(1)
Q(2) ~
4
U(1)
U(2)
4.50
3.00
Q(3) 5 U(3) 2.25
Q(4) 3 U(4) 5 .15
Data does not necessarily have to be listed in two DATA statements.
One DATA statement may be used. On some computer systems , the
statement may be placed anywhere in the program .2 The program
might look like this :
HI DIM Q(4),U(4)
999 END
Note that the first four values in the DATA statement are stored in array
0 ; the next four values are stored in array U.
2 . Some systems insist that the DIM statement be the first state ment in the program;
some insist that the END statement be the last statement in the program Thu s, on
these computers, care must be taken in the placement of the DATA statement.
258 PROGRAMMING IN BASIC
10 [11M (H4),U(4)
999 END
In this program, data is stored in pairs (See Chapter Five , " Sets of
Data Read in a Loop," page 161.) This is an example of how sub-
scripted variables act like ordinary variables -they're Just named
differently. Instead of using variables P and F as you did in Chapter
Five , the subscripted variables 0(1) and U(I) are used. Below is an
explanation of how the numbers are assigned to the subscripted
variables in pairs .
0(1)
0(2) ~52 U(1)
U(2)
4.50
3.00
0(3) U(3) 2 .25
The fourth time through the loop 1=4
3 is assigned to 0(4) 110 READ 0(4),U(4)
5.15 is assigned to U(4) 120 DATA 2,4 .50,4,3.00 ,5,225Q]JID
120 DATA
i
2 ,
i
4.5~? -, -, ••••
The DATA statement in Program 2, which uses two loops, lists the
quantities first, then the unit prices. This is because the storing of
quantities is completed before the storing of unit prices begins .
Something else that should be noted: When there is one loop, as in
Program 3, the number of elements in both arrays is the same, since
the subscript of each array (the 1 in 0(1) and U(I») is the index of the
FOR statement FOR 1= 1 TO 4 . The test value indicates the number of
elements in the arrays. When there are two loops, as in Programs 1
and 2, the indexes may differ and so may the test values . As a result,
the number of elements in array Q may be different than the number
of elements in array U.
99 END
99 END
(c) 10 DIM 45
2£1 FOR J=l TO 45
30 REAII A(J)
40 IIATA -,-,-, ••••• (45 data i tenls)
50 NEXT J
99 END
260 PROGRAMMING IN BASIC
99 ENIt
Array A Array B
3 9
6 18
9 27
12 36
15 45
10 ItIM A(5),B(5)
20 FOR K=1 TO 5
30 REAIt A(K),B(K)
40 DATA 3,6,9,12,15,9,18,27,36,45
50 NEXT K
99 ENIt
(f) In the program segment shown below, the data items are to
be stored as follows.
Array C Array 0
2 12
4 14
6 16
8 18
10 20
10 DIM C(5),[I(5)
20 FOR 1=1 TO 5
30 READ C(I)
40 NEXT I
50 FOR J=1 TO 5
60 READ D(J)
70 NEXT J
8~ DATA 2,4,6,8,10,12,14,16,18,20
999 END
Array A Array 8
I~ I I~~ I
A(1 ) 8(1 )
A(2) 8(2)
A(3) 8(3) 30
99 END
99 END
99 END
Problem 3
Using Two FOR /NEXT Loops Using One FOR /NEXT Loop
Y - YEARS Y - YEARS
R - RATE R - RATE
( Start
'V
)
DIM DIM
Y,R Y,R
End
NEXT I NEXT I
End
NEXT J
ONE-DIMENSIONAL ARRAYS 263
HI [I I M A( un or
20 FOR 1=1 TO 5
(b) In line 30, the index and the name of the array are inter-
changed. The index should be the subscript of the array
name.
30 READ BOO
(c) The DIM statement must include the name of the array. Also,
the number 45 must be enclosed in parentheses and must
follow the name of the array.
10 DIM A(45)
30 READ A(K),B(K)
40 [lATA 3,9,6,18,9,27,12,36,15,45
array
1'iii
A BA B
iA tB
(f) Nothing is wrong .
2. (a)
Array A
A(1) 11
~~~~ ~~
A(4) 44
A(5) 55
264 PROGRAMMING IN BASIC
(b)
Array M Array N
M(1) ~1 N(1) ~2
M(2) 33 N(2) 44
M(3) 55 N(3) 66
(c)
Array M Array N Variable C
M(1) [J]J N(1) I33l C 1'5Q.1 (replaced by 66)
M(2) LEJ N(2) [}!] C 66
Notice that the value 55, entered in the simple variable C, is
lost, since it is replaced by the number 66. The other values
are retained as each is stored in its own subscripted variable.
(b) The data must be listed in pairs, so that the first item of each
pair is assigned to an element of array Y and the second item
of each pair is assigned to an element of array R.
Hl [11M F' ( 4 )
2f1 FOR 1=1 TO 4
3~ READ F' ( 1)
40 DATA 4,3,1,2
50 NEXl I
99 END
The following examples will show you how information can be printed
from this array. Suppose you want the computer to print the number
of people living in your apartment (apartment 3) . You simply ask the
computer to print the contents of P(3).
50 PRINT P(3)
99 ENII
RUN
99 END
RUN
How would you code the PRINT statement if you wanted the com-
puter to print the contents of the first and the fourth storage locations
on the same line widely spaced?
50 PRINT F'(1),P(4)
266 PROGRAMMING IN BASIC
99 ENB
RUN
4 2
What would the PRINT statement and the RUN look like if you wanted
the contents of all the storage locations printed on the same line
closely spaced?
5~ PRINT P(1);P(2);P(3);P(4)
99 END
RUN
431
This isn't too onerous if you have only a few numbers in the array.
It's just the same as printing the contents of four simple numeric
variables, such as A, B, C, and D. But what would you do if the array
contained 100 items and you wanted the computer to print them all?
As in the storage of data items in an array, the FOR/NEXT loop can be
used to make the computer look after the job of referencing each
storage location. Here is a program segment that prints the number of
people living in each apartment of the Parkview Apartments.
Although it is written to print four items, it can just as easily print more
or less. Simply change the subscript in the DIM statement, the test
value in the FOR statement, and the number of data items in the DATA
statement.
HI DIM P(4)
40 FOR 1=1 TO 4
50 PRINT F' (I H
61!'1 NEXT I
99 END
RUN
4 3 1 ...
")
ONE-D IMENS IONAL ARR AYS 267
Notice the semicolon at the end of the PRINT statement. This causes
the items to be printed on the same line closely spaced .
In the above examples, it was assumed that the data items had
been stored by previous statements. The programs below show how
the operations of storing and printing are combined in one program.
One or two FOR/NEXT loops can be used . The first program uses two
loops. It stores the data items in the firs t loop and prints them in the
second loop . The second program does both in one loop .
1. Using two FOR/NEXT loops
HI DIM P(4)
RUN
431 2
Note that a different index is used for printing the items . If there are
two loops in a program , it is better to use different indexes. Notice as
well that the numeric subscripts of array P are the same in both loops,
regardless of whether I or J is used , since the range of both indexes is
the same . In the first loop, the values are stored in P(1), P(2) , P(3) ,
and P(4) because I ranges from 1 to 4. In the second loop , the values
are referenced by the same subscripts because J also ranges from 1
to 4. One more thing. Note that the array is DIMENs Io Ned only once-
at the beginning of the program.
An easier and more efficient way to write th is program is to use just
one FOR/NEXT loop .
6~ PRINT F' ( I ) r
7~ NEXT I
99 END
FWN
4 3 1 ...
")
10 [tIM P(4)
99 END
RUN
2 1 3 4
10 [JIM O(4),U(4)
60 FOR J==l TO 4
70 PRINT Q(J),U(J)
80 NEXT J
99 END
RUN
- Blank line before the results.
,..,
.:.. 4 • c..J·
4 3
5 2.25
3 5.15
50 FOR 1=1 TO 4
6111 PRINT ~<------------Placed inside the loop but before a block
of PRINT statements.
70 PRINT "QUANTITV:"iQ(I)
80 PRINT 'UNIT PRICE:";U(I)
90 PRINT "EXTENDED COST:";C(I)
HJ0 NEXT I
999 END
RUN
QUANTITY: 2
UNIT PRICE: 4.5
EXTENDED COST: 9
./
QUANTITY: 1\
UN I T F'R ICE: 3 1 - - - Blank line before each block of results.
EXTENDED COST: 12
L..
QUANTITY: 5
UNIT PRICE: 2.25
EXTENDED COST: 11.25 .",
QUANTITY: 3
UNIT F'RICE: 5.15
EXTENDED COST: 15.45
RUN
25 50 75 HH:J
II. This program uses the INPUT statement to enter the data into
array A. It uses a separate loop to print the data so that the output
is apart from the prompts .
RUN
VALUE FOR A(I)? 25
VALUE FOR A(I)? 5111
VALUE FOR A( I )? 75
VALUE FOR A(I)? 1138
25 58 75 1111~
III. Here is the second stage of the program that was started in
Section 7.1, page 256.
ONE-DIMENSI O NA L ARR AYS 271
RUN
2 4.5
4 3
5 2.25
3 5.15
The data is stored in the first loop . After this operation is complete, the
data is printed in the second loop .
10 DIM Q(4),U(4)
20 PRINT
272 PROGRAMMING IN BASIC
3B FOR 1=1 TO 4
4B READ Q(I),U(I)
5B DATA 2,4.50,4,3.00,5,2.25,3,5.15
60 PRINT Q(I),U(I)
7B NEXT I
99 END
RUN
')
.:.. 4.5
4 3
5 2.25
3 5.15
In line 40 , two data items are read. The y are then printed before the
next two items are read and printed . The operations of REA D and PRINT
alternate within the one loop .
RUN
2 4 6 8
(d) Do the same as in question (c) , but this time print the items
backwards .
RUN
8 6 4 2
(e) Write a program segment that prints the first four elements of
array A and the first four elements of array B, using one
FO R/NEXT loop .
ONE-DIMENSIONAL A RR AYS 273
RUN
...'"> 4
4 16
6 36
8 64
(a) Use the REA D statement with one DATA statement to store the
above information in two arrays.
(b) Use one FO R/NE XT loop to read and print the above informa-
tion .
274 PROG RAM MING IN BASIC
RUN
Problem 3
Y - YEARS
R - RATE
C~Start)
W
Next I
999 END
(d)
6111 FOR 1=4 TO 1 STEP -- 1
70 PRINT A ( I ) ,
B0 NEXT I
999 END
(e)
60 FOR 1=1 TO 4
70 PRINT A(I),B(l)
S0 NEXT I
999 END
60 PRINT A(I)
RUN
1 1f!
2 20
3 30
(c) There is insufficient data for the array A. Since the test value
in the FOR statement is 4 and the data pattern for A is 1,2 ,3 , it
appears that A should have one more value and that this
value should be 4. This means that the DIM statement and the
DATA statement should be changed .
10 [IIH A(4),[t(4)
50 DATA 1,15,2,46,3,23,4,58
276 PROGRAMMING IN BASIC
3.
1~ DIM Y(3),R(3)
20 PRINT
30 FOR 1=1 TO 3
40 READ Y(I),R(I)
S£) DATA U~,.12d5,.13,~J0,.15
60 PRINT "YEARS:';Y(I),"RATE:";R(I)
70 NEXT I
99 END
S0 LET T=P(1)tP(2)
6f) P'RINT T
99 END
RUN
S0 LET T=P(1)tP(2)
= 4+ 3
= 7
5~ LET T=P(1)+P(2)+P(3)+P(4)
60 PRINT 1
99 END
RUN
HI
III. The previous statement is relatively simple if there are only a few
elements to add. But what if there are 100 elements? The task
becomes quite onerous. In the examples shown below,
FOR/NEXT loops are used to find the total number of people living
in the Parkview Apartments. As mentioned in the previous
section, the programs can just as easily manipulate 100 ele-
ments of an array. Simply change the subscript in the DIM
statement, the test value in the FOR statement, and increase the
number of data items. Here are two versions of the same pro-
gram.
1. This version stores and prints the data in one loop, then
calculates and prints the total in a separate loop.
HI DIM P(4)
20 LET T=:kJ
999 END
RUN
'")
4 3 1 .:..
4
7
8
10
278 PROGRAMMING IN BASIC
RUN
4 3 1 2
10
ONE-DIMENSIONAL ARRAYS 279
UI DIM F'(4)
2'-'1 PRINT
321 LET T::::~
421 FOR 1=1 TO 4
50 READ F'(I)
621 DATA 4,3,1,2
721 PRINT P(I),
80 LET T=TtP(I)
921 NEXT I
12121 PRINT T -Placed outside the loop.
999 END
RUN
4 3 1 2
10
RUN
4 4
3 7
1 8
...
'1
Hl
IV. Let us now assume that the four people who live in Apartment 1
move out and that the family moving in has six members. Here is
the statement that makes this change.
80 LET F'(1)=6
80 LET P(4)=3
80 LET P(4)=P(2)
8~ LET P(2)=P(2)tl
40 LET P(U=0
50 LET P(2)=0
60 LET P(3)=~
70 LET P(4)=0
ONE-DIMENSIONAL ARRAYS 281
40 FOR 1=1 TO 4
50 LET P(l)=0
60 NEXT I
10 DIM Q(4),U(4)
RUN
2
4
4
3
...,
c'
~Thedata
5 2.25
3 5. 15
9
1 .:..';
~------The
( extended cost of each item
11. 25
15.45
999 ENII
RUN
2 4.5
4 3
5 2.25
3 5.15
ONE-DIMENSIONAL ARRAYS 283
9 12 11. 25 15.45
The DIM statement sets aside four storage locations for array
C in which the results are stored. Here is how line 160 is
executed.
10 DIM O(4),U(4),C(4)
20 PRINT
30 FOR 1=1 TO 4
40 READ (HI),U(I)
50 DATA 2,4.5~,4,3.00,S,2.25,3,5.15
68 LET C(I)=Q(I)*U(I)
284 PROGRAMMING IN BASIC
70 PRINT Q(I),U(I),C(I)
80 NEXT I
99 END
RUN
2 4.5 9
4 3 12
5 2.25 11. 25
3 5.15 15.45
10 DIM Q(4),U(4),C(4)
20 FOR 1=1 TO 4
30 READ Q(I),U(I)
40 DATA 2,4.50,4,3.00,5,2.25,3,5.15
50 LET C(I)=Q(I)*U(I)
60 PRINT
70 PRINT "QUANTITY";Q(I)
80 PRINT "UNIT PRICE";U(I)
90 PRINT "EXTENDED COST OF ITEM";C(I)
10B NEXT I
999 END
RUN
ONE-DIMENSIONAL ARRAYS 285
QUANTITY 2
UNIT PRICE 4.5
EXTENDED COST OF ITEM 9
QUANTITY 4
UNIT PRICE 3
EXTENDED COST OF ITEM 12
OUANTITY ~j
UNIT PRICE 2.25
EXTENDED COST OF ITEM 11.25
QUANTITY 3
UNIT PRICE 5.15
EXTENDED COST OF ITEM 15.45
Problem I
Y YEARS I - INTEREST
R - RATE A - AMOUNT OF INVESTMENT
( Start
'V
) o J<=3
DIM
Y,R,I
'V
Calculate
A=4000 Interest
I(J)= A*R(J)
Print
Blank line
Y(J)
R(J)
I(J)
____
E_nd____
) ~~ __N_E_:_T_J__ ~
286 PROGRAMMING IN BASIC
(a) Use two arrays to store the data (years and rates).
(b) Store each calculated interest in a third array.
(c) Use one FOR/NEXT loop to read, calculate, and print.
(d) Interest = Amount Invested x Rate of Interest
(e) Fill in the missing lines.
01 F'~EM Y---YEARS
02 REM R--RATE
03 REM I---INTEREST
~4 REM A--AMOLJNT OF INVESTMENT
10 DIM Y(3),R(3),I(3)
20 LET A=4e~H!J
30 PRINT
40
S0 FOR J:::1 TO 3
60
7B
El0
90 PRINT
1I~~
1 Hl
120
13121
999 END
RUN
AMOUNT! 4000
YEARS! H'l
RATE: .1.2
INTEREST! 4B0
ONE-DIMENSIONAL ARR AY S 287
YEAF::~: 15
RATE: • L~
INTEREST: 52111
YEARS: 2~
RATE: .15
INTEREST: ,~,r,H)
(a) READ Y ( I ) , F: ( I )
(b) READ I(J),Y(J)
(c) READ I<J) ,R(J)
(d) READ I ( I ) y ' ( ( I )
(e) READ Y(J) IRL)
(a) Use two array s - one for the rates of discount and the other
to store the amounts of discount as they are being calcu-
lated.
(b) Use a LET statement to enter the balance of the account.
(c) Use the READIDATAstatements to enter the rates of discount.
(d) Read , calculate, and print in one FOR/NE XT loop .
(e) Discount = Rate of Discount x Account Balance.
- - - - - - - - - - - - - - - --.------.
RUN
III. Rewrite the above program. This time use the INPUT statement to
enter the rates. 3
RUN
1. 40 PRINT "AMOUNT:";A
2. (e) 60 READ Y(J),R(J)
3.70 DATA 10,.12,15,.13,2e,.15
4. (b) S0 LET I<J)=A*R(J)
5. 100 PRINT "YEARS:";Y(J)
3. You may omit this problem if you are not using an interactive computer system.
ONE-DIMENSIONAL ARRAYS 289
999 END
RUN
l.
3
4
5
6
ONE - DIMEN SIONA L ARRAYS 291
Sorting Program
A ARRAY THAT STORES THE NUMBERS
T - TEMPORARY STORAGE OF A NUMBER
DIM
A
K=1 TO 6
~
~ End
)
NEXT I
Interchange
Numbers NEXT K
T=A(J)
A(J)= A(J+ 1)
A(J+1)=T
NEXT J
NEXT L
r
292 PROGRAMMING IN BASIC
I. The first time through the loop J=1. A(J) is actually A(1) and
A(J+1) is actually A(2) . Line 230 is false since 4 is not less than
2. Therefore, 4 and 2 must be interchanged.
1. Place the 4in temporary storage. LETT=A(1)
I61!2 A(2)
442
t I
2. Place the 2 in location A(1). LET A(1)=A(2)
I61!2 A(2)
422
t I
3. Place the 4 in location A(2). LET A(2)= T
IA(1) A(2)
424
I t
The 4 and 2 are interchanged and the order is now:
t t
241 563
II. The second time through the loop J=2. A(J) is actually A(2) and
A(J+1) is actually A(3). Line 230 is false, since 4 is not less
than 1. Therefore, 4 and 1 must be interchanged.
1. Place the 4 in temporary storage. LET T = A(2)
T A(2) A(3)
4 4 1
t I
2. Place the 1 in location A(2). LET A(2) = A(3)
T A(2) A(3)
4 1 1
t I
3. Place the 4 in location A(3). LET A(3)=T
T A(2) A(3)
4 1 4
I t
The 4 and 1 are interchanged and the order is now:
~ t
2 1 456 3
III. The third time through the loop J=3. A(J) is actually A(3) and
A(J+1) is actually A(4). Line 230 is true, since 4 is less than 5.
Therefore, no interchange is made and control is transferred
ONE-DIMEN SION A L A RRAYS 293
T A(5) A(6)
6 3 3
t I
3 . Place the 6 in location A(6) . LET A(6) =T
T A(5) A(6)
6 3 6
I t
The 6 and 3 are interchanged and the order is now
t t
2 1 4 5 3 6.
The J loop is complete and control enters the L loop . The value of
L becomes 2 and the J cycle is repeated . The Land J loops
continue until the value of L is greater than 6 . At this point,
looping terminates . The numbers are now sorted in ascending
order: 1 2 3 4 5 6 .
A SHORT SUMMARY
In many applications of programming , the computer must retain all
the data that is used in the program. One example is in the sorting of
names or numbers; all must be in memory in order to compare one
with another to see which one comes first. Some business applica-
tions use the same data items several times in a program . This makes
it essential that the items be stored in their own locations so that no
values are lost when new ones are entered . Although simple vari-
ables may perform the same functions , what makes subscripted
variables so convenient is the fact that the computer, not the pro-
grammer, sets up explicit storage locations to store all the data . These
locations are adjacent to one another in a block of storage called an
array, to which the programmer assigns a name . In order to give every
location a different address, the programmer tells the computer to
assign a number to each location along with the name of the array.
Thus , each address is unique , since the number assigned to it is
different from any other. An example of a subscripted variable is P(3) .
294 PROGRAMMING IN BASIC
The P is the name of the array; the 3 is the subscript. This particular
variable represents the third storage location in array P.
Usually, a subscript is assigned to each location of an array by the
use of a FOR/NEXT loop as the data items are being stored. The
operations of storing, printing, and calculating may be combined in
various ways.
01 REM L--LARGE
02 REM S--SALE
UI LET L=-l
20 PRINT
30 FOR 1=1 TO 5
40 READ S
50 DATA 8700,6300,94e0,76~0,8500
60 PRINT "SALE:";S
70 IS S)L THEN 90
80 GO TO 100
90 LET L=S
100 NEXT I
110 PRINT
120 PRINT "THE LARGEST SALE IS:";L
999 END
RUN
SALE: 8700
ONE-DIMENSIONAL ARRAYS 295
SALE: 6:HH!I
SALE: 94~HJ
SALE: 7600
SALE: 8500
01 REM S--SALE
02 REM L--LAF~GE
10 DIM S(5)
20 LET L=-l
30 PRINT
40 FOR 1=1 TO 5
50 READ S(I)
60 DATA 8700,6300,9400,7600,8500
70 PRINT "SALE:";S(I)
80 IF S(I»L THEN 100
90 GO TO 110
100 LET L=S(l)
110 NEXT I
120 PRINT
130 PRINT "THE LARGEST SALE IS:";L
999 END
RUN
SALE: 8700
SALE: 6300
SALE: 9400
SALE: 7600
SALE: 8500
similar the two programs are). This means that data stored in sub-
scripted variables may be printed after all the items are entered
One final comment. The computer must know in advance the
maximum number of storage locations needed, particularly (in most
versions of BASIC) when the number of elements in the array is more
than 10 or 11. The statement that instructs the computer to reserve a
specific number of storage locations is the DIM (DIMENSION) state-
ment.
Array A Array 8
4 16
7 49
2 4
(a) Use two FOR/ NEXT loops and two DATA statements in one
program.
(b) Use one FOR/NEXT loop and one DATA statement in the other
program.
(c) In the program that uses one loop, explain how the data
items must be listed in the DATA statement.
8. Write program segments that print the following elements of
array A which consists of ten elements.
(a) The first element.
(b) The first and tenth elements on the same line widely spaced.
(c) All ten elements. Use a FOR/ NEXT loop. Output is to be printed
on one line closely spaced.
(d) Repeat (c), but have the program print the elements back-
wards, that is, from last to first.
9. (a) Explain the difference in execution between the following
two programs.
(b) Show the output of each.
ONE-DIMENSIONAL ARRAYS 297
I.
UI I1IM A(4)
20 FOR 1::1 TO 4
30 READ A(I)
4~ DATA 3,6,9,12
5~ NEXT I
60 PRINT
70 FOR J=l TO 4
80 PRINT A(J);
90 NEXT J
99 ENII
II.
10 DIM A(4)
20 PRINT
30 FOR 1=1 TO 4
40 READ A(I)
50 DATA 3,6,9,12
60 PRINT A(I);
70 NEXT I
99 END
(a)
10 I1IM C(4)
20 LET 1" :-·0
100 PRINT
11111 FOR J=l TO 4
120 LET T=TtC(J)
13111 PRINT T;
14111 NEXT J
999 END
(b)
10 DIM C(4)
20 LET T=0
11110 PRINT
298 PROGRAMMING IN BAS IC
1 HI FOR J= 1 TO 4
120 LET T~T+C(J)
130 NEXT .J
140 PRINT T
999 END
13. Identify the errors, if any, in the program segments shown below.
Assume that the required number of items are listed in the DATA
statement. Make the necessary corrections.
999 END
300 PR OGRAMMING IN BAS IC
999 END
99 END
14. What will be stored in each variable of the array(s) after execution
of each of the fo llowing program segments? Show the name of
the variable and its content. For example , if there are two arrays,
you could show the contents in the following manner .
Array A Array 8
~ ~
A(1 ) 8(1 )
A(2) 8(2) 20
A(3) 8(3) 30
99 END
99 END
50 FOR J=l TO 3
60 REArl Y(J)
70 NEXT J
80 DATA 4,8,12,16,20,24
99 END
(d) Notice that the data statements are the same in Programs (b)
and (c). Is there any change in the order of the data items in
arrays X and Y after execution of Program (c) in comparison
to the way the items were stored in Program (b)? If the order
has changed, state the reason.
Problem 1
Q QUANTITY C EXTENDED COST
U - UNIT PRICE T TOTAL COST
( start)
Calculate
Extended Cost
DIM C(I)= Q(I)*U(I)
Q,U,C Total Cost
T=T+C(I)
302 PROGRAMMING IN BASIC
PROGRAMMING PROBLEMS
1. This is the final stage of the program that was started in Section 7.1,
page 256 . Find the extended costs of the following items and the total
cost of all the items.
Item Quantity Unit Price
1 2 $4.50
2 4 3.00
3 5 2.25
4 3 5.15
(a) Use the READ/DATA statements to store the above information in
two arrays. Array Q stores the quantities, array U stores the unit
prices.
(b) Store the extended cost of each item in a third array.
(c) Accumulate the total cost of all the items in a simple numeric
variable .
(d) In one FOR/ NEXT loop have the computer perform the following:
(i) Read the data using one DATA statement.
(ii) Calculate the extended cost of each item.
(iii) Accumulate the total cost of all the items.
(iv) Print the data and extended costs as shown in the RUN .
(e) Place the PRINT statement that prints the total cost outside the
loop.
(f) Extended Cost of Each Item = Quantity x Unit Price
(g) Total Cost = Total Cost + Extended Cost of Each Item
RUN
QUANTITY 2
UNIT PRICE 4.5
EXTENDED COST OF ITEM 9
QUANTITY 4
UNIT PRICE 3
EXTENDED COST OF ITEM 12
QUANTITY 5
UNIT PRICE 2.25
EXTENDED COST OF ITEM 11.25
QUANTITY 3
UNIT PRICE 5.15
EXTENDED COST OF ITEM 15.45
RUN
67 c" "
85 1 .J.;..
C'~,
79 231
93 324
RUN RUN
ACCOUNT: 1 ACCOUNT: 1
BALANCE? 450 BAL~INCE: 450
[I I SCOUNT: 9 [IISCOUNT: 9
AMOUNT REMITTED: 441 AMOUNT REMITTED: 441
304 PROGRAMMING IN BASIC
RUN
WEEKLY WAGES!
350 400 45111 500
HOURLY RATES:
8.75 10 11.25 12.5
(a) Use the READ/DATA statements to enter the code and the amount
of each transaction. Store the information in two arrays.
(b) Store the balance in a simple numeric variable. Initialize this
variable to zero outside the FOR/NEXT loop.
ONE - DIMENSIONAL ARRAYS 305
RUN
Problem 5
C CODE (INDEX)
A AMOUNT OFTRANSACTION
B BALANCE
( Start
'V
)
DIM
C,A
'V
B=0
!
l§
306 PROGRAMMING IN BASI C
~-..................-End
...............
)
Read
C(I),A(I)
Calculate Calculate
Balance Balance
B= B+A(I) B= B-A(I)
Print
Blank line
C(I),A(I)
B
NEXT I
(a) Use the INPUT statement to enter the number of the employee
and the number of parts produced. Store the information in two
arrays.
(b) Store an income in a simple numeric variable.
(c) Use one FOR/NEXT loop to enter the data, to calculate an income,
and to print the output.
(d) Income = Number of Parts Produced x Rate
RUN RUN
RUN
12 14 16 18 2~
144 196 256 324 400
8. Write a program that prints the multiplication table for the even
numbers 12 to 20 inclusive.
(a) Use one FOR/NEXT loop to read the five numbers into an
array, say N.
(b) Use nested FOR/NEXT loops to produce the table. The outer
loop retains a value, while the inner loop multiplies this value
by all the numbers in the array. Your main statement should
be
144168192216240
144168192216240
168 196 224 252 280
RUN
Problem 8
N DATA NUMBER
P - PRODUCT
( Start
)
DIM
~
N,P
End
)
Read
N(K) Calculate
Product
P(J)= N(I)*N(J)
\lI
NEXTK
NEXT J
NEXT I
310 PRO G RAMMING IN BASIC
A=1
B = 9,7,6,5 ,3 ,2
A=3
B = 9,7, 6,5,3,2
xx IF A(I)=B(J) THEN xx
assuming that the index of the outer loop is I and the one for the
inner loop is J. If the statement is true , transfer control to the
statement that prints the common number (from either array). If
the statement is false, transfer control to the inner NEXT state-
ment.
(a) Use the READ/DATA statements to store the numbers in two
arrays.
(b) Use a separate FOR/NEXT loop to read and print the data.
(c) Use nested FOR/ NEXT loops to find the common numbers and
to print them.
RUN
ARRAY A 1 ARRAY B 9
ARRAY A 3 ARRAY B -,I
ARRAY A 4 ARRAY B 6
ARRAY A 5 ARRAY B 5
ARRAY A 7 ARRAY It "7.J
Problem 9
A ARRAY A
B - ARRAY B
( Start
\JI
)
DIM
A,B
'¥
FOR 1= 1 TO 6
'VJ<=6
Print
">------:~Common No.
'V_ A(I)
Print
A(K),B(K)
W NEXT J
NEXT K
~ G
NEXT 1
312 PROGRAMMING IN BASIC
10. Using the data from Problem 9, have the computer add the
corresponding elements of arrays A and B. Store the results in
array C. Your calculations should be as follows.
Array A 1 3 4 5 7 8
Array B 9 7 6 5 3 2
Array C 10 10 10 10 10 10
(a) Use the READIDATA statements to store the data in two arrays
(array A and array B).
(b) Use two FOR/NEXT loops:
(i) One to read the data.
(ii) The other to perform the additions, print the data, and
print the results.
(c) Your statement to add should be
xx LET C(I)=A(I)+B(I)
RUN
EIGHT TWO-DIMENSIONAL
ARRAYS
A. After completing this chapter , you should be able to write BASIC
programs and complete skeletal BASIC programs that:
1. Store data in two-dimensional arrays by rows or by columns .
2. Print information from two-dimensional arrays by rows or by
columns.
3. Perform calculations on data stored in two-dimensional arrays
by rows or by columns .
4. Combine the above operations in a variety of ways within
FOR/NEXT loops .
B. In addition, you should be able to:
1. Differentiate between:
(a) A one-dimensional array and a two-dimensional array.
(b) The DIM statements that reserve storage locations for the
two types of arrays.
2. Display and label a doubly subscripted variable .
3. Find errors in programs.
4. Given program segments:
(a) Indicate how the data is stored, by rows or by columns.
(b) State what is stored in each element of the array(s).
5. Write program segments that:
(a) Print specific elements of an array.
(b) Perform calculations on specific elements of an array.
6. Produce the output of programs.
1 2 3 4 ~ One row
t1 One column
2
3
4
One-dimensional arrays are suitable for a variety of applications , such
as storing lists of numbers or names, but they may not be adequate if
a large number of data items are required as in statistical programs
and various business programs. These are more conveniently han-
dled by two-dimensional arrays, which consist of two or more rows
(or two or more columns). This arrangement of numbers is also
referred to as a matrix.
314 PROGRAMMING IN BASIC
Suppose that mystery books are stored on the third shelf (row 3) in
the first section (column 1). This would be recorded as storage area
31. If an abbreviated version of the library's name (say, R) is used
along with the location of a book, the inventory records would indicate
that mystery books are stored in R(31); that is, Roxvale Park Library,
storage area 31. The location of the history books would be R(11),
while that of autobiographies would be R(13). In BASIC these loca-
tions are written as R(3, 1), R(1, 1), and R(1 ,3), where R is the name of
the array and the digits within the parentheses are the subscripts. The
two subscripts give the terms doubly subscripted variable and
two-dimensional array. The array is two-dimensional because you
work in two directions - across the rows and down the columns. The
subscripted variables store the elements of the array. In this case,
they store the elements of array R and there are 12 such elements (3
rows x 4 columns = 12 elements). As in one-dimensional arrays, a
particular item of data is referenced by using the name of the array
and the location of the stored value. Unlike one-dimensional arrays,
the location must consist of two numbers (subscripts) enclosed in
parentheses. The first subscript is the number of the row; the second
subscript is the number of the column. These subscripts must be
separated by a comma.
Comma
R 3 ~ 1 ) <E---- Subscripts enclosed
i l' i in parentheses
Name of Row Column
the Array Number Number
Make sure you understand that the numbers in the areas shown
above represent the number of books, just as the array in Chapter
Seven showed the number of people living in each apartment. There
are two mystery books, since a number 2 is shown in row 3, column 1.
In BASIC, variable R(3,1) is said to contain the number 2. What does
R(1,1) contain? the number 3.
How does the computer store these numbers in a two-dimensional
array? This time nested FOR/NEXT loops are used - one loop for the
rows and one loop for the columns. Here is a program that stores the
numbers in the computer as elements of array R.
316 PROGRAMMING IN BASIC
Before going through the program, you should know the difference
between the variables 1 and J in the subscripted variable R(I,J).
Because 1 is listed first, this variable represents the number of the
row; J , then, represents the number of the column. Since 1 denotes
rows and there are three rows, the test value in 20 FOR 1=1 TO 3 is
three . J denotes columns, and since there are four columns, the test
value in 30 FOR J= 1 TO 4 is four. Illustrated below is how the data is
stored.
The first time through the loops, 1= 1 and J = 1. In line 40, R(I,J) is
actually R(1,1) . The number 3 is stored in the first row , first column.
Row 1 3
~--------4------
Row2
Row3
1 now remains constant, while J goes through its cycles. This means
that the row number stays the same, while the column number
changes.
Row 1 3 2
Row2
Row3
The third time through the J loop, 1= 1 and J= 3. In line 40, R(I,J) is
actually R(1 ,3). The number 0 is stored in the first row, third column.
3 2
Row 1 I
Row2
r---------+---------+---------+-------~
Row3
~--------~--------~--------~------~
The fourth time through the J loop, 1= 1 and J= 4 . In line 40, R(I,J) is
actually R(1 ,4) . The number 1 is stored in the first row , fourth column.
3 2
Row 1 I
Row2
r---------+---------+---------+-------~
Row3
~--------~--------~--------~------~
The J (column) loop is now complete and control enters the 1 (row)
loop. The value of 1 changes to 2, while the value of J reverts to 1. All
four columns of the second row will be filled as J goes through its
cycles. In the READ statements shown below, the number of the row
(I) remains 2, while the number of the column (J) varies from 1 to 4.
The numbers 1,0,2,3 are stored in the second row .
READ R(2,3)
READ R(2,4)
60 DATA 1,(j,2,3
3 2
Row 1 I
Row2 2 3
~--------+---------+---------+-------~
Row3 ~--------~--------~--------~------~
The J (column) loop is again complete and control enters the 1 (row)
loop. The value of 1 changes to 3, while the value of J reverts to 1. All
four columns of the third row will be filled as J goes through its cycles.
In the READ statements shown below, the number of the row (I)
remains 3, while the number of the column (J) varies from 1 to 4. The
numbers 2,4,1,0 are stored in the third row.
Row 1 3 2
Row 2 2 3
Row3 2 4
80 NEXT J
90 NEXT I
TWO-DIMENSIONAL ARRAY S 319
While the value of 1 remains one (in the first row), the value of J
changes from the first column to the second, third, and fourth
columns . After the J loop is satisfied , 1 changes to 2, which means
that the second row is filled as J goes through its loops once more.
The third row is filled when 1is equal to 3 and J has gone through all its
cycles . When 1 is equal to 4, looping terminates .
Care must be taken in listing the numbers in the DATA statement.
Because the data is stored by rows , the numbers in the DATA state-
ment must be listed by rows. This is why three DATA statements are
used (one for each row) , so you can readily see that the data items are
listed by rows . The three statements can be combined into one as
follows .
1st row 2nd row 3rd row
~ ~ ~
50DATA 13,2,0,1, 11 ,0,2,3, 12,4,1,0 1
However, multiple DATA statements will be used in most of the
programs in this book so that you can easily distinguish each row (or
column).
10 DIM R<3,4)
20 FOF: J=l TO 4 -Column loop on the outside.
3B FOR 1=1 TO 3
40 READ R(I,J)
50 DATA 3,1,2
6B DAT A 2 "1" 4 -Items listed by columns.
70 DATA 0,2,1
B0 DATA 1,3,0
90 NEXT I
100 NEXT J
999 END
Illustrated below is a trace through the cycles that fill the first
column . The first time through the loops 1= 1 and J= 1. In line 40,
R(I,J) is actually R(1,1). The number 3 is stored in the first row, first
column.
J now remains constant while 1 goes through its cycles. This means
that the column number stays the same while the row number
changes. The second time through the 1 (row) loop, 1= 2 and J= 1. In
line 40, R(I,J) is actually R(2, 1). The number 1 is stored in the second
row, first column.
Row 1 I 3
Row2 1
~--------+---------+---------+-------~
Row3 2
~--------~--------~--------~------~
The 1 (row) loop is now complete and control enters the J (column)
loop. The value of J changes to 2, while the value of 1reverts to 1. The
second column will be filled as 1 goes through its cycles.
Row 1 I 3 2
Row 2 1 0
~--------+---------+---------+-------~
Row 3 2 4
~--------~---------~--------~------~
The process continues for columns 3 and 4. Notice that the order of
the variables 1 and J was not changed in the subscripted variable
R(I,J). The first subscript isa/ways the number of the row, regardless
TWO-DIMENSIONAL ARRAYS 321
20 FOR 1=1 TO 3
3B FOR J=l TO 4
Array A
Column 0 Column 1 Column 2 Column 3
1--------+--------1I------+--------1I~
Row 0
Row1
Row Zero
Row2
i
Column Zero
The elements of this matrix are referenced in the same manner as the
elements of a matri x that does not have a row zero and a column zero.
For example, the top row gives variables A(0,0), A(0 ,1) , A(0,2) and
A(0,3) . The variable in the next row, left-most column, is A(1,0) .
Throughout this book, the top row of a matrix is considered as row
one and the first column on the left is considered as column one.
10 DIM A(2,3)
20 Far.: 1=1 TO 2 - Row loop on the outside.
30 FOr.: J=l TO 3
40 r.:EAD A(I,j)
50 [lATA UJ,20,30 -Items listed by rows.
60 DATA 40,5O,60
70 NEXT J
B0 NEXT I
99 END
II. This program uses the INPUT statement to enter the same data,
this time by columns.
10 DIM A(2,3)
2B PRINT
30 FOR J=l TO 3 -Column loop on the outside.
40 FOR 1=1 TO 2
50 PRINT 'VALUE FOR A(I,j)";
60 INPUT A(I,j)
70 NEXT I
BB NEXT j
99 END
RUN
Storeroom A Storeroom B
Sec 1 Sec 2 Sec 3 Sec 1 Sec 2 Sec 3
Shelf 1 1 2 3 Shelf 1 9 8 7
Shelf 2 4 5 6 Shelf 2 6 5 4
Shelf 3 7 8 9 Shelf 3 3 2 1
999 END
TWO-DIMEN S IO NAL ARRA YS 325
10 DIM A(3,3),B(3,3)
20 FOR 1=1 TO 3 - Row loop on the
30 FOR .j=1 TO 3 outside .
40 READ A(I,J),B(I,J)
50 DATA 1,9,2,8,3,7
60 DATA 4,6,5,5,6,4 -Items listed by rows .
70 DATA 7,3,B,2,9,1
B0 NEXT J
90 NEXT I
99 END
In this program, the data items are read into the computer in pairs;
the first member of each pair is read into array A, the second member
of each pair is read into array B. The first time through the J cycles,
1= 1 (row 1) and J= 1, then 2, and 3 (columns 1, 2, and 3) . The
statements
40 READ A(I,J),B(I,J)
5a DATA 1,9,2,B,3,7
result in
~
~
A(1,1) 8(1 ,1)
A(1,2) 2 8(1 ,2)
A(1,3) 3 8(1 ,3)
This is shown below in matrix form .
Storeroom A Storeroom 8
Sec 1 Sec 2 Sec 3 Sec 1 Sec 2 Sec 3
Shelf 1 I I 2 I 3 I Shelf 1 I 9 8 7
326 PROGRAMMING IN BASIC
The second time through the J cycles, 1=2 (row 2) and J = 1, then 2,
and 3 (columns 1,2, and 3). The statements
4~ READ A(I~j),B(I,J)
60 DATA 4,6,5,5,6,4
rn
result in
A(2,1) ~ 8(2,1)
A(2,2) 5 8(2 ,2) 5
A(2,3) 6 8(2,3) 4
This is shown below in matrix form .
Storeroom A Storeroom 8
Sec 1 Sec 2 Sec 3 Sec 1 Sec 2 Sec 3
Shelf 1 I : I 2 3 Shelf 1 I 9 I 8 I 7 I
Shelf 2. . 5 6 Shelf 2 6 5 4
The third time through the J cycle 1=3 (row 3) and J = 1 , then 2, and 3
(columns 1,2, and 3). The statements
40 READ A(I,j),B(I,j)
70 DATA 7,3,8,2,9,1
result in
Compare the DATA statements in the first program with those in the
second. In Program 1, all of the data for array A is listed first, followed
by all of the data for array B . This is because each array is filled by
separate sets of nested FOR /NEXT loops.
The second program has only one set of nested FOR/ NE XT loops and
only one READ statement. The data items are listed in pairs. The first
member of each pair is stored in array A; the second member of each
pair is stored in array 8.
50 DATA 1,9,2,8,3,7
60 DATA 4,6,5,5,6,4
70 DATA 7,3,8,2,9,1
Data is stored in pairs because the READ statement lists both arrays.
In this program, array A is listed before array B.
50 DATA 1, 9 -,--,-,-
1 . 10 DIM A(4,5)
20 FOR 1:.:1 TO 5
30 FOR J=l TO 4
40 READ A(I,J)
50 DATA -,-,-, ...... (20 items of data)
100 NEXT J
110 NEXT I
999 Hili
2 . 10 DIM 8(3,3)
328 PRO GRAMMIN G IN BASIC
100 NEXT I
110 NEXT J
999 END
100 NEXT I
110 NEXT J
999 END
4. 10 DIM M(4),N(3,4)
20 FOR 1=1 TO 3
30 FOR J =l TO 4
40 RE AD M( I,J ) , N( I,J)
50 DATA - , - , - , •••••• (24 items of data)
100 NEXT J
110 NEXT I
999 END
5. 10 DIM P(7,B),R(B,7)
20 FOR J=l TO 7 ...,
30 FOR 1=1 TO I
40 READ P( I ,J) ,R( I ,J)
50 DATA - , - , - , • • • • •• (98 items of data)
HH'l NEXT I
110 NEXT J
999 END
A B
1 2 3 149
456 16 25 36
7 8 9 49 64 81
TWO-D IMENS IONA L A RR AYS 329
10 DIM A(3,3),B(3,3)
20 FOR 1=1 TO 3
30 FOR J=l TO 3
40 READ A(I,J),S(I,J)
S0 DATA 1,2,3,4,5,6,7,8,9
60 DATA 1,4,9,16,25,36,49,64,81
10e NEXT J
110 NEXT I
999 END
II. Answer the following questions for each program shown below .
A B
1 2 3 10 20 30
456 40 50 60
(a) 1 e DIM A( 3 , 4 )
20 FOR 1=1 TO 3
30 FOR J=l TO 4
40 READ A(I,J)
50 DATA
60 DATA 22,24,26,28,3~,32
70 NEXT J
S0 NEXT I
99 END
10~ NEXT L
110 NEXT K
12f! DATA 10,2~,30,40,50960
130 DATA 15,25,35,45,55,65
999 END
(e) Notice that the data statements are the same in Programs (c)
and (d). Is there any change in the order of the data items in
arrays M and N after execution of Program (d) in comparison
to the way the items were stored in Program (c)? If the order
has changed, state the reason.
Y R
10 12 14 .10 .11 .12
16 18 20 .13 .14 .15
(a) Write two programs to enter the above data items into the
arrays by rows.
( start)
DIM
Y,R
1>2
FOR 1=1 T02 FOR K= 1 TO 2
K<=2
NEXT J NEXT L
NEXTI NEXT K
332 PROGRAMMING IN BASIC
HI [11M A(4,:i)
20 FOR 1=1 TO 4
30 FOR J=l TO 5
5. Nothing is wrong.
6. Since the READ statement lists two arrays (A and B) and
since array A is coded before array B, the DATA statement
must list the data items in pairs , so that the first member of
TWO - DIMENSIO NAL ARRAYS 333
4~ READ A(I,J),B(I,J)
5~ DATA ld,2~4,3,9
6~ DATA 4,16,5~25,6~~~6
7~ DATA 7,49,8,64,9,81
II. (a) 1. The data items are read in by rows because the index of
the outer loop is the first subscript of array A. The first
subscript of a doubly subscripted variable represents
the number of the row.
2. A
10 12 14 16
18 20 22 24
26 28 30 32
(b) 1. The data items are read in by rows .
2. M N
10 20 30 15 25 35
40 50 60 45 55 65
(c) 1. The data items are read in by rows.
2. M N
10 30 50 20 40 60
15 35 55 25 45 65
(d) 1. The data ite ms are read in by columns since the inde x of
the outer loop is the second subscri pt of ar rays M and N .
The second subscript of a doubly subscripted variable
represents the number of the column.
2. M N
10 50 35 20 60 45
30 15 55 40 25 65
(e) The order of the data items in arrays M and N is changed
after execution of Program (d) . This is because Program (c)
reads the data by rows, while Program (d) reads the data by
columns.
01 REM Y--YEARS
a2 REM R--RATE
- - - - - - - - - - - - - -
01 REM Y--YEARS
02 REM R--RATE
1~ DIM Y(2,3),R(2,3)
2~ FOR 1=1 TO 2 -Row loopon the outside.
3~ FOR J~l TO 3
4~ READ Y(I~J),R(I,J)
5~ OAT A 10,. 111" 12, • 11 , 14, .12 -Items listed by rows.
60 DATA 16,.13118,.14,20,.15
70 NEXT J
8f\ NEXT I
99 END
(b) The data items must be listed in a specific order because the
READ statement reads the values into two arrays - Y and R.
This means that the data items must be listed in pairs, with
the first item of each pair assigned to an element of array Y
(since Y is the first array listed in the READ statement) and the
second item of each pair assigned to an element of array R.
TWO-DIMENSIONA L ARRAYS 335
HI DIM R(3,4)
20 FOR 1=1 TO 3
30 FOR J=l TO 4
40 READ R(I,J)
sa DATA 3,2,~rl
68 DATA 1,0,2,3
70 DATA 2,4d,e
80 NEXT J
90 NEXT I
99 END
99 END
RUN
2
336 PROG RAMMIN G IN BAS IC
How would you ask the computer to print the element in row 1,
column 1, of the array shown above ?
5~ PRINT F:(l,l)
99 END
RUN
How would you code the PRINT statement if you wanted to have two
elements printed on the same line wide ly spaced - the element in
row 1, column 1, and the element in row 3, column 4?
99 END
RUN
What would the PRINT statements and the RU N look like if you wanted
to have all the elements printed by rows on one line closely spaced ?
40 PRINT R(1,1);R(1,2);R(1,3);R(1,4);
5~ PRINT R(2,1);R(2,2);R(2,3);R(2,4);
60 PRINT R(3,1);R(3,2);R(3,3);R(3,4)
99 END
RUN
3 2 ell e 232 4 1 e
segment that prints the number of books in each storage area. This
one uses nested FOR/NEXT loops. Although it is written to print 12
items, it can just as easily print more or less. Simply change the
subscripts in the DIM statement, the test values in the FOR statements,
and the number of data items in the DATA statement .
lliJ0 PRINT
lUI FOR 1=1 TO 3
12~ FOR J::;;l TO 4
130 PRIN~R(I,j); This PRINT statement counteracts the semicolon .
140 NEXT J The next item is printed on a new line.
150 PRINT
160 NEXT I
999 END
RUN
32121 1
1 023
2 4 1 0
How did the computer print the numbers as a matrix? It's very
similar to what was done in Chapter Six, page 227. The semicolon at
the end of 130 PRINT R(I,J); prints the items on the same line while
the computer is in the J (column) cycles. Before the computer enters
another I (row) loop, it is forced off the line by the PRINT statement in
line 150. The next item, which is the first item of a new row, is printed
on a new line.
In the previous program segments, it was assumed that the data
items had already been entered . Two programs that include both the
entering and the printing of data are shown below. The first program
reads and prints the data items using separate sets of nested
FOR/ NE XT loops; the second program does both in one set of loops.
10 DIM R(3,4)
17~ NEXT J
18~ NEXT I
200 REM PRINT ITEMS FROM AN ARRAY
210 PRINT
220 FOR K=l TO 3 - Row loop on the outside .
230 FOR L=l TO 4
240 PRINT R(K,L);
250 NEXT L
26~ PRINT
27~ NEXT K
999 END
RUN
3 2 0 1
1 0 2 3
....'1 4 1 0
10 DIM R(3,4)
20 PRINT
30 FOR 1=1 TO 3 - Row loop on the outside .
40 FOR J=l TO 4
5~ READ R(I,J)
60 DATA 3,2,e"1
70 DATA 1,0,2,3 -Items listed by rows .
80 DATA 2,4,1,0
90 PRINT R(I,J);
le0 NEXT J
110 PRINT
120 NEXT I
999 END
RUN
3 2 0 1
1 023
2 4 1 0
1. Prints by rows
HI DIM R(3,4)
999 END
RUN
3 2 1 1 o 2 3 4 1 121
2. Prints by columns
340 PROGRAMMING IN BASIC
999 END
RUN
3 1 2 2 B 4 0 2 1 1 3 ~
70 [lATA 40,50,60
80 PRINT A(I,J); - Prints the data by rows on one line.
90 NEXT J -Indicates the end of the column loop .
U/JI1I NEXT I -Indicates the end of the row loop.
999 END - Terminates program execution.
RUN
II. The program shown below uses the INPUT statement to enter the
same data . This time the items are entered and printed by
columns . The program uses separate sets of nested loops to
store and print the data so that the output is apart from the
prompts Compare the output with that of Program I, which
prints the items by rows .
RUN
10 4111 20 50 30 60
342 PR OGRAMMING IN BA S IC
III. Here is the second stage of the program that was started in
Se ction 8.1, page 324 .
Storeroom A Storeroom B
Sec 1 Sec 2 Sec 3 Sec 1 Sec 2 Sec 3
Shelf 1 1 2 3 Shelf 1 9 8 7
Shelf 2 4 5 6 Shelf 2 6 5 4
Shelf 3 7 8 9 Shelf 3 3 2 1
10 DIM A(3,3),B(3,3)
RUN
STOREROOM A
1 2 J
4 5 6
7 B I'j>
STORE.ROOM B
....,
9 8 /
6 5 4
3 2 1
Notice that the data items are listed in pairs and by rows. The first
member of each pair is stored in array A, the second in array B. Three
DATA statements are used, one for each row so that you can readily
see how the data is listed. Also, the PRINT routines use different
indexes. Array A uses K and L in its FOR statements, while array B
uses M and N. Even with different indexes, each routine prints by
rows, since the first subscript (that is, the row subscript) of each array
is used as the index of the outer loop.
1~ DIM A(3,3),B(3,3)
2~ PRINT
3~ FOR J:: 1 TO 3 - Column loop on the outside.
4~ FOR 1=1 TO 3
5~ READ A(I,J),BCI,J)
6~ DATA 1,9,4,6,7,3
7~ DATA 2,8,5,5,8,2 -Items listed by columns.
80 DATA 3,7,6,4,9,1
9~ PRINT A(I,J),B(I,J)
11iJ~ NEXT I
lla PRINT
12£'! NEXT J
999 END
RUN
1 9
344 PROGRAMMING IN BASIC
4 c.
1 3
2 8
c c:"
J ,J
8 ...
r)
3 7
6 4
9 1
Note the difference in the data statements between this program and
the previous one. This time the data items are listed by columns . Also
notice that the column loop is on the outside. A PRINT statement is
placed between the NEXT statements so that the blank line it produces
will help you distinguish one column from another.
(a) Write a PRINT statement that prints the last element of the
array (fourth row, fourth column).
RUN
2
(b) Write a PRINT statement that prints the first and last elements
of the array widely spaced.
RUN
1 2
TWO - DIMEN SIONAL ARRAYS 345
RUN
5 6 7 8
RUN
.....,
6
8
4
A
234
5 7 8
9 8 6
543
RUN
:L 672
A B
1 2 3 9 8 7
4 5 6 6 5 4
2.
RUN
YEARS 1e RATE •1
YEARS 12 RATE • 11
YEAr~S 14 RATE .12
YEARS 16 RATE .13
YEARS 18 RATE .14
YEARS 2B RATE .15
Problem 3 (b)
Y - YEARS R - RATE
DIM
Y,R
348 PROGRAMMING IN BASIC
J>3
End
NEXTI
NEXT J NEXT L
NEXT K
(c) (e)
30 PRINT 30 F'RINl
40 FOR J=l TO 4 4L3 FOR 1:= 1 TO 4
50 PRINT A(2,J) ; 50 FOR J=: 1 TO -4
60 NEXT J 60 IF I=J THEN 8ll
70 GO TO S·)0
999 END 80 PRINT A(I,JH
9D NEXT J
(d) HH'l NEXT I
3D PRINT
40 FOR 1=1 TO 4 999 END
50 PRINT A(I,2)
,S0 NEXT I
999 END
30 FOR 1=1 TO 2
40 FOR J=l TO 3
60 DATA 1,9,2,8,3,7
70 DATA 4,6,5,5,6,4
RUN
987
654
123
456
350 PR OG RAM MING IN BAS IC
01 REM Y--YEARS
02 REM R--RATE
10 DIM Y(2,3),R(2,3)
20 REM READ AND PRINT BY ROWS
30 PRINT
40 FOR 1=1 TO 2 -Row loop on the outside .
50 FOR J=l TO 3
60 READ Y(I,J),R(I,J)
70 DATA 10,.:LI~,12,.11,14,.12 -Itemshstedbyrows .
80 DATA 16,.13,18,.14,20,.15
90 PRINT "YEARS";Y(I,J),"RATE";R(I,J)
100 NEXT J
110 NEXT I
999 END
~H REM 'y--YEARS
02 REM R-'-RATE
I. Suppose you want to know the total number of books in the first
two storage areas (row 1, columns 1 and 2). Here is a statement
that performs this calculation .
5~ LET T=R(1,1>tR(1,2)
60 PRINT T
99 END
RUN
5
5~ LET T=R(1,1>tR(1,2>
=3+2
=5
II. If you want to know the total number of books on the first shelf
(row) , the statement will look as follows .
50 LET T=R(1,1>tR(1,2>tR(1,3>tR(1,4)
60 PRINT T
352 PROGRAMMING IN BASIC
99 END
RUN
6
III. The previous statement is not too difficult to code since there are
only four sections to a shelf. But what if you wanted to know the
total number of books in all the storage areas? The statement
gets to be quite long. In fact, if there were 100 or 1000 storage
areas, it would be almost impossible to code the statement in this
fashion. As in storing and printing, FOR/ NEXT loops will be used so
that the computer references each storage location in the array.
Here are two versions of the same program. Both programs
store, print, and calculate by rows.
1. This version stores and prints the data in one set of nested
FOR/NEXT loops and calculates the total in another set. Notice
that the variable T, in this program, is initialized just before its
use in the calculation routine. Initialization may take place
prior to this; for example, right after the DIM statement.
RUN
3 2 0 1
~
1 0 .:. 3
2 4 1 ~
19
10 [11M R(3,4)
21!l LET T " 0
3O PRINT
4£1 FOR 1=1 TO 3
5£1 FOR J=l TO 4
60 READ R(I,J)
70 DATA 3,2,11"1
se [lATA 1,O,2,3
9£1 DATA 2,4ddJ
11!l0 PRINT R(I,J);
lUI LET T=TtR(I,J)
12£1 NEXT J
131!l PRINT
14~ NEXT I
150 PRINT T
999 END
RUN
3 2 1
1
2
£I
4
°21 3
0
19
999 END
RUN
40 FOR 1=1 TO 3
50 LET T=T+R<I,4)
60 NEXT I '"
70 PRINT I
80 PR 1 NT T Variable used for the number
of the row.
999 END
RUN
VI. Assume that the librarian places another book in the storage area
located in row 2, column 3. Here is the statement that makes this
change.
80 LET R(2,3)=R(2,3>+1
VII. Here is another change. The number of books in the first row ,
first column , is now the same as the number of books in the third
row , second column. The statement for this change is as follows .
40 PRINT
50 FOR 1=1 TO 3
60 FOR J ~ l TO 4
70 IF R(I,J)=0 THEN 90
80 GO TO HH~
90 PRINT "ROW:"jI,"COLUMN:";J
100 NEXT J
lUI NEXT 1
999 END
RUN
ROW: 1 COLUMN: 3
ROW! 2 COLUMN! 2
ROW: 3 COLUMN: 4
4B FOR 1=1 TO 3
5B FOR J=l TO 4
6e LET R(I,J)=a
70 NEXT J
80 NEXT 1
The first time through the Iloop the value of J changes from 1 to 4
and each element in row 1 becomes zero. Control re-enters the I
loop . The value of I is now 2 and each element in the second row
becomes zero, as J goes through its cycles once more. The last
time through the I loop (the value of I is now 3), each element in
the third row becomes zero.
X. Here is the last stage of the program that was started in Section
8.1, page 324 .
RUN
A 1 II 9
TOTAL HI
A 2 B 8
TOTAL 10
A 3 B 7
TOTAL 1 ~J
A 4 B 6
TOTAL 10
A 5 B r:"
..J
TOTAL 1~
A 6 It 4
TOTAL 10
A 7 B 3
TOTAl. HI
A 8 B '1
"-
TOTAL 1~
A 9 B 1
TOTAL 10
01 REM Y--YEAF:S
02 REM R--RATE
03 REM I--INTEREST
04 REM A--AMOLJNT INVESTED
10 DIM Y(2,3),R(2,3),I(2,3)
2~ LET A=412J00
112J~ REM READ THE DATA
1 HI FOR M= 1 TO 2
120 FOR N=1 TO 3
130
140 DATA 10,.1121,12,.11,14,.12
150
160 REM CALCULATE THE INTEREST
170
18121
19121 NEXT M
2121121 REM PRINT AMOUNT INVESTED
21121 PRINT
220
300 REM PRINT YEARS, RATE, INTEREST
31121 FOR K=1 TO 2
32121 FOR L=1 TO 3
330 PRINT
340
35121
360 NEXT L
37121
999 END
RUN
AMOUNT INVESTED 401210
360 PROGRAMMING IN BASI C
YEARS 10 RATE •1
INTEREST 400
YEARS 20 RATE . 15
INTEREST 600
R
Column 1 Column 2 Column 3 Column 4
Row 1 I 3 2 (/) 1
Row 2 (/) 2 3
~--------~-------+--------~--------~
Row 3 2 4
L -_ _ _ __ _ _ _L -_ _ _ _ _ _ ~
(/)
_ __ __ _ _ _- L_ __ __ _ _ _ ~
Assume that the librarian places two more books in each storage
area . Write a program that prints the original number of books
and the increased number of books in each storage area.
(a) Perform all operations by rows.
(b) Use one set of nested FOR/NEXT loops to read and print the
data.
(c) Use another set of nested loops to increase each element of
the array by two, and print these increased amounts.
(d) Draw a flowchart before you write the program .
RUN
3 2 0 1
1 0 2 3
2 4 1 ~
5 4 2 3
3 2 4 5
4 6 3 2
II.
Problem II
( Start
W
)
DIM
R
W
Print
Blank line
W
@§J
TWO-DIMENSIONAL ARRAYS 363
,..----- -- - - - -- - - - - -- -_ _ -- - - - - - - - - - - - - - - -- ,
..
1> 3
End
Increase
Elements
R(K ,L)= R(K,L)+ 2
NEXT J
NEXT L
NEXT I
NEXT K
364 PROGRAMM ING IN BASIC
A SHORT SUMMARY
One-dimensional arrays are often inadequate when large quantities
of data are to be entered into the computer. These are more conve-
niently handled by two-dimensional arrays, which are often referred
to as matrices Here is an example of a matrix.
A
2 3 1 2
4 0 3 1
o 1 4 2
This matrix has three rows and four columns. To reference a particular
item of data, the array name must be used and must be followed by
two subscripts enclosed in parentheses. The first subscript is a/ways
the number of the row ; the second subscript is a/ways the number of
the column. These subscripts must be separated by a comma.
Comma
l
A 3 1 ) <E-------- Subscripts enclosed
l' i f in parentheses
Name of Row Column
the array number number
In order to reserve a sufficient number of storage locations, the
subscripted variable in the DIM statement must also have two sub-
scripts. The first subscript reserves storage locations for the rows;
the second subscript reserves storage locations for the columns.
10 DIM A 3 4
l' t l'
Name Number Number
of the of of
array rows columns
In this DIM statement, twelve storage locations are reserved
(3x4=12).
Whereas a one-dimensional array requires one FOR/NEXT loop , a
two-dimensional array usually requires nested FOR/NEXT loops - one
loop for the rows and the other loop for the columns. Data may be
manipulated either by rows or by columns, depending on the sub-
script used as the index of the outer loop and on the order of the data
items in the DATA statement. If the row subscript is used as the index
of the outer loop and the data items are listed by rows, the data will be
manipulated by rows.
The storing, printing, and processing of data may be performed in
one set of nested FOR/N EXT loops or in several. If one set of loops is
used, all operations are performed the same way - either by row or
by column. If several sets are used, operations may be performed
differently among the sets of nested FOR/NEXT loops.
713 NEXT I
999 END
7~ NEXT M
999 END
6~ NEXT J
7111 NEXT I
999 END
(d) In the program segment shown below , the data items are to
be stored in their respective arrays by columns.
A B
123 3 6 9
4 5 6 12 15 18
789 21 24 27
10 DIM A(3,3),B(3,3)
2~ FOR J=1 TO 3
3111 FOR 1=1 TO 3
40 READ A(I,J),B(I,J)
5~ DATA 1,3,2,6~3,9
6111 DATA 4,12,5,15,6,18
7~ DATA 7,21,8,24,9,27
8~ NEXT I
9~ NEXT J
999 END
A B
456 16 20 24
789 28 32 36
READ A(I,J),B(I,~I)
50 IIATA 10,10B,2B,2~~,3~,3~0
6B DATA 4B,4BB,Sa,SBB,6B,60B
78 NEXT I
80 NEXT J
99 END
R
4 7 8 5
869 7
100 PRINT
110 FOR 1=1 TO 2
120 FOR J=l TO 4
130 LET P(I,J)~R(I,J)*3
140 PRINT P(I,J);
150 NEXT J
160 PRINT
178 NEXT I
999 ENII
PROGRAMMING IN BASIC
H'!0 PRINT
11~ FOR 1=1 TO ..'")-
120 FOR J=l TO 4
130 LET T=T+R(I,J)
140 PRINT 1;
150 NEXT J
160 NEXT I
999 END
20 LET T::::0
100 PRINT
110 FOR 1=1 TO 2
120 FOR J=l TO 4
130 LET T=TtR(I,J)
140 NEXT J
150 NEXT I
160 PRINT T
999 END
10 DIM A(3,3),B(3,3)
2~ FOR 1=1 TO 3
30 FOR J=l TO 2
40 READ A(I,J)
50 DATA 5,4,8,8,5,4,6,4,5
60 NEXT I
70 NEXT J
80 PRINT
90 FOR K=l TO 3
10a FOR L=l TO 3
110 LET S=0
120 LET B(K,L)=A(K,L)T2
130 LET S=StA(K,L)
1.40 PRINT B(K,L);
150 NEXT L
161:'1 NEXT K
170 PRINT S
999 END
RUN
25 64 36
16 16
64 16 25
287
TWO-DIMENSIONAL ARRAYS 371
PROGRAMMING PROBLEMS
The first two problems involve the number of library books in the
Roxvale Park Library first discussed in Section 8.1. Shown below is
the current number of each type of book in each storage area of the
library.
R
Column 1 Column 2 Column 3 Column 4
2 4 3 2
Row 1 I
Row2 . 4 2 4 3
Row3 2
L -_ _ _ _ _ _ _ _ ~
5 3
_ __ _ _ _ _ _- L_ _ _ _ _ _ _ _ ~
2
_ __ __ _ _ _ ~
RUN
"l
"- 4 3 2
4 ")
"- 4 3
2 5 3 "
"-
TOTAL: 36 AVERAGE: 3
RUN
Problem 2
L - LARGE
R1 - ROW NUMBER C1 - COLUMN NUMBER
( start)
Print
DIM Blank line
FORI=1T03 End
R L
R1 ,C1 .
L= R(I,J)
R1=1
C1 = J
NEXT J
NEXT I
TWO-DIMENSIONAL ARRAYS 373
The next five questions are problems concerning the two store-
rooms that contain various styles of shoes. Here is the information
once more.
Storeroom A Storeroom B
Sec 1 Sec 2 Sec 3 Sec 1 Sec 2 Sec 3
Shelf 1 1 2 3 Shelf 1 9 8 7
Shelf 2 4 5 6 Shelf 2 6 5 4
Shelf 3 7 8 9 Shelf 3 3 2 1
RUN
STOREROOM A
1 ')
"- 3
4 5 6
-,
I 8 9
STOREROOM II
9 8 7
6 5 4
3 2 1
TOTAL IN STOREROOM A 45
TOTAL IN STOREROOM B 45
TOTAL IN BOTH STOREROOMS 9~
374 PROGRA MMING IN BAS IC
4. Suppose the supervisor asks the stock clerk to move some of the
shoes from one storeroom to the other so that the corresponding
storage loca tions in each storeroom have the same number of
pairs of shoe s.
(a) In one set of nested FOR/ NEXT loops, read the data and
perform the calculations .
(b) To obtai n the same number of pairs in the corresponding
storage Iocations , you must:
-add t he number of pairs in the corresponding locations
and store the sums in a third array . (See page 357 ,
Progr am X.) Your statement should be something like the
folio wing .
xx LET C(I,J) = A(I,J)+ 8(/,J)
-divid e the numbers stored in the third array by 2 and store
the results in both array A and array B. Your statement
shoul d be as follows:
xx LET A(I,J)= C(I,J)/2
You s hould have a similar statement for array B.
(c) Use two sets of nested FOR/ NE XT loops to print the new
number s from both arrays.
RUN
STOREROO M A
5 5 5
5 5 5
5 5 5
STORE ROO M It
5 5 5
5 5 "'.
;:J
5 5 C'
""
5. Supposetha t several pairs of shoes have been sold and that the
following nu mbers of pairs remain in each storeroom.
RUN
Problem 5
A STOREROOM A
V - VALUE OF SHOES P - PRICE
C Start
\lI
)
DIM
A,V,P
1
~
376 PR OGRAMMIN G IN BASIC
End
NEXT J
NEXTM
NEXT I
NEXTK
6. Write a program that finds the tota l value of the shoes in sto re-
roo m A.
(a) Use one set of nested FO R/NEXT loops to read the prices.
TWO-DIMENSION AL ARRAYS 377
(b) Use another set of nested FOR/NEXT loops to read the num-
ber of pairs of shoes in each storage location of storeroom A,
and to calculate the total value . Store the total value in a
simple variable, say T.
RUN
1353
(b) Use another set of nested loops to find the required storage
locations in storeroom B and to print these shelf and section
numbers.
RUN
STOREROOM A
SHELF 1 SECTION 1
SHELF 1 SECTION 3
SHELF 2 SECTION :3
SHELF 3 SECTION 1
STOREROOM B
SHELF 1 SECTION ... ~
SHELF ... ~
SECTION ... ")
SHELF 2 SECTION 3
378 PROGRAMMING IN BASIC
Problem 7
( Start )
DIM
A,S
1> 3
J> 3
FORJ=1T03
NEXT J
NEXT L
NEXT I
NEXT K
TWO - DIMENSIONAL ARRAYS 379
The last three problems will use one or both of the following matrices.
A B
3 527
*
4 6 496
7 8 3 8 1
RUN
123
456
789
RUN
2 468
380 PROGRAMMING IN BASIC
Problem 9
C - COMMON NUMBER
( Start )
DIM
End
A,B
J> 3
Store
Common Number
C= A(I,J)
No
Print
C
NEXT J
NEXT I
TWO-DIMENSIONAL ARRAYS 381
Program (a)
RUN
Program (b)
RUN
20 MAT READ A
i i i i
Statement Key word Function Name of
Number to be the Array
performed
Input/Output
MAT READ A - Reads the data into array A.
MAT INPUT A - Allows the user to key the data into array A.
MAT PRINT A - Prints items from array A.
Assignment 1
MAT B=A - Copies the elements of array A and assigns
them to array B.
MAT A=ZER - Assigns zero to each variable of array A.
MAT A=CON - Assigns the number one to each variable of
array A.
MAT A=IDN - Assigns the identity matrix to matrix A.
Mathematical
MAT C = A+ B - Adds the elements of array A to the correspond-
ing elements of array B and stores the sums in
the corresponding locations of array C .
MAT C= A- B - Subtracts the elements of array B from the
corresponding elements of array A and stores
the differences in the corresponding locations of
array C.
MAT B= (2)*A - Multiplies each element of array A by 2 (a scalar)
and stores the products in array B.
MAT C= A*B - Using matrix multiplication , multiplies matrix A
by matrix B and stores the products in matrix C.
Special
MAT B==TRN(A) -Transposes the rows and columns of matrix A
and stores the result in matrix B.
MAT B== INV(A) -Determines the inverse of matrix A and stores
the result in matrix B.
The program using FOR/ NEXT loops requires at least eleven state-
ments to read and print the data; more would be needed if the PRINT
routine had its own nest of loops. The program using MAT statements
requires only six statements, yet data is entered and printed the same
way-that is, by rows .
It was mentioned in the previous chapter that some computer
systems support matrices with zero subscripts. 2 On these systems,
MAT statements may not manipulate variables with zero subscripts;
they assume that the subscripts start at 1 . This means that DIM A(3,4)
reserves 20 storage locations (0 to 3 for the first subscript , and 0 to 4
for the second subscript) , but a MAT statement will use only 12 of
these locations (1 to 3 for the first subscript , and 1 to 4 for the second
subscript). If the DIM statement is omitted , matrix A will automatically
have 121 storage locations reserved for its elements (0 to 10 for each
subscript). It may be necessary to supply 100 values (1 to 10 for each
subscript, since the zero elements are ignored). If only 12 data items
are supplied, an error message may occur when an attempt is made
to use a MAT statement. It is therefore recommended that all matrices
referenced by MAT statements have their dimensions defined.
It should also be mentioned that each MAT statement works inde-
pendently of another . For example, if data is read by a MAT READ, it
is not necessary that the data be printed by a MAT PRINT. Further-
more , a specific element of the array must still be accessed by a
subscripted variable. And, on many computer systems, the same
array name may not be coded on both sides of the equals sign.
Examples of invalid statements are as follows .
30 MAT A=AtB
40 MAT B=A*B
50 MAT C=INV(C)
2. As mentioned in Chapter Eight, zero subscripts are not used in this book.
MATRI X STATEMENTS AND LIBRARY FUNCTIONS 385
Each of the MAT statements listed earlier in this section will now be
briefly explained.
INPUT/OUTPUT
The following program segment stores data in a one-dimensional
array (a vector).
I. MAT READ
HI DIM A(4)
2~ MAT READ A
31-!1 DATA 1,2,3,4
99 EN[I
1~ [11M A(3,4)
2~ MAT READ A
3a DATA 1,2,3,4,5,6,7,8,9,10,11,12
99 END
1~ DIM A<3,4),B(2,3),C<4)
2~ MAT READ A,B,C
3~ DATA 1,2,3,4,5,6,7,8,9,10,11,12
4~ DATA 6,5,4,3,2,1
50 DATA 4,3,2.1
99 EN[I
The first 12 data items are stored in matrix A, the next 6 are stored in
matrix S, and the last 4 are stored in vector C. On the majority of
systems, there must be sufficient data to fill all the positions reserved
by the DIM statement.
The MAT INPUT statement is another MAT instruction that enters values II. MAT INPUT
into an array .
386 PROGRAMMING IN BASIC
1~ DIM A(4)
20 MAT INPUT A
99 END
fWN
r,>
10 DIM A(12)
20 MAT INPUT A
99 END
RUN
?
If only four numbers are typed in response to the question mark, the
variable A(eJ) and the variables A(5) to A( 12) inclusive will not be
used.
The MAT INPUT instruction also stores values in a two-dimensional
array.
RUN
?
MATRI X STATEMENTS AND LIBRAR Y FUNCTIONS 387
As with the MAT READ statement, the values must be entered by rows
and , on most computer systems, the number of values entered is
determined by the dimensions specified in the DIM statement. In the
above program, six values must be keyed in , since the dimension
statement has reserved six storage locations. First A(1, 1) is filled,
then A(1 ,2), A(1 ,3), A(2 ,1), A(2,2) , and finally A(2 ,3) . It should be
noted that some versions of BASIC do not allow more than one vector
and/or matrix to be filled by one MAT INPUT statement.
The MAT PRINT statement prints elements from either a one- III. MAT PRI NT
dimensional array or from a two-dimensional array. The statement
outputs all positions, including blank ones , which are printed as
zeros . First consider the output from a one-dimensional array (a
vector) .
10 DIM A(4)
4~ MAT PRINT A
99 END
Hl DIM A(4)
2~MAT READ A
3~DATA 1,2,3,4
40 PRINT
5~ MAT PRINT A
99 END
388 PROGRAM MIN G IN BAS IC
RUN
10 [11M A(2,3),B(2,7),C(4)
2£'l MAT READ A,B,C
321 DATA 121,221,321,421,521,60
40 DATA 1,2,3,4,5,6,7
521 DATA 8,9,121,11,12,13,14
60 DATA 1.2121,2021,3021,400
721 PRINT
821 MAT PRINT Adh C
99 END
RUN
1 2 3 4
5 6 7
<
~----- One blank line between the rows .
8 9 10 11
12 13 14
<
~----- Two blank lines between the output of
two arrays .
1021
2021
3021
42121
MATRI X STATEMENTS AND LIBRAR Y FUN CTIONS 389
RUN
1~ 2121 3121
~(-------- One blank line between the rows.
4121 5121 6121
123 456 7
( One blank line between the rows .
8 9 1121 11 12 13 14
<E<=--------- - Two blank lines between the output of two arrays.
1121121
2121121
4121121
The MAT CON statement may also be considered an initialization III. MAT A= CON
statement. The only difference between this statement and the MAT
ZER statement is that MAT CON assigns the number one instead of zero
to each variable of an array. The statement may not work on a one-
dimensional array.
MATRIX STATEMENTS AND LIBRARY FUNCTIONS 391
10 DIM A(3,3)
20 MAT A=I[lN
30 PRINT
40 MAT PRINT A;
99 END
rWN
1 £) 0
£) 1 0
i!) 0 1
Mathematicai3
This statement adds the elements of array A to the corresponding
elements of array B and stores the sums in the corresponding
I. MAT C=A+B
locations of array C. All three arrays must have the same dimensions.
The statement may be used on both one-dimensional and two-
dimensional arrays .
3. The intent of this section is to explain the various MAT functions. If you wish to
become more familiar with matrix mathematics, read any Algebra text that includes
operations on matrices .
Small inaccuracies in the storage of some numbers may produce results that are
approximations when the numbers are used in calculations . For example, the
numbers representing zeros in the identity matrix (found by multiplying the original
matrix by its in verse) may be near zero, such as 8.S2463E-09. These approximations
apply to non-zero numbers as well.
392 PROGRAMMING IN BASIC
This statement is similar to the previous one, except that MAT C=A- II. MAT C=A-8
B subtracts the elements of array B from the corresponding elements
of array A. The differences are stored in the corresponding locations
of array C. All three arrays must have the same dimensions . The
statement may be used on both one-dimensional and two-dimen-
sional arrays.
This MAT statement multiplies each element of array A by 2 (a scalar) III. MAT 8 = (2) *A
and stores the products in the corresponding locations of array B.
Arrays A and B must have the same dimensions. On most computer
systems, the parentheses around the scalar are required, and on
some systems the scalar must be to the left of the array name. The
scalar may be a number, a variable, an expression, a subscripted
variable, or a library function, as long as it represents a single value.
The statement may be used on both one-dimensional and two-
dimensional arrays.
MATC=A*B multiplies matrix A by matrix B, using matrix multiplica- IV. MAT C=A *8
tion and stores the products in matrix C. In this type of multiplication,
the number of columns in matrix A must be the same as the number of
rows in matrix B.
A B
2 X 3~3 X 4
The same
The result is a 2x4 matrix that has the same number of rows as matrix
A and the same number of columns as matrix B.
MATRIX STATEMENTS AND LIBRAR Y FUNCTIONS 393
10 [11M A(2,3),B(3,4),C(2,4)
2fJ MAT READ A,B
30 DATA 1,2,3,4,5,6
40 [lATA 9,8,7,6,5,4,3,2,1,O,1,2
50 MAT C=A*B
60 PRINT
70 MAT PRINT A;B;C;
99 END
FWN
1 2 3
4 5 6
9 8 7 6
<~
d 4 3 2
1 0 1 2
22 16 16 16
6} 52 49 46
Special Functions
After execution of this statement, the rows and columns of matrix A I MAT B TRN (A)
are transposed (interchanged) and the result is stored in matrix B. I f ' =
matrix A has 2 rows and 3 columns, matrix B will have 3 rows and 2
columns.
UI DIM A(2,3),B(3,2)
20 MAT READ A
30 DATA 1,2,3,4,5,6
40 MAT B=TRN(A)
50 PRINT
60 MAT PRINT A;B;
99 END
rWN
1 2 3
4 5 6
1 4
394 PROGR AMM ING IN BASIC
2 5
3 6
The MAT INV statement finds the inverse of a matrix, if its inverse II. MAT B= INV(A)
ex ists . The inverse is a particular matrix which, when multiplied by the
original matrix, yields the identity matrix . That is,
A*B=B*A=I
where I is the identity matrix. All three matrices must be square .
Some of the elements of the inverse may be close approximations.
(See Footnote 3 on page 391 .)
10 DIM A(2,2),B(2,2)
20 MAT REAII A
3P.1 DATA 1,2,3,4
40 MAT B=INV(A)
51:'1 PRINT
60 MAT PRINT A;B;
99 END
RUN
1 2
3 4
--2 1.
1.5 -.5
10 DIM A(2,2),B(2,2),C(2,2)
20 MAT READ A
31:'1 DATA 1,2,3,4
40 MAT B=INV(A)
50 PRINT
60 MAT PRINT A;B;
70 PRINT 'THE DETERMINANT OF A I5:';DET
99 ENII
MATR IX STATE M ENT S AND LIB RARY FUN CTIO N S 395
RUN
1 2
3 4
-2 1
1.5 -.5
If your computer does not support the DET function , multiply the
original matrix by its inverse . The resu lt should be the identity matrix
(or a close approximation ).
10 DIM A(2,2),B(2,2),C(2,2)
20 MAT READ A
30 DATA 1,2,3,4
40 MAT B=INV(A)
50 PRINT
60 MAT PRINT A;B;
70 MAT C=A*B
80 MAT PRINT C
99 END
RUN
'")
l .:..
3 4
··-2 1
1.5 -.5
1 0
0 1
40 MAT A=ZER(2,3)
~jl!J MAT B=CON(3,4)
61!J MAT C=IDN(3,3)
70 PRINT
130 MAT PRINT A;B;C;
99 END
(a) 10 [I I M A ( 3 , 2 )
2~J MAT INPUT .. . . . .. . . ......... . . . .. . (Page 386)
(c) 10 DIM A ( 2 , 3 )
(d) 10 [I I M A( 3 , 4 )
45 LET C=4
50 MAT B=C*A .... . .... . ...... . . .... . (Page 392)
(c) Multiply the elements of matrix B by the scalar 3 and store the
products in matrix D.
(d) Transpose the rows and columns of matrix A and store the
result in matrix E.
(e) Set all the elements of matrix B to 1.
(f) Print matrices C, D, E, and the new B matrix with headings as
shown in the following RUN . Remember, the output produced
by your computer system may not be exactly the same as the
one shown below.
RUN
SUBTRACTION
333
~5 3 3
SCALAR MULTIPLICATION
12 15 18
21 24 27
TRANSF'OS I TI ON
1 4
c:.
2 _I
INITIALIZATION
111
111
20 MAT INPUT A
MATRIX STATEMENTS AND LIBRAR Y FUN CTIONS 395
25 MAT B=A
30 MAT A=ZER(3,4)
or
2.
Ie DIM A(2,3),B(2,3),C(2,3)
221 DIM D(2,3),E(3,2)
30 MAT READ A,B
421 DATA 1,2,3,4,5,6
50 DATA 4,5,6,7,8,9
621 MAT C=B-A
7£1 MAT D=(3)*B
821 MAT E=TRN(A)
(~[1 MAT B=CON
10fl PRINT
110 PRINT ·SUBTRACTION"
128 MAT PRINT C;
130 PRINT ·SCALAR MULTIPLICATION"
1421 MAT PRINT [I;
150 PRINT "TRANSPOSITION"
160 MAT PRINT E;
1721 PRINT "INITIALIZATION"
1821 MAT PRINT B;
999 END
10 LET X=5.17
20 PRINT
30 PRINT X,INT(X)
99 END
RUN
5.17 5
Notice that the decimal part is removed. Generally, the rules are as
follows .
1. If the argument is positive, the decimal part is discarded and the
resultant number is smaller than the argument. In the above
example, 5 is smaller than 5.17.
2. If the argument is negative , the computer may do one of two
things :
(a) Remove the decimal part. The number - 5.1 7 becomes - 5.
(b) Change the number to the next lower integer. The number
- 5.17 now becomes - 6.
Here are some more examples.
X INT(X)
642 642
7094 7
o o
.025 eJ
-934 -934
- 49.321 - 49 or - 50
-.067 oor-1
RUN the following program and see what your computer produces
when the argument is negative.
Hl LET X=-49.321
20 LET Y=-.067
3~ PRINT
40 PRINT X,INT(X)
402 PROGRAMMING IN BASI C
The INT function can be used to isolate digits from numbers. The idea Isolating digits
is to get the digit you want in the position that is immediate ly to the left
of the decimal point (in the units position) , then discard the decimal
part. First a digit will be separated from a whole number and then
digits will be separated from two decimal numbers.
1. This example separates the digit 3 from the whole number 349.
10 LET N=349
2£1 LET H=INT(N/1~~)
:HI PRINT
4£1 PRINT H
99 END
RUN
3
20 LET H=INT(N/1~~)
= INT(349/ 100)
= INT(3.49)
=3
RUN
4
Line 20 moves the decimal two places to the right so that the
decimal point is just before the 4.
MATRI X ST ATEME NTS AN D LIBRAR Y FUN CT IO NS 403
20 LET M=N*HH'J
= .23456*100
= 23.456
3~ LET T=INT«M-INT(M»*10)
= INT((23.456 - INT(23.456))*1 0)
= INT((23.456- 23)*1 0)
= INT(.456*1 0)
= INT(4.56)
=4
1~ LET N=1.23456
20 LET M=N*100111
3~ LET T=INT«M-INT(M»*10)
4111 PRINT
5~ PRINT T
99 ENII
RUN
5
Line 20 moves the decimal three places to the right so that the
decimal point is just before the 5.
2~ LET M=N*HJI1II1I
= 1.23456*1000
= 1234.56
3~ LET T=INT«M-INT(M»*ll11)
= INT((1234.56-INT(1234.56))*1 0)
= INT((1234.56- 1234)*10)
= INT(.56*1 0)
= INT(5.6)
=5
113LET N=.264
2e LET M=N*11313
313LET T=INT«M-INT(M»*113)
413PRINT
513PRINT T
99 END
RUN
Notice that the computer gives an output of 3. The error occurs when
the INT of M (which is 26) is subtracted from M (which is 26.4) The
computer arrives at a difference of .399999999 which , when multi -
plied by 10 and truncated by the INT function , results in 3. You can
safeguard the desired result by increasing the difference by a small
amount. If you add , for example , .00001 to .399999999 you get:
.399999999
+ .00001
.400009999
Multiplying .400009999 by 10 and then using the INT function on the
product gives 4 . Statement 30 should now look as fol lows.
Note that the amount added to .399999999 need not be .00001 . It can
be as large as .1 or as small as .000000001 on some computers .
The INT function can check to see if one integer will divide evenly into Checking division
another (in other words , there will be no remainder ). The statement
that performs this operation is :
xx IF I/J=INT(I/J) THEN xx
where I is the integer to be tested and J is the divisor . Here are a few
examples .
1. 1= 8
J=2
2. 1=9
J=2
XX IF I/J = INT(I/J) THEN xx
9/2 = INT(9/2)
4.5 = INT(4 .5)
4.5 =4
This statement is not true ; therefore , 2 does not divide evenly
into 9 .
Care must be taken when one of the numbers is negat ive , since
this will give the INT function a negative argument. If your computer
changes a negative decimal number to the next lower integer when it
uses the INT function (- 5.17 becomes - 6), you must add 1 to the
result of the INT function . The example shown below divides 2 into - 9
and increases the result of the INT function by 1 .
3. 1=-9
J=2
ln Chapter Six (page 248), you write a program for a review problem Rounding off numbers
that involved compound interest. The program produced numbers
with more than two decimal places . At that time , it was mentioned that
these figures could be rounded off to the nearest cent and that the
methods for rounding off would be shown in later chapters.s Here is
the formula that performs the rounding off function .
INT(N *1 OjD+ .5)/1 OjD
N is the number to be rounded and 0 is the desired number of
decimal places. Shown below are examples of rounding off the
number 4.5678 to various decimal places-to the nearest tenth,
hundredth, thousandth, and to the nearest whole number.
5 . O utput can also be rounded by the PRINT USING statement. Th is is covered in the
next chapte r.
406 PROGRAMMING IN BASI C
H= INT(N/100)
= INT(349/ 100)
= INT(349)
=3
RUN
8 5 3
2 6 7
9 1 3
This is how the computer executes lines 50, 60 , and 70 using the
value 853 . Move the 8 to the units position.
Algebraically
521 LET H=INT(N/1~B) 853
100 = 8.53 = 8
= INT(853/100)
= INT(8.53)
=8
408 PROGRAMMING IN BASIC
RUN
853 358
267 762
913 319
1.
3. Checking Division
10 PRINT
20 LET N=468
~50 LET J=2
40 IF N/J=INT(N/J) THEN 7121
50 PRINT "DOES NOT DIVIDE EVENLY"
621 GO TO 99
7121 PRINT "DIVIDES EVENLY"
99 END
RUN
DIVIDES EVENLY
5.
01 REM N--NUMBER
~2 REM H--HUNDREDS POSITION
I:B REM T--TENS POSITION
1Z14 REM U--UNITS POSITION
05 REM f~--REVERSED NUMBER
HI PRINT
20 FOR 1=1 TO 3
30 READ N
4~ DATA 853,267,913
50 LET H=INT(N/100)
60 LET T=INT«N-H*100)/10)
70 LET U=INT(N-H*100-T*10)
80 LET R=U*100tT*10tH
90 PRINT N,R
100 NEXT I
S'("l9 END
30 LET A=INT(N*RNIt(l)tI)
....
c.._ _ _ Different argument
MATRIX STATEMENTS AND LIBRARY FUNCTIONS 413
r~lJN
.681657766
.128694532
.31534812
.715774119
3.22490736E-£I3
.85595318'7
Notice that the random numbers in the above RUN each have nine
digits, except for a number that ends with a zero (insignificant zeros
are not printed) . Also , numbers that are too small are converted to E
format. Here is another RUN from the same program. Is the output the
same?
RUN
.937648934
.£127785757
.18eS31S34
.37'7229542
.759118247
.4433£17551
7. Note that lines 30 and 40 could have been combined into one statement: 30
PRINT RND(1) .
414 PROGRAMMING IN BASIC
8. The midpoint .5 can be included in either "between r/J and .5" or "between .5 and
1" .
M ATRI X STATEMENTS AND LIBRAR Y FUNCTIONS 415
HJ LET N=H:l
28 LET 1=1
30 LET R=INT(N*RND(l)tI)
40 PRINT
5~ PRINT R
99 END
"Number" of numbers: (J-I)+1 = (100-1)+1 = 99+1 100 Generating whole numbers between
First endpoint : 1 1 and 100 inclusive
10 LET N=ll11l11
20 LET 1=1
38 LET R=INT(N*RND(l)tI)
48 PRINT
5~ PRINT R
99 END
416 PROGRAMMING IN BASIC
10 LET N=6
20 LET 1=1
30 LET R=INT(N*RND(l)tI)
40 pr~INT
50 PRINT R
99 END
" Number" of numbers : (J-I)+ 1 = (26- 7)+ 1 = 19+ 1 = 20 Generating whole numbers between
First endpoint : 7 7 and 26 inclusive
10 LET N=2~
20 LET 1=7
3~ LET R=INT(N*RND(l)tI)
40 PRINT
5~ PRINT R
99 END
DIE 1: 6 DIE 2: 4
BOTH DICE: 10
DIE 1: 5 DIE 2: 2
BOTH IIICE: 7
DIE 1: 4 DIE 2: 3
BOTH DICE: 7
418 PROGRAMMING IN BASIC
HEADS: 6
TAILS: 4
9. Your computer may require a different argument for the RND function.
MATRI X STATEMENTS AND LIBRARY FUNCTIONS 419
2.
01 REM H--HEADS
02 REM T--TAILS
03 REM R--RANDOM NUMBER
10 LET N=2
20 LET 1=1
3~ LET H=0
40 LET T=0
50 PRINT
60 FOR K=l TO 10
70 LET R=INT(N*RND(l)tI)
80 IF R=2 THEN 110
90 LET H=Htl
100 GO TO 120
:l10 LET T=Ttl
120 NEXT K
130 PRINT "HEADS:";H
:l40 PRINT "TAILS:";T
999 END
Problem 2
H HEADS
T - TAILS R - RANDOM NUMBER
( start)
C§
420 PROGRAMMING IN BASIC
Print
H End
T
Generate
Random No.
R=INT
(N*RND(1)+ I)
Increment
Taiis
T=T+1
Increment
Heads NEXTK
H= H+1
Function Description
ABS(X) Calculates the absolute value of X.
ATN(X) Calculates the arctangent of X*
COS(X) Calculates the cosine of X*
EXP(X) Raises e to the power of X**
INT(X) Retains the integer part of X.
LOG(X) Calculates the natural logarithm of X (X must be positive).
RND(X) Generates random numbers.
SGN(X) Determines the sign of X.
SIN(X) Calculates the sine of X*
SQR(X) Calculates the square root of absolute X.
TAB(X) Tabulates to the appropriate column.
TAN (X) Calculates the tangent of X*
ATN, COS, SIN, and TAN are trigonometric functions ; EXP and LOG
are algebraic functions; ABS, SGN, and SQR are primarily mathe-
matical functions but may occasionally be used in business applica-
tions. In this section the ABS, SGN, and SOR functions will be
explained. The INT and RND functions have already been discussed;
the TAB function will be covered in the next chapter .
This function calculates the absolute value of a number, which is the ABS(X)
number without a sign regardless of whether the number is positive
or negative .
Thus: ABS(12) = 12
ABS(0) = 0
ABS( - 1 2) = 12
10 READ X,Y,Z
20 [tATA 12,I!)'-12
~~0 F'R I NT
40 F'RINT ABS(X),ABS(Y),ABS(Z)
99 END
FWN
12
The SGN function determines the sign of a number. The function SGN(X)
returns a 1 if the number is positive, a 0 if the nu mber is zero, and a - 1
if the number is negative.
Thus: SGN(12)= 1
SGN(0)= 0
SGN(-12)= -1
HI READ X,Y,Z
2~ DATA 12,0,-12
30 PRINT
40 PRINT SGN(X),SGN(Y),SGN(Z)
99 END
RUN
1 -1
This function calculates the square root of a number. The square root SOR(X)
of a number is a value that yields a given quantity when the value is
multiplied by itself. For example , 5 is the square root of 25 because
5x 5= 25 . The argument of this function must be positive.
10 LET X=25
20 PRINT
3~ PRINT X,SGR(X)
99 END
RUN
25 5
RUN
THE SIGN OF A IS: 1
THE RESULT IS: C'
~I
RUN
4 2
9 3
16 4
25 5
36 6
49 7
II. Write a program that reads in six non-zero numbers and adds
only the positive values. Use the library function SGN to check
the sign of the number. If it is positive, add the number; if it is
negative, skip the number.
RUN
.,
.'- 2
4 6
6 12
MATRIX STATEMENTS AN D LIBR ARY FUN CTIO NS 425
Problem II
T - TOTAL
N NUMBER READ IN
S - SIGN OF THE NUMBER
Calculate
Total Positive
Numbers
T=T+N
Print
N,T
End
~ NEXT I
3 . 90 PRINT N,S
4. 100 NEXT I
II.
01 REM T--TOTAL
02 REM N--NUMBER READ IN
03 REM S--SIGN OF THE NUMBER
10 LET T=0
20 PRINT
30 FOR 1=1 TO 6
40 READ N
50 DATA 2,-3,4,-5,6,-7
60 IF SGN(N)=-l THEN 90
70 LET T=TtN
80 PRINT N,T
90 NEXT I
99 END
A SHORT SUMMARY
BASIC provides a number of features that greatly facilitate the writing
of programs. One of these features , although not supported by all
computer systems, is the handling of arrays by the use of MAT
statements. These special statements instruct the computer to per-
form operations on an entire array, rather than on one element at a
time . Thus, programs are much shorter, since FOR/NE XT loops are not
required. Section 9.1 introduced the following MAT instructions .
Input/Output
MAT READ A, MAT INPUT A, MAT PRIN T A
Assignment
MAT B= A, MAT A= ZER, MAT A= CON, MAT A= ION
Mathematical
MATC=A+B, MATC=A-B, MATB=(2)*A, MATC=A*B
Special
MAT B=TRN (A), MAT B= INV(A)
BASIC also offers a number of library (standard or built-in) functions.
These are prewritten routines that may be "called" upon to perform
certain operations. One of the functions available on most computer
systems is the INT function This library function retains the integer
part of a number and discards the decimal part . Three uses of the INT
function were discussed in Section 9.2 . Each is listed below along
with a sample statement.
MATRI X STATEMENTS AND LIBRAR Y FUN CTIONS 427
2. Checking Division
This statement checks whether or not one integer divides exactly into
another.
xx IF I/J=INT(I/J) THEN xx
3. Rounding Off Numbers
The general formula for rounding off numbers is:
INT(N *1 OiD+ .5)/1 DiD
where N is the number to be rounded and D is the number of desired
decimal places.
Another library function available in the BASI C language is the RN D
function. This built-in function, discussed in Section 9.3, generates a
pseudo-random number. Random numbers are frequently used to
simulate procedures or to test new programs . Since the numbers
generated by the RND function fall between eJ and 1, they are usually
converted to whole numbers so that they are in a more acceptable
form. The formula for this conversion is:
INT(N*RND(l )+1)
where I is the first endpoint (the lowest number wanted) and N is the
"number" of numbers in the range. The latter value is calculated by
subtracting the first endpoint from the second and adding 1: (J-I)+l.
The argument of the RND function varies greatly among computer
systems. It's best to check your manual to find out what your com-
puter requires.
A number of other library functions are available in the BA SIC
language. These include the trigonometric functions ATN , COS, SIN ,
and TA N; the algebraic functions EXP and LOG; and the mathematical
functions A BS, SGN , and SOR. The last three functions were discussed
in Section 9.4 . The A BS function calculates the absolute value of a
number ; the SGN function determines the sign of a number ; and the
SOR function finds the square root of a positive number .
10 [11M A(3,2)
20 PRINT
30 FOR 1=1 TO 3
10. Unle ss an alternative meth od is specified, any question or problem that involves
a BAS IC feature not s uppo rted by your computer system may be omitted.
428 PROGRAMMING IN BASIC
40 FOR J=l TO 2
50 READ A(I,J)
60 DATA -,-,-, .... (6 items of data)
7~ PRINT A(I,J);
80 NEXT J
90 PRINT
100 NEXT I
999 END
10 DIM A(3,4),B(3,2)
20 MAT READ A,B
30 DATA -,-,-, ••••
40 DATA -,-,-, ••••
99 END
A B
9 8 7 6 1 2
5 432 3 4
1 (/)98 5 6
3. Suppose the MAT INPUT statement is used to store the data items
1,2,3,4,5,6 in the 2x3 matrix A. To which variable of A is each item
assigned? (Hint: A(1, 1)= 1; A(1 ,2)= 2; etc.)
4. (a) What output does your computer system produce for the
following program?
10 DIM A(2,3),B(2,6),C(3)
20 MAT READ A,B,C
30 DATA 15,25,35,45,55,65
40 DATA 1,2,3,4,5,6,7,8,9,0,1,2
50 DATA 10,20,30
60 PRINT
70 MAT PRINT A,B,C
99 END
(b) What would the output look like if the items in the MAT PRINT
statement were separated by semicolons instead of by com-
mas with a semicolon following the last item?
MATRIX STATEMENTS AND LIBRARY FUNCTI ONS 429
HI DIM A(3,4),B(4,3)
40 MAT B=A
(b) 1.0 DIM A(4,3)
40 MAT A=CON(S,4)
48 MAT A=IIIN
430 PR OGRA MMIN G IN BAS IC
40 MAT C=A*B
1£1 PRINT
2£1 FOR 1=1 TO 7
30 READ X
4£1 DATA 493,6.714,£1,.£139
50 DATA - S82,-36.123,-.£I42
6£1 PRINT X,INT(X)
70 NEXT I
99 END
12 . Checking Division
Write a program that checks whether or not 3 divides evenly into
367. Print DIVIDES EVENLY if the division is exact ; print DOES
NOT DIVIDE EVENLY if the division is not exact.
13 . Rounding Off Numbers
(a) Write a program that rounds off 27 .15 to the nearest tenth
(27 .2) .
(b) Write a program that rounds off 27.156 to the nearest hun-
dredth (27.16).
(c) Write a program that rounds off 27 .1567 to the nearest
thousandth (27 .157) .
(d) Write a program that rounds off 19.85 to the nearest whole
number (20).
14 . What is the purpose of the RND function?
15. State two reasons why random numbers generated by the RND .
function are not truly random .
16. The RND function produces numbers that are evenly distributed
between'/) and 1. Explain the meaning of this statement .
17 . For each of the fo ll owing , code a program that generates a
random number.
(a) A decimal number between'/) and 1.
(b) A whole number between 1 and 100 inclusive.
(c) A whole number between 1 and 9 inclusive .
(d) A whole number between 8 and 24 inclusive .
(e) A whole number between 23 and 36 inclusive .
18. What output will the following programs produce?
(a) HI PRINT
20 FOR 1=1 TO 3
3~ READ X
40 DATA 14d'l,-14
5~ PRINT X,ABS(X)
6~ NEXT I
99 END
(b) 1~ PRINT
2~ FOR 1=1 TO 3
3f'l REA[I X
4~ DATA 14":),-14
5~ PRINT X,SGN(X)
6~ NEXT I
99 END
(c) if'l LET X=49
20 PRINT
PRINT X,SQR(X)
3f'l
99 END
432 PROGRAMMING IN BASIC
Programming Problems
1. Chapter Eight presented a number of review problems that
involved two storerooms in which various styles of shoes were
stored . Each room had three shelves with the shelves partitioned
into three sections so that it was possible to treat each storeroom
as a matrix. In Problem 7, page 377, the supervisor wanted to
replenish the stock in the storage locations that had two pairs of
shoes or less. Suppose an order has been filled and that these
locations now have eight pairs of shoes each. Write a program
that will show this change for both storerooms.
Storeroom A Storeroom B
Sec 1 Sec 2 Sec 3 Sec 1 Sec 2 Sec 3
Shelf 1 1 3 2 Shelf 1 4 0 3
Shelf 2 5 4 0 Shelf 2 3 1 2
Shelf 3 2 3 5 Shelf 3 5 4 3
RUN
STOREROOM A
B 3 8
..,.
.J 4 8
8 3 5
STOREROOM B
4 8 3
3 8 8
5 4 3
r
Problem 1
A STOREROOM A
B - STOREROOM 8
DIM
A ,S
NEXT J NEXT L
NEXTI NEXT K
434 PROGRAMMING IN BASIC
RUN
1 1130 1140 1150
2 1276.9 1299.6 1322.5
3 1442.9 1481.54 1520.88
4 1630.47 1688.96 1749.01
RUN
17 IS A PRIME NUMBER
25 IS NOT A PRIME NUMBER
29 IS A PRIME NUMBER
RUN
17 IS A PRIME NUMBER
25 IS NOT A PRIME NUMBER
29 IS A PRIHE NUMBER
Problem 4
N - NUMBER TO BE TESTED J INDEX USED AS THE DIVISOR
MATRIX STATEMENTS AND LI BRARY FUNCTIONS 437
Yes Print
N (not
prime)
J> SQR(N)
NEXT I
Yes
NEXT J
438 PROGRAMMING IN BASIC
RUN
[lAYS: 11
HOURS: 13
MINUTES: 46
SECONDS: 4111
Problem 7
N NUMBER OF POSSIBLE MOVES P2 - SECOND PLAYER
I FIRST ENDPOINT R1 - RANDOM NO . FOR 1 ST PLAYER
P1 FIRST PLAYER R2 - RANDOM NO . FOR 2ND PLAYER
Start
First Player
Random No.
R1=INT
(N*RNO(1)+I)
Total Moves
P1=P1+R1
Second Player
Random No .
R2= INT
(N*RNO( 1)+ I)
Total Moves
P2= P2+ R2
NEXT J
440 PROGR A MMIN G IN BAS IC
8 . Using the index of a FOR statement as your data, find the square
roots of the numbers from 1 to 10 inclusive. Round off each
square root to:
(a) The nearest tenth .
(b) The nearest hundredth.
(c) The nearest thousandth .
Use two FO R/NE XT loops :
(i) The outer loop generates the data.
(ii) The inner loop uses the inde x of its FO R statement as the
number of required decimal places . Code this variable in the
statement that finds the square root and rounds off the result.
Your statement should look as follows.
xx LET S = INT(SOR(N)* 10tD+.5)/ 10tD
whereS is the square root rounded off to the required number
of decimal places, N is the data (the index of the outer
FO R/NE XT loop), and D is the number of decimal places (the
index of the inner FOR/ NEXT loop) .
Print the number and the three versions of its square root on one
line widely spaced.
RUN
,.,1
.:..
1
1 .4
1
1 .41
1
1.414
3 1 .7 1.73 1. 732
4 2 2 2
5 2.2 2.24 2.236
6 2.4 2.45 2.449
7 2.6 2.65 2.646
8 2.8 2.83 2.828
9 3 3 3
HI 3.2 3.16 3.162
Problem 9
N - " NUMBER " OF NUMBERS IN THE RANGE
I FIRST ENDPOINT
C - COUNTER
D1 - DIE NUMBER ONE
D2 - DIE NUMBER TWO
D - TOTAL OF BOTH DICE
( start)
Print
Blank line End
C
J < =50
Generate
Random No.
D1=INT
(N*RND(1)+ I)
Generate
Random No .
D2=INT
(N*RND(1)+I)
Calculate
Total Rolled
D= D1+D2
Increment
Counter
C=C+1
NEXT J
442 PROGRAMMING IN BASIC
RUN RUN
525
HOURLY RATES
11.38
12.33
13.13
ADVANCED OUTPUT FEATURES 443
EN ADVANCED
OUTPUT FEATURES
A. After completing this chapter, you should be able to write BAS IC
programs to format output by means of:
1. The TAB function .
2. The PRINT USING and IMAGE statements .
B. In addition, you should be able to:
1. Display and label a PRINT statement that uses the TAB function.
2. Write short BASIC programs using the TAB function to produce
the following :
(a) Positive and negative signs before numbers.
(b) Strings and numbers on one output line.
(c) Dollar signs before amounts.
(d) Centred headings.
(e) Numbers centred under headings.
3. Produce the output of programs.
4. (a) State the purpose of the PRINT USING statement.
(b) Display and label a PRINT USING statement.
5. (a) State the purpose of the IMAGE statement.
(b) Display and label an IMAGE statement.
6. Write short BASIC programs using the PRINT USING and IMAGE
statements to produce the following :
(a) Centred headings.
(b) Numbers centred under headings.
(c) Positive and negative signs before numbers.
(d) Dollar signs before amounts .
(e) Whole numbers aligned in a column.
(f) Numbers aligned by decimal points.
(g) Numbers rounded off to a specific number of decimal
places.
(h) Numbers expressed in scientific notation.
7. (a) Summarize what happens when more positions are
reserved in a field of an IMAGE statement than are needed
for:
(i) A string .
(ii) A number that contains a decimal point.
(b) Produce the output of a program involving (i) and (ii).
8. (a) Summarize what happens when a field specification is too
narrow for:
(i) A string.
(ii) A number.
(b) Produce the output of a program involving (i) and (ii).
9. (a) Summarize what happens when there is an insufficient
number of field specifications for the number of items to
be printed.
(b) Produce the output of a program involving (a).
444 PROGRAMMING IN BASIC
10. (a) Summarize what happens when there are more field
specifications than items to be printed.
(b) Produce the output of a program involving (a).
30 PRINT ( 16)
l A
TAB
i
Statement
i
PRINT
r i
Key word Argument which spec-
l'
Value to be
number instruction meaning to ifies the column in printed
tabulate which the first charac-
ter of the item is to be
printed
The TAB instruction must precede the item to be printed and must
consist of the key word TAB followed by an argument (in parentheses)
which specifies the column in which the displayed item is to begin.
The argument may be expressed as a constant, a variable, or an
arithmetic expression. Its value must not be negative. The argument
is usually followed by a semicolon,1 which is followed by the item to
be printed. Each tabulated position is counted from the current line's
left-most column, which is considered to be the zero column on the
majority of computers. For the programs in this book, the left-most
column is numbered zero.
In the previous chapters, statements consisted of 40 characters or
less. When a statement contains more than 40 characters, the extra
characters can be coded on the next line starting in the left-most
column. Thus, the number of PRINT statements can be reduced by
using one long PRINT statement rather than several short ones to
obtain the same line of output. Compare the following.
1. Some systems accept a comma after the argument, others require no punctuation .
In this book, the argument will be followed by a semicolon .
A DVANC ED OUTPUT FEATURE S 445
30 PRINT TAB(0);"HI"
30 PRINT TAB(12);"HI"
This statement has two TAB functions. Notice that the column
number in the second function specifies the position counted
from the left-most column, not from the item just printed. A
semicolon must be coded before each TAB function so that items
are printed on the same line. In the statement above, the semico-
lon referred to is the one before TAB(3). If a comma is used,
some systems ignore the TAB command and THERE would be
printed in the next available print zone. Thus, a computer that
allows 10 characters to a zone would print THERE in column 10.
4.
The first TAB command prints the first character of the string HI in
column 6. The second TAB command instructs the computer to
print the string THERE starting in column 3. Since the carrier has
already passed column 3, the instruction TAB(3) is ignored and
THERE is printed immediately after HI. On some computer
systems THERE is printed on the next line. In other words, the
print mechanism cannot move from right to left (it can not back-
space).
5.
HI LET A=12
2~ PRINT TAB(4);A
6.
10 LET B=-15
20 PRINT TAB(4);B
10 LET 1=7
20 LET J::30
30 PRINT TAB(I);"Hl";TAB(J-l);"THERE"
10 LET X=367
20 PRINT TAB(6);"X =";TAB(22);X
fi 1 1 1 11~11=1 1 1 11 1 1 1 1 1 1 1 1 121~
448 PROG RAMM ING IN BAS IC
The PRI NT statemen t in this program prints the string X = and the
value 367 on one line .
9.
4~ PRINT TAB(16.85);"HELLO"
10.
6~ PRINT TAB(49);"HELLO"
10 I 9
I I - First line
I I iH LLO Second line
10 PRINT TAB(7);"RETAIL";TAB(27);ITOTAL"
20 PRINT TAB(7);"PRICE";TAB(18);"TAX";TA
B(27);"COST"
1~ PRINT TAB(25);"RETAIL";TAB(44);"TOTAL"
2~ PRINT TAB(25);"PRICE";TAB(36);"TAX";TAB(44);"COST"
Ii! I I I I II I I I I I I 25 I 136 4~
R~
~~IE:
TO TA
I I I1 I I 1 1 1111 p~ I T CO ST
13. The TAB function can also be used to print dollar signs before
amounts .
40 LET 5=150.45
50 LET C=22.57
6~ PRINT "5ALES";TAB(7);"$";TAB(8);S;TAB
(21);ICOMMI55ION";TAB(33);I$";TAB(34);C
cen tred under these headings. The price of the second watch
has been changed to $50 .
A customer buys three watches , the first one priced at $55, the
second one priced at $50, and the third one priced at $40 . If a
sales tax of 5% is added to the retail price , what is the sales tax
and what is the total cost for each watch ?
(a) Use the READIDATA statemen ts to enter the retail price of
eac h watch.
(b) Use a trailer value to terminate input.
(c) Sales Tax = Retail Price x .05
(d) Total Cost = Retail Price + Sales Tax
~ 7 17 18 27
IREITA IL TO TAL
PR ICE TAX CO 5T
1 ~5 2. 75 57 .75
J
50 2.5 5~ .'.5
I 40 2 4.:..
TAB(17);T
17 18
TAX
'2 t 71s
t
I
Blank column
18
TAX
~
"- .75
iBlank column
ADVA NCED O UTPUT FEATURES 453
UI PRINT
221 FOR 1=1 TO 7
321 PRINT TAB(5+I);IT";
421 NEXT I
521 PRINT
60 FOR J=l TO 6
721 PRINT TAB(9); "T"
821 NEXT J
99 EN[t
RUN
TTTTTTT
T
T
T
T
T
T
121 PRINT
20 FOR 1=1 TO 6
454 PROGRAMMING IN BASIC
1 ******
******
2 *********
*********
3 **
**
4 **********
**********
5 *************
*************
6 ****
****
10 PRINT
20 FOR Y=6 TO -6 STEP -1
321 LET X=YT2
40 PRINT TAB(X);"*"
50 NEXT Y
99 END
RUN
*
*
*
*
*
**
*
* *
*
*
*
Line 20 - Se ts up a loop with the value of the inde x ranging from 6 to
-6.
Line 30 - Squares the value of the index and assigns the result to X.
Line 40 - Prints an asterisk in column X of a new line each time
through the loop.
- The first time through the loop , an asterisk is prin ted in column 36
(X=y2 = 6 2 = 36)
- The second time thro ugh the loop , an aste ri sk is printed in column
25 of a new line (x= y2 = 52 = 25) .
- The seventh time through the loop , an asterisk is prin ted in column
o of a new li ne (x = y2 = 02 = 0).
- The last time through the loop an asteris k is printed in column 36 of
a new line (x = y2 = (- 6)2 = 36) .
1.
2.
3.
4.
5.
0 8 24 J1
AM T
I~
0 -. O~IN I~ Tk~ E \1
6.
3. 2~ LE T H=40
30 LET R=19.S5
40 PRINT TAB(12);"HOURS";TAB(23);"RATE"
50 PRINT TAB(12);H;TABC22);R
5. 30 LET C=31
40 PRINT TAB(9);"AtB =" HAB(20);C
6. 10 LET 1=4
20 LET J=26
30 LET A=24
40 LET B=-B
50 PRINT TAB(I);A;TAB(J-I);B
7. 30 LET 1=17.64
40 PRINT TAB(I);"NAME"
III. This problem appeared in Chapter Five , page 159. Suppose your
consumption of electricity for each of the firs t three months of the
year was as follows.
Month Kilowatt-hours
1 1000
2 950
3 930
If the consumption charge is 3.5 cents per kilowatt-hour, what
would be the amount of your electric bill for each of the three
months?
(a) Use a FOR/ NEXT loop to keep track of the months .
(b) Use the RE ADIDATA statements to enter the data (kilowatt-
hours).
(c) Bill = Kilowatt-hours x Rate (.035)
(d) Centre the headings , data , and results, as shown in the
output below.
0 6 16 T-r-'
29= r
~ 1~ ~~ 35'
t:> 95~ 33 .2~
~ 93~ 32 .5~
458 PROGRAMMING IN BASI C
IV. Write a program that prints the letter Z six characters wide and
whose left-most characters are in column 9 .
(a) Use three FOR/NEXT loops :
(i) The first loop prints the top line of the Z .
(ii) The second loop prints the diagonal oftheZ . The index in
the FOR statement should run in a negative direction; that
is , the test value should be less than the initial value and
the step value should be -1 .
(iii) The third loop prints the bottom line of the Z . This loop is
similar to the one that prints the top line.
(b) The argument of the TAB function in each of the three loops
should be 8 plus the index of the loop . This places the left-
most characters of the Z in column 9. (Hint: You will need a
semicolon at the end of some of the PRINT statements to
produce characters on the same line .)
RUN
ZZZZZZ
Z
Z
Z
Z
Z
Z
ZlZZZZ
Problem IV
~
B C
459 459
ADVANC ED O UT PUT FEATURE S 459
NEXTI
NEXT J NEXT K
1. 40 PRINT TAB(0);24;TAB(16);-49
4. 40 PRINT TAB(3);INAHE";TAB(14);IADDRESS"
;TAB(28);ITELEPHONE"
5. 40 PRINT TAB(8);IAHOUNT"
50 PRINT TAB(8);"OF LOAN";TAB(24);"INTER
EST"
6. 40 PRINT TAB(8);IDEPOSIT";TAB(25);"BALAN
CE"
50 PRINT TAB(9);1400;TAB(25);12695
460 PROGRAM M ING IN BASIC
II .
1
2.
NUMBER : Column 10
RATE PER Column 23
OF HOURS: Column 9
HOUR: Column 25
3.
23
RA TE
HOURS : Column 12
RATE: Column 23
40: Column 12
19.55: Column 22
4.
5.
ADVANC ED OUTPUT FE AT URE S 461
A+B = : Column 9
31 : Column 20
6.
24 : Column 4
- 8: Column 22
7.
NAME : Column 17
8.
III .
IV.
:L0PRINT
20 FOR 1=1 TO 6
30 PRINT TAB(8tI); "Z";
40 NEXT I
50 PRINT
60 FOR J=6 TO 1 STEP -1
70 PRINT TAB(8tJ); "Z"
80 NEXT J
90 FOR K=l TO 6
100 PRINT TAB(8tK); "Z";
110 NEXT K
999 END
60 PRINT "SALES";TAB(7);"S";TABCS);S;TAB
(·21); "COMMISSION" nAB(33); "S" HAB(34);C
2 . If your compu ter system does not use an IM AGE sta tement but instead references a
string variable to which a formatted string (an image) has been ass igned, refer to the
examples on page 474 . You shou ld fir st re ad the mate rial in thi s section to become
famili ar with the terminol ogy . If the PR INT USI G statement is not available on yo ur
co mputer syste m , you may skip this section.
ADVANCED OUTPUT FEATURES 463
The PRI NT USING and IMAGE statements always work together. The
PRINT USING statement instructs the computer what to print and which
IMAGE statement it must use ; the IMAGE statement provides the format
(the pattern) . Here is the general form of the PRINT USING statement.
Comma Comma
r
Statement
r
PRINT
r
Indicates which
r r
Items to be printed
number instruction IMAGE statement
will be used
When the computer executes the above statement, it will use IMAGE
statement numbered 200 to print the two strings PROGRESS and
REPORT. This IMAGE statement may be coded as in the example
shown below. The hyphens in the statement represent spaces .
10 spaces 5 spaces
200
1 1
----------######## -----######
r
Statement Colon
r
Positions
1
Positions
number reserved reserved
for the string for the string
PROGRESS REPORT
Notice that the line number of the IMAGE statement is the same as the
one that follows PRINT USING. A colon must immediately follow this
line number .3 A series of number signs (#) designates the location of
an item and is referred to as a field specification The output for the
above PRINT USING and IMAGE statements will be printed as follows.
3. Some computer systems use a percent symbol (%) instead of a colon (:).
464 PROGRAMMING IN BASIC
More than one PRINT USING statement may reference the same
IMAGE statement. Shown below are a number of PRINT USING and
IMAGE statements and their output. Coding and output may differ on
your computer system and some of the features may not be available
Check your manual to find out which ones you can use and how they
are coded. The computer used for the programs in this book consid-
ers the left-most column as the zero column. This means that if there
are 10 spaces before an item , the printed item starts in column 10.
(This is actually the eleventh column when the left-most column is
considered column 1.)
Reserved Locations
Output
Line 15 instructs the computer to print the strings PRICE, TAX, and
COST, using IMAGE statement 110 as follows.
(a) Leave 7 spaces.
(b) Print the string PRICE starting in column 7. Notice that 6 posi-
tions have been reserved for only 5 letters. Excess columns to
the right of the string are left blank.
4 . A field is a sequence of positions set aside for a specific item of information, such
as a name or an address or an account number .
466 PROGRAMMING IN BASIC
Reserved Locations
Output
ru 5
1 I 1 i11JJ
Excess column
/\ Column left blank if the
left blank number is positive
1° 1 1111~1 115191
130: ____ •••••
-159
iExcess column
lett blank
35 LET K=1000
40 LET B=33
45 PRINT USING 150,K,"BILL",B
Reserved Locations
Output
Excess columns
i
Filled
left blank with two
number is zeros
positive
50 LET S=15B11!
55 LET C=185
60 PRINT USING 1611!,S,·COMMISSION",C
Reserved Locations
r
1611!: ____ SALES ___ ttt ___ tttttttt ___ tttt
COMMISSI 185
Field specification
too narrow for 1500
ADVANCED OUTPUT FEATURES 469
Output
Filled with
3 asterisks
In this example , the field specification is too small for the number
1500. Three positions have been reserved instead of five for the
four-digit number and its sign. Most computers will fill the three
available positions with three asterisks or with three number
symbols. Other computers will print the number with one asterisk
(*), or one number symbol (#), or one percent symbol (%) to the
left of the number. The field specification for the string COMMIS-
SION is also too narrow (eight positions have been reserved for a
ten-character string) . This time, the computer prints as many
characters as possible in the positions available, with the result
that the two right-most characters are discarded .
8. This is what happens when there are not enough field specifica-
tions in an IMAGE statement.
Reserved Locations
Output
First line
In this example, three items are to be printed, yet only two fields
have been designated . In this situation , the computer reuses the
IMAGE statement and prints the unformatted items on additional
lines. Some computer systems print the unformatted items on
the same line .
470 PROGRAMMING IN BASIC
Reserved Locations
Output
10 READ A,B,C
20 DATA 325,32,3
30 READ Al,Bl,Cl
4~ DATA 325,32.5,3.25
51?) PRINT
60 PRINT USING 90,A,Al
70 PRINT USING 90,B,Bl
80 PRINT USING 90,C,Cl
90: ___ •••• _____ •••••••
99 END
RUN
3 ")<:"
.:....J 325.00
32 32.50
3 3.25
ADVANCED OUTPUT FE ATU RE S 471
HI READ A,B,C
20 DATA 5.93852,67.4628,853.9254
38 PRINT
4~ PRINT USING 70,A
50 PRINT USING 70,B
60 PRINT USING 70,C
70: ___ $ttt.tt
99 END
RUN
$ 5.94
$ 67.46
$853.93
10 LET A=1234.S67
20 PRINT
40: ___
99 END
.t .......
30 PRINT USING 40,A
,! !,
RUN
1.234567Et03
472 PROGR A MMING IN BASIC
13. The PRINT USING and IMAGE statements can be used to print the
sign of a number . Here are three examples.
(a) When a plus sign is placed before a number's field specifica-
tion, most computers print a sign before the number. The
sign that is printed depends upon the number. If the number
is positive, the computer prints "+"; if the number is nega-
tive , the computer prints "- "
RUN
+52.64 -63.89
HI LET C=52. 64
20 LET D=-63.89
30 PRINT
40 PRINT USING 5P.l,C,D
5P.l! ___ -11.11 _____ -11.11
99 END
RUN
52.64 -63.89
1B LET E=-42.53
2B PRINT
AD VAN C ED O UT PUT FEATURES 473
RUN
42.53
10 LET S=69413.87
20 PRINT
3~ PRINT USING 4~,S
4~:___ SALES: _____ $tt,ttt.tt
99 END
RUN
SALES: $69,413.87
1~ LET N=158
2~ LET F$=" ____ ttttt"
30 PRINT
40 PRINT USING F$;N
99 END
10 LET N=-159
20 LET F$=" ____ ttttt"
30 PRINT
40 PRINT USING F$;N
99 END
10 LET N=94.6
20 LET F$=" ____ tttt.tt"
30 PRINT
40 PRINT USING F$;N
99 END
10 LET K=HJe0
20 LET B=33
30 LET B$="BILL"
40 LET F$=" __ K HOURStttttttt _____ ~ ___ ~ __ ttt.tt"
50 PRINT
60 PRINT USING F$;K,B$,B
99 ENII
ADVAN C ED OUTPUT FEATURES 475
The string BILL is assigned to the string variable B$. The reserved
location is delimited by percent signs and consists of five positions
(the percent signs are included In the count). BILL is left-justified,
which results in one space after the printed word .
HJ LET S=15~~
20 LET C=185
3~ LET C$="COMMISSION"
40 LET F$=" ____ SALES ___ t t t ___ ______ /. ___ tttt"
~
50 PRINT
60 PRINT USING F$;S,C$,C
99 END
FWN
Since the field specification for the number 1500 is too small, the
computer being used prints a percent symbol to the left of the
number. The word COMMISSION has as man y characters printed as
there are positions reserved .
10 LET S=1500
20 LET C=185
30 LET C$="COMMISSION"
40 LET F$=" ____ SALES ___ ttttt ___ /. ________ /."
50 PRINT
60 PRINT USING F$;S,C$,C
99 END
RUN
No location has been reserved for the value of C (185). The computer
reuses the image and prints the remaining item on the same line . The
first location reserved for a number will be used to print 185. Notice
that SALES is printed again. This is because SALES is coded as the
first item in the image .
7. Example 10, page 470 (Aligns numbers and decimal poin ts.)
HI READ A,B,C,D
20 DATA 5.93852,67.4628,853.9254,69413
30 LET F$=· ___ $tt,III.II·
40 PRINT
50 PRINT USING F$;A
60 PRINT USING F$;B
7~ PRINT USING F$;C
80 PRINT USING F$;D
99 END
RUN
$ 5.94
<} 67.46
$ 853.93
$69,413.00
10 LET A=52.64
20 LET B=-63.89
30 LET F$=" ___ +II.II _____ +tl.tl'
40 LET G$=· ___ -II.II _____ -II.tl"
50 PRINT
60 PRINT USING F$;A,B
7~ PRINT USING G$;A,B
99 END
HUN
+52.64 -63.89
-52.64 -;'-63.89
ADVANCED OUTPUT FEATURE S 477
The computer being used prints a plus sign before a positive number
and a minus sign before a negative number when a plus sign is coded
before a number's field specification. When a minus sign is coded
before a number's field specification, a minus sign is printed before a
positive number and two minus signs separated by a percent symbol
are printed before a negative number.
f1 7 18 27
R 11 A IlL TO TA
P RI T~X CO ST
'-- '- I
I~ I ~
1'.1
I~I.II
1
::-
l ~ 2.5~
$
$
2 '1'1"
2.0~,--
$
$
$
57 .71!'i
C' '')
.;J.:.
42 .01£l
.5~
1111 PRINT
2111 PRINT USING 3~
6. For computers that do not use an IMAGE statement, simply assign the image to a
string variable (usually before the PRINT USING statement) and reference the string
28 PRINT ' ______ TTTTTTT'
variable in the PRIN T USIN G statem ent. If your co mputer requires a numeric variable in 5B PRINT ' _________ T'
the PRIN T USIN G stateme nt (and since there is no numeric value to print in this
program), use regular PRI NT sta tements to format.
ADVANCED OUTPUT FE ATURES 479
RUN
TTTTTTT
T
T
1
T
T
T
Line 20- Prints the horizontal bar of the T using IMAGE state-
ment 30 to format. The left-most character is positioned in
column 6.
Lines 40 to 70 - These lines form a loop in which a column of 1's
is printed in print position 9.
7. If your computer does not use an IMAGE statement , refer to pages 473 through to
477 and to page 478 if you need help.
480 PROGRA MMING IN BASIC
(page 473)
.~ :1 .--
689
94
5
(Page 470)
~ 19
4. 69
Ie7 .25
131 7 . 1~3
I
21 91
:617 I~31
4 .6
87 .2
C'
• ..J
(Page 471)
(Page471)
121 6
+4 3. 62
-5 9. lis
(Page 472)
(Page 472)
10 LET 5=46327
20 PRINT
30 PRINT USING 40,"TOTAL SALES",S
40: _____ tttttttt _____ ttt
99 END
(Page 468)
99 END
(Page 469)
12. (a) What happens when there are more field specifications
than items to be printed?
(b) Show the output of the following program . Indicate the
columnar position of each item .
10 PRINT
20 PRINT USING 30,"NAME","ADDRESS"
30: _____ tttt _____ ttttttt _____ tttttt
99 END
(Page 470)
II . Rewrite the program you wrote in the "Yo ur Turn " unit of Section
10.1 on page 457. Use PRINT USING and IMAGE statements rather
than the TA B function to centre headings and amounts. Here is
the problem .
Suppose your consumption of electricity for each of the first
three months of the year was as follows.
Month Kilowatt-hours
1 1000
2 950
3 930
ADVANCED OUTPUT FEATURES 483
'0 16 1 -IT 16
l~
iM01NTH I '- " t IJsI-f+ - 1
IILIL
-:-
l 1I')1
~I _ l~ __
I-.
1 0~
..J~
3~
jj 5.§~
3. ·5
~. ~ ~
- - -
III. In Section 10.1 (Page 453) , a sample program was listed that
drew a bar graph (a histogram) that showed the sales amounts of
si x stores. Each bar had two lines of asterisks with each column
of asterisks in a bar representing $1 OOOworth of sales . The sales
represented on the graph were $6000, $9000 , $2000, $10000 ,
$13000, and $4000. Rewrite the program to include the follow-
ing changes.
(a) Do not print the number of the store .
(b) Start each bar in column zero.
(c) If your computer does not print a row of asterisks, use
another symbol.
(d) Replace the PRINT statement that contains the TAB function
with a PRINT USING statement and code the symbol of your
choice in an IM AGE statement B Code a semicolon at the end
of the PRINT US ING statement in order to print symbols con-
secutively on the same line. A following blank PRINT will
counteract the semicolon so that a new line of symbols can
be printed. Another blank PRINT will produce a blank line
between two bars. See the program on page 453 if you need
help .
RUN
xxxxxx
XXXXXX
xxxxxxxxx
XXXXXXXXX
8. Code the symbol as a string in a regular PRINT statement if your computer requires
a numeri c variable in the PRINT USING statement. (Noti ce that the program does not
print a numeric value )
484 PROGRAMMING IN BASIC
xx
XX
X>:XXXXXXXX
XXXXXXXXXX
XXXXXXXXXXXXX
XXXXXXXXXXXXX
XXXX
XXXX
10 prnNT
2~ PRINT USING 30,"DEPOSIT","BALANCE"
30! __________ ttttttt _____ ttttttt
99 END
9. If your computer does not use an IMAGE statement, assign images to string
variables and reference the string variables in the PRINT USING statements. If your
computer requires a numeric variable in the PRINT USING statement (and there is none
as in Problem 1), use the regular PRINT statement to format. The following show how
the programs must be written for one computer system. (Other examples are given
on pages 474 through to 477.) Your reference manual should show you how to code
the programs if your computer requires something different. The remaining pro-
grams for Problem I would be coded in a similar manner.
10 PRINT
20 PRINT ' __________ DEPOSIT _____ BALANCE'
99 END
ADVANC ED OUTPUT FE AT URE S 485
HI PRINT
20 PRINT USING 30
321: __________ DEPOSIT _____ BALANCE
99 END
2.
121 PRINT
20 PRINT USING 30,267,-489,316.25
30: ____ tttt ____ tttt ____ tttt.tt
99 END
3.
10 LET S=4000
2~ LET C=600
30 PRINT
421 PRINT USING 5B,S,C
521: __ SALES __ ft,ttt.tt ___ COM. __ fttt.tt
99 END
4.
U) READ A,B,C
20 DATA 689,94,5
30 PRINT
421 PRINT USING 70,A
5~ PRINT USING 70,8
621 PRINT USING 70,C
70: ___ tttt
99 END
5.
6.
7.
10 LET A=98765.432
20 PRINT
30 PRINT USING 40,A
40: _____ tt.t •••••• ,! !!
99 END
8.
HI LET A=43. 62
20 LET B=-59.18
30 Pf< I NT
40 PRINT USING 60,A
50 PRINT USING 60,B
60: ______ +•••
99 END
t.
9.
10. (a) When a field specification is too narrow for a string , the
computer prints as man y characters as possible in the
AD VANCED OUTPUT FE ATURE S 487
(b)
r, 1111~JIlJd1fffi[rrB or
(b)
21
$46327 First line
$ 925.L.-'..-J_
- S ec·ond line
or
1211
(b)
1211
II.
III.
A SHORT SUMMARY
Two features that have been added to the original BASIC language
(although not available on all computer systems) are the TAB function
and the PRINT USING and IMAG E statements. Both provide a program-
mer with greater flexibility in the spacing of output items. The general
form of a TAB function is as follows.
Semicolon
r
Statement
number
I
PRINT
instruction
r
Key word
meaning to
r
Argument which
specifies the
r
Value to be
printed
tabulate column in which
the first character
of the item is to
be printed
Comma Comma
will be used
490 PROGRAMMIN G IN BAS IC
10 spaces 6 spaces
100
1 1
----------## # # # #### ## -- ----### # #
r
Statement
number
I
Colon
I
Positions
re served for
I
Positions
reserved for
the string the amount of
TOTAL SALES sales
(f) 'iej IT
I
(a)
10 PRINT
20 PRINT TAB(6);IFAHRENHEIT"
99 ENII
(b)
UI PRINT
20 PRINT TAB(6);IFAHRENHEIT";TAB(26);"CE
LSIUS"
99 END
(c)
10 LET F=68
20 LET C=20
30 PRINT
492 PROG RA MMING IN BASIC
4~ PRINT TAB(6);"FAHRENHEIT";TABC26);"CE
LSIUS"
S0 PRINT
6~ PRINT TAB(9);F;TABC28);C
99 END
(d)
1~ PRINT
2~ PRINT TAB(15);"NAME";TABC6);"DEPT."
99 END
(e)
10 LET 1=10
2~ LET C=245
30 LET D=-63
40 PRINT
50 PRINT TABCI);C;TABCIt12);D
99 END
(f)
1~ LET J=14.93
PRINT
2P.l
30 PRINT TABCJ);"DISCDUNT"
99 END
(g)
10 LET C=-243
PRINT
2P.l
30 PRINT TAB(5);"A-B =";TAB(15);C
99 END
(h)
01 7
248
48
8
~
- ,-
-r- 'r-'
13 I
! 4.895
1 9'<'.~1~6
~~? ~1~8
n l l l l lll!~1
(h) Rewrite the program for Problem (g ). This time, code an
IM A GE statement that produces a minus sign when the num -
ber is negative but no sign when the number is positive.
Reserve only two print positions for the digits to the left of the
decimal point.
11. (a) What happens when there are more field specifications than
items to be printed?
(b) What is the output of the following program?
10 LET U=63.95
2~ F'RINT
30 PRINT USING 40,"UNIT F'RICE",U
40: ___ tttttttttt ___ $tt.tt ___ $ttt.tt
99 END
PROGRAMMING PROBLEMS11
For each of the first seven problems, write two programs
(i) One program that uses the TAB function to format output.
(ii) The other program that uses the PRINT USING and IMAGE state-
ments to format output.
Insert commas within numbers only in those programs that use the
PRINT USING statement. Except for Problem 4, code all strings in the
image. A statement may require more than one line. If you are using
an interactive system, you must press the RETURN key after each
typed statement, even when the cursor has automatically dropped to
the beginning of a new line. The RETURN key transmits the statement
to the computer's memory.
1. Write programs that print the initials of your name. You may use
any symbol you wish to print the letters. In the example below, an
E was used for the letter E; a B was used for the letter B, and an L
was used for the letter L.
RUN
EEEEEEE BBBBBB L
E B B L
E B B L
EEEEE BBBBBB L
E B B L
E B B L
EEEEEEE BBBBBB LLLLLLL
2. Write programs that will draw pictures. You may use the one
displayed below or any other drawing you wish to select.
RUN
++++++++++++++
+ ++++++++++ +
+ + + +
+ + + +
+ + + +
+ ++++++++++ +
++++++++++++++++++++++++
+ +
++++++++++++++++++++++++
++++++++++++++++++++++++
+ +
+ ~ ~ ~ ~ 0 ~ ~ B ~ +
+ ~ 0 B 0 0 B 0 0 B +
+ 000 0 0 0 0 0 0 +
+ 0 0 B 0 0 B B B ~ +
+ +
++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++
Write programs that calculate the balance in your bank account after
each transaction.
1 2~~
0 5 15 I
[E PO!=; IT I T'HD RAj"'" ALI NICEl i
"'"
I I
I
$:
I
1a·~ :S
I
ill $
aall:ll
,1, 9a:aj
1;2,1'~~I :
'$ 45~ $ 2,
Problem 3
B - BA LANCE
C - C ODE
A - A MOUNT
ADVANCED OUTPUT FEATURES 499
Calculate Calculate
Balance Balance
B=B+A B=B-A
I ~ I I ~I '~i31
$ ~1 ~14I~i .' 525
Y R
12. If you are using a computer that must reference a string variable instead of an
IMAGE statement, code the headings in the image. If your system requires a numeric
variable in the PRINT US I ~IG statement, use the ordinary PRINT statement to form the
headings
ADVAN CED OUTPUT FEATURES 501
4 11 2 6!J 28 I
"I I 'N VIE 5jTiMEINIT I: IS 4e'Be 1
NO. F YEAHIS RA TIE IN TER ES h'
1°1 •1 $1 41ee
121 . 11 414e
I 14 . 1~ : 1 4118e
16
18
..: e
. 13
. 14
.1 ~
• 6eer
•• 56e
I
0 '4 11 t2e 28
I N~ ESTM EN T
I : $ 4,
o B011I II I
INO. Iu F YEiA R5 I~' TE R'E1
ST
RiAjTE
I 1
4ee.
44el' ~r
10 . 110 $
12 . 111 $ ee
14 .1t2 $ 48 0 • ee
1 I
16
6 e . i:
.13 $ ~21e •
l ,t!
121~
.14
.15 • ~~~.
$
ee
ee
0 ) 7 II 23 r IJ
H
I I TOIT Al ,tW MB'E F:'OL LIS : 5'011
I
R liF
I I
NulH£liE R 7
1.1?J
N
T
II :IEr
11 I
III j J
Using the PRINT USING and IMAGE Statements
zl~ UM~B ER
A~
~ 23
TOT N OF RO oIL S :1 5 1?) I I
Problem 6
N " NUMBER" OF NUMBERS IN RANGE 01 - DIE NUMBER ONE
I FIRST ENDPOINT 02 - DIE NUMBER TWO
S NUMBER OF SEVENS o - TOTAL OF BOTH DICE
E NUMBER OF ELEVENS
( start)
Print
S,E End
ADVANCED OUTPUT FEATURES 503
A
502
J<=50
Generate
Random No.
D1=INT
(N*RND(1)+I)
enerate
Random No.
D2=INT
(N*RND(1)+I)
Calculate
Total Rolled
D=D1+D2
Accumulate
Number of 7's
S=S+1
Accumulate
Number of 11 's
E=E+1
NEXT J
RUN
*
**
* *
* *
** **
* *
** **
* **
**
*
* *
* *
* *
** *
*
* *
* *
* *
**
*
- - - - - - - - - -- --
9. In Section 10.1 (page 455), a program was listed that used the
TAB function to draw the graph of the function X=y2 Rewrite the
program. This time have the computer draw the x and y axis as
well as the curve of the function.
RUN
*
*
* *
*
*
*-- ----------------------------------
* *
*
*
*
*
506 PROGRAMMING IN BASIC
Problem 9
Start
Calculate
Square of Y
X=y2
NEXTY
NEXT J
Calculate
Square of Y
X=y2
NEXTY
SUBPROGRAMS 507
LEVE SUBPROGRAMS
A. After completing this chapter, you should be able to write BASIC
programs and complete skeletal BASIC programs that reference:
11.1 SUBROUTINES
Some procedures are used so frequently that it is more efficient to
write the routine only once and then call the routine from various
points within a program whenever the routine is needed. The
sequence of instructions is called a subprogram. One example is the
standard (library or built-in) function that was discussed in Chapter
Nine. This prewritten set of instructions forms part of the BASIC
language and may be called upon to perform a particular co mputation ,
such as finding the square root of a number. Another example of a
subprogram is the subroutine. The routine is not an integral part of
BASIC but is written by a programmer as a separate module or section
of the whole program. Thus , subroutines provide a method by which a
very long program can be broken down into a number of parts. One of
these parts must be the main program capable of communicating with
the va rious subroutines . The main program and the subroutines
make it possible for more than one programmer to be assigned to a
program, thereby reducing the amount of time it takes to write the
program and quite often reducing the number of errors in the first
RUN . Once these subroutines are RUNn ing, they can be saved on a
disk or on a cassette tape and loaded into the computer's memory
whenever they are required . In this way, subroutines that perform
specific tasks need to be written only once. Some of these tasks may
be the sorting or merging of names or numbers, the setting up of
frequentl y used headings, or the calculations of recurrent arithmetic
problems. To explain how subroutines are executed, the following
examples will be used . Each one is slightly different, yet each one
processes a main program and its subroutine (or subroutines) the
same way.
Line 50 calls the subroutine that starts at line 200. The coding of the
calling statement varies, depending on the computer being used.
SUBPROGRAMS 509
RUN
RUN
Line 50 calls subroutine 200; line 90 calls subroutine 300; and line
120 calls subroutine 400. After execution of one of the subroutines ,
control is transferred to the statement immediately following the
GOSUB that referenced the subroutine.
ADDs,~(--J...J
60 END
RUN
THE RESULT IS! 8
THE RESULT IS! 2
THE RESULT IS: 15
RUN
J
71 REM THAT PRINTS
80 GO SUB 2 U0 - - - - - - - - - - - - ,
90 END
2£10 REM THIS SUBROUTINE PRINTS ·
210 PRINT
22i!1 FOR J=1 TO 4
230 PRINT P(JH
24i!1 NEXT J
250 RETURN
RUN
4 3 1 2
431 2
514 PROGRAMMING IN BASIC
RUN
3 2 ~ 1
1 023
2 4 1 0
50 FOR J=l TO 4
60 READ R(I,J)
70 DATA 3,2,0,1
80 DATA 1,0,2,3
90 DATA 2,4,1,0
100 REM CALL THE SUBROUTINE
101 REM THAT PRINTS
110 GOSUB 200----------------~
120 NEXT J
130 PRINT
140 NEXT I
150 END
RUN
3 2 0 1
1 0 2 3
2 4 1 0
The GOSUB statement is an unconditional branch which transfers The GOSUB statement
control to a subroutine. Reference to a subroutine may not be made
by any other branching statement, such as a GO TO, an IFfTHEN, or an
ON GO TO, when the routine that is called ends with a RETURN .
Although each statement appears to perform a similar operation, only
the GOSUB remembers the point of reference so that control can be
automatically transferred to the appropriate statement of the calling
program when a RETURN is encountered. Some com puter systems
insist that the first statement of the subroutine be an executable
statement; others are not so particular. Line numbers in a subroutine
must be different from those in the calling program . However, the
GOSUB statement need not have a line number that is lower than the
number of the statement it is ca lling .
Nested subroutines must be in a hierarchical order. The first
subroutine may call the second subroutine but the second one may
not call the first. In other words, a subroutine may not reference its
calling program. The following program segment is invalid .
18~ RETURN
A RETURN statement must be placed at the end of each subroutine in The RETURN statement
order to transfer control automatically back to the calling program .
The point of return is the statement immediately following the GOSUB
that referenced the subroutine. In some versions of BASIC, this
statement must be executable .
Some computer systems support an ON .. GOSUB statement which is The ON . . . GOSUB statement 2
similar to the ON .. GO TO statement. The ON . .. GOSUB allows the
computer to select a subroutine from several incorporated in a
program. Here is an example of a program that uses an ON ... GOSUB
statement.
2. Try the above program If your computer system does not suppon the ON GOSUB
statement, you may omit this part of the chapte r
SUBPROGRAMS 517
RUN
SUBROUTINE 1
SUBROUTINE 2
SUBROUTINE 3
~1 REM K--COUNTER
02 REM D--NUMBER OF DECIMAL PLACES
~3 REM N--NUMBER OF ARTICLES
~4 REM Q--QUANTITY
05 REM P--UNIT PRICE
06 REM V--EXTENDED VALUE
o 2 15 31
QUA i l I Tyl I UNI T PRICE VALUE
~ $ i2 31 '~~ $ 214.65
8·1:5 $ 19.49 $ 165.617
8.5 $ 1~1 . 67 $ 133.21
./~70 NEXT K
80 GOSUB 200------------------~~ - Calls subroutine 200 to print the last
row of symbols.
~90 END
I
!
200 REM PRINT A FWW OF SYMBOLS~
I
I
210 FOR 1=1 TO M - Sets up a loop to print a row of symbols .
220 PRINT TAB(I);"B"; - Prints the symbol B .
I
23e NEXT I
240 PRINT - Counteracts the semicolon at the end
of line 220 so that the next symbol is
I
printed on a new line .
~25~ RETURN
~
l 220!BBBBBB
230 RETURN
300 REM PRINT LEFTMOST AND
301 REM RIGHTMOST SYMBOLS (2 LINES)
310 FOR J=1 TO 2 - Sets up a loop for 2 rows.
320 PRINT USING 330 - Prints the left-most 8 and the right-most 8
of a row using IMAGE statement 330.
330 t B______ B
340 NEXT J
350 RETURN
FWN
BBBBBB
B B
B B
[~BBBBB
B B
B B
BBBBBB
01 REM R--RECEIPTS
02 REM P--F'AYMENTS
03 REM B--BALANCE
RUN
RECEIPTS: 431
522 PRO GR AMM ING IN BAS IC
PAYMENTS: 16.5
BALANCE: ·4 14.5
01 REM R--RECEIPTS
02 REM P--PAYMENTS
~3 REM B--BALANCE
3. Rewrite the sample program on page 518 but with the following
changes.
0 2 15 31
au AN TI TY UN 111 PI" ICE VA LUE
fJ $ 23 .85 1$
2(16
4. 65
~l· ~• ..J I
$
$
1 9 .49
15 .67 :1
5. 6 7
13 3. 2
SUBPROGRAMS 523
Problem 3
Q QUANTITY D NUMBER OF DECIMAL PLACES
P - UNIT PRICE V EXTENDED VALUE
( Start
) o
Calculate
Value
V= INT(Q*P*1 0iD
+.5)!iOiD
GOSUB
200
GOSUB
300
NEXT I
524 PROGRAMM IN G IN BAS IC
2,
3.
01 REM Q--QUANTITY
02 REM P--UNIT PRICE
03 REM D--NUMBER OF DECIMAL PLACES
04 REM V--EXTENDED VALUE
10 REM THIS IS THE MAIN PROGRAM
20 PRINT
30 PRINT TAB(2); "QUANTITY" ;TAB(15); "UNIT
PRICE";TAB(31);"VALUE"
4e PRINT
50 LET D=2
60 FOR 1=1 TO 3
70 READ Q,P
Be DATA 9,23.B5,B.5,19.49,B.5,15.67
90 GOSUB 2~~
1~~ GOSUB 3~~
SUBPROGRAMS 525
l1B NEXT I
120 END
2BB REM THIS SUBROUTINE CALCULATES THE
21211 REM EXTENDED VALUE OF EACH ARTICLE
21B LET V=INT(Q*P*10TD+.5)/10TD
22e RETURN
3Be REM THIS SUBROUTINE PRINTS THE
3e1 REM DATA AND THE VALUES
3HI PRINT TAB(4)HHTAB(16);"$";TAB(17);P
;TAB(3e);I$";TAB(31);V
32121 RETURN
10 DEF FNM(M1}=M1*1.609
i ~
Dummy Constructed
argument by
the user
1~ DEF FNM(M1)=M1*C
15 LET C=1.609
2£1 LET M=5
3~ LET K=FNM(M)
To distinguish the argument in the function definit ion from the one
in the function reference, the argument in the function reference is
called the actual argument. Remember, the one in the function
definition was referred to as the dummy argument .
528 PR OG RAMMING IN BASI C
The logic of the program that converts miles to kilometres will now
be traced. Here is the program once more .
10 liEF FNM(Ml)=Ml*I.6~9
20 LET M=5
30 LET K=FNM(M)
40 PRINT
50 PRINT M; "MILES =";K;"KILOMETRES"
99 END
RUN
20 LET M=5~
30 LET K=FNM(M)
10 liEF FNM(Ml)=Ml*I.6a9
30 LET K=FNM(M)
\.
10 DEF
11
FNM(Ml)=Ml*1.6~9
\
30 LET K=FNM(M)
U
10 DEF FNC(Nl)=Nlt2
20 LET N=3
30 LET C=FNC(FNC(N»
40 PRINT
50 PRINT C
99 END
RUN
10 DEF FNM(M1)=M1*1.609
20 LET M=lB
30 LET K=FNH(M)
= 16.09
FNM(M1) =M1*1.609
FNM(11) =11*1 .609
= 17.699
30 LET K=FNM(Mtl)
= 17.699
FNM(M1) = M1 *1.609
FNM( 10) = 10*1.609
= 16.09
30 LE T K=FNH(H)t1
= 16.09+1
= 17.09
30 LET K=FNM(M)+SQR(64)-.09
= 16.09+ SOR(64)- .09
= 16.09+ 8- .09
= 24 .09- .09
=24
FNM(M1) = M1 *1 .609
FNM(10) = 10*1.609
= 16.09
- ;-
30 PRINT OK =";SGR(FNM(M)+84-.09)
SOR(16.09+ 84- .09)
SOR(1 00 .09- .09)
SOR(100)
10
Output: K = 10
10 DEF FNM(H1)=INT(Ml*1.609*10TDt.5)/10TD
20 LET D=2
30 LET H=10
40 LET K=FNH(Ht1)
= FNM(1 0+ 1)
= FNM(11')
40 LET K=FNH(M+1)
= 17.70
10 DEF FNH(M1)=Ml*1.609
'\
30 LET K=FNM(M)
10 DEF FNM(Ml)=Ml*I.6a9
30 LET K=FNM(M)
'\ - Both represent a
numeric value.
10 DEF
50 LET
RUN
4 6
3, Check your manual or try the above program to see if your computer system
supports multiline user-defined functions, If not, you may omit this part of the
chapter.
4. Some systems require a RETURN statement instead of FNEND, since these comput-
ers treat the function as a subroutine.
534 PROGRAMMING IN BASIC
RUN
10 DEF FNR(Al)~INT(Al*1~TDt.5)/10TD
20 L.ET [1=2
10 DEF FNN(Hl)=R*Hl-D
20 DEF FNR(Wl)=INT(Wl*10TD2t.5)!10TD2
30 LET D2=2
40 READ H,R,D
50 DATA 37,11.543,79.50
60 LET W=FNN(H)
70 LET N=FNR(W)
80 PRINT N
99 END
7~ LET N=FNR(W)
8~ PRINT N
99 END
H1 [lEF FNQ(Ai,Bi,Ci)~B1T2-4*Al*Cl
2~ READ A,B,C
3t'! DATA 2,6,3
(a) 4t'! LET Q;:FNCHA,B,C)
RUN
37 1.85
5. You may omit Problem 4 if your computer does not allow several variables in the
argument list.
538 PROGRAMM ING IN BAS IC
1~ DEF FNACR1)=ItCI*Rl )
2~ PRINT
30 LET I=UHHI
40 LET R=.17
50 FOR N=1 TO 3
60
70 PRINT A
B0 LET R=R+'01
90 NEXT N
99 END
RUN
1170
1180
1190
(c) Ca lcul ate t he squares of the numb ers from 1 to 5 inclu sive.
(i) Co mp lete line 10 w ith a DEF state men t.
(ii) Co mp lete line 40 with a fun ction referen ce coded in a LET
state m ent.
10
20 PRINT
30 FOR N=1 TO 5
40
50 PRINT t-hS
60 NEXT N
99 END
RUN
1 1
'")
~- 4
3 9
4 16
5 25
SUBPROGRAMS 539
HI DEF FNB(Al)
20 IF Al(=5 THEN 5~
3~
4~ GO TO 6~
5~
60 FNEND
7~ LET A=3
8~ PRINT
90 PRINT A,FNB(A)
99 END
RUN
3 27
RUN
6. You may skip question Si d) if your computer system does not support multiline
user-defined functio ns .
540 PROGRAMMING IN BASI C
Problem 6
P1 - DUMMY VARIABLE N - NUMBER OF ARTICLES (INDEX)
P - ACTUAL PRICE C - COSTOFTHEARTICLES
~ Start ~
DEF
FNC(P1)= INT
End
(P1/2*N*10jD
+ .5)/1 OJ D
Calculate
Cost
C= FNC(P)
NEXTN
2.
60 LET W=FNN(H)
= FNN(37)
FNN(H1)= R*H1- D
FNN(37)= 11 .543*37-79.50
= 427 .091- 79.50
=347 .591
7~ LET N=FNR(W)
= FNR(347.591)
3.
6~ LET W=FNV(H)
= FNV(44)
6~ LET W=FNV(H)
= 391.2065
7~ LET N=FNR(W)
= FNR(391 .2065)
7~ LET N=FNR(W)
= 391.21
4.
5.
6.
A SHORT SUMMARY
Subroutines and user-defined functions allow a programmer to write
often-used routines or calculations just once . These may be called
upon from various points within a program whenever they are
needed. The computer branches to the routine or function and after
processing the statement(s), returns to the point of reference wher'e
execution resumes. A subroutine is called by a GOSUB statement,
which gives the number of the line where control is to be directed.
The instructions in the subroutine are executed until a RETURN state-
ment is encountered . This statement RETURNS control to the main
program -specifically , to the statement immediately after the GOSUB
that referenced the subroutine. The main program must end with an
END statement or a STOP statement, depending upon the computer
l
system being used.
40 GoSUB 2ee
r~~~ END
SUBPROGRAMS 545
LET C=A+B~
RETUF:N
More than one value may be sent to the subroutine and more than
one value may be returned to the main program. A main program may
call several different subroutines or it may call the same subroutine
more than once. Subroutines may be nested (one calling another),
however, they must be in a hierarchical order. Thus, a program
utilizing subroutines must be comprised of a main program and at
least one subroutine.
A user-defined function is a mathematical equation (function)
named and defined in a DEF statement. The function is called by the
function reference which includes the name of the function and an
argument. It is usually coded in a PRINT statement or in a LET state-
ment. A value is passed from the actual argument in the function
reference to the dummy argument in the function definition.
r r
i
I
Dummy Function
i Actual
argument argument
5. For the main program shown on page 548 , write a subroutine that
finds the average of four numbers .
(a) Use a FOR/NE XT loop in your subroutine .
(b) Use a counter to keep track of the " number" of numbers.
(c) Don't forget to initialize to zero the counter, and the variable
that accumulates the sum .
548 PROGRAMMING IN BASIC
RUN
67
85
79
93
RUN
67
85
79
93
..
0 10 23
SU HI AIV ER A E
3·4 81
2210 PRINT
2HI PRINT A,B
(b) 121 LET 5=0
20 LET A=8
321 LET B=4
40 GOSUB 2021
521 END
2021 LET S=AtB
218 PRINT
228 PRINT A,B,S
2321 LET A=AT2
248 GOSUB 30
258 RETURN
(c) This program is to find the square of A after its
initial value has been added to B .
10 LET s=e
2£'1 LET A=8
321 LET B=4
4£'1 GOSUB 200
50 END
208 LET S=AtB
210 PRINT
550 PROGRAMMING IN BASIC
10 DEF FNRCN1)=INT(Nl*10TDt.5)/10TD
20 LET D:=0
10 DEF FNY(Al,Bl)=A1T2tB1T2
20 READ A,B
30 DATA 3,4
(a) 40 LET Y=FNY(A,B)
552 PR OG RAMMIN G IN BASI C
RUN
18
(d) HI DEF FNB (A 1) =SIJR ( (BT2tA 1) 12)
20 READ A,B
30 [lATA 2,4
40 LET C=FNB(A)
50 PRINT
6121 PRINT A,B,C
99 END
1_ -
SUBPROGRAMS 553
21. Fill in the missing lines for the following program. The program
calculates a table of cubes for the numbers from 1 to 5 inclusive.
10
20 PRINT
30 FOR N=l TO 5
40
50 PRINT N,C
6e NEXT N
99 END
RUN
1 1
2 8
3 2"7
4 64
5 125
HI [lEF FNB(A1)
20
30
40
5111
60 FNENII
70 LET A=9
8£1 PRINT
9111 PRINT A,FNB(A)
99 END
RUN
9
554 PROGRAMMING IN BASIC
Programming Problems 9
Subprograms provide an excellent opportunity to review concepts
learned in earlier chapters, since all that needs to be done is to divide
previous programs into two or more parts (main program and subrou-
tines) or to call a user-defined function several times to perform a
calculation more than once. The concept being reviewed and the
page number where it was first introduced is given for each problem
to enable you to referto a particular page should you need some help.
Some problems are slightly modified so that the latest techniques are
utilized along with the ones being reviewed.
(a) Use two subroutines. Call each subroutine from the main pro-
gram.
(i) One subroutine adds the amount of a purchase to the bal-
ance.
(ii) The other subroutine subtracts the amount of a payment from
the balance.
(b) Use the PRINT USING and IMAGE statements to format the output
Code the headings in the PRINT USING statement
(c) Use the READ/DATA statements to enter the code and the amount
of each transaction .
(d) Use an ON ... GO TO statement to branch to the statement that calls
the appropriate subroutine or to branch to the end of the main
program. A code of 1 indicates a purchase, a code of 2 denotes a
payment, and a code of 3 terminates input.
(e) Depending on your code:
Balance = Balance + Purchase
or
Balance = Balance - Payment
9. If yo ur computer system does not support the PRIN'I USING statement , use the TAB
function to format yo ur output. Also, instead of an IMAGE statement, some systems
reference a string va riable to which an Image has been assigned
SUBPR OG RAM S 555
RUN
FIRST STORE
CHAIR: 80 LAMP: 60
REDUCED: 70 REDUCED: :::,0
SECOND STORE
CHAIR: 80 LAMP: 60
REDUCED: 60 REDUCED: 40
xx DATA 2,1,2,1,2,2,1,2,1,2
xx DATA 1,2,1,1,2,1,2,1,1,2
10. If your computer system does not allow the use of the ON GOSUB statement, use
the ON GO TO statement to branch to a statement that calls the appropriate subrou-
tine.
SUBPROGRAMS 557
Problem 3
T TRUE
F FALSE
A ANSWER
Calculate Calculate
No. TRUE answers No. FALSE answers
T=T+1 F= F+1
Return Return
Print
T,F End
NEXT I
558 PROGRAMMING IN BASIC
Employee No. Hrs. Worked Rate Income Tax Oed. Union Dues Pension Oed.
1 44 10.241 80 2 3.00
2 37 11.543 75 2 2.50
3 39 12.349 90 2 4.00
(i) One subroutine calculates the gross pay with overtime. This
subroutine calls the subroutine that calculates the net pay.
(ii) A second subroutine calculates the gross pay with no over-
time. This subroutine also calls the subroutine that calculates
the net pay.
(iii) A third subroutine calculates the net pay. This subroutine
calls the subroutine that prints.
(iv) A fourth subroutine prints the information as shown below,
using format-free output.
(b) Use a FOR/NEXT loop to keep track of the employees, with the
index of the FOR statement denoting the number of the
employee.
(c) Use the READ/DATA statements to enter the hours, rate, and
deductions.
(d) Calculations
Problem 4
02 - NUMBER OF DECIMAL PLACES H1 - OVERTIME HOURS
E INDEX (EMPLOYEE NUMBER) R1 OVERTIME RATE
H REGULAR HOURS V OVERTIME
R REGULAR RATE G GROSS PAY
I INCOME TAX DED. o DEDUCTIONS
U UNION DUES N NET PAY
P PENSION FUND OED.
GOSUB400
End
GOSUB400
Return
Return
GOSUB200
Calculate
Net Pay
N=G - O
GOSUB 500
Return
Return
560 PROGRAMMING IN BASI C
RUN
EMPL. 1 HRS 44 RATE 10.241
OVERTIME HOURS 5
OVERTIME RATE 15.3615
OVERTIME PAY 76.8075
GROSS PAY 476.21
INCOME TAX 8~
UNION DUES :1.
PENSION 3
TOTAL DEDUCTIONS 85
NET PAY 391.21
0 7 I 27
MF' LO YEE WA GES
I I
1 I.$ 39 1 • ~ 1
2
~ I: 34 7 . 59
3 815 • l" 1
Problem 5
FNV FUNCTION WITH OVERTIME H1,W1 DUMMY VARIABLES
FNN FUNCTION WITH NO OVERTIME H HOURS
FNR FUNCTION THAT ROUNDS OFF AN R RATE
AMOUNT D DEDUCTIONS
D2 NUMBER OF DECIMAL PLACES W WAGES (NOT ROUNDED)
E INDEX (EMPLOYEE NUMBER) N NET WAGES (ROUNDED)
562 PROGRAMMING IN BASIC
~ Start ~
DEF
FNV(H1)= R*39+
(H1-39)*R*1 .5
-0 End
DEF
FNN(H1)= R* H1-
o
DEF
FNR(W1)= INT Calculate
(W1 *1 OJ 02 + .5)/ Total
10jD2 Deductions
0= I+U+P
Calculate
Yes
Wages (w ith
overtime)
W= FNV(H )
NEXT E
(a) Use two subroutines . Call each subroutine from the main pro-
gram.
(i) One subroutine accumulates the total number of moves of
each player (see (e)).
(ii) The other subroutine finds the winner by comparing the two
totals , then prints the number of the winner and his/her total
number of moves (see (f)).
(b) Use the PRINT USING and IMAGE statements to format your output.
Code the headings in the IMAGE statement.
(c) Initialize two variables to zero . These variables accumulate each
player's moves. Also set one variable to the "number " of
numbers on the dial (9) and another variable to the first endpoint
(1 ).
(d) Use a FOR/NEXT loop to control the number of plays. The loop
should contain the statement that calls the first subroutine.
(e) In the first subroutine, generate a random number from 1 to 9
inclusive for the first player. The random number represents the
number of moves that can be made . Immediately following this
statement, accumulate the player's moves. Do the same for the
second player.
(f) In the second subroutine, find the winner by comparing the
accumulated moves of the two players . Print the winner and
his/her total number of moves as shown below. Print the number
of the player (the winner) as a string . Be careful when formatting
this number. A space is not left automatically before the number
when it is coded as a string.
Note: The output changes with each RUN, since the progra m uses
random numbers .
Sample RUN
0 1161 II I I I I 22 I, !
NNIE!R 1
I:T U I i
1 Ii T
l TO
48
MO 1) [ 5
Problem 6
P1 - FIRST PLAYER
P2 - SECOND PLAYER
N "NO." OF NUMBERS IN RANGE
I FIRST ENDPOINT
R1 RANDOM NO. FOR FIRST PLAYER
R2 - RANDOM NO. FOR SECOND PLAYER
( start)
\!I
~
564 PR OGR A MMIN G IN BASIC
J> 10
GOSUB 300
GOSUB 200 )
NEXT J
0 0)
First Player
Random No. Print
R1=INT " 1" , P1
(N*RND(1)+ I)
Total Moves
P1=P1+R1
Return
SUBPROGRAMS 565
RUN
MATRIX A
4 5 6
8 9 4
7 8 9
MATRIX B
12 15 18
24 27 12
21 24 27
MATRIX C
16 20 24
32 36 16
28 32 36
11. You may skip this problem if your computer system does not support MAT
statements .
566 PROGRAMMING IN BASIC
RUN
MAH:IX A
4 c:'
'-' 6
8 9 4
-,, 8 9
MATRIX B
12 15 18
24 27 12
,"") -,
21 24 ...._ I
MATRIX C
16 20 24
32 36 16
28 32 36
(d) Print the first year's compound amounts across the first line of
output (for each rate of interest) , the second year's compound
amounts across the second line of output (for each rate of
interest) , etc. To do this, the PRINT statement that prints the
number of the year and the PRINT statement that prints the
compound amount should each end with a semicolon. Do not use
the PRINT U S ING and IMAGE statements or the TAB function to
format your output.
RUN
RUN
EMPLOYEE,PARTS,DEDUCTIONS? 1,212,105
WAGES: 391.72
12. Use the READ /DATA statements to enter the data if you are not using an interactive
system .
568 PROGRAMMING IN BASIC
EMPLOYEE,PARTS,DEDUCTIONS? 2,213,11~
WAGES: 389.1116
EMPLOYEE,PARTS,DEDUCTIONS? 3,2l119,102
WAGES: 387.69
EMPLOYEE,PARTS,DEDUCTIONS? 99999,111,0
RUN
EMPLOYEE: 1
PARTS, DEDUCTIONS: 212 11115
WAGES: 391.72
EMPLOYEE: 2
PARTS, DEDUCTIONS: 213 110
WAGES: 389.06
EMPLOYEE: 3
PARTS, DEDUCTIONS: 21119 102
WAGES: 387.6 1jl
10
(f) Except for the following changes , your flowchart should be simi-
lar to the one for Problem 6 in Chapter Ten on page 502.
(i) Draw a symbol for the DEF statement before the symbol that
represents the printing of the headings.
(ii) The material in two of the symbols should describe state-
570 PROGRAMMING IN BASIC
-
e 8 ".:......JI
0: .
1 AI II CI REISiULiT
2 6 -4
,.
<.
I I
1 8 16 B
13 -4 2 -1 I
Problem 13
( Start
\It
)
I
I
i DEF
FND(A 1) I
Y
eJ
13. You may om it Problem 13 if you cannot use multiline user-defined functions on
your computer.
SUBPROGRAMS 571
FND= -1
Calculate
Function FNENIJ
FND= SQR(Bj2-
4*A1*C) End
Call function
D= FND(A)
NEXT I
TW VE STRINGS
A. After completing this chapter, you should be able to write BASIC
programs that:
1. Store strings in the computer by means of
(a) The INPUT statement.
(b) The READ/DATA statements .
(c) The LET statement.
2. Store strings in
(a) A simple string variable.
(b) A one-dimensional array.
(c) A two-dimensional array.
3. Compare strings .
4. Concatenate strings.
5 . Extract
(a) Any number of left-most characters from a string .
(b) Any number of right-most characters from a string .
(c) Any series of characters from a string.
(d) One character from a string.
6 . Sort strings .
7. Use special functions to
(a) Find the length of a string.
(b) Convert a string that consists of digits to its numeric value.
(c) Convert a number to its string equivalent.
(d) Convert an AS CII code to its AS CII character .
(e) Convert a single character to its ASCII code .
B. In addition, you should be able to :
1. Define a string variable .
2. Explain how a character is stored in a computer and summa-
rize the reason for this method of storage .
3. State what the letters ASCII represent.
4. Summarize the hierarchical ordering of ASCII codes.
5. Evaluate relational string expressions .
6. Find errors in programs .
7. Produce the output of programs.
variable on most systems must end with a dollar sign ($). A$ is a string
variable, while A is a numeric variable. Some computers accept A 1$ ,
N9$, etc., as string variables . Others allow a double letter, such as
AA, NN. It is a good idea to construct a string variable so that it
indicates the kind of information assigned to it. N$ might represent a
person's Name, while C$ could stand for the name of a City . The
series of characters assigned to a string variable is often considered
the value of the variable.
Some computer systems require the dimensioning of a string
variable when the string contains more than one character. Others
require no dimensioning unless the variable represents an array . The
undimensioned string variable is allowed a maximum number of
characters, the number depending on the computer. If dimensioning
is required , the parameter following the string variable represents the
maximum number of characters in the string. For example, 10 DIM
A$(8) designates A$ as a string variable, with a maximum of 8
characters in its string.1
Some systems allow two parameters to dimension both the num-
ber of elements in an array and the number of characters in each
string of the array. The DIM statement
10 DIM A$(6)9, B$(8), C$4
dimensions the variables as follows .
The string variable A$ is dimensioned as an array of six elements,
with each element (string) having a maximum of nine characters.
The string variable B$ is an array of eight elements, with each
element (string) having a default 2 length of one character.
The string variable C$ is a simple string variable whose string may
consist of a maximum of four characters.
The length of a string varies among different computers - from
zero characters (the null string) to a specific maximum, which may be
as low as 6 characters and as high as 255 characters (72 and 255 are
the more common maximums) . Check your manual to find out the
maximum number of characters allowed in a string by your computer
system .
1. In thi s book. DIM stat ements are not used to specify string ca pacity but are used to
dimension arrays.
2. In th e absence of a param eter, the computer ass ume s that the va lue is a specific
number.
STRINGS 575
-Same number
-Same order
-Same type
I
.~
- - - - - - - -- - -
Use the various DATA and PRINT statements shown above , along with
the READ statement, to find out how your computer prints strings.
3. If you are not using an interactive system, you may omit programs that use INPUT
statements or questions that refer to these statements.
STRIN GS 577
35:'1 INPUT N$, C$, N - Requests data, user enters the name of a person , the name of a
city , and a number .
45:'1 PRINT N$;C$;N -Prints the name of the person, the name of the city , and the
number closely spaced .
99 END - Terminates program execution .
RUN
DATA? JOHN SMITH ,ROXVALE,123456
JOHN SMITH ROXVALE 123456
To obtain the space after SMITH in the output line, a space must be
left after JOHN SMITH when the name is keyed into the computer.
No space needs to be left after ROXVALE, since the compu ter prints
a space before a pos itive number.
RUN
JOHN SMITH ROXVALE 123456
To obtain the space after SMITH in the outpu t, a space must be coded
after SMITH in the DATA statement. As in Program 1, no space
needs to be coded after ROXVALE , since the computer leaves a
space before a positive number .
FWN
Notice that the computer requires quotes around a string when a LET
statement is used to assign the string to a string variable. The space
after JOHN SMITH in the output is obtained by leaving a trailing space
in the string "JOHN SMITH "in line 1O. An alternative method is to
code the space before ROXVALE. As in the other programs, no
space is needed after ROXVALE.
10 LET A$=B$=C$="ROXVALE"
70 NEXT I
99 END
RUN
P$
Column 1 Column 2 Column 3
10 [11M P$(3,3)
20 PRINT
30 FOR 1=1 TO 3
40 FOR J=l TO 3
50 READ P$(I,J)
60 [lATA MERCURY ,VENUS ,EARTH ,MARS
,JUPITER ,SATURN ,URANUS ,"NEPTUNE"
70 [lATA PLUTO
B0 PRINT P$(I,J);
90 NEXT J
100 PRINT
110 NEXT I
999 END
580 PROGRAMMING IN BASIC
RUN
(a) 10 PRINT
20 PRINT "NAME,TELEPHONE NUMBER";
30 INPUT N,T
40 PRINT Nn
99 END
(b) 10 PRINT
20 FOR 1=1 TO 3
30 READ M$
40 DATA JANUARY,MAY,SEPTEMBER
50 PRINT M$;
60 NEXT I
99 END
HON[lAY JANUARY 1
I SCORE[I 24 POINTS
RUN
5. Rewrite the program for Problem 4 . This time, read the names
into a two-dimensional array that has two rows and three
columns. Here is the data in matrix form .
Anne Craig Barry
Roger Laurie Tracy
(a) Use nested FOR/NE XT loops to control input.
(b) Read the names by rows.
(c) Print only the first , third, and fifth names closely spaced. Use
explicit subscripts to denote the row and the column of each
element of the array.
RUN
(c) The three words will be printed with no space between each
word . There are a number of solutions , two of which are
shown be low .
5 . Prog rams are written fo r a co mputer th at leaves o ne space bef ore a pos iti ve
number and one s pace after any number .
STR INGS 583
10 READ D$,Mf,[I
20 DATA MONDAY ,JANUARY,1
30 PRINT
40 PR I NT [t~ HI$;[I
99 END
10 LET Df="MONDAY I
20 LET M$="JANUARY"
30 LET [t=1
40 PRINT
50 PRINT D$;M$;[t
99 END
RUN
SCORE? I SCORED,24,POINTS
10 READ I$,N,P$
20 DATA I SCORED,24,POINTS
30 PRINT
40 PRINT IHNH'$
99 END
4.
01 REM N$--NAME
10 DIM N$(6)
20 PRINT
30 FOR 1=1 TO 6
40 READ N$(I)
50 DATA ANNE ,CRAIG ,BARRY ,ROGER ,LAU
RIE ,TRACY
60 NEXT I
70 PRINT N$(1),N$(3),N$(S)
99 END
5.
01 REM N$--NAME
10 DIM N$(2,3)
20 PRINT
30 FOR 1=1 TO 2
40 FOR J=l TO 3
STRINGS 585
50 READ NS(I,J)
60 DATA ANNE ,CRAIG ,BARRY ,ROGER ,L
AURIE ,TRACY
70 NEXT J
Sf! NEXT I
90 PRINT NS(1,1);N$(1,3);N$(2,2)
99 END
6. This book uses decimal notation to represent the ASC II codes for letters, digits ,
speCial characters, and system commands.
7. The intent of this unit is merely to introduce you to hexadecimal notation If you
wish a more detailed discussion on hexadecimal representation, refer to a Mathe-
matics book or to a Data Processing text.
8. A code that represents a system command does not have a corresponding
character .
,
586 PROGRAMMING IN BAS IC
These two statements cause a carriage return . CHR$ and HEX are
special functions that enable a programmer to use an ASCII code in a
program. The following table lists the ASCI I codes in octal, decimal ,
and hexadeci mal translations fo r the characters most often used .
.
space 040
042
32
34
20
22
# 043 35 23
$ 044 36 24
,
047 39 27
( 050 40 28
) 051 41 29
* 052 42 2A
+ 053 43 2B
, 054 44 2C
- 055 45 2D
056 46 2E
/ 057 47 2F
rJJ 060 48 30
1 061 49 31
2 062 50 32
3 063 51 33
4 064 52 34
5 065 53 35
6 066 54 36
7 067 55 37
8 070 56 38
9 071 57 39
072 58 3A
, 073 59 3B
< 074 60 3C
= 075 61 3D
> 076 62 3E
A 101 65 41
B 102 66 42
C 103 67 43
D 104 68 44
E 105 69 45
F 106 70 46
G 107 71 47
H 110 72 48
I 11 1 73 49
J 112 74 4A
K 113 75 4B
L 114 76 4C
- ---.----------------------------------------------------------------------~--,.
STRINGS 587
M 115 77 4D
N 116 78 4E
0 117 79 4F
P 120 80 50
0 121 81 51
R 122 82 52
S 123 83 53
T 124 84 54
U 125 85 55
V 126 86 56
W 127 87 57
X 130 88 58
Y 131 89 59
Z 132 90 5A
Notice the hierarchical ordering of the ASCII codes . The space and a
number of special characters precede the digits. The digits are
followed by other symbols, which, in turn, are followed by the capital
letters . This hierarchy makes it possible to compare strings by using
the same relational operators that are used to compare numbers. The
computer compares two strings by comparing one character at a
time, moving in a left-to-right direction until a difference is found.
Here are some examples . For each relational expression, the answer
is either true or false . Consult the ASCII list of codes for the numerical
equivalent of a character. The codes shown below are in decimal
notation.
1. Is JANSEN equal to JANZEN?
RUN
AIKEN AITKEN
Notice the trailing space after each name . This space is neces-
sary, otherwise the semicolon in the executed PR INT statement
causes the two names to be printed with no space between
them .
2 . This program illustrates how a string variable can be compared
with a string.
01 REM [I$--DAY
421 DAT A SU NDAY, TUE S DAY, THUR S D{'-\ Y, SAT UR D - Supplies the READ statement with
AY 4 strings.
521 IF D$="SATURDAY" THEN 921 - Tests the value of 0$ :
(i) If its value is SATURDAY,
control is transferred to line 90
which prints a message .
(ii) If its value is not SATURDAY,
the computer proceeds to the
next statement.
621 NEXT I - Transfers control back to line 20.
70 PRINT "SATURDAY NOT FOUND" - Prints the string SATURDAY
NOT FOUND.
Bf) GO TO 999 - Transfers control to the END
statement.
921 PRINT "IT'S SATURDAY" - Prints the string IT'S SATURDAY.
999 END - Terminates program execution.
RUN
IT'S SATURDAY
01 REM S$ - -STRING
RUN
'YEAR' IS ENTERED 2 TIMES
RUN
TORTOISE TORTOISE
RUN RUN
111222 333
STRINGS 591
The addition in Program (a) attaches 222 to the tail end of 111,
which produces 111222. The addition in Program (b) is a numeric
addition which produces the sum 333.
Some systems require the use of the STR function to concatenate
strings. Here is an example .
RUN
111222
RUN
BASICCOBOL
RUN
BASICCOBOL
********************
1e LET B$="BASIC"
2e LET C$=" COBOL"
tSpace before COBOL
e1 REM W$--WORD
e2 REM L$--LETTER
1e LET W$=·· -Initializes the string variable W$ to the null string .
2e FOR 1=1 TO 5 - Sets up a loop for the five letters .
3e READ L$ - Reads the letters one at a time.
40 DATA B,A,S,I,C - Supplies the READ statement with the letters .
se LET W$=W$+L$ - Concatenates the letters one at a time and stores the accumulated
result in W$.
60 NEXT I - Transfers control back to line 20.
70 PRINT - Leaves a blank line.
80 PRINT W$ - Prints the concatenated word.
99 END - Terminates program execution.
RUN
BASIC
STRING S 593
IH REM W$--WORD
02 REM L$--LETTER
10 LET W$=" " -Initializes the string variable W$ to blank .
20 FOR 1=1 TO C"
~I - Sets up a loop for the five letters .
30 READ L$ - Reads the letters one at a time.
40 [lATA IhA,S,I,C - Supplies the READ statement with the letters .
50 STR(W$,xd)=L$ - Concatenates the letters one at a time in the variable W$ by
setting the first character of W$ (1= 1) to the first letter read, the
second character of W$ (1= 2) to the second letter read , etc .,
until the loop is complete (1= 5) .
60 NEXT I - Transfers control back to line 20.
70 PRINT -Leaves a blank line.
80 PRINT W$ - Prints the concatenated word.
99 END - Terminates program execution.
RUN
BASIC
RUN
(a) HI PRINT
20 LET AS="AN[lERSEN I
40 IF A$>=BS THEN 70
521
60 GO TO 99
70
99 END
RUN
ANDERSEN ANDERSON
(b) HI PRINT
2~ FOR 1=1 TO 4
30 READ Pi
40 DATA MERCURY,VENUS,EARTH,MARS
521
621 PRINT "I LIVE ON THE PLANET EARTH"
70 NEXT I
99 END
RUN
(a) HI PRINT
221 LET G$="GREAT DANE"
30 IF GS)CHIHUAHUA THEN 60
STRI NGS 595
40 PRINT "CHIHUAHUA"
50 GO TO 99
60 PRINT G$
99 EN[I
RUN
PROGRAMS IN BASIC
(b) L I N D SAY L I N D S E Y
7673 7868 83@ 76 73 78 68 83 @
False
9. The co des shown for Pro blem 1 are in dec imal notation .
596 PROGRAMMING IN BASIC
2.
3B IF G$)"CHIHUAHUA" THEN 6B
RUN
B APPEARS 3 TIMES
10 LET P$="PROGRAMS"
2B LET IS=" IN"
3B LET BS=" BASIC"
4B LET CS=Pf+I$+BS
SB PRINT
6B PRINT CS
99 END
10 LET P$='PROGRAMS"
20 LET 1$=" IN"
30 LET B$=" BASIC"
40 STRCC$,1,8)=P$
50 STR(C$,9,3)=I$
60 STRCC$,12,6)=B$
70 PRINT
80 PRINT C$
99 ENII
LEFT$CS$,7> 5$(3,7)
i
Function
V
Arguments
String
variable
I V
Subscripts
and the name of the function vary widel y among computers . Shown
below are different versions of the two methods along with their
interpretations . The string PLAYING WITH WORDS has been
assigned to S$ in the examples . Either the string variable or the string
itself (enclosed in quotation marks) may be used as the argument of a
function . To simplify the examples , the string variable has been used .
Function Method
LEFTf(S$,7) Extract the 7 left-most characters. PLAYING
SUBSTR (S$, 1,7) Extract 7 characters starting at the first. PLAY I NG
STR(S$,1,7)
Subscript Method
Extract 7 characters starting at the first PLAYING
or
Extract the first character through and PLAYING
including the seventh .
Function Method
R I GHT$ (S$, un Extract the 10 right-most characters. WITH WORDS
SUBSTR (Sf, 9,1 B) Extract 10 characters starting at the ninth. WITH WORDS
STR(S$,9dB)
SUBSTR(S$,9) Extract the ninth character through and WITH WORDS
STR<Sf,9) including the last.
Subscript Method
Function Method
Extract 10 characters starting at the fifth IN G WIT H W
or
Extract the fifth character through and ING WI
including the tenth.
Subscript Method
S$(5,111l) Extract 10 characters starting at the fifth I NG WIT H W
or
Extract the fifth character through and ING WI
including the tenth.
Variations
10 LET S$="PLAYING WITH WORDS' 20 LET LS=STR(SS,I,7)
20 LET LS=LEFTS(S$,7) 20 LET LS=SUBSTR(S$,1,7)
30 PRINT 2~ LET LS=SS(I,7)
40 PRINT LS
99 END
RUN
PLAYING
HJ PRINT
20 PRINT RIGHT$("PLAYING WITH WORDS",10)
99 END
RUN
WITH WORDS
Variations
WITH
Variations
20 IF STR(S$,9,4)="WITH" THEN 40
50 PRINT STR(S$,9,4)
20 IF SUBSTR(S$,9,4)="WITH" THEN 40
50 PRINT SUBSTR(S$,9,4)
20 IF S$(9,12)="WITH" THEN 40
50 PRINT St(9,12)
602 PROGRAMMING IN BASIC
IV. This program finds how many A 's there are in the name BAR-
BARA. Here are the instructions.
01 REM K--COUNTER
02 REM N$--NAME
10 LET 1\=0
20 LET N$="BARBARA"
30 FOf~ 1=1 TO 7
40 IF MID$(N$,I,l)="A" THEN 60
50 GO TO 70
60 LET K=Kt1
70 NEXT I
80 PRINT
90 PRINT "NO. OF A'S IN BARBARA IS:";K
99 END
RUN
Variations
40 IF STR(N$,I,l)=IA" THEN 60
40 IF SUBSTR(N$,I,l)=IA" THEN 60
40 IF N$(I,I)="A" THEN 60
RUN
1 ALLAN SMITH
2 ALLAN MILLS
3 ALLAN WEBSTER
2. One of the "Your Turn" programs on page 594 compared the two
names Andersen and Anderson to determine which one was
greater, then printed the names alphabetically . Rewrite the pro-
gram, this time comparing the last three characters of each
name. In one IFITHEN statement, perform the following :
RUN
ANDERSEN ANDERSON
(a) Divides the string 5671234 into the two substrings 567 and
1234, by using the LEFT$ function and the RIGHT$ function .
(b) Determines which substring is the greater .
(Hint: This does not mean greater numerically .)
(c) Branches to the appropriate PRINT statement to print the
greater of the two substrings.
604 PROGRAM MING IN BASI C
RUN
567
4. In Chapter Nine on pages 409 and 412, you were shown how to
reverse the order of the digits of a number. The same thing can
be done with the characters of a string. Write a program that
prints each of the names Michael, Suzanne, and William with
their letters in reverse order. Notice that each name has seven
letters. To reverse the order of the letters in names that have
various lengths, the number of characters in each name must
first be determined. This is explained in the next section.
RUN
LEAHCIM
ENNAZUS
MAILLIW
Problem 4
N$ - NAME L$ - LEDER
C~~tart )
@J
STRINGS 605
o
Extract
End
Substring
L$= MID$(N$,J, 1)
NEXT J
NEXT I
1111 PRINT
606 PROGRAMMING IN BASIC
20 LET K=l
30 FOR 1=1 TO 6
40 READ N$
50 DATA ALLAN SMITH,LAUREEN PETERS,ALL
AN MILLS,SANDRA CAMPBELL,ALLAN WEBSTER
60 DATA MARY WILLIAMS
70 IF LEFT$(N$,S)="ALLAN" THEN 9~
80 GO TO 110
90 PRINT K,N$
100 LET K=Ktl
110 NEXT I
999 END
Variations
70 IF STR(N$,l,S)="ALLAN" THEN 9~
70 IF SUBSTR(N$,l,S)=IALLAN" THEN 9~
70 IF N$(l,S)="ALLAN" THEN 90
2.
10 PRINT
20 LET M$="ANDERSEN I
30 LET N$="ANDERSON I
40 IF RIGHTS(M$,3)(=RIGHT$(N$,3) THEN 70
S0 PRINT NS;M$
60 GO TO 99
70 PRINT M$;N$
99 EN[I
Variations
40 IF STR(M$,6,3)<=STR(NS~6~3) THEN 70
or 40 I F S TR ( M$ , 6 ) <: =S TR ( N$ , 6) THE N 7 0
40 IF SUBSTR(M$,6,3)(=SUBSTR(N$,6,3) THEN 7~
or 40 IF SUBSTR(MS,6)<=SUBSTR(N$,6) THEN 70
40 IF M$(6,8)<=NS(6,B) THEN 70
or 40 IF M$(6)<=NS(6) THEN 70
3.
01 REM S$--STRING
02 REM L$--LEFT SUBSTRING
03 REM R$--RIGHT SUBSTRING
STRINGS 607
leI PRINT
20 LET S$=15671234"
30 LET L$=LEFT$(S$,3)
40 LET R$=RIGHT$(S$,4)
50 IF L$ >=R$ THEN 80
60 PRINT R$
70 GO TO 99
80 PRINT L$
99 END
Variations
30 LET L$=STR(S$,1,3)
or 40 LET R$=STR(S$,4,4)
40 LET R$=STR(S$,4)
30 LET L$=SUBSTR(S$,1,3)
40 LET R$=SUBSTR(S$,4,4)
or40 LET R$=SUBSTR(S$,4)
30 LET L$=S$(1,3)
40 LET R$=S$(4,7)
or40 LET R$=S$(4)
4.
01 REM N$--NAME
02 REM L$--LETTER
10 PRINT
20 FOR 1=1 TO 3
30 READ N$
40 DATA MICHAEL,SUZANNE,WILLIAM
50 FOR J=7 TO 1 STEP -1
60 LET L$=MID$(N$,J,l)
70 PRINT L$;
80 NEXT J
90 PRINT
10e NEXT I
999 END
Variations
60 LET L$=STR(N$,J,l)
60 LET L$=SUBSTR(N$,J,l)
60 LET L$=N$(J,J)
608 PROGRAMMING IN BASI C
I. LEN
LEN(N$) LEN("MAUREEN")
t
String variable String
i
RUN
7
II. VAL
i
String variable
l'
String of digits
RUN
2468
III. STR$
STR$(N) STR$(2468)
i
Numeric variable
i
Numeric value
RUN
2468
IV. CHR$
CHR$(C) CHR$(65)
i
Numeric variable
r
Numeric value
RUN
65 A
V.ASC
RUN
A 65
The following will help you differentiate between CHR$ and ASC.
(a) CHR$ resembles character-it changes its argument to an ASCII
character.
(b) ASC resembles ASCII- it changes its argument to an ASCII code.
The five functions just shown may also be used with subscripted
variables. The following program determines the length of each of the
five words that are stored in the one-dimensional array W$ .
RUN
VARIABLE 8
FUNCTION 8
SUBSCRIPTED 11
ARRAY 5
SUBROUTINE 10
2. Write a program that converts each of the strings "24" and "25"
to its numeric value, then adds the two numbers.
RUN
24 25
24 25
49
(a) Use a FOR/ NEXT loop . Set the initial value in the FOR statement
to 65 and the test value to 90.
(b) Use the index as the argument of the function that converts
each number to its ASCII character. Assign the character to a
string variable .
(c) Print the value of the index and its ASCII character on one line
widely spaced.
RUN
STRINGS 613
65 A
66 B
67 C
90 Z
RUN
S 83
E 69
A 65
...
3")
F 7e
G 71
Problem 4
S$ - STRING
A$ - SUBSTRING A - ASCII CODE
11 . If you r computer system does not accept a string variable as the argument of the
ASC function , you may omit this question.
614 PROG RAMMING IN BAS IC
End
Extract
Substring
A$= MIO$(S$,1 ,1)
Convert to
ASCII code
A=ASC(A$)
NEXTI
19 3456
3456
5789 67 C
5789
(e) RUN
T 84
2.
UJ REAli A$, B$
20 DATA "24","25~3
30 LET A=VAL(A$)
40 LET B=VAL(B$)
50 LET C=AtB
60 PRINT
70 PRINT A$,B$
80 PRINT A,B
90 PRINT C
99 END
3.
10 PRINT
20 FOR 1=65 TO 90
30 LET C$=CHR$(I)
40 PRINT I,C$
50 NEXT 1
99 END
4.
01 REM S$--STRING
02 REM A$--SUBSTRING
03 REM A--ASCII CODE
10 PRINT Variations
20 LET S$="SEA FLOOR SPREADING"
30 FOR 1=1 TO LEN(S$) 40 LET A$=STR(S$,I,1)
40 LET A$=MID$(S$,I,1) 40 LET A$=SUBSTR(S$,I,1)
50 LET A=ASC(A$) 40 LET A$=S$(I,I)
60 PRINT A$,A
70 NEXT I
99 END
13. The programs in this book need quotes around strings that consist of numbers .
616 PROGR AM'MING IN BASI C
A SHORT SUMMARY
Strings give the means by which alphabetic and alphanumeric data
can be manipulated. Many of the operations performed on numeric
data can also be performed on strings . Strings may be assigned to
string variables by using the same statements that assign numeric
data to numeric variables. The relational operators that are used to
compare two numbers may also be used to compare two strings .
However, substrings are extracted from strings differently than the
way digits are separated from numbers. Two basic methods exist-
the function method and the subscript method . The function method
uses built-in functions, while the subscript method uses subscripted
string variables. Substrings may be formed by extracting an y number
of left-most characters from a string , any number of right-most
characters from a string, or any series of characters from within a
string . The arguments or subscripts indicate where the extraction
begins and where it ends . It is also possible to isolate a single
character. However, many disparities exist among the different ver-
sions of BASIC in the interpretation of the arguments and subscripts .
The function name also differs among computers.
Several functions are available on most computers to enable the
user to perform special operations on strings , such as finding the
length of a string, converting a string that consists of digits to its
numeric value, and converting an ASCII code to its character equiva-
lent. The reverse of the last two operations is also available.
Strings are used in many applications Some of the more common
ones are the sorting of names, the printing of address labels, the
search for a particular name or word, and , along with numeric data,
the maintenance of payroll records and the control of inventory .
JUNE 21 WEDNESDAY
j
Month and day
i
Day of the week
Assign your name to one string variable, the month and day of the
month to another string variable, and the day of the week to a
STRINGS 617
(a) 10 PRINT
20 PRINT "NUMBER,STREET";
30 INPUT N,S
40 PRINT N;S
99 END
RUN
(c) 10 PRINT
20 FOR 1=1 TO 5
14. If you are not using an interactiv e system, you may omit question 6 (a)
618 PROG RAMM IN G IN BAS IC
(f) 1 0 F' R I NT
20 LET B$="BASIC"
3111 LET P$="PROGRAMMING"
4111 PRINT
50 PRINT B$;P$
99 END
(g) 10 LET S$= 1SOMETHI NG WRONG 1
20 LET L=LEN$(S$)
30 PRINT
40 PRINT L
99 END
(h) 1111 LET N=1234
20 PRINT
3111 PRINT VAL(N)
99 END
(i) 1111 LET N$=19111"
20 PRINT
3111 PRINT CHR$(N$)
99 END
(j) HI READ N
20 DATA 5678
3111 PRINT
40 PRINT STR(N)
99 END
- - - ---------------------r---
STRINGS 619
(d) 10 READ N
20 DATA 54
30 PRINT
4111 PRINT N
5111 PRINT CHR$(N)
99 END
Programming Problems
1. In Section 12.4 page 604 you wrote a program that printed three
names with their letters in reverse order. Each name had seven
letters. Rewrite the program, this time using the words PRO-
GRAMMER, BASIC, and COMPUTER as your data. Notice that
the words have different lengths, which means that you will need
the LEN function to determine the number of characters in each
word .
RUN
REMMARGORF'
CISAB
RETUF'MOC
...,,-,,
""
where W$ is the word read into the computer, R$ is the word with
its letters in reverse order, and J is the index of the inner loop. As
the value of J changes, the expression LEN(W$)+1-J sets the
first character of R$ to the last letter of W$, the second character
of R$ to the second last letter of W$, etc.
Print the results as shown below. Remember, there is no
space printed before and after a string. To make sure that your
words in the output line do not run together, code a space after
STRING S 621
RUN
Problem 2
R$ - REVERSE
W$- WORD
Concatenate
End Substrings
R$= R$+MID$
(W$,J,1 )
NEXT J
NEXT I
622 PROGRAMMING IN BASI C
3 . Write a program that reads the names of the twelve months of the
year into a 3x 4 two - dimensional array . Print the names in matrix
form. Perform the read and write operations by rows in one set of
nested FOR/NE XT loops .
Note: If your computer does not require quotes around strings
in the DATA statement and if it allows only two lines of data in the
statement, perform the following when more data items are to be
coded:
(a) In the second line of the first DATA statement, place quotes
around the last string and its trailing space .
(b) The line should not end with a comma .
(c) Code the next string in a new DATA statement.
This gives a space in the output between the last string of the first
DATA statement and the first string of the second DATA statement.
RUN
RUN
PROGRAMMER
BASIC
COMPUTER
Problem 4
L - LENGTH
W$- WORD
L$ - LONGEST WORD
Print
BlanL~line !---~
C )
End
'-----~
Determine
Length
L= LEN(W$)
Save Word
L$=W$
NEXT I
624 PROGRAMMING IN BA S IC
~.: }: LET T$=N$ (J) - Places the first name of a pair in temporary storage.
:.::., LET N$ (J) =-N$ (J+ 1) - Places the second name of the pair in the current variable .
,.""
,',,', LET N$ (Jt 1) =T $ ~ Places the name that is in temporary storage in the next variable.
T N$(1 ) N$(2)
RUN
ALEXANDER
EDWARD
GAYLE
ST RINGS 62!
JAMES
NANCY
TRACY
Problem 5
N$ - NAME
T$ - TEMPORARY STORAGE
DIM
N$
GOSUB200 ~
Read
N$(I)
K> 6
NEXT I
NEXTK
626 PROGRAMMING IN BASIC
Return
nterc - ange
Names
T$= N$(J)
N$(J)= N$(J+ 1)
N$(J+1)= T$
NEXT J
NEXT L
6. Write a program that reads the names of the following five people
in first name first order , with one space between the first name
and the last name.
Arthur Brown, James Anderson , Ell en Miller , Steven Taylor,
Allan Fraser
Print their names in this manner : last name, comma, first name .
(a) Use two FOR/ NEXT loops :
STRINGS 627
(i) The outer loop controls the reading of the names. (Hint:
Do not leave a space after each last name in the DATA
statement.)
(ii) The inner loop locates the space between a first name
and a last name. To find the space:
- Use J as the index of the FOR statement.
- Use the LEN function as the test value in the FOR
statement. (The argument of the LEN function is the
string variable that stores a name.)
- Use the MID$ function to check each character of a
name for the space (" "). The arguments of the MID$
function should be the string var iable that stores a
name, the index of the inner loop, and the number 1.
When the space is found , the value of the index is the
number of characters in the first name plus the space.
Transfer control to a statement that extracts the first
name. This should be followed by a statement that
extracts the last name.
(b) To extract the first name :
(i) Use the LE FT$ function and assign the substring to a
string variable, say LS.
(ii) The arguments of the LEFT$ function should be the string
variable that stores a name and the index of the inner
loop. The value of the index is the number of characters
in the first name plus the space.
Example: IARTHURIBROWN
The value of the second argument (J) is 7.
(c) To extract the last name:
(i) Use the RIGHT$ function and assign the substring to
another string variable, say RS .
(ii) The arguments of the RIGHT$ function should be the
string variable that stores a name and the LEN function
minus the index of the inner loop . The latter argument is
the length of the name minus the number of characters in
the first name and the space.
Example: ARTHURIBROWNI
Length of name = 12.
Length of first name and space = 7.
Length of last name is 12- 7= 5 .
The value of the second argument (LEN(NS)-J) is 5.
(d) Print the substring extracted by the RIGHT$ function, a
comma, then the substring extracted by the LEFT$ function.
(e) Continue with the next name.
RUN
BROWN, ARTHUR
AN[lERSON,JAMES
MILLER,ELLEN
TAYLOR, STEl,,'EN
FRASER,ALLAN
,
II
628 PR OG RAMMIN G IN BAS IC
Problem 6
N$ - NAME
L$ - LEFf SUBSTRING (FIRST NAME) R$ - RIGHT SUBSTRING (LAST NAME)
Extract Left
Characters
L$= LEFf$(N$,J)
Extract Ri'ght
Characters
R$= RIGHT$
End (N$ ,LEN(N$)-J)
NEXTI
J>LEN(N$)
NEXT J
(b) Set up an inner loop with a FOR statement that has an initial
value of 1 and a test value equal to the length of the string.
Use J as the index.
(c) Find the position of the decimal point by using the MID$
function to check each character of the string. This statement
is similar to the one used in Problem 6, where each character
in a name was checked for a space. When the decimal point
is found, transfer control to the PRINT statement that pro-
duces the RUN shown below. The value of J at this point is the
number of characters up to and including the decimal point.
(d) Print the number stored as a string in the string variable and
the number stored in the numeric variable on one line widely
spaced. Use the TAB function to align the number stored in
the string variable. If your computer leaves a space before a
positive number, this space is included as the first character
of the string. Since the longest number entered has six
characters up to and including the decimal point (t1l3125.),
the argument of the TAB function should be 6- J. Thus, the
first character of the string t1l3125.49 will be positioned in
column zero.
RUN
9.67 9.67
3125.49 3125.49
.26 .26
85.17 85.17
123.45 123.45
14.21 14.21
67, 79, 77, 80, 85, 84, 69, 82, 32, 76, 73, 84, 69, 82, 65, 67, 89
9. Write a program that reads the five numbers 20, 15, 25, 40, and
60 into a one-dimensional array, then converts each number to
its string equivalent. Remember, some computer systems
include a leading space in the string equivalent, while others do
not. Thus, your output may differ from the one shown below.
RUN
20
15
25
40
60
630 PROGRAMMING IN BASIC
10. Write a program that uses a FOR/NEXT loop to control the following
operations: 15
(a) Generates fifteen random whole numbers ranging from 49to
57 inclusive.
(b) Changes each of these numbers to its ASCII character equiv-
alent.
(c) Converts the ASCII character to its ASCII code equivalent.
(d) Prints the ASCII character and its code widely spaced. Refer
to Chapter Nine, page 415, if you need help in generating
random numbers.
6 54
8 56
1 49
9 57
11. Modify your program for the above problem so that it generates
twenty-six random whole numbers ranging from 65 to 90 inclu-
sive .
E 69
G 71
L 76
A 65
15. If your computer system does not accept a string variable as the argument of the
ASC function , you may omit this problem
16. Remember , decimal notation is used for the ASCII codes.
INDEX 631
Index
A multiplication , 35 o
ABS function, 421 subtraction , 35 Data , 20
Accuracy, 124 BINAC , 3 sets o f, 160
Actual argument, 527 Binary notation , 585 Data bus , 6
Address bus, 6 Bit, 5 DATA statement , 79
Address register, 5 Branch , 108, 136 one-dimensional array, 257
Aiken, Howard, 2 conditional, 123 rules for, 80
ALGOL, 8 unconditional, 108, 123 tw o- dimensional array, 325, 326
Algorithm, 8 BREAK key, 15 Debugging, 20
Algorithmic language , 8 BREAK message, 515 De cimal notation, 585
AL T MODE ke y , 15 Bus , 6 DEF statement, 525
Anal og co mputer, 2 Bus line, 6 multiline user-defined function, 533
Anal ytical engine, 2 Byte, 5 single-line user-defined
Argument, function , 525
actual, 527 DELETE ALL command, 13
dumm y , 526,527 C DELETE command , 13
of a function, 400 Central Processing Unit (CPU), 4 DEL key, 14
o fTAB function, 444,44 7, 44 8 Centring headings , 464 DET fun c tion, 394
of the function definition, 526 using IMAGE statement , 464 Device controller, 6
of the function reference, 527 using PRINT USING statement , 464 Difference engine , 2
of the INT function, 407 using TAB function, 448 Digital computer, 1
oftheRNDfunction, 412 CHR$ function, 586,610 DIM statement, 315
SQR function, 422 CLEAR command, 13 MAT statements, 384
Arithmetic-Logical Unit (ALU), 4 CLR k'ey, 14 one-dimensional array, 254
Arrays, COBOL, 8 two -dimensional array, 323
one dimensional, 251 Coding , 20 Disk Operating System (DOS), 5
calculating with, 276 , 351 Compiler, 7 DONE message, 15
printing from, 264 , 335 Computer languages, 7 Doubly subscripted variable, 315
subroutine , 513 history of, 6 Dummyargument, 526
subscript with , 252 Computers , Dumm y set , 163
two dimensional , 315 analog , 2
ASC function , 610 BINAC , 3
AS C II codes, 585 digital , 1
list of, 586 EDVAC , 3 E
Assembler, 7 ENIAC , 2 Eckert , J, Presper , 2
Assembly language, 7 generations of, 3 Edit programs, 14
solid state, 3 EDVAC, 3
B UNIVAC I, 3 E format , 42
Babbage, Charles, 2 Concatenation, 590 Electronic computer, history of ,
BACKSPACE key, 14 Conditional branch, 123 END statement, 14,509, 515
BASIC, Connectors, 21 Engine, 2
definition, 8 off-page, 21 analytical, 2
expressions, 35 CONTINUE command, 15,515 difference, 2
extended, 9 Control bus, 6 ENIAC, 2
history of, 9 Control Unit (CU) , 4 ENTER key, 13
BASIC program, rules for, 17-19 Convers ion, 40 ESC key, 15
line number, 19 arithmetic into BASIC , 40 Expressions,
REM statement , 509 BASIC into arithmetic , 40 as step value , 214
statement, 18 Conversion formula, RND PRINT statement, 25 , 36 , 57
BASIC symbols , 35 , 111 , 120, 128, fun ction , 415 used as initial value , 209
135,205, 522 , 539 Corrections, 14 used as test value, 209
addition, 35 Counter, 130, 154 Extended BASIC , 9
division, 35 CTRL-C key, 15 External dev ice , 5, 6
exponentiation, 35 Cursor, 13,27,445 External media , 6
632 PROGRAMMING IN BASIC
~__ c: ~,-• • - -- • ~.
. .-::
_ , .-
••
_ _• I -~~_
,"
-4111
~.~ ~