0% found this document useful (0 votes)
23 views532 pages

Boillot Michel - Understanding FORTRAN

Uploaded by

wilsonjesusrb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views532 pages

Boillot Michel - Understanding FORTRAN

Uploaded by

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

Second Edition

Michel Boilldt f u.s.c,


BOOKSTOftE

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

WEST PUBLISHING COMPANY


St. Paul New York Los Angeles San Francisco
COPYRIGHT® 1978
COPYRIGHT® 1981 By WEST PUBLISHING CO.
50 West Kellogg Boulevard
P.O. Box 3526
St. Paul. Minnesota 55165

All rights reserved


Printed in the United Slates of America

Library of Congress Cataloging in Publication Data

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

Preface to the second edition ix

Preface to the first edition xi

1 COMPUTERS AND COMPUTING


Computer organization and concepts
A model computer
Computer hardware and software
The punched card
Computer access modes

INTRODUCTION TO FORTRAN — PART 1 22


FORTRAN character set and coding form
Constants, variables, and expressions
Replacement statement, WRITE, FORMAT, STOP, END
Format codes I, F
Carriage control

3 INTRODUCTION TO FORTRAN — PART 2 70


READ, GO TO, arithmetic and logical IF, computed GO TO,
comment card
Format codes I, F, T, X and literal data
1

CONTENTS

4 THE COUNTING PROCESS 121

INTEGER, REAL, DATA, IMPLICIT


End of file checking and the END-option
Counting
Format code slash /

5 THE ACCUMULATION PROCESS 170

Accumulation
DO loops and the CONTINUE statement
Flowcharting the DO statement
Random numbers

6 DATA REPRESENTATION 209


numbers
Integers, real
A format code
DOUBLE PRECISION, COMPLEX, LOGICAL

7 ONE-DIMENSIONAL ARRAYS 250


Subscripts and arrays
The DIMENSION statement
Implied DO
Frequency distribution and sorting

8 TWO-AND THREE-DIMENSIONAL ARRAYS 31

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

11 FILE PROCESSING 450


Sequential file concepts

Unformatted READ/WRITE
FORTRAN statements END FILE, REWIND, BACKSPACE,
DEFINE FILE
Direct access files
Direct access READ and WRITE
File flowchart symbols

12 STRUCTURED PROGRAMMING 472


Pseudocode
Top-down program design
DO WHILE, DO UNTIL, and SELECT

Index 499
Digitized by the Internet Archive
in 2010

http://www.archive.org/details/understandingforOOboil
PREFACE
TO THE
SECOND
EDITION

This second edition of UNDERSTANDING FORTRAN is the result of the previous


edition and the response of students and instructors who have used the first edition. New
topics, additional programming exercises and problems, and certain FORTRAN 77
features have been incorporated in this edition. The clarity and the readability of the
text has been significantly improved: the general form of the various FORTRAN
statements have been boxed in, numerous explanations and problems have been
reworded, examples of invalid code have been boxed in and screened, computer type face
has been used for all FORTRAN programs. Following is a list of some of the significant
changes that have been made.
The Flowchart chapter in the first edition has been absorbed into the first five
chapters, to integrate flowcharting with actual program code. Chapter III introduces the
IF THEN ELSE statement which is available in FORTRAN 77 compilers as well as in
most WATFIV compilers. In Chapter V a new section on reports has been introduced,
dealing with control break logic; some instructors may wish to use this section to discuss
input data validation. The section on random numbers has undergone significant
also
changes. Chapter 6 brings more coverage to alpha-numerical data handling through the
A Format code and through the CHARACTER statement (available on most recent
FORTRAN compilers).
Chapter 7 on arrays has been rewritten to include the NAMELIST option and
many new programming exercises of interest have been added. The introductory
programming examples on functions and subroutines in Chapters 8 and 9 have been
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

1-1 THE ELECTRONIC BRAIN


News Item: During a three-day test period prior to Thanksgiving in 1979, the National
Airlines computerized reservation system handled over 40 millon inquiries
with only two errors, and these were detected and corrected by the system.
News Item: Apple Computer, Inc. which manufactures low-cost personal computers, has
announced the availability of a voice recognition device that makes the com-
puter capable of understanding and responding to verbal commands.
News Item: For years mathematicians conjectured that four colors are sufficient to color
any map in such a way that no contiguous areas have the same color, but no
one could actually prove this was true. Scientists at the University of Illinois
have used a computerized approach to establish a proof of the proposition.
News Item: At the 1979 National Computer Conference held in New York City a competi-
tion was held for computer controlled "mice." Participants in the contest built
small, self-contained, computer-controlled vehicles decorated to look like
mice. At the conference each "mouse" was placed in a maze, the design of
which was kept secret from the contestants. The "mouse" that ran the maze in
the shortest time was declared the winner.
The computers mentioned in the above news items are the high-speed, internally pro-
grammed electronic computers that have become the unseen "brains" behind most of the
business transactions of everyday life. Computers have also had an incalculable influence
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.

1-2 COMPUTERS— WHAT ARE THEY?


Computers are automatic electronic machines that can accept and store vast amounts of
information and perform arithmetic at high speeds to produce answers to complex prob-
lems. Without human intervention, they can process long sequences of instructions (called
programs) to solve a variety of problems ranging from payroll calculations to satellite tra-

jectory computations.

1-2-1 Organization of a Computer


The computer can be thought of as a system made up of five components, as shown in Fig-
ure 1-1 These components and their functions are as follows:
.

1. The from the outside world to the computer. This informa-


input unit feeds information
tion includes both dataand instruction (program).' Input units are capable of reading
information recorded on such different mediums as punched cards, magnetic tape, and
terminal keyboards. The information read from these devices is placed into appropriate
memory locations.

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

Central Processing Unit

(CPU)

INPUT
COMPUTERS AND COMPUTING

1-2-3 Computer Programs


An electronic computer may be called an electronic "brain," but its function and prob-
lem-solving ability depend on the intelligence of a human being, who directs and controls
the machine. This person, called a. programmer, is responsible for giving the computer a set
of instructions consisting of the necessary steps required to derive a solution to a given
problem. The set of instructions that controls the computer is called a program.
A
program can be executed (processed) by the computer only when it is stored in the
computer's memory and is in machine language code. Machine language is the only lan-
guage the computer can understand. It is a language in which all operations are represent-
ed by machine recognizable numeric codes and in which memory locations containing
data and program instructions are represented by numeric addresses. Machine language
programs are very detailed and hence difficult to write. Machine languages vary from one
computer manufacturer to another; they are machine dependent, reflecting the design of
each computer. Other types of languages (called high-level languages) have been developed
to allow the user to formulate problems in a much more convenient and efficient manner.
Such languages are problem oriented rather than machine oriented. High-level languages
are machine independent, which means that programs written in such languages can be
processed on any type of computer. Programs written in a high-level language must ul-
timately be translated into machine language before they can be executed by the computer.
Special programs called language translators or compilers have been developed to provide
this translation service. FORTRAN is an example of a high-level language. It is an
acronym for FORmula TRANslation.
The following will help you understand how and why a language like FORTRAN, in-
stead of the computer's machine language, is used by the programmer: Each memory loca-
tion has an "address". Suppose one wanted to add the data contained in memory loca-
tions 065 and 932 and to store the result in location 752. The machine instruction for this
might be "43065932752." The first two numbers are called the operation code. This code is
used by the control unit to determine what action (add, multiply, and so on) is to be per-
formed on the data in the specified memory locations. After an operation is specified, the
operands are given. Operands represent the addresses of the data to be used. The data to
be added are in memory locations 065 and 932; The result will be stored in location 752.
The machine language instruction- is broken down as follows:

43 065 932 752


t t .^^ t .

Operation code Memory address of Address for


first and second result
operands

In FORTRAN programs, arithmetic operations are indicated by the symbols + (addi-


tion), -
(subtraction), * (multiplication), / (division), and ** (exponentiation). Each mem-
ory location is assigned a symbolic name. Let us agree to call location 065 by the symbolic
name P, location 932 by X, and location 752 by A. Then the FORTRAN instruction
equivalent to the machine language instruction "43065932752" would be

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.

1-3 YOU MIGHT WANT TO KNOW


1. Just how fast do computers operate?

Answer: The latest model computers operate at speeds measured in nanoseconds (1


nanosecond = billionth of a second). For example, the ILLIAC IV computer is
1

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?

Answer: Perhaps. One nanosecond is to second as 1 second is to 32 years. In other


1

words, there are approximately billion seconds in 32 years. One nanosecond is the ap-
1

proximate time required for light to travel 1 foot.

3. Is there any limit to the internal speeds of a computer?

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

size and density of an integrated circuit "chip."

Mcmof>
(PROM)
(S. 192 Bill)

(KAM)

Internal
Internal clock

loj.c

loj.c Filrrnal control lo|ic

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.

5. Do computers make mistakes?

Answer: Unless a computer component malfunctions (an extremely rare occurrence),


computers do not make mistakes. Of course, programmers may cause computers to err
because of incorrect instructions in a program. Most "computer errors" are at-
tributable to human error rather than to actual machine malfunction.

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

BASIC beginner's /Ill-Purpose 5'ymbolic /nstruction Code


COBOL common fiusiness-Oriented Language
RPG Report Program Generator
PL/I Programming Language /
ALGOL /4LG0rithmic Language
SNOBOL String Manipulation Language
GPSS General-Purpose Simulation System
APL ^ Programming Language
WATFOR lVATeT\oo POPTRAN— FORTRAN-like language developed at
the University of Waterloo primarily for student usage.
WATFIV A version of WATFOR
7. How many versions of FORTRAN are there?

Answer: Every manufacturer implements FORTRAN in a slightly different way. In


fact, a given computer installation might have several different versions of FORTRAN
available, all running on the same computer. All FORTRAN compilers are measured
against a "standard" description of the language formulated by the American National
Standards Institute (ANSI), which is a subdivision of the Bureau of Standards. Most
FORTRAN compilers meet these standards and have other features that are classified
A technical reference manual developed by the computer
as extensions of the language.
manufacturer for the FORTRAN used at the reader's computer installation is a worth-
while investment and may save hours of frustration and inconvenience. The serious stu-
dent should consult a FORTRAN user's guide while studying this text.

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

1-4 A MODEL COMPUTER


Let us consider a very simple model computer that operates conceptually in much the
same way as its larger real-life counterparts (see Figure 1-4). The input medium consists of
pieces of paper on which numbers have been written. The memory unit consists of a group
of sequentially numbered "pigeonholes." Each "hole," or location, in the memory can
hold one instruction or one number. Locations can be referred to either by name or by ad-
dress.The arithmetic/logical unit is represented by a desk calculator capable of per-
forming arithmetic and logical operations. The role of the control unit is played by a hu-
man operator who can fetch instructions from memory one at a time and execute them;
the operator can also fetch data from or store data in various memory locations. The types
of instructions capable of being executed include:

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

5. Conditional branching. Perform a comparison test between two values in coordination


with the logical unit and branch to a specified memory location if the test condition is

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

that condition is not met.

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:

1 READHRS Determine the number of hours worked


from time card.
IF HRS > 40 GO TO 5 Check if number of hours is greater than 40.

PAY = 2*HRS If not, compute regular pay and go to print

GO TO 6 pay.

PAY = 80 + 3* HRS - 40 ( If hours are greater than 40, compute regular


pay, which is $80, plus overtime at rate of

$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-7 A Central Processing Unit (courtesy Hewlett-Packard Company).

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-

zation costs are significantly lowered by multiuser participation.


COMPUTERS AND COMPUTING 13

Figure 1-9 A line printer (courtesy IBM) Figure 1-10 A plotter (courtesy Hewlett-
Packard Company).

Figure 1-11 A card reader (courtesy IBM).

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. Operating system programs.

3. User processing programs.

Translation programs (compilers) are programs used by the computer system to


translate high-level languages or problem-oriented languages into machine language.
These translation programs are generally supplied by the hardware manufacturer.
Operating system programs are usually supplied by the computer manufacturer to as-
sist in the overall operation of the computer system. They are used to regulate and super-
vise the sequence of activities going on at any time in the system. These programs min-
imize operator intervention in the actual operation of the computer and ensure a smooth,
fast, and efficient transition among the varied tasks performed by the system. Other oper-
ating system programs aid the programmer in his or her own work; examples of such pro-
grams are and library programs. Following is a list of functions performed by some
utility

operating system programs:

1. Load programs into memory from mass storage.

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.

4. Handle requests for input/output from executing programs.

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.

1-5-3 The Punched Card


One of the most widely used media for communication with a computer is the punched
card. Many computersystems require the user to punch his or her program and data on
punched cards before these can be processed by the card reader (see Figure l-ll). The
most widely used version of the punched card is shown in Figure 1-14. The card is divided

12 edge l.etters Special characters


Digits
^^/MBLDtriiHi LMnafijfSTuvij
12 lllllllll
jt

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

2 lltl MI I Itl II! I III II II I III! 'lll!III)IIlIIl!MI!III!III!III!|l!|lII!Il|llI!!i:

3 111 I 1 I I I Ill 111 lllll 11 1 111 1 1 lllllllllllllllllllllllllllllllllllllllllllllllll


4 Ten
Numeric 4 4|l I I 4 4 I ill I 4 4 4 4 4|4 4 4 4 4 4 I 4 I4I||444I4444444444444I44|II|444444444I4444444444
punches l|) llli llllllll iSi II nisiliiiissiiiisiiiiiiiisiitillssjiiiliiiiltiii)
numbered
5 I > 1 I ) i I
y rows
6 II I III I I I I I III II t I I III I i I i I iiiiiiliiiiiiiiiiiiiiiiiiiiiiliiiililiiiiliiiiiii
7 ? : 1 1 ?li I MM l|l M M m|m M I im|miim)immimmmiimiiIiii|i||mimiii
8 1 1 1 1 1 III II lllllllllllllllll lllllllllllllllllllllllllllllllllllllllllllllllll
9 1 1 1 1 1 1 1| I I I I I I III II I I I lis II I I I II I I I ill I I I I I I I I I I I I I I I M ) II I I I I I ) 11 ) I I I I I I I ) I

V. ^ ^^ 9 edge

80 numbered columns

A
,

16 COMPUTERS AND COMPUTING

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

1-5-4 Computer Access Modes


From communications (submission of programs) with a computer can
a user standpoint,
be established in methods or modes: balch-processing and conversational
two different
mode. Both of these access methods may or may not be available on the user's particular
COMPUTERS AND COMPUTING 17

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

Paper stack which


must be separated

Figure 1-17 Batch-processing flow.


18 COMPUTERS AND COMPUTING

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

1-5-5 A Typical Job


The FORTRAN program shown in Figure 1-18 will perform the task outlined in Section
1-4. Comparison of this program with the program in Section 1-4 should reveal many
similarities as well as some differences in the actual code. The requirements for writing
FORTRAN code are the subject of the remainder of this text, so the reader need not be
concerned with the technical details of the program at this time.
Let us assume for the moment that the program has been written and is available in
the form shown in Figure 1-18. The program and data it will process must still be pre-
pared in some comput-
suitable form for submission to the computer. In a conversational
ing environment, the program and data will be entered one line at a time at a terminal (see
Section 1-5-3). In a batch-computing environment the program and data will be punched
onto cards or collected using a text editor and submitted from the text editor to the com-
puter as a complete "job". In both conversational and batch environments, certain in-
structions must be included to inform the operating system how the job is to be processed.
In a conversationalenvironment, these instructions are specified at the terminal; in a batch
environment, these instructions are punched onto cards and submitted with the program
and data. Figure 1-19 shows a complete job deck for the compilation and execution of the
COMPUTERS AND COMPUTING 19

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"

Mill nun I nn i mm nn n n nn n n n in nninii


n M I M M I I M M I I I I MMM M I I I M M M I I I M M M I 1 1 1 1 1 1 1

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

1. List five parts of a computer and explain the function of each.

2. Define the following:

a. CPU. b. CRT. c. Program.


d. Data. e. Nanosecond. f. ANSI.
g. Machine language. h. Unconditional branch. i. Conditional branch.
j. Batch environment. k. Conversational computing. I. Hollerith code.

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

6. Which of the following is used for input as well as output?

a. Card reader b. Printer Hi Magnetic tape


^0/ All of the above e. None of the above

7. A compiler is

A
program which translates machine code into a high-level language.
a.

Another name for FORTRAN.


b.

c. A program which loads FORTRAN into memory.

^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

a. An operand b. A compiler /cJ An operation code d. A translator

9. Determine whether each of the following statements is true or false.

"f a. Each memory location has a corresponding address.


b. A machinelanguage operand may indicate where the result of a particular operation
is to be placed.

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

sponse to his program.


/ g. Time sharing is made possible by the use of time slices.
t^ h. Multiprogramming means that instructions from two or more programs can be
, processed at the same time by the CPU.
"X i. A single card column may accommodate any number up to and including the
tr number 99.
COMPUTERS AND COMPUTING 21

1-6-2 Other Problems

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.

2. a. If you will be working computing environment, determine


in a conversational
sign-on, sign-off and other procedures necessary to compile and execute a FOR-
TRAN program. Try out these procedures with the program shown in Figure 1-18.
b. If you will be working in a batch-processing environment, determine the operating

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?

1-6-3 Answers to Self Test

1. Input: Device which reads information from some medium.


Output: Device which writes information onto some medium.
Memory: Stores program instructions and data.
Arithmetic/logical: Circuitry which performs arithmetic and decisions on the data
Control: Executes program instructions.

2. a. CPU: Central processing unit— Memory, arithmetic/logical and control units.


b. CRT: Cathode ray tube— Input/output visual display device.
c. Program: Instructions to solve a problem.
d. Data: Information to be processed by a program (numbers, lists of names etc.).

e. Nanosecond: One billionth of a second.


f. ANSI: American National Standards Institute.
g. Machine language: Numerical language inherent in the design of the particular com-
puter.
h. Unconditional branch: GO TO— branch or transfer to same location each time the
instruction is executed,
i. Conditional branch: IF— branch based on whether a condition is true or false,
j. Batch environment: Computing system in which programs and data are processed
some period of time after submission of programs,
k. Conversational computing: Computing system in which user's instructions and data
are analyzed and processed immediately.
1. Hollerith code: Punched-card code.

3. 102.5; 47.5 4. THEEND . 5. 80,12.

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

2-1 PROBLEM EXAMPLE

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:

1. The replacement (assignment) statement used for calculations; for example


Al = W1*E1

2. The WRITE statement used to identify which variables are to be printed.

3. The EORMAT statement used to position the numeric values (results) and the
alphabetic messages on the output line.

4. The STOP statement to terminate execution of the program.

5. The END statement which must be the last statement in any FORTRAN program.
INTRODUCTION TO FORTRAN— PART 1 23

FORTRAN Program (sTARTj Explanations

Wl = 75.6 Wl - 75.6 Define the width oflot 1.

W2 = 98 5
. W2 = 98.5 Define the width of lot 2.

El = 121.5 El = 121.5 Define the length of lot 1

E2 = 110.6 E2 = 110.6 Define the length of lot 2.

A1 = W1*E1 Al = W1*E1 Compute area of lot 1

A2 = W2*E2 A2 = W2*E2 Compute area of lot 2.

WRITE (6,10)A1 j
WRITE 7 Print area oflot 1.

/ "AREA LOTl IS'\Al/

WRITE Print area oflot 2.


WRITE (6.11)A2 "AREA LOT2 IS .A2
/ 7
Compute total area oflot
AT0TAL = A1+A2 ATOTAL = Al + A2
and lot 2.

WRITE
WRITE(6,13)AT0TAL / "TOTAL AREA IS", Print total area.

ATOTAL

STOP Stop.
C]l2L_)
10 FORMAT 3X ( AREA LOTl IS F8 1
, ' ' , .

11 FORMAT (3X, 'AREA L0T2 IS' ,F8.1)


13 FORMAT 3X ( TOTAL AREA IS 2X F8
, ' ' , , .
1
END

Figure 2-1 Calculation of the Area of Two Lots.


5 )
) 1

24 INTRODUCTION TO FORTRAN— PART 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
( , ' ' . .

11 FORMAT 3X AREA L0T2 IS F8 1


( , '
' , .

13 FORMAT 3X TOTAL AREA IS 2X F8


( , ' ' , , .

END

AREA LOTl IS 9185.4


AREA L0T2 IS 10894.1
TOTAL AREA IS 20079.5

Figure 2-2 Computer-produced FORTRAN listing and results.

' ENP
INTRODUCTION TO FORTRAN— PART 1 25

2-2 GETTING STARTED

2-2-1 Character Set


The characters used in FORTRAN are grouped into three classes:

Alphabetic. The alphabetic characters are:

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

300 -2 63247 +4 are integer constants.


6.32 -3.21 .0005 +63.04 are real constants.

An imbedded blank (blanks between the first and last digit) in a constant has no effect on
the value of the constant.

Example The following constants have the same value:

6 32 632 6 3 2

No characters other than those just described can be used in writing constants.

Example The following constants are invalid:

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-

ferent internal representations.

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.

Examples The following are valid variable names:

X Ql COUNT
ABC SUM X12345

The following are invalid variable names:

INVOICE

,^
INTRODUCTION TO FORTRAN— PART 1 27

Integer Memory Real variables

MAX

KOUNT

JAR

N103
K

28 INTRODUCTION TO FORTRAN— PART 1

Examples The following are valid expressions:

FOR TRA N expression A Igebraic expression

A a

14 14

(A/B)*C a
'
~b'
A*B-30. a'b-30
-C —c
(A*B)*»2 {aby

(-C + B)*D {-c + b)d


A**B (t

-3.7 -3.7

A**. 5 a

( (A-B)**3)**.25 ^{a- by
PMT*(1 + IC)**N/IC-1 PMT(1 + icy - 1

ic

A*(X + B/(2*A) )**2+ (4*A*C-B*B)/(4*A**2) a{x + _6J^ + 4ac - b'


2a 4 a'
-2*V*(X*X + Y*Y)/(U*U + V*V)**2 -2v{x'+y')
{u'- + v'y

(2*MU*(E + VO)/(H*H) )**.5


h'
F*( (LAM-1)/R0-L*(L + 1)/(R0*R0) ) F fX - 1 - /(/+ 1) 1

Following are some examples of invalid expressions:

3(A + JB) Operator missing after the 3.


A- (B + C*(K) Unpaired parentheses. Should be A - B + C* ( (

X*-3 Two operators side by side. Should be X*( — 3).

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

3*(4+(8/2)) 3* (4+ (8/2) )


=3* (4 + 4) =3*8 = 24

When no parentheses are present in an expression, operations are performed according to


the following rules of precedence:

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

1. A-B-hC B is subtracted from A and the result is added to C.


3. -2. -^5
(3. - 2.) + 5. = 1. + 5. = 6.

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.

3. A/B*C Since multiplication and division have the same priority, B is

first divided into A (A/B), and the result of the division is

multiplied by C. This is different from A/(B*C).


9./4.*2 (9./4.)*2 = 2.25*2. = 4.50

4. A/B/C First A/B is performed, and the result is then divided by C.


You will get the same answer if you calculate A/(B*C).

8 /4 /2
. .
|- ^ 2. = 2. ^ 2. = 1.

5. (A-^B)/C*D The parentheses indicate that the sum of A + B is to be per-


formed first. The sum is then divided by C and the result is

multiplied by D, giving
A + B D not A + B
C C*D
9.
(3. +e. )/3.*6 '6. = 3.*6. =
3.

6. A + B*C**2 Since exponentiation has highest priority, C' is computed.


This result is then multiplied by B, since multiplication has the
next highest priority. Finally, this result is added to A, giving
A + (B*(C**2)).
3. +Z.*2.**2 3. + (3.*2.^) = 3. (3.*4) = 3. + 12. = 15.
.

30 INTRODUCTION TO FORTRAN-PART 1

7. A**B**C Exponentiations are evaluated from right to left; therefore, B


israised to the power C. This result is used as the power of A,
giving
A**(B**C) not (A**B)**C
3**2.**3. 3.**(2.**3.) = 3.**8. = 6561. not
(3**2. )**3. = 9.**3. = 729.

2-2-6 The Replacement Statement


A
replacement statement specifies arithmetic operations to be performed and the location
(variable) into which the value
computed is to be placed. The general form of the replace-
ment statement is

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:

^ = 3- 123 Define X to be 3.123 (place 3.123 in location X).


Whatever value was in X before is now destroyed
(replaced).
CI = A B /C
( -I-
) Compute A -I- B, divide by C, and call result C 1

Z = 3.**2. Let Z be equal to 3. squared.


SK = Z + 4 * * 5
(
. ) . SK is computed as the square root of Z -I- 4.

The following are examples of invalid replacement statements:

^ '^ = ^ A variable and not a constant must occur on the


left-hand side of the equals sign; also, how can one
store the value of X
into 3.16?
X+ Y=l An expression cannot occur on the left-hand side
of the equals sign; also, how could one store a in I

the sum of two memory locations?


HRS*RATE -I- BONUS There is no variable specified into which the result
is to be stored.

2-2-7 Mixed-Mode Expressions


A mixed-mode expression is an expression in which constants and/or variables of different
modes (integer, real) are present. The general evaluation rule is as follows: If
an integer

'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

Expression Value oj Expression

3/2. 1.5 The integer 3 is converted to real 3.


3./2 1.5 The integer 2 is converted to real 2.
4.-^3/2 5. The operation 3/2, involving integers,
is performed, resulting in 1. Then 4. -h

1 is a mixed-mode expression eval-


uating to 5.

4.*3/2 6. The operation 4.*3 is performed first,

yielding 12., which is then divided by 2


to give 6.
4.*(3/2) 4. (3/2) is performed first, giving 1, which
is then multiplied by 4., yielding 4.
4 + 3/2 5.5 3/2. ismixed mode, which evaluates to
1.5, which is added to 4, giving 5.5.
1-^7.2 6.2 If I = —I, the expression evaluates to
6.2. In memory, however, the value
stored in 1 is still the integer — 1

2-2-8 Mixed -Mode Replacement Statements


A mixed-mode replacement statement is a replacement statement in which the mode of the

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

IX = 3. 2 The value stored in IX will be the integer 3


When a real value is converted to integer,
any fractional part is truncated.
X = 3-h2 The value of X will be 5., not 5
J = 3 /2. The value of the expression is 1.5, but the
value stored in J will be 1, since J is an in-

teger variable.
KX = 4/3 + e.s 4/3 is 1 , numbers are integers. +
since both 1

6.8 = one of the operands is real.


7.8 since
The value stored, however, is 7 since KX is
integer.
1

INTRODUCTION TO FORTRAN— PART 1

2-2-9 The FORTRAN Coding Form


A FORTRAN program consists of a sequence of FORTRAN instructions called FOR-
TRAN siatements. These FORTRAN
statements are punched into specific fields with only
one statement allowed per card. The layout for a statement card is shown in FORTRAN
Figure 2-4.

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

2[2 2 2 2 22222222222222 2222222222222222222222222222 2222222222222 2222222222 222222


3I3 3 3 3 3 33333 33 3 33 3 33 3333333 33 3 3 33333333333333333 3333)33333333 )133333)31133311
1

4'4 4 4 4 44444444444 444 4444444444444444444444444444 4444444444444 4444444444444444


I

5[5 5 5 5
555555555555555555555555555555555555555555 S55SSSS555SSS S5SSS55S5SSSSSSS
E6S6(SE6&SE666E6666S66(SSS6SE6CC teSS66SSS( EEEtEEfiE<fit(( ttllKtIIICSdIt
miinninini
I

7|7 7 77 77777777777777 7777777777777777777777777777 7777777777777


I

n 8 8 i IBIIIIISIISIIISIIIIIIIIMIIIIIIIIIIIIIlin tlllllMIIIII iiiiiiiiiiiiiiii


sis
.|i
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 3 9 9 9 9 9 9 9 9 9 9
1 •
9 9 9 9 9 9 9 9 9 9 9 9
iiiifnuu<4n»ii*»ior2in»Bsnania>iuiJMBai7a)i<iflUUM«9<t4i«t«taKiinwsBsanMiiiiB
nMWtty _^ .
••)
9SS9SSSSSISS9 SSSISSStlMISIIt
n^naaan*
V
Figure 2-4 FORTRAN Statement Card.

The following fields are used in punching a FORTRAN statement:

Card columns 1-5 Statement number (optional except for


formats).
Card column 6 Continuation (optional) discussed in Section 3-5-5
Card columns 7-72 Body of FORTRAN statement (always
required).
Card columns 73-80 Identification (optional).

A statement number is an unsigned integer number which identifies a particular


FORTRAN statement. It allows one to distinguish one FORTRAN statement from an-
other by giving it statements need be numbered.
a special address. Not all FORTRAN
The programmer can number all statements if he or she wishes. Statement numbers can be
from one to five digits long and are punched anywhere in card columns through 5.- The 1

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

Chapter 3, Section 3-5-5).


Card columns 73-80 can be used to identify the author and/or for sequencing
purposes (see Figure 2-3 and Section 2-5-1 for further discussion), or they can be left
blank. FORTRAN coding sheets are available commercially to help the novice identify
the various fields punched card. The coding sheet simplifies the transcription of the
in the
program onto punched cards during the keypunching operation (see Figure 2-5).

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

2-2-10 The Complete Job


As we have noted in Chapter I, Section 1-2-3, FORTRAN is an example of a high-level
language. FORTRAN allows a user to communicate with a computer in a semi-Eng-
lish-scientific language which hopefully is not too difficult to learn — after all, there are cer-
words, such as READ, WRITE, FORMAT, STOP, END etc. The
tain easily recognizable
FORTRAN programmer can express his problem through mathematical relationships
and formulas. The computer, however, does not understand FORTRAN directly; its natu-
ral language is machine language. To the computer, FORTRAN is a foreign language (see
Figure 2-6), which must be translated into machine language before it can be processed
(executed). In the early days of computers, machine language specialists would translate
high-level languages into machine language. Today, special language translator programs
[compilers) are used to perform this translation at extremely high speeds, without human
intervention. The compiler reads a FORTRAN program [source code) and produces a re-
sulting set of machine instructions [object code) that can then be executed by the CPU (see
Figure 2-7).

Toprocess a program on a computer requires more than submission of some source


code written in a high-level language. The computer system must be told, among other
things, what high-level language to expect so as to direct the appropriate compiler for the

Pu/zied computer speaks


only machine language
Inslruclions
in I ORTRAN
FORTRAN
what's that??
Please do
what I say

Figure 2-6 Language barrier.


INTRODUCTION TO FORTRAN— PART 1 35

Joyful computer understands


Do you need a
translator, monsieur? machine language
The waiter is telling
you they are snails.

Please do
what 1 say
36 INTRODUCTION TO FORTRAN— PART 1

2-2-1 1 The WRITE Statement


The general form of the WRITE statement is:

\^K\TE{device-number, format-statement-number) [variable-list]

where device-number is a code (integer constant) representing the output device to be used

(printer, tape, disk, etc.)


format-statement-nuniber is the number of a FORMAT statement to be used to de-
scribe the output operation (layout design)
variable-list is a list of variable names separated by commas. When the WRITE state-

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

Device-number Format List of variable names

WRITE (6,10) PAY HRS RATE , ,

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:

Device-number- Ph vsical device

5
INTRODUCTION TO FORTRAN— PART 1 37

The following are examples of invalid WRITE statements:

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

statement-number FORMAT (/c/,, /^Z:, .M,)

where statement-number is the format label referred to in a WRITE statement,

fd\,fdi, . . . J(i„ are format codes which can be either:

1. Data format codes used to identify the mode of the data items (numerical results) to be

printed: for integer and F for real numbers: or


I

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

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

general form of the X format code is:

nX

where n is an integer specifying the number of spaces (blanks) desired.

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

Three spaces at the beginning


Output form
of the output line

The I Format Code

Integer data is described for an output operation by the I format code. The general
form of the I format code is:

Iw

where I specifies that an integer is to be written out,


w specifies the number of spaces to be reserved on the output Hne for the number
(width of output field).

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

Note the one-to-one correspondence


ICT = 43200 between each variable in the list of
LI =-4 variables and the corresponding format
J SUM = 33 codes in the FORMAT.
WRITE (6, 14
Note the absence of a comma before the
14 FORMAT (2X,
parenthesis.

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

15 FORMAT (2X, 13, IX, 12, 2X, 14)

First print position


» ,1,4 Printed line

The F Format Code

Real data is described by the F format code. The general form of the F format code is:

Fu.^

where F number is to be printed out


specifies that a real
H^' number of spaces (print positions) to be reserved on the output re-
specifies the
cord (line) for the number
^specifies the number of digits to the right of the decimal point that are to be print-
ed for the real number.
INTRODUCTION TO FORTRAN— PART 1 41

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

left instead of leading zeroes.


Depending on the number of digits (d) specified in the format code Fw.d, the data will
be rounded as necessary, as shown in the following example.

Example 2

A- 12.6534
B=13.7
WRITE (6, 16 A, A B

16 FORMAT (2X, F9.3, F6.1 F5.0 F7.3)

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

12 FORMATdX, F7 3 . . 1X,F5.1, 1X,F6.2, 1X.F5.4

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.

To provide a field (w) sufficiently large to represent a real (lloating-point) number,


the follow ing rule is offered:

minimum for_vv ^.d + 1 + ( 1


) + wh

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)

Output field for J Output field for K

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 Format Code for Literal Data

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:

The character string AVERAGE often characters (including the blank) is


IS, consisting

printed starting in is the numer-


print position 5. Immediately following the literal string
ical field for K V. Blanks within the single quotes are part of the literal and hence are print-

ed on the output form.


44 INTRODUCTION TO FORTRAN— PART 1

Example 2

IERR0R = 999
WRITE(6,6)IERR0R
6 F0RMAT(T2, '*** *** '
,13)
# * * 9 9 9

Literal field

More than one literal string can be described in a format, as in:

Example 3

K = 35
INTRODUCTION TO FORTRAN— PART 1 45

Literals can be used conveniently to provide headings, as follows:

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

Finally, it is possible to have a WRITE statement without any variable-list, as in:

Example 6

WRITE(6.11)
11 FORMAT 3X XYZ CORPORATION
( ,
'
'
)

The following will be produced on the output line:

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.

2-2-13 The STOP Statement


The general form of the STOP statement is:

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.

2-2-14 The END Statement


The general form of the END statement is:

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.

2-3 You Might Want To Know


_1*.-What happens if I insert extra unneeded sets of parentheses in an expression?

Answer: Extra sets of parentheses have no effect on the evaluation of an expression.

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.

2. How long can a printed line be?

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.

4. How many WRITE statements can reference a FORMAT statement?


Answer: As many as desired. The FORMAT is then shared by many WRITE state-
ments.

5. What happens if I try to divide by zero?

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

statements). The END statement is not translated into a machine-language instruc-


END statement
tion. If the is not the last of the FORTRAN statements, the remain-
ing FORTRAN statements will not be read (processed) by the compiler. In the con-
text of the cartoon in Figure 2-6, the American could use an END statement to tell the
translator that the message preceding the END statement is all he wants trans-
lated. The world's shortest FORTRAN program is just an END statement all by
itself! The STOP statement, on the other hand, is translated into a machine-language
instruction and is therefore executed by the CPU during execution time to inform the
system that all machine instructions (corresponding to the program) have been carried

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

of a negative number is undefined. For example, (— 3.)**2. would result in an execu-


tion-time error.

11. Can an exponent be negative?

Answer: Yes. For example, 3.**( — 2) is evaluated as — = J_


3.^ 9.

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

13. Is it possible to reduce the number of operations required to evaluate an expression


using nested parentheses?

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

Evaluation of this expression will require 2 exponentiations


3 multiplications
3 additions.

The above expression can, however, be simplified by factoring as follows:

-
2x' + 3x' -6x+ \ = {2x' + 3a- - 6) x + \

= {{2x + 3)x-6)x+ \

This can then be written as:

( (2*X + 3)*X-6)*X+ 1

Evaluation of this expression will require 3 multiplications

3 additions.

14. How do I cause an apostrophe to be printed as a part of a literal string?

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

50 INTRODUCTION TO FORTRAN— PART 1

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,

15. What happens as a result of the following code?

X = 23 99 Overlap of two fields due to incorrect use of the


Y = 567.45 Tab feature.

WRITE(6,11)X,Y
11 F0RMAT(T2,F5,2,T5,F6.2)

Answer: The printed line is constructed in memory as:

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

arrangement and subsequent output line.

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.

2-4 PROGRAMMING EXAMPLES

2-4-1 Finite and Infinite Sums


Consider the sum of the following 1,000 terms:

SUM=i+ 1+ 1+ 1 +...+ ±=1+ 1+ 1+ 1 +...+


2" 2- 2' 2''' 2 4
2' 8

This is a geometric progression, and its sum can be computed as follows:

1
- r
INTRODUCTION TO FORTRAN— PART 1 51/

P.9
where a is the first term of the progression (a = 1

r is the ratio of any two consecutive terms {r = 1 /2)


n is the number of terms to be added {n = 1,000).
The infinite sum

1 +1 + 1 + 1+ . . . +J_+ . . .

and so forth can be computed as SUM = inrl < 1

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 .

11 FORMAT T5 THE DIFFERENCE IS F5 3


( ,
'
' . .

END

Figure 2-9 Calculation of the Sum of a Geometric Progression.

2-4-2 Income Calculation


Mr. X is a widower with three children aged 12, 16, and 19. His monthly salary is

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

52 INTRODUCTION TO FORTRAN— PART 1

CHILD = 119.25
SALMON = 1023.36
RETIRE = 9 SALMON* 045 /12 (
.

.
)

SSTAX= .0613*SALM0N
TAXING = .136*SALM0N
PAYNET = SALMON - RETIRE + SSTAX + TAXING (

PAYLIF = 096* SALMON - TAXING - SSTAX


. (

PAY = PAYNET -PAYLIF


PAY = PAY + 2.*GHILD
WRITE (6. 14) PAY
14 FORMAT 2X SPENDABLE INGOME F7 2
( ,
'
' , .
)

STOP
END
SPENDABLE INGOME 952 01 .

Figure 2-10 Income Tax Calculation.

2-5 PROBING A LITTLE DEEPER


2-5-1 The Identification Field

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.

2-5-2 Carriage Control Characters


You may have noticed that in all programs written thus far we have purposely stayed away
from print position 1 for the printing of the results on the output form. The reason for this
is to provide one space for a carriage control character to be interpreted by the printer to
control the vertical movement of the output form (page). This first character on every line
sent to the printer is used as a code to determine the vertical spacing of the paper rather
than as a character to appear on the line. In any event the code is not printed. It is just a
signal to the printer to tell it to single-space, double-space, skip to the top of a new page,
etc. The table shown in Figure 2-1 I summarizes permissible codes and the meaning as-
sociated with each.

Code Meaning

1 Skip to the top of a new page


Double-space.
+ Do not space; i.e., stay on the same line,

blank Single-space,
other characters May have special installation printer control effects.

Figure 2-1 1 Carriage Control Characters.


INTRODUCTION TO FORTRAN— PART 1 53

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.

The above code segment will result in the following output.

Last printed line. This is still where


the printer is before it encounters
WRITE(6,10)AX

Before printing 3.2, the printer spaces


one line since the carriage code is blank

Example 2

AX = 3 2 . output line

WRITE (6, 10) AX .2


10 F0RMAT(F3.1) ]
L reserved for carriage control character.

This would have resulted in the following output.

Last printed line.

The 3 of 3.2 is interpreted as a carriage -

control character since the FORMAT


forces it in the first print position. The
digit 3 might be interpreted to space one
line. Note that the code (3) does not
get printed.

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

54 INTRODUCTION TO FORTRAN— PART 1

This code segment would yield the following output:

As a result of a preceding WRITE, the


printer is still on thai line.
423
As a result of the WRITE(6J0)I and the
carriage control code of 0, the paper
moves up two lines and prints 423. This
leaves one blank line between the last
line printed and the current line.

Example 2

J = 623
WRITE(6,15)J
15 FORMAT( '
1 '
,17) Note the literalT in the 1st prim position.

This code segment would yield the following output:

Last printed line

The output is printed at top of new page. 623

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.

This code segment yields the output:

Last line printed

At the conclusion of VVRITE(6,1 ), THE NUMBER OF GIRLS IS 678


1

the literal message is printed and the


printer stays put. The next WRITE
statement tells the printer not to advance
the form { + ) but to print K
on that very same line.
INTRODUCTION TO FORTRAN— PART 1 55

It is important that a carriage control character be included explicitly in a FORMAT


statement used for printed output. The system will use as a carriage control character
whatever character appears in the first print position of the output line; it does not matter
to the system whether this character originated as a literal or a data item from an F or I

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

This code will produce the following output:

Last line printed

Top of new page


K has value 123. Since the first character
to be printed in the first print position is a 23 -24
1, that character is interpreted as a "skip
to next page" and does not get printed.

2-6 FLOWCHART ASSISTANCE


2-6-1 Algorithms, Programs, and Flowcharts
As a problem computer can function only if it is given instructions on how to
solver, the
proceed. A
of instructions for solving a problem is called an algorithm. Algorithms of
set
one type or another are used daily by people to solve such routine problems as baking a
cake, operating an electrical appliance, or solving a quadratic equation. Algorithms can be
expressed in verbal or in symbolic form. To be useful an algorithm must be expressed in a
way that can be understood and executed by the person (or machine) for which it is in-
tended. A computer prograw is a specific example of an algorithm intended for a machine.
It is expressed in a symbolic language that the computer can readily understand and ex-

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

/read hrs/ Find the number of hours (HRS) punched on


a card (the data card is not shown).

<QjRS
INTRODUCTION TO FORTRAN— PART 1 57

Symbol Example

{ START J Start execution here.

CZ=) Terminal
( STOP ) Stop execution here.

READ 7 Assign two values read from some ex-


I A and

OO ^-B ternal source to the variables B.


/ /
Input/Output

WRITE 7 Write the values contained in A and


I
A, B to some external medium.
Bont(
/ /

Add the value contained in Y to the


Processing X = Y + Z
value contained in Z and place the re-
sult in X.

o Connector (entry)

Y£3
Take the Yes path X is equal
if to 4,
Decision -^ otherwise take the No path.

Flowlines point to the next block to


be executed.

Flowlines

X = X - 1

After execution of the processing

6 Connector (transfer)
block containing X =X—
execution at entry point marked A.
1 , resume

Figure 2-13 Program Flowchart Symbols.


58 INTRODUCTION TO FORTRAN— PART 1

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

READ HRS, RATE

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

The sequence of instructions to be executed in a flowcharted algorithm is denoted by


straight lines with anarrowhead such as or I . The direction of flow isalways in
the direction pointed out by the arrowhead.

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:

1. To identify a block by a label for reference purposes, and

2. To indicate transfer to another labeled block.

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

toward the connector as in -•


( j , the connector is being used to indicate a transfer,
that is, execution should resume at an entry point with the same symbol as used in the con-
nector at the transfer point. For example, consider the following flowchart segment:

/ 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-6-3 Flowchart Self-Test

1. Is a recipe found in a cookbook an example of a flowchart? An algorithm? A program?


INTRODUCTION TO FORTRAN— PART 1 61

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

Translate the following algebraic expressions into FORTRAN:


a
a.

f. y'^^

i. 2(x/')

1. V + a'
INTRODUCTION TO FORTRAN— PART 1 63

c. WRITE(6, 11)4,5.23 ( WRITE(6.16)A.I,J


11 F0RMAT(T5,I2,F4.2) 16 F0RMAT(T3,F4.5,I2,I1)
e. WRITE(6,7)A,K,C f WRITE (6, 9) 'RESULT IS' ,J
7 F0RMAT(F5.2,I3,F4. )
9 F0RMAT(3X,I3)
g. WRITE(6,12. )X,Y \ WRITE(6,15)I,X,K
12 F0RMAT(2X,F3.1,F3.1) 15 FORMAT (IX, 12, 13, II)
i. WRITE(6,11)X- Y j WRITE(5,9)KL,M1
11 FORMAT (F3. 2, F4.0) 9 FORMAT (3X, 13, 13)

7. Which of the following statements are true?

a. Statement numbers must be sequentially numbered.


b. Integer variables must start with one of the letters I,J,K,L,M,orN.
c. The statement END denotes the logical end of the program.
d. Statement numbers cannot exceed 99999.
e. Syntax errors are detected at execution time.
f. FORMATS can be located anywhere in the program before the END card.
g. The STOP is used by the compiler to terminate the translation process,
h. SAM. is a valid, real variable name.
i. Statement numbers must column 1. start in

j. A FORMAT can be referenced in any number of WRITE statements.


k. X=X+ 1 . is a valid FORTRAN statement.
I. WRITE( 6, 11) is an invalid output statement.
m. 4./4/5 evaluates to the same as 4./(4/5).
n. 2*J = 3 is a valid replacement statement.
o. The maximum number of characters for a FORTRAN variable name depends on
the particular system,
p. Depending on the integer values I and J and the real variable C , I*J*C ^ I*C*J .

q. K = -(K) is a valid statement,


r. In describing the output format Fw.^ for a real number, the value d should always
be less than or equal to vv.

For A = 3., B = —2., I = 6, and J = 0, evaluate each of the following expressions.

a. A**2 + B b. I+2/3 c. A**B


d. A*3. + B*4 e. A/B f. A/B*3 + A
g. A/B/2 h. A/B + 2. i. J/I

J. I/J k. A**I I. (A + I)/B


m. A**2**3 n. B**b7 o. J**B

9. What value will be stored in X or IX by each of the following statements, assuming


that A = 3.2, B = -2., I = 6, and J = 0?

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
; ' :

64 INTRODUCTION TO FORTRAN — PART 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:

a. A = 743.25 F10.3 d. A = 328.74 F5.2


b. A = -643.281 F7.2 e. A = .37 F5.2
c. A = -4768.6 F6.0

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 WRITE(6,11)I,J,K


'-
11 F0RMAT(T8,I4,3X,I1. 15

c. XXX = 4. 3257 ABC = 19.2


YYY = -.0007 IJ3 = 4
ZZZ = XXX + YYY WRITE (6. 13) ABC, IJ3
WRITE 6 12 XXX YYY ZZZ
( , ) , , 13 FORMAT (2X, 14, 3X.F6.0
12 F0RMAT(T4,F7.3,F7.3,F7.3:
e. I =.8 1 = 11
J= .6 WRITE(6,12)I
Z= I+J 12 FORMAT (12)
WRITE(6,11)Z WRITE (6, 13)
11 F0RMAT(1X,F2.0. 'I2,F4.1' 13 FORMAT( '1' ,
'1' .

'ALL'

2-7-2 Programming Exercises


1. The lowest temperature ever recorded in the Antarctic is — 126.9° Fahrenheit. Write a
program to convert this temperature in degrees Centigrade and print the result. The

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.

a. Simple interest / = pn for:

/-= .04
/ = 3
p= 100
INTRODUCTION TO FORTRAN— PART 1 65

b. Volume of a cube V = cMbr c = 3.1672.


c. a circle A = irr^ for r = 6.2.
Area of

d. Volume of a cone v = - wrh for r = 9.\ and h = 4.932.


3

3. Write a program segment to interchange the values contained in memory locations S


and T.

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

8. Write a program to approximate the Julian date (introduced by Julius Caesar in 46


B.C.) equivalent to the calendar date given in the form: month, day. The Julian date is
the day of the year. January has Julian date 1, February 2 has Julian date 33,
1

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:

a. The total principal given by the formula:

=
^ ''
(' ^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

19, Determine whether A= 1.3 is a root of the polynomial:

j.v'^ + 4x'- .76a- - 1145

2-7-3 Answers to Self Test

1. An expression is a part of a statement. An expression should always be to the


right-hand side of the " = " sign. The value of a constant does not change; the value of
a variable may change. Integer data cannot have decimal points; real data always have
decimal points.

2. A source statement is a statement written in a compiler language such as FORTRAN.


Job control cards are cards required for communication with the operating system to
compile and execute program. Execution lime is the time during which the computer
a

is executing the translated program. Compile time is the time during which the com-

puter is translating a program into machine language.

3. a. Real variable. b. Integer variable. c. Invalid variable: too many char-


acters.

d. Invalid variable: contains special character. e. Integer constant,


f. Invalid variable: numeric first character. g. Real variable.
h. Real constant. i. Integer constant.
j. Invalid variable: numeric first character and special characters.
k. Invalid variable: decimal point. I. Invalid constant: imbedded "-."
m. Invalid variable. n. Integer variable. o. Real variable.
p. Integer variable. q. Invalid constant: imbedded " + ."
r. Invalid variable: special character. s. Invalid constant: $ must not be used.
t. Invalid constant: imbedded "<."

4. a. X*(Y-kZ) b. A/B*C c. A/B**5 d. A*X**2 -h B*X -^ C


e. A/(B*S) f. Y**(l./3.) g. 3.14*R**2
h. A/(X + Y) - .5/(X*Z) 2.*(X*Y**(-1)) j. -X**2 i.

k. A**{X + Y) +3.5 Y + k**X 1.

m. (Y-Y0)/(Y1-Y0)*(X-X0)/(X1-X0) n. Z- 1 -h l/( ( 2 + 3/( 1 -X) )

0. (-B-h (B*B-4.*A*C)**.5)/(2.*A) p. U**(2*N)


q. ((4.*(X1*X1-kX2*X2-^X3*X3) - (XI +X2 -kX3) **2)/( 3. * ( 3 .
-1 . ) )
)** .

5. a. STOP. b. I through N. c. FORMAT. d. Carriage control.


e. Statement number. f. END. g. Constants. h. Alphanumeric,
i. Variables. j. Expression. k. Sequencing/identification.
1. Statement. m. Job control. n. Object code, source code. o. Fandl.
p. XorT. q. Compilation, execution. r. Truncation of fractional part.

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.

e. F4. is invalid: there must be a digit after the decimal point.


INTRODUCTION TO FORTRAN— PART 1 69

f. The WRITE statement list must not control literal strings.

g. No "." is used after the format statement number.


h. The variable X must be described with a real format code,
i. The WRITE statement list must not contain expressions,

j. Unit 6 and not unit 5 represents the output device.

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.

q. T. r. F; d shoul d be less than \Y-'.


'J< .y yp^'^

8. a. 7. b. 6 c. .111111 d. 1. e. -1.5 f. -1.5


g. -.75 h. 0.5 i. j. error. k. 729.
I. —4.5 m. 6561. n. Error, base is negative. o. undefined.

3. 6. b. 3 c. 4. d. -5 e. .0277778 f. 0. g. 0.

Ii." U i.

10. S = 0. J =0 JK = 1

11. a. 3/4*4. = 0. but(3*4.)/4 = 3. b. 2.*3/4 = 1 .5 but 2.*(3/4) = 0.

12. 2 5 b. - 6 4 2 8
a.
I I I |
7|4|5 |
.

, | | |
|
|,5 ,
,
.

,
,

13. In this exercise the first print position is not shown,


^
a. I I I I
i V l I I I I I I I I l^ l Vl^ l l

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.

e. |Q||I 2|. F-|4|. 1|


| I I
| | I

'• j-in — I
Top of new page.

1 |
A Li L
|
I
Top of new page.V)
1 |
.

3
INTRODUCTION TO
FORTRAN— PART 2

3-1 PROBLEM EXAMPLE


Mr. Loh is paid at a regular rate of $6.50 per hour for the first 40 hours. The overtime rale
for hours in excess of 40 is 1 .5 program to read
times the regular rate. Write a FORTRAN
thenumber of hours worked and compute and print out Mr. Loh's gross pay.
An example of a FORTRAN program to solve this problem is shown in Figure 3-1
New FORTRAN statements used in this program include:

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.

4. The comment statement used to document the program.

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

15 PAY = PAY1 + PAY2

16 GOTO 18
1 1

72 INTRODUCTION TO FORTRAN— PART 2

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.

Control cards ^XTTNPTar Z^


/^
Data cards
Control cards ^/^ JUL
STOP
roi^tiHTa?^
deck source R£hIi<.5.1) M5
KORTRAN '^e^D(5.i)
£hII',S, 1) Ml
m
Contro I cjwfiLg i^.'fHiipRQG (^i»Tgatr
cards JOt BDILLDT BEGIN
1 . .

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

I n !|M '""""."""""""""'"""""" ' ! nn ! ? J ; ! 7 7 7 ; ! J I ! ! m ! ! 7 ! ! ! ?

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

I g g I g i 1 1 1 1 1 g 1 1 1 II 1 1 1 1 1 1 i g I g g g I g I g g g I g g g g g g g g 1 1 1 1 i iiiiiiiiig nil g giiiniiiiig gg

n I ! ) s 1
1
' mm ) ! !
!
" « ) ! ) n ) 1 1 1 J I in 3 s I i I in I ) m ) nnnnnnnnnnnn nn I

Figure 3-2 Physical Job Deck before Compilation.

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 —

Data deck FORTRAN program


reads data cards
sequentially.

Memory
Source deck is no longer
present (has been translated).

Figure 3-3 Physical Job Deck During Execution.

The general form of the READ statement is:

READ {device-number, format-statement-number) variable-list


where device-number is an integer specifying the input device (address of device),
for example card reader, magnetic tape, disk, etc'
format-statement-number is a user-selected statement number describing
the layout of the data on the input record, and
variable-list specifies the names of values to be read from the input medium
(cards); each data item on the input record will be stored in the named memory lo-
cations specified in the variable-list.

If cards are used as input, the input data can be punched anywhere in card columns 1-80.

Example
format number

device number list of variable names

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

3-2-2 The FORMAT Statement


It is apparent that the READ statement all by itself does not provide the computer suffi-

cient information to know the following:

1. How many items there are per card.

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

74 INTRODUCTION TO FORTRAN— PART 2

2. In what card column each data item starts.

3. How many card columns are used for each data item (length of data item).

4. The mode of the data item, integer or real.

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

READ ( 5 , 10 JHRS IRATE .JBONUS


) ,

10 FORMAT 15, 13, 12

data card

The above input operation can be interpreted as follows:


Read three numbers (three variables are named) from a card (device-number 5) ac-
cording to the data layout described by the FORMAT labeled 10. FORMAT 10 can be in-
terpreted as follows: The first number (JHRS) will be an integer number (specified by the I

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

The general form of the FORMAT statement is:

statement-number FORMAT {fd^Jdi fd,,)

where statement-nutnher is the format label referred to in a READ statement;


fd\Jd2, . . .
,fd„ are format codes, which can be either:

1 Data format codes to identify data on the card as either integer or real numbers.

2. Edit codes to control placement or editing of the input record.


INTRODUCTION TO FORTRAN— PART 2 75

Data format codes can be any of the following codes:^

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.

The format code


I

The general form of the I format code is:

In

where I specifies that an integer is to be read, and


w specifies the width of the integer field (number of card columns).

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

Data cards Values in memory


FORTRAN Code
= 213
READ(5,5)I,J,K 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.

The F Format Code

The general form of the F code is:

Fw.d

-Other format codes discussed in later chapters are E, D, and A.


76 INTRODUCTION TO FORTRAN— PART 2

where F specifies thai a real number is to be read


vv (number of card columns),
specifies the field width
d tells the system where to assume the decimal point in the number read into memo-
ry in case no decimal point is punched in the number field.

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

Implied position of the decimal point

READ(5,5)A,B,C
5 FORMAT F5 5 F3 ( . , .
2 F2
, .
INTRODUCTION TO FORTRAN— PART 2 77

Example 2

Decimal point punched on card

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

READ (5.5) ,^K^


5 FORMAT \F;4.2,
( ^1/ 2 .F / 4 . ^i;2)
INTRODUCTION TO FORTRAN— PART 2 79

The X Format Code

The general form of the X format code is:

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

bypassed This procedure or block of code


5 READ(5,10)X is executed repeatedly.

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.

3-2-4 The Logical IF Statement


Recall that the central processing unit (CPU) has a unit to carry out logical operations.
This hardware feature enables the computer to compare numbers and thereby make de-
cisions. The computer's ability to make decisions is probably one of the most powerful
and desirable characteristics of the concept of a stored program. Any computer stripped of
its logical capability would be no more than an extremely fast calculator that could only

process sequential arithmetic and input/output instructions.


The IF statement allows the computer to transfer to a nonsequential instruction in a
program depending on whether or not certain conditions are met. In this way a program
can contain several alternate paths that are data dependent. Certain blocks of FORTRAN
statements may be bypassed in the program as a result of transferring to a nonsequential
instruction.
In Figure 3-1, if NHRS is less than or equal to 40, the block of statements labeled
12-16 will be bypassed, and execution will resume at statement 17. If NHRS is not less

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

The logical IF can be flowcharted as follows:

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.

Logical IF statements Meaning

1 IF(X.EQ.O. )G0T0 5 If X =0, transfer to statement 5;


3 A=4 otherwise process the nexLstatement labeled 3

(meaning X is less than OTgreater:than 0).

4 IF( (X-Y)**2.LT.Z)G0T0 40 If(X - Y)-< Z, process statement 40; otherwise if


8 IF(Z.GT.2)G0T0 60 (X - Y)= > Z, fall through and execute statement 8

5 IF(SQRT(X) .GE.2. ) G0T0 50 If VX> 2, go to 50. If v/X< 2, process the


7 WRITE(6,11)X next sequential statement 7.

2 IF(X + Y.NE. (J-K) )G0T070 If X -h Y = J - K, process statement 6;

6 READ (5, 5) A otherwise go to statement 70.

Figure 3-5 Examples of Logical IF Statements.


82 INTRODUCTION TO FORTRAN— PART 2

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:

If I is even, then 2*(I/2) = 1 For example, if I = 4, then 2*(4/2) = 2*2 =4


If I is odd. then 2*(I/2) 5^ I For example, if I = 5, then 2*(5/2) = 2*2 = 4 ?^ 5

Example I is flowcharted and coded in Figure 3-6.

c
Read a value I from card.

Is I even?

No, print message.

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

If N> 0, write the code POS on the output medium.


If N = 0, ZERO on the output medium.
write the code
If N < 0, write the code NEG on the output medium.

The flowchart and program are shown in Figure 3-7.

c
Read the number.

Is it different from zero? Yes

No.
Write ZERO
and stop.

Yes.
Is it positive?

No, write NEG

and stop.

Yes, write POS

and stop.
84 INTRODUCTION TO FORTRAN— PART 2

As displayed in Figure 3-7, the sequence of FORTRAN instructions parallels exactly


the physical sequence of the flowchart blocks. Note the importance and necessity of the
two GO TO 5 statements after the WRITE(6, ) and WRITE(6,22) instructions.
1 1
1

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?

No; write ZERO

and stop.

Yes; write NEG

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

FQRTR AN_program. When the compiler encounters the


notes the physical en d of the
'E>rD^tatemeht7Trknows there are no more FORTRAN instructions to translate into ma-
chine language. The STOP statement, on the other hand, translated by the FORTRAN is

compiler into a machine-language'^instruction.^jidhLich when processed by the CPU means


that the program has come to its; logical conclusion} that is, the machine instructions cor-
responding to the FORTRAN progranrhave^eerTprocessed and there is nothing more to
do in this program. In essence, the END is processed at compilation time, whereas the
STOP is processed at execution time — two very distinct times during the life of any FOR-
TRAN program.
Another example will help illustrate the use of more than one IF statement in a FOR-
TRAN program.
Example 3

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

4 IF(N1.LT.N3)G0 TO 2 Simpler just to use GO TO 3

2 GO TO 3

3-2-5 The Logical IF Revisited

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

where logical-expression consists of two arithmetic expressions linked together by the


logical operators .LE., .GT., .EQ., etc., and statement is any executable statement except
another IF statement or DO statement (see Chapter 5).
If the condition described by the logical-expression is met (the value of the

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-

ualized as shown as follows:


86 INTRODUCTION TO FORTRAN— PART 2

r START ^

Read three numbers. /read N1,N2,N3/ READ(5,50)N1,N2,N3


50 FORMAT (13, 13, 13)

Is first > second? IF(N1.GE.N2) G0T04

No. IF(N2.LT.N3)G0T0 3
Is second < third?

No, largest is second; LARG = N2

Go write it. GOTO 10

Yes; largest is third; 3 LARG = N3

Go write it. GOTO 10

Yes.
Is first < third?
,^
— 4 IF(N1.LT.N3)G0T03

No; largest is first; LARG = N1

Write largest. 10 WRITE (6, 12) LARG


12 FORMAT (T5, 13)

Stop. STOP
END

Figure 3-9 Largest of Three Numbers.


INTRODUCTION TO FORTRAN— PART 2 87

Yes ANY STATEMENT


IF (logical-expression) statement
EXCEPT IF AND DO

6
Examples

5 IF(A.LT.B)K = K+ 1 IfA < B, the statement


10 IF(A.EQ.4) GOTOl K = K + will be executed. Then
1

statement 10 will be processed. If A


> B, statement 10 is processed next.
8 IF CODE NE
( . . . ) WRITE 6
( ,
1 ) If CODE ?i 0, A will be printed
before terminating.
6 STOP if CODE = 0, the program is termi-
nated.

7
A

88 INTRODUCTION TO FORTRAN— PART 2

(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 the above flowchart were coded as follows:

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

Only one statement is permissible on the same line as the IF statement.

3-2-6 The Arithmetic IF Statement


The arithmetic IF allows for a three-way transfer out of a decision block as opposed to a
two-way transfer for a logical IF. When comparing, for example, two numbers, A and B,
the decision block can reflect three exits, one in case A is less than B, a second one in case
A equals B, and third one in case A is greater than B. The flowchart symbol for an
arithmetic IF is shown as follows:

The colon (:) can be Meaning


interpreted as
"compared to." IfA < B, process slalemen I 11.

If A = B. process slalemenl 2.

If A > B. process slalemenl 34.

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

The general form of the arithmetic decision statement is:

I ¥{expression) statement-number- ,statefnent-number-2,statement-number-3 1

where expression within parentheses is any FORTRAN expression


statement-number-\, 2 and 3 are FORTRAN statement numbers defined in the pro-
gram.

The IF statement can be interpreted as follows:

1. Evaluate the expression.

2. If the result is negative, transfer to statement-number- 1


If the result is equal to zero, transfer to statement-number-2
If the result is positive, transfer to statement-number-3

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

if expression is < if expression = if expression is >


go to statement 1 go to statement 2 go to statement 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

IF(A-B)11,2,34 means if A - B = or if A = B, then go to 2


if A - B > or if A > B, then go to 34

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

Some valid IF statements and their meanings are shown as follows:

IF slalements Meaning

IF(X)1,3,5 IfX <0,goto l;ifX = 0, goto3;ifX >0,goto5.


IF X - -4
( ( ) ) 1 , 1 , 2 These two statements are logically thesame
IF X + 4 1 1 2
( ) , , and could be interpreted as comparing X with —4.
IF X Y*Z 3 4 3
( -I- ) , , If X Y *Z = 0, go to 4; otherwise go to 3
-I-

IF(2*X + (Z- 4)*X**2)1,2,3 Evaluate the expression and transfer to 1,2 or 3


90 INTRODUCTION TO FORTRAN— PART 2

Some invalid IF statements are shown below:

IF statements
INTRODUCTION TO FORTRAN— PART 2 91

In method 1, the sequence of FORTRAN instructions parallels exactly the physical


sequence of the flowchart blocks. This method
probably the easiest for the beginner to
is

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 ^

Read 3 numbers /read N1,N2,N3/ READ(5,50)N1,N2,N3


50 F0RMAT(I3,I3,I3)

is first > second? IF(N1-N2)1,4.4

No. 1 IF(N2-N3)3.2,2
Is second > third?

Yes; largest is second; 2 LARG = N2


go and write it.

GOTO 10

No; largest is third;


VIP 3 LARG = N3
go and write it.

GOTO 10

Yes. 4 IF(N1-N3)3,5,5
Is first > third?

Yes, largest is first. 5 LARG = N1

Write largest. 10 WRITE (6, 12) LARG


12 FORMAT (T5, 13)

Stop. STOP
END

Figure 3-11 Largest of Three Numbers.


INTRODUCTION TO FORTRAN— PART 2

3-2-7 The IF THEN ELSE Statement


In 1977 a new version of FORTRAN (now known as FORTRAN 77) was approved by
the American National Standards Institute. This version of FORTRAN may or may not
exist at the reader's installation. To make use of the material in this section, the reader
should check with his installation to determine whether the FORTRAN 77 compiler is

available on his or her system.


ANSI 1977 FORTRAN provides another way to express the logical/arithmetic IF
statements. This new feature, called the IF THEN ELSE statement, enhances the clarity
and readability of FORTRAN code by reducing the use of the GO TO statements. In
Chapter 12 the role of the IF THEN ELSE in the perspective of structured programming
is discussed in greater depth.
The following diagram illustrates the general form of the IF THEN ELSE structure:
Code Meaning

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

arithmetic IF statements. If the condition is true, statement-1 statement-2, statement-n, . . .

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

94 INifRODUCTION TO FORTRAN — PART 2

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.

IF/ THEN structure Logical IF structure

READ (5,6) HRS RATE , READ (5, 6) HRS, RATE


IF HRS LE 40 THEN
( . . ) IF(HRS.LE.40) GO TO 5
REGPAY = HRS * RATE OVTPAY = HRS - 40 * RATE *
( ) 1 . 5
ELSE WRITE (6, 7) OVTPAY
OVTPAY = HRS - 40 * RATE * ( ) 1 . 5 REGPAY = OVTPAY + 40 * RATE
WRITE (6, 7) OVTPAY GO TO 8
REGPAY = OVTPAY + 40 * RATE 5 REGPAY = HRS * RATE
ENDIF 8 WRITE(6;|) REGPAY
WRITE (6,8) REGPAY
Note the absence of the GO TO statements, which is one characteristic of structured pro-
gramming.

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

If the condition is true, the block of statements, statement-l stateinent-n, is executed . . .

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

BONUS = 1 * SALES . GOTO?


WRITE (6,5) BONUS 8 BONUS = 1 * SALES.

ENDIF WRITE (6,5) BONUS


PAY = HRS * RATE + BONUS 7 PAY = HRS * RATE + BONUS
WRITE (6,6) PAY WRITE (6,6) PAY

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.

Nested IF/THEN Structures

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:

Sales Commission (percentage oj sales)

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

IF ( SALES LT 500 THEN


. . )

COM= .02* SALES com = 2% sales


ELSE
IF ( SALES LT 5000 THEN
. . )

COM= .05* SALES com = 5% sales


ELSE
COM= .08* SALES com = 8% sales

ENDIF
ENDIF

9- 9
WRITE (6,5) COM / WRITE com /
96 INTRODUCTION TO FORTRAN— PART 2

Approach 2 The same problem can be visualized as:

IF ( SALES GE 500 THEN


. . )

Yes
IF ( SALES. GE. 5000) THEN

COM = 08 . SALES No com = 8% sales

ELSE
COM = 05 * SALES .
com = y'/c sales
ENDIF
ELSE
COM= .02* SALES

ENDIF
com = 2% sales
o
WRITE (6,5) COM / WRITE com /

In approach 1 the sequence of key words is IF THEN ELSE . . . whereas in approach 2


the sequence is IF THEN IF . . . The first approach is preferable because of its readability.
Approach 2 not recommended because it is difficult to follow.

3-3 You Might Want To Know


1. When a data card is read, does the computer only read those fields specified by the
data format codes in the FORMAT or does it actually read all 80 card columns?

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

READ-list? For instance:

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

in a numeric field; what will happen?

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?

Answer: Blanks are interpreted as zeroes.

7. What happens if I want to read a large number, as follows?

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.

8. How can I read imaginary or complex numbers?

Answer: See Chapter 6 for a complete discussion.

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

Answer: The T feature allows to restart a READ operation at different positions


within a record. In the above case, I = 1 39, J = 398, K = 1

11. Can you have more than one STOP statement in a program?
( ) )

98 INTRODUCTION TO FORTRAN — PART 2

Answer: Yes. For example:

IF(X.GT.O)GOTO 15
16 WRITE(6.12)
STOP
15 WRITE(6,11)
STOP
12 FORMAT 3X, 'X IS NEGATIVE
( '

11 FORMAT 3X, 'X IS POSITIVE'


(

END
Remember, though, you can have only one END statement, and it must be the last

statement in your program.

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-

ments are ignored by the compiler.

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

On many systems .1 may be approximated to .09999999; hence X = .4999999. On the


other hand, Y can be represented exactly as .5; hence, on some systems X may not
equal Y, even though this is the case arithmetically. In such cases the user may want to
ask whether X— Y is close enough to 0, which would mean that X is sufficiently close

to Y. This can be expressed as follows:

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.

15. Suppose I want to print a line full of asterisks: ****. . .


***. What is an easy way I can
do that?

Answer: WRITE(6,5)
'*'
5 FORMAT! IX, 132 )
INTRODUCTION TO FORTRAN— PART 2 99

Note that the format code 132 '*'


would be invalid. A duplication factor may be ap-
plied to any sequence of format codes contained in parentheses. See Section 3-5-4.

16. Can more than one condition be treated in the same logical IF statement?

Answer: Yes. Consider the following examples:

Example 1

To determine if AGE lies between 7 and 14, the following statement can be used:

Flowchart meaning

/ READ AGE /

READ (5,1) AGE


AGE GT 7 AND AGE LT 14 WRITE (6,4
IF ( . . . . . . )

4 FORMAT (IX, 'YES'

The statement IF ( AGE GT 7 AND LT 14 would


. . . . . ) be invalid.

Example 2

To determine if SEX equals 1 , or LIFE equals 10, the following code is used:

READ (5, 3) SEX, LIFE


IF SEX EQ 1 OR LIFE EQ 10 WRITE (6,2
( . . . . . . )

2 FORMAT (IX, 'YES'

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

A more complete discussion of compound logical expressions is found in Chapter 6.


100 INTRODUCTION TO FORTRAN— PART 2

3-4 PROGRAMMING EXAMPLES


3-4-1 Solution of a Quadratic Equation
Let us write a program to determine the roots of the polynomial a.v^ + b.v + c. The three
constants and c will be read at execution time.
a, b,

If there are no real roots, print the message NO REAL ROOTS


If the roots are equal, print the message BOTH ROOTS ARE EQUAL TO _
If the roots are unequal, print the message ROOTl = R00T2 =
Recall that the formula to compute the roots of a quadratic equation is:

_ - b + \/b^ - 4ac - b - \/b- - 4ac


X, = X. =
2a 2a

This program to solve this problem is shown in Figure 3-12.

3-4-2 Compound Interest Problem


Write a program to read an interest rate (R), a principal and a number of years (N). If
(P),
the principal and earned interest are left in the account, compute the total value of the in-
vestment after N years. The formula to calculate the total amount is A = P(l R)"". Both
-I-

input and output can be visualized as follows:

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

Read coefficients. /rEAD A,B,C / READ(5,10)A,B,C


10 F0RMAT(F5.1,F5.2,F5.3;

Compute discriminant. D = B^ - 4AC D= B*B-4.*A*C

See if discriminant Yes IF(D.LT.O. )G0T0 75


is negative.

No. Xl= (-B + D**.5)/{2.*A)


Compute a root.

Are roots unequal? IF(D.EQ.O. ) G0T0 65

Yes. X2= (-B-D**.5)/(2.*A)


Compute other root X2 =
and

print both roots WRITE XI, X2 WRITE(6,11)X1,X2


and
L 7
go and stop. GO TO 80

No. WRITE XI 65 WRITE (6, 12) XI


Print equal roots L 1
and
go and stop. GO TO 80

75 WRITE (6, 13)


13 FORMAT (T5. 'NO REAL ROOTS'
Yes.
I
WRITE"NO / 11 FORMAT T5, 'R00T1=' ,F8.
(

Print roots not real. / REAL ROQTS^y *'R00T2=' ,F8.2)


12 FORMAT T5( BOTH ROOTS
,
' '
,

* '
ARE EQUAL TO F8 2 '
, .

Stop. ( STOP ) 80 STOP


END

Figure 3-12 Solution of a Quadratic Equation.


102 INTRODUCTION TO FORTRAN— PART 2

3-5 MORE FORTRAN STATEMENTS


3-5-1 The Comment Statement
Sometimes when a program gets to be lengthy the programmer may find it helpful to ex-
plain within the program the purpose of one or more FORTRAN instructions, the usage
of a particular variable, or the function of specific program segments. The practice of in-
terspersing comment cards throughout the program can be very helpful when the pro-
grammer at a later date decides to review or make revisions to some parts of the program.
Comment cards can help the programmer recapture the essence of some of his or her ori-
ginal thoughts. Also, comment cards will help another user who wishes to use the program
understand the overall program structure.
Comment cards can be inserted anywhere in a program by punching a C in card col-
umn When the compiler reads the C in card col urn nj., it realizes that the information on
1 .

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

on the ouput device with all other FORTRAN instruc-


the content of that card to be listed
tions. As an example see Figure 3-14. Note the two blank lines in the listing after the head-
ing. Blank cards inserted in a program are translated into blank lines on the program list-
ing.

QUADRATIC EQUATION

READ (5, 10) A,B,C rr ROOTS ARE EQUAL


COMPUTE DISCRIMINANT
D = B*B-4.*A»C
IF(D.LT.O) GO TO 75 X2 =
Xl= (-B + D**.5)/(2.*A) ROOTS ARE UNEQUAL
DETERMINE IF ROOTS ARE EQUAL IF(D.EQ.O) GO TO 65
IF (D.EQ.O) G0T0 65 DETERMINE IF ROOTS ARE EQUAL
ROOTS ARE UNEQUAL XI =
X2= (-B-D**.5)/(2.*A) r. IF(D.LT.O) GO TO 75
LCOMPUTE
D = B*B-4.*A*C

ROOTS ARE EQUAL

STOP
A C DISCRIMINANT
READ(5,10)A,B.C

END QUADRATIC EQUATION

Figure 3-14 Use of the Comment Card.

3-5-2 Annotation Block


The annotation block is used to indicate a remark or a comment in a

flowchart. The annotation block is placed to the right of flowchart blocks as follows:

The variable sum will

accumulate the sum


SUM =

The variable grade


will store each grade
/ READ grade/
INTRODUCTION TO FORTRAN— PART 2 103

The broken line indicates the placement of the remark in the program. The FORTRAN
code for the above flowchart would appear as:

C THE VARIABLE SUM WILL ACCUMULATE THE SUM


SUM =
C THE VARIABLE GRADE WILL STORE EACH GRADE
READ(5,10)GRADE

3-5-3 The Computed GO TO Statement


A useful and convenient statement that transfers to different points in a program with just
one FORTRAN statement is the computed GO TO. The general form of the computed
GO TO is:

GO TO {statement-number-\ , statement-number-2, statement-number-n)^ variable

where jw/g^/gjTuist_be an integeryarmbie name ajid statement-nuniber-\ ,2, • • • n are FOR-


TRAN statement numbers^[e!med in the program.
If the value of the integer variable is 1, control is transferred to statement-number-1.
If the value of the integer variable is 2, control is transferred to statement-number-2. In
general, if the value of the variable is /, control is passed to the /'
statement in the list of
statements. For example:

GO TO (3, 57, 100, 4 ),N If


) )) )

104 INTRODUCTION TO FORTRAN— PART 2

READ (5,6) KODE If KODE is not equal to 1,2,3,4, or


GOTO (15,20,25,30,35) ,KODE 5, then go to the next statement and
WRITE(6,100)K0DE print an error message.
100 FORMAT (3X, 'INVALID CODE' ,13
STOP
15 WRITE(6,101)
101 FORMAT 3X FRESHMAN
,

( ' '

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

3-5-4 The Duplication Factor


Many times a sequence of variables is read, each having the same format code description.

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

equivalent to statement 101 above:

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:

n Fw'd and n I H'

where n is the optional duplication factor; n must be an unsigned integer.

Example
FORTRAN code Data card Value stored in memory
I =0
READ (5,5)I,J,K,L,M |

J = 10
K = 9

FORMAT (212, II, 212 L = 22


5
M = 33
INTRODUCTION TO FORTRAN— PART 2 105

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

The following two statements are equivalent:

I card column 6

101 F0RMAT(3X, 'AREALOTl IS' ,2X,F8.1,3X, 'AREAL0T2IS' ,2X,F8.1


101 FORMAT 3X AREA LOTl IS 2X F8 1
( ,
'
' , , .

3X AREA L0T2 IS
,
'
2X F8 1 ' , , .

A statement can be continued onto several successive lines.

Example

The following statements 100 and 101 are equivalent.

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

This example will produce: 3 blanks

. I DREAM OF THINGS THAT- - - - -NEVER WERE


)

106 INTRODUCTION TO FORTRAN— PART 2

If the following statement had been used,


[—card column 72

11 FORMAT ( . . .,' I DREAM OF THINGS THAT NE


*VERWERE' )

the following output would be produced:

I DREAM OF THINGS THAT NEVER WERE

3-6 EXERCISES
3-6-1 Self Test

1, Which of the following coding segments are valid? If invalid, state reasons.

a. READ(5,10) ;A,B,C b. READ(5,5)I,J


10 F0RMAT(F1.0,F2.0,F3.0) 5 FORMAT( II , 14)

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?

5 FORMAT (Tl, II, II, II) (a)

5 FORMAT (T2, IX, II, IX, 12, 15) (b)


READ ( 5, 5) I, J, K 5 FORMAT( 13 II ,T6 II
, , (c)

r Card column 1 of data card 5 FORMAT 14 13 15


( , , )
(d)

V, .,^, .,_, ,,,,,,_ 5 FORMAT (T8, II, 14, II) (e)


|1|3| |5|.|2| I I
|-|4|6|7|.|1|9| | 5 FORMAT( 12 Tl II T2 14;
, , , . (0
5 F0RMAT(2(1X,I1) ,T10,I3) (g)

3. You are to punch an input data file on cards with three fields per card.

FLDI FLD2 FLD3

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)

|1|. |3| |2|5|.|1|. |5| I I


5 FORMAT (T2,F1.1, 12, F2.0) (e)

5. Simulate the output produced by the following program segments on the printout list-

ing and indicate all print positions and blanks.

a. READ(5,10)A,J,X,Z n a
)/— <^^^^ <^Q'""^" ^^ data card
^

10 FORMAT IX F3 2 T6 13 F4 2 F3
( , , , , ,
'

WRITE(5,11)X,A,J,Z ||3|4|3|1| |2| |.|5|6| |2|l| |

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

6. Are the following statements true or false?


a. Only one STOP statement is allowed per program.
b. Card column of a data card is reserved for card control.
1

c. A C in card column 6 indicates a continuation from the preceding card.


d. Data cannot be punched in card columns 73-80 of a data card.
e. Data cards are read at compilation time.
f. FORMATS must immediately follow the READ instruction.
g. FORMATS are not required to have statement numbers.
h. The same FORMAT can be used for a READ and WRITE instruction.
i. A C in card column will cause a compilation error. I

j. FORMATS are nonexecutable statements.


k. Running out of data cards will cause a compilation error.
1. The statement 5 GOT05 is grammatically incorrect.
m. The statement READ(5, 10)J,J,J is invalid.
n. The statement GO TO KODE3 is valid.
o. In a READ operation, either FORMAT(T2,. . .), or FORMAT(2X,. . .) will cause
reading to start at the same card column,
p. Data cards can immediately follow the READ statement within the FORTRAN
program deck.

7. What are some execution time errors you could expect as a result of a READ instruc-
tion? A WRITE instruction?

8. Write IF statements for the following flowchart blocks.


108 INTRODUCTION TO FORTRAN — PART 2

(a)

(C) (d)

(e) (0
(e)

(S) (g) < -^ -^^^

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

14. Write the necessary IF statements to perform the following:

a. If X is greater than but less than 3*A, go to 7.

b. If both A and B lie between 1 and 8 inclusively, go to 8; otherwise go to 4.


c. If X exceeds 4 while Y is less than 5, or if X is less than 5 while Y is greater than 4,
go to 10; otherwise stop.

15. Discuss the following code segment in terms of possible errors:

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?

X = l./3. +1./3. +1./3.


IF(X.EQ.l) GO TO 15
WRITE(6,5)X
5 FORMAT (F4. 2)
INTRODUCTION TO FORTRAN— PART 2 111

3-6-2 Programming Problems

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:

NUMBER 1 NUMBER 2 DIFFERENCE


5 2.5 2.5
2. The metric system is upon us! Some simple approximation rules for metric con-
versions are listed as follows:

a. Fahrenheit to Celsius: Take half and subtract 15.

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.

3. Write a program to read a value for X and compute X% X\ \/^and v^^


4. Final grades in a course are determined by adding scores obtained on three tests Tl,
T2, T3. Students get a PASS if the sum of the three scores in 186 or more and a FAIL
otherwise. Write a program to read three scores from one data card and determine the
final letter grade. Print the input scores, the average, and the final letter grade.

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:

ACCT NUMBER XXXX AVERAGE = YYY Y


: .

Note blank line.


TESTS aaa aaa aaa

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

the unpaid amount. Print that amount.


112 INTRODUCTION TO FORTRAN— PART 2

8. A salesperson is assigned a commission on the following basis:

Sale Commission

$.00 to $1,000 2.5%


$1,001 to $5,000 6.0
over $5,000 10.5

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.

Grades Letter Grade


0-60 F
61-70 D
71-80 C
81-90 B
91-100 A
13. Write a program to calculate the area of a right triangle, given the lengths of the three
sides.Each data card will contain three integers: the length of the hypotenuse in col-
umns 1-10, the first leg in columns 1 1-20, and the second leg in columns 21-30. As-
sume that the last data card will have a zero in the hypotenuse field.

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

Write a program to make the decision for John Doe.

18. A certain metal is graded according to the results of three tests. These tests determine
whether the metal satisfies the following specifications:

a. Carbon content is below 0.67.

b. Rockwell hardness is no less than 50.


c. Tensile strength is greater than 70,000 psi.

The metal is graded if it passes all three tests, 9 if it passes tests


1 and 2. It is graded 1

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

19. The FHA insures


follows:
$25,000.
a. Three percent of the amount up to
b. Ten percent of the next $10,000.
c. Twenty percent of the remainder.
security number and the mortgage
amount^ The
The input a card containing a social
is
social security number and the
amount of down
output should contam the applicant's
over $60,000 and so md.cate on the output.
payment required. Reject any application
and 100. Write a program to break down that
20 Read an amount in cents between penn.es as possible.
quarters, dimes, nickels, and .s
Amount into the fewest number of
For example:

76 cents = 3 quarters and 1 penny.

according to the fol-


Company charges customers for electricity
21. The Wastenot Utility

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

the new meter readings, and


calculate
Write program to accept as input the old and
a

the amount of the customer's


bill.

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-
,
'/:

TRAN as XNEW = .5*(X0LD + A/XOLD). Starting with an initial approximation,


XOLD = 1, a new approximation, XNEW, to the square root of A is computed using
the above formula. This new approximation, in turn, can be refined by substituting
XOLD by XNEW to compute a newer approximation, XNEW. This process can be
continued until the square of the new approximation is close to A within a XNEW
prescribed degree of accuracy, t (where e = .1, .01, .001, etc., depending on the ac-
curacy needed); that is,

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:

2.56a- .0341= -.56


, . -,^' -^ -,^. and set e = .0
3.14.V + 4.32i' = ^0.76
, ,
116 INTRODUCTION TO FORTRAN— PART 2

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:

a. 7.Y + 2v - 3r =1 10.Y + 3r + 2r- w = -1.5


v - 5y -Iz =6 x-5y^ + vv = 3
--

-A- + V + 2 =8 5a: + 5>'- lOr = 4.1

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)

root lies in the interval [XPOS,XNEG]

>X

P(XNEG)<0 -

Midpoint of interval [XPOS,XNEG]

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;

mathematically speaking, this means P(X) < where | |


( t is a prescribed degree of ac-

curacy.

Using the method described, compute a root of y = x' - 2x- + x - 16 in the interval

[3,4]. Start with XPOS


= 4 and XNEG = 3 and stop when = .1; ( i.e., |P(X)| < .1.
INTRODUCTION TO FORTRAN— PART 2 117

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)

Write a program to produce an output similar to:

student ID
118 INTRODUCTION TO FORTRAN— PART 2

3-6-3 Answers to Self Test

1. a. Invalid. b. Valid. c. Invalid d. Invalid. e. Invalid. f. Valid.

2. a. 1,3,0 b. 0, invalid data in field, -4 c. 130,5,2


d. 1305, invalid data, -46 e. 0, -46, 7 f. 13, 1 . invalid data

g. 3, 5,-46

3. a.
INTRODUCTION TO FORTRAN— PART 2 119

9. a. Case I : R = 2. Case 2: R = 1 b. Case 1 : 3 is written.


Case 2: —4 is written.
c. Case 1: 3 is written. Case 2: 4 is written. d. Case 1: STOP.
Case 2: is written.
e. Case 1 : 2 and 3 are written. Case 2: I and —4 are written.

10. a. IF(I.EO.N) b. X.EQ. 2 not a statement. c. Missing parenthesis.


d. Missing relational operator. e. Missing right parenthesis.
f. Infinite loop if 17 < B. g. Comma illegal,

h. Missing parentheses and comma


illegal. i. Illegal END.
j. IF in YES branch is illegal. k. Only one statement allowed in

YES branch.

11. a. 4 READ(5,6)A,B.C b. IF(B.GE.60)C = C + 1


IF(C**2.EQ.A*A+B*B)WRITE(6,7)A,B,C GO TO 4
GO TO 4

c. IF(X.GT.MAX)MAX = X d. IF(B*B-4 •A*C.LT.0)G0T06


e. IF(HRS-40)1,2,3 R=2
3 W = 1.2*R*H GO TO 5
GO TO 6 6 R=l
2 W = 1.05*R*H 5
GO TO 6
1 W = R*H
6 WRITE(6,5)W

12. a. 1 ifZ < L 2ifZ> 1. b. 1 ifZ > .2, 2ifZ = .2, 3ifZ < .2.

c. 1 ifZ5^ -7, 2ifZ = -7. d. 1 ifO<Z < 1, 2ifZ = orZ = 1 0,


3 ifZ > 1 orZ <0.
e. 1 for all values of Z. f. 3ifZ>— 1, 2 otherwise.
g- 2 for all values of Z.

13. a. IF(X.NE.1)G0T05 or IF(X-1. )5.3,5


IF(Y.GT. -1)G0T06 3 IF(Y + 1. )5,5,6
GO TO 5
IF (X.EQ 2) GO TO 6 or IF(X-2)3,6,4
IF(X.LT 2) GO TO 3 3 IF(Z + 1)5,6.6
IF(T.EQ.X)GOTO 5 4 IF(T-X)6,5,6
GO TO 6
IF(Z.LT 1)G0T05
GO TO 6
14. a IF(X.LE.0)G0T05 or
IF(X.LT.3*A)G0T07

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

120 INTRODUCTION TO FORTRAN— PART 2

c. IF(X.GT.4)G0T0 1 or IF(X - 4) 12 12 , .

IF(X.LT.5)G0T02 12 IF(X - 5)2 11 11


, ,

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

4-1 PROBLEM EXAMPLE


A poll was conducted in a political science class to determine students' feelings about
isolationism. The code used to record students' opinions was as follows:

Code Meaning
;

122 THE COUNTING PROCESS

INTEGER CODE r START


^

DATA 1/0/ I = I IS used lo counl number


of proisolalionisl
students.

10 READ (5,1) CODE /read CODl/ Read a eode.


1 FORMAT! II)

17 IF(C0DE.EQ.9)G0T04 Is it the last one?

WRITE (6, 2) CODE Yes: go and \Nrite out


2 FORMAT (2X, ID lota! of proisolationists.

20 IF(C0DE.NE.2)G0T0 10 No; vvrite out the code and


determine whether it is

an isolationist response.

1 = 1 + 1 Is It? Yes; counl it.

GOTO 10 No; read more cards.

4 WRITE(6,5)I / WRITE 1 / W rile out number of


proisolationist students.

STOP STOP
(^ J
5 FORMAT IX ( , THE NUMBER OF PROISOLATIONIST STUDENTS IS '

, 2X 14
,

END

Figure 4-1 Program Using Counting and Pnd-ol'-Pile Checking.

4-2 FORTRAN STATEMENTS


4-2-1 Specification Statements

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

4-2-2 Explicit Mode Specification


The mode of a variable is implicitly defined by the first character of the name of the vari-
able. If the first character is I, J, K, L, M, or N, the variable is normally in integer mode
(represents a number without a decimal point); otherwise, it is in real mode. It is possible
to explicitly define (change) the mode of a variable by using a specification statement IN-
TEGER or REAL. The general form of these statements is:

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.

4-2-3 The DATA Statement


The DATA statement can be used to specify an initial value for a variable. The general
form of the DATA statement is:

DATA variable-list / constant-list /[, . . .

where variable-list is a list of variables separated by commas, and


constant-list is a list of constants separated by commas.

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

DATA A B/3 .2,0./


, The value of A will be 3.2 and the value of B will be 0.

There must be the same number of variables as constants in the associated lists.

Example

The following DATA statement is invalid:

DATA A,J,K/3.2,4/ Only two constants.


124 THE COUNTING PROCESS

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

DATAC0DE,LL/0,3.2/ Mismatch of modes.

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

The value of A will be 3., B will be 0., I will be 1, and J will be 0.

DATA statements must be placed after other specification statements.

Example

INTEGER A
REAL I
DATA A, 1/1,-3. 2/

A is an integer variable with value 1; I is a real variable with value —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:

> J ' Repetition factors.

DATA I , J , K/3\0/ A B , , , C D/4*J


, -4 .
1 ) /
» ^ in this context,
the * means repetition,
not multiplication.

It is important to remember that the DATA statement is a non-executable statement, that


is, the values specified by the DA TA statement are initialized during the compilation proc-
ess. The DATA statement cannot be used during execution time to set or reset variables to
particular values. Consider the following example:

5 C = Before the program is executed, the values of R and


DATA R F/3, . . 2 /
. F are 3. and 2., respectively. The DATA statement
• will not be carried out during execution time
• and hence cannot be used to reset variables R and F to 3
R=X+ 1 and 2 if R and F have been changed somewhere in the pro-
• gram. Only a replacement statement can reset R and F to 3
• and 2.
IF (C.LT.3) G0T0 5
THE COUNTING PROCESS 125

4-2-4 Counting

Counting is an essential technique in programming. Counting can be used to read a speci-


fied number of data records from a file, to repeat a certain procedure a number of times
(loop control), to count the occurrence of specific events, or to generate sequences of num-
bers for computational uses. In any event, the and there- computer cannot count by itself,

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,

the value that was previously stored in I.


Note that in the problem example of Section 4-1, the statement = + is bypassed I I 1

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 .

4-2-5 Loop Control

An important application of counting is loop control. Loop control allows the programmer

to repeat a procedure (task) a predetermined number of times by making use of a counter


to keep track of the number of times the procedure is being carried out (loop). Exiting
from the loop is achieved when the counter has reached the designated value. Consider,
for example, the following problem: Ia data file contains six grades (one grade per card).
Write a program to read these six grades and print those greater than 90. Also print the
number of occurrences of grades over 90. I

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 =

Set up counter for cards. 1


=

Read a grade. /read grade/

Increment card counter by

Is grade > 90?

Yes. Add I to the coun-


ter that counts grade
over 90 and print
that grade. / WRITE 7
/ GRADE /

No. Is it the last card


(i.e., the sixth card)?

If this was the last card,


print number of grades
over 90.
THE COUNTING PROCESS 127

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.

Q START INTEGER C90


J

C90 =
Set up card count for
six cards to read.
J = 6

Read a grade. /rEADGRADe/

One less card to read.

is grade > 90?

Yes. Count it and C90 = C90 + 1

write it.

Have we read 6 cards?


128 THE COUNTING PROCESS

4-2-6 Number Generation


Another important application of counting number generation. For example, to gener-
is

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

Set number generator to 0. I = 1 =

Increment counter. 1 = 1 + 1 10 1 = 1 + 1

Perform multiplication. J = 12*1 J = 12*1

Perform addition. K = 12 + I K= 12+ I

Write out tables. / WRITE 1,J,1.k


/ WRITE(6,1)I,J,I,K
'

1 F0RMAT(2X, '12XM3, = ' M4,3X


*'12+' ,13, '=' ,14)
Yes " "
Complete up to 10? IF(I,LT.10)G0T0 10

Q STOP ") STOP


END

Figure 4-6 Addition and Multiplication Table for 12.

4-2-7 End-of-Flie Check


As noted in computers can read from a variety of devices or mediums: punched
Chapter 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

hence describes many characteristics of an entity. An employee record might consist of a


social security number field, a name and address field, etc., all punched on one card. A file
is a collection of related records.
When reading a file it is important that no attempt be made to read more records than
are present in the file. The problem of end of file arises when the computer is programmed
THE COUNTING PROCESS 129

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.

Automatic End of File

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

/ READ ZeNDOFFIL E(EOF) I

/ RECORD/

PERFORM
PROCESS END OF FILE
RECORD PROCESSING

Q STOP

Figure 4-7 Automatic End-of-Fiie Processing.

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

Consider the following problem example: A deck of cards contains an unknown


number of program to compute and print
cards, each containing a person's age. Write a
the occurrence of age above N, where N is an age punched on the very first card of the
data deck. A program to solve this problem is whown in Figure 4-8. Note that if the data
card containing the age had been left out of the program deck, an error message would be
printed out.
J '

130 THE COUNTING PROCESS

Q STARTJ INTEGER AGE COUNT ,

EOF
Read key age. If no data / RHAD N /- READ (5, LEND = 40 IN
cards, write error message. 1 FORMAT! 13)

Initialize count. COUNT = COUNT =

HOI
Read ages; when finished, / RHAD AG H / 13 READ (5,1 .END =33) AGE
print age count.

Is age > key age? IF AGE GT hU COUNT,= COUNT +


( . . 1

No; read more cards.


fA'P /f^
Yes; count occurrence. COUNT =
COUNT + 1

GOTO 13

Write count over N. /WR ITH COUNT 7 33 WRITE(6.11)C0UNT


11 F0RMAT(T10.I4)

r STOP
J STOP

In case there are no / WRITH 7 40 WRITE (6. 5)


data cards. / "HRROR". / 5 FORMAT IX ERROR NO DATA
/ "NODATA" /
( , •

r STOP STOP
END

Kijjure 4-8 Automatic Hnd of File.

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.

Last-Card Code Method

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

Last-card code 99.


The
Note the zero value ^^^
T^ 99 :a1
rest of the card is blank.

for all data fields on


the last card.
/ail222311 66 2 A LCC is zefo for all data
cards except last one.
\

social security age sex 1 = male


2 = female

Figure 4-9(a) Last-Card Code End-of-File Check.


132 THE COUNTING PROCESS

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

C is used lo count all cards. C = C =

NTY is count of males over 90. NT\' = NTY =

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

No: count the card. C = C + 1

Yes
IF AGE. LT. 90 GO TO 3
( I

Yes
IF(S.NE.1)G0T03

Male over 90. Count


and write social security NTY = NTY + NTY = NTY + 1

number.

/ WRITESS / WRITE(6,4)SS
4 FORMAT (5X, 19)
GO TO 3

Yes: compute percentage. P = (100*NTY)/C 6 P= (100*NTY)/C

/
^
WRIT! P 7
'
WRITE(6,7)P
'

7 FORMAT (12X,F6. 2:

STOP
(ZEiiD END

Figure 4-9(b) Last-Card Code Program.


THE COUNTING PROCESS 133

4-2-8 Models of Programs Using Data Cards


There are many different ways to write a program or a flowchart to solve a particular
problem. The beginning programmer may be bewildered by the numerous possibilities and
may not know where and how to start. An attempt is made in the following paragraphs to
suggest a successful approach to solve a problem that requires reading and processing data
cards. Almost all of the problems that you will be asked to solve initially will fit into one of
the following categories.

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.

1 . Initialize needed counters and variables.


Can use the DATA statement. I =
I is used as the card count.

I
READ 7
Read the data off the card. Read card.
/ A,B ,F /

3. Increment the card counter. Count card.

4. Process the data on the card


(count, print, add, make decision, etc.).

> Process data on card.

5. Test to determine whether last card read


is really the last. Go back to read on Test for end of data.
the condition less than.

6. If it is last card, complete last chores; i.e.,


End-of-file chores.
print results, compute percentage, etc.

Figure 4-10 Counting Data Cards.


134 THE COUNTING PROCESS

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.

3. Test if this is the last card. Test for last card.

4. Process the data and then go back Process data.


to read more cards.

5. Print results and perform general Hnd-of-file

end-of-file operations. operations.

Figure 4-1 1 Last-Card Code Method.


THE COUNTING PROCESS 135

Case 3. You are to process an unknown number of cards using the automatic end of file.

(See Figure 4- 2.) 1

( )

1. Initialize needed counter and variables Initiali


\
for program.

I READ 7 EOF
2. Read the data. / (END=I5) /-^ Read data.

3. Process the data and go back to


Process data.
read more cards.

4. Print results and perform general


G^H End-of-file
cleanup functions. processing.

( )

Figure 4-12 Automatic End of File.

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

4-2-9 The Slash(/) Format Code


FORMAT statements written thus far have described one physical input or output record,
i.e., one punched card or one line of print. By using the control format code "/" it is possi-
ble to describe more than one input or output record with one FORMAT statement. The /
format code may be interpreted to mean "end of physical record;'' it is used to separate
lists of format codes describing different physical records. No comma is required between

the / and other format codes, although a comma may be used.


)

136 THE COUNTING PROCESS

Q START ^

1. Initialize needed counters and variables


Initialize.
for the program.

2. Read the data. / READ A. B... / Read data.

3. Test to see if it is the last card, a is

a value chosen outside the known Test for trip record.


range of A.

4. Process data and read more cards. > Process data.

5. Print results and perform end-of-


End-of-file processing.
file routines.

Figure 4-13 Model for Trip-Record Processing.

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

The + ' '


carriage control code can be very useful..for, undjrH^^^ To underline a
particular heading we can use the following code:

WRITE (6, 5)
5 FORMAT (T50, 'JULY REPORT '/'+' ,T50 11 , 't '
)

underline graphic symbol

This will produce the following output:

JULY REPORT

Example 3
READ (5,3)A,B, I,J,X
3 F0RMAT(F4.1/F4.0,I2/I2,F5.0)

/ ' / Value stored in

memory
A = 1.3

B = 2.1
I
= 11
J = 39
X = 5.6

The READ list from three records. The value for


specifies that five variables are to be read
A is taken from the means
first
/ data card. The
"end of this record; select a new record
and continue processing at the beginning of the new record;" hence the values for B and I

are captured from the second card, while those for J and X are taken from the third data
card.
B

138 THE COUNTING PROCESS

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

Fnd of first record: go to the next card.

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

End first record: start of second line.


End second record; start of third hne

End third record: start of fourth line


on which 2X,F4.0 is to be processed.
THE COUNTING PROCESS 139

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

4-3 You Might Want To Know


I don't understand the difference between a nonexecutable statement and an executable
statement.
s Can you help?

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:

a. Data cards were included in the job.


b. The check for last record is in the logically correct place (it should immediately fol-

low a READ statement).


c. The end-of-file item (code) on the last card is punched correctly and in the card col-
umns specified in the FORMAT.
d. The FORMAT describing the data record is correct.

4. Yesterday I wrote a program with ten data cards and the computer only read the first

five. What happened?


Answer: Since it read five cards, you instructed it to read only the first five cards, at
which time the STOP instruction was encountered in your program. Check the logic of
the program. What the computer does with the five remaining cards in the card reader
that were unprocessed by your program will vary among systems. The cards expected
by the system after your data cards are someone else's job control cards, not your data
cards with just numbers on them. Eventually, the excess data cards will be fiushed out
by the system.
THE COUNTING PROCESS 141

5. If a DATA statement can be replaced by a replacement statement, why use the DATA
statement?

Answer: A primary reason is programmer convenience. A great many variables can be


initialized in one DATA statement that otherwise would require many replacement
statements. Another reason might be that of saving time during the execution of a pro-
gram. The DATA statement is interpreted by the compiler once to accomplish the in-
itialization; replacement statements must be repeated each time the same program is
executed. This time-saving would apply if the program were to be run a number of
times and not recompiled each time.

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

could be initialized to 15 and then compared to 25 for loop-exiting purposes.

4-4 PROGRAMMING EXAMPLES


4-4-1 Computing a Percentage of Passing Grades
A deck of cards consists of several packets of data decks, each containing grades obtained
by different class sections of an Introduction to Business course. Each packet is identified
by a header card specifying the section number and the number of grades for the particular
section. One student grade (0-100) is punched per card. No section is expected to contain
more than 100 students. Write a complete program to determine the percentage of passing
grades for each section (passing grades are grades over 60). Provide a listing of grades by
section number on different pages with appropriate headings. Both input and output can
be visualized as follows:
Blank lines

SECTION 102
GRADES
90
80
73

PASSING grade's = XXX


RASSINGP;E_RCENTAGE = XXX_-
2L

SECTION 103

Packet 1
GRADES
22
(33 grades)
32
ccl-3
10

Number of grades Section number PASSING GRADES = XXX


in packet that follows cclO-12 PASSING PERCENTAGE = XXX X -

(card columns 5-7)


-Output—
)

142 THE COUNTING PROCESS

The program to solve this problem is shown in Figure 4-14.

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.

I is used to count cards 1 = 1 =


in each packet.

Read number ofgrades in /READ N.SECTy READ (5, 5 )N, SECT


packet and section number.

Is this the last card?


5 F0RMAT(T5,I3,T10,I3)
Yes; stop. *^ STQP"^ IF(N.LT.OlSTOP
No; write section.
WRITE (6, 6) SECT

Read a grade. 10 READ(5,7)GR


7 FORMAT! 13)
Count it. 1 = 1 + 1

Write it. WRITE(6,8)GR


8 FORMAT (T55, 13)

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

FORMAT /T45 PASSING GRADES^ 13


/T50

.
I

'
.

' SECTION ' .


14//

'

/T45 PASSING PERCENTAGE= F5 1


.

' ' . .

END
Figure 4-14 Computing Percentage of Passmg Cjrades.
THE COUNTING PROCESS 143

4-4-2 Short-Term Interest


The formula to compute a simple interest INTDUE on a loan of L dollars at an interest
rate R for T days is given by:

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.

4-5 PROBING DEEPER .


'A

4-5-1 The IMPLICIT Statement ^ '-^

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:

\MPUC\T type [ala] • •


)[jype(ala] •)]

where type can be INTEGER, REAL, or other mode type,


a can be a single letter or a range of letters denoted by I i
— l:, and /, and /: are sin-
gle letters of the alphabet.

Examples

IMPLICIT INTEGER A C-F REAL I-N


( , ) , (

IMPLICIT REAL (C) INTEGER (A,B),

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

144 THE COUNTING PROCESS

START
C 3
Write out headings. WRITE-LOAN"
f"RATE".'"MONTHS".i
"INTEREST DUE-

Count number of months.

Get ready to compute T = 30


the interest due for the
first 30 days.

Read loan and interest


I
READ
rate.

Compute interest due. INTDUE = L*R*T 360

Write out result.


I WRITE L.R. 7
/ T, INTDUE
I

Increment month by I.

Add 30 to days.

Is this 3th month?


1

No; compute more


interests.
Yes; stop.

LOAN RATE
1000.
THE COUNTING PROCESS 145

4-6 FLOWCHART ASSISTANCE


4-6-1 Search for Largest Grade
Each record of a set of records contains a grade (0-100). It is not known how many re-

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

/ RtADMAX / Set Maximum grade to rade


first gFc read.
1

Assume one grade at least.

/ RKADCiRADt / Read another gradc

i| Have we run out of grades?

IS MAX larger than the grade just read?


If the grade just read is larger than MAX,
then store the grade read into MAX; i.e., replace
MAX by the current largest grade;
go back and read more cards.

/ \\RiT[ MAX / Write out the maximum grade and stop.

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.

4-6-2 FLOWCHART SELF TEST


Determine the output produced by each of the following:

1. a
f STAR I
THE COUNTING PROCESS 147

the following nowcharts.


Determine the number of records read by each of

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 =

= I + Data deck / READ LCC,g/


--99

/ 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

4-6-3 Answers to Flowchart-Self-Test

1. a. 2,3. b. -1,1, -1,1, etc. c. 2, 4.5; 3,4; 4, 3.5. d. 18,14;21,20

2. a. 7. b. 10. c. 4. d. Infinite.

3. a. Prints values for X which are greater than 90.


b. M will store the smallest value of G.

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.

8. a. I = 3, four cards read, b. I = 1, one card read,


c. I = 5, four cards read, d. I = 1, six cards read,
e. 1=1, one card read. f. 1=6, six cards read.

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

158 THE COUNTING PROCESS

3. Write the code to generate the following sequences of numbers:

a. 2,4,6,8, ... 100


b. 7,9,11,13. .. 101
c. 1,9,25,49. ..289
d. 1,-1,1,-1,1,-1 . . . 1,-1
e. -17,-15,-13 ... -1

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:

Given 3,4,8,4,-3,-2,-1, the program would print 3,4,8,4,-3


Given -2,1,-3, the program would print -2,1
Given 1,2,3,4,5, the program would print 1,2,3,4,5
Determine the number of lines generated or the number of data cards processed (read)
by the following statements, given the various formats:

READ(5,5)I,J WRITE (6, 6) I,


5FORMAT! 14/13 )>^ 6 FORMAT (/1X,I2///1X, 13)
5 FORMAT (/I4, 13) g- 6 FORMAT! '0' ,I2/1X,I3/)
5 FORMAT (/I4, 13/) h. 6 FORMAT (//T2,I2/1X, 13)
5 FORMAT (//I4, 13/) i. 6 FORMAT (//1X.I2/1X/I4///)
'7
5 FORMAT (yi/I4/'/i3/'/^ 6 FORMAT(/'0' ,I2/'0',I3)
6. Which of the following statements are true?

a. Specification statement errors are detected at execution time.


b. DATA statements can be inserted anywhere in a FORTRAN program.
c. Specification statements are nonexecutable statements.
d. The statement INTEGER ISAM, SAM, KKK is valid.
e. Automatic end of file can be used in certain cases when printing an unknown
number of values.
f. IMPLICIT INTEGER/A-Zjs an invalid specification statement.
g. Three consecutive slashes at the beginning of an output format (///) mean three
blank lines.

h. The statement READ 5 6 X I Y will read three cards.


( , ) , ,

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

6 FORMAT! 12/'+' ,13)

4-7-2 Programming Exercises


1. Modify the program of Figure 4-15 so that only one counter (I) is needed in the pro-
gram instead of both and T. I
THE COUNTING PROCESS 159

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
.

160 THE COUNTING PROCESS

8. A file containing numbers thought to be in ascending sequence is contained on cards


(one number per card). Write a program to perform a sequence check, i.e., to make
sure that no numbers are out of order. If one is out of sequence, print it and print its

position in the Mst (was it the fourth, seventh, etc.). Stop at the first out-of-sequence
number.

Example

Given the numbers 10,1,3,9,8,4,15, the output would be:

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

single, 2 = married, 3 = divorced, and 4 = widowed). There is an unknown number of


data records. Write a program to compute and print the following:

a. The percentage of people over 30 years of age.


b. The number of people who are either widowed or divorced.
c. The number of people who are over 50 or less than 30 and who are not married.

11. Write a program to read a value for J (J > 0) and:


a. Print the even integers that are less than or equal to J, starting with 12.

b. Print the first J odd integers starting with 1

c. Determine if J is a prime number.

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:

Top of nev. page

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

The table should be


centered in the listing.
162 THE COUNTING PROCESS

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.

Write a program to print out the following board (exactly).

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

MORTGAGE PAYMENT PLAN

PRINCIPAL INTEREST RATE DURATION MONTHLY- PAYMENT

50,000 9.50 20 xxxx-xx


XXXX'XX
XXXX'XX
XX
THE COUNTING PROCESS 163

The formula to compute the monthly payment:

P ' 1
12
M =
\ T. 12
P is the principal. 1

/ is the interest rate.

ris the mortgage duration in years.

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:

HOURS RATE OVERTIME HOURS PAY


10.00 5.00 50.00
50.00 5.00 10 275 00'
.

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:

HOURS RATE PENSION PLAN PAY


50.00 10.00 18.30 531.70

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:

HOURS RATE PENSION PLAN


50.00
)) )

164 THE COUNTING PROCESS

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:

10,11,12,13,14,15,16 The median is 13.

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

*( BEATS RECORD OF 70 SET IN 1906


3 10/25/76 HIGH TODAY 73*
LOW TODAY -10**
*( BEATS RECORD OF 68 SET IN 1938
** BEATS RECORD OF -8 SET IN 1918
(

4 10/26/76 HIGH TODAY 22


LOW TODAY -18*
*( BEATS RECORD OF -5 SET IN 1900

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

octal up to a number N read from a card?

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

nr-n = total fixed costs


BEP
variable costs
sales
166 THE COUNTING PROCESS

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

Fixed Variable % Variable Break-


Sales costs cos t cost of sales even Profit Deficit
900,000 180,000 • 75 . • •

• 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

are expected to reach 80 percent or 81 percent of next year's projected $900,000


A recent internal study carried out by the company on the various aspects of
sales.
the manufacturing operations disclosed production inefficiencies. Corrective
measures could significantly lower fixed costs. Determine the extent to which
present fixed costs could be reduced to satisfy the projected variable costs figures
for the coming year.

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:

Selling Variable Breakeven


costs cost/unit point Decision
$1.10 117,647
1.11 117,647

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:

r,r-r. = total fixcd costs


BhP
_ variable cost/unit
selling price/unit

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.

Some helpful formulas and decision rules:

a. Order an item only if the ending inventory is less than or equal to the reorder
point for that item.

b. Amount to order = order level — ending inventory.

c. Cost of ordering an item = amount ordered*unit price.


168 THE COUNTING PROCESS

Inventory Summary (week ending October 1, 1979)

Item number
THE COUNTING PROCESS 169

4-7-3 Answers to Self Test

1. a. IF(I.EQ.9)G0T06 b. IF(I.LT.IO) GO TO 2 c. IF( I LT 10 )G0 TO 5


. .

d. IF (I. EQ. 9) GO TO 6 e. IF( I EQ


. . )G0 TO 6 f. IF( I GT. -4)G0 TO 2
.

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.

e. Trigger and last-card code methods.

3.
5
THE ACCUMULATION
PROCESSA^ rT- nO<^

5-1 PROBLEM EXAMPLE


Write a FORTRAN program compute the sum of the first N integers, where N is an in-
to
teger read from a data card. A program
to solve this problem is shown in Figure 5- Note 1 .

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

Figure 5-1), which is an extension of the counting concept covered in Chapter 4.

5-2 FORTRAN STATEMENTS


5-2-1 The DO Statement
The DO statement represents no new programming concepts: in fact, any FORTRAN
program can be written without the DO statement. The purpose of the DO statement is
strictly one of convenience to the programmer, it is used primarily for loop control. The

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)

Determine the value of N. / READ N / INTEGER SUM


READ(5.1)N
1 FORMAT (12)
Initialize sum ofintegers to SUM = SUM=0

zir.
Start the counter.

Add the integer to I


SUM = SUM + I

the sum.
/
> D010I = 1.N
L ^^ / 10 SUM = SUM + I
Increment the counter,
I

j
r 1=1+1 K /
,

/
/

Test counter with N.


If

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.

The general form of the DO statement is:

DO statement-number index = initial, test [, increment]

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

Increment is an optional integer constant or integer variable specifying the incre-


ment to be added to the index after each pass through the body of the loop. If
172 THE ACCUMULATION PROCESS

omitted, the value of the increment is assumed to be I. In many FORTRAN com-


pilers, increment may be an arithmetic expression (integer or real).

Follow ing are some examples of valid and invalid DO statements:


Valid DO statements Invalid DO statements Comments

00 10 1 = 1,303 DO 3X = 1,3,4 Index must be integer.


DO 5 J = 4, 1000,66 D04I = 1, 20,-1 Increment must be positive.
D0 4KSUM = M1,M2,M3 D0 6Z = M+X,-3,T*2 Invalid index. Expressions not
allowed.
D0 6LL = NSTAR,MITY D0 6K = I,J,TER Increment is real.
D0 8K = 10,M,4 D0 8L=l.l,10,-.l Should be integer values.
D0 9K = I + 1, 10 I + 1 is an expression, not an
integer.

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

DO statement Flowchart rcprcsenlalioii

r"
1

DO 10 INDEX = INIT,ITEST,INCR

statement— 1

Body or range
statement-
of the loop

10 statement-/? Foot 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:

Process statement- 1, statement-2, statement-3 • • • statement-n as many times as the index


takes on values ranging from the initial value up to but not beyond the test value in steps
of the increment.
The DO statement is useful for processing a statement a specific number of times as in
Example 1, where it is desired to read a record and write it out 303 times.

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

15 Body of the loop consists of all statements


READ(5,4) X
90 WRITE (6, 5) X
following the DO statement down to and
including statement 90.
25 X = 3

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.

'See exceptions in Section 5-3 for new FORTRAN standards.


.

174 THE ACCUMULATION PROCESS

Example 2

— DO 15 1 = 3,100,2 This code will generate a table of the


ISQR=I*I square root and the square of the num-
SQR00T = I**.5 bers 3, 5, 7, • 99.
•-15 WRITE(6,1)I,ISQR,SQR00T
1 F0RMAT(2X,I3,I7,F6.2)

It is often convenient to express the terminal value of a DO loop as a variable as in


Example 3.

Example 3

READ(5,1)N The increment part of the DO is omitted. The increment


DO 15K=1,N value is assumed to be I

^15 The body of the loop w'\\\ be repeated N times.

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

Thus the following code would be invalid:


THE ACCUMULATION PROCESS 175

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:

DO 10 I = 1 , 20 A premature exit from the loop will be taken


IF ( I .GE. 11 ) GO TO 5 when I takes on the value 11.

LlO X = X-t-l

5 WRITE (6, 11) I The value printed for I is 1 1

5-2-3 The CONTINUE Statement


Many non-DO controlled loops often terminate with an IF or GO TO statement. Coding
these loops with a DO statement becomes difficult, since the last statement of a DO loop
cannot be a transfer or decision statement. The dummy statement CONTINUE provides
the programmer with a grammatical way out. Consider the problem of reading 100 grades
and counting those greater than 90.
176 THE ACCUMULATION PROCESS

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.

DO 100 K = 1,66 Permissible.

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.

DO 10J0E = 1,10 Permissible.

The value assumed by JOE will be the value as-


sumed by the index at the time the exii was
IF(Y.EQ.6. )G0T0 70, taken from the loop. (JOE is undefined if body
ofloop is processed ten limes.)

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

5-2-5 Nested Loops


Many times when writing programs it is necessary to repeat a loop a certain number of
times. This is an example of a loop within a loop or, more exactly, of a complete loop
being part of the body of another loop. In such cases each pass in the outer loop causes the
inner loop to run through its complete cycle. The following code illustrates the mechanism
of the so-called nested loop.

Outer loop. DO 20 1 = 1,3


Since I varies DO
from I to 3 the
inner loop will
be processed
three times.
180 THE ACCUMULATION PROCESS

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 START START 100


")
Q J 20
80
C = SUM =0 70
60

c = c + I
READ
/ GRADt

SUM = SUM + GRADE


Each time, the constant
is added to the previous

count.

Each time, a new GRADE (variable)


is added to the current SUM.

Figure 5-2 Comparison between Counting and Accumulating.

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.

SUM = Initialize SUM to 0. SUM is used as an accumulator


to accumulate all grades.
DO 25 I = 1,5 Process statements 1 5 through 25 five times.
15 READ 5 1 GRADE
( , ) Read a GRADE.
The new SUM is equal to the old SUM plus the
GRADEjust read.
SUM = SUM + GRADE The first time around the loop SUM + GRADE

= + 60 = 60, hence new SUM = 60.


1 FORMAT (F3.0) The second time around SUM + GRADE = 60 + 70
= 130, hence the new SUM = 130. Each time through
the loop, we are adding the grade just read to form a
running or partial sum of grades. When five grades
have been read, the sum of five grades will have been
computed.
25 CONTINUE Go back to statement 15 until the loop has been
AV = SUM/5 processed five times. Now that all the grades have been
WRITE(6,2)AV read, i.e., gone through its full
the loop has cycle, we
STOP can compute the average and print it out.
2 FORMAT 2X, 'AVERAGE=' ,F5.1
(

END

Figure 5-3 Average of Five Grades.


182 THE ACCUMULATION PROCESS

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

Sequence of partial sums


f^lOO
1^^20"
(^^80~

70
60

Input data
THE ACCUMULATION PROCESS 183

Example 2

6 Y= l Since INIT > ITEST the loop is bypassed and


DO 5 I = 10 , control is passed from statement 6 to statement 17.

5 CONTINUE In this case NT = '^ "*" *

= -8 < 0.

7 X= l

Example 3

00 5 1 = 1,10,-1 The loop will be bypassed since NT = -^^ W\ =-8<0.

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.

5-4 PROGRAMMING EXAMPLES


5-4-1 Transfer Inside and Outside a Loop
A deck of cards contains an unknown number of cards, each containing a grade (a max-
imum of 100 cards including trip record). Passing grades are those grades above 73. Print
each passing grade and compute the percentage of passing grades. A negative grade signi-
fies end of data. A program to solve this problem is shown in Figure 5-4. Note how the
DO used to keep track of the number of grades read. In computing the per-
index I is

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.

KOUNT = Initialize count of grades above 73 to zero.


DO 10 I = 1,100 Process at most 100 cards.
READ (5,3) GRADE Read a grade.
IF GRADE. LT.O. GO TO 15
( ) Is this the end of the data?
IF GRADE. LE. 73. )G0T0 10
( If grade < 73, read more cards.
WRITE (6, 3) GRADE Otherwise, write out passing grade
KOUNT = KOUNT + 1 and count it.

10 CONTINUE
15 PERCEN=K0UNT/(I-1. )*100 Compute percentage of passing grades.
WRITE (6,1) PERCEN KOUNT , Write results.

1 FORMAT IX, F5.1,2X, 13)


STOP
3 FORMAT (2X,F6.1)
END
Figure 5-4 Percentage of Passing Grades.
184 THE ACCUMULATION PROCESS

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

immediately multiplied to the current product in PROD.

INTEGER PROD Set PROD milially to 1 . This variable is used


PROD =1 as the accumulator for the product. It should
READ 5 5 N
( , ) not be set to since this would cause the prod-
5 FORMAT (12) uct to remain 0.

DO 2 I = 1 . N Read a value for N and use the DO index I to


PROD = PROD'I generate the values 1.2,3. • N while at the •

2 CONTINUE same time forming the product of these num-


WRITE|6,4)N.PR0D bers.

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

Figure 5-5 Calculation of N Factorial.

5-4-3 Standard Deviation


The general formula to compute the standard deviation for n grades .x ,, .Y2, .v,, . . ., a,, is giv-
en by:

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

8 N = K-1 Subtract I for the end of file card.

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

Figure 5-6 Calcuhilion of Standard Deviation.


THE ACCUMULATION PROCESS 185

5-4-4 The Sine of X

The general formula to compute an approximation lor the sine of.v. where x is the radian
measure of an angle, is given by:

A' A' , X'


1!

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:

1. Find the factorials of the odd numbers from 1 to 1 1 (1 !, 3!, . . . 1 1 !).

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

ISIGN = Set variable to determme if sign is positive


6 FORMAT (F3.0) or negative.
7 FORMAT (F8. 4)
S = 0. Set accumulator S to 0.
READ (5, 6 )X Read the radian measure.
DO 101 = 1,11,2 Generate the odd numbers.
TX = X**I Fmd the powers of X.
IFACT = 1 Set the factorial to 1

DO 8 J = 1,1 Compute I factorial.


IFACT = IFACT*J
8 CONTINUE
S=S+ ( -1 **ISIGN*TX/IFACT Accumulule
) the sum (or ditTerence) of the
powers ofX divided by the corresponding
factorial.
ISIGN = ISIGN + Update the sign for the next term.
10 CONTINUE
WRITE (6,7)S
STOP
END
Method 2 Method 3
READ (5. 3 )X DATA K, SUM, N/1,0 .1/
F0RMAT(F3.0) READ(5,5)X
XSQ = X*X X = -X
S = 20 SUM = SUM + (-X)**N/K
IFACT = 1 N=N+2
DO 10 1 = 1,5 K = K*(N-1)*N
S = S + X/IFACT IF(N.LE.11)G0T0 20
X = X*XSQ WRITE (6, 6) SUM
10 IFACT = -IFACT* (2^ 2*1+1 5 FORMAT (F3.0)
WRITE(6,6)S 6 FORMAT (F8. 4)
FORMAT (4X,F8 4) END
END
186 THE ACCUMULATION PROCESS

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:

1. Major or documentary headings: Identification of the purpose of the report. Date of


the report or transaction. Identification of the company, agency, etc.

2. Subheadings: Titles or labels should be provided for each column of information listed.

In some cases underlining might benefit the appearance of the report.

3. Summary or intermediate results should be printed whenever necessary to provide


subtotals for a group of entries that are similar in nature; for instance, sales subtotals
for a given salesman in a salesmen sales report, or item subtotals in an inventory.

4. Overall or grand totals reflecting sum of subtotals, etc. An accompanying descriptive


explanation should precede numerical results.

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

333121481337 COMPUTER UTILIZATION REPORT


33312098100 6
.
DECEMBER 1981
/ 22212118150 STUDENT DATE RUNS TOTALS
111121381040
111121281150 111
111121081200

Student Date Program


number runs
THE ACCUMULATION PROCESS 187

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-

plained in Figure 5-8) to initialize OLDNUMBER and NEWNUMBER


to the number
read from the very first record. That switch is then turned off. Both programs are shown in
Figures 5-9 and 5-10.

5-5 PROBING DEEPER


5-5-1 Flowchart Symbol for the DO Statement
There symbols to represent the DO statement. The symbol
exists a variety of flowchart
presented in this section is in accordance with the new standards proposed
conceptually
for ANSI FORTRAN. The main difference between the existing standards in terms of the
DO loop processing and the proposed standards is that the DO index is set to the initial
value and tested immediately with the terminal value. If the initial value is greater than the
terminal value the body of the loop is bypassed, and processing resumes with the state-
ment following the foot of the loop. Consider, for example, the following statement:

DO 80 J = 3,22,2

The corresponding flowchart symbol is depicted in Figure 5-11.


The sequence of activities in the DO flowchart symbol can be visualized as follows:

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

we have encountered a new student and it is time at this point to


SUBTOT = II print the subtotals of the preceding stuctent. We must also reset
OLDNUMBER = NE\\NLMBI R SUBTOT to zero in order to accumulate new totals for the student
whose number was just read. Also we need to reset the previous
student number to the new number just read, since we will need to
compare that number with the next number to be read. If we failed
Add no. progs, lo
to do this we would always be comparing the new number with the
TOTAL and SUBTOT
number from the first data card, and that number would never
change.

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

Figure 5-7 A Report Example.


THE ACCUMULATION PROCESS 189

V
TOTAL =0
SUBTOT =
1 , ) )

190 THE ACCUMULATION PROCESS

INTEGER PROGS DATE SUBTOT TOTAL , . .

TOTAL =
SUBTOT =
WRITE(6,1)
WRITE (6. 9)

READ (5.2, END=8 NEWNO DATE PROGS I , ,

OLDNO = NEWNO
6 IF OLDNO. EQ. NEWNO) GO TO 5
(

WRITE (6, 3) SUBTOT


SUBTOT =
OLDNO = NEWNO
5 TOTAL = TOTAL + PROGS
SUBTOT = SUBTOT + PROGS
WRITE 6 4 NEWNO DATE PROGS
( . ) . ,

READ (5.2, END=8 NEWNO DATE PROGS ) . ,

GO TO 6

8 WRITE (6. 9)
WRITE 6 7 SUBTOT TOTAL
( . ) .

1 FORMAT (T12. 'CARD COMPUTER UTILIZATION REPORT'


VT16 DECEMBER 1981 //T5
, • '


STUDENT T17 DATE T26 RUNS T35 TOTALS
, , ,

• , ' ' , ' ' , ' '

2 FORMAT (13, 16, 14)


3 FORMAT (T36, 15)
4 F0RMAT(T7,I3,T16,I6.T27,I4)
7 F0RMAT(T36.I5//T5. 'TOTAL PROGRAM RUNS .T35 16) ' .

9 FORMAT ( )

STOP
END

Figure 5-9 Report without Switch.

INTEGER PROGS DATE SUBTOT TOTAL SWITCH


. . , ,

TOTAL =
SUBTOT =
SWITCH =
WRITE (6,1)
WRITE (6, 9)

6 READ (5,2, END=:8 NEWNO DATE PROGS ) , ,

IF(SWITCH.NE.0)G0T0 10
SWITCH =
OLDNO = NEWNO
10 IF OLDNO. EQ. NEWNO) GO TO 5
(

WRITE (6, 3) SUBTOT


SUBTOT =
OLDNO = NEWNO
5 TOTAL = TOTAL + PROGS
SUBTOT = SUBTOT + PROGS
WRITE 6 4 NEWNO DATE PROGS
( , ) , ,

GO TO 6

8 WRITE(6,9)
WRITE 6 7 SUBTOT TOTAL
( . ) ,

1 FORMAT (Tl 2, 'CARD COMPUTER UTILIZATION REPORT'


*/T16 DECEMBER 1981 //T5
,

' ,

• .

STUDENT T17 DATE T26 RUNS T35 TOTALS


' ' .
,

' .
.

' ' . ' '

2 FORMAT (13, 16, 14)


3 FORMAT (T36. 15)
4 FORMAT (T7, 13, T16, I6,T27,I4)
7 F0RMAT(T36,I5//T5, 'TOTAL PROGRAM RUNS ,T35 16) ' .

9 FORMAT ( )

STOP
END

Figure 5-10 Report with Switch.


THE ACCUMULATION PROCESS 191

Step-by-step description DO jJowchart symbol

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

Figure 5-1 1 The DO Flowchart Symbol.

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

5-5-2 Relationship between the List of Variables and List of Fornnat


Codes
If there are more data format codes in a FORMAT statement than there are variables in

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

192 THE ACCUMULATION PROCESS

Compound C COMPOUND INTEREST PROBLEM


interest INTEGER T
problem WRITE(6,1)

1 FORMAT T3 AMOUNT TIO PRINCIPAL


(
,

' ,
,

'

T20 YEARS T30 INTEREST


,
* •
' , '
'

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

codes in the FORMAT


and the READ list specifies eight variables, three cards will be
read with only two items read on the third card, assuming the control code / is not used.
Consider the following examples:

Number of variables Number of data format Number


in the RE A D list codes in FORMA T
6
6
6
6
6
6
6
6
194 THE ACCUMULATION PROCESS

5-5-3 Random Numbers


Random numbers are introduced in this section because, starting with this chapter, some
exercises will require the use of random numbers to simulate certain real-life events. Such
exercises can be interesting and fun, since in many instances outcome cannot be pre-
the
dicted (unless the user has knowledge of statistics). Random numbers are often used in
writing programs that must simulate probabilistic events. For example, consider the
throwing of a die. the event can be 1,2, 3, 4, 5, or 6; each outcome is
The outcome of
equally likely to occur. A
program can use random numbers in the range of to 6 to sim- 1

ulate the outcome of a single throw of a die.


There is no standard method for generating random numbers from a FORTRAN
program. However, most computer installations have random number routines stored in
their libraries that can be accessed by the user. Typically there is a function (which might
be called RANDOM, or RAND) that returns a random number in some range. A func-
tion is a special program one or more values as arguments and returns a single
that accepts
value to the calling program. For example, Y = RANDOM(I) might result in a random
value for Y in the range to 1, that is, < Y < 1, while might return a random integer
I

value. Thus to simulate the throwing of a die we might use:

IDIE = RAND0M(I)*6. +1.

The value returned by RANDOM(I)*6. will be in the range of 0. to 6. (excluding 0. or 6.).


Adding will yield a value in the range of to 6.9999. Placing this real value in the integer
1 1 .

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.

column column 2 column 5

\
row 1

row 2 escape

Submarine is initially positioned


in row 4, column 2.
THE ACCUMULATION PROCESS 195

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
,

direction (1 = up, 2 = left, 3 = down, 4 = right). A program to solve this problem is


shown in Figure 5-13.)

E counts the escapes and D the destroys.


Simulate 1000 trips for the sub.
each trip originating at row 4 and column 2.

Determine the move (direction) for the sub


and calculate its new coordinates (R,C).
Sub moves up. Subtract from row and 1

test for mines or to continue trip ( ! 7).

Sub moves left. Check column is


if 1

If it is, sub is destroyed. If not go to 17 and


determine next position of sub.

If sub moves right, check row = 2 and column = 5,

GO TO 8 in which case the sub escapes.


If C is not 5, the sub is in no danger and it

continues its trip at 17.

Otherwise it has been destroyed.

Increment escape counter.


Do iOOO trips starting at R = 4 and C = 2.
196 THE ACCUMULATION PROCESS

e.
THE ACCUMULATION PROCESS 197

q-
.

198 THE ACCUMULATION PROCESS

15 DO 10 1 = 1,5
WRITE (6, 1)1
IF(I.GT.5)G0T0 15
10 CONTINUE

5. Will the following code compute the average often grades?

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

How many cards will be processed by the following READ instructions?


a. READ(5,5)A,B,C 5 FORMAT (F5.1,F5.1,F5.1
with
5 FORMAT (F5.1,F5.1)
FORMATS 5 F0RMAT(4F5.1)

b. READ(5,6)I,J.K,L,M,N with j6 FORMAT II 12 12


( , , )

FORMATS (6 FORMAT( II 12 13 14)


, , ,

c. READ(5,7)A,I,D 7 FORMAT F5.1, 13, F4.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

INTEGER A B STAT STATIC STATIOO


, , , , ,

DATA X,Y, A, 1/4*0/


DATA PI E/3 14159 2 71828/
,

,

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

5-6-2 Programming Problems


1. Write a program to compute 3 + 5 + 7 + 9+--I- 225 + 227. Do not read cards.

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

d. 9/10 + 9/100 + 9/1000+ ••• \^.

4. Write a program to read a value for N and compute the sum of the squares of the first J

N even integers. For example, if N =4, the sum is 2- + 4^ + (y + 8".

ST'Writea program to compute 1 + (1-2) + (1-2-3) + (1-2-34) + ••• + (l-2-34- •11)

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

200 THE ACCUMULATION PROCESS

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

TOTAL WAGES ARE S10737418 23 FOR 30 DAYS WORK .

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:

a. The total sales.


b. The average cost of a breakfast meal.
c. The minimum cost of a dinner meal.

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

12. Write a program to compute the following sequences of sums:

S, = 1

S, = 1 + Vi

S, = 1 + Vl + '/3

S4 = 1 + '/2 + '/1 + 1/4

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

Assume the data has been sorted into order by


only once), quantity and cost per item.
ascending department number. Write a report to summarize the inventory in the fol-
lowing manner:

DEPARTMENT
THE ACCUMULATION PROCESS 201

slow-moving items. The purpose of the program is to produce a report showing rec-

ommended sale price as follows:

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:

AM ORTIZA TION SCHEDULE


PRINCIPAL: = Sxxxxxx.xx INTEREST = xx.xx% PAYMENT = Sxxxxx.xx

MONTH PAYMENT TO PA YMENT TO TOTAL PRINCIPAL


INTEREST PRINCIPAL PA YMENT BALANCE
Sxxxxx.xx Sxxxxx.xx Sxxxxx.xx Sxxxxxx.xx

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

stay in the tunnel forever? How


on the average, does the dog stay in the tun-
long,
nel (each node takes one minute to cover)? Restart the dog at node 0, one
thousand times and count the number of times he escapes through F4 or Bs. Kick
the dog out if he stays in tunnel more than 30 moves.

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

Starting position for mole

Water -•
— Bridge

A mole in this position is

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

and R = 6, C = 6 one hundred times.)

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:

String 2 String 4 String 6


length = 4 length = 2 length = 1

6,8, 10,4,2,0, 1,7,8, 1,2, I

String 1 String 3 String 5


length = 3 length = 4 length = 2

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

(1) the amount the book cost and


(2) either a or a I (0 if the book is paperback, 1 if it is hardback).

You want to know the following information:

a. Total amount taken in. (TOT)


b. Total number of books sold.
c. Average price per book.
d. Minimum price of a hardback book.
e. Average price of a paperback book.

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

2. Trip card (last-card code) contains — 1 .0, — 1

Output: Print TOT, NUM, AVG, XMIN, PAP on one line, in this order.
Test data:
206 THE ACCUMULATION PROCESS

If X = 1, compute thenumber of terms required to produce sin with a truncation er- 1

ror less than 5.10 '.


The truncation error is equal to the first term neglected. For ex-
ample, if the first two terms are used to compute sin .v, the truncation error is .\-/5\
(the first term not used).

31. The number e can be approximated by the formula:

e, ^ \ + |(1 +-^(1 + ](1 + ^)))

However, a better approximation would be:

^100 - 1 +|(1 + j(l +^1 + {(1 +3(1 +-^( • •


-9^(1 + TOO^)
• •)

Write a program to compute e^^

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

Conversational students had a higher average score than batch-processing stu-


dents. Write a program to determine if this difference is significant. The difference is

significant if / > 2.069, where is given by the following formula:


t

t
=
'
[{N, - 1)5; +{N,- \)S;] . (yV. + ^,)

{N, + /V, - 2) ^. . A/,


THE ACCUMULATION PROCESS 207

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|

5-6-3 Answers to Self Test

1. a. Valid. b. Limit must be an integer, c. Index must not be changed, d. Inconsis-


tent use of I. e. Experssion not allowed for index. f. Increment must be positive,
g. Body of interior loop overlaps body of outer loop. h. Index must be integer mode,
i. Foot of loop 91 is missing, j. Valid, k. Foot of loop cannot be IF. I. L is re-
defined in loop, m. Valid, n. Valid, o. Index cannot be modified within loop.
p. Cannot branch into body of loop after normal exit from loop. q. Valid, r. Valid,
s. Foot of loop cannot be a DO statement.

2. a. 1,3,5,7,9. b. 6,9,12,15,18. c. 4. d. 10,100,1000

3. a. 120. b. 21. c. 8.

4. Neither. The value of I will never be greater than 5.

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 =

7. a. 1,2,1. b. 2,2. c. 1,3, error I is integer, and described by F type.

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-

ments are processed at compilation time, not execution time. g. T. h. T. F: i.

Counting is a special kind of the accumulation process, j. F: The comment will be

listed once at compilation time.

9. STATIOO is seven characters long.


X, A, and I are integers and should not be initialized to 0. but to
315.0 is incorrect in statement 10, should be 315
^ Need a comma in the computed GO TO(10. 20, 30, 30), L.
10 should be an executable statement in the computed GO TO and not a FORMAT.
Incorrect placement of the two CONTINUE statements.
In the last IF statement I*J*L is not a logical expression.
GO TO 77 invalid since this causes a transfer into the midst of a DO loop.
is

FORMAT 200 missing. is

Note that THEN L = L + 1 is not a compilation error since THEN L is a variable.


6
DATA
REPRESENTATION

6-1 PROBLEM EXAMPLE


Each card of a deck of cards contains a student's name and the student's final score. Write
a program to assign each student a letter grade, as shown below. The output should be
similar to the following:

Grade Output
. . ' I

210 DATA REPRESENTATION

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

used for this purpose.


A B F now contain the
DATA A B C/ , . ' '
,
' 'CV The variables A, B, C, D, and
DATAD,F/'D' , 'F'/ alphabetic characters A, B. C, D, and F, respectively.
P = TRUE
.
The logical variable P is initially set to .TRUE., stating
thai there is only one highest score. two or more If

highest scores exist, P will be changed to .FALSE, by


statement 14.

AMAX = AMAX is the current highest grade and is used to keep


track of the student's name with highest grade so far. It

is initially but will be reset to the first grade by state-


ment 13.
15 READ (5. 5, END=6) NAME, SCORE For A grades K = 1 0, 1 1 B grades K = 9; for C
; for

K=SC0RE/10. +1. grades K = 8,7; for D grades K = 6 and for F grades K


Kl=K-5 = 1 For A
,2,3,4 or 5. grades K = 6,5; for B grades K
1 1

G0T0(1,2,2,3,4.4) ,K1 = C grades K


4; for 1 = 3,2; for D grades K = and 1 I

GRADE = F for F grades K is negative. The reason for using K


1

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

GOTO 10 been used.


2 GRADE = C If K I is negative or zero, the statement following the
GOTO 10 GO TO is taken.
3 GRADE = B Note that if K = 1 is 3 or 2, transfer will be made only
GOTO 10 to statement 2.
4 GRADE = A If current highest score is larger than grade, just go
10 WRITE (6, 11) NAME, SCORE, GRADE back and read more cards. If current highest score is

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

8 FORMAT TIO SCORE WAS OBTAINED BY OTHER STUDENT S


( ,
'
( ;

END

Figure 6-1 Letter Grades.


DATA REPRESENTATION 211

A program to solve this problem is shown in Figure 6-1. Note the three new FOR-
TRAN features:

1. The DOUBLE PRECISION statement.


2. The LOGICAL statement.
3. The A (alphabetic) FORMAT code.

6-2 NUMBER REPRESENTATION


6-2-1 Internal Data Representation

Integer Data

The internal form from that used for real or alphanumeric


for integer data differs
data. On most computers integer data is in binary form (also c'dWed fixed point
represented
— the decimal point is assumed fixed to the right of the rightmost digit). Each integer in
memory occupies a computer word consisting of a fixed number of binary dig/Ts (BITs).
Integer variable names then, are just names for computer words. Word lengths on dif-
ferent computers vary from 8 to 60 bits; some typical lengths for specific computers are
shown in Figure 6-2. The range of values that can be represented in integer mode is direct-
ly proportional to the word length used. Maximum integer values for some computers are

shown in Figure 6-2.


212 DATA REPRESENTATION

For example, in base 10 the number 6325.3 might be expressed as

mantissa
(fractional part) exponent

.63253 X 10^

\ base (most machines use base 2J8 or 16)

It real number occupies one computer word, which consists of a


should be noted that a
fixednumber of bits (see Figure 6-3). Internally, this means that the computer word is bro-
ken down into two parts: an exponent and a mantissa (fractional part).

Example

The number 6325.3 might be expressed as 63253X loVy

w ,,

and its internal representation might be 04 632 53 one word

exponent T "^ fractional part


(base 10 assumed) implied position (mantissa)
of decimal point

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 )

straight integer representation


/
exponent
\
fractional part code used to represent each
1234= .1234 X 10^ digit or character is

exponent = 04 01 = 1 03 = 3

fractional part = 123400 02 = 2 04 = 4

From we could conceivably look at the c/zaracre'r string 01 02 03 04 and


this visualization
interpret it number 1,020,304 or we could interpret it as the real number
as the integer
020304 X 10' = 203040 if we do not know the mode used. Conversely, the real number
04123400 could be interpreted as the character string 4BZ0 if 12 is the code for the letter B
and 34 the code for the letter Z. Even though we can give different interpretations to the
memory contents of a variable, the computer does not get confused when it processes the
variable, since it knows in what mode the variable is to be processed (from the definition
of the variable).
Alphanumeric data can be stored in variables of any mode, but no arithmetic opera-
tions should be performed on these variables (it does not make sense to compute an aver-
age of telephone numbers, or divide one name by another name!). To avoid errors, the
programmer should be careful not to use mixed-mode alphanumeric variables in IF state-
ments or across the equals sign in a replacement statement. Consider the following exam-
ple: Suppose the variable L contains the alphanumeric string 01020304 and it is desired to

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.

Initialization of Alphanumeric Variables

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:

DATA SAM STAR J/3HTHE IH* 4HHHHH/


, , , ,

This results (on IBM 360/370) in memory as: SAM = T H E ^


where Jb is the character "space" STAR = ^^^^
J =HHHH
2. Enclose the character string within single quote marks. For example:

DATA SUE SAM JSUM/ AMCA ',' + ',


, , ' 'WT .'
\ Note two blanks.
Assuming four characters per word, this results in: SUE = AbCA
SAM= +^^^
JSUlA = Y,]6i:.

The A Format Code

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

Assume each variable can contain four characters:

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

Assume each variable can contain four characters:

Memory
/ \
[w_

4
READ (5,1 I T
1 FORMAT! A7 A5

^TTe WAS MOUSY


DATA REPRESENTATION 217

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
/

218 DATA REPRESENTATION

However, the following is valid and a branch to 20 would be made:

DATA CAR/ CAR / ' '

IF (A. EQ. CAR) GO TO 20

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

The programmer should be careful not to use mixed-mode alphanumeric variables in IF


statements. If A and I both contain in memory theword CAT, then the statement

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

M contains CAT, then

IF (M.EQ.I) G0T0 30
will result in a true, equal condition and a branch to 30 will be taken.

6-2-3 Alphanumeric Data and the CHARACTER Specification


In FORTRAN 77 the CHARACTER statement is an additional type specification which
can be used to declare variables for storing alphanumeric data. The word length of these
variables is one (that is, one character) unless otherwise specified. The CHARACTER
statement is a nonexecutable statement and must be placed before the first executable
statement.

Initialization in the CHARACTER Statement

Example 1

M
CHARACTER A*4/ HATS / L/ / ST*3/ DO
'
'
. '
'
, '
'/ - NO/ TR
'
'
DATA REPRESENTATION 219

The interpretation of the preceding is as follows:

a. A*4 means that A is to store four characters, so A = HAT S

b. L, without a length specification, means L stores one character; thus, L = M


c. ST*3 means the word length of ST is three; thus one blank is used to "fill" memory on
the right. ST = DO^
d. Since NO has no length specification, only one character gets stored; thus NO = T
Note that the leftmost characters get stored in a CHARACTER declaration when the
character string exceeds the length specified.
The maximum length allowed for a character variable is 255.

Example 2

CHARACTER*4 A/ HATS/, B* 5/ 'DON' 'T'/,X/'MAN'/


'

The results in memory are:

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:

CHARACTER B0X*4,M FIRST*2 ,

BOX='GO' Fill to the right with blanks.


M = TOP
'
' Truncation to the right.

FIRST =' NO'


The results in memory would be BOX = GOM]zl, M = T, FIRST = NO

The A Format Code and CHARACTER variables


Variables which have declared in the CHARACTER specification statement can be
read with A
format code following the same rules given for reading alphanumeric
data with real or integer -variables see (Section 6-2-2). For example, the following code:

CHARACTER ME* 4, SEX NAME* 8, LOAN* ,

READ(5,10) NAME, SEX ,ME .LOAN


10 FORMAT A8 ,A1,2X,A3,
( A6)
\ \ I I /
with data I^RICHARDM 11 PSC ]2J]zJBUS
K

220 DATA REPRESENTATION

would be stored in memory as:

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.

Comparisons with Character Variables

CHARACTER variables can be compared to other CHARACTER variables or to


literal strings in IF statements. Such CHARACTER variables (strings) are compared
character by character rather than a word at a time (algebraically) as in the case of real or
integer vari-ables. If two character strings are of unequal length, the smaller of the two is

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-

al strings. Consider the following examples:

Legal

CHARACTER FNAM*8,J0B*6

READ(5,2)FNAM.J0B First, the contents of JOB. which is six

2 FORMAT (A8,2X,A6) characters long, padded with two blanks


is

on the right. Since FNAM and JOB are


CHARACTER variables, each character
code in the memory for FNAM com- is
IF(FNAM.EQ.JOB) GO TO 5
pared to each character code in JOB to see
if they are the same.
H
AND FNAM LT
.

FNAM GT
.

IF ( . ' ' . . . '

Comparison here is made between the con-


*WRITE(6,20)FNAM tents of FNAM and HWW^^W. If the
code for the leftmost character in FNAM is
greater than the code for 'H". then this con-
dition is true. A similar comparison is made
between FNAM and 'K'. in essence, this
determines if the contents of FNAM lie

alphabetically between H and K.


DATA REPRESENTATION 221

Illegal
222 DATA REPRESENTATION

Examples

Exponential form Basic form

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

The E Format Code

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

The general form of the E format code is:

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.

/-* CLC) Ci^ tf^^


Example O/U
1
\>\a^*^ UnU^

READ (5,1) A B C D E
\ I i I I

1 FORMAT E5.2 E6.0 E8.5 E7.5 E8.1


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

Value stored 3 2 X 10 12.3456 Trouble Trouble


T

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:

Value of data item


DATA REPRESENTATION 225

Each variable in the Ust-of-variables is assigned double precision mode. It should be


noted that DOUBLE PRECISION affects only real numbers, not integer numbers. The
double precision feature does not exist for integers. This does not mean that a variable
name starting with through cannot be declared in a DOUBLE PRECISION list. Such
I M
a variable would just represent a double precision real number.

Example

DOUBLE PRECISION XJ
X = 123456789012345. Both X and 1 are now double precision
I = .1 234567890 12345D40 real constants.

DOUBLE PRECISION is a nonexecutable specification statement subject to the same re-

strictions as other specification statements (see Section 4-2-1 ).

Double precision constants can be represented in a basic form similar to the


basic-real-constants except that double precision constants will have more significant
digitsthan can be stored in an ordinary floating-point word. For example, on the IBM
360/370 the constant 63217869.2, which contains more than seven significant digits, auto-
matically becomes a double precision constant.
There is also an exponential form for double precision constants that is analogous to
the exponential form for real constants except that the character D is used in place of E.

Example

6.2D + 4 has value 62000


- .0326798432 56D - 1 4 has value - .00000326798432 1 56

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

DOUBLE PRECISION T.X


X = I*J/C**K-l-T

First C**K is performed in real mode.


Then I*J is performed in integer mode.
Then (I*J)/(C**K) is performed in real mode.
Then (I*J)/(C**K) + T is performed in double precision.
Finally, the double precision result is stored in the double precision variable X.

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

226 DATA REPRESENTATION

DOUBLE PRECISION X,Y Results


REAL A B ,

X =1.2345678903 X will contain 1234.56789


A =X A will contain 1234.567
Y = 999999999 Y will contain 999999999.
B =Y B will contain 999999900.
1 = 1. 29456789D1 1 will contain 12 (no round ofQ.
J=Y J will contain 999999999

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.

6-2-6 Logical Type Data and the L Format Code


Perhaps without the reader being aware of it, we have already made extensive use of
logical expressions. A logical expression can be thought of as a proposition (a proposition
is a statement that is For example, the statement "I am 36 years old"
either true or false).
is either true or false; similarly, the statement "X is greater than 63" is either true or false.

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:

Valid. X.LT.1.3 Invalid X-^23*Z


XAM NE. .

(X-hY)**2.EQ.4
2.*Y.GT.X-Y
-1. .LE.SQRT(Z)

Logical expressions, just like arithmetic expressions, can be processed in replacement


statements and in logical IF statements. In either case the logical expression is first eval-
uated and the result of this evaluation takes on the logical values .TRUE, or .FALSE.
(these values are called logical constants), jusi as the evaluation of 3. + 5. takes on the nu-
merical value 8. These logical values, .TRUE, and .FALSE., can be stored in logical vari-
ables in the same way that arithmetic constants can be stored in variables. However,
DATA REPRESENTATION 227

logical variables must be declared in a LOGICAL statement. The LOGICAL statement


has the general form:

LOGICAL variable-list

where variable-list is a list of any variable names.

Example

LOGICAL X,I,A

The following are now logical variables: X,I,A. Once a variable is declared LOGICAL, it

can be assigned the values .TRUE or .FALSE,


through replacement statements. It cannot,
however, be assigned numeric values. The general form for logical replacement statements
is:

logical-variable = logical-expression

The following are valid examples of logical replacement statements:

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 following are examples of invalid logical replacement statements:


228 DATA REPRESENTATION

The effect of the logical operators on two logical expressions, e^ and P;, can be de-
scribed as follows:

f, .AND. €2 is .TRUE, if and only if e, and e^ are both.TRUE. .

Cy .OR. ei is .TRUE, if either e, or ei (or both) are .TRUE. .

.NOT. ej is .TRUE, if e^ is .FALSE, (evaluate ei and negate it).

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

Some examples of invalid compound expressions are:

LOGICAL A,B,C
B

230 DATA REPRESENTATION

Example 2

Suppose X = 30, Y = 40, A = TRUE, and B = .FALSE. .

. 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

the logical-expression is .FALSE., the statement following the IF is executed.

Example:

Suppose X = 30, Y = 40 and B = .TRUE.

LOGICAL A, B,C

IF(B)G0T0 30 B is TRUE., hence the branch to 30 is taken.

A = X LT Y . . A is.TRUE.;A.AND.BisTRUE.;
IF(A.AND.B)C= .TRUE C = .TRUE, is processed.
therefore

IF(X.GT. lOO.OR. .NOT.B) GO TO 7 X.GT. 100 is .FALSE.; .NOT. B is .FALSE.;



therefore the next statement is executed.

The L Format Code

Logical variables can participate in input/output statements. In order to assign value


to a logical variable via the READ or WRITE statements, the L format code must be
used. The general form of the L code is:

Lu
DATA REPRESENTATION 231

where w represents the field width.


When will scan the input field from left to right.
reading a logical variable, the system
If the nonblank character is T, the value stored for the logical variable is .TRUE.; if
first

the first nonblank character is F or if the entire field is blank, the value stored is .FALSE. .

Remaining characters in the field are ignored. On output, a T or an F is printed, depend-


ing on whether the variable is .TRUE, or .FALSE. The character T or F is right-justified
.

on the output field with w — blanks to the left.


1

Example

LOGICAL X,Y,Z Printout

READ 5 2 X Y
( , ) , ,
Data card
FORMAT (L3, LI,,L5)
L5)
WRITE(6,2)X,Y,Z
STOP
END
232 DATA REPRESENTATION

Following are invalid examples of complex constants:

(0. ,1) I is not a constant.


1. ,1. No parentheses.
(3115,3.4) The real part is an integer.
(.004E + 4,5.1010 The parts differ in mode.

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

A well-documented description of these functions is generally available in the FORTRAN


technical reference manual for the particular computer system.

Input/Output of Complex Variables

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)

6-3 YOU MIGHT WANT TO KNOW


1. What are "significant digits"?

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:

1001 .56 has six significant digits


0012.4
[
have three significant digits (.000315 = .315 X lO"')
.000315

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:

Graphic symbol Punched card code Hexadecimal representation

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

8. Can initialize an alphanumeric


I string through a replacement statement; for example,
X = 'DOG'?
Ansvier: Not usually. Many recent FORTRAN compilers and WATFIV systems will
permit it, however, if X has been declared a character variable.
9. What is the advantage of using logical variables and logic processing?

Answer: Decisions can be expressed in a straightforward fashion. Also, logical vari-


ables can be employed in Boolean algebra, which can be used as a mathematical tool
or model in the study of sets, in the study of switching circuits, and in applications
that make use of truth or decision tables.

10. Can I define a logical variable in a DATA statement?


Answer: Yes.

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

6-4 PROGRAMMING EXAMPLES


6-4-1 Logical Problem Example
Each card of a deck of cards contains the following fields:

Student name (eight characters at most) ccl-8


Age An age of terminates the data deck. cc9-10
Sex I = male, 2 = female ccl 1

Class 1 = freshman, 2 = sophomore ccl2

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.

6-4-2 Switching Circuits ^ dC.0


Consider an electrical circuit consisting of a power source and switches such as:

Switch A

^•^ Power source

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-

pression A.OR.B represents the parallel circuit.


It is possible to write logical expressions for any switching circuits:

Examples

circuits Logical expressions

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.

6-4-3 Complex Roots of a Quadratic


The roots of ax' + bx + r = are given by:

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

*'X1=' .2F7.3, 'X2=' ,2F7.3)


GO TO 2
10 STOP
END
Figure 6-9 Complex Rools of a Quadralic.

6-5 PROBING DEEPER


6-5-1 More on Floating-Point Numbers and integers

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

X = .42 X 10' X X 10"^ = X .3) X (10' X 10"-) = .126 X 10"'


4.2 .003 .3 (.42
4.2 + .003 ^.42 X 10' + .3 X 10'- = .42 X 10' + .0003 X 10' = .4203 X 10'

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

and well stocked.


The absolute error, such as the one above, is not as horrendous as one might suppose.
After all, if the computer represents 1,000,000,400 as 1,000,000,000, the absolute error
may be 400, but, relatively speaking, what is 400 compared to 1,000,000,400':* Very little.
Also, suppose the computer represented .6 as .5; then the absolute error would be .1,
which is small, but, relatively speaking, to commit an error of .1 to represent .6 is horren-
dous even though the absolute error is small. Hence another measure of error is in-
troduced, called the relative error, which may be more meaningful than the notion of
absolute error.
DATA REPRESENTATION 241

The relative error of a computer-generated number is the absolute error divided by


the computer approximation for that number. For example, if we have a true value of
.00006 and a computer approximation of .00005, the absolute error is only 10~^ but the rel-
ative error is .00001/. 00005 = .2 or 20 percent. If, on the other hand, we have a true value
of 1,000,000,400 and an approximation of 1,000,000,000, the absolute error is 400 but the
relative error is 400/1,000,000,000 = .4 X 10"**
or nearly zero, percentagewise.
Fixed-point arithmetic is much faster than floating-point arithmetic, hence if execu-
tion time is critical it may be wise to use integer mode data and arithmetic whenever possi-
ble. There is some inherent error in the representation of data in floating-point schemes.
During the number conversion process, some decimal numbers cannot be translated exact-
ly in binary; for example, .^ has no exact binary representation. The resulting binary val-
. 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?

2. What restrictions are there on the placement of specification statements in FOR-


TRAN programs?

3. Express each of the following exponential constants in basic form:


a. 3.2E-4 e. 432.4D2
b. .0034E10 f. -163.94872D - 10
c. -132.4E6 g. 1632543.1 ID -8
d. -132.4E-6 h. .0000324D15

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

7. Which of the following statements are correct?


a. A + B could be a valid logical expression, depending on how A and B are specifi-

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

f. Y.AND.SQR(X) is a valid logical expression.

8. Evaluate each of the following logical expressions if A = 3.0, B = •4, andC = 0.

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

9. Determine the value of the following expressions, given A = .TRUE., B = .TRUE.,


C = FALSE..
a. A.OR.B
b. .NOT.C
c. (A.OR.B) .AND. C
d. .TRUE.. OR.
e. .TRUE. .AND. C (read it quickly!)
f. .NOT C. OR 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 .

called the exclusive-or.)

12. Represent each of the following circuits by means of a logical expression.


a.
244 DATA REPRESENTATION

b.
DATA REPRESENTATION 245

2. A deck of cards contains two fields per card: a name and marital status code = sin- ( 1

gle, 2 = married, = divorced, 4 = widowed). Produce a listing (using just one


3

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 compute the number of lucky dates.

5. Each data card consists of six items described as follows:

Item Description/ code

1 Marital status 1 = single 2 = married 3 = divorced 4 = widowed


2 Sex 1 = female 2 = male
3 Age 1 = over 30 2 = under 30
4 Contentment 1 = happy 2 = unhappy
5 Family name
6 First name

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:

ZAN OAKS IS OVER 30 HE IS MARRIED AND UNHAPPY


. .

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.

Full professor: teacher must have a doctorate in any 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).

8. Write a FORTRAN program to determine whether the following logical equations


are always satisfied regardless of the values of A, B, and C.
a. .NOT.(A.AND.B) = .NOT.A.OR.(.NOT.B)
b. A.OR.(B.AND.C) = (A.OR.B).OR.(A.OR.C)
c. .NOT.(A.AND.B).OR.A = TRUE.
d. A.AND.B.OR.(.NOT.A.AND.C)= .NOT.A.AND.(.NOT.B).AND.C.OR.A
.AND.B.AND.(.NOT.C).OR.B.AND.C
DATA REPRESENTATION 247

Problem 8a can be partially verified by observing that if A = .TRUE, and B =


.FALSE, then:

.NOT.(.TRUE.. AND. .FALSE.) = . NOT. TRUE. .OR.(.NOT.. FALSE.)


.NOT.(FALSE.) = .FALSE..OR..TRUE.
TRUE. = TRUE.
It remains to be proved what happens for other combinations of A and B. A table
of all possible values that A, B, and C can assume is constructed as follows:

A
248 DATA REPRESENTATION

based, floating-point machine described in Exercise 9, and suppose that truncation is

performed. Let us evaluate (2000. + .4) -I- .6 and 2000. + (.4 + .6).

(2000. + .4) + .6 = (.2000 X 10^ + .4000 X 10") + .6000 X 10"


= (.2000 X 10^ + .00004 X 10^ + .6000 X 10"
= (.20004 X 10')+ .6000 X 10"
= (.2000 X 10') + .6000 X 10" Truncation occurs.
= (.2000 + .00006) X 10'
= .20006 X 10'
= .2000 X 10' Truncation occurs.

2000. + (.4 -t- .6) = .2000 X 10' + X 10" +


(.4000 .6000 X 10")
= .2000 X 10' +
(.1000 X 10')
= .2000 X
10' +
.0001 X 10'
= (.2000+ .0001) X 10'
= .2001 X 10'

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.

6-6-3 Answers to Self Test

1. Double precision mode data allows more significant digits to be computed but takes
more space to store each value.

2. Specification statements must precede executable statements.

3.
DATA REPRESENTATION 249
.

7
ONE-DIMENSIONAL
ARRAYS

7-1 PROBLEM EXAMPLE


Let us write a program to calculate the average of five grades read from cards, one grade
per card, and print the difference between each grade and the average. Up until this time it

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.

DEVIATION OF 5 GRADES WITHOUT ARRAYS


READ (5,5) GRADEl GRADE2 GRADES GRADE4 GRADE5
, , , ,

FORMAT (F5.1)
AVE = GRADEl + GRADE2 + GRADE3 + GRADE4 + GRADE5 /5
(

DIF = GRADEl -AVE


WRITE (6, 10) GRADEl, DIF
DIF = GRADE2-AVE
WRITE 6 1 GRADE2 DIF
( , ) ,

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

252 ONE-DIMENSIONAL ARRAYS

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

C DEVIATION FOR FIVE GRADES USING ARRAYS


DIMENSION GRADE( 5) Reserve five memory locations for array GRADE.
SUM =
DO 10 I = 1.5
READ(5,6)GRADE(I)
SUM = SUM + GRADE I ( Accumulate the sum of the grades (see following discussion).
10 CONTINUE
AVE = SUM/5 Compute the average.
DO 30 I = 1,5 Compute the difference between each grade and average
DIF = GRADE(I) -AVE
WRITE(6,7)GRADE(I) ,DIF when 1 = 1, DIP = GRADE(l) - AVE
7 FORMAT (T10,F5.1,3X.F5.1 I = 2. DIP = GRADE(2) - AVEetc.
30 CONTINUE
6 FORMAT (F5.1)
STOP
END

Figure 7-4 Average and Deviation with Arrays.

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

could be visualized as:

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.

7-2 FORTRAN STATEMENTS


7-2-1 DIMENSION Statement
The general form of the DIMENSION statement is

DIMENSION variable^ {limits) Ivariable^ {limit.) . .]

where DIMENSION is a FORTRAN key word,


variable^, variable^, . . . are names of the various arrays (any valid variable name)
(The type of the array (integer or real) is implicitly determined by the name of the
array. If the name starts with through N, the array elements are integer; other-
I

wise, they are real.), and


//w/7|, limit^, . . . are unsigned integer constants representing the maximum
number of memory locations reserved for each array.
This does not mean that all reserved locations must be used when processing the array. Ar-
ray subscripts can vary from 1 to the limit declared in the DIMENSION statement and
cannot exceed that limit. Any array used in a program must first be declared in a
DIMENSION statement. Any number of arrays can be declared in a DIMENSION list.

For example, the statement

DIMENSION X( 6) ,Z(20) ,JSUM(107)

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.

The following DIMENSION statements are invalid:

DIMENSION A 3 ( . ) Invalid limit — should be an integer constant.


DIMENSION A N ( ) N is not an integer constant.

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

Subscript expression form Example Meaning

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

V is an unsubscripted integer variable name. the corresponding entry in array L.


c an k are unsigned integer constants.

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-

valid subscripts for pre-1977 FORTRAN.

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

Accumulation of Array Elements

To compute the sum of the elements of the array A = 10.

code can be used:


ONE-DIMENSIONAL ARRAYS 259

7-2-4 Input and Output of Arrays


There are essentially-,two metjiods for loading (reading) and writing out arrays. The first
method uses the ^x77//(77^QrTii_jif th^DOJjo^ illustrated in Figure 7-4. The second
method uses an implied form of the DO loop that is equivalent to listing all array entries
individually in the READ caUed the DO list. The selection of the meth-
list. ThjsjrietjT^od is

od for inputting or outputting arrays is determined^byTFearrangement of the data, which


may preclude one method from being used. If the exact number of array elements to be
processed is known ahead of time, then the impliedTXTTist can always be used. The two
methods are discussed FrTmoredetail as followsT""

Explicit Use of the DO Loop


A straightforward approach to read five grades from five data cards (one grade per
card) into an array, GRADE, is to have five READ statements, each specifying the five
memory locations into which the grades are to be stored.

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

This method is clearly tedious. A preferable approach is to read GRADE(I) as I varies


from I to 5, i.e., the READ statement is part of the DO loop where the array subscript is

also used as the index of the DO loop.


For example, to read ten data items from cards (one
data item per card), the following code can be used:

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

DIMENSION IHR 10 ( ) , RATE 10


( )

DO 10 1 = 1,10
READ(5,5)IHR(I) ,RATE(I)
10 CONTINUE
5 FORMAT! 13, 2X,F4.0)

Input Data A rray storage


\R RATE
60 10. 40 IHR(l)
20
50

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.

DOUBLE PRECISION NAME (101) For example: NAME(1)= IQHN


DIMENSION SCORE (100) NAME(2) = MICHAEL _
1 = 1 NAME(3) = S ANDRA__
8 READ (5,11) NAME I ( ) , Tl T2 LCC, , On last card N AME(I) will contain
IF(LCC.EQ.99) GO TO 9 blanks and T1,T2 will be zero.
SCORE(I) = (Tl-hT2)/2.
1 = 1-1-1 Count cards
GO TO 8 and go back to read more cards.
9 1 = 1-1 1must be subtracted from because of the I

WRITE (6,1)1 end-of-file card.


11 FORMAT (A8,2F5. 0,12)
1 FORMAT (14)

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

DOUBLE PRECISION NAME (101) DOUBLE PRECISION NAME 100 ), TEMP (

REAL SCORE (100) REAL SCORE (100)


1 = 1 1 =
7 READ (5,9, END = 8 NAME (I ) ) , Tl T2
, 7 READ(5,9,END = 8) TEMP,T1,T2
SCORE (I) = (Tl-^T2)/2. 1 = 1-^1
1 = 1 + 1 NAME I = TEMP
( )

GO TO 7 SCORE (I) = (Tl + T2)/2.


8 1=1-1 GO TO 7
WRITE (6, 5) 8 WRITE(6,5)I

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 )

262 ONE-DIMENSIONAL ARRAYS

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 (

DO 5 1 = 1, 1000 Loop will never be carried out 1 ,000 times


READ 5 9 END = 8 NAME I
( . . ) ( ) , Tl T2
, since the READ statement will force an exit
SC0RE(I)=(Tl+T2)/2. from the loop when the end of file is encoun-
CONTINUE tered.
1 = 1-1 Take into account the end-file record.
WRITE (6,7)

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

The implied DO list is essentially a short-form notation to list subscripted variables in


a READ/WRITE list. Instead of writing

READ(5,5)A(1) ,A(2),A(3),A(4),A(5),A(6)

the more compact and convenient notation is used:

READ (5,5)(A(I),I = 1,6,1)

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

READ(5,10)(Ai I) ,1 = 1,5 WRITE(6,10)(B(I) ,1 = 1,5


10 FORMAT (F5.0) 10 FORMAT (2X,2F6.0)

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

264 ONE-DIMENSIONAL ARRAYS

Example 2

READ(5,10) (A(I) ,1 = 1,13 WRITE(6,10) (A(I ,1 = 1,13;


10 FORMAT (3F5.0) 10 FORMAT! 12F6.0)

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

READ (5. 5) (SALES (I) ,1 = 1,7)


14 entries in all
FORMAT F4 ( -^ .

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

READ (5. 10) (A(I),B(I),I = 1,5 WRITE(6.10)(A(I) ,B(I),I = 1,5)


10 FORMAT (2F5.0) 1 FORMAT 3F6 ]- : -i"^/
( .
^
j-
1 )) )

266 ONE-DIMENSIONAL ARRAYS

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:

WRITE(6,1) (1,1 = 1,9) Write as I I varies from 1 to 9.


1 FORMAT 1 TIO PARTNO 4X 9
(
'
' , , ' .
'
, , ( ' MACHINE ' , 12 2X , )

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:

DIMENSION A 301 ( Force the implied DO list to read


READ (5.5, END = 8)(A(I) ,1 = 1, 500 )
the end-of-file card to cause an
8 1 = 1-1 exit from the loop before it has run
5 FORMAT 3F5. ( 0) its complete cycle. I is not undefined
Since a transfer was forced out of the DO list.

DO 10 K = 1 , 1 is the number of items read.

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.

Initially is 1, and the


I first time through the loop the READ statement becomes

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:

READ (5,6) (A( I) ,1 = 1,9)


6 FORMAT (3F5. 3)
ONE-DIMENSIONAL ARRAYS 267

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

three cards will have to be read altogether.

Nested DO Lists

Implied DO-lists can be nested, very much as DO loops are. Consider the following
example:

Nested DO list Equivalent

WRITE(6,5)(A(I) ,B(I),(M(J),J = 1,4),I = 1,3) DO 61 = 1,


5 FORMAT( IX, 2F5. 0,415) WRITE( 6 5 A(
, ) I) ,B( I ) ,
(M( J ) ,
J = 1 ,4]
I 6 CONTINUE
5 FORMAT IX, 2F5. 0,415)
(

A, B| Ml
268 ONE-DIMENSIONAL ARRAYS

The DATA Statement

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.

or DATA(A(I) ,1 = 1, 5)/l. ,2.1,-3. ,4. ,5.6/ DOIisi.

or DATA A/1 . ,2 . 1 ,-3. ,4. , 5. 6/ Just the array name.

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

To initialize 100 elements of array A to zeroes, we write:

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.

7-3 YOU MIGHT WANT TO KNOW


1. Can you have more than one DIMENSION statement?

Answer: Yes. as man\ as you want. For example:

DIMENSION A(10) ,B(3)


DIMENSION SAM( 4) is equivaleni to DIMENSION A(10).B(3),SAM(4).JP(I0)
DIMENSION JP( 10)
2. What happens if have dimensioned PRICE
I as an array and I use PRICE in a state-

ment such as Y = PRICE*QUAN(J)7

Answer: On a few systems, PRICE will be interpreted as PRICE(I). On most systems,


however, this is an error. PRICE should be subscripted, i.e., provided with an index.
ONE-DIMENSIONAL ARRAYS 269

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:

DIMENSION A( 100) ,B( 60) I 45 C( 50) , ( ) ,

INTEGER A B The array elements of A and B will be processed as integers in


, the program.

REAL I The array elements of are processed as real numbers. 1

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.

5. Does a DIMENSION statement initialize array elements to any specific values?

Answer: No, it is the programmer's responsibility to initialize arrays.

6. What happens if I write WRITE(6,10)A or READ(5,10)A, where A is the name of an


array?

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:

DIMENSION HRS 3 RATE 3 ( ) . ( Input


READ (5,3) HRS RATE ,

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:

HRS RATE HRS RATE


40.
270 ONE-DIMENSIONAL ARRAYS

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.

8. What differentiates a FORTRAN function from a subscripted variable? For instance,


when I write Y = SIN(X), is SIN(X) a subscripted variable?

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:

SUM = TABl I + TAB2 ( ( ) ( I ) , I = 1 , 10 ) or


(A(I) ,1 - 1,10) = 0.

Answer: No, implied DO lists are valid only in input/output and DATA statements.

10. Can I use arrays to store logical values?

Answer: Yes. For example:

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:

READ(5,6)(A(I) ,I = 1,4),(B(I),I = 1,6),I

In this case I is used to control three independent entities.

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?

Answer: Certainly. For example:

WRITE (6.5)A,(K(J),J = 1,3),(X(I),B(I),I = 1,9)


In this case A, K,, K:, K,,, Xi,B|, X2, B2 • •• Xy, B9 will be printed in that order.

7-4 PROGRAMMING EXAMPLES


7-4-1 An Array Search
Suppose array G contains ten grades and it is desired to determine the largest grade.
Searching an array for a particular item is a frequent activity while working with arrays.
The following partial code illustrates a method for finding the largest value of G. The
grades have already been read into array G.

DIMENSION G( 10) Assumes grades have already been read.


XLARG = G 1 ( Set XLARG initially to the first grade.
DO 5 1 = 2,10
14 IF(XLARG.LT.G(I XLARG = G ( 1 f the largest grade so far is less than the
new grade G(I), replace XLARG by the
new grade G(I).
5 CONTINUE Otherwise, keep on searching.
WRITE (6, 4) XLARG Write largest grade.

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

7-4-3 Frequency Distribution


Write a program to produce a frequency distribution of test grades. Given a list of grades,
we must find how many times a grade of 1 appears, how many times a grade of 2 appears,
a grade of 3,4,5, • • • 100. The grades range from 1 to 100 and are read from data cards (one
per card).
The method used to solve this problem can be understood visually through the following
diagram:

Array K consisting of 100 counters initially set to zeroes.

K( 1 ) is the counter to count grades of 1

input
K(2) is the counter to count grades of 2.

K(3) is the counter to count grades of 3.


f5Q

aa
K(4) is the counter to count grades of 4.

aQ
r^5o
K(50) counts the grades of 50.

r K(IGRADE) counts the grades IGRADE.


\IGRADE
K(IOO) counts the grades 100.

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

Figure 7-7 Frequency Distribution.

7-4-4 Bar Graphs


II is often desirable to produce graphic output from a computer program. A scientific

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

1 ' ' , ' '


Skip to next page for titles

DO 20 IDAY = 1,7
READ (5, 2) KSALES
IF KSALES. NE.O) GOTO 15
(

WRITE (6, 3) IDAY


GO TO 20
Print the day and number of stars
15 WRITE(6.3)IDAY, (STAR, J = l.KSALES;
corresponding to the sales for that day.
20 CONTINUE
3 FORMAT (T3. 12, T8,20A1) Assume sales do not exceed 20 (20A 1
).

2 FORMAT (12)
STOP
END

Figure 7-8 Example of A Bar Graph.

7-4-5 Array Input/Output


To be admitted to the MENSA club candidates must score a minimum of 74 points on an
Each candidate's name and
intelligence test. test score are recorded on punched cards as
shown below. Write a program to read a deck of cards to produce the following informa-
tion:

1. Two separate paragraph listings of names of successful and unsuccessful candidates.


Each line should contain four names.

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

Card columns 1-8


\ Card columns 9-1

Not more than 100 data cards


276 ONE-DIMENSIONAL ARRAYS

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-

flects the number of failing candidates.


The implied DO W'RITE(6,1 1)(1PASS(1).1 = i.KP) specifies the
list list of all passing
candidates while FORMAT tells the computer to print first a heading
1 1 names with four
names of passing candidates and their scores are
per line under the heading. Similarly, the
specified by the statement WRlfE(6.13)(IPASS(l).PASS(l),l = 1,KP). FORMAT 13
specifies that one name and one score are to be printed per line. Note the position of the
literals PASSING and FAILING in formats 13 and 14 and note the use of the parentheses

in (T60,A8,T70,F6.1)) to force format control to restart at the rightmost open parenthesis


in the format to print all remaining names and scores. (See Section7-5-2 for a complete dis-

cussion of this feature.)

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

INTEGER PASS 100 FAIL (100 SCORE


( ) , ) ,

PRECISION IFAIL( 100) IPASS( 100) ,NAME


^-^DOUBLE ,

DATA KP KF/0 0/
, ,

10 READ (5,1, END =70) NAME, SCORE


1 FORMAT (A8, 13)

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

End of pass 1 :-2;:


280 ONE-DIMENSIONAL ARRAYS

K= 1 Initially the pointer to the smallest element is 1 , thai is; G(K)


L=K+ 1 or G( 1 ) is assumed to be the smallest number before entering
the loop.
L is 2, to avoid comparing G(l) with G(l) as would be the
case if the first value of I in the DO loop was I initially.

DO 10 I =L N , Compare N numbers to determine smallest value.


IF(G(K).GT.G(I))K = I IfG(K) > G(I) then the smallest element so far is at position
I, and so we reset K to to keep track of the smallest number.
i

This makes G(K) the smallest element so far.


If G(K) < G(i) then G(K) is still the smallest element and K

still points to the location of the smallest element.


10 CONTINUE At the completion of the loop, K identifies the location of the
smallest element and G(K) is the smallest number in the ar-
ray.
T = G(1) Save the value of G(l).
G( 1) =G(K) Store the smallest number in G( I).
G(K) =T Store G(l) in the location that used to contain the smallest
number.

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.

L=K+ 1 L = 2,3,---,N - l.N.


DO 10 I = L N , On the last pass G(N - 1 ) is compaied to G(N).
IF(G(K),GT.G(I))K = I
10 CONTINUE
T = G(J)
G(J)=G(K) Interchange procedure.
G(K) =T
15 CONTINUE

Figure 7-12 Interchange Maximum/Minimum.

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

functions r = .v- + .v — 6 and y = sin.v in the interval (—4,3.6):

1. Fill in an array ILINE with blanks.


ONE-DIMENSIONAL ARRAYS 281

2. Compute = .v' + .v — 6 for x = —4 and insert


a value J the symbol "*" in position J of
the array (ILINE(J) = '*') and print the array ILINE.

3. Repeat steps 1 and 2 for values of .v = —3.6,-3.2, • • •


3.6 (incremental value is arbi-
trary).

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

7-5 PROBING A LITTLE DEEPER


7-5-1 Namelist Declaration
In many FORTRANS the NAMELIST declaration allows one to READ and WRITE
without FORMATS. The general form of this statement is:

NAMEUST /name\/list\/[name2/lisl2/

group name list of variables whose group name is name I

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.

Name I is used in the READ/WRITE instruction instead of the FORMAT statement


number. For example:

WRITE (6,NAME1) means: Print on the output form the name and the cor-
responding value of each of the variables specified
in NAMEI.
)

282 ONE-DIMENSIONAL ARRAYS

DIMENSION ILINE( 28) ,JLINE( 28)


DATA IBLANK ISTAR/ '.''/
, '

WRITE (6, 9)
( 1 X Y X Y
9 FORMAT
, , .

T4 T9 T35
,

' ' , ' '


,
' , ' ' , T40 '
'

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

NAMELIST/NOW/TABLE PULSE PART F/ , , , THEN PULSEI

NAMELIST/THEN/PULSE PART/ , I PART


READ (5, NOW)

In essence, the statement READ(5,N0W) says: Read a maximum of four variables


(TABLE, PULSE, PART, and F) from the input device.
The variables themselves are specified (punched) in equation form on the data cards,
such as PART = 'REAR-AXLE' or F = -1-0078. When the READ statement is ex-
ecuted, the computer scans the input data until it encounters a record with a blank in col-

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-

cation of the array, etc.


All data cards associated with the NAMELIST must have a blank in card column 1

Example

input

READ (5, NOW (^ ^TABLE = 5, -2, 10. &END


^ U&NOWl^fPULSE = . TRUE • PART = REAR- AXLE
,
'
' I

The above READ would result in the following memory arrangement:


PULSE =. TRUE. PART = REAR- AXLE F has not been read
TABLE (1) =3 TABLE(2) =-2 TABLE(3) =10

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
(
'
'
,

' ' , T20


,

'
' , T30
,

' ' , T40


,

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

a. INTEGER B( 3) b. DIMENSION A( 100) ,B(N


c. REAL A nJ^ d. INTEGER (2* 100)
2. In terms of memory arrangement, what is the difference between a three-element ar-
ray and any three variable names?

3. In the context of subscript expressions discussed in Section 7-2-2, which of the follow-
ing are invalid subscripts?

a. B(3.) b. C(-3) c. B(J+K)


d. C(2 + 3*K) e. D(K*3-4) f. F(3/J+4)
g. E(-3*K) h. A(I + 3.4) i. SAM(5-3)
4. State whether the following statements are true or false:
a. The DIMENSION statement is an executable statement.
b. An implied DO list is an executable statement.
c. A FORMAT is an executable statement. . .

d. END a nonexecutable statement.


is

e. The DATA statement an executable statement. is

f. If A is an array, then READ(5,1)A will cause reading of just A(l).


g. Subscripted variables can be used in any FORTRAN statement in the same way
as nonsubcripted variables.
h. The INTEGER and REAL statements can be placed anywhere in the program.

5. Determine the number of records processed (cards/lines) by the following code:

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

6. Convert the following implied DO lists to the explicit DO loop form:

a. READ (5, 5) (A(I) ,1 = 1,6 b. READ(5, 6) (A(I) ,K(I) ,1 = 2,9,2


5 FORMAT (2F5.0) 6 F0RMAT(2(F5.1,I2) )

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)

e. REAL X 3 Y 3( ) , ( f. REALX(3) Y(3) ,

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)

g. INTEGER C h. REAL X( 16)


REAL X 5 ( READ(5,1) (X(I) A,I = 1,41
READ(5,1)X(5) 1 F0RMAT(3F6.1)
READ (5,1)X(1),X(4)
^
X(3)=X(1)*5
X(2) =X(1) +X(5)
1 F0RMAT(F6.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.

a. READ (5,5)(A(I),I = 1,5),(B(J),J = 1,3)


5 F0RMAT(3F5.2)
b. WRITE(6,6)(K,A(I) ,B(I),I,I = 1,5)
6 F0RMAT(I2,2F3.0.I3)

c. READ(5,5)(A(J) ,B(J) ,J = 1,9)


5 FORMAT (F5.1)
d. WRITE(6,8) (A(J) ,J = 1,N,K-1)
8 FORMAT (FlO.l)

e. READ(5,7)A, (A(J) ,J = 1,7) ,B,KK


7 FORMAT (4F3.0)

f. READ(5,8)(A(I) ,(B(J),J = 1,5),I = 1,5)


8 F0RMAT(F5.1)

g. WRITE(6,11)(PAY(J.) .J = l,3)
11 F0RMAT(2F6.1)
290 ONE-DIMENSIONAL ARRAYS

h. WRITE (6, 4) (I, (A(I),I = 1,3),B,I = 1,5)


4 FORMAT (IX, II, 3F5.0,F3.0)

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

DIMENSION A (100) DIMENSION A( 6)


WRITE(6,5)A DO 10 1 = 1,5
READ(5,5) (A(I) ,1 = 1,110) READ(5.7)A(I) .A(I + 1)
F0RMAT(10F5.0) 7 F0RMAT(2F5.0)
STOP 10 CONTINUE
END STOP
END

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

\S^ 6 FORMAT (3F5.1)


(.x^ 6 F0RMAT(3F5.1/F5.1)
U^ 6 FORMAT (F5.1/(2F5.1)

c. WRITE(6,4) (A(I) ,1 = 1,7)


4 FORMAT IX 2F4 0/lX 2 F3
( , . , ( .
1 , IX /2 IX F3
)
( , .
)

15. Find at least five syntax errors in the following code:

REALA(IO) ,B(20) IBIG A w^


DIMENSION A( 10) ,C(3)
DATA C/4 5 6/ ^^\. ^aJtW^'^-^^
,

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

7-6-2 Programming Problems

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.

3. Input two vectors, A and B, with five coordinates and compute


A|B| + A.B. + •• AjBv
X

292 ONE-DIMENSIONAL ARRAYS

This exercise requires interactive communications with a terminal. Guess a number


between and 10 and let the computer guess it randomly, using random numbers be-
1

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:

GRADES Top of new page

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.

9. An array, A, supposedly contains 20 elements already sorted in ascending order.


Write the code to perform a sequence check. Print YES if the array is in sequence; oth-
erwise, print NO.
10. Array A (10 elements) and array B (16 elements) have already been loaded. Write the
code to determine the number of identical elements in both arrays, and determine
which element of A is closest to the constant value 5.89.

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:

1 0, 1 2,30,87 The median is ( 1 2 + 20)/2 =11.


16,53,99 The median is 53.
ONE-DIMENSIONAL ARRAYS 293

To determine whether N is even or odd, evaluate 2*(N/2) - N

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:

NEGATIVE NUMBERS -XX.

COUNT OF ZERO NUMBERS


POSITIVENUMBERS
294 ONE-DIMENSIONAL ARRAYS

HUBIT 200 180 20


FARAH 130 120 10
TODINI 160 154 6
AVERAGE WEIGHT LOSS IS 12 POUNDS
1 MEMBER WITH WEIGHT LOSS OVER 12 POUNDS
"*'" name
19. Same problem as 17, except that a is to be printed beside each member's
whose weight loss is over the average. Hint: Use the carriage control character + to
print the star (*).

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:

5 is out of sequence since 15 > 5.

6 is out of sequence since 15 > 6.

4 is out of sequence since 30 > 4.

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:

Projected earnings Projected costs

Co $18,000 (purchase cost


£, $2,500 C| 1,000 of the van)
£, 2,500 G 1,500
e] 3,000 Cy 2,000
£4 4,500 C4 2,000
£s 6,000 C5 2,100
£, 6,000 Q 2,400
ONE-DIMENSIONAL ARRAYS 295

The decision to purchase the van depends on the benefit/cost ratio (BCR) (gross-
ly speaking, earnings/expenditures) given by the formula

^' "^^^ +/)' +£2(1 +iy + ...Ed\ +/?


BCR =
Co + C, (1 + /•)' + Qd + /y + . . . + Q(l + iy

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:

Benefit /cost ratio Investment rate

6%
6.1

Stop when the BCR is greater than 1 and print the message:

PURCHASE OF THE VAN REQUIRES AN INVESTMENT RATE OF XX. XX

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

1 Remember that leap years have


2 31 one more day in February.
3 59
4 90

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

output of NOVEMBER 18, 1978.

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

Let J be the Julian date (see problem 26 above).


Let Y be the year (last two digits only).

a. Compute X = 365.25* Y + J

b. If the decimal part of X is zero, subtract one from X.


c. Compute the remainder after dividing the integer part of X by seven.

The remainder corresponds to the days of the week as follows:

= Sunday 1 = Monday 2 = Tuesday etc.

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

* * * * * * * *
* * * * *****
* * *

* * * *

» n * <iiti » H.»t. * **********»i| . **»t.

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

Hint: Use A(1),A(2), ^ACIO) as counters and• •


eval
90-99 uate A(IG/ 10 + ) where IG is the grade read.
I

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.

{x^-jy + {X2 - xy + (.v, - .V)- + + (A-„ - xY


sd =
• •

n - 1

where n = number of grades;


X = average of grades;
x^,X2,Xy, • • x„ are the grades.

39. For each student you have one card with his or her account number in card
in a class,

columns 1-4 and columns 1-40 (three columns each). A blank


ten test scores in card 1

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

procedure is carried out until the entry has been found.


er section; this splitting-in-half
The end points of a section are identified by two pointers, L (left) and R (right).
Initially L = and R = number of entries + 1. The method can be visualized as fol-
lows. We are trying to determine whether 51 is in array A ( elements). 1 1
ONE-DIMENSIONAL ARRAYS 299

Left section Right section

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 =

Means corresponding number


in A is second smallest.
ONE-DIMENSIONAL ARRAYS 301

SCHEDULE
Married Filing Joint Returns and Qualifying Widows and Widowers

If Line 5 is: The tax is:

Not over $3,400 No tax.


Over $3,400 but not over $5,500 14% of excess over $3,400
Over $5,500 but not over $7,600 $294, plus 16% of excess over $5,500
Over $7,600 but not over $1 1,900 $630, plus 18% of excess over $7,600
Over $1 1,900 but not over $16,000 $1,404, plus 21% of excess over $1 1,900
Over $16,000 but not over $20,200 $2,265, plus 24% of excess over $16,000
Over $20,200 but not over $24,600 $3,273, plus 28% of excess over $20,200
Over $24,600 but not over $29,900 $4,505, plus 32% of excess over $24,600
Over $29,900 but not over $35,200 $6,201, plus 37% of excess over $29,900
Over $35,200 but not over $45,800 $8, 162, plus 43% of excess over $35,200
Over $45,800 but not over $60,000 $12,720, plus 49% of excess over $45,800
Over $60,000 but not over $85,600 $19,678, plus 54% of excess over $60,000
Over $85,600 but not over $109,400 $33,502, plus 59% of excess over $85,600
Over $109,400 but not over $162,400 $47,544, plus 64% of excess over $109,400
Over $162,400 but not over $2 5,400
1 $81,464, plus 68% of excess over $162,400
Over $2 15,400 $177,504, plus 70% of excess over $215,400

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

b. Sort the arrays in ascending order by ID number.


c. Print the sorted arrays, one ID, corresponding day sent up, and distance per line.

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

306 ONE-DIMENSIONAL ARRAYS

Part number Quantity sold

b. Write a program to read the day's transaction deck to produce a parts inventory
and to:

1 Print a "reorder"message whenever less than 20 items are in stock.


2. Discount the price on any unsold part by ten percent of its original cost
(rounded to nearest digit).
The inventory report, for example, might be drawn as follows:

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:

PART NUMBER QUANTITY COST/PART


100 300
115 40 90 ^^ Note new
130 5 93 ^^^ inserts.
132 300

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

be assigned to the other four heats in a similar manner.


Write a program to:

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

N is the number of eniries in arrav D.

1 = J
ONE-DIMENSIONAL ARRAYS 309

3. a. B(3). b. Invalid. c. Invalid. d. C(3*K + 2). e. Invalid,

f. Invalid. g. Invalid. h. Invalid. i. Invalid.

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

1 READ(5,5)A(I),A(I + I) 2 READ(5,6)A(I),K(I),A(I + 2),K(I + 2)

7. a. (I.) Skip to the top of a new page, space down four lines

(2.) ±_2. (3-) 11111


J._4_ (4.) _1 L^l±ll
±
b. (I.) Invalid; mixed modes. (2.) 1 _ j_
^l-l
^1-1
_ J._4
(3.) 1_1 _A_Z_1
1-1^1
c. (1.) 1 1^_-1. 3^ 1, 0_^
2_ i.__-l^ ±, L: 9--
U-) __l^_Z.l^ 1- 1- 9.- 1 Top of page
__1^_- 1, 1, 1, 0_,

(3.) _L
_ J_^_j^2^ 3, 5_, 0__
J cannot be described by an F format.

d. (1.) _1^ :zl^mi^ll-l


^1_^_^1^1^0
(2.) _1^5_
— 1-L
-1-1.
L^5_
-1—1
- _1_^0_
-l^o_
(3-) 1_-1_-1--1--1--1--1: 1-

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

8-1 PROBLEM EXAMPLE


Widgets, manufacturer of widgets of all kinds, uses three identical shops in its prod-
Inc.,

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

Figure 8-1 Average Hours Lost by Machine.

8-2 FORTRAN STATEMENTS


8-2-1 Two-Dimensional Arrays
So far all the arrays we have considered have been one-dimensional or linear arrays in
which only one subscript is used in addressing elements of the array. Many limes when
writing programs it is necessary to work with data arranged in table form (rows or col-
umns of information). Two-dimensional arrays can be used in FORTRAN to represent
such data structures. These arrays can be conveniently manipulated for processing and for
input/output purposes through the use of indices or subscripts.
For example, the table of numbers shown in Figure 8-2 could be stored in a
two-dimensional array, A, containing three rows and five columns. The conventional
method of addressing elements of a two-dimensional array is to write the row number
first, followed by the column number. Thus the element in the second row and third col-

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.

8-2-2 The DIMENSION statement for Two-Dimensional Arrays


The general form of the DIMENSION statement is

DIMENSION \ariahle{ro\\-limit.column-limit){.

where variable is the name of the array.


TWO- AND THREE- DIMENSIONAL ARRAYS 313

Column 2 Column 4
Column

Row 1

Row 2

Row 3
)

314 TWO- AND THREE- DIMENSIONAL ARRAYS

Subscript expressions for two-dimensional arrays behave in the same way as


one-dimensional subscript expressions. (See Section 7-2-2.) For example, the following
references to a two-dimensional array are valid:

TABLE(3*K,I + 2)
B(10*ISUM-?,J)
C(K,5*L)

8-2-3 Processing Two-Dlmensional Arrays


Two-dimensional arrays can be processed in essentially the same way as sin-
gle-dimensional arrays. Suppose, for example, that we wished to determine the number of
elements with values less than 50 in an array, A, of size 4X3. The search for values less
than 50 can be accomplished by successively examining the first, second, third, and fourth
row of the array A, as shown in Figure 8-3.

DIMENSION A 4 ( , 3 K is a counter used to count array elements with


10 K = value less than 50.
20 DO 40 1 = 1,4
oc r,n 40J
25D0
30
/in T

TF(A(T
i i
= 1,3
Ti PF ^0 1(^0 70 40
FoT 3 fixed value of
, ,

hence the search


.-,•,
m
I,

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

Figure 8-3 Processing All Elements of A Two-Dimensional Array.

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

The interchange procedure can be accomplished by moving, successively, each ele-


ment of column 3 into a temporary location, TEMP, then moving the corresponding ele-
ment of column 17 into the vacated column 3 position, and finally moving the saved value
in TEMP into the corresponding location of column 17, as depicted in Figure 8-4. If no

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

the interchange procedure is shown in Figure 8-4.

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

A(3.i: A(3,2) A(3,3) A(3.4) A(3,5) Shop 3

A<2,1) A(2,2) A(2,3) A(2,4) A(2,5) Shop 2

A(l,l) Ad, 2) Ad, 3) Ad, 4) A(1,5) Shop 1

One method to input the above data is:

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)

Using an implied DO list, the list of variables could be shortened to:

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:

READ(5,3) ((A(I,J),J = 1,5),I = 1,3)


i I

Inner loop cycles the fastest


as I = 1. J runs through 1, 2, 3, 4, 5.

Outer loop moves slowest. For each value


of I, ihe inner index J runs from to 5. 1

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:

READ(5,3)A(1,1),A(1,2) ,A(1,3) ,A(1,4) .A(l,5) ,A(2,1) ,A(2,2) ,A(2,5) ,A(3,1) A(3,5)

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

A(l,5) A(2.5) A(3,5) Machine 5

A(I,4) A(2,4) A{3,4) - Machine 4

A(l,3) A(2,3) A(3,3) Machine 3

A(l,2) A(2,2) A(3,2) K Machine 2

A(l,l) A(2,l) A(3,l) •


Machine 1

Hours lost for shops 1, 2, 3

To input the preceding data the following code might have been used:

READ(5,4) A(l,l) ,A(2,1) ,A(3,i;


. . READ(5,4) A(l,2) ,A(2,2) ,A(3,2;
READ (5, 4) A(1,3),A(2,3),A(3,3;
READ (5,4) A(1,4),A(2,4),A(3,4;
READ(5,4) A(l,5) ,A(2,5) ,A(3,5;
or

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

READ (5, 4) ((A(I,J),I = 1,3),J = 1,5)

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:

Fast index Slow index Fast index Slow index

4 F0RMAT(4F4.0) 4 FORMAT 4F4 (


.
)

READ (5, 4) ((A(I,J),I = 1,4),J = 1,4: READ(5,4)((A(I,J) ,J = 1,4),I = 1,4;

When J = 1 , 1 takes on values 1 ,2,3,4. When I = 1 , J takes on values 1 ,2,3,4.


When J = 2, 1 takes on values 1 ,2,3,4 etc. When I = 2, J takes on values 1,2,3,4, etc.
Hence the array is stored in column Hence the array is stored in row fashion,
fashion, as shown on the next page. as shown on the next page.
318 TWO- AND THREE- DIMENSIONAL ARRAYS

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

In this example, the array B is to be read column-wise.

The following code might be used to read the above data:

READ(5,1)( (A(I,J),J = 1,3),(B(K,I),K=1,4),C(I),I = 1,4)


1 FORMAT (8F5.0)
If the beginner finds the preceding method too confusing, he can use a combination of a
DO loop and an implied DO list as follows:

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:

SHOP 1 XX. XX. XX. XX. XX.


SHOP2 XX. XX. XX. XX. XX.X
SHOP3 XX.X XX.X XX.X XX.X XX.X

The following code can be used to generate the preceding output:

Shop number Hours lost


f /
WRITE(6,1)(I, (A(I,J),J = 1,5),I = 1,3)
1 F0RMAT(8X, 'SH0PM2,5X,5F10.1)
generates 1 ,
A^^ , A^j, A13, Ai4,Ai5,2, A21 , A22/ • -3, • -Ajs

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
)

320 TWO- AND THREE- DIMENSIONAL ARRAYS

The following code can be used:


Average lost for each
Machine numbers Shop number Hours lost machine
\ \ / /
WRITE(6,1)(K,K=1.5) ,(I,(A(I,J),J = 1,5),I = 1,3),(S(J),J = 1,5)
1 FORMAT 1 T35 MAINTENANCE ANALYSIS //T24 5 MACHINE
(
'
' , ,
'
2X // '
, (
'
M2 . )

*3(8X, 'SHOP' ,I3,5X,5F10. 1/) ,T25, 'AVERAGE' ,5F11.2) 1


'

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

stead of the one shown.


Another example illustrates the power of the two-dimensional arrays for input/
output considerations. Suppose it is desired to print the following multiplication tables:

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

1*10=10 2*10 = 20 3*10 = 30 10*10 = 100

The following code could be used:

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.

8-2-5 Three-Dimensional Arrays


A three-dimensional array is a data structure which can be accessed using three subscripts.
A three-dimensional array can be visualized as a cube containing several two-dimensional
arrays. Consider an array specified by:

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)

Any element of the cube can be referenced by Q(IR,IC,ID),


where IR indicates the row.
IC indicates the column.
ID indicates the depth, i.e., which of the two-dimensional arrays the element is in.
Input/output and processing techniques for three-dimensional arrays are similar to
the techniques for two-dimensional arrays. For example, suppose Widgets, Inc., referred
to in Section 8-1, has twojactories, each containing three shops of five machines each. An
array to store the data regarding the repair records of machines could be specified by:

DIMENSION A( 3, 5, 2 )

Shop Machines Factory

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 \

A(2.2,2) Shop 2 I Factory 2


A(1,2,2) A(l,3,2) A(1,4,2) A(l,5,2) Shop 1 )

Shop 3
j
A(2,l,l) A(2,2,11 Shop 2 \ Factory 1

Ad.l.i: A(1,2,1) A(1,3,1) A(1,4,1) Ad, 5,1) Shop


op 1 /

Hours losr on machine 1 Hours lost on machine 4


of shop 1, factory 1 of shop 1, 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.
) )

322 TWO- AND THREE- DIMENSIONAL ARRAYS

DIMENSION A( 3. 5. 2) ,S(5 Three shops, five machines, two factories.


READ (5,1) (((A(I,J,K),J = 1,5),I = 1,3),K=1,2
1 F0RMAT(5F2.0)
DO 30 J = 1 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
(
'
'
, ,
'

WRITE (6, 3) (A(I,J,K),J = 1,5),I = 1,3


(

40 CONTINUE
3 FORMAT (20X,5F6.0)
WRITE (6, 4) (S(J),J = 1,5)
(

4 FORMAT OAVERAGES T21 5F6 1


' ' , , .

STOP
END

Figure 8-5 Sample Program to Process a Three-Dimensional Array.

8-2-6 Internal Representation of Multidimensional Arrays

Internally, two-dimensional arrays are stored as a linear sequence of elements in column


order. For example, an array, A, with three rows and three columns is stored as follows:

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:

RHAD(5,3)(A(IJ),J = 1,3),I = 1,3)


TWO- AND THREE- DIMENSIONAL ARRAYS 323

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

REAL X( 3, 4)---^ Note


READ 5 3 X
( , )
^^
3 FORMAT (3F4.0)

This code will result in all 12 elements of X being read, with three data items per card. The
data can be visualized as:

X(l,4) X(2,4) X(3,4)

X(1,3) X(2,3) X(3,3)

X(1,2) X(2,2) X(3,2)

X(l,l) X(2,1) X|3,l)

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

3. Can I initialize two-or three-dimensional arrays in a DATA statement?


Answer: Most systems will allow it. For example:

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.

4. Can I change the implicit mode of a multidimensional array?

Answer.Yes, in the same way as in one-dimensional arrays. For example:

REAL M 4 7 X 3 5
( , ) , ( ,
The elements of M are real.
INTEGER X 3 47 ( ,
)
The entries of X are integer.

DOUBLE PRECISION MAT(3,5) MAT consists of double-precision elements.


LOGICAL X(5,2)
COMPLEX T(51,4) ,IT(3,1) \

5. Is there any limit to the size of a multidimensional array?

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.

8-4 PROGRAM EXAMPLES


8-4-1 A Frequency Distribution

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

8-4-2 Flagging Example

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.

INTEGER R,S, SEAT (10,6)


C SET ALL 60 SEATS TOO
DO 10R=1.10
DO 10 S= 1.6
10 SEAT(R,S)=0
C THE TICKETS SOLD ARE READ IN AND THE APPROPRIATE LOCATIONS ARE SET TO 1

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

Figure 8-7 A Flagging Example.


)

328 TWO- AND THREE- DIMENSIONAL ARRAYS

8-4-3 Alphabetic Data ^.^


/,A<L>-.ti>^

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.

INTEGER ADDR( 100,4) CITY (100,2) .STATE (100) ZIP (100)


, ,

DIMENSION NAME (100,5)


K=l
10 READ (5,1, END = 20) (NAME(K,J) ,J = 1,5) (ADDR(K.J) ,J = 1,4) ,

*(CITY(K,J) ,J=1,2) ,STATE(K) ,ZIP(K)


K=K+ 1
GOTO 10
20 K = K-1
C K IS THE NUMBER OF NAMES/ADDRESSES TO BE PROCESSED
DO 40 L= 1,4
D040M = 1,K
40 WRITE (6, 3) (NAME(M,J) ,J = 1,5) (ADDR(M,J) , ,J = 1,4)
*(CITY(M,J) ,J=1,2) ,STATE(M) ,ZIP(M)
,

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

Figure 8-8 Mailing Label Program.

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

8-4-4 A Three-Dimensional Array Example


A data processing class consists of ten students. Each student receives a grade on three
separate program tests (PI . P2, P3) and on three separate math tests (Ml. M2, M3). Com-
pute each student's overall average (combining programming and math test scores) and

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:

Math scores of student 2


Programming scores of student 2

Math scores of student 1

Programming scores student 1

The program to solve this problem is shown in Figure 8-10.

DIMENSION A (3, 10,2) ,AV(10)


DO 100 J = 1,10
100 AV(J)=0.
READ(5,1)(((A(I,J,K) ,I = 1,3),K = 1,2),J = 1,10)
1 FORMAT 3F2 ( .
)

DO 10 1 = 1,3
DO 10 J = 1,10 Sum of all grades
DO 10 K = 1,2 per student.

10 AV(J) =AV(J) +A(I,J,K) Math scores, Math scores,

DO 20 J = 1,10 student 1 last 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.
.

LARGEST SCORE ON THIRD TEST IS 96 .


TWO- AND THREE- DIMENSIONAL ARRAYS 331

8-5 PROBING DEEPER


8-5-1 Graphing
It is often desirable to produce graphic output from a computer program. A scientific
problem may require the graph of a function; a business problem may require a bar graph.
Both types of graphs can be produced by FORTRAN programs.
A basic technique of graphing uses an array to represent a line of output. Each ele-
ment of the array stores one character to be printed on the line. The program can then
store any desired character into positions on the line prior to printing the line. In this sec-
tion we shall examine techniques for producing bar graphs.

Example

Data regarding sales for a week have been tabulated as shown below:

Day
) )

332 TWO- AND THREE- DIMENSIONAL ARRAYS

INTEGER BLANK CHAR ,

DIMENSION LINE( 20)


DATA BLANK/' '/CHAR/'*'/
WRITE (6,1)
1 FORMAT IDAY TIO SALES
( ' ' , , '
'

Print 7 lines _D0 20 IDAY = 1,7


READ 5,2 )KSALES
(

,
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

Figure 8-11 Horizonlal Bar Graph Example.

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

INTEGER CHAR GRAPH (10,7)


,

DATA GRAPH/70*' '/.CHAR/'*'/


DO 20 IDAY= 1,7
READ 5,2 )KSALES
(

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

334 TWO- AND THREE- DIMENSIONAL ARRAYS

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.

a. ( (A(I,J) ,1 = 1,3) ,J = 1.2) FORMAT (8F3. 1)


b. ( (A(I,J) ,1,1 = 1,3) ,J = 1,2) FORMAT 2 F3 1 12 /F3 .1,12)
( ( . ,
)

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.

7. Assume arrays A, JSUM, and VAR contain the following data:


TWO- AND THREE- DIMENSIONAL ARRAYS 335

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-

ment using the DO list.

a. b.

r ^13 '^23 ^33 ^43


r b, b^ bj
^12 ^22 ^32 ^42

^11 ^21 ^31 ^41 ^14 ^15 ^16

r ^11 ^12 ^13

d.

^b^ ^51 ^61 "^ei

^31 '^31 ^41 ^^41

'^n "^ll '^21 '^21

r
336 TWO- AND THREE- DIMENSIONAL ARRAYS

b. Calculate the sum of the elements in the third row.


c. Find the largest value in the first column.
d. Create a linear array, B, consisting of five elements initialized to zero. Calculate
the sum of each column of A, storing the result in the corresponding column posi-
tion of B.
e. Add corresponding elements of rows 2 and 3 of the array A, storing results in row
3,that is, A(3J) = A(3,l) + A(2J),etc.

f. Interchange column 3 and row 4.

g. Compute the sum of the entries of the first diagonal.


h. Compute the sum of the entries of the second diagonal and determine the largest
entry of that diagonal,
i. Read values for I and J so that I < I, J < 5, and interchange row I with column J.

12. Read in two arrays, C and D, of size 3X3, given the following input on one card.

1_2J 9_2_4 4_5_6 7_8_9


Row I ofC Row I of D Row 2 of C Row 2 of D

13. Write the code to determine the smallest element of an array. A, of size 10 X 10 and its

position in the array (column and row).

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

Row Row 2 Row 'r40

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

8-6-2 Programming Problems

8-6-2a Two-Dimensional Arrays

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.

1979 Optional State Sales Tax Tables

Your itemized deduction for general sales Alabama'


tax paid can be estimated from these tables Income Family size Over
plus any qualifying sales taxes paid on the 1 2 3 4 5 5
items listed on page 16. To use the tables: $1— $8,000 93 115 122 131 142 160
Step 1 — Figure your total available in- $8,001— $10,000 109 132 142 153 165 185
come. $10,001— $12,000 124 147 161 173 187 208
Step 2— Count number of exemptions $12,001— $14,000
the 138 161 178 191 206 228
for you and your family. Do not count ex- $14,001— $16,000 152 174 194 209 225 248
emptions claimed for being 65 or over or $16,001— $18,000 164 186 210 226 242 266
blind as part ofyour family size. $18.001— $20,000 176 197 225 242 259 284


^?^''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
^

Student number Five test scores


338 TWO- AND THREE- DIMENSIONAL ARRAYS

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

Democrat Republican American

1,2.4,5 2,3,5 2,3,4,5

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

JMAR IS 5 2 MANUEL GLEASON MARIS

C GLEASON 5 2

( HORN 5 2
GOLDBERG
LGOLDBERG
MANUEL
3
3

1
1

r HORN

Name
/ Row
/
Seat
I

In deference to the passenger's selection of a seat on a particular row rewrite the


above problem in such a way that if the passenger's seat is already taken, the as-
signment of the next available seat will start at the row chosen by the passenger
rather than the first row.

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

Salesperson Date of sales Sales amount

111 012381 100.00


222 012481 250.00
111 012581 300.00
222 012781 200.00
334 012881 57.50
TWO- AND THREE- DIMENSIONAL ARRAYS 341

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

Salesperson number Date of sales Sales amount Total amount


111 012381 100.00
111 012581 300.00
400.00
222 012481 250.00
222 012781 200.00
450.00
334 012881 57.50
57.50
Total sales 907.50

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:

a. Sort both arrays in ascending order by time.


b. Print each heat with list of names for each heat (four names per line).

c. Print names of swimmers with faster than average swimming time (one per line).

For example:

N(l,l) N(l,2) N)l,3) N(l,4)

BOIL
N(2,l)

N(16,!)
342 TWO- AND THREE- DIMENSIONAL ARRAYS

The output should be similar to the following:

HEAT NAMES
1 Name 1, Name 5, Name 9, Name 13
2 Name 2, Name 6, Name 10, Name 14

4 Name 4, Name 8, Name 12, Name 16

SWIMMERS WITH FASTER THAN AVERAGE SWIMTIME


Name time
Name time

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.

Life insurance premium payments

JOHN LIVELONG
Age Annual premium Total premium/ 6 years

20 — —
21 — —

26 — —
The formula to compute the yearly premium for a $1 policy is

Mr where x is the age at issuance of policy,


P=
;y _ yy " n is number of payment years,
the
A/.V and N^ are given in the table below.

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:

Commutation columns — interest at 2 'A percent


(based on 1958 CSO mortality 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-

lows them one at a time to their escape or absorption.

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

The output should be similar to:

Percentage escapes XXX.


Percentage Absorbed XXX.
Escapes through rightmost points XX
Particles over 500 moves XX

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.

19. Following is a questionnaire used in a survey to determine people's attitudes toward


abortion:

Abortion attitude survey

Children D No childrenD Widowed D Divorced D


MaleD Female D Married D Single D
Age group: Below 20 D 20-30 31-40 41 -above D
If you are opposed to abortion, answer part A below.
If you are not opposed to abortion, answer part B below.
If in part A or part B there are questions about which you feel undecided, leave both
boxes blank.

Part A If you are opposed to abortion, is it:

Yes No
D D On religious grounds?
D n Because you believe the fetus has an absolute right to life?

D n Because you believe physical pain is inflicted on the fetus in


the abortion process?

n D Do you feel abortion would be justified in specific instances


(such as rape, malformed fetus, danger to mother's life etc.)?

Part B If you are not opposed to abortion, is it because you feel:

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?

D D Unwanted children should not be born?

D D A fetus is an incomplete human being, and as such no moral


or legal laws are applicable to it?

n n Laws against abortion would increase criminal abortions?

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

b. Same as a for those favoring abortion (seven questions altogether).


c. Determine the number of undecided responses for each of the respondents and re-

cord these as follows:


Respondent 1 Respondent 2 Respondent 3
Respondent 4 Respondent 5 Respondent 6
. Respondent 10
. .

d. Determine the percentage of respondents opposed to abortion.


e. Determine the number of women between 20 and 30 years old, with children, who
are opposed to abortion.
f. Were there more men in favor of abortion than there were women?
g. Were there more single women against abortion than married women for abor-
tion?

20. A Data Noise-Elimination Problem. A common problem in the collection of


Digital
digital data via telecommunications is the phenomenon of noise momentary fluctua- —
tions in the signal. When the data being transmitted represent an image as in pictures
transmitted by satellites and space vehicles, noise results in obviously invalid random
black, white, and gray spots when the image is reconverted to visual form. In order to
eliminate at least some noise from a picture it is possible to examine the image in
digital form prior to converting it to visual form and replace noise elements by an esti-
mate of the correct signal. Finding noise elements can be accomplished by examining
the difference between each element and the elements surrounding it. Noise elements
generally differ drastically from the surrounding elements for example, a white ele-—
ment surrounded by black elements or a black element surrounded by white. An esti-
mate of the correct signal can be made by replacing the noise element by the average
of the surrounding elements.
Write a program to eliminate noise from a digitized image stored in a 30 X 30 ar-
ray. Each element of the array represents one "spot" in the image and stores a value
from to 9. Zero (0) represents white; 9 represents black; the values between and 9
represent shades of gray. An element can be assumed to be a noise element if it differs
in absolute value by 4 or more from five of its surrounding elements. For example,
consider the element A(3,3) in the array below:
There are eight elements surrounding A(3,3); the relevant differences are:

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.

Write a program to enhance contrast in a 30 X 30 digitized image described in

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

Word Word Word Word


cc 1-8 cc 10-17 cc 19-26 cc 28-35
Code Code Code Code

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

In general, if /I is m X n (m rows and n columns) and B is n X q, then the product


matrix C = A • B is of size mX q.The entry Q
of the product matrix can be computed
by multiplying the /th row of /I by theyth column of B as follows:

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

b. The XYZ Company is renting the five machines A, B, C, D, E from a tooling


company. The hourly rental cost for each machine is as follows:

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. (X + Y).Z = X.Z + Y-Z


b. (X.Y).Z = X.(Y.Z)
28. An n X n matrix A is said to be symmetric if and only if A = A . (See Problem 25d
above.) Write a program to demonstrate that

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

A~' = -- (A""'+r,A"'' + r.A""' + • • • + c,,.,!)

where the c's are all constants defined as

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')),

c„ = -1/A;(r„_, tr(A) + r„_,tr(A=) + + c, 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

For example, the inverse of a 2 X 2 matrix X is X~ = (X + r,!) where

c. = -l/2(c, tr(X) + tr(X2))andri = -,tr(X).


354 TWO- AND THREE- DIMENSIONAL ARRAYS

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

an edge connecting vertices and 3. A way of representing a graph in a computer is by


1

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.

A walk in a graph is defined as a series of vertices connected by edges. In the ex-


ample of Figure 8-13, 34 would represent a walk since edges exist connecting vertices
1

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.

Figure 8-13 Geometric Representation of A 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.

Figure 8-16 Sample Graphs.

8-6-2b Three-Dimensional Arrays


1. Temperatures are read into a 3 X 3 X 4 cube in the sequence shown in Section 8-2-6.
Write a program to determine the highest and lowest temperatures.

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.

(«lll, ^222, a^ii, ^444 I


fl|4l, ^232, ^323, 0414 1
CtC.)

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.

5. Write the program of Problem 17, 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).

Flight Plane Departure


number Origin Stops capacity time

700 State College Harrisburg 5 7:05 A.M.


Baltimore
Washington
701 Washington Harrisburg 5 9:00 A.M.
State College

430 State College Harrisburg 5 4:15 P.M.


Baltimore
Washington
431 Washington Baltimore 6:15 P.M.
Harrisburg
State College
TWO- AND THREE- DIMENSIONAL ARRAYS 357

Transactions (requests for seats)


358 TWO- AND THREE- DIMENSIONAL ARRAYS

Sample output from your program

Date
TWO- AND THREE- DIMENSIONAL ARRAYS 359

8-6-3 Answers to Self Test

1. a. Legal, b. Legal, c. Legal d. Missing parentheses.


e. Real number is invalid for size specification.
f. Variablemay not be used to specify array size.
g. More dimensions than allowed on most compilers.
h. Misplaced parenthesis i. 3*10 not allowed, j. Legal.

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

c. READ( )(C(2,K),K = 1,5)


d. READ( )(A(J,1) ,B(J) ,J = 1,3)
e. WRITE )(K,(A(I,1),(B(J),J = 1,3),I = 1,2)
(

f. READ( )(A(1,J),J = 1,3),(B(2,J).J = 1,3),(C(J),J = 1.3)


g. WRITE )(A(1,J),B(1,J),C(1,J),I,J = 1,3)
(

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

A(2,3) .A(3,3) ,J. 3 records.


d. A(1,1),B(1,1),A(1,2),B(1,2),A(2,1).B(2,1),A(2,2),B(2,2),
A(3,1),B(3,1),A(3,2),B(3,2). 12 records.
e. C(1),A(1,1),A(1,2),A(1,3),P(1,1),P(2,1),C(2),A(2,1),
A(2,2),A(2,3),P(1,2),P(2,2). 2 records.
f. A(1,1,1),A(2,1,1),A(1,1,2),A(2,1,2),A(1,1,3),A(2,1,3),
A(1,2,1),A(2,2,1),A(1,2,2),A(2,2,2),A(1,2,3),A(2,2,3).
2 records.

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 ( 2X 12F4 1214 F5


, . , , .
)

b. WRITE( )( (A(I,J) ,J = 1,4) ,(JSUM(I,J) ,J = 1,4) ,VAR,I = 1,3


FORMAT ( 2X 4F4 , 414 F5 . , , .
)

c. WRITE( )( (A(I,J) ,1 = 1,3) ,VAR, (JSUM(I,J) ,1 = 1,3) ,J = 1,3:


FORMAT ( 2X 3F4 , F5 314
. , . ,

d. WRITE( )( (A(I,J) ,JSUM(I,J) ,J = 1,4) ,1 = 1.3)


F0RMAT(4(F5.0,I5) )

e. WRITE( )( (A(I,J) ,JSUM(I,J) ,1 = 1,3) ,J = 1,4)


F0RMAT(6(F5.0,I5) )
) ) ) ) )

360 TWO- AND THREE- DIMENSIONAL ARRAYS

8. a . READ )((A(I,J),J = 1,4),I = 1,3)


(

FORMAT (4F5.0)
b. READ( )(A(1,J),J = 1,6),(B(I),I = 1.6)
FORMAT 2 3F5 0/( 3F3 ( . ) ,
( .
)

c. READ( )(A(I,1),B(I,1),I = 1,6)


F0RMAT(2(F4.0,1X,F5.0)
d. READ( )(A(I,1),B(1,I),I = 1.6)
F0RMAT(2(F5.0,F6.0)
e. READ( )((A(I,J),J = 1,3).(B(I.J),J = 1,2).I = 1,9)
F0RMAT(3F5.0,2F3.0)
f. READ( ) (
(A(I,J) ,J = 1,9) ,1 = 1,8) , (
(B(I,J) ,1 = 1,4) ,J = 1,2
F0RMAT(8(9F3.0/) ,
(3F4.0)
9. DO 11 = 1,4
D01J = 1,7 or DATA A/28* 0./
1 A(I,J)=0.0
10. DO 2 I = 1 . 16
D02 J = l,6
2 A(I,J)=J
11. a. DIMENSION A( 5, 5) ,B(5)
READ (5,1)((A(I,J).J = 1,5),I = 1,5)
1 F0RMAT(5F10.0)
WRITE (6,2)((A(I,J),I = 1,5),J = 1.5)
2 FORMAT (2X,5F10.0)

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

14. DIMENSION F( 40, 17) ,G( 680)

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

mile X = TAN( 25-/57. 296;


k\ Initial ship position
WRITE(6,10)X
I- .y25° 10 FORMAT (2X.F8. 4)
> A' = distance STOP
END
'
^1 Ship position one hour later
.4663

Figure 9-1 Distance Calculation.

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 FORTRAN SUPPLIED FUNCTIONS

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

of any arithmetic expressions. The general form of a function reference is:

function-name {argument-expression [,...])

v/hcTt function-nameis the name of the function.

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:

Outer parentheses identify the argument.

Y = SQRtJ(3.*(X1 +X2 + X3)-(X1 + X2 + X3) **2)/(3.*(3. - 1.)))


' '

Expression is to be evaluated as the argument.

FORTRAN-supplied functions are furnished by the computer manufacturer with the


FORTRAN compiler. These functions are stored in system libraries on magnetic disks or
other types of storage devices. The FORTRAN library of functions consists of
mathematical functions and other special functions described in the next two sections.

9-2-2 Mathematical Functions


Common mathematical functions supplied with FORTRAN are shown in Figure 9-3.
Note that there are restrictions on the range of values acceptable as arguments, for exam-
ple, in the square root and logarithmic functions. If an invalid argument is detected by a
function, an error message will be printed.
FUNCTIONS 365
) )

366 FUNCTIONS

The following are invalid references to mathemalical functions:

J= lABS(R) The function lABS must have an integer argument.


K = SQRT(3) The function SQRT must have a real argument.

9-2-3 Special Functions


Certain other functions shown in Figure 9-4 are also included in the FORTRAN libraries.
The mode conversion functions are used to change the mode of an argument. This mode
conversion can, of course, be accomplished by use of a replacement statement in which the

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.

then J = IFIX(A/B) + IFIX(A/4.) = 1 -H = I

The transfer of sign and positive difference functions requires two arguments. Consider
the following:

Function reference Value Function reference Value

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

9-3 YOU MIGHT WANT TO KNOW


1. Can an argument expression contain a reference to another function?

Answer: Yes. For example:

SQRT(ABS(X)) and SQRT SQRT( Y) (

2. is it better to use SQRT or **.5 to calculate the square root?


FUNCTIONS 367
368 FUNCTIONS

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.

4. Can an array element be used as a function argument?

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^

/ SMALL = AMINl (X(1),X(2).X(3).X(4),X(5),X(6),X(7))


It would, of course, be better for the programmer to write a function that would accept
the array as an argument to return the smallest element (see Section 9-5).

6. Are all FORTRAN-supplied functions stored in the system library?

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.

7. What if I dimension an array SIN(IO), and in my program I refer to Y = SIN(X); will

the sine function of X be computed?

Answer: No. The compiler will treat any reference to SIN as an array reference. There
are no "reserved words" in the FORTRAN language.

9-4 PROGRAMMING EXAMPLES


9-4-1 Prime Numbers
The program in Figure 9-5 provides a list of all the prime numbers between 5 and 10,000.
A prime number is a number which is only divisible by and by itself. To determine 1

whether a number N is prime, it suffices to check whether N is divisible by any integer up


to and possibly equal to n/N". For example, to determine whether 43 is prime one needs
only to check if 43 is divisible by 2, 3, 4, 5, or 6.
FUNCTIONS 369

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

divisible by J, I is not prime.

DO 5 I = 5 10000 2, , Skip all even numbers.


11 K = SQRT(FLOAT(I) )
Determine VT Argument of SQRT must be real
DO 4 J = 3,K,2
12 IF(M0D(I,J)*EQ-0)G0T0 6 Check if lis divisible by any integer
4 CONTINUE up to and possibly including >/r
Up write (6, 31) I Number is prime; print it.

5 CONTINUE
STOP
31 FORMAT (125)
END

Figure 9-5 List of Prime Numbers.

9-4-2 Break-Even Analysis


Systems analysts at the XYZ Company computed the revenue function associated with the
manufacture and marketing of a new company product. A cost function was also
projected for that product. Both functions are as follows:

Revenue function: y = IS.vp-*/' + 0.5

Cost function: v=^^


16
—2
I- ^- +
4
4

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

DIMENSION KLINE( 70)


DATAIR, IC, KBLANK/ 'R' 'C ,
,
'
'/ Select graphic s\ mbols for graph
WRITE(6,10)
2X REVENUE 2X
,

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

1 KLINE(I) =KBLANK Blank out the hne before inserting character.


J =R + 0.5 Round oft.

7 KLINE(J) =IR Insert the graphic character "R" on the hne.


L = C + 0.5
8 KLINE(L) =IC Insert the graphic character "C" on the hne.
WRITE(6,11)X,R,C, KLINE
1 FORMAT IX F3 3X F4
( 3X F4
, . , , , . , . , 3X 70A1
,

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

K = OdanX +y)*4 = .^6


\ = .2(UinX + 9)*4 = .17
X = 4(umX +9)*4 = 38

4(l.i[iX + 9)*4 = >4

\ = .V4(UinX + 9)*4 = }1
372 FUNCTIONS

DIMENSION LINE (72) Initialize the graphic symbols.


,

DATAKAST.KBLANK/'*' ' '/


X=
3 Y = TAN(X)
D04I = 1,72
4 LINE(I) =KBLANK
16 J= (Y + 9)*4+0.5 .5 is added to lake care of round-off.
IF(J.LT.O)GOTO 11 Check for outside the range.
5 IF(J.GT.72)G0T0 11
6 LINE(J) =KAST
WRITE(6,15)X,Y,LINE
15 F0RMAT(1X,F4.1,2X,F6.2,72A1
12 X = X+ .2
IF(X.LE.7)G0T03
8 STOP
11 WRITE(6,15)X,Y Print X.Y if outside the range.
GOTO 12
END

0.0
FUNCTIONS 373

9-5 PROGRAMMER-DEFINED FUNCTIONS


9-5-1 Programming Example
Teacher X at the beginning of the semester agrees with her students on the way in which
their final grades will be determined. If the average of their three test scores (at six weeks,
12 weeks, and final) is higher than their final, that average becomes their semester grade;
otherwise their score on the final determines their final if grade is more
grade (they pass
than 70). Let us write a program to read a deck of student records which each record
in

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:

NO. Tl T2 FINAL SCORE GRADE


1
374 FUNCTIONS

Main Program
FUNCTIONS 375

The correspondence between arguments can be visualized as follows:

Memory

t ^

1 ( Ij-^
376 FUNCTIONS

MAIN PROGRAM

TRANSFER
"AV = AVRGE(. .
.)

RETURN GRADE = LETTER TRANSFER


(. . .)

RETURN

CLASS = LETTER (. .
.)

Figure 9-9 Flovspath between A Main Program and Function Suprograms.

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

9-5-3 The Invocation Statement


The general form of a function invocation statement is:

function-name {a^,ai,ay, ^fln)

whQrQ function-name is the name of the function (any vaUd variable name), and a|,a2,flj,

,a^ are arguments to be passed to the function subprogram.


• •

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.

Consider, for example, the following:

X = 3.*SUB(Y)/SAM-h3 One argument is passed to the function.


AX = A(T,J,3) -hB(X**2,1.5) The function A has three arguments, while the
function B has two arguments.
IF(TRAP(X,K) -8)1,1,3 The function TRAP is part of an IF statement.
it is first evaluated and its value is compared
to 8.

Z = S1(A,B(1) ,3*I+K,J) SI has four arguments. Arguments can be


T = SUB2 SIN X Y - SUB2 (3.1,0
( ( ) , ) functions, too.

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.

9-5-4 The FUNCTION Definition Statement and the


RETURN Statement
The first statement in every function subprogram is the FUNCTION statement. The gen-
eral form of this statement is:

[type] F\JNCT\ON function-name ip^, p., p^, -^Pn)

whcTQ function-name is the name of the function, and

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

function is dummy arguments take on the values of the "real" arguments


executed, the
specified in the callingprogram. More precisely, the function processes directly the real
arguments through the dummy arguments.
The arguments in the invocation statement must correspond in numbeTj^ mode, and
order with the arguments in the FUNCTION statement. The argument names can be the
same or different. If an argument in a function subprogram is an array name, the array
should be declared in a DIMENSION statement in the function subprogram.
Return to the calling program is effected by the RETURN statement, which returns
control to the statement in the calling program where the invocation was made. Many RE-
TURN statements can be included in a function subprogram (see, for example, the pro-
gram in Figure 9-8). A distinguishing feature of the function subprogram is that at its con-
clusion the statement to which the return is made is variable (unlike the GO TO state-
ment). The return point depends on the statement at which the function was called (in-

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

Calling program Function subprogram

FUNCTION ALARG (A. B


IF(A.GT.B)GOTO 5
ALARG =B
Z = ALARG X Y ( , RETURN
WRITE(6,3)Z 5 ALARG =A
\\
RETURN ^^
END

IF ALARG (Z,T) -3.1)1,1,2


(
^'

Example 2

INTEGER QUIZZ INTEGER FUNCTION QUIZZ J K L ( , .

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

1 = 2 FUNCTION BAKER (X,Y, J


A = 7.0
Y = BAKER (3. 2, 9. 8* A, I

The arguments of BAKER must be two real

values followed by an integer value.

When BAKER is executed X = 3.2, Y = 9.8*7 = 68.6 and J = 2

Example 4

In this example, the function name participates as a variable in the subprogram.

DIMENSION A( 10) ,B(10 FUNCTION SUM(Z)


DIMENSION Z( 10)
= SUM
DO 10 1 = 1,10
X = SUM ( 10 SUM = SUM + Z(I)
RETURN
END
Y = SUM ( Note the DIMENSION statement required in

the subprogram. SUM (name of the function)


is used as an accumulator.

Example 5

DIMENSION A( 10) ,B(10) FUNCTION ALARG(X


DIMENSION X( 10)

X = ALARG A ( ) + ALARG B ( ALARG = X(1)


DO 10 1 = 2,10
When the RETURN statement is executed,
control is passed to the point at which the IFALARG.LT.X(I ALARG = X(I
function was invoked. First ALARG(A) 10 CONTINUE
is executed, then ALARG(B), then the RETURN
sum of the two largest numbers'is stored in X. END
) )

380 FUNCTIONS

Example 6

This example illustrates the use of several RETURN statements.

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.

Calling program Function subprogram

DIMENSION CLASSl (10,10) FUNCTION AVER ARAY NR NC ( , ,

DIMENSION CLASS2( 5, 5) DIMENSION ARAY NR NC ( ,


)

DIMENSION CLASS3 7 17 ( , AVER =

A = AVER (CLASSl, 10, 10) DO 5 I = 1 NR , Variable dimension


B = AVER(CLASS2,5,5) DO 5 J = 1,NC
C = AVER(CLASS3,7,17) AVER = AVER + ARAY (I, J)
TOT = A -K B -h C /3
(
)
AVER = AVER/(NR*NC)
RETURN
END

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

The following are invalid function references or function definition statements:

Calling program Function subprogram

X = AMAX(2. 1,3,4.) FUNCTION AMAX(X,Y,Z) "3" is integer and "Y" is real.

INTEGER SMALL FUNCTION SMALL(T,X) SMALL should be declared as


INTEGER in the subprogram.

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.

DIMENSION FUNCTION DAM(T(1),T(2),J)


Q(IOO) Subprogram arguments may not be
DIMENSION T(IOO)
C = DAM(Q(l),Q(2),-4) suscripted variable names.

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

TIP = (X + Y)/2 function subprogram.

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

Calling program Subprogram


Same name,
FUNCTION FICA(Z
different values
(since HOURS and RATE
hve not been passed as
HOURS = 30 arguments)
READ (5,1) RATE FICA = HOURS *RATE*Z
PER = 585 .

Z = FICA(PER)
1

382 FUNCTIONS

Example 2

Main program Subprogram

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 .

1^F0RMAT(F5.2) 30 WRITE (6,1) TAX


30 CONTINUE

Same statement numbers (valid — different programs)

9-5-5 Position of the Function Subprogram in the Job Deck


All user-defined function subprograms are separate physical and logical entities and as
such are compiled independently of one another. The compiler treats each function sub-
program as a new program in the job deck. Special system control cards (job control, work
flow, etc.) may be required to physically separate each program from one another as de-
picted in Figure 9-10. The student should determine the proper control cards required by
his or her computer system.

— End of file card

Job control cards separating


main program and
subprograms.

Figure 9-10 Job Makeup.


FUNCTIONS 383

9-5-6 Program Example

Write a program to compute the binomial expression C{n,m) =


m\{n — m)\

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:

C(6,2)=^ = ^±^:}±1- =15


2!4! (2.1H4.3.2.1)

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

Figure 9-H Combination without function subprogram.


N ) !

384 FUNCTIONS

INTEGER COMB. FACT


READ(5.1)N,M
1 FORMAT (212)
COMB = FACT N / FACT M * FACT N - M
(
)
( (
)
( ) )

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

Figure 9-12 Combination wilh Function FACT.

9-5-7 A Lottery Example


As a promotional gimmick, every patron of the Circle K gas station gets a lucky card with
three numbers on it ranging from 10 to 10,000. The station manager then draws at random
a number from any of the customers' numbers matches the one drawn by
1 to 10,000. If
the manager, the customer gets a dollar amount equal to one-tenth of his lucky number.
Write a program to read ten customer lucky cards and determine the dollar amount of any
lucky winner. For example, if the lucky card contains the numbers 50, 100 and 200 and the
manager draws the number 50, the customer wins five dollars.

To solve this problem we will write:

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

so, to compute the dollar win.

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.

2. The way which the


in FUNCTION statement is u.sed to declare that the program is a
function subprogram.

3. The way in which the function value in the function subprogram is returned to the call-

ing program through the name of the function itself.

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

Read the ten cards one at a time.. DIMENSION CARD( 3)


Call the function IRAND to choose a random DO 15 = 1,10
1
number from to 10,000. The arguments of
1
READ (5,1) (CARD (J ,J = 1,3,
the random routine are and 10,000. The I K = IRAND( 1,10000)
function WIN computes the amount won. if AMT = WIN CARD, K) (
^^
the customer loses, AMT = 0, The array WRITE(6,11)AMT
CARD is transmitted to the function WIN as 11 F0RMAT( 'OAWINOF' ,F10.0, 'CENTS'
well as the lucky number K, which is the ran- 15 CONTINUE
dom number returned by the function 1 FORMAT (3F5.0)

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

gram. Similarly, N is just a dummy name for


DIMENSION SLIP( 3)
the variable K, defined in the calling program.
DO 151 = 1,3
If no match exists between the numbers
IF(SLIP(I) -N)15,3,15
on the card and the number drawn by the
= 15 CONTINUE
manager, the value of the function is WIN
WIN =
0. If there is a match, WIN is one-tenth of the
RETURN
lucky number.
3 WIN = SLIP(I)/10
Note how the name of the function WIN
RETURN
returns the value of the function to the calling
END
program.

Function IRAND returns any integer value FUNCTION IRAND IBEG ITER ( ,

between IBEG and ITER (IBEG < ITER). In DATA IM IB IA/25211 32768 19727/
, , , ,

the case of this program, IBEG and ITER IA = M0D(IM*IA,IB)


take on those values passed by the calling pro- X = FLOAT (lA) /FLOAT (IB)
gram, i.e., IBEG = 1 and ITER = 10.000. The IRAND = X* ITER - IBEG + 1 + IBEG
( )

value X, as a result of the computations, RETURN


always a number from to The value
real I .
is

END
,,C.(T (%\^^
IRAND becomes any number from to I

Af ^V.\<L^
'<"

10,000. Note how IRAND transmits the func- - civop'


mo^U,"3^
tion value to the calling program.
L.^^^
(>s
^x'^''^
s--^

Figure 9-13 Random Number Lucky Win. tV\'


= c\^C.'^^^
PLO^I
tt.
^?
9-5-8 Why Use Function Subprograms?
A subprogram can be an aid in writing shorter and more compact programs. The pro-

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.

9-5-9 Statement Functions


As we have seen, FORTRAN allows the programmer to define his own functions through
the use of function subprograms. The function subprogram, in general, may require sever-
al lines of code and can produce several answers (more than one RETURN statement),
even though only one value can be returned to the calling program, in some cases where
the function is so simple that it can be expressed in one line of code and can only produce
one possible answer, the statement function can be used to great advantage. Statement
functions are generally used when a particular arithmetic expression needs to be evaluated
program. Unlike function sub-
for different values of the variable at different places in the
programs, which are compiled independently, statement functions are defined within (part
oO the program that uses the statement function. For example, if it is needed to evaluate a
second-degree polynomial several times in a program for different values of the variable,
the statement function POLY could be used as follows:

Program without statement junction Program with statement function

X = -5.6 POLY(X) =2.1*X**2-3*X + 1


Y = 2. 1*X**2-3*X + 1 X = -5.6
X = 2. 12347 Y = POLY(X)

IF(2.1*X**2-3*X + 1-T0T)1,1.3 IF ( POLY ( 2 . 12347 )


- TOT ) 1 , 1 , 3

T = 10.6 T = 10.6
SUM = SUM + SQRT 2 1*T**2 - 3*T +
( . 1 ) SUM = SUM + SQRT( POLY T (

The general form of the statement function definition is:

function-name {a^^a^.a^, •
-,«„) = expression

where function-na/ne is the name of the function (any variable name),


a^^a^My, •
s^n are dummy arguments which must be nonsubscripted variable
names, and
FUNCTIONS 387

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:

Name of Dummy Arithmetic expression


Function arguments involving dummy arguments
'

Function \ y'T\ I I

dejiniiion AV(X.Y,Z)= X+(Y + Z)/2.+10

READ (5,1) SUM First executable statement

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 ^

a. F(X) = (X-h2)/(X-2) +X**2 F(X) =


^ _ ^
+ X-

• The value of Y will be 19.

• The value of Y is computed, substituting


Y — p(4 0) T for X in the function definition.

Y = F(T)
( Q
C ;

388 FUNCTIONS

BETA(Y) =A*Y**2 + B*Y + C The expression involves variables other than


the formal argument Y.

READ The values ofA.B.andCare established. The


( 5 , 1 ) A B , ,

function will be evaluated for values of IX


DO 10 IX =1,10
varying from to 10. Note that the mode of
Q = BETA (FLOAT (IX
1

the actual argument and the formal argument


10 WRITE (6, 2) IX,
must be the same. The FLOAT function con-
IX to real mode.
verts the integer

c. RAD DEGREE = DEGREE/57 296


( ) .
RAD converts degrees into radians.

Statement functions can be used as arguments

(RAD (30. of any other functions.


Y = SIN

d. B1(Y) =ABS(Y-1. ) Statement functions can reference other pre-


B2(Y) =L0G(B1 )(X) /lO viously defined statement functions. Bl and 82
are functions.

Z = B2(-5 Z = LOG(| - 5 - l| )/IO= LOG(6)/I0

COMB(N,M) = The COMB function could be used in the pro-


'
FACT N / FACT M *FACT N - M
(
(
(
gram of Figure 9-12. Note the use of the
) )

user-defined function subprogram F.ACT.

K = COMB (8, 2

L PAY HRS RATE = HRS*RATE + BONUS


(
, )

BONUS = 50.
X = PAY(40. ,5. )
X = 5*40 + 50 = 250
BONUS = BONUS -K 10
Y = PAY(50. ,4. )
Y = 4*50 + 60 = 260

g. FAHR(C) =9./5.*C + 32 The variable C is used as an ordinary variable


in the program, even though it is also used as a
dummy argument.

C = 0.
TEMP = FAHR( 100
The value of C is
C = C-Fl.
I
FUNCTIONS 389

h. REAL INT The FORTRAN-supplied function INT is re-


INT(R,N) =PRIN*(1. +R)**N defined as a user function. Note the use of the
subscripted variable A(3). In this case, R =
A(3)andN = K*360 + J.

DUE = INT(A(3) ,K*360+J

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

10 READ 5 6 END = 200 Al Bl CI A2 B2 C2


( , , ) , . . , ,

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

5 FORMAT 2X SYSTEM WILL NOT CONVERGE


(
'
, ,
'

6 FORMAT (6F5.0)
200 STOP
END
FUNCTIONS 391

9-6 EXERCISES
9-6-1 Self Test

1. Write FORTRAN statements to translate each of the following:


a. a = sin-'x — cos^x
b. z = e' — e~'
c. X = \/ \p- q\
d. Find the largest of A, B, C, D, and E.
e. Find the smallest of I, J, K, and 3.

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.

a. X = MAX (2. 1,3. 1,4) FUNCTION MAX (X,Y,Z


b. IF(LOW(I,J,K) )1,2,3 FUNCTION LOW (K, I, J
c. REAL MALL FUNCTION MALL (X,T)
X = MALL X T ( ,

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

1. MIM = SUB(X,2*J,9.8) FUNCTION (X,K,S) ^O'^"'*'*^


m. SON = OF (A, GUN) FUNCTION OF(A,NON)
)

392 FUNCTIONS

n. DIMENSION B( 5) FUNCTION TIP (A, B,C)


X = TIP(B(1) ,X,B(5) ) DIMENSION A( 5):=-
o. DIMENSION A( 5) FUNCTION CAN(T J ,3) ,

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

r. X = COT(X) FUNCTION COT(X)


7. Which of the following function subprogram declarative statements are incorrect?
State the reason in each case.

a. FUNCTION AD (A,B,C + D) e. FUNCTION A( A ,B C , )

b. FUNCTION SORT (X,Y,Z) f. FUNCTION B( A C( 1


,
) )

c. FUNCTION FUNCTION(X) g. FUNCTION (A, AA,B)


d. FUNCTION SQRT( I) h. FUNCTION C( A .B ,B)

8. Which of the following statement function definition statements are invalid? State rea-
sons.

a. SOME(A(I) ,B) =A(I)*2 g. HI 1 ,2 3) = A+ 1 + 2 + 3


( ,

b. SQRT(A,B) =SQRT(A) +SQRT(B) h. A(L) = L + AL + SIM


c. T(Y)=Y**2 + 2 Y = A(K) -AL-SIM
A(X) =T(X) +1 i. ADD(X,Y,Z) =X + Y + Z
d. SQRT(X) =X**0.5 T = ADD(X*Y,T)
e. R00T = -B + SQRT(B*B-4*A*C) j. C(X + 1,A) = (X + 1)*3 + A
C(B) =B**2 + FUN k. MIX(K) = LOG(K + 1
f. LONE(I,J,K) =I*J*K S = MIX(3.1)+3
L = LONE (1,2,3) +I*J*K

9. Determine whether the following statements are true or false. -^ t^


"^ /

a. The mode of a FORTRAN-supplied mathematical function is determined by its

arguments.
^ b. The argument of the ABS function must be real.

f^ c. In-line functions are part of the function libraries.


d. Y = SQRT(3) could mean to store the third element of array SQRT into Y if

SQRT is dimensioned. ^ /-t-t^^


e. The trigonometric supplied functions are actually function subprograms. H
f. The END statement in some cases is not needed in function subprograms.
"T g. Function subprograms can return only one value to the calling program.
f- h. The function reference = STAN(X,Y) is invalid, since and STAN are not of
I I

the same mode,


i. In some cases, function subprograms can be compiled concurrently with the call-
ing program.
r^ j. Since only one value can be returned by a function subprogram, only one RE-
TURN statement is allowed in the subprogram.
FUNCTIONS 393

k. In the definition of a function subprogram, a dummy argument cannot be a sub

scripted variable name.


1. Array names are permitted as arguments in a function subprogram. /
m. Statement functions are compiled independently of the program in which they are \^

'"

n. A statement function can be coded in only one statement. '


-^f
o. Real arguments used in a reference to a statement function can be subscripted var- ~f^
iables. S^fcvC^^'V- ^^^

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

12. Write a function to perform the following:

a. C^ = A^ + B^-2ABC0S(C) Length of one side of a triangle.


b. A = P( 1 + I/J )^*^ Compound interest: P is fixed.

c. A = P(1+R)'^ Simple interest: Pis fixed.


d. 1/R = 1/Rl + 1/R2 + 1/R3 Total resistance.
e. Q= .92A(T, -To)/H Heat flow: H is fixed.

f. e' = 1 + X + XV 2 + XV3
!

g. Y = Be"^''cos(V b^-a^x- t)

13. Specify the output obtained by the following two programs:

a. IMPLICIT INTEGER (A-Z) Data for part a:

READ(5,7)A.B,C i Ja ii g-'l ^l-^2.-^\


7 FORMAT (212, 13) * card column 1

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 '

P0L = A*X**2 + B*X + C 2x''^^3X-/^


RETURN -^L^^ 3- tQ '~ - ^'
.

END 2,
'
,
J ) ,

394 FUNCTIONS

b. IMPLICIT INTEGER (A-Z) Data for part b:


INTEGER ITEM(3) 11461733 card 1
REALPRICE(3) 1172 845
DO 10 1 = 1,3 1166142
10 READ(5,11)ITEM(I) ,PRICE(I 1172
11 F0RMAT(I4,F4.2)
READ (5, 12)
12 FORMAT (14)
L = FIND (ITEM, J)
IF(L.LT.0)G0T08
WRITE(6,15)ITEM(L) ,PRICE(L)
15 F0RMAT(1X,I4,2X,F5.2)
STOP
8 WRITE(6,13)J
13 FORMAT IX 14 IX COULD .

( , , '
'

'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

9-6-2 Programming Problems

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

two miles off shore?

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.

6. A salesperson is assigned a commission on the following basis:

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.

9. Write a function subprogram to evaluate a 2 X 2 and a 3 X 3 determinant.

10. Write a function subprogram to evaluate C(N,M) (see Section 9-5-6).

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

If item has not been sold in last 30 days, discount is 10 percent.


If item has not been sold in last 60 days, discount is 20 percent.
If item has not been sold in last 90 days, discount is 40 percent.

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.

12. Write a program to do the following:

a. Array A contains N elements (N < 100). Write a function subprogram to perform


asequence check on the elements of A. If the array is in sequence (ascending), re-
turn a value of I

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

Input Average data set 2 is 70.0


Combined average is 56.6

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

an array of variable length (see Section 6-4-3).

17. Write statement functions for each of the following:


a. K = Trr^

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

startmg with .v = 1 until |a-


,

- 43,|
,

< .01.
A-

19. Input values for a and /. Write a program using statement functions wherever possible
to compute .v as follows:

if fl > compute x = at + T' + at -\


h [a - \)t
'

+
i'-iy
I ,
FUNCTIONS 397

ifO < a < 1, compute A- = t' + at +—+ {a - \) i~^ + (a -—)'''

if a < 0, compute .V = log(|a|.0 + /- +al H \- (a - I)?"'

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

21. It can be shown that:

. . .

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

22. The number e can be defined as the limit off


J
as « tends to infinity:

e = liml I

,,-a. \ n /

Using this definition of e write a program to determine n so that:

e - (-^^-^ < .001 Use the function EXP for e.


I
j I

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

Recall that .v must be expressed in radians.

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

the following series definition?

"

e'= 1 +—+—+— +• +— +
1!
2

2!
3

3! n\

How many terms of the series do you need to improve on EXP(l)?

26. The president of the XSTAR Company company's present account-


realizes that the
ing procedures are too slow, too inefficient,and not sufficiently accurate to deal with
the increasing annual volume of processing of the company. Plans have been made to
replace manual accounting operations with a wholly computerized system. The cur-
rent total manual operating costs in dollars in terms of annual processing volume is
given by >' = A- + .5 (where y is the dollar cost and x the annual processing volume).
Projected total computerized cost is given by the formula v = .75a' + 2. The antici-
pated annual processing volume will be close to four units. Write a program to:
a. Determine graphically whether the president's decision to switch to a com-
puterized system is economically sound (graph both lines).
b. Determine graphically the breakeven point (the annual volume of processing that
would justify the president's plan for changing methods of operation).
Realizing that an annual volume of processing of four units is not sufficient
to warrant such a change in operations, a compromise is effected. The new opera-
tional procedures will involve both manual and computer operations. The cost at-
tached to such a new system is given by y = .445a +1.5. Write a program to:
c. Determine graphically whether such a system would be economically beneficial to
the company.
d. Determine graphically the breakeven point for the total computerized system ver-
sus the computer manual plan.

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:

y = n(\5xe-'h and y = n(—- — +—+4\

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.

31. What you use on v = /x to get a feel


scale factors could 1 for the shape of the graph of
that function? Experiment by graphing that function.

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.

33. Generalize Exercise 32 by accepting the radii from input.

9-6-3 Answers to Self Test

1. a. A = SIN(X)**2 - C0S(X)**2 b. Z = EXP(X) - EXP(-X)


c. X = SQRT(ABS(P- Q)) d. ALARG = AMAX1(A,B,C,D,E)
e. KSMAL = IVIIN0(I,J,K,3)

2. To round the value in A to the nearest hundred:

A = 100*IFIX((A + 50.)/100.).

To round the value in A to the nearest thousandth:

A= IFIX((A +,0005)* 1000.)/ 1000.

To round the value in A to the nearest whole number:

A = IFIX(A + .5).

3. a. 9. b. 3. c. -2 d. -100. e. 2.4. f. 102.4. g. 0.

h. -2.4 i. 100. j. 83.4. k. 2. 1. 1.


400 FUNCTIONS

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

6. a. Invalid: 4 and z different mode. b. Valid. c. Mode of function must be


the same in the calling program and in the function definition. d. Valid: no ref-
erence to a function is made since A is an array in the main program. e. 2 + S
and mixed modes.
J are f. Valid. g. Valid. h. Function has no name,
i. C0T(3) should have three arguments. j. Invalid: subscripted variable T(l).
k. Function reference cannot occur in I/O statement list. Number of 1.

arguments do not agree. m. GUN, NON different mode. n. Valid,


o. Dummy argument must not be a constant. p. Function is not assigned a val-
ue, q. Valid. r. Valid.

7. a. Dummy argument cannot be an expression. b. Valid. c. Function


name too long. d. Valid (user defines own SQRT). e. Function name and
argument cannot be the same. f. Argument cannot be subscripted variable.
g. Function name is missing. h. Valid.

8. a. Dimensioned variable cannot be in dummy argument list. b. Function


cannot refer to itself, and number or arguments must be the same as in function defi-
nition, c. Valid. d. Valid. e. Function definition must precede ex-
ecutable statements. f. Valid: dummy variables may be used as actual variables
in a program. g. Dummy
arguments may not be constants. h. Valid.
i. Number of arguments in function reference and in function definition do not
match. j. Expression (X + 1) cannot be used as a dummy argument,
k. Mode of actual arguments must match mode of dummy arguments.
9. a. F. b. T. c. F. d. T. e. T. f. F. g. T. h. F.
i. T. J. F. k. T. 1. T. m. F. n. T. o. T.

10. FN(L,J,A) =L*X*X + J*X-A


11. FN(L,J,A,Y) =L*Y*Y-i-J*Y-A
12. a. SIDE(A,B,C) = A*A + B*B -h 2 *A*B*COS( C .
)

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

f. E(X) =1. -hX + X*X/2. +X**3/6.


g. F(A,B,ASM,X,T) = A*EXP( -ASM*X *COS( SQRT B*B - ASM* *2*X^ - T ) ( )j

13. a. 90,112. b. 1172,8.45.


10
SUBROUTINES

10-1 PROBLEM EXAMPLE


Dr. X has two FORTRAN classes. Array FINAL contains the ten final grades of class
1 1

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

^ pass arguments to the subprogram.

2. The SUBROUTINE statement, which declares that a subprogram is a subroutine.

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

Program without Subroutines Program with Subroutines

REALFINAL1(10),FINAL2(8),FINAL(10) REALFINALl(lO) ,FINAL2(8) ,FINAL(10:


READ(5,7)FINAL1,FINAL2 READ (5,7) FINALl FINAL2 ,

WRITE(6,4)FINAL1,FINAL2 WRITE (6,4) FINALl FINAL2 .

SUM = CALL AVRGE FINALl AVI 10 ( , ,

D05I = 1,10
SUM = SUM + FINALI(I) CALL AVRGE FINAL2 AV2 8 ( , , )

CONTINUE
AVI = SUM/10 IF(AV1.GT.AV2) GO TO 20

SUM = CALL ADJUST FINALl 10 FINAL AVI ( , , ,

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

' FINALl /IX 10F5 1/ '


, .

BONUS = AVrO.05 IX, 'FINAL2 7'1X,8F5.1)


D08I = 1,10 FORMAT (10F5. 1)
FINAL(I) = FINALI(I) + BONUS END
CONTINUE
WRITE(6,6)BONUS,(FINAL(I),I = 1,10) SUBROUTINE AVRGE CLASS AVG N ( , , )

REAL CLASS (10)


GO TO 2 SUM =
D0 5I = 1,N
20 BONUS = AV2*0.05 SUM = SUM + CLASS(I)
D09I = 1,8 5 CONTINUE
FINAL(I) = FINAL2(I) + BONUS AVG = SUM/N
CONTINUE RETURN
WRITE(6,6)BONUS,(FINAL(l),l = 1,8) END

2 STOP SUBROUTINE ADJUST CLASS K FINAL AVG ( , , ,

REAL CLASS 10 FINAL 10 ( ) . (

4 FORMAT(1X,'FINAL171X,10F5.1/ BONUS = AVG*0. 05


1X,'FINAL271X,8F5.1) D09I = 1,K
6 F0RMAT(1X,'B0NUS = ',F5.1/ FINAL I = CLASS I + BONUS
( ) ( )

MX, 'ADJUSTED GRADES71X,10F5.1) 9 CONTINUE


7 FORMAT(10F5.1) WRITE (6,6) BONUS FINAL I 1=1 K ,
( ( ) , ,

END RETURN
6 FORMAT IX BONUS= F5 1/
(
,

' ' , .

* IX ADJUSTED GRADES /IX 10F5 1


.
' '
, .

END

Figure 10-1 A Sample Program with Subroutines.


)

404 SUBROUTINES

REALFINAL1(10),FINAL2(8),FINAL(10) FINALl contains the ten scores of class!. FINAL2 contains


the eight grades of class2. and FINAL is an array into which
the adjusted scores will be stored (either eight or ten scores).
READ(5,7)FINAL1,FINAL2 Read scores from both classes into FINALl and FINAL2 an
7 FORMAT(10F5.1) write them out.
WRITE(6,4)FINAL1,FINAL2
CALL AVRGE(FINAL1,AV1,10) Call the AVRGE program, which will compute the average
(AVI) often grades stored in array FINALl. In subroutine
AVRGE the array FINALl isreferredtoasCLASS.AVI is
referred to as AVG, and N equal to ten. The subroutine
is

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

are transmitted to program ADJUST. Array FINAL which


does not contain any data yet, is made available to
GO TO 2 ADJUST. Progam ADJUST adds five percent of AVI
(BONUS) to each class score and stores the resulting
I ad-
justed scores in FINAL.
20 CALL ADJUST(FINAL2,8,FINAL.AV2) FINAL, upon return from ADJUST, will contain the adjusts
scores of the eight grades stored in FINAL 2, and BONUS w
be equal to five percent of A V2.

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

Figure 10-2 Sample Program with Explanations.


SUBROUTINES 405

First call to AVRGE

Memory

FINAL 1 |60

FINAL 2
406 SUBROUTINES

Program with task sharing Main program with


( suhrouiinesi same tasks
repetition oj
without \uhri)iitine
MAIN PROGRAM

Transfer
-CALL AVRGE
Return

CALL AVRGE
AVRGE CODE
CALL ADJUST-

CALL ADJUST-
ADJUST CODE

END

Subroutint
±
ADJUST CODE

Subroutine

Figure 10-4 Flowpath between A Main Program and Subprograms.

10-2 FORTRAN STATEMENTS


10-2-1 Subroutines
A subroutine is an independently compiled block of code sometimes called a subprogram.
The prefix sub- implies that a subroutine is not really a complete program, in the sense that
if it were executed all by itself it would not produce meaningful results. Subroutines are
usually written to carry out generalized procedures that are data-independent, for exam-
SUBROUTINES 407

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.

10-2-2 The CALL Statement


The general form of the CALL statement is:

CALL subroutine-name [(a 1,02,03, • • •, On)]

where CALL is a required key word,


subroutine-name is the name of the subroutine (any valid variable name), and
Oi, 0:, • • •, fl„ are arguments to be passed to the subroutine. These arguments may be
variables, subscripted variables, array names, constants, expressions, or function
names. Arguments are used to either transmit data from the calling program or to re-

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

evaluated and passed to the third argument ofSi .

PAT T 9ITRP / <^TM/ Y ^ Y^ The sine of X will be evaluated and the value passed to
SUB2 as the first parameter.

10-2-3 The SUBROUTINE Statement


The SUBROUTINE statement must be the first statement in every subroutine subpro-
gram. The general form of the SUBROUTINE statement is:

SUBROUTINE subroutine-name[{puP2,P}, -^Pn)]

where SUBROUTINE is a required key word,


subroutine-name is the name of
the subroutine (any valid variable name), and

P\,p2,p^. Pn are dummy arguments•,used to communicate data to and from the


calling program. These arguments can either be variables, array names, or function
names (no subscripted variable names or constants).
If an argument is an array name, the array name should be declared in a

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

subroutine is executed, the dummy


arguments lake on the values of the "real" arguments
specified in the CALL statement of the calling program. More preci.sely. the subroutine
processes directly the real arguments through the dummy arguments.
The arguments in the CALL statement should correspond in number, order, and
mode with the dummy arguments of the SUBROUTINE statement. The names used may
be the same or different. The order of the arguments in the CALL statement and in the
SUBROUTINE statement must be the same; that is. there must be a one-to-one cor-
respondence between both sets of arguments.

integer integer

real One-lo-one correspondence between arguments.


t
Five arguments in calling and called program.
t
CALLSUB(X .2.T.L.3.5) Mode between corresponding arguments preserved.

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

Main program Subprogram Comments

DATAX.Y/3. .4./ SUBROUTINE ADD (A, B,C


CALL ADD (X,Y,R) C = A+B
WRITE(6,1)R RETURN The value of R is 7.

CALL ADD (X,R,Z) END


WRITE(6.1)Z The value of Z is 10.

In the first call to ADD, arguments A, B, and C correspond to X. Y. and R. respectively.


In the second ADD, arguments A. B. and C correspond to X. R. and Z. respective-
call to

ly-

It should be emphasized again that the subroutine can change values in the main pro-
gram. Consider the following example:

Kxample 2

Main Program Subprogram

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

Main program Subprogram

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.

If an array is to be passed to a subroutine, the name of the array is specified in the

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 A( 10) ,B(10 \ SUBROUTINE SUMIT X S ( ,

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

Main Program Subprogram


.Same name hut
no relationship .

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:

r Main Program Subprogram


Same name
Same values
•A' D030I = 1,10 ^^'
(Arguments)
SUBROUTINE FICA HRS RATE Z ( , ,

READ (5,1) RATE, DO 30 1 = 1,10


CALL FICA HRS RATE PER
( . , TAX = HRS*RATE*Z
1 FORMAT F5. 2)- ( 1 FORMAT T5, 'FICA=' ,F5.1)
(

30 CONTINUE- 30 WRITE (6,1) TAX

Same statement numbers: perfectly valid

10-2-4 The COMMON Statement


One method from one subprogram to another is to specify
that can be used to pass data
each data item (variable) in list of the CALL and SUBROUTINE state-
the argument
ments. It should be noted that the "dummy variables*" (arguments) of the subroutine do
not really have a fixed memory address. When a "dummy variable" is encountered in the
subroutine, the system must look up the address of the corresponding argument in the call-
ing program and process the contents (value) of that memory location or use it for storage.
The "address" of the dummy variable changes depending on the argument in the main
program that it represents. For example:
SUBROUTINES 411

Calling program Memory SUBROUTINE SUB (Z


A=l
B=2
CALL SUB A (

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.

Figure 10-5 Subprogram Job Make-Up.

10-3 YOU MIGHT WANT TO KNOW


1. Why use subroutines?

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?

Answer: Perhaps, particularly in long or complex problems. It may be possible to seg-


ment the tasks that make up the complete program, write subprograms to perform
) ' )

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.

3. What statements can be used in a subroutine?

Answer: Any FORTRAN statements except other SUBROUTINE or FUNCTION


declarative statements.

4. Is a STOP statement necessary after the RETURN statement?

Answer: No. Logically the STOP instruction cannot get executed, since RETURN
will pass control back to the calling program.

5. If an argument in a CALL statement is just used by the subroutine to pass a particular


result to the calling program, need that argument be initialized to a specific value in
the calling program?

Answer: No. For example:

CALL ADD X Y RES ( , , SUBROUTINE ADD A B RES ( , ,

RES = A + B
There is no need to initialize RES to any value in the calling program.

6. If I use a DATA statement to initialize a variable in a subroutine, will that variable be


reinitialized every time the subroutine is called?

Answer: No. For example:

CALLTX(Y,3) SUBROUTINE TX(X ,K)


DATA SUM/0 / .

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

The practice of using the STOP statement in a subroutine is not recommended, as


many programmers feel it should be the privilege of the main program to stop execu-
SUBROUTINES 415

tion of the complete program. A flag can be used in the subroutine and tested in the

main program if there is cause for immediate termination of the job.

8. Can a subroutine call another subroutine or a function subprogram?

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

9. How many COMMON statements may be contained in a program?


Answer: As many as desired. Locations in COMMON are allocated sequentially in
the order encountered in the of the COMMON statements.
lists

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.

11. Can the COMMON statement be used with function subprograms?


Answer: Yes. It is used inexactly the same wa\ as in subroutine subprograms. Re-
member that subroutine arguments should not be listed in the COM statement. MON
12. FUNCTIONS and SUBROUTINES seem to have a lot in common. Can I change the
value of a parameter in a function subprogram as I can in a subroutine subprogram?

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

COM MON statement in order to operate directly on that common data.

14. Can a subroutine use arrays that are not declared as arguments or in a COMMON
statement?

Answer: Yes. For example:

SUBROUTINE SUB A. B,K) (

DIMENSION A (100) ,C(50,10)


DATAC/500*0./
The array C is to be used in the subroutine even though it is not part of the argument
list of the subroutine.

10-4 PROGRAMMING EXAMPLES


10-4-1 An Investment Decision
Mrs. X. must decide whether to buy a condominium now at a relatively high interest rate
or wait one year and buy at what is anticipated to be a lower interest rate. She is looking at
a S55,000 condo which she can purchase with 20 percent down and a 30-year mortgage at
14 percent. The current rate of inflation for housing is from 8 to 10 percent per year; thus
in one year the condominium is expected to be worth $60,000. However, the interest rate

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

WRITE 6 1 I 1 PI PAYMT TOTl


( , ) , , ,

1 FORMAT T5 F5 3 T15 F6
( . T29 F6 2 T40 FIO 2
. , , . , . . , , .

CALL CALC 12 P2 PAYMT T0T2


( , , ,

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

SUBROUTINE CALC ( I , P , PAYMT TOT) ,

REAL I, LOAN
LOAN= .2*P
PAYMT = LOAN* (1/12. /(I. -(1. +1/12. )**( 360. ) ) )

TOT = PAYMT* 360+ .2*P


RETURN
END

INTEREST PRINCIPAL MONTHLY PAYMENT TOTAL


0.140 55000. 521.34 198684.00
0.115 60000. 475.34 183123.00
THE DIFFERENCE IN TOTAL COST IS 15561 00 .

Figure 10-6 Investment Decision Program.

10-4-2 Solution to a Quadratic Equation


The two solutions to quadratic equations of the form a.x- + bx + t = are given by the
following formulas:

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

SUBROUTINE QUAD (A,B,C,X1,X2, FLAG


INTEGER FLAG
FLAG =
JF(A.EQ.0)G0T0 20
1 DISC = B**2-4.*A*C
IF(DISC)30,2.2
2 Xl= (-B+SQRT(DISC) )/(2.*A)
X2= (-B-SQRT(DISC) )/(2.*A)
RETURN
20 Xl = -C/B
X2 = X1
RETURN
30 FLAG = 1
RETURN
END

Figure 10-7 Solution of Quadratic Equations.

10-4-3 Sort Example


Mr. X has calculated the final grades for two data-processing classes. He wishes to sort the
grades for each class into ascending sequence and also to produce one list with the grades
for the two merged and sorted into ascending sequence. Since the code for sorting
classes
is fairly long and the program requires that the sorting procedure be performed several

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

DIMENSION GRADEl 50 GRADE2 50 .GRADE (100)


( ) , (

READ(5,1)N1,N2, (GRADEl(I) ,1 = 1 ,N1) (GRADE2i , I) ,I = 1,N2)


FORMAT (2I2/(F3.0)
CALL SORT GRADEl, Nl)
(

CALL OUTPUT GRADEl Nl ( ,

CALL SORT (GRADE2,N2)


CALL OUTPUT GRADE2 N2 ( ,

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 .

CALL SORT GRADE Nl + N2


( ,
)

CALL OUTPUT GRADE Nl + N2


( ,

STOP
END

SUBROUTINE SORT(G N SUBROUTINE OUTPUT (G,N


DIMENSION G(IOO) DIMENSION G(IOO)
M = N-1 WRITE (6,1)
DO 10 1 = 1, FORMAT 'ODATASET'
( )

LIM = N-I WRITE(6,2)(G(I) ,I=1,N:


D0 10J = 1,LIM F0RMAT(2X,10F6.0)
IF(G(J) .LE.G( J+1) IGOTOIO RETURN
Q = G(J) END
G(J) =G(J + 1)
G(J+1) =Q
10 CONTINUE
RETURN
END

Figure 10-8 Sort Program with Subroutines.

10-4-4 A Class Report


A deck ofcards consists of two subdata decks, each containing grades obtained by two dif-
ferent classes. Each subdeck is identified by a header card specifying the class and the
number of students for the particular class. One student grade is punched per card. No
class expected to contain .more than 100 students. Write a complete program to de-
is

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

Number of grades Card columns 33


card columns 1-3 10-20
AVERAGE = 66.3
COUNT OF GRADES BELOW AVERAGE IS 8

A program to solve the above problem is shown in Figure 10-9.

10-5 PROBING DEEPER


10-5-1 Flowchart Symbols for Subroutines
The predefined process block Ll lis used to s how a branch to a subroutine in a pro-
I

gram flowchart. For example. CALLSUB(X.Y)| could be translated into a FORTRAN


|

program as CALL SUB(X,Y).


The terminal blockC ^is used in a program flowchart to show the entry point
and exit point(s) in a subroutine. The entry point corresponds to the first instruction in the
subroutine and could be indicated by placing the name of the subroutine in a begin/end
block and a list of the dummy arguments such as C SUB(X.Y) J An exit point corresponds
to the use of the RETURN instruction and would be shown on the program flowchart as
( RHTLRN ) A complete program flowchart for the program of Figure 10-6 is shown in
Figure 10-10.
SUBROUTINES 421

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 )

Transfer control to subroutine AVRGE.


GRADE, N, AV, LOW dre c'dWcd arguments; CALL AVRGE GRADE N AV LOW ( , , ,

they are used in the subroutine to determine


the grade average and highest score. In the
subroutine, the dummy argument SCORE is

used to refer to GRADE (defined in the main


program). Both of these variables identify the
same memory locations.
Similarly L, SUM, and LOWl refer to N,AV,
and LOW respectively. The average and
number of grades below the average are com-
puted in the subroutine in SUM and LOWl,
which in effect stores the results in AV and
LOW.
Transfer to subroutine PRINT and print N CALL PRINT N GRADE HEADER AV LOW
( , , , ,

grades with a header (class/number), the aver- 5 CONTINUE


age AV, and the count of grades < average. At STOP
the conclusion of the PRINT routine, return is END
made to the main program at the instruction
following CALL PRINT.

Subroutine AVRGE will compute the average SUBROUTINE AVRGE SCORE L SUM LOWl) ( , , ,

o\' L grades stored in an array SCORE and INTEGER SCORE( 100)


store the result in SUM. The count of grades SUM = .

below the average is stored in LOWl . Initially. L0W1 =


LOW! is set to 0. D0 1I = 1,L
The array SCORE is really the array GRADE, SUM = SUM + SCORE (I)
which has been read in the main program, and SUM = SUM/L
L (or N) is the number of grades to be pro- D02I = 1,L
cessed. Note that the subroutine does not IF SCORE I
( LT SUM LOWl = LOWl +
( ) . . ) 1
change the array SCORE and the variable L, CONTINUE
and hence these are not changed in the main RETURN
program. The average and highest score are re- END
turned to the main program in AV and LOW
via SUM and LOWl. SUBROUTINE PRINT N GRADE H AV LOW ( , , , ,

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

listed vertically. The average of grades AV and


(
FORMAT '1' ,T48,A6,A5/(T53,I4)
LOW (count below average) will also be print- WRITE (6, 6 )AV, LOW
ed. FORMAT T50 AVERAGE IS F8 1/
( , '
'

, .

Note none of the arguments are changed


that ^T50 COUNT OF GRADES BELOW AVERAGE IS
,
'
,13)
in the subroutine (set to any value). RETURN
The array H is another name for the array END
HEADER defined in the main program.

Figure 10-9 Main Program Calling Two Subroutines.


2 n
)

422 SUBROUTINES

r START
J

CALL CALXd 1 ,P1 .PAVMT, TOT

r~^ ITF. IlPl.PAYMT.TOTl


7 QCALC(I,P,PAYMT,TOT)D
CALL CALCI I2,P2.PAVMT,TOTl

DIP =T()T1 - TOT

/ \VR ITE DIF


7
SUBROUTINES 423

Main program Subprogram

DIMENSION A( 3, 3) ,B(3,3),C(3,3 SUBROUTINE ADD X Y Z K( , , ,

DIMENSION! (2, 2) ,Q(2,2),R(2,2) DIMENSION X(3,3),Y(3,3),Z(3,3


K=:3 DO 101 = 1,
CALLADD(A,B,C,K) DO 10J = 1,K
K=2 Z(I,J) =X(I,J) +Y(I,J)
Unequal sizes
CALL ADD (T,Q,R,K) RETURN

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:

Main program Subprogram

DIMENSION A (3, 3) ,B(3,3),C(3,3) SUBROUTINE ADD(X Y .Z ,M,N) ,

DIMENSION! (2, 2) ,Q(2,2),R(2,2) DIMENSION X(M ,N) ,Y(M,N),Z(M,N)


M=3 D010I = 1,M
N=3 D010J = 1,N
CALL ADD(A,B,C,M,N) 10 Z( I J = X(
, ) I , J ) + Y( I J
,
)

• 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:

Main program Subprogram

DIMENSION A 10 ( ) , B 50( ) , C ( 200 ) SUBROUTINE SUB X K ( ,

DIMENSION X(l)
• •

CALL SUB (A, 10)

N = 36
CALL SUB (B,N)

CALL SUB (C, 175)

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)

Column Column Column Column Column


1 2 NC

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

Since two-dimensional arrays are stored column-wise in a single-dimensional array,


the linear position or address L of the element X(I,J) is (J — ) full columns from the origin
1

plus I positions down in the Jth column. Since each column consists of NR elements, the
hnear address L of X(1,J) is:

L= (J-l)*NR-i-I, hence A(L) is equivalent to A(I,J).

Consider the following array A stored in memory as a one-dimensional array.

3
R

426 SUBROUTINES

Main program Subprogram

DIMENSION A( 3, 3) ,B(17,13 SUBROUTINE TOT X SUM NR NC ( , , .

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:

L= (K- 1)*NR*NC+ (J-1)*NR+I


K - I planes away J — 1 columns away 1 positions away

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

Similar formulas can be w ritten for arrays of higher dimensions.

10-5-3 Named COMMON Blocks


Recall that variables located in COMMON are available to any program containing the
COMMON statement. In many instances the number of variables contained COM- in

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

Main program Subprograms

COMMON/BLKl/X Y/BLK2/Q , , SUBROUTINE SUBl


C0MM0N/BLK1/X,Y

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

The general form of the COMMON statement is:

COMMON [/block-name/] lisl-of-variahles [/block-name/] list-oj-variables

where COMMON is a required key word,


block-name is the name of the block COMMON, and
slashes (/) are a required part of the statement.
If the block name is omitted, the variables are placed in unnamed (sometimes called blank)
COMMON.
Examples

COMMON/XYZ/X 10 Y 100 / ABC/RR 100 ( ) , ( ) (

COMMON A B C 10 / BL0CK3/Q R S
, , ( ) , ,

COMMON are named XYZ, ABC, and


Three blocks of BL0CK3, while blank COM-
MON contains the variables A,B, and ten elements of C.

10-5-4 BLOCK DATA


One method for initializing simple variables or arrays which appear in blank or labeled
COMMON is a BLOCK DATA subprogram.
Suppose that each element of array X in blank COMMON is to be initialized to and
the variable BE in block-name BLK 1 is to be initialized to "GOOD." Then the following
code may be used:

Main program Subprogram

CHARACTER*4 BE BLOCK DATA


REAL X( 10) ,Y(4) COMMON R,S
COMMON X F/BLKl/M Y BE/BLK2/R ITEM
, , , , COMMON /BLK1/L,Z,NE
REALR(10)/10*0./,Z(4)
CHARACTER*4 NE/'GOOD'/
END

Note that the first statement of the subprogram is:

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-

gram) is dimensioned at 10. Each element of that array is set initially to 0.


Since BE appears in named COMMON
BLKl, this block is listed in the BLOCK
DATA subprogram and Z is dimensioned to 4 (even though it is not initialized).
428 SUBROUTINES

NE, which corresponds lo BE, is declared a CHARACTER*4 variable and iniiiaHzed


to "GOOD '.

Since no variable in BLK2 is to be initialized, it is not listed in the BLOCK DATA


subprogram.
WATFIV allows initialization of variables and arrays in blank or named COMMON
in DATA or specification statements. Some FORTRAN compilers only allow initializa-
tions of variables in COMMON to be done with the BLOCK DATA subprogram.

10-5-5 Multiple Entry

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:

ENTRY name (p\,pi,py, )

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

Main program Subprogram

REAL X( 2, 3) ,RS(2) ,CS(3) SUBROUTINE MAT A, N,M) (

CALL MAT (X, 2, 3) REALA(N,M) ,RSUM(N) ,CSUM(M)


4 READ (5, 6, END = 40) I. J DO 10 1 = 1, N
X(I,J) =X(I,J) +1 D04J = I,M
GO TO 4 4 A(I,J)=0
40 CALL RMAT(X,2,3,RS,CS) 10 CONTINUE
RETURN
ENTRY RMAT(A,N,M,RSUM,CSUM
D06I = 1,N
CALL CMAT(X,2,3,CS RSUM I = ( )

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.

10-5-6 Multiple Returns from Subroutines

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:

CALL name {p\, p2, & S\, py, &52, • • •)

where name is name;


a valid subroutine

/)i, /?:,•• • communicate data to and from the subroutine;


are arguments used to
5i, 52, are•
statement
• •
numbers of statements in the main program where control is
to be returned (these must be preceded by the & symbol in the argument list to dif-
ferentiate them from constants).

In the subprogram use the following format:

SUBROUTINE name(pu pi,* .Pi,* ,)


RETURN 1

RETURN 2

RETURN
END

where name is a valid subroutine name:


/?i, p2, are dummy arguments used to communicate data to and from the calling
program;
* are used to correspond with the &Si, Slsi, -in the main program's CALL argu-
ment list;

RETURN 1 means execution returns to the main program to the statement cor-
responding to the first *;
) . .

430 SUBROUTINES

RETURN 2 means execution returns to the statement corresponding to the second


(*), and so on;
RETURN indicates a return to the statement in the main program following the
CALL.
It is also valid to specify RETURN N where N is an integer variable.

Example

The following main program and subroutine determine the roots of the equation Ax' +
Bx+ C = 0.

Main program Subroutine

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

DI = SQRT(B**2-4*A*C) IF (B**2-4*A*C.EQ.O) RETURNS


Rl= (-B-DI)/(2*A) IF (B**2-4*A*C.LT.O) RETURN 2
R2= (-B + DI)/(2*A) RETURN
WRITE(6,7)R1,R2 END
GO TO 60
5 R = -C/B
WRITE(6,7)R
GO TO 60
8 WRITE(6.81)
GO TO 60
10 RD = -B/(2*A)
WRITE(6.7)RD,RD
GO TO 60
3 FORMAT (3F5.1)
7 F0RMAT(1X,2(F10.2,2X)
81 FORMAT( IX, 'COMPLEX ROOTS'
80 STOP
END

In the subroutine, if A = 0, execution is returned to statement 5 in the main program. If


5' — 4/4C = 0, execution returns to statement 10 (the statement that corresponds to the
third asterisk). \{ B' — AAC < 0, return is to statement 8. If none of these conditions is
true; that is, \{ B^ — AAC > 0, control is returned to the statement following the CALL. In
each case appropriate messages are printed about the roots.

1 0-5-7 The EXTERNAL Statement


Suppose you wanted to determine the maximum value taken on by each of the following
functions:

I. \= 3x' -2x''- 14 X ranges from 2 to 10 in increments of 3.

2. y = sJ(x-4}(x + 6} X ranges from —4 to 5 in increments of 1

3. V = sinix) X ranges from .1 to 1.1 in increments of . 1


SUBROUTINES 431

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 .

be written since it is a library function.

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

SUBROUTINE MAXI INIT TER INC FUNC ( , , , )


The range of the function FUNC is

REAL INIT.TER, INC, MAX [INIT, TER].


MAX = FUNC (INIT)
7 INIT = INIT + INC Assume maximum function value is
IF(INIT. GT. TER) GO TO 8 FUNC(INIT).
IF FUNC INIT GT MAX MAX = FUNC INIT
( ( ) . . ) ( The first tmie FUNC is actually POLY, and
GOTO? hence P0LY(2), P0LY(5), . . . will be com-
8 WRITE (6, 3) MAX puted.
3 F0RMAT(1X,F10.2)
RETURN Later on FUNC will be the sine function,
END and the maximum value for the sine func-
tion in the interval and I.I will be
. I

FUNCTION POLY(X) printed.


P0LY = 3*X**3-2*X**2-14
RETURN
END

FUNCTION SQPOLY(X)
SQPOLY = SQRT( (X-4: (X-^6:
RETURN
END
Figure 10-11 Use of the External Statement.

The general form of the statement is:

EXTERNAL name], name!,

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

10-5-8 The EQUIVALENCE Statement


The EQUIVALENCE slalcmenl can be used lo give more ihan one name lo a niemor\ lo-

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.

WRITE(6J 1)A The value uriiten for A will be 3.

The general form of the EQUIVALENCE slatemenl is:

EQUIVALENCE {list-of- variables)

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^

EQUIVALENCE (A(3) ,B(3) ) vields the pairing ' "


j'Ti'
Bi B: B« B4 85

EQUIVALENCE (A(2) ,B(3) ) yields the pairing '


\ N. V 8? '

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

DIMENSION A (2, 2) ,B(3,2) A^^ A^i Ap A^^


EQUIVALENCE (A(2.1) .B(3,l) )
B,,
\ \ \
8^1 8,1 8,2 8., B,2
<^
Hence Bn and Bt: are assigned separate memory locations.
The EQUIVALENCE statement is sometimes used when two or more programmers
working independently on program segments have used different names for the same vari-
able. Rather than rewrite the entire program with the same variable names, the
EQUIVALENCE statement can be used. Similarly, the EQUIVALENCE statement al-

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-

ray can be given a different name. Consider the following example:

DIMENSION A (10, 10) AINVER( 10 10 ,TEMP(10,10) , , )

EQUIVALENCE AINVER (1.1), TEMP (1,1))


(

The inverse matrix has now been computed. Write it


WRITE(6.1)AINVER out. At this point in the program AINVER is no longer
needed.
Let us use the storage of AINVER to read into it some
READ(5,11)TEMP temperatures. Calling the array AINVER could be mis-
leading so we call it TEMP.

10-6 EXERCISES
10-6-1 Self Test
1. What would happen if you tried to execute a subroutine all by itself?

2. List two distinct differences between function and subroutine subprograms.

3. What advantages are there in using subroutines?

4. What are two ways to pass data to a subroutine?

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?

6. Would the statement DIMENSION X(N) be valid in a main program? In a sub-

routine? In a function subprogram? What restrictions would be placed on X and N?

7. Find the error in each of the following:


^
Main program Suhprogran] ct^

a. INTEGER A 10) ( ,B( 10 SUBROUTINE SUB (I, J)


% DIMENSION I (10) ,J(10
DO lOK^l.lO
CALL SUB A B ( , 10 I(K)=J(K)
RETURN
END
X B

434 SUBROUTINES

b. DIMENSION X( 100 SUBROUTINE SUB A, X (

DIMENSION A(IOO)
X =
DO 3 1 = 1,100
CALL SUB (X, 14 3 X = X + A(I)
RETURN
END

c. DIMENSI0NX(10,10) ,Y(3,4, SUBROUTINE SUBC( A


DIMENSION A( 10,10

CALL SUBC (

RETURN
CALLSUBC(Y) END

d. DIMENSION A( 15 SUBROUTINE SUBD(P


DIMENSION Q( 15)
DO 10 1 = 1,15
10 Q(I)=P
CALLSUBD(A,B RETURN
END

c. DIMENSION X( 3,4) SUBROUTINE SUBE X N M ( , ,

DIMENSION X(N,M)

CALL SUBE (X

f. DIMENSION X( 3, 4 SUBROUTINE SUBF(X, A,


DIMENSIONX(A,B)

CALLSUBF(X,3,4)

g. REALJSUMdO SUBROUTINE (JSUM.K.R


DIMENSION JSUM(l)
REAL J SUM
CALL SUB (JSUM.N, 3.1
SUBROUTINES 435

h. DIMENSION A(5) ,B(5) ,C(5) ,E(5, SUBROUTINE SUB B E K DD ( , , ,

COMMON D( 3) COMMON DD( 3)


DIMENSION E(l)

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.

9. Determine what the following program does.


L

436 SUBROUTINES

INTEGER A 4 B 4 ( ) , ( ) , BLOOD 4 ( ) , TYPE Data:


COMMON A, B, BLOOD MICHELLE)2(>{+A)f^
DO 10 1 = 1,4
10 READ(5,11)A(I) ,B(I) ,BLOOD(I) MARC>^>^>^;6>^)5+AB
11 FORMAT (2A4,2X. A3) R0BERT)^)2^;?$j?^+Ajj^
READ (5, 12) TYPE +A>{
12 FORMAT (A3)
WRITE (6, 13) TYPE
13 FORMAT! IX, THESE PEOPLE HAVE BLOOD
'
', 2X A3
,
^ A
CALL SEARCH (TYPE)
STOP
END

SUBROUTINE SEARCH(L)
INTEGER Nl 4 N2 4 BLOOD 4
( ) , ( ) , ( ) ,

COMMON N1,N2, BLOOD


DO 10 1 = 1,4
IF(BLOOD(I) .EQ.L)WRITE(6,19)N1(I) ,N2(I
10 CONTINUE
19 FORMAT (T3,2A4)
RETURN
END

10-6-2 Programming Problems

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.

4. Same as Exercise 2, with a two-dimensional array.

5. Same as Exercise 3, with a three dimensional array.

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.

c. Multiply each element of an array by a constant.

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:

d = sj (A-, - A'2)^-H(K, - Y.y

19. In a particular class, grades are based on homework, quizzes, and


tests. For each stu-

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

real numbers. There are at most 100 students.

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

Number of v. JONES 1 123142433


studer
;nts ^~^
1123 14 2433
440 SUBROUTINES

Create a table of costs for the different items. For example:

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

29. An interesting method of encoding data is to load a message to be encoded into a


two-dimensional array and then interchange rows and interchange columns a number
of times. The resultant sequence of characters is the encoded message. In order to de-
code the message, the sequence of steps used in the encoding process is followed in re-
verse order. For example, consider the message "I HAVE BUT ONE LIFE TO GIVE
FOR MY COUNTRY." Let us load the message into a 6 X 7 array:

1
442 SUBROUTINES

Interchange column 1 and column 5 L


SUBROUTINES 443

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:

CALL SORT(array, length-of-array)

where both array and length-of-array are INTEGERS.


Write a general INTEGER function ITOTAL that calculates the number of
points in a given hand. This subprogram has two arguments. An example of a call to
ITOTAL is:

IX = ITOTAL(array, length-of-array)

where both array and length-of-array are INTEGERS.


The points are calculated as follows:

4 pts for each ace


3 pts for each king
2 pts for each queen
1 pt for each jack

(Hint: the MOD function might help in this routine.)


Write a subroutine SHOW with two arguments. The first argument is an IN-
TEGER array of length 3 which contains the sorted cards, and
1 the secondargument
is an INTEGER variable containing the number of points in the hand. An example of
a call to SHOW is:
SUBROUTINES

CALL SHOW(array. number-of-points).

Subroutine SHOW prints the contents of the argument and


hand passed to it as an
prints the number of points in the hand. It and in ascend-
prints out the cards by suit
ing order within a suit. The order of the suits at printout is spades, hearts, diamonds,
and then clubs. Print the information according to the sample shown below. Note:
The array have already been sorted into ascending order of spades, hearts, etc.. by
will

the subroutine SORT: subroutine SHOW


is merely a "print" routine.

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

A(l,7.1) A(l,7,6) A(2,7.1) A(2,7,6)


A(4.7,5)
SUBROUTINES 445

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.

You will process an unknown number of questionnaires.

Input: When a person answers the questionnaire, his answers are punched on one card
in the following manner:

Columns 1-3 ID number for the person responding (INTEGER).


Columns 5-8 The four responses to the questions in group I, one column
each (each is an INTEGER and 5, inclusively).
between I

Columns 10-7 The group 2, one column


eight responses to the questions in
each (each is an INTEGER between and 5, inclusively). I

Columns 19-25 The seven responses to the questions in group 3, one column
each (each is an INTEGER between and 5, inclusively). I

A sample card might look like:

columns 0000000001 1111111 11 222222

1 234567890 234567890 2345


1 1

4213 43145244 4144535


r 218
Your main program should read in a card and use the subprograms as described here.
This should be done for each card.

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:

Y = AVE (array-name, length-of-array).


SUBROUTINES 447

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:

CALL HIST (array-name).

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.

Column 0000000001 11111111 122222222223333333


123456789012345678901234567890123456

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

The printout for the three groups ofquestions should read:

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

The XXX is to be replaced by the person's ID number. The is to be replaced by


the appropriate message as just discussed.
An example of a call to OP is:

CALL OP(id-n umber, array-name)

1 0-6-3 Answers to Self Test

1. The dummy variables are not initialized properly and might destroy memory: also the
return address is unknown.

2. a. A function generally returns one value; a subroutine returns many values.


b. A subroutine is invoked by the CALL statement, whereas a function is invoked im-
plicitly in an expression.

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.

6. A variable as a size declarator is valid in a subprogram. X and N must be dummy vari-


ables.

7. a. Mode of real and dummy arguments must match.€-§


b. Value of the constant 14. cannot be changed in the subprogram.
c. Dimension of an array in a subprogram must match dimensions in the calling pro-
gram (except for one-dimensional arrays).
d. P should be dimensioned instead of Q.
e. Number of arguments does not match.
f. Mode of size declarator in DIMENSION must be integer.
g. Missing name for subroutine.
h. A dummy argument may not also be in COMMON (D).
8. a. Subroutine name is missing; also, constant is found in list of dummy arguments.
b. Valid.
c. Missing "/" at beginning of name of common block.
d. Improper syntax.
e. Constant in list of dummy arguments.
f. Valid.
g. Use parentheses instead of slashes.
SUBROUTINES 449

h. Dimensioned variable in list of dummy variables.


i. Invalid syntax.
j. Array B should be dimensioned 13.

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

9. The printout will be as follows:

THESE PEOPLE HAVE BLOOD +A


MICHELLE
ROBERT
11
FILE
PROCESSING

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
/

Name security Rate

1 ..x-ri
DOE JOHN 001222333 4 05 25 4 TURNER SUE 111222333 3 75 ADAMS LORNE 999333222 3 06 00 2

Employee record Employee record Employee record

Figure 11-1 Personnel File on Magnetic Tape.

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.

11-1-2 Program Example


Mr. X wishes to maintain data regarding the number of parts on hand at his company's
warehouse. The company has just taken inventory, so the number of parts on hand at the
present time is known. This data is entered into the computer system and retained in a file.
A short FORTRAN program shown in Figure 1-2 is used to create this file on external 1

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
)

452 FILE PROCESSING

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

WRITE 7 PARTN QTY


( ) .
^ rite on file 7. it

WRITE (6,2) PARTN QTY Write same record on printer.


GO TO 100
44 END FILE 7
REWIND 7
STOP
1 F0RMAT(I6,I3)
2 F0RMAT(1X,I6,3X,I3)
3 FORMAT IPART # 2X
(

' ' ,
,

'
QUANTITY '

END

PART # QUANTITY
mill 20
222222 3
333333 25
444444 123

Figure 11-2 File creation program.

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

12 READ (5,1, END = 21) PART.QUANTY


" ^iP.'f
"' Read a change record.
14 DO 13 1 = 1, N ^ ' r^ Find a part number in the file which is
"
IF(P(I) .EQ.PART)GOTO 15 equal to the part number on the change re-
13 CONTINUE cord.
WRITE (6,2) PART If the part number is not on file, write the

GO TO 12 appropriate error message.


15 Q(I)=Q(I)+ QUANTY - . Update appropriate quantity.
GO TO 12 -//^^Iv^^'P^
21 REWIND 7-
D030I = 1,N
Ar)"'^
IIhX' ^^^
r^^y^a:^i
^Reposition file 7.
Rewrite file 7 with updated data.

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

Figure 11-3 File Update Program.


FILE PROCESSING 453

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

454 FILE PROCESSING

11-2 FILE PROCESSING STATEMENTS


11-2-1 Formatted vs Unformatted I/O
If the format statement number is omitted from the READ or WRITE statement, data is

read or written without undergoing translation by FORMAT specifications. FORMATS


are required to translate data in character form to internal form for input
and from in-
ternalform to character form for output. Numerical data on data cards is in character
form and hence must be translated into internal number representation before it can be
processed by the arithmetic unit. The printer requires its data in character form so FOR-
MATS must be used to translate an internal number representation into character form
before it can be printed. Data may, however, be stored on devices such as tapes and disks
in either internal 1-6). The unformatted WRITE statement
or character form (see Figure 1

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.

FOR TRA N statements Files /storage

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.

11-2-2 The END FILE Statement


Every file must have a system end-of-file record following the last data record of the file.

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:

END FILE device-number

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.

11-2-3 The REWIND Statement


A major advantage of a disk or tape file is that it can be processed repeatedly by a pro-
gram. The REWIND statement causes the next input operation addressed to a file to re-
turn to the program the first record of the file. When the file is on tape, the tape is physi-
cally rewound and repositioned so that the first record of the file is available at the next
operation. When the file is on disk, the rewinding is logical rather than physical. The re-

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

where device-number is the number associated with the file to be rewound.


456 FILE PROCESSING

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

11-3 YOU MIGHT WANTTO KNOW


1. If there any way to get the system to backspace a record in processing a file?

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.

3. Can 1 skip files if there are more than one on a tape?

Answer: Yes. For example:

10 READ (7, END =88) DATA '

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

V./'^.v^^'^ G0T0(1,2),K ,^,((y qA ^ ^''ii^


G0T07 S-'^ ^-^rT^
^'
2 N = 1 .
//«/
f
7 READ(N,8)A,B,C

5. What is the advantage of using unformatted READ/WRITE statements as opposed to


formatted READ/WRITE statements?
^
Answer: Time is saved by unformatted READ, since no translation of the data read is
necessary. Unformatted WRITE may save space, since less space may be used by the
internal form of a data item than the character form.
FILE PROCESSING 457

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

Answer: Yes. See discussion in Section 1 1-5-2.

11-4 PROGRAMMING EXAMPLES


11-4-1 File Creation
In the following program examples, we shall assume that a file MASTER (device-number
7) has been established, containing payroll data records including identification number,
name, and hourly wage. The program used to create the file is shown in Figure 1-7; the 1

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.

C THIS PROGRAM CREATES THE FILE MASTER FROM CARD INPUT


DIMENSION NAME( 5)
1 READ 5 100 END = 60 ID NAME H Create file 7 in unformatted form.
( , , ) , ,

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.

C THIS PROGRAM PRODUCES A LISTING OF THE FILE MASTER


DIMENSION NAME( 5)
WRITE(6,10)
WRITE(6,11)
1 READ 7, END =100) ID, NAME, H
( Access to file 7 is made through an
2 WRITE (6, 12) ID, NAME, unformatted READ, since this was the way the
GO TO 1 file was initially created.
100 WRITE(6,13)
STOP
10 FORMAT '1' ,60( '*'
(

11 FORMAT (IX, 'ID NUMBER' 5X 'NAME' ,16X, 'HOURLY WAGE'


, ,
)

12 F0RMAT(1X,I9,5X,5A4,2X,F7.2)
(
13 FORMAT (IX, 60 '*' )

END

ID NUMBER NAME- HOURLY WAGE


123456789 DOE JOHN 5.00
222222222 BROWN JIM 2.50
333333333 GREEN MARY 7.25
456789000 SMITH SAM 4.21

P'igure 11-8 File-Listing Program.


458 FILE PROCESSING

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

special difficulties. However, in most cases it is advantageous to store a file in ascending


order by record key. Note that the sample file listed in Figure 1-8 is sorted into ascending 1

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)

containing the new file.


If tapes are being used for file storage, a common procedure would be to store the file

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.

1 1 -4-3 Report Generation


A second file (HOURS) is to be created containing records in the form:

Identification-number, hours- worked.

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

DIMENSION NID( 100) ,NEWNAM( 100 , 5 ) ,WAGNEW(100)


DIMENSION NAME( 5)
DO 10 I = 1 , 101 Read new records into arrays
READ (5,100,END = 20)NID(I) (NEWNAM(I,J) ,J = 1,5) ,WAGNEW(I) ,

10 WRITE(6,102)NID{I) (NEWNAM(I,J) ,J=1,5) ,WAGNEW(I) ,

20 N = I-l N represents the number of items to be added.


1 = 1
21 READ 7 END = 50 ID NAME H
( , ) Read a record from master file.
, ,

23 IF( ID.EQ.NID( I GO TO 33 )
Check for duplicate identification numbers.
)

IF(ID.GT.NID(I) GO TO 30 If Don master file is less than new record ID.


)
I

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

GO TO 23 40; otherwise continue the loop.


33 WRITE(6,101)ID Write error message.
GO TO 22
50 IF(I.GT.N)G0T0 60
51 WRITE(8)NID(I) (NEWNAM(I,J) ,J = 1,5) ,WAGNEW(I
,

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.

4 IF(MASTID.LT.ID)GOTO 190 If MASTER IDisgreaterthanHOURSID,

5 WRITE(6,101)ID write error message.


GO TO 2
190 READ ( 7 END = 500 MASTID NAME WAGE
, ) , , Read new record on MASTER file if MASTER
GO TO 3 ID is less than HOURS ID.
200 PAY = HOURS*WAGE Compute pay and write report line when MAS-
WRITE 6 102 ID NAME WAGE HOURS PAY TER D
( , ) , , , , I is equal to hours ID.
GOTO 1
500 WRITE(6,101)ID
READ 8 END = 600 ID HOURS
( . ) , If end is reached on MASTER, current hours
GO TO 500 record and remaining HOURS are in error.
700 READ (8, END =600) ID, HOURS If end is reached on MASTER, remaining
WRITE (6, 101) ID HOURS records are in error.

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

101 FORMAT (2X NO MATCHING RECORD ID NUMBER


'
110 ' , )

102 FORMAT (2X 19 3X 5A4 2X F7 2 6X F7 2 2X F8 2


, , , , . , , . , , .

103 FORMAT (IX, 70


END
******»»*»*#************#***)<***)<************
ID NUMBER NAME HOURLY WAGE HOURS PAY
123456789 DOE JOHN 5.00 40.00 200.00
222222222 BROWN JIM 2.50 53.00 132.50
NO MATCHING RECORD ID NUMBER 444444444
456789000 SMITH SAM 4.21 24.00 101.04
555555555 JONES MARK 7.50 50.00 375.00
*»#»#*#**#**#*#***********************************
Figure 11-12 Gross Pay Report.

11-5 DIRECT-ACCESS FILES


11-5-1 Definition

Records contained on a dire'ct-access file may be accessed by specifying a number which is

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

462 FILE PROCESSING

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.

There may be additional operating system considerations in setting up a direct-access


file. The reader must consult locally available references for further details.
r77
^^^ 11-5-2 The DEFINE FILE Statement
The DEFINE FILE statement is a specification statement which is used to specify certain
parameters for a direct-access file. The general form of the statement is:

DEFINE FILE device-number {length, size. mode, cursor) (.••]

w here device-number is the number associated with the file and used as a device-number in

allRE.AD WRITE statements for the file,

length is the maximum number of records to be stored on the file,

size is the size of each record,


mode is either E, U, or L, specifying whether records are stored in formatted form

(E),unformatted form (U), or a mixture of the two forms (L), and


cursor is an integer variable which will be associated with the file to point to the next
available record. After any READ/WRITE operation, the value of the cursor vari-
able is automatically set by the system to the record number of the next record 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

mode is U (unformatted), size specifies the number of w ords in a record.

Examples

DEFINE FILE 8 (1000 4 U KPOINT , , ,

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.

DEFINE FILE 9 (5000, 60, E,N9) 10(1050 ,70 L ,N10 ,


, )

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.

1 1 -5-3 Direct-Access READ and WRITE


Direct-access files must be processed with READ and WRITE
special direct-access state-

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,

record-number is an integer expression specifying the position of the record on the


file, and
list-of-variables is a list of the variables to be read/ written.

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.

11-5-4 Program Example


Direct-access files are very convenient to use when a direct correspondence can be set up
between the record key and the position of the record in the file. For example, suppose we
must create a file to store payroll data for a small company with employee identification
numbers ranging from 001 to 999. The employee identification number can be used to
point to the position of the record in the file (see the program in Figure 1-13). The pro- 1

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

C THIS PROGRAM CREATES A DIRECT ACCESS FILE


DIMENSION NAME( 5)
DEFINE FILE 8 (1000 6 U K8 , , , )

1 READ (5, 100, END =20) ID, NAME, RATE


WRITE(8'ID)ID,NAME,RATE The value in ID.
GOTO 1
20 STOP
100 F0RMAT(I3,5A4,F5.2)
END

Figure 11-13 Direct-Access File Creation.

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

Note that no sorting of records is required to produce a sequentially stored file.

CTHIS PROGRAM LISTS A DIRECT ACCESS FILE


DIMENSION NAME( 5)
DEFINE FILE 8 (1000, 6, U,K8)
DO 10 1 = 1,1000
READ(8'I)ID.NAME,RATE
IF(I-ID)10,11,10
11 WRITE (6, 100) ID, NAME, RATE
10 CONTINUE
STOP
100 F0RMAT(2X,I3,2X,5A4,2X,F7.2)
END

100 ABLE BAKER 3.00


123 DOE JOHN 5.00
222 BROWN JIM 2.50
333 GREEN MARY 7 25
.

456 SMITH SAM 4.21


555 JONES MARK 7.50

Figure 11-14 Direct-Access File Listing.

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

C THIS PROGRAM USES THE CURSOR TO LIST A DIRECT ACCESS FILE


DIMENSION NAME( 5)
DEFINE FILE 8 (1000, 6, U,K8)
K8=l
1 READ(8'K8)ID.NAME,RATE
IF(ID.NE.K8 - 1)G0T0 11 Since K8 is incremented automatically
WRITE 6 100 ID NAME RATE
( , ) , , after each READ, the value of the ID
11 IF(K8.LE.1000)G0T01 just read should be K8 — I if the
STOP record contains valid data.
100 F0RMAT{2X,I3,2X,5A4,2X,F7.2)
END

Figure 11-15 Use of Cursor in Direct-Access File Listing.

Suppose that we now wish


to produce a gross pay report based on an input file con-
taining records with employee identification and hours worked. As each hourly record is
read, the associated record from the direct-access file is read and the data from the two re-
cords are used to produce a line on the report. Compare the logic used in the program of
Figure 11-16 with that required to process sequential files (see Figure 11-12). Again note
the fact that the ID must equal the record position; otherwise, the record is an unused re-
cord.

C THIS PROGRAM PRODUCES A GROSS PAY REPORT


C FROM A DIRECT ACCESS FILE
DIMENSION NAME( 5)
DEFINE FILE 8 (1000, 6, U,K8)
1 READ (5, 100, END = 20 )NUM, HOURS Read data from record number NUM.
READ 8 NUM ID NAME RATE
( ' ) , , If valid data are not contained on this
IF(ID.NE.NUM)GOTO 10 record, write error message.
PAY = H0URS*RATE
WRITE 6 101 ID NAME RATE HOURS PAY
( , ) , , , ,

GOTO 1
10 WRITE (6, 102) NUM
GOTO 1
20 STOP
100 FORMAT 13, F6. 2)
(

101 FORMAT 2X 13 2X 5A4 2X F7 2 2X F8 2


( , , , , , . , , .

102 FORMAT 2X NO MATCHING RECORD FOR EMPLOYEE


( ,
'
' , 14
END

Figure 11-16 Gross Pay Report.

1 1 -5-5 System Flowcharts


The flowchart technique has also been applied to describe the relationships among pro-
grams and file in a data-processing system. In a computing system various devices may be
used to store a file. In a system flowchart, different symbols (blocks) are used to represent
files stored on these devices (see Figure 1-17). 1
466 FILE PROCESSING

FLIGHT
CRT display SCHEDULE
DISPLAY

Teletype DEPOSIT
terminal TRANSACTIONS

Magnetic tape

Punched cards CASH SALES


FILE

Paper tape

Magnetic disk

Magnetic drum INVENTORYl


FILE

Printer
SALES
REPORT

Processing INVENTORY
program UPDATE

Figure 11-17 System Fknvcharl Symbols and Examples.


FILE PROCESSING 467

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

Input/output Tape file is used as


an input file.

Processing program.

Disk file is used as


Printed output is

an input and an produced.

output file.

Teletype is used as input (via a


telecommunications link).

Processing program.
Telecommunications link

CRT display is used


as an output device
(via a telecommunications
Imk).

Figure 11-18 System Flowchart Flowlines.


468 FILE PROCESSING

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

Figure 1 1-20 A Simple telecommunications system.

FORTRAN
PROGRAMMING STORAGE
FILE
SYSTEM

USER 3

Figure 11-21 A More Complex System.

11-6 EXERCISES
11-6-1 Self Test

1. What purpose is served by each of the following features of FORTRAN?


a. The END = option.
b. The END FILE statement.
c. The REWIND statement.
d. The BACKSPACE statement.
2. What is the difference between formatted and unformatted processing of data?

3. What is a record key? Why is it important?

4. Differentiate among the following: data item, data record, data file.

5. What are the disadvantages of sequential access to data? Are there advantages?

11-6-2 Programming Problems


1. Write a program to perform addition of records, deletions of records, and changing of
file discussed in Section 11-1. Use a code on the in-
existing records for the inventory
put record to indicate the action to be performed. For example, you might use 1 for
addition, 2 for deletion, and 3 for change.
470 FILE PROCESSING

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.

A master file must also be created with records in the format:

salesman-number, name, amount-of-sales-to-date.

Programs are needed to:

a. Create the files.

b. Update the master file from data in the sales file.

c. Produce a report showing each salesperson's totals to date.

7. Dr. X teaches an introduction to computers course to 15 students. Three equally


weighted tests are given in the course. A file is created for the class; each record con-
sists of a student name followed by the student's grade. Records are sorted by name in

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

account-number, name, present-balance.

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-

tical? Can you think of a solution to the problem?

13. Modify the program of Exercise 6 to use direct-access files. Make an appropriate as-

sumption about the salesperson number field.

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 1 -6-3 Answers to Self Test

1. a. The END = option allows automatic branching when the end-of-file record read. is

b. The END FILE statement causes an end-of-file record to be written.


c. The REWIND statement causes a file to be repositioned so that the first record in
the file is available for processing.
d. The BACKSPACE statement causes the repositioning of a file one record
backwards.

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.

3. A record key is a field in a record. It is important because it is used to retrieve data


from a file.

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

than programs using traditional developmental methods.


Some programming languages have a sufficiently rich repertoire of constructs to per-
mit the writing of programs without the GO TO statement. FORTRAN 77 and WATFIV
have added structured programming statements acceptable to their compilers; this chapter
introduces these statements along with structured programming concepts.
Structured programming makes use of top-down program design. At each stage in the
development process, a program is described as a sequence of one or more tasks. Each
task may then be respecified as a sequence of tasks describing what is to be done at a
slightly higher level of detail. Finally, when all tasks have been specified in sufficient de-
tail, the program can be coded in a programming language.

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.

12-1-1 Structured Programming Example


As you now know, a flowchart is a pictorial representation of the method (logic) used to
solve a particular problem; it diagram form the sequence of steps that must be
identifies in
taken (from beginning to end) in order to arrive at the solution of the problem. For exam-
ple, the flowchart in Figure 12-1 identifies the sequence of activities that a person might
perform upon waking up in the morning. Figure 12-1 is so important to the understanding
of structured programming concepts that the reader is asked to visually walk through the
complete flowchart as many times as needed to understand the process involved. Note the

two distinct types of activities physical or processing activities such as GET OUT OF
BED, LIE DOWN, etc., and mental or sensory activities involving decisions, the outcome
of which is always expressed in terms of YES or NO.
Eventually program flowcharts must be translated into some particular high-level
language. Figure 12-1 illustrates two language approaches differing not in grammar but in
structure and organization. The language displayed is obviously not a programming lan-
guage that can be processed by a computer; it is an example oi pseudo code, which is simi-
lar to FORTRAN. Pseudo code does not have to be precise, and grammatical rules are

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:

IF something is true THEN execute something


ELSE execute something else

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.

2. Reading the code is somewhat difficult or inconvenient because of the TO state- GO


ments, which force the reader to visually skip down to a particular line, then surge up
again somewhere in the code only to sink down again to a lower level and resurface mo-
ments later.
474 STRUCTURED PROGRAMMING

Flowclwn Trudiiional — version


Gel oul of bed wake-up-routine
get out of bed

Yes if it is non exercise day


th enskjH n reliefi

[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

Figure 12-1 Traditional Versus Structured.


STRUCTURED PROGRAMMING 475

Structured design Version Structured design Version 2

WAKE-UP-ROUTINE. WAKE-UP-ROUTINE.

GET OUT OF BED GET OUT OF BED


IF IT IS NON EXERCISE DAY IF IT IS NON EXERCISE DAY
THEN SIGH IN RELIEF THEN SIGH IN RELIEF
ELSE ELSE
EXECUTE EXERCISES EXECUTE EXERCISES
BOIL WATER EXECUTE COFFEE PREPARATION
FILL CUP EXECUTE TASTE WHILE
ADD COFFEE SUGAR = INSUFFICIENT
EXECUTE TASTE WHILE EXECUTE DRINK-AND-CLEAN-UP
SUGAR = INSUFFICIENT
DRINK CUP
CLEAN DISHES
STOP EXERCISES
LAMENT
EXECUTE PUSH-UPS 10 TIMES
EXERCISES GET DRY
LAMENT PUSH-UPS
EXECUTE PUSH-UPS 10 TIMES LIE DOWN
GET DRY PUSH UP
PUSH-UPS GRUNT
LIE DOWN COFFEE PREPARATION
PUSH UP BOIL WATER
GRUNT FILL CUP
TASTE ADD COFFEE
ADD SUGAR TASTE
STIR ADD SUGAR
TAKE SIP STIR
TAKE SIP
DRINK-AND-CLEAN-UP
DRINK CUP
CLEAN DISHES
STOP

Structured design Version 3

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.

Figure 12-1 Continued


476 STRUCTURED PROGRAMMING

Much concentration is needed to keep up with what is happening.


This structural or traditional approach to writing code as illustrated in version is the
way it is done in FORTRAN. However, since the early 1970's new ideas in the area of
program structure have evolved into what is now called "structured programming." As
mentioned in Section 12-1. constructs are becoming available in FORTRAN compilers
to allow us to write code in a "structured" way.

12-1-2 Elements of Structured Programming


Consider the pseudo code of version in Figure 12-1 See how the program has been writ-
1 .

ten in four independent modules/sections/parts/paragraphs, each representing distinct


activities. Simply by reading the first paragraph entitled WAKE-UP ROUTINE the read-

er gets an overview of the process involved. The statement in the WAKE-UP ROUTINE
paragraph

ELSE EXECUTE EXERCISES

is self-explanatory and at this level of generality requires no further elaboration on the


part of the reader. If the reader wishes to get down to a sub-level of specificity he or she
can glance at the EXERCISES paragraph to extract the details. As far as readability is
concerned, the reader is spared the minutia if that is what he or she wishes to avoid at this
particular time.
Note the absence of any GO TO statements — in effect, version 1 reads like English
prose in that it is a sequence of paragraphs made up of sentences (topics and supporting
items.)
Look now at version 2; the size of the WAKE-UP ROUTINE has been greatly re-
duced, and certain activities have been consolidated into tasks and relegated to para-
graphs, for example, COFFEE-PREPARATION, the details of which can certainly be
omitted from the overview paragraph WAKE-UP ROUTINE. The main paragraph has
become a little more general with the inclusion of the EXECUTE COF-
FEE-PREPARATION statement, which is still by itself self-documenting and
self-explanatory.
Finally, look at version 3; the WAKE-UP-ROUTINE has shrunk drastically to three
lines of code while still program something version was in-
radiating the essence of the —
capable of doing no matter which three lines were read. With this ability to break down a
problem into independent pieces, a lead programmer could very easily assign members of
his team to work on or write these different pieces —
and test them independently too!
Figure 12-1 displays only three structured versions of the program; however, many
other variations could have been produced just as well. All three versions display a com-
monality of structure, discipline, and style. Indeed, all three versions exhibit three and
only three types of logical structures.

1. The sequence structure:


In each procedure statements are executed sequentially, i.e., one after the other.
STRUCTURED PROGRAMMING 477

Example Sequence Structure

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

2. The selection structure:


YES or NO decisions are made on the basis of whether a particular condition met. If is

the condition met the THEN action specifies a


is steps to be taken for that condi-
list

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

IF IT IS NON EXERCISE DAY


THEN SIGH IN RELIEF

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

Example EXECUTE structure

EXECUTE EXERCISES EXECUTE


EXERCISES

GET DRY GET DRY

The paragraph EXERCISES is


EXERCISES _ J
performed once and control
is returned to the sentence
GET DRY.

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

b. A paragraph is executed an unspecified number of times while a particular condi-


tion within the procedure is met. Control is then returned to the statement follow-

ing the EXECUTE.

Example EXECUTE WHILE structure

EXECUTE TASTE WHILE ^^/sugar = \___^


SUGAR = INSUFFICIENT
DRINK CUP

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

Initial specification of a process First redefinition as a sequence of tasks

write paycheck for employee read employee data record


compute pay
write check

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.

12-2-2 IF THEN ELSE


The construct IF THEN ELSE is used to test for a condition and take appropriate action.
It has the general form:

IF condition THEN process ELSE process 2


1

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

First redefinition: read employee data record


compute pay
write check
Second redefinition: read employee data record
IF hours worked < 40 THEN compute regular pay
ELSE compute pay for 40 hours
compute overtime pay
add overtime pay to regular pay
write check

In FORTRAN the code could be written as:


1
READNUM, HRS, RATE
READ(5,1)NUM,HRS,RATE ll 1
NO
IF HRS GT 40 THEN DO
( . . )

REGPAY = 40*RATE REGPAY = 40*RATE


OTPAY = HRS-40 *RATE* 1
(
)
. OTPAY = (HRS-40)*RATE*I.5
REGPAY = REGPAY + OTPAY REGPAY = REGPAY + OTPAY
ELSE DO
REGPAY = HRS*RATE REGPAY = HRS*RATE

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

The DO CASE is not implemented in FORTRAN, however, in WATFIV the DO CASE


construct has the following general form:

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:

C DO CASE DEPENDING ON ISTAT


C
DO CASE ISTAT
STRUCTURED PROGRAMMING 485

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

To compute a deposit or withdrawal the following code could be used:

Pseudo code
DO CASE deposit
balance = balance + amount
CASE withdrawal
balance = balance - amount
IF overdrawn THEN write appropriate message
ELSE exit

The code for the above might be:

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

Figure 12-4 WHILE DO.

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

COUNT = COUNT -hi


END WHILE

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

C READ A DOLLAR BILL


C KOUNT =
READ, BILL
C
C INITIALIZE COUNT OF THE NUMBER
C OF QUARTERS
False
KOUNT =
C
C SUBTRACT .25 FROM THE AMOUNT GIVEN,
C WHILE THIS AMOUNT IS GREATER THAN
C COUNT THE NUMBER OF TIMES 25 IS .
BILL = BILL - .25

C SUBTRACTED FROM THE AMOUNT


C
WHILE (BILL - .25.GE.0)D0 KOUNT = KOUNT + I

BILL = BILL -.25


KOUNT ^ KOUNT + 1
END WHILE
C
PRINT COUNT
C
C
PRINT THE NUMBER OF QUARTERS L 7
PRINT, KOUNT, 'QUARTERS'
STOP ( STOP j
END
Note that in the above example the condition tested involves the value of BILL, and there-
fore the value of BILL is changed within the WHILE loop.

12-2-5 Do and While Do


in many instances the DO loop and the WHILE DO construct can be used in-

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 ,

10 CONTINUE SUM = SUM -h X


AV = SUM/10. 1 = 1 + 1
PRINT, AVE END WHILE
STOP AV = SUM/10.
END PRINT, AV
STOP
END
488 STRUCTURED PROGRAMMING

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

ment, and no initialization statement (I = 1) is needed. This counter is auiomaticallv in-


cremented and tested at the object statement, and no increment statement (I = + I) is 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

index; thus DO 17 1 =4, 18,3 would


result in 3 being added to the current value of after I

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.

12-2-6 Execute Remote Block


The EXECUTE REMOTE BLOCK construct allows a block of statements to_be executed
simply by naming the block. It is similar to FUNCTION or SUBROUTINE subpro-
grams, but the block of statements appears in the same program calling it. The general
form of the construct as well as its WATFIV implementation is:

EXECUTE name Must be same name

,— REMOTE BLOCK name


statements

L-END BLOCK

END

1. When the EXECUTE statement is processed, control transfers to the REMOTE


BLOCK of statements named by name. These statements are executed up to the END
BLOCK, at which time execution is returned to the statement following the EX-
ECUTE.
2. No RETURN used in the REMOTE BLOCK— all statements between
statement is

REMOTE BLOCK END BLOCK are executed.


and

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

490 STRUCTURED PROGRAMMING

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 ,

C SHORTEST MALE AND FEMALE HEIGHTS.


C
30 WRITE(6,2)AVM,AVF,MMIN,FMIN
STOP
1 FORMAT II, F5,l) (

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 THE SHORTEST MALE HEIGHT MMIN (

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
( ) : ( ) :

C THE SHORTEST FEMALE HEIGHT.


C
REMOTE BLOCK FEMALE
F= F+1
SUMF = SUMF + HEIGHT
AVF = SUMF/F
IF HEIGHT LT FMIN FMIN = HEIGHT
( . . )

END BLOCK
END

Figure 12-5 The EXECUTE REMOTE BLOCK.


STRUCTURED PROGRAMMING 491

12-3 YOU MIGHT WANT TO KNOW


1. What languages are better than FORTRAN for implementing structured programs?

Answer: Any block structured language such as


COBOL (COmmon business Oriented Language)
ALGOL (/ILCOrithmic Language)
PL/I (Programming Language f)
A?L{A /Programming Language)

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?

Answer: In it may be possible to write more compact code using the


some instances
traditional approach. The value of structured programming is seen most clearly in the
development of large programs. The top-down approach enables the identification of
relatively independent program modules (processes). Such modules can be coded and
tested separately. The use of structured constructs imposes a discipline on program-
mers, enabling the separately constructed modules to fit together without mutual in-

terference. A team working on programming


a project can be assigned separate mod-
ules. Errors can also be traced more easily than in a traditional setting where the flow-
path may be very circuitous and difficult to follow.

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.

5. Are there any other structured statements allowed in WATFIV?


Answer: Yes. The WHILE EXECUTE REMOTE BLOCK construct allows a block of
statements to be processed while a certain condition is true. The condition is tested
before each execution of the REMOTE BLOCK. The general form of this statement is:
492 STRUCTURED PROGRAMMING

WHILE {condition) EXECUTE name process


RhMOTi: BlOCk

REMOTE BLOCK name


rest 01
statements
program

END BLOCK f STOP


J

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:

C\LL'\K\nSL {deck, punch)

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

12-4 PROGRAMMING EXAMPLES


12-4-1 File Merging
Write a program in pseudo code to merge the contents of two sequential files (FILE and I

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.

read file I record


read file 2 record
WHILE NOT (end of file 1 or end of file 2) DO
IF record key I < record key 2 THEN write file I record on output file

read file 1 record


ELSE write file 2 record on output file

read file 2 record


DO CASE end of file 1

WHILE NOT end of file 2 DO


write file 2 record on output file

read file 2 record


CASE end of file 2
WHILE NOT end of file 1 DO
write file 1 record on output file

read file 1 record

Figure 12-6 File-Merging Program.

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

Figure 12-7 Sort Program.

12-4-3 Course Information


On we have enrollment information records on 100 courses offered at Wakeup
tape unit 2
College. On each record we have the course index numbers in columns 5-8, the current en-
) )

494 STRUCTURED PROGRAMMING

rollment in columns 9-1 1, and the maximum enrollment allowed


columns for the course in
78-80. When a student requests a course, his or her punched on a card in ID number is

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-

pacity. For example:

STUDENT xxxxxxxx IS ENROLLED IN COURSE NO. xxxx


COURSE NO. xxxx if FULL.
A program to solve this problem is shown in Figure 12-8.

INTEGER INDEX (100) CUR (100) MAX (100) ID, COURSE


, , ,

C INDEX IS AN ARRAY HOLDING THE 100 COURSE NUMBERS


C CUR IS AN ARRAY HOLDING THE CORRESPONDING ENROLLMENTS FOR EACH OF THE
C 100 COURSES
C MAX IS AN ARRAY HOLDING THE MAXIMUM ENROLLMENT FOR EACH OF THE 100
COURSES THESE VALUES ARE READ OFF OF 100 RECORDS ON TAPE UNIT 2
.

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 '

C COURSE IS USED TO READ THE REQUESTED COURSE INDEX NO .

C AT END OF FILE, STOP EXECUTION


100 READ (5, 18. END =60) ID, COURSE
18 F0RMAT(I9,2X,I4)
C FIND COURSE NUMBER REQUESTED IN THE ARRAY INDEX AND COMPARE ENROLLMENT
C WITH MAXIMUM ALLOWED.
DO 15 I = 1,100
IF COURSE EQ INDEX I
( . THEN DO
. ( ) )

IF(MAX(I) .GE.CUR(I) THEN DO )

C REQUESTED COURSE WAS FILLED TO CAPACITY


WRITE(6,80)C0URSE
80 FORMAT IX COURSE NO 14 ( IS FULL,
'
.
'
,
'
.
'
)

C REQUESTED COURSE NOT FILLED TO CAPACITY-ENROLL STUDENT


C IN CLASS BY ADDING 1 TO THE ENROLLMENT
ELSE DO
CUR(I) =CUR(I) +1
WRITE (6, 44) ID, COURSE
44 FORMAT IX STUDENT ',19 IS ENROLLED IN COURSE NO
( ,
'
14 ,
'
.
'

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

12-4-4 Solution to a Quadratic Equation


The two solutions to quadratic equations of the form ax' + bx + c = are given by the
following formulas:

_ -b + \/ b~ - Aac _ -b - V b' - Aac


•^' -^^
Ta Ya

\{ 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

REMOTE BLOCK QUAD


FLAG =
IF(A.NE.O) THEN DO
DISC = B**2-4*A*C
IF{DISC.GE.O) THEN DO
Xl= (-B + SQRT(DISC) )/(2.*A)
X2 = -B - SQRT DISC /( 2 *A
( (
) )
.

ELSE DO
FLAG = 1
END IF
ELSE DO
Xl = -C/B
X2 = X1
END IF
END BLOCK

10 F0RMAT(3F10.0,T80,I1)
(

11 FORMAT '0A=' .F11.0.2X, 'B=' ,F11.0,2X, 'C=' ,F11.0


12 FORMAT + T50 (
NO SOLUTION
' ' , .
'

'

13 FORMAT( '+' ,T50. 'Xl=' ,F11.3,2X, 'X2=' ,F11.3)


END

Figure 12-10 Solution of Quadratic Equations.


496 STRUCTURED PROGRAMMING

12-5 EXERCISES
12-5-1 Self Test

1. Write FORTRAN or WATFIV code for each of the following:


a. IFa < bTHENx = x + 1

ELSE y = > + I

b. IFs < t THEN write s,t

ELSE IF s> THEN t write t,s

ELSE write s

c. a = I

X =
WHILE a < 10 DO
X = X + a
a = a + I

d. WHILE NOT end of file DO


read a,b,c
I F not end of file TH EN write a,b,c
ELSE exit

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

CASE num >


p = p+\
STRUCTURED PROGRAMMING 497

2. Is it necessary to have mutually exclusive conditions when using the CASE construct?
Why?

12-5-2 Programming Problems


Any programming problem from any chapter can be approached from the structured
point of view.

1 2-5-3 Answers to Self Test

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

b. IF(S.LT.T) G0T0 30 IF S LT T THEN DO PRINT S T


( . . ) , ,

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

affect the outcome.


INDEX

212-221 Array initialization and


andtheCHARACTER duplication 256-257
Absolute error 240-241 specification 218-221 Array manipulation 256-258
Accumulation of elements Alphanumeric variables, Array merge 258
258 initialization of 214-215 Arrays 251-253,256-268.270
Accumulation process Annotation block 102-103 initialization and dupli-
180-182 APE 6.491 cation of 256-257, 268

A format code 215-218, Apostrophe 49-50 input/output of


219-220.235-236 Applications program 14-15 256-268. 275-276
and alphanumeric data Area, calculation of 22-24 multidimensional
212-218 Argument 363 322-324, 325
and CHARACTER dummy 407 reversing 257
variables 219-220 Argument-expression 364 three-dimensional
form of 215 Arithmetic 27 320-322, 325, 330
Algebraic expression 28 Arithmetic IE statement two-dimensional. See
ALGOL 6.491 88-92 Two-dimensional array
Algorithm 55-56 form oi' 89 Array search 258
Alphabetic data 328-329 Arithmetic/logical unit 2 Assigned statement 219
Alphanumeric data Arithmetic operations 27 Automatic end of file
and the A format code order of operation in 28-30 129-130, 135,261
212-218 Array elements Average, calculation of
characterization of accumulation oi 258 250-251,311-312

499
1 1

INDEX

B COMMON statement Conversational mode 16. 17. 18

410-412.415.416.426-427 Counting 125. 128. 133


BACKSPAC L siaicmcnl 456 form of 412.427 CPU 3.10.12
Bar graphs 274-275 Compilation and loading 72 Cursor 462, 464
BASIC 6 Compiler 4, 34
Basic form for real constants Compile-time error 46
221 Complex data 231-233
Batch-processing mode 16-18
Complex roots, of a quadratic Data
Binary digit 21 equation 239-240 alphabetic 328-329
Bmomial expression, COMPLEX statement alphanumeric. See
computing 383-384 232-233 Alphanumeric data
BITs 211 Complex variables. complex 231-233
BLOCK DATA 427-428 input/output of 233 integer. See Integer data
Break-even analysis 369-370 Compound interest. logical. See Logical data
Bubble-sort 276-278 calculation of 100-102 real. See Real data

Compound logical expression Data deck 72-73


227-230 Data representation
Computed GO TO statement alphanumeric 212-221
103-104 internal. See Internal data
representation
CALL statement 407 Computer,
Carriage control characters model of 7-10 DAT.A statement

52-55 organization o\' 2-3 123-124. 140. 141

Central processing unit 3. 10. speed of operation of 5-6 form o\' 123

Computer access modes used to initialize arrays 268


12
Channel 12 16-18 Decimal numbers, internal
Computer error 6 representation of 234-235
Character set 25
Decision block 58-59
CHARACTHR SPECIFI- Computer hardware 10-13

CATION, and alpha- Computer language 6 DEFINE FILE statement

numeric data 218-221 Computer program 2, 4-5, 462

CHARACTER statement 14-15.55 Device-number 36.73


218-221 applications 14-15 D format code 224-226
initialization in 218 executive 14 DIMENSION statement
253-254, 256, 260
CHARACTER variables, monitor 14

compared with other operating s\ stem 14 form of 253.312


220-221 supervisor 14 for two-dimensional arrays
variables
212-213 translation 4. 14 312-314
Character string
variable 422-426
COBOL 6.491 user processing 14-15
Computer programmer 4 Direct-access files 461-469
Code
Computer software 14-15 defined 461-462
format. See Format code
131-132,134.261 Conjunction 227 example of use of 463-465
last card
object 34 Connector blocks 59-60 Direct-access READ statement
operation 4 Constant 25-26 462-463

pseudo 472-473.478-479 computing value of 22 Direct access WRITE


expressed in integer mode statement 462-463
source 34
trip 130, 131 25 DO CASE statement 482-485
Column limit 313 logical 226 DO nested
list, 267

Column method, for real 221-224 DO loop,


processing two- real mode for 25 compared uith WHILE DO
dimensional arrays 315 CONTINUE statement 487-489
explicit use of 259-262
Comment card 102 175-177, 183
Control cards 72-73 for two-dimensional arrays
Comment statement 102
COMMON block 426-427 Control unit 2 316,319
INDEX 501

DOstalemenl 170-175, END FILE 455 Flagging 327


182-183, 187-191 ENTRY 428-429 Floating-point form 211
llowchart symbol for extended READ 129 Floating-point numbers
187-191 GO TO 79-80 and integers 240-241
form of 171 IF THEN ELSE Flowchart 55-60. 145-146
DOUBLE PRECISION 93-96,479-482 system 465-469
statement 217,224-226. logical IF 80-88,99.230 Flowchart symbols 56-60
235 multiple RETURN connector block 59-60
form of 224 429-430 decision block 58-59
Dummy argument 407 READ 71-73,74 for the DO statement
Duplication and iniliali/ation RETURN 377-382 187-191
of arrays 256-257,268 REWIND 455-456 flowlines 59
Duplication factor 104-105 STOP 45,48 input/output block 56-58
WHILE DO 487-489 processing block 58
WRITE 36-37,38,40,44, for subroutines 420.422
EBCDIC 236 45, 47 terminal block 56
E format code 222-224 EXECUTE REMOTE Flowlines 59
Element 251 BLOCK construct Format code 38-45

END FILE statement 455 489-491 A 215-218,219-220.


End of file Execution-time error 46-47 235-236
automatic 129-130, 135 Executive program 14 D 224-226
last-card code method Explicit mode E 222-224
131-132, 134 specification 123 F 40-42. 75-77

trip-record method Exponential form, for real I 39-40, 75

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

ENTRY statement 428-429 output o\' 223-224 o\' 191-193


EQUIVALENCE statement Expression 27-30 slash (/) 135-139
432-433 logical 80, 85 T 42-43, 78

Error 46-47 Extended Binary Coded X 38-39, 79

absolute 240-241 Decimal Interchange Code FORMAT statement 37-45,

compile-time 46 236 47. 73-79

execution time 46-47 EXTERNAL statement form of 38, 74

logical 46-47 430-432 reuse and (/) 284-287


relative 240-241 Format-statement-
round-off 241 number 36, 73

syntax 46 Formatted versus


Executable statements 140 unformatted statement
arithmetic IF 88-92 Factorial N 184 454-455, 456-457
BACKSPACE 456 F format code 40-42, 75-77 FORTRAN 4
CALL 407 Field 128 arithmetic operations in 4
computed GO TO 103-104 File 128,450-451,456 character set for 25
continuation 105-106 direct access 461-469 constants for 25-26
CONTINUE 175-177, 183 File creation 457 problem solving through
direct-access READ File merging 493 use of 22-25
462-463 File organization 450-451 variables for 26-27
direct-access WRITE File processing statement versions of 6

462-463 454-456 FORTRAN coding


DO 170-175, 182-183, Finite and infinite sums form 32-34
187-191 50-51 FORTRAN expression 28
DO CASE 482-485 Fixed point 21 1 FORTRANjob 34-35
5

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

32-34 nonexecutable. See


arithmetic IF 88-92 Nonexecutable statements
BACKSPACF 456 READ 72-73.74 H
REAL High-level language 4
CALL 407 123

CHARACTER 218-221 RETURN 377-382 Hollerith code 16

COMMON 410-412.415. REWIND 455-456


416.426-427 specification. See

COMPLEX 232-233 Specification statements I

52
computed GO TO 103-104 STOP 45.48 Identification field

continuation 105-106 SUBROUTINE 407-410 I format code 39-40. 75

CONTINUE 175-177. 183 unconditional transfer IF statement


with alphanumeric data
DATA 123-124. 140. 141 79-80
DEFINE FILE 462 variable DIMENSION 217
DIMENSION 253-254. 422-426 arithmetic 88-92

256.260.268-271 WRITE 36-37. logical 80-88

DIMENSION lor 38,40,44.45,47 IFTHEN ELSE


two-dimensional FORTRAN supplied function statement 93-96. 479-482

arrays 312-31 363-364. 368 IF THEN structure 94

direct access Fractional numbers 98 nested 95-96

READ 462-463 Frequency distribution IMPLICIT statement

direct access 273-274. 325-327 143-144

WRITE 462-463 Function Implied DO list 263-266.

DO 170-175. defined 363-364 270.271


182-183. 187-191 form of 364 for two-dimensional

DO CASE 482-485 mathmatical 364-366 arrays 316-319


Income calculation 51-52
DOUBLE PRECISION mode conversion 366
217,224-226,235 programmer-defined Increment 171-172

END 45-46.48 373-390 Index 171.252-253

END FILE 455 speech 366, 367. 368 Initial 171

ENTRY 428-429 TAN 370-372 Initiali/alion 124. 125

EQUIVALENCE 432-433 Function invocation statement of alphanumeric variables

executable. See 377 214-215

Executable statements FUNCTION Initialization and


READ 129
extended statement 377-382 duplication of arrays

EXTERNAL 430-432 Function subprogram 256-257. 268

processing 454-456 375-376 Input devices 1.12


for file
Input output block 56.58
FORMAT 37-54.47.73-79 position in job deck of 382
formatted versus reasons for using 385-386 Input output devices 12

unformatted 454-455. Input/output of arrays


456-457 256-268. 275-276,

FUNCTION 377-382 Input output of

function invocation 377 GOTOstalemcnl complex variables 233

GO TO 79-80 79-80 Input/output o\'

IF THEN ELSE 93-96. computed 103-104 two-dimensional

479-482 form of 79 arrays 315-320

IMPLICIT 143-144 GPSS 6 Integer arithmetic 27

INTEGER 123 Grade assignment 209-2 Integer data 26

LOGICAL 227-230 Graph 280-281 representation o\' 2 1 1


INDEX 503

use of I format code for Logical IF statement Named COMMON block


39-40 80-88, 99, 230 426-427
Integer mode, for constants form o\' 80, 85, 230 NAM ELIST declaration
25 logical expressions in 230 281-284
Integer numbers 49 Logical operation 99 NAM ELIST slatemenl 282
Integers and floating- Logical problems 237 and READ statement
point numbers 240-241 Logical replacement 282-283
INTEGER statement 123 statement 227 and WRITE statement
Integer variable 26-27 LOGICAL statement 283-284
Integer variable names 217 227-230 Nanosecond 5
maximum/
Interchange Logical variable 236 Negative numbers 48-49
minimum sorting 279-280 Loop 125. See also DO loop Nested DO list 267
Interest nested 179-180 Nested IF/THEN
compound 102 transfer into and structures 95-96
short-term 143 out of 177-178, 183 Nested loops 179-180
Internal data Loop control 125-127 Nested parentheses 28. 49
representation 21 1-212 Looping 79 Nonexecutable statements
decimal numbers 234-235 Lottery 384-385 122, 124, 140
integer data 21 1 CHARACTER 218-221
real data 211-212 M comment 102
Internal representatu)n of COMMON 410-412,
multidmiensiona! arrays Machine-dependent language 415,416,426-427
322-324 4 COMPLEX 232-233
Inventory 452-453 Machine language 4 DATA 123-124, 140, 141
Investment 416-417 Mass storage devices 12 DEFINE FILE 462
Mathematical functions DIMENSION
364-366 253-254,256,260,
Memory unit 2 268-271,312-315
Job deck Merging 258, 458. 493 DOUBLE PRECISION
position of function Mixed-mode expression 217, 224-226,235
subprogram in 382 30-3 END 45-46,48
position of subprograms Mixed-mode input 78 EQUIVALENCE 432-433
in 412-413 Mixed-mode replacement FORMAT 37-45,47,73-79
statement 31 FUNCTION 377-382
Mode conversion IMPLICIT 143-144
function 366 INTEGER 123
Keypunch machine 16
Monitor program 14 LOGICAL 227-230
Multidimensional array NAMELIST 281-284
322-324. 325 REAL 123
Language, machine 4
Multiple entry SUBROUTINE 407-410
form of 428 variable DIMENSION
Last-card code
to subroutines 428-429 422-426
131-132, 134.261
Multiple return Number generation 128
L format code 230-233
form of 429 Number representation
Literal string 212
from subroutines 429-430 211-233
Logical constants 226
Multiple RETURN accuracy of 234-235
Logical data 226-233
statement 429-430
and the L format code
Multiprogramming 12
230-233
Logical error 46-47 Object code 34
Logical expression Online communication
N
80, 85, 230 Operating system
compound 227-230 N I, calculation of 184 program 14
504 INDEX

Operation code 4 representation of 21 1-212 COMMON 410-412.415,


Outpul deMces 2. use of F format code lor 416.426-427
40-42 COMPLEX 232-233
Real mode, for constants 25 DATA 123-124. 140. 141
Real numbers 49 DEFINE FILE 462
Parenlheses 47 RbAL statement 123 DIMENSION 253-254,
nested 28,49 Real variable 26-27 256.260.268-271.312-315
used in expressions 27, 28, Record 128,450-451 DOUBLE PRECISION
29 Record key 450-451 217,224-226,235
Pay. calculation o\' Relative error 240-241 explicit mode
10-1 \
Replacement statement 30 specification 123
Percentage, computing logical 227 FORMAT 37-45
141-142 mixed-mode 31 FUNCTION 377-382
Physical job deck 72-73 Report, computer produced IMPLICIT 143-144
PL/1 6,491 186-187 INTEGER 123
Prime numbers 368-369 Report generation 458-461 LOGICAL 227-230
Problem-oriented Representation of numbers NAMELIST 281-284
language 4 211-233,234-235 REAL 123
Process 479 RETURN statement SUBROUTINE 407-410
Processing block 58 377-382, 429-430 variable DIMENSION
Programmer 4 form of 429 422-426
Programmer-defined multiple 429-430 SQRT function 236
(unctions 373-390 Reversing 257 Standard deviation 184
function subprograms REWIND statement 455-456 Statements. See Executable
of 375-376 Roots of a quadratic statements;
Programming, structured. equation 239-240 FORTRAN statements:
Sf*? Structured Round-off error 241 Nonexecutable statements:
programming Row limit 313 Replacement statements:
Pseudo code 472-473, Row method for processing Specification statements
478-479 two-dimensional arrays Statement function 386-390
Punched card 15-16 314 example of use of 389
RPG 6 Statement function
definition, form of 386
Statement number 38
Quadratic equation STOP statement 45,48
complex roots of Searching 258 Structured programming
239-240 Significant digit 233-234, 235 advantages of 491
solution to 100, Sign-off and sign-on elements of 476-478
417-418,495 procedures 18 example of 472-476
Sine o\' X. computation o\' pseudo code for
185 472-473.478-479
Slash (/) format code Structured pseudo code
Random numbers 194-195 135-139 472-473
Rational numbers 47 SNOBOL 6 Subprogram, position in

READ statement 71-73.74 Sorting 276-280.418-419.493 job deck of 413-414


extended 129 bubble 276-278 Subroutine
Real arithmetic 27 interchange maximum/ tlowcharl ssmbols for
Real constants minimum 279-280 420. 422
in basic form 221 Source code 34 multiple entry to 428-429
in exponential form Special function 366. multiple returns from
221-224 367. 368 429-430
Real data 26 Specification statements 122 SUBROUTINE statement
floating-point form of 21 CHARACTER 218-221 407-410
INDEX 505

Subscript 251.252,254-256, unconditional GO TO expression stored in 30


324 79-80 integer 26-27
Supervisor program 14 Translation program 14,34 integer data in 26
Switching circuit 237. 239 Translator 4 logical 236
Syntax error 46 Trip code 130, 131 real 26-27
System flowchart 465-469 Trif) record 130-131 real data in 26
Two-dimensional array Variable DIMENSION
312-320, 325 statement 422-426
DIMENSION statement for Variable-list 36, 73
Table look-up 272-273 312-314 related to list of
Tabulation 125 implied DO list for format codes 191-193
TAN function, graph of 316-319
370-372 input/output of 315-320 W
Telecommunication 12 processing 314-315
Terminal block 56 WATFIV 6

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

unconditional 79-80 Variable 26-27, 56


\
X

You might also like