Boillot Michel - Understanding FORTRAN
Boillot Michel - Understanding FORTRAN
USED
Understanding
FORTRAN
Second Edition
2 / Jj£a.-*W-^i J1
l,y.^J v^ir S' (r^fcCU^^
'T
6 :>
- fn/
6/
rM
0'
ot^^'
4*.
Understanding
FORTRAN
Second Edition
Michel Boillot
Pensacola Junior College
Boillot. Michel H.
Understanding LORTRAN.
Includes index.
1. FORTRAN (Computer program language)
I. Title.
OA76.73.L25B64 1981 001.64'24 80-29507
ISBN 0-8299-0355-0
2nd Reprint— 1981
CONTENTS
CONTENTS
Accumulation
DO loops and the CONTINUE statement
Flowcharting the DO statement
Random numbers
Implied DO
Graphing
9 FUNCTIONS 362
FORTRAN supplied functions
User written functions
FORTRAN statements FUNCTION, RETURN
Statement functions
10 SUBROUTINES 401
FORTRAN statements CALL, SUBROUTINE, RETURN, COMMON,
EQUIVALENCE
Flowchart symbols for subroutines
Variable DIMENSIONS
Named COMMON
CONTENTS
Unformatted READ/WRITE
FORTRAN statements END FILE, REWIND, BACKSPACE,
DEFINE FILE
Direct access files
Direct access READ and WRITE
File flowchart symbols
Index 499
Digitized by the Internet Archive
in 2010
http://www.archive.org/details/understandingforOOboil
PREFACE
TO THE
SECOND
EDITION
changed for better student understanding. Chapter 9 also includes sections on BLOCK
DATA, multiple ENTRY and multiple RETURN. Finally, Chapter II has been
rewritten to present a stronger case for structured programming with actual FORTRAN
code, using the IF THEN ELSE construct.
Acknowledgments
I have come to realize that no successful textbook can be produced without the
assistance and better judgment of colleagues and reviewers. am greatly indebted to
I
Wayne Horn of Pensacola Junior College, without whose assistance this book would
never have materialized. am also indebted to Carol Shingles for her superb reviews
I
and many suggestions, including problems and explanations, the results of an obvious
deep concern for students and how they learn. would also like to thank Betty Whitten
I
of the University of Georgia, Don Bishko of the State University of New York at
Albany, Arnold McEntire of Appalachian State University, and Edward Suppiger,
Professor Emeritus, Princeton University, John Elwin of San Diego State University,
Bruce Palmer of South Dakota School of Mines and Technology, and Nell B. Dale, of
the University of Texas at Austin for their helpful comments and constructive criticisms.
My thanks also go to Lea Fuller and Nancy Dale for their critical editing and
proofreading of the book. Additionally wish to thank Gary Woodruff, West's College
I
Department Editor, for his advice and encouragement during the writing process.
Finally must thank Mona, Marc and Laura for their understanding and patience.
I
M. Boillot
PREFACE
TO THE
FIRST
EDITION
This text represents a unique approach to teaching and learning FORTRAN. All chapters
are divided into five or six sections, each with a specific purpose. In the first section, a
completely defined problem is presented with a programmed solution and flowchart. The
display of the complete program before any discussion of the material to be covered in the
chapter is to stimulate the reader's curiosity by confronting him with a "conceptual
whole." The reader may capture the essence of the program without much difficulty. This
complete program illustration serves to introduce the new language features and syntax to
be discussed in the chapter. The reader is warned not to spend too much time on this in-
troductory programming example, since subsequent sections will clarify the program; de-
tails, at this point, are unimportant.
The second section contains explanations of the new features, syntax and program-
ming techniques. Numerous short, illustrative examples are included to show both correct
and incorrect coding, usage of programming techniques, and so on.
The third section, entitled "You might want to know," is in question-and-answer for-
mat. It attempts to anticipate commonly asked questions and provides informally phrased
answers. This section represents a compilation of predictable pitfalls for novice program-
mers.
The fourth section displays two or three "worked-out problems" which apply the lan-
guage features and programmed techniques covered in the preceding sections. These prob-
lems are taken from a variety of disciplines reflecting both scientific and business areas of
applicability. The reader at this stage should be able to comprehend all program details
and may wish to refer back to the program example of the first section for further study.
xi
xii PREFACE TO THE FIRST EDITION
Many chapters feature an optional fifth section containing material deemed desirable
for the sake of a complete presentation of the FORTRAN language, but not necessarily
essential to all students. Each instructor may elect to cover or omit these optional sections.
All chapters conclude with a section containing exercises and programming prob-
lems. The first part of the sixth section, entitled "Self test," enables the reader to test his
understanding of the material covered in the chapter. Answers to the self test are provided
at the end of each chapter for immediate feedback. The second part of the sixth section
contains an extensive collection of problems ranging over a wide variety of subject matter
areas and levels of difficulty. Problems are generally presented in graduated order of dif-
ficulty. The
instructor or reader should be able to find problems impacting his own area of
There are "fun" problems often dealing with the simulation of a processor an en-
interest.
vironment (a random number generator function is supplied in Chapter 8 for use in these
problems), "total" problems requiring the student to design a complete system, and. of
course, traditional-type problems. Some instructors may wish to select some of these prob-
lems to present as the firstprogramming example of the chapter instead of using the one
given in the first section. In any event, the abundance of problems in the sixth section will
allow the instructor to give his students different problems semester after semester.
Other features, in addition to the overall organization of the text, are as follows. In-
itial discussions of input/output are placed in separate chapters. This enables the student
to concentrate on each topic separately rather than having to master both simultaneously.
This approach has been used successfully at Pensacola Junior College as well as at other
institutions. Chapter 6 centrali/es all information on alphabetic data, number and data
represention. double precision, logical and complex data. To many, the presentation of
this material in Chapter 6 may seem too premature, or even totally unnecessary. For some
classes. Chapter 6, excepting the section on alphabetic data, should be optional. Omitting
Chapter 6 does not break the logical continuity between Chapters 5 and 7. The instructor
may always cover this chapter at a time he deems propitious. Structured programming is
included in an independent chapter. There is a great deal of interest at present in the con-
cepts and techniques of structured programming, and, while not every class will cover this
topic, the author feels that most readers will profit from a brief exposure to these ideas.
Many people have attempted to "debug" this book, but inevitably some errors will
remain. The author would appreciate any correspondence with users regarding errors or
suggestions dealing with the improvement of this book.
Understanding
FORTRAN
Second Edition
1
COMPUTERS
AND
COMPUTING
on government, science, and the arts in the years since the first fledgling computer was in-
vented in the mid- 1940s. Today, computers are being applied to every conceivable prob-
lem. One has only to pick up any popular magazine to read about newer, larger, and more
complex problems being solved by them. The computer has become an indispensable tool
in all scientific and commercial endeavors.
jectory computations.
2. The memory unit stores information. It holds the program necessary to solve a problem
and any data that will be processed by the program. The memory is divided into loca-
tions (cells), each of which has an address. Instructions and data are stored in these
cells.
3. The control unit fetches the instructions and data from memory and executes instruc-
tions one at a time with the assistance of the input, output, or arithmetic/logical unit.
All the other components operate as directed by the control unit.
4. The arithmetic /logical unit consists of the electronic circuitry, which performs
arithmetic operations such as addition, multiplication, subtraction, and division, and
logical operations, such as comparison of numbers.
5. The output unit can transfer (copy) the contents of certain memory locations onto some
external medium such as punched cards, punched paper tape, magnetic tape, a printed
page produced by a teletype or line printer, or a cathode ray tube (CRT) screen for vis-
ual display.
'
Data are the information (raw facts) to be processed by a program. For example, if a program is designed to
sort names into alphabetical order, then the names to be sorted would be the data for that program.
COMPUTERS AND COMPUTING 3
(CPU)
INPUT
COMPUTERS AND COMPUTING
A = P +X
-In memory, the machine language instruction would be represented in binary (Ts and O's).
COMPUTERS AND COMPUTING
In practice, the high-level language programmer never need worry about machine ad-
dresses or operation codes. The FORTRAN programming system takes care of all such
details, allowing the programmer to focus attention on the logic of the problem.
capable of executing 100 to 200 million instructions per second; that is, one instruction
takes 5 to 10 nanoseconds to execute.
2. I cannot conceive of how fast a nanosecond is. Can you help me?
words, there are approximately billion seconds in 32 years. One nanosecond is the ap-
1
Answer: Electrical signals are propagated at speeds approaching the speed of light (1
foot/nanosecond). Integrated circuits packing many thousands of transistors per
square inch have been designed to minimize the length of interconnections through
which electrical signals are propagated, thereby reducing the time it takes a signal to
travel from one transistor to another in that circuit. Figures 1-2 and 1-3 illustrate the
Mcmof>
(PROM)
(S. 192 Bill)
(KAM)
Internal
Internal clock
loj.c
Figure 1-2 Magnified view of the Intel 8748 single Figure 1-3 Functional map of the 8748 mi-
chip microcomputer (courtesy Intel Corporation). crocomputer (actual size: 5.6 X 6.6 milli-
meters).
COMPUTERS AND COMPUTING
4. Computers may be very fast and powerful devices, but aren't there problems that even
the fastest and largest of them cannot handle?
Answer: Yes. If a computer a billion times faster than the fastest computer available to-
day were to analyze all possible outcomes of a chess game, it would require on the or-
der of 10'"" hours (many billions of years) to make the first move in the game.
6. What computer languages are there other than machine language and FORTRAN?
Answer: .One survey reported over 600 computer languages in more or less widespread
use. Many of them were special-purpose languages oriented to a single application.
Some of the better-known languages are
8. Is there any way I could possibly "hook up" my brain to a computer to assist me in my
studies and intellectual pursuits?
Answer: Perhaps someday this will be possible. Dr. Adam V. Reed, a neurologist, com-
puter engineer, and mathematical psychologist at Rockefeller University, predicts that
within a few years it will be possible to implant a minuscule computer into people's
heads. This operation will allow people to store an almost infinite amount of data with
near-instant recall capability. It will sharpen their mental processes, giving them the
speed and accuracy of a computer.
COMPUTERS AND COMPUTING
\
COMPUTERS AND COMPUTING
1. Input. Read a value from the input medium and store that value in a specified memory
location. For example, the instruction
READ X
will cause one value on the input medium to be read and stored in a memory location
called X.
2. Output. Copy a value from a memory location onto the output medium. For example,
the instruction
WRITE X
will cause the contents of X to be written out on the output pad.
3. Calculations. Perform calculations in coordination with the arithmetic unit and place
results in desired memory locations. For example, the instruction
Y = X*2 + 1
will cause the control unit to fetch the value contained in memory location X and ac-
tivate the arithmetic unit to multiply that value by 2, and then add 1 to the result. The
final result is then stored in memory location Y.
4. Unconditional branching. Take the next instruction from a specified memory location.
For example, the instruction
GO TO 3
causes the control unit to fetch the next instruction from location 3 rather than from
the next sequentially numbered location. Unconditional branching, then, simply means
transfer directly to a particular instruction in memory.
met. If the condition is not met, no transfer occurs and the following instruction is
taken from the next memory location. For example, the instruction
IFX< 4 GO TO 60
causes the control unit to first fetch the value X from memory and then request the
logical unit to compare that value with 4. If the logical unit reports that the value of X
is less than 4, the control unit fetches the next instruction from location 60. If the value
of X is greater than or equal to 4, the next instruction is taken from the next sequential-
ly numbered location. Hence a conditional transfer allows a program to process a par-
ticular instruction(s) if a certain condition is met, or process different instruction(s) if
6. Termination. Cease execution of instructions for this program and wait for a new pro-
gram to be loaded into memory. For example, the instruction
STOP
causes the program to terminate. No more instructions in this program are executed.
To illustrate the concepts just discussed, let us write a short program to calculate and
write out an amount of pay owed to an employee who is paid $2 an hour with time and a
COMPUTERS AND COMPUTING
half pay for all hours inexcess of 40. The number of hours worked is punched on a time
card. The complete set of instructions to solve this problem might be as follows:
GO TO 6 pay.
$3 per hour.
6 WRITE PAY , HRS Print pay and numbers of hours.
7 STOP Stop.
Suppose this program has been loaded in memory as shown in Figure 1-5. After ex-
ecution of the instruction at location 1, the value read from the input unit (38, in this ex-
ample) is placed in location HRS (see Figure 1-6). The computing system will have auto-
matically reserved a location for HRS. In the second instruction, the logic unit will de-
termine that the contents of location HRS are not greater than 40; hence, the next instruc-
tion to be executed comes from location 3. After the instruction in 3 is executed, the con-
tents of location PAY become 2*38 = 76. The instruction at location 4 causes the control
READ HRS
10 COMPUTERS AND COMPUTING
unit to takes its next instruction from location 6. The instruction at location 6 will cause
the contents of locations HRS and PAY to be copied onto the output medium. The in-
struction at location 7 causes the control unit to stop and wait for the next program. The
status of the model computer after execution of this program is shown in Figure 1 -6.
READ HRS
COMPUTERS AND COMPUTING 11
Figure 1-8 DEC System- 10 Central Processing Unit (courtesy Digital Equipment Corporation).
12 COMPUTERS AND COMPUTING
The hardware used for input and output devices also varies greatly from one system
to another. Some devices such as the line printer (see Figure 1-9), cardpunch, and the
graph plotter (see Figure 1-10) can be used as output devices only. Other devices such as
the punched-card reader (see Figure 1-11) can be used as input devices only. Still others
can be used both for input and output purposes, although generally not simultaneously.
Such devices include the Teletype (see Figure 1-12), the punched-paper tape
reader/punch, the CRT (cathode ray tube) console (see Figure 1-13), the magnetic disk,
the magnetic drum, and magnetic tape. The last three are sometimes referred to as mass
storage devices because they are capable of storing large quantities of data and can be ac-
cessed by the CPU very rapidly.
The input/output devices for a particular system can be located physically close to the
CPU or at some distance —
in an adjacent room or miles away. If they are located miles
away, data can be transmitted to the CPU via telephone lines. This technique is called lele-
communication. The user can dial the computer's number to initiate communication, iden-
tify himself or herself, transmit a program and/or data, and receive results at his or her
terminal. When finished, the user can release the telephone line for other use.
A typical computing system will generally include a great variety of input/output de-
vices. Most of these devices are electromechanical and thus operate at far slower speeds
than CPU internal processing speeds where processing is wholly electronic. Therefore, if
the CPU is required to wait for such devices to perform a complete operation (a data
transmission from a Teletype, for example), the advantage of the tremendous internal
speeds of the CPU is greatly reduced. In most computer installations the CPU is equipped
with one or more channels. A channel is a special-purpose device which controls
input/output operations; it relieves the CPU of the task of communicating directly with
input/output devices. The CPU, for example, will instruct a channel to perform an output
operation (such as writing out results on a printer), and while the channel is busy servicing
this output request the CPU can continue processing instructions. In this way CPU com-
putations are carried out concurrently with I/O operations, which increases the efficiency
of the computer system.
Computers can be used in many different types of operating environments, each re-
flecting different organizational needs, hardware configurations, and economic bases. Of
special interest multiprogramming and time-sharing environments. In a multi-
are
programming setting several programs are present in memory at one time. While a chan-
nel is servicing an I/O request for a particular program, the CPU can start processing a
new program or resume processing a program temporarily interrupted by a previous I/O
request, or each program can be interrupted sequentially to allow execution of other pro-
grams in memory. In a time-sharing environment, numerous terminals (Teletypes, CRTs,
etc.) are attached to the CPU by ground cables or telephone lines. These terminals allow
users to communicate directly {online) with the computer. Users enter their programs
directly into the system at the terminal rather than submitting the program in punched
card form. To the user at the terminal it appears that he or she has the computer all to him
or herself and that only his or her program is being executed by the CPU. In reality, the
CPU may be servicing several other users concurrently. This is accomplished by allowing
each user a small slice of time and by processing each user's program in turn. Thus while
one user is typing FORTRAN instructions on a Teletype the CPU may be processing an-
other user's program. The most significant advantage of time sharing is that the user has
immediate access to the computer; feedback is instantaneous. In addition, computer utili-
Figure 1-9 A line printer (courtesy IBM) Figure 1-10 A plotter (courtesy Hewlett-
Packard Company).
Figure 1-12 Teletype terminal (courtesy Figure 1-13A CRT console (courtesy
Teletype Corporation). Hewlett-Packard Company).
14 COMPUTERS AND COMPUTING
1-5-2 Software
The term software is generally used to describe the set of programs, written by the pro-
grammer, that causes the computer hardware to function. There are three basic software
categories:
1. Translation programs.
2. Print messages for the operator and the programmer regarding the status of the pro-
gram.
3. Perform job accounting by keeping track of who uses the computer and for how long.
5. Handle the collection of data from telecommunication lines (in time-sharing system).
6. Schedule the slice of time to be allocated each user's program (in a time-sharing or
multiprogramming system).
7. Perform some routine processing of data, such as sorting and copying the contents of
one data set onto a specified device.
8. Maintain the store of programs on the mass storage device — adding programs to the
no longer needed, and so forth.
store, deleting those
9. Attempt to recover from and/or correct errors that may occur in any segment of the
computing system.
10. Interpret the job set up and job control instructions specified by the programmer.
At the heart of most operating systems is a program variously called the supervisor.
program is usually resident in memory at all times and
the executive or the monitor. This
performs many essential tasks such as program loading and error checking. This resident
portion of the operating system loads other less-often used routines as they are required.
User processing programs, sometimes called applications programs, are those pro-
grams written by individual users to solve particular problems. They may be written in a
COMPUTERS AND COMPUTING 15
generalized fashion and modified as needed to fit the peculiar requirements of a particular
system, or they may be constructed exactly to satisfy specific needs. For example, a com-
pany may construct its own payroll system or it may purchase (or rent) a general set of
payroll programs and modify them if necessary. Companies guard their processing pro-
grams as a very important company asset. Extensive security measures are taken to avoid
the loss or theft of programs. A considerable store of programs is usually available to a
computer user; in fact, the usefulness of a computer may well depend more on the variety
and efficiency of the available software than on any single aspect of the hardware.
It is of interest to note that over the last decade or so computer hardware has under-
gone dramatic cost reductions, which have not been accompanied by corresponding re-
ductions in computer software costs. On the contrary, software development costs have
soared to the point where now in a typical computer operation approximately 85 percent
of the total computer system budget is earmarked for software costs, as opposed to only 5
percent in 1950.
I I II II I
Two
Zone unmarked
11 lllllllll I I I I II I
punches x rows
iiiiiiiiiiiiimimIIIII III illlllllll|MMIIIIIIl|lll|lll|lll|llll|lllllll
1 I n I I I I I i| I I I I I I I I M I I I M I I
I 11 I I I M I I I I M I I 1 1) I I I I I I I I I I M I i 1 I I I M I I I I I 11
V. ^ ^^ 9 edge
80 numbered columns
A
,
into 80 vertical columns; each column can be used to record one character. A character is
represented by one or more punched holes. Each column is divided into 12 horizontal
punch positions or rows. Rows 0, 1,2,.. .,9 are usually numbered on the card; rows 12
and are at the top of the card and usually are not numbered. The top area of the card is
1 1
usually left blank for interpretation (printed translation) of the data punched on the card.
The code used to represent data on a punched card is called the Hollerith code, in
honor of Herman Hollerith, who around 1890 pioneered the use of punched-card equip-
ment for data-processing machines. The Hollerith code is summarized in Figure 1-14.
—
Each alphabetic character is represented by two punches a zone punch (12, 11 or 0) and a
numeric punch (1,2,.. .,9). Numeric characters require only a single numeric punch (0, 1
2,. .,9). Other characters are assigned other combinations of punches. The codes used for
.
these vary from one system to another. The card illustrated in Figure 1-12 was punched on
an IBM 029 keypunch machine.
Cards are punched on a keypunch machine such as the one shown in Figure 1-15. The
keypunch is equipped with a keyboard similar to the keyboard of a typewriter (see Figure
1-16). Depressing a key causes the appropriate character to be punched on a card. The
ALPHA and NUMERIC keys are used to punch characters from the lower half of a key
(ALPHA) or the upper half of a key (NUMERIC). The device is ordinarily in ALPHA
mode, which means that depressing a key will cause the character on the lower half of the
key to be punched. To punch a character on the upper half of a key, both the NUMERIC
and the key for the desired character must be depressed at the same time, similar to de-
pressing the shift key on the typewriter.
Altlililfiitoliliiiiia
~ttii^ii^feiiiiiii«i«
wmmm
^^\
Figure 1-15 Keyboard of IBM 029 Keypunch Figure 1-16 IBM 029 Keypunch
(courtesy IBM). (courtesy IBM).
computer system. Some systems will support batch-processing mode only, while others
will support conversational mode only. Some systems will support both.
Batch-processing can be characterized as an indirect method to communicate with a
computer (see Figure 1-17). The user must first punch the instructions on cards, which
must then be read by a card reader (Figure 1-13) to transmit the instructions to the com-
puter system. Thus, the punched card acts as an intermediary agent between the user and
the computer. In conversational mode, the user communicates directly (or enters into a
dialogue) with the computer by keying in instructions line by line on a terminal (see Fig-
ures 1-9 and 1-10). The computer may then immediately react to each line by specifying
whether any grammatical errors have been made. The user can then key in corrections. If
no errors are present in the complete program, the computer will print results on the user's
teletype or visual screen, thus providing the user with near instantaneous feedback. Such a
quick-response system is highly desirable both in terms of time saving and learning bene-
fits. In a batch-processing environment, on the other hand, hours or even days may elapse
before the user obtains his output (results). Typically when the computer operator submits
a program, the system creates a queue (waiting line) of programs storing them in its mass
storage device. The computer then processes these programs sequentially in the order en-
countered in the input stream. Results are then printed (first one in, first one out) on a
printer on continuous output forms, which must then be separated by the operator and
distributed to each owner punched cards and result listing). This sequence of activities,
over which the user has no control, is time consuming, which explains the time delay
(turn-around time) between submission of a program and receipt of the output. If mis-
takes (iceypunching or other) are made, many program submissions may be required
before receiving an error-free output. Figure 1-17 illustrates the logistics of
batch-processing.
In systems which support conversational computing, the communication link be-
tween the terminal and the computer takes many forms. Telephone links are quite com-
monly used. To initiate communications via the telephone, the user must dial the number
of the computer and place the telephone receiver in a special device (called a modem)
which is attached to the communications terminal. When other types of links are used, it is
usually unnecessary for the user to take special action to establish communications.
In all but the smallest systems, the user must establish his identity to the computer
before making use of the computing facility. This is done to enable the system to account
for the time used, to bill users accordingly and to establish what resources are available to
individual users. Before a person can make use of a conversational system, it is generally
necessary to have an assigned account number and perhaps also a special password. After
establishing the communications link, if necessary, the user enters his account number and
password. If these match a list kept by the computing system, the user is allowed to pro-
ceed; if not, the user may not have access to the computing
facility. These steps, called a
sign-on procedure, are quite specific to a particular computing system. An equally impor-
tant operation is ihc sign-off procedure, which is followed when the user is finished. Almost
all systems have a command such as GOODBYE or BYE which terminates the user's
communications with the system and releases the terminal for another user. It is important
that the sign-off procedure be followed after each session at a terminal. If a user does not
sign off, the next person may continue without signing on, and the time used by both per-
sons will be charged to the first user's account.
It will be necessary for the reader to familiarize himself with the system he plans to
use. A manual is normally available for this purpose. Before attempting to write a
user's
FORTRAN program on a given system, the user should learn the sign-on/sign-off pro-
cedures and other idiosyncracies of his particular computing system. A coworker or fellow
student who has just made a run on the system may also be helpful in this regard.
program shown in Figure 1-18. Note the inclusion of operating system instructions (job
control cards) before, between and after the program and data. The operating system in-
structions will vary greatly from one computing system to another; hence the reader must
determine local requirements for these instructions.
TflTT
Trar
11 rnfituJ^T^gx. rs.g. sx. r47ry
PAY = 80.
m Tn b
Pc!.v =. g m HP^
— "5
(MRS - 40)
ir(;HRS.GT.4ft> r^r\ TO 5
TTT TORffiSTTTTTTT
IRTSTRTTITiyTiSS"
J 2 2 2 2 2 2 22222222222 2222222222222222222222222222
3 3 3 3 3 3 3 3 3 3 313 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 13 3 3 3 3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 444 44444444444444444444444444444444444444
i i 5 i i i a an s i s i i s i i s i s s s s n n ns 5 i i i i i i s i i
5 ( (( I ^n n n n n n n n n n
( t I s n Mn nnnn
t ( t s
1 1 n 1 1 7 ? ? J 1 7 ) ? 1 1 1 ) ) 7 ? ) J M I ) I ) 7 ? n 1 1 1 n J 1 7 Mnn
inn i|nn I n i inn inn in n in in nnnin
nn n nnmmii snmnnn n ssnnnnnm
V"-"
20 COMPUTERS AND COMPUTING
1 -6 Exercises
1-6-1 Self Test
3. What value will be written by the program in Figure 1-5 if the input value is 47.5 in-
stead of 38?
4. If the punches 0-3, 12-8, 12-5, 12-5, 1 1-5 and 12-4 are found on a punched card, what
is the meaning of the message?
5. The card used for keypunching is divided into vertical columns and
punching positions (rows).
7. A compiler is
A
program which translates machine code into a high-level language.
a.
^oj A program which translates a high-level language program into machine code.
8. The part of the machine-language instruction which tells the computer what to do is
called
"J~ c. Computer hardware consists of all the physical components which make up a com-
. puter system.
I d. High-level languages are machine-independent.
r. e. The term software refers to such material as punched cards, magnetic tape, paper
'
tape etc.
^ f. In a batch-processing environment, the user receives an almost instantaneous re-
1. Modify the program in Section 1-4 to read both the number of hours woriced and the
rate ofpay from one input card. The output hne should contain the pay, the hours
worked and the rate.
system instructions and the exact makeup of the job deck necessary to compile and
execute a FORTRAN program. Try out these procedures with the program shown
in Figure 1-18.
3. Make a of tasks to which computers have been applied. Pool the list you make with
list
others in your class. The variety and number of applications will probably surprise you
and will give you a feeling for the important role the computer plays in our society.
4. List some problems that would not be suitable for solution by means of a computer.
Are there any conditions which would change your assessment of the feasibility of a
computer solution?
6. c. 7. d. 8. c.
9. a. T. b. T. c. T. d. T. e. F. f. F. g. T. h. F. i. F.
2
INTRODUCTION TO
FORTRAN— PART 1
Mr. X. has two rectangular lots of land. The width (Wl) of lot is 75.6 and its length (El)
1
is 121 The width of lot 2 is 98.5 and its length (E2) is 10.6. Calculate and print the area
.5. 1
of each lot and the combined area of both lots. An example of a FORTRAN program to
solve this problem is shown in Figure 2-1. Analyze carefully Figures 2-2 and 2-3 to see how
the FORTRAN program is punched on the cards. Also look at the computer printout
sheet and notice the listing of the original program and the results printed by the FOR-
TRAN program. Note the five types of FORTRAN statements in the program of Figure
2-1:
3. The EORMAT statement used to position the numeric values (results) and the
alphabetic messages on the output line.
5. The END statement which must be the last statement in any FORTRAN program.
INTRODUCTION TO FORTRAN— PART 1 23
W2 = 98 5
. W2 = 98.5 Define the width of lot 2.
WRITE (6,10)A1 j
WRITE 7 Print area oflot 1.
WRITE
WRITE(6,13)AT0TAL / "TOTAL AREA IS", Print total area.
ATOTAL
STOP Stop.
C]l2L_)
10 FORMAT 3X ( AREA LOTl IS F8 1
, ' ' , .
Wl=75.6
W2 = 98 .
El = 121.5
E2 = 110.6
A1=W1*E1
A2 = W2*E2
WRITE(6,10)A1
WRITE(6,11)A2
ATOTAL = Al + A2
WRITE(6,13)AT0TAL
STOP
10 FORMAT 3X AREA LOTl IS F8 1
( , ' ' . .
END
' ENP
INTRODUCTION TO FORTRAN— PART 1 25
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Numeric. The numeric characters are:
0123456789
Special. The special characters are:
u () + -*/ =
2-2-2 Constants
A constant is a quantity of a fixed numerical value that is explicitly stated; in other words,
it is a number. A constant may be expressed in integer mode or real mode. An integer con-
stant is always written without a decimal point; a real constant is always written with a
decimal point. Either type may be preceded by a sign (+ or —) if desired.
Examples
An imbedded blank (blanks between the first and last digit) in a constant has no effect on
the value of the constant.
6 32 632 6 3 2
No characters other than those just described can be used in writing constants.
632,000
26 INTRODUCTION TO FORTRAN— PART 1
The allowable size (magnitude) of integer and real constants and their internal representa-
tion on a computer is discussed in detail in Chapter 6. Integers and real numbers have dif-
2-2-3 Variables
Unlike a constant, a variable can assume different values. Variable names can be from one
One can think of a variable as the name given to a memory lo-
to six characters in length.
cation into which data is to be stored. Judicious choice of variable names helps make un-
derstandable the purpose of a particular FORTRAN statement as in PAY =
HRS*RATE, where PAY, HRS, and RATE are variable names. The first character of a
variable name must be alphabetic; succeeding characters can be alphabetic or numeric. No
"special" characters can be used in a variable name.
X Ql COUNT
ABC SUM X12345
INVOICE
,^
INTRODUCTION TO FORTRAN— PART 1 27
MAX
KOUNT
JAR
N103
K
A a
14 14
(A/B)*C a
'
~b'
A*B-30. a'b-30
-C —c
(A*B)*»2 {aby
-3.7 -3.7
A**. 5 a
( (A-B)**3)**.25 ^{a- by
PMT*(1 + IC)**N/IC-1 PMT(1 + icy - 1
ic
When parentheses are present in an expression, the operation within the parentheses is
performed first.
Example
Expression Evaluation
3* (4 + 5) 3*(4 + 5) =3*9 = 27
If parentheses are nested in an expression, then the innermost set of parentheses is per-
formed first.
INTRODUCTION TO FORTRAN— PART 1 29
Example
Expression Evaluation
Operation Precedence
** high
*or/ intermediate
+ or - low
Operations with higher precedence are performed before operations with lower pre-
cedence. The operations of addition/subtraction and multiplication/division are per-
formed in order from left to right according to the rules of precedence. Exponentiations
are performed in order from right to left.
Examples
2. A + B*C Since multiplication has priority, B*C is computed and the re-
sult is then added to A, giving A + (B*C).
3. +2.*3. 3. + (2.*3.) = 3. + 6. = 9.
8 /4 /2
. .
|- ^ 2. = 2. ^ 2. = 1.
multiplied by D, giving
A + B D not A + B
C C*D
9.
(3. +e. )/3.*6 '6. = 3.*6. =
3.
30 INTRODUCTION TO FORTRAN-PART 1
variable = expression
The value of the expression is first computed, and the result is placed (stored) in the vari-
able in the lefi-hand part of the statement. The equals sign used in a replacement statement
must be understood as a replacement sign rather than a mathematical equality.' Accord-
ingly, the statement X = X -f- is completely legal, since it means add
I
to whatever value I
is currently in memory cell X and store the result in X. The following are valid
examples of
replacement statements:
'Some texts use the symbol ^ to denote replacement so as to avoid the ambiguity of the two meanings of the
= sign.
INTRODUCTION TO FORTRAN— PART 1 31
and a real constant are involved in an arithmetic operation, the integer value is converted
to real before the operation is performed, and the result becomes a real quantity, if two in-
tegers or reals are involved in an arithmetic operation, the resulting mode for that opera-
tion will be the same as the mode of the operands.
Examples
variable on the left is different from the mode of the evaluated expression on the right. In
this case the mode of the value of the expression is converted to the mode of the variable
on the left-hand side of the equals sign before the resulting value is stored in the variable.
In essence, the mode of the variable on the left-hand side of the equals sign determines the
mode of the final value of the expression; that is, the expression on the right is evaluated
first, using the rules of hierarchy, and the final answer is stored in the mode of the variable
on the left.
Examples
teger variable.
KX = 4/3 + e.s 4/3 is 1 , numbers are integers. +
since both 1
C5=» STATEMENT
FORTRAN
OiOOOO OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOBOOOOOOOeOOOOOOflOOODOOOOt MIOIIMI •IQIII
l! . 1
^lon«al4Bl•^lll•!071Jl^^»Bl•nJ^I^l•)lnl3>^»»^)l4^^lno«^«s«4«^••l^JUlJ^>^»^•nl•B
iln
)
1
1111111111111111111111111111111111111111111111111111111 1 11 It 1 1 n I 111111
I
5[5 5 5 5
555555555555555555555555555555555555555555 S55SSSS555SSS S5SSS55S5SSSSSSS
E6S6(SE6&SE666E6666S66(SSS6SE6CC teSS66SSS( EEEtEEfiE<fit(( ttllKtIIICSdIt
miinninini
I
digits should be punched in consecutive card columns. Statement numbers need not be
numbered sequentially and are required only when a statement is to be referenced by an-
other FORTRAN statement in the program.
The FORTRAN statement itself can be punched anywhere into card columns 7
through 72. For program readability, the beginning programmer may wish to punch all his
statements starting in column 7. If a statement is too long to fit on one card in card col-
=Some installations require the number to be right-justified in card columns 2-5 because blanks are in-
terpreted as zeros.
INTRODUCTION TO FORTRAN— PART 1 33
umns 7-72, it can be continued onto another card by use of the continuation field (see
IBI^ FOniRAN
34 INTRODUCTION TO FORTRAN— PART 1
Blanks can be interspersed anywhere in card columns 7-72 within a FORTRAN state-
ment; that imbedded blanks are permissible in variables, constants, or FORTRAN key
is,
words. For example, the above statement could have been punched as follows:
50 P AY= 5 .2 5 HRS - 10
1 I 3 4 i 6 I I 1 ig II U 13 U IS IS ins 19 20 II 22 23 24 li U 21 21 29 30 31 32 33 34 ]i 3S 31 31 39 40 41 42 43 44 ii 4C 41 41 49 it SI il ii
1 n 1 1 1 1 n 1 1 1 1 n 1 1 1 n 11 1 1 1 1 1 1 1 1 II I 1 1 1 1 1 1 II 1 n 1 11 n 1 1 11
Please do
what 1 say
36 INTRODUCTION TO FORTRAN— PART 1
where device-number is a code (integer constant) representing the output device to be used
ment is executed the contents of the variables specified in the variable-list are written
onto the specified output device according to its specified format.
Example
The above WRITE statement can be interpreted as follows: Write the contents of
memory locations PAY, HRS, RATE onto device number 6 according to the layout de-
scription given by the FORMAT labeled 10. Note that even though the content of PAY is
written out, the value of PAY in memory is not destroyed. The device-number associated
with specific devices is dependent on the computer system being used. A typical assign-
ment might be:
5
INTRODUCTION TO FORTRAN— PART 1 37
WRITE (6
38 INTRODUCTION TO FORTRAN— PART 1
The above output operation can be interpreted as follows. Write three numbers (three
variables are named) on an output page (device-number 6) according to the data layout
described by the FORMAT statement labeled 10. The FORMAT may be interpreted as:
The first variable (JHRS) will be printed as an integer value (specified by the formal I
code) in the first two form (12), the next variable will be print-
print positions of the output
ed as an integer in the next three print positions (13), and the last variable (JRATE) will be
printed in the next two print positions (12), that is, print positions 6-7.
Temporarily, until discussion of printer carriage control in Section 2-5-2, we shall re-
frain from printing any data in print position I of an output page, as this position is used
to control the printer in terms of vertical page movement.
The general form of the FORMAT statement is
1. Data format codes used to identify the mode of the data items (numerical results) to be
2. Edit codes used to control the placement and editing of the data items in the output re-
cord: X for spacing, single quote O for literal data, and T for specifying the beginning
print position for an output field. Note that all format codes must be separated by com-
mas.
In this chapter we shall only consider the I, F, X, literal, and T format codes and reserve
discussion of other format codes for subsequent chapters.
The X format code is an edit code used to specify spaces on an output line. It is gener-
ally used to provide margins or to separate fields by a certain number of blank spaces. The
nX
Example The code shown in the following example can be interpreted as follows: Write the
number K on a line with the help of format number 1. Beforeyou print K, allow three 1
blank spaces, and then print an integer (12) using two print positions. Note that the X for-
mat code does not have a corresponding item in the variable list of the WRITE statement.
INTRODUCTION TO FORTRAN— PART 1 39
K = 14
WRITE(6,11)K
11 F0RMAT(3X,I2)
1 4
Integer data is described for an output operation by the I format code. The general
form of the I format code is:
Iw
The I format code can be used only to describe integer mode variables. The negative
sign occupies one space (print position), which should be included in the total number of
spaces allocated for the output field (h').
Example 1
Number is right-justified
First print
position 1
Printed line
The first variable, ICT, in the variable-list is associated with the first numeric format
code, 15; the second variable, LI, is associated with the second numeric format code, 12,
and so on. If the number of digits in the number to be printed is less than the width re-
40 INTRODUCTION TO FORTRAN— PART 1
served for il, the number is righi-justijied {\\\q rightmost digit is placed on the rightmost
print position of the output field) with blanks inserted to the left in place of leading zeroes.
Example 2
K = 35
J = 5 3 5 First line
WRITE(6,12)K
12 FORMAT (2X,I3)
L = K*J
17 5 Second line
WRITE(6,11)L,J
11 FORMAT (6X, 13, IX, 12)
Note that for each different WRITE statement one obtains a separate output line. In the
case of the first WRITE, only one number is printed on one line, whereas in the second
WRITE statement two entries are printed on a new line.
/^'^
Care must be exercised to provide enough space in an I format code for all the digits^
of the number (including the negative sign "-"
enough spaces are al-
if required). If not
I
located, an error message will be printed. The exact form of the message will differ among
I
Vsystems. In the following example a set of asterisks indicates insufficient field width.
Example 3
K=1234
J = -14
WRITE (6, 15) K ,
J ,
J
1 I 1
Real data is described by the F format code. The general form of the F format code is:
Fu.^
The decimal point is always printed. occupies on^ pxint positijoaia-the output field and
It
hencenTusTbeTrreluded in the total number of spaces (w) allocated for the real value.
The F format code can be used only to describe real mode variables. The reader may
wonder why it is necessary to worry about the number of digits to the right of the decimal
point on the output. Internally, the computer carries out computations to many decimal
places; for example, the result of 10.12*5.24 is stored internally as 53.0288, and the pro-
grammer may only be interested in the first two decimal positions (dollars and cents).
Hence it is always the programmer's responsibility to specify the number of digits wanted
for the fractional part of the result.
Example 1
A = 63 426
.
B = -4 2 .
WRITE(6,15) A
II
. A ,
III
A , B , B
15 FORMAT (IX,
6 5
. .
|
F6 3
4|2 6
II|
.
|
,
. .
F9
6 5 ..4 2 6
.
.
|
,
. .
IX,
III
F6.1,
.6.3,..4|
F6.1,
.4. .21
F4.0)
Note that if the number of digits in the number to be printed is less than the width of
the field reserved for it, the number is right-justified in the field, with blanks inserted to the
Example 2
A- 12.6534
B=13.7
WRITE (6, 16 A, A B
I I I
,1.2.. .6.5.31 1.3. 1.3. ..7.0.0
A
\A
A is rounded to is rounded to is rounded to
three decimal places one decimal place the nearest whole number
Note that in the case of the variable B the value 13.700 is printed, since the format
specifies three fractional positions.
With F format codes care must be exercised to provide enough print columns for all
of the decimal point of the real number. If not enough print columns are
digits to the left
42 INTRODUCTION TO FORTRAN— PART 1
allocated, an error message will be printed. The exact form of the message differs among
systems. In the following example a row of asterisks indicates an error specifying insuffi-
cient field width.
Example
A = -123. 456 If F7.3 is used, then the output field is only seven print columns
B= 2509.01 wide, which cannot accommodate the eight characters for A,
C = 12 . w hich include the minus sign and the period.
WRITE (6. 12) A , A B , , C
i i
Not enough space Not enough Cannot print Cannot print ihc
for negative sign. space for sign, leading digit 2. two leading digits, 12.
Field width?' Number of digits to the Decimal Sign if Number of digits in the whole
right of decimal point. point. needed. portion of the number (digits
to left of decimal point).
The beginning programmer is warned again that any real variables that are to be
F format codes in the
printed nntsi be described by FORMAT. For example, the next code
segment is invalid:
WRITE(6,11)A,B,C
INTRODUCTION TO FORTRAN— PART 1 43
print positions where the data output layout is already specified (business forms, checks,
tables, reports, etc.)
Example
K = 35
WRITE(6,10)J.K
10 FORMAT (T5. 12. TIO, 13)
The format code T5 specifies that the output field for J is to start in print position 5 and
that the output field for K is to start in print position 10. The T format code arbitrarily al-
lows the programmer to skip to any desired position at will on the line. Note that T4 or 3X
would cause the output record to start in print position 4.
The use of single quotes (') in a FORMAT around a string of characters specifies that
the string (all characters within the two single quotes)
is to be placed on the output line at
whatever print position the printer happens to be at that time. Literal strings are generally
used to create headings, identify numerical results, or provide messages or explanation.
Example 1
WRITE(6.10)KV
10 FORMAT (T5, 'AVERAGE IS M3:
Example 2
IERR0R = 999
WRITE(6,6)IERR0R
6 F0RMAT(T2, '*** *** '
,13)
# * * 9 9 9
Literal field
Example 3
K = 35
INTRODUCTION TO FORTRAN— PART 1 45
Example 5
M=5
ID=25
IY=76
WRITE(6,5)M,ID.IY
5 FORMAT T60 XYZ COMPANY PAYROLL REPORT DATE
( ,
'
MX , 12 ,
'/ M2 ,
'
/ M2
Output line
XYZ COMPANY PAYROLL REPORT.DATE 5/26/81
Print 1 60 90
position
Example 6
WRITE(6.11)
11 FORMAT 3X XYZ CORPORATION
( ,
'
'
)
1 1 1 m^ \ F i
°
i
'^
|
P °
| i
'^
i
^^|i ° N
| | | 1
Such WRITE statements are generally used to produce headings or page titles.
STOP
The STOP statement is used to terminate execution of a program. At least one STOP state-
ment should occur in every FORTRAN program; more than one can be used if desired.
END
46 INTRODUCTION TO FORTRAN— PART 1
The last statement in every FORTRAN program must be the END statement. Only one
END statement can be used in a program. END is a nonexecutable instruction (see Sec-
tion 2-3, question 7) and should not be assigned a FORTRAN statement number.
2-2-15 Errors
Errors are not uncommon when writing programs. There can be keypunching errors,
grammatical errors, logical errors (the program does not solve the intended problem), ex-
ecution errors, job control, or workflow errors. Errors (or bugs as they are commonly
called) confront the beginner on all fronts. How good a programmer really is depends to a
certain extent on his ability to debug (locate errors) in his program!
There are two distinct classes of errors that are likely to occur in predefined time se-
quence during the processing of a FORTRAN program on a computer.
1. Compile-time errors (Syntax errors). These errors are caught by the compiler during the
machine-language translation process. Statements are incorrectly structured or gram-
matical rules are not observed. A list of errors (if any) is generally provided on the
printout form within or following the program listing.
Examples
WRITE(6,15)A
INTRODUCTION TO FORTRAN— PART 1 47
A logical error can also be picked up by the operating system. Consider the following
example illustrating an infinite loop:
5 GO TO 5
An error message dealing with "time exceeded" would probably be printed. Certain
execution errors can cause immediate cancellation of the job. A list of execution-time
errors with their codes and meanings is provided by the system on the printout form.
It is recommended that the reader consult the manufacturer's FORTRAN technical
reference manual for a complete description and explanation of each of the different
types of execution-time errors.
Example
( X+ ( Y* Z + W
(
) ) ) is equivalent to X -K Y* Z + W
(
The important point is that parentheses must occur in matched pairs. For each left pa-
renthesis, there must be a right parenthesis. Too many parentheses may slow down the
compilation process, however.
Answer: This depends on the particular system. Typical lengths vary from 80 to 144
characters.
3. How does the computer represent repeating decimal numbers (rational numbers)? For
example, how can the computer represent exactly ./3. in decimal form? 1
Answer: It can't; only the first few digits are retained. For instance, on an IBM 370
computer 1 ./3. = .3333333 and 8./9. = .8888889 (last digit is rounded ofQ.
Answer: An execution-time diagnostic will be printed, and your program will usually
be terminated. Division by zero is not a permissible operation.
6. What happens when I multiply (or divide, add, or subtract) two numbers and the re-
sult is too large to be represented as a number on my computer system? Also, what
happens if the number is too small to be represented on the system (less than 10"^^ for
IBM 370)?
Answer: In the first case an overflow condition will occur, and an execution-time error
will appear to that effect. The program will generally not cancel, and execution of the
48 INTRODUCTION TO FORTRAN— PART 1
program will continue. The user should check the logic or scale numbers if necessary.
In the second case an underflow occurs with a corresponding error message. The
variable is generally set to 0, and the program will proceed. Check the logic to under-
stand why such a condition would arise.
7. I am confused on the difference between STOP and END. Can you help?
Answer: The END statement is processed at compilation time to inform the compiler
that there are no more FORTRAN statements to be translated (no FORTRAN code
follows; the physical end of the FORTRAN program has been reached not the phys- —
ical end of the complete job, control cards and all, but just the FORTRAN source
out, all results (if any) have been printed out, and that as far as this job is concerned
there is nothing else to do; i.e., the STOP causes execution to terminate and represents
the logical end of the program as opposed to the physical end designated by the END
statement. The STOP statement causes control to be returned to the operating system.
which process other programs (if any). As will be seen in Chapter 3, the STOP
will
statement can be placed anywhere in the program (before the END).
8. I am performing some arithmetic computations on some data, and I do not know how
many digits I should reserve for my output field (I,F) in the FORMAT.
Answer: Most of the time you can estimate an upper limit and use that length for your
width, w. Otherwise, make your field as large as possible — 120 or F20.I, for example.
The result will be right-justified anyway, with blanks on the left. If you are working
with very large magnitudes, use the E format discussed in Chapter 6.
9. You know, it's really funny, yesterday visited the computing center and overheard
I I
someone say, "There's a bug somewhere in my program." I was tempted to tell him to
call the local pest control man. What do you think he was really saying?
Answer: A "bug" in the computer science jargon simply refers to an error or a mistake
of some kind. To "debug" a program means getting rid of the bugs or errors in a pro-
gram.
10. Can I use a negative number as a base in exponentiation? For example, is (— 3)**2 or
(-3.)**2. valid?
Answer: To a certain extent this depends upon the compiler being used. In many sys-
tems, exponentiation involving small integer exponents is implemented by repeated
multiplication. For example, (— 3)**2 is implemented as (— 3)*(— 3), resulting in no
problems. However, for larger integer exponents and for all real exponents, most
compilers use logarithms to evaluate the expression. In these cases the use of a
negative number as a base in exponentiation will result in an error since the logarithm
INTRODUCTION TO FORTRAN— PART 1 49
12. In everyday life we don't differentiate between integer and real (floating point) num-
bers when performing arithmetic operations. Why do we in FORTRAN?
Answer: Actually, we do allow for a difference in everyday-life computations as well
as in FORTRAN. Sometimes we have to figure the position of the decimal point when
multiplying or dividing two real numbers. Obviously, operations involving decimal
points are more time-consuming than those without a decimal point. When some
computers rent for $82 per minute or more and only integer arithmetic is desired, it
would be uneconomical and wasteful of time to worry about the position of an un-
needed decimal point during computations. On a typical computer, real number oper-
ations may be 100 times slower than integer number operations.
In a scientific environment, too, it may be necessary to work with very large num-
bers requiring the use of exponents and of decimal points. It would be impractical to
write 10^" as an integer; hence, an alternative arithmetic is required (real arithmetic).
Answer: Yes. Consider, for example, the evaluation of 2x^ + 3.v^ — 6x + 1. A straight-
forward way to code this expression is:
2*X**3-l-3*X**2-6*X-i-l
-
2x' + 3x' -6x+ \ = {2x' + 3a- - 6) x + \
= {{2x + 3)x-6)x+ \
( (2*X + 3)*X-6)*X+ 1
3 additions.
Answer: The difficulty with an apostrophe is that it is used to enclose the literal string;
a formal code such as 'XYZ'W' is ambiguous to a compiler. Many compilers use the
following rule to avoid ambiguity: In order to print an apostrophe as a part of a literal
string, use two apostrophes in succession. The compiler will insert one apostrophe on
the output line in place of the two present in the format code.
I
Example
WRITE(6,16)
16 FORMAT 3X ( .
'
SUSAN ' '
S GRANDMOTHER '
)
would produce the
following line:
,S,U,S|A,N, •, S, ,G,R,A,N,D,M,0|T|H|E,R,
WRITE(6,11)X,Y
11 F0RMAT(T2,F5,2,T5,F6.2)
T2 T5
i2,3. .,9.9,
Processing F5.2 and then returning to
I
—5 —6 —7 [— —4 II
I I
5
—— I
[
I column 5 to print F6.2 on same line thus eras-
ing what was in print positions 5 and 6.
.2, 3. ..5. 6. 7. ..4. 5. This then results in the following memory
I
If a Tab number is less than a preceding tab in the same format, this does not cause
the printer to skip to the next line but to overlap results on the same line.
1
- r
INTRODUCTION TO FORTRAN— PART 1 51/
P.9
where a is the first term of the progression (a = 1
1 +1 + 1 + 1+ . . . +J_+ . . .
Let us write a program to compute the sum of the first 1,000 terms, the infinite sum, and
the difference between these two sums. See Figure. 2-9.
R= .5
N=1000
A=l.
SUM1=A*(1. -R**N)/(1. -R)
SUM2 = A/(1. -R)
WRITE(6.10)SUM1,SUM2
DIF = SUMl - SUM2
WRITE(6,11)DIF
STOP
10 FORMAT T5 THE FINITE SUM IS F6 3 THE INFINITE SUM IS
( ,
'
' , . ,
' '
, F6 3 .
END
$1,023.36. His monthly contribution to a retirement plan is 4.5 percent of his first nine
months' salary. For each child under 18, he receives $1 19.25 in child support from social
security. Hismonthly social security deduction is 6.13 percent of his monthly income, and
his federal income tax is 13.6 percent of his yearly gross (deducted on a monthly basis).
Monthly payments for life insurance equal 9.6 percent of his monthly salary after social se-
curity and federal tax deductions. Write a program to compute Mr. X's monthly spend-
able income after taxes, deductions, and supplemental support income. A program to
solve this problem is shown in Figure 2-10.
. )
CHILD = 119.25
SALMON = 1023.36
RETIRE = 9 SALMON* 045 /12 (
.
.
)
SSTAX= .0613*SALM0N
TAXING = .136*SALM0N
PAYNET = SALMON - RETIRE + SSTAX + TAXING (
STOP
END
SPENDABLE INGOME 952 01 .
Card columns 73-80 are listed in the program listing but are not translated by the com-
piler. This can be used to identify the program and/or author of the program, in ad-
field
dition, a sequence number can be punched into this field to make it easier to rearrange it in
sequence if the deck is dropped. See, for example, the program in Figures 2-2 and 2-3.
Code Meaning
blank Single-space,
other characters May have special installation printer control effects.
The vertical movement of the output form (page) is effected at the very beginning of the
WRITE instruction when the printer interprets the carriage control code specified in the
FORMAT; before the printer writes out anything checks the carriage control code to de- it
cide whether to space a line, double-space, skip to the top of a new page, etc. THEN it
writes the output line. The vertical spacing of the form is not performed at the end of the
WRITE operation.
The X format code or the T format code can be used to provide a blank as the first charac-
ter on the line and hence cause the printer to single-space.
Example 1
AX = 3 2 .
WRITE(6,10)AX
10 FORMAT IX, F6.1) ( could have used T2 in the FORMAT instead of IX.
Example 2
AX = 3 2 . output line
Printer control can be achieved by placing the desired carriage control code as a literal in
the first position of the output line.
Example 1
I = 423
WRITE(6.10)I
10 FORMAT '0M3) ( Note the literal '0' in the 1st print position.
1
Example 2
J = 623
WRITE(6,15)J
15 FORMAT( '
1 '
,17) Note the literalT in the 1st prim position.
Example 3
10 WRITE(6,11)
1 FORMAT 2X THE NUMBER OF GIRLS IS
( ,
'
'
)
K = 678
15 WRITE(6,12)K
12 FORMAT + ,T26,I3) Note the literar +
(
' ' '
in the 1st print position.
field.
Example 4
K=123
L = -24
WRITE(6,16)K,L
16 FORMAT ( 13 ,2X,I3) Carriage control code is pan of 1st number lo be printed
ecute.
Because of the logical organization and sequencing of program instructions and be-
cause of requirements of specific computer languages, it is usually difficult to write a com-
puter program without first expressing the algorithm in some preliminary form. For a sim-
ple problem, a verbal outline of the steps required may suffice; for more complex prob-
lems, however, a widely used tool is the program /7ouT/?«r/. A flowchart is a pictorial rep-
resentation of the logic (method) used to solve a particular problem. It is a diagram il-
lustrating the sequence of steps (instructions) that a person or machine must execute to ar-
rive at the solution to a problem. A flowchart is particularly useful for visualizing paths
through the logic of an algorithm. For example, the algorithm of Figure 1-5 (computing
pay for the number of hours worked) could be expressed in flowchart form as shown in
Figure 2-12. Note that there are two paths through the algorithm; the path taken depends
on the particular value of HRS supplied at execution time. Since there is generally more
than one correct method to solve a problem, there also can be any number of flowcharts.
56 INTRODUCTION TO FORTRAN— PART 1
r^ START
J
<QjRS
INTRODUCTION TO FORTRAN— PART 1 57
Symbol Example
CZ=) Terminal
( STOP ) Stop execution here.
o Connector (entry)
Y£3
Take the Yes path X is equal
if to 4,
Decision -^ otherwise take the No path.
Flowlines
X = X - 1
6 Connector (transfer)
block containing X =X—
execution at entry point marked A.
1 , resume
memory
than giving each location a numerical address, which would be difficult to re-
member and which would not be very meaningful, symbolic names are used to represent
the data. The computer, not the programmer, determines which exact memory cell is to be
used to store the particular data. Variable names can be chosen to convey the nature of the
data to be processed. For example, the flowchart segment in Figure 2-14 shows that two
numbers are to be read from a record (card) and stored in two memory locations called
HRS and RATE. Other names, such as X and Y, could be used instead of HRS and
RATE, but the judiciously selected names of HRS and RATE serve to better identify and
document the nature of the transaction under consideration. For an output operation, the
instruction WRITE, followed by a list of symbolic locations (variables), is used. The value
of each of the locatio ns is to be written onto some output device. For example, the block
/WRITE PAY, HRS/ indicates that values in locations PAY and HRS are to be displayed
on some device.
Memory
Data card
35
7
HRS
INTRODUCTION TO FORTRAN— PART 1 59
greater than (>), less than or equal to (<), greater than or equal to {>) or not equal to {^).
The decision block is the only block from which two different logical paths may be
selected. Flowlines indicate the path to be taken, depending on the decision made. For ex-
ample, consider the following decision block:
If the value of X is greater than 4, the path marked YES is taken; otherwise, the NO path
is taken.
Another way of expressing decision is in terms of a comparison between two values.
The two values being compared are separated by a colon (:) in the decision block; the two
paths are marked with the relation symbols that are appropriate for the decision in ques-
tion. For example, the decision above could also be written:
If X is greater than 4, the path marked ">" will be taken; otherwise, the path marked "<"
will be taken.
Flowlines
Connector Blocks
When it is inconvenient to draw flowlines to connect one area of the flowchart to an-
other, connectors are often used. Connectors serve two purposes:
The symbol used for a connector is a small circle ( ) .A numeric or alphabetic label
is placed in the connector block. When the flowline points away from the connector such
as ( -, the connector is being used to denote an entry point, that is, a block to
J
60 INTRODUCTION TO FORTRAN— PART 1
which transfer will be made from some point in the flowchart. When the flowline points
/ WRITE X.Y /
r END ^
If the value of X is less than4, the block containing Y = X + Z is executed and transfer is
made to the entry point marked "25," which contains the WRITE instruction. If the value
of X is greater than 4, the block containing X = 4 is executed and transfer is made to the
entry point labeled "A." The flowchart above is equivalent to the following:
Note that in a flowchart it is possible to have many transfer connectors such as"
Only one entry connector such as ( A j ^ may be designated in a flowchart, how-
ever.
2. Determine the output produced by the following flowcharts, given the following data
cards:
r START ^ ^r
/read hrs/
/readovtme/
TOT = HRS+OVTME
WRITE TOT
YW
Z 7 40
p
r^ STOP
J
62 INTRODUCTION TO FORTRAN— PART 1
f. y'^^
i. 2(x/')
1. V + a'
INTRODUCTION TO FORTRAN— PART 1 63
a. X = I b. IX = A c. X = (I + 3)/2
d. IX = -A + B e. X = I**B f. X = J*l/.l
g. X=J h. X = B**J i. IX = J*A
10. As a result of the following program code, indicate what value will be placed in mem-
ory locations S, J, and JK.
1=4.
A = 1
; ' :
f\- I
B = 2
S = (3/I)*3
J = (3./9)*3
JK = (A + 2./B)/2
11. Show that if I and J are integer variables, and C is real, it is possible to have the fol-
lowing situation:
a. -L. C 5^
1 C
J J
b. C.I/J ?^ C.(I/J)
12. Indicate the printed output field (print positions) for A, given the following format
specifications:
13. What output will be produced by each of the following program segments?
a. X = 3.2 b. I = +1632
Y = X*.16 J = -4
WRITE(6,10)X,Y K = I/J
10 FORMAT 3X F4 TIO F9
( , , , , . 2
,
'ALL'
formula is C = — (F — 32).
9
2. Write a program to evaluate each of the formulas for the indicated values (use tf =
3.1415) and print the answers with appropriate literal headings.
/-= .04
/ = 3
p= 100
INTRODUCTION TO FORTRAN— PART 1 65
4. Write the code to produce the remainder (expressed as an integer) of A/B. For exam-
ple, the remainder of 13/2 is 1, and the remainder of 17/3 is 2.
5. Can you write the program in Section 2-4-2 in more compact form?
6. Write a program to compute and print the length of the hypotenuse of a right triangle,
given its two legs are A = 1 .0056 and A2 = 1 35.77.
7. Write a program to compute and print (7./3.)*3 and (3.*7.)/3. Do you expect the re-
be 7.?
sult to
December 31 has Julian date 365. A formula for approximating the Julian date is
(month — 1)*30 + day. Compute the Julian dates for November 7, May 25, and
March 21.
9. Write a program to compute and print the area and the length (perimeter) of each of
the following:
5.05
13.73
10. Write a program to print out your initials by magnifying them as follows:
MMM
66 INTRODUCTION TO FORTRAN — PART 1
The date for Easter Sunday is then March (22 + ND+NE). Note that this can give a
date in April. In order to compute the remainder, NR, of the division of NA by 19, or
of NB by 4, or in general, the remainder of the division of NUM 1 by NUM2, the fol-
lowing statement can be used:
NR = NUM1-NUM1/NUM2*NUM2 i.e.. the remainder of the division of 17 by 3
is 17 - 17/3*3 = 17-5*3 = 2
Write a program to read a year N and compute the date for Easter Sunday for that
year using the formula 22 + ND + NE. The resulting month should either be March or
April.
12. Mr. X is a brick layer. Last year his gross pay was $23,564.99. After deducting 6.13
percent for social security and 23.5 percent for income tax from his gross pay, was his
net income greater than Ms. Y's net income? Ms. Y is a teacher who grossed $19,874
but had $850.45 dedected for her income retirement plan and 16.03 percent of her
gross income for income tax purposes. Print both salaries.
13. Given an interest rate / of 6 percent and a principal P of $1,956.45 deposited for an
1 1-year period in a savings account, write a program to compute a total principal, T.
using the formula:
T= F{\ + ly
where .V is the number of years.
Suppose the interest is compounded daily for the same time period of 1 1 years. Write
a program to compute:
=
^ ''
(' ^i)'"
where y is the number of times the interest is compounded per year.
b. The difference between total amounts when the interest is compounded once and
360 times a year.
14. A wholesaler accepts a $5,000 promissory note at 10 percent in lieu of cash payment
for delivered goods. Write a program to compute the maturity value of the note for a
30-, 60-, and 90-day short-term loan. The formula to compute the maturity value S is
5 = ^(1 + A/V), where P is the principal, / is the interest rate, and A' is the number of
years (if it is less than a year, it is expressed as days/360).
15. Ms. X would like to deposit $1,500 at a savings institution. She considers a local bank
and a credit union. The credit union requires an initial nonrefundable fee of $15. De-
posits earn 6'/4 percent at the credit union and 6 percent at the bank. Ms. X knows she
will need the $1,500 two and a half years. Write a program to determine whether
in
she should save at the bank or at the credit union. The formula to compute the
amount A = P{\ -\- I Y where P is the principal, / is the interest rate, and N is the
\s,
number of years.
INTRODUCTION TO FORTRAN— PART 1 67
16. A balance sheet showing the financial position of a business has the following format.
Assets are generally listed in the order specified. This balance sheet will be referred to
repeatedly in later chapters.
XYZ CORPORATION
Balance Sheet
April 30, 1981
Liabilities and
Assets Stockholders' Equity
Cash Liabilities
Accounts payable 3000
68 INTRODUCTION TO FORTRAN— PART 1
is executing the translated program. Compile time is the time during which the com-
6. a. No comma after (6,10); also field for A is too small, should be at least two charac-
ters long.
b. Value of variable I can be used as a carriage control character.
c. The WRITE statement must contain variables. „
d. F4.5 is an invalid FORMAT code since 5 > 4.
7. a. F. b. T. c. F. d. T. e. F. f. T. g. F. h. F.
i. F. j. T. k. T. I. F. m. F. n. F. o. F. p. F.
3. 6. b. 3 c. 4. d. -5 e. .0277778 f. 0. g. 0.
Ii." U i.
10. S = 0. J =0 JK = 1
12. 2 5 b. - 6 4 2 8
a.
I I I |
7|4|5 |
.
, | | |
|
|,5 ,
,
.
,
,
b.i I
^
¥ i i
^
ii I rrm^iTi
c.
^ l ¥ l
^
l ^ °^lV ^l l l 1
^1
i V^^
d. ABC and IJ3 should be defined respectively by F and I format codes.
'• j-in — I
Top of new page.
1 |
A Li L
|
I
Top of new page.V)
1 |
.
3
INTRODUCTION TO
FORTRAN— PART 2
1. The READ statement used to read data from punched cards or other input medium.
2. The GO TO statement used to transfer control to a nonsequentially placed instruction.
3. The IF statement used to branch to other program statements depending upon a condi-
tion.
Note that in the program of Figure 3-1, statements 12, 13, 14. and 15 could have been
replaced with just the statement + (NHRS - 40)*6.50* .5. To make this
PAY = 40*6.50 1
program more flexible, we could have read a variable rate R and an overtime pay rate fac-
tor F so that by changing the above statement to PAY = 40*R + (NHRS - 40)*R*F, the
program could have computed any gross pay for any rate R and any overtime rate of F.
70
INTRODUCTION TO FORTRAN— PART 2 71
START
C CALCULATION OF GROSS PAY
RATE = 6.50
5 READ(5,10)NHRS
10 FORMAT (12)
IF(NHRS.LE.40)G0T0 17
12 PAY1 = 40*RATE
13 0VTM = NHRS-40
14 PAY2 = 0VTM*RATE*1.5
16 GOTO 18
1 1
too specifically; thus, in our example, pay is computed only for a fixed rate of $6.50. If we
want same program for different values of RATE, we have to reset RATE each
to use the
time to different rates, and every time we do, the entire program has to be completely re-
compiled because one statement was changed. This is time-consuming, inefficient, and in-
convenient.
Another way to assign any desired value to a variable is to use the READ statement.
The READ statement allows the program to accept data during the execution of the pro-
gram (after compilation). The data is punched on cards (data cards), and these values can
be read by the computer as specified by the FORTRAN READ instructions. For example,
a payroll program will be able to compute different salaries depending on the rate of pay
punched on each employee's data card.
It is very important to note that even if one program consists of only one deck of
cards, the program deck consists of three separate and distinct parts, all processed dif-
ferently by the computer system.
The FORTRAN program consists of FORTRAN statements that use FORTRAN
key words under strict grammatical rules. Data cards contain numbers that will eventually
be read by the FORTRAN READ statements. These two entities are physically separate,
as shown in Figure 3-2. Usually the FORTRAN source deck is separated from the data
deck by special control cards (workflow or job control cards telling the computer what ac-
tion to take). These control cards will vary from system to system and will generally be
physically located in front of the FORTRAN program, between the program and data
deck, and possibly after the data deck as shown in Figure 3-2. The FORTRAN source
deck is first read by the compiler, which translates it into machine language. It is then
stored (loaded) into the memory of the computer. This stage is called compilation and load-
ing. The data cards still have not been processed.
D I MM I s 1 1
'
• 1 1 M t ) a 1 1 1 1 1 1 D 1 1 g 1 1 e 1 1 1 1 g 1 1 1 1 1 1 M I gg ig gg ggg gg giiiiiiiiigg gggiii
I
I
J
I I I I I I I I I I I I I I I I I I I 11 I I I I I I I I I I I I M I I I I I I I I I I I I 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
|!n]]n3; ) j nn 1 1 1 3 3 3 ) 3 1 s i ni n ) 1 1 1 1 1 s ni i 1 1 1 3 3 3 3 3 3 3 3 3 3 13 13 3 3 3 3 3 3 3 3 3 3 3 3 3 3 1
I 4 I 4 < 4 < < < < < 4 4 ( 4 4 I 4 4 I I i I I 4 I 4 4 I I < I < ( < < 4 < < I I < < I < 4 4 I I 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
5 S S i S S S S S S 5 5 S S i S S. S S. S S S S S S S S i 5 S S S S S S i 1 S i S i S S 5 S S S Si s s s Si SSSS55 sssnsi S S S S S 1 SS i
i i t . ( s ( : [ S. ( i i i i t S ( ( ( t ( t i S S S E S i t f ( i S i i i t ( t i li ( t i ( Si i C i II I i ii i i t i ($ I I E i I I I i i I i
I I J I I I I ) 7 I I I I ) I I I J I nM 7 I M t I I I I I 1) 1 I I I I I) I I I I J I I ) I I 1 I 1 I 1 I 1 1 I I I I I I 7 ) I 1 7 J 7 I 1 I I
n I ! ) s 1
1
' mm ) ! !
!
" « ) ! ) n ) 1 1 1 J I in 3 s I i I in I ) m ) nnnnnnnnnnnn nn I
Once control is passed to the program in memory, the data cards are read by the
READ statements in the order these (or their equivalent in machine language) are encoun-
tered in the FORTRAN program. See Figure 3-3.
INTRODUCTION TO FORTRAN— PART 2 73
Control cards
^^A Operating system —
Memory
Source deck is no longer
present (has been translated).
If cards are used as input, the input data can be punched anywhere in card columns 1-80.
Example
format number
\
READ 5 10 HRS RATE BONUS
( , ) , ,
The above READ statement can be interpreted as follows: Read three numbers from
one or more cards (device number 5 might imply data is read from cards) and store these
three numbers in memory location HRS, RATE, and BONUS, respectively.
'These numbers will vary from installation to installation. Throughout this text the number 5 will be used to
refer to the card reader. In some insta'llations the number I is used.
.
3. How many card columns are used for each data item (length of data item).
A FORMAT is needed in conjunction with the READ statement to inform the computer
precisely how the READ operation is to be performed, that is, how to process the various
data on the input record.
Each READ statement must specify a format-statement-number; each FORMAT
statement must have a statement number by which it can be referred to. The READ an is
executable statement while the FORMAT is nonexecutable. The READ instruction is car-
ried out according to the specifications described in the FORMAT. For this reason the
FORMAT statement can be placed anywhere in the program (before the END statement).
Some programmers prefer to place all their FORMATS at the beginning or end of
their programs while others place them immediately following the associated READ state-
ments.
Example
JHRS Memory
data card
format code) found in the first five card columns (1-5). The next number (IRATE) will be
an integer number found in the next three card columns (6-8), and the last number
(JBONUS) will be an integer found in the following two card columns (9-10).
1 Data format codes to identify data on the card as either integer or real numbers.
F This code identifies a real number; that is, real data is to be read from the input re-
cord (card).
I This code identifies an integer number.
In
One card column must be reserved for the minus sign if the integer is negative. Any
blanks within the integer data field, whether leading or trailing, are interpreted as zeroes;
hence the integer number must be right-justified within the field. Integer data can consist
only of the digits through 9 and the + and — sign;any other character punched in an I
field will result in an execution-time READ error. The corresponding variable in the
READ list must be an integer variable.
Example 1
+ 2 = 3
FORMAT (14, II, 12 vy J
K =44
2 1 = 210
1
= J
K = -5
In Example I the READ list specifies three numbers to be read. Since the FORMAT
has three data format codes, this means that three numbers are to be read from one card.
Note that the leading and trailing blanks are read as zeroes. Also note that the plus sign
for I in the first data card is not really needed to identify a positive number. Reading starts
at the first card column unless otherwise specified (T and X edit format codes) and each
new field immediately follows the preceding field on the data card, as long as there are no
other control format codes.
Fw.d
If there is no decimal point punched in the number field on the data card, u' columns
are read, and then the decimal point is assumed automatically by the system ^positions to
the left of the rightmost position in the field. This results in the number being stored in
memory with d decimal digits to the right of the decimal point. If a decimal point is
punched in the number field, the number is read as is, into memory, and the implied posi-
tion of the decimal point specified by The presence of a decimal point on
d is disregarded.
and ^can be any number between and w.
the data card overrides the implied position d,
For grammatical considerations, d must always be specified in the format even though it
might not be used.
In all cases d must be such that d < w. Blanks are treated as zeroes. One card column
must be reserved for the minus sign if the real number is negative, and another card col-
umn must be reserved if the decimal point is to be punched in the number field.
Once again it should be pointed out that w represents the number of columns to be
read. If a decimal point is punched in the field, this column is counted as part of the field
length vv.
Variables in the READ list that are described by an F code in the format must be real
variables.
Example 1
READ(5,5)A,B,C
5 FORMAT F5 5 F3 ( . , .
2 F2
, .
INTRODUCTION TO FORTRAN— PART 2 77
Example 2
READ 5 1 X Y
( , ) , ,
1 F0RMAT{F5.5,F3.2,F2.0:
78 INTRODUCTION TO FORTRAN— PART 2
Mixed-Mode Input
It is permissible to combine both real and integer variables in a READ list. The pro-
grammer must then make sure that the variable name in the READ list is properly de-
scribed by a format code of the corresponding type. If a real variable name is read, its cor-
responding format code should be F; if an integer variable name is read, its corresponding
format code should be I. If this is not the case, number conversion will take place, which
will change the value of the input data, thereby causing logical errors in the program.
Example
nX
where n is an integer specifying the number of positions to be skipped. The effect of the X
code is to skip n card columns (positions) between fields.
Example
MJ
READ(5,5)X,I,J X = 3.2 I = 230 J = 9
5 F0RMAT(4X,F2.1,2X,I3,1X,I1)
^ 3 d .^ fc. Z 3 .»^ y
4X 2X IX
The above example can be interpreted as follows: First skip four card columns, and start-
ing in card column 5 find a two-digit real number, then skip two card columns and find a
two-digit integer, then skip one card column and find a one-digit integer number. A com-
bination of both T and X can be used in the same format as in:
READ(5,7)X,I,J,Z
7 FORMAT TIO F3 2 2X
( , . . , I1 , 3X 12 T30 F4
, , , .
1
Card columns
80 INTRODUCTION TO FORTRAN— PART 2
Example 1 Example 2
- GO TO 5 6 READ (5, 10) GRADE
This code is
GO TO 6
Once again the reader is reminded that statement numbers need not be in ascending or de-
scending order; statement numbers, however, must be punched in card columns 1 through
5.
than or equal to 40, the next instruction (statement 12) is executed. A very useful form of
the logical IF statement is:
IF (logical-expression) GO TO statement-number
where logical-expression consists of two arithmetic expressions linked together by one of
the relational operators shown in Figure 3-4. The reader can think of a logical ex-
pression as a proposition, i.e., a statement which is either true or false. For exam-
ple, the statements "I am 36" and "X is less than 63" are either true or false. The
statement-number is the statement transferred to if the logical-expression is true,
that is, if the condition specified in the decision statement is met. If the condition
isnot met (result of the logical expression is false), control is passed to the state-
ment immediately following the IF statement.
FORTRAN
relational operators
INTRODUCTION TO FORTRAN— PART 2 81
IF (logical-expression) GO TO Sg
Si _
S2 E
Next statement
Note that Si immediately follows the IF statement whereas S2 can pre-
cede the IF statement or be anywhere after S,.
Example 1
IF(X.LE.63. )G0T0 5
Z=4
5 -^
Example 2
IF(Y.EQ.X)G0T07
Z=T
Figure 3-5 displays numerous examples of logical IFs and their meanings.
To better understand the logical IF statement and its interaction with other FOR-
TRAN statements in a program, consider the following examples:
Example 1
Read an integer number I from a card and determine whether 1 is even or odd. Since
integer division results in the truncation of all digits to the right of the decimal point, the
following is true:
c
Read a value I from card.
Is I even?
(E>
Yes. print message.
(D
INTRODUCTION TO FORTRAN— PART 2 83
logical IF Statements are required (see Example 2 and Figure 3-7). In that case it is advan-
tageous to use the arithmetic IF (Section 3-2-6).
Example 2
Read a number N and write a program to do the following:
c
Read the number.
No.
Write ZERO
and stop.
Yes.
Is it positive?
and stop.
and stop.
84 INTRODUCTION TO FORTRAN— PART 2
If N were zero and the two GO TO 15s were omitted, the message ZERO would be
written as a result of the WRITE(6,1 1): The computer would execute the next instruction
WRITE(6,22), which would write NEG, and finally the WRITE(6,33) would be processed,
printing the message POS. Altogether, three messages would be printed when in fact only
one should be printed. Note, however, that there is no need for a GO TO 15 after state-
ment 3 since the STOP statement is the next executable statement following statement 3.
There are many other ways to code the program in Figure 3-7. An alternative is
shown in Figure 3-8, which results in the STOP statement being in the middle of the pro-
gram.
c
Read the number.
Is it positive?
No.
Is it negative?
and stop.
and stop.
Yes.
Write POS
and stop.
INTRODUCTION TO FORTRAN— PART 2 85
Note again END statement last in the program, as should be, since de-
that the is it it
Read three numbers from a card and print out the largest value. If the three numbers
are equal, print either value. The flowchart and program are shown in Figure 3-9. Note
that in the case of statement 4 the IF statement transfers control directly to statement 3
whenever Nl < N3. The beginning programmer may be tempted to write the following,
which is correct, though awkward:
•3 LARG = N3
GO TO 10
2 GO TO 3
The logical IF is somewhat more powerful than has been previously shown. The general
form of the I F statement is:
IF (logical-expression) statement
logical-expression is true), the statement within the IF statement is executed. If the condi-
tion is not met (the value of the logical-expression is false), the statement is not executed.
In both cases control is passed to the statement following the IF. The logical IF can be vis-
r START ^
No. IF(N2.LT.N3)G0T0 3
Is second < third?
Yes.
Is first < third?
,^
— 4 IF(N1.LT.N3)G0T03
Stop. STOP
END
6
Examples
7
A
(true branch)
Yes
C = C + IF(A.GE.40)G0T0 5
D = [3 -I- I
D = D+ 1
S = S +
S = S + A GO TO 4
5 C = C + 1
4 -
IF(A.GE.40)C = C + 1
D=D+ 1
S= S+A
4 -
then in the event A > 40, statements D= D+ 1 and S = S + A would be executed in addi-
tion to C = C + 1 . This is clearly wrong.
The reader also should not be tempted to code the flowchart as:
IF ( A GE 40
. . ) C = C + 1 , GO TO 4
If A = B. process slalemenl 2.
The above nowcharl could be lake exit lake exit 2 Uike exil 34
visualized linearly as A : B irA<B if A = B if A >B
and translated
into FORTRAN as
IF(A-B' 11 2 .
34
INTRODUCTION TO FORTRAN— PART 2 89
It should be noted that the sequence of the three statement numbers in the IF statement
always corresponds to the sequence of relational operations: less than 0, equal to 0, and
greater than 0, in that order. The reader can visualize this sequence as follows:
< =0 >0
IF (expression) 1, 2, 3
The comparison of two numbers, A and B, in an IF statement can be made using the ex-
pression A — B as follows:
A - B <0 if or if A^ B, thengoto 11
In some cases a decision may require only a two-way transfer, in which case ap-
propriate IF statement-numbers can be combined as follows:
IF A - B
( ) 1 , 5 , if A = B, go to 5; otherwise go to 1 (unequal).
meaning
IF(A-B)11 ,11 ,4 if A< B, go to 1 1; otherwise go to 4 (greater).
IF slalements Meaning
IF statements
INTRODUCTION TO FORTRAN— PART 2 91
follow. Note the importance and necessity of the two GO TO 15 statements following
statements and 2.
1 If N were zero and these two TO statements were omitted, the GO
message ZERO would first be number 1, then the com-
written as a result of statement
puter would execute the next instruction at 2, which would write NEG, and then statement
3 would be processed, causing the message POS to be printed. Altogether, three messages
would be printed when in face only one should be printed. Note, however, that a GO TO
15 is not needed after statement 3, since the STOP instruction immediately follows the
WRITE statement in the flowchart.
Methods 2 and 3 also illustrate alternative FORTRAN programs. However, these do
not reflect a physical matching of FORTRAN statements with the flowchart blocks. Nev-
ertheless, they are correct. The important point to keep in mind is that the logical flowpath
in the jlawchart be preserved in the FORTRAN program. Whether statemet 1 or 2 or 3
follows immediately the IF statement is immaterial as long as the IF statement connects
these statements logically (if not physically) as shown in the flowchart.
Method 3 may appear to be incorrect at first glance as a result of the STOP statement
being in the middle of the program. This is not really so; the STOP statement generally can
be almost anywhere in a program.
Once again, the END denotes the physical end of the FORTRAN program (after the
END statement there are no more FORTRAN statements) and used by the compiler to is
stop translating the program into machine language, while the STOP statement comes into
effect at execution time to tell the CPU that processing (execution of the machine instruc-
tions corresponding to the FORTRAN program) is completed and that it is the (logical)
end of the program.
Another example will help illustrate the use of more than one IF statement in a FOR-
TRAN program.
Example 2
Read three numbers from a card and print out the largest value. If the three numbers
are equal, print the value. The program and flowchart are shown in Figure 3-1 1.
Note that in the case of statement 4, the IF statement transfers control directly to
statement 3 if N < 1 N3. This is perfectly valid, even though the beginner might sometimes
be tempted to write the following:
3 LARG = N3
GOTO 10
4 IF(N1 -N3)2,5,5 This statement could be replaced by IF(N1 - N3)3, 5,
'
f
2 GO TO 3 The GO TO 3 statement is not needed.
92 INTRODUCTION TO FORTRAN— PART 2
(^ START ^
No. 1 IF(N2-N3)3.2,2
Is second > third?
GOTO 10
GOTO 10
Yes. 4 IF(N1-N3)3,5,5
Is first > third?
Stop. STOP
END
FALSE TRUE
IF (condition) THEN condition
statement-1 statement-1
statement-2 statement-2
statement-n statement-n
ELSE
statement-a statement-a
statement-b statement-b
statement-z statement-z
ENDIF ENDIF
where statement-1 ,. etc., can be any FORTRAN statements except logical and
. .
are executed (all statements up to the ELSE word), after which control is passed to the
statement following the ENDIF statement. If the condition is false, statement-a, state-
ment-b, . . . statement-z are executed (all statements between the ELSE and ENDIF), after
which control is passed to the statement following the ENDIF statement.
Note the indentation of the statements within the IF/ELSE and ELSE/ENDIF in-
tervals to improve readability and comprehension. The ENDIF key word must be specifi-
ed if the IF/THEN option is used. The three key words of IF, ELSE, and ENDIF should
be aligned; a common practice is to set off the inner statements of the IF/THEN structure
at least four positions to the right of the IF, and ELSE key words.
One rule is that the ELSE and ENDIF should have no statement numbers, meaning
that one should not transfer (GO TO) either the ELSE or ENDIF statements.
1
Exjmple 1
;ad a number of hours worked and a rate of pay to compute an employee's pay check.
Write out the overtime pay if appropriate.
The ELSE key word in the IF/THEN structure can be omitted, which leads to the
simpler structure:
TRUE FALSE
IF (condition} THEN
statement-1 statement-
statement-2 statement-2
slalement-n
statement-n
ENDIF
-<?
"N; and control is passed to the statement following the ENDIF. \f\\i€'cdnJiti'on is false, con-
trol is passed to the statement following the ENDIF.
Example
If amount of sales exceeds $10,000, add aBONUS equal to 10 percent of SALES to PAY,
and print BONUS. If SALES is below $10,000, BONUS zero. In any event print out the
is
PAY.
INTRODUCTION TO FORTRAN— PART 2 95
BONUS = BONUS =
IF SALES GT 10000 THEN
( . . ) IF SALES GT 10000 GO TO 8
( . . )
The unstructured code could have been simplified somewhat by using the statement IF
(SALES. LE. 10000); however, this does not translate directly the phrase "If the amount of
sales exceeds $10,000 . .
." stated in the problem.
In many problems, making decisions depends on comparing more than just two operands.
Consider the following problem. A salesman is assigned a commission on the following
basis:
Under $500 2%
$500 and under $5000 5%
$5000 and over
Two different approaches to solving this problem, leading to two different nested struc-
tures, are as follows:
Approach 1
ENDIF
ENDIF
9- 9
WRITE (6,5) COM / WRITE com /
96 INTRODUCTION TO FORTRAN— PART 2
Yes
IF ( SALES. GE. 5000) THEN
ELSE
COM = 05 * SALES .
com = y'/c sales
ENDIF
ELSE
COM= .02* SALES
ENDIF
com = 2% sales
o
WRITE (6,5) COM / WRITE com /
Answer: Actually, the computer reads all 80 card columns into memory but only
selects and processes those fields described by the data format codes (I, F). By process-
ing, we mean converting each number into its proper internal machine representation
and storing it into the corresponding memory location described in the READ list.
2. Do I need to initialize a variable to some value before I can use that variable in a
GR =
READ(5,10)GR
Answer: No. The fact that GR is in the READ-list implies that a memory location will
be reserved for it.
3. If I know ahead of time A can never be greater than B, can I omit the third statement
in an arithmetic IF statement as in IF(A — B)l,2?
INTRODUCTION TO FORTRAN— PART 2 97
Answer: No. For grammatical reasons the arithmetic IF must always have three state-
ment numbers. Two of these statement numbers can be the same, of course.
4. What happens if during execution, my program needs to read data cards, but I forgot
to include all or some of them in may job deck?
Answer: The computer will read the end-of-file card and cause an execution error.
End-of-file checks are discussed in Chapter 4.
5. Suppose that at execution time my program reads numbers from data cards that have
been punched incorrectly. For example, suppose that punch an alphabetic character I
Answer: A READ error will occur, which will cause termination of your program.
6. What happens if I try to read an integer or a real number from a data card and the
data card is blank?
READ(5,10)X
10 FORMAT (F15.0: 12 3 4 5 6 7 8 9 12 3 4 5
Answer: The number of significant digits that can be retained for real numbers varies
depending upon the computer in use. Some computers have the capability for seven
significant digits, hence the number X might be stored as 123,456,700,000,000, thereby
resulting in an error of 89,012,345. See Chapter 6 for double precision and internal
representation of numbers.
9. Can I use the same format for more than one READ statement?
Answer: Yes. For example:
READ(5,5)I,J
READ(5,5)IPR0D
5 F0RMAT(I3,I3)
10. What happens if I write the following code?
I
READ(5,6)I,J,K
6 FORMAT (13, T2, 13, Tl, II) 13 9 8 4
IT J
11. Can you have more than one STOP statement in a program?
( ) )
IF(X.GT.O)GOTO 15
16 WRITE(6.12)
STOP
15 WRITE(6,11)
STOP
12 FORMAT 3X, 'X IS NEGATIVE
( '
END
Remember, though, you can have only one END statement, and it must be the last
12. When you read data from cards is it a good idea to immediately print out that data on
the output form?
Answer: Yes. In fact, it is strongly recommended that you print out all the original
data that your program is reading. The programmer can then verify the accuracy of
the input data, which can then be used for documentation purposes to anyone reading
the program who does not have access to the original data.
13. Was I surprised the other day! I knew I made a mistake, but the compiler didn't catch
it. I punched G0T051 instead of GO TO 51 and my program still ran. How about
that?
Answer: The compiler is smarter than you think. Spaces within FORTRAN state-
14. Since certain fractional numbers may not always be represented exactly in memory
owing to a binary representation of numbers, would K be set to 3 in the following ex-
ample?
Y = .5
X = .1 + .1 + .1 + .1 + .1
IF(X.EQ.Y)K = 3
IF(ABS(X - Y).LT.EPS)K = 3
where EPS = .01, .001, .0000001, etc., depending on the degree of accuracy needed,
and ABS is the symbol to represent the absolute value function.
Answer: WRITE(6,5)
'*'
5 FORMAT! IX, 132 )
INTRODUCTION TO FORTRAN— PART 2 99
16. Can more than one condition be treated in the same logical IF statement?
Example 1
To determine if AGE lies between 7 and 14, the following statement can be used:
Flowchart meaning
/ READ AGE /
Example 2
To determine if SEX equals 1 , or LIFE equals 10, the following code is used:
The operators .AND. and .OR. are called logical operators. These may be combined to
form logical expressions such as:
IF (
(SEX. EQ. LAND. MS. NE. GRADE) .OR. (SEX.EQ. 3. AND.MS.GT. 4) ) GOTO 1
input output
RiP
r^.|i|i|5 i|o|o|o|o|o 3|0
i N
COMPOUND INTEREST PROBLEM
I I I
F4.0 F6.2 12
INTRODUCTION TO FORTRAN— PART 2 101
C START ")
* '
ARE EQUAL TO F8 2 '
, .
that card is just for the programmer and consequently does not view it as a FORTRAN in-
struction and does not translate machine language. A C in card column causes
it into 1
QUADRATIC EQUATION
STOP
A C DISCRIMINANT
READ(5,10)A,B.C
flowchart. The annotation block is placed to the right of flowchart blocks as follows:
The broken line indicates the placement of the remark in the program. The FORTRAN
code for the above flowchart would appear as:
( ' '
GO TO 106
20 WRITE(6,102)
102 FORMAT (3X, 'SOPHOMORE'
GO TO 106
25 WRITE(6,103)
103 F0RMAT(3X, 'JUNIOR'
GO TO 106
30 WRITE (6, 104)
104 F0RMAT(3X, 'SENIOR'
GO TO 106
35 WRITE(6,105)
105 FORMAT (3X, 'GRADUATE'
106 STOP
6 FORMAT (II)
END
Example
READ(5,101)X,Y,Z
101 FORMAT (F4.0,F4.0,F4.0)
It is possible in such instances to recode the list of the format codes using a duplication
factor to specify the repetition of the format code. The following FORMAT statement is
101 F0RMAT(3F4.0)
Any data format code can be duplicated using the duplication factor. A more general
form for the I and F format codes is:
Example
FORTRAN code Data card Value stored in memory
I =0
READ (5,5)I,J,K,L,M |
J = 10
K = 9
In the preceding example, five numbers are to be read. Instead of writing 12,12,11,12,12, the
format list is made more compact by use of duplication factors 212,11,212.
Example
WRITE(5,5)A,J,B,K,L,M,N
5 F0RMAT(3X,2(F3.1,I2) ,3(2X,I1))
This format is equivalent to (3X,F3.1, 12, F3.1,I2,2X,I1,2X,I1,2X, II)
2 3
3-5-5 Continuation
A FORTRAN statement is often too long to fit in card columns 7-72. In this event a state-
ment can be co ntinued onto one or more succeeding cards. If any character other than_a_
blank or-zero is punched into card column 6, the statement on that card is treated as a con-
tinuation of the preceding line (card). For example, statement 101, shown in the following
example, is continued by placing an asterisk "*" in card column 6 of the continuation line.
Note that statement 101 itself has no continuation character in card column 6.
Example
I card column 6
3X AREA L0T2 IS
,
'
2X F8 1 ' , , .
Example
I
card column 6
100 X=Y+
Z+
Q
101 X=Y+Z+Q
Caution must be exercised when continuing a literal string within quotes in a FOR-
MAT.
Example
WRITE(6,11) r— column 72
1 1 FORMAT ( . . . ,
'
I DREAM OF THINGS THAT ^
INEVERWERE' )
3-6 EXERCISES
3-6-1 Self Test
1, Which of the following coding segments are valid? If invalid, state reasons.
c. READ(5,6)A,I,J d. READ(5,7)A,B,a -
6 FORMAT (F4. 5, 12, II) 7 F0RMAT(F5 2 I3,F4) . ,
e. READ(5,8)X,J,Y , f. READ(5,5)X.I
8 FORMAT (F3.1,F2jJ(f4) 5 F0RMAT(T5 ,F5 . 1 ,T2 12)
,
2. What values would be read for I,J,K, given the following READ statement with as-
sociated data card for the following formats?
3. You are to punch an input data file on cards with three fields per card.
a. Without punching decimal points on the data cards, specify the READ instruc-
tionand accompanying format to read the following numbers (four cards in all).
INTRODUCTION TO FORTRAN— PART 2 107
4. What values would be read for A,I,S as a result of the following READ operations?
5 FORMAT (F4.0, 12, 3X,F1.1) (a)
READ(5,5)A,I,S 5 FORMAT( T3,F4. 3 IX II ,F3. 1 . , (b)
^ , . . ,^ ^ 5 F0RMAT(2X,F2.1,I3,F3.0) (c)
""
r 5 F0RMAT(T2,F6.1,I1,F2.2) (d)
5. Simulate the output produced by the following program segments on the printout list-
a. READ(5,10)A,J,X,Z n a
)/— <^^^^ <^Q'""^" ^^ data card
^
10 FORMAT IX F3 2 T6 13 F4 2 F3
( , , , , ,
'
11 FORMAT T3 F4 1 2X F3 1 IX 13 F2
( , . , , . . , , .
)
b. READ 5, 10) A, I. J, C
( Card column of datacard I
10 F0RMAT(T2,F4.1,2X,I2,I1,F4.4;
C = 2*C I I
|2|.|4| I |3| |9|-|l|.|3| |
WRITE(6,11)C,J,I,A
11 FORMAT (TIO, 'RES=' ,F4. , IX ,2I3,F4. 2
7. What are some execution time errors you could expect as a result of a READ instruc-
tion? A WRITE instruction?
(a)
(C) (d)
(e) (0
(e)
(i)
INTRODUCTION TO FORTRAN— PART 2 109
9. Indicate the action taken by each of the following IF statements, given the following
two cases:
110 INTRODUCTION TO FORTRAN— PART 2
13. Write the necessary IF statements for the following decision blocks:
(a) (b)
IF(X-1. )3,3,5
READ (5,6) A
3 Y = 2
5 Z = 4.
6 FORMAT (F4.1)
16. Will a branch to 15 be taken as a result of the following code? What value is printed
forX?
1. Write a program to read two numbers on a card and print these two numbers and
their differences on one output hne. The output should be similar to:
b. Inches to centimeters: Double and add half: 40 inches: 2*40 + 20 = 100 cm.
c. Miles to kilometers: Add 60 percent: 100 miles: 100 + 60 percent of 100 = 160
km.
d. Pounds to kilograms: Take half and then some: 60 lbs: 60/2 = 30—10 percent of
30 = 27kgs. ^. l.&'-2:
V^^''
Write a program to read a Fahrenheit temperature, a number of inches, a number of
miles, and a number of pounds and convert to corresponding metric measures. Identi-
fy results with appropriate headers.
5. Write a program to compute and print the absolute value of a number X read from a
datacard. Recall the|X| = X if X > and|X = -XifX < 0. |
6. A student DPIOI has her account number in card columns 1-4 and three test scores
in
in card columns 1-19. The student's average is based on her two best scores. Starting
1
on a new page, print the student's account number and her average on one line and
the three test scores on another line (double-space) as follows:
7. Write a program to read two numbers, D and R. D is the balance due for a custom-
er'scharge account. R is the amount received from the customer. Compare these two
numbers. If they are equal, print the message "NOTHING OWED." If the amount
received is greater than the amount due, the customer is given credit toward his or her
account. Print out his or her credit balance. If the amount received is less than the
amount owed, the new balance computed by adding a 1.5 percent service charge to
is
Sale Commission
Write a program to read a sale (real value in card columns 25-29) and compute the
commission.
9. Write a program to print a balance sheet as shown in Section 2-7-2, problem 16 for
each of the following three companies for the month of May 1981. The data read for
each company should be entered at execution time using the READ statement. Use
the following tables for data.
INTRODUCTION TO FORTRAN— PART 2 113
12. Same problem as 1 1 except that the grade table differs and N can be 100.
14. Write a program to read three real values, and decide whether these represent the sides
of a triangle. (Hint: The sum of any two sidesmust always be greater than the third.)
15. Rewrite the program of problem 13 so that the three numbers on the data card can be
inany order. Your program will have to decide which side is the hypotenuse.
16. Change the program in Figure 3-11 to print out a message if all three numbers are
equal. Also change the FORTRAN code in Figure 3-1 1 to ensure that the three IF
statements follow one another in the code.
17. John Doe must decide whether to buy a house this year at relatively high interest rates
or wait until next year when interest rates are anticipated to be lower but when infla-
tion will have increased the cost of the house. This year he can buy a $50,000 house
with 10 percent down and the balance financed at 13.5 percent for 30 years. Next year
he can buy the same house for $53,000 with 10 percent down and the balance financed
at 3 percent for 30 years. Based on the total cost of the house (principal and interest),
1
should he buy now or wait? The formula to compute the amount of monthly payment,
M, given the principal, P, interest rate, /, and the time in years, T, is:
p.±
r.i2
18. A certain metal is graded according to the results of three tests. These tests determine
whether the metal satisfies the following specifications:
8, if it passes test and 7 if it passes none of the tests. Write a program to read a
1,
carbon content, a Rockwell constant, and a tensile strength, and determine the grade
of the metal.
114 INTRODUCTION TO FORTRAN-PART 2
as
home mortgages up to $60,000. The down payment schedule is
lowing scale:
Kilowatt-hour
0-300 5.00
301-1,000 5.00 + .03 for each kwh above 300
35.00 +.02 for each kwh above 1,000
1,001 -and over
years of service
22. Salaries at the
Corporation are based on job classification,
XYZ
same: percentage of
pay for all employees ,s the
education and merit rating. The base
to the followmg schedule:
the base pay is added according
Percentage of
Job base pay
classification
10
25
50
15
Percentage of
base pay per year
and calcu-
codes for each of the four variables,
Write a program to accept numerical
percentage of base pay.
late the employee's salary as a
INTRODUCTION TO FORTRAN— PART 2 115
23. The square root of number. A, can be computed by successive approximations using
a
the iterative formula .v„ + = (.v„ + A/.y„). This formula can be expressed in FOR-
,
'/:
IXNEW^ - A|<6
Write a program to read A and EPS (0 to compute v^. Write an error message if A < 0.
Can you rewrite the above simply by replacing and XOLD by one variable, X? XNEW
24. Systems of equations can be solved by iterative techniques. For example, the system
•V - 3.r = 2
''^-^
can be solved by solving for .v in terms of r in
the first equation and for r in terms of v in the
second equation to obtain:
.V= (3 - r)/2
y = (A- - 2)/3
Starting with aninitial approximate solution, XOLD = YOLD = 1, we refine this ap-
proximation by computing and XNEW YNEW as follows:
XNEW = (3- YOLD)/2
YNEW = (XOLD - 2)/3
This procedure is repeated by letting the old approximations become the new approx-
imations (XOLD = XNEW and YOLD = YNEW) and computing new values for
XNEW and YNEW in terms of XOLD and YOLD. The process can be terminated by
substituting XNEW and YNEW in the original equation and verifying that:
2XNL\V + YNLVV ^ 3 ^
2XNLW + YNEW -3^0 |2XNEW + YNEW - 3| < f
0^'^
XNEW - 3YNH\V ^ 2 XNEW - 3YNEW - 2 ^ XNEW - 3YNEW - | 2 |
< t
where e is a prescribed degree of accuracy {€ = .01, .0001, etc.). Can you rewrite the
above process more simply by substituting X for XNEW and XOLD? Write a pro-
gram to solve the following system of equations using the preceding iterative techni-
que:
25. Write a program to read values for a. h. c. d, r. s. and f, to solve the following system
of equations:
a • X =
-'r h ' \ r
c • X +d y = • .V
26. By extending the iterative technique to a system of three or more equations in three
unknowns (in the first equation compute x in terms of v and z: in the second equation
compute y in terms of x and z, etc.), write a program to solve the following systems of
equations:
X- >' + r + 5vv = 5
27. Determining the roots of a polynomial, v= P(a), implies finding values, a,, so that
y = P(a, ) = 0. a systematic method to determine a is presented as follows:
Siep 1 . Determine by visual inspection two values for X, i.e., XPOS and XNEG so
that P(XPOS) > and P(XNEG) < 0. This means that a root of P(X) exists in
the interval XPOS, XNEG, since polynomials are continuous functions and
the graph of r = P(a) must intersect the a axis somewhere between XPOS and
XNEG.
y M
P(XPOS)>0 possible graphs for y = P(X)
>X
P(XNEG)<0 -
Step 2. For the next approximation, X to the root, take the midpoint of the interval
XPOS, XNEG:
X =
XPOS + XNEG
Slep J. Determine whether P(X) > or P(X) < 0. If P(X) > 0, then the root must lie
between X and XNEG. If P(X) < 0, then the root must lie between X and
XPOS. Then go back to step 2 and recompute a new (refined) approximation.
=
X, making sure to replace XPOS or XNEG by X depending on the sign of y
P(X).
The above algorithm can be terminated when y = P(X) is "sufficiently close" to zero;
curacy.
Using the method described, compute a root of y = x' - 2x- + x - 16 in the interval
28. Using the method described in Exercise 27, determine a root of y = x^ + lOx- — 81 in
the vicinity of -3.5. Stop when |y |
< .001.
29. Each card of a deck of cards (unknown number of cards) contains the following data:
Freshman
n
1
2 Sophomore
3 Junior
Student ID Score Class Code 4 Senior
(0-100)
student ID
118 INTRODUCTION TO FORTRAN— PART 2
g. 3, 5,-46
3. a.
INTRODUCTION TO FORTRAN— PART 2 119
YES branch.
12. a. 1 ifZ < L 2ifZ> 1. b. 1 ifZ > .2, 2ifZ = .2, 3ifZ < .2.
b. IF(A LT.1)G0T0 4 or
IF(A GT.8)G0T0 4
IF(B.LT GO TO 4
IF(B.GT GO TO 4
GO TO 8
1
c. IF(X.GT.4)G0T0 1 or IF(X - 4) 12 12 , .
STOP 11 STOP
1 IF(Y.LT.5)G0T0 10 1 IF( Y - 5) 10 11 11
, ,
STOP 2 IF(Y-4)11,11,10
2 IF(Y.GT.4)G0T0 10
STOP
15. The statement following an arithmetic IF must have a statement number: otherwise
the READ statement will never be processed.
16. No. The value of X will not be exactly 1, because of fractional representation; how-
ever, the value of 1 .00 will be printed, because of round
id off.
V,
^5
•\Ij
A
4
THE COUNTING ^>;„/
PROCESS
Code Meaning
;
an isolationist response.
STOP STOP
(^ J
5 FORMAT IX ( , THE NUMBER OF PROISOLATIONIST STUDENTS IS '
, 2X 14
,
END
There are a number of statements in FORTRAN which are classed as specification state-
ments because they specify certain attributes of variables to the FORTRAN compiler. For
example, specification statements can be used to specify the mode of a variable (IN-
TEGER, REAL, etc.). Other specification statements will be introduced later.
All specification statements are nonexecutable (see Section 4-3, question 1) and
should be placed in the FORTRAN program deck prior to the first executable statement
(such as replacement, decision. READ, WRITE, etc.).
THE COUNTING PROCESS 123
INTEGER variable-list
REAL variable-list
Any variable included in the variable-list of the INTEGER statement automatically be-
comes an integer wherever it is encountered in the program, even though that variable
name may not start with I, J, K, L, M, or N. Any variable included in the list of the REAL
statement becomes a real mode variable.
Examples
INTEGER X,CODEl,QI,J
REAL I,J123, SUM
The variables X,C0DE1,QI would ordinarily be real but will now become integer. The
variables I,J123 would implicitly be integer but are now explicitly defined to be real. In an
input/output statement, an INTEGER specified variable should be described in the FOR-
MAT by the format code I and a REAL specified variable should be described by an F
format code in the FORMAT.
The first variable in the variable-list is associated with the first element in the constant-list,
the second variable with the second constant, etc.
Example
There must be the same number of variables as constants in the associated lists.
Example
The mode of the constant must match the mode of the associated variable. The following
DATA statement is invalid because of differences in modes between constant and vari-
able.
Example
^More than ox\qjariable-list / constant -list I can be included in a DATA statement. Repeti-
tions must be separated by a comma.
Example
DATA A B/3 , . , .
/ , I , J/l^^O/^^^Note comma required.
Example
INTEGER A
REAL I
DATA A, 1/1,-3. 2/
Finally, the DATA statement can include repetition factors. Suppose we wanted I, J, K to
be initialized to 0, and A, B, C, D to be initialized to -4.1. The following statement could
be used:
4-2-4 Counting
fore the programmer must resort to certain counting techniques. Consider the problem ex-
ample in Section 4- where it is desired to count the number of occurrences of the code 2.
1 ,
A variable acting as a counter, I in the example, is set (initialized) to zero before the count-
ing process starts. A CODE is read and tested to determine whether it is equal to 2. If
CODE equals 2, the statement I = I + 1 is processed; that is, the value 1 is added to the
counter I; that result then becomes the new value for I, reflecting the fact that another
CODE 2 has been found.
The statement I = I -I- 1 is of such paramount importance that we re-emphasize its
meaning:
1 = 1-1-1 means add 1 to I and call this the new value I, or the new value
for I is equal to the old value plus 1
Internally, this statement causes the computer to fetch the contents of memory location I,
add 1 toand store the result back into location I. This, of course, causes destruction of
it,
whenever CODE is not equal to 2, which means that for any value other than 2 the counter
I will not be incremented by Other examples of counting are discussed in Section 4-4.
1 .
An important application of counting is loop control. Loop control allows the programmer
There are many ways to solve this problem; we offer two methods, shown in Figures
4-2 and 4-4. In Figure 4-2 a counter is used to control the number of times a grade is read
and tested. The counter is initially set to zero and incremented by each time after the 1
READ statement.
In Figure 4-2 the statements 10 through 25 constitute a loop. To better visualize the
mechanism of the loop process, we can trace through the loop and, for each cycle through
the loop, record the values assumed by the different variables. A table of values can then
be constructed. This process is called tabulation. The table corresponding to the program
in Figure 4-2 is shown in Figure 4-3 withl the corresponding data deck.
126 THE COUNTING PROCESS
C START ^
Initialize counter for
grades above 90. C90 =
In Figure 4-4, the counter is initially set to 6 and is decremented by 1 each time by the
statement J = J - 1 after the READ statement. See Figure 4-5 for tabulation.
C90 =
Set up card count for
six cards to read.
J = 6
write it.
ate the even positive integers, the statement = + 2 is repeatedly used with set initially
I I I
to 0. To generate the odd-positive integers, the same formula could be used, with initially I
set to 1. The program shown in Figure 4-6 prints a 12s addition and multiplication table.
Numbers 1, 2, 3, 10 can be generated by the statement
• • •
,
= 1+1, with initially set to 1 I
0. There is no need to read these numbers from cards, since they can be easily generated.
Each time a new value is generated for I, it is immediately included in the computational
formulas 12*1 and 12 + I. The value of I is then compared to 10 to determine the end of
the program. A program to solve this problem is shown in Figure 4-6.
Q START J
Increment counter. 1 = 1 + 1 10 1 = 1 + 1
card, magnetic tape, or terminals. Data on such mediums is generally organized by fields:
for example, if data cards are used, a field is defined as a group of related card columns. A
field identifies a particular fact about an entity; a record is a group of related fields and
to read an unknown number of cards (records). Different methods exist to take care of
automatic
such a situation. In this section three end-of-file techniques are discussed: the
end of file, the trip record, and the last-card code techniques.
On some systems the programmer can instruct the computer to keep reading cards
until these run out; then, by a special READ statement discussed below, the computer
transfers control to a particular statement in the program to continue processing (for ex-
ample, to compute a grade average when all grades have been read). The computer auto-
matically senses the end of file (no more data cards to read) and is told where and what to
do when this condition arises (see Figure 4-7). Not all systems, however, have this auto-
Q STARTJ
/ RECORD/
PERFORM
PROCESS END OF FILE
RECORD PROCESSING
Q STOP
matic end-of-file processing capability, and the reader is advised to check with his com-
puter installation to determine the availability of this feature. Most systems, however, now
have the capability to detect an end-of-file condition, which allows the programmer to
transfer to a particular statement when there are no more data cards. In such cases the
programmer is relieved of the task of either counting cards or simulating an end-of-file us-
ing the last-card code method. The general format for the extended READ is:
R E A D{device-number.format-statement-number. EN D = statement-number)variable-list
where END is a keyword which identifies the statement number that the programmer
wishes to transfer to when an end of file is reached (no more data records).
EOF
Read key age. If no data / RHAD N /- READ (5, LEND = 40 IN
cards, write error message. 1 FORMAT! 13)
HOI
Read ages; when finished, / RHAD AG H / 13 READ (5,1 .END =33) AGE
print age count.
GOTO 13
r STOP
J STOP
r STOP STOP
END
Trip-Record Method
If the user's system does not support the automatic end of file, it is the user's responsi-
bility to inform the computer system when it is reading the last data card; otherwise, an er-
ror message will be printed by the computer if and when it reads, under control of the
user's program, an end-of-file card. An end-of-file card is that card which physically fol-
lows all data cards (on some systems it may be a card with * punched in card columns I
and 2, or it may be a card with an invalid character punched in card column followed by 1
a blank followed by END JOB or other codes, depending on the system used), in any
event, when a user program reads such an end of file, the program will be terminated at
once if the automatic end of file feature is not available or not used.
The program must, therefore, be made to simulate an end-of-file ctindilion. A spe-
cial end-of-file code, called a trip code, purposefully different from any of the data items
read, but in the same card columns, can be punched on the very last card of the data deck
and tested every time a data item is read. In the program of Figure 4-1, CODE is com-
THE COUNTING PROCESS 131
pared to 9 every time a data item is read. If it is not equal to 9, this means that the physical
end of the data deck has not yet been reached and hence more cards can be read. If, on the
other hand, CODE equals 9, this means that all the data has been read and an exit is taken
from the READ loop. (See statement 17 of Figure 4-1.) Again, this special code is called a
trip code and is placed on the last record (card). In the case of the program in Figure 4-1,
for example, each data item read represents a potential trip code. To select a value for the
code is easy; just use a value different than 0, or 2. This may not always be so simple,
1 ,
however. Consider a deck of data cards, each card containing one grade, where the grades
range from to 100; the value 9 for trip code is unsatisfactory, since it could then be in-
terpreted as a grade. Of course, an out-of-range trip value could be chosen. What about a
set of numbers of an unknown range? In this case the last-card code technique is used.
A widely used technique for end-of-file checking is to add to the original deck of data
cards a "last card,'' on which just one special last-card code (generally a numerical value)
has been punched (see Figure 4-9). This last-card code is punched in different card col-
umns from any it cannot possi-
of the original data fields that are to be processed, so that
bly be mistaken as one of the original data Then, every time a card is read, not only
fields.
are all of the original data fields read but also the last-card code (LCC) is read. The value
of LCC on all data cards except the last one is zero, since blank fields are interpreted as ze-
roes by the computer (see Figure 4-9). On the last data card, however, the value of LCC
will be nonzero. Hence, if LCC equals zero, this means that the end o{ the data cards has
not been reached and more cards still need to be read; if, on the other hand, LCC equals
the user-defined last-card code (99 in Figure 4-9), the end of the deck of data cards has
been reached, and a transfer to a predetermined ^itement in the program is effected.
Consider, for example, the following problem. A deck of data cards (unknown
number) contains demographical data on a small midwestern town. Each card consists of
three fields: a social security number, an age, and a sex field (see Figure 4-9(a)). The town
mayor wants to determine the percentage of the total town population of males over 90,
including the list of social security numbers of these people. A program to solve this prob-
lem is shown in Figure 4-9(b). Note that the check for last-card code is performed im-
mediately after the READ instructions lest the three blank fields on the last card (all zero-
es) be included in the processing of the data.
r START
J INTEGER SS. AGE, S
SS.AGE.S.IXC 3 READ(5.1)SS,AGE,S,LCC
7 1 F0RMAT(I9,I3,I1,T79,I2
>cs
Is It the last data card'.' IF(LCC.EQ.99)G0T0 6
Yes
IF AGE. LT. 90 GO TO 3
( I
Yes
IF(S.NE.1)G0T03
number.
/ WRITESS / WRITE(6,4)SS
4 FORMAT (5X, 19)
GO TO 3
/
^
WRIT! P 7
'
WRITE(6,7)P
'
7 FORMAT (12X,F6. 2:
STOP
(ZEiiD END
Case I. You are asked to process a predetermined number of cards N using the counting
method to stop reading cards (see Figure 4-10).
C START ^
C =
• > Initialize.
I
READ 7
Read the data off the card. Read card.
/ A,B ,F /
Case 2. You are to process an unknown number of cards using the last-card code method
(last card contains the last-card code and no other data). (See Figure 4-11.)
C~D
1 . initialize needed counters used for
\ Initialize.
processing of the data on the data card.
2. Read all the data, including the / RtAD 7 Read data and
last-card code. / A.B....C. LCC / last-card code.
Case 3. You are to process an unknown number of cards using the automatic end of file.
( )
I READ 7 EOF
2. Read the data. / (END=I5) /-^ Read data.
( )
Case 4. You are to process an unknown number of data cards using a trip (trigger) record.
The trip code is an original data item punched on all data cards which is tested for a value
known to be outside the range of the data item (see Figure 4- 3). 1
Q START ^
Note that processing will restart at the very beginning of the new record; in the case of out-
put, before the next record is printed, format control will look at the carriage control
code to determine what action to take in terms of vertical paper movement.
Example 1
WRITE (6. 5) J, K
1
5 FORMAT T5 12/ ( , ' ' , TIO 12 ,
Go to the next line and print J; this is the end of this record (line). Since another record is
to be printed check the carriage control code for the new record. Since it is a 1, skip to the
top of a new page and print K.
the format had been F0RMAT(T5,12/1X,12), then J would be printed on the next
If
line;and since the carriage control code starting the second record is blank (IX), the print-
er would advance to the next line and print K.
If the format had been F0RMAT(T5, 12/710,12), J would be printed on the next line;
and since TIO implies a blank for the first print position for the next record (carriage con-
trol), the printer advances one line and prints K.
THE COUNTING PROCESS 137
Example 2
WRITE (6, 5)
5 FORMAT (T50, 'JULY REPORT '/'+' ,T50 11 , 't '
)
JULY REPORT
Example 3
READ (5,3)A,B, I,J,X
3 F0RMAT(F4.1/F4.0,I2/I2,F5.0)
memory
A = 1.3
B = 2.1
I
= 11
J = 39
X = 5.6
are captured from the second card, while those for J and X are taken from the third data
card.
B
Four variables are to be written as four distinct records. The carriage control for the first
record blank as a result of iX so the printer spaces one line and writes the value for I.
is
The second output record is then processed and a "blank" carriage control character
causes the printer to space one line and print the value for J. Record 3 is then processed
and the printer double spaces and prints the value for K. Finally, the fourth record is proc-
essed, and the value of A is w ritlen at the top of a new page.
Example 5
First record
•Lnd of second record. Data was read from card but nothing was
transmitted to memory (no format codes on that record).
READ ( 5, 5) A,
FORMAT! F4.0//F4.0 Beginning of third record on which the number 4 is read.
A - 3.. B = 4.
In Example 5, three records are read. Any data contained on record 2 is read, but no data
on it will be transmitted to memory, since the record has no accompanying data format
code. The slash means end of the record; go to the next record.
Fxample 6
- - X X X X
WRITE ( 6, 6) A, B/ / / /
6 FORMAT (2X,F4.0 / / / 2X F4 , .
First line-*^
In Example 6, line 1 will contain the value of A, and the fourth record (line 4) will contain
B.
Example 7
Line 1
WRITE (6
7 FORMAT
140 THE COUNTING PROCESS
Unswer: I'll try! The nonexecutable statements that have been encountered so far are
END, FORMAT, INTEGER, REAL, DATA, while the executable statements have
been READ, WRITE, IF, GO TO, STOP, and the replacement statement. Nonex-
ecutable instructions are processed by the compiler and not by the CPU at execution
time. Executable instructions are those instructions translated by the compiler into ma-
chine language and then executed by the CPU. Essentially, nonexecutable instructions
are instructions to the compiler that do not get translated into machine language. The
END statement, for instance, is not translated into a machine instruction(s); it merely
informs the compiler that that there are no more FORTRAN statements to be trans-
lated (the physical end of the deck of FORTRAN statements has been reached). The
INTEGER specification statement is not translated into machine language but tells the
compiler that whenever an INTEGER-specified variable is encountered in the program
it is to be processed as an integer. The FORMAT
informs the compiler how to com-
plete the translation of the READ/WRITE instructions, etc. The statement X = 2. is
an executable instruction. It is translated into a set of machine instructions that causes
the CPU at execution time to store the number 2. in memory location X.
2. Is it possible to use the DATA statement to reset variables to specified values during
execution of a program?
Answer: No. The values of variables specified in a DATA statement are already set at
the beginning of execution of a program. The DATA statement is not an executable
statement and hence cannot be executed by the program to reset the values of variables.
To reset the variable, use a replacement statement.
3. What happens if there are no more records (cards) left to be processed when a READ
statement is executed?
Answer: An error message will be printed. On most systems the program execution is
cancelled at this point. The programmer should recheck his program to determine if:
4. Yesterday I wrote a program with ten data cards and the computer only read the first
5. If a DATA statement can be replaced by a replacement statement, why use the DATA
statement?
6. In the example of Figure 4-1 the counter was initialized to zero. Is this necessary?
Answer: It is necessary to initialize any variable used as a counter before entering the
program loop in which that counter is used. The value zero is generally used as the in-
itial value when the counter is used to count occurrences of specific entities (events).
Other values can be used when the counter is used for other purposes (see Section 4-4).
The counter should not be reset to its initial value within the program loop in which it
is used. Note that if a loop is to repeat a procedure ten times, for instance, the counter I
SECTION 102
GRADES
90
80
73
SECTION 103
Packet 1
GRADES
22
(33 grades)
32
ccl-3
10
Note the position of the FORTRAN STOP statement, it does not immediately precede
the END statement.
Q START ")
CT is used to count CT =
^ 15 CT =
INTEGER SECT, GR,CT
passing grades.
Is it over 60?
Yes; count it.
IF(GR.GT.60)CT = CT+1
No; is it last grade
in packet?
IF(I.LT.N)GOTO 10
Yes; readmore grades.
No; compute percentage.
PER = CT*100./I
Print it and start on
a new packet.
/ WRITE CT. PER / WRITE (6, 2 )CT, PER
GOTO 15
i 6 FORMAT
2
*T53. 'GRADES'
(
(
•
1
•
.
I
'
.
'
' ' . .
END
Figure 4-14 Computing Percentage of Passmg Cjrades.
THE COUNTING PROCESS 143
INTDUE = L*R*T/360
Write a program to read a dollar amount and an interest rate, and produce a table show-
ing the interest to be paid at the end of each month for a period of 12 months (assume each
month is 30 days).
A counter is needed to repeat the computation of the interest due 12 times, while T
must be incremented each time by 30. This can be achieved by the statement T = T + 30
with T = or T = 30, depending on whether T = T + 30 precedes or follows the computa-
tion for the interest. A program to solve this problem is shown in Figure 4-15.
In programs that make extensive use of integer and/or real variables, it becomes cum-
bersome to list all such variables in explicit mode declaration statements. For this reason
the IMPLICIT specification statement allows the programmer to formulate hisown con-
ventions for implicit mode declaration. For example, the statement IMPLICIT REAL (I)
would cause all variables with names beginning with the character I to be real. It is possi-
ble to specify a range of letters in alphabetical order in the IMPLICIT statement; for ex-
ample, the statement IMPLICIT INTEGER(A-D) would cause any variable beginning
with A, B, C, or D to be an integer variable. The general form of the implicit statement is:
Examples
In the first statement variables beginning with A, C, D, E, and F are implicitly integer; all
other variables are real. In the second statement, variable names starting with the letter A
or B become integer variables. REAL (C) does not change the mode C of since it is im-
plicitly real. The IMPLICIT statement must be they/>.s7 statement among other specif-
ication statements.
7
START
C 3
Write out headings. WRITE-LOAN"
f"RATE".'"MONTHS".i
"INTEREST DUE-
Increment month by I.
Add 30 to days.
LOAN RATE
1000.
THE COUNTING PROCESS 145
cords there are in the set. We want to draw a flowchart to print the highest grade. Since we
do not know how many records there are, we could add to the set of records a last record
with a negative grade on it, so that every time we read a record we can ask the question,
"Is the grade read negative?" If it is, it means the end of the set has been reached; other-
wise more records need to be read.
To determine the largest grade requires that we compare successively a new grade
with the highest grade found so far new grade read is larger than MAX, we
(MAX); if the
replace MAX by the new grade; otherwise we keep on reading grades until we find one
that is larger than MAX (if there is one). At the end of the program, MAX is the highest
grade. To start the comparisons we can set MAX equal to the first grade (after all, if there
were only one grade, MAX would be the highest score!). A flowchart with accompanying
tabulation is shown in Figure 4-16.
f START j
f STOP j MAX
XzL
(^
IK
CK
j^
38
146 THE COUNTING PROCESS
Another approach to solving the problem would have been to set MAX equal to zero
instead of reading the first grade into MAX. In this way, the first time we compared MAX
with the first grade read, MAX would be less than the first gradew)nce MAX is zero, and
as a result the first grade read would be stored in MAX. Using this approach, only one
READ statement is present in the flowchart.
1. a
f STAR I
THE COUNTING PROCESS 147
r START ( START
J
j
^'
( START
J
148 THE COUNTING PROCESS
y
THE COUNTING PROCESS 149
A deck of 16 cards contains one temperature reading per card which can be either
positive, negative, or zero. Draw a flowchart to print the count of positive, negative,
and zero temperatures to obtain a printout similar to the following (assume each
WRITE block causes just one line of output to be printed).
a.
TEMPERATURE
150 THE COUNTING PROCESS
C.
/ READG / / RHADG /
Q STOP ) (^
STOP ^
(^
START J Q START ^
X = X =
I = / RHADG /
/ READG /
THE COUNTING PROCESS 151
/
g-
Q START )
I =
/ READG / / READG /
6. Determine the number of cards read, the value printed for I, and the last value read for
G, given the following flowcharts with data cards as shown. Indicate whether an
end-of-file condition will occur (when the computer is instructed to read cards but there
are none left.
a.
^ START J Q START^J
I = I =
/ READCLCC /
' ' '
/j^'^
r99
/ST
p2
152 THE COUNTING PROCESS
d.
Q START ^ ^ START ^
I = I =
/ READGXCC / / RHADG.LCC /
r
THE COUNTING PROCESS 153
Q START^J
1 =
1 = 1 + 1
154 THE COUNTING PROCESS
r STARI
J ^ SIARi
j
I = 1
1 - 1
RH AD GR / / ri;ad(;r.lcc; /_Ei2£
^^ start ^^ START j
J
= I -
I
/ RKADGR.LCC: 7 1 = 1 + 1
EOF
/ RKADGR.LCC A
THE COUNTING PROCESS 155
2. a. 7. b. 10. c. 4. d. Infinite.
4. a.
/ RFADTHMP /
/ WRITETHMF' /
K = K + I
N = N + P= P+ I
156 THE COUNTING PROCESS
b.
c
THE COUNTING PROCESS 157
7. a, b,d.
4-7 EXERCISES
4-7-1 Self-Test
1. Complete each IF statement so that the program will read ten data cards.
a. 1 = b. 1 =
2 READ(5,1)J 'J
2 1=1+1
IF(II=1)G0T06 ^^'^ READ 5 ( ,
1 )
=1 +1
1
GO TO 2
6 STOP
1 FORMAT (12)
END
c. DATA 1/0/
READ(5,1)J
IFdCZI GO TO 5
GOTO?
1 = 1 + 1
GO TO 2
STOP
FORMAT (12
END
1 = 10
IFd l 1 GO TO 6
READ (5,1) J
1 = 1-1
GO TO 2
STOP
FORMAT (12)
END
K
4. A deck of cards contains an unknown number of cards, each card containing a number
between -99 and 99. Write the code to print the numbers read up to and including the
first number that changes sign. For example:
6 F0RMAT(F5.1/I3/F5.1)
i. The statement READ 5 7 I X K will read five cards.
( , ) , ,
7 F0RMAT(I1,F1.1,I2,F2.2,F3.3)
j. The statement READ 5 6 I J will read the same card twice.
( , ) ,
2. a. A data deck contains ten pairs of grades (one pair per card). Write a program to
compute and print out each pair and its corresponding sum. (Define your own
input/output formats.)
b. Suppose that the first record in the data deck contains the number of records
which follow. For example:
I
Three data records
.
position in the Mst (was it the fourth, seventh, etc.). Stop at the first out-of-sequence
number.
Example
10
1 Out of sequence , position 2
3
9
8 Out of sequence , position 5
4 Out of sequence . position 6
15
9. A data deck contains 100 numbers (one number per card). Write a program to read
these numbers, and stop whenever the number 4 (by itselQ has been read three times.
Print the total number of items read. (It is conceivable that the number 4 may not oc-
cur three times.)
10. Each data record contains two items: an age and a code for marital status (1 =
in a file
12. A data file contains 100 positive or negative numbers (one number per card). Write a
program to stop reading the file whenever two numbers of the opposite sign follow
one another. Print the total number of items read.
13. A deck of cards consists of an unknown number of cards. Each card contains two in-
tegers in card columns 8-9 and 78-79, respectively. Count the occurrence of positive,
negative, and zero numbers. Print all numbers read and their corresponding counts
using the following format; for example:
|6
THE COUNTING PROCESS 161
14. Write a program to print out multiplication tables from 2 to 10, as follows.
MULTIPLICATION
Top of new page
Note the
blank lines.
16. The number e can be defined as the limit of (1 + 1/n)" as n gets larger and larger.
Write a program to approximate a value for e. Stop when the difference between two
successive approximations is less than .001 . Print out the values for e and n.
*******
17.
*******************************
*******
^* * *
*******************************
*******
* * *
*******
*
*******
* 4f
*******************************
* * * *
*******
*******
*******************************
*******************************
18. Write a program to produce the following comparative mortgage tables for principal
varying from 50,000 to 100,000 dollars in steps of 10.000, given varying interest rates
from 9.50 to 12.50, in increments of .25 and duration of 20, 25, and 30 years.
P ' 1
12
M =
\ T. 12
P is the principal. 1
19. Same problem as Exercise 17 except that the interest and principal are read from
cards.
20. Each employee working at Slimpower, Inc., is paid at a regular hourly rate of $5.00
40 hours. The overtime rate is 1.5 the regular rate. The number of hours
for the first
worked by each employee is punched into card columns 1-4 on a data card (two deci-
mal positions are assumed, with no decimal point punched in the field.)
a. Write a program to compute each employee's pay and produce an output similar
to the following:
b. Same as part a, except that the number of hours and the rate of pay are read from
data cards in card columns 1-4 and 7-11. Also 6.1 percent of each employee's pay
for the first 30 hours is subtracted from the gross pay. The produced output
should be similar to:
c. Same as part b, except that a bonus amount is recorded for each employee on the
data cards in card columns 15-18 as a three-digit integer number. If the employ-
ee's pay exceeds $500, the bonus is added to the employee's pay; if not, the bonus
field is left blank on the output, as follows:
d. Same as part a, except that overtime hours are converted into corresponding regu-
lar hours. For instance, 10 hours of overtime at time-and-a-half rate of $8.00 per
hour is equivalent to 15 straight hours (regular hours at $8.00 per hour).
21. Read 30 grades already sorted in ascending order and compute the mode. The mode is
defined as the score which occurs most frequently. For example, given the grades 10,
15. 15, 17, 17, 17,20, 21, the mode is 17.
22. Read N grades (one per card) already sorted in ascending order (N is to be read from
the first card) and compute the median. The median is that mark that divides a dis-
tribution of scores into two equal parts. For example:
11 -I- 12
10,11,12,13 The median is -, = 11.5
23. Write a program to make Each data card should contain nine
daily weather reports.
integer values giving the following information: current month, day, and year; high
temperature for the day, low temperature for the day; year in which the record high
for this day was set, record high temperature; year of record low, record low tem-
perature. After reading a data card, print a message of one of the following four types,
depending on the data.
1 10/23/76
Stop reading data cards when you come to one with a month number of zero.
24. Management of any group of people is made more complex by the many types of rela-
tionships between the manager and his subordinates and among groups of sub-
ordinates. There are three types of relationships.
a. Direct single: the manager relates directly to each subordinate. The number of
these relationships is equal to n, the number of subordinates.
b. Direct group: the manager relates to each distinct group of subordinates. The
number of these relationships is 2" — 1 .
.
c. Cross: each subordinate relates to other subordinates. The number of these rela-
tionships is n{n — 1).
The total number of relationships in the group is 2" + n- — 1 Write a program to cal-
.
culate the number of direct single, direct group, cross, and total number of rela-
THE COUNTING PROCESS 165
tionships for 1 to 50 subordinates. Have your program print these in tabular form for
each number of subordinates in the range specified. The mode used for the variables
in this program will have a significant effect on the results produced. Try using all in-
teger variables, then all real variables. Which results are the most useful?
25. Write a program perform octal counting up to 27^, that is, print the numbers I,
to 2,
• •
,7, 10, 11 , • •• ,
•• -,27. Can you generalize your program for counting
17, 20, 21 , in
26. A wholesaler accepts a $5,000 promissory note from a retailer at 10 percent in lieu of
cash payment for delivered goods. Write a program to compute the maturity value of
the note for a 30-, 60-, and 90-day short-term loan. (Formula for maturity value S =
is
P{\ + /• IV). S is maturity value, P is principal, / is interest rate, and A' is the number
of years, or, if less than 1 year, number of days/360.)
27. The simple discount is the amount deducted from the maturity value 5" (see Problem
26 above) of an obligation when the latter is sold before its date of maturity. The for-
mula is SD = S • D • N where SD = simple discount, S = maturity value, D= dis-
count rate, and N = term of loan, that is, time remaining before maturity.
A wholesaler receives a $10,500 promissory note for goods sold to a retailer. The
note matures in A' months and bears an / percent interest rate. One month later the
wholesaler sells his note to a bank at a 9 percent discount rate. Write a program to
compute:
a. The maturity value of the note for N = 30, 60, and 90 days with interest rate of /
= 4 percent, 5 percent and 6 percent. That is. A' = 30 for / = 4 percent, 5 percent,
and 6 percent. A' = 60 for 1 = 4 percent, 5 percent, 6 percent, and so forth.
b. The proceeds received by the wholesaler as a result of selling the note to the bank
for A' = 30, 60, and 90 days with interest rate of 4 percent, 5 percent, and 6 percent
respectively.
28. Ms. Small is thinking of borrowing $5,000 to purchase a new automobile for A^
months at a 12 percent simple discount rate. Write a program to compute the pro-
ceeds of this loan for the following values of A': 6 months, 1 year, 2 years, and 3 years.
The proceeds (P) is thesum remaining after the discount is deducted and is given by
the formula: P = S{\ - SD- N) (see Problem 27 above).
29. The Kiddie Up Company manufactures toys for adults. The company expects fixed
costs for the next year to be around $180,000. With the demand for adult toys increas-
ing, the company is looking for sales of $900,000 in the year to come. The variable
costs are expected to run at about 74 percent of sales.
a. Write a program to determine the breakeven point (BEP) (the dollar amount of
sales that must be made to incur neither a profit nor a loss), and compute the ex-
pected profit. The formula to compute the BEP is
The Kiddie Up Company management is arguing that with the current rate of in-
flation, variable costs will run higher for the next year — probably anywhere from
75 to 83 percent of sales. With sales still projected at $900,000, the management
directs its DP staff to generate the following report to determine the breakeven
point and the profits and losses for varying variable costs. Sales and fixed costs re-
main constant.
KIDDIE UP COMPANY
Operations Forecast 1981
• 76 • • •
900,000 180,000 83
Write a program to complete the above report. Place three stars (***) in the profit
column if there is no profit. Do the same for deficit.
c. The company employees have just won a new contract. As a result, variable costs
30. XSTAR is a small company supplying major auto parts companies with a single item.
The total fixed costs to run the company amount to $40,000 per year. The company
has had a steady dollar breakeven point value (BEP) for the last three years, and the
president of the company would like to keep his BEP at about the same level of
$1 17,647 for the coming year. To test several options, the president believes the selling
price per item could range anywhere from $1.10 to $1.30; however, he feels certain
that the variable cost per item should not fall below $.75 nor exceed $.83. To help
crystallize the president's thinking, write a program displaying different combinations
of selling prices ($1.10 to $1 .30 in increments of one cent) and corresponding variable
costs, all yielding a constant BEP of $1 17,647; that is. generate a table with headings
as follows:
1.30 117,647
THE COUNTING PROCESS 167
If the variable cost per unit falls outside the interval of $.75-5.83, state in the decision
column that the variable cost is either too low or too high. The formula to compute
the BEP is given by:
31. One method for calculating depreciation is to subtract a fixed percentage of the ori-
ginal value of the item each year. Thus $100 item depreciated at 10 percent would be
a
valued at $90 at the end of the first year, $80 at the end of the second, and so forth.
Another method for calculating depreciation is to subtract a fixed percentage of the
present value of the item. A $100 item depreciated at 10 percent would be valued at
$90 at the end of the first year, $90 - X 90 = $8 at the end of the second year, and
. 1 1 ,
so forth. Write a program to accept as input the original value (V), the depreciation
rate (R), and a number of years (N), and produce a table showing the value of the
items for the first, second, third, • • •
Nth year using both depreciation methods.
32. You have been Naddor, Inc., a world-famous firm specializing in inven-
hired by E.
tory control problems, to write a computer program for one of Naddor's largest cus-
tomers. The Shopping Basket. This firm would like to computerize part of its reorder-
ing system to cut down on the cost of replenishing inventories.
Each Friday at the close of business, the ending inventory of each product is com-
pared to the fixed reorder point for that product. If the ending inventory is equal to or
below the reorder point for that product, The Shopping Basket orders enough of the
item to bring the amount on hand up to a predetermined order level. Any order placed
on Friday is delivered over theweekend so that the company can begin a new week of
business with well-stocked shelves. It is possible that the ending inventory could be
negative, indicating that demand exceeded supply during the week and some orders
were not filled. Shopping Basket policy is to order enough to cover this backordered
demand. See inventory summary below.
Your task is to write a program to read five data cards corresponding to the five
different products to determine which products must be ordered and how much of
each product to order. The program should also calculate the cost of ordering each
item and the total cost for all products ordered. Design the program to make the cor-
rect reorder decision for an unknown number of items.
To aid you in your task, you have been given some old records that illustrate how
the reorder system works. You should use the sample data in the following Inventory
Summary to test your program. Note that the only output required from your pro-
gram is an Order Report similar to the one shown here.
a. Order an item only if the ending inventory is less than or equal to the reorder
point for that item.
Item number
THE COUNTING PROCESS 169
2. a. Implicit mode specification uses the first character in a variable name to define the
mode of the data; exphcit mode specification uses one of the mode specification
statements to specify the mode of a variable.
b. INTEGER BETA,GAMMA
REAL KOUNT,MODEM
c. The DATA statement is used to specify the initial contents of a variable. It is not es-
sential because replacement statements could be used in place of the DATA state-
ment.
d. The IMPLICIT statement allows the programmer to define his or her own rules for
implicit mode definition. It is not essential since the explicit specification statements
can be used.
3.
5
THE ACCUMULATION
PROCESSA^ rT- nO<^
the FORTRAN DO statement used in the program in Figure 5-1 that is used to generate
the numbers 1, 2, 3,4 • • • N.
This chapter also discusses the accumulation process (statement 10 of the program in
usual procedure for loop control is to iniliali/e a counter to a certain value, then increment
that counter by a constant, and finally compare the counter to a terminal value for loop
exiting. With one DO statement, the user specifies the initial, the increment, the terminal
value of the counter (index), and the range of the DO, within which all statements are to be
processed a specific number of times.
170
THE ACCUMULATION PROCESS 171
(^
start)
zir.
Start the counter.
the sum.
/
> D010I = 1.N
L ^^ / 10 SUM = SUM + I
Increment the counter,
I
j
r 1=1+1 K /
,
/
/
and
I < N, go back and
I to
print the result
stop.
SUM; otherwise
and
L_£ -<-^
X
WRITE /
/
/ N.SUM /
I : N >
2
WRITE (6. 2 )N,
FORMATdX, 'SUMOFFIRST'
*I4, 'INTEGERS IS' ,18)
STOP
SUM
STOP END
c 3
Flgure5-1 Sum of N Integers.
where statement-immber is the number of the last statement in the body of the loop; some-
times called the/oo/ of the loop.
Index is an integer variable name sometimes called the DO variable, which essen-
tially counts the number of times the body of the loop will be executed. In many
FORTRAN compilers the index may be a real variable.
Initial is a positive integer constant or integer variable specifying the initial value of
the index. In many- FORTRAN compilers initial can be an arithmetic expression
(integer or real).
Test is a positive integer constant or variable against which the index is tested to de-
termine whether or not an exit should be taken from the loop. In many FORTRAN
compilers test can be an arithmetic expression (integer or real).
It should be noted again that the above "invalid" DO statements would be valid in recent
FORTRAN compilers. The readers should check with their technical FORTRAN referen-
ce manuals to determine whether initial, test, and increment can be arithmetic expressions.
The DO statement can be visualized by a flowchart as follows:
effect of the
(For recent FORTRAN compilers see question 2 in section 5-3.)
r"
1
DO 10 INDEX = INIT,ITEST,INCR
statement— 1
Body or range
statement-
of the loop
statement- /? -I-
THE ACCUMULATION PROCESS 173
It should be noted that the body of the loop will always be processed at least once.' X'O'
Note also that the DO statement itself is not part of the range but merely identifies the
statement following the DO as the first statement of the range. The statements within the
body of the loop can be any type of executable statements (IF, GO TO, DO,
Input/Output, etc.). The foot of the loop cannot be a STOP, an arithmetic IF, a GO TO, a
computed GO TO, or another DO statement or END. It can be a logical IF, however.
The statements in the range of the DO loop (statements 1, 2, 3 n) are repeated • • •
once for each value of the index, starting with the initial value up to the test value in steps
of the increment specified. Each time the foot of the loop is processed, the variable IN-
DEX is incremented by the incremental value INCR and tested. If INDEX is greater than
the test value ITEST, the statement following the foot of the loop is processed (the loop
has run through its complete cycle). Otherwise, control is transferred to the first statement
of the loop (statement- 1 in the above diagram). Another interpretation of the DO loop is:
Example 1
Statement number specifying Index Starting value Test value Increment value
the last statement of loop. of index. for index. for index.
DO 90 303
To improve readability, the body of the loop is set off at least two positions to the right of
all other FORTRAN statements.
All statements in the body of the loop (statements 15 and 90) will be processed 303 times,
as J ranges from the starting value of 1 to the terminal value of 303 in steps of 1 . Each time
the statement at the foot of the loop is encountered, the statement is executed and the loop
index J is incremented by the increment value (1 in this case) and compared to the terminal
value (303 in this case). If it is less than or equal to the terminal value, processing resumes
at the beginning of the body of the loop (statement 1 5); otherwise, the statement following
the foot statement is processed (statement 25).
Sometimes it is convenient to use the index not just as a counting mechanism for loop
control but also as a variable (number generator) within the body of the DO loop, as in
Example 2.
Example 2
Example 3
The initial, terminal, and increment values can all be expressed with variables (see Exam-
ple 4).
Example 4
READ 5 1 N M INC
( , ) , , See Section 5-3 for the number of times the body of the
DO 16L = N,M,INC loop will be executed.
Ll6
5-2-2 DO Don'ts
A. The last statement of a DO loop must not be:
• An arithmetic IF statement.
• Another DO statement.
• A STOP statement.
• A computed or unconditional GO TO.
• A nonexecutable statement.^
B. The index, the beginning value, the terminal value, and the incremental value cannot be
changed within the DO loop. If these are changed, unpredictable results will occur. For
example:
— DO 15 J = 1 ,
10^^3_^^ Invalid.
J = T + !-* '
The value of the index is changed.
-15 S = S*J
C. Do not count on the last value of the index to be equal to the test value specified in the
DO statement upon normal exit from a loop ("normal" meaning not transferring pre-
maturely out of the DO loop before it has completed its full cycle). The value of I in
that case is undefined. Consider the following, for example:
DO 5 1 = 1,10 ^Undetermined.
1-5 WRITE(6,6)I ^^
y^ The loop will print
p 1,2,3. .. 10.
WRITE (6,6) L^ I
' is
'^^ not defined in this
"°^ th case, since the loop has completed its full
cycle i.e., exit of the loop is made through the foot of the loop.
This does not mean that if an exit is made out of the loop before the loop has com-
pleted its full cycle then the value of the index is undetermined. The index will have
whatever value it had at the time of the exit. Consider the following example:
LlO X = X-t-l
Incorrect code
c = o
THE ACCUMULATION PROCESS 177
Example 2
c = o.
178 THE ACCUMULATION PROCESS
Case 3. Transfer can be made from one statement to another within the same loop.
— DO 70 J = 1,1000
IF(X.NE.1)G0T0 50,
Permissible.
50 Y = 2*J
1-70 CONTINUE
Case 4. Transfer can be made from a statement in the loop to the foot of the loop.
IF(X.NE.1)G0T0 100,
LlOO CONTINUE
Case 5. Transfer from a statement within a loop to a statement outside the loop is per-
missible.
L-IO CONTINUE
70 DO 15 1 = 1, JOE
Case 6. A transfer from within a DO loop to the DO statement itself will cause a re-
initialization of the index rather than a continuation of the loop process. The following
code will result in an infinite loop:
p4
THE ACCUMULATION PROCESS 179
DO 5 J = 6,10 6* 6 =
DO 7 K = 6,12
KPROD = J*K
WRITE(6,1)J,K,KPR0D
L? CONTINUE
separate each set of tables from
WRITE(6,2) one another by a blank line.
1-5CONTINUE
STOP
1 FORMAT (2X, 12, ' ,12, '=' ,13:
2 FORMAT (/)
END
THE ACCUMULATION PROCESS 181
Counting Accumulating
c = c + I
READ
/ GRADt
count.
A complete program will help clarify the accumulation process. Five test grades are
punched on cards, one grade per card. The program shown in Figure 5-3 computes and
prints out the average of the five grades.
END
Note the importance of setting SUM initially to zero outside the loop, and note how
sums of grades are formed each time a GRADE is read, using the statement
the partial
SUM = SUM + GRADE. The statement Y = SUM + GRADE would noi accumulate a
sum.
The accumulation process in the program of Figure 5-3 can be better understood or
visualized if we tabulate the values of SUM and given sample grades as follows:
1
70
60
Input data
THE ACCUMULATION PROCESS 183
Example 2
= -8 < 0.
7 X= l
Example 3
5 CONTINUE
3. Can the CONTINUE statement appear anywhere other than at the foot of a DO loop?
Answer: Yes, if it is not used at the foot of a DO loop, the CONTINUE statement
passes control to the next statement in the program.
centage note the division by I — since the last grade read is a trip record, not a grade to
1
be averaged out. Exit from the loop is made by transfer and not through the CONTINUE
statement, hence the value of I is well defined.
If no trip record or last-card code were used in the program of Figure 5-4 and there
happened to be fewer than 100 cards, an end-of-file error condition would occur at the
READ statement, since the DO loop would instruct the computer to read 100 cards.
10 CONTINUE
15 PERCEN=K0UNT/(I-1. )*100 Compute percentage of passing grades.
WRITE (6,1) PERCEN KOUNT , Write results.
5-4-2 Calculation of N!
N! is read as N factorial. The factorial function N!, where N is a positive integer, repre-
sents the product of the first N positive integers, starting with one. For instance, 15! =
1.2'3 • • •i4«15. The program in Figure 5-5 computes N! where N is a number read from a
data card. Note that in this case the numbers 1,2,3 • •, N are not read from data cards but
are generated internally by the DO index I. Every time a new value is generated for I, it is
f* 4 FORMAT! IX, 'FACTORIAL' ,13. 'IS' ,116) The factorial function produces rapidiv grow-
STOP ing results in terms of magnitudes. Most sys-
END terns cannot express 7! as an integer result. 1
SD = /n{.\] + xl + A-^ + • • •
+ A-;) - (a, + .V: + .v, + • • + .v,,)"
y n{n-\)
Write a program to read at most 30 grades from data cards (one grade per card) and
compute the average and the standard deviation. To compute the standard deviation, it is
necessary to:
1. Accumulate the sum of the grades (.v, + .V2 + • • + a,,) where // is the number of grades.
2. Accumulate the sum of the square of each grade (.v, -I- .xs + • • •
xl).
The program to solve this problem is shown in Figure 5-6. Note how the number of grades
read is determined by using the automatic end-of-file READ feature.
SUM = 0. Sum of the grades.
SUMSQ = Sum of each grade squared.
DO 5 K = 31 1 . Force the DO loop to read the end of
READ (5.1. END = 8 GRADE ) Tile card: this way a transfer out of the
SUM = SUM + GRADE loop will be made, and the value of the
SUMSQ = SUMSQ + GRADE* '2 index K will reflect the number of
5 CONTINUE cards read (includes the end of file).
DEV= (
(N*SUMSQ-SUM**2)/(N*(N- 1) )
)** 5 Compute standard deviation.
AV = SUM/N
WRITE(6,2)DEV.AV
STOP
2 FORMAT (T9, STANDARD DEVIATION = ' '
.F5 2//T9. '
AVERAGE = '
,F51)
1 FORMAT (F5 1)
END
The general formula to compute an approximation lor the sine of.v. where x is the radian
measure of an angle, is given by:
Write a program to give the approximate the sine of any angle between zero degrees and
1 80 degrees, given the radian measure of the angle. To compute the sine, it is necessary to:
2. Accumulate the sum (or difference) of the odd powers of x divided by the odd
factorials.
The most straightforward approach, though not the most efficient, is illustrated in method
I For every term of the approximation, the factorial function is recomputed from scratch
.
— and so is the raising of x to the odd powers. Methods 2 and 3 display a more efficient
and a much more "clever" code to solve the same problem. Study carefully these two
methods to see how they "work."
Mclhod I
5-4-5 Reports
The observation that computer-produced reports should be easy to read, easy to under-
stand, and attractively designed appears so evident that one might feel this subject war-
rants no further comment. Yet the physical appearance of a report is of dramatic
importance. Decisions are made daily by people of all walks of life that are based on
—
computer-produced reports detailed reports, summarized reports, etc.
A "good" report is one which is self-explanatory (accurate, obviously), self-
contained, and organized in a way that allows the reader to capture the essence of the
report as well as the detail. These characteristics should be reflected in a design that is
neat, clear, and pleasant to the eye. It is impossible to list all ingredients that comprise an
ideal report; a partial list, however, follows:
2. Subheadings: Titles or labels should be provided for each column of information listed.
Example
The director of the computing center at XYZ University needs to compile the number of
program runs by students every month. Each card of an input card file contains a student
number, a date, and a number of program runs. Cards are already sorted in sequence by
student number; i.e., all records for a given student occur in a group. Let us write a
program to produce a report that will not only summarize the total program runs for all
students but also for each individual student. Both the input and output are shown as
follows:
Input Output
The totals for each student are called intermediate or minor totals.
The basic idea in producing this type of report is to keep accumulating a minor total until
a change occurs in the student number. If the record read belongs to the same student as
the preceding record, the number of program runs read is added to the current minor
total. If the record read pertains to a new student, a control break has been found. At this
point the minor total for the previous student is printed and the accumulator for the new
minor total is set, to zero.
The decision as to whether the student just read belongs to the current group or to a
new group is made by storing the current student number in OLDNUMBER before the
next student number is read into NEWNVMBER. These two variables are then compared.
If they are equal, the record belongs to the current group and the new number is moved
into OLDNUMBER; otherwise, if they are unequal, a control break has occurred.
To comparison process going between OLDNUMBER and NEWNUMBER,
start the
there are two methods, presented in Figure 5-7 and Figure 5-8. Method in Figure 5-7 1
reads the first record separately from the remainder of the records; both OLD and
NEWNUMBER are initialized to the student number read from the first card. Method 2
in Figure 5-8 reads the input file with only one READ statement and uses a switch (ex-
DO 80 J = 3,22,2
i
r J = 3,5,7 21 22 is the test value.
statements in loop
L
188 THE ACCUMULATION PROCESS
^ TOTAL =0
SUBTOT =
TOTAL accumulates number of runs by all students.
SUBTOT accumulates number of runs for each individual.
Read a student number and call it NEWNUMBER.
cedure involves comparing two succeeding student numbers, we
Since the pro-
READ NtWNUMBLR
DATE. PROGS
need two different names for the student numbers — one for the
previous (old) student number and the other for the new student
number.
OLDNUMBtR = NHWNUMBtR To start the comparison procedure we initialize the previous stu-
dent number to thenumber read from the first card. The first time
offcour.se these two numbers will be equal.
IS NEWNUMBI R k The first time through the procedure the two numbers are equal, so
we add PROGS to both TOTAL and SUBTOT and print out that
OLDNUMBER
first record; in fact, we want to do this whenever the previous
£ number equals the new number, that is, when it is the same stu-
dent.
WRITE SUBTOr
7 If the number read is different than the preceding one, this means
WRITE NEWNUMBER Whether or not the numbers are the same we compute a new TO-
DATE. PROGS TAL and SUBTOT and print a complete line with student number,
date, and number of runs.
READ NEWNUMBER Finally we read another card. If the end of file is encountered we
DATE. PROGS print the last student's subtotal and overall total; otherwise we go
back to process the information on the card that was just read.
URITE TOTALS
7
(Z_)
V
TOTAL =0
SUBTOT =
1 , ) )
TOTAL =
SUBTOT =
WRITE(6,1)
WRITE (6. 9)
OLDNO = NEWNO
6 IF OLDNO. EQ. NEWNO) GO TO 5
(
GO TO 6
8 WRITE (6. 9)
WRITE 6 7 SUBTOT TOTAL
( . ) .
•
STUDENT T17 DATE T26 RUNS T35 TOTALS
, , ,
9 FORMAT ( )
STOP
END
TOTAL =
SUBTOT =
SWITCH =
WRITE (6,1)
WRITE (6, 9)
IF(SWITCH.NE.0)G0T0 10
SWITCH =
OLDNO = NEWNO
10 IF OLDNO. EQ. NEWNO) GO TO 5
(
GO TO 6
8 WRITE(6,9)
WRITE 6 7 SUBTOT TOTAL
( . ) ,
• .
' .
.
9 FORMAT ( )
STOP
END
J = 3
Yes
-(j = 3^;7 .
22)
PROCESS
BODY
PROCESS
OF LOOP
BODY
OF LOOP
J = J + 2
£
PROCESS STATEMENT PROCESS STATEMENT
FOLLOWING FOOT FOLLOWING FOOT
Consider the following problem: The principal, P, left in a savings account for T years
at interest rate R, compounded yearly, yields a total amount, A, given by the formula
A = P( 1 + R/. Write a program to compute a total amount, A, given a principal of $ ,000 1
at different interest rates varying from 5 to 8 percent in steps of 1 percent for a time period
of one to three years. Document your program with an appropriate flowchart (see Figure
5-12).
the corresponding list of variables in the READ/WRITE statement, the unused data for-
mat codes are ignored.
Example 1
READ(5,5)IX,IY
5 F0R1VIAT(I3,I2,I4,I5)
) ;
' ,
,
'
P =1000
DO 40T = 1,3
DO 35 IR = 5,8,1
R = IR/100.
A = P*(1. +R)»»T
WRITE(6,2)A,P,T,R
35 CONTINUE
40 CONTINUE
2 FORMAT T2 F7 ( , .
2 Tl 1 F5
, , . , T23 , I1 , T32 F3 2
, .
STOP
END
AMOUNT
THE ACCUMULATION PROCESS 193
In Example only two numbers are to be read, and these will be described by the first
I
two data formal codes, 13 and 12. The remaining format codes (14 and 15) are not process-
ed, since only two numbers are to be read.
If, on the other hand, there are more variables in the list of variables than there are
data format codes, the sequence of format codes is reused (start at the beginning of the
FORMAT) until all variables Each FORMAT statement describes
have been satisfied.
one record; hence any reuse of the sequence of format codes will cause a new input record
to be selected or output record to be produced.
Example 2
I = 39
READ(5,5)I,J,K J = 33
5 FORMAT (12) K =44
In Example 2 the READ list specifies that threenumbers are to be read. Since the
FORMAT has only one data format code, only one number will be read per card. Hence
to satisfy the READ list three cards will be read. The three integers will be read from the
first two card columns of the three data cards.
The list of variables in the READ statement tells the computer how many variables it
must read; the number of data format codes (I.F, etc.) in the FORMAT specifies how
many items are to be read per record (card). For example,
if there are three data format
location IDIE will result in the truncation of all fractional digits so that the value of IDIE
will be 1,2,3,4,5, or 6.
Readers must determine the specifics of random number generation for their installa-
tions before attempting any programming exercises using random number generation. If
the user has no random number generator routine, he or she can append to his or her
source deck the random number program shown in Chapter 9, Figure 9-13, labeled
FUNCTION IRAND(IBEG,ITER).
Example
A submarine has been trapped into an enemy bay with only one escape channel leading
out of the bay. The bay is surrounded by mines as depicted below. All equipment is
malfunctioning and the blind submarine is now moving randomly in any of the four
cardinal directions one square at a time. If the sub touches any of the mines it is instantly
destroyed. Write a program to determine the sub's escape chances from its present posi-
tion at row 4, column 2. The sub escapes when it reaches row 2, column 5.
\
row 1
row 2 escape
To solve this problem we identify the position of the sub by setting R = 4 and C = 2
and follow the sub's path (changing either R or C) to its destruction or its escape. An es-
cape (E) or destroy (D) counter is then incremented appropriately. When the sub has es-
caped or been destroyed it is repositioned in row 4, column 2. The entire process is carried
out 1000 times. The chances or the sub's escape is then E out of 1000.
To simulate the movement of the sub we use the statement J = RANDOM(Z)*4 + 1,
which returns in J a random value 1 2, 3, or 4. Each number is associated with a particular
,
e.
THE ACCUMULATION PROCESS 197
q-
.
15 DO 10 1 = 1,5
WRITE (6, 1)1
IF(I.GT.5)G0T0 15
10 CONTINUE
a. SUM = SUM =
= 1,10
DO 10 1 1 = 1,10
DO 15
READ (5,1) GRADE READ (5,1) GRADE
10 SUM = SUM + GRADE SUM = SUM + GRADE
AVERAG = SUM/I 15 AVE = SUM/I
1 FORMAT (F5.1) WRITE (6, 6) AVE
6. What will the final value of J be?
J = i^-^'r
DO 41 = 1,10
4 J=J + .1
with
FORMATST FORMAT (F5. 1/12)
I? F0RMAT(F5.1)
8. Which of the follow ing statements are true? If false, state the reason.
DO 10 1X2 = N N 1 is ,
-1- a valid statement.
In some special cases the index of a DO loop can be a fioating point variable.
If the initial value of the index of a DO loop not specified,
is assumed to be
it is 1
The CONTINUE statement can only be used as the last statement in the range of a
DO loop.
New ANSI FORTRAN standards state that the body of a loop will always be
processed at least once. ^
'"
A nonexecutable statement in the body of a DO loop can be processed more than
once at exe(?tion time,
g. The value of the index of a DO loop having completed its full cycle becomes un- T
defined,
h. A DO loop should always be entered at the DO statement,
i. Accumulating and counting are synonymous terms,
j. One comment card in the range of a DO loop will cause a listing of at least one^ ^
comment and probably more, depending on the number of times the body of the ^>jr'"''
loop is executed.
9. Identify at least six errors in the following program; identify compilation errors.
THE ACCUMULATION PROCESS 199
READ(5,10) K,L,N ,
1/
10 FORMAT! 315-0) ^^
IF (KEQL) THENL = L+1 ^
GOTO (10,20,30,30)^L
20 STOP
30 WRITE (6,25) L
25 FORMAT (16)
DO 100 1 = 1.10
DO 300 J = 1,3
77 M=I*J
WRITE (6,200)M
100 CONTINUE
300 CONTINUE
IF(I*J*L)G0T0 77
STOP
END
2. Write a program to compute 1-2 + 3-4 + 5-- 100. Do not read cards.
3. Write a program to compute the sums of the first 100 terms of the following geometric
progressions (use formulas of Section 2-4- ) and their infinite sums whenever possible:
1
a. 1+2 + 4 + 8+ 16+---
b. 3 -9 + 27-81 + •••
c. 4 + 2+ + 1/2+ 1/4+ ••
1
4. Write a program to read a value for N and compute the sum of the squares of the first J
6. Write a program to read a value for N and compute 1*N + 2*N + 3*N + • • +
40*N. For example, if N = 3, compute 1-3 + 2-3 + 3-3 + • + 40-3. •
7. A data deck contains positive and negative numbers varying from - 100 to 100. Using
the last-card code method, write a program (using the DO statement) to compute the
sum of the positive numbers and the sum of negative values. Print both sums. (Max-
imum number of cards is 100.)
8. Grades are recorded on cards, two grades per card. The first negative number in-
dicates the end of the data deck. Write a program to determine the largest and
smallest grades and the average of the grades. Make use of the DO loop. (Maximum
number of cards is 100.)
.
9. Mr. X. is hired for 30 days' work. The first day he earns $.01 the second day, $.02; the
;
third day, $.04; in general, double the previous day. Print out a table showing the day
and the amount earned for each of the 30 days. Don't ask for the name of the com-
pany for which Mr. X. works. The last line of the output should read
10. You work in a diner. Every time a meal is sold, a card is punched with the cost of the
order and a meal code. A
meal code of means breakfast meal, I a 2 means lunch, and a
3 means dinner. Write a program to compute:
11. Using a DO loop, write a program to determine whether a number N read from card
is prime. A prime number is any number which can only be divided by itself and by 1
S, = 1
S, = 1 + Vi
S, = 1 + Vl + '/3
How many different sums would you have to compute before the sum exceeds 3.5?
13. A data file consists of records, each containing the following information about items
produced manufacturing plant: department number, item number (may occur
at a
DEPARTMENT
THE ACCUMULATION PROCESS 201
slow-moving items. The purpose of the program is to produce a report showing rec-
If item has not been sold in the last 30 days, discount is 10 percent.
If item has not been sold in the last 60 days, discount is 20 percent.
If item has not been sold in the last 90 days, discount is 40 percent.
However, any item that has sold in the last 30 days is not to be placed on sale. If
there is only one (1) of an item left in stock, it is not to be placed on sale no matter
when the last date of sale was. The amount of discount allowed is also subject to the
following rule: Sale prices cannot be lower than cost.
The report should have page headings at the top of each page of output; assume
any reasonable number of lines as the page length.
15. Write a program to produce an amortization schedule for a loan. Input for the pro-
gram consists of the amount of money borrowed (the principal), the interest rate, and
the amount of the monthly payment. An amortization schedule shows for each month
the amount of interest due, the amount of the payment applied to the principal, and
the new principal balance. Use the following layout as a guide:
Note: The last payment will be different than the other payments in most cases. Your
program should determine when the last payment has been reached and take
appropriate action so that the borrower does not pay more than is owed.
16. Modify the program of problem 15 above to compute the monthly payment required
to amortize the loan based on the principal, interest rate, and time. The required for-
mula is found in problem 17, Section 4-6-2.
17. The Meals on Wheels Company operates a fleet of vans used for the delivery of cold
foods at various local plants and construction sites. The management is thinking of
purchasing a specially built $18,000 van equipped to deliver hot foods. This new addi-
tion to the fleet is expected to generate after-tax earnings £,, £, •> ^6 (<is displayed in
•
the following table) over the next six years, at which time the van's resale value will be
zero. Projected repair and maintenance costs Q, Ci Ci •
, Q over the six years are
shown in the table.
202 THE ACCUMULATION PROCESS
Projected earnings
f.
THE ACCUMULATION PROCESS 203
five with an "honest" die, we would simulate 1,000 tosses and count the number of times a
five came out; 1 ,000 tosses woud probably result in a answer close to 67, representing /6
1 1
of the time.
18. Write a program to generate 100 random numbers in the range of 0-10. Determine the
average of the numbers. What would you expect the result to be?
19. Marc and Laura each toss a die. What is the probability that each will toss the same
number?
20. Sue Ellen and Anabelle each toss a pair of dice. What is the chance that both will toss
out a 2(i.e., each tosses two ones)? A 3? A 4? A 12?
21. Charlie tosses a pair of dice. What number (sum of the face values of both dice) is
more likely to be thrown; i.e., a two is face value of one and one, a 7 is a combination
of 4, 3 or 5, 2 or 6, 1 etc.
22. On a multiple-choice test consisting often questions, each question has five answers to
choose from — A, B, C, D, or F. Margie does not know the answer to questions 3 and
7. What is the probability of her guessing both answers correctly? One answer?
Neither?
23. a. A dog is lost in a tunnel at node (see diagram below). It can move one node at a
time in either direction forward and backward with equal probability. When the
dog hits node B^, however, a force of nature always propels it directly to node B4.
The dog escapes from the tunnel when it hits either B5 or F4. Does the dog have a
better chance to exit forward or backward? What
is the chance that the dog could
node
B5 B4 B3 B: B, F, F: F, F4
• • • • » ' • • • •
_ \ ) _
b. Same as part a, except that node B. propels the dog to node B4 only when trav-
eling in a left direction. If node B, is reached when traveling to the right, the node
B2 has no effect.
24. a. The following diagram represents an island surrounded by water (shaded area).
One bridge leads out of the island. A mole is placed at the black square. Write a
program to make the island. The mole is allowed to
mole take a walk through the
travel only one square at a time, either horizontally or vertically. A random
number between and 4 should be used to decide which direction the mole is to
1
take. The mole drowns when hitting the water and escapes if it crosses the bridge.
What is the mole's chance of getting safely out of the island? Restart the mole 100
times at the starting block, and count the number of times it escapes, even if it
drowned on some of its prior promenades.
204 THE ACCUMULATION PROCESS
Water -•
— Bridge
not to be considered
escaped yet
(Hint: To start, use two variables, R (row) and C (column), to control movement
of the mole. Initially, R = 3 and C = 4. If the mole moves to the right, set C = C
+ 1 ; and set C = C — I if it moves to the left. Likewise, change R for vertical mo-
tion. Then test every time to see if R = 1 or R = 6 for water contact, etc.)
The above island (maze) has now been transformed into a closed arena from
which no mole can escape. One mole is place in row column and another mole 1 , 1
in row 6, column 6. Moles move about the arena as described in part a above.
Upon hitting a wall, the mole bounces back to the position it occupied prior to
hitting the wall. Both moles move at the same time. Write a computer program to
determine, on the average, how many mole moves are made before a mole col-
lision occurs. {Hint: After any collision, restart the moles back in R = 1, C = 1
25. Write a program to determine the least number of random numbers between 1
and 100 that you should generate for the average of these numbers to lie in the in-
terval 47 to 53.
26. Let us define a string of numbers as either an ascending sequence of numbers (e.g., 1,
5, 9, 17, 17, 18; each value is greater than or equal to its predecessor) or as a descend-
ing sequence of numbers (e.g., 17, 16, 9, 9, 0; each value is less than or equal to its
predecessor). The length of a string is the number of numbers in the sequence. For ex-
ample, the following sequence contains six strings:
Write a program to generate 100 random numbers in the range of to 10 and de-
termine the average length of the strings encountered. A "good" random number gen-
erator should generate a low average string length.
27. Jane Jones has $200,000 to invest in speculative gold stock. The gold mines are of such
a nature that they either go broke, leaving stock worthless, or strike gold and make
the stock owners wealthy. Jane Jones's goal is to retire with $2,000,000. She plans to
THE ACCUMULATION PROCESS 205
invest $100,000 at a time. She estimates that the probability of losing each $100,000 in-
vestment is 75 percent, while the probability of making $1,000,000 from the same in-
vestment is 25 percent. In either case, she will sell the stock and make further $100,000
investments of the same nature. What is the probability of her retiring with
$2,000,000?
Write a program to simulate the behavior of the investment scheme, using a ran-
dom generator to determine whether the stock (the initial investment of $100,000) be-
comes worthless or valuable. Simulate 100 such investments, count the wins (makes
$2,000,000) and losses (goes broke), and from these figures determine the probability
for a successful retirement.
28. You are the owner of a bookstore that sells both paperback and hardback books. For
every book you sell, you have a card punched with two numbers representing
Input: 1. Set of prices and codes; one set per card; all prices are between 0.00
and 1000.00 (realnumber); all codes are either or (integer number). 1
Output: Print TOT, NUM, AVG, XMIN, PAP on one line, in this order.
Test data:
206 THE ACCUMULATION PROCESS
32. A study was conducted to determine whether different communication modes to com-
puters could affect a student's attitude toward programming. In a computer-related
course, 13 students used the batch-processing mode to solve problems on the com-
puter, while 12 other students used the conversational mode to solve the same prob-
lems. The following entries reflect the average score obtained by each student across
all the 20 questions of the Attitude Test Toward Programming (ATTP) given at the
end of the semester:
Mode of communication
Batch-processing Conversational
2.75 4.15
2.95 3.70
3.00 3.55
3.10 4.45
4.50 4.20
4.75 3.95
2.50 3.80
3.35 4.00
4.00 3.00
3.05 3.65
2.00 4.00
3.35 4.35
4.10
t
=
'
[{N, - 1)5; +{N,- \)S;] . (yV. + ^,)
where X and Xf, are the averages of the conversational and batch scores, respectively;
S and Sf, are the standard deviations for conversational and batch modes re-
spectively (see Section 5-4-3 for the programming example of a stan-
dard deviation); and
N^_ and TV^ are the number of scores for conversational and batch processing, re-
spectively.
33. Write a program to compute the area under a curve, y = j{x):
y
208 THE ACCUMULATION PROCESS
35. Write a program to determine a five-digit number did.^didjds that when multiplied by
a digit k between 2 and 9 will give a result ofd^djd^d^d,. For instance:
d| d: d, da ds
X k
d. dj d, d. d|
3. a. 120. b. 21. c. 8.
5. a. The value of the index should not be used I after normal/complete exit from loop.
The value of is indeterminate. I b. Yes.
6. J =
8. a. F: limit on DO
statement cannot be an expression.
a b. F: index must be integer,
c. must always be specified.
F: Initial value d. F: the CONTINUE statement can be
used anywhere in a program. e. F: New standards provide that if the initial value ex-
ceeds the limit, the body of the loop is not processed at all. f. F: Nonexecutable state-
Grade Output
. . ' I
DOUBLE PRECISION NAME IHOLD , NAME is used to store the student's name and
IHOLD is used to identify the student's name with the
highest current score.
LOGICAL P The proposition that there is one and only one highest
score is either true or false. The logical variable P is
GOTO
10 instead of K is to list only six statements in the com-
1 GRADE = puted GO TO statement, versus statements if K had 1 1
IF AMAX - SCORE 13 14 15
( ) , , equal to the grade read, then no longer true that it is
14 P= .FALSE. there is only one highest score. Set P to false and keep
GO TO 17 track of the name at 17. A highest grade has been
13 AMAX = SCORE found and hence the proposition that only one highest
P = TRUE , grade exists is (temporarily) true. Keep track of name
17 IHOLD = NAME and score and read more cards.
GOTO 15 Write the name of last student with highest score.
6 WRITE (6, 7) IHOLD If P is true, then only one student obtained highest
IF(P)G0T09 score.
WRITE (6, 8) If P is false, print message that highest score was
9 STOP shared by other student(s).
5 FORMAT (A8,F5.1)
11 FORMAT (TIO, AS, 3X,F6.1,2X,A1)
7 FORMAT TIO HIGHEST GRADE WAS OBTAINED BY
( ,
'
A8 MX , )
END
A program to solve this problem is shown in Figure 6-1. Note the three new FOR-
TRAN features:
Integer Data
mantissa
(fractional part) exponent
.63253 X 10^
Example
w ,,
The range of values that can be represented using floating-point representation is de-
pendent on the number of bits (digits or ) allowed for the exponent and on the number
1
of bits allocated to the mantissa in each computer word. Some typical ranges are shown in
Figure 6-3.
DATA REPRESENTATION 213
Character strings are not generally processed numerically; that is, they do not participate
in additions, subtractions, etc.
The internal form used to represent alphanumeric (character) data differs from that
used to represent integer or real data. Each computer word can "hold" a limited number
of characters. The number of characters depends on the particular computer. The number
of characters per word on various computers is shown in Figure 6-4. Hence many words
(variables) will be needed to store long character strings. For example, the character string
173 FIR DR. would require three words on a typical IBM system:
7 3 F I R D R
84 98
17 3 FIR
The code used might be, for instance:
214 DATA REPRESENTATION
Of course, the mode of the data can also be defined by an input FORMAT code. If the
data is to be read from cards, an I computer to represent the data in integer
code tells the
code, an F code in real number code, and an A code in character code.
To better understand the alphanumeric A format code and the way in which charac-
ter data is used in a program, it is helpful to visualize the differences in the internal repre-
sentation of the three data modes. The following discussion is purely conceptual but serves
to illustrate the three different data representations.
Consider the collection of digits 1234. This group of digits can be thought to represent
a signed integer number 1234 or a signed real number 1234. or a string of characters 1, 2, 3,
and 4 (as in an address 1234 North 12th Ave.). These three different data modes can be vis-
ualized as follows:
Integer code 1234 ^ea/ number code 1234. Character code 1234
00 00 12 34 04 '12 34 00 0l!02!03'04
I I )
exponent = 04 01 = 1 03 = 3
store that character string in X. If the statement X = L is used, then X will not contain
01020304. Before storing L in X, the computer will convert L to real mode, since X is real,
and hence X will contain 07 102030 (01020304= 1,020,304= .1020304 X 10^ = 07102030).
However, if the statement M = L is used, then the mode is preserved across the equals
sign and no conversion takes place, and M will contain 01020304. Similarly, if X contains
the string 01020304 and L contains the string 01020304, the statement: IF(X.EQ.L)GO TO
5 will not result in a transfer to statement 5, since L will be converted to real mode before
the comparison is made (07102030), and the two numbers (variables) will be unequal.
The DATA statement can be used to initialize variables to alphanumeric data. Most
systems allow the programmer to define alphanumeric variables as follows:
DATA REPRESENTATION 215
1. Count the number (n) of characters in the constant and precede the character string by
nH as follows:
The A data format code is used to describe alphanumeric data fields for both input
and output. The general form of the A format code is:
nAw
where w is the field width and « is a duplication factor. Alphanumeric data can be stored
in either integer or real variables. On input, ifless than the maximum number
w is
of characters that can be stored in a word, blanks are inserted to the right in the
word in memory.
Example 1
Memory
READ (5,2)
\
2 FORMAT A4(
I
216 DATA REPRESENTATION
The variable A stores the first four characters, B stores the next four; three characters are
read for C, and the system automatically provides one filler blank to the right. Two filler
blanks are provided for D, and four characters are stored in each of the variables N and
1
N2.
If the field w exceeds the maximum number of characters / that can be stored in a
word (see Figure 6-4), the rightmost / characters in the field are read and stored in the vari-
able.
Example 2
Memory
/ \
[w_
4
READ (5,1 I T
1 FORMAT! A7 A5
As noted previously, one computer word can contain a limited number of characters.
This, then, means that many words are required to store even the smallest of character
strings. It is possible to double the number of characters per variable by declaring such a
variable a DOUBLE PRECISION variable. In effect, this results in two contiguous mem-
ory words being allocated to the variable. (The DOUBLE PRECISION statement is dis-
cussed in Section 6-2-4.) For example, with / = 8 (IBM 370 double precision):
Memory storage
DOUBLE PRECISION X,I,Y
DATA I, K,/' SHE LEFT' 'ME'/
,
READ(5,1)X , Y
1 FORMAT (AlO , A3:
M
/
Example 2
The programmer should be careful not to use mixed-mode alphanumeric variables across
the equals sign in a replacement statement. Consider the following example: suppose the
variable L contains the alphanumeric string 01020304 and it is desired to store that charac-
ter string in X. If the statement X = L is used, then X will not contain 01020304. Before
storing L in X, the computer will X is real, and hence X will
convert L to real mode, since
contain 07102030 (01020304 = 1,020,304 = 07102030). = 1020304 X
However, if the 10^
statement M = L is used, then the mode is preserved across the equals sign and no con-
version takes place, and M will contain 01020304. An interesting note on this: If you get
output in which names are scrambled or "wrong characters" are printed (i.e., you expect
BRAD and get DR*B), this is a good indication that there has been mixed mode of
alphanumeric variables across the equals sign in a replacement statement.
Example 3
IF (A. EQ. I) GO TO 30
would result in a false, unequal condition. The numerical code associated with A and in I
this comparison will not be equal, since A is real and is integer, and the computer will I
convert to real mode before a comparison is made (see Example 2). However, if variable
I
IF (M.EQ.I) G0T0 30
will result in a true, equal condition and a branch to 30 will be taken.
Example 1
M
CHARACTER A*4/ HATS / L/ / ST*3/ DO
'
'
. '
'
, '
'/ - NO/ TR
'
'
DATA REPRESENTATION 219
Example 2
A=HATS
B=D0N1T
X=MAN^
All variables in this example, unless otherwise designated (B*5), will have a word length of
four (CHARACTER*4). Note thattwo single quotes in succession indicate that the single
quote (') is part of the literal string and does not indicate the end of the literal string.
Assignment Statements
Variables that have been declared in the CHARACTER specification statement can
be assigned alphanumeric values through the replacement statement as follows:
NAME = RICHARDS
SEX =M
ME = PSCl^ A trailing blank is furnished.
LOAN = BUS^ The rightmost four characters are read.
Note that the rightmost characters are stored when the number of columns read exceeds
the length specified in the CHARACTER declaration.
Output of variables declared in the CHARACTER statement is done with the A for-
mat and follows the same rules as integer and real variables containing alphanumeric data,
as discussed in Section 6-2-2.
padded to the right with blanks to equal the length of both strings. The comparison stops
at the first non-equal character. An error will occur, however, if REAL or INTEGER var-
iables containing alphanumeric data are compared to CHARACTER variables or to liter-
Legal
CHARACTER FNAM*8,J0B*6
FNAM GT
.
Illegal
222 DATA REPRESENTATION
Examples
X = -.01E3*Y X = -10.*Y
Y=16.2E-4*Z + W Y= .00162*Z + W
Z = 4.2E + 20**2-Z*.5E-21 Only exponential form is practical
Input of exponential numbers. Numbers in exponential form can be read from data
cards using the E format code. Recall that an exponential number can be written as:
hasic-real-constant E integer-exponent
For example:
2134 E + 30
basic-real-constant integer-exponent
Ew.^
where w represents the number of card columns reserved for the data field, and d in-
forms the system where to place the decimal point in the basic-real-constant in
case no decimal point is punched on the card.
If there is no decimal point punched in the basic-real-constant, the basic-
real-constant is adjusted (read) with d fractional digits (the decimal point is assumed d
positions to the left of the character E punched in the field). This adjusted value is then
raised to the specified integer-exponent. If the decimal point is punched in the
basic-real-constant, d is ignored and the basic-real-constant is raised to the specified in-
teger power; i/ nevertheless must be included in the E format description.
READ (5,1) A B C D E
\ I i I I
Card column 1
of data card
Value stored 6.32 X lO"* 632. x 10^ 60029 X 10" 00632 X 10' 330.0 X 10
T
Two fractional
I
Zero fractional Five fractional Kive fractional One
T
Iractional
positions positions positions positions position
DATA REPRESENTATION 223
/
Note that blanks are read as zeros.
Example 2
READ (5,1) E F G H
* I
1 FORMAT (E7.1 E6.4 E8.0 E6.4
i i I \
/\
Card column
of data card
I I J
One fractional Four fractional Exponent too large Basic real constant field
position positions ElOOO not long enough
Example 3
READ (5,1) X Y Z W
1 FORMAT E7.0 E10.4 E9.1 E3.3
/^
224 DATA REPRESENTATION
the Start w must be greater than or equal to 7 if it is to print the sign, the leading 0, the deci-
mal point, the E, the sign of the exponent, and the two digits for the exponent. (If \v is not
large enough some systems will not print the leading zero.) Consider the following ex-
amples:
Example
DOUBLE PRECISION XJ
X = 123456789012345. Both X and 1 are now double precision
I = .1 234567890 12345D40 real constants.
Example
Double precision constants and variables can be mixed with real and integer constants and
variables in any arithmetic expression. When any double precision operand and a non-
double precision operand are involved in an arithmetic operation, the nondouble precision
is converted to double precision; the operation is then carried out using 'double precision
arithmetic. The final result of the expression is a double precision number.
Example
If, in a replacement statement, a double precision value is to be placed into a real vari-
able, significant digits may be lost. Consider the following example, assuming a real vari-
able can hold at most seven significant digits:
Y
The D format code' can be used for input/output of double precision data. The gen-
eral form of the D format code is Dw.d. Details of the way the D format code is used are
exactly the same as for the E format code discussed in Section 6-2-3.
Double precision data occupies more memory space than real data. Operations per-
formed on double precision operands take longer than the same operations with real
arithmetic.
Such expressions have been used in logical IF statements. Syntactically speaking, a FOR-
TRAN logical expression can be defined as two arithmetic expressions linked together by
a relational operator (.GT.,.GE.,.LT. etc.). Consider, for example, the following elemen-
tary logical expressions:
(X-hY)**2.EQ.4
2.*Y.GT.X-Y
-1. .LE.SQRT(Z)
LOGICAL variable-list
Example
LOGICAL X,I,A
The following are now logical variables: X,I,A. Once a variable is declared LOGICAL, it
logical-variable = logical-expression
LOGICAL A, B,C
X=4
Y = -2
A = TRUE
. A is true.
C =A
B = X LT Y
. .
C = Y NE SQRT X
. . (
B= (X + Y)**2.EQ.4
C = 2.*Y.GT.X-Y
The effect of the logical operators on two logical expressions, e^ and P;, can be de-
scribed as follows:
This can be illustrated in table form, as shown in Figure 6-6. Note that the .NOT. operator
can only be connected to one logical expression.
e\
DATA REPRESENTATION 229
LOGICAL A,B,C
B
Example 2
. NOT . ( X + Y LT 100 OR A
. . . . ) . OR .
\/
70
FALSE
. FALSE .
Any logical expression can be used in a logical IF statement, the general form of which is:
IF {logical-expression) statement
If the value of the logical-expression is .TRUE., the statement is executed; if the value of
Example:
LOGICAL A, B,C
A = X LT Y . . A is.TRUE.;A.AND.BisTRUE.;
IF(A.AND.B)C= .TRUE C = .TRUE, is processed.
therefore
Lu
DATA REPRESENTATION 231
the first nonblank character is F or if the entire field is blank, the value stored is .FALSE. .
Example
READ 5 2 X Y
( , ) , ,
Data card
FORMAT (L3, LI,,L5)
L5)
WRITE(6,2)X,Y,Z
STOP
END
232 DATA REPRESENTATION
Before a complex variable can be processed, it must be declared in the COMPLEX state-
ment, which has the form:
COMPLEX list-oj-variable-names
For example, COMPLEX A,B,X(10) specifies that A,B and an array, X, of length 10 are
complex variables.
Internally, eachcomplex variable consists of two memory locations; the first for the
real partand the second for the imaginary part of the number. Complex expressions can
be formed in much the same way as real and integer constants. The result of evaluating an
expression where a term is complex is always a complex value.
DATA REPRESENTATION 233
Input/output of complex variables requires two data descriptor format codes for each
complex variable. The first format code describes the real part, and the second describes
the imaginary part of the number.
Example
COMPLEX A,B,C
READ (5, 1) ^ ? '
1 F0RMAT(F4.0,F6.0,F3.2,F4.3)
real part of A imaginary part real part imaginary pari of B
ofA ofB
C= (6.2,-4.325)
WRITE(6,3)A,B,C
3 FORMAT (2X.6F8. 4)
Answer: Generally speaking, significant digits are those digits used to represent any
number. Leading zeroes as well as zeroes immediately following the decimal point are
not significant. For example:
Trailing zeroes may or may not be significant, depending on what context they
are used in. For example, in the following set of measurements — and 10.0
10.5, 13.6,
— the number 10.0 has three significant In a digits. different set of measurements
— 11.356, 12.555, and 10.000— the number 10.000 has five significant digits; yet 10.0 =
10.000.
Computers represent numbers and carry out operations using a fixed number of
which is dependent on the computer's hardware. Any number or
significant digits, n.
any result of an operation must then be expressed as accurately as possible with those
n digits.
Since computers cannot, in general, represent nonterminating decimal numbers
exactly, those numbers are rounded off. Rounding off a number to n significant digits
amounts to finding the closest approximation to that number with n or fewer nonzero
digits. More technically, this means discarding all digits to the right of the /7th signifi-
234 DATA REPRESENTATION
cant digit. If the first discarded digit is 5 or greater, add 1 to the nlh digit; otherwise,
leave the nih digit unchanged.
Example
The following numbers are rounded off to seven significant digits (IBM 360/370):
rounded
41.239824 to 41.23982 =.4123982X10^
.0011145678rounded to .001114568 =.1114568X10'^
315.00075 rounded to 315.0008 =.3150008X10^
1000001499999.98 rounded to 1000001000000.00 =.1000001X10"
Note in the last example the loss of precision in the final number representation
(499,999!).
2. Does "significance" of digits imply accuracy of result? That is, if computed result
the
of an operation is carried out to seven significant digits, does this mean that the com-
puter result represents the first seven digits of the true answer?
Answer: No. Significance and precision or accuracy of results are not synonymous.
Consider the following example: Two carpenters must saw a board in seven equal
parts. Assume they use a computer for their calculations which carries out operations
to seven significant digits. Beth carpenters feel very satisfied with the accuracy of their
measurement of the board —
40.01 and 39.89 inches respectively. A computer printout
yields an answer of 5.715714 (40.01/7) and 5.698541 (39.89/7) for one-seventh of the
board. The very presence of seven digits on the computer printout form might so over-
whelm the carpenters that each might think his seven digits must be correct. Yet both
results have only one digit in common! How many of these digits are then truly mean-
ingful? One? Two? Precision depends on the accuracy of the measurements, not on the
seven significant digits. Many programmers have blind faith in computer printouts;
yet much of a computer's input data in real life deals with approximate measurements
of weights, distances, temperatures, forces, etc. Significant digits themselves will not
affect the precision of results to any great extent. Hence results should always be in-
terpreted with the greatest of care even if 15 digits are used to express a result and even
if DOUBLE PRECISION is used.
If it is known that the input data are 100 percent accurate, then of course the
number of significant digits used in carrying operations can affect the precision of the
results. The reader might be interested in the subject of error analysis, which treats the
effects of significant digits or roundoff on numerical operations.
3, Is it true that most decimal numbers don't have an exact internal representation on
the computer?
Answer: Yes. in fact 99.999... percent of the numbers that we can manipulate in every-
day life are not represented exactly on a computer, which is not suprising when we re-
alize that the set of real numbers on a computer is finite. Numbers with small magni-
tudes have the best chance of being the most accurately represented on a computer.
There are thousands and thousands more computer real numbers in the in-
literally
between 100,000 and 100,001: and the
terval [0,1] than there are, say, in the interval
interval or gap between any two successive computer real numbers widens dramati-
DATA REPRESENTATION 235
cally as the numbers grow in magnitude. For example, on the 360/370 the real number
following 3,000,000,000 is 3,000,001,000, not 3,000,000,001 (using single precision).
It should be noted, however, that all integers are represented exactly in memory
up to the number of significant digits allowed by the computer system (see Figure 6-2).
Note also the difference in significant digits for real versus integer numbers (see Fig-
ures 6-2 and 6-3). Integers are represented exactly in memory because the integer con-
version to binary is exact. In the case of floating-point number conversion, the frac-
tional part generally does not convert exactly in binary; for example, .1,0 =
.0001 1001 100 • • . which must be rounded off.
4. Does the DOUBLE PRECISION statement give me more significant digits for integer
numbers?
Answer: No. The DOUBLE PRECISION statement affects only real numbers. There
is no double precision for integers. If an integer variable is declared in a DOUBLE
PRECISION statement, that variable becomes automatically a real variable and
should be described by an F edit code in a READ/WRITE format.
5. I need more significant digits than DOUBLE PRECISION can give me on the system
that I use. What can I do?
Answer: You will have to write your own code. See Exercise 40, Section 7-6-2, for
some thoughts on this matter.
6. Was I surprised the other day when a result of —0. was printed for my answer. I didn't
know the computer used negative zeros!
Answer: Some do and some do not. But your result wasn't really —0. Your FORMAT
just didn't leave enough places to print additional fractional digits. For example:
X = -.04
WRITE(6,1)X This statement would cause —0.0 to be printed.
1 FORMAT(2X,F4.1)
7. What characters can be processed by the alphanumeric A format code?
Answer: Any valid FORTRAN characters. The FORTRAN character set consists of
26 letters, 10 digits, and 1 3 special characters, as follows:
Blank 40
4B
4E
50
5B
5C
5D
5E
60
61
6B
7D
7E
236 DATA REPRESENTATION
The numeric code representing the FORTRAN character set is called EBCDIC (Ex-
tended Binary Coded Decimal Interchange Code). The collating (ordering) sequence
is
special characters < letters of the alphabet < digits (0 through 9).
The ordering of the special characters is shown in ascending order above. Some FOR-
TRAN compilers may accept source programs punched in the ASCII code (similar
code to EBCDIC).-*
Example
LOGICAL X
DATA X/ TRUE /. .
11. Can I use the SQRT function or **.5 to compute the square root of a complex
number?
Answer: No, use the CSQRT function. A list of functions that can operate on complex
numbers is shown in Chapter 9, Figure 9-3. Complex numbers can, however, be raised
to an integer exponent; i.e., (3.,— 4.)**4 is valid.
12. Is there any other means (except DOUBLE PRECISION for real numbers) to change
the word length or bytes allocated to real, integer, logical, or complex data?
Answer: Yes, all of the following are acceptable type specification statements on IBM
370/30xx/43xx computers.
DATA REPRESENTATION 237
Write a program to list the names of students who are more than 2 1 years of age and com-
pute the number of male freshmen, female freshmen, male sophomores, and female
sophomores. A program to solve this problem is shown in Figure 6-7. Note the simplicity
of using the logical IF.
Switch A
If the switch is up, no current travels through the circuit; if the switch is down, current
flows through the circuit. Let us represent the switch A with a logical variable having value
.TRUE, if the switch is down and .FALSE, if the switch is up.
Two switches can be arranged in series as:
'K
In this case, current travels through the circuit only when both A and B are down. The ex-
pression A.AND.B represents the series circuit.
Two switches can also be arranged in parallel:
B
238 DATA REPRESENTATION
r START
^ DOUBLE PRECISION SN
INTEGER FM FF SM SF AGE CLASS SEX
, , , , , ,
FM =0
FF = DATAFM.FF,SM,SF/4*0/
SM =0
SF =
/RFAD SN.AGF /
10 READ 5, 1)SN, AGE, SEX, CLASS
(
SEX.CLASS /
^ IS ^^
DATA REPRESENTATION 239
In this case, current travels through the circuit when A or B (or both) are down. The ex-
Examples
B ~
A A AND
.
.
( B OR. .
^lk
E AND F
. .
.
) . OR .
( G AND H
. .
G H
-Hiji—
The program shown in Figure 6-8 can be used to evaluate the above circuits for vari
ous values of the switches.
LOGICAL A, B,C,E,F,G,H,X,Y
2 READ(5,1,END=10)A,B,C,E,F,G,H
1 FORMAT (7L1)
X = A AND B OR C
. . ( . .
Y = E AND F
( OR G AND H
. . ) .
.
( . .
WRITE(6,3)A,B,C,X
3 FORMAT 3X CIRCUITl 3L2 IS L2
(
.
WRITE(6,4)E,F,G,H,Y
4 FORMAT 3X CIRCUIT2 4L2 IS L2
(
,
' ' ,
,
' ' ,
GO TO 2
10 STOP
END
Figure 6-8 Evaluation of Circuit Expressions.
-b + s/ b^ - 4ac -b - s/ b~ - Aac
X. '
= ^2 =
2a la
U b' - 4ac > 0, the values of x, and .v, are real; otherwise, they are complex. The pro-
gram shown in determine the roots of the quadratic equation.
Figure 6-9 will If the solu-
tions are real, the imaginary part of the roots will be zero (assume A 9^ 0). 1
240 DATA REPRESENTATION
COMPLEX X1,X2,A1,B1,C1,D
2 READ(5,1,END = 10)A,B,C
1 FORMAT! 3F4.0)
A1 = A
B1 = B
C1 = C
D = CSQRT(B1**2 -4. A1*C1) CSQRT requires complex arguments.
Xl= (-B1+D)/{2.*A1)
X2= (-B1-D)/(2.*A1)
WRITE(6.3)A,B,C,X1,X2
3 FORMAT (2X, A=' ,F5. 0, 'B=' ,F5
' .
, 'C=' , F5 .
.
Operations on floating-point data are performed using both the exponent and mantissa in
much the same way as hand operations are performed using numbers represented in scien-
tific notation.
Examples
Much larger and much smaller numbers can be represented with lloating-poinl than
with fixed-point numbers. However, the number of significant digits is limited with Hoat-
ing-point representation. For example, on the IBM 360/370, 1000000999999999 is internal-
ly stored as 1000000000000000 since the computer can only retain seven significant digits.
This really means that 10'- + 999,999,999 = 10''. Any operations performed on large
magnitudes result in large errors called absolute errors. For example, 10''" + 10 '- = 10''",
which means that 10- ' is totally ignored. On the real line there are gigantic gaps between
numbers as these become larger and larger. The number
on that immediately follows 10''
the IBM
360/370 is + 10''
not + 10''\ + 1,000,000,000,000. The gap is
10'' 1 or even 10"
worth 10'''*! Comparatively speaking, the numbers between and are extremely dense 1
ue is an approximation of .1 to within seven digits of accuracy (IBM 370). There are also
,,,
other rational numbers that have no finite decimal representation, such as 1./3. =
.3333333.
After any calculation only a given number of digits are stored for the result. In a pro-
gram with many calculations this error (called round-off error) may encroach on one or
more of the digits of the calculated result, causing fewer than the anticipated number of
digits to be correct. For example on the IBM 370:
1 .0007* .007
1 = 1 .007705
while in real life
1.0007*1.007 = 1.0077049.
This is only one digit off in the sixth fractional position. However, if the result were to be
multiplied by 10'", this would result in an error of ,000.
1
6-6 EXERCISES
6-6-1 Self Test
1. What advantage is there in using double precision mode variables and constants?
What is the price that you pay for double precision mode, however?
4. What value will be stored in each of the following examples as a result of a READ op-
eration? The result should be expressed as O.ddddddd X \(f\ where d and e are the sig-
nificant digits and the digit exponent, respectively.
242 DATA REPRESENTATION
Punched data
DATA REPRESENTATION 243
ed.
b. X + Y.LT.5. is an elementary logical expression.
c. B.OR. 10 compound logical expression.
is a
d. A.NOT.B is an invalid, compound logical expression.
e. The value of A.AND.(.NOT.A) is .FALSE. .
a. A.LT.B
b. .NOT.A.GT.O.
c. B.LT. COR. A.LT.B
d. B.LE.C. AND. A.LT.B
e. C GT B AND
. A LE 16
. OR B EQ 4
. . ( . . . . . . . .
)
f. .NOT. (A.GT.B.OR.C.EQ.O)
g. .NOT. A.GT.B.OR.C.EQ.O
h. A EQ B AND B LT C OR
. . NOT A LT B
. . . . .
.
( . . . .
10. Write one IF-statement which will have the same effect as the statements below.
a. IF(X.GT.0)G0T0 20 b. IF(X.GT 10)G0T0 20
GO TO 30 IF(X.LT 0)G0T0 20
20 IF(X.LT.10)ST0P GO TO 30
30 . . . 20 STOP
30 . . .
11. Write a LOGICAL expression involving two LOGICAL variables, A and B, which
has the value .TRUE, if only A is .TRUE, or if only B is .TRUE, and which has the
value .FALSE, if both A and B are .TRUE, or both are .FALSE. (This expression is .
b.
DATA REPRESENTATION 245
2. A deck of cards contains two fields per card: a name and marital status code = sin- ( 1
WRITE statement) of the names and their corresponding alphabetic marital status.
Example
JONES MARRIED
SALEM SINGLE
3. In a physical education class, students get either a pass or fail for the course. If the av-
erage of the student's three test scores is below 70, the student fails the course. The
student's three test scores are recorded on cards as follows (assume no more than 30
cards):
Student 3
Student 2 —
*
Student 1
246 DATA REPRESENTATION
(3) Small and aggressive and over 65, or timid and tall and under 16.
Write a program to transcribe this data into English sentences having the following
structure:
/SINGLE
r f ,e, 30 OVER SHE. ,o , MARRIED j^^^ HAPPY I J
r,rst-namefam.ly-nameISi^^^^j^3^[
'M
. 1
•
j ^^ j DIVORCED (UNHAPPY
|
I WIDOWED
For example, the data card [2212 OAKS ZAN should produce the following sentence:
6. To be eligible for promotion teachers at Franzia College must have taught there for at
Franzia College, somewhere in the state for at least seven
least five years or if not at
years. Teachers are not eligible for promotion after 25 years of teaching. To be eligible
for promotion to:
Assistant professor: teacher must have at least a master's degree in the field in which he
teaches.
Associate professor: teacher must have at least a master's degree plus 30 hours in his
teaching field.
In addition, no teacher is eligible for promotion if he or she has not served three full
years in his rank. The rank below assistant professor is instructor. Only four ranks ex-
ist at Franzia College. Design a card layout form for personnel to record all faculty
data and write a program to determine the number of faculty eligible for promotion.
7. Write a program for the IRS to determine who should file income tax returns (use cur-
rent IRS data forms).
A
248 DATA REPRESENTATION
performed. Let us evaluate (2000. + .4) -I- .6 and 2000. + (.4 + .6).
Devise an experiment to show that the associative property does not hold for float-
ing-point arithmetic on your machine.
11. Another source of error when using floating-point data representation is the change in
base that is performed in storing a decimal value. Consider, for example, the decimal
value .1. There is no exact representation of this value in base 2,8, or 16. The value
stored for . is only an approximation of
1 Consider the following code: . 1 .
X= .1
Y=X+X+X+X+X+X+X+X+X+X
WRITE(6,5)Y
If a sufficient number of significant digits are written out, the value of Y will be
.9999999999 ...
Test the above program with appropriate format codes (F20.15, etc.) to de-
termine the approximate accuracy of your computer.
1. Double precision mode data allows more significant digits to be computed but takes
more space to store each value.
3.
DATA REPRESENTATION 249
.
7
ONE-DIMENSIONAL
ARRAYS
has been possible to compute an average of grades simply by reading each grade in just
one variable name, using the statement READ(5,3)GRADE and accumulating these
grades as they are read. This procedure cannot be used in this case, however, since each
new grade destroys the previous value in GRADE, thereby making it impossible to com-
pare each grade with the average once the average has been computed. Each grade must
therefore be preserved, and for that reason five distinct memory locations (variables) are
needed, as shown in Figure 7- 1
ONE-DIMENSIONAL ARRAYS 251
One method for solving this problem is shown in Figure 7-2. This code is somewhat
cumbersome owing to the individual labeling of the five different variable names.
FORMAT (F5.1)
AVE = GRADEl + GRADE2 + GRADE3 + GRADE4 + GRADE5 /5
(
DIF = GRADE3-AVE
WRITE(6,10)GRADE3,DIF
DIF = GRADE4-AVE
WRITE(6,10)GRADE4,DIF
DIF = GRADE5-AVE Output
WRITE 6 10 )GRADE5 ,DIF
( ,
10 F0RMAT(T10,F5.1,3X,F5.1) ^6.
STOP ^^
END 89
45.
80.
)
Allocation of the five memory locations to the array GRADE is made through the
DIMENSION statement (see Figure 7-4), which tells the compiler to reserve five memory
locations for the array GRADE. Both of the methods described to solve the problem of
Section 7-1 make use of the same amount of memory locations. In the case of the array
GRADE, a block of five sequential memory locations is reserved for the five grades. Five
memory locations are also used in the case of the individualized labeling of each grade
GRADE). GRADE2 What makes the array concept different and powerful is that ele-
ments within the array can be indexed with a subscript, thereby considerably simplifying
the task of manipulating array elements for processing and for input/output considera-
tions (see Figure 7-4).
For example, to read the five grades into the array GRADE (storing them into
GRADE(1),GRADE(2) GRADE(5)), the program in Figure 7-4 repeatedly processes
the statement READ(5,6)GRADE(I) for values of ranging from to 5. The value of isI 1 I
called a subscript or an index. It is initially set to 1... so that the first time the statement
READ(5,6)GRADE(I) is executed GRADE(I) will refer to GRADE(l) and hence the val-
ue read from the data card GRADE(l). The second time, is 2 and
will be stored in I
GRADE(I) will identify GRADE(2); a new value will be stored in GRADE(2). Eventually
I will be 5 and GRADE(I) will refer to GRADE(5), and the last value read will be stored
in GRADE(5). For example, if the five following data cards were read, the array GRADE
GRADE(5)
ONE-DIMENSIONAL ARRAYS 253
Through the use of indexing, accumulation logic can be used to calculate the sum of
grades. The statement SUM = SUM + GRADE(I) (see Figure 7-4) accomplishes this ac-
cumulation process. The first time through the loop, = and SUM = SUM + I 1
GRADE(I) = + GRADE(l) = 56; the first grade in the array is added to SUM, which is
initially zero. The second time through the loop, I = 2 and SUM = SUM + GRADE(I) =
56 + GRADE(2) = 56 + 78 = 134. Finally, when = 5, the fifth grade in the array will
1
have been added to the sum of the four previous grades. Output also can be handled in a
loop by using a variable subscript on the array GRADE in much the same way as for in-
put. In this example the use of an array may not result in a significantly shorter program,
but the array technique may be used for many more grades with no increase in the number
of statements required and no explicit use of additional variable names.
declares X and Z as real arrays and JSUM as an integer array. In this case the array X may
contain up to six elements, the array Z up to 20 elements, and the array JSUM up to 107
integer values. One can visualize the elements of X, Y, and JSUM as shown in Figure 7-5.
DIMENSION statements must appear in the program prior to the first executable
statement (Replacement statement, I/O statement, IF and GO TO statements). A simple
practice is to place the DIMENSION statement at the very beginning of the program. Ar-
254 ONE-DIMENSIONAL ARRAYS
Array X
It t t t I
X(1)X(2)X(3)X(4)X(5)X(6)
Array Z
ONE-DIMENSIONAL ARRAYS 255
c < *^
. , /I A(3) Third element of array A
V B(J) refers to jth element of B.
k*V C0ST(3*K: If K is initially 1, the subscript
spans every third element of COST.
k*V±c L(10*ISUM-7; Evaluate 10*ISUM - 7 and look at
In FORTRAN 77, subscripts may be integer or real expressions, or array elements. Sup-
pose the values of array A and variables I and R are as follows:
I R
1-
256 ONE-DIMENSIONAL ARRAYS
Stance, A(3) = .0076. Also the same subscript can be used to reference two different array
elements, for example, A(I) and B(I).
No^tetiial-Lh£,^ullscript expression must be an integer e x p ressi on, in pT e-\ 911 FO R-
TRAN. Smce subscripts identify the position of an element in an array, it is important that
no~§Trt7scripts evaluate to zero or a negative number. Following are some examples of in-
A(-3)
ONE-DIMENSIONAL ARRAYS 257
Sometimes it is necessary to set an array, C, to the sum of two other arrays, A and B,
in such a way that C(l) = A(l) + B(l), C(2) = A(2) + 8(2), • • •
, C(IOO) = A(IOO) +
8(100). The following code can be used (assume A and 8 have already been loaded):
DO 15 1 = 1,100
15 C(I) = A(I) +B(I) Forexample: A(l) 3.
A(2)
A(IOO)
258 ONE-DIMENSIONAL ARRAYS
Memory
READ(5,1) GRADE (i:
READ (5,1) GRADE(2:
READ (5,1) GRADE(3: GRADE(l) GRADE(5)
READ(5,1) GRADE(4;
I I
READ(5,1) GRADE(5;
40 50 60 30 80
fio"
(m0£
50
r40
Example 1
A(l)
15
A(2)
DIMENSION A 10)
A(3)
DO 10 I = 1 10
READ(5,5: A(I
10 CONTINUE
5
The
FORMAT (F5.0
first time through the loop I is and A( ) is read from the data card. The second time
1 ,
F 15. A(10)
through the loop I is 2, and the data item on the second card is stored into A(2). Finally, I
is 10, and the tenth data item on the tenth card is read into A(IO). Because there is only one
variable in the READ list the corresponding format should only specify one data format
code.
260 ONE-DIMENSIONAL ARRAYS
To read two numbers per card into two different arrays, IHR and RATE, the follow-
ing code can be used:
Example 2
DO 10 1 = 1,10
READ(5,5)IHR(I) ,RATE(I)
10 CONTINUE
5 FORMAT! 13, 2X,F4.0)
50 2.5
20 60
40 5.1
V
ONE-DIMENSIONAL ARRAYS 261
Consider the following problem: Each card of an unknown number of cards contains
a student's name and two test scores. Read into an array, NAME, the name of each stu-
dent (eight characters maximum) and store in array, SCORE, the average of each stu-
dent's score. Print the number of records processed. Assume a maximum of 100 student
records. The following two approaches are presented:
Last-card code method. An additional card containing a last-card code is appended to
the data deck.
Automatic end-of-file method. Since the automatic end-of-file method is probably the
most widely used technique to terminate reading an input file, we present two methods
that can be used interchangeably.
Method L
option I option 2
In option names are directly read into array NAME; however, the terminal value of
1 the
the index one more than the number of grades read, since I counts the cnd-of-file card.
I is
Hence must be subtracted from L In option 2 the index reflects the exact number of
1 I
grades read, however, the name is read into TEMP first, before the name is stored into the
array.
Method 2.
The DO loop can be used to read cards; however, an upper limit for the number of cards
to be read must be known inadvance since the DO loop must know the number of times
the loop is to be carried out. Suppose we expected no more than 100 cards (excluding the
end-of-file card). The trick consists of telling the DO loop to read at least one more card
I )
than the maximum number of cards expected — in our case 101, or 200, or even 10,000 so —
as to force the loop to read the end-file card and therefore take an exit from the loop
through the END = 8 option of the READ statement. With this approach the value of the
DO index upon the end-of-file exit will always reflect the number of grades read plus one
(plus one for the end-of-file). The index I is not undefined outside the loop since the loop
never runs through its complete cycle; i.e., it is forced to exit prematurely through the
END = 8 option.
option J
REAL SCORE (100)
DOUBLE PRECISION NAME 101 (
option 2
DO 5 1 = 1, 1000
READ(5,9, END=8) NAME(I) ,T1,T2
SCORE(I) = (Tl + T2)/2.
5 N = I The value of N refiects the number of elements
8 WRITE(6,7)N read.
When the DO loop is teminated the value of N represents the number of elements read
into the array whether normal exit is taken (100 times exactly) or whether an end of file
condition exists.
If it is desired to read into an array. A, more than one number per card (two, for in-
stance), the following code can be used:
A
DIMENSION A (10)
DO 101 = 1,5,2
1 91 6
READ(5,5)A(I) ,A(I + 1)
10 CONTINUE
5 FORMAT (2F5.0)
ONE-DIMENSIONAL ARRAYS 263
Implied DO List
READ(5,5)A(1) ,A(2),A(3),A(4),A(5),A(6)
The above statement can be interpreted as follows: Read the numbers A(I) as I ranges
from 1to 6 in steps of 1. The incremental step 1 can be omitted, which results in an auto-
matic incremental value of 1. Six values will then be read from one or more cards as speci-
fied by the number of data format codes in the format. Once again, the implied DO list
specifies the total number of values to be read into memory or written out, and the format
specifies how many of these values will be read per card (or written per line). In the case of
the implied DO, there is no one-to-one correspondence between the number of variables in
the READ/WRITE list and the data format codes in the corresponding formats. Consider
the following examples:
Example 1
In both cases five elements are to be read or written. The format specifies the number of
entries per record. For the READ operation there is one item per card; hence five cards
will be read. For the WRITE operation there are two items (2F6.0) per line; hence three
lines will be printed, with only one item printed on the last line.
^ 7
Example 2
In both cases 13 elements are processed. For the READ operation there are three items
per card (3F5.0); hence five cards will be read, with only the first entry on the fifth card
read. For the WRITE operation 12 items are printed per line ( 12F6.0); hence two lines will
be printed, with only one field printed on the second line.
Example 3
WRITE 6 6 (I ,'SALES I I = 1
( , )
( ) , ,
FORMAT T5 12 ,"^10 F5 1 ^
( , , . ) •2 per line
SALES
r 82.7 84.1
r
A
{
84.
36.3
ONE-DIMENSIONAL ARRAYS 265
Example 4
The literal "MACHINE" is repealed nine times, and the numbers 1,2,3, • • •
8,9 can be
generated by the implied DO list, as follows:
It should be noted that with the implied DO list, the last-card code method cannot be
used to read an unknown number of cards, since it is not possible to test array elements as
they are read within the DO list. The automatic end-of-file in the READ statement can be
used, however. The last value of the index used in the DO list will reflect the count of
logical records read plus one (because of the end-of-file). Eor example, if the array A is to
be loaded from a deck of an unknown number of cards (no more than 100 cards), with
three data items per card, the following code can be used:
In conclusion, the implied DO list is a convenient method to load or write out arrays.
The implied DO
cannot be used if it is desired to analyze or test data items as they are
list
read into memory or written out. For example, if one wishes to load an array with num-
bers from data cards and stop loading when a specific number is encountered in the input-
file, an explicit DO loop must be used, since the implied DO list does not allow the testing
while reading.
Common Misunderstandings
One of the most confusing aspects of input/output of arrays is the relationship be-
tween the list of variables specified by the READ/WRITE statement and the correspond-
ing FORMAT. Consider the following example of what is consistently misinterpreted by
many. The question or problem is: how many data cards will be read by the following
code?
DO 5 I = 1 , 9 The reader might think that this code will read A(l)
READ 5 6 A ( , ) (
I as I goes from 1 to 9, and since three numbers are
5 CONTINUE specified in the FORMAT, three data cards will be
6 F0RMAT(3F5. 3) read altogether. That is not the case.
READ(5,6)A(1). This statement says "just read one element A(l);" now the format says
"the maximum number of entries that can be read from card is three," but that's just a 1
—
maximum in our particular case the computer only wants to read one element. Hence
each cycle through the DO loop results in one card being read, so altogether nine cards
will be read.
Contrast the example just presented with the following:
In this case the READ statement says "1 need to read altogether nine elements." The
FORMAT says "no more than three elements per card." Hence to satisfy the READ list
Nested DO Lists
Implied DO-lists can be nested, very much as DO loops are. Consider the following
example:
A, B| Ml
268 ONE-DIMENSIONAL ARRAYS
The DATA slatement was used earlier (see Chapter 4, Section 4-2-3) to establish in-
itial values for nonsubscripted variables. It can also be used to initialize arrays. Recall that
the DATA statement should be placed after the DIMENSION statement. Initialization of
an array can be done by listing explicitly the named array elements and their correspond-
ing values or by defining the array elements through the DO list (see Example 1):
Example 1
REALA(5)
DATAA(l) ,A(2),A(3),A(4) ,A(5)/1. ,2.1, -3. ,4. ,5.6/ Explicit form.
In the third case the number of array elements initialized is equal to the size of the ar-
ray declared in the DIMENSION
statement (5 elements for A in this case).
The duplication factor "*" in the list of constants may be used to simplify the cons-
tant list.
Example 2
DIMENSION A( 200)
DATA (A(I) ,1 = 1,100 )/100*0./
Note that A(I0I),A(I02), •
,A(200) still remain undefined. Note that the"*'" in the cons-
tant list means repetition of a constant, not multiplication.
3. What can I do to change the impHcitly defined mode of an array, i.e., store integer val-
ues in a floating-point array or store floating-point values in an integer array?
Answer: Declare the array using the INTEGER or REAL type statement, as in:
An equivalent method to dimension and define the mode for the arrays is
INTEGERA(IOO) ,B(60)
REAL 1(45)
4. Is there any limit to the size of an array?
Answer: No, the maximum size for an array is a function of the memory size of the
system in use.
Answer: The entire array as specified in the DIMENSION statement will be process-
ed. If A has been dimensioned A(79), all 79 entries will be written or read.
Example
DIMENSION A( 10)
READ(5,10)A
10 FORMAT (F6.0)
The above code is equivalent to READ(5,10)A(1), A(2), A(3), A(4), A(5), A(6), A(7),
A(8), A(9), A(10),or, READ(5,10)(A(I),I = 1,10).
Care must be exercised when just using names of arrays without subscripts in an
input/output operation. Consider the following example:
r 50. 2.5
3 F0RMAT(F3.0,2X,F5.2) 20.
40. 5.5
^
HOURS RATE
/
The above code would load arrays HRS and RATE as follows:
7. Can you dimension an array for 50 elements and use only the first 30 elements?
Answer: Yes. In that event the last 20 memory locations will not be used.
Answer: Unless you dimension an array called SIN in your program, SIN(X) is not a
subscripted variable name but a function name.
9. Can I use an implied DO list in an arithmetic statement to process an array? For ex-
ample, I can write:
Answer: No, implied DO lists are valid only in input/output and DATA statements.
DIMENSION A (30)
LOGICAL I (20) ,A
The following are now logical variables: I( 1 ),I(2), • • • ,I(20),A( 1 ),A(2). • • ,A(30).
11. What if I use a subscripted variable name in my program and I forget to dimension it?
Answer: No compilation error will occur, since the compiler will think that it is a func-
tion. An error will occur later on since no such function is defined anywhere.
12. Can the same index be used more than once in implied DO lists as follows:
READ(5,5) (
(A(I) .1 = 1,5) ,SAM,I = 1,9)
Answer: No, the inner implied DO list A(I),I = 1,5 will change the value of I used to
control the outer implied DO list, i.e., I = 1,9. Note, however, that the following is
permissible:
13. My friend was running a FORTRAN program and he had a statement, X = A(J), in
which J exceeded the limit expressed in the DIMENSION statement. Although the re-
sults he got for his program were in error, he did not get an error message.
Answer: By means of the DIMENSION statement, the programmer informs the com-
piler of the maximum number of memory locations he needs for the array. If the user
inadvertently at execution time refers to an array element, A(J), in which J is outside
the range specified in the DIMENSION statement (exceeds the size declared in the
DIMENSION statement), some systems may fail to inform the user that he has ex-
ceeded the array dimension and actually process A(J) as that element J positions away
from the first element of A. This can result in destruction of data or machine instruc-
tions representing FORTRAN instructions, depending on the value of J and depend-
ing on whether A(J) is to the left or to the right of the equals sign in a replacement
ONE-DIMENSIONAL ARRAYS 271
Statement. With most FORTRANS, however, if the index goes outside the range spec-
ified in the DIMENSION statement during execution, an error message is printed and
execution of the program terminates at that point.
14. Can I use a sequence of impHed DO hsts in the Hst of variables for a READ/WRITE
statement?
The variable XLARG is initialized to G(l) before searching the remaining elements
of the array. Any element XLARG becomes the new value of XLARG
that is larger than
at statement 14. This method, however, does not indicate the position of the largest ele-
ment within the array G. It just identifies XLARG as the largest element.
Another method which indicates the position or location of the largest element within
the array makes use of an index or pointer to locate the largest element. Initially this point-
er is set to the position of the first element (generally position one). Then as array elements
are compared one another, the pointer is changed appropriately to reflect the new loc-
to
lion of the largest number found so far. Thus if K is the pointer to the largest element
found so far and G(K) < G(I), then I is now obviously the position of the largest element,
so K is set to and the comparison of G(K) with G(I) for different values of is continued.
I I
This search method is illustrated by the following example given the array G with ele-
ments 6,4,7,2 and 6.
272 ONE-DIMENSIONAL ARRAYS
Array G
6
K=l
D07I = 2,5
IF(G(K).LT.G(I))K = I
7 CONTINUE
WRITE(6,8)K,G(K)
8 F0RMAT(1X,I1,F10.1)
ONE-DIMENSIONAL ARRAYS 273
The table of constants is stored in the array R via the READ statement. If a zone (IZ)
and weight (W) are read with values 5 and 10 respectively, the corresponding shipping rate
is R(IZ) = R(5) = 1.40. The total cost of shipping a package of = 10 pounds is then W
R(IZ)*W = .40* 10 = 14. More generally, the cost per pound to send a oackage to a zone
1
IZ is R(1Z). The total cost for sending a package of pounds to a zone IZ then becomes W
W*R(IZ).
input
K(2) is the counter to count grades of 2.
aa
K(4) is the counter to count grades of 4.
aQ
r^5o
K(50) counts the grades of 50.
Except for K( 1 ), K(2), K(3), K(50) all other counters will be at the conclusion of the program.
A program to solve this problem for grades ranging form 1 to 100 is shown in Figure 7-7.
Since there are 100 possible grades, 100 counters will be required to record all occurrences
of grades. The array K will be used for that purpose with K(1),K(2), • • • ,K(100) serving
the 100 counters.
In the first DO loop, the array of counters K is initialized to zero. A grade IG is
READ and the IGth counter is incremented by 1; i.e., K(IG) = K(IG) + 1. The value of
IG is used to designate which of the counters should be incremented. Thus, if IG has a val-
ue of 65, the statement K(IG) = K(IG) + is the same as K(65) = K(65) + 1, and hence
1
K(65) is incremented by K(65) is the counter used to record occurrences of the grade 65.
1 ;
When the end-of-file is encountered, a listing of all the nonzero grades and their cor-
responding frequency counts is produced. (See Figure 7-7.) On output only the counters
with nonzero values are printed. In statement 75 WRITE(6,6)I,K(I), the variable I repre-
sents the grade while K(I) represents the corresponding grade count (the one counting the
grade I). If K(I) = 0, this means that there was no grade I read.
274 ONE-DIMENSIONAL ARRAYS
C FREQUENCY DISTRIBUTION
DIMENSIONK(IOO)
DO 1 1 = 1,100
K(I)=0 Iniliali/e ihc 100 counters to zeros.
CONTINUE
1
4 READ(5,5,END = 70)IG
5 FORMAT (19)
WRITE(6,5)IG
55 K(IG) =K(IG) +1 Increment the counter corresponding to the grade IG.
GO TO 4
70 WRITE (6, 7)
DO 80 I = 1.100
IF(K(I) .EQ.0)G0T0 80 If the count of grades for grade I is 0. do not print count.
75 WRITE(6,6)I,K(I) Write the grades and their corresponding frequency
80 CONTINUE counts.
STOP
6 FORMAT( 15,114)
7 FORMAT(/' GRADES FREQUENCY '
)
END
Sample out put
23
45
23
12
100
100
100
GRADES FREQUENCY
12 1
23 2
45 1
100 3
problem may require the graph of a function; a business problem may require a bar graph.
Consider, for example, the following problem. Data regarding company sales for a week
have been tabulated as shown:
Day
ONE-DIMENSIONAL ARRAYS 275
The solution to this problem is shown in Figure 7-8. Note that the variable STAR is in-
itialized to the character "*," and every time a sale is read (KSALES) only the number of
stars (*) equal to KSALES is printed by the implied DO list in statement 15.
DATA STAR/'*'/
WRITE (6,1)
FORMAT IDAY T8 SALES
( ,
DO 20 IDAY = 1,7
READ (5, 2) KSALES
IF KSALES. NE.O) GOTO 15
(
2 FORMAT (12)
STOP
END
2. Two consecutive tables listed vertically of names and scores of successful and unsuc-
cessful candidates (one name and corresponding score per line). The input and output
can be visualized as follows:
Output
Input
SUCCESSFUL CANDIDATES
MONISH 46
ANTONE 75
MILLS 44
LAZY 48
MICHAEL 90
LOUD 56
PENSKE 81
r
ADAMS 74
A program to solve this problem is shown in Figure 7-9. Since the names of the candidates
must be printed by group (success/failure), two arrays are needed to store the names of
successful candidates and of unsuccessful candidates.
A name and a score are both read from a card. If the score is not greater than 74. the
name is stored in the array IFAIL and its corresponding grade in array FAIL. The index
KF is used to place each name and score in successive array locations. Arrays PASS, I
PASS, and index KP are used similarly to record the passing candidates" data. When the
end-of-file (EOF) is reached, KP rellects the number of passing candidates while KF re-
7-4-6 Sorting
Two methods for sorting are discussed. One method is called the bubble sort and the other
the interchange maximum or minimum. /
/
Bubble Sort \ /
Write a program to sort a grou{>.of grades into descending sequence. A maximum of
100 cards, each containing a grade, will be read. The program to perform this sort is
shown in Figure 7-11.
The method used to sort the five numbers in the program of Figure 7-11 is illustrated
graphically in Figure 7-10. This method shifts the s,mallest value to the fifth position of ar-
ray G, then shifts the next smallest value to the fouYtli position, then to the third, and so
on. The shiftingaccomplished by comparing pairs oKcontiguous array elements, one
is
pair at a time, and interchanging the two numbers whenever necessary to ensure that the
smallest value is continuously rnbved to the right. For instancKthe first and second num-
bers are compared; if the second is less than the first, the second rs. compared to the third.
If the second is larger than the first, these two numbers are interchanged, and the second
number (the smallest now) is then compared to the third. Ultimately the smallest value is
moved into the fifth position (see Figure 7-10).
The sorting algorithm requires two loops. An outer loop (statement 90) to control the
positioning of the smallest element in the rightmost position of the ever-shrinking array
(positions 5,4,3,2) and an inner loop (statement 100) to control the movement of the
smallest element to the rightmost position of the shrinking array through the interchange
procedure (statements 120,130,140). Once again, the outer loop controls the number of
passes (see Figure 7-10). If an array has N elements, then N - passes will be required. 1
ONE-DIMENSIONAL ARRAYS 277
DATA KP KF/0 0/
, ,
IF SCORE GE 74 GO TO 60
( . . )
KF = KF + 1
IFAIL(KF) =NAME
FAIL(KF) = SCORE
GOTO 10
60 KP = KP + 1
278 ONE-DIMENSIONAL ARRAYS
10
No interchange
ONE-DIMENSIONAL ARRAYS 279
Interchange Maximum/Minimum
Another method that can be used to sort an array of numbers in ascending (or de-
scending) order isdetermine the location (position) of the smallest element in the array
to
and interchange that element with the first element of the array. At the end of this first
se&t®fe' pass the smallest element is in the first position. The array is then searched for the
next smallest element, with the search starting at position 2 of the array; the smallest ele-
ment is then swapped with the number in position 2 of the array. At the end of this second
search pass the first two elements of the array are already in ascending sequence order.
The search for the next smallest number starts in position 3, and the same search and in-
terchange process is repeated until the last two rightmost array elements are processed.
Using this sorting procedure, an array of N elements will require N — 1 passes for the
search and interchange procedure. During the first pass, N elements will be compared,
while in the last pass only two elements
be compared. This sort process can be con-
will
trasted with the bubble sort process illustrated in Figure 7-10 as follows:
Array G 10-2 3 -1 20
"^7
Search for smallest value starts at position 1
To generalize this code for the complete sort program, K must take on values, 1,2,3,
• • • N — 1 (for N — I passes). The interchange process will require that T = G(2) on the
second pass, T = G(3) on the third pass, etc. Hence an additional loop is required to con-
trol K and the positioning of the succeeding smallest values into locations G(1),G(2),G(3),
• • • ,G(N — I). The complete code is shown in Figure 7-12. in which it is assumed that the
array G has been loaded.
DIMENSION G( 100)
READ(5,1)N
1 FORMAT (13)
N1 = N-1
DO 15 J = 1,N1 N - I passes.
K=J K = 1,2.3, •,N - 1.
7-4-7 Graph
Plotting the graph of a function y = fix) can be accomplished by computing integer values
"*"
for —
; for successive values of .v i.e., J = j\x} and placing a graphic symbol such as —
at position J on each output line. To better understand the graphing process, let us plot the
There is one minor problem, though: For some values of a, J is negative (see Figure
7-13); Jcannot be negative, since it is used as a subscript of ILINE to indicate the position
of the symbol "*" on the output line. This problem can be taken care of by adding to .v' +
A — 6 a constant C, which will neutralize the largest negative value of a' + a — 6 in the giv-
en interval and ensure that J > Adding such a constant does not change the shape of the
I .
graph but results in the translation of the x axis by C. In the preceding example a constant
C = 7.25 could be used, since the largest negative value for J is —6.25 (a = —.5). With J =
A' + .V — 6 + and largest value for J in the interval is J = {x = — .5) and
7.25, the smallest \
J = \S{x = Hence the array ILINE must be dimensioned to a size of at least 18.
3.6).
In the case of the sine function a constant of 2 is added to J = SIN(X) to ensure that J
> (SIN(X) = - for some values of a). Plotting J = SIN(X) + 2 is somewhat difficult,
1 I
since most of the values taken by J will be or 2 (J truncates fractional digits). To magnify
I
or stretch the graph over a wider area of print columns, we can multiply SIN(X) + 2 by a
factor —
let us say 8 in this case which will spread —
out J from a minimum of 1*8 when
SIN(X) = - to a maximum of
I 3*8 = 24 when SI NX = I. An array of a size of at least 24
must be reserved for the array to print the sine function. Multiplying the function by 8
does not plot the original function exactly but gives a fairly good idea of the shape of the
curve while preserving the roots (see Figure 7-13).
NAMEUST /name\/list\/[name2/lisl2/
where name is a name given to a 1 list of variables specified in lisi I. Group names can be
any valid variable name.
Lisi I is a list of variables or array names separated by commas. The same variable
or array name may appear in more than one list.
WRITE (6,NAME1) means: Print on the output form the name and the cor-
responding value of each of the variables specified
in NAMEI.
)
WRITE (6, 9)
( 1 X Y X Y
9 FORMAT
, , .
T4 T9 T35
,
XP = -4
XS = V
18 YP = XP*XP + XP-6
YS = SIN(XS) ,>'
DO 15 1 = 1,28
ILINE(I) = IBLANK Vo^
15 JLINE(I) = IBLANK A
JP = YP + 7.25
JS= (YS + 2)*8
ILINE(JP) = ISTAR
JLINE(JS) = ISTAR
WRITE(6.11)XP.YP,ILINE,XS.YS,JLINE
11 FORMAT 2F5
( .
1 , 2X 28A1 T32 2F5
, . , .
1 , 28A1
XP =
ONE-DIMENSIONAL ARRAYS 283
TABLE
CHARACTER* 10 PART NOW PULSE
INTEGER TABLE( 3) PART
LOGICAL PULSE F
umn 1, an ampersand (&) in column 2, and the name of the list to be read, specified in the
READ statement — NOW in this case. This name must be followed by a blank. Values are
then assigned to the variables specified in the list as follows:
Columns 12 3
I
y & NOWl^ name of variable = value, name of variable = value, etc. |
The variables defined must be separated by commas and can be spread out over many
cards until the characters & END are found. This terminates the data assignment.
To assign values to an array, one should punch the name of the array, then the equals
( = ) sign, then the list of values separated by commas. The first value is given to the first lo-
Example
input
Note on the data card do not have to be made in the order that the
that the assignments
variables are listed in the NAMELIST
statement. Also note that not all variables have to
be specified on the input card. In the preceding case, for example, F is not read, yet it is
specified in the NAMELIST statement.
NAMELIST and WRITE
If the code listed above is followed by the statements
WRITE(6,NOW)
WRITE(6,THEN)
284 ONE-DIMENSIONAL ARRAYS
all the values of the Mst named NOW and THEN would be printed in the order that they
appear in the NAMELIST statement. The output would also be labeled with the name giv-
en to the variable or array. For example, the output would be similar to:
&NOW
ONE-DIMENSIONAL ARRAYS 285
Example 3
.Rightmost open parenthesis
WRITE(6,10)(K(I) ,1 = 1,21) /
10 F0RMAT(1X,I1/1X,2(I1,1X,I1) ,2(1X,I1,I1) )
L I
Output listing
K,
C
L
286 ONE-DIMENSIONAL ARRAYS
Consider, for example, the following problem, which requires the reuse of the formal.
Each pair of cards of a deck of cards contains a student's class schedule for the week. The
first card contains the student's Monday schedule (identical to Wednesday's and Friday's)
and the second card contains the student's Tuesday schedule (same as Thursday's). Write
a program to produce a weekly class schedule comparable to the following.
TIME
ONE-DIMENSIONAL ARRAYS 287
To print the student's class schedule without the end statement "TOTAL HOURS
WORKED IS," reuse of the format is necessary; that is, statement 2 in Figure 7-13 should
be changed to:
M T
2 FORMAT 1 //T8 TIME
(
'
'
,
'
' , T30
,
' W , T50
,
' TH '
, T60
*'F'//(T9,I2,T13,5A10)
Each line following the header line is printed according to
the format starting at the rightmost open parenthesis.
7-6 EXERCISES
7-6-1 Self Test
1. Which of the following are legal array declarations for arrays A and B?
3. In the context of subscript expressions discussed in Section 7-2-2, which of the follow-
ing are invalid subscripts?
DO 10 1 = 1,5 b. DO 10 J = 1,9
READ(5,6)A(I) READ(5,6)A(J) ,B(J)
6 FORMAT (3F5.0) 6 FORMAT (F5. 3)
10 CONTINUE 10 CONTINUE
K= 1,6,2
DO 10 REAL A( 4), J
READ(7,7) (A(I 1 = 1, DO 5 1 = 1,4
7 FORMAT (3F5.0) 5 WRITE(6,6)J,A
10 CONTINUE 6 FORMAT IX. 2F4.1)
(
'f-'i
288 ONE-DIMENSIONAL ARRAYS
7. Specify the exact output (print positions, etc.) for the WRITE operations, given the
arravs A,B, and K, defined as follows:
1.5
array A
array B
ONE-DIMENSIONAL ARRAYS 289
a. INTEGER C b. INTEGER C
REAL X 5 ( REALX(3) ,Y(2
C = l READ 5 1 X
( , ) ,
3 READ(5,1)X(C) 1 F0RMAT(4F6.1)
IF(C.EQ.5)G0T0 . . .
C = C + 1
GO TO 3
1 F0RMAT(F6.1)
c. INTEGER C d. REAL X 4 Y 3( ) , ( :
REAL X 5 (
READ 5 1( , )
= 1 READ(5.1)Y
3 READ(5,1)X(C) 1 F0RMAT(4F6.1)
IF(C.EQ.5) GOTO . . .
C = C + 2
GO TO 3
1 F0RMAT(F6.1)
READ(5,1) (X(I) ,Y(I) ,1=1,3) READ (5.1) (X(I 1 = 1,3) ,(Y(I) ,1 = 1,3
1 F0RMAT(4F6.1) 1 F0RMAT(4F6.1)
10. Which of the following DO lists are invalid? In the event the implied DO list is valid,
specify the number of cards read or lines written. If the implied DO list is invalid, state
the reason, and state whether an error will occur at compilation or execution time.
g. WRITE(6,11)(PAY(J.) .J = l,3)
11 F0RMAT(2F6.1)
290 ONE-DIMENSIONAL ARRAYS
11. Given an array, A, of size 100, write the code to generate the following output, using
both the implied DO list and explicit DO loop for the WRITE statement.
a.
A, A. A, A^
A., A,
A, A.
C.
100 A,
A,., A,
12. Array POS contains 12 numbers. Using only one WRITE statement, write the code to
produce exactly the following output:
POS LISTING: X
ONE-DIMENSIONAL ARRAYS 291
14. Specify the list of variables that are read or written by the following instructions; for
example the list of names might be: N, L, M, M, • • •
Specify the position of each of
the variables on the input or output medium.
a' L
a. INTEGER M(20)
WRITE (6,5)(N,L,(M(J),J = 1,4:
5 FORMAT (IX, 3I3/( IX, 412) )
b. REAL T(10)
READ 5, 6) A, B, (T(I),I = 1,5)
(
M
, ,
"'"'"
=
20 READ( 5,1) (A(I) ,1 1,10)
DO 3 1 = 1,10
IF(A(I) .GE.IBIG) THEN IBIG = A( I
IF (A(I) .LTISMALL) ISMALL = A(I)
3 CONTINUE, r^
IF(IBIG = 0)G0T0 20
STOP
END
1. Write the code to fill successive elements of an array with the values 5,7,9, II,- ,225.
Do not use a READ statement.
2. Assume array A with 50 elements has already been loaded. Write the code to compute
the sum of the squares of the elements of array A.
tween and 10. No two same numbers should be guessed by the computer.
I
Write a program to read 16 grades (one grade per card) and compute the number of
grades less than the average. The output should be as follows:
XX.
XX.X
XX.
AVERAGE IS XX.X
NUMBER OF GRADES LESS THAN AVERAGE IS XX
6. Same problem as 5, except that it is not known how many data cards there are. Any
grade outside the range 0-100 indicates the end of the input file. Assume no more than
1,000 cards. Could you print the message "AVERAGE IS" on the same line as the last
grade?
7. The Miles Furniture Store is going out of business. Each different store item have
been labeled 1,2,3, • •
,100 (100 different items in all). The cost per item and the
number of items in stock have been recorded as follows: COST(!) is the cost of item I
and QU AN(I) is the number of items I. Assume the COST and QUAN arrays have al-
ready been read in. Write a program segment to compute Miles inventory in dollars.
8. A deck of 60 cards contains three numbers per card. Write the code to read the first 20
numbers into array A, the next 30 in array B, and the next 10 in array C.
11. Read into an array. A, of size 1 1, ten numbers in ascending order from one card; read
another number R from another card and insert it in proper sequence in array A.
12. A and B are arrays of size 100 and 50, respectively. Write the code to store the num-
bers 1,2,3, • • •, 100 into array A, and the first 50 odd integers starting at 101 into array
B. Then store arrays A and B in ascending order in array C. Do not read data from
cards.
13. A deck of cards (no more than 100 cards) contains one grade per card. These grades
are already in ascending order. Compute and print the median. The median is that
score which divides a distribution of scores into two equal parts. For example:
14. A deck of 100 cards contains numbers ranging from -100 to 100, one number per
card. These numbers are already in ascending sequence. Store the positive numbers in
array A and the negative numbers in array B.
15. An array, A, contains 31 numbers that can be either positive, zero, or negative. Write
a program to print the negative numbers, the count of zero numbers, and the positive
numbers, three per line, as follows:
20. An encyclopedia company has hired part-time saleswomen. The name of each woman
and the number of encyclopedia sets each has sold are recorded on separate data
cards. Each woman gets paid $90.00 for each set sold, as well as $15.00 extra for each
set (and fraction) sold over the average of the sets sold by all the saleswomen. Write a
program to produce the names of the women, the number of sets sold, and the amount
earned. For example, if the average is 5.8 and a woman sold eight sets, she gets paid a
bonus for the three sets over the average (2.2 becomes 3).
21. A deck contains an unknown number of cards, with three positive numbers per card.
The first negative number encountered in the input deck signifies the end of the data.
Write a program to read the first 20 numbers into array A, the next 30 into array B,
and the remaining elements in array C. Note that it is possible that there may only be
ten numbers in all, in which case only array A gets partially filled, or there might be
enough to fill array B but not C, etc. Assume no more than 90 data items in all and
print out any array that has been either fully or partially filled.
22. Same as Exercise 9, except that the output will list each element out of sequence. For
example, assume array A contains 15,5,6,20,30,4,70. Then:
23. The Meals on Wheels Company operates a fleet of vans used for the delivery of cold
foods at various local plants and construction sites. The management is thinking of
purchasing a specially built $18,000 van equipped to deliver hot foods. This new addi-
tion to the fleet is expected to generate after-tax earnings £,, £.< £^6. (^s displayed in
the following table) over the next six years, at which time the van's resale value will be
zero. Projected repair and maintenance costs Q, C,, d, , Q, over the six years are
as follows:
The decision to purchase the van depends on the benefit/cost ratio (BCR) (gross-
ly speaking, earnings/expenditures) given by the formula
where / is the rate of investment of earnings by the company. If BCR > 1 , then the
company should acquire the van.
Write a program to determine how (/') would have to be
high the investment rate
raised to permit the purchase of the vehicle. Write a program to compute the BCR for
investment rates starting at 6 percent and increasing in amounts of .1 percent. The
output should be as follows:
6%
6.1
Stop when the BCR is greater than 1 and print the message:
24. Read a line of text from a card and determine the number of words in the line. Words
may be defined as character strings separated by commas, periods, or blanks.
25. Read a line of text and write the code number of vowels (A,E,I,0,U) oc-
to count the
curring in that line. Then determine the number of words and the number of vowels in
each word.
26. Write a program to calculate the exact Julian date equivalent to the date specified in
the form: month, day, year. The Julian date is the day of the year. January has Julian 1
date 1, February 2 has Julian date 33, December 31 has Julian date 365. Use a table
showing the number of days that have occurred since the beginning of the year for
each month. For example:
Month Days
27. Write a program to convert dates given in the form of month-number, day, year to the
form of month-name, day, 19year. For example, input of 18 78 should produce 1 1
28. Write a program to determine the day of the week for any date in the twentieth cen-
tury. Use the following algorithm:
296 ONE-DIMENSIONAL ARRAYS
a. Compute X = 365.25* Y + J
29. To minimize transmission errors, words in telegrams are usually separated by slashes
(/). Read a telegraphic line of text and regenerate it to its original form by substituting
blanks wherever slashes appear.
30. Addresses in telegrams are transmitted serially. A double slash indicates a new line.
For example: I308/NORTH/20TH/AVE//ATLANTA//GEORGIA/75603//.
Read five such addresses and recreate them as envelope addresses.
31. Using the bar graph method discussed in Section 7-4-4, produce abstract computer art
as follows. Fill an array S of size 60 with random numbers between I and 100 and
graph the corresponding bar graph for each element of S.
32. Using the bar graph method discussed in Section 7-4-4, write the code to graph the
functionv= .V- and V = 10|sinx| to obtain a graph similar to:
* y y
* *
*
* * * * * * * *
* * * * *****
* * *
* * * *
33. Write the code to produce the following outputs using a combination of DO and im-
plied DO lists.
b.
ONE-DIMENSIONAL ARRAYS 297
C.
10
298 ONE-DIMENSIONAL ARRAYS
37. Write a program to read 30 grades (ten per card) and compute and print the number
of grades falling in the following intervals:
1-9
10-19
20-29
38. Write a program to read n grades {n > 10) and calculate the standard deviation of
these n grades. The standard deviation may be computed by the following formula.
n - 1
39. For each student you have one card with his or her account number in card
in a class,
card is used to indicate the end. The student's average is based on his or her nine best
scores. Write a program to produce the following output at the top of a new page:
GRADING REPORT
ACCOUNT NUMBER: XXXX AVERAGE = YYY.Y
TESTS :aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa
ACCOUNT NUMBER: XXXX AVERAGE = YYY.Y
TESTS :aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa
40. BINARY SEARCH. We have discussed in this chapter a method to search for a par-
ticular entry in a table.Such searches have been sequential and time-consuming in the
sense that searching starts with the first entry and proceeds with successive entries. A
shorter search is the binary search; it is essentially a guessing game. The binary search,
however requires that ihe table already be arranged in a particular order (ascending or
descending). The array is split into two sections at the midpoint either the desired —
entry is in the right section or it is in the left section. If it is in the right .section that sec-
tion is againup into two subsections, and the desired number is in one or the oth-
split
3
300 ONE-DIMENSIONAL ARRAYS
43. An array. A, contains 20 numbers that are not sorted. Write a program to define an
array, P, of size 20, that identifies the position order (from smallest to largest) of each
of the numbers in array A. For example:
A = 51
P =
SCHEDULE
Married Filing Joint Returns and Qualifying Widows and Widowers
48. The program in Figure 7-14 read a student's schedule and arranged it in an easy to
read format. Write a program to read two cards, the one containing the student's
first
Monday schedule (same as Wednesday's and Friday's) and the second one containing
his Tuesday schedule (identical to Thursday's). The course description and meeting
lime are punched in any order on the data cards. For example:
302 ONE-DIMENSIONAL ARRAYS
49. Dr. X. is an information-science teacher. A file consisting of his student's names and
their respective grades is stored in memory as follows:
Student Grade I
MARGULIES
ONE-DIMENSIONAL ARRAYS 303
51. Same problem as inExample 50 except that a reorder notice should be printed when-
ever the stock below ten percent of the original stock. Identify any item that has
falls
not been sold that day with two asterisks on the output. All invalid items should be
listed after the updated inventory has been printed. The output should be similar to:
304 ONE-DIMENSIONAL ARRAYS
Can you rewrite the code for the above exercise in such a way that each student's
grade is printed across each Hne of the output form after the student name but before
the average? After the scaled average?
53. On NBC's Today show's weather report, temperatures from various cities in the Unit-
ed States are hsted by geographic areas. Temperature readings are collected from vari-
ous weather-measuring stations and punched on cards in no special sequence order.
Each card contains the following data:
City
ONE-DIMENSIONAL ARRAYS 305
d. Find the maximum distance traveled by a balloon for each day and print the ID,
day, and maximum distance for each of five days (you should print the results for
the first day, then the second, third, etc.).
e. Find the average distance traveled by balloons released on the first and fifth days
combined and print this average distance (one result).
Input: Fifteen cards with two integer numbers and one real number on each.
Output: Fifteen printed lines of sorted ID's and corresponding days and distances
(ID), day, distance). Five printed lines of maximum distances for each day
(day 1 5) (ID, day, distance). One printed line of the average dis-
through day
tance traveled on the first and fifth days (average).
Test data
123
269
120
460
111
986
629
531
729
833
621
143
972
410
511
55. a. Without reading any data cards (initialize arrays to the constants specified) create
and print the following inventory file for an auto parts dealer:
PART NUMBER
115
120
125
130
160 140 99
For example, there are 50 of the item numbered 1 5 and each costs 90 cents. Dur-
1
ing the day, sales transactions are recorded on punched cards (or simulated by a
random number generator) as follows:
.
b. Write a program to read the day's transaction deck to produce a parts inventory
and to:
PART
ONE-DIMENSIONAL ARRAYS 307
e. During the day, a parts salesperson persuades the manager to add three new parts
to his currentHne of parts. The parts numbers are numbers between 100 and 170,
excluding those already in use. The manager decides to purchase 300 of each of
those new parts. Read three cards with a parts number and corresponding cost on
each card and produce a new inventory table by inserting the new records in their
appropriate ascending position in the file as follows:
56. You are the organizer for the National Swimming Finals. You want to have a pro-
gram that will seed the swimmers in the correct preliminary heat (race). You have 36
swimmers, each with an identification number and a submitted time. The swimming
pool has only six lanes, swimmers can swim at a time.
so only six The procedure for
seeding is to (1) sort the swimmers according to submitted times, and (2) assign to the
first swimmers with the first, seventh, thirteenth,
heat the and thirty-first fastest . . .
times. (Note: A person whose time is 52.1 \s faster than someone whose time is 55.8.
Fastest time means least time.) The swimmers in the second heat should be those with
the second, eighth, fourteenth, and thirty-second fastest times. Swimmers should
. . .
a. Read 36 cards, each card containing an integer ID and a submitted time, and
store these one at a time into an integer array and a real array.
b. Sort both arrays in ascending order by the time.
c. Starting with the first heat print the heat number (integer). Then print the ID
number and time of each swimmer in that heat in ascending order by time. Repeat
for each heat.
d. Print on a separate line (1) the number of swimmers who swam faster (less time)
than the average and (2) the average submitted time.
57. Two sort methods have been presented in Chapter 7: the bubble and the mini/max
sort. These two sorting techniques are not the most efficient methods, however. An
extremely efficient sorting method is the Shell-Metzner sort displayed in flowchart
form below. In an article entitled "A Comparison of Sorts" in Creative Computing,
Volume 2, John Grillo compared the three methods and determined that to sort
100,000 numbers would take 7.1 days, 3.8 days, and 15 minutes for the bubble,
mini/max, and Shell-Metzner sort, respectively. To sort 10,000,000 numbers would
take 93 years, 50 years, and 2.5 days, respectively! Write a program to sort N numbers
using the following flowchart.
308 ONE-DIMENSIONAL ARRAYS
1 = J
ONE-DIMENSIONAL ARRAYS 309
4. a. F. b. T. c. F. d. T. e. F. f. F. g. T (except for
subscripts). h. F.
5. a. 5. b. 18. c. 4. d. 12 lines
6. a. DO I I = 1,6,2 b. DO 2 =2,9,4 I
7. a. (I.) Skip to the top of a new page, space down four lines
(3.) _L
_ J_^_j^2^ 3, 5_, 0__
J cannot be described by an F format.
8. a. 5 FORMAT(5F10.0/(10I8)) b. 5 FORMAT(2FI0.0,I5)
c. 5 FOR1V1AT(3F10.0/IOO(IOI6/),2X,F5.0,I3)
310 ONE-DIMENSIONAL ARRAYS
9.
a.
10.
12.
13.
14.
8
TWO- AND THREE-
DIMENSIONAL ARRAYS
uction Each shop has five machines required in the manufacture of widgets. The
facilities.
company has compiled the repair records on all the machines and has tabulated the
number of hours lost on each machine in each shop as shown below:
Machine
Shop
312 TWO- AND THREE- DIMENSIONAL ARRAYS
DIMENSION A( 3, 5) ,S(5)
00101 = 1.3
10 READ (1,3) (A(I,J),J = 1,5) Read A(1J),A(I,2),A(I,3),A(K4),A(1,5)A(2,I)- • •.
3 F0RMAT(5F2.0)
DO 35 J = 1,5
S J =0
( ) Zero out array S.
00301 = 1,3
S(J) =S(J) 4-A(I,J) For each machine J, compute the hours lost in each shop.
I.e., Oj — /\|j I /\ Tj 1 r\^j.
30 CONTINUE
S(J) =S(J)/3.0 Compute the average of hours lost for each machine.
35 CONTINUE
00401 = 1,3
WRITE(6,4) (A(I,J) ,J = 1,5)
40 CONTINUE
WRITE (6, 5) (S(J),J = 1,5)
4 FORMAT (20X.5F6.0)
5 FORMAT ('0AVERAGES',T21. 5F6.0)
STOP
END
umn of array A would be addressed A(2,3). In general, A(I,J) is the element found in the
Ith row and Jth column. Note that the two subscripts are separated by a comma and
enclosed in parentheses.
DIMENSION \ariahle{ro\\-limit.column-limit){.
Column 2 Column 4
Column
Row 1
Row 2
Row 3
)
TABLE(3*K,I + 2)
B(10*ISUM-?,J)
C(K,5*L)
TF(A(T
i i
= 1,3
Ti PF ^0 1(^0 70 40
FoT 3 fixed value of
, ,
mner
the
J spans the columns of A,
loop scans the rows
of A;thatisA||,A|2,A,3,A2i,A22'---.
35 K=K+ l'
40 CONTINUE
\f all elements of an array are to be processed, two loops with two indices
In general,
controlling therow and column of the array are required. The order of these loops in the
program is immaterial. The program shown in Figure 8-3 with statements 20 and 25 in-
terchanged would perform the same task. In this case columns 1, 2, and 3. in that order,
are searched for elements less than 50.
Another example of row and column processing (or vice versa) will help the reader
better understand this procedure. Given the array A defined below, we would like to com-
pute the sum of the elements of the first row of A and store that sum in S( ), compute the 1
sum of the elements of the second row of A and store it in S(2), etc.
1
TWO- AND THREE- DIMENSIONAL ARRAYS 315
Column method:
The same result can also be attained if we proceed along columns as in the column meth-
od. Assume array S has been initialized to zeroes.
D06J = 1,4 $2 = 2 33 = 3
DO 6 I = 1 , $2 = 2 + 5 33 = 3 + 6
S(I)=S(I + A I,J) — Si = 1-^4-^7 S2 = 2 + 5 + 8 33 = 3+6+9
6 CONTINUE ^31 = 1-1-4-1-7-1-10 32 = 2 + 5 + 8-^11 33 = 3 + 6 + 9+12
Another illustration will help clarify the index mechanism of a two-dimensional ar-
ray. Suppose it is desired to ( compute the sum of the entries of the Nth row of an array,
1
)
A, of size 10 X 17, where N is accepted from input, and (2) interchange column 3 with
column 17. The row sum to be calculated is SUM = A(N,1) + A(N,2) + A(N,3) + • • •
A(N,16) + A(N,17). The row index is fixed to N, while the column index varies from 1 to
17.
temporary location, TEMP, were used, the elements of column 3 would be destroyed by
the statement A(I,3) = A(I,17), as ranges from to 10. 'the code to perform the sum and
I 1
DIMENSI0NA(10,17)
A,3,
READ(5,1)N
SUM =
D0 20 J = l,17
20 SUM = SUM + A(N,J)
DO 30 I = 1,10
TEMP = A(I,3)
A(I,3) =A(I,I7)
A(I,17) =TEMP
30 CONTINUE
316 TWO- AND THREE- DIMENSIONAL ARRAYS
READ(5,3)A(1,1) ,A(1,2),A(1,3),A(1,4),A(1.5)
READ(5.3)A(2,1) ,A(2,2),A(2,3),A(2,4),A(2,5)
READ(5,3)A(3,1) .A(3,2),A(3,3),A(3,4),A(3,5)
Of course, by using a DO loop that code could be reduced to:
DO 2 I = 1,3
2 READ(5,3)A(I,1) ,A(I.2),A(I,3),A(I,4),A(I.5)
3 F0RMAT(5F6.0)
DO 2 1 = 1,3
2 READ(5,3) (A(I,J) ,J = 1,5)
3 F0RMAT(5F6.0)
This is the form used in Figure 8-1. FORMAT statement 3 specifies that five variables are
to be read from one record; actually there is no real reason for the external DO loop used
above. Two implied DO lists could also be used as follows:
Once again, the implied DO list is nothing more than a compact technique to generate
a list of variables. What the DO list actually does is generate the following code:
Hence 15 values are to be read in memory. The number of values read per card (record) is
specified by the format. FORMAT(5F6.0) specifies that five values are to be read per card.
Since 15 variables are to be read, three data cards will be required. Had the FORMAT
specified 7F6.0, three cards would have been read, with on^y one entry on the last card
read.
Suppose that in the problem of Section 8-1 the data punched on each card were to
represent the hours lost for each machine. The input data might be visualized as:
TWO- AND THREE- DIMENSIONAL ARRAYS 317
To input the preceding data the following code might have been used:
DO 2 J = 1,5
2 READ(5,4) A(1,J) ,A(2,J) ,A(3,J
4 FORMAT (3F6.0)
or
DO 2 J = 1,5
2 READ(5,4) (A(I,J) ,1 = 1,3;
or
When using implied DO lists for reading or writing data, the beginning programmer
should be careful about which index moves fastest in the implied DO list. The following
examples show how arrays can be loaded row-wise or column-wise, depending on how the
implied DO list is coded:
DDDD
nnnn
Many implied DO lists can be specified in one READ/WRITE statement. Consider the
following, for example:
Example 1
Assume three arrays — A,B,C — are to be read row-wise, according to the data layout
shown below:
TWO- AND THREE- DIMENSIONAL ARRAYS 319
Example 2
DO 101 = 1,4
READ(5,1)(A(I,J),J = 1,3),(B(K,I),K = 1,4),C(I)
10 CONTINUE
Two dimensional arrays can be used to great advantage when printing tables of num-
bers that require some form of column/row identification and headings. Consider, for ex-
ample, the problem in Figure 8-1, where it is desired to print the input data according to
the following output:
For the programmer who wishes to generate the more sophisticated output shown
here for Figure 8- with just one WRITE statement:
1
,
MAINTENANCE ANALYSIS
MACHINE! MACHINE 2 MACHINES MACHINE4 MACHINES
SHOPl
)
/ \ i
Shop Number Data Average result (K)
(I) (A(I,J)) (S(J))
The beginning programmer may wish to use two or three separate WRITE statements in-
1* 1 = 1 2* 1 = 2 3* 1 = 3 • • • 10* 1 = 10
1* 2 = 2 2* 2 = 4 3* 2 = 6 10* 2 = 20
1* 3 = 3 2* 3 = 6 3* 3 = 9 10* 3 = 30
INTEGER MULT(10,10)
DO 10 J = 1,10
DO 10 1 = 1,10
10 MULT (I, J) = I*J Compute ail entries of multiplication table (row-wise).
DO 15 J = 1,10
15 WRITE(6,11) (I, J .MULT(I,J) ,1 = 1,10) When.! = 1, the first row of the above
11 F0RMAT(10(I2, '*M2. = M3,3X) '
)
table is printed.
When J = 2, the second row of the above
table is printed, etc.
DIMENSION Q 3 ( . 2 4
, ) or REAL Q 3 2 4 ( , ,
We may think of this cube as containing four two-dimensional arrays, three rows and two
columns each.
TWO- AND THREE- DIMENSIONAL ARRAYS 321
Column Column
Row ^ ^ ^ Depth Row Depth
Q(1J,4) Q( 1,2,4)
Q(l,l,3)
Q(2,2,4)
Q(1.K2)
Q(3,2.4)
DIMENSION A( 3, 5, 2 )
Suppose the data for each shop has been punched onto data cards, with data for fac-
tory 1 preceding data for factory 2. The data can be visualized as:
Shop 3 \
Shop 3
j
A(2,l,l) A(2,2,11 Shop 2 \ Factory 1
The FORTRAN code required to read, compute the average time lost on each machine,
and write out the results is shown in Figure 8-5.
) )
S(J) =0
DO 20 K= 1,2
DO 20 I = 1,3
S(J) =S(J) -t-A(I,J,K) S(J) is total of hours lost on machine J.
20 CONTINUE
S(J) =S(J)/6. S(J) is the average of hours lost on
30 CONTINUE machine J for the six shops.
DO 40 K= 1,2
WRITE(6.2)K
2 FORMAT 26X FACTORY NUMBER ',13
(
'
'
, ,
'
40 CONTINUE
3 FORMAT (20X,5F6.0)
WRITE (6, 4) (S(J),J = 1,5)
(
STOP
END
A(l.l) Ad, 2)
I
1 I I
A(3,1) A(3,2)
IA(3,3)
n I I
t * * * * t J I i
Array A (3, 3)
stored linearly
nnnnBiiii
''^11 ^21 ^31 ^12 ^22 ^32 ^13 ^23 ^33
Although the array A is stored column-wise in memory, this does not mean that A has to
be read into memory by columns. It can be read row-wise as in:
Three-dimensional arrays are stored linearly in memory. The internal order of storage
for the array A(3,5,3) is column-wise across each depth plane.
Order
A(l,l,l
A(2,l,l
A(3,l,l
A(l,2,l
A(l,l,3)
M -•Depth 3
A(2,2,l
A(3,2,l
A(3,5,3)
A(l,3,l
A(2,3,l A(l,l,2) ir
A(3,3,l
A( 1,4,1
AAAA Depth 2
A(2,4,l A
I
A(3,4,l
A(I,5,1 A(3,5,2) .
A(l,l,l)
A(2,5,l
A(3,5,l
A(l,l,2
>l .^ AXX Depth 1
A(2,l,2 lill
A(3,l,2
A(l,2,2
\XA A(3,5,l)
An array name can be used in a READ or WRITE list without subscripts. In that case
the elements are processed in column order.
Example
This code will result in all 12 elements of X being read, with three data items per card. The
data can be visualized as:
These array considerations apply for output as well. For example, suppose the array IX
contains the following data:
324 TWO- AND THREE- DIMENSIONAL ARRAYS
17
IX =
TWO- AND THREE- DIMENSIONAL ARRAYS 325
DIMENSION X( 3, 2)
DATA( (X(I,J) ,1 = 1,3) ,J = 1,2 )/3*l. ,3*2./
or
DATA X/3*l. ,3*2./
The array X will be initialized to Is for column 1 and to 2s for column 2.
REAL M 4 7 X 3 5
( , ) , ( ,
The elements of M are real.
INTEGER X 3 47 ( ,
)
The entries of X are integer.
Answer: Theoretically, no. Practically, yes. Restrictions on array sizes are dictated by
the size of the memory of the particular system. For example, on a system with memory
size of 32,000 bytes the statement DIMENSION A(100,10,10) exceeds the memory
size. On larger systems the operating system may take up a large portion of memory;
the programmer requiring large arrays should check on memory availability at his or
her particular installation.
Data regarding the smoking habits of students at a university have been gathered. The stu-
dent's class(1 = freshman, 2 = sophomore, 3 = junior, 4 = senior, 5 = graduate) and a
code representing the student's smoking habits (1 = don't smoke, 2 = one pack or less a
day, 3 = more than one pack a day) have been recorded on data cards. Each card contains
the student's class and smoking habit. It is desired to write a program to generate a fre-
quency table displaying the frequency of the student's smoking habits by class and re-
sponse, for example, how many seniors smoke one pack or less a day. To better under-
stand the problem, assume we have the data cards shown below. We could manually re-
cord or check off each response in a table of five rows (for the five classes) and three col-
umns (for the smoking habits) as follows:
326 TWO- AND THREE- DIMENSIONAL ARRAYS
Class • Habit
£ 5 1
*
Data cards
3 2 -I
_£
r vr
Habit
Class
2
1
r / t-
3 ^ Frequency table
4
5
TV T
A class code of zero will terminate the input and cause the frequency table to be printed.
The output should be arranged as follows:
FREQUENCY DISTRIBUTION
CLASS
TWO- AND THREE- DIMENSIONAL ARRAYS 327
Tickets have been sold for a play in a small auditorium. There are ten rows, each with six
seats. On cards you have the row number and seat number for the tickets already sold.
These cards end with —1,-1 "trip" card. You are now filling requests. On each card you
have the row and seat requested. If the seat requested is empty, sell the seat. If the seat re-
quested is filled, sell the person the first empty seal in the requested row. If there are no
empty seats in that row, print out an appropriate message.
The idea behind this program is to create 60 memory locations representing the 60
seats and to initially set all 60 memory locations to to indicate an empty seat. Thus when
SEAT(4,5) = 0, this means that row 4, seat 5 is empty. When a particular seat is sold, we
set the appropriate memory location to 1 (or any other nonzero number). Thus, if row 4,
seat 5 has been sold, then SEAT(4,5) = 1. A program to solve this problem is shown in
Figure 8-7.
7 READ(5,1)R,S
IF (R.EQ.-1)G0T03
SEAT(R,S) =1
GOTO?
C READ IN REQUESTS AND DETERMINE IF THE SEAT IS EMPTY
3 READ(5,1)R,S
IF(R.EQ.-1)G0T0 80
IF(SEAT(R,S) .EQ.1)G0T0 12
C SEAT REQUESTED WAS EMPTY SELL THE TICKET AND PRINT OUT MESSAGE ,
SEAT R S =1
( , )
WRITE(6,5)R,S
GO TO 3
C REQUESTED SEAT WAS FILLED LOOK FOR AN EMPTY SEAT IN REQUESTED ROW ,
12 DO 18 J = 1,6
IF SEAT R J( EQ 1 GO TO 18 ( , ) . . )
SEAT(R,J)=1
WRITE(6,5)R,J
GO TO 3
18 CONTINUE
WRITE(6,4)R
GO TO 3
C THE FOLLOWING STATEMENTS PRINT A PICTURE FROM ROW 10 TO ROW 1 OF '
S AND 1 ' S
C SHOWING THE SEATS SOLD AND EMPTY.
80 DO 17 I = 1,10
R=ll-I
17 WRITE (6,2) (SEAT (R,S) ,S= 1,6)
STOP
1 FORMAT (12, II)
2 F0RMAT(1X,6I3)
4 FORMAT 5X 'NO SEAT AVAILABLE IN ROW
( ,
'
, 13
5 FORMAT 5X 212 AVAILABLE
( , , '
'
END
Example 1 /
Each card of a deck of no more than 100 cards contains a person's name (20 characters)
followed by the person's address {li\ characters), state (2 characters), and zip code
number. Let us write a program names and addresses in memory and print four
to store all
sets of mailing labels for each person. The program to perform this task is shown in Figure
8-8. Since each name may contain up to 20 characters, it is not possible to store each name
in a one-dimensional array; five variables are needed, hence a two-dimensional array with
NAME(K,1), NAME(K,2). NAME(K,3), NAME(K,4), NAME(K,5) to represent the
name of the Kth person. The same is true for the address. Note, however, that the state
may be stored in a single-dimension array, since it occupies fewer than four characters.
STOP
1 F0RMAT(5A4,4A4,2A4,A2,I5)
3 FORMAT IX 5A4/1X 4A4/1X 2A4 2X A2 3X 15//
( , , , , , , ,
END
BRYAN STANDLEY
21 E. 4TH
PENSACOL FL 32503 —7 Four of each are printed.
WILSON HART
1814 N 12TH
MILTON FL 36609
Example 2
Suppose you have to alphabetize ten names, each eight characters in length. These names
may be stored, for example, in the INTEGER array N(10,2) as follows:
TWO- AND THREE- DIMENSIONAL ARRAYS 329
N(l,l) MICH
N(2,l)
N(3,l)
N(4,l)
N(10.
330 TWO- AND THREE- DIMENSIONAL ARRAYS
determine the highest score obtained on the third math test (P3).
To solve this problem we shall use a three-dimensional array. A, with three rows (for
three tests), ten columns (for ten students), and a depth of two (for programming and
math scores). For example, A(3,9.2) refers to the third math test of the ninth student, and
A(3,9.1) refers to the third programming score of the ninth student. Data is recorded on
data cards in the following sequence:
DO 10 1 = 1,3
DO 10 J = 1,10 Sum of all grades
DO 10 K = 1,2 per student.
20 AV J = AV J /6
( ) Average grade per student.
( ) .
t
ALARG = A(3,1.2)
DO 30 J = 2, 10
IF(ALARG-A(3,J,2) )29,30,30 70
29 ALARG = A(3,J,2)
30 CONTINUE \
WRITE(6,2) (AV(J) ,J = 1,10) A(3.K2)
2 FORMAT OSTUDENT AVERAGES
(
'
10F4.0) '
,
WRITE(6,3)ALARG
3 FORMAT OLARGEST SCORE ON THIRD TEST IS
(
' '
, F4 . )
STOP
END
STUDENT AVERAGES 67 32. 58. 74. 59. 56. 65. 54. 53. 52.
.
Example
Data regarding sales for a week have been tabulated as shown below:
Day
) )
,
blank out line DO 10 1 = 1,20
LINE(I) = BLANK
— 10 CONTINUE
IF(KSALES.EQ.O)GOTO 12
Insert number of DO 11 I = 1 ,KSALES
asterisks per line LINE(I)=CHAR
11 CONTINUE
WRITE (6,3) IDAY KSALES LINE , ,
20 CONTINUE
3 FORMAT ( 13 TIO 13 3X 20A1
'
, , , , ,
2 FORMAT (12)
STOP
END
the volume of the second day. etc. In the last column (column 7) we store no graphic sym-
bols (sales = 0). We then obtain an array GRAPH, which looks like:
GRAPHd.l)
GRAPH(3,1)
TWO- AND THREE- DIMENSIONAL ARRAYS 333
2 FORMAT (12) ^^
IF KSALES EQ
( GO TO 20
. . )
^^
100 DO 11 1 = 1, KSALES
11 GRAPH I, IDAY )= CHAR
(
20 CONTINUE -, f^^
JR0W=10 ^sr^^'^'-'^^
-.0
30 WRITE(6,3)(GRAPH(JR0W,J) ,J = 1,7
3 F0RMAT(1X,7(1X,A1)
OROW = JROW - 1
'lF(JR0W.GE.l)G0T0 30
10 WRITE (6, 4)
( 1 1 , )
4. Using implied DO lists, write the I/O statements corresponding to the following lists
of variables:
a. WRITE(6,10)A(4) ,A(5),A(6),A(7).---,A(90)
b. WRITE(6.4)B(1),B(3),B(5),B(7),B(9),--,B(99)
c. READ 5,2 )C( 2,1) .C(2,2),C(2,3).C(2,4),C(2,5)
d. READ(5,1)A(1.1) ,B(1),A(2,1),B(2),A(3.1),B(3)
e. WRITE(6,5)K,A(1,1) .B(1),B(2),B(3),K,A(2,1),B(1),B(2),B(3)
f. READ(5,3)A(1,1) A( ,2) A( ,3) ,B(2 1 ,B(2 .2) ,B(2 ,3) ,C( 1
, , , ) )
*C(2) .C(3)
g. WRITE(6,1)A(1,1) ,B(1,1).C(1,1),I,A(1.2),B(1,2),C(1,2).I,
*A(1,3) ,B(1,3) ,C(1,3) ,1
5. Generate the corresponding READ/WRITE list of variables for the following im-
plied DO lists, and specify the number of records (cards/lines) that would be process-
ed by the accompanying FORMATs.
c. (
(A(I.J) ,1 = 1,3) ,J,J = 1,3) F0RMAT(3F3.1,I1/(3F3.1,I1)
d. ( (A(I,J) ,B(I,J) ,J = 1,2) ,
F0RMAT(F3.1)
*I = 1,3)
e. (C(I) (A(I,J) ,J = 1,3)
, , FORMAT (6F4.1)
*(P(K,I) ,K = 1.2) ,1 = 1,2)
f. ( (A(I,J,K) ,1 = 1,2) ,K=1,3)
( F0RMAT(11F3.0)
*J = 1,2)
6. A is a 13 X 16 array. Write the code to print the rows (one per line) of array A in the
order of row 13, row 12, •••, row 2 and row 1; i.e., starting with the last row, on the
first output line etc.
d. 10 2. 20 3. 30 4. 40
50 6. 60 7. 70 8. 80
90 10. 100 II. 110 12. 120
e. 1 10 5. 50 9. 90 2. 20 6. 60 10. 100
3 30 7. 70 11. 110 4. 40 8. 80 12. 120
For part e, you may want to use a combination of a DO loop and an implied DO
list.
8. Generate the correct input statements to read the following with one READ state-
a. b.
d.
r
336 TWO- AND THREE- DIMENSIONAL ARRAYS
12. Read in two arrays, C and D, of size 3X3, given the following input on one card.
13. Write the code to determine the smallest element of an array. A, of size 10 X 10 and its
14. Assume an array, F, of size 40 X 1 7 that already contains data. Write the code to store
the rows of the array F sequentially into a one-dimensional array, G, of size 680 (40 X
17), as follows:
F(l,l) F(l,17)
Row 1
Row 2
F(40,17)
Row 40
L
m
F(l,l) F(l,2) F(l,17) F(2,l) F(40,17)
15. Assume the array A(10,3) has been read in; write a program segment to compute the
sum of the elements of the array A, and print the following with one WRITE state-
ment.
TWO- AND THREE- DIMENSIONAL ARRAYS 337
1. An array, A, has a size of 4 X 9. Write a program to interchange the first column with
the ninth, the second column with the eighth, etc.
2. Using the state sales tax tables shown below (courtesy of Internal Revenue Service),
write aprogram to read a "total available income" to compute a tax deduction for
general sales tax paid.
•
^?^''7.nnnn7H'!r''''^'''rT' $20,001 -$22,000 188 208 239 257 275 301
usnotover$40,000,fmdthemcomehnefor
$22,001 -$24,000 199 218 253 271 290 317
your State on the tables and read across to
$24,001 -$26,000 210 228 266 285 305 332
fmd the amount ofsales tax for your family
$26,001 -$28,000 221 238 279 299 320 347
size
,„B $28,001 —$30,000 231 247 291 313 334 362
^;
Step 3 — ,.
It your income is over ^.nnnf^
$40,000
but not over $100,000, find the deduction $30,001— $32,000 241 256 303 326 347 376
listed on the income line "$38,001 $32,00 -$34,000
1
251 265 315 338 360 390
-$40,000" for your family size and State. $34,00 -$36,000
1
261 274 327 350 373 403
For each $5,000 (or part of $5,000) of in- $36,001 -$38,000 271 282 338 362 386 416
come over $40,000, increase the deduction $38,001 -$40,000 280 290 349 374 399 429
by the amount listed for the line "$40,001 $40,001— $100,000 14 15 17 19 20 21
-$100,000." (See Step 3 B)
Step 3 C — If your income is over
$100,000, your sales tax deduction is limited to the deduction for income of $100,000. To figure
your sales tax deduction, use Step 3 B but don't go over $100,000.
On Schedule A,, line 13. enter the large of the sales tax estimate from this table or the amount
your records show that you paid.
3. Each card in a file consists of six data items organized as follows: a student number,
five test scores. There are at most 100 cards. For example:
I
111 10 20 30 40 50|
222 10 10 70 60 40
^
Read the data into a two-dimensional array. For example A(3,I), with I ranging from I
to 5, represents the third student's test scores. Compute the average score for each stu-
dent and the average score on each test. The format for your output is as follows:
Student
TWO- AND THREE- DIMENSIONAL ARRAYS 339
7. You own four warehouses across the country, each of which can stock five particular
items (see arrangement below). The data is recorded on one record in column fashion,
for example: 14, 15, 25, 5, 15, 20, 25, 3, • •, 16, 5, 20, 10. Write a program to read the
data into a two-dimensional array to produce the following output, identify any item
that has zero stock in three or more warehouses.
Total/warehouse
Warehouse 1 14
Warehouse 2 15
Warehouse 3 25
Warehouse 4 5
340 TWO- AND THREE- DIMENSIONAL ARRAYS
10. a. A small airplane has a seating capacity of five rows with three seats per row. Seat
reservations are handled by a computer. Seat preferences for each passenger are
recorded on cards with the name of the passenger, the row, and the seat number
punched on one card. If a requested seat is vacant, reserve the seat for the passen-
ger and print his name and seat number. If the requested seat is already taken, as-
sign seats in row-wise fashion, starting with seat I. row I, and move to the end of
the row before starting with the second row, etc. if and when all seats have been
taken print a message that the plane is full. In any event, whether the plane is full
or not print the seating arrangement with passenger names as shown in the dia-
gram below. Note that all seats on the output are identified by underlign charac-
ters. For example given the following input the output should be as follows
C GLEASON 5 2
( HORN 5 2
GOLDBERG
LGOLDBERG
MANUEL
3
3
1
1
r HORN
Name
/ Row
/
Seat
I
11. The Formfit Company manufactures brassieres and girdles. The company employs
ten salespeople. Sales, date, and amount of sales are recorded by the company on a
day-to-day basis whenever sales are made. This data is transcribed onto data cards as
follows (note that the transactions are noi sorted by salesperson number and can oc-
cur in random fashion):
Write a program to produce a monthly sales report summarizing total sales and total
sales for each salesperson. Transactions must be grouped by salesperson number and
listed in ascending salesperson number order. For example, given the preceding input,
the output should have the following format (input records are assumed to be in date
order):
12. You are the organizer for the National Swimming Finals, and you would like a com-
puter program to seed swimmers in the correct preliminary heats (races). Each swim-
mer's name and submitted time is recorded on punched cards. There are 16 swimmers
altogether. The swimming pool has four lanes only, and hence only four swimmers
can race at one time. The procedure for seeding is as follows.
Sort the swimmers by their submitted times and designate their heats as follows:
The swimmers in the first heat are those with the first, fifth, ninth, and thirteenth
fastest time. The swimmers in the second heat are those with the second, sixth, tenth,
and fourteenth fastest time. The remaining heats are determined in a similar manner.
Each card contains a name (16 characters maximum) and a time. Write a program to
read the 16 names into an array N(16,4) with each row containing a name (four
words) and the 16 times into the array T(16). Then:
c. Print names of swimmers with faster than average swimming time (one per line).
For example:
BOIL
N(2,l)
N(16,!)
342 TWO- AND THREE- DIMENSIONAL ARRAYS
HEAT NAMES
1 Name 1, Name 5, Name 9, Name 13
2 Name 2, Name 6, Name 10, Name 14
13. Rewrite the code for the program of Figure 7-14 to generate a class schedule, using
two-dimensional arrays.
14. John Livelong is thinking of buying a six-payment life policy of $20,000 on his twen-
tieth birthday. (Six-payment policy means that annual payments are limited to six
years.) John has been told that the earlier you buy life insurance the less expensive it
is; nevertheless, he would still like to see for himself the differences in annual pay-
ments for ages 20 to 26 (in yearly increments) and the total payments over six years in
each case. Write a program to produce the following report, using the table look-up
process.
JOHN LIVELONG
Age Annual premium Total premium/ 6 years
20 — —
21 — —
26 — —
The formula to compute the yearly premium for a $1 policy is
Example
The net annual premium for a six-year payment life policy for $ 1 .00 issued at age 22 is:
M, ,784,367.0723
P = = .0567
^22 - ^28 156,184,676.1673- 124,748,158.3773
TWO- AND THREE- DIMENSIONAL ARRAYS 343
Hence for a $3,000 life policy the payment would be $3,000 X .0567 = $170.10. Load the
A/, and A^v entries into arrays from the following table:
Age
344 TWO- AND THREE- DIMENSIONAL ARRAYS
17. The region shown below is a two-dimensional model of a section of a nuclear reactor.
The point marked S is the source of particles which are free to travel one mesh step in
any direction with equal probability. Points marked A are centers of absorption, and
any particle reaching such a point is considered to have been absorbed. Points marked
R are reflectors and return a particle to the point from which it came, taking a total of
two steps in the process. Points marked E indicate that a particle has escaped through
the absorbing medium. Blank points are scattering centers from which the particle
moves one mesh step in any direction with equal probability. Motion can be in the
horizontal or vertical direction only. The source is to be considered as a normal mesh
point.
EEEEEEE
E. AAA
A ... A A
R A
R...A...A...AEEAA
R A
R AAA
R E
R E
R E
R. S . . . A. . . A E
R E
R E
R E
R E
R AAA
R AAA E
R .... A EA EEA
EEAAEAEEEE
Write a program which starts individual particles one at a time from point S and fol-
a. Run 500 keep track of each particle in an array which records the
particles;
number of and whether the particle was absorbed or escaped. Termi-
steps taken
nate any particles remaining in the reactor after 500 moves and count them. Such
particles are neither absorbed nor escaped.
b. Print out the percentage of particles that escaped and that were absorbed.
c. Print out the number of particles that escaped versus the number of steps taken
(so many escaped on the fifth step, so many escaped on the sixth step, etc.). Do
the same have been absorbed.
for the particles that
d. Print how many particles escaped through the rightmost points.
TWO- AND THREE- DIMENSIONAL ARRAYS 345
No steps
346 TWO- AND THREE- DIMENSIONAL ARRAYS
Write a program to read the given numbers in an array and determine whether or not
there is a relationship between "major" and future success. If .v > 9.488, the rela-
tionship exists; otherwise, it does not.
Yes No
D D On religious grounds?
D n Because you believe the fetus has an absolute right to life?
Yes No
D D A woman has a right to her own body?
D n Abortion is a private decision for the parents alone to make?
n D Abortion can be a valid means to control population
growth?
n D No physical pain is inflicted on the fetus in the abortion
process?
The number of respondents should be at least ten. Either simulate responses or hand
out questionnaires to friends to be completed. Before you start writing the program,
think of the most efficient way to handle input and special code considerations. Try to
use just one two-dimensional array to store the responses of all ten candidates,
a. Determine how many yes, no, and undecided responses there were for the four
questions to be completed by those opposed to abortion. The printout should be
as follows:
TWO- AND THREE- DIMENSIONAL ARRAYS 347
Opposed to abortion
Yes No Undecided
Question 1
Question 2
Question 3
Question 4
17-3
TWO- AND THREE- DIMENSIONAL ARRAYS
Five of the differences are greater than or equal to 4, hence the element may be classi-
fied as a noise element. Noise elements should be replaced by the average of the sur-
rounding elements;
= 7 + 6 + 9 + 9 +2 + 8 + 8+1 =
in this case A(3,3) 6
21. A Digital Image Enhancement. Another problem in the analysis of images in digitized
form is sometimes difficult to recognize because of insufficient con-
that objects are
trast between the object and its background. One method that can be used to enhance
digital images is to reduce the number of distinct shades of gray from the number rep-
resented in the initial signal (ten in the example) to a lesser number such as five (black,
white, and three shades of gray), three (black, white, and gray), or even two (black and
white). This process is somewhat like increasing the contrast on a black and white tele-
vision set. With increased contrast some detail is lost but remaining images are more
prominent.
Exercise 20. Perform three enhancements: translate the image from the original ten
different values to five (low contrast), three (medium contrast), and two (high con-
trast) different values using the following table of transformations:
Original
TWO- AND THREE- DIMENSIONAL ARRAYS 349
n DRINKS H
2 V E R Y
RRIBLE4M0NKEY 5THE
As a result of the read operation, two arrays, WORD and KODE, would appear as
follows:
,WORD
350 TWO- AND THREE- DIMENSIONAL ARRAYS
23. A radio station has hired you to write a program to help them plan their air time. You
will be given 12 cards with the following information on each card: an integer record
identification, an integer representing record type (1 = rock, 2 = jazz, 3 = classical),
and a real number indicating playing time measured in tenths of a minute. You need
to do the following:
a. Read the three fields of each card one at a time into a two-dimensional array and
one real array.
b. Sort the arrays in ascending order by playing time.
c. Print the sorted arrays, one identification number, type, and corresponding
playing time per line.
d. Find the total playing time of each type of record and print in the order of rock,
jazz, and classical.
e. Find the classical record with the playing time closest to 10.6 minutes and print
the located record's identification number, type (3), and playing time.
Use DO loops and try to use a double DO loop for part d. The input data is as fol-
lows:
TWO- AND THREE- DIMENSIONAL ARRAYS 351
where a clear path exists, and ones are placed in every area where a land mine is set
(any person that steps on any portion of the square yard with a mine will be blown
up). Using the provided chart you are to follow the path free from mines and destroy
the enemy command post, being careful not to step on any areas with mines.
Initialize a two-dimensional array with ones for the squares in the gray area and
zeroes for the path free of mines (light area).
352 TWO- AND THREE- DIMENSIONAL ARRAYS
yth column
A.
/th row a,, a,: -a,,, I bi^\ = a,, 'hi, + a,:' b:, + + a,„ . b,„ = dj
i ':'
\
I I
Note:To multiply two matrices, A and B. the number of columns in A must equal the
number of rows in B. Such matrices are conformable.
a. Write a program to read two 4X3 matrices and compute their sum and difference
(in the case of subtraction, corresponding entries are subtracted).
b. Write a program to read a 3 X 3 matrix A and a 3 X 3 matrix B. Compute A • B
and (A + B)'{A - B).
c. Write a program to input N and compute A where A is a matrix that has been
read in.
A'' = A'A A
N matrices
d. Read in asquare matrix ^ and print out its transpose /I (the rows of /f are equal
to the columns of /I; row /of /l^ = column i of A).
26. The XYZ Company manufactures four products: P,, P., P,, P4. Each of these products
must undergo some type of operation on five different machines: A, B, C, D, E. The
time (in units of hours) required for each of those products on each of the five machin-
es is shown below:
TWO- AND THREE- DIMENSIONAL ARRAYS 353
Machines A B C D E
Rental cost/hour $10.00 $5.75 $3.50 $10.00 $5.76
Write a program to compute total rental expense for all machines. (Hint: Express
rental costs as a X 5 matrix and multiply by matrix result of part a.)
1
27. Write a program to verify that for any comformable matrices, X, Y, Z of your choice
the following is true:
a. A A is symmetric.
•
b. A + A is symmetric.
29. A strictly triangular matrix is a square matrix with all entries on and below the main
diagonal equal to zero. Write a program to show that if A is a 4 X 4 triangular matrix,
then A'^ = A«A«A«A is the zero matrix (in general A" = zero matrix if A is an // X n tri-
angular matrix.)
30. The trace of a matrix is defined as the sum of its diagonal elements. Let A be a 5 X 5
matrix and B be a 5 X 5 matrix. Write a program to demonstrate that tr(A'B) =
tr(B.A), and tr(A + B) = trA+ trB, where //-stands for the trace.
31. A method for computing the inverse of any matrix on a computer is as follows: Let A
be an /7 X // matrix, {n > 1). Then
f I
= — tr(A) (See Exercise 30 for the definition of the trace),
c. = -l/2(ri tr(A) + tr(A=)),
Cy = -l/3(r,tr(A) + r, tr(A-) + tr(A')),
Write a program to compute the inverse of a 5 X 5 matrix A and check that it is indeed
the inverse by verifying that A • A^' = (identity matrix). 1
32. A graph is a structure made up of a set of vertices and edges connecting the vertices. A
common means of representing a graph is with points and line segments as shown in
the example of Figure 8-13. In the example, the vertices are labeled 1 , 2, 3, • • -, 8; the
segments connecting the numbered points represent edges. For instance, there is
line
means of an adjacency matrix. An adjacency matrix has a row and a column for each
vertex in the graph. The graph of Figure 8-13 could be represented by the matrix A
shown in Figure 8-14. In an adjacency matrix A, the value of a,^ is 1 if there is an edge
connecting vertices / and /: the value of a„is zero otherwise. For example, «,, = 1 rep-
resents an edge connecting vertices 1 and 3.
I and 3, and 3 and 4. The sequence 12 would not represent a walk since no edge con-
nects these two vertices. The length of a walk is defined as the number of edges trav-
ersed in the walk. For example, the walk 134 is of length 2, since the edges 13 and 34
are traversed. The walk 14 is of length 1; the walk 13741 is of length 4. The matrix of
Figure 8-14 may be thought of as representing the number of walks of length 1 con-
necting any two vertices of the graph.
1
a,| fl|4 + fli2«:4 +
356 TWO- AND THREE- DIMENSIONAL ARRAYS
c. Write a program to analyze an adjacency matrix of size n. and output all con-
nected segments. (Handle as a special case segments of size one, that is, vertices
not connected to any other vertex.) Test your program using the graphs shown in
Figure 8-16.
2. Write a program to print the four diagonals of a 4 X 4 X 4 cube, using an index mecha-
nism of three subscripts.
3. Assume each vertical slice of a 3 X 3 cube contains a 3 X 3 matrix (the first vertical slice
is matrix /4, the second vertical slice is matrix B. and the third vertical slice is matrix Q.
a. Compute D = A + B + C.
b. Compute /I \
c. Compute A*B'C.
4. Write the program of Problem 4, Section 8-6-2a for a cube.
6. The following is the schedule of a small Pennsylvania airline. Write a program for
maintaining passenger reservations for three days (see Figure 8-17).
Date
TWO- AND THREE- DIMENSIONAL ARRAYS 359
2. A(1,1),A(2,1),A(1,2),A(2,2),A(1,3),A(2,3),A(1,4),A(2,4)
B(1,1,1),B(2,1,1),B(3.1,1),B(1,1,2),B(2,1,2),B(3,1,2),
B(1,1,3).B(2,1.3),B(3,1,3).B(1,1.4),B(2,1,4),B(3,1,4)
3. TC will compute the sum of each column.
TR will compute the sum of each row.
4. a. WRITE (
)(A(I),I=4,90)
b. WRITE )(B(J),J = 1,99,2)
(
5. a. A(1,1),A(2,1),A(3,1),A(1,2),A(2,2),A(3,2). 1 record.
b. A(1,1),I,A(2,1),I,A(3,1),I,A(1,2),I.A(2,2),I,A(3,2),I.
4 records.
c. A(l,l) ,A(2,1) ,A(3,1) ,J,A(1,2) ,A(2,2) ,A(3,2) ,J,A(1,3) ,
6. DO 10 I = 1,13
K=14-I
10 WRITE(6,6)(A(K,J),J = 1,16)
6 FORMAT (5X, 16F4.1)
7. a. WRITE( ) (
(A(I,J ,J = l ,4) ,1 = 1 ,3)
) JSUM(I ,J ,J=1 ,4) ,1=1 .3) ,VAR , ( )
FORMAT (4F5.0)
b. READ( )(A(1,J),J = 1,6),(B(I),I = 1.6)
FORMAT 2 3F5 0/( 3F3 ( . ) ,
( .
)
b. SUM =
DO 3 I = 1 5 ,
3 SUM = SUM + A 3 ( ,
1
c. ALARG = A(1,1)
DO 4 I =2,5
IF(ALARG.LT.A(I,1) ALARG = ) A( 1 ,
1
4 CONTINUE
d. DO 5 I = 1,5
5 B(I)=0
D06I = 1,5
D06J = 1,5
6 B(J) =B(J) -hA(I,J)
e. D07I = 1.5
7 A(3,I) =A(3,I) +A(2,I)
f. DO 8 I = 1 , 5
H0LD = A(I,3)
A(I,3) =A(4,I)
8 A(4,I)=H0LD
g. SUM2 =
D09 1 = 1,5
9 SUM2 = SUM2-hA(I,I)
TWO- AND THREE- DIMENSIONAL ARRAYS 361
h. SSUM=0
SLARG = A(1,5)
DO 16 1 = 1,5
J = 6-I
SSUM = SSUM-hA(I,J)
IF(SLARG.LT.A(I,J) )SLARG = A( I , J )
16 CONTINUE
i. READ (5, 3) I, J
3 FORMAT (211)
DO 17 L = 1,5
HOLD = A(I,L)
A(I,L) =A(L.J)
17 A(L,J)=HOLD
12. READ 5,3)
( ( (C(I,J),J = 1,3),(D(I,J),J = 1,3),I = 1,3)
'^
13. KROW = 1
K0LUMN = 1 A (fO/y
ALARG = A 1 1 ( , r.i^^^ ni.'^ ^-^ ry^
DO 5 I = 1,10 / \^^ "^^^
\J]
D05J = 1,10 A J^ '
IF(ALARG.GT.A(I,J) GO TO 5 )
ALARG = A I J ( ,
KROW = I
KOLUMN = J
5 CONTINUE
K=l
DO 10 1 = 1,40
DO 10 J = 1,17
G(K)=F(I,J)
10 K = K-hl
15. DIMENSION A( 10,3)
SUM =
DO 10 1 = 1,10
DO 10 J = 1,3
10 SUM = SUM-kA(I,J)
WRITE(6,5) (J,J = 1,10),((A(I,J).I = 1,10),J = 1,3) ,SUM
5 FORMAT T30
(
( FINAL /T5 10 COL 13 2X /3 T5 10F6 1/ /T5
,
'
'
, '
' , ,
)
( , .
)
*'SUMIS' ,F5.1)
.
9
FUNCTIONS
9-1 INTRODUCTION
The reader is probably familiar with many mathematical functions such as the square
root, and the exponential and trigonometric functions. These functions, as well as others,
are available to the FORTRAN programmer through the use of libraries that are provided
by the computer system. FORTRAN also allows the programmer to define and write his
own functions, which he may want to incorporate in the library (user or system library).
In any event, functions allow the programmer to transfer to a prewritten block of code
(routine) to perform a specific task. This is very convenient when the same task is to be re-
peated numerous times or at different places in a program. Functions relieve the program-
mer of writing the code for routine tasks while certain user-written functions can be shared
by different users, resulting in a significant economy of effort.
In this chapter we examine functions which are included with FORTRAN and
shall
also describe procedures for the programmer to define functions of his own. Consider, for
example, the following problem. An observer on shore sights a ship one mile away, mov-
ing along a line perpendicular to his line of sight. One hour later he sights the ship and
finds an angle of 25° between the two sightings (see Figure 9-1). How far has the ship trav-
eled?
Using trigonometric methods, it can be shown that the distance traveled in one hour
is X = tan 25°. A FORTRAN program to perform this calculation is shown in Figure 9-1
362
FUNCTIONS 363
The program makes use of the function TAN; the programmer does not have to write a
routine to evaluate the tangent function. Note that the argument of the function TAN
must be expressed in radians. One radian is equivalent to 57.296° (180° = tt radians),
hence 25° = 25/57.296 radians.
9-2-1 Definition
A function is a correspondence between one setof numbers, called arguments, and another
set of numbers, cdWed val ues of the fiiji£iian. For example, the square root function may be
used in a FORTRAN statement as follows:
Function value .Argument
/
Y = SQRT(16.
Figure 9-2 illustrates the use of the square root function to produce the square root of the
integers 1 through 7.
WRITE (6
364 FUNCTIONS
The mode of argument depends on the function used; for example, the SQRT
the
function requires argument to be real (see Figures 9-3 and 9-4). Functions may be part
its
The argument-expression (there must be at least one) may take the form of a cons-
tant, a variable, another function reference, or an expression containing constants, vari-
ables, arithmetic operations, and function references. The argument expression is eval-
uated to a single value, which is then passed to the function as an argument.
Logically, we can think of the function as being evaluated at the point of invocation
(where it appears in the statement). Internally, a transfer is made to a set of instructions
which calculates the value of the function based on the value of the arguments. Control is
then returned at the point at which the function is called. The mode (whether real, integer,
etc.) of the value returned by the function is determined by the mode of the function name
(integer if it starts with I,J,K,L,M, or N and real otherwise). Some functions may have
more than one argument as in the case of the function MINO which selects the smallest
value of the integer arguments:
AK = MIN0(I,J,K,L,3,5.NT)
/
'
I
^ I
'
^More than one argument.
Function value is stored
in AK as a real number.
The function returns an integer value
(Name MINO starts with M).
The argument of the function must always be enclosed within parentheses. The argument
itself may contain parentheses, as in:
366 FUNCTIONS
mode of the expression on the right is different than that of the variable on the left. The
mode conversion functions allow this operation to be performed within an arithmetic ex-
pression.
Example
If A = 3.andB = 2.
The transfer of sign and positive difference functions requires two arguments. Consider
the following:
ISIGN(3,-2) -3 IDIM(3,-2) 5
ISIGN(3,2) 3 DIM(3. ,2.5) .5
SIGN(-3. ,-2. -3. IDIM(-3.-2)
ISIGN(-3,2) 3 IDIM(-3,2)
The functions that return the largest and smallest of a sequence of arguments require
at least two arguments and may have any number of arguments.
Example
Suppose J = 3 and K = -2 Function reference Value
MIN0(3,9,7.-1,4) -I
MAX1(3. ,9.,7.,-l.,4.) 9
AMINO(J,K,J*K.J-kK) -6.
MAX0(J,K,J*K,J-i-K,14) 14
Answer: The listings of functions in Figures 9-3 and 9-4 are by no means exhaustive.
The reader is manual for the FORTRAN sys-
referred to the manufacturer's reference
tem available to him for a complete listing. Also, most installations have available
packages of statistical and other mathematical functions with a wide variety of
capabilities. When available, such functions may considerably reduce the amount of ef-
fort involved in program development.
Answer: Yes. For example, if A and XYZ are arrays, the following are valid function
references:
SQRT(A(4)), ABS(XYZ(L,J) )
5. Can the MAX/MIN functions return the value of the largest/smallest value contained
in an array?
Answer: Yes, but each element of the array must be listed as a separate argument. For
example: ^^i co-l£ ^^ 'f jzlc^
Answer: No. Some functions, such as ABS, INT, are said to be in-line functions, while
others are said to be out-of-llne functions. In-line functions are inserted by the FOR-
TRAN compiler in the FORTRAN whenever a reference to that func-
program itself
tion is made; i.e., the compiler itself generates the code for the function during the com-
pilation process. An out-of-line function, on the other hand, is stored in the system li-
brary, and the FORTRAN compiler generates external references to it; that is, the
compiler generates the necessary instructions to link the FORTRAN program to the li-
brary function program so that transfer can be established between the two programs.
Answer: No. The compiler will treat any reference to SIN as an array reference. There
are no "reserved words" in the FORTRAN language.
Note in Figure 9-5 the use of the FLOAT function in statement 1 1 to make the argu-
ment of the square root function a real argument. Note also the use of the MOD function
in statement 12 to determine whether I (possible prime candidate) is divisible by J. If 1 is
5 CONTINUE
STOP
31 FORMAT (125)
END
Determine graphically the breakeven point(s). A solution to the problem is shown in Fig-
Note that:
ure 9-6.
^ 7a ^
A- a' - + 28a + 64
=
A-'
^=
. 8.x^
>'
i6-T^T + 16
The numerator is then factored to yield ((a — 8).v+ 28)a + 64 as in statement 2 in Figure
9-6. The latter expression of the cost function is more efficient in terms of computations,
since it contains only two multiplications and one division as opposed to four and three,
respectively, in the original cost function. Both the cost and revenue functions are graphed
for values of a ranging from to II.
In Figure 9-6, the array KLINE is used to print each line of the graph. This array is
initially filled with 70 blanks. The integer value J of the revenue function and the integer
value L of the cost function are then computed for X = 0,1,2, • -, II. Each time, the
graphic symbols R and C are inserted in positions J and L of the array KLINE (statements
7 and 8). The array is then printed:
1 )
370 FUNCTIONS
10 FORMAT 1 X (
' '
, , ' , ' COST '
X =
2 C= (X-8. )*X + 28. )*X + 64. )/16.
( ( ( )
R=15.*X»EXP(-X/3. +0.5 )
DO 1 1 = 1.70
X = X + 1
IF(X.LT.12)G0T02
3 STOP
FUNCTIONS 371
The programmer must decide what portion of the graph she wants to retain, since she
cannot graph all those points close to the asymptotes. She may decide, as in the program
of Figure 9-7, to graph only those points that fall inwhere r
the area lies between -9 and
9. When writing the program, this means that the programmer must test the values for r
and graph only those points falling in the restricted area.
K = 9
18 vertical print
positions
= -9
Since graphs are printed on the printer output form with the v axis horizontal and the
X axis vertical, only 18 print positions (-9 to 9) would be used to print v = tan(.Y). To mag-
nify the graph for a better graphic display, a scale factor of 4 is applied to make use of 72
print positions (4 X 18) instead of just 18. The graph is then drawn one horizontal line at a
time using the array LINE to print a line of blanks except for the graphic character * in-
serted at position (TAN.v + 9)*4 on that line:
Example:
L1NE(2) LINE{37)
LlNE(l)
1) L1NE(3) LIN
\ /
\ = .V4(UinX + 9)*4 = }1
372 FUNCTIONS
0.0
FUNCTIONS 373
contains three test scores, to determine each student's best score combination and final
grade as well as the class average. The output can be visualized as follows:
Main Program
FUNCTIONS 375
Memory
t ^
1 ( Ij-^
376 FUNCTIONS
MAIN PROGRAM
TRANSFER
"AV = AVRGE(. .
.)
RETURN
CLASS = LETTER (. .
.)
Function subprograms are usually written to carry out generalized procedures that are
data-independent, for example, determining the largest element of any array, computing
the average or the standard deviation of any set of grades, etc. Parameters or arguments
(sometimes called dummy arguments
because they are used as placed holders) are used to
illustrate the waywhich the procedure (function) is to be carried out. These arguments
in
in turn must be specified by the program wishing to make use of the generalized pro-
cedure; for example, what is the name of the array whose largest element must be found?
What is the exact number of grades for which an average is to be calculated? A function
subprogram should be viewed as one logical component (module) of a total program that
might consist of numerous other logical components (subprograms).
Function subprograms can be catalogued in the system or user libraries if these func-
tions are to be shared by other users or used repeatedly by the programmer (in the same
way as the mathematical functions are stored in the libraries).They can also be part of the
jobstream, i.e., part of the deck that is submitted each time the program is to be run. Func-
tions can be accessed or executed from another program (main program or other subpro-
grams) by invoking the name of the function and by specifying a list of arguments.
FUNCTIONS
whQrQ function-name is the name of the function (any vaUd variable name), and a|,a2,flj,
These arguments can be variables, subscripted variable names, array names, cons-
tants, expressions, or function names.
The value of the function is returned in the name of the function (acting as a vari-
able).
The mode of the value of the function is implicitly defined by the function name. If
the name begins with I,J,K,L,M, or N, the function value is integer; otherwise, it is
real.
The reader may wonder how the compiler differentiates between a function and a ref-
erence to an array. For example, 8(3*1 - 1,2) could be a reference to a function or to an
element of the array B. If the variable B is dimensioned, then B is an array; if B is not
dimensioned, the compiler will treat any reference to B as a reference to a function subpro-
gram.
P\y P^ Py^
• •
1 /'n yre dummy
arguments used to pass the data to and from the call-
ing program. These arguments can either be variable names, array names, or
function names. Subscripted variables such as X(I) and constants are not per-
mitted as arguments in the function definition. Type is an optional parameter
) ;
378 FUNCTIONS
which specifies the mode of the value returned b\ the function. If type is omitted,
themode of the function value is imphcitly defined in the function name. If the
name starts with I. J. K, L, M, or N, the value is integer: otherwise, it is real.
The dummy arguments used in the subprogram are the names for the actual argu-
ments defined in the calling program and listed in the invocation statement. When the
voked).
The last statement in every function subprogram must be the END statement. Fol-
lowing are some examples of function subprograms:
Example 1 Function ALARG returns the largest value of any two arguments. \
Example 2
QUIZZ = (J +K + L)/3.
RETURN
END
IF QUIZZ 30 40 50
( ( , , ) . GT T GO TO 2
. ) Note the INTEGHR specifications
in both programs.
QUIZZ returns an integer value.
Y = QUIZZ(J,30,L)
FUNCTIONS 379
Example 3
Example 4
Example 5
380 FUNCTIONS
Example 6
FUNCTION RATE(Q)
RATE = 10
Y = RATE(3.2) IF(Q.GT.3.0)G0T03
RETURN
3 IF(Q.GT.5.0)G0T07
RATE = 20
Z = RATE(9.8 RETURN
7 RATE = 3
RETURN
END
{Q<3
3 < Q< 5
Q> 5
Note the use of the multiple RETURN statements but only one END statement as the
very last statement.
It is often necessary to write function subprograms that will process arrays of varying
sizes. In this case it is possible to use an integer variable to specify the size of the array in
the DIMENSION statement. A more detailed and complete discussion of variable
dimension for multidimensional arrays is presented in Section 10-5-2. In the following ex-
ample the subprogram will process arrays of varying sizes. The rows and columns are
passed as the second and third arguments.
The function AVER computes the average of the grades stored in ARAY. Being able to
use the variable dimension in the function subprogram allows the user to write one sub-
program to find the average of any array of any size. The reader is cautioned to check his
or her technical FORTRAN reference manual to ascertain whether the variable dimension
feature is available at his or her installation.
FUNCTIONS 381
X = SMALL(3.1,X)
S = C0T(A,B,T(3)) FUNCTION COT(X,Y,Z)
X = COT(T,Z,P) Function cannot invoke itself.
MIM = SUB(X,2*J,9.8)
FUNCTION SUB(X,J) Arguments disagree in number.
DIMENSION CART(IO) FUNCTION TIP(X,Y,Z) Z must be dimensioned in the
X = TIP(3,9,X,CART)
Since subprograms are separate programs that are treated independently by the com-
piler, variable names appearing in both the calling and called program can be identical
with no risk of confusion possible; likewise, duplicate labels are permissible, since the pro-
grams are compiled separately. For the same reason, if in a function subprogram the pro-
grammer wishes to refer to a variable that is defined in the calling program, he cannot use
the same name and hope that it will refer to the variable with the identical name in the call-
ing program. The only way to "communicate'' variables between programs is either
through the COMMON statement (see Section 10-2-4) or by passing the variable name as
an argument in the function-calling sequence. Consider the following examples:
Example 1
Z = FICA(PER)
1
382 FUNCTIONS
Example 2
FUNCTION FICA(HRS,R,Z
Same names,:
same values
DO 30 1 = 1, DO 30 1 = 1,10
READ(5,1)R TAX = HRS*R*Z
T = FICA(HRS,R,P 1 FORMAT TIO FICA=
(
,
'
' , F5 .
C{n,m) represents the number of ways to choose m objects from n different objects. For ex-
ample, if six people are on a ship and the lifeboat can hold only two, then:
This represents the number of different combinations of people who could be saved. One
approach to the problem is shown in the program of Figure 9-11.
The factorial calculation must be repeated three times to compute the result. The pro-
gram is greatly simplified by use of a function subprogram to perform the calculation of
factorials as shown in Figure 9-12. Note in the program of Figure 9-12 that the function
FACT is declared explicitly to be of integer mode in the subprogram. In the main program
FACT must also be included in an INTEGER statement to specify that it represents in-
teger data.
INTEGER COMB
READ(5,1)N,M
1 FORMAT (212)
NFACT = 1
DO 101 = 1,
10 NFACT = NFACT*: I
Factorial computation.
MFACT=1
DO 20 I = 1,M
20 MFACT = MFACT*I I
Factorial computation.
NM = N - M
NMFACT =
D0 30I = 1,NM
30 NMFACT = NMFACT* } Factorial computation.
COMB = NFACT/ MFACT*NMFACT (
WRITE(6,2)N,M,C0MB
2 FORMAT 1 COMBINATIONS OF
(
'
M3 ,
'
OBJECTS TAKEN ',13 ,
'
AT A TIME IS ' ,14
STOP
END
COMBINATIONS OF 6 OBJECTS TAKEN 2 AT A TIME IS 15
384 FUNCTIONS
WRITE(6,2)N,M,C0MB
2 FORMAT 1 COMBINATIONS OF ',13 OBJECTS TAKEN
(
'
,
' '
. 13 ,
'
AT A TIME IS '
, 14
STOP
END
INTEGER FUNCTION FACT N (
FACT = 1
DO 101 = 1,
10 FACT = FACT*I
RETURN
END
COMBINATIONS OF 6 OBJECTS TAKEN 2 AT A TIME IS 15
1. A function called IRAND' to generate random numbers between two specified integers
named IBEG and ITER. This function can be copied by the user to generate random
numbers if his or her installation does not have a random number generator.
2. A function called WIN to determine whether the customer has a lucky number and if
A program to accomplish the above is shown in Figure 9-13. Note the following:
1. The way in which IRAND and WIN are invoked (called) and how the arguments (pa-
rameters) are passed to the functions with the same name.
3. The way in which the function value in the function subprogram is returned to the call-
'The function IRAND can be used on any computer system to generate random numbers.
FUNCTIONS 385
The complete program shown in Figure 9-13 consists of three independent blocks of
code (or subprograms), which perform very specific tasks: the main program, which acts
as a coordinator between the other two subprograms; the IRAND program, which gener-
ates random numbers; and the WIN program, which computes an amount won or lost.
IRAND. STOP
END
The array SLIP in the function WIN really re-
fers to the array CARD in the calling pro- FUNCTION WIN SLIP, N) (
Function IRAND returns any integer value FUNCTION IRAND IBEG ITER ( ,
between IBEG and ITER (IBEG < ITER). In DATA IM IB IA/25211 32768 19727/
, , , ,
END
,,C.(T (%\^^
IRAND becomes any number from to I
Af ^V.\<L^
'<"
grammer can break program into smaller logical components that are easier to work
his
with, resulting in a more readable program. A subprogram can result in an economy of
code for procedures or tasks that are to be performed repeatedly at different places in a
386 FUNCTIONS
program. The code for the procedure is wrillen just once and is not recoded wherever it is
needed in the program.
Function subprograms that are to be used frequently should be compiled, debugged,
and thereafter included in the program in object deck form (or stored in a library). This
saves computer time, since the subprogram need not be recompiled each time it is to be
used. Subprograms may be written and shared by users through "share" libraries. A brief
subprogram description and its use (calling sequence) should be included in the listing of
the subprogram through comment cards.
In long, complex problems it may be possible to .segment the tasks that make up a
complete program; the programmer can write these tasks as subprograms and verify that
each subprogram executes properly. The complete program can then be constructed using
the already w ritten and debugged subprograms.
T = 10.6 T = 10.6
SUM = SUM + SQRT 2 1*T**2 - 3*T +
( . 1 ) SUM = SUM + SQRT( POLY T (
function-name {a^^a^.a^, •
-,«„) = expression
expression is any arithmetic expression that does not contain any subscripted vari-
ables. This expression will contain a^^a.^ay, -,0,, as well as possibly other variables
or constants, or references to function subprograms or previously defined statement
functions.
The statement function definition should precede the first executable statement of the
program but follow such specification statements as DIMENSION, INTEGER, etc. The
statement function definition can be visualized as follows:
Function \ y'T\ I I
Function RES = AV 3 ( . . 2 . 1 , 10 .
)
= 3+ ( 2 1 + 10 /2 + 10
.
)
use
^^J. " Real (actual) arguments.
Substitute these values
Answer is stored Name of for X. Y, and Z above;
in RES function i.e., X = 3, Y = 2.1 and Z =
,
10
When a statement function is executed, the value of the real (actual) arguments re-
places thedummy arguments in the expression of the function definition. If variables other
than the dummy arguments are used in the expression, then their current values will be
used when the function is evaluated. The use of a variable as a dummy argument does not
preclude its use as a variable later in the program. The only purpose of the dummy argu-
ment is to illustrate the way in which the real arguments are manipulated to produce the
function value.
In the expression of the function definition, the dummy arguments must be non-
subscripted variable names. In the calling statement of the function, the real arguments
can be subscripted variables or arithmetic expressions. As with function subprograms, the
real arguments must agree in number, order, and in mode with the dummy arguments in
the function definition. The mode of the value returned is determined implicitly by the
name of the function but can be changed by appropriate specification statements.
Examples ^
Y = F(T)
( Q
C ;
388 FUNCTIONS
K = COMB (8, 2
BONUS = 50.
X = PAY(40. ,5. )
X = 5*40 + 50 = 250
BONUS = BONUS -K 10
Y = PAY(50. ,4. )
Y = 4*50 + 60 = 260
C = 0.
TEMP = FAHR( 100
The value of C is
C = C-Fl.
I
FUNCTIONS 389
i. T(X) =SQRT(X**2 + 9. ) +A
A=ll
S = T(4) +SQRT(T(5) )
S = ^25+ 11 + v/>/34+ 11
The following are examples of invalid statement function definition or invalid refer-
ences to statement functions:
a.
) ) ) '
390 FUNCTIONS
The program uses the Gauss-Seidel iteration procedure, which involves starting with an
approximation jCq, >'o of the solution and computing successive approximations for a and y
using the following formulas:
}'„ + = - a: v,, ^
I
^f :
,)
It can be shown that this sequence of approximations a,, r, converges towards the solution
of the system of linear equations if:
The program in Figure 9-14 accepts as input the values a,, />,, r,, a.^ t>2. C: and tests to see if
the Gauss-Seidel iteration procedure will converge. If it will not converge, an appropriate
message is produced; if it will converge, the first eight terms of the sequence are computed.
Program Output
8.
XNEW( Q /Al * CI - B1*Q
) = ( 1 .
)
(
YNEW Q (
1 /B2
) C2 - A2*Q
= ( .
)
(
11 WRITE(6,2)A1,B1,C1,A2,B2,C2
IF(ABS(A1)*ABS(B2) - ABS( Bl ABSI A2 )
) ) 190 190 12 , .
12 WRITE(6.3)
Y=
DO 100 N= 1,8
X = XNEW(Y)
Y = YNEW(X)
WRITE(6,4)N,X,Y
100 CONTINUE
GOTO 10
190 WRITE(6,5)
GO TO 10
1 FORMAT (6F2.0.T80, ID
2 FORMAT 2X F3 X 4-
( F3 Y= F4, . ,
'
' , . , , . )
N (
3 FORMAT
, , ,
2X 3X XN 4X YN
•
•
, ' ' . ' ' . '
•
4 FORMAT 2X 12 2X F5 2 2X F5 2
( , . , . , , .
6 FORMAT (6F5.0)
200 STOP
END
FUNCTIONS 391
9-6 EXERCISES
9-6-1 Self Test
2. How could IFIX be used to round to the nearest hundred? To the nearest thousandth?
To the next largest integer?
3. What will be the value of each of the following if A = 100., B = -2.4, C = 81, D= 0?
a. SQRT(C) '
g. DIM(B,A) O
b. SQRT(SQRT(C) )^ h. AMIN1( A,B ,C ,D)
c. IFIX(B) -.'.' i. AMAX1(A,B,4.*B,C,D)
d. SIGN(A,B)- 'P^ j. ABS(B) +ABS(C)
e. SIGN(B,A) ^'^ k. ALOGIO(A)
f. DIM(A,B) ^^^'^ 1. SIN(D) +COS(D)
4. In the graph of Figure 9-7, what would be the difference if instead of using J = (tanx
+ 9)*4 to determine the position of the graphic character on the line we used J = tan.v
+ 35. Why do you think it is necessary to have a magnifying factor such as 4 in this
case?
5. What statement in the program of Figure 9-7 would you change in order to display the
graph of the tangent function in 126 print positions instead of 72?
6. Determine which of the following function subprograms are invalid. Give reasons.
d. DIMENSION A( 5) FUNCTION A( I, J, T)
INTEGER X S ,
Z = A(X,K,3*S)
e. T = BAD (1,2 -1-3,3* I) FUNCTION BAD (I, J, K)
f. M = TUT SQRT R S ( ( ) , FUNCTION TUT (RT,T)
g. S = MAD(3. ,2*S,-1) FUNCTION MAD (X,Y,K)
h. P=MAT(ABS(K) ,2,SIN(T FUNCTION (X,I,T)
i. S = C0T(A,B,C0T(3) )
FUNCTION COT (X,Y,Z)
j. DIMENSION Q( 100) FUNCTION DAM(T(1) ,T,J)
T = DAM(Q(1) ,Q,-4) DIMENSION T( 100)
k. WRITE(6,11)FUNC(1. ,2. FUNCTION FUNC X Y ( ,
392 FUNCTIONS
Z = CAN(T.3,6/L)
p. A = PAT(L,M,N) FUNCTION PAT (N,M,L)
N=l
M=l
L=3
RETURN
q. S = LARG(2,LARG(3,4) ) FUNCTION LARG( I J ,
)
8. Which of the following statement function definition statements are invalid? State rea-
sons.
arguments.
^ b. The argument of the ABS function must be real.
'"
10. Define one statement function that could be used for all statements 5,6,7,8.
5 Y= 3*X**2 + 2*X-1.
WRITE(6,1)Y
6 T = I*X**2+7*X-T0T
7 S = 3*X**2-K(2)*X + SIN(T)
SUM = S + T
8 IF(17*X**2 + MIN1(A,B)*X-SQRT(A) )1,2,3
11. Same exercise as 10, except that statement 5 is coded as Y = 3 *T**2 + 2*T - 1
f. e' = 1 + X + XV 2 + XV3
!
g. Y = Be"^''cos(V b^-a^x- t)
DO 10 1 = 1,2 _;> ,
^^
Y= (10-I)*P0L(A,B,C,-I) fcj)x ra^i^.^r^/ y _
10 WRITE (6, 14 )Y
'" '
^.^
14 FORMAT! IX. 17)
STOP
END
INTEGER FUNCTION POL A, B,C,X) (
y- ^\
"''
'
INTEGER A, B,C,X '
END 2,
'
,
J ) ,
394 FUNCTIONS
( , , '
'
'NOT BE FOUND'
STOP ^
fv
END
INTEGER FUNCTION FIND A B ( ,
INTEGER A( 3) ,B
FIND = -1
DO 10 1 = 1,
IF (A(I EQ.B) FIND = I ^
10 CONTINUE
RETURN
END
1. Find the square roots of a group of ten positive real numbers, one to a card (card col-
umns 1-5, with a decimal point punched in the field). Remember there are two roots,
a positive and a negative root.
2. Modify the program in Figure 9-1 to produce a table showing the distance traveled by
the ship for angles varying from 1° to 45°. How is the program changed if the ship is
3. You are dealt 13 cards. They are punched on one data card in the following manner:
the numbers 01-13 represent the spades from the 2 to the ace; 14-26 represents the
hearts from the 2 to the ace; 27-39, diamonds from the 2 to the ace; 40-52. clubs from
the 2 to the ace. The 13 numbers are not in order. How many kings are there? Use the
MOD library function.
4. The number of different poker hands of five cards that could be dealt from a deck of
52!
52 cards is (where 521 = 52*5 1*50 • • •
1). Write a function subprogram to
5!(52- 5)!
compute the factorial of any positive number and use that function to calculate the
above formula.
FUNCTIONS 395
5. A deck of cards contains an employee name, number of hours worked, and rate of
pay. Write a main program to read the cards and call a function subprogram to com-
pute each employee's pay. Hours in excess of 40 are paid at a rate of time and a half.
The printout should list the employee name, number of hours, rate of pay, and pay.
Sale Commission
$0.00-$ 500.00 1%
$500.01 -$5000.00 5%
over $5000.00 8%
Write a main program to read a sale (one per card) and use a subprogram to compute
the commission.
7. Same as Exercise 6 with the difference that eight sales are recorded on one card.
8. Write a function subprogram to calculate the difference between the largest and
smallest elements of an array of variable length.
11. The first card in a data deck contains the current date. Each succeeding card contains
(among other items) the date of the last time an item was sold, the number of items on
hand, the cost per item, and the regular selling price. A store plans a sale to try to sell
slow-moving items. The purpose of the program is to produce a report showing rec-
ommended sale price as follows: .
;
-
^ . d
However, any item that has been sold in the last 30 days is not to be put on sale. If
there is only one (1) of an item left in stock, it is not to be placed on sale no matter
when the last date of sale was. The amount of discount allowed is also subject to the
following rule: Sale prices may not be lower than cost. Write a subprogram to return
the cost of a particular item using a main program to read the data and to produce a
finalized report for all items read.
b. Same a part a except that it is not known whether the elements of A are in ascend-
ing or descending order. \
13. You have 50 students. For each you have a The student is al-
name and ten test scores.
lowed to drop his or her lowest score before Use a subprjjgram
an average is figured.
to find the surrLpf the scores for each student/and a nother subprogram to find the in- m
imu m sc Qie. Print the student's name and average. (The sum subprogram should be
general to allow an array of any dimension.)
396 FUNCTIONS
14. Write a program to read sets of data on cards as follows: The first entry on a card
(card columns 1-2) N
and represents the number of numbers to be read from the
is
card for the first set of data. These N numbers are punched on one card (three col-
umns each with one implied decimal place) starting in card column 3. N may not ex-
ceed 25. There is a maximum of 50 data cards. Write a program to compute the aver-
age of each of the .sets of data and then of the combined set of data using a function
subprogram to compute the average of each set of numbers. The input and output can
be visualized as follows:
02 I 80 60 Data set I
19.5
04 I 195 40 60 805
40.0
60.0
80.5
Four numbers
Average data set I is 50.0
Data set 2
N = 4
80.0
N<25 60.0
Ouipui
15. Given a.v- + h\ -I- c = 0, the roots (values for .v which make the statement true) are
h ± \/ h' - A ac.
found by The main program will read values for a. h. c. If a is
zero, then there is only one real value for .v(.\ = - c/b). if/?' - Aac is negative, then
there are two complex roots for a. U h' — Aac is positive or zero, then there are "two''
real roots for a as found by the formula. Write a subprogram that returns a if o = 0; 1
returns a 2 if /?' — Aac is negative, and returns a 3 if /?' — Aac is positive or zero. Then,
depending on what is returned, write an appropriate message or answer.
16. Write a function to calculate the standard deviation of a set of data ilcins contained in
b. y = ax- + hx~ + ex + d
c. q = X sin(A) -I- .v- cos(.v) where a is to be expressed in degrees.
d. The difference between the largest and smallest values in a list of six real values.
18. Use a sta tement function to compute the square root of 43, using the formula
A- = —(.V
1
2
-t- —
43
)
.
- 43,|
,
< .01.
A-
19. Input values for a and /. Write a program using statement functions wherever possible
to compute .v as follows:
+
i'-iy
I ,
FUNCTIONS 397
+ (.-i),-.
la -—)?"' + sin(flO
(These formulas are used to determine the stress coefficient of certain plastics under-
going dilation by heat.)
20. Iterative methods for solving systems of linear equations (illustrated in Figure 9-13)
can be terminated in either of the following methods:
a. When |a„+ I
- A„| < e and r„+|-r„| < e where t is a prescribed degree of ac-
curacy.
b. When a„ and r„ are substituted back into the equations and the numerical results
are within t of the constants on the righthand side of the original system of equa-
tions.
Write a program using the Gauss-Seidel method to solve a system of equations and
use programmer-defined functions to terminate the iterative process using both of the
above termination criterion. Set e = .01
. . .
=
x^ ,x^ x\!-•••
sm(.v) A' 1
3! 5! 7!
where a' is expressed in radians. Write a program to calculate values of sin(.v) using the
first five terms of the equation for values of a- ranging from 0° to 90° in increments of
10°. Compare the value you get with the value returned by the FORTRAN function
SIN.
e = liml I
,,-a. \ n /
23. Write a program to show that as n gets larger and larger, the following expressions
converge to one limit. Can you guess at the limits from your printouts?
tv + 1
a.
n + 1
log(^0
n'\og{\ +^)
—
398 FUNCTIONS
24. Write a program to determine the limits of the following expressions as x approaches
0. (Let A range from 1° to .1° in steps of .1°.)
sin(.v) , .V sin(jc)
X 1
- cos(,v)
tanCv) 15/
b. __ e.
X tan(6/)
c. —
tan(2.v)
^^
sin(7.v)
-
25. Using the exponential function EXP(X), compute EXP(l). The value off to eight
placesis 2.71828182. Can you obtain a better approximation than EXP(l) by using
"
e'= 1 +—+—+— +• +— +
1!
2
2!
3
3! n\
•
27. The Toystar Corporation is marketing a new toy. Expected revenues are approx-
imated by the function >' = 3 s/lc. Costs associated with the production and the sales
of the toy are defined by the function y = 1 x' /A. Write a program to determine -\-
graphically the breakeven point for the production of the new toy.
28. Write a program to graph the total profit function of the example in Exercise 26. The
total profit function is defined as the difference between the cost and revenue func-
tion, that is, T{x) = \
R(x) — C{x) |
, where R, C, and Tare, respectively, the revenue,
FUNCTIONS 399
the cost, and the total profit functions. In the case of Exercise 26, identify on the total
profit graph the point at which profit is maximum.
29. Sometimes it is helpful to expand or contract a graph. Scale factors are used for this
purpose. Rewrite the breakeven analysis program of Section 9-4-2 to change both
graphs by using the functions:
where n is a scale factor accepted from input. If « = the graph should be identical to 1 ,
the one depicted in Figure 9-6. If a7 = 10, the graph should be steeper, and if /? = .5 the
graph should be wider (more elongated). Try various scale factors.
30. Determine graphically the roots of y = x sin(x) as x varies from to Svr. You may
have to use a scale factor. Remember this will not affect the roots.
32. Write a program to plot a circle. Hint: The equation of a circle of radius r centered on
the y axis passing through the origin is given by:
iy — ry + x' = /•'
or y = ± \J r — x^ + r
Plot both branches by adding .5 to the r positive branch and -.5 to the y negative
branch. Use r = 4.5 initially.
A = 100*IFIX((A + 50.)/100.).
A = IFIX(A + .5).
4. The values for lanx for values of .v close to 0, tt, 2-k, etc., would appear to fall on a
straight line, because the differences among successive values of the function are small
in these interals. The factor 4 is needed to "magnify" the differences so that they are
visible on the graph.
5. DIMENSION LINE(120)
J = (Y + 9)*7 + 0.5
5 I F(J- 120)6,6,11
b. A(T,AI,J) =P*(l-hAI/J)**(J*T)
c. SINT(R,N) =P*(l-hR)**N
d. R(R1,R2,R3) = (1./R1 + 1/R2 + 1./R3) **(-!)
e. HF(A,TI,TO) = 92*A* TI - TO)/H . (
and array FINAL 2 contains the eight final grades of class 2. To ensure fairness in both
classes, Dr. X assigns final grades as follows:
1. Both class averages are computed; AV 1 for class 1 and A V2 for class 2.
2. If A V < A V2,
1 all class 1 students get five percent of A V added
1 to their grades.
3. If A V > A V2,
1 all class 2 students get five percent of A V2 added to their grades.
Write a program to print the original scores and the adjusted scores. Both input and out-
put can be visualized as follows:
Input Output
402 SUBROUTINES
A program to solve this problem is shown in Figure 10-1 .The program m the left column
of Figure 10-1 is written without subroutines and the program in the right column is writ-
ten w ith subroutines. Note the use of:
1. The CALL statement, which is used to call for the execution of a subroutine and to
The program shown in Figure 10-2 consists of three independent program segments, each
performing specific tasks. These program segments are:
1. The main program, which coordinates the use of the two subroutines AVRGE and AD-
JUST.
2. The AVRGE program, which computes and returns to the main program the average
of N scores stored in an array. CLASS.
3. The ADJUST program, which adds a constant (BONUS) to each of the N grades in the
array CLASS and stores these adjusted grades in an array called FINAL.
The three programs are compiled independently of one another. Through the CALL state-
ments, information (such as the score arrays, the number of scores) is passed from the call-
ing program to the called program by means of arguments or parameters specified in the
CALL statement and also in the SUBROUTINE definition statement.
Arguments can be used as two-way or one-way communication links between the call-
ing and the called program. In the AVRGE program CLASS is a one-way parameter in
the sense that the main program specifies the values for the array, FINAL, and these are
not changed in the subroutine. In the case of the AVG parameter in subroutine AVRGE,
AVG is used to transmit a result from the subroutine back to the main program. The cor-
respondence between arguments is illustrated in Figure 10-3. Information and results be-
tween the called and calling program are thus passed by means of arguments.
The flowpath of data between the three blocks of code can be visualized as shown in
Figure 10-4. Note how it is possible, through the use of subroutines, to avoid duplication
of code as shown on the righthand side of Figure 10-4. Whenever a procedure (task) is to
be performed, a transferis made (through the CALL statement) to that procedure which
when completed returns (RETURN) to the program that called the procedure. In the case
of the program in Figure 10-1 instead of twice writing the code to determine the average
,
and to adjust the scores, one block of code is written which is called twice by the main pro-
gram.
Finally the reader may come to think that there is "no big'" difference between a func-
tion and a subroutine subprogram. Indeed the difference is barely noticeable — in fact, the
AVRGE program could have been written as a function subprogram since only one result
is passed from the subprogram to the main program. In the case of the ADJUST program,
however, eight results are passed back to the main program: i.e., the entire array FINAL 1
or FINAL2 is changed by the subprogram and sent back to the main program.
SUBROUTINES 403
D05I = 1,10
SUM = SUM + FINALI(I) CALL AVRGE FINAL2 AV2 8 ( , , )
CONTINUE
AVI = SUM/10 IF(AV1.GT.AV2) GO TO 20
D03I = 1,8
SUM = SUM + FINAL2(I) GO TO 2
CONTINUE
AV2 = SUM/8 CALL ADJUST FINAL2 8 FINAL AV2 ( , , ,
IF(AV1.GT.AV2) GO TO 20 STOP
FORMAT IX (
,
END RETURN
6 FORMAT IX BONUS= F5 1/
(
,
' ' , .
END
404 SUBROUTINES
stores the result (average) into AVG, which is the same mem(
ry location as AVI.
CALL AVRGE(FINAL2,AV2,8) The AVRGE program is called once again, but this time it w
compute the average of eight grades stored in FINAL2. The
resulting average is stored in memory location AV2 (called
AVG in subprogram).
IF(AV1.GT.AV2)GOTO20 Determine which class has lowest average.
10 CALLADJUST(FINAL1,10,FINAL,AV1) The ten grades in FINALl and the average of class (AVI 1
END
SUBROUTINE AVRGE(CLASS,AVG,N) This program is coded to perform the following general func-
REALCLASS(IO) tion: Compute the average of N scores stored in an array
SUM = called CLASS. The resulting average is stored in AVG. Any
DOS = I.N
I array argument must be declared as an array in the subroutin
SUM = SUM + CLASS(I) If AVI < AV2 (Statement 10 CLASS be-
in main program),
CONTINUE comes dummy name for array FINALl, i.e., CLASS refers
a
AVG = SUM/N to array FINALl If AV2 < AVI (statement 20 in main pro-
.
RETURN gram), then arrays CLASS and FIN,'\L2 are one and the sam
END
SUBROUTINE ADJUST (CLASS, K,FINAL,AVG) This program is coded to perform the following generalized
REAL CLASS(10),FINAL(10) procedure: Initialize the elements of array FINAL (K ele-
BONUS = AVG*0.05 ments) to the K scores in array CLASS and add BONUS to
D09 = 1,K
1 each of the FINAL scores. BONUS equals five percent of the
FINAL(I) = CLASS(I) + BONUS average of the scores in CLASS (AVG).
CONTINUE FINAL corresponds to FINAL in main program.
WRITE(6,6)BONUS,(FINAL(l),l = 1,K) CLASS corresponds to either FINALl or FINAL2.
RETURN K corresponds to either 10 or 8.
F0RMAT(1X,'B0NUS = '.F5.1/1X, AVG corresponds to either AV I or A V2.
'ADJUSTED GRADES71X,10F5.1)
END
Memory
FINAL 1 |60
FINAL 2
406 SUBROUTINES
Transfer
-CALL AVRGE
Return
CALL AVRGE
AVRGE CODE
CALL ADJUST-
CALL ADJUST-
ADJUST CODE
END
Subroutint
±
ADJUST CODE
Subroutine
pie, sorting or merging of any arrays, computation of averages for any set of grades, etc.
Parameters or arguments (sometimes called dummv arguments} are used in the subrpjiime
to illustrate the way in which the procedure is to be carried out in the subroutine. These
arguments must be specifically identified by the program wishing to make use of the gener-
alized procedure. The name of the particular array to be sorted and the exact number of
grades for which an average is to be computed are examples of arguments which might be
passed to a subroutine.
A subroutine should be viewed as one logical component of a total program that
might consist of numerous other logical components (subprograms). A subroutine can be
accessed (executed) from another program (main program or other subprogram) through
the use of the CALL statement.
ceive data (values, results) from the called program. Arguments are optional.
Examples
CALL SUB X ( )
One argument is passed to the subroutine called SUB.
CALL XRAY '^o arguments are passed to XRAY.
CALL SI (A B(l) 3*1 +K J) Four arguments are passed to the subroutine; 3*1 + K is
PAT T 9ITRP / <^TM/ Y ^ Y^ The sine of X will be evaluated and the value passed to
SUB2 as the first parameter.
DIMENSION statement within the subroutine. The size of that array should be the same
as the size of the corresponding argument (array) in the calling program (see Section
A
408 SUBROUTINES
10-5-2 for exceptions). The duninn arguments used in the subroutine refer to the actual
names or arguments listed in the the calling program. When the
invocation statement o['
integer integer
XX is same as X.
J is same as 2 (J = 2).
SUBROUTlNt SUB(XX. J . S . K Z
.
) S is same as T.
K is same as L.
Z is same as 3.5 (Z = 3.5).
integer integer
Example 1
ly-
It should be emphasized again that the subroutine can change values in the main pro-
gram. Consider the following example:
Kxample 2
SUBROUTINE TRKX.C)
A=4 X = 7.
CALLTRI (A,B C = 3.1
WRITE (6,1) RETURN
END
SUBROUTINES 409
A is 4 when the CALL is made to the subroutine; on return to the main program, the value
for A will be 7.
The value of any expression in the CALL statement is calculated before passing val-
ues of parameters to the subroutine.
Example 3
SUBROUTINE SUB4(A,B,C)
X = 3.
Y = 2.
CALLSUB4(X,X + Y,3.*Y:
The value of A will be 3.; the value of B will be 5.: the value of C will be 6.
CALL statement. The array name used in the subroutine must be specified in a
DIMENSION (REAL, INTEGER etc.) statement and its size must equal the size of the
corresponding array in the calling program.
Example 4
Note
Main program Subprogram
^DIMENSION X( 10)
S =
CALL SUMIT(A,SUM1 DO 10 1 = 1,10
10 S = S + X(I)
RETURN
CALL SUMIT(B,SUM2 END
Two calls to subroutine SUMIT are made. As a result, SUM 1 and SUM2 will contain the
sum of the elements of array A and B respectively.
The following are incorrect SUBROUTINE statements:
Main program
;
410 SUBROUTINES
subroutine. A distinguishing feature of the subroutine is that at its conclusion the state-
ment to which transfer (return) is made in the calling program is variable (unlike the GO
TO statement). The return point depends on the statement at which the subroutine was
called. The last statement of a subroutine must always be the END statement.
Since subprograms are really separate programs that are treated independently by the
compiler, variable names appearing in both the calling and called program can be identical
with no risk of confusion possible; for instance,in the following example the variables
HOURS and RATE are used in both the calling and called program but there is no rela-
tionship between them. The content of the variable Z is directly related because it is used
as a dummy argument and as a real argument.
whatsoever:
HOURS = 30 different values SUBROUTINE FICA(Z
READ (5,1) RATE
PER= .485
CALLFICA(Z) TAX = HOURS*RATE*Z
In the same way, duplicate labels are permissible since the programs are compiled inde-
pendently. For example:
CALL SUB (
412 SUBROUTINES
As a result of the CALL statement in the main program. TOTAL = (X(l) + A + B(2))/l
Example 3
Memorv
COMMON X( 4) ,B,C(2:
CALL COT
COMMON block
SUBROUTINES 413
a new program in the job deck. Special system control cards Gob control, workflow, etc.)
may be required to separate each program from one another as depicted in Figure 10-5.
The student should determine the proper control cards required by his or her computer
system.
Answer: A subroutine can be an aid in writing shorter and more compact programs.
The programmer can break his program into smaller logical components that are easi-
er to work with, resulting in a more readable program. A subroutine can result in an
economy of code procedures or tasks that are to be performed repeatedly at dif-
for
ferent places in a program(s). The code for the procedure is written just once and is
not recoded wherever it is needed in the program.
Subroutines that are to be used frequently should be compiled and tested until
thoroughly debugged and thereafter included in the program in object deck form (or
stored in a library). This saves computer time, since the subroutine need not be recom-
piled each time it is to be used. In that perspective, subroutines may be written and
shared by users through "share" subprogram libraries. A brief subroutine description
and its use (calling sequence) should be included in the listing of the subprogram by
means of comment cards.
2. There are no repetitive tasks in most of the programs I write. Are subroutines of any
value to me?
414 SUBROUTINES
these tasks, and verify that each subprogram executes properly. The complete pro-
gram can then be constructed using the already written and debugged subprograms.
Answer: No. Logically the STOP instruction cannot get executed, since RETURN
will pass control back to the calling program.
RES = A + B
There is no need to initialize RES to any value in the calling program.
• SUM = SUM + K
CALLTX(Y,4) RETURN
As a result of the first call to TX, the value of SUM 3. The second time through TX,
is
SUM will equal 7, not 4. If you need to reset SUM to 0, use the statement SUM = 0.
7. Can a subroutine use a STOP statement?
Answer: Yes. Consider the following example:
SUBROUTINE QUAD A B ( . , C X
, , ROOTl R00T2,
)
DISC = B**2-4*A*C
IF (DISC.NE.O)GOTOl
2WRITE(6,11)
11 FORMAT (T20, 'ROOTS ARE IMAGINARY
STOP^-^^^^^^^^^
1 ROOTl =77~~"~-~Note the STOP slatcmcnt.
tion of the complete program. A flag can be used in the subroutine and tested in the
Answer: Yes, as long as the subroutine does not call itself. Nor can a subroutine call a
subroutine that calls the original subroutine. You must avoid calling sequences that
result in a closed loop, such as:
MAIN PROGRAM
SUBROUTINE A
SUBROUTINE B
Example
COMMON arrangement
COMMON X(4) Xi
COMMON A,
COMMON Z(2)
416 SUBROUTINES
The value of the second parameter is changed to 6 by the subroutine; however, the ac-
tual parameter is a constant 3. This can have an unpredictable effect in the program.
Similarly, the value of the third parameter is changed by the subroutine, but the actual
parameter is an expression and not a storage location.
Answer: Yes, you can write a function to perform the exact same tasks as a sub-
routine; however, this is contrary to the purposes of a function subprogram. A func-
tion is generally used to return a single value to the calling program via the function
name. A subroutine should be written when the value of more than one variable is to
be changed.
13. Why would I ever want to write a subroutine without arguments such as CALL SUB?
Answer: Perhaps you might want to write a subroutine just to set up headings for each
page of a lengthy computer-generated report or to control the printer for special edit-
ing effects, or you might want to use SUB in conjunction with a data set defined in a
14. Can a subroutine use arrays that are not declared as arguments or in a COMMON
statement?
may decline to 1.5 percent in the next year. Should Mrs. X. buy the condominium now or
1
wait? The program in Figure 10-6 can be used to help make the decision. Note the use of a
subroutine to calculate the total cost for each option. The formula to compute the month-
ly payment is:
SUBROUTINES 417
interest
principal*
p
monthly payment
'-•>'-'"
(interestX
REAL 11,12
11= .14
12= .115
PI = 55000.
PL = 60000.
WRITE (6, 5)
5 FORMAT T4 INTEREST 2X PRINCIPAL 2X MONTHLY PAYMENT
( ,
' '
, ,
'
' , ,
' '
, 2X ,
'
TOTAL
CALL CALC 1 1 PI PAYMT TOTl
( , , ,
1 FORMAT T5 F5 3 T15 F6
( . T29 F6 2 T40 FIO 2
. , , . , . . , , .
DIF = T0T1-T0T2
WRITE 6 1 12 P2 PAYMT T0T2
( , ) , , ,
WRITE(6,2)DIF
2 FORMAT ('OTHE DIFFERENCE IN TOTAL COST IS ', F9. 2
STOP
END
REAL I, LOAN
LOAN= .2*P
PAYMT = LOAN* (1/12. /(I. -(1. +1/12. )**( 360. ) ) )
=
-b + V b- - Aac
=
-b - J b~ - 4ac
X] .V2'
2a la
) )
418 SUBROUTINES
\( b- — 4ac < 0, then the solutions are complex. The program shown in Figure 10-7 uses a
subroutine to solve quadratic equations. Iflhe solution cannot be found, because the roots
are complex or because the equation is not a quadratic {a = 0). the subroutine sets a flag
which can be tested by the main program. Otherwise, the two solutions are calculated.
INTEGER FLAG
*
100 READ(5,8.END= lOlA.B.C
8 F0RMAT(3F10.0)
CALL QUAD (A, B.C. XI, X2, FLAG )
WRITE(6,11)A,B,C
11 FORMAT! 0A = '
.F11.0,2X, B= '
,F11.0,2X, 'C = '
.Fll.O)
IF(FLAG.EQ.1)G0T0 30
20 WRITE(6,13)X1,X2
13 FORMATi + ,T50, 'Xl = ,F11.3,2X, 'X2 =
' ' ' '
,F11.3)
GOTO 100
30 WRITE(6.12)
12 FORMAT( + .T50, 'NO SOLUTION'
• '
GOTO 100
10 STOP
END
times, using a subroutine for sorting is an efficient way to construct the program. Also,
since the output of an array is performed several times, the code to produce the output can
be placed in a subroutine. A program using a subroutine to perform the sorting and a sub-
routine to perform output is shown in Figure 10-8. A header card in the data deck in-
dicates the number of grades of each class. Grades are recorded one per card. Assume
there will be no more than 50 students in each class.
SUBROUTINES 419
D0 30 I = 1,N1
30 GRADE(I) = GRADEl (I
D0 40I = 1,N2
Merge grades in one array.
J=N1 + I
40 GRADE(J) =GRADE2(I .
STOP
END
termine each class's grade average and the number of grades below the average and to pro-
vide a listing of grades with appropriate headings. The reading of the data cards must be
performed in the main program. One subroutine will take care of all output functions,
while another subroutine will calculate the class average and the number of grades less
than the average. Both the input and desired output can be visualized as follows:
420 SUBROUTINES
Inpiii Oiitpui
Top of neu
pagc MATH 102
80
90
73
45
AVERAGE = 54.0
COUNT OF GRADES BELOW AVERAGE IS 13
ART 301
50
64
96
The array HEADER is used to store the dif- DOUBLE PRECISION HEADER( 2)
ferent class sections.
No more than 100 students (grades) per class. INTEGER GRADE (100)
Read and process both subdecks. DO 5 1 = 1,2
Read the number of grades, section number READ 5 6 N HEADER GRADE
( , ) ,
,
( ( I) , I = 1 ,
and grades one subdeck at a time. 6 FORMAT (12, 2X, A6. A5/(I3 )
Subroutine AVRGE will compute the average SUBROUTINE AVRGE SCORE L SUM LOWl) ( , , ,
DOUBLE PRECISION H( 2)
Subroutine PRINT will print a heading found INTEGER GRADE (100)
in H( and H(2) on a new page, with N grades
1 ) WRITE(6,5)H(1) ,H(2) (GRADE (I) ,1=1, ,
, .
422 SUBROUTINES
r START
J
In the case of arrays A and B, subroutine ADD will add correctly these two arrays
and store the resulting array in C. In the case of arrays T and Q, however, the subroutine
will add these two arrays incorrectly. The cause for this is in the way the compiler trans-
lates a two-dimensional address (row, column) into a one-dimensional (or linear) address.
The subroutine array X(3,3) is represented by the compiler as a linear structure of nine ele-
ments arranged in column order as shown here:
^n
)
424 SUBROUTINES
One way to correct the problem is to make use of the variable DIMENSION feature
(variable DIMENSIONS are not available on all compilers), which allows the user to ad-
just the size of the array defined in the subroutine to the size of the corresponding array in
the main program (calling program). Integer variables in the subroutine DIMENSION
statement are used to reflect the varying sizes of the arrays.
For example, the problem of adding corresponding elements of two arrays could have
been coded as follows:
• RETURN
END
CALL ADD T Q R 2 2( , . , , )
Note that in this program it is now possible to add arrays that are not necessarily square.
It should be noted that in the case of one-dimensional arrays it is not necessary to use
variable DIMENSION, since one-dimensional arrays are addressed linearly. Consider the
following valid code:
DIMENSION X(l)
• •
N = 36
CALL SUB (B,N)
Note that the DIMENSION statement in the subroutine could just as well have been
DIMENSION X(IOO), DIMENSION X(IOOOO). The compiler does not reserve memory
storage for arrays defined as arguments in subroutines, since storage is already reserved
for those arrays in some other subprograms. The DIMENSION statement, however, must
be present in the subroutine if any arguments are arrays. This is required for addressing
purposes for the compiler. Variable dimension should be used when writing subroutines
that process variable size two- (or more) dimensional arrays. Unfortunately, some ver-
sions of FORTRAN do not allow for the variable DIMENSION feature. When writing
programs for such systems, it is necessary to simulate the procedure used by the compiler
in calculating the address of a two- (or more) dimensional array element reference.
The formula to compute the linear address of an array element, X(I.J), of an array, X,
of size NR rows and NC columns can be computed as follows: Consider the array X:
SUBROUTINES 425
Number of rows
Number of columns
DIMENSION X(NR,NC) (nr, NC represent integer constants)
Row 1
m. m
Row 2 i
Row 3
Ith row
Row I
^ I
X(I,J)
Jth column
X(I J) is 1 positions away
from the beginning of
Row NR
i m i column J.
(J
- 1) full columns before we get to column J
plus I positions down in the Jth column. Since each column consists of NR elements, the
hnear address L of X(1,J) is:
3
R
426 SUBROUTINES
DIMENSION X(l)
SUM =
CALLT0T(A,RES1.3.3) DO 10 1 = 1, NR
DO 10 J = 1.NC
L= (J-1)*NR+I
CALLT0T(B,RES2.17,13) SUM = SUM + X L) (
10 CONTINUE
RETURN
For three-dimensional arrays, the formula used by the compiler to calculate the linear
address of an element. A(l.J.K), of an array. A, of NR rows, NC columns, and ND depth
is given by:
For example, given DIMENSION A(2,3,4), the linear position L of A(l,3,2) is:
L= (2-l)*2*3+ (3-1) *2 + 1 = 11
MON large and subroutines do not require access to variables. In such cases
is all all it is
possible to construct named blocks of COMMON. These named COMMON blocks allow
subroutines to access onlv those COMMON blocks that are needed.
Example
CALL SUBl
END
SUBROUTINE SUB2
CALL SUB2 C0MM0N/BLK2/Q,R
In this example, two blocks of COMMON are defined in the main program. Note that the
subroutines do not share any common area with one another; however, each shares a sepa-
rate common area with the main program.
SUBROUTINES 427
COMMON A B C 10 / BL0CK3/Q R S
, , ( ) , ,
BLOCK DATA
and the last statement is:
END
There are no executable statements and no RETURN statement. The only statements al-
lowed besides the COMMON
statements are IMPLICIT statements (must follow BLOCK
DATA), specification, DIMENSION, and DATA statements. If a variable or array is to
be initialized, the entire COMMON block in which it isstored must be specified. All
dimensions and specifications must agree with those in the main program. Thus, all of
blank COMMON is listed and array R (which corresponds to array X from the main pro-
A method that allows one to enter subroutines or functions at differenl points in the sub-
program is the ENTRY statement. The general form of this statement, which appears in
the subprogram, is:
where name is any valid variable name; in a function subprogram, this name returns a val-
ue to the main program;
P\, /?:,••• are dummy arguments used to communicate data to and from the calling
program (follow ing the rules discussed previously).
Notice that there is no SUBROUTINE or FUNCTION used before the word ENTRY.
Example
D0 8J = 1,M
8 RSUM(I) =RSUM(I) -i-A(I,J
6 CONTINUE
ENTRY CMAT(A,N,M,CSUM)
DO 17J = 1,M
CSUM(J) =0
DO 19 1 = 1. N
19 CSUM(J) =CSUM(J) -kA(I,J
17 CONTINUE
RETURN
END
SUBROUTINES 429
The first CALL in the main program is to the entire SUBROUTINE MAT. This
causes each element of the two-dimensional array X to be set to zero, and then control is
returned to the main program. (If there had been no RETURN statement after 10 CON-
TINUE, then the statements after ENTRY RMAT(X,N,M,RSUM,CSUM) and ENTRY
CMAT(X,N,M,CSUIVI) would have been executed also. ENTRY statements are nonex-
ecutable statements and would have been ignored.) The second CALL is to RMAT. This
causes execution to start after ENTRY RMAT. First the row sums are calculated and then
the column sums. Notice that all dimensioning and specifications of arguments are put im-
mediately after the SUBROUTINE statement, and not after the ENTRY statements.
Finally, the last CALL is to CMAT, and entry occurs at that point in the subroutine. The
columns' sums only are calculated and returned to the main program.
ENTRY statements may not appear within the range of a DO loop.
When a RETURN is executed in a subroutine, execution in the main program goes to the
statement immediately following the CALL statement. If you want to return to different
points in the main program, depending on outcomes in the subroutine, the following mul-
tiple return can be used.
The general form of the multiple return is:
RETURN 2
RETURN
END
RETURN 1 means execution returns to the main program to the statement cor-
responding to the first *;
) . .
430 SUBROUTINES
Example
The following main program and subroutine determine the roots of the equation Ax' +
Bx+ C = 0.
60 READ 5 3 END = 80 A B C
( . . ) , , SUBROUTINE ROOTS (A,*.B,C,*,*)
CALL ROOTS A &5 B C &8 &10 ( , , , , , ) IF A EQ
( RETURN 1
. . )
You could write two function subprograms, POLY for the first function and SQPOLY for
the second function as shown in Figure 10-1 The third function, sin x, does not need to 1 .
A subroutine MAX! (see Figure 10-1 1) can be written to calculate the maximum val-
ue for any function within a given range. In order for MAX! to know which function it is
supposed to process, the name of the function must be one of the arguments transmitted to
MAXI. To ensure against the function name arguments POLY, SQPOLY, and SIN being
MAXI as ordinary variable names, the various function names are listed in
interpreted by
the EXTERNAL statement of the program calling MAXI. The dummy argument for the
function name is FUNC in subroutine MAXI. The complete program is shown in Figure
10-11.
EXTERNAL POLY SQPOLY SIN , , In the main program POLY. SQPOLY, and
SIN are to he construed as function names.
CALLMAXI(2. ,10. .3. ,POLY) The interval for POLY is [2. 10], and the in-
crement value is 3.
CALL MAXI (-4. , 5. , 1. , SQPOLY; Go and find the maximum value taken on
by function SQPOLY in the interval [-4,
CALL MAXI ( .1, 1.1, .1, SIN) 5]. Increment is 1 . Find maximum sine value
STOP in interval .1 and 1.1.
END
FUNCTION SQPOLY(X)
SQPOLY = SQRT( (X-4: (X-^6:
RETURN
END
Figure 10-11 Use of the External Statement.
where namel name2, , are valid names . . . for built-in functions, function subprograms, or
subroutine subprograms, which are to be passed as arguments to a function or sub-
routine subprogram.
)
432 SUBROUTINES
cation. For example. EQUIVALENCE(A,B) causes the variables A and B lo have the
same address: i.e., an\ reference lo A is equivalent lo a reference to B and \ice versa. A
and B should be thought of as different names for the same memory location. Consider the
following example:
EQUIVALENCE(A,B)
A = I.
8 = 3.
Here each variable in the list-oj-variahlcs is declared lo be equivalent to the others. The
variables can be subscripted variable names. The EQUIVALENCE statement must ap-
pear after the DIMENSION and COMMON statements but before any executable state-
ments. Any equivalenced variables should be of the same mode.
Example
EQUIVALENCE X Y ( , ) ,
( ZZZ R STU
, ,
The variables X and Y share the same memorv location. ZZZ, R, and STU all refer to the
same storage location; they are synonv mous names for the same variable.
Arrays or parts of arrays can be equivalenced by specifying the starting locaLion at
which sequential matching between arrav elements is desired. For example, assume arrays
A and B are to be equivalenced:
DIMENSION A(5),B(5) ^, ^. ^, .^ .,
EQUIVALENCE (A(l) ,B(1) ) vields the pairing I » » » 1
Bi B: B Bj B^
8 1 8: B' 84
J ... .^
In this case 8,and As are assigned separate memory locations. The pairing of elements ter-
mmales assoon as an array has reached its DIMENSION si/e (5 in this case for array 8).
In the case of two-dimensional arrays, ihe matching sequence is perl\)rmed according lo
the linear memory sequence in which multidimensional arravs are repre^ented. For exam-
ple:
SUBROUTINES 433
lows the programmer to reuse arrays that might otherwise be used only once in a program.
To reuse the same array for a different purpose and to avoid name confusion, the same ar-
10-6 EXERCISES
10-6-1 Self Test
1. What would happen if you tried to execute a subroutine all by itself?
5. Why can't you write the code equivalent to a subroutine in the main program and
branch to it whenever you want to execute that code?
434 SUBROUTINES
DIMENSION A(IOO)
X =
DO 3 1 = 1,100
CALL SUB (X, 14 3 X = X + A(I)
RETURN
END
CALL SUBC (
RETURN
CALLSUBC(Y) END
DIMENSION X(N,M)
CALL SUBE (X
CALLSUBF(X,3,4)
CALL SUB B E 3 D( , , ,
Which of the following statements are invalid or false? Stale the reason.
a. SUBROUTINE(A,X,Z,3.126)
b. CALL A(X,Y,Z(JNE))
c. COMMON''A/LJ,K,L
""
d. EQUIVALENCE TABLE(IOO)
e. SUBROUTINE ANT(X,Y,2.)
f COMMON /W/X
(dimension A(IOJO)
^1 EQUI VALENCE/ A(5),B(5j/
h. SUBROUTINE BC(K,L(IO),M)
i. COMMON W/T/ \^
. (DIMENSION A(10),B(I0) i 4^
- [EQUIVALENCE (A(5),B(8)),(MSUM,fsUM)
k. The statement DIMENSION A(IO),B(5,5),C(P) is valid in some cases.
I. Only one RETURN is allowed in a subroutine.
m. Two-dimensional arrays are stored in memory in column sequence.
n. The COMMON
statement can be placed anywhere in the program before the first
executable statement.
o. It is possible for subroutines to have no arguments.
p. Arguments in a subroutine arguments list can be declared in a COMMON state-
ment.
q. EQUIVALENCE and COMMON statements really mean the same thing.
r. Arguments in a calling sequence and in a subroutine must always agree in number
and mode.
s. Subroutine names cannot have more than six characters.
t. The EQUIVALENCE statement can be put anywhere before the first executable
statement.
u. More than one COMMON statement is allowed per subroutine.
v. If a statement number is the same in a main program and in a subprogram, there
will be a syntax error.
w. In a subroutine the statement END is not necessary because of the RETURN state-
ment.
x. Subscripted variable names cannot be used in a subroutine declaration statement.
y. At least one RETURN statement should immediately precede the END statement
in a subroutine.
z. The French revolution took place in 1791.
436 SUBROUTINES
SUBROUTINE SEARCH(L)
INTEGER Nl 4 N2 4 BLOOD 4
( ) , ( ) , ( ) ,
1. A toy store sells 20 different toys. Write a main program to read the costs of toys into
a one-dimensional array. In addition,
a. Write a subroutine to print all items over $5.00.
b. The store decides to run a sale on all its merchandise: everything is reduced to 60
percent. Write a subroutine to output the new prices.
^
2. Write a subroutine that accepts a one-dimensional array and returns the largest and
the smallest element of that array.
3. Write a subroutine that accepts a one-dimensional array and returns the position of
the largest and the position of the smallest element.
6. Rewrite the program of Figure 10-6 without subroutines. Compare the length and the
complexity of the two programs, is there any advantage in using subroutines in this
instance?
7. Rewrite the program of Figure 10-1 without arguments for either subroutines.
8. Modify the program of Figure 10-6 to find the breakeven point for the future interest
rate. How it does not matter whether Ms.
low does the interest rate have to go before
X buys now or waits? Also generalize the program to enter a variable interest rate, a
house purchase cost, and a percentage of house purchase price for down payment.
SUBROUTINES 437
9. Write and test subroutines to perform tiie following tasics on two-dimensional arrays.
a. Set all elements of an array to a constant.
b. Add corresponding elements of two arrays, storing results in a third array.
10. Write a subroutine that accepts a one-dimensional array and reverses the elements of
the array.
11. Write a subroutine that accepts any integer and sets a flag to one if the integer is a
prime number and sets a flag to zero otherwise.
12. Each card of a deck of cards (no more than 50) contains a name (maximum of eight
characters).Read the names and corresponding grades in a 50 X 2 double-precision
array with names in column and grades in column 2. For example:
I
K(!J)- MARTIN
K(2J)-
438 SUBROUTINES
15. Write a subroutine to accept a number from 20 to 99 and return two variables (argu-
ments) that will print the number in letter form. Use two alphabetic arrays to store the
words one, two, three, • • •. nine, and the words twenty, thirty, • • -, ninety.
16. Write a subroutine to compute a standard deviation and apply it to solve Exercise 30,
Section 5-6-2.
17. Write a subroutine to multiply two arrays (matrices) as illustrated in Exercise 38, Sec-
tion 7-6-2.
18. Write a subroutine to accept the coordinates of up to 100 ships and determine which
two ships are the closest. If (J,, K|) are the coordinates of ship 1 and (A':, K:) arc the
coordinates of ship 2, then the distance d separating the two ships is given by:
dent there is name, eight homework scores, four quiz scores, and
a card with his or her
three test scores. Print out each student's name, homework average, quiz average, and
test average. To do this, write a general subprogram to find the average of an array of
20. Given three values. A, B, C, on d card, write a subprogram to determine if they make
up the sides of a triangle (the sum of any two is more than the third). If they do, let K
= 1and find the area of the triangle where area = \/ S*{S — A)*{S — B)*{S — C) and
S = .5{A + B C). If the three values do not make up the sides of a triangle, let A^ =
-\-
and let the area = 0. Then, if they do make up a triangle, write another subprogram to
determine it it is a right triangle let RIGHT = —
if it is; let RIGHT = if it is not.
1
The main program should print out appropriate messages and answers.
21. Write a subroutine to update inventory. From the main program, seven cards will
have the item number and amount in stock at the beginning of the day. These cards
are followed by cards that have the item number, amount shipped out or amount re-
ceived, and a code with value if the item was received and 2 if the amount was ship-
1
ped out. These cards are not in any order, and some items may not have been shipped
out or received, and some items may have had several orders shipped out or received.
A blank card indicates the end of these cards. When the inventory has been updated,
punch the new inventory on cards, including item number and quantity. (Use the
COMMON statement.)
22. On the first card of a deck of cards, we have punched the answers (I, 2, 3. 4) to a mul-
tiple choice test of ten questions. On the second card is the number of students (card
columns 1-4). On each of the next cards is a student name (eight characters) followed
by the student's ten answers to the ten questions. Write a main program to read the
data cards, using a subroutine to determine the percentage of correct answers for each
student and another subroutine to determine the grade (^100 = A, 80-89 = B, 60-79
= C, and below, a D). The output should be performed by a third subroutine to print
the student name, the letter grade, and percentage. The input and output can be view-
ed as follows:
SUBROUTINES 439
NAME
Student LAUGHLIN 4123142432
scores SATO 112 3 1113 2 4
Item tag
SUBROUTINES 441
28. Write a subroutine that will accept an integer number and return via an array all per-
mutations of the digits that make up the number. The subroutine should compute the
number of digits and return this value also.
Example
Input 321
Output NUMBER OF DIGITS 3
PERMUTATIONS 1 23
1 32
2 1 3
23 1
3 1 2
32 1
1
442 SUBROUTINES
A subroutine should be used to simulate for automatic ejection to the top of a new
page, to provide a page number, headings, and a demarcation Hne. The average class
grade should be printed all by itself on a new numbered page. Would you expect the
class average grade to be close to 50?
32. Write a program that will read in a bridge hand for each of four players (West, North,
East, and South, in that order). Each hand has 13 cards. Each hand is on its own data
card (therefore, there are four data cards). A data card will look like this:
02 14 41 12 42 01 49 48 22 21 13 40 24
Each two-digit number represents one playing card in that player's hand. The num-
bers 1-13 represent the spades 2-ace (example: 1 represents 2 of spades, 1 1 represents
the queen of spades, and 13 represents the ace). The numbers 14-26 represent the
hearts 2-ace; the numbers 27-39, the diamonds; and 40-52, the clubs (example: 25
represents the king of hearts). These 13 numbers should be stored in an INTEGER ar-
ray. Call a subroutine SORT to sort the numbers in ascending order (notice that by
representing the cards this way, SORT arranges the cards into their separate suits and
puts them in ascending order within the suits). Call an INTEGER function ITOTAL
to calculate the number of points in this hand. WRITE the name of the hand (West,
North, East, or South, in that order) in the main program and then call a subroutine
SHOW to write out the contents of the hand and the number of points in the hand as
per the instructions and coding form below. Repeat all of above for each hand.
Write a general subroutine SORT that will take any integer array and return a
sorted array in ascending order of the same elements. An example of a call to SORT
is:
IX = ITOTAL(array, length-of-array)
Print the cards so that an A is printed when an ace is present and a K when there
is a king, likewise a Q for queen and J for jack. Output for sample data card given is
shown below:
WEST
SPADES
2
3
K
A
HEARTS
2
9
10
Q
DIAMONDS
CLUBS
2
3
4
10
J
NUMBER OF POINTS \x
NORTH
33. a. Store into a three-dimensional array, K(9, 7. 6), the geometric sets representing
the ditiits 1-9 as follows:
A(2,l,l) A(2,1.6)
A(l,l.l) A(4,1.2)
1 i
2 2
L _z:
4 4
2 2 2 4 4
A(l,2,l)
2 2 2 2 4 4
2 2 4 4 4 4
2 2 4 4 4 4 4 4
2 2 4 4
2 2 2 2 2 2 4 4
Read a card containing three digits and write a subroutine to display the three
digits as a continuous geometric ensemble. For example, if the digits 2, 1, 4 are
read, the subroutine should produce the following output:
2 2
446 SUBROUTINES
37. Same exercise as 36, except that two symbols must be printed per line.
38. You work for the VPI Polling Company. They want you to write a program that will
evalute data from questionnaires of the following form:
1. There are three groups of questions on each questionnaire. The first group has
four questions, the second group has eight questions, and the third group has sev-
en questions.
2. Each question will be answered with a number between one and five, inclusively
with the following meanings: 1 = strongly disagree; 2 = disagree; 3 = don't care;
4 = agree; 5 = strongly agree.
You are asked to write a program that will be required to do the following for each
questionnaire, in this order:
a. Use a subprogram AVE to find the average response for each group of questions
(must be invoked three times).
b. Use a subprogram HIST to draw a histogram showing the average responses to
the three groups of questions.
c. Use a subprogram OP to write the respondent's (person's) average opinion for
each of the three groups of questions.
Input: When a person answers the questionnaire, his answers are punched on one card
in the following manner:
Columns 19-25 The seven responses to the questions in group 3, one column
each (each is an INTEGER between and 5, inclusively). I
Write a general REAL function AVE which has as its arguments an INTEGER
array (the answers to the questions of a particular group) and the length (INTEGER)
of the array (the number of questions). AVE should compute the average of the num-
bers in the array. Use this same subprogram three times for each questionnaire to find
the average response for each of the three groups of questions. An example of a call to
AVE is:
Store (in the main program) the three averages in an array. Note: Be careful of integer
division!
Write a subroutine, HIST, which has one REAL argument, the array of averages
of the three groups of questions. An example of a call to this subroutine is:
The subroutine HIST should make a histogram of the three averages using the coding
form and description that follow:
Start the histogram at the top of a new page.
Line
**********
3 GROUP 1
4
5
*************
6 GROUP2
7
8
**************
9 GROUP3
10
11
12
13 12 3 4 5
For each .25 points an asterisk is printed. For example, if the average response
for group 3 is 3.71, then 14 asterisks are used, since there are 14 full .25 points in 3.71.
Do not round off. Any fraction less than .25 is ignored. Note that a double line of
asterisks is drawn for each average. The preceding histogram shows what would be
printed if the averages were 2.5, 3.3333, and 3.71 for the three groups, respectively.
This is only an example. Be sure to have your histogram print the minus signs as
shown, the words, "GROUP 1," "GROUP 2," and "GROUP 3" in the left-hand col-
umns as shown, and the numbers one through five on the bottom as shown.
Write a subroutine OP with two arguments. The first is an INTEGER variable
which represents the respondent's ID number. The second argument is a REAL array
containing the averages of the three groups of questions. This subroutine should print
the following messages:
1 If the average is 1 , the person STRONGLY DISAGREES.
2. If the average is greater than 1 but less than or equal to 2, the person DISAGREES.
3. If the average is greater than 2 but less than or equal to 3, the person DOES NOT
CARE.
4. If the average is greater than 3 but less than or equal to 4, the person AGREES.
5. If the average is greater than 4 but less than or equal to 5, the person STRONGLY
AGREES.
448 SUBROUTINES
Column 2
\
PERSONxxxS VIEW ABOUT GROUP QUESTIONS 1 IS
PERSON xxxS VIEW ABOUT GROUP 2 QUESTIONS IS
PERSON xxxS VIEW ABOUT GROUP 3 QUESTIONS IS
1. The dummy variables are not initialized properly and might destroy memory: also the
return address is unknown.
3. a. Program segmentation.
b. Utilization of coding segments from program libraries.
4. a. COMMON.
b. Argument lists.
5. Return to a variable point (location) using the simple GO TO statement is not possible.
k. T.
1. As many RETURN statements as desired can be used, although it is preferable to
have one RETURN and many GO TO statements addressing the RETURN state-
ment.
m.T.
n. T.
o. T.
p. True, but both methods may not be used in the same subprogram.
q. F.
r. T.
s. T.
t. T.
u. T.
V. Statement labels are independent among main programs and subprograms.
w. The END statement is required at the end of every main program or subprogram.
X. T.
y. F.
z. F(1789).
11-1 INTRODUCTION
11-1-1 File Concepts
Many applications of computers, particularly in business environments, require the
storage and processing of large amounts of data. Typically there is too much data to store
in memory one time,
at so the data is stored externally. The
earliest computers used
punched cards and magnetic tapes for storage of data. Later computers used magnetic
disks and drums as external storage devices.
Data is organized into records containing related data items. Groups of related re-
cords compose 'dfile. For example, a personnel file might contain one record for each em-
ployee in a company. Each record would be composed of such data items as the employee
name, social security number, age, date hired, and so on. For convenience in processing,
the data items in each record are stored in the same order.
Records within a file are organized for easy access to process the data they contain.
One data item is designated as the record key and is used as the basis for the file organiza-
tion. In the example just given the employee social security number might be the record
key (see Figure 11-1). The file might then be organized sequentially, randomly, or in any
one of a number of other schemes. Using sequential organization, records are placed in the
file in order by record keys; each record has a record key value larger than that of its pred-
ecessor. A file that is organized sequentially is usually processed sequentially; a program
processes each record in turn, starting with the first record in the file. Using random or-
450
FILE PROCESSING 451
Number
r
Position
•
roHp dependents Record key
c- <-<Jue
^ ^
Social
1
/
1 ..x-ri
DOE JOHN 001222333 4 05 25 4 TURNER SUE 111222333 3 75 ADAMS LORNE 999333222 3 06 00 2
ganization, records are placed in the external storage device at a location which is calcu-
lated from the value of the record key. This organization allows a program to have ran-
dom access to any specified record within a file without processing other records in the
file. This type of file organization is not commonly supported in FORTRAN systems.
Direct-access file organization offers a compromise between the limitations of sequential
and the advantages of random organization. Direct-access files are discussed in Section
11-5.
Regardless of the type of file organizations and the device used for storage, certain
tasks are commonly performed in a file-processing environment. Initially, the file must be
created and stored on the external storage device. Programs may be required to merge the
contents of two files, insert records into an existing file, delete records from a file, change
data items on individual records in a file, and generate reports based on the data contained
in the file.
storage. The physical device used for storage will vary from one system to another. The de-
vice-number used on the WRITE statement will be associated by the operating system
with an appropriate file-storage device. New features introduced in the program of Figure
1 1-2 include the END FILE statement and the unformatted WRITE.
Later, as parts are used from or added to the inventory, it will be necessary to update
the data recorded in this A second program shown in Figure 1-3 could be used for
file. 1
this purpose. New features introduced in this program include the unformatted READ
statement and the REWIND statement.
Finally, a program will be required to list the contents of the file for determining how
many parts are available, how many should be ordered, and so forth. Such a program is
shown in Figure 11-4. A system flowchart showing the relationships among these pro-
grams is shown in Figure 1-5. 1
)
INTEGER PARTN.QTY
C THIS PROGRAM IS USED TCKCREATEA PARTS INVENTORY FILE
WRITE(6,3) ,
100 READ(5, 1 ,END = 44)PARTN,QTY " Read a record IVom the card reader. ,
' ' ,
,
'
QUANTITY '
END
PART # QUANTITY
mill 20
222222 3
333333 25
444444 123
'
I Ml-'
INTEGER P(IOO) ,Q(100) .PART.QUANTY Store into appropriate arrays all part num-
C LOAD CONTENTS OF FILE 7 INTO ARRAYS P AND Q bers and associated quantities.
DO ION = 1,100
READ(I_END = 11)P(N) ,Q(N).'' /, -
10 CONTINUE
11 N = N -^ N represents the number of records.
..
WRITE(7)P(I) ,Q(I)
30 CONTINUE ,„;. '"^7/ u/u ir^i
^, END FILE 7 ,^^ (xA 'M^'-
^.rt.. 'J .^
J i-I k(l
kit
"
5^^^
REWIND 7 -''|S^' ^^.. pCVf^ f
STOP U-^'^*' ^^
F0RMAT(I6,I3)
1
FORMAT OINVALID PART NUMBER
2 ( ' ' , 17
END
INVALID PART NUMBER 234567
INTEGER PARTN,QTY
WRITE(6,1)
10 READ(7,END=99)PARTN,QTY
WRITE(6.2)PARTN,QTY
GOTO 10
/nJ^
J ^ ef JmJ-^
99 REWIND?
STOP
(
1 FORMAT 'IPART #', 2X 'QUANTITY
,
'
2 F0RMAT(1X,I6,3X,I3)
END
?kKYiJ^
B
form of the numbers onto the storage medium. Data which has been
will write the internal
written out in the internal form on a storage medium does not need to be retranslated
when it is read, and hence the unformatted READ statement is used. Using unformatted
data whenever possible may save space on the external storage device being used and
speed up the processing of data by the program.
File 1^
/IT^
READ (5,3) A
3 FORMAT (F5. 2; C data card
memory
A 02143200
X = 2.*A
WRITE(7)A,X File 7
021
REWIND? 2^00
02286'400^
READ 7 ( )
REWIND?
READ(?,10
10 FORMAT (F5
WRITE(8,9
FORMAT (2X
REWINDS memory
READ(8,4)D,C
FORMAT (T4,A4,T9,F4.1
REWINDS
READ(S)Z
FILE PROCESSING 455
Example
. READ(7)A,B.K
Three values will be read from a record on device 7. No translation will take place; the
data will be assumed to be in internal form.
WRITE(10)X,Y,LL.KK
Four values in internal form will be written on device 10.
The END FILE statement is used to write this record when a disk or tape file is being
created by a FORTRAN program. The general form of this statement is:
where device-number is the number associated with the disk or tape file.
Example
1 READ(5,10,END= 100)A,B,C
SUM = A + B + C
WRITE(7)A,B,C,SUM
GOTOl
100 END FILE 7
10 FORMAT (3F5.0)
Statement 100 will cause the system end-of-file record to be written on device number 7.
sult, however, is the same; the first record of the file is the next one available for process-
ing. The general form of the REWIND statement is:
REWIND device-number
Example
100 END FILE 7
REWIND 7
2 READ 7, END =1000) A, B,C, SUM
(
WRITE(6,110)A,B,C,SUM
GO TO 2
1000 STOP
After processing of the file on device 7 is terminated, the file is rewound and processed
again (statement 2).
Answer: Yes. The BACKSPACE statement causes the system to back up one record at
a time from the current position of the file. For example, to backspace four records in a
file the following code could be used:
DO 10 1 = 1,4
10 BACKSPACE 7
2. Can a file be used as both an input file and an output file in the same program?
Answer: Yes. For example, combine the program segments in Sections 11-2-3 and
11-2-4. This program would create a file, rewind it, and read it back.
GOTO 10
88
4. How can I read data from more than one file using one READ statement?
Answer: Instead of using an integer constant to represent the logical input unit, use an
integer variable name, as in: .'^/^^^<^ ^^J
6. Can I write formatted and unformatted records on the same file? For example:
WRITE(7)A
WRITE(7,4)B
4 FORMAT 2X SUM IS F4
,
'
( ' , .
2
program used to list the file is shown in Figure 1-8. In both examples the END = option 1
is used to control the program when end of file is reached; no special last record is needed.
WRITE(7)ID,NAME,H
GOTO 1
60 END FILE 7
REWIND 7
STOP
100 F0RMAT(I9,5A4,F5.2)
END
\ Figure 11-7 File Creation Program.
12 F0RMAT(1X,I9,5X,5A4,2X,F7.2)
(
13 FORMAT (IX, 60 '*' )
END
11-4-2 Merging
As new employees are hired, it will be necessary to add items to the file MASTER. If no
ordering assumed in the file MASTER, adding records at the end of the file presents no
is
sequence by identification number. We will write a program that will accept new items to
be added to the file and then merge the new items with the old items in such a way as to
preserve the order of the records in the new file.
Throughout this discussion, it is assumed that there are too many items in the file
MASTER to be stored into arrays. If such storage were available, techniques like those
used in the would be appropriate. In this program we will assume
program of Section 11-1
that there is sufficient space available in memory for the new items to be added to the file.
The program shown in Figure 1-9 will accept new items to be added, store these in arrays,
1
and print a listing of each new item. When all new items have been entered, the program
will merge the new items with the old and create a file NEW MASTER (device-number 8)
MASTER as a backup in case errors are discovered and use the file NEW MASTER in
subsequent processing. If disk storage is used there may not be room to store both the file
MASTER and NEW MASTER permanently. In this case a typical procedure would be to
copy the contents of the file MASTER onto tape for backup storage and copy the file
NEW MASTER onto MASTER. The file MASTER is used in subsequent processing: the
area used by the file NEW MASTER is released for other usage. The program in Figure
11-9 assumes that disk storage is used and that a backup copy of the file MASTER has
been produced prior to execution of this program; hence the program copies the contents
of NEW MASTER into MASTER.
/tf~ In the program of Figure 1 1-9 it is assumed that the new items are in ascending se-
quence. If this is not the case, a sort algorithm could be used prior to merging the new
items. In all file important to institute error checks with appropriate
processing it is
messages to ensure that erroneous data do not enter the system. Note, for example, the
checking in the program of Figure 1-9 that ensures that employees with duplicate identi-
1
fication numbers are not allowed to enter the file. If a duplicate identification number ap-
pears, a message is written on the report. The new contents of the file MASTER are shown
in Figure 1 1-10.
The program used to create and list the file HOURS is shown in Figure 11-11. Note the
use of the REWIN D statement to enable processing the file after its creation.
^ \p
4C^'^'
^ FILE PROCESSING 459
23 IF( ID.EQ.NID( I GO TO 33 )
Check for duplicate identification numbers.
)
WRITE 8 ID NAME H
( ) ,
(h^n output master file record onto new file
,
GO TO 21
30 WRITE(8)NID(I) (NEWNAM(I,J) ,J=1,5) ,WAGNEW(I)
.
22 1 = 1 + 1
IF(I.GT.N)G0T0 40 If all new records have been used, go to
1 = 1 + 1
GO TO 50
40 WRITE(8)ID,NAME,H
READ 7 END = 60 ID NAME
( , ) , ,
GO TO 40 __^
60 END FILE 8
REWIND 8
REWIND 7
61 READ 8 END = 70 ID NAME
( , ) , ,
WRITE(7)ID.NAME,H
GO TO 61
70
5A4.F5.2)
'DUPLICATE ID' ,110
I9,2X,5A4,F7.2)
460 FILE PROCESSING
*«»«*»*»#»»«*««*****»*«***»*»*»«»*****»*«#»**
ID NUMBER
FILE PROCESSING 461
C THIS PROGRAM READS THE FILE HOURS AND MASTER AND PRODUCES GROSS PAY REPORT
DIMENSION NAME( 5)
WRITE(6,100)
1 READ 7 END = 700 MASTID NAME WAGE
( , Read a record on MASTER file.
) , ,
2 READ (8, END =600) ID, HOURS Read a record on HOURS file.
3 IF(MASTID.EQ.ID) G0T0 200 If ID'S are equal, go to 200.
GO TO 700
600 WRITE (6, 103)
REWIND 7
REWIND 8
STOP
(
100 FORMAT '1 701 *')/2X, ID NUMBER 3X NAME ' , ,
'
M7X ,
'
HOURLY WAGE '
,
#5X, 'HOURS
5X PAY' )
associated with each record. The number corresponds to the position of the record in the
file — a program can access the fifth record, the tenth record, etc., without processing any
other records in the file. Hence, records are accessed directly; any record in the file may be
read or written at will.
) .
Associated with each direct-access file is an integer variable called the cursor. The
cursor points to the record in the file that is available for processing without repositioning
of the file. Each read or write operation on a direct-access file causes the cursor to point to
the record immediately following the one just processed. Direct-access files can be created
in formatted form, unformatted form, or a mixture of the two. The number of records and
the size of each record must be specified in the program.
w here device-number is the number associated with the file and used as a device-number in
the file.
The specifications for length and size must be unsigned integer constants. When the mode
is E (formatted) or L (mixed), size specifies the number of characters in a record; when the
Examples
The file on device-number 8 will contain 1,000 records. Records will be written and read
without format control. Each record will be four words long. (A record of a length of four
words would ordinarily accommodate four variables unless double-precision variables are
used.) The variable KPOINT is associated with the file.
The files on device-numbers 9 and 10 are declared to be direct-access files. File 9 records
will be in formatted form; file 10 records may be in either formatted or unformatted form.
File 9 records are 60 characters in length; file 10 records are 70 characters in length.
ments. The general form of the direct-access READ and WRITE statements is:
FILE PROCESSING 463
RE AD{device-number'record-number[/ormat-statenient-nunihc'r])l is t-of-variables
V\lR\TE{device-number'record-number[Jormat-statemenl-number])list-of-variables
where device-number is the number of the device associated with the file,
Examples
READ(8'14)A,B,C
This statement will read the variables A,B,C from the fourteenth record of a direct access
file on device-number 8.
K=132
READ(9'K,16)P,Q,R
Record 1 32 will be read from a direct access file on device-number 9.
L = 14
K=2
READ(10'L*K-h2)X,Y
The value of the expression L*K -I- 2 = 14*2 + 2 = 30 specifies which record of the file is
to be read.
WRITE(8'95)A,B,C
The values of A,B, and C will be written in unformatted form onto record 95 of the file on
device-number 8.
K = 97
WRITE(9'K,160)P,Q,R
The values of P,Q,R as interpreted by format statement 160 will be the 97th record on the
file on device-number 9.
gram could be used to create the file or add records to the file. Compare this program to
the merging program for sequential files in Figure 11-9. Note in the program of Figure
1 1-13 that the cursor associated with file 8 is K8, but the program uses the variable ID to
determine the record to be written. Although the system automatically sets the value of K8
after each READ or WRITE, the program may use any integer variable to specify the re-
cord to be accessed in the file.
464 FILE PROCESSING
At first glance it would seem to be superfluous to write the value of the I D into the re-
cord, since the position of the record corresponds to the value of ID. However, suppose we
now wish to list the contents of the file. The file contains ,000 records, although some (or
1
many) may not be used. (The contents of unused records is dependent on the operating
system.) One way to test for unused records is to compare the position of the record with
the contents of ID when the record is read. If they are equal, the record is in use; if they are
not equal, the record is not used. This approach is used in the program of Figure 1-14. 1
The cursor could be used to read the entire file, since it always points to the next se-
quentiallynumbered record in the file. The program in Figure 1-14 could be rewritten as
1
shown in Figure 11-15. Note that after the READ operation the value of the cursor is one
larger than the position of the record just read, since it is incremented automatically as a
pari of the READ statement execution.
FILE PROCESSING 465
GOTO 1
10 WRITE (6, 102) NUM
GOTO 1
20 STOP
100 FORMAT 13, F6. 2)
(
FLIGHT
CRT display SCHEDULE
DISPLAY
Teletype DEPOSIT
terminal TRANSACTIONS
Magnetic tape
Paper tape
Magnetic disk
Printer
SALES
REPORT
Processing INVENTORY
program UPDATE
Inside the block, the type of data contained in the file is identified. A processing step is
symbolized by use of a rectangle. Within the rectangle the name of a processing program is
printed.
The flow of data from files to processing programs and from programs to files is sym-
bolized by flowlines such as:
71
Processing program.
output file.
Processing program.
Telecommunications link
If the head of the flowHne points away from the file and toward a processing block, the file
is an input file for the program. If the head of the flowline points away from the processing
block and toward a file, the file is being produced as output from the program. A file may
be used for both input and output by a program; in this case a double-headed fiowline
•
such as 'is used.
If no telecommunications link is used between the CPU and the input/output device
used for the file, a straight fiowline is used. If telecommunications is used, a fiowline such
^s
~Z. .
may be used to signify that telephone lines (or other link) are being used to transmit data.
For example, the system fiowchart in Figure 11-19 illustrates a data-processing system in
which two programs are used to produce paychecks. The DAILY PAYROLL UPDATE
PROGRAM is used daily to record the time worked by each employee from the DAILY
TIMECARDS input file. This data is recorded on records in the PAYROLL MASTER
FILE. Periodically this file is used as input for the PAYCHECK PROGRAM which ac-
tually produces CHECKS.
FILE PROCESSING 469
FORTRAN
PROGRAMMING
SYSTEM
FORTRAN
PROGRAMMING STORAGE
FILE
SYSTEM
USER 3
11-6 EXERCISES
11-6-1 Self Test
4. Differentiate among the following: data item, data record, data file.
5. What are the disadvantages of sequential access to data? Are there advantages?
2. In the example of Figure 1 1-9, suppose the new items are not in sorted sequence. Add
logic to perform the sort.
3. Write a program to delete items from the file MASTER discussed in Section 1 1-4.
4. Write a program to process changes in name and hourly wage for the file MASTER
discussed in Section 1 1-4.
5. Rewrite the program of Section 7-4-3 using a file to store the students' names and
grades.
6. Write programs for the Widget Manufacturing Company's sales information system.
A sales file is to be created with records in the following format:
salesman-number, amount-of-sales.
alphabetical order. Each time a test is given, the file is updated to refiect the total
score (sum of grades) obtained by each student so far. At the end of the semester Dr.
X computes the average of the three scores and assigns letter grades as follows:
90 and above
FILE PROCESSING 471
Checks must be processed against the master file. Write a program which accepts in-
formation about checks to be processed as input and updates the master file. Note
that checks will be presented in any order so that some sorting will be required before
updating the file.Also note that more than one check may be processed against an ac-
count. What type of error conditions may be encountered? If your system supports
random-access binary files, this problem should be greatly simplified.
10. Rewrite the airline reservation problem of Exercise 6, Section 8-6-2b to allow main-
tenance of passenger reservation information in files.
11. The Grand Order of Beavers bills its members for dues on a monthly basis. The
Vice-Exalted Flat Tail has been performing this task by hand, but since a computer
system has become available he feels that the billing could be made more efficient us-
ing a computerized system. Design and implement a system to maintain membership
rolls and. produce and associated reports. Payments should be processed in small
bills
batches as they are received. Include a feature for dropping a member if his dues are in
arrears by three months or more.
12. Consider the program examples of Section 1-5-4. Suppose the identification number
1
is nine digits rather than three digits in length. Will the same approach still be prac-
13. Modify the program of Exercise 6 to use direct-access files. Make an appropriate as-
14. Modify the programs for Exercise 7 to use direct-access files. Add an appropriate stu-
dentnumber field.
15. Modify the program for Exercise 9 to use direct-access files. Make an appropriate as-
sumption about the account number field.
1. a. The END = option allows automatic branching when the end-of-file record read. is
2. Unformatted processing of data works with data in its internal form; formatted proc-
essing of data causes translation of data between internal and external forms.
4. A data file is a collection of data records. A data record is composed of data items.
5. Sequential access to data requires that each record in a file be processed (read) to ob-
tain any record from the file. It is the only file-access method available on certain de-
vices (e.g., tape). There is less overhead involved in accessing a sequential file than in
using other methods.
12
STRUCTURED
PROGRAMMING
12-1 INTRODUCTION
Structured programming has become a very important concept in the art of program de-
sign. Structured programming originated in the observation that the unrestricted use of
the GO TO statement resuUs in programs that are difficult to follow, difficult to debug,
and even more difficult to modify. It has been shown that programs that are developed us-
ing structured programming concepts prohibiting or restricting the use of the GO TO are
less likely to contain logical errors, are developed more rapidly, and are easier to maintain
The language used to develop programs written in this manner is sometimes called
pseudo code. A program written in pseudo code is a description of the procedures (tasks)
that must be carried out. Tasks are executed sequentially unless the program makes use of
certain structured constructs as IF THEN ELSE, WHILE DO, DO CASE, and EX-
472
STRUCTURED PROGRAMMING 473
ECUTE REMOTE BLOCK. (Note that GO TO is not included in this list.) Many of these
constructs are available in FORTRAN them are now part of the WATFIV-S
77. All of
language. The reader is encouraged to check with his or her computer installation to de-
termine the availability of WATFIV-S. A program written in structured pseudo code may
be read from beginning to end like a book or essay. There are no jumps or GO TOs to in-
terrupt the logical flow of the statement of the algorithm.
secondarily important. One example of this pseudo code, labeled traditional version in
Figure 12-1 is essentially an exact copy of the flowchart (line-to-line similarity) in which
the flowchart decision block is expressed as an English sentence through the construct:
where either the THEN or ELSE branch is taken but not both at the same time.
Carefully go through version to see how the pseudo code is made to correspond to
the sequence of activities in the flowchart. Now don't look at the flowchart anymore
— cover it and look at version as if for the first time. Can you easily reconstruct the
up,
entire process or meaning of the program? Do you find that the code as written is very
readable, clear, and understandable, or would you agree to the following observations:
1. To understand the essence of the program you must read all the lines in the code, from
WAKE-UP-ROUTINE to D.
[goto B|
ELSE
Lament sigh in relief
LAMENT
IF IT IS 10th PUSH UP
TH EN GET D RY
[GO to"b1
ELSE
LIE DOWN
PUSH UP
GRUNT
IGOTOTI
BOIL WATER
FILLCUP
ADD COFFEE
IFSUGAR = INSUFFICIENT
\ THEN ADDSUGAR
STIR
TAKE SIP
|GOTOC|
ELSE
DRINK CUP
CLEAN DISHES
STOP
WAKE-UP-ROUTINE. WAKE-UP-ROUTINE.
WAKE-UP-ROUTINE
EXECUTE WAKE-UP-ACTIVITIES
EXECUTE COFFEE-CUP-ROUTINE
STOP
In this case 2 procedures would need to be written,
each one making use of course of existant pro-
cedures.
er gets an overview of the process involved. The statement in the WAKE-UP ROUTINE
paragraph
FILL CUP
ADD COFFEE
EXECUTE TASTE WHILE SUGAR = INSUFFICIENT
The ADD COFFEE statement is executed after the FILL CUP statement.
THE EXECUTE statement executed after the ADD COFFEE statement.
is
tion; otherwise (condition is not met), the ELSE action (a different sequence of steps) is
taken.
Both the THEN and ELSE actions cannot be taken at the same time.
Example SELECTION Structure
Then zone
> delimited by
ELSE
ELSE
EXECUTE EXERCISES
BOIL WATER
See Section 12-2-2 for the implementation of the IF/ELSE in FORTRAN 77 and
WAT-FIV-S.
3. The Iteration (EXECUTE) structure:
Two basic types of EXECUTE are available,
a. A procedure (paragraph) is performed a fixed number of times (once, twice, twen-
ty times, etc.) and return from the paragraph is automatically made to the state-
ment following the EXECUTE statement.
478 STRUCTURED PROGRAMMING
In WATFIV this construct is carried out through the EXECUTE statement (see Sec-
tion 12-2-6). Such a construct is not yet implemented FORTRAN 77.
in
TASTE I
STRUCTURED PROGRAMMING 479
implementation of the task requires one statement or one hundred statements. We shall
follow the convention of expressing tasks in lowercase characters while reserving up-
percase characters for structured constructs. The following are examples of tasks:
compute pay
process transaction record
update master file record
initialize counters
increment appropriate counter
interchange x and y
x =
y = x^ + 3
Note that these tasks may be either simple or complex when the fmal coding is written.
A process is defined as a logically related set of tasks. A program is a process, but any
logically related set of tasks within a program may also be referred to as a process.
Top-down program design may be viewed as the repeated redefinition of processes, with
each redefinition yielding tasks that are more detailed than those given at the preceding
level.
Example
The top-down method of program development is illustrated in the above example. The
initial specification of the process "write paycheck for employee" is rewritten as a set of
more detailed tasks. Any process that is not a sequentially executable set of tasks must
make use of one or more of the following constructs: IF THEN ELSE, DO WHILE, DO
UNTIL, and SELECT.
If the condition is true, process 1 is performed; if the condition is false, process 2 is per-
formed. After either of the two processes is performed, the task following the IF THEN
ELSE statement is performed (see Figure 12-1).
480 STRUCTURED PROGRAMMING
STRUCTURED PROGRAMMING 481
ENDIF
WRITE 6,5) REGPAY
I
I
5
/write check/
There are a few differences between the IF THEN ELSE statement and the logical IF
that warrant mentioning. The true branch of a logical IF statement can be any executable
statement except another IF statement or a DO statement. However, with the IF THEN
ELSE statement, process or process 2 may contain other IF or DO statements. For ex-
1
ample, to print out whether a number is negative, zero, or positive, the following code is
acceptable:
IF(N.LT.O)THENDO
PRINT, 'NEG'
ELSE DO
IF{N.EQ.O)THENDO
PRINT, 'ZERO
ELSE DO
PRINT, 'POS'
ENDIF
ENDIF
16 STOP
482 STRUCTURED PROGRAMMING
Another difference between the logical or arithmetic IF and the IF THEN ELSE is
that the statement following the END IF is executed after either the true or false branch is
processed. Thus, in the example just given the true branch prints NEGand then control
transfers to statement 16, which is STOP. Also, after executing PRINT, 'ZERO', state-
ment 16 is processed next; and finally, after printing POS, the next statement executed is
statement 16, STOP. STOP statements are not needed after each of the PRINT statements
as with the logical or arithmetic IFs.
12-2-3 DO CASE
Another structured construct that is very similar to the computed GO TO but avoids the
use ofGO TO statements is the DO CASE statement. The DO CASE construct, like the
computed GO TO, used is to select an appropriate action based on the value of an index
(integer variable). The general form of the construct is:
^
DO CASE case 1
process 1
CASE case 2
process 2
CASE case n
process n
The process corresponding to whichever condition is true will be executed and then con-
trol is transferred to the statement following the last CASE.
A flowchart form of the DO CASE construct is shown in Figure 12-3.
PROCESS 1
STRUCTURED PROGRAMMING 483
DO CASE index
process 1
CASE
process 2
CASE
process 3
CASE
process n
IF NONE DO
process
END CASE
Where index is an integer variable, if index = 1, process I is executed and then control is
transferred to the statement following the END CASE. If index = 2, only process 2 is ex-
ecuted and then execucion is transferred to the statement following the END CASE, and
so forth. If index is negative, zero, or greater than n, the statements following IF NONE
DO are executed and then control transfers to the statement following END CASE. IF
NONE DO optional. If
is it is omitted, and if the index is negative, zero, or greater than n,
control is transferred to the statement following the END CASE. Finally, the word CASE
can follow the statement DO CASE index, in which case process I would follow. For ex-
ample:
DO CASE index
CASE
process I
CASE
process 2
END CASE
Example 1
Suppose we wish to print out whether a person is single (index = I), married (index = 2),
widowed (index = 3), or divorced (index = 4). Using the DO CASE construct, the process
could be written in pseudo code as:
Pseudo code
DO CASE single
print, 'single'
CASE married
print, 'married'
484 STRUCTURED PROGRAMMING
CASE widow
print, "widow"
CASE divorced
print, "divorced"
CASE other
write error message
One of the CASEs will be true, and the appropriate action will be taken. The above pseudo
code can be implemented as follows:
Notice, after any of the cases is excuted, control is transferred to the STOP statement (the
statement after END CASE). SeparateGO TOs or STOPs are not needed after each of the
PRINT statements as is necessary when using the computed GO TO.
Example 2
Pseudo code
DO CASE deposit
balance = balance + amount
CASE withdrawal
balance = balance - amount
IF overdrawn THEN write appropriate message
ELSE exit
DOCASEKODE
C IN CASE KODE IDENTIFIES DEPOSIT
CASE
BAL = BAL + AMT
C IN CASE KODE IDENTIFIES A WITHDRAWAL
CASE
BAL = BAL - AMT
IF BAL LT ( PRINT BAL AMT
. . ) , ,
END CASE
12-2-4 WHILE DO
Another construct (available in WATFIV-S but not in FORTRAN) which provides loop
control, is the WHILE DO construct. This feature enables a program to perform one or
more statements (process) while a condition is true. The condition is tested before execu-
tion of the process. The general form of the statement is:
WHILE condition DO
process
The flowchart and WATFIV implementation of the statement is shown in Figure 12-4.
486 STRUCTURED PROGRAMMING
Code Flowchart
False
WHILE {logical-expression DO )
process
END WHILE
The logical expression is tested. If the condition is true, then the statements (process) fol-
lowing the WHILE DO are executed. The logical expression is tested again, and if the con-
dition remains true, the statements following the WHILE DO are executed again. This
procedure is continued until the logical expression is false, at which time control transfers
to the statement following the END WHILE. Note that the logical expression is tested
before the loop is processed; also, no GO TO is needed to transfer back to the WHILE
statement.
The process performed in a WHILE DO construct must modify the condition that is used
to terminate execution of the process (increment count, read a special record, etc.), other-
wise an endless loop will be created.
Example 1 To process a payroll procedure for 80 employees the following code could be
used:
COUNT =
WHILE(C0UNT.LE.80)D0
READ (5,6) NAME HRS RATE , ,
IF(HRS.LE.40) THEN DO
REGPAY = HRS*RATE
ELSE DO
REG PAY = 40*HRS + HRS-40 RATE* 1 ( ) . 5
END IF
WRITE (6.7) NAME HRS RATE REG PAY , , ,
Example 2 Given a one-, two-, five-, ten-, or twenty-dollar bill, exchange it for an equal
amount of quarters.
STRUCTURED PROGRAMMING 487
code
READ BILL
terchangeably, especially when used for loop control. For example, if you want to find the
average often numbers read from cards, either of the following two programs can be used:
SUM = SUM=0
DO 10 1 = 1.10 1 = 1
READ , WHILE (I.LE.IO) DO
SUM = SUM - X READ ,
These two programs, however, illustrate several major dilTerences beiv\een DO loops
and WHILE DOs. With the DO loop, the counter (index) is initialized by the DO state- I
needed; in fact, putting such a statement in the loop would cause an execution error. How-
ever, when the WHILE DO construct is used, the value ofthe variable (index) being tested
must be initialized (I = \) prior {o the WHILE DO statement; and within the WHILE DO
loop, this counter must be explicitly changed (I = in order to avoid an infinite loop
I -I- 1 )
(I would never be greater than 10). It should also be noted that with the DO loop, the val-
ue of I is tested against 10 after each execution of the loop; whereas with the WHILE DO
construct, the value of 1 is tested before each execution of the loop.
Another difference between the DO loop and the WHILE DO loop is that although
either the DO loop or the WHILE DO loop can be used when a variable is needed as a
counter or to generate positive integer values, only the WHILE DO can be easily used
when the initial value, increment value, or test value involves negative or real fractional
VckJues. The increment, and test values in a DO statement must be nonncgative in-
initial,
tegers. no such restriction when using the WHILE DO loop. For example, if you
There is
want to find and print the values for X and Y where Y = 2X- 3X 5 when X has the -I- -I-
values of -3., -2.5, -2., - 1.5 4.5, the following WHILE DO loop can be used:
X = -3.
WHILE (X.LE.4.5) DO
Y = 2*Y**2-3*X-5
PRINT, X,Y
X = X+ .5
END WHILE
There are two between the DO and WHILE DO loops worth men-
final differences
tioning. First, in theDO loop the current value ofthe index automatically compared to is
the test value; thus DO 15 = 3, 89, 4 would result in the current value of being com-
I I
pared to 89 after execution of statement 15. However, in the WHILE DO loop the condi-
tion being tested may involve expressions containing one or more variables; thus, the state-
ment WHILE (X + 2*Y .LT. 4.56) DO is acceptable. Secondly, when a DO loop is used,
the value of the index changed by adding the increment value to the current value of the
is
each execution of statement 17. However, in the WHILE DO loop the value of the vari-
able being tested in the WHILE DO statement may be changed by any means; thus
X=16.
WHILE (X.GT. .1) DO
X = X*.5
END WHILE
would result in this loop being processed for X equal to 16., 8., 4., 2.. 1 ., .5, .25. and .125.
STRUCTURED PROGRAMMING 489
Also
READ X ,
WHILE (X.GE.O) DO
READ ,
END WHILE
would result in this loop being processed as long as the value read for X is not negative.
L-END BLOCK
END
3. Your program cannot transfer into a REMOTE BLOCK by any means other than the
EXECUTE statement. Thus, the statement before the REMOTE BLOCK statement
should be one causing transfer of control.
4. Not statement within the REMOTE BLOCK can transfer to other statements outside
the BLOCK.
5. Variables used in the program that executes the REMOTE BLOCK and the variables
in the REMOTE BLOCK are shared and are not passed by COMMON blocks or argu-
ment lists.
) )
Example
Suppose we wish to determine the number of men or women in a survey, their average
heights, and the shortest man and woman. Using the EXECUTE REMOTE BLOCK con-
struct, the process could be written as shown in Figure 12-5.
READ MMIN
INTEGER SEX
99 READ 5 1 END = 30 SEX HEIGHT
( , , ) ,
C
C IF SEX = 1 ( MALE EXECUTE REMOTE BLOCK MALE
)
C
IF ( SEX EQ . .
1 ) EXECUTE MALE
C
C IF SEX = 2 ( FEMALE EXECUTE REMOTE BLOCK FEMALE
)
C
IF SEX EQ 2
( . . ) EXECUTE FEMALE
GO TO 99
C
C WHEN THERE IS NO MORE DATA PRINT THE MALE AND FEMALE AVERAGES AND THE ,
2 F0RMAT(1X,4(F6.2,2X)
C
C REMOTE BLOCK MALE ADDS 1 TO THE MALE COUNTER (M) ADDS THE HEIGHT TO :
C THE MALE SUM SUMM FINDS THE MALE AVERAGE AVM AND DETERMINES
( ) :
( )
C
REMOTE BLOCK MALE
M=M+ 1
SUMM = SUMM + HEIGHT
AVM = SUMM/M
IF HEIGHT LT MMIN
( . . ) MMIN = HEIGHT
END BLOCK
C
C REMOTE BLOCK FEMALE ADDS 1 TO THE FEMALE COUNTER F ADDS THE HEIGHT TO ( ) :
C THE FEMALE SUM SUMF FINDS THE FEMALE AVERAGE AVF AND DETERMINES
( ) : ( ) :
END BLOCK
END
These language have features that closely resemble the IF THEN ELSE and WHILE
DO constructs.
2. I believe I can write simpler programs traditionally'than those generated by translating
pseudo code into FORTRAN. What good is this approach to me?
3. But I don't work on large programming projects! What good is structured program-
ming to me?
Answer: Pseudo code serves as documentation for the program. Since pseudo code is
written in a compact and straightforward manner, it is easy to understand and easy to
change in the event changes are necessary. Pseudo code may be written at a relatively
high level with many details of implementation omitted. Such a program statement is a
very effective way to communicate the essential elements of an algorithm to others. It
also sharpens the ability of the programmer to think logically, by breaking down a
problem into distinct processes.
4. I am still not convinced. Is there any evidence that structured programming does what
you say?
Answer: Yes. Top-down program design together with the use of structured constructs
in program implementation have resulted in significant decreases in program develop-
ment time and cost and in an increase in program dependability in a number of soft-
ware design projects in business and industry. Pseudo code has become the standard
way of expressing algorithms in computer science publications. Although structured
programming is only a few years old, it has gained wide acceptance among computer
users.
Another structured statement is the AT END DO. The statements following AT END DO
are only processed when an end-of-file condition occurs during a READ operation. The
statement is implemented as follows:
(READ statement)
AT END DO FOF
statements
RbAD,
7
executable
slalemenls
END AT END
Note that AT END DO must immediately follow the READ statement. If a data card is
read, control transfers to the statement immediately after the END AT END. When an
end of file occurs, the block of statements between AT END DO and END AT END are
processed and then control transfers to the statement immediately following the END AT
END.
6. I plan to use my program with other FORTRAN compilers, not just WATFIV. What
do do if Eve used structured programming statements with
I compiler my WATFIV
and now want to run the program with a FORTR.AN compiler not having structured
constructs?
Answer: WATFIV has a SUBROUTINE called TRANSL that translates the struc-
tured statements to conventional FORTRAN without using GO TO statements. Ac-
cess can be obtained as follows:
where deck is the unit number for the input data, and punch is the unit number for the
output data.
Consult your WATFIV user's guide for restrictions and usage.
STRUCTURED PROGRAMMING 493
FILE 2) containing records in ascending sequence. The progam shown in Figure 12-6
could be used. Note the two independent processes present in this program. These process-
es could be coded separately if desired.
12-4-2 Sorting
Write a program in pseudo code to sort n elements of an array into ascending sequence us-
ing the sort algorithm described in Section 7-4-6. The program in Figure 12-7 could be
used. Note how compact and straightforward the program is when expressed in pseudo
code.
k = n
WHILEk > 1
J= 1
WHILEj < k DO
IF array(j) > array(j -I- 1 ) THEN interchange array(j) and array(j + 1)
ELSE exit
j=j+ 1
k = k - I
columns 1-9 and the index number of the course requested is punched in columns 12-15
(these cards can be in any order). Write a program that will print out a message enrolling
the student in the requested course or informing the student that the course is filled to ca-
DO 10 1 = 1,100
READ(2,7)INDEX(I) ,CUR(I) ,MAX(I)
7 F0RMAT(4X,I4,I3,T78,I3)
10 CONTINUE
C ID IS USED TO READ A STUDENT S ID NUMBER '
END IF
GO TO 100
END IF
15 CONTINUE
C REQUESTED COURSE WAS NOT AMONG THE 100 OFFERED
WRITE (6, 82) ID, COURSE
82 FORMAT IX STUDENT ',19 2X COURSE NO 14 2X NOT OFFERED
( , ' , , ' .
'
, , '
'
GOTO 100
60 STOP
END
Figure 12-8 Course Informalioii.
STRUCTURED PROGRAMMING 495
\{ b' — Aac < 0, then the solutions are complex. The program shown in Figure 12-10 uses a
subroutine to solve quadratic equations. If the real solution cannot be found, a message to
that effect should be printed.
INTEGER FLAG
READ(5,10)A,B,C,LC
WHILE(LC.NE.9) DO
EXECUTE QUAD
WRITE(6,11)A,B,C
IF FLAG NE
( THEN DO . . )
WRITE(6,13)X1,X2
ELSE DO
WRITE (6, 12)
END IF
READ(5,10)A,B,C,LC
END WHILE
STOP
ELSE DO
FLAG = 1
END IF
ELSE DO
Xl = -C/B
X2 = X1
END IF
END BLOCK
10 F0RMAT(3F10.0,T80,I1)
(
'
12-5 EXERCISES
12-5-1 Self Test
ELSE y = > + I
ELSE write s
c. a = I
X =
WHILE a < 10 DO
X = X + a
a = a + I
e. a = I
x =
WHILE a < 10
X = X + a
a = a + 1
f. cl =
c2 =
c3 =
DO CASE X < 10
= cl + cl 1
CASEx 10
=
c2 = c2 + I
CASEx > 10
c3 = c3 + 1
g. n =
z =
p =
UNTIL end of file
DO read num
IF end of file THEN exit
ELSE DO CASE num <0
n = n + 1
CASE num =
z = z + 1
2. Is it necessary to have mutually exclusive conditions when using the CASE construct?
Why?
FORTRAN WATFIV
1. a. IF A LT B GO TO 10
( . . ) IF A LT B THEN DO X = X +
( . . ) 1
Y = Y+1 ELSED0Y = Y + 1
GO TO 20 ENDIF
10 X = X + 1
20 _ .
IF(S.GT.T)G0T0 40 ELSE DO
WRITE(6,1)S IF(S.GT.T)DOPRINT, T,S
GO TO 50 ELSE DO PRINT, S
40 WRITE(6.2)T,S ENDIF
GO TO 50 ENDIF
30 WRITE(6,2)S,T
50 _
c.
•
A=l A=l
X=0 X=0
100 IF( .N0T.A.LE.10)G0T0200 WHILE( A LE 10 )D0
. .
X=X+A X=X+A
A=A+1 A=A+1
GO TO 100 END WHILE
200 _
d. 3 READ (5, LEND = 4) A. B,C WHILE(A.GE.O)DO
WRITE(6,2)A,B,C READ(5.1)A,B,C
GO TO 3 PRINT,A,B,C
4 _ END WHILE
e. A = l A=l
X = X=
5 X=X+A WHILE A. LE. 10) DO
(
A= A+1 X=X+A
IF( .N0T.A.GT.10)G0T0 5 A = A+1
END WHILE
498 STRUCTURED PROGRAMMING
C1 = Same
C2 =
C3 =
IF(X.LT 10)C1 = C1 + 1
IF(X.EQ 10)C2 = C2 + 1
IF(X.GT.10)C3 = C3+1
g. N = N=
Z = Z=
P = P =
10 READ(2,2,END = 100)NUM WHILE NUM. GT. -100) DO
(
IF(NUM.LT.0)N = N + 1 READ(5,2,END=100)NUM
IF(NUM.EQ.0)Z = Z + 1 IF NUM LT
( THEN DO N = N + 1
. . )
IF(NUM.GT.0)P = P + 1 ELSE DO
GOTO 10 IF NUM EQ
( THEN DO Z = Z +
. . ) 1
100 CONTINUE ELSE DO P = P + 1
ENDIF
END IF
2. When the CASE structure is used, the first condition that tests TRUE is the applicable
condition. If cases are not mutually exclusive, the order in which the tests are made will
499
1 1
INDEX
Central processing unit 3. 10. speed of operation of 5-6 form o\' 123
1 30- 3 1
constants 221-224 L 230-233
End-of-file check 128-132 Exponential numbers for literal data 43-45
END statement 45-46,48 input o\' 222-223 relationship with variables
INDEX
bar 274-275
FORTRAN program logical IF 80-88.99.230
deck 72 multiple RETURN of the TAN function
370-372
FORTRAN source deck 72 429-430
FORTRAN statements 22. NAMELIST 281-284 Graphing 331-333
52
computed GO TO 103-104 STOP 45.48 Identification field
Test 1 7
u WATFOR 6
T format code 42-43, 78 WHILE DO statement
Three-dimensional Unconditional transfer 485-487
array 320-322. 325. 330 statement 79-80 compared with DO loop
Timesharing 12 User processing program 487-489
Top-down program design 14-15 WRITE statement 36-37,47
472
Transfer into and out
of loops 177-178. 183
Transfer statement Value of a function 363 X format code 38-39, 79