0% found this document useful (0 votes)
143 views

Complete Fortran Lecture Notes

Uploaded by

Manozer Mensah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
143 views

Complete Fortran Lecture Notes

Uploaded by

Manozer Mensah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 250

MET 253:

Programming with Fortran I

eoasare
September, 2016

Email : fortranclass@gmail.com

I don’t know what the programming language of the year 2000


will look like, but I know it will be called FORTRAN. V.1.5
Charles Anthony Richard Hoare (1982)
Course Content

Part1 : Introduction to Linux

The Linus operating system


Basic Linus terminal commands
Introduction to Emacs and other editors

Part2 : Fortran 90 Basics

Program Structure
Variables and Statements
Data types and Numerical Operators
Character Processing
Unformatted and formatted output
Course Content
Part3 : Fortran 90 Array

Basic features of Fortran 90 array


Initialising and assigning arrays
Whole and section array assignment

Part4 : Loops and Branches (Control Structures)

IF statement and IF construct


DO and While construct
SELECT CASE

Part4 : Fortran Subprogram

Functions
Subroutine
Module
Recommended Textbooks
1 Fortran 90/95 for Scientists and Engineers
by: Stephen J. Chapman

2 Introduction to Programming with Fortran


by: Ian D. Chivers and Jane Sleightholme

3 Fortran 90 Handbook
by: Jeanne C. Adams, Walter S. Brainerd, Jeanne T. Martin, Brian
T. Smith, Jerrold L. Wagener

4 Introduction to Fortran 90 for Scientists and Engineers


by: Brian Hahn

5 Fortran 90/95 Explained second edition


by: Michael Metcalf

6 Many other Fortran 90 books and also other materials from


google
Format of the class

Lectures

1 1.5 hours of lecture

2 0.5 hour of assignment presentations

3 1 hour of programming practice

Grading

Assignments, class presentations and midsem (30%)

Final examination (70%)


Advantages of Linux

Why should I choose Linux?

Best price/performance ratio


Reliable
User friendly
Serve different purpose from your mobile phone to a supercomputer
Scientific software is developed mostly in Linux today
Basic Introduction to Linux

1 In Linux folder is called directory

2 Directories are organized into a single monolithic tree. The top-most


directory is called the root directory.

3 When you open konsole/terminal, you will find yourself working in


your personal directory called home directory. Linux home
directories are are located under the directory /home

4 A pathname is a string that identifies the location of a particular


file, the sequences of directories to move through to find it.

5 The pathname /home/username/try.txt indicates a file named


try.txt in the home directory of the user username.

6 Remember the case sensitiveness of what you type on the konsole


(terminal)
Basic Introduction to Linux
When users log in, they are placed in a personal directory called their
home directory (/home/username). By convention, Linux home
directories are located under the directory /home. Your home directory is
also symbolized by ∼.
Instead of typing /home/username, you could just type ∼. Typing less by
using well known symbols saves you time
The current directory (or working directory) is denoted by a period (.) is
the directory you are “in” at any given time. If you give a pathname with
no leading slash, then the location of the file is worked out relative to the
working directory. Such pathnames are called relative pathnames; you’ll
use them much more often than full pathnames.
The parent directory is represented by a double period (..).The double
period can be used at any place in a path to move towards the root of
the directory tree, effectively canceling the previously mentioned directory
in a path. However, it makes the most sense to use the double period as
the first directory in a path.
Rules for naming files and directories

1 Files are organized into directories, or listings of files. Like all other
files in Linux, a directory is also treated as a file. Each directory can,
in turn, contain subdirectories, creating hierarchical listings.

2 The filenames can be up to 255 characters (or bytes) long

3 Files and directories names are case sensitive

4 Upper and lower case letters, numbers, dot (.), underscore ( )


symbol

5 Blank space are allowed but it is very difficult use those files

6 The symbol / (root directory) is reserved as separator between files


and directories and therefore should not be used
Cont. rule for naming files
Linux has no concept of a “file extension“ like some other operating
systems. The contents and/or purpose of a file is determined by other
means. Although Unix-like operating system dont use file extensions to
determine the contents/purpose of files, some application programs do
(like Fortran).
It is common to name files using the syntax below

<filenamebody>.< extension>

where the extension (usually no more than three or four letters) indicates
the file type. For example
.txt : text file
.html (or .htm) : INTERNET page file
.tex : document in the TeX (or LaTeX)
.ps : postscript file
Meaning of some commands
1 ’mkdir’ for creating a directory folder
eg. mkdir dirname this creates directory called dirname
2 ’cp’ for copy file or directory to another file for directory
eg. cp filename1 filename2 both files will be in the directory
for directory cp -r dirname1 dirname2
You can copy files/directories into a different directory

3 ’mv’ for rename file and directory


eg. mv filename1 filename2 rename filename1 as filename2
mv dirname1 dirname2 rename dirname1 as direname2
4 ’ls’ for directory list show the content of the directory

5 ’cd <dirname>’ for changing current directory to <dirname> cd


direname where direname is a directory inside the current working
directory
Cont. meaning of some commands
1 ’rm <filename>’ for delete (remove) file <filename>
!! USE WITH CAUTION !!
Better use ’rm -i <filename>’, type y for yes and n for no then enter

2 ’rm -r <dirname>’ for removing directory <dirname>


!! USE WITH CAUTION !!
Better use ’rm -r -i <dirname>’
3 ’pwd’ for showing the current path or current working directory
4 ’cat<filename>’ for listing the contents of a file. You can also ’less’
or ’more’ for listing
5 ’df’ for displaying the amount of available disk space
6 ’date’ for displaying the date and time on your system
7 ’Exit’ for exiting the konsole (terminal)
8 ’man’ to the manual page (of command)
Introduction to Emacs
Emacs provides a mode that makes it easy to edit Fortran code,
providing context sensitive indentation and layout.
Notation
It is very important to become familiar with these notations used in all
standard Emacs documents.
1 C-x = press the Ctrl key, hold it and press x.
2 M-x = press the Alt key, hold it and press x.
3 C-M-x = press and hold Ctrl key, then add Alt and then x.
4 RET = Enter key
5 SPC = the Space bar
6 ESC = the escape key
7 C-x-C-f = press Ctrl and keep it down while you press x first and
then f.
Note - at times Shift key is used in combination with Ctrl or Alt keys
Basic Emacs commands

C-x C-f - opens a file and shows it in the current buffer


C-x C-s - saves the buffer
C-x C-w - writes the buffer in a different file (Save as)
C-x C-c - quites emacs
C-a - jump to the beginning of the current line
C-e - jump to the end of the current line
M-f - move forward one word
M-b - move backward one word
M-< - move to the top of the buffer
M-> - move to the bottom of the buffer
C-d - delete the character at the cursor
C-k - delete the text from the position of cursor to the end of the current
line
M-d - delete forward until the end of the next word
M-Del - delete backwards until the beginning of a previous word
Basic Emacs commands conti

C-r - search backward (searching towards the top of the current buffer)
C-s - search forward (searching towards the end of the current buffer)
M-% - replace forward
C-SPC - mark the beginning of the text for copying/moving/deleting
C-w - cut the text from buffer to the clipboard
C-y - paste the text from the clipboard at the position of the cursor
C- - undo the last change
ESC ESC ESC - cancel the last operation
Saving Document
After executing C-x C-s command, the minibuffer at the bottom of your
screen ask for the file name, type the name and the extension. To replace
an existing file, press the TAB key during writing the file name and
Emacs automatically adds the rest of the name.
Course Objective

The objectives of this course include the following:

The first part will involve the students learning the basic principles
of Fortran programming
To be able to understand the basics of any Fortran code
Students will learn how to write their own simple programs
Learn how to manipulate data input/output files
To use Fortran to solve climate/meterology related problems.

Good News
No previous programming experience is required.
What is computer program?

A computer program is a set of instructions for the computer to execute


sequentially. The particular set of rules for coding the instructions to a
computer is called a programming language.
Steps involve -
Initially the program source code is written in plain text by the
programmer using text editor (eg emacs, gedit, kwrite, etc) and
then saved. Fortran 90 files typically have extension (.f90).
This file is then compiled (by existing application, called the
compiler) to translate the plain text of the source code to binary
code for the processor. The executable files have extension (.exe).
The binary executable file is then run to get the output/results in
plain text.
Fortran Background

Fortran (FORmula TRANslator) was the first high-level programming


language proposed in 1953 by John Backus and the first program was run
in April 1957. Fortran is use mainly within the scientific community for
solving problems that has a significant arithmetic content.

Versions/Standards
Fortran 66 - first standard
Fortran 77 - character handling
Fortran 90 - array and modular programming
Fortran 95 - functional programming
Fortran 2003 - object-oriented and generic programming
Fortran 2008 - concurrent programming.
Fortran 2015 - is under development
Fortran Program Structure without subprograms

Everything in square brackets [ ] is


optional. However, it is good
[PROGRAM name ] programming practice to put the
name of the program in both header
[IMPLICIT NONE] and END statements.

[Declaration statements]
name (program name) must:
[Execution statements]
Begin with a letter
END [ PROGRAM name] (upper/lower case)
It contains letters, digits 0-9,
and underscore characters
Maximum of 31 characters.
names are case-insensitive.
Fortran Program Structure with internal subprograms

[PROGRAM name ] The subprogram can be a function,


subroutine and module.
[IMPLICIT NONE] The structure of a subprogram is
similar to that of the main program
[Declaration statements]
but with some keywords.
[Execution statements]

[CONTAINS] The subprogram(s)/procedures


appear in the program after the
[Subprogram-part] keyword contains.
Contains marks the end of the main
END [ PROGRAM name]
code of the program and indicates
the start of the definition of the
subprogram(s)
Fortran Program Structure with external subprograms

Subprogram(s)/procedures can
[PROGRAM name ] appears after the end of the main
program.
[IMPLICIT NONE]
Subprograms that are not contained
[Declaration statements] in the main program are called
external subprograms/procedures.
[Execution statements]

END [ PROGRAM name] External procedures/subprograms


can be in the same file as the main
[Subprogram-part] program or in a different file.
If in different file, they are compiled
independently of other procedures
and program units.
Features of Fortran Program 1/14

IMPLICIT NONE

This is very important non-executable fortran statement used to


disable the default typing provisions of Fortran.

When this statement is used in the program, any variable that does
not appear in an explicit type declaration statement is considered
error.

If omitted, fortran uses implicit declaration where a variable is


considered INTEGER if the first letter of its names lies in the range
of I - N and will be declared as a REAL variable otherwise.

IMPLICIT NONE should appear after the Program name


statement and before any type declaration statement.

IMPLICIT NONE will be use in this course to write safe programs.


Features of Fortran Program 3/14

Fortran Data type

A Fortran 90 data type may be an INTEGER, REAL, LOGICAL,


COMPLEX, and CHARACTER or STRING

An integer data type is a string of digits with an optional sign: 12,


-20, 0, +2333

A real data type has two forms decimal and exponential

The decimal form consist of string of digits with exactly one decimal
point. e.g 1.4, -13.5, +0.04, 33333.5

In the exponential form, start with an integer/real. followed by a


E/e, followed by an integer (i.e., the exponent). e.g 15E3 (15x103 ),
equivalent to 15e3 (15x103 )
Features of Fortran Program 4/14

Fortran Data type cont.

A logical data type is either .TRUE. or .FALSE.


Note that the periods (dots) surrounding TRUE and FALSE are
required!

A complex data type consists of two numeric constants separated


by comma and enclosed in parentheses. e.g (1.,0.) equivalent to 1
+ 0i and (0.7071,0.7071) equivalent to 0.7071 + 0.7071i

A character/string data type is a string of characters enclosed


between two double or two single quotes. e.g “abc” produces abc
The length of a character string is the number of characters
between the quotes including blank space.
Features of Fortran Program 5/14

Variables

A variable is an entity that is used to store a value, comparable to


the use of variable in algebra.
Must be between 1 and 31 characters in length. The first character
must be a letter and the remaining if any, may be letters, digits or
underscore.
The variables are case insensitive and therefore NAME and naMe
are the same.
Fortran 90 does not have reserved words and therefore Fortran
keywords can be used as variable names but avoid it.
The type of a variable is declared in the declaration statement.
Variable can be given a value during the execution of the program -
by assignment or by a READ statement.
Features of Fortran Program 6/14

Valid Variables names


x
my variable
Results17
STUDENT
my20 NaMe

Invalid Variables names


1x first character is a number
my$variable ’$’ is not letter, numeral or underscore
my really really long variable name more than 31 characters
Features of Fortran Program 7/14

Declaration of Variables

Fortran 90 uses the following for variable declaration, where


type-specifier is one of the fortran following keywords: INTEGER,
REAL, LOGICAL, COMPLEX and CHARACTER, and list is a
sequence of identifier separated by commas.
type-specifier :: list
Example:
INTEGER :: x, total ! x and total holds integer data type
REAL :: avg, z ! avg and z holds real data type
CHARACTER variables require the string length
The keyword CHARACTER must be followed by the length attribute
(LEN = integer value), where integer value is an integer value that
holds the length of the string.
Features of Fortran Program 8/14

Declaration of Variables cont

If the length of the string is 1 then the CHARACTER can be


declared without the LEN attribute.
EXAMPLE:
CHARACTER (LEN = 20) :: answer, name
Variables answer and name can hold up to 20 characters.
CHARACTER :: phy
Variable phy can hold only ONE character ( i.e length is 1)
There is another way of declaring CHARACTER length when
PARAMETER attribute is used. The compiler assumed the length
from the parameter and you do not have to state the length. The
symbol * is used for the length of character.
EXAMPLE ::
CHARACTER (LEN = *), PARAMETER :: dir = “my program”
Features of Fortran Program 9/14

Variables Attributes
Various Fortran attributes may be specified for variables in their
type-declaration statement.
The PARAMETER attribute dictates that a constant is being
defined. A variable declared with this attribute may not have its
value changed within the program unit.
The PARAMETER attribute is used after the data type keyword,
followed by variable name followed by an = and then value for the
variable.
EXAMPLE :
REAL, PARAMETER :: PI = 3.143
! PI will be equal to 3.14 throughout the program
INTEGER, PARAMETER :: TOTAL = 10
! TOTAL will be equal to 10 throughout the program
Features of Fortran Program 10/14

Variable Initialization

A variable receives its value with


Initialization: It is done once before the program runs.
Assignment: It is done when the program executes an assignment
statement.
Input: It is done with a READ statement.
The variable can be initialized in their type-declaration statement
EXAMPLE:
REAL :: x = 0.05
! x can be assigned different value within the program
INTEGER :: gravity = 10
! gravity can be assigned different value within the program
It can also be initialized before execution statement.
Features of Fortran Program 11/14

Standard input/output (I/O) statement

Fortran uses the READ * as standard input statement to read data


into variable from the keyboard.
Read statement is of the form: READ *, input list
If READ * has n variables in its list, there must be n Fortran
declared constants.
Each entered constant must have the type of the corresponding
variable.
Data items are separated by spaces and may spread into multiple
lines.
The asterisk * can be change to specify the data format. The
format is of the form READ “(input format)”, input list
Features of Fortran Program 12/14

Standard input/output (I/O) statement cont

Fortran uses the PRINT * as standard output statement to display


data output on the screen.

Print statement is of the form: PRINT *, output list

To print undeclared string in your program put the string statement


in between double quotes. e.g PRINT*,“This is fortran class”
displays This is fortran class

PRINT*, without output list produces a blank line

A formatted PRINT statement is of the form: PRINT


“(output format)”, output list
Features of Fortran Program 13/14

Program Comments

Comments start with a exclamation mark (!)


Everything following (!) will be ignored by the compiler
Always comment your code so you can understand it later and also
for others to understand when reading your code.
Example :
output = input1 + input2 ! sum the inputs
PROGRAM first program
! This program tries to illustrate some basic features of fortran
INTEGER :: x, y
Features of Fortran Program 14/14

Cases and Indentation

Except within character strings, Fortran is completely


case-insensitive.

Fortran keywords such as REAL, DO, END, IF and intrinsic


functions such as SIN, COS , TAN should be in “UPPER CASE“
letters and user created entities such as variable names should be in
lower case.

’Indentation’, this is essential for program readability. It is common


to indent a program’s content by 2 spaces from its header and END
statement, and also indent the statements contained within, for
example, Fortran keywords such as IF constructs or DO loops by a
similar amount.
Operators in Fortran 1/13
There are four types of operators in Fortran 90:
arithmetic, relational, logical and character.

