Вы находитесь на странице: 1из 14

Functions and Subroutines

Functions and subroutines are FORTRAN's subprograms. Most problems that require a computer
program to solve them are too complex to sit down and work all the way through them in one go.
Using subprograms allows you to tackle bite size pieces of a problem individually. Once each piece is
working correctly you then put the pieces together to create the whole solution. To implement
functions and subroutines, first write a main program that references all of the subprograms in the
desired order and then start writing the subprograms. This is similar to composing an outline for an
essay before writing the essay and will help keep you on track.
Functions
The purpose of a function is to take in a number of values or arguments, do some calculations with
those arguments and then return a single result. There are some functions which are written into
FORTRAN and can be used without any special effort by you, the programmer. They are called
intrinsic functions. There are over 40 intrinsic functions in FORTRAN and they are mainly concerned
with mathematical functions.
The general way to activate a function is to use the function name in an expression. The function
name is followed by a list of inputs, also called arguments, enclosed in parenthesis:
answer = functionname (argumentl, argument2, . . .
External Functions
The intrinsic functions in FORTRAN are useful but there will be a time when there is no intrinsic
function to meet your needs. When this occurs you may write your own function subprogram.
You have to do one thing in the main program to use an external function. You need to declare the
function name in the variable declaration section. Function names follow the same rules as for
variable names: less than six letters or numbers and beginning with a letter. Because of this, function
names should not be used as variable names. Once that is done and the function is written, activating
it is just like activating an intrinsic function.
Now you are ready to write your function. There are a few rules for writing external functions:
Function subprograms and any other subprograms are placed after the END statement of the
main program.
They are started with a line that includes the type of value the function will return, the function
name, and the list of arguments the function takes as inputs.
Any variables the function uses, including the arguments, must be declared in the function
right after the first line. The function name is not declared within the function.
You must use the function name in an assignment statement within the function. This is how
the compiler knows which value to pass back to the main program.
A function must finish with RETURN and END statements.
A return statement in a function subprogram acts like a stop statement in the main program;
the subprogram is terminated and Fortran returns to where it left off in the main program.

Subroutines
You will want to use a function if you need to do a complicated calculation that has only one
result which you may or may not want to subsequently use in an expression. Recall the external
function example program where the average was called and then squared in one line.
Subroutines, on the other hand, can return several results. However, calls to subroutines cannot be
placed in an expression.
In the main program, a subroutine is activated by using a CALL statement which include the
subroutine name followed by the list of inputs to and outputs from the subroutine surrounded by
parenthesis. The inputs and outputs are collectively called the arguments.
A subroutine name follows the same rules as for function names and variable names: less than six
letters and numbers and beginning with a letter. Because of this, subroutine names should be
different than those used for variables or functions.
As with functions, there are some rules for using subroutines. Keep these in mind when writing
your subroutines:
You do not need to declare the subroutine name in the main program as you do with a
function name.
They begin with a line that includes the word SUBROUTINE, the name of the subroutine,
and the arguments for the subroutine.
A return statement in a subroutine instructs Fortran to terminate the subroutine and return
to the main program at the point where it departed. Thus it works like a stop statement in
the main program, halting the program prematurely before the final end statement. A
subroutine may have several returns, but only one end statement
One way of indicating which variables are inputs and which are outputs is to put the inputs on the
first line, use a continuation marker and put the outputs on the second line. See the example
program for an application of this programming style.
All variables used by the subroutine, including the arguments, must be declared in the subroutine.
The subroutine name is not declared anywhere in the program. A subroutine is finished off with a
RETURN and an END statement.
INPUT/OUTPUT
FORTRAN provides two types of input/output statements. In the first type, the programmer must
explicitly specify the format in which the data is presented for input or, in the case of output, the
precise format in which it is to be displayed. In the second type of input/output, certain predetermined
standard formats that match the types of items in the input/output list are automatically provided by
the compiler. It is this second type, known as list-directed input/output, that we consider in this
section. List-Directed Output

The simplest list-directed output statement has the following form:


List-Directed Output Statement
Form:
PRINT *, output-list
where:
output-list is a single expression or a list of expressions separated by commas. Each of these
expressions is a constant, a variable, or a formula.
The statement may also be used in the form
PRINT *
where no output list is used.
Purpose:
Displays the values of the items in the output list. Each PRINT statement produces a new line of
output. If the output list is omitted, a blank line is displayed.
In some situations, one or more blank lines in the output improve readability. A blank line can be
displayed by a PRINT statement of the form
PRINT *
in which the output list is empty. Note that the comma that normally follows the * is also omitted.
Execution of each statement of this form causes a single blank line to be displayed.
List-Directed Input
The simplest form of the list-directed input statement is
List-Directed Input Statement
READ *, input-list
where
input-list is a single variable or variables separated by commas.
Purpose:
Causes the transfer of values from some external source (usually the keyboard or a file) and the
assignment of these values to the variables in the input list. The following rules apply:
i.

A new line of data is processed each time a READ statement is executed.

ii.

If there are fewer entries in a line of input data than there are variables in the input list,

successive lines of input are processed until values for all variables in the list have been
obtained.
iii.

If there are more entries in a line of input data than there are variables in the input list, the
first data values are used, and all remaining value's are ignored.

iv.

The entries in each line of input data must be constants and of the same type as the variables
to which they are assigned. (However, an integer value may be assigned to a real or a double
precision variable, and a real value may be as signed to a double precision variable, with
automatic conversion taking place.)

v.

Consecutive entries in a line of input data must be separated by a comma or by one or more
spaces

In an interactive mode of operation, the values assigned to variables in an input list are entered during
program execution. In this case, when a READ statement is encountered, program execution is
suspended while the user enters values for all the variables in the input list.
Program execution then automatically resumes. Because execution is interrupted by a READ
statement and because the correct number and types of values must be entered before execution can
resume, it is good practice to provide some message to prompt the user when it is necessary to enter
data values. This is accomplished by preceding each READ statement with a PRINT statement that
displays the appropriate prompts.
Write and Format Statements
Just as in Basic we use TAB and PRINT USING commands to more precisely control program
output, in Fortran we can use write commands with format statements. While these can get
complicated, the most commonly used options are pretty easy to use. A typical write statement is
write (*,20) x, y, z

The "*" in the parentheses instructs Fortran to write to the screen, while "20" refers to the label of
the format statement for this write command. The x, y, and z are the variables to be printed.
A formatstatement for this write command might be
20

format (3f10.4) .

Inside the parentheses, the "3" indicates that 3 entities will be printed, the "f" denotes that these will
be floating point real numbers (not exponential notation), the "10" stipulates that 10 places will be
used for printing (counting the sign, decimal point, and the digits), and ".4" mandates 4 digits after the
decimal point. Some printouts formatted this way are
12345.6789

-1234.5678

, 10002.3400 .

The letter "f" in this context is a format code letter; here are some of the more commonly used format
code letters, with their implications:

real number, floating point format

single precision real number, exponential notation

double precision real number, exponential notation

integer

text string (character)

space

vertical space (line feed)

tab indicator

Strings (in quotes) may be placed in format statements, separated by commas. Here are examples of
write statements with corresponding format statements; at the right of each is a description of the
corresponding output:

write
(*,10)
n,
10 format (i4,4x,f10.4,2x,f10.4)

x,

write
(*,20)
20 format ("The area is ",f8.5)

write (*,30) "The


30 format (a,f8.5)

write
(*,40)
40 format (3d20.14)

write
(*,50)
50 format (a20,4x,i3)

area

integer
n
printed
using
4
places,
then 4 spaces,
then real numbers
y
x and y printed with 2 spaces
between,
each
using
10
places
and 4 decimal places

area

is

x,

student,

",

y,

area

string in quotes is printed, then the


real number area is printed, using
8 places with 5 decimal places

same output as immediately above

3 double precision numbers x, y, z


printed,
each
reserving
20
spaces,
with 14 decimal places

student,
a
text
string
up
to
20
score characters,
is
printed,
then
4
spaces,
then
score,
an
integer
using a maximum of 3 places

write
(*,60)
60 format (t10,f4.2,/,t10,f6.2)

r,

tabs
to
column
10,
prints
real
number r, goes to next line, tabs to
column 10, prints real number A

You can use loops with format statements to print arrays; here are examples:
do
i
write
end
70 format (f5.2)

write (*,80)
80 format (f5.2)

=
(*,70)

an
array
a
of
real
numbers,
10
indexed
from
1
to
10,
is
printed;
a(i)
each
entry
occupies
5
places
with
do
2
decimal
places,
and
is
printed
on a separate line

1,

(a(i),

1,

10)

write (*,90) (a(i),


90 format (10f5.2)

1,

10) same output as above, except


entries are printed on the same line

do
7

i
write (*,7)
format
end do

=
(m(i,j),

1,
=

1,

same output as immediately above

that

all

5 prints a 5 x 6 two-dimensional array


6) m of integers, with each integer entry
(6i3) m(i,j) occupying 3 places. Each row
of the matrix appears on its own line.

Here are other useful things to know about formatting:


1. If you do not specify a format, GNU Fortran will print real numbers using about 9 digits, even
if you do calculations in double precision. If you want to print in double precision you must
use write and format statements. When double precision is used the maximum number of digits
possible is 17. A format specifier something like format (fm.n), where m is at least 20, is
required to take full advantage of double precision.
2. If a value is too large to be printed in the specified format, Fortran will just print a string of
asterisks (eg: ********** ). If you get such an output, you have to fix your format statement.
3. Real numbers are rounded off (not truncated) to fit the specified formatting.
4. If your formatting specifies more positions than the number requires, blanks are inserted to the
left of the number.
5. Format statements may appear anywhere in a program after the variable declarations and
before the end statement.
6. Unless your format statement is very simple, the chances are that your output won't look like
you want on the first try - just fiddle with the formatting until you get it right.

Common (Blank)

Ordinarily the only information shared between the main program and subprograms are the values of
variables appearing in variable lists. The common statement can be used to share additional
information.
The simplest form of the common statement is the blank common statement. Let us suppose for
illustration that the main program has real variables x and y as well as an integer variable n which are
to be shared with one or more subroutines. Then at the beginning of the main program, before any
executable statements, you first declare the types of x, y, and n and next insert the "blank common"
statement
common x, y, n

This instructs Fortran to preserve three "common" memory locations for x, y, and n, designated as
triangles below:
x
y
n
These memory locations are then accessible by all subroutines of the program containing a similar
common statement (but with possibly different variables). For example, suppose a subroutine declares
real variables u and v and an integer variable m. If the subroutine contains also the common statement
common u, v, m

then u, v, and m will share memory locations with x, y, and n, respectively :


x u
y v
n m
When the values of u, v, and m change in the subroutine, then the values of x, y, and n in the main
program change accordingly; and vice-versa - changes in x, y, or n in the main program produce
changes in u, v, and m in the subroutine. Obviously, because of the sharing of memory locations, the
types of x, y, and n must match those of u, v, and m, respectively (and also dimensions must match in
the case of arrays.)
It is possible for a third or even more subroutines to share the same three memory locations. If a third
subroutine has real variables a and b and an integer variable k, as well as the statement
common a, b, k

then x, u, a share one memory location, y, v, b another, and n, m, k a third. A change in one of these
variables in the main program or a subroutine produces the same change in whatever variables share
the same memory location.

A common statement cannot list variables that are listed also in the title statement of the subprogram
in which the common statement appears. (EG: If a subroutine's first line is "subroutine area(r)", then
you cannot list r in the subroutine's common statement.)
Common (Named)
In programs with more than one subroutine it is sometimes desirable to share different sets of
variables among different sets of program units. In such situations the named common statement is
useful. The general form of this statement is
common / name1 / list1 / name2 / list2 / name3 / list3 / / nameN / listN

The "names" are names for the different sets of variables, and the "lists" contain the names of
variables in these sets.
Suppose, for example, that the main program uses variables A, B, C, D, E, F, G, while subroutine
"demo1" uses variables A, B, C, D, and subroutine "demo2" uses variables C, D, E, F, G. If we want
all program units using the same variable to share the value of that variable, then in the main program
we insert the named common statement
common / first / A, B / second / C, D / third / E, F G

in subroutine "demo 1" we insert


common / first / A, B / second / C, D

and in "demo 2" we insert


common / second / C, D / third / E, F, G

Then the variable set "first" consists of A and B, and is shared by the main program and demo1.
Variable set "second" consists of C and D and is shared by all three units. Variable set "third" consists
of E, F, and G and is shared by the main program and "demo2". It is not necessary that different units
use the same variable names for shared data. For example, subroutine "demo2" could name its five
variables V, W, X, Y, Z; then its common statement would change to
common / second / V, W / third / X, Y, Z

and consequently V and C would share a memory location, as would W and D, X and E, Y and F, and
Z and G.
Do While Loops
A do while loop in Fortran is similar to the same loop in Basic. However, in Fortran the test must be
enclosed in parentheses, and the end of the loop is identified with either end do or a
labeled continuestatement. As in "if then" constructions, in loop tests one uses letter abbreviations
for relations such as "", ">", "=", etc. Here are two loops adding the squares of the integers from 1 to
10; they differ only in the way the loops are terminated:
N=1

N=1

S=0

S=0

do while (N .le. 10)

do 5 while (N .le. 10)

S = S + N ** 2

S = S + N ** 2

N=N+1

N=N+1

end do

continue

Do Loops
"For Next" loops in Basic become "Do Loops" in Fortran. Such a loop begins with a do statement,
and ends with either end do, or a labeled continue statement. Here are two loops that add the squares
of the integers from 1 to 10:
sum = 0

sum = 0

do i = 1, 10

do 5 i = 1, 10

sum = sum + i ** 2

end do

print *, "The sum is", sum

sum = sum + i ** 2
5

continue
print *, "The sum is", sum

The end do and continue statements serve only to identify the end of the loop. The limits of the loop
may be variables as well as numbers (e.g.: do i = m, n). As in Basic you may indicate a step size,
which can be positive or negative. For example, the statement
do i = 1, 9, 2
specifies that the loop variable i run over the odd numbers 1, 3, 5, 7, 9.
Loops can be nested, and nested loops can end on the same continue statement (but not on the
same end do statement). Here are two instances of nested loops assigning the entries of a 10 x 10
matrix:
do i = 1, 10

do 5 i = 1, 10

do j = 1, 10

do 5 j = 1, 10

a(i,j) = i + j

a(i,j) = i + j

end do

end do

continue

Variables, Declarations, Types


After the program name come the declaration statements, stating the types of the variables used in the
program. A variable name consists of characters chosen from the letters a-z and the digits 0-9; the
first character of the name must be a letter. You are not allowed to use your program name as a
variable, nor are you allowed to use words reserved for the Fortran language, such as "program",
"real", "end", etc.
The variable types in Fortran are
1) integer (in the range from about - 2 billion to + 2 billion)
2) real (single precision real variable)
3) double precision (double precision real variable)
4) character (string variable)
5) complex (complex variable)
6) logical (logical variable)
As illustration, the declaration statements
real r, area
integer M, N
double precision a, b
declare that r and area are single precision real variables, that M and N are integers, and that a and b
are double precision real variables.
If you do not declare the type of a variable, Fortran will by default make it an integer if it starts with
one of the letters i through n, and will make it a single precision real variable otherwise. However, it
is normal (and good) programming practice to declare the type of every variable, as otherwise
mistakes are easily made.
The implicit quantifier before a type declaration makes all variables starting with the listed letters of
the specified type. For example, the declarations
implicit integer (i-m)
implicit real (r-t)
make variables starting with i, j, k, l, m integers, and those starting with r, s, t real. However, the
implicit quantifier is probably best avoided, as programmers with short memories will make mistakes.
A declaration statement is nonexecutable - that is, it provides information but does not instruct
Fortran to carry out any action. Declarations must appear before any executable statement (a
statement thatdoes tell Fortran to take some action).

