100% found this document useful (1 vote)
78 views

Programming in BASIC A Complete Course (1982)

This document discusses programming in BASIC. It covers topics such as variables, arrays, loops, branching, functions, and strings. Various programming examples are provided to demonstrate different BASIC programming concepts.

Uploaded by

Delfin Butlonosy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
78 views

Programming in BASIC A Complete Course (1982)

This document discusses programming in BASIC. It covers topics such as variables, arrays, loops, branching, functions, and strings. Various programming examples are provided to demonstrate different BASIC programming concepts.

Uploaded by

Delfin Butlonosy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 644

·

• - -- - - - - - -- - - - ~
-

- - -
(
.
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

HOLT, RINEHART AND WINSTON OF CANADA, LIMITED TORONTO

L_
Copyright © 1982 by Holt. Rinehart and Winston of Canada. Limited.

All rights reserved.


It is illegal to reproduce any portion of this book except by special
arrangement with the publishers . Reproduction of this material by any
duplication process is a violation of copyright.

While every precaution has been taken in the preparation of this


book. no liability is assumed for damages resulting from the use of
the Information contained herein .

Published simultaneously in the United States of America by Holt,


Rinehart and Winston. Publishers, New York.. N.Y.

Canadian Cataloguing In Publication Data

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

Edito r : F.L. Barrett


Production Editor: Jocelyn Van Huyse
Cover and Interior Design: Maher & Murtagh Inc.
Typesetting, Assembly and Technical Art : Trigraph Inc.

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.

1,1 THE ELECTRONIC COMPUTER


The impact of the electronic computer cannot be minimized . It has
affected almost every one of us in one way or another. From the vital
function of data processing in business and government to the
modern technologies of medicine, space travel, and national
defense , computers have extended man's capabilities and knowl-
edge. They are now found quietly at work in such diverse places as
banks , department stores, hospitals, oil refineries, airports, pulp and
paper mills , schools , and newspaper offices.
What is a computer and why has its impact been so great? The
computer is an electronic device that uses stored data and instruc-
tions to generate information. Its dramatic effect on most of us is due
to its untiring performance and fantastic speed. When properly pro-
grammed, a computer is able to outperform thousands of office clerks
in speed and accuracy and is even capable of making logical deci-
sions .
Although the digital computer will mainly be discussed, you should
2 PROGRAMMING IN BASIC

be aware that there are two kinds of electronic computers - the


analog computer and the digital computer. The digital computer is a
machine that counts data in discontinuous form, while the analog
computer is a machine that measures values continuously. By using
gauges and meters, physical conditions, such as pressure, voltage,
temperature, and velocity, can be measured by analog computers .
Digital computers operate on numbers, letters of the alphabet, and
other symbols which are transformed into discrete binary (base two)
electronic signals. They solve problems by following instructions
which have been submitted in the form of a program.
The development of the electronic digital computer will quickly be
reviewed. The first machine designed with features that are found in
today's computers was conceived by Charles Babbage, a professor
atTrinity College in Cambridge, England. A mathematical genius, he
developed a computing machine in 1822 that was capable of calculat-
ing logarithmic tables automatically. He called it the Difference
Engine. Realizing that computing machines should be able to solve
any numerical problem, he became interested in designing a general
purpose machine. This change in plans resulted in the withdrawal of
the financial aid he was receiving from the English government, and
his work on the Difference Engine was abandoned. For the remainder
of his life, Babbage concentrated his efforts on a machine that he
called the Analytical Engine. Embodying many of the principles
used in modern computers, it included an arithmetic unit, a storage
unit, and a control unit. Instructions were submitted on punched
cards, and results were printed by an output unit. Unfortunately,
Babbage worked on ideas that surpassed the technology of metal-
lurgy, and his Analytical Engine, begun in 1830, was never com-
pleted. It was not until the twentieth century that his original ideas
were incorporated in the first operable computer.
In 1939, Professor Howard Aiken developed an electromechanical
machine known as the HARVARD MARK I. Successfully completed
in 1944, it is considered the world's first workable machine capable of
solving a series of mathematical and logical problems. However, it
was not fully electronic, since it used mechanical devices to perform
these calculations. The MARK I was huge. It had a mass of five tonnes
and consisted of over seventy devices connected by hundreds of
kilometres of wiring. A set of sequential instructions punched into
paper tape automatically controlled its operations. Punched cards
supplied the data, and output was either punched into new cards or
typed. Although the MARK I could provide results faster than any
machine of its time, it is considered slow by today's standards
because of its electromechanical design.
In 1946, J. Presper Eckert and John Mauchly built the first all-
electronic computer called the ENIAC (Electronic Numerical Integra-
tor And Computer). The electromechanical devices used by the
MARK I were replaced by a large number of vacuum tubes . Electronic
pulses flipped these vacuum tubes on and off much like turning an
electrical switch on and off. The computer received its instructions by
means of plug boards (control boards) which had to be hand-wired by
highly skilled technicians. Its size was enormous. With over 18 000
vacuum tubes, it covered more than 135 m 2 (the floor space of an
average-sized house) and generated so much heat that it had to be
cooled by extensive air-conditioning systems. Before each program
could be RUN, 6 000 switches had to be set and its 18 000 tubes had
COMPUTERS AND COMPUTER LANGUAGES 3

to be in functioning order. Still, the ENIAC was a remarkable machine.


With no moving parts other than its input and output units, calcula-
tions could be performed one thousand times faster than by the MARK
I, since electric currents move more quickly than electromechanical
devices. A union had taken place between electronics and comput-
ers, one that has flourished right up to the present.
It soon became apparent that the formidable, time-consuming task
of wiring in a program was unnecessary. If instructions and data could
be stored in the memory of the computer, new programs could be
written without making changes in hardware. The concept of the
stored program was the contribution of John von Neumann , a
mathematician, who helped design the EDVAC (Electronic Discrete
Variable Automatic Computer), the first digital computer that used
the principle of a stored program . The notion of internal program-
ming proved to be a breakthrough in computer design, and even
with today's advanced technology, it remains a feature of modern
computers .
The year 1949 heralded a new dimension in computer design. A
much superior machine called the BINAC introduced magnetic tape
for mass storage of information , and its crystal diodes replaced the
many vacuum tubes as switches . It used binary (base two) arithmetic
by transmitting electronic pulses through tubes that were filled with
liquid mercury. The presence of an electronic pulse represented one
binary digit. Its improvements reduced the size of computers from a
machine occupying 135 m2 of floor space to one occupying the space
of two over-sized filing cabinets . After BINAC, improvements in elec-
tronic computers progressed with amazing speed . In 1951, the
UNIVAC I (Universal Automatic Computer) carried out statistical
analysis and processed business data, rather than scientific and
engineering information. It marked the beginning of automatic data
processing.
By 1959, computers no longer depended on vacuum tubes for any
of their operations. Transistors replaced these tubes and computers
were now referred to as solid state computers . The machines
required very little power, generated minimal amounts of heat, and
were much more compact and reliable. Computing power increased
and new types of input/output equipment were introduced.
The year 1965 saw a revolution in the computer industry with the
development' of the integrated circuit (IC). Transistorized circuits
were mounted on a silicon chip by photoelectrically etching the
design on the chip. At first only a few transistors were etched on a
chip the size of a quarter. Since then, densities have increased
rapidly . Today, the technique is so refined that transistorized circuits
can be laid down on a chip about the size of the period at the end of
this sentence. A Large Scale Integrated (LSI) circuit, more compli-
cated rhan the ENIAC which had a mass of 30 t, can now be placed on
your fingertip!
Traditionally, computers have been categorized into generations ,
with each generation introducing a drastic change .
(a) The first generation used vacuum tubes (1946) .
(b) The second generation used transistors (1959).
(c) The third generation used integrated circuits (1965).
Since the appearance of the integrated circuit , component densities
have increased to such an extent that many people believe com put-
4 PROGRAMMING IN BASIC

ers are now in the fourth generation (LSI) or even in the fifth genera-
tion (VLSI-Very Large Scale Integration).

1.2 THE MICROCOMPUTER


The history of the microcomputer is understandably brief, since its
introduction to the general public has just recently taken place.
I. History of the
Commercial Large Scale Integration (LSI) first appeared in 1971 , Microcomputer
developed by companies that were new in the computer business
and that found a potential market for their product in the form of desk
and pocket calculators. The first general purpose microprocessor (an
LSI component that holds most of the functions of a conventional
computer) was developed in 1971 and was expanded upon the
following year. Placed on the market to promote memory chips, its
sales took everyone by surprise. The dynamic market for the
microprocessor sent the original manufacturer and his competitors
scurrying to redesign the faulty processor.
Microcomputers were first sold in 1975 as computer kits directed
mainly at the electronic hobbyist and engineer . The first completely
assembled microcomputer designed for non-technical personnel
was introduced to the general public in 1977. From the humble
beginnings of an LSI chip, a new industry emerged, brought about by
the declining cost of the assembled product and by its dramatically
reduced size. Today , many individuals and small business firms can
afford computing power with the result that several related industries
and support services have come into being. These include computer
consultants, who provide software (programs), publishing compa-
nies that issue computer magazines and books, computer stores that
provide both sales and service, and computer clubs, shows , and
conferences. Of these developments, the provision of software has
become the most crucial. Before a computer can function, it must be
told what to do . Detailed instructions written for the computer are
called programs (software) , and unless one can write one's own, they
must be purchased. (They are stored on either cassette tapes or on
magnetic disks.) Today, software is being developed at an alarming
rate , ranging from accounting systems to word processing, from
scientific applications to computer games. Most of these are mass-
produced and sold in cassette form. Should an individual wish to have
a tailor-made program , it must be written by either the individual or by
a professional programmer. It is interesting to note that in recent
years, software is becoming more expensive than some of the
hardware. This phenomenon has come about because of the
reduced cost of electronic components and the increased cost of
programming.

The structure of a microcomputer system is basically similar to that of


a conventional computer system, since it comprises the same five
II. Architecture of the
fundamental units. These include the Control Unit (CU) and the Microcomputer System
Arithmetic-Logical Unit (ALU) , which together form the Central
Processing Unit (CPU), memory, an input module, and an output
module.
First, the internal structure of a microcomputer (the CPU or
microprocessor unit, the main memory , and the interface circuitry)
COMPUTERS AND COMPUTER LANGUAGES 5

will be examined. This will be followed by a brief discussion of


external devices usually referred to as peripherals.

1. The Microprocessor Unit (MPU)


The heart of a microcomputer is the tiny silicon chip called the A. The Internal Structure
microprocessor chip. In spite of its minuscule size, this LSI compo-
nent incorporates all the functions of a traditional CPU. The features of a Microcomputer
that make microcomputers so different fromother computer systems
are their reduced cost and size brought about by the microprocessor.
The cost of a processor is presently one of the least expensive
components in a microcomputer, while its compactness has reduced
the size of am icrocomputer system to such an extent that a computer
can now be placed on the top of a desk. But what is truly remarkable
about the microprocessor chip is its programmability, a feature that
makes it so versatile that it is now considered a peripheral to other
equipment , such as pocket calculators, digital watches, microwave
ovens, and video games. The microprocessor in a computer system
includes the following units:
(a) The Arithmetic and Logical Unit (ALU), which contains the cir-
cuitry that performs arithmetic operations, such as addition,
subtraction , multiplication, and division, and makes logical deci-
sions, such as determining the relationship between two values;
(b) The Control Unit, which supervises the functions of the computer
by generating and regulating all control signals so that the sys-
tem's operations and the flow of data are synchronized. Its main
function is to retrieve, interpret, and execute instructions that are
stored in the computer's main memory.
Microprocessors are equipped with several registers that act as
small memories to store information temporarily . Examples of such
reg isters are the instruction register that holds the current instruction,
the address register (or registers) that stores the address of the data
item or instruction, and a program counter that holds the address of
the next instruction.

2. The main memory


The main memory of a microcomputer system comes in the form of
specialized memory chips mounted on printed circuit boards. There
are two types of memory: one type is called Random Access Memory
(RAM), to which information can be written and from which informa-
tion can be read; the other is called Read Only Memory (ROM), from
which information can only be read. Microprocessor programs and
frequently used instructions are written permanently into ROM, mak-
ing this type of memory unavailable to the user. Information in RAM is
lost when the computer is turned off, while the information in ROM is
permanent and is always available.
Memory consists of thousands of storage locations called bytes.
Each byte is capable of storing one character, which usually consists
of eight binary digits generally referred to as bits. Since the bits are
operated on as a unit, a byte is the smallest accessible part of
memory. The memory section of a microcomputer contains one or
more printed circuit boards with a storage capacity that usually ranges
from 4K to 64K bytes (K represents one thousand). Not all of this is
users' programmable memory. Some of it is taken up as ROMS and
some of it is used as a work space, particularly for the Disk Operating
6 PROGRAMMING IN BASIC

System (DOS), when a disk drive is used to store and retrieve


information. On the whole, most of the computer's memory is users'
K (RAMS).

3. Input/Output interface chips


The rates of data transmission for input/ouput devices such as key-
boards, printers, and readers are much slower than the transmission
rate of a microprocessor. A special printed circuit board called an
interface must be installed to enable an external device to communi-
cate with the MPU. There are two types of interfaces, serial and
parallel. Serial interfacing transmits bits in a series, one bit following
the other at an exact rate. Parallel interfacing sends bits simultane-
ously. If eight bits are transmitted, then eight wires are needed
to transfer the bits side by side. Teletypes, cathode ray tubes, and
other communication terminals require serial interfacing; printers,
keyboards, paper tape readers, and card readers need parallel
interfaci ng.
Communication lines, grouped by function, connect all internal
components of a microcomputer. Each group is called a bus. There
are generally three types of buses to provide this communication: the
data bus, which transmits data; the address bus, which selects the
location (origin or destination) of the data to be transferred; and the
control bus, which transmits control signals . A cabinet, referred to as
the mainframe, houses the microprocessor, memory, interfaces,
and bus lines. Today, the technology of LSI circuits has advanced to
such an extent that all the functions of a simple computer (micropro-
cessor, memory, and peripheral circuitry) can be incorporated on a
single chip , the microcomputer-on-a-chip . However, most micropro-
cessors require non-resident memories (the main memory) and
external input/output circuitry (interface chips).

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 .

1.3 COMPUTER LANGUAGES


A computer is unable to function automatically unless it receives
explicit instructions. This series of instructions is called a program
COMPUTERS AND COMPUTER LANGUAGES 7

and the procedure for developing the series is called programming.


The first programs, written in the early 1950s, were in machine
language - a numeric language expressed as a combination of ones
and zeros. Based on the binary numbering system, machine lan-
guage lends itself perfectly to the two possible conditions of a circuit
which can be turned either on or off. Since the controlling circuitry of
the central processing unit understands these conditions, no transla-
tion of the language is necessary. However, this causes the language
to be machine -dependent, making it necessary for the programmer
to fully understand the internal structure of the computer being used.
Programming, therefore, becomes cumbersome, onerous, and sub-
ject to many errors. This is especially true when instructions and data
must be referenced by their storage locations.
To ease the programmer's task, symbolic (assembly) languages
were developed. These employ symbols (alphabetic characters
referred to as mnemonic codes) to denote the machine language
instructions. Since operation codes, such as ADD, SUBT, and DIV ,
more closely resemble the English language, programmers find
symbolic languages simpler to learn and easier to use, especially
after they become familiar with the required op-codes (symbols). An
assembly language cannot be used directly by a computer. It must
first be translated or assembled into machine language instructions.
The computer performs this translation by using a special program
called an assembler supplied by the manufacturer. The assembly
language usually has a one-to-one correspondence with the machine
language and is therefore assembled on this basis . This results in a
program that has the same instructions as the original program but in
machine-language form. Because of this close relationship with
machine language, an assembly language continues to be depen-
dent on the model of computer in use . Although not as complex to
write , programming in an assembly language remains a detailed and
time-consuming task.
The need for a problem-oriented language , and one that more
closely resembles the human language, soon led to the development
of several high-level languages such as FORTRAN, COBOL ,
ALGOL, PL/I and BASIC. Working in this type of language, a pro-
grammer need not be involved with the details of computer operation
and is able to shift his concentration to the development of a program.
The languages are easier to learn and, because of their machine-
independent feature, can be used on a variety of computers with only
minor modifications. However, these problem-oriented languages
must be translated into machine language by a manufacturer-sup-
plied program. This is either a compiler or an interpreter, depending
on the language being translated . An interpreter executes
(processes) each statement immediately after it is translated, while a
compiler translates a whole program and executes it at a later time .
Each language has its own compiler or interpreter. For example, each
of the languages FORTRAN and COBOL requires its own compiler, while
interpretive BASIC , the version adopted by most microcomputers, is
translated by an interpreter. Programs written in high-level languages
are called source programs; their translated versions are referred to
as object programs. Here is a brief summary of some of the high-
level languages currently in use.
8 PROGRAMMING IN BASIC

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.An algorithmic language is a procedure-oriented language which solves a problem


by setting up a series of well-defined steps (procedures). A detailed set of instruc-
tions to solve a specific problem is called an algorithm

2.lnteractive programming allows an individual to work interactively with the com-


puter, as if in a two-way conversation The user gives information to the computer
and receives information from it while the program is being processed In a time-
sharing system, several remote terminals have simultaneous access to a centrally
located computer. Telephone lines connect the terminals to the computer.
COMPUTERS AND COMPUTER LANGUAGES 9

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

high-level languages cannot be used directly by the computer and


must be translated first into machine language instructions. BASIC ,
one of the many problem-oriented languages in use today , was
designed primarily for interactive situations and is currently the lan-
guage adopted by most microcomputers.

QUESTIONS FOR REVIEW


1. State the function of
(a) The analog computer.
(b) The digital computer.
2. (a) What two computing machines did Charles Babbage
design?
(b) What was the reason for the development of each machine?
(c) State some of the principles embodied in his second
machine that are included in today's computers. Why was it
not possible to completely build a modern machine during
his time?
3 . (a) Who designed the MARK I?
(b) When was it successfully completed?
4. (a) Who developed the ENIAC?
(b) Give a brief description of this computer.
5. What was the main difference between the MARK I and the ENIAC?
6. What important contribution did John von Neumann make in the
design of a computer?
7. What three featu res did the BINAC introduce?
8. State four improvements that solid state computers had over
computers that used vacuum tubes .
9. (a) What do the letters LSI mean?
(b) Briefly describe how an LSI circuit is made.
(c) How has the density of its circuitry changed?
10. Computers have been categorized into generations. Character-
ize each generation, giving its introductory year.
11. Briefly summarize the history of the microcomputer.
12. (a) What is meant by software?
(b) In what two ways can software be purchased?
(c) What is the recent trend with respect to software and hard!
ware?
13. What five fundamental units do all computer systems possess?
14. (a) What is meant by a peripheral?
(b) Give three examples .
15. (a) Name the two main components of a microprocessor and
state the functions of each .
(b) Why are microprocessors equipped with several registers?
16. (a) Give the definition and purpose of
(i) RAM,
(ii) ROM .
(b) What is a byte?
17. (a) What is the purpose of an interface chip?
(b) What is the difference between serial interfacing and parallel
interfacing?
COMPUTERS AND COMPUTER LANGUAGES 11

18. State the purpose of each of the following


(a) Data bus
(b) Address bus
(c) Control bus
19. What is meant by a microcomputer-on-a-chip?
20. Give two examples of external media used for mass storage of
information.
21. (a) State two features that differentiate machine lang uage from
symbolic languages .
(b) What feature makes them similar?
22. Other than be ing easier to learn, what advantage do high-level
la ng uages have over machine and symbolic lang uages?
23. What is the differen ce between an interpreter and a co mpiler?
24 . State the main purp ose for the development of each of the
following high-level languages .
(a) ALGOL
(b) FORTRAN
(c) PUI
(d) COBOL
(e) BASIC
25. At first BASIC was limited to approximately 20 words . How has this
been rectified and what is the resultant problem?
12 PROGRAMMING IN BASIC

TWO INTRODUCING BASIC


A. Through the study of this chapter, you will become familiar with :
1. The structure of a BASIC program.
2. The rules that must be observed when writing a BASIC pro-
gram.
3. REMARK statements.
4. Executable and non-executable statements.
5. Flowcharting symbols.
6. Integers and floating-point numbers.
7. The BASIC symbols for arithmetic operations.
8. The hierarchy of operations including parentheses.
B. You should be able to :
1. Operate the system commands on an interactive system.
(a) Clear the computer's memory.
(b) Transmit a typed statement or command to the com-
puter's memory .
(c) Displaya program.
(d) Clear the screen.
(e) Terminate a program.
2. Make corrections in a BASIC program using an interactive
system.
3. Delete and insert lines in a BASIC program using an interactive
system.
4. Draw flowcharts for simple BASIC programs.
5. Evaluate BASIC expressions.
6. Produce the output of programs.
7. Convert arithmetic problems into BASIC expressions and vice
versa.
8. Convert numbers from arithmetic notation to scientific nota-
tion and vice versa .
g. Write BASIC programs using PRINT statements that
(a) Leave blank lines .
(b) Evaluate expressions.
(c) Print messages (strings).
(d) Use commas to separate items.
(e) Use semicolons to separate items.
(f) Print strings and numeric values on one line.
(g) Use a comma or a semicolon at the end of the first of two
PRINT statements to output two items on one line.
(h) Counteract the comma or semicolon placed at the end of a
PRINT statement.

- -- - - -- - - -- - - - -- _.._ - - -- -- - -
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 .

2. Clearing the computer's memory


It is important that you erase any "old " program that is stored in the
computer's memory before typing in a new program . On most com-
puter systems, this command does not clear the screen. Type one of
t~~mands shown below, then press IRETURNI or IENTERI or ICRI.

-- ---
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.

3. The [RftlJi!N] or [ENT"JRl or ICRI key


One of the above keys must always be pressed after each statement
or command is typed. The appropriate key transmits the typed
statement or command to the computer's memory. Similar to the
carriage return on a typewriter, it allows you to type the next entry at
the beginning of a new line . Throughout this book , the IRETURN I will be
used for this particular command. However, many computer systems
do not require a IRETURNI signal if another command key, such as
I STOP!, has been depressed .

4. Displaying a program on the screen


To display a program currently stored in memory , type L~r LIS or
LI or L), then press the I RETURNI key. Most version~~c auto-
matically list the line numbers in ascending order, regardless of the
sequence of their entry into the computer. There are several LIST
commands.
(a) LIST without a line number displays your whole program.
(b) LIST 100 displays only line 100.
14 PROGRAMMING IN BASIC

(c) LIST 40,100 displays lines 40 and 100.


(d) LIST 40-100 displays lines 40 to 100 inclusive.
(e) LIST - 40 displays all lines up to and including line 40.
(f) LIST 40- displays all lines from 40 to the end of your program
(including line 40).

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.

5. Executing (processing) instructions


Th~Wor RU command instructs the computer to execute your
program, ~g with the lowest line number and terminating when
either an @Dl statement, a STOP statement, or the highest line
number is reached. Type RUN or RU, then press the !RETURN! key . If
there are errors in your program, the computer will show you which
lines are incorrect and will print diagnostic messages to tell you what
is wrong. It is a good idea to LIST your program before RUNning it, just
to make sure that your instructions are correctly stored in memory.

6. Clearing the screen


To clear the entire screen without erasing your program from mem-
ory, depress the! CLR! key; or type CLS or HOME, then press !RETURN!.
On some computer systems, the ~ command not only clears your
screen, it also deletes the line you are currently typing. All the lines
previously typed remain in memory.

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.

2.1 SYSTEM COMMANDS- Your Turn


Even though you may not understand what you are typing, it doesn 't
matter . The main concern of this section is to give you an opportunity
to use the different system commands . You will be asked to key in
several programs, each one stressing a different set of commands.
Try all those given for a particular operation , and if none of them work,
consult your manual or ask someone who knows. The page number
where the command was introduced is typed after each exercise .

1. Clear the computer's memory of all old instructions . (Page 13)


2 . Enter the following program into the compu·ter . Remember to
I. Commands Required
press I RETURNI after each statement has been typed . (Page 13) to Enter a BASIC Program
into the Computer and to
1~ PRINT
Execute the Program
20 LET A=l
30 PRINT A
40 L.ET A=A+l
50 IF A>5 THEN 99
60 GO TO 30
99 END
16 PROGRAMMING IN BASIC

3. Display the program on your screen . (Page 13)


4. Execute the program. (Page 14)
Your RUN should produce the following results.

RUN

1
. \
A.•

3
4

,-,

5 Clear the screen. (Page 14)


Your screen should now be blank. LIST the program again. If
everything went right, the program should reappear on your
screen.

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

1. Erase the old program from memory.


2. Key in the fOllowing program .
III. Terminating Execution
of a Program
1~ LET A=l
20 PRINT A
30 LET A=Atl
40 GO TO 20
99 ENII

3. LIST and RUN the program . Your RUN should produce the follow-
ing.

RUN
1
2
3
4
".w
6
7

Notice that the computer continues to process the instructions.


4. Terminate the program. (Page 15)

2.2 A BASIC PROGRAM


A number of rules must be observed when you write a BASIC program.
Below is a sample program to which you can refer as the rules are
being presented. Do not enter the program into your computer; it is
here merely as an aid to help you understand the rules.
18 PROGRAMMING IN BA SIC

~1 REM THIS PROGRAM FINDS THE AVERAGE


~2REM OF 4 NUMBERS
~3 REM K-'-COUNTER
~4 REM S--'SUM
05 REM N1---"NUMBER" OF NUMBERS
06 REM N--NU11BEF~S TO BE AVEF'~IGED
~7 REM A--AVEF:AGE

HH:1 REM INITIALIZE THE VARIABLES


110 PRINT
120 LET K=l
130 LET S''''0
2e0 REM READ THE DATA
21~ READ Nl.
22f1 READ N
23f1 DATA 4,67,85,79,93
300 REM ADD, PRINT THE NUMBERS
3f11 REM AND THE ACCUMUL.ATED SUM
310 LET S=StN
320 PRINT N,S
400 REM INCREMENT THE COUNTER
410 LET K=K+1
420 IF K>Nl THEN 51210
430 GO TO 220
50f1 REM FIND THE AVERAGE
510 LET A=S/Nl
600 REM PRINT THE AVERAGE
61f1 PRINT
62f1 PRINT "THE AVERAGE IS:";A

999 END
RUN
67 67
81:',J 1""")
..J.:..

79 231
93 324

THE AVERAGE IS: Bl

1. All BASIC programs consist of statements. Rules


2. Each statement may not exceed a certain number of characters .
Some versions of BASIC allow seventy-two characters , some
allow seventy-nine characters , and others allow even more . If the
allowed maximum is exceeded , either the excess characters are
ignored or the entire statement is ignored . An error message
INTRODUCING BASIC 19

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.

130 LET S=£1

2. An integer is a number that has no decimal point.


3. Programs are documented by inserting explanations throug hout the programs to
make them easier to understand .
20 PROGRAMMING IN BASIC

5. The programs in this book include END statements. The END


statement will be the highest-numbered statement in a program.
In the sample program, the END statement is numbered 999.

999 END

6. Programs are made up of executable statements and non-


executable statements . An executable statement is an instruc-
tion, one to which the computer can respond by following a
direction. A non-executable statement is not an instruction,
therefore, the computer does not execute (process) this type of
statement. Examples taken from the sample program are
Executable statements :

220 E:EAD N
41.121 LET K:::Ktl
620 PRINT "THE AVERAGE IS:";A

Non-executable statements: The REM statements

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,

An oval represents a terminal point, either


the beginning or the ending of a program. ( )
A parallelogram indicates an input or an
output operation.
/ /
INTRODUCING BASIC 21

A rectangle denotes a processing opera-


tion.

Lines of flow connect two symbols. Arrow-

11 <
heads show the direction of programming
logic.
~

Circles , called connectors, are used


instead of lines and arrows to connect
symbols when processing lines are long
and complex . With an appropriate letter or
number inside, one connector denotes an
exit from one part of the flowchart , while a
second connector indicates the entry to
another part of the flowchart, thus main-
taining a continuous flow of logic.
0
An off-page connector indicates that the
flowchart is continued on another page.

As concepts are developed throughout the book, other symbols will


be introduced and other flowcharts displayed to help you understand
more easily a program's logic.
Although flowcharts vary in detail, a few basic rules are usually
observed .
1. Construct the flowchart so that the direction of programming
logic flows from top to bottom and from left to right.
2. Connect all symbols with lines and arrows, or connectors .
3. When there are several entries to one symbol, point the lines to
the main line entering the symbol.
Permitted Not permitted

'I
22 PROGRAMMIN G IN BASIC

4. Place a description of the operation inside each symbol.


5. Use a template to draw a flowchart. A template is a piece of
plastiC usually 10 cm long and 25 cm wide in which the symbols
have been cut.

2.3 FLOWCHARTING-Sample Program


Shown below is a flowchart for a program that adds two numbers ,
then prints their sum . Do not be too concerned if you don't under-
stand how the computer processes some of the statements. This will
be covered in another chapter. At the moment , all that is required is to
learn to flowchart a simple BASIC program .

The program

01 REM N1--FIRST NUMBER


02 REM N2--SECOND NUMBER
£13 REM S--SUM
HI READ N1,N2
2£1 DATA 7,5
3£1 LET S=Nl+N2
41?1 Pf".:INT S
99 END

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

2.3 FLOWCHARTING- Your Turn


Draw a flowchart for the following program. This program subtracts
one number from another, then prints the difference. Opposite each
symbol, write the appropriate statement(s).

~l REM NI--FIRST NUMBER


~2 REM N2--SECOND NUMBER
03 REM D--DIFFERENCE

READ Nl,N2
lli1
2~ DATA 12,5
3~ LET D::N 1--N2
40 PRINT [I
99 END

2.3 FLOWCHARTING-Solution for "Your Turn"


N1 - FIRST NUMBER
N2 - SECOND NUMBER
D - DIFFERENCE

( 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

2.4 THE PRINT STATEMENT


The PRINT statement gets information out of the computer so that you
are able to see it. This information is either displayed on a screen or
typed on paper and is in the form of numbers and messages. Some
PRINT statements also leave blank lines wherever you wish to have
them in your output. Here are two simple programs using PRINT
statements that leave blank lines.

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

In Program 1, the statement 10 PRINT leaves a blank line just before


the output. In Program 2, the statement 30 PRINT leaves a blank line
between the two values in the output. Most programs in this book
leave a blank line right after the word RUN (in other words, before the
output). To achieve this and to be consistent, the PRINT statement is
placed just before the one that prints the results.

10 PRINT ~--
( Placed just before the statement that prints the results.
20 PRINT 3
9<; END
RUN
(
~------ Blank line before the results.
3

Some computer systems allow you to type a question mark instead of


the word PRINT. For ease of reading, it is better to use the word.

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 ./
.......

Notice that no quotation marks are printed in the output. Messages


are often used as headings or to identify results. For example, THE
AVERAGE IS: 81.
A program that prints both a string and the result of a calculation is
shown below.

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.

2,4 THE PRINT STATEMENT - Your Turn


If you are using a microcomputer, remember to clear any old instruc-
tions from the computer's memory before keying in a new program.
(It is assumed that you will remember this from now on.) Page
numbers are given for programs similar to the ones you are to write,
so that you can refer to these pages if you need any help.
1. Write a program that prints your name on one line, 12+5 on the
next line, and the answer to 12+5 on the last line. Leave one
blank line after the word RUN, (Page 25)
26 PROGRAMMING IN BASIC

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

2.4 THE PRINT STATEMENT-Programs for


"Your Turn"

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

2.5 THE PRINT STATEMENT WITH COMMAS


OR SEMICOLONS
Until now, only one value or message per line has been printed, using
a separate PRINT statement for each line of output. It is possible to
print several items on one line with just one PRINT statement. The
items are printed across the line with a specific number of spaces
between each item. The values listed in the PRINT statement must be
separated by either commas or semicolons. On most computer
systems, a comma tells the computer to print the items spread widely
across the page or screen, while the semicolon causes the items to
be printed closer together. However, there are exceptions. A few
computers do not recognize the comma in a PRINT statement, but
INTRODUCING BASIC 27

treat it as a semicolon instead. Thus, the output is always closely


spaced .
,
Commas in a PRINT statement usually divide an output line into zones I. Commas in the PRINT
of fixed and equal width. The number of zones and the width of each
zone are dependent on the computer system . Most computers have StatementS
either four or five zones with 10, 15, or 16 characters to each zone.
Only one item is printed in a zone.
It was mentioned earlier in the chapter that pressing the IRETURNI
key transmits a statement to the memory of the computer. Suppose
the last character of a statement is in the last print position of a line and
that the cursor has automatically dropped down to the beginning of
the next line. To transmit the statement to memory, you must still
press the IRETURNI key, even though the cursor is positioned on a
new line. It was also mentioned that the number of characters to a
statement varies among computers . To be consistent, all programs in
this book are written for a computer that allows 79 characters to a
statement but permits only 40 characters to a display line (each line
has four zones with ten characters to a zone). This means that a
statement can use 40 print positions in the first line and 39 in the
second. In the first nine chapters, statements are brief so that they fit a
40-character line. Statements in the other chapters are longer. It
should also be mentioned that, wherever possible, output is given to
help you understand a new concept in a sample program and to
indicate the results you should obtain for a "Your Turn " problem or a
programming problem .
Now, try some sample programs. A comma between two items in a
PRINT statement causes the second item to be printed on the same
line but in the next available zone. If there are more items than zones ,
the computer prints the remaining items on successive lines, using all
the zones in one line before going on to the next line.

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

it is filled in with a minus sign . The follow ing is an example of a RUN


with positive and negative numbers .

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

Strings usually start in the first position of each zone.

1.0 PRINT
20 PRINT "HI,',"HOW","ARE","YOU?"
99 END

RUN
HI, HOW ARE YOU?
I I I I

First position of each zone

It is common pract ice to use one PR INT statement to print a combina-


tion of strings and numbers . Here is an example .

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

Zones of varying widths

Do not be too concerned if your output turns out differently . Some


computer systems leave one space before and one space after the
number in each zone, regardless of whether the number is signed or
unsigned. As a result, numbers no longer line up. Compare the
output below with the one just shown .

RUN
f1l1221133311444411555551
~ 1-2211-33311-444411-555551

One space before and one space after each number

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

One space before each number

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

For computers that leave no space between numbers in the output ,


it is necessary to insert a space . Examine the following program .
.,
UI PRINT
20 PRINT U I ";22;' I ;333; I I ;4444; I ";5
5555
99 END

To obtain a space between the output numbers, one space is


enclosed in quotation marks after each number in the PRINT statement
(except after the last number) . Notice , also , that the PRINT statement
exceeds 40 characters and is continued on the next line, starting in
the first position of the line .
Semicolons separating strings in a PRINT statement cause mes-
sages (strings) to be printed with no space between them . This is
because each string starts in the first position of a zone .

Hl PRINT
20 PRINT "HI,";"HOW";"ARE";"YOU?"
99 END
RUN
HI,HOWAREYOU?
I I I I

First position of each zone

To print a more legible line, each string that is followed by another


string should have a trailing space coded within its quotation marks.

2111 PRINT "HI, ";"HOW ";"ARE ";"YOU?"


t
Space
t
Space
t
Space

Another solution is to code a leading space in each string that is


preceded by another string.

20 PRINT "HI,";" HOW";" ARE";" YOU?"

t
Space
t
Space
t
Space
--~~----------------------------------- --

INTRODUCING BASIC 31

A RUN of a program using either one of the above statements now


produces the following .

RUN

HI, HOW ARE YOU'!'

Here is a program that combines strings and numbers . The program


on page 28 used a comma to separate the items ; this one uses a
semicolon .

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

10 PRINT 10 PRIN T ~space


20 PRINT • HI' , 2111 F'RI NT • HI" ;
30 PRINT "THERE" 30 PRINT 'THERE"
99 END Printed on 99 END Printed on
the same the same
RUN line. RUN line.

HI THERE HI THERE ~------I


32 PROG RAMM IN G IN BASIC

Notice the space in the string "Hit" in Program 2. This space is


needed , otherwise your output will be HITHERE. The output in
Program 1 will run the words together if you are using a computer that
treats a comma as a semicolon. To get a space between the two
words, line 20 in Program 1 should be changed to 20 PRINT "HI" ,.
If your computer leaves a space before a number, no trailing space
needs to be coded in the string that precedes the number.

1111 PRINT
20 PRINT 4" NUMBER ";
3B PRINT j
99 END No space

RUN

NUMBER 4
i
Space

There is a technique to counteract the comma or semicolon that


appears at the end of a PRINT list. Have a PRINT (the one that prints a
blank line) as the next PRINT statement. This causes the output of a
subsequent PRINT to be placed on a new line . It 's the same as not
having a comma or a semicolon after "HI" in the above programs.

1. Using a Comma 2. Using a Semicolon

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

Note that no space is inserted in the string "HI" in Program 2 since


the next word (THERE) is printed on a new line.

2.5 THE PRINT STATEMENT WITH COMMAS


OR SEMICOLONS-Your Turn
You will now have the opportunity to try the various PRINT statements
on yo ur own. There are man y sample programs in the previous unit;
INTRODU CING BASI C 33

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

Your RUN should be as follows .

RUN

LAST
OUESTION
34 PROGRAMMING IN BASIC

2,5 PRINT STATEMENT WITH COMMAS OR


SEMICOLONS- Programs for "Your Turn"

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

2.6 INTEGERS, FLOATING-POINT NUMBERS,


HIERARCHY OF OPERATIONS
There are two terms you should be familiar with before you start
working with BASIC expressions.? One is the term integer and
the other is the term floating-point . Both refer to numbers. An
integer is a number that has no decimal point; a floating-point number
is one that has a decimal point. Floating-point means that the decimal
point "floats" or moves within the number depending on the value
you want . For example, the number 257 may be changed to 25 .7 or
2.57 or .257 or .0257, etc., by moving the position of the decimal
point. In BASIC, numbers (whether integer or floating-point) are oper-
ated on by arithmetic operators. These operators must be in a form
that is understood by the computer. You have already had examples
of addition and subtraction in the previous sections. Here is a com-
plete list.

Operation Symbol in BASIC


Addition +
Subtraction
Multiplication *
Division /
Exponentiation 8 i or ** or 1\
(The act of raising a
number to a power-for
example, 42 = 4 x 4 = 16.)

When two or more operators appear in one statement, confusion


may arise as to which one is processed first. This is solved by a set of
rules known as the hierarchy of operations . The order of execution
is as follows.
1. Exponentiation
2. Multiplication and division - Multiplication and division have
equal priority, therefore these operations are performed in the
order they appear in a statement . (The computer always
processes a statement in a left-to-right direction.)
3. Addition and subtraction -As in multiplication and division,
addition and subtraction have equal priority, which means that
these operations are also processed in a left-to-right order.
When a statement contains parentheses, the operations within the
parentheses are executed first, starting with the innermost pair of
parentheses, then moving outwards to the second innermost pair,
then to the third innermost pair, etc . If there are two sets of parenthe-
ses, one following the other, the computer clears the first set of
parentheses before clearing the second . In the expression
(2+3)/(7-2)

7. When arithmetic operators connect numbers or variables or a combination of one


or more numbers with one or more variables . a BASIC expression is formed .
8. Throughout this book the symbol i will be used to represent exponentiation .
36 PROGRAMMING IN BASIC

the computer performs the addition in the first set of parentheses,


then the subtraction in the second set of parentheses, and finally the
division. Parentheses can alter the normal order of execution. For
example:
2+(3*4) = 14 but (2+3)*4 = 20
It should be mentioned that two arithmetic operators may not be
written consecutively. The expression 3*-4 is invalid, while 3*( -4)
is valid. You may also have more than one expression in a PRINT
statement.

H'l PRINT
20 PRINT ~+1,0tl+2,~+1+2+3,0+1+2+3+4
99 END

RUN

1 3

2,6 INTEGERS, FLOATING-POINT NUMBERS,


HIERARCHY OF OPERATIONS-Sample
Problems
1. The following BASIC expressions will be evaluated twice; first by
hand and then by the computer. Go over each step so that you
understand how the computer follows the rules of hierarchy.
Note that just one arithmetic operation is performed at a time.
(a) 5*3-4/2+1 (c) 7*2-(41'2-8)/(3+1)
V V
15-4/2+1 7*2-(16-8)/(3+1)
V
15- 2+ 1
V
7*2- 8/(3+ 1)
V
13+ 1 7*2- 8/4
V
V
14
V
14-8/4

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

(e) 15- (2j3- 2*(3*(7- 5)- 5)) (f) (4j2+5)/(2j3- 5)+ 7

15- (2j3- 2*(3*2- 5))


V V
(16+5) /(2j3-5)+ 7
V
15- (2j3- 2*(6- 5))
V
21/(2j3- 5)+ 7

15- (2j3- 2*1)


V V
21 /(8-5)+7
V
15-(8-2*1)
V
21 /3+ 7

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?

(a) HI PRINT (d) HI PRINT


20 PRINT 5*3-4/2t1 2£1 PRINT 8-(2*(3+4)-6>+1
99 END 99 END

RUN RUN
14 1

(b) ifJ PRINT ( e) HI PRINT


2~ PRINT 6t3i2/(5-2)-4 20 PRINT 15-(2T3-2*(3*(7-5)-5»
99 END 99 END

RUN RUN

5 9

(c) 1~ PRINT (f) 1.~PRINT


2~ PRINT 7*2-(4i2-B)/(3+1) 2~ PRINT (4i2t5)/(2T3-5)t7
99 END 99 END

RUN RUN

12 14
38 PROGRAMMING IN BASIC

2.6 INTEGERS, FLOATING-POINT NUMBERS,


HIERARCHY OF OPERATIONS- Your Turn
1. Evaluate the following BASIC expressions. Do one calculation at a
time.
(a) 4j2- 9/3+ 1
(b) 2*5j2/(1 0- 8)+3
(c) 6*3- (8/2j2)/(6- 4)
(d) 16-(2*(9/3+1)-4)+2
(e) 7-(2*(3*(8/4-1)+2)-6)+5
(f) 9- (9/ 3+ 1)17*2-12)+3

2. Write six BASIC programs to evaluate the above expressions. RUN


the programs on your computer and compare the answers with
the ones you arrived at when the calculations were done by hand.
The answers for each expression should be the same.

2.6 INTEGERS, FLOATING-POINT NUMBERS,


HIERARCHY OF OPERATIONS-Solutions for
"Your Turn"
1. (a) 4j2-9/3+1 (c) 6*3-(8/2j2)/(6-4)
V V
16 - 9/3 + 1 6*3 - (8/4)/(6 - 4)
V V
16-3+1 6*3 - 2/(6 - 4)
V V
13 + 1 6*3 - 2/2
V V
14 18 - 2/ 2

18 -1
V
V
17

(b) 2*5j2/(10 - 8) + 3 (d) 16-(2*(9/3+1)-4)+2


f,/" V
2*5j2/2 +3 16-(2*(3+1)-4)+2
V V
2*25/2+3 16-(2*4-4)+2
V V
50/2 +3 16-(8-4)+2
V V
25+3 16-4+2
V V
28 12+2
V
14
INTRODUCING BASIC 39

(e) 7 - (2*(3*(8/4 -1) +2) - 6) +5 (f) 9 - (9/3 + 1 )/(7*2 -12) +3


V V
7 - (2*(3*(2 - 1) + 2) - 6) + 5 9 - (3 + 1 )/(7*2 -12) +3
V
7 - (2*(3*1 +2) - 6) +5
V
9-4/(7*2-12)+3
V
7 - (2*(3 +2) - 6) +5
V
9 - 4/(14 -12) +3
V ~
7 - (2*5 - 6) + 5 9 - 4/2 +3
V V
7-(10-6)+5 9-2+3
V V
7-4+5 7+3
V V
3+5 10
V
8

2. (a) 18 PRINT (d) 10 PRINT


20 PRINT 412-9/3+1 28 PRINT 16-(2*(9/3+1)-4)+2
99 END 99 END

RUN RUN

14 14

(b) 10 PRINT (e) 1£1 PRINT


28 PRINT 2*5T2/(10-8)+3 20 PRINT 7-(2*(3*(8/4-1)+2)-6)+5
99 END 99 END

RUN RUN
28 8

(c) HI PRINT (f) 18 PRINT


28 PRINT 6*3-(8/212)/(6-4) 28 PRINT 9-(9/3+1)/(7*2-12)+3
99 END 99 END

RUN RUN
17 10
40 PROGRAMMING IN BASIC

2.7 CONVERTING FROM ARITHMETIC INTO


BASIC AND VICE VERSA
When writing BASIC programs , it is often necessary to convert arith-
metic problems into BASIC expressions. You should also be able to do
the reverse.
1. Here are some arithmetic problems that have been changed to
BASIC expressions.

Arithmetic BASIC

(a) 2+3(6- 4) 2+3*(6-4) - Don't forget the asterisk!


3 2+3/(4+5)-7 - Note the parentheses.
(b) 2+ 4+5- 7
2+3
(c) 4+5-7 (2+3)/(4+5)-7 - Notice two sets of parenthe-
ses .
(d) 6+ (5- 2)2 6+ (5- 2)12/(3+4) - Be careful what you square-
3+4
just 5- 2.
(7-3)3+8 L 4
(e) 5+2 ((7- 3)13+812- 4)/(5+2) -This is a tough one. Notice
that all of the numerator must
have parentheses around it,
which results in two left paren-
theses in front of 7- 3.

2. These convert BASIC expressions into arithmetic problems.

BASIC Arithmetic

(a) 3+ 512- 4/6+ 7 4 - Note 4 divided by 6.


3+9--+ 7
6
(b) 3+512-4/(6+7) 3+9- - 4 - This time 4 is divided by 6+ 7.
6+7
3+9-4
(c) (3+512- 4)/(6+ 7) - Notice the numerator now - it
6+7
consists of several numbers
and operators.
(d) 8-(4+2)13+5/(9-2) 8- (4+ 2)3+_5_ - Watch the parentheses.
9-2
4 3 +(8-3)2
(e) (413+(8-3)i2) /(6-2)-7 - Another tough one. The
6- 2 7
numerator has parentheses
within it. Also, the denomina-
tor does not include the num-
ber 7.
INTRODUCING BASIC 41

2.7 CONVERTING FROM ARITHMETIC INTO


BASIC AND VICE VERSA- Your Turn
1. Convert the following arithmetic problems into BASIC expres-
sions.

(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

2. Convert the following BASIC expressions into arithmetic prob-


lems.

(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

2.7 CONVERTli\jG FROM ARITHMETIC INTO


BASIC AND VICE VERS/\-Solutions for "Your
Turn"
1. Arithmetic into BASIC

(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

2. BASIC into Arithmetic


3
(a) 2 _lQ
4 5
(b) (6 - 2)3 + ~ + 5 + 7
4 2
42 PROGRAMMING IN BASIC

(c) (5+4)3 + 4~3 - 6;4


(d) 7+(3+6)2 __9_
4 +3 7- 4
(e) (6-2)3+8 +8-2
4+3 5+1
2(3+(7-5)2 - 9) _
(f) 4 +5 7

2.8 PRINTING NUMBERS


Many computer systems print whole numbers without decimal points
even when the numbers are entered as decimal fractions with zeros.
Thus, 132 is printed 132 when entered as 132.00. A number that
includes a decimal point has all the leading and trailing zeros
dropped. For example, 01.20 appears as 1.2, with the leading zero
and the trailing zero left off. Remember, not all computer systems
print numbers as described above. See what your computer prints by
RUNning the following program.

10 PRINT
20 PRINT 132.00,01.20
99 END

What does your output look like?


Any number that contains more digits than the computer allows
(usually 6 to 15) is converted to scientific notation, sometimes
known as E format or E specification.

Mantissa Exponent

8.12345678 E +09

In the above example:


1. The letter E separates the mantissa from the exponent.
2. The exponent indicates the power of 10 to which the number is to
be raised. In this case, the decimal point is moved nine places to
the right, which results in the number 8,123,456,780. If the
exponent had been negative, the decimal point would be moved
9 places to the left. The resultant number would now be
.0000000081234.5678.
3. There is one digit to the left of the decimal point.
INTRODUCING BASIC 43

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

What does your output look like? Check the following :


1. How many digits are there to the right of the decimal point?
2. Is the last digit rounded off?
3. Are trailing zeros to the right of the decimal point dropped?
4. Does the exponent have a sign when it is positive?
5. How many digits are printed to express an exponent that is less
than 10?

2.8 PRINTING NUMBERS-Sample Problems


Suppose that your computer expresses a number in scientific nota-
tion as follows :
- Allows eight digits to the right of the decimal point.
- Rounds off the last permissible digit.
- Prints a two-digit , signed exponent.
- Drops all trailing zeros.
1. The problems shown below convert numbers from arithmetic
notation to scientific notation (E format)
(a) 7 123 456 885.
44 PROGRAMMING IN BASIC

The decimal point is moved from the last position in the


number to the position immediately after the 7, a total of 9
moves.

7.~ Scientific notation 7 .12345689E +09

t
9 moves Last permissible digit is rounded

The exponent must be +09 to indicate that the decimal is to


be moved 9 places to the right in order to convert the number
back to arith metic notation.

7 123 456 890.


~
9 moves

Notice that accuracy is lost; the result is 7 123 456890


instead of 7 123 456 885 .
(b) 14 000 000 000 000,
The decimal point is moved from the last position in the
number to the position immediately after the 1, a total of 13
moves.

1.~ Scientific notation 1.4E+ 13

13 moves

The exponent must be + 13 to indicate that the decimal is to


be moved 13 places to the right in order to convert the
number back to arithmetic notation.

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.

~876543218 Scientific notation: 9. 87654322E - 03


t
I
3 moves Last permissible digit is rounded
INTRODUCING BASIC 45

The exponent must be - 03 to indicate that the decimal is to


be moved 3 places to the left in order to convert the number
back to arithmetic notation .

.00987654322
-----
3 moves

Once more, accuracy is lost. The result is .00987654322


instead of .009876543218
(d) .00000000081234
The decimal point is moved from the first position in the
number to the position immediately after the 8, a total of 10
moves.

~.1234 Scientific notation: 8.1234E - 10

10 moves

The exponent must be -10 to indicate that the decimal is to


be moved 10 places to the left in orderto convert the number
back to arithmetic notation .

. 00000000081234
'--~

10 moves

2. These problems convert numbers from scientific notation to


arith metic notation .

Scientific Notation Arithmetic Notation


(a) 1 .23456789E+ 1 0 12 345 678 900
Two zeros must be added to 1.23456789 before moving the
decimal 10 places to the right.
(b) 5.8E+ 14 580000 000 000 000
Thirteen zeros must be added to 5 .8 before moving the
decimal 14 places to the right.
(c) 1 .23456789E- 04 .000123456789
Three zeros must be placed in front of 1.23456789 before
moving the decimal 4 places to the left.
(d) 7.65E- 07 .000000765
Six zeros must be placed in front of 7.65 before moving the
decimal 7 places to the left.
46 PROGRAMMING IN BASIC

2.8 PRINTING NUMBERS- Your Turn


1. Convert the following numbers from arithmetic notation to scien-
tific notation. In which questions is accuracy lost?
(a) 3 987 654 328
(b) 123987 654321
(c) 12300000000 000
(d) 12000000000000000
(e) .000002345678987
(f) .0000000123

2 . Convert the following numbers from scientific notation to arith-


metic notation.
(a) 4.1234567E+10
(b) 3 .12345E+12
(c) 7.5E+ 13
(d) 2.45678E- 02
(e) 9 .123E-06

2.8 PRINTING NUMBERS- Solutions for "Your


Turn"
1. Arithmetic notation to scientific notation
(a) 3 .98765433E+09 Accuracy is lost. Arithmetic notation is
3 987 654 330 instead of 3 987 654 328.
(b) 1.23987654E+ 11 Accuracy is lost. Arithmetic notation is
123 987 654 000 instead of 123 987 654321 .
(c) 1.23E+13
(d) 1.2E+16
(e) 2.34567899E- 06 Accuracy is lost. Arithmetic notation is
.00000234567899 instead of .000002345678987.
(f) 1.23E- 08

2. Scientific notation to arithmetic notation

(a) 41 234 567 000


(b) 3 123 450000000
(c) 75 000000000000
(d) .0245678
(e) .000009123

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

execute a program . Many of these are machine dependent, so it may


be necessary for you to refer to your computer manual for the
required variations. Flowcharting and a few flowchart symbols were
also introduced . As concepts are developed in this book, techniques
and other symbols used in flowcharting will be explained . Several
rules must be observed in the writing of BASIC programs. They will
become more familiar to you as you write your own programs in
successive chapters .
The computer evaluates a BASIC expression in a specific order
known as the hierarchy of operations . The order of execution is as
follows .
1. Parentheses
2. Exponentiation
3. Multiplication and division, whichever appears first
4. Addition and subtraction, whichever appears first
Quite often the writing of BASIC programs involves the conversion
of arithmetic problems into BASIC expressions . For example,
(4~5)2 + 7 in arithmetic becomes (4+5)i2/6+ 7 in BASIC. You should
also be able to do the reverse. Numbers that contain more digits than
the computer allows are converted to scientific notation. Results vary
depending on the computer being used.
Information is displayed or printed by means of a number of PRINT
statements.
1. A PRINT statement with no list leaves a blank line .
2. A PRINT statement with commas prints items widely spaced
across a line.
3 . A PRINT statement with semicolons prints items closely spaced
on a line.
4 . A PRINT statement with messages (strings) must have the strings
enclosed in quotation marks.

Questions and Exercises 9


1. State the system commands required by your computer to:
(a) Clear the computer's memory.
(b) Transmit a typed statement or command to the computer's
memory.
(c) Display a program on the screen .
(d) Execute a program.
(e) Clear the screen.
(f) Terminate a program .
2. On your computer system , what operations are required to:
(a) Correct a character in a line before the IRETURNI key is
pressed?
(b) Correct a character in a line after the IRETURNI key is
pressed?
(c) Delete a line?
(d) Insert a line?

9 . If you are not using an interactive system, you may ignore Prob lems 1 and 2.
48 PROGRAMMING IN BASI C

3. (a) A BASIC program consists of a number of _ _ _ _ _ __


(b) What maximum number of characters does your computer
allow in one statement?
(c) In what order are BASIC statements executed? Give one
exception.
(d) State three reasons why REMARK statements are used .
4. What is the difference between an executable statement and a
non-executable statement? Give an example of each .
5. Draw a flowchart for the following program. The program multi-
plies one number by another, then prints the product. Notice the
extra PRINT statement that leaves a blank line. Opposite each
symbol , write the appropriate statement(s) .

01 REM N1--FIRST NUMBER


02 REM N2--SECOND NUMBER
03 REM P--PRODUCT

10 READ N1,N2
20 DATA 3,9
30 LET P=Nl*N2
40 PRINT
5~ PRINT P
99 END

6 . What is the difference between an integer and a floating-point


number?
7 . List the five arithmetic operations used in BASIC and give their
BASIC symbols .
8 . List the hierarchy of operations, including parentheses within
parentheses . Should two operators of equal priority appear in
one statement, explain the order of execution.
9. Evaluate the following BASIC expressions. Do one calculation at a
time.
(a) 3+16/2i3+6/3
(b) 8-12/4 *(21 2+ 1)/5
(c). (3i2+5)/(2i3-1)+6
(d) 3+ 4/2+ (8- (4+2))12
(e) 6+4*3*(9/(6- 3)- 2)- 7
(f) 30- (2*(8/4+3*(7 - 5)+5))
10. Show the RUNS for the following programs.

(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

(c) 121 PRINT


20 PRINT 10,200,3000,4ee00
:~0 PRINT -10,-200,-3000,-40000
4fJ PRINT 10;200;3000;40000
521 PRINT -10;-200;-3000;-40000
99 END

(d) 10 PRINT
20 PRINT "MY",
3~ PRINT "PROGRAM"
99 END

(e) 10 PRINT
20 PRINT "MY";
321 PRINT "PROGRAM"
99 END

(f) 121 PRINT


20 PRINT "MY ";
321 PRINT "PROGRAM"
99 ENII

(g) 10 PRINT
221 PRINT " MY " ;
321 PRINT
421 PRINT "PROGRAM"
99 END
50 PROGRAMMING IN BASIC

11. Convert the following arithmetic problems into BASIC expres-


sions.

(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

12. Convert the following BASIC expressions into arithmetic prob-


lems.
(a) 3+2/(8- 6)+(5- 2)/7
(b) (3+1)12-(4+1)/(6-2)
(c) ((5-1)13+9)/(7+6)
(d) 2*(3+(5-1 )j2)- 4/(7- 3)
(e) (6+4)13/(4- (3*(7+2)- 9))
(f) (7- (5*(3j2- 2)+8))/(4+5)

13. Convert the following numbers from arithmetic notation to scien-


tific notation. In which questions is accuracy lost?
(a) 1 234 567 869
(b) 12 345 678 900
(c) 15 000 000 000 000 000
(d) 9876543211 000
(e) .0001234567847
(f) .0000002345
14. Convert the following numbers from scientific notation to arith-
metic notation.
(a) 6.123456E+ 10
(b) 3.12345678E+ 13
(c) 6.1E+15
(d) 5.4321 E- 05
(e) 5.4E- 08

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

3. 25- (3+ 2)2 + 8~2 6


RUN
8
4. 4(2(6- 2)- 3)+5
RUN

5. 5(12-(3(9-7)2-6)+4)
RUN
50
6. 3~02 + 4(6- 3)2
RUN
4()

For the following problems, it is assumed that your computer


differentiates between a comma and a semicolon. In each output,
leave one blank line after the word RUN.

7. Write a BASIC program that prints HOW ARE YOU DOING?


spread widely across the page or screen.

8. Rewrite the above program so that your RUN produces


HOWAREYOUDOING? Use four strings in your PRINT state-
ment.

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 .

12. Write a BASIC program to evaluate 6-12. As in Problem 11, use


two PRINT statements - one to print a string and the answer
widely spaced apart, and the other to print them closer together.
Change the string to THE ANSWER IS:.

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

Your RUN should be as follows .

RUN

LAST
PROGRAH
ENTERING DATA INTO THE COMPUTER 53

THREE ENTERING DATA


INTO THE COMPUTER
A. After completing this chapter, you should be able to write BASIC
programs and complete skeletal BASIC programs that
1. Enter data into the computer using LET statements.
2. Enter data into the computer using INPUT statements.
3. Enter data into the computer using READ/DATA statements .
4. Retain values of variables for use in subsequent statements .
5. Transfer (copy) values from specific storage locations and
place them into other storage locations .
6. Use prompts to identify values entered into the computer by
means of INPUT statements.
7. Use one or several READ statements in conjunction with one
or several DATA statements .
8. Reassign values in DATA statements by means of RESTORE
statements.

B. In addition, you should be able to


1. Define a variable and give examples.
2. Display and label a LET statement.
3. Explain how a LET statement is executed .
4. Explain how a statement such as A=A+1 is entirely logical in
BASIC.
5. Define initialization.
6. Summarize the response made to an INPUT statement.
7. State the purpose of
(a) the READ statement.
(b) the DATA statement.
8. Correct invalid program segments that use
(a) LET statements .
(b) INPUT statements .
(c) READIDATA statements.
(d) RESTORE statements .
9. Explain how a RESTORE statement is executed.
10. Produce the RUNS of programs .

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 numeric variable may consist of one or several characters ,


depending on the computer system; however, the first character
must always be alphabetic. The remaining characters may be letters
or numbers . The following rules may have to be observed, depending
upon the version of BASIC being used.
(a) Only two letters may be allowed in a numeric variable; the rest
would be ignored . This means that variables AA, AAB, and
AACD are all the same , since the B of AAB and the CD of AACD
are dropped .
(b) It may be necessary for the second character of the variable to be
a digit. Thus , A1 would be valid while AA would not be valid .
After you have learned about the LET statement in the next section ,
try the different symbols for variables and see which ones work on
your computer system . Here are some examples of numeric vari-
ables. A is used as the first character; however, any letter of the
alphabet may be used .

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.)

3.2 THE LET STATEMENT


The LET statement is one of three methods by which data may be
entered into the computer. The general form is as follows .
1. 10 LET A 24

stat:ment
number
i
Key word
i
Variable
i
Equals sign
i
Number
2. 30 LET A A+1
t
Expression

The LET statement is composed of a statement number, the word


LET , a variable, and an equals sign followed by a number or an
expression. In example one , the number 24 to the right of the equals
sign is aSSigned to the variable A on the left . This means that 24 is
stored in address A. Notice that the item on the left-hand side of the
equals sign must be a simple numeric variable, not an expression .
The assignment A=A+1 in example two is particularly worthy of
comment. It seems to resemble an algebraic equation, yet mathemat-
ically it doesn't make sense . However, in BASIC it is entirely logical.
The equals sign does not denote the usual algebraic operation but
rather assigns the result of A+ 1 to the variable on the left-hand side
of the equals sign. (The computer adds one to the value of A then
assigns this new value back to A.) The former value stored in address
A is lost.
ENTERIN G DATA INTO THE CO MPUTER 55

There is one more term you should know. When a variable is


assigned a value for the first time (before it is used in an expression),
we say that the variable has been initialized . Although variables can
be initialized by the other statements covered in this chapter, the LET
statement is most often used to perform this function . Here are two
examples .

UI LET A= 1 -Initializes A to 1.
20 LET 5=0 -Initializes S to 0.

These two statements should be executed only once. The intention


is to initialize the variables prior to using them in subsequent state-
ments . If a variable is not initialized, the following may occur :
1. The computer may give an error message .
2. The computer may give the non-initialized variable a value of
zero.
3. The value of the non-initialized variable may continue to be the
value that was assigned to it in a previous program if the program
is not cleared from memory.
Variables may be initialized in any order. If there are two variables to
initialize, say A to 1 and 5 to 0, A may be initialized first and then 5, or
vice versa .

10 LET A=l or 10 LET 5=0


20 LET 5=0 2£1 LET A=l

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 .

10 LET A=24 -Initializes A to 24.


20 LET B=A+1 -Increments the value of A by 1, then assigns the new value to B.
30 PRINT - Leaves a blank line after the word RUN .
4iJ PRINT A,I~ - Prints the values of A and B .
99 END - Terminates program execution .

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.

1£11 LET A=4 -Initializes A to 4.


20 PRINT - Leaves a blank line after the word RUN.
3'" PRINT "A =. ; A - Prints the variable and its value.
40 LET 8=A - Copies the value that is stored in A and places it in B .
5~ PRINT "B ::. ; B - Prints the variable and its value.
99 END - Terminates program execution.

RUN

A =4
B =4

The number 4 is now stored in address A and in address B. Also, lines


30 and 50 each prints a variable as well as its value. The statement
30 PRINT "A =";A asks the computer to print two separate parts:

(a) •A =. - The computer prints A = (Remember strings in Chapter Two?)

(b) ;A - The computer prints 4 (The current value of A.)

- The semicolon stops automatic li ne spacing so that


the 4 is printed on the same line as the A = .
The final result is
A = 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

Instead of assigning the result of an expression to a variable, and


then printing the value of the variable , an expression may be placed
directly in a PRINT statement. The following programs each produce
the same result.

(a) Expression Assigned (b) Expression Placed in


to a Variable a PRINT Statement

HI LET A=2 1e LET A=2


2e LET B=At2 20 PRINT
"30 PRINT 3e PRINT "B =" ;At2
40 PRINT "B =";B 99 END
99 END
RUN
RUN
B = 4
B = 4

In some versions of BASIC, you may use one LET statement to


assign the same value to several variables. For example

10 LET A=B=C=D=1

assigns 1 to each of the variables A,B,C, and D . This is known as a


multiple-assignment statement. It should also be mentioned that the
key word LET may be omitted on many computer systems . That is,
10 LET A= 1 gives the same result as 10 A=1 . Throughout this book,
the word LET is retained.
Just one or two hints before you go through a sample program . It's
a good idea to assign as many data items as possible to variables
before any calculations are made. In this way, all data is stored and
ready for use. The second hint is this: Try to use variables that
represent the types of data assigned to them. For example, the
variable 0 could mean deposit while the variable W would stand for
withdrawal.

3.2 THE LET STATEMENT -Sample Programs


1. This program prints the whole numbers 1,2 ,3 using only one
variable.

Ie LET A=I -Initializes A to 1.


2e PRINT - Leaves a blank line after the word RUN.
3e PRINT A - Pri nts the cu rrent value of A (1) before making any chang es to
its vaiue .
58 PROGRAMMING IN BAS IC

40 LET A=A+l -Increments the value of A by 1.


50 PRINT A - Prints the current value of A (2) before making any changes to
its value.
60 LET A=A+l -Increments the value of A by 1.
'.70 PRINT A - Prints the current value of A (3).
99 END - Terminates program execution .

RUN
1.
,,-
~)

First A =1 A

Then A = A+ 1 A
= 1+ 1
=2

Finally A = A+ 1 A
=2+1
=3

Notice that the address A contains only one number at a time .


The previous number in A is replaced by the latest one stored .
This is important to know, because if you wish to have the old
value printed , you must do th is before making any changes to the
value of the variable .
2. The previous program can be written more efficiently by using
more than one variable . In this way , you don 't have to worry about
losing values before they are printed .

HI LET A=l -Initializes A to 1.


20 LET B=A+l -Increments the value of A by 1, then stores the result in B .
:50 LET C=A+2 -Increments the value of A by 2, then stores the result in C.
40 PRINT - Leaves a blank line after the word RUN.
50 PRINT A - Prints the current value of A .
60 PRINT B - Prints the current value of B.
70 PRINT C - Prints the current value of C .
99 END - Terminates program execution .
ENTERING DATA INTO THE CO MPUTER 59

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

In this program , no value is destroyed since each value is


assigned to a different variable (1 is assigned to A; 2 is assigned
to S ; and 3 is assigned to C). The contents of variables A,S, and
C may be printed any time after each variable has been assigned
a value .

3.2 THE LET STATEMENT-Your Turn


1. Identify the errors , if any , in the LET statements shown below .

(a) 10 LET A=l AND 2 (d) 10 LET A=A+2


(b) 10 LET A-9=B (e) 10 LET 5=A
(c) 10 LET A=16 (f) 1 0 LET 1 A= 1

2. If the values of A, S , and C are initially 1,2, and 3 respectively for


each of the following program segments, what will be their values
after execution of each statement? In which program segments
do the values of A and S interchange? The first one has been
done for you .

(a) 40 LET C=A 40 LET C=A


50 LET A=B C=1
60 LET B=C 50 LET A=B
A=2
60 LET B=C
B=1
60 PROGRAMMING IN BASIC

The values of A and B are interchanged in this program segment,


since A is now equal to 2 and B is now equal to 1.

(b) 40 LET A=C (d) 40 LET A=B


50 LET B=A 50 LET C=A
60 LET C=B 60 LET B=C

(c) 40 LET C=B


50 LET B=A
60 LET A=C

3. What is the output of each of the following programs?

(a) 10 LET A=3 (c) 10 LET A=6


20 LET A=AT2 20 LET B=A
30 PRINT 30 LET C=Bt2
40 PRINT A 40 LET A=C
99 END 50 PRINT
60 PRINT A,C
99 END

(b) 10 LET A=3 (d) 10 LET A=2


20 PRINT 2£1 LET B=AT2
30 PRINT A 3£1 LET A=Bt2
40 LET A=AT2 40 LET B=Ai2
50 PRINT A 50 PRINT
99 END 6£1 PRINT A,B
99 ENII

4 . In each of the following programs, what initial value should A


have in order to produce the RUN shown?

(a) 10 LET A= ------ (b) UI LET A= ------


20 LET B=A 2£1 LET B=At2
30 PRINT 30 PRINT
40 PRINT "B =" j B 40 PRINT "B ="jB
99 END 99 END

RUN RUN

B = 12 B = 6
ENTERING DATA INTO THE COMPUTER 61

(c) 10 LET A= ------ (d) 10 LET A= -------


20 LET B=AT2 20 LET B=A-4
30 LET C=B 30 LET C=Bt2
40 PRINT 40 PRINT
50 PRINT 'C =' ; C 50 PRINT IC =I ; C
99 ENIt 99 END

RUN RUN

C = 9 C = 10

5. Write a program that prints the numbers 2, 4, 6, 8. Use only one


variable.

RUN

2
4
6
8

6. Rewrite the above program so that you incorporate the following


changes .

(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

7. Suppose you had $400 in your bank account. What amount


would you have if you deposited $600 at the beginning of this
month? How much would you have left in your account if you
withdrew $250 one week later?
(a) Use LET statements to enter the data.
(b) Current Balance = 400.
(c) Don 't forget to print the Current Balance before making any
changes to its value.
62 PROGRAMMING IN BASIC

(d) Current Balance = Current Balance + Deposit


(e) Again , have the computer print the Current Balance before
changing its value .
(f) Current Balance = Current Balance - Withdrawal
(g) A flowchart is drawn to help you follow the flow of logic .
Notice that when several consecutive statements perform
the same type of operation, all descriptive material is placed
in one symbol with the items listed on separate lines .

ITI 40 PRINT A
50 PRINT B

If several items are coded in one statement, they will be


listed on one line within the symbol.

I I Print
A,B

Also note that REM statements and messages in PRINT state-


ments are not displayed in a flowchart.

RUN

CURRENT BALANCE: 400


DEPOSIT: 600
CURRENT BALANCE: 10B0
WITHDRAW,AL: 250
CURRENT BALANCE: 750
ENTERING DATA INTO THE COMPUTER 63

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

3.2 THE LET STATEMENT-Solutions for "Your


Turn"
1. (a) Only one value may be assigned to A.

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.

121 LET B=A-9

(c) Nothing is wrong .


(d) Nothing is wrong .
(e) The item on the left-hand side of the equals sign must be a
numeric variable, not a number.

HI LET A=5

(f) The first character of the numeric variable 1A must be alpha-


betic .

HI LET Al=l

2.

(b) 40 LET A=C (d) 421 LET A=B


A=3 A=2
S2I LET B=A S2I LET C=A
8=3 C=2
621 LET C=B 621 LET B=C
C=3 8=2
(c) 421 LET C::B
C=2
521 LET B=A
8= 1
60 LET A=C
A=2
ENTERING DATA INTO THE COMPUTER 65

The values of A and B are interchanged in program segment (c).


3.

(a) RUN (c) RUN

9 8 8

(b) RUN (d) RUN

3 6 36
9

4.

(a) 10 LET A=12 (c) Ii!! LET A=3

(b) 10 LET A=4 (d) Ii!! LET A=12

5.

121 LET A=2


28 PRINT
30 PRINT A
4i!! LET A=A+2
50 PRINT A
60 LET A=A+2
7i!! PRINT A
80 LET A=A+2
90 PRINT A
99 END

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.

01 REM C--CURRENT BALANCE


1212 REM D--DEPOSIT
03 REM W--WITHDRAWAL
10 LET C=400
2£1 LET D=6ee
30 LET W=25e
40 PRINT
5121 PRINT "CURRENT BALANCE:";C
60 PRINT "DEPOSIT:";D
70 LET C=C+D
S0 PRINT "CURRENT BALANCE:";C
90 PRINT "WITHDRAWAL:";W
100 LET C=C-W
11121 PRINT "CURRENT BALANCE:";C
999 END

3,3 THE INPUT STATEMENT1


The INPUT statement is another way by which data may be entered
into a computer. Consider the following program using the LET state-
ment.

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

1. This method of entering data is used in an interactive or in a time-sharing


environment. If you are not using this type of system (teletype, cathode ray tube, or
microcomputer), you may wish to ignore this section.
ENTERING DATA INTO THE COMPUTER 67

assigned to A? Surely there must be some other method by which


data can be entered into the computer without having to modify the
LET statement after each RUN. There is! You can reduce the amount of
work by the use of an INPUT statement. Here is an example.

10 PFU NT
2111 INPUT A
30 PRINT A
99 END

RUN
'i'

When the computer encounters the INPUT statement during execu-


tion of the program, it displays a question mark and then waits for the
programmer to enter a value. The user types the number 2 immedi-
ately after the question mark, then presses the RETURN key.

RUN

? 2 - The user types the number 2 then presses RETURN.

The value 2 is stored in address A and displayed on the screen.

RUN

? 2

To change the contents of A from 2 to 31, the user RUNS the


program a second time. Again the computer displays a question mark
and waits for a data item to be keyed in. The user types the number 31
after the question mark and presses the RETURN key. The result is
shown below.

RUN

? 31
31

The above process is repeated for the number 49.


68 PRO G RAMMING IN BASIC

Take another look at the program .

10 PR I NT - Placed before the INPUT statement.


20 INPUT A
30 PRINT A
99 ENtl
FUlN
~(------ Blank line
"~ 2
2

Notice that a PRINT statement is placed before the INPUT statement.


This leaves a blank line after the word RUN , that is , before the display
of the keyed-in value . In the other two methods of entering data, a
PRINT statement is placed (in most programs) just before the PRINT
that prints the results. For example, when the LET statement is used to
enter data, the PRINT statement is placed as follows .

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 .

1. The first method uses two INPUT statements .

H'l PRINT - Leaves a blank line after the word RUN.


20 INPUT A - Requests data, user enters the value for A .
3~ INPUT B - Requests data, user enters the va'l ue for B.
40 LET C=A-B - e
Subtracts the va'lue of from the value of A
and stores the result in C.
50 PRINT "A =" ;A, "B =" ;B, "C =";C - Prints the values of A, e, and C .
99 END - Terminates program execution .
ENTERIN G DATA INTO THE CO MPUTER 69

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 .

UI PRINT - Leaves a blank line after the word RUN .


20 PRINT "VALUE FOR A" ; -Identifies the value to enter (a prompt).
3£1 INPUT A - Requests data, user enters the value for A .
40 PRINT "VALUE FOR B" ; -Identifies the value to enter (a prompt).
50 INPUT B - Requests data, user enters the value for B.
60 LET C=A-B - Subtracts the value ofB from the value of A
and stores the result in C.
l~ PRINT "A =" ;A,"B =" ;B,"C = I ; C - Prints the values of A, B, and C.
99 END - Terminates program execution .

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

28 PRINT "VALUE FOR A";


38 INPUT A
70 PR OG RAM M ING IN BAS IC

are replaced by the one statement

20 INPUT "VALUE FOR A";A

2. The second method by which two values may be entered uses


just one INPUT statemen t.

HI PRINT - Leaves a blank line after the word RUN .


20 INPUT A,B - Requests data, user enters the values for A and B .
:~0 LET C=A-B - Subtracts the value of B from the value of A and stores the result in C .

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.

10 PRINT - Leaves a blan k line after the word RUN .


20 PRINT "VALUES FOR A,B"; -Identifies the value to enter (a prompt).
30 INPUT A,B - Requests data, user enters the value for A
andB .
40 LET C=A-B - Subtracts the value of B from the value of A
and stores the result in C .
50 PRINT "A =";A,"B =";B,"C =";C - Prints the values of A, B, and C .
99 ENII - Terminates program execution .

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

2. On some systems , each val ue is keyed in on a separate line. The computer


displays a question mark on a new lin e every time a va lu e is entered (except after th e
last va lu e) .
ENTERING DATA INTO THE COMPUTER 71

below the prompt. Since a data item is always displayed when it is


typed in response to an INPUT statement, there is no need to have a
special PRINT statement to print the data item again. From now on,
most of the programs using the INPUT statement will have their data
displayed only once, and this will be directly after the question mark.
Eliminating this duplication, the program and its RUN now look like
this:

10 PRINT - Leaves a blank line after the word RUN.


20 PRINT "VALUES FOR A,B"; -Identifies the values to enter (a prompt).
30 INPUT A,B - Requests data, user enters the values for A and B.
40 LET C=A--B - Subtracts the value of B from the value of A and
stores the result in C.
50 PRINT "C =";C - Prints only the value of C, since the values of A and
B are already displayed.
99 END - Terminates program execution.

RUN

VALUES FOR A,B? 12,4 - Data displayed only once.


C = 8

When assigning values to multiple variables in one INPUT state-


ment, several rules must be observed.
1. The variables listed in the INPUT statement must be separated by
commas, with no comma before the list and no comma at the end
of the list.

No commas here

2B INPUT A,B,C
~
'V
Commas here

2. The values keyed in must be separated by commas with no


comma before the list and no comma at the end of the list.

No commas here
/~
VALUES FOR A,B.C? 2.4.6
V
Commas here

3. There must be a one-to-one correspondence between the


values keyed in and the variables listed in the INPUT statement.
72 PROGRAMMING IN BASI C

20 PRINT ·VALUES FOR A,B,C";


30 INPUT A,B,C
- Same number of values as variables (3) .
- Same order.
99 END - Same type . (In this case, all are numeric values, not strings.)

RUN

IJALUES

4. When insufficient data is supplied, your computer may perform


one of the following:
(a) It may print a message asking for more data (often in the form
of one or two question marks on the next line) ;
(b) It may simply wait for more data ;
(c) It may terminate execution .
Suppose you inadvertently forge t to enter the value for C when
you RU N the following program. It is assumed that when insuffi-
cien t data is entered , your computer types two question marks
on the lin e immediately below the one where the values for A and
B are keyed in .

10 PRINT
20 PRINT "VALUES FOR A,B,C";
30 INPUT A,B,C
40 PRINT A,B,C
99 ENII

RUN

VALUES FOR A,B,C7 2,4 -ForgottokeyinthevalueforC .


?'!' - Computer displays two question marks on the next line .

The value for C should now be typed right after the last question
mark .

RUN

VALUES FOR A,B,C7 2,4


77 6 ~ Value for Centered .

After you press the RETURN key, program execution resumes .


ENTERING DATA INTO THE COMPUTER 73

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

VALUES FOR A,B,C? 1,2,3,4 -Userenterstoo


?EXTRA IGNORED much data .
1 2 3

3,3 THE INPUT STATEMENT-Sample


Programs
1. Suppose you purchased the following items.

Quantity Item Unit Price


2 Coat $132
3 Jacket 58
This program finds the cost of the two coats, the cost of the three
jackets, and the total cost of all the items.
(a) Use two INPUT statements to enter the quantity and the unit
price of each item.
(b) Cost of Coats = Quantity x Unit Price
(c) Cost of Jackets = Quantity x Unit Price
(d) Total Cost = Cost of Coats + Cost of Jackets

1211 REM Q1--QUANTITY (COATS)


1212 REM U1--UNIT PRICE OF COATS
1213 REM Q2--QUANTITY (JACKETS)
1214 REM U2--UNIT PRICE OF JACKETS
I2IS REM C--COST OF COATS
1216 REM J--COST OF JACKETS
1217 REM T--TOTAL COST

10 PR I NT - Leaves a blank line after the word RUN .


2121 f'RINT "COATS--QTY,UNIT PRICE"; -Identifiesthequantityandtheunitprice
of the coats (Q1 and U1) - a prompt.
74 PRO GRAMMING IN BASIC

38 INPUT 01,U1 - Requests data, user enters the values


for 01 and U1 .
48 PRINT aJACKETS--OTY,UNIT PRICE a ; -Identifies the quantity and the unit price
of the jackets (02 and U2) - a prompt.
58 INPUT 02,U2 - Requests data, user enters the values
for 02 and U2.
68 LET C=Ol*U1 - Finds the cost of the coats and stores
the result in C.
78 LET J=02*U2 - Finds the cost of the jackets and stores
the result in J .
B8 LET T=CtJ - Finds the total cost of all the items
and stores the result in T .
98 PRINT aCOATs:a;C - Prints the cost of the coats .
100 PRINT aJACKETS:a;J - Prints the cost of the jackets.
110 PRINT "TOTAL COST:a;T - Prints the total cost of all the items.
999 END - Terminates program execution.

RUN
COATS--OTY,UNIT PRICE? 2,132
JACKETS--OTY,UNIT PRICE? 3,58
COATS: 264
.JACKETS: 174
TOTAL COST: 438

2. The program shown in Part 1 is now rewritten , this time using


only one IN PUT statement to enter the values.

81 REM 01--QUANTITY (COATS)


02 REM U1--UNIT PRICE OF COATS
03 REM 02--0UANTITY (JACKETS)
04 REM U2--UNIT PRICE OF JACKETS
05 REM C--COST OF COATS
06 REM J--COST OF JACKETS
07 REM T--TOTAL COST
18 PR I NT - Leaves a blank line after the word
RUN.
28 PRINT ·OTY,UNIT PRICE--COAT,JACKET a ; -Identifies the quantities and unit
prices of the coats and jackets
(01 ,U1 ,02,U2) - a prompt.
30 INPUT 01, U1,02, U2 - Requests data, user enters the
values for 01 ,U1 ,02,U2.
48 LET C=Ol*U1 -Findsthecostofthecoatsand
stores the result in C .
58 LET J=02*U2 - Finds the cost of the jackets and
stores the result in J.
ENTERING DATA INTO THE COMPUTER 75

60 LET T=CtJ - Finds the total cost of all the items


and stores the resu It in T .
70 PRINT "COATS:";C - Prints the cost of the coats.
80 PRINT "JACKETS:";J - Prints the cost of the jackets.
90 PRINT "TOTAL COST:";T - Prints the total cost of all the items .
99 END - Terminates program execution .

RUN
OTY,UNIT PRICE--COAT,JACKET? 2,132,3,58
COATS: 264
JACKETS: 174
TOTAL COST: 438

3.3 THE INPUT STATEMENT - Your Turn


I. 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 one INPUT statement to enter the total amount you have
set aside and the number of days that you will be buying
lunch.
Total Amount
(b) Average Amount Each Day = Number of Days
(c) Fill in the missing lines.

01 REM T--TOTAL AMOUNT


02 REH [I--DAYS
03 REM A--AVERAGE AMOUNT EACH DAY
10 PRINT
20 PRINT "TOTAL AMOUNT,DAYS";
30
40
50
99 END

RUN
TOTAL AMOUNT,DAYS? 12.50,5
AVERAGE AMOUNT EACH DAY: 2.5

1. Which statement should be coded in line 30?

(a) LE T T:: 12.5


(b) LET T=12.5,5
76 PROGRAMMING IN BASI C

(c) INPUT T
(d) INPlJl lid
(e) INPUT T,D

2. Which statement should be coded in line 40?

(a) LET T=[l/A


(b) LET T=A/D
(c) L.ET A=D/T
(d) L.El I~=T/[I
(e) LE:.T [I=T/A

3 . Complete line 50 with a PRINT statement.


II. An employee in a furniture factory is paid according to the
number of pieces produced. Write a program that finds the total
number of pieces produced in 8 hours if the output was 6 pieces
per hour .
(a) Use two INPUT statements to enter the number of hours and
the number of pieces per hour .
(b) Total Pieces = Number of Hours x Number of Pieces per
Hour

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

HOURS,PIECES PER HOUR? 8,6


TOTAL PIECES: 48
ENTERING DATA INTO TH E COMPUTER 77

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

3.3 THE INPUT STATEMENT-Solutions for


"Your Turn"
I.

1. (e) 30 INPUT T,D


2. (d) 421 LET A=T ID
3.50 PRINT "AVERAGE AMOUNT EACH DAv:a;A

II.

211 REM H--HOURS


212 REM P- - PIECES PER HOUR
03 REM T--TOTAL PIECES
10 PRINT
20 PRINT "HOURS";
30 INPUT H
40 PRINT "PIECES PER HOUR" ;
521 INPUT P
60 LET T=H*P
721 PRINT "TOTAL PIECES:";T
99 END

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

The off-page connector is used in the flowchart of this program . The


symbol on the previous page indicates that the flowchart is continued
on page 79 . The symbol on this page indicates that the flowchart is
continued from page 78 .

3.4 THE REAOIDATA STATEMENTS


The READ statement combined with the DATA statement is the third
method by which data may be entered into the computer .

10 READ A,B,C
20 [lATA 24,25,26

A READ statement is always associated with a DATA statement. The


READ statement directs the computer to locate the DATA statement
and to assign (in sequential order) the values listed in the DATA
statement to the variables that are coded in the READ statement.
Perhaps the best approach in explaining this method of entering data
into the computer is to list a few rules . As each rule is mentioned, it will
be accompanied by a program or a program segment to try and make
it as easy as possible for you to understand what the rule is all about.
80 PROGRAMMING IN BASIC

1. A READ statement must have at least one accompanying DATA


statement

10 REALI A,B,C
2B DATA 24,25,26
30 PRINT
40 PRINT A,B,C
99 END

The DATA statement supplies the READ statement with values.


The first number in the DATA statement (24) is assigned to the
first variable in the READ statement (A), The second number in
the DATA statement (25) is assigned to the second variable in the
RE AD statement (8) . Finally, the third number (26) is assigned to
the third variable (C). Should there be more numbers and more
variables , the computer assigns values until it runs out of
numbers and variables.

2. The variables listed in the READ statement must be separated by


commas with no comma before the list and no comma after the
list

No commas here
/'
10 READ A,B,C
'\
V
Commas here

3 . The values listed in the DATA statement must be separated by


commas with no comma before the list and no comma after the
list

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.

20 DATA 85,13.24,96, •••••••••••• ,64,123 ~ Numbercompletedinthenextline.


45.67,149,2.37, ••••••••••••••••••• ,352 - No comma after tlh e last item when
the line is followed by a statement.
30 DATA 425,14.98,510
ENTERING DATA INTO THE COMPUTER 81

Notice that the number 12345.67, which is incomplete in the first


line of the first DATA statement, is completed in the second line
starting in the first position of the line. The second line must not
end with a comma, since this line is followed by a statement (in
this case , by another DATA statement).

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

Here are two more examples.

(a) Hl [lATA 24,25,26 (b) 10 READ A,B,C


20 READ A,B,C 20 PRINT
30 PRINT 30 PRINT A,B,C
40 PRINT A,B,C 40 DATA 24,25,26
99 END 99 END

In example (a), the computer ignores the DATA statement in


line 10 until it finds the READ statement in line 20 . It then assigns
values from the "skipped" DATA statement and resumes execu-
tion, starting at line 30. In example (b), the computer ignores the
two PRINT statements in its search for a DATA statement, assigns
values, and then returns to line 20. As shown in the above
programs, the READ statement may have a line number that is
either higher or lower than that of the DATA statement.

5. The DATA statement must have at least the same number of


values as the READ statement has variables, and there must be a
one-to-one correspondence between the values and the vari-
ables. Excess data is ignored , while insufficient data causes an
error message.

UI READ A,B,C - Same number of values as variables (3).

3~
1\'
DATA 2 Ah25,26
- Same order .
- Same type . (In this case, all are numeric values, not strings .)
82 PROGRAMMING IN BASIC

(a) Excess Data

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 .

(b) Insufficient Data

10 READ A,B,C
28 DATA 24,25 -Insufficient data.
30 PRINT
40 PRINT A,B,C
99 END

RUN

?OUT OF DATA ERROR IN lS -Error message,


or something similar.

6. A program may have several DATA statements for one READ


statement.

10 READ A,B,C
20 DATA 24,25
3£'l DATA 26
40 PRINT
58 PRINT A,B,C
99 END

The computer reads items starting at the lowest-numbered DATA


statement and continues reading from sequentially higher-
numbered DATA statements until the READ statement is satisfied.
7. A program may have several READ statements accompanied by
only one DATA statement.

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

In this program, line 10 assigns 24 to A and 25 to B. When the


computer encounters line 20, it remembers that 24 and 25 have
already been assigned , so it continues to the third value and
assigns 26 to C.

8. Variables, expressions , and numbers with com mas (for example ,


the number 1,000) are invalid data items .

20 DATA X,D/2,1,000
'Invalid
V

3.4 THE READIDATA STATEMENTS-Sample


Program
The sample program in Section 3.3 is rewritten and shown below
using the READIDATA statements to enter the data instead of the INPUT
statement. Here is the problem once more.
Suppose you purchased the following items.

Quantity Item Unit Price


2 Coat $132
3 Jacket 58
This program finds the cost of the two coats, the cost of the three
jackets, and the total cost of all the items.
(a) Use the READ/DATA statements to enter the quantity and the
unit price of each item.
(b) Cost of Coats = Quantity x Unit Price
(c) Cost of Jackets = Quantity x Unit Price
(d) Total Cost = Cost of Coats + Cost of Jackets

01 REM Q1--QUANTITY (COATS)


02 REM U1--UNIT PRICE OF COATS
03 REM Q2--QUANTITY (JACKETS)
04 REM U2--UNIT PRICE OF JACKETS
05 REM C--COST OF COATS
06 REM J--COST OF JACKETS
07 REM T--TOTAL COST
84 PROGRAMMING IN BASIC

- Reads the quantities and unit prices of the coats and


jackets from the DATA statement.
2a DATA 2,132,3,58 - Supplies the READ statement with data.
3a LET C=Ql*Ul - Finds the cost of the coats and stores the result in C.
4e LET J::Q2*U2 - Finds the cost of the jackets and stores the result in J .
5e LET T=C+J - Finds the total cost of all the items and stores the
result in T.
6~ PRINT - Leaves a blank line after the word RUN .
PRINT ·COATS·,IH,U1
7 I!! - Prints the quantity and unit price of the coats.
sa PRINT "COST PRICE:·;C - Prints the cost price of the coats.
9~ PRINT - Leaves a blank line.
lB~ PRINT ·JACKETS·,Q2,U2 - Prints the quantity and unit price of the jackets.
11~ PRINT ·COST PRICE:";J - Prints the cost price of the jackets.
120 F'R INT - Leaves a blank line.
13~ PRINT ·TOTAL COST:";T - Prints the total cost of all the items.
999 END - Terminates program execution.

RUN
COATS 2 132
COST PRICE: 264
JACKETS 3 58
COST PRICE: 174

TOTAL COST: 438

3.4 THE READIDATA STATEMENTS- Your


Turn
I. To have enough cash on hand to make change, a grocer starts
the day with $80.
1. How much cash does the grocer have at the end of the day if
$431 was received?

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

1. Complete line 20 with a DATA statement.

2. Complete lines 40, 50, and 60 with PRINT statements .

3 . Which statement should be coded in line 80?

(a) LET B=BtR


(b) LET B=B-R
(c) LET B=R-B
(d) LET R=R-B
( e) LET R=RtB

4. Complete line 100 with a PRINT statement.

5. Which statement should be coded in line 11 O?

(a) l.ET F'=B-P


(b) LET P=BtP
86 PROGRAMMING IN BASIC

(c) LET B=F'-B


(d) LET B=PtB
(e) LET B=B-P

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

TOTAL AMOUNT; 12.5


NUMBER OF DAYS: 5
AVERAGE AMOUNT EACH DAY; 2.5

III. An employee in a furniture factory is paid according to the


number of pieces produced . Find the total number of pieces
produced in 8 hours if the output was 6 pieces per hour.
(a) Use the READIDATA statements to enter the number of hours
and the number of pieces per hour .
(b) Total Pieces = Number of Hours x Number of Pieces per
Hour.
(c) Draw a flowchart before you write the program .

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

3,4 THE REAO/OATA


STATEMENTS-Solutions for "Your Turn"
I.

1.20 DATA 80,431,16.50


2.40 PRINT "CHANGE:";C
50 PRINT "RECEIPTS:";R
60 PRINT "PAYMENTS:";P
3. (a) 80 LET B=BtR
4 . 100 PRINT "CHANGE, RECEIPTS: ";B
5. (e) 110 LET B=B-P
88 PR OG RAMMI NG IN BAS IC

II .

01 REM T--TOTAL AMOUNT


02 REM D--DAYS
03 REM A--AVERAGE AMOUNT EACH DAY

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

3.5 THE RESTORE STATEMENT


Sometimes you may want to read the data items from one DATA
statement several times during execution of a program . This can be
accomplished by the use of a RESTORE statement. When the
computer encounters a RESTORE, it goes back to the first item in the
DATA statement that has the lowest line number. These data items are
reassigned when the computer executes the next READ statement.
Here is an example.

1£1 READ A,S


20 DATA 1,2
30
4~
50 RESTORE
60 READ L,M
70
99 END

The first READ statement assigns 1 to A and 2 to B. The RESTORE


statement makes all the items in the DATA statement available for
reassignment. This means that when the computer encounters the
READ statement in line 60, numbers 1 and 2 are reassigned, but this
time to Land M.
The program shown below prints the values of all the variables to
help you trace through the logic of the RESTORE statement.
90 PROGRAMMING IN BASIC

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

The first READ statement assigns 1 to A and 2 to B. The numbers 3,


4, and 5 are ignored. The RESTORE statement causes the computer to
go back to the beginning of the DATA statement with the result that
when the computer encounters the READ statement in line 60, 1 and 2
are reassigned, but this time to Land M, while 3 is assigned to N. The
numbers 4 and 5 are ignored . A RUN produces the following .

RUN
A = 1 B = 2
L = 1 H = 2 N = 3

Without the RESTORE statement, the computer does not go back to


the beginning of the DATA statement after assigning 1 to A and 2 to B.
Instead, the remaining values 3, 4, and 5 are assigned to L, M, and N
respectively . A RUN now produces the following .

RUN

A = 1 EI = 2
L = 3 H = 4 N = 5

3.5 THE RESTORE STATEMENT-Sample


Program
This sample program changes original data (10,20,30) first by adding
10 to each value and then by subtracting 10 from each value.
(a) Use the READ/ DATA statements to assign values to A, B, C.
(b) Change the values of A, B, C by adding 10 to each .
(c) Use a RESTORE statement to reassign the numbers in the DATA
statement to variables X, Y, Z .
. (d) Change the values of X, Y, Z by subtracting 10 from each .
Note : The original values of A, B, C and X, Y, Z must be printed
before they are changed.
ENTERING DATA INTO THE COMPUTER 91

- Reads the values of A, e, C from the DATA


statement.
20 DATA 10,20,30 - Supplies the READ statement with data.
30 PRINT - Leaves a blank li ne after the word RUN.
41!! PRINT "A =" ;A,"B ; " ;B,"C =";C - Prints the origin al values of A, e, C.
50 LET A=At10 - Adds 10 to the val ue of A and stores the
result back into A.
60 LET B=Bt10 e
- Add s 10 to the value of and stores the
resu It back into e.
70 LET C=Ct10 - Adds 10 to the val ue of C and stores
the result back into C.
80 PRINT "A =" jA,"B =" ;B,"C =";C - Prints t he new values of A, e, C.
9~ RESTORE - Causes the co mputer to go back to the
fi rst item in the DATA statement that has the
lowest line number.
100 READ X,Y,Z - Reassigns the values in the DATA
statement to variables X, Y, Z.
PRINT
lll!! - Leaves a blank li ne.
PRINT "X =" jX,"Y
1:.~~ ::=" ;Y,"Z =";Z - Prints the original values of X, Y, Z.
130 LET X=X-10 - Subtracts 10 from the value of X and
stores the result back into X.
140 LET Y=Y-H1 - Subtracts 10 from the value of Y and
stores the result back into Y.
150 LET Z=Z-10 - Subtracts 10 from the value ofZ and
stores the result back into Z.
160 PRINT "X ::=" ;X,"Y ::=" ;Y,"Z =";Z - Prints the new values of X, Y, Z.
999 END - Terminates program execution.

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

3,5 THE RESTORE STATEMENT-Your Turn


1. Identify the errors, if any, in the program segments shown below.
Make the necessary corrections. Note: Part (a) has two errors.

(a) 10 READ A,B,C (b) 10 READ A,B,C


20 DATA 1,2,3 20 DATA 2,4,6
60 RESTORE D,E,F 60 RESTORE
70 READ {I,E
99 END
99 END
92 PROGRAMMING IN BASIC

(c) UI READ A,It,C (d) HIREAD A,8,C


20 llATA 4,8,12
40 RESTORE
50 REAlI D,E,F 60 RESTORE 4,8,12
60 DATA 2,3,4 70 READ ll,E,F

99 END 99 END

2. What is the output of each of the following programs?

(a) 10 READ A,8,C


20 DATA 3,6,9
30 PRINT
40 PRINT "A =" ;A,"8 =" ;8,"C = C I ;

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

3. A customer is shopping for two items, a chair and a table lamp .


These items are originally marked at $80 and $60 respectively at
two different stores . The first store is offering a discount of $10 on
each item, while the second store is offering a discount of $20 on
each item. Write a program that finds the reduced price of each
item in each store.
(a) Use the READ/ DATA statements to assign the original prices to
variables C1 (chair in first store) and L1 (lamp in first store) .
(b) Change the values of C1 and L 1 by subtracting $10 from
each (discount offered by first store).
(c) Use a RESTORE statement to reassign the original prices to
variables C2 (chair in second store) and L2 (lamp in second
store) .
ENTERING DATA INTO THE CO MPUTER 93

(d) Change the values of C2 and L2 by subtracting $20 from


each (discount offered by second store).
(e) Remember to print the original values of C1, L 1 and C2, L2
before the values are changed.
(f) A new symbol is introduced in the flowchart. A six-sided
figure, called the preparation symbol, indicates that the com-
puter is getting prepared for a routine. Preparations vary. The
computer may initialize a variable, set up a FOR /N EXT loop
(explained in Chapter Six) or, as in this flowchart, RESTORE
data that has already been read.

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

3.5 THE RESTORE STATEMENT -Solutions


for "Your Turn"
1. (a) The key word RESTORE should not be followed by a list of
variables. The RESTORE statement should be followed by a
READ statement.

HI r~ EAD A,B,C
20 DATA 1,2,3

60 RESTORE
lD READ D,E,F
99 END

(b) Nothing is wrong.


(c) Nothing is wrong.
(d) The key word RESTORE should not be followed by a list of
numbers.

10 F,EAD A,B,C
20 DATA 4,8r12

60 RESTORE
7111 READ D,E,F

99 END

2.

(a) RUN (c) RUN


A ..- 3 B ::;:
6 C ::;:
9 A -- 5 B - HI
F' - 3 Q ::;:
6 R ::;:
9 P ::;:
5 a - HI R = 15
A ::;:
2111
(b) I:;:UN

A ::;: 3 B = 6 C = 9
p = 12 Q = 15

3.

1111 REM C1--CHAIR IN FIRST STORE


1112 REM L1--LAMF' IN FIRST STORE
1113 REM C2--CHAIR IN SECOND STORE
1114 REM L2--LAMP IN SECOND STORE
ENTERIN G DATA INTO THE COM PUTER 95

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

3,6 A WAGE PROGRAM


Here is a sample program that will be rewritten in subsequent
chapters but with additions and modifications so that it reflects newly
learned concepts. The program determines the wages of an
employee who works a certain number of hours at a specific rate per
hour. Deductions are made for income tax, union dues, and a regis-
tered pension plan . Here is the data needed for this program .

Hours Income Tax Union


Worked Rate Oed, Dues Pension Oed.
37 $11.54 $75 $2 $2.50

(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

1~0 REM READ/DATA STATEMENTS


105 READ H,R,I,U,P Calculate
110 DATA 37,11.54,75,2,2.50 Gross Pay
G=H*R
200 REM GROSS PAY Total Deductions
205 LET G=H*R D= I+U+P

300 REM TOTAL DEDUCTIONS


305 LET D=ItUtP Calculate
Net Pay
400 REM NET PAY IN =G-D
405 LET N=G-D

500 REM PRINT STATEMENTS Print


505 PRINT Blank line
510 PRINT "HOURS";H,"RATE";R H,R
515 PRINT "GROSS PAY" ; G G
~j20 PRINT "INCOME TAX";I I
525 PRINT "UNION DUES";U
53£1 PRINT "PENSION" H'
535 PRINT "TOTAL DEDUCTIONS" HI
540 PRINT "NET PAY";N
999 END

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

1. Which two statements enter data into the computer?

*******************************
105 READ H,R,I,U,P
110 DATA 37,11.54,75,2,2.50
ENTERING DATA INTO THE COMPUTER 97

2. Which statement calculates the gross pay?

*******************************
2~5 LET G=H*R

3. Which statement calculates the total deductions?

*******************************
305 LET [I=ItUtP

4. Which statement calculates the net pay?

*******************************
405 LET N=G-[I

5. Which statement prints the gross pay?

*******************************
515 PRINT 'GROSS PAY';G

6. Which statement prints the net pay?

*******************************
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

Eac h of the follow in g prog rams prints th e numbers 1, 2, 3 on one


li ne an d the sq uares of these numbers (1, 4, 9) on the next lin e. Pay
close atte ntio n to the RUN S . Noti ce that th e LET state ment and the
READ/DATA state ments produ ce the same RUNS. Th e INPUT statement
produ ce s a RUN th at is different, sin ce data is displayed imm ediatel y
after a prompt. Ther e is no need to have thi s data printed again.

1. Using the LET statement

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

2. Using the INPUT statement

10 PRINT
20 PRINT ·VALUES FOR A,B,C";
30 INPUT A,B,C
40 PRINT A12;B12;CT2
99 END

rWN

VALUES FOR A,B,C? 1,2,3


149

3. Using the READ/DATA statements

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

Items listed in a DATA statement may be reread by means of a


RESTORE statement. The program shown below assigns 1,2, and 3 to
variables A, B, and C, then reassigns these values to variables L, M,
and N.

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

The preparation symbol, a six-sided figure, was introduced in this


chapter. It indicates that the computer is getting prepared for a
routine. New techniques in flowcharting were also explained. These
included the placement of consecutive and similar operations in one
symbol and the omission of irrelevant material.

Questions and Exercises 3


1. Give the definition of a variable,
2. What must be the first character of a numeric variable?
3. Display and label a LET statement. Explain how a LET statement is
executed.
4. The assignment A=A+1 seems to resemble an algebraic equa-
tion, yet mathematically it makes no sense. Explain how such a
statement is entirely logical in BASIC.
5. Explain the term initialization of a variable. Give an example, Is
there any particular order in which two variables should be
initialized?
6. A programmer wishes to have the value of A printed each time a
number is assigned to the variable. What is wrong with the
following program? Make the necessary corrections.

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

The programmer would like to have the following RUN .

RUN
A = 1
A ::: 2
A = 3

7. Write a short program that copies a value stored in location A and


places it in location B . Use a LET statement to enter your data into
the computer . Print the values of both A and B and show the RUN
of your program.
8. What is wrong with the following program? Make the necessary
correction .

10 LET A=l
20 LET C==A+B
30 PRINT
40 PRINT "C =";C
99 ENII

RUN

C = 1£1

9. If the values of A, B, and C are initially 1, 2, and 3 respectively for


each of the following program segments , what will be their values
after execution of each statement? In which program segments
do the values of A and B interchange?

(a) 4£1 LET C=A (c) 48 LET A=B


5£1 LET A=B 5£1 LET B=C
6£1 LET B=C 6£1 LET C=A

(b) 4£1 LET B=C (d) 4 £I LET C=B


5£1 LET A=B S£I LET B=A
6£1 LET C=B 6£1 LET A=C
ENTERING DATA INTO THE COMPUTER 101

10. (a) What happens when the computer encounters an INPUT


statement?
(b) How does the programmer respond?
11. Write two programs, each of which INPUTS two values and PRINTS
two values. In one program use two INPUT statements to enter the
data; in the second program use only one INPUT statement . Show
the RUN for each program.
12. Using prompts, modify the following program so that the values
of A and B can be identified. Show the RUN for the modified
version of the program .

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 .

(a) HI LET B-4=A (e) 2fJ INPUT,X,Y,Z

99 END 99 END

(b) 1 fJ LET 51=121 (f) 2fJ PRINT ·VALUES FOR X,Y,Z· ;


3fJ INPUT X,Y,Z
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

(d) 1 B LET A=lfJ AND 12

99 END
102 PRO GRAMMING IN BASI C

(h) 20 PRINT ·VALUES FOR A,B,C·;


30 INPUT A,B,C

99 END
RUN

14. What is the purpose of each of the following statements?


(a) The READ statement
(b) The DATA statement
15. Write a program segment in which three READ statements are
satisfied by one DATA statement.
16. Write a program segment in which one REA D statement is satis-
fied by three DATA statements.
1 7. Identify the errors , if any, in the prog ram seg ments shown be low .
Make the necessary corrections.

(a) 20 REAlI A,B,C (f) 20 READ A,B,C


30 DATA ldtl,3
99 EN[I

(b) 20 REA[I A,B,C (g) 20 REAlI, A, B, C


30 DATA 48,49,SB
60 DATA 2,3
(c) 20 DATA 16d7d8 (h) 20 READ A,B,C

60 READ A,B,C 60 END


99 DATA 98,99dB0
(d) 20 READ A,B,C (i) 10 READ A,B,C
3B [lATA, 10, 11,12 20 DATA 113,20,30

60 RESTORE I,J,K

99 ENIt
(Note : There are two errors.)

(e) 21:1 READ 1,2,3 (j) 10 READ A,B,C,D


31:1 DATA A,B,C 20 DATA 2,4,6,8
60 RESTORE
71:1 READ I
99 END
ENTERING DATA INTO THE COMPUTER 103

18. Using a sample program, explain how a RESTORE statement is


executed .
19. Show the RUNS for the following programs.

(a) HI LET B=4 (d) 10 READ A,B


20 PRINT 20 DATA 1,2,3,4,5
30 PRINT B 30 PRINT
40 LET B=B+6 40 PRINT "A =' jA, "B c: B I ;

50 PRINT B 50 RESTORE
99 ENII 60 READ I,J,K
70 PRINT I =";I,"J =";J,"K
I = I ; K
99 END

(b) 10 LET C=2 (e) 10 READ A,B


28 LET D=C+1 20 DATA 1,2,3,4,5
30 LET C=C12 30 PRINT
40 LET D=C+1 40 PRINT • A =" jA, "Et =' ; B
58 PRINT 50 READ I,J,K
60 PRINT C,D 60 PRINT I =";I,'J =' ;J, 'K =";K
I

99 END 99 END

(c) Ul LET 1=8


20 LET J=I
:Hl LET K=J-5
40 LET I=K
50 PRINT
68 PRINT I,K
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

Using the LET Statement and the


READ/DATA Statements Using the INPUT Statement

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

2. If you were working in the furniture department of a store and


received a basic salary of $1 00 a week and a commission of 10%
based on sales, and if you sold $2200 worth of furniture last
week, how much commission would you receive? What would
your income be for the week?
(a) Use S for Salary.
(b) Use A for Amount of Sales.
(c) Commission = Amount of Sales x Rate of Commission (.10)
(d) Income = Salary + Commission

Using the LET Statement and the


READ/DATA Statements Using the INPUT Statement

RUN RUN

SALARY: 100 RATE: .1 SALARY,RATE? 100,.10


AMOUNT OF SALES: 2290 AMOUNT OF SALES? 2200
COMMISSION: 220 COMMISSION: 220
INCOME: 320 INCOME: 320

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

3 . A retailer purchases 50 pairs of shoes at a total cost of $2000 and Problem 3


sells them for $3100. Operating expenses amount to $500. Write S SALES
a program that finds the profit before expenses are paid (gross C COST
profit) and the profit after expenses are paid (net profit). E EXPENSES
(a) Gross Profit = Sales - Cost G GROSS PROFIT
(b) Net Profit = Gross Profit - Expenses N NET PROFIT

Using the LET Statement and the


READ/DATA Statements

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.

Using the LET Statement and the


READ/DATA Statements Using the INPUT Statement

RUN RUN

SALARY: 55a SALARY? 55121


PAYHENTS: 35121 PAYMENTS? 35a
AHOUNT SAVED: 2Ba AMOUNT SAVED: 2121a

SALARY: 55121 SALARY: 5521


PAYHENTS: 125 PAYHENTS? 125
AHOUNT SAVED: 625 AHOUNT SAVED: 625
106 PROGRAMMING IN BASIC

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

5. Convert 77°F to degrees Celsius. The conversion formula is as


follows.
C = .Q(F- 32)
9

Using the LET Statement and the


READ/DATA Statements Using the INPUT Statement

RUN RUN

FAHRENHEIT: 77 FAHRENHEIT'? 77
CELSIUS: 25 CELSIUS: 25

6. Use the READIDATA statements to assign 2000, 5000, and 8000 to


three variables. Print these values. Using the RESTORE state-
ment, copy the contents of these three storage locations and
store the values in three different locations in the computer. Print
the contents of these last three locations.

RUN

A = 2000 B = 5000 C = 8000


X = 2000 Y = 5000 Z = 8000
BRANCHING AND LOOPING I 107

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 .

4.1 THE GO TO STATEMENT


Until now, statements have been executed sequentially, from lowest
line number to highest. Sometimes, you may want to change the
108 PROGRAMMING IN BASIC

order of execution. One statement that alters the normal sequence is


the GO TO statement. (Some computer systems require GOTO.)
Here is how it works.

[ ~~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.

4.1 THE GO TO STATEMENT -Sample


Programs 1
The GO TO statement will now be used in a program that prints the
whole numbers 1,2, and 3. Three variations of this program are given ,

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

HI LET A=l -Initializes A to 1.


PRINT - Leaves a blank line.
[2~
3~ PRINT "A =" ; A - Prints the current valu e of A .
LET A=A+l
~~
- Increments A by 1.
GO TO 20 - Transfers control back to line 20. Execution res umes seq uentially
unti l line 50.
99 END - Not executed, but may have to be included.

F:LJN

A .- 1

I') ..-. r)
"'-

A -- 3

The program is in a continuous loop. How do you abort (stop) the


program? It depends on your computer system . A number of com-
mands to terminate a program were given in Chapter Two on page 15.
The list is shown again below. Remember, you may have to press
RETURN after the command key is pressed . If you are not using an
interactive system, turn off the machine and consult your manual.
(a) Press the STOP key .
(b) Hold the CTRL key down; press the C key .
(c) Press the BRE AK key .
(d) Press the ES C key .
(e) Press the A LT M O DE key .
(f) Press the S key .
(g) Turn off the machine.
(h) Consult your manual.

2. Using the INPUT statement

PRINT - Leaves a blank li ne.


PRINT "VALUE FOR A"; -Identifies the value to be entered.
INPUT A - Requests data, user enters the current value for A.
PRINT "A =";A - Prints the value of A .
GO TO 10 - Transfers control to line 10. Execution resumes
sequentially until line 50.
99 EN[I - Not executed , but may have to be included.
110 PROGRAMMING IN BASIC

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.

3. Using the READ/DATA statements

[ 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

After A is assigned a value of 3, the computer attempts to read


another value. Since all the items in the DATA statement are already
assigned , the computer prints a message something like the one
above , then stops .

4.1 THE GOTOSTATEMENT -YourTurn


Write three programs for each of the following two problems. Each
program is to use one of the three methods by which data can be
entered into the computer. RUN your programs to see what your
BRANCHING AND LOOPING I 111

computer system prints when a program is in a continuous loop


(using the LET statement), when the computer requests more data
(using the INPUT statement), and when the computer informs you that
it is out of data and stops (using the READIDATA statements). The RUNS
are shown below.
1. Print the whole numbers 2, 4, 6.

The LET Statement The INPUT Statement The READ/DATA Statements

A = 2 VALUE FOR A'? 2 A = 2


A = 2
A = 4 A = 4
VALUE FOR A? 4
A = 6 A = 4 A = 6

VALUE FOR A? 6 ,?OUT OF DATA ERROR IN 10


A = 6

VALUE FOR A'?

2. A customer buys 3 watches, one priced at $40, a second one


priced at $50, and the third one priced at $60. If a sales tax of 5%
is added to the retail price, what is the total cost of each watch?

(a) Sales Tax = Retail Price x .05


(b) Total Cost = Retail Price + Sales Tax
(c) In the flowchart, notice that a GO TO statement is represer;ted
by a line and two arrows. These are drawn from the PRINT
symbol (from the symbol that includes the statement just
before the GO TO) to the READ symbol. The flowchart is drawn
for the program that uses the READ/DATA statements.

The LET Statement The INPUT Statement The READ/DATA Statements

RETAIL PRICE: 40 RETAIL PRICE1 40 RETAIL PRICE: 40


SALES TAX: 2 SALES TAX: 2 SALES TAX: 2
TOTAL COST: 42 TOTAL COST: 42 TOTAL COST: 42
RETAIL PRICE: 5~ RETAIL PRICE'? 5~ RETAIL PRICE: 50
SALES TAX: 2.5 SALES TAX: 2.5 SALES TAX: 2.5
TOTAL COST: 52.5 TOTAL COST: 52.5 TOTAL COST: 52.5
~:ETAIL PRICE: 60 RETAIL PRICE'? 6~ RETAIL PRICE: 61a
SALES TAX: 3 SALES TAX: 3 SALES TAX: 3
TOTAL COST: 63 TOTAL COST: 63 TOTAL COST: 63

RETAIL PRICE'? ?OUT OF [lATA ERROR IN 11a


112 PROGRAMMING IN BASIC

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

4.1 GO TO STATEMENT-Programs for


"Your Turn"
1.

Using the LET Statement Using the INPUT Statement

HI LET A=2 10 PRINT


2~ PRINT 20 PRINT "VALUE FOR A";
3~ PRINT "A =" ; A 30 INPUT A
4~ LET A=At2 4111 PRINT "A =";A
5~ GO TO 20 58 GO TO 10
99 END 99 END
- - ~ ~------------,--

BRANCHING AND LOOPING I 113

Using the READ/DATA Statements

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.

Using the LET Statement Using the INPUT Statement

lH r~EM R--REHIIL PRICE ~1 ~:EM R---RETAIL PRICE


£12 REM T--TAX 02 REM T--TAX
~3 REM C--COST 1113 REM C---COST
1£1 LET R=4111 1111 PRINT
2£1 LET T=R*.1115 2~ PRINT "RETAIL PRICE" ;
3£1 LET C=RtT 3£1 INPUT R
4£1 PRINT 411 LET T=R*.11I5
~:j£l PRINT " REHllL PRICE:";R 5111 LET C=RtT
6£1 PRINT "SALES TAX:"q 60 PRINT "SALES TAX:";T
7fl PRINT "TOTAL COST:" ;C f'11I PF:INT "TOTAL COST:";C
BI1l LET R=R+ HI BI1l GO TO 1111
90 GO TO 2111 '1' 9 END
99 END

Using the READ/DATA Statements

01 REM R--RETAIL PRICE


1112 REM T--TAX
03 REM C--COST
1111 READ R
2£1 DATA 4111, 51!'), 6111
3£1 LET T=R*.I1IS
4111 LET C=RtT
50 PRINT
6111 PRINT "RETAIL PRICE:";R
7111 PRINT "SALES TAX:"q
8111 PRINT "TOTAL COST: C1 ;

9£1 GO TO 1111
99 ENIt
114 PROGRAMMING IN BASIC

4.2 THE IFfTHEN STATEMENT


The programs in Section 4,1 should be modified, They were either in
a continuous loop (using the LET statement), requested more data
(using the INPUT statement), or gave an error message (using the
READ/DATA statements), They should be changed so that the com-
puter can get out of the loop in order to execute the rest of the
program,

'1'7 END

In this example, the END statement is never executed, To abort the


first two programs, you had to type in a system command, Although
you didn't have to abort the program using the READ/DATA statements
(because it gave an error message instead), it, too, never reached the
END statement. There must be some other method by which looping
can be stopped so that termination of a program is automatic and not
user dependent. In other words, the END statement is executed, One
of the solutions is the IFITHEN statement, an important decision-
making statement. Here is an example,

30 IF A=6 THEN 99

99 END

In statement 30, the key word IF is followed by a relationship (in this


case, between A and 6); the key word THEN is followed by a statement
number which indicates the statement to which control must be
transferred when the relationship is true, In the example above, if A is
equal to 6, the computer branches to line 99, The program is now out
of the loop; in fact, it has reached the END statement. If A is not equal
to 6, the computer goes on to the next line and execution resumes
sequentially until line 60,

30 IF A=6 THEN 99

99
~
END
BRANCHING AND LOO PING I 115

Some computer systems accept the words GO TO instead of the


word THEN. Others accept THEN GO TO, while still others allow an
executable statement such as PRINT, END, or an assignment state-
ment after the word THEN. Here are some examples of the different
ways the statement may be written.

4f~ IF A=26 THEN 12e


~j 0 IF B=le GO TO HIe or 50 IF B=le GOTO lee
6£1 IF C=49 THEN GO TO 999 or 60 IF C=49 THEN GOTO 999
7£1 IF [I=5B THEN PRINT C
Be IF E=14 THEN [I::DT2
9£1 IF F=67 THEN END

Take another look at the IF part. The relationships in the examples


so far have been between a variable and a number. This does not
always have to be the case. The relationships may also be between :

(a) A variable and another variable.


20 IF A = C THEN 40
(b) A variable and an expression .
20 IF A = B*C THEN 40
(c) Two expressions.
20 IF A/2 == B*C THEN 40
Here is a simple table showing the BASIC relational operators and their
meanings.

RELATIONAL OPERATOR MEANING


is equal to
> is greater than
>= is greater than or equal to
< is less than
<= is less than or equal to
<> is not equal to

4.2 THE IF/THEN STATEMENT-Sample


Programs
The three sample programs in Section 4.1 will now be modified so
that the computer can pass out of the loops. Each program prints the
whole numbers 1, 2, 3, but enters data into the computer in a different
way . This time the IFITHEN statement will be used to automatically stop
116 PR OG RAMM IN G IN BASIC

program execution by transferring control out of the loop to the END


statement. Trace through the logic of the following programs . Ke y in
and RUN the first program in each of parts 1, 2, and 3 (not the program
segment) .

1. Using the LET statement

HI LET A=l -Initializes A to 1.


20 IF A>3 THEN 99 - Tests the current value of A .
(i) If A is greater than 3, control is transferred to the END state-
ment where the program terminates.
(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 .
30 PRINT - Leaves a blank line .
40 PRINT • A =. ; A - Prints the current value of A.
50 LET A=Atl -Increments A by 1.
60 GO TO 20 - Transfers control back to line 20.
99 END - Terminates program execution .

RUN
A = 1

A = 2

A = 3

There is usually more than one way to write a program. Here is


another method by which the relationship between A and 3 can be
tested .

H1 LET A=l -Initializes A to 1.


2~ IF A(=3 THEN 40 - Tests the current value of A .
(i) If A is less than 3 or A is equal to 3, control is transferred to line
40, where execution resumes sequentially until line 70.
(ii) If A is greater than 3, the computer proceeds to the next
statement .
30 GO TO 99 - Transfers control to the END statement , where the program ter-
minates .
40 -- } - Executable statements.
50 --
60 LET A=Atl -Increments A by 1 .
70 GO TO 20 - Transfers control back to line 20.
99 END - Terminates program execution .
BRANCHING AND LOO PI NG I 117

2. Using the INPUT statement

H'J PRINT - Leaves a blank line.


2~ PRINT "VALUE FOR A"; -Identifies the value to be entered .
3El INPUT A - Requests data, user enters the value for A .
4~ IF A) 3 THEN 99 - Tests the current value of A .
(i) If A is greater than 3, control is transferred to the
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.
50 PRINT "A =";A - Prints the current value of A .
60 GO TO HI - Transfers control back to line 10.
9(1 END - Terminates program execution .

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

3El INPUT A - Requests data, user enters the value for A .


40 IF A(=3 THEN 6B - Tests the current value of A .
(i) If A is less than 3 or A is equal to 3, control is transferred to line
60, where execution resumes sequentially until line 70 .
(ii) If A is greater than 3, the computer proceeds to the next
statement.
5£1 GO TO 99 - Transfers control to the END statement.
60 - Executable statement.
70 GO TO HI - Transfers control back to line 10.
99 END - Terminates program execution.
118 PROGRAMMIN G IN BASIC

3. Using the READ/DATA statements

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

In the above program an extra value is listed in the DATA statement,


the number 3.5 . As in the program that uses the INPUT statement, this
value may be any number greater than 3 in order to stop execution.
An alternative version of the above program wou ld be as follows.

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 .

10 LET A=l -Initializes A to 1.


20 PRINT - Leaves a blank line.
30 PRINT "A =";A - Prints the current value of A.
40 IF A) 2 THEN 99 - Tests the current value of A .
(i) If A is greater than 2, control is transferred to the END statement.
(ii) If A is not greater than 2 (less than 2 or equal to 2). the computer
proceeds to the next statement. Execution resumes sequen-
tially until line 60.
50 LET A=Atl -Increments A by 1.
60 GO TO 20 - Transfers control back to line 20.
99 ENt. - Terminates program execution .

RUN

A = 1

A = 2

A = 3

4.2 THE IF/THEN STATEMENT-Your Turn


In Section 4.1 , you were asked to write three programs for each of the
two problems presented . The programs for each problem were to use
the three methods by which data can be entered into the computer .
Rewrite these programs . This time use IFITHEN statements to transfer
control out of the loops. Here are the two problems again .
120 PR OGRAMMING IN BASIC

1. Print the whole numbers 2, 4, 6. Your programs should produce


the following RUNs.

Using the LET Statement and the


READ/DATA Statements Using the INPUT Statement

RUN RUN

A = 2 VALUE FOR A? ......,


...,
A = "-
A = 4
VALUE FOR A? 4
A = 6 A = 4

VALUE FOR A? 6
A = 6

VALUE FOR A? 8

2 . A customer buys three watches - one priced at $40, a second


one priced at $50, and a third one priced at $60. If a sales tax of
5% is added to the retail price , what is the tax and what is the total
cost of each watch?
(a) Sales Tax = Retail Price x .05
(b) Total Cost = Retail Price + Sales Tax
(c) The decision symbol, a diamond-shaped figure , is intro-
duced in the flowchart. It indicates that the computer is about
to make a decision. The four points of the symbol represent
incoming and outgoing flows of logic. The top point is usually
reserved for an incoming path of logic, while the other three
are used to show the various outgoing paths of logic. A
symbol with two outgoing branches usually has the word
YES or the word NO marked on the exit paths to show the
respective result of an IFITHEN test. A decision symbol with
multiple branches will be shown in the next section . The
flowchart is drawn for the program that uses the INPUT state-
ment.
(d) Your programs should produce the following RUNs.

Using the LET Statement and the


READ/DATA Statements Using the INPUT Statement

RUN RUN

RETAIL PRICE: 40 RETAIL PRICE? 4~


SALES TAX: 2 SALES TAX: 2
TOTAL COST: 42 TOTAL COST: 42
RETAIL PRICE: 5~ RETAIL PRICE? 5~
SALES TAX: 2.5 SALES TAX: 2.5
TOTAL COST: 52.5 TOTAL COST: 52.5
BRANCHING AND LOOPING I 121

RETAIL PRICE: 60 RETAIL PRICE'? 60


SALES TAX: 3 SALES TAX: 3
TOTAL COST: 63 TOTAL COST: 63

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

4.2 TH E IF/THEN STATEMENT -Programs for


"Your Turn"

1. Using the LET Statement Using the READ /DATA Statements

10 LET A=2 Hl READ A


2£1 IF A)6 THEN 99 221 DATA 2,4,6,8
30 PRINT 321 IF A>6 THEN 99
4£1 PRINT 'A = ' ; A 421 PRINT
5£1 LET A=At2 521 PRINT 'A =' ; A
6£1 GO TO 20 6£1 GO TO 10
99 END 99 END

Using the INPUT Statement

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

2. Using the LET Statement

01 REM R--RETAIL PRICE


212 REM T--TAX
£13 REM C--TOTAL COST
121 LET R=40
20 IF R>60 THEN 999
321 LET T=R*.e5
40 LET C;;;;RtT
5£1 PRINT
621 PRINT 'RETAIL PRICE:";R
721 PRINT "SALES TAX: " ; T
821 PRINT "TOTAL COST:';C
9£1 LET R=RtH'1
1021 GO TO 2£1
999 END
BRAN CHIN G AND LO OPING I 123

Using the READ/DATA Statements Using the INPUT Statement


-----------------------
91 REM R--RETAIL PRICE 01 REM R--RETAIL PRICE
92 REM T--TAX £12 F~EM T--TAX
93 REM C--TOTAL COST 03 REM C--TOTAL COST

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

4,3 THE ON" ,GO TO STATEMENT


The last two sections discussed the GO TO and the IFfTHEN state-
ments. The GO TO statement is referred to as an unconditional
transfer, since there is no choice but to GO TO a specific statement.
The IFfTHEN statement is referred to as a conditional transfer. This is
because the computer branches to another statement only when a
certain condition is met. The IFfTHEN statement offers a two-way
choice. Conditions can be either true or false . If the condition is true,
the computer branches to the statement specified ; if the condition is
false , there is no transfer and the computer proceeds to the next line .
Here is another conditional control statement. This one offers a
multiple-way choice for control to be transferred . It is called the
ON ... GO TO statement (some computer systems require ON. ,.
GOTO) , and it allows the computer to branch to one of several
statements , depending on the current value of a certain variable or
expression. This variable or expression is called the index of the
ON . . . GO TO. Here are two examples, one using a variable as the index
and the other using an expression as the index.

/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

If the numeric value of the variable or expression is either 1 or 2 or


3, etc ., co ntrol is transferred to either the fi rst or second or th ird, etc .,
statement number in the list In the example 20 ON 1 GO TO
25,40,50,60,50,2 if 1 = 1, control is transferred to statement 25 , the
first number in the list If 1 = 2, control is transferred to statement 40 ,
the second number in the list If 1 = 3 or 5, control is transferred to
statement 50, the third and fifth numbers in the list If 1 = 4, control is
transferred to statement 60, the fourth number in the list Note that the
value of the index (I) is really a code that is used to transfer control to
anyone of the statements whose numbers are listed in the ON .. GO
TO statement.
In example two, the expression J-2 is evaluated. If the result is a
number that contains a decimal fraction, the decimal part is ignored
(that is , the number is truncated), and the integer portion is used as
the value of the index . For example, if the evaluation ofJ-2 results in
2.85 , the .85 (the decimal part) is ignored, and the result of J-'2 is
considered to be 2 (the integer part). This means that in the second
example ,30 ON J-2 GO TO 60,45,60,80, control is transferred to
statement number 45 .
Numbers are represented in a computer as a series of ones and
zeros (base two) .3 Due to the conversion of a decimal number to
binary format, small inaccuracies may occur in one or several of the
low-order digits of the decimal. Here is an example.

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

Subtracting 13 from 13.2 and multiplying the result by 10 should


give the number 2, yet the computer prints out 1.99999999. When
this is truncated in an ON . . . GO TO statement, the index turns out to be
1 instead of 2 You can safeguard the index simply by increasing its
value by a small amount An ON GO TO statement may look as
follows .

2111 ON Ct.11I1111111 GO TO 3111,5111,999

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

Again , refer to your manual if no version of the ON .. . GO TO state-


ment mentioned in this section works on your computer system.
You may have realized by now that one ON ... GO TO statement can
be used instead of several IFfTHEN statements. Our first example

20 ON I GO TO 25,4B,5~,6~,50

could have been coded as follows,

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

Notice that one ON ... GO TO statement replaces the five IFITHEN


statements.

4,3 THE ON" ,GOTO STATEMENT-Sample


Program
Here is a program that READs in a number and uses an ON ... GO TO
statement to:
(a) Add 2 to the number if the index is 1.
(b) Subtract 2 from the number if the index is 2.
(c) Multiply the number by 2 if the index is 3.
(d) Divide the number by 2 if the index is 4.
(e) Terminate execution when the index is 5. Use LET statements to
initialize and generate the index .
Notice how control branches out of the loop to line 999, the END
statement, when the index is equal to 5.

HI PRINT - Leaves a blank line .


2~ LET 1=1 -Initializes the index to 1.
30 REAli A - Reads the value of A from the DATA
statement.
4~ DATA 1~ - Supplies the READ statement with data.
5~ ON I GO TO 60,80,100,120,999 - Branches to a statement whose line
number is in the list. The
branch depends on the value of the index.
6~ PRINT A,At2 - Prints the values of A and A+2.
70 GO TO 130 - Transfers control to line 130.
130 PRINT A,A-2 - Prints the values of A and A-2 .
9~ GO TO 130 - Transfers control to line 130.
100 PRINT A,A*2 - Prints the values of A and A*2.
110 GO TO 130 - Transfers control to line 130.
120 PRINT A,A/2 - Prints the values of A and A/2.
1.30 LET I=It1 -Increments the index by 1.
14£1 GO TO 50 - Transfers control back to line 50 .
(i99 END - Terminates program execution.

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.

4,3 THE ON" ,GO TO STATEMENT - Your


Turn
I. The social fees to a community club are as follows:
1 person $150
family rate (2 people) 275
family rate (3 people) 400.
Write a program that prints the above fee schedule.
(a) Use the READ/DATA statements to enter the number of peo-
ple and the fee for each category.
(b) Use an ON ... GO TO statement to branch to the statements
that print the appropriate fees and to branch to the END
statement.
(c) Use the number of people as the index with a code of 4 to
terminate the loop.
(d) Fill in the missing lines.

01 REM P--NUMBER OF PEOPLE (INDEX)


02 REM F--FEE

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

ONE PERSON: 150


FAMILY--TWO PEOPLE: 275
FAMILY--THREE PEOPLE: 400
128 PR OG RAMMING IN BAS IC

1. Complete lines 30 and 40 with DATA statements .


2. Complete lines 80 and 100 with PRINT statements .
3. Complete line 110 with a GO TO statement.
4. Complete line 120 with a PRINT statement.
5. Complete line 130 with a GO TO statement.
6. Wh y does this program require a fourth DATA statement with
the value 4 as the first item in the list? What is the purpose of
the second number (85)? Must it be a specific number?
II. An article formerl y marked at $60 is now advertised at a reduced
price in three different stores. Find the amount that a customer
would save in each store .

Store Rate of Reduction


1 25%
2 20%
3 15%

(a) Use two sets of RE A D/DATA statements , one to enter the


marked price and the other to enter the number of each
store.
(b) Use the O N . . . G O TO statement to branch to the statements
that multiply the marked price by the appropriate rates of
reduction and to branch to the END statement.
(c) Use the number of the store as the index with a code of 4 to
terminate your loop.
(d) Amount Saved = Marked Price x Rate of Reduction
(e) The flowchart for this program has four paths coming from
the decision symbol. Pairs of connectors (with the same
letter ins ide both connectors of a pair) show where control is
transferred depending on the value of S . The lines coming
from the three process symbols converge to the output
figure . Control is then transferred from this figure to the
second input symbol.

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

4,3 THE ON" ,GO TO


STATEMENT -Solutions for "Your Turn"
I.

1. 30 [lATA 2,275
4E1 DATA 3,400
130 PR O GRA MMING IN BASIC

2. PRINT "ONE PERSON:";P


8~
PRINT "FAMILY--TWO PEOPLE:";F
10~
3.110 GO TO U3
4.120 PRINT "FAMILY--THREE PEOPLE:";F
5. 13£1 GO TO HI

6. The fourth DATA statement is required in order to assign 4 to


the index so that the computer can branch out of the loop.
The purpose of the second number is to satisfy the READ
statement. Since there are two variables in the READ state-
ment (P and F) , there must be two items of data in the DATA
statement. This second number need not be a specific value
since the program is stopped before the number can be
used.
II.

01 REM M--MARKED PRICE


£12 REM S--STORE NUMBER (INDEX)
03 REM A--AMOUNT SAVED

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.

4.4 COUNTERS-Sample Programs


I. The following program prints out five numbers (5, 12,9, 14, 17) .
A counter controls the loop so that it is performed five times .
A long with each number, the current value of the counter is also
printed.

121 PRINT - Leaves a blank line .


20 LET K=l -Initializes the counter to 1.
3f1 READ A - Reads the values of A one at a time from the DATA
statement.
421 DATA 5,12,9,14,17 - Supplies the READ statement with data.
5~ PRINT K,A - Prints the current values of K and A.
60 LET K=K+1 -Increments the counter by 1.
70 IF K>5 THEN 99 - Tests the current value of the counter.
(i) IfK is greater than 5 , control is transferred to the END
statement.
(ii) If K is not greater than 5, the computer proceeds to the
next statement.
Sf! GO TO 30 - Transfers control back to line 30.
99 ENI) - Terminates program execution .

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

HI PRINT - Leaves a blank line .


2l?lLET K=l -Initializes the counter to 1.
30 LET P=K*S ~ Multiplies the counter by 5.
40 PRINT K,P - Prints the current value of the counter and the product.
5i1 LET K=Ktl -Increments the counter by 1.
6~~ IF K>4 THEN 99 - Tests the current value of the counter .
(i) If K is greater than 4, control is transferred to the END statement.
(ii) If K is not greater than 4, the compute r proceeds to the next
statemen t.
7,.1 GO TO 3a - Transfers control back to line 30.
<'9 END - Terminates program execution.

fWN

1 S
2 10
3 1""
.J
4 2f:'1

III. Counters may also be negative . For example :

10 PRINT - Leaves a blank line.


20 LET K=S -Initializes the counter to 5.
3£1 READ A - Reads the values of A one at a time from the DATA
statement.
4~ DATA 5,12,9,14,17 - Supplies the READ statement with data .
Sf! PRINT K,A - Prints the current values of K and A .
6~ LET K=K-l - Decrements the counter by 1.
70 IF K)f:'I THEN 30 - Tests the current value of the counter.
(i) If K is greater than 0, control is transferred to line 30 to
resume READing .
(ii) If K is not greater than 0 (that is , equal to 0), the
computer proceeds to the next statement.
99 END - Terminates program execution.
BRANCHING A ND LOOPING I 133

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.

4.4 COUNTERS-Your Turn


I. A retailer purchases three articles from a wholesaler; the first
one costs $50, the second one costs $10, and the third one costs
$30 . Before placing them in the salesroom, the retailer marks up
each article by 30%. What is the markup and what is the retail
price of each article?
(a) Use the READ/DATA statements to READ in the cost price of
each article.
(b) Use a counter to control your loop.
(c) Print out the number of the article (1, 2, 3, which is your
counter), the cost price , markup, and retail price .
(d) Markup = Cost Price x .30
(e) Retail Price = Cost Price + Markup

01 REM K--COUNTER (ARTICLE NO.)


~2 REM C--COST PRICE
~3 REM M--MARKUP
04 REM R--RETAIL PRICE
10 PRINT
20 LET K=l
30 READ C
4~
50
60
70 PRINT K,C,M,R
80
90
HH'
999 END
134 PROGRAMMING IN BASIC

RUN

1 S0 15 65
2 10 3 13
3 30 9 39

1. Complete line 40 with a DATA statement.


2. Which statement should be coded in line 50?

(a) LET R=M*.3111


(b) LET C=R*.3111
(c) LET M=C+R
(d) LET C:::M+R
(e) LET M=C*.3111

3 . Which statement should be coded in line 60?

(a) LET F:=C-M


(b) LET C ~"R-M
(c) LET R=CtM
(d) L ET M=C*. 3111
(e) LET C=M*. 3111

4. Increment the counter in line 80.


5 . Which statement should be coded in line 90?

(a) IF K<3 THEN 999


(b) IF K=3 THEN 7111
(c) IF K<3 THEN 4111
(d) IF K:>3THEN 999
(e) IF K>3 THEN 3111

6. Complete line 100 with a GO TO statement .

II. Suppose a deduction of $600 is allowed on taxable income for


each dependent under the age of 18. Find the deductions on
three income tax returns - the first with 1 dependent , the sec-
ond with 2 dependents, and the third with 3 dependents.
(a) Use a counter
-to terminate yo ur loop ;
- in your calculations .
BRANCHING A ND LOOPING I 135

(b) Deduction = Dependents (your counter) x 600


(c) Draw a flowchart before you write the program.

RUN

DEPENDENTS: 1 DEDUCTION: 60P.1


DEPENDENTS: 2 DEDUCT ION: 120111
DEPENDENTS: 3 DEDUCT ION: 180111

4.4 COUNTERS-Solutions for "Your Turn"


I.

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.

01 REM K--COUNTER (NO. OF DEPENDENTS)


02 REM D--DEDUCTION

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.

1. It checks each data item for the final value.

10 LET A:::40
20 IF A)100 THEN

60 LET A=At20
138 PROGRAMMING IN BASIC

70 GO TO 20
80 ~(----------~

'199 END

2. It checks a counter for a specific value .

H'l LET K=l


20

5~ LET K=Ktl
60 IF K)3 THEN
7a GO TO 20 80~
80 (

999 END

The third method of controlling a loop is by means of the ON .. GO TO


statement, which uses its index to transfer control to a particular
statement. In the example shown below, control is transferred to the
END statement when the value of the index (K) becomes 3.

40 ON K GO TO 50, 7~" 999

999 EN [I 4f(:.....-_ _ _ _ _ _.....J1

The decision symbol , a diamond-shaped figure, was introduced in


this chapter. It indicates that the computer is about to make a deci-
sion. Two outgoing branches from the symbol usually signify an
IFfTHEN statement, while multiple outgoing branches signify an ON.
GO TO statement.

Questions and Exercises


1. Why is a GO TO statement considered an unconditional branch?
2. What happens when a GO TO statement directs control to a
statement with a lower line number?
3. Identify the errors, if any , in the GO TO statements shown below .
Make the necessary corrections.
BRAN CHING AND LOOPING I 139

(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

4 . Why is an IFfTHEN statement considered a conditiona l branch?


5 . How do the follow ing statements differ in the number of alterna-
tives offered in transferring contro l?
(a) The GO TO statement
(b) The IFfTHEN statement
(c) The ON ... GO TO statement
6. List the six BASIC relational operators and their meanings.
7. Write IFfTHEN statements for the following.
(a) Branches to line 30 if the value of A is equal to 12.
(b) Branches to line 50 if the value of A is not equal to the value
ofC.
(c) Branches to line 70 if the value of A divided by 10 is less than
the value of B.
(d) Branches to line 40 if the value of A mu ltiplied by 5 is greater
than or equal to the value of B multiplied by C .
8. Identify the errors, if any , in the IFfTHEN statements shown below.
Assume that the variables have been assigned values prior to
each IFfTHEN statement .

(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

9 . Give the definition of


(a) A branch.
(b) A loop.
10. Rewrite the following program so that the test in line 30 deter-
mines whether or not the value of A is less than or equal to 10
(instead of greater than 10) .

HI F'RINT
20 LET A=l
30 IF A)10 THEN 99
40 PRINT A
140 PROGRAMMING IN BASI C

5£1 LET A=Atl


6f.l GO TO 3£1
99 END

11 . What is wrong with the following program?

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

12. What is the difference in execution between the ON . GO TO


statement and the GO TO statement?
13 . What happens when the value of the index of an ON ... GO TO
statement is a number that contains a decimal fraction? Give an
example .
14. Identify the errors, if any, in the ON ... GO TO statements shown
below. How does your computer respond to (a) and (d)?

(a) 1£1 LET K=3


2£1 DN K--3 GO TO 3~,5~,7~,999

(b) 1£1 LET K=12


2£1 ON K/6 THEN GO 9I1ldl~,8~

(c) 1£1 LET K;;::l~


2£1 ON K/4 GO TO 6~,55,8~

( d) 111l LET 1<=3


20 ON 1<*2 GO TO 12£1,19~,1~5

(e) 1£1 LET 1<=1


20 ON Ktl GO TO 55,85,95,999

(f) HI LET \(=3


2£1 LET J=4
3£1 ON I< OR J GO TO 4~,6~,8~,999
BRA NC HING AND LOOPING I 141

15 . Do the following program segments give the same results?

(a) 3~ LET 1(=1


40 ON I( GO TO 5~,lB,999

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

16. What is the output of the following program?

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

17. (a) State two restrictions that limit the index of an ON .. GO TO


statement.
(b) Summarize how your computer responds to an ON ... GO TO
statement whose index is out of the range .
18. State the purpose of each of the three statements that are
required to set up a counter that controls a loop . Code each
statement along with your explanation .
19. Rewrite the program shown below so that the counter runs in a
negative direction ; that is, the counter is decremented rather
than incremented in line 60 .

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

2. Suppose the employees of the XYZ Manufacturing Company are


paid on the basis of the number of parts produced. If the rate of
pay is $2 per part in department 12, find the incomes of three
employees using the weekly record given below .

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

Employee Number of Parts Produced


1 212
2 213
3 209
(a) Use the READ/DATA statements to enter the number of parts
produced by each employee.
(b) Use a counter :
-to keep track of the number of the employee.
-to terminate your loop after the third employee.
(c) Print the department number (12) along with the rate.
(d) Income = Number of Parts Produced x Rate

Problem 1
P REGULAR PRICE
D DISCOUNT
R REDUCED PRICE

Yes " ( End _ )


__

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

3. Write a program that determines the balance of a customer's


account after each of the following transactions . There is no
previous balance. Codes are used to indicate whether the trans-
action is a purchase or a payment.
Purchase .. . . . . . .. $250
Payment . .. .. .. . .. ..... . . . 150
Purchase . .... . .. . .. , .. . ... .. . 300
Payment .. .. ..... . 200
(a) Use the INPUT statement to enter the code and the amount of
each transaction.
(b) Use an ON . _. GO TO statement for multiple branching.
(c) Use a code of 1 if the transaction is a purchase, a code of 2 if
a payment is made , and a code of 3 to indicate the end of the
data .
(d ) Depending on your code :
Balance = Balance + Purchase
or
Balance = Balance - Payment.

Using the INPUT Statement Using the READ/DATA Statements

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.

30 LET L=-1 -Initia lizes LARGE to - 1 .

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

80 LET L=S - Replaces LARGE by the amo unt of the SALE .


BRANCHING AND LOOPING I 147

Complete the above program segment so that your program


finds the largest sale made by one salesperson whose sales are :
$8700,$6300,$9400,$7600,$8500.

(a) Use the INPUT statement to enter the data.


(b) Use a counter to terminate your loop.

Using the INPUT Statement Using the READ/DATA Statements

RUN RUN

SALE'? 87121121 SALE: 87121121


SALE'? 63121121 SALE: 63121121
SALE'? 949B SALE: 949121
SALE'? 76121121 SALE: 76121121
SALE'? 85121121 SALE: 85121121

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

Note: Separate symbols for PRINT statements that print End


blank lines are omitted in flowcharts.

7 Shown below is the formula that finds the area of a rectangle.


Area = Length x Width
Find the areas of 5 rectangles The first one has a length of 3 units
and a width of 2 units.
(a) Use LET statements to enter the dimensions of the first
rectangle.
(b) Inside a loop, increase the length of this rectangle by one unit
and the width by one unit. Find the dimensions of the remain-
ing rectangles the same way, that is, increase the length and
the width of each previous rectangle.
(c) Use a counter to control your loop.
(d) Print headings over the lengths, widths, and areas, as shown
in the RUN. Leave a blank line after the headings. Code the
headings as strings in a PRINT statement.
(e) Print your output widely spaced.

RUN
LENGTH WIDTH AREA
3 2 6
3 12
'56" 4 221
5 321
7 6 42
r-------.---------------- ~ - - -.---- ~ --.- ~ ~ -.- - - - - - - - - - - - ---,-- - - - - ,

BRANCHING AND LOOPING II 149

F VE BRANCHING
AND LOOPING II

A. After completing this chapter, you should be able to write BASIC


programs and complete skeletal BASIC programs that use:
1. Trailer values to terminate loops.
2. Special values that represent the number of data items.
3. Sets of data entered during passes through loops.
4. The summation routine.
B. In addition, you should be able to:
1. Explain the purpose of a trailer value.
2. Summarize how a special value terminates a loop.
3. (a) Explain how sets of data are assigned to variables during
each pass through a loop.
(b) State the purpose of the last set.
4. Find errors in programs.
5. Produce the output of programs.
6. Differentiate between the various ways of terminating a loop.
(a) a counter
(b) a special value
(c) a traHer value
(d) a test on each data item
(e) an ON ... GO TO statement

5.1 TERMINATING A LOOP-TRAILER VALUE


The last chapter illustrated three ways by which a loop can be
controlled. These are:
1. An IFfTHEN statement that checks each data item for the final
value.
2. An IFfTHEN statement that checks a counter for a particular value.
3. An ON ... GO TO statement that uses its index to transfer control to
a specific statement.
There are two more ways by which the IFfTHEN statement can
control a loop. One of them detects the end of input data by the use of
a trailer value or a flag. This value is usually some illogical number for
the program being written and is entered as the last item. Each time a
data item is entered, a test is made to determine whether or not this
number is the trailer value. If the item is not the trailer value, execution
continues; if it is, control is transferred to another routine or to the END
statement. Here are two program segments, each using a trailer value
to detect the end of input data. One program enters data by means of
the INPUT statement; the other program enters data by the use of the
READ/DATA statements.
150 PROGRAMMING IN BASIC

1. Using the INPUT statement 2. Using the READ/DATA statements

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 ~----------------~

In Program 1, the trailer value is keyed in as the last number in


response to the INPUT statement in line 30, Line 40 tests this value,
and if the number is the trailer value, control is transferred to the END
statement. If the number keyed in is not the trailer value, the com-
puter proceeds to line 50, In Program 2, the flag is listed as the last
item in the DATA statement. The test in line 30 is execu ted in the same
manner as in Program 1,

5,1 TERMINATING A LOOP-TRAILER VALU E


-Sample Programs
The three sample programs in Section 4,1 of Chapter Four made no
provisions for the computer to branch out of the loops _These three
programs printed the whole numbers 1, 2, and 3, Two of these
programs will now be rewritten - the one using the INPUT statement
and the one using the READ/DATA statements, To detect the end of
data, a trailer value (a flag) of 99999 will be used,

1. Using the INPUT statement

10 PRINT - Leaves a blank line,


20 PRINT -VALUE FOR A-; -Identifies value to be entered,
30 INPUT A - Requests data, The last value entered wil l be 99999,
4B 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.
(ii) If A is not equal to 99999 , the computer proceeds to
the next statement.
50 PRINT 8A =8;A - Prints the current value of A,
6i'\ GO TO ii' - Transfers control back to line 10.
99 END - Terminates program execution,

RUN

VALUE FOR A'? 1


A = 1
---- - -- - - -.-------

BRANCHING AND LOOPING II 151

'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.

2. Using the READ/DATA statements

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.

5.1 TERMINATING A LOOP- TRAILER VALUE


- Your Turn
Now might be a good time to review some of the problems in the
"Your Turn" units of Chapter Four. In each of the following, use a flag
of 99999 to terminate input.
152 PROGRAMMING IN BAS IC

1. Problem from Section 4.2, Page 120


A customer buys three watches : the first one priced at $55, the
second one priced at $60, and the third one priced at $40. If a
sales tax of 5% is added to the retail price, what is the tax and
what is the total cost of each watch?
(a) Use the INPUT statement to enter each retail price. Your
flowchart should be similar to the one on page 121 in Chapter
Four. The only difference is in the decision symbol , where
you should check for the trailer value instead of the last data
item.
(b) Sales Tax = Retail Price x .05
(c) Total Cost = Retail Price + Sales Tax

Using the INPUT Statement Using the READ /DATA Statements

RUN RUN

RETAIL PRICE'? 55 RETAIL PRICE: 55


SALES TAX: 2.75 SALES TAX: 2.75
TOTAL COST: 57.75 TOTAL COST: 57.75
RETAIL PRICE'? 60 RETAIL PRICE: 60
SALES TAX: 3 SALES TAX: 3
TOTAL COST: 63 -TOTAL COST: 63

RETAIL PRICE'? 40 RETAIL PRICE: 40


SALES TAX: 2 SALES TAX: 2
TOTAL COST: 42 TOTAL COST: 42
RETAIL PRICE'? 99999

2. Problem from Section 4.4, Page 133


A retailer purchases three articles from a wholesaler; the first one
costs $50, the second one costs $10, and the third one costs
$30 . Before placing them in the salesroom , the retailer marks up
each article by 30% . What is the markup and what is the retail
price of each article?
(a) Use the RE A D/ DATA statements to enter the cost price of each
article .
(b) Use a counter to keep track of the article currentl y being
marked up (article 1, article 2, article 3)
(c) Print out the number of the article along with its cost, markup ,
and retail price .
(d) Markup = Cost Price x .30
(e) Retail Price = Cost Price + Markup

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

3. Problem from Section 4.4, Page 134


Suppose a deduction of $600 is allowed on taxable income for
each dependent under the age of 18. Find the deductions on
three income tax returns -the first with 1 dependent, the sec-
154 PROGRAMMING IN BASIC

ond with 2 dependents, and the third with 3 dependents .


(a) Use the READ/ DATA statements to enter the number of
dependents on each income tax return.
(b) Deduction = Dependents x 600

RUN

NO. OF DEPENDENTS; 1
DEDUCTION: 600
NO. OF DEPENDENTS: 2
DEDUCTION: 12021
NO. OF DEPENDENTS: 3
DEDUCTION: IS00

5.1 TERMINATING A LOOP- TRAILER VALUE


- Solutions for "Your Turn"

1. Using the INPUT Statement Using the READ/DATA Statements

01 REM R--RETAIL PRICE 01 REM R--RETAIL PRICE


02 REM T--TAX 02 REM T--TAX
213 REM C--TOTAL COST 03 REM C--TOTAL COST
10 PRINT 121 READ R
20 PRINT ·RETAIL PRICE·; 221 DATA SS,60,4e,99999
30 INPUT R 30 IF R=99999 THEN 999
40 IF R=99999 THEN 99 421 LET T=R*.es
521 LET T=R*.05 521 LET C=R+T
60 LET C=R+T 60 PRINT
721 PRINT "SALES TAX:";T 70 PRINT ·RETAIL PRICE:·;R
se PRINT "TOTAL COST:";C S0 PRINT "SALES TAX:";T
90 GO TO 10 921 PRINT ·TOTAL COST:·;C
99 END 100 GO TO 121
999 END

2.

211 REM K--COUNTER (ARTICLE NO.)


02 REM C--COST PRICE
213 REM M--MARKUP
214 REM R--RETAIL PRICE
BRANCHING AND LOOPING II 155

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.

01 REM N--NUMBER OF DEPENDENTS


~2 REM D--DEDUCTION

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

5.2 TERMINATING A LOOP-SPECIAL VALUE


Here is one more method that uses the IFn"HEN statement to control a
loop. This one uses the READ/DATA statements and a counter. First,
look at the READIDATA statements.

10 READ N

[~40
HEAD A
30 DATA 4,67,85,79,93

5~
6e GO TO 20

Line 10 assigns 4 to N as a special value. Since the statement


READ N is placed before the loop, this value must be the first item of
data and N is assigned the value only once. The special number tells
the computer how many data items follow. As there are four pieces of
156 PROGRAMMING IN BASIC

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~<------------~

In line 80, the counter is compared to N, which has a value of 4


(assigned to it by the READ statement in line 20) . The loop is per-
formed repeatedly as long as the value of K is not greater than 4
(K= 1,2,3,4). The last time the computer is in the loop, the value of K
is greater than 4, causing control to transfer out of the loop to the END
statement. Notice that while K is less than or equal to 4, control is
transferred to line 30-the READ statement that reads in the next item
of data, and not to line 20, which reads in the number of data items .

5.2 TERMINATING A LOOP-SPECIAL


VALUE-Sample Program
The storage room in a stationery store contains the following items :
10penand pencil sets @ $13 .50each.
10 pads of bond paper @ 1.25 each .
10 pencil erasers @ . 4 5 each .
The program finds the extended value of each of the above articles.
(a) Use the RE AD statement to store the number of different articles
(3) in a simple variable. The variable is used subsequently with a
counter to terminate the loop.
(b) Use another READ statement to enter the unit price of each article.
(c) Use one DATA statement.
(d) Extended Value of each Article = Unit Price x 10

10 LET K=l -Initializes the counter to 1.


20 REAli N - Reads the number of data items.
BRANCHING AND LOOPING II 157

3~ READ F' - Reads the prices one at a time.


40 DATA 3,13.5~,1.25,.45 - First number is assigned to N; prices are
assigned to P.
5111 LET V=F'*1111 - Calculates the extended value of the article.
6111 PRINT - Leaves a blank line.
70 F'RINT "UNIT F'RICE:";F' - Prints the unit price.
80 F'RINT "EXTENDED VALUE:";V - Prints the extended vallue of the article.
9111 LET K=Kt1 -Increments the counter by 1.
11110 IF K>N THEN 999 - Tests the current value of the counter.
(i) If K is greater than N (the number of data items) ,
control is transferred to the END statement.
(ii) If K is not greater than N, the computer
proceeds to the next statement.
11111 GO TO 30 - Transfers control back to line 30.
999 END - Terminates program execution.

RUN
UNIT PRICE! 13.5
EXTENDED VALUE: 135
U~!ITPRICE: 1.25
EXTENDED VALUE: 12.5
UNIT PRICE! .45
EXTENDED VALUE: 4.5

5.2 TERMINATING A LOOP-SPECIAL


VALUE- Your Turn
I. Three depositors have the following balances in their personal
savings accounts:

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

(e) Interest = Bala nce x .10


(f) Balance = Balance + Interest

~1 REM K--COUNTER (NO. OF DEPOSITOR)


~2 REM R--RATE OF INTEREST
~3 REM N--NUMBER OF DEPOSITORS
~4 REM B--BALANCE IN ACCOUNT

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

1. Complete line 50 with a DATA statement.


2. Complete line 70 with a PRINT statement.
3. Which statement should be coded in line 80?

(a) LET B=I*R


(b) LET I =B*R
(c) LET B:::ItR
(d) LET I =BtR
(e) LET R=:Ic-I
BRANCHING AND LOOPING II 159

4. Which statement should be coded in line 90?

(a) LET B =: f~*I


(b) L [- ·1 B:R+I
(c) l.ET I :::B+R
(d) LET I::: B··R
( e) l E1 fJ,=:B+ I

5 . Complete lines 100 and 110 with PRINT statements.


6. Which statement should be coded in line 130?

(a) (Ill TO 999


(b) IF K<N THEN 999
(c) GO TO 3e
(d) IF K>N THEN 999
(e) IF K:>N THEN 3e

7. Complete line 140 with a GO TO statement.

II. Suppose y our 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
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

5.2 TERMINATING A LOOP-SPECIAL


VALUE-Solutions for "Your Turn"
I.
BRAN CHING AND LOOPING II 161

2.70 PRINT 'DEPOSITOR:' ;K, 'BALANCE:';B


3. (b) 80 LET I=B*R
4. (e) 90 LE T £1=£1+ I
5. 1~0 PRINT "INTEREST:';I
110 PRINT "NEW BALANCE:";B
6. (d) 130 IF K)N THEN 999
7. 140 GO TO 40

II.

01 REM R--RATE PER KILOWATT-HOUR


02 REM K--COUNTER (MONTH NO.)
03 REM N--NO. OF MONTHS
04 REM H--KILOWATT-HOURS
05 REM B--ELECTRIC BILL
10 LET R=.035
20 L.ET K==l
30 READ N
4~~ RE~HI H
50 DATA 3,1000,950,930
621 LET B=H*R
713 PRINT
80 PRINT "MONTH:";K
90 PRINT "KILOWATT-HOURS:";H
100 PRINT "ELECTRIC BILL:";B
110 LET K=K+l
120 IF K)N THEN 999
130 GO TO 411'
99'} ENt.

5.3 SETS OF DATA READ IN A LOOP


One of the problems in the "Your Turn" unit of Section 4.3 in Chapter
Four used four DATA statements to supply one READ statement with
numbers which were read in pairs each time the computer passed
through the loop. The statements looked like this.

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

The first number of each pair was assigned to P (the number of


people) and the second number was assigned to F (the social fee)
The number 4 in the last DATA statement terminated the loop by
causing control to transfer to the EN D statement by means of an ON ...
GO TO statement.
The number of DATA statements can be reduced by placing as
many items as possible in one DATA statement. This is illustrated in
the program segment shown below . Notice that the last pair of
numbers has been changed from 4,85 to -1,(& .

HI READ P,F
2~ DATA 1,150,2,275,3,40~,-1,B
3~
4~
50
60 GO TO 1~
99 END

How is an item of data assigned to its respective variable? Here is


how it is done, using the above program segment as an example.

The first time through the loop


~ isassignedtoP READ P,F
150isassignedtoF DATA (1,15~),2,275,3,4~~,-1,0
The next time through the loop
2 is assigned to P READ F', F
275isassignedtoF DATA 1d5~,(2,275),3,41110,-1,0
The next time through the loop
3 is assigned to P READ p, F
400isassignedtoF DATA 1,1511"2,275,(3,41110),-1,0
The last time through the loop
-1 isass'i gnedtoP READ P,F
0isassignedtoF DATA 1d5i~"2,275,3'4111111+1'11I)

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

If -1 has been assigned to P, control is transferred to the END


statement. Although only one number of the set is used in the IFfTHEN
statement, there must be two numbers in the set, since the RE A D
statement lists two variables and both variables must be assigned
values. This last set of numbers is often called a dummy set , as the
numbers are never utilized in calculations. In fact, the number used to
detect the end of input data is actually the trailer value or flag you
learned about in Section 5.1 , where a number consisting of a series of
nines was used as the flag.
Listed below are a few rules you should remember.

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.

5.3 SETS OF DATA READ IN A LOOP-


Sample Program
Programs entering sets of data may have their loops controlled by any
of the methods shown so far; that is, by a counter, a special value, a
trailer value, a test on each data item, or by using an ON .. . GO TO
statement. The last program segment used a trailer value (a flag) of
- 1 . Here is a program that uses an ON . . ,GO TO statement.
The salespersons of the XYZ Shoe Company are each paid a
commission based on the amount of their sales. The company has
computerized its payroll and uses codes to identify sales amounts .
The program finds the amount of commission for each of three
salespersons whose respective sales are $350, $290, and $467 . The
company uses the following codes:

Amount of Sale Code Rate of Commission


Less than $300 1 10%
$300 to $399.99 2 12%
$400 to $499.99 3 15%
164 PROGRAMMING IN BASIC

(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.

a1 REM K--CODE (INDEX)


k12 REM S- --SALES
03 REM R--RATE
04 REM C--COMMISSION

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.

5.3 SETS OF DATA READ IN A LOOP


- Your Turn
1. A retailer receives a discount from a wholesaler , depending upon
the number of articles purchased. The retailer's Accounts Pay-
able has been computerized and codes have been assigned as
follows .

Number of Articles Code Rate of Discount


Less than 100 1 6%
100 to 199 2 8%
200 to 299 3 10%

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.

(a) Use the READ/DATA statements to enter the number of arti-


cles and the code for each purchase .
(b) Use an ON . . . GO TO statement to branch to the statements
that assign the appropriate rates of discount and to branch to
the END statement.

01 REM N--NUMBER OF ARTICLES


02 REM K--CODE (INDEX)
"3 REM R--RATE
166 PR OG RAMM IN G IN BAS IC

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

Refer to the preceding program to answer the following ques-


tions.
(a) What values are assigned to the variable K during execution
of the program ?
(b) Expla in how the various rates are assigned to R.
(c) What would be the output if lines 50 and 70 were omitted?
(d) How is the program terminated?
(e) What is wrong with the following DATA statement , if this
statement is used instead of the one shown in the program?
How does it affect execution of the program on your com-
puter?

2. What is wrong with the following program? Make the necessary


corrections.

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

3. What is the output of the following program?

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

4. Rewrite the program for Problem 1 so that your modified program


calculates the amount of discount and the net cost of each
purchase . The gross costs are recorded below .

Number of Articles Purchased Gross Cost


250 $500
60 120
140 280
(a) Use the READ /DATA statements to enter the number of arti-
cles , the gross cost, and the code for each purchase. Do not
use more than two DATA statements .
(b) Use an ON . .. GO TO statement to branch to the statements
that assign the appropriate rates of discount and to branch to
the END statement.
(c) Use a code of 4 to terminate your loop.
(d) Discount = Gross Cost x Rate of Discount
(e) Net Cost = Gross Cost - Discount
168 PROGRAMMING IN BASIC

(f) Remember to draw a flowchart for your program. Your


flowchart should be similar to the one in Chapter Four on
page 129. The following changes are required :

(i) You should have only one READ statement.


(ii) Each branch , except the one to the END, should lead to a
different process symbol to assign a different rate of
discount to the same variable . Logic then converges from
these sy mbols to one process symbol which depicts the
calculation of the discount and the calculation of the net
cost. This is followed by the output figure.

HUN

NO. OF ARTICLES: 25~


GROSS COST: 5BB
RATE OF DISCOUNT: .1
AMOUNT OF DISCOUNT: S0
NET COST: 45111

NO. OF ARTICLES: 6B
GfWSS COST: 12111
RATE OF DISCOUNT: .1216
AMOUNT OF DISCOUNT: 7.2
NET COST: 112.8

NO. OF ARTICLES: 140


GROSS COST: 28111
RATE OF DISCOUNT: .08
AMOUNT OF DISCOUNT: 22.4
NET COST: 257.6

5.3 SETS OF DATA READ IN A


LOOP - Solutions for "Your Turn"
1. (a) K= 3, 1, 2, 4
(b) IntheoN . .. GOTostatement:
When K is equal to 3 , control is transferred to statement
number 80, which assigns .10 to R.
When K is equal to 1, control is transferred to statement
number 40 , which assigns .06 to R.
When K is equal to 2, control is transferred to statement
number 60, which assigns .08 to R.
When K is equal to 4, control is transferred to line 999 , whic h
is the END statement.
BRANCHING AND LOOPING II 169

(c) RUN

NO. OF ARTICLES: 250


RATE OF DISCOUNT: .1

NO. OF ARTICLES: 60
RATE OF DISCOUNT: .1

NO. OF ARTICLES: 140


f.:ATE OF DISCOUNT: .1

(d) The program terminates when the READ statement assigns 4


to K and control is transferred to the fourth number listed in
the ON . GO TO statement. This is line number 999 , which is
the END statement.
(e) The first two numbers in the DATA statement are in reverse
order . The value of the index is 250, which is out of the range
of the numbers listed in the ON ... GO TO statement. Depend-
ing on your computer system , one of the following may
occur.
1 . Execution stops and the computer gives an error mes-
sage.
2. The ON . .. GO TO statement is ignored and the statement
following the ON ... GOTO is executed.
3. Control is transferred to the last number on the list.

2. Line 50 is never executed as this statement number is not listed


in the ON ... GO TO statement. There should be four statement
numbers in the ON . GO TO statement and four sets of data in the
DATA statement (two numbers in each set) . The two statements
should be changed to the following.

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.

01 REM N---NUMBER OF ARTICLES


£12 F.:EM G--GROS5 COST
213 r~EM K---CODE (INDEX)
214 r,[M R-- --FMTE
05 F:EM B--- Drs C 0 UN T
06 REM C- --NET COST

1£1 HEAD N,G,K


2~ DATA 25£1,500,3,621,120,1,14£1,280,2
:~£1 DATA 0,0,4
4£1 ON K GO TO 50,70,9£1,999
50 LET ·R=.£I6
6£1 GO TO 100
7£1 LET R==.218
821 GO TO HHl
921 LET R=.l£1
10F.1 LET D=G*R
:1.1.0 LET C=G-[I
12£1 PRINT
13£1 PRINT 'NO. OF ARTICLES:";N
14£1 PRINT 'GROSS C05T:";G
150 PRINT "RATE OF DI5COUNT:";R
16£1 PRINT 'AMOUNT OF DI5COUNT:";D
1721 PRINT 'NET C05T:";C
18£1 GO TO 1£1
999 END

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

1.0 LET S:::~ -Initializes the sum (subtotal) to zero.

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 .

UH" GO TO 4~ - Transfers control back to line 40 to read the next number.

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.

5.4 SUMMATION-Sample Program


As mentioned in Chapter Four on page 118, a loop may be terminated
by transferring control to a statement that starts a new routine . This
feature will now be combined with the summation concept you have
just learned. The program shown below finds the average of the four
numbers 67,85,79, and 93. 2 Instead of transferring control to the END
statement (when summation is complete) , the computer branches to
the statement that finds the average. Two PRINT statements and the
END statement complete the program. Its output includes the
numbers and the accumulated sums.
(a) Use the READ statement to store the number of numbers in a
simple variable. The variable is used subsequently with a counter
to branch to the statement that finds the average.
(b) Use another READ statement to enter the numbers.
(c) Use one DATA statement.
Sum of Numbers
(d) Average = "Number" of Numbers

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

10 PRINT - Leaves a blank line .


20 LET K=l -Initializes the counter to 1.
30 LET 5=-"0 -Initializes the sum (subtotal) to zero.
4e REAli Nl - Reads the number of values (4) .
5£1 f;:EAlI N - Reads the numbers one at a time .
60 DATA 4,67,85,79,93 - Supplies the READ statements with the number
of values and the numbers themselves .
70 LET S=StN - Adds the subtotal to the current number and
assigns the result back to S .
SB PRINT N,5 - Prints the current number and the subtotal.
90 LET 1(=l(tl -Increments the counter by 1.
100 IF I(>N1 THEN 120 - Tests the current value of the counter .
(i) If K is greater than N1 (4), control is
transferred to line 120 to find the average .
(ii) If K is not greater than N1 , the computer
proceeds to the next statement to resume
the reading of numbers .
110 GO TO 50 - Transfers control back to line 50 .
120 LET A=S/N1 - Finds the average .
1:.30 PRINT - Leaves a blank line .
140 PRINT "THE AVERAGE IS:";A - Prints the average .
999 END - Terminates program execution

RUN

67 67
85 152
79 231
93 324

THE AVERAGE IS: 81

5.4 8U MMATION - Your Turn


1. Identi fy the errors in the program segments shown below . Make
the necessary co rre ctio ns .

(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

2. What is the output of each of the following programs?

(a) Hl PRINT (b) 1e PRINT


2e LET S=0 2e READ D
30 READ D 3.0 DATA 1.0,2.0,321,99999
4£1DATA 10,221,3£1,99999 4£1 LET S=0
5.0IF D=99999 THEN 99 5£1 IF D=99999 THEN 99
6e LET S=StD 6e LET S=S+D
7~ F'RINT D,S 70 PRINT D,S
S0 GO TO 3£1 8£1 GO TO 2.0
99 END 99 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

WEEK 1 40.00 4.0.0.0


WEEK 2 38.021 78BB
WEEK 3 44.0£1 122.021
WEEK 4 46.00 1682121

TOTAL SALES: 16SBe


COMMISSION: 252.0
174 PROGRAMMING IN BAS IC

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

5.4 SUMMATION-Solutions for "Your Turn"


1. (a) S reverts to zero each time the computer executes the loop,
since S is initialized inside the loop. The GO TO statement
should transfer control to line 60 rather than to line 50 . S
would now be initialized outside the loop.

:~~ LET 5'..:0

C
6~ RU~D D
70 DArA 10,20,30
80 LET 5=5+[1

1 HI GO TO 6a

999 END

(b) There is insufficient data in the DATA statement. READ N


assigns the number 6 to the variable N, which means that
there should be six items of data. Either change the number
of items to three or add three more items in the DATA
statement.

(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.

(a) RUN (b) RUN

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

5.5 A WAGE PROGRAM


The program in Chapter Three calculated an employee's earnings
based on the number of hours worked and the hourly rate of pay.
Deductions were made for income tax, union dues, and a registered
pension plan. In order to incorporate some of the concepts that you
learned in the last two chapters, the program below is written for three
employees whose regu la r work week is 39 hours. The y are paid
time-and-a-half for overtime. Here is the data you will need for the
program .

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

(a) The READ/ DATA statements are used


- To assign a special number to a variable that represents the
number of employees . This variable is used subsequently with a
counter to te rm inate the loop .
- To input data (hours, rates , and deductions) .
(b) Remarks are placed in strategic spots to help you understand the
program.
BRAN CHING AND LOOPING II 177

(c) Blank lines have been inserted only for clarity.


(d) Calculations
1. Gross Pa y (no overtime) = Regular Hours x Regular Rate
2. Gross Pay with overtime:
- Overtime Hours = Regular Hours - 39
- Overtime Rate = Regular Rate x 1.5
- Overtime Pay = Overtime Hours x Overtime Rate
- Gross Pay (with overtime) = 39 x Regular Rate + Over-
time Pay
3. Net Pay:
- Total Deductions = Income Tax Deduction + Union Dues
+ Pension Deduction
- Net Pay = Gross Pay - Total Deductions

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 .

13 REM N--NET F'AY

100 f,EM SET UP A COUNTER


105 LET K=1

2[10 REM READ/DATA STATEMENTS


20~i REM READ NO. OF EMPLOYEES
21£1 READ N1
215 [I(~ TA 3
220 REM READ HOURS, RATE, DEDUCTIONS
225 READ H,R,I,U,P
23~ DATA 44,10.24,80,2,3
235 DATA 37,11.54,75,2,2.50
240 DATA 39d2.34,90,2,4
3[10 REM CHECK FOR OVERTIME
305 IF H>39 THEN 500
400 REM GROSS PAY--NO OVERTIME
405 LET H1=0
41t'l LET R1 ==0
415 LET V=0
420 LET G=H*R
425 GO TO 600
178 PR OG RAMMI NG IN BAS IC

~.:j00 REM GROSS PAY--WITH O'VERT IME


505 LET Hl=H-39
~S 10 LET Rl=R*1.5
515 LET V=Hl*R1
521:1 LET G=39*RtV

600 REM NET PAY


605 LET II=ItUtP
611?1 LET N=G ·- II

7~0 REM PRINT STATEMENTS


705 PRINT
710 PRINT "EMPLOYEE";K,"HRS";H,"RATE";R
715 PRINT "OVERTIME HOURS";Hl
720 PRINT "OVERTIME RATE";Rl
725 PRINT "OVERTIME PAY";V
73~ PRINT "GROSS PAY";G
735 PRINT "INCOME TAX";I
740 PRINT ·UNION DUES";U
745 PRINT "PENSION";P
750 PRINT "TOTAL IIEDUCTIONS";II
755 PRINT "NET PAY";N
800 REM CHECK FOR LAST DATA ITEM
B05 LET K=Ktl
810 IF K)Nl THEN 999
815 GO TO 225

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
- - -- ---.,.-- -

BRANCHING AND LOOPING II 179

UI'H ON DUES 2
PENSION 2.5
TOTAL DEDUCTIONS 79.5
NET PAY 347.48

EMPLOYEE 3 HRS 39 RATE 12.34


OVERTIME HOURS B
OVERTIME RATE B
OVERTIME PAY 0
GfWSS PAY 481.26
INCOME TAX 91i'J
UNION DUES 2
PENSION 4
TOTAL DEDUCTIONS 96
NET PAY 385.26

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

Gross Pay Gross Pay


- No Overtime -with Overtime
H1=0 H1=H-39
R1 =0 R1=R*1 .5
V=(/J V= H1 *R1
G=H*R G= 39*R+ V
Increment
Counter
K= K+ 1
Net Pay
0= 1+ U+ P
N=G-D

C~End)
[I] No

Print
Blank line
~
K,H,R
H1
R1

1. Which two statements enter the number of employees into the


computer?

*****************************************
2UI READ N1
215 DATA 3

2. Which statement compares the above variable with a counter?

*****************************************
810 IF K)N1 THEN 999
BRANCHING AND LOOPING II 181

3. Which statement checks for overtime?

*****************************************
305 IF H) 39 THEN 5e~

4 . If the above statement is true , which rout ine calculates the


overtime?

*****************************************
The statements in the 500 range .

5. Which statement finds the overtime rate?

*****************************************
510 LET Rl=R:*1.5

6. Which statement finds the gross pay without overtime? With


overtime?

*****************************************
420 LET G=H*R
52~ LET G=39*RtV

7. Which statement transfers control back to the READ statement to


read more data?

*****************************************
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-

A special number which denotes the number of data items is


assigned to a variable (N). As in Program 1, a counter keeps track of
the data. As long as the value of the counter is less than or equal to
that of the variable storing the number of items (4), execution of the
loop continues. The loop ends once the value of the counter is greater
than that of the variable (N).

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~<-----------------~

A trailer value (some illogical number in relation to the program) is


entered as the last item of data. Each time a data item is entered, it is
BRANCHING AND LOO PIN G II 183

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

[!: IF A>40 THEN 9 9 -


PRINT A
50 LET A=At10
60 GO TO 30
99 END ~

Data that increases (or decreases) by equal amounts can be checked


to determine whether or not the final value has bee n reached. In the
above program , execution co ntinu es until the increment causes a
result that is greater than the final value requ ired in the program . At
this point, loopin g terminates.

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

The ON .. . GO TO statement uses an index as a code to transfer control


to one of several statements in its list. One of the values of the index
causes control to transfer to a statement outside the loop , thereby
terminating the loop . In the above program , a code of 4 transfers
control to the END statement.
Sets of data items, consisting of two or more values in a set , may be
coded in one DATA statement. Each time the computer passes
through the loop, consecutivesets of data are assigned to the same
variables.
The summation of numbers can be accomplished by accumulating
the sum in a variable. The addition is performed within a loop . With
each pass through the loop , another number is added to the subtotal.
The variable that accumulates this sum should first be initialized to
zero outside the loop.
184 PROG RAMMI NG IN BASIC

Questions and Exercises


1. What is the purpose of a trailer value (a flag)?
2 Complete lines 30 and 40 so that the program terminates by
means of a trailer value.

1~ PRINT
2fJREAD A
30 [lATA
40
~:ifl PRINT A
6£1 GO TO 20
fl9 END

FWN
r)

"'"
4
6

3. The following program counts the number of data items (exclud-


ing the trailer value) . Fill in the missing lines .

U1
2') READ A
30 DATA 40,50,60,-1
4£1
5£1LET 1<=1<+1
60
70 PRINT
80
99 END

RUN

(i) Which statement should be coded in line 10?

(a) LET 1<=0


(b) LET 1<=1
(c) LET K-'1
-,,-
(d) l.ET 1<=-1
( e) l.ET A=:-1
BRAN C HING AND LOOPING II 185

(ii) Which statement should be coded in line 40?

(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

(iii) Complete line 60 with a GO TO statement.


4. Complete line 80 with a PRINT statement.
(a) Summarize the procedure followed by the computer during
execution of the READ/DATA statements in the program seg-
ment shown below .

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

(b) A counter is often incorporated in a program in order to


terminate a loop. What three statements must be added to
the above program segment so that the loop will be term i-
nated? Explain how these statements are executed .
5 . Refer to the program shown below to answer the following
questions.
(a) Explain how data is assigned to variables A and B each time
the computer goes through the loop.
(b) What is the purpose of the last set of numbers? Wh y must
there be two numbers in this set?
(c) What is the output of the program?

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

enter the numbers and a trailer value to terminate the loop.


Explain each step the computer takes during summation.

RUN

10 10
2£1 3£1
30 6£1
40 1£10

7. What is wrong with each of the following program segments?


Make the necessary corrections.

(a) This program is to add the (c)


numbers 39, 84, and 26. 30 REA{I A
Assume that control trans- 40 {lATA 39,84,26
fers out of the loop . 50 IF A=99999 THEN 999

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) 01 REM N--NO. OF [lATA ITEMS


£12 REM {I--DATA ITEM

3£1 LET K=l


4£1 READ N
5£1 READ {I
6£1 DATA 3,39,84,26

12£1 LET K=Kt1


130 IF K)N THEN 999
14£1 GO TO 4£1
(?99 END
- -- - - - - - - -- - -- - - - - - -.------ -

BRANCHING AND LOOPING II 187

8. What is the output of each of the following programs?

(a) a1 PRINT (c) 1£'1 PRINT


2£'1 READ A 2£'1 READ A,B
30 DATA 1,2,3,-1 30 DATA 1,1£'10,2,2£'1£'1,3,3£'1£'1,4,99999
4£'1 LET T=£'I 4£'1 IF B=99999 THEN 99
5£'1 IF A=-l THEN 99 5£'1 LET C=B/A
6£'1 LET T=TtA 60 PRINT B,C
7£'1 PRINT A,T 70 GO TO 20
8£'1 GO TO 20 99 END
99 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

9. During execution of the following program, the computer informs


you that there is insufficient data. Rewrite this program in four
different ways, each version using one of the methods listed
below to terminate input.

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

NO. OF PARTS 43 SUBTOTAL 43


NO. OF PARTS 42 SUBTOTAL 85
NO. OF PARTS 45 SUBTOTAL 130
NO. OF PARTS 43 SUBTOTAL 173
NO. OF PARTS 40 SUBTOTAL 213

TOTAL NO. OF PARTS: 213


RATE: 2
INCOME: 426

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

2. Using a code of 1 to indicate TRUE and a code of 2 to indicate


FALSE, write a program that finds the number of TRUE answers
and the number of FALSE answers on a questionnaire that
consists of 20 questions. Initialize a variable, say T, to zero. If an
answer is TRUE , increment this variable by 1.

xx LET T=Ttl

3. "xx" denotes a statement number .


190 PROG RAMMING IN BASI C

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

(a) Use the RE AD statement to store the number of answers in a


simple variable . The variable is used subsequently with a
counter to terminate the loop.
(b) Use another REA D statement to enter the data.
(c) Use an ON ... GO TO statement for branching .
BRANCHING AND LOOPING II 191

RUN

NO. OF TRUE ANSWERS: 12


NO. OF FALSE ANSWERS: 8

3 . From the information recorded below, find:


(i) The extended cost of each item .
(ii) 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 INPUT statement to enter the quantity and the unit
price of each item.
(b) Use a trailer value to terminate your loop.
(c) Extended Cost of Each Item = Quantity x Unit Price
(d) Total Cost = Total Cost + Extended Cost of Each Item

Using the INPUT Statement Using the READ/DATA Statements

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

4. Write a program that counts the number of one-dollar bills, five-


dollar bills, and ten-dollar bills deposited in a bank account. The
bills deposited are:
5,10 ,1,5,1,10,5,1,10,1 ,1,5,10,1,1,10,20,5,1 ,5,1.
(a) Use the READ/ DATA statements to enter the data.
(b) Use a trailer value to terminate your loop .
(c) Use IFITHEN statements to determine the denomination of
each bill.
192 PROGRAMMING IN BASIC

(d) Your program should check for the deposit of a different


denomination of bill . This is shown in the flowchart. If the
results of all the IFiTHEN tests are false (because a bill other
than a 1, a 5, or a 10 is deposited), control should be
transferred to the READ statement.

FWN

NO. OF ONE-DOLLAR BILLS: 9


NO. OF FIVE-DOLLAR BILLS: 6
NO. OF TEN-DOLLAR BILLS: 5

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.

Using the INPUT Statement Using the READ/DATA Statements

RUN RUN

')ALUE FOR N? 1 NO. OF POSITIVE NUMBERS: 3


VALUE FOR N? -2 SUM OF POSITIVE NUMBERS: 9
l.,.'ALUE FOR N? 3
VAL.UE FOR N? -4
VALUE FOR N? 5

NO. OF POSITIVE NUMBERS: 3


SUM OF POSITIVE NUMBERS: 9

6. In Chapter Three (Page 106), you were asked to write a program


to convert a Fahrenheit degree to a Celsius degree. Write a
program that converts the following five Fahrenheit degrees to
Celsius degrees.

(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

FAHRENHE I T: 5'='1 CELSIUS: 1'='1


FAHRENHEIT: 59 CELSIUS: 15
FAHRENHEIT! 68 CELSIUS: 20
FAHRENHEIT: 77 CELSIUS: 25
FAHRENHEIT: 86 CELSIUS: 30
194 PROGRAMMING IN BASIC

7. On July 1, your bank account showed a balance of $1 000. During


the month you made the following deposits and withdrawals:
July 1 balance $1000
10 withdrawal 80
15 deposit 450
23 withdrawal 100
31 deposit 450
Write a program that calculates the balance of your bank account
after each transaction.
(a) Initialize a variable to the July 1 balance .
(b) Use a code of 1 for a deposit, a code of 2 for a withdrawal, and
a code of 3 to terminate your loop.
(c) Use the READ/ DATA statements to enter the code and the
amount of each transaction . Use one DATA statement.
(d) Use an ON .. . GO TO statement for multiple branching .
(e) Depending on your code:
Balance = Balance + Deposit
or
Balance = Balance - Withdrawal

FWN

AMOUNT: 80 BALANCE: 929


AMOUNT: 450 BALANCE: 1370
AMOUNT: 190 BALANCE: 1279
AMOUNT: 450 BALANCE: 1729
195

SIX FORI NEXT LOOPS


A. After completing this chapter, you should be able to write BASIC
programs and complete skeletal BASIC programs that use:
1. Single FOR/NE XT loops.
2. Nested FOR/ NEXT loops .
3. PRINT statements to counteract commas or semicolons at the
end of previous PRINT statements.
4. PRINT statements that leave blank lines between specific rows
of output.
B. In addition, you should be able to:
1. Display and label a FOR statement.
2. State the purpose of each part of a FOR statement.
3. State the purpose of the NEXT statement.
4. Explain the execution of a FOR /NEXT loop .
5. Make corrections to:
(a) Invalid FOR statements.
(b) Invalid program segments using FOR/NEXT loops.
(c) Invalid program segments using nested FOR /NEXT loops.
6. Determine how many times a FOR/NEXT loop is executed
when:
(a) The initial value and the test value are the same, and the
step value is any number.
(b) The test value is greater than the initial value and the step
value is zero or negative.
(c) The test value is less than the initial value and the step
value is zero or positive .
7. Determine the value of the index after a FOR /NE XT loop is
complete.
8. Calculate the number of times
(a) A FOR/NEXT loop is executed.
(b) An inner FOR/ NEXT loop is executed.
9. State the values the index takes on in a FOR statement.
10. Complete a FOR statement.
11 . Explain what is meant by a nested loop.
12. Determine the output of programs.

6.1 GENERAL FORM


In Chapter Four, a loop was set up and controlled by the use of a
counter. There is another way to generate and control a loop, one that
is powerful and flexible yet simple and convenient to use . It is called a
FOR/NEXT loop and its general form looks like this.

10
20 FOR 1=1 TO 3 STEP 1
196 PROGRAMMING IN BASIC

3~
4~
5~ NEXT I
60

Two statements control a FOR/ NE XT loop. The FOR statement sets


up the loop and the NE XT statement marks the end of the loop. The two
statements always work together. All statements between these two
are said to be inside the loop. This means that statements 30 and 40
are executed each time the computer passes through the loop. When
looping is complete, control transfers to the statement immediately
following the NEXT statement.

The FOR Statement


Index Initial Test Step

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.

The NEXT Statement

5~ NEXT I

The NEXT statement instructs the computer to increment or decre-


ment the index (I) by the value indicated in the STEP clause, and then
to branch back to the beginning of the loop . This makes it essential
that the variable in the NEXT statement be the same as the index in the
corresponding FOR statement.
Here are the steps the computer takes when executing a FOR/ NE XT
loop. The program segment on page 195-96 will be used in the
discussion. As you read the steps listed below, try and trace the
computer 's path by following the arrows drawn in the program seg-
ment. Do this several times to make sure you understand the proce-
dure.
FOR/ NEXT LOOPS 197

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

1. In line 20, 1 is assigned a value of 1. 1= 1.


2 . Statements 30 and 40 are executed.
3. The statement NEXT 1 in line 50 instructs the computer to
increment 1by 1 (STEP 1).1 = 2. Control is transferred back to line
20.
4. The computer checks to see if 1is greater than 3. Since 1= 2 and 2
is not greater than 3, statements 30 and 40 are executed.
5. The statement NEXT 1 in line 50 instructs the computer to
increment 1 by 1 (STEP 1).1 = 3. Control is transferred back to line
20.
6. The computer checks to see if 1is greater than 3. Since 1= 3 and 3
is not greater than 3, statements 30 and 40 are executed.
7. The statement NEXT 1 in line 50 instructs the computer to
increment 1by 1 (STEP 1) .1= 4. Control is transferred back to line
20.
8 . The computer checks to see if 1is greater than 3. Since 1= 4 and 4
is greater than 3, control is transferred to the statement immedi-
ately after the NE XT statement, skipping those instructions inside
the loop. The FOR/NEXT loop is now terminated.
Shown below is a comparison of a program segment that controls a
loop by the use of a FOR/NEXT loop with one that uses a counter.

(a) Using a Counter (b) Using a FOR/NEXT Loop

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

The NEXT statement, in conjunction with the STEP value, increments


(increases) I by 1. (This replaces line 150.)
The NEXT statement replaces line 170. The result is a program that
not only has fewer statements but clearly defines the beginning and
the ending of a loop .
There are a number of rules that must be observed when using
FOR/NEXT statements . They are not difficult to learn , and once
mastered, they are very easy to follow. Examples will be used to make
sure you understand each rule as it is presented .

1. The index must be a simple numeric variable which takes on a


number of numeric values.

20 FOR 1=1 TO 3 STEP 1

I takes on the value 1, then 2, then 3, and finally 4. Once I is set at


4, its value is greater than the test value and control is transferred
to the statement immediately after the loop. This means that the
loop is executed three times - when 1= 1 ,2, and 3. There is a
formula to calculate the number of times a loop is performed. Its
general form is as follows .

Where n, = the initial value


n2 = the test value
n3 = the step value

Applying the formula to the FOR statement above gives 3 as the


result.

20 FOR 1=1 TO 3 STEP 1


iii

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

3. There may be any number of statements inside the loop with a


minimum of one. In the above example, there are two statements
-lines 30 and 40.
4. If the step clause is omitted, the computer uses 1 as the step
value . In other words , the step value is assigned the number 1 by
default.

20 FOR 1=1 TO 3

5. The index may be used in a statement inside the loop . However,


some versions of BASIC explicitly disallow the index to be altered
within the loop, regardless whether it's done by a READ state-
ment, an INPUT statement, or a LET statement. Others allow the
index to be changed, but this change may interfere with the
automatic incrementing (or decrementing) as specified in the
STEP clause. What does your computer print when you RUN the
following program?

10 FOR 1=1 TO 7 STEP 1


20 PRINT I
30 LE T 1= 1 +2 ( Index altered
40 PRINT "ALTERED I =";1
5£1 NEXT I
99 END

6. It is possible to transfer out of a FOR /NEXT loop before it has


reached its limit by using a GO TO, an IFITHEN, or an ON . .. GO TO ,
but it is not possible to transfer to a statement within a FOR/NEXT
loop . In other words, the only entry into a FOR/NE XT loop is by
means of the FOR statement.

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

(a) Step value is positive (c) Step value is negative

UI FOR 1=1 TO 1 STEP 1 10 FOR 1=1 TO 1 STEP -1


221 PRINT I 221 PRINT I
321 NEXT I 30 NEXT I
99 END 99 END

(b) Step value is zero

UI FOR 1=1 TO 1 STEP 0


221 PRINT I
321 NEXT I
9(? END

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.

(a) Step value is zero (b) Step value is negative

10 FOR 1=1 TO Ie STEP 0 10 FOR 1=1 TO 121 STEP -1


221 PRINT I 221 PRINT I
321 NEXT I 30 NEXT I
99 END 99 END

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.

(a) Step value is zero (b) Step value is positive

HI FOR 1=10 TO 1 STEP 0 10 FOR 1=10 TO 1 STEP 1


20 PRINT I 20 PRINT I
30 NEXT I 321 NEXT I
99 END 99 END

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

I has a value of 4 when the FOR/NEXT loop is complete. On some


computers , the value of I remains at 4; on others it reverts to 3. In
the event that you may want to use the index after a loop, you
should know what value the index takes on in your computer
system when a loop is complete . RUN the following program.
What is the value of I when it is printed outside the loop?

10 FOR 1=1 TO 3 STEP 1


20 PRINT I
30 NEXT I
40 PRINT ·VALUE OF I OUTSIDE LOOP:";I
99 END

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 .

10 FOR 1=1 TO 10 STEP 1


20 LET J=IT2}
30 f'R I NT I, ~J ~ Indented
40 NEXT I
99 END

6,1 GENERAL FORM-Sample Program


A sample program in Chapter Five on page 171 found the average of
four numbers. A special value was read to indicate the number of
numbers that were to be averaged. This special value was then
compared with a counter to terminate input. In this program, a
FOR/NEXT loop will be used to control the entering of data . Here is the
problem once more .
Find the average of the four numbers 67 , 85, 79, 93. Print each
number currently added along with the accumulated sum.
202 PROGRAMMING IN BASIC

(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

HI PRINT - Leaves a blank line .


20 LET S=fl -Initializes the sum to 0.
3B FOR 1=1 TO 4 STEP 1 - Sets up a loop .
4B REAli N - Reads the numbers one at a time.
50 DATA 67,85,79,93 - Supplies the READ statement with the numbers.
6e LET S=StN - Accumulates the sum of the numbers .
7B PRINT N,S - Prints the number and the accumulated sum .
80 NEXT I - Transfers control to line 30 .
90 LET A=S/4 - Finds the average.
1130 PRINT - Leaves a blank line.
110 PRINT "THE AVERAGE IS:";A - Prints the average.
999 END - Terminates program execution.

RUN

67 67
85 152
79 231
93 324
THE AVERAGE IS: 81

6.1 GENERAL FORM- Your Turn


I. A retailer is allowed a cash discount of 2% if the store's accounts
are paid within 10 days . Suppose the retailer takes advantage of
this cash discount when three accounts with balances of $450,
$600, and $240 are cleared. Find the discount and the amount
remitted (paid) on each account.
(a) Use a FOR/NE XT loop to keep track of the accounts.
(b) Use the RE AD/DATA statements to enter the balance of each
account.
(c) Discount = Balance x .02
(d) Amount Remitted = Balance - Discount
(e) Fill in the missing lines.

~1 REM I--INIIEX (NO. OF ACCOUNT)


02 REM B--BALANCE IN ACCOUNT
03 REM D--I1ISCOUNT
134 REM R--AMOUNT REMITTED
FOR/NEXT LOOPS 203

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

I INDEX (NO. OF THE EOUIPMENT) I INDEX (NO. OF THE EOUIPMENT)


S SALES PRICE S - SALES PRICE
C COMMISSION C - COMMISSION

)
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 .

1 . Which statement should be coded in line 10?

(a) FOR I=B TO II STEP R


(b) FOR I=R TO II
(c) FOR 1=1 TO 3 STEP 2
(d) FOR 1=1 TO 3
(e) FOR 1=3 TO 1

2. Complete line 30 with a DATA statement.


3. Which statement should be coded in line 50?

(a) LET B=R-D


(b) LET R:::B - [I
(c) LET [I=B-R
(d) LET R::BtD
(e) L.ET B=DtR
FO R/ NEXT LOOPS 20!
/
4. Which sta ~ ment shou ld be coded in li ne 70?

(a) I:' f~ I NT "ACCOUNT:·;A


(b) F'~U NT ·ACCOUNT:· ;B
(c) PF~!NT ·ACCOUNT·;!
(d) PRINT • ACCOUNT: • ; R
(e) F'I:;:INT • ACCOUNT: • ; I

5 . Complete lines 80, 90 , and 100 with PRINT statements.


6. Which statement should be coded in li ne 11 O?

(a) NEXT 1'";


(b) NEXT=I
(c) NEXT 3
(d) iI/EXT I
(e) GO TO 10

II. A salesperson sold three pieces of equipment, the first for


$1200, the second for $1500, and the third for $1300. If 10%
commission based on sales is received, what commission does
the salesperson receive on each piece of equipment sold?
(a) Use a FOR/NEXT loop to keep track of the input (each piece of
equipment).
(b) Use an INPUT statement to enter the sales price . If you are
not using an interactive system , use the READ/ DATA state-
ments .
(c) Print the number of the equipment (first, second, or third) .
(d) Commission = Sales Price x .10
(e) No standardized symbols mark the beginning and the end-
ing of a FOR/ NEXT loop . In the flowcharts shown, the prepara-
tion symbol is used to represent the FOR statement and the
process symbol is used to represent the NEXT statement. In
both flowcharts , logic flows from the FOR statement to the
NE XT statement and then back to the FOR , as long as I is less
than or equal to 3 . When I is greater than 3 , control is
transferred to the END statement .

Using the INPUT Statement Using the READ/DATA Statements

RUN RUN

EQUIPMENT: 1 EQU I PMENT: 1


SALES PRICE~ 1200 SALES PRICE: 1200
COMMISSION: 120 COMMISSION: 120

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

6.1 GENERAL FORM-Solutions for "Your


Turn"
I.

1. (d) 10 FOR 1=1 TO 3


2. 30 DATA 450,6~0,24~
3. (b) 50 LET R=B-D
4. (e) 70 PRINT "ACCOUNT:"; I
5. 8~ PRINT "BALANCE:";E!
9~ PRINT "DISCOUNT:";D
10~ PRINT "AMOUNT REMITTED:";R
6. (d) 1.111J NEXT I

II . Using the INPUT Statement

01 REM I--INDEX (NO. OF THE EQUIPMENT)


~2 REM S--SALES PRICE
03 REM C--COMMISSION
1~ FOR 1=1 TO 3 STEP 1
20 PRINT
30 PRINT "EQUIPMENT:";I
40 PRINT TSALES PRICE";
5~ INPUT S
60 LET C=S*.l~
70 PRINT 'COMMISSION:";C
80 NEXT I
99 END

Using the READ/DATA Statements

a1 REM I--INDEX (NO. OF THE EQUIPMENT)


02 REM S--SALES PRICE
03 REM C--COMMISSION
FOR/ NE XT LOOPS 207

10 FOR 1=1 TO 3 STEP 1


20 READ S
30 DATA 12~0,1500,1300
40 LET C=S*.10
50 PRINT
60 PRINT "EQUIPMENT:";I
70 PRINT "SALES PRICE:";S
B0 PRINT "COMMISSION:";C
90 NEXT I
99 END

6.2 VARIATIONS-INITIAL VALUE AND TEST


VALUE
The initial value and the test value need not always be written as in
Section 6.1. There are a number of variations in their codings which
give greater flexibility to the writing of programs.
I. The initial value and the test value may be represented by
variables that have been assigned values prior to their use in the
FOR statement. On many computer systems, these variables
must be different than the index. Some versions of BASIC do not
allow the initial value and/or the test value to be altered inside the
loop. What does your computer print when you RUN the following
programs?

1. Initial value changed within the loop

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

2. Test value changed within the loop

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 .

1~ FOR 1=5 TO 8 STEP 1


40 FOR 1=.5 TO 8.5 STEP 1
30 FOR 1=0 TO l~ STEP 1
6~ FOR 1=-4 TO 0 STEP 1
50 FOR 1=-8.5 TO -1.5 STEP 1

Some versions of BASIC will truncate a decimal value to the next


smaller integer . For example, .5 becomes 0,8.5 becomes 8, and
- 8.5 becomes - 9. When all the parts of a FOR/NEXT loop have
been discussed, a sample program will show you how the
desired results can be obtained if your computer system trun-
cates the decimal numbers in a FOR statement.

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.

(a) 20 FOR 1=1 TO 3 (b) 10 LET A=2


20 FOR I=A/2 TO A+1

Initial value = 1 Initial value = N2 = 2/2 =


Test value = 3 Test value = A + 1 = 2 + 1 = 3

6.2 VARIATIONS-INITIAL VALUE AND TEST


VALUE-Sample Programs
The following programs demonstrate the three variations discussed
in this section. Each program prints the numbers 0, 1,2,3,4 and the
squares of these numbers (O, 1,4,9, 16), as shown in the RUN below.

RUN

o o
1 1
2 4
3 9
4 16
--- - - --- -- - - - - - - - - - - - - - - - - - - - - " T " ' " " - -

FOR/NEXT LOOPS 209

1. Variables used as initial and test values

HI PRINT - Leaves a blank line.


20 LET A=~ -Initializes A to r!J.
3~ LET B=4 -Initializes B to 4.
4~ FOR I=A TO B STEP 1 - Sets up a loop, using A as the initial value and B as the
test value.
50 LET Y=IT2 - Squares the index and stores the result in Y.
60 PRINT I , Y - Prints the value of the index and its square.
70 NEXT I - Transfers control to line 40.
99 END - Terminates program execution.

2. Initial value different than one

1'" PRINT - Leaves a blank line.


20 FOR I=~ TO 4 STEP 1 - Sets up a loop with the initial value set to 0.
30 LET Y=IT2 - Squares the index and stores the result in Y.
40 PRINT I,Y - Prints the value of the index and its square.
S0 NEXT I - Transfers control to line 20.
99 END - Terminates program execution.

3. Expressions used as initial and test values

U1 PRINT - Leaves a blank line.


20 L.ET A=5 -Initializes A to 5.
30 FOR I=A-5 TO A-l STEP 1 - Sets up a loop using expressions to set the initial
and test values to 0 and 4 respectively.
40 LET Y=IT2 - Squares the index and stores the result in Y.
5E'1 PRINT I,Y - Prints the value of the index and its square.
60 NEXT I - Transfers control to line 30.
99 END - Terminates program execution.

6.2 VARIATIONS-INITIAL VALUE AND TEST


VALUE- Your Turn
1. State the error in the program shown below.

10 PRINT
20 READ A,II
30 DATA 6,10
210 PROGRAMMING IN BASIC

40 FOR I=A/3-1 TO C/2+1


50 LET J=IT2
6~' PRINT I,~I
7f) NEXT I
99 ENII

2. What is the RUN of the following program?

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

3. Trace through the logi c of the program shown below, then


answer the following questions .

(a) How many times will the loop be performed?


(b) What is the output of the program?
(c) Suppose the data statement is changed to 30 DATA 8,12 .
What value will be assigned to J the last time the loop is
executed?

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

4. What RUN does the following program produce?

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

5 . A clothier is offering a 20% discount on all items in the store . If


you purchased a coat, a jacket, and a pair of gloves regularly
priced at $190, $80, and $12 .50 respectively , what amount did
you save on each item? What was the reduced price of each item
and what was the total amount of your bill?

(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

~IRT I CLE 2 HARKED PRICE 8e


AMOUNT SAVED 16
REDUCED PRICE 64
ARTICLE 3 HARKED PRICE 12.5
AMOUNT SAVED 2.5
REDUCED PRICE 1e

TOTAL BILL 226

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

6.2 VARIATIONS-INITIAL VALUE AND TEST


VALUE-Solutions for "Your Turn"
1. Variable C has not been assigned a value prior to the FOR/ NEXT
loop.
2

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.

01 REM T--TOTAL BILL


02 REM I--INDEX (NO. OF THE ARTICLE)
03 REM M--MARKED PRICE
04 REM S--AMOUNT SAVED
85 REM R--REDUCED PRICE
10 LET T=0
2~ LET A=l
3l1J LET B=3
40 FOR I=A TO B STEP 1
~)l1J READ M
60 DATA 190,80,12.50
70 LET S=M*.20
80 LET R=M-S
90 LET T=T+R
10~ PRINT
110 PRINT 'ARTICLE';I,'MARKED PRICE';M
12l1J PRINT 'AMOUNT SAVED';S
130 PRINT 'REDUCED PRICE";R
140 NEXT I
150 PRINT
160 PRINT 'TOTAL BILL';T
999 END
214 PROGRAMMING IN BASIC

6.3 VARIATIONS-STEP CLAUSE


To provide even greater flexibility in programming , the value in the
STEP clause is not always restricted to 1. It may be a multiple of 1, a
decimal fraction, or a negative number . It may also be a variable or an
expression . If the value is not 1, the STEP clause must be coded in the
FOR statement.

1. The step value may be a variable or an expression

(a) The step value as a variable.

HI LET C=l
2~ FOR 1=1 TO 3 STEP C

(b) The step value as an expression .

10 LET C=4
2~ FOR 1=1 TO 3 STEP C/4

Notice in the above examples that the variable is assigned a value


prior to its use in the STEP clause and that the variable is different than
the one representing the index . As with the index , the initial value,
and the test value , the step value should not be changed within the
loop.

2. The step value may be a multiple of one

1~ FOR 1=1 TO 6 STEP 2

In this example, the index is increased by 2 each time the computer


passes through the loop . When the value of the index becomes 7
(1 ,3,5,7) , this value exceeds the test value and looping terminates .

3. The step value may be a decimal fraction

1~ FOR 1=1 TO 3 STEP .S

The index, in this example, is incremented by .5 each time the loop is


executed (1,1.5,2,2 .5,3,3 .5) . When the value of the index reaches
3.5, its value is greater than the test value, and the loop terminates.
Note that this example may cause problems if the computer truncates
the step value of .5 to zero and zero increments are not accepted .
FOR/ NEXT LOOPS 215

4. The step value may be negative

1~ FOR 1=6 TO 3 STEP -1

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.

10 FOR 1=6 TO 3 STEP -1}~Loopperformed


5111 FOR 1=3 TO 6 STEP 1 four times

5. The following calculates the number of times a loop


is executed when the step value is different than one

10 FOR 1=1 TO 10 STEP 2

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 .

6.3 VARIATIONS-STEP CLAUSE-Sample


Programs
Step clauses with values that are multiples of one and those with
variables or expressions are relatively easy to understand. The ones
with fractional values and negative values may be a little more difficult.
The sample programs shown below use the last two features.
1. Suppose you wish to borrow $4000 and would like to know the
amounts of interest at rates of 12%, 13%, and 14% . Here is the
program.
216 PROGRAMMING IN BASI C

(a) Use the LET statement to enter the amount to be borrowed .


(b) Use a FOR/ NE XT loop to generate the interest rates .
(c) Use a fractional value in the STEP clause.
(d) Interest = Amount x Rate (index)

1.1.1 LET A=4~HH'I -Initializes A to 4000.


2E1 PRINT - Leaves a blank line.
3~ PRINT "AMOUNT:";A - Prints the amount to be borrowed .
40 FOR R=.12 TO .14 STEP .Ell - Sets up a loop which initializes the rate to .12
then increments the rate by .01 .
5E1 LET I=A*R - Calculates the interest.
6~ PF:INT - Leaves a blank line.
7E1 PRINT "RATE:";R - Prints the rate of interest.
BEl PRINT "INTEREST:";I - Prints the amount of interest.
<lEI NEXT R - Transfers control to line 40.
99 END - Terminates program execution.

RUN

AMOUNT: 4E1E10

RATE: .12
INTEREST: 4811!
RATE: .13
INTEREST: 5211!
RATE: .14
INTEREST: 56E1

For computer systems that truncate the decimal numbers in the


FOR statement, the above program can be modified as follows.

(a) Changeline40to 4E1 FOR J=12 TO 14 STEP 1


(b) Add line 45 45 LET R=J/ HH"
(c) Changeline90to 9E1 NEXT J

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

30 PRINT 1, + - ( - - Remember the comma and the semicolon in Chapter Two?


40 N EXT 1 When either one is placed at the end of a PRINT statement, the
99 END numbers are printed on the same line.

RUN

20 15 10

If the PRINT statement had ended with a semicolon, the output


would have been:

RUN
252015 HI

6.3 VARIATIONS-STEP CLAUSE-Your Turn 1


1. How many times will the loop be performed for each of the
following FOR statements?

(a) 10 FOR 1=1 TO 8 STEP 2


(b) 3tl FOR 1=8 TO 1 STEP -2
(c) 50 FOR 1=.10 TO .15 STEP .01

2. What values will the index take on in each of the following FOR
statements? Do not include the value that terminates the loop.

(a) FOR 1=450 TO 6liH!' STEP 50


(b) FOR 1=7 TO 15 STEP 3
(c) FOR 1=.5 TO 3 STEP .5
(d) FOR 1=-8 TO 8 STEP 3
(e) FOR 1=14 TO e STEP -2

1. Exercises that use decimal numbers in the FOR statement may be omitted if your
computer system truncates these numbers .
218 PROGRAMMING IN BASIC

3. Fill in the blanks in the following program .

HI PRINT
20 FOR 1= _____ TO _ _ _ _- STEP _ _ __
30
40 NEXT I
99 END

FWN

10 6 2 -2 -6

4. State the error in the program shown below .

10 PRINT
221READ A,B
321DATA 221d0
421FOR I=A TO B STEP 2
521 PRINT I
621NEXT I
99 END

5. What is the RUN of the fol lowi ng program?

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

6. Rewrite the sample program on page 215. 2 Here is the problem


once more , but with different interest rates .
Suppose you wish to borrow $4000 and would like to know the
amounts of interest at rates of 10%,12%, and 14%.
(a) Use the LET statement to enter the amount to be borrowed .
(b) Use variables to represent the initial , test, and step values.
Enter these values into the computer by means of the
READ/ DATA statements.

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

(c) Use a FOR/ NEXT loop to generate the interest rates.


(d) Use a fractional value in the STEP clause.
(e) Interest = Amount x Rate (index)
(f) Drawa flowchart before you write the program.

FWN

AMOUNT: 4000
HATE: .1
INTEREST: 400

RATE: .12
INTEREST: 480
RATE: .14
INTEREST: 560

7. Write a program that prints the numbers 30, 28 , 26 , 24 , 22 , and


20 in a column as shown below. Use a FOR/NEXT loop.

f~ UN

3fl
28
:26
24
,"),.)
1 _. A..

6,3 VARIATIONS-STEP CLAUSE-Solutions


for "Your Turn"

1. (a) (8;1 ) + 1 = (~ ) + 1 = 3+1 = 4

(b) C~28 ) + 1 = (::::; ) + 1 = 3+ 1 = 4

(c) (" 15;1·10 ) + 1 = C 5~110 ) + 1 = (i) + 5+1 6

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.

2~ FOR I=10 TO - 6 STEP -4


30 PRINT I;

4 . The step value sho uld be - 2.

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

A AMOUNT Z STEP VALUE


X INITIAL VALUE R RATE (INDEX)
Y TEST VALUE I INTEREST
FOR/NEXT LOOPS 221

( Start )

A=4000

Decimal numbers truncated


in the FOR statement.

~__
End_)
End

W R<=Y, 'V J<=Y


Calculate Calculate
Interest Rate
I=A*R R= J/1 00
I
Print I
Blank line I
R I
I I
'V

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

6,4 NESTED LOOPS


In some programs it may be necessary to control routines by using
more than one FOR/ NEXT loop . Here is an example. Don't be too
concerned about all the PRINT stateFABnt.s. These will be explained
later on in the section .

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

lIZ) FOR 1=1 TO 3


20
30
40 FOR J=l~TO
4 1= 1
1'50 -- I J = 1,2,3,4
\60 NEXT..vJ
70
80 NEXT 1
99 ENII

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

It is also possible to have several inner loops nested inside one


outer loop.

I
In addition to the rules for single loops , there are a number of
restrictions that must be observed when using nested loops.

1. Each FOR/NE XT pair of statements must have its own index


variable . On some computer systems, the variable after the key
word NEXT may be left out. However, this may cause some
confusion, particularly when there are several loops in a pro-
gram. Therefore , it's probably well worth the effort to type it in .
2 . A loop may not cross over (overlap) another loop .

Permitted Not permitted

3. It is possible to transfer control from a point within an inner loop to


a statement outside the loop . However, the reverse is not possi-
ble . You may not transfer control from a point outside the inner
loop to a statement inside .

Permitted Not permitted

I
~ ~
- - - - - - - - -- -- - -- - - -- - -- - - - - - - - - -----.-- -

FOR/NEXT LOOPS 225

How does one calculate the number of times an inner loop is


performed? Use the program segment shown below.

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

Sometimes calculations within the inner loop accumulate. An


example is the addition of the monthly salaries of each of several
employees to get a yearly salary. This total should not be carried over
into another employee's calculations. If the outer loop keeps track of
the employees, then initialization of each employee's total salary to
zero should be done right after the outer loop is set up, that is,
between the two FOR statements. Part of the program for the above
problem might look something like this:

01 REM N--EMPLOYEE NUMBER


02 REM T--TOTAL SALARY
03 REM 5--MONTHLY SALARY
10 FOR N=l TO 3
20 l.ET T=0 -Initializes each employee's total yearly salary to zero before the
3£'l total is calculated.
40 FOR 5=1 TO 12

HH'I LET T=T+5 - Calculates the total yearly salary of each employee.

6.4 NESTED LOOPS-Sample Programs


Nested loops are often used to print tables such as multiplication
tables or interest tables. Here is a program that prints the multiplica-
tion table for the numbers 1,2, and 3. It also gives you an opportunity
226 PROGRAMMING IN BASIC

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.

01 REM R--ROW (ROWS GO ACROSS)


02 REM C--COLUMN (COLUMNS GO DOWN)
03 REM P--PRODUCT

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

Line 10- Leaves a blank line after the word RUN .


Line 20 - Prints the heading 1 2 3 . Notice the eleven spaces before
the numbers . This causes the numbers 1 2 3 to be centered over
their appropriate columns .
Line 30- Leaves a blank line after the heading .
Line 40- Sets up a loop for the three rows .
Line 50- Prints the number of the row. This statement is placed
between the two FO R statements so that the onl y time the row number
is printed is when R changes. The comma causes the next PR INT
statemen t to print values on the same line as the row number.
Line 60- Sets up the loop for the three columns .
Line 70- Multiplies the row number by the column number. Since
the values of both Rand Care 1, the result is 1 (Row 1 x Column 1).
This is stored in P .
Line 80 - Prints the value of P . The semicolon causes the val ues of P
to be printed on the same line . The output so far is :

Line 90- The column number changes from 1 to 2. Control is


transferred back to line 60 and the C loop is executed a second time .
FOR/ NE XT LO OPS 227

The result of line 70 is 2 (Row 1 x Column 2). The output so far is :


1 1 2
Line 90 is reached once more, and the column number changes from
2 to 3 . Control is transferred back to line 60 and the C loop is executed
for the third and last time . The result of line 70 is 3 (Row 1 x Column
3). The output so far is :
123
C is increased to 4. Since this is higher than the test value , control is
transferred to line 100.
Line 100 - This PRINT statement counteracts the semicolon in
PRINT P; . The next value will be printed on a new line .
Line 110- The row number now changes to 2 and C reverts to 1. The
whole cycle is repeated, starting with the printing of the new row
number on the next line . Looping continues until R is greater than 3.
Control is then transferred to the END statement, wh ich terminates the
program .
PRINT statements in a program that contains nested loops are often
confusing . Here are two programs that add the numbers 2,3, and 4 to
each of the numbers 1, 2, 3, and 4. The first one single spaces its
output; the second one double spaces the output.

1. Output single spaced

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

2. Output double spaced

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

4£1 LET K=ItJ


50 PRINT K;
60 NEXT J
70 F'R I NT - Counteracts the semicolon in PRINT K;
811J NEXT I
99 END

RUN

3 4 5 6

4 5 6 7

"".J 6 7 8

In both programs, the statement 50 PRINT K; causes items to be


printed on the same line. The PRINT in line 70 counteracts the
semicolon in PRINT K; and forces the computer off the line so that
the next item (which starts a new row) is printed on a new line.
Program 2 has a PRINT statement between the two FOR statements,
and the one at the beginning of the program is eliminated. This PRINT
results in a blank line before each row is printed. To be consistent , the
PRINT that counteracts the semicolon will be kept between the NEXT
statements. The one that leaves a blank line between each row will be
placed between the FOR statements. If output is to be single spaced,
the first PRINT will be placed at the beginning of the program rather
than between the FOR statements. Also, most of the remaining
flowcharts will include symbols for "blank" PRINTs.

6.4 NESTED LOOPS- Your Turn


I. Problem 2 on page 142 in Chapter Four gave the total number of
parts produced by each of three employees for the XYZ Manu-
facturing Company. In this problem, you are to find these totals
as well as the income for each employee. The rate paid is $2 for
each part produced.

Employee Parts Produced Per Day


1 42,41,44,45,40
2 43 ,42,45,43,40
3 43,39 ,44,42,41

(a) Use an outer FOR/NEXT loop to keep track of the three


employees.
(b) Use an inner FOR/NEXT loop to keep track of the days.
(c) Between the two FOR statements, initialize to zero a variable
that represents the total number of parts produced by each
employee .
FOR/ NEXT LOOPS 229

(d) Use the READ/DATA statements to enter the number of parts


produced by each employee.
(e) Total Number of Parts = Total Number of Parts + Parts
Produced in One Day
(f) Income = Total Number of Parts x Rate
(g) Fill in the missing lines .

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

1. Which statement should be coded in line 20?

(a) FOR D=l TO 5


(b) FOR R=l TO 3
230 PROGRAMMING IN BASIC

(c) H)f~ N=: 1 T () 5


(d) FOR [1=1 TO 3
(e) FOR N=1 TO 3

2. Which statement should be coded in line 40?

(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

3. Complete lines 60, 70, and 80 with DATA statements (one


DATA statement for each employee).
4. Which statement should be coded in line gO?

(a) LET T=TtP


(b) L.ETT==T*f'
(c) LET T==T*R
(d) LET I=TtP
(e) LET I=T*F'

5. Which statement should be coded in line 11 O?

(a) LET I::T+R


(b) LET I=Ttl
(c) L.ET I=T*R
(d) LET I=I*R
(e) L.ET 1=I*T

6. Complete lines 130, 140, and 150 with PRINT statements.

7. Which statement should be coded in line 160?

(a) GO TO 28
(~ IF N)3 THEN 28
(c) NEXT N
(d) NEXT, N
(e) NEXT Nt3

II. Two salespersons receive a commission of 20% on their sales .


Based on the sales shown below , what commission does each
salesperson receive each month? What total commission does
each salesperson earn for the three months?
Salesperson Sales Each Month
1 7000 ,6000,6500
2 8000,7500,6000
FOR/NEXT LOOPS 231

(a) Use an outer FOR/NE XT loop to keep track of the salesper-


sons .
(b) Use an inner FOR/NEXT loop to keep track of the months.
(c) Between the two FOR statements, initialize to zero a variable
that represents each salesperson's total commission. Also
code the PRINT statement that prints the number of a sales-
person.
(d) Use the READ/DATA statements to enter the sales .
(e) Commission = Sales x .20
(f) Print the number of the month alongside the commission.
(g) Total Commission = Total Commission + Commission Per
Month
(h) The flowchart illustrates how the two loops are nested. The
inner loop goes through its cycle as long as M is less than or
equal to 3. Once M is greater than 3, control re-enters the
outer loop. This loop terminates when N is greater than 2.

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

Problem II T TOTAL COMMISSION S SALES


N - NO. OF SALESPERSON M MONTH C COMMISSION

Start

End

\V N<=2


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.

1. (e) 2~ FOR N=l TO 3


2. (d) 40 FOr.: [1= 1 TO 5
3. 60 DATA 42,41,44,45,40
70 DATA 43,42,45,43,40
80 DATA 43,39,44,42,41
4 . (a) 90 LET T=TtP
5. (c) 1 HI LET I=T*R
FOR/ NE XT LOOPS 233

6. 13~PRI NT "EMPLOYEE:"; N
14~PRINT "PARTS:";T
150 PRINT "INCOME:";I
7. (c) 1.60 NEXT N

II.

l?Jl REM N--NO. OF SALESPERSON


02 REM T--TOTAL COMMISSION
~3 REM M--MONTH
1214 REM S--SALES
~5 REM C--COMMISSION

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

6.5 A WAGE PROGRAM


Here is the wage program once more. The data shown in Chapter
Five on page 176 will be used . A FOR/ NE XT loop terminates input
rather than a counter. The index of the FOR statement represents the
number of the employee .

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

(d) Blank lines have been inserted for clarity only.


(e) Calculations
1. Gross Pay (no overtime) = Regular Hours x Regular Rate
2 Gross Pay with overtime:
- Overtime Hours = Regular Hours - 39
- Overtime Rate = Regular Rate x 1.5
- Overtime Pay = Overtime Hours x Overtime Rate
- Gross Pay (with overtime) = 39 x Regular Rate + Over-
time Pay
3. Net Pay:
- Total Deductions = Income Tax Deduction + Union Dues
+ Pension Deduction
-Net Pay = Gross Pay - Total Deductions

01 REM E--INDEX (EMPLOYEE NUMBER)


02 REM H--REGULAR HOURS
03 REM R--REGULAR RATE
04 REM I--INCOME TAX DED.
05 REM U--UNION DUES
06 REM P--PENSION FUND DED.
07 REM Hl--0VERTIME HOURS
08 REM Rl--0VERTIME RATE
09 REM V--OVERTIME
10 REM G--GROSS PAY
11 REM D--DEDUCTIONS
12 REM N--NET PAY
10~ REM SET UP A FOR/NEXT LOOP
105 FOR E=1 TO 3
200 REM READ HOURS,RATES,DEDUCTIONS
205 READ H,R,I,U,P
210 DATA 44,10.24,80,2,3
215 DATA 37,11.54,75,2,2.50
220 DATA 39,12.34,90,2,4
300 REM CHECK FOR OVERTIME
305 IF H)39 THEN 500
400 REM GROSS PAY---NO OVERTIME
405 LET Hl=0
410 LET Rl=0
415 LET V=0
420 LET G=H*R
425 GO TO 600
5ea REM GROSS PAY--WITH OVERTIME
505 LET Hl=H-39
5H' LET Rl=R*I.5
515 LET V=Hl*Rl
520 LET G=39*RtV
600 REM NET PAY
FOR/NEXT LOOPS 235

6a5 LET D::I+U+P


61a LET N=G-D
7~H!l REM PRINT STATEMENTS
7kJ5 PRINT
71e PRINT "EMPLOYEE";E,"HRS";H,'RATE";R
715 PRINT "OVERTIME HOURS";Hl
720 PRINT 'OVERTIME RATE';R1
725 PRINT 'OVERTIME PAY·;V
73e PRINT 'GROSS PAY';G
735 PRINT "INCOME TAX";I
74~ PRINT 'UNION DUES';U
745 PRINT 'PENSION';P
75~ PRINT "TOTAL DEDUCTIONS";D
755 PRINT "NET PAY';N
8Be REM TRANSFER TO BEGINNING OF LOOP
1305 NEXT E

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

1. In the above program , what two statements control the loop?

****************************************
H'J5 FOR E=l TO 3
805 NEXT E

2. In the wage program in Chapter Five, page 177


(a) What five statements are replaced by 105 FOR E= 1 TO 3?

****************************************
105 LET K=l
210 READ Nl
215 DAHl 3
8~~j LET K=Ktl
81~ IF K)Nl THEN 999

(b) What statement is replaced by 805 NEXT E?

****************************************
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 .

Index Initial Test Step

1 val'ue value value

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

reverse is not permitted Control must not be transferred from a point


outside the loop to a statement inside.

Permitted Not permitted

\ ~
i-'"

A FOR/NEXT loop can be nested inside another as long as the loops


do not cross over (overlap) .

Permitted Not permitted

It is possible to have several inner loops nested inside one outer


loop and to have several levels of looping, although there may be a
limit as to the number of levels.

Several loops inside one loop Several levels of loops

Questions and Exercises 3


1. Display and label the general form of a FOR statement. State the
purpose of each part of the statement.
2. What is the purpose of the NEXT statement?

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

3 . Using a simple program segment, explain how the computer


executes a FOR/NE XT loop .
4 . Identify the errors, if any , in the program segments shown below .
Make the necessary corrections .

(a) HI NEXT 1 (d) 10 FOR L=1 TO 5


20 20
30 FOR 1=1 TO HI 30 NEXT L
48 GO TO 20

(b) 1.0 FOR J=1 TO 3 (e) 10 FOR M>10 TO 58


20 READ K 20
30 DATA ah20,30 30 NEXT M
40
S0 NEXT K

(c) 10 LET 1=0 =


(f) 1 0 FOR N 1 0 S T E P 1
20 FOR J=1 TO 3 20
30 LET K=ltJT4 30 NEXT N
40
50 NEXT J

5 . How many times does your computer system execute a


FOR/ NEXT loop for each of the following FO R statements?

(a) HI FOR A=1 TO 1 STEP 1


(b) 28 FOR B=1 TO 1 STEP -1
(c) 30 FOR C=1 TO 1 STEP 111
(d) 40 FOR II=1 TO 18 STEP 8
(e) 50 FOR E=10 TO 1 STEP 1

6 . On your computer system, what value does the index take on


after a FOR/NEXT loop is complete?
7. How many times will the FOR/NEXT loop be executed in each of
the following program segments?

(a) 18 FOR P=1 TO HI STEP 1 (d) 10 FOR S=10 TO 2 STEP -2


20 20
30 NEXT P 38 NEXT S
(b) 10 FOR Q=4 TO 26 STEP 2 (e) 10 FOR T=-9 TO 9 STEP 3
28 20
30 NEXT Q 38 NEXT T

(c) 18 FOR R=3 TO 21 STEP 4 (f) HI FOR U=.5 TO 5 STEP .5


28 20
30 NEXT R 38 NEXT U
240 PROGRAMM ING IN BASIC

8. Identify the errors , if any, in the FOR statements shown below .


Assume that the loop is to be executed more than once . Make
the necessary corrections .

(a) 10 FOR 1=3 TO 6 STEP -1 (f) 10 LET A=-6


20 LET B=-12
30 FOR N=A TO B

(b) 10 LET A=5 (g) 18 FOR P=.l TO 1 STEP • 1


20 FOR J=A TO B STEP 2
(c) 10 FOR K=S TO 2S (h) 1" FOR Q=Q TO 1111 STEP 5
(d) UI FOR L=10 TO STEP 3 (i) 1111 LET A=-l
20 LET B=-20
30 FOR R=A TO B-1 STEP -1
(e) HI LET A=4 (j) HI LET A=36
20 LET B=16 20 FOR S=A/3 TO A/6
30 FOR M=A TO M STEP 2

9. What is meant by a nested loop?


10. Identify the errors, if any, in the program seg ments shown below.
Make the necessary corrections .

(a) 10 FOR I --"Jc' TO 14 STEP 3 (d) 10 FOR 1=1 TO 4


~~0 FOR J=l TO K STEP 1 20 FOR J=l TO 5
30
60 NEXT J 40 NEXT J
70 NEXT I S0 GO TO 30
60 NEXT I
(b) 10 FOR 1=3 TO 7 STEP 2 (e) 10 FOR 1=1 TO 10
20 FOR J=l TO 4 20 FOR J=l TO 14
60 NEXT I 60 LET K=JtI
70 NEXT J 70 IF K)20 THEN 140
80 NEXT J
90

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
-- - -

FOR/NEXT LOOPS 241

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

12. Fill in the blanks in the following programs.

(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

.3- .7 101 1.5


242 PROGRAMMING IN BASIC

13. How many times is the inner loop executed in the following
program segment?

10 FOR 1=1 TO 9 STEP 2


20 FOR J=1 TO 13 STEP 3

60 NEXT J
70 NEXT I

14. What is the output of each of the following programs?

(a) 10 FOR 1=1 TO 3


20 PRINT
30 PRINT 01 = 0; I
40 FOR J=2 TO 6 STEP 2
50 PRINT oJ = 0 ; J,
60 NEXT J
70 PRINT
80 NEXT I
99 END

(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

WEEKLY WAGES: 400


HOURLY RATE! H!
WEEKLY WAGES: 450
HOURLY RATE: 11. 25
WEEKLY WAGES: 500
HOURLY RATE: 12.5

Problem 1
W WEEKLY WAGES (INDEX)
H - HOURLY RATE

Start

W>500 ( _______
End -=--)
Calculate
Hourly Rate
H=W/40

NEXTW

2. Companies A, B, and C, selling farm equipment, pay their


salespersons commissions of $2000, $2200, and $2400 respec-
tively on sales amounting to $1 0000. What rate of commission is
each company offering?
(a) Use a LET statement to enter the sales.
(b) Use a FOR/NEXT loop to generate the commissions paid.
(c) Rate of Commission = Commission (Index)
Sales
244 PROGRAMMING IN BASIC

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

INITIAL SALARY: 19000

INCREASE: 1 SALARY: 20000


INCREASE: 2 SALARY: 21000
INCREASE: 3 SALARY: 22000
INCREASE: 4 SALARY: 23000
INCREASE: 5 SALARY: 24000
INCREASE: 6 SALARY: 25000

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 .

Store Number Sales Per Month


1 2000,2200,1700,2300
2 1800,2100,2200,2400
3 1900,2000,1800,2200
(a) Use an outer FOR /NE XT loop to keep track of the stores.
(b) Use an inner FO R/ NEXT loop to keep track of the months .
(c) Between the two FOR statements, initialize to zero a variable
that represents each store's total sales. Also code the PRINT
statement that prints the number of a store .
(d) Use the RE AD/DATA statements to enter the sales .
(e) Total Sales = Total Sales + Sales Per Month
(f) Your flowchart should be similar to the one for Problem lion
page 231 . In addition to changing the descriptions within
some of the symbols , omit the two figures that represent the
calculation and the printing of the commission .

RUN
STORE: 1
TOTAL SALES: 82ee
STORE: 2
TOTAL SALES: 8See
STORE: 3
TOTAL SALES: 7900

6. Discounts are often offered by manufacturers to encourage


retailers to purchase merchandise in large quantities. What
amount of discount would a clothier receive from each of three
manufacturers on a shipment of suits if the quoted price is $4000
and a discount of 4% is offered by one manufacturer, 6% by
another, and 8% by a third? What would be the net price in each
case?
(a) Use the READIDATA statements to enter the quoted price .
(b) Use a FO R/NE XT loop to generate the rates of discount.
(c) Discount = Quoted Price x Rate of Discount
(d) Net Price = Quoted Price - Discount

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

Decimal numbers truncated


in the FOR statement.

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

7. As an extension to Problem 6, suppose the clothier wishes to


know what discounts would be received from each of the three
manufacturers if two separate purchases are to be made priced
at $3000 and $4000 respectively . Do not find the net prices.
(a) Use an outer FO R/NE XT loop to generate the quoted prices.
(b) Use an inner FOR/NEXT loop to generate the rates of discount.
(c) Between the two FO R statements, code the PRINT statement
that prints a quoted price
(d) Discount = Quoted Price x Rate of Discount

RUN

QUOTED PRICE: 3~HH!I


RATE: .04 DISCOUNT: 120
RATE: .06 DISCOUNT: lse
RATE: .08 [IISCOUNT: 24111

QUOTED PRICE: 4el1l0


RATE: .04 DISCOUNT: 16111
RATE: .1116 DISCOUNT: 24111
RATE: .1118 DISCOUNT: 32111

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

RATE: .13 AMOUNT: 1630.47361


RATE: .14 AMOUNT: 1688.962117
RATE: .15 AMOUNT: 1749.021625
FOR/NEXT LOOPS 249

9. Rewrite the previous program so that the compound amounts are


calculated each year. Use each of the three rates each year .
(a) Use two FOR /NE XT loops:
(i) The outer loop keeps track of the years (period of time in
the formula). Use the index of the FOR statement to print
the number of the year at the beginning of each output
line. Place this PRINT statement between the FOR state-
ments .
(ii) The inner loop generates the interest rates .
(b) Compound Amount = 1OOO( 1+ R) Year Number
(C) Print the first year's compound amounts across the first line
of output (for each rate of interest), the second year 's com-
pound amounts across the second line of output (for each
rate of interest), etc. To do this, your PRINT statement that
prints the number of the year and the PRINT statement that
prints the compound amount should each end with a semi-
colon.
(d) Compound amounts will not be rounded off to the nearest
cent.

RUN

1 1130 1140 1150


2 1276.9 1299.6 1322.5
3 1442.897 1481.544 1520.875
4 1630.47361 1688.96017 1749.00625

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.

'V R<= .15 'V J<= 15


Calculate
Calculate
Compound
Rate
Amount
R= J/1 00
C=1000*(1+R)jY
'V~ I
I
Print I
C I
I
'V_ _

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.

7.1 STORING DATA IN ARRAYS


Until now, you have been using simple numeric variables, such as A,
K , N1 , A9 , etc ., to store your numbers . Each variable is capable of
storing only one number at a time. If a different number is assigned to
the same variable , the previously stored value is replaced by the new
one . To store two numbers , two variables must be used ; three
numbers require three variables , etc . Using the LET statement , the
numbers are entered as follows.

1£1 LET A=l


2£1 LET :8=2
3£1 LET C=3
252 PROGRAMMING IN BASIC

The values can also be entered by the INPUT statement or by the


READIDATA statements. However, no matter which way they are
entered, you still need three different variables - one variable for
each number. This means that if you want to keep all the numbers in
storage so that they can be referenced later on in the program, each
number must have its own storage location with an address that is
unique. Note that a number is always referenced by a variable, which
is considered to be its address. When there are only a few numbers to
store, it is fairly simple for the programmer to supply these variables.
But if you want to store 10,50, or 100 different numbers, you will need
10, 50, or 100 different variables. Not only is the process of storing
the numbers cumbersome and time-consuming, but referencing
them may cause some confusion. However, there is a way by which
the computer can store and retrieve numbers automatically.
What the programmer does is inform the computer that it must set
aside enough locations in memory to store all the data. These loca-
tions are adjacent to one another in a block of storage called an array
to which the programmer assigns a name. Each storage location
within the block must be given an address that is unique. The address
is created by having the computer assign a number to a location and
attaching this number to the name of the array. In this chapter, one-
dimensional arrays will be discussed. This type of an array, also
referred to as a vector or a list, consists of only one row or one column
of numbers.
An analogy is a one-storied apartment block. Suppose you live in
the Parkview Apartments. There are four apartments and you live in
apartment number 3. If you want to direct some friends over for a visit,
you would probably give them the name of the apartment block
(Parkview) and the number of your apartment (3). If you used an
abbreviated version for Parkview, say P, your address could be
written as P(3) in BASIC. The address of the people who live in the first
apartment would be written P(1). This system of notation gives each
apartment a unique address since the apartment numbers differ:
P(1), P(2), P(3), and P(4); spoken as "P sub 1", "P sub 2", "P sub
3", "P sub 4". The P is the name of the array; the number is called
the subscript. P(1), P(2), (P3), and P(4) are referred to as sub-
scripted variables. They store elements of the array P. In this particu-
lar array, there are four subscripted variables. Depending on your
computer system, the number of elements in an array may vary from
zer0 1 to 255, or to a maximum number that is dependent on available
memory.
To reference a specific data item, you must use the name of the
array of which it is a member, along with its location within the array.
This location, or subscript, must follow the array name and must be in
parentheses. The subscripts must be whole numbers, not decimal
numbers, and on most systems they cannot be negative. A subscript
may also be a variable or an expression. Any variable used as a
subscript must be assigned a value previous to its use. For example,
if N=1, P(N) refers to the first location in the array; if N=5, P(N-3)
refers to the second location in the array. On most computer systems,
an array name may be any valid variable name (some computers
insist that it be a single letter). It must be unique; that is, no two array
names may be the same. Some systems allow the name of a numeric
array to be the same as that of a simple numeric variable. (It would be

1 In this book, one will be used as the smallest subscript


O NE-DIMENSIONA L ARRAYS 253

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).

30 READ P(I) means READ P(1)


40DATA@3,1,2

P(1) P(2) P(3) P(4)


4

The second time through the loop 1=2. P(I) is actually P(2). The
number 3 is stored in P(2) .

30 READ P(I) means READ P(2)


40 DATA4~1,2

P(1) P(2) P(3) P(4)


4 3

The third time through the loop I = 3. P(I) is now P(3) . The number 1 is
stored in P(3) .

30 READ P(I) means READ P(3)


40 DATA 4,3m2
254 PR OG RAMMING IN BASIC

P(1) P(2) P(3) P(4)


4 3

The fourth time through the loop 1= 4. P(I) is now P(4) . The number 2
is stored in P(4) .

30 READ P(I) means READ P(4)


40 DATA4,3,1~

P(1) P(2) P(3) P(4)


4 3 2

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

locations to be reserved. This number can be misleading. Depending


on your computer system DIM A(10) may mean:
- Locations (/) to 9, which gives 10 locations.
- Locations 1 to 10, which gives 10 locations.
- Or locations (/) to 10, which gives 11 locations.
On many systems, the DIM statement is not needed for arrays with
11 or fewer elements. The computer will automatically reserve these
locations for you. However, it's best to dimension every array your-
self. This way you determine the maximum size of the array. If there
are more than 10 or 11 elements in your array, space must be
reserved by using the DIM statement. It should also be noted that
some computer systems allow a variable (which has previously been
assigned a value) in the DIM statement to indicate the number of
storage locations to be reserved.
Here are a few more rules concerning the DIMENSION statement.
The same DIM statement must not be executed more than once. This
is why most programmers place it at the beginning of a program,
although some computer systems insist that it be the first statement.
Also, the DIM statement must precede statements that enter data into
the arrays. The number of reserved locations does not necessarily
have to be the same as the number of data items stored. You may
reserve more locations than you need; however, you may not reserve
less than you need. If your program uses more than one array, both
may be dimensioned in one statement with a comma between the
names of the arrays.

10 DIM P(4),RC20)

7.1 STORING DATA IN ARRAYS-Sample


Programs
Now trace through some sample programs. There is no output
(except for the prompt in the second program), since all that the
programs do is store data.
I. In this program, the READ/DATA statements are used to store four
values in an array named A. The values are 25, 50, 75, 100.

HI [11M A(4) - Reserves four storage locations.


20 FOR 1=1 TO 4 - Sets up a loop.
30 READ ACI) - Reads values from the data statement one at a time and stores
each item as an element of array A.
40 DATA 25,50,75,100 - Supplies the READ statement with data.
50 NEXT I - Transfers control to line 20.
99 END - Terminates program execution.
256 PROGRAMMING IN BASIC

II. This prog ram uses the INPUT statement to enter the data into
array A.

10 {11M A(4) - Reserves four storage locations .


20 FOR 1~1 TO 4 - Sets up a loop.
30 PRINT 'VALUE FOR A ( 1 ) .; -Identifies the value of the variable A(I) . I varies
from 1 to 4.
40 INPUT A (1) - Requests data, user enters the value of A(I).
50 NEXT 1 - Transfers control to line 20.
99 END - Terminates program execution.

III. Shown below is a problem that appeared in Chapter Five


(Review Problem 3, page 191). This time arrays are used to store
the data. The program will be developed in four stages:

1. In Section 7.1, the data is stored .


2. In Section 7.2, the data is stored and printed .
3. In Section 7.3, the data is stored and printed and the
extended cost of each item is calculated .
4. Finally, in the review problems, you will be asked to program
all of the above and calculate the total cost of all the items .
Here is the data .

Item Quantity Unit Price


1 2 $4 .50
2 4 3.00
3 5 2.25
4 3 5.15

(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.

(b) Three programs are written:

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.

1. Using two FOR/NEXT loops and two DATA statements

H'I [11M Q(4) ,U(4)

100 REM STORE QUANTITIES IN ARRAY Q


110 FOR 1=1 TO 4
120 REA [I Q(I)
ONE-DIMENSIONAL ARRAYS 257

130 DATA 2,4,5,3


140 NEXT I
20~ REM STORE UNIT PRICES IN ARRAY U
210 FOR J=l TO 4
220 READ U(J)
230 DATA 4.50,3.~~,2.25,5.15
240 NEXT J
999 END

Notice how the data is stored. Each array is filled by means of a


separate routine. The first loop stores the quantities. When this loop is
complete , the second loop stores the unit prices.

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 :

2. Using two FOR/NEXT loops and one DATA statement

HI DIM Q(4),U(4)

100 REM STORE QUANTITIES IN ARRAY Q


110 FOR 1=1 TO 4
120 READ Q(I)
130 NEXT I
200 REM STORE UNIT PRICES IN ARRAY U
210 FOR J=l TO 4
220 READ U(J)
230 NEXT J
30~ REM DATA STATEMENT
310 DATA 2,4,5,3,4.50,3.00,2.25,5.15

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

3. Using one FOR/NEXT loop and one DATA statement

10 [11M (H4),U(4)

HH21 FOR 1::1 TO 4


110 REA [I Q(I),U(I)
120 DATA 2,4.50,4,3.0~,5,2.25,3,5.15
130 NEXT I

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 .

The first time through the loop 1= 1 .


2 is assigned to 0(1) 110 READO(l) ,U(l)
4.50 is assigned to U( 1) 120 DATA(2 , 4.5~4 , 3 . 00 , 5 , 2 .2 5 , 3,515
0(1) [IJ U(1) 14.501
The second time through the loop 1=2
4 is assigned to 0(2) 110 READ 0(2),U(2)
3.00 is assigned to U(2) 120 DATA 2,4 . 50(4,30~5,2 . 25,3,515

0(1) r2l U(1) 1


4 .50 1

0(2) [}] U(2) 3.00


The third time through the loop 1=3
5 is assigned to 0(3) 110 READO(3) ,U(3)
225 is assigned to U(3) 120 DATA 2,4 . 50,4 , 3 . 00~3,5.15

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

0(1) ;324 U(1) 4.50


0(2) U(2) 3.00
0(3) U(3) 2.25
0(4) U(4) 5.15
Now to summarize the programming of Problem III: The program
using one loop requires fewer statements; however, care must be
taken in listing the data. The data must be listed in pairs, of which the
first value is stored in array 0 and the second value is stored in array
U. The items are listed in this order because the READ statement lists
array 0 before array U
ONE-DIMENSIONAL ARRAYS 259

110 READ Q(I),U(I)

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.

7.1 STORING DATA IN ARRAYS- Your Turn


1 . Identify the errors, if any, in the program segments shown below.
Make the necessary corrections .

(a) H1 DIM A(S)


20 FOR 1=1 TO 10
30 READ A (I>
4~ DATA 2,4,6,8,10,12,14,16,18,20
50 NEXT I

99 END

(b) 10 DIM B(1.0)


20 FOR K=l TO HI
30 READ K(EI)
40 DATA 2,4,6,8,10,12,14,16,18,20
50 NEXT K

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

(d) HI ItIM R ( 15)


20 PRINT
30 FOR 5=1 TO 5
40 PRINT "VALUE FOR R(S)";
50 INPUT R(S)
60 NEXT 5

99 ENIt

(e) In this program segment, the data items are to be stored as


follows.

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

2. What will be stored in each variable of the array(s) after execution


of each of the following program segments? Show the name of
ON E-D IMENSIONAL ARRAYS 261

the variab le an d its content. Fo r example , if there are two arrays ,


you cou ld show the contents in the fol lowing manner .

Array A Array 8

I~ I I~~ I
A(1 ) 8(1 )
A(2) 8(2)
A(3) 8(3) 30

(a) 1.0 DIM A(5)


20 FOR 1=1 TO 5
30 READ A(1)
40 DATA 11,22,33,44,55
50 NEXT I

99 END

(b) 10 DIM M(3),N(3)


20 FOR 1=1 TO 3
30 f.:EAD M(1),N(1)
4111 DATA 11,22,33,44,55,66
5~ NEXT I

99 END

(c) 1111 DIM M(2) ,N(2)


20 FOR 1=1 TO 2
30 READ M(1),N(I),C
40 DATA 11,33,55,22,44,66
511) NEXT I

99 END

3. Suppose a savings and loan compan y offers vary ing rates of


inte rest on inve stm e nts de pe nding on th e length of ti me the
money is in vested . The data is as follows .

No. of Years Rate of Interest


10 12%
15 13%
20 15%
(a) Write two programs , each one READi ng th e above informa-
tion into two arrays . One program uses two FOR/NEXT loops
and two DATA statements ; the other program uses one
FOR/NEXT loop an d one DATA statement.
(b) In the program th at uses one loop , explain wh y the data items
in the DATA statemen t must be listed in a specific order.
(c) The DIM stat e men t in the flowchart is re pres e nted by the
process sy mbol . Subse quent to the DIM stat ement , notice
that the variables Y and R in the flowchart are subscripted
whenever th ey are use d.
262 PR OG RAM MING IN BAS IC

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

7.1 STORING DATA IN ARRAYS- ll


Solutions for "Your Turn
1. (a) There are not enough storage locations reserved for array A.
Either increase the dimension of A to 10 or change the test
value in the FOR statement to 5. In the second alternative, the
data statement may remain unchanged since, on most com-
puter systems, excess data is ignored.

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)

(d) Nothing is wrong .


(e) The data items in the DATA statement are not listed in their
proper order. Since they are being read in as pairs, the first
item of each pair must be assigned to an element of array A,
the second item of each pair must be assigned to an element
of array B.

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.

3. (a) Using Two FOR/NEXT Loops Using One FOR/NEXT Loop

~1 REM Y--YEARS 01 REM Y--YEARS


~2 REM R--RATE ~2 REM R--F"..:ATE

HI DIM Y(3) ,R(3) U;' DIM Y(3),F"..:(3)


2k1 FOR 1=1 TO 3
100 REM STORE YEARS IN (-lRRAY Y 30 READ Y(I),R(I)
11~ FOR 1=1 TO 3 40 DATA 10,.12,15,.13,20,.15
120 READ Y(1) 50 NEXT I
13~ DATA 10,15,20 99 END
140 NEXT I
20a REM STORE RATES IN ARRAY R
21k1 FOR J=l TO 3
220 READ R(J)
230 DATA .12,.13,.15
240 NEXT J
999 END

(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.

7.2 PRINTING FROM ARRAYS


In the last section, you learned how numbers can be stored in an
array. A sufficient number of storage locations was reserved by the
DIM statement. As each value was stored, the computer attached a
number to the array name to identify a specific location in storage. In
this section, you will learn how to print the contents of each location.
Again, the Parkview Apartments will be used as an analogy. The
block has 4 apartments, and in Section One a program was written
that stored the number of people living in each apartment.
ONE-DIMENSIONAL ARRAYS 265

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

P(1) P(2) P(3) P(4)


4 3 2

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

The computer prints the contents of P(3) just as it PRINTed the


contents of a simple numeric variable. How would you ask the
computer to print the contents of the first storage location?

5£1 PRINT P(l)

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)

UHl REM STORE ITEMS IN AN ARRAY


1121 FOR 1=1 TO 4
120 READ F' ( 1)
13£1 DATA 4,3,1,2
14£1 NEXT I
200 REM PRINT ITEMS FROM (iN ARRAY
21£1 PRINT
220 FOR J=l TO 4
230 PRINT P ( J) ;
24£1 NEXT ~J
999 END

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 .

2. Using one FOR/NEXT loop

1£1 DIM P(4)


2£1 PRINT
3£1 FOR 1=1 TO 4
4£1 READ P ( 1)
5£1 [lATA 4,3,1,2
268 PROGRAMMIN G IN BASIC

6~ PRINT F' ( I ) r
7~ NEXT I
99 END

FWN

4 3 1 ...
")

Make sure you understand the difference in the execution of these


two programs. The one using two FOR/NEXT loops reads in all the data
items. After the y have all been entered, the computer then prints
them. It completes one operation at a time (the READing of data)
before going on to the next operation (the PRINTing of data). Each
operation uses a different FOR/NEXT loop. The program using one
FOR/NEXT loop reads one item of data and prints it right away. It then
reads the second item of data and prints that one . The operation s of
RE AD and PRINT alternate within the one loo p . Whi ch program do you
prefer?
Here is a challenge . How would you instruct the computer to print
the items backwards (that is , a program that prints the number of
peop le in each apartmen t but starts with apartment 4 and ends with
apartment 1)?

P(1) P(2) P(3) P(4)


4 3 2

Your statements should look something like this .

10 [tIM P(4)

40 FOR 1=4 TO 1 STEP -1


50 PRINT PCl);
60 NEXT I

99 END

RUN
2 1 3 4

One last comment before going on to some sample programs. The


placement of blank PRINT statements is often confusing . Examine
where the y are coded in the following two program segmen ts .
1. Output single spaced

10 [JIM O(4),U(4)

50 PR I NT - Placed just before the loop that prints the results.


ON E-DIMEN SION AL ARR AYS 269

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

2. Blocks of output double spaced

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

7.2 PRINTING FROM ARRAYS-Sample


Programs
The following programs print what was stored in the sample programs
in Section 7.1.
270 PROGRAMMING IN BASIC

I. This program stores and prints the four values 25 , 50 , 75 , 100. It


uses the READ/ DATA statements to enter the values into an array
named A.

U:'J DIM A(4) - Reserves four storage locations.


20 PRINT - Leaves a blank line.
30 FOR 1=1 TO 4 - Sets up a 'l oop.
48 READ A(I) - Reads values from the data statement one at a time and
stores each item as an element of array A.
50 DATA 25,50,75,10~ - Supplies the READ statement with data .
60 PRINT A(I), - Prints the items widely spaced on one line.
78 NEXT I - Transfers control to line 30.
99 END - Terminates program execution.

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 .

10 [11M A(4) - Reserves four storage locations.


20 PRINT - Leaves a blank line.
30 FOR 1=1 TO 4 - Sets up a loop to enter the data.
48 PRINT "VALUE FOR A(I)"; -Identifies the value of the variable A(I) .
I varies from 1 to 4.
58 INPUT A ( I ) - Requests data, user enters value for A(I).
60 NEXT I - Transters control to line 30.
70 PRINT - Leaves a blank line after the prompts .
80 FOR J=l TO 4 - Sets up a loop to print the data.
90 PRINT A(J), - Prints the data widely spaced on one line .
11110 NEXT J - Transfers control to line 80.
999 END - Terminates program execution .

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

Item Quantity Unit Price


1 2 $4.50
2 4 3 .00
3 5 2.25
4 3 5.15
(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 Q stores the quantities ; array U stores the unit
prices .
(b) Two programs are written :
1. The first program uses two FOR/NE XT loops-one loop
to store the data, the other loop to print the data.
2. The second program uses one FO R/ NE XT loop to store
and print the data.

1. Using two FOR/NEXT loops

le0 REM STORE THE DATA


110 FOR 1=1 TO 4
120 READ Q(I),U(I)
130 DATA 2,4.50,4,3.0B,5,2.25,3,5.15
140 NEXT I

200 REM PRINT THE DATA


210 PRINT
220 FOR J=l TO 4
230 PRINT Q(J),U(J)
240 NEXT J
999 END

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 .

2. Using one FOR/NEXT 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 .

7.2 PRINTING FROM ARRAYS-Your Turn


1. Write one or more statements to perform the following . Assume
the data has already been stored.
(a) Write a PRINT statement that prints the first element of the
array A.
(b) Write a PRINT statement that prints the first and tenth ele-
ments of the array A widely spaced on the same line.
(c) Write a program segment that prints the first four elements of
array A. Use a FO R/ NEXT 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

2. Is there anything wrong with each of the following programs? If


there is no error, show the output ; if there is an error , state what is
wrong and make the necessary corrections .

(a) HI DIM A(4) (c) 10 DIM A(3),BC4)


2£'1 PRINT 20 PRINT
3£'1 FOR 1=1 TO 4 30 FOR 1=1 TO 4
4£'1 READ A CI> 40 READ A(I),BCl)
5£'1 DATA 5,U"15,2e 5£'1 DATA 1,15,2,46,3,23,58
6£'1 PRINT A 6£'1 PRINT ACl),BCl)
7£'1 NEXT I 7£'1 NEXT I
99 END 99 END

(b) 1£'1 DIM A(3) ,B(3) ,C(3)


2£'1 PRINT
30 FOR 1=1 TO 3
4£'1 READ A(I),BCI),CCI)
5£'1 DATA 1,1£'1,10£'1,2,2£'1,200,3,3£'1,3£'10
6£'1 PRINT ACI),BCI),CCI)
7£'1 NEXT I
99 END

3. This is an extension of the " Your Turn" problem in Section 7.1. In


this section , you are to print the data in addition to storing it.
Suppose a savings and loan company offers vary ing rates of
interest on investments depending on the length of time the
money is invested . The data is as follows.

No. of Years Rate of Interest


10 12%
15 13%
20 15%

(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

YEARS: 1" RATE: .12


YEARS: 15 RATE: .13
YEARS: 20 RATE: .15

Problem 3
Y - YEARS
R - RATE

C~Start)
W

Next I

7.2 PRINTING FROM ARRAYS-Solutions for


"Your Turn"
1.

(a) 6" PRINT A(l)


ONE-DIMENSIONA L ARR AYS 275

(b) se PRINT A(l),A(Un


(c)
60 FOR 1=1 TO 4
70 PRINT A ( I ) ,
S0 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

2 . (a) In line 60, the variable A in the PRINT statement must be a


subscripted variable .

60 PRINT A(I)

(b) Nothing is wrong.

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 REM Y--YEARS


02 REM R--RATE

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

7.3 CALCULATING WITH ARRAYS


Section 7.1 entered data into an array; Section 7.2 printed the data. In
this section, calculations are performed using this data. Again, the
number of people living in each apartment of the Parkview Apart-
ments will be used as data items . The first few examples are program
segments in which it is assumed that the data has alread y been stored
in an array called P.

P(1) P(2) P(3) P(4)


4 3 2
I. Suppose you want to know the total number of people living in
apartments one and two . Here is a statement that performs this
calculation.

S0 LET T=P(1)tP(2)
6f) P'RINT T

99 END
RUN

Line 50 is executed as follows:

S0 LET T=P(1)tP(2)
= 4+ 3
= 7

II . If you want to know the total number of people living in the


apartment block , the statement will look like the following.
ONE-DIMENSIONAL ARRAYS 277

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

100 REM STORE AND PRINT THE DATA


1 HI PRINT
120 FOR 1=1 TO 4
130 READ P(I)
140 DATA 4,3,1,2
150 PRINT P(I),
160 NEXT I

2~0 REM CALCULATE AND PRINT THE TOTAL


210 FOR J=l TO 4
220 LET T=T+P(J)
230 PRINT T -Placed ,inside the loop.
240 NEXT J

999 END

RUN
'")
4 3 1 .:..

4
7
8
10
278 PROGRAMMING IN BASIC

Notice in this program that the statement PRINT T is inside


the loop. This gives a subtotal after each calculation. Here is
how the computer accumulates the total.

P(1) P(2) P(3) P(4)


4 3 2

Before the loop starts, T is initialized to zero. T=0.


The first time through the loop J= 1. The computer adds
whatever is currently stored in T to whatever is stored in
P(1). The result is stored back into T.
220 LET T = T + P(J)
= T + P(1)
=0+4
=4
The second time through the loop J=2. The current value of
Tis 4.
220 LETT=T +P(J)
= T + P(2)
=4+3
=7
The third time through the loop J=3. The current value of T
is 7.
220 LET T = T + P(J)
= T+ P(3)
=7+1
=8
The fourth time through the 100pJ=4. The current value ofT
is 8.
220 LET T = T + P(J)
=T+P(4)
=8+2
=10
To print just the total without subtotals, the routine will look
as follows.

200 REM CALCULATE AND PRINT THE TOTAL


210 FOR J=l TO 4
220 LET T=TtPeJ)
230 NEXT J
240 PRINT T -Placed outside the loop.
999 END

RUN

4 3 1 2
10
ONE-DIMENSIONAL ARRAYS 279

2. The storing, printing, and calculating operations can be


combined in one loop.

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

The above program gives no subtotals since the statement


PRINT T is outside the loop. To obtain subtotals, place the
PRINT T statement inside the loop as follows.

421 FOR 1=1 TO 4


521 READ F'(I)
60 DATA 4,3,1,2
70 PRINT P(I),
821 LET T=TtP(I)
921 F'R I NT T - Placed inside the loop.
1210 NEXT I
999 END

RUN

4 4
3 7
1 8
...
'1
Hl

The comma after PRINT P(I), causes the subtotal to be


printed on the same line as the data item. Since the state-
ment PRINT T does not end with a comma, the next data
item and subtotal are printed on a new line.
280 PROGRAMMING IN BASIC

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

P(1) P(2) P(3) P(4)


6 3 2

V. Here is another change. Suppose the family in Apartment 4


moves out and the new family has the same number of people as
the family now living in Apartment 2. Instead of coding

80 LET P(4)=3

you can write

80 LET P(4)=P(2)

A copy of the number stored in P(2) is placed in P(4) . Both


storage locations now contain the number 3 The statement is
similar to one that was discussed in Chapter Three, page 56,
where simple variables were used: 40 LET B=A. Here sub-
scripted variables are used, but they act just the same. Each
apartment now contains the following number of people.

P(1) P(2) P(3) P(4)


6 3 3

VI. The family in Apartment 2 has an additional member. The state-


ment that makes this change is:

8~ LET P(2)=P(2)tl

One is added to the number already stored in P(2).


P(2)= P(2)+ 1
=3+1
=4
VII. Suppose everyone moves out of the apartment block because of
renovations. Zero must now be stored in each element of the
array. This can be accomplished by the following statements.

40 LET P(U=0
50 LET P(2)=0
60 LET P(3)=~
70 LET P(4)=0
ONE-DIMENSIONAL ARRAYS 281

However, an easier method is to use a FOR/NEXT loop, particularly


when zero (or any other number) must be assigned to many
elements of the array.

40 FOR 1=1 TO 4
50 LET P(l)=0
60 NEXT I

As the index I changes from 1 to 4, the subscript of array P also


changes from 1 to 4. Each time the computer passes through the
loop, a subscripted variable is assigned a value of zero; first P(1),
then P(2), then P(3), and finally P(4).
VIII. This is the third stage of the program that was started in Section
7.1, page 256.

Item Quantity Unit Price


1 2 $4.50
2 4 3.00
3 5 2.25
4 3 5.15
Again the READIDATA statements will be used to store the quantities in
array Q and the unit prices in array U. Here are several programs that
calculate the extended cost of each item.

1. This program uses two FOR/NEXT loops:

(a) The first loop reads and prints the data.


(b) The second loop calculates and prints the extended
cost of each item.
Extended Cost of Each Item = Quantity x Unit Price

10 DIM Q(4),U(4)

100 REM READ AND PRINT THE DATA


lUI PRINT
120 FOR 1=1 TO 4
130 READ Q(I),U(I)
14~ DATA 2,4.50,4,3.00,5,2.25,3,5.15
150 PRINT Q(I),U(I)
160 NEXT I

2~H" REM CALCULATE AND PRINT THE


201 REM EXTENDED COST OF EACH ITEM
210 PRINT
220 FOR J=l TO 4
230 LET C=Q(J)*U(J)
240 PRINT C
250 NEXT J
999 END
282 PROGRAMMING IN BASIC

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

The following programs are quite different from Program 1.


They place the extended costs of the items in a separate
array. First you will be shown two versions of a program . The
differences between the first three programs will then be
reviewed.

2 This version uses two FOR /NEXT loops:


(a) The first loop reads and prints the data and calculates
the extended cost of each item .
(b) The second loop prints the costs .

100 REM READ AND PRINT THE DATA


101 REM CALCULATE THE COSTS
110 PRINT
120 FOR 1=1 TO 4
130 READ Q(I)1U(I)
140 DATA 2,4.50,4,3.00,5,2.25,3,5.15
150 PRINT Q(I),U(I)
160 LET C(I)=Q(I)*U(I)
170 NEXT I
200 REM PRINT THE COSTS
210 PRINT
220 FOR J::::l TO 4
230 PRINT C ( J ) ,
240 NEXT J

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.

The first time through the loop 1= 1


C(1) = 0(1) * U(1)
2 * 4.5
9

C(1) C(2) C(3) C(4)


9
The second time through the loop 1= 2
C(2) = 0(2) * U(2)
4 *3
= 12

C(1) C(2) C(3) C(4)


9 12
The third time through the loop 1= 3
C(3) = 0(3) * U(3)
5 * 2.25
= 11.25

C(1) C(2) C(3) C(4)


9 12 11.25
The fourth time through the loop 1= 4
C(4) = 0(4) * U(4)
3 * 5.15
= 15.45

C(1) C(2) C(3) C(4)


9 12 11 .25 15.45
3. This version uses one FOR/NEXT loop to do everything-
read , calculate, and print.

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

Now look at the differences . Program 2 prints the extended costs


after they have all been calculated. This is possible, since each cost is
stored in its own location and may be referenced any time after it is
calculated (before the END statement). Using the four subscripted
variables C(1), C(2), C(3) , and C(4) gives four different storage
locations. It is impossible to print the costs this way in Program 1,
where each result was stored in variable C . In Program 1, the
contents of C had to be printed immediately after the cost was
calculated , since each stored cost (except the last one) was replaced
by a new one.
Program 3 is something like Program 1, in that the extended costs
are printed right after each one is calculated. However, there is a
difference. When the loop is complete in Program 3, all the costs are
retained because each is stored in its own subscripted variable. In
Program 1, all that is left in variable C at the end of the second loop is
the last cost, since the previous values in C were continually replaced
by new ones.

4. The output of Programs 2 and 3 may cause some confusion


as to the meaning of the numbers . Shown below is a differ-
ent version of Program 3. Strings are printed to indicate what
the various numbers represent.

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

7.3 CALCULATING WITH ARRAYS- Your


Turn
I. This is the final extension of the problem that appeared in
Sections 7.1 and 7.2. In this section, you are to calculate the
yearly interest on an investment of $4000, using the rates shown
below.

No. of Years Rate of Interest


10 12%
15 13%
20 15%

(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)

1. Complete line 40 with a PRINT statement.


2. Which statement should be coded in line 60?

(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)

3. Complete line 70 with a DATA statement.


4. Which statement should be coded in line 80?

(a) LET I<J)=A*V(J)


(b) LET l ( J) =A*R (.J)
(c) LET YLJ)=ILl:'*A
(d) LET A=Y(J)*R(J)
(e) LET A=I(J)*Y(J)

5. Complete lines 100, 110, and 120 with PRINT statements.


6. Complete line 130 with a NEXT statement.

II. A retailer is allowed a 3% discount on accounts that are paid


within 10 days , 2% if they are paid within 20 days, and no
discount if they are paid on the due date . Find the amount of
discount for each of the three conditions on an account that has a
balance of $2000.

(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.
- - - - - - - - - - - - - - - --.------.

288 PROGRAMMING IN BASIC

RUN

ACCOUNT BALANCE: 2~0e

RATE OF DISCOUNT: .03


AMOUNT OF DISCOUNT: 60
RATE OF DISCOUNT: .~2
AMOUNT OF DISCOUNT: 4~
RATE OF DISCOUNT: 0
AMOUNT OF DISCOUNT: 0

III. Rewrite the above program. This time use the INPUT statement to
enter the rates. 3

RUN

ACCOUNT BALANCE: 20e0


RATE OF DISCOUNT? .03
AMOUNT OF DISCOUN1: 60 '
RATE OF DISCOUNT? .02
AMOUNT OF DISCOUNT: 40
RATE OF DISCOUNT? 0
AMOUNT OF DISCOUNT: e

7.3 CALCULATING WITH ARRAYS-Solutions


for "Your Turn"
I.

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

110 PRINT "RATE: ;RU)


I

1221 PRINT "INTEREST:";I(J)


6. 1321 NEXT J

II. Using the READ/DATA statements

211 REM R--RATE OF DISCOUNT


212 REM D--DISCOUNT
213 REM B--ACCDUNT BALANCE
121 DIM R(3) ,D(3)
20 LET B=2e~~
321 PRINT
421 PRINT "ACCOUNT BALANCE:";B
521 FOR 1=1 TO 3
621 READ R(I)
721 DATA .03,.212,0
821 LET D(I)=R(I)*B
921 PRINT
lee PRINT "RATE OF DISCOUNT:";R(I)
1121 PRINT "AMOUNT OF DISCOUNT:";D(!)
1221 NEXT I
999 END

III. Using the INPUT statement

211 REM R--RATE OF DISCOUNT


212 REM D--DISCQUNT
213 REM B--ACCOUNT BALANCE
HI DIM R(3) ,[1(3)
221 LET B=2eee
321 PRINT
421 PRINT "ACCOUNT BALANCE:";B
521 FOR 1=1 TO 3
621 PRINT
721 PRINT "RATE OF DISCOUNT";
821 INPUT R(I)
921 LET D(I)=R(I)*B
12121 PRINT "AMOUNT OF DISCOUNT:";D(I)
1121 NEXT I
999 END
290 PROGRAMMING IN BAS IC

7.4 A SORTING PROGRAM


A different version of a wage program was listed in each of Chapters
Three , Five, and Six. The calculation of payroll is usually computer-
ized in many business firms that have computers, particularly if the
payroll is large. Another program that is often used is one that sorts
numbers or names. Shown below is a program that sorts numbers in
ascending order. In Chapter Twelve, you will be asked to write a
program that sorts names alphabetically.

01 REM A--ARRAY THAT STORES THE DATA


02 REM T--TEMPORARY STORAGE
HI DIM A(6)

100 REM READ THE NUMBERS


110 FOR 1=1 TO 6
12£1 READ A(I)
130 DATA 4,2,1,5,6,3
14£1 NEXT I

200 REM SORT THE NUMBERS


210 FOR L=l TO 6
220 FOR J=l TO 5
230 IF AeJ)(=A(Jt1) THEN 270
240 LET T=A(J)
250 LET A(J)=AeJt1)
260 LET AeJt1)=T
270 NEXT J
280 NEXT L
300 REM PRINT THE SORTED NUMBERS
310 PRINT
320 FOR K=l TO 6
330 PRINT ~d K)
340 NEXT K

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

Line 210 - Sets up a loop to sort through the numbers 6 times.


Line 220 - Sets up a loop to sort two adjacent numbers each time the
computer passes through the loop. The test value must be one
number less than the number of data items, since the number stored
in J will be compared with the number stored in J+1. If the numbers
are already in order, no exchange is made; if they are not in order, the
two numbers must be interchanged. To perform this, the concept of
copying the content of a storage location and placing the value in
another location is used. The exchange of two numbers must be done
in three stages. At this point L, the index of the outer loop, is 1. The
numbers are currently stored in this order : 42 1 563. The following is
an explanation of one entire J cycle.

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

back to line 220 by branching first to line 270 (NEXT J) . The


order of the numbers remains t t
2 1 4 5 6 3.
IV. The fourth time through the loop J=4. A(J)is actually A(4) and
A(J+1) is actually A(5). Line 230 is true, since 5 is less than 6.
Therefore, no interchange is made and control is transferred
back to line 220 by branching first to line 270 (NEXT J) The
order of the numbers remains t .J.,
2 1 4 5 6 3.
V. The fifth time through the loop J=5. A(J) is actually A(5) and
A(J+ 1) is actually A(6) . Line 230 is false , since 6 is not less than
3. Therefore, 6 and 3 must be interchanged.

1. Place the 6 in temporary storage . LET T = A(5 )


T A(5) A(6)
6 6 3
t I
2. Place the 3 in location A(5) . LET A(5)= A(6)

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.

1. One loop may perform all three operations.


2. One loop may read and print the data, while another performs the
calculations and prints the results.
3. One loop may just read the data, while a second performs all the
other operations.
4. Three loops may exist, each loop performing one of the three
operations.

By now, you have probably thought of other combinations.


Perhaps the best way to illustrate the difference between the use of
subscripted variables and simple variables is by looking at sample
programs. The two programs below are actually quite similar; the
difference is in the retention of values. Trace through the logic of each
program. The problem is one you had in Chapter Four (Review
Problem 6, page 146).
Find the largest sale made by one salesperson whose sales are:
$8700,$6300,$9400,$7600,$8500.
(a) Use the READIDATA statements to enter the sales.
(b) In a FOR/NEXT loop, enter and print the data and find the largest
sale.

1. Using a Simple Variable

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

THE LARGEST SALE IS: 9400

2. Using Subscripted Variables

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

THE LARGEST SALE IS: 9400

Program 1 assigns each sale to one variable - the variable 5. Each


time a value is read, the sale currently in storage is replaced by the
new one . This means that the contents of 5 must be printed before a
new item is entered. Printing the contents of 5 after all sales have
been entered will give you only the last value , since all previous
values have been continually replaced by new ones . As there is only
one storage location for all the sales , a value is referenced by using
just the simple variable 5
Program 2 stores each sale in its own storage location : 5(1) , 5(2),
5(3),5(4),5(5) . To reference a particular value , the array name must
be used along with its subscript. Since no values are lost as each new
one is entered, there is no need to print each item of data as it is
stored (although Program 2 does it in this way just to show you how
296 PROGRAMMING IN BASIC

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.

Questions and Exercises


1. What is a one-dimensional array? How are the items of an array
arranged in the computer's memory?
2. What is a subscripted variable?
3. What is the difference between the variable P3 and the variable
P(3)?
4. (a) Display and name the different parts of the DIM statement.
(b) What is the purpose of the DIM statement?
(c) What three restrictions must be observed when using the
DIM statement?
5. Why is it not necessary to dimension an array of less than ten or
eleven elements on some computer systems?
6. Write two BASIC programs, each storing ten data items (numbers
1 to 10 inclusive) in the array A.
(a) Use the INPUT statement in one program to enter the data.
(b) Use the READ/DATA statements in the other program.
7. Write two BASIC programs, each reading the following data into
two arrays.

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

10. Show the RUN of each of the following program segments.


Assume that the data items 2, 5, 1, 4 have already been entered
into the computer.

(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

11. Code one or more statements to perform the following opera-


tions on array D that consists of six elements . Assume that the
data items have already been entered .

(a) Replace the third element by the number 7.


(b) Copy the element in the first storage location by placing the
value in the fifth location of the array .
(c) Subtract the first element from the fourth . Store the result in
the first location of the array.
(d) Increase the sixth element by 2.
(e) Find the sum of all six elements of the array. Use a FOR/ NEXT
loop. Store the result in a simple numeric variable.
(f) Multiply each of the six elements of the array by 2 and place
each product in the array E. Use a FOR/NEXT loop.
(g) Print the contents of the even-numbered locations of the
array on one line closely spaced.
(h) Initialize all six elements to zero. Use a FOR/NE XT loop.

12. What is the output of each of the following programs?

(a) 10 [11M A(3),B(3)


20 PRINT
30 FOR 1=1 TO 3
40 READ A(I),B(l)
50 [lATA 2,8,3,27,4,64
60 PRINT A(l),B(l)
70 NEXT I
99 END

(b) 10 DIM A(3),B(3)


20 PRINT
30 FOR 1==1 TO 3
40 READ A( I)
50 PRINT A( I ) ,
60 NEXT I
70 PRINT
80 FOR J=l TO 3
90 READ B(J)
100 PRINT B( J) ,
110 NEXT J
120 DATA 2,3,4,8,27,64
999 END
ONE-DIMENSIONAL ARRAYS 299

(c) 10 DIM A(3) ,B(3) ,C(3)


20 PRINT
30 FOR 1=1 TO 3
40 READ {~(1),B(1)
50 DATA 3,5,6,4,2,20
60 PRINT A( 1) ,[1 ( 1)
70 NEXT I
80 PRINT
90 FOR J:::1 TO 3
100 LET C(J)=A(J)*B(J)
110 PRINT C(J)
120 NEXT J
999 END
(d) 1111 DIM A(3) ,B(3) ,C(3)
2£1 PRINT
30 FOR 1=1 TO 3
40 READ A(1),£\(1)
50 DATA 3,5,6,4,2,20
60 LET C(l)=A(J)*B(J)
70 PRINT A(l),B(I/,C(J)
80 NEXT I
99 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.

(a) 10 DIM A(10)


20 FOR J=l TO tel
READ J(A)
30
40 DATA - , - , - ,
50 NEXT J
......
99 END

(b) H'I DIM M( 16) ,N(20)


20 FOR 1=1 TO 16
30
40
READ M (1)
DATA - , -. , - ,
50 NEXT I
......
100 FOR J=l TO 14
11111 READ N(J)
120 DATA -,-,-, ......
130 NEXT J

999 END
300 PR OGRAMMING IN BAS IC

(c) 10 DIM X(3) ,Y(3)


20 PRINT
30 FOR K=1 TO :3
40
50
60
READ X(I() ,Y(K)
DATA - , - , - ,
PRINT X,Y
......
"70 NEXT K

999 END

(d) 10 DIM A(4),B(5)


20 FOR 1=1 TO c:'J
30 READ A(l),B(l)
40 DATA 1,6,2,7,3,8,4,9,5,10
50 NEXT I

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

(a) 10 DIM A(5)


20 FOR 1=1 TO 5
30 READ A(I)
40 DATA 4,8d2,16,20
50 NEXT I

99 END

(b) 10 DIM X(3) ,Y(3)


20 FOR 1=1 TO 3
30 READ X(l),Y(I)
40 DATA 4,8,12,16,211"24
50 NEXT I

99 END

(c) HI DIM X(3) ,Y(3)


20 FOR 1=1 TO 3
38 READ X(I)
40 NEXT I
ONE-DIMENSIONAL ARRAYS 301

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

TOTAL COST 47.7

Programming Problems 2 to 6 are problems you had in previous


chapters. This time you will be using subscripted variables instead of
simple numeric variables.
ONE-DIMENSIONAL ARRAYS 303

2. Chapter 5, Section 5.4, Page 171


Find the average of the four numbers 67 , 85, 79, 93.
(a) Use the READ statement to store the number of numbers in a
simple variable . Use this variable as the test value in your FOR
statement.
(b) Use another READ statement to store the numbers in an array.
(c) Use one DATA statement.
(d) Use one FOR/NEXT loop to perform the following:
(i) Read the numbers.
(ii) Accumulate the sum in a simple numeric variable.
(iii) Print each number along with the accumulated sum.
Sum of Numbers
( e ) A vera g e - -:-;-:--:-=-='7-'---=-;-;-:'-'-;-;c-;---"---;---
- "Number" of Numbers

RUN

67 c" "
85 1 .J.;..
C'~,

79 231
93 324

THE AVERAGE IS: 81

3. Chapter 6, Section 6.1, Page 202


A retailer is allowed a cash discount of 2% if the store's accounts are
paid within 10 days. Suppose the retailer takes advantage of this cash
discount when three accounts are cleared with balances of $450,
$600, and $240 . Find the discount and the amount remitted (paid) on
each account.
(a) Use the INPUT statement to store the account balances in an
array.
(b) Store the discounts and the amounts remitted in two separate
arrays.
(c) Use one FOR/NEXT loop to:
(i) Enter the data.
(ii) Calculate the discount and the amount remitted on each
account.
(iii) Print the information as shown in the RUN. (Hint: Use the
index as your account number.)
(d) Discount = Balance x .02
(e) Amount Remitted = Balance - Discount

Using the INPUT Statement Using the READ/DATA Statements

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

ACCOUNT: 2 ACCOUNT: "-")

BALANCE~ 600 BALANCE: 6f,H~


DISCOUNT: 12 DISCOUNT: 1 .-)
"-
AMOUNT REMITTEII! 588 AMOUNT REMITTED: 588
ACCOUNT: 3 ACCOUNT: 3
BALANCE? 240 BALANCE: 24111
DISCOUNT: 4.8 DISCOUNT: 4.8
AMOUNT REMITTED: 235.2 AMOUNT REMITTED: 235.2

4. Chapter 6, Review Problem 1, Page 242


Write a program that converts weekly wages of $350, $400, $450,
and $500 to hourly rates based on a 40-hour week_
(a) Use the READ/DATA statements to store the weekly wages in an
array_
(b) Store the hourly rates in another array_
(c) Use two FOR/NEXT loops:
(i) One to read and print the data and to calculate the hourly
rates.
(ii) The other to print the hourly rates.
Weekly Wages
(d) Hour Iy Rate = 40

RUN

WEEKLY WAGES!
350 400 45111 500

HOURLY RATES:
8.75 10 11.25 12.5

5. Chapter 4, Review Problem 3, Page 144


Write a program that determines the balance of a customer's account
after each of the following transactions . There is no previous balance.
Codes are used to indicate whether the transaction is a purchase or a
payment.

Purchase . .. ........ $250


Payment ........... 150
Purchase . . . . . . . . . .. 300
Payment ... . ....... 200

(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

(c) Use one FOR/ NE XT loop to


(i) Read the data.
(ii) Calculate the balance .
(iii) Print the information as shown in the RUN .
(d) Use an ON ... GO TO statement for multiple branching .
(e) Use a code of 1 if the transaction is a purchase, a code of 2 if a
payment is made .
(f) Depending on your code :
Balance = Balance + Purchase
or
Balance = Balance - Payment

RUN

CODE, AMOUNT: 1 25121


BALANCE: 25l!1
CODE, AMOUNT: 2 150
BALANCE: 10l!1

CODE, AMOUNT: 1 300


BALANCE: 40121
CODE, AMOUNT: 2 20121
BALANCE: 200

Problem 5
C CODE (INDEX)
A AMOUNT OFTRANSACTION
B BALANCE

( Start

'V
)
DIM
C,A

'V

B=0

!

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

6. Chapter 4, Review Problem 2, Page 142


Employees working for the XYZ Manufacturing Company are paid on
the basis of the number of parts produced. If the rate is $2 per part ,
find the incomes of the following three employees using the weekly
record given below.
ONE-DIMENSIONAL ARRAYS 307

Employee Number Number of Parts Produced


49 160
67 158
52 162

(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

Using the INPUT Statement Using the READ/DATA Statements

RUN RUN

EMPLOYEE, PARTS? 49,160 EMPLOYEE, PARTS: 49 160


INCOME: 320 INCOME: 320

EMPLOYEE, PARTS? 67,158 EMPLOYEE, PARTS: 67 158


INCOME: 316 INCOME: 316
EMPLOYEE, PARTS? 52,162 EMPLOYEE, PAins: 52 162
INCOME: 324 INCOME: 324

The remaining four problems are new.

7. Write a program that squares the even numbers from 12 to 20


inclusive.

(a) Use one FOR/NEXT loop to


(i) Generate the numbers in the FOR statement. (Hint: You
will need a STEP clause.)
(ii) Square the even numbers (the values of the index) and
store the results in an array.
(iii) Print the original (even) numbers.
(b) Use another FOR/NEXT loop with the same initial, test, and
step values to print the contents of the array.
(c) Note: Although you will be using only five storage locations
in the array, 20 locations must be dimensioned. This is
because the DIM statement reserves adjacent storage loca-
tions starting at location number one (or zero, depending on
the computer system being used). Each location is num-
bered one higher than the previous location. When the value
of the index is 20, the square of 20 is stored in the twentieth
storage location of the array.
Problem 8 conserves memory by reading in the numbers,
rather than using the values in the FOR statement as data.
308 PROGRAMMING IN BASIC

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

xx LET P(J) = N(I) *N(J)


assuming that the index of the outer loop is I and the one for
the inner loop is J. The first time through the I loop, 12 is
multiplied by each of the numbers in the array. This is
performed (and the results printed) during the J cycles to
produce the following.

144168192216240

Control enters the I loop and the second number (14) is


multiplied by all the numbers in the array during the passes
through the J loop. The output produced so far is as follows.

144168192216240
168 196 224 252 280

This continues until I is greater than 5, at which time looping


terminates.
(c) Print each product immediately after it is calculated. Remem-
ber to code a semicolon after the PRINT statement and to
place a blank PRINT between the NEXT statements in order to
produce the output shown below.

RUN

144 168 192 216 240


168 196 224 252 28e
192 224 256 288 320
216 252 288 324 3bB
240 280 32e 36e 400
ON E- DIMENSI ONA L A RRAYS 309

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

9. Write a program that checks the contents of two arrays to see


whether or not a common number is stored in both arrays. If it is ,
print the number.

Array A contains the numbers 1,3,4,5,7 ,8 .


Array B contains the numbers 9,7,6,5 ,3 ,2 .
(Hint : Have the computer compare each number in array A with
al/ of the numbers in array B. The first comparison is when A= 1.)

A=1
B = 9,7,6,5 ,3 ,2

If a 1 is found in array B, have the computer print it, otherwise, no


printing takes place. Now do the same for the second number in
array A.

A=3
B = 9,7, 6,5,3,2

This time a 3 is found in array B. The number 3 is printed. To


perform the above routine, you need two loops -an outer one to
access the elements of array A and an inner one to access all the
elements of array B for each one of array A. Your main statement
will be

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

ARRAY A 8 ARRAY It ';"-

NO. IN BOTH ARRAYS: 3


NO. IN BOTH ARRAYS: 5
NO. IN BOTH ARRAYS: 'J
ONE-DIMENSIONAL ARRAYS 311

Problem 9
A ARRAY A
B - ARRAY B

( Start

\JI
)
DIM
A,B

FOR 1= 1 TO 6

FOR K=1 T06


K>6 t::\.
~

'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

Array C now contains a series of tens.

(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)

assuming that the index for this loop is I.

RUN

ARRAY A ARRAY B ARRAY C


1 9 1~
3 7 UI
4 6 1~
5 5 10
7 3 HI
8 2 HI
TWO-DIMENSIONAL ARRAYS 313

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.

8.1 STORING DATA IN ARRAYS


Chapter Seven introduced you to a one-dimensional array. This type
of an array can be thought of as a list of numbers arranged either
horizontally (in a row) or vertically (in a column).

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

1 2 3 4 <E---- Two rows 1 5


5 6 7 8 Four columns 2 6 ~ Four rows
3 7 Two columns
4 8
As in Chapter Seven, something tangible will be used as an
analogy. Suppose a library is located not far from where you live.
Books are stored on long shelves and the shelves are partitioned into
sections. Although there are many more bookshelves in the library
than the number used in this illustration, assume that there are three
shelves and that the shelves are partitioned into four sections, giving
a total of twelve storage areas. Each storage area holds a different
type of book; for example, history books may be stored on the top
shelf in the first section, science-fiction books may be stored on the
top shelf in the second section, autobiographies may be stored on the
top shelf in the third section, etc. In keeping an inventory of the books,
the librarian records the number of the shelf and the number of the
section where a specific type of book is kept. A two-digit number is
used; the first digit denotes the number of the shelf (the row) and the
second digit represents the number of the section (the column). The
storage areas are numbered as follows.
The storage areas on the first shelf (row) are numbered 11, 12, 13,
14.
Column 1 Column 2 Column3 Column4
Row 1
11 12 13 14
Notice that the row is listed first, then the column.
1 1 1 2 1 3 1 4
t t t t t t t t
Row Column Row Column Row Column Row Column
The storage areas on the second shelf (row) are numbered 21, 22,
23,24.
Column 1 Column 2 Column 3 Column 4
Row 2 L __--'-_ _ _ --'-___--'-___- - '
21 22 23 24
The storage areas on the third shelf (row) are numbered 31, 32, 33,
34.
Column 1 Column 2 Column 3 Column 4
Row3
31 32 33 34
Shown below are the twelve storage areas in the library. The library is
named the Roxvale Park Library.

ROXVALE PARK LIBRARY


Column 1 Column 2 Column 3 Column 4
Row 1
Row2
Row3
TWO-DIMENSIONAL ARRAYS 315

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

The array name must be unique - no two-dimensional arrays may


have the same name. Moreover, it is best not to name a two-dimen-
sional array and a one-dimensional array the same, although some
systems allow this. The rule may also apply to a two-dimensional
array and a simple variable. Again, check your manual.
The current number of books in each storage area is as follows.

ROXVALE PARK LIBRARY


Column 1 Column 2 Column 3 Column 4
Row 1 3 2 0 1
Row2 1 0 2 3
Row3 2 4 0

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

H'! DIM R(3,4)


2f1 FOR 1=1 TO 3 -Rowloopontheoutside .
30 FOR J=l TO 4
40 READ R(I,J)
50 DATA 3,2,~,1
6e DAT A 1 d~, 2 ,3 -Items listed by rows.
7e DATA 2,4,1!B
8e NEXT J
9B NEXT 1
99 END

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.

40 READ R(I,J) means READ R(1, 1)


50 DA TA(3),2,0, 1

Column 1 Column 2 Column 3 Column 4

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.

The second time through the J (column) loop, 1= 1 and J = 2. In line


40, R(I,J) is actually R(1,2). The number 2 is stored in the first row,
second column.

40 READ R(I,J) means READ R(1 ,2)


50 DATA 3~0,1
TWO-DIMENSIONAL ARRAYS 317

Column 1 Column 2 Column 3 Column 4

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.

40 READ R(I,J) means READ R(1 ,3)


50 DATA3,2~1

Column 1 Column 2 Column 3 Column 4

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.

40 READ R(I,J) means READ R(1 ,4)


50 DATA 3,2,O(1)

Column 1 Column 2 Column 3 Column 4

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 .

40 READ R(I,J) means READ R(2,1)


READ R(2,2)
318 PROGRAMMING IN BASIC

READ R(2,3)
READ R(2,4)
60 DATA 1,(j,2,3

Column 1 Column 2 Column 3 Column 4

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.

40 READ R(I,J) means READ R(3,1)


READ R(3,2)
READ R(3,3)
READ R(3,4)
70 DATA 2,4,1,(j

Column 1 Column 2 Column 3 Column 4

Row 1 3 2
Row 2 2 3
Row3 2 4

The 1 cycle is now complete and control is transferred to the END


statement.
Did you notice that the numbers are stored by rows? The first row is
filled, then the second row, and finally the third row. This is because
the 1 loop (which represents rows) is placed on the outside, while the
J loop (which represents columns) is placed on the inside.

2~ FOR 1=1 TO 3 - Row 'Ioop on the outside.


30 FOR J=l TO 4 - Column loop on the inside .

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).

An alternative method for storing the numbers is by columns.

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

This program differs from the previous one in two ways:


1. The loops are interchanged . The J (column) loop is on the
outside, while the 1 (row) loop is on the inside .
2. The data items in the DATA statement are listed by columns rather
than by rows.

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.

40 READ R(I,J) means READ R(1,1)


50 DATACl\1,2
320 PROGRAMMING IN BASIC

Column 1 Column 2 Column 3 Column 4


Row 1 3
Row2
Row3

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.

40 READ R(I,J) means READ R(2,1)


50 DATA3ffi2

Column 1 Column 2 Column 3 Column 4


Row 1
Row2
Row3 E~ I
The third time through the 1 (row) loop, 1= 3 and J = 1. In line 40, R(I,J)
is actually R(3, 1). The number 2 is stored in the third row, first column.

40 READ R(I,J) means READ R(3,1)


50DATA3,1(2j

Column 1 Column 2 Column 3 Column 4

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.

Column 1 Column 2 Column 3 Column 4

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

of the letter of the alphabet ; the second subscript is a/ways the


number of the column. However , the I and J loops were interchanged
which placed the J (column) loop on the outside and in the DATA
statement, the data items were listed by columns rather than by rows.
As with the DATA statements in the program that stores the items by
rows, the DATA statements in this program may also be combined .
Col 1 Col 2 Col 3 Col 4
~ ~ ~ ~
50 DATA I 3,1,2, I 2,0,4 , I 0,2,1, I 1,3,0 I
Shown below are the number of books in each storage area, this time
in the form of a matrix without headings or marginal information .
R
320 1
1 0 2 3
241 0
Here is the way to determine the order of the data items in the DATA
statement if you want to store the matrix as shown above, that is,
R(1,1)=3, R(1,2)=2, R(1,3)=~, R(1,4)=1, R(2,1)=1, etc. The loop
you place on the outside indicates the way the values are to be listed
in the DATA statement. If you have the row loop on the outside , the
data items should be listed by rows ; if you have the column loop on
the outside , the data items should be listed by columns . It doesn 't
matter how the items are stored (by rows or by columns); if the loop
on the outside corresponds with the way the data items are listed, the
end result will be the same.

By Rows By Columns Final Result


3 2 0 1 320 1 3 2 0 1
1 0 2 3 1 0 2 I 1 0 2 3
2 4~ 241 t 2 4 1 0
Suppose you had the row loop on the outside but listed the data items
by columns.

20 FOR 1=1 TO 3
3B FOR J=l TO 4

What will now be stored in the array?


R
3 1 2 2
o 4 0 2
1 1 3 0
In the above matrix R(1,1)=3, R(1,2)=1, R(1,3)=2, R(1,4)=2,
R(2, 1)=~, etc . This is not the same as the original matrix.
322 PROGRAMMING IN BASIC

Perhaps it should be pointed out that matrices are not actually


organized as such in the computer. They are stored as lists. However ,
users find matrices the most convenient way to think of and to
manipulate large amounts of data.
Now look at the DIM statement. Notice that it has two subscripts
which are separated by a comma. The first subscript reserves a
sufficient number of storage locations for the rows; the second
subscript reserves a sufficient number of locations for the columns.
10 DIM R ( 3 4 )
i i T
Name Number Number
of the of of
array rows columns
In this DIM statement, twelve storage locations have been reserved
(3x4=12) . You may reserve more locations than you need for either
the rows or the columns, but you may not reserve less. On some
computer systems, the DIM statement is not required if each subscript
is less than 11 . The computer will automatically reserve these loca-
tions. However, if one of the subscripts is greater than 10, the DIM
statement must be used. As mentioned in Chapter Seven, it is best to
dimension every array yourself. You should also note , as you go over
the various programs presented in this chapter, that doubly sub-
scripted variables are used the same way as simple variables-
they're just named differently. One more comment before going on to
some sample programs. In many versions of BASIC, the numbering of
the rows and the numbering of the columns start at zero.

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.

8,1 STORING DATA IN ARRAYS-Sample


Programs
As in the first section in Chapter Seven, these sample programs will
not give you any output (except for the prompts in the second
program) , since the programs Just store the data and do not print it.
TWO-DIMENSIONAL ARRAYS 323

I. In this program, the RE AD/DATA statements are used to store


values in a 2x 3 array by rows. Here is the data to be stored in
array A.
A
10 20 30
40 50 60

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

VALUE FOR A(I,j>? 1111


VALUE FOR A(I,J)? 40
VALUE FOR A(I,J)? 20 - Values entered by columns.
VALUE FOR A(I,J>? 50
VALUE FOR A(I,J>? 30
VALUE FOR A(I,j>? 60

III. Here is a problem that will be completed in three stages:

1. In Section 8.1, the data is stored .


2. In Section 8.2, the data is stored and printed .
3. In Section 8.3, the data is stored and printed and a summa-
tion routine is performed .
324 PROGRAMMING IN BASI C

A department store has two storerooms in which it keeps various


styles of shoes . Suppose each room has three shelves with the
shelves partitioned into three sections, giving a total of nine
storage locations . The storerooms contain identical stock in
corresponding locations . For example, in both storerooms, style
A of shoe is stored on the top shelf, first section; style B is stored
on the top shelf, second section; style C is stored on the top
shelf, third section, etc. An inventory is taken and the following
number of pairs of each style of shoe is recorded.

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

(a) READ/DATA statements are used to enter the data by rows.


(b) Two programs are written :
1. The first program stores the data in arrays A and B, using
a separate set of nested FOR / NE XT loops for each array.
2 . The second program uses one set of nested FOR/NE XT
loops to store the data into both arrays.

1. Using two sets of nested FOR/NEXT loops

100 REM STORE DATA IN ARRAY A


110 FOR 1=1 TO 3 - Row loop on the outside .
120 FOR J:::l TO 3
130 READ A(I,J)
140 DATA 1,2,3
158 DATA 4,5,6 -Items listed by rows.
168 IIATA 7,8,9
178 NEXT J
180 NEXT I

200 REM STORE DATA IN ARRAY B


218 FOR 1\=1 TO 3 - Row loop on the outside .
220 FOR L==l TO 3
23121 REArl B(I(,L)
24121 DATA 9,8,7
250 DATA 6,5,4 -Items listed by rows.
268 DATA 3,2, 1
27121 NEXT L
28£1 NEXT 1\

999 END
TWO-DIMEN S IO NAL ARRA YS 325

In this program , each array is filled by means of a separate routine .


The first set of loops stores data in array A. When this is complete , the
second set of loops stores data in array B. It is possible to combine all
DATA statements , provided the " combined" statement is not too long.
The listing of the data, however, must be in proper order. All of the
data for A must be listed first , followed by the data for B. As mentioned
in the previous chapter , some computer systems allow this statement
to be placed anywhere in the program , while others insist that it be
placed after the DI M statement and /or before the EN D statement.
290 DATA 11 ,2,3,4,5,6 ,7,8,9 1, 19 ,8,7 ,6,5 ,4,3 ,2,1 1
i i
Data for Array A Data for Array B

2. Using one set of nested FOR/NEXT loops

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

A(3,1) ~ 8(3 ,1) ~


A(3,2) 8 8(3,2) 2
A(3,3) 9 8(3,3) 1
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 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

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.

Data for Array A

140 DATA 1,2,3


15£1 DATA 4,5,6
160 DATA 7,8,9
TW O- DIMEN S IO NAL ARR AYS 327

Data for Array B

240 DATA 9,8,7


250 DATA 6,5,4
260 DATA 3,2,1

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.

Data for Arrays A and B

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 -,--,-,-

8,1 STORING DATA IN ARRAYS- Your Turn


I. Identify the errors, if any, in the program segments shown below .
Make the necessary corrections.

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

2111 FOR J::1 TO 3


30 FOR 1=1 TO 3
40 READ B( Jd)
50 DATA - , - , - , t • • t • + (9 items of data)

100 NEXT I
110 NEXT J
999 END

3. if:'! DIM C(3,2) ,II(3,2)


20 FOR J=l TO 2
30 FOR 1=1 TO 3
40 READ C(I,J),D(I,J)
5111 DATA -,-,-,+ ...... (6 items of data)

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

6. In the following program segment , the data items are to be


stored in their respective array s by rows .

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 .

1. How is the data read , by rows o r by co lumns?


2 . What will be stored in the array(s) after ex ecution of each
program? You may show the contents in matri x form . For
example , if there are two 2x 3 arrays , you ma y display the
conte nts in the following manner.

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

(b) 10 DIM M(2,3) ,N(2,3)


20 FOR 1=1 TO 2
30 FOR J=l TO 3
40 READ M(I,J)
50 NEXT J
60 NEXT I
70 FOR K=l TO 2
S0 FOR L=l TO 3
90 READ N(K,L)
330 PROGRAMMING IN BASIC

10~ NEXT L
110 NEXT K
12f! DATA 10,2~,30,40,50960
130 DATA 15,25,35,45,55,65
999 END

(c) 10 DIM M(2,3) ,N(2,3)


20 FOR 1=1 TO 2
30 FOR J=l TO 3
40 READ M(I,J),N(I,J)
5f! DATA 10,20,30,40,5~,60
6f! DATA 15,25,35,45,55,65
7~ NEXT J
8a NEXT I
99 END

(d) Hl DUi M(2,3) ,N(2,3)


20 FOR J=l TO 3
3~ FOR 1=1 TO 2
4~ READ M(I,J),N(I,J)
5a DATA 1~,20,30,40,5a,60
60 DATA 15,25,35,45,55,65
7~ NEXT I
80 NEXT J
99 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.

III. This problem is similar to a problem in the "Your Turn" units of


Chapter Seven. Instead of storing information in two one-dimen-
sional arrays, you are to store the data in two 2x 3 arrays.
Suppose a savings and loan company offers varying rates Clf
interest on investments, depending on the length of time the
money is invested. The data is shown below in matrix form.

No. of Years Rate of Interest

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.

(i) The first program uses two sets of nested FOR/NEXT


loops. One set reads the years into array Y; the other
reads the rates into array R.
TWO-DIMENSIONAL ARRAYS 331

(ii) The second program uses one set of nested loops to


read the data into arrays Y and R. Use one READ state-
ment.
(b) In the program that uses one set of nested FOR/NEXT loops,
explain why the data items in the DATA statement must be
listed in a specific order.

Problem III-Using Two Sets of Nested FOR/NEXT Loops


Y YEARS
R - RATE
, . . - - -- - -- -------- ~~--~------- ----------------------,

( 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

8,1 STORING DATA IN ARRAYS-Solutions


for "You r Turn"
I. 1. There is an insufficient number of storage locations
reserved for the rows . Depending on the program , this may
be corrected in one of two ways .
(a) Exchange the subscripts of the subscripted variable A in
the DIM statement.

(b) Interchange the test values in the two FOR statements.

HI [11M A(4,:i)
20 FOR 1=1 TO 4
30 FOR J=l TO 5

2. Nothing is wrong. Notice that the subscripts of 8 are 8(J,I).


In this case, J represents the number of the row, since J is
the first subscript and the first subscript always indicates the
number of the row. 1 represents the number of the column.
The data is read in by rows because J (the row subscript) is
the index of the outer loop.
3. The program runs out of data. There should be twelve items
of data - six values for array C and six values for array D.

50 [lATA -, -, --, •••••• (12 items of data)

4 . In the DIM statement, the array M must have storage loca-


tions reserved for the rows as well as for the columns.
Because the row (I) loop has a test value of 3, the number of
reserved locations for the rows must be at least 3.

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

each pair is stored in array A, and the second member is


stored in array B.

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.

III. (a) Using Two Sets of Nested FOR/NEXT Loops

01 REM Y--YEARS
a2 REM R--RATE
- - - - - - - - - - - - - -

334 PROGRAMMING IN BASIC

1~~ REM STORE YEARS IN ARRAY Y


11 ~ FOR 1=1 TO 2 - Row loop on the outside.
120 FOR J=l TO 3
13~ READ YCI,J)
1.4~ DATA 1~r12d4 -Items listed by rows.
15~ DATA 16,18,2~
16£1 NEXT J
17~ NEXT I

2~fI REM STORE RATES IN ARRAY R


21£1 FOR K=l TO 2 -Rowloopontheoutside.
22f1 FOR L=l TO 3
23f\ READ R(K,L)
24f1 DATA. :10 ~ .11 ~ .12 -Items listed by rows.
25f\ DATA .13,.14,.15
260 NEXT L
270 NEXT K
999 END

Using One Set of Nested FOR/NEXT Loops

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

8.2 PRINTING FROM ARRAYS


This section explains how the contents of a two-dimensional array
can be printed out on a screen or on paper. Below is the program that
stored the number of each type of library book in an array called R.

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

Here are the contents of the array .


Array R
Column 1 Column 2 Column 3 Column 4
Row 1 I 3 2 (/J 1
Row 2 1 (/) 2 3
~--------+---------r---------r-------~
Row 3 2 _ _ _ _ _ __ _4 _ _ _ _ _ _ _ __ __ _L -_ __ __
____ (/J _
~
~
~
~
Suppose you want the computer to print the number of mystery
books . Since mystery books are stored on the third shelf (row) in the
first section (column), simply ask the computer to pri nt the contents of
R(3,1 )

S[lI PRINT R(3d)

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

The coding becomes burdensome with so many elements in the


array. It would be especiall y onerous if there were , say, 100 items in
the array and you wanted to print them al l. As in storing , you can make
use of nested FOR / NEXT loops and make the computer look after the
job of referencing each storage location . Here is another program
TWO-DIMENSIONAL ARRAYS 337

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.

1. Using two sets of nested FOR/NEXT loops

10 DIM R(3,4)

100 REM STORE ITEMS IN AN ARRAY


110 FOR 1=1 TO 3 -Rowloopontheoutside.
120 FOR J=l TO 4
130 READ R(I,J)
140 DATA 3,2,0,1
150 DATA 1,0,2,3 -Items listed by rows .
160 DATA 2,4,1,0
338 PRO G RAMMING IN BASI C

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

2. Using one set of nested fOR/NEXT loops

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

What is the difference in the execution of these two programs? As


in the programs in Chapter Seven , pages 267 and 268 , the program
using two sets of nested FOR/NEXT loops reads in all the data in the first
set of loops, then prints the data in the second set. It completes the
TW O-DIMENSI ONAL ARR AYS 339

READing operation before it starts the PRINTing operation. The pro-


gram using one set of nested FOR/NEXT loops reads one item of data
and prints it right away. It then reads the second item of data and
prints that one. The operations of READ and PRINT alternate within the
inner loop.
Both programs read and print the data items by rows. The READing
and PRINTing of items do not necessarily have to be done this way.
They can be read and printed by columns. In fact, the program that
uses two sets of loops can read the items one way and print them the
other way . The program that uses one set of loops wil l print the data
items the same way as they are read , s ince the REA D and PR INT
statements are within the same set of loops. Here are two more
variations of the program that uses two sets of nested FOR/NEXT loops.
Both read the data by rows, however, the first version prints by rows;
the second one prints by columns. Output for both programs is
printed on one line closely spaced so you can readily see the
difference in the order of the printed items.

1. Prints by rows

HI DIM R(3,4)

100 REM STORE ITEMS BY ROWS


110 FOR 1=1 TO 3 - Row loop on the outside.
120 FOR J=l TO 4
130 READ R(l,~J)
140 DATA 3,2,0,1
150 DATA 1"~,2,3 -Items listed by rows.
160 DATA 2,4,t,0
170 NEXT J
180 NEXT I
200 REM PRINT ITEMS BY ROWS
210 PRINT
220 FOR K=1 TO 3 - Row loop on the outside .
230 FOR L=l TO 4
240 PRINT R(K,L);
250 NEXT L
260 NEXT K

999 END

RUN

3 2 1 1 o 2 3 4 1 121

2. Prints by columns
340 PROGRAMMING IN BASIC

lB0 REM STORE ITEMS BY ROWS


110 FOR 1=1 T,Q 3 -Rowloopontheoutside.
120 FOR J=l TO 4
130 READ R(I,J)
14B DATA 3,2,O,1
150 DATA 1,B,2,3 -Items listed by rows.
160 DATA 2,4,1,0
170 NEXT J
180 NEXT I

2B0 REM PRINT ITEMS BY COLUMNS


210 PRINT
220 FOR L=l TO 4 -Columnloopontheoutside.
230 FOR K=l TO 3
240 PRINT R(K,L);
250 NEXT K
260 NEXT L

999 END

RUN

3 1 2 2 B 4 0 2 1 1 3 ~

8.2 PRINTING FROM ARRAYS-Sample


Programs
What was stored in the sample programs in Section 8.1 will now be
printed.
I. This prog ram uses the READ/DATA state ments to enter val ues into
a 2x 3 array. It uses one set of nested FOR/NEXT loops to store and
print by rows. Here is the data.
A
10 20 30
40 50 60

lB DIM A(2,3) - Reserves six storage locations.


20 PRINT - Leaves a blank line.
30 FOR 1=1 TO 2 - Sets up a loop for the rows.
40 FOR J=l TO 3 - Sets up a loop for the columns.
50 READ A(I,J) - Reads items from the data statement one at a time and stores
the items in array A by rows.
60 DATA lB,2B,3B - Data items listed by rows.
TWO-DIMENSIONAL ARRA YS 341

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

1111 2111 30 4111 5~ 60

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 .

1111 [11M A(2,3) - Reserves six storage locations .


2111 PRINT - Leaves a blank line after the word RUN.
30 FOR J=l TO 3 - Sets up a loop for the columns .
40 FOR 1=1 TO 2 - Sets up a loop for the rows .
50 PRINT ·VALUE FOR A(I,J)"; - Identifies the value of the variable A(I,J) .
I varies from 1 to 2 and J varies from 1 to 3.
60 INPUT A(I,J) - Requests data. User enters the values by
columns .
70 NEXT I - Indicates the end of the row loop.
80 NEXT J -Indicates the end of the column loop .
90 PRINT - Leaves a blank line after the prompts .
100 FOR L=l TO 3 - Sets up a loop for the columns.
110 FOR K=l TO 2 - Sets up a loop for the rows.
120 PRINT A(K,L); - Prints the data by columns on one line .
130 NEXT K - Indicates the end of the row loop .
140 NEXT L -Indicates the end of the column loop.
999 END - Terminates program execution .

RUN

VALUE FOR A(I,J>? 10


VALUE FOR A(I,J)? 40
VALUE FOR A(I,J>? 20
VALUE FOR A(I,J>? 50
VALUE FOR A(I,J)? 30
VALUE FOR A(I,J)? 60

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

(a) RE A D/ DATA statements are used to store the data in arrays A


and B.
(b) Two programs are written .
1. The first program reads and prints by rows . It prints the
contents of the arrays in separate sets of nested
FOR/NE XT loops so that the output of each array is in
matri x form .
2. The second program reads and prints by columns ,
using one set of nested FOR/ NE XT loops .

1. Reads and prints by rows

10 DIM A(3,3),B(3,3)

100 REM READ THE DATA


110 FOR 1=1 TO 3 - Row loop on the
outside .
120 FOR J=l TO 3
130 READ A(I,J),B(I,J)
140 DATA 1,9,2,8,3,7
150 DATA 4,6,5,5,6,4 - Items listed by rows.
160 DATA 7,3,8,2,9,1
170 NEXT J
180 NEXT I
200 REM PRINT NO. OF PAIRS
201 REM IN STOREROOM A
210 PRINT
228 PRINT "STOREROOM A"
230 FOR K=l TO 3 - Row loop on the
outside .
240 FOR L=l TO 3
258 PRINT A(K,L);
260 NEXT L
278 PRINT
280 NEXT K
31in:I REM PRINT NO. OF PAIRS
301 REM IN STOREROOM B
310 PRINT
320 PRINT "STOREROOM B"
330 FOR M=l TO 3 - Row loop on the
outside .
TWO-DIMENSIONAL ARRAYS 343

34~ FOR N=l TO ~~


35~ PRINT B(M,N),
360 NEXT N
370 PRINT
380 NEXT M
999 END

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.

2. Reads and prints by columns

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.

8.2 PRINTING FROM ARRAYS-Your Turn


1. The following questions ask for specific elements to be printed.
Assume that the data has already been entered in a 4x 4 array
named A.
A
1 234
567 8
9 8 7 6
543 2

(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

(c) Write a program segment that prints the elements in the


second row of the array closely spaced . (Hint Use a
FOR/ NEXT loop for the columns and 2 as the subscript for the
row.)

RUN

5 6 7 8

(d) Write a program segment that prints the elements in the


second column of the array one item per line . (Hint: Use a
FOR/NEXT loop for the rows and 2 as the subscript for the
column .)

RUN
.....,
6
8
4

(e) Write a program segment that prints the elements in the


principa l diagonal of the array on one line closely spaced.
The diagonal is shown below .

A
234
5 7 8
9 8 6
543

Notice that the diagonal falls on those elements whose row


numbers and column numbers are the same - that is, where
I=J . Thus , if I=J , the element is to be printed . Use nested
FOR/ NE XT loops th at perform by rows .

RUN

:L 672

2. Is there anyth ing wrong with the following programs? If there is


no error , show t he output ; if there is an error, state what is wrong
and make the necessary corrections . The data is shown below in
matri x form .
346 PR OG RA MMING IN BAS IC

A B
1 2 3 9 8 7
4 5 6 6 5 4

2.

(a) H'I DIM A<2,3)


2111 PRINT
30 FOR 1=1 TO 3
4111 FOR J = l TO ')
~.-

5111 READ A(I,J)


6111 DATA 1,2,3
7111 DATA .lh5,b
8111 PRINT A(I,J);
9111 NEXT J
1111111 PRINT
11111 NEXT I
999 END

(b) 1111 DIM A(2,3),B(2,3)


2111 PRINT
3111 FOR 1=1 TO 2
4111 FOR J=l TO 3
5111 READ (~(I,J),B(I,J)
6111 DATA 1 ,2, 3 , 4 , 5 , 6
7111 DATA 9,8,7,6,5,4
8111 PF::I NT B(I,JH
9111 NEXT J
1111111 PRINT
11111 NEXT I
999 EN[I
(c) 1111 [11M A<2,3) ,B(2,3)
2111 PRINT
3111 FOR 1=1 TO 2
4111 FOR J=l TO 3
5111 READ A(I,J),B(I,J)
60 DATA 1,9,2,8,3,/
7111 DATA 4,6,5,5,6,4
8111 PRINT B(I,JH
9111 NEXT J
1111111 PRINT
11111 NEXT I
12111 PRINT
13111 FOR K=l TO 2
140 FOR L=l TO 3
15111 PRINT A(K,LH
16111 NEXT L
17111 PRINT
lBI1I NEXT K
999 END
TWO-DIMENSIONAL ARRAYS 347

3. This is an extension of the "Your Turn" problem in Section 8.1,


page 330. In this section, you are to print the data in addition to
stori ng it.
Suppose a savings and loan company offers varying rates of
interest on investments, depending on the length of time the
money is invested. The data is shown below in matrix form.

No. of Years Rate of Interest


Y R
10 12 14 .10 .11 .12
16 18 20 .13 .14 .15

Write two programs , each using the READ/ DATA statements to


enter the data.
(a) The first program reads and prints the data by rows in one set
of nested FOR/ NE XT loops.
(b) The second program reads the data by columns but prints it
by rows . Use two sets of nested FOR/ NE XT loops - one to
read the data, the other to print the data. Here is the RUN for
both programs .

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

8.2 PRINTING FROM ARRAYS-Solutions for


"Your Turn"
1.
TWO-DIMENSIONAL ARRAYS 349

(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

2. (a) The test values in the FOR statements should be inter-


changed. Because there are two rows and three columns,
the test value for the I loop should be 2 and the test value for
the J loop should be 3.

30 FOR 1=1 TO 2
40 FOR J=l TO 3

(b) The items in the DATA statement must be listed in pairs so


that the first member of each pair is stored in array A, and the
second member of each pair is stored in array B.

60 DATA 1,9,2,8,3,7
70 DATA 4,6,5,5,6,4

(c) Nothing is wrong.

RUN

987
654
123
456
350 PR OG RAM MING IN BAS IC

3. (a) Reads and Prints by Rows

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

(b) Reads by Columns, Prints by Rows

~H REM 'y--YEARS
02 REM R-'-RATE

100 REM READ BY COLUMNS


110 FOR J=l TO 3 - Column loop on the outside .
120 FOR 1=1 TO 2
130 READ Y(I,J),R(I,J)
140 DATA 111)'.10,16,.13
150 DATA 12,.11,18,.14 -Items listed by columns.
160 DATA 14,.12,2'~,.15
170 NEXT I
180 NEXT J
200 REM PRINT BY ROWS
210 PRINT
220 FOR K=l TO 2 - Row loop on the outside .
230 FOR L=l TO 3
240 PRINT "YEARS";Y(K,L),"RATE";R(K,L)
250 NEXT L.
260 NEXT K
999 END
TW O-DIMEN S IONAL ARRAYS 351

8.3 CALCULATING WITH ARRAYS


How does the computer process data that has been stored in a two-
dimensional array? A number of programs and program segments
concerning the library books in the Roxvale Park Library are listed in
this section to show you how various calculations may be performed.
Recorded below, in matrix form , are the number of books in each
storage area of the library .
R
Column 1 Column 2 Column 3 Column 4
Row 1 I 3 2 0 1
Row 2 1 0 2 3
~--------4---------~---------+--------~
Row 3 2 4
L -_ _ _ __ __ _ ~
0
_ __ _ _ __ __ L_ _ _ _ _ _ _ __ L_ __ __ _ _ _ ~

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

Line 50 is executed as follows .

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.

100 REM STORE AND PRINT THE DATA


lUI PRINT
120 FOR M= 1 TO 3 - Row loop on the outside.
130 FOR N=l TO 4
140 READ RCM,N)
150 DATA 3,2,O,1
160 DATA 1,0,2,3 -Items listed by rows.
170 DATA 2,4,1,O
180 PRINT R(M,N);
190 NEXT N
200 PRINT
210 NEXT M
300 REM CALCULATE AND PRINT THE TOTAL
310 LET T=0
320 FOR 1=1 TO 3 -Row loop on the outside.
330 FOR J=l TO 4
340 LET T=TtR(I,J)
350 NEXT J
360 NEXT I
370 PRINT T
999 END
TWO-DIMENSIONAL ARRAYS 353

RUN

3 2 0 1
~
1 0 .:. 3
2 4 1 ~
19

Here is how the computer accumulates the total.


The first time through the J loop, 1= 1, J = 1, T = 0, and
R(1,1)= 3. The computer adds whatever is currently stored
in T to whatever is stored in R(1 ,1). The result is stored back
intoT.
340 LET T = T + R(I,J)
=T+R(1,1)
=0+3
=3
The second time through the J loop, 1= 1 , J = 2, T = 3, and
R(1 ,2) = 2.
340 LET T = T + R(I,J)
=T+R(1,2)
=3+2
=5
The third time through the J loop, 1= 1, J = 3, T = 5, and
R(1,3)= 0.
340 LET T = T+ R(I,J)
=T+R(1,3)
=5+0
=5
The fourth time through the J loop, 1= 1 , J = 4, T = 5, and
R(1,4)=1.
340 LET T = T+ R(I,J)
=T+R(1,4)
=5+1
=6
The J loop is complete. Control enters the I loop and the
value of I changes to 2 (row 2) . The value of J reverts to 1.
The element in the second row , first column, will now be
added . R(2,1)= 1.
340 LET T = T + R(I,J)
= T+R(2, 1)
=6+1
=7
The inside (J) loop continues until J= 4. At this point T= 12.
Control enters the I loop (row 3) and J goes through its
cycles for the last time. The total eventually reaches 19.
Notice that no subtotals are printed, just the final total after
all calculations have taken place. If you want subtotals, the
354 PROGRAMMING IN BASIC

statement PRINT T must be placed inside both loops (usu-


ally right after the summation ).

30~ REM CALCULATE AND PRINT THE TOTAL


310 LET T==1!l
320 FOR 1=1 TO 3
331!l FOR J=1 TO 4
341!l LET T=TtR(I,J)
350 PR I NT T; - Placed inside both loops .
360 NEXT J
371!l NEXT I

Output for the subtotals only will look like this:


3 5 5 6 7 7 9 12 14 18 19 19
2. This version combines all operations in one set of FOR/NE XT
loops.

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

The next two program segments perform summations-


one adds a row of numbers, the other adds a column of
numbers. Assume that the data has alread y been stored.
IV. Program segment" on page 351 added the number of books
on the first shelf (row). It used explicit numbers as subscripts-
R(1,1), R(1,2), etc. The program segment is rewritten , this time
using a variable to denote the column number.
TW O-DIMENSIONAL ARRAYS 355

4El FOR J==l TO 4


5a LET T=T+R(l,J)
6~ NE~T J t
7 ~ F'R I NT Variable used for the nu mber
8~ PRINT T of the column.

999 END

RUN

Notice that there is no need to use a variable as the subscript for


the number of the row since you remain in row one throughout
the summation. A variable for the column number is needed
because you move from the first column, to the second, third,
and fourth. Thus, a loop is required for the columns only.

V. The program segment shown below finds the total number of


books in the last section (column). This time the column number
remains constant while the row number changes . J = 4 but a
variable is needed for the number of the row . The routine
requires a loop for the changing row numbers .

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

One is added to the number already stored in R(2,3).


R(2,3)= R(2,3)+ 1
= 2+1
=3
356 PROG RAMMING IN BASIC

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 .

This mean s that whatever is stored in R(3,2) is copied and stored


in R(1, 1) . Both storage locations now contain the number 4.
VIII. The program segment below prints out the storage areas (the
row numbers and the column numbers) that have no books. It
performs by rows.

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

Line 70 is executed in the following manner. If an element in the


array is the number zero , control is transferred to line 90 and the
computer prints the number of the row and the number of the
column. The element in the next column of the same row is then
checked for zero . If it is not zero , control is transferred to line 100
to check the element in the next column . Once all the elements
in the row are checked (the J loop is complete) , the computer re-
enters the I loop and each element in the next row is checked for
zero as J goes through its cycles . Finally, when the elements in
all the rows have been chec ked (in other words , when the I loop
is satisfied), execution terminates .
IX. Suppose all the books have been signed out. The easiest way to
assign zero to each element of the array is by using nested
FO R/NEXT 100ps .1

4B FOR 1=1 TO 3
5B FOR J=l TO 4

1. It should be noted that so me 01 th e elements o f th e array are already zero. The


program seg ment does not check lor th is and ass ign s ze ro to th ese elemen ts as well.
TWO-DIMENSIONAL ARRAYS 357

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 .

Sto reroom A Storeroom B


Sec 1 Sec 2 Sec3 Sec 1 Sec 2 Sec 3
Shelf 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

The supervisor of the shoe department wants to know the total


number of each style of shoe. Since each style is stored on the
same numbered shelf and section in storeroom A as in store-
room B, all that needs to be done is to add the number of pairs in
the corresponding storage areas . For example, in the first row of
the matrices shown above, the program adds 1 + 9, 2+ 8, 3+ 7.
The corresponding numbers in the remaining rows are then
added. The sum of each calculation will equal 1O.
(a) All operations are performed by rows.
(b) One set of nested FOR /NEXT loops is used to read the data
and to perform the calculations. The sums are stored in a
third (two-dimensional) array .
(c) A second set of nested loops is used to print the information
shown below.

l.0a REM REA[I THE [lATA


101 REM CALCULATE THE SUMS
110 FOR 1=1 TO 3
120 FO R J=l TO 3
13~ REA[I A(I,J),(I(I,J)
140 DATA 1,9,2,8,3,7
150 DATA 4,6,5,5,6,4
160 DATA 7,3,8,2,9,1
170 LET C(I,J)=A<I,J)+(I(I,J)
180 NE XT J
19~ NEXT 1
358 PROGRAMMING IN BAS IC

2~~ REM PRINT STATEMENTS


210 FOR K=l TO 3
220 FOR L=l TO 3
230 PRINT
240 PRINT "A";A(K,L),"B";B(K,L)
250 PRINT "TOTAL";C(K,L)
260 NEXT L
270 NEXT K
999 END

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

8,3 CALCULATING WITH ARRAYS- Your Turn


I. This is the final extension of the problem presented in Sections
8.1 and 8.2. In this section, you are to calculate the yearly interest
on an investment of $4000 using the rates shown below . The
rates are dependent on the number of years the money is
invested.
TWO-DIMENSIONAL ARRAYS 359

No. of Years Rate of Interest


y R
10 12 14 .10 .11 .12
16 18 20 .13 .14 .15

(a) Perform all operations by rows.


(b) Use one set of nested FOR/NEXT loops to read the data and
calculate the interest. Store the interest in a third (two-
dimensional) array.
(c) Use another set of nested loops to print the years, rates, and
interest amounts as shown in the RUN .
(d) Interest = Amount Invested x Rate of Interest
(e) Fill in the missing lines .

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 12 F:ATE .11


INTEREST 440

YEARS 14 RATE .12


INTEREST 480

YEARS 16 RATE .13


INTEREST 52~

YEARS 18 RATE .14


INTEREST :i6f21

YEARS 20 RATE . 15
INTEREST 600

1. Which statement should be coded in line 130?

(a) READ Y(N,H) ,R(N,M)


(b) READ Y(H,N) ,R(M,N)
(c) READ R(M,N) ,Y(M,N)
(d) READ Y(N,H),R(M,N)
(e) READ R(N,H) ,Y(M,N)

2. Complete line 150 with a DATA statement.


3 . Which statement should be coded in line 170?

(a) LET A(HdO==I<M,N)*R(M,N)


(b) LET R(H,N)=A*IOhN)
(c) LET I<H,N)==A(M,N)U,(M,N)
(d) LET I<M,N)=A*R(M,N :-
(e) LET I=A*R(M,N)

4. Complete line 180 with a NE XT statement.


5. Complete line 220 wi th a PRINT statement.
6 . Complete lines 340 and 350 w ith PRINT statements .
7. Complete line 370 with a NE XT statement.
II. Sh own below is the number of each type of book originally
stored in the Roxva le Park Library.
TWO-DIMENSIONAL ARRAYS 361

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

8.3 CALCULATING WITH ARRAYS-Solutions


for "Your Turn"
I.

1. (b) 130 READ Y(M,N) ,R(M,N)


2.150 [lATA 16,.13,18,.14,20,.15
3. (d) 171!) LET I(M,N)=A*R(M,N)
4. 18e NEXT N
5. 22e PRINT "AMOUNT INVESTED";A
6.340 PRINT ·YEARS";Y(K,L),"RATE";R(K,L)
350 PRINT "INTEREST";I(K,L)
7. 37e NEXT K
362 PROGRAMMING IN BASIC

II.

100 REM READ AND PRINT THE DATA


11£'1 PRINT
120 FOR I~l TO 3
130 FOR j=1 TO 4
140 READ R(I,j)
150 DATA 3,2,O,1
160 DATA 1,~,2,3
170 DATA 2,4,1,~
180 PRINT R(I,j);
190 NEXT j
200 PRINT
210 NEXT I
300 REM INCREASE THE ELEMENTS
301 REM PRINT THE INCREASED AMOUNTS
310 PRINT
320 FOR K=l TO 3
330 FOR L=l TO 4
340 LET R(K,L)=R(K,L)+2
350 PRINT R(K,L);
360 NEXT L
37£'1 PRINT
380 NEXT K
999 END

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.

Questions and Exercises


1. What is the difference between a one-dimensional array and a
two-dimensional array?
TWO- D IMENSIONAL ARRAYS 365

2. Display and label a doubly subscripted variable.


3. State the difference between a DIM statement that reserves
storage locations for a two-dimensional array and one that
reserves storage locations for a one-dimensional array.
4. Write two programs that store the following data items in arra y A
by rows .
A
2 4 6 8
10 12 14 16
18 20 22 24
(a) One program uses the INPUT statement to enter the data.
(b) The other program uses the READ/DATA statements.
5. Write two programs, each reading the following data into two
arrays. Use one READ statement in each program .
X y
20 22 24 60 66 72
26 28 30 78 84 90
(a) One program reads the data by rows.
(b) The other program reads the data by columns .
6. Identify the errors , if any , in the program segments shown below.
Assume that a sufficient number of data items has been supplied .
Make the necessary corrections.

(a) 10 DIM [«5,4)


2k'! FOR 1=1 TO 5
30 FOR J::1 TO ..-..J
READ B(I,J)
413
5k'!
613
DATA - , - , - ,
NEXT J
...... (25 items of data)

713 NEXT I

999 END

(b) 10 DIM C(3,4)


20 FOR 1'1=1 TO 4
30 FOR N=l TO 3
READ C(N,M)
40
513
613
DATA - , - , - ,
NEXT N
...... (12 items of data)

7~ NEXT M

999 END

(c) 113 DIM X(6,7) ,Y(7,6)


213 FOR 1=1 TO 6
30 FOR J=l TO 6
40 READ X(I,J),Y(I,J)
S0 DATA - , - , - , • • • • •• (72 items of data)
366 PROGRAMMING IN BAS IC

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

7 . (i) In each of the following programs, is the data read in by rows


or by columns?
(ii) What will be stored in the array(s) after execution of each
program? You may show the contents in matrix form. For
example, if there are two 2x 3 arrays, you may display the
contents in the following manner.

A B
456 16 20 24
789 28 32 36

(a) 1111 DIM A(3,2)


2111 FOR J=1 TO 2
30 FOR 1=1 TO 3
4111 READ A(I,J)
5111 DATA 10,20v30,4e,5~,60
6111 NEXT I
7111 NEXT J
99 END
TWO-DIMENSIONAL ARRAYS 367

(b) 10 DIM A(2,3),B(2,3)


20 FOR 1=1 TO 2
30 FOR J=1 TO 3
40 READ A(IrJ)d!(Id)
50 DATA 1B,100,20,200,30,300
60 DATA 40,40O,50,500,6O,600
70 NEXT J
80 NEXT I
99 END

(c) Ul DIM A(2,3),B(2,3)


20 FOR J=l TO 3
38
48
FOR 1::1 TO ..
")

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

8. Write one or more statements that print the following elements of


a 4x 5 array named A.
(a) The first element (first row, first column) .
(b) The first and last elements on one line widely spaced. (The
last element is in the fourth row, fifth column .)
(c) All 20 elements by rows. Use nested FO R/N EXT loops. Output
is to be printed in matrix form.

9. Show the RUN for each of the following program segments.


Assume that the data shown below has already been entered.

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

(b) HI [tIM R(2,4)


2B LET T=e

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

(c) HI DIM F~(2,4)

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. Code one or more statements to perform the following opera-


tions on a 3x 4 array named R. Assume that the data has already
been entered.
R
12 10 16 14
20 18 30 22
26 24 10 32

(a) Replace the element in row 2, column 4, by 34.


(b) Copy the element in row 1, column 3, by storing the value in
row 2, column 3.
(c) Subtract the element in row 1, column 1, from the element in
row 3, column 4. Store the result in row 1, column 1.
(d) Increase the element in row 3, column 1, by 10.
(e) Find the sum of the elements in the second row. Use one
FOR/NEXT loop. Store the result in a simple variable.
(f) Find the sum of the elements in the second column. Use one
FOR/NEXT loop. Store the result in a simple variable.
(g) Print the number of the row and the number of the column
where the element is a 10. Use nested FOR/NEXT loops and
perform the routine by rows.
(h) Square each element of the array and store the results in a
two-dimensional array named S. Use nested FOR/NEXT
loops. Perform the routine by rows.
(i) Initialize al112 elements to zero. Use nested FOR/NEXT loops
and perform the routine by columns.
TWO- DI MEN SIO NA L ARRAYS 369

11 . What is the output of each of the foll owing programs?

(a) 1 ~ DIM A(2,3),B(2,3)


2111 PRINT
30 FOR 1=1 TO 2
4111 FOR J=l TO 3
5111 READ A(l,J),B(I,J)
6111 DATA 1,10,2, ? H,3, J ~
7111 DATA 4,40,5,50 , 6,60
8111 PRINT A(I,JH
9111 NEXT J
1111111 PRINT
11111 NEXT I
12111 PRINT
L30 FOR K=1 TO 2
14111 FOR L=1 TO 3
15111 PRINT B(K,l);
160 NEXT L
17111 PRINT
180 NEXT K
999 END

(b) 1111 DIM A(4,4)


2111 PRIN T
30 FOR 1=1 TO 4
4111 FOR J=1 TO 4
5111 READ A(I,J)
6111 DATA 1,2,3,4,5,6,7,8
70 DATA 9,1111,11,12,13,14,15,16
8111 IF I=J THEN 11111
9111 LET A(I,J)=0
1111111 GO TO 12111
1 UI LET A(I,J)=1
12111 PF:INT A(I,J);
130 NEXT J
14111 PF:INT
150 NEXT I
999 END

(c) HI DIM A(2,2) ,(1(2,2) ,C(2,2)


2111 PRINT
3111 FOR 1=1 TO 2
40 FOR J=1 TO 2
50 READ A(I,J),B(I,J)
60 DATA 7,6,1,0
7111 DATA 9,8,5,4
8111 LET C(I,J)=A(I,J) - B(I,J)
90 PRINT C(I,J);
10111 NEXT J
110 PRINT
12111 NEXT I
999 END
370 PROGRAMMING IN BASIC

(d) l~ DIM X(3,2)


2~ FOR 1=1 TO 3
3~ FOR J=l TO 2
4~ READ X(I,J)
5~ DATA 5,10,15,20,25,30
60 NEXT J
7~ NEXT I
80 PRINT
90 FOR L=1. TO 2
100 FOR K=l TO 3
110 PRINT X(K,L);
120 NEXT K
130 NEXT L
999 END

12. The following program squares each element of array A, stores


the results in array B, then sums the squared values. The pro-
gram, however, has a number of errors. Make the necessary
corrections so that it produces the RUN as shown. Here is the
data.
A
586
454
845

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
_ __ __ _ _ _ ~

1. Write a program that finds the average number of books in each


storage area.
(a) Use one set of nested FOR/ NE XT loops to read and print the
data.
(b) Use another set of nested loops to accumulate the total in a
simple variable, say T. Keep a running counter to count the
number of storage areas as the total number of books is
being accumulated.
(c) Total = Total + Number of books in each storage area
(d) Average =Total
Counter
(e) Print the total and the average

RUN
"l
"- 4 3 2
4 ")
"- 4 3
2 5 3 "
"-

TOTAL: 36 AVERAGE: 3

2. This problem is similar to one you had in Chapter Four (Review


Problem 6, page 146.) This time you will be using a doubly
subscripted variable instead of a simple variable.
Write a program that finds the storage area that has the
greatest number of books . Print the number of books it contains
and its location.
(a) Perform all operations in one set of nested FOR/NEXT loops.
(b) Find the greatest number of books by assigning a number,
such as -1, to a simple variable, say L. Compare each item
of data with this value and replace L with the data item if the
item is larger. Your main statement should be IF R(I,J) > L
THEN xx , where XX is the number of the statement that
replaces L with the data item .
(c) Each time a data item is larger than L, store the number of the
row and the number of the column in simple variables , such
as R1 and C1.
372 PROGRAMMING IN BAS IC

RUN

GREATEST NO. OF BOOKS: 5


ROW: 3 CDLUMN: 2

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

3. Write a program that finds the following:


- The total number of pairs of shoes in storeroom A.
- The total number of pairs of shoes in storeroom B.
- The total number of pairs of shoes in both storerooms.
Refer to page 352.
Program III (1)
Use four sets of nested FOR/NEXT loops:
- The first set reads the data.
- The second set prints (in matrix form) the number of pairs of
shoes in storeroom A.
- The third set prints (in matrix form) the number of pairs of
shoes in storeroom B.
- The fourth set finds and prints the total number of pairs of
shoes in each storeroom and in both storerooms.
(a) Use simple variables to store the totals - for example, Tl,
T2, T3.
(b) Total in Both Storerooms = Total in Storeroom A + Total in
Storeroom B

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.

Sto reroom A Storeroom B


Sec 1 Sec2 Sec3 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
TW O- DIMENSIONAL ARRA YS 375

Calculate the value of the shoes in each storage location in


storeroom A. Shown below are the prices for each style of shoe.
Prices
Sec 1 Sec 2 Sec 3
Shelf 1 $50 $48 $52
Shelf 2 45 53 46
Shelf 3 62 58 64

Use three sets of nested FOR /NEXT loops:


(a) The first set reads the prices into a two-dimensional array,
say P.
(b) The second set reads the number of pairs of shoes in each
storage location of storeroom A and calculates the values.
Your statement that calculates the value of each style of shoe
should look something like the following.
xx LET V(I,J)=A(I,J)*P(I,J)
(c) The third set prints the values as shown in the RUN.

RUN

VALUE OF SHOES IN EACH


LOCATION OF STOREROOM A
50144 104
225 212 0
124 174 320

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.

(c) Total Value = Total Value + Number of Pairs in Each Loca-


tion x Price for Each Location

RUN

1353

7. Here is the last problem concerning the storerooms . The super-


visor wants to know which styles (that is, which storage loca-
tions) in each storeroom have two pairs of shoes or less so that
an order may be placed to replenish the existing stock.
(a) Use one set of nested FOR /NE XT loops to perform the follow-
ing:
- Read the data into both arrays .
- Find each storage location in storeroom A that has two
pairs of shoes or less . Your statement to find such a
location should look something like the following .

_ _ IF A(I,J) < =2 THEN xx

where xx is the number of the statement that prints the


shelf number and the section number of the storage loca-
tion that has two pairs of shoes or less .

(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

8. Find the sum of the elements in the principal diagonal of matrix A.


Do you remember what is meant by the principal diagonal of a
matrix? This is the line that falls on those elements whose row
numbers and column numbers are the same . (See page 345,
" Your Turn," Problem 1.)
Check each element to see if it is located in a row and a column
that are numbered the same; that is, if I=J. If it is, perform the
addition and store the sum in a simple variable . If I is not equal to
J , print the element just checked , then check the next element.
When all the elements have been checked and printed , print the
sum of the diagonal as shown in the RUN. Perform all operations
in one set of nested FOR/ NEXT loops (except the last PRINT).
Note : Other than different descriptions within the symbols and a
few more PRINT figures, your flowchart should be similar to the
one for Problem 2.

RUN
123
456
789

THE SUM OF THE ELEMENTS


OF THE DIAGONAL IS: 15

9. Write a program that answers the following question. Which


numbers stored in array A are also stored in the respective
positions of array B? For example, the number 2 in row 1, column
2, of array A is also in row 1, column 2, of array B. When you find
such a number, store it in a simple variable, say C . Your main
statement should be

_ ______IF A(I,J)=B(I,J) THEN xx

where xx is the number of the statement that stores the common


number in variable C. Use one set of nested FOR/NEXT loops.

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

10. Write separate programs to perform the following on matrix A:


(a) Find the sum of the elements in each row.
(b) Find the sum of the elements in each column.
To find the sum of the elements in each row:
- Place the row loop on the outside.
-Initialize S (SUM) to zero between the FOR statements.
- Place the column loop on the inside.
To find the sum of the elements in each column:
- Place the column loop on the outside.
-Initialize S (SUM) to zero between the FOR statements.
- Place the row loop on the inside.
Use separate sets of nested FOR/NEXT loops in each program
to read the data and find the sums . To print the row numbers and
the column numbers as shown in the RUNS , print the values of I
and J .

Program (a)

RUN

SUM OF ROW 1 IS: 6


SUM OF ROW "'- IS: 15
')

SUM OF ROW 3 IS: 24

Program (b)

RUN

SUM OF COLUMN 1 IS: 12


SUM OF COLUMN 2 IS: 15
SUM OF COLUMN 3 IS: 18
382 PROGRAMMING IN BASIC

INE MATRIX STATEMENTS


AND LIBRARY FUNCTIONS
A. Depending on the support given by your computer system, the
completion of this chapter should enable you to write BASIC pro-
grams and complete skeletal BASIC programs that:
1. Use MAT statements to manipulate data in arrays .
2. Use the INT function to:
(a) Separate digits from numbers and break down amounts
into components.
(b) Check the exactness of division.
(c) Round off numbers .
3. Use the RND function to :
(a) Generate random decimal numbers.
(b) Generate random whole numbers.
4. Use the ABS, SGN, and SOR library functions .
B. In addition, you should be able to:
1. Convert a program that uses FOR/ NEXT loops to manipulate
data in arrays to one that uses MAT statements.
2. State how data is entered by a MAT READ and a MAT INPUT.
3. Write MAT statements that perform specific functions.
4. (a) State which MAT statements may be used to redimension
arrays .
(b) Code these statements in a program segment.
5. Produce the output of programs.
6. Find errors in program segments .
7. (a) Define the term library function .
(b) State two other terms that name this function .
(c) Explain how library functions are "called. "
8. State the purpose of:
(a) A library function.
(b) The INT function.
(c) The RND function.
(d) The ABS, SGN, and SOR functions.
9. Recognize other library functions.
10. (a) Define the term argument.
(b) Describe how an argument is coded .
11 . Evaluate expressions using the INT function .
12. (a) State two reasons why numbers generated by the RND
function are not truly random .
(b) Summarize the meaning of the statement " numbers gen-
erated by the RND function are evenly distributed between
eJ and 1 ."

9.1 MATRIX 8TATEMENT8


The last two chapters introduced you to one-dimensional and two-
dimensional arrays. To be able to read data, print items, and perform
MATRIX STATEMENTS AND LIBRARY FUNCTIONS 383

calculations, FOR/NEXT loops were used. However, a number of


operations involving arrays can be handled more conveniently by
MATrix statements . Not all versions of BASIC include these instruc-
tions , so check your manual or experiment with some of the ones
shown below. If your computer system does not support MATrix
statements, you may skip this section.
MAT statements instruct the computer to perform operations on an
entire array rather than on one element at a time. Thus, programs are
much shorter, since operations performed by these instructions do
not require FOR/NEXT loops. The general form of a MAT statement
looks like the following.

20 MAT READ A
i i i i
Statement Key word Function Name of
Number to be the Array
performed

Here is a list of some of the functions performed by MAT statements .

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.

1. As with an array created in a FOR/NEXT loop, subscripted variables will be used to


refer to storage locations in an array created by a MAT statement. The term matrix
refers strictly to a two-dimensional array
384 PROGRAMMING IN BASIC

Before these statements are explained, compare a program that


uses MAT statements with one that uses FOR/NEXT loops .

Using FOR/NEXT Loops Using MAT Statements

10 DIM A(2,3) HI DIM A(2,3)


20 PRINT 20 MAT READ A
30 FOR 1=1 TO 2 30 DATA -,-,-, (6 items of data)
40 FOR J=l TO 3 40 PRINT
50 READ A(I,J) 50 MAT PRINT A
60 DATA -,-,-, (6 items of data) 99 END
70 PRINT A(I,J);
80 NEXT J
90 PRINT
100 NEXT I
999 END

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

Some computer systems allow one subscript in the DIM statement of


a one-dimensional array, such as DIM A(4); followed by a MAT READ
statement or a MAT INPUT statement. Others insist on two sub-
scripts - A(1 ,4) if the list is thought of as a row of num bers, or A(4, 1)
if the list is thought of as a column of numbers.
The MAT READ statement may also be used to store values in a two-
dimensional array (a matrix).

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

Values that are stored in a matrix by a MAT READ statement must be


entered by rows, which means that the items in the DATA statement
must be listed by rows .
Most versions of BASIC allow several matrices or vectors to be
listed in one MAT READ statement.

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,>

When the above program is executed, the computer displays a


question mark. Numbers may be typed on separate lines by pressing
the RETURN key after each value is entered. A comma must separate
the numbers if more than one value is typed on a line. If there are too
many entries for one line , some systems allow an ampersand to be
typed at the end of the unfinished line . Another question mark ,
generated by the ampersand, is displayed at the beginning of the next
line and the remaining data items are then keyed in . The process may
be repeated for additional lines of input. Many systems automatically
display a question mark on a new line when the RETURN key is
pressed and not enough values have been entered to satisfy the MAT
INPUT statement.
On some computer systems, the MAT INPUT statement allows fewer
values to be entered into a one-dimensional array than there are
locations reserved by the DIM statement. Consider the following
program.

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.

1.0 DIM A(2,3)


20 MAT INPUT A
99 END

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

Output from a vector differs greatly among computer systems. If the


computer considers the list as a row vector, output is printed in row
form. Spacing between items mayor may not depend on the punctu-
ation placed after the name of the vector . On some systems, a comma
produces wide spacing, a semicolon produces closely spaced out-
put. Other computers make no distinction between a comma and a
semicolon. If the computer considers the list as a column of numbers,
output is printed in columnar form, either single spaced or double
spaced. Whether in row form or columnar form , output from two
vectors mayor may not have an extra blank line between each
vector's output.
Try the following program several times, first with no punctuation
after the array name in the MAT PRINT statement, then with a comma,
and finally with a semicolon after the name . What kind of output does
your computer system produce? Does punctuation make any differ-
ence? Does one of the punctuation marks produce an error mes-
sage? In the programs that follow , the output from a one-dimensional
array will be double spaced and in columnar form, regardless of the
type of punc tuation (if any) placed after the name of the vector in the
MAT PRINT statement.

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

Now, consider the output from a two-dimensional array (a matrix).


The output of the program shown be low is from a computer that has
four pr int zones.

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

121 221 321


~-----
( One blank line between the rows.
421 50 621

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

Most computer systems print the values of a matrix by rows. Since A


is dimensioned as a 2x3 matrix, its output has two rows and three
columns. A blank line is left between the rows. Matrix B is dimen-
sioned as a 2x7 matrix . Since the computer used for the programs in
this book does not print more than four items on one line , each row for
matrix B requires two lines in order to print out seven columns of
numbers . A blank line is left between the two rows. The last item in the
dimension statement is a vector. As already explained , the computer
prints the values of a vector double spaced and in columnar form ,
regardless of the type of punctuation following the vecto r' s name in
the MAT PRINT statement. Notice that this computer leaves an extra
blank line (two blank lines) between the output of matrix A and that of
matrix B, and between the output of matrix B and the output of vector
C. It should also be mentioned that on some systems, a comma
placed after the last matrix name in a MAT PR INT statement produces
the same spacing between the items of the matrix as coding no
punctuation at all. Both cause the items of the matrix to be widely
spaced .
If the MAT PRINT statement in the previous program is changed to

the output will be as follows .

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 semicolons after A and B cause the output to be closely spaced .


Each row of matrix B is now printed on one line , since there are
enough print positions for the seven columns . A blank line is left
between the rows. The items of vector C continue to be in columnar
form, double spaced . Again , two blank lines are left between the
390 PROGRAMMING IN BASIC

output of two arrays . Remember , the output shown on page 389 is a


sample of how one computer system prints the values of arrays . Try
the program on page 388. How does your computer print the
numbers? Compare your output with the output shown on the same
page. Now, replace the MAT PRINT statement with one that uses
semicolons . Again, examine your output and compare it with the one
shown on page 389 .
For the remaining MAT statements, RUNS will be displayed only for
concepts that are unfamiliar to you . Keep in mind that these RUNS
might not be in exactly the same form as the ones produced by your
computer system.
Assignment
Arrays (either one-dimensional or two-dimensional) may be dupli-
cated by this statement. Each element of array A is copied by
I. MAT B=A
assigning it to a corresponding variable of array B. Two identical
arrays are now stored in memory.

One-dimensional Array Two-dimensional Array

HI DIM A(3),B(3) 10 DIM A(2,3),B(2,3)


20 MAT READ A 20 MAT READ A
30 DATA 1,2,3 30 DATA 1,2,3,4,5,6
40 MAT B=A 40 MAT B=A
50 PRINT 50 PRINT
60 MAT PRINT A,B 60 MAT PRINT A;B;
99 END 99 END

This statement assigns zero to each variable of array A. Thus, MAT


ZER is often considered an in itialization statement. If the array is two-
II. MAT A=ZER
dimensional and your computer system supports variables with zero
subscripts, these variables may be ignored and you may have to set
them to zero by using the LET statement , the REAOIDATA statements,
or the INPUT statement. Note, too , that some computer systems do
not allow MAT ZER to be used on one-dimensional arrays.

One-dimensional Array Two-dimensional Array

10 DIM A(3) 10 DIM A(2,3)


20 MAT A=ZER 20 MAT A=ZER
30 PRINT 30 PRINT
40 MAT PRINT A 40 MAT PRINT A;
99 END 99 END

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

One-dimensional Array Two-dimensional Array

:L0DIM A(3) 10 DIM A(2,3)


20 MAT A=CON 20 MAT A=CON
30 PRINT 30 PRINT
40 MAT PRINT A 40 MAT PRINT A;
99 END 99 END

This statement assigns the identity matrix to A. The identity matrix is a


square matrix whose principal diagonal consists of ones and whose
IV. MAT A=IDN
remaining elements are zeros .

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 .

One-dimensional Array Two-dimensional Array

10 DIM A(3),B(3),C(3) 10 DIM A(2,3),B(2,3),C(2,3)


2~ MAT REAII A,B 20 MAT REAII A,B

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

30 DATA 1,2,3 30 DATA 1,2,3,4,5,6


40 DATA 9,8,7 40 [lATA 9,8,7,6,5,4
50 MAT C=AtB 50 MAT C=AtB
60 PRINT 60 PRINT
70 MAT PRINT A,B,C 70 MAT PRINT A;B;C;
99 END 99 END

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.

One-dimensional Array Two-dimensional Array

10 DIM A(3),{!(3) 10 DIM A(2,3),B(2,3)


20 MAT REA[I A 20 MAT READ A
30 DATA 1,2,3 30 DATA 1,2,3,4,5,6
40 MAT B=(2)*A 40 MAT B=(2)*A
50 PRINT 50 PRINT
60 MAT PRINT A,B 60 MAT PRINT A;B;
99 END 99 END

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

On some systems, you may check for the existence of an inverse by


using the DET function . If the DET function , performed on the original
matrix, returns a non-zero value, the matrix has an inverse . Some
systems that recognize the DET function insist that the function be
used after the MAT INV statement. It mayor may not requ ire an
argument.

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

THE DETERMINANT OF A 15:-2

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

Changing the Dimensions of an Array


It was mentioned that on some computer systems , the MAT IN PU T
statement allows any number of data items to be entered into the
computer , provided the number does not exc eed the dimensions of
the array. Several other MAT statements may be used to redimension
396 PROGRAMMING IN BASI C

arrays during execution of a program. These include MAT READ , MAT


ZER, MAT CON, and MAT IDN. On many systems, MAT PRINT may not be
used to redimension an array. The new dimensions must not exceed
the original dimensions as specified in the DIM statement. Dimen-
sions may be changed on both one-dimensional and two-
dimensional arrays Here are some examples

1. 10 DIM A(4) 2. HI DIM B(3,4)


20 MAT READ A(3) 20 MAT READ B(2,3)
3l!l
DATA 1,2,3 30 DATA 1,2,3,4,5,6
40 PRINT 40 PRINT
50 MAT PRINT A 50 MAT PRINT B;
99 END 99 END

In Program 1, vector A has been redimensioned so that it is now a


three-element vector. In Program 2, matrix B has been redimen-
sioned so that it is now a 2x3 matrix . The MAT READ statement in both
programs stores values in the redimensioned arrays .

3. H'J DIM A(3,4) ,B(5,7) ,C(6,4)

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

Statement 40 redimensions A as a 2x3 matrix, then assigns zero to


each variable of the redimensioned matrix. Statement 50 redimen-
sions B as a 3x4 matrix, then assigns 1 to each variable of the
redimensioned matrix. Statement 60 redimensions C as a 3x3 matrix,
then assigns the identity matrix to the redimensioned matrix. The MAT
ZER and MAT CON statements may also redimension vectors. MAT IDN
may redimension only matrices.
The dimensions in the MAT statements may be expressed as
variables. However, positive integers must be assigned to these
variables prior to their use in the statements. And, as with constants,
the values of the variables may not be greater than the dimensions
originally specified in the DIM statement.

9.1 MATRIX STATEMENTS - Your Turn


Many sample programs were listed in this section. For the following
questions, page numbers are given so that you can quickly refer to a
program if you need some help.
MATRI X STATEMEN TS AND LIBRARY FUNCTION S 397

1. Define the errors , if an y , in the program segments shown below .

Make the necessary corrections .

(a) 10 [I I M A ( 3 , 2 )
2~J MAT INPUT .. . . . .. . . ......... . . . .. . (Page 386)

(b) This MAT statement is to make a duplicate copy


of matrix A.
10 DIM A(4,3),B(4,3)

25 MAT A=B .... .. . .. . ...... . . . ... ... . (Page 390)

(c) 10 DIM A ( 2 , 3 )

30 MAT A=ZER(3,4) .. . . . . ...... . ... . ( Page 395)

(d) 10 [I I M A( 3 , 4 )

35 MAT A=IDN ......... .. .. .. . ... (Page 391)

40 MAT C=AtB ... . ...... . ..... . ... ... (Page 391)

45 LET C=4
50 MAT B=C*A .... . .... . ...... . . .... . (Page 392)

(g) 10 DIM A(4,5) ,B(5,3) ,C(4,3)

55 MAT C=A*B . ..... .... . .. .. ........ (Page 392)

(h) 10 DIM A ( 3,4) , B ( 3 ,4)

60 MAT B= TRN (A) . . .... . . . ... . . . . . . . (Page 393)

(i) 10 DIM A(8,7) ,B(8,7)

65 MAT B=INV(A) ... .. ... . . .. (Page 394)

2. Write a program that reads data into 2 two-dimensional arrays


and performs the following operations using M AT statements .
The data is shown below in matrix form .
A B
1 2 3 456
456 789
(a) Read the data using one MAT statement.
(b) Subtract the elements of matri x A from the corresponding
elements of matrix B and store the differences in matri x C .
398 PROGRAMMING IN BASIC

(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

9.1 MATRIX STATEMENTS-Solutions for


\\Your Turn"
1. (a) The MAT INPUT statement must include the name of the
matrix.

20 MAT INPUT A
MATRIX STATEMENTS AND LIBRAR Y FUN CTIONS 395

(b) To make a duplicate copy of matrix A, the values of matrix A


must be assigned to matrix B. Therefore , A must be on the
right-hand side of the equals sign and B must be on the left-
hand side.

25 MAT B=A

(c) The size of the redimensioned matrix must not be greater


than the size of the original matrix as specified in the DIM
statement. Either increase the dimensions in the DIM state-
ment or decrease the dimensions in the MAT ZER statement.

or 1£'1 DIM A(2,3)

30 MAT A=ZER(3,4)

(d) The identity matrix is a square matrix. Since it is being


assigned to A, A must also be a square matrix.

or

(e) Nothing is wrong.


(f) Most computer systems require parentheses around the
scalar .

(g) Nothing is wrong .


(h) Transposing a matrix interchanges its rows and columns . If a
matrix has three rows and four columns, its transposed form
will have four rows and three columns. In this program
segment, the dimensions of B should be four rows and three
columns.

(i) A matrix multiplied by its inverse produces the identity


matrix. Since the identity matrix is a square matrix, the
matrices involved in the calculations must also be square .
400 PROGRAMMING IN BASIC

Matrices A and B in this program segment must be square


matrices.

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

9.2 THE INT FUNCTION


BASIC has a number of library (standard or built-in) functions that are
written directly into the language. These are prewritten routines that
may be called upon to perform certain operations, such as finding the
square root of a number. To call a library function, its name (which
consists of three letters) must be coded along with the value upon
which the computer is to operate. This value, called the argument,
must follow the function name and must be in parentheses. It may be
expressed as a constant, a variable, a library function, an arithmetic
expression, or as a string.4 For example, the square root function is
accessed by SQR(X) , where X has previously been assigned a
number. The function may be called by coding it in a LET statement,
such as xx LET B=SQR(25), or by placing the function in a
PRINT statement, such as xx PRINT SQR(25). The LET statement
assigns the result of the function to the variable that is to the left of
the equals sign; the PRINT statement prints the result. One or more
library functions may also form an expression such as

4. Functions that operate on strings are covered in a later chapter.


MATRI X STATEMENTS AND LIBRARY FUNCTIONS 401

SQR(25)+INT(S.85)-2 , which is placed either in a LET statement or in


a PRINT statement. In this expression, the result of the SOR function is
added to the result of the INT function to give another answer from
which 2 is subtracted .
The function to be discussed in this section is the INT function.
Remember in Chapter Four it was mentioned that a decimal number
is made up of two parts-the integer portion and the decimal portion.
An example is the number 5.17 which has 5 as the integer part and
.17 as the decimal part.
Suppose you want to retain only the integer part of a number. The
INT function will perform this operation for you. Here is a program that
keeps the integer part of 5.17.

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

5£1 PRINT Y,INT(Y)


99 END

What value does your computer print for INT(X), - 49 or - 50?


What value does your computer print for INT(Y), f/J or -1?

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

Line 20 isolates the 3 as follows :

20 LET H=INT(N/1~~)
= INT(349/ 100)
= INT(3.49)
=3

2. This program separates the digit 4 from .23456 .

1£1 LET N=.23456


2£1 LET M=N*1~0
3£1 LET T=INT«M-INT(M»*10)
4£1 PRINT
50 PRINT T
99 END

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

Line 30 isolates the 4 as follows:

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

3. Digits may be separated from decimal numbers greater than one


in the same manner as in Program 2. The program below
separates the digit 5 from the number 1.23456 .

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

Line 30 isolates the 5 as follows :

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

A note of warning is in order. It was mentioned in Chapter Four that


small inaccuracies in the storage of some numbers may cause
404 PROGRAMMI NG IN BAS IC

problems . Here is an example of what could happen . The program is


to isolate the digit 4 .

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.

313 LET T=INT«M-INT(M)t.0013e1)*lB)

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

xx IF I/J = INT(I/J) THEN xx


8/2 = INT(8/2)
4 =INT(4)
4 =4

Since the statement is true , 2 divides evenly into 8.


MATRI X STATEMENTS AN D LIBRAR Y FUNCTI O NS 405

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

xx IF I/J= INT(I/J) + 1 THEN xx


- 9/2 = INT( - 9/2)+ 1
-4.5 =INT( - 4.5)+1
-4 .5 =-5+1
-4 .5 =-4
The results, without the negative signs , are the same as the
results in example two , where positive numbers were used .

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.

1. Rounding off 4.5678 to the nearest tenth


Round ing off a number to the nearest tenth means that the rounded
number has one digit to the right of the decimal point. 0= 1 .
R= INT(N*1 OJ 0+ .5) / 1OJ 0
= INT( 4.5678*1 OJ 1+ .5)/ 1OJ 1
= INT( 4.5678* 10+ .5) / 1OJ 1
= INT(45.678+ .5) / 1OJ 1
= I NT( 46 .178)/ 1OJ 1
= 46/ 1Oj1
= 46/ 10
=4 .6
4.5678 has been rounded off to 4.6

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

2. Rounding off 4.5678 to the nearest hundredth


Rounding off a number to the nearest hundredth means that the
rounded number has two digits to the right of the decimal point. D= 2.
R= INT(N*1 OiD+ .5) / 1OiD
= INT(4.5678*1 0i2+ .5) / 10i2
= INT(4.5678*1 00+ .5)/1 0i2
= INT( 456.78+ .5) /10i2
= INT(457.28)/10i2
= 457/ 10i2
= 457/ 100
=4 .57
4.5678 has been rounded off to 4.57

3. Rounding off 4.5678 to the nearest thousandth


Rounding off a number to the nearest thousandth means that the
rounded number has three digits to the right of the decimal point.
D=3.
R= INT(N* 1OiD+ .5)/ 1OiD
= INT(4.5678 * 10i3+ .5) /1013
= INT(4.5678*1 000+ .5) / 1013
= INT(4567.8+ .5)/ 10i3
= INT(4568.3)/ 1013
= 4568/1 013
= 4568/1000
= 4.568
4.5678 has been rounded off to 4.568

4. Rounding off 4.5678 to the nearest whole number


Rounding off a number to the nearest whole number means that the
rounded number has no digits to the right of the decimal point. D= 06
R= INT(N*1 OiD+ .5)/ 1OiD
= INT(4 .5678*1 0i0+ .5) /1010
= INT(4 .5678*1 + .5) / 10i0
= INT( 4.5678+ .5)/ 10i0
= INT(5.0678)/ 10i0
= 5/ 10i0
= 5/1
=5
4.5678 has been rounded off to 5

9.2 THE INT FUNCTION - Sample Program


On page 402, you were shown how a digit can be separated from
a whole number. Do you remember how this is done? First, the

6. Raising a number to the power of zero resu lts in one .


MATRIX STATEMENTS AND LIB RAR Y FUN CTI ONS 407

required digit is moved to the position immediately to the left of the


decimal point (the units position) by dividing the number by a power
of 10. The decimal part is then removed by the IN T function . For
example , to separate the 3 from 349 , the following calculations are
performed.

H= INT(N/100)
= INT(349/ 100)
= INT(349)
=3

Here is an extension of this principle . The following program isolates


each of the three digits in the numbers 853, 267, and 913 .

211 REM N--NUMBER


02 REM H--HUNDREDS POSITION
213 REM T--TENS POSITION
214 REM U--UNITS POSITION
10 PRINT
20 FOR 1=1 TO 3
3B READ N
40 DATA 853,267,913
50 LET H=INT(N/1~0)
621 LET T=INT«N-H*l~B)/lB)
721 LET U=INT(N-H*l~B-T*lB)
821 PRINT H,T,U
921 NEXT I
99 END

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

Remove the hundreds and move the 5 to the un its position .

6~ LET T=INT«N-H*1~8)/lB) 853


= INT((853- 8*1 00) / 10) - 800
= INT((853- 800)/1 0) 53 5.3 5
= INT(53/ 10) 10
= INT(5.3)
=5

Remove the hundreds and the tens .

78 LET U=INT(N-H*1~8-T*18) 853


= INT(853- 8*100- 5*1 0) - 800
= INT(853- 800- 5*1 0) 53
= INT(853- 800- 50) - 50
= INT(53- 50) 3
= INT(3)
=3

9.2 THE INT FUNCTION-Your Turn


1. Given that 1=6, what value does your computer assign to J in
each of the following statements?

(a) 38 LET J=INT(It3.2) (d) 68 LET J=INT(I-INT(It1.54»

(b) 48 LET J=INT (I-I) (e) 78 LET J=INT(ItINT(I-4.85»

(c) 58 LET J=INT(I-18.99) (0 BB LET J=INT(I-INT(I-8.63»

2. Isolating Digits from Numbers


(a) Write a program that separates the digit 6 from 63 .
(b) Write a program that separates the digit 7 from 789.
(c) Write a program that separates the digit 8 from 285 .
(d) Write a program that separates the digit 1 from 37 .51 .
3. Checking Division
Write a program that checks whether or not 2 divides evenly into
468. Print DOES NOT DIVIDE EVENLY if the division is not
exact ; print DIVIDES EVENLY if the division is exact.
MATRIX STATEMENTS AND LIBRARY FUNCTIONS 409

4. Rounding Off Numbers


(a) Write a program that rounds off 45.16 to the nearest tenth.
(b) Write a program that rounds off 45.168 to the nearest hun-
dredth.
(c) Write a program that rounds off 45 .1687 to the nearest
thousandth.
(d) Write a program that rounds off 24.68 to the nearest whole
number.
5. The sample program on page 407 isolated the digits of three
different numbers. Modify the program so that it prints a number
whose digits are in reverse order. For example, the reverse of
853 is 358 . The numbers you are to reverse are 853, 267 , and
913.
(a) Isolate each digit as in the sample program.
(b) Change the position of the digits by multiplying the former
units digit by 100, the former tens digit by 10, and leaving the
former hundreds digit unaltered . Using 853 as our example,
the digits are changed as follows:
3 (the former units digit) becomes 300. (3x 100)
5 (the former tens digit) again becomes 50 . (5x 10)
8 (the former hundreds digit) remains 8.
(c) Add the repositioned digits.
(d) Print the original number and its reverse.
Note: Perform (b) and (c) in one statement. Your program
should be very similar to the sample program on page 407.

RUN

853 358
267 762
913 319

9.2 THE INT FUNCTION - Solutions for "Your


Turn"
The answers for Problem 1 will vary depending on whether your
computer truncates a negative value or changes the value to the next
lowest integer.

1.

(a) 3l:'1 LET J=INT(I+3.2)


= INT(6+3.2)
= INT(9.2)
=9
410 PROGRAM M ING IN BASIC

(b) 40 LET J=INT(I-I) (e) 70 LET J=INT(ItINT(I-4.85»


= INT(6- 6) = INT(6+ INT(6- 4.85) )
= INT(0) = INT(6+ INT( 1.15))
=0 = INT(6+ 1)
= INT(7)
(c) 50 LET J=INT(I-HI.99) =7
= INT(6 - 10.99)
= INT( - 4.99) (f) 80 LET J=INT(I-INT(I-8.63»
= - 4or - 5 = INT(6- INT(6- 8.63))
= INT(6- INT(- 2.63))
(d) 60 LET J=INT(I-INT(It1.54» =INT(6- (-2)) or =INT(6- (-3))
= INT(6- INT(6+ 1.54)) = INT(6+2) = INT(6+3)
= INT(6-INT(7.54)) = INT(8) = INT(9)
= INT(6- 7) =8 =9
= INT(-1)
= - 1

2. Isolating Digits from Numbers Result

(a) 10 LET N=63 63


20 LET T=INT(N/10) INT(63/10) = INT(63)= 6
30 PRINT
40 PRINT T 6
99 END

(b) HI LET N=789 789


20 LET H=INT(N/100) INT(789/ 100) = INT(7.89) = 7
30 PFU NT
40 PRINT H 7
99 END

(c) :L0 L ET N=285 285


20 LET H=INT(N/100) INT(285/ 100) = INT(2.85) = 2
30 LET T=INT«N-H*100)/10) INT(( 285 - 2* 100)/ 10) =
40 PRINT INT(( 285 - 200) / 10) =
5~ PRINT T INT(85/ 10) = INT(85)=8
99 END 8

(d) 10 LET N=37.51 37 .51


20 LET H=N*10 37 .51 * 10 = 375 .1
30 LET T=INT«H-INT(H»*10) INT((375.1-1 NT(375 .1)) * 10) =
40 PRINT INT((375 .1- 375)* 10) =
50 PRINT T INT(.1 * 10)=INT(1)=1
99 END 1
MATRIX STAT EMENTS AND LIBRARY FUNCT IONS 411

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

4. Rounding Off Numbers Result

(a) 10 LET N=45.16 45 .16


~!0LET 11= 1 1
30 LET R=INT(N*leTDt.S)/1BTD INT(45 .16* 1 OJ 1+ .5)/ 1OJ 1= INT(452 .1)/ 10=
452/ 10= 45.2
40 PRINT
50 PRINT R 45 .2
99 END

(b) U~ LET N=45. 168 45 .168


20 LET D=2 2
321 LET R=INT(N*121TDt.5)/121TD INT(45 .168*1 Oj2+ .5)/ 1Oj2= INT(4517 .3) / 100=
4517/ 100= 45 .17
421 PRINT
58 PRINT R 45.17
99 END

(c) 1 ~ LET N=45.1687 45 .1687


20 LET D=3 3
30 LET R=INT(N*lBTDt.5)/1BTD INT(45.1687*1 Oj 3+ .5)/ 1 Oj 3= INT(45169 .2)/ 1000=
45169/ 1000= 45 .1 69
40 PRINT
50 PRINT R 45.169
99 END
(d) 1121 LET N=24.68 24 .68
20 LET D=0 o
30 LET R=INT(N*lBTDt.5)/1BTD INT(24.68*1 Oj0+ .5)/ 1Oj 0 = INT(25 .18)/ 1 =
25/ 1 = 25
40 PRINT
5121 PRINT R 25
99 END
412 PROGRAMMING IN BASIC

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

9.3 THE RND FUNCTION


One of the more interesting library functions is the RND(X) function.
RND is the abbreviation for random number. Each time it is refer-
enced, a different decimal number is generated (produced), consist-
ing of at least six digits and whose value ranges between el and 1. This
means that the RND(X) function generates numbers from .000001 to
.999999 inclusive . Not all computers produce numbers with six
digits. Some generate a random number that contains as many digits
as will fit into one zone. For example, if a computer allows ten
characters per zone, the random number may consist of nine digits if
the first position is reserved for the assumed plus sign and end zeros
are printed . When the number is too small (that is, too close to zero),
most versions of BASIC convert it to scientific notation.
The RND function varies greatly among computer systems. Some
require initialization, such as LET R=RND(-1), to activate the ran-
dom number generator. This is followed later on in the program by
other statements that contain the RND function. Other systems
require no initialization.
For those systems that require initialization, the sign of the argu-
ment determines whether the seed (the starting point of a sequence
of random numbers) is always the same or different. Generally, the
RND(X) function used in statements after initialization has an argument
different from that used in initialization.

10 LET R=RNIt (-1) -Ee'------- Initialization

30 LET A=INT(N*RNIt(l)tI)
....
c.._ _ _ Different argument
MATRIX STATEMENTS AND LIBRARY FUNCTIONS 413

The argument in line 30 may be (1) on some computer systems.


The versions of BASIC that require no initialization may produce
random numbers, regardless of whether the argument is positive,
negative, or zero. Some versions that require no initialization insist
that the argument be non-zero while others are much more restrictive
and produce random numbers only when the argument is positive or
only when it is negative or only when the argument is zero. In
addition, some computer systems insist that the argument be an
integer, and some systems require no argument at all. Because of
these variations, check your manual or try some programs yourself to
see what version suits your computer.
Suppose your computer system requires no initialization and that it
accepts a positive integer (1) as the argument of the RND function.
Here is a program that prints six random numbers.

HI PRINT - Leaves a blank lilne .


2£1 FOR 1=1 TO 6 - Sets up a loop.
3£1 LET R=RND(l) - Generates a random number and assigns it to R.
4£1 PRINT R - Prints the random number.?
5f! NEXT 1 - Transfers control to line 20.
99 END - Terminates program execution .

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

Although the numbers in the above two RUNS may appear to be


random, they are not truly random and are often called pseudo-
random numbers. They are not truly random because they are
generated by a fixed numerical algorithm (procedure) and because of
the predictability of the relationship of time after the first random
number is generated. In order to start with a different seed (a different
starting point), some systems require a RANDOM statement or a
RANDOMIZE statement before the statement that includes the RND
function. Some randomize the seed by using a negative argument in
the RND function, while others (as mentioned above) use an initializa-
tion statement in which the RND function has a negative argument. To
resolve the time relationship problem, some of the computers that
have a real-time clock use the time (RND( - TI) or something similar)
to produce the random seed. A different argument is then used in
subsequent RND functions to generate random numbers. You should
check your manual for the following points to see what your computer
system requires to produce random numbers.
(a) Do you need an initialization statement? If so, what argument
does the RND function require in the initialization statement?
(b) Do RND functions in other statements require arguments? If so,
what kind?
(c) Do you need a RANDOM or a RANDOMIZE statement?
(d) If your computer has a real-time clock, what argument do you use
to produce random seed?
RUN the program on page 413 several times and check your output
for the following:
(a) How many digits does each random number have?
(b) Is a zero printed at the end of a number?
(c) Is any number expressed in E format?
To keep calculations clear, the random numbers displayed in this
book will consist of six digits.
At this point, it should be mentioned that the RND function produces
numbers that are evenly distributed between (/) and 1. This means
that in a long run, the probability of a number falling between (/) and .5
is about the same as the probability of one falling between .5 and 1.8
Looking at it in a different perspective, the chance of a number being
less than 1 is 100% (every number will be less than 1), of a number
being less than .9 is 90% (about 9 out of 10 numbers will be less than
.9), of a number being less than .333 is 33 113% (about 333 out of 1000
numbers will be less than .333) and of a number being less than (/) is
0% (no numbers will be less than 0).
Now that you know how to generate random numbers, what can
you do with them? You can use them to simulate (imitate) a procedure
or use them to test a new program . Random numbers are often used
in programs to test the outcome of events that take place in a random
fashion. Of course, many games are based on random numbers,
such as those that use spinners or dice. The numbers generated in
the program on page 413 are not too useful in the form shown. Whole
numbers, say from 1 to 10 or from 1 to 100, may be more appropriate
for some of the above applications. How are these numbers con-
verted to the more convenient whole numbers?

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

This can be accomplished by using the following conversion formula :


INT(N *RND(1)+ I)
N is the "number" of numbers in the range, and 1 is the first endpoint
(the lowest number wanted) . Finding the "number " of numbers
involves a basic principle in counting. If you want to know how many
numbers there are between 2 and 7 inclusive, simply use the formula
(J-I)+1
where J is the second endpoint and 1 is the first endpoint. One is
added to the difference because you want to include both endpoints.
Therefore, the " number" of numbers between 2 and 7 inclusive is
(7-2)+1=6.
The result obtained within the parentheses of the conversion
formula is usually a decimal number. The INT function is used to
change this random decimal number to a random whole number.
Here are some examples. In each one, the lowest random number
(.000001) and the highest random number (.999999) are used in the
formula as numbers that have been generated by the RND function .
The purpose is to see if the statement produces the two endpoints
given in each example . If it does, all the other random whole numbers
produced by the formula should fall between these two endpoints.
RUN the program for each example several times to verify that the
numbers generated are in the required range .

"Number" of numbers: (J-I)+ 1 = (10-1)+ 1 = 9+ 1 = 10 Generating whole numbers between


First endpoint : 1 1 and 10 inclusive

HJ LET N=H:l
28 LET 1=1
30 LET R=INT(N*RND(l)tI)
40 PRINT
5~ PRINT R
99 END

Lowest Random Number Highest Random Number


R = INT(N*RND(1)+ I) R = INT(N*RND(1)+ I)
= INT(1 0* .000001 + 1) = INT(10*.999999+ 1)
= INT(.00001 + 1) = INT(9.99999+ 1)
= INT(1 .00001) = INT(1 0.99999)
=1 =10

"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

Lowest Random Number Highest Random Number


R = INT(N*RND(1)+ I) R = INT(N*RND(1)+ I)
= INT(1 00*.000001 + 1) = INT(1 00*.999999+ 1)
= INT( .0001 + 1) = INT(99.9999+ 1)
= INT(1.0001) = INT(1 00 .9999)
=1 = 100

"Number" of numbers: (J-I)+ 1 = (6- 1)+ 1 = 5+ 1 = 6 Generating whole numbers between


First endpoint: 1 1 and 6 inclusive

10 LET N=6
20 LET 1=1
30 LET R=INT(N*RND(l)tI)
40 pr~INT
50 PRINT R
99 END

Lowest Random Number Highest Random Number


R = INT(N*RND(1)+ I) R = INT(N*RND(1)+ I)
= INT(6*'000001 + 1) = INT(6*'999999+ 1)
= INT(.000006+ 1) = INT(5 .999994+ 1)
= INT(1 .000006) = INT(6.999994)
=1 =6

" 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

Lowest Random Number Highest Random Number


R = INT(N*RND(1)+ I) R = INT(N*RND(1)+ I)
= INT(20*.000001 + 7) = INT(20*.999999+ 7)
= INT(.00002+ 7) = INT(19 .99998+ 7)
= INT(7.00002) = INT(26 .99998)
=7 =26

Finally, instead of generating just one random whole number, the


following program generates ten random whole numbers. The
numbers range from 5 to 12 inclusive. RUN the program several times.
"Number" of numbers: (J-I)+1 = (12-5)+1 = 7+1 = 8
First endpoint: 5
MATRIX STATEMENTS AND LIBRARY FUN CTIONS 417

H'l LET N=8


20 LET 1=5
~50 PRINT
40 FOR K=l TO HI
50 LET R=INT(N*RND(l)tI)
60 PFU NT R
70 NEXT K
99 END

9.3 THE RND FUNCTION-Sample Program


Here is a program that simulates the roll of a pair of dice . It prints out
the number rolled on the first die, the number rolled on the second
die, and the total rolled on both dice. The pair of dice are rolled three
times. (Note: The roll of one die results in a number that ranges from 1
to 6 inclusive.)

01 REM Dl--DIE NUMBER ONE


~2 REM D2--DIE NUMBER TWO
~3 REM D--TOTAL OF BOTH DICE

H'l LET N=6 - "Number" of numbers in the range.


20 LET 1=1 - First endpoint in the range .
30 FOR K=l TO 3 - Sets up a loop.
40 LET Dl~INT(N*RND(l)tI) - Generates a whole number between
1 and 6 inclusive .
50 LET D2=INT(N*RND(1)tI) - Generates a whole number between
1 and 6 inclusive.
6flJ LET D=DltD2 - Adds the two random whole numbers.
70 PRINT - Leaves a blank line.
80 PRINT "DIE l:";Dl,"DIE 2:";D2 - Prints the number rolled on each die.
90 PRINT "BOTH DICE:";D - Prints the total rolled on both dice.
100 NEXT K - Transfers control to line 30 .
999 END - Terminates program execution.

RUN (Sample RUN)

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

9,3 THE RND FUNCTION-Your Turn


1. For each of the following, code a program that generates a
random number.
(a) A decimal number between I/) and 1.
(b) A whole number between 1 and 10 inclusive.
(c) A whole number between 1 and 1000 inclusive.
(d) A whole number between 1 and 8 inclusive.
(e) A whole number between 5 and 25 inclusive.
(f) A whole number between 20 and 36 inclusive.
2. Random numbers can simulate the tossing of a coin. Since there
are only two possibilities (heads ortails), you can assign, say, 1 to
heads and 2 to tails. The range of random numbers will be from 1
to 2 inclusive. Write a program that counts the number of heads
and the number of tails that are "flipped" out of ten tosses.
Draw a flowchart before you write the program.
(a) If the random whole number is 1, increase the number of
heads by one.
(b) If the random whole number is 2, increase the number of tails
by one.

RUN (Sample RUN)

HEADS: 6
TAILS: 4

9,3 THE RND FUNCTION-Solutions for "Your


Turnl/g
1.

(a) :1.(3 LET R=RND(l)


2111 PRINT
3111 PRINT R
99 END

(b) 1111 LET N=lB


2111 LET 1=1
3111 LET R=INT(N*RND(l)tI)
4111 PRINT
5111 PRINT R
99 END

9. Your computer may require a different argument for the RND function.
MATRI X STATEMENTS AND LIBRARY FUNCTIONS 419

(c) 10 LET N=1~00 (e) 10 LET N=21


20 LET 1=1 20 LET 1=5
30 LET R=INT(N*RND(l)tI) 30 LET R=INT(N*RND(l)tI)
40 PRINT 40 PRINT
50 PRINT R 50 PRINT R
99 END 99 END
(d) 10 LET N=8 (f) 10 LET N=17
20 LET 1=1 20 LET 1=20
30 LET R=INT(N*RND(l)tI) 30 LET R=INT(N*RND(l)tI)
40 PRINT 40 PRINT
50 PRINT R 50 PRINT R
99 END 99 ENII

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)

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

9.4 OTHER LIBRARY FUNCTIONS


A number of other library functions are included in the BASIC lan-
guage. Here is a list of the most common functions available with a
brief description of each.
MATRI X STATEMENTS AND LIBRARY FUN CT IONS 421

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

*On most compu ter systems, X must be in radians. However, on so me systems,


radians (R), degrees (0 ), or gradians (G) may be entered into a trigonometri c
function by means of a SELECT statement.
**The letter e represents an irrational number who se numer ical value is 2.7183 when
round ed off to 4 decimal places .
422 PROG RAMMIN G IN BASIC

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

9.4 OTHER LIBRARY FUNCTIONS-Sample


Program
This prob lem reads in two values at a time, determines the sign of th'e
first one, then solves an equation in which the functions AS S and SOR
are used .

01 REM A--FIRST VALUE


02 REM B--SECOND VALUE
03 REM S--SIGN OF THE FIRST VALUE
04 REM R--RESULT OF THE EQUATION

10 FOR 1=1 TO 3 - Sets up a loop.


20 READ A,B - Reads in the values of A and B.
3~ DATA 2,9,-3,25,-21,49 - Supplies the READ statement with data.
40 LET S=SGN(A) - Determines the sign of A .
MATRI X STATEMENTS AND LIBR ARY FUNCTI O NS 423

50 LET R=ABS(A)tSQR(B) - Adds the absolute value of A to the square


root of B.
60 PRINT - Leaves a blank line .
70 PRINT "THE SIGN OF A IS:";S - Prints the sign of A.
80 PRINT 'THE RESULT IS:";R - Prints the result of the equation .
90 NEXT I - Transfers control to line 10.
99 END - Terminates program execution.

RUN
THE SIGN OF A IS: 1
THE RESULT IS: C'
~I

THE SIGN OF A IS:-1


THE RESULT IS: 8
THE SIGN OF A IS:-1
THE RESULT IS: 28

9.4 OTHER LIBRARY FUNCTIONS-Your Turn


I. Write a program that calculates the square roots of numbers .
Read in the data, then check each item to see if it is negative (use
the SGN function). If it is, change the value of the number to its
absolute value and store the result in the same variable . Calcu-
late the square roots of all the numbers .
(a) Print each value and its square root on one line widely
spaced .
(b) Use the following data : 4,- 9,16 ,- 25 ,36,- 49.
(c) Fill in the missing lines .

01 REM N--NUHBER READ IN


02 REM S--SQUARE ROOT OF THE NUMBER
10 PRINT
2l1J FOR 1=1 TO 6
3l1J READ N
40 DATA 4,-9,16,-25,36,-49
50 IF SGN(N)=-l THEN 70
60 GO TO 80
70
Bl1J
90
100
999 END
424 PROGRAMMING IN BASIC

RUN
4 2
9 3
16 4
25 5
36 6
49 7

1. Which statement should be coded in line 70?

(a) L.ET N=ABS (I)


(b) L.ET N=ABS (N)
(c) GO TO HHl
(d) GO TO 30
(e) L.ET N=SQR ( I)

2. Which statement should be coded in line 80?

(a) L.ET N=SQR(N)


(b) LET N=SQR(S)
(c) LET S==SQR(N)
(d) LET S=SQR(I)
(e) LET N=SQR(I)

3. Complete line 90 with a PRINT statement.


4. Complete line 100 with a NEXT statement.

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.

(a) Use a FOR/ NEXT loop to control input.


(b) Use the following data: 2, - 3 , 4, - 5,6, - 7.
(c) Print the positive numbers and their cumulative totals.

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

9.4 OTHER LIBRARY FUNCTIONS-Solutions


ll
for "Your Turn
I.

1. (b) 7~ LET N=ABS(N)


2. (c) 821 LET S=SQR(N)
426 PROGRAMMING IN BASIC

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

1. Separating Digits from Numbers


This statement separates a digit from the hundreds position of a
number.
xx LET H = INT(N/1 00)

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 .

Questions and Exercises 10


1. Modify the program shown below so that the reading and print ing
of data items are performed by MATRI X statements.

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

2. (a) When a MAT READ statement is used to store data in a two-


dimensional array, are the items entered by rows or by
columns?
(b) Complete the two DATA statements in the following program.
The data is shown below in matrix form.

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

5. Write MATRIX statements that perform the following operations.


(a) Make a duplicate copy of array A and store it in array B.
(b) Assign zero to each variable of array C.
(c) Assign one to each variable of array D.
(d) Assign the identity matrix to matrix E.
(e) Add the elements of array F to the corresponding elements
of array G and store the sums in the corresponding locations
of array H.
(f) Subtract the elements of array I from the corresponding
elements of array J and store the differences in the
corresponding locations of array K.
(g) Multiply each element of matrix L by the scalar 4 and store
the products in matrix M.
(h) Multiply matrix N by matrix P using matrix multiplication and
store the products in matrix O.
(i) Transpose the rows and columns of matrix R and store the
transposed matrix in matrix S.
(j) Calculate the inverse of matrix T and store the inverse in
matrix V.
6 . (a) Which MATRIX statements allow changes in the dimensions
of one-dimensional and two-dimensional arrays?
(b) Code three different MATRIX statements, each one redimen-
sioning one of the matrices listed in the following DIM state-
ment.

7. Identify the errors , if any, in the program segments shown below .


Make the necessary corrections.

(a) The following MAT statement is to make a duplicate


copy of matrix A .

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)

(c) 18 DIM A(4,3)

48 MAT A=IIIN
430 PR OGRA MMIN G IN BAS IC

(d) HI DIM A(3,2),B(3,2),C(3,2) (g) 1£1 DIM A(2,3),B(2,3)

4£1 MAT C=B-A 40 MAT B=TRN(A)


(e) 1£1 DIM A(3,4),B(3,4) (h) 1£1 DIM A(6,6),B(6,6)

40, MAT B=3*A 4£1 MAT B=INV(A)

(f) 1£1 DIM A(4,5),B(S,3),C(4,S)

40 MAT C=A*B

8. (a) What is a library function?


(b) What two other terms name these functions?
(c) How is a library function coded and where is it usually placed
in a program?
(d ) What is an argument? How may it be expressed ?

9 . (a) What is the purpose of the INT function?


(b) What output does y our computer produce for the following
program?

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

10. If M= 7 , what value does your computer assign to N in each of the


following statements?

(a) Hl LET N=INT(MtS.9) (d) 40 LET N=INT(M-INT(Mt3.2»

(b) 20 LET N=INT(M/M-1) (e) 50 LET N=INT(MtINT(M-4.S»


(c) 3£1 LET N=INT(M-16.5) (f) 60 LET N=INT(M-INT(M-16.5»

11 . Isolating Digits from Numbers


(a) Write a program that separates the digit 8 from 85 .
(b) Write a program that separates the digit 2 from 268 .
(c) Write a program that separates the digit 9 from 591 .
(d) Write a program that separates the digit 6 from 31.62.
MATR IX STATEMENTS AND LIBRARY FUNCTIONS 431

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.

(a) Check each storage location (element of the matrix) to see


whether or not it has two pairs of shoes or less . If it has,
change the quantity to 8. Do this for both storerooms.
(b) Use two sets of nested FOR/NEXT loops; one to check the
stock in storeroom A and to print the new quantities, the
other to perform the same operations for storeroom B.
(c) Use MAT statements to read the old quantities and to print the
new quantities. Here is the data before the order was filled.

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

MATRIX STATEMENTS AND LIBRARY FUN CTI O NS 433

Problem 1
A STOREROOM A
B - STOREROOM 8

DIM
A ,S

A(I ,J) = B S(K,L)= B

NEXT J NEXT L

NEXTI NEXT K
434 PROGRAMMING IN BASIC

2. This is a review problem from Chapter Six (Problem 9, page 248)


in which compound amounts were calculated but not rounded off
to the nearest cent. This time you are to round of the amounts to
dollars and cents. Here is the problem once more .
Using an initial principal of $1000, find the amount of an
investment at the end of each year for four years, using interest
rates of 13%, 14%, and 15%. The amount of the investment after
interest has been added is called the compound amount. The
formula to calculate this amount is as fol low s.
Compound Amount = Principal( 1+ Rate of Interest)Period of Time
(a) Use two FOR/NEXT loops:
(i) The outer loop keeps track of the years (period of time in
the formula). Use the index of the FOR statement to print
the number of the year at the beginning of each output
line. Place this PRINT statement between the FOR state-
ments.
(ii) The inner loop generates the interest rates .
(b) Compound Amount = 1000(1 + R) Year Number
(C) Print the first year's compound amounts across the first line
of output (for each rate of interest) , the second year's com-
pound amounts across the second line of output (for each
rate of interest) , etc. To do this, your PRINT statement that
prints the number of the year and the PRINT statement that
prints the compound amount should each end with a semi-
colon.
(d) After each compound amount has been calculated, use the
INT function to round off the amount to the nearest cent. (See
page 406 .)

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

3. A prime number is an integer greater than one that cannot be


divided exactly by any positive integer except by one and itself.
To determine whether or not an integer is prime , divide the
integer by all the numbers between 2 and n-1 inclusive, where n
is the number (integer) to be tested. If the divisions are not exact ,
the number is prime; if a division is exact, the number is not
prime.
(a) Use an outer FOR/NEXT loop to read in the numbers 17, 25 ,
and 29.
(b) Use an inner FOR/NEXT loop to determine whether or not the
integer is prime . In your FOR statement , set the initial value at
2 and the test value at n-1. The index will be your divisor.
MATRI X STATEMENTS AND LIBR A RY FUNCTIONS 435

(c) Your main statement should be


xx IF N/J=INT(N/J) THEN xx
where N is the number read in and J is the index . For
example, if 9 is the integer to be tested, then
9/2 = INT (9/2)
4.5 = INT(4.5)
4.5 =4

This statement is not true when 9 is divided by 2. Therefore,


9 is prime at this point in the program . Your program should
now divide 9 by 3.
9/3= INT(9/3)
3= INT(3)
3=3
Since this statement is true , 9 is not a prime number. To test
a prime number such as 17, your program should divide 17
by all the integers between 2 and 16 inclusive .
(d) If the main statement is true , transfer control to a statement
that prints the number being tested and the message IS NOT
A PRIME NUMBER. Otherwise, divide the number by the
next divisor . If the statement is false for every division, print
the number being tested and the message IS A PRIME
NUMBER.
(e) Do the same for the next two data numbers.

RUN
17 IS A PRIME NUMBER
25 IS NOT A PRIME NUMBER
29 IS A PRIME NUMBER

4. There are two ways by which the efficiency of your program on


prime numbers can be improved .
(i) After dividing by 2, only odd integers need to be used as
divisors.
(ii) It is not necessary to try all odd integer divisors between 2
and n-1 . The number of divisors can be greatly reduced if
your program uses only those divisors that do not exceed the
square root of the number being tested.
(a) Use an outer FOR/NE XT loop to read in the numbers 17,
25 , and 29.
(b) Use an inner FOR/NEXT loop to determine whether or not
the integer is prime. Use 3 as the initial value and SQR(N)
as the test value in the FOR statement of this loop. Use a
step value of 2. The index will be your divisor .
(c) Between the two FOR statements , test each data item by
dividing the number by 2.
436 PROGRAMMING IN BASI C

RUN
17 IS A PRIME NUMBER
25 IS NOT A PRIME NUMBER
29 IS A PRIHE NUMBER

5. This will be your last problem on prime numbers . Instead of


reading in three numbers , have the computer generate 15 ran-
dom whole numbers between 2 and 100 inclusive . Check these
numbers to see whether or not they are prime . Your program for
Problem 4 should be modified as follows:
(a) Change the test value of the outer loop to 15.
(b) Code initialization statements that supply the statement that
generates a random number with the "number" of numbers
and the first endpoint. Remember, the definition of a prime
number does not include the number 1, therefore the first
endpoint must be 2 .
(c) Replace the READ/ DATA statements by a statement that gen-
erates a random whole number between 2 and 100 inclusive.
This statement should be placed immediately following the
FOR statement of the outer loop .
(d) Following the statement that generates a random number,
insert a statement that checks whether or not the random
number is 3 or less. If it is, transfer control to the statement
that prints the number and the message IS A PRIME NUM-
BER.

Since output differs with each RUN , none is shown below .


Instead , all the prime numbers between 2 and 100 inclusive have
been listed . Your RUNS should include some of these numbers as
prime numbers.
2,3,5,7 ,11 ,13,17 ,19,23,29,31 ,37,41 ,43,47,53,59,61 ,67,71,73,
79 ,83 ,89 ,97

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

6. This problem is similar to the sample program (Page 407) that


separates digits from a number. Write a program that converts
1 000000 seconds to days, hours, minutes, and seconds .
1 day = 86400 seconds
1 hour = 3600 seconds
1 minute = 60 seconds
(a) Assign the one million seconds to a variable, say I , by using a
LET statement.
(b) Use the INT function on all calculations that include division.
(c) Days: Divide 1 by 86 400.
(d) Hours : Subtract the days (in seconds) from 1 and divide the
result by 3600 .
(e) Minutes: Subtract the days (in seconds) and the hours (in
seconds) from I , then divide the result by 60.
(f) Seconds: Subtract the days (in seconds) , the hours (in
seconds), and the minutes (in seconds) from I.
(g) Print the number of days, hours, minutes, and seconds as in
the RUN shown below.

RUN

[lAYS: 11
HOURS: 13
MINUTES: 46
SECONDS: 4111

7. Suppose two players are playing a game in which each one


moves his/her chip a certain number of times, depending on
where the dial stops on a spinner. The dial may stop at any
number from 1 to 9 inclusive. Write a program that determines
which player made the greatest number of moves after each one
had 10 plays.
(a) Use a FOR/ NEXT loop to control the number of plays.
(b) Generate a random number from 1 to 9 inclusive for the first
player . This represents the number of moves he/she can
make. Immediately following this statement, accumulate the
player's moves.
(c) 00 the same for the second player .
(d) After 10 plays, find the winner by comparing the accumu-
lated moves of the two players.
(e) Print the winner as shown in the sample RUN.

RUN (Sample RUN)

PLAYER 1 IS THE WINNER


WITH A TOTAL OF 52 HOVES
MATRI X STATEMENT S AND LIBR ARY FUN CTIO N S 439

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

9. It was demonstrated in a sample program on page 417 that the


random number generator can be used to simulate the roll of a
pair of dice. Write a program that finds out how many times a roll
of dice adds to 7 if the pair are rolled 50 times. Remember, the
random numbers must be converted to whole numbers between
1 and 6 inclusive.
(a) Use a FOR /NEXT loop to control the number of times the pair of
dice are rolled .
(b) Keep a running counter to accumulate the number of times
the number 7 is rolled .

RUN (Sample RUN)

THE NUMBER 7 WAS ROLLED


12 TIMES OUT OF 50 ROLLS
MATRI X STATEMENTS AND LIBRARY FUNCTIONS 441

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

10. In Chapter Six, you were asked to write a program to convert


weekly wages to hourly rates based on a 40-hour week. (See
Review Problem 1 on page 242.) Write a new program, this time
using wages of $455 , $493, and $525 , and incorporating the
following changes:
(a) Store the data and the hourly rates in 2 one-dimensional
arrays.
(b) H I R t Weekly Wage
our y a e = 40
(c) Use the INT function to round off each hourly rate to the
nearest cent. (The number of decimal places is 2.) Use one
statement to find the hourly rate and to round it off .
(d) Use the MAT READ statement to read the data and MAT PRINT
statements to print the weekly wages and the hourly rates.
(e) If your computer system does not support MAT statements,
read and print the data in a FOR/NE XT loop . Use another
FOR/NEXT loop to print the hourl y rates. Don't forget to place
an extra blank PRINT statement before the statement that
prints HOURLY RATE S so that this heading is printed on a new
li ne .

Using MAT Statements Without MAT Statements

RUN RUN

l~EEKL Y WAGES WEEKLY WAGES


455 455 493 525
HOURLY RATES
493 11.38 12.33 13.13

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).

10.1 THE TAB FUNCTION


Until now, the output of a program was formatted (arranged) by the
computer. This type of output is known as format-free output. Your
only control was in the horizontal spacing of items by the use of
commas or semicolons in a PRINT statement. The TAB function is a
feature that gives greater flexibility in the positioning of items. Used
only in PRINT statements (and available in most versions of BASIC) , it
instructs the computer to override a print zone and skip to a specific
column to display an item. It is similar to the setting of tab stops on a
typewriter. Here is the general form.
Semicolon

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.

(a) 3~ PRINT TAB(3H"NAME";TAB(11';


40 PRINT "ADDRESS";TAB(22);"ACCOUNT ";
50 PRINT ·NUMBER"

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

(b) 30 PRINT TIUI(3);"NAME";TAB(11);"A(I[lRESS"


;TAB(22);"ACCOUNT NUMBER"

Both examples print the heading

NAME Atl(lRESS ACCOUNT NUMBER

By eliminating line numbers 40 and 50 and the two PR INTS, the


number of coded lines can be reduced to two.
Care must be taken when reaching the last print position in a line.
On an interactive system , the cursor automatically shifts to the first
position in the next line and waits for the statement to be completed . If
there are no other characters to enter, the RETURN ke y must be
pressed to transmit the typed stateme nt to memory, even though the
cursor is positioned on a new line .
Shown below are a number of PR INT statemen ts that use the TA B
function to format output.
1.

30 PRINT TAB(0);"HI"

HI starts in the left-most column .


2.

30 PRINT TAB(12);"HI"

This time HI is printed in column 12 , which is actually the


thirteenth column, since the left-most column is numbered 0.
3.
446 PROGRAMMING IN BASIC

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.

Next available print zone.

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

Tabulates to the column Tabulates to the column


set aside for the space set aside for the first
that precedes a positive digit of a positive number.
number.
AD VANC ED OUTPUT FE AT UR ES 447

These examples print a positive number. As mentioned in a


previous chapter, some computer systems leave a space before
a positive number for the assumed plus sign. This means that the
space is considered as the first character of the number and a
column is set aside for this space. When you tabulate for the
number, you must tabulate to the column reserved for this space.
Other computers leave no space before a positive number. In
this case , you tabulate to the column reserved for the first digit of
the number. In this book , a positive number is preceded by a
space and you must tabulate to the co lumn set aside for this
space.

6.

10 LET B=-15
20 PRINT TAB(4);B

This example prints a negative number. When the number is


negative , you must tabulate to the column set aside for the sign,
since the minus sign is the first character of the number.
7.

10 LET 1=7
20 LET J::30
30 PRINT TAB(I);"Hl";TAB(J-l);"THERE"

Arguments may be variables or arithmetic expressions as well as


constants (numbers). The argument of the first TAB function in
line 30 instructs the computer to print HI starting in column 7 .
In the second TAB function, the expression is evaluated
(30-7= 23), and the string THERE is printed -starting in column
23.
8.

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"

The INT function is automaticall y applied to the argument 16.85.


This means that the number is truncated and the integer part (16)
is retained . The string HELLO starts in column 16.

10.

6~ PRINT TAB(49);"HELLO"

10 I 9
I I - First line
I I iH LLO Second line

HELLO is to be printed in column 49 , which is th e fiftieth column


whe n you consider the left- most column as column 1. Since the
computer allows only 40 columns on one print line , the string
HELLO will be prin ted on the next line in column 9. This is
because 50- 40= 10, which is the tenth column when you co n-
sider the left-most column as column 1, but the ninth column
when you consider the left-most column as column zero .

11 . The TAB function is often used in the spacing of headings .

1~ PRINT TAB(2);"RETAIL PRICE";TAB(19);"


TAX";TAB(27);"TOTAL COST"

Notice that the PRINT statement takes up two lines, since it


contains more than 40 characters . Also , headi ngs should be
placed outside a loop so that the y are printed only once.

12. The head ings in Examp le 11 can be printed on two lines .


ADVA NCED OUTPUT FE ATURE S 449

10 PRINT TAB(7);"RETAIL";TAB(27);ITOTAL"
20 PRINT TAB(7);"PRICE";TAB(18);"TAX";TA
B(27);"COST"

n1 111 1 1~~I~1ffi lli~JI I I I I I ri~~ II 11111 1


Line 10 prints the word RETAIL starting in column 7 and the word
TOTAL starting in column 27. This statement ends in the fortieth
position of the line. If you are using an interactive system with a
40-character line, your cursor will have dropped to the first
position in the next line . As already mentioned, you must press
the RETURN key to transmit the statement to the computer's
memory , even though the cursor is positioned on a new line. Line
20 prints PRICE starting in column 7, TAX starting in column 18,
and COST starting in column 27 . Because this statement con-
sists of more than 40 characters, it is continued on the next line .
Remember, the computer used for these programs has only
40 columns to one print line. If your system allows more charac-
ters on one line, your centring will be different. For example , if
you are using a computer that has 75 columns to a line, the
headings could be centred as follows .

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

Notice that more spacing is left on both sides of the headings,


since there are 75 columns to a print line instead of 40 .

To centre the headings , you must determine the number of


spaces that must be left on either side of the headings. To do this ,
subtract the total number of print positions that will be used
(including the spaces between columnar headings) from the
number of positions on a print line and divide the result by 2.
Using the second output in Example 12, the first line will be
centred, since it is the longer of the two . This line has 24
characters including the 13 spaces between the words RETAIL
and TOTAL. Because the computer, in this example, has 75 print
positions , 24 is subtracted from 75 and the difference (51) is
divided by 2. The result is 25 (the fraction is dropped) so that
there are 25 spaces to the left of the headings and 26 spaces to
the right of the headings .
In this chapter and in the remaining chapters of this book, all
programs and problems are written for a computer that has a 40-
450 PROGRAMMING IN BASIC

character line, that considers the left-most column as the zero


column, and that leaves a space before a positive number . The
space before a positive number and the minus sign before a
negative number are considered part of the respective number.

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

Notice that there is no need to tabulate for SALES since it begins


in column zero. The computer is instructed to tabulate to column
7 for the first dollar sign and to column 8 for the amount 150.45 .
-Because the computer leaves a space for the sign of a positive
number, column 8 is left blank . It is not possible to eliminate this
space, even if you tabulate to column 7 for the amount 150.45,
since the carrier is already past this column after printing the
dollar sign and you cannot tabulate backwards . If you are using a
computer that leaves no space for a positive sign, column 8 will
be filled in with the 1 of 150.45 and the amount will be printed as
follows .

Completing the PRINT statement , the computer tabulates to


column 21 before printing COMMISSION, then tabulates to
column 33 for the second dollar sign, and finally tabulates to
column 34 for the amount 22.57.

10.1 THE TAB FUNCTION-Sample


Programs
I. Here is one of the "Your Turn " problems that was presented in
Chapter Five on page 152. This time the headings shown in
Example 12, page 449, will be printed and ·the data and results
AD VANCED O UTPUT FE ATUR ES 451

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

01 REM R--RETAIL PRICE


02 REM T--TAX
~3 REM C--TOTAL COST

10 REM PRINT THE HEADINGS


20 PRINT - Leaves a blank line.
30 PRINT TAB(7);IRETAIL";TAB(27);ITOTAL" - Prints the first line of the
heading using the TAB
function for centring .
40 PRINT TAB(7);IPRICE";TAB(18);ITAX";TA - Prints the second nne of the
B(27); "COST" heading using the TAB
function for centring .
50 PRINT - Leaves a blank line.

100 REM CALCULATE THE TOTAL COST


101 REM PRINT THE AMOUNTS
110 READ R - Reads the values of R one at
a time.
- Provides the READ statement
with data.
130 IF R=99999 THEN 999 - Checks for the trailer vafue .
140 LET T=R*.05 - Calculates the sales tax .
150 LET C=R+T - Calculates the total cost of a
watch .
160 PRINT TAB(8);R;TAB(17);T;TAB(26);C - Prints the retail price , sales
tax , and total cost using the
TAB fu nction for centring .
170 GO TO 110 - Transfers control back to the
RE AD statement .
999 END - Terminates program
execution .
452 PROGR AMMI NG IN BASIC

Your output should be as follows .

~ 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.:..

Since the space for an assumed plus sign is considered to be


part of a positive number, this space must be taken into consid-
eration when centring the number under its heading . Examine
the TAX column . The T in the heading TAX is printed in column 18
(the argument of the TAB function is 18) .

TAB ( 18) ; "T AX "

The space before the number 2.75 is printed in column 17 (the


arg ument of the TAB function is 1 7) .

TAB(17);T

This gives the following output.

17 18
TAX
'2 t 71s
t
I
Blank column

If the arguments had been the same, the output would be as


follows .

18
TAX
~
"- .75
iBlank column
ADVA NCED O UTPUT FEATURES 453

The amount 2.75 is no longer centred under TAX .


II. It was mentioned on page 447 that the argument of the TAB
function may be a variable . This allows pictures or graphs to be
drawn under programmer control, since the value of the argu-
ment may vary. Here are some examples.

1. A Letter of the Alphabet


Th is program pri nts the letter T. Notice that the sym bois used to print
the letter are also T's.

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

Lines 20 to 40 - These lines form a loop in which seven T's are


printed on one line (the PR INT statement ends with a semicolon). The
line of T's starts in column 6 (5+1 = 5+ 1 = 6) and ends in column 12
(5+1 = 5+ 7 = 12) .
Line 50 - Counteracts the semicolon after PRINT statement 30, caus-
ing the next T symbol to be printed on a new line.
Lines 60 to 80 - These lines form a loop, in which six T symbols are
printed . Each T is printed on a new line (the PRINT statement ends with
no punctuation) and each symbol is printed in column 9.

2. A Bar Graph (Histogram)


Suppose you want to compare the sales of six stores . This can be
done graphically by means of a histogram . In the following program,
each column of a bar represents $1000 worth of sales . Store 1 has
sales of $6000 since it has 6 columns of asterisks ; store 2 has sales of
$9000 since it has 9 columns of asterisks, etc. Notice that each bar
has two lines of asterisks . A blank line separates the bars of two
stores .

121 PRINT
20 FOR 1=1 TO 6
454 PROGRAMMING IN BASIC

31!1 REAli A,B


40 DATA 1,6,2,9,3,2,4,IB,5,13,6,4
50 PRINT A;
60 FOR J=1 TO 2
70 FOR K=l TO B
80 PRINT TAB(3+K);"*";
90 NEXT K
100 PRINT
110 NEXT J
120 PRINT
130 NEXT I
999 END
f,UN

1 ******
******
2 *********
*********
3 **
**
4 **********
**********
5 *************
*************
6 ****
****

Line 30 - Assigns data to variables A and B. A represents the


number of the store and B represents the number of asterisks to be
printed (the amount of sales) .
Line 50 - Prints the store number in column one opposite the first
line of each bar.
Line 60 - Sets up a loop to print two lines of asterisks for each bar.
Line 70 - Sets up a loop to print a number of asterisks on one line ,
the number depending on the value of B .
Line 80 - Prints the asterisks starting in column 4 (3+ K = 3+ 1 = 4)
and ending in column 3+ B (3+ K = 3+ B, where B has been assigned
a value by the READ/ DATA statements) .
Line 100 - Counteracts the semicolon at the end of PRINT statement
80 in order to print the second row of asterisks of each bar on a new
line .
Line 120 - Leaves a blank line between two bars.

3. The Graph of a Function


This program draws the graph of the function X= y2, where y ranges
from 6 to - 6 inclusive. Thus, when y= 6, X= 36 and an asterisk is
ADVANC ED O UTP UT FE ATU RE S 455

prin ted in column 36 . When y = 0, X= (/) and an asteris k is printed in


column zero . When y= - 6 , X= 36 and an asteris k is printed in column
36 . These values of x are used in the TAB function to gi ve the
horizontal placement for the asteri sks . For vertical placement, the
PRINT statement that prints an asterisk ends without a comma or a
semicolon , which causes each asterisk to be printed on a new line.

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) .

10.1 THE TAB FUNCTION-


. Your Turn
I. Code PRINT statements with TA B fun ctions to produce the follow-
ing . Numbe rs are to be coded dire ctly into the PRI NT statemen ts;
do not assign them to variab les
456 PROGRAMMING IN BASIC

1.

2.

3.

4.

5.

0 8 24 J1
AM T
I~
0 -. O~IN I~ Tk~ E \1

6.

11 11111 ~+itITI IIII II III L~~~~I


II. Show the output of each of the following program segments .
Indicate the column in which the first character of each item is
printed . Remember , the computer used for the programs in this
book cons iders the space for the assumed plus sign of a positive
number as the first character of the number.
ADVAN C ED O UTPUT F:EATURES 457

2.40 PRINT TABC1~);INUMBER";TABC23);"RATE


PER"
5~ PRINT TAB(9);"OF HOURS";TABC2S);"HOUR

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

4.40 PRINT TAB(12);IHOW";TABCS);"ARE";TABC


26);"YOU?"

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"

8.40 PRINT TAB(52);"BYE"

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

IMOiNTH' 1\ Hio RS E III L

~ 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

10.1 THE TAB FUNCTION - Solutions for "Your


Turn"
I.

1. 40 PRINT TAB(0);24;TAB(16);-49

2.40 PRINT TAB(12);ISALES";TAB(22);3600

3.40 PRINT TAB(17);"Xty =";TAB(26);94

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

HOURS : Column '/)


RATE : Column 12

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.

1~III I I IJIIJ±tt-il~RIE I I II [t~j~?


HOW: Column 12
ARE: Column 15
YOU ? : Column 26

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.

BYE: Column 12 on the second line .

III .

01 REM R--RATE PER KILOWATT-HOUR


~2 REM H--KILOWATT HOURS
~3 REM B--BILL

1~ REM PRINT THE HEADINGS


28 PRINT
30 PRINT TAB(6);"MONTH";TAB(16);"K HOURS
"HAB(29); "BILL"
40 PRINT

100 REM CALCULATE THE BILL AND


101 REM PRINT THE DATA AND AMOUNTS
110 LET R=.035
120 FOR 1=1 TO 3
130 READ H
462 PR OGRA MMING IN BAS IC

14~ DATA 1000,950,930


1. ~S0LET B=H*R
160 PRINT TAB(7);I;TABC17);H;TAB(28);B
in) NEXT I
999 END

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

10.2 THE PRINT USING AND IMAGE


STATEMENTS2
Another method to format output is by means of the PRINT USING
and IMAGE statements. Until now, the printed numbers either had
too many decimal places (and had to be rounded off by the INT
function) or they had an insufficient number of decimal places, since
insignificant zeros were not printed (e.g., 2.40 was printed as 2.4).
Th e PRINT US ING and IM AGE statements can also be used to align
decimal points and print dollar signs. Yo u no longer need to code
lengthy and cumbersome PRI NT statements such as

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

in order to print the following .

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

40 PRINT USING 200


1 1
"PROGRESS"," REPORT"

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.)

1. The PRINT USING and IMAGE statements may be used to set up


headings.

10 PRINT USING 100,"RETAIL","TOTAL"


15 PRINT USING 110,"PRICE",·TAX",·COST"
100: _______ lttttt ______________ ttttt
110: _______ tttttt _____ ttt ______ tttt

Reserved Locations

100: _______ lttttt ______________ ttttt


RETAIL TOTAL
110: _______ tttttt _____ ttt ______ tttt
PRICE TAX COST

Output

Line 10 instructs the computer to print the strings RETAIL and


TOTAL using IMAGE statement 100 as follows.
ADVANCED OUTPUT FEATURES 465

(a) Leave 7 spaces .


(b) Print the string RETAIL starting in column 7 Strings are left-
justified, which means that they start in the left-most column of a
field 4
(c) Leave 14 spaces.
(d) Print the string TOTAL starting in column 27.

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.

11~: _______ tttttt


F'F: I eEl
Left blank

(c) Leave 5 spaces.


(d) Print the string TAX starting in column 18.
(e) Leave 6 spaces.
(f) Print the string COST starting in column 27.

2. Instead of coding strings in a PRINT USING statement, they may be


placed directly into an IMAGE statement. The PRINT USING and
IMAGE statements for the above headings will now look as fol-
lows.

10 PRINT USING 100


15 PRINT USING 110
l~~: _______ RETAIL ______________ TOTAL
110: _______ PRICE ______ TAX ______ COST

3. This example prints a positive integer.

20 PRINT USING 120,158

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

120=- ___ •••••


158

Output

ru 5
1 I 1 i11JJ
Excess column
/\ Column left blank if the
left blank number is positive

Line 20 instructs the computer to print the number 158 using


IMAGE statement 120 as follows:
(a) Leave 4 spaces.
(b) Print the number 158 right-justified. This means that the last
digit is printed in the right-most column of the field and the
remaining digits are printed consecutively to the left of this
digit. The column reserved for the sign is lett blank if the
number is positive. Excess columns to the lett of the
assumed plus sign are also filled with blanks. Remember ,
the computer being used leaves a space for an assumed
plus sign and this space is considered to be part of the
number. Thus , the field specification for any number (posi-
tive or negative) must include a column for the sign .
4. This example prints a negative integer.

25 PRINT USING 130,-159

13~: ____ •••••

Reserved Locations Output

1° 1 1111~1 115191
130: ____ •••••
-159
iExcess column
lett blank

Line 25 instructs the computer to print the number -159 using


IMAGE statement 130 as follows.
ADVANCED OUTPUT FEATURE S 467

(a) Leave 4 spaces .


(b) Print the number - 159 right-justified . Since the number is
negative , the column reserved for the sign is filled with a
minus sign. Again , excess columns to the left of the number
are filled with blanks .
5. This example shows how a decimal number can be printed .

30 PRINT USING 140,94.6

Reserved Locations Output

140: ____ •••••••


94.6 [ Um9hl11J
/ r Fille~ithazero
Excess column Column left blank if the
left blank number is positive

Line 30 instructs the computer to print the number 94.6 using


IMAGE statement 140 as follows.
(a) Leave 4 spaces .
(b) Print the number 94 .6. Notice that a decimal point is coded
within the number symbols . Excess columns to the left of the
decimal po int are filled with blanks ; excess columns to the
right of the decimal point are filled with zeros .
6. Both the PRINT USING and IMAGE statements combine numbers
with strings in this example.

35 LET K=1000
40 LET B=33
45 PRINT USING 150,K,"BILL",B

Reserved Locations

150: __ K HOURS •••••••• _____ ••••• __ ••••••


1B00 BILL 33
468 PRO G RAMMING IN BAS IC

Output

Excess columns
i
Filled
left blank with two
number is zeros
positive

Line 45 instructs the computer to print the values of K and B


using IM AGE statement 150 as follows.
(a) Leave 2 spaces.
(b) The IMAGE statement supplies the string K HOURS.
(c) Print the number 1000 right-justified, Eight positions are
reserved for the number , Four positions are for the digits;
one position is for the assumed plus sign and is left blank ;
three positions are extra . These three extra positions are
also filled with blanks .
(d) Leave 5 spaces .
(e) Print the string BILL left-justified. Five positions are
reserved for the word; 4 positions are for the fou r letters; the
fifth position is extra and is filled with a blank.
(f) Leave 2 spaces.
(g) Print the number 33 right-justified with the decimal point.
Three positions are reserved to the left of the decimal point.
Two positions are for the digits , the third position is for the
assumed plus sign and is left blank. The two reserved posi-
tions to the right of the decimal point are filled with zeros .
7. Here is an example of what happens when field specifications are
too small .

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.

65 PRINT USING 170,"COST","TAX','TOTAL'

Reserved Locations

17B: ____ t t t t t _____ t t t


COST TAX
TOTAL

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

9 . When there are more field specifications than items to be printed,


the extra fields are ignored .

70 PRINT USING 180,·COST","TAX·

Reserved Locations

180: ____ ••••• _____ ••• _____ •••••


COST TAX i
Ignored

Output

The remaining programs ill ustrate additional features available in


most vers io ns of BASIC that support the PRINT USING and IMAGE
statements.
10. Whole numbers can be aligned in a column and decimal points
can be aligned one under the other.

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

11. Numbers can be rounded (some computers truncate) and dollar


signs can be printed.

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

If your computer truncates a decimal number, increase the


number by a small amount (the amount depends on the number
of desired decimal places). For example, to round 853.9254 to
two decimal places, the following PRINT USING and IMAGE state-
ments may be used.

40 PRINT USING 70,Ct.005

70: ___ $ttt.tt


99 END

After adding .005 to 853.9254, the result is 853.9304. This


number is truncated to two decimal places , since there are two
number symbols after the decimal point in the IMAGE statement.
The output is $853 .93 .
12. The PRINT USING and IMAGE statements may be used to convert
ordinary numbers to scientific notation . To inform the computer
of the conversion, four exclamation marks must follow the num-
ber's field specification (##. ### II!!). The symbol E, a sign, and
a two-digit exponent will replace these explanation marks.

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 "- "

H" LET A=52.64


20 LET B=-63.89
30 PRINT
40 PRINT USING 50,A,B
50: ___ +11.11 _____ +11.11
99 END

RUN

+52.64 -63.89

(b) When a minus sign is placed before a number's field specifi-


cation, some computers print a minus sign before a negative
number and leave a space before a positive number. Other
systems print a minus sign before a positive number and
indicate an error for the negative number.

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

(c) When there is no sign before a number's field specification


and no position has been reserved for the sign, some com-
puters print a negative number without its sign, causing the
number to appear positive. Other systems consider the field
specification to be too small and indicate an error by printing
one or several asterisks or number symbols, or a percent
symbol as explained on page 469.

1B LET E=-42.53
2B PRINT
AD VAN C ED O UT PUT FEATURES 473

3~ PRINT USING 4~,E


4~: ____ tt.tt
99 END

RUN

42.53

14 . With the exception of the number symbol (# ) that designates a


field , PRINT US ING statements will print an y character that appears
in an IM AG E statement. This includes periods, commas , and
dollar signs within a field , and exclamation marks that do not form
the set that converts numbers to scientific notation . Some com-
puter systems will not print a row of asterisks . The following
example prints a colon after the word SALES , a dollar sign before
the number 69413.87, and a comma and a decimal point within
the number.

10 LET S=69413.87
20 PRINT
3~ PRINT USING 4~,S
4~:___ SALES: _____ $tt,ttt.tt
99 END

RUN

SALES: $69,413.87

Some computers offer a number of specialized features. Several


are mentioned below . Check your manual for features offered by your
computer system.
1. Amounts can be protected by printing asterisks to the left of the
number.
2. Dollar signs can float so that a dollar sign is alwa ys printed just
before any number regardless of the length of the number.
3. Asterisks can fill unused positions to the left of a number with a
floating dollar sign printed just before the number.
4. Commas can be automatically inserted in any number to segre-
gate digits in groups of three , working from right to left
Some computer systems do not require an IMAGE statement. Instead ,
the image is assigned as a string to a string variable. 5 The computer
"calls" the image by referencing the string variable in a PRINT USING
statement. The programs shown below were written for a computer
that requires a semicolon after this string variable. One or several
variables, whose values are to be printed, follow the semicolon. The

5. A string variable is represented by a letter of the alphabet followed by a dollar sign


($) A string mu st be encl osed in qu otati on marks when it is assigned to a string
variable by the LET statement. Strings and string variables are discussed in detail in
Chapter 12 .
474 PROGRAMMING IN BASIC

computer used designates locations for numeric values in the image


by number signs (#) , while the locations for string values are delim-
ited by percent signs (%) . The computer leaves a space before a
positive number. There are 9ther variations in the coding of the PRINT
USING statement and the LET statement that contains the image. For
example, in the PRINT USING statement some systems require a
comma instead of a semicolon after the string variable that stores the
image. In the image, some computers require a series of number
signs (#) to designate a string instead of percent signs (%) that
delimit the string. You should refer to your manual to find out how to
code these two statements for your computer system. The following
examples are taken from this section. Your output for some may be
slightly different than what is shown on the referenced page. The
hyphens indicate spaces.
1. Example 3, page 465 (Prints a positive integer.)

1~ LET N=158
2~ LET F$=" ____ ttttt"
30 PRINT
40 PRINT USING F$;N
99 END

2. Example 4, page 466 (Prints a negative integer .)

10 LET N=-159
20 LET F$=" ____ ttttt"
30 PRINT
40 PRINT USING F$;N
99 END

3. Example 5, page 467 (Prints a decimal number.)

10 LET N=94.6
20 LET F$=" ____ tttt.tt"
30 PRINT
40 PRINT USING F$;N
99 END

4. Example 6, page 467 (Prints numbers and strings.)

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 .

5. Example 7, page 468 (Field specifications too small.)

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

SALES /.1500 COMMISSI 185

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 .

6. Page 469 (Insufficient number of field specifications .)

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

SALES 15~0 COMMISSION SALES 185

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.)

U:,) READ A,B,C


20 DATA 325,32,3
476 PROGRAMMING IN BASIC

31a READ A1,B1,C1


4~ DATA 325,32.5,3.25
5~ LET F$=· ___ tttt _____ tttt.t.·
60 PRINT
7~ PRINT USING F$;A,Al
80 PRINT USING FS;B,Bl
90 PRINT USING F$;C,C1
99 END

8. Examples 11 and 14, pages 471 and 473


(Rounds off numbers and prints special characters.)

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

9. Examples 13 (a) and 13 (b), page 472


(Prints plus and minus signs before numbers.)

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.

10. Sample Program, page 478 (Modify statements as follows)

30 PRINT • _______ RETAIL ______________ TOTAL·


4~ PRINT • _______ PRICE ______ TAX ______ COST·

160 LET F$=· ________ $tt ______ $t.tt ____ $tt.tt·


170 PRINT USING F$;R,T,C

It should be noted that on some computer systems , the PRINT


USING statement must have at least one numeric variable in its list of
variables. For example, if RETAIL and TOTAL are assigned to string
variables and the string variables are listed in the PRINT USING state-
ment, the computer may display an error message unless a numeric
variable is also in the list.

10.2 THE PRINT USING AND IMAGE


STATEMENTS- Sample Programs
1. The following program was listed in Section 10.1 on page 451.
Instead of using the TAB function to format the output, this
program uses the PRINT USING and IMAG E statements. Here is the
problem once more.
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 statements to enter the retail price of
each watch.
(b) Use a trailer value to terminate input.
(c) Sales Tax = Retail Price x .05
(d) Total Cost = Retail Price + Sales Tax

~1 REM R--RETAIL PRICE


fl2 REM T--TAX
~3 REM C--TOTAL COST

10 REM PRINT HEADINGS


20 PRINT - Leaves a blank line.
30 PRINT USING 50 - Prints the first line of the heading using
IMAGE statement 50.
478 PROGRAMMING IN BASI C

40 PRINT USING 6~ - Prints the second line of the


heading using IMAGE statement 60.
50: _______ RETAIL ______________ TOTAL -IMAGE statement that provides the
format for the first line of the heading .
-IMAGE statement that prov,i des the
format for the second line of the
heading .
7~ PRINT - Leaves a blank line .

10~ REM CALCULATE THE TOTAL COST


1~1 REM PRINT THE AMOUNTS
lUI READ R - Reads the values of R one at a time .
120 DATA 55,50,4~,99999 - Provides the READ statement with data.
13~ IF R=99999 THEN 999 - Checks for the trailer value.
140 LET T=R*.11I5 - Calculates the sales tax.
150 LET C=RtT - Calculates the total cost of a watch .
16~ PRINT USING 170,R,T,C - Prints the retail price, sales tax, and
total cost, using IMAGE statement 170.
-IMAGE statement that provides the
format for PRINT USING statement 160.
18111 GO TO 11~ - Transfers control back to the READ
statement.
999 END - Terminates program execution .

The output should be as shown below .

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~

2. The PRINT USING and IMAGE statements can be used to print


letters of the alphabet. On page 453, the letter T was printed by
means of the TAB function. The following program uses the PRINT
USING and IMAGE statements to print the same letter 6

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

30! ______ TTTTTTT


40 FOR 1=1 TO 6
50 PRINT USING 60
6~: _________ T
70 NEXT 1
99 END

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.

10.2 THE PRINT USING AND IMAGE


STATEMENTS- Your Turn 7
Many sample programs and lines of output were shown in this
section. A page number is written opposite each question so that you
may quickly refer to a particular example if you need help. Keep in
mind that the computer being used has a 40-character line, considers
the left-most column as the zero column, and leaves a space before a
positive number.
l. Write programs that produce the following outputs. Use one or
several PRINT USING statements but only one IM AGE statement.
1. Write two programs for the output shown below.
(a) In one program, code the strings in the PRINT USING
statement.
(b) In the other program, code the strings in the IMAGE
statement.

(Pages 464 and 465)

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

2. Code the numbers shown below in the PRINT USIN G state-


ment. Use the IM AG E statement simply to format .

(Pages 465 and 466)

3. Use LET statements to assign the amounts to variables .


Code the strings as well as the dollar signs, the comma , and
the decimal points in the IMAGE statement.

(page 473)

4. Use the READIDATA statements to enter the numbers into the


computer . Print the numbers al igned in a column as shown
below .

.~ :1 .--
689
94
5

(Page 470)

5. Use the . RE ADIDATA statements to enter the numbers


4.68945 , 87 .25391 , and 317 .52849 into the computer . Align
the decimal points and round off the numbers to two decimal
places by means of the PRINT USIN G and IM AG E statements .

~ 19
4. 69
Ie7 .25
131 7 . 1~3

(Pages 470 and 471)


ADVANCED OUTPUT FE ATURES 481

6. Rewrite the program for Problem 5. This time place a dollar


sign before each number.

I
21 91

:617 I~31
4 .6
87 .2
C'
• ..J
(Page 471)

7. Use the LET statement to assign 98765.432 to a variable.


Convert the number to scientific notation .

(Page471)

8. Use LET statements to assign the numbers shown below to


two variables . Code an IMAGE statement that produces a
plus sign before the positive number, and a minus sign
before the negative number.

121 6
+4 3. 62
-5 9. lis

(Page 472)

9. Rewrite the program for Problem 8. This time , code an IM AGE


statement that produces a minus sign before the negative
number , but no sign before the positive number. Reserve
only two print positions for the digits to the left of the decimal
point.

(Page 472)

10. (a) What happens when a field specification is too narrow


for :
(i)A string?
(ii)A number?
482 PROGRAMMING IN BASIC

(b) What is the output of the following program? Indicate the


columnar position of each item .

10 LET 5=46327
20 PRINT
30 PRINT USING 40,"TOTAL SALES",S
40: _____ tttttttt _____ ttt
99 END
(Page 468)

11. (a) What happens when there is an insufficient number of


field specifications for the number of items to be
printed?
(b) What is the output of the following program? Indicate the
columnar position of each item.

1.0 LET 5=46327


20 LET C=925
~50 PRINT
40 PRINT USING 50,"SALES",S,"COM.",C
50! _____ ttttt _____ ~ttttt

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

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 READIDATA statements to enter the data
(kilowatt-hou rs) .
(c) Bill = Kilowatt-hours x Rate (.035)
(d) Use the PRINT USING and IMAGE statements to print the
headings , the data, and the results as shown in the
output below . Code the headings in the IMAGE state-
ment.

'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.2 THE PRINT USING AND IMAGE


STATEMENTS-Solutions for "Your Turn"g
I. 1. (a) Strings Coded in the PRINT USING Statement

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.

Using a String Variable (Problem 3)

1.0 LET 5=4000


20 LET C=600
30 LET F$=· __ 5ALES __ $t,ttt.tt ___ COM. __ sttt.tt·
40 PRINT
50 PRINT USING F$;S,C
99 END

Using a Regular PRINT Statement (Problem 1)

10 PRINT
20 PRINT ' __________ DEPOSIT _____ BALANCE'
99 END
ADVANC ED OUTPUT FE AT URE S 485

(b) Strings Coded in the IMAGE Statement

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.

Systems That Truncate a Number


121 READ A,B,C
20 DATA 4.68945,87.25391,317.52849
30 F'RINT
40 PRINT USING 7B,A 421 PRINT USING 70,A+.0e5
50 PRINT USING 70,8 50 PRINT USING 7e,B+.0B5
60 PRINT USING 7B,C 60 PRINT USING 7B,C+.BB5
70: _________ tttt.tt
99 END
486 PROGRAMMING IN BASIC

6.

Systems That Truncate a Number


1,0 READ A,B,C
20 DATA 4.68945,87.25391,317.52849
30 PRINT
40 PRINT USING 70,A 40 PRINT USING 70,A+.005
50 PRINT USING 70,B 50 PRINT USING 70,B+.005
60 PRINT USING 70,C 60 PRINT USING 70,C+.005
70: _________ ••••• tt
99 END

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.

:1.0 LET A=43.62


20 LET B=-59.18
30 PRINT
40 PRINT USING 60,A
50 PRINT USING 60,B
60: ______ - •••••
99 END

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

positions that are available . Since a string is left-


justified , the right-most characters that have no reserved
locations are discarded .
When a field specification is too narrow for a number,
some computers fill the available positions with aster-
isks or with number sy mbols (#) . Other computers print
the number with one asterisk (*) , or one number symbol
(#), or one percent symbol (%) to the left of the number.

(b)

r, 1111~JIlJd1fffi[rrB or

11 . (a) When there is an insufficient number of field specifica-


tions for the number of items to be printed , 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.

(b)

21
$46327 First line
$ 925.L.-'..-J_
- S ec·ond line

or

1211

12 . (a) When there are more field specifications than items to


be printed , the extra fields are ignored.

(b)

1211

II.

21 1 REM R--RATE PER KILOWATT-HOUR


488 PROGRAMMING IN BASIC

02 REM H--KILOWATT HOURS


03 REM B--BILL
1~ REM PRINT THE HEADINGS
2~ PRINT
3~ PRINT USING 40
40! ______ MONTH _____ K HQURS ______ BILL
50 PRINT

100 REM CALCULATE THE BILL AND


101 REM PRINT THE DATA AND AMOUNTS
110 LET R=.f2J35
121:1FOR 1=1 TO 3
13~ REA[I H
140 DATA 1000,950,93121
1.50 LET B=H*R
16~ PRINT USING 171:1,I,H,B
170: _______ I I ________ I I I I I ______ $lt.11
180 NEXT I
999 END

Using a String Variable

160 LET F$=" _______ lt ________ ttltt ______ $tt.111


170 PRINT USING F$;I,H,B

III.

Using a Regular PRINT Statement


10 PRINT
20 FOR 1=1 TO 6
30 READ B
40 DATA 6,9,2,10,13,4
50 FOR J=l TO 2
60 FOR K=1 TO B 60 FOR 1\=1 TO B
70 PRINT USING 80; 70 PRINT "X';
80:X 9~ NEXT K
90 NEXT K
11210 PRINT
110 NEXT J
120 PRINT
130 NEXT I
999 END
ADVANCED OUTPUT FEATURES 489

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

60 PRINT TAB (10)


1 A

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

The TAB command instructs the computer to override a print zone


and to tabulate to a specific column before printing an item. Similar to
the setting of tab stops on a typewriter, it is often used to centre
headings and to centre items beneath the headings. It is also used to
draw pictures and graphs. 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 . Care must be taken when
tabulating, since forgotten items may not be inserted by tabulating
backwards.
The PRINT USING and IMAGE statements always work together. The
PRINT USING statement instructs the computer what to print and which
IMAGE statement to use ; the IMAGE statement provides the format.
The general form of each statement is as follows.

The PRINT USING Statement

Comma Comma

80 PRINT USING 100


1 "TOTAL SALES " ,T
1
I
Statement
number
I
PRINT
instruction
1
Indicates which
IMAGE statement
V
Items to be printed

will be used
490 PROGRAMMIN G IN BAS IC

The !MAGE Statement

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

These two statements greatly simplify the centring of headings and


numbers . Some computer systems do not use an IMAGE statement.
Instead , a PRINT US ING statement references a string variable to which
a formatted string (an image) has been assigned . Several addit ional
features are offered by the PRINT USING statement . They include the
following.
- Align whole numbers in a co lumn
- Align decimal points .
- Round off or truncate numbers and print insignificant zeros to the
right of the decimal point.
- Print dollar signs before amounts.
- Print commas within numbers to group digits .
- Print signs before numbers .
- Print special characters other than those used in formatting.
- Con vert numbers to scientific notation.

QUESTIONS AND EXERCISES


1. What is the purpose of the TAB function?
2. Display and label a PRINT statement that uses the TAB function to
print an item that starts in column 12.
3 . Write programs that produce the following outputs. Use the TAB
function to position items in specific column s. Ass ign all con -
stants to variables .

(a) MruIra 1 11 1 11 1 1 $lJ311 11 1 1 1 1 1 11-01219141.h~1


(b) ffff 1 1 1 1~IJJNITI!MffiIllJfW
ADV ANCE D OUTP UT FEATURES 491

(d) FH++ +-i-l-i-.F+ +H

(f) 'iej IT
I

4. Show the output of each of the following programs . Indicate the


columnar position of each item as in the output shown in Problem
3.

(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)

10 PRINT TAB(47);"DEPARTMENT NUMBER"


99 END
ADVAN CED OUTPUT FEATURE S 493

5. (a) What is the purpose of the PRINT USING statement?


(b) Display and label a PRINT USING statement.

6. (a) What is the purpose of the IMAGE statement?


(b) Display and label an IMAGE statement.

7. Write programs that produce the following outputs. Use one or


several PRINT USING statements but only one IMAGE statement. ' o
Assign all constants to variables by the READIDAT A statements.
(a) Write two programs for the output shown below.
(i) In one program, code the strings in the PRINT USING
statement.
(ii) In the other program, code the strings in the IMAGE
statement.

(b) Place the numbers in the columns as specified.

(c) Code the strings in the IMAGE statement .

(d) Align the numbers 248 , 48 , and 8 as shown below.

01 7
248
48
8

10. Instead of referencing an IM AG E statement, your computer may require a string


variable to which an image has been assigned . Also, if the computer needs a numeric
variable in the PRINT U SING statement , use the ordinary PRINT statement to format
Problem 7(a)
494 PROGRAMMIN G IN BASIC

(e) Round off each of the numbers 4.89457 , 96 .00587 , and


352 .66823 to three decimal places by means of the PRINT
U SING and IM AGE statements.

~
- ,-
-r- 'r-'
13 I
! 4.895
1 9'<'.~1~6
~~? ~1~8

(f) Round off each of the amounts 1234.567, 23456.782 , and


345678.926 to the nearest cent by means of the PRINT USING
and IMAGE statements.

(g) In your program , code an IMAG E statement that produces a


plus sign before the positive number and a minus sign before
the negative number .

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.

(i) Enter the number .00812345, then convert the number to


scientific notation.
ADVA NCED OUTPUT FEATURES 495

Indicate the columnar position of each item when yo u show the


output of the following programs.
8. (a) What happens when more positions are reserved in a field
than are needed:
(i) For a string?
(ii) For a number that contains a decimal point?
(b) What is the output of the following program?

H'I LET T=25. 673


20 PRINT
3l!1 PRINT USING 5l!1,"TOTAL"
40 PRINT USING 60,T
5111: ____ ••••••••
60: ____ 44 ••••••••••
S'9 END

9. (a) What happens when a field specification is too narrow for:


(i) A string?
(ii) A number?
(b) What is the output of the following program?

1111 LET U=24936


2111 PRINT
3111 PRINT USING 4111, "UNIT PRICE",U
40: ______ ••••••• ______ ••••
99 ENII

10 (a) What happens when there is an insufficient number of field


specifications for the number of items to be printed?
(b) What is the output of the following program?

1111 LET 0=843


20 PRINT
3l!1 PRINT USING 40,"OUANTITY",0,"PRICE"
4111: _____ t ••••••• _____ ••••
99 END
496 PROGRAMMING IN BASIC

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

11. Remember, instead of referencing an IMA GE statement, your computer may


require a string variable to which an image has been assigned. If your computer
system does not support the PRI T USING statement, use just the TAB function to
format output. Use the ordinary PRI NT statement to format headings if your computer
requires a numeric variable in the PRINT USI G statement.
ADVANCED OUTPUT FEATURES 497

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 ~ +
+ +
++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++

3. On November 1 your checking account showed a balance of


$2000. During the month you made the following deposits and
withdrawals:

November 10 Withdrawal $ 100


15 Deposit 450
24 Withdrawal 120
30 Deposit 450

Write programs that calculate the balance in your bank account after
each transaction.

(a) Use the LET statement to assign the initial balance to a


variable, say B.
(b) Use the READ/DATA statements to enter the code and the
amount of each transaction.
(c) Use a code of 1 if the transaction is a deposit , a code of 2 if
the transaction is a withdrawal, and a code of 3 to terminate
the input.
(d) Use the ON .. . GO TO statement to branch to the appropriate
statements.
(e) Depending upon your code,

Balance = Balance + Deposit


or
Balance = Balance - Withdrawal
498 PROGRAMM ING IN BASIC

Using the TAB Function

Using the PRINT USING and IMAGE Statements

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,

$ 41c;~ 'I + 1 $ 681~

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

4. This problem is similar to one presented in Chapter Six (Problem


5, page 245) . Find the total sales for each of the three stores
shown below .

Store Number Sales per Month

1 2367.25, 1985.60, 2249.05, 1857


2 1952.30,2 149.15, 1767.80, 2364
3 2284.10, 1849.55, 1987.85,2 193
500 PROGRAMMING IN BASIC

(a) Use an outer FOR/NEXT loop to keep track of the stores.


(b) Use an inner FOR/NEXT loop to keep track of the months.
(c) Between the two FOR statements, initialize each store's total
sales to zero.
(d) Use the READIDATA statements to enter the sales.
(e) Total Sales = Total Sales + Sales per Month
(f) In the program that uses the PRINT USING and IMAGE state-
ments, code the headings in the PRINT USING statement. 12

Using the TAB Function

I2l 7 L ·rrf122 J IT~llTT


I I
I Sh"IOiRE I !
Tr~
I IF~LfS
I
1 I $ ~ 5~ ; . ~

I ~ I I ~I '~i31
$ ~1 ~14I~i .' 525

Using the PRINT USING and IMAGE Statements

!Jr~i1L ~~EiSI '


Ie 7
5TioR ~
I I
B '~~8 ' 19i01
1
2 I $
l
3 II ..
$1 8i' ') 3 3 . 21~1
._$ 1,3 ~ 4 • 5 e

5. Here is a problem from the "Your Turn" units of Chapter Eight.


Suppose a savings and loan company offers varying rates of
interest on investments depending on the length of time the
money is invested. The amount of the investment is $4000. Find
the yearly interest for each rate shown below. The interest is not
added to the investment each year it is calculated.

No. of Years Rate of Interest

Y R

10 12 14 .10 .11 .12


16 18 20 .13 .14 .15

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

(a) Store the numbers of years and the rates in 2 two-dimen-


sional arrays
(b) Use one set of nested FOR/ NE XT loops to read , calculate , and
print by rows.
(c) Store the calculated interests in a two-dimensional array.
(d) Interest = Amount Invested x Rate of Interest

Using the TAB Function

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

Using the PRINT USING and IMAGE Statements

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

6. This problem is an extension of Problem 9, Chapter Nine, page


440. This time you are to find out how many 7's and how many
11 's are rolled out of 50 rolls of the dice. Use the random number
generator to simulate the roll of a pair of dice. Remember, the
random numbers must be converted to whole numbers between
1 and 6 inclusive. See Chapter Nine , page 416 if you need any
help.
(a) Use a FOR /NEXT loop to control the number of times the pair of
dice are rolled .
(b) Keep two running counters, say S for seven and E for
eleven , to accumulate the number of times the numbers 7
and 11 are rolled.
(c) The output will be different for each RUN .
502 PROGRAMMING IN BASIC

Using the TAB Function

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

r lJ~ BEI 7 N ,HII ERI 11

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

7. A furniture store is offering a 12 112% discount on television sets at


its end-of-the-year sale. Calculate the discounts and the
reduced prices for six TV sets regularly priced at $853, $894,
$842, $925, $987, and $961.
(a) Use a FOR/NEXT loop to read the data, to perform the calcula-
tions, and to print the information shown below.
(b) Discount = Regular Price x .125
(c) Reduced Price = Regular Price - Discount
(d) In the program that uses the TAB function, use the INT func-
tion to round off each discount to the nearest cent. In the
program that uses the PRINT USING and IMAGE statements,
use these two statements to round off each discount and
each reduced price to the nearest cent. Output for the latter
program may be slightly different than the one following.
504 PROGRAMMIN G IN BASIC

8. Write a program that uses the TA B function to draw the figure


shown below.
(a) Print an asterisk in column 15.
(b) Use two FOR/NE XT loops:
(i) The first loop prints the remaining asterisks of the upper
part of the figure, Your PRINT statement should contain
two TAB functions. The first function has the argument
15-1 and the second function has the argument 15+1,
where 1 is the index of the loop .
(ii ) The second loop prints all but the last asterisk of the
lower part of the figure. The index of this loop should run
in a negative direction . The PRINT statement should have
two TAB functions with arguments that are the same as
the TAB functions of the first loop (the index may be
different).
(c) Following the NEXT statement of the second loop , print an
asterisk in column 15.

RUN

*
**
* *
* *
** **
* *
** **
* **
**
*
* *
* *
* *
** *
*
* *
* *
* *
**
*
- - - - - - - - - -- --

ADVANCED OUTPUT FEATURES 505

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.

Use three FOR/NEXT loops:


(a) The first loop draws the upper part of the curve:
- The value of the index should range from 6 to 1 inclusive.
- Square the value of the index.
-In one PRINT statement, print the symbol for the y axis in
column zero and the asterisk (which represents the
squared value) in column X
- Between the first and second loops, code the statement
that prints an asterisk in column zero.
(b) The second loop prints the x axis.
- The value of the index should range from 1 to 36 inclusive.
- Between the second and third loops, code a "blank"
PRINT so that the symbol for the y axis and the next
asterisk are printed on a new line.
(c) The third loop prints the lower part of the curve.
- The value of the index should range from - 1 to - 6
inclusive.
- The statements within this loop should be the same as
those within the first loop.

Note: Two PRINT statements each require a semicolon at


the end of the statement. Check your program carefully to
determine which PRINT statements need this punctuation
mark.

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:

1. (a) One subroutine.


(b) Several subroutines.
(c) Nested subroutines.
(d) Several su broutines by use of the ON. GOSU B statem e nt.
2. (a) Single-line, user-defined functions.
(b) Multiline, user-defined functions.

B. In addition, you should be able to:


1. Define a subroutine.
2. State the advantages of subroutines and user-defined func-
tions.
3. Explain how GOSUB and RETURN statements are executed.
4. Produce the output of programs.
5. Find errors in programs:
(a) Make corrections if there are errors.
(b) Show RUNS if there are no errors.
6. Define a user-defined function.
7. State the purpose of a DEF statement.
8. Explain where DEF statements and function references may
be placed in programs.
9. Display and label a DEF statement.
10. State the rules that must be observed when naming user-
defined functions.
11. Differentiate between a function definition and a function
reference
12. Define a dummy argument and state its purpose.
13. Define an actual argument and state its purpose.
14. (a) State how the argument in a function definition may be
expressed.
(b) State the various ways by which the argument in a func-
tion reference may be expressed.
(c) State the restriction placed on the argument in the func-
tion definition and on the argument in the function refer-
ence.
15. Summarize three rules that must be observed when more
than one argument is allowed in the function definition and in
the function reference.
16. (a) Describe the composition of a multiline user-defined
function.
(b) Explain when a multiline user-defined function should be
used.
(c) Explain how a value is passed from a function reference to
a statement in a multiline user-defined function.
17. State the number of values returned from a user-defined
function.
18. Determine the results of user-defined functions.
508 PROGRAMMING IN BASIC

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.

1. A main program that calls one subroutine once

10 REM THIS IS THE MAIN PROGRAM


2£'1 LET A=5
3£'1 LET B=3
40 REM CALL THE SUBROUTINE THAT ADDS
50 GOSUB 200
60 PRINT
70 PRINT "THE SUM IS:";S
80 END

200 REM THIS SUBROUTINE ADDS~---'


210 LET S=AtB
- 220 RETURN
RUN

THE SUM IS: 8

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

Some systems require GOSUB; some insist on GO SUB; others


accept an abbreviation (such as GOS.). Notice that the statement
referenced by the GOSUB is a REM statement. In some versions of
BASIC, the referenced statement must be an executable statement.
After control is transferred to the subroutine, the statements in the
subroutine are executed until a RETURN statement is reached. This
transfers control back to the main program , specifically to the state-
ment immediately after the GOSUB that referenced the subroutine. In
the above program , this is statement 60.
Execution continues in the main program until the END statement is
encountered. This statement is required at the end of a main program
to prevent execution from dropping through to the first subroutine.
Some versions of BASIC allow aSTOP statement. In this case, the last
statement in the program may have to be an END statement. Experi-
ment or check your manual to find out what your computer system
requires . The STOP and END statements are explained in greater detail
a little further on in this section.
2. A main program that calls one subroutine several
times

HI REM THIS IS THE MAIN PROGRAM


20 LET A=5
30 LET B=3
40 REM CALL THE SUBROUTINE THAT ADDS
5£1 GOSUB 200
6£1 PRINT
7£1 PRINT "THE SUM IS:";S
8~ LET A=1.5
90 LET B=13
1~£1 GOSUB 2~£1
11~ F'R I NT "THE SUM IS:";S
12£1 LET A=25
13£1 LE T B=2~~
14£1 GOSUB 20£1------------------~
15£1 PRINT "THE SUM IS:";5
16£1 END

2~£I REM THIS SUBROUTINE ADDS


2H'1 LET S=AtB
22£1 RETURN

RUN

THE SUM IS: 8


THE SUM IS: 28
THE SUM IS: 48

In this program, subroutine 200 1 is called three times - in lines 50,


100, and 140. The RETURN statement transfers control to line 60, line
110, or line 150, depending on which GOSUB statement called the
subroutine.

1. Subroutine 200 means the subroutine that starts at line 200.


510 PROGRAMMING IN BA S IC

3. A subroutine that returns more than one value

10 REM THIS I S THE MAIN PROGRAM


20 LET ~l=:: 5
30 LET B=3
40 REM CALL THE SUBROUTINE THAT
41 REM PERFORM S SEVERAL CALCULA TION S
5~ GOSUB 200----------------------~
6~ PRINT
70 PF:INT "THE SUM IS:";5
80 PRINT "THE DIFFERENCE IS:";D
9~ PRINT "THE PRODUCT IS:";P
HI0 END
20~ REM THIS SUBROUTINE PERFORM S
2~1 REM SEVERAL CALCULATIONS
210 LET S=AtB
220 LET D=A-B
230 LET P=A*B
240 RETURN
RUN
THE SUM IS: 8
THE DIFFERENCE IS: 2
THE PRODUCT IS: 15

Severa l ca lc ul ations are performed in the sub ro utine before control


is transferred back to line 60 in th e m ain pro gram.

4. A main program that calls more than one subroutine

10 REM THIS IS THE MAIN PROGRAM


20 LET A=5
30 LET B=3
40 REM CALL THE SUBROUTINE THAT ADDS
50 GOSUB 200--------------------~
60 PRINT
70 PRINT "THE SUM IS:";S
80 REM CALL THE SUBROUTINE THAT
81 REM SUBTRACTS
90 GOSUB 300 ---------------------J
1~0 PRINT "THE DIFFERENCE IS:";D
110 REM CALL THE SUBROUTINE THAT
111 REM MULTIPLIES
120 GOSUB 400--------------------~
13~ PRINT "THE PRODUCT IS : ";P
140 END
SUBPROGRAMS 511

lm REM THIS SUBROUTINE ADDS


210 LET S=AtB
220 RETURN
E

300 REM THIS SUBROUTINE SUBTRACTS


310 LET D=A-B
320 RETURN

401i'1 REM THIS SUBROUTINE MULTIPLIES


4UI LET P=A*B
420 RETURN

RUN

THE SUM IS: 8


THE DIFFERENCE IS: 2
THE PRODUCT IS: 15

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.

5. A subroutine that calls another subroutine (nested


subroutines)

10 REM THIS IS THE MAIN PROGF:AM


20 LET A=5
30 LET B=3
40 REM CALL THE SUBROUTINE THAT
41 REM CALCULATES
50 GOSUB 200

ADDs,~(--J...J
60 END

2130 REM THIS SUBROUTINE


201 REM SUBTRACTS AND MULTIPLIES
210 PRINT
220 LET R=AtB
230 GOSUB 300----------~
240 LET R=A-B
250 GOSUB 300-----------~
260 LET R=A*B
270 GOSUB 31i'11i'1------------~~
280 RETURN

300 REM THIS SUBROUTINE PRINTS~~--~


310 PRINT 'THE RESULT IS:';R
320 RETURN
512 PROGRAMMING IN BASIC

RUN
THE RESULT IS! 8
THE RESULT IS! 2
THE RESULT IS: 15

Line 50 in the main program calls subroutine 200 to perform


various calculations . After each calculation, subroutine 300 is called
to print the result. The RETURN statement in the second subroutine
transfers control back to the first subroutine to line 240, line 260, or
line 280, depending on which GOSUB called the subroutine. Thus, in
the first subroutine , calculations are performed and the PRINT subrou-
tine is called until the RETURN statement is encountered. Control is
then transferred to line 60 in the main program .

6. A subroutine with multiple RETURNs

1~ REM THIS IS THE MAIN PROGRAM


20 READ A,B
3~ DATA 5,3
40 PRINT
5~ FOR 1::1 TO 3
60 READ C
7~ DATA 1,2,3
80 REM CALL THE SUBROUTINE
81 REM THAT CALCULATES
90 GOSUB 2e0--------------------------~
100 PRINT "THE RESULT IS:";R
1 H'I NEXT I
120 END
2e0 REM THIS SUBROUTINE ADDS, SUBTRACTS
201 REM AND MULTIPLIES DEPENDING ON
2~2 REM THE VALUE OF THE CODE
210 ON C GO TO 220,240,260
22~ LET R::A+B
230 RETURN
240 LET R::A--B
250 RETURN
260 LET R::A*B
27~ RETURN

RUN

THE F:ESUL T Ie.


...,
THE RESULT IS! "-
8 . ~I

THE RESULT IS: 15

Line 60 reads in a code. A code of one denotes addition, a code of


two means subtraction, and a code of three represents multiplication .
SUBPROGRAMS 513

Line 90 calls the subroutine, wh ich performs an ar ithmeti c ope rati on


depending on the value of C (the code) After each calc ulati on,
control RETURNS to statement 100 in the main program .

7. Subroutines with one-dimensional arrays


(a) Using Two FOR/NEXT Loops

10 REM THIS IS THE MAIN PROGRAM


2~ DIM P(4)
30 FOR 1=1 TO 4
40 READ P(I)
50 DATA 4,3.1,2
60 NEXT I
70 REM CALL THE SUBROUTINE

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

(b) Using One FOR/NEXT Loop

10 REM THIS IS THE MAIN PROGRAM


21:') DIM P(4)
3111 F'R I NT
40 FOF~ 1=1 TO 4
50 READ P(I)
6£1 DATA 4,3,1,2
70 REM CALL THE SUBROUTINE
71 REM THAT PRINTS
80 GOSUB 200--------------.
9i!1 NEXT I
100 END

200 REM THIS SUBROUTINE PRINTS


210 PRINT P(IH
220 RETURN
RUN

431 2
514 PROGRAMMING IN BASIC

Both programs read and print data using a one-dimensional array


for storage . In Program (a), the statement that calls the subroutine is
outside the FOR/ NEXT loop in the main program. This means that the
data items are printed after all have been read into the array. The
subroutine requires its own FOR/NEXT loop to print the data. In Pro-
gram (b), the statement that calls the subroutine is inside the
FOR/ NEXT loop. This time each item of data is printed immediately after
it is read and the subroutine no longer requires a FOR/NEXT loop .
8. Subroutines with two-dimensional arrays
(a) Using Two Sets of Nested FOR/NEXT Loops

10 REM THIS IS THE MAIN PROGRAM


20 DIM R(3,4)
3~ FOR 1=1 TO 3
4~ FOR J=l TO 4
5~ READ R(I,J)
6~ DATA 3,2,~,1
70 DATA 1,0,2,3
8~ DATA 2,4,1,0
90 NEXT J
10~ NEXT I
11~ REM CALL THE SUBROUTINE
111 REM THAT PRINTS
120 GOSUB 200--------------------~
130 END

200 REM THIS SUBROUTINE PRINTS


210 PRINT
220 FOR K=l TO 3
230 FOR L=l TO 4
240 PRINT R(K,L);
25~ NEXT L
260 PRINT
270 NEXT K
280 RETURN

RUN
3 2 ~ 1
1 023
2 4 1 0

(b) Using One Set of Nested FOR/NEXT Loops

10 REM THIS IS THE MAIN PROGRAM


20 DIM R(3,4)
30 PRINT
40 FOR 1=1 TO 3
SUBPROGRAMS 515

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

200 REM THIS SUBROUTINE PRINTS


2H1 PRINT R(I,J);
220 RETURN

RUN

3 2 0 1
1 0 2 3
2 4 1 0

Both programs read and print data using a two-dimensional array


for storage. In Program (a), the statement that calls the subroutine is
outside the set of nested FOR/NE XT loops in the main program. This
means that the data items are printed after all have been read into the
array. The subroutine requires its own set of nested FOR/NE XT loops to
print the data. In Program (b), the statement that calls the subroutine
is inside the set of nested FOR/NEXT loops. This time each item of data
is printed immediately after it is read and the subroutine no longer
requires FOR/NE XT loops.
Some of the statements that have been introduced in this section
will now be explained in greater detail.
Depending on the computer system being used, either an END The STOP and END statements
statement or a STOP statement must be placed at the end of the main
program, otherwise execution continues into the first subroutine. If
the system requires an END statement, another such statement is
probably not needed at the end of the program. The'STOP statement is
treated differently among computer systems. Some consider it as a
GO TO statement that causes control to branch to the END statement.
Others execute the program but print the message BREAK AT xx or
something similar (xx represents the number of the STOP statement) .
Still others stop execution entirely and print the break message. On
some systems, execution of the program may be resumed by typing
CONT or CONTINUE. If the STOP statement is accepted, any number
of STOP statements may be used, however, a STOP may not be placed
at the end of a program. Also, several END statements may be allowed
in a program, but execution ENDS when the statement is encountered .
When using either a STOP or an END , care should be taken to branch
around the statement when a particular routine is to be continued.
516 PROGRAMMING IN BASI C

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 .

le0 REM THIS IS THE FIRST SUBROUTINE

140 GOSUB 20~--------------------------~

18~ RETURN

2~~ REM THIS IS THE SECOND SUBROUTINE

250 GOSUB 100


290 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.

10 REM THIS IS THE MAIN PROGRAM


20 PRINT

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

3111 FOR 1=1 TO 3


40 READ C
5111 DATA 1,2,3
60 REM CALL ONE OF THE SUBROUTINES
61 REM DEPENDING ON THE VALUE OF C
70 ON C GOSUB 100,2~0,300
80 NEXT I
90 END

100 REM THIS IS THE FIRST SUBROUTINE


110 PRINT 'SUBROUTINE 1"
120 RETURN

200 REM THIS IS THE SECOND SUBROUTINE


210 PRINT 'SUBROUTINE 2"
220 RETURN

300 REM THIS IS THE THIRD SUBROUTINE


310 PRINT 'SUBROUTINE 3'
320 RETURN

RUN

SUBROUTINE 1
SUBROUTINE 2
SUBROUTINE 3

The ON ... GOSUB in line 70 transfers control to one of the subrou-


tines, depending on the value of C. If the va.lue of C is 1, control is
transferred to subroutine 100. If the value of C is 2, control is
transferred to subroutine 200. And if the value of C is 3, control is
transferred to subroutine 300. The RETURN statement in each of the
three subroutines transfers control back to line 80, which is the
statement immediately following the ON ... GOSUB.
As with the ON ... GO TO statement, the value of the index cannot be
less than 1 (negative or zero), nor can it be greater than the number of
statement numbers in the list. Depending on your computer system,
one of the following may occur:
(a) Execution stops and the computer gives an error message.
(b) The ON ... GOSUB statement is ignored and the statement fol-
lowing the ON ... GOSUB is executed.
(c) Control is transferred to the last statement number in the list
when the value of the index exceeds the number of statement
numbers.
(d) Control is transferred to the first statement number in the list
when the value of the index is less than one.

11.1 SUBROUTINES-Sample Programs


1. Here is a problem that appeared in Chapter Five on page 156.
The program shown on page 518 reviews the method by which a
518 PROGRAMMING IN BASIC

loop can be terminated by using a special value and a counter. It


also incorporates some of the concepts most recently covered,
such as the INT function , the TAB function, and the subroutines.
A storage room in a stationery store contains the following
items.
9 pen and pencil sets @ $23 .85 each
8.5 boxes bond paper @ 19.49 each
85 bo xes carbon paper @ 15.67 each

The program finds the extended value of each of the above


articles.
(a) Use the READ statement to store the number of different
articles (3) in a simple variable. The variable is used subse-
quently with a counter to terminate the loop .
(b) Use the READ/DATA statements to enter the quantity and the
unit price of each article.
(c) Use the INT function to round off the extended value of each
article to the nearest cent.
(d) Use the TAB function to fo rmat the output.
(e) Use one subroutine to calculate the extended value of each
article.
(f) Use a second subroutine (called by the first subroutine) to
print the information as shown.
(g) Extended Value = Quantity x Unit Price

~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

1~ REM THIS IS THE MAIN PROGRAM


2~ PRINT - Leaves a blank line .
30 PRINT TAB(2);'QUANTITY';TAB(15);'UNIT - Prints the heading .
PRICE' nAB(31); 'VALUE'
40 PRINT - Leaves a blank line.
50 LET D=2 - Two decimal places.
6~ LET K=l -Initializes the counter to 1.
7~ READ N - Reads the number of articles .
80 DATA 3 - Supplies the number of articles.

90 READ Q,P - Reads the quantity and price


of each article.
- Supplies the quantity and price
of each article .
110 GOSUB 200------------------~~----~ - Calls the subroutine that
calculates the extended
value of each article.
SUBPROGRA MS 519

p120 LET K=Kt1 -Increments the counter by 1.


130 IF K}N THEN 150 - Tests the current value of the
counter.
(i) If K is greater than N (the
number of articles), control is
transferred to the END state-
ment.
(ii) If K is not greater than N, the
computer proceeds to the
next statement.
140 GO TO 90 - Transfers control back to line 90
to continue reading.
150 END - Terminates program execution .

200 REM THIS SUBROUTINE CALCULATES THE~


201 REM EXTENDED VALUE OF EACH ARTICLE
210 LET V=INT(Q*P*10TDt.5)/10TD - Calculates the extended value
of each article to the nearest
cent.
220 GOSUB 300-----------------------. - Calls the subroutine that prints
the data and the extended
values.
230 RETURN - Transfers control to line 120.

300 REM THIS SUBROUTINE PRINTS THE~


301 REM DATA AND THE VALUES
310 PRINT TAB(4) ;QnAB(16) j "$" nAB(17) jp - Prints the quantity, unit price,
;TAB(30);I$";TAB(31);V and extended value of each arti-
cle .
'---320 RETURN - Transfers control to line 230.

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

2. Subroutines are often used to draw pictures or letters of the


alphabet when several of the lines are the same. Here is a
program that prints the letter B . The left-most symbols are
printed in print position one when using the TAB function.
(a) Using the TAB Function

10 REM SET UP A LOOP FOR


11 REM EACH HALF OF THE "B"
21!1 LET M=6 -M represents the number of symbols in a
row. It is also used to position a symbol.
30 PRINT
40 FOR K=l TO 2
S0 GOSUB 2~"~
GOSUB 30111
-------11- -
.i
Calls subroutine 200 to print a row of symbols .
- Calls subroutine 300 to print the left-most
and right-most symbols of a row.
520 PROGRAMMING IN BASIC

./~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

300 REM PRINT LEFTMOST AND~/---""


301 REM RIGHTMOST SYMBOLS (2 LINES)
310 FOR J=l TO 2 -Setsupaloopfor2rows.
320 PRINT TAB(l);"B";rAB(M+l);IB" -Printstheleft-mostBandtheright-
330 NEXT J most B of a row .
~340 RETURN
RUN
[lBBBBB
B [I
B It
BBBBBB
B B
B P
BBBBBB

(b) Using the PRINT USING and IMAGE Statements

10 REM SET UP A LOOP FOR


11 REM EACH HALF OF THE "B"
20 PRINT
30 FOR K=l TO 2
40 GOSUB 200-----------------~~ - Calls subroutine 200 to print a row of
symbols.
- 50 GO SUIt 300 _ _ _ _ _ _ _----Jf~ - Calls subroutine 300 to print the left-
most and right-most symbols of a row.
60 NEXT K
70 GOSUB 200-------------------~) - Calls subroutine 200 to print the last
row of symbols .
~80 END
200 REM PRINT A ROW OF SYMBOLS~
210 PRINT USING 22~ - Prints a row of B's using IMAG E state-
ment 220.
SUBPROGRAMS 521

~
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

11 ,1 SUBROUTINES- Your Turn


1. Write a subroutine for the following ma in program to calculate the
amount of cash a grocer has at the end of a day if he received
$431 and paid out $16.50.
Balance = Receipts - Payments

01 REM R--RECEIPTS
02 REM P--F'AYMENTS
03 REM B--BALANCE

10 REM THIS IS THE MAIN PROGRAM


20 f.:EAD R,P
30 DATA 431,16.50
40 GOSUB 2~H~
50 PRINT
60 PRINT "RECEIPTS!" ;R
70 PRINT "PAYMENTS:";P
B0 PRINT "BALANCE: • ; B
90 END

RUN

RECEIPTS: 431
522 PRO GR AMM ING IN BAS IC

PAYMENTS: 16.5
BALANCE: ·4 14.5

2. Modify the program in Problem 1 so th at there are two subrou-


tines ; the first one is called by the main program, the second one
is called by the first subroutine .

(a) The first subroutine calculates the balance .


(b) The second subroutine formats the headings and amounts
as shown in the o utput below. Use the TAB function.

01 REM R--RECEIPTS
02 REM P--PAYMENTS
~3 REM B--BALANCE

10 REM THIS IS THE MAIN PROGRAM


20 READ R,P
30 DATA 431,16.50
40 GOSUB 2""""
50 END
-
0 !3 16 29
IRE CE IF' TS PA YM EN TS BA LA NCE
$ 4131 $ 16 . 5 $ 41 4.5

3. Rewrite the sample program on page 518 but with the following
changes.

(a) Use a FOR/NEXT loop to control input rather than a counter


tested against the n umber of data items read in.
(b) Have the main program call both subroutines .
(c) In the flowchart , the process symbol is used to indicate the
GOSUB statement. The oval denotes th e RETURN statement
since this symbol represents a term inal point.

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

0=2 Return Return

GOSUB
200

GOSUB
300

NEXT I
524 PROGRAMM IN G IN BAS IC

11,1 SUBROUTINES-Solutions for "Your


Turn"
1,

2~~ REM THIS SUBROUTINE CALCULATES


201 REM THE BALANCE
210 LET B=R-P
220 RETURN

2,

2~0 REM THIS SUBROUTINE CALCULATES


2e1 REM THE BALANCE
2H1 LET B=R--F'
220 GOSUB :50~
230 RETURN
3~e REM THIS SUBROUTINE PRINTS
3U3 PRINT
3 2 0 P RI NT TAB ( 3 ) ; • RECE I P TS" ; TAB ( 1 6 ) ; " F' AY
MENTS";TAB(29);"BALANCE"
33e PRINT
340 PRINT TAB(4);"$";TAB(S);R;TAB(17);"S
";TAB(lB);P;TAB(29);"$";TAB(30);B
350 RETURN

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

11.2 USER-DEFINED FUNCTIONS


It was mentioned at the beginning of this chapter that standard or
built-in functions are a particular type of subprogram. These routines
are written by someone else and may be called upon to perform
specific operations. BASIC gives you the opportunity to write your own
functions (mathematical expressions). Referred to as user-defined
functions, they are incorporated in a program when the same calcula-
tions must be performed several times. Different values may be used
for each calculation . Here is a program that calls a user-defined
function to convert miles to kilometres .

1211 REM M1--DUMMY VARIABLE


1212 REM M--MILES
1213 REM K--KILOMETRES

1121 DEF FNM(Ml)=Ml*1.6e9


2121 LET M=5
3e LET K=FNM(M)
4121 PRINT
5e PRINT M;"MILES =";K;"KILOMETRES"
99 END
RUN

5 MILES = 8.045 KILOMETRES

Line 10 contains a user-defined function. Notice that the function


must be named and defined in a DEF statement. If there is more than
one user-defined function in the program, each one must be
described in its own DEF statement. The position of this statement in
the program depends on the computer system being used. On some
systems the function must be defined before it is called ; on others the
DEF statement may be placed anywhere in the program . Usually, all
DEF statements are placed together at the beginning of a program.
526 PROGRAMMING IN BASIC

The general form of a DEF statement is as follows .


10 DEF FNM (M1) M1*1.609
i i i i i i
Statement Key word Name of Dummyargument Equals Function written
number meaning the which takes on Sign by the user
"defined" function the actual value
when the function
is referenced
The statement begins with a line number followed by the key word
DEF, which is an abbreviation for "defined." This is followed by the
function definition which consists of the name of the function, its
argument (in parentheses) , an equals sign , and a mathematical
expression. The function name requires three letters of the alphabet.
The first two letters must be FN; the third is supplied by the user and
may be any letter of the alphabet. This means that there may be as
many as twenty-six different user-defined functions in one program.
Examples of function names are: FNA, FNR, FNZ . Usually, the user
supplies a letter that is appropriate for the function . In the name FNM
shown above, the letter M was chosen because the function converts
miles to kilometres.
The variable immediately after the function name is called the
function's argument. It must be enclosed in parentheses and must be
a simple variable; it may not be a subscripted variable. Usually , but
not always, it appears In the mathematical expression on the right-
hand side of the eq uals sign . Some versions of BASIC allow several
arguments within the parentheses. These arguments must be sepa-
rated by commas. An example is shown below.

A function name may also be coded without an argument on some


computer systems.
The argument in the function definition is referred to as the dummy
argument, since it plays no significant role, other than to act as a
place-holder for the value that will be operated on when the function
is called. The mathematical expression on the right-hand side of the
equals sign is the function that has been constructed by the user.

10 DEF FNM(M1}=M1*1.609
i ~
Dummy Constructed
argument by
the user

Besides the dummy variable , the function may contain constants ,


library functions , other previously defined functions , and simple or
subscripted numeric variables. Most versions of BASIC do not permit
self-referencing of user-defined functions .
SU BPRO G RAM S 527

10 DEF FNS(A 1)= A 1 *FNS(A 1 +2)


i
May not be allowed
The values of the variables in the function are the ones most recently
assigned. In the conversion program shown below , the value for Cis
1.609 .

1~ DEF FNM(M1)=M1*C
15 LET C=1.609
2£1 LET M=5
3~ LET K=FNM(M)

FNM(M) in line 30 is called the function reference, since it makes a


reference to a function definition . It consists of the name of the
function and its argument in parentheses . It is similar to a library
function that calls a routine already written . The function reference is
usually coded in a LET statement or in a PRINT statement to call a user-
defined function. The value of its argument is passed to the dummy
argument in the function definition. On most computer systems, the
function reference may appear within an algebraic express ion, in
another user-defined function, in another function reference and, on
some systems, nested in its own function reference. This last method
of coding a function reference is discussed in further detail on page
529.
While the argument of a function definit ion must be a simple
variable, the argument of a function reference may be a constant, a
simple variable, a subscripted variab le, an express ion , or a library
function As already mentioned , some computers may allow the
argument to be a function reference. Remember , it is the value of the
argument that is passed to the function definition. Shown below are
some examples of function references.

1~ DEF FNR (A 1) =A 1 +FNM (M) -In another user-defined function, argument is a


simple variable . .
2~ IFF NM ( 6 ) +2> 1 ~ THEN 160 -In an arithmetic expression, argument isa constant.

3£1 LET K=FNM(M(I» -In a LET statement, argument is a subscripted variable.

4~ PRINT FNM(4+A/2) -In a PRINT statement, argument is an expression.

5~ PRINT FNM(SGR(M» -In a PRINT statement, argument is a library function .

6~ LET K=FNR(FNM(M» -In another function reference, arguments are a


function reference and a simple variable.

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

Function definition Function reference


~ -.v
I
( i r t
1~ DEF FNM(Ml)=Ml*1.609 30 LET K=FNM(M)
i Actual
I
Dummy
argument argument

The logic of the program that converts miles to kilometres will now
be traced. Here is the program once more .

01 REM Ml--DUMMY VARIABLE


02 REM M--MILES
03 REM K--KILOMETRES

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

5 MILES = 8.045 KILOMETRES

1. The computer obtains a value for the actual argument.

20 LET M=5~
30 LET K=FNM(M)

The value of the actual argument (M) is 5.


2. The computer looks for the function named FNM and passes the
value of M from the actual argument to the dumm y argument.

10 liEF FNM(Ml)=Ml*I.6a9

30 LET K=FNM(M)
\.

The dummy argument (M1) is rep laced by 5.


3. The computer passes the 5 from the argument on the left-hand
side of the equals sign to the variable on the right-hand side of
the equals sign.
SUBPROGRAMS 529

10 DEF
11
FNM(Ml)=Ml*1.6~9

The value of M1 in the equation is 5.


4 . The computer evaluates the equation (function) . The function
name serves as a temporary storage location for the result 8 .045 ,
which cannot be accessed until it is assigned to the variable K .
Other methods of calling the user-defined function and obtaining
the result are listed on page 527.

Passes the result 8.045 to K .


10 DEF
+ I
FNM(Ml)=Ml*1.6~9
I

\
30 LET K=FNM(M)
U

5. The computer prints the values of M and K.

50 PRINT M;"MILES =";K;"KILOMETRES"

As mentioned on page 527, some versions of BAS IC allow nested


function references. Here is an example .

10 DEF FNC(Nl)=Nlt2
20 LET N=3
30 LET C=FNC(FNC(N»
40 PRINT
50 PRINT C
99 END

RUN

The inner function reference passes 3 to the dummy argument in the


function definition and 5 is returned as the argument of the outer
function reference. The outer function reference then passes 5 to the
dummy argument and the result of the calculation (7) is returned and
assigned to C.
On the following page are a number of statements that call a user-
defined function. In each problem, the value for K will be found using
the function definition and the value for M given before the state-
ments.
r
530 PR OG RAMMIN G IN BASIC

10 DEF FNM(M1)=M1*1.609
20 LET M=lB

(a) 30 LET K=FNM (M)


=FNM(10)
FNM(M1) =M1*1.609
FNM(10) = 10*1.609
= 16.09

30 LET K=FNH(M)
= 16.09

(b) 30 LET K=FNH(Mt1)


=FNM(10+1)
=FNM(11)

FNM(M1) =M1*1.609
FNM(11) =11*1 .609
= 17.699

30 LET K=FNM(Mtl)
= 17.699

(c) 30 LET K=FNM(H)t1


= FNM(1 0)+ 1

FNM(M1) = M1 *1.609
FNM( 10) = 10*1.609
= 16.09

30 LE T K=FNH(H)t1
= 16.09+1
= 17.09

(d) 30 LET K=FNH (M) +SQR (64)·-.09


= FNM(1 0)+ SOR(64)- .09

FNM(M1) =M1*1 .609


FNM(10) = 10*1.609
= 16.09

30 LET K=FNM(M)+SQR(64)-.09
= 16.09+ SOR(64)- .09
= 16.09+ 8- .09
= 24 .09- .09
=24

(e) 30 PRINT 'K =' ;SQR(FNM( M >+84-.~9)


SOR(FNM(1 0)+84- .09)

FNM(M1) = M1 *1 .609
FNM(10) = 10*1.609
= 16.09
- ;-

SUBPROGR AMS 531

30 PRINT OK =";SGR(FNM(M)+84-.09)
SOR(16.09+ 84- .09)
SOR(1 00 .09- .09)
SOR(100)
10
Output: K = 10

The following user-defined function rounds off the result in Problem


(b ) on page 530 to two decimal places .

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')

FNM(M1) = INT(M1 *1.609*1 OjD+.5)/ 1OjD


FNM(11) = INT(11 *1 .609*1 Oj2+ .5) /1Oj2
= INT(11 *1.609*100+ .5) /1Oj2
= INT(17.699*100+ .5) /10j2
= INT(1769.9+ .5) / 1Oj2
== INT(1770.4)/ 1Oj2
= 1770/1Oj2
= 1770/ 100
= 17.70

40 LET K=FNH(M+1)
= 17.70

There are several rules that must be observed concerning the


relationship between the function definition and the function refer-
ence .
1. The name of the funct ion in the function definition and the name
in the function reference must be the same . This lets the com-
puter know which user-defined functio n is being called . In the
conversion program , the name of the funct ion is FNM . It appears
in statement 10 (in the function definition) and in statement 30 (in
the function reference) .

10 DEF FNH(M1)=Ml*1.609
'\
30 LET K=FNM(M)

2. The actual argument must correspond in type to the dummy


argument (either numeric or str ing) . It is not necessary that the
argument names be the same .
532 PROGRAMMING IN BASIC

10 DEF FNM(Ml)=Ml*I.6a9

30 LET K=FNM(M)
'\ - Both represent a
numeric value.

3. Some versions of BASI C allow several dummy arguments in the


function definition and several actual arguments in the function
reference. In this situation, the dummy arguments must corre-
spond to the actual arguments in number, order, and type.

10 DEF FNQ(A,B,C)= •••••• - Same number.


\\\
50 LET O=FNO(X,Y,Z)
- Same order.
- Same type.

Here is another example

10 DEF

50 LET

The arguments in the function definition are simple numeric


variables. The arguments in the function reference are a numeric
expression, a subscripted variable, and a library function.
Although expressed differently, they correspond to those in the
function definition in number , order , and type . The value of
4*X-V is passed to A; the value ofZ(I) is passed to B; and the
val ue of SQR(W) is passed to C.
4. When a function definition and a function reference have one
argument each, Just one value is passed from the actual argu-
ment to the dummy argument. Computer systems that allow
several arguments are able to pass more than one value from the
function reference to the function definition. In the program
segment

10 DEF FNO(A,B,C)= ••••••


'\'\'\
50 LET O=FNO(X,Y,Z)

three values are passed to the function definition. The three


dummy ar~Jments, A, B , and C, are replaced by the values of X,
V, and Z. However, in every program, only one numeric value
results from the evaluation of a user-defined function and, there-
fore, only one value is returned to the calling statement. In the
above program segment, the returned value is assigned to the
variable Q.
SUBPROGRAMS 533

As already mentioned, each user-defined function must have its


own DEF statement with a function name that is unique (different from
the other user-defined functions),
Some versions of BASIC allow multiline user-defined functions 3 Multiline user-defined function
These define complex functions that often require branching and
looping. The function must be preceded by a DEF statement which
consists of a line number, the key word DEF followed by the name of
the function, and its argument in parentheses As in single-line
functions, some computer systems allow more than one dummy
argument in the function's argument list. Just one value is returned to
the calling statement after the function is evaluated, Unlike single-line
functions, the DEF statement must not include an arithmetic equation,
To define the function, several statements must follow the DEF state-
ment. The result of the multiline function is returned to the calling
statement by assigning the value to the name of the function in one of
its statements, The entire definition ends with the statement
FNEND.4
The rules observed for single-line functions must also be observed
for multiline functions, However, there are several additional restric-
tions, Control may not be transferred to a statement within the
function from a point outside orfrom a statement within the function to
a point outside, Also, some versions of BASIC do not allow INPUT
statements or PRINT statements inside the user-defined function,
Here is an example of a program that uses a multiline user-defined
function,

H'J DEF FNB(Al>


2e IF Al<=l~ THEN 5~
30 LET FNB=Al-2
48 GO TO 6~
S0 LET FNB=Al+2
68 FNEND
78 LET A=4
88 LET B=FNB(A)
90 PRINT
lla0 PRINT A;B
999 END

RUN

4 6

The function FNB adds 2 to a number if the number is less than or


equal to 10; otherwise, it subtracts 2 from the number, that is, if the
number is greater than 10,
Line 10- The DEF statement is comprised of a statement number,
the key word DEF, followed by the name of the function and its

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

argument in parentheses. Some computer systems allow more than


one argument, in which case the arguments must correspond to
those in the function reference The argument A1 acts as a place-
holder for the value of the actual argument A. When the function
reference calls the user-defined function, the dummy argument is
replaced by the value of the actual argument. This value (4) is passed
to the dummy variable that may appear in one or more of the state-
ments in the user-defined function .
Line 20 - Checks the number that has been passed to the user-
defined function.
(i) If the number is less than or equal to 10, control is transferred to
line 50 .
(i i) If the number is greater than 10, the computer proceeds to the
next line .
Line 30- Subtracts 2 from the number if the number is greater than
10, and assigns the result to the fun ction name FNB .
Line 40 - Transfers control to line 60, which is the end statement of
the user-defined function.
Line 50 - Adds 2 to the num ber if the n um ber is less than or eq ual to
10, and assigns the result to the function name FNB .
Line 60- Marks the end of the user-defined function .
Line 70 - Assigns 4 to the variable A.
Line 80 - Contains the function reference that calls the user-defined
function FNB . It passes the value of A to the dummy argument in the
function definition The result (only one value) is returned to the
calling statement and assigned to B.
Line 100- Prints the value of A (the data) and the va lue of B (the
res u It)
Line 999- Termin ates program execution.

11.2 USER-DEFINED FUNCTIONS- Sample


Program
Suppose that the price of an article has been reduced from $15 for
one article to $22.95 for two, and that you would like to know the cost
of three articles, the cost of five articles, and the cost of seven articles.
Here is a program that performs these calculations using a user-
defined function .
(a) Use the READ/DATA statements to enter the price .
(b) Use a FOR/NEXT loop to control the number of times the function is
evaluated. Use the value of the index as the number of articles .
(c) Cost of the articles = pr~ce x Number of Articles (the index)

01 REM PI--DUMMY VARIABLE


02 REM P--ACTUAL PRICE
03 REM N--NUMBER OF ARTICLES (INDEX)
04 REM C--COST OF THE ARTICLES
10 DEF FNC(Pl)=PI/2*N - Defines the function .
20 READ P - Reads in the price.
30 DATA 22.95 - Supplies the READ statement with the price.
SUBPROGRAMS 535

40 PRINT - Leaves a blank line.


50 FOR N=3 TO 7 STEP 2 - Sets up a loop.
60 LET C=FNC(P) - Calls the user-defined function and
passes the price to the dummy
argument Pl. After the function is
evaluated, the result is assigned
to C.
70 PRINT "COST OF";N;"ARTICLES IS:";C - Prints the cost of a specific
number of articles.
80 NEXT N - Transfers control to line 50 .
99 END - Terminates program execution.

RUN

COST OF 3 ARTICLES IS: 34.425


COST OF 5 ARTICLES IS: 57.375
COST OF 7 ARTICLES IS: 8~L 325

11.2 USER-DEFINED FUNCTIONS- Your Turn


In the first four problems perform all calculations by hand .
1. Find the value of B in each of the following program segments.
The function in the function definition is the one that rounds off
dollars and cents to the nearest cent.

10 DEF FNR(Al)~INT(Al*1~TDt.5)/10TD
20 L.ET [1=2

(a) 30 LET A=13.485


40 LET B=FNR(A)
(b) 30 LET A=14.163
40 LET B=FNR(A)*2
(c) 30 LET A=14.163
4111 LET B=FNR(A*2)
(d) 3111 LET A=16.398
40 LET B=SGR(FNR(A)t32.60)

2. In the program shown below, find the net wages of an employee


who has no overtime hours . The first user-defined function in the
program gives the value of W (wages not rounded) . The second
user-defined function rounds off the wages to the nearest cent.
This gives the value of N .

01 REM Hl--DUMHY VARIABLE


02 REM H--HOURS WORKED
536 PROG RAMMING IN BAS IC

~3 REM R--RATE PER HOUR


~4 REM D--DEDUCTIDNS
05 REM D2--NUMBER OF DECIMAL PLACES
06 REM W--NET WAGES (NOT ROUNDED)
07 REM N--NET WAGES (ROUNDED)

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

3 . Suppose an employee's regular weekly hours are 39 hours and


that the company offers time-and-a-half for overtime. The follow-
ing function finds the employee's net wages , including overtime.
R*39+(H-39)*R*1.5-D
R denotes Rate per hour, H stands for Hours worked, and D
means Deductions .
(a) R * 39-rate times regular hours gives regular pay.
(b) H - 39 - hours worked minus regular hours gives overtime
hours .
(c) R * 1.5 - rate times 1.5 gives overtime rate.
(d) (H -39) * R*1.5 - overtime hours times overtime rate gives
overtime pay .
(e) R*39 + (H -39)*R*1.5 - regular pay plus overtime pay
gives gross wages.
(f) R*39+(H-39)*R*1.5 - D-gross wages minus deduc-
tions gives net wages .
The following program uses the above formula as a user-defined
function to find the wages of an employee who has worked
overtime. The wages are then rounded off to the nearest cent by
the second user-defined function. Find the value of N.

01 REM Hl--DUMMY VARIABLE


02 REM H--HOURS WORKED
03 REM R--RATE PER HOUR
04 REM D--DEDUCTIONS
05 REM D2--NUMBER OF DECIMAL PLACES
06 REM W--NET WAGES (NOT HOUNDED)
07 REM N--NET WAGES (ROUNDED)
10 DEF FNV(Hl)=R*39t(Hl-39)*R*1.5-D
20 DEF FNR(Wl)=INT(Wl*10TD2t.5)/10TD2
30 LET D2=2
40 READ H,R,D
50 DATA 44,10.241,85
60 LET W=FNV(H)
SUBPROGRAMS 537

7~ LET N=FNR(W)
8~ PRINT N
99 END

4. Find the va lue of Q in each of the statements shown below using


the following function definition and the va lues given for A , B,
and C 5

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)

(b) 4~ LET Q=FNQ(A,B,C)t10

(c) 4~ LET Q=FNQ(A,B+l,C)

(d) 4£1 LET Q=SQR(FNQ(A,Btl,C»

5 . Fill in the missing lines for the following programs .


(a) Calculate the sales tax of an article.
(i) Sales Tax = Price x Rate
(ii) Complete line 10 with a DEF statement.

~1 REM Pl--DUMMY VARIABLE


~2 REM P--PRICE
£13 REM R--RATE
04 REM T- - TAX
it'!
20 READ P,R
3 I?) DATA 37,.05
40 LET T=FNT(F')
50 PRINT
6~ PRINT P,T
99 END

RUN

37 1.85

(b) Calculate the amount of an investment by adding the yearly


interest to the investment. Use $1000 as the initial in vest-
ment for each of the rates 17%, 18%, and 19%.
(i) Amount = Investment + (Investment x Rate)
(ii) Complete line 60 with a function reference coded in a LET
statement.

5. You may omit Problem 4 if your computer does not allow several variables in the
argument list.
538 PROGRAMM ING IN BAS IC

01 REM Rl--DUMMY VARIABLE


02 REM R--RATE
~3 REM I--INITIAL INVESTMENT
~4 REM A--AMOUNT

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.

01 REM N1--DUMMY VARIABLE


02 REM N--NUMBER
03 REM S--NUMBER SQUARED

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

(d) The following program uses a multi line user-defined func-


tion. 6 It cubes a number if the number is less than or equal to
5, otherwise it squares the number ; that is, if the number is
greater than 5.
(i) Complete line 30 with a statement that squares the
number.
(ii) Complete line 50 with a statement that cubes the num-
ber .

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

6. Rewrite the sample program on page 534 . This time, code a


user-defined function that not only calculates the cost of each
article but also rounds off the result to the nearest cent. Here is
the problem once more .
Su ppose that the price of an article has been reduced from $15
for one article to $22 .95 for two and that you would like to know
th e cost of three articles , the cost of five articles , and the cost of
seven articles .
(a) Use the READIDATA statements to enter the price .
(b) Use a FOR/NEXT loop to control the number of times the
function is evaluated. Use the value of the index as the
number of articles .
(c) Cost of the articles = pr~ce x Number of Articl es (the index)
(d) In the flowchart , the DEF statement and the LET statement that
calls the user-defined function are represented by process
symbols .

RUN

COST OF 3 ARTICLES IS: 34.43


COST OF 5 ARTICLES IS: 57.38
COST OF 7 ARTICLES IS: 80.33

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

11.2 USER-DEFINED FUNCTIONS - Solutions


for "Your Turn"?
1.

(a) 40 LET B=FNR (A)


= FNR(13.485)
FNR(A 1)= INT(A 1 *1 OJ D+ .5)/ 1OJ D
FN R( 13.485)= INT( 13.485* 1OJ 2+ .5)/1 Oj2
= INT(1348.5+ .5) / 1Oj2
= INT(1349.0)/1 Oj2
= 1349/ 100
= 13.49
40 LET B=FNR(A)
= 13.49

7. Some of th e simpler steps in th e solutions have bee n omitted.


SUB PROGRAMS 541

(b) 40 LET B=FNR (A) *2


= FNR(14 .163)*2
FNR(A1)= INT(A1 *10jD+ .5) / 10jD
FNR(14.163) = INT(14 .163*1 Oj2+ .5) /1Oj2
= INT(1416.3+.5)/ 10j2
= INT(1416 .8)/ 10j2
= 1416/100
= 14.16
40 LET B=FNR(A)*2
=14 .16*2
=28.32

(c) 40 LET B=FNR (A*2)


= FNR(14 .163*2)
= FNR(28 .326)
FNR(A 1)= INT(A 1 *1 OJ D+ .5)/1OJ D
FNR(28.326)= INT(28.326*1 Oj2+ .5) /1Oj2
= INT(2832.6+ .5) /1Oj2
= INT(2833 .1 )/1 Oj2
= 2833/100
=28.33
40 LET B=FNR(A*2)
=28.33

(d) 40 LET B==SQR (FNR (A) t32. 6~)


= SOR(FNR(16 .398)+32 .60)
FNR(A 1) = INT(A 1 *1 OJ D+ .5)/ 1OJ D
FNR(16.398)= INT(16.398*1 Oj2+ .5) /1Oj2
= INT(1639.8+ .5) /1Oj2
= INT(1640.3)/ 1Oj2
=1640/100
= 16.40
40 LET B=SQR(FNR(A)t32.60)
= SOR(16.40+32.60)
=SOR(49)
=7

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

621 LET W=FNN(H)


=347 .591
542 PROGR AMMI NG IN BASI C

7~ LET N=FNR(W)
= FNR(347.591)

FNR(W1)= INT(W1 *1 Oj02+ .5)/1 Oj02


FN R(347.591)= INT(347 .591 *1 OJ 2+ .5)/1 Oj2
= INT(34759.1+ .5)/1 Oj2
= INT(34759.6)/ 1Oj2
= 34759/100
=347.59

7'~ LET N=FNH(W)


=347.59

3.

6~ LET W=FNV(H)
= FNV(44)

FNV(H1)= R*39+ (H1- 39)*R*1 .5- 0


FNV( 44) = 10.241 *39+ (44- 39)*10.241 *1 .5- 85
= 10.241 *39+ 5*10.241 *1.5- 85
= 399.399+ 5*10.241 *1 .5- 85
= 399.399+51.205*1.5- 85
= 399.399+ 76 .8075- 85
= 476.2065- 85
= 391 .2065

6~ LET W=FNV(H)
= 391.2065

7~ LET N=FNR(W)
= FNR(391 .2065)

FN IR (W1)= INT(W1 *1 Oj02+ .5)/1 OJ 02


FNR(391.2065)= INT(391.2065*1 Oj2+ .5) /1Oj2
= INT(39120.65+ .5)/ 1Oj2
= INT(39121 .15)/ 1Oj2
=39121 / 100
= 391 .21

7~ LET N=FNR(W)
= 391.21

4.

(a) 4~ LET Q=FNQ(A,Et,C)


= FNQ(2,6,3)
SUBPROGRAMS 543

FNO(A 1,81 ,C1)= 81 j2- 4*A 1 *C1


FNO(2 ,6,3)= 6j2- 4*2*3
= 36- 4*2*3
=36- 8*3
=36-24
=12
40 LET G=FNG(A,B,C)
=12

(b) 40 LET G=FNG(A,B,C>t10


= FNO(2,6,3)+ 10
FNO(A1 ,81 ,C1)= 81j2-4 *A1 *C1
FNO(2,6,3)= 6j2- 4*2*3
= 36- 4*2*3
= 36- 8*3
=36-24
=12
40 LET G=FNQ(A,B,C)t10
=12+10
=22

(c) 40 LET (~=FNQ(A,B+l,C)


= FNO(2,6+ 1,3)
= FNO(2,7 ,3)
FNO(A 1,81 ,C1)= 81 j2- 4*A 1*C1
FNO(2 ,7,3) = 7j2- 4 *2 *3
= 49-4*2*3
=49-8*3
=49-24
=25
40 LET G=FNQ(A,B+l,C)
=25

(d) 40 LET G=SQR(FNQ(A,B+l,C»


= SOR(FNO(2,6+ 1,3))
= SOR(FNO(2,7,3))
FNO(A 1,81 ,C1)= 81 j2- 4*A1 *C1
FNO(2 ,7,3)= 7j2- 4*2*3
= 49-- 4 *2*3
= 49- 8*3
=49 - 24
=25
40 LET Q=SQR(FNG(A,B+l,C»
= SOR(25)
=5

5.

(a) 10 DEF FNT(F'1)=F'lU,

(b) 60 LET A=FNA (R)


544 PROGRAMMING IN BASIC

(c) 10 DEF FNS(N1)=N1i2


40 LET S=FNS(N)
(d) 30 LET FNB=A1i2
58 LET FNB=A1i3

6.

81 REM P1--DUMMY VARIABLE


82 REM P--ACTUAL PRICE
03 REM N--NUMBER OF ARTICLES (INDEX)
04 REM C--CoST OF THE ARTICLES
18 DEF FNC(P1)=INT(P1/2*N*1~TD+.5)/leTD
28 LET D=2
38 READ P
40 [lATA 22.95
50 PRINT
60 FOR N=3 TO 7 STEP 2
70 LET C=FNC(P)
88 PRINT "COST OF";N;"ARTICLES IS:";C
98 NEXT N
99 END

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.

Function definition Function reference


~I
I i , ~, i
10 liEF FNM(Ml)=Ml*1.609 3~ LET K=FNM(M)

r r
i
I

Dummy Function
i Actual
argument argument

Some computer systems allow more than one argument in the


function definition and in the function reference, making it possible to
pass more than one value to the function definition. However, on all
systems, only one value is returned to the calling statement. Some
systems support multiline user-defined functions. These are used to
define complex functions that often require branching and looping .

Questions and Exercises 8


1. What is a subroutine?
2. State two advantages in the use of subroutines .
3. Explain how the GOSUB and RETURN statements work together .
4. What is the output of each of the following programs?

(a) 1111 PRINT


2111 LET P:=111

8. You may skip questions concerning multiline user-defined functions, ON GOSUB


statements, and user-defined functions with more than one argument if your com-
puter system does not support these .
546 PROGRAMMIN G IN BAS IC

321 LET N::::0


40 FOR 1::::1 TO 6
50 READ A
621 DATA 5,-2,9,-4,3,-6
70 GOSUB 20'~
80 NEXT I
921 PRINT P,N
H~21 END

200 IF A<0 THEN 230


210 LET P=PtA
2221 RETURN
238 LET N::::N+A
240 RETURN
(b) 121 PRINT
20 LET E=~
38 LET D=0
40 FOR 1::::1 TO 6
50 READ A
621 DATA 5,-2,9,-4,3, - 6
721 IF A/2=INT(A/2) THEN 112!lJ
821 GOSUB 3210
921 GO TO 110
1210 GOSUB 200
110 NEXT I
120 PRINT E ,[1
130 END
2021 LET E=[+l
210 RETURN
32121 LET [I=D+ 1
310 RETURN
(c) HI DIM P(4),F:(4)
221 PRINT
30 FOR 1=1 TO 4
40 READ P ( I)
521 DATA 4,3,1,2
60 PF:INT P ( I ) ;
721 NEXT I
821 GOSUB 2021
921 END
2021 PRINT
2121 FOR J=: 1 TO 4
2221 LET P(J)=P(J)*2
2321 PRINT P(J);
248 NEXT J
2521 RETURN
SUB PR OGR A MS 547

(d) 10 DIM R(3,4)


20 PRINT
30 FOR 1=1 TO 3
4111 FOR J=l TO 4
50 READ R(I,J)
6121 DATA 3,2vlhl
7111 DATA 1"?J~2,3
8111 DATA 2,4,1,111
9121 GOSUB 2111111
UH1 NEXT J
lal PRINT
120 NEXT I
13111 GOSUB 3111111
140 PRINT
150 PRINT S
16121 ENI)
2111121 PRINT F.:(I,J);
21121 RETURN
31110 LET S::0
3HI FOR L=l TO 4
32121 LET S=StR(1,L)
330 NEXT L
340 RETURN
(e) 1111 PRINT
2121 FOR 1=1 TO 3
3121 REAli C
40 DATA 1,2,3
5121 ON C GOSUB llUI, 21110, 3111l?!
6121 NEXT I
7121 ENfI
UJI2I PRINT
11121 PRINT I,ITl
120 RETURN
20121 PRINT
21111 PRINT I,IT2
221:1 RETURN
31110 PRINT
310 PRINT I,IT3
32121 RETURN

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

01 REM N--NUMBERS TO BE AVERAGED


02 REM S~-SUM
03 REM A--AIJERAGE

10 REM THIS IS THE MAIN PROGRAM


20 PRINT
30 FOR 1=1 TO 4
4111 REArl N ( I )
50 DATA 67,85,79,93
60 PRINT N (1)
70 NEXT I
80 GOSUB 2~Hl
90 PRINT
10l1! PRINT "THE SUM IS:";S
110 PRINT "THE AVERAGE IS:";A
120 END

RUN

67
85
79
93

THE SUM IS: 324


THE AVERAGE IS! 81

6. Modify the program in Problem 5 so that there are two subrou-


tines; the first one is called by the main program and the second
one is called by the first subroutine.
(a) The first subroutine finds the sum and the average.
(b) The second subroutine prints the sum and the average with
headings as shown on page 549 . Use the TAB function.

01 REM N--NUMBERS TO BE AVERAGED


02 REM S--SUM
03 REM A--AVERAGE
10 REM THIS IS THE MAIN PROGRAM
20 PRINT
30 FOR 1=1 TO 4
40 READ N(I)
50 DATA 67,85,79,93
60 PRINT N(I)
70 NEXT I
80 GOSUB 2e0
90 END
SUB PROG RAMS 549

RUN
67
85
79
93
..
0 10 23
SU HI AIV ER A E

3·4 81

7. What is wrong with each of the following programs?

(a) 10 LET A=8


2£'1 LET B=4
3£'1 GOSUB 20£'1
40 LET S=AtB
5£'1 PRINT S
621 END

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

220 PRINT Ad!,5


2:30 RETUr~N
240 LET A=rH2
250 RETURN
(d) 10 LET 5=0
20 LET A=8
30 GOSUB 2~~
40 END
200 LET S=5+A
2H'JPRINT
220 PRINT A,5
230 LET A=A+l
24~ IF 5<20 THEN Hl
250 RETURN

8. (a) What is a user-defined function?


(b) State an advantage in its use.
9 . (a) What is the purpose of the DEF statement?
(b) Where are DEF statements usually placed in a program?
(c) Display and label a DEF statement.
10. (a) How are user-defined functions named? Give three exam-
ples of function names.
(b) What restriction is placed on the name of a user-defined
function if there is more than one such function in a program?
11. (a) State the difference between a function definition and a
function reference.
(b) Where maya function reference appear in a program?
12. (a) Where is a dummy argument coded in a program? What is its
purpose?
(b) Where is an actual argument coded in a program? What is its
purpose?
13. (a) How may the argument In a function reference be
expressed? Give four examples.
(b) State one restriction placed on this argument in its relation to
the dummy argument in a function definition.
(c) How must the argument In a function definition be
expressed?
14. What three ru les must be observed when a computer system
allows more than one argument in the function definition and in
the function reference?
15. How many values are returned from the function definition to the
statement that contains the function reference?
16 (a) Summarize the composition of a multiline user-defined func-
tion.
(b) When is this type of function used?
(c) How is a value passed from a function reference to a variable
in a multiline user-defined function?
(d) How many values are returned from the multiline user-
defined function?
SUBPROGRAMS 551

17. Find , by hand, the value of R in each of the following program


segments. The user-defined function is the expression that
rounds off a decimal number to the nearest whole number.

10 DEF FNRCN1)=INT(Nl*10TDt.5)/10TD
20 LET D:=0

(a) 30 LET N=2.68


40 LET R=FNR(N)

(b) 30 LET N=6.32


40 LET R=FNR(N)*2
(c) 30 LET N=6.32
40 LET R=FNR(N*2)

18. What is the output of each of the following programs?

(a) H! DEF FNR(Nl)=INT(Nl*10TDt.5)/10TD


20 DEF FNS(Rl)=SQR(Rl)
30 LET D=0
40 LET N=63.85
50 LET R=FNR(N)
60 LET S=FNS(R)
70 PRINT
80 PRINT N,R,S
99 END

(b) 10 DEF FNR(B)=INT(B*10TDt.5)/10TD


20 DEF FNW(Al)=Al*14.3
30 LET [1=0
40 LET A=5
50 LET W=FNR(FNW(A»
60 PRINT
70 PRINT W
99 END

19. Find, by hand, the value of Y in each of the following statements,


using the function definition and the values for A and B as shown
below.

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

(b) 4121 LET Y=FNY (A, B) t2

(c) 4121 LET Y=FNY (A, Bt2)

(d) 4121 LET Y=SIJR(FNY(A,B»

20 . Indicate the errors , if any, in the programs shown below . If there


is an error, make the necessary correct ion . If there is no error ,
show the result of a RU N.

(a) 1121 DEF FNB(A1)=A1t2


2121 LET A=5
3121 LET B=FNA(A)
4121 PRINT
50 PRINT A,B
99 END
(b) 1121 ItEF FNB(A1)=A1t2
20 PRINT
30 FOR 1::1 TO 5
4121 REAli A(I)
5121 DATA 1121,2121,3121,4121,5121
60 LET B=FNB(A(I»
70 PRINT A(I),B
80 NEXT I
99 END

(c) 1121 DEF FNB(A1)=A1tBtC


20 READ B,C
3121 I1ATA 4,8
4121 LET D=FNB(A)
5121 PRINT
6121 PRINT II
99 END

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.

(i) Complete line 10 with a DEF statement.


(ii) Complete line 40 with a function reference coded in a LET
statement.

01 REM N1--DUMMY VARIABLE


02 REM N--NUMBER
03 REM C--NUMBER CUBED

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

22. Complete the program below with a multiline user-defined func-


tion. The program checks a number to see if it is odd or even . A
code of 1 is printed if the number is even; a code of!/) is printed if
the number is odd . Use the INT function to check divisibility. Refer
to Chapter 9, page 404, if you need help.

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.

1. ON ... GO TO statement - Chapter Four, page 123


Programming problem-Chapter Four, page 144
Write a program that determines the balance of a customer's account
after each of the following transactions. There is no previous balance.
Codes are used to indicate whether the transaction is a purchase or a
payment

Purchase ... . . . .. .. . . . ...... . . ... $250


Payment ...... . ......... . ..... 150
Purchase . . . . . . . . . . . . . . . . . . . . . . .. 300
Payment ......... . .............. 200

(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

Using the PRINT USING and IMAGE Statements

Using the TAB Function

2. RESTORE statement-Chapter Three, page 89


Programming problem - Chapter Three, page 92
A customer is shopping for two Items - a chair and a table lamp .
These items were originally marked at $80 and $60 respectively at
two different stores. The first store is offering a discount of $10 on
each item, while the second store is offering a discount of $20 on
each item. Write a program that finds the reduced price of each item in
each store.

(a) Use two subroutines:


(i) The first subroutine calculates the reduced prices offered by
the first store.
(ii) The second subroutine calculates the reduced prices offered
by the second store.
(b) Print the information for each store in the appropriate subroutine.
Use format-free output.
(c) Remember to print the original value of each item before making
any change in its value.
(d) In the main program, perform the following:
(i) Use the READIDATA statements to assign the original prices to
C1 (chair in first store) and L 1 (lamp in first store).
(ii) Call the first subroutine to change the values of C1 and L 1.
(iii) Use a RESTORE statement to reassign the original prices to
variables C2 (chair in second store) and L2 (lamp in second
store).
(iv) Call the second subroutine to change the values of C2 and
L2 .
556 PROGRAMMING IN BASIC

RUN

FIRST STORE
CHAIR: 80 LAMP: 60
REDUCED: 70 REDUCED: :::,0
SECOND STORE
CHAIR: 80 LAMP: 60
REDUCED: 60 REDUCED: 40

3. ON ... GOSUB statement 10 - Chapter Eleven, page


516
Programming problem - Chapter Five, page 189
Write a program that finds the number of TRUE answers and the
number of FALSE answers on a questionnaire that consists of 20
questions.
(a) Use two subroutines:
(i) One subroutine calculates the number of TRUE answers.
(ii) The other subroutine calculates the number of FALSE
answers.
Remember to initialize two variables to zero in the main program
before accumulating the number of TRUE answers and the num-
ber of FALSE answers.
(b) Use the PRINT USING and IMAGE statements to format the output.
Code the headings in the PRINT USING statement.
(c) Use a FOR/NEXT loop to control input.
(d) Use the READ/DATA statements to enter the data shown below.

xx DATA 2,1,2,1,2,2,1,2,1,2
xx DATA 1,2,1,1,2,1,2,1,1,2

(e) Use the ON. GOSUB statement to branch to the appropriate


subroutine. A code of 1 indicates a TRUE answer and a code of 2
indicates a FALSE answer.

ffiIIfWIn~~~ Ill ifmWlli


I
E ,!
I

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

4. INT function-Chapter Nine, page 400


Programming problem - Chapter Six, page 233
A wage program was written in Chapter Three and modified In
Chapters Five and Six. Rewrite the program so that it is divided into
several subroutines. Shown below is the problem with the informa-
tion you need.
Find the wages for three employees who are paid on the basis of a
39-hour week and who receive time-and-a-half for overtime. Deduc-
tions are made for income tax, union dues, and a registered pension
plan.

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

(a) Use four subroutines:

(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

(i) Gross Pay with overtime:


- Overtime Hours = Regular Hours - 39
- Overtime Rate = Regular Rate x 1.5
- Overtime Pay = Overtime Hours x Overtime Rate
- Gross Pay (with overtime) = 39 x Regular Rate + Over-
time Pay. Use the INT function to round off the gross pay to
the nearest cent.
(ii) Gross Pay (no overtime) = Regular Hours x Regular Rate
Use the INT function to round off the gross pay to the nearest
cent.
(iii) Net Pay:
- Total Deductions = Income Tax Deduction + Union Dues
+ Pension Deduction
- Net Pay = Gross Pay - Total Deductions
SUBPROGRAMS 559

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.

Calculate Set to Zero


Ovetime Hrs. Hl=0
H1 = H-39 R1 = Ql
Overtime Rate V=Ql
R1=R*1.5
Calculate
Gross Pay
G= INT(H*R*1 OJ
02+ .5)/ 10i02

GOSUB400

End
GOSUB400

Return

Return

GOSUB200

GOSUB 300 NEXTE

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

EMPL. 2 HRS 37 RATE 11.543


OVERTIME HOllRS 0
OVERTIME RATE 21
OVERTIME F'AY 21
GROSS PAY 427.219
INCOME TAX 75
UNION DUES 2
PENSION 2.5
TOTAL DEDUCTIONS 79.5
NET PAY 34"7.59

EMPL. 3 HRS 39 RATE 12.349


OVERTIME HOURS 11I
OVERTIME RATE 21
OVERTIME PAY 121
GROSS PAY 481.61
INCOME TAX 921
UNION DUES 2
PENSION 4
TOTAL DEDUCTIONS 96
NET PAY 385.61

5. INT function-Chapter Nine, page 400


User-defined functions - Chapter Eleven, page 525
Programming problem - Chapter Six, page 233
The number of statements in the wage program in Problem 4 can be
greatly reduced if on Iy the net wages are calculated and the remaining
information is not required. Two functions that calculate the net
wages are shown on page 561. The first one finds the wages of an
employee who works more than 39 hours; the second one finds the
wages of an employee who works 39 hours or less. Deductions are
subtracted in both functions . R represents RATE, H1 is the dummy
argument for HOURS, and D denotes DEDUCTIONS.
SUBPROGRAMS 561

With overtime R*39t<Hl-39)*R*1.5-·D


Withnoovertime R*Hl-ii

You should use three user-defined functions:


(i) One finds the wages that include overtime .
(ii) Another finds the wages that do not include overtime.
(iii) The third rounds off either one of the above wages to the nearest
cent.

Code the function references in LET statements. Pass the hours of


work to the user-defined functions that calculate the wages and pass
the wages to the user-defined function that rounds off the wages to
the nearest cent. If you need some help, refer to page 535 of this
chapter, where the wage functions were introduced as "Your Turn"
problems.
(a) Use a FOR/NE XT loop to keep track of the employees. Use the
index of the FOR statement to represent the number of the
employee.
(b) Use the TAB function to format your output. Print the headings
outside the FOR/ NEXT loop.
(c) Use the RE AD/DATA statements to enter the hours, rate, and
deductions.
(d) Check the hours for overtime. If the employee worked more than
39 hours , call the user-defined function that calculates wages
with overtime; otherwise, call the user-defined function that
calculates wages with no overtime.
(e) After finding the employee's wages , call the user-defined func-
tion that rounds off the wages to the nearest cent.

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 )

Calculate Round off


Wages (no wages to
overtime) nearest cent
W= FNN(H) N= FNR (W)

NEXT E

6. RND function- Chapter Nine, page 412


Programming probl e m - Chapt er Nine, page 438
Suppose two playe rs are playing a game in which each one moves
his/ her chi p a certain number of times, depending on where the dial
stops on a spinner. The dial may stop at any number from 1 to 9
in clus ive. Write a program that determines which player makes the
greater number of moves after each one has had 10 plays .
SUBPROGRAMS 563

(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

Second Player Return


Random No .
R2=INT
(N*RND(1)+ I)
Total Moves
P2= P2+R2 Return

Return
SUBPROGRAMS 565

7.1Wo-dimensional arrays-Chapter Eight, pages 357,


361, and 362
Write a program that multiplies each element of the matrix shown
below by 3 (a scalar), stores the results in matrix B, then adds the two
matrices (A and B) to produce a third matrix, C.
(a) Read the data in the main program .
(b) Use nested FOR/NEXT loops in the main program and in each of
the subroutines.
(c) Use four subroutines . The main program calls the first subroutine
and the first subroutine calls the others to print the three matrices.
Reference all subroutines outside the FOR/ NEXT loops.
(i) The first subroutine multiplies matrix A by the scalar to
produce matrix B, then adds the two matrices to produce
matrix C. Your statement to add should be
xx LET C(K,L)=A(K,L)+B(K,L)
providing your indexes are K and L.
(ii) The second subroutine prints matrix A.
(iii) The third subroutine prints matrix B.
(iv) The fourth subroutine prints matrix C.
(d) Print the arrays in matrix form as shown in the RUN. Do not use the
PRINT USING and IMAGE statements or the TAB function to format
your output. Here is the data.
A
456
894
789

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

8. MAT statements 11 - Chapter Nine, pages 383, 398,


and 400
Rewrite the program in Problem 7, this time using MAT statements to
read, multiply, add, and print.

11. You may skip this problem if your computer system does not support MAT
statements .
566 PROGRAMMING IN BASIC

Use two s ubroutines :


(i) The first subroutine is cal led by the main program to multiply and
add.
(ii) The second subroutine is called by the first sub routine to print the
three matrices .

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

9 .• NT function-Chapter Nine, page 400


Programming problem - Chapter Nine, page 434
Using an initial principal of $1000 , find the amount of an investment at
the end of eac h year for four years when interest is added each yea r to
the investment. Use interest rates of 13%, 14%, and 15%. The
am ount of the investment after interest has been added is called the
compound amount. Th e formula to ca lculate this amount is as shown
below.
Compound Amount = Principa l( 1 + Rate of Interest)PeriOd of Time

(a) Call a user-defined function to calculate the compound amount.


Use the INT function in this statement to round off the amount to
the nearest ce nt.
(b) Use a LET statement to assign the principal ($1000) to a variable.
Code a function reference in another LET statement and pass the
$1000 to the user-defined function.
(c) Use two FOR/NEXT loops:
(i) The o ute r loop keeps track of the years (period of ti m e in the
formula). Use the index of the FOR statement to print the
number of the year at the beginn in g of each output line . Place
th is PRINT statement between the FOR statements
(ii) Th e in ner loop generates the interest rates.
SUBPROGR AMS 567

(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

1 113~ 1140 115~


2 1276.9 1299.6 1322.5
3 1442.9 1481..54 152~L88
4 163~.47 1688.96 1749.~11

10. INPUT statement 12 -Chapter Three, page 66


Trailer value - Chapter Five, page 149
INT function - Chapter Nine, page 400
Programming problem-Chapter Four, page 142
Employees of the XYZ Manufacturing Company are paid on the basis
of the number of parts they produce . Find the weekly wages of three
employees who are paid $2.343 for each part they produce. Use the
following information.

Employee No. of Parts Produced Deductions


1 212 105
2 213 110
3 209 102
(a) Use a user-defined function to calculate the wages Include the
INT function to round off the wages to the nearest cent.
Wages = Number of Parts Produced x Rate - Deductions
(b) Use a LET statement to assign the rate to a variable .
(c) Use the INPUT statement to enter the employee number, the
number of parts produced, and the employee's deductions . Use
a trailer value of 99999 to terminate input.
(d) Code the function reference in a LET statement and pass the
number of parts produced to the user-defined function.
(e) Use format-free output.

Using the INPUT Statement

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

Using the READ/DATA Statements

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

11. Special value-Chapter Five, page 155


INT function - Chapter Nine, page 400
Programming problem-Chapter Ten, page 503
A furniture store is offering a 121/2% discount on television sets at its
end-of-the-year sale. Calculate the discounts and the reduced prices
of six TV sets regularly priced at $853, $894, $842, $925 , $987, and
$961.
(a) Use two user-defined functions :
(i) One calculates the discount. Use the INT function in this
statement to round off the discount to the nearest cent.
Discount = Regular Price x .125
Code the function reference that calls this user-defined
function in a LET statement. Pass the regular price to the
function and assign the returned value (the discount) to a
variable , say D .
(ii) The second user-defined function calculates the reduced
price.
Reduced Price = Regular Price - Discount
Code the function reference that calls th is user-defined
function in the PRINT stateme nt that prints the amounts as
shown on the following page , Pass the regular price to the
user-defined function .
(b) Use the RE A D statement to store the number of TV sets in a
SUBPR O GRAMS 569

simple variable . The variable is used subsequently with a counter


to terminate the loop. The counter should be set initially to one
and incremented after each reduced price is calculated.
(c) Use the READ/DATA statements to enter the regular prices.
(d) Use the TAB function to format your output.

12. AND function-Chapter Nine, page 412


Programming problem - Chapter Ten, page 501
Write a program that finds how many 7's and how many 11's are rolled
out of 50 rolls of a pair of dice. Use the random number generator to
simulate the roll of the dice.
(a) Use a user-defined function to generate a random whole number
between 1 and 6 inclusive.
(b) Use the TAB function to format the headings and the results .
(c) Use a LET statement to assign the "number" of numbers (6) to a
variable .
(d) Code a function reference in each of two LET statements -one
for each die. In both statements pass the "number" of numbers
to the user-defined function. Assign the returned random num-
ber to the variable representing the die; say 01 for die number 1
and 02 for die number 2.
(e) Find the total of a roll and check for a 7 or an 11. Keep two running
counters-one to accumulate the number of times a 7 is rolled,
and the other to accumulate the number of times an 11 is rolled.

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

ments that use function references rather than statements


that generate random numbers.
Note: Output will differ for each RUN.

13. Multiline user-defined function 13 - Chapter Eleven,


page 533
Write a program that uses a multiline user-defined function to find the
square root of Bi2-4*A*C. Find the square root only if the equation
results in a positive or zero value, then assign the square root to the
function name. If the result of the equation is a negative value, assign
-1 to the function name.
(a) Use a FOR/NE XT loop to control input.
(b) Use the READID ATA statements to assign data to the three vari-
ables, A, B, and C, respectively. Use the following data state-
ments .

>::-: DATA 2,6,4


>~>~ DATA 1,8,16
:-::-: DATA 3,4,2

(c) Code the function reference in a LETstatement. Pass the value of


A to the user-defined function.
(d) Use the TAB function to format your output as shown.

-
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

14. A program on page 519 illustrated how subroutines can be called


upon to draw common lines of letters of the alphabet. Use
subroutines to draw your initials one under the other such as
Eorm
B OJ
L ,
The second type of display is often used when letters are printed
on paper.
(a) Use the TAB function and the same symbol throughout (per-
haps an asterisk) to draw the letters .
572 PROGRAMMING IN BASIC

(b) Use one variable to represent the number of symbols to be


printed. Change the value of this variable (when necessary)
before calling a subroutine. The variable can also be used to
position a symbol by coding the variable in the argument of
the TAB function.
15. Use subroutines to draw a picture of your choice. You may use
either the TAB function or the PRINT USING and IMAGE statements
to draw the picture .
STRINGS 573

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.

12.1 STRING VARIABLES


The programs in the preceding chapters manipulated only numeric
data. The use of alphanumeric data (a mixture of numeric, alphabetic,
and special characters) was restricted to the PRINT statement. The
characters were enclosed within quotation marks and printed as a
string . Other than printing a heading or a message a string was not
manipulated in any other way .
A stri ng may be assigned to a variable. This type of variable is called
a string variable and, like a numeric variable, must begin with a letter
of the alphabet. To differentiate between the two types , a string
574 PROGRAMMING IN BASIC

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 .

12.2 ENTERING STRINGS INTO THE


COMPUTER
The three methods by which strings may be entered into the com-
puter will now be discussed. (Note that they are the same methods
that were introduced in Chapter Three.) Strings that are assigned to
variables must often be enclosed in quotation marks , particularly
when more than one string is entered on the same line in response to
an INPUT request or listed in the same DATA statement. These quotes
may be double or single , depending on the computer system being
used . Some systems require quotes around a string when the string

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

consists of a number or when one of its characters is a comma or a


colon. Quotes may also be necessary when a string contains a
leading space or a trailing space. The majority of computers requires
quotes when a string is entered by means of a LET statement or when
the string is coded in an IFfT HEN statement.

10 LET A$="HELLO" 3~ IF B$="HI" THEN 9~

Check your computer manual or experiment to find out when you


need quotation marks around strings . The strings in this chapter are
enclosed in quotes when:
1. The string consists of a number.
2. The string contains a comma or a colon.
3. The string contains a leading space.
4. The string contains a trailing space and the string is the last item
in the second line of a DATA statement.
5. The string is in a LET statement, an IFfT HEN statement , or a PRINT
statement.
It should also be mentioned that a quote is usually not allowed within a
string when the quote is the same type (double or single) as the one
that delimits the string . Also, a string comprised of numbers may not
be used in arithmetic computations .
As with numeric data, strings must be separated by commas when
more than one string is typed in response to an INPUT statement or
listed in the same DATA statement. The data must correspond in
number, order, and type to the variables listed in the INPUT statement
or in the READ statement.

-Same number
-Same order
-Same type

The string JANUARY is assigned to the string variable M$ , the


number 1 is assigned to the numeric variable 0, and the string
MONDAY is assigned to the string variable 0$.
Just a few words concerning the printing of strings. If your com-
puter distinguishes a comma from a semicolon, a comma in the PRINT
statement produces wide spacing between two strings ; a semicolon
leaves no space unless a leading space or a trailing space is coded as
part of a string .

10 DATA JOHN SMITH ,ROXVALE


t
Trailing space in the string JOHN SMITH

I
.~
- - - - - - - -- - -

576 PROGRAMMING IN BASIC

A string that includes a leading space must be enclosed in quotation


marks.

10 DATA JOHN SMITH," ROXVALE"


i
Leading space in the string ROXVALE

Numbers are printed differently among computer systems. The com-


puter used for this book leaves one space before a positive number
for the assumed plus sign and fills this space in with a minus sign
when the number is negative. It leaves one space after any number
regardless of the number's sign. If your computer leaves no space
before a number and no space after a number, a space must be coded
in the string that comes before the number and in the string that
comes after the number or the space may be coded as a separate
string in the PRINT statement. Here are two examples.

20 DATA JANUARY ,1," MONDAY"


30 PRINT M$;rqD$
t t .h'
Aspacelneac string.
or
20 DATA JANUARY,l,MONDAY

30 PRINT M$;· • ;D;· • HI$


t. . .__---'t'--__ Spaces coded as strings.

Use the various DATA and PRINT statements shown above , along with
the READ statement, to find out how your computer prints strings.

12.2 ENTERING STRINGS INTO THE


COMPUTER - Sample Programs
A number of programs are shown below to illustrate the three
methods of entering strings. Semicolons , rather than commas, are
coded in the PRINT statements since differences in spacing are more
readily apparent by their use. Each of the programs assigns the name
of a person to N$, the name of a city to C$, and a number to N.

1. Using the INPUT statement J

H'l PRINT - Leaves a blank line.


20 PRINT "DATA"; -A prompt.

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.

DATA? JOHN SMITH ,ROXVALE,123456


i
Space
i
No space

2. Using the READ/DATA statements

- Reads the name, city , and number


from the DATA statement.
20 DATA JOHN SMITH ,ROXVALE,123456 - Supplies the READ statement with data .
30 PRINT - Leaves a blank line.
40 PRINT N$;C$;N - Prints the name, city , and number
closely spaced .
99 END - Terminates program execut ion.

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 .

20 DATA JOHN SMITH ,ROXVALE,123456


t
Space
t
No space
578 PROGRAMMING IN BASIC

3. Using LET statements

10 LET N$="JOHN SMITH · - Assigns JOHN SMITHI)4 to N$.


20 LET C$="ROXVALE" - Assigns ROXVALE to C$.
30 LET N=123456 - Assigns 123456 to N.
40 PRINT - Leaves a blank line.
50 PRINT N$;C$;N - Prints the name, city, and number closely spaced.
99 END - Terminates program execution.

FWN

JOHN SMITH ROXVALE 123456

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 N$="JOHN SMITH "


20 LET C$=" ROXVALE' i or 1~ LET N$="JOHN SMITH"
20 LET C$=" ROXVALE"
t
Space Space

Some versions of BASIC allow multiple assignment statements to


assign strings to string variables. For example, the statement

10 LET A$=B$=C$="ROXVALE"

assigns ROXVALE to each of the variables A$, B$, and C$.


String variables can also store arrays. The following program reads
the names of the nine planets into a one-dimensional array, then
prints the names closely spaced .

1£1 [11M P$(9)


2£1 PRINT
30 FOR 1=1 TO 9
40 READ P$(I)
5£1 DATA MERCURY ,VENUS ,EARTH ,MARS ,J
UPITER ,SATURN ,URANUS ,NEPTUNE ,PLUTO
60 PRINT P$(I);

4. The symbol tI represents a space


STRINGS 579

70 NEXT I
99 END

RUN

MERCURY VENUS EARTH MARS JUPITER SATURN


URANUS NEPTUNE PLUTO

The variable P$ in lines 10,40, and 60 is a subscripted string variable.


On most computers, this variable needs to be dimensioned when
there are more than ten elements (strings) in the array . Notice that the
data statement requires two lines. This is permitted since the com-
puter being used allows 79 characters in a statement. Each string
contains a trailing space . Without this space , the names of the planets
would run together when they are printed.
The name of a specific planet can be printed by referencing the
appropriate element of the array. For example, if you want to print the
name of the planet on which you live, the PRINT statement would be
PRINT P$(3). The statement must be coded out of the loop, other-
wise the name will be printed more than once .
The program below stores the names of the planets as elements of
a two-dimensional array, then prints the names in matrix form . Here
are the names arranged as a matrix.

P$
Column 1 Column 2 Column 3

Row 1 MERCURY VENUS EARTH


Row 2 MARS JUPITER SATURN
Row3 URANUS NEPTUNE PLUTO

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

MERCURY VENUS EARTH


MARS JUPITER SATURN
URANUS NEPTUNE PLUTO

In this program, P$ is a doubly subscripted string variable. On most


systems, the variable needs dimensioning only if one of its subscripts
is greater than 10. The names of the planets in the DATA statement are
listed by rows since the row loop is on the outside. Again, each string
must contain a trailing space. Notice that NEPTUNE is enclosed in
quotes. These quotes are necessary, as the string must end with a
space. Without the quotes, the next planet's name (PLUTO) would
be printed immediately after NEPTUNE, since PLUTO is coded in a
new DATA statement.
Specific elements may be referenced by coding explicit subscripts
for the row and column. For example, if you want to print MARS, your
PRINT statement would be PRINT P$(2,1) .

12.2 ENTERING STRINGS INTO THE


COMPUTER- Your Turn
1. What is wrong with each of the following programs? Make the
necessary corrections.

(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

(c) 10 LET B$="BLACK"


20 LET W$="WHITE"
30 PRINT
40 PRINT £1$; "AND" ;W$
99 END
STRINGS 581

2. Write three programs, each one producing the following output.

HON[lAY JANUARY 1

(a) Assign MONDAY and JANUARY to separate string vari-


ables.
(b) Assign the number 1 to a numeric variable.
(c) To enter the data :
- The first program uses the INPUT statement. Show how
the data is entered in response to this statement.
- The second program uses the READ/ DATA statements.
- The third program uses LET statements.
(d) Use semicolons to separate the items in the PRINT state-
ments.
3. Write three programs, each one producing the output shown
below. Replace the score with your own number of points.

I SCORE[I 24 POINTS

(a) Assign I SCORED to a string variable, the number of points


to a numeric variable, and POINTS to a second string varia-
ble.
(b) To enter the data:
- The first program uses the INPUT statement. Show how
the data is entered in response to this statement.
- The second program uses the READ/ DATA statements.
- The third program uses LET statements.
(c) Use semicolons to separate the items in the PRINT state-
ments.
4. Write a program that enters the following six names into the
computer and prints only the first, third , and fifth names widely
spaced.
Anne, Craig, Barry, Roger, Laurie, Tracy
(a) Use a FOR/ NEXT loop to control input.
(b) Use the READ/DATA statements to enter the names. Leave a
trailing space after each name in the DATA statement .
(c) Store the names in a one-dimensional array .
(d) Use explicit subscripts to print the appropriate elements of
the array .
(e) Notice that there is no extra space between the names in the
output. Each name starts in the first print position of a zone .
The trailing space in each string in the DATA statement is part
of the name.

RUN

ANNE BARRY LAur~ IE


582 PROGRAMMING IN BASIC

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

ANNE BARRY LAURIE

12.2 ENTERING STRINGS INTO THE


COMPUTER - Solutions for "Your Turn"5
1. (a) The variable N in lines 30 and 40 should be a string variable ,
since a person 's name will be assigned to this variable.

3i!l INPUT N$,T


4i!l PRINT Ni;T

(b) The names of the months will be printed with no space


between each name. There should be a space after JANU-
ARY and another after MA Y in line 40.

4i!l DATA JANUARY ,MAY ,SEPTEMBER

(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 .

li!l LET B$="BLACK " 10 LET B$="BLACK "


4i!l PRINT B$;"AND ";W$ 2~ LET Wi:" WHITE"

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

2 . (a) Using the INPUT Statement

£11 REM [t~--[tAY OF THE WEEK


~2 REM M$--MONTH
03 REM [t--DAY OF THE MONTH
10 PRINT
20 PRINT I[tATE";( Optional
3£1 INPUT [t$.t'l$,[t
40 PRINT [1$; M$ HI
99 END
RUN
DATE? MON[tAY ,JANUARY,l

(b) Using the READ/DATA Statements

10 READ D$,Mf,[I
20 DATA MONDAY ,JANUARY,1
30 PRINT
40 PR I NT [t~ HI$;[I
99 END

(c) Using LET Statements

10 LET Df="MONDAY I
20 LET M$="JANUARY"
30 LET [t=1
40 PRINT
50 PRINT D$;M$;[t
99 END

3. (a) Using the INPUT Statement

01 REM 1$--1 SCORE[t


02 REM N--NUMBER OF POINTS
03 REM P$--POINTS
HI PRINT
20 PRINT I SCORE I ; ~ Optional
3111 INPUT I$,N,P$
421 PRINT I$;NH'$
99 END
584 PROGRAMM ING IN BAS IC

RUN

SCORE? I SCORED,24,POINTS

(b) Using the READ/DATA Statements

10 READ I$,N,P$
20 DATA I SCORED,24,POINTS
30 PRINT
40 PRINT IHNH'$
99 END

(c) Using LET Statements

10 LET 1$="1 SCORED"


20 LET N=24
30 LET P$="POINTS"
40 PRINT
50 PRINT l$;NH'$
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

12,3 PROCESSING STRINGS


Before the processing of strings is discussed, you should be aware of
how information is stored in a computer. Each character (digit, letter,
or other symbol) is stored as a series of ones and zeros. These ones
and zeros are representative of the two states of the computer's
electronic circuitry, which can be either on or off. Conventionally, a 1
signifies that the circuit is on, while a (/) signifies that the circuit is off.
The 1 and the (/) are referred to as bits (binary digits) . The order of
their sequence is the numeric equivalent of a particular character. For
example, the number 1 is represented by the seven bits (/)11 (/)(/)(/)1 , the
letter A is represented by 1(/)(/)(/)(/)(/) 1, and the bit pattern for the letter Z
is 1011010. To standardize these numeric codes, several encoding
systems have come into existence. One of these is the seven-bit
ASCII code. ASCII is the acronym for American Standard Code for
Information Interchange. In ASCII, the digits (/) through 9 precede the
letters of the alphabet as shown on page 586.
Since the base two numbering system is an awkward system with
which to work, the binary codes are usually converted to their base
ten equivalent (decimal notation) or base eight equivalent (octal
notation) or base sixteen equivalent (hexadecimal notation). The
notation used depends on the computer system 6 Base ten uses the
ten digits (/) through 9 ; base eight uses the eight digits (/) through 7. To
represent values in hexadecimal notation, 16 one-digit symbols are
required. Since only ten are available in the decimal system, the
letters A, B, C, D, E, and F are used to represent the values 10,11,12,
13,14, and 15. 7
The process of converting letters, digits, and other characters to
their ASCII codes is referred to as encoding. Translating the ASCII
codes into their corresponding characters is called decoding. There
are many ASCII codes . These include codes that represent system
commands, such as the code for a carriage return which is shown
on the following page in two notations. 8

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

HI PR I NT CHR$ ( 13 ) Decimal notat ion


10 PRINT HEX(0D) Hexadecimal notatio n

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 .

Character Octal Decimal Hexadecimal

.
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

Character Octal Decimal Hexadecimal

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?

JAN SEN JAN ZEN


746578@ 74 6578@

False. 83 (the code for S in JANSEN) is not equal to 90 (the


code for Z in JANZEN).
2. Is STEPHENS less than STEVENS?

STEPHENS < STEVENS


838469@) 838469@

True . 80 (the code for P in STEPHENS) is less than 86 (the


code for V in STEVENS).
3. Is BROWNE greater than BROWN?

BROWNE > BROWN


6682 7987 78@) 6682 79 87 78@
588 PROGRAMMING IN BASIC

True . 69 (the code for E in BROWNE) is greater than 32 (t he


code for the space following BROWN) .

The remaining relational operators work in a similar manner . By using


these operators, it is possible to sort strings alphabetically in much
the same way as numbers were sorted in the Sorting Program in
Chapter Seven.

12,3 PROCESSING STRINGS-Sample


Programs
1. This program compares the two names AIKEN and AITKEN and
prints them in alphabetical order.

10 PRINT - Leaves a blank line.


20 LET A$="AIKEN " - Assigns AIKENt) to the string variable A$.
30 LET B$="AITKEN " - Assigns AITKENt) to the string variable B$ .
40 IF A$<=B$ THEN 70 - Compares the two strings:
(i) If the value of A$ is less than or equal to that of B$ ,
control is transferred to the PRINT statement, which prints the
value of A$ before the value of B$ .
(ii) If the value of A$ is greater than that of B$, the
computer proceeds to the next statement, which prints the
value of B$ before the value of A$ .
50 PRINi B$;A$ - Prints the value of ,B $ , then the value of A$ .
60 GO TO 99 - Transfers control to the END statement.
70 PRINT A$;B$ - Prints the value of A$, then the value of B$ .
99 EN[I - Terminates program execution .

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

10 PRINT - Leaves a blan k line.


20 FOR 1=1 TO 4 - Sets up a loop.
312l READ [1$ - Reads 4 strings one at a time and assigns each string to the
variable 0$.
STRINGS 589

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

In line 50, the string SATURDAY is enclosed in quotes. Most


computer systems require these quotes whenever a string is
compared with another value in an IFrTHEN statement. Also, no
trailing space is left after the name of each day in the DATA
statement, since these strings are not printed .
3. In this program, a counter (K) keeps track of how many times the
word YEAR is entered into the computer.

01 REM S$ - -STRING

121 LET K=~ -Initializes a counter to zero.


2f) FOR 1=1 TO 5 - Sets up a loop .
321 READ S$ - Reads 5 strings one at a time and
assigns each string to the
variable S$.
- Supplies the READ statement with 5
strings .
50 IF S$<>"YEAR" THEN 7B - Tests the value of S$ :
(i) If its value is not YEAR,
control is transferred to line 70
to resume reading.
(ii) If its value is YEAR, the
computer proceeds to the next
statement.
621 LET K=Kt1 -Increments the counter by one.
721 NEXT I - Transfers control back to line 20.
BB PRINT - Leaves a blank line.
90 PRINT "'YEAR' IS ENTERED";K;"TIMES" - Prints the number of times YEAR
is entered into the computer.
r
590 PROGRAMMING IN BASIC

99 END - Terminates program execution .

RUN
'YEAR' IS ENTERED 2 TIMES

As in the previous program , there is no need to code a space


after each string in the DATA statement since these words are not
printed.

4. Strings can be transferred orcopied from one storage location to


another without altering the contents of the first location.

10 LET A$="TORTOISE" - Ass ig ns TORTOISE to A$.


20 LET B$="HARE" - Assigns HARE to B$.
30 LET B$=A$ - Copies the string that is stored in A$ and places it in B$.

40 PRINT - Leaves a blank line.


50 PRINT A$,B$ - Prints the values of A$ and B$ widely spaced .
99 END - Terminates program execution.

RUN
TORTOISE TORTOISE

The string HARE in variable B$ has been replaced by the string


TORTOISE. TORTOISE is now stored in two locations, A$ and
B$. Since a comma is used in the PRINT statement , there is no
need for a trailing space after each string in the LET statements.
The second item is automatically printed in the next available
print zone .

5. Two strings can be added, although the computational procedure


is not the same as that performed on numeric data. The process
is referred to as concatenation. Here is a comparison of the two
types of addition.

(a) Addition on Strings (b) Addition on Numeric Values

10 LET A$="111" iE1 LET A=111


20 LET B$="222" 20 LET B='J'J'J
~~~

30 LET C$=A$+B$ 3 I?! LET C=AtB


40 PRINT 4 I?! PRINT
50 PRINT C$ 51?! PRINT C
99 END 99 END

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 .

HI LET A$=llll" - Assigns the string 111 to A$.


20 LET £1$="222" -Assigns the string 222 to B$.
30 STR(C$,1,3)=A$ - Sets the first, second, and th ird characters of C$ to 111 .
40 STR(C$,4,3)=B$ - Sets the fourth, fifth, and sixth characters of C$ to 222.
5111 PRINT - Leaves a blank line.
60 PRINT C$ - Prints the concatenated string.
99 END - Terminates program execution.

RUN

111222

6. Care must be taken when words are concatenated, for no space


is left between the words after they are "attached." Examine the
results of the following programs .
Using the "+" Operator

10 LET B$="BASIC" -AssignsthestringBASICtoB$.


20 LET C$= 1 COBOL 1 -Assigns the string COBOL to C$.
30 LET S$=B$+C$ -Concatenates the two strings .
4111 PRINT -Leaves a blank line .
521 PRINT S$ -Printstheconcatenatedstring.
99 END - Terminates program execution .

RUN
BASICCOBOL

Using the STR Function

10 LET B$="BASIC" - Assigns the string BASIC to B$.


2111 LET C$="COBOL" - Assigns the string COBOL to C$ .
30 STR(S$,t,5)=[I$ - Sets the first character through and including the fifth character of
S$ to BASIC.
40 STR(S$,6,S)=C$ - Sets the sixth character through and including the tenth character
of S$ to COBOL .
50 PRINT - Leaves a blank line.
6111 PRINT S$ - Prints the concatenated string.
99 END - Terminates program execution.
r-
592 PROGRAMMING IN BASIC

RUN
BASICCOBOL

How can the programs be modified so that there is a space


between the two words?

********************
1e LET B$="BASIC"
2e LET C$=" COBOL"
tSpace before COBOL

A leading space is coded in the string COBOL (" COBOL"). In


the function method , line 40 would be changed to 40
STR(S$,6,6)= C$. An alternative method is to code a trailing
space in the string BASIC ("BASIC ") with no space in the string
COBOL ("COBOL").

7. It is possible to accumulate strings. The programs shown below


accumulate the five letters B, A, S, I, and C in the string variable
W$. When using the "+" operator, the accumulation is similar to
the way numbers are added on the computer. The variable in
which the letters are accumulated is first initialized to the null
string (LET W$= ''I'), much like setting a numeric variable to zero
before numbers are summed (LET S=0). When using the STR
function to accumulate strings, initialization is to the "blank"
character rather than to the null string.

Using the "+" Operator

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

Using the STR Function

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

8. String variables may not be compared with numeric variables.


The following program produces an error message which will
be either the one shown below or something similar.

if! PRINT - Leaves a blank line.


20 LET A=123 -Assigns a numeric value to a numeric variable.
30 LET B$="123" - Assigns a string to a string variable .
40 IF A=B$ THEN 70 - Attempts to compare a numeric value with a
string; produces an error message.
50 PRINT A; " IS NOT EQUAL TO
60 GO TO 99
70 PRINT A;"IS EQUAL TO " ;II$
99 EN[I

RUN

?TYPE MISMATCH ERROR IN 4~

12,3 PROCESSING STRINGS - Your Turn


1. State whether the following relational expressions are true or
false . Write the ASC II code beneath each character until you find a
difference in the two strings .
r
594 PR OG RAMMING IN BAS IC

(a) SPARKES< SPARKS (d) KRUEGER <> KRUGER

(b) LlNDSA Y= LINDSE Y (e) LYNN < =L YNNE

(c ) FREDER ICK> = FREDRICK (f) PHILIPS> PHILLIPS

2. Fill in the missing lines .

(a) HI PRINT
20 LET AS="AN[lERSEN I

321 LET B$="ANDERSON 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

I LIVE ON THE PLANET EARTH

3. Indicate the errors , if any , in the programs shown below . If there


is an error, make the necessary correction ; if there is no error,
show the 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

(b) 10 LET K=0


20 FOR 1=1 TO 8
30 REA[I A$
4~ [lATA A,B,[I,B,F,C,A,B
50 IF A$="B" THEN 70
60 GO TO 80
70 LET K=K+l
80 NEXT I
90 PRINT
100 PRINT "B APPEARS";K;"TIMES"
999 END

4 . Write a program that concatenates the three strings PRO-


GRAMS, IN, BASIC . Assign each string to a string variable by
means of a LET statement .

RUN
PROGRAMS IN BASIC

12.3 PROCESSING STRINGS - Solutions for


"Your Turn"9
1. (a) SPA R K E S < SPA R K S
83 80 65 82 75@ 838065 82 75@
True

(b) L I N D SAY L I N D S E Y
7673 7868 83@ 76 73 78 68 83 @
False

(c) F RED E R C K > = F RED R I C K


7082 69 68@ 7082 69 68@
False

9. The co des shown for Pro blem 1 are in dec imal notation .
596 PROGRAMMING IN BASIC

(d) K RUE G E R < > K RUG E R


758285@ 758285@
True

(e) L Y N N < L Y NNE


76 89 78 78@ 7689 78 78@
True

(f) PHI L I P S > PHI L L I P S


8072 73 76@ 8072 73 76@
False

2.

(a) SB PRINT A$;BS (b) SB IF P$< > "EARTH" THEN 70


70 PRINT B$;A$

3. (a) The string CHIHUAHUA in line 30 should be enclosed in


quotation marks.

3B IF G$)"CHIHUAHUA" THEN 6B

(b) Nothing is wrong .

RUN
B APPEARS 3 TIMES

4. Using the "+" Operator

B1 REM C$--CONCATENATED STRING

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

Using the STR Function

B1 REM Cf--CONCATENATED STRING


STRINGS 597

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

12,4 EXTRACTING SUBSTRINGS10


Until now, you have been working with a string in its entirety. There
may be occasions when you want to access just part of a string.
Suppose each string consists of a person's first name, last name,
address, and telephone number. You may want to extract just the last
name from each string so that the names can be sorted alphabetically,
or perhaps you may want to extract the last name and the telephone
number from each string . The piece of string that is extracted is called
a substring . There are several different ways by which the various
versions of BASIC extract substrings . Some of the variations are given
in this chapter. If you find that none of them work on your com puter
system, check your manual. A feature that does affect the way a
substring is extracted is the method by which characters in a string
are numbered. Some systems consider the left-most character as
character number zero ; others consider it as character number one .
A substring may be comprised of one of the following:
1. Any number of left-most characters of a string.
2. Any number of right-most characters of a string.
3. Any series of characters from within a string.
You will be shown two basic methods of extracting substrings. One is
called the function method, which uses a built-in function followed by
arguments in parentheses, and the other is called the subscript
method, which uses a string variable followed by subscripts in paren-
theses. Two examples are shown below.

Function Method Subscript Method

LEFT$CS$,7> 5$(3,7)
i
Function
V
Arguments
String
variable
I V
Subscripts

Although two basic methods of extracting substrings exist, the


interpretation of the arguments, the interpretation of the subscripts ,
10 Some ve rsions of BASIC do not extract substrings from strings. Check your
computer manual, and if your system does not support this operation, you may omit
this section .
598 PROGRAMMIN G IN BASI C

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 .

I. To extract the left-most characters


xx LET S$= "PLAYING WITH WORDS"

Example Interpretation Result

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 .

II. To extract the right-most characters


xx LET S$= "PLAYING WITH WORDS"
Example Interpretation Result

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

Extract 10 characters starting atthe ninth . WITH WOR[tS

S$(9,18) Extract the ninth character through and WITH WORDS


including the eighteenth.
STRINGS 599

S$(9) Extract the ninth character through and WITH WORDS


including the last.

III. To extract any series of characters


xx LET S$= "PLAYING WITH WORDS"
Example Interpretation Result

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.

Extract the fifth character through and ING WITH WORDS


including the last.

SUBSTR(S$,5,HD Extract 10 characters starting atthe fifth . ING WITH W


STR(S$,5,1111)

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.

Notice that the first numeric argument in MID$(S$,5,10) and in


S$(5,10) indicates the starting point of the extraction. The argument
or subscript that follows is the one that is interpreted differently by the
various computer systems . Below is a review of the interpretation of
these two examples .

1. S$ indicates the string upon which the extraction will be per-


formed .
2. The 5 indicates where the extraction begins . This argument or
subscript is usually interpreted in the same way by all computers .
In this case , the extraction begins at the fifth character of the
string stored in S$ .
3. The last argument or subscript is the one that is interpreted
differently by the various systems . It may mean:
(a) Extract 10 characters starting at the fifth , or
(b) Extract the fifth character through and including the tenth .

One more comment before going on to some sample programs. If


the arguments or subscripts are negative orgreater than the length of
the string (or greater than what is left in the string) , an error message
will likely resu lt. Remember , some computer systems consider the
600 PROGRAMMING IN BASIC

left-most character of a string as character number zero. This means


that the argument or subscript indicating the start of an extraction of
the left-most characters would be zero.

12.4 EXTRACTING SUBSTRINGS-Sample


Programs
The programs that follow use the features listed below.
1. The left-most character of a string is considered character
number one.
2. The functions RIGHT$, LEFT$, and MID$ are used to
extract substrings with variations shown either alongside the
statements or below the program. Refer to your manual if the
ones given cannot be used on your computer system.
3. The third argument of the MID$ function indicates the num-
ber of characters to extract - that is, the count. For example,
MID$(S$,7,3) means "extract three characters starting at
the seventh."
4. In the variations:
(a) The third argument in the function method indicates the
number of characters to extract (the count). For exam-
ple, SUBSTR(S$,9,4) means "extract four characters
starting at the ninth."
(b) The second subscript in the subscript method indicates
where the extraction ends. For example, S$(4,8) means
"extract the fourth character through and including the
eighth."
I. This program extracts the seven left-most characters from a
string. The function is coded in a LET statement. A string variable
is used as an argument.

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

II. In this program, the ten right-most characters are extracted.


Instead of the string variable, the actual string (in quotes) is
coded as an argument of the function. The function is coded in a
PRINT statement.
STRIN GS 601

HJ PRINT
20 PRINT RIGHT$("PLAYING WITH WORDS",10)
99 END
RUN
WITH WORDS

Variations

20 PRINT SUBSTR("PLAYING WITH WORDS",9,10)


or20 PRINT SUBSTR("PLAYING WITH WORDS",9)

15 LET S$="PLAYING WITH WORDS"


2111 PRINT S$(9.18) or 20 PRINT S$(9)

20 PRINT STR("PLAYING WITH WORDS",9,10)


or20 PRINT STR("PLAYING WITH WORDS",9)

III. This program extracts a substring of four characters, starting at


the ninth character of the initial string. The function is coded in
both an IF statement and a PRINT statement. Notice the quotation
marks around the string WITH in line 20 .

10 LET S$="PLAYING WITH WORDS"


20 IF HID$(S$,9,4)="WITH" THEN 40
30 GO TO 99
40 PRINT
50 PRINT HID$(S$,9,4)
99 END
RUN

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.

(a) Use a counter to keep track of the number of A 's found.


(b) Use a FOR/ NEXT loop to control the testing of each letter in
the name .
(c) Use the MID$ function to test each letter. The function's
arguments should be the following:
(i) A string variable in which the name is stored.
(ii) The index of the FOR statement, say I. This is the starting
point of the substring in each test.
When I is 1, the substring starts at B;
When I is 2, the substring starts at A;
When I is 3, the substring starts at R,
etc.
(iii) The number 1, which indicates the length of the sub-
string. In this case, only one letter is extracted at a time.
(d) If the extracted letter is A, increment the counter; if it is not,
test the next letter.
(e) After all the letters in the name have been tested, print the
message as shown in the RUN.

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

NO. OF A'S IN BARBARA IS: 3

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

12.4 EXTRACTING SUBSTRINGS- Your Turn


1. The following is a list of members who belong to the social
committee of a local community club. Write a program that
STRINGS 603

determines the number of members whose first names are Allan


and prints the names of these members with a running counter
alongside each name.

Allan Smith, Laureen Peters, Allan Mills, Sandra Campbell, Allan


Webster, Mary Williams

(a) Initialize a counter to 1.


(b) Use a FOR/ NEXT loop to control input.
(c) Use the READ/ DATA statements to enter the names in first
name first order .
(d) Use the LEFT$ function in an IFfTHEN statement to extract the
first five characters of each name. In the same statement,
determine whether or not the substring is ALLAN. If it is,
transfer control to a statement that prints the name and the
runni1ng counter as shown in the RUN. Immediately after this
statement, increment your counter.

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 :

(a) Extract the three right-most characters of each name by


means of the RIGHT$ function.
(b) Compare the substrings using a relational operator.
(c) Branch to the appropriate PRINT statement.

RUN
ANDERSEN ANDERSON

3. Write a program that performs the following operations:

(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.

(a) Use two FOR/ NE XT loops:


(i) One loop controls the entering of data .
(ii) The other controls the isolating and printing of each letter.
(b) Use the RE A D/ DATA statements to enter the data .
(c) To print the letters of a name in reverse order :
(i) Set the initial value of the FOR statement in the inner loop
to 7 (the length of each name), then work backwards to 1
(the STEP value should be -1) . This means that you will
be working from the last letter in a name to the first letter.
(ii) Use the MID$ function to isolate each letter. Assign the
isolated letter to a string variable. The arguments of the
MID$ function should be the string variable in which the
name is stored, the index of the inner loop, and the
number 1, which extracts one letter at a time.
(iii) Print the value of the string variable that stores the
isolated letter. End the PRINT statement with a semicolon
so that each letter is printed on the same line with no
intervening spaces.

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

12.4 EXTRACTING SUBSTRINGS-Solutions


for "Your Turn"
1.

1111 REM N$--NAME

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

12.5 OTHER FUNCTIONS


Several other string-handling functions are available in most versions
of BASIC. Although the disparities are not as great as in the extraction
of substrings , some of the ones shown below may need an alterna-
tive. Refer to your manual if the following functions cannot be used on
your computer system.

I. LEN

LEN(N$) LEN("MAUREEN")
t
String variable String
i

This function counts the number of characters in a string. RUN the


following program using your first name as data, to produce the
number of characters in your name.

10 READ N$ - Reads your name.


20 DATA MAUREEN - Supplies the READ statement with your first name.
30 LET L=LEN(N$) - Counts the number of characters in your name and stores the
result in a numeric variable.
40 PRINT - Leaves a blank line.
50 PRINT L - Prints the number of characters.
99 END - Terminates program execution .

RUN
7

II. VAL

VAL(S$) VAL ( "2468 I )

i
String variable
l'
String of digits

The VAL function converts a string that consists of digits to its


numeric value. For example, the string "2468" is converted to 2468.
If the string contains a non-numeric character, the computer converts
only those digits to the left of the character or gives an error message.
Some computers use NUM instead of VAL .

10 LET S$=12468" - AssignsastringofdigitstoS$ .


STRIN GS 609

20 LET N=VAL(S$) - Converts the string to its numeric value.


3111 PRINT - Leaves a blank line.
4111 PRINT N - Prints the numeric value.
99 END - Terminates program execution.

RUN

2468

Depending on your computer system , a space mayor may not be left


before the printed number .

III. STR$

STR$(N) STR$(2468)
i
Numeric variable
i
Numeric value

STR$ is the opposite to VAL. It converts a number to its string


equivalent.

10 LET N=2468 -Assigns a number to N .


20 LET S$=STR$(N) - Converts the number to a string.
30 PRINT - Leaves a blank line .
40 PRINT S$ - Prints the string.
99 END - Terminates program execution.

RUN

2468

Computers that leave a space before a positive number will leave a


space before its string equivalent. This is because the computer
takes the space for the assumed plus sign into consideration when
the n umber is converted to its stri ng. Thus , the space becomes part of
the string. When the LEN function is applied to the string stored in S$
(tb2468), the computer will return a length of 5.
The last two functions may be confusing. The following will help
you remember what each one does .
(a) VAL resembles value - it changes its argument to a numeric
value.
(b) STR$ resembles string-it changes its argument to a string .
610 PRO GRAMMIN G IN BASIC

IV. CHR$

CHR$(C) CHR$(65)
i
Numeric variable
r
Numeric value

This function converts a number to its AS C II character equivalent. The


number must be an ASCII code, otherwise the result will likely be an
error message. If the code represents a system command, no char-
acter is displayed . For example , the number 13 is the decimal nota-
tion for a carriage return. Nothing is displayed when 13 is converted to
its ASC II character .

HI LET C=65 - Assigns an ASCII code (in decimal notation) to C.


2~ LET C$=CHR$(C) - Converts the number to its ASCII character equivalent.
3~ PRINT - Leaves a blank line.
4~ PRINT C,C$ - Prints the code and its ASCII character.
99 END - Terminates program execution.

RUN

65 A

V.ASC

ASC(C$) ASC( "A") ASC(A)


i
String variable
i
String
i
Character

ASC is the opposite to CHR$. It converts a single character to its ASCII


code . If the argument consists of a series of characters, onl y the first
character of the string is converted. Some systems do not accept a
string variable as the argument of the ASC function. Instead , a single
character (without quotes around it) is required.

1~ LET C$="A 1 - Assigns the character A to C$.


20 LET C=ASC(C$) - Converts A to its ASCII code equivalent.
30 PRINT - Leaves a blank line.
40 PRINT C$,C - Prints the character A and its ASCII code .
99 END - Terminates program execution .
STRINGS 611

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$ .

121 DIM W$(5) - Reserves storage locations


for five words.
20 PRINT - Leaves a blank line.
30 FOR 1=1 TO 5 - Sets up a loop.
40 F:EAD W$ ( I) - Reads the words from the
DATA statement one at a time
and stores each word as an
element of array W$.
50 DATA VARIABLE,FUNCTION,SUBSCRIPTED, - Supplies the READ statement
ARRAY,SUBROUTINE with the words.
60 LET L=LEN(W$(I») - Determines the length of each
word and stores the length
in a numeric variable.
70 PRINT W$(I);TAB(20);L - Prints the word and its length.
80 NEXT I - Transfers control back to
line 30.
99 EN[I - Terminates program execution.

RUN

VARIABLE 8
FUNCTION 8
SUBSCRIPTED 11
ARRAY 5
SUBROUTINE 10

12.5 OTHER FUNCTIONS- Your Turn


1. What is the output of each of the following programs?
612 PROGRAMMING IN BASIC

(a) 10 LET A$="NUMBERS AND STRINGS" (d) 10 READ A


20 LET L=LEN(AS) 20 DATA 67
30 PRINT 30 PRINT
40 PRINT L 40 PRHH A,CHR$(A)
99 END 99 END

(b) 10 LET AS="5789" (e) HI READ A$


20 PRINT 20 DATA T
30 PRINT VAL< A$) 30 PRINT
40 PRINT A$ 40 PRINT A$,ASC(A$)
99 END 99 END

(c) 10 LET A=3456


20 PRINT
30 PRINT STR$(A)
40 PRINT A
99 END

2. Write a program that converts each of the strings "24" and "25"
to its numeric value, then adds the two numbers.

(a) Use the READ/DATA statements to read the two strings.


(b) Use three PRINT statements in addition to the one that leaves
a blank line:
(i) The first one prints the strings.
(ii) The second one prints the numbers.
(iii) The third one prints the sum.

RUN

24 25
24 25
49

3 . Write a program that converts the decimal numbers 65 through


90 to their AS C II character equivalents.

(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

4. Write a program that converts each character of the string SEA


FLOOR SPREADING to its ASCII code equivalent as follows. 11
(a) Assign the string to a string variable.
(b) Set up a FOR/NEXT loop whose FOR statement has an initial
value of one and a test value that is equal to the number of
characters in the string (use the LEN function).
(c) Extract each character of the string one at a time by means of
the MID$ function . Assign the character to a string variable.
See Problem 4 on page 604 if you need help with the
arguments of the MID$ function.
(d) Convert each character to its ASCII code by means of the ASC
function and assign the code to a numeric variable.
(e) Print the character and its ASCII code on one line widely
spaced.

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

12.5 OTHER FUNCTIONS-Solutions for "Your


Turn"12
1.

(a) RUN (c) RUN

19 3456
3456

(b) RUN (d) RUN

5789 67 C
5789

12 . Th e spaci ng in you r o utput may differ fro m th e ones shown .


STRINGS 615

(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 .

Questions and Exercises


1. Explain how a string variable is coded.
2. Write three programs that print your name and the current date .
Each program prints the items on one line closely spaced and
each program enters the data in a different way. The first program
uses the INPUT statement (without a prompt) , the second pro-
gram uses the RE ADIDATA statements, and the third program
uses LET statements. The date consists of two strings : (a) the
month and the day of the month, and (b) the day of the week . An
example is shown below.

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

third string variable . Show your response to the INPUT statement.


Below is a sample line of output.

JOHN SMITH JUNE 21 WEDNESDAY

3. (a) Explain how a character (digit, letter of the alphabet, or other


symbol) is stored in a computer.
(b) State the reason for this method of storage.
4. (a) What do the letters ASCII represent?
(b) What is an ASCII code? Define base two (binary), base ten
(decimal), base eight (octal), and base sixteen (hexade-
cimal) representations of numbers.
(c) What is the hierarchical order of the ASCII codes listed on
page 586?
5. State whether the following relational expressions are true. or
false. Write the ASCII code beneath each character until you find a
difference in the two strings. Refer to page 586 for the ASCII
codes.

(a) GRAHAM< GRAHAME (c) THOMPSON > = THOMSON

(b) FRANCIS <> FRANCES (d) HUTCHESON<= HUTCHISON

6. What is wrong with each of the following programs? Make the


necessary corrections. Several items printed on one output line
must be separated by one or more spaces. 14

(a) 10 PRINT
20 PRINT "NUMBER,STREET";
30 INPUT N,S
40 PRINT N;S
99 END

RUN

NUMBER, STREET? 123,MAIN STREET


(b) 10 LET N=123
LET S$=MAIN STREET
21:'1
30 PRINT
40 PRINT N,S$
99 END

(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

3111 READ 1,.1$


40 DATA NUMBER,SEVEN,IS,THE,WINNER
50 PRINT W$;
60 NEXT I
99 END
(d) 10 PRINT
2111 LET A$="789 1
3111 LET B=789
40 IF A$=B THEN 70
5111 PRINT A$;"IS NOT EQUAL TO";B
60 GO TO 99
7111 PRINT A$;"IS EQUAL TO";B
99 END
(e) 10 PRINT
20 FOR 1=1 TO 2
3111 READ A$,B
4111 DATA STEVEN,4598,MICHAEL,2485
5111 PRINT A$,B$
60 NEXT I
99 END

(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

7. What is the output of each of the following programs?

(a) lIe'l PRINT (e) 10 LET S$="STRING HANDLING"


2111 LET A$="MICRO" 20 LET L=LEN(S$)
3111 LET B$="MINI" 30 PRINT
4111 IF A$>=B$ THEN 70 4~ PRINT L
50 PRINT A$,B$ 99 END
6111 GO TO 99
7111 PRINT B$,A$
99 END

(b) 10 PRINT (f) 10 LET S$=15432"


2111 LET C$="COMPUTER" 2111 PRINT
30 FOR 1=1 TO LEN(C$) 30 PRINT S$
40 LET L$=MID$(C$,I,l) 40 PRINT VAL< S$)
50 PRINT L $; ,1
1 •
99 END
60 NEXT I
99 END

(c) 1111 READ A (g) 1111 LET Z$="Z"


20 IIATA 9753 2111 LET C=ASC(Z$)
3111 PRINT 30 PRINT
4111 PRINT A 4111 PRINT Z$,C
5111 PRINT STR$(A) 99 ENII
99 END

(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 .

(a) Use two FOR/NEXT loops :


(i) One loop controls the entering of data.
(ii) The other controls the isolating and printing of each letter.
620 PROGRAMMING IN BASIC

(b) Use the READIDATA statements to enter the data.


(c) To print a name in reverse order:
(i) Use the LEN function as the initial value of the inner loop
to set the index first to the number of characters in a
word, then work backwards to 1 (the STEP value should
be - 1). This means that you will be working from the last
letter in a word to the first letter.
(ii) Use the MID$ function to isolate each letter. Assign the
isolated letter to a string variable.
(iii) Print the value of the string variable.

RUN

REMMARGORF'
CISAB
RETUF'MOC

2. The program in Problem 1 prints one letter at a time in reverse


order. It IS possible to accumulate the letters by concatenation
much like you accumulate a sum of numbers. Replace the
statement that isolates each letter by a statement that performs
the following:
(a) Isolates each letter of the word by means of the MID$ func-
tion.
(b) Concatenates this isolated letter to the string variable that
accumulates the letters.
(c) Stores the result in the same string variable (similar to xx
LET S=S+N when adding numbers).
Don't forget to set the string variable that accumulates the
letters to the null string. Do this between the two FOR statements
so that the string variable is nullified before each word is
reversed. Should you need some help, refer to page 592, where
a similar program illustrates how to set a string variable to the null
string and how to accumulate the letters.
If you are using a computer that requires the STR function to
concatenate strings, set the string variable that accumulates the
letters to blank. Use the following statement to concatenate the
letters instead of a statement that uses the MID$ function.

...,,-,,
""

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

the word OF , a space before IS , and a space after IS in yo ur PRINT


statement.

RUN

THE REVERSE OF PROGRAMMER IS REMMARGORP


THE REVERSE OF BASIC IS CISAB
THE REVERSE OF COMPUTER IS RETUPMOC

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

JANUARY FEBRUARY MARCH APRIL


MAY JUNE JULY AUGUST
SEPTEMBER OCTOBER NOVEMBER DECEMBER

4 . The program for Problem 6 in Chapter Four (Page 146) deter-


mined the largest sale made by a salesperson . Something similar
can be done with strings . Write a program that finds which of the
three words PROGRAMMER, BASIC, or COMPUTER contains
the greatest number of letters .
(a) Use a FOR/NE XT loop to control input.
(b) Use the READIDATA statements to enter the data .
(c) Assign a low value (say L= -1) to a numeric variable outside
your loop.
(d) Use the LEN function in an IFfTHEN statement to compare the
number of characters in a word with the current value of L.
(i) If the number of characters is greater than the current
value of L, replace L by the LENgth of the word just read .
Save this word (which is currently the longest) in another
string variab le , say L$ .
(ii) If the number of characters is not greater, go on to the
next word .
(e) Print the data and the longest word as shown below . (Hint:
Notice the space after IS: in the output. This space should be
coded in your PRINT statement.)

RUN

PROGRAMMER
BASIC
COMPUTER

THE LONGEST WORD IS: PROGRAMMER


STRINGS 62

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

5. In Chapter Seven, a program was listed that sorted numbers in


ascending order. Write a similar program , this time sorting the
names Nancy , James, Tracy , Ale xander , Gayle , and Edward
alphabetically.
(a) Use a separate FOR/ NE XT loop to read the names into a one-
dimensional array , say N$ . Sort the names in a subroutine
that is called immediately after all the names have been read .
Perform the printing of the names in its own loop in the main
program after control RETURNS from the subroutine.
(b) To sort the names, use two FOR /NE XT loops:
(i) The outer loop controls the sorting of the six names.
(ii) The inner loop sorts two adjacent names. Set its test
value one number less than the number of names, since
you will be comparing the name stored in J with the one
stored in J+1 . If the two names are in order, no exchange
is made; if they are not in order, the names must be
interchanged. To perform this, you must place the first
name of a pair in temporary storage, the second name of
the pair in the current variable (N$(J)), and the name that
is in temporary storage in the next variable (N$(J+1)).

~.: }: 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.

Suppose J = 1. This is what happens with the first pair of


names.

T N$(1 ) N$(2)

Nancy James -Initial storage .


Nancy ( Nancy James - Places the first name of the pair in temporary storage.
Nancy James ( James - Places the second name of the pair in the first variable.
Nancy James Nancy - Places the name that is in temporary storage in the
I l' second variable.

The first pair of names is now in alphabetical order.


(c) Refer to the sorting program in Chapter Seven, page 290, if
you need some help.

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

7. It is possible to align the decima l points of numbers by using the


TAB function along with several of the functions learned in th is
chapter . Align the numbers 9.67 , 3125.49 , .26, 85.17, 123.45,
14.21. The procedure is as follows :
(a) Set up an outer loop to control the reading of the numbers .
Convert each number to a string immediately after the num-
ber is read in .
STRINGS 625

(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

8. Write a program that decodes the following ASCII codes (in


decimal notation) into their ASCII character equivalents. Use the
READ/DATA statements to enter the numbers.

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.

RUN (Sample RUN)16

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 .

RUN (Sample RUN)

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

F FOR/ NEXT loop, 196 MAT statemen ts, 382


Field speci fication , 486 va riation s, 207 comparison with FOR/ NEXT
using PRINT USING Input device, 6 loop, 384
statement , 463 ,468-470 keyboard, 6 DIM statement, 384
Fl ag , 149,163 Inpu tlout puttermin al, 6 functions, 383
Fl oating -point , 35 INPUT statement, 66 MAT CON, 390
Fl owchart, 20 rules for , 71 MAT ION , 39 1
definition, 20 Inst ruction register, 5 MAT INPUT, 385
rules for, 21 Instructions, 20 MAT INV, 394
symbols, 20, 62 , 86, 93, 95 , 23 1 , executable statement, 20 MAT PRINT, 384,387
261 executing (processing), 14,20 MAT READ , 384
template, 22 non -executable statement , 20 MAT TRN, 393
FNEND statement, 533 Integer, 35, 124 MAT ZER , 390
Format-free output, 444 Integrate d Ci rcuit (IC), 3 redimensioning arrays, 395
FOR/ NEXT loop, 195 Interactive programming, 8 Mauchly, John , 2
assigning location numbers Interface chip, 6 Memory , clea ring computer 's, 13
in arrays, 252 Interfacing , 6 microcomputer mem ory , 5
com parison with MAT parallel, 6 bit, 5
stateme nt, 384 seria l, 6 byte, 5
nested loops, 222, 224 ~terp reter , 7 Random Access Memory (RAM ), 5
rules for, 198 INT function, 400 Read Only Memory (ROM), 5
tru ncation , 208,216 arg ument of, 401 Microcomputer , 4
formul a to calculate number of checking division, 404 history, 4
execu tion s, 198,2 15, 225 isolating digits , 402 internal st ructure, 5
index, 196 rounding off numbers, 405 memory, 5
FOR statement , 196 Isolating digits, 402 Microcomputer-on-a-chip, 6
FORTRAN , 8 INT functi on, 402 Microcomputer system , architecture
Function definition , 526 of, 4
argument of, 526 K Micropro cesso r, 4
USER -D EFINED function , name Kemeny, John, 9 ch ip, 5
of , 526 Kurtz, Thomas, 9 registers, 5
Fun ction refere nce, 527 unit, 5
argument of, 527 L MID$ function, 598
USER-DEFINED function, 527 Large-Scale Integrated circuit (LSI), 3, Multilin e user-defined func tion , 533
4 DEF state ment, 533
G LEFT$ function , 598 Multiple-assignment stateme nt, 57
Ge nerations of computers, 3 LEN function , 608 Multiple branching , 165
GOSUB statement , 509,516 LET statem ent, 54
GO TO statement, 107-108 Library functions, 508 N
definition, 400 Nested loops , 222
H list of, 420 pun ctuation , 228
HARVARD MARK I, 2 Line number, rul es for BASI C rules for , 224
He xadecimal notation, 585 program, 19 Neumann , John von, 2
HE X function, 586 LIST com mand, 13 NEW command, 13
Hierarchy of operations, 35 Loop , 108 , 136 NEXT statement, 196
High-leve l langu age, 7 methods of controlling, 114 Numbers, printing , 42
HOME command , 14 terminating, 150, 154
trailer val ue , 150 o
Object program , 7
IFrr HEN statement, 114 M Octal notation, 585
IMAGE statement , 462, 464 Machine langu age, 7 OK message , 15
Index, 196 Mainframe, 6 One-dimensional array, 251
FOR/N EXT loo p , 196 Mass storage , 6 DATA state ment, 257
ON ... GO TO statemen t, 123 Mat rix, 313,3 15,382 DIM stateme nt, 254
Information, storage of, 585 addition, 39 1 subscripted va ri ab le , 252
Initialization , 55, 130 ass ignment, 390 ON . .. GOSUBstateme nt , 516
RNDfunc tion , 412 multiplica tion , 392 ON ... GO TO statement , 123
Initial value, 196 scalar , 383 Operators, 35
different than on e, 209 subtraction, 392 relational, 115
INDEX 633

Output devices, 6 argument of, 412 Summation, 170,278, 354


printers, 6 conversion formula, 415 Symbolic language , 7
video monitors, 6 inillalization , 412 System commands, 12
RUBOUT key , 14
p RUN command, 14
Parallel interfacing, 6 T
Parentheses, 35 TAB function. 444
subscript with arrays, 252 S argument of , 444,447,448
PAUSE key, 15 Scientific notation, 42,471 centring headings, 448
Peripheral, 5,6 SCRATCH command , 13 Template, 22
PUI, 8 Screen, clearing of, 14 Terminate execution, 15
PRINT statement, 24 Serial interfacing, 6 Test value,
blank lines, 24,68, 127, 227, 268 SGN function, 421 FOR/NEXT loop, 196
comma spacing, 27 S key, 15 variations, 207
expressions, 25, 37, 57 Software, 4 Time-sharing environment, 8, 12,66
pu nctuation at end, 30, 69, 217, Solid state computer, 3 Time-sharing system, 8
226,228,337 Sorting program. 290 Trailer value, 149,163
semicolon spacing, 28 Source program, 7 Transistor , 3
strings, 24 Special value, 155 Truncation, 124
PRINT USING statement, SOR function, 400 . 421 FOR/ NEXT loop, 208,216
centring headings , 464 Statement, 18 ON .. . GO TO statement, 124
field specification, 463 , 468-470 executable, 20,509 Two-dimensional array , 315
scientific notation , 471 GOSUB, 509 , 516 DATA statement , 325,326
with IMAGE statements, 462 non-executable. 20, 136 DIM statement, 323
with string variable, 473,484 parentheses with , 35
Problem-oriented language, 7 REM, 509 U
Program, 4,6 rules for BASIC program, 18 Unconditional branch, 108, 123
assembler, 7 STEP clause, 196 UNIVAC I, 3
counter, 5 variations, 214 USER-DEFINED function, 525
displaying on screen, 13 Step value, FOR/NEXT loop, 196 DEF statement, 525,533
edit, 14 STOP key, computer, 13, 15 FNEND statement, 533
object, 7 STOP statement, 14, 509, 515 function definition, 526
sorting, 290 Storage, 6 function reference, 527
source, 7 information, 585 multiline, 533
stored, 3 mass, 6 name of, 526
terminating, 15 Stored program , 3 Single line, 525
Programming, 7 Storing data in arrays, 251 User 's K, 6
Prompt, a, 69,71 , 151 STR function, 591 , 598
Strings, 13,53,574 V
R comparing, 587 Vacuum tube, 2
Random Access Memory (RAM), 5 defined, 24 VAL function , 608
RANDOM IZE statement, 414 entering into the computer, 574 Variable, 13
Random numbers, 412 nUll, 13 as initial value, 209
Random seed, 412,414 PRINT statement, 24 as step value, 214
Read Only Memory (ROM), 5 String variable, 573 as test value, 209
READ statement, 79 PRINT USING statement, 473,484 defined, 53
rules for, 80 STR$ function, 609 initialization, 55
READY message, 15 Subprogram, 508 LET statement, 55
Redimensioning arrays, 395 Subroutine, 508 numeric, 53
Registers, microprocessors, 5 with arrays, 513 non-initialized, 55
Relational operators, 115 Subscript, with arrays, 252 omission, 201
with strings, 587 Subscripted variable, 252 READIDATA statements, 79
REM statement, 509 one-dimensional array, 252 representing array name , 254
rules for BASIC program, 17-19 two-dimensional array, 315 Vector, 252
RESTORE statement, 89 SUBSTR function , 598 Very Large-Scale Integration (VLSI), 4
RETURN key, 13, 27 Substring, 597
RETURN statement, 509,516 definition , 597 W
RIGHT$ function, 598 extraction of function method, 597 Wage program , 95, 176, 233
RND function , 412 extraction of subscript method, 597 formula for, 536
,
/'
1~ ~ ~~~_ ~. -
, , .. ~

~__ c: ~,-• • - -- • ~.
. .-::
_ , .-
••

_ _• I -~~_
,"
-4111

~.~ ~

You might also like