Arithmetic Operator

Order of Precedence Operator Meaning


[1] ** Exponentiation operator
[2] / Division operator
[2] * Multiplicative operator
[3] + additive operator
[3] - Minus operator
Within the same level of precedence, evaluation will proceed from
left to right for all the operators with the exception of
exponentiation where evaluation proceeds from right to left.
Parentheses (...) can be used to change the default order of
precedence.
Data Type Conversions 2/13
If an operator has two operands of the same data type (single
mode) then the result has the same type.
- Operations involving only reals yield a type real result.
- Operations involving only integers yield a type integer result.
If the operands have different data types (mixed mode) then an
implicit type conversion is applied to one of them to bring it to the
type of the other. When integers and reals are mixed in arithmetic
operations the result is a real.
Exponentiation is an exception to the type conversion rule:
- when the exponent is an integer it does not have to be converted
to the type of the other operand and the result is evaluated as if by
repeated multiplication.
- But if the exponent has any other data type the calculation is
performed by implicit use of the LOG and EXP functions
-If the exponent has a negative value the result is simply the
reciprocal of the corresponding positive power.
Data Type Conversions - example 3/13

10.0 / 2.0 * 5.0 evaluates as (10.0 / 2.0) × 5.0 = 25.0


5.0 * 2.0 ** 3 evaluates as 5.0 × (2.03 ) = 40.0
A −3 will be worked out as 1 / (A × A × A)
Repeated exponentiation is the single exception to the left-to-right
rule for equal precedence:
C
A ** B ** C evaluates as AB
For non-integer powers (which includes whole-number powers if a
decimal point is used) the result will be worked out by using the fact
that
ab = (elna )b = eblna
A3.0 will be worked out as e3.0lnA
Integer Division 4/13
If one integer divides another in a subexpression then the results of the
subexpression will be an INTEGER.
In short, division of two integers produces an integer result by truncation
(towards zero).
Consider,
REAL :: a, b, c, d, e
a = 1999/1000
a is (about) 1.000. The integer expression 1999/1000 is evaluated and
then truncated towards zero to produce an integral value, 1.
d = 1999.0/1000
e = 1999/1000.0
d and e are (about) 1.999 because both RHS’s are evaluated to be real
numbers, in 1999.0/1000 and 1999/1000.0 the integers are promoted to
real numbers before the division.
The Assignment Statement 5/13

The assignment statement has a form of

variable = expression
where variable has been declared and therefore has a type
If the type of variable and expression are identical, the result is
saved to variable.

If the type of variable and expression are not identical, the result of
expression is converted to the type of variable.

If expression is REAL and variable is INTEGER, the result is


truncated.
Mixed Type Assignment 6/13

When the RHS expression of a mixed type assignment statement has


been evaluated it has a specific type, this type must then be converted to
fit in with the LHS.
For example,

1 INTEGER = REAL
The RHS is evaluated and then the value is truncated (all the
decimal places lopped off ) then assigned to the LHS.

2 REAL = INTEGER
The INTEGER is evaluated as REAL. The RHS expression is simply
stored (approximately) in the LHS.
Mixed Type Assignment - example 7/13

REAL :: a = 1.1, b = 0.1 ! A real declaration with assignment


INTEGER :: i, j, k ! An integer declaration

i = 3.9 ! assigning a constant to i


i will be 3, the value 3.9 is truncated to an integer
j = -0.9 ! assigning a constant to j
j will be 0, value -0.9 is truncated to an integer
k=a-b ! assigning a variable to value of an expression
k will be 1 or 0, the result of a- b would be close to 1.0 (it could be
1.0000001 or it could be 0.999999999), so, because of truncation, k
could contain either 0 or 1.
Operators in Fortran 8/13

Relational Operator

Relational operators are used to test the relationship between two


numeric operands for that specific operator.
Expression involving these operators will reduce to either ’.TRUE.’
or ’.FALSE.’.

Operator Meaning
< or .LT. Less than
> or .GT. Greater than
== or .EQ. Identically equal to
/ = or .NE. Not equal to
<= or .LE. Less than or equal to
>= or .GE. Greater than or equal to
Operators in Fortran 9/13

Logical Operator

Logical operators act on logical expressions to create a largest


logical expression.
Parentheses (...) can be used to change the default order of
precedence.
Logical operators and relational operators may be combined into
logical expressions using the following operators:
Order Operator Meaning
[1] .NOT. Negative the following operand
[2] .AND. .TRUE. if both operands are .TRUE.
[3] .OR. .TRUE. if at least one operand is .TRUE.
[4] .EQV. .TRUE. if both operands reduce to the same
[4] .NEQV. .TRUE. if both operands are different
Operators in Fortran - example 9/13
PROGRAM logic examp
IMPLICIT NONE
LOGICAL :: test, try, phy !declaring a logical variables
LOGICAL:: student=.TRUE. !declaring and initialise logical variable

INTEGER:: age=20 !integer declaration and initialisation


test = .NOT. (age==20) !negating the result of the expression
PRINT*, test !result is False
try = (student) .AND. (age==20) !using the AND operator
PRINT*, try !result is TRUE because both statements are true
phy = .NOT. (student) .OR. (age==20) !using the OR operator
PRINT*, phy !result is TRUE because one statement is true
END PROGRAM logic examp
Operators in Fortran 10/13

Character Operator

There is only one character operator, concatenation symboled //.


If strings A and B have lengths m and n, then concatenation A // B
is a string of length m+n
It is use to join two separate characters.

Example:
’Man’ // ’chester’ gives ’Manchester’
CHARACTER(LEN = 7) :: word 1 =“missing”
CHARACTER(LEN = 3) :: word 2 = “you”
CHARACTER(LEN = 10) :: ans
ans = word 1 // word 2 ! missingyou
Operators in Fortran 11/13

Character substrings

A consecutive portion of a string is a substring.


To use substrings, one may add an extent specifier to the
CHARACTER variable.
An extent specifier has the following form:
(integer exp1 : integer exp2)
The first and the second expressions indicates the start and end: (3
: 8) means 3 to 8.
If A = “abcdefg”, then A (3 : 5) means A’s substring from position
3 to position 5 (i.e., “cde”)
If the first extent specifier is missing, the substring start from the
first character, and if the second extent specifier is missing, the
substring ends at the last character.
Fortran Intrinsic Function 12/13
Function Meaning Data type
SQRT(x) square root of x Real
COS(x) cosine of x Real in radian
SIN(x) Sine of x Real in radian
TAN(x) Tangent of x Real in radian
ASIN(x) Sine inverse Real
ACOS(x) Cosine inverse Real
ATAN(x) Tangent inverse Real
EXP(x) ex Real
ALOG(x) loge (x) Real
ALOG10(x) log10 (x) Real
ABS(x) Absolute value of x Real, Integer
MAX(x1,x2 .... ) Maximum value of x vector Real, integer
MIN(x1,x2 ....) Minimum value of x vector Real, integer
MODULO(x, y) x modulo y Real, integer
MOD(x, y) remainder when x is divided by y Real
Data type Conversions 13/13

Function Meaning
INT(x) Truncate a real number to an integer
NINT(x) Round a real number to the nearest integer
REAL(x) Convert to real
CEILING(x) Nearest integer greater than or equal to x
FLOOR(x) Nearest integer less than or equal to x
CMPLX(x) Real to complex
FRACTION(x) Fractional part of real
Write and Run fortran program 1/3

Creating a fortran program

Either open a pre-existing source code or create it and save using


text editor and should have a name that ends in .f90.
A text editor is a type of program used for editing plain text files.
Examples of some text editors are (emacs, gvim, vi, gedit, kile,
xemacs etc)
On command line and inside your program directory, open the file by
typing:
emacs prog1.f90 where prog1 is the filename and emacs text editor
Emacs shows blank page since prog1 is a new file.
Write and Run fortran program 2/3

Compiling fortran program

The role of fortran compilers is to translate the plain text of the


source code to binary code for the processor.
Some free available compilers are (g95, gfortran, f95, etc )
During compilation the program is checked for syntax errors and, if
none are found, an executable file is created
The default name for the executable file will be a.out but you can
also specify a name with different extension.
In the same directory containing the program file type of one these
commands:
1. g95 -o prog1.exe prog1.f90 this produces executable file called
prog1.exe
2. g95 prog1.f90 this produces executable file called a.out
Write and Run fortran program 3/3
Please note that the above compilation syntax is applicable only when
the main program and subprograms/procedures are in the same file.
When we get to Fortran subprograms part of the course, we will use
different compilation syntax whe the subprogram and main program are
in different files.

Running fortran program

If compilation step is carried out successfully, then the executable


prog1.exe or a.out will appear when the files are listed with ls.
You can then run the program with the command ./prog1.exe or
./a.out
The ./ before the file name tells the computer that the executable
file is in the current directory.
Fortran 90 Control Structures 1/10

DO and DO WHILE loops

If a block of code is to to performed repeatedly it is put inside a DO loop


There are two basic types of DO loops:

Deterministic DO loops
The number of times the section is repeated is stated explicitly.

Non-deterministic DO loops
The number of repetitions is not stated in advance.
Fortran 90 Control Structures 2/10

DO loops - ( Deterministic DO loop)

The number of times the section is repeated is stated explicitly.


The syntax is as follows:
DO control-var = initial, final [ , step ]
< Statements >
END DO
control-var is an integer variable, initial, final and step are integer
or integer expression; however, step cannot be zero.
If step is omitted, its default value is 1
statements are executable statement of the DO LOOP
The control-var runs from initial in increments of step until it
reaches the value final and then the loop terminates.
If step is positive, then DO counts up; if step is negative, then DO
counts down
Fortran 90 Control Structures 3/10

DO loops - ( Deterministic DO loop)

If step is positive
The control-var receives the value of initial

If the value of the control-var is less than or equal to the value of


final, the statements part is executed. Then, the value of step is
added to control-var, and goes back and compares the value of
control-var and final.

If the value of control-var is greater than the value of final, the


DO-loop completes and the statement following END DO is
executed.
Fortran 90 Control Structures 4/10

DO loops - ( Deterministic DO loop)

If step is negative
The control-var receives the value of initial

If the value of control-var is greater than or equal to the value of


final, the statements part is executed. Then, the value of step is
added to control-var, goes back and compares the value of
control-var and final.

If the value of control-var is less than the value of final, the


DO-loop completes and the statement following END DO is
executed.

Count down loop always requires a step. That is the loop will not
work without a specified step
Deterministic Do loop Example 5/10

Sovle the function f(x) numerically in the domain 0 ≤ x ≤ 10




 0 x <4
0.1(x − 4) 4≤x ≤5

f (x) =

 20 − 0.1(x − 4) 5≤x ≤6
0 x >6

What do we need ?
If construct
Deterministic Do loop
Dimension attribute
PROGRAM func x0
! this program solve a function with 11 data point
IMPLICIT NONE
INTEGER, PARAMETER :: i start = 0, i end = 10
INTEGER :: icount
REAL, DIMENSION (i start : i end) :: f xy !array declaration
DO icount = i start, i end !do loop with step =1
IF ( icount < 4 ) THEN !1st condition
f xy (icount) = 0
ELSE IF ( icount >= 4 .AND. icount <= 5) THEN !2nd condition
f xy ( icount ) = 0.1 * (icount - 4)
ELSE IF ( icount >= 5 .AND. icount <= 6 ) THEN !3rd condition
f xy( icount ) = 20 - 0.1 * ( icount - 4 )
ELSE !last condition
f xy ( icount ) = 0
END IF
PRINT*, icount, f xy ( icount )
END DO
END PROGRAM func x0
Fortran 90 Control Structures 6/10

DO loops - ( Non-deterministic DO loop)

The number of repetitions is not stated in advance. The enclosed section


is repeated until some condition is or is not met. Note that this loop can
be infinite without the condition.
This may be done in two alternative ways:
The first requires a logical reason for stopping looping
The second requires a logical reason for cycling looping.

Non-deterministic DO-loops are particularly good for:


1 summing power series (looping stops when the absolute value of a
term is less than some given tolerance)
2 single-point iteration (looping stops when the change is less than a
given tolerance)
Fortran 90 Control Structures 7/10

Non-deterministic Do loop - ( with Exit condition)

In these, the loop is terminated by a conditional exit statement, ie. an IF


statement or logical IF which executes exit action.
The syntax is as follows:

DO
< statement body >
IF (< logical-expression > ) EXIT
< statement body >
END DO

The loop continues until some logical expression evaluates as TRUE.


Then it jumps out of the loop and continues with the code after the
loop. In this form a TRUE result tells you when to stop looping.
Fortran 90 Control Structures 8/10

Non-deterministic Do loop - ( with Cycle condition)

The CYCLE statement starts the next iteration (ie. executing


statements again).
The syntax is as follows:

DO
< statement body >
IF (< logical-expression > ) CYCLE
< statement body >
END DO

The action of the IF statement if it is TRUE is to cause the program to


cycle immediately to the next iteration of the loop, skipping any
remaining statements in the current cycle.
Fortran 90 Control Structures 9/10

Non-deterministic Do loop - ( Exit and Cycle Example)

PROGRAM exit cycle exam


IMPLICIT NONE
INTEGER :: i
INTEGER, PARAMETER :: istart = 1, iend = 5, ilimit=3
DO i = istart, iend
IF (i == ilimit) EXIT ! IF statement condition to exit loop
PRINT*, i
END DO
END PROGRAM exit cycle exam
Please re-run the program by replacing the EXIT with CYCLE and exam
the difference in the output.
Non-deterministic Do loop Example 10/10
Pi ( π ) can be estimated from the series

X (−1)n ∞
pi 1 1 1 1
= 1 − + − + − ...
4 3 5 7 9 2n + 1
n=0

We could re-write the series as a sum of all positive terms:



X 8
π= an where an =
(4n + 1)(4n + 3)
n=0

Write a fortran program to evaluate pi from the series until an term is


less than a given threshold (torelance).
What do we need?
condition to exit the loop
set the torelance
increments of the loop
PROGRAM cal pi
!to calculate pi from series
IMPLICIT NONE
REAL, PARAMETER :: eps = 0.001 ! torelance value
INTEGER :: ncount ! loop counter
REAL :: pival ! store the pi value
REAL :: series val ! store the series value
ncount = 0 ! assign initial counter
pival = 0.0 ! assign initial pi value
DO
series val = 8.0 / ( ( 4 * ncount + 1 ) * ( 4 * ncount + 3 ) )
pival = pival + series val ! update the pi value
ncount = ncount + 1 !update the counter
IF ( series val < eps ) EXIT ! condition to exit loop
END DO
PRINT 10, ’# of steps = ’, ncount, ’ ,value of pi = ’, pival
10 FORMAT (a,I2,2x,a,F6.4) !print format
END PROGRAM cal pi
Example program 1/5

Product of two variables


PROGRAM firstprogram ! start of program
!This program finds product of two real variables
IMPLICIT NONE ! All variables used must be declared
REAL :: x,y,z ! Declare variables
x = 5.1 ! Assign x
y = -17.2 ! Assign y
z = x*y ! Assign (x*y) to z
PRINT*,’The product of x and y is’, z ! Print out z
END PROGRAM firstprogram ! end of program
Example program 2/5

Radius and perimeter of cycle

PROGRAM maths ! start of program


!This program finds the radius and perimeter of a cycle
IMPLICIT NONE ! All variables used must be declared
REAL, PARAMETER :: pi = 3.143 ! parameter declaration
REAL :: rad, area, peri ! Declare variables to be used
PRINT*, ’Enter the radius of the cycle’
READ*, rad
area = pi*rad**2 ! assign area
peri = 2*pi*rad ! assign peri
PRINT*,’The area of a cycle of radius’, rad ’is’, area
PRINT*, ! print blank line
PRINT*,’The perimeter of a cycle of radius’, rad ’is’, peri
END PROGRAM maths ! end of program
Formatted Output 1/7
Lots of input/output ( I/O) related features in Fortran - not all will
be considered for now
Fortran PRINT statements do formatting by preceding the variables
to be printed with (format descriptor).
Format descriptor are put in parentheses.
Symbols used with format descriptor are shown in the table below:
Symbol meaning
c Column number
d Number of digits to right of the decimal places of real
m Minimum number of digits to be displayed
n Number of spaces to skip
r Repeat count - the number of times to use a descriptor
w Field width - the number of characters to use including
leading (+ or -) signs as well as decimal point

