You are on page 1of 307

B

1.390.750

"r

i: ; ta

'<*]&

FORTRAN 77
With MTS and the IBM PC

by
Brlce Carnahan
James O. Wilkes
College of Engineering
The University of Michigan
Ann Arbor

1988

Copyright 1988
by Brice Caraahan and James O. Wilkes
All rights reserved. This book or any part
thereof must not be reproduced in any form
without the written permission of the authors.

pV\cr

k^_

PREFACE
This book, together with its companion volume, The IBM PC and The
Michigan Terminal System, has been written primarily for the introductory fresh
man engineering digital-computing course, Engr. 103, at the University of Michi
gan. It should also be useful to others who wish to learn about the FORTRAN- 77
language and apply it to their own computing problems.
Chapters 1-3 and 6-11, being concerned with FORTRAN 77 exclusively, are
of general interest. Chapters 4 and 5 are of more local appeal, since they discuss
compilation and execution in specific situationsnotably with MS FORTRAN on
the IBM PC and with VS FORTRAN on the IBM 3090-600 mainframe computer
at the University of Michigan. Two features that should prove helpful are the sub
stantial number of example programs, and the end-of-section exercises, solutions
for all of which appear in Appendix A.
We wish to thank all those who have shared their computing knowledge with
us, particularly including Jim Rennell and Pankaj Shah, who have done excellent
work in maintaining the Engr. 103 3Com Ethernet local-area network in fine shape.
The assistance of Lili Kokkinakos and Laurie Breck in helping to prepare the
final version of the book is much appreciated. So, too, is the highly skillful and
untiring effort of Mich Rasulis, both in working with the typesetting program and
in drawing the figures.
For the technically minded, this book was composed on an IBM PC-AT
computer using the TgX "typesetting" program, and was printed on an Apple
LaserWriter printer. Eleven-point type was used for the majority of the text. The
figures were drawn using the MacDraw and CricketDraw programs on a Macintosh
computer.
Inquiries about this text should be directed to us, at the Chemical Engineer
ing Department, The University of Michigan, Ann Arbor, MI 48109-2136. Finally,
students enrolled in Engr. 103 at the University of Michigan are welcome to come
to our office, 3146 Dow Building, if they have questions about this book or any
other aspects of the course.
Brice Carnahan
James O. Wilkes
September 1, 1988

TABLE OF CONTENTS
Page
PREFACE

TABLE OF CONTENTS

iii

CHAPTER 1INTRODUCTION TO COMPUTERS AND FORTRAN


1.1
1.2
1.3

1.4
1.5

Introduction to Digital Computers


Development of the FORTRAN Language
Analysis of a FORTRAN Program
Example Program 1.1Triangle Problem, First Version
Example Program 1.2Triangle Problem, Second Version
Fundamental Concepts and Notation
Three Statements: GO TO, STOP, and END

1-1
1-6
1-9
1-11
1-14
1-19
1-22

CHAPTER 2ARITHMETIC STRUCTURES


2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8

Introduction
Types: Integer and Real
Constants
Variables
Function References
Operators and Expressions
Mixed-type Expressions
Assignment Statement

2-1
2-2
2-3
.2-5
2-7
2-10
2-15
2-17

CHAPTER 3INPUT AND OUTPUT


3.1
3.2

3.3

Introduction
List-Directed READ and WRITE Statements
Example Program 3.1List-Directed I/O
Example Program 3.2List-Directed I/O
Formatted READ Statement
iii

3-1
3-2
3-5
3-6
3-8

3.4
3.5
3.6
3.7

The FORMAT Declaration


The Formatted WRITE Statement
Literal Fields
Carriage Control
Example Program 3.3Formatted I/O

3-9
3-17
3-19
3-20
3-22

CHAPTER 4RUNNING FORTRAN-77 PROGRAMS ON THE IBM PC


4.1
4.2
4.3
4.4
4.5
4.6
4.7

Introduction
Compilation, Linking, and Execution
The Microsoft FORTRAN-77 Compiler/Linker for the
IBM PC
FORTRAN-77 in the FEC Laboratories
Example Compilation/Execution 4.1
Allocation of I/O Units
Example Execution 4.2I/O Assignments
Terminating Execution
Error Messages
Example Program 4.3Diagnostics

4-1
4-1
4-2
4-6
4-7
4-8
4-9
4-10
4-11
4-11

CHAPTER 5RUNNING FORTRAN-77 PROGRAMS UNDER MTS


5.1
5.2
5.3
5.4

5.5

Introduction
Compilation
Execution
Example MTS VS-FORTRAN 77 Compilation and
Execution
Example 5.1MTS Compilation/Execution
Error Messages

5-1
5-1
5-3
5-5
5-5
5-10

CHAPTER 6LOGICAL AND CONDITIONAL STRUCTURES


6.1
6.2
6.3
6.4
6.5
6.6
6.7
6.8
6.9

Introduction
Relational Operators and Simple Logical Expressions
Logical Operators and Compound Logical Expressions
Logical Assignment Statement
Complete Precedence Table for FORTRAN Operators
The Computed GO TO Statement
The Block IF ( IF/THEN/ELSE) Structure
Other Conditional Statements (Logical and Arithmetic
IF Statements)
Example Program 6.1Roots of a Quadratic Equation

IV

6-1
6-3
6-5
6-8
6-11
6-12
6-14
6-20
6-24

CHAPTER 7SUBSCRIPTED VARIABLES AND ITERATION


7.1
7.2
7.3
7.4

Introduction
Storage of Arrays and the DIMENSION
Declaration
Iteration: The DO and CONTINUE Statements
Several Examples Involving Iteration
Example Program 7.1 Table of Functions
Example Program 7.2Array Manipulation
Example Program 7.3Sorting the Elements of
a Vector

7-1
7-2
7-4
7-10
7-10
7-13
7-15

CHAPTER 8ADDITIONAL INPUT AND OUTPUT FEATURES


8.1
8.2
8.3
8.4
8.5
8.6
8.7

Introduction
The OPEN and CLOSE Statements
Reading and Punching Cards
The G, L, and T Format Codes
Formatted Array Input and OutputIntroduction
Examples of Array Input and Ouput
File-Control Statements: BACKSPACE, REWIND
and ENDFILE
Example Program 8.1 File-Control Statements

8-1
8-1
8-2
8-3
8-5
8-9
8-20
8-20

CHAPTER 9ADDITIONAL DECLARATIONS


9.1
9.2
9.3
9.4
9.5

Introduction
The DATA Declaration
Type Declarations
The EQUIVALENCE Declaration
Order of Statements in a FORTRAN Program

9-1
9-1
9-3
9-10
9-12

CHAPTER 10FUNCTION AND SUBROUTINE SUBPROGRAMS


10.1
10.2
10.3
10.4
10.5
10.6

Introduction
FUNCTION Subprograms
Example Program 10.1Function for Array Averages
The Dimensioning of Arrays in Subprograms
SUBROUTINE Subprograms
Multiple Entry PointsThe ENTRY Statement
The INTRINSIC and EXTERNAL Declarations
Example Program 10.2EXTERNAL and INTRINSIC
Declarations

10-1
10-5
10-8
10-17
10-20
10-26
10-28
10-29

10.7
10.8
10.9
10.10

Statement (Internal) Functions


The COMMON Declaration
BLOCK DATA Subprograms
Arrangement of Subprograms

10-30
10-33
10-36
10-36

CHAPTER 11CHARACTER STRUCTURES


11.1
11.2

11.3
11.4

Introduction
I/O of Character Information
Example Program 11.1Formatted Character I/O
Example Program 11.2List-Directed Character I/O
Manipulation of Character Information
Example Program 11.3Alphabetizing a List
Internal I/O Statements Involving Character
Variables
Example Program 11.4Plotting the Sine Function
Example Program 11.5Employee Information
Example Program 11.6A Small Word-Processor

11-1
11-2
11-3
11-5
11-8
11-9
11-13
11-14
11-18
11-20

APPENDIX A:

Solutions to Exercises

A-l

APPENDIX B:

Summary of Statement Types

B-l

INDEX

1-1

VI

CHAPTER 1
INTRODUCTION TO COMPUTERS AND FORTRAN

1.1 Introduction to Digital Computers


Although digital computers are often viewed as very fast numerical calcula
tors, they are, in fact, rather general devices for manipulating symbolic informa
tion. In most applications, the symbols being manipulated are numbers or digits
(hence the name, digital computer), and the operations being performed on these
symbols are the standard arithmetical operations such as subtraction and divi
sion. However, the symbols might just as easily have nonnumerical values and
the operations be nonnumerical in nature. For example, the symbols might be
characters such as letters and punctuation marks, and the operations might result
in the parsing of sentences for their word and phrase structure. A general-purpose
computer can be instructed to accept, store, manipulate, and display virtually any
kind of information in properly encoded symbolic form.
General-purpose computers are designed to solve essentially any problem
that is computable. Computability has a rigorous mathematical or logical meaning,
but an intuitive understanding of the term is adequate for most programmers. A
computable problem is one that can be stated unambiguously and for which an
unambiguous terminating solution procedure or algorithm can be outlined, step by
step. If the algorithm is in graphical form it is usually called a flow diagram; if it is
a list of commands that can be interpreted directly by a computer, the algorithm
is called a program.
Although we tend to view a digital computer as a unit, that is, as a single
problem-solving machine, every computer is in fact a collection of a large number
of inter-connected electromechanical devices, all directed by a central control unit.
Fortunately, an understanding of computer operation and the ability to use a
computer does not require detailed knowledge either of electronics or of hardware
(the physical equipment) construction. An overall view of the organization of the
computer with emphasis on function rather than electrical or mechanical details
is sufficient.
Viewed functionally, all items of equipment associated with a digital com
puter can be grouped into four general categories:
1. Memory.
2. Input/output units.
1-1

Chapter 1 Introduction to Computers and FORTRAN


3. Arithmetic unit.
4. Control unit.
The machine shown in Fig. 1.1 is hypothetical, but typifies most currently
available digital computers. Specific operating details for each of the many com
puters now in use will vary from one machine to the next.

Input
Devices

MEMORY
(Store)

Output
Devices

Arithmetic
Unit

Control Unit

Fig. 1.1 Overall digital- computer organization.


(Lines between units show flow of information.)
The Memory. The principal or fast memory or store is the heart of the
digital computer, and consists of solid-state devices in which a large number of
binary digits or bits can be saved and retrieved rapidly. Since almost any kind of
information (Greek letters, punctuation marks, etc.) can be encoded as a unique
sequence of binary digits, the memory can be viewed functionally as a place where
any kind of digitally encoded information can be stored and in turn retrieved.
Since the store is considered to hold a large collection of binary digits, most
machines use the binary number system for internal calculations, and are hence
called binary computers. To simplify the problem of locating any sequence of digits
in the memory, the overall collection of storage elements is usually divided into
smaller addressable packages, the smallest of which contains eight binary bits and
is called a byte. Depending on the particular computer, groups of 16, 32, and 64
binary bits are called half, full, and double words, respectively.
The memories of most digital computers are constructed so that the content
of a memory word may be retrieved or read without destroying it (non-destructive
read-out); on the other hand, when a new number is stored or written into a
memory word, the previous content of that word is lost (destructive read-in). This
is completely analogous to the operation of a tape recorder: recorded information
may be played back without destroying it; when a new signal is recorded over
previous information, the earlier recording is destroyed or erased in the process.
Access time (the time required to retrieve one or more bytes of stored in
formation) for semi-conductor memories is measured in billionths of a second or
1-2

1.1 Introduction to Digital Computers


nano-seconds, and is the same for all memory locations, regardless of their ad
dresses. The fast memory is a relatively expensive part of the computer, although
advances in semiconductor technology have reduced the cost substantially over the
past few years. To back up the fast store, there is a variety of other storage devices
with longer access times, but with much larger capacities and lower initial costs.
The most important of the secondary or peripheral storage devices are the disk file
(and its smaller version, the diskette), and magnetic tape.
Input and Output (I/O) Equipment. The function of the I/O equipment is
to allow communication between the user of the machine and its memory. There
may be several such devices, depending on the size and complexity of the comput
ing installation.
For small computers, the keyboard is commonly used for input. However,
other input devices can include punched cards and magnetic-tape units. A lightpen or a movable "mouse" can also be used for drawing pictures on a cathode-ray
tube screen or for making selections from a displayed "menu." In fact, almost
any signal-generating device (for example, an electrocardiograph machine) can be
adapted as a suitable input device for a computer. In some computing installations,
small computers are employed for input and output to larger computers.
The output devices are often similar to the input devices. For small comput
ers, a TV monitor and a dot-matrix printer are commonly used for output. Other
output devices can include magnetic tape drives, high-speed laser-driven printers,
synthetic speech units, and so on.
The Arithmetic Unit. The ability to save and retrieve information is useful
in itself. However, to solve a problem, we would like to read information (data)
into some words of memory, operate on this information in some planned way to
produce results (which could be stored in other words of the memory), and finally
to display the data and results on some output device.
Information in the memory that is to be manipulated is first read nondestructively and passed to a part of the computer called the arithmetic unit. The
latter contains all the circuitry required to perform the standard arithmetical oper
ations (such as addition, subtraction, multiplication, and division) and also many
other nonarithmetical operations such as the shifting or digit-wise examination of
numbers, the comparison of numbers for sign, relative magnitude, and so forth.
Each digital computer has a fixed number of distinctly different operations,
called machine instructions, which the arithmetic unit is capable of executing. In
addition, some other machine instructions are used for controlling the reading and
writing operations of the I/O devices. Most large computers have 200 or more
such operations in their instruction repertoire. The instruction repertoire for each
different model of computer is usually different from that of all other machines.
The results of operations in the arithmetic unit are then stored in selected memory
locations.
With the addition of the arithmetic unit, the digital computer now begins
to assume a meaningful form. The machine can read data from its environment
1-3

Chapter 1 Introduction to Computers and FORTRAN


and enter them into the memory. The contents of various memory words can
then be manipulated in the arithmetic unit by means of the operations that the
computer is designed to perform. The results of these operations can be stored in
the memory along with the original data and subsequently retrieved for display on
the output equipment. The sequence of events is:
1.
2.
3.
4.

Read data into the memory via the input equipment.


Operate (in the arithmetic unit) on the data stored in the memory.
Store in the memory the results of these operations.
Retrieve the results from the memory for display on the output equipment.

The Control Unit. Obviously, in order to process data in a meaningful way


and produce useful reults, the computer must have associated with it a controlling
device that supervises the sequence of activities taking place in all parts of the
machine. This control equipment must decide:
1. When (and with which input device) to bring information into the memory.
2. Where to place the information in the memory.
3. What sequence of operations on information in the memory is to be done in
the arithmetic unit.
4. Where intermediate or final results of operations in the arithmetic unit are
to be saved in the memory.
5. When, and on which output device, results are to be displayed.
With the addition of the control unit, (see Fig. 1.1), we now have a machine
that is capable of solving suitably stated and defined problems, given a list of com
mands for the operations to be performed. Often, the combination of arithmetic
and control units is called the central processing unit (CPU); in microcomputers,
the CPU is called the microprocessor.
How does the machine user indicated what the machine is to do to solve his or
her problem? First, the problem must be examined, and a step-by-step procedure
or algorithm outlined for its solution. A list of commands, called a program, is then
made from the instruction repertoire, in order to cause the computer to implement
the algorithm. The instruction must be ordered in the proper sequence; only those
in the instruction repertoire may appear in the program.
Machine-Language Instructions. When using a pocket calculator, the user
assumes several of the functions of the control unit in deciding which number
or operation is to be used next. Typically, a new number or instruction might
be entered every few seconds. With the very high internal operating speed of a
digital computer (millions of individual instructions are executed every second on
the larger machines), it is impractical for the machine user to enter commands
from the keyboard. Consequently, some other approach is necessary to allow very
rapid processing of machine instructions.
Because direct communication between the machine and its environment
involves the use of slow mechanical equiment, any approach that requires such
1-4

1.1 Introduction to Digital Computers


contact continuously, such as pressing keys, or even reading from punched cards,
is impossibly slow. One solution to this problem was first suggested by Burks,
Goldstine, and von Neumann. f Since a program is an assembly of information,
and the memory of a computer can be viewed as a place for storing any kind of
information, the program can be stored in the memory along with the data and
results. Virtually all the general-purpose computers now available are organized
this way, and are consequently known as stored-program computers. Since only
digits may be stored in the memory, the instructions must be encoded in digital
form before being stored. The code used is called the machine's language, and the
encoded program is known as a machine-language program.
The ultimate form of each machine-language instruction must be a sequence
(32 in number, for example) of binary digits corresponding to the normal mode of
storage in the machine. Since a complicated problem might require many thou
sands of such instructions, the writing of an error-free program would be extremely
tedious. In addition, in order to write programs in machine language, one must
be reasonably familiar with all the instructions in the repertoire of the machine.
Obviously, easier ways of communicating with the computer are required
to achieve programming efficiency, and symbolic languages for describing algo
rithms have been developed for this purpose. Here, symbols and recognizable
words (rather than sequences of binary digits) are used for representing the oper
ations required in the algorithm.
Indeed, most users would prefer to communicate with the machine in a
familiar symbolic form that comprises algebraic notation, English words, etc., and
to be able to write a program in a form such as:
START

READ X. Y. Z
U - (X + Y)/Z
PRINT X. Y. Z. U
GO TO START

Thus, detailed knowledge of machine-language instructions would be unnec


essary and the language might hopefuly be used to describe programs for more than
one computer, making it possible to interchange programs with other computer
users.
Computer languages similar to that illustrated above, and allowing straight
forward description of an algorithm, are called algebraic, algorithmic, or procedureoriented languages. The languages are (insofar as is possible), machine indepen
dent; that is, details of hardware organization or of machine language are not
apparent to the user of the language. Programs written in such languages cannot
t A.W. Burks. H.H. Goldstine. and J. von Neumann. "Preliminary Discussion of the Logical Design of
an Electronic Computing Instrument." a report prepared for the Ordnance Dept.. U.S. Army. at the
Institute of Advanced Study, Princeton. New Jersey. June. 1946. Reprinted in Datamation. Vol. 8,
Nos. 9 and 10. 1962.

1-5

Chapter 1 Introduction to Computers and FORTRAN


be executed directly by the computer; they must first be translated into equiva
lent machine-language programs. The programs that implement the translation
are called compilers.
Following Fig. 1.2, a source program written in the procedure-oriented lan
guage is first translated into an object or machine-language program. The resulting
object program is then stored in the memory and is subsequently executed by the
computer. Thus, the processing of a program written in a procedure-oriented
language occurs in two steps:
1. Translation or compilation.
2. Execution.
INPUT

OUTPUT

Step 1
Compiler
Program

(e.

Program
j., FORTRAN)

Memory

Compiler
Program

Object Program
in
Machine Language

Step 2
Memory
Program
Object
Program

Fig. 1.2 Steps during compilation and execution.


FORTRAN-77 (or simply, FORTRAN) is one of the most popular procedureoriented languages and will be discussed in the rest of this book. Note finally that
since each different model of computer has its own machine language, there must
be a compiler for each procedure-oriented language for every different kind of
computer! Fortunately, FORTRAN translators are available for most machines on
the commercial market, so that FORTRAN programs can be processed on most
digital computers now in use.
1.2 Development of the FORTRAN Language
FORTRAN-77 is a procedure-oriented language having a well-defined syntax
or grammar, that was developed to allow the unambiguous description and imple
mentation of algorithms, particularly those of a numerical nature. FORTRAN-77
(or, more simply, FORTRAN) is one of the programming languages that is most
1-6

1.2 Development of the FORTRAN Language


widely used by scientists and engineers today. This popularity stems from three
historical facts:
1. FORTRAN-77 is a direct descendent of FORTRAN-I, the first procedureoriented language.
2. The FORTRAN family of languages was developed by the International
Business Machines Corporation, which has featured prominently in com
puter sales in the United States and around the world.
3. In order to remain competitive in both hardware and software, other man
ufacturers have developed FORTRAN compilers for their computers. As a
result, virtually every manufacturer supplies a FORTRAN compiler for each
machine in its product line.
Almost by default, FORTRAN became for many years the universal comput
ing language for enginering calculations, while many other "universal" computing
languages have come and gone. This is not to say that FORTRAN will never
be displaced by better and more powerful procedure-oriented languages such as
PASCAL, but that its continued use seems assured.
We will begin with a brief description of the development of the FORTRAN
family of programming languages. The first mention of a FORmula TRANslation
System seems to have occurred in an internal IBM report, dated late in 1954.f The
first translator for the original FORTRAN language, later known as FORTRANI, was released in 1957 for use on the first of the IBM large-scale computers,
the IBM 704. An improved translator that allowed users to define their own
functions and subroutines was released in 1958, and this expanded language was
called FORTRAN-II.
A FORTRAN-III language appears to have been developed and employed
internally at various IBM installations, but was never released for customer use.
In 1962, the FORTRAN-IV language specifications were published; by 1965, most
manufacturers were committed to the production of compilers for some version of
FORTRAN for their machines.
Fortunately, the situation has been clarified somewhat in the intervening
years by the publication of two reports by the American Standards Associa
tion, later known as the American National Standards Institute or ANSI. The
first report, ratified in 1966, defined a language that has since become known as
FORTRAN-66, and that corresponds essentially to FORTRAN-IV. The second
ANSI report has defined (in 1978) a FORTRAN-77 language in two versions: full
FORTRAN and subset FORTRAN. The latter contains some restrictions in order
to make it easier to implement on small computers.
The FORTRAN-77 language described in this text will hereafter be known
simply as FORTRAN. It is essentially the ANSI subset FORTRAN, and corre
sponds closely to MS-FORTRAN, a comprehensive dialect sold by the Microsoft
Corporation for the MS-DOS Operating System as used in the IBM Personal Com
puters in the Freshman Engineering Computing Laboratory at the University of
t JE. Sammet, Programming Languages, History and Fundamental; Prentice-Hall. Englewood Cliffs,
N.J.. 1969.

1-7

Chapter 1 Introduction to Computers and FORTRAN


Michigan. All programs reproduced in this text were compiled using the Microsoft
FORTRAN compiler in conjunction with an IBM Personal Computer.
Before embarking upon a description of FORTRAN, it seems appropriate
to discuss the nature of procedure-oriented languages, and their similarities to
natural languages. It is essential to understand that the syntax for a computerprogramming language is completely arbitrary. The syntactical rules that rigor
ously characterize which character strings constitute a grammatically legal pro
gram are usually drawn up by a committee. Thus, the language rules depend on
a variety of influences, not the least being personal opinion or prejudices of those
formulating them! Language design is sometimes considered more an art than a
science; consequently, some rules will seem very artificial or even silly, particularly
to the beginning programmer.
Nevertheless, the rules are inviolable, and must be followed to the letter.
In this respect, programming laguages are similar to artificial international lan
guages, such as Esperanto and Interlingua, each defined by committees of language
specialists. As an illustration, Esperanto contains a rule on the formation of plural
nouns (domoj, tabloj, pomoj, for example): "All plural nouns end with the letter j;
only plural nouns may end with the letter j." The rule is obviously quite arbitrary.
Nevertheless, because it is inviolable, there is never any question about the iden
tity of plurals; compare this with the irregularity of plural formation in English:
books, sheep, men, for example. The rigid syntax of such languages makes them
much easier to learn than natural languages, which are replete with irregularities
and ambiguities.
Table 1.1 Analogies Between English and FORTRAN
English

FORTRAN

Noun
Verb
Phrase
Sentence
Paragraph
Chapter

Operand
Operator
Expression
Statement
Subprogram
Assembly of
subprograms

There are some analogies between a program written in a procedure-oriented


language and a paragraph or chapter written in a natural language. For example,
each is composed from a finite set of symbols that includes letters, digits, punctu
ation marks, and parentheses; in FORTRAN, this collection of symbols is called
the character set. In a natural language, the basic element with a distinct meaning
is called a word; words are assigned an identity as to type, such as noun, verb,
or preposition. In FORTRAN, we refer to the basic elements as operands, opera
tors, character strings, delimiters, etc. For example, the FORTRAN statement or
"sentence"
1-8

l.S Analysis of a FORTRAN Program


X = 3.4 + Y
contains the three operands X, 3.4, and Y (with associated numerical values) and
the two operators, = and +, which act on the operands; note the (rather tenuous)
analogy between verbs and nouns in a natural language and operators and operands
in FORTRAN. We can extend this analogy still further, and increasing levels of
complexity are summarized in Table 1.1.
Two important differences should also be noted between natural languages
and well-designed programming languages:
1. In a natural language, there is often a clear meaning associated with forms
that violate the syntax or grammar. For example, the collection of En
glish words "We ain't got none of them posters left" violates elementary
English grammar; yet, the fact remains that anyone fluent in the language
would understand that the posters are no longer available. A comparable
syntactical error in FORTRAN will render the FORTRAN statement ab
solutely meaningless; that is, only perfect FORTRAN is acceptable to the
FORTRAN compiler. The compiler can translate all grammatically cor
rect symbol strings; it cannot translate any grammatically incorrect symbol
string.
2. In a natural language, grammatically correct constructions can still provide
ambiguities for the reader; this may be because of a poor choice of phrasing
or word order, or because the same symbol string may have several meanings
associated with it, as in the sentence: "I have a bill." Here, bill might refer
to an invoice, a draft for a proposed statute, a piece of paper money, and
several less likely possibilities such as a bird's beak or a medieval weapon.
The meanings of legal symbol strings are usually called the semantics of
a language; clearly, natural languages have a very complex semantics. The
semantics of most computing languages is more readily formalized than for a
natural language. In general, the programmer should view any syntactically
correct FORTRAN program as having only one meaning.
No doubt, the comments of the preceding paragraphs distort definitions
sacred to linguists and computing-language designers. Nevertheless, there are
obvious similarities betwen the programmer and the author. Each attempts to
create a complete and unambiguous representation of an idea from a basic set of
symbols using a formal set of syntactical rules and an associated semantics.
1.3 Analysis of a FORTRAN Program
We include in this section a simple, but complete, FORTRAN program with
data and output. It is unnecessary for the reader to understand everything included
here; however, he or she should gain some feeling for the nature of a FORTRAN
program, and its relationship to the algorithm (including the flow diagram) for
solving the problem.
1-9

Chapter 1 Introduction to Computers and FORTRAN

z/

s\ A

45.0
60.0
53.1
53.2
89.0

10.0
10.0
3.0
3.0

10.0

Fig. l.S Problem and data.


The problem. The input data, shown in Fig. 1.3, consist of several pairs of
values for the angle A (in degrees) between the base and hypotenuse of a rightangled triangle, and for the length X of the base. The problem is then to compute
the altitude Y and hypotenuse Z of the triangle from the following formulas:
Y = XtanA,
Z = \/X2 + Y2.
The output is to show the numerical values of all the variables: A, X, Y, and
Z. The program should be able to process any number of sets of data.
Flow diagram. The sequence of events needed to accomplish the above is
represented diagrammatically in Fig. 1.4.

Fig. 1.4 Flow diagram for triangle problem.


The box resembling a punched card denotes an input operation, in which
we are reading two values and storing them in the variables A and X, respectively.
Note that when we say "store in the variable A," we consistently mean that the
value read for variable A is stored in the memory word assigned to the variable A.
The rectangular box designates arithmetic computations; for example, Y = X tan
A means that the result of X times the tangent of A is stored in the variable Y.
The box resembling a torn sheet of paper shows an output operation, in which the
values of A, X, Y, and Z are printed or otherwise displayed.
Note that if we to wish to process several sets of data, the arrow returning
to junction box "1" allows us to repeat the sequence. In this case, it is understood
from the dotted arrow leading to the "End" box that repetition ceases when there
are no more input data to be read.
1-10

l.S Analysis of a FORTRAN Program


Example Program 1.1Triangle Problem, First Version
The following FORTRA.N program will solve the above problem.

Column:
1
2
3
Line: 4
5
6
7
8

12
3
123456789012345678901234567890
PROGRAM TRI1
C
Triangle Problem. 1st version.
1 READ (*.*) A. X
Y = X*TAN(A*3. 14159/180.0)
Z = SQRT(X**2 + Y**2)
WRITE (*.*) A. X. Y. Z
GO TO 1
END

Note the following about the program:


1 . It is written entirely in terms of letters, digits, and special characters (such as
* .
. /). Upper-case letters such as PROGRAM. X. and GO TO are generally
(but not universally) needed for FORTRAN statements. However, lower
case letters may appear in comments (identified here by C in column 1) , and
may also be manipulated and printed by a program (not shown here).
2. There are similarities to the flow diagram, as evidenced, for example, in the
variable names, A . X. Y. Z. and the words READ and WRITE.
3. There is just one statement per line of the program, and most of the state
ments start in column 7 (they could continue through column 72 if neces
sary).
4. Occasionally, there are symbols in columns 1-6.
5. The column and line numbers are not part of the program, but have been
given above for our own orientation.
Data and output. The following is a copy of both the data that we typed
on the IBM/PC keyboard (e.g., 45.0 and 10.0 for A and X, respectively), and of
the output generated by the program on an IBM/PC monitor (screen):
45.0. 10.0
45.0000000
60.0. 10.0
60 . 0000000
53.1. 3.0
53.1000000
53.2. 3.0
53 . 2000000
89. . 10.

10.0000000

9 . 9999880

14.1421300

10 . 0000000

17 . 3204800

19.9999700

3 . 0000000

3.9956180

4 . 9964950

3 . 0000000

4.0101770

5.0081450

1-11

Chapter 1 Introduction to Computers and FORTRAN


89.0000000

10.0000000

572.8573000

572.9446000

89.0000000

10.0000000

572.8573000

572.9446000

89.0000000

10.0000000

572.8573000

572.9446000

89. 10
89 10

(We have underlined the input data values in this introduction, just to distinguish
them from the output.) Note that the output consists of values for the variables A.
X . Y . and Z, and that there are at most seven significant digits before the computer
adds some extra zeros. Actually, as evidenced by the results for the first triangle,
in which the altitude should equal the base, the results are probably correct to
about six significant digits, the same as the approximation to n introduced in the
program.
Explanation of statements in the program. We now explain each program
line in turn. If some of the ways of doing things seem a little strange or contrived to
you, remember that we are playing according to the rules of FORTRAN, and that
a program must follow fairly rigid rules if it is to be unambiguously understood
by the computer.

Line 1:

PROGRAM TRI1

Here, we are identifying our program with the name TRI1. Although such
naming of (main) programs is optional, we shall name all our programs for later
consistency with other types of program units called external functions and sub
routines, which must have names.

Line 2:

Triangle Problem. 1st version.

The "C" in column 1 means that this line is to be treated as a "comment,"


and forms no essential part of the calculations. Comments are inserted for the
convenience of the user, allowing internal documentation of the program. All such
lines are ignored by the FORTRAN compiler, however. It is good programming
practice to document all FORTRAN programs with a liberal proportion of such
comment lines, making the program more readable not only for others, but for the
programmer as well!

Line 3:

READ (*.*)

A. X

The "1" in column 4 is a statement number or statement label, and may


actually appear anywhere in columns 1-5; it serves the same purpose as the "1"
1-12

l.S Analysis of a FORTRAN Program


in the small circle in the flow diagram, and we shall return to it later. (Statement
numbers may be anywhere in the range 1-99999; the choice is ours, except that
we must not use the same number more than once in columns 1-5.)
READ (*.*) A. X tells the computer to expect two data values to be read
during each input operation, and that these are to be assigned to the variables A
and X respectively. Where these values come from, and how they are to appear,
is determined by the (*.*) part. The first asterisk denotes an input device, and
specifically means that the data will be typed in at our computer keyboard. The
second asterisk indicates that we are using free-format or list-directed input, and
that we need not worry much about spacing. Note, for example, from the last three
sets of data that the values for A and X (e.g., 89.0 and 10. 0) can be separated
either by a blank space, or by a comma. We can even in this case omit the decimal
point, although this omission is generally not good programming practicealways
include a decimal point when dealing with numbers that may have fractional parts.
Such numbers are called floating-point or real numbers.

Line 4:

Y - X*TAN(A*3. 14159/180.0)

This statement computes the tangent of the angle A (or, more precisely, of
the number stored in the memory location assigned to the variable A), multiplies
it by X, and stores the results in the variable Y. Note the following:
1. The name of the FORTRAN function reference for computing a trigonomet
ric tangent is TAN. The programmer should commit to memory this name
and those of several other commonly used functions, such as SQRT. SIN.
COS. EXP, and ALOG.
2. Like all other function references in FORTRAN, the argument or number
on which TAN operates is enclosed in parentheses.
3. TAN must have its argument in radians. Since there are "k or 3.14159 radians
in 180, the value of A must be multiplied by tt and divided by 180. The
multiplication and division operators are designated by * and /, and must
be included where appropriate; for example, 3.14159A is improper for the
product of A and jr. (Other operators are + for addition, - for subtraction,
and ** for exponentiation; e.g., A**3 indicates the cube of A.)

Line 5:

Z = sqRT(X**2 + Y**2)

Here, \/X2 + Y2 is evaluated and the result stored in Z. Observe that we have
used another useful function reference, named SQRT, and that again the expression
forming its argument is enclosed in parentheses. The exponentiation operator "**"
takes its usual precedence over addition, i.e., X and Y are individually squared
before being added together.
1-13

Chapter 1 Introduction to Computers and FORTRAN

Line 6:

WRITE (*.*)

A. X. Y. Z

The values of A and X (read as data) and Y and Z (computed by the program)
are "written" or displayed on the monitor, as indicated by the first asterisk. The
second asterisk indicates free-format format or list-directed output. The latter has
the merit of simplicity in programming, but the disadvantage that we must accept
whatever the computer decides in the way of spacing and number of decimal places
printed. For example, the first set of output values for A. X. Y. and Z was:

45.0000000 10.0000000 9.9999880 14.1421300


Observe that the computer was unable to compute the altitude of the trian
gle exactly (it should have been 10.0), and that there are probably more decimal
places printed than we really want. We shall soon see under Version 2, with some
additional statements in the program, how we can overcome these drawbacks.

Line 7:

GO TO 1

Now that we have processed one set of data, we return to the READ statement
(whose statement number was l) for input of further data sets, if any.

Line 8:

END

This must appear as the last statement of every program, and indicates
that no more statements are to be processed. It is not normally used to stop the
program from runningthat is accomplished by methods we shall discuss later.
Note that the program can process any number of data sets in sequence.
Whenever control returns to the READ statement, the next data line typed at the
keyboard is read and the appropriate calculations are made. Most computing
systems are designed so that an attempt to read a data line when the last data
have already been read will simply cause the program to stop executing. In the
case of the IBM PC, execution can also be halted by typing the key-combination
<Ctrl-C> or <Ctrl-Break>. Thus, it is unnecessary to specify ahead of time the
number of data lines to be processed, thereby avoiding the need to count in the
program itself the number of data sets read.
Example Program 1.2Triangle Problem, Second Version
If you feel moderately confident with Version 1 above, now consider the
following modified program.
1-14

1. S Analysis of a FORTRAN Program

Col:

12
3
4
5
1234567890123456789012345678901234567890123456789012345678
PROGRAM TRI2
C
C
Triangle Problem. 2nd version.
C
C
Define I/O units 5 and 6
OPEN (5. FILE* TRI2.DAT')
OPEN (6. FILE-'LPTl')
C
C
201
C
C
1

C
C
202
C
C

Use formatted output to print a heading


WRITE (6.201)
FORMAT Cl'. 6X. 'A'. 9X. 'X'. 9X. 'T' . 9X. 'Z'/' ')
Read input values. perform computations
READ (5.*.END=999) A. X
Y - X*TAN(A*3. 14159/180.0)
Z - SQRT(X**2 + Y**2)
Use formatted output for all variables
WRITE (6.202) A. X. Y. Z
FORMAT (' '. 4F10.4)
Return to statement 1 for more data
GO TO 1

C
C

No more data remaining in input file


999

STOP
END

The above program was run in conjunction with the following lines of data,
which were stored separately in a file named TRI2.DAT (again, column numbers
have been added for convenience):
Col:

1
2
12345678901234567890
45.0. 10.0
60.0. 10.0
53.1. 3.0
53.2. 3.0
89. . 10.
89. 10
89 10
1-15

Chapter 1 Introduction to Computers and FORTRAN


This new program produced the following output, which now has a much
better appearance than before (note the column alignment):

Col:

12
3
4
12345678901234567890123456789012345678901
A
X
Y
Z
45.0000
60.0000
53 . 1000
53.2000
89.0000
89 . 0000
89 . 0000

10.0000
10 . 0000
3.0000
3.0000
10.0000
10.0000
10.0000

10.0000
17.3205
3.9956
4.0102
572.8573
572.8573
572.8573

14.1421
20.0000
4.9965
5.0081
572.9446
572.9446
572 . 9446

Concerning the program itself, which is named TRI2, several more comment
statements have been added for purposes of documentation. The blank lines with
just a C in column 1 are purely for ease of reading. The calculations are exactly
the same as in Version 1, but there are several respects in which the new program
is more sophisticated:

OPEN (5. FILE-' TRI2.DAT')

OPEN (6. FILE-'LPTl')


Here, device number 5 (a fairly standard number for input) is identified with
the file TRI2 .DAT, which is where the pairs of values for A and X have been stored.
Also, device number 6 (standard for output) is identified with the local IBM PC
printer, whose name is LPT1. Soon, we shall see that devices 5 and 6 are again
mentioned in the READ and WRITE statements.

WRITE (6.201)

201 FORMAT ('1'. 6X. 'A\ 9X. 'X'. 9X. 'Y'. 9X. '!'/ ' ')
Here, we are using formatted output to generate the heading that appears at
the top of the output, which now appears on the printer (and not the TV monitor),
because unit 6 was identified with LPT1 in the OPEN statement. Two statements are
1-16

l.S Analysis of a FORTRAN Program


neededWRITE and FORMAT; note that they are linked by the common statement
number 201. The exact spacing and appearance of the heading are controlled by
the codes that appear in parentheses in the FORMAT statement. With one exception,
to be mentioned in the next paragraph, any characters or literal strings enclosed in
primes (such as 'A') will appear directly in the printed output. Also, an entry such
as 9X means that there are to be exactly nine blank spaces between, for example,
the letters A and X.
The one exception is that a character enclosed in primes, and that would
normally be printed in column 1, is not printed, but is treated as a carriage-control
character instead. Thus, '1' indicates that the output is to start at the top of a new
page. The slash (/) terminates a line of output, and the ensuing blank, ' ', is the
carriage-control character for single-line spacing. In this instance, however, there
is nothing to be printed on the second line, so a completely blank line appears
between the heading and the numerical output.

READ (5.*.END-999)

A. X

Here, values for A and X are to be read from input device 5 (identified with
the file TRI2.DAT in the OPEN statement). As before, the asterisk denotes that listdirected (format-free) input is involved. The additional code END=999 indicates
that if there are no more data-values remaining to be read, then control should
automatically be transferred to the statement whose number follows the equals
sign (999 has arbitrarily been chosen in this instance). You will see later wfcat
happens.

WRITE (6.202)

202

A. X. Y. Z

FORMAT (' '. 4F10.4)

Now comes another WRITE/FORMAT combination, this time linked by the


statement number 202. Its purpose is to print numerical values for the four vari
ables A. X. Y. and Z, which appear in the WRITE statement. How these values
are to appear is governed by the format specification 4F10.4, whose parts have the
significance shown in Table 1.2. Note that all sets of four output values conform
to the F10.4 code, e.g.:
12
3
4
12345678901234567890123456789012345678901
53.2000
3.0000
4.0102
5.0081
<
><
><
><
>
Variables:
A
X
Y
Z
Format codes:
F10.4
F10.4
F10.4
F10.4
Column:
Values:

1-17

Chapter 1 Introduction to Computers and FORTRAN


Table 1.2 Parts of the Format Code 4F10.4
Code

Meaning

There are four numbers receiving similar treatment; the


format specifications could also have been written fully as
F10.4, F10.4, F10.4. F10.4.

The numbers being read are floating-point, i.e., they contain


a decimal point. (FORTRAN also calls these "real" num
bers, in contrast to integers, which do not have a decimal or
fractional part, and for which the format code is I.)

Ten columns are to be allowed for each of the four numbers,


with four columns after the decimal point. Not all columns
have to be used, and one of them must be reserved for the
decimal point. Also, if any number were negative, it would
be prefixed with a minus sign, which also requires one column
for output.
Observe also that a blank has been written into column 1 of each output line,
and will be interpreted as a carriage-control character, hence insuring single-line
spacing.
10.4

999

STOP

Recall that when an attempt was made in statement number 1 to read non
existent data, control would automatically be passed to the statement numbered
999. Well, here it is, and its purpose is to halt execution of the program and return
control to DOS, the operating system.
Conclusions. We have covered a great deal of ground in the above. If most
of Version 1 makes sense, you have already made a good start. If not, we shall be
going through all of it again in subsequent chapters. At any rate, you should now
be somewhat familiar with several of the topics we shall be discussing.
Exercises for Section 1.3

(See Appendix A for answers to all exercises)

Referring to the above FORTRAN programs:


1.
2.
3.
4.
5.
6.

In which column do most of the statements that are not comment lines start?
What is the last statement in the program?
What characters appear that are neither letters nor digits?
Which statements appear to go in pairs?
Can lower-case letters appear in comments?
What is the purpose of the first character in every line of output?
1-18

1.4 Fundamental Concepts and Notation


1.4 Fundamental Concepts and Notation
The principal character subsets used for constructing FORTRAN programs
are:
Alphanumeric Characters
Alphabetic: the capital letters A through Z (some FORTRAN compil
ers also allow the 26 lower-case letters to be used here).
Numeric: the decimal digits 0 through 9.
Special Characters

+ -/() = .,':
Blanks may also appear, but in most contexts they have no significance.
Additional special characters, including lowercase letters and characters such as
| < > !

? # @

^
may also appear in character strings to be read or printed, and in comment state
ments. In FORTRAN programs, all characters must be placed on the line; for
example, Ai and X2 are improper.
Column Number
15 6 7

72

r~i
State-i

merit
Number I

FORTRAN Statement

ITI
Continuation
Code
l_l

Fig. 1.5 Format for FORTRAN Statements.


FORTRAN statements will normally be entered on a series of lines, with
one statement (or a comment) per line. A line in a program (as opposed to a data
line) can have up to 72 columns, each of which will ultimately be left blank or
will be typed with a single character. The line format is shown in Fig. 1.5, and is
further described in Table 1.3.
A comment prefixed by the letter C or an asterisk in the first column causes
no action to be taken by the compiler, other than to reproduce the comment at
the appropriate point in any listing of the program. For example, the lines
C
C

COMPUTE RMS VALUE OF CURRENT


Formats for I/O statements
1-19

Chapter 1 Introduction to Computers and FORTRAN


might appear at some point in the program to assist the reader in interpreting
it. Note that the comments are not written as part of the output from the object
program generated by the compiler; they simply appear in the printed listing of
the program.

Table l.S Use of Columns in a FORTRAN Statement


Column

Contents

May contain the letter C or an asterisk If so, the line will be


treated as a comment, and will be ignored by the compiler.

1-5

May contain a statement number or label, positioned any


where in the five-column field. It is often necessary to make
specific reference to particular statements in a program. A
statement may be uniquely identified by prefixing it with any
integer from 1 through 99999. The statement numbers need
not be in any particular sequence, but a given statement num
ber can correspond to only one statement. If no reference is
made to a statement elsewhere in the program, then that
statement is usually (and preferably) not assigned a number;
any executable statement (not yet definedsee below) may
be given a statement number, however. Labels should not
appear on any nonexecutable statement (sometimes called a
declaration), except for a FORMAT declaration, described in
Chapter 3.

7-72

Contains a FORTRAN declaration or executable statement


between columns 7 and 72 inclusive.

If the statement is very long, it may be continued in columns


7-72 of one or more subsequent lines, up to a maximum of 19;
in this case, each subsequent line must contain a continuation
code in the form of any character other than 0 (or a blank)
in column 6. We suggest that the digits 1-9 be used.

Messages can be written by the executing object program only if WRITE


statements (see Chapter 3) appear in the program. Comments are not considered
to be FORTRAN statements, and need not conform to the format shown in Fig.
1.5. Each comment must have a C or * in column 1; thereafter, characters may
appear in any columns; a continuation code is not allowed. A purely blank line is
also treated as a comment line.
AH lines in a FORTRAN program that are not comments are statements,
and must be written to conform to the format shown in Fig. 1.5. To write valid
1-20

1.4 Fundamental Concepts and Notation


algorithms, the programmer must adhere to standard statement types with rigid
basic structures.
Table 1.4 General References Used in This Book
References
A
A*
B
.23.
C
'C
P

C
I
Z
7
I
C
M
MAMS
..
5
T
U
V
"VB
VC
VI
VZ

Meaning
Dummy argument for a subprogram.
Calling argument for a subprogram.
Logical (Boolean) expression.
Logical (Boolean) operator.
Arithmetic or logical constant.
Literal (character) constant.
Input/output device or file.
Arithmetic expression (real or integer).
Character expression.
Integer expression.
Real expression.
Subprogram (function or subroutine) name.
Integer constant or unsubscripted
integer variable.
A list, usually of variable names.
Statement number or label; an array name
in some circumstances.
Labeled COMMON block name.
Relational operator.
Executable statement.
Type or mode.
Unit number for input or output.
Arithmetic variable (real or integer).
Logical (Boolean) variable.
Character variable.
Integer variable.
Real variable.

There are two fundamentally different types of statements or "sentences"


in the language: executable and nonexecutable. The executable statements are
those that cause the FORTRAN compiler to generate machine-language instruc
tions that will be executed when the object or machine-language version of the
FORTRAN source program is loaded into the memory of the computer. Nonexe
cutable statements, also known as declarations, are special statements that do not
cause machine code to be generated, but which supply information to the compiler,
such as the types of variables (see the INTEGER and REAL declarations in Sections
2.4 and 9.3, for example), and the amount of memory to be assigned to subscripted
1-21

Chapter 1 Introduction to Computers and FORTRAN


variables (Section 7.2). Except for the FORMAT statement, declarations must not
have statement labels; each FORMAT statement, however, must have a label.
In the chapters that follow, a basic set of FORTRAN statement types will be
described, using the general references shown in Table 1.4. General references will
be described when they are first used. Any printed or typed characters, such as
words and punctuation marks, shown in the general formulation of each statement
type are part of the basic statement structure and must not be altered in any way.

Exercises for Section 1.4


1. Check true or false, as appropriate:
(a)

Statement numbers in a FORTRAN program may be


in columns 1 through 6 inclusive.

(b)

A completely blank line is a comment line.

(c)

A comment may be inserted in a FORTRAN program


by typing a C in column 1 or 2.

(d)

A C in column 6 identifies that line in a FORTRAN


program as a continuation of the previous one.

(e)

Statement numbers in a FORTRAN program may be


in the range 0 through 99999.

(f)

The maximum number of columns available for a


FORTRAN statement, not including the statement
number and continuation code, is 65.

T D

F D

1.5 Three Statements: GO TO, STOP, and END


We conclude this chapter by describing three simple statements: GO TO,
STOP, and END. The END statement must appear once in every program; however,
the other two are also used quite frequently.
Transfer Statements. Statements are normally executed in sequence, but
the unconditional transfer executable statement,

GO TO JJ

at any point in the program will cause the statement numbered M to be executed
next. Examples are:

GO TO 10
GO TO 75
1-22

1.5 Three Statements: GO TO. STOP. and END


There are two principal uses for such a statement: (a) after processing a set
of data, to return to the beginning of a program to read another set of data (for
example, GO TO 1 could be used to return to a READ statement numbered 1); and
(b) to bypass a segment of a program under certain circumstances, sometimes in
conjunction with the logical IF statement of Chapter 6.
Terminating Program ExecutionThe STOP Statement. Execution of the
object program produced by the compiler can be terminated in a variety of ways.
Most programs are written to process more than one set of data values; in fact,
the number of such data sets is usually arbitrary. In these cases, the natural way
of terminating computation is with the attempted execution of an input (READ)
statement after the last data set has already been read. The approach was used in
the first program of Section 1.3, in which any number of sets of data for triangles
could be processed.
An alternative way of terminating execution and transferring control to the
operating system is to use the STOP statement, which is available in three forms
shown below. In each case, execution of the program ceases immediately, and a
message is displayed in the output. Here, 7 is an unsigned integer constant of five
digits or less (see Section 2.3), and 'C is a character constant (Section 11.1).
Form of Statement
STOP
STOP I
STOP 'C

Displayed Message
STOP - Program terminated.
I
'C'

Examples of the STOP statement are:


STOP
STOP 7
STOP 'Negative value not allowed for variable X'
The STOP statement can be executed at any time, not necessarily after the
end of data has been reached; in fact, one occasionally encounters programs in
which all essential information is generated internally, so that no data are read at
all, and no input statements even appear.
The END Statement.

The statement

END
must appear once, as the very last statement, in every program. It is a signal
to the compiler that no more statements appear in that program. Unlike other
executable statements, the END declaration should not be numbered. Usually, END
is not the last statement to be executed in a program. A transfer statement, a
STOP statement, or a call for return to the operating system will almost invariably
be the final executable statement preceding the END statement.
1-23

Chapter 1 Introduction to Computers and FORTRAN


Notes

1-24

CHAPTER 2
ARITHMETIC STRUCTURES
2.1 Introduction
Our first goal in this chapter is to describe completely the syntactical or
grammatical rules for the formation of all proper statements of the form
V -
where "V designates the name of an arithmetic variable and is an arithmetic
expression. The equal sign in FORTRAN is called the assignment operator; the
left-pointing arrow would would seem to be a more appropriate character to use
for assignment, but the equal sign is always used in FORTRAN instead. In every
case, a numerical value is computed for the expression on the right-hand side of the
equal sign; this numerical value is then assigned as the new value of the variable
appearing on the left-side of the equal sign.
Such statements are called arithmetic assignment (or substitution) state
ments and appear whenever arithmetical operations are to be performed and a
new numerical value is to be assigned to a memory location. Representative ex
amples are:
Y = X*TAN(A*3. 14159/180.0)
Z = SQRT(X**2 + Y**2)
In each case, the statement causes the expression on the right-hand side of the
equal sign to be evaluated and the numerical result to become assigned as the new
value of the variable on the left-hand side.
Table 2.1 Building Blocks for Arithmetic Expressions
Operands

Operators

Integer constants
Real (floating-point) constants
Integer variables
Real variables
Integer function references
Real function references
2-1

** (exponentiation)
* (multiplication)
/ (division)
+ (addition)
- (subtraction)
(negation)

Chapter 2Arithmetic Structures


Arithmetic expressions are constructed from the basic operations and op
erators listed in Table 2.1. Table 2.2 illustrates how a representative assignment
statement can be broken down into its constituent parts.

Table 2.2 Analysis of an Assignment Statement


Statement:

Y X*TAN(A*3. 14159/180.0)

Arithmetic Operands:
Constants
Variables
Function Reference

3.14159, 180.0
A. X, Y
TAN( )

Arithmetic Operators:
Multiplication
Division

Assignment Operator.

The action of the assignment statement is in two parts, as follows:


1. Evaluate the arithmetic expression on the right-hand side of the equal sign.
This involves retrieving from memory the current value of the variable A,
which is presumably in degrees, since it is converted to radians (by multiply
ing by tt/180) before evaluating its trigonometric tangent and multiplying
the result by the current value of the variable X.
2. Assign the numerical value of the expression thus computed as the new value
of the variable Y. Note that the previous number associated with variable Y
has been over-written in the process, and is no longer stored in the memory
of the computer.
2.2 Types: Integer and Real
Certain quantities, such as the number of a particular month in the year
(January = 1, February = 2, etc.), or the number of points in a football score,
can assume only integral or whole-number values. Others, such as e (2.71828),
Avogadro's number (6.023 x 1023), or the mass of an electron (9.107 x 10~28 gram)
may require fractional parts for their accurate representation and /or need a scale
factor (such as 1023 or 10~28) because they would otherwise be inconvenient to
write in full. We differentiate between integer (or fixed-point) numbers on one
hand, and real (or floating-point) numbers on the other. This distinctionthat
of different types or modesis preserved in the computer, where integer numbers
and real numbers are both stored and manipulated differently. In most computers,
arithmetic operations involving integer operands are executed more rapidly than
are the corresponding operations on real operands, since no attention need be paid
to scale factors and decimal-point location.
2-2

2. S Constants
A complex type is also available for handling complex arithmetic, but will
not be discussed in this text. Information of two other types may also be stored
and manipulated in FORTRAN programs. Quantities having truth values {true or
false) are said to be of logical type, and will be discussed in Sections 6.1-6.3. FOR
TRAN also has features that allow the manipulation of strings of symbols. These
strings are assigned a character type and are discussed in several later sections,
particularly in Chapter 11.
Exercises for Section 2.2
State the type (integer or real) of each of the following:
(a) The number of days in a month.
(b) The average number of days in a month.
(c) jr.

(d) The number of pages in a book.


(e) The amount of money in a checking account.
(f) A baseball batting average.
2.3 Constants
A constant is a known quantity whose value is invariant. Integer or fixed,
point constants are numbers that consist of a string of digits. A decimal point
is assumed to lie after the rightmost digit, but must be omitted. A plus sign
is optional, but if the integer is negative it must be preceded by a minus sign.
An integer constant of standard length (see Section 9.3) must lie in the range
-2147483647 through +2147483647. However, this range will vary for different
FORTRAN compilers. Leading zeros, although permissible, are ignored. Commas
for separating hundreds, thousands, and millions are not permitted.
Examples of integer constants
365 +0365 -6636174

700

Real or floating-point constants of the F-type and of standard length are


numbers that consist of a string of one to seven significant digits with a deci
mal point, again possibly preceded by a sign. Leading and trailing zeros are not
significant.
Examples of F-type real constants
3.14159
003.14159
-0.00006321702
0.0

453.
453.000
21367250000.

An F-type mantissa may have appended to it a scale factor in the form of


the letter E followed by an integer constant, producing an E-type real constant.
The integer constant indicates the power of 10 by which the mantissa is to be
multiplied. Examples are:
2-3

Chapter 2Arithmetic Structures

E-type Constant

Interpretation

9.107E-28
9107. E-31
-1.9E4

9.107 xl0-28
9.107 xlO-28
-19,000.0

Both the F- and E-type constants are stored identically in the computer
only their external appearance is different. As shown in Fig. 2.1, the absolute value
of a real constant (whether of the F- or E-type) must lie between approximately
8.43 x 10~37 and 3.37 x 1038, or be zero. Again, this range is established by
the particular compiler or computer being used. We shall use the notation C to
designate a general arithmetic constant, and I to denote an integer constant.
Acceptable
i
-Acceptable

-Acceptable

1
39

-0.337x10

fA3S0,0
-36 U <J \
>
-36
-0.843x10
0.843x10

7T
0.337x10

Illegal
Fig. 2.1

The acceptable range for both F- and E-type real constants.

Exercises for Section 2.3


1. Indicate which of the following are integer, F-type real, E-type real, or
invalid constants.
(a)
(b)
(c)
(d)

10.
CONST
- 39
6.3e-6

(e) .693E09
(f) 0.693E+09
(g) -2147843646
(h)2.7E(56)

(i) PI
(j) -723.4E-80
(k) 37.560
(1) 6.023 * 10 * *23

2 Check true, or false, as appropriate.


(a)

1 . 234567E89 is a valid real-type constant.

(b)

If 3.14159 is expressed as an E-type real number in


an arithmetic expression, at least 10 columns will be
needed for it:

(c)

2.4E0.5 is legal for 2.4 x lO06.

TD

FD

(d)

Real values may normally be stored correct to approximately seven significant digits.

T D

F D

2-4

2.4 Variables
2.4 Variables
An arithmetic variable is a FORTRAN entity that may assume different
numerical values during the execution of a program. The name of a variable
ultimately refers to an address in memory where the numerical value of the variable
is to be stored. Each variable name is assigned a unique memory location; hence,
the variable has just one value at any given time. In essentially all respects,
FORTRAN variable names play the role of variable symbols in ordinary algebra.
Rules for naming variables are:
1. A variable name consists of between one and six alphanumeric characters
(the collection of the 26 capital letters, A. B. . . ., Z. plus the ten decimal
digits, 0. 1. .... 9).
2. The first character of the name must be alphabetic, that is, one of the capital
letters.
Thus, the following are all acceptable variable names:
A
A5
BETA

I
JACK
MONTH

PRESUR
VOLUME
VALUE

The following would not be acceptable:


7PX
X/19
PRESSURE

(does not begin with a letter);


(contains a special character, /);
(contains more than six characters).

Although FORTRAN naming rules allow the programmer to choose variable


names from a very large set of possibilities, the use of suitably descriptive names
(such as V. VOL. or VOLUME for a volume variable in a problem) has obvious
advantages from the standpoint of program readability.
Numerical values may be stored in memory locations in one of two internal
formats (integer and real) as described previously. It is essential that the FOR
TRAN compiler know which of these two internal number representations will be
used for each variable in the program. FORTRAN uses the following implicit type
or mode assignment for each variable name in the program:
1. If the variable name begins with any of the letters I. J. K. L. M. or N.
then the variable value is stored in integer form. Such variables are called
integer variables, generally designated as "VI or I, and are restricted to
the number range already described for integer constants, namely, integers
between -2147483647 and +2147483647, inclusive; thus, integer variables
may never have fractional parts.
2. If the variable name begins with any letters except I. J. K. L. M. or N.
then it is a real variable. Real variables, generally designated as "\}R, may
have fractional parts and must lie in the number range already specified
for real constants, namely between roughly 8.43 x 10~37 and 3.37 x 1038 in
2-5

Chapter 2Arithmetic Structures


magnitude or be equal to zero. Values of real variables are always stored in
memory using the real-number internal format.
Thus, of the acceptable variable names listed previously, A, A5, BETA,
PRESUR , VOLUME . and VALUE are all of real type, while the variables I , JACK .
and MONTH are of integer type.
Sometimes the implicit type assignment of variables is inconvenient. For
example, if the programmer wishes to compute an arithmetic mean having a frac
tional part, assignment of the arithmetic mean to a variable named MEAN would
lead to errors (MEAN is assumed to be an integer variable by the FORTRAN implicit
naming convention, and hence could not be assigned a value having a fractional
part). Of course, changing the name to XMEAN or AVG would solve the problem,
since these variables are assumed to be of real type. Nevertheless, the program
mer might still wish to use the variable name MEAN and can do so providing the
compiler is informed that in this program MEAN should be assigned type real rather
than integer. This can be accomplished by including in the program an explicit
type declaration of the form
REAL

MEAN

Similarly, if variables names ALPHA and COUNT were to be assigned integer rather
than the implied real type, the explicit type declaration would have the form
INTEGER ALPHA, COUNT
The general forms for the REAL and INTEGER explicit type declarations (see Section
9.3 for complete details) are:
REAL t
INTEGER

where is a list of variable names, separated by commas.


Throughout this text, the symbol V will be used to represent a general
arithmetic variable of either integer or real type. In situations where the variable
type is restricted to be either integer or real, the symbols VI or I and "VZ will be
used instead.
Exercises for Section 2.4
1. Examine the following list of alleged variable names. State the normal
mode of those that are valid; give the individual reason or reasons why the others
are invalid.
(a)
(b)
(c)
(d)
(e)

XXXXXX
GOBLUE
INDEX
I.J+K
XXXXXXX

(f) #VALUE
(g) 37FEET
00
(i) L1INE
(j) .TRUE.
2-6

(k) MARION
(1) MAURICE
(m) X + 2
(n) COUNT
(o) ySVALUE

2.5 Function References


2. If in a program the variables COUNT and POINTS are to be of integer type,
what declaration is needed?
3. If in a program the variables LENGTH, MASS, and TIME are to be of
real type, what declaration is needed?
2.5 Function References
Efficient programs for evaluating most of the common mathematical func
tions, such as the exponential and trigonometric functions, are available in FOR
TRAN. Such programs have already been compiled into object form and are nor
mally stored in the computing-system library. The programs are in the form of
external functions, to be described in more detail later in Section 10.3. A function

Table 2.S Frequently Used FORTRAN Functions


Function
Name

Mathematical
Significance

Function
Reference

Function
Value

ABS

Absolute value
(magnitude)
Natural logarithm
Common logarithm
Arccosine
Arcsine
Arctangent
Arctangent

ABS()

1*1

ALOG(f)
ALOG10()
ACOS()
ASIN(f)
ATAN(f)
ATAN2(<?1,2)

In (base e)
log (base 10)
0 < arccos < jt
-jt/2 < arcsin < jt/2
-jt/2 < arctan < n/2
-ir < arctan( l/2)

COS()
COSH()
EXP(f)

cos
cosh
exp

IABS(7)

\ei\

SIN()
SINH(()
SQRT(f)
TAN()
TANH()

sin
sinh
1/2

AL0G
AL0G10
ACOS
ASIN
ATAN
ATAN2

< IT

COS
COSH

EXP
IABS

SIN
SINH
SQRT

TAN
TANH

Cosine
Hyperbolic cosine
Exponential
function
Absolute value
(magnitude)
Sine
Hyperbolic sine
Square root
Tangent
Hyperbolic tangent

tan
tanh

has a function name, one or more arguments, and returns a value associated with
its name. Functions are executed at appropriate points in a FORTRAN program
simply by making reference to them. The argument or arguments are enclosed
in parentheses immediately following the function name, 7; commas are used to
separate arguments, if more than one argument is required.
2-7

Chapter 2Arithmetic Structures


The function reference has the form
T()
where, in general, the argument or arguments can be arithmetic expressions (see
Section 2.6).
The names of the common functions are already specified (and hence cannot
be changed by the programmer) , and follow the naming conventions for arithmetic
variables described in Section 2.4. The type or mode of the value returned by the
function is determined by the implicit type convention for arithmetic variables;
that is, if the function name begins with any of the letters I, J, K, L, M, or
N, then the value is an integer, otherwise, the value is real. The type of each
argument is specified a priori, and cannot be changed by the programmer.
Table 2.3 lists several of the common FORTRAN functions. Of those listed,
only the function IABS returns an integer value. In addition, the argument (ar
guments in the case of the ATAN2 function) is always of real type, except for the
argument for the function IABS, which must be an integer. A corresponding list
of double-precision functions, which compute to several more significant digits, is
given in Section 9.3.
Arguments for the trigonometric functions must be given in radians, rather
than in degrees. Thus a function reference such as
COS(30.7)
will return the value of the cosine of 30.7 radians. If the cosine of 30.7 degrees
were required, then the proper function reference would be
COS (30. 7/57. 29578)
where the constant 57.29578 corresponds to the number of degrees per radian.
Taking into account the type assignment for arguments, function references
such as
SQRT(4)
ALOG(MEAN)
IABS (ALPHA)
are invalid, while references such as
SQRT(4.)
ALOG(XMEAN)
IABS (JACK)
2-8

2.5 Function References


are syntactically correct.
The functions listed in Table 2.3 are probably the most important ones
for the average FORTRAN programmer. However, each computing installation
will have many other special-purpose functions available in its library; these are
usually described in a catalog prepared by the local computing-center staff and are
available to all users of the computing system. Later, in Sections 10.2 and 10.3,
we shall see that provision is made for programmers who wish to write their own
functions in FORTRAN.
Exercises for Section 2.5
Write down FORTRAN function references corresponding to the following
algebraic expressions:

(a) yfi

(d) y/El

(g) y/b

(b)ln2

(e) sin 37

(h) sin/?

(c) log \x\

(f) | log x\

(i) sin(v/hT20)

2. Complete the following table by placing an X in the appropriate category


(I = integer, R = real).

Constant
I
R

Variable
I
R

Function
Reference

I
(a) JOE
(b) E - 5.1
(c) l.E - 5
(d) IABS(K)
(e) 1.000.000.
(f) STEPHEN
(g) G0T09
(h) ATAN(THETA)
(i)-6

(j) 1000000000
(k) 1.5E**2
(1) ENG103
(m) -002
(n) TAMMY
3. Explain why the following statement is in error:
X = SQRT(NAME) - 4.57

2-9

None of
These

Chapter 2Arithmetic Structures


2.6 Operators and Expressions
In Sections 2.3, 2.4, and 2.5, we have described the three basic arithmetic
operands: constants, variables, and function references. Each basic operand has an
associated type, either integer or real. These arithmetic operands are the numbervalued "nouns" from which we can begin to construct number-valued "phrases"
called arithmetic expressions. To construct such expressions, we also need a set
of arithmetic operators, which operate upon the arithmetic operands and are the
"verbs" of the FORTRAN language. The FORTRAN arithmetic operators are
listed in Table 2.4 in decreasing level of precedence (processing order).
As is the case for conventional algebraic notation, the minus sign is used for
both the binary (two-operand) operation, subtraction, and the unary (one-operand)
operation, negation; the unary + operation is available, but has no effect on its
operand (being ignored by the FORTRAN compiler) and thus is never needed in
practice.

Table 2.4 Arithmetic Operators


Operator

Precedence
Level

( )

**
*
/
+
+
-

2
3
3
4
4
4
4

Purpose
Override normal
priority
Exponentiation
Multiplication
Division
Addition
Unary +
Subtraction
Negation (unary -)

Example

Conventional
Meaning

(X + Y)*Z

(* + y)*

A**B
3.17*A
X/BETA
X + Y
+ Q
Z - 7.5
- Q

a"
3.17a
x/fi
x+y
+9
z - 7.5
-9

The arithmetic unit of a digital computer is an inherently serial device, car


rying out just one arithmetic operation at a time. Therefore, in the evaluation of
a valid arithmetic expression, the individual arithmetic operations must be per
formed in some specified order, determined by the precedence of the operators.
Certain implied operations, such as the evaluation of subscripts (see Section 7.2)
and of functions (see Section 2.5), have the highest precedence, and are performed
before any of the arithmetic operations. These highest-precedence operations are
then followed, in order of decreasing precedence, by the four levels shown in Table
2.4, with 1 being the highest precedence and 4 the lowest. Observe that multipli
cation and division have equal precedence, and similarly for addition, subtraction,
unary +, and unary -. Among operators of equal precedence, the processing order
is from rightrto-left for exponentiation, and from left-to-right for all others.
Table 2.5 illustrates how operands and operators can be combined to produce
legal FORTRAN arithmetic expressions.
2-10

2.6 Operators and Expressions

Table 2.5 Examples of Arithmetic Expressions


Algebraic Expression

FORTRAN Expression

x+y
x + yz
{x + y)z
a + b\c2 -d/e)
a + bx + cx2

X + Y
X + Y*Z
(X + Y)*Z
A + B*(C**2 - D/E)
A + B*X + C*X**2 or
A + X*(B + C*X)
AL0GCABS (TAN (ALPHA)))
A/(B*C) or A/B/C
SqRT(X**2 + Y**2)

In | tan a\
a/(bc)
(i2+y2)1/2

Observe that in FORTRAN all operators must appear explicitly; for exam
ple, the product of Y and Z must be written as Y*Z, not as YZ, since the latter would
be interpreted by the FORTRAN compiler as a single variable named YZ. Also note
that in a manner completely analogous to that used in conventional algebraic no
tation, parentheses can be used for overriding the usual operator precedence order.
For example, in the fourth expression of Table 2.5, the operations are performed
in the following order:
1.
2.
3.
4.
5.

Exponentiation:
Division:
Subtraction:
Multiplication:
Addition:

C**2
D/E
C**2 - D/E
B*(C**2 - D/E)
A + B*(C**2 - D/E)

The parentheses around the expression C**2 - D/E insure that all opera
tions inside the parentheses will be performed before the multiplication operation
outside the factor (C**2 - D/E) is initiated. The FORTRAN programmer will
soon discover that parentheses are needed in FORTRAN arithmetic expressions
exactly where they are required in the equivalent algebraic expressions. One ex
ception, also noted below, is in expressions involving negative exponents: x~on
must be written as X**(-0.72), for example.
Blank spaces are of no consequence in the writing of FORTRAN expressions,
and may appear anywhere to improve program readability.
The rules for forming all possible valid arithmetic expressions, , are quite
simple, though their recursiveness (describing expressions in terms of previously
formed expressions) sometimes leads to confusion. There are eleven such rules,
shown in Table 2.6. The first three rules indicate that arithmetic constants
C (such as 7. -5689. 2.6. -94.87E-9), arithmetic variables V (such as JOE.
MEAN. DC10. ALPHA), and arithmetic function references 7{) [such as SIN(5.4) .
SQRT(BETA)] are also arithmetic expressions, E . The remaining eight rules show
how arithmetic expressions (such as t , l, and 2) can be manipulated and lead
to further arithmetic expressions. Referring to Table 2.6, note the following:
2-11

Chapter 2Arithmetic Structures

Table 2.6 Rules for Forming Arithmetic Expressions

Rule

Operand or Operation f

1
2
3
4
5
6
7
8
9
10
11

Arithmetic constant
Arithmetic variable
Arithmetic function reference
Parentheses
Unary +
Unary - (negation)
Exponentiation
Multiplication
Division
Addition (binary +)
Subtraction (binary -)

Arithmetic
Expression Form
C
V
W)
(0
+e
-e
51**52
1*2
l/2
n+2
\-i2

fAlso note that:


12

Two or more of the operators


**,*,/,+, and - must
not be juxtaposed.

1. Rule 4 allows parenthesis pairs to be added at will; both parentheses must


appear, and the left parenthesis must appear to the left of the corresponding
right parenthesis.
2. In Rule 7, if the exponent has an integral value, it is preferable to make
it of integer type, that is X**4 is preferable to X**4. (although either is
acceptable syntactically). In this case, X**4 is evaluated by simple multi
plication, X*X*X*X, while X**4. is evaluated by finding the logarithm of X,
multiplying by 4., and then evaluating exp(4 x In X); obviously, the latter
approach requires much more computing time than repeated multiplication.
Computation will be interrupted if the exponent is real and the base is neg
ative, since the attempt to evaluate the logarithm of the negative base will
fail.
3. Rules 7 through 11 allow mixed- type expressions, if the programmer so
desires (see Section 2.7). Thus, the following are syntactically correct:
JACK*X

3.14159**2

3 - DELTA

17.5 - IABS (LEMON)

4. Rule 12 precludes the formation of expressions, such as Z*-Y that would be


invalid algebrically [the expression X*(-Y) is valid, however]. It also pre
cludes one expression form that would normally be acceptable algebraically,
involving negative exponentiation. One could properly wite a~b without us
ing parentheses; A**-B is improper in FORTRAN, however, because of Rule
12, and must be written as A**(-B) instead.
2-12

2.6 Operators and Expressions


These expression-formation rules can be used recursively to construct ex
pressions of considerable complexity. For example, suppose that the algebraic
expression

sin 5 + 0.00032|y|
occurred in an engineering problem, and that we wish to construct its FORTRAN
equivalent. First, each of the algebraic operands should be given FORTRAN
equivalents, for example those shown in Table 2.7. The corresponding FORTRAN
expression is
X**3/(SIN(THETA) + 3 . 2E-4*ABS(Y) )
which can be verified as being legal by observing from Table 2.8 that it is con
structed according to the rules of Table 2.6 (and the operator precedence of Table
2.4).
Table 2.7 Algebraic Operands
and Their FORTRAN Equivalents
Algebraic

FORTRAN

3
0.00032
X
y
9
sin
i i

3
3.2E-4 (or 0.00032)
X
Y
THETA
SIN
ABS

Exercises for Section 2.6


1. Giving your reasons, indicate which, if any, of the following alleged FOR
TRAN arithmetic expressions violate the rules for forming such expressions:
(a)
(b)
(c)
(d)

A + B*C + (D/E**2)
A + BC
(BSQ - AC4)**-0.5
KATHY - 4.56E3 + E3

(e)
(f)
(g)
(h)

4/VOLUME - A/(B +C/(D + E/(F + G)))


2.5*ATAN(DIST**2.5) - 0.0000000456
((P/Q/ROS/T/U)
(1. - 1. + 1. - l.)**3

2. Show the order in which the following expressions will be evaluated. If,
at the time of execution, A = 24.0, B = 3.0, C = 4.0, and D = 2.0, also give their
values:
(a) A/B/C
(b) A/(B*C)
(c) A/(B/C)

(d) -D**C**B
(e) 1.25*ALOG(EXP(2.0)) - 91.5/(A + 6.5)
(f) SQRT(B**C) - C**B
2-13

2.7 Mixed-Type Expressions

Table 2.8 Steps in the Construction


of a FORTRAN Arithmetic Expression
Entity

Involves

Obeys Rule

3. 3.2E-4
X, Y, THETA
SIN(THETA)
ABS(Y)
3.2E-4*ABS(Y)
SIN(THETA) +
3.2E-4*ABS(Y)
(SIN (THETA) +
3.2E-4*ABS(Y))
X**3
X**3/ (SIN (THETA)
+ 3.2E-4*ABS(Y))

Constants
Variables
Function reference
Function reference
Multiplication

1
2
3
3
8

Addition

10

Parentheses
Exponentiation

4
7

Division

3. Choosing obvious variable names, write FORTRAN expressions that are


equivalent to the following:
( >
(a)

a+h
cTd

(6)
(c)

e* - k*
ab'-i

{d)

a(10,9)(0.910)

(c)

tan a + tan2 a

U)

sin(a+|/?|)2
ln7 + e

4. Find the errors, if any, in the following arithmetic expressions:


FORTRAN Expression

Intended Meaning

(a) LOG(2.*X + SINE(ALPHA))

ln(2z + sina)

(b) A/D*B/E/(F/C)

abc/def

(c) (TAN. BETA - l.)**16GAMMA


(d) 0.79E(2Y + 1)
(e) A*B**C*D**E

(tan/3-1)16
7.9 x 102y
abcde

(f) A**B**2

a26

(g) SIN** (-1)(COS**2 (THETA))

sin-1 (cos2 (0))

(h) 3*SQRT(J*K) - X**3.0


(i) A**B**C

3{jk)^2 - x3
{ab)c
2-14

2.6 Operators and Expressions


2.7 Mixed-Type Expressions
When both operands for any of the binary operators **. * . /. +, or - are
of real type, the object program generated by the FORTRAN compiler will employ
floating-point hardware instructions to perform the arithmetic. For example, the
values of expressions such as
5.78*9.654
ALPHA/BETA
9.7 + X

will also be of real type; the results will be as accurate as possible for the word
length (about seven decimal digits).
Similarly, when both operands for a binary operation are of integer type,
the compiler will generate integer machine instructions to perform the arithmetic.
The values of expressions such as
5*7

5/7

MEAN** (-2)

5 + JOE

will always be of integer type. However, the programmer must exercise care in two
cases involving integer operations:
1. The division of one integer operand by another integer operand. If the
operation would normally produce a result with a fractional part, the result
is truncated to the next lower integer in absolute value. Illustrations of
integer division are given in Table 2.9.
2. The exponentiation of an integer operand by a negative integer operand. For
example, 5** (-2) is treated as 1/5**2 and has the value 0.
Table 2.9 Examples of Integer Division
Expression

Value

5/7

0
2
2
-2
10
15
N, if and only if N
is an integral
multiple of I

14/7
14/5
(-14)/5
14/5*5
15/5*5
N/I*I

Digital computers do not normally have machine-language instructions for


handling two operands of different types. Thus, while there will be an integer
instruction for adding two integer operands, and a floating-point instruction for
adding two real operands, there will not be an instruction for addition of an integer
2-15

2.7 Mixed- Type Expressions


operand to a real operand. Nevertheless, FORTRAN does allow the mixing of
integer and real operands in arithmetic expressions, so that expressions such as
3.4 + 4, I/ALPHA, and X**2 are syntactically correct. Except for exponentiation
of a real base by an integer power, whenever an operator is applied to two operands,
one of integer type and the other of real type, the operand of integer type is first
converted to real type, and the calculation is then performed using floating-point
arithmetic.
Thus, if even only one operand in a mixed-type expression is real, then the
final value of the expression will be real. The programmer must be careful when
mixing types, however, as parts of the expression may still be processed using
integer operations. For example,
5/4 + 2.5
will be evaluated as follows:
1. Since division has precedence over addition, the expression 5/4 will be cal
culated first, using integer division, yielding the integer value 1.
2. Before the addition operation can be performed, the integer 1 will be con
verted to real form 1 . automatically by instructions in the object program
produced by the FORTRAN translator.
3. The floating-point addition operation will produce the real sum: 1. + 2.5
= 3.5.
If the expression were written as 5 . /4 + 2.5, or 5/4. + 2.5, or 5./4. + 2.5,
the resulting value would be 3.75, since floating-point rather than integer division
would have been used.
To illustrate these points further, refer to Table 2.10; even though the last
two expressions appear similar, the order of processing produces different results.
Table 2.10 Mixed-Type Expressions
(I - 4, J - 10. BETA - 2.5)
Expression

Value

Type

J/I
J/I*BETA
BETA*J/I

2
5.
6.25

Integer
Real
Real

The conversion of an integer operand value to the equivalent real value re


quires several machine operations; the process is called floating an integer, and oc
curs automatically when mixed-type expressions appear in FORTRAN programs.
Because there is a penalty to be paid in additional computational time, however,
the programmer should not mix types unnecessarily. Thus, 4 . 0*X should be used
rather than 4*X, for example. In one exception to this rule-of-thumb, already dis
cussed in Section 2.6, it is preferable to raise a real base to an integer power (X**2,
say) rather than to the real equivalent of the integer power (X**2. , for example).
2-16

2.6 Operators and Expressions


Type conversions can be effected directly by referencing one of two built-in
functions (not listed in Section 2.5) called IFIX and FLOAT. If Z and I are,
respectively, expressions of real and integer type, then the function reference
IFIXUR)
has as its value the integer equivalent of the real argument Z. If the real argument
has a fractional part, then the fixing operation will cause the fraction to be dropped
when the integer is formed. The function reference
FLOAT ( I)
produces as its value the real-type equivalent of the integer argument. Thus,
SQRT(FLOAT(I)) is a valid FORTRAN function reference, while SQRT(I) is not.
Exercises for Section 2.7
1. If I - 6. J - 7. K -2. X - 2.25. and Y 4.75. state the value
and type of the following arithmetic expressions:
(a)
(b)
(c)
(d)
(e)
(f)

2 + 3./2**2
2 + 3/2**2
2 + 3/2. **2
X**(-K)
I**K
I - J/K

(g) (I - J)/K
(h) SQRT(X) - IABS(K)
(i) -IABS(K) + SQRT(X)
(j) I**(-I)
(k) -1**1
(1) ABS(K*Y)

2. Will the algebraic expression n(n + l)/2 always be correctly represented


for both even and odd values of n, by the FORTRAN expression N*(N + l)/2?
3. If J = 2. N 11. and P 1. . what are the values and types of the
following expressions?
(a) FLOAT (N) /J
(b) N/FLOAT(J)

(c) 4./J**3/P
(d) 4/J**3/IFIX(P)

2.8 Assignment Statement


The arithmetic assignment (or substitution) statement has the general form

V -
in which the variable V (possibly subscripted, as described in Section 7.2) and
expression may be of either integer or real type. The value of the expression
is computed as described in Section 2.6, and is then assigned as the new value of
the variable V.
The flow-diagram block used for assignment is the rectangle, shown in Fig.
2.1. One or more assignment statements may appear inside the block.
2-17

2.8 Assignment Statement

V - 6

Fig. 2.2 Assignment Block


If and V have the same type, then the assignment is straightforward.
However, if is real and V is integer, then the value of is truncated to the next
lower integer in absolute value before the assignment is made. Thus, the statement
MEAN =9.7
will cause the integer 9 to be assigned as the new value of the variable MEAN.
Conversely, if is integer and V is real, then the value of will be floated and
assigned as the new value of "V; in this case, there will be no change in value. Thus,
the statement
X - 5
will cause a real 5.0 to be assigned to the variable X. The equal sign
is called
the assignment or substitution operator.
The automatic type conversion invoked when and V are of different types
can be used to advantage. If, for example, one wishes to determine the integral and
fractional part of the value of a variable X, the following sequence of assignment
statements will cause the integral part of X to be assigned to variable IX and the
fractional part to be assigned to variable FX:
IX = X
FX = X - IX
Table 2.11 gives examples of several assignment statements, in which the
final two valid examples demonstrate that assignment does not mean equality in
the usual algebraic sense. For example, the statement I I + 1 causes the value
of variable I to be incremented by unity. The equal sign is in a sense a poor choice
for the assignment operator. The left-pointing arrow, , would be preferable, as
it indicates the dynamic nature of the assignment operation. Unfortunately, this
character is not used in FORTRAN.

Table 2.11 Assignment Statements


Valid

Invalid

X = Y
INT = 4.9
DISCR = SQRT(B*B - 4.*A*C)
OHMS - VOLTS/AMPS
1 = 1+1
X = -X

-X = Y
4.9 = INT
SQRT(B*B - 4.*A*C) = DISCR
VOLTS/AMPS = OHMS
1 + 1 = 1
-X = X
2-18

2.6 Operators and Expressions


Table 2.12 illustrates how assignment statements can be used for interchang
ing the values stored in two variables, A and B, for example. The first construction
fails, because after execution of the statement A = B, the original value of A has
been permanently erased before it can be stored in B. Note that a third variable
(SAVEA, for example) is needed, as shown in the second construction.
Table 2.12 Interchange of Values
1. (Incorrect)

A = B
B = A

2. (Correct)

SAVEA - A
A = B
B = SAVEA

Exercises for Section 2.8


1. Which, if any, of the following are valid FORTRAN assignment state
ments?
(a)
(b)
(c)
(d)

X - Y
X <- Y
SQRT(4.0) 2.0
I I - 1

(e) A + B - SQRT(D - E)
(f) I = 4.78 - I + I - 4.78
(g) ALPHA = BETA = J - Q

2. Consider the variables W, X, Y. and Z. Write FORTRAN statements


that will store the value of W in X, X in Y, Y in Z, and Z in W.
3. If A 5.3, B = 3.2, and JACK 4 , what values will be assigned to
the variables I , X , and JACK in the following FORTRAN assignment statements?
(a) I = A
(b) X = JACK + A
(c) I - JACK + A

(d) JACK = JACK + 1


(e) JACK = -3.52

4. Complete the numbered entries in Table 2.13, showing the values of X,


Y, Z, and I after execution of successive assignment statements?
Table 2.1S
Assignment
Statement

Values after execution


X
Y
Z
I

X
Y
Z
X
I
I

2.2

=
=
=
=
=
-

2.2
4.7
X + Y
-Z
ABS(X)
I + 1

2-19

2.8 Assignment Statement


5. Using obvious variable names, write FORTRAN statements that are
equivalent to:
(a)
W

y = ir x 10-6*
ex cos 9 + x~x cosh 6
y=
2xz

l x
6.
sequence?

1
1
i-l
x-2
i-3
What are the values of the variables G, H, and I after the following

MONTH 6.5
JOE - 5
XYZ = 5.
G = MONTH/JOE*XYZ
H - XYZ*MONTH/JOE
I = MONTH/ (JOE*XYZ)
7. Write down a single assignment statement that will take the integer value
stored in J (which may be either even or odd), increase it to the next higher odd
integer, and store the result back in J.
8. Write down a single assignment statement that will take the square root
of the positive integer stored in I, drop any fractional part, and store the result in
the variable K. (For example, if I = 19, K would become 4).

2-20

CHAPTER 3
INPUT AND OUTPUT

3.1 Introduction
The majority of FORTRAN programs include statements that will cause the
computer to read numerical input values or data, and to display numerical output
values or results similar to the examples already seen in Section 1.3. The present
chapter is largely concerned with such "I/O" statements. A discussion of more
advanced features is given in Chapter 8 (particularly on the I/O of arrays) and in
Chapter 11 (particularly on the I/O of non-numerical information, such as strings
of characters).
There are many ways of communicating with a digital computer, especially
if the machine is large. Consequently, I/O may involve a variety of devices, such
as a remotely located terminal, a magnetic tape unit, or the cathode-ray screen of
a graphics terminal. However, most computer programmers are likely to use the
following I/O devices most heavily:
1. Input. In the first instance, a terminal or microcomputer keyboard will prob
ably be used for entering data. However, to save repetition and to facilitate
editing, such information will often be stored in a permanent file on disk
storage, which may be used in the second instance.
2. Output. The two most frequently used devices are the TV monitor and the
printer. Such devices (and others, including files) can readily be accommo
dated by the READ . WRITE . and FORMAT statements that follow.
When considering the input/output of information, three essential items
must be specified:
1. An identification of the particular information involved, typically as a list t
of values (both numeric and nonnumeric) that are being transmitted.
2. The source of input values or the destination of output values, typically as a
code that identifies a particular I/O file or device. In some I/O statements,
this item can be omitted or defaulted, in which case we must accept a
standard I/O unit supplied by the computing system (e.g., the terminal
keyboard for input and the TV monitor for output).
3. The format according to which the information is to be interpreted and
arranged. This item can again be omitted from certain I/O statements, in
which case we must also accept a format supplied by the computing system.
3-1

Chapter SArithmetic Structures


3.2 List-Directed READ and WRITE Statements
For our purposes, list- directed means that the format is supplied by the
computer, depending on the list of variables involved, and that we do not have to
worry about it. Thus the benefit of simplicity is achieved at the cost of some lack
of control. The following are the most important forms of the list-directed input
statements, in which the codes are described in Table 3.1.
READ
READ
READ

(U. *) Z
(U. *. END- JV) Z
(U. *. ERR- .A/1. END=>/2)

Table S.l Codes in the READ Statement


Code

Meaning

Code for the unit from which input is to occur, even


tually to be identified as a file or device. If an aster
isk (*) is inserted, a default unit (such as the terminal
keyboard) will be specified by the particular computing
system. Other codes will be discussed later.

Indicates that instead of using a specified format (see


Section 3.4) a list-directed input of values is implied.
That is, each item of data being transmitted is stored in
a manner appropriate to the type and length (see Section
9.3) of the corresponding variable or other name in the
list.

M or M2

The number of an executable statement to which con


trol is automatically transferred when an end-of-file is
encountered, typically when when there are no remain
ing data to be read.

Ml

The number of an executable statement to which control


is automatically transferred if an error in data transmis
sion occurs, typically when the data contains an unintel
ligible or inappropriate character.

List of variables whose values are to be read. (The list


can also include array elements, array names, and array
segments, to be discussed in Chapters 7 and 8.) Suc
cessive values in the data being transmitted must have
a one-to-one correspondence to the variables in the list,
and must be separated by blanks or commas.
3-2

S.2 List-Directed READ and WRITE Statements


Examples
Consider the input statements
(a)
(b)

READ (*.*)
READ (5.*)

I. J. K. ALPHA. X. Y. MEAN
I. J. K. ALPHA. X. Y. MEAN

in conjunction with the following sequence of values, assumed to be available on


the "default" input device for (a), and on device number 5 (which might be a
diskette file, for example), for (b):

Column:
Line 1:
Line 2:

1
2
1234567890123456789012345
30. 17. -4. 384
0.00495 2.496E2
6

The column numbers have been shown here merely to emphasize that the spacing
of the individual values is quite arbitrary. After execution of the corresponding
READ statements, the seven variables in the list will have the following values:
Variable

Type

Value

I
J
K

Integer
Integer
Integer
Real
Real
Real
Integer

30
17
-4
384.
0.00495
249.6
6

ALPHA

X
Y
MEAN

Each time a list-directed READ statement is executed, data values are read,
starting with a new data line; reading continues over more than one line, if neces
sary, until the values have been read for all variables in the list. Any information
on the last data line that is typed to the right of the value assigned to the last
variable in the input list will be ignored. Each constant must be contained on one
line, so that the splitting of a constant between two data lines is not allowed.
Integer constants, F-type and E-type real constants, the logical constants
.TRUE. and .FALSE. (and their abbreviations T and Fsee Section 6.2), and char
acter constants (to be postponed until Chapter 11) may appear on the data lines.
If the same constant, C, appears m times in sequence on a line, an abbreviated con
struction m*C is allowed. Only integer constants may be read for integer variables,
and integer, F-type, and E-type real constants may be read for real variables. For
example, if we wished to read the value 700 for the integer variable NUMBER, the
value .TRUE, for the logical variable SWITCH, and the repeated value 4.5 for the
real variables A . B . C . D . and E, the input statement would be
READ (*.*)

NUMBER. SWITCH. A. B. C. D. E
3-3

Chapter SArithmetic Structures


and the contents of the data line could be
700.

T.

5*4.5

We next consider list-directed output statements, of which the following is


the most important form:
WRITE (U. *)

The meanings of U and * are identical with those for the READ statement, just
discussed. Again, if an asterisk is inserted for U, then a default devicesuch as
the TV monitorwill be suplied by the computing system. The END option has
no significance on output; although the ERR option will compile, it is not generally
used.
However, the list t now has more comprehensive possibilities on output.
Generally, it may include expressions of any typearithmetic, logical, and char
acter. Since character expressions (to be discussed in Chapter 11) are essentially
literal strings (that is, a sequence of one or more characters), we now have the pos
sibility of displaying messages in the output, along with the values of the various
entities.
If expressions appear in the output list, their first character must not be a
left parenthesis. Thus, (A + B)/2. is illegal, but A/2. + B/2. and +(A + B)/2.
are valid.
Examples (excluding character strings)
WRITE (*.*)
WRITE (6.*)

NUMBER. SWITCH. A. B. C. D. E
X. Y. Z. 100. SQRT(B**2 - 4.*A*C)

The values of the variables and/or expressions are printed, in order, across
the output page. Integer, F-type real, E-type real, and logical expressions are
displayed using 112. F16.7. E14.6. and Ll format specifications (see Sections
3.4 and 8.4), respectively, with one blank preceding successive fields. A typical
line of output will have up to four or five fields.
The provision for both literal constants and expressions of character type
to appear in the output list allows the programmer to label the output variables
easily, without the necessity of using the A format specification (Section 11.2).
Example (including character strings)
If the integer variable N has the value 700, the real variable PI has the value
3.14159, then the statement
WRITE (6.*)

'N -'. N. ' PI -'. PI. ' PI.LT.1.2 -'. PI.LT.1.2

would produce printed output having the appearance


N =

700 PI -

3.1415900 PI.LT.1.2 F
3-4

S.2 List- Directed READ and WRITE Statements


Example Program 3.1List-Directed I/O
The reader can reinforce most of the above concepts by reading carefully
through the following program and its output.
Program
PROGRAM IOCHK1
C
C
C
C
C

Program for demonstrating simple versions of


the READ/WRITE statements. The first asterisk
denotes the keyboard for READ and the monitor
for WRITE. The second asterisk denotes listdirected (format-free) input and output.

Input values from keyboard


READ (*.*) X. I
Display values on the monitor
WRITE (*.*) X. I
Display prompting message on the monitor
WRITE (*.*) ' Enter values for Y and J:'
Input values from keyboard
READ (*.*) Y. J

Display values on the monitor


WRITE (*.*) Y. J

Display values again. this time with labels


WRITE (*.*)
' Y -'. Y. ' J =' . J

Display a message (literal string) without values


WRITE (*.*)
' Now demonstrate the END= option.'

C
C

Input and display values until


end-of-file (<Ctrl-Z>) entered
WRITE (*.*) ' Enter values for A and B:'
READ (*.*. END-999) A. B
WRITE (*.*) ' A. B -'. A. B. ' A + B -'. A + B
GO TO 10

10

Control comes here on end-of-file


3-5

Chapter SArithmetic Structures


999

STOP 'End of IOCHK1'


END

Output from monitor


The above program was run on an IBM PC. The following is a copy of what
appeared on the monitor, and includes not only the program output but also a
copy of what was entered as data from the keyboard (here underlined for clarity).
1.2345678. 2147483647
1.2345680
2147483647
Enter values for Y and J:
10.. 314159
10.0000000
314159
Y =
10.0000000 J =
314159
Now demonstrate the END- option.
Enter values for A and B:
1. . 2.
A. B
1.0000000
2.0000000
Enter values for A and B:
1 2
A. B *
1.0000000
2.0000000
Enter values for A and B:
0.1234E5. 5.432E1
A. B =
12340.0000000
54.3200000
Enter values for A and B:
999.999. -0.123
A. B =
999.9990000 -1 .230000E-001 A
<Ctrl-Z>
End of IOCHK1

A + B =

3 . 0000000

A + B

3.0000000

A + B -

12394 . 3200000

+ B -

999 . 8760000

Example Program 3.2List-Directed I/O


The following program is similar to that in Example 3.1, except that input
is now taken from the file IOCHK2.DAT and output is to the printer. Details of how
I/O units 5 and 6 are so identified at execution time appear in Chapter 5.
Program
PROGRAM IOCHK2
C
C
C
C
C

Program for demonstrating simple versions of the


READ/WRITE statements. The two I/O numbers are
identified at execution time as follows:
5 = File I0CHK2.DAT
6 - Printer (IBM PC name is LPT1)

3-6

S.2 List- Directed READ and WRITE Statements


C
C

As usual. the asterisk denotes list-directed


(format-free) input and output.

Input values
READ (5.*) Y. J

Print these values


WRITE (6.*) Y. J

Print values again. this time with labels


WRITE (6.*)
'Y -'. Y. ' J -'. J

Print a message (literal string) without values


WRITE (6.*)
'Now demonstrate the END= option.'

C
10

Input and print values until none remain


READ (5.*. END=999) A. B
WRITE (6.*) 'A. B ='. A. B. ' A + B -'. A + B
GO TO 10

Control comes here on end-of -f ile


999

STOP
END

Listing of input file IOCHK2.DAT


1.2345678. 2147483647
1.. 2.
1 2
0.1234E5. 5.432E1
999.999. -0.123

Printed output
1.2345680
2147483647
Y *
1.2345680 J =
2147483647
Now demonstrate the END= option.
A. B =
1.0000000
2.0000000
A. B =
1.0000000
2.0000000
A. B =
12340.0000000
54.3200000
A. B 999.9990000 -1 .230000E-001 A

A
A
A
+

+
+
+
B

B B =
B =
-

3.0000000
3.0000000
12394.3200000
999.8760000

Observe that the output is no longer interspersed with the input values, and is
therefore easier to read.
Finally, note the flow-diagram blocks for input (resembling a punched card)
and output (like a torn sheet of paper) operations, shown in Fig. 3.1. In the first
3-7

Chapter SArithmetic Structures


two cases, values for variables in the list t are to be either input or output. In the
third case, the character string 'C is to be displayed.

Fig. S.l Flow- diagram blocks for input and output.


Exercises for Section 3.2
1. Explain the significances of the asterisks in the statements:
READ (*.*) A. B. C
WRITE (*.*) A. B. C
2. What are the advantages and disadvantages of list-directed input and
ouput?
3. You are using list-directed input to read values from unit 5 for the
variables R. S. T. and INDEX, which have values of 2.5, 250,000, 2.5 billion, and
-999, respectively. Give the appropriate input statement and show in two different
ways the appearance of the data values.
4. You are using list-directed output to display values on unit 6 for the
same variables (and the same values) as in 3 above. Give the appropriate output
statement if:
(a) Only the values are to be displayed.
(b) The values and identifying labels are to be displayed.
5. What is the significance of the integer value for J in the input file in
Example Program 3.2?
3.3 Formatted READ Statement
The most general I/O statements are called the formatted input and output
statements. The formatted input statement has the following principal forms
READ
READ
READ

(U. M) C
(U. Ml. END=>/2) ,
{U. Ml. END=^/2. ERR=A/3)

in which the input-unit code U, list , and END and ERR options are identical to
those defined in Section 3.2.
Information as to how the data values in the list t are arranged in the data
lines is supplied in the form of a special code, called the format specification, which
appears in a separate nonexecutable FORMAT statement or declaration having the
form:
M

FORMAT (Format Specification)


3-8

8.4 The FORMAT Declaration


Here, the statement number M of the FORMAT declaration is the same as the second
element inside the parentheses in the associated READ statement, and links the READ
statement with the FORMAT declaration. In rare cases (see Section 8.4), M may be
the name of a variable containing the format specification in character form, and no
FORMAT statement need appear in the program to accompany the READ statement.
Example
READ (5. 101)

X. Y. I. N. TEMP

As a result of this statement, the object program would read five numerical
values from one or more lines from device 5. The layout of the five numbers (two
real numbers for X and Y followed by two integer numbers for I and N followed by
one real number for TEMP) in the data line(s) would be described in the format
specifications of a FORMAT statement numbered 101. Only variables may appear in
the input list C. Clearly, the attempted reading of more general expressions, such
as X + Y, would be inadmissible, since the compiler assigns memory locations only
to variable names and constants that appear in FORTRAN statements.
3.4 The FORMAT Declaration
The FORMAT declaration that accompanies a READ statement may appear
anywhere in the FORTRAN program prior to the END statement. Some program
mers prefer to place the FORMAT declaration immediately after the READ statement,
but in most of the example programs in this text all FORMAT statements are grouped
together near the end of the program, following all of the executable statements.
Note that the FORMAT statement is the only FORTRAN declaration (nonexecutable
statement) that is allowed to have a statement number, and that it must have one.
The statement number must not appear in any executable statement other than
the input (or output) statement for which the format specification applies. If the
format specification is identical for two or more input or output statements, then
the some FORMAT statement may be referenced in these input or output statements.
Since most of the remarks on input formats apply equally well to output
formats (which accompany WRITE statements, as described in the next section),
we shall call the information on a single line of input or output a unit record. The
maximum number of characters (including blanks) in a unit input record is flexible,
but most programmers do not exceed 80; historically, this number corresponded
to the number of columns on a punched card, but it is also about the maximum
number of columns that can be listed conveniently on a normal piece of paper. In
most cases, the maximum length of a unit output record will correspond to the
number of columns on the printer, typically 80 or 132. If screen output is being
produced, then the unit output record is restricted to 80 columns.
A record is subdivided into one or more fields, each of which is in turn a
group of one or more columns. A format specification consists of one or more field
specifications, separated by commas, showing how each record is thus subdivded,
3-9

Chapter SArithmetic Structures


and also indicating what type of information is to be found in each field. There
must be a one-to-one correspondence between the format specification and the
order and types of the variables or expressions in the relevant input or output list.
Thus, unless special provision is made, variable names or labels for expressions
will not appear on the record.
The field specifications available for numerical information include those
shown in Table 3.2.
Table S.2 Field Specifications for Numerical Information
Field
Specification

Interpretation f

nlm

n integer fields, each m columns wide, each contain


ing an integer constant placed to the extreme right
of its field.

nFm . d

n real fields, each m columns wide, each containing an


F-type constant, with the decimal point assumed to
be located immediately to the left of the digit in the
dth column, counting from the rightmost column in
the field.

nEm.d

n real fields, each m columns wide, each containing


an E-type constant. The integral exponent must be
placed to the extreme right of the field. The decimal
point in the mantissa is assumed to be located d
columns to the left of the letter E.

nX

A skip field, consisting of n blank columns. (If used


for input, these columns are ignored no matter what
they contain.)
f Note: if n is omitted from an I . F . or E specifi
cation, a single field is assumed (that is, n = 1); n
may not be omitted from an X specification.

Examples are shown in Table 3.3; the "square-cup" character, U, emphasizes


the presence of certain blank spaces.
For input, the decimal point may be omitted from a number read from an E
or F field, in which case it will be presumed to be located according to the field
specification. (If the point is in a position not agreeing with the field specification,
the latter will be overridden.)
In the E-type field, there is considerable flexibility available on input, as
shown by the equivalence of the last three numbers in the above table. The ap
pearance of the output for such a number, however, depends on the compiler and
3-10

S.4 The FORMAT Declaration


usually appears with the first significant digit of the mantissa immediately to the
right of the decimal point and with the exponent adjusted accordingly, that is, in
normalized scientific form. Optional plus signs may or may not appear, again de
pending on the particular compiler. If fewer decimal places are requested than are
actually available in the machine's memory, then the figures of least significance
will be lost. Obviously, a correct field specification must specify enough columns
to be able to contain all the characters requested, including digits, decimal points,
and minus signs.

Table S.S Examples of Field Specifications


Field
Specification

Possible
Contents

Value
Assigned

15
15
F10.5
F10.5
E12.3
E12.4
E12.3

U5768
UU-6U
UUU3.14159
U U U3.142 U U
UUUU-6.731E5
U U -0.6731E + 6
UU-67.310E04

5768
-60
3.14159
3.14200
-6.731 x 106
-6.731 x 105
-6.731 x 105

Special care is required when specifying the width of E fields on output. E


fields are typically printed in the form sO.xxxEsee or s.xxxEsee, where s is a
blank (or plus sign) or a minus sign, ee is the integral exponent, and xxx are
the d significant digits in the mantissa. Thus, m must not be smaller than d +
7 or d + 6, depending on the particular compiler. Be generous! The width of
a field can often be overspecified to advantage, resulting in several blank spaces
separating the numbers, which are then easier to interpret. When an output field
is underspecified (for example, attempting to print a value 9872 using an 13 field)
a series of asterisks is typically written in the field to indicate the error.
Example
Consider an input line with the following information:

Column:
Values:

12
3
4
1234567890123456789012345678901234567890
741
6 -247.932
9.107E-28

Fields:

15
<

Variables: I

15
><

F10.4
><

5X
><

E15.3
><

>
EMASS

3-11

Remaining
columns are
ignored

Chapter SArithmetic Structures


The following statements would be appropriate for reading the above values.
102

READ (5.102) I. J. Y. EMASS


FORMAT (215. F10.4. 5X. E15.3)

After the READ statement has been processed, I. J. Y. and EMASS would have
the values 741, 6, -247.932, and 9.107 x 10-28, respectively. If columns 21 through
25 were all blank (as in the above case), then an equivalent format specification
would be
102

FORMAT (215. F10.4. E20.3)

That is, blank spaces can usually be incorporated as part of an overspecified field
width.
If the format specification of a unit record contains a repeated field pattern,
then an abbreviated specification is allowed; the part of the specification that is to
be repeated is enclosed in parentheses and is preceded by the number of repetitions.
For example, the following are equivalent:
103
103

FORMAT (15. F10.4. 5X. E15.4. F10.4. 5X. E15.4. 110)


FORMAT (15. 2(F10.4. 5X. E15.4). 110)

If more than one unit record is to be described for a single input or output
statement, three courses of action are available:
(a) If the unit records are to be identical, the format specification need be given
once only.
(b) If the unit records are different, slashes (/) must be incorporated into the
specification to delineate the end of each unit record.
(c) If the first one or more records are different from the last unit records, which
are identical, then extra parentheses must be inserted around the last part of
the specification. This parenthesized part of the format is used repeatedly for
remaining elements of the input or output list. As this feature is normally
used when reading or printing arrays (see Section 8.5), discussion will be
delayed until later.
Examples
(a) Read the variables A. B. C. D. E. F. G. and H. The data lines are
such that two F10.4 fields appear on each line; that is, A and B appear on the
first line in columns 1-10 and 11-20, respectively, variables C and D appear on the
second line with the same format, and so on, as shown in Table 3.4.
The READ and accompanying FORMAT statements would be:
READ (5.104) A. B. C. D. E. F. G. H
104 FORMAT (2F10.4)
3-12

8.4 The FORMAT Declaration


Table 8.4 Layout of values for variables
A-H on successive data lines
Column:

1
2
1234567890123456789012345

Line 1:
Fields:

A
B
<--F10.4-X--F10.4->

Line 2:
Fields:

C
D
<--F10.4-X--F10.4->

Line 3:
Fields:

E
F
<--F10.4-X--F10.4->

Line 4:
Fields:

G
H
<--F10.4-X--F10.4->

When the READ statement initiates reading from device 5, the associated
programs responsible for converting the characters appearing on the input lines to
real and integer numbers to be stored in variable locations in memory initiate a
format specification scan, starting at the beginning of the specification. A and B
will be read from the first line using the 2F10.4 specification. Since no additional
specifications appear in the FORMAT statement, the format scanner returns to the
beginning of the specification and reprocesses the code 2F10.4. assuming that the
code also applies to the next unit record. Hence, C and D will be read from the
second data line. Again, the scanner encounters the end of the specification, and
the process is repeated, so E and F are read from the third data line and G and H
are read from the fourth data line. The format scanner reverts to the beginning of
the specification whenever it reaches the end of the specification, and additional
data values corresponding to unread variables in the READ statement input list
still remain. A variant of this "back-to-the-beginning" scanning mechanism is
described in Section 8.5.
If the slash convention were to be used, the above example could also be
written as:

104

READ (5. 104) A. B. C. D. E. F. G. H


FORMAT (2F10.4/ 2F10.4/ 2F10.4/ 2F10.4)

We consider the first form preferable, especially if there is a long list of variables.
(b) Values are to be read for two variables, X and Y, spread over three data
lines. Each variable is assigned to an F10.5 field, X starting in column 16 of the
first line, and Y starting in column 31 of the third line. (The contents of the
3-13

Chapter SArithmetic Structures


remaining columns, and of the second line in particular, are to be ignored.) Note
that an empty input record (i.e., the line to be skipped over) can be indicated
with two slashes in sequence in the format specification. An appropriate input
statement and FORMAT declaration would be:

106

READ (5.106) X. Y
FORMAT (15X. F10.5//30X. F10.5)

(c) Read values for B . C . D . MEAN . F . and G . entered on three lines as


shown in Table 3.5.
Table S.5 Layout of values for variables B. C
D . MEAN . F . and G on successive data lines.
12
3
Column: 123456789012345678901234567890123456789012345
Line 1:
Fields: <

B
E15.8

C
E15.8

D
E15.8

>

Line 2:
MEAN
F
Fields: <--I8--X--F12.6--->
Line 3:
Fields: <

30X--

G
-><--F10.5->

The appropriate statements would be


105

READ (5.105) B. C. D. MEAN. F. G


FORMAT (3E15.8/ 18. F12.6/ 30X. F10.5)

It is legal, although very unusual, for a READ statement to have no input


list , in which case lines in the input file can be skipped under format control;
that is, the format specification simply consists of a sequence of slashes. There
should be one fewer slashes than the number of lines to be skipped; thus, when no
specification appears at all, as in
100

FORMAT (

one line will be skipped in the input data.


In summary, the rules for scanning input formats are:
1. When a READ statement is executed, the associated format is scanned leftto-right from the beginning.
2. A data line is read and partitioned into fields according to the format for
the first record.
3-14

8.4 The FORMAT Declaration


3. Contents of the fields are converted to the specified internal form (integer,
real, etc.) and are assigned, in order, to variables in the input list.
4. This procedure is followed for additional records, their associated formats,
and appropriate variables in the list until either:
(a) The list is satisfied.
(b) The end of the format specification is reached, but the list is not satisfied.
If situation (a) applies, then both reading and format scanning cease. If case
(b) applies, and no "repeating parentheses" (see Section 8.5) are present in
the format specification, and the end of the format is encountered before the
list is satisfied, reading is resumed with the next data line, and the format
scan proceeds from the beginning of the specification.
A word of caution is in order concerning the types of variables and their
corresponding format specifications. Data are read from lines, converted as spec
ified, and stored in the memory locations assigned to the variables. Usually, no
check is made to determine that the information stored is of the proper type for
the variable. For example, if the user inadvertently uses an 110 specification for
the information stored in a real variable named X, then normally no indication of
the error will be made at the time. Almost invariably, however, such a mismatch
of types will cause problems later in the calculations. The programmer must take
special care to insure that the data values, format specification, and input list are
compatible in their order of appearance and types.
Exercises for Sections 3.3 and 3.4
1. Check true, or false, as appropriate:
(a)

A single FORMAT statement can be referred to in more


than one READ or WRITE statement in a single pro
gram.

T D

F D

(b)

All FORMAT declarations may be grouped together immediately after the END statement.

(c)

The values of real variables may be read using either


E or F format specifications.

T D

(d)

A program must contain at least one READ statement.

T D

F D

(e)

A FORMAT declaration is the only nonexecutable statement that is allowed to have a statement number
and it must have one.
The smallest number (one that is negative with
largest magnitude) that can be printed using the for
mat specification F5 . 2 is -9 . 99 .

T D

F D

T D

F D

T D

F D

(f)

(g)

Statement numbers for FORMAT declarations used for


READ statements must lie between 100 and 199.
3-15

Chapter SArithmetic Structures


(h)

If the following appears in your program,


READ (5.101 .END-999)

T D

F D

X. Y. Z

then there must be a statement numbered 999 in your


program, and it must be a STOP statement.
(i)

If values for X. Y. and Z are entered as F10.5 numbers on three separate lines (one number on each line),
they may be read using:
READ (5.100) X. Y. Z
100 FORMAT (F10.5)

T D

(j)

If values for X. Y. and Z appear in the first three


F10.3 fields of a single data line, they may be read
using

110

READ (5.110) X. Y. Z
FORMAT (F10.3)

because the format code F10.3 will be repeated as


many times as needed.
2. Values for X and Y are to be read from one data line, entered as two F10 . 3
numbers in columns 11-20 and 31-40, respectively. The rest of the card is blank.
Write a READ and a FORMAT statement to achieve this.
3. Consider the following three data lines:
1
Column:
Line 1:
Line 2:
Line 3:

12345678901234567890
24.293
1.42E-7
Name and address.
27
-4

Give a READ statement and its accompanying FORMAT declaration that will read
these three lines and store the four numbers in the variables X. Y. JANE. and
MARVIN . respectively. Make sure that the words on the second line are ignored.
4. The following READ statement and FORMAT declaration appear in a pro
gram:

150

READ (5.150) IDA. JOE. KATHY. E. PI. FTMILE


FORMAT (215/ 10X. 110/ F10.5. F10.5/ E15.2)

If the values for the six variables are 1001. -366. 123456. 2.718. 3.14159.
and 5280 . , respectively, show in detail how you would enter these values on the
data line or lines. Could the FORMAT declaration be written more compactly? If
so, how?
3-16

S.5 The Formatted WRITE Statement


5. Values for A. B. C.
with two F10.4 fields per line.
D on the second line, and E is
Explain in detail the action of
(a)

D. and E have been entered on three data lines,


That is, A and B are entered on the first line, C and
by itself in the first ten columns of the third line.
each of the following:

101

READ (5.101) A. B. C. D. E
FORMAT (2F10.4)

102

READ (5.102) A. B. C. D. E
FORMAT (2F10.4/ 2F10.4/ 2F10.4/ 2F10.4)

(b)

6. The following information is to be entered on two data lines:

riable

Field Designation

Line

Column

N
M
A
B
C
D
X
Y
Z

110

1
1
1
1
2
2
2
2
2

1- 10
11-20
31 -40
41-50
5-12
13-20
21-35
36-50
66-80

no
F10.3
F10.3
F8.5
F8.5
E15.5
E15.5
E15.5

Write the input and FORMAT statements required in order to:


(a)
(b)
(c)
(d)

Read in the entire contents of all nine variables on the two lines.
Read in N. A. B. C. X. and Z.
Read in C. D. X. Y. and Z.
Skip the entire contents of both data lines.

7. Write down representative READ and FORMAT statements to read from


one data line the values for three variables: N (known to lie between -9999 and
+9999), ABLE (0.000 to 99.999), and BAKER (-0.001 x 10~24 to 0.999 x 1025). If N
- 1234. ABLE - 5.0, and BAKER = -0.329 x 10~8, show the exact appearance of
the data line according to your FORMAT declaration.
3.5 The Formatted WRITE Statement
The formatted output statement
WRITE (U. A/)

causes the values of all variables (or, most generally, expressions of arithmetic,
logical, or character type) in the output list t to be transmitted to the output
unit U . Values of the variables and expressions in the list are written on the device
according to the format specification appearing in an associated FORMAT declaration
3-17

Chapter SArithmetic Structures


whose statement number is M. A value of U equal to 6 is conventionally used to
denote an output device, although most computing systems are flexible enough to
admit other possibilities.
As described in Section 8.4, variable formats may also be used occasionally,
in which case M is the name of a variable (see Section 7.2) containing a format
code in coded character form.
Example
WRITE (6.201)

X. Y. I. N. TEMP*Y

As a result of the appearance of this statement in a FORTRAN program,


the values of the four variables X. Y. I . N. and the expression TEMP*Y would be
retrieved from their assigned memory locations. The format specification in an
accompanying FORMAT declaration would then be scanned by the routines respon
sible for preparing unit record images to be sent to device 6, such as a printer. If,
for example, the values of the five variables are:
Variable
or Expression

Value

X
Y

17.56786
7.568806 x 10- u

I
N
TEMP*Y

5
-10
-23.73821

and the FORMAT declaration has the form


201

FORMAT (5X. F10.3. E15.4. 215. F12.3)

then the unit record sent to the output device would have contents similar to the
following:
12
3
4
5
Column: 1234567890123456789012345678901234567890123456789012
Content:

17.568

0.7569E-10

-10

-23.738

Note that spaces are required for decimal points and minus signs, that real numbers
are rounded before being printed, and that the E format specification causes the
value to be printed in normalized scientific form.
The format specification for output information is essentially the same as for
input information, and the I . F . E. and X format codes described in the previous
section apply without change. Output format specifications usually contain two
additional kinds of information, however:
1. Information about the spacings that are to occur before the output line is
displayed.
3-18

S.6 Literal Fields


2. Information about characters (labels, messages) that should be printed in
addition to the numerical values associated with variables or expressions in
the output list.
These two topics will be introduced next.
3.6 Literal Fields
In this section, we discuss the printing of literal or character information. It
is a simple matter to print messages and to identify numerical values of variables in
output lists of WRITE statements by incorporating character constants (sometimes
called literal strings) directly into the format specification. A character constant
is a sequence of characters enclosed in primes (apostrophes):
m^rr^m^ . . . m
Here, the n characters mi . . . m . including blank spaces, constitute the content of
the string, known in output formats as a literal field; the characters will be printed
automatically. If m. is itself a prime ('), then two primes must appear in sequence,
e.g. 'don"t'.
Alternatively, the literal field may be specified in the form of a Hollerith
field or string having the form
nHmirri2rn3 . . . Tln
This form for literal constants was introduced into the early FORTRAN languages,
and is still retained in FORTRAN 77, but has largely been replaced by the more
convenient prime-delimited character string. (Hollerith invented the punched card
as we know it, and designed many of the early business machines, particularly
those used in tabulating the U.S. Census in the late 19th century.)
Example
Suppose that at some stage in a program that computes pressures at nodes
in a piping network, N has the value 7 and the pressure at node 7 is the value of
the variable P7. If P7 equals 2.793, the statements

220

WRITE (6.220) N. P7
FORMAT C At node number '. 13. 5X. ' Pressure = '. F7.3)

would cause the following to be printed:

Col:

12
3
4
123456789012345678901234567890123456789012345
At node number

Pressure
3-19

2.793

Chapter SArithmetic Structures


Note the blank space before At in column 1. If the Hollerith field equivalent of the
literal field were used, then the FORMAT statement for this example would appear
as
220

FORMAT (16H At node number . 13. 5X. 12H Pressure = . F7.3)

Example:
A format specification may consist entirely of a literal field. The correspond
ing WRITE statement will then have an empty list.

221

WRITE (6.221)
FORMAT (' The input data now follow')

In this case, the message is simply printed without any accompanying numerical
values.

3.7 Carriage Control


Single-line spacing on output is achieved by ensuring that there is a blank
space in column 1 of each line. To illustrate, suppose we wish to display the value
of X, known to need no more than nine columns, including one digit after the
decimal point on output. Then, any of the following would achieve the desired
result:
1. Start the format specification with a blank in a literal field:

201

WRITE (6.201) X
FORMAT (' '. F9.1)

2. Start the format specification with a skip field:

202

WRITE (6.202) X
FORMAT (1X. F9.1)

3. Overspecify the width of the field for X:

203

WRITE (6.203) X
FORMAT (F10.1)

Note that in the examples given in Section 3.6, the output lines also started with
a blank in column 1.
Carriage control other than single line spacing can be achieved by placing
an appropriate character in column 1 by means of a literal field. The codes shown
in Table 3.6 are used at most installations:
3-20

S. 7 Carriage Control

Table S.6 Carriage-Control Codes

Character
code

Action before printing or


otherwise displaying the line

Blank

Single space.

Double space.

No advance.

Skip to the top of the next page

The carriage-control character is not displayed with the remainder of the formatted
line. The second character in the line appears in the second column of the output.
Examples
The statements

223

WRITE (6. 223) JOBNO


FORMAT ( ' lThese are the results for job number:'. 15)

would insure the printing of the line

Col:

12
3
4
123456789012345678901234567890123456789012345
These are the results for job number:

55

at the top of a fresh page starting in column 2 of the line (assuming that the
current value of the variable JOBNO is 55).
On the other hand, the statements

224

WRITE (6.224)
FORMAT ('l')

would merely advance the printer paper to the top of the next page, without
displaying any output.
It is important to note that each new line must have its own carriage-control
character in the first column. Thus, to write out a labeled value of X at the top of a
new page and unlabeled values of Y and Z two lines below, the following statements
would accomplish the desired effect:

225

WRITE (6.225) X. Y. Z
FORMAT ('lX = ' . F10.3/ '0' . 2E15.4)
3-21

Chapter SArithmetic Structures


As a final illustration, the first example in Section 3.6 might alternatively
be written as
WRITE (6.226)
226

N. P7

FORMAT (' At node number '. 13/ 'OPressure = ' . F7.3)

which would cause the following to be displayed single-spaced under the last pre
viously written line:

Col:

12
3
4
1234567890123456789012345678901234567890
At node number
Pressure =

2.793

If the first character in a line to be printed is not one of the valid carriage
control characters, then at most installations the carriage will be single spaced,
and the entire line, including the first character, will be printed starting in column
2 of the output record. Note that in this case the maximum number of columns
specified in the format for the unit record must be one smaller than the width of
the output medium. When the output record is to be punched or written into a
disk file, the carriage control character has no significance; all characters in literal
fields, including any character in column 1 of the record, will be punched.
The rules for scanning output formats are identical with those for scanning
input formats, except that records are assembled according to the format spec
ification and sent to the output device for display. Literal fields are processed
automatocally, even when they follow the fields associated with the last variable
in the output list. For example, the statements
WRITE (6.227)
227

N. P7

FORMAT (' At node number ' . 13. ' Pressure = '. F7.3.
1 ' psig')

would cause the character string "psig" (the abbreviation for pounds per square
inch gauge) to be printed after the numerical value of the variable P7.
Example Program 3.3Formatted Input and Output
The program that follows reads values for real variables X. Y. and MEAN.
and integer variables COUNT and N, using formatted input, and writes the values
out using formatted output; The program counts the (arbitrary) number of data
sets processed. The flow diagram is shown in Fig. 3.2.
3-22

S. 7 Carriage Control

'Heading'

N = 0

*.

N = N+l

X, Y, COUNT
N,MEAN

X,Y, COUNT
N,MEAN

End

Fig. S.2 Flow diagram for formatted I/O example.


Program
PROGRAM FORMIO

Short illustration of formatted input and output .

Type declarations
INTEGER COUNT
REAL MEAN
Print heading. initialize data-set counter
WRITE (6.201)
NDATA - 0

C
1

Read and print five data values


READ (5.101.END=999) X. Y. COUNT. N. MEAN
WRITE (6.202) X. Y. COUNT. N. MEAN
Increment counter. return for next data set
NDATA = NDATA + 1
GO TO 1

C
999

C
101
201
202

Print number of sets of data processed


WRITE (6.203) NDATA
STOP
.... Formats for input and output statements ....
FORMAT (F10.5. E20.3. 10X. 215/ 20X. F10.3)
FORMAT ('lThe output from this short I/O program is:'/)
FORMAT ('0X - '. F15.5. 10X. 'Y - '. E15.5/
1 ' COUNT = ' . 15. 15X. ' N = '. 15/
2 ' The value of MEAN is: '. F10.3)
3-23

Chapter SArithmetic Structures


203

FORMAT ('OSets of data processed:'. 13)


END

Data
Col :

12

12345678901234567890123456789012345678901234567890
76.54321
56
10
-1.234E-20
12345
12.34567
-1.234567E-20
-123 100
-0.001
76.54321
10
-1.234 E
-5
0.0

Note that there are two data lines per data set (the slash in FORMAT statement
101 indicates this). The first data line in each set is formatted with the unit-record
specification
F10.5. E20.3. 10X. 215
corresponding to the first four variables in the READ statement list as follows:
Variable
X
Y
COUNT

Columns on Line

Format Specification

1-10
11-30
41-45
46-50

F10.5
E20.3
15
15

The second data line in each set is formatted with the unit record specification
20X. F10.3
and contains the value of the last variable in the READ statement list as follows:

Output
Col:

Variable

Columns on Line

Format Specification

MEAN

21-30

F10.3

12
3
4
12345678901234567890123456789012345678901234567890
The output from this short I/O program is:

X =
76.54321
COUNT =
56
The value of MEAN is:

Y =
N 12.345

3-24

-.12340E-19

10

S. 7 Carriage Control
X 12.34567
COUNT = -123
The value of MEAN is:

Y =
N .001

-.12346E-19
100

X =
76.54321
COUNT =
0
The value of MEAN is:

Y =
N
.000

-.12340E-04
100

Sets of data processed:

Concerning the program, data, and output, note the following:


1. The first WRITE statement, which has no list, and which produces a heading
at the top of a new page for the output for all data sets, is executed just
once.
2. In the first data set, no decimal point appears in the value for real variable
MEAN. In this case, the decimal point is automatically inserted three columns
to the left of the right end of the field.
3. The decimal point location for the value of X in the third data set does
not agree with the corresponding format (F10.5). In this case, the former
overrides the latter.
4. A blank integer field (COUNT in the third data set) is interpreted as a zero.
5. The MS compiler/IBM PC combination (see Chapter 4) interpreted the
value of N in the third data set as 100, because there was one blank column
remaining in the field that is interpreted as a zero. However, some compilers
would have led to a value of 100 being read because blanks are not inter
preted as zeros. It is good programming practice to avoid conflicts between
the format and the appearance of the data.
6. The second printed line of output is triple spaced from the first line. The
termination of the format numbered 201 with a slash caused a single blank
line, and this was followed by a double-line spacing caused by the format
numbered 202.
7. The number of digits printed for a number need not be the same as the
number read. Also, all printed numbers are right-adjusted in their assigned
fields, and on output E fields are printed in normalized scientific notation.
Exercises for Section 3.7
1. Check true or false, as appropriate:
(a)

A "1" or "2" in the first column of an output line will


cause single- or double-line spacing, respectively.

(b)

A READ statement and a WRITE statement may share


the same FORMAT declaration.
In the following, two blank lines will appear between
the printed values of A and B :

TU

F D

(c)

3-25

Chapter SArithmetic Structures

201

WRITE (6.201) A. B
FORMAT (' ' , F10.5/ '0'. F10.5)

(d)

If VAR has the value 2.616, and is printed using an


F10.2 field, its value will be truncated to 2.61 .

(e)

The character code

(f)

The following will cause the word "MESSAGE" to be


printed on the fourth line of a new page:

202

is used for triple spacing.

WRITE (6, 202)


FORMAT ( ' 1 ' // ' 0MESSAGE ' )

2. If the current value of X is 1 .5, indicate which of the following FORMAT


declarations would cause single-line spacing, in conjunction with the statement
WRITE (6,203) X:
(a)
(b)
(c)
(d)
(e)

203
203
203
203
203

FORMAT
FORMAT
FORMAT
FORMAT
FORMAT

(' X ='. F5.1)


(1X, F5.1)
(F10.1)
("X ='. F5.1)
(' /' + . 10X, 'X ', F5.1)

(f)

203

FORMAT (F3.1)

3. Consider the statement WRITE (6,204) X, in which X may be either pos


itive or negative. If the corresponding field specification in the FORMAT declaration
is Em.d, which of the following conditions should in general be met?
(a) m > d + 5,
(b) m > d + 6,

(c) m > d + 7,
(d) m > d + 8.

4. The following output statement,


WRITE (6. 205) Xl. Yl , X2, Y2, X3, Y3
is intended to causes printing, at the top of a new page, of the form:

Col :

12
3
4
1234567890123456789012345678901234567890
X-VALUES

Y-VALUES

XXX. XX
XXX. XX
XXX. XX

yyy.yy
yyy.yy
yyy.yy
3-26

S. 7 Carriage Control
Here, "xxx.xx" indicates that the values of X are likely to have three digits before
the decimal point, and two after it. What is the shortest FORMAT specification that
is needed?
5. The following output statements,
WRITE (6.206) A. N. EPS
WRITE (6.207) ITER. VALUE

are intended to cause printing, double-spaced from the previous line, of the form:
Col:

12
3
4
1234567890123456789012345678001234567890
Input data are :

A
N
EPS

=
=
=

sdd.ddd

dd
sO . dddEsdd

Program worked!
ITER
VALUE

Results are:

dd
sdd.ddddd

(Here, "d" indicates a digit that is expected to be printed, and "s" allows for a
possible minus sign.) What FORMAT specifications are needed to achieve the above
output?

3-27

Chapter SArithmetic Structures


Notes

3-28

CHAPTER 4
RUNNING FORTRAN-77 PROGRAMS ON THE IBM PC
4.1 Introduction
The primary purpose of this text is to describe the FORTRAN-77 language,
and not to engage in too many details of other related topics involving hardware
and software, which are fully discussed in our companion book, The IBM Personal
Computer and the Michigan Terminal System. However, we include here for com
pleteness some comments on compiling and executing FORTRAN-77 programs
using:
1. The Microsoft (MS) FORTRAN compiler (version 4.00) and linker, running
on the IBM PC (Chapter 4).
2. The IBM VS (Virtual-Storage) FORTRAN compiler, running under MTS
(the Michgian Terminal System) on the IBM 3090-600 computer at the Uni
versity of Michigan Computing Center (Chapter 5).
In all cases, we assume that your FORTRAN-77 program has already been
written, probably with the assistance of a visual-editing program, such as VEDIT,
and that it has been stored on a diskette with the file-name extension . FOR (this
particular extension is required by the MS compiler. In this and the next chapter,
we shall give details of compilation and execution of a representative program that
is stored on a diskette under the file named:
progfile. FOR

(such as PROG. FOR)

4.2 Compilation, Linking, and Execution


The translation of your FORTRAN source program and its eventual execu
tion by the computer is a three-step process, as follows.
1. Compilation is the process that translates an algorithm represented in the
symbolic FORTRAN language (the source program) into an equivalent al
gorithm in the machine's language (the object program). There may be
several individual source programs or subprograms involved in a package or
suite of programs required to solve a given problem. Typically, the compiler
treats each subprogram separately and generates corresponding individual
object programs. (If appropriate, the individual source programs can even
be translated at different times.)
4-1

Chapter 4Running FORTRAN-77 Programs on the IBM PC


2. Linking is the process that gathers together the individual object programs,
along with any library programs, and generates a single interconnected
machine-language program called the object module. Library programs per
form commonly needed tasks such as trigonometric function evaluation, and
are already available in object form, usually on disk storage in a library
with name extension . LIB. Individual machine-language programs are usu
ally compiled into relocatable form, meaning that they can be moved or relo
cated as blocks of instructions to any block of addresses in the main memory.
The process of linking the individual programs to create the object module
involves a significant amount of address recalculation, since any addresses
associated with operands in the program must be modified to account for
the relocation of the programs in the memory.
3. Execution involves the loading of the object module produced by the linker
into the computer's main memory and then transferring control of the central
processor to it. The program that does the memory loading is called the
loader. The executing program reads the user's data from input devices or
files and writes results for display or printing on output devices of files.
The three steps, viewed from the standpoint of the programs involved and
their inputs and outputs are displayed in Table 4.1.

Table 4.1 Inputs and Output Programs


During Compilation, Linking, and Execution
Process

Program

Input

Output

Compilation

Compiler

Source language
programs

Relocatable object
programs

Linking

Linker

Relocatable object
programs from
compilation and
library

Object module

Execution

Object
module

User's data, from


keyboard

User's results, to
monitor, printer,
or disk files

4.3 The Microsoft FORTRAN-77 Compiler/Linker for the IBM PC


In Microsoft's implementation of the compiler/linker, the compilation task
involves either two or three passes; that is, the compilation "step" is in fact more
than one step and involves processing by two or more programs, all of which
constitute the compiler. The two passes (or three, depending on some user options,
such as code optimization) are given in Table 4.2.
4-2

4.S The Microsoft FORTRAN-77 Compiler/Linker for the IBM PC


Table 4.2 The Passes of the MS-FORTRAN Compiler.
Pass

Action

Pass 1

Translates the source program, stored in the file


PROG. FOR for example, into an intermediate form,
consisting of some temporary files that will be used
by later passes of the compiler. It also produces a
program-listing file, whose name has the extension
. LST (PROG . LST, for example) , which is important be
cause it identifies and explains, as far as possible, any
syntactical or language errors in the source program.

Pass 2

Takes the intermediate files produced in Pass 1 and


generates the relocatable object code. The output
from Pass 2 is an object program or programs that
are stored in a file whose name has the extension . OBJ
(such as PROG . OBJ). Also deletes the intermediate files
from Pass 1, and generates more intermediate files
that may be needed by Pass 3.

Pass 3

Optimizes the object code, improving the efficiency of


calculation of certain expressions, particulary if they
have elements in common. Can also produce an op
tional listing of the object program (in hexadecimal
code) in a file with the name extension .COD, or of
an assembly language version of the program in a file
with the name extension . ASM, and/or of a file con
taining detailed information about all of the programs
in an object module in a file with name extension
.MAP. Since very few programmer need such listings,
we will ignore this latter feature.

The linker then takes the individual relocatable object programs produced
by the compiler, stored in the file or files with the extension .OBJ, links them
with the necessary library programs (present in one or more library files with the
name extension .LIB), reassigns memory addresses, and generates a final object
module that can subsequently be loaded into the fast memory of the IBM/PC and
executed. The output from the linker is in a file whose name has the extension
.EXE (such as PROG. EXE).
As supplied by Microsoft, the MS compiler resides in several files on six
double-sided diskettes. Although it is possible to use floppy-disk versions of the
compiler and linker on a dual-floppy drive IBM PC, it is a very tedious process. In
essentially all cases, one wants to have the compiler/linker files stored on the hard
4-3

Chapter 4Running FORTRAN-77 Programs on the IBM PC


disk of a PC-XT or PC-AT, or for networked machines to have the files stored
on the hard disk of the network file server. The most important of these files are
listed in Table 4.3.

Table 4.S Important Files in tht! MS FORTRAN-77 Compiler.


File Name

Purpose

Size (Bytes)

Fl.EXE

150,343

Pass 1 of the compiler.

Fl.ERR

15,776

Error messages for Pass 1.

F2 . EXE

185,117

Pass 2 of the compiler.

F3.EXE

126,667

Pass 3 of the compiler.

F23.ERR

2,914

Error messages for Passes 2 and 3.

FL.EXE

25,011

Compiler manager.

FL.HLP

1,584

Help messages for manager.

FL.ERR

1,817

Error messages for manager.

F3S.EXE

82,629

LINK. EXE

50,531

LLIBFORE.LIB

194,048

Alernate Pass 3 when optimization


is disabled.
Linker.
Library file that supports an arithmetic coprocessor (such as the Intel
8087) if present; otherwise, floating
point calculations are done using
software.

Depending on the options desired, there are several ways of calling the vari
ous programs that constitute the Microsoft compiler. The sequence of compilation
activity is controlled by the "manager" program in the file FL . EXE, in response to
input from the user.
Some of the more important files that are used or produced (some option
ally) by the compiler are shown in Table 4.4. There, progfile.FOR is your original
FORTRAN source program file such as PROG. FOR. The progfile.LSJ will contain
a listing of your FORTRAN program statements, any diagnostic error messages
describing errors in FORTAN syntax, and other information such as listing of all
FORTAN variables, arrays, functions, and subroutines referenced in the source
program, and the total memory-space required. The other files are in general not
of interest to ordinary mortals.
4-4

4.S The Microsoft FORTRAN-77 Compiler/Linker for the IBM PC


If your source program contains an error (usually caught by Pass 1 of the
compiler), then the compilation/linking process will be aborted, and you can ex
amine the listing file to determent the nature of any error found . VEDIT can the
be used to make correction in the file progfile.FOR, and the compilation/linking
operations can be attempted again.
Table 4.4 Symbolic Names Used by the Compiler
Name

Contents of File

progfile.FOR

FORTRAN source program.

progfile.LST

Program listing and diagnostics generated by the


compiler.

progfile.OBJ

Relocatable object program generated by the com


piler.

progfi.le.kSH

Assembly-language version of the program.

progfile.COD

Machine-language version of the program.

progfileMkP

Memory-mapping information about the object


programs generated.

Table 4.5 lists the symbolic names of the most important files involved in
the linking operation (when LINK. EXE is being executed).
Table 4.5 Symbolic Names Used in Linking
Name

Contents of File(s)

progfile.OBJ

Object program(s) produced by the compiler.

library.LIB

Object versions of the library programs. The ma


jor library file is LLIBFORE.LIB, but other library
files may also be used under some circumstances,
depending in particular on the availability of an
arithmetic coprocessor.

progfile.EXE

Final executable object module.

The most important file from the user's standpoint is the final executable
load module file progfile.EXE. The file progfile.OBJ may be of interest if other object
program files, produced with a different execution of the compiler, are to be linked
together.

4-5

Chapter 4Running FORTRAN-77 Programs on the IBM PC


4.4 FORTRAN-77 in the FEC Laboratories
In the Freshman Engineering Computing (FEC) Laboratories at the Uni
versity of Michigan, all of the compiler program files shown in Table 4.1 are stored
permanently in a subdirectory named FORT77 on the hard disk (drive D : ) of the
Ethernet network fileserver. Note that the IBM PCs in the FEC laboratories are
not equipped with Intel 8087 coprocessors, and that the file LLIBFORE . LIB is the
appropriate library file needed by the linker.
To simplify student use of the compiler, there is a batch file that is named
FORT77.BAT on the network fileserver. This batch file handles all of the details
of the multiple-pass compilation/linking operation. During the processing, the
compiler and linker files are downloaded from the network disk into the main
memory of your IBM/PC. Intermediate files produced by the compiler are stored
on your personal diskette. In most cases, the compiler programs erase these files,
once they are no longer needed, so you will not see them in your diskette directory
after processing. In addition, the relocatable object program file with the name
extension .OBJ is erased after the linking process is complete, to save space on
your diskette.
To compile and link a FORTRAN-77 program, do the following:
1. Prepare your FORTRAN source program using VEDIT, and store it in a
file named progfile.FOR on your diskette in Drive B:, where progfile is any
legal DOS file name.
2. Be sure that the master diskette is in Drive A: and your personal diskette
is in Drive B : . Do not change the default drive from A : .
3. Enter the DOS command:
A:\>F0RT77 progfile<cr>
In the above, be sure to observe the following:
1. Do not append the drive name B: to the name of your source program file,
even though A: is the default drive; the batch file takes care of this apparent
inconsistency.
2. Do not include the filename extension .FOR in the DOS command line; doing
so may cause your file progfile.FOR to be modified unexpectedly during the
compilation process.
If there are no FORTRAN language errors, compilation and linking will be
successful and when the DOS prompt A> shows again, the following files will be
present on your personal diskette:
progfile. LST
progfile .EXE

4-S

4.4 FORTRAN-77 in the FEC Laboratories


If there is an error encountered during the compilation process, one or more
intermediate files with name extension ( . TMP) produced by the compiler may be
present on your diskette. You can erase them, if you are short of space on your
diskette.
The . LST file contains a listing of the program, some information about the
size of the program, and so on. You can print a copy of the program listing on the
printer if you wish (using the DOS commands COPY or PRINT), or display the file
on the screen using the MORE filter.
The file progfile.EXE contains the executable linked object module. To exe
cute the object program, simply enter the DOS command:
A : \>B : progfile<cr>
If there are FORTRAN source language errors in your program, then the
Microsoft compiler will abort execution of the later passes of the compiler and
of the linker, and no progfile.OBJ or progfile.EXE files will be generated. However,
the listing file progfile.LST will be present on your diskette. You should list the
file on your printer or display it on the screen using the MORE filter, and note any
diagnostics (error messages) produce by the compiler. Once you decide what the
problem is, use VEDIT to correct the errors in the source program in progfile.FOR
and attempt to compile the program again.
For example, if your source program PROG. FOR contained one or more syntax
errors, and did not compile, you should first examine the file PROG . LST (either by
using the DOS command:
MORE>B : PROG . LST

or by using a visual editor such as VEDIT:


VEDIT B: PROG. LST
Once you have found your errors (see Section 4.7), make the necessary corrections
in the file PROG. FOR, and repeat the compilation/linking procedure given above.
Eventually, you will have a program that compiles properly, in which case you can
then proceed to the execution stage.
Example Compilation/Execution 4.1
Here, we illustrate the above material by reproducing the output that ap
peared on the monitor during compilation of a short FORTRAN-77 program stored
in the file TRI1 .FOR (see Section 1.3). For emphasis, we have underlined what we
typed.
A : \>F0RT77 TRIKcr>

4-7

Chapter 4Running FORTRAN-77 Programs on the IBM PC


A:\>Echo off
Microsoft (R) FORTRAN Optimizing Compiler Version 4.0
Copyright (C) Microsoft Corp 1987. All rights reserved.
tril.FOR

Microsoft (R) Overlay Linker


Version 3.55
Copyright (C) Microsoft Corp 1984, 1985, 1986.
reserved.

All rights

Compilation/linking OK . . .
Compilation is now complete, and the final object module is in the executable
file TRI1.EXE on the B: drive. It is executed simply by typing its name, with or
without the extension . EXE:
A:\>B:TRIKcr>

45.0. 10.0<cr>
45.0000000

10.0000000

9.9999880

14.1421300

60.0, 10.0<cr>
60.0000000

10.0000000

17.3204800

19.9999700

(At this stage, execution was terminated by entering <Ctrl-Break>, an attention


interrupt. We could also have entered <Ctrl-Z>, an end-of-file indicator.)

4.5 Allocation of I/O Units


If you did not identify the I/O units (such as 5 and 6, appearing in READ
and WRITE statements) within your program by using the OPEN statement, they will
default (under the Microsoft Version 4.00 compiler) to CON, that is, to the keyboard
and monitor, respectively. However, you can also optionally reassign them to other
devices and files by using the "redirection" characters
(for input) and
(for
output). In this regard, various devices have the names shown in Table 4.6.
Table 4.6 IBM PC Device Names
Device

Name

Keyboard (for input)


Monitor (for output)
Printer

CON
CON
LPT1 or PRN

4-8

4.5 Allocation of I/O Units


We have found the following approaches to be practical for any given pro
gram:
1. For input it is almost always the case that any unit number will permanently
be identified. For example, consider the input statement.
READ (5. 101. END=999)

Here, unit 5 may be the keyboard if there is only a very small number of data
values to be entered, but will almost certainly be a file, such as PROG. DAT,
if there are more than just a few such values. In either case, it is reasonable
to make a permanent identification within the program, such as:
OPEN (5. FILE^'CON')
or
OPEN (5. FILE-' PROG. DAT')

2. The output units can also be defined similarly, either within the program or
during execution. However, the odds are that you will want to use two or
three different output media at various stages of program development:
(a) The monitor, CON, during the early stages of debugging, when you want
to see some results quicklyeven if they are incorrect.
(b) The printer, LPT1 or PRN, when your program is working correctly and
you want a permanent copy of the output.
(c) A file, such as PROG. OUT, particularly if you want to store the results,
either for later processing or for incorporation into text material using an
editor or word processor.
To preserve flexibility on output, we recommend that you do not generally
use the OPEN statement to define the output units within the program, but
identify them during program execution.
Example Execution 4.2I/O Assignments
Here, the file CHIOLD.EXE was executed, corresponding to Example Program
11.2 (see Section 11.2). Again, what we typed is underlined.
Assignment of Unit 6 to the Monitor(Default Case)
The following appearing on the monitor, with nothing printed.
A:\>CHIOLD
The gray dog
has brown eyes.
The beige cat
has blue eyes.
The white rabbit
has pink eyes.
Stop - Program terminated.
4-9

Chapter 4Running FORTRAN-77 Programs on the IBM PC


Reassignment of Unit 6 to the Printer Using the Redirection Character >
The following appeared on the monitor:
A:\>CHIOLD > LPT1

The following appeared on the printer:


The gray dog
has brown eyes .
The beige cat
has blue eyes.
The white rabbit
has pink eyes.
Stop - Program terminated.
4.6 Terminating Execution
There are three principal ways of halting execution of your program:
1. With a STOP statement within the program. This method is used in the
majority of programs in this book, typically in conjunction with an input statement
containing the END option:
1

999

READ (5. 101. END=999)

GO TO 1
STOP

Thus, when there are no more data, the end-of-file on unit 5 will cause transfer of
control to the STOP statement.
Note that if the data are being read from the keyboard, an end-of,file can
be entered either with:
<Ctrl-Z> <Enter>
<F6> <Enter>

or

If the data are coming from a file, there will normally be an "end-of-file" at the
end of the file.
2. Again by an end-of-file, without the END option in the READ statement,
as in:
1

READ (5. 101)

In this case, an error message (#1298) will appear on the monitor. By the time the
message appears, all of the (presumably correct) answers will have been generated,
so this "error" is not in fact an error.
3. By an "attention interrupt," caused by entering either:
<Ctrl-Break>
<Ctrl-C>

or

4-10

4 . 7 Error Messages
4.7 Error Messages
As far as possible, the MS FORTRAN compiler attempts to locate errors
through a set of diagnostic messages, which may appear either during compilation
or execution.
Example Program 4.3Diagnostics
The compile-time diagnostics will appear on the monitor, but may be ex
amined more leisurely by looking (either with a visual editor or with the TYPE
command) at the program-listing file, which has the file-name extension . LST. For
example, suppose that we attempt to compile the following "program," which is
adapted from Example Program 1.2, stripped of its comments (thereby already
serving as a bad example), but with a few extra comments inserted to pinpoint
the four errors.
Program

201
1
C

C
202
C
909

PROGRAM TRI2
OPEN (5. FILE-' TRI2.DAT')
Should be FILE. not DEVICE:
OPEN (6. DEVICE- 'LPT1')
WRITE (6.201)
FORMAT Ol'. 5X. 'A'. 9X. 'X'. 9X. 'T' . OX. 'Z'/' ')
READ (5.*.END=999) A. X
Y - X*TAN(A*3. 14159/180.0)
Should conclude with a right parenthesis:
Z - SQRT(X**2 + Y**2
WRITE (6.202) A. X. Y. Z
Format should be 4F10.4:
FORMAT (4F1.4)
GO TO 1
Statement label should match 999 in READ:
STOP
END

TRI2 . LST (with a few lines deleted)


1
PROGRAM TRI2
2
OPEN (5. FILE- 'TRI2.DAT')
3 C
Should be FILE. not DEVICE:
4
OPEN (6. DEVICE-' LPT1')
***** Error 149 -- unrecognizable option
***** Error 115 -- ")" expected
5
WRITE (6.201)
6 201 FORMAT Cl'. 5X. 'A'. 9X. 'X'. 9X.
4-11

'Y'. 9X. 'Z'/'

Chapter 4Running FORTRAN-77 Programs on the IBM PC


')
7
1 READ (5.*.END=999) A. X
8
Y - X*TAN(A*3. 14159/180.0)
9 C
Should conclude with a right parenthesis:
10
Z - SqRT(X**2 + Y**2
***** Error 26 -- M)M expected
11
WRITE (6.202) A. X. Y. Z
12 C
Format should be 4F10.4:
13 202 FORMAT (4F1.4)
14
GO TO 1
15 C
Statement label should match 999 in READ:
16 909 STOP
17
END
Label 999
not defined.
***** Error 131 -- label not defined

Name

Type

REAL

Offset P Class
50

sqRT

INTRINSIC
INTRINSIC

TAN
X
Y
Z

REAL
REAL
REAL

54
58
62

Name

Type

Size

TRI2
Pass

Class
PROGRAM

One

4 Errors Detected
17 Source Lines

Remarks
The first (DEVICE), second (missing ")"), and fourth (missing 999) errors
were clearly pinpointed, with probably enough information for the program
mer to have some idea as to how to correct them. The first error caused two
diagnostics.
The third error (4F1 .4 instead of 4F10.4) was not found, and would have to
wait for detection until execution time, when a number was actually printed
and found not to fit the format specification.
Following Item 2, execution-time errors usually center on either:
4-12

4.7 Error Messages


(a) Input and output. For example, the formats may have inadequate
space for the values being written, or there might be a type mismatch
(an integer field for a real number), or file names might be given
incorrectly.
(b) Arithmetic. For example, the program might attempt to take the
logarithm or the square root of a negative number.
Unfortunately, only a numerical code is generally given in these cases,
without further explanation. It may be tracked down by referring to
either Appendix C of the Microsoft FORTRAN Reference Manual, or
to the Microsoft FORTRAN Compiler Quick Reference Guide.
A list of all variables and subprograms is also given.

4-13

Chapter 4Running FORTRAN-77 Programs on the IBM PC


Notes

4-14

CHAPTER 5
RUNNING FORTRAN-77 PROGRAMS UNDER MTS

5.1 Introduction
Translation with the Microsoft compiler, and execution of the resulting ob
ject program, as discussed in Chapter 4, is particularly suitable for programs that
are no more than a few hundred statements long, and which do not take excessive
times to produce results. If more computing power is needed, the programmer
will probably wish to turn to the resources of a large "main-frame" computing
installation, of which the IBM 3090-600 machine in the Computing Center at the
University of Michigan is an excellent example.
The operating system for this IBM 3090-600 computer is the Michigan Ter
minal System, or MTS, and is fully discussed in our companion volume, The IBM
Personal Computer and the Michigan Terminal System.
The resources of MTS include a powerful FORTRAN-77 compiler, written
by IBM, and known as VS FORTRAN, where VS ("virtual storage") denotes a
particular way of organizing the memory of the computer. The goal of this chap
ter is to demonstrate how the VS-FORTRAN compiler can be accessed from an
IBM PC computer that is linked with MTS through appropriate communications
equipment.
We assume the reader will have examined, in particular, Chapters 5 and 6
of The IBM PC and MTS, and will be familiar with the following concepts:
1.
2.
3.
4.

Public, private, and temporary files.


Pseudo-devices and logical I/O units.
The WINDOW program for establishing the IBM PC/MTS link.
The $RUN command, and the setting of upper limits on CPU time.

5.2 Compilation
The VS FORTRAN-77 compiler is available in the MTS public file *FORTRANVS, and an appropriate call for our purposes, including the placement of a
representative upper limit on CPU time for all subsequent $RUN commands, is:
$SET TIME-1
$RUN *FORTRANVS SCARDS=5 SPRINT= SPUNCH-0
5-1

Chapter 5Running FORTRAN-77 Programs Under MTS


Here, the definitions shown in Table 5.1 are in effect:

Table 5.1 Parameters for the FORTRAN-77 Compiler Under MTS


Name

Meaning

FORTRANVS

Public file containing the IBM VS FORTRAN-77


compiler.

SCARDS

Logical I/O unit assignment for a file, with sym


bolic name S, where the FORTRAN-77 source pro
gram is stored. (In the rather unlikely event that
SCARDS=S is omitted, S defaults to *S0URCE*; that
is, the user would have to enter the source program
directly from the keyboard.)

SPRINT

Logical I/O unit assignment for a file or pseudodevice, with symbolic name , where the compiler
writes a program listing, together with any error
messages and other information concerning the ob
ject program. If SPRINT is omitted, any diag
nostic messages will appear on the monitor, but a
detailed program listing will not be generated.

SPUNCH

Logical I/O unit assignment for a file, with symbolic


name 0, where the object program is to be stored.
Caution: the file 0 is not automatically emptied
from any previous use. If SPUNCH=0 is omitted, 0
defaults to -LOAD, which is first emptied; that is,
the object program is automatically stored in a fresh
temporary file named -LOAD .

Examples of Compilation
1.

$RUN *FORTRANVS SCARDS- -SOURCE SPRINT LIST SPUNCHOBJ

The FORTRAN-77 program in the temporary file -SOURCE is compiled. The com
piler listing appears in the temporary file -LIST, and the object program is stored
in the temporary file -OBJ.

2.

$RUN *FORTRANVS SCARDS=-SOURCE SPRINTLIST

The same as Example 1, except that the object program is now automatically
stored in the temporary file named -LOAD.
5-2

5.S Execution
3.

$EMPTY PROG. OBJ OK


$RUN *FORTRANVS SCARDS=PROG . FOR SPUNCH=PROG . OB J

The FORTRAN-77 program in the permanent file PROG. FOR is compiled. Error
messages (if any) will appear on the monitor, and the object program will be
stored in the permanent file PROG. OBJ, which has just been emptied of any possible
previous contents.
5.3 Execution
Assuming that the source program has been compiled successfully, the re
sulting object program must next be executed with the $RUN command. It is
now appropriate to note that the I/O units can be assigned to actual devices or
files during either (or both) of two distinct stages of program development and
execution:
1. During execution, by including parameters of the form U = D in the $RUN
command, as illustrated below. Here, the generalized symbols have the
meanings given in Table 5.2.
Table 5.2 Parameters in the $RUN Command
Code

Meaning

I/O unit number. In the FORTRAN source program, U is an


integer expression, although some installations may have some
restrictions on acceptable values. For this reason, we shall con
fine our numbers to small integers, notably including the con
ventional values of 5 for input and 6 for output.

Name of device or file that is to be identified with unit number


U. Typically, D will be either:
(a) An input or output file, for example: DATA or PROG . OUT.
(b) A pseudo-device name, for example *S0URCE* (the key
board) or *SINK* (the monitor).

2. Within the program itself, by using the OPEN statement (see also Section
8.2), of which an appropriate form is:
OPEN (U. FILE-'P'. STATUS-' status')
Here, U is the same as above, but (in contrast to MS FORTRAN), D must be
a file name of not more than seven alphanumeric characters. Thus, pseudodevices such as *S0URCE* and *SINK* cannot be included, nor can file names
such as PROG. DAT, because they contain a special character.

5-3

Chapter 5Running FORTRAN-77 Programs Under MTS


Thus, in contrast to MS FORTRAN, the utility in MTS of the OPEN state
ment is confined to I/O involving MTS files with some restrictions on their names.
For these reasons, we are not strongly advocating the use of the OPEN statement
when running under MTS. The status parameter may be needed if V is a file: OLD
(the default case) signifies an existing file; NEW means that the file is to be created
implicitly by the program. The only time this parameter is needed is when writing
into a new permanent file.
Examples of Execution
1.

$SET TIME=1 (either here or at an earlier stage


in the current session)
$RUN -LOAD 5=*SOURCE* 6-*SINK*
or
$RUN -LOAD

An upper limit of one CPU second has been made for all $RUN commands. The
object program, in the temporary file -LOAD, is loaded and executed. Unit 5
(presumably appearing in a READ statement), is assigned to the keyboard, and
unit 6 (presumably appearing in a WRITE statement) is assigned to the monitor;
note that these two assignments are also the default cases.
2. $RUN PROG. OBJ 5=PROG.DAT 6=PROG.OUT T=l
The object program in the permanent file PROG. OBJ is loaded and executed,
there being an upper limit of one CPU second for this $RUN command only. Unit 5
is assigned to the permanent file PROG. DAT, and unit 6 is assigned to the permanent
file PROG. OUT. Assuming unit 6 appears in a WRITE statement, the file PROG. OUT
will somehow have to be displayed before the program output can be seen. Two
useful possibilities are:
(a) Display the contents of the file on the monitor:
$COPY PROG. OUT or
$COPY PROG. OUT *SINK*

(which has the same effect).

(b) Transfer the file to a diskette on the IBM PC (the MTS prompt
emphasized here):
#y.TELECOPY TO B: PROG. OUT FROM PROG. OUT ASCII NOTAB
Then, after signing off, print it (the DOS prompt is emphasized here):
A>COPY B: PROG. OUT LPT1 :
A>COPY B: PROG. OUT PRN:

or
(which has the same effect).
5-4

is

5.2 Example MTS VS-FORTRAN 77 Compilation and Execution


5.4 Example MTS VS-FORTRAN 77 Compilation and Execution
Example 5.1MTS Compilation/Execution
The following is an example of compilation and execution of a FORTRAN77 program from an IBM PC, using the VS-FORTRAN compiler under control
of MTS on the IBM 3090-600 computer at the University of Michigan Computing
Center. The program is essentiality Example Program 1.2 from Section 1.3, with
the two OPEN statements deleted. Before accessing MTS, the configuration of Table
5.3 was made for the two diskette drives.
Table 5.S Drive Configurations Before Accessing MTS
Drive

Contains File

Description

A:

WINDOW

Program for accessing the Michigan Terminal


System.

B:

TRI2 . FOR
TRI2.DAT

FORTRAN- 77 source program.


Data for source program.

Our goal is to compile the program, execute the resulting object program
with the data, and return the results to the IBM PC in the file B : TRI2 . OUT.
The listing below shows successive lines appearing on the monitor, with
some minor rearrangements to accommodate the slightly reduced width of this
text. As usual, everything we type has been underlined. To explain what is about
to happen, we have added here only some headings of the form:

Explanatory heading

In our example, we have employed temporary files for S, C, and 0, but permanent
files could also have been used, provided that they had been created beforehand.

Use the WINDOW program to access MTS


A>WIND0W
'/, WINDOW (MS-DOS) - Michigan Communications Protocol (MCP)
% A Licensed Proprietary Software Product of The University of
Michigan
% Version Number: 83DEC040
% '"/.HELP" => cmds. "%PF?" > PF keys
% << You may type now
5-5

Chapter 5Running FORTRAN-77 Programs Under MTS

'/.Merit : Hermes (DOW1 13 : MP08 : IBMPC)

:
: : Sign on with user number and password : : : : :
: : : : : Observe messages about system status : : : : :

Which Host?UM
MTS Ann Arbor
#

(AE51-00523)

All users $copy *NUBS - concerning NUBS closing for renovation

# THE 9700 PAGE PRINTER AT UNYN IS DOWN


#$SIGNON K8VM
#Enter password.
7PASSWORD
#Terminal , Normal , Univ/Gov ' t
#Last signon was at 10:01:19, Thu Jul 30/87
#User K8VM signed on at 10:10:26. Thu Jul 30/87

: : : : : Transfer FORTRAN-77 program from the IBM PC


: : : : : to a temporary MTS file that is named -SOURCE

#/.TELECOPY FROM B:TRI2.FOR TO -SOURCE ASCII NOTAB


#Execution begins
MCP:COPY -> Read:
11 Blocks,
703 Bytes
MCP:COPY -> Written:
26 Records,
677 Characters
#Execution terminated
%File copy is done!

List file with line numbers

#$LIST -SOURCE
1
2
3
4
5

PROGRAM TRI2
C
C
C
C

Triangle Problem. 2nd version.


Note: I/O devices 5 and 6 will
5-6

5.2 Example MTS VS-FORTRAN 77 Compilation and Execution


6
7
8
9
10
11
12
13
14
15

C
C
C

16
17
18
19
20
21
22
23
24
25
26

C
C

be defined at execution time

201
C
C
1

202
C
C

Use formatted output to print a heading . .


WRITE (6.201)
FORMAT Cl'. 5X. 'A". 9X, 'X'. 9X, "T" , 9X. "Z'/
Read input values, perform computations ...
READ (5,*.END=999) A. X
Y = X*TAN(A*3. 14159/180.0)
Z SQRT(X**2 + Y**2)
Use formatted output for all variables
WRITE (6.202) A. X, Y, Z
FORMAT (4F10.4)
Return to statement 1 for more data
GO TO 1

C
C

No more data remaining in input file


999

STOP
END

Transfer data file and list it

#'/.TELECOPY FROM B: TRI2.DAT TO -DATA ASCII NOTAB


#Execution begins
MCP:COPY -> Read:
1 Blocks,
64 Bytes
MCP:COPY -> Written:
7 Records.
57 Characters
#Execution terminated
%File copy is done!
#$LIST -DATA
1
2
3
4
5
6
7

45.0. 10.0
60.0. 10.0
53.1. 3.0
53.2. 3.0
89., 10.
89. 10
89 10

Place upper limit of one CPU second for all


5-7

Chapter 5Running FORTRAN-77 Programs Under MTS


:::: $RUN commands, and compile the source program

#$SET TIME=1
#$RUN *FORTRANVS SCARDS=-SOURCE SPRINT=-LIST SPUNCH=-OBJ
VS FORTRAN Release 3.0
#Execution begins
EXECUTION BEGINS
VS FORTRAN COMPILER ENTERED. 10:17:02
****** END OF COMPILATION 1 ******
VS FORTRAN COMPILER EXITED.
10:17:02

#Execution terminated

::::: Execute the object program; identify


: : : : : the input and output units to be used

#$RUN -OBJ 5=-DATA 6=-0UT


#Execution begins
#Execution terminated

Examine the program output, with proper in


terpretation of carriage -control characters

#$COPY -OUT
>

>
>
>
>
>
>
>

45. 0000
60. 0000
53. 1000
53. 2000
89. 0000
89. 0000
89 . 0000

10.0000
10.0000
3.0000
3.0000
10.0000
10.0000
10.0000

T
10. 0000
17. 3204
3. 9956
4.0102
572. 7986
572. 7986
572. 7986

Z
14. 1421
19. 9999
4. 9965
5. 0081
572. 8857
572. 8857
572. 8857

Transfer the output file back to the IBM PC


5-8

5.2 Example MTS VS-FORTRAN 77 Compilation and Execution

#%TELECOPY TO B:TRI2.OUT FROM -OUT ASCII NDTAB


#Execution begins
MCP:COPY -> Read:
9 Records,
318 Characters
MCP:COPY -> Written:
6 Blocks,
327 Bytes
#Execution terminated
%File copy is done!

Terminate the MTS session

#$SIGNOFF
#K8VM 10:10:26 to 10:20:01, Thu Jul 30/87
#Terminal . Normal , Univ/Gov ' t
#Elapsed time
9.566 minutes
$.20
#CPU time used
.925 seconds
$.50
#CPU storage VMI
2.616 page-min
$.21
#Wait storage VMI
3.374 page-hr
#Page-ins
126
#Disk I/O
1539
#
Approximate cost of this run:
$.94
#Disk storage charge
6 page-hr
$.00
#
Approximate remaining balance:
$45.76
%H08:DOW113-AEBE:UM51 Connection closed
% Line to network has been disconnected
% Line to network is now connected

: : : : : Return control to DOS : : : : :


%EXIT
A>
Look at the output , which will contain
: : : : : any carriage-control characters and may
: : : : : have to be edited or further manipulated

A>TYPE B:TRI2.OUT

5-9

Chapter 5Running FORTRAN-77 Programs Under MTS


A

45.0000
60.0000
53.1000
53 . 2000
89.0000
89.0000
89 . 0000

10.0000
10.0000
3.0000
3.0000
10.0000
10.0000
10.0000

10 .0000
17 .3204
3.9956
4 .0102
572 .7986
572 .7986
572 .7986

Z
14. 1421
19. 9999
4. 9965
5. 0081
572. 8857
572. 8857
572. 8857

5.5 Error Messages


Compile-time diagnostics will appear on the monitor shortly after the call
on *FORTRANVS. Here, for example, we have deliberately introduced four errors
into our program, two of which are detected immediately:
#$SET TIME=1
#$RUN *FORTRANVS SCARDS=-SOURCE SPRINT=-LIST SPUNCH=-OBJ
. VS FORTRAN Release 3.0
#Execution begins
EXECUTION BEGINS
VS FORTRAN COMPILER ENTERED. 13:34:35
ISN
4:
1 READ (5,* ,LAST=999) A, X
AN UNRECOGNIZED KEYWORD WAS FOUND IN THE I/O CONTROL LIST.
PARAMETER IS IGNORED.
ISN
6:
Z = SQRT(X**2 + Y**2
EXPRESSION HAS AN INCORRECT PAIRING OF PARENTHESIS. CHECK THAT
THERE IS A RIGHT PARENTHESIS FOR EVERY LEFT PARENTHESIS.
****** END OF COMPILATION 1 ******
VS FORTRAN COMPILER EXITED.
13:34:36
#Execution terminated

RC-12

These diagnostics may be placed in better context by examining the file


-LIST (only a portion of which is reproduced below):
#COPY -LIST
>ISN
>ISN
>ISN
>

1
2
3 201
C

PROGRAM TRI2
WRITE (6,201)
FORMAT ('l". 5X. 'A'. 9X. "X' . 9X. 'T" , 9X. 'Z'/' ')
Should be END, not LAST:
5-10

5.5 Error Messages


>ISN 4
1 READ (5.*.LAST=999) A. X
>***ERROR 1494(E)***
AN UNRECOGNIZED KEYWORD WAS FOUND IN
THE I/O CONTROL LIST. PARAMETER IS IGNORED.
>ISN 5
Y - X*TAN(A*3. 14159/180.0)
>
C
Should conclude with right parenthesis:
>ISN 6
Z SQRT(X**2 + Y**2
>***ERROR 1037 (S)***
EXPRESSION HAS AN INCORRECT PAIRING
OF PARENTHESIS. CHECK THAT THERE IS A RIGHT PARENTHESIS FOR
EVERY LEFT PARENTHESIS.
>ISN 7
WRITE (6.202) A. X. Y. Z
>
C
Format should be 4F10.4:
>ISN 8 202 FORMAT (4F1.4)
>ISN 9
GO TO 1
>
Statement number should match 999 in READ
C
>ISN 10 909 STOP
>ISN 11
END
Observe that:

1. All statements except comments are assigned internal statement numbers


(ISNs) by the compiler.
2. The first (LAST-999) and second [missing ")"] errors were pinpointed by the
compiler, with enough information for the programmer to have some idea
as to how to correct them.
3. The third error (4F1.4 instead of 4F10.4) was not found, and would have
to wait for detection until execution time, when an attempt would be made
to print a number and it would be found not to fit the format specification.
4. The fourth error (no way of reaching the statement numbered 909) was
not found. However, when the error "LAST=999" in the READ statement
was later corrected to "END=999", a recompilation indicated: "Statement
number 999 is referenced but not defined."
5. The compiler program-listing file -LIST is formatted with a width of 132
columns and may be examined more easily by telecopying it to the file
B:PR0G.LST (for example), setting the printer width to 132 columns (MODE
LPT1 : 132), and then printing it (COPY PROG.LST LPT1:).

5-11

Chapter 5Running FORTRAN-77 Programs Under MTS


Notes

5-12

CHAPTER 6
LOGICAL AND CONDITIONAL STRUCTURES

6.1 Introduction
So far, we have been concerned with the evaluation and manipulation of
arithmetic or number- valued operands and arithmetic expressions of two different
types: real and integer. In this chapter, however, we shall see how FORTRAN
also allows the programmer to evaluate and manipulate truth-valued operands and
expressions whose type is called logical. The principal use of these expressions is
to allow the posing of questions such as:
"Is the current value of the arithmetic variable I smaller
than the current value of the arithmetic variable N?"
for which the answer is two-valued ("yes" or "no"). In response to the answer,
the program might then branch to either of two different sequences of statements
(or perhaps bypass a sequence of statements) on a conditional basis. There is a
well-developed algebra, called Boolean algebra [named after the English logician
and mathematician, George Boole, (1815-1864)] for creating and manipulating ex
pressions having the value true or false. Questions such as that above are normally
written as logical expressions having the form of propositions. For example,
I < N
is a logical expression whose value is either true or false, and is a much more
succinct way of posing the question than the English sentence shown above.
Boolean algebra also allows us to create more complicated logical expres
sions. For example, if A denotes the logical operator and, then the expression
a < 7.5j/2

p + q > 9.7i

i #j

is true when a < 1 .by2 and p + q > 9.7i and i ^ j, all at the same time,
and is false otherwise. The operators <, >, and ^ are called relational operators
and connect arithmetic or number-valued operands, while the logical operators
have logical or truth-valued operands. In fact, Boolean algebra allows the use of
variables, constants, and functions having truth values as well.
6-1

Chapter 6Logical and Conditional Structures


Although not all of the operations of Boolean algebra are available in FOR
TRAN, the language contains an adequate subset for posing quite complicated
questions about numerical and logical relationships. In this chapter we shall in
troduce the simplest logical operands, logical constants, variables, and function
references, all of which are defined to be logical or Boolean expressions, denoted
generally as B.
There are just two logical constants, true and false, which are written as:
.TRUE..

.FALSE.

FORTRAN allows the use of variables having logical or Boolean values,


denoted generally as VB . The naming rules are the same as those given in Section
2.4:
1. The name of a variable consists of between one and six alphanumeric char
acters.
2. The first character of the name must be a letter.
FORTRAN has an implicit typing convention that automatically assigns
type integer to variable names beginning with the letters I. J. K. L. M. or N.
and type real to all others. Therefore, one must explicitly assign the type to logical
variables in a type declaration of the form:
LOGICAL C
where is a list of logical variables. For example, if the declaration
LOGICAL

LIGHT. SWITCH. VALVE

appears before the first executable statement in a program, then the three variables
LIGHT. SWITCH. and VALVE will be assigned logical type. Each will always be
either true or false during execution of the program. For example, the variable
SWITCH might represent the position of an electrical switch (true meaning the
switch is closed, and false meaning the switch is open); the value of LIGHT might
be true when a light is on, and false when the light is off, and so forth.
None of the common FORTRAN functions (see Section 2.5) has a logical
value. It is possible (although raresee Section 10.3) for a programmer to define
his own function with the general name TB for which the function reference 7B()
has a logical value.
Although logical constants, variables, and function references represent basic
kinds of logical operands, and are each also logical expressions, B, the programmer
will make much more frequent use of the simple logical expressions described in
the next section.
6-2

6.2 Relational Operators and Simple Logical Expressions


6.2 Relational Operators and Simple Logical Expressions
A simple logical expression, also known as a simple Boolean expression, is of
the form
l .Z. 2
Here, l and 2 are any arithmetic expressions and .Z. is a relational operator,
available in six forms, shown in Table 6.1.
Table 6.1 Relational Operators
Relational
Operator

Algebraic
Equivalent

LT.
GT.
EQ.
LE.
GE.
NE.

<
>
=
<
>

For example, if we have variables X = 2. Y 3.4. I 2. and INT = 7. then


the following expressions will have the indicated values:
Simple Logical Expression

Value

I .EQ. INT
INT/X .GE. Y
X*Y .NE. INT + 1.

.FALSE
.TRUE.
.TRUE.

1 and 2 may be quite complicated, provided that the rules for their for
mation in Section 2.6 are followed. For example, assuming that all the variables
are of integer or real type, the following would be acceptable:
X*Y/BETA + 1.67E-5*SQRT(TAN(THETA)) .LE. ABS(P*q)**3.5
The precedence of all the relational operators is the same, and lower than all of the
arithmetic operators. Thus it is never necessary to enclose 1 or 2 in parentheses,
since the comparison of the numerical values implied by the relational operator will
never be made until both arithmetic expressions have been completely evaluated. If
the final computed values of 1 and 2 are of different type (one real and the other
integer), then the integer expression is converted to the real equivalent, and the
comparison implied by the relational operator is carried out using real arithmetic.
For example, the expression
5*X .GE. 7
6-3

Chapter 6Logical and Conditional Structures


will be evaluated as follows:
1.
2.
3.
4.

The integer 5 will be converted to a real 5.


The expression 5.*X will be evaluated using real arithmetic.
The integer 7 will be converted to a real 7.
The real 7. will be subtracted from the value of 5.*X to determine the
difference. If the difference is greater than or equal to zero, then the simple
logical expression is assigned the value .TRUE. ; otherwise, it is assigned the
value .FALSE.
It is important to note that the following are not the same:
X = Y
X .EQ. Y

The character sequence X Y is an arithmetic assignment statement that makes


the new value of the variable X equal to the current value of the variable Y. However,
X . EQ . Y is a simple logical expression that is true if the current values of X and
Y are equal; the value of X is not modified during the evaluation of the expression.
Most programmers will find that the majority of the logical expressions in
their programs are of the simple type described here.
Exercises for Section 6.2
1. Choosing obvious variables names, write simple logical FORTRAN ex
pressions that are true when:
(a)
(b)
(c)
(d)
(e)
(f)

x is greater than hz + sin p.


|x| > e .
b2 < 4ac.
j is an integral multiple of 5.
i j is an integral multiple of 3.
m(j + k) is an odd integer.

2. In conventional notation, show the meaning that FORTRAN will ascribe


to the following expressions:
(a)
(b)

ABS(P*Q)**3.5 .LE. N*ALOG(6.78) - COS (PHI)


E*1.3E - 4*EXP(E) .EQ. E**E*4./EXP(2.*E)**E

3. Is it true that arithmetic operators have a lower precedence than relational


operators?

6-4

6.S Logical Operators and Compound Logical Expressions


6.3 Logical Operators and Compound Logical Expressions
Compound logical expressions, also known as logical or Boolean expressions,
can be formed from suitable combinations of logical constants, logical variables,
logical function references, simple logical expressions, and logical operators.
Using B, 81, and S2 to denote logical expressions, either simple or com
pound, the FORTRAN logical operators .NOT. . .AND.. .OR.. .EqV. . .NEQV.
are denned in decreasing order of precedence in Table 6.2. All logical operators
have lower precedence than relational operators.
Table 6.2 Definitions of Logical Operators
Logical
Operator

Precedence
Level

.NOT.

Use

Logical negation (a unary operator).

.AND.

The expression Si .AND. B2 has the value


.TRUE. if and only if both Si and S2 are
.TRUE. Otherwise, the expression has the
value .FALSE.

.OR.

The expression Si .OR. S2 has the value


.TRUE. if either Si or S2 (or both) is
.TRUE. Otherwise, the expression has the
value .FALSE.

.EQV.

The expression Bl .EQV. S2 has the value


.TRUE. if Si and Si are both .TRUE. or both
.FALSE. Otherwise, the expression has the
value .FALSE.

.NEQV.

The expression Si .NEQV. 52 has the value


.TRUE. if SI is .TRUE. and S2 is FALSE. or
if SI is .FALSE. and S2 is .TRUE. Otherwise,
the expression is . FALSE .

The action of .AND. . .OR. . and .EQV. can also be seen in Table 6.3 by
the entries in the associated truth tables, in which T and F are abbreviations for
.TRUE. and .FALSE.
A single logical constant, variable, or function reference represents the sim
plest form of a logical expression, S. Using the general notation already estab
lished, the set of eight rules given in Table 6.4 describes the formation of all possible
FORTRAN logical expressions.
One additional rule is that two .NOT. operators cannot be juxtaposed, i.e.,
.NOT. .NOT. A.LT.C is syntactically incorrect. The .NOT. operator is only re
quired infrequently, particularly if its operand is a simple logical expression, since
6-5

Chapter 6Logical and Conditional Structures


the relational operator can be replaced by its complement. For example, A . LT . B
and . NOT . A . GE . B are equivalent logical expressions.
Table 6.S Truth Tables for .AND. . .OR. . and .EqV. Operators

Bl .AND. B2

B2
T

Bl

Bl .or. Bl

B2
T

Bl

Bl .Eqv. B2

B2
T

Bl

These rules and the precedence-ordering of the logical operators are illus
trated by evaluating the logical expression given in Fig. 6.1, shown to have the
value .TRUE. if, for example, X - 9.6. Y - 67.4. and 1-3.
6-6

6.4 Logical Assignment Statement

Table 6.4 Rules for Forming Logical Expressions


Rule
1
2
3
4
5
6
7
8
9
10

X .GT. Y
I
I
.FALSE.

Operand or Operation

Logical Expression Form

Logical constant
Logical variable
Logical function reference
Parentheses
Simple logical expression
(relational operators)
Logical negation, ->
Logical and, A
Logical or, V
Logical equivalence
Logical nonequivalence

. TRUE . . . FALSE .
VB
?8()

.AND.

I .NE. 2
L
J
.TRUE
I .

.OR.

(*)
51 .Z. 2
.NOT. B
Bl .AND. S2
fll .OR. fl2
fll .EQV. fl2
fll .NEQV. fl2

.NOT.

I
.FALSE.

SQRT(Y) . LE . 4.7
I
I
.FALSE.
I
. TRUE
I .

. TRUE .
Fig. 6.1

Evaluation of a Compound Logical Expression.

Because of the precedence-ordering of the relational and logical operators,


the parenthesis rule (4) is required only to assure proper processing of the logical
operators. For example, if the expression in Fig. 6.1 is modified to have the form
shown in Fig. 6.2 and all variables have the same values, the order of expression
evaluation will be different, and the logical value will be .FALSE. rather than
.TRUE.

X .GT. Y
I
.FALSE .

.AND.

(I .NE. 2
I
I
.TRUE.

.OR.

.NOT.

SQRT(Y) . LE . 4.7)
I
I
.FALSE
I
.

L
. TRUE .
_l
. TRUE
I .
L
.FALSE .
Fig. 6.2 Evaluation of a Compound Logical Expression.
(Exercises for this section appear under those for Section 6.4.)
6-7

Chapter 6Logical and Conditional Structures


6.4 Logical Assignment Statement
The logical assignment (or substitution) statement has the form
VS = B
which is similar to the arithmetic assignment statement of Section 2.8, except that
both the expression being evaluated and the variable whose value is being assigned
must be of logical type. For example, noting that A and SWITCH are declared to
be logical variables, while C is a real variable, the following segment contains two
logical assignment statements:
LOGICAL A. SWITCH
C = 6.25
A = SQRT(C) .GE. 4.5
SWITCH = .NOT. A

Example
Consider the circuit shown in Fig. 6.3 with switches SI and S2 connected
in parallel. Let FORTRAN variables Sl. S2. and CIRCUT be declared to be of
logical type, with the truth values of Sl and S2 (true or false) corresponding to
the positions (closed or open) of the two switches, SI and S2, respectively.

cTTcl
B

O b2
c Q_
Fig. 6.S Electrical switches.
Then the following logical assignment statement will assign the value . TRUE . to
the logical variable CIRCUT when either SI or S2 or both are closed, and the value
.FALSE. otherwise:
CIRCUT = Sl .OR. S2
Thus the value of CIRCUT will indicate whether or not there is a closed path from
point A to point B.
Exercises for Sections 6.3 and 6.4
1. Check true or false, as appropriate:
(a)

Logical operators have a higher precedence than relational operators.


6-8

TD

FD

6.4 Logical Assignment Statement


(b)

The operators listed below are given in decreasing


order of precedence:
** , * .

+ . . NOT . , . LT .

(c)

The statement Z P .EQ. Q needs the declaration


LOGICAL P, Q, Z for it to compile properly.

(d)

The following expression is always true:

X .GT. Y .OR. X .NOT.


(e)

.GT. Y

If TOBE is a logical variable, then the following expression is always true:


TOBE .OR.

.NOT. TOBE

2. Choosing obvious variable names, write FORTRAN logical expressions


that are true only when:
(a)
(b)
(c)
(d)
(e)
(f)
(g)
(h)
(i)
(j)

x and y and z are all equal to one another.


x and y and z are all of unequal magnitude.
a is equal to either b or c, but not to both.
z lies between x + 2 and x + 7, inclusive.
falls between j and k, exclusive, assuming that j < k.
i > y > z.
Either a is zero or 6 is positive, or both.
Either a is zero or b is positive, but not both.
Two (but not all three) of the variables x, y, z have equal magnitude.
m and n each lie between 2 and 9, inclusive.

3. Evaluate SWITCH at the end of the following program segment, clearly


showing all intermediate calculations.
LOGICAL SWITCH. Z
Z - .TRUE.
X = 4
Y = 3
SWITCH = .NOT.CX.GE.Y .AND. Z .OR. X-(1 . +Y) . GT. 0. )
4. Giving your reasoning, what are the types and values of the following
expressions if the variables have the values A5.. B"7., C 12., X = 6.,
and SWITCH .TRUE.?
.NOT. A.GT.3. .AND. B.LT.7.
1
.X.EQ.7. .AND. SWITCH

.AND. 3..LT.C .OR.

5. If I - 3. J = 5, K = 2, B 1. , and C = 15. , what is the value of


the following logical expression? Show your work.
I*2.NE.J+K .AND. 3. .LE.B+SQRT(B+C) .OR. J.EQ.I+K
6-9

Chapter 6Logical and Conditional Structures


6. If I 1 and J = 2, evaluate the following expression, showing all your
work:
I*J .EQ. 2 .AND. J .LT. -6 .OR.

.TRUE.

7. Consider the shaded region of the x/y plane shown in Fig. 6.4. If X and
Y are FORTRAN variables whose values are the x and y coordinates of a point in
the plane, write a logical expression that is true if and only if the point (X,Y) lies
inside or on the boundary of the shaded region.

Fig. 6.4

Region and boundary.

8. If Si, $2, and S3 are logical expressions, can here possibly be any differ
ence between the values of the following expressions?
(a)
(b)

Si .AND. S2 .OR. S3
S3 .OR. S2 .AND. Si

9. Write a FORTRAN program segment, including type declarations, that


will assign a value of .TRUE. to a logical variable ANSWER if the point (x,y) is
outside the shaded region shown in Fig. 6.5, and will assign a value of .FALSE. to
ANSWER if (x, y) is inside the shaded region or on its boundary. Assume that X and
Y are real FORTRAN variables that denote x and y, respectively.

2 1/2
y = (4 ,x )

y = (l-x )

Fig. 6.5 Region and Boundary.


10. Fig. 6.6 shows an electrical network with switches numbered 1 through
6. Let the on/off status of each switch be represented by the value of a logical
6-10

6.5 Complete Precedence Table for FORTRAN Operators


variable (51, for the first switch, for example), such that .TRUE. indicates that the
switch is closed (on) and .FALSE. indicates that the switch is open (off). Write a
FORTRAN logical expression that will be true if and only if there is at least one
closed path from point A to point B. Check your expression for several different
switch settings.

Tf^To
Fig. 6.6 Switches in series and parallel.
11. Explain the difference, if any, between the following FORTRAN expressions:
(a)
(b)

X = Y + Z
A.NE.B

and
and

X.EQ.Y + Z
.NOT. A.EQ.B

12. Write a single FORTRAN statement that will assign the value . TRUE. to
the logical variable IMULTJ if I is an integral multiple of J and the value . FALSE .
otherwise.
13. Write a single FORTRAN statement that will assign the value .TRUE.
to the logical variable PYTHAG if X . Y . and Z have values corresponding to the
sides of a right-angled triangle, and the value .FALSE. otherwise.
14. What type statement is essential for the following segment to compile
properly?
J - 3.5
MASS = 17/J
X - MASS*2.5 + 12.5

Y - X .GT. 4.7
After execution of this segment, what are the types and values of J . MASS . X .
and Y?
6.5 Complete Precedence Table for FORTRAN Operators
The FORTRAN operators are listed in Table 6.5 in decreasing order of
precedence. Parentheses appear at the top of the list to indicate their role in
overriding the usual precedence order. The evaluation of functions and subscripts
has also been included to indicate their high priorities.

6-11

Chapter 6Logical and Conditional Structures

Table 6.5 Complete Precedence Table for Operators


Type

Operator

0
Evaluation of function references
and subscripts
Arithmetic

**
*. /
+ . - (binary and unary)

Relational

.LT.. .GT.. .EQ.. .LE..

Logical

.NOT.
.AND.
.OR.
.Eqv.. .NEqv.

Assignment

6.6 The Computed GO TO Statement


The unconditional transfer statement,
GO TO M

has already been discussed in Section 1.4 as a means for causing statements to be
executed out of their normal line-by-line sequence.
In a flow diagram, a box-type symbol is not normally associated with uncon
ditional transfer from one part of the diagram to another; instead, a directed line
is all that appears (see, for example, the flow diagram and programs in Sections
1.2). In some cases, however, particularly when the diagram already has many
blocks, it is more convenient to represent the unconditional transfer, as shown in
Fig. 6.7, with two circles inscribed with the same number; the first circle has an
arrow pointing tra; the second circle has an arrow pointing out. It is understood
that control automatically passes from the first circle to the second one.

*\9f J

0*0"

Fig. 6.7 Unconditional transfer.


The computed GO TO statement
GO TO (J/1. JV2

JVn).
6-12

VI

6.7 The Block IF (IF/THEN/ELSE) Structure


is also available for achieving a multiple branch at any point in the program. Here,
VI is an unsubscripted integer variable that assumes a value from 1 through n, the
number of statement labels involved. For example, if the current value of INT is
2, then
GO TO (1. 7. 4. 10).

INT

will transfer control to the statement numbered 7. Should VI < 1 or VI > n,


control passes automatically to the next statement.
The computed GO TO can be represented in a flow diagram with a circle
containing the integer variable VI, with arrows pointing to several possible branch
points, illustrated in Fig. 6.8.

Fig. 6.8 Conditional transfer.


Exercises for Section 6.6
1. Is it true that if the current value of MSU is 1, the following will transfer
control to the statement that is numbered 3?
GO TO (3. 2. 1). MSU
2. Consider the following two statements:

GO TO (2. 1. 3). I
X = Y - 2.5

For the values of I listed below, indicate, after the GO TO statement has been
executed, the number of the next statement that is executed.
Value of I

Number of next
statement executed

0
1
2
3
4
5
6-13

Chapter 6Logical and Conditional Structures


6.7 The Block IP (IF/THEN/ELSE) Structure
It is frequently necessary to take a certain course of action if a prescribed
condition is metand to take alternative action (including no action) if the con
dition is not met. In such cases, we can use the block IF structure, which will now
be illustrated in a variety of forms of increasing complexity.

Fig. 6.9 Flow diagram for the IF/THEN structure.


In its simplest form, corresponding to the flow diagram of Fig. 6.9, the block
IF structure is:
IF (B)

THEN

One or more statements S to


be executed if B is true. (We
suggest that these statements be
indented for clarity).
END IF
Note that a diamond block is employed in the flow diagram for the IF statement,
and that the terminating small circle corresponds to the END IF (which can also
be written as one word, ENDIF).
Examples:
1. If X is negative, display the values for A . B . and C; otherwise, do nothing:
IF (X .LT. 0.) THEN
WRITE (6.201) A. B. C
END IF

2. If K does not equal KMAX, interchange A and B; otherwise, do nothing.


Note that three statements are required for the interchange:
IF (K .NE. KMAX)

THEN
6-14

6.7 The Block IF (IF/THEN/ELSE) Structure


SAVEA
A
A = B
B = SAVEA
END IF

Fig. 6.10 Flow diagram for the IF/THEN/ELSE structure.


If there are two alternative statement sequences, only one of which is to be
executed (depending on the value of B), the corresponding block IF structure, also
shown in Fig. 6.10, is:
IF (S)

THEN

One or more statements 51, to


be executed if B is true.
ELSE
One or more statements 52, to
be executed if B is false.
END IF
Example
If N is not an integral multiple of J, increment J by one; otherwise, transfer
to the statement numbered 50. Note that in this example, the two branches of the
structure do not recombine:
IF (N/J*J .NE. N)
J - J + 1
ELSE
GO TO 50
END IF

THEN

6-15

Chapter 6Logical and Conditional Structures


In its most general form, the block IF structure is:
IF (Sl)

THEN

Statements to be executed
if Si is true.
ELSE IF (S2)

THEN

Statements to be executed if
Si is false and S2 is true.
ELSE IF (S3)

THEN

Statements to be executed if Si
and S2 are false and S3 is true.
ELSE IF (S)

THEN

ELSE
Statements to be executed if none of the
previous logical expressions is true.
END IF

Any number of ELSE IF (B) THEN sub-blocks may appear, and the ELSE
sub-block need not be present. Statements in at most one of the sub-blocks will
be executed; (if no ELSE sub-block appears, then it is possible that no statements
in the block IF will be executed).
Thus, the following statements correspond to the flow diagram of Fig. 6.11:

IF (Bl) THEN
Sl
ELSE IF (S2) THEN
$2
ELSE
53
END IF
6-16

6.7 The Block IF (IF/THEN/ELSE) Structure

Fig. 6.11

Flow diagram for the IF/THEN/ELSEIF/ELSE structure.

One block IF can be nested in another block IF, provided that the nested
block IF is entirely inside one of the sub-blocks of the nesting block IF, e.g.,
LOGICAL SWITCH
IF (X.LT.Y .AND. SQRT(P + ABS(Q)) .GE. 1 .E6)
A - B - C
IF (DELTA .LE. BETA) THEN
X - SIN (BETA)
Y = COS (DELTA)
ELSE
X - SIN (DELTA)
Y - COS (BETA)
END IF
GAMMA = BETA + DELTA
ELSE IF (SWITCH)
P ' X + Y
ETA - X - Y
ELSE
Q = R*S/GAMMA
END IF

THEN

Another, comprehensive, use of the block IF appears in Example Program 6.1 in


Section 6.9.
Exercises for Section 6.7
1. Write FORTRAN statements that correspond to the flow diagram shown
in Fig. 6.12. State briefly what it accomplishes.
6-17

Chapter 6Logical and Conditional Structures

Fig. 6.12

Conditional structure

2. Consider the following complete FORTRAN program:


1

P = 5.

Q = 6.
R = 7.

3
4
5

S = 8.
IF (S .GT. P)
IF (P + Q

6
7

S = 0.
END IF

8
9
10

ELSE
GO TO 13

11

END IF

12

GO TO 5

13

STOP
END

Complete the following sequence of statement execution:


1-2-3-4-

3. The value of F varies with x as shown in Fig. 6.13. Write corresponding


FORTRAN statements that will compute the appropriate value of F, depending
on the current value of X.
6-18

6.7 The Block IF (IF/THEN/ELSE) Structure

Fig. 6. IS

Variation of F with x.

4. Write FORTRAN statements that correspond to the flow diagram shown


in Fig. 6.14.

Fig. 6.14 Flow diagram for Exercise 4.


5. How can you check to see if two non-zero variables have the same sign
(that is, both are positive or both are negative)? Write FORTRAN statements
that will store X in XR if the variables FX and FXR have the same sign, but that will
store X in XL if they do not have the same sign.
6. Write FORTRAN statements that will insert a double space after the
previous output line and print the message "LEAP YEAR" (starting in column 5) if
NDAYS equals 366, but that will do nothing otherwise.
7. Write FORTRAN statements corresponding to the flow diagram of Fig.
6.15. Assuming that N is not negative, what does the sequence of calculations
achieve? (Hint: follow the diagram and compute the final value of M for N 0.
1. 2 . 3 . and 4 in sequence.)

j..1..l

T
1r
N^

Fig. 6.15 Flow diagram for Exercise 7.

6-19

M = Mxl

Chapter 6Logical and Conditional Structures


8. Write a program that reads (using formatted or list-directed input) and
processes several data lines, each line containing values for three logical variables:
LOG1, OPER. and LOG2. [Note that formatted logical values are read using an "L"
format code. For example, the code L5 indicates that either a T (true) or F (false)
can be expected within a 5-column field.]
If OPER is . TRUE . , the value of the following expressions is to be computed
and printed:
LOG1 .AND.

.NOT. LOG2

However, if OPER is .FALSE. , the value of the following expression is to be computed


and printed:
.NOT. LOG1 .OR. LOG2
Write a program that will achieve this. Also show the appearance of the data lines
and corresponding output for the following two sets of data:

First set:
Second set:

LOG1

OPER

LOG2

F
T

T
F

F
F

9. The value of f(x) varies with x as shown in Fig. 6.16. Given a value for
X, write FORTRAN statements that will compute the corresponding value of the
function F.
f (x)

Constant
Value
Constant
Value
Fig. 6.16

The function f(x).

6.8 Other Conditional Statements (Logical and Arithmetic IF Statements)


The block IF structure of the previous section has largely superseded two
earlier FORTRAN conditional statementsthe logical and arithmetic IF state
ments. However, these still remain in the language and are occasionally useful.
The logical IF statement has the form
IF (B) S
6-20

6.8 Other Conditional Statements (Logical and Arithmetic IF Statements)


where B is a Boolean expression, and S is now any one executable statement,
except another IF. ELSEIF. ELSE. ENDIF. END. or DO statement (see Section
7.3). The following action, also illustrated in Fig. 6.17, is taken:
1. B is evaluated.
2. IF B is true, S is performed. Control then passes to the next executable
statement after the logical IF statement (if S does not transfer to some other
part of the program) .
3. If B is false, no action is taken, and control then passes to the next executable
statement following the logical IF statement.

Fig. 6.17

The logical IF statement.

Examples
1. If X is negative, display the values for A. B. and C:
IF (X .LT. 0.)

WRITE (6.204) A. B. C

2. If T exceeds TMAX or the logical variable PRINT is false, transfer to the


statement numbered 50:
IF (T.GT.TMAX .OR. .NOT. PRINT)

GO TO 50

Observe that in these two examples, the constructions are shorter than those with
the corresponding block IF.
3. If K does not equal KMAX . interchange A and B; otherwise, do nothing.
Since the interchange takes three statements, and the logical IF statement can
only accommodate a single statement S , there is now a problem. The solution is
that S must be an unconditional transfer, and the following segment will achieve
the desired result:
IF (K .NE. KMAX) GO TO 5
GO TO 10
6-21

Chapter 6Logical and Conditional Structures


5

10

SAVEA = A
A - B
B - SAVEA
(Next statement)

Observe that two GO TO statements are needed in this particular instance. The
construction is simplified if instead the complementary logical expression is inves
tigated:
IF (K .EQ. KMAX) GO TO 10
SAVEA A
A = B
B = SAVEA
10 (Next statement)

The logical IF statement is convenient if only a single statement is to be executed


if B is true; in more complex situations, the block IF structure is much preferred
because of its clarity. The block IF is essential for the writing of structured pro
grams.
A transfer to one of three possible statements can also be achieved by the
conditional transfer or arithmetic IF statement:
IF ()

Ml. Ml. M3

According to whether the value of the arithmetic expression is negative, zero,


or positive, control is transferred to the statement numbered Ml, M2, or MS,
respectively. If a two-way branch were desired, then two of the three statement
numbers would be identical. The arithmetic IF statement was the only conditional
statement in the early FORTRAN languages.
Example
If A and BETA have values of 2.6 and 54.9, respectively, then
IF (A - BETA)

5. 10. 15

causes a transfer to the statement numbered 5 because the value of A - BETA is


negative.
Exercises for Section 6.8
1. Check true or false, as appropriate:
(a)

If the value of EMU is -75, then the statement


IF (EMU)

10. 20. 30

will cause the program to transfer to the statement


numbered 30.
6-22

6.8 Other Conditional Statements (Logical and Arithmetic IF Statements)


(b)

The following is a syntactically correct logical IF


statement:
IF (Z - 37.)

(c)

F D

GO TO 91

If SWITCH and X are logical variables, then the following is a valid logical IF statement:
IF (X .AND. NOT. SWITCH)

(d)

T D

GO TO 100

If X = 2. and Y = -3., the statement


IF (Y - X + 6.)

50. 50. 60

will transfer control to the statement numbered 50.


(e)

The following is a legal FORTRAN statement:


IF Y < X AND Z = 3 THEN Z = 3

2. Write FORTRAN statements that will increment by one the value of


INEG. IZER. or IPOS. according to whether the value of X is negative, zero, or
positive, respectively.
3. In the following FORTRAN program, give the values of ITER. SUM. and
PROD each time statement 5 is executed.

SUM - 0.
PROD - 1.
ITMAX - 6.
ITER 0
ITER = ITER + 1
IF (PROD .GT. 6.) SUM = SUM + ITER
IF (SUM .LT. ITER) PROD = PR0D*ITER
IF (ITER .LT. ITMAX) GO TO 1
STOP
END

4. After execution of each of the following, what is the number of the


statement to which transfer occurs? Assume that 1 = 3. J = 6. and K = 7.
(a)
(b)
(c)

IF (J - K) 3. 2. 1
IF (J - 2*1) 5. 5. 10
IF (IABS(K)) 1. 2. 3

6-23

Chapter 6Logical and Conditional Structures


6.9 Example Program 6.1Roots of a Quadratic Equation
Finally, we write a FORTRAN program that reads values for a, b, and c,
and proceeds to find the roots of the quadratic equation
ax2 + bx + c = 0.
There are three alternative solutions to be considered, shown in Fig. 6.18.

xl
V =
X2
'One root,'
x

-h + \ri
2a
-b - Vd
2a

' Imaginary
roots '

I
X1 ' X2

Fig. 6.18 Flow diagram for quadratic equation program.


1. One root. When a = 0, the solution is simply x c/b. In the program,
any a smaller than than 10~10 in magnitude is to be taken effectively zero
(the program assumes that b will not be zero at the same time).
2. Two real roots. When 62 4ac is not negative, the quadratic equation has
two real roots:
6-24

6.9 Example Program 6.1 Roots of a Quadratic Equation

11 = ,^-(-b + y/b2 -4ac),

12 = 7T"
2a (
v & y/b2 - 4ac)7 .
3. Imaginary roots. When b2 4ac < 0, the equation has two complex conjugate
roots. The program indicates that the roots are imaginary, but does not
calculate them.
List of Variables
Program Symbol

Definition

A
B
C
DISCR
SQRTD
z
Xl. X2

Coefficient, a.
Coefficient, 6.
Coefficient, c.
d = b2 - 4ac.
Square root of DISCR.
Root for the one-root case, x.
Roots for the two- root case, ii,x2.

Program
PROGRAM QUAD
C

Roots of quadratic equation.

Input coefficients, compute discriminant ....


OPEN (5. FILE-' QUAD. DAT')
READ (5.101.END=999) A. B. C
DISCR = B*B - 4.*A*C
WRITE (6.201) A, B. C, DISCR

C
C

Choose appropriate alternative using BLOCK IF


IF (ABS(A) .LT. l.E-10) THEN
A is essentially zero; compute and print one root
X = - C/B
WRITE (6.202) X
ELSE IF (DISCR .GE. 0.)

THEN

Compute and print two roots


SQRTD - SQRT (DISCR)
6-25

Chapter 6Logical and Conditional Structures


Xl - (-B + SQRTD)/(2.*A)
X2 (-B - SQRTD)/(2.*A)
WRITE (6.203)

Xl. X2

ELSE
C

Reject case of imaginary roots


WRITE (6.204)
END IF

Return for more data


GO TO 1

Terminate if no more data


999

STOP

Formats for input and output statements


FORMAT (3F10.3)
FORMAT ("2Roots of quadratic equation, with'/
1
'0A
- '. F10.3/ ' B
= '. F10.3/
2
' C
" ' , F10.3/ ' DISCR F10.3)
202 FORMAT ( 'OCoef f icient A is near zero - one root only'/
1
'0X
= ' , F10.5)
203 FORMAT ('0X1
= '. F10.5/ ' X2
= '. F10.5)
204 FORMAT ( '0Discriminant negative - roots imaginary")
101
201

END
Data
1.
1.
4.46
0.0

1.
-5.
2.957
2.957

-6.
6.25
0.901
0.901

Output (Some blank lines have been removed)


Roots of quadratic equation, with
A
=
1.000
B
=
1.000
C
=
-6.000
DISCR =
25.000
Xl

2.00000
6-26

6.9 Example Program 6.1 Roots of a Quadratic Equation


X2

-3.00000

Roots of quadratic equation, with


A
B
C
DISCR

=
=
=
-

1.000
-5.000
6.250
.000

Xl
X2

=
=

2.50000
2 . 50000

Roots of quadratic equation, with


A
B
C
DISCR

4.460
2.957
.901
-7.330

Discriminant negative - roots imaginary

Roots of quadratic equation, with


A
B
C
DISCR

=
=
=

.000
2.957
.901
8.744

Coefficient A is near zero - one root only


X

- . 30470

Discussion of Results
The four data sets have yielded, respectively, two different real roots, two
identical real roots, imaginary roots, and one real root. All possible paths through
the program have been tested. With the exception of a data set for which both a
and 6 have zero values (an inconsistent case for which we could have tested), the
program should be able to handle any arbitrary combination of real values for a,
b, and c.

6-27

Chapter 6Logical and Conditional Structures


Notes

6-28

CHAPTER 7
SUBSCRIPTED VARIABLES AND ITERATION

7.1 Introduction
Frequently, we wish to use a single variable name for several related variable
values. Normally, the individual values are differentiated by attaching a subscript
to the variable name. For example, we might describe the weight of objects num
bered 1, 2, 3, and 4 as Wi, u>2> u>3, and wt. The FORTRAN variables introduced
in Section 2.4 are called simple or scalar variables. Each variable name is assigned
to a single memory location, and may have just one value associated with it at a
time. Fortunately, FORTRAN also allows a second kind of a variable, called an
array variable or subscripted variable that is assigned a sequence of memory loca
tions, one for each of the several values associated with the name. The number of
locations depends on information in a DIMENSION declaration, to be introduced in
Section 7.2.
Individual elements of an array are differentiated from one another by en
closing their subscripts in parentheses, immediately following the array name. For
example, for the four-element singly subscripted array or vector W, the individual
elements would be written as: W(l) . W(2) . W(3) . and W(4).
The naming rules and types for subscripted variables are the same as for
simple variables, that is, the name must consist of from 1-6 alphanumeric char
acters, with a letter as the first character. The type of all elements of an array
is determined by the type of its name, and is assigned using the implicit naming
convention (if the first letter is I. J. K. L. M. or N, the variable is of integer
type, etc.), or by using an explicit type declaration (INTEGER. REAL. LOGICAL.
or CHARACTERsee Section 9.3). Each subscript must be an integer arithmetic
expression EI . (Some compilers allow real expressions as subscripts, which are
then truncated to the next lower integer if they involve fractional parts, but we
suggest that subscript expressions always be true integers).
Examples
X(222)

BETA(J - 1)

DELTA(K(J) - L)

Note that the subscript expression may involve other subscripted variables, as in
the last example above.
7-1

Chapter 7Subscripted Variables and Iteration


Arrays may have more than one dimension, that is, involve more than one
subscript. The maximum number of subscripts allowed depends on the particular
compiler, and is typically between three and seven. The individual subscripts are
separated by commas.
Examples
A(I,J)

TABLE(3.9)

SALES ( ITEM. NSTORE.NWARE)

Here, A(I , J) is the element in the Ith row and the Jth column of a two-dimensional
array (or table or matrix) named A. depicted generally in Fig. 7.1. The last of
these examples above is an element of the three-dimensional array named SALES.
In an acccounting program, SALES (ITEM, NSTORE.NWARE) might represent the total
dollar sales of merchandise with product number ITEM to the store number NSTORE
from the warehouse numbered NWARE.
Column J

Row I

ACM)
A(2,l)

A(l,2)
A(2,2)

A(l, J)
A(2, J)

A(1,N)
A(2,N)

A(I,1)

A(I,2)

A(I, J)

A(I,N)

A(M,1)

A(M,2)

A(M, J)

A(M.N)

Fig. 7.1 General appearance of a matrix


A with M rows and N columns.
7.2 Storage of Arrays and the DIMENSION Declaration
In subset FORTRAN, the minimum value allowed for a subscript is one;
unfortunately, zero and negative subscripts, sometimes encountered in mathemat
ical notation, are not allowed. The maximum value of a subscript for an array in
FORTRAN is determined in a DIMENSION declaration of the form
DIMENSION V (Jl, 72

In)

where V is the array name, and Jl, 12, . . ., Jn are unsigned integer constants
equal to the largest subscript values likely to be used for each of the n subscripts.
For one-dimensional arrays, 12, . . ., Jn would be deleted. The smallest subscript
values are always assumed to be unity, but it is not essential to make complete use
of all the storage space thus assigned. More than one array may be "dimensioned"
in a single DIMENSION declaration. For example,
DIMENSION A(5.10). STRESS(15)
7-2

7.2 Storage of Arrays and the DIMENSION Declaration


would reserve 50 memory locations for the elements A (1.1) through A (5. 10) and
15 locations for the elements STRESS(l) through STRESS (15). The DIMENSION
declaration for an array must precede the first mention of the array name in the
program.

Y(l,l)

Yd,D

Y(1, 2)

Yd, 3)

Y(2,l)

Y(2,l)

Y(2,2)

Y(2,3)

Yd, 2)

(a)

Y(2,2)

Yd, 3)

Y(2,3)

(b)

Fig. 7.2
(a) Conventional arrangement of a two-dimensional array (matrix),
(b) Storage sequence of array elements in computer memory.
Since the internal addressing structure is one-dimensional in the computer
memory, arrays having more than one subscript are automatically reorganized into
an equivalent one-dimensional sequence for internal bookkeeping purposes. The
convention adopted by the FORTRAN compiler is to let the array element with
all subscripts equal to one to be the first element stored in the set of contiguous
memory locations assigned to the array. Thereafter, each subscript in turn is
varied from its minimum to maximum value, starting with the first subscript, then
the second subscript etc. Note that this scheme leads to the storage of matrices
in column-by- column rather than the more conventional row-by-row order, and is
illustrated for a 2 x 3 array named Y in Fig. 7.2.
Thus, the 2 x 3 x 2 array B would be saved in the order B(l.l.l). B(2.1.l);
BCl.2.1). B(2.2.l); B(1.3.1). B(2.3.l); B(1.1.2). B(2.1.2); B(1.2.2).
B(2.2.2); BU.3.2). andB(2.3.2).

Exercises for Section 7.2


1. Name four ways in which a FORTRAN compiler could interpret paren
theses in a program.
7-3

Chapter 7Subscripted Variables and Iteration


2. Assuming that the arrays STRESS, and V have been dimensioned properly,
which of the following, if any, would be unacceptable to the FORTRAN compiler?
State why.
(a) STRESS (999)

(b) V(0, 2, J)

3. Write a FORTRAN statement that is equivalent to:

y = y< + (x - Xi)

y<+i - y,
Xi+l - Xi

4. Is it true that the declaration DIMENSION A(100.100) reserves 40,000


bytes of memory?
5. Which, if any, of the following must appear at least once in every FOR
TRAN program?
(a) A DIMENSION statement.
(b) A WRITE statement.
(c) An END statement.

(d) A STOP statement.


(e) A FORMAT statement.
(f) A READ statement.

7.3 Iteration: The DO and CONTINUE Statements


Algorithms frequently contain one or more segments that are to be processed
repeatedly a certain number of times. Such a procedure is called iteration. The
sequence of FORTRAN statements used to implement the repeated processing is
called a loop. There is normally some variable, called the iteration variable, index,
or counter, that assumes a different value on each pass through the loop (that is,
each time the sequence is processed or executed). Iteration loops could be handled,
if necessary, by using only the substitution, conditional, and transfer statements.
For example, the mean x of n numbers Zi, x2, . . . ,xn could be computed as
shown in Fig. 7.3, using the formula
1
1 n
x = -{xi + x2 + ...xn) = - Y]xi.

Fortran Statements

10

20

Action

S = 0.
1=1
IF (I .GT. N) GO TO 20
S = S + X(I)
1=1+1
GO TO 10
XBAR = S/N

Fig. 7.S

Initialization
Testing
Incrementing
Transferring

Computing the mean of the elements of a vector.


7-4

7.S Iteration: The DO and CONTINUE Statements


Note that the second, third, and fifth FORTRAN statements are concerned
with initializing, testing (against an upper limit), and incrementing the iteration
variable or index I; the sixth statement transfers back to an earlier statement in
the loop.

VJ = Dl

Initialize

Test

Blocks to
be executed
repeatedly

Blocks to
be executed
repeatedly

VJ = VJ + J3
Increment

Next statement
after blocks to be
executed repeatedly
Fig. 7.4a
Conventional Block Structure.

Fig. 7.4b
Hexagonal Block Structure.

This kind of iteration sequence occurs so often that a special iteration state
ment, called the DO statement, is part of FORTRAN. Essentially, the four oper
ations of initializing, testing, incrementing, and transferring are condensed into a
simple structure having the general form
DO M

VI = II. 12. 73

(One or more statements, forming the


range or scope of the iteration)

Because there are some restrictions on the last statement in the range of the
iteration, a generally more acceptable and therefore satisfactory version, which we
shall use in this text, is:
7-5

Chapter 7Subscripted Variables and Iteration


DO JV

VI - II. 12. 13

(One or more statements, forming the


range or scope of the iteration)
M

CONTINUE

The CONTINUE statement, which is acceptable in all instances, merely serves


as a "landing pad" at the end of the loop, and causes no other action to be taken.
In the above, 71, 72, and 73 are integer expressions. For the moment,
assume that 73 is positive. The following actions, also illustrated in Fig. 7.4a, then
occur:
1. The unsubscripted integer variable index "VI is first set equal to 71.
2. If this value exceeds 72, the range of the loop is bypassed, and control is
automatically transferred to the statement immediately following the one
numbered M .
3. If "VI does not exceed 72, the subsequent statements, up to and including
the statement numbered M (the range of the iteration), are executed.
4. VI is then incremented by 73, and the sequence of operations described in
steps 2 and 3 above is repeated. Eventually control will be passed in step 2
to the statement immediately following the one numbered M .
If 73 is negative, VI is initially set to 71 as in step 1 above. Should 71
be smaller than 72, the range of the loop is bypassed. Otherwise, the looping
operation continues as above, except that "VI is decremented until its final value
falls below the lower limit 72.
If the increment 73 is unity, it may be omitted:
DO H VI - 71. 72
To represent the above more concisely, we shall use a hexagonal block, shown
in Fig. 7.4b, as the flow-diagram symbol for iteration. The iteration variable, and
its indicated sequence of values are inscribed inside the box. Following the blocks
containing the part of the algorithm that is to be repeated, there appears a small
circle. A dashed line pointing from the circle back to the hexagon shows the part
of the diagram involved in the iterative calculations.
The use of the hexagonal flow-diagram block for iteration and the corre
sponding DO statement is illustrated in Fig. 7.5, which finds the mean of numbers
Xl through xn.
Note that since the increment 73 does not appear in the DO statement, it
is assumed to be equal to one; that the statement with statement number 10 is
the last statement to be executed inside the loop; and that no transfer statements
appear explicitly in the FORTRAN program segment. (The transfers do occur, of
course; they are caused automatically by the DO statement.)
7-6

7.S Iteration: The DO and CONTINUE Statements


There are some additional operating peculiarities and programming restric
tions that must be observed when using the DO statement:
1. A one-way transfer can be made completely out of a DO loop, but this must
not lead to the DO statement itself.
2. If a one-way transfer is made out of the DO loop, the index "VI will have the
value it had at the time of the transfer, and may be used as an ordinary
integer variable. If the natural exit (when the index is sequenced through
all specified values) is taken, the value of the index VI is not necessarily the
value that it had on the last pass through the loop; the programmer should
assume that the value of VI is unknown.

i
S = 0

<g>-

FORTRAN Statements

10

S = 0
DO 10 I = 1, N
S = S + X(I)
CONTINUE

S - S + x

XBAR = S/N

X = S/n

T
Fig. 7.5 Program segment with flow diagram.
The index VI or any of the associated indexing parameters (II, 12, 73) must
not be modified during the execution of the range; they may be changed
outside the range.
The last statement in the range (the statement with the label JJ) must be ex
ecutable and must not involve a GO TO. STOP. RETURN. DO . arithmetic IF .
or block IF. ELSE IF. ELSE. END IF. END. or a logical IF statement con
taining any of these statement types. To avoid the necessity of remembering
such conflicts, we recommend that every loop terminate with a CONTINUE
statement.
DO statements may appear within the ranges of other DO statements. How
ever, the ranges of the DO statements must not overlap; that is, all of the
statements in the ranges of an inner DO statement must be within the range
7-7

Chapter 7Subscripted Variables and Iteration


of an outer DO statement. The DO loops are then said to be nested. Examples
of valid and invalid nestings are:
Valid
DO 10 I-l.M
DO 5 J-1.N

5
CONTINUE
10 CONTINUE

Valid
DO 10 I-l.M
DO 10 J-l.H

10 CONTINUE

Invalid
DO 10 1=1. M
DO 5 J-l.N

10 CONTINUE
5
CONTINUE

Note that more than one DO loop may end with the same statement, as
occurs, for example, when no more calculations are required inside the outer
DO loop after the inner DO loop is completed. The iteration variables are
initialized and incremented and tested in the usual way, however. In the
second example above, I would be set to 1, J would take on successively
all the values from 1 to N, then I would be incremented to 2, and J would
take on all the values from 1 to N again, etc. However, for program clarity,
we recommend that each DO loop be terminated with its own CONTINUE
statement, and that statements inside a loop be indented as shown in the
examples in the next section.
6. A one-way transfer must not be made into the range of a DO loop from
outside that loop. In the only exception to this rule, FORTRAN allows a
transfer out of the range of the innermost DO loop, and then a subsequent
transfer back into the range of that DO, provided that none of the iteration
parameters VI, II, 12, and 13 is modified outside the range.
Exercises for Section 7.3
1. Check true, or false, as appropriate:
(a)
(b)

A DO loop may always terminate with a CONTINUE


statement.
After execution of the following sequence, J will have
the value 19:
J - 50
DO 50 I - 10. 20. 3
J = I
50 CONTINUE

T D

(c)

In a DO loop, the iteration index must appear as the


subscript of an array.

T D

F D

(d)

No more than ten statements can be used in the range


of a DO loop.

T D

F D

7-8

7.S Iteration: The DO and CONTINUE Statements


(e)

A DO loop is always performed at least once, even if


the initial value of the index exceeds its upper limit,
as in:

T D

F D

T D

F D

T D

F D

DO 30 K = 20. 15
(f)

In a DO loop, the index can be decremented, but only


in steps of one (for example,
DO 40
DO 40

(g)

M = 10. 2. -1
M = 10. 2. -2

is legal, whereas
is illegal).

The variable X can be used as the index in a DO loop


provided it is declared to be of integer type.

2. Which, if any, of the following would be unacceptable statements in


FORTRAN? Explain.
(a)
(b)
(c)

IF
DO
DO
8 IF

(A
99
8
(I

.NE. B) DO 5 I - 1 . 10
J = 0. 100
I - 1. 16
.EQ. J) A = B

3. Indicate the errors, if any, that would be unacceptable to the FORTRAN


translator in the following iteration statements:

(a) DO 67.5 I = 1. 2. 3
(b) DO N INT = 3. 2. 1

(c) DO 11 J(I) = -4. 17


(d) DO 11 COUNT 1. N+l

4. After execution of the following, what will be the value of INT in each
case?
(a)

INT = 10
DO 20 L - 1.6
INT L
20

(b)

(c)

CONTINUE

20

INT = 10
DO 20 L = 1. 6. 2
INT = L
20

INT = 10
DO 20 L = 6.1
INT - L

(d)

CONTINUE

CONTINUE
INT = 10
DO 20 L - 6. 1. -2
INT = L

20

CONTINUE

5. Giving your reasons, point out any syntactical errors in the following
sequence:

50

DO 50 K = 1
. N+l
IF (V(K) .GT. 2.5) K = 4
IF (V(K) .EQ. 10.) GO TO 60
7-9

Chapter 7Subscripted Variables and Iteration


6. Write the FORTRAN statements to reserve storage for the subscripted
variables in the following sequences, where the value of N is 100 or less:
(a)
DO 40 I - 1. N
C(I) = A(I)*B(I)**2
40 CONTINUE
(b)
50

DO 50 J - 2. N. 2
C(2*J+2) - J
CONTINUE

60

DO 60 M - 1. 2*N+1. 3
ALPHA(M+1) - BETA(4*N - M)
CONTINUE

(c)

7.4 Several Examples Involving Iteration


Example Program 7.1Table of Functions
The following program employs a WRITE statement within a DO loop to print
successive lines of a table of three functions of a variable X, which is incremented
in steps of DX between an initial value XLOW and a final value XHIGH. An integer
index I is used in the DO loop and is translated into the corresponding value of X
by a simple formula.
Some caution is needed. For example, if XLOW 0. . XHIGH 10. . and DX
0. 1, we would expect the number of lines in the table to be (10. 0.)/0.1 + 1,
presumably 101. However, since 0.1 cannot be represented exactly in a binary
computer, the number of entries might be computed (for example) as 100.9999.
Since this value is truncated to the next lower integer, the addition of an extra 0.5
before truncation will always lead to the correct number of entries being computed.
Observe that subscripted variables are not involved.
Program
PROGRAM TABLE
C
C

Illustration of iteration loop to generate


table of mathematical functions.

C
C
C

Define 5 and 7. (Unit 6 is defined during


execution time. first as CON when testing.
and then as LPT1 for the final copy)
OPEN (5. FILE- 'CON')
OPEN (7. FILE-'CON')

Print heading
7-10

7.4 Several Examples Involving Iteration


WRITE (6,201)
C

Read data, find number of table entries


WRITE (7,202)
READ (5.*) XLOW. XHIGH. DX
NTABLE - (XHIGH - XLOW)/DX +1.5

C
DO 10

X - XLOW + (I - 1)*DX
WRITE (6.203) X. X**2, SQRT(X) , SIN(X)
CONTINUE
STOP

10

C
201

Compute and print table entries


I 1, NTABLE

Formats for output statements


FORMAT ('1
Table of Mathematical Functions'/ ,0'.
1 7X, 'X'. BX. XSQUARE'. 3X. 'SQRT(X) ' , 4X, "SIN(X)'/)

202
203

FORMAT (' Enter values for XLOW. XHIGH. and DX:")


FORMAT (' ' . 4F10.4)
END

Data
Values of XLOW -6.0, XHIGH - 10.0. and DX - 0.5 were entered from
the keyboard when the program was run.
Output
Table of Mathematical Functions
X
5.0000
5.5000
6.0000
6 . 5000
7.0000
7.5000
8.0000
8.5000
9.0000
9.5000
10.0000

XSQUARE

SQRT(X)

SIN(X)

25.0000
30.2500
36.0000
42.2500
49 . 0000
56 . 2500
64.0000
72 . 2500
81.0000
90.2500
100.0000

2.2361
2 . 3452
2 . 4495
2 . 5495
2.6458
2 . 7386
2 . 8284
2.9155
3.0000
3.0822
3.1623

-.9589
-.7055
-.2794
.2151
.6570
.9380
.9894
.7985
.4121
-.0752
-.5440

7-11

Chapter 7Subscripted Variables and Iteration


Short Examples
1. Compute NFACT, the value of N! [that is, lx x 2 x (N - 1) x N],
assuming that N is one or greater.
NFACT = 1
DO 5 I = 1. N
5

or

NFACT - NFACT*I
CONTINUE

NFACT = 1
DO 5 I = N. 1. -1
NFACT = NFACT* I
CONTINUE

Note that when repeated multiplication is involved, the variable NFACT must be
initialized to 1 before the loop calculations are done, and that the value of the
iteration variable I may be used in calculations inside the loop, as long as it is not
changed (for example, a statement such as I I + 1 inside the DO loop would not
be allowed). In the first example, N! is found by computing Ix2x3x4x,.. x(N2)x(N l)xN, whereas in the second loop the calculations are implemented in the
reverse order, Nx(N-l)x(N-2)x x 2 x 1.
2. Compute NUMBER, the number of elements in the vector K containing N
elements K(l). K(2) . ..., K(N) that have even subscripts and are also even in
value:

30

NUMBER = 0
DO 30 INT - 2. N. 2
IF (K(INT)/2*2 .EQ. K(INT))
CONTINUE

NUMBER = NUMBER + 1

This program segment initializes NUMBER with a zero; it then examines K(INT),
where INT starts with 2 and is incremented by 2 . so that only even-subscripted
elements are tested. The logical expression in the IF statement takes advantage
of the truncation of fractional parts resulting from integer division. Should N be
an odd number, then the last element of K to be examined will be K(N - 1).
3. Assume that an array SALE contains sales figures for sales from company
warehouses to customers. Let SALE(I.J) be the total sales from warehouse I
to customer J during a particular month, illustrated for specific values of M = 4
customers and N 3 warehouses in Table 7.1.
Table 7.1 Sales from Warehouse I to Customer J

Warehouse I

1
2
3

Customer J
12
3
4
10
2
6 15
4
0
9
1
12
7
4 20
Total
7-12

WARE(I)
33
14
43
90

7.4 Several Examples Involving Iteration


Now compute elements of a vector WARE such that WARE (I) contains the total sales
from the Ith warehouse to all customers. Also compute TOTAL, the total sales from
all N warehouses to all M customers. An appropriate program segment is:

40
50

TOTAL * 0.
DO 50 I = 1. N
WARE(I) - 0.0
DO 40 J = 1. M
WARE(I) = WARE(I) + SALE(I.J)
CONTINUE
TOTAL = TOTAL + WARE (I)
CONTINUE

4. Compute the product P of all elements above the main diagonal of the
NxN square matrix A, as shown in Fig. 7.6.

P = 1

kiFig. 7.6

P = P x a

Flow diagram for Example 4.

Appropriate program segments are:

P - 1.
DOB 1=1.N-1
DO 5 J = 1+1. N
P = P*A(I.J)
CONTINUE

5
10

P - 1.
DO 10 I = 1. N-l
DO 5 J - 1+1. N
P = P*A(I.J)
CONTINUE
CONTINUE

Note in the first example that two loops terminate with the same statement; this
does not interfere with normal sequencing of the iteration variables. However,
in the interest of clarity, we recommend that each loop terminate with its own
CONTINUE statement, as in the second example.
Example Program 7.2Array Manipulation

1.
2.
3.
4.

Here, we find the following properties of the N-element vector X:


Its smallest element, LOW.
Its largest element, HIGH.
The total of all the elements, SUM.
The mean, XBAR, of all the elements.
7-13

Chapter 7Subscripted Variables and Iteration


Array-segment notation, discussed in Chapter 8, is used for reading and
printing X(1) , . . ., X(N). The variables LOW (and HIGH) are initially equated to
X(1), and are updated if any smaller (or larger) elements are found as the DO loop
is used to examine all elements. The program can process more than one set of
data.
Program
PROGRAM ARRAY
C

Illustration of DO loop for array manipulation.

Declarations
REAL LOW
DIMENSION X(100)
OPEN (5, FILE=' ARRAY. DAT')

C
1

C
C

10
C

Read and print N and the vector X


READ (B.101,END=999) N, (X(I) , I - 1, H)
WRITE (6,201) N, (X(I), I - 1. N)
Compute sum S of all elements, also find the
smallest and largest elements LOW and HIGH .
SUM - 0.
LOW = X(1)
HIGH - X(1)
DO 10 I = 1. N
SUM - SUM + X(I)
IF (X(I) .LT. LOW) THEN
LOW = X(I)
ELSE IF (X(I) .GT. HIGH) THEN
HIGH = X(I)
END IF
CONTINUE

999

Compute mean XBAR. print results, stop


XBAR - SUM/N
WRITE (6,202) SUM. XBAR. LOW, HIGH
GO TO 1
STOP

101
201

Formats for input and output statements


FORMAT (15/ (5F10.2))
FORMAT ClThe'. 13. ' elements of the vector X are:'//

7-14

7.4 Several Examples Involving Iteration


1 (' '. 4F10.2))
202 FORMAT COSUM
1
' LOW

-'. F10.2/
'. FlO. 2)

-'. F10.2/ ' XBAR


-'. F10.2/ ' HIGH

END
Data
12
35.21
26.22
57.56

16.07
45.09
18.91

44.90
11.94

5.43
57.55

7.66
36.48

Output (at the top of a new page)


The 12 elements of the vector X are:
16.07
5.43
36.48
SUM
XBAR

LOW
HIGH

35.21
45.09
57.55

44.90
26.22
18.91

7.66
11.94
57.56

363.02
30.25
5.43
57.56

Computer Example 7.3Sorting the Elements of a Vector


Write a FORTRAN program that will read, and then sort into ascending
sequence, the values contained in the elements of the vector V(l), ...,V(N). For ex
ample, if before the sort N 5 and the vector elements contain the values 7. . 1 . .
4 . . 6 . . 2 . . then after the sort the values should be in the order 1 . . 2 . . 4 . .
6. . 7. Table 7.2 shows how the values V(l), ..., V(5) change during successive
passes of the sorting procedure.
In general, for a given pass number I . V(I) is compared with all subsequent
elements of the vector, that is, with V(J) . for J 1+1. 1+2, ..., N; if V(I) >
V(J), the two elements must be interchanged so that they then are in ascending
order. In Table 7.2, boldface values are in no need of further sorting. The program
can sort more than one set of data.
Program
PROGRAM VSORT
C
C

Program for sorting the elements of a vector


V(l). V(2). .... V(N) into ascending order.
7-15

Chapter 7Subscripted Variables and Iteration


Table 7.2 Successive Passes in the Sorting Procedure
Pass number I during the sort

V(l)

V(2)

V(3)

V(4)

V(5)

After
sort

Before
sort

1
2
4

Declarations
DIMENSION V(100)
OPEN (5. FILE- 'VSORT.DAT')

C
1

Read and print N and the vector V


READ (5.101.END-999) N. (V(I) . I - 1. M)
WRITE (6.201) N. (V(I) . I - 1 . N)

C
DO 50
C
C

25
50
C

Conduct N - 1 passes of the sorting algorithm


I - 1. N - 1

Compare later elements V(J) with V(I).


and interchange if not in ascending order
DO 25 J - I + 1. N
IF (V(I) .GT. V(J)) THEN
SAVEV = V(I)
V(I) = V(J)
V(J) - SAVEV
END IF
CONTINUE
CONTINUE

999

Display the sorted values and return for more data


WRITE (6.202) (V(I) . I = 1 . N)
GO TO 1
STOP

101

Formats for input and output statements


FORMAT (15/ (8F5.1))

7-16

7.4 Several Examples Involving Iteration


201

FORMAT ClThe", 13, ' elements of the vector V are:


1 (5X. 8F5.D)
202 FORMAT ("0The sorted elements of the vector V are:'
1 (5X. 8F5.1))
END
Data
5
7.
48
35.6
84.4
85.0
78.9
29.4
83.0

1.

4.

6.

12.0
45.9
66.3
76.4
73.7
26.2

99.7
22.5
0.5
83.8
32.6
56.6

98. 8
51..7
71..6
25,.2
32 3
38 .7

91
73
88
42
1
14

.9
9
.0
.9
.6
9

26.2
98.9
49.1
76.5
66.4
19.4

43..7
73..7
22 .1
37 .8
81 .1
27 .2

13.1
66.6
61.2
68.8
95.1
48.1

Output (at the top of a new page)


The

5 elements of the vector V are:


7.0

1.0

4.0

6.0

2.0

The sorted elements of the vector V are:


1.0

2.0

4.0

6.0

7.0

The 48 elements of the vector V are:


35.6
84.4
85.0
78.9
29.4
83.0

12.0
45.9
66.3
76.4
73.7
26.2

99.7
22.5
.5
83.8
32.6
56.6

98.8
51.7
71.6
25.2
32.3
38.7

91.9
73.9
88.0
42.9
1.6
14.9

26.2
98.9
49.1
76.5
66.4
19.4

43.7
73.7
22.1
37.8
81.1
27.2

13.1
66.6
61.2
68.8
95.1
48.1

The sorted elements of the vector V are:


.5 1.6 12.0 13.1
25.2 26.2 26.2 27.2
37.8 38.7 42.9 43.7
56.6 61.2 66.3 66.4

14.9
29.4
45.9
66.6
7-17

19.4
32.3
48.1
68.8

22.1
32.6
49.1
71.6

22.5
35.6
51.7
73.7

Chapter 7Subscripted Variables and Iteration


73.7 73.9 76.4 76.5 78.9 81.1 83.0 83.8
84.4 85.0 88.0 91.9 95.1 98.8 98.9 99.7
Exercises for Section 7.4
1. Referring to Example 1 in Section 7.4 for computing NFACT. could the
DO loop in the first program segment begin with DO 5 I = 2 . N instead of DO 5
1 = 1. N? Also, how would you modify the second program segment if its first
statement were NFACT - N instead of NFACT 1?
2. Referring to Example 2 in Section 7.4, how would you modify the program
segment if odd-x&lued elements with even subscripts were to be counted? What if
even-valued elements with odd subscripts were to be counted?
3. How could you modify the program segment of Example 3 in Section 7.4
to find the total sales CUST(J) to each customer for the month (J = 1 . 2
M)?
4. Write the FORTRAN statements that will reverse the order of the values
in the elements of a vector A(l), . . ., A(N). That is, the values contained in A(l)
and A(N) . A(2) and A(N-l), etc., are to be interchanged. Make sure that your
statements will work for N either odd or even.
5. Assume that values for N and the elements of an NxN square matrix A
have already been assigned. Write a program segment that will compute (using
only one DO loop, if possible):
(a) SMDIAG, the sum of the main diagonal elements, A(l.l) + A(2.2) + +
A(N.N).
(b) PRDIAG, the product of the reverse diagonal elements, A(1.N) x A(2.N-1)
x,..x A(N.1).
6. Assume that values for N and the elements of an NxN square matrix A have
already been assigned. Write FORTRAN statements that will store the individual
numbers of negative, zero, and positive elements below the main diagonal in the
variables NNEG . NZER, and NPOS, respectively.
7. The number of items of type I (= 1 . 2
L) sold by store J (* 1 .
2
M) for month K (= 1. 2
12) is designated as NSALESU. J. K). The
L x M x N three-dimensional array NSALES contains all possible such information.
The profit on the sale of each item I is PROF (I). Write FORTRAN statements that
will compute over the twelve months:
(a) ITEM(I), the number of items of each type sold by all the stores combined.
(b) TOTAL, the total profit made by all the stores combined.
8. Write FORTRAN statements that will evaluate any nth-degree polyno
mial with coefficients ai, a2, . . ., an+1 for any argument x:
Pn{x) = ax + a2x + a3x2 H
7-18

1- ani"-1 + an+lxn.

7.4 Several Examples Involving Iteration


Assume that the value of x is already stored in the variable X, and that the coeffi
cients are already stored as A(l) . A (2)
A(N+1). The value of the polyno
mial is to be stored in the variable POLY.
9. Repeat Exercise 8, but now use the nested evaluation scheme:
Pn(x) = (...((an+iX + an)x + an-1)xH

+ 02)1 + 0.!.

10. The Fibonacci sequence of integers Fi is given by:


F0 = l; Fl = l; F{ = Fi-i + F{.3, i = 2,3,...
That is, the first few numbers are: 1, 1, 2, 3, 5, 8, 13, . . . etc. Given a non-negative
integer N, write a program segment that will compute the corresponding Fibonacci
number F/f and store it as the value of the variable FN.
11. Given a matrix with elements A (1.1)
A (M.N), write FORTRAN
statements to rearrange the elements in descending order, by rows, that is, place
the largest element in A (1.1), the next largest element in A (1.2), and so forth,
with the smallest element in A(M.N).
12. Write a program segment that will compute SUM2 and SUM3, the sums
of the squares and cubes, respectively, of the positive elements of the vector V :
V(l). V(2)
V(N).

7-19

Chapter 7Subscripted Variables and Iteration


Notes

7-20

CHAPTER 8
ADDITIONAL INPUT AND OUTPUT FEATURES
8.1 Introduction
Many of the details of input and output were covered earlier, in Chapter 3.
Here, we add a few more topics, the most useful being the OPEN statement, the
reading and writing of arrays, some additional format specifications, and manipu
lation of files.
8.2 The OPEN and CLOSE Statements
The numerical I/O unit codes appearing in READ and WRITE statements must
sooner or later be assigned to actual devices or files, and can be so identified during
either or both of two distinct stages of program development and execution:
1. During execution, by means that have already been described in Chapter 4
and 5.
2. Within the program itself, by using the OPEN statement, which is the main
topic of this section.
To identify within a program a particular I/O unit with an actual device or
file, we use the OPEN statement, for which an appropriate form is:
OPEN (U. FILE-'P'. STATUS-' stags')
Here, the generalized symbols have the meanings shown in Table 8.1.
Examples
OPEN (5. FILE-'CON: ')
READ (5.101) X. Y. Z
Values for X. Y. and Z are to be entered at the keyboard.
OPEN (6. FILE-' PROG. OUT'. STATUS-'NEW' )
WRITE (6.*) X. Y. Z
Values for X. Y. and Z are to be written to a new file named PROG. OUT on the
current directory of the default drive; the drive and directory path may also be
included (such as FILE- 'C:\ABC\PR0G. OUT').
8-1

Chapter 8Additional Input and Output Features


Table 8.1 Symbols in the OPEN Statement
Symbol

Meaning

I/O unit number. Most generally it can be an integer expres


sion, although some installations may have some restrictions
on acceptable values. For this reason, we shall confine our
numbers to small integers, notably including the conventional
values of 5 for input and 6 for output.

Name of device or file that is to be identified with unit number


U. Typically, P will be either:
(a) An input or output file, for example:
PROG. DAT or PROG. OUT
(b) A device that is part of the computer hardware. For
the IBM PC, P can be, for example:
CON:
CON:
LPT1:
PRN :

status

Keyboard (for input).


Monitor (for output).
Printer.
Another name for the printer.

May be needed if P is a file. OLD (the default case) signifies an


existing file; NEW means that the file is to be created implicitly
by the program. The only time this parameter is needed is
when writing into a new file.

There is a companion statement, of the form


CLOSE iU)
that will terminate identification of unit U, previously appearing in an OPEN state
ment, with any device or file. The CLOSE statement is rarely needed, since all files
are automatically closed when program execution terminates; one use would be
before reallocating unit U in a second OPEN statement.
8.3 Reading and Punching Cards
Cards may be read and punched, provided that the computing installation
is equipped with a card read/punch unit. The appropriate statements are identical
with those of Chapter 3 for formatted input and output:
READ (P. Ml. END=>/2)
WRITE (P. M) C

8-2

8.4 The G. L. and T Format Codes


The device number P must now correspond to the card read/punch unit, and the
other parameters are as previously defined. Care must be taken to insure that
the number of columns in each input/output record, established by the format
specification, does not exceed 80, since each card is limited to 80 columns of
characters. Carriage-control characters in any output lines are punched in column
1 of the associated card.
8.4 The G, L, and T Format Codes
Three additional format specifications that are used less frequently than
those already described in Section 3.4 are:
nLm

nGm.d

Tin

TLo

TRm

The first specification, nLm, is used for reading and printing values of logical
variables (or expressions for output). Here, n is the number of logical fields, each
m columns wide. In an input field, the first appearance of a T or F in the field
causes the value . TRUE . or . FALSE . , respectively, to be assigned to the pertinent
variable. On output, the letter T or F will be written right-adjusted in the ouput
field of width m.
The G or general specification can be used for reading or writing variable
values of real type; n is the number of such fields, m is the number of columns in
each field, and d is the number of decimal places for input. On the data line the
data may be typed using either the I . E . or F forms for constants. For example,
if the input statement and the associated format are:

201

REAL MAX
READ (6.201) ALPHA. BETA. MAX. TEMP
FORMAT (4G10.3)

and the data line has the appearance

Col:

12
3
4
1234567890123456789012345678901234567890
27344 1.459E-8
10.
20.5

then the variables would be assigned the values:


ALPHA - 27.344

BETA - 1.459x10-"

MAX = 10.

TEMP =20.5

When used as an output specification, the .d portion is the number of signif


icant digits that will be printed. The information is automatically scaled to either
E or F form, depending upon the magnitudes of the numbers involved.
The T or transfer specification determines the column position on an input
line or ouput line where the next field in the format specification is to begin. It is
analogous to the tab facility on a typewriter. The TLm and TRm format specifications
8-3

Chapter 8Additional Input and Output Features


are similar to the Tm specification, except that the column pointer is moved m
columns to the left (TLm) or to the right (TRm) of the current column position. For
example, the ouput statement and associated format

201

WRITE (6.201)
FORMAT (' ' . T10. 'INVENTORY' . T50. '1986'. TL23.
1 'STORE 10')

would produce an output line with the following appearance:

Col:

12
3
4
5
123456789012345678901234567890123456789012345678901234
INVENTORY
STORE 10
1986

Note that the m in the specification Tm causes a tab-stop to column m, and that
successive transfer specifications need not proceed from left to right across the line.
Exercises for Section 8.4
1. The values A = 3.6x 1017, B = 0.0004, X = 7.654, and CHECK - . TRUE. are
to be read, using three general fields and one logical field. Give all the necessary
FORTRAN statements to achieve this, and also show the layout of the data line.
2. Consider the following statements and two data lines:

101

Col:

LOGICAL UP. DOWN


READ (5.101) UP. DOWN. X. Y. XJK
FORMAT (2L10/ 3G10.2)
12
3
123456789012345678901234567890
.FALSE.
TWO
12345
3.142E0
6.2

After the READ statement has been executed, what are the values of UP.
DOWN. X. Y. and XJK?
3. In the following program, the variables ONE and TWO are to be read as
. TRUE . and . FALSE . , respectively. Indicate how you would type the data line and
show how the ouput will appear.

100

LOGICAL ONE. TWO. SWITCH


READ (5.100) ONE. TWO
SWITCH - .NOT. ONE .AND. TWO
WRITE (6.100) ONE. TWO. SWITCH
FORMAT (2L10. T25. L2)
STOP
END
8-4

8.5 Formatted Array Input and OutputIntroduction


8.5 Formatted Array Input and OutputIntroduction
The general formatted input statements introduced in Section 3.3,
READ (D. M)
t
READ (P. >/l. END = M2) t
READ (U. Ml. END - M2. ERR M3)

may be used to read individual array elements or entire arrays as well as the simple
variables illustrated in the examples of Section 3.4. The elements of the input list
C may be any of the following, separated by commas:
(a)
(b)
(c)
(d)

Simple variable names: X. NANCY. SWITCH.


Array names: TABLE. MATRIX.
Individual elements of arrays: TABLE(5). MATRIX(I+3. J)
Array segments (described below).

When individual array elements appear in the list, they are treated exactly
like simple variables, that is, one value is read from a data line for each element as
specified in the format specification of the accompanying FORMAT declaration. For
example, the input statement and accompanying format specification

101

READ (5.101) X. BETA(7). T(5.6). G0(J)


FORMAT (4F10.5)

would cause four numbers to be read from a data line according to the specification
4F10. 5, and to be assigned to X. BETA (7) . T(5 .6), and GO (J), respectively. The
particular element of GO assigned the new value would be determined by the current
value of variable J; in this case J must have been assigned a value prior to execution
of the READ statement. Array variables BETA. T, and GO would be dimensioned in
a DIMENSION declaration (Section 7.2).
If variable subscripts appear in the input list, the values of the variables
involved may be read with the same READ statement, provided that they appear in
the input list prior to their use in subscript expressions. For example, the following
would be acceptable:
READ (5.102)

N. PRESUR(N) . ISUM(N-5)

But the statement with variable N in a different position in the input list would be
unacceptable:
READ (5.102)

PRESUR(N). ISUM(N-5) . N

(If N had been assigned a value before execution of this READ statement, then the
statement would be acceptable; the old value of N would be used in computing
subscripts for PRESUR and ISUM, and then the new value of N would be read.)
8-5

Chapter 8Additional Input and Output Features


When the name of an array variable appears in the input list without at
tached subscripts, all of the elements of the array, as specified in the DIMENSION
declaration will be read. For example, if the statements

103

DIMENSION V(10). M(3.5)


READ (5.103) V. M
FORMAT (10F8.3/ 1515)

appear in a FORTRAN program, then the READ statement will cause ten real
numbers to be read for the ten elements of the one-dimensional array named V, and
fifteen integer numbers to be read for the fifteen elements of the two-dimensional
array M. The data would be typed according tho the format specification with
the ten elements of V in order on the first data line, each with an F10.3 format
code, and the fifteen elements of M typed on the second data line, each with an
15 format code. Since matrix elements are stored internally column-by- column
(Section 7.2), the data values for M must appear in the order M(1.l) . M(2.l) .
M(3.l) . M(l .2) . M(2.2) . etc., on the second data line; note that this is not the
"natural" row-by-row order one might wish to use.
Array Segments. When only a part of an array is to be read or when
the more natural row-by-row ordering of data for matrices is desired, an array
segment may appear as an element of an input list. An array segment is contained
in parentheses and has the form:
(l. VI - II. 12. 13)
Here, t is an input list conforming to the rules given previously, that is, a list
containing simple variable names, array variable names, individual elements of
arrays, or array segments. Thus it is possible (and often desirable) for an array
segment list t to contain other imbedded array segments. The appearance of an
array segment in a list t is equivalent to the hypothetical sequence

DO M VI - J1. 12. 13
Add list C to the input or output list
CONTINUE

That is, the list of variables L will be accumulated in the input or output
list t as many times as the corresponding DO loop would be performed. This is
not mere repetition, since the list of variables will almost always contain the index
V I as a subscript. Therefore, this type of construction is particularly useful when
reading or printing arrays. As with the DO statement, omission of 13 implies that
the incremental value is unity.
8-6

8.5 Formatted Array Input and OutputIntroduction


Example
Read a value for N, followed by values for the N elements of the vector X,
that is, X(l). X(2)
X(N):
READ (5.101)

N. (X(I). I = 1 . N)

Note that the array segment functions exactly like a DO loop in that I is set to 1,
2, 3, ..., N, leading to an effective input list of the form X(l) . X(2). X(3)
X(N). Appropriate format specifications are given in Section 8.6.
Example
Read values for M and N, followed by all the elements of the M x N matrix A,
row by row:
READ (5.102)

M. N. ((A(I.J). J - 1. I). I 1. M)

One feature of format specifications not introduced in Section 3.4, that adds
considerably to the flexibility allowed in reading and writing out information, in
volves the use of "repeating parentheses." This feature is used when the first one
or more unit records have a different format specification from the last two or more
unit records, all of which are identical. Then a set of parentheses called "repeating
parentheses" may be inserted around the last part of the specification.
Whenever the format scanner reaches the end of the specification but the
I/O list remains unsatisfied (that is, there are still variables in the I/O list whose
values have not yet been read or written), the scanner repeatedly processes the
portion of the specification enclosed by the repeating parentheses until the list is
satisfied. (Literal field specifications following the field specification corresponding
to the last element of an output list will be processed, however.)
The rules for the scanning of input formats may be summarized as follows.
When a READ statement is executed, the associated format is scanned from the
beginning, and from left to right. A data line is read, and partitioned into fields
according to the format for the first record; contents of the fields are converted to
the specified internal form (integer, real, etc.) and assigned, in order, to variables
in the input list. This procedure is followed for additional records, their associated
formats, and appropriate variables in the list until either:
1. The list is satisfied (all variables are read).
2. The end of the format specification is reached, but the list is not satisfied.
If Case 1 applies, then both reading and format scanning cease. If Case 2 applies,
the format is scanned from right to left until the first left parenthesis is encountered
that matches the right parenthesis immediately inside the FORMAT declaration at
the right. For example, in the declaration
8-7

Chapter 8Additional Input and Output Features


FORMAT

( ) / (
T

))
T

the appropriate left parenthesis (and its matching companion) are marked with
arrows. Reading is then resumed with the next data line and the format is scanned
to the right, starting with this left parenthesis. If the end of the format is again
encountered before the list is satisfied, then this is just another instance of Case
2.
If no "repeating parentheses" are used and the end of the format specification
is encountered before the list is satisfied, reading is resumed with the next data
line and the format scan proceeds from the beginning of the format specification,
as already described in Section 3.4, and illustrated by the preceding example.
Example
Read values for variables B and C, typed on the first data line as shown in
Table 8.2, followed by three lines containing eight pairs of values X(I) , Y(I) , I =
1, 2, 3, . . ., 8. The values of elements of the X and Y arrays are arranged alternately,
three pairs per line, with each record having the same format, as shown in Table
8.2.
Table 8.2 Appearance of Values on Successive Data Lines.
Line 1:
Fields:

B
F5.1

C
F5.1

Line 2:
Fields:

X(1)
F5.1

Y(1)
E15.5

X(2)
F5.1

Y(2)
E15.5

X(3)
F5.1

Y(3)
E15.5

Line 3:
Fields:

X(4)
F5.1

Y(4)
E15.5

X(5)
F5.1

Y(5)
E15.5

X(6)
F5.1

Y(6)
E15.5

Line 4:
Fields:

X(7)
F5.1

Y(7)
E15.5

X(8)
F5.1

Y(8)
E15.5

The appropriate READ and FORMAT statements are:

105

READ (5.105) B, C. (X(I). Y(I). I - 1, 8)


FORMAT (2F5.1/ (3(F5.1. E15.5)))
T *

*T

The repeating parentheses are marked with f and show that the record format
3(F5. 1 , E15.5) will be used repeatedly for any remaining elements in the input
list whenever the end of the format specification is encountered by the format
scanner. The other interior parentheses, marked with "*", simply indicate that
8-8

8.6 Examples of Array Input and Output


the specification F5 . 1 . E15 . 5 is to be repeated three times, as discussed in Section
3.4; parentheses of this type are usually preceded by an integer constant to indicate
the number of repetitions of field or record specifications. Repeating parentheses,
on the other hand, are not usually preceded by a constant.
Repetition caused by the introduction of repeating parentheses applies only
to the final unit record(s) in the format specification. It is impossible to repeat
unit record specifications in the middle of the format specification an arbitrary,
but unspecified, number of times using the repeating parentheses convention.

8.6 Examples of Array Input and Output


Formatted Input. We shall now illustrate the reading of vectors (onedimensional arrays) and matrices (two-dimensional arrays) for elements of a 10element vector X and a 3 x 4 matrix A. So that the values can be readily identified
with corresponding elements, the examples will involve the following for vector X:
X(l) = 1.0. X(2) - 2.0. X(3) = 3.0. X(4) = 4.0. X(5) = 5.0
X(6) - 6.0. X(7) = 7.0. X(8) = 8.0. X(9) 9.0. X(10) = 10.0
The values to be read for the elements of matrix A are:

A=

1.1
2.1
3.1

1.2
2.2
3.2

1.3
2.3
3.3

1.4
2.4
3.4

Thus, the value being read for element X(I) will be 1 .0, while the value being read
for element A(I.J) will be I.J, where I and J are the row and column indices,
respectively.
Column J

Row I

A (1,1)
A (2,1)

A(1,2)
A (2, 2)

A(1,J)
A (2, J)

A(1,N)
A(2,N)

A (1,1)

A(I,2)

A (I, J)

A(I,N)

A(M, 1)

A(M, 2)

A(M, J)

A (M.N)

Fig 8.1 General appearance of a matrix


A with M rows and N columns.
In the examples that follow, we assume that all program segments are ac
companied by the declaration
DIMENSION X(10). A(3.4)
8-9

Chapter 8Additional Input and Output Features


However, in order to write FORTRAN segments that could be used in more general
situations we shall assume that the vector X has K elements of interest (in our case,
K must be no larger than 10) and that the matrix A has M rows and N columns of
interest (in these examples, M and N could be no larger than 3 and 4, respectively,
given the above DIMENSION declaration). Viewed in the general context, A would
appear as shown in Fig. 8.1.
Examples of array input.
several examples, which follow.

Formatted array input is now illustrated with

Example 1.
FORTRAN Statements
READ (5.100) K. (X(I) . I - 1 . K)
100 FORMAT (15/ (4F5.1))

Data Lines
Col:

12
3
123456789012345678901234567890
10
1.0 2.0 3.0 4.0
5.0 6.0 7.0 8.0
9.0 10.0

The value of K (10 in this case) is read from the first line using the unit
record format 15. The slash indicates that the next variable in the input list,
X(l), should be read from the next data line. X(l) . X(2) . X(3) . and X(4) are
read according to the format 4F5. 1 from the second line. Since the list is not yet
satisfied [X(5) has not yet been read], the format scanner scans from right to left
until it encounters the left parenthesis of the repeating parenthesis pair (indicated
here by upward arrows, |). The scanner then resumes scanning of the format
specification from left to right, so that values for X(5) through X(8) are read from
the third line using the same 4F5 . 1 specification. Finally, for the fourth line, only
the first two of the next four F5.1 fields are examined, since X(9) and X(10) are
the last variables to be read. Note that if the format had been written as:
100

FORMAT (15/ 4F5.1)

the values of K and of X(l) . X(2) . X(3) . and X(4) would have been read cor
rectly. At that point, the format scanner would return to the beginning of the
format specification, since no repeating parentheses appear. The third line would
be read using the specification 15, leading to an error, since the proper specifi
cation for the third line is 4F5.1. If the array X were dimensioned to have ten
elements, then all ten values could have been read using the statements
8-10

8.6 Examples of Array Input and Output

100

READ (5.100) X
FORMAT (5F5.1)

In this case, the first data line would not be present (since the entire array is to
be read, and X is dimensioned to have ten elements, K does not need to be read),
and X(l) through X(10) would be spread over two lines, with five F5. 1 fields per
line. However, when less than the entire set of element values is to be read, this
form would be inadequate.
Example 2.
FORTRAN Statements
READ (5.101) M. N. ((A(I.J). J - 1 . N) . I * 1. M)
101 FORMAT (215/ (6F5.1))

Data Lintes
1
Col:

123456789012345678901234567890

3
1.1
2.3

4
1.2
2.4

1 .3
3 .1

1.4
3.2

2..1
3. 3

2.2
3.4

The values of M and N are read from the first data line according to the first
specification, 215. Thereafter, the repeating parentheses cause successive lines to
be read with the unit record specification 6F5.1. Note that the array segment
(A (I. J). J 1. N) is imbedded within the array segment (
,1 = 1. M); in
the latter segment, the only list element is the imbedded array segment. The array
segment indices vary as if the list were being selected by two DO loops of the form:

10
20

DO 20 I = 1. M
DO 10 J = 1. N
Read element A (I. J)
CONTINUE
CONTINUE

Thus the indices are varied in the sequence (1 .1) . (1.2). (1.3). (1.4).
(2.1). (2.2). (2.3). (2.4). (3.1). (3.2). (3.3). (3.4) . so that the ar
ray elements are read in row-by-row. However, since the format indicates that six
numbers appear on each line, new rows of the matrix do not necessarily start on
the new data lines (they would if M had a value equal to an integral multiple of six,
not allowed in our example, since A is dimensioned to have only four columns).
8-11

Chapter 8Additional Input and Output Features


Example S.
FORTRAN Statements

10
110
111

READ (5.110) M. N
DO 10 I - 1. M
READ (5.111) (A(I.J). J - 1. N)
CONTINUE
FORMAT (215)
FORMAT (6F5.1)

Data LintiS
1
2
3
123456789012345678901234567890
3
4
1..1 1 .2 1 .3 1 .4
2 .1 2 .2 2 .3 2 .4
3 .1 3 .2 3 .3 3 .4

Col:

In this case, the values of M and N are read in a separate READ statement using
FORMAT statement number 110. The other READ statement is inside a DO loop for
which the iteration variable is I. The array segment (A (I. J) . J 1. N) causes
the variables A(I.1) . A(I.2). A(I.3). and A(1. 4) to be read, starting with a
new data line. The first time through the loop, the elements of the first row (I
= l) are read from the second data line, etc. Note that althought the format
specifications for the data lines are the same as in example 2, this structure allows
the more natural arrangement using a new data line for each new row; this is true,
even when the value of M exceeds six. We prefer this arrangement for reading in
arrays, even though more statements are required.

Example 4.
FORTRAN Statements

101

READ (5.101) M. N. ((A(I.J). I - 1 . M) . J = 1 . N)


FORMAT (215/ (6F5.1))

Data Lines

Col :

1
2
3
123456789012345678901234567890
4
3
1.1 2.1 3.1 1.2 2.2 3.2
1.3 2.3 3.3 1.4 2.4 3.4
8-12

8.6 Examples of Array Input and Output


The only difference between this example and that in 2 above is in the array
segment; here, the segment involving iteration on J (the column index) is imbedded
inside the segment involving iteration on I (the row index), rather than vice versa.
This causes the array elements to be read in column-by-column, rather than the
more natural row-by-row order of example 2, so the data line entries must be in
column order. If the A array were dimensioned to have three rows and four columns
as indicated earlier, then the values could have been read with the statements

100

READ (5.100) A
FORMAT (6F5.1)

In this case, the first data line would not be present, since M and N do not
need to be read. If the entire array is not to be read or column-by-column ordering
of the data is not desired, then this form would be improper.
Formatted Output. The general formated output statement introduced in
Section 3.5,
WRITE Ul.M) t
may be used to write out the values (possibly with labels or messages) of individual
array elements or of entire arrays as well as the simple variables illustrated in the
examples of Chapter 3. In fact, output lists may contain any elements that can
appear in input lists and, in addition, expressions of any type. When individual
elements of an array appear in the list, the values are printed according to the for
mat specification in exactly the way that simple variable values would be printed.
For example, if N has the value 7 and AGE(7) has the value 56.7, the statements
WRITE (6.201)
201

N. AGE(N)

FORMAT ( 'lFor person:

'. 13/ 'OAge is: '. F5.1)

would cause the following to be printed at the top of the next printed page:
Col:

1
2
12345678901234567890
For person:
7
Age is:

56.7

When the name of an array variable appears in the output list without
attached subscripts, a// of the elements of the array, as specified in the DIMENSION
declaration will be written. For example, if the statements

202

DIMENSION VECTOR(1O). MATRIX(3.5)


WRITE (6.202) VECTOR. MATRIX
FORMAT CO'. lOFB.l/'O'. 1515)
8-13

Chapter 8Additional Input and Output Features


appear in a FORTRAN program, then the WRITE statement will cause the ten real
numbers corresponding to the elements of VECTOR to be written on one line, fol
lowed, double-spaced, by the 15 integer values of MATRIX. The elements of MATRIX
would be written in column order, MATRIX (1.1). MATRIX(2.1). MATRIX(3.1).
MATRIX (1,2), MATRIX (2,2), etc., across the page. This output form for matrices
almost always leads to confusion, and its use is not recommended. The following
examples illustrate some of the more important features of writing vector and
matrix values.
Examples of array output. Formatted array output is further illustrated
with several examples, which follow.
Example 1.
An integer variable N and a set of N paired values X(I) , Y(I) , I 1, 2,
. . . , N, are to be printed with labels so that the output page appears as follows:
Line

1
2
3
4

Column
1
2
3
4
5
12345678901234567890123456789012345678901234567890
The values of the nn data sets are:
x( l) xxxxx.xxxx
X( 2) xxxxx.xxxx

Y( l) yyyyy,yyyy
Y( 2) yyyyyyyyy

X(nn) xxxxx.xxxx

Y(nn) yyyyy.yyyy

6
6

N + 2

Here, nn is the value of N and xxxxx.xxx and yyyyy.yyy are the values of the
variables X(I), Y(I), I 1, 2, 3
N. An appropriate output statement
and FORMAT declaration would be:

203

WRITE (6.203) N. (I. X(I) . I, Y(I) . I - 1 , N)


FORMAT ClThe values of the
12. ' data sets are:'//
1 C X('. 12. ') - '. F10.4. 5X. 'YC. 12. ') - '.
2 F10.4))

Note that two slashes in sequence indicate that an empty record or blank line is
to be printed, and that the iteration variable, I, may appear in the array segment
list.
8-14

8.6 Examples of Array Input and Output


The following examples assume that the values of elements of the vector X
and matrix A are the same as those used in the formatted input examples of the
previous few pages; K. M. and N are assumed to have the values 10, 3, and 4,
respectively.
Example 2.
FORTRAN Statements
WRITE (6.204)

204

K. (X(I). I = 1. K)

FORMAT ClThe ' . 13. ' elements of


1 ' the vector X are:'/ C '. 4F10.2))

T
Output
Col:

12
3
12345678901234567890123456789012345678901

The

10 elements of the vector X are:


1.00
2.00
3.00
4.00
5.00
6.00
7.00
8.00
9.00
10.00

Repeating parentheses are allowed in output as well as in input formats, and are
emphasized here with |. The first character in each line (1 in the first line and
blank in all subsequent lines) is used for carriage control; the carriage-control
character for repeated line formats must appear inside the repeating parentheses.
Example S.
FORTRAN Statements
DO 20 I - 1. M

20
205

WRITE (6.205)
CONTINUE

(A(I.J). J - 1. N)

FORMAT (' ' . 6F10.1)

Output
12

Col:

12345678901234567890123456789012345678901
1.1
1.2
1.3
1.4
2.1
2.2
2.3
2.4
3.1
3.2
3.3
3.4

This approach to the printing of matrices causes elements to be printed row-byrow with each new line starting at the left edge of the page, and is our preferred
approach to the printing of two-dimensional arrays.
8-15

Chapter 8Additional Input and Output Features


Example 4.
FORTRAN Statements
WRITE (6.206)

((A(I.J). J - 1 . N) . I - 1. M)

206 FORMAT (' '. 3F10.1)

Output

Col:

12
3
4
1234567890123456789012345678901234567890
1.1
1.2
1.3
1.4
2.1
2.2
2.3
2.4
3.1
3.2
3.3
3.4

With the imbedded segment iterating on variable J and the outer segment iterating
on I, the elements are printed in row-by-row order, as in example 3. However, a
new row does not begin at the edge of the page unless N is an integral multiple of
the number of entries per line (three in this case).

Exercises for Section 8.6


1. Elements of two vectors, X and Y, each with N elements, are to be read.
The first line contains a value of N using an 15 field in the first 5 columns. The
elements of X and Y are typed on subsequent lines in F8. 5 fields, with 10 values
per line, with the elements in the order X(l). Y(l). X(2) . Y(2) . etc. That is,
the second line starts with X(l), the third starts with X(6), and so on. Write the
necessary input and format statements required to:
(a)
(b)
(c)
(d)

Read N and all the elements of X and Y.


Read N and all the elements of Y (but not X).
Read N and all the elements of X and Y having odd subscripts.
Read N and all the elements of X having odd subscripts and all the elements
of Y having even subscripts.

2. Write the appropriate I/O and format statements to implement the fol
lowing:
(a) Read the variables N. EPS. etc. from data lines arranged as follows. Use
F-type fields for all real variables except EPS . which should have an E-type
field.
8-16

8.6 Examples of Array Input and Output

Columns

Variable
Line 1

Line 2

Line S

Line 4 etc.

N
EPS
P(5)
A(1)
A(2)
A(3)
A(4)
A(5)
A(6)
A(7)

1-5
6-20
31-40
41-50
51-60
1- 10
11-20
21-30
31-40
41-50

A(8)

1-10

A(12)

41-50

Decimal Places

5 elements of the vector A with the format


of lines 2 and 3, until A(N) is reached.

(b) Write column headings and appropriate double-spaced values under the
headings shown below:

12
3
4
Col :
123456789012345678901234567890123456789012345
I
I
I VOLUME I
I RADIUS |
I WEIGHT I
Heading:
I I I
I V(1)
|
I R(D
I
I W(1)
I
I 1 I
I
V(2)
I
1
2
|
I
R(2)
I
I
W(2)
I
Values to appear
double-spaced
I
I
I
I
I
I
1 , I
under the heading:
j
,
I
I
.
I
1 ' 1
'
1
|
|
I V(N)
I
I w(N)
I
I N |
I R(N)
I
II
ii
Iddddd.ddl
Idd.dddddl
Format for values:
Idddl
Idddd.dddl
(d digit or sign position)
3. Values for M and N, and the elements of an M-row by N-column matrix K
are to be read using any of the following READ and FORMAT statement combinations:
(a)
100

READ (5.100) M, N. ((K(I.J), J = 1 . N) . I = 1 , M)


FORMAT (215/(615))

8-17

Chapter 8Additional Input and Output Features


(b)

10
101
102

READ (5.101) M. N
DO 10 I = 1, M
READ (5. 102) (K(I,J), J = 1 , N)
CONTINUE
FORMAT (215)
FORMAT (1015)

103

READ (5.103)
FORMAT (815)

(c)

M. N. K

If M = 3 and N = 5, and K is the matrix shown below, indicate exactly how you
would type the data lines corresponding to each of the combinations (a), (b), and
(c) given above.
( 1
6

2
7

3
8

4
9

5 \
10

11

12

13

14

15 J

[You may assume that the declaration DIMENSION K(3.5) has been used.]
4. Write FORTRAN statements that will print all the elements on the main
diagonal of a 10 x 10 matrix Q, starting at the top of a new page. The elements
should be printed in a single column, in F10.3 form, and should be single spaced.
5. Consider the following program segment:

200

DIMENSION A(10. 10)


WRITE (6.200) ((A(I.J), J - 2, 4. 2) , I - 3, 4
FORMAT (' ' .2F10.4)

In which of the following arrangements would the above cause the elements
of A to be printed?
(a)

A(3.2)
A(3,4)

A(4.2)
A(4.4)

(c)

A(3.2)
A(4.2)

A(3.3)
A(4.3)

(b)

A(3,2)
A(4.2)

A(3.4)
A(4.4)

A(3.4)
A(4.4)

6. What may be undesirable about using the following statement to print


all the elements of the matrix ARRAY?

WRITE (6.200) ARRAY


8-18

8.6 Examples of Array Input and Output


7. The integer matrix A, dimensioned 4x5, has the following elements stored
in it:
/ 1
6
A=
11
Vl6

2
7
12
17

3
8
13
18

4
9
14
19

5
10
15
20,

Now consider the following output statement/format combinations:


(a)
10
201

DO 10 J - 1, 4
WRITE (6,201) J. (A(I.J), I = 1 . 4)
CONTINUE
FORMAT C '. 515)

202

WRITE (6.202)
((A(I.J). J - 1, 5), 1=2, 3)
FORMAT (' '. 215)

203

WRITE (6,203) A
FORMAT ( ' ' . 415)

(b)

(c)

Identify which, if any, of the following output will be produced by each of


the output statements (a), (b), and (c) above. Assume that all fields are 15.
(i)

1
2
3
4
5

6
7
8
9
10

11
12
13
14
15

16
17
18
19
20

(ii)

6
11

7
12

8
13

9
14

(iii)

12
1
2
1
2
6
7
11
12
16
17

3
3
8
13
18

4
4
9
14
19

10
15

(iv)

1
2
3
4

1
2
3
4

(v)

6
7
8
9
10

11
12
13
14
15

(vi)

6
8
10
12
14

7
9
11
13
15

6
7
8
9

11
12
13
14

16
17
18
19

8. Print the elements of a 20 x 12 matrix BETA in matrix form (by rows) with
double spacing between rows. The minimum field specification for each element is
F6.2.
8-19

Chapter 8Additional Input and Output Features


9. Print the elements of the NxM matrix B in matrix form (by rows) with an
F10.4 field specification for each element. The elements should be printed across
the page with no more than 12 per line. If M is larger than 12, remaining elements
in the row should be printed on subsequent lines, single spaced. Each new row of
elements should be printed starting at the left edge of the page, triple spaced below
the elements of the preceding row. Write the FORTRAN statements required to
do this.
8.7 File-Control Statements: BACKSPACE, REWIND, and ENDFILE
Here, we briefly describe three statements that will find occasional use during
input and output operations involving files:
BACKSPACE It
REWIND It
ENDFILE It
In each case, U is the integer number of the unit involved in the data transmission
to or from the file.
The REWIND statement (which derives its name when magnetic tape was
a more predominant storage medium than today) is useful when one part of a
program has written information into a file (identified by U), and a later part of
the same program needs to read the same information, starting from the beginning
of the file. The action caused by the REWIND statement is to reposition the file
pointer at the beginning of the first line of the file; subsequent data transfer will
then occur from that position. A typical application occurs when one part of a
program acts as a "pre-processor," and prepares data in a preliminary form, which
is then re-read and further processed by a later part of the program.
The BACKSPACE statement has a similar effect, except that the file pointer
only moves back to the beginning of the most recently read or written record or
line. BACKSPACE should not be used on files that are formatted for the list-directed
READ and WRITE statements.
The ENDFILE statement writes an end-of-file record into the file identified
by U , and the file pointer is then positioned at the end of this record. The file
is then unavailable for further data transfer unless preceded by a REWIND or two
BACKSPACE statements (for reading) or one BACKSPACE statement (for writing).
Example Program 8.1File-Control Statements
The above three statements are illustrated by the following program and its
output. Five lines of data are first written to the file named REWIND . OUT (associated
with unit 7). Through subsequent REWIND and BACKSPACE statements, either the
whole file, or just its last line, are then read and printed. Note that two BACKSPACE
statements are neededthe first to position the pointer at the beginning of the
8-20

8.7 File-Control Statements: BACKSPACE. REWIND. an d ENDF I LE


end-of-file indicator, and the second to position it at the beginning of the record
before that.
Note: This program uses CHARACTER variables (Chapter 11) and the DATA
declaration (Section 9.2) so you may wish to read these sections before examining
the program in detail.
Program
PROGRAM REWIND
C
C

Illustration of the ENDFILE. REWIND. and


BACKSPACE statements.

Declarations
CHARACTER* 12 NAME (5) . WORD (5)
DATA WORD /'First line.. 'Second line.'.
1

C
C
C

10

' Third line .' . 'Fourth line. ' . 'Fifth line. '/
OPEN (7. FILE-' REWIND. OUT'. STATUS- 'NEW')
Generate five lines of information.
printing as we go . and also writing
into the file REWIND. OUT
WRITE (6.201)
DO 10 1=1.5
WRITE (6.301) I. WORD(I)
WRITE (7.301) I. WORD(I)
CONTINUE

Insert end-of-file record into REWIND. OUT


ENDFILE 7

Rewind file to the beginning


REWIND 7

Read and print contents of the file


WRITE (6.202)
READ (7.301.END-30) I. NAME(I)
WRITE (6.301) I. NAME(I)
GO TO 20

20

C
C
C
30

Backspace two records (the end-of-file record and then the record before that) ; read
and print just the fifth line of the file
BACKSPACE 7
8-21

Chapter 8Additional Input and Output Features


BACKSPACE 7
WRITE (6.203)
READ (7.301) I. NAME(I)
WRITE (6.301) I. NAME(I)
STOP
C

Formats for input and output statements


FORMAT ( ' lPrint lines as they are sent to ' .
1
' the file REWIND. OUT : 7)
202 FORMAT ('ORewind file. read and print entire contents:'/)
203 FORMAT ('OBackspace file. read and print fifth line:'/)
301 FORMAT (15. lX. A12)
201

END

Output (at the top of a new page)


Print lines as they are sent to the file REWIND. OUT:
1
2
3
4
5

First line.
Second line.
Third line.
Fourth line .
Fifth line.

Rewind file. read and print entire contents:


1
2
3
4
5

First line.
Second line.
Third line.
Fourth line.
Fifth line.

Backspace file. read and print fifth line:


5 Fifth line.

8-22

CHAPTER 9
ADDITIONAL DECLARATIONS

9.1 Introduction
The distinction between executable statements and non- executable state
ments or declarations has already been made in Section 1.4. The latter were seen
as aids to the compiler that did not generate any executable object code, examples
being the FORMAT . INTEGER. LOGICAL. PROGRAM . and REAL declarations. In this
chapter, we describe the DATA. EQUIVALENCE. and additional type declarations.
Other important declarationsthe EXTERNAL. INTRINSIC. COMMON. and BLOCK
DATA statements, will be delayed until the end of Chapter 10.
9.2 The DATA Declaration
It is frequently useful to be able to preset or initialize values of variables
(possibly subscripted, as long as the subscripts are constants) before execution
of the program begins. This means that the memory locations assigned to the
named variables will already contain the specified values when the program is
initially loaded into the computer's memory. The DATA declaration can be used
for this purpose; at its simplest, it has the form
DATA t/ Cl. C2

Cn/

Here, t represents a list of variables or array names that will be preset with the n
constants Cl, C2, . . ., Cn. For example:
CHARACTER FIRST*4. LAST*7
LOGICAL SWITCH
DIMENSION Y(10)
DATA X. Y(6). INT. FIRST. LAST. SWITCH/ -6.7.
1 1.93E-6. 49. 'John'. 'Roberts'. .TRUE./
would preset X with the value -6.7, Y(6) with 1.93 x 10-6, INT with 49, FIRST
with the characters 'John', LAST with the characters 'Roberts' (see Chapter 11
for details about character information) and SWITCH with the logical value .TRUE.
Representative declarations have also been added in the above example.
9-1

Chapter 9Additional Declarations


To preset entire arrays, the array name only is given; also, the construction
m*C may be used to repeat the constant C a total of m times. For example, the
sequence
DIMENSION A(3.3), B(5.10)
DATA A. B/ 6*1.. 1.5. 2.7. -6.2. 16.3. -14.6. 48*0./
would preset the first two columns of matrix A with the value 1., A(1 ,3) with 1.5,
A(2.3) with 2.7, A(3.3) with -6.2, B(1.1) with 16.3, and B(2.1) with -14.6;
the remaining 48 elements of the matrix B would be assigned zeros. Every element
of a named array must be assigned a value.
The pattern of slashes can be repeated, in which case a comma must precede
every list of variables except the first. For example,
DIMENSION B(5.10). Y(10)
DATA X. Y(6)/ -6.7. 1.93E-6/. B/ 16.3. -14.6. 48*0./.
1 SWITCH/ .TRUE./
The DATA declaration must not be confused with reading data values using
the READ statement. The DATA declaration is nonexecutable (the compiler sees to
it that the values are already assigned before execution even begins), whereas the
READ statement is executable. Variables initialized with the DATA declaration may,
however, be modified subsequently, the same as any other variable. The list t may
also contain array segments; for example, the statement
DATA (B(I). C(I). I - 1. 9. 2)/ 5*5.3. 5*-0.7/
would assign the values 5.3 to B(1), C(1) , B(3) . C(3) , and B(5) . and the
value -0.7 to C(5) , B(7) . C(7) , B(9) . and C(9). There are some restrictions,
discussed in Section 10.9, on the assignment of initial values to variables in blank
or labeled COMMON blocks.
Exercises for Section 9.2
1. The variables INTOCM, LBTOKG, and GALLTR are to be preset before
execution (i.e. during compilation) with the values 2.54, 0.45359, and 3.78541,
respectively. Write all necessary declarations to achieve this.
2. Before execution, the elements V(1), . . ., V(100) of the 100-element
vector V are each to be preset with the value zero, and the variables E and PI are
to be preset with the values 2.71828 and 3.14159, respectively. Write all necessary
declarations to do this.
3. X, MATRIX, and TRIPLE are the names of real arrays of maximum di
mensions 10, 10 x 10, and 10 x 10 x 10, respectively. Write down the declarations
needed to reserve space, assign proper type, and preset (at compilation time) all
these array elements to zero.
9-2

9.S Type Declarations


4. Storage is to be reserved for a matrix M, and its elements are to be
preset before execution with the values shown below. Write down all the necessary
declarations.
/6.4 2.8 -0.6 -1.6 \
VO.O 0.0 0.0
7.9 J
5. Storage is to be reserved for a matrix ITEM, and its elements are to be
preset before execution with the values shown below. Write down the necessary
declarations.

ITEM =

1
0
0
0

0
2
0
0

0
0
3
0

0
0
0
4

\
0
0
0/

6. If the following two declarations appeared in a FORTRAN program, what


would then be the values for the variables indicated below?
DIMENSION A(3.4). B(4)
DATA A. B/ 2*5.9. 0.. 1.6. 6*2.. 4*2.5. -0.5. 0./
1(1.2) -

A(1.4) -

A(3.2) -

B(2) =

7. If the following three declarations appeared in a FORTRAN program,


what would then be the values for M(2.l). M(3.3). X(l) . and X(5)?
REAL M
DIMENSION X(5). M(3.4)
DATA X. M/ 3*0.. 1.2. 4*1.0. 4*2.. -2.. -3.. 3*4.5/

9.3 Type Declarations


As described in Section 2.2, the first letter in the name of a variable normally
establishes its type; if the first letter is I. J. K. L. M. or N, the variable is of
integer type; otherwise it is of real type. There are no reserved letters for logical
type. If desired, we can override this convention by using one or more mode or
type declarations of the form
INTEGER t
L0GICAL t
REAL C
Here, the simple variable or array names comprising the list , are understood by
the compiler to be integer, logical or real as specified, regardless of their initial
letters. A type declaration must precede the first appearance of the variable or
array name in the program. Occasionally (see Section 10.6), a function name,
without arguments, may also be included as part of the list t.
9-3

Chapter 9Additional Declarations


Examples
INTEGER COUNT
L0GICAL SWITCH. ANSWER
REAL LAMBDA. LENGTH. I

Variables may also be declared to be of the character type with the decla
ration (see Chapter 11):
CHARACTER
Character variables named in the list t are assumed to contain one character,
unless another optional length is selected, as described below.

Table 9.1 Standard and Optional Word Lengths


Type (mode)
Standard integer
Optional integer
Standard real
Optional real
Standard logical
Optional logical
Standard character
Optional character

Number
of Bytes
4
2
4
8
4

2t

Approximate
Magnitude Range
0 through 2147483647
0 through 32767
0, 10-36 through 1038
0, lO-307 through 10308
.TRUE. or .FALSE.
.TRUE. or .FALSE.

Precision
(Decimal Digits)
9+
4+
6+
15+

1
2-127

t Note: The optional logical word length depends on the compiler.

Precision, range, and word length. The byte, the smallest addressable mem
ory element, consists of eight binary bits, equivalent to two hexadecimal characters.
Depending on the type of information and the desires of the programmer, com
puter words assigned to hold the values of constants or variables may be of length
1, 2, 4, or 8 bytes. A word of length 1, 2, 4, or 8 bytes is called a byte, half-word,
full-word, or double-word, respectively. The standard word size assigned by the
FORTRAN compiler for all integer, real, and logical constants and variables is
the full word. Variables of character type are assigned a standard length of one
character or byte, although the programmer may choose, as options, other word
sizes. The selection of lengths and magnitudes, where applicable, is shown in Table
9.1 (these options may differ for compilers run on machines other than the IBM
personal computer).
9-4

9. S Type Declarations
Constants of integer and logical type are always assigned to words of standard
length. Real constants of the F type are also always assigned to standard words.
Real constants with more than seven significant digits can be stored in the doubleword or double-precision form by the compiler, provided that the exponential type
of real constant is used with the letter E replaced by the letter D. Up to 15 significant
digits may appear. Examples of double-precision constants are:
1.7D10. 1.23456789012345D0. -6.655D-22. 1.D0

If word lengths other than the standard are to be used for variables, several
options are open to the programmer. The most straightforward approach is to
modify the type declarations as follows:
CHARACTERS t
INTEGER*2 t
LOGICAL*2 t
REAL* 8 t
Here, the variables in the list t will be assigned the appropriate type and storage of
the indicated length, in bytes. In the character declaration, b must be an unsigned
integer constant in the range 1 through 127 (see Chapter 11).
Examples
CHARACTER*5 INDEX. WORD
INTEGER* 2 G. N
LOGICAL*2 BOOL. SWITCH
REAL*8 ALPHA. BETA. MEAN

A statement completely equivalent to the declaration REAL*8 is the doubleprecision declaration


DOUBLE PRECISION t
Example
DOUBLE PRECISION

ALPHA. BETA. MEAN

Individual variables within a type declaration may also be specified to be of


particular length by appending *b to the variable name, where b is the number
of bytes to be assigned to that particular variable. If present, *b overrides the
assumed length for other variables in the list. For example, the declaration
REAL* 8

ALPHA. BETA. MEAN*4


9-5

Chapter 9Additional Declarations


will cause ALPHA and BETA to be assigned to double words while MEAN would be
designated as a full-word real variable.
On occasion, it is desirable to declare that all, or perhaps most, variables
are to be of nonstandard type or length. The IMPLICIT declaration is provided for
this purpose. For example, if all variables whose names begin with the letters A.
B . D . E . and F are to be double-precision real variables, all variables beginning
with the letters M. N. and P are to be integers assigned to half-words, and all
variables beginning with R are to be full-word integers, while the usual rules apply
for variables beginning with other letters, the declaration
IMPLICIT REAL* (A. B. D-F) . INTEGER*2(M. N. P) . INTEGER(R)
would accomplish the desired type and length assignments. First letters may also
be reserved for variables of character type; for example,
IMPLICIT CHARACTER*27(C. S-U)
would assign character type to variables whose first letters are C. S. T. and U;
each variable would be of length 27 bytes.
The IMPLICIT statement is particularly useful in convering a program from
single-precision (four-byte) to double-precision (eight-byte) arithmetic for all cal
culations. If the usual naming conventions have been used for all variables, this
conversion from single- to double-precision can be accomplished with the single
statement
IMPLICIT REAL*8(A-H. 0-Z)
One word of caution is in order here. The IMPLICIT statement also assigns the
given type to any function reference starting with the indicated letters. Such
an assignment may result in computational problems unless care is also taken to
insure that the functions are modified to accept double-precision arguments and to
return double-precision values. This is a simple matter when programmers supply
their own FORTRAN functions, and is described in Section 10.2. The IMPLICIT
declaration cannot change the single-precision nature of the library functions of
Section 2.5; the double-precision library functions described in Table 9.3 must
be used instead. Thus, if the preceding IMPLICIT declaration appeared in the
program, the following would be illegal:
A - SQRT(B)
C - 7.5*SIN(3.2*X + Y)
whereas
A = DSQRT(B)
C = 7.5*DSIN(3.2*X + Y)
would be acceptable (see below).
9-6

9.S Type Declarations


When present, there must be only one IMPLICIT statement in a program.
It must be the first statement in a main program (aside from an optional program
statement), and the second in a function or subroutine subprogram (see Sections
10.2 and 10.4). Any assignments made in a type or DOUBLE PRECISION declaration
override the implied assignments of an IMPLICIT declaration.
When two adjacent operands of different types and/or lengths are related by
an arithmetic operator in an arithmetic expression, one of the operands is normally
converted to the type and length of the other, and the result is also of that type
and/or length. The rules are that real takes precedence over integer, and that
greater precision takes precedence over lower precision. If X. Y. M. and N were of
type real-full, real-double, integer-half, and integer-full, respectively, the type and
lengths of the results for some typical operations would be as shown in Table 9.2.
Table 9.2 Examples Involving "Mixed" Operands
Expression

Type

Expression

Type

M + M

Integer*2
Integer*4
Real*4
Real*8
Integer*4
Real*8

M - X
M - Y
5*DSQRT(Y)
5.D0*SQRT(X)
M*SIN(X)

Real*4
Real*8
Real*8
Real*8
Real*4

2*M
2.*M
2.D0*M

M*N
X/Y + M

Double-precision function references. With the exception of the function


IABS, each of the functions listed in Section 2.5 requires a real argument of standard
length (four bytes) and returns a real value of standard length. They are called
single-precision functions. A comparable set of functions, called double-precision
functions, is also available. These require real arguments of double length and
return real values of double length. The names, listed in the same order as those
of the single-precision functions in Section 2.5, are given in Table 9.3.
Table 9.S Representative DoublePrecision Function References
DABS
DLOG
DLOG10
DACOS

DCOSH
DEXP
DSIN
DSINH

DASIN
DATAN
DATAN2
DCOS

DSQRT
DTAN
DTANH

Function references are of the same form as before. For example:


DSIN(3.D0)
has as its value the sine of 3 radians, accurate to at least 15 significant decimal
digits.
9-7

Chapter 9Additional Declarations


Assignment of dimensions and initial values in type declarations. The type
declarations may be used to specify the dimensions and initial values as well as
the types of variables. The general form is
T*b

Vl(dl)*bl/ Cl/. .../. Vn(dn)*bn/ Cn/

Here, T is one of the types INTEGER. REAL. L0GICAL. or CHARACTER. Vi, i = 1,


2, . . ., n are variable names that are to be of type T and of length bi bytes; bi
is optional, and, if absent, is assigned the value b. If "Vi is a subscripted variable,
then the dimensioning information is given by (di) where di is a string of integers,
separated by commas, and equivalent to those that would appear in a DIMENSION
declaration for the same variable (see Section 7.2). The optional entries /Ci/ are
the initial values to be assigned to Vi, and are equivalent to those that would
appear in a DATA declaration for the same variable. If b does not appear, then the
standard length is used.
Example

REAL*8 ALPHA (10. 5. 7) *4/ 350*1./. MEAN. DELTA(1O)/


2*5. DO. 8*0. D0/

is equivalent to the following:


REAL* 8 MEAN. DELTA
DIMENSION ALPHA (10. 5. 7). DELTA(1O)
DATA MEAN. DELTA. ALPHA/ 2*5. D0. 8*0. DO. 350*1./
Exercises for Section 9.3
1. Check true, or false, as appropriate:
(a)

The following is a valid FORTRAN statement:

X - DSQRT(4.0E1)
(b)

The statement REAL*8 X . Y . Z makes double precision all those variables whose names start with the
letters, X. Y. and Z.

T D

(c)

A variable may be made double-precision by appending D in front of its name.

T D

F D

(d)

The following statements will insure that a doubleprecision value of n, accurate to 11 digits, will be
stored in PI. (Assume the digits are correct.)

T D

F D

REAL*8 PI
PI - 3.1415926535
9-8

9.S Type Declarations


2. Suppose that the following declarations appeared in a FORTRAN pro
gram:
IMPLICIT REAL*8(A, F-H) , INTEGER(P)
INTEGER S. X, GO*2. MONTH*2
REAL ALPHA, GO2
DOUBLE PRECISION PFACTR. MEAN
LOGICAL G, SW*2
DIMENSION SW(10). GO(2)
What would be the types and lengths of the following FORTRAN expressions?
(a)
(b)
(c)
(d)

GO2 + GO (2)
S*MONTH + AL
PENNY*GO(1)
GO(1)/INT

(e) IABS(PS - NANCY) - DSIN(MEAN)


(f) X.LT.GONE .AND. SW(7)
(g) 5.37D-6*GO(2) - N*SQRT(ALPHA - BETA)
(h) FUN(PFACTR) - S/P

3. Convert the following program segment into double-precision form:


X - 3.7
Y 4.6
Z - X/SQRT(Y)
4. Consider the following program, in which all variables and arithmetic are
in single precision:

200

READ (5,*) A. B, C
Z - A + SQRT(B)/SIN(C) + 2.8
WRITE (6.200) A. B. C. Z
FORMAT (4F10.5)
STOP
END

Indicate the modifications needed for converting this to double-precision


form.
5. Write the appropriate declarations to indicate that all variables beginning
with the letters A-J , P , and X are of type real and length double, all variables
beginning with the letters R and Z are integers of length two, all variables beginning
with the letter T are of the type logical and length two, and that all other variables
follow the usual naming convention.
6. Explain in detail what each of the following declarations accomplishes:
(a)
1

INTEGER*2 D(4.4.2)*4/ 4*2. 8*-3. 20*0/. MAN (20) . JOE.


F(3.2)*4/6*5/

REAL MEAN(3.4.7)/ 42*1. E-25. 42*-l.E-25/. AL(10)*8/


5*5. 2D0. 5*0. DO/

(b)

9-9

Chapter 9Additional Declarations


9.4 The EQUIVALENCE Declaration
It is occasionally convenient to refer to the same storage location by two or
more different names. This is achieved by using the declaration
EQUIVALENCE

(Vl, V2, .... Vn)

Here, the "Vi, i 1 , 2, . . ., n may be either:


1.
2.
3.
4.

Simple variable names.


Array names.
Elements of an array.
Elements of a multidimensional array with a single equivalent subscript.

The listed variables may be of any type; types of individual entries need not agree.
Examples
1.

EQUIVALENCE (SPEED. VEL)

The variables SPEED and VEL could be used interchangeably.


2.

EQUIVALENCE (AVG. NANCY. SWITCH)

Assuming that AVG is of real type, that NANCY is of integer type, and that SWITCH is
of logical type, it would be unreasonable to use the three variables interchangeably.
In this case, the same location would serve to hold values of the variables of three
different types at different times during execution of the program.
3.

DIMENSION X(10) . Y(10)


EQUIVALENCE (G0. Y(2) . X(5))

The specification that Y(2) is to coincide with X(5) automatically assigns relative
locations to all other elements of the X and Y arrays; that is, this statement also
equates Y(1) with X(4) , Y(3) with X(6) , etc, as shown in the following alignment:
X(1) X(2) X(3) X(4) X(5) X(6) X(7) X(8) X(9) X(10)
Y(1) Y(2) Y(3) Y(4) Y(5) Y(6) Y(7) Y(8) Y(9) Y(10)
The location assigned to Y(2) and X(5) is also assigned to variable GO. Care must
be taken to avoid destroying the normal sequential arrangement of arrays.
Example (invalid)
EQUIVALENCE (Y(2). X(5) . Y(4))
9-10

9.4 The EQUIVALENCE Declaration


The most important use of the EQUIVALENCE statement is to save storage in
a program requiring large arrays that are used during only part of the execution of
the program. For example, suppose that a large matrix A, dimensioned to have 200
rows and 100 columns, is needed only during the first part of execution, while two
other arrays, a matrix M with 300 rows and 40 columns and a singly subscripted
variable DELTA with 3,000 elements, are not required until later in the execution
of the program, as shown in Fig. 9.1, in which the asterisks indicate the positions
of the designated array elements. The 20,000 full words (80,000 bytes) assigned
to A are more than adequate to hold the 12,000 words of M and the 3,000 words of
DELTA. Appropriate declarations for this situation are:
DIMENSION A (200. 100). M(300.40). DELTA (3000)
EQUIVALENCE (A.M). (A(1.61). DELTA)

or
DIMENSION A(200.100). M(300.40). DELTA(3000)
EQUIVALENCE (A(l.l). M(l.l)). (A(12001). DELTA(l))
*A(1,1) or
M(1,l)

*A(1,61) or
DELTA ( 1 )

A(1,60) or *
M(101,40)

3,000
Locations

12,000
Locations

A(200,l) or
*M(200,1)

A(200,60) or
M(300,40) *

A(200,75) or
DELTA(3000) *

A(l,100)*

5,000
Locations

A(200,100)

Fig. 9.1 Storage assignment for arrays A. M. and DELTA.


Observe that the first entry of an array can be indicated by the array name
alone. Care must be taken to assure that the usual FORTRAN storage conventions
have been used in assigning equivalent locations. In this example, M will occupy
the first 12,000 locations assigned to A. Because two-dimensional arrays are stored
column by column, this means that the 12,001st element of A is A(l .61). Elements
of multidimensional arrays may be specified with an equivalent single subscript that
takes into account the storage scheme used, as is illustrated by the final example
above. Note that more than one equivalence group can be assigned in a single
EQUIVALENCE declaration.
Exercises for Section 9.4
1. The sizes of three arrays A. MAT. and VEC are denned by:
DIMENSION A(50.100). MAT(250.10). VEC(1000)
9-11

Chapter 9Additional Declarations


The matrix A is needed only early in the program, at a stage when MAT and VEC
are not required. Later, when the elements of MAT and VEC are being manipulated,
there is no longer any need for A. Show, by means of an EQUIVALENCE declaration,
how the space originally occupied by A can be reused for storing MAT and VEC.
2. If any of the following are invalid, explain why:
(a)
(b)
(c)

EQUIVALENCE (V. Y(l)). (DVDT. Y(2))


EQUIVALENCE (Y(l) . VECTOR (7) . Y(9))
LOGICAL DECIDE
EQUIVALENCE (INTEGR. REALX. DECIDE)

3. After execution of the following what are the values of X(6) . X(9) .
Y(2). and Y(10)?

10

20

DIMENSION X(10). Y(10)


EQUIVALENCE (X(3) . Y(l))
DO 10 I - 1. 10
X(I) - I
CONTINUE
DO 20 I - 5. 10
Y(I) -1+4
CONTINUE

4. After execution of the following, what are the values of VEL. X(l) . and
Y(5)?

10

DIMENSION X(10). Y(20)


EQUIVALENCE (SPEED. VEL). (X(2) . Y(3))
SPEED - 10.5
DO 10 1=1.5
X(I) - FLOAT(I)
CONTINUE

9.5 Order of Statements in a FORTRAN Program


The order of executable statements in a FORTRAN program depends upon
the algorithm being implemented in program form. The order of nonexecutable
statements or declarations, however, depends to some extent at least on the con
struction of the compiler being used. Certain translators are "one-pass" compilers,
that is, the FORTRAN source program is scanned only once from the first state
ment to the last; object code for each statement is produced as it is encountered.
In contrast, the more common multipass compilers may examine the statements
in a subprogram more tha once before generating the final object code. Obviously
the one-pass compilers may require that certain restrictions on the ordering of
declarations be followed by the programmer.
9-12

9.5 Order of Statements in a FORTRAN Program

Table 9.8 Recommended Order of Statements


PROGRAM. FUNCTION. SUBROUTINE. or BLOCK DATA
IMPLICIT

Explicit type statements:


CHARACTER
DOUBLE PRECISION
INTEGER
LOGICAL
REAL
DIMENSION
COMMON
EQUIVALENCE
EXTERNAL. INTRINSIC
DATA

Statement Functions

Executable Statements (including OPEN and CLOSE)

FORMAT
END

To simplify the problem, we suggest the order shown in Table 9.4 for state
ments within a FORTRAN subprograms; most compilers allow considerably more
flexibility, but this order should satisfy even the most restrictive ordering rules.
FORMAT declarations may appear anywhere in the program after an IMPLICIT dec
laration and before the END declaration.

9-13

Chapter 9Additional Declarations


Notes

9-14

CHAPTER 10
FUNCTION AND SUBROUTINE SUBPROGRAMS

10.1 Introduction
Thus far, we have been concerned primarily with main programs, which have
the distinguishing feature that at execution time they are automatically started
with their first executable statement. In Section 2.5, we have also mentioned
that there are other types of programs, called functions, which conduct special
sequences of calculations when reference is made to them. Indeed, FORTRAN
recognizes four types of subprograms:
1.
2.
3.
4.

Main subprograms.
Function subprograms.
Subroutine subprograms.
Block Data subprograms.

This chapter is concerned with the second and third types of subprograms.
The reason for being interested in such subprograms is that we often wish
to repeat a particular algorithm, but to apply it to different values. Certain al
gorithms, such as those for computing the sine or square root of a number, are
so common that they have their own symbols. For example, sin x, sin(7.95), and
sin(62 - 4ac), all imply the same procedure, namely that the sine of some quantity
is desired, but that the quantity or argument itself (x,7.95,i2 4ac,etc.) differs
from one reference to the procedure to another.
It is clearly desirable to preserve the generality of a procedure for finding
sines of any number; otherwise, a separate algorithm would have to be written for
each possible argument that might be used! That is, one algorithm (program) for
finding sin a;, another for finding sin(7.95), and so forth.
Fig. 10.1 shows how a procedure for evaluating sines might stand in relation
to a main sequence that makes reference to the procedure. Suppose that the
procedure, named sin for short, is formulated for finding the sine of a hypothetical
quantity or dummy argument y. The understanding is that whenever a reference
is made to sin, the dummy argument y is assigned to the memory address of the
actual or calling argument whose sine is desired. Thus, the actions taken as a
result of the appearance of the references to the procedure "sin" that appear in
the calling program are:
10-1

Chapter 10Function and Subroutine Subprograms


1. Leave the main sequence of calculations in the calling program, enter the
procedure sin, and substitute the address of the calling argument x as the
address of the dummy argument y. Thereafter, any reference to the dummy
argument y in the procedure will cause the value in the memory location of
the actual argument x to be used in the calculation.

z^= sin(x)
Enter
Sequence of
calculations for
evaluating sin(y)
Return

Main sequence of calcu


lations (calling program)

Procedure sin with


dummy argument y

Fig. 10.1 Relation between calling program and procedure.


2. Perform the sequence of calculations in the procedure, which effectively com
putes sin x.
3. Return to the calling program with the computed value, at the point where
sin was originally referenced.
4. Store the returned value in the memory location assigned to variable z.
The other two references to the procedure occur similarly, except that the
two calling arguments are now the constant 7.95 and the expression b2 Aac (the
dummy argument y is assigned to the memory address where the value 7.95 or
b2 4ac is stored). The values returned by the procedure are stored in q2 and r,
respectively.
In formulating a flow diagram for a procedure, which will be distinct from
any flow diagram or diagrams in which reference is made to the procedure, the
following basic items must be considered.
1. A representative name must be selected to identify the procedure.
2. An appropriate dummy argument or arguments (some procedures require
more than one) must be selected.
3. It must be clear where the procedure starts or is entered, and where the
procedure return with results of the calculations to the calling program.
10-2

10.1 Introduction
Example
Draw a flow diagram for a procedure named AVG that computes xbar, the
average (arithmetic mean) value of the n elements of the vector x: xx,x2, . . . ,xn.
Here, n and x are two dummy arguments for the procedure.

( Enter 1

S - 0

_
s
* - n"

S = S + x.

Fig. 10.2 Flow diagram for procedure AVG.


Procedures such as AVG, shown in the flow diagram of Fig. 10.2, are called
in other flow diagrams by making reference to them at the appropriate point (s).
When a single value is returned by a procedure (as is xbar by the procedure AVG),
the reference normally has the form
xbar AVG(x,n)
where x and n are replaced by the calling arguments. For example, if the average
of the first m elements of an array p were required, then the calling flow chart
would contain a reference such as
pbar - AVG (p,m)
If the procedure has more than one dummy argument, then the actual ar
guments must be placed in the same relative position in the calling argument list.
For example, the dummy arguments n and x refer to the number of elements and
the name of the array, respectively; the actual arguments must therefore appear
in the list in the order p followed by m.
Sometimes, procedures produce more than one value as the result of cal
culation. For example, a procedure named SORT could sort the n elements of an
array x into ascending sequence. In this case, the dummy arguments are n and x,
but it would not make sense to refer to SORT as was done with AVG, that is with
s = SORT(n,x)
10-3

Chapter 10Function and Subroutine Subprograms


since there would be no single value associated with the name SORT to assign to the
variable s. In fact, the results of the calculation are communicated by one of the
arguments, x; that is, upon entering the procedure, the elements of the dummy
variable array x are unsorted, but on return they are in order. In such cases,
where there is no single value associated with the procedure name, the procedure
cannot be invoked implicitly simply by including a reference to it in an expression
of appropriate type; it must be called explicitly, for example:
CALL SORT(n,x)
In FORTRAN, procedures that return a value when referenced (such as
the procedure AVG above) are called function subprograms, while procedures that
must be called explicitly (such as the procedure SORT above) are called subroutine
subprograms. There is a large number of standard function subprograms (usually
simply called functions) in the FORTRAN library such as SIN. SQRT, etc, (see
Sections 2.5 and 9.3). There are no comparable standard FORTRAN subroutine
subprograms.
In addition , most computing-center libraries will contain many FORTRANcallable functions and subroutines for performing common numerical and statis
tical calculations. These functions and subroutines are already in object form
and can be referenced or called from any FORTRAN subprogram, including main
subprograms.
These library functions and subroutines have many advantages, among the
more important being:
1. Programmers need not prepare their own programs for evaluating common
functions, or carrying out standard calculations such as solving simultaneous
linear equations, or computing standard statistical quantities.
2. The library programs (often called library routines) can be used with com
plete confidence that they have been thoroughly tested and will produce the
specified results.
3. The same routine may be called by different FORTRAN programs, and,
indeed, may be called by the same program several times with different
arguments.
4. Only one copy of the object program for a routine is stored in the com
puter's memory, even when references are made to it by several different
subprograms, thus saving on storage requirements.
5. Overall efficiency of the computing facility is greatly improved. (Imagine
the problems that would be encountered if programmers had to write their
own programs to find square roots, values of trigonometric functions, and
logarithms, etc.)
6. By relegating some parts of the algorithm to procedures or subprograms,
complex algorithms can be segmented into smaller pieces that are easier to
program, debug, and document.
10-4

10.2 FUNCTION Subprograms


Frequently, programmers would like to segment the overall algorithm into
parts that are not already available as procedures in the form of FORTRAN or
library functions and subroutines. In such cases, FORTRAN allows programmers
to write their own procedures, which are then compiled into object form and can be
referenced (functions) or explicitly called (subroutines) exactly as are the library
functions and subroutines.
These essentially independent subprograms are usually called external func
tions and subroutines, because they are compiled independently of other programs,
and the object programs generated are loaded into areas of the computer memory
outside (external to) blocks of storage assigned to other subprograms. The writing
and use of external functions and subroutines will be covered in Sections 10.3 and
10.4, respectively.
10.2 FUNCTION Subprograms
The function subprogram, sometimes called the external function to distin
guish it from the internal function (see Section 10.7), has:
1.
2.
3.
4.

A name.
Zero or more dummy arguments.
A beginning or entry point.
A body of FORTRAN statements that compute a value for the function
reference.
5. An end or return point.

Every user-defined FORTRAN function subprogram must begin with a func


tion definition statement containing its name and arguments (and possibly its
type), and terminate with the END declaration. Between these two delimiting
statements there must be at least one statement to assign a value to the function
name and at least one RETURN statement to indicate when a return to the call
ing program is to occur. The general appearance of every FORTRAN external
function is:
T*b FUNCTION 7 (Al. Al

An)

FORTRAN executable statements and


declarations needed to evaluate the
function (the body of the function)
7 - or fl
RETURN
END

or C

Here, 7 is the name of the function; the naming convention is the same
as that for variables. T is the type of the value returned by the function; it is
an optional entry and, if present, must be either INTEGER. REAL. LOGICAL. or
10-5

Chapter 10Function and Subroutine Subprograms


CHARACTER. If the type is not specified, then the naming conventions for variables
apply; that is, if the name begins with one of the letters I . H. K. L. M. or N, the
value is a four-byte integer, otherwise it is a four-byte real number. The optional
entry *b (valid only if T is present) is discussed at the end of this section.
The entries Al, A2, . . ., An are the n dummy arguments for the function and
must be unsubscripted variable or array names or the dummy names of subrou
tine or other function subprograms. All dummy arguments that are array names
must appear in a DIMENSION declaration in the body of the function, as detailed
in Section 10.3. If the function has no arguments (very unusual) the FUNCTION
declaration appears as T*b FUNCTION 7 ( ).
The dummy arguments are assigned no memory locations inside the block
of the main memory where the instructions for the function are stored. When the
function is referenced in another subprogram, the addresses of the actual argu
ments effectively become the addresses of the corresponding dummy arguments.
If the actual arguments are scalar or array variables, the variable addresses are
used. If the actual argument is an expression other than a variable, then the
memory address containing the value of the constant or expression (the latter is
computed by the calling program before entry into the function) is assigned to the
corresponding dummy argument.
Once the argument names or addresses in the calling argument list have
been equated with those for the corresponding dummy arguments, the body of the
function is executed. Inside the function, 7 may be considered to be a simple
variable having the type and word length assigned to the function 7 .
The name 7 without attached arguments may appear virtually anywhere in
the executable statements of the body of the function that a simple variable of the
same type and length might appear. There is one exception: 7 may not appear
as a calling argument for another subprogram.
Also, / must not call upon itself (a process called recursion), either directly
or indirectly [7 cannot call on another subprogram if Q in turn calls on 7).
The function name must appear as the left member of an appropriate assignment
statement, at least once in the body of the function. Thus, one of the following
statement forms must appear somewhere at least once:
Type of 7

Assignment Statement

Integer or Real
Logical
Character

7 =
7= B
7 IC

When the execution of statements in the body is complete, and a value has
been assigned to 7 as indicated above, the return to the calling program is effected
by the statement
RETURN
10-6

10.2 FUNCTION Subprograms


The last value assigned to 7 in the function will be the value that is assigned to the
function reference in the calling program. Usually there will be one RETURN state
ment (or more, if appropriate) in every function. Once the function is called, or
entered, calculation continues in the body of the function until a RETURN statement
is encountered. The function then transfers control back to the calling program
where it was originally called. The last statement in every function subprogram
(and indeed in every subprogram) is
END
The END statement is executable. If END is executed, calculation in the function
ceases and an automatic return to the calling program takes place, i.e. , END can
act as a substitute for RETURN. For program clarity, we recommend that RETURN
statements be used.
The names selected for the dummy arguments and for all the variables in
the body of the function have no relationship whatsoever with variables of the
same names in the main program or other function or subroutine subprograms
unless they are associated with one another by occupying the same relative po
sitions in the lists of calling and dummy arguments. With this one exception, a
variable named X in one subprogram is unrelated to a vaiable named X in another
subprogram, since each subprogram is compiled separately. (The programmer also
has the option of deliberately equating variables in different subprograms with the
COMMON declaration, to be discussed in Section 10.8.)
Thus, the programmer can choose quite arbitrary names for dummy argu
ments and local variables (variables that are not dummy arguments) in the function
without fear that a particular name has already been given some other meaning
in another program.
The algorithm for computing the value of the function reference appears
as the body of the function and may contain any of the FORTRAN statements
described in the preceding sections. (It is unusual, however, for input statements
to appear in functions.)
In the calling program, which will be another subprogram, the function ref
erence must appear as part of, or the whole of, an arithmetic, logical, or character
expression, depending upon the type of the function value. The function reference
will have the general form
7 {AU, A2*, ... , An*)
where the Ai*, i = 1, 2, . . ., n are the actual or calling arguments that are associ
ated with the dummy arguments Ai, i = 1, 2, . . ., n of the function. The actual
arguments Ai* in the calling sequence must correspond in number, order, and type
with the dummy arguments in the FUNCTION statement.
If a dummy argument is the name of an array, then the corresponding call
ing argument must also be the name of an array (or possibly an element of an
10-7

Chapter 10Function and Subroutine Subprograms


array, as described below). If the dummy argument is the name of a dummy sub
program, then the corresponding calling arguments must be the name of an actual
subprogram (this possibility is also discussed later in this section). If the dummy
argument is a simple variable of integer, real, logical, or character type, then the
corresponding calling argument in general may be any expression of that type.

Example Program 10.1Function for Array Averages


We wish to write a function, named AVG, with dummy arguments X and N,
and with the heading:
FUNCTION AVG (X. N)

The function is to compute the average value of the N elements of the vector X
according to the steps outlined in Section 7.3, and is to be tested by referrring to
it in a main subprogram named AVTEST.
Programs
PROGRAM AVTEST
C

Main program for testing function AVG.

Declarations
DIMENSION V(10). Y(25)
DATA V / 10.2. 99.4. 43.1. 46.8. 3.7.
1
25.1. 77.0. 61.3. 29.9. 49.6/
OPEN (5. FILE-' AVTEST. DAT')

C
C

Average of 10 elements in vector V


(already stored by the DATA statement)
WRITE (6.201) 10. (V(I). I - 1. 10)
VBAR = AVG(V. 10)
WRITE (6.202) VBAR

C
C

Read M and the elements of vector Y and compute their average


READ (5.101)
M. (Y(I). I - 1 . M)
WRITE (6.201) M. (Y(I) . I = 1 . M)
WRITE (6.202) AVG(Y. M)
STOP

C
101

Formats for input and output statements


FORMAT (15/ (5F10.1))
10-8

10.2 FUNCTION Subprograms


201
1
202

FORMAT ('OThe '. 12. ' elements of the array are:'/


/ C '. 5F8.1))
FORMAT ('OThe average of the elements is: ' . F7.1)
END

FUNCTION AVG (X. N)


C
C

External function for computing the average


of the N elements of the vector X.

C
C
C

Declaration to indicate that X is a


singly subscripted array.
(Does not
allocate storage - see Section 10.3) .
DIMENSION X(N)

10
C

Compute average in the usual way


SUM = 0.
DO 10 I = 1. N
SUM - SUM + X(I)
CONTINUE
Return with average in AVG
AVG - SUM/N
RETURN
END

In the main program, there are two references to AVG. First, the average of
the 10 elements of the vector V is determined by AVG and stored in the variable VBAR,
which is then printed. In the second reference, AVG appears as a real expression
directly in a WRITE statement; thus, the average of the M elements in the vector Y
is determined and printed immediately.
In the function, note that the dummy argument X has been dimensioned, as
required, and that the name of the function, AVG, appears in the left member of
an assignment statement preceding the return to the calling program.
Data (M, and the elements of the vector

22
4.4

111.0
872.7
900.2
289.5

546.2
203.3
103.2
61.9
460.2

987.1
941.3
343.6
205.3

57.6
487.7
707.8
710.0

10-9

293.0
771.5
423.9
13.7

Chapter 10Function and Subroutine Subprograms


Output
The 10 elements of the array are:
10.2
25.1

99. 4
77.0

43.1
61.3

46.8
29.9

The average of the elements is:

3.7
49.6
44.6

The 22 elements of the array are:


4.4
111.0
872.7
900.2
289 .5

546.2
203.3
103.2
61.9
460 . 2

987.1
941.3
343.6
205.3

57.6
487.7
707.8
710.0

The average of the elements is:

293.0
771.5
423.9
13.7

431.6

Examples of other possible references to the function AVG:


1.

XMEAN - AVG(X. N)

The average of the first N elements of the array named X is computed and
assigned to the variable XMEAN. Coincidentally, the names of the calling arguments
are identical with the names of the dummy arguments used in AVG.
2.

Y(7) - 3. /AVG (BETA. K+2)

When the dummy argument is a simple variable (N), the corresponding


calling argument may be an expression of the same type, such as K + 2. Thus,
the value of N used in the function is two greater than the value of K in the calling
program.
3.

SVAR - (SUMSQ - N*AVG(Z. INT)**2)/(N - 1.)

The average of the first INT elements of an array Z is computed and used in
the evaluation of a rather complicated expression.
4.

IF (AVG (GAM. 2+J*K) .LE. X/P + 7.5) P - SQRT(DEL)

Reference to AVG may occur anywhere that an arithmetic expression is appropriate.


10-10

10.2 FUNCTION Subprograms


5. Two groups A and B contain NA and NB people, respectively. Their ages
(real) are stored in the vectors A and B, respectively. Write a program that will
accept this information and display a message as to which group is older; assume
for simplicity that there is no chance of a tie.
A complete main program (definitely of inferior qualitythere are no com
ments and it has not been checked by compiling and running) that calls upon the
function AVG twice to solve the problem, is:

100

DIMENSION A(50). B(50)


READ (5.100) NA. NB. (A(I) . I - 1. NA) . (B(I). 1=1. NB)
IF (AVG(A.NA) .GT. AVG(B.NB)) THEN
WRITE (6.*)
'Group A is older'
ELSE
WRITE (6.*) 'Group B is older'
END IF
STOP
FORMAT (2I5/U0F8.1))
END

Functions may compute more than one value, in which case some of the
dummy arguments can also be used to return results to the calling program, in
addition to the return of the single value associated with the name of the function,
7. In these cases, the appropriate dummy argument(s), A for example, would
appear in assigment statement(s) such as:

A = t
or
or

A = B
A = C

When such an assignment is made, it is essential that the corresponding calling


argument A* be a variable, and not a more general expression, since there would
be no associated memory location in the calling program in which to store the
value (that the FORTRAN programmer would have access to). The assignment
of some results to dummy arguments is now illustrated.
Example
A company runs N stores, and records the monthly profit for each store over
a period of M months. Denote the profit made during the Ith month by the Jth
store as P(I.J), and suppose that the P(I.J) have been assigned values for 1 <
I<M. 1<J<N. Write a function, named PROFIT, that will return:
1. As its value, the total profit made by all the stores over all the months.
2. By assignment to dummy arguments, the greatest profit PMAX made by any
store in any month, and the corresponding month and store numbers, IMAX
and JMAX, respectively. Assume for simplicity that PMAX occurs for only one
store in only one month. An appropriate function is:
10-11

Chapter 10Function and Subroutine Subprograms

5
10

FUNCTION PROFIT (M. N. P. PMAX. IMAX. JMAX)


DIMENSION P(24.50)
PROFIT = 0.
PMAX = P(l.l)
IMAX = 1
JMAX = 1
DO 10 I - 1. H
DO 5 J = 1. N
PROFIT = PROFIT + P(I.J)
IF (P(I. J) .GT. PMAX) THEN
PMAX = P(I.J)
IMAX - I
JMAX = J
END IF
CONTINUE
CONTINUE
RETURN

END
Note that the function name PROFIT has been used as an ordinary real
variable in the body of the function, and that values will be assigned by the
function to the calling arguments corresponding to the dummy arguments PMAX .
IMAX, and JMAX. A valid reference to the function PROFIT in a calling program,
provided that PROF were appropriately dimensioned (see Section 10.3) would be
INTEGER STORE
DOLLAR = PROFIT (NMONTH. NSTORE. PROF. PMAX. MONTH. STORE)
Upon return from the function, the following variables would have the indicated
information:
DOLLAR

Total profit made by all the stores.

PMAX
MONTH
STORE

The largest profit made by a single store.


Number of month in which PMAX occurred.
Number of store that made PMAX.

Notes on the Type and Length of Functions. If, in the function heading,
7*b FUNCTION 7 (Al, A2, ...,An)
the type T is omitted, then the entry *b must not appear. If the type is specified,
however, then *b may appear as an option, and indicates the length, in bytes, of
the function value. Only those combinations of standard and optional type and
length listed in Section 9.3 may appear. The examples shown in Table 10.1 should
clarify the situation:
10-12

10.2 FUNCTION Subprograms


Table 10.1 Functions of Different Type and Length

Function Value
Length (bytes)
Mode or Type

FUNCTION Statement

Real
Real
Illegal
Real
Integer
Integer
Illegal
Logical
Logical
Character
Character

FUNCTION F(
)
REAL*8 FUNCTION F(
)
FUNCTION F*8(
)
DOUBLE PRECISION FUNCTION F(.
INTEGER FUNCTION F(
)

INTEGER*2 FUNCTION F(.


INTEGER*8 FUNCTION F(.
LOGICAL FUNCTION F(. ..
LOGICAL*2 FUNCTION F(.
CHARACTER FUNCTION F(.

...)
...)
.)
...)
...)

CHARACTER*25 FUNCTION F(

Four
Eight
Eight
Four
Two
Four
Two
One
Twenty-five

The type of value returned by the function may also be specified by an IM


PLICIT declaration (see Section 9.3); if present, the IMPLICIT delcaration must be
the second statement in the function definition, immediately following the FUNC
TION statement. The function type can also be specified in an explicit type decla
ration.
Examples
1. FUNCTION MOVE(...)
IMPLICIT REAL*8(M)
2. FUNCTION WORD(...)
IMPLICIT CHARACTER*5(S-Z)
FUNCTION MOVE(.
REAL*8 MOVE

.)

If the function has a type and length that do not conform to the usual
naming conventions for variables, then the function name must also appear in a
type declaration in the calling program where it is referenced. For example, if the
double-precision function MOVE were defined as shown in the above examples, then
the declaration
REAL*8 MOVE
must appear in the calling program.
The dummy arguments that are variables, array, or function names may be
of any standard or optional type and word length (see Section 9.3). The type and
10-13

Chapter 10Function and Subroutine Subprograms


length of variables that do not conform to the usual naming conventions may be
specified implicitly with the IMPLICIT declaration or explicitly with an appropriate
type declaration in the body of the function. Every function must have at least
one argument.
Example
REAL*8 FUNCTION PRIME (DELTA. MAX. N. X. NUMBER. M. Y)
IMPLICIT REAL*8(A-M)
REAL N
INTEGER M. X*2

In this case, the following type and length assignments will be made:
Name
PRIME
DELTA

MAX
N
NUMBER

M
X

Mode or Type

Length (bytes)

Real
Real
Real
Real
Integer
Integer
Integer

Eight
Eight
Eight
Four
Four
Four
Two

Exercises for Section 10.2


1. Check true, or false, as appropriate.
(a)

The declaration END is needed at the end of a main


program, but not always at the end of a function sub
program.

T D

(b)

Variables in a function always have the same values


as variables of the same name in a main program that
calls on the function.
In the example below, the fourth statement contradicts the second statement and is therefore in error:

T D

F D

T D

F D

T D

F D

(c)

REAL*8
FUNCTION P (DELTA. MAX. N. X. NO. M. Y)
IMPLICIT REAL*8 (A - M)
REAL N
INTEGER M. X*2

(d)

The following are acceptable as the first two statements of a FORTRAN function:
FUNCTION DEGREE (A(3) . B)
DIMENSION A (10)
10-14

10.2 FUNCTION Subprograms


2. After execution of the following main program segment, what are the
values of all the variables A . B . C . X . Y . and Z in the main program?
Main Program Segment
X
Y
Z
A

10.
4.
DIVIDE (X.
6.

B - 3.
C - DIVIDE (B.

Function

DIVIDE

FUNCTION DIVIDE (A.


DIVIDE A/B

Y)

B)

RETURN

END
A)

3. The factorial of a non-negative integer N is defined asN! = lx2x3x


xN for N > 1, and as 1 for N = 0. Write an integer function, named FACT, that
will compute and return as its value the factorial of the dummy integer argument
N, assumed to be non-negative. Which (if any) of the following references to FACT
would be legal?
(a)
(b)
(c)

X - FACT(M)
IF (FACT(I**2) .GT. 100)
J - FACT (7.)

GO TO 3

4. After execution of the following, what are the values of the variables A .
B. C. D. E. and F in the main program?
Mam Program Segment

Function

E - 6.
F-3.
D - SUB (E + 1 . . E - F)
B - 7.
C - 2.
A - SUB (SUB(B+2.. B-2.). C)

SUB

FUNCTION SUB (P. Q)


SUB-P-q
RETURN
END

5. Write a logical function named CHECK, with dummy arguments V and N


that will examine the N elements V(l)
V(N) of the vector V. If the number of
elements with positive values exceeds the number of elements with zero or negative
values, the value returned by CHECK is to be .TRUE. Otherwise, the value returned
by CHECK is to be .FALSE.
6. The Fibonacci sequence of integers F.. is given by:
F0 = l;

Fi = l;

F< = P|-x + F^a,

t = 2,3, ...

Write an integer FORTRAN function, to be named FIBON, with a single


argument N (> 0), that computes as its value F;v, the Nth Fibonacci number.
10-15

Chapter 10Function and Subroutine Subprograms


7. A function f(x) has the appearance shown in Fig. 10.3. Write a FOR
TRAN function named F, with the single argument X, that calculates and returns
the value of f (X) .
f (x)

Constant
Value
Constant
Value
Fig. 10.S Function f(x).
8. A prime number n is divisible without remainder only by itself and one.
For example, with n = 47, if we examine possible factors 2, 3,..., 46, we find
that none of them divides n exactly. In practice, we need only examine possible
factors as far as the square root of n (rounded down to the next lower integer);
for example, for n = 46, we actually only have to check as far as 6 for a divisor.
Write a logical function, named PRIME, with a single dummy argument N that will
return a value .TRUE. if N is prime, and .FALSE. otherwise. (Assume that N is a
positive integer, no larger than one million.)
9. Examine the following FORTRAN programs carefully:
DIMENSION A (100)
READ (5.101) N. X
READ (5.102) (A(I). I = 1. N + 1)
P = EVAL (N. A. X)
WRITE (6.200) N. X. P. (A(I) . I 1. N + 1)
GO TO 1
101 FORMAT (15, 5X. F10.3)
102 FORMAT (5F10.3)
200 FORMAT C0'. 'N '. 15. 5X. "X ' . F10.3.
1 5X. 'P = '. F10.3/ C0", 5F10.3))
END
1

FUNCTION EVAL (N. A. X)


DIMENSION A (100)
EVAL = 0.
DO 10 I - 1. N + 1
EVAL - EVAL + A(I) *X**(I-1)
10-16

10. S The Dimensioning of Arrays in Subprograms


10

CONTINUE
RETURN
END

Data
12
3
Col: 123456789012345678901234567890
2
2.000
3.000
-1.000
2.000

(a)
(b)
(c)
(d)

In a few words, what do these programs accomplish?


In symbolic form, what value does EVAL return to the calling program?
What value will be printed for P for the given set of data?
Draw a diagram, clearly indicating exact column and line positions, that
shows the appearance of the computer output for the given set of data.
(e) Would the program produce the correct result for X equal to zero? If not,
how would you modify the program to allow for this possiblity?

10.3 The Dimensioning of Arrays in Subprograms


Every subscripted variable that appears in a function must be dimensioned
in the function. The dimensioning of arrays that are dummy arguments for the
function is handled somewhat differently from the dimensioning of arrays that are
not.
Subscripted variables that are not dummy arguments must be dimensioned
in the usual way (see Section 7.2). Storage for such arrays appears inside the
object program for the function. Consequently, the precise arrangement of the
array must be known before the function is compiled; the maximum value of each
subscript must be specified as an integer constant.
However, dummy arrays (array names that appear in the dummy argument
list), require no storage, since they are replaced by calling array names, for which
storage has been reserved in the calling program. However, the name of the dummy
array must still appear in a DIMENSION declaration inside the subprogram, for the
following two reasons.
First, since the compiler translates each subprogram independently, it must
be able to distinguish between subscripted variables and function references by
examining only the FORTRAN statements in the function definition. Since both
array and function names are immediately followed by parentheses, the appearance
(or absence) of the name in a DIMENSION declaration indicates that it is an array
name (or a function name) .
Second, for arrays with two or more subscripts, it conveys vital storage
information. Recall from Section 7.2 that such arrays are always stored internally
with single subscripts. For example, for the 2 by 3 matrix A, the equivalence is
shown in brackets:
10-17

Chapter 10Function and Subroutine Subprograms


1(1.1)
1(2.1)

[=K1>]
[= 1(2)]

1(1.2)
1(2,2)

[-1(3)]
[- 1(4)]

1(1.3)
1(2.3)

[-1(5)]
[- 1(6)]

Observe that if 1(1 . J) is stored as 1(K), then the translation from double to single
subscripts and vice versa is given by:
K - I + (J - 1)*NROWS
J = (K - D/NROWS + 1
I - K - (J - 1)*NROWS

(using integer division)

Here, NROWS (2 in the example) is the number of rows of the matrix, and clearly
plays a key role in the translation scheme. (In contrast, the number of columns is
not involved.) It follows that if the calling program has indicated a certain value
for NROWS, then the subprogram must also indicate the same value, otherwise twodimensional array elements will not be retrieved correctly from memory. In the
few cases in which triply subscripted arrays are employed, the upper limits on the
first two subscripts must then agree in the calling program and the subprogram,
for a similar reason. There is no problem if only a single subscript is involved.
To summarize, there must be essential agreement between the dimensions
of a multidimensional array in a calling program and its corresponding dummy
subprogram arguments.
With the above in mind, there are three alternatives for the upper limits for
the subscripts of dummy arrays:
1. Integer constants, as in DIMENSION 1(5.10), which is acceptable as long as
the coresponding calling array name has also been dimensioned to have the
same number of rows. However, it would preclude use of the subprogram
with another calling program in which the array name were dimensioned
to have a different number of rows. Thus, if fixed dimensions are used for
multidimensional dummy arrays, the generality of the subprogram is severely
limited. For singly subscripted arrays, there is no problem. For example,
any of the following declarations would be acceptable in the function 1VG of
Example Program 10.1:
DIMENSION X(1)
DIMENSION X(10)
DIMENSION X(100)
2. Integer dummy argument values, as in DIMENSION 1(M,N), where values of
the dummy arguments M and N are supplied by the calling program (or that
are assigned to COMMON storage, as described in Section 10.9). This is an
example of a variable-size array, and is much more flexible, since the sub
program can now be used in conjunction with a variety of calling programs,
in which the calling arrays could have various numbers of rows.
10-18

10. S The Dimensioning of Arrays in Subprograms


Variable dimensions may be used only in function and subroutine subpro
grams, and then only for array names that are dummy arguments; they can never
be used in main subprograms, or for array names in function or subroutine sub
programs that are not arguments.
Example
If two integer variables are added to the dummy argument list for the func
tion PROFIT of Section 10.2, so that the FUNCTION and DIMENSION statements are:
FUNCTION PROFIT (M. N. P. PMAX. IMAX. JMAX. NROWS. NCOLS)
DIMENSION P (NROWS. NCOLS)

then the calling program might contain the statements


DIMENSION PROF (24. 50)
DOLLAR - PROFIT (NMONTH. NSTORE. PROF. PMAX. NMMAX. NSMAX.
1
24. 50)
or perhaps
DIMENSION PROF (12. 75)
DOLLAR - PROFIT (10. 50. PROF. PMAX. NMMAX. NSMAX. 12. 75)

and no change would need be made in the DIMENSION declaration in PROFIT. The
combination
DIMENSION PROF (12. 75)
DOLLAR = PROFIT (10. 50. PROF. PMAX. NMMAX. NSMAX. 10. 50)

would lead to inconsistent subscription, however. The variable dimensions should


correspond to the actual dimensions, and not to the number of elements in the
array that are being used.
3. An asterisk is also permitted in place of the upper limit for the last
subscript, as in:
DIMENSION X(*). A(24.*)
Finally, any array element may be used as a calling argument corresponding
to a dummy array name in a function. The calling array element is treated as if it
were the first element of the dummy array; the correspondence between elements of
the calling and dummy arrays can be established by accounting for the sequential
storage scheme used by FORTRAN. For example, suppose that we wished to find
the average value abar of elements in the matrix A that lie in the jth column
between the kth and mth rows inclusive; that is
10-19

Chapter 10Function and Subroutine Subprograms

abar =

> a..,..

m - k + 1 f-'
'
i=fc
Then, using obvious FORTRAN names, the function AVG of Example Program
10.1 could be called to compute the average in a calling program as follows:
ABAR - AVG(A(K.J). M-K+l)
This is feasible because matrices are stored column-by-column, so that the cor
respondences between the calling array A and the dummy array X are: [A (K.J) .
1(1)]. [A(K+1.J). 1(2)]. ..., [A(M.J). X(M-K+1)]. This feature should be
used only if the storage allocation scheme for arrays is thoroughly understood by
the programmer.
10.4 SUBROUTINE Subprograms
A FORTRAN subroutine subprogram is a procedure with a name, a set of
zero or more dummy arguments, an entry point, a return point, and a body con
sisting of FORTRAN executable statements and declarations. The most significant
difference between a FORTRAN subroutine and a FORTRAN function is that a
function returns a value associated with its name; a subroutine does not. All re
sults of calculations in the subroutine must be returned to the calling program
through the argument list, in a manner similar to that already described for the
function PROFIT in Section 10.2 (or through common storage, described later in
Section 10.8).
The key statements in the definition of a subroutine are
SUBROUTINE 7 (Al. A2

An)

FORTRAN executable statements and


declarations needed to perform the
subroutine calculations (the body
of the subroutine)
RETURN
END
The subroutine name 7 follows the same rules as for variable names except
that the first letter has no special significance, since there is no type associated
with the subroutine name. There is no assignment statement of the form 7 = E .
Since a subroutine has no value, it may not be referenced implicitly in an
arithmetic, logical, or character expression. Instead, it must be invoked explicitly
in a calling program with the statement
CALL 7 (Al*. Al*

An*)
10-20

10.4 SUBROUTINE Subprograms


where the Ai*, i = 1, 2, ..., n, are the n actual or calling arguments that will
replace the dummy arguments Ai, i = 1, 2, . . ., n, during the execution of the
subroutine. Most of the material in Sections 10.2 and 10.3 describing the behavior
of function subprograms carries over directly to subroutine subprograms. The
number, order, and types of calling and dummy arguments must agree. Variable
dimensioning of dummy arrays is permitted. Normally, there will be at least one
RETURN statement, and there may be more than one. As for functions, either the
END or RETURN statement causes an immediate return to the calling program.
Example
Write a subroutine, named CMPLEX (why not COMPLEX?), that will compute
the magnitude of r and the angle 6 in the polar representation of a complex number
having real and imaginary parts i and y. Assume that r and 9 are given by
r = (x2 + y2)1/2,
6 = arctan(y/z).
Use the names X. Y. R. and THETA, with obvious interpretations.
The FORTRAN statements defining the subroutine CMPLEX are:
SUBROUTINE CMPLEX (X. Y. R. THETA)
R - SQRT(X**2 + Y**2)
THETA - ATAN2(Y. X)
RETURN
END

Some possible statements appearing in calling programs are:


CALL
CALL
CALL
CALL

CMPLEX
CMPLEX
CMPLEX
CMPLEX

(X. Y. R. THETA)
(XREAL. YIMAG. RADIUS. PHASE)
(2.9. B - 7.6. X(4) . Y(4))
(A - B*SIN (ALPHA) . Z(29) . R. PHI)

In each case, the first two arguments serve to supply values to the subrou
tine. In general, such arguments may be expressions, in which case values will
be computed for them before entering the subroutine. The last two arguments
indicate where the computed values returned from the subroutine are to be stored.
Such arguments must be variable names, possibly with subscripts. For example,
the following call would be meaningless, because there is no indication as to where
the computed values are to be stored:
CALL CMPLEX (X. Y. 2.0. A + B)
10-21

Chapter 10Function and Subroutine Subprograms


The following calls would also be improper:
CALL CMPLEX (X. Y. R. THETA. EPS) - too many arguments
CALL CMPLEX (I. J. R. THETA)
- incorrect type for the
first two arguments
Example
Write a subroutine named MAXMIN that will find the maximum and minimum
values AMAX and AMIN in the matrix A having M rows and N columns. The names
M. N. A. AMAX. and AMIN are the dummy names to be used in the subroutine;
the actual arguments in the calling program may, of course, have different names.
Assume that the actual array will be dimensioned to have M rows and N columns.
The defining FORTRAN statements are:

10
20

SUBROUTINE MAXMIN (M. N. A. AMAX. AMIN)


DIMENSION A(M.N)
AMAX - (1.1)
AMIN - (1.1)
DO 10 I - 1. M
DO 20 J - 1. N
IF (A(I.J) .GT. AMAX) THEN
AMAX A(I.J)
ELSE IF (A (I. J) .LT. AMIN) THEN
AMIN - A(I.J)
END IF
CONTINUE
CONTINUE
RETURN
END

The algorithm assigns the first element A(l . 1) to both AMAX and AMIN. Thereafter,
each element of the array is checked against AMAX and AMIN. If an element larger
than AMAX or smaller than AMIN is subsequently found, AMAX or AMIN is assigned
the new value. Some possible calling statements are:
CALL MAXMIN (M. N. VELOC. BIG. SMALL)
CALL MAXMIN (5. 6. AA. AAMAX. AAMIN)

Variable dimensions have been used in the subroutine. Therefore, in the first
case, the values of M and N should be the values of the row and column dimensions
for the array VELOC. Similarly, the array AA in the second example should be
dimensioned to have five rows and six columns.
A subroutine may be defined to have no arguments, in which case the SUB
ROUTINE statement has the form
SUBROUTINE 7
10-22

10.4 SUBROUTINE Subprograms

This situation usually arises only when all of the information needed by the sub
routine is available in COMMON storage, described in Section 10.8.
Normally, when a RETURN statement is encountered in a subroutine, con
trol passes back to the calling program with execution resuming at the statement
immediately following the CALL statement. In subroutine, but not function subpro
grams, the RETURN statement may be modified in conjunction with some compilers
to have the form
RETURN I
where I is either an unsigned integer constant or an integer variable of standard
length. The parameter I allows the subroutine to return control to particular
statement numbers in the calling program. This alternative return feature is im
plemented rather awkwardly, as follows. Asterisks may appear as elements of the
dummy argument list:
SUBROUTINE 7 (ill . A2. *. AA. *

An)

Wherever asterisks appear in the dummy argument list, statement numbers pre
fixed by asterisks must appear in the calling program in the actual argument list
in the CALL statement:
CALL 7 (Al*. A2*. *Ml. A4*. *M2

An*)

In this example, there are just two statement numbers, Ml and .A/2, shown, but
there could be any number in any argument position.
If the modified RETURN statement
RETURN I
is encountered in the subroutine and I has the value of 1 then control returns to
the statement in the calling program with the statement numbered Ml] if I has
the value 2 then control is returned to the statement numbered M2 in the calling
program, and so forth.
Example f
Write a subroutine named TESTC that examines a dummy variable, named
CHAR, of character type and length 1 and determines if it contains a letter, a blank,
a digit, or a special character. If the character is a letter, then the normal return
should be used; if the character is a blank, a digit, or a special character, then
the alternate return feature should be used to return to three different numbered
statements in the calling program.
t Material on character type in Chapter 11 should be read before examining this example.

10-23

Chapter 10Function and Subroutine Subprograms


Knowledge of the ASCII codes shown in Table 11.1 is needed to solve this
problem. Some of the symbols of interest appear in groups within ranges of code
numbers as shown in Table 10.2.
Table 10.2 Code Ranges for Symbol Subsets
Symbol Subset

Letters
Digits
Blank
Special
characters

Range
Lower Limit
Character
Code
65
A
0
48
32
!

33
58

Upper Limit
Character
Code
Z
90
9
57
/
?

47
63

A FORTRAN subroutine to identify the character type follows:


SUBROUTINE TESTC (CHAR. *. *. *)
CHARACTER CHAR
IF (CHAR.GE.'A' .AND. CHAR.LE.'Z') THEN
RETURN
ELSE IF (CHAR.EQ. ' ') THEN
RETURN 1
ELSE IF (CHAR.GE. '0' .AND. CHAR.LE.'Q') THEN
RETURN 2
ELSE
RETURN 3
END IF
END

Suppose that the following statements appear in a calling program:


CHARACTER SYMB
CALL TESTC (SYMB. *20. *30. *40)
RETURN FOR SYMB A LETTER. . .

C
10

.RETURN FOR SYMB A BUNK.

20
..RETURN FOR SYMB A DIGIT.

30
10-24

10.4 SUBROUTINE Subprograms

RETURN FOR SYMB A SPECIAL CHARACTER


40

Then, after TESTC is called, it will return control to the statements numbered
10. 20. 30. or 40. if CHAR contains a letter, blank, digit, or special character,
respectively.
Exercises for Section 10.4
1. Check true or false, as appropriate:
(a)
(b)
(c)

A subroutine cannot have more than one RETURN


statement.
A subroutine may include a READ statement.
The subroutine whose name is PAGE returns a real
value associated with its name.

T D

F D

T D

F D

2. Consider the following two subprograms:


Main Program
A = 10.
B * 2.
C = 4.
CALL TEST (A.
CALL TEST (3.

Subroutine

TEST

SUBROUTINE TEST (ABLE. BAKER)


IF (ABLE .GT. BAKER) THEN
BAKER - ABLE
END IF
RETURN
END

B)

. O

After execution of the above main program segment, what are the values of the
variables A . B . and C?
3. After execution of the following main program segment, what are the
values of A . B . C . X . Y . and Z in the main program?
Subroutine

Main Program
DATA
DATA
CALL
CALL

A.
X.
S
S

B.
Y.
(A.
(Z.

C/
Z/
B.
Y.

2 . . 3 . . 4./
2. . 3... 4./
C)
X)

SUBROUTINE S (X. Y. Z)
X = l./X
Y = Z**3
RETURN
END

4. Write a FORTRAN subroutine, with the heading:


SUBROUTINE FUNX (X. EPS. LOG1PX. N)

10-25

Chapter 10Function and Subroutine Subprograms


that approximates ln(l + x) with its series expansion:
x3

i3

x*

ln(l + s) = x-y + 1--T + ...7=F


Values for the dummy arguments X . EPS . and N are supplied by the calling pro
gram, and LOG1PX is returned as the value of the series. X corresponds to x, and the
series is to be terminated either when the absolute value of the current term being
added or subtracted becomes less than the small tolerance EPS (algebraically, e),
or the number of such terms equals N.

10.5 Multiple Entry PointsThe ENTRY Statement


Subprograms that have several statements in common or that require large
local (that is, not dummy) arrays may often be combined into one subprogram
with several different entry points, one for each subprogram name. [Note: this
feature is not available in MS FORTRAN.] This merging of routines leads to more
compact FORTRAN programs, and may save considerable storage. For example,
the algorithm for computing the sine function is clearly very similar to that for
computing the cosine function, since cosx = sin(x+ jt/2). And, in fact, the library
functions SIN and COS of Section 2.5 are not independent functions, but represent
two different entry points to a single subprogram.
The entry point for a function with a single name is the FUNCTION statement
itself. When a function has more than one entry point, the ENTRY statement is
used; such functions have the following general appearance:

T FUNCTION 7*l*b (All. Al2

ENTRY 72 (A2l. ATI

Jl2n2)

ENTRY 7Z (AZl. A32

X3n3)

ENTRY Jm (Ami. Am2

>lmnm)

yUnJ

END
Here, the 7j, j = 1, 2, ..., m, are the m different function names, and the yJji,
i = 1, 2, ..., ny, are the n, dummy arguments associated with the jth function
name 7j. The FUNCTION statement has already been described in detail in Section
10-26

10.5 Multiple Entry Points The ENTRY Statement


10.2. The type and word lengths of the values associated with the function names
need not be identical. If the names selected do not conform to the usual naming
conventions, the type may be assigned explicitly in a type declaration or implicitly
with an IMPLICIT declaration immediately following the FUNCTION statement.
The dummy argument lists for the various entries need not be identical,
although the same dummy argument may appear in more than one list. However,
the first appearance of a dummy argument in the subprogram must not precede
its first appearance in a dummy argument list. For example, the following would
be illegal:
FUNCTION ALPHA (X. Y. Z)

X + Y

ENTRY BETA (Q. N. X. Y)

When a reference to one of the names is made in a calling program, the


calling argument list must agree in number, order, and type with the dummy
argument list appearing in the ENTRY statement for that name. In FORTRAN,
each entry name is treated as a simple variable in the function. The value returned
to the calling program is specified in the usual way; the function name must appear
on the left-hand side of an assignment statement before the return to the calling
program.
Example
Write a FORTRAN function with two entry names, AVGA and AVGD, that
have common dummy argument lists (M. N. X). When AVGA is referenced, the
elements of the array X from X(M) to X(N) inclusive are to be sorted into ascending
algebraic order; when AVGD is referenced, the elements X(M) to X(N) inclusive are
to be sorted into descending algebraic order. The value returned by the function
for either entry should be the average value of the Mth through the Nth element of X.
The sorting algorithm used is that to be described in Section 11.3 for alphabetizing
a list of words.
FUNCTION AVGA (M. N. X)
DIMENSION X(N)
L0GICAL ASCEND
ASCEND - .TRUE.
GO TO 10
10-27

Chapter 10Function and Subroutine Subprograms

10

20
30

ENTRY AVGD (M. N. I)


ASCEND - .FALSE.
AVGA - 0.
DO 30 I M. N - 1
DO 20 J - I + 1. N
IF (X(I) .GT. X(J) .AND. ASCEND .OR.
X(I) .LT. X(J) .AND. .NOT. ASCEND)
XISAVE - X(I)
X(I) - X(J)
X(J) - XISAVE
END IF
CONTINUE
AVGA - AVGA + X(I)
CONTINUE

THEN

AVGA - (AVGA + X(N))/(N - M + 1)


AVGD - AVGA
D17TTTTJM
lUiiuitn

END

In this example, the logical variable ASCEND is set to . TRUE. when the func
tion AVGA is called and to .FALSE. when AVGD is called. The name AVGA is used
in the function as a simple variable to accumulate the sum of the array elements
and is then assigned to the arithmetic mean of the array elements. AVGD is then
assigned the same value, so that the average value will be returned to the calling
program, whichever entry name was used in the original function reference.

10.6 The INTRINSIC and EXTERNAL Declarations


Dummy subprogram names may appear in the dummy argument list of
a FORTRAN subprogram, in which case the corresponding entry in the calling
argument list must be an actual function or subroutine name. However, since
there will be no parentheses following the subprogram name in the calling program,
the compiler cannot recognize, without further identification, the name as that of
a subprogram. For this reason, such names must be declared in an INTRINSIC
declaration if they are one of the standard library functions of Section 2.5 or 9.3,
and in an EXTERNAL declaration otherwise. The forms are:
EXTERNAL 7l . 72
INTRINSIC 7l. 72

7n
7n

where the Ji, i 1,2, . . ., n, are function or subroutine names.

10-28

10.6 The INTRINSIC and EXTERNAL Declarations


Example Program 10.2EXTERNAL and INTRINSIC Declarations
Program
PROGRAM DECLNS
C

Illustration of the EXTERNAL and INTRINSIC declarations.

Declarations
EXTERNAL F
INTRINSIC COS
LOGICAL MYFUN
OPEN (5. FILE-' CON')
OPEN (7. FILE- 'CON')

C
C
C
C

Read X, then refer to MYFUN. There are no


parentheses following COS and F. yet they
are recognized as function names because
of the INTRINSIC and EXTERNAL declarations
WRITE (7.*)
'Enter a value for X:'
READ (5,*) X
WRITE (6.*)
'X - ' . X
IF (MYFUN (COS. F. X)) THEN
WRITE (6.*) 'COS(X) is larger than F(X)'
ELSE
WRITE (6.*)
'F(X) is larger than COS(X) '
END IF
GO TO 1
END

FUNCTION F(Y)
F = ALOG(Y)
RETURN
END
LOGICAL FUNCTION MYFUN(F1, F2, Z)
C
C
C
C

MYFUN is .TRUE. if F1(Z) exceeds F2(Z), and is .FALSE.


otherwise. The compiler recognizes Fl and F2 as functions
because they are followed by parentheses and do not
appear in a DIMENSION declaration.
MYFUN = F1(Z) .GT. F2(Z)
RETURN
END

10-29

Chapter 10Function and Subroutine Subprograms


Output (with a few blank lines added for clarity)
X 1.0000000
COS(X) is larger than F(X)
X 2.0000000
F(X) is larger than COS(X)
X 3.0000000
F(X) is larger than COS(X)

10.7 Statement (Internal) Functions


All FORTRAN functions discussed previously are external functions, in that
they are compiled as independent programs, and occupy regions of computer mem
ory outside areas assigned to other main, function, and subroutine subprograms.
FORTRAN also allows the programmer to write a special form of function called
a statement function that is an internal function, that is, the function is defined to
be a part of a subprogram. It is compiled as a part of the program in which it is
defined, and occupies storage space inside the block of memory locations assigned
to that program.
Thus, an internal function acts as a kind of "slave" function to its owner
or parent subprogram; it cannot be referenced in any other subprogram. One
advantage of the internal function not possessed by the external function is that it
has access to all variables in its parent subprogram, not just to information passed
to it through its argument list. The principal disadvantages of the statement
function are:
1. It can be used only when the calculation of the function value can be com
puted in a single expression.
2. Being internal to a program, it is inaccesible to all other programs.
As is true of all FORTRAN functions, a statement function must:
1. Have a name, 7 .
2. Have a set of dummy arguments, Al, A2, . . ., An.
3. Return a value corresponding to an expression .
The FORTRAN statement function has the form:
7 (Al, A2, ...,An) = or 8
Note that the dummy arguments are enclosed in parentheses and are separated by
commas. The defining statement must precede the first executable statement in
the subprogram in which it appears.
The name of the function follows the usual naming rules for real, integer, or
logical variables. Unless the function name appears in an explicit type declaration
10-30

10.7 Statement (Internal) Functions


(see Section 9.3), the FORTRAN implicit typing convention is applied to the value
returned. Statement functions of CHARACTER type are not allowed.
Example
An arithmetic statement function named FUN is defined as follows:
FUN(X.Y.Z) - Y**2 - 4.0*X*Z
Then, a reference to the function in the assignment statement
D = SQRT(FUN(A.B.C))
would cause the variable D to be assigned the value (B2 - 4XAxC)1/2.
The arithmetic expression may involve other functions, even other state
ment functions, provided they have been defined in preceding declarations.
Example
Thus, if the functions COT and F have been defined with the statements
COT(X) - COS(X)/SIN(X)
F(X) - 4.0*X**2 + COT(X+0.5)
then a reference to F of the form
Z - F(S + E**2 - 5.37)
would cause Z to be assigned the value
4(S + E2

- 5.37)2 +

cos(S + E2

- 4.87)/sin(S + E2 - 4.87).

The arithmetic statement function name may not be used as an actual ar


gument for an external function or subroutine; in effect, the statement function is
isolated from contact with all FORTRAN subprograms, except the one in which
the defining statement appears, thus restricting its generality. However, because
the statement function is an internal function, it has access to all variables in its
parent program. Thus, the expression may contain both dummy arguments and
actual variables in the parent program.
Example
When the function defined by
ALPHA(X.Y) = X - 3.*Y + B/C
is referenced in the statement
q - 5.2*ALPHA(A.P)
10-31

Chapter 10Function and Subroutine Subprograms


Q will be assigned the value 5.2 x (A - 3xP + B/C), where the current values of
actual variables B and C are used.
Example of a logical statement function
L0GICAL ALTB
ALTB(A.B) - A .LT. B

The same dummy arguments may be used in any number of function definitions.

Exercises for Section 10.7


1. Is it possible for one statement function to refer to another statement
function in the same program?
2. What is the value of P after execution of the following program segment?
Show clearly how you obtained your answer.
REAL MULT
ADD (X. Y) - X + Y
MULT (X. Y) - X*Y
A - 5.5
B - 2.5
P - MULT (ADD((A - B) . 3.5). ADD(A. B))

3. With an explanation, give the value of VAR at the end of the following
program segment:
GOBLUE (A. B. I) = SQRT(2.*A)/B - IABS(I)
X - 8.
Y - 4.
VAR - 2.5 - GOBLUE (X. Y. -1)
4. What are the values of R and S after execution of the following? Explain.
ADD (P. Q) - P + q

sub (p. q) - p - q
DIV
X Y R S -

(A. B) - SUB(A. B)/ADD(A. B)


1.
3.
DIV(X. Y)
DIV(Y**2. 1.)
10-32

10.8 The COMMON Declaration

5. Write a statement function named AREA that gives as its value the area
of a triangle with sides B and C and included angle ALPHA (degrees). Give example
statements that use AREA to evaluate the areas of the two triangles shown in Fig.
10.4, and store the values in AREA1 and AREA2, respectively.

Fig. 10.4 Two triangles.


10.8 The COMMON Declaration
Ordinarily, variables in subprograms are local to their own subprogram.
Thus, a variable named ALPHA in a function has no direct relationship to a variable
named ALPHA in a calling program. Of course, the argument list for the function
allows a direct relationship to be established if ALPHA is a dummy variable in
the function. Sometimes, it is desirable to establish a direct relationship without
passing the information through the argument list. The COMMON declaration allows
the user to do this. In its simplest form, the statement is:
COMMON "Vl . V2

Vn

where the "Vi, i = 1, 2, . . ., n are the names of simple variables or arrays. If the
same COMMON statement appears in a main program and one or more associated
subprograms, then the listed variables will be identical in all the programs. Thus,
the COMMON statement has the effect of transmitting data implicity or indirectly
from one subprogram to another.
The COMMON statement allows a more general approach than indicated above,
in that it is not necessary to use the same names for the common variables in the
various subprograms. Only the position of the name in the COMMON statement list
is crucial. For example, if the statements:
COMMON
COMMON

X. Y. Z
ALPHA. BETA. Z

occurred in a main program and a function, respectively, then the values of ALPHA.
BETA. and Z in the function would be identical with the values of X. Y. and Z.
respectively, in the main program. If array names appear in the COMMON list, then
such variables must be dimensioned in both programs; usually, the dimensions
will be compatible. In essence, the FORTRAN compiler sets aside a region of
memory called blank COMMON for storage of values associated with the variables in
the COMMON lists. The variables are ordered linearly in the common region, with
10-33

Chapter 10Function and Subroutine Subprograms


arrays occupying the appropriate number of locations in the string of memory
words.
An extension of the blank COMMON block, called labeled COMMON, is also avail
able. The COMMON statement then has the form:
COMMON /MAMS/ VI. V2

Vn

where MAM is the name of the common block, and follows the usual naming
rules. The major use of labeled common is to allow certain subprograms to have
"private" common regions, not shared by all subprograms in a program suite. If
desired, blank common and more than one named common block can be defined
in a single COMMON declaration. For example, either the statement pair,
COMMON A. B
COMMON /NAME/ BETA. DELTA/ REGION/ C. D

or the single statement,


COMMON A. B/ NAME/ BETA. DELTA/ REGION/ C. D

assigns A and B to blank common, BETA and DELTA to the common region named
NAME, and C and D to the common region named REGION.
Special care is required when COMMON variables appear in EQUIVALENCE state
ments. Since the variables within a COMMON block are assigned to storage in the
order of their appearance within the block, and since different COMMON blocks can
not overlap, variables within one block or variables in two different blocks cannot
be made equivalent in an EQUIVALENCE statement. However, other variables may
be made equivalent to COMMON variables, provided that there is no implied shifting
of the first element in a COMMON block. For example, the statements:
DIMENSION ALPHA (5)
COMMON BETA. A. B
EQUIVALENCE (A. ALPHA (3))

would not be permitted, since the element ALPHA (1) could not be brought into the
COMMON region without changing the address assigned to the first COMMON variable,
BETA.
For reasons too complex to explain here, variables within COMMON blocks may
have to be listed in order of decreasing word size, in which case all 8-byte variables
would appear first, all 4-byte variables, next, and so on.
Variables assigned to either blank or labeled COMMON may not be preset using
the DATA declaration in main, function, or subroutine subprograms. Variables in
labeled common blocks may be preset with a DATA declaration in a special BLOCK
DATA subroutine discribed in Section 10.9.
10-34

10.9 BLOCK DATA Subprograms


Exercises for Section 10.8
1. In the following, what declaration is missing from the main program?
Main Program

Function JIMMY

COMMON A. B, C
A - 1.
B - 2.
C = 3.
Z - JIMMY(4.)

REAL FUNCTION JIMMY (X)


COMMON A, C, B
JIMMY - A + B - C + X
B = C + 5.
RETURN
END

After execution of the above, what are the values of A, B, C. and Z in the
main program?
2. In the following, what values will be printed for A, B. C, and Z in the
main program?
Main Program

201

Subroutine INVERT

COMMON A
A - 1.
B - 2.
C - 3.
D - 4.
CALL INVERT (C.D)
WRITE (6,201) A. B. C. D
FORMAT (' ' . 4F10.3)
STOP
END

SUBROUTINE INVERT (X. Y)


COMMON Z
X - Y
IF (Y .GT. 1.) Y - l./Y
Z = Y
RETURN
END

3. After execution of the following program segment, what values will be


printed by the WRITE statement.
Main Program

Subroutine SUB

COMMON /IN/ A. B. C
COMMON /OUT/ S. T. U
A - 2.
B - 4.
C - 6.
D = 10.
CALL SUB(D)
WRITE (6.201) A. B. C.
1 D. S. T, U

10-35

SUBROUTINE SUB(D)
COMMON /IN/ A, B, C
COMMON /OUT/ S, T. U
S = B**A
T = S/A
U A
A = B
B = C/A
D = C**2
RETURN
END

Chapter 10Function and Subroutine Subprograms


10.9 BLOCK DATA Subprograms
FORTRAN does not allow the values of variables appearing in unlabeled
common storage to be initialized using the DATA declaration. However, some com
pilers do allow variables in labeled common blocks to be assigned initial values
using the DATA declaration, but only in a separate subprogram called the BLOCK
DATA subprogram, of the form:
BLOCK DATA

END
These delimiting statements must enclose any essential COMMON , DIMENSION , type,
and DATA declarations. For example, to initialize the arrays A and B in the labeled
block ALPHA, the subprogram could appear as:
BLOCK DATA
LOGICAL PRINT
DIMENSION A(100), PRINT(10)
COMMON /ALPHA/ A. PRINT
DATA A. PRINT/ 100*0., 10*. FALSE./
END
Here, the 100 elements of A will be preset with zero values, and the ten elements
of the logical array PRINT will be preset with the values . FALSE .
The BLOCK DATA subprogram has no name, cannot be called by other sub
programs, and must not contain any executable statements. Its sole purpose is the
initialization of variables in labeled common blocks.
10.10 Arrangement of Subprograms
A complete FORTRAN source program consists of one (and only one) main
subprogram, any number of FUNCTION and SUBROUTINE subprograms, and possibly
one BLOCK DATA subprogram. Although many FORTRAN compilers will accept a
source program with the subprogam segments in any order, virtually any translator
will accept the order:
1. Main subprogram.
2. FUNCTION and SUBROUTINE subprograms, in any order.
3. BLOCK DATA subprogram.
Each subprogram must be terminated with its own END declaration. Thus, the
complete program will appear most generally as shown in Fig. 10.5.
10-36

10.10 Arrangement of Subprograms

FORTRAN Main Subprogram


END
"FUNCTION or SUBROUTINE
First FORTRAN Function or Subroutine Subprogram
END
FUNCTION or SUBROUTINE
Second FORTRAN Function or Subroutine Subprogram
END

END
"FUNCTION or SUBROUTINE
Last FORTRAN Function or Subroutine Subprogram
END

BLOCK DATA Subprogram


_END

Fig. 10.5 General appearance of a FORTRAN program.

10-37

Chapter 10Function and Subroutine Subprograms


Notes

10-38

CHAPTER 11

CHARACTER STRUCTURES

11.1 Introduction
We often desire to read and write character information of a variable nature.
For example, important pieces of information required for a payroll-calculation
and check-writing program would include the employee names, addresses, and the
amounts to be paid.
Fortunately, FORTRAN allows such symbolic information to be stored in
ternally in variables of character type. FORTRAN also has the facility for reading,
writing, and manipulating character constants, variables, function references, and
expressions. The programmer needs to know that one byte of storage is required
for each character or symbol. Thus, words of length one, two, or three bytes can
store the internal representation of one, two, or three characters, and so on, up to
a maximum of 127 characters in one variable.
A character constant (sometimes called a literal constant, character string,
or literal string) consists of a string of one to 127 characters enclosed in primes. If
a prime is one of the desired characters, then two primes must be juxtaposed.
Examples
'A'

'CALL 761-5683'

'Don' 't do that! '

' '"

The last example is a character constant consisting of a single prime.


A character variable is named using the usual rules for naming FORTRAN
variables. Every character variable must be explicitly or implicitly typed with the
CHARACTER or IMPLICIT declarations. Unless otherwise specified, each variable is
assigned one byte (contains just one character). However, character variables may
have optional lengths of two through 127 characters. Character array variables are
also permitted.
Examples
CHARACTER
DIMENSION

LETTER. MESSAG*21
MESSAG(1O)
11-1

Chapter 11 Character Structures


These two declarations would cause the character array MESSAG to have 10 ele
ments, each of which has 21 bytes of storage assigned to it. The two declarations
could also be rolled into one:
CHARACTER

LETTER. MESSAG ( 10) *21

A character expression, C, consists of one of the following:


(a)
(b)
(c)
(d)

A
A
A
A

character constant, 'C.


character variable, "VC.
character function reference, 7C ( ).
parenthesized character expression, (C).

Examples
'Break In Case Of Fire'

MESSAG(5)

('ABC')

A character assignment statement has the following form:


vc = ec
Examples
LETTER - 'A'
MESSAG(5) = "Break In Case Of Fire'
A - LETTER
Here, the variables LETTER. MESSAG, and A are assumed to be of character type
and of sufficient length to hold the character string. If the length (in bytes) of tC
is greater than the length of "VC, the leftmost characters of iC are stored.
Exercises for Section 11.1
1. Check true or false, as appropriate:
(a)

Two characters can be stored in each byte of memory.

T D

F D

(b)

Characters can be encoded in a word length of between 1 and 255 bytes.

T D

F D

2. Write a single CHARACTER declaration that will reserve four bytes for the
character variables X, Y, and Z, 25 bytes for NAME. and 50 bytes for WORD.
11.2 I/O of Character Information
The format specification for input and output of character (alphabetic) in
formation is
nAm
11-2

11.2 I/O of Character Information


where n is the number of repeated fields containing characters and m is the number
of columns in each field; if n is equal to one, it may be omitted.
The action taken is illustrated in Fig. 11.1. Let b be the number of bytes or
characters in a variable storage word. Then, if m < b (Case A), the m characters
are stored left-adjusted in the storage word on input and blanks are added to fill
out the word on the right; on output (Case B), the leftmost in stored characters
are retrieved from the storage word and printed.
Variable
1
i

Variable

<
Field

Field

Blanks
added

Not
printed

Blanks
added

Discarded Variable
<

Input

Output

Fig. 11.1 Input and output of character infor


mation for unequal variable and field lengths.
However, if m > b (Case C), the leftmost (m - b) characters in the field are dis
carded, and the rightmost b characters are stored on input (note the inconsistency
with the assignment operation); on output (Case D), the b characters are printed
right-justified in the field with leading blanks. These features are also shown in
the following example.

Example Program 11.1Formatted Character I/O


Program
PROGRAM CHIOFO
C

Illustration of character I/O with formats.

Declarations
CHARACTER FIRST*4. LAST*10, GROUP+8, SS(3)*4, TITLE*4
INTEGER AGE
OPEN (5. FILE- 'CHIOFO. DAT')
11-3

Chapter 11 Character Structures

Read variables, print with rearrangement


READ (5.101) FIRST. LAST. (SS(I). I - 1 . 3) . GROUP.
1 TITLE. AGE
WRITE (6.201) FIRST. LAST, GROUP. TITLE. AGE.
1 (SS(I). I - 1. 3)
STOP

Formats for input and output statments


101 FORMAT (A4. 6X, A10. A3. A2. A4. lX. A8. 2X.
1 A4. 4X. 12)
201 FORMAT ClName: \ Al . ' . '. A10/ ' Company Group: '.
1 A8/' Position: \ A4/ "0Age:
12/
2 ' Social Security Number: '. A3.
A2,
A4)
END

Data
Col:

1
2
3
4
5
12345678901234567890123456789012345678901234567890
ANTONIA
FRASER
214282104 RESEARCH MNGR
40

After execution of the READ statement, the variables will contain the follow
ing character strings, with U denoting a blank space:
Variable

Contents

FIRST
LAST
SS(1)
SS(2)
SS(3)
GROUP
TITLE
AGE

"ANTO'
FRASERUUUU'
214U'
28UU'
'2104'
"RESEARCH"
MNGR'
40

Note that AGE contains the integer 40, whereas all other information is stored in
encoded character formincluding the digits of the social security number.
Output (at the top of a new page)

Col:

1
2
1234567890123456789012345
Name: A. FRASER
Company Group: RESEARCH
11-4

(continued)

11.2 I/O of Character Information


Position: MNGR
Age: 40
Social Security Number: 214-28-2104

Finally, since literal constants may appear in the output list, literal fields
(including any carriage-control characters) could be transferred from the FORMAT
declaration to the WRITE statement as follows:
WRITE (6.201)
'lName: '. FIRST. '. '. LAST.
' Company Group: '. GROUP. ' Position: '. TITLE.
'OAge: '. AGE. ' Social Security Number: '.
(SS(I). I - 1. 3)
201 FORMAT (A7. Al . A2. A10/ A16. A8/ Al1. A4/
1
A6. 12/ A25. A3. '-\ A2. '-\ A4)
1
2
3

Note that the FORMAT declaration must now contain "A" field specifications that
correspond to literal constants in the list. This is not a particularly useful varia
tion, since the number of characters in each literal constant must now be counted
accurately, and it will therefore not be pursued.

Example Program 11.2List-Directed Character I/O


Program
PROGRAM CHIOLD
C

Illustration of list-directed character I/O.

Declarations
CHARACTER BEAST*8. SEX. HAIR*5. EYES*5. KIND* 10
OPEN (5. FILE-' CHIOLD. DAT')

C
C

Read variables. print with rearrangement


Note that variables SEX and AGE are not used
1 READ (5.*.END=999) BEAST. SEX. HAIR. EYES. KIND. AGE
WRITE (6.*)
' The ' . HAIR. ' '. BEAST. ' has ' .
1 EYES. ' eyes. '

C
999

Return for next data set ; quit


GO TO 1
STOP
END

11-5

Chapter 11 Character Structures


Data
dog', 'M', 'gray', "brown', 'beagle', 1.5
'cat', 'F', 'beige', 'blue', 'Siamese', 3.
'rabbit', 'M' , 'white', 'pink', 'unknown' , 2.25
Output
The gray dog
The beige cat
The white rabbit

has brown eyes.


has blue eyes.
has pink eyes.

Note that the programmer has little control over the positioning of the line
on the printed page when the list-directed output statement is used exclusively.
If the length of the character variable exceeds the length of the assigned literal
constant, blanks are automatically added on the right when the constant is stored
in the memory. (If, on the other hand, the number of characters in the literal
constant exceeds the length of the character variable, any extra characters are
trimmed from the right end of the constant.)
Exercises for Section 11.2
1. Check true or false, as appropriate:
(a)

Characters can be read and printed using the A for


mat code.

(b)

If WORD is a five-byte character variable, and the string


'Anastasia' is read into it, the contents of WORD will
then be 'tasia'.

(c)

The string 'BREN' will be displayed after the following


the sequence:

201

CHARACTER*4 NAME
NAME - 'BRENDA"
WRITE (6.201) NAME
FORMAT (' ' . A4)

2. Write a complete FORTRAN program that will achieve the following:


(a) Initialize the character variables BO and WOODY to the literal strings
'Michigan 14' and 'Ohio State 6', respectively.
(b) Print out the contents of BO and WOODY on the first line of a new page,
with a comma and two blank spaces between them.
3. Consider the following program and data:

CHARACTER FIRST*10, LAST*10. ONE*3, TWO*4


READ (5.100,END=999) I. FIRST. LAST, ONE. TWO
11-6

11. S Manipulation of Character Information


100

200
999

FORMAT (Il. 2X. A10. lX. A10. lX. A3. A4)


WRITE (6.200) I. ONE. TWO. FIRST. LAST
GO TO 1
FORMAT C 10'. I1. 2X. A3. '-'. A4. 2X. Al. '. '. A10)
STOP
END

Data
Col:

12
3
12345678901234567890123456789012345
1. GEOFFREY
2. ANNABEL
3. ANNE

MOREHOUSE
JOHNSON
SEITZ

6639248
9940024
7619103

In the spaces below, show in detail the output that would be printed by the
program:
12
3
4
Col :
1234567890123456789012345678901234567890

4. Three data lines contain the following information about three books
(titles, authors, and publication dates):
Col:

12
3
4
5
12345678901234567890123456789012345678901234567890
1. Thermodynamics
2. Polymers
3. Numerical Methods

Van Wylen Gordon


Pearson
John
Hornbeck Robert

1963
1966
1975

Write a FORTRAN program that will read the above lines as data, and produce
the following output:
Col:

12
3
4
1234567890123456789012345678901234567890
AUTHOR
G. Van Wylen
J. Pearson
R. Hornbeck

BOOK
Thermodynamics
Polymers
Numerical Methods
11-7

DATE
63
66
75

Chapter 11 Character Structures


11.3 Manipulation of Character Information
First, note that the coded form of a character is stored in one byte of memory,
which consists of eight binary bits. It follows that the number of distinct characters
that can be so encoded and stored is two raised to the power of eight, namely, 256.

Table 11.1 ASCII Character Codes


Code

Character

Code

Character

Code

Character

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

Blank space, U
I
a

65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P

97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125

a
b
c
d
e
f
8
h
i

#
$
%
it
>
(
)
*
+

/
0
1
2
3
4
5
6
7
8
9
:

<

Q
R
S
T
U
V
W
X
Y
Z
[
\
]

j
k
1
m
n
0
P
q
r
B
t
u
V
w
X
y
z
{
1
}

>
?
e

One of the various schemes that have been used for the internal represen,
11-8

11. S Manipulation of Character Information


tat ion of characters is the ASCII Code (American Standard Code for Information
Interchange), in which each character is assigned an integral value ranging from 0
through 255. Table 11.1 shows that part of the ASCII code of greatest interest to
us.
Since each character has a numerical equivalent, it is possible to compare
one character against another, using the relational operators discussed in Section
6.2. Indeed, two character expressions Cl and CI may appear with one of the
relational operators in simple logical expressions of the form
Cl

.Z.

01

For purposes of comparison, the character expressions are treated as if they were
integers, converted according to the ASCII codes of Table 11.1.
For example, the logical expression
'A' .LT. 'B'
will always be . TRUE, whereas
'MARY' .LT. 'JACK'
will always be .FALSE. If one of the operands is shorter in length than the other,
the shorter operand is padded on the right with blanks to produce two operands
of equal length. Thus, the following are equivalent:

'CHURCHILL' .GT. 'TRUMAN'

and

'CHURCHILL' .GT. 'TRUMAN

A very important feature is that the ASCII equivalents of the characters


increase in the natural order of the alphabetical characters. Hence, these simple
logical expressions allow the programmer to alphabetize character strings contain
ing letters and blanks rather easily, by sorting their numerical equivalents into
ascending order, as shown in the following example.
Example Program 11.3Alphabetizing a List
Program
PROGRAM ALSORT
C

Sorting a list into alphabetical order.

Declarations
CHARACTER*20 NSAVE. NAME
DIMENSION NAME(100)
OPEN (5. FILE= 'ALSORT.DAT')
11-9

Chapter 11 Character Structures

Initialize index. read all names ....


I - 1
READ (5.101.END-10)
NAME(I)
I - I + 1
GO TO 1
N - I - 1

10
C

DO 30
C

Perform N - 1 passes of sorting algorithm


I 1. N - 1

Interchange all pairs found out of order


DO 20 J - I + 1. N
IF (NAME(I) .GT. NAME(J)) THEN
NSAVE - NAME (I)
NAME(I) - NAME(J)
NAME (J) - NSAVE
END IF
20
CONTINUE
30 CONTINUE

Print alphabetized list


WRITEC6.202) N. (NAME(I) . I - 1 . N)
STOP

Formats for input and output statements


FORMAT (A20)
FORMAT ( 'lAlphabetized list of. 13. ' names:'/

101
202

''/(''. A20))
END

The algorithm used is quite simple. The word in NAME(l) is compared, in


turn, with each of the other elements of the NAME array; whenever a word pair is
found to be out of order, the two words are interchanged. After one complete pass
through the array, the first word in alphabetical order is NAME(l) . Next, NAME(2) is
compared with the elements of the arrays with larger subscripts in similar fashion;
after the second pass, the word second in alphabetical order will be in NAME(2).
The procedure is repeated until a total of N - 1 such passes through the array has
been completed.
To change the length of the words to be alphabetized, only the CHARACTER
declaration need be modified.

11-10

11. S Manipulation of Character Information


Data
Johnson, Mary
Rodriguez, Hector P.
Johnson, Harry
Rodriguez , Hector
Huang, Hing-Sheng
Jones, Alfred
Johns , Harvey
Pof f enberger, Thomas M.
Pooley, Beverley J.
Johns , Harry
Duderstadt, James J.
Johnston, Harry, I
Twist, Oliver
Washington, George
McTavish, Angus
McTavish, A.
Johnston, Harry, II
Output
Alphabetized list of 18 names:

Duderstadt, James J.
Huang, Hing-Sheng
Johns , Harry
Johns , Harvey
Johnson, Harry
Johnson, Mary
Johnston, Harry, I
Johnston, Harry, II
Jones, Alfred
McTavish, A.
Mc Tavish , Angus
Pof f enberger, Thomas
Pooley, Beverley J.
Rodriguez , Hector
Rodriguez, Hector P.
Twist, Oliver
Washington, George
11-11

Chapter 11 Character Structures


Character variables may appear in compound logical expressions as well as
simple ones.
Example
1

IF (WORD(1) .EQ.'BLACK' .AND. WORD(2) .EQ.'CAT')


GO TO 5

Exercises for Section 11.3


1. Check true, or false, as appropriate:
(a)

The ASCII equivalent of the letter D is 100.

(b)

The expression 'Bobu' .GT. 'AmyU' (note the blank


spaces) is .TRUE.

(c)

The expression 'UBob' .GT. 'AmyU' (note the blank


spaces) is . TRUE .

(d)

The following statement would be legal if the variable


NAME were of character type.

IF (NAME .EQ. 'JOHN')

N = N + 1

2. In Example Program 11.3, what change(s) would be needed to sort the


list of variables into reverse alphabetical order?
3. If the following five-character FORTRAN words were alphabetized, show
their final order.
Original Order
1.
2.
3.
4.
5.
6.

Alphabetized Order

MARYU
MARKU
UMARY
MARY .
LUKEU
MARY.

4. If, in a program, we have the following statements,


CHARACTER INSECT (4) *4
DATA INSECT / 'FLY ". 'BEE

'WASP', 'ANT '/

what is then the type and value of the following expression?


INSECT(3) .GE. INSECT(1)

.AND. INSECT(4) .NE. INSECT(2)

11-12

11.4 Internal I/O Statements Involving Character Variables


5. A coded text consists of a series of four-character groups. Successive
groups are separated by one blank space, and there are ten groups on each data
line, starting in columns 1, 6, 11, etc. Write a program that will:
(a) Read in successive lines of data.
(b) Examine successive groups for the character sequences 'ABCD', 'em7X', and
'XXXX', and print out the line number(s) on which each sequence was found.
11.4 Internal I/O Statements Involving Character Variables
An interesting feature involving character variables is the capability of per
forming internal input and output operations. As the name implies, these I/O
reading and writing operations are confined to the fast memory. In effect, infor
mation already stored in memory can be manipulated under format control and
written into other parts of the memory; individual characters can be examined
and rearranged.
It is important to remember that these reading and writing operations do
not involve the keyboard, monitor, printer, or files, as have all the input and output
statements used hitherto. The expression core,to-core I/O was used previously to
describe internal I/O, and perhaps emphasized more that the internal memory is
the medium for reading and writing.
The internal output statement has the form:
WRITE (VC.M)

where the individual parts have the meanings given in Table 11.2.
Table 11.2 Codes for Internal Output Statement
Code

Meaning

VC

Character variable or an element of a character array.

}/

Statement number of an associated FORMAT declaration (or


the name of a character variable or an element of a charac
ter array where the format specification is stored in coded
character form).

Output list.

The WRITE statement causes the values associated with the elements of the
list to be prepared as unit output records under control of the format specifica
tion in the usual way. However, instead of being written as successive lines on a
printer, the output is written into the variable or array element VC. The number
of characters involved should not exceed the length of the character variable or
11-13

Chapter 11 Character Structures


array element "VC; if fewer characters are involved, then blanks are automatically
added on the right to fill "VC.
One of the major uses of the internal WRITE statement is in the preparation of
execution-time formats for use in other, conventional (external), input and output
statements. Suppose that we wish to prepare an output format of the form
(1X. nnFmm.j)
in the character variable OUTPUT, of length 13 characters, and nn, mm, and j are
the values of three integer variables N. M. and J, respectively (to be computed in
the program). Then the program would have the following general appearance:
CHARACTER

OUTPUT* 13

N
M
J

201

WRITE (OUTPUT. 201) N. M. J


FORMAT C(1X. '. 12. 'F'. 12. '.'. Il. ')')

WRITE (6. OUTPUT)

If the values assigned to N. M. and J were 6, 15, and^4, respectively, then the
contents of OUTPUT, and hence of the format used in the last WRITE statement,
would be:
(1X.

6F15.4)

Example Program 11.4Plotting the Sine Function


As a more complicated example, suppose that we wish to prepare a plot
of the sine function at intervals of ten degrees, so that the printer output has
the appearance shown below. The following program was written to generate the
desired graph.
11-14

11.4 Internal I/O Statements Involving Character Variables

SINE
-1.0
+
Degrees
.0
10.0
20.0
30.0
40.0
50.0
60.0
70.0
80.0
90.0
100.0
110.0
120.0
130.0
140.0
150.0
160.0
170.0
180.0
190.0
200.0
210.0
220.0
230.0
240.0
*
250.0
*
260.0 *
270.0 *

0.0
+

*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*

280.0 *
290.0
*
300.0
*

310.0
320.0
330.0
340.0
350 . 0
360.0

1.0
+

*
*
*
*
*
*
11-15

Chapter 11 Character Structures


Program
PROGRAM GRAPH
C
C

Illustration of internal WRITE statement


to generate a graph of the sine function.

Declarations
CHARACTER PART1*10. PART3*7. F0RM*20
DATA PARTl / '(1X. F6.1. '/
DATA PART3 / 'X. ''*")'/
Conversion factor. print heading
DEGPR - 180. /3. 141593
WRITE (6.201)

Angles 0. 10
DO 30 I - 0. 36
DEGREE - 10*1

C
C

Determine number of column


skips before printing asterisk
NCOL - 25.*(1. + SIN(DEGREE/DEGPR)) +1.5

C
C

30

360 degrees

Assemble individual parts of


format; then print asterisk
WRITE (FORM. 202) PARTl. NCOL. PART3
WRITE (6. FORM) DEGREE
CONTINUE
STOP

Formats for output


FORMAT Cl'. 30X. 'SINE'
1 22X. '0.0'. 22X. '1.0'
2 24('-'). ' + '. 24C-').
3 ' ')
202 FORMAT (A10. 13. A7)
201

statements
/ '0'. 5X. '-1.0'.
/ ' '. 7X. '+'.
' + ' / ' Degrees' /

END
After the value of the angle is printed at the beginning of each successive
line, NCOL is the number of intervening blank columns (inserted by using the X
format code) before the plotting character"*" is printed. Apart from the small
adjustment factor of 1.5 (what is the reason for it?), observe that NCOL oscillates
11-16

11.5 Additional Programs for Character Manipulation


about a base value of 25 columns, with an amplitude of 25 columns. The internal
output statement WRITE (FORM. 202) . . . prepares the format for the succeeding
output statement WRITE (6. FORM) ....
The key to understanding the above is to examine the three variables that
are written into FORM (a character variable of length 20), under control of the
format numbered 202:
Variable

Contents

Field

PARTl
NCOL

(lX. F6.1.
Number of columns
to be skipped
X. '*')

A10

PART3

13
A7

The internal input statement has the form


READ (VC. M)

where VC and M have the same meanings as in the corresponding WRITE statement,
and t is an input list.
The input statement causes the character content of "VC to be read into
element of the list , under control of the associated format specification.
Example
Suppose that we want to know if the third character of a word saved in
the eighth element of the array NAME is the letter B. Assume that each element of
NAME has up to ten characters. Then the following statements might appear in the
program:
CHARACTER
DIMENSION

100

NAME* 10. LETTER


NAME (100)

READ (NAME(8).100) LETTER


FORMAT (2X.A1)
IF (LETTER .EQ. 'B') GO TO 10

The third letter of NAME(8) is read into the character variable of length 1 named
LETTER. Presumably, appropriate action will be taken at the statement numbered
10.
An important use of the internal input statement is the re-reading of input
images, with possibly different formats. Recall that when a line is read with a
formatted input statement, it is read only once, and that the line must be typed
in strict accordance with the format specification and the input list. An example
now follows.
11-17

Chapter 11 Character Structures


11.5 Additional Programs for Character Manipulation
We conclude this chapter with two programs that further illustrate the abil
ity of FORTRAN to process information involving characters. Note that neither
example involves any significant arithmetic calculations in the traditional sense.

Example Program 11.5Employee Information


Suppose that for each employee, a company maintains personnel information
on successive lines of a file. We wish to read the lines and tabulate each employee's
name, social-security number, age, and sex on the printer. The lines containing
this information have been typed in two different formats as follows:

Name:
S.S No:
Age:
Sex:
Code in
column 60:

Format 1
Columns

Format 2
Columns

Appearance

5-25
41-49
30-31
52

2-20
21-29
30-31
50

Alphabetic
Integer
Integer
F or M

The lines may also contain other employee information of no interest at the mo
ment. The format for each line is indicated by a character ("A" or "2") appearing
in column 60, as shown above. All other lines, not to be processed, have different
characters in column 60.

Program
All variables have been assigned character mode. LINE contains the the first
59 columns of a line and FCODE contains the character typed in column 60. Other
data items are assigned obvious names.
PROGRAM SOCSEC
C
C
C

Illustration of internal READ statement to process


personnel records that are stored in a file in two
different formats.

Declarations, print heading


CHARACTER LINE*59, FCODE. NAME*21, SSNO*9. AGE*2. SEX
OPEN (5, FILE- ' SOCSEC.DAT')
WRITE (6.200)

11-18

11.5 Additional Programs for Character Manipulation


C
1

Read information for one person into LINE


READ (5.100.END=999) LINE. FCODE

C
C
C

According to code 'A' or '2', read information into four separate variables, also
reject case of invalid code in column 60
IF (FCODE .EQ. 'A') THEN
READ (LINE. 101) NAME. AGE. SSNO, SEX
ELSE IF (FCODE .EQ. '2') THEN
READ (LINE. 102) NAME. SSNO. AGE. SEX
ELSE
GO TO 1
END IF

Print in uniform format , return to READ


WRITE (6.201) NAME. SSNO. AGE. SEX
GO TO 1
STOP

999
C

Formats for input and output statments


FORMAT (A59, Al)
FORMAT (4X. A21. 4X. A2. 9X, A9, 2X. Al)
FORMAT (1X. A19. A9. A2, 18X. Al)
FORMAT ('i' , 5X. 'NAME'. 15X. 'SOC.SEC.NO. ' .
1 2X. 'AGE', 4X. "SEX" / ' ')
201 FORMAT (' ', A21 , 4X. A9, 4X, A2, 5X, Al)

100
101
102
200

END

Data (a confusing jumble!)


1
2
3
4
5
6
123456789012345678901234567890123456789012345678901234567890
Giuseppe Verdi
xyz 88 Italy 123456789 M Mus.
James A. Whistler 98765432169 Painter/etcher M
zxx
J.M.W. Turner
33322444476 Painter
M
zyx
Bad information in this line - to be rejected.
Eleanor Roosevelt
xxz 78 U.S.A. 212121212 F Lect.
Dorothy Sayers
12121212164 Writer
F
yxz
The quick brown fox jumps over the lazy dog. QWERTYUIOP
11-19

A
2
2
x
A
2

Chapter 11 Character Structures


Output (at the top of a new page)
12
3
4
5
12345678901234567890123456789012345678901234567890
NAME
Giuseppe Verdi
James A. Whistler
J.M.W. Turner
Eleanor Roosevelt
Dorothy Sayers

SOC.SEC.NO.

AGE

SEX

123456789
987654321
333224444
212121212
121212121

88
69
76
78
64

M
M
M
F
F

Sometimes, at least, computers make things a little easier.

Example Program 11.6A Small Word-Processor


Introduction
Here, we use the character-manipulating abilites of FORTRAN to write a
very modest "word- processor," which can read a paragraph of text and reprint
it with different column widths. Consider, for example, the following short para
graph:
Col:

1
2
1234567890123456789012345
Bernoulli's equation is
essentially an energy
balance along a
streamline. It states
that the sum of kinetic .
potential. and pressure
energy remains constant.

Note the following:


1. Each word terminates with a blank. Words within a line are separated by
one or more blanks.
2. Words are not broken or hyphenated between two lines.
3. For our purposes, we shall consider commas and periods as part of the word.
For example, the last word in the paragraph is "constant." not "constant" .
4. Each line may be terminated by zero, one, or more blanks. The end of the
paragraph is signalled by a blank in column 1.
5. There will be no more than 250 words, and no more than 1,000 characters
in the paragraph.

11-20

11.5 Additional Programs for Character Manipulation


Our problem is to read a paragraph such as the above, together with two
additional integers, NBEGIN (= 5, for example) and NEND (45, for example), and
then to print the paragraph so that it is reformatted and lies between columns
NBEGIN through NEND. For example:

Col:

12
3
4
123456789012345678901234567890123456789012345
Bernoulli's equation is essentially an
energy balance along a streamline . It
states that the sum of kinetic .
potential. and pressure energy remains
constant.

The above is achieved by the set of three programs:


1. A main program, which calls on subroutines INPUT and OUTPUT, and also
reads the values of NBEGIN and NEND.
2. A subroutine named INPUT, which:
(a) Reads a paragraph such as the above, one line at a time. Each input
line contains 60 characters (including blanks) in columns 1 through
60, and is stored in CHAR, a CHARACTER* 1 vector, 60 elements long.
(b) Returns immediately to the calling program if a blank is found in
column 1.
(c) Builds up a CHARACTER* 1 vector PARA that eventually contains all the
characters in the paragraph (excluding blanks). For example, PARA
might contain the following:
Bernoulli 'sequationisessentiallyanenergybalancealong
(d) Also builds up two other vectors, LOCATE and NCHAR, such that:
LOCATE (W)

Gives the location in the PARA vector where


word W starts.

NCHAR (W)

Gives the number of characters in word W.

Again relating to the introductory example, we might have:


W

LOCATE (W)

NCHAR (W)

1
2
3
4

1
12
20
22

11
8
2
11

etc.
11-21

Chapter 11 Character Structures


(e) Finds the total number of words, NWORDS, in the paragraph.
3. The subroutine OUTPUT, which prints the reformatted paragraph between
columns NBEGIN and NEND.
Program
PROGRAM WRDPRC
Main program that calls on INPUT to read and print a paragraph. and on OUTPUT to reformat and reprint paragraph.

C
C
C
C
C
C
C
C
C
C
C
C

LOCATE (W)
NBEGIN
NCHAR(W)
NEND
NWORDS
PARA

Location in PARA vector where word W starts.


Beginning column for printing reformatted
paragraph .
Number of characters in word W. including
the following blank.
End column for printing reformatted
paragraph .
Number of words found in paragraph.
Vector used for storing characters in
paragraph.

Declarations
CHARACTER* 1 PARA
DIMENSION LOCATE(25O). NCHAR(250) . PARA(1O00)
OPEN (5. FILE-' WRDPRC. DAT')

C
1

Call on input to read and print paragraph


CALL INPUT (LOCATE. NCHAR. NWORDS. PARA)

Read column range for reformatted paragraph


READ (5.101) NBEGIN. NEND
WRITE (6.201) NBEGIN. NEND

Call on OUTPUT to reformat and print paragraph


CALL OUTPUT (LOCATE. NCHAR. NBEGIN. NEND. NWORDS. PARA)

Process another paragraph


GO TO 1

Formats for input and output statements


101 FORMAT (215)
201 FORMAT (' Reformatted column range is from '. 13. ' to '.
1 13)
11-22

11.5 Additional Programs for Character Manipulation


END

SUBROUTINE INPUT (LOCATE. NCHAR. W. PARA)


C
C
C
C
C

C
CHAR
W

Index for successive characters in paragraph .


Vector used for storing characters in a
single line of input.
Index for successive words in paragraph.

Declarations
INTEGER C. W
CHARACTER* 1 CHAR. PARA
LOGICAL HEAD
DIMENSION CHAR (60) . LOCATE (250) . NCHAR(250) . PARA (1000)
HEAD - .TRUE.

Initialize column and word counters


C - 0
W - 0

C
1

Read and print a line of PARA


READ (5.101.END=999) (CHAR( J) . J 1 . 60)
IF (HEAD) THEN
WRITE (6.201)
HEAD - .FALSE.
END IF
WRITE (6.202) (CHAR(J) . J - 1. 60)
Blank in column 1 is end of paragraph
IF (CHAR(l) .EQ. ' ') RETURN

C
C

Locate and store words in PARA. Set


column index for beginning of new line
J - 0

C
C
10

Increment column index


Check to see if end of line
J - J + 1
IF (J .EQ. 61) GO TO 1
If a blank. move to next column
IF (CHAR(J) .EQ. ' ') GO TO 10
11-23

Chapter 11 Character Structures

Process next word


W - W + 1
C - C + 1
LOCATE (W) = C
NCHAR(W) 1
20

PARA(C) = CHAR(J)
J - J + 1

Either the end of a word


IF (CHAR(J) .EQ. ' ') THEN
GO TO 10

Or advance the character count


ELSE
C C + 1
NCHAR(W) - NCHAR(W) + 1
GO TO 20
END IF
999

STOP

101
201
202

Formats for input and output statements


FORMAT (60A1)
FORMAT ('OOriginal paragraph is:'/ ' ')
FORMAT (' '. 60A1)

END

SUBROUTINE OUTPUT (LOCATE. NCHAR. NBEGIN. NEND. NWORDS.


1 PARA)
C
C
C
C
C
C
C

C
CHAR
CHAR
J
W

Index for successive characters in paragraph.


Vector used for storing characters in a single
line of output .
Number of characters in current word.
Column index for line of output .
Index for successive words in paragraph.

Declarations
INTEGER C. CHARS. W
CHARACTER* 1 CHAR. PARA
DIMENSION CHARC72). LOCATE (250) . NCHAR(250) . PARA(1O00)
11-24

11.5 Additional Programs for Character Manipulation


WRITE (6.201)
C

Insert leading blanks


DO 10 J - 1. NBEGIN - 1
CHAR(J) * ' '
CONTINUE
J - NBEGIN

10

Reformat and print paragraph line by line


DO 50 W = 1. NWORDS
CHARS - NCHAR(W)

C
C

Print line if full. reset column index J.


insert leading blanks for next line
IF (J + CHARS - 1 .GT. NEND) THEN
WRITE (6.202) (CHAR(I). I - 1. J - 1)
DO 15 J = 1. NBEGIN - 1
CHAR(J) - ' '
CONTINUE
J - NBEGIN
END IF

15

Add word (and possible blank) to line


DO 20 C - 1. CHARS
CHAR(J + C - 1) - PARA ( LOCATE (W) + C - 1)
CONTINUE
J - J + CHARS
IF (J .LT. NEND .OR. W .NE. NWORDS) THEN
CHAR(J) - ' '
J - J + 1
END IF

20

Print line if last word


IF (W .EQ. NWORDS) WRITE (6.202)
1
50

(CHAR(I) . 1=1.
J - 1)

CONTINUE
RETURN

C
201
202

Formats for output statements


FORMAT ( 'OReformatted paragraph is:'/ ' ')
FORMAT (' '. 72A1)
END
11-25

Chapter 11 Character Structures


Data
The data are reproduced in the output and are not given here.

Output
Original paragraph is:
The data transmission rate is usually measured in Baud.
which in most instances is equivalent to the number of bits
per second being transmitted. The typical IBM/PC
communication board can transmit and receive data at Baud
rates in the range 50 - 20000. The transmission rate in
terms of characters is about one tenth of the Baud rate. so
that. for example. about 120 characters per second can be
transmitted at 1200 Baud.
Reformatted column range is from

10 to

40

Reformatted paragraph is:


The data transmission rate is
usually measured in Baud. which
in most instances is equivalent
to the number of bits per
second being transmitted. The
typical IBM/PC communication
board can transmit and receive
data at Baud rates in the range
50 - 20000. The transmission
rate in terms of characters is
about one tenth of the Baud
rate. so that. for example.
about 120 characters per second
can be transmitted at 1200
Baud.
Original paragraph is:
Liquid air: -- Air was first liquefied in bulk in 1895
independently by Hampson in England and Linde in Germany.
who made use of a new principle. namely. the Joule-Thomson
effect. investigated by Joule and William Thomson (later.
Lord Kelvin) from 1852. When a compressed gas escapes
into free air through an expansion valve. a slight cooling
11-26

11.5 Additional Programs for Character Manipulation


effect occurs with most gases (such as air. oxygen. carbon
dioxide. and nitrogen) but a slight heating effect with
hydrogen at the ordinary temperatures.
This temperature
change is quite different from that due to the external
work done by a gas in adiabatic expansion. and is due to
the internal work spent in separating the molecules
against their attractions.
Reformatted column range is from

5 to

60

Reformatted paragraph is:


Liquid air: -- Air was first liquefied in bulk in 1895
independently by Hampson in England and Linde in
Germany. who made use of a new principle. namely. the
Joule-Thomson effect. investigated by Joule and William
Thomson (later. Lord Kelvin) from 1852. When a
compressed gas escapes into free air through an
expansion valve. a slight cooling effect occurs with
most gases (such as air. oxygen. carbon dioxide. and
nitrogen) but a slight heating effect with hydrogen at
the ordinary temperatures. This temperature change is
quite different from that due to the external work done
by a gas in adiabatic expansion. and is due to the
internal work spent in separating the molecules against
their attractions.

11-27

Chapter 11 Character Structures


Notes

11-28

APPENDIX A

SOLUTIONS TO EXERCISES

Section 1.3 (page 1-18)


1.
4.

Column 7
WRITE and FORMAT

2.
5.

END
Yes

3.
6.

*../=:()
Carriage -control

Section 1.4 (page 1-22)


1. (a) F
(b) T
(c) F
(f) F (66 columns)

(d) T

(e) F

Section 2.2 (page 2-3)


(a)
(d)

Integer
Integer

(b)
(e)

Real
Real

(c)
(f)

Real
Real

Section 2.3 (page 2-4)


(a)
(b)
(c)
(d)
(e)
(i)

F-type real
Invalid
Integer
Invalid
E-type
E-type

2. (a) F

(g)
(h)
(i)
(j)
(k)
(1)

Invalid
Invalid
Real variable
Invalid
Invalid
Invalid

(b) F (e.g., 3.14159E0)

(c) F

(d) T

Section 2.4 (page 2-6)


1. (a)
(b)
(c)
(d)
(e)

Valid, real.
Valid, real.
Valid, integer.
Invalid. ." and "+"
not allowed.
Invalid, too long.

(i)
(j)

A-1

(k)

Valid, integer.
Invalid. 11 . " not
allowed.
Valid, integer

(1)

Invalid, too long

Solutions to Exercises
(f)
(g)
(h)

(m)

Invalid. "#" not allowed.


Invalid, first character
must be alphabetic .
Valid, real

2.

INTEGER

3.

REAL

(n)
(o)

Invalid. "+" not


allowed.
Valid, real
Invalid, Greek let
ters not allowed.

COUNT. POINTS

LENGTH, MASS

(TIME may be omitted, already REAL)

Section 2.5 (page 2-9)


1. (a)
(b)
(c)
(d)
(e)
(a)
(b)
(c)
(d)
(e)
(f)
(g)
(h)
3.

SQRT(3.14159)
ALOG(2.)
ALOG10(ABS(X))
SQRT(5.3)
SIN(37.*3. 14159/180.)

(f)
(g)
(h)
(i)

ABS(ALOG10(X))
SQRT(5.)
SIN(BETA)
SIN(SQRT(ALOG(20.)))

Integer variable .
None .
Real constant.
Integer function ref .
None .
None .
Real variable.
Real function reference.

(i)

Integer constant.
Integer constant .
None .
Real variable .
Integer constant.
Real variable .

(j)
(k)
(1)
Cm)
(n)

Because the argument is not a real number.

Section 2.6 (page 2-13)


1. (a)
(c)
(d)
(f)
(h)

Correct.
(b) Correct (BC is one variable).
Invalid, cannot juxtapose two operators.
Correct.
(e) Correct.
Correct.
(g) Invalid, parentheses do not match.
Correct

2. (a)

2.
(b) 2.
(c) 32.
(d) -(2.**64.) or
approximately -1.845 x 1010.
(e) -0.5 (f) -55.

3. (a)
(b)
(c)

(A + B)/(C + D)
EXP(3. 14159) - 3.14159**EXP(1.)
A*B**(X - 1.)
A-2

Solutions to Exercises
(d)
(e)
(f)

A*10.**0. 9*0. 9**10


TAN(ALPHA) + TAN(ALPHA)**2
(SIN(ALPHA + ABS(BETA))**2)/(ALOG(GAMMA) + EPS)

4. The correct FORTRAN expressions are:


(a) ALOG(2.*X + SIN (ALPHA))
(b) Correct .
(c) (TAN(BETA) - l.)**16.
(d) 7.9*10.**(2.*Y)
(e) Correct.
(1) A**(2.*B)
(g) ARSIN(COS(THETA)**2)
(h.) 3.*SQRT(1.*J*K) - X**3 or
3.*SQRT(FLOAT(J*K)) - X**3
(i) (A**B)**C
Section 2.7 (page 2-17)
1. (a)
(b)
(c)
(d)
(e)
(f)
2.

2.75. real.
2, integer.
2.75. real.
5.0625. real.
Zero, integer.
9, integer.

(g)
(h)
(i)
(j)
(k)
(1)

Zero, integer.
-0.5. real.
-0.5. real.
Zero, integer
-46656. integer.
9.5. real.

Yes, since the numerator always has one even factor.

3. (a)
(b)

5.5, real.
5.5, real.

(c)
(d)

0.5, real.
Zero, integer.

Section 2.8 (page 2-19)


1. Valid:
(d) , (f ) .
Invalid: (a), (b) . (c) , (e) . (g) .
2.

SAVEW - W
W - Z
Z Y
Y - X
X - SAVEW

3. (a) 5

(b) 9.3

(c) 9

(d) 5

A-3

(e) -3

Solutions to Exercises

4.

Assignment
Statement
X
Y
Z
X
I
I

=
-

Values after execution


Y
Z

2.2
4.7
X + Y
-Z
ABS(X)
I + 1

2.2
2.2
2.2
-6.9
-6.9
-6.9

4.7
4.7
4.7
4.7
4.7

6.9
6.9
6.9
6.9

6
7

5. (a) Y = 3.14159*X*10.**(-6.*Z)
(b) Y - (EXP(X)*COS(THETA) + X**(-X)*COSH(THETA))/(2.*X*Z)
(c) Z - l./U-l.) + l./(X-2.) +l./(X-3.)
G = 5.
H - 6.
I - 0

(MONTH has the integer value 6)

(J + l)/2*2 + 1
8.

K SqRT(FLOATU))

or

K - SQRT(1.*I)

Section 3.2 (page 3-8)


1

The first asterisk in the READ statement indicates that a default device (such
as a terminal keyboard) will be used for input. The first asterisk in the
WRITE statement also indicates that a default device (such as a TV monitor)
will be used for output. The second asterisks in both the READ and WRITE
statements indicate that list-directed (and not formatted) I/O will be used.

2 . The advantages of list-directed input and output include simplicity and easy
labeling of output variables. The main disadvantage is lack of control, espe
cially in the appearance of output.
3. READ (*.*) R. S. T. INDEX
2.5. 2.5E+05. 2.5E+09. -999
2. 5 250000.0 2500000000 -999
4. (a)
(b)

WRITE(*.*) R. S. T. INDEX
WRITE(*.*) 'R - '. R. ' S - '. S. ' T - '. T.
1 ' INDEX - ' . INDEX

5 . Largest integer that can be stored in memory.


A-4

Solutions to Exercises
Section 3.3 and 3.4 (page 3-15)
1.

(a) T
(b) F
(c) T
(d) F
(h) F (999 need not be STOP)

2.
or

101
101

READ (5.101) X.Y


FORMAT (10X. F10.3. 10X. F10.3)
FORMAT (2(10X. F10.3))

102

READ (5.102) X. Y. JANE. MARVIN


FORMAT (F10.3. E10.2// 16. 114)

3.

4.

(e) T
(i) T

Column:
Line 1:
Line 2:
Line 3:
Line 4:

(D T
(j) F

(g) F

12
3
12345678901234567890123456789012345
1001 -366
123456
2.71800
3.14159
5.28E+03

Assuming no other characters appear in the data lines, the FORMAT statement could
have been written more compactly as follows:
102 FORMAT (215/ 120/ 2F10.5/ E15.2)

5.
(a) The READ statement initiates reading on unit 5. A and B will be read
from the first line using the 2F10 . 4 specification. Since no additional
specifications appear in the FORMAT statement, the scanner goes back
to the beginning of the specification and reads C and D from the second
line using the 2F10.4 specification. The scanner will again encounter
the end of the specification and the process will be repeated for E. The
second of the F10.4 field specifications is not used for the last line.
(b) The READ initiates reading on unit 5. A and B will be read from the
first line using the 2F10.4 specification. The slash indicated the end
of a unit record, so the scanner goes down to the next line to read
C and D using the 2F10.4 specification. Encountering the next slash,
the scanner goes to the third line to read E. The last three F10 . 4 fields
will remain unused.
6. (a)
100

READ (5.100)

N. M. A. B. C. D. X. Y. Z

FORMAT (2110. 10X. 2F10.3/ 4X. 2F8.5. 2E15.5. 15X.


1 E15.5)
A-5

Solutions to Exercises

(b)
101

7.

READ (5.101) N. A, B, C, X. Z
FORMAT (110, 20X, 2F10.3/ 4X. F8.5. 8X. E15.5, 30X.
1 E15.5)

(c)
102

READ (5.102) C. D. X. Y. Z
FORMAT (/4X. 2F8.5. 2E15.5. 15X. E15.5)

(d)
103

READ (5.103)
FORMAT (/)

READ (5.100) N. ABLE. BAKER


100 FORMAT (15, F6.3. 4X. E10.3)

Column:

12
3
12345678901234567890123456789012345
1234
5.0
-0.329E-8

Section 3.7 (page 3-25)

(a) F

2.

(a), (b) , (c), (d) (at most installations), (e) .

3.

(b) (see output of Example Program 3.3, for example).

4.

205
1

5.

(b) T

(c) F

(d) F

(e) F

(f) T

FORMAT Cl', 8X. ' X-VALUES' . 7X. "Y-VALUES7


'0' , 2F15.2/ (' ' , 2F15.2))

206

FORMAT ('0lnput data are:'/ '0


A
1 F8.3/ 4X. "N
= ' , 14/ 4X. 'EPS

= ',
- '. E12.3)

207

FORMAT ('0Program worked! Results are:'/


1 '0
ITER
- ', 14/ 4X. 'VALUE - '. F10.5)

Section 6.2 (page 6-3)


1.

(a)
(c)
(e)
(f)

X .GT. 5.*Z + SIN(P)


(b)
B**2 .LE. 4.*A*C
(d)
I - J .EQ. (I - J)/3*3
M*(J + K)/2*2 .NE. M*(J + K)

A-6

ABS(X) .GT. EPS


J .EQ. J/5*5

Solutions to Exercises
2.

3.

(a)

|p?|35

<

n In 6.78 -

cos<

(b)

Exl.3xl0_4xeB - EBx4/[exp(2E)]B

No.

Sections 6.3 and 6.4 (page 6-8)


1. (a) F
2. (a)
(b)
(c)
(d)
(e)
(f)
(g)
QO
(i)

(j)

(b) F

(c) F

(d) F

(won't compile)

(e) T

X.EQ.Y .AND. Y.EQ.Z


X.NE.Y .AND. Y.NE.Z. AND. Z.NE.X
A.EQ.B .OR. A.EQ.C. AND. B.NE.C
(X + 2.) .LE. Z .AND. Z .LE. (X + 7.)
J.LT.I .AND. I.LT.K
(Assuming j is less than k)
X.GT.Y .AND. Y.GT.Z
A.EQ.0. .OR. B.GT.0.
A.EQ.0. .AND. B.LE.0. .OR. A.NE.0. .AND. B.GT.0.
ABS(X).EQ.ABSCY) .AND. ABS(Y) .NE.ABS(Z) .OR.
1 ABS(Y) .EQ.ABS(Z) .AND. ABS(Z) .NE. ABS(X) .OR.
2 ABS(Z) .EQ.ABS(X) .AND. ABS(X) .NE. ABS(Y)
2.LE.M. .AND. M.LE.9 .AND. 2.LE.N .AND. N.LE.9

3. SWITCH .NOT.(X.GE.Y .AND. Z .OR. X - (1. + Y).GT.0)


I
I
T
|
I
T
0.
I
I
I
I
T
F
I
I
T
i
I
F

A-7

Solutions to Exercises

.NOT.A.GT.3. .AND.B.LT.7. .AND. 3. .LT.C.OR. .X.EQ.7. .AND. SWITCH


II
II
I
I
I
I

F
I

I
F
I

F
I

F
I

5.

I*2.NE.J+K .AND. 3. .LE.B+SQRT(B+C) .OR. J.EQ.I+K


I
I
I
I
I
I
T
T
T
I
I
T
I

6.

I*J.EQ.2 .AND. J.LT.-6 .OR.


I
I
I
I
T
F
I
I

.TRUE.

7.

ABS(Y) .GE. ABS(X) .AND. ABS(Y) .LE. L/2.

8.

No difference.

9.

10.

LOGICAL ANSWER
ANSWER - Y.LT.0. .OR. X**2 + Y**2 .GT. 4.
1 X**2 + Y**2 .LT. 1.

.OR.

Sl .AND. (S4.AND. (S5.OR.S6) .OR. S2.AND.S3)

A-8

Solutions to Exercises

11.

(a) The first is an arithmetic assignment statement, whereas


the second is a simple logical expression.
(b) No difference.

12.
13.

IMULTJ - I/J*J .EQ. I


PYTHAG - ABS(X**2 + Y**2 - Z**2) .LT. EPS .OR.
1
ABS(Y**2 + Z**2 - X**2) .LT. EPS .OR.
2
ABS(Z**2 + X**2 - Y**2) .LT. EPS
(Here, EPS is some very small positive numberwhy?)

14.

LOGICAL Y
J - 3 (integer)
MASS 5 (integer)
X - 25. (real)
Y - .TRUE. (logical)

Section 6.6 (page 6-13)


1.
2.

Yes
I
0
1
2
3
4
5

Next Statement Executed


4
2
1
3
4
4

Section 6.7 (page 6-17)


1.

IF (I.NE.J) THEN
SAVEA - A
A - B
B - SAVEA
ELSE
X = SQRT(Y)
END IF

A-9

Solutions to Exercises
2.

1-2-3-4-5-6-7-8-11-12-5-9-10-13

3.

IF (X .LT. -1.) THEN


F = -1.
ELSE IF (X .LT. 1.) THEN
F - X
ELSE
F - 1.
END IF

4.

IF (A.LE.B .AND. I.EQ.J)


X - SQRT(Y)
ELSE
X - 0.
Z - Y
END IF

5.
1

6.

7.

10

THEN

IF (FX .LT. 0. .AND. FXR .LT. 0. .OR.


FX .GT. 0. .AND. FXR .GT. 0.) THEN
XR - X
ELSE
XL - X
END IF

IF (NDAYS .EQ. 366) THEN


WRITE (6.201)
201
FORMAT ('0
LEAP YEAR")
END IF
N

Final Value of M

0
1
2
3
4

1
1
2
6
24

M = 1
IF (N .GT. 1)
I - 1
I - I + 1

(Factorial of N is stored in M)

THEN

A-10

Solutions to Exercises
M M*I
IF (I .NE. N)
END IF

8.
101

201

GO TO 10

LOGICAL LOG1, LOG2, OPER


READ (5.101) LOG1, OPER. LOG2
FORMAT (3L5)
IF (OPER) THEN
WRITE (6.201) LOG1 .AND. .NOT. LOG2
ELSE
WRITE (6.201)
.NOT. LOG1 .OR. LOG2
END IF
FORMAT ('0Logical expression is ', Ll)
STOP
END

Data Lines
Col:

1
2
12345678901234567890

Output:
Logical expression is F
Logical expression is F
9.

PI - 3.14159
IF (X .LE. -2.) THEN
F = -2.
ELSE IF (X .LE. 0) THEN
F - X
ELSE IF (X .LE. 1.5*PI) THEN
F - SIN(X)
ELSE
F - -1.
END IF

Section 6.8 (page 6-22)


1
2.

(a) F

(b) F

(c) T

(d) F

IF (X .LT. 0.) THEN


INEG = INEG + 1
A-ll

(e) F

Solutions to Exercises
ELSE IF (X .EQ. 0.)
IZER - IZER + 1
ELSE
IPOS - IPOS + 1
END IF

THEN

(Can also be done using the arithmetic IF statement)


3.

Execution
Number
1
2
3
4
5
6
(a) 3

(b) 5

ITER
1
2
3
4
5
6

SUM
0.
0.
0.
0.
5.
11.

PROD
1.
2.
6.
24.
24.
24.

(c) 3

Section 7.2 (page 7-3)


1.

(a) Override normal precedence of operators in


expressions.
(b) FORMAT specification.
(c) Subscripts.
(d) Function reference.
(e) IF (
) THEN, etc.

2.

(a) Acceptable.
(b) Unacceptable in subset FORTRANthe smallest
subscript allowed is 1.

3.

Y - Y(I) + (X - X(I))*(Y(I + 1) - Y(I))/


1
(X(I + 1) - X(I))

4.

Yes (one standard word equals four bytes).

5.

Only (c).

Sections 7.3 (page 7-8)


1.

(a) T

(b) T

(c) F

(d) F

A-12

(e) F

(f) F

(g) T

Solutions to Exercises

2.

(a)

Unacceptable; cannot use DO statement in conjunction


with logical IF statement.
Acceptable.
Acceptable, although somewhat unusual.

(b)
(c)
3.

(a)

The statement number must be an integer constant,


such as 67.
The statement number N is not an integer constant.
The index cannot be the element of an array.
Legal if COUNT is declared to be an integer (for
subset FORTRAN, otherwise OK).

(b)
(c)
(d)

4.

(a) 6

(b) 5

(c) 10

(d) 2

5.

The index K must not be reassigned inside the loop under


any circumstances. The last statement in the range must
not involve an unconditional transfer (GO TO).

6.

(a)
(b)
(c)

DIMENSION A (100) . B(100). C(100)


DIMENSION C(202)
DIMENSION ALPHA(200) . BETA(201) (last M is 199)

Section 7.4 (page 7-18)


1.

2.

3.

Yes.
DO 5

I - N - 1, 1, -1

DO 30 INT ' 2, N, 2
IF (K(INT)/2*2 .NE. K(INT))

NUMBER - NUMBER + 1

DO 30 INT - 1, N. 2
IF (K(INT)/2*2 .EQ. K(INT))

NUMBER - NUMBER + 1

Initialize to zero the array CUST:

10

DO 10 J = 1, M
CUST(J) = 0
CONTINUE

Then insert the following statement before the one numbered 40:
CUST (J) CUST (J) + SALE (I, J)
A-13

Solutions to Exercises

4.

10

MID - N/2
DO 10 I - 1, MID
SAVEA - A(I)
A(I) A(N - I + 1)
A(N - I + 1) - SAVEA
CONTINUE

10

SMDIAG - 0.
PRDIAG - 1.
DO 10 I - 1. N
SMDIAG = SMDIAG + A(I.I)
PRDIAG - PRDIAG*A(I,N-I+1)
CONTINUE

10
20

NNEG - 0
NZER = 0
NPOS - 0
DO 20 I - 1,
DO 10 J - 1, I - 1
IF (A(I.J) .LT. 0.) THEN
NNEG - NNEG + 1
ELSE IF (A(I,J) .EQ. 0.) THEN
NZER - NZER + 1
ELSE
NPOS - NPOS + 1
END IF
CONTINUE
CONTINUE

5.

6.

7.

10
20
30

INTEGER TOTAL
TOTAL = 0
DO 30 I - 1, L
ITEM(I) - 0
DO 20 J = 1.
DO 10 K ITEM(I)
TOTAL CONTINUE
CONTINUE
CONTINUE

M
1. 12
- ITEM(I) + NSALES(I.J.K)
TOTAL + NSALES(1, J,K)*PROF(I)

A-14

Solutions to Exercises

8.

POLY - A(l)
DO 10 I 1. N
POLY POLY + A(I+1)*X**I
10

CONTINUE

10

POLY - A(N+1)
DO 10 I - N. 1. -1
POLY - POLY*X + A (I)
CONTINUE

9.

10.

INTEGER FN. FN1 . FN2


FN1 - 1
FN = 1
IF (N .GT. 1) THEN
DO 10 I - 2. N
FN2 - FN1
FN1 - FN
FN FN1 + FN2
10

11.

CONTINUE
END IF
DIMENSION A(10.10)

C
C

Take each element in turn


DO 40 I = 1, M
DO 30 J - 1, N

C
C
C

10
20
30
40

Compare with all subsequent elements


and make an interchange if necessary
DO 20 K - I, M
DO 10 L - J+l. N
IF (A(I.J) .LT. A(K.L)) THEN
SAVEA - A(I.J)
A(I.J) - A(K.L)
A(K,L) - SAVEA
END IF
CONTINUE
CONTINUE
CONTINUE
CONTINUE
A-15

Solutions to Exercises

12.

SUM2 = 0.
SUM3 0.
DO 10 I - 1, N
IF (V(I) .GT. 0.) THEN
SUM2 = SUM2 + V(I)**2
SUM3 - SUM3 + V(I)**3
END IF
CONTINUE

10

Section 8.4 (page 8-4)


1.

LOGICAL CHECK
READ (6. 200) A. B. X. CHECK
FORMAT (3G10.3. L10)

200

12
3
4
1234567890123456789012345678901234567890
3.6E+17
0.0004
7654
T

Col:

2.

UP - .FALSE.
DOWN .TRUE.
X - 123.45
Y - 3.142
XJK - 6.2
Data
Col:
or

12
3
123456789012345678901234567890
T
F
.TRUE.
.FALSE.

Output
Col :

1
2
3
123456789012345678901234567890

Section 8.6 (page 8-16)


1. (a)
100

READ (5.100) N. (X(I). Y(I) , I - 1 . N)


FORMAT (15/ (10F8.5))

A-16

Solutions to Exercises

(b)
105

READ (5.105) N. (Y(I), I - 1 . N)


FORMAT (15/ (5(8X, F8.5)))

110

READ (5.110) N. (X(I). Y(I) . I - 1. N, 2)


FORMAT (15/ (3(2F8.5. 16X)/ 2(16X, 2F8.5)))

(c)

(d)

Assuming just one data set, the following is


one possibility, also illustrating the REWIND
statement (see Section 8.7):

115
116

READ (5.115) N. (X(I) . I - 1. N. 2).


REWIND 5
READ (5.116) (Y(I). I - 2. N. 2)
FORMAT (15/ (F8.5.2(24X.F8.5)/ 16X.2(F8.5.24X)))
FORMAT (/ (2(24X.F8.5)/ 8X. 3(F8.5.24X)))

100

READ (5.101) N. EPS. P(5). (A(I). I - 1, N)


FORMAT (15. E15.3. 10X. F10.5. 2F10.4/ (5F10.4))

2. (a)

(b)

3.
(a)

(b)

WRITE (6.105) (I, R(I) . W(I) . V(I) . I = 1 . N)


105 FORMAT (T4. 'I". T12. 'RADIUS'. T24. 'WEIGHT'
1
T36. 'VOLUME'/
2 C0'. 14. 5X. F8.3, 4X. F8.5. 4X. F8.2))

Col:

Col:

12
3
123456789012345678901234567890
3
5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

12
3
123456789012345678901234567890
3
5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
A-17

Solutions to Exercises

(c)

12
3
4
1234567890123456789012345678901234567890
3
5
1
6
11
2
7
12
3
8
13
4
9
14
5
10
15

Col:

4.
201

WRITE (5,201) (Q(I.I). I - 1. 10)


FORMAT Cl'. F10.3/ ('
F10.3))

5.

Answer is (b) .

6.

Elements will be written column-by-column.

7.

(a) (iv)

8.

(b) (vi)

DO 10 I - 1. 20
WRITE (6.202)

(c) (i)

(BET1(I.J). J 1, 12)

10
202

CONTINUE
FORMAT ('0' . 12F6.2)

20
203

DO 20 I - 1, N
WRITE (6.203) (B(I.J), J - 1. M)
CONTINUE
FORMAT ('0'/ ' ', 12F10.4/ (' ' , 12F10.4))

9.

Section 9.2 (page 9-2)


1.

REAL INTOCM. LBTOKG


DATA INTOCM. LBTOKG. GALLTR /2.54. 0.45359. 3.78541/

2.

DIMENSION V(100)
DATA V. E. PI /100*0.. 2.71828. 3.14159/

3.

REAL MATRIX
DIMENSION X(10), MATRIX (10. 10) . TRIPLE(10.10.10)
DATA X, MATRIX, TRIPLE /1110*0./

4.

REAL M
DIMENSION M(2.4)
DATA M /6.4. 0.0, 2.8, 0.0. -0.6. 0.0. -1.6. 7.9/

A-18

Solutions to Exercises
5.

DIMENSION ITEM (4,5)


DATA ITEM/1. 4*0. 2. 4*0. 3. 4*0. 4. 4*0/

6.

A(1.2) - 1.6
A(l,4) - 2.

A(3.2) - 2.
B(2) - 2.5

7.

M(2.1) - 1.
M(3.3) - -3.

x(1) - 0.
X(5) - 1.0

Section 9.3 (page 9-8)


1. (a) F

(b) F

(c) F

(a)
(b)
(c)
(d)

Real, 4 bytes.
Real, 8.
Integer. 4.
Integer 4.

(d) F
(e)
(f)
(g)
(h)

Real, 8.
Logical. 4(?)
Real, 8.
Real, 8.

3.

REAL*8 X. Y, Z
X - 3.7D0
Y 4.6D0
Z - X/DSQRT(Y)

4.

Add: REAL*8 A, B, C, Z; change SQRT to DSQRT; change


SIN to DSIN; change 2.8 to 2.8D0; optionally, change 4F10.5
to 4D15.5.

5.

IMPLICIT INTEGER*2 (R. Z) . LOGICAL*2 (T)


IMPLICIT REAL*8 (A- J. P. X)
(Note:

6.

LOGICAL*2 is available in MS-FORTRAN only.)

The single statements are equivalent to the following:


(a)

INTEGER*2 MAN. JOE


INTEGER D. F
DIMENSION D(4.4.2). MAN (20) . F(3.2)
DATA D. F/4*2. 8*-3, 20*2. 6*5/

(b)

REAL MEAN
REAL*8 AL
DIMENSION MEAN(3.4.7). AL(10)
DATA MEAN. AL/42*1 .E-25. 42* -lE. -25. 5*5. 2DO. 5*0. D0/
A-19

Solutions to Exercises
Section 9.4 (page 9-11)
1.

EQUIVALENCE (A(1.1). MAT(1.1)). (A(1.51). VEC(1))


EQUIVALENCE (A. MAT). (A(1.51), VEC(1))

2.

(b)

3.

X(6) - 6.. X(9) - 11., Y(2) = 4.. Y(10) - 14.

4.

VEL - 10.5. X(1) - 1.. Y(5) - 4.

or

Invalid; conflicts with the natural sequence of storage


for the vector Y.

Section 10.2 (page 10-14)


1.

(a) F

(b) F

(c) F

(d) F

2.

A - 6.. B 3.. C = 0.5. X 10.. Y - 4. . Z 2.5

3.

INTEGER FUNCTION FACT(N)


FACT - 1
DO 10 I - 1. N
FACT - FACT*I
10 CONTINUE
RETURN
END
Reference (c) is illegal because the calling argument is not an
integer.

4.

A - 2., B - 7.. C - 2. . D - 4. . E 6. . F - 3.

5.

10

LOGICAL FUNCTION CHECK (V,N)


NUMBER - 0
DO 10 I - 1. N
IF (V(I) .GT. 0.) THEN
NUMBER - NUMBER + 1
ELSE
NUMBER - NUMBER - 1
END IF
CONTINUE
CHECK - NUMBER .GT. 0
RETURN
END
A-20

Solutions to Exerciaea

6.

10

7.

INTEGER FUNCTION FIBON(N)


INTEGER Fl. F2
DATA Fl. F2 /l . 2/
FIBON 1
IF (N .LE. 1) RETURN
DO 10 I - 3. N
FIBON - Fl + F2
Fl - F2
F2 FIBON
CONTINUE
RETURN
END
FUNCTION F(X)
IF (X .LE. -2.) THEN
F - -2.
ELSE IF (X .LT. 0.) THEN
F - X
ELSE IF (X .LT. 1.5*3.14159)
F - SIN(X)
ELSE
F - -1.
END IF
RETURN
END

8.

10

LOGICAL FUNCTION PRIME(N)


PRIME - .TRUE.
M - SQRT(1.*N)
DO 10 I - 1. M
IF (N/I*I .EQ. N) THEN
PRIME - .FALSE.
RETURN
END IF
CONTINUE
RETURN
END

A-21

THEN

Solutions to Exerciaea

9.

(a) The program reads and prints the coefficients of an


nth-degree polynomial, and then references the function
EVAL to evaluate the polynomial for a given value of x.

(b) EVAL ai + a2x + a3x2 + ,,, + aw+ix"


(c) 3. -

1. x 2. + 2. x 2. x 2.

9.

12
3
4
Col: 123456789012345678901234567890123456789012345678

(d)

N -

2
3.000

(e)

10

x -1.000

3.000

P =

9.000

2.000

No. The correct value is a0, but this is multiplied by 0. in


the function EVAL, whose middle four statements should be
replaced by:
EVAL - A(1)
DO 10 I - 2, N + 1
EVAL - EVAL + A(I)*X**(I-1)
CONTINUE

Section 10.4 (page 10-25)


1.

(a) F

2.

A - 10. , B - 10. , C - 4.

3.

A - 0.5. B - 64.. C - 4.. X - 2.. Y - 8.. Z - 0.25

4.

10

(b) T

(c) F

SUBROUTINE FUNX (X. EPS. LOG1PX. N)


REAL LOG lPX
LOG1PX - X
D0 10 I - 2. N
TERM - X**I/I
LOG1PX - LOG1PX - (-1)**I*TERM
IF (ABS(TERM) .LT. EPS) RETURN
CONTINUE
RETURN
END
A-22

Solutions to Exercises
Section 10.7 (page 10-32)
1.

Yes.

2.

P - 52.

3.

VAR - 2.5

4.

R -0.5
S = 0.8

5.

AREA(ALPHA. B. C) - 0. 5*B*C*SIN(ALPHA*3 . 14159/180. )


Y = SQRT(3.)
Z - 2.
AREA1 - AREA(30.. SQRT(3.). 2.)
AREA2 - AREA(D. P, Q)

Section 10.8 (page 10-35)


1.

The declaration REAL JIMMY is missing.


A 1. , B - 2. . C - 7. . Z - 6.

2.

A 0.25. B - 2.. C - 4.. D - 0.25

3.

A = 4.. B = 1.5. C = 6.. D - 36.. S - 18.. T = 8. . U

Section 11.1 (page 11-2)


1. (a) F
2.

(b) F

CHARACTER*4 X. Y. Z. NAME*25. WORD*50

Section 11.2 (page 11-6)


1. (a) T
2.

201

(b) T

(c) T

CHARACTER BO*11, WOODY*12


DATA BO. WOODY/ 'Michigan 14'. 'Ohio State 6'/
WRITE (6.201) BO. WOODY
FORMAT Cl'. All. '.
A12)
END

A-23

Solutions to Exercises

3.

12
3
4
123456789012345678901234567890123456789012345
101 633-9248 G. MOREHOUSE
102 994-0024 A. JOHNSON
103 761-9103 A. SEITZ

Col:

4.

PROGRAM BOOKS
CHARACTER TITLE*20, LAST*10, FIRST*10
INTEGER YEAR
WRITE (6.201)
FORMAT (5X, AUTHOR', 10X, 'BOOK', 11X. 'DATE')

201
1
101

READ (5.101.END=999) TITLE. LAST. FIRST, YEAR


FORMAT (5X, A20. 2A10. 2X. 12)
WRITE (6.202) FIRST. LAST, TITLE. YEAR
FORMAT (2X. Al , '. ', A10. A20. 12)
GO TO 1
STOP
END

202
999

Sections 11.3 (page 11-12)


1.

(a) F

2.

Change .GT. to .LT.

3.

1.
2.
3.

4.

(b) T

(c) F

UMARY (U - blank)
LUKEU
MARKU

(d) T

4. MARYU
5. MARY,
6. MARY.

A logical expression, with the value .TRUE.

5.

PROGRAM DECODE
CHARACTER*4 CHARS. GROUP
DIMENSION CHARS(3). GROUP(10)
DATA CHARS /"ABCD" . 'em7X'. 'XXXX7
LINE = 0
READ (5.101.END=999) (GROUP (I). 1=1. 10)
LINE = LINE + 1
DO 20 I - 1, 10
DO 10 J - 1. 3
IF (GROUP(I) .EQ. CHARS(J)) THEN
A-24

Solutions to Exercises

10
20
990
101
201

WRITE (6.201) CHARS(J). LINE


END IF
CONTINUE
CONTINUE
GO TO 1
STOP
FORMAT (10(A4. lX))
FORMAT (' Sequence '. A4. ' found in line

END

A-25

13)

Solutions to Exercises
Notes

A-26

APPENDIX B
SUMMARY OF STATEMENT TYPES

See Table 1.2 for general references used in the following.


Prototype

Purpose

Executable Statements
BACKSPACE U

Backspace file pointer

CALL 7 (Al*. A2*

An*)

Call for subroutine

CLOSE (U)

I/O unit termination

CONTINUE

Continuation

DO M VI - II. 12. 13

Iteration

END

End of (sub)program

ENDFILE U

End-of-file record

GO TO M

Unconditional transfer

GO TO (Ml. M2

Mn). VI

Multiple transfer

IF (Bl) THEN
General
form
of
block
conditional
structure

ELSE IF (82) THEN


ELSE IF (S3) THEN
ELSE
END IF
IF (B) S

Logical conditional

IF () Ml. M2. MS

Arithmetic conditional

OPEN (U. FILE'P'. STATUS-' status')

I/O unit identification

B-l

Appendix BSummary of Statement Types


PAUSE

Suspend execution

READ (U. *) t

List-directed input

READ {U. *, END=J/)

List-directed input

READ (tt, *, ERR-JYl. END-JV2)

List-directed input

READ (U. JJ) t

Formatted input

READ (Zi, JVl. END=A/2)

Formatted input

READ (tt.

Formatted input

ERR=J/2, END=A/3) t

READ CVC. A/)

Internal input

REWIND

Move pointer to
beginning of file

STOP

Terminate execution

STOP I

Terminate execution

STOP 'C

Terminate execution

V =

Arithmetic assignment

VB = B

Logical assignment

vc - tc

Character assignment

WRITE (U. *)

List-directed output

WRITE (U. AO t

Formatted output

WRITE (VC. AO t

Internal output

Nonexecutable Statements
CHARACTERS
COMMON Vl. V2

Explicit character type


Vn

COMMON /MAMS/ Vl. V2

DATA / Cl. C2

Shared variables
Vn

Shared labeled
variables

Cn/

DIMENSION V (11. 12.

Variable initialization
In)

Array storage

DOUBLE PRECISION t

Explicit doubleprecision type

EQUIVALENCE (Vl. V2
EXTERNAL 7l . 72

Vn)

Alternative naming

7n

Subprogram names as
subprogram arguments
B-2

Appendix BSummary of Statement Types


M FORMAT (Format specification)

I/O format

IMPLICIT T*b (Range of first letters)

Implicit type

INTEGER*b C

Explicit integer type

INTRINSIC 71. 72

Library function name


as subprogram argument

7n

LOGICAL*b C

Explicit logical type

REAL C

Explicit real type

PROGRAM 7

Main program name

Function Subprogram
7*b FUNCTION 7 Ml. A2
ENTRY 7 (Al. Al

An)

An)

Heading
Additional entry

7 - t or B or C

Assign value

RETURN

Return to calling pro


gram

Subroutine Subprogram
SUBROUTINE 7 (Al. AT.
ENTRY 7 (Al. A2

An)

Heading

An)

Additional entry

RETURN or RETURN I

Return to calling pro


gram

Statement Function
7 (Al. A2

An - or B)

Define function

BLOCK DATA Subprogram


BLOCK DATA

Heading

B-3

Appendix BSummary of Statement Types


Notes

B-4

INDEX

naming of, 7-1


segment, in input and
output lists, 8-6, 8-11
storage of elements in, 7-3
subscripts for, 7-1
ASCII character codes, 11-8
Assignment statement,
arithmetic, 2-1, 2-17
character, 11-2
logical, 6-8
Attention interrupt, 4-10

A field (format code), 11-2


A, subprogram dummy
argument, 10-21
A*, subprogram calling
argument, 10-21
Algorithm, 1-4
Alphabetizing a list, 11-9
Alphanumeric characters, 1-19
. AND . , logical operator, 6-5
ANSI, 1-7
Arguments, actual or calling,
10-2, 10-7, 10-21
dummy, 10-2, 10-5, 10-18,
10-21, 10-31
Arithmetic expression, 2-1,
2-10
mixed-type, 2-15
rules for forming, 2-12
type (mode) of, 2-16
Arithmetic
assignment statement, 2-17
IF statement, 6-22
operators, 2-10
precedence for, 2-10
unit, 1-3
variables, 2-5
Arrays, 7-1
dimensioning of, 7-2, 10-17
input and output, 8-5, 8-9

B
B, Logical (Boolean)
expression, 6-3, 6-5
BACKSPACE statement, 8-20
Batch files, for compilation,
4-6
Binary computer, 1-2
Blank COMMON, 10-33
Blanks, in FORTRAN statements,
1-19
in A fields, 11-3
in literal fields, 3-20
BLOCK DATA subprogram, 10-36
Block IF structures, 6-14
nested, 6-17
Boolean (see Logical)
Byte, 1-2, 11-1
I-l

Index
Computer (see Digital computer)
Conditional
structures, 6-1
transfer statement, 6-12
Conditional, statements,
6-14, 6-22
nested, 6-17
Constant, character, 11-1
double-precision, 9-56
integer, 2-3
literal, 11-1
logical, 6-2
real, 2-3
Continuation line, in FORTRAN,
1-20
code for, 1-20
CONTINUE statement, 7-6
Control unit, 1-4
CPU (see Central processing
unit)

C, arithmetic or logical
constant, 2-3, 6-2
'C, character constant, 11-1
Calling arguments, 10-2, 10-7,
10-21
agreement with dummy
arguments, 10-7
CALL statement, 10-20
Card, reading and punching,
8-2
Carriage control, 3-20
characters for, 3-21
Central processing unit (CPU),
1-4
time limit, 5-1
Character, alphanumeric, 1-19
ASCII codes for, 11-8
assignment statement, 11-2
constant, 11-1
manipulation of, 11-8
reading and printing of,
11-3
special, 1-19
variable, 11-1
CHARACTER declaration, 9-45
CLOSE statement, 8-2
Comments, in FORTRAN programs,
1-20
COMMON declaration, 10-33
blank, 10-33
labeled, 10-34
presetting values of
variables in, 10-36
Compiler, 1-6
MS FORTRAN, 4-2, 4-4
VS FORTRAN, 5-1, 5-5
Compound logical expressions,
6-5
Computed GO TO statement, 6-12

D, I/O device or file,


4-8, 5-3, 8-2
DATA declarations, 9-1
initialization of COMMON
variables, 10-36
Decimal points in real con
stants, 2-3
in input fields, 3-11
Declarations, 1-21, 9-1
Destructive read-in, 1-2
Device, input and output,
4-8, 8-2
Diagnostics (see Error
Messages)
Digital computer, 1-1
general-purpose, 1-1
organization of, 1-2
DIMENSION declaration, 7-2,
1-2

Index
MS FORTRAN, 4-11
VS FORTRAN, 5-10
Executable statement, 1-21
Execution, of object program,
MS FORTRAN, 4-7, 4-10
termination of, 4-10
VS FORTRAN, 5-3, 5-5
Exponent, floating-point,
in FORTRAN constant, 2-4
range, for real numbers,
2-4
Exponentiation, 2-10
Expression, arithmetic, 2-10
compound logical, 6-5
mixed type, 2-15
simple logical, 6-3
EXTERNAL declaration, 10-28

9-8
in functions and
subroutines, 10-17
Diskette, configurations for,
4-6
DO statement (see Iteration
statement)
DOUBLE PRECISION
constant, 9-5
declaration, 9-5
function references, 9-7
Drive, configurations for,
5-5
Dummy argument, 10-2, 10-5,
10- 18, 10-21, 10-31

E
E-type constant, 2-4
, arithmetic expression,
2-10
C, character expression,
11-2
iI or I, integer
expression, 2-16
t Z, real expression, 2-16
E field (format code), 3-10
ELSE statement, 6-16
ELSE IF statement, 6-16
END statement, 1-23, 10-7
ENDFILE statement, 8-20
END IF statement, 6-14, 6-16
End of file, 3-2, 4-10
END, option in read statement,
3-2, 3-8, 8-2, 4-10
ENTRY statement, 10-26
. EQ . , relational operator, 6-3
EQUIVALENCE declaration, 9-10
. EQV . , logical operator, 6-5
ERR option, 3-2, 3-8
Error messages,

F
F field (format code), 3-10
F-type constant, 2-3
7, subprogram name,
Field
in input and output, 3-9
overspecified, 3-12
underspecified, 3-11
File, allocation to I/O unit,
4-8, 8-1
File-control statements, 8-20
BACKSPACE, 8-20
ENDFILE, 8-20
REWIND, 8-20
File-name extensions,
.EXE, 4-4, 4-5
. LST, 4-5, 4-7
.MAP, 4-5
.OBJ, 4-5
FLOAT function, 2-17
Floating-point type, 2-2
Flow diagram,
1-3

Index
assignment block, 2-18
conditional-transfer
block, 6-14
examples of, 1-10, 6-24
IF/THEN/ELSE block, 6-14
input and output blocks,
3-8
iteration block, 7-5
unconditional-transfer
block, 6-12
FORMAT declaration, 3-9,
8-3, 11-3
Format, of FORTRAN statements,
1-19
comment, 1-20
continuation code, 1-20
statement label field, 1-20
statement field, 1-20
Format specifications, 3-8,
8-3, 11-3
A field, 11-2
E field, 3-10
F field, 3-10
6 field, 8-3
I field, 3-10
L field, 8-3
parentheses, for
repetition, 8-8
slash, for end-of- record,
3-12
T (transfer) code, 8-3
X field, 3-10
variable, 11-13
FORTRAN 77, analogy with
English language, 1-8
development of language,
1-6
MS FORTRAN, 4-1
statement format, 1-20
VS FORTRAN, in MTS, 5-1
*FORTRANVS, public file, 5-2,

5-8
Freshman engineering computing
laboratory at U-M, 4-6
Function,
double-precision, 9-7
library, 2-7
name, in EXTERNAL
declaration, 10-28
name, in INTRINSIC
declaration, 10-28
references, 2-8
statement or internal,
10-30
subprogram, 10-5
FUNCTION declaration, 10-5

G
G field (format code), 8-3
.GE., relational operator, 6-3
General references, 1-21
GO TO statement, 1-22, 6-12
.GT., relational operator, 6-3

H
Hardware, 1-1
H (Hollerith) format code,
3-19

I
I field (format code), 3-10
J, integer expression, 2-16
in the DO statement, 7-6
IBM 3090-600 computer, 5-1
IF statement, arithmetic, 6-22
block, 6-14
logical, 6-20
IF/THEN structure, 6-14
1-4

Index
Internal statement numbers,
5-11
Interrupt, program, 4-10
INTRINSIC declaration, 10-28
Iteration (DO) statement, 7-4
generation of table by,
7-10
index restrictions, 7-6
index in, 7-6
nested, 7-8, 7-15
range, 7-5

IF/THEN/ELSE structure, 6-15


IF/THEN/ELSE IF/ELSE
structure, 6-16
IFIX function, 2-17
IMPLICIT declaration, 9-6
Index, in DO statement, 7-6
Input and output, 1-3, 3-1
array, 8-5, 8-9, 8-13
character, 11-2
device assignments for,
END and ERR parameters,
3-2, 3-8, 8-2
equipment for, 1-3
formatted, 3-8, 3-17, 8-3,
8-9
internal, 11-13
list-directed, 3-2
lists for, 3-2, 3-8, 3-17, 8-13
statements, 3-2, 3-8, 3-17
8-2, 8-5
READ statement, 3-2, 3-8,
8-2, 8-5
variable format, 11-13
WRITE statement, 3-2, 3-17,
8-3
Instruction, machine-language,
1-4
repertoire, 1-5
Integer constant, 2-3
division, 2-15
field (format code), 3-10
type, 2-2, 9-3
variable, 2-5
INTEGER declaration, 2-6, 9-3
Interchanging values of two
variables, 6-14
Internal function (see State
ment function)
Internal I/O statements, 11-13
READ, 11-17
WRITE, 11-13

L
L field (format code), 8-3
Z, list, 3-2, 3-8, 3-17,
8-2, 8-5
Label, statement, 1-20
Labeled COMMON, 10-34
. LE. , relational operator, 6-3
Length, specification, 9-5
Library program, 2-7, 10-4
Line spacing, (see Carriage
control)
Linking object programs, 4-1, 4-3
List, in input and output
statements, 3-2, 3-8,
3-17, 8-2, 8-5
List-directed I/O statements,
3-2
example programs for, 3-5,
3-6
including character
strings, 3-5, 11-5
Literal (see also Character),
constant, 11-1
field, 3-19
-LOAD, MTS file, 5-2
Logical
assignment statement, 6-8
constant, 6-2
1-5

Index
expression, simple, 6-3
compound, 6-5
format code, 8-3
IF statement, 6-20
operators, 6-5
variable, 6-2
LOGICAL declaration, 6-2, 9-3
Logical I/O units in MTS, 5-2
Loop, iteration, 7-4
. LT., relational operator, 6-3

N
M, statement number,
MAMS , labeled COMMON block
name,
Naming conventions, common
block, 10-34
functions, 10-6
subroutine, 10-20
variables, 2-5
.NE. , relational operator, 6-3
.NEQV., logical operator, 6-5
Nested statements,
conditional, 6-17
iteration, 7-8, 7-15
Nondestructive read-out, 1-2
Nonexecutable statement, 1-21
. NOT . , logical operator, 6-5
Number, FORTRAN statement,
1-20
Numbers (see Constants)

M
Machine
language, 1-4
instruction, 1-4
program, 1-5
Main subprogram, 10-1
Manipulation of characters,
11-8
Mantissa, 2-3
Matrix, (see also Array)
FORTRAN storage as vector,
7-3
input and output of, 8-9
array segment notation
for, 8-6
Memory, (see also Storage),
1-2
Messages, in output, 3-19
error (see Error messages)
Mixed-type expressions, 2-15
Mode, (see Type)
MS FORTRAN, 4-1
compilation, 4-1, 4-3, 4-6,
diagnostics, 4-11
execution, 4-7, 4-9
MTS (Michigan Terminal
System), 5-1, 5-5

O
Object program, 1-6
MS FORTRAN, 4-1, 4-5
VS FORTRAN, 5-4
OPEN statement, 1-16, 8-1
Operands, arithmetic, 2-2,
2-13
Operators, arithmetic, 2-10
logical, 6-5
relational, 6-3
.OR. , logical operator, 6-5
Order of statements, 9-13
Output statements (see WRITE
statement)
Output equipment, 1-3
1-6

Index
internal, 11-17
list-directed, 3-2
Real constant, 2-3, 9-5
field, 3-10
type, 2-2
variable, 2-5, 9-5
REAL declaration, 2-6, 9-3
Record, unit, 3-9
Relational operators, 6-3
Repeating parentheses, 8-8,
8-10, 8-11
RETURN statement,
in functions, 10-6
in subroutines, 10-23
REWIND, 8-20
$RUN, MTS command, 5-1, 5-8

P
Parentheses, in arithmetic
expressions, 2-11
in repeated FORMAT speci
fications, 8-8, 8-10,
8-11
Plotting the sine function,
11-14
Precedence, of arithmetic
operators, 2-10
complete table, all
operators, 6-12
of logical operators, 6-5
Precision, 9-4
Presetting variables and
arrays, 9-1
Procedure-oriented language,
1-5
Procedure, 10-1
PROGRAM declaration, 1-12
Pseudo-device, 5-2
Punched card (see Card)

S
S, executable statement, 1-21
SCARDS, SPRINT, SPUNCH, 5-2
$SIGNOFF, MTS command, 5-9
SSIGNON, MTS command, 5-6
Simple logical expression, 6-3
Skip field, 3-10
Slash, format specification,
3-12
Source program, 1-7
Special characters, 1-19
Statement, FORTRAN, (see also
under individual
statement types)
executable, 1-21
format for, 1-20
function, 10-30
nonexecutable, 1-21
number, 1-20
order in program, 9-13
STATUS parameter in OPEN
statement, 5-3
STOP statement, 1-23

Q
Quadratic equation, roots of,
6-24

R
relational operator, 6-3
Range, of constants, 2-4
of DO loop, 7-5
Read-in, destructive, 1-2
Read-out, nondestructive, 1-2
READ statements, (see also
Input and output
statements)
formatted, 3-8,
8-2, 8-5
1-7

Index
Storage, 1-2
disk file, 1-3
diskette, 1-3
magnetic tape, 1-3
Stored-program computer, 1-5
Subprograms, arrangement of,
10-36
BLOCK DATA, 10-36
FUNCTION, 10-5
main, 10-1
SUBROUTINE, 10-20
SUBROUTINE subprogram, 10-20
Subscripted variables, (see
Arrays)
Subscripts, 7-1
Substitution statement, (see
Assignment statement)
Symbolic, language, 1-5
names, 1-21

real, 2-2
Type declarations, 9-3, 9-8
explicit, 2-6
for functions, 10-13
implicit, 2-5

U
U, I/O unit number, 3-2,
5-3, 8-2
Unconditional transfer
statement, 1-22, 6-12
Unformatted input and output
statements (see Listdirected I/O)
Unit record, 3-9

V
V, arithmetic variable, 2-5
VB , logical (Boolean)
variable, 6-2
VC, character variable, 11-1
VJ, integer variable, 2-5
VZ, real variable, 2-5
Variable, formats, 11-13
Vector, (see also Arrays)

T
T, type or mode (see
CHARACTER. INTEGER.
LOGICAL, REAL,)
T (transfer) format code, 8-3
%TELECOPY, for file transfer,
5-6, 5-7, 5-9
Terminating execution, 1-23,
4-10
THEN statement, 6-14
Time, access, 1-2
limit on CPU, 5-1
Transfer, format specifi
cation, 8-3
statements, 1-22, 6-12
Translation, of source
program, 1-6, 4-1
Truth tables, 6-6
Type (mode)
integer, 2-2

W
WINDOW communications program,
5-5
Word processor, 11-20
WRITE statement, (see also
Input/output statements)
formatted, 3-17
internal, 11-13
list-directed, 3-4

X
X field (format code), 3-10
1-8

UHtVEBSm Of KICK

9015 01830 2490

You might also like