Professional Documents
Culture Documents
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
1.4
1.5
1-1
1-6
1-9
1-11
1-14
1-19
1-22
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
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
3-9
3-17
3-19
3-20
3-22
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
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
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
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
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
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
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
10-30
10-33
10-36
10-36
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:
B-l
INDEX
1-1
VI
CHAPTER 1
INTRODUCTION TO COMPUTERS AND FORTRAN
Input
Devices
MEMORY
(Store)
Output
Devices
Arithmetic
Unit
Control Unit
READ X. Y. Z
U - (X + Y)/Z
PRINT X. Y. Z. U
GO TO START
1-5
OUTPUT
Step 1
Compiler
Program
(e.
Program
j., FORTRAN)
Memory
Compiler
Program
Object Program
in
Machine Language
Step 2
Memory
Program
Object
Program
1-7
FORTRAN
Noun
Verb
Phrase
Sentence
Paragraph
Chapter
Operand
Operator
Expression
Statement
Subprogram
Assembly of
subprograms
z/
s\ A
45.0
60.0
53.1
53.2
89.0
10.0
10.0
3.0
3.0
10.0
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
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
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:
Line 3:
READ (*.*)
A. X
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
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:
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
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
C
C
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
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:
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
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
1-17
Meaning
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
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
+ -/() = .,':
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
Contents
1-5
7-72
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.
(b)
(c)
(d)
(e)
(f)
T D
F D
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
Displayed Message
STOP - Program terminated.
I
'C'
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
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)
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.
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.
700
453.
453.000
21367250000.
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
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
(b)
(c)
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
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
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
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
(a) yfi
(d) y/El
(g) y/b
(b)ln2
(e) sin 37
(h) sin/?
(f) | log x\
(i) sin(v/hT20)
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
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
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
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
3.14159**2
3 - DELTA
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
A + B*C + (D/E**2)
A + BC
(BSQ - AC4)**-0.5
KATHY - 4.56E3 + E3
(e)
(f)
(g)
(h)
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
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
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
Intended Meaning
ln(2z + sina)
(b) A/D*B/E/(F/C)
abc/def
(tan/3-1)16
7.9 x 102y
abcde
(f) A**B**2
a26
3{jk)^2 - x3
{ab)c
2-14
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
Value
Type
J/I
J/I*BETA
BETA*J/I
2
5.
6.25
Integer
Real
Real
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)
(c) 4./J**3/P
(d) 4/J**3/IFIX(P)
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
V - 6
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
A = B
B = A
2. (Correct)
SAVEA - A
A = B
B = SAVEA
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
X
Y
Z
X
I
I
2.2
=
=
=
=
=
-
2.2
4.7
X + Y
-Z
ABS(X)
I + 1
2-19
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
(U. *) Z
(U. *. END- JV) Z
(U. *. ERR- .A/1. END=>/2)
Meaning
M or M2
Ml
READ (*.*)
READ (5.*)
I. J. K. ALPHA. X. Y. MEAN
I. J. K. ALPHA. X. Y. MEAN
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
T.
5*4.5
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.*)
700 PI -
3.1415900 PI.LT.1.2 F
3-4
C
C
10
A + B =
3 . 0000000
A + B
3.0000000
A + B -
12394 . 3200000
+ B -
999 . 8760000
3-6
Input values
READ (5.*) Y. J
C
10
STOP
END
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
(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
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
Interpretation f
nlm
nFm . d
nEm.d
nX
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
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
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
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
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
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
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
106
READ (5.106) X. Y
FORMAT (15X. F10.5//30X. F10.5)
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->
FORMAT (
T D
F D
(b)
All FORMAT declarations may be grouped together immediately after the END statement.
(c)
T D
(d)
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)
T D
F D
X. Y. Z
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)
110
READ (5.110) X. Y. Z
FORMAT (F10.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
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
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)
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
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.
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
X. Y. I. N. TEMP*Y
Value
X
Y
17.56786
7.568806 x 10- u
I
N
TEMP*Y
5
-10
-23.73821
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
220
WRITE (6.220) N. P7
FORMAT C At node number '. 13. 5X. ' Pressure = '. F7.3)
Col:
12
3
4
123456789012345678901234567890123456789012345
At node number
Pressure
3-19
2.793
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.
201
WRITE (6.201) X
FORMAT (' '. F9.1)
202
WRITE (6.202) X
FORMAT (1X. F9.1)
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
Character
code
Blank
Single space.
Double space.
No advance.
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
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
N. P7
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
Type declarations
INTEGER COUNT
REAL MEAN
Print heading. initialize data-set counter
WRITE (6.201)
NDATA - 0
C
1
C
999
C
101
201
202
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
(b)
TU
F D
(c)
3-25
201
WRITE (6.201) A. B
FORMAT (' ' , F10.5/ '0'. F10.5)
(d)
(e)
(f)
202
203
203
203
203
203
FORMAT
FORMAT
FORMAT
FORMAT
FORMAT
(f)
203
FORMAT (F3.1)
(c) m > d + 7,
(d) m > d + 8.
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
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
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 results, to
monitor, printer,
or disk files
Action
Pass 1
Pass 2
Pass 3
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
Purpose
Size (Bytes)
Fl.EXE
150,343
Fl.ERR
15,776
F2 . EXE
185,117
F3.EXE
126,667
F23.ERR
2,914
FL.EXE
25,011
Compiler manager.
FL.HLP
1,584
FL.ERR
1,817
F3S.EXE
82,629
LINK. EXE
50,531
LLIBFORE.LIB
194,048
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
Contents of File
progfile.FOR
progfile.LST
progfile.OBJ
progfi.le.kSH
progfile.COD
progfileMkP
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
library.LIB
progfile.EXE
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
4-S
4-7
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
Name
CON
CON
LPT1 or PRN
4-8
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
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
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
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-13
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.
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
Meaning
FORTRANVS
SCARDS
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
Examples of Compilation
1.
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.
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.
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
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
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*
(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
Contains File
Description
A:
WINDOW
B:
TRI2 . FOR
TRI2.DAT
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.
:
: : Sign on with user number and password : : : : :
: : : : : Observe messages about system status : : : : :
Which Host?UM
MTS Ann Arbor
#
(AE51-00523)
#$LIST -SOURCE
1
2
3
4
5
PROGRAM TRI2
C
C
C
C
C
C
C
16
17
18
19
20
21
22
23
24
25
26
C
C
201
C
C
1
202
C
C
C
C
STOP
END
45.0. 10.0
60.0. 10.0
53.1. 3.0
53.2. 3.0
89., 10.
89. 10
89 10
#$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
#$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
#$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
A>TYPE B:TRI2.OUT
5-9
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
RC-12
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-11
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
.FALSE.
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
Algebraic
Equivalent
LT.
GT.
EQ.
LE.
GE.
NE.
<
>
=
<
>
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
6-4
Precedence
Level
.NOT.
Use
.AND.
.OR.
.EQV.
.NEQV.
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
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
X .GT. Y
I
I
.FALSE.
Operand or Operation
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
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
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)
TD
FD
+ . . NOT . , . LT .
(c)
(d)
.GT. Y
.NOT. TOBE
.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
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
2 1/2
y = (4 ,x )
y = (l-x )
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
Operator
0
Evaluation of function references
and subscripts
Arithmetic
**
*. /
+ . - (binary and unary)
Relational
Logical
.NOT.
.AND.
.OR.
.Eqv.. .NEqv.
Assignment
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"
JVn).
6-12
VI
INT
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
THEN
THEN
6-14
THEN
THEN
6-15
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
Fig. 6.11
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
Fig. 6.12
Conditional structure
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
Fig. 6. IS
Variation of F with x.
j..1..l
T
1r
N^
6-19
M = Mxl
.NOT. LOG2
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
Fig. 6.17
Examples
1. If X is negative, display the values for A. B. and C:
IF (X .LT. 0.)
WRITE (6.204) A. B. C
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
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)
Ml. Ml. M3
5. 10. 15
10. 20. 30
(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
50. 50. 60
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
IF (J - K) 3. 2. 1
IF (J - 2*1) 5. 5. 10
IF (IABS(K)) 1. 2. 3
6-23
xl
V =
X2
'One root,'
x
-h + \ri
2a
-b - Vd
2a
' Imaginary
roots '
I
X1 ' X2
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
C
C
THEN
Xl. X2
ELSE
C
STOP
END
Data
1.
1.
4.46
0.0
1.
-5.
2.957
2.957
-6.
6.25
0.901
0.901
2.00000
6-26
-3.00000
=
=
=
-
1.000
-5.000
6.250
.000
Xl
X2
=
=
2.50000
2 . 50000
4.460
2.957
.901
-7.330
=
=
=
.000
2.957
.901
8.744
- . 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
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
TABLE(3.9)
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)
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
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).
(b) V(0, 2, J)
y = y< + (x - Xi)
y<+i - y,
Xi+l - 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
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
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
VI - II. 12. 13
CONTINUE
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
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)
T D
(c)
T D
F D
(d)
T D
F D
7-8
T D
F D
T D
F D
T D
F D
DO 30 K = 20. 15
(f)
(g)
M = 10. 2. -1
M = 10. 2. -2
is legal, whereas
is illegal).
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
(a) DO 67.5 I = 1. 2. 3
(b) DO N INT = 3. 2. 1
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
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)
C
C
C
Print heading
7-10
C
DO 10
X - XLOW + (I - 1)*DX
WRITE (6.203) X. X**2, SQRT(X) , SIN(X)
CONTINUE
STOP
10
C
201
202
203
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
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
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
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.
Declarations
REAL LOW
DIMENSION X(100)
OPEN (5, FILE=' ARRAY. DAT')
C
1
C
C
10
C
999
101
201
7-14
-'. F10.2/
'. FlO. 2)
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
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
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
C
DO 50
C
C
25
50
C
999
101
7-16
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
1.0
4.0
6.0
2.0
2.0
4.0
6.0
7.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
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
1- ani"-1 + an+lxn.
+ 02)1 + 0.!.
7-19
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
Meaning
status
8-2
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)
Col:
12
3
4
1234567890123456789012345678901234567890
27344 1.459E-8
10.
20.5
BETA - 1.459x10-"
MAX = 10.
TEMP =20.5
201
WRITE (6.201)
FORMAT (' ' . T10. 'INVENTORY' . T50. '1986'. TL23.
1 'STORE 10')
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:
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
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)
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
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
103
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
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
( ) / (
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
105
*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
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)
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
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
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
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
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
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)
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
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
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
204
K. (X(I). I = 1. K)
T
Output
Col:
12
3
12345678901234567890123456789012345678901
The
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)
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
((A(I.J). J - 1 . N) . I - 1. M)
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).
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
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
(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
8-17
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
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)
2
7
12
17
3
8
13
18
4
9
14
19
5
10
15
20,
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)
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
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
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
END
First line.
Second line.
Third line.
Fourth line .
Fifth line.
First line.
Second line.
Third line.
Fourth line.
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
ITEM =
1
0
0
0
0
2
0
0
0
0
3
0
0
0
0
4
\
0
0
0/
A(1.4) -
A(3.2) -
B(2) =
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.
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
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
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
DCOSH
DEXP
DSIN
DSINH
DASIN
DATAN
DATAN2
DCOS
DSQRT
DTAN
DTANH
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)
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
GO2 + GO (2)
S*MONTH + AL
PENNY*GO(1)
GO(1)/INT
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
(b)
9-9
The listed variables may be of any type; types of individual entries need not agree.
Examples
1.
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.
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
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)
3. After execution of the following what are the values of X(6) . X(9) .
Y(2). and Y(10)?
10
20
4. After execution of the following, what are the values of VEL. X(l) . and
Y(5)?
10
Statement Functions
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
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
z^= sin(x)
Enter
Sequence of
calculations for
evaluating sin(y)
Return
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.
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.
An)
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
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
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
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
C
C
C
101
C
C
C
10
C
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
99. 4
77.0
43.1
61.3
46.8
29.9
3.7
49.6
44.6
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
293.0
771.5
423.9
13.7
431.6
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.
The average of the first INT elements of an array Z is computed and used in
the evaluation of a rather complicated expression.
4.
100
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
5
10
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
PMAX
MONTH
STORE
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
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(
)
...)
...)
.)
...)
...)
CHARACTER*25 FUNCTION F(
Four
Eight
Eight
Four
Two
Four
Two
One
Twenty-five
.)
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
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
T D
(b)
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.
4.
DIVIDE (X.
6.
B - 3.
C - DIVIDE (B.
Function
DIVIDE
Y)
B)
RETURN
END
A)
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
Fi = l;
t = 2,3, ...
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
CONTINUE
RETURN
END
Data
12
3
Col: 123456789012345678901234567890
2
2.000
3.000
-1.000
2.000
(a)
(b)
(c)
(d)
[=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
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
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)
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)
An*)
10-20
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
10
20
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
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
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
C
10
20
..RETURN FOR SYMB A DIGIT.
30
10-24
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)
T D
F D
T D
F D
Subroutine
TEST
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
10-25
i3
x*
Jl2n2)
X3n3)
>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
X + Y
10
20
30
THEN
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.
7n
7n
10-28
Declarations
EXTERNAL F
INTRINSIC COS
LOGICAL MYFUN
OPEN (5. FILE-' CON')
OPEN (7. FILE- 'CON')
C
C
C
C
FUNCTION F(Y)
F = ALOG(Y)
RETURN
END
LOGICAL FUNCTION MYFUN(F1, F2, Z)
C
C
C
C
10-29
- 5.37)2 +
cos(S + E2
- 4.87)/sin(S + E2 - 4.87).
The same dummy arguments may be used in any number of function definitions.
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 -
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.
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
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
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
Function JIMMY
COMMON A. B, C
A - 1.
B - 2.
C = 3.
Z - JIMMY(4.)
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 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
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
END
"FUNCTION or SUBROUTINE
Last FORTRAN Function or Subroutine Subprogram
END
10-37
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'
' '"
LETTER. MESSAG*21
MESSAG(1O)
11-1
A
A
A
A
Examples
'Break In Case Of Fire'
MESSAG(5)
('ABC')
T D
F D
(b)
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
Variable
<
Field
Field
Blanks
added
Not
printed
Blanks
added
Discarded Variable
<
Input
Output
Declarations
CHARACTER FIRST*4. LAST*10, GROUP+8, SS(3)*4, TITLE*4
INTEGER AGE
OPEN (5. FILE- 'CHIOFO. DAT')
11-3
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)
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.
Declarations
CHARACTER BEAST*8. SEX. HAIR*5. EYES*5. KIND* 10
OPEN (5. FILE-' CHIOLD. DAT')
C
C
C
999
11-5
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)
(b)
(c)
201
CHARACTER*4 NAME
NAME - 'BRENDA"
WRITE (6.201) NAME
FORMAT (' ' . A4)
200
999
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
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
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
.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:
and
Declarations
CHARACTER*20 NSAVE. NAME
DIMENSION NAME(100)
OPEN (5. FILE= 'ALSORT.DAT')
11-9
10
C
DO 30
C
101
202
''/(''. A20))
END
11-10
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
(b)
(c)
(d)
N = N + 1
Alphabetized Order
MARYU
MARKU
UMARY
MARY .
LUKEU
MARY.
11-12
where the individual parts have the meanings given in Table 11.2.
Table 11.2 Codes for Internal Output Statement
Code
Meaning
VC
}/
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
OUTPUT* 13
N
M
J
201
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)
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
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
C
C
30
360 degrees
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
Contents
Field
PARTl
NCOL
(lX. F6.1.
Number of columns
to be skipped
X. '*')
A10
PART3
13
A7
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
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
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
11-18
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
999
C
100
101
102
200
END
A
2
2
x
A
2
SOC.SEC.NO.
AGE
SEX
123456789
987654321
333224444
212121212
121212121
88
69
76
78
64
M
M
M
F
F
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.
11-20
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.
NCHAR (W)
LOCATE (W)
NCHAR (W)
1
2
3
4
1
12
20
22
11
8
2
11
etc.
11-21
C
C
C
C
C
C
C
C
C
C
C
C
LOCATE (W)
NBEGIN
NCHAR(W)
NEND
NWORDS
PARA
Declarations
CHARACTER* 1 PARA
DIMENSION LOCATE(25O). NCHAR(250) . PARA(1O00)
OPEN (5. FILE-' WRDPRC. DAT')
C
1
C
CHAR
W
Declarations
INTEGER C. W
CHARACTER* 1 CHAR. PARA
LOGICAL HEAD
DIMENSION CHAR (60) . LOCATE (250) . NCHAR(250) . PARA (1000)
HEAD - .TRUE.
C
1
C
C
C
C
10
PARA(C) = CHAR(J)
J - J + 1
STOP
101
201
202
END
C
CHAR
CHAR
J
W
Declarations
INTEGER C. CHARS. W
CHARACTER* 1 CHAR. PARA
DIMENSION CHARC72). LOCATE (250) . NCHAR(250) . PARA(1O00)
11-24
10
C
C
15
20
(CHAR(I) . 1=1.
J - 1)
CONTINUE
RETURN
C
201
202
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
5 to
60
11-27
11-28
APPENDIX A
SOLUTIONS TO EXERCISES
Column 7
WRITE and FORMAT
2.
5.
END
Yes
3.
6.
*../=:()
Carriage -control
(d) T
(e) F
Integer
Integer
(b)
(e)
Real
Real
(c)
(f)
Real
Real
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
(c) F
(d) T
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)
Solutions to Exercises
(f)
(g)
(h)
(m)
2.
INTEGER
3.
REAL
(n)
(o)
COUNT. POINTS
LENGTH, MASS
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)
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)
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.
3. (a)
(b)
5.5, real.
5.5, real.
(c)
(d)
0.5, real.
Zero, integer.
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
=
-
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
(J + l)/2*2 + 1
8.
K SqRT(FLOATU))
or
K - SQRT(1.*I)
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
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
102
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
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 (/)
Column:
12
3
12345678901234567890123456789012345
1234
5.0
-0.329E-8
(a) F
2.
3.
4.
205
1
5.
(b) T
(c) F
(d) F
(e) F
(f) T
206
= ',
- '. E12.3)
207
(a)
(c)
(e)
(f)
A-6
Solutions to Exercises
2.
3.
(a)
|p?|35
<
n In 6.78 -
cos<
(b)
Exl.3xl0_4xeB - EBx4/[exp(2E)]B
No.
(j)
(b) F
(c) F
(d) F
(won't compile)
(e) T
A-7
Solutions to Exercises
F
I
I
F
I
F
I
F
I
5.
6.
.TRUE.
7.
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.
A-8
Solutions to Exercises
11.
12.
13.
14.
LOGICAL Y
J - 3 (integer)
MASS 5 (integer)
X - 25. (real)
Y - .TRUE. (logical)
Yes
I
0
1
2
3
4
5
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.
4.
5.
1
6.
7.
10
THEN
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
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
(a) F
(b) F
(c) T
(d) F
(e) F
Solutions to Exercises
ELSE IF (X .EQ. 0.)
IZER - IZER + 1
ELSE
IPOS - IPOS + 1
END IF
THEN
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
2.
(a) Acceptable.
(b) Unacceptable in subset FORTRANthe smallest
subscript allowed is 1.
3.
4.
5.
Only (c).
(a) T
(b) T
(c) F
(d) F
A-12
(e) F
(f) F
(g) T
Solutions to Exercises
2.
(a)
(b)
(c)
3.
(a)
(b)
(c)
(d)
4.
(a) 6
(b) 5
(c) 10
(d) 2
5.
6.
(a)
(b)
(c)
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
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.
11.
CONTINUE
END IF
DIMENSION A(10.10)
C
C
C
C
C
10
20
30
40
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
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
A-16
Solutions to Exercises
(b)
105
110
(c)
(d)
115
116
100
2. (a)
(b)
3.
(a)
(b)
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
5.
Answer is (b) .
6.
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.
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.
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
(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.
5.
6.
(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.
2.
(b)
3.
4.
or
(a) F
(b) F
(c) F
(d) F
2.
3.
4.
A - 2., B - 7.. C - 2. . D - 4. . E 6. . F - 3.
5.
10
Solutions to Exerciaea
6.
10
7.
8.
10
A-21
THEN
Solutions to Exerciaea
9.
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
(a) F
2.
A - 10. , B - 10. , C - 4.
3.
4.
10
(b) T
(c) F
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.
2.
3.
(b) F
201
(b) T
(c) T
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
202
999
(a) F
2.
3.
1.
2.
3.
4.
(b) T
(c) F
UMARY (U - blank)
LUKEU
MARKU
(d) T
4. MARYU
5. MARY,
6. MARY.
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
END
A-25
13)
Solutions to Exercises
Notes
A-26
APPENDIX B
SUMMARY OF STATEMENT TYPES
Purpose
Executable Statements
BACKSPACE U
An*)
CLOSE (U)
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
Logical conditional
IF () Ml. M2. MS
Arithmetic conditional
B-l
Suspend execution
READ (U. *) t
List-directed input
List-directed input
List-directed input
Formatted input
Formatted input
READ (tt.
Formatted input
ERR=J/2, END=A/3) t
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
DATA / Cl. C2
Shared variables
Vn
Shared labeled
variables
Cn/
Variable initialization
In)
Array storage
DOUBLE PRECISION t
EQUIVALENCE (Vl. V2
EXTERNAL 7l . 72
Vn)
Alternative naming
7n
Subprogram names as
subprogram arguments
B-2
I/O format
Implicit type
INTEGER*b C
INTRINSIC 71. 72
7n
LOGICAL*b C
REAL C
PROGRAM 7
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
Subroutine Subprogram
SUBROUTINE 7 (Al. AT.
ENTRY 7 (Al. A2
An)
Heading
An)
Additional entry
RETURN or RETURN I
Statement Function
7 (Al. A2
An - or B)
Define function
Heading
B-3
B-4
INDEX
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
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
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