They are applied to both output and input


Formatted Output 2/7

Integer Output - The I Descriptor

Integer values are right justified in their fields. This means that integers
are printed out so that the last digit of the integer occupies the
rightmost column of the field.
The I descriptor has the general form
rIw or rIw.m
where r, w, and m have the meanings given in the above table.
Example
INTEGER :: x = 12345
PRINT’(I5)’, x !integer with field width = 5, 12345 is the output
If the integer is too large to fit into the field in which it is to be printed,
then the field is filled with asterisk.
PRINT’(I3)’, x !integer with field width = 3, **** is the output
Formatted Output 3/7

Real Output - The F Descriptor


Real values are printed right justified within the fields. If the specified
field width is less than the number to be printed, the number is rounded
off before it is displayed. On the other hand, if the specified width is
more than the number to printed, extra zeros are appended to the right
of the decimal point.
The I descriptor has the general form
rFw.d
where r, w, and d have the meanings given in the table.
Example:
REAL :: x = 1234.678
PRINT’(F8.3)’, x !output = 1234.678
PRINT’(F8.2)’, x !output = 1234.68 why difference in position?
PRINT’(F8.4)’, x !output = *****, why?
Formatted Output 4/7

Real Output - The E Descriptor

Real data can be printed in exponential form using the E descriptor. Real
values displayed by E descriptor are normalized to a range between 0.1
and 1.0. For example 4.096 x 103 will appears as 0.4096E+04 using the
E descriptor
The E descriptor has the general form
rEw.d
The width w of E descriptor must satisfied the expression
w ≥ d +6 where d has the same meaning given in the table
Example:
REAL :: res = 23456
PRINT’(E11.5)’, res !output = 0.23456E+05
PRINT’(E13.5)’, res !output = 0.23456E+05, check the position
PRINT’(E8.2)’, res !output = 0.23E+05
Formatted Output 5/7

True Scientific Notation - The ES Descriptor

The ES descriptor is exactly the same as the E descriptor, except that


the number to be printed is displayed with mantissa in the range between
1 and 10
The ES has the form:
rESw.d
The formula for the minimum width of an ES descriptor is the same as
that of E but the leading zero in E descriptor is replaced by a significant
digit in ES.
Example:
REAL :: ans = 2345.6
PRINT’(ES11.5)’, ans ! output = 2.34560E+03
PRINT’(ES8.2)’, ans ! output = 2.35E+03
PRINT’(ES7.2)’, ans ! output = *****, why?
Formatted Output 6/7

Character Output - The A Descriptor

A descriptor has the form:


rA or rAw
where r and w have the meanings given in the table
The rA descriptor displays character data with the same width as the
number of characters being displayed whiles the rAw displays character
data with width w. The rA are printed right justified and if the width of
the field is shorter than the length of character variables only first w
characters of the variable are printed.
Example:
CHARACTER(LEN = 7) :: dept = ’physics’
PRINT’(A7)’, dept ! output = physics
PRINT’(A)’, dept ! output = physics
PRINT’(A3)’, dept ! output = phy
PRINT’(A3)’, dept(5:7) ! output = ics ,you should know why?
Formatted Output 7/7

Horizontal Spacing - The X Descriptor

The X Descriptor is used to add one or more blanks space between two
values on the output line.
The X Descriptor has the form of a positive integer followed by X:
nX
where n is the number of blanks to insert.
Example:
CHARACTER(LEN = 7) :: dept = ’physics’
REAL :: ans = 2345.6
PRINT’(ES8.2,A7)’, ans, dept ! output = 2.35E+03physics
PRINT’(ES8.2,2X,A7)’, ans, dept ! output = 2.35E+03 physics
where 2X create two blank spaces between ES8.2 and A7 outputs
What is computer program?

A computer program is a set of instructions for the computer to execute


sequentially. The particular set of rules for coding the instructions to a
computer is called a programming language.
Steps involve -
Initially the program source code is written in plain text by the
programmer using text editor (eg emacs, gedit, kwrite, etc) and
then saved. Fortran 90 files typically have extension (.f90).
This file is then compiled (by existing application, called the
compiler) to translate the plain text of the source code to binary
code for the processor. The executable files have extension (.exe).
The binary executable file is then run to get the output/results in
plain text.
Fortran Background

Fortran (FORmula TRANslator) was the first high-level programming


language proposed in 1953 by John Backus and the first program was run
in April 1957. Fortran is use mainly within the scientific community for
solving problems that has a significant arithmetic content.

Versions/Standards
Fortran 66 - first standard
Fortran 77 - character handling
Fortran 90 - array and modular programming
Fortran 95 - functional programming
Fortran 2003 - object-oriented and generic programming
Fortran 2008 - concurrent programming.
Fortran 2015 - is under development
Fortran Program Structure without subprograms

Everything in square brackets [ ] is


optional. However, it is good
[PROGRAM name ] programming practice to put the
name of the program in both header
[IMPLICIT NONE] and END statements.

[Declaration statements]
name (program name) must:
[Execution statements]
Begin with a letter
END [ PROGRAM name] (upper/lower case)
It contains letters, digits 0-9,
and underscore characters
Maximum of 31 characters.
names are case-insensitive.
Fortran Program Structure with internal subprograms

[PROGRAM name ] The subprogram can be a function,


subroutine and module.
[IMPLICIT NONE] The structure of a subprogram is
similar to that of the main program
[Declaration statements]
but with some keywords.
[Execution statements]

[CONTAINS] The subprogram(s)/procedures


appear in the program after the
[Subprogram-part] keyword contains.
Contains marks the end of the main
END [ PROGRAM name]
code of the program and indicates
the start of the definition of the
subprogram(s)
Fortran Program Structure with external subprograms

Subprogram(s)/procedures can
[PROGRAM name ] appears after the end of the main
program.
[IMPLICIT NONE]
Subprograms that are not contained
[Declaration statements] in the main program are called
external subprograms/procedures.
[Execution statements]

END [ PROGRAM name] External procedures/subprograms


can be in the same file as the main
[Subprogram-part] program or in a different file.
If in different file, they are compiled
independently of other procedures
and program units.
Features of Fortran Program 1/14

IMPLICIT NONE

This is very important non-executable fortran statement used to


disable the default typing provisions of Fortran.

When this statement is used in the program, any variable that does
not appear in an explicit type declaration statement is considered
error.

If omitted, fortran uses implicit declaration where a variable is


considered INTEGER if the first letter of its names lies in the range
of I - N and will be declared as a REAL variable otherwise.

IMPLICIT NONE should appear after the Program name


statement and before any type declaration statement.

IMPLICIT NONE will be use in this course to write safe programs.


Features of Fortran Program 3/14

Fortran Data type

A Fortran 90 data type may be an INTEGER, REAL, LOGICAL,


COMPLEX, and CHARACTER or STRING

An integer data type is a string of digits with an optional sign: 12,


-20, 0, +2333

A real data type has two forms decimal and exponential

The decimal form consist of string of digits with exactly one decimal
point. e.g 1.4, -13.5, +0.04, 33333.5

In the exponential form, start with an integer/real. followed by a


E/e, followed by an integer (i.e., the exponent). e.g 15E3 (15x103 ),
equivalent to 15e3 (15x103 )
Features of Fortran Program 4/14

Fortran Data type cont.

A logical data type is either .TRUE. or .FALSE.


Note that the periods (dots) surrounding TRUE and FALSE are
required!

A complex data type consists of two numeric constants separated


by comma and enclosed in parentheses. e.g (1.,0.) equivalent to 1
+ 0i and (0.7071,0.7071) equivalent to 0.7071 + 0.7071i

A character/string data type is a string of characters enclosed


between two double or two single quotes. e.g “abc” produces abc
The length of a character string is the number of characters
between the quotes including blank space.
Features of Fortran Program 5/14

Variables

A variable is an entity that is used to store a value, comparable to


the use of variable in algebra.
Must be between 1 and 31 characters in length. The first character
must be a letter and the remaining if any, may be letters, digits or
underscore.
The variables are case insensitive and therefore NAME and naMe
are the same.
Fortran 90 does not have reserved words and therefore Fortran
keywords can be used as variable names but avoid it.
The type of a variable is declared in the declaration statement.
Variable can be given a value during the execution of the program -
by assignment or by a READ statement.
Features of Fortran Program 6/14

Valid Variables names


x
my variable
Results17
STUDENT
my20 NaMe

Invalid Variables names


1x first character is a number
my$variable ’$’ is not letter, numeral or underscore
my really really long variable name more than 31 characters
Features of Fortran Program 7/14

Declaration of Variables

Fortran 90 uses the following for variable declaration, where


type-specifier is one of the fortran following keywords: INTEGER,
REAL, LOGICAL, COMPLEX and CHARACTER, and list is a
sequence of identifier separated by commas.
type-specifier :: list
Example:
INTEGER :: x, total ! x and total holds integer data type
REAL :: avg, z ! avg and z holds real data type
CHARACTER variables require the string length
The keyword CHARACTER must be followed by the length attribute
(LEN = integer value), where integer value is an integer value that
holds the length of the string.
Features of Fortran Program 8/14

Declaration of Variables cont

If the length of the string is 1 then the CHARACTER can be


declared without the LEN attribute.
EXAMPLE:
CHARACTER (LEN = 20) :: answer, name
Variables answer and name can hold up to 20 characters.
CHARACTER :: phy
Variable phy can hold only ONE character ( i.e length is 1)
There is another way of declaring CHARACTER length when
PARAMETER attribute is used. The compiler assumed the length
from the parameter and you do not have to state the length. The
symbol * is used for the length of character.
EXAMPLE ::
CHARACTER (LEN = *), PARAMETER :: dir = “my program”
Features of Fortran Program 9/14

Variables Attributes
Various Fortran attributes may be specified for variables in their
type-declaration statement.
The PARAMETER attribute dictates that a constant is being
defined. A variable declared with this attribute may not have its
value changed within the program unit.
The PARAMETER attribute is used after the data type keyword,
followed by variable name followed by an = and then value for the
variable.
EXAMPLE :
REAL, PARAMETER :: PI = 3.143
! PI will be equal to 3.14 throughout the program
INTEGER, PARAMETER :: TOTAL = 10
! TOTAL will be equal to 10 throughout the program
Features of Fortran Program 10/14

Variable Initialization

A variable receives its value with


Initialization: It is done once before the program runs.
Assignment: It is done when the program executes an assignment
statement.
Input: It is done with a READ statement.
The variable can be initialized in their type-declaration statement
EXAMPLE:
REAL :: x = 0.05
! x can be assigned different value within the program
INTEGER :: gravity = 10
! gravity can be assigned different value within the program
It can also be initialized before execution statement.
Features of Fortran Program 11/14

Standard input/output (I/O) statement

Fortran uses the READ * as standard input statement to read data


into variable from the keyboard.
Read statement is of the form: READ *, input list
If READ * has n variables in its list, there must be n Fortran
declared constants.
Each entered constant must have the type of the corresponding
variable.
Data items are separated by spaces and may spread into multiple
lines.
The asterisk * can be change to specify the data format. The
format is of the form READ “(input format)”, input list
Features of Fortran Program 12/14

Standard input/output (I/O) statement cont

Fortran uses the PRINT * as standard output statement to display


data output on the screen.

Print statement is of the form: PRINT *, output list

To print undeclared string in your program put the string statement


in between double quotes. e.g PRINT*,“This is fortran class”
displays This is fortran class

PRINT*, without output list produces a blank line

A formatted PRINT statement is of the form: PRINT


“(output format)”, output list
Features of Fortran Program 13/14

Program Comments

Comments start with a exclamation mark (!)


Everything following (!) will be ignored by the compiler
Always comment your code so you can understand it later and also
for others to understand when reading your code.
Example :
output = input1 + input2 ! sum the inputs
PROGRAM first program
! This program tries to illustrate some basic features of fortran
INTEGER :: x, y
Features of Fortran Program 14/14

Cases and Indentation

Except within character strings, Fortran is completely


case-insensitive.

Fortran keywords such as REAL, DO, END, IF and intrinsic


functions such as SIN, COS , TAN should be in “UPPER CASE“
letters and user created entities such as variable names should be in
lower case.

’Indentation’, this is essential for program readability. It is common


to indent a program’s content by 2 spaces from its header and END
statement, and also indent the statements contained within, for
example, Fortran keywords such as IF constructs or DO loops by a
similar amount.
Operators in Fortran 1/13
There are four types of operators in Fortran 90:
arithmetic, relational, logical and character.

Arithmetic Operator

Order of Precedence Operator Meaning


[1] ** Exponentiation operator
[2] / Division operator
[2] * Multiplicative operator
[3] + additive operator
[3] - Minus operator
Within the same level of precedence, evaluation will proceed from
left to right for all the operators with the exception of
exponentiation where evaluation proceeds from right to left.
Parentheses (...) can be used to change the default order of
precedence.
Data Type Conversions 2/13
If an operator has two operands of the same data type (single
mode) then the result has the same type.
- Operations involving only reals yield a type real result.
- Operations involving only integers yield a type integer result.
If the operands have different data types (mixed mode) then an
implicit type conversion is applied to one of them to bring it to the
type of the other. When integers and reals are mixed in arithmetic
operations the result is a real.
Exponentiation is an exception to the type conversion rule:
- when the exponent is an integer it does not have to be converted
to the type of the other operand and the result is evaluated as if by
repeated multiplication.
- But if the exponent has any other data type the calculation is
performed by implicit use of the LOG and EXP functions
-If the exponent has a negative value the result is simply the
reciprocal of the corresponding positive power.
Data Type Conversions - example 3/13

10.0 / 2.0 * 5.0 evaluates as (10.0 / 2.0) × 5.0 = 25.0


5.0 * 2.0 ** 3 evaluates as 5.0 × (2.03 ) = 40.0
A −3 will be worked out as 1 / (A × A × A)
Repeated exponentiation is the single exception to the left-to-right
rule for equal precedence:
C
A ** B ** C evaluates as AB
For non-integer powers (which includes whole-number powers if a
decimal point is used) the result will be worked out by using the fact
that
ab = (elna )b = eblna
A3.0 will be worked out as e3.0lnA
Integer Division 4/13
If one integer divides another in a subexpression then the results of the
subexpression will be an INTEGER.
In short, division of two integers produces an integer result by truncation
(towards zero).
Consider,
REAL :: a, b, c, d, e
a = 1999/1000
a is (about) 1.000. The integer expression 1999/1000 is evaluated and
then truncated towards zero to produce an integral value, 1.
d = 1999.0/1000
e = 1999/1000.0
d and e are (about) 1.999 because both RHS’s are evaluated to be real
numbers, in 1999.0/1000 and 1999/1000.0 the integers are promoted to
real numbers before the division.
The Assignment Statement 5/13

The assignment statement has a form of

variable = expression
where variable has been declared and therefore has a type
If the type of variable and expression are identical, the result is
saved to variable.

If the type of variable and expression are not identical, the result of
expression is converted to the type of variable.

If expression is REAL and variable is INTEGER, the result is


truncated.
Mixed Type Assignment 6/13

When the RHS expression of a mixed type assignment statement has


been evaluated it has a specific type, this type must then be converted to
fit in with the LHS.
For example,

1 INTEGER = REAL
The RHS is evaluated and then the value is truncated (all the
decimal places lopped off ) then assigned to the LHS.

2 REAL = INTEGER
The INTEGER is evaluated as REAL. The RHS expression is simply
stored (approximately) in the LHS.
Mixed Type Assignment - example 7/13

REAL :: a = 1.1, b = 0.1 ! A real declaration with assignment


INTEGER :: i, j, k ! An integer declaration

i = 3.9 ! assigning a constant to i


i will be 3, the value 3.9 is truncated to an integer
j = -0.9 ! assigning a constant to j
j will be 0, value -0.9 is truncated to an integer
k=a-b ! assigning a variable to value of an expression
k will be 1 or 0, the result of a- b would be close to 1.0 (it could be
1.0000001 or it could be 0.999999999), so, because of truncation, k
could contain either 0 or 1.
Operators in Fortran 8/13

Relational Operator

Relational operators are used to test the relationship between two


numeric operands for that specific operator.
Expression involving these operators will reduce to either ’.TRUE.’
or ’.FALSE.’.

Operator Meaning
< or .LT. Less than
> or .GT. Greater than
== or .EQ. Identically equal to
/ = or .NE. Not equal to
<= or .LE. Less than or equal to
>= or .GE. Greater than or equal to
Operators in Fortran 9/13

