FORTRAN Programming
Anand Karipot
Dept. of Atmospheric & Space Sciences
1
Introduction
• Computer program: to provide the computer a set of working
instructions and make it perform certain tasks in a desired way.
• Programming language: Human-readable language that can be
translated into machine-readable language using a specific compiler.
They are necessary for communication between human and computer.
E.g. C, C++, Fortran, Basic, Pascal,……..
• Prog. languages have fixed rules such as syntax and formats that have
to be followed exactly.
• Compiler: Translates the program written by the programmer to the
machine language. Compiler creates an executable program, which is
then run to generate desired outputs.
2
Programming – A structured approach
• Analyse the problem & plan the program
• Flowcharts
• Write and Edit the code.
• Compile, correct errors if any, and recompile as necessary
• Execute and debug program.
• Obtain the desired output
3
FORTRAN
What is FORTRAN ?
FORmula TRANslation
Versions of Fortran: Fortran 66, 77, 90, 95
Why Fortran ? Why not C, C++, Basic, Pascal……????
4
FORTRAN
Advantages / Why to learn Fortran ?
• Good at numerical analysis and scientific calculations
• A large number of programs and routines in Fortran are
exchanged internationally
• Efficient compilers are available
• The dominating language on supercomputers; most of
weather prediction and climate models are written in Fortran
• Scientists have no interest in learning new languages !!!!
5
Tools/ Requirements
• Computer – Laptop/ PC/ Workstation/ Supercomputer
• Operating System – DOS/Windows/Mac/Unix/Linux
• Text Editor
• Fortran Compiler – Converts program to machine language
6
Basic Structure of a Fortran Program
• Program name
• Variable declaration
• Input statements/ Assign values to variables
• Process data/ Calculations
• Output statements: Write/ Print results
• End program
7
Sample fortran program
program add100
! to find the sum of numbers 1 to 100
implicit none
real::sum
integer::i
do i = 1,100
sum = sum+i
end do
write*,sum
end program add100
8
Flow of a Program
• Linear sequence; One statement per line (preferred), can be more,
should be separated by ‘ ; ’
• Comments (ignored while compiling)
• Blank spaces are ignored (but not within a variable name)
• Repetition : Loops
• Selections : Conditional statements
• Finish program with an END program statement
9
Free-form: f90/f95
No particular position for program statements on the console/ screen
in free-form codes
In free-form:
• Continuation character ‘&’ is to be put at the end of preceding line.
• Comment line/entry character ‘!’, can be put anywhere on the line.
total=value1+value2&
+value3+value4&
+value5
! Comments
! Comments
101 goto 200
1002 format(‘Answer =‘,I4) 10
Variables
• Variables should be declared in the beginning, before any program
statement.
• Declaration involves giving a name, and stating what type of variable it
is.
• Important types of variables:
integer
real
complex
character
logical
• More than one variable can be declared on a single declaration line
11
Variables
contd…..
Variable names :
Must be at least one alphabetic character long, up to a maximum
of 31 alphanumeric characters
Must start with an alphabetic character
Case insensitive. “ANAND" & “anand" won't be distinguished
by the compiler
Alphanumeric characters allowed are : a-z, 0-9 and the
underscore ( _ )
Implicit variables: names starting with I,J,K,L,M,N are integer
variables (by default; can be changed through declaration)
12
Variables contd…
Examples:
• Valid names :
A
i1
abcd ! Use meaningful variable names
A_Temp
Year2009
Totalvalue
• Invalid names :
a&b
8Mangoes
_no_money$
• Variables can't have the same name as the program itself.
• Variables may or may not have initial values, and they can be changed to
other values later in the program. 13
Basic Data Types/ Variables
Real x = 5.246
Integer ix = 5
Complex z = (10.4,3.21) = 10.4+ i 3.21
Logical test = .TRUE. (variables that can hold
true or false)
Character vname = ‘anand’
‘123acd’
14
Data type/ variable declarations
Real :: temp
real :: press,wind,dir
Integer : : year,month
Double precision:: pres
real*8:: temp
character :: file*10, name1*30
Character*10 file1,name10
character(len=10) :: file
character(10) :: name
15
Data type/ variable declarations
contd….
e.g.
real variable c = 2.998E8 means 2.998 × 108
double precision variable h = 6.626D-34 means 6.626 × 10-34
• variable types can be changed within the program statements using
real( ) dble( ) int( )
16
Data type/ variable declarations
contd….
e.g.
implicit none ! At the beginning of the program
! all variables to be declared; none of the
! variables will be taken as integer or real by
! default
real:: a,b
integer:: i,j
a = 1.2
i=4
j = int(a) ! value of j will be 1
b = real(i) ! value of b will be 4.0
17
Parameter
Parameters are constants, defined in the beginning of the program
before any executable statements
Once defined, their value can not be changed in the rest of the program.
e.g.
real, parameter:: g=9.81655,pi=3.1415
integer,parameter:: m=365
18
Assignments / expressions/ arithmetic operations
e.g.
temp = 23.5
number = 5
y = height
Arithmetic Operators:
+ addition
- Subtraction
* Multiplication
/ Division
** power
e.g.
tempK = temp1+273.16
sum = sum + x
avtemp = (temp1 + temp2)/2
volume = (4.0*pi*radius**3.0)/3.0
19
Assignments / expressions/ arithmetic operations
Does a + b * c means a + (b * c) or (a + b) * c ?
The precedence of the common operators is:
**,
*, /
+, -
Parentheses are used to get around these precedence rules
a**(b+1) means a to the power (b+1), whereas
a**b+1 means (a to the power b) + 1
Solution of a quadratic equation
x = (-b+sqrt(b**2.0-4.0*a*c))/(2.0*a) 20
Sample program 1 – with errors
program atempavg
! To find the average of two temperature values in oC and convert it into
Kelvin
implicit none
real parameter:: cfactor = 273.16
real: atemp1,atemp2,avtemp,atempK
atemp1 = 27.5643
atemp2 = 26.3216
avtemp = atemp1+atemp2/2.0
atempK = avtemp+cfactor
write(*,*)avtemp, atempK
stop
end program atempaverage
! Errors ????????
21
Sample program 1 - corrected
program atempavg
! To find the average of two temperature values in oC and convert it into
! Kelvin
implicit none
Real, parameter:: cfactor = 273.16
real:: atemp1,atemp2,avtemp,atempK
atemp1 = 27.5643
atemp2 = 26.3216
avtemp = (atemp1+atemp2)/2.0
atempK = avtemp+cfactor
write(*,*)avtemp,atempK
stop
end program atempavg
22
Arithmetic operations should be coded carefully
integer:: i,j
real:: a,b,c
i=2 ; j=3
a=i ! Whats the value of a ?
b = i/j ! Value of b ?
c = real(i)/j ! Value of c ?
23
Logical Expressions
A logical expression is made up of :
Variables
Constants
Logical operators
.LT. or < less than
.GT. or > greater than
.LE. or <= less than or equal to
.GE. or >= greater than or equal to
.EQ. or = = equal to
.NE. or /= not equal to
24
Logical Expressions
contd…..
Usage e.g.
(a < 10)
(temp1 /= temp2)
Logical expressions can be combined using logical test operators :
.AND.
.NOT.
.OR.
e.g.
((a < = 3) .or. (b >= 5))
25
Conditional statements
Different types of conditional statements
IF [ condition(s) ] [ statement]
………………………………………………
IF [ condition(s) ] THEN
[ statement(s) ]
END IF
……………………………………………….
IF [ condition(s) ] THEN
[ statement(s) ]
ELSE IF [ condition(s) ] THEN
[ statement(s) ]
ELSE
[ statement(s) ]
END IF 26
Conditional Statements
e.g.
IF (temp <= 30)count = count+1
………………………………………………….
IF (temp < 40)THEN
count1 = count1+1
ELSE
count2 = count2+1
END IF
……………………………………………………
IF ( day = = ‘Monday’ ) THEN
iday1 = iday1+1
ELSE IF ( test = = .TRUE. ) THEN
a = a + 25
ELSE IF ( ( x >4 ) .AND. ( y < 3 ) ) THEN
c = a+b
ELSE
c = 0.0
27
END IF
Use of Logical Variables
Logical variables take on the value of .true. or .false.
e.g.
logical :: a, b
a = x >= 0.0
b = y /= 1.0
if (a .and. b) then…
The above program segment is same as:
If((x>=0.0).and.(y/=1.0))then
28
Array Variables
An array variable is a variable capable of storing a set of data of the
same type in a single data structure.
Arrays can be of any data type and can be declared with other
variables in the beginning of the program.
Declaration of array variable:
REAL:: abcd(100)
INTEGER:: loop(20),data(500)
CHARACTER:: names(10)*20
double precision:: x(100)
29
Array variable
contd….
• Each array member is addressable by an array subscript
e.g. for REAL:: x(10), subscripts range from 1 to 10. i.e. x(1),
x(2)… x(10)
• The array subscript may be a constant value, variable or expression
x(1) = SIN(y)
x(loop) = 4.0*x(loop-1)
• Array subscripts can also vary from a negative integer to a positive
integer or from 0 to a positive integer
REAL,dimension(-10:10):: x
INTEGER,dimension(0:200):: datax
30
Array variable contd…
Arrays can be multi-dimensional
REAL:: pres(5,2) (can also be declared as:
real,dimension(5,2)::pres)
i.e. pres(1,1), pres(1,2), pres(2,1)…
real:: wind(3,3,5)
i.e. wind(1,1,1), wind(1,1,2),…..
Declaring a variable of unknown size
real, dimension(:), allocatable :: x
…… and in the program body, the array size can be allocated as:
i = 10
allocate(x(i))
….. and after finishing the purpose:
deallocate(x) 31
Array Arithmetics
real :: a(10), b(10), c(10)
do i = 1,10
c(i) = a(i) + b(i)
enddo
! The above arithmetic operation can be performed with the simple statement
c = a+b
Other usages:
a=b ! copies the array b into a
a=b+1 ! a(i) = b(i)+1 for i=1,2,3
a(m:n) ! refers to the array locations of variable ‘a’ starting at m and
! ending at n
a(m:n:im) ! Array locations starting at ‘m’ and ending at ‘n’, incremented by ‘im’.
32
Array Arithmetic
x(1:5) = y(2:6) copies elements 2 to 6 of y into elements 1 to 5 of x
z(1:3) = y(1:5:2) copies elements 1,3,5 of y into elements 1,2,3 of z
abb(2,:) = z copies the vector z into the second row of variable abb
33
Where…. elsewhere
Real::a(10)
…….
…….
where (a > 0.0)
a = log(a)
elsewhere
a = 0.0
end where
34
Iterations: DO loop
Loops allow blocks of commands/statements to be repeated
DO <index> = <start>,<stop> [,<step>]
<statement(s)>
END DO
index : integer variable
start: initial value of index
stop: final value of index
step: increment, optional; assumed as 1 if not specified
e.g. calculate average of 100 temperature values
do i = 1, 100
sum = sum+temp(i)
end do
ave = sum/100.0
35
DO Loop
more examples…
do i = 1, 100
if(i>50.and.i <=75)then
sum = sum+temp(i)
icount = icount+1 ! What this program segment will do ?
end if
end do
ave = sum/icount
do i = 1,100,2
avg = avg+ i ! What about this ?
cnt = cnt+1
end do
avg = avg/cnt
36
Do loop …… more
• DO loop with numeric label
do 1000 j = 0,10,2
<statement(s)>
1000 continue
• Implied DO loop
read(1,*)(value(i1),i1 =1,10)
(e.g datafile: 10.21,11.50,20.45,18.21,….,14.25)
• Double DO loop
do i = 1,10
do j = 1,20,2
a = a + i*j ! What will be the value of ‘a’ after the
end do ! execution of this do loop ??
37
end do
DO WHILE Loop
INTEGER:: test
test = 15
DO WHILE (test > 12)
test=test-1
x1 = x1+1
END DO
38
Go To
To jump from one statement line to other
breaking the sequence
e.g. go to 201
a = a+1
201 b = a
! Can also be 201 continue
39
Input/ Output Statements
Free Format
read (*, *) temp
read(*,*)temp,pres
write(*,*) temp,pres
The first “ * ” in the bracket means we will read from/ write to
standard devices like keyboard/ screen
second “ * ” means the default reading/ writing formats
40
Input/output contd….
read*,temp
write*,temp
print*,temp
write(*,*)’enter temp data’
write(*,*)’average temperature =‘,avgT
41
Format Specifiers
Format specifiers for variables consist of a letter and digit(s)
A : Character variable.
I : Integer variable.
F : Real variable.
E : Real variable, exponential form.
e.g. A10, I2, F12.4, E12.4
“ / ” and “ X “ are used for new line and space
42
Formatted read/write
read(*, ’(i4, f5.2)’ ) ihour,temp
! ………..or………….
read(*,10) ihour,temp
10 format(i4,f5.2)
e.g.: For the above formatted read, values should be entered as
113029.42 (ihour = 1130, temp = 29.42)
i4 = 4 integer locations, i2 = 2 interger locations
F5.2 = real value of total 5 locations including sign, of which 2 decimal
places and one for the decimal point.
! to read a name of 10 character long
read(*,’(A10)’)name
43
Formatted read/write contd…
write(*,20)iyear,imonth,iday,temp,press,wspeed,wdir
20 format(1x,i4,1x,i2,1x,i2,f6.2,1x,f7.2,1x,f5.2,1x,f6.2)
……… same as…………..
20 format( 3 (1x,i4), 4(1x,f12.4))
e.g. Actual data to be entered as: 2002,11,30,27.44,1013.31,09.45,350 .11
write(*, ’(f6.2)’ ) ’Todays temperature = ‘,temp
44
Read/write from/to a file
open (15, file=‘input.dat’,status=‘old’)
open (16, file=‘output.dat’,status=‘new’)
! …………. status=‘unknown’
do i = 1,100
read (15, *)idate(i),temp(i)
end do
…………………
……………………..
write (16, *) mintemp,maxtemp,avtemp
close (15) ! closing file 15
close (16)
45
Formatted read/write from/to a file
do i = 1,100
read (15, 150)idate(i),temp(i)
enddo
……………….
……………………..
write (16, 160) mintemp,maxtemp,avtemp
150 format(i4,1x,f6.2)
160 format(3(f6.2,1x))
close (15)
close (16)
46
More on opening input/output files…….
OPEN(unit=20,file=‘indata.dat’,status=‘unknown’)
! can also be written as
character ifile*12
ifile=‘indata.dat’
OPEN(unit=20,FILE=ifile, STATUS=‘old’)
! If input/ output file is in a different folder,
ifile=‘c:/data/temp/indata.dat’
47
Sample program 2
(with lots of mistakes)
Program rainanalysis
This program is to find the average of daily rainfall exceeding 2.5 mm
implicit none
integer,parameter::m=30
real::rain(m),count
Integer::i,sumrain
open(1,file=‘rainfall.dat’)
m = 30
do i = 1,m
read(1,2)rainf(i)
end do
do i = 1,30
If(rain(i)>2.5mm)then
sumrain = sumrain+rain
count = count+1
end if
sum rain = sumrain/30.0
Write(*,*)count,sumrain
close(1)
end program rain analysis
48
DATA Statement
REAL a,b,c
INTEGER d(5),lots(100)
CHARACTER single(5)*1
DATA a /1.5/
DATA b,c /2.5,5.6/
DATA d /1,2,3,4,5/
DATA lots /100*0.0/
DATA single /5*’Y’/
49
Intrinsic/ built-in Functions
Intrinsic functions are mostly mathematical functions used in computations
Parameters (can be constants/numbers, variables, expressions) are passed to
functions and functions return a single value of certain data type.
y=ATAN(1.0) y=SIN((pi*degrees)/180.0)
y=LOG10(x) y=x+3.0*LOG(x)
y=EXP(2.4) y=INT(2.3)
50
Intrinsic function
SIN(x) ASIN(x)
COS(x) ACOS(x)
TAN(x) ATAN2(x)
SINH(x) EXP(x)
COSH(x) LOG(x)
TANH(x) LOG10(X)
SQRT(x) MOD(X,Y)
ABS(x)
MAX(x1,x2…) Max value of x1, x2, …
Usage e.g.:
a = 10.0*sin(x)+log10(x+y)+sqrt(22.5)
51
Intrinsic functions contd….
matmul(a,b) performs matrix multiplication on 2 array
arguments with compatible size and
rank
maxval(a) returns maximum element of an integer or
real array
minval(a) returns minimum element of an integer or
real array
product(a) returns the product of the elements of an
array
sum(a) returns the sum of the elements of an array
52
Sub-program: Functions and subroutines
Used to make the program more structured
Code to implement a particular calculation can be written just once,
but used many times
Function subprogram
• Returns a single value through the name of the function
(just like intrinsic functions)
• Function is defined after the ‘contains’ statement in the
main program
• Helpful to structure the program
53
Function contd….
e.g.
Program abcd
Real::rad,degrees,value
----------
-----------
degrees = 90.0
value = RAD( degrees )
------------
contains
FUNCTION rad(degrees) ! Can also be wriiten as:
REAL:: degrees,pi,temp,rad
pi=4.0*ATAN(1.0) FUNCTION rad(xy)
REAL:: xy,pi,temp,rad
temp=(pi*degrees)/180.0 pi=4.0*ATAN(1.0)
rad=temp rad=(pi*xy)/180.0
end function rad end function rad
end program abcd end program abcd
54
Subroutines
• Another method for “structuring” the program.
• Subroutines may change none, one or many of the arguments passed
to them.
• The CALL statement is used to call subroutines, which is then
defined after the ‘contains’ statement in the main program.
• Argument data types must match in the main program and
subroutine
CALL product(xx,yy,i1,22.4) !..... (in the main prog)
SUBROUTINE product(xx,yy,i1,za)…. (after contains
statement in the main
program)
55
Subroutine …….contd
e.g.
program tempaverage
real:: temp(100),avg
------------------------
CALL average(temp,avg)
--------------------
contains
SUBROUTINE average(temp,avg)
real:: temp(100),avg
do k = 1,100
avg = avg + temp(k)
enddo
avg = avg/100.
end subroutine average
end program tempaverage
56
Subroutine another example……….
program averageall
real:: temp(100),press(100),avgT,avgP
------------------------
CALL average(temp,avgT)
CALL average(press,avgP)
--------------------
contains
SUBROUTINE average(x1,avg1)
real:: x1(100),avg1
avg1 = 0.0
do k = 1,100
avg1 = avg1 + x1(k)
enddo
avg1 = avg1/100.
end subroutine average
end program averageall 57