Chapter 1: Fortran Programming: Detailed Notes
Chapter 1: Fortran Programming: Detailed Notes
Detailed Notes
This chapter contains a brief introduction to the most commonly used FORTRAN commands, and should
be read in conjunction with the example programs. See the ‘what you need to know’ handout for a summary.
FORTRAN Layout
1 Program Tiger TITLE
2 Implicit None turns on spell-checking
3 Real:: energy, mass, velocity declares variables
4 mass=1. sets value for mass
5 velocity=1.
6 energy = mass* (velocity**2)/ 2. calculation E = mv 2 /2
7 ! mks units comment
8 Print *, energy ! Prints to screen print command and comment
9 End Program Tiger ends execution
Notes
• Upper and lower case are interchangeable except for character strings (see below)
Names of Variables
Good Bad / Not Allowed Ugly
Mass M+N g3x2v
Kinetic Energy Kinetic Energy x
MyName 3X real
Name3 Name 3 x3
2
Arithmetic Expressions
FORTRAN MATHS
x=a*b x = ab
x=a+b Same
x=a-b Same
x=a**b x = ab
x=a/b x = ab
x=a*b+c x = ab + c (Multiplication done first)
x=(a*b)+c x = ab + c
x=a/b*c/d+e !!! Who knows!!! Use brackets
ac
x=(a/b)*(c/(d+e)) x = b(d+e)
The equals sign: The = sign really means ‘is assigned the value’. Therefore
x=x+1
Integer Division
Integer variables do not store fractions or remainders, so care is needed when performing operations with
integers.
8/3 → 2
4/5 → 0
-8/3 → -2
(5*8)/5 → 8
5*(8/5) → 5
If reals and integers are mixed, a product or division becomes real, e.g. 8.0/5 → 1.6.
Example Program:
Program CatsandDogs
Integer:: dog
Real:: cat
cat=8.0/5
dog=cat
print *,dog !→ prints 1
print *,cat !→ prints 1.6000000
End Program CatsandDogs
Note that:
dog=8.0/5
cat= dog
results in dog having value 1 and cat value 1.0000000.
4
Intrinsic Functions
Fortran supplies numerous functions, e.g.,
Sqrt, Sin, Cos, Tan, Exp, Log.
Some of these operate only on particular data types, e.g., Sqrt should be given a real rather than an
integer.
FORTRAN MATHS
√
x=Sqrt(4.0) x = 4 = 2.0
pi=4.*atan(1.) pi= 4 ∗ tan−1 (1) = π
y=sin(pi/2.) y = sin ( π2 ) = 1.0
5
To print to screen
Print *, OR Write(*,*)
The first * means STANDARD OUTPUT.
The second * means AUTOMATIC FORMATTING.
Example:
Write(*,*) “Mass=”, answer,”grams”
Here ‘answer’ is a real variable storing 27.2. The output is
Mass=27.2000000grams
OPEN(17, FILE=’foot.bal’)
(Note: instead of 17, any small(ish) integer other than 5 (=the keyboard) and 6 (=the screen) may be
used.)
After this command can read from ‘foot.bal’ using Read (17,*), e.g.
Integer :: Score
Open (17, File=’foot.bal’)
Read (17,*) score
and (optional), when all reading is finished
Close (17)
Each call to Read goes to a new line by default, so if foot.bal contains
3
1
0
4
OPEN(17, FILE=’lion.txt’)
will create it. This is important if you are writing to a new file. Note that a file should usually be opened
only once (do not place an OPEN command inside a DO loop.)
6
DO loops
DO loops are used when the same operation needs to be repeated ‘many’ times. Below are three different
types of loop used in different situations. The type of DO loop to use depends on whether the number of
times you want the loop to run is known beforehand (type 2) or depends on the results of operations
carried out in the loop (Type 1a or b).
When the END DO statement is reached the computer returns to the DO line and starts over again.
If in Type 1a the EXIT statement cannot be reached, or in Type 1b (condition) is never met, the program
runs forever, an INFINITE LOOP!!
To exit an infinite loop....hit Ctrl-C
It is customary to indent statements within DO loops, (by e.g. 3 spaces). It is also common practise to
place the EXIT as near the top or bottom of the loop as possible.
Note, however, that all three types can be easily used to execute some statements exactly 10 times.
a
a+c
a + 2c
.
.
a + jc
The second loop fails because 5 ∗ 0.2 6= 1 in computer arithmetic, as 0.2 cannot be stored exactly with a
finite number of bits in binary!
8
IF and IF blocks
IF blocks
If too much information must be placed after the IF (condition) then we can go to multiple lines
IF (x/=0) THEN
y=1/x
z=y+2
END IF
Possible relations going into an IF statement are
>, <, >=, <=, ==, / =, representing >, <, ≥, ≤, =, 6= respectively
IMPORTANT:: Note that == really means ‘equals’ whereas = means ‘is assigned the value’.
Other possibilities include logical operations acting on logical variables
.and., .or., .not.
Note that the computer treats entire expression (x > 3) as a logical variable that is ‘.true.’ if x > 3 and
‘.false.’ if x ≤ 3.
ELSE statement
Example
IF (x/=0) THEN
y=sin(x)/x
ELSE
y=1
END IF
Example:
logical :: giraffe
giraffe = (2**2 == 4)
1. IF (giraffe) THEN ....
2. IF (giraffe==.true.) THEN .... !WRONG
3. IF (giraffe .eqv. .true.) THEN .... !GOOD BUT SAME AS (1)
9
Arrays
Integer :: matrix1(3,4)
Real :: position(3)
Character(len=20) :: namelist(100)
Matrix1 contains 12 integers, position 3 reals, and namelist 100 × 20 character strings
Filling arrays
• Method 1: One by one
Real :: x(3)
x(1)=2.47
x(2)=3.e10
x(3)=-6.3
• Method 2: as a vector
Real :: x(3)
x=(/ 2.47, 3.e10,-6.3 /)
Parameter Declaration
Parameters are variables that are ‘hardwired’ at the start of the program. Array sizes can be declared
using a parameter variable, but not a normal integer.
Example
Integer, Parameter :: maxsize=100
Character(len=20):: names(maxsize)
bear = (/ . , . , . , . , . /)
0 1 2 3 4
Accessing Subarrays
Example
Integer :: x(3), wolf(3,0:4),row,col
DO row=1,3
DO col=0,4
wolf(row,col)=row*col
END DO
END DO
gives
0 1 2 3 4
wolf = 0 2 4 6 8
0 3 6 9 12
then the following statements, processed in order give
x=wolf(:,2) ! gives x = (2, 4, 6) i.e. wolf(:,2) is the column with index 2.
x=wolf(:,4) ! gives x = (4, 8, 12)
x=wolf(3,0:2) ! gives x = (0, 3, 6)
x=wolf(:,2) ! gives x = (2, 4, 6)
x(2:3)=wolf(1:2,4) ! gives x = (2, 4, 8), as x(1) is unchanged.
x=0 ! gives x = (0, 0, 0)...sets all components to zero
x(1:2)=wolf(3,3:4) ! gives x = (9, 12, 0)
11
Manual Formatting
Difficulty: Write(2,*) or Print *, both rely on computer to decide formatting.
Program Format
Integer :: x=34
Real :: y=2.7, z=-120
Character(len=30) :: myformat
myformat=”(A,I6,A,2F12.4)”
write(6,myformat) “x=”,x,” and y and z =”,y,z
End Program Format
The output from this is: (blank spaces not in strings are denoted by ‘*’)
x=****34 and y and z =******2.7000***-120.0000
Comments
The write statement has five things to write out:
34 → ∗ ∗ ∗ ∗ 34
−1207 → ∗ − 1207
etc
F8.2 is a format for real nos. and means 8 spaces in total (including decimal pt., ‘-’ sign and spaces, with
exactly two numbers after the decimal pt.
−102 → ∗ − 102.00
80.738 → ∗ ∗ ∗80.74
etc
F8.4 ***0.0217
ES9.2 **2.17E-02 2.17 × 10−2
E9.2 **0.22E-02 0.22 × 10−1 (rounded)
E9.3 *0.217E-02 0.217 × 10−1
12
write(6,“(3f12.4)”) y,z,w
Subroutines
Subroutines are self-contained ‘mini’-programs written to perform specific tasks. They are usually found
after the main program (or in separate files which are ‘linked’ during compilation.
Program Middle
Integer :: lion,tiger,bear
.
.
Call Findmidpoint(lion,tiger,bear)
.
Contains
.
Subroutine Findmidpoint(a,b,midpoint)
Integer, Intent(in) :: a, b
Integer, Intent(out) :: midpoint
Integer :: silly
silly = a + b
midpoint = silly/2
End Subroutine Findmidpoint
End Program Middle
• In this subroutine ‘a’ takes the value of ‘lion’, ‘b’ takes the value of ‘tiger’ and ‘bear’ will be assigned
the calculated value of ‘midpoint’.
• The types of all corresponding variables must match (e.g. ‘lion’ with ‘a’, etc.)
• As a,b have been declared Intent(in), they cannot be changed in the subroutine.
• If it is desired to change the value of the input variables, they can be declared Intent(inout)
Example
Program Intswap
Integer :: x=-10, y=17
Print *,x,y
Call Swap(x,y)
Print *,x,y
Contains
Subroutine Swap(a,b)
Integer, intent(inout) :: a,b
Integer :: temp
temp=a
a=b
b=temp
End Subroutine Swap
End Program Intswap
This gives output
−10 17
17 −10
14
Functions
Functions are similar to subroutines, but are designed to return an output of a given form from a specified
input. Notice that they are called implicitly (not using CALL).
x=2
y=3
z=sillyfun(x,y)
.
.
.
Function sillyfun(a,b)
Integer, intent(in)::a,b
Real:: sillyfun
sillyfun=sin(2.4*a*b)
End Function Sillyfun
• The module can have no executable statements, e.g. x=2*pi, just declarations functions and
subroutines.
• If modules and program are stored in one file modules should come first
16
Recursion
A function or subroutine cannot call itself unless it is declared recursive. By allowing subroutines and
functions to call themselves, we create the possibility of implementing recursive algorithms.
A recursive algorithm solves a (difficult) problem of order N indirectly, by breaking it down into problems
of order N − 1 or less, and then calling itself to reduce these constituent problems still further. In this
manner the problem is eventually reduced to problems of low order (e.g. order 1) that may be solved
directly.
Example 1: The factorial function (see example program)
Example 2: Towers of Hanoi (see example program)
Objective: Transfer rings to the third stick.
Restriction: Rings may only be placed on top of larger rings.
A Recursive Algorithm:
The problem of moving N rings from stick a to stick c may be broken down as follows:
1. Move N-1 rings from stick a to stick b (to see how, go to comment 4).
2. Move ring N to c.
4. Break down the N − 1 problems using (1-3). E.g. To move N − 1 rings from a to b, Move N − 2
rings from a to c, move ring N − 1 from a to b, and finally move N − 2 rings from c to b. The
problem of moving N − 2 rings is broken down in exactly the same way.
1. A function which moves the top ring from one stick to another
e.g. Subroutine movetop (from, to)
(i.e. movetop (b,c) moves top ring from b to c.)
Initial State
Object-Orientated Programming
Purpose: to write re-usable, error-free programs
Jargon:
1. An abstract data structure is some form of data (e.g. a set of numbers 1-150, a digitalised
photograph, etc.) together with functions and subroutines used to manipulate the data (e.g. union /
intersection of sets, cropping / removing red-eye, for photograph).
2. A class is a method of implementing the Abstract data structure. e.g. a user-defined data type, and
functions which use the type.
3. An object is a variable declared using the user-defined type. e.g. S,T,V,W in Example 13.
General Structure
Declaration
type mydata
variabletype1 :: label1
variabletype2 :: label2
.
.
end type mydata
(‘variabletype1::’ and ‘variabletype2::’ refer to declaration of intrinsic variables e.g. ‘real::’, ‘logical::’ or
‘character(len=3)::’.)
Note that some of the data inside mydata can be in the form of arrays.
Example:
type league
character(len=20)::teamnames(20)
end type league
Usage
Declaring ‘premiership’ to be a league
type(league) :: premiership
Filling in Values
Values of the teamnames in premiership can be filled in as follows
premiership%teamnames(1)=’Liverpool’
premiership%teamnames(2)=’Arsenal’
premiership%teamnames(3)=’Cambridge United’
etc.
or, alternatively
premiership=league( (/ ’Liverpool’,’Arsenal’,’Cambridge United’,..../) )
i.e. with a vector of character strings of length 20.
19
Operator Overloading
Purpose: Extend meaning of ‘∗’, ‘+’, ‘-’ etc. so that they work on user defined types.
It can be convenient to represent complex operations acting on user defined types or arrays (e.g. union or
intersection of sets - see example 13) by a simple operator such as ‘∗’ or ‘+’.
FORTRAN allows the meaning of operators such as ‘∗’, ‘+’ etc. to be EXTENDED, so that when the
operator is applied to the objects in question (for example a set of character strings, or a data type) for
which the operator WOULD NOT NORMALLY HAVE A MEANING, fortran knows to look in a
(supplied) subroutine or function to apply the operator.
Syntax
to overload ‘∗’ with the function intersection:
interface operator(∗)
module procedure intersection
end interface
note that ‘intersection’ can be either a subroutine or a function that acts on variables of type(set). If V
and W are of type(set) then V∗W will be their intersection.