Logical Operator

Logical operators act on logical expressions to create a largest


logical expression.
Parentheses (...) can be used to change the default order of
precedence.
Logical operators and relational operators may be combined into
logical expressions using the following operators:
Order Operator Meaning
[1] .NOT. Negative the following operand
[2] .AND. .TRUE. if both operands are .TRUE.
[3] .OR. .TRUE. if at least one operand is .TRUE.
[4] .EQV. .TRUE. if both operands reduce to the same
[4] .NEQV. .TRUE. if both operands are different
Operators in Fortran - example 9/13
PROGRAM logic examp
IMPLICIT NONE
LOGICAL :: test, try, phy !declaring a logical variables
LOGICAL:: student=.TRUE. !declaring and initialise logical variable

INTEGER:: age=20 !integer declaration and initialisation


test = .NOT. (age==20) !negating the result of the expression
PRINT*, test !result is False
try = (student) .AND. (age==20) !using the AND operator
PRINT*, try !result is TRUE because both statements are true
phy = .NOT. (student) .OR. (age==20) !using the OR operator
PRINT*, phy !result is TRUE because one statement is true
END PROGRAM logic examp
Operators in Fortran 10/13

Character Operator

There is only one character operator, concatenation symboled //.


If strings A and B have lengths m and n, then concatenation A // B
is a string of length m+n
It is use to join two separate characters.

Example:
’Man’ // ’chester’ gives ’Manchester’
CHARACTER(LEN = 7) :: word 1 =“missing”
CHARACTER(LEN = 3) :: word 2 = “you”
CHARACTER(LEN = 10) :: ans
ans = word 1 // word 2 ! missingyou
Operators in Fortran 11/13

Character substrings

A consecutive portion of a string is a substring.


To use substrings, one may add an extent specifier to the
CHARACTER variable.
An extent specifier has the following form:
(integer exp1 : integer exp2)
The first and the second expressions indicates the start and end: (3
: 8) means 3 to 8.
If A = “abcdefg”, then A (3 : 5) means A’s substring from position
3 to position 5 (i.e., “cde”)
If the first extent specifier is missing, the substring start from the
first character, and if the second extent specifier is missing, the
substring ends at the last character.
Fortran Intrinsic Function 12/13
Function Meaning Data type
SQRT(x) square root of x Real
COS(x) cosine of x Real in radian
SIN(x) Sine of x Real in radian
TAN(x) Tangent of x Real in radian
ASIN(x) Sine inverse Real
ACOS(x) Cosine inverse Real
ATAN(x) Tangent inverse Real
EXP(x) ex Real
ALOG(x) loge (x) Real
ALOG10(x) log10 (x) Real
ABS(x) Absolute value of x Real, Integer
MAX(x1,x2 .... ) Maximum value of x vector Real, integer
MIN(x1,x2 ....) Minimum value of x vector Real, integer
MODULO(x, y) x modulo y Real, integer
MOD(x, y) remainder when x is divided by y Real
Data type Conversions 13/13

Function Meaning
INT(x) Truncate a real number to an integer
NINT(x) Round a real number to the nearest integer
REAL(x) Convert to real
CEILING(x) Nearest integer greater than or equal to x
FLOOR(x) Nearest integer less than or equal to x
CMPLX(x) Real to complex
FRACTION(x) Fractional part of real
Write and Run fortran program 1/3

Creating a fortran program

Either open a pre-existing source code or create it and save using


text editor and should have a name that ends in .f90.
A text editor is a type of program used for editing plain text files.
Examples of some text editors are (emacs, gvim, vi, gedit, kile,
xemacs etc)
On command line and inside your program directory, open the file by
typing:
emacs prog1.f90 where prog1 is the filename and emacs text editor
Emacs shows blank page since prog1 is a new file.
Write and Run fortran program 2/3

Compiling fortran program

The role of fortran compilers is to translate the plain text of the


source code to binary code for the processor.
Some free available compilers are (g95, gfortran, f95, etc )
During compilation the program is checked for syntax errors and, if
none are found, an executable file is created
The default name for the executable file will be a.out but you can
also specify a name with different extension.
In the same directory containing the program file type of one these
commands:
1. g95 -o prog1.exe prog1.f90 this produces executable file called
prog1.exe
2. g95 prog1.f90 this produces executable file called a.out
Write and Run fortran program 3/3
Please note that the above compilation syntax is applicable only when
the main program and subprograms/procedures are in the same file.
When we get to Fortran subprograms part of the course, we will use
different compilation syntax whe the subprogram and main program are
in different files.

Running fortran program

If compilation step is carried out successfully, then the executable


prog1.exe or a.out will appear when the files are listed with ls.
You can then run the program with the command ./prog1.exe or
./a.out
The ./ before the file name tells the computer that the executable
file is in the current directory.
Fortran 90 Control Structures 1/8

Nested DO Loops

If one loop is completely inside another one, the two loops are called
nested loops.
For each control-var of the outer loop, the entire inner loop has to be
completed before next iteration in the outer loop.
When Fortran compiler encounters an END DO statement, it associates
that with the innermost currently open loop.
Therefore, the first END DO statement closes the inner loop and the last
the outermost loop.
Fortran 90 Control Structures 2/8
PROGRAM nested
IMPLICIT NONE
INTEGER :: icount, jcount ! counters declaration
DO icount = 1, 3, 1 !the outer loop statement
DO jcount = 1, 5, 1 !inner loop statement
PRINT*, icount, ” * ”, jcount, ” = ”, icount * jcount
END DO !end do for inner loop
END DO !end do for outer loop
END PROGRAM nested
for each icount step, jcount will run from 1 to 5 before icount will
update.
for the outer loop, the inner loop serve as the executable statement.
for the inner loop, PRINT statement is the executable statement.
Fortran 90 Control Structures 2/8

Nested DO Loops -Example


PROGRAM nest exam
IMPLICIT NONE
INTEGER :: x, y
INTEGER, PARAMETER :: xstart = 1, xend = 2
INTEGER, PARAMETER :: ystart=1, yend=4
REAL :: results
PRINT*,’ enter the value for x and y’
DO x = xstart, xend
DO y = ystart, yend
results = (x*1.0)/(y*1.0) ! 1.0 convert integer to real why?
PRINT 10, x, y, results
10 FORMAT (2(1x,I2),1x,F4.2) ! print format why 2?
END DO
END DO
END PROGRAM nest exam
Fortran 90 Control Structures 3/8

DO WHILE construct
The DO WHILE loop always exits at the top of the loop construct as
this is where the test takes place.
The syntax is as follows:

DO WHILE (< logical-expression >)


< body statements >
END DO

The body statements in the DO WHILE block are executed for as long as
the result of the logical-expression remains TRUE.
The DO range is executed repeatedly as follows.
Prior to each execution of the DO range, the logical expression is
evaluated. If it is true, the range is executed; if it is false, the DO
WHILE construct terminates.
DO WHILE - example 4/8

PROGRAM do while eg
IMPLICIT NONE
INTEGER :: i
REAL :: sum
i=0 ! i initialization
sum = 0.0 ! sum initialization
DO WHILE ( i < 5 ) ! condition for the loop
i = i +1 ! i counter increment
sum = sum + i ! summing over i
PRINT 20, i, sum ! print each step
END DO
PRINT 20, i, sum ! print only final step
20 FORMAT (I2, 2x, F5.2) ! print format
END PROGRAM do while eg
Fortran 90 Control Structures 5/8

SELECT CASE Construct


The SELECT CASE statement chooses which operations to perform,
depending on the set of outcomes (selector) of an expression that can be
integer, character or logical, but not real.
The general form is:

SELECT CASE (expression)


CASE (case selector 1)
< statements 1 >
CASE (case selector 2)
< statements 2 >
CASE DEFAULT
< statements default >
END SELECT
Fortran 90 Control Structures 6/8

SELECT CASE Construct


If the expression is in the range of values included in case selector 1,
then < statements 1 > is executed
then move to the next case selector to execute statements in that block
if its expression is true.
The CASE DEFAULT (optional) is used whenever the value of the
expression is outside of all the case selector.
The SELECT CASE construct is alternative to an
IF-ELSE IF - END IF construct.
SELECT CASE Construct - example 7/8
PROGRAM mycase
INTEGER :: month
PRINT*, ”enter the month number”
READ*, month
SELECT CASE(month)
CASE(1,2,12)
PRINT*,”DJF”
CASE(3,4,5)
PRINT*,”MAM”
CASE(6,7,8)
PRINT*,”JJA”
CASE(9,10,11)
PRINT*,”SON”
CASE DEFAULT
PRINT*,”Illegal month number”, month
END SELECT
END PROGRAM mycase
SELECT CASE Construct - example 7/8
PROGRAM case eg
IMPLICIT NONE
REAL, PARAMETER :: pi = 3.143
REAL :: area, radius, length, breadth
INTEGER :: figure
INTEGER, PARAMETER :: fstart =1, fend = 4
PRINT*, ’Enter the radius, length and the breadth of the figure’
READ*, radius, length, breadth
DO figure = fstart,fend
SELECT CASE (figure)
CASE (1) ! cycle calculation
area = pi *radius **2
PRINT 10, ’area of a cycle is’, area
CASE (2) ! square calculation
area = length * length
PRINT 10, ’area of a square is’, area
SELECT CASE Construct - example - conti 8/8

CASE (3) ! rectangle calculation


area = length * breadth
PRINT 10, ’area of a rectangle is’, area
CASE DEFAULT ! undefined figures
PRINT 10, ’other solids’
10 FORMAT (a, 2X, F6.2) ! output format
END SELECT
END DO

END PROGRAM case eg


Debugging Fortran Programs 1

Programs seldoms run corrrectly the first time, even for experienced
programmers. Errors in programs are known as bugs, the process of
locating and eliminating them is known as debugging.
Four types of errors are found in Fortran programs:
Compilation errors

Run-time errors

Logical errors

Rounding errors
Debugging Fortran Programs 2
Compilation Error
Compilation errors are errors in syntax and construction, like spelling
mistakes or wrong punctuation that are picked up by the compiler during
compilation, the process whereby your program is translated into
machine code. They are the most frequent type of error. The compiler
prints a messages, which may or may not be helpful, when it encounters
such an error.

Run-time Error
If a program compiles successfully, it will run. Errors occuring at this
stage are called run-time errors, and are invariably fatal, i.e. the program
“crashes” or abort during execution. A run-time error occurs when an
illegal mathematical operation is attempted during program execution
(for example attempting to divide by 0).
Debugging Fortran Programs 3

Logical Error
These are errors in the actual algorithm you are using to solve a problem,
and are the most difficult to find; the program runs, but gives the wrong
answer! It’s even worse if you don’t realize the answers are wrong.

Rounding Error
At times a program will give numerical answers to a problem which
appear inexplicably different from what we know to be the correct
mathematical solution. This can be due to rounding error which results
from the finite precision available on the computer
Assignment
Write a fortran program to evaluate exponential function using DO
WHILE construct

x
X xn x2 x3
e = =1+x + + + ...... for all x
n! 2! 3!
n=0

Every succeeding term is just the previous term multiplied by x/n. At


some point the term x/n becomes very small, so that it is not sensibly
different from zero, and successive terms add little to the value. The
function therefore repeats the loop until x/n is smaller than the
tolerance. The number of evaluations is not known beforehand, since this
is dependent on x:
What you need?
Set the tolerance to decide which term to stop
Set initial values
Update term, count, compare term value with tolerance
Example 1

Write a program which will assigned in two real numbers x and y and will
print out the product z.

Steps

Declare 3 real variables

Assign values to 2 of the variables

Write the formula for the product and assign the results to the 3
variable

Print the output of the 3rd variable to the screen


Example 1 - sample solution

Product of two variables


PROGRAM firstprogram ! start of program
!This program finds product of two real variables
IMPLICIT NONE ! All variables used must be declared
REAL :: x,y,z ! Declare variables
x = 5.1 ! Assign x
y = -17.2 ! Assign y
z = x*y ! Assign (x*y) to z
PRINT*,’The product of x and y is’, z ! Print out z
END PROGRAM firstprogram ! end of program
Example 2

Write a program which will read in the radius of cycle and the program will
compute the area and the perimeter
Step
Declare 3 variables for the - radius, area and perimeter
Declare pi using the parameter attribute hope you remember?
Use PRINT statement to prompt the user to enter the value for the radius,
e.g - PRINT*, ’enter the value of the radius of the cycle’
Use READ statement to assign the radius
Assign the value of the area using the formula π × radius 2
Remember how to write pi and exponentiation in fortran

Assign the value of the perimeter using the formula 2 × π × radius


Use PRINT statement to display the value of the area on the screen
Use PRINT statement to display the value of the perimeter on the screen
Example 2 - sample solution

Radius and perimeter of cycle

PROGRAM maths ! start of program


!This program finds the radius and perimeter of a cycle
IMPLICIT NONE ! All variables used must be declared
REAL, PARAMETER :: pi = 3.143 ! parameter declaration
REAL :: rad, area, peri ! Declare variables to be used
PRINT*, ’Enter the radius of the cycle’
READ*, rad
area = pi*rad**2 ! assign area using area formular
peri = 2*pi*rad ! assign peri using perimeter formular
PRINT*,’The area of a cycle of radius’, rad ’is’, area
PRINT*, ! print blank line
PRINT*,’The perimeter of a cycle of radius’, rad ’is’, peri
END PROGRAM maths ! end of program
Assignment
Write a program which evaluates the vapour pressure using the Clausius
Clapeyron Equation given by
  
Lv 1 1
es = eso exp −
Rv To T
Assuming the following constant
To = 273 K
eso = 6.11 hPa
Lv = 2.50 × 106 Jkg −1
Rv = 461.5 Jkg −1 K −1
The program should read the temperature (T) from the keyboard
The program should print the results es to the screen

Please each group should submit their program file to the email below
Subject of the mail - Assignment 1
Body of the mail - group members name and their index numbers
Email : fortranclass@gmail.com

Submission deadline: thursday (10/11/2016) midday


MET 254:
Programming with Fortran II

eoasare
January, 2017

Email : fortranclass@gmail.com

Computers are good at following instructions,


but not at reading your mind. V.1.5
Donald Knuth (1938)
Programming with Fortran II (MET 254) eoasare
Course content
Outline

Part 1 : Fortran subprograms

Function
Subroutine
Module

Part 2 : Fortran Array

Array terminology and referencing


Array declaration and syntax
Array construction and expression
Dynamical allocation of array
Programming with Fortran II (MET 254) eoasare
Course content
Outline

Part 3 : Fortran input/output

Open/close statements
Read and write Statements
Read data with/without header
Reading table as array
Formatted and unformatted files

Part 4 : Practical session using meteorological data

Manipulation of in situ data


Estimation of basic meteorological indices
Brief introduction to gnuplot
Programming with Fortran II (MET 254) eoasare
Some Recommended Textbooks

1 Fortran 90/95 for Scientists and Engineers


by: Stephen J. Chapman

2 Introduction to Programming with Fortran


by: Ian D. Chivers and Jane Sleightholme

3 Fortran 90 Handbook
by: Jeanne C. Adams, Walter S. Brainerd, Jeanne T. Martin,
Brian T. Smith, Jerrold L. Wagener

4 Introduction to Fortran 90 for Scientists and Engineers


by: Brian Hahn

5 Fortran 90/95 Explained second edition


by: Michael Metcalf

6 Many other Fortran 90 books and also other materials


from google
Course obectives
At the end of this part you will:

understand any Fortran code and modify it to suit your need

be able to write your own simple programs from scratch

be able to use Fortran to manipulate data

know how to read external dataset and write your your output
into external files

be able to use Fortran to solve climate/meterology related


problems
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran Program Units

A fortran program can be built up from a collection of


program units
There are four types of program unit in the Fortran
1 Main program
2 Functions
3 Subroutines
4 Modules
Each program must contain one (and only one) main program
A subprogram or procedure (functions and subroutines) are
computations that can be “called” (invoked) from the main
program
Relevant functions and subroutines can be put together into a
module.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran Program Units

Fortran 90 has two types of subprograms, functions and


