You are on page 1of 13

MTMA33 FORTRAN BASICS 2007

FORTRAN 90 Basics

This document provides only a very basic introduction to FORTRAN 90 to allow you to begin
writing FORTRAN 90 programs. FORTRAN 90 is actually a very powerful language with many
features not described here. For a readable full description of the language see, for example,
FORTRAN 90/95 explained, by Metcalf and Reid (Oxford University Press).

1. FORTRAN 90 program structure

A FORTRAN program consists of a sequence of lines of text called statements, which are
instructions to the computer. The outline structure of a program is as follows:
PROGRAM name
Type declaration statements
Executable statements
END PROGRAM name
Here items in italics are not to be taken literally; they indicate the sort of thing that should appear
in that position. Executable statements are statements that do things, for example calculate an
expression, read or write to a file, etc. Type declaration statements tell the compiler about the
types of data the program will use, etc.

1.1. Line structure, and continuation lines


Each line may be up to 132 characters long. Statements may begin at the left hand margin, though
it is often useful to indent some statements to make the program more readable. If a statement
needs to be more than 132 characters long, or simply to improve the readability of the code, a
statement may be continued by up to 39 additional continuation lines. If a line is to be continued
then its last non-blank character, or last non-blank before a "!", must be "&".E.g.
root = &
(-b + root_of_discriminant) &
/ (2.0*a)
Blanks have no significance, except within character strings, so blanks can be inserted where
desired to make the code more readable. Also, FORTRAN is not case sensitive, except within
character strings.

1.2. Comments
Anything to the right of a "!" is regarded as a comment and is ignored by the compiler (except
when the "!" appears within a character string). E.g.
! This is a comment line
x = x + 1 ! and this statement includes a comment
You are strongly encouraged to use comments. A few seconds typing in comments can save hours
or days of head scratching when you or someone else tries to understand the code later.

1
MTMA33 FORTRAN BASICS 2007

2. Quantities that FORTRAN can manipulate

2.1. Types
FORTRAN can manipulate several different types of data

TABLE 1. Types of FORTRAN data


Type Example Description
INTEGER -3 Whole numbers
REAL 3.14159 Numbers that can have a decimal part. Includes
very small or large numbers where "times 10 to
the power" in scientific notation is represented by
"e"

COMPLEX (0.0,1.0) Pairs of real numbers giving the real and


imaginary parts of a complex number

LOGICAL .TRUE. .TRUE. or .FALSE. Used for Boolean algebra and to


control program flow.

CHARACTER 'Hello' Strings of characters, delimited by either


apostrophes or quotation marks.
"End of run"

Each type of data can come in several kinds, for example with higher precision. The most useful of
these is DOUBLE PRECISION, which is like a REAL but with more significant figures stored and a
wider range of exponents allowed. FORTRAN_90 also allows the programmer to define their own
types of data, for example a type consisting of an integer and a character string that could contain
a code number and a name.

2.2. Literal constants


Constants can have any of the types discussed in section 2.1. If a constant is needed in a FORTRAN
program its value can simply appear in the place where it is needed. E.g.,
i = 20 ! 20 is an INTEGER constant
e = 2.71828 ! 2.71828 is a REAL constant
PRINT *, 'Enter a number' ! 'Enter a number' is a
! CHARACTER constant

2
MTMA33 FORTRAN BASICS 2007

2.3. Variables
Variable names must have between 1 and 31 alphanumeric characters (letters, underscores and
numerals), and the first must be a letter. Choosing variable names sensibly will greatly help the
intelligibility of your code. Variables can have any of the types discussed in section 2.1. The type of
each variable can be declared in the type declaration statements at the start of the program. E.g.
INTEGER :: i, j
REAL :: heat_capacity
The length of a character variable is specified in the type declaration.
CHARACTER(LEN=20) :: axis_title
By default, variables whose type is not specified are assumed, implicitly, to be INTEGER if their
name starts with i, j, k, l, m, or n and REAL otherwise. However, you are strongly encouraged to
override this by inserting the statement
IMPLICIT NONE
before your type declaration statements. Then all variables must be declared; any not declared will
cause an error message. Doing this speeds up program development enormously by catching a lot
of bugs that would otherwise be difficult to track down.

