
1. Introduction
Fortran is one of many programming languages available. The name
Fortran is short for FORmula TRANslation and this guide is based on
Fortran 90, which is a version agreed in 1990. Fortran 95, a later standard,
was a minor revision of Fortran 90. The latest standard, Fortran 2003, is in
its final draft stages.
Fortran was developed for general scientific computing and is a very
popular language for this purpose. In 1996 it was estimated that Fortran
was employed for more than 90% of scientific computation (see Scientific
Computing World, April 1996). Fortran is not, however, particularly suitable
as a non-scientific general-purpose language or for use in equipment
control, commerce, text management etc where more appropriate
alternatives are available.
Fortran 90 is available on the ITS Linux service, the UNIX service and on
the Networked PC service. In this course you will use it on the ITS Linux
service. You will need to be familiar with basic Linux commands (e.g. those
covered in Guide 169: An introduction to Linux) and be able to use a Linux
text editor, such as pico, emacs or vi.
About the course
This course provides an introduction to the Fortran 90 programming
language. It should provide you with enough knowledge to write
straightforward Fortran programs and you should also gain some general
experience which can usefully be applied when using any programming
language. The course is constructed from five parts:
Part 1 Getting started: programming basics
Part 2 Input and output, and using intrinsic functions
Part 3 Arrays: vectors and matrices
Part 4 Program control: do loops and if statements
Part 5 Subprograms: functions and subroutines
If you receive these notes on an ITS course, they will be issued by part.
Please bring the notes for previous parts of the course with you to future
sessions so that you have them for reference.
If, at the end of the course, you wish to know more about Fortran 90, many
books and on-line tutorials have been written on the subject. Some
suggestions are given at the end of Part 5.
2. Programming basics
This section describes the structure and contents of a Fortran 90 program.A program is simply a set of instructions that tell a computer to do a
particular task. To create a program that works, and works efficiently, you
will need to do the following before you start writing the program:
1) Make sure that you understand the aims of the program.
2) Decide on the information that the program will need as input and that it
should produce as output.
3) Make sure that you understand how the computations will be done (i.e.
that you understand the algorithms to be used) and the order in which
they should be done.
It is very easy to skip one or more of steps 1 - 3 and start writing a program
without really thinking about how it will work. Unless the program is very
small, this will probably lead to a program that is badly structured and
difficult to follow. Most programs do not work perfectly first time, but they
are more likely to work and will be easier to correct if they are well
structured from the beginning.
So, once you have completed steps 1 - 3,
4) Create a program that will solve the specified problem with the
algorithm(s) and input/output requirements that you have identified.
5) Test the program thoroughly.
2.1 The main parts of a Fortran 90 program
A Fortran 90 program has four main elements, in this order:
Program name
The first line of the program gives the program's name, e.g.
program fred2
The program name allows you to recognise the program by looking at the
version that you have typed into the computer. Later versions of the
program might be called, for example,
program fred3
or
program fred4
In principle the program name is optional, but during this course you should
always give a name to your programs.
Initialisation section: declaration of variables
The initialisation section sets some rules for the program but does not carry
out calculations. In particular, it is used to declare all the variables that will
be used to store numbers, etc, within your program. In Fortran 90 there are several pre-defined variable types such as integer, real and character,
and it is even possible to define new types. The declaration statements set
the types of your variables and can also be used to set initial values. The
Fortran rules do not insist that you declare variables, but it is good
programming and helps avoid many errors.
Main program body
The main program body contains all the executable Fortran statements that
will carry out the task you wish to perform. Statements are generally
executed in order, from top to bottom. The last statement must be an end
statement. In many cases the efficiency and appearance of the main
program can be aided by:
Subprogram(s)
The structure of a program can be made much clearer if blocks of
instructions that perform particular tasks are moved out of the main
program and into subprograms. Subprograms are also very useful if the
same block of instructions is needed several times.
2.2 The layout of Fortran 90 statements
A Fortran 90 program consists of a series of executable and nonexecutable statements. Executable statements are ones that cause the
computer to perform some desired operation, e.g. the addition of two
numbers, whereas non-executable statements provide information which
enables the proper operation of the program, e.g. the definition of variables.
Whether it is part of an executable or non-executable statement, each line
in a Fortran 90 program must conform to certain rules about layout:
• A line can be up to 132 characters long (including spaces).
• Any line can start with leading spaces to improve layout.
• An & at the end of a line indicates that the statement continues on the
next line. If the item to be continued is a character constant or a format
statement (both discussed later in the course), the next line should start
with a second &.
• If a line contains an exclamation mark (!), everything from the
exclamation mark to the end of the line is a comment and will not be
executed. Every comment line must begin with this character.
• Several statements can appear on a line, separated by semi-colons (;).
Note: earlier versions of Fortran used a much more rigid layout. This is still
permitted in Fortran 90 but is no longer necessary. Details of the older
layout style are given in section 15.1. The newer, 'free format' layout is
used throughout this guide.
3. Data types
The data that are handled by a program fall into two main types. Constants
have a fixed value, while variables, in which the program will store its input,
output, constants and intermediate results, may change value during
execution of the program.
3.1 Constants
Any constant must have a type so that the computer knows how to store
and handle it. The range of numbers permitted in each type depends on the
computer: the descriptions given below are common on machines with a
32-bit operating system. The main types of constant are:
Integer Integers are normally stored in 4 bytes (that is, 32 bits, i.e. 32
binary 0s and 1s) of storage space. This allows integers from
-2147483647 (231) to +2147483647 (231 - 1) to be
represented.
Real Floating-point real numbers also have a default storage
allocation of 4 bytes. The sign, mantissa and exponent must
all be held in this space. Depending on the Fortran 90
implementation; real numbers can lie typically between
approximately 1038. Four-byte floating point numbers have
only about 7 significant digits.
Double
precision
Double precision numbers are similar to real numbers but are
allocated twice as much storage space, 8 bytes, so that they
can hold more digits in the mantissa. They have about 15
significant figures and can lie in the approximate range 10-307 -
10308.
Character Character variables can be used to hold standard text/ASCII
characters with one byte per character and N bytes in total,
where N is an integer. Unless N is defined in the declaration
of the variable, the variable can hold only 1 character.
Logical Logical variables have a value of either .true. or .false. . They
take storage space of 4 bytes.
Complex Two real (4 byte) numbers stored as a pair and treated as the
real and imaginary parts of a complex number.
The following examples show you how to enter constants correctly.
3.1.1 Integers
Any number without a decimal point falling between the prescribed limits is
a valid integer, e.g:
-3478
0
568546
+12345678
The following are not valid integers:
-1,000 (commas not allowed)
987. (contains a decimal point)
987654321098 (too big)
3.1.2 Reals
Real numbers contain a decimal point and lie within the prescribed range
such as:
0.0123 (can also be written as 1.23E-02)
0.0 (can also be written as 0.0E0)
-23456.0 (can also be written as -2.3456E4)
+987652.0 (can also be written as 9.87652E+05)
Examples of illegal real constants are:
-10 (no decimal point, integer)
1,123. (commas not allowed)
145678E4 (no decimal point in mantissa)
666888.E8.2 (decimal points not allowed in exponent)
3.1.3 Double Precision
These follow the same basic rules as for real numbers but D must be used
instead of E to indicate the exponent. For example, 1.23D-02 and
0.0123D0 represent the double precision version of 0.0123.
3.1.4 Character
Character constants must be contained within single quotes (apostrophes),
for example:
'This is a 31 character constant'
' '
'45.68'
The following are not valid character constants:
Invalid character constant (no quotes)
'Another one (unpaired quote)
To include an apostrophe within the character constant, two apostrophes
should be used e.g.
'Fortran 90 solved all of Julie''s problems'
The '' pair will be interpreted as a single apostrophe within the character
string.
3.1.5 Logical
The only valid logical constants are .true. and .false. (or .TRUE. and
.FALSE.).
3.1.6 Complex
Complex constants are written as a bracketed pair of valid real numbers
separated by a comma, e.g.:
(1.234,-6.5E-3)
where, in this example, 1.234 is the real part of the complex constant and
-0.0065 is the imaginary component.
3.2 Variables
Variables are where your program will store its input, output, constants and
intermediate results. In standard Fortran 90, variable names may contain
alphabetic and numeric characters and underscores but must begin with an
alphabetic character and be no longer than 31 characters long in total. So
loop3 and MyAnswer are valid variable names but 123x and _abc are not.
In general it is helpful to give variables sensible names that suggest their
purpose.
You should be aware that unlike some other programming languages
Fortran does not distinguish between upper and lower case characters, so
a variable called NUMBER is entirely equivalent to one called number or
NUMber etc. Early versions of Fortran used upper case only, but this is no
longer necessary and you need not follow this convention during the
course.
Like constants, variables have to have a type. Any valid constant value can
be assigned to a Fortran variable, provided that the type of the constant is
compatible with the variable's type.
At the beginning of a program you should declare each variable and its
type. The declaration is simply a statement of the variable's type and some
optional extra details such as an initial value.
If you miss out the declaration of a variable, Fortran 90 will give it a type
according to its name: undeclared variables with names beginning with the
letters I,J,K,L,M,N will be given type integer whereas all others (A to H and
O to Z) will be type real. This 'implicit typing' rule is convenient but also
causes problems, since it means that Fortran will accept any mis-spelled or
undeclared variables instead of warning you. This is discussed further in
section 12. To instruct Fortran to reject any variables that have not been
declared, include the line:
implicit none
before any other declarations. The implicit none statement should be used
in all of the programs in this course.
As well as using implicit none, it is strongly advised that you comply with
the naming conventions of implicit typing when naming variables. This can
be useful if (when!) you need to resolve problems in your programs.
4. How to write, process and run a program
There are four stages to creating a Fortran 90 program:
1) Create and save the program using a text editor. The file you create is
called the source code and should have a name that ends in .f90, e.g.
fred.f90.
2) Compile the code into an intermediate format, called an object file.
Compilation is done by the command pgf90. During compilation your
program is checked for syntax errors and, if none are found, a file is
created with a name ending in .o, e.g. fred.o.
3) Link the file into a final, executable form of your program. If compilation
was successful, the pgf90 command will next link your program with
any libraries that it needs. If linking is successful, the object file will be
removed and an executable file will be created. The default name for
the file will be a.out, but you can also specify a name, e.g. fred.
Whereas the original source code that you typed in should normally be
understandable to any Fortran 90 compiler, the final, executable form of
your program is specific to a particular machine type.
4) Run the program.
4.1 Writing the program
In the following sections of this course, you will create a number of small
programs. To keep the files separate from the rest of your work, you might
want to create a directory now in which to store the files. Then cd to the
new directory and work from there:
cd
mkdir Fortran
cd Fortran
Use a text editor (e.g. pico or emacs) to type in the following program and
save it as a file called mult1.f90.
program mult1
implicit none
integer:: i,j,k
!
! This simple Fortran program multiplies two integers.
! It then displays the integers and their product.
!
i = 5
j = 8
k = i * j
write(*,*)i,j,k
stop
end program mult1
Note the following:
Line 1 The file and program names do not have to be the same.
However, it is sensible to choose meaningful names for both so that you know which program is in which file and have an
indication of the purpose of the program.
Line 2 The implicit none line tells the compiler not to use the implicit
rules for variable types/names. Its effect is that any
undeclared or mis-spelled variables will cause an error when
the program is compiled.
Line 3 This declaration statement reserves storage space for three
integer variables called i, j and k.
Lines 4-7 Comment statements have been used to document the
program.
Lines 8-9 The assignment statement i = 5 places the value 5 into the
variable i and similarly the statement j = 8 gives j the value 8.
Line 10 The assignment statement k = i * j multiplies the values of
variables i and j on the right and assigns the result to the
variable k on the left. Notice that the result variable must be
on the left.
Line 11 A write statement is used to display the contents of the three
variables i, j and k. Note that commas must be used to
separate the items in the list of variables. The (*,*) part
contains information about the destination for the output and
the format of the output. The * symbols mean that we accept
the defaults: the default destination is the screen and we will
accept the default format.
Line 12 When a running program arrives at the stop statement,
execution is terminated and the word STOP is displayed on
the screen. The STOP statement is not compulsory.
Although it is not recommended, a program may have
several STOP statements numbered STOP 1, STOP 2, etc,
at different places within the program.
Line 13 The end statement indicates the end of the program or
subprogram. It is good practice to include the name of the
program in this line, as shown.
When you have typed in the program, compile, link and run the program as
described in the next section.
4.2 Compilation and linking
Once you have created your source file mult1.f90, you can compile and
link it in one step using the pgf90 command. At a Linux command prompt,
type:
pgf90 -o mult1 mult1.f90
where the basic command is pgf90 mult1.f90 and the option -o mult1 is
used to name the output file mult1. If you omit this option, your executable
file will be called a.out, regardless of the name of your source file.
Note: on the ITS Sun UNIX service, the compilation and linking command is
f90.
If the compilation and linking process was successful, pgf90 will run without
displaying any messages. If any errors occurred during compilation or
linking, error messages will be displayed. Go back to the text editor and
correct the errors in mult1.f90, then save, re-compile and re-link.
Once the compilation and linking have been completed successfully, you
will have an executable file called mult1.
4.3 Running the program
To run the mult1 executable, simply type its name:
mult1
If your program compiled, linked and ran first time without errors then go
back to the editor and deliberately introduce errors in order to see what
happens - e.g. try changing integer to intger in the declaration statement
and try changing i to ii in line 10. What happens if you leave this second
mistake and remove the implicit none statement? Make sure that you
remember to correct your program afterwards!
4.4 Removing old files
At the end of this first exercise you will have generated some files. The
mult1.f90 source file that you typed is useful to keep for future reference,
but you can delete the executable file mult1, which is using up space. If
you have a mult1.o file, that can be removed too. The executable and
object files can be regenerated from mult1.f90 if you need them again.
In the next exercise you will need to modify your mult1 program. Instead of
editing mult1.f90, it is a good idea to copy mult1.f90 to another file, e.g.
mult2.f90, then work on this new file. When you are developing a new
program in a series of stages it is always a good idea to take copies as you
go along and leave previous (working) versions in case your modified
program does not work and you cannot remember exactly how the original
was written! So always keep backup copies of your source files.
Exercise
In this exercise you will write a simple program that reads any two integers
typed on the keyboard and writes the two integers and their product on the
screen. To work through this section, first make a copy of mult1.f90 and
call the copy mult2.f90.
One of the problems with mult1 is that if you want to multiply any other pair
of integers, instead of 5 and 8, then you need to modify the program each
time. An alternative, more efficient approach is to modify the program so
that you can input any two integers and then multiply these. In order to do
this you should remove lines 8 and 9 from mult2.f90, i.e. the lines:
i = 5
j = 8
and replace them with the single line:
read(*,*)i,j
This read statement tells the computer to expect to receive two values from
the keyboard when the program runs. When it receives the two values, it
will place them in order in the integer variables i and j. Note that the list of
variables in a read statement must be separated by commas.
In this example the first * in the brackets is an instruction to use the default
source of information, which is the keyboard, and the second * tells the
computer to interpret the two values in an appropriate default manner - in
this case as integers because i and j have been declared as integers. Later
in the course you will see how to specify a different source of information
(e.g. a file) and a particular format for the incoming information.
When you have made the necessary changes to mult2.f90, compile, link
and run your new program. The program will pause to allow you to input the
information required. Type in 5,8 or 5 8 and then press the Enter key and
you should then obtain the same result as with mult1. With this new
program, however, you can multiply any two integers.
This program is still not very “user-friendly”. For example there is no
indication that the program is waiting for the input of numbers. To improve
this, include the following write statement before the read statement:
write(*,*) ‘Enter the two integers to be multiplied’
Anything that is written between the two apostrophes will appear on the screen
when the modified program is run. Try it!
More user-friendly output can also be obtained by mixing text and results in
the following manner. Try replacing the simple output statement:
write(*,*)i,j,k
with the following version:
write(*,*)' The product of ',i,' and ',j,' is ',k
As you can see, anything between pairs of apostrophes is written literally to
the screen as a character string, while the other items (i, j and k) which are
not between apostrophes are recognised as variables and their value is
written.
Later in the course you will see how to customise the format of your output
using a format statement.
Exercise
Modify mult2.f90 so that it operates with real variables x,y,z instead of
integer i,j,k and name the altered program mult3.f90. How does the
answer differ from the answer given by mult2?
Next, modify mult3.f90 so that it operates with double precision variables
x,y,z instead of real x,y,z and name the altered program mult4.f90.
What
changes do you notice in your answers?
5. Converting between types of variable
In the exercises above you experimented with some different types of variable. It is important to use appropriate variable types in your program,
or it may not work properly. For example, the following program shows
what happens when two integers are divided. Type the program into a file
named divide1.f90:
program divide1
implicit none
integer:: i,j
real:: x
!
! Program to demonstrate integer division.
!
write(*,*)' Enter two integers'
read(*,*)i,j
x = i / j
write(*,*) i,' divided by ',j,' is ',x
stop
end program divide1
Compile and link this program, and then run it for some trial values of i and
j. You will see that the results are only correct when i is an exact multiple of
j. In any other case, the result is truncated to an integer even though x is
real. This happens because of the way the statement is calculated. The
right hand side of the line x = i/j is calculated first. Both i and j are integers,
so the result of i/j is also an integer. The integer result is then converted to
a real number to be stored in x, but the truncation has already occurred.
Accidental integer division is a common error in programming.
In order to obtain the true (possibly non-integer) ratio of any pair of
integers, copy your program to a new file divide2.f90 and alter the line
x = i / j
of your new program to:
x=real(i)/real(j)
real converts an integer value into a real value and thus the division now
involves two real numbers. Check that your new program gives the correct
answer. Note that it would not have been sufficient to write real(i/j). Why
not?
real is called an intrinsic function because it is a function that is built-in to
Fortran. Some other intrinsic functions for conversion between different
number types are:
dble transform a variable to double precision
int truncate a real number to an integer
nint round a real number to the nearest integer Reminder! At this point you will have a number of files taking up disk space.
Delete any that you do not need (but keep the .f90 source files for later
reference).
Exercise
Write a program (inv.f90) to read a real number, take the inverse and show
the result on the screen. Write a second version (inv2.f90) that works in
double precision. Run the two versions of your program, using the number
7 as input, and compare the results.
6. hierarchy of operations in Fortran
You have already seen that the order of operations matters. In general, thecomputer takes the following steps when executing an assignment
statement:
1) it calculates the result on the right hand side of the statement in a form
appropriate to the types involved,
2) it looks at the type of the variable on the left and finally,
3) it converts the result on the right in order to assign a value to the
variable on the left hand side.
The first of these steps often involves evaluating an arithmetic expression.
When a general Fortran arithmetic expression is computed there is a strict
order in which the component parts of the expression are evaluated. The
order is:
1) Terms in (round) brackets starting from the innermost brackets and
working outwards.
2) Exponentials working from right to left (Note that xy is written x**y in
Fortran).
3) Multiplication (denoted by a single *) and division, working from left to
right.
4) Additions and subtractions working from left to right.
Note that consecutive mathematical operators are not allowed. Some
examples of invalid expressions and corrected versions are:
Exercise
Write a program, order.f90, to evaluate the following three expressions:
x=a*b+c*d+e/f**g
y=a*(b+c)*d+(e/f)**g
z=a*(b+c)*(d+e)/f**g
where all variables are of type real. Set trial values for the variables and
convince yourself that the expressions are evaluated according to the
described hierarchy.
We will be talking About Introduction to Fortran 90 Part 2 in our next post, which is About Input and Output :

0 Comments