subroutines.
Subprograms are independent blocks of Fortran which perform
a specific task.
They may be written and compiled separately, and are joined
to a main program when the program is linked.
One main advantage of subprograms is that they may be
written and tested as isolated units to ensure that they
operate correctly.
Another advantage of subprograms is that they are portable,
i.e it can be use in later programs whenever you need it.
Functions and subroutines may be internal (i.e. contained
within and only accessible to one particular program unit) or
external (and accessible to all).
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran Program Units

Note that there is significant difference between external and


internal subprogram
External subprograms may themselves contain internal
subprograms (which will only be accessible to the host
external subprogram); internal subprograms may not contain
internal subprograms.
Subprogram starts with the keyword (function or subroutine)
and ends with (end function or end subroutine) and the
function name or subroutine name; this is quite like the syntax
we have already met introducing the program itself.
External subprogram that resides in a separate file from the
main program must be compiled separately.
However, external subprograms that resides in the same file as
the main program are compiled together with the main
program using the compilation syntax of the main program.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran Program Units

compiling main program with external program

If the main program and subprogram(s) are in the same file


then the compilation syntax is the same as before.
However, if the subprogram(s) are in different file(s) then the
compilation syntax is as follows:
gfortran - o m progname.exe m progname.f90 sub progname.f90
where:
gfortran - is the compiler in this case gfortran
m progname - is the main program name
sub progname.f90 - is the subprogram name
In this case the subprogram is save in file named
sub progname.f90
Additional subprograms can be added after sub progname.f90
We run the m progname.exe executable file to get output for
our program
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Functions

Function Statement 1

Function returns a single computed result via the function


name.
A Fortran function, or function subprogram has the following
syntax:
type FUNCTION function-name (arg1, arg2, . . ., argn)
IMPLICIT NONE
[ declaration part ]
[ execution part ]
END FUNCTION function-name
type is a Fortran 90 type (e.g., INTEGER, REAL, LOGICAL,
etc).
function-name is a Fortran 90 identifier.
arg1, ...., argn are dummy arguments
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Functions

Functions syntax 2

Function receives inputs from the outside world via its dummy
arguments, does some computations, and returns the result
with the function-name
The function-name must appear in one or more assignment
statement like this:
function-name = expression
where the result of expression is saved to the name of the
function
Note that function-name cannot appear in the right-hand
side of any expression except recursive function.
The variables listed in the argument list in the function
definition are called dummy variables. Their names do not
have to match the names used in parts of the program where
the function is called.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Functions

Function Statement
Note that a function without dummy arguments is declared with
empty parentheses ( ). The syntax is as:
type FUNCTION function-name ( )
IMPLICIT NONE
[ declaration part ]
[ execution part ]
END FUNCTION function-name
If the function is written in the same file as the main program,
it must appear after the end of the main program.
The arguments used when the function is actually invoked are
called actual arguments. They may be variables (e.g. x, y),
constants (e.g. 1.0, 2.0) or expressions (e.g. 3.0 + x, 2.0/y ),
but they must be of the same type, number and at the same
positions as the dummy arguments.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Functions

Functions declaration in the main program

A function may be declared to be external to the main program


with EXTERNAL attribute.
When a name in an argument list is declared to be external, this
tells the compiler that a separately function is passed in the
argument list instead of a variable.
Syntax for EXTERNAL attribute declaration is:
type, EXTERNAL :: func name1, func name2, .....
Example
REAL, EXTERNAL :: my function
It appears with other specification statements, after any use or
implicit statements and before any executable statements.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Functions - internal function example

PROGRAM func examp


IMPLICIT NONE
REAL :: res, x, y,z
PRINT*,’enter the three points’
READ*, x,y,z
res = myfunc(x,y,z) ! call function
PRINT*,’results is’,res
CONTAINS ! keyword to introduce internal subprogram
! type FUNCTION Fname (arguments)
REAL FUNCTION myfunc (xp,yp,zp) !function statement
IMPLICIT NONE
REAL :: xp,yp,zp ! dummy argument declaration
myfunc = SQRT(xp**2 + yp**2 + zp**2) ! function formula
END FUNCTION
END PROGRAM func examp
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Functions - external function example

Compute area of triangle based on Heron’s formula

The formula for the semiperimeter of a triangle with side lengths a,


b, and c is

a+b+c
s=
2
The area of a triangle can also be calculated from its
semiperimeter and side lengths using Heron’s formula
p
area = s(s − a)(s − b)(s − c)
The area is coded as function
see next page for the program
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Functions - external function example

PROGRAM func eg
! compute area of triangle using Heron’s Formula
IMPLICIT NONE
REAL, EXTERNAL :: tri area ! declare external function
REAL :: side1,side2,side3,ans
PRINT*,’Enter the sides of the triangle’
READ*, side1, side2, side3 ! input triangle sides
ans = tri area(side1,side2,side3) ! calculate area using function
PRINT’(A, F6.3)’,’Area of triangle is = ’, ans
END PROGRAM func eg

REAL FUNCTION tri area(a, b, c) ! Function first line


IMPLICIT NONE
REAL :: a,b,c ! Dummy variables
REAL :: h per ! local variable
h per = (a+b+c)/REAL(2) !why real(2)
tri area = SQRT(h per*(h per-a)*(h per-b)*(h per-c))
PRINT* ,’half of triangle perimeter = ’ , h per
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Recursive Functions

Recursive Functions

A function that calls itself (directly or indirectly) is called a


recursive function.
If the function is recursive then the FUNCTION keyword in
the top line must be proceeded by the keyword RECURSIVE.
With recursive function, Fortran allows specification of two
different names for invoking the function recursively and for
returning its results.
The actual name of the function is used whenever we want
the function to invoke itself, and a special dummy argument is
used whenever we want to specify a value to return.
The name of this special dummy argument is specified in a
RESULT cluase in the FUNCTION statement.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Recursive Functions

Recursive Function Statement


Its declaration syntax is of the form:
RECURSIVE type FUNCTION Fname (arg1, . argn) RESULT(ans)
IMPLICIT NONE
[ declaration part ]
[ execution part ]
END FUNCTION Fname
The value returned by the function call is the value assigned to ans
within the the body of the function.
If there is a RESULT clause, that name must be used as the result
variable, so all references to the function name are recursive calls.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Recursive Functions - example

PROGRAM recu func


! compute factorial of number using recursive function
IMPLICIT NONE
INTEGER, EXTERNAL :: fac !Declare external function
INTEGER :: x, res, xstart, xend
PRINT*, ’Enter the lower & upper limit of # to find factorial’
READ*, xstart, xend !input limits
DO x = xstart, xend
res = fac(x) ! invoking function
PRINT* , x, ’factorial = ’ , res
END DO
END PROGRAM recu func
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Recursive Functions - example

!RECURSIVE type Function Fname(arguments) RESULT(argument)


RECURSIVE INTEGER FUNCTION fac(xval) RESULT(ans fac)
IMPLICIT NONE
INTEGER, INTENT(IN) :: xval
IF (xval == 0) THEN
ans fac = 1
ELSE
ans fac = xval * fac(xval - 1) !function name on RHS why?
END IF
END FUNCTION fac
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Functions input/output declaration

Functions Intent Declaration

It is a good practice to declare whether dummy arguments are


intended as input or output using the INTENT attribute.
The intent of a variable in a function/subprogram can have
one of three values: in, out or inout
INTENT(IN) - The dummy argument is used only to pass
input data to the subprogram and its content does not change.
INTENT(OUT) - The dummy argument is a variable and is
used only to return results to the main program when the
subprogram is invoked.
INTENT(INOUT) - The dummy argument is used both to
pass input data to the subprogram and also to return results
to the main program when he subprogram is invoked.
The INTENT attributes is not essential but it allows
compilers to check for coding errors thereby enhancing safety.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Functions input/output declaration

Functions Intent Declaration

The INTENT attribute is valid only for dummy subprograms


arguments/variables

It is an error to declare the INTENT of local variables in a


subprogram or variables in a main program.

If an INTENT(IN) object is assigned a value or if an


INTENT(OUT) object is not assigned a value then errors will
be generated during compilation.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Functions - Assignment

Write a program that will read in the lengths a and b of two sides
of a triangle and the angle between them θ (in degrees). Calculate
the length of the third side c using the cosine rule:
The program should print out the type of triangle based on the
sides
c 2 = a2 + b 2 − 2abcos(θ)
Write the cosine rule as a function
Outline
Variables to be declared
Declare function
lengths and angle should be read from the keyboard
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Subroutine

A Function computes and returns one value, the function


value, with the function name. Subroutines, on the other
hand, can return several results. However, calls to subroutines
cannot be placed in an expression.
A subroutine must have a name, followed by a list of variables
in parentheses. A variable may be of any type, including a
character variable, and can be an array.
The main program uses a call statement to call the
subroutine. The call statement has also a list of variables,
which are substituted for the subroutine variables.
The subroutine executes, modifying some or all of its
variables, which are then substituted back for the original call
variables in the main program. The variables in the call
statement must match the variables in the subroutine
according to number, type, and dimension.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Subroutine

Subroutine syntax

Subroutine is used in computations that involves the return of


several values of different types. It takes values from its formal
arguments, and returns some computed results with its formal
arguments.
Subroutine syntax is of the form:
SUBROUTINE subroutine-name (arg1,arg2, ..., argn)
IMPLICIT NONE
[ declaration part ]
[ execution part ]
END SUBROUTINE subroutine-name
If a subroutine does not require any dummy arguments, the first
line is written with or without empty parentheses ( ) but the
keyword subroutine and its name should be there.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Subroutine

To call Subroutine

The subroutine is invoked by the CALL statement in the main


program
The CALL statement may have one of the three forms:
1 CALL subroutine-name (arg1, arg2, ...., argn)
2 CALL subroutine-name ( )
3 CALL subroutine-name
The last two forms are equivalent and are used for calling
subroutine without dummy arguments.
The order and type of the actual arguments in the arguments
list in the CALL statement must match the order and type
of the dummy arguments declared in the subroutine.
You do not need to declare the subroutine name in the main
program as you do with a function name
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Subroutine - Internal Subroutine example

PROGRAM root mean square error


!this program compute room mean sqaure error of usser defined constant

IMPLICIT NONE
INTEGER, PARAMETER :: point=5
REAL, DIMENSION (point) :: xobs,xmod
REAL :: ans
PRINT*, ’enter the values for the observed data’ !enter the values for the

observed data

READ*, xobs
PRINT*,’enter the values for the model dats’ !enter the values for the model data

READ*, xmod
CALL my rmse(xobs, xmod, ans) !subroutine call

! Call subroutine name (list of arguments)


PRINT*, ans !print results
CONTAINS !below this statement are subprogram
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Subroutine - Internal Subroutine example - cont

SUBROUTINE my rmse(x obs, x mod, rmse) !subroutine first line statement


IMPLICIT NONE
INTEGER :: icount
INTEGER, PARAMETER ::point=5
REAL, DIMENSION(point) ::x obs,x mod !array declaration for 10 real variable
REAL :: rmse, sum val = 0
DO icount = 1,point !the do loop
sum val = sum val +(x obs(icount) - x mod(icount))**2
!root mean square error formula square part

END DO
rmse=SQRT(sum val/point) !rmse complete formula

END Subroutine !end of subroutine

END PROGRAM root mean square error


Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Subroutine - external Subroutine example

PROGRAM cosinerule
!This formula computes area of triangle using cosine rule
IMPLICIT NONE
REAL :: side1, side2, angle 1 ! input data declaration
REAL :: side3 ! output data declaration
PRINT* , ’Enter the two sides of the triangle’
READ* , side1, side2
PRINT* , ’Enter the angle between the sides’
READ* , angle 1 ! enter angle in degrees
CALL triangle side( side1, side2, angle 1, side3 ) ! subroutine call
PRINT 10, ’the third side of the triangle = ’, side3
10 FORMAT ( A, 2x, F5.3 ) ! print format
END PROGRAM cosinerule
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Subroutine - external Subroutine example - continue

SUBROUTINE triangle side ( a, b, angle, c ) ! subroutine statement


! subroutine takes in two sides of triangle, angle and third sides
IMPLICIT NONE
REAL, INTENT(IN) :: a, b, angle ! triangle sides and angle
REAL, INTENT(OUT) :: c ! third side of triangle
REAL :: theta ! angle in radian
REAL, PARAMETER :: pi =3.143 ! pi declared as constant
theta = (angle/REAL(180))*pi ! convert degrees to radian
c = SQRT(a**2 + b**2 - (2*a*b*COS(theta))) !cosine rule

END SUBROUTINE triangle side


Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Subroutine - empty parentheses example

PROGRAM cosinerule
!This formula computes area of triangle using cosine rule

IMPLICIT NONE

CALL triangle side( ) ! subroutine call

END PROGRAM cosinerule


Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Subroutine - empty parentheses example

SUBROUTINE triangle side ( ) ! subroutine statement


! subroutine takes in two sides of triangle, angle and third sides
IMPLICIT NONE
REAL :: a, b, angle, c, theta ! triangle sides and angle
REAL, PARAMETER :: pi =3.143 ! pi declared as constant
PRINT* , ’Enter the two sides of the triangle’
READ* , a, b
PRINT* , ’Enter the angle between the sides’
READ* , angle ! enter angle in degrees
theta = (angle/REAL(180))*pi ! convert degrees to radian
c = SQRT(a**2 + b**2 - (2*a*b*COS(theta))) !cosine rule
PRINT 10, ’the third side of the triangle = ’, c
10 FORMAT ( A, 2x, F5.3 ) ! print format
END SUBROUTINE triangle side
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Recursive Subroutine

Recursive Subroutine

It is permissible for subroutine also to invoke itself.


recursive subroutine must have the keyword recursive it its
first line.
Its declaration is of the form:
RECURSIVE SUBROUTINE subroutine-name (arg1,arg2, ..., argn)
IMPLICIT NONE
[ declaration part ]
[ execution part ]
END SUBROUTINE subroutine-name
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Subroutine - Assignment

Write a subroutine to calculate new coordinates (x’ , y’ ) from ( x ,


y ) when the axes are rotated counterclockwise through an angle of
a radians using:
x ’ = xcos(a) + ysin(a)
y’ = - xsin(a) + ycos(a)
Write a main program to read in values of x, y, a, call the
subroutine and print out the new coordinates.
We have three input parameters (x , y and a ) and two output
parameters (x’ and y’)
Remember to convert angle (a) from degrees to radians
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran 90 Modules

Fortran 90 MODULE

Module exist so that anything required by more than one


program unit may be package in a module and made available
were needed.
They are designed to hold declaration of variables, data and
subprograms which are to be made available to other program
unit.
A program may use any number of module, with the
restriction that each must be named separately.
A module looks like the main program, except that it does
not have the executable part. Hence, a main program must be
there to use modules
A module consists of two part: a specification part for the
declaration statements, and a subprogram part.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran 90 Modules

Module Syntax

Fortran 90 module has the following syntax:


MODULE module-name
IMPLICIT NONE
[ Declaration part ]
CONTAINS
[ internal functions/subroutines ]
END MODULE module-name
Module can contain just the declaration part or the
subprogram part, or both.
Any program unit that makes use of the module’s contents
should include the following statement (USE [module-name])
immediately after the program name or other program unit
statement
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran 90 Modules

Some features of Module

After USE [module-name ] statement, the variables and


subprograms contained in the [module-name ] can be used in
the program unit.
Note that it is not necessary to declare the module variables
in the main program. The USE statement is sufficient.
If a module is contained in the same file as the main program,
it must come before the main program.
Modules cannot USE themselves either directly (module A
uses A) or indirectly ( module A uses module B which uses
module A)
To restrict program unit to access only variables that it
requires from module, the ONLY qualifier is used. e.g
USE module-name, ONLY: var1, var2
Only var1 and var2 of the module variables are accessible.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran 90 Modules

Some features of Module

The (USE module-name, ONLY) statement safeguards the


module elements that are not needed by making them
inaccessible to the program.
It can also make programs more transparent, by showing the
origin of the data objects or subprograms, particularly if the
program uses several modules.
If the name of an item that is accessed from a module
conflicts with another name elsewhere, one may use the
“renaming” feature of USE.
For each identifier in USE to be renamed, the the syntax:
USE module-name, name-in-program => name-in-module
In this program, the use of name-in-program is equivalent to
the use of name-in-module in the module
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran 90 Modules

Module accessibility - Public and Private

By default, everything in a module is publicly available, that