2.4. Initial values for variables


Initial values for variables can be specified in the type statement. E.g.,
INTEGER :: i = 1, nstop = 200
REAL :: a = 1.0, b = 2.0, c=1.0
An alternative way is to use a DATA statement. E.g,
INTEGER :: i, nstop
REAL :: a, b, c
DATA i, nstop /1, 200/, a, b, c /1.0, 2.0, 1.0/

2.5. Parameters
A parameter is a named constant. It cannot be changed by the program as it runs. However, the
programmer can change it between runs. Parameters are useful when the same constant appears
in many places in a program, for example as an array size. A parameter type is declared and its
value assigned in a type statement. E.g.,
INTEGER, PARAMETER :: npoints = 1000
REAL, PARAMETER :: pi = 3.14159

3
MTMA33 FORTRAN BASICS 2007

3. Calculations

3.1. Assignment
Assignment statements are of the form
variable = expression
This means evaluate the expression on the right hand side and put the result into the variable
appearing on the left hand side. Any value that the variable had previously is overwritten and lost.
The "=" sign thus has a slightly different meaning from its usual mathematical meaning. For
example,
x = x + 1.0
is a perfectly valid assignment statement and involves no contradiction.
Unless it has been given an initial value in a type or data statement, a variable is undefined, i.e.
has no definite value, until it appears on the left hand side of an assignment statement or is read
in a READ statement. Then it becomes defined. Undefined variables cannot be used in expressions.

3.2. Numeric operators


Expressions are built up from operators and operands. The numeric operators built into FORTRAN
are

TABLE 2. Numeric operators


High precedence ** Exponentiation
* Multiplication / Division
Low precedence + Addition - Subtraction

When several operators appear in an expression, e.g.,


x = y + b*z**2
the operators are evaluated in the order of precedence given in table 2. Operators with equal
precedence are evaluated left to right, except for repeated exponentiations. E.g.
a-b+c means (a - b) + c
but
a**b**c means a**(b**c)
Parentheses can be used to override the default order of evaluation of operators, and should be
used to avoid ambiguous-looking expressions like
b/2.0*a
The results of INTEGER arithmetic are always integers. In the case of division not yielding an exact
integer the result is truncated towards zero to give an integer. E.g. the result of 8/3 is 2; the result
of -8/3 is -2; the result of 2**(-3) is 0. Usually expressions do as you might expect when combining
different types in one expression: INTEGERSs are converted to REALs when they are to be
combined with REALs and REALs are converted to COMPLEX when they are to be combined with
COMPLEX. However
volume = (4/3) * pi * r**3
will yield the wrong result because the integer subexpression (4/3) will be evaluated first as 1.

4
MTMA33 FORTRAN BASICS 2007

3.3. Relational operators


Relational operators compare two numerical expressions and return a logical value.

TABLE 3. Relational operators


< Less than
<= Less than or equal to
== Equal to
/= Not equal to
> Greater than
>= Greater than or equal to

For example, if a and b are real variables equal to 1.0 and 2.0 respectively, then a < b would have
the value .TRUE. while a == b would have the value .FALSE. .

3.4. Logical operators and expressions


Logical expressions can be combined using Boolean logical operators. These are, in order of
precedence

TABLE 4. Logical operators


High precedence .not. Logical negation
.and. Logical intersection
.or. Logical union
Low precedence .eqv. and .neqv. Logical equivalence and non-equivalence

E.g.,
fun = sun .and. surf ! fun, sun and surf
! are LOGICAL variables

Relational expressions may be included in logical expressions. E.g.