Assignment
The equals sign "=" assigns the variable on the left side the value of the number or expression on the
right side (exactly as in Basic).
Parameter
The parameter statement works like CONST in Basic - it specifies a value for a constant. The syntax
is
parameter (name = constant expression)
where name is replaced by the name of the constant, and constant expression by an expression
involving only constants. Thus
parameter (pi = 3.14159)
specifies a value for the constant pi, while the succeeding statement
parameter (a = 2* pi, b = pi/2)
fixes values of new constants a and b in terms of the old constant pi. Remember that once a constant
is defined you are not allowed to change its value later.
All parameter statements must appear before the first executable statement.
Comments
A comment is similar to an REM statement in Basic. You can indicate a comment by placing a "c" in
column 1 and then the comment in columns 7-72. Alternatively, you can use an exclamation point "!"
to indicate a comment; it may occur anywhere in the line (except columns 2-6). Everything on a line
after an exclamation point becomes a comment.
FILE PROCESSING
Sometimes it is convenient in a Fortran program to use files for accessing or storing data - especially
when large amounts of data are involved. Too much keyboard input during the run of a program leads
to mistakes and tedium, while too much screen output has similar consequences. Putting data into
files - both for input and output - is a more leisurely and less error-prone approach.
Open
The open command is used to open files - that is, it makes files available so that Fortran can read or
write to them. The simplest form of the command is
open (unit = number, file = "name") .
In place of number you insert a positive integer (but not 6) to be used to refer to the file, and instead
of name you insert the name of the file. Here are examples of open commands:
open (unit = 2, file = "scores")