is, the USE statement in the main program makes available
all of the code in the module
PUBLIC and/or PRIVATE statements ( or attributes ) may be
used to restrict access to some variables, declaration
statement or subprograms in a module
Everything that is declared PRIVATE is not available outside
the module unit, PUBLIC is the opposite.
As a statement PUBLIC or PRIVATE can set the default for
the module, or can be applied to a list of variables or module
names.
As an attribute PUBLIC or PRIVATE can control access to
the variables in a declaration list.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran 90 Modules

Module accessibility - Public and Private

To specify PRIVATE and PUBLIC, do the following:


PUBLIC :: name-1, name-2, ...., name-n
PRIVATE :: name-1, name-2, ...., name-n
The PRIVATE statement without a name makes all entities in
a module private. To make some entities visible outside the
module declare them as PUBLIC.
PUBLIC and PRIVATE may also used in the declaration
statement. e.g
INTEGER, PRIVATE :: sum1, avg1
where sum1 and avg1 are visible within the module
INTEGER, PUBLIC :: sum2, avg2
where sum2 and avg2 are available within/outside the module
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran 90 Modules

Compiling Programs with Module

The module may be in the same source file as other units or it


may be in a different file.
To enable compiler to operate correctly, the module must be
compiled before any program units that USE it. Hence,
1 if it is in a different file the module must be compiled first;
2 if it is in the same file the module must come before any
program units that USE it.
Suppose a program consists of the main program mypro.f90
and a module mymod.f90, then compilation syntax is as
follows:
compiler name -o mypro.exe mymod.f90 mypro.f90
Run the mypro executable file (./mypro.exe) to get the
output
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran 90 Modules

Compiling Programs with Module

Since modules are supposed to be designed and developed


separately, they can also be compiled separately to object
codes.
Module is compile with the syntax :
compiler name -c mymod.f90
The -c option causes the file to be compiled but not linked;
this creates mymod.o and mymod.mod files.
Compile the main program with the syntax:
compiler name -c mypro.f90
Once the two parts have compiled successfully, link them
together with the command:
compiler name -o mypro.exe mymod.f90 mypro.f90
Run the mypro.exe executable file (./mypro.exe) to get the
output
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran 90 Modules - example
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran 90 Modules - example

MODULE stat eg !module and its name


IMPLICIT NONE
CONTAINS !to specify internal subprograms

REAL FUNCTION mean (xval, nnum) !Mean function


IMPLICIT NONE
INTEGER, INTENT(IN) :: nnum !input variable
REAL, INTENT(IN), DIMENSION(:) :: xval !input variable array
REAL :: total !local variable declaration
INTEGER :: i !local variable declaration
total = 0.0 !initialise total
DO i = 1, nnum !loop to sum input data
total = total + xval(i) !sum the varous input data
END DO !end of loop
mean = total/REAL(nnum) !to calculate the mean
END FUNCTION mean !end of function
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran 90 Modules - example

REAL FUNCTION std dev (xval, nnum, dmean)


!function standeviation
IMPLICIT NONE
INTEGER, INTENT(IN) :: nnum !# of input data
REAL, INTENT(IN) :: dmean !dummy variable for mean
REAL, INTENT(IN), DIMENSION(:) :: xval !input data
REAL :: vari !local variable to hold variance
INTEGER :: i !local variable for loop iterator
vari = 0.0 !intialized variance
DO i = 1, nnum
vari = vari + (xval(i) - dmean)**2 !variance summation
END DO
vari = vari/REAL((nnum-1)) !variance formula
std dev = SQRT(vari) !standard deviation formulation
END FUNCTION std dev !end of function

END MODULE stat eg !end of module


Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran 90 Modules - example

PROGRAM stats
USE stat eg !use the module name
IMPLICIT NONE
REAL, DIMENSION(10) :: mydata !actual input data name
REAL :: mymean, mystd dev !mean and standard deviation
INTEGER :: n # of input data
PRINT*, ’enter the number of data point and data value’
READ* , n, mydata
mymean = mean(mydata, n) !mean function
mystd dev = std dev(mydata, n, mymean) !standard deviation
function
!mystd dev = std dev(mydata, n, mean(mydata, n))
!alternative to use mean function
PRINT 10, ’ mean is: ’, mymean, ’standard deviation is:’, mystd dev
10 FORMAT (A, 2X, F4.2, 2X, A, 2X, F4.2)
END PROGRAM stats
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran 90 Modules - example

Compiling program using Module in a different file


Let assume that from the above program the module part is saved in a
file named module.f90
The main program is also saved separately in a file named
module prog.f90
Compilation steps
compile module first using syntax
gfortran -c module.f90
compile the main program using syntax
gfortran -c module prog.f90
Once the two parts have compiled successfully, link them together
with the command:
gfortran -o module prog.exe module.f90 module prog.f90
run the output .exe file with syntax
./module prog.exe
Assignment
Write a fortran program that consist of a main program and a module.
The module should contain a subroutine that solves root mean squared
error: r Pn
2
i=1 (xobs,i − xmodel,i )
RMSE =
n
where Xobs is observed values and Xmodel is modelled values at time i.
The subroutine should accept an arbitrary input values for both Xobs and
Xmodel , assume that n=10
and
a function that solves f(x) numerically in the domain 1 ≤ x ≤ 100


 0 x < 40
0.1(x − 40) 40 ≤ x ≤ 50

f (x) =

 20 − 0.1(x − 40) 50 ≤ x ≤ 60
0 x > 60

The actual input variables for both the function and the subroutine
should be assigned in the main program.
The final output from both the function and the subroutine should be
displayed in the main program
Programming with Fortran II

PROGRAMMING WITH
FORTRAN II

Email:fortranclass@gmail.com

I don’t know what the programming


language of the year 2000 will look like,
but I know it will be called FORTRAN.
Charles Anthony Richard Hoare
Programming with Fortran II
Course content
Outline

FORTRAN ARRAY
- terminology and referencing
- Array declaration and syntax
- Array construction and expression
- Dynamical Allocation of array
READ and WRITE data from/to file
- Open statement
- Attributes of open statement
- Read and write Statement
- Read data with/without header
- Reading table as array
- Formatted and unformatted files
Practical session using meteorological data
- Manipulate field data
- Brief introduction to gnuplot
Programming with Fortran II
Fortran Array
Terminology

An array is a collection of (scalar) data, all of the same type,


whose individual elements are arranged in a regular pattern and
individual elements are accessed by subscripting the array.
There are 3 possible types of arrays depending on the binding of an
array to an amount of storage.
1 Static arrays: their size is fixed when the array is declared and
can not be altered during execution. This is inflexible because
the dimension of the array have to be changed for different
data set.
2 Semi-dynamic arrays: the size of an array is determined after
entering a subroutine and arrays can be created to match the
exact size required but can only be used for a subroutine.
3 Dynamic arrays : the size and therefore the amount of storage
used by a dynamic array can be altered during execution. In
Fortran 90 such arrays are called allocatable arrays.
Programming with Fortran II
Fortran Array
Importance of Fortran array

The reasons for using an array are:


Easier to declare (one variable name instead of tens or even
thousands).
Reduction of program size.
Flexible accessing (one can easily operate on various array
areas in different ways).
Easier to understand the code and operate upon.
Possibility of selecting part of the array of interest to work on.
Programming with Fortran II
Fortran Array
Terminology - Array Attributes

In FORTRAN 90 the following terminology is used:


Rank - (or alternatively called dimension) refers to the
number of subscripts needed to locate an element within an
array. A scalar variable has a rank of zero.
- Vector: An array with a rank of 1 is called a vector.
- Matrix: An array with a rank of 2 or greater is called a
matrix
Extent - refers to the number of elements in a dimension
Shape - is a vector containing the extents of an array
Size - refers to the total number of elements of an array,
which simply is the product of extents
Bounds- refers to upper and lower limits of indices; by default,
they are taken 1:Extent but can be specified.
Conformable - two arrays are conformable if they have the
same shape
Programming with Fortran II
Fortran Array
Declaration or Specifications

To declare/specify an array the following attributes of the array


must be known:
The name given to the array (e.g. Student mark). The name
given to the array is up to 31 alphanumeric characters
including underscore but the first character must be a letter.
The type of the elements (e.g. integer). All elements must be
of the same type and the type can be integer, real, logical,
character, or derived.
The dimensions of the array (e.g. 1 dimension). Up to 7
dimensions are allowed
The lower and upper bounds for each dimension (e.g 1 and 8).
Declaring the lower bound is optional. If the lower bound is
not specified Fortran 90 assumes that the index begins with 1.
Notice that the type of the bounds is always integer.
Programming with Fortran II
Fortran Array
Declaration or Specifications

Like other variables arrays are specified with a specific data


alerttype (INTEGER, REAL, derived type, etc.). For static arrays,
the rank (up to a maximum of 7) and the bounds (upper and
lower) in each dimension are declared. Declaring the lower bound
is optional. If the lower bound is not specified Fortran 90 assumes
that the index begins with 1.
Alternate and equivalent forms used to declare an array are as
follows:
1. type, DIMENSION(bound) [, attribute] :: name
2. type [, attribute] :: name (bound)
where [, attribute] allows for the declaration of other type
attributes, if required. Remember the attributes we have used so
far
Throughout this course, we will only the first form of declaration.
Programming with Fortran II
Fortran Array
Declaration examples

Below are examples of array declaration:


INTEGER, DIMENSION(6) :: xval ! integer array of 6 elements
REAL, DIMENSION(0:9) :: ans ! real array of 10 elements
REAL, DIMENSION(2,3) :: mydata ! 2-D (table) real array

Individual elements
Individual elements and sections of an array are uniquely identified
through sub- scripts, one per rank separated by commas. This
subscript is an integer value (or an expression whose result is an
integer value)
REAL, DIMENSION(8) :: a
INTEGER, DIMENSION(5,4) :: b
a(5) !fifth element
b(4,2) !element at intersection of the 4th row and 2nd column.
Programming with Fortran II
Fortran Array
Array Section

To access a section of an array you need the name of the array


followed by two integer values separated by a colon enclosed in
parentheses. The integer values represent the indices of the section
required. For multi-dimensional arrays use a list of integer values
separated by a comma.
The syntax is as follows
array name ([lower]:[upper]:[step], [...]) where lower and upper are
default to the declared dimensions and step defaults to 1.
Example
array name(3:5) refers to elements 3, 4, 5 of the array array name
array name(1:5:2) refers to elements 1, 3, 5 of the array
array name
mydata(1:3, 2:4) refers to elements from rows 1 to 3 and columns
2 to 4 of array mydata (table or 2-D array).
Programming with Fortran II
Fortran Array
Array Section

Section of an array can be selected using one of the following:


Using colon: This is a facility that enables us to access whole or
parts of columns or rows. For example, b(:4) refers to all elements
of the fourth column.
Using subscripts: For example, alpha(i,j) refers to the element at
the intersection of ith row and jth column. Subscripts i,j are
defined previously within the program.
Using expressions: For example, alpha(2*k) refers to an element
whose position is the result of the multiplication. The result of an
expression must be an integer within the declared bounds.
Using stride: For example, beta(3,1:7:2) refers to elements 1,3,5,7
of the third row., beta(1,2:11:2) refers to elements 2,4,6,8,10 of
the first row. This is a valid statement despite that the upper
bound of the second dimension is 10.
Programming with Fortran II
Fortran Array
Multi-dimensional Arrays

The declaration of a two-dimensional array P is as follows:


REAL, DIMENSION(1:6,1:8) :: P
A two-dimensional array has two indices and is called a matrix.
The above matrix is visualized below, matrix P has 42 elements
arranged in 6 rows and 8 columns. The cross areas indicates the
subsection given below:
Programming with Fortran II
Fortran Array
Multi-dimensional Arrays - Sections

The declaration of a two-dimensional array P is as follows:


REAL, DIMENSION(1:6,1:8) :: P
Explanation to selected sections are given below:

P(1:3,1:4) is a 3 x 4 section the missing stride implies a value


of 1,
P(2:6:2,1:7:3), which could be written: P(2::2,:7:3) is a 3 x 3
section.
(A missing upper bound (in the first dimension) means
assume the upper bound as declared, (6), A missing lower
bound is the lower bound as declared, (1).)
P(2:5,7) is a 1D array with 4 elements; P(2:5,7:7) is a 4 x 1
2D array,
P(1:6:2,1:8:2) is a 3 x 4 section. This could also be written as
P(::2,::2), here both upper and lower bounds are missing so
the values are taken to be the bounds as declared.
Programming with Fortran II
Fortran Array
Multi-dimensional Arrays - Conformance

The declaration of a two-dimensional array P is as follows:


REAL, DIMENSION(1:6,1:8) :: P
Explanation to conformance of array are given below:
P(1:3,1:4) = P(1:6:2,1:8:2) is a valid assignment both LHS
and RHS are 3 x 4 sections.
P(1:3,1:4) = 1.0 is a valid assignment a scalar on the RHS
conforms to any array on the LHS of an assignment.
P(2:6:2,1:7:3) = P(1:3,1:4) is not a valid assignment an
attempt is made to equate a 3 x 3 section with a 3 x 4
section, the array sections do not conform.
P(2:6:2,1:7:3) = P(2:5,7) is not a valid assignment an attempt
is made to equate a 3 x 3 section with a 4 element 1D array.
P(2:5,7) is a 1D section - the scalar in the second dimension
’collapses’ the dimension.
P(2:5,7:7) is a 2D section - the second dimension is specified
with a section (a range) not a scalar so the resultant
sub-object is still two dimensional.
Programming with Fortran II
Fortran Array
Array Input/Output

Printing Arrays

The conceptual ordering of array elements is useful for defining the


order in which array elements are output. If A is a 2D array then:
PRINT*, A
would produce output in Array Element Order:
A(1,1), A(2,1), A(3,1), ..., A(1,2), A(2,2), ...
Sections of arrays can also be output, for example,
PRINT*, A(::2,::2)
would produce:
A(1,1), A(3,1), A(5,1), ..., A(1,3), A(3,3), A(5,3), ...
An array of more than one dimension is not formatted neatly, if it
is desired that the array be printed out row-by-row (or indeed
column by column) then this must be programmed explicitly.
This order could be changed by using intrinsic functions such as
RESHAPE, TRANSPOSE or CSHIFT.
Programming with Fortran II
Fortran Array
Array Input/Output

Input of Arrays

Elements of an array can be read in and assigned to the array in


array element order, for example,
READ*, A
would read data from the standard input and assign to the
elements of A.
Sections of arrays can also be input, for example,
READ*, A(::2,::2)
is perfectly valid and will assign to the indicated subsection of A.
Programming with Fortran II
Fortran Array
Intrinsic Functions for Arrays

Intrinsic Functions for Arrays

Most intrinsic functions that we use for scalars, for example SIN,
INT, and ABS, are elemental; i.e. they can also apply to arrays.
For example:
REAL :: A= (/ 0.2, 0.3, 0.4, 0.5, 0.6 /)
PRINT *, SIN(A)
gives
0.1986693 0.2955202 0.3894183 0.4794255 0.5646425
There are, in addition to the elemental functions, intrinsic
functions whose arguments are specifically arrays.
Some of them are listed in the next slide
Programming with Fortran II
Fortran Array
Intrinsic Functions for Arrays

Function Description
MAXVAL(A) Gives the maximum value of array A
MINVAL(A) Gives the minimum value of array A
MAXLOC(A) Index location of maximum value of A
MINLOC(A) Index location of minimum value of A
PRODUCT(A) Gives product of the values in array A
SIZE(A) Gives the number of values of array A
MATMUL(A,B) Gives the cross product of arrays A and B
TRANSPOSE(A) Gives the transpose of array A
SUM(A) Gives the sum of the values in array A

We are going to use most of them in the exercises


Programming with Fortran II
Fortran Array
Array Inquiry Intrinsics

Array Inquiry Intrinsics


These intrinsics allow the user to quiz arrays about their attributes
and status and are most often applied to dummy arguments in
procedures. Consider the declaration:
REAL, DIMENSION(-10:10,23,14:28) :: A
The following inquiry intrinsics are available,
1. LBOUND(array name [,DIM])
Returns a one dimensional array containing the lower bounds of an
array or, if a dimension is specified, a scalar containing the lower
bound in that dimension.
For example,
PRINT*,LBOUND(A) ! produces -10 1 14 ie lower bounds in
each dimension
PRINT*,LBOUND(A,1) ! produces -10 ie lower bound in first
dimension
Programming with Fortran II
Fortran Array
Array Inquiry Intrinsics