summer = sun .and. temperature > 22.0 ! temperature is REAL
! sun is LOGICAL
In this case any relational operators take precedence over logical operators.

5
MTMA33 FORTRAN BASICS 2007

3.5. Character expressions


Character variables can be manipulated by concatenation and by extracting substrings. E.g., if
word1 = 'hot' and word2 = 'pot' then word1//word2 has the value 'hotpot' and
word1(1:2)//word2(2:3) has the value 'hoot'.

3.6. Intrinsic functions


FORTRAN has many built-in functions that can be used in computing expressions. Some of the
most useful are given in table 5.

TABLE 5. Intrinsic functions


MIN(a1,a2,...) Minimum of the arguments
MAX(a1,a2,...) Maximum of the arguments
SIGN(a,b) Absolute value of a times sign of b
INT(a) Integer part of a (truncated towards 0)
NINT(a) Nearest integer to a
ABS(a) Absolute value of a
SQRT(a) Square root of a
EXP(a) e to the power a
LOG(a) Natural logarithm of a
SIN(a) Sine of a
COS(a) Cosine of a
TAN(a) Tangent of a
ATAN(a) Arctangent of a
SINH(a) Hyperbolic sine of a
COSH(a) Hyperbolic cosine of a
TANH(a) Hyperbolic tangent of a
REAL(i) Convert INTEGER to REAL type
REAL(z) Real part of a COMPLEX value z
AIMAG(z) Imaginary part of a COMPLEX value z
CONJG(z) Complex conjugate of z
LEN(y) Length of a character string y

6
MTMA33 FORTRAN BASICS 2007

4. Printing and Reading

4.1. Printing
To print results to the monitor a PRINT statement is used.
PRINT *, expression1, expression2, ...
The expressions expression1, expression2, ... can be of any type.

4.2. Reading
To read data from the keyboard a READ statement is used.
READ *, variable1, variable2, ...
When the program reaches the READ statement it pauses and waits for the data to be typed in.
Note that it is advisable to have a PRINT statement before the READ statement otherwise you
won’t know that the programme is waiting for you to enter something!

E.g.,
PRINT *, 'Enter two REAL numbers'
READ *, a, b
PRINT *, 'Their sum is ', a + b

5. Control statements
Normally FORTRAN statements are executed in top-to-bottom order. The program stops when it
reaches the END PROGRAM statement. (The program can be made to stop elsewhere by a STOP
statement.) Control statements allow the program to depart from the normal top-to-bottom
exectution order. Control statements are what give computer programs the power to perform very
complex calculations.

5.1. The IF statement


The IF statement is the simplest control statement. It has the form
IF (logical_expression) action_statement
For example,
IF (leapyear) ndays = 366

7
MTMA33 FORTRAN BASICS 2007

5.2. The IF construct


Alternative cases can be catered for, and more complex conditional code included, by using the IF
construct.
IF (logical_expression_1) THEN
statements_1
ELSEIF (logical_expression_2) THEN
statements_2
ELSEIF (logical_expression_3)
statements_3
...
ELSE
statements_4
ENDIF
There may be any number of ELSEIF blocks, including none. The ELSE block is also optional. If it is
omitted then there is no action if the logical expression in the IF statement is false.
IF constructs may be nested within each other to handle complicated cases. Indentation is
recommended to keep the code readable. See Example 4 in the appendix.
IF constructs can be given a name. This is useful in long and complicated programs, helping both
the programmer and the compiler's error checking. E.g.,
swap: IF (a < b) THEN
temp = a
a=b
b = temp
ENDIF swap

8
MTMA33 FORTRAN BASICS 2007

5.3. The DO construct


The DO construct allows a sequence of statements to be repeated a number of times. One form of
the DO construct is
DO control_var = first, last, step
statements
ENDDO
Here control_var is an INTEGER variable, and first, last, and step are INTEGER expressions. The
statements are executed times (this may be 0 times). On successive iterations control_var takes
the values first, then first+step, etc. step may be omitted from the DO statement; then it takes the
default value 1. control_var may not be explicitly modified by any of the statements within the
loop. See Example 5.

An alternative form of the DO construct is


DO WHILE(logical_expression)
statements
ENDDO

The loop is entered or re-entered only if logical_expression is .TRUE. . This form of the construct is
useful when the number of iterations is not known before entering the loop. Obviously the
calculations carried out by statements must result in the logical_expression eventually becoming
.FALSE., otherwise the loop will carry on for ever.
Like IF constructs, DO loops can be given names to improve the readability of complex codes and
to help the compiler's error checking. E.g.,
timeloop: DO step = 1, nstop
statements
ENDDO timeloop

DO loops can be nested one within another. Also DO loops can contain IF constructs and IF
constructs can contain DO loops.

5.4. The GOTO statement


A GOTO statement transfers control to another part of the program. It has the form
GOTO label
statements
label statement
The label is a string of up to 5 digits. In the target statement the label must appear in the first
5 columns. The target statement may be either before or after the GOTO statement. Usually the
target statement is of the form
label CONTINUE
CONTINUE is a do nothing statement that exists mainly to make target statements clearer (and as
an alternative terminating statement for DO loops). GOTOs should be used only when absolutely
necessary, otherwise they lead to unstructured code that is difficult to read and error prone.

9
MTMA33 FORTRAN BASICS 2007

6. Arrays

Arrays are a way of giving lots of data values of the same type the same name, allowing lots of
similar calculations to be done with a small amount of code. Arrays may be of any type, and the
rules for naming them are the same as for non-array variables (called scalars). The elements of an
array are identified by indices. The number of indices needed is the dimension of the array, which
may range from 1 to 7.

6.1. Array declaration


The size and shape of an array is specified in the type statement. E.g,
REAL :: a(10)
defines an array whose elements are a(1), a(2), ..., a(10). By default the lowest index is 1, but this
can be overridden by specifying a lower bound. E.g.,
REAL :: a(0:100)
PARAMETERS that are defined before the array is declared can be used in declaring the array. E.g.,
INTEGER, PARAMETER :: rows = 10, columns = 25
REAL :: matrix(rows, columns)

6.2. Calculations using arrays


An individual element of an array can be used in calculations by specifying its index. The index
must be an integer. E.g.,
a(3) = SQRT(2.0) + b
f= c(1) + c(2)*x + c(3)*x*x
Arrays become powerful computing tools when the index is a DO loop control variable. See
Example 6 and Example 7.

FORTRAN 90 can also perform calculations on whole arrays using a single statement. For example
a = 2.0*b ! a and b are arrays
takes each element of the array b, multiplies it by 2.0, and stores the result in the corresponding
element of array a. The arrays a and b must be conformable, i.e. have the same shape and size.
Subarrays may also be manipulated by specifying a range of indices. E.g.,
a(1:10) = c(11:20,i) + d(n+1:n+10) + 1.0
PRINT *,' a = ', a(1:10)
Again, the subarrays must be conformable. Note that a scalar is conformable with any array, in the
obvious way.

10
MTMA33 FORTRAN BASICS 2007

7. Subprograms

A piece of code that needs to be executed at several different places in a program can be put in a
subprogram and that subprogram called from the main program at the appropriate places. This
reduces program length and programmer effort, and reduces the risk of introducing bugs. The use
of subprograms also produces more modular and structured code, and so you are encouraged to
place well-defined subtasks in subprograms even if they are used only once. FORTRAN allows two
kinds of subprogram: SUBROUTINEs and FUNCTIONs

7.1. Subroutines
A SUBROUTINE has a very similar structure to a PROGRAM, except that it can include some
dummy arguments.

SUBROUTINE name(dummy1, dummy2, ...)


Type declaration statements
Executable statements
END SUBROUTINE name

The dummy arguments provide one way to pass data between the main program and the
subroutine. (Another way is through modules.) A statement of the form
CALL name(actual1, actual2, ...)
has the effect of executing the subroutine statements with the dummy arguments replaced by the
corresponding actual arguments. See Example 10. The actual arguments may be constants or
variables, including arrays. The dummy arguments must be variables. Usually the CALL and
SUBROUTINE statements should have the same number of arguments, and the corresponding
argument should have the same type and shape and size.
When an argument is an array it is often convenient to pass its shape and size information as
arguments too. See Example 11.
Some arguments may be intended solely for passing data into the subroutine and should not be
modified by the subroutine. Others may be intended solely for passing results out of the
subroutine and need not be defined on the way in. Yet others may be intended for passing data
both ways. The clarity of the code may be improved and the compiler's error checking helped by
specifiying the intent in the subroutine's type declaration statements. See Example 10 and
Example 11. The INTENT may be IN, OUT, or INOUT.
SUBROUTINEs may CALL other SUBROUTINEs. However, special steps must be taken if a
SUBROUTINE is required to call itself, either directly or indirectly.

11
MTMA33 FORTRAN BASICS 2007

7.2. Functions
A FUNCTION has a similar structure to a SUBROUTINE.
type FUNCTION name(dummy1, dummy2, ...)
Type declaration statements
Executable statements
END FUNCTION name

The important differences are that a FUNCTION has a type, and that somewhere in the executable
statements name must be assigned a value. It is poor programming practice to change the values
of the dummy arguments within a FUNCTION. If you need to do this then it's better to use a
SUBROUTINE. A FUNCTION is invoked by using its name in a similar way to using any intrinsic
function. See Example 8.

12
MTMA33 FORTRAN BASICS 2007

8. Files

Data may be be written to or read from files stored on the computers discs. A file may be opened
for reading or writing using an OPEN statement.
OPEN(unit, file = filename)
Here unit is an INTEGER expression (usually in the range 1-99) and filename is a CHARACTER
expression. Subsequent READ or WRITE statements then refer to the file via the unit number.
READ(unit1, format1) inputlist
WRITE(unit2, format2) outputlist
Here inputlist is a list of variables to be read in from the file, and outputlist is a list of variables
and constants to be written out to the file.
There are various ways of specifying the format of the data to be read or written, depending on
the format parameter of the READ or WRITE statement. The simplest case is when the format
parameter is an asterisk (list-directed I/O). Then a READ statement does its best to read the data
whatever format it is in, and a WRITE statement choses a reasonable format for the data being
written at that moment.
The user can control the format explicitly by specifying it in a CHARACTER string built up from
edit descriptors separated by commas and enclosed in parentheses.

TABLE 6. Format specifiers


Type Edit Description Example Output
descriptor
INTEGER Iw Width w, right WRITE(6,'(I6)') 123456 123456
adjusted
REAL Fw.d Width w, d WRITE(6,'(F12.5)') 3.14 3.14000
decimal places
REAL Ew.d Scientific notation, WRITE(6,'(E12.5)') 1005.0 0.10050E+
d decimal places 03
CHARACTER A Character string WRITE(6,'(A)') 'HELLO' HELLO
X Skip a character WRITE(6,'(I2,X,I2)') 22,23 22 23
/ New line WRITE(6,'(I2,/,I2)') 22,23 22
23

Longer format strings, or format strings that are to be used repeatedly, can be specified in a
FORMAT statement and referred to by a label. E.g.,
WRITE(6,900) a(1:100)
900 FORMAT(10F12.5)
In this example the FORMAT statement specifies 10 numbers to be written, each in floating point
format, and each with 12 characters including leading blanks, and 5 decimal places. The WRITE
statement writes 100 numbers, so the specified format is recycled 10 times, producing 10 lines of
output, each with 10 numbers.

13

You might also like