open (unit = 7, file = "a:scores.txt")


open (unit = 5, file = "h:\\results\\primes")
open (unit = 24, file = "c:\\fortran\\data\\divisors.dat") .
Fortran uses the unit number to access the file with later read and write statements. Several files can
be open at once, but each must have a different number. There is one thing to remember about
numbering a file - you cannot use the number 6, as GNU Fortran reserves that number to refer to the
screen.
Note that quotes enclose the filename. Also, in specifying a directory path for a file, you must use
double backslashes instead of single ones. Do not put a space on either side of the colon after the
drive letter. If you do not specify a drive or directory path for a file, or if you specify the same drive
upon which GNU Fortran is installed but without a path, GNU Fortran will by default assume the file
is located on the same drive and in the same directory from where Fortran is running.
If the named file does not already exist, Fortran will create it; if it does exist, Fortran will replace it.
(So don't mistakenly give the file the same name as another important file!)
Close
The close command is used to close one or more files - examples are
close (5)

close (1, 3, 8) .

The first of these commands closes the file numbered 5, while the second closes the three files
numbered 1, 3, and 8. It is not necessary to close files; all files will automatically be closed when
an end or stopstatement is executed. However, in programs handling large amounts of data it can be
prudent to close files before the end of the program in order to avoid possible memory problems and
to increase efficiency.
Write (to Files)
The write command is used to write data to a file. For example, the command
write (7,*)
works like a print * command, except that data is written to the file numbered 7 instead of to the
screen. The two statements
print *, "The solutions to the equation are : ", x1, x2
write (7,*) "The solutions to the equation are : ", x1, x2
produce exactly the same output, except that the first writes to the screen and the second to file
number 7. The command "write (7,*)" on a line by itself serves as a line feed, skipping a line in the
file numbered 7 before the next writing to that file.
You can also use write statements in conjunction with format statements to write to a file; this gives
you better control of formatting. In the following, the first number in "write (7,5)" refers to the file
number and the second to the label of the format statement:

write (7,5) "The solutions are ", x1, " and ", x2
5

format (a,f16.10,a,f16.10)

The "write (7,5)" command works exactly like the similar command "write (*,5)", except that in the
former output is directed to file number 7, and in the latter to the screen.
Each execution of a write command writes to a single line in a file. The next write command will
write to a new line.
Read (from Files)
The read statement is used to read data from a file. Generally data is read from a file in the standard
way, line-by-line and from left to right. But you must remember that each read statement begins
reading a new line, whether or not the preceding read statement used all the data in the preceding line.
Suppose for example that a file is numbered 7, and that the first two lines of the file contain the data
(separated by commas)
1.23 , 4.56 , 7.89
11, 13 , "Sally"
If the first two read statements in the program are
read (7,*) x, y, z
read (7,*) m, n, first ,
then the program assigns x = 1.23, y = 4.56, z = 7.89, m = 11, n = 13, first = "Sally". The variables
will have to be declared in the program to correspond with the data assigned them by the read
statements. For instance, in the above situation x, y, and z will have been declared real variables, m
and n integers, and "first" a character variable. Failure to match variable types with data types will
most likely lead to error messages.
It is possible that a program does not know beforehand the length of a file. If data is being read from a
loop, there is a way to exit the loop when all data in the file has been read, thereby avoiding a
program hang-up. One simply modifies the read statement to something like
read (7,*,end=10) .
This command instructs Fortran to read the next line in the file numbered 7, but to jump to the
statement labelled 10 in the program in the event that the last line in that file has already been read.
You can also use format specifiers in read statements, but this can be somewhat tedious and we will
not go into the details. As but one example, suppose you want to make the assignments
n = 77

x = 123.45

y = 67.8 ,

where n is an integer and x and y are real variables. Then you may use the read and format statements
read (7,5) n, x, y

format (i2,f5.2,f3.1)

and in file number 7 place the corresponding line of data


7712345678

Fortran will read and separate the data, insert appropriate decimal points, and assign it to the
variables. But as you can see the method is confusing and perhaps not worth the effort.
How Read(*,*) differs from Read *, ?
The first asterisk (*) means the input comes from the keyboard in a READ statement and goes to the
screen in a WRITE statement. The second asterisk (*) means the computer decides how the I/O
elements should look based on the TYPE of data in the input/output list. This is sometimes called
"FREE-FORMAT".

Вам также может понравиться