Array Inquiry Intrinsics


REAL, DIMENSION(-10:10,23,14:28) :: A
2. UBOUND(array name [,DIM])
Returns a one dimensional array containing the upper bounds of an
array or, if a dimension is specified, a scalar containing the upper
bound in that dimension. For example,
PRINT*,UBOUND(A) ! produces 10 23 28 ie lower bounds in
each dimension
PRINT*,UBOUND(A,1) ! produces 10 ie lower bound in first
dimension
3. SHAPE(array name)
Returns a one dimensional array containing the shape of an object.
For example,
PRINT*,SHAPE(A) ! produces 21 23 15 ie number of elements
in each dimension
Programming with Fortran II
Fortran Array
Array Inquiry Intrinsics

Array Inquiry Intrinsics

REAL, DIMENSION(-10:10,23,14:28) :: A
4. SIZE(array name [,DIM])
Returns a scalar containing the total number of array elements
either in the whole array or in an optionally specified dimension.
For example,
PRINT*,SIZE(A) ! produces 7245 ie multiplication of dimension
PRINT*,Size(A,1) ! produces 21 ie element in first dimension
PRINT*,Size(4) ! is an error as the argument must not be scalar
Programming with Fortran II
Fortran Array
Array constructors

Array constructors

Array constructors are used to give arrays or sections of arrays


specific values or initial values. An array constructor is a
comma separated list of scalar values or expressions delimited
by (/ and /).
The constructor must be of the correct length for the array, in
other words, the section and the constructor must conform.
Only one dimensional constructors are allowed; to initialize
higher rank matrices, we need to explicitly RESHAPE the
constructor to the desired shape.
The general form is:
array name = (/ list /)
where list can be one of the following (next slide)
Programming with Fortran II
Fortran Array
Array constructors

Array constructors

1 A list of values of the appropriate type:


INTEGER, DIMENSION (5) :: myvec = (/1,2,3,4,5/)
2 Variable expression(s):
REAL, DIMENSION (2) :: myexp = (/SIN(30.0), COS(40)/)
3 Array expression(s):
INTEGER, DIMENSION (5) :: myarray = (/1,eray(1:3), 80/)
where eray(1:3) is already known/declared array. In this case
eray can be declared with parameter attributes
4 Implied DO loops:
REAL, DIMENSION (10) :: mylop = (/(i, i= 1,10)/)
i must declared as integer. But is possible to convert i to real
(remember)
We come back to implied DO loop later.
Programming with Fortran II
Fortran Array
Array constructors- Example

PROGRAM array
IMPLICIT NONE
INTEGER, DIMENSION (5) :: myvec = (/23,21,100,1,5/)
REAL, DIMENSION (4), PARAMETER ::mycon=(/0.1,0.2,0.3,0.4/)
REAL, DIMENSION (10) :: impdo !implied do loop eg
REAL, DIMENSION (3) :: expres !expression eg
REAL, DIMENSION (9) :: myarray !array eg
INTEGER :: i

PRINT*, ’myvec array’, myvec !print myvec array


expres = (/SIN(mycon(1)), COS(mycon(4)), TAN(mycon(2))/)
PRINT*, ’expres array’, expres !print expres array
myarray = (/(REAL(myvec)), mycon/)
PRINT*, ’myarray values are’, myarray !print myarray
impdo = (/(i, i = 1, 10)/)
PRINT*, ’impdo array is’, impdo !print impdo array
END PROGRAM array
Programming with Fortran II
Fortran Array
Array constructors- 2D

There is a restriction that only one dimensional constructors are


permitted, for higher rank arrays the RESHAPE intrinsic must be
used to modify the shape of the result of the RHS so that it
conforms to the LHS:
Example
Consider the declaration:
INTEGER, DIMENSION (1:3,1:4) :: my
my = RESHAPE((/11,21,31,12,22,32,13,23,33,14,24,34/),(/3,4/))
PRINT*, my
the out put is 11 12 13 14
21 22 23 24
31 32 33 34
The values are specified as a one dimensional constructor and then
the shape is modified to be a 3 x 4 array which conforms with the
declared shape of my.
Programming with Fortran II
Fortran Array
The RESHAPE Intrinsic Function

The RESHAPE Intrinsic Function


RESHAPE used for the initialization or assignment of
multi-dimensional arrays, i.e., arrays with rank greater than 1. It
can be used on a declaration statement or in a separate statement.
The syntax is :
RESHAPE(SOURCE, SHAPE [,PAD] [,ORDER])
where:
source - one dimensional array or constructor containing the data
shape - one dimensional array or vector subscript containing the
new shape of the data
pad - is a one dimensional array of values which is used to pad out
the resulting array if there are not enough values in source. The
pad constructor is used repeatedly (in array element order) to
provide enough elements for the result. pad is optional.
order - allows the dimensions to be permuted, in other words,
allows the array element ordering to be modified, order is optional.
Programming with Fortran II
Fortran Array
The RESHAPE Intrinsic Function - examples

The RESHAPE examples


To assign 2 x 2 integer array to a variable named myarray.
INTEGER, DIMENSION(2,2) :: &
myarray = RESHAPE ((/1,2,3,4/),(/2,2/))
PRINT*, myarray
The output is 13
24
The result of the RESHAPE is a 2 x 2 array (specified by the
second argument (/2,2/)).
Note by default, arrays are filled by column major form (i.e fixing a
column and assigned the rows before moving to next column).
However, this default can be changed by using ORDER specifier.
Alternatively, myarray can be declared and later assigned its
elements using the RESHAPE function.
Programming with Fortran II
Fortran Array
The RESHAPE Intrinsic Function - examples

The RESHAPE examples - using ORDER specifier

Let consider the same array but this time using the ORDER
specifier
INTEGER, DIMENSION(2,2) :: myarray
myarray = RESHAPE ((/1,2,3,4/),(/2,2/),ORDER=(/2,1/))
PRINT*, myarray
the output is 12
34
This time the array is filled up in row major form, (i.e fixing a
fixing and assigned the columns before moving to next row) this is
specified by the ORDER=(/2,1/) specifier. The default ordering
is, of course, ORDER=(/1,2/).
The ORDER keyword is necessary because some optional
arguments are missing. In this case PAD is missing.
Programming with Fortran II
Fortran Array
The RESHAPE Intrinsic Function - examples

The RESHAPE examples - using PAD specifier


When the size of the array is more than the SOURCE, PAD
specifier is used to provide additional elements. The result of
RESHAPE must conform to the array object on the LHS of the =
Let consider this example
INTEGER, DIMENSION(2,4) :: myarray ! 2x4 array
myarray = RESHAPE ((/1,2,3,4,5,6/),(/2,4/),(/0/),(/2,1/))
PRINT*, myarray
the output is 1234
5600
The source object has less elements than the LHS so the resulting
array is padded with the extra values taken repeatedly from the
third array argument, PAD, (/0/).
Note this example does not use keyword arguments.
Programming with Fortran II
Fortran Array
The RESHAPE Intrinsic Function - examples

The RESHAPE examples - using keyword arguments


It is possible to use RESHAPE function with keyword arguments.
Let consider the previous example:
INTEGER, DIMENSION(2,4) :: myarray ! 2x4 array
myarray = RESHAPE ((/1,2,3,4,5,6/),(/2,4/),(/0/),(/2,1/))
This is equivalent to
myarray = RESHAPE(SOURCE=(/1,2,3,4,5,6/),&
SHAPE=(/2,4/),&
PAD=(/0/),&
ORDER=(/2,1/))
If one of the optional arguments is absent then keyword arguments
should be used for the other optional argument to make it clear to
the compiler (and the user) which is the missing argument. The
keywords are the names of the dummy arguments.
Programming with Fortran II
Fortran Array
Implied DO loop

Implied DO loop

Implied DO loops are DO loops in the sense that they control


the execution of some iterative procedure, but are different
from DO loops because they do not use the do statement to
control the execution.
Implied DO loops are are shorthand in FORTRAN to provide a
method for array initialization, generate set of values/element
and to cut down the number of lines of coding.
The implied DO loop has the following syntax:
(item-1, item-2, ....,item-n, v=initial, final, step)
Where
item-1, item-2, ....,item-n are variables or expressions
v is an integer
initial, final and step are integer expressions.
Programming with Fortran II
Fortran Array
Implied DO loop - example

Implied DO loop - example

The execution of an implied DO loop below lets variable v to start


with initial, and step though to final with a step size step.
To generate sequence of integers, consider the declaration:
INTEGER :: i
PRINT*, (i+1, i=1,5) ! step is 1, similar to DO loop
The output is 23456
To generate sequence of variables square with step, consider the
declaration:
INTEGER :: i
PRINT*, (i**i, i=1,10,2) ! step is 2, similar to DO loop
The output is 1 9 25 49 81
Programming with Fortran II
Fortran Array
Implied DO loop - example

Implied DO loop - Nested

Implied DO loop may be nested similar to DO loops


INTEGER :: i , j
PRINT*, ( ( i*j ,i = 1,4) , j = 1,6 )
The output is 1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16 5 10 15 20
6 12 18 24
In the above, ( i*j ,i = 1,4) is nested in the implied j loop.
When j=1, the implied DO loop generates the product of i*j with i
moving from 1 through to 4.
Then j moves to 2 while implied DO loop ( i*j ,i = 1,4) repeat the
cycle until j gets to 6.
Programming with Fortran II
Fortran Array
Dynamic Arrays - Allocatable Arrays

The ALLOCATABLE Attribute

In many situations, one does not know exactly the shape or


extents of an array. As a result, one can only declare a “large
enough“ array.
The ALLOCATABLE attribute comes to rescue.
The ALLOCATABLE attribute indicates that at the
declaration time one only knows the rank of an array but not
its extent.
Therefore, each extent has only a colon : .
Example
INTEGER, ALLOCATABLE, DIMENSION (:) :: a ! rank 1 array
ie a vector
REAL, ALLOCATABLE, DIMENSION (: , :) :: b ! rank 2 array
ie a matrix
Programming with Fortran II
Fortran Array
Dynamic Arrays - Allocatable Arrays

The ALLOCATE Statement


After declaring the dynamic array, the bounds can be assigned
using ALLOCATE statement
The ALLOCATE statement has the following syntax:
ALLOCATE (array name (lower bound:upper bound))
For multi-dimensional array, complete extents in each
dimension is required. For 2D array the syntax becomes:
ALLOCATE (array name ( lb1 : ub1 , lb2 : ub2 ))
where lb1 and ub1 are lower and upper bounds in the 1st
dimension and lb2 and ub2 have the same meaning but for
2nd dimension.
Example (based on above allocatable declaration)
ALLOCATE (a (10) ) ! 10 element vector
ALLOCATE (b (4,4)) ! 4x4 matrix ie 2D array
Programming with Fortran II
Fortran Array
Dynamic Arrays - Allocatable Arrays

The ALLOCATE Statement

At times, it is important to check the status of the allocation.


If you wish to check the allocation status then the syntax
becomes:
ALLOCATE (array name (L bound:U bound),STAT=status)
In this form, the integer variable status will be set to zero if
allocation is successful, but will be assigned some value if
there is insufficient memory.
ALLOCATE only allocates arrays with the ALLOCATABLE
attribute.
In the ALLOCATE statement we could specify a list of objects
to create but in general one should only specify one array
statement if there is more than one object and the allocation
fails it is not immediately possible to tell which allocation was
responsible.
Programming with Fortran II
Fortran Array
Dynamic Arrays - Allocatable Arrays

Example

PROGRAM myown
IMPLICIT NONE
REAL, ALLOCATABLE, DIMENSION(:):: myvec ! vector array
INTEGER :: check var, xval
PRINT*,’enter the extent of the array’ ! size of vector
READ*,xval
ALLOCATE(myvec(xval), STAT=check var)
IF (check var/=0) THEN ! to check for correct dimension
PRINT*, ’not enough memory’
END IF
PRINT*,’enter the elements of the array’
READ*,myvec ! assign values to the array myvec
PRINT*,’array size is’, size(myvec), ’and elements are’, myvec
END PROGRAM myown
Programming with Fortran II
Fortran Array
Dynamic Arrays - Allocatable Arrays

The DEALLOCATE Statement

If the allocated array is no longer needed in the program, the


associated memory can be freed using DEALLOCATE
statement. The syntax is as follows:
DEALLOCATE (array name)
The syntax with status check is as follows:
DEALLOCATE (array name, STAT=status)
After deallocation of an array, it is not available and any
access will cause a program error.
It is an error to attempt to DEALLOCATE an array that has
not previously been allocated space or one which does not
have the ALLOCATE attribute
Again one should only supply one array per DEALLOCATE
statement
Programming with Fortran II
Fortran File input and output
File input/output

File input/output (I/O)

So far we have considered only terminal input/output (I/O) using


simple READ and PRINT . Many times programs read large sets of
input data from data files, and write large amounts of output
results to another files; these can be subsequently used by other
programs (eg to plot output), which, for example, analyze them.
File data are permanent, in the sense that they remain after the
program who produced them finishes.
A program can read or write formatted and unformatted data
records

FORMATTED data files


are composed of ASCII characters only
information is in human-readable form
formatted data files are portable
Programming with Fortran II
Fortran File input and output
File input/output

UNFORMATTED data files

store data in the binary form, as represented internally by the


computer
information is not human-readable
there is no roundoff, no computational overhead, and results
in a smaller file
unformatted data files may not be portable, since the internal
representation may be different on different computer systems
they are useful to temporarily store intermediate results during
one execution.
A formatted file may be viewed using an editor or printed on a
printer. An unformatted file has no discernible structure and
should be regarded as single stream of bytes of raw data.
An unformatted file is normally only viewed using a suitable user
written program.
Programming with Fortran II
Fortran File input and output
File input/output

In Fortran 90 a file is connected to a logical unit denoted by a


number. This number must be positive and is often limited to be
between 1 and 100, the exact number will be given in the compiler
manual.
Each logical unit can have many properties, for example,
file - the name of the file connected to the unit
The name is specified in the OPEN statement.
action - read, write, read and write,
If a file is opened for one sort of action and another is
attempted then an error will be generated, for example, it is
not permissible to write to a file opened solely for reading.
status - old, new, replace, scratch etc.
If ’OLD’ is specified the file must exist; if ’NEW’ the file must
not exist; if ’REPLACE’ and the file exists it will be deleted
before a new file is created; and if ’SCRATCH’ the file will be
deleted when closed.
In general use ’OLD’ for input and ’NEW’ for output
Programming with Fortran II
Fortran File input and output
File input/output

Continued from previous slide

access method - sequential, direct


sequential - is ’normal’ access, each write / read causes a
pointer to move down the file, the next line which is written /
read appears after the previous line.
direct - each line is accessed by a number (a record number)
which must be specified in the read / write statement made.
Fortran program can use more than one file but each file
should have a different logical unit number.
Before a file can be used it first must be open using the open
statement. Close statement is also used to close the file after
usage
Programming with Fortran II
Fortran File input and output
File input/output

OPEN statement
The OPEN statement is used to connect a named file to a logical
unit and to specify certain properties for that file which differ from
the defaults. It can be used to create or connect to an existing file.
The syntax is
OPEN([UNIT=]<integer>,FILE=<filename>,ERR=<label>, &
STATUS=<status>,ACCESS=<method>,ACTION=<mode>)
where
UNIT=< integer > specifies a numeric reference for the named file. The
number must be one that is not currently in use.
FILE=< filename > gives the filename to be associated with the logical
unit. The name must match exactly with the actual filename if you are
reading from existing file
ERR=< label > specifies a numeric label where control should be
transferred if there is an error opening the named file.
Programming with Fortran II
Fortran File input and output
File input/output

continued from previous slide OPEN statement syntax


STATUS=< status > specifies the status of the named file, the
status may be one of the following options:
’OLD’ - file exists
’NEW’ - file does not exist.
’REPLACE’ - file will be overwritten.
’SCRATCH’ - file is temporary and will be deleted when closed.
’UNKNOWN’ - unknown.
ACCESS=< method > specifies the access method with these two
options,
’DIRECT’- the file consists of tagged records accessed by an ID
number, in this case the record length must be specified (RECL).
Individual records can be specified and updated without altering
the rest of the file.
’SEQUENTIAL’ - the file is written / read (sequentially) line by
line.
Programming with Fortran II
Fortran File input and output
File input/output

continued from OPEN statement slide


ACTION=< mode > specifies what can be done to the file, the
mode may be one of the following,
’READ’, - open for reading.
’WRITE’ - open for writing.
’READWRITE’ - open for both reading and writing.
Example
OPEN(17,FILE=’output.dat’,ERR=10, STATUS=’REPLACE’, &
ACCESS=’SEQUENTIAL’,ACTION=’WRITE’)
A file output.dat is opened for writing, it is connected to logical
unit number 17. The file is accessed on a line by line basis and
already exists but is to be replaced. The label 10 must pertain to a
valid executable statement.
Programming with Fortran II
Fortran File input and output
File input/output

OPEN statement - example

Throughout this course, OPEN statement will take the simplest


form in the assignments
Example
OPEN(UNIT=10,FILE=’filename.txt’, ACTION=’READ’)
This will open the file ’filename.txt’ and assign it to ’UNIT’ 10.
The file should already exist and is being opened with read
permission only. Any attempt to write into the file will generate
error.
OPEN(UNIT=20,FILE=’array.txt’, ACTION=’WRITE’)
This will open the file ’array.txt with write permission only and
assign ’UNIT’ of 20. Any attempt to read from the file will
generate error.
Programming with Fortran II
Fortran File input and output
File input/output

READ statement
The READ statement includes the keyword READ, followed by a
set of parentheses containing pertinent information, followed by a
list of variables (separated by commas). The READ statement is
used to read in data from a file.
The simplest syntax is as follows
READ(UNIT=< unit >, FMT =< format >) < data list >
where
unit - Set to be the unit number of the opened file
format - You can specify a string of formatting characters that
describe how the data is arranged in the file or use the default
FMT=*.
data list - The declared data types that is to be read from the data
file separated by commas.
Programming with Fortran II
Fortran File input and output
File input/output

READ statement - example

READ(UNIT=14, FMT=”(3(F10.7,1x))”) a,b,c


This example would read in three real numbers that occupy ten
columns and have seven decimal places with one blank space
separating the numbers.
READ(UNIT=14, FMT=*) a,b,c
This example uses the default Fortran format specified with
FMT=*.
Note it is reading from data file assigned with unit 14
!Remember format descriptors (last semester)
Note that the simplest method of formatting it is to use the
default fortran format FMT=*. This means that we do not have to
be strict about the number of decimal places or how many blank
spaces separate each element from its neighbouring element.
Programming with Fortran II
Fortran File input and output
File input/output

READ statement - example

The READ statement can read input values into a set of variables
from the keyboard.
The READ statement has the following forms:
READ (*,*) var1, var2, ..., varn
This form starts with READ(*,*), followed by a list of variable
names, separated by commas. The computer will read values from
the keyboard successively and puts the value into the variables.
READ (*,*)
It does not read in anything (to skip a whole line of data). It is
useful in reading data file headers.
!This READ(*,*) is similar to the already know input statement
READ*
Programming with Fortran II
Fortran File input and output
File input/output

WRITE statement
The WRITE statement includes the keyword WRITE, followed by a
set of parentheses containing pertinent information, followed by a
list of variables (separated by commas). The write command is
used to write data to a file
The simplest syntax is as follows
WRITE(UNIT=< unit >, FMT =< format >) < data list >
where
unit - Set to be the unit number of the opened file
format - You can specify a string of formatting characters that
describe how the data is to be written to the file or use the default
FMT=*.
data list - The declared data types that is to be written into the
data file separated by commas.
Programming with Fortran II
Fortran File input and output
File input/output

WRITE statement - example

WRITE(UNIT=14, FMT=”(3(F10.7,1x))”) a,b,c


Equivalent to
WRITE(UNIT=14, 30) a,b,c
30 FORMAT (3(F10.7,1x))
This example would write three real numbers that occupy ten
columns and have seven decimal places with one blank space
separating the numbers.
WRITE(UNIT=14, FMT=*) a,b,c
Equivalent to
WRITE(14,*) a,b,c
This example uses the default Fortran format that is specified with
FMT=*.
Note it is writing data into file assigned with unit 14
Programming with Fortran II
Fortran File input and output
File input/output

WRITE statement - print output on the screen

The WRITE statement can be used also to print output to the


screen like PRINT* statement.
WRITE(*, FMT=”(3(F10.7,1x))”) a,b,c
Equivalent to
WRITE(*,10) a,b,c
10 FORMAT(3(F10.7,1x))
WRITE statement can be used to output empty line (blank line).
The syntax is
WRITE(UNIT=14, *)
This print empty line in the output file assigned unit 14
WRITE(*,*)
This print blank line on the screen
Programming with Fortran II
Fortran File input and output
File input/output

CLOSE statement
Execution of a CLOSE statement terminates the connection of a
file to a unit. Any connections not closed explicitly by a CLOSE
statement are closed by the operating system when the program
terminates, unless an error condition has terminated the program.
In its simplest form the CLOSE statement requires a unit number
(of a file already open)
The syntax is
CLOSE (UNIT=unit number)
where unit number refers to the unit number of the opened file.
For example to close a file opened with unit 10:
CLOSE (10)
CLOSE (UNIT=10)
The above CLOSE statements are equivalent
Programming with Fortran II
Fortran File input and output
Reading Data from a file

Reading Data from a File

To read/write data from/to file, the following should be noted:


Location of the file (in the same directory with the program or
in a different directory):
- same directory - path to the data is not required
- different directory - path to the data is required
File content (data of the same type or of different types):
- same type - data can be read using array declaration
depending on data dimension
- different type - each type must be declared separately by 1D
array
Data information (data with/without header )
- with header - header information must be read first
Dimension and size of the data file should be known
Programming with Fortran II
Fortran File input and output
Reading Data from a file

Reading Data from a File - example

Consider integer data below saved as examp1.txt without header


11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
!Note the data is saved in a plain text format
Data is in the same directory with the source code
Data properties
- Rank 2 array !why?
- composed of integer data type
- no header
- 4 x 4 array ! what is the array size?
- data can be declared with a single array ! why?
See next slide for the code
Programming with Fortran II
Fortran File input and output
Reading Data from a file - example1

PROGRAM examp1
!this program read input data from a file and write output in another file
IMPLICIT NONE
INTEGER, DIMENSION(4,4) ::mydata !4x4 array declaration
INTEGER ::i,j
OPEN (20, FILE=’examp1.txt’,ACTION=’READ’) !input file
OPEN (30, FILE= ’output1.txt’, ACTION=’WRITE’) !output file
DO i=1,4
READ (20,*) (mydata(i,j),j=1,4) !implied do loop
WRITE (30,*)(mydata(i,j),j=1,4) !write into the file assigned 30
END DO
WRITE(*,*) MAXVAL(mydata) !maximum value of the data
WRITE(*,*) MAXLOC(mydata) !location of maximum value
WRITE(*,*) MINVAL(mydata) !maximum value of the data
WRITE(*,*) MINLOC(mydata) !location of minimum value
WRITE(*,*)TRANSPOSE(mydata) !transpose of the matrix
WRITE(*,*) SUM (mydata) !sum of the whole data
WRITE(*,*)SUM (mydata,1) !sum along each column
END PROGRAM examp1
Programming with Fortran II
Fortran File input and output
Reading Data from a file - example2

Consider integer data below saved as examp2.txt with header


R1 R2 R3 R4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
The data header are R1, R2, R3 and R4
The header must be read first with empty Read statement
Data consist of 4 rows and 4 columns (4x4 array)
Example
READ (10,*)
To skip a line of input data assigned unit 10
See next slide for the code
Programming with Fortran II
Fortran File input and output
Reading Data from a file - example2

PROGRAM examp2
IMPLICIT NONE
INTEGER, DIMENSION(4,4) ::mydata !4x4 array declaration
INTEGER ::i,j
OPEN (20, FILE=’examp1.txt’,ACTION=’READ’) !input file
OPEN (30, FILE= ’output1.txt’, ACTION=’WRITE’) !output file
!————————————————————————–
READ(20,*) !to read the header (skip 1st line of data)
!—————————————————————————
DO i=1,4
READ (20,*) (mydata(i,j),j=1,4) !implied do loop
WRITE (30,*)(mydata(i,j),j=1,4) !write into the file assigned 30
END DO
WRITE(*,*) MAXVAL(mydata) !maximum value of the data
WRITE(*,*) MAXLOC(mydata) !location of maximum value
WRITE(*,*) MINVAL(mydata) !maximum value of the data
WRITE(*,*) MINLOC(mydata) !location of minimum value
END PROGRAM examp2
Programming with Fortran II
Fortran File input and output
Reading Data from a file - example3

This example consist of table(2D array) of different data types.


name age mark
kwame 20 89.0
kwasi 12 75.5
kojo 17 23.9
kwaku 18 30.1
yaw 19 24.0
kofi 23 50.7
kwabena 25 90.7
Three data types are represented here strings, integer and real
A single array declaration cannot read the entire data ! why?
Three 1D array declarations is needed each representing a
particular data type
What should be the length of the array? !given by # of rows
Remember data header must be read first.
Programming with Fortran II
Fortran File input and output
Reading Data from a file - example3

PROGRAM examp3
! !this program read input data from a file
IMPLICIT NONE
INTEGER, PARAMETER :: nrow = 7 !total # of rows in the data
CHARACTER(LEN=10), DIMENSION (nrow) :: myname !name
INTEGER, DIMENSION (nrow) ::age !age declaration
REAL, DIMENSION (nrow) :: mark !mark declaration
INTEGER ::i !loop iterator
OPEN (50, FILE=’examp3.txt’,ACTION=’READ’) !input file
OPEN (5, FILE= ’output3.txt’, ACTION=’WRITE’) !output file
READ (50,*) !to read the header
DO i=1,nrow
READ(50,*) myname(i), age(i), mark(i) !note the positions
WRITE(5,*) myname(i), age(i), mark(i) !write output to file
END DO
!do your analysis here with the data
CLOSE(50) !close input file
CLOSE(5) !close output file
END PROGRAM examp3
Programming with Fortran II
Fortran File input and output
Reading Data from a file - using allocatable array

At times data comes with headers that contains information about


the dimensions of the data. In this case allocatable attribute can
be used.
Allocatable attribute can be used only if the rank of the array is
known at the declaration time
Consider this example, real data saved as examp4.txt
nrow 7
ncol 3
mark1 mark2 mark3
65.0 70.6 89.0
67.2 80.0 75.5
55.5 72.0 56.8
92.3 45.8 39.9
78.0 66.9 69.9
70.0 80.0 71.7
78.9 89.9 90.7
The # of columns and rows are given as part of the header
information.
Programming with Fortran II
Fortran File input and output
Reading Data from a file - using allocatable array
PROGRAM examp4
!how to use allocatable attribute
IMPLICIT NONE
INTEGER :: nrow, ncol !total # of rows and columns in the data
REAL, ALLOCATABLE :: mydata(:,:) !array declaration
CHARACTER (LEN = 50) :: dummy !To store data header strings
INTEGER ::i, j !loop iterator
OPEN(10, FILE=’examp4.txt’,ACTION=’READ’) !input file
READ(10,*) dummy, nrow !dummy read nrow and 7=nrow ie # of rows
READ(10,*) dummy, ncol !dummy read ncol and 3=ncol ie# of columns.
READ(10,*) !This skip the header of the data
ALLOCATE (mydata(nrow,ncol)) ! to allocate array nrow=7, ncol=3
OPEN(5, FILE= ’output4.txt’, ACTION=’WRITE’) !output file
DO i=1,nrow
READ(10,*)(mydata(i,j), j=1,ncol) !note the positions same as the file
WRITE(5,10) (mydata(i,j), j=1,ncol) !write output to file assigned unit
10 FORMAT(3(F4.1,2x)) !write format remember
END DO
!do your analysis here with the data
CLOSE(10) !close input file
CLOSE(5) !close output file
END PROGRAM examp4
Programming with Fortran II
Fortran File input and output
Reading Data from different directory

Reading Data from different directory

If data is in a directory different from the source program, then the


path to the directory is required
Assumed the data below is saved on the desktop as examp5.txt
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
Let assumed that the path to the data is /home/ohene/Desktop
Of course you know how to check the path of directory using pwd
(! last semester lecture 1)
The path /home/ohene/Desktop will declared as character using
parameter attributes. what does it mean?
During the opening of the file, the path to data will be joined with
the filename (examp5.txt) using the character operator
concatenation (//)
Programming with Fortran II
Fortran File input and output
Reading Data from different directory

PROGRAM examp5
!how to read/write from/into file in a different directory
IMPLICIT NONE
CHARACTER (LEN = *), PARAMETER :: &
dir=”/home/ohene/Desktop/” !path to data declared as dir
INTEGER, PARAMETER :: nrow=4, ncol=4 !# of rows and columns
INTEGER, DIMENSION(nrow,ncol) :: mydata !data declaration
INTEGER ::i, j !loop iterators
OPEN(1,FILE=dir//’examp5.txt’,ACTION=’READ’) !open input file
OPEN(5,FILE=dir//’output5.txt’,ACTION=’WRITE’) !open outputfile
DO i=1,nrow
READ(1,*) (mydata(i,j),j = 1,ncol) !read data from file
WRITE(5,’(4(I2, 2x))’)(mydata(i,j), j= 1,ncol) !write data
END DO
!Do your analysis with the data here
CLOSE(1); CLOSE(5) !close files
END PROGRAM examp5
Programming with Fortran II
Fortran File input and output
Practical session

Practical session using meteorological data

Example ::
Seasonal mean
Inter-seasonal variabilities
Using Gunplot to plot the output
Programming with Fortran II (MET 254) eoasare
Fortran File input and output
Lab1

A file containing daily temperature (min, max) and rainfall is provided.


We writing a fortran program to read the data and perform the following
task

1 estimate rainfall anomaly over the study period (2009 - 2013)

rain − rain
rain
where rain is monthly recorded rainfall and rain is the mean rainfall
over the period (2009 - 2013)

2 Plot the results using gnuplot


Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics

GNUPLOT can display the manuals for its commands e.g. type help plot to get
information on the plot command
Commands can be shortened e.g. rep instead of replot or p instead of plot or lt
instead of linetype
reset restores the defaults If you want to use more than one GNUPLOT
command in one line, you have to separate the commands by semicolon (;)
GNUPLOT comments start with #
Start GNUPLOT by typing gnuplot on the terminal, in this case you want to use
GNUPLOT interactively
By default, GNUPLOT will plot the data using points
To start GNUPLOT, make sure you are in the ”data“ directory first, else you
will have to specify the path to the file
GNUPLOT not only reads data from files, it can also plot analytical functions
GNUPLOT has several formatting parameters that can be used to change the
appearance of a plot. These parameters are accessed using the set command.
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics

Graphs of scientific data need the following:


Title (or figure caption)
What are you plotting against what?
(Caption) What do the lines mean?
Axis labels
Units
Example of plot command in gnuplot
plot with p ”filename.dat“ u 1:2 w lp
where
p stands for plot
u stands for using (columns)
w stands for with
lp stands for linespoints
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics

You may use a # character to comment a line out. If you wish to wrap a
command over more than one line, add a \ character to the end of the previous
line. For example:
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics

Output formats
By default, screens are displayed to the standard output. The set output
command redirects the display to the specified file or device.
Use set terminal to tell gnuplot what kind of output to generate. Several
terminals have many additional options. You can check your current terminal
with show terminal
The simple synatx is

set output ’filename.ext’


set terminal postscript
replot
The terminal can be postscript, png, eps etc
Other format options can be added
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics

The previous is just for gnuplot environemnt, however we can also use the shell
for gnuplot scripts
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics

If missing data exist in data series, you can specified to leave those missing
values
set datafile missing ”put the missing value here“
Example
set datafile missing ”-9999“
set datafile missing ”NAN“
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics

timefmt command applies to timeseries where data are composed of


dates/times. Plot data with date as x- axis or y-axis
The syntax
set timefmt ”<format string>“
The string argument tells gnuplot how to read timedata from the datafile. The
valid formats are:
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics

Example
if the data is of the form
#Date MFT
2010/Jan 37 49 86
2010/Feb 12 17 29
... .... .... ....
... .... .... ....
2012/Jul 67 99 166
Then xtics can be set as follows
set xdata time # set axis for data format
set timefmt ”%Y/%b” # defined the format as in the data
set format x ”%Y/%b” # set xtics format
set xrange[”2010/Jan”:”2012/Jul”] # set xtics range
The data can be plotted afterwards

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy