<<

THE UNIVERSITY

LIVERPOOL

Fortran Course Notes

AC Marshall with help from JS Morgan and JL Schonfelder

Thanks to Paddy OBrien

University of Liverp o ol

Contents

Intro duction to Systems

What is a Computer

What is Hardware and Software

Telling a Computer What ToDo

Some Basic Terminology

How Do es Computer Memory Work

Numeric Storage

What Are Computer Programs

Programming Languages

Highlevel Programming Languages

An Example Problem

An Example Program

Analysis of Temp erature Program

A Closer Lo ok at the Sp ecication Part

A Closer Lo ok at the Execution Part

HowtoWrite a

A Quadratic Equation Solver

The Problem Sp ecication

The Algorithm

The Program

The Testing Phase

Discussion

Software Errors

Compiletime Errors

Runtime Errors

The Compilation Pro cess

Switches

Intro duction

The Course i

Evolution

A Brief History of Fortran

Drawbacks of Fortran

New Fortran Features

Advantages of Additions

Language Obsolescence

Obsolescent Features

Arithmetic IF Statement

ASSIGN Statement

ASSIGNed GOTO Statement

ASSIGNed FORMAT Statement

Hollerith Format Strings

PAUSE Statement

REAL and DOUBLE PRECISION DOlo op Variables

Shared DOlo op Termination

Alternate RETURN

Branching to an END IF

Undesirable Features

Fixed Source Form

Implicit Declaration of Variables

COMMON Blo cks

Assumed Size Arrays

EQUIVALENCE Statement

ENTRY Statement

Object Oriented Programming

Fortran Object Oriented Facilities

Data Abstraction

Data Hiding

Encapsulation

Inheritance and Extensibility ii

Polymorphism

Reusability

Comparisons with C

Fortran Programming

Example of a Fortran Program

Co ding Style

Language Elements

Source Form

Free Format Co de

Signicant Blanks

Comments

Names

Statement Ordering

Data Objects

Intrinsic Typ es

Literal Constants

Implicit Typing

Numeric and Logical Declarations

Character Declarations

Constants Parameters

Initialisation

Examples of Declarations

Expressions and Assignment

Expressions

Assignment

Intrinsic Numeric Op erations

Relational Op erators

Intrinsic Logical Op erations

Intrinsic Character Op erations iii

Character Substrings

Concatenation

Op erator Precedence

Precedence Example

Precision Errors

IF Statement

IF Construct

Nested and Named IF Constructs

Conditional Lo ops

Conditional Cycle Lo ops

Named and Nested Lo ops

DO WHILE Lo ops

Indexed DO Lo op

Examples of Lo op Counts

Scop e of DO Variables

SELECT CASE Construct

Mixing Objects of Dierent Typ es

Mixed Numeric Typ e Expressions

Mixed Typ e Assignment

Integer Division

Intrinsic Pro cedures

Typ e Conversion Functions

Mathematical Intrinsic Functions

Numeric Intrinsic Functions

Character Intrinsic Functions

Simple Input Output

PRINT Statement

READ Statement iv

Arrays

ArrayTerminology

Declarations

Array Conformance

Array Element Ordering

Array Syntax

Whole Array Expressions

Visualising Array Sections

Array Sections

Printing Arrays

Input of Arrays

Array IO Example

Array Inquiry Intrinsics

Array Constructors

The RESHAPE

Array Constructors in Initialisation Statements

Allo catable Arrays

Deallo cating Arrays

Masked Assignment Where Statement

Masked Assignment Where Construct

Vectorvalued Subscripts

Selected Intrinsic Functions

Random Numb er Intrinsic

Vector and Matrix Multiply Intrinsics

Maximum and Minimum Intrinsics

Array Lo cation Intrinsics

Array Reduction Intrinsics

Program Units

Main Program Syntax

Main Program Example v

Pro cedures

Functions

Argument Asso ciation

Lo cal Objects

Argument Intent

Scop e

Host Asso ciation

Example of Scoping Issues

SAVE Attribute

Keyword Arguments

Optional Arguments

Optional Arguments Example

Pro cedures and ArrayArguments

Explicitshap e Arrays

Assumedshap e Arrays

Automatic Arrays

SAVE Attribute and Arrays

Explicit Length Character Dummy Arguments

Assumed Length Character Dummy Arguments

Arrayvalued Functions

Charactervalued Functions

Side Eect Functions

Recursive Pro cedures

Recursive Function Example

Recursive Example

Object Orientation

Stack Simulation Example

Stack Example Program

ReusabilityModules vi

Restricting Visibility

The USE Renames Facility

USE ONLY Statement

Mo dules

Mo dules General Form

Pointers and Targets

Pointer Status

Pointer Declaration

Target Declaration

Pointer Manipulation

Pointer Assignment

Pointer Assignment Example

Asso ciation with Arrays

Dynamic Targets

Automatic Pointer Attributing

Asso ciation Status

Pointer Disasso ciation

Pointers to Arrays vs Allo catable Arrays

Practical Use of Pointers

Pointers and Pro cedures

Pointer Valued Functions

Pointer I O

Derived Typ es

Sup ertyp es

Derived Typ e Assignment

Arrays and Derived Typ es

Derived Typ e IO

Derived Typ es and Pro cedures

Derived Typ e Valued Functions

POINTER Comp onents of Derived Typ es vii

Pointers and Lists

Linked List Example

Arrays of Pointers

Mo dules Typ e and Pro cedure Packaging

Derived Typ e Constructors

Generic Pro cedures

Generic Interfaces Commentary

Derived Typ e IO

Overloading Intrinsic Pro cedures

Overloading Op erators

Op erator Overloading Example

Dening New Op erators

Dened Op erator Example

Precedence

Userdened Assignment

Dened Assignment Example

Semantic Extension Example

Yet Another Example

More on Object Oriented Programming byJSMorgan

Semantic Extension Mo dules

Semantic Extension Example

Complex Data Typ e

Complex Intrinsics

Parameterised Intrinsic Typ es

Integer Data Typ e byKind

Constants of Selected Integer

Real KIND Selection

Kind Functions

Expression Evaluation

Logical KIND Selection viii

Character KIND Selection

Kinds and Pro cedure Arguments

Kinds and Generic Interfaces

More Intrinsics

Manipulation Intrinsic Functions

Array Construction Intrinsics

MERGE Intrinsic

SPREAD Intrinsic

PACK Intrinsic

UNPACK Intrinsic

TRANSFER Intrinsic

Input Output

OPEN Statement

READ Statement

WRITE Statement

FORMAT Statement FMT Sp ecier

Edit Descriptors

Other IO Statements

External Pro cedures

External Subroutine Syntax

External Subroutine Example

External Function Syntax

Function Example

Pro cedure Interfaces

Example

Required Interfaces

Pro cedure Arguments

The INTRINSIC Attribute

The EXTERNAL Attribute

Pro cedure Arguments Example ix

Object Initialisation

DATA Statement

DATA Statement Example

Data Statement Implied DO Lo op

Handling Exceptions

GOTO Statement

GOTO Statement Example

RETURN and STOP Statements

Fortran

Rationale by Craig Dedo

FORALL

Nested WHERE Construct

PURE Pro cedures

Elemental Pro cedures

Improved Initialisations

Automatic Deallo cation

New Initialisation Features

Remove Conicts With IEC

Minimum Width Editing

Namelist

CPU TIME Intrinsic Subroutine

MAXLOC and MINLOC Intrinsics

Deleted Features

New Obsolescent Features

Language Tidyups

High Performance Fortran

Compiler Directives

Visualisation of Data Directives

ASCI I Collating Sequence x

References xi

Mo dule

Fundamentals Of Computer

Programming

Intro duction to Computer Systems

What is a Computer

The following schematic diagram gives the layout of a Personal Computer PC most single user

systems follow this general design

Main memory

Keyboard CPU VDU

Disc drive

The comp onents p erform the following tasks

CPU Central Pro cessor Unit doesthework fetches stores and manipulates values

that are stored in the memory Pro cessors come in all dierent shap es and sizes

there are many dierent typ es of architectures which are suited to a variety of dierent tasks

We do not consider any particulartyp e of CPU is this course

Main memory RAM Random Access Memory used to store values during

execution of a program It can e written to and read from at any time

Intro duction to Computer Systems

Disc drive hard or oppy p ermanently stores les programs and data Hard discs

are generally lo cated inside the machine and come in a variety of dierent sizes and sp eeds

They do not in fact store les p ermanently they often go wrong and so must undergo a

backup at regular intervals The oppy disc drive allows a user to make his or her own back

up of imp ortant les and data It is very imp ortant to keep backups Do not b e caught out

you maywell lose all your work

Keyb oard allows user to input information Nowadays most keyb oards have more or less

the same functionality

VDU Visual Display Unit visually outputs data There are numerous typ es of VDU

diering in the resolution dots p er inch and the numb er of colours that can b e represented

Printer allows a hard copytobemade Again there are many dierent typ es of printers

available for example line printers dotmatrix printers bubble jet printers and laser printers

These also dier in their resolution and colour palette

The last four are known as p eripheral devices

A go o d PC could contain

Intel Pentium P CPU

MBytes RAM main memory

GByte hard disc

SVGA monitor

IBM PC keyb oard

In addition a system may include

printer for example an HP LaserJet

soundcard and sp eakers

CD ROM drive Read Only Memory

SCSI scuzzy disc fast

oppy disc drive for backing up data

network card

What is Hardware and Software

A computer system is made up from hardware and software

Hardware is the physical medium for example

circuit b oards

pro cessors

Septemb er University of Liverp o ol

Telling a Computer What ToDo

keyb oard

A piece of software is a computer program for example

an op erating system

an editor

a compiler

aFortran program

The software allows the hardware to b e used Programs vary enormously in size and complexity

Telling a Computer What ToDo

To get a computer to p erform a sp ecic task it must b e given a sequence of unambiguous instructions

ora program

We meet many examples of programs in everyday life for example instructions on how to assemble a

b edside cabinet These instructions are generally numb ered meaning that there is a sp ecic order to

b e followed they are also supp osed to b e precise so that there is no confusion ab out what is intended

insert the spigot into hole A

apply glue along the edge of side panel

press together side and top panels

attach toggle pin B to gromit C

and so on

If these instructions are not followed to the letter then the cabinet would turn out wonky

Some Basic Terminology

It is necessary to cover some terminology Hop efully much of it will b e familiar you will hear many

of the terms used throughout the course

Bit is short forBinary Digit have value of or or on or oor true or false

Bits makeup

make up KByte KiloByte or K Why I hear you ask Because



KBytes make up MByte MagaByte orM

MBytes make up GByte GigaByte or G

all machines have a wordsize a fundamental unit of storage for example bits bits etc

The size of a word in Bytes diers b etween machines APentium based machine is bit

Fortran Course Notes File CourseNotesps

Intro duction to Computer Systems

a op is a oating p oint op eration p er second A oating p oint op eration o ccurs when two real

numb ers are added Todaywe talk of megaops or even gigaops

parallel pro cessing o ccurs when twoormore CPUs work on solution of the same problem at

the same time

How Do es Computer Memory Work

In this hyp othetical example wordsize is taken to b e bits

3F2910101110 3F2A

3F2B 3F2C

A computers memory is addressable Each lo cation is given a sp ecic numb er which is often repre

sented in base for example C Hexadecimal digits are as follows

A B C D E F A B F The CPU is able to read to and write from

a sp ecied memory lo cation at will Groups of memory lo cations can b e treated as a whole to allow

more information to b e stored Using the cryptic hexadecimal identiers for memory lo cations is very

awkward so Fortran allows English names to b e used instead this allows programs to make sense

to a casual reader

Even when the computer has just been turned on each memory lo cation will contain some sort of

value In this case the values will b e random In the general case the values will b e those that remain

from the previous program that used the memory For this reason it is very imp ortant to initialise

memory lo cations b efore trying to use the values that they are storing

All CPUs have an instruction set or language that they understand Eventually all Fortran

programs must be translated or compiled into instructions from this set Roughly sp eaking all

pro cessors have the same sort of instructions available to them The CPU can say things like fetch

me the contents of memory lo cation FCor write this value to lo cation AF This is the basis of

howallprograms work

Consider the following sequence of assembler co de instructions

LDA FC load fetch the contents of FC

ADD F add to this the contents of F

STO FA store the value in lo cation FA

The sequence of instructions which is meant only for illustrative purp oses eectively adds two numb ers

together and stores the result in a separate memory lo cation Until when the rst dialect of Fortran

was develop ed all computer programs were written using assembler co de It was then

working for IBM who prop osed that a more economical and ecient metho d of programming their

computer should b e develop ed The idea was to design a language that made it p ossible to express

mathematical formulae in a more natural way than that currently supp orted by assembler languages

The result of their exp eriment was Fortran short for IBM Mathematical Formula Translation System

This new language allowed the ab ove assembler instructions to be written less cryptically as for

example

K I J

Septemb er University of Liverp o ol

Numeric Storage

A compiler would then translate the ab ove assignment statement into something that lo oks likethe

assembler co de given ab ove

Numeric Storage

In general there are twotyp es of numb ers used in Fortranprograms INTEGERs whole numb ers

and REALs oating p oint numb ers

INTEGERs are stored exactly usually in range however they are not stored in the

format hinted at in the previous section but in a sp ecial way that allows addition and subtraction to

be performed in a straightforward way

REALs are stored approximately and the space they o ccupy is partitioned into a mantissa and an

exp onent In the following numb er the mantissa is and the exp onent is

In a REAL numb er the exp onent can only take a range of values if the exp onent is exp ected

to b e large then it may b e necessary to use a numeric storage unit that is capable of representing larger

values for example DOUBLE PRECISION values

It is p ossible for aprogram to throwanumeric exception such as overow which o ccurs when

numb er is outside of supp orted range for example a real numb er where exp onent is to o big or

underow which is the opp osite the numb er is to o close to zero forrepresentation for example a

real numb er where the exp onent is to o small

In Fortran the KIND mechanism allows the user to sp ecify what numeric range is to b e supp orted

This allows programs to b e numerically portable Dierent computer systems will allow numb ers of

diering sizes to b e represented by one word It is p ossible that when a program has b een moved from

one computer system to another it may fail to execute correctly on the new system b ecause underow

or overow exceptions are generated The KIND mechanism combats this serious problem

CHARACTERsvariables are stored dierently

What Are Computer Programs

Programming Languages

Computers only understand binary co des so the rst programs were written using this notation This

form of programming was so on seen to b e extremely complex and errorprone so assembler languages

were develop ed So on it was realised that even assembler languages could b e improved on Todaya

go o d must b e

totally unambiguous unlike natural languages for example English old women and men

suck eggs do es this mean that men or old men suck eggs

expressive it must b e fairly easy to program common tasks

practical it must b e an easy language for the compiler to translate

simple to use

All programming languages have a very precise syntax or grammar This will ensure that a

syntacticallycorrect program only has a single meaning

Fortran Course Notes File CourseNotesps

What Are Computer Programs

Highlevel Programming Languages

Assembler co de is a LowLevel Language It is socalled b ecause the structure of the language

reects the instruction set and architecture of the CPU A can get very close to the

physical hardware Lowlevel languages allow very ecient use of the machine but are dicult to use

Fortran Fortran ADA C and Java are examples of HighLevel Languages They provide a

much higher degree of abstraction from the physical hardware They also allowfor p ortable programs

to b e written ie programs that will run on a variety of dierent systems and which will pro duce the

same results regardless of the platform As well as having the ab ove b enets highlevel languages are

more expressive and secure and are much quicker to use than lowlevel languages In general however

awell written assembler program will run faster than a highlevel program that p erforms the same task

At the end of the day an program that runs on a CPU must still be represented as a

series of binary digits This is achieved by compiling translating a highlevel program with a sp ecial

piece of software called a compiler are incredibly complicated programs that accept other

programs as input and generate a binary executable object le as output

An Example Problem

Consider the following problem which is suitable for solution by computer

o o

Toconvert from FFahrenheit to C Centigrade we can use the following formula

c f

o

Toconvert from C to K Kelvin weadd

A sp ecication of the program could b e that it would prompt the user for a temp erature expressed in

degrees Fahrenheit perform the necessary calculations and print out the equivalent temp eratures in

Centigrade and Kelvin

An Example Program

Aprogram which follows the ab ove sp ecication is given b elow

PROGRAM TempConversion

IMPLICIT NONE

INTEGER DegF DegC K

PRINT Please type in the temp in F

READ DegF

DegC DegF

PRINT This is equal to DegC C

K DegC

PRINT and K K

END PROGRAM TempConversion

This program in this case called Tempf can b e compiled using the NAg v Fortran compiler

The compiler is invoked on the Unix command line as follows

Septemb er University of Liverp o ol

Analysis of Temp erature Program

chadadamm f Tempf

NAg Fortran compiler v New Debugger

If the program has b een written exactly as ab ove then there will not b e any error messages or diag

nostics The case where a program contains mistakes will b e covered later The compiler pro duces

executable co de which is stored by default in a le called aout It is p ossible to give this le a

dierent name this is discussed later The executable le can b e run bytyping its name at the Unix

prompt

chadadamm aout

Please type in the temp in F

This is equal to C

and K

The program will start executing and will print out Please type in the temp in F on the screen

the computer will then wait for a value to b e entered via the keyb oard As so on as the required input

has b een supplied and the Return key pressed the program will continue Almost instantaneouslythe

equivalent values in Centigrade and Kelvin will app ear on the screen

Analysis of Temp erature Program

The co de is delimited by PROGRAM END PROGRAM statements in other words these two lines mark

the b eginning and end of the co de Between these lines there are two distinct areas

Sp ecication Part

This is the area of the program that is set aside for the declarations of the named memory lo cations

or variablesthatare used in the executable areaoftheprogram As well as supplying variable

names it is also necessary to sp ecify the typ e of data that a particularvariable will hold This

is imp ortant so that the compiler can work out how store the value held bya variable It is also

p ossible to assign an initial values to a variable or sp ecify that a particular memory lo cation holds

a constant value a readonly value that will not change whilst the program is executing These

techniques are very useful

Execution Part

This is the area of co de that performs the useful work In this case the program do es the

following

prompts the user for input

reads input data Deg F

o

calculates the temp erature in C

prints out this value

calculates the temp erature in Kelvin and

prints out this value

Fortran Course Notes File CourseNotesps

What Are Computer Programs

A Closer Lo ok at the Sp ecication Part

There are a couple more p oints that should b e raised The IMPLICIT NONE statement should always

be present in every Fortran program unit Its presence means that all variables mentioned in the

program must b e declared in the sp ecication part A common mistake whilst co ding is to mistyp e a

variable name if the IMPLICIT NONE statement is not present then the compiler will assume that the

mistyp ed variable name is a new hitherto unmentioned variable and will use whatever value happ ened

to b e in the memory lo cation that the variable refers to An error such as this caused the US Space

Shuttle to crash

The third line of the program declares three INTEGER whole numb er variables there are a numb er of

other variable typ es that can b e used in dierent situations

REAL real numb ers ie no whole numb ers eg REAL variables can

hold larger numb ers than INTEGERs

LOGICAL can only take one of two vaules TRUE or FALSE

CHARACTER contains single alphanumeric character eg a

CHARACTERLEN contains alphanumeric characters A numb er of consecutive alphanu

meric characters are known as a string

user dened typ es combination of the ab ove see later

Fortran is not case sensitive K is the same as k

A Closer Lo ok at the Execution Part

Let us nowlookatthepart of the program that do es the actual work

PRINT Please type in the temp in F writes the string b etween the quotes to the

VDU screen

READ Deg F reads a value from the keyb oard and assigns it to the INTEGER variable Deg F

Deg C Deg F this is an assignment statement The expression on the

RHS is evaluated and then assigned to the INTEGER variable Deg C This statement contains a

numb er of op erators

is the multiplication op erator

is the subtraction op erator

is the assignment op erator

The Fortran language also contains and op erators for addition and division

Division is much harder than any other op eration for a CPU to p erformittakes longer so uses

more resources for example if there is a choice b etween dividing by or multiplying by

the latter should b e selected

C C displays a string on the screen followed by PRINT This is equal to Deg

the value of a variable Deg Cfollowed by a second string C

By default input is from the keyb oard and output to the screen

Septemb er University of Liverp o ol

HowtoWrite a Computer Program

How to Write a Computer Program

There are four general phases during the development of any computer program

sp ecify the problem

analyse and break down into a series of steps towards solution ie design an algorithm

write the Fortran co de

compile and run ie test the program

When writing a computer program it is absolutely vital that the problem to b e solved is fully understo o d

A go o d p ercentage of large programming projects run into trouble owing to a misunderstanding of what

is actually required The sp ecication of the problem is crucial It is usual to write a detailed sp ec

of the problem using a natural language eg English Unfortunately it is very easy to write an

ambiguous sp ecication which can b e interpreted in a numb er of ways by dierent p eople In order to

combat this a numb er of Formal Metho ds of sp ecication have b een develop ed These metho ds are

often highlevel abstract mathematical languages which are relatively simple to convert to highlevel

programs in some cases this can b e done automatically Examples of such languages are Z and VDM

We do not prop ose to cover such sp ecication languages here For the purp oses of learning Fortran

a simple natural language sp ecication is adequate

Once the problem has b een sp ecied it needs to b e broken down into small steps towards the solution

in other words an algorithm should b e designed It is p erfectly reasonable to use English to sp ecify

each step This is known as pseudoco de

The next two phases go handinhand they are often known as the co detestdebug cycle and it is

often necessary to perform the cycle a numb er of times It is very rare that a program is written

correctly on the rst attempt It is common to maketyp ographical errors which are usually unearthed

by the compiler Once the typ os have b een removed the program will b e able to b e compiled and an

executable image generated Again it is not uncommon for execution to exp ose more errors or bugs

Execution may either highlight runtime errors which o ccur when the program tries to p erform illegal

op erations eg divide by zero ormay reveal that the program is generating the wrong answers The

program must be thoroughly tested to demonstrate that it is indeed correct The most goal

should b e to supply test data that executes every line of co de There are many software to ols that

generate statistical rep orts of co de coverage such as the Unix utilityor the more comprehensive

LDRA Testb ed

A Quadratic Equation Solver

This section shows the various steps that are needed when designing and writing a computer program

to generate the ro ots of a quadratic equation

The Problem Sp ecication

Write a program to calculate the ro ots of a quadratic equation of the form



ax bx c

Fortran Course Notes File CourseNotesps

What Are Computer Programs

The ro ots are given by the following formula

p



b b ac

x

a

The Algorithm

READ the values of the co ecients a b and c from the keyb oard

if a is zero then stop as we do not have a quadratic equation



calculate value of discriminant D b ac

b

if D is zero then there is one ro ot

a

p p

b D D b

and if D is then there are two real ro ots

a a

p p

bi D bi D

if D is there are two complex ro ots and

a a

PRINT solution

The Program

The following program is one solution to the problem

PROGRAM QES

IMPLICIT NONE

INTEGER a b c D

REAL RealPart ImagPart

PRINT Type in values for a b and c

READ a b c

IF a THEN

Calculate discriminant

D bb ac

IF D THEN one root

PRINT Root is ba

ELSE IF D THEN real roots

PRINT Roots arebSQRTREALDa

and bSQRTREALDa

ELSE complex roots

RealPart ba

Since D calculate SRQT of D which will be ve

ImagPart SQRTREALDa

PRINT st Root RealPart ImagPart i

PRINT nd Root RealPart ImagPart i

END IF

ELSE a

a is equal to so

PRINT Not a quadratic equation

END IF

END PROGRAM QES

Septemb er University of Liverp o ol

The Testing Phase

The Testing Phase

As the basic goal we want to ensure that each and every line of the program has b een executed

Lo oking at the co de we need the following test cases

discriminant greater than zero real valued ro ots

discriminant equals zero single real valued ro ot

discriminant less than zero complex valued ro ots

co ecient a is zero not a quadratic equation

These four situations can b e seem to corresp ond to each of the four PRINT statements in the program

The following values of co ecients should exercise each of these lines

a b and c

a b and c

a b and c

a b and c

Below is what happ ens when the ab ove test data is supplied as input to our program

uxaadamm aout

Type in values for a b and c

Roots are and

uxaadamm aout

Type in values for a b and c

Root is

uxaadamm aout

Type in values for a b and c

st Root i

nd Root i

uxaadamm aout

Type in values for a b and c

Not a quadratic equation

It can b e seen that every line has b een executed and in each case the correct results have b een pro duced

Discussion

The previous program intro duces some new ideas

Fortran Course Notes File CourseNotesps

What Are Computer Programs

comments anything on a line following a is ignored Comments are added solely forthe

b enet of the programmer often a program will b e maintained by a numb er of dierent p eople

during its lifetime Adding useful and descriptive comments will b e invaluable to anyb o dy who

has to mo dify the co de There is nothing wrong with having more comments in a program than

there are executable lines of co de

IF construct dierent lines are executed dep ending on the value of the Bo olean expression

IF statements and constructs are explained more fully in Sections and

relational op erators is equal to or is greater than Relational op erators see

allow comparisons to be made between variables There are six such op erators for use

between numeric variables the remaining four are

greater than or equal to

not equal to

less than

less than or equal to

These op erators can also b e written in nonsymb olic form these are EQ GT GE NE

LT and LE resp ectively

nested constructs one control construct can b e lo cated inside another This is explained

more fully in Section

pro cedure call SQRTX returns square ro ot of X A pro cedure is a section of co de that

p erforms a sp ecic and common task Calculating the square ro ot of anumber is a relatively

common requirement so the co de to do this has b een written elsewhere and can b e called at any

p oint in the program This pro cedure requires an argument X to b e supplied this is the

numb er that is to b e square ro oted In this case the routine is an intrinsic pro cedure this

means that it is part of the Fortran language itself every compiler is b ound to include this

pro cedure Formore information see Section

typ e conversion in the ab ove call the argument X must b e REAL this is sp ecied in the

Fortran standard language denition In the program D is INTEGER REALD converts D to

b e real valued so that SQRT can b e used correctly Fora more detailed explanation see Section

Another useful technique demonstrated here is the precalculation of common subexpressions for

example in order to save CPU time we only calculate the discriminant D once

Software Errors

Errors are inescapable There are twotyp es of error compiletime or syntax errors and runtime

errors Errors are often known as bugs b ecause one of the very earliest computers started pro ducing

the wrong answers when a moth ew inside it and damaged some of its valves

Compiletime Errors

In quadratic equation solver program if we accidentally mistyp ed a variable name

RaelPart ba

Septemb er University of Liverp o ol

The Compilation Pro cess

then the compiler would generate a syntax error

uxaadamm f Quadf

NAg Fortran compiler v

Error Quadf line

Implicit type for RAELPART

detected at RAELPART

Error Quadf line

Symbol REALPART referenced but never set

detected at QESendofstatement

f terminated errors found by pass

The compiler is telling us that RAEL PART has not b een given an explicit typ e in other words it has

not b een declared in the sp ecication area of the co de It is also telling us that weare trying to print

out the value of REAL PART but that we have not actually assigned anything to it As you can see from

the ab ove compiler output error messages tend to b e obtuse at times A sign of a go o d compiler is

one that can give sp ecic and useful error messages rather than simply telling you that your program

do esnt make sense

Runtime Errors

If we had made the following typ o in our quadratic equation solver

RealPart ba

then the program would compile but up on execution wewould get a runtime error

uxaadamm aout

Type in values for a b and c

Arithmetic exception

Floating divide by zero aborting

Abort

the program is telling the CPU to divide b byzeroa As this is imp ossible our program crashes

and an error message is sent to the screen It is runtime errors likethis that mean it is absolutely

essential to thoroughly test programs b efore committing them for serious use

It is also p ossible to write a program that gives the wrong results this is likely to b e a bug in the

algorithm

The Compilation Pro cess

The NAg Fortran compiler is invoked by f followed by the lename of the program to b e compiled

f Quadf

This command

Fortran Course Notes File CourseNotesps

What Are Computer Programs

checks the program syntax

generates object co de

passes object co de to linker which attached libraries system IO etc and generates executable

co de in a le called aout

Step attaches co de which deals with amongst other things mathematical calculations and input from

the keyb oard and output to the screen This co de which is resident in a system is used with all

available compilers in other words the same IO library will b e used with C ADAorCprograms

This alleviates the need for each compiler to include a separate instance of these IO routines It is

p ossible that this step may give a linker error if pro cedures used in the co de cannot be found in a

library

Executable co de is pro cessor sp ecic Co de complied for an Intel Pentium will not run an a Sun SPARC

and viceversa If aprogram is moved to a dierent platform then it will need to b e recompiled If

the program conforms to the Fortran standard then the source co de will not need editing at all

Some compilers accept extensions to the Fortran standard If any of these extensions are used

the program will b e nonstandard conforming and may need signicant rewriting when compiled on a

dierent platform orby a dierent compiler

Compiler Switches

All compilers can b e invoked with a numb er of dierent options The eect of these options is explained

in the man pages or in the compiler manual The NAg compiler has a numb er for example

o outputlename gives executable a dierent name for example Quad

f Quadf o Quad

dryrun show but do not execute commands constructed by the compiler

hpf accept the extensions to Fortran as sp ecied by the High Performance Fortran Forum

info level set level of information messages generated by the compiler from to

time rep ort execution times

f Quadf o Quad time

Formore information ab out the compiler typ e

man f

Question Compilation and Editing

The following program calculates the ro ots of a quadratic equation

Septemb er University of Liverp o ol

Compiler Switches

PROGRAM QES

IMPLICIT NONE

INTEGER a b c D

REAL RealPart ImagPart

PRINT Type in values for a b and c

READ a b c

IF a THEN

Calculate discriminant

D bb ac

IF D THEN one root

PRINT Root is ba

ELSE IF D THEN real roots

PRINT Roots arebSQRTREALDa

and bSQRTREALDa

ELSE complex roots

RealPart ba

ImagPart SQRTREALDa

PRINT st Root RealPart ImagPart i

PRINT nd Root RealPart ImagPart i

END IF

ELSE a

PRINT Not a quadratic equation

END IF

END PROGRAM QES

Using an editor typ e the ab ove program into a le called QuadSolverf

Compile and run the program Verify the correctness of the co de by supplying the following test

data

a a b and c

b a b and c

c a b and c

d a b and c

Copy QuadSolverf into a new le called NewQuadSolverf

Edit this le and declare a new REAL variable called one over a

In the executable part of the co de set one over a to be equal to the value of a

Where ever this expression o ccurs replace it with one over a Why is this a go o d idea

D and where appropriate precalculate SQRTREALD Dene another new REAL variable called sqrt

and substitute this new variable in place of this expression

Use a dierent set of test data to that given ab ove to convince yourself that NewQuadSolverf

is a correct program

Change the name of the program to b e FinalQuadSolverf and compile the co de to pro duce

an executable le called FinalQuadSolver

Delete the original program QuadSolverf and the executable le aout

Question The Hello World Program

Write a Fortran program to print out Hello World on the screen

Fortran Course Notes File CourseNotesps

Mo dule

Intro duction to Fortran

Intro duction

Fortran has b een widely used by scientists and engineers foranumberofyears now It has b een a

very successful language but is nowshowing signs of age in the last few years there has b een a tendency

for p eople to drift away from Fortran and b egin to use C Ada or C The Fortran standard has

now b een revised to bring it up to date with a new improved language known informally as Fortran

b eing dened Comparisons have b een rightly drawn b etween the new Fortran standard and APL

ADA and C All three languages contain elements which make them the avour of the month

they are to some degree object oriented The criteria for what makes a language actually object

oriented is debatable but the new op erator overloading user dened typing and MODULE packaging

features of Fortran certainly help to forward its case Along with ADA and APL it uses the concept

of array op erations and reduction op erators Fortran also supp orts user dened generic pro cedures

to enhance usability but these are implemented in a simpler and more ecient waythaninADA

Here we highlight the new Fortran features which make language more robust and usable for

example of those mentioned ab ove many are objectbased facilities which makeitmore dicult to

make mistakes ordodaftthings Fortran is also comparable to ADA in the sense that it to o has

many restrictions detailed in the standard do cument meaning that mistakes which in other languages

such as C C and Fortran would b e syntactically correct but cause an odd action to be

taken are ruled out at compile time As an example of this if explicit interfaces are used then it

is not p ossible to asso ciate dummy and actual arguments of dierent typ es this was p ossible in

Fortran and was sometimes used in anger but generally indicated an error

The Course

Throughout the course it is assumed that the user has exp erience of Fortran or least one other

high level programming language such as Mo dula Pascal APL Ada Cor Algol and understands terms

like bits real numb ers precision and data structures

Fortran Evolution

A Brief History of Fortran

Fortran which originally sto o d for IBM Mathematical FORmula TRANslation System but has b een

abbreviated to FORmula TRANslation is the oldest of the established highlevel languages having

b een designed by a group in IBM during the late s The language b ecame so p opularintheearly

s that other vendors started to pro duce their own versions and this led to a growing divergence of

dialects by there were dierent compilers It was recognised that such divergence was not in

the interests of either the computer users or the computer vendors and so Fortran b ecame the

rst language to b e ocially standardised in it is quite common fortheFortran version numb er

to b e out of step with the standardisation year The publication of the standard meant that Fortran

A Brief History of Fortran

b ecame more widely implemented than any other language By the mid s virtually every computer

mini or mainframe was supplied with a standardconforming Fortran language pro cessing system

It was therefore p ossible to write programs in Fortran on any one system and b e reasonably condent

that these could b e moved fairly easily to work on any other system This and the fact that Fortran

programs could b e pro cessed very eciently led to Fortran b eing the most heavilyused programming

language for noncommercial applications

The standard denition of Fortran was up dated in the late s and a new standard ANSI X

was published by the American National Standards Institute This standard was subsequently

in adopted by the International Standards Organisation ISO as an International Standard IS

The language is commonly known as Fortran since the nal draft was actually

completed in and is the version of the language now in widespread use Compilers which usually

supp ort a small numb er of extensions have over the years b ecome very ecient The technology

which has b een develop ed during the implementation of these compilers will not b e wasted as it can

still b e applied to Fortran programs

The venerable nature of Fortran and the rather conservative character of the standard revision

left Fortran with a numb er of oldfashioned facilities that might b e termed deciencies orat

least infelicities Many desirable features were not available for example in Fortran it is very

dicult to represent data structures succinctly and the lack of any dynamic storage means that all

arrays must have a xed size which can not b e exceeded it was clear from a very early stage that a

new more mo dern language needed to b e develop ed Work b egan in early s on a language known

as Fortran x x was exp ected to b e in keeping with the previous names forFortran The work

to ok years partly b ecause of the desire to keep Fortran a strict subset and also to ensure that

eciency one of the b onuss of a simple language was not compromised Languages such as Pascal

ADA and Algol are a treat to use but cannot match Fortran for eciency

Fortran is a major development of the language but nevertheless it includes all of Fortran

as a strict subset and so any standard conforming Fortran program will continue to b e a valid

Fortran program The main reason for this is due to the vast amount of socalled dusty deck

programs that p opulate Scientic installations all over the world Many manyears have b een put into

writing these programs which after so many years of use ie intheeld testing are very reliable

Most of the dusty deck co des will b e Fortran but there are doubtless many lines of Fortran

to o

In addition to the old Fortran constructs Fortran allows programstobeexpressed in ways

that are more suited to a mo dern environment and has rendered obsolete many of the

mechanisms that were appropriate in Fortran Here wehavetried to present an approach to

programming which uses the new features of Fortran to go o d eect and which will result in p ortable

ecient safe and maintainable co de We do not intended to present a complete description of every

p ossible feature of the language

In Fortran some features of Fortran have b een replaced by b etter safer and more ecient

features Many of these features are to be lab elled as depracated and should not be used in new

programs Tools exist to eect automatic removal of such obsolescent features examples of these

are Pacic Sierra Researchs VAST and NA Softwares LOFT In addition these to ols p erform

diering amounts of vectorisation transliteration of serial structures to equivalent parallel structures

As the Fortran standard is very large and complex there are inevitably a small numb er of

conicts grey areas Such anomalies often only come to light when compliers are develop ed Since

standardisation many compilers have b een under development and a numb er of these anomalies have

b een identied A new standard Fortran will recitify these faults and extend the language in the

appropriate areas In the last couple of years the Fortran based language known as High Performance

Fortran HPF has b een develop ed This language contains the whole of Fortran and also includes

other desirable extensions Fortran will include many of the new features from HPF

Fortran Course Notes File CourseNotesps

Fortran Evolution

HPF is intended for programming distributed memory machines and intro duced directives For

tran structured comments to give hints on how to distribute data arrays amongst grids of non

homogeneous pro cessors The idea is to relieve the programmer of the burden of writing explicit

messagepassing co de the compilation system do es this instead HPF also intro duced a small numb er

of executable statements parallel assignments side eect free PUREpro cedures which have b een

adopted byFortran

Drawbacks of Fortran

By to days standards Fortran is outmo ded many other languages have b een develop ed which

allow greater expressiveness and ease of programming The main drawbacks have b een identied as

Fortran awkward or xed form source format

Each line in a Fortran program corresp onds to a single punched card with columns

meaning that each line can only b e characters long This causes problems b ecause any text

in columns onwards is simply ignored line numb ers used to b e placed in these columns In

this day and age this restriction is totally unnecessary

Other restrictions of Fortran

the rst columns are reserved for line numb ers

the th column can only b e used to indicate a line

comments can only b e initiated bymarking the rst column with a sp ecial character

only upp er case letters are allowed anywhere in the program

variable names can only b e characters long meaning that mnemonic and cryptic names

must b e used all the time maintenance unfriendly

no inline comments are allowed comments must b e on a line of their own

Lack of inherent parallelism

Fortran is supp osed to be a performance language to day High Performance Computing is

implemented on Parallel machines Fortran has no inbuilt way of expressing parallelism

In the past calls to sp ecially written vector subroutines have b een used or reliance has b een made

on the compiler to vectorise parallelise the sequential serial co de It is much more ecient to

give the user control of parallelism This has b een done to a certain extent by the intro duction

of parallel array syntax

Lack of dynamic storage

Fortran only allows static storage for example this means temp orary shortlived arrays

cannot b e created onthey nor can p ointers which are useful for implementing intuitive data

structures b e used All Fortran programs must declare arrays big enough for any future

problem size which is an awkward and very unattractive restriction absent in virtually all of the

current p opular highlevel languages

Lack of numeric p ortability

Problems arise with precision when Fortran co de from one machine to another

Many Fortran systems implement their own extensions to give greater precision this means

that the co de b ecomes nonp ortable Fortran has taken ideas for the various Fortran

extensions and improved them so that the new language is much more p ortable that b efore

Septemb er University of Liverp o ol

New Fortran Features

Lack of userdened data structures

In Fortran intuitive userdened data typ es were not available as they are in ADA

Algol C Pascal etc Their presence would make programming more robust and simpler In

Fortran there is no way of dening comp ound objects

Lack of explicit recursion

Fortran do es not supp ort recursion which is a very useful and succinct mathematical

technique In the past this had to b e simulated using a user dened stack and access routines

to manipulate stack entries Recursion is a fairly simple and a co de ecient concept and was

to all intents and purp oses unavailable

Reliance on unsafe storage and sequence asso ciation features

In Fortran global data is only accessible via the notoriously op entoabuse COMMON blo ck

The rules which applied to COMMON blo cks are very lax and the user could inadvertently do

quite horrendous things Fortran presents a new metho d of obtaining global data Another

technique which is equally as op en to abuse as COMMON blo cks is that a user is allowed to alias

an array using an EQUIVALENCE statement A great deal of errors stem for mistakes in these two

areas which are generally regarded as unsafe however there is no real alternative in Fortran

New Fortran Features

Fortran is a major revision of its predecessor many of the inadequacies of Fortran have b een

addressed

Fortran denes a new co de format which is much more like every other language

free format no reliance on sp ecic p ositioning of sp ecial characters

upto columns p er line

more than one statement p er line

inline comments allowed this makes it easier to annotate co de

upp er and lower case letters allowed makes co de more readable

it is virtually imp ossible to misplace a character now

longer and more descriptive object names upto characters

names can b e punctuated by underscores making then more readable

Parallelism can now be expressed using whole array op erations which include extensive slicing

and sectioning facilities Arithmetic maynow b e p erformed on whole arrays and array sections

Op erations in an array valued expression are conceptually p erformed in parallel

Tosupport this feature many parallel intrinsic functions have b een intro duced including reduction

op erations such as SUM add all elements in an array and return one value the sum and MAX

VAL scan all elements in an array and return one value the biggest This concept comes

from APL

The masked parallel assignment WHERE statement is also a new feature

The intro duction of dynamic heap storage means that p ointers and allo catable arrays can b e

implemented Temp orary arrays can now b e created onthey p ointers can b e used for aliasing

arrays or sections of arrays and implementing dynamic data structures such as linked lists and

trees

Fortran Course Notes File CourseNotesps

Fortran Evolution

To combat nonp ortability the KIND facility has b een intro duced This mechanism allows the

user to sp ecify the desired precision of an object in a p ortable way Typ e sp ecications can b e

parameterised meaning that the precision of a particular typ e can be changed by altering the

value of one constant Appropriate intrinsic inquiry functions are dened to query the precision

of given objects

Userdened typ es which are constructed from existing typ es can now be constructed For

example a typ e can b e dened to represent a D co ordinate which has three comp onents x y z

or a dierent typ e can be used to represent p ersonal details name age sex address phone

numb er etc Dening objects in this wayismore intuitive and makes programming easier and

less errorprone

Explicit recursion is now available For reasons of eciency the user must declare a pro cedure

to b e recursive but it can then b e used to call itself

Facilitypackaging has b een intro duced MODULEs replace many features of Fortran They

can b e used for global denitions of typ es objects op erators and pro cedures and can b e used

to provide functionality whose internal details are hidden from the user data hiding

Reshaping and retyping functions have b een added to the language which means that features

that relied on storage asso ciation such a EQUIVALENCE do not have to b e used

pro cedure interfaces which declare pro cedure and argument names and typ es can now b e sp ecied

this means that

programs and pro cedures can b e separately compiled more ecient development

array b ounds do not have to b e passed as arguments

array shap e can b e inherited from the actual argument

better typ e checking exists across pro cedure b oundaries

more ecient co de can b e generated

new control constructs have b een intro duced for example

DO ENDDO not part of Fortran this will reduce use of numeric lab els in the

program

DO WHILE lo op

the EXIT command for gracefully exiting a lo op

the CYCLE command for abandoning the current iteration of a lo op and commencing the

next one

named control constructs which are useful for co de readability

SELECT CASE control blo ck which is more succinct elegant and ecient than an IF

ELSEIF ELSEIF blo ck

Internal pro cedures are nowallowed Apro cedure is allowed to contain a further pro cedure with

lo cal scop e it cannot b e accessed from outside of the pro cedure within which it is dened

It is now p ossible to dene and overload op erators for derived and intrinsic data typ es which

mean that socalled semantic extension can be p erformed For example an arbitrary length

integer can be implemented using a linked list structure one digit per and then all the

intrinsic op erators dened overloaded so that this typ e can b e treated in the same way as all

other typ es The language thus app ears to have b een extended All intrinsic op erators

and and assignment can b e overloaded dened for new typ es

Septemb er University of Liverp o ol

Advantages of Additions

MODULEs also provide object based facilities forFortran for example it is p ossible to use a

mo dule to implement the ab ovementioned long integer data typ e all required facilities for

example denitions objects op erators overloaded intrinsics and manipulation pro cedures may

be packaged together in a MODULE the user simple has to USE this mo dule to have all the features

instantly available The mo dule can now b e used like a library unit

An ancillary standard The varying strings mo dule has b een dened and is implemented in

a mo dule When using this mo dule the user can simply declare an object of the appropriate

STRING which can b e manipulated in exactly the same fashion as the intrinsic typ e VARYING

character typ e All intrinsic op erations and pro cedures are included in the mo dule and are

therefore available for all objects of this typ e All the implementation details are hidden from the

user

useful libraries can b e written and placed in a mo dule

DATA subprograms are now redundant since a MODULE can b e used for the same purp ose

Advantages of Additions

The intro duction of the previously mentioned new features have had an impact on the general standing

of the language Fortran can b e thought of as b eing more natural more exible more expressive

more usable more p ortable and ab ove all safer

Even though Fortran is a subset of Fortran the user should steer away from unsafe features

of the new language Many dangerous features have b een sup erseeded by new features of Fortran

for example

COMMON blo cks use a mo dule

EQUIVALENCE use TRANSFER using EQUIVALENCE also reduces p ortability

reshaping of arrays across pro cedure b oundaries this used to b e p ossible when using assumed

sized arrays use the RESHAPE function at the call site

retyping of arrays across pro cedure b oundaries use TRANSFER

reliance on lab els has b een decreased

xed form source use free form

IMPLICIT NONE statement intro duced which if preset disallows implicit typing of variables In

Fortran undeclared variables were implicitly declared with the typ e b eing derived from the

rst letter of the variable name this meant that wrongly sp elled variable names could pass

through a compiler with no warning messages issued at all If the variable was referenced then

a totally random value the incumb ent value of the memory lo cation where the variable resides

would b e used with p otentially disastrous consequences

internal pro cedures pro cedures within pro cedures with lo cal scop e alleviate the need for the

awkward ENTRY statements ans statement functions

Language Obsolescence

Fortran has carried forward the whole of Fortran and also a numb er of features from existing

Fortran compilers This has b een done to protect the investment in the millions of lines of co de that

Fortran Course Notes File CourseNotesps

Language Obsolescence

have b een written in Fortran since it was rst develop ed Inevitably as mo dern features have b een

added many of the older features have b ecome redundant and esp ecially those using

Fortran for the rst time need to b e aware of the p ossible pitfalls in using them

Fortran has a numb er of features marked as obsolescent this means

they are already redundant in Fortran

b etter metho ds of programming already existed in the Fortran standard

programmers should stop using them

the standards committees intention is that many of these features will b e removed from the next

revision of the language Fortran

Obsolescent Features

Fortran includes the whole of Fortran as a subset warts and all but the sp ecication also

agged some facilities as obsolescent The following features maywell b e removed from the next revision

of Fortran and should not b e used when writing new programs Fortran retains the functionalityof

these features which can all b e b etter expressed using new syntax

Arithmetic IF Statement

It is a three waybranch statement of the form

IF expression lab el lab el lab el

Here expression is any expression pro ducing a result of typ e INTEGER REAL or DOUBLE PRECISION

and the three lab els are statement lab els of executable statements If the value of the expression is

negative execution transfers to the statement lab elled lab el If the expression is zero transfer

is to the statement lab elled lab el and a p ositive result causes transfer to lab el The same

lab el can b e rep eated

This relic of the original Fortran has been redundant since the early s when the logical IF and

computed GOTO were intro duced and it should b e replaced by an equivalent CASE or IF construct

ASSIGN Statement

Used to assign a statement lab el to an INTEGER variable the lab el cannot b e used as an integer though

it is generally used in a GOTO or FORMAT statement

ASSIGN lab el TO integervariable

ASSIGNed GOTO Statement

Historically this was used to simulate a pro cedure call b efore Fortran had pro cedures its use should

b e replaced by either an IF statement orbya pro cedure call

Septemb er University of Liverp o ol

Obsolescent Features

ASSIGNed FORMAT Statement

The ASSIGN statement can b e used to assign a lab el to an integer which is subsequently referred to in

an inputoutput statement

The same functionality can be obtained by using CHARACTER strings to hold FORMAT sp ecications

The FORMAT sp ecication can either b e this string or a p ointer to this string

Hollerith Format Strings

Used to represent strings in a format statement like this

WRITE

FORMATH TITLE OF PROGRAM

The use of Hollerith strings is outofdate as strings can now b e delimited by single or double quotes

WRITE

FORMATTITLE OF PROGRAM

PAUSE Statement

PAUSE was used to susp end execution until a key was pressed on the keyb oard

PAUSE stop co de

The stop co de is written out at the PAUSE new co de should use a PRINT statement forthe stop

co de and a READ statement which waits for input to signify that execution should recommence

REAL and DOUBLE PRECISION DOlo op Variables

In Fortran REAL and DOUBLE PRECISION variables can b e used in DOlo op control expressions

and index variables This is unsafe b ecause a lo op with real valued DOlo op control expressions could

easily iterate a dierent numb er of times on dierent machines a lo op with control expression

maylooponceortwice b ecause real valued numb ers are only stored approximately

could equal say or The rst evaluation would execute times whereas the second

would only give execution The solution to this problem is to use INTEGER variables and construct

REAL or DOUBLE PRECISION variables within the lo op

The following lo op is obsolescent

DO x

PRINT INTx

END DO

PRINT x

Fortran Course Notes File CourseNotesps

Language Obsolescence

Shared DOlo op Termination

A numb er of DO lo ops can currently be terminated on the same p ossibly executable statement

this causes all sorts of confusion when programs are changed so that the lo ops do not logically end on

a single statement any more

IF N GOTO

DO KN

DO JN

DO IN

AIJKAIJK

The simple solution is to use END DO instead

Alternate RETURN

This allows a calling program unit to sp ecify lab els as arguments to a called pro cedure as shown The

called pro cedure can then return control to dierent p oints in the calling program unit by sp ecifying

an integer parameter to the which corresp onds to a set of lab els sp ecied in the

argument list

CALL SUBxy

CONTINUE

CONTINUE

SUBROUTINE SUBXY

RETURN

RETURN

END

Use an INTEGER return co de and a GOTO statement or some equivalent control structure

Branching to an END IF

Fortran allowed branching to an END IF from outside its blo ck this feature is deemed obsolete

so instead control should b e transferred to the next statement instead or alternativelyaCONTINUE

statement could b e inserted

Undesirable Features

The following features are not marked as obsolescent yet can and indeed should b e expressed using

new syntax

Septemb er University of Liverp o ol

Fixed Source Form

Use free form source form as this is less errorprone and more intuitive

Implicit Declaration of Variables

Always use the IMPLICIT NONE statement in each program unit any undeclared variables will be

rep orted at compile time

COMMON Blo cks

One of the functions of mo dules is to provide global data this will b e expanded up on later

Assumed Size Arrays

It is recommended that instead of assumedsize arrays assumedshap e arrays b e used in new programs

instead With this class of array it is not necessary to explicitly communicate any information regarding

b ounds to a pro cedure however in this case an explicit interface must be provided If an arrayistobe

reshap ed or retyp ed across a pro cedure b oundary then the new intrinsics RESHAPE TRANSFER PACK

and UNPACK should b e used to achieve the desired eect

EQUIVALENCE Statement

EQUIVALENCE is often used forretyping or aliasing and sometimes for simulating dynamic workspace

This feature is considered to b e unsafe and nonp ortable and should not b e used Fortran oers

the TRANSFER intrinsic for retyping

a POINTER variable for aliasing

the ALLOCATABLE attribute for temp orary workspace arrays

ENTRY Statement

ENTRY statements allowpro cedures to b e entered at p oints other than the rst line This facility can

b e very confusing if this eect is desired then the co de should b e reorganised to take advantage of

internal pro cedures

Object Oriented Programming

In the last ten years Object Oriented Design and Object Oriented Programming has b ecome increasingly

popular languages such as C and Eiel have b een hailed as the programming languages of the

future but howdoesFortran compare

Programming paradigms have evolved over the years With each successive renement of program

ming style have come improvements in readability maintainability reliability testability complexity

Fortran Course Notes File CourseNotesps

Object Oriented Programming

power structure and reusability The rst computer programs were written in assembler languages and

primitive languages such as the original Fortran which p ossessed only the single statement IF and

GOTO statement to control the ow of execution even pro cedures had to b e simulated using a cunning

combination of ASSIGN and GOTOClearly the directed graphs of these early programs resembled a b owl

of spaghetti with a vast numb er of logical paths passing through the co de in an unstructured fashion

Each path of a program represents a unique combination of predicates which some argue must all

be tested in order to gain condence that the program will function correctly In Davis presents

some estimations of the p ossible numb er of paths through such an unstructured program a line



program can have up to p ossible paths

The next phase of intro duced the concept of a function co de mo dules could

b e written and the program partitioned into logical and to some extent reusable blo cks This had

the eect of reducing the complexityof the program less paths and improving the maintainability

readability and overall structure A go o d example of an advanced functional language is Fortran

If the line program of ab ove could b e split into four separate functions then the numb er of paths



would b e reduced to

Functional programming forced the user to adopt b etter programming practises however there still

existed many dimly lit back alleys where programmers can p erform dirty tricks In Fortran use

of the COMMON blo ck is one classic example Due to the absence of high level data structures see next

paragraph users were often reluctant to supply seemingly endless lists of objects as arguments to func

tions it was much easier to hide things b ehindthescenes in a COMMON blo ck which allows contiguous

areas of memory to b e available to pro cedures In Fortran it is also easy to inadvertently retyp e

parts of the memory leading to all sort of problems For example the following program was supplied

to the Sun f compiler which generated one warning

PROGRAM Duffer

DOUBLE PRECISION INIT

COMMON GOOF INIT A B

CALL WHOOPS

PRINT INIT INIT A A B B

END

SUBROUTINE WHOOPS

COMMON GOOF INIT A B

INIT

A

B

END

the following output was generated

INIT A B

With the intro duction of Algol the concept of was b orn chaotic jumps

around the co de were replaced by compact and succinct blo cks with a rigidly dened structure Ex

amples of such structures are lo ops and if blo cks Data was also allowed to b e structured through the

use of p ointers and structures Both these features allowed for greater mo dularity clarity and more

compact co de Fortran missed the b oat with regards to structured data however Fortran

has corrected this oversight With this new structure applied our line program will nowhavea



maximum of paths

The latest and most fashionable is ob jectoriented programming This

style of programming promotes software reusability mo dularity and precludes certain error conditions

Septemb er University of Liverp o ol

Fortran s Object Oriented Facilities

by packaging together typ e denitions and pro cedures for the manipulation of objects of that typ e

Fortran do es not have such an extensive range of objectoriented capabilities as say C but is

comparable to original ADAandprovides enough to b e of great use to the programmer

Fortran s Object Oriented Facilities

Fortran has some degree of object oriented facilities such as

data abstraction userdened typ es

data hiding PRIVATE and PUBLIC attributes

encapsulation Mo dules and data hiding facilities

inheritance and extensibility sup ertyp es op erator overloading and generic pro cedures

p olymorphism users can program their own p olymorphism by generic overloading

reusability Mo dules

Fortran had virtually no object oriented features at all Fortran adds much but by no means

all the required functionality As usual there is a trade o with eciency One of the ultimate goals of

Fortran is that the co de must b e ecient

Data Abstraction

It is convenient to use objects which mirror the structure of the entities which they mo del In Fortran

user derived typ es provide a certain degree of abstraction and the availability of p ointers allows fairly

complex data structures to b e dened Pointers are implemented in a dierent way from many languages

and are considerably less exible but more ecient than say p ointers in C As Fortran p ointers are

strongly typ ed their targets are limited but this leads to more secure and faster co de Fortran do es

not supp ort enumerated typ es but these can b e simulated in a semantic extension mo dule without

to o much trouble

Two main problems are the lack of parameterised derived typ es and the lack of subtyp es

Parameterised derived typ es are userdened typ es where the individual typ e comp onents have selectable

kinds The idea would b e to dene a skeleton typ e which could b e supplied with KIND values in such

a way that the individual comp onents are declared with these KINDs As currently dened derived

typ es can have kind values for the comp onents but they are xed for example the following twotyp es

are totally separate

TYPE T

INTEGERKIND sunzoom

REALKIND spock

END TYPE T

TYPE T

INTEGERKIND sunzoom

REALKIND spock

END TYPE T

Fortran Course Notes File CourseNotesps

Object Oriented Programming

If the kind selection could be deferred until object declaration then they could be considered to be

parameterised

Subtyp es are as their name suggests a sub class of a parent typ e A common example may be a

p ositive integer typ e which has exactly the same prop erties as an intrinsic INTEGER typ e but with a

restricted range Subtyp es are exp ensive to implement but provide range checking security

Data Hiding

Fortran supp orts fairly advanced data hiding Any object or pro cedure can have its accessibility

dened in a MODULE by b eing given a PRIVATE or PUBLIC attribute There is however a drawback in

that MODULEsmay inherit functionalityfrompreviously written MODULEsby using them but objects and

functionalitythatare PRIVATE in the useasso ciated mo dule cannot b e seen in the new mo dule There

really needs to b e a third typ e of accessibility which allows PRIVATE objects to b e accessible outside

their mo dule under certain circumstances This would allowfor much greater extensibility

Encapsulation

Encapsulation refers to bundling related functionality into a library or other such self contained package

whilst shielding the user from any worries ab out the internal structure

Encapsulation very closely aligned with data hiding and is available through MODULEs MODULE PROC

EDUREs and USE statements and backed up by the ability to rename mo dule entities or to selectively

imp ort only sp ecied objects

Inheritance and Extensibility

Fortran supp orts sup ertyp es meaning that userdened typ es can include other dened typ es and

ahierarchy can b e built up however this do es not apply in the other direction Fortran do es not

have subtyp es Due to the lack of functional and object inheritance cannot b e transmitted in

this fashion however ADA has subtyp es but is still not considered to b e an object oriented language

Being able to dene subtyp es which inherit access functions from the parent typ e is a very imp ortant

asp ect of object oriented programming and Fortran do es not supp ort this

Polymorphism

The generic capabilities of Fortran are very advanced however p olymorphism is not inherent in the

language and must b e programmed by the user Sp ecic pro cedures must always b e userwritten and

added to the generic interface In addition Fortran do es not supp ort dynamic binding an example

of this is the inability to resolve generic pro cedure calls at runtime The standard forbids generic

pro cedure names to b e used as actual pro cedure arguments the sp ecic name must b e used instead

Dynamic binding is generally thought to b e an exp ensive feature to have in the language and is not

included owing to eciency concerns

Many instances of p olymorphism are ruled out b ecause of the lack of subtyp es

Septemb er University of Liverp o ol

Comparisons with C

Reusability

MODULEs provide an easy metho d to access reusable co de Mo dules can contain libraries of typ es

object declarations and functions which can b e used by other mo dules Use of the mo dule facility must

b e encouraged and traditional Fortran programmers must try hard to program in this new way

Comparisons with C

In a pap er Fortran and available on the World Wide Web

httpcsepphyornlgovcsephtml

C and Fortran are compared and contrasted in their suitabilityfor computational scientic work

Fortran Course Notes File CourseNotesps

Mo dule

Elements of Fortran

Fortran Programming

Example of a Fortran Program

Consider the following example Fortran program

MODULE TriangleOperations

IMPLICIT NONE

CONTAINS

FUNCTION Areaxyz

REAL Area

REAL INTENT IN x y z

REAL theta height

theta ACOSxyzxy

height xSINtheta Area yheight

END FUNCTION Area

END MODULE TriangleOperations

PROGRAM Triangle

USE TriangleOperations

IMPLICIT NONE

REAL a b c Area

PRINT Welcome please enter the

lengths of the sides

READ a b c

PRINT Triangles area Areaabc

END PROGRAM Triangle

The program highlights the following

free format source co de

Executable statements do not have to start in or after column as they do in Fortran

MODULE TriangleOperations

Aprogram unit used to house pro cedures Similar to a C class

IMPLICIT NONE

Makes declaration of variables compulsory throughout the mo dule It applies globally within the

MODULE

CONTAINS

Sp ecies that the rest of the MODULE consists of pro cedure denitions

Example of a Fortran Program

FUNCTION Areaxyz

This declares the function name and the numb er and name of its dummy arguments

REAL Area function type

FUNCTIONs return a result in a variable which has the same name as the function in this case

Area The typ e of the function result must b e declared in either the header or in the declarations

The initiates a comment everything after this character on the same line is ignored by the

compiler

REAL INTENT IN x y z

The typ e of the dummy arguments must always b e declared they must b e of the same typ e as

the actual arguments

The INTENT attribute says howthearguments are to b e used

IN means the arguments are used but not redened

OUT says they are dened and not used

INOUT says that they are used and then redened

Sp ecifying the INTENT of an argument is not compulsory but is good practise as it allows the

compiler to detect argument usage errors

REAL theta height

The nal REAL declaration statement declares lo cal variables for use in the FUNCTION Such

variables cannot b e accessed in the calling program as they are out of scop e not visible to the

calling program

theta ACOSxyzxy

This statement assigns a value to theta and uses some mathematical op erators

multiplication

exp onentiation

division

addition

subtraction

The brackets parenthesis are used to group calculations as on a calculator and also to sp ecify

the argument to the intrinsic function reference ACOS

Intrinsic functions are part of the Fortran language and cover many areas the simplest and

most common are mathematical functions such as SIN and COS or MIN and MAX Many are

designed to act elementally on an array argument in other words they will perform the same

function to every element of an array at the same time

height xSINtheta Area yheight

This highlights two statements on one line The indicates that a new statement follows on the

same line Normally only one statement p er line is allowed

The function variable Area must b e assigned a value or else the function will b e in error

END MODULE this signies the end of the mo dule

PROGRAM Triangle

The PROGRAM statement is not strictly necessary but its inclusion is go o d practice There may

only b e one p er program

Fortran Course Notes File CourseNotesps

Fortran Programming

USE Triangle Operations tells the program to attach the sp ecied mo dule This will allow

the Area function to b e called from within the Triangle program

IMPLICIT NONE

An IMPLICIT NONE statement turns o implicit typing making the declaration of variables com

pulsory

REAL a b c Area

Declaration of real valued objects a b and c are variables and Area is a function name This

function must b e declared b ecause its name contains a value

PRINT Welcome please enter the

This PRINT statement writes the string in quotes to the standard output channel the screen

The at the end of the line tells compiler that the line continues and the at the start of the text

tells the compiler to insert one space and continue the previous line at the character following

the If the were at the start of the line or if there were no on the second line then the

string would have a large gap in it as the indentation would b e considered as part of the string

READ a b c

This READ statement waits for three things to b e input from the standard input keyb oard The

entities should b e separated byaspace Digits will b e accepted and interpreted as real numb ers

things other than valid numb ers will cause the program to crash

PRINT Triangles area Areaabc

This PRINT statement contains a function reference Area and the output of a string

The is an escap ed character and is transformed on output to a single Typing just a single

quote here would generate an error b ecause the compiler would it had encountered the end

of the string and would ag the character s as an error The whole string could be enclosed

by double quotes which would allow a single quote to b e used within the string without

confusion The same delimiter must b e used at each end of the string

The function call invokes the FUNCTION with the values of a b and c b eing substituted for x

y and z

a b and c are known as actualarguments

x y and z are known as dummyarguments

a b and c and x y and z are said to b e argument asso ciated

cannot refer to a b and c in the function they are not in scop e

END PROGRAM Triangle

An END PROGRAM statement terminates the main program

Co ding Style

It is recommended that the following co ding convention is adopted

Fortran keywords intrinsic functions and user dened typ e names and op erators should b e in

upp er case and user entities should b e in lower case but maystart with a capital letter

indentation should b e or spaces and should b e applied to the b o dies of program units control

blo cks INTERFACE blo cks etc

Septemb er University of Liverp o ol

the names of program units are always included in their END statements

argument keywords are always used for optional arguments

always use IMPLICIT NONE

Please note In order that a program ts onto a page these rules are sometimes relaxed here

Adopting a sp ecic and do cumented co ding style will make the co de easier to read and will allow

other p eople to b e instantly familiar with the style of co de

Language Elements

Source Form

The most basic rules in any programming language are those which govern the source form These

rules determine exactly how statements in a program are entered into the computer and how they

are displayed The source form rules are analogous to those fundamentals of natural language which

dene the alphab et used to express the words in the language the punctuation symb ols to b e used

how sentences are to b e written left to right up and down right to left etc These are the rules we

are going to describ e here

Free Format Co de

Fortran supp orts the new free format source form

characters p er line

extended character set

line continuation character

comment initiator

statement separator

signicant blanks

Fortran has two basically incompatible source forms an old form compatible with that used in

Fortran xed format and a new form more suited to the mo dern computing environment

free format The old form used a very strictly dened layout of program statements on lines This

was well suited to the expression of programs when the main metho d of entering programs into a

computer was by the use of stacks of cards with holes punched in them to represent the characters

of the program statements Such punched card systems also worked with a very restricted set of

characters only upp ercase letters for example were allowed The new form is designed to b e easier

to prepare and to read using the sort of keyb oard display that is now ubiquitous This new form uses

a much wider character set and it allows much greater freedom in laying out statements on a line It

is this new form that weare going to describ e here since this is the form wewould exp ect any new

programmer to employ The old form will not b e describ ed in any great detail

The old character in column metho d of line continuation is replaced byan at the end of a line

Only one is essential however if a string is to b e split then there should also b e an at the b eginning

Fortran Course Notes File CourseNotesps

Language Elements

of the text on the next line in order to preserve the spacing The continued line eectively b egins from

the character after the

PRINT This is a long constant continued from line to line

by use of the continuation mark at both the end of the

continued line and at the start of the continuation line

is ineective within a comment and cannot b e on a line on its own

INTEGER SQUASHED UP REAL CLOSE Two for the price of one

The allows two statements ormore to o ccupy the same line and signies that the following text

is a comment

In free format blanks b ecome signicant The rules are fairly straightforward blanks cannot o ccur in

the middle of names keywords or literals and in general blanks must app earbetween keywords and

between keywords and names See Section formore details

Question Reformatting Co de

The following program which is available by anonymous ftp from ftplivacuk in the direc

tory pubfcoursesprogs lename BasicReformatQuestionf has been badly laid out

Reformat it so its is neat and readable but p erforms exactly the same function

PROGRAM MAININTEGERdegreesfahrenheit

degreescentigradeREAD

degreesfahrenheitdegreescentigrade

degreesfahrenheitPRINT

degreesCENtiGrAdeEND

Character Set

The statements of a Fortran program are expressed using a carefully dened restricted character

set This character set has b een chosen so that it is available on almost every machine currently in

use The Fortran character set can b e repro duced by virtually every displayprinter or other input

output device which uses characters It consists of the set of alphanumeric characters and a limited

set of punctuation marks and other sp ecial symb ols The alphanumeric characters are the upp er case

letters AZ the lower case letters az the digits and the underscore character There is

no dierence b etween upp er and lower case letters in Fortran The allowed punctuation and other

sp ecial symb ols are shown in the following table

Septemb er University of Liverp o ol

Signicant Blanks

Symb ol Description Symb ol Description

space equal

plus minus

slash

left paren right paren

comma p erio d

single quote double quote

semicolon colon

shriek amp ersand

p ercent less than

greater than dollar

question mark

The last one in each column and do not have any sp ecial meaning in the language Most mo dern

computer systems are able to pro cess a somewhat wider character set than this however this set is

chosen so that it will b e available on virtually every computing system in every country in the world

The characters found on any particular machine in excess of these are very likely to either not exist on

some other machine or have very dierent graphic representation Apart from textual output the case

of a letter is insignicant to Fortran unlikesay C so the dierent cases can therefore b e used to

improve the readability of the program

A collating sequence is dened Section and is standard ASCI I see Section

Signicant Blanks

In free format programs spaces or blanks in statements can be thought of as b eing signicant

Consecutive spaces blanks have the same meaning as one blank Blanks are not allowed in language

keywords For instance INT EGER is not the same as INTEGER Neither are blanks allowed in names

dened by the programmer The name hours could not b e written as ho urs not that any one would

be likely to do so If a name is made up from twowords it is common practice to use an underscore

as a separator The continuation character acts as a space and so cannot b e used in the middle of

names and keywords

Keywords and names may not b e run together without spaces or some other punctuation to separate

them Thus

SUBROUTINEClear

would b e illegal and not equivalent to

SUBROUTINE Clear

Likewise

INTEGER a

is valid and

INT EGER a

Fortran Course Notes File CourseNotesps

Language Elements

is not

Blanks must app ear

between two separate keywords

between keywords and names not otherwise separated by punctuation or other sp ecial characters

INTEGER FUNCTION fiti is valid

INTEGERFUNCTION fiti is not

INTEGER FUNCTIONfiti is not

Blanks are optional b etween certain pairs of keywords such as END construct where construct

is DO FUNCTION PROGRAM MODULE SUBROUTINE and so on Blanks are mandatory is other situations

Adding a blank b etween two valid English words is generally a go o d idea and will b e valid

Apart from observing the ab ove rules spaces can b e used lib erally to increase the readabilityofpro

grams Thus the following statements

POLYNXXX

and

POLYN X X X

are equivalent

To sum up the rules governing the use of blanks are largely common sense Judicious use of blanks

and sensible use of upp er and lower case can often signicantly clarify more complicated constructs

or statements and some systematic convention for this use can make it very much easier to read and

hence to write correct programs As statements can start anywhere on a line most programmers use

indentation to highlight control structure nesting for example within IF blo cks and DO lo ops

Comments

It is always very go o d practice to add descriptive comments to programs On any line a character

indicates that all subsequent characters up to the end of the line are commentary Such commentary

is ignored by the compiler Comments are part of the program source but are intended for the human

reader and not for the machine

PROGRAM Saddo

Program to evaluate marriage potential

LOGICAL TrainSpotter Do we spot trains

LOGICAL SmellySocks Have we smelly socks

INTEGER i j Loop variables

The one exception to ab ove is if the app ears in a character context for example in

Septemb er University of Liverp o ol

Names

PRINT No chance of ever marrying

the do es not initiate a comment

A comment can contain any of the characters available on the computer b eing used A comment is not

restricted to use the Fortran character set Aprogram containing comments using characters outside

this set may still b e p ortable but the comments may lo ok somewhat o dd if the program is moved to

another system with a dierent extended set of characters

With mo dern compilation systems it is often p ossible to give the compiler hints by annotating programs

with sp ecically structured comments which are interpreted and acted up on to pro duce ecient co de

The HPF High Performance Fortran language is implemented in this way

Next line is an HPF directive

HPF PROCESSORS P

Switch to fixed format

DIR FIXEDFORM

Names

The Fortran language denes a numb er of names or keywords such as PRINT INTEGER MAXetc

The sp elling of these names is dened by the language There are a numb er of entities that must b e

named bytheprogrammer such as variables pro cedures etc These names must b e chosen to ob ey

a few simple rules A name can consist of up to alphanumeric characters letters or digits plus

underscore The rst character in any name must b e a letter In names upp er and lower case letters

are equivalent The following are valid Fortran names

A aAa INCOME Num NO underscore

The following declarations are incorrect statements owing to invalid names

INTEGER A does not begin with a letter

INTEGER Anamemadeupofmorethanletters too long characters

INTEGER Depth contains an illegal character

INTEGER A subtract from A is meaningless here

The underscore should b e used to separate words in long names

CHARACTERLEN username valid name

CHARACTERLEN username different valid name

With this and the new long names facilityinFortran symb olic names should b e readable signicant

and descriptive It is worth sp ending a minute or so cho osing a go o d name which other programmers

will b e able to understand

Statement Ordering

Fortran has some quite strict rules ab out the order of statements Basically in any program orpro cedure

the following rules must b e used

Fortran Course Notes File CourseNotesps

Language Elements

The program heading statement must come rst PROGRAM FUNCTION or SUBROUTINE A

PROGRAM statement is optional but its use is recommended

All the sp ecication statements must precede the rst executable statement Even though DATA

statements may b e placed with executable text it is far clearer if they lie in the declaration area

It is also a go o d idea to group FORMAT statements together forclarity

The executable statements must follow in the order required by the logic of the program

The program orpro cedure must terminate with an END statement

Within the set of sp ecication statements there is relatively little ordering required however in general

if one entity is used in the sp ecication of another it is normally required that it has b een previously

dened In other words named constants PARAMETERs must b e declared b efore they can b e used as

part of the declaration of other objects

The following table details the prescrib ed ordering

PROGRAM FUNCTION SUBROUTINE MODULE or BLOCK DATA statement

USE statement

IMPLICIT NONE

PARAMETER statement IMPLICIT statements

FORMAT PARAMETER and DATA DerivedTyp e Denition Interface blo cks

and ENTRY statements Typ e declaration statements Statement

statements function statements and sp ecication

statements

DATA statements Executable constructs

CONTAINS statement

Internal or mo dule pro cedures

END statement

Execution of a program b egins at the rst executable statement of the MAIN PROGRAMwhena pro cedure

is called execution b egins with the rst executable statement after the invoked entry p oint The non

executable statements are conceptually executed simultaneously on program initiation in other

words they are referenced once and once only when execution of the main program b egins

There now follows a explanation of the table

Septemb er University of Liverp o ol

Statement Ordering

There can b e only main PROGRAM

there may b e many uniquely named FUNCTIONsand SUBROUTINEsprogram units pro cedures

there may be any numb er of uniquely named MODULEs which are asso ciated with a program

through a USE statement Mo dules are very exible program units and are used to package a

numb er of facilities for example pro cedures typ e denitions object declarations or semantic

extensions Their use is very much encouraged and they replace a numb er of unsafe features of

Fortran

There can b e only one BLOCK DATA subprogram these will not b e describ ed as part of this

course their purp ose is to dene global constants or global initialisation and this is b est done

bya MODULE and USE statement

USE statement

This attaches a mo dule whose entities b ecome useasso ciated with the program unit When a

mo dule is used its public contents are accessible as if they had b een declared explicitly in the

program unit Mo dules maybeprecompiled like a library ormay b e written bytheprogrammer

Any global entities should b e placed in a mo dule and then used whenever access is required

The IMPLICIT NONE statement should b e placed after a USE statement Its use is implored

FORMAT and ENTRY statements Format statements should b e group ed together somewhere in

the co de ENTRY statements provide a mechanism to drop into a pro cedure halfway through

the executable co de Their use is outmo ded and strongly discouraged owing to its dangerous

nature

PARAMETER statement and IMPLICIT statement

IMPLICIT statements should not b e used IMPLICIT NONE should b e the only form of implicit

typing considered IMPLICIT statements allow the user to redene the implication of an objects

rst letter in determining what its implicit typ e will be if it is not declared Cannot have an

IMPLICIT statement if there is an IMPLICIT NONE line

PARAMETER statements it is suggested that the attributed Fortran style of PARAMETER

declaration b e used

DATA statements should but do not have to b e placed in the declaration common practice puts

them after the declarations and b efore the

Interface blo cks are generally placed at the head of the declarations and are group ed together

Statement functions are a form of inline statement denition internal pro cedures should b e used

instead

executable statements are things like DO statements IF constructs and assignment statements

CONTAINS separates the main program unit from any lo cally visible internal pro cedures

the internal pro cedures follow the same layout as a normal pro cedure except that they cannot

contain a second level of internal pro cedure

the END statement is essential to delimit the current program unit

Fortran Course Notes File CourseNotesps

Data Objects

Data Objects

Intrinsic Typ es

Fortran has three broad classes of object typ e

character

b o olean

numeric

these give rise to ve simple intrinsic typ es known a default typ es

CHARACTER for strings of one ormore characters

LOGICAL for objects which have the values true or false

REAL and DOUBLE PRECISIONfor approximate p ossibly fractional numb ers

INTEGER for exact whole numb ers

COMPLEX for representing numb ers of the form x iy

For example

CHARACTER sex letter

CHARACTERLEN name string

LOGICAL wed married

REAL height

DOUBLE PRECISION pi

INTEGER age whole No

COMPLEX val x iy

Each typ e has

a name

a set of valid values

a means to denote values

a set of op erators

Note

Most programming languages have the same broad classes of objects

The three broad classes cannot b e intermixed without some sort of typ e co ercion b eing p erformed

REAL and DOUBLE PRECISION objects are approximate DOUBLE PRECISION should not nowbe

used In Fortran an object of this typ e had greater precision than REALinFortran the

precision of a REAL object may b e sp ecied making the DOUBLE PRECISION data typ e redundant

All numeric typ es have nite range

A default typ e is not parameterised by a kind value

Septemb er University of Liverp o ol

Literal Constants

Literal Constants

A literal constant is an entity with a xed value

INTEGER

REAL

REAL

E REAL

D DOUBLE PRECISION

FALSE LOGICAL

Maudib CHARACTER

Maudib CHARACTER

Note

there are only two LOGICAL values

integers are represented by a sequence of digits with a or sign signs are optional

REAL constants contain a decimal p oint or an exp onentiation symb ol INTEGER constants do not

character literals are delimited by the double or single quote symb ols and

two o ccurrences of the delimiter inside a string pro duce one o ccurrence on output for example

Maudib but not Maudib b ecause of the diering delimiters

there is only a nite range of values that numeric literals can take

constants may also include a kind sp ecier

Implicit Typing

If a variable is referenced but not declared in its scoping unit then by default it is implicitly declared

The typ e that it assumes dep ends on the rst letter

I J K L M and N represent integers

all other letters dene real variables

This short cut is p otentially very dangerous as a missp elling of a variable name can declare and assign

to a brand new variable with the user b eing totally unaware

Implicit typing should always b e turned o byadding

IMPLICIT NONE

as the rst line after any USE statements In this way the user will be informed of any undeclared

variables used in the program

Consider

Fortran Course Notes File CourseNotesps

Data Objects

DO I

CONTINUE

in xed format with implicit typing this declares a REAL variable DOI and sets it to instead

of p erforming a lo op times Legend has it that the example sighted caused the crash of the

American Space Shuttle An exp ensive missing comma

Numeric and Logical Declarations

Variables of a given typ e should b e declared in typ e declaration statements at the start of a program

unit A simplied syntax follows

typ e attributelist variablelist value

The is actually optional however it do es no harm to use it moreover if attributelist or

value are present then the is obligatory

The following are all valid declarations

REAL x

INTEGER ij

LOGICAL POINTER ptr

REAL DIMENSION y z

DOUBLE PRECISION DIMENSION w

The DIMENSION attribute declares a array this can b e overridden as with z which is declared

as a D array with elements

attributelist represents a list of attributes such as PARAMETER SAVE INTENT POINTER TARGET

DIMENSIONforarrays or visibility attributes An object maybegivenmore than one attribute p er

declaration but some cannot b e mixed such as PARAMETER and POINTER

Character Declarations

Character variables can b e declared in a similarway to numeric typ es using a CHARACTER statement

CHARACTER variables can

refer to one character

refer to a string of characters which is achieved by adding a length sp ecier to the object

declaration

A simplied syntax follows

typ e LEN lengthsp ec attributelist variablelist value

If attributelist or value are present then so must b e

The following are all valid declarations

Septemb er University of Liverp o ol

Constants Parameters

CHARACTERLEN name

CHARACTER sex

CHARACTERLEN str

In the same way as the DIMENSION attribute was overridden in the example of Section so can the

string length declaration sp ecied by LEN this is achieved using the notation If a DIMENSION

sp ecier is present it can also b e overridden The length sp ecier must come after the dimension if

both are b eing overridden

CHARACTERLEN name sex str

CHARACTERLEN DIMENSION tom dick harry

CHARACTER POINTER Pch

The rst line is exactly the same as the previous declaration

There is a substantial dierence b etween a character variable of characters CHARACTERLEN

or CHARACTER and an array of elements the rst is scalar and the second is nonscalar

Other attributes can b e added in the same wayasfor numeric typ es see Section

Constants Parameters

Symb olic constants o ddly known as parameters in Fortran can easily b e set up either in an attributed

declaration orinaPARAMETER statement it is recommended that the attributed form b e used

INTEGER priceoffags F style not recommended

PARAMETER priceoffags F style not recommended

REAL PARAMETER pi F style

CHARACTER constants can assume their length from the asso ciated literal LEN they can also b e

declared to b e xed length

CHARACTERLEN PARAMETER son bart dad Homer

Parameters should b e used

if it is known that a variable will only take one value

The variable is forced to b e unchanged throughout the program If any statement tries to change

the value an error will result

for legibility where a magic value o ccurs in a program such as

Symb olic names are easier to understand than a meaningless numb er

for maintainability when a constant value could feasibly b e changed

The value of the constant can b e adjusted throughout the program by changing line

Fortran Course Notes File CourseNotesps

Data Objects

Initialisation

When a program is loaded into the computers memory the contents of declared variables are normally

undened it is clearly useful to override this and give variables useful initial values For example

INTEGER i j

REAL max D

CHARACTERLEN light Amber

CHARACTERLEN gumboot Wellie

LOGICAL on TRUE off FALSE

For CHARACTER variables if the object and initialisation expression are of dierent lengths then either

the object will b e padded with blanks on the RHS or

the initialisation expression will b e truncated on the right so it will t

Variables can b e initialised in a numb er of ways

PARAMETER statements

DATA statements

typ e declaration statements with an expression clause

Limited expressions known as initialisation expressions can also b e used in typ e declaration statements

These expression must b e able to b e evaluated when the program is compiled if you cant work out

the values then neither can the compiler Initialisation expressions can contain PARAMETERsor literals

Arrays may be initialised by sp ecifying a scalar value or by using a conformable array constructor

REAL PARAMETER pi

REAL radius

REAL circum pi radius

INTEGER a

In general intrinsic functions cannot b e used in initialisation expressions however the following intrin

sics may b e used

REPEAT

RESHAPE

SELECTED INT KIND

SELECTED REAL KIND

TRANSFER

TRIM

LBOUND

Septemb er University of Liverp o ol

Examples of Declarations

UBOUND

SHAPE

SIZE

KIND

LEN

BIT SIZE

numeric inquiry intrinsics for example HUGE TINY EPSILON

In this context the arguments to these functions must b e initialisation expressions

Examples of Declarations

The following declarations showhowcareful choice of data typ e name and inclusion of comments can

help readability

CHARACTERLEN Location Name of hospital

CHARACTER Ward Ward eg A B C etc

INTEGER NumBabiesBorn Sum total of births

REAL TimeElapsed Time since st birth hours

REAL MaxTimeTwixtBirths longest gap between births

REAL AveTimeTwixtBirths average gap between births

REAL TimeSinceLastBirth gap since the last birth

LOGICAL NHS Is it an NHS hospital

There is nothing wrong with using verb ose variable names and augmenting declarations with comments

explaining their use

It is imp ortant to use an appropriate data typ e for an object for example the ab ove variable Location

is the name of a hospital it is clearly appropriate to use a CHARACTER string here We have assumed

that the name can b e represented in letters The second variable Ward only needs to contain one

letter of the alphab et this is reected in its declaration It is also a go o d idea to initialise any variables

that are used to hold some sort of counter In the ab ove co de fragment we have such examples

NumBabiesBorn is incremented by one each time there is a new birth this value must always be a

whole numb er so INTEGER is the appropriate data typ e TimeElapsed measures the time in hours

since the rst birth in order to b e accurate we need to b e able to represent fractions of hours so a

REAL variable is in order when the program b egins to run zero time will have elapsed which explains

the initialisation the nal example is MaxTimeTwixtBirths the longest sp ell of time b etween births

again it is a go o d idea to initialise the variable to a sensible value owing to the wayitwillprobably b e

used in the program It is likely that the following will app ear

IF TimeSinceLastBirth MaxTimeTwixtBirths THEN

MaxTimeTwixtBirths TimeSinceLastBirth

END IF

The AveTimeTwixtBirths variable will also have to represent a nonwhole numb er so REAL is the

obvious choice The variable TimeSinceLastBirth is used to store the current time gap between

births and is in this sense a temp orary variable LOGICAL variables are ideal when one of two values

needs to b e stored here wewishtoknow whether the hospital is NHSfunded ornot

Fortran Course Notes File CourseNotesps

Data Objects

Question Declaration Format

Which of the following are incorrect declarations and why If you think a declaration may be

correct in a given situation then say what the situation would b e

ReAl x

CHARACTER name

CHARACTERLEN name

REAL var

INTEGER a

BOOLEAN loji

DOUBLE X

CHARACTERLEN town Glasgow

CHARACTERLEN town Glasgow

CHARACTERLEN PARAMETER city Glasgow

INTEGER pi

LOGICAL wibble TRUE

CHARACTERLEN PARAMETER Bognor

REAL PARAMETER pye

pie pye REAL two

REAL a b

LOGICALLEN frisnet

CHARACTERLEN you know yknow

CHARACTERLEN you know yknow

INTEGER ia ib ic id

in free format source form

DOUBLE PRECISION pattie D

DOUBLE PRECISION pattie E

LOGICAL DIMENSION bool

REAL poie atan

declare the following objects

Name Status Typ e Initial Value

feet variable integer

miles variable real

town variable character letters

home town constant character your home town

in uk constant logical is your home town in UK

sin half constant real sin

Septemb er University of Liverp o ol

Expressions and Assignment

Expressions

Each of the three broad typ e classes has its own set of intrinsic inbuilt op erators these are combined

with op erands to form expressions Expressions are made from one op erator eg and

and at least one op erand Op erands are also expressions

Expressions have typ es derived from their op erands they are either of intrinsic typ e or a user dened

typ e For example

NumBabiesBorn numeric valued

Ward Ward character valued

TimeSinceLastBirth GT MaxTimeTwixtBirths logical valued

In addition to the intrinsic op erations

op erators maybedenedby the user for example INVERSE These dened op erators with

or op erands are sp ecied in a pro cedure and can b e applied to any typ e or combination of

typ es The op erator functionality is given in a pro cedure which must then b e mentioned in an

interface blo ck Such op erators are very p owerful when used in conjunction with derived typ es

and mo dules as a package of objects and op erators

intrinsic op erators may be overloaded when using a derived typ e the user can sp ecify exactly

what each existing op erator means in the context of this new typ e

Assignment

Expressions are often used in conjunction with the assignment op erator to give values to objects

This op erator

is dened b etween all intrinsic numeric typ es The twooperandsof the LHS and RHS do

not have to b e the same typ e

is dened b etween two objects of the same userdened typ e

may be explicitly overloaded so that assignment is meaningful in situations other than those

ab ove

Examples

a b

c SIN

name initialssurname

bool aEQbORcNEd

The LHS is an object and the RHS is an expression

Fortran Course Notes File CourseNotesps

Expressions and Assignment

Intrinsic Numeric Op erations

The following op erators are valid for numeric expressions

exp onentiation a dyadic takes two op erands op erator for example evaluated

right to left

and multiply and divide dyadic op erators for example

and plus and minus or add and subtract a monadic takes one op erand and dyadic

op erators for example and

All the ab ove op erators can b e applied to numeric literals constants scalarandarray objects with the

only restriction b eing that the RHS of the exp onentiation op erator must b e scalar

Example

a b c

f

Note that op erators have a predened precedence which denes the order that they are evaluated in

see Section

Question Area Of a Circle

Write a simple program to read in the radius and calculate the area of the corresp onding circle

and volume of the sphere Demonstrate correctness by calculating the area and volume using radii of

and

Area of a circle



area

Volume of a sphere



r

volume

Hint place the READthearea calculation and the PRINT statement in a lo op as follows Aprogram

which is available by anonymous ftp from ftplivacuk in the directory pubfcoursesprogs

lename BasicAreaOfCircleQuestionf is given b elow

PROGRAM Area

DO

PRINT Type in the radius a negative value will terminate

READ radius

IF radius LT EXIT

area calculation

PRINT Area of circle with radius

radius is area

PRINT Volume of sphere with radius

radius is volume

Septemb er University of Liverp o ol

Relational Op erators

END DO

END PROGRAM Area

In this way when a negative radius is supplied the program will terminate

Hint use the value for

Relational Op erators

The following relational op erators deliver a logical result

GT greater than

GE greater than or equal to

LE less than or equal to

LT less than

NE not equal to

EQ equal to

for example

i GT

is an expression delivering a TRUE or FALSE result

These ab ove op erators are equivalent to the following

greater than

greater than or equal to

less than or equal to

less than

not equal to

equal to

for example

i

Both sets of symb ols may b e used in a single statement

Relational op erators

compare the values of two op erands

Fortran Course Notes File CourseNotesps

Expressions and Assignment

deliver a logical result

can b e applied to numeric op erands restrictions on COMPLEX which can only use EQ and NE

can b e applied to default CHARACTER objects b oth objects are made to b e the same length

by padding the shorter with blanks Op erators refer to ASCI I order see App endix

cannot b e applied to LOGICAL objects for example

bool NE TRUE

is not a valid expression but

NOTbool

is

are used in scalar form in IF statements see Section and elementally in the WHERE

statement see Section

Consider

bool iGTj

IF iEQj c D

IF i j c D

The example demonstrates

simple logical assignment using a relational op erator

IF statements using b oth forms of relational op erators

When using realvalued expressions which are approximate EQ and NE have no real meaning

REAL Tol

IF ABSab LT Tol same TRUE

Intrinsic Logical Op erations

A LOGICAL or b o olean expression returns a TRUE FALSE result The following op erators are

valid with LOGICAL op erands

NOT monadic negation op erator which gives TRUE if op erand is FALSEfor example

NOTa LT b

AND logical and op erator TRUE if b oth op erands are TRUE

OR logical or op erator TRUE if at least one op erand is TRUE

EQV TRUE if b oth op erands are the same

NEQV TRUE if b oth op erands are dierent

Septemb er University of Liverp o ol

Intrinsic Character Op erations

The following are examples of logical expressions

REAL a b x y

LOGICAL l l

l NOTxEQyANDaEQb

l lEQVxGTaORyLTbNEQVaEQb

Intrinsic Character Op erations

Character Substrings

Consider

CHARACTERLEN PARAMETER string abcdefgh

substrings can b e taken

string is abcdefgh the whole string

string is atherstcharacter

string is nd rd and th characters

string is an error the substring must b e sp ecied from a p osition to a p osition a single

subscript is no go o d

string is abcdefgh

string is a

Concatenation

There is only one intrinsic character op erator the concatenation op erator Most string manipulation

is p erformed using intrinsic functions

CHARACTERLEN PARAMETER name Coal

CHARACTERLEN song Firey name

PRINT Rowche Rumble

PRINT songname

would pro duce

Rowche Rumble

Foal

The example joins together two strings and then the rst character of song and the nd rd and th

of name Note that cannot b e mixed with other typ es or kinds

Fortran Course Notes File CourseNotesps

Expressions and Assignment

Op erator Precedence

The following table depicts the order in which op erators are evaluated

Op erator Precedence Example

userdened monadic Highest INVERSEA

or

monadic or

dyadic or

strstr

GT LE etc A B

NOT NOTBool

AND AANDB

OR AORB

EQV or NEQV AEQVB

userdened dyadic Lowest XDOTY

In an expression with no parentheses the highest precedence op erator is combined with its op erands

rst In contexts of equal precedence left to right evaluation is p erformed except for

Other relevant points are that the intrinsically dened order cannot be changed which means that

user dened op erators have a xed precedence at the top and b ottom of the table dep ending on the

op erator typ e The op erator with the highest precedence has the tightest binding from the table

userdened monadic op erators can b e seen to b e the most tightly binding

The ordering of the op erators is intuitive and is comparable to the ordering of other languages The

evaluation order can b e altered by using parenthesis expressions in parentheses are evaluated rst In

the context of equal precedence left to right evaluation is p erformed except for where the expression

is evaluated from right to left This is imp ortant when teetering around the limits of the machines

representation Consider ABC and ACBif A were the largest representable numb er and C is p ositive

and smaller than B the rst expression is OK but the second will crash the program with an overow

error

One of the most common pitfalls occurs with the division op erator it is go o d practice to put

numerator and denominatorinparentheses Note

ABC

is not the same as

ABC

but

Septemb er University of Liverp o ol

Precedence Example

ABC

is equivalent to

ABC

This is b ecause the multiplication op erator binds tighter than the addition op erator however

ABC

is not equivalent to

ABC

b ecause of left to right evaluation

The syntax is such that two op erators cannot b e adjacent one times minus one is written and

not This is the same as in most languages

Precedence Example

The precedence is worked out as follows

in an expression nd the op erators with the tightest binding

if there are more than one o ccurrence of this op erator then the separate instances are evaluated

left to right

place the rst executed sub expression in brackets to signify this

continue with the second and subsequent sub expressions

move to next most tightly binding op erator and follow the same pro cedure

It is easy to make mistakes byforgetting the implications of precedence The following expression

x abcde

is equivalent to

x abcde

The following pro cedure has b een followed to parenthesise the expression

tightest binding op eratoris This means cd is the rst executed sub expression so should

b e surrounded bybrackets

and are the second most tightly binding op erators and expressions involving them will be

evaluated next put b and e in brackets

Fortran Course Notes File CourseNotesps

Expressions and Assignment

and have the next highest precedence Since they are of equal precedence o ccurrences are

evaluated from left

at last the assignment is made

Likewise the following expression

NOTAORBEQVCANDDORNOTE

is equivalent to

NOTAORBEQVCANDDORNOTE

here

the tightest binding op erator is NOT followed by AND followed by OR

the two sub expressions containing the monadic NOT are eectively evaluated rst as there are

two of these the leftmost NOTA is done rst followed by NOTE

the sub expression CANDD is evaluated next followed by OR left to right

nally the EQV is executed

Parentheses can b e added to any expression to mo dify the order of evaluation

Question Op erator Precedence

Rewrite the following expression so that it contains the equivalent symb olic relational op erators

and then add parenthesis to indicate the order of evaluation

NOTAANDBEQVCORDANDEORxGTyANDyeqz

Add parenthesis to this expression to indicate the order of evaluation

abcdefghjk

Precision Errors

Each time two real numb ers are combined there is a slight loss of accuracy in the result After many

such op erations such roundo errors b ecome noticeable Catastrophic accuracy loss often arises

b ecause two values that are almost equal are subtracted the subtraction may cancel the leading digits

and promotes errors very rapidly from loworderdigitstohighorder ones

For example consider the numb ers and these maybeapproximated in memory as

and resp ectively whereas the true dierence is D the representation may

give D a erro r

Septemb er University of Liverp o ol

Precision Errors

x y

PRINT x x y y

PRINT xy xy but should be d

Maypro duce

x y

xy d but should be d

A whole branch of is dedicated to minimising this class of errors in algorithms

Fortran Course Notes File CourseNotesps

Mo dule

Control Constructs Intrinsics

and Basic IO

Control Flow

All structured programming languages need constructs which provide a facilityfor conditional execu

tion The simplest metho d of achieving this functionalityisby using a combination of IF and GOTO

which is exactly what Fortran supp orted Fortran has progressed since then and now includes a

comprehensive basket of useful control constructs Fortran supp orts

conditional execution statements and constructs IF statements and IF THEN ELSEIF

ELSE END IF

These are the basic conditional execution units They are useful if a section of co de needs to

be executed dep ending on a series of logical conditions being satised If the rst condition

in the IF statement is evaluated to b e true then the co de b etween the IF and the next ELSE

ELSEIF or ENDIF is executed If the predicate is false then the second branch of the construct

is entered This branch could b e either null an ELSE oran ELSEIF corresp onding to no action

the default action or another evaluation of a dierent predicate with execution b eing dep endent

up on the result of the current logical expression Each IF statement has at least one branch

and at most one ELSE branch and may contain any numb er of ELSEIF branches Very complex

control structures can b e built up using multiply nested IF constructs

Before using an IF statement a programmer should b e convinced that a SELECT CASE blo ck or

a WHERE assignment blo ck would not b e more appropriate

lo ops DO END DO

This is the basic form of iteration mechanism This structure allows the b o dy of the lo op to b e

executed a numb er of times The numb er of iterations can b e a constant a variable expression

or can b e dep endent on a particular condition b eing satised DO lo ops can b e nested

multiway choice construct SELECT CASE

A particular branch is selected dep ending up on the value of the case expression Due to the

nature of this construct it very often works out computationally cheap er than an IF blo ck

with equivalent functionality This is b ecause in a SELECT CASE blo ck a single control expression

is evaluated once and then its single result is compared with each branch With an IF

ELSEIF blo ck a dierent control expression must b e evaluated at each branch Even if all control

expressions in an IF construct were the same and were simply compared with dierent values

the general case would dictate that the SELECT CASE blo ck is more ecient

and less imp ortantly

unconditional jump statements GOTO

Direct jump to a lab elled line This is a very p owerful statement it is very useful and very op en

to abuse Unstructured jumps can makea program virtually imp ossible to follow the GOTO must

IF Statement

b e used with care It is particularly useful for handling exceptions that is to say when emergency

action is needed to b e taken owing to the discovery of an unexp ected error

IO exception branching ERR END EOR

This is a slightly o ddball feature of Fortran in the sense that there is currently no other form of

in the language The feature originated from Fortran It is p ossible

to add qualiers to IO statements to sp ecify a jump in control should there b e an unexp ected

IO data error end of record or should the end of a le b e encountered

It is always go o d practice to use at least the ERR qualier in IO statements

IF Statement

This is the most basic form of conditional execution in that there is only an option to execute one

statement or not the general IF construct allows a blo ck of co de to b e executed The basic form

is

IF logicalexpression execstmt

If the TRUE FALSE valued expression logicalexpression evaluates to TRUE then the

execstmt is executed otherwise control of the program passes to the next line This typ e of IF

statement still has its use as it is a lot less verb ose than a blo ckIF with a single executable statement

For example

IF logicalval A

val is TRUE then A gets set to otherwise it do es not If logical

A logical expression is often expressed as

expression relationalop erator expression

For example

IF x GT y Maxi x

IF i NE AND j NE k ij

IF i AND j k ij same

As REAL numb ers are represented approximately it makes little sense to use the EQ and NE

relational op erators b etween realvalued expressions For example there is no guarantee that and

are equal If two REAL numb ers expressions are to b e tested for equality then one should

lo ok at the size of the dierence b etween the numb ers and see if this is less than some sort of tolerance

REAL Tol

IF ABSab LT Tol same TRUE

Consider the IF statement

Fortran Course Notes File CourseNotesps

Control Flow

IF I Print I

this maps onto the following control ow structure

IF (I > 17)

I > 17

PRINT*, "I > 17" I <= 17

! Next statement

Figure Schematic Diagram of an IF Statement

IF Construct

The blo ckIF is more exible than the single statement IF since there can b e a numb er of alternative

mutually exclusive branches guarded by dierent predicates The control owisalotmore structured

than if a single statement IF plus GOTO statements were used The scenario is that the predicates in

the IF or ELSEIF lines are tested in turn the rst one which evaluates as true transfers control to the

appropriate inner blo ck of co de when this has b een completed control passes to the ENDIF statement

and thence out of the blo ck If none of the predicates are true then the elseblo ck if present is

executed

The simplest form of the IF construct is equivalent to the IF statement in other words if a predicate

is TRUE then an action is p erformed

Consider the IF THEN construct

IF I THEN

Print I

END IF

this maps onto the following control ow structure

Septemb er University of Liverp o ol

IF Construct

IF (I > 17) THEN

I > 17

PRINT*, "I > 17" I <= 17

END IF

Figure Visualisation of an IF THEN Construct

It is a matter of p ersonal taste whether the ab ove construct or just the simple IF statement is used

for this sort of case

The IF construct may contain an ELSE branch a simple example could b e

IF I THEN

Print I

ELSE

Print I

END IF

this maps onto the following control ow structure

IF (I>17) THEN

I > 17 ELSE

PRINT*, "I>17" PRINT*, "I<=17"

END IF

Figure Visualisation of an IF THEN ELSE Construct

The construct may also have an ELSEIF branch

IF I THEN

Fortran Course Notes File CourseNotesps

Control Flow

Print I

ELSEIF I

Print I

ELSE

Print I

END IF

Both ELSE and ELSEIF are optional and there can b e any numb er of ELSEIF branches The ab ove

maps to the following control ow structure

IF (I > 17) THEN

I > 17 I >= 17

PRINT*, "I>17" ELSEIF(I==17)THEN

I == 17 ELSE

PRINT*, "I==17" PRINT*, "I<17"

ENDIF

Figure Visualisation of an IF THEN ELSEIF Construct

The formal syntax is

name IF logicalexpression THEN

thenblo ck

ELSEIF logicalexpression THEN name

elseifblo ck

ELSE name

elseblo ck

END IF name

The rst branch to have a TRUE valued logicalexpression is the one that is executed If none

are found then the elseblo ck ifpresent is executed

For example

IF x GT THEN

CALL SUB

ELSEIF x EQ THEN

CALL SUB

Septemb er University of Liverp o ol

Nested and Named IF Constructs

ELSEIF x EQ THEN

CALL SUB

ELSE

CALL SUB

ENDIF

A further IF construct may app earinthe thenblo ck the elseblo ck orthe elseifblo ck

This is now a nested IF structure

Statements in either the thenblo ck the elseblo ck orthe elseifblo ck maybe lab elled

but jumps to such lab elled statements are p ermitted only from within the blo ck containing them

Entry into a blo ckIF construct is allowed only via the initial IF statement Transfer out of either the

thenblo ck the elseblo ck orthe elseifblo ck is p ermitted but only to a statement entirely

outside of the whole blo ck dened by the IFEND IF statements A transfer within the same blo ckIF

between any of the blo cks is not p ermitted

Certain typ es of statement eg END SUBROUTINE END FUNCTION or END PROGRAM statement are not

allowed in the thenblo ck the elseblo ck orthe elseifblo ck

Nested and Named IF Constructs

All control constructs can b e b oth named and nested for example

outa IF a NE THEN

PRINT a

IF c NE THEN

PRINT a AND c

ELSE

PRINT a BUT c

ENDIF

ELSEIF a GT THEN outa

PRINT a

ELSE outa

PRINT a must be

ENDIF outa

Here the names are only cosmetic and are intended to make the co de clearer cf DOlo op names which

do If a name is given to the IF statement then it must be present on the ENDIF statement but not

necessarily on the ELSE or ELSEIF statement If a name is present on the ELSE or ELSEIF then it

must b e present on the IF statement

The example has two nested and one named IF blo ck Nesting can b e to any depth unless the compiler

prohibits this even if it do es the limit will almost certainly b e congurable

Even though construct names are only valid within the blo ck that they apply to their scop e is the

whole program unit This means that a name may only b e used once in a scoping unit even though

no confusion would arise if it were reused See Section for a discussion of scop e

Question The Triangle Program

Write a program to accept three INTEGER lengths and rep ort back on whether these lengths

Fortran Course Notes File CourseNotesps

Control Flow

could dene an equilateral isosoles or scalene triangle or equal length sides or whether they

cannot form a triangle

Demonstrate that the program works by classifying the following

Hint If three lengths form a triangle then times the longest side must b e less than the sum of all

three sides In Fortran terms the following must b e true

MAXsidesideside sidesideside

Conditional Exit Lo ops

A lo op comprises a blo ck of statements that are executed cyclically When the end of the lo op is

reached the blo ck is rep eated from the start of the lo op Lo ops are dierentiated bythewaytheyare

terminated Obviously it would not b e reasonable to continue cycling a lo op forever There must b e

some mechanism for aprogram to exit from a lo op and carry on with the instructions following the

Endoflo op

The blo ck of statements making up the lo op is delimited by DO and END DO statements This blo ck is

executed as many times as is required Each time through the lo op the condition is evaluated and the

rst time it is true the EXIT is p erformed and pro cessing continues from the statement following the

next END DO Consider

i

DO

i i

IF i GT EXIT

PRINT I is i

END DO

if i control jumps here

PRINT Loop finished I now equals i

this will generate

I is

I is

Septemb er University of Liverp o ol

Conditional Cycle Lo ops

I is

I is

Loop finished I now equals

This typ e of conditionalexit lo op is useful for dealing with situations when we want input data to

control the numb er of times the lo op is executed

The statements between the DO and its corresp onding END DO must constitute a prop er blo ck The

statements may b e lab elled but no transfer of control to such a statement is p ermitted from outside

the lo opblo ck The lo opblo ck may contain other blo ck constructs for example DO IF or CASE but

they must b e contained completely that is they must b e prop erly nested

An EXIT statement which is not within a lo op is an error

Conditional Cycle Lo ops

Situations often arise in practice when for some exceptional reason it is desirable to terminate a

particular pass through a lo op and continue immediately with the next rep etition or cycle this can b e

achieved in Fortran byarranging that a CYCLE statement is executed at an appropriate p oint in the

lo op

For example

i

DO

i i

IF i AND i CYCLE

IF i EXIT

PRINT I is i

END DO

PRINT Loop finished I now equals i

this will generate

I is

I is

I is

I is

I is

Loop finished I now equals

Here CYCLE forces control to the innermost DO statement the one that contains the CYCLE statement

and the lo op b egins a new iteration

In the example the statement

IF i AND i CYCLE

Fortran Course Notes File CourseNotesps

Control Flow

if executed will transfer control to the DO statement The lo op must still contain an EXIT statement

in order that it can terminate

A CYCLE statement which is not within a lo op is an error

Named and Nested Lo ops

Sometimes it is necessary to jump out of more than the innermost DO lo op Toallow this lo ops can

b e given names and then the EXIT statement can b e made to refer to a particularloop An analogous

situation also exists for CYCLE

outa DO

inna DO

IF aGTb EXIT outa jump to line

IF aEQb CYCLE outa jump to line

IF cGTd EXIT inna jump to line

IF cEQa CYCLE jump to line

END DO inna

END DO outa

The optional name following the EXIT or CYCLE highlights which lo op the statement refers to

For example

IF aEQb CYCLE outa

causes a jump to the rst DO lo op named outa line

Likewise

IF cGTd EXIT inna

jumps to line

If the name is missing then the directive is applied as usual to the next outermost lo op so

IF cEQa CYCLE

causes control to jump to line

The scop e of a lo op name is the same as that of any construct name

Question Mathematical Magic

If you take a p ositive integer halve it if it is even or triple it and add one if it is odd and re

p eat then the numb er will eventually b ecome one

Septemb er University of Liverp o ol

DO WHILE Lo ops

Set up a lo op containing a statement to read in a numb er input terminated by zero and to print

out the sequence obtained from each input The numb er is considered to b e very unlucky and if it

is obtained as part of the sequence then execution should immediately terminate with an appropriate

message

Demonstrate that your program works by outputting the sequences generated by the following sets of

numb ers

DO WHILE Lo ops

If a condition is to b e tested at the top of a lo op a DO WHILE lo op could b e used

DO WHILE a EQ b

END DO

The lo op only executes if the logical expression evaluates to TRUE Clearly here the values of a or

b must b e mo died within the lo op otherwise it will never terminate

The ab ove lo op is functionally equivalent to

DO IF a NE b EXIT

END DO

EXIT and CYCLE can still b e used in a DO WHILE lo op just as there could b e multiple EXIT and CYCLE

statements in a regularloop

Indexed DO Lo op

Lo ops can b e written which cycle a xed numb er of times For example

DO i

END DO

is a DO lo op that will execute times it is exactly equivalent to

DO i

END DO

The syntax is as follows

Fortran Course Notes File CourseNotesps

Control Flow

DO DOvar expr expr expr

execstmts

END DO

The lo op can b e named and the execstmts could contain EXIT or CYCLE statements however a

WHILE clause cannot b e used but this can b e simulated with an EXIT statement if desired

The numb er of iterations which is evaluated b efore execution of the lo op b egins is calculated as

MAXINT expr expr expr expr

in other words the lo op runs from expr to expr in steps of expr If this gives a zero or

negative count then the lo op is not executed It seems to b e a common misconception that Fortran

lo ops always have to b e executed once this came from Fortran and is now totally incorrect

Zero executed lo ops are useful forprogramming degenerate cases

If expr is absent it is assumed to b e

The iteration count is worked out as follows adapted from the standard

expr is calculated

expr is calculated

expr ifpresent is calculated

the DO variable is assigned the value of expr

the iteration count is established using the formula given ab ove

The execution cycle is p erformed as follows adapted from the standard

the iteration count is tested and if it is zero then the lo op terminates

if it is non zero the lo op is executed

conceptually at the END DO the iteration count is decreased by one and the DO variable is

incremented by expr Note howthe DO variable can b e greater than expr

control passes to the top of the lo op again and the cycle b egins again

More complex examples may involve expressions and lo ops running from high to low

DO i kj

DO i k kj jk

END DO

END DO

An indexed lo op could be achieved using an induction variable and EXIT statement however the

indexed DO lo op is b etter suited as there is less scop e forerror

The DO variable cannot b e assigned to within the lo op

Septemb er University of Liverp o ol

Indexed DO Lo op

Examples of Lo op Counts

There now follows a few examples of dierent lo ops

upp er b ound not exact

loopy DO i

iterations

END DO loopy

According to the rules given earlier the fact that the upp er b ound is not exact is not relevant

The iteration count is INT so i will take the values and nally

although the lo op is not executed when i holds this value this is its nal value

negative stride

DO j

iterations

END DO

similar to ab ove except the lo op runs the other way high to low j will b egin with the value

and will end up b eing equal to

a zerotrip lo op

DO k

iterations

loop skipped

END DO

This is a false example in the sense that the lo op b ounds are literals and there would b e no p oint

in co ding a lo op of this fashion as it would never ever b e executed The execution is as follows

rstly k is set to and then the iteration count would b e evaluated and set to This would

mean that the lo op is skipp ed the only consequence of its existence b eing that k holds the value

missing stride assume it is

DO l

i

iterations

END DO

As the stride is missing it must take its default value which is This lo op runs from to

so the implied stride means that the lo op is executed times

missing stride

DO l

zerotrip

END DO

As the stride is missing it must take its default value which is This lo op runs from high to low

to so the implied stride means that the lo op is not executed The nal value of l will b e

Fortran Course Notes File CourseNotesps

Control Flow

Scop e of DO Variables

Fortran is not blo ck structured all DO variables are visible after the lo op and have a sp ecic value

The index variable is recalculated at the top of the lo op and then compared with expr if the lo op

has nished execution jumps to the statement after the corresp onding END DO The lo op is executed

three times and i is assigned to times the index variable will retain the value that it had just b een

assigned For example

DO i

PRINT I in loop i

END DO

PRINT I after loop i

will pro duce

I in loop

I in loop

I in loop

I after loop

Elsewhere in the program the index variable may b e used freely but in the lo op it can only b e referenced

and must not have its value changed

SELECT CASE Construct

The SELECT CASE Construct is similar to an IF construct It is a useful control construct if one of

several paths through an algorithm must b e chosen based on the value of a particular expression

SELECT CASE i

CASE

PRINTi is prime

CASE

PRINTi is

CASE DEFAULT

PRINT i is not prime and is

END SELECT

The rst branch is executed if i is equal to or the second if i is greater than orequalto

and the third branch if neither of the previous has already b een executed

A slightly more complex example with the corresp onding IF structure given as a comment

SELECT CASE num

CASE

IFnumOR ORnum THEN

PRINT Woof woof

CASE

Septemb er University of Liverp o ol

SELECT CASE Construct

ELSEIFnumGEANDnumLE OR

PRINT Bow wow

CASE

ELSEIF numGE THEN

PRINT Bark

CASE DEFAULT

ELSE

PRINT Meow

END SELECT

ENDIF

Imp ortant p oints are

the caseexpr in this case is num

the rst caseselector means if num is equal to either or then

the second caseselector means if num is b etween and inclusive

or and inclusive then

sp ecies the range of greater than or equal to one hundred

if a case branch has b een executed then when the next caseselector is encountered control

jumps to the END SELECT statement

if a particular case expression is not satised then the next one is tested

An IF ENDIF construct could b e used but a SELECT CASE is neater and more ecient

SELECT CASE is more ecient than ELSEIF b ecause there is only one expression that controls the

branching The expression needs to be evaluated once and then control is transferred to whichever

branch corresp onds to the expressions value An IF ELSEIF has the p otential to have a dierent

expression to evaluate at each branch p oint making it less ecient

Consider the SELECT CASE construct

SELECT CASE I

CASE Print I

CASE Print I and I

CASE Print I

CASE DEFAULT Print I

END SELECT CASE

this maps onto the following control ow structure

Fortran Course Notes File CourseNotesps

Control Flow

SELECT CASE (I)

CASE(1)CASE(2:9) CASE(10:) CASE DEFAULT

PRINT*, PRINT*, "I==1" PRINT*, "I>=10" PRINT*, "I<=0" "I>=2 and I<=9"

END SELECT CASE

Figure Visualisation of a SELECT CASE Construct

The syntax is as follows

name SELECT CASE caseexpr

CASE caseselector name

execstmts

CASE DEFAULT name

execstmts

END SELECT name

Note

the caseexpr must b e scalarandINTEGER LOGICAL or CHARACTER valued

there may b e any numb er of general CASE statements but only one CASE DEFAULT branch

the caseselector must b e a parenthesised single value ora range section with a stride of

one for example TRUE or A range sp ecier is a lower and upp er limit separated

by a single colon One or other of the b ounds is optional giving an op en ended range sp ecier

the caseexpr is evaluated and compared with the caseselector s in turn to see which

branch to take

if no branches are chosen then the CASE DEFAULT is executed if present

when the execstmts in the selected branch have b een executed control jumps out of the

CASE construct via the END SELECT statement

as with other similar structures it is not p ossible to jump into a CASE construct

CASE constructs may b e named if the header is named then so must b e the END SELECT statement

IfanyoftheCASE branches are named then so must b e the SELECT statement and the END statement

Amore complex example is given b elow this also demonstrates how SELECT CASE constructs maybe

named

Septemb er University of Liverp o ol

outa SELECT CASE n

CASE outa

M

CASE outa

DO i n

inna SELECT CASE lineii

CASE

PRINT At EOL

CASE azAZ

PRINT Alphabetic

CASE DEFAULT

PRINT CHAR OK

END SELECT inna

END DO

CASE DEFAULT outa

PRINT N is zero

END SELECT outa

Analysis

the rst SELECT CASE statement is named outa and so is the corresp onding END SELECT state

ment

the caseexpr in this case is n this is evaluated rst and its value stored somewhere

the rst caseselector means if n is less than or equal to so if this is true then

this branch is executed when the next caseselector is encountered control jumps to the

END SELECT statement

if the ab ove case expression is not satised then the next one is tested sp ecies the range

of greater than or equal to one If n satises this then the DO lo op containing the nested CASE

construct is entered If it do es not then the DEFAULT action is carried out In this case this

branch corresp onds to the value the only value not covered bytheotherbranches

the inner case structure demonstrates a scalar CHARACTER caseexpr which is matched to a

list of p ossible values or indeed a list of p ossible ranges If the character substring lineii

matches a value from either the list or list of ranges then the appropriate branch is executed If

it is not matched then the DEFAULT branch is executed Note a CHARACTER substring cannot

b e written as linei

this inner case structure is executed n times as sp ecied by the lo op and then control passes

back to the outer case structure Since the executable statements of the case branch have now

b een completed the construct is exited

Mixing Objects of Dierent Typ es

Mixed Numeric Typ e Expressions

When an subexpression is evaluated the actual calculation in the CPU must b e b etween op erands of

the same typ e this means if the expression is of mixed typ e the compiler must automatically convert

promote or co erce one typ e to another Default typ es have an implied ordering

Fortran Course Notes File CourseNotesps

Mixing Objects of Dierent Typ es

INTEGER lowest

REAL

DOUBLE PRECISION

COMPLEX highest

thus if an INTEGER is mixed with a REAL the INTEGER is promoted to a REAL and then the calculation

p erformed the resultant expression is of typ e REAL

For example

INTEGER REAL gives a REAL is

REAL INTEGER gives a REAL is

DOUBLE PRECISION REAL gives DOUBLE PRECISION

COMPLEX anytyp e gives COMPLEX

DOUBLE PRECISION REAL INTEGER gives DOUBLE PRECISION

Consider the expression

intrealdpc

the typ es are co erced as follows

int to REAL

intreal to DOUBLE PRECISION

intrealdp to COMPLEX

The ab ove expression is therefore COMPLEX valued

Note that numeric and nonnumeric typ es cannot b e mixed using intrinsic op erators nor can LOGICAL

and CHARACTER

In general one must think hard and long ab out mixed mo de arithmetic

Mixed Typ e Assignment

When the RHS expression of a mixed typ e assignment statement has b een evaluated it has a sp ecic

typ e this typ e must then be converted to t in with the LHS This conversion could be either a

promotion or a relegation For example

INTEGER REAL or DOUBLE PRECISION

The RHS needs relegating to b e an INTEGER value The right hand side is evaluated and then

the value is truncated all the decimal places lopp ed o then assigned to the LHS

Septemb er University of Liverp o ol

Integer Division

REAL or DOUBLE PRECISION INTEGER

The INTEGER needs promoting to b ecome a REAL The right hand side expression is simply stored

approximately in the LHS

For example as real values are stored approximately

REAL a b

INTEGER i j k

i i will be

j j will be

k a b k will be or

Notes

since i is INTEGER the value must b e truncated integers are always formed by truncating

towards zero

j an INTEGER would b e truncated to

the result of a b would b e close to it could b e or it could b e

so b ecause of truncation k could contain either or

Care must b e taken when mixing typ es

Integer Division

If one integer divides another in a sub expression then the typ e of that sub expression is INTEGER

Confusion often arises ab out integer division in short division of two integers pro duces an integer

result by truncation towards zero

Consider

REAL a b c d e

a

b

c

d

e

a is ab out The integer expression is evaluated and then truncated towards

zero to pro duce an integral value Its says in the Fortran standard P section

The result of such an op eration integer division is the integer closest to the mathematical

quotient and b etween zero and the mathematical quotient inclusively

b is ab out for the same reasons as ab ove

c is ab out b ecause due to the parentheses is calculated

d and e are ab out b ecause b oth RHSs are evaluated to b e real numb ers in

and the integers are promoted to real numb ers b efore the division

Fortran Course Notes File CourseNotesps

Intrinsic Pro cedures

Question Decimal to Roman Numerals Conversion

Using a SELECT CASE blo ck and integer division write a program that reads in a decimal num

ber between and and prints out the equivalent in Roman Numerals

Demonstrate that your program works with the numb ers

The output should contain no emb edded spaces

i x c

ii xx cc

iii xxx ccc

iv xl cd

v l d

vi lx dc

vii lxx dcc

viii lxxx dccc

ix xc cm

Hint Use a CHARACTER string or CHARACTER strings to store the numb er b efore output The longest

numb er is dccclxxxviii characters

Intrinsic Pro cedures

Some tasks in a language are p erformed frequently Fortran has ecient implementations of such

common tasks builtin to the language these pro cedures are called intrinsic pro cedures Fortran

has intrinsic pro cedures in a numb er of dierent classes

elemental such as

mathematical such as trigonometric and logarithms for example SIN or LOG

numeric for example SUM or CEILING

character for example INDEX and TRIM

bit manipulation for example IAND and IOR There is no BIT data typ e but intrinsics exist

for manipulating integers as if they were bit variables

Elemental pro cedures apply to scalar objects as well as arrays when an array argument is

supplied the same function is applied to each element of the array at conceptually the same

time

inquiryfor example ALLOCATED and SIZE These rep ort on the status of a program We can

inquire ab out

Septemb er University of Liverp o ol

Typ e Conversion Functions

the status of dynamic objects

array b ounds shap e and size

kind parameters of an object and available kind representations useful forportable co de

the numerical mo del used to represent typ es and kinds

argument presence for use with OPTIONAL dummy arguments

transformational for example REAL and TRANSPOSE The functionality includes

rep eat forcharacters rep eats strings

mathematical reduction pro cedures ie given an array return an object of less rank

array manipulation shift op erations RESHAPE PACK

typ e co ercion TRANSFER copies bitforbit to an object of a dierent typ e Stops p eople

doing dirty tricks like changing the typ e of an object across a pro cedure b oundary which

was a p opular Fortran trick

PRODUCT arrays PRODUCT and DOT

miscellaneous nonelemental SUBROUTINEs including timing routines for example SYSTEM

CLOCK and DATE AND TIME

The pro cedures vary in what arguments are p ermitted Some pro cedures can b e applied to scalars and

arrays some to only scalars and some to only arrays All intrinsics which take REAL valued arguments

also accept DOUBLE PRECISION arguments

Typ e Conversion Functions

In Fortran it is easy to explicitly transform the typ e of a constant orvariable by using the inbuilt

intrinsic functions

REALi converts the integer i to the corresp onding real approximation the argument to REAL

can b e INTEGER DOUBLE PRECISION or COMPLEX

INTx converts real x to the integer equivalent following the truncation rules given b efore The

argument to INT can b e REAL DOUBLE PRECISION or COMPLEX

Other functions mayform integers from noninteger values

CEILINGx smallest integer greater or equal to x

FLOORx largest integer less or equal to x

NINTx nearest integer to x

DBLEa converts a to DOUBLE PRECISION the argument to DBLE can be INTEGER REAL or

COMPLEX

CMPLXx or CMPLXxy converts x to a complex value x iy

IACHARc returns thepositionofthe CHARACTER variable c in the ASCI I collating sequence

the argument must b e a single CHARACTER

th

ACHARi returns the i character in the ASCI I collating sequence see the argument ACHAR

must b e a single INTEGER

Fortran Course Notes File CourseNotesps

Intrinsic Pro cedures

For example

PRINT REAL INT INT

PRINT IACHARC ACHAR

would give

C

Mathematical Intrinsic Functions

Summary

ACOSx arccosine

ASINx arcsine

ATANx arctangent

ATANyx arctangent of complex numb er x y

COSx cosine where x is in radians

COSHx hyp erb olic cosine where x is in radians

EXPx e raised to the p ower x

LOGx of x

LOGx logarithm base of x

SINx sine where x is in radians

SINHx hyp erb olic sine where x is in radians

SQRTx the square ro ot of x

TANx tangent where x is in radians

TANHx tangent where x is in radians

ASIN ACOS arcsin and arccos

The argument to each must b e real and jjfor example ASIN has value

radians

ATAN arctan

The argument must b e real valued for example ATAN is ATAN has value



ATAN arctan the principle value of the nonzero complex numb er XY for example

ATAN has value

The two arguments Y X note order must be real valued if Y is zero then X cannot be

These numb ers represent the complex value XY

TAN COS SIN tangent cosine and sine

Their arguments must b e real or complex and are measured in radiansfor example COS

is

TANH COSH SINH hyp erb olic trigonometric functions

The actual arguments must b e REAL valued for example COSH is

Septemb er University of Liverp o ol

Numeric Intrinsic Functions

x

EXP LOG LOG SQRT e natural logarithm logarithm base and square ro ot

The arguments must must b e real or complex with certain constraints for example EXP

is

Note that SQRT is an invalid expression b ecause the argument to SQRT cannot b e INTEGER

All angles are expressed in radians

Question Point on a circle

Write a program to read in a vector dened by a length r and an angle in degrees which

prints out the corresp onding x y coordinates Recall that arguments to trigonometric functions are

in radians

Demonstrate correctness by giving the x y coordinates for the following vectors

r

r

r

r

r

(x,y)

r

θ

Hint rememb er that

y

sin

r

and

x

cos

r

Numeric Intrinsic Functions

Summary

Fortran Course Notes File CourseNotesps

Intrinsic Pro cedures

ABSa absolute value

AINTa truncates a to whole REAL numb er

ANINTa nearest whole REAL numb er

CEILINGa smallest INTEGER greater than or equal to REAL numb er

CMPLXxy convert to COMPLEX

DBLEx convert to DOUBLE PRECISION

DIMxy p ositive dierence

FLOORa biggest INTEGER less than or equal to real numb er

INTa truncates a into an INTEGER

MAXaaa the maximum value of the arguments

MINaaa the minimum value of the arguments

MODap function

MODULOap mo dulo function

NINTx nearest INTEGER to a REAL numb er

REALa converts to the equivalent REAL value

SIGNab transfer of sign ABSabABSb

As all are elemental they can accept arrayarguments the result is the same shap e as the arguments

and is the same as if the intrinsic had b een called separately foreacharray element of the argument

ABS absolute value

The argument can b e INTEGER REAL or COMPLEX the result is of the same typ e as the argument

except for complex where the result is real valued for example ABS is ABS is

and ABSCMPLX is

AINT truncates to a whole numb er

The argument and result are real valued for example AINT is and AINT is

ANINT nearest whole numb er

The argument and result are real valued for example AINT is and AINT is

CEILING FLOOR smallest INTEGER greater than or equal to or biggest INTEGER less than

or equal to the argument

The argument must b e REALfor example CEILING is CEILING is

CMPLX converts to complex value

The argument must b e two real numb ers for example CMPLX is a complex numb er

DBLE co erce to DOUBLE PRECISION data typ e

Arguments must b e REAL INTEGER or COMPLEX The result is the actual argument converted to

a DOUBLE PRECISION numb er

DIM p ositive dierence

Arguments must b e REAL or INTEGERIf X bigger than Y then DIMXY XYif Y X and

result of XY is negative then DIMXY is zero for example DIM is and DIM is

INT truncates to an INTEGER as in integer division

Actual argument must b e numeric for example INT isand INTCMPLX is

MAX and MIN maximum and minimum functions

These must have at least two arguments which must be INTEGER or REAL MAX is

Septemb er University of Liverp o ol

Numeric Intrinsic Functions

MOD remainder function

Arguments must be REAL or INTEGER MODap is the remainder when evaluating ap for

example MOD is MOD is

MODULO mo dulo function

Arguments must be REAL or INTEGER MODULOab is amo db for example MOD is

MOD is

REAL coverts to REAL value

For example REAL is

SIGN transfers the sign of the second argument to the rst

The arguments are real or integer and the result is of the same typ e and is equal to ABSab

ABSbfor example SIGN is SIGN is

Question Quadratic equation solver

Write a program to read in values of a b and c and calculate the real ro ots of the corresp ond

ing quadratic equation



y a x bx c

Point out if the equation only has one or no real ro ots

The program should rep eatedly exp ect input a b and c should b e used to terminate

Hint recall that the solution of a general quadratic equation equation is

p



b b ac

x

a

Hint The program has a single ro ot if



b ac

two real ro ots if



b ac

and imaginary ro ots if



b ac

Fortran Course Notes File CourseNotesps

Intrinsic Pro cedures

Character Intrinsic Functions

Summary

th

ACHARi i character in ASCI I collating sequence

ADJUSTLstr adjust left

ADJUSTRstr adjust right

th

CHARi i character in pro cessor collating sequence

IACHARch p osition of character in ASCI I collating sequence

ICHARch p osition of character in pro cessor collating sequence

INDEXstrsubstr starting p osition of substring

LENstr Length of string

LEN TRIMstr Length of string without trailing blanks

LGEstrstr lexically GE

LGTstrstr lexically GT

LLEstrstr lexically LE

LLTstrstr lexically LT

REPEATstri rep eat i times

SCANstrset scan a string forcharacters in a set

TRIMstr remove trailing blanks

VERIFYstrset verify the set of characters in a string

th

ACHAR i character in ASCI I collating sequence

The argument must b e b etween and this function is the inverse of IACHARfor example

ACHAR is d Compare to CHAR

ADJUSTL adjust a string left

The argument must b e a string and the result is the same string with leading blanks removed

and inserted as trailing blanks

ADJUSTR adjust a string right

The argument must b e a string and the result is the same string with trailing blanks removed

and inserted as leading blanks

th

CHAR i character in the compilers collating sequence

Takes a single character as an argument The result is similarto ACHAR but uses the compilers

collating sequence this will often b e the same as ACHAR

IACHAR p osition of a character in ASCI I collating sequence

Takes a single character as an argument which must be an ASCI I character and returns its

p osition of a character in ASCI I collating sequence for example IACHARd is

ICHAR p osition of a character in the compilers collating sequence

Takes a single character as an argument which must be valid and returns its p osition of a

character in the compilers collating sequence for example IACHARd is The result is

often the same as IACHAR

INDEX starting p osition of a substring in a string

Takes twoarguments b oth must b e of typ e CHARACTER and of the same kind the result is the

rst o ccurrence of substr in strfor example INDEXjibberisheris is

Septemb er University of Liverp o ol

LEN LEN TRIM length of string

Both take one string argument the rst function returns the length of the string including the

trailing blanks and the second discounts the blanks for example LENWhoosh is

LEN TRIMWhoosh is

LGE LLT lexical p ositional op erators

These functions accept two strings of the same kind the result is comparable to that of relational

op erators in the sense that a LOGICAL value is returned governed by the lexical p osition of

the string in ASCI I order This means there is a dierence between the case of a letter for

example LGTTinTin returns FALSE LGETinTin and LGEtinTin

return TRUE

REPEAT concatenate string i times

The rst argument is a string and the second the numb er of times it is to be rep eated for

example REPEATBoutrous is Boutrous Boutrous

TRIM remove trailing blanks

VERIFY verify that a set of characters contains all the letters in a string

The two arguments set and string are characters and of the same kind Given a set of

characters stored in a string the result is the rst p osition in the string which is a character

that is NOT in the set for example VERIFYABBAA is and VERIFYABBABA is

Question Concatenate Names

Write a program which accepts two names Christian name and Family name a maximum of

characters each and outputs a single string containing the full name separated by one space with the

rst letter of each name in upp er case and the rest of the name in lower case You may assume that

all inputs are valid names

Hint a comes b efore A in the ASCI I collating sequence

This sequence is given in the notes

Simple Input Output

PRINT Statement

This is the simplest form of directing unformatted data to the standard output channel for example

PROGRAM Outie

CHARACTERLEN PARAMETER longname

Llanfairphwyllgogogoch

REAL x y z

LOGICAL lacigol

x y z

lacigol y eq x

PRINT longname

PRINT Spock says illogical

Fortran Course Notes File CourseNotesps

Simple Input Output

Captain

PRINT X x Y y Z z

PRINT Logical val lacigol

END PROGRAM Outie

pro duces on the screen

Llanfairphwyllgogogoch

Spock says illogical Captain

X Y Z

Logical val F

As can b e seen from the ab ove example the PRINT statement takes a comma separated list of things

to print the list can b e any printable object including userdened typ es as long as they dont contain

p ointers The indicates the output is in free default format Fortran supp orts a great wealth

of output and input formatting which is not all describ ed here

There are a couple of p oints to raise

LOGICAL variables can b e printed

lacigol y eq x

generates an F signifying FALSE

Strings can b e split across lines

PRINT Spock says illogical

Captain

If a CHARACTER string crosses a line indentation can still b e used if an is app ended to the end

of the rst line and the p osition from where the string is wanted to b egin on the second see

the Sp o ck line in the example the s act like a single space

The double in the string the rst one escap es the second Strings maybe delimited bythe

double or single quote symb ols and but these may not b e mixed in order to delimit a string

The following would pro duce the same output as the statement in the program

PRINT Spock says illogical

Captain

In this case the delimiter do es not have to b e escap ed

Notice how the output has many more spaces than the PRINT statement indicates This is b ecause

output is unformatted The default formatting is likely to b e dierent b etween compilers

Each PRINT statement b egins a new line nonadvancing IO is available but we have to sp ecify

it in a FORMAT statement

Septemb er University of Liverp o ol

READ Statement

READ Statement

This is the simplest form of reading unformatted data from the standard input channel for example

if the typ e declarations are the same as for the PRINT example

READ longname

READ x y z

READ lacigol

would read the following input from the keyb oard

Llanphairphwyllgogogoch

e

T

Note

each READ statement reads from a newline

the READ statement can transfer any object of intrinsic typ e from the standard input

The format sp ecier in the READ statement is comparable to the functionalityof PRINTin other

words unformatted data is read Actually this is not strictly true formatted data can b e read but the

format cannot b e sp ecied As long as each entity to b e read in is blank separated then the READ

statement simply works through its argument list Each READ statement b egins a new line so if there

are less arguments to the read statement than there are entries on a line the extra items will b e ignored

Fortran Course Notes File CourseNotesps

Mo dule

Arrays

Arrays

Arrays or matrices hold a collection of dierent values at the same time Individual elements are

accessed by subscripting the array

A element array can b e visualised as

1231314 15

Figure A One Dimensional D Array

And a arrayas

Dimension 2

1,1 1,2 1,3

2,1 2,2 2,3

3,1 3,2 3,3

Dimension 1 4,1 4,2 4,3

5,1 5,2 5,3

Figure ATwo Dimensional D Array

Every arrayhasatyp e REAL INTEGER etc so each element holds a value of that typ e

ArrayTerminology

Array Terminology

Examples of declarations

REAL DIMENSION X

REAL DIMENSION Y Z

The ab ove are explicitshap e arrays

If the lower b ound is not explicitly stated it is taken to b e

Terminology

rank the numb er of dimensions up to and including dimensions X has rank Y and Z have

rank

b ounds upp er and lower limits of indices an unsp ecied b ound is X has lower b ound and

upp er b ound Y and Z have lower b ounds of and with upp er b ounds and

extent numb er of elements in dimension which can b e zero X has extent Y and Z have

extents and

size either the total numb er of elements or if particular dimension is sp ecied the numb er

of elements in that dimension All arrays have size

shap e rank and extents X has shap e Y and Z have shap e

conformable twoarrays are conformable if they have the same shap e for operations between

twoarrays the shap es of the sections must generally conform just like in mathematics Y

and Z have the same shap e so they conform

there is no storage asso ciation forFortran arrays

Explicitshap e arrays can have symb olic b ounds so long as they are initialisation expressions evalu

atable at compile time

Question Rank Extents etc

Give the rank b ounds size and shap e of the arrays dened as follows

REAL DIMENSION ONE

REAL DIMENSION TWO

INTEGER DIMENSION THREE

REAL DIMENSION FOUR

Declarations

As long as the value of lda is known the following are valid

Fortran Course Notes File CourseNotesps

Arrays

REAL DIMENSION R

REAL DIMENSION S

REAL T

REAL DIMENSION X

INTEGER PARAMETER lda

REAL DIMENSIONlda Y

REAL DIMENSIONldalda Z

The ab ove example demonstrates

b ounds can b egin and end anywhere the array X

default lower b ound is

there is a shorthand form of declaration see T

arrays can b e zerosized If lda were set to b e zero

INTEGER PARAMETER lda

then the array Y would b e zero sized

Zerosized arrays are useful when programming degenerate cases esp ecially when invoking pro ce

dures in this case wewould exp ect lda to b e a dummy argument which determines the size of

some lo cal or automatic array no extra co de has to b e added to test for zero extents in any

of the dimensions statements including references to zero sized arrays are simply ignored

Question Hotel Array

Declare an array of rank which might be suitable for representing a hotel with o ors and

ro oms on each o or and two b eds in each ro om Howwould the second b ed in the th ro om on o or

b e referenced

Consider the following declarations

REAL DIMENSION A

REAL DIMENSION B

REAL DIMENSION C

REAL DIMENSION D

Individual array elements are denoted by subscripting the array name by an INTEGER for example

th

A element of Aor C elements down across

The arrays can b e visualised as b elow

The rst dimension runs up and down the page and the second dimensions runs across the page

Question Array References

Given

Septemb er University of Liverp o ol

Array Conformance

A(1) A(15)

B(-4,0) B(-4,2) C(1,1) C(1,3) D(0,0) D(0,2)

B(0,0) B(0,2) C(5,1) C(5,3)

D(4,0) D(4,2)

Figure Visualisation of Arrays

INTEGER i j

REAL DIMENSION A

which of the following are valid array references for the array

A

A

AI

A

AIJ

AINTATAN

Hint ATAN is

Array Conformance

If an object or subobject is used directly in an expression then it must conform with all other objects

in that expression Note that a scalar conforms to any array with the same value for every element

fortwoarray references to conform b oth objects must b e the same shap e

Using the declarations from b efore

C D is valid

A B is not valid

Fortran Course Notes File CourseNotesps

Arrays

C = D Valid

B = A

Invalid

Figure Visualisation of conforming Arrays

Visualisation

A and B have the same size elements but have dierent shap es so cannot b e directly equated To

force conformance the array must b e used as an argument to a transformational intrinsic to change its

shap e for example

B RESHAPEA is see later

A PACKBTRUE is see later

A RESHAPEB is see later

B PACKATRUE is see later

Arrays can have their shap es changed by using transformational intrinsics including MERGE PACK

SPREAD UNPACK and RESHAPE

Twoarrays of dierent typ es conform and if used in the same expression will have the relevant typ e

co ercion p erformed just like scalars

Question Conformance

Given

REAL DIMENSION ONE

REAL DIMENSION TWO

INTEGER DIMENSION THREE

REAL DIMENSION FOUR

Which two of the arrays are conformable

Septemb er University of Liverp o ol

Array Element Ordering

first elt

C(1,1) C(1,3)

C(5,1) C(5,3)

last elt

Figure Visualisation Of Array Element Ordering

Array Element Ordering

Fortran do es not have any storage asso ciation meaning that unlike Fortran the standard

do es not sp ecify howarrays are to b e organised in memory This makes passing arrays to a pro cedure

written in a dierent language very dicult indeed

The lack of implicit storage asso ciation makes it easier to write p ortable programs and allows compiler

writers more freedom to implement lo cal optimisations For example in distributed memory computers

an array may be stored over pro cessors with each pro cessor owning only a small section of the

whole array the standard will allow this

There are certain situations where an ordering is needed for example during input or output and in

these circumstances Fortran do es dene ordering which can b e used in such contexts It is dened

in the same manner as the Fortran storage asso ciation but it do es not imply anything ab out

howarray elements are stored

The array element ordering is again of column majorform

CCCCCC

This ordering is used in array constructors IO statements certain intrinsics TRANSFER RESHAPE

PACK UNPACK and MERGE and any other contexts where an ordering is needed

Question Array Element Ordering

Given

REAL DIMENSION ONE

Fortran Course Notes File CourseNotesps

Arrays

REAL DIMENSION TWO

INTEGER DIMENSION THREE

REAL DIMENSION FOUR

Write down the array element order of each array

Array Syntax

Using the earlier declarations references can b e made to

whole arrays conformable

A

This statement will set whole array A to zero Each assignment is p erformed conceptually

at the same time Scalars always conform with arrays

B C D

This adds the corresp onding elements of C and D and then assigns each element if the result

to the corresp onding element of B

For this to b e legal Fortran b oth arrays in the RHS expression must conform B and C must

b e same shap e and size The assignment could have b een written B C D

demonstrating how a whole array can b e referenced by subscripting it with a colon This is

boundupper bound and is exactly equivalent to using only its name shorthand for lower

with no subscripts orparentheses

elements

A

This statement sets one element the rst element of A A to zero

B A C

Sets element B to the sum of two elements

If present array subscripts must b e integer valued expressions

A particular element of an array is accessed by subscripting the array name with an integer

which is within the b ounds of the declared extent Subscripting directly with a REAL COMPLEX

CHARACTER DOUBLE PRECISION or LOGICAL is an error This and indeed the previous example

demonstrates how scalars literals and variables conform to arrays scalars can b e used in many

contexts in place of an array

array sections

A

This assignment sets three elements of A A A and Atozero

BC

Adds one to the subsection of C and assigns to the subsection of B

The ab ove examples demonstrate how parts or subsections of arrays can be referenced An

array section can be sp ecied using the colon range notation rst encountered in the SELECT

CASE construct In addition the sequence of elements can also have a stride like DO lo ops

meaning that the section sp ecication is denoted byasubscripttriplet which is a linear function

Care must b e taken when referring to dierent sections of the same array on b oth sides of an assignment

statement for example

Septemb er University of Liverp o ol

Whole ArrayExpressions

DO i

Ai Ai Ai

END DO

is not the same as

A A A

in the rst case a general element i of A has the value

Ai Ai Ai A A

but in the vectorised statement it has the value

Ai Ai Ai

The correct vector equivalent to the original DOlo op can be achieved by using the SUM intrinsic

A SUMi i

In summary b oth scalars and arrays can b e thought of as objects More or less the same op erations

can b e p erformed on each with the array op erations b eing p erformed in parallel It is not p ossible to

have a scalar on the LHS of an assignment and a non scalararray reference on the RHS unless that

sectionisanargument to a reduction function

Whole Array Expressions

A whole or section of an array can b e treated like a single variable in that all intrinsic op erators which

apply to intrinsic typ es have their meaning extended to apply to conformable arrays for example

B C D B

as long as B C and D conform then the ab ove assignment is valid Recall that the RHS of the

op erator must be scalar Note that in the ab ove example CD is not matrix multiplication

MATMULCD should b e used if this is the desired op eration

The ab ove assignment is equivalent to

PARALLEL

B CDB in

B CDB in

B CDB in

B CDB in

END PARALLEL

With array assignment there is no implied order of the individual assignments they are performed

conceptuallyinparallel

In addition to the ab ove op erators the subset of intrinsic functions termed elemental can also be

applied for example

Fortran Course Notes File CourseNotesps

Arrays

B SINCCOSD

The functions are also applied element by element thus the ab ove is equivalent to the parallel execution

of

PARALLEL

B SINCCOSD

B SINCCOSD

END PARALLEL

Many of Fortran s intrinsics are elemental including all numeric mathematical bit character and

logical intrinsics

Again it must be stressed that conceptually there is no order implied in the array statement form

each individual assignment can b e thought of as b eing executed in parallel b etween corresp onding

elements of the arrays this is dierent from the DOlo op

Visualising Array Sections

Consider the declaration

REAL DIMENSION P

The sections

P is a section the missing stride implies a value of

P which could b e written Pisa section

A missing upp er b ound in the rst dimension means assume the upp er b ound as declared

A missing lower b ound is the lower b ound as declared

P is a D array with elements P is a D array

P is a section This could also b e written as P here b oth upp er

and lower b ounds are missing so the values are taken to b e the b ounds as declared

Conformance

P P is a valid assignment b oth LHS and RHS are sections

P is a valid assignment a scalaron the RHS conforms to any array on the

LHS of an assignment

P P is not a valid assignment an attempt is made to equate a

section with a section the array sections do not conform

P P is not a valid assignment an attempt is made to equate a

section with a element D array

It is imp ortant to recognise the dierence b etween an n element D arrayanda n D array

Septemb er University of Liverp o ol

Visualising Array Sections

P(1:3,1:4) P(2:6:2,1:7:3)

P(2:5,7) P(2:5,7:7) P(1:6:2,1:8:2)

Figure Visualisation of Array Sections

Fortran Course Notes File CourseNotesps

Arrays

P is a D section the scalar in the second dimension collapses the dimension

P is a D section the second dimension is sp ecied with a section a range not a

scalar so the resultant subobject is still two dimensional

Array Sections

The general form of a subscripttriplet sp ecier is

bound b ound stride

The section starts at b ound andendsator b efore b ound stride is the increment by

which the lo cations are selected b ound b ound and stride must all b e scalar integer

expressions Thus

A the whole array

A Am to An in steps of

A as above

Amn Am to An

Amnk Am to An in steps of k

A A to A in steps of

A A to A step Zero size

Am from Am to default UPB

An from default LWB to An

A from default LWB to UPB step

Amm element section

Am scalar element not a section

are all valid

If the upp er b ound b ound is not a combination of the lower b ound plus multiples of the stride

then the actual upp er b ound is dierent from that stated this is the same principle that is applied to

DOlo ops

Another similaritywiththe DOlo ops is that when the stride is not sp ecied it is assumed to have a

value of In the ab ove example this means that A is the same as A but A is a

zero sized section and A is a section that runs backwards Zero strides are not allowed and

in any case are pretty meaningless

Other b ound sp eciers can b e absent to o if b ound or bound is absent then the lower or

upp er b ound of the dimension as declared is implied if b oth are missing then the whole dimension is

assumed

Let us examine the ab ove sections in detail

A

This runs from the declared lower b ound to the declared upp er b ound so refers to the whole

array

A

Denes the element section running from A to A The stride is missing therefore is

assumed to b e

Septemb er University of Liverp o ol

Printing Arrays

A

Exactly the same section as ab ove

Amn

From element Am to An

Amnk

The section runs from m to n in strides of k

A

This section runs from to in steps of

A

This section runs from to in steps of ie this is a zero sized section

Am

This section runs from M to the declared upp er b ound in steps of

An

This section runs from the declared lower b ound to n in steps of

A

This section runs from the declared lower b ound to the upp er b ound in strides of

Amm

This is a one element array and is distinct from Am which is a scalar reference

Question Array Sections

Declare an array which would be suitable for representing draughts board Write a program to

set all the white squares to zero and the black squares to unity A draughts board is with

alternate black and white squares

Printing Arrays

The conceptual ordering of array elements is useful for dening the order in which array elements are

output If A is a D array then

PRINT A

would pro duce output in Array Element Order

A A A A A

Sections of arrays can also b e output for example

PRINT A

Fortran Course Notes File CourseNotesps

Arrays

would pro duce

A A A A A A

An arrayofmore than one dimension is not formatted neatly if it is desired that the arraybeprinted

out rowbyrowor indeed column by column then this must b e programmed explicitly

This order could b e changed by using intrinsic functions such as RESHAPE TRANSPOSE or CSHIFT

Input of Arrays

Elements of an array can b e read in and assigned to the arrayinarray element order for example

READ A

would read data from the standard input and assign to the elements of A The input data may be

punctuated by any numb er of carriage returns which are simply ignored

Sections of arrayscanalsobeinputfor example

READ A

is p erfectly valid and will assign to the indicated subsection of A

Array IO Example

Consider the matrix A

1 4 7

2 5 8

3 6 9

Figure Visualisation of the array A

The PRINT statements in the following program

PROGRAM Owt

IMPLICIT NONE

INTEGER DIMENSION A RESHAPE

Septemb er University of Liverp o ol

Array Inquiry Intrinsics

PRINT Array element a

PRINT Array section a

PRINT Subarray a

PRINT Whole Array a

PRINT Array Transpd TRANSPOSEa

END PROGARM Owt

pro duce on the screen

Array element

Array section

Subarray

Whole Array

Array Transposed

Array Inquiry Intrinsics

These intrinsics allow the user to quiz arrays ab out their attributes and status and are most often

applied to dummy arguments in pro cedures Consider the declaration

REAL DIMENSION A

the following inquiry intrinsics are available

LBOUNDSOURCEDIM

Returns a one dimensional array containing the lower b ounds of an array or if a dimension is

sp ecied a scalar containing the lower b ound in that dimension For example

LBOUNDA is array

LBOUNDA is scalar

UBOUNDSOURCEDIM

Returns a one dimensional array containing the upp er b ounds of an arrayor if a dimension is

sp ecied a scalar containing the upp er b ound in that dimension For example

UBOUNDA is

UBOUNDA is

SHAPESOURCE

Returns a one dimensional array containing the shap e of an object For example

SHAPEA is array

SHAPE is array

SIZESOURCEDIM

Returns a scalar containing the total numb er of array elements either in the whole arrayorinan

optionally sp ecied dimension For example

SIZEA is

Fortran Course Notes File CourseNotesps

Arrays

SIZEA is

SIZE is an errorastheargument must not b e scalar

ALLOCATEDSOURCE

Returns a scalar LOGICAL result indicating whether an array is allo cated ornot For example

PROGRAM Main

IMPLICIT NONE

INTEGER ALLOCATABLE DIMENSION Vec

PRINT ALLOCATEDVec

ALLOCATEVec

PRINT ALLOCATEDVec

DEALLOCATEVec

PRINT ALLOCATEDVec

END PROGRAM Main

will pro duce FALSE TRUE and FALSE in that order

Question Inquiry intrinsics etc

Given

INTEGER DIMENSION A

Write a small program which contains intrinsic function calls to show

the total numb er of elements in A

the shap e of A

the lower b ound in dimension

the upp er b ound in dimension

Array Constructors

Array constructors are used to give arrays or sections of arrays sp ecic values An array constructoris

a comma separated list of scalar expressions delimited by and The results of the expressions

are placed into the arrayinarray element order with any typ e conversions b eing p erformed in the same

manner as for regular assignment The constructor must b e of the correct length for the array in other

words the section and the constructormustconform

For example

PROGRAM MAin

IMPLICIT NONE

INTEGER DIMENSION ints

CHARACTERlen DIMENSION colours

REAL DIMENSION heights

Septemb er University of Liverp o ol

The RESHAPE Intrinsic Function

heights

colours RED GREENBLUE

note padding so strings are chars

ints i i

END PROGRAM MAin

The array and its constructor must conform

Notice that all strings in the constructorfor colours arecharacters long This is b ecause the string

within the constructor must b e the correct length forthevariable

i i is an impliedDO sp ecier and may be used in constructors to sp ecify a sequence of

constructor values There may b e any numb er of separate implied DOs which may b e mixed with other

sp ecication metho ds In the ab ove example the vector ints will contain the values

Note the format of the implied DOa DOlo op index sp ecication

surrounded byparentheses

There is a restriction that only one dimensional constructors are p ermitted for higher rank arrays the

RESHAPE intrinsic must b e used to mo dify the shap e of the result of the RHS so that it conforms to

the LHS

INTEGER DIMENSION board

board RESHAPE

The values are sp ecied as a one dimensional constructor and then the shap e is mo died to b e a

array which conforms with the declared shap e of board

Question Array Constructor

Write an array constructorfor the element rank array BOXES containing the values

The RESHAPE Intrinsic Function

RESHAPE is a general intrinsic function which delivers an array of a sp ecied shap e

RESHAPESOURCESHAPEPADORDER

Note

the RESHAPE intrinsic changes the shap e of SOURCE to the sp ecied SHAPE

SOURCE must b e intrinsic typ ed array itcannotbeanarray of userdened typ es

SHAPE is a one dimensional array sp ecifying the target shap e It is convenient to use an explicit

array constructorfor this eld in order to make things clearer

PAD is a one dimensional array of values which is used to pad out the resulting array if there are

not enough values in SOURCEThe PAD constructor is used rep eatedly in array element order

to provide enough elements for the result PAD is optional

Fortran Course Notes File CourseNotesps

Arrays

ORDER allows the dimensions to b e p ermuted in other words allows the array element ordering

to b e mo died ORDER is optional

For example the following statement assigns SOURCE to A

A RESHAPE

The result of the RESHAPE is a array sp ecied by the second argument the result is

lled in array element order and lo oks like

Visualisation

1 3 1234 2 4

RESHAPE

Figure Visualisation of the Eect of the RESHAPE Intrinsic

Also consider

A RESHAPE

ORDER

This time the array is lled up in rowmajorform the subscripts of dimension vary the quickest

this is sp ecied by the ORDER sp ecier The default ordering is of course ORDER

The ORDER keyword is necessary b ecause some optional arguments are missing A lo oks like

Clearly the result of RESHAPE must conform to the array object on the LHS of the consider

RESHAPE

this has the value

The source object has less elements than the LHS so the resulting array is padded with the extra values

taken rep eatedly from the third array argument PAD Note how this reference do es not use

keyword arguments it is directly equivalent to

Septemb er University of Liverp o ol

Array Constructors in Initialisation Statements

RESHAPESOURCE

SHAPE

PAD

ORDER

and

RESHAPESOURCE

PAD

SHAPE

ORDER

If one of the optional arguments is absent then keyword arguments should b e used for the other optional

argument to makeitclear to the compiler and the user which is the missing argument The keywords

are the names of the dummy arguments

Array Constructors in Initialisation Statements

Named array constants of any rank can b e created using the RESHAPE function as long as all comp onents

can b e evaluated at compile time just like in initialisation expressions

INTEGER DIMENSION PARAMETER Unitvec

CHARACTERLEN DIMENSION PARAMETER

lights RED BLUE GREEN

REAL DIMENSION PARAMETER

unitmatrix RESHAPE

Note how the string length of the PARAMETER lights can b e assumed from the length of the constructor

values The strings in the constructor must all b e the same length

Previously dened constants PARAMETERs may also b e used to initialise variables consider

INTEGER DIMENSION

unitmatrixT RESHAPEunitmatrix ORDER

This assigns the transp ose of unit matrix to unit matrix T

Question Travelling Salesman Problem

A salesman travels between towns A B C D E whose distances apart are given in the fol

lowing table

A B C D E

A

B

C

D

E

Which is the shortest route which takes in all the towns

Fortran Course Notes File CourseNotesps

Arrays

Allo catable Arrays

Fortran allows arrays to b e created onthey these are known as deferredshap e arrays and use

dynamic heap storage this means memory can b e grabb ed used and then put back at any p oint in

the program This facilityallows the creation of temp orary arrays which can b e created used and

discarded at will

Deferredshap e arrays are

declared like explicitshap e arrays but without the extents and with the ALLOCATABLE attribute

INTEGER DIMENSION ALLOCATABLE ages

REAL DIMENSION ALLOCATABLE speed

given a size in an ALLOCATE statement which reserves an area of memory for the object

ALLOCATEages STATierr

IF ierr NE THEN

PRINT ages Allocation request denied

END IF

ALLOCATEspeedlwbupbSTATierr

IF ierr NE THEN

PRINT speed Allocation request denied

END IF

In the ALLOCATE statement we could sp ecify a list of objects to create but in general one should

only sp ecify one array statement if there is more than one object and the allo cation fails it

is not immediately p ossible to tell which allo cation was resp onsible The optional STAT eld

rep orts on the success of the storage request if it is supplied then the keyword must b e used to

distinguish it from an array that needs allo cating If the result ierr is zero the request was

successful otherwise it failed This sp ecier should b e used as a matter of course

There is a certain overhead in managing dynamic or ALLOCATABLE arrays explicitshap e arrays are

cheap er and should b e used if the size is known and the arrays are p ersistent are used for most of the

life of the program The dynamic or heap storage is also used with p ointers and obviously only has a

nite size there may b e a time when this storage runs out If this happ ens there may b e an option

of the compiler to sp ecify increase the size of heap storage

Deallo cating Arrays

Heap storage should b e reclaimed using the DEALLOCATE statement

IF ALLOCATEDages DEALLOCATEagesSTATierr

As a matter of course the LOGICAL valued intrinsic inquiry function ALLOCATEDshouldbeusedto

check on the status of the array b efore attempting to DEALLOCATE b ecause it is an error to attempt

to deallo cate an array that has not previously b een allo cated space or one which do es not have the

ALLOCATE attribute Again one should only supply one array per DEALLOCATE statement and the

optional STAT eld should always b e used ierr holds a value that rep orts on the success failure

of the DEALLOCATE request in an analogous way to the ALLOCATE statement

Septemb er University of Liverp o ol

Deallo cating Arrays

Memory leakage will o ccur if a pro cedure containing an allo catable array which do es not p ossess the

SAVE attribute is exited without the array b eing DEALLOCATEd this constraint will be relaxed in

Fortran The storage asso ciated with this array b ecomes inaccessible for the whole of the life of

the program

Consider the following sorting program which can handle any numb er of items

PROGRAM sortanynumber

Read numbers into an array sort into ascending order

and display the sorted list

INTEGER DIMENSION ALLOCATABLE nums

INTEGER temp I K ntosort ierr

PRINT How many numbers to sort

READ ntosort

ALLOCATE numsntosort STATierr

IF ierr NE THEN

PRINT nums Allocation request denied

STOP halts execution

END IF

PRINT Type in ntosort values one line at a time

DO Intosort

READ numsI

END DO

DO I ntosort

DO K I ntosort

IFnumsI numsK THEN

temp numsK Store in temporary location

numsK numsI Swap the contents over

numsI temp

END IF

END DO

END DO

DO I ntosort

PRINT Rank I value is numsI

END DO

IF ALLOCATEDnums DEALLOCATEnums STATierr

IF ierr NE THEN

PRINT nums Deallocation request denied

END IF

END PROGRAM sortanynumber

Fortran Course Notes File CourseNotesps

Arrays

Masked Assignment Where Statement

The WHERE statement is used when an array assignment is to b e p erformed on a nonregular section of

the LHS array elements in other words the whole array assignment is masked so that it only applies

to sp ecied elements Masked array assignment is achieved using the WHERE statement

WHERE I NE A BI

the eect of this statement is to p erform the assignment Ajk BjkIjk for all values of

j and k where the mask Ijk NE isTRUE In the cases where the mask is FALSE no

action is taken

For example if

B

and

I

then

A

Only the indicated elements corresp onding to the nonzero elements of I have b een assigned to

Conformable array sections may b e used in place of the whole arrays for example

WHERE Ijkjk NE Ajkjk BjkjkIjkjk

is p erfectly valid

Question WHERE Statement

Write a WHERE statement that will take a D INTEGER array and negate all o ddvalued p ositive

numb ers

Masked Assignment Where Construct

Masked assignment may alsobeperformed byaWHERE construct

WHEREA

B LOGA

C SQRTA

ELSEWHERE

B C is NOT changed

ENDWHERE

Septemb er University of Liverp o ol

Masked Assignment Where Construct

the eect of this co de blo ck is to p erform the assignments Bjk LOGAjk and Cjk

SQRTAjk wherever Ajk is TRUE For the cases where the mask is FALSE the

assignments in the ELSEWHERE blo ck are made instead Note that the WHERE END WHERE is not a

control construct and cannot currently b e nested This constraint will b e relaxed in Fortran

In all the ab ove examples the mask the logical expression must conform to the implied shap e of

each assignment in the b o dy in other words in the ab ove example all arrays must all conform

The execution sequence is as follows evaluate the mask execute the WHERE blo ck in full then execute

the ELSEWHERE blo ck The separate assignment statements are executed sequentially but the individual

elemental assignments within each statement are conceptually executed in parallel It is not p ossible

to have a scalar on the LHS in a WHERE and all statements must b e array assignments

Consider the following example from the Fortran standard pp

The co de is a D Monte Carlo simulation of state transition Each gridp oint is a logical variable

whose value can b e interpreted as spinup or spindown The transition b etween states is governed by

a lo cal probabilistic pro cess where all p oints change state at the same time Each spin either ips to

the opp osite state or not dep ending on the state of its six nearest neighb ours Gridp oints on the edge

of the cub e are dened by cubic p erio dicity in other words the grid is taken to b e replicated in all

dimensions in space

MODULE Funkt

CONTAINS

FUNCTION RAND m

INTEGER m

REAL DIMENSIONmmm RAND

CALL RANDOMNUMBERHARVEST RAND

RETURN

END FUNCTION RAND

END MODULE Funkt

PROGRAM TRANSITION

USE Funkt

IMPLICIT NONE

INTEGER PARAMETER n

INTEGER iterations i

LOGICAL DIMENSIONnnn ising flips

INTEGER DIMENSIONnnn ones count

REAL DIMENSIONnnn threshold

REAL DIMENSION p

p

iterations

ising RANDn LE

DO i iterations

ones

WHERE ising ones

count CSHIFTones CSHIFTones

CSHIFTones CSHIFTones

CSHIFTones CSHIFTones

WHERE NOTising count count

threshold

Fortran Course Notes File CourseNotesps

Arrays

WHERE count threshold p

WHERE count threshold p

WHERE count threshold p

flips RANDn LE threshold

WHERE flips ising NOT ising

ENDDO

END PROGRAM TRANSITION

Note CSHIFT p erforms a circular shift on an arrayfor example if

A

then

CSHIFTA

is A shifted one place to the left with the leftmost numb er wrapping around to the right

A

and is A shifted one place to the right

CSHIFTA

is

A

It is also p ossible to sp ecify a dimension forDandupward arrays If

A

B

then

CSHIFTB

shifts the array one p osition in dimension downwards

A

B

and

Septemb er University of Liverp o ol

Vectorvalued Subscripts

CSHIFTB

A

B

and so on

Question Array Masked Array Assignment

Using an array constructor and the WHERE statement implement the following algorithm for nding

prime numb ers

dene a vector Primeofsize n

initialise Prime such that Primei i for i n

set i

forall jij inif Primej is exactly divisible by i then set Primej hint

use the MOD remainder intrinsic in conjunction with a WHERE statement

increment i

if i equals n then exit

if Primei is zero then goto step

goto step

Print out all nonzero entries of the vector the prime numb ers

Hint the WHERE statement is an array assignment statement and not a control construct therefore it

cannot contain a PRINT statement The PACK intrinsic can accept an arrayargument and a conformable

MASK and will return a D vector of all the elements of the array where the corresp onding mask elements

are TRUE

Print PACKArrayMask

Vectorvalued Subscripts

Index indirection can b e intro duced by using vectorvalued subscripts A one dimensional vector can

b e used to subscript an array in a dimension The result of this is that an array section can b e sp ecied

where the order of the elements do not follow a linear pattern Consider

INTEGER DIMENSION V

INTEGER DIMENSION W

Fortran Course Notes File CourseNotesps

Arrays

then AV is shorthand for the irregular section that contains A A A Aand A in

that order

V

14 81012

Figure Subscripting Using a Vector

The following statement is a valid assignment to a element section

AV

Likewise if A contains the elements then

C AW

would set the subsection C to

Vectorvalued subscripts can b e used on either side of the assignment op erator however in order to

preserve the integrityofparallel array op erations it would b e invalid to assign values to AW b ecause

A would b e assigned to twice It must b e ensured that subscripts on the LHS of the assignment

op eratorare unique

It is only p ossible to use one dimensional arrays as vector subscripts if a D section is to b e dened

then two D vectors must b e used for example

A SUMCVW

Note vector subscripting is very inecient and should not b e used unless absolutely necessary

Question Vector Subscripts MAXLOC

Generate an arbitrary D array vector lled with random numb ers b etween and By using the

MAXLOC intrinsic with a suitable mask set up an integer array VSubs which contains a p ermuted index

set of vector such that VectorVSubsi VectorVSubsi for all valid i

You may nd it useful to use the MAXLOC intrinsic For example

MAXLOCVSubs

Septemb er University of Liverp o ol

returns an array containing the index of the largest element of the array VSubs and

MAXLOCVSubsMASKVSubsLTVSubsi

returns the p osition of the largest element that is less than the value of VSubsi In both cases

the result is a one element D array The array contains one element because VSub only has one

dimension

Selected Intrinsic Functions

Random Numb er Intrinsic

RANDOM NUMBERHARVEST is a useful intrinsic esp ecially when developing and testing co de It is an

elemental SUBROUTINE so when invoked with a REAL valued argument which has INTENTOUT it

will return in its argument a pseudorandom numb er or conformable array of pseudorandom numb ers

in the range x

For example

REAL HARVEST

REAL DIMENSION HARVEYS

CALL RANDOMNUMBERHARVEST

CALL RANDOMNUMBERHARVEYS

will assign a random numb er to the scalarvariable HARVEST andanarray of dierent random numb ers

to HARVEYS This subroutine is very useful for numeric applications where large arrays need to be

generated in order to test or time co des

The random numb er generator can b e seeded by user sp ecied values The seed is an integer arrayofa

compiler dep endent size Using the same seed on separate invo cations will generate the same sequence

of random numb ers

RANDOM SEEDSIZE int nds the size of the seed

SEEDPUT array seeds the random numb er generator RANDOM

For example

CALL RANDOMSEEDSIZEisze

CALL RANDOMSEEDPUTIArrisze

CALL RANDOMNUMBERHARVEST

PRINT Type in a scalar seed for the generator

READ iseed

CALL RANDOMSEEDPUTiseed i isze

CALL RANDOMNUMBERHARVEST

ALLOCATEISeedArrayisze

PRINT Type in a isze element array as a seed for the generator

READ ISeedArray

Fortran Course Notes File CourseNotesps

Selected Intrinsic Functions

CALL RANDOMSEEDPUTISeedArray

CALL RANDOMNUMBERHARVEST

DEALLOCATEISeedArray

Using the same seed on separate executions will generate the same sequence of random numb ers

There are other optional arguments which can b e used to rep ort on which seed is in use and rep ort on

how big an array is needed to hold a seed This pro cedure may also b e called with no arguments in

order to initialise the random numb er generator

Question Random Numb er Generation

NUMBER write a program to simulate the throwofadie Using the intrinsic subroutine RANDOM

Vector and Matrix Multiply Intrinsics

There are twotyp es of intrinsic matrix multiplication these should always b e used when appropriate as

they will b e the most ecient metho d of calculation

PRODUCTVEC VEC DOT

This is the inner dot pro duct of two rank arrays Clearly VEC VEC must conform in size

and must b e one dimensional Care must b e taken not to confuse this intrinsic with DPROD the

DOUBLE PRECISION pro duct function or PRODUCT the intramatrix pro duct see Section

An example of use is

DP DOTPRODUCTAB

which is equivalent to

DP AB AB

or

DP SUMAB

The result is also dened for COMPLEX and LOGICAL arrayarguments For COMPLEX the result is

DP SUMCONJGAB

and for LOGICAL

DP LAANDLB OR LAANDLB OR

MATMULMAT MAT

This is the traditional matrixmatrix multiplication and is not equivalent to MATMAT There

are certain restrictions placed on the function arguments which saythatthearrays must match

in sp ecic dimensions they do not have to b e conformable

Septemb er University of Liverp o ol

Vector and Matrix Multiply Intrinsics

if MAT has shap e n m and MAT shap e m k then the result has shap e n k

if MAT has shap e m and MAT shap e m k then the result has shap e k

if MAT has shap e n m and MAT shap e m then the result has shap e n

Element ij of the result is

SUMMATiMATj

The result is also dened for LOGICAL arguments

ANYMATiANDMATj

If A and B are set up as follows

A

and

B C

B C

B

A

then the following program

PROGRAM DEMO

INTEGER A

INTEGER B

A

A

B

B

PRINT DOTPRODUCTAA DOTPRODUCTAA

PRINT MATMULAB MATMULAB

END PROGRAM DEMO

gives

DOTPRODUCTAA

MATMULAB

Question MATMUL Intrinsic

For the declarations

REAL DIMENSION A B C

what is the dierence b etween CMATMULAB and CAB

Fortran Course Notes File CourseNotesps

Selected Intrinsic Functions

Maximum and Minimum Intrinsics

There are two intrinsics in this class

MAXSOURCESOURCESOURCE returns the maximum values over all source ob

jects

MINSOURCESOURCESOURCE returns the minimum values over all source ob

jects

For example

MAX is

MIN is

The list of source objects are searched from left to right as indicated in the diagram b elow If two

values are equal then it is the rst that is selected as also indicated in the diagram b elow

MAX(X)

7-289 410 27 10 21

Figure Visualisation of the MAX Intrinsic

The MAX and MIN intrinsics may also accept arrayarguments The result is the same shap e and size

as each argument for example

MIN is

MAX is

Question MAX and MIN

What is the value of

MAX

MIN

Septemb er University of Liverp o ol

Array Lo cation Intrinsics

Array Lo cation Intrinsics

There are two intrinsics in this class

MAXLOCSOURCEMASK

Returns a one dimensional array containing the lo cation of the rst maximal value in an array

under an optional mask If the MASK is present the only elements considered are where the mask

is TRUE Note that the result is always array valued

The source array is searched from left to right and the p osition of the rst o ccurrence of the maximum value is returned

MAXLOC(X) = (/6/)

7-289 410 27 10 21

Figure Visualisation of MAXLOC When Applied to a D Array

Consider this further D example if

A

Array

then

MAXLOCArray is corresp onding to the lo cation of value

MAXLOCArrayArrayLE is

Only the following elements are considered

A

Array

the maximal value is at the lo cation indicated

MAXLOCMAXLOCArrayArrayLE

MAXLOCArrayArrayLE gives so the overall result is array valued

corresp onding to the lo cation that holds the largest element of the array

MINLOCSOURCEMASK

Returns a one dimensional array containing the lo cation of the rst minimal value in an array

under an optional mask

MINLOCArray is

The minimal value is element A

MINLOCArrayArrayGE is gives

MINLOCMINLOCArrayArrayGE

This is eectively MINLOC so the result is array valued corresp onding

to the second element of the array

Fortran Course Notes File CourseNotesps

Selected Intrinsic Functions

Question MAXLOC

What is the value of

MAXLOC

MAXVAL

MINLOC

MINVAL

If

A

A

what is

MAXLOCA MASK A LT

MAXVALA MASK A LT

MAXLOCA MASK A LT

MAXVALA MASK A LT

Array Reduction Intrinsics

Reduction functions are aptly named b ecause an array is op erated up on and a result obtained which

has a smaller rank than the original source array For a rank n arrayifDIM is absent or n then

the result is scalar otherwise the result is of rank n

SUMSOURCEDIMMASK

SUM returns the sum of array elements along an optionally sp ecied dimension under an

optionally sp ecied mask

if DIM is absent the whole array is considered and the result is a scalar

Septemb er University of Liverp o ol

Array Reduction Intrinsics

SUM(W) = 58

7-289 410 27 10 21 +++ + + + ++++

= 58

Figure SUM of a D Array

If DIM is not sp ecied fortheSUM of a D array then the result is obtained by adding all the elements together

SUM(X) = 105

7-289 410 27 10 21 + = 105 107 7 1 10-2-2729 -2

+ ++++ + ++++

Figure SUM of a D Array

if DIM is sp ecied the result is an arrayofrankn of sums for example summing down the columns

SUM(X,DIM=1) = (/17,16,5,5,8,8,0,14,12,11,-1/)

7-289 410 27 10 21 + 107 7 1 10-2-2729 -2

Dimension 1 1716 5 5 8 8 0 14 12 11 -1

Figure Summing along Dimension of a D Array

or along the rows

Fortran Course Notes File CourseNotesps

Selected Intrinsic Functions

SUM(X,DIM=2) = (/58,47/)

7-289 410 27 10 21 58 107 7 1 10-2-2729 -2 47 + ++++ + ++++

Dimension 2

Figure Summing along Dimension of a D Array

if MASK is present then the sum only involves elements of SOURCE which corresp ond to

TRUE elements of MASKfor example only the elements larger than are considered

SUM(W,MASK=W>6) = 51

7-289 410 27 10 21 ++++ +

= 51

Figure SUM Under the Control of a Mask

if the array is zero sized then the sum is

PRODUCTSOURCEDIMMASK

PRODUCT returns the pro duct of all array elements along an optionally sp ecied dimension

under an optionally sp ecied mask

if DIM is absent the whole array is considered and the result is a scalar

if DIM is sp ecied the result is an arrayofrankn of pro ducts for example if

A

PRINT PRODUCTADIM

PRINT PRODUCTADIM

gives

if MASK is present then the pro duct only involves elements of SOURCE which corresp ond to

TRUE elements of MASKfor example

Septemb er University of Liverp o ol

Array Reduction Intrinsics

PRINT PRODUCTAMASKALT

gives

if the array is zero sized then the pro duct is

ALLMASKDIM

ALL returns TRUE if all values of the mask are TRUE along an optionally sp ecied

dimension DIM If DIM is sp ecied then the result is an array of rank n otherwise a

scalar is returned

For example consider a D arrayif DIM then the function returns a D vectorwiththe

result b eing as if the ALL function has b een applied to each column in turn If DIM the

result is as if the ALL function had b een applied to each row in turn

If A is as b efore and

B

then the following

PRINT ALLANEBDIM

gives

T F F

recall that dimension runs up and down the page

Similarly

PRINT ALLANEBDIM

gives

F F

where dimension run across the page

if DIM is absent then the whole array is considered for example

PRINT ALLANEB

gives the scalar value

F

if the array is zero sized then ALL returns TRUE

ANYMASKDIM

ANY returns TRUE if any values of the mask are TRUE along an optionally sp ecied

dimension DIM If DIM is given then the result is an arrayofrankn for example

PRINT ANYANEBDIM

PRINT ANYANEBDIM

gives

T F T

T T

Fortran Course Notes File CourseNotesps

Selected Intrinsic Functions

if DIM is absent then the whole array is considered for example

PRINT ANYANEB

gives the scalar value

T

if the array is zero sized then ANY returns FALSE

COUNTMASKDIM

COUNT returns the numb er of TRUE elements in a sp ecied LOGICAL array along dimension

DIM The result is an arrayofrankn for example

PRINT COUNTANEBDIM

PRINT COUNTANEBDIM

gives

if DIM is absent then the whole array is considered for example

PRINT COUNTANEB

gives the scalar

if the array is zero sized then COUNT returns zero

MAXVALSOURCEDIMMASK

MAXVAL returns the maximum values in an array along an optionally sp ecied dimension

under an optionally sp ecied mask

if DIM is sp ecied the result is an arrayofrankn of maximum values in other dimensions

for example

PRINT MAXVALADIM

PRINT MAXVALADIM

gives

if DIM is absent the whole array is considered and the result is a scalar

if MASK is present then the survey is only p erformed on elements of SOURCE which corresp ond

to TRUE elements of MASKfor example

PRINT MAXVALAMASKALT

only considers elements of A that are less than and gives

the largest negative numb er of the appropriate kind is returned if the array is zero sized

MINVALSOURCEDIMMASK

Septemb er University of Liverp o ol

Array Reduction Intrinsics

MINVAL returns the minimum value in an array along an optionally sp ecied dimension under

an optionally sp ecied mask

if DIM is sp ecied the result is an arrayofrankn of minimum values in other dimensions

for example

PRINT MINVALADIM

PRINT MINVALADIM

gives

if DIM is absent the whole array is considered and the result is a scalar

if MASK is present then the survey is only p erformed on elements of SOURCE which corresp ond

to TRUE elements of MASKfor example

PRINT MINVALAMASKAGT

gives

the smallest p ositive numb er of the appropriate kind is returned if the array is zero sized

Question Summation Example

Which ve consecutive numb ers have the greatest sum

Question Op erations on arrays and array intrinsics

Declare constant arrays A and X where

A

C B

C B

C B

X

C B

A

Using the relevant intrinsics set M and N to b e the extents of A

Print the array A out rowbyrow

Write a Fortran program which use intrinsics to print out the following

Fortran Course Notes File CourseNotesps

Selected Intrinsic Functions

a The sum of the pro duct of the columns of A use intrinsics

b The pro duct of the sum of the row elements of A use intrinsics

c The sum of squares of the elements of X

d The mean of the elements of X

e The sum of the p ositive elements of X

f The innitynorm of X ie the largest of jx ji n

i

g The one norm of A ie the largest column sum of ja j

ij

Question Salaries Example

The salaries received by employees of a company are

and the p osition in the hierarchy of each employee is indicated bya corresp onding category thus

Write a program to nd the total cost to the company of increasing the salary of p eople in categories

and by and resp ectively

Septemb er University of Liverp o ol

Mo dule

Pro cedures

Program Units

Fortran has two main program units

main PROGRAM

The place where execution b egins and where control should eventually return b efore the program

terminates The main program may contain any numb er of pro cedures

MODULE

Aprogram unit which can also contain pro cedures and declarations It is intended to b e attached

to any other program unit where the entities dened within it b ecome accessible A mo dule is

similar to a C class

MODULE program units are new to Fortran and are supp osed to replace the unsafe Fortran

features such as COMMON INCLUDE BLOCK DATA as well as adding a much needed limited object

oriented asp ect to the language Their imp ortance cannot b e overstressed and they should b e

used whenever p ossible

There are two classes of pro cedure

SUBROUTINE

A parameterised named sequence of co de which performs a sp ecic task and can be invoked

from within other program units bytheuseofa CALL statement for example

CALL PrintReportSummaryCurrentFigures

Here control will pass into the SUBROUTINE named PrintReportSummary after the SUBROUTINE

has terminated control will pass back to the line following the CALL

FUNCTION

As a SUBROUTINE but returns a result in the function name of any sp ecied typ e and kind

This can b e compared to a mathematical function say f x An example of a FUNCTION call

could b e

PRINT The result is fx

Here the value of the function f with the argument x is substituted at the appropriate p oint

in the output

Pro cedures are generally contained within a main program or a mo dule It is also p ossible to have

stand alone or EXTERNAL pro cedures these will b e discussed later see Section

Program Units

Main Program Syntax

This is the only compulsory program unit every program must have one

PROGRAM main program name

declaration of lo cal objects

executable stmts

CONTAINS

internal pro cedure denitions

END PROGRAM main program name

The PROGRAM statement and main program name are optional however it is go o d p olicy to always

use them main program name can b e any valid Fortran name

The main program contains declarations and executable statements and may also contain internal

pro cedures These internal pro cedures are separated from the surrounding program unit the host in

this case the main program byaCONTAINS statement Internal pro cedures may only b e called from

within the surrounding program unit and automatically have access to all the host program units

declarations but may also override them Please note that some implementation of HPF may not yet

supp ort internal pro cedures

PROGRAM Main ! ... CONTAINS ! Internal Procs SUBROUTINE Sub1(..) ! Executable stmts END SUBROUTINE Sub1 ! etc. FUNCTION Funkyn(...) ! Executable stmts END FUNCTION Funkyn

END PROGRAM Main

Figure Schematic Diagram of a Main Program

Internal pro cedures may not contain further internal pro cedures in other words the nesting level is a

maximum of The diagram shows two internal pro cedures Sub and Funkyn however there may

b e any numb er of internal pro cedures subroutines or functions which are wholly contained within the

main program

The main program may also contain calls to external pro cedures This will be discussed later see

Section

Septemb er University of Liverp o ol

Pro cedures

The main program must contain an END statement as its last nonblank line For neatness sake this

should really b e suxed by PROGRAM so it reads END PROGRAM and should also have the name of the

program attached to o Using as descriptive as p ossible END statements helps to reduce confusion

Main Program Example

The following example demonstrates a main program which calls an intrinsic function FLOOR and

an internal pro cedure Negative

PROGRAM Main

IMPLICIT NONE

REAL x

INTRINSIC FLOOR

READ x

PRINT FLOORx

PRINT Negativex

CONTAINS

REAL FUNCTION Negativea

REAL INTENTIN a

Negative a

END FUNCTION Negative

END PROGRAM Main

Although not totally necessary the intrinsic pro cedure is declared in an INTRINSIC statement the

typ e is not needed the compiler knows the typ es of all intrinsic functions

The internal pro cedure is contained within the main program so do es not require declaring in the

main program

The compiler is able to see the pro cedure and therefore knows its result typ e numb er and typ e of

arguments

Pro cedures

Apro cedure such as an intrinsic function is an abstracted blo ck of parameterised co de that p erforms

aparticular task Pro cedures should generally b e used if a task has to b e p erformed twoormore times

this will cut down on co de duplication

Before writing a pro cedure the rst question should b e Do we really need to write this or do es a

routine already exist Very often a routine with the functionality already exists for example as an

intrinsic pro cedure or in a library somewhere Fortran has intrinsic pro cedures covering a

variety of functionalityandtheNAg fl Numerical Library contains over mathematic pro cedures

so there is generally a wide choice

The NAg library deals with solving numerical problems and is ideal for engineers and scientists fl

the NAg Fortran Mk I library has just b een released as a successor to the well resp ected and p opular

Fortran library which contains at least routines

Other libraries include BLAS Basic Linear Algebra Subroutines for doing vector matrixvector and

matrixmatrix calculations these should always b e used if p ossible IMSL Visual Numerics akin to

NAg Library LaPACK linear algebra package Uniras graphics routines very comprehensive Many

of these packages will b e optimised and shipp ed along with the compiler

Fortran Course Notes File CourseNotesps

Program Units

Note that the HPFF dened a set of routines that should b e available as part of an HPF compilation

system If the target platform is to be a parallel computer it will be worth investigating further a

numb er of Fortran version of these pro cedures exist for example at LPAC

httpwwwlpacacukSELHPCMaterialsHPFlibraryHPFlibrary

As the use of Fortran grows many useful p ortable library mo dules will b e develop ed which contain

routines that can b e USEdby any Fortran program See World Wide Web Fortran Market

httpwwwfortrancomfortranmarkethtml

There is also an auxiliary Fortran standard known as the Varying String mo dule This is to b e

added to the Fortran standard and will allow users to dene and use objects of typ e VARYING STRING

where CHARACTER objects would normally b e used The Standard has already b een realised in a mo dule

byLawrie Schonfelder at Liverp o ol University All the intrinsic op erations and functions forcharacter

STRING objects can b e used in more or less the same variables have b e overloaded so that VARYING

way as other intrinsic typ es which contain routines that can b e USEdbyanyFortran program See

World Wide Web Fortran Market

httpwwwfortrancomfortranmarkethtml

Ifapro cedure is to b e written from scratch then the following guidelines should b e followed

It is generally accepted that pro cedures should b e no more than lines long in order to keep

the control structure simple and to keep the numb er of program paths to a minimum

Pro cedures should be as exible as p ossible to allow for software reuse Try to pass as many

of the variable entities referenced in a pro cedure as actual arguments and do not rely on global

storage or host asso ciation unless absolutely necessary

Try to give pro cedures meaningful names and initial descriptive comments

There is absolutely no p oint in reinventing the wheel if a pro cedure or collection of pro cedures

already exist as intrinsic functions or in a library mo dule then they should b e used

Subroutines

Consider the following example

PROGRAM Thingy

IMPLICIT NONE

CALL OutputFiguresNumbers

CONTAINS

Septemb er University of Liverp o ol

Functions

SUBROUTINE OutputFiguresNumbers

REAL DIMENSION INTENTIN Numbers

PRINT Here are the figures Numbers

END SUBROUTINE OutputFigures

END PROGRAM Thingy

The subroutine here simply prints out its argument Internal pro cedures can see all variables declared

in the main program and the IMPLICIT NONE statement If an internal pro cedure declares a variable

which has the same name as a variable from the main program then this sup ersedes the variable from

the outer scop e for the length of the pro cedure

Using a pro cedure here allows the output format to be changed easily To alter the format of all

outputs it is only necessary to change on line within the pro cedure

Internal subroutines lie b etween CONTAINS and END PROGRAM statements and have the following syntax

SUBROUTINE pro cname dummy args

declaration of dummy args

declaration of lo cal objects

executable stmts

END SUBROUTINE pro cname

Recall that not all HPF compilers implement Internal subroutines

A SUBROUTINE may include calls to other pro cedures either from the same main program from an

attached mo dule or from an external le Note how in the same way as a main program a SUBROUTINE

must terminate with an END statement It is go o d practice to app end SUBROUTINE and the name of

the routine to this line as well

Fortran also allows recursive pro cedures pro cedure that call themselves In order to promote

optimisation a recursive pro cedure must b e sp ecied as such it must have the RECURSIVE keyword

at the b eginning of the subroutine declaration see Section

Question Simple example of Subroutine

Write a main program and internal subroutine that returns as its rst argument the sum of two

real numb ers

Functions

Consider the following example

PROGRAM Thingy

IMPLICIT NONE

PRINT Fab

CONTAINS

REAL FUNCTION Fxy

REAL INTENTIN xy

Fortran Course Notes File CourseNotesps

Program Units

F SQRTxx yy

END FUNCTION F

END PROGRAM Thingy

Functions op erate on the same principle as SUBROUTINEs the only dierence b eing that a function

returns a value In the example the line

PRINT Fab

p

 

will substitute the value returned by the function for Fab in other words the value of a b

Just likesubroutines functions also lie b etween CONTAINS and END PROGRAM statements They have

the following syntax

prex FUNCTION pro cname dummyargs

declaration of dummy args

declaration of lo cal objects

executable stmts assignment of result

END FUNCTION pro cname

It is also p ossible to declare the function typ e in the declaration area instead of in the header

FUNCTION pro cname dummy args

declaration of dummy args

declaration of result typ e

declaration of lo cal objects

executable stmts assignment of result

END FUNCTION pro cname

This would mean that the ab ove function could b e equivalently declared as

FUNCTION Fxy

REAL F

REAL INTENTIN xy

F SQRTxx yy

END FUNCTION F

Recall that not all HPF compilers implement internal functions

Functions may also b e recursive see Section and may b e either scalarorarray valued including

user dened typ es and p ointers Note that owing to the p ossibilityof confusion b etween an array

reference and a function reference the parentheses are not optional

Question Simple example of a Function

Write a main program and an internal function that returns the sum of two real numb ers supplied

as arguments

Septemb er University of Liverp o ol

Argument Asso ciation

Question Random Numb er Generation

Write a function which simulates a throw of two dice and returns the total score Use the in

NUMBER to obtain pseudorandom numb ers to simulate the throw of the trinsic subroutine RANDOM

dice

Argument Asso ciation

Recall in the SUBROUTINE example we had an invo cation

CALL OutputFiguresNumberSet

and a declaration

SUBROUTINE OutputFiguresNumbers

An argument in a call statement in an invo cation for example NumberSet is called an actual

argument since it is the true name of the variable An argument in a pro cedure declaration is called

a dummy argument for example Numbers as it is a substitute for the true name A reference to a

dummy argument is really a reference to its corresp onding actual argument for example changing the

value of a dummy argument actually changes the value of the actual argument Dummys and actuals

are said to b e argument asso ciated Pro cedures may have any numb er of such arguments but actuals

and dummys must corresp ond in numb er typ e kind and rank Fortran programs which outed

this requirement were not standard conforming but there was no wayfor the compiler to check

For the ab ove call Numbers is the dummy argument and NumberSet is the actual argument

Consider

PRINT Fab

and

REAL FUNCTION Fxy

here the actual arguments a and b are asso ciated with the dummy arguments x and y

If the value of a dummy argument changes then so do es the value of the actual argument

Lo cal Objects

In the following pro cedure

SUBROUTINE Madrasij

INTEGER INTENTIN i j

REAL a

REAL DIMENSIONij x

Fortran Course Notes File CourseNotesps

Program Units

aandx are known as lo cal objects and x will probably have a dierent size and shap e on each call

They

are created each time a pro cedure is invoked

are destroyed when the pro cedure completes

do not retain their values b etween calls

do not exist in the programs memory b etween calls

So when a pro cedure is called any lo cal objects are b ought into existence for the duration of the call

Thus if an object is assigned to on one call the next time the program unit is invoked a totally dierent

instance of that object is created with no knowledge of what happ ened during the last pro cedure call

meaning that all values are lost

The space usually comes from the programs stack

Argument Intent

In order to facilitate ecient compilation and optimisation hints in the form of attributes can b e given

to the compiler as to whether a given dummy argument will

hold a value on pro cedure entry which remains unchanged on exit INTENTIN

not b e used until it is assigned a value within the pro cedure INTENTOUT

hold a value on pro cedure entry which may be mo died and then passed back to the calling

program INTENTINOUT

For example

SUBROUTINE exampleargargarg

REAL INTENTIN arg

INTEGER INTENTOUT arg

CHARACTER INTENTINOUT arg

REAL r

r argICHARarg

arg ANINTr

arg CHARMODarg

END SUBROUTINE example

It can b e seen here that

arg is unchanged within the pro cedure

the value of arg is not used until it has b een assigned to

arg is used and then reassigned a value

The use of INTENT attributes is not essential but it allows go o d compilers to check for co ding errors

thereby enhancing safety If an INTENTIN object is assigned a value orifanINTENTOUT object is

not assigned a value then errors will b e generated at compile time

Septemb er University of Liverp o ol

Scop e

Question Erroneous Co de

What is wrong with the following internal pro cedure

SUBROUTINE MistakenABC

IMPLICIT NONE

REAL INTENTIN A

REAL INTENTOUT C

A C

END SUBROUTINE Mistaken

Scop e

The scop e of an entity is the range of a program within which an entity is visible and accessible Most

entities have a scop e which is limited to the program unit in which they are declared but in sp ecial

circumstances some entities can have a scop e that is wider than this The b est waytoprovide global

data is by implementing a MODULE which contains the required global data declarations and then USEing

it wherever required Using COMMON to achieve this is strongly discouraged as this metho d of global

data declaration is considered to b e unsafe obtuse and outmo ded

Host Asso ciation

In Fortran dierent routines were entirely separate from each other they did not have access

to each others variable space and could only communicate through argument lists orby global storage

COMMON such pro cedures are known as external

Pro cedures in Fortran may contain internal pro cedures which are only visible within the program

unit in which they are declared in other words they have a lo cal scop e Consider the following example

PROGRAM CalculatePay

IMPLICIT NONE

REAL Pay Tax Delta

INTEGER NumberCalcsDone

Pay Tax Delta

CALL PrintPayPayTax

Tax NewTaxTaxDelta

CONTAINS

SUBROUTINE PrintPayPayTax

REAL INTENTIN Pay Tax

REAL TaxPaid

TaxPaid Pay Tax

PRINT TaxPaid

NumberCalcsDone NumberCalcsDone

END SUBROUTINE PrintPay

REAL FUNCTION NewTaxTaxDelta

REAL INTENTIN Tax Delta

NewTax Tax DeltaTax

NumberCalcsDone NumberCalcsDone

END FUNCTION NewTax

Fortran Course Notes File CourseNotesps

Program Units

END PROGRAM CalculatePay

PrintPay is an internal subroutine of CalculatePay and has access to NumberCalcsDone It can b e

thought of as a It is said to b e available to the pro cedures by host asso ciation The

variables Pay and Tax on the other hand are passed as arguments to the pro cedures This means

that they are available byargument asso ciation

The decision of whether to give visibility to an object by host asso ciation orbyargument asso ciation is

tricky there are no hard and fast rules If for example Pay Tax and Delta had not b een passed to

the pro cedures as arguments but had b een made visible by host asso ciation instead then there would b e

no discernible dierence in the results that the program pro duces Likewise NumberCalcsDone could

have b een communicated to b oth pro cedures byargument asso ciation instead of by host asso ciation

In a sense the metho d that is used will dep end on p ersonal taste or a sp ecic inhouse co dingstyle

Here Pay Tax and Delta are not used in every single pro cedure in the same wayasNumberCalcsDone

which acts in a more global way

NewTax cannot access any of the lo cal declarations of PrintPay for example TaxPaid and vice

versa NewTax and PrintPay can be thought of a resting at the same scoping level whereas the

containing program CalculatePay is at an outer higher scoping level see Figure

PrintPay can invoke other internal pro cedures which are contained by the same outer program unit

but cannot call itself as it is not recursive see Section for discussion ab out recursion

Up on return from PrintPay the value of NumberCalcsDone will have increased byoneowing to the

last line of the pro cedure

Question Standard Deviation

Write a program which contains an internal function that returns the standard deviation from the

mean of an array of real values Note that if the mean of a sequence of values x i n is denoted

i

by m then the standard deviation s is dened as

r

P

n



x m

i

i

s

n

Hint In Fortran SUMX is the sum of the elements of X

To demonstrate correctness print out the standard deviation of the following numb ers of em

and also for the following

Example of Scoping Issues

Consider the following example

Septemb er University of Liverp o ol

Scop e

PROGRAM Proggie Proggie

IMPLICIT NONE

REAL A B C scope Proggie

CALL subA scope Proggie

CONTAINS

SUBROUTINE SubD scope Sub

REAL D D is dummy alias for A

REAL C local C from Proggies C

C A A cannot be changed

D D C D can be changed

B C B from Proggie gets new value

END SUBROUTINE Sub

SUBROUTINE AnuvvaSub scope AnuvvaSub

REAL C another local C unrelated

END SUBROUTINE AnuvvaSub

END PROGRAM Proggie

This demonstrates most of the issues concerning the scop e of names in pro cedures

If an internal pro cedure declares an object with the same name as one in the host containing program

unit then this new variable sup ersedes the one from the outer scop e for the duration of the pro cedure

for example Sub accesses B from Proggie but sup ersedes C by declaring its own lo cal object called C

This C in Subis totally unrelated to the C of Proggie

Internal pro cedures may have dummy arguments however any object used as an actual argument to

an internal pro cedure cannot b e changed by referring to it by its original name in that pro cedure it

must be assigned to using its dummy name For example Sub accesses A known lo cally as D by

argument asso ciation and is forbidden to assign a value to or mo dify the availability of A it must

be altered through its corresp onding dummy argument see P of Fortran standard The

variable A can still b e referenced in Sub as if it p ossessed the INTENTIN attribute see Section

for the implications of the INTENT attribute

A lo cal variable called A could b e declared in Sub which would clearly b ear no relation to the A which

is argument asso ciated with d When Sub is exited and control is returned to Proggie the value that

C had b efore the call to the subroutine is restored

The C declared in AnuvvaSub bears no relation to the C from Proggie or the C from Sub

Question Lo cal Variables

At each of the indicated p oints in the co de give the status lo cal dummy argument host asso ciated

or undened and if appropriate the values of the variables v v v v r and i

PROGRAM PerOg

IMPLICIT NONE

REAL VV

INTEGER VV

V

V

V

V

Fortran Course Notes File CourseNotesps

Program Units

Position

CALL InteVV

Position

CALL ExteVV

Position

CONTAINS

SUBROUTINE Interi

REAL INTENTINOUT r

INTEGER INTENTINOUT i

INTEGER v

Position

r

i

v

END SUBROUTINE Inte

END PROGRAM PerOg

SAVE Attribute

The SAVE attribute can b e

applied to a sp ecied variable In the following example NumInvocations is initialised only on

the rst call conceptually at program startup and then retains its new value b etween calls

SUBROUTINE Barmyargarg

INTEGER SAVE NumInvocations

NumInvocations NumInvocations

applied to the whole pro cedure by app earing on a line on its own This means that all lo cal

objects are SAVEd

SUBROUTINE poloxy

IMPLICIT NONE

INTEGER mint neckjumper

SAVE

REAL stick car

In the ab ove example mint neck jumper stick and car all have the SAVE attribute

Variables with the SAVE attribute are known as static objects and have static storage class

In fact the SAVE attribute is given implicitly if an object which is not a dummy argument or a

PARAMETER app ears in an initialising declaration in a pro cedure so

Septemb er University of Liverp o ol

Keyword Arguments

INTEGER SAVE NumInvocations

is equivalent to

INTEGER NumInvocations

however the former is clearer

ClearlytheSAVE attribute has no meaning in the main program since when it is exited the program

has nished executing

Objects app earing in COMMON blo cks or DATA statements are automatically static

Question Save Attribute

Write a skeleton pro cedure that records how many times it has b een called

Keyword Arguments

Normal argument corresp ondence is p erformed by p osition the rst actual argument corresp onds to the

rst dummy argument and so on Fortran includes a facilitytoallow actual arguments to b e sp ecied

in any order At the call site actual arguments maybeprexed by keywords the dummy argument name

followed by an which are used when resolving the argument corresp ondence If keywords

are used then the usual p ositional corresp ondence of arguments is replaced bykeyword corresp ondence

for example consider the following interface description

SUBROUTINE axisxylminmaxi

REAL INTENTIN x y l min max

INTEGER INTENTIN i

END SUBROUTINE axis

axis can b e invoked as follows

using p ositional argument invo cation

CALL AXIS

using keyword arguments

CALL AXISMaxMinLI

As so on as one argument is prexed bya keyword then all subsequent arguments going left to right

must also b e prexed

Note if an EXTERNAL pro cedure see is invoked with keyword arguments then the INTERFACE

must b e explicit at the call site

In summarykeyword arguments

allow actual arguments to b e sp ecied in any order

Fortran Course Notes File CourseNotesps

Program Units

help improve the readabilityoftheprogram

when used in conjunction with optional arguments make it easy to add an extra argument

without the need to mo dify each and every invo cation in the calling co de

are the dummy argument names

Question Keyword Arguments

Write a main program and an internal subroutine that returns as its rst argument the sum of

two real numb ers Invoke this using keyword arguments

What are the imp ortant things to rememb er when using keyword arguments

Optional Arguments

Dummy arguments with the optional attribute can b e used to allow default values to b e substituted in

place of absent actual arguments Any argument with the OPTIONAL attribute may b e omitted from an

actual argument list but as so on as one argument has b een dropp ed all subsequent arguments going

left to right must b e keyword arguments to allow the compiler to resolve the argument corresp ondence

Any use of optional arguments requires the interface of the pro cedure to b e explicit the compiler needs

to know the ordering typ e rank and names of the dummy arguments to work out the corresp ondence

The status of an optional argument can b e found using the PRESENT intrinsic function

Many of the intrinsic pro cedures have optional arguments and keywords can b e used for these pro cedures

in exactly the same wayasfor user dened pro cedures

Optional Arguments Example

Consider the following internal subroutine with two optional arguments

SUBROUTINE SEEab

IMPLICIT NONE

REAL INTENTIN OPTIONAL a

INTEGER INTENTIN OPTIONAL b

REAL ay INTEGER bee

ay bee

IFPRESENTa ay a

IFPRESENTb bee b

Both a and b have the OPTIONAL attribute so the subroutine SEE can b e called in the following ways

CALL SEE

CALL SEE CALL SEEba same

CALL SEE CALL SEEa same

CALL SEEb

In the ab ove example of pro cedure calls the rst call uses b oth default values the second and third

use none and the remaining two b oth have one missing argument

Septemb er University of Liverp o ol

Optional Arguments

Within the pro cedure it must b e p ossible to check whether OPTIONAL arguments are missing or not

the PRESENT intrinsic function which delivers a scalar LOGICAL result has b een designed esp ecially

for this purp ose

If an optional argument is missing then it may not b e assigned to for example the following is invalid

IF NOTPRESENT up up TRUE WRONG

Question Erroneous Co de

What is wrong with the following internal pro cedure

SUBROUTINE MistakenABC

REAL INTENTINOUT A

REAL INTENTOUT OPTIONAL B

REAL INTENTIN C

A CB

IF PRESENTB B A

END

Question Draw aCircle

Write an internal subroutine which draws circles The routine takes twoarguments the rst denes

the radius of the circle and the second is optional and denes the colour by which the circle is shaded

The default colour for the circle shading should b e green Assume you have twolibrary subroutines

available one called Circle which takes one REAL argument the radius and draws the circumfer

ence and one called Shade Circle which shades it in and takes one character argument that denes

the colour as a character string eg Rfor red orGfor green

Fortran Course Notes File CourseNotesps

Mo dule

More Pro cedures

Pro cedures and Array Arguments

There are three typ es of dummy arrayargument

explicitshap e all b ounds sp ecied

INTEGER DIMENSION INTENTIN explicitshape

The actual argument that b ecomes asso ciated with an explicitshap e dummy must conform in

size and shap e An explicit INTERFACE is not required in this case This metho d of declaring

dummy arguments is very inexible as only arrays of one xed size can b e passed This form of

declaration is only very o ccasionally appropriate

assumedsize all b ounds passed except the last

INTEGER INTENTIN lda dummy arg

INTEGER DIMENSIONlda assumedsize

The last b ound of an assumedsize array remains unsp ecied it contains a and can adopt

an assumed value An explicit INTERFACE is not required This was the Fortran metho d

of passing arrays but has b een totally sup erseded by the next category

assumedshap e no b ounds sp ecied

INTEGER DIMENSION INTENTIN assumedshape

All b ounds can b e inherited from the actual argument The actual array that corresp onds to the

dummy must match in typ e kind and rank An explicit INTERFACE must be provided This typ e

of argument should always used in preference to assumedsize arrays

Note an actual argument can be an ALLOCATABLE array but a dummy argument cannot be

this means eectively that an ALLOCATABLE array must b e allo cated b efore b eing used as an actual

argument

Explicitshap e Arrays

A dummy argument that is an explicitshap e array must conform in size and shap e to the asso ciated

actual argument no b ound information is passed to the pro cedure Consider the following examples

PROGRAM Main

IMPLICIT NONE

INTEGER DIMENSION A

Assumedshap e Arrays

INTEGER DIMENSION A

INTEGER DIMENSION A

CALL subbyA OK

CALL subbyA non conforming

CALL subbyA OK

CALL subbyRESHAPEA OK

CONTAINS

SUBROUTINE subbyexplicitshape

IMPLICIT NONE

INTEGER DIMENSION explicitshape

END SUBROUTINE subby

END PROGRAM Main

The b ottom line is subby can accept any argument as long as it is an default INTEGER array

This is clearly a very inexible approach which generally should not b e used

Assumedshap e Arrays

Declaring dummy arrays as assumedshap e arrays is the recommended metho d in Fortran Consider

PROGRAM TV

IMPLICIT NONE

REAL DIMENSION X

REAL DIMENSION Y

CALL gimletXY

CALL gimletXY

CALL gimletXY invalid

CONTAINS

SUBROUTINE gimletab

REAL INTENTIN a b

END SUBROUTINE gimlet

END PROGRAM TV

An assumedshap e array declaration must have the same typ e rank and kind as the actual argument

The compiler will insist on this

Note

array sections can b e passed so long as they are regular that is not dened by vector subscripts

The reason for this is concerned with eciency A vector subscripted section will b e nontrivial

to nd in the memoryitislikely to b e widely scattered and would probably need to b e copied on

entry to the pro cedure and then copied back on exit this will create all sorts of runtime p enalties

the actual argument cannot b e an assumedsize array If an actual argument were an assumed

size array then the b ound extent information of the last dimension would not b e known meaning

that the relevant information could not b e passed on to a further pro cedure

Fortran Course Notes File CourseNotesps

Pro cedures and ArrayArguments

The third call is invalid b ecause the second section reference has one dimensions whereas the declaration

of the dummy has two

Automatic Arrays

Other arrays can dep end on dummy arguments these are called automatic arrays and their size is

determined by the values of dummy arguments These arrays have lo cal scop e and a limited lifespan

and as they have their size determined by dummy arguments and are created and destroyed with each

invo cation of the pro cedure cannot have the SAVE attribute or b e initialised Arrays of this class are

traditionally used forworkspace

Consider

PROGRAM Main

IMPLICIT NONE

INTEGER IX IY

CALL unebusriotIX

CALL unebusriotIY

CONTAINS

SUBROUTINE unebusriotAMN

INTEGER INTENTIN M N

INTEGER INTENTINOUT A

REAL AMN automatic

REAL ASIZEASIZEA ditto

REAL AAA automatic

END SUBROUTINE

END PROGRAM Main

The b ound sp eciers of an automatic arraycanoriginate from

scalar dummy arguments which are passed as arguments for example A

comp onents of other dummy arguments for example A

characteristics of other dummy arguments SIZE or LEN intrinsics for example A will b e the

same shap e as A

a combination of the ab ove

There is currently no way to tell whether an automatic array has b een created Typically if there is

insucient memory to allo cate an automatic array the program will ungracefully crash If this is not

desired then the less intuitive allo catable array should b e used

Question Typ es of Arrays

In the following internal subroutine which are the automatic and which are the assumed shap e

arrays

SUBROUTINE ArrayTypesABCD

Septemb er University of Liverp o ol

SAVE Attribute and Arrays

INTEGER INTENTIN D

REAL DIMENSION AC

REAL DIMENSION B

REAL DIMENSIONSIZEA E

INTEGER DIMENSIONDD F

SAVE Attribute and Arrays

Consider

SUBROUTINE subdim

INTEGER INTENTIN dim

REAL ALLOCATABLE DIMENSION SAVE X

REAL DIMENSIONdim Y

IF NOTALLOCATEDX ALLOCATEX

In the same way that a SAVEdvariable p ersists b etween pro cedure calls the array X will remain allo cated

and its value preserved b etween separate invo cations

Dummy arguments or objects which dep end on dummy arguments for example automatic objects

see Section cannot have the SAVE attribute This is b ecause the dummy arguments could be

dierent on each invo cation of the pro cedure As Y dep ends on a dummy argument it cannot b e given

the SAVE attribute

Explicit Length Character Dummy Arguments

This typ e of dummy argument declaration is comparable to an explicitlength array declaration in that

an explicitlength actual CHARACTER arrayargument must match the corresp onding dummy in kind as

wellasinrank If the actual is a scalar default character variable then the length of the dummy must

b e less than or equal to the length of the actual This approach is clearly inexible and other metho ds

should really b e used consider

PROGRAM Main

IMPLICIT NONE

CHARACTERLEN DIMENSION wurd

CALL charexamplewurd

CALL charexamplewurd

CONTAINS

SUBROUTINE charexamplewirdwerds

CHARACTERLEN INTENTINOUT wird

CHARACTERLEN INTENTINOUT werds

END SUBROUTINE charexample

END PROGRAM Main

The example demonstrates that assumedshap e arrays or indeed explicitlength arrays if desired can

still b e used for character dummy arrayarguments

Fortran Course Notes File CourseNotesps

Pro cedures and ArrayArguments

Assumed Length Character Dummy Arguments

This is the recommended metho d of passing strings in Fortran

CHARACTER dummy arguments can inherit the typ eparamvalue LEN sp ecier from the corresp onding

actual argument however the kind parameter and rank must still match This form of argument

declaration is much more exible than using explicitlength strings and is analogous to using assumed

shap e dummies in that the length information is inherited from the actual argument An argument

with this form of inherited size is called an assumedlength character dummy

PROGRAM Main

IMPLICIT NONE

CHARACTERLEN Vera

CHARACTERLEN Hilda

CHARACTERLEN Mavis

CALL charladyVera

CALL charladyHilda

CALL charladyMavis

CONTAINS

SUBROUTINE charladyword

CHARACTERLEN INTENTIN word

PRINT Length of arg is LENword

END SUBROUTINE charlady

END PROGRAM Main

The actual length of a dummy can b e acquired by using the LEN inquiry intrinsic which is comparable

to the SIZE array inquiry intrinsic

Arrayvalued Functions

As well as returning conventional scalar results functions can return p ointers arrays or derived typ es

Forarray valued functions the size of the result can b e determined in a fashion which is similartothe

way that automatic arrays are declared

Consider the following example of an array valued function

PROGRAM proggie

IMPLICIT NONE

INTEGER PARAMETER m

INTEGER DIMENSIONMM im im

IM funnieIM invoke

CONTAINS

FUNCTION funnieimascal

INTEGER INTENTIN ima

INTEGER INTENTIN scal

INTEGER funnieSIZEimaSIZEima

funnie imascal

Septemb er University of Liverp o ol

Charactervalued Functions

END FUNCTION funnie

END PROGRAM proggie

here the b ounds of funnie are inherited from the actual argument and used to determine the size of the

result array a xed sized result could have b een returned bydeclaring the result to b e an explicitshap e

array but this approach is less exible

Question Triangular Numbers Array Valued Function

The numb ers are called triangular numb ers b ecause the numb er of units

th

in each can b e displayed as a triangularpyramid of blobs The i p is computed from p p i

i i i

Write an array valued function which takes one argument N and returns a vector of the rst N

triangular numb ers

Make sure to sp ecify the argument INTENT

Write a test program to demonstrate the function and print out the sequence where N

Question Vector Multiplication Array Valued Function

Write a function Outer that forms the outer pro duct of two vectors If A and B are vectors

then the outer pro duct is a matrix C such that C A B

ij i j

Write a test program which accepts two integers giving the size of the A and B vectors uses the

RANDOM NUMBER function to assign values and then prints the outer pro duct

Charactervalued Functions

It is clearly useful to have a function that returns a CHARACTER string of a given length The length of

the result can either b e xed or can b e inherited from one of the dummy arguments

FUNCTION reverseword

CHARACTERLEN INTENTIN word

CHARACTERLENLENword reverse

INTEGER lw

lw LENword

reverse characters

DO I lw

reverselwIlwI wordII

END DO

END FUNCTION reverse

In this case the length of the function result is determined automatically to b e the same as that assumed

by the dummy argument word Automatic CHARACTER variables could also b e created in this way

Note that word cannot b e used until after its declaration it is for this reason that in this case the

function typ e cannot app earasaprex to the function header

An explicit interface must always b e provided if the function uses a LEN length sp ecication

Fortran Course Notes File CourseNotesps

Pro cedures and ArrayArguments

Side Eect Functions

If in the function invo cation

rezzy funkyabc funkyabc

both funky and funky mo dify the value of a and a is used in the calculation of the result then the

order of execution would b e imp ortant Consider the following two internal functions

INTEGER FUNCTION funkyabc

REAL INIENTINOUT a

REAL INIENTIN bc

a aa

funky ab

END FUNCTION funky

and

INTEGER FUNCTION funkyabc

REAL INIENTINOUT a

REAL INIENTIN bc

a a

funky ac

END FUNCTION funky

Notice how b oth functions mo dify the value of a this means that the value of rezzy is wholly dep endent

on the undened order of execution

With a b and c the following happ ens

if funky executed rst then rezzy

in funky a is initially equal to

up on exit of funky a is equal to

up on exit funky is equal to

in funky a is initially

up on exit of funky a is equal to

up on exit funky is equal to

this means that rezzy is

and a equals

if funky executed rst then rezzy

in funky a is initially

up on exit of funky a is equal to

up on exit funky is equal to

in funky a is initially equal to

Septemb er University of Liverp o ol

Recursive Pro cedures

up on exit of funky a is equal to

up on exit funky is equal to

this means that rezzy is

and a equals

Aprop erly constructed function should b e such that its result is uniquely determined by the values of

its arguments and the values of its arguments should b e unchanged by any invo cation as should any

global entities of the program Fortran will intro duce the PURE keyword which when applied to a

pro cedure asserts that the routine is sideeectfree in the sense that it do es not change any values

b ehind the scenes For example a PURE function will not change any global data nor will it change

the values of any of its arguments If at all p ossible all functions should b e PURE as this will keep the

co de simpler

Recursive Pro cedures

Recursion o ccurs when pro cedures call themselves either directly or indirectly Any pro cedural call

chain with a circular comp onent exhibits recursion Even though recursion is a neat and succinct

technique to express a wide variety of problems if used incorrectly it may incur certain eciency

overheads

In Fortran recursion had to b e simulated by a user dened stack and corresp onding manipulation

functions in Fortran it is supp orted as an explicit feature of the language For matters of eciency

recursive pro cedures SUBROUTINEs and FUNCTIONs must b e explicitly declared using the RECURSIVE

keyword See b elow

Declarations of recursive functions have a slightly dierent syntax to regular declarations the RESULT

keyword must b e used with recursive functions and sp ecies a variable name where the result of the

function can b e stored The RESULT keyword is necessary since it is not p ossible to use the function

name to return the result Array valued recursive functions are allowed and sometimes a recursive

function reference would b e indistinguishable from an array reference The function name implicitly

has the same attributes as the result name

The fact that a function exhibits recursion must b e declared in the header valid declarations are

INTEGER RECURSIVE FUNCTION factN RESULTNFact

or

RECURSIVE INTEGER FUNCTION factN RESULTNFact

In the ab ove the INTEGER applieds to both fact and N Fact

or

RECURSIVE FUNCTION factN RESULTNFact

INTEGER NFact

In the last case INTEGER NFact implicitly gives a typ e to fact it is actually illegal to also sp ecify a

typ e for fact

Subroutines are declared using the RECURSIVE SUBROUTINE header

Fortran Course Notes File CourseNotesps

Pro cedures and ArrayArguments

Recursive Function Example

The following program calculates the factorial of a numb er n and uses nnn

PROGRAM Mayne

IMPLICIT NONE

PRINT fact etc

CONTAINS

RECURSIVE FUNCTION factN RESULTNFact

INTEGER INTENTIN N

INTEGER NFact also defines type of fact

IF N THEN

NFact N factN

ELSE

NFact

END IF

END function FACT

END PROGRAM Mayne

fact The INTEGER keyword in the function header sp ecies the typ e forboth fact and N

The recursive function rep eatedly calls itself on each call the values of the argument is reduced by one

and the function called again Recursion continues until the argument is zero when this happ ens the

recursion b egins to unwind and the result is calculated

is evaluated as follows

is so calculate then multiply by

is need to calculate

is is and

can nowwork back up the calculation and ll in the missing values

Recursive Subroutine Example

Subroutines can also b e recursive

RECURSIVE SUBROUTINE FactorialN Result

INTEGER INTENTIN N

INTEGER INTENTINOUT Result

IF N THEN

CALL FactorialNResult

Result Result N

ELSE

Result

END IF

END SUBROUTINE Factorial

Septemb er University of Liverp o ol

Question MaggotOnion Recursive Pro cedure Conundrum

An onion with an unknown numb er of layers contains a maggot at an unknown layer Write a

recursive function which will determine the depth of the maggot using the probability of of a

maggot b eing at a particularlayer and a random numb er generator

Object Orientation

Stack Simulation Example

261

Push(2) Push(6) 2 Push(1) 6

162 162

6 Pop2 Pop Pop

Figure How a Stack Works

A stack can b e thought of as a pile of things that can only b e accessed from the top You can put

something on the top of the pile a Push action and you can grab things o the top of the pile a Pop

action

The diagrams show the conventional visualisation of a stack As elements are pushed onto the top of

the stack the previous top elements get pushed down as things are popped o the top the lower stack

entries move towards the top

Fortran Course Notes File CourseNotesps

Object Orientation

2

Push(2) Push(6) Pos Pos

26 261

Push(1) Pos Pos

26116 26

Pop Pop Pos Pos

22

Pop

Pos Pos

Figure How a Stack Could b e Implemented

These diagrams showhowwe will simulate the stack using an array with a p ointer to indicate where

the top of the stack is As elements are pushed onto the stack they are stored in the array and the top

p osition moves right as things are p opp ed o the top of the stack moves left From this description

it can b e seen that we need three objects to simulate a stack

a current p osition marker

the array to hold the data

the maximum size of the stack array

This data is needed byboththePush and Pop pro cedures and should b e made global

Stack Example Program

For example the following denes a very simple element integer stack

PROGRAM stack

IMPLICIT NONE

INTEGER PARAMETER stacksize

INTEGER SAVE storestacksize pos

stuff that uses stack

Septemb er University of Liverp o ol

Reusability Mo dules

CONTAINS

SUBROUTINE pushi

INTEGER INTENTIN i

IF pos stacksize THEN

pos pos storepos i

ELSE

STOP Stack Full error

END IF

END SUBROUTINE push

SUBROUTINE popi

INTEGER INTENTOUT i

IF pos THEN

i storepos pos pos

ELSE

STOP Stack Empty error

END IF

END SUBROUTINE pop

END PROGRAM stack

store and pos do not really need the SAVE attribute as here they are declared in the main program

and do not go out of scop e The declaration of stack size as a PARAMETER allows the stack size to

b e easily mo died it do es not need the SAVE attribute b ecause it is a constant

The main program can now call push and pop which simulate adding to and removing from a

element INTEGER stack The current state of the stack that is the numb er of elements on the sack

and the values of each lo cation are stored as global data

Actually this is not the ultimate way of simulating a stack but demonstrates global data See later

foranimprovement

Reusability Mo dules

A stack is a useful which can be applied to many dierent situations In its current

state if we wished to use the stack with a dierent program then it would b e necessary to retyp e or

cut and paste the existing text into this other program There is a far b etter way to enable the co de

to b e used elsewhere and that is to convert the existing PROGRAM to a MODULE This technique is called

encapsulation

MODULE Stack

IMPLICIT NONE

INTEGER PARAMETER stacksize

INTEGER SAVE storestacksize pos

CONTAINS

SUBROUTINE pushi

END SUBROUTINE push

SUBROUTINE popi

END SUBROUTINE pop

END MODULE Stack

Fortran Course Notes File CourseNotesps

Object Orientation

In the ab ove mo dule the data structures and access functions that relate to the stack have b een

encapsulated in a MODULEItisnow p ossible for any other program units that need to utilise a stack

to attach this mo dule with a USE statement and access its functionality

PROGRAM StackUser

USE Stack attaches module

IMPLICIT NONE

CALL Push CALL Push

CALL Popi CALL Popj

END PROGRAM StackUser

All entities declared in Stackfor example push and popare now available to StackUser This form

of software reusabilityisacornerstone of object oriented programming in this case the mo dule is like

a C or Java class as it contains the denition of an object the stack and all the access functions

used to manipulate it push and pop

A p oint of note is that the SAVE statement in the mo dule b ehaves as usual The variables store and

pos are given the SAVE attribute b ecause objects in a mo dule only exist when the mo dule is b eing used

In the StackUser program the mo dule is in use for the lifetime of the program it has the scop e

of the program However if the mo dule was not used in a main program but was instead attached

to a pro cedure then when that pro cedure is exited and control passed back to the main program

which do es not contain a USE statement the mo dule will go out of scop e and any nonstatic objects

nonSAVEd objects will disapp ear from memory The next time the mo dule is brought back into

scop e a new instance of these variables will b e created however any values held by nonstatic objects

will b e lost This is the same principle as when the SAVE attribute is applied to objects declaredina

pro cedure

Within a mo dule functions and subroutines are called mo dule pro cedures and follow slightly dierent

rules from regularpro cedures The main dierence is that they may contain internal pro cedures in

the same wayasPROGRAMs

All mo dules must b e compiled b efore any program unit that uses the mo dule

Mo dules can also b e used to replace the functionalityof a COMMON blo ck COMMON blo cks have long

b een regarded as an unsafe feature of Fortran In Fortran they were the only way to achieve

global storage In Fortran global storage can b e achieved by

declaring the required global objects within a mo dule

giving these objects the SAVE attribute

attaching the mo dule via USE to each program unit which requires access to the global data

Wherever the MODULE is used the global objects are visible

For example to declare X Y and Z as global declared them in a mo dule

MODULE Globby

REAL SAVE X Y Z

END MODULE Globby

and use the mo dule

Septemb er University of Liverp o ol

Reusability Mo dules

PROGRAM YewZing

USE Globby

IMPLICIT NONE

END PROGRAM YewZing

If the use of a COMMON blo ck is absolutely essential then a single instance of it should b e placed in a

MODULE and then used A COMMON blo ck names a sp ecic area of memory and splits it up into areas

that can be referred to as scalarorarray objects for a single COMMON blo ck it is p ossible to sp ecify

a dierent partition of data objects each time the blo ck is accessed each partition can be referred

to by any typ e in other words the storage can be automatically retyp ed and repartitioned with gay

abandon this leads to all sorts of insecurities Putting the blo ck in a MODULE removes any p ossibility

of the ab ove typ e of misuse This will have the eect of ensuring that each time the COMMON blo ck

is accessed it will b e laid out in exactly the same way and mimics the techniques of placing COMMON

blo cks in INCLUDE les a common Fortran technique

Question Encapsulation

Stats which contains encapsulated functions for calculating the Dene a mo dule called Simple

mean and standard deviation of an arbitrary length REAL vector The functions should have the fol

lowing interfaces

REAL FUNCTION meanvec

REAL INTENTIN DIMENSION vec

END FUNCTION mean

REAL FUNCTION StdDevvec

REAL INTENTIN DIMENSION vec

END FUNCTION StdDev

Hint In Fortran SIZEX gives the numb er of elements in the array X

You maylike to utilise your earlier co de as a basis for this exercise

Add some more co de in the mo dule which records how many times each statistical function is called

during the lifetime of a program Record these numb ers in the variables mean use and std dev use

Demonstrate the use of this mo dule in a test program in one execution of the program give the mean

and standard deviation of the following sequences of numb ers

and

plus two other sequences

Print out the values of mean use and std dev use for this run of the program

Fortran Course Notes File CourseNotesps

Object Orientation

Question Complex Arithmetic Mo dules

A complex numb er with solely integer comp onents can b e represented as atwo element INTEGER

Complex Arithmetic which contains FUNCTIONs each ac array Write a MODULE called Integer

cepting two integer complex numb er op erands and delivering the result of addition subtraction

multiplication and division Where appropriate Fortran integer division rules should be followed

The following rules for complex arithmetic maybeuseful

a bix y i a xb y i

and

a bi x y i a xb y i

and

a bi x y i a x b y a y b xi

and

a bi a bi x y i

 

x y i x y

Also write a pro cedure to accept one integer complex numb er and one nonnegative integral exp onent

which delivers the result of

Note for n

n

a bi a bi a bi

z

n

Restricting Visibility

Data hiding has b een intro duced to Fortran as a safety feature it prevents anyb o dy using a mo dule

from changing certain mo dule objects such as those used for housekeeping Restricting the visibility

of purely internal details also allows the mo dule to b e up dated mo died without the user b eing aware

For example the following lines could b e added to the stack example

PRIVATE pos store stacksize hidden

PUBLIC pop push not hidden

size and pos are hidden from the user whereas pop and push This would ensure that store stack

are not This makes the mo dule much safer as the user is unable to accidentally mo dify the value of

pos the index of the top of the stack or mo dify the contents of store the data structure holding

the contents of the stack

The default accessibility for an arbitrary mo dule is PUBLIC which means that if accessibility is not

sp eciced a user will have access to all entities This can b e reversed by using a PRIVATE statement

directly after the IMPLICIT NONE statement

Septemb er University of Liverp o ol

The USE Renames Facility

MODULE Blimp

IMPLICIT NONE

PRIVATE

unlessed specified otherwise all

other entities are PRIVATE

END MODULE Blimp

There is also an attributed form of the visibility sp eciers

In our example we can equivalently use statements and attributes

PUBLIC set default visibility

INTEGER PRIVATE SAVE storestacksize pos

INTEGER PRIVATE PARAMETER stacksize

Which means in the main PROGRAM

CALL Push CALL Popi

is p erfectly OK but

pos storepos

would b e agged by the compiler as an error

Access to the stack is now only p ossible via the access functions pop and push

Question VisibilityAttributes

Add visibility attributes to your Simple Stats mo dule so that the usage statistics variables mean use

and std dev use cannot b e accessed directly but must b e viewed by calling either of the access sub

routines Print Mean Use or Print Std Dev Use In other words

CALL PrintMeanUse

CALL PrintStdDevUse

should print out the values of mean use and std dev use

What advantage do es this approach hold

The USE Renames Facility

The USE statement names a mo dule whose public denitions are to be made accessible It has the

following form

USE mo dulename newname usename

Fortran Course Notes File CourseNotesps

Mo dules

Ifalocalentity has the same name as an object in the mo dule then the mo dule object can b e renamed

as many renames as desired can b e made in one USE statement they are just supplied as a comma

separated list

USE Stack IntegerPop Pop

Here the mo dule object Pop is renamed to IntegerPop when used lo cally This renaming facilityis

essential otherwise user programs would often require rewriting owing to name clashes in this waythe

renaming can b e done by the compiler Renaming should not b e used unless absolutely necessary as

it can add a certain amount of confusion to the program It is only p ermissible to rename an object

once in a particular scoping unit

USE ONLY Statement

It is p ossible to the availability of objects declared in a mo dule made visible by use asso ciation

by using the ONLY clause of the USE statement In this way name clashes can b e avoided by only using

those objects which are necessary It has the following form

USE mo dulename ONLY onlylist

The onlylist can also contain renames

This metho d can b e used as an alternative to renaming mo dule entities for example a situation may

arise where a user wishes to use or objects from a mo dule but discovers that if the mo dule is

accessed by use asso ciation there are a couple of hundred name clashes The simplest solution to this

is to only allowthe or objects to b e seen by his her program These or objects can b e renamed

if desired

For example

USE Stack ONLYPos IntegerPop Pop

Only Pos and Pop are made accessible and the latter is renamed

The USE statement with its renaming and restrictive access facilities gives greater user control enabling

two mo dules with similar names to b e accessed by the same program with only minor inconvenience

In addition the ONLY clause gives the compiler the option of just including the object co de asso ciated

with the entities sp ecied instead of the co de for the whole mo dule This has the p otential to make

the executable co de smaller and faster

Question USE Renames Statement

Write a USE statement that accesses the Simple Stats mo dule This USE statement should sp ecify

that only the pro cedures Mean and Print Mean Use are attached and that they are renamed to be

Average and Num Times Average Called

Mo dules

Mo dules are new to Fortran They have a very wide range of applications and their use should b e

encouraged They allow the user to write object based co de which is generally accepted to b e more

Septemb er University of Liverp o ol

Mo dules General Form

reliable reusable and easier the write than regular co de

A MODULE is a program unit whose functionality can be exploited by any other program unit which

attaches it via the USE statement A mo dule can contain the following

global object declarations

Mo dules should b e used in place of Fortran COMMON and INCLUDE statements If global

data is required for example to cut down on argument passing then objects declared in a mo dule

can b e made visible wherever desired by simply attaching the mo dule Objects in a mo dule can

b e given a static storage class so will retain their values b etween uses

Sets of variable declarations which are not globally visible can also b e placed in a mo dule and used

at various places in the co de this mimics the functionalityofthe INCLUDE statement INCLUDE

was an extension to Fortran and literally included a sp ecied le at the appropriate place

in the co de

interface declarations

It is sometimes advantageous to package INTERFACE denitions into a mo dule and then use the

mo dule whenever an explicit interface is needed This should b e done in conjunction with the

ONLY clause but is only really useful when mo dule pro cedures cannot b e used

pro cedure declarations

Pro cedures can b e encapsulated into a mo dule which will make them visible to any program unit

which uses the mo dule This approach has the advantage that all the mo dule pro cedures and

hence their interfaces are explicit within the mo dule so there will b e no need forany INTERFACE

blo cks to b e written

controlled object accessibility

Variables pro cedures and op erator declarations can have their visibility controlled by access

statements within the mo dule It is p ossible for sp ecied objects to be visible only inside the

mo dule This technique is often used to provide security against a user meddling with the values

of mo dule objects which are purely internal to the mo dule

packages of whole sets of facilities

Derived typ es op erators pro cedures and generic interfaces can be dened and packaged to

provide simple object oriented capabilities

semantic extension

A semantic extension mo dule is a collection of userdened typ e declarations access routines

and overloaded op erators and intrinsics which when attached to a program unit allowtheuser

to use the functionalityasifitwere part of the language

Mo dules General Form

The syntax of a mo dule program unit is

MODULE mo dule name

declarations and sp ecications statements

CONTAINS

denitions of mo dule pro cedures

END MODULE mo dule name

Fortran Course Notes File CourseNotesps

Mo dules

mo dule name is the name that app ears in the USE statement it is not necessarily the same as the lename

MODULE Nodule ! TYPE Definitions ! Global data ! .. ! etc .. CONTAINS SUBROUTINE Sub(..) ! Executable stmts CONTAINS SUBROUTINE Int1(..)

END SUBROUTINE Int1

! etc. SUBROUTINE Intn(..)

END SUBROUTINE Int2n END SUBROUTINE Sub ! etc. FUNCTION Funky(..) ! Executable stmts CONTAINS

! etc

END FUNCTION Funky

END MODULE Nodule

Figure Schematic Diagram of a Mo dule Program Unit

Entities of other mo dules can b e accessed bya USE statement as the rst statement in the sp ecication

part This is called useasso ciation

Noncircular dep endent denition chains are allowed one mo dule USEs another which USEs another

and so on providing a partialinheritance mechanism

A mo dule may include the following declarations and sp ecications

Septemb er University of Liverp o ol

Mo dules General Form

USE statements a mo dule inherit the environment of another mo dule either fully orpartially by

using USE ONLY clause

object denitions any declarations and denitions that could app ear in a main program can also

b e found here

object initialisations

typ e denitions

accessibility statements

interface declarations of external pro cedures

MODULE PROCEDURE declarations pro cedures that app ear after the CONTAINS sp ecier Mo dule

pro cedures are written in exactly the same way as regular external pro cedures and may also

contain internal pro cedures They can be given visibility attributes so may be private to the

mo dule or usable by any program unit that employs the mo dule

Fortran Course Notes File CourseNotesps

Mo dule

Pointers and Derived Typ es

Pointers and Targets

It is often useful to have variables where the space referenced by the variable can b e changed as well

as the values stored in that space This is the functionalitythata p ointer variable provides The space

to which a p ointer variable p oints is called its target p ointer variables do not hold data they p oint to

scalarorarrayvariables which themselves may contain data Pointers are used in much the same way

as nonp ointer variables with added functionalityand a small numb er of extra constraints In many

situations the p ointer has the p otential to use less space than the target

Target

Pointer Target

Target

Figure The Relationship Between a Pointer and its Target

Pointers are very useful as they can b e used to access variables indirectly aliasing and provide a more

exible alternative to ALLOCATABLE arrays Pointers may also b e used in conjunction with userdened

typ es to create dynamic data structures such as linked lists and trees These structures are useful

for example in situations where data is b eing created and destroyed dynamically and it cannot be

predicted in advance how this will o ccur

Fortran p ointers are unlike C p ointers as they are much less exible and more highly optimised The

need for eciency has implications in the way that they are used declared and what they can p oint to

Pointers are strongly typ ed in the sense that a p ointer to a REAL scalartarget may not p oint to any

other data typ e INTEGER LOGICAL etc normay it p oint to an array A p ointer to a one dimensional

arraymay not p oint to an array of a dierent dimensionality unless the array has b een sectioned down

to the required rank In order to further enhance optimisation anything that is to b e p ointed at must

have the TARGET attribute either explicitly or implicitly In its lifetime a p ointer can b e made to p oint

at various dierent targets however they all must b e correctly attributed and b e of the correct typ e

kind and rank At any given time a given p ointer may only have one target but a given target maybe

p ointed to bymore than one p ointer

The use of p ointers may have a detrimental eect on the p erformance of co de but can be used to

actually enhance eciency For example when sorting a set of long database records on one eld it is

much more ecient to declare an array of p ointers one for each database entry to dene the sorted set

than to physically move copy large database records Pointer variables are typically small probably

smaller than the storage required for one default integer variable so can b e used to conserve memory

Moving arrays ab out in memory will involve a large and costly copy op eration whereas retargeting a

couple of p ointers is a far less exp ensive solution

Pointer Status

In general a reference to the pointer will be a reference to the target Pointers are automatically

dereferenced in other words when the p ointer is referenced it is actually the value of the space that

the p ointer references that is used

Pointer Status

Pointer variables have states

undened the initial status of a p ointer

asso ciated the p ointer has a target

disasso ciated the p ointer has no target but is dened Visualisation

Pointer

Associated Target

Disassociated Null

Undefined ???????

Figure The Three States of a Pointer

There is a scalar LOGICAL intrinsic function ASSOCIATED which returns the asso ciation status of a

p ointer The function returns TRUE if the p ointer is asso ciated and FALSE if it is disasso ciated

the result is undened if the p ointer status is itself undened

As good practise one should always use the NULLIFY statement to disasso ciate p ointers b efore any

use Since an unasso ciated p ointer has an undened status it should not b e referenced at all not even

in an ASSOCIATED function call Fortran will allow p ointers to b e nullied on declaration

Pointer Declaration

A POINTER is a variable declared with the POINTER attribute it has static typ e kind and rank deter

mined by its declaration

REAL POINTER Ptor

REAL DIMENSION POINTER Ptoa

The rst declaration sp ecies that the name Ptor is a p ointer to a scalar REAL target the second

sp ecies that Ptoa is a p ointer to a rank array of reals Pointers cannot p oint to literals

The ab ove raises three interesting p oints

Fortran Course Notes File CourseNotesps

Pointers and Targets

the declaration xes the typ e kind and rank of any p ossible target

p ointers to arrays are always declared with deferredshap e array sp ecications

the rank of a target is xed but the shap e mayvary

Avariable with the POINTER attribute may not p ossess the ALLOCATABLE or PARAMETER attributes

Target Declaration

If ordinary variables are to b ecome targets of a p ointer they must b e declared as such and b e given the

TARGET attribute

REAL TARGET x y

REAL DIMENSION TARGET a b

REAL DIMENSION TARGET c

With these declarations and those from Section

x or y may b ecome asso ciated with Ptor

a b or c may b ecome asso ciated with Ptoa

As Fortran has always b een asso ciated with eciency it was felt that p ointers should b e implemented

as eciently as p ossible and to this end the TARGET attribute was included The Fortran standard

says

The TARGET attribute is dened solely primarily for optimization purp oses It

allows the pro cessor to assume that any nonp ointer ob ject not explicitly declared as

a target may be referred to only by way of its original declared name Fortran

Standard

The ab ove text is to b e changed as indicated in Fortranastheword solely is felt to b e misleading

The TARGET attribute is also used at pro cedure b oundaries to say that one of the arguments is a TARGET

which clearly means that the TARGET attribute has uses other than for optimisation

Pointer Manipulation

Pointers have two separate forms of assignment which should not be confused as they have very

dierent results

p ointer assignment

is a form of aliasing referring to an object by a dierent name the p ointer and its target

refer to the same space

can take place between a p ointer variable and a target variable or between two p ointer

variables

normal assignment

Septemb er University of Liverp o ol

Pointer Assignment

can take place b etween a p ointer variable and an object of the appropriate typ e kind and

rank the object on the RHS do es not need to have the TARGET attribute The TARGET

attribute is not needed b ecause the LHS of the assignment is simply an alias for a regular

object and the RHS is not b eing p ointed at When an alias is used on the LHS of an

assignment statement the reference can b e thought of as b eing a reference to the aliased

object

sets the space p ointed at to the sp ecied value If a particular space is p ointed at by a

numb er of p ointers then changing the values in the space obviously changes the dereferenced

value of all asso ciated p ointers

In summary p ointer assignment makes the p ointer and the variable reference the same space whilst

normal assignment alters the value contained in that space

Pointer Assignment

Consider

Ptor y

Ptoa b

The rst statement asso ciates a p ointer Ptor with a target yPtor is made an alias for y and the

second asso ciates the p ointer Ptoa with bPtoa is an alias for b From nowonnow Ptor and y

and Ptoa and b can b e used interchangeably in statements since they b oth reference the same entity

If the value of y or b is changed the value of Ptor or Ptoa also changes but the lo cation of space

p ointed at do es not

If Ptor is also a p ointer to a scalar real then the p ointer assignment

Ptor Ptor

makes Ptor also p oint to y meaning that y has two aliases The ab ove statement has exactly the

same eect as

Ptor y

Pointer Assignment Example

Consider

x

Ptor y

Ptor x y x

Fortran Course Notes File CourseNotesps

Pointers and Targets

3.14159 x Ptor

3.14159 y

Figure Visualisation of Pointer Assignment

The three statements have the following eect

x is a regular assignment x receives a value

Ptor y aliass y to b e Ptor y do es not necessarily have a meaningful value

Ptor x sets the space p ointed at by Ptor ie y to the value of x any assign

ments references to Ptor are really assignments references to y

At the end of the ab ove sequence of statements x and Ptor have the same value this is b ecause Ptor

is an alias for y so the last statement eectively sets y If the value of x is subsequently

changed the value of Ptor and y do not x is not b eing p ointed at by anything so changing its

value has no eect However

Ptor

means that b ecause of aliasing y would also take the value

Asso ciation with Arrays

An array p ointer may b e asso ciated with the whole of a target ora regular section of a target as long

as the section has the correct rank and typ e and kind A regularsectionisanarray section that can

b e dened by a linear function a subscripttriplet denes a regular section

An array p ointer cannot b e asso ciated with a nonregular vector subscripted array section

Assuming the same declarations as b efore

this is valid

Ptoa a

This p ointer assignment statement aliases the sp ecied section to the name Ptoa for exam

ple Ptoa refers to element a Ptoa refers to to element a and so on

SIZEPtoa gives and SHAPEPtoa gives

this is valid

Ptoa a

Septemb er University of Liverp o ol

Asso ciation with Arrays

This means alias Ptoa to a D array Note that the section sp eciers uphold the rank even

though they only sp ecify one element

these are invalid the targets have the wrong rank

Ptoa a

Ptoa a

Ptoa a

The ranks of the targets must b e

this is invalid as the target is not a regular section but is dened by a vector subscript

v

Ptoa avv

Even if the vector subscript v did dene a regular section the statement would still b e invalid as

the sectioning is sp ecied by a vector subscript

For example

Ptoa(1,1) Ptoa(1,2) A(3,1) A(3,3)

Ptoa

Ptoa(2,1) Ptoa(2,2) A

A(5,1) A(5,3)

Figure APointer to a Section of an Array

Ptoa a

Here the top left subsection element can b e referred to through TWO names

A

Ptoa

Fortran Course Notes File CourseNotesps

Pointers and Targets

Dynamic Targets

Targets for p ointers can also be created dynamically by allo cation As well as allotting space for

allo catable arrays the ALLOCATE statement can reserve space to b e the target of a p ointer in this case

the p ointer is not so much an alias of another variable it is more a reference to an unnamed part of

the heap storage

ALLOCATEPtorSTATierr

ALLOCATEPtoannk STATierr

The ab ove statements allo cate new space the rst for a single real and the second for a rank real

array These objects are automatically made the targets of Ptor and Ptoa resp ectively

In ALLOCATE statements the status sp ecier STAT should always be used recall that a zero value

means that the allo cate request was successful and a p ositive value means that there was an error

and the allo cation did not take place There should only b e one object p er ALLOCATE statement so if

the allo cation go es wrong it is easy to tell which object is causing the problem In a pro cedure any

allo cated space should b e deallo cated b efore the pro cedure is exited otherwise the space will b ecome

inaccessible and will b e wasted Allo cated space that is to b e retained b etween pro cedure calls should

have the SAVE attribute

It is not an error to allo cate an array p ointer that is already asso ciated If an array p ointer is already

allo cated and is then allo cated again links with the rst target are automatically broken and a new

target installed in its place Care must b e taken to ensure that the original target is still accessible by

another p ointer otherwise its storagewillbelostfor the duration of the program

Automatic Pointer Attributing

All p ointer variables implicitly have the TARGET attribute This means that any p ointer can b e asso ci

ated with any other p ointer as shown b elow

Ptoa A

Ptor Ptoa

This would asso ciate the element of the target of Ptoa with Ptor

Ptoa

Ptor

A(5,1)

Figure Automatic Attributing of Arrays

Here the b ottom left subsection element can b e referred to through THREE names

Septemb er University of Liverp o ol

Automatic Pointer Attributing

Ptoa

Ptor

A(5,1)

Figure Automatic Attribution of a Pointer

Ptor

A

Ptoa

This form of aliasing has advantages in b oth convenience of expression and eciency For example

if a particular element was b eing used frequently within a nested lo op the calculation of the index of

particular element need only b e done once Subsequent references to the element can then b e made

through the scalar p ointer

Question Pointers and Assignment

Given the following declarations

IMPLICIT NONE

REAL POINTER a b c

REAL TARGET e f g h

REAL k

INTEGER POINTER o

INTEGER TARGET r s

INTEGER v

of the lines b eloware incorrect Which are they and why are they wrong

a h

b h

o s

c g

a k

a e

b v

c g b c

e f

a f

c g

b REALr

Fortran Course Notes File CourseNotesps

Pointers and Targets

Asso ciation Status

The status of a dened p ointer maybetestedby a scalar LOGICAL intrinsic function

ASSOCIATEDPtoa

If Ptoa is dened and asso ciated then this will return TRUE if it is dened and disasso ciated it will

return FALSE If it is undened the result is also undened the Edinburgh and NAg compilers

give opp osite results if ASSOCIATED is given an undened p ointer argument neither give an error

The target of a dened p ointer may also b e tested

ASSOCIATEDPtoa arr

If Ptoa is dened and currently asso ciated with the sp ecic target arr then the function will return

TRUE otherwise if it will return FALSE

The ASSOCIATED intrinsic is also useful to avoid deallo cation errors

IFASSOCIATEDPtoa DEALLOCATEPtoa STATierr

Pointer Disasso ciation

Pointers can b e disasso ciated with their targets by

nullication

NULLIFYPtor

The NULLIFY statement breaks the connection of its p ointer argument with its target if any

and leaves the p ointer in a disasso ciated state however it do es not deallo cate the targets

storage This space will b e inaccessible until the program terminates unless it is p ointed to by

at least one more p ointer A list of p ointers to nullify may b e sp ecied

Immediately after their app earance in a declaration statement nondummy argument p ointers

are in an undened state as a matter of course they should be nullied to bring them into a

disasso ciated state Using an undened p ointer as an argument to the ASSOCIATED statement

is an error b ecause an undened p ointer cannot b e referenced anywhere

deallo cation

DEALLOCATEPtoa STATierr

The DEALLOCATE statement breaks the connection b etween the p ointer and its target and returns

the space to the heap storage for reuse The statement should b e used when the target space

is nished with for example at the end of a pro cedure The target is left in a disasso ciated or

nullied state

The STAT eld should always be used to rep ort on the success failure of the deallo cation

request as usual zero indicates success and a p ositive value means failure It is p ossible to

deallo cate ALLOCATABLE arrays and POINTER variables in the same statement however it is

recommended that there only b e one object p er DEALLOCATE statement in case there is an error

It is an error to deallo cate anything that has not b een rst allo cated or that is in a disasso ciated

or undened state and it is also an error to deallo cate an object that has more than one p ointer

asso ciated with it any other p ointers should rst b e nullied b efore deallo cation is p erformed

Septemb er University of Liverp o ol

Pointers to Arrays vs Allo catable Arrays

Pointers to Arrays vs Allo catable Arrays

In the general case ALLOCATABLE arrays should b e used in preference to POINTER arrays in order to

facilitate optimisation Arrays which are the target of p ointers may be referred to by a numb er of

dierent names aliass whereas ALLOCATABLE arrays may only have one name Clearly if aliasing is

desired then POINTERsand TARGETs must b e used

There are two main restrictions imp osed up on allo catable arrays which do not apply to POINTER arrays

unallo cated ALLOCATABLE arrays cannot b e passed as actual arguments to pro cedures

ALLOCATABLE arrays cannot b e used as comp onents of derived typ es

In summary ALLOCATABLE arrays are more ecient and POINTER arrays are more exible

An interesting discussion ab out p ointer eciency can b e found here

httpeuclidmathfsuedu pbismuRESEARCHSOFTWAREPOINTERpointerhtml

Practical Use of Pointers

Pointers can b e of great use in iterative problems Iterative metho ds

make guess at required solution

use guess as input to equation to pro duce b etter approximation

use new approximation to obtain b etter approximation

rep eat until degree of accuracy is obtained

As an example let us nd the square ro ot of a numb er by iteration

X YX

n n

X

n

A stable and rapidly convergent algorithm which pro duces acceptable value forsquare ro ot in small

numb er of iterations

The following iterative co de segment could b e found in a solution

REAL Y tolE

REAL prevapp nextapp

prevapp set initial approx

DO calculate next approx

nextapp prevapp Yprevapp

IF ABSnextappprevappnextapp tol THEN

EXIT

ELSE

prevapp nextapp

END IF

Fortran Course Notes File CourseNotesps

Pointers and Targets

END DO

nextapp now contains the required result

This structure is typical of such iterative pro cesses however in general the objects involved are not

simple real variables and the up date pro cess is not just a simple arithmetic assignment It is frequently

the case that the objects which hold the approximations are large arrays and the cost of the copy

op eration moving the result of one iteration to b ecome the input to the next is a signicant prop ortion

of the total cost of an iteration In such cases it is much more ecient to use p ointers to avoid having

to do the copying op erations

Forarrayproblems a more ecient solution can b e constructed which uses p ointers

PROGRAM Solve

IMPLICIT NONE

REAL tolE

REAL DIMENSION TARGET approx approx

REAL DIMENSION POINTER prevapprox nextapprox swap

prevapprox approx

nextapprox approx

prevapprox initialapproximation

DO

nextapprox iterationfunctionofprevapprox

IF ABSMAXVALnextapproxprevapprox tol EXIT

swap prevapprox

prevapprox nextapprox

nextapprox swap

END DO

CONTAINS

FUNCTION iterationfunctionofin

REAL DIMENSION in

REAL DIMENSIONSIZEinSIZEin iterationfunctionof

END FUNCTION

END PROGRAM Solve

function of The DO lo op contains the iteration which gradually moves towards the solution iteration

is an array valued function uses the values of prev approx and improves them to be closer to the

solution Convergence is tested by examining the dierence b etween the twomostrecentapproxima

tions The worst value chosen by MAXVALisused If this worst value diers from the corresp onding

value from the previous iteration bymore than the tolerance then a further iteration is p erformed The

supp osition is that when values remain constant b etween iterations they have reached their optimum

value In other words when all array elements have stabilised the solution has b een found

The following statements

swap prevapprox

prevapprox nextapprox

nextapprox swap

shue the arrays around turns the current approximation in to the previous one for the next iteration

next approx ends up p ointing to the old prev approx which has outlived its usefulness on the next

Septemb er University of Liverp o ol

Pointers and Pro cedures

iteration this array can b e used to hold the next set of approximations Here p ointer assignment replaces

two p otentially exp ensive copy op erations The net eect is that prevapprox and nextapprox are

swapp ed at the cost of p ointer assignments which is quite small whereas to swap the actual objects

would require real assignments a much more exp ensive op eration

Pointers and Pro cedures

Pointer variables may b e used as actual and dummy arguments in much the same way as nonp ointer

variables As with all arguments dummies and actuals must match in typ e kind and rank Note that

a POINTER dummy argument cannot have the INTENT attribute In some areas p ointers are slightly

more exible than nonp ointer arguments for example unallo cated ALLOCATABLE arrays cannot be

passed as actual arguments to a pro cedure but unasso ciated unallo cated POINTER arrays can

If a p ointer is to b e used as an actual argument then the interface must b e explicit The reason for

this is b ecause a p ointer argument can b e interpreted in twoways

immediately dereference and pass the target the corresp onding dummy argument do es not have

the POINTER attribute

pass the p ointer so it can b e manipulated as a p ointer in the pro cedure the corresp onding dummy

argument do es have the POINTER attribute

For example

PROGRAM Supping

IMPLICIT NONE

INTEGER POINTER Pint Pint

CALL BeerPintPint

CONTAINS

SUBROUTINE Beerargarg

INTEGER POINTER arg

INTEGER INTENTIN arg

END SUBROUTINE Beer

END PROGRAM Supping

Pint which corresp onds to the nonp ointer arg is dereferenced b efore b eing passed to Beer Pint

is not

Referring to Pint in the main program references exactly the same space as arg in the subroutine

howeveritisnotguaranteed that if an unasso ciated p ointer is asso ciated in a pro cedure that on return

to the call site the p ointer will still b e asso ciated This is not dened to b e the case in the standard

Pointer Valued Functions

A function may b e p ointer valued in the articial example b elow the function ptr returns a p ointer

to the larger of a and b

Fortran Course Notes File CourseNotesps

Pointers and Targets

PROGRAM main

IMPLICIT NONE

REAL x

INTEGER TARGET a b

INTEGER POINTER largest

CALL RANDOMNUMBERx

a x

CALL RANDOMNUMBERx

b x

largest ptr

print largest

CONTAINS

FUNCTION ptr

INTEGER POINTER ptr

IF a GT b THEN

ptr a

ELSE

ptr b

END IF

END FUNCTION ptr

END PROGRAM main

It is not p ossible to have an attribute in the FUNCTION statement so the sp ecication that the function

is p ointer valued must b e made amongst the declarations The following declaration would also suce

INTEGER FUNCTION ptr

POINTER ptr

Clearly for the function to return a result the correct typ e the function name must identify a target

by b eing on the LHS of a p ointer assignment

The interface of an external p ointer valued function must always b e explicit see

The following illustrates an external p ointer valued function

PROGRAM main

IMPLICIT NONE

REAL x

INTEGER TARGET a b

INTEGER POINTER largest

INTERFACE

FUNCTION ptrab

IMPLICIT NONE

INTEGER TARGET INTENTIN a b

INTEGER POINTER ptr

END FUNCTION ptr

END INTERFACE

CALL RANDOMNUMBERx

a x

CALL RANDOMNUMBERx

b x

Septemb er University of Liverp o ol

Pointer I O

largest ptrab

print a b Largest largest

END PROGRAM main

FUNCTION ptrab

IMPLICIT NONE

INTEGER TARGET INTENTIN a b

INTEGER POINTER ptr

IF a GT b THEN

ptr a

ELSE

ptr b

END IF

END FUNCTION ptr

Pointer IO

When p ointers app ear in I O statements they are always immediately dereferenced so their target is

accessed instead Clearly a p ointer must not b e disasso ciated as dereferencing would make no sense

Consider the following example

PROGRAM Eggie

IMPLICIT NONE

INTEGER ierr

REAL DIMENSION TARGET arr

REAL DIMENSION POINTER p q

p arr

PRINT p

ALLOCATEq STATierr

IF ierr EQ THEN

READ q

PRINT q

DEALLOCATEq

PRINT q invalid no valid target

END IF

END PROGRAM Eggie

In the rst output statement p is dereferenced and the three real numb ers are printed out in array

element ordering The READ statement works in a very similar way Once q has b een allo cated its

app earance in the input statement causes the program to exp ect real numb ers to b e entered on the

standard input channel

The last PRINT statement is an error as it is not p ermissible to attempt to read or write to or from a

deallo cated p ointer

It is not p ossible to print out the address of the target of a p ointer

Derived Typ es

It is often advantageous to express some objects in terms of aggregate structures for example

Fortran Course Notes File CourseNotesps

Derived Typ es

co ordinates x y z

addresses name numb er street etc

Fortran allows comp ound entities or derived typ es to b e dened in other languages these maybe

known as structures orrecords Programs can b e made simpler more maintainable and more robust

by judicious choice of data structures Cho osing an ecient data structure is a complex pro cess and

many b o oks have b een written on the subject

In Fortran a new typ e can b e dened in a derivedtyp estatement

TYPE COORDSD

REAL x y z

END TYPE COORDSD

The typ e COORDS D has three REAL comp onents x y and z These could have b een declared on

three separate lines and the resultant typ e would have b een identical Objects of this new typ e can

b e used in much the same way as objects of an intrinsic typ e for example in assignment statements

as pro cedure arguments or in IO statements however it is not p ermissible to initialise a comp onent

in a derived typ e declaration statement

D can b e declaredinatyp e declaration statement An object of typ e COORDS

TYPE COORDSD pt

Derived typ e objects can b e attributed in the same wayasfor regulartyp e declarations for example

the DIMENSION TARGET or ALLOCATABLE attributes are all valid subject to a small proviso mentioned

later

TYPE COORDSD DIMENSION TARGET ptarr

Derived typ e objects can b e used as dummy or actual arguments and so can b e given the INTENT or

OPTIONAL attributes they cannot however p ossess the PARAMETER attribute

Sup ertyp es

A new derived typ e can b e declared that has as one of its comp onents a further derived typ e This

typ e must have already b een declared or must b e the typ e currently b eing declared The latter is how

recursive data structures are formed

TYPE SPHERE

TYPE COORDSD centre

REAL radius

END TYPE SPHERE

A sphere is characterised by a centre p oint and a radius a typ e with these two comp onents is an

intuitive way of describing such an object This is b etter than dening a typ e with real comp onents

which are all at the same level

Septemb er University of Liverp o ol

Derived Typ e Assignment

TYPE SPHERE

REAL x y z radius

END TYPE SPHERE

Objects of typ e SPHERE can b e declared

TYPE SPHERE bubble ball

There is no sequence asso ciation for derived typ es in other words there is no reason to supp ose that

objects of typ e COORDS D should o ccupy contiguous REAL storage lo cations

Derived Typ e Assignment

Values can b e assigned to derived typ es in twoways

comp onent by comp onent

as an object

The op erator can b e used to select a single sp ecic comp onent of a derived typ e object which allows

the object to be given values in a piecewise fashion In order to select a sp ecic comp onent it is

necessary to know the names given to the comp onents when the derived typ e was initially declared

The object bubble is of typ e SPHERE which weknow is comp osed of two comp onents centre and a

radiushowever centre is itself a derived typ e comp onent so therefore not of intrinsic typ e meaning

that the individual comp onents must b e selected from this comp onent to o In order to assign a value

an intrinsic typ ed expression to a derived typ e comp onent using a regular assignment statement it

must b e ensured that each comp onent is fully resolved in other words the comp onent selected is of

intrinsic typ e

In the following two statements

bubbleradius

bubblecentrex

bubbleradius is of typ e REAL so can be assigned a REAL value but bubblecentre is of typ e

D which must therefore must b e further resolved in order to p erform assignment of a single COORDS

intrinsically typ ed value bubblecentrex or y or z is of intrinsic typ e so can b e given a

value using the intrinsic assignment op erator

During assignments of this typ e normal typ e co ercion rules still applyfor example an INTEGER could

b e assigned to a REAL comp onent of a derived typ e with the INTEGER value simply b eing promoted

As an alternative to the ab ovementioned comp onentbycomp onent selection it is p ossible to use a

derived typ e constructor to assign values to the whole object This structure constructor takes the

form of the derived typ e name followed byaparenthesised list of values one for each comp onent For

example consider

bubblecentre COORDSD

Fortran Course Notes File CourseNotesps

Derived Typ es

bubblecentre is of typ e COORDS D so we can use the automatically dened derived typ e constructor

COORDS D to co erce the listed values to the correct typ e Here as COORDS D has three comp onents

the constructor must also b e supplied with expressions

The object bubble can b e set up using the SPHERE constructor this has two comp onents one of typ e

COORDS D and one of typ e REALAs bubblecentre is of typ e COORDS D this can b e used as one

comp onent of the constructor The other comp onent is default REAL

bubble SPHEREbubblecentre

In the ab ove example COORDSD could b e used in place of bubblecentre

bubble SPHERECOORDSD

It is not p ossible to have

bubble SPHERE

Even though the typ e constructor lo oks like a function call there is no keyword selection or optional

elds

Assignment b etween two objects of the same derived typ e is intrinsically dened ball and bubble

can b e equated

ball bubble

Arrays and Derived Typ es

It is p ossible to dene derived typ es which contain arrays of intrinsic or derived typ e objects These

arrays cannot b e ALLOCATABLE but can have the POINTER attribute

Consider

TYPE FLOBBLE

CHARACTERLEN nom

INTEGER DIMENSION harry

END TYPE FLOBBLE

TYPE FLOBBLE bill

TYPE FLOBBLE DIMENSION ben

it is also p ossible to declare an array of objects where each element of the array also contains an array

however it is not p ermissible to refer to an arrayofarrays We can refer to an element or subsection

of the array comp onent

billharry

billharry

benharry

benharry

benharry

Septemb er University of Liverp o ol

Derived Typ e IO

in the ab ove example the ve expressions all dene a section of some sort there is only one nonscalar

index in the reference In a derived typ e that has more levels of derived typ e nesting there can still

only b e sectioning of at most one comp onent level

The following twoexpressions are not allowed b ecause sectioning is in more than one comp onent

benharry invalid

benharry invalid

Therstexpression is invalid b ecause a section is taken from the array of objects and also from one of

the comp onents of each object the second expression is invalid for the same reason although slightly

more subtle the reference here is a one element subsection of ben not scalar and the whole of the

harry comp onent Rememb er that ben is scalarandben is non scalar

Derived Typ e IO

Derived typ e objects can be used in IO statements in much the same way as intrinsic objects the

only restrictions are that

the derived typ e must not contain a POINTER comp onent this is b ecause the p ointer reference

may never be resolved If for example a circular list structure were to app ear in an output

statement the program would never terminate

the visibility of the internal typ e comp onents must not b e restricted see Section

A derived typ e object is written out or read in as if all the comp onents were explicitly inserted into the

output statement in the same order in which they were dened

So

PRINT bubble

is exactly equivalent to

PRINT bubblecentrex bubblecentrey

bubblecentrez bubbleradius

Derived typ es containing arrays are handled in the exp ected way Individual comp onents are input

output in order with individual elements of arrays output in array element order

Derived Typ es and Pro cedures

Derived typ es can be used as arguments to pro cedures however the typ e denition must be made

accessible by either use or host asso ciation Indeed if the same textual denition of a nonSEQUENCE

typ e app ears in two separate program units the twotyp es which have the same names typ es and

comp onents are not considered to b e the same This is b ecause of optimisation the compiler can

represent the typ e however it sees t

Fortran Course Notes File CourseNotesps

Derived Typ es

A SEQUENCE typ e is a sp ecial class of derived typ e which relies on sequence asso ciation The comp o

nents of a sequence typ e are b ound to b e stored in contiguous memory lo cations in the order of the

comp onent declarations

All typ e denitions should b e encapsulated in a mo dule

MODULE VecDef

TYPE vec

REAL r

REAL theta

END TYPE vec

END MODULE VecDef

To makethetyp e denitions visible the mo dule must b e used

PROGRAM Up

USE VecDef

IMPLICIT NONE

TYPEvec north

CALL subbynorth

CONTAINS

SUBROUTINE subbyarg

TYPEvec INTENTIN arg

END SUBROUTINE subby

END PROGRAM Up

Typ e denitions can only b ecome accessible by host or use asso ciation

So long as the typ e denition is visible derived typ e arguments b ehave like intrinsically typ ed arguments

they can b e given attributes OPTIONAL INTENT DIMENSION SAVE ALLOCATABLE etc Interfaces

are required in the same situations as for intrinsic typ es

Derived Typ e Valued Functions

Functions can return results of an arbitrary dened typ e

FUNCTION Pookanga roo

USE VecDef

TYPE vec Poo

TYPE vec INTENTIN kanga roo

Poo

END FUNCTION Poo

Recall that the typ e denition must b e made available byhostor use asso ciation

Question Complex arithmetic

Mo dify your existing Integer Complex Arithmetic mo dule and dene a typ e INTCOMPLEX which

is able to represent a complex numb er with integer comp onents

Septemb er University of Liverp o ol

Derived Typ e Valued Functions

TYPEINTCOMPLEX

INTEGER xy

END TYPE

Mo dify the mo dule pro cedures etc to accept this datatyp e instead of the previously implemented

element array

Add two functions UPLUS and UMINUS to the mo dule which each takeone INTCOMPLEX argument such

that

UPLUSZI ZI

UMINUSZI ZI

Write a test program to demonstrate

Fortran Course Notes File CourseNotesps

Mo dule

Mo dules and Objectbased

Programming

POINTER Comp onents of Derived Typ es

It is forbidden to include ALLOCATABLE arrays as comp onents of derived typ es however complex data

structures can b e constructed by including POINTER variables instead These comp onents can p oint to

scalarorarray valued intrinsic or derived typ es which means that dynamically sized structures can b e

created and manipulated As an example consider

TYPE VSTRING

CHARACTER DIMENSION POINTER chars

END TYPE VSTRING

Objects of this typ e have a comp onent which is a p ointer to a dynamically sized D arrayofcharacters

This data typ e is useful forstoring strings of dierent lengths

TYPEVSTRING Pvs Pvs

ALLOCATEPvschars

Pvschars Hello

Pvs1 Hello

Figure APonter to a Variable Length String

There is a restriction concerning IO of userdened typ es which contain p ointer comp onents see

Section the object must b e resolved to an intrinsic typ e comp onent If

TYPEVSTRING nom

print nom Illegal

print nomchars fine

the comp osite object nom cannot b e output but since nomchars is a p ointer to a CHARACTER array

it can b e written

Pointers and Lists

Pointers and Lists

The use of p ointers with derived typ es also provides supp ort for structures such as linked lists Derived

typ es may contain p ointers to any other typ e including the typ e b eing currently dened It is not

p ossible to p oint to a typ e which has yet to b e dened the target typ e must b e dened or b e b eing

dened

In the following example CELL contains a p ointer to another object also of typ e CELL

TYPE CELL

INTEGER val

TYPE CELL POINTER next

END TYPE CELL

this denes a single linked list of the following schematic structure

27 3458

Valnext Val next

Figure A Linked List With Elements

the ab ove diagram represents two cells each cell contains a value INTEGER and a link to the next cell

The last cell in the list should have a null target use the NULLIFY command As long as something

p oints to the head of the structure the whole of the list can b e traversed

Intrinsic assignment b etween structures containing p ointer comp onents is subtlely dierent from nor

mal assignment is always intrinsically dened for assignment between two objects of the same

derived typ e so when the typ e contains a p ointer comp onent must b ehave sensibly in other words

it do es what the user would exp ect it to do

nonp ointer comp onents are assigned by copying the value from the RHS to the corresp onding

comp onent on the LHS

p ointer comp onents are p ointer assigned using the op erator

So

TYPECELL A

TYPECELL TARGET B

A B

is equivalent to

Aval Bval

Anext Bnext

Other recursive structures can b e built up such as singly or doubly linked lists or nary trees

Fortran Course Notes File CourseNotesps

Derived Typ es

Linked List Example

The following fragment would create a linked list of cells starting at head and terminating with a cell

whose next p ointer is null disasso ciated

PROGRAM Thingy

IMPLICIT NONE

TYPE CELL TARGET head

TYPE CELL POINTER curr temp

INTEGER k

headval listhead default

NULLIFYheadnext unundefine

curr head curr head of list

DO

READ k get value of k

ALLOCATEtemp create new cell

tempvalk assign k to new cell

NULLIFYtempnext set disassociated

currnext temp attach new cell to

end of list

curr temp curr points to new

end of list

END DO

END PROGRAM Thingy

There now follows a linebyline dissection of the example

TYPE CELL TARGET head this is a cell which anchors the list This is the starting

p oint for traversal of the list

TYPE CELL POINTER curr temp declare p ointers to two cells curr p oints to the

current p osition in the list this will tell us where the next list cell is to b e added temp is used

for receiving a newly allo cated cell b efore it gets tagged onto the list

INTEGER k variable used when reading the data

headval set the value of the list anchor to b e zero null

NULLIFYheadnext disasso ciate nullify the head of the list

curr head curr marks the p osition in the list where the next cell is to b e added As we

havent really started yet this is at the head of the list

DO END DO a lo op where the input is read and the list is built up

READ read value of k

ALLOCATEtemp creates a new cell called temp if the lo op is not on its rst iteration the

previously created cell will have b een attached to the end of the list The ALLOCATE statement

will create a new temp elsewhere in the memory which can then eventually b e attached to the

linked list

tempvalk set the value part of the cell to the previous input value

NULLIFYtempnext initialise disasso ciate nullify the p ointer comp onent of the new cell

This cell will b e the end of the list for at least one lo op iteration

Septemb er University of Liverp o ol

Pointers and Lists

currnext temp attach the new cell to the end of the list The list is anchored by head

and the last cell in the list is nullied and p ointed to by curr Adding a new cell to the end

of the list is achieved by simply making the last list item p oint to the new cell The p ointer

comp onent of the new cell has already b een nullied ready for the next iteration of the lo op

curr temp reassign the p ointer which indicates the end of the list temp is now the last item

in the list so curr should b e made to p oint to this cell

To summarise

headval

NULLIFYheadnext

curr head

curr

0 Null

head

Figure Initialisation of the List

This rst set of statements take a TARGET cell head the head of the list and initialise it Here

initialisation involves setting the numeric comp onent to zero headval and NULLIFYing the

p ointer comp onent The p ointer curr is set to p oint a the current insert p oint in the list as the list

has no memb ers the current insert p oint is at the head of the list

ALLOCATEtemp

tempval k

NULLIFYtempnext

k Null

temp

Figure Initialisation of a New Cell

The second sequence of statements creates a new cell from the heap storage called temp This cell

has its value comp onent set to the most recent input value k and is then given the disasso ciated

status using NULLIFY

currnext temp

curr temp

Fortran Course Notes File CourseNotesps

Derived Typ es

curr

0 k Null

head

Figure The Addition of a New List Memb er

The third sequence of statements take the new cell an insert it in the list at the current insert p oint

The insert p oint p ointed to by curr is then moved to reect the addition

curr

0 k Null

head

Figure The General Structure of the List

When the list is completed it will have a structure similar to that given in the ab ove diagram The list

can b e traversed bystarting at the head cell and following the p ointer links

It is no go o d having a linked list if it cannot b e navigated Awalkthrough which prints each cell

value out could b e programmed as follows

curr head

DO

PRINT currval

IFNOTASSOCIATEDcurrnext EXIT

curr currnext

END DO

curr head the variable curr is used as a placemarker Since we do not need to know

where the end of the list is there is no need to keep curr p ointing at it We can always nd the

end bystarting at the head and traversing the list until we reach a null p ointer Thus curr is

b eing reused

DO END DO the list traversal is p erformed within this lo op The criterion for exiting is

that the p ointer comp onent of the current cell is disasso ciated null

PRINT currval print out the value of the current cell this rst time around the lo op this

will b e the value of the list head which was set to the default value of if this is not required

then it should b e skipp ed

Septemb er University of Liverp o ol

Arrays of Pointers

IFNOTASSOCIATEDcurrnext EXIT if the p ointer is not asso ciated with a target then

the lo op is exited This can b e thought of as if the p ointer comp onent is null then EXIT

curr currnext move to the next cell the statement says make curr p oint to the

target of currnext currnext is immediately dereferenced

Question Dened Typ es and Pointers

Write a program to implement a tree sort The program should read in textual names from standard

input and place each name in a binary tree The algorithm is

read in a name

IF name end EXIT

add the name to the tree

print the tree

Steps and should b e implemented with recursive pro cedures

The algorithm for Step is for each no de

if the no de is null add the name to the no de and return

if the name is earlier in the alphab et than the no de name

recursively go down the left branch

otherwise

recursively go down the right branch

The algorithm for Step is

if the no de is null return

recursively print the left branch

print the no de name

recursively print the right branch

Arrays of Pointers

As it is p ossible to create arrays of objects of derived typ es so is p ossible to create what are in eect

arrays of p ointers

TYPE iPTR

INTEGER POINTER compon

END TYPE iPTR

TYPEiPTR DIMENSION ints

Fortran Course Notes File CourseNotesps

Derived Typ es

ints

Figure Visualisation of an ArrayOfPointers

Visualisation

Here we have an arrayof elements each of which can p oint to an INTEGER It is not p ossible to

refer to ints as there is no context where a whole arrayor subarray of p ointers like this can b e

used dereferencing can only b e used on a scalar p ointer

intscompon valid

intscompon not valid

intscompon not valid

If desired ints could have b een ALLOCATABLE

TYPE iPTR

INTEGER POINTER compon

END TYPE iPTR

TYPEiPTR DIMENSION ALLOCATABLE ints

ALLOCATEints

The following is also acceptable and denes and array of p ointers to integer arrays

TYPE iaPTR

INTEGER POINTER DIMENSION acompon

END TYPE iaPTR

TYPEiaPTR DIMENSION intsarrays

Each p ointer comp onent can b e made to p oint to an unnamed part of the heap storage or to an existing

array

INTEGER ierr

ALLOCATEintsarraysacomponSTATierr

ALLOCATEintsarraysacomponSTATierr

Septemb er University of Liverp o ol

Arrays of Pointers

or

INTEGER TARGET Ia Ib Ic

intsarraysacompon Ia

intsarraysacompon Ib

intsarraysacompon Ic

ALLOCATABLE arrays cannot b e comp onents of derived typ es

Question Arrays of Pointers

Rewrite the MAXLOC sorting example using an array of p ointers instead of a vector subscript to

hold the order of the numb ers

Question Sorting Using Pointers

Using derived typ es and p ointers to minimise storage write a program to set up a usersp ecied

numb er of element arrays and ll them with random numb ers b etween and and then using

your SimpleStats MODULE sort them rstly on the basis of their mean and secondly on the basis of

their standard deviation Print out the results of the sorting so that the array with the greatest mean

is printed out rst alongside the actual value of its mean to demonstrate correctness and the array

with the smallest mean is printed out last Do the same with the sorted list of standard deviations viz

Position Mean

Array is

Position Mean

Array is

Position Mean

Array is

and so on

Hint Use an arrayofthefollowing user dened typ e

TYPE ARRAYINFO

REAL DIMENSION POINTER Array

REAL ArrayMean

REAL ArrayDev

END TYPE ARRAYINFO

to hold the array its mean and its standard deviation You should create twoarrays where each element

can p oint to objects of typ e ARRAYINFO these arrays can b e used to represent the sorted mean and

standard deviation lists

You may nd it useful to employ other data structures to aid the solution Do not worry ab out

implementing an ecient sorting mechanism

Fortran Course Notes File CourseNotesps

Mo dules Typ e and Pro cedure Packaging

Mo dules Typ e and Pro cedure Packaging

In a prop er program it would b e very useful to use derived typ es in the same way as intrinsic typ es

and even use them interchangeably with intrinsic typ es To do this we must for each derived typ e

denition provide the same functionalitythatisprovided for intrinsic typ es For example there are

no intrinsic functions dened for userdened typ es and op erations b etween derived and intrinsic typ es

are very limited however

pro cedure arguments can b e derived typ es

functions can return results of derived typ es

op erators can b e overloaded to apply to derived typ es

So we can write a package which contains

typ e denitions

constructors

overloaded intrinsics

an overload set of op erators

generic overload set denitions

other useful pro cedures

This form of bundling is known as encapsulation

There are many advantages to including the ab ove functionality in a mo dule

derived typ e denitions must b e placed in a mo dule so that their structure can b e made visible

by use asso ciation in non MODULE program units

the interfaces for generic pro cedures user dened op erators op erator overloads and assignment

overloads must all b e explicit

following the same logic it makes excellent sense to put the actual overloaded intrinsic pro cedures

and intrinsic op erators in this mo dule to o

any other relevant pro cedures should also b e placed in the mo dule to provide an encapsulated

package of typ e denitions op erator denitions intrinsic pro cedures and access routines

This mo dule when USEd would provide an almost transparent semantic extension to Fortran

An example of this kind of mo dule is the varying string mo dule which is to b e an ancillary standard

to Fortran An implementation of this mo dule has b een written at Liverp o ol and includes all the

relevant intrinsic functions for example LEN INDEX and op erators for example LGE which

have b een dened for the new VARYING STRING typ e This means that objects of typ e VARYING STRING

can b e used almost transparently with objects of the same and intrinsic CHARACTERtyp e

Septemb er University of Liverp o ol

Derived Typ e Constructors

Derived Typ e Constructors

Derived typ es have their inbuilt constructors however it is often a go o d idea to write a sp ecic routine

instead These should always b e used instead of the default constructor

Purp ose written constructors can supp ort default values optional and keyword arguments and will not

have to be mo died if the internal structure of the typ e is changed It is also p ossible to hide the

internal details of the typ e by placing a PRIVATE statement with the typ e denition

MODULE ThreeDee

IMPLICIT NONE

TYPE CoordsD

PRIVATE

REAL x y z

END TYPE CoordsD

CONTAINS

TYPECoordsD FUNCTION InitCoordsDxyz

REAL INTENTIN OPTIONAL xyz

Set Defaults

InitCoordsD CoordsD

IF PRESENTx InitCoordsDx x

IF PRESENTy InitCoordsDy y

IF PRESENTz InitCoordsDz z

END FUNCTION InitCoordsD

END MODULE ThreeDee

If an argument is not supplied then the corresp onding comp onent of Coords D is set to zero

The following calls are all valid

PROGRAM TestoD

USE ThreeDee

IMPLICIT NONE

TYPECoordsD pt pt pt

pt InitCoordsD

pt InitCoordsD

pt InitCoordsDy

PRINT pt pt

PRINT pt pt

PRINT pt pt

END PROGRAM TestoD

This program will pro duce

Fortran Course Notes File CourseNotesps

Mo dules Typ e and Pro cedure Packaging

pt

pt

pt

This approach allows greater exibility

Generic Pro cedures

Dening a generic interface to a pro cedure is a way of grouping pro cedures with similar functionality

together under one name Typically a generic pro cedure interface has a general name and contains a list

of sp ecic pro cedures with similar functionality which are implemented for all data typ es in a program

Whenever the generic pro cedure name is used the compiler is able to tell which sp ecic pro cedure this

instance of use corresp onds to by lo oking the typ es of the actual arguments The sp ecic pro cedure

can then b e invoked

Most intrinsics are generic in that their typ e is determined by their arguments For example ABSX

returns a real value if X is REAL

returns a real value if X is COMPLEX

returns a integer value if X is INTEGER

It is p ossible to ignore the generic interface and still refer to a pro cedure by its sp ecic name for

example DABS CABS or DABS the end eect will be the same Note that if the pro cedure name

is used as an actual argument then the sp ecic name must be used Fortran do es not supp ort

runtime resolution of generic overloads as this would compromise eciency

A user can dene his her own generic names for user pro cedures This is implemented through a

generic interface sp ecication The user may then call the pro cedure with a generic name and the

compiler will examine the numb er typ e rank and kind of the nonoptional arguments to decide which

sp ecic pro cedure to call at compiletime See Section for the interaction between generic

interfaces and kinds If no such pro cedure exists then an error is generated Thesetofpro cedures in

the generic interface is known as an overload set For example

INTERFACE CLEAR

SUBROUTINE clearinta

INTEGER DIMENSION INTENTINOUT a

END SUBROUTINE clearint

SUBROUTINE clearreala

REAL DIMENSION INTENTINOUT a

END SUBROUTINE clearreal

END INTERFACE CLEAR

int and clear real can b oth b e called by the generic name CLEAR clear int will b e called clear

if the actual argument is INTEGER clear real will b e invoked if the argument is REAL The overload

set consists of clear int and clear real It is b elieved that using generic pro cedure names makes

programming much easier as the user do es not have to rememb er the sp ecic name of a pro cedure but

only the function that it p erforms

Pro cedures in a generic interface must b e all functions or all subroutines they cannot b e mixed In

the case of functions it is the typ e of the arguments not the typ e of the result which determines which

sp ecic pro cedure is called

Septemb er University of Liverp o ol

Generic Interfaces Commentary

In order to use user dened generic pro cedure names the interfaces must b e explicit The b est wayto

do this is to put the generic interface into a mo dule and attach it by USE asso ciation

Note currently the END INTERFACE statement cannot contain the interface name This is a language

anomaly and is due to b e corrected in Fortran It is likely that many compilers will accept co de

with the name present

Given

MODULE schmodule

INTERFACE CLEAR generic int

MODULE PROCEDURE clearint

MODULE PROCEDURE clearreal

END INTERFACE CLEAR

CONTAINS

SUBROUTINE clearinta

INTEGER DIMENSION INTENTINOUT a

actual code

END SUBROUTINE clearint

SUBROUTINE clearreala

REAL DIMENSION INTENTINOUT a

actual code

END SUBROUTINE clearreal

END MODULE schmodule

PROGRAM Main

IMPLICIT NONE

USE schmodule

REAL prices

INTEGER counts

CALL CLEARprices generic call

CALL CLEARcounts generic call

END PROGRAM Main

prices is a realvalued array so the corresp onding sp ecic pro cedure from the overload set is the one

with a single realvalued arrayasadummyargument clear real

counts is integervalued so the second call will b e resolved to clear int

In order for the compiler to b e able to resolve the reference b oth mo dule pro cedures must b e unique

with resp ect to their nonoptional arguments

Generic Interfaces Commentary

In order for a call to a generic interface to be resolved the overload set must be unambiguous In

other words the sp ecied pro cedures must all b e unique in at least one of typ e kind or rank in their

nonoptional arguments In other words by examining the arguments the compiler calculates

which sp ecic pro cedure to invoke

When parametrised typ es are b eing used in a program default intrinsic typ es should not b e used for

arguments in pro cedures that o ccur in generic interfaces This is b ecause the default typ e corresp onds

to a particular kind which varies from pro cessortopro cessor See Section

Fortran Course Notes File CourseNotesps

Mo dules Typ e and Pro cedure Packaging

Derived Typ e IO

Derived typ es with PRIVATE comp onents need sp ecial pro cedures for IO They cannot b e used in a

simple PRINT or WRITE statement

MODULE ThreeDee

IMPLICIT NONE

TYPE CoordsD

PRIVATE

REAL x y z

END TYPE CoordsD

INTERFACE Print

MODULE PROCEDURE PrintCoordsD

END INTERFACE Print

CONTAINS

SUBROUTINE PrintCoordsDCoord

TYPECoordsD INTENTIN Coord

PRINT Coordx Coordy Coordz

END SUBROUTINE PrintCoordsD

TYPECoordsD FUNCTION InitCoordsDxyz

REAL INTENTIN OPTIONAL xyz

Set Defaults

InitCoordsD CoordsD

IF PRESENTx InitCoordsDx x

IF PRESENTy InitCoordsDy y

IF PRESENTz InitCoordsDz z

END FUNCTION InitCoordsD

END MODULE ThreeDee

Coords D may only be output via the generic interface Print which calls the Print Coords D

pro cedure A generic Print interface can b e extended for each and every derived typ e dened

CALL PrintinitCoordsD

Using this approach further abstracts the typ e denition from the users program If the internal

structure of the typ e is changed then the output routine can be changed accordingly the users

program can remain untouched

Overloading Intrinsic Pro cedures

When a new typ e is added it is a simple pro cess to add a new overload to any relevant intrinsic

pro cedures A generic interface is dened with the same name as the existing generic intrinsic name

Septemb er University of Liverp o ol

Overloading Intrinsic Pro cedures

Any pro cedures included in this interface sp ecication are added to the overload set Note The

body of the pro cedures should be PURE in the sense that they should not alter any global data or

pro duce output Existing intrinsics may be actually b e redened by including a pro cedure with the

same argument typ es as the original intrinsic When the generic name is supplied the new pro cedure

is called instead of the Fortran intrinsic of the same name

As an example assume that we wish to extend the LEN TRIM intrinsic to return the numb er of letters

in the owners name when applied to objects of typ e HOUSE

MODULE newhousedefs

IMPLICIT NONE

TYPE HOUSE

CHARACTERLEN owner

INTEGER residents

REAL value

END TYPE HOUSE

INTERFACE LENTRIM

MODULE PROCEDURE ownerlentrim

END INTERFACE

CONTAINS

FUNCTION ownerlentrimho

TYPEHOUSE INTENTIN ho

INTEGER ownerlentrim

ownerlen LENTRIMhoowner

END FUNCTION ownerlentrim

other encapsulated stuff

END MODULE newhousedefs

The user dened pro cedures are added to the existing generic overload set whenever the ab ove mo dule

is USEd

STRING mo dule All the intrinsic functions that Intrinsic is used in the VARYING

apply to CHARACTER variables have b een overloaded to apply to object of typ e VARYING STRING Thus

VARYING STRING objects may b e used in exactly the same wayasCHARACTER objects

Question Complex Arithmetic Generic Interfaces

Complex Arithmetic mo dule by adding the overload sets for the following Enhance your Integer

intrinsics

REAL returns INTEGER result the real part of a complex numb er Eg REALxy is x

INT returns INTEGER result as ab ove

AIMAG returns INTEGER result the imaginary part of a complex numb erEg AIMAGxy is y

CONJG returns INTCOMPLEX result the conjugate of a complex numb er Eg CONJGxy is

xy

ABS returns REAL result absolute value of a complex numb er Eg ABSxy is SQRTxxyy

so that they accept arguments of typ e INTCOMPLEXREAL and INT should have the same functionality

ie return the rst nonimaginary comp onent of the numb er

Fortran Course Notes File CourseNotesps

Mo dules Typ e and Pro cedure Packaging

Demonstrate that the whole mo dule works by USEing it with the following test program which is

available by anonymous ftp from ftplivacuk in the directory pubfcoursesprogs lename

IntegerComplexzProgramf

PROGRAM Testo

USE IntegerComplexArithmetic

IMPLICIT NONE

PRINT REAL

PRINT REALINTCOMPLEX

PRINT INT

PRINT INTINTCOMPLEX

PRINT AIMAG

PRINT AIMAGINTCOMPLEX

PRINT CONJG

PRINT CONJGINTCOMPLEX

PRINT ABS

PRINT ABSINTCOMPLEX

END PROGRAM Testo

Overloading Op erators

Intrinsic op erators such as and can be overloaded to apply to all typ es in a program This

should b e encapsulated in a mo dule

sp ecify the generic op erator symb ol in parentheses in an INTERFACE OPERATOR statement

sp ecify the overload set in a generic interface

declare the MODULE PROCEDUREsFUNCTIONs which dene how the op erations are implemented

These functions have one or two nonoptional arguments with INTENTIN which corresp ond to

monadic and dyadic op erators

For a dyadic op erator the function has two arguments the rst corresp onds to the LHS op erand

and the second to the RHS op erand For example to dene addition between an integer and say

a representation of a rational numb er there would have to be two pro cedures dened one for the

integerrational combination and one forfor the rationalinteger combination A monadic op eratorhas

acorresp onding pro cedure with only one argument

As usual overloads are resolved by examining the numb er typ e rank and kind of the arguments so the

overload set must b e unambiguous The b o dy of the pro cedures should b e PURE in the sense that they

should not alter any arguments global data orpro duce output

Op erator Overloading Example

The op erator can b e extended to apply to the rational numb er data typ e as follows

MODULE rationalarithmetic

Septemb er University of Liverp o ol

Overloading Op erators

IMPLICIT NONE

TYPE RATNUM

INTEGER num den

END TYPE RATNUM

INTERFACE OPERATOR

MODULE PROCEDURE ratrat intrat ratint

END INTERFACE

CONTAINS

FUNCTION ratratlr rat rat

TYPERATNUM INTENTIN lr

END FUNCTION ratrat

FUNCTION intratlr int rat

INTEGER INTENTIN l

TYPERATNUM INTENTIN r

END FUNCTION intrat

FUNCTION ratintlr rat int

TYPERATNUM INTENTIN l

INTEGER INTENTIN r

END FUNCTION ratint

END MODULE rationalarithmetic

In order for multiplication to be dened between all combinations of integer and rational numb ers

three new combinations must b e dened Obviously integerinteger multiplication already is dened

the remaining three combinations integerrational rationalinteger and rationalrational are dened

in the pro cedures int rat rat int and rat rat resp ectively These three new pro cedures are added

to the op erator overload set of the op erator

It is not p ossible to mo dify the op eratorprecedence when an op erator is overloaded it retains its place

in the p ecking order of op erators

With the following typ e declarations in force

USE rationalarithmetic

TYPE RATNUM ra rb rc

the following sp ecic function references would b e valid

rc ratratintratrarb

however using overloaded intrinsic op erators is clearer and should b e encouraged

rc rarb

And even b etter still add visibility attributes to force user into go o d co ding

MODULE rationalarithmetic

TYPE RATNUM

PRIVATE

Fortran Course Notes File CourseNotesps

Mo dules Typ e and Pro cedure Packaging

INTEGER num den

END TYPE RATNUM

INTERFACE OPERATOR

MODULE PROCEDURE ratratintratratint

END INTERFACE

PRIVATE ratratintratratint

it is now not p ossible to use rat rat etc

Every intrinsic op erator can b e overloaded Some op erators exist in b oth monadic and dyadic forms

for example and and if they are b oth to b e overloaded they must b e handled as separate cases

Question Complex Arithmetic Overloading Op erators

Complex Arithmetic mo dule so that the pro cedures which p erform the ve Mo dify your Integer

basic arithmetic op erations overload the intrinsic op erators Do the same with the pro cedures that

p erform unary plus and unary minus

Dening New Op erators

As well as overloading existing intrinsic op erators new op erators can b e dened They follow the dot

notation of Fortrans nonsymb olic op erators such as AND or OR They have the form

name

where name can only contain letters Op erator names can b e the same as object names with no

conict

For all op erator denitions there must be one or two INTENTIN arguments corresp onding to the

denition of a monadic or dyadic op erator As with generic pro cedure interfaces there must be a

unique set of overloads no duplicity is allowed Of all op erators a userdened monadic has the

highest precedence and a userdened dyadic has the lowest

It is not p ossible to redene the meanings of intrinsic op erators such as NOT and GE

Dened Op erator Example

Consider the following mo dule containing the denition of the TWIDDLE op erator in b oth monadic

and dyadic forms

MODULE twiddleop

INTERFACE OPERATOR TWIDDLE

MODULE PROCEDURE itwiddle iitwiddle

END INTERFACE TWIDDLE

CONTAINS

FUNCTION itwiddlei

INTEGER itwiddle

INTEGER INTENTIN i

Septemb er University of Liverp o ol

Dening New Op erators

itwiddle ii

END FUNCTION

FUNCTION iitwiddleij

INTEGER iitwiddle

INTEGER INTENTIN ij

iitwiddle ij

END FUNCTION

END MODULE

The following program

PROGRAM main

USE twiddleop

print TWIDDLE TWIDDLE TWIDDLETWIDDLE

TWIDDLETWIDDLE

END PROGRAM

pro duces

Note the INTENT attribute which is mandatory and that the END INTERFACE statement cannot contain

the op erator name

The ab ove example highlights how op eratorprecedence inuences the results of TWIDDLETWIDDLE

and TWIDDLETWIDDLE The parentheses mo dify the execution order so that in the rst case

TWIDDLE is evaluated rst the second expression uses intrinsic op eratorprecedence meaning that

the rst expression to b e evaluated is the monadic o ccurrence of TWIDDLE

Question Series and Parallel Resistance Dened Op erators

Dene a mo dule called LECCY OPS containing two op erators PARALLEL and SERIES which

given two default REAL resistance values as op erands will deliver the resistance obtained by connecting

them in parallel or series

For series resistance

R R R



and forparallel

R R R



Use the following test program which is available by anonymous ftp from ftplivacuk in the di

rectory pubfcoursesprogslename DefinedOperatorResistanceQuestionf to demon

strate correctness of the mo dule

PROGRAM Testo

USE Resistance

Print SERIES SERIES

Print PARALLEL PARALLEL

END PROGRAM Testo

Fortran Course Notes File CourseNotesps

Mo dules Typ e and Pro cedure Packaging

Precedence

There is an intrinsic ordering of op erators see Every op eratorinFortran has a precedence

the op erator with the highest precedence is combined with its op erands rst User dened monadic

op erators have the highest precedence of all op erators and user dened dyadic op erators have the

lowest precedence User dened op erators which have the same name as intrinsic op erators retain the

same precedence

For example assume that there are two user dened op erators one monadic the other dyadic then

the expression

TWIDDLEejaTWIDDLEbcANDd

is equivalent to

TWIDDLEejaTWIDDLEbcANDd

The monadic TWIDDLE op erator is combined with its op erand rst whereas the dyadic TWIDDLE

will b e the last op erator to b e considered

Userdened Assignment

Assignment b etween two objects of intrinsic typ e and b etween the same user dened typ e is intrinsically

dened however assignment b etween two dierent userdened typ es orbetween an intrinsic and a

userdened typ e must b e explicitly programmed

Assignment overloading is done in much the same way as op erator overloading except that the pro cedure

which denes the assignment pro cess is a SUBROUTINE with twoarguments The b o dy of the pro cedure

should b e PURE in the sense that it should not alter any arguments global data orpro duce output

Sp ecication of the subroutines which describ e how the assignment is p erformed are given in an INTER

FACE ASSIGNMENT blo ck these subroutines must have the following prop erties

the rst argument is the variable which receives the assigned value the LHS It must have the

INTENTOUT attribute

the second actual argument is the expression whose value is converted and assigned to the result

the RHS expression The corresp onding dummy argument must have the INTENTIN attribute

Dened Assignment Example

Take the rational numb ers example dening the mathematical op erators and is of

little use if the assignment op erator is undened A mo dule should b e written which sp ecies an

interface giving the overload set for the assignment op erator the rules should b e explicitly dened in

mo dule pro cedures for assignment b etween

LHS REAL RHS RATNUM

LHS RATNUMRHS INTEGER

Septemb er University of Liverp o ol

Userdened Assignment

The following interface sp ecies which pro cedures should b e employed for assignment involving rational

numb ers

INTERFACE ASSIGNMENT

MODULE PROCEDURE ratassint realassrat

END INTERFACE

PRIVATE ratassint realassrat

The sp ecic pro cedures will b e given in the CONTAINS blo ck of the mo dule

SUBROUTINE ratassintvar exp

TYPE RATNUM INTENTOUT var

INTEGER INTENTIN exp

varnum exp

varden

END SUBROUTINE ratassint

SUBROUTINE realassratvar exp

REAL INTENTOUT var

TYPE RATNUM INTENTIN exp

var expnum expden

END SUBROUTINE realassrat

the b o dy of each subroutine must contain an assignment to the rst argument

Wherever the mo dule is used the following is valid

ra

i rbrc

If i is declared as an INTEGER and all other objects are of typ e RATNUM then the rst assignment follows

the rules that are laid out in the pro cedure rat ass int and the second accesses real ass rat

Question Complex Arithmetic Overloading the Assignment Op erator

Mo dify your Integer Complex Arithmetic mo dule so that the assignment op erator is overloaded

to allow objects of typ e INTEGER and REAL to b e assigned to INTCOMPLEX objects REAL values should

be truncated before use

Semantic Extension Example

The visibility sp eciers can b e applied to all objects including typ e denitions pro cedures and op erators

It is a particularly go o d idea to deny access to the mo dule pro cedures which dene what overloading

a certain op erator actually means For example consider the rational arithmetic mo dule we clearly

want the op erator to b e visible by use asso ciation PUBLIC but there is no advantage to b e gained

byallowing rat rat int rat and rat int to b e visible to the user An analogous situation arises for

the assignment op erator

For example

Fortran Course Notes File CourseNotesps

Mo dules Typ e and Pro cedure Packaging

MODULE rationalarithmetic

IMPLICIT NONE

PUBLIC OPERATOR

PUBLIC ASSIGNMENT

TYPE RATNUM

PRIVATE

INTEGER num den

END TYPE RATNUM

TYPE PRIVATE INTERNAL

INTEGER lhs rhs

END TYPE INTERNAL

INTERFACE OPERATOR

MODULE PROCEDURE ratrat intrat ratint

END INTERFACE OPERATOR

INTERFACE ASSIGNMENT

MODULE PROCEDURE ratassint realassrat

END INTERFACE ASSIGNMENT

PRIVATE ratrat intrat ratint ratassint realassrat

CONTAINS

SUBROUTINE ratassintvar exp

and so on

END SUBROUTINE ratassint

etc

END MODULE rationalarithmetic

The typ e INTERNAL is only accessible from within the mo dule

The following entities are PUBLIC RATNUM typ e no internal access the rest are PRIVATE

rat rat int rat rat int rat ass int real ass rat and the typ e INTERNAL Note that the

visibility statements for named entities must come after their declaration after the MODULE PROC

EDURE statements

To build a complete class should also add

constructors for RATNUM initRATNUM

output pro cedure for RATNUM Print

overloaded intrinsics REAL CEILING FLOOR etc

Yet Another Example

Dene a mo dule

Septemb er University of Liverp o ol

Userdened Assignment

MODULE circles

IMPLICIT NONE

PRIVATE

TYPE PUBLIC POINT

REAL xy

END TYPE POINT

TYPE PUBLIC CIRCLE

TYPEPOINT centre

REAL radius

END TYPE CIRCLE

INTERFACE OPERATOR CROSSES

MODULE PROCEDURE circlecrosses

END INTERFACE

PUBLIC OPERATOR CROSSES

CONTAINS

LOGICAL FUNCTION circlecrosses cc

TYPECIRCLE INTENTIN cc

REAL d

d ccentrex ccentrex

ccentrey ccentrey

IF d cradius cradius OR

d cradius cradius THEN

circlecrosses TRUE

ELSE

circlecrosses FALSE

END IF

END FUNCTION circlecrosses

END MODULE circles

This is an example demonstrating the visibility attributes op erator denition encapsulation and de

rived typ e denitions

internal comp onents of POINT and CIRCLE are not visible

the op erator CROSSES can b e seen but the pro cedure circle crosses cannot

Program calls mo dule

PROGRAM Example

USE circles

TYPECIRCLE DIMENSION c

INTEGER Xings

read in data c

DO I

DO J I

IF cI CROSSES cJ THEN

PRINT I crosses J

Xings Xings

END IF

END DO

END DO

PRINT Num circles which cross Xings

END PROGRAM

Fortran Course Notes File CourseNotesps

Mo dules Typ e and Pro cedure Packaging

When the mo dule app ears in a USE statement the typ e denition and op erator can safely be used

however any reference to the typ e comp onents or the pro cedure circle crosses would b e an error

Question Complex Arithmetic Accessibility control

Mo dify your Integer Complex Arithmetic mo dule to take advantage of the accessibility state

ments

Use accessibility statements to restrict visibility of the mo dule pro cedures and typ e structure Write a

constructor function and I O subroutines fortheINTCOMPLEX typ e which have the following interfaces

construction

TYPEINTCOMPLEX FUNCTION SetupINTCOMPLEXii

INTEGER INTENTIN i i

END FUNCTION SetupINTCOMPLEX

output

SUBROUTINE PutINTCOMPLEXic

TYPEINTCOMPLEX INTENTIN ic

END SUBROUTINE PutINTCOMPLEX

input

SUBROUTINE GetINTCOMPLEXic

TYPEINTCOMPLEX INTENTOUT ic

END SUBROUTINE GetINTCOMPLEX

Demonstrate that the whole mo dule works by USEing it with the following test program which is

available by anonymous ftp from ftplivacuk in the directory pubfcoursesprogs lename

IntegerComplexcProgramf

PROGRAM Testo

USE IntegerComplexArithmetic

IMPLICIT NONE

TYPEINTCOMPLEX var var ans

var

PRINT var

CALL PutINTCOMPLEXvar

PRINT

var

PRINT var

CALL PutINTCOMPLEXvar

PRINT

var

PRINT var

CALL PutINTCOMPLEXvar

Septemb er University of Liverp o ol

Userdened Assignment

PRINT

var

PRINT var

CALL PutINTCOMPLEXvar

PRINT

var SetupINTCOMPLEX

var SetupINTCOMPLEX

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

Fortran Course Notes File CourseNotesps

Mo dules Typ e and Pro cedure Packaging

PRINT Type in the two INTCOMPLEX components

CALL GetINTCOMPLEXvar

PRINT

PRINT This is what was typed in

CALL PutINTCOMPLEXvar

PRINT

PRINT Your number

ans var var

CALL PutINTCOMPLEXans

PRINT

Intrinsics

PRINT REAL

PRINT REALvar

PRINT

PRINT INT

PRINT INTvar

PRINT

PRINT AIMAG

PRINT AIMAGvar

PRINT

PRINT CONJG

CALL PutINTCOMPLEXCONJGvar

PRINT

PRINT ABS

PRINT ABSvar

END PROGRAM Testo

More on Object Oriented Programming by J S Morgan

Many Fortran programmers may not realise that it is p ossible to implement a C style of object

oriented programming OOP metho dology using the features already extant in Fortran In some

areas Fortran OO programming is a little more verb ose and arguably less elegant than C but

nevertheless OO Fortran programs are quite easily implemented

This section is based on a pap er Howtoexpress C Concepts in Fortran

httpwwwcsrpiedu nortoncoofhtml

by V K Dec yk C D Norton and B K Szymanski at the Jet Propulsion Lab oratory California

Institute of Technology For those wishing to understand the essentials of OOP the article is a go o d

read

Septemb er University of Liverp o ol

Userdened Assignment

They demonstrated OO programming using a database example Here I have used an example related

to graphics to illustrate the same principles

Basically a class in OOP terms is a typ e in Fortran terms which has PRIVATE comp onents together

with a constructorfor creating instances of a class a destructor which destroys instances of a class

and a series of metho ds which p erform various manipulations of instances of the class In the following

I have ignored destructors to keep the co de fragments down to a minimum

Thus to create a class such as a p oint class for use in graphics applications a Fortran mo dule can

b e used For example

MODULE pointclass

PRIVATE

TYPE point

PRIVATE

REAL xy coordinates of the point

ENDTYPE point

INTERFACE new

MODULE PROCEDURE newthis

END INTERFACE

INTERFACE draw

MODULE PROCEDURE drawthis

END INTERFACE

PUBLIC point new draw

CONTAINS

SUBROUTINE drawthisthis

TYPEpoint this

WRITE Drawing point at thisx thisy

END SUBROUTINE drawthis

SUBROUTINE newthisthisxy

TYPEpoint this

REAL xy

thisx x

thisy y

END SUBROUTINE newthis

END MODULE pointclass

Note that the PRIVATE statement makes all names in the mo dule private by default The PRIVATE

statement in the TYPE denition makes the comp onents of the typ e private The public statement

makes only those names which the user is allowed access to visible to the user of the mo dule

The use of the generic names fornewdraw etc allows us to then use the same names for the metho ds

Fortran Course Notes File CourseNotesps

Mo dules Typ e and Pro cedure Packaging

pro cedures in Fortran parlance of other classes It allows new classes to inherit the typ es and

pro cedures of other classes

Thus a line class can b e created as

MODULE lineclass

USE pointclass inherit the public entities of pointclass

PRIVATE

TYPE line

PRIVATE

TYPEPOINT pp

ENDTYPE line

INTERFACE new overrides new for this object

MODULE PROCEDURE newthis

END INTERFACE

INTERFACE draw

MODULE PROCEDURE drawthis

END INTERFACE

PUBLIC linenewdraw

CONTAINS

SUBROUTINE drawthisthis

TYPEline this

WRITE Drawing linethis

END SUBROUTINE drawthis

SUBROUTINE newthisthispp

TYPEline this

TYPEpoint pp

thisp p

thisp p

END SUBROUTINE newthis

END MODULE lineclass

Note that the line class is a sup erclass of the p oint class Inheritance in OO programming is usually

asso ciated with subclassing

We can then write statements such as

TYPEpoint pp

TYPEline aline

create objects

CALL newp

CALL newp

Septemb er University of Liverp o ol

Userdened Assignment

CALL newalinepp

draw them

CALL drawp

CALL drawaline

Frequently in graphics programs it is necessary to create structures consisting of objects of dierent

classes For example a drawing can be mo delled as an array whose elements can contain p oints or

lines or other graphical objects

To achieve this in C it is p ossible to use its socalled dynamic binding features which are accessed

via virtual functions Fortran do es not supp ort these features directly and so a little extra work is

needed

The approach taken is to create eectively a sup ertyp e which handles the housekeeping asso ciated

with manipulating the dierent subtyp es and keeps this hidden from the user

Thus we create a graphic object class which can manifest itself in instances of p oints or lines

Thus

MODULE graphicobjectclass

USE pointclass

USE lineclass

PRIVATE

TYPE graphicobject

PRIVATE

TYPEpoint POINTER pp

TYPEline POINTER lp

ENDTYPE graphicobject

INTERFACE creategraphicobject

MODULE PROCEDURE createpoint createline

END INTERFACE

PUBLIC graphicobject creategraphicobject point line new

drawgraphicobject

CONTAINS

SUBROUTINE createpointthisp

TYPEgraphicobject this

TYPEpointTARGET p

thispp p

NULLIFYthislp

END SUBROUTINE createpoint

SUBROUTINE createlinethisl

TYPEgraphicobject this

TYPElineTARGET l

Fortran Course Notes File CourseNotesps

Mo dules Typ e and Pro cedure Packaging

NULLIFYthispp

thislp l

END SUBROUTINE createline

SUBROUTINE drawgraphicobjectthis

TYPEgraphicobject this

IFASSOCIATEDthisppTHEN

CALL drawthispp

ELSEIFASSOCIATEDthislpTHEN

CALL drawthislp

ENDIF

END SUBROUTINE drawgraphicobject

END MODULE graphicobjectclass

The ab ove uses a typ e with p ointers to the dierent objects When an object of a typ e is cre

ated the appropriate p ointer is p ointed to that object The other p ointer is NULL At runtime the

graphic object checks which object is b eing referenced and calls the appropriate routine draw

Finally putting all this together we can now write programs such as the following

PROGRAM usegraphicobjects

USE graphicobjectclass

IMPLICIT NONE

TYPEgraphicobject gg

TYPEpoint apointppc

TYPEline aline

REAL xyr

set some specific values

x y r

create objects

CALL newapointxy OO equivalent apoint new apointxy

CALL newp

CALL newp

CALL newc

CALL newalinepp OO equivalent aline new alinepp

create generic objects

CALL creategraphicobjectg apoint

CALL creategraphicobjectg aline

draw them

CALL drawgraphicobjectg OO equiv gdrawgraphicobject

CALL drawgraphicobjectg

Septemb er University of Liverp o ol

Semantic Extension Mo dules

END PROGRAM usegraphicobjects

The ab ove I hop e has demonstrated how in Fortran by using a well disciplined metho dology and

including a disciplined naming scheme it is p ossible to mimic the object oriented style of programming

to quite a large degree

The main drawback with the ab ove co de can b e seen when one tries to add an extra object typ e class

to the scheme It is fairly straightforward to

create a new object such as a circle by writing a mo dule using one of the other mo dules as a template

However adding in the necessary co de to the use graphic objects mo dule is much more tricky since

changes have to be made in several dierent places and this can be error prone This is where the

expressibility of a true objectoriented language scores over Fortran

Semantic Extension Mo dules

In summary mo dules can be dened which provide a semantic extensions to the language Such

mo dules require

a mechanism for dening new typ es

a metho d for dening op erations on those typ es

a metho d of overloading the op erations so users can use them in a natural way

away of encapsulating all these features in such a way that users can access them as a combined

set

details of underlying data representation in the implementation of the asso ciated op erations to

be kept hidden

Semantic extension allows the user to express a problem in terms of the natural objects and op erations

relating to that problem This philosophy is used in socalled object oriented programming Fortran

do es provide many features desirable for OOP but falls short of providing all of them

The VARYING STRING mo dule is a go o d example of semantic extension it has has mo dule pro ce

dures which are used to extend generic intrinsic pro cedures intrinsic relational op erators and the

concatenation op erator Most entities in the VARYING STRING mo dule are PRIVATE except the typ e

and intrinsic entities such as the extended op erators and functions

Semantic Extension Example

The use of semantic extension mo dules is not restricted to typ es which are analogous to the intrinsic

typ es such other forms of numb ers The technique can b e used to build extensions in a vast range of

areas The following example illustrates this It denes a mo dule that provides facilities for handling

straight line segments as single objects Lines are assumed to b e dened bythexandycoordinates

of their endp oints For simplicity only two functions are dened ie a function to create a line given

its endp oints and a logical binary op erator which can b e used to check whether two lines intersect

The latter is implemented as a function with twoarguments of typ e LINE returning a logical result

However it would b e p ossible to build up a complete mo dule dening a wide varietyof facilities for

manipulating lines

Fortran Course Notes File CourseNotesps

Mo dules Typ e and Pro cedure Packaging

MODULE Lines

IMPLICIT NONE

Definition of derived type for lines

TYPE LINE

PRIVATE

REAL X Y X Y

XY and XY are the endpoints of the line

END TYPE LINE

Interface Definitions for Generic names

INTERFACE CreateLine

This Procedure creates a line between two points

The arguments of the function will be XYXY

and they can be either all REAL or all INTEGER

MODULE PROCEDURE RealLineConstructor IntegerLineConstructor

END INTERFACE

INTERFACE OPERATORCROSSES

This operator tests if two lines intersect

MODULE PROCEDURE LineLineCrosses

END INTERFACE

CONTAINS

Definitions of specific procedure bodies

FUNCTION IntegerLineConstructorXYXY

INTEGER XYXY

TYPELINE IntegerLineConstructor

IntegerLineConstructorX X

IntegerLineConstructorY Y

IntegerLineConstructorX X

IntegerLineConstructorY Y

END FUNCTION IntegerLineConstructor

FUNCTION RealLineConstructorXYXY

REAL XYXY

TYPELINE RealLineConstructor

IntegerLineConstructorX X

IntegerLineConstructorY Y

IntegerLineConstructorX X

IntegerLineConstructorY Y

END FUNCTION RealLineConstructor

FUNCTION LineLineCrossesLL

TYPELINE L L

LOGICAL LineLineCrosses

REAL XL XL XL YL XL YL m c

REAL Cth Sth

REAL PARAMETER tol E a small number

angle L makes with xaxis

IF LX LX tol THEN

th pi

Septemb er University of Liverp o ol

Semantic Extension Mo dules

ELSE

th ATAN LYLYLXLX

END IF

Cth COSth

Sth SINth

Find x coordinates of L in new axis system

XL LXCth LYSth

XL LXSth LYCth

Find coords of endpoints of L in new axis system

XL LXCth LYSth

YL LXSth LYCth

XL LXCth LYSth

YL LXSth LYCth

find m and c for equation of new line

LineLineCrosses FALSE

IF XL XL tol THEN lines not parallel

m YLYLXLXL

c YL m XL

xcross cm

Test if crossing point is inside line segment

IF XL xcross AND XL xcross THEN

LineLineCrosses TRUE

END IF

END IF

END FUNCTION LineLineCrosses

END MODULE Lines

The mo dule can b e used in a program such as the one b elow

PROGRAM UsingLines

USE Lines

IMPLICIT NONE

TYPELINE L L Declare two objects of type Line

Create two lines one using the INTEGER interface and one

using the REAL interface

L CreateLine

L CreateLine

IF LCROSSESL THEN

PRINT line crosses line

ELSE

PRINT line does not cross line

END IF

END PROGRAM

We could mo dify the mo dule by changing the internal representation of a line b ecause of the judiciously

chosen object accessibility the change in representation is totally hidden from the user

MODULE Lines

Fortran Course Notes File CourseNotesps

Mo dules Typ e and Pro cedure Packaging

IMPLICIT NONE

TYPE LINE

PRIVATE

REAL X Y SLOPE LENGTH

XY is the start of the line

END TYPE LINE

Interface Definitions for Generic names

INTERFACE CreateLine

This Procedure creates a line between two points

The arguments of the function will be XYXY

and they can be either all REAL or all INTEGER

MODULE PROCEDURE RealLineConstructor IntegerLineConstructor

END INTERFACE

INTERFACE OPERATORCROSSES

This operator tests if two lines intersect

MODULE PROCEDURE LineLineCrosses

END INTERFACE

CONTAINS

Definitions of specific procedure bodies

FUNCTION IntegerLineConstructorXYXY

INTEGER XYXY

TYPELINE LineConstructor

LineConstructorX X

LineConstructorY Y

LineConstructorslope REALYYXX

LineConstructorlength SQRTREALYYXX

END FUNCTION IntegerLineConstructor

FUNCTION RealLineConstructorXYXY

REAL XYXY

TYPELINE LineConstructor

LineConstructorX X

LineConstructorY Y

LineConstructorslope YYXX

LineConstructorlength SQRTYYXX

END FUNCTION RealLineConstructor

rewrite of the whole module to use the new structure

END MODULE Lines

The main program given ab ove could use either of the two Lines mo dules without mo dication

Septemb er University of Liverp o ol

Mo dule

Parametrised Intrinsic Typ es

Plus

Complex Data Typ e

This intrinsic data typ e has the same precision as default REAL and has comparable prop erties to other

intrinsic data typ es

A COMPLEX object is made up from two default REAL cells and is declared as follows

COMPLEX z j za

Symb olic constants are expressed as a coordinate pair

COMPLEX PARAMETER i

Realvalued literals and symb olic constants and complex valued literals and symb olic constants can

all b e used in a COMPLEX object initialisation statement for example PARAMETER statement but it is

not p ermissible to allow a constructed value containing realvalued symb olic constants as comp onents

So

INTEGER PARAMETER a a

COMPLEX PARAMETER i

COMPLEX PARAMETER ii i

COMPLEX PARAMETER iii a

is OK but

COMPLEX PARAMETER iv aa

is no good The CMPLX constructor cannot b e used in initialisation expressions

Complex values can b e constructed elsewhere using the CMPLX intrinsic function

z CMPLXxy

This format must be used if the RHS is not a literal constant It is recommended that the CMPLX

intrinsic b e used even when the RHS is a literal value except in PARAMETER statements as this makes

the program more consistent and highlights the typ e conversion

z CMPLX

Complex Data Typ e

Typ e co ercion b ehaves exactly as fortheREAL data typ e for example if a COMPLEX literal contained

integers these would b e promoted to REAL values b efore assignment to the COMPLEX variable

Complex expressions can b e used in the same way as other typ es

REAL x COMPLEX a b c

a xbcCMPLX

b

The real value x will b e promoted to the complex value CMPLXx b will b e set to CMPLX

If necessary all other data typ es are promoted to complex values When a noncomplex value is co erced

a is placed in the complex part of the co ordinate pair

Complex Intrinsics

The following intrinsic are relevant to the COMPLEX data typ e

AIMAGz imaginary part of a complex numb er

When supplied with a COMPLEX argument this function returns the imaginary part for example

AIMAG is

REAL or DBLE real part of a complex numb er

When applied to a complex argument returns the real part of the complex value as a REAL or

DOUBLE PRECISION numb er For example DBLE is D

CONJGz conjugate of a complex numb er

When applied to a complex argument returns the complex conjugate of a complex numb er for

example CONJGCMPLXxy equals CMPLXxy

ABSz absolute value of a complex numb er

When applied to a complex argument returns the real valued absolute value for example

ABSCMPLXxy equals SQRTx y

SIN etc mathematical functions

The set of mathematical intrinsic functions is dened generically for complex arguments The

result typ e will generally b e complex

For example SINz will calculate the complex function result as would be exp ected if z

x iy then

real part of sinzsinxcoshy

imaginary part of sinz cosxsinhy

As a rule of thumb if the mathematical function can b e applied to complex arguments then it

will b e implemented as such in Fortran

Septemb er University of Liverp o ol

Complex Intrinsics

Question Complex Arithmetic Mixing Typ es

Complex Arithmetic mo dule by adding the overload sets for op erations Enhance your Integer

between REAL and INTCOMPLEX op erands and INTEGER and INTCOMPLEX op erands these should b e

implemented for dyadic and Clearly the result of an op eration between a REAL and

INTCOMPLEX expression and an INTEGER and INTCOMPLEX expression should b e of typ e INTCOMPLEX

REAL numb ers should b e truncated b efore use

Recall that if a is integer or real valued then

a x y i a xy i

and

a x y i a x y i

and

a x y i a xa y i

and

a a x a y

i

   

x y i x y x y

so

i i

and

i i

Demonstrate that the whole mo dule works by USEing it in the following test program which is avail

able by anonymous ftp from ftplivacuk in the directory pubfcoursesprogs lename

IntegerComplexProgramf

PROGRAM Testo

USE IntegerComplexArithmetic

IMPLICIT NONE

TYPEINTCOMPLEX var var ans

var

PRINT var

CALL PutINTCOMPLEXvar

var

PRINT var

Fortran Course Notes File CourseNotesps

Complex Data Typ e

CALL PutINTCOMPLEXvar

var

PRINT var

CALL PutINTCOMPLEXvar

var SetupINTCOMPLEX

var SetupINTCOMPLEX

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT Type in the two INTCOMPLEX components

CALL GetINTCOMPLEXvar

PRINT This is what was typed in

CALL PutINTCOMPLEXvar

PRINT Your number

ans var var

CALL PutINTCOMPLEXans

Septemb er University of Liverp o ol

Complex Intrinsics

Intrinsics

PRINT REAL

PRINT REALvar

PRINT INT

PRINT INTvar

PRINT AIMAG

PRINT AIMAGvar

PRINT CONJG

CALL PutINTCOMPLEXCONJGvar

PRINT ABS

PRINT ABSvar

REAL INTEGER OP INTCOMPLEX

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

var SetupINTCOMPLEX

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

Fortran Course Notes File CourseNotesps

Complex Data Typ e

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

INTCOMPLEX OP INTEGER REAL

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

Septemb er University of Liverp o ol

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

END PROGRAM Testo

Parameterised Intrinsic Typ es

Fortran had a problem with numeric p ortability the precision and exp onent range of a data typ e

on one pro cessorwould not necessarily b e the same on another For example a default REAL maybe

 

able to supp ort numb ers up to say on one machine and up to on another One of the goals

of Fortran was to overcome this p ortabilityproblem Fortran implements a portable precision

selecting mechanism it supp orts typ es which can b e parameterised by a kind value an integer The

kind value is used to select a representation mo del fora typ e and for numeric typ es can b e sp ecied

in terms of the required precision A pro cessor can supp ort dierent precisions or representations

of INTEGER REAL and COMPLEX dierent CHARACTER sets for example arabic musical notation and

cryllic script and dierent ways of representing LOGICAL objects DOUBLE PRECISION do es not have

dierent precisions and its use is not recommended use a parameterised REAL typ e instead

An example of the parameterisation of an intrinsic typ e is

INTEGERKIND ik

REAL rk

The kind parameters corresp ond to diering precisions supp orted by the compiler details in the compiler

manual

Fortran Course Notes File CourseNotesps

Parameterised Intrinsic Typ es

Objects of dierent kinds can be mixed in arithmetic expressions and rules exist for typ e co ercion

pro cedure arguments however must match in typ e and kind There is no typ e co ercion across

pro cedure b oundaries

Integer Data Typ e byKind

Selecting kind parameters by an explicit integer is still not portable the explicit integer will corresp ond

to dierent precisions on dierent machines a mechanism is needed to select a kind value on the

basis of the desired precision For integers this can only b e achieved by using the SELECTED INT KIND

intrinsic function For example SELECTED INT KIND returns an integer which corresp onds to the

 

kind representation capable of expressing numb ers in the range In the case of SELECT

ED INT KIND the argument sp ecies the minimum decimal exp onent range for the desired mo del

For example

INTEGER short medium long vlong

PARAMETER short SELECTEDINTKIND medium SELECTEDINTKIND

long SELECTEDINTKIND vlong SELECTEDINTKIND

INTEGERshort abc

INTEGERmedium def

INTEGERlong ghi

The ab ove declarations sp ecify that precision should b e at least

 

short

 

medium

 

long

 

vlong

If a mo del with at least the stated precision is not available then the function will return and any

declaration using this kind value will give an error at compile time

Constants of Selected Integer Kind

Constants of a selected kind are denoted by app ending underscore followed by the kind numb er oran

integer constant name b etter

long

Be very careful not to typ e a minus sign instead of an underscore

There are other pitfalls to o the constant

short

may not b e valid as KIND short may not b e able to represent numb ers greater than Be very

careful as the numb er may overow

Septemb er University of Liverp o ol

Real KIND Selection

Real KIND Selection

This works on a similarprinciple to integer kind selection the intrinsic SELECTED REAL KIND can b e

parameterised with two values the minimum precision and the minimum decimal exp onent range the

corresp onding kind value will b e returned or if the desired range cannot b e supp orted the result will

be

SELECTED REAL KIND will return a kind value that supp orts numb ers with a precision of digits

and decimal exp onent range b etween and

Declarations are made in the same wayasfor INTEGERs for example

INTEGER PARAMETER r SELECTEDREALKIND

r SELECTEDREALKIND

REALKINDr x y z

REALr PARAMETER diff r

COMPLEX variables are sp ecied in the same way

COMPLEXKINDr cinema

COMPLEXr inferiority rr

Both parts of the complex numb er have the same numeric range

It can also b e seen how the literal kind sp ecication is achieved by the use of the underscore

Kind Functions

It is often useful to b e able to interrogate an object to see what kind parameter it has

KIND is an intrinsic function that returns the integer which corresp onds to the KIND of the argument

The argument can be a variable or a literal For example KINDa will return the integer which

corresp onds to the kind of a and KIND returns the kind value chosen for the representation used

for the default integer typ e

The typ e conversion functions INT NINT REAL DBLE etc have an optional KIND argument for

sp ecifying the representation of the result of the function for example

INTEGERKIND ik

REAL x

INTEGER i

ik REALxKIND

or better

ik REALxKINDik

Retaining the representation precision is imp ortant note the dierence between the following two

assignments

INTEGER ia ib

Fortran Course Notes File CourseNotesps

Parameterised Intrinsic Typ es

REALKIND rk

rk rk REALiaKINDREALibKIND

and

rk rk REALiaREALib

In the second example the RHS op erand is less accurate than in the rst

Question Kind Functions and Available Representations

Write a program which quizzes a pro cessor and prints out the available kinds for the INTEGER

data typ e For each available kind give the maximum exp onent range that is supp orted Also give

the kind numb er corresp onding to the default INTEGER If an exp onent is to o largetobesupported



then SELECTED INT KIND will return You can assume that no numb er greater than will b e

supp orted

Expression Evaluation

If the two op erands of any intrinsic op eration have the same typ e and kind then the result also has

this typ e and kind If the kinds are dierent then the op erand with the lower range is promoted b efore

the op eration is p erformed

For example with the following declarations

INTEGERshort members attendees

INTEGERlong salaries costs

the expression

members attendees is of kind short

salaries costs is of kind long

members costs is also of kind long

Care must b e taken to ensure the LHS is able to hold numb ers returned by the RHS

The rules for normal typ e co ercion still hold in mixed typ e expressions INTEGERsare promoted to

REALs REALsto DOUBLE PRECISION and so on

Logical KIND Selection

LOGICAL objects follow exactly the same principle as for numeric data typ es Even though a LOGICAL

variable can only hold one of two values it can still b e represented in a numb er of dierent ways For

example

Septemb er University of Liverp o ol

Character KIND Selection

LOGICALKIND yorn TRUE

LOGICALKIND DIMENSION mask

IF yorn EQ LOGICALmaskKINDyorn

KIND could mean that only one byte is used to store each element of mask which would conserve

space Must refer to the compiler manual

LOGICAL(KIND=1) 1 byte

LOGICAL(KIND=4) 4 bytes

Figure Possible Sizes of Dierent Logical Kind Variables

LOGICAL KIND intrinsic however the KIND intrinsic can be used to inquire There is no SELECTED

ab out the representation and as demonstrated ab ove the LOGICAL intrinsic which has an optional

KIND argument can b e used to convert b etween representations

Character KIND Selection

Every compiler must supp ort at least one character set which must include all the Fortran characters

A compiler may also supp ort other character sets

INTEGER PARAMETER greek

CHARACTERKINDgreek zeus athena greek

CHARACTERKINDLEN mohammed arabic

Normal op erations apply individually but characters of dierent kinds cannot b e mixed

For example

print zeusathena OK

print mohammedathena illegal

print CHARICHARzeusgreek

Recall that CHAR gives the character in the given p osition in the collating sequence ICHAR and CHAR

must b e used when converting b etween character sets which means that only one character at a time

can b e converted

Literals can also b e sp ecied

greek

Notice how the kind is sp ecied rst this is so the compiler has advanced knowledge that some

funny characters are ab out to app ear and is able to warn the lexical analyser of this fact

Fortran Course Notes File CourseNotesps

Parameterised Intrinsic Typ es

Kinds and Pro cedure Arguments

Dummy and actual arguments must match exactly in kind typ e and rank this is how generic overloads

are resolved In the following example it is assumed that the kind parameters are initialised in a mo dule

good practice

SUBROUTINE subbieabc

USE kinddefs

REALr INTENTIN a c

REALr INTENTOUT b

Any dummy arguments to an invo cation of subbie must have matching arguments for example

USE kinddefs

REALr arg

REALr arg

CALL subbier arg arg

Using instead of r will not b e correct on all compilers The default kind always corresp onds

to a sp ecic kind Which kind it corresp onds to dep ends on the compiler this means that in the

example on one pro cessor may be identical and have identical kind value to r but on

r this would mean that the ab ove program would another pro cessor it may be equivalent to

compile OK sometimes the rst case and other times would fail owing to the pro cedure arguments

not matching in typ e rank and kind Atrulyportable program should NOT use intrinsic default typ es

Kinds and Generic Interfaces

Notethatifapro cedure is dened with an argument of default intrinsic typ e then it is also dened for

one parameterised instance of that typ e Consider

INTERFACE blob

MODULE PROCEDURE a

MODULE PROCEDURE b

END INTERFACE blob

CONTAINS

SUBROUTINE ai

INTEGERKIND INTENTIN i

END SUBROUTINE a

SUBROUTINE bi

INTEGERKIND INTENTIN i

END SUBROUTINE b

here b oth pro cedures have a unique interface as the kinds of the two dummy arguments are dierent

Consider

Septemb er University of Liverp o ol

Kinds and Generic Interfaces

INTERFACE blob

MODULE PROCEDURE a

MODULE PROCEDURE c

END INTERFACE blob

CONTAINS

SUBROUTINE ai

INTEGERKIND INTENTIN i

END SUBROUTINE a

SUBROUTINE ci

INTEGER INTENTIN i

END SUBROUTINE c

here if the default integer typ e corresp onds to a kind value of then the generic interfaces for blob

and blob are the same however if the default integer typ e corresp onds to a kind value of the

mo dule will be in error b ecause the overload set is non unique In summary default intrinsic typ es

should not app ear in generic interface sp ecications if any parameterised typ es app earasarguments

to other pro cedures in the overloads set This will ensure that the program is more p ortable

Question Dierent precision INTCOMPLEX

Enhance your Integer Complex Arithmetic mo dule by converting the co de to a portable sys

tem which can represent INTCOMPLEX values say in the range

int and Expressions containing INTCOMPLEXsmay involve integers of two kinds of INTEGERs short

 

long int which corresp ond to ranges of and resp ectively so the overload

set for numeric op erators must b e extended There is still only one kind of REAL and COMPLEX data

typ e

Mo dify your program so that Setup INTCOMPLEX is a generic function which constructs values for all

int and long int combinations of short

Demonstrate that the whole mo dule works by USEing it in the following test program which is avail

able by anonymous ftp from ftplivacuk in the directory pubfcoursesprogs lename

IntegerComplexProgramf

PROGRAM Testo

USE IntegerComplexArithmetic

IMPLICIT NONE

TYPEINTCOMPLEX var var ans

var

PRINT var

CALL PutINTCOMPLEXvar

var

PRINT var

CALL PutINTCOMPLEXvar

var

Fortran Course Notes File CourseNotesps

Parameterised Intrinsic Typ es

PRINT var

CALL PutINTCOMPLEXvar

var SetupINTCOMPLEX

var SetupINTCOMPLEX

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

ans var var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT Type in the two INTCOMPLEX components

CALL GetINTCOMPLEXvar

PRINT This is what was typed in

CALL PutINTCOMPLEXvar

PRINT Your number

ans var var

CALL PutINTCOMPLEXans

Intrinsics

PRINT REAL

Septemb er University of Liverp o ol

Kinds and Generic Interfaces

PRINT REALvar

PRINT INT

PRINT INTvar

PRINT AIMAG

PRINT AIMAGvar

PRINT CONJG

CALL PutINTCOMPLEXCONJGvar

PRINT ABS

PRINT ABSvar

REAL INTEGER OP INTCOMPLEX

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

var SetupINTCOMPLEX

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

Fortran Course Notes File CourseNotesps

Parameterised Intrinsic Typ es

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

INTCOMPLEX OP INTEGER REAL

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

Septemb er University of Liverp o ol

Kinds and Generic Interfaces

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

PRINT

ans var

CALL PutINTCOMPLEXans

var SetupINTCOMPLEXshortintlongint

PRINT var SetupINTCOMPLEXshortintlongint

CALL PutINTCOMPLEXvar

var SetupINTCOMPLEXshortintshortint

PRINT var SetupINTCOMPLEXshortintshortint

CALL PutINTCOMPLEXvar

var SetupINTCOMPLEXlongintshortint

PRINT var SetupINTCOMPLEXlongintshortint

CALL PutINTCOMPLEXvar

PRINT var SetupINTCOMPLEXlongintlongint

var SetupINTCOMPLEXlongintlongint

CALL PutINTCOMPLEXvar

PRINT shortint SetupINTCOMPLEXlongintlongint

ans shortint var

CALL PutINTCOMPLEXans

PRINT SetupINTCOMPLEXlongintlongint shortint

ans var shortint

CALL PutINTCOMPLEXans

PRINT SetupINTCOMPLEXlongintlongint shortint

ans var shortint

CALL PutINTCOMPLEXans

Fortran Course Notes File CourseNotesps

More Intrinsics

PRINT var longint

ans var longint

CALL PutINTCOMPLEXans

PRINT var SetupINTCOMPLEXlongintlongint

var SetupINTCOMPLEXlongintlongint

CALL PutINTCOMPLEXvar

PRINT longint SetupINTCOMPLEXlongintlongint

ans longint var

CALL PutINTCOMPLEXans

PRINT SetupINTCOMPLEXlongintlongint

ans var longint

CALL PutINTCOMPLEXans

END PROGRAM Testo

More Intrinsics

Bit Manipulation Intrinsic Functions

Summary

BTESTipos bit testing

IANDij AND

IBCLRipos clearbit

IBITSiposlen bit extraction

IBSETipos set bit

IEORij exclusive OR

IORij inclusive OR

ISHFTishft

ISHFTCishft circularshift

NOTi complement

MVBITSifrifrpos lenitoitopos move bits SUBROUTINE

Variables used as bit arguments must b e INTEGER valued The mo del for bit representation is that of

an integer so would have a bit representation of all s would have all zeros except fora in the

last p osition p osition zero The p ositions are numb ered from zero and go from right

to left just like regularbinary numb ers

The mo del for bit representation is that of an unsigned integer for example

The numb er of bits in a single variable dep ends on the compiler parameterised integers should b e

SIZE gives the numb er of bits in a variable used to x the numb er of bytes The intrinsic BIT

Here is a summary of the bit intrinsics and examples of their use assume that A has the value

and B the value in the following

BTEST bit value

Septemb er University of Liverp o ol

Array Construction Intrinsics

s-1 3 2 1 0 0.. 0000 value = 0

s-1 3210 00.. 1 0 1 value = 5

s-1 3210

00 0 11 value = 3

Figure Visualisation of Bit Variables

TRUE if the bit in p osition pos of INTEGER i is FALSE otherwise for example BTESTA

has value TRUE and BTESTA is FALSE

IAND bitwise AND

The twoarguments are INTEGER the result is an INTEGER obtained by doing a logical AND on

each bit of arguments for example IANDAB is

IBCLR bit clear

Set bit in p osition pos to for example IBCLRA is

IBITS extract sequence of bits

IBITSA is in binary or eectively

IBSET set bit

Set bit in p osition pos to for example IBSETA is

IEOR IOR bitwise OR exclusive or inclusive

For example IEORAB is and IORAB is

ISHFT ISHFTC logical and circular shift

Shift the bits shft p ositions left if shft is negative move bits to the right ISHFT lls

vacated p ositions by zeros ISHFTC wraps around for example ISHFTA is

ISHFTA is ISHFTCA is ISHFTCA

is

NOT compliment of whole word

NOTA is

MVBITS SUBROUTINE copy a sequence of bits b etween objects

For example MVBITSAB says move bits b eginning at p osition in A to B p osition

the bits are counted from right to left this gives B the value

Array Construction Intrinsics

There are four intrinsics in this class

Fortran Course Notes File CourseNotesps

More Intrinsics

MERGETSOURCEFSOURCEMASK

This function has the eect of merging twoarrays under a mask whether to include TSOURCE

or FSOURCE in the result dep ends on LOGICAL array MASK where it is TRUE the element from

TSOURCE is included otherwise the element from FSOURCE is used instead

SPREADSOURCEDIMNCOPIES

This function replicates an arraybyaddingNCOPIES along a dimension The eect is analogous

to taking a single page and replicating it to form a b o ok with multiple copies of the same page

The result has one more dimension that the source array SPREAD is useful during vectorisation

of DOlo ops

PACKSOURCEMASKVECTOR

This function packs an arbitrary dimensioned array into a onedimensional vector under a mask

PACK is useful forcompressing data

UNPACKVECTORMASKFIELD

This function unpacks a vector into an array under a mask UNPACK is a complementary function

to PACK and is therefore useful for uncompressing data

MERGE Intrinsic

MERGETSOURCEFSOURCEMASK

This function merges twoarrays under mask control TSOURCE FSOURCE and MASK must all conform

and the result is TSOURCE where MASK is TRUE and FSOURCE where it is FALSE

Consider

INTEGER DIMENSION TSOURCE FSOURCE

LOGICAL DIMENSION MASK

LOGICAL PARAMETER T TRUE

LOGICAL PARAMETER F FALSE

TSOURCE RESHAPE

FSOURCE RESHAPE

MASK RESHAPETFTFFT

Now as

T T F

MASK

F F T

the highlighted elements are selected from the two source arrays

TSOURCE

and

FSOURCE

Septemb er University of Liverp o ol

Array Construction Intrinsics

thus

MERGETSOURCE FSOURCE MASK

SPREAD Intrinsic

SPREADSOURCEDIMNCOPIES

This function replicates an arrayby adding NCOPIES of in the direction of a stated dimension

For example if A is then

SPREADA

As DIM the vector is spread along dimension the direction of a row

C B

C B

SPREADA

A

In this case DIM so the vector is spread along dimension the direction of a column

Agoodusefor this intrinsic is during vectorisation when say a doubly nested DO lo op is combining a

vector with each column of an array at the centre of the lo op the statement can b e rewritten as a D

array assignment by creating a copy of the vectorfor each column of the array For example

DO i

DO j

Aij Bi

END DO

END DO

can b e transformed to

A SPREADB

which exploits Fortran array syntax

PACK Intrinsic

PACKSOURCEMASKVECTOR

This function packs a arbitrary shap ed array into a onedimensional array under a mask VECTORif

present must b e D and must b e of same typ e and kind as SOURCE

Element i of the result is the element of SOURCE that corresp onds to the ith TRUE element of MASK

in array element order for i t where t is the numb er TRUE elements in MASK

Fortran Course Notes File CourseNotesps

More Intrinsics

If VECTOR is present the result size is that of VECTOR otherwise the result size is t unless MASK is

scalar with the value TRUE in which case the result size is the size of SOURCEIf VECTOR has size

nt element i of the result has the value VECTORifor i t n

For example if

T T F

MASK

F F T

and

A

then

PACKAMASK is

VECTOR is absent meaning that size of the result is the numb er of TRUE elements in MASK

The elements of A which corresp ond to the TRUE elements of MASK are

A

It can b e seen that the highlighted elements are taken from A in array element order and packed

into the result

PACKAMASK is

Here VECTOR is present so the result is of size The rst t elements of the results are as

before corresp onding to the TRUE elements of the mask The remaining values are taken

from VECTOR the th value of the result is the t th element of VECTOR Hence the result

PACKATRUE is

Here the mask is scalar so the rst elements are A and the rest from the end of VECTOR

UNPACK Intrinsic

UNPACKVECTORMASKFIELD

This function unpacks a vectorintoanarray under a mask FIELD must conform to MASK and and

must b e of same typ e and kind as VECTOR The result is the same shap e as MASK

If

FIELD

and

T T F

MASK

F F T

then

UNPACK MASK FIELD

Septemb er University of Liverp o ol

TRANSFER Intrinsic

The highlighted elements originate from VECTOR and corresp ond to the TRUE values of MASKthe

other values are from the corresp onding elements of FIELD

Also

UNPACK NOTMASK FIELD

again highlighted elements corresp ond to the TRUE values of NOTMASK the other values are from the

corresp onding elements of FIELD

TRANSFER Intrinsic

Most languages have a facility to change the typ e of an area of storage in Fortran p eople used

EQUIVALENCEFortran adds a dierent facility The TRANSFER intrinsic converts not co erces a

physical representation b etween data typ es it is a retyping facility The intrinsic takes the bit pattern

of the underlying representation and interprets it as a dierent typ e The intrinsic has the following

syntax

TRANSFERSOURCEMOLD

where SOURCE is the object to b e retyp ed and MOLD is an object of the target typ e For example

REAL DIMENSION A AA

INTEGER DIMENSION B

COMPLEX DIMENSION C

A TRANSFERB

AA TRANSFERB

C TRANSFERB

The same bit pattern is used foreachvariable typ e

INTEGER 000.. 11B

REAL 0 .. 0 1 0 1 A

REAL .. ..0101AA

COMPLEX0 .. 0 101 C

Figure Visualisation of the TRANSFER Intrinsic

Fortran Course Notes File CourseNotesps

More Intrinsics

the variable will take on the numb er dened by its bit pattern

The ab ove example highlights the following p oints

SOURCE can b e arrayor scalar valued of any typ e

MOLD can b e arrayorscalarvaluedofanytyp e and sp ecies the result typ e which is the same

shap e as SOURCE

in the example there is a big dierence b etween MOLD being array valued and scalar

the result of TRANSFERB is an array this is assigned elementbyelement to

A

the result of TRANSFERB is a scalar this scalar is assigned to every element of AA

The rst half of B bytes is interpreted as a REAL numb er

represents an array valued COMPLEX variable

Septemb er University of Liverp o ol

Mo dule

Odds and Ends

Input Output

Fortran has a wealth of IO to o much to cover here It has many statements for example READ

WRITE OPEN CLOSE REWIND and BACKSPACE built in to the language and also has very powerful

formatting commands forprettyprinting orformatted output

So far all examples have p erformed IO with a terminal Fortran allows a numb er of dierent

streams les to be connected to a program for both reading and writing In Fortran a le is

connected to a logical unit denoted by a numb er This numb er must b e p ositive and is often limited

to b e b etween and the exact numb er will b e given in the compiler manual Each logical unit

can have many prop erties for example

le the name of the le connected to the unit

The name is sp ecied in the OPEN statement

action read write read and write

If a le is op ened for one sort of action and another is attempted then an error will b e generated

for example it is not p ermissible to write to a le op ened solely for reading

status old new replace etc

similar to ab ove if we op en a new le but the le already exists then an error results

access metho d sequential direct

sequential isnormal access each write read causes a p ointer to move down the le

the next line which is written read app ears after the previous line

direct each line is accessed by a numb er a record numb er which must b e sp ecied in

the read write statement made

The maximum numb er of les which can b e op en at any one time will also b e sp ecied in the compiler

manual

OPEN Statement

The OPEN statement is used to connect a named le to a logical unit It is often p ossible to preconnect

alebefore the program has b egun if this is the case then there is no need foran OPEN statement

however there are many default IO settings many of which are pro cessor dep endent Its go o d practice

not to rely on defaults but to sp ecify exactly what is required in an explicit OPEN statement This will

make the program more p ortable

The syntax is

Input Output

OPENUNIT integer FILE lename ERR lab el

STATUS status ACCESS metho d ACTION mo de RECL intexpr

where

UNIT integer sp ecies a numeric reference for the named le The numb er must be one

that is not currently in use

FILE lename gives the lename to b e asso ciated with the logical unit The name must

match exactly with the actual le sometimes this means that the lename needs to contain a

sp ecic numb er of blanks

ERR lab el sp ecies a numeric lab el where control should b e transferred if there is an error

op ening the named le

STATUS status sp ecies the status of the named le the status may b e one of the following

OLD le exists

NEW le do es not exist

REPLACE le will b e overwritten

SCRATCH le is temp orary and will b e deleted when closed

UNKNOWN unknown

ACCESS metho d sp ecies the access metho d

DIRECT the le consists of tagged records accessed by an ID numb er in this case the

record length must be sp ecied RECL Individual records can be sp ecied and up dated

without altering the rest of the le

SEQUENTIAL the le is written read sequentially line by line

ACTION mo de sp ecies what can b e done to the le the mo de may b e one of the following

READ op en for reading

WRITEopenfor writing

READWRITE openfor b oth reading and writing

There are other less imp ortant sp eciers which are not covered here

There now follows an example of use

OPENFILEoutputdatERR STATUSREPLACE

ACCESSSEQUENTIALACTIONWRITE

Aleoutputdat is op ened for writing it is connected to logical unit numb er The le is accessed

on a line by line basis and already exists but is to b e replaced The lab el must p ertain to a valid

executable statement

OPENFILEinputdatERR STATUSOLD RECLiexp

ACCESSDIRECTACTIONREAD

Here a le is op ened for input only on unit The le is directly accessed and clearly already exists

Septemb er University of Liverp o ol

READ Statement

READ Statement

Syntax not all the sp eciers can b e used at the same time

READUNIT unit FMT format IOSTAT intvariable ERR lab el

END lab el EOR lab el ADVANCE advancemo de REC intexpr

SIZE numchars outputlist

where

UNIT unit is a valid logical unit numb er or for the default standard output if it is the

rst eld then the sp ecier is optional

FMT format is a string of formatting characters a valid FORMAT statement lab el ora for

free format If this is the second eld then the sp ecier is optional

IOSTAT intvariable sp ecies an integer variable to hold a return co de as usual zero means

no error

lab el in ERR is a valid lab el to where control jumps if there is a read error

lab el in END is a valid lab el to where control jumps if an endofle is encountered this can

only b e present in a READ statement

advancemo de sp ecies whether each READ should start a new record or not setting the

sp ecier to NO initiates nonadvancing IO The default is YES If nonadvancing IO is used

then the le must b e connected for sequential access and the format must b e explicitly stated

EOR will jump to the sp ecied lab el if an endofrecord is encountered This can only b e present

in a READ statement and only if ADVANCENO is also present

REC intexpr is the record numb er for direct access

the SIZE sp ecier is used in conjunction with an integer variable in this case nch The variable

will hold the numb er of characters read This can only b e present in a READ statement and only

if ADVANCENO is also present

Consider

READFMTFxRECiexp abc

here the record sp ecied by the integer iexp is read this record should contain real numb ers

separated by a space with column and decimal places The values will b e placed in a b and c

READAADVANCENOEORSIZEnch str

Since nonadvancing output has b een sp ecied the cursor will remain on the same line as the string is

read Under normal circumstances default advancing output the cursorwould b e p ositioned at the

start of the next line Note the explicit format descriptor SIZE reurns the length of the string and

EOR sp ecies an destination if an endofrecord is encountered

Fortran Course Notes File CourseNotesps

Input Output

WRITE Statement

READ and WRITE can b e interchanged in the following not all the sp eciers can b e used at the same

time

WRITEUNIT unit FMT format IOSTAT intvariable ERR lab el

ADVANCE advancemo de REC intexpr outputlist

where

UNIT unit is a valid logical unit numb er or for the default standard output If it is the

rst eld then the sp ecier is optional

FMT format is a string of formatting characters a valid FORMAT statement lab el ora for

free format If this is the second eld then the sp ecier is optional

IOSTAT intvariable sp ecies an integer variable to hold a return co de as usual zero means

no error

lab el in ERR is a valid lab el to where control jumps if there is an WRITE error

ADVANCE advancemo de sp ecies whether each WRITE should start a new record or not

setting the sp ecier advancemo de to NO initiates nonadvancing IO The default is

YES If nonadvancing IO is used then the le must b e connected for sequential access and

the format must b e explicitly stated

REC intexpr is the record numb er for direct access

Consider

WRITEFMTIIOSTATistatERR ENDEOR ival

here I means INTEGER with digits the lab els and are statements where control

can jump on an I O exception ival is an INTEGER variable whose value is written out

WRITEAADVANCENO Input

Since nonadvancing output has b een sp ecied the cursor will remain on the same line as the string

Input under normal circumstances default advancing output the cursorwould b e p ositioned

at the start of the next line Note the explicit format descriptor

See later foramore detailed explanation of the format edit descriptors

FORMAT Statement FMT Sp ecier

The FMT sp ecier in a READ or WRITE statement can give either a line numb er of a FORMAT statement

an actual format string ora

Consider

WRITEFMTXIXname Aijstr

Septemb er University of Liverp o ol

Edit Descriptors

This writes out to the le outputdat the three variables i j and str according to the sp ecied

format spaces X integer valued ob jects of digits with no gaps I one space X

the string name and then letters of a character ob ject A The variables are taken from the

IO list at the end of the line Note the double single quotes escap ed quote around name A single

could have b een used here instead

Consider

READ xy

This reads two values from inputdat using free format and assigns the values to x and y

Further consider

WRITEFMT ab

FORMATvalsFX

The WRITE statement uses the format sp ecied in statement to write to the standard output channel

The format is instances of a real valued ob ject spanning columns with an accuracy of

decimal places F followed bytwo spaces X

Given

WRITEFMT

WRITEFMTXIXname A Philip

FORMATvalsFX

the following is written

name Philip

Edit Descriptors

Fortran contains a large numb er of output edit descriptors which means that very complex IO patterns

can be sp ecied it is only intended that a summary be presented here Any go o d textb o ok will

elab orate

Editor Meaning

Iw w chars of integer data

Fwd w chars of real data d dec pl

Ewd w chars of real data d dec pl

Lw w chars of logical data

Aw w chars of CHARACTER data

nX skip n chars n spaces

Where

w determines the numb er of the total numb er of characters column width that the data spans

on output if there are insucient columns for the data then numeric data will not cannot b e

printed CHARACTER data will b e truncated

Fortran Course Notes File CourseNotesps

Input Output

d sp ecies the numb er of decimal places that the data contains and is contained in the total

numb er of characters The numb er will b e rounded not truncated to the desired accuracy

and

I sp ecies that the data is of INTEGER typ e

E writes REAL using exp onent form E

F uses decimal p oint form

for F and E the sign is included in the total numb er of characters bydefaultplussignsare not

output

L sp ecies LOGICAL data TRUE and FALSE are output as a single character T or FIf w is

greater that one them the single character is padded to the left with blanks

A sp ecies CHARACTER data If w is sp ecied strings which are to o long more than w characters

will b e truncated If w is not sp ecied any length of string is appropriate

X skips the sp ecied numb er of characters n blanks are output

Descriptors or groups of descriptors can b e rep eated byprexing orparenthesesing and prexing with

the numb er of rep eats for example I can b e rep eated twice by sp ecifying I and IX can be

rep eated twice by sp ecifying IX

Many of the ab ove edit descriptors can b e demonstrated

WRITEFMTXIXname AFXE

ABCDEFGHI

gives

bbbbbbbnamebABCDbbbbbbbbE

where the b signies a blank In the ab ove example the rst INTEGER is unable to b e written as the

numb er is to o long and the last REAL numb er is rounded to t into the spaces available The string is

truncated to t into the space available A READ statement could use the same format editor

Typ e co ercion is not p erformed so INTEGERs cannot b e written out as REALs

Other IO Statements

CLOSE unattaches the unit numb er sp ecied in the statement This should always b e used to

add an end of le mark at the closure p oint It is an error to close a le that is not op en

REWIND simply puts the le p ointer back to the start

BACKSPACE moves the le p ointer is moved back one record however it often puts the le

p ointer back to the start and then fast forwards

ENDFILE forces an endofle to b e written into the le but the le remains op en

Septemb er University of Liverp o ol

Other IO Statements

The ab ove statements have other sp eciers such as IOSTAT

For example

REWIND UNIT

BACKSPACE UNIT

ENDFILE

CLOSE IOSTATival

Question File IO

Write a program to op en a new sequential le on unit calledmarksdat The program should

then read a students name followed by hisher marks for four exams from the keyb oard the default

unit and write these to the le on a single line Rep eat the readwrite pro cess until a student with

the name END is entered Close the output le

Question Formatted IO

Given the statement

READFAL ACL

what would the variables A a real C a character of length L a logical contain when given the

following input Note b signied a blank space

bbbbbbNObTRUE

bbbbbbYbbFbbbbb

bbbbbbbbbbbbbT

bbbbbbbbbbbbbbbbbbF

Question Formatted IO

Give the formats which would b e suitable for use with the statements

REAL A

CHARACTERLEN B

INTEGER C

READFORM ABC

if the record to b e read is b is blank

bbbbbINTRODUCTORYb

and values to b e assigned to A B and C are given in the following table

Fortran Course Notes File CourseNotesps

External Pro cedures

A B C

INTRODUCTORY

DUCT

TROD

TORY

Question More Formatted IO

Given that A is an array declared with the statement

INTEGER DIMENSION A

give a formatted input statement which will read in the values to A to Aetc from the

following records

Question Formatted File IO

A le personneldat contains records of peoples name up to characters age digit in

teger height in metres to the nearest centimetre telephone numb er digit integer Write a

program to read the le and print out the details in the following format

Height

Name Age metres Tel No

Bloggs J G

Clinton P J

etc

Question More File IO

Write a program to read the le pro duced by the exam marks program and to print a list of students

and their average marks

External Pro cedures

Fortran allows a class of pro cedure that is not contained within a PROGRAM or a MODULE an

EXTERNAL pro cedure

This is the old Fortran style of programming and is more clumsy than the Fortran way

Dierences

Septemb er University of Liverp o ol

External Subroutine Syntax

they may b e compiled separately

may need an explicit INTERFACE to b e supplied to the calling program

can b e used as arguments in addition to intrinsics

should contain the IMPLICIT NONE sp ecier

External Subroutine Syntax

Syntax of a nonrecursive subroutine declaration

SUBROUTINE pro cname dummy args

declaration of dummy args

declaration of lo cal objects

executable stmts

CONTAINS

internal pro cedure denitions

END SUBROUTINE pro cname

SUBROUTINEsmay contain internal pro cedures but only if they themselves are not already internal

SUBROUTINE Ext_1(...) ! ... CONTAINS ! Internal Procs SUBROUTINE Int_1(...) ! Executable stmts END SUBROUTINE Int_1 ! etc. FUNCTION Int_n(...) ! Executable stmts END FUNCTION Int_n END SUBROUTINE Ext_1

SUBROUTINE Ext_2(...) ! etc

END SUBROUTINE Ext_2

Figure Schematic Diagram of a Subroutine

Fortran Course Notes File CourseNotesps

External Pro cedures

The structure is similar to that of the main PROGRAM unit except a SUBROUTINE can b e parameterised

with arguments and the typ e and kind of these must b e sp ecied in the declarations section A SUB

ROUTINE may include calls to other program units either internal external or visible by USE asso ciation

dened in a mo dule and USEd in the pro cedure

External Subroutine Example

An external pro cedure may invoke a further external pro cedure

SUBROUTINE subabc

IMPLICIT NONE

EXTERNAL sumsq

REAL a b c s

CALL sumsqabcs

END SUBROUTINE sub

calls

SUBROUTINE sumsqaabbccss

IMPLICIT NONE

REAL INTENTIN aa bb cc

REAL INTENTOUT ss

ss aaaa bbbb cccc

END SUBROUTINE sumsq

The principle is the same as for calling an internal pro cedure except that

whereas an internal pro cedure has access to the hosts declarations and so inherits amongst

other things the IMPLICIT NONE external pro cedures do not An IMPLICIT NONE is needed in

every external pro cedure

the external pro cedure should b e declared in an EXTERNAL statement This is optional but is

go o d practise

External Function Syntax

Syntax of a nonrecursive function

prex FUNCTION pro cname dummy args

declaration of dummy args

declaration of lo cal objects

executable stmts assignment of result

CONTAINS

internal pro cedure denitions

END FUNCTION pro cname

Septemb er University of Liverp o ol

External Function Syntax

here prex sp ecies the result typ e or

FUNCTION pro cname dummy args

declaration of dummy args

declaration of pro cname typ e

declaration of lo cal objects

executable stmts assignment of result

CONTAINS

internal pro cedure denitions

END FUNCTION pro cname

Functions are very similar to subroutines except that a function should have a typ e sp ecier which

denes the typ e of the result The typ e of the function result can either b e given as a prex to the

function name or alternatively b e given in the declarations area of the co de bypreceding the function

name with no arguments orparentheses byatyp e sp ecier It is a matter of p ersonal taste which

metho d is adopted For example

INTEGER FUNCTION largestijk

IMPLICIT NONE

is equivalent to

FUNCTION largestijk

IMPLICIT NONE

INTEGER largest

The function name pro cname is the result variable so a function must contain a statement which

assigns a value to this name a routine without one is an error

The typ e of an external function must be given in the calling program unit It is go o d practise to

attribute this declaration with the EXTERNAL attribute A valid declaration in the calling program unit

might b e

INTEGER EXTERNAL largest

Function Example

A function is invoked by its app earance in an expression at the place where its result value is needed

total total largestabc

The function is dened as follows

INTEGER FUNCTION largestijk

INTEGER i j k

largest i

IF j GT largest largest j

IF k GT largest largest k

END FUNCTION largest

Fortran Course Notes File CourseNotesps

External Pro cedures

or equivalently as

FUNCTION largestijk

INTEGER i j k

INTEGER largest

END FUNCTION largest

The largest value of i j and k will b e substituted at the place where the function call is made As

with subroutines the dummy and actual arguments must match in typ e kind and rank

More than one function or the same function more than once may b e invoked in a single statement

For example

rezzy funkyabc funkyabc

Care must b e taken that the order of execution will not alter the result aside from op eratorprecedence

the order of evaluation of a statement in a Fortran program is undened It is not sp ecied whether

funky or funky is evaluated rst they could even b e executed in parallel

If a function invo cation has sideeects and it is called twice in the same statement then problems may

o ccur To safeguard against this a function invo cation should not assign to its arguments mo dify any

global variables orperform IO A function which ob eys these restrictions is termed PURE The PURE

sp ecier will b e part of the Fortran language

Pro cedure Interfaces

Fortran has intro duced a new feature whereby it is p ossible often essential and wholly desirable to

provide an explicit interface for an external pro cedure Such an interface provides the compiler with all

the information it needs to allowittoitmake consistency checks and ensure that enough information

is communicated to pro cedures at runtime

Consider the following pro cedure

SUBROUTINE expsum n k x sum in interface

USE KINDVALSONLY long

IMPLICIT NONE

INTEGER INTENTIN n in interface

REALlong INTENTIN kx in interface

REALlong INTENTOUT sum in interface

REALlong cooltime

sum

DO i n

sum sum expikx

END DO

END SUBROUTINE expsum in interface

The explicit INTERFACE for this routine is

INTERFACE

SUBROUTINE expsum n k x sum

Septemb er University of Liverp o ol

Pro cedure Interfaces

USE KINDVALSONLY long

INTEGER n

REALlong INTENTIN kx

REALlong INTENTOUT sum

END SUBROUTINE expsum

END INTERFACE

An interface declaration which is initiated with the INTERFACE statement and terminated by END

INTERFACE gives the characteristics attributes of both the dummy arguments for example the

name typ e kind and rank and the pro cedure for example name class and typ e for functions The

INTENT attribute should also b e given this has not b een covered yet see Section for details

The USE statement is necessary so that the meaning of long can b e established An interface cannot

b e used forapro cedure sp ecied in an EXTERNAL statement and viceversa

The declaration can be thought of as b eing the whole pro cedure without the lo cal declarations for

example cool time and executable co de If this interface is included in the declarations part of

a program unit which calls expsum then the interface is said to be explicit Clearly an interface

declaration must match the pro cedure that it refers to

It is is generally a go o d idea to make all interfaces explicit

An interface is only relevant for external pro cedures the interface to an internal pro cedure is always

visible as it is already contained within the host Interfaces to intrinsic pro cedures are also explicit

within the language

An interface only contains

the SUBROUTINE or FUNCTION header

if not included in the header the FUNCTION typ e

declarations of the dummy arguments including attributes

the END SUBROUTINE or END FUNCTION statement

Interfaces are only ever needed for EXTERNAL pro cedures

Question Interfaces

What is the interface of the following pro cedure

SUBROUTINE SGETRIFA IPIV INFO

USE LAPRECISION ONLYWP

IMPLICIT NONE

REALKINDWP INTENTINOUT DIMENSION A

REALKINDWP ALLOCATABLE DIMENSION WORK

INTEGER INTENTIN DIMENSION IPIV

INTEGER INTENTOUT INFO

INTEGER N

INTEGER ILAENV

EXTERNAL ILAENV

INTRINSIC MIN MATMUL

INFO

Fortran Course Notes File CourseNotesps

External Pro cedures

N SIZEA

IF SIZEA N THEN

INFO

ELSE IF SIZEIPIV N THEN

INFO

ENDIF

IF NEQ RETURN

END SUBROUTINE SGETRIF

Interface Example

The following program includes an explicit interface

PROGRAM interfaceexample

IMPLICIT NONE

INTERFACE

SUBROUTINE expsumNKXsum

INTEGER INTENTIN N

REAL INTENTIN KX

REAL INTENTOUT sum

END SUBROUTINE expsum

END INTERFACE

REAL sum

CALL expsumsum

END PROGRAM interfaceexample

The ab ove interface includes information ab out the numb er typ e kind and rank of the dummy argu

ments of the pro cedure expsum

Using an INTERFACE provides for b etter optimisation and typ e checking and allows separate compila

tion to b e p erformed

Required Interfaces

Explicit interfaces are mandatory if an EXTERNAL pro cedure

has dummy arguments that are assumedshap e arrays p ointers ortargets

This is so the compiler can gure out what information needs to be passed to the pro cedure

for example the rank typ e and b ounds of an array whose corresp onding dummy argument is an

assumedshap e array see Section or the typ es and attributes of p ointers ortargets

has OPTIONAL arguments

The compiler needs to knows the names of the arguments so it can gure out the correct

asso ciation when any of the optional arguments are missing

is an arrayor p ointer valued result functions

The compiler needs to know to pass back the function result in a dierent form from usual

Septemb er University of Liverp o ol

Pro cedure Arguments

contains an inherited LEN length sp ecier character functions

The compiler needs to know to pass string length information to and from the pro cedure

and when the reference

has a keyword argument

Same reasons as optional case ab ove

is a dened assignment

Extra information is required

is a call to the generic name

Extra information is required

is a call to a dened op erator functions

Extra information is required

Recall that a pro cedure cannot app earbothinanINTERFACE blo ck and in an EXTERNAL statement in

the same scoping unit

Question Simple External Pro cedure

Write a program that lls an array of a user sp ecied size with random real numb ers in the range

This program should then call an EXTERNAL pro cedure which rep orts on the frequency of numb ers

less than in this array Use assumedshap e arrays in the pro cedure You may nd the COUNT

intrinsic useful in this question

Pro cedure Arguments

If an external pro cedure is to b e used as an argument it needs to b e declared at the call site with an

INTRINSIC or EXTERNAL attribute

INTRINSIC attribute for inbuilt external pro cedures

EXTERNAL attribute for external or dummy pro cedures

Internal pro cedures are forbidden to app earasarguments

The INTRINSIC Attribute

A name with the intrinsic attribute represents an intrinsic pro cedure and allows it to b e used as an

actual argument Note the sp ecic not generic pro cedure name should be used Many intrinsic

functions can b e referred to b e two dierent names the sp ecic and the generic names The Fortran

intrinsic functions are multiply dened one foreachargument of a dierent intrinsic typ e for example

REAL INTEGER and COMPLEX Each of these dierent functions has a dierent name for example

ABS IABS and CABS corresp onding to the dierent argument typ es All of these sp ecic names also

b elongs to a generic name class in this case ABSand can b e accessed by using the generic name

instead of the sp ecic name The compiler is able to lo ok at the typ e of the argument and decide which

Fortran Course Notes File CourseNotesps

External Pro cedures

sp ecic function should b e referenced this is called generic resolution Ifapro cedure is to b e passed

as an actual pro cedure argument the sp ecic name must b e used b ecause the pro cedure reference will

not have any arguments at the p oint where it is passed so the generic reference will not b e able to b e

resolved Apro cedure maybeattributedaspart of a typ e declaration orinanINTRINSIC statement

For example

INTRINSIC MVBITS

REAL INTRINSIC ASIN

declares ASIN to b e an intrinsic function and will allowittobeusedasanactualargument INTRIN

SIC and EXTERNAL statements cannot currently contain the separator This is a language anomily

and will b e removed in Fortran

The following pro cedure call would b e valid

CALL subboMVBITS ASIN

where the denition of subbo is as follows

SUBROUTINE subbosubfun

IMPLICIT NONE

EXTERNAL sub

REAL EXTERNAL fun

PRINT fun

CALL sub

END SUBROUTINE subbo

It can be seen that the dummy pro cedure arguments can be invoked in the same way as regular

pro cedures Note how dummy pro cedure argument are always declared as EXTERNAL even if they are

intrinsic functions This is b ecause in the ab ove case fun is not the name of an intrinsic pro cedure

The EXTERNAL Attribute

A name with the external attribute represents an external pro cedure or a dummy pro cedure and allows

it to be used as an actual argument Note the sp ecic not generic pro cedure name should be

used As Fortran allows EXTERNAL user dened pro cedures to have the same names as INTRIN

SIC pro cedures it is often necessary to b e able to dierentiate b etween two references If an intrinsic

pro cedure name is used in an EXTERNAL statement then only the external pro cedure is visible in that

scop e the intrinsic b ecomes unavailable Apro cedure may b e attributed as part of a typ e declaration

orinanEXTERNAL statement

For example

EXTERNAL MySubby

INTEGER EXTERNAL MyFunky

INTEGER EXTERNAL IABS

Septemb er University of Liverp o ol

Pro cedure Arguments

My Subby and My Funky are declared to be a user written external subroutine and integer function

resp ectively Both these pro cedures can nowbe used as actual arguments in pro cedure invo cations

IABS is also declared to b e a userwritten external function and will also b e allowed to app ear an actual

argument The intrinsic function IABS will b ecome unavailable in the current scoping unit If an

intrinsic pro cedure name is used in an EXTERNAL statement then only the external pro cedure of that

name is visible in that scop e the intrinsic b ecomes unavailable

Pro cedure Arguments Example

The following example demonstrates the use of pro cedures as arguments

PROGRAM main

IMPLICIT NONE

INTRINSIC ASIN

REAL EXTERNAL mysin

EXTERNAL diffo

CALL subbyASINmysindiffoSIN

END PROGRAM

SUBROUTINE subbyfunfunsubx

IMPLICIT NONE

REAL INTENTIN x

REAL EXTERNAL fun fun

EXTERNAL sub

PRINT funx funx

CALL subfunxfunx

END SUBROUTINE subby

SUBROUTINE diffoyfx

IMPLICIT NONE

REAL INTENTIN xy

REAL EXTERNAL f

print Diffo yfx

END SUBROUTINE diffo

REAL FUNCTION mysinx

END FUNCTION mysin

It can b e seen that when a pro cedure is passed as an actual argument it is merely passed by referencing

its name if it is a function which is supplied with arguments for example SIN then it will b e

evaluated b efore the call is made

The ab ove example raises a few p oints

INTRINSIC ASIN sp ecies that ASIN refers to the Fortran intrinsic function and allows it to

b e used as an actual argument which corresp onds to a dummy pro cedure ASIN is the sp ecic

name of the generic function SIN

REAL EXTERNAL my sin declares my sin to b e a userdened real valued function which

can b e used as an actual argument which corresp onds to a dummy pro cedure

Fortran Course Notes File CourseNotesps

Object Initialisation

EXTERNAL diffo declares diffo to b e an external subroutine and allows it to b e used as an

actual argument which corresp onds to a dummy pro cedure

diffo is argument asso ciated with sub when sub is invoked it is really diffo that is b eing

invoked

when sub diffo is called the rst argument is evaluated funxand the second and

third arguments are passed across

dummy and actual pro cedure arguments must match in typ e kind rank and numb er of argu

ments

some intrinsic functions cannot b e used as dummy pro cedure arguments these include LLT and

typ e conversion functions such as REAL see the Fortran standard for a full list

must always use the sp ecic name of any intrinsic pro cedure ie must use ASIN and not SIN

Question Functions as dummy arguments

Write a subroutine that accepts a function with one real argument user dened or intrinsic a

start value i end value i and stride i and prints out the value of the function at each p oint dened

by the sequence ii ii i Demonstrate its functionality by pro ducing tables for two

intrinsic and two user dened functions

Object Initialisation

DATA Statement

In Fortran the main use of the DATA statement is to allow initialisation of sections of arrays where

the facilities of array constructors and assignment in the array declaration make this dicult A DATA

statement can b e placed anywhere in the relevant program unit but its is common practice to place it

amongst the declarations It is executed once conceptually in parallel on the rst invo cation of the

pro cedure just b efore the rst executable statement

DATA statements are go o d for initialising o dd shap ed sections of arrays

The syntax is as follows

DATA varlist datalist varnlist datanlist

The numb er of constants in each datalist must be equal to the numb er of variables array

elements in the corresp onding varlist Each datalist can only contain constants or structure

userdened typ e constructors plus implieddo lo op sp eciers and rep etition sp eciers

Any object initialised by the DATA statement has the SAVE attribute

DATA Statement Example

As an example consider initialising a array with all the edge values equal to and with

the rest of the array zero This is very hard to do in an initialisation statement it can b e done using a

Septemb er University of Liverp o ol

Data Statement Implied DO Lo op

RESHAPE and a series of implieddo lo ops but the whole array must b e initialised in one go The DATA

statement allows this op eration to b e spread over a numb er of lines

REAL matrix

DATA matrix top row

DATA matrix bot row

DATA matrix left col

DATA matrix right col

DATA matrix interior

The expression means o ccurrences of the is the rep etition sp ecier and the

numb er of rep eats must be a scalar integer literal not a variable In this context it cannot be

confused with the multiplication op erator b ecause such op erators are not allowed in a DATA statement

A list of comma separated initialisations is also allowed for example

DATA matrix top row

A further example shows how initialisation in an assignment statement when it can b e done is neater

than a DATA statement

INTEGER countIJ

REAL inc max min

CHARACTERLEN light

LOGICAL red blue green

DATA count I J

DATA inc max minE E E

DATA lightAmber

DATA redTRUE blue greenFALSEFALSE

is the same as

INTEGER count I J

REAL incE maxE minE

CHARACTERLEN lightAmber

LOGICAL redTRUE blueFALSE greenFALSE

Data Statement Implied DO Lo op

In a DATA statement the varlist may b e sp ecied by means of an impliedDO Initialising a matrix

to have a given constant value say on the diagonal and zero everywhere else is simple to do using

this metho d

The object section can b e sp ecied by a tight lo op which is more expressive than array syntax would

allow

REAL diag

DATA diagii i sets diagonal elements

DATA diagijdiagjijii

sets the upper and lower triangles

Fortran Course Notes File CourseNotesps

Handling Exceptions

The rst DATA statement containing the following impliedDO diagii i has the same

eect as if diagii were nested in a DO i DOlo op The second contains a nested

impliedDO and b ehaves as if the second lo op expression i is the outermost DO of a set of two nested

lo ops in other words its is like

DO i

DO ji

diagij

diagji

END DO

END DO

so the j lo op varies the quickest meaning that the following elements are selected in the given order

diag diag diag diag

diag diag

Handling Exceptions

GOTO Statement

The GOTO statement

is a p owerful but undisciplined branching statement

can b e used to create jumps to almost anywhere in a program unit

can b e dangerous

can lead to unstructured co de logical spaghetti

is very useful in exceptional circumstances such as jumping out of heavily nested structures

The basic syntax is

GOTO numericlab el

The lab el must exist be in the same scoping unit as the statement and be executable This lab el

cannot b e a construct name

GOTO should not be used for simulating other available control structure such as lo ops use the

purp osedesigned syntax

GOTO Statement Example

Consider the following example of an atro cious use of the GOTO statement

Septemb er University of Liverp o ol

RETURN and STOP Statements

GOTO jump forward

CONTINUE

i i

IF i eq GOTO

PRINT Line

j j loop

IF j ne GOTO

GOTO jump back

CONTINUE

The co de fragment demonstrates forward and backward transfer of control and the simulation of a

lo op The whole example could b e b e rewritten in a far neater and structured way

The b est use of GOTO statements is in jumping out of a heavily nested structure when an unexp ected

event o ccurs such as a p otential divide by zero

RETURN and STOP Statements

The RETURN and STOP statements can b e used to program exceptions in pro cedures

RETURN transfers control to the last line of the pro cedure and then back to the calling program unit

and serves as a quick exit from the middle of a pro cedure It is esp ecially useful when things have gone

wrong and the pro cedure execution needs to b e ab orted

STOP causes the program to terminate immediately A string or numb er may b e written to the standard

output when this happ ens STOP is again useful for exceptions however this statement could cause

great problems on a distributed memory machine if some pro cessors just stop without cleaning up

STOP is often used as status rep ort which comments on the success or failure of a program execution

For example the following will exit from the subroutine if there is insucient space to allo cate the

array A

SUBROUTINE subierror

INTEGER INTENTOUT ierror

ALLOCATEASTATierror

IF ierror THEN

PRINT memory fault

RETURN

END IF

END SUBROUTINE

The same eect as that of the RETURN statement could be obtained by putting a lab el on the END

statement and using a GOTO statement to pass control directly to this lab el

In the ab ove example STOP could b e used instead of RETURN

STOP stopped in sub

the string is optional or can b e a literal integer constant of up to digits It is output up on execution

of STOP at which time execution of the program terminates

Fortran Course Notes File CourseNotesps

Fortran

Fortran

Fortran will b e the new Fortran Standard It will include the following

FORALL statement and construct

FORALLinjm

Aij ij

END FORALL

simultaneously assigns ij to each arrayelementAij

nested WHERE constructs

user dened ELEMENTAL pro cedures this will allow the ELEMENTAL keyword to be added to

pro cedure denitions

PURE pro cedures this will allowthe PURE keyword to b e added to pro cedure denitions and states

that the pro cedure is sideeect free ELEMENTAL pro cedures are PURE

userdened functions in initialisation expressions

automatic deallo cation of arraysnoneedtodeallocatearrays b efore leaving a pro cedure

improved object initialisation p ointers can b e initialised to b e disasso ciated

remove conicts with IEC IEEE oating p oint arithmetic standard

more obsolescent features for example xed source form assumed sized arrays CHARACTER

len declarations statement functions

language tidyups and ambiguities mistakes

The full content of Fortran is not yet nalised and may change

Rationale by Craig Dedo

The reasons for the changes are laid out b elow

FORALL

The FORALL statement and construct and PURE pro cedures were added to FortrantoallowFortran

programs to execute eciently in parallel on multipro cessor systems These features allow the majority

of programs co ded in High Performance Fortran HPF to run on a standard conforming Fortran

pro cessor with little change Adding these features to Fortran do es not imply that a particular

Fortran pro cessor is multipro cessor

The purp ose of the FORALL statement and construct is to provide a convenient syntax for simultaneous

assignments to large groups of array elements The multiple assignment functionalityitprovides is very

similar to that provided by the array assignment statement and the WHERE construct in Fortran

FORALL diers from these constructs in its syntax which is intended to b e more suggestive of lo cal

op erations on each element of an array and in its generality which allows a larger class of array sections

Septemb er University of Liverp o ol

Rationale by Craig Dedo

to b e sp ecied In addition a FORALL may invoke userdened functions on the elements of an array

simulating Fortran elemental function invo cation alb eit with a dierent syntax

FORALL is not intended to b e a completely general parallel construct for example it do es not express

pip elined computations or multipleinstruction multipledata MIMD computation well This was

an explicit design decision made in order to simplify the construct and promote agreement on the

statements

Nested WHERE Construct

The WHERE construct was extended in order to provide for syntactic regularity with the FORALL con

struct The FORALL construct allows for nested FORALL constructs

Early implementation of some High Performance Fortran HPF pro cessors included the nested WHERE

construct Use of these pro cessors showed that the feature provided real value to customers

PURE Pro cedures

The purp ose of PURE pro cedures is to allow a pro cessor to know when it is safe to implement a

sectionofcodeasa parallel op eration The freedom from side eects of a pure function assists the

ecient implementation of concurrent execution and allows the function to b e invoked concurrently in

a FORALL without such undesirable consequences as nondeterminism It also forces some error checking

on functions used in a FORALL construct

Elemental Pro cedures

ELEMENTAL pro cedures provide the programmer with more powerful expressive capabilities and the

pro cessor with additional opp ortunities for ecient parallelisation

Extending the concept of elemental pro cedures from intrinsic to userdened pro cedures is very much

analogous to but simpler than extending the concept of generic pro cedures from intrinsic to user

dened pro cedures Generic pro cedures were intro duced for intrinsic pro cedures in Fortran and

extended to userdened pro cedures in Fortran Elemental pro cedures were intro duced for intrinsic

pro cedures in Fortran and b ecause of their usefulness in parallel pro cessing it is quite natural that

they b e extended to userdened pro cedures in Fortran ELEMENTAL pro cedures are PURE

Improved Initialisations

A signicant numb er of useful applications will b e facilitated by the ability to p erform more complicated

calculations when sp ecifying data objects Allowing a restricted class of nonintrinsic functions in certain

sp ecication expressions achieves this goal

Automatic Deallo cation

Automatic deallo cation of allo catable arrays provides a more convenient and less errorprone metho d of

avoiding memory leaks by removing the burden of manual storage deallo cation for allo catable arrays

Fortran Course Notes File CourseNotesps

Fortran

The undened allo cation status of Fortran meant that an allo catable array could easily get into a

state where it could not b e further used in any way whatso ever It could not b e allo cated deallo cated

referenced or dened The result was undened if the arraywas used as the argument to the ALLOCATED

function Removal of this status provides the user with a safe wayofhandlingunSAVEd allo catable

arrays and p ermits use of the ALLOCATED intrinsic function to discover the current allo cation status of

the array at any time

New Initialisation Features

The prime motivation for adding a means to sp ecify default initialisation for objects of derived typ e is

a desire to eliminate memory leakage ie situations in which allo cated memory b ecomes inaccessible

This can occur in applications which manipulate objects of derived typ e with p ointer comp onents

Most memory leakage can b e avoided if it is p ossible to sp ecify that p ointers b e created with an initial

status of disasso ciated

This standard provides a new intrinsic function NULL with a single optional argument NULL allows

the initial status of a p ointer to b e sp ecied as disasso ciated in declarations structure constructors or

typ e denitions

Several alternatives were considered and rejected foravariety of reasons Most of these reasons involve

the problem of disambiguating references to generic pro cedures ie when a program invokes a generic

pro cedure which sp ecic pro cedure is supp osed to b e invoked Completely dening a p ointer object

b efore using it do es not help with the disambiguation problem Creating a NULL constant do es not

provide any way to sp ecify the typ e and typ e parameters of the p ointer that is returned A NULL

function with a MOLD argument provides these needed capabilities

This language extension do es not completely solve the memory leakage problem for that an automatic

destructor is needed which would b e invoked for lo cal p ointers and structures with p ointer comp onents

when the pro cedure in which they are created terminates Such a facility is not included in this standard

it could b e provided automatically byapro cessor that strove to conserve allo catable memory

Automatic p ointer destructors were not included in this standard b ecause the consequences of inac

cessible p ointers are not as serious as they are with allo catable arrays which b ecome inaccessible If a

lo cal unSAVEd p ointer is not deallo cated and the program exits the pro cedure in which it is dened

the storage is not recoverable but the p ointer is reusable

For reasons of determinacy and p ortability an object for which default initialisation is sp ecied is not

allowed to app earina DATA statement In traditional implementations a compiler passes initialisation

information for nondynamic variables to a loader which is frequently designed to handle object co de

from several dierent languages It would b e dicult to guarantee that initialisation in a DATA statement

would override the default initialisation sp ecied in a typ e denition

Remove Conicts With IEC

Edits to sections and removed conicts in Fortran with the IEC IEEE

standard Previous Fortran standards app eared to prohibit certain numeric values and numeric op era

tions which were valid when using IEC arithmetic Fortran requires that the value of a p ositive

zero b e the same as that of a negative zero whereas IEC requires that they b e dierent Fortran

prohibits any mathematically invalid op eration whereas IEC requires such op erations to pro duce

Inf Inf or NaNs

These conicts were removed to allowpro cessors the ability to implement more of the IEC arithmetic

mo del without violating the Fortran standard

Septemb er University of Liverp o ol

Rationale by Craig Dedo

Minimum Width Editing

Certain edit descriptors have b een extended to allowformatted output of numeric values while minimis

ing the amount of white space pro duced This extension p ermits more information to b e presented

on a limited width display device eg terminal without concern ab out overowing a user sp ecied

eld width Allowing a zero eld width to be sp ecied for the I B O Z and F edit descriptors

provides this functionality A eld width sp ecication of zero always sp ecies a minimum eld width

it never sp ecies suppression of data output or an actual eld width of zero

Namelist

Although not describ ed here namelist input has b een extended to allow comments to follow one or

more object name value pairs on a line This allows users to do cument howa namelist input le

is structured which values are valid and the meaning of certain values Each line in the namelist

input may contain information ab out name value pairs This additional information mayimprove the

do cumentation of the input le

CPU TIME Intrinsic Subroutine

TIME has b een added This feature is provided to allow the assessment A new intrinsic subroutine CPU

of which pro cessor resources a piece of co de consumes during execution This could b e the execution

of the whole program or only a small part of it Additional purp oses could be comparing dierent

algorithms on the same computer or trying to discover which parts of a calculation on a computer are

most exp ensive

MAXLOC and MINLOC Intrinsics

Fortran sp ecied the MAXLOC and MINLOC intrinsics with only ARRAY and MASK arguments The

High Performance Fortran HPF group added the DIM argument b etween the original twoarguments

for consistency with the MAXVAL and MINVAL intrinsics An incompatibilitybetween Fortran and

HPF results unless MAXLOC and MINLOC are sp ecied as generic interfaces each with two sp ecic

interfaces the rst matching Fortran and the second adding a nonoptional DIM argument as the

second argument The Fortran Standards Committee decided that Fortran should allowthe DIM

and MASK arguments to b e sp ecied in either order For consistencythisprovision for DIM and MASK

to be sp ecied in either order was extended to the other intrinsics which have the same arguments

These intrinsics are MAXVAL MINVAL PRODUCTand SUM

Deleted Features

Any deleted features will app ear in an Annex to the standard The current list of deleted features is

real and double precision DO control variables

branching to an END IF from outside its blo ck

PAUSE statement

ASSIGN assigned GOTO assigned FORMAT sp eciers

Fortran Course Notes File CourseNotesps

High Performance Fortran

cH edit descriptor

CHARACTER len style declarations

New Obsolescent Features

There are some new obsolescent features to b e added to those brought over from Fortran

computed GOTO

statement functions

DATA statements amongst executables

assumedlength character functions

xed form source

assumedsize arrays ie with in the last dimension

Language Tidyups

Language tidyups are mainly concerned with ironing out ambiguities in the Fortran standard and

adding extra text to make matters clearer

High Performance Fortran

Some of this section has b een taken from the High Performace Fortran Forum Draft Sp ecication v

Using sections of this rep ort is encouraged by the HPF so long as the following notice is published

c

Rice University Houston Texas Permission to copy without fee all or part of

this material is granted provided the Rice Universitycopyright notice and the title of this

do cument app ear and notice is given that copying is by p ermission of Rice University

It is widely recognised that represents the only plausible way to continue to increase

the pro cessor power that is available to programmers and engineers In order that this power be

embraced by the whole scientic community the metho d by which the power is harnessed must be

made much more accessible

On current parallel distributed memory architectures the language systems provided require the pro

grammer to insert explicit between communicating programs each of which knows

only ab out a subset of the data even if this data represents a single logical entity such as an array

This approach has often b een compared to programming early digital computers in the days b efore

high level languages were develop ed it is awkward time consuming and errorprone Put succinctly

Message Passing is the assembler language of parallel programming

Septemb er University of Liverp o ol

Compiler Directives

High Performance Fortran HPF was develop ed to help bring distributed memory systems into the

general scientic community Using HPF programmers can write data parallel programs in much the

same way as they write normal sequential high level programs

Lo osely HPF contains by data distribution directives which allow the user to sp ecify to the compiler

how to distribute a single object across the available pro cessors This distribution is done by the

compiler transparently to the programmer who can manipulate distributed objects as a whole even

though they maybepartitioned b etween saypro cessors Thus HPF programs are much easier

to write than are messagepassing programs

HPF is an extension of Fortran The array calculation and dynamic storage allo cation features of

Fortran make it a natural base for HPF The new HPF language features fall into four categories

with resp ect to Fortran

New directives

The new directives are structured comments that suggest implementation strategies or assert facts

ab out a program to the compiler They may aect the eciency of the computation p erformed

but do not change the value computed bytheprogram The form of the HPF directives has b een

chosen so that a future Fortran standard may cho ose to include these features as full statements

in the language by deleting the initial comment header

New language syntax

Some new language features for example FORALL WHERE new intrinsics PURE and ELEMENTAL

pro cedures and the intrinsic functions which were made rstclass language constructs rather

than comments b ecause they aect the interpretation of a program

Library routines

The HPF library of computational functions denes a standard interface to routines that have

proven valuable for high p erformance computing including additional reduction functions com

bining scatter functions prex and sux functions and sorting functions

Language restrictions

The language has b een restricted in a very small numb er of areas

Storage and sequence asso ciation is immensly complicated when arrays are stored noncontinuously

and even on totally separate pro cessors If an HPF program is b eing run over a wide area net

work WAN then rather than o ccupying two adjacent storage lo cations in memorytwo elements

of an arraymaybeseparated by s of miles Full supp ort of Fortran sequence and storage

asso ciation is simply not p ossible with the data distribution features of HPF Some restrictions

on the use of sequence and storage asso ciation are dened These restrictions may in turn re

quire insertion of HPF directives into standard Fortran programs in order to preserve correct

semantics

Compiler Directives

HPF includes features which describ e the collo cation of data ALIGN and the partitioning of data

among memory regions or abstract pro cessors DISTRIBUTE Compilers may interpret these annota

tions to improve storage allo cation for data subject to the constraint that semantically every data

object has a single value at any p oint in the program In all cases users should exp ect the compiler to

arrange the computation to minimise communication while retaining parallelism

The mo del is that there is a twolevel mapping of data objects to memory regions referred to as

abstract pro cessors Data objects typically array elements are rst aligned relative to one another

Fortran Course Notes File CourseNotesps

High Performance Fortran

this group of arrays is then distributed onto a rectilinear arrangement of abstract pro cessors The

implementation then uses the same numb er or p erhaps some smaller numb er of physical pro cessors

to implement these abstract pro cessors This mapping of abstract pro cessors to physical pro cessors is

languagepro cessor dep endent

Arrays are aligned with a template that is to say mapp ed onto a meshed object Any numb er of

arrays can b e mapp ed to a template The idea is to align array elements which are used in the same

assignment statement this will minimise communication b etween pro cessors Once all the arrays have

b een aligned the template is distributed amongst the pro cessors declared in a PROCESSORS directive

In each dimension the distribution can b e

BLOCK or BLOCK m if the template has t items and these are to b e distributed amongst

p pro cessors then each pro cessor receives dtedpe elements It is also p ossible to sp ecify how

many elements each pro cessor received by supplying the optional m parameter

CYCLIC or CYCLICLBR m the template items are distributed to the pro cessor either one

element at a time or m elements at a time in a round robin fashion Thus the rst pro cessor

gets the rst m elements of the template If any array elements are aligned with these

particular template items then they will be assigned to the pro cessor The second pro cessor

will get the next m elements of the template and so on When the last pro cessorhas

b een given template items the whole pro cess wraps around and the rst pro cessor receives more

template items until the template is exhausted CYCLIC distribution is often used to ensure load

balancing

Visualisation of Data Directives

Consider the following data layout directives

HPF PROCESSORS P

HPF TEMPLATE T

INTEGER DIMENSION A

HPF ALIGN AJK WITH TJK

HPF DISTRIBUTE TCYCLICBLOCK ONTO P

These directives will cause the data distribution depicted in Figure It can b e seen that the array A

is aligned to the template with a stride in the rst dimension and in the second every pro cessor

owns part of the array although it can b e seen that owing to the CYCLIC distribution in dimension

the set of array items that a particularpro cessorowns cannot b e describ ed by a linear function or

a subscripttriplet

Septemb er University of Liverp o ol

Visualisation of Data Directives

A(1,1) 1234567

1 1

2 2

3 3

4 4

5 5

1 1

2 2

3 3

4 4

5 5

A(6,1) 1234567

A(6,10)

Array item Template item1 Processor 1

Figure Alignment of a D Array with a D Template and Distribution onto a D Pro cessor Grid

P owns A

P owns A

P owns A and A

P owns A and A

P owns A and A

P owns A A A and A

It is for this reason that CYCLICM distribution results in an inecient implementation the compiler

must describ e the elements that a particularpro cessorowns by a union of subscript triplets instead of

Fortran Course Notes File CourseNotesps

High Performance Fortran

the single subscript triplet which can b e used for all the other distributions The target co de will have

an extra nested lo op for each for each dimension with a CYCLICM distribution

The statement

A A

causes no communication b ecause b oth elements are owned by the same pro cessorbut

A A

do es generate a communication along a rowofpro cessors b etween P and P on row

The directives

HPF PROCESSORS P

HPF TEMPLATE T

INTEGER DIMENSION A

HPF ALIGN AJK WITH TJK

HPF DISTRIBUTE TBLOCK ONTO P

demonstrate the collapsing of a template dimension so that a dimensional template can b e distributed

onto a dimensional pro cessor see Figure

Septemb er University of Liverp o ol

Visualisation of Data Directives

A(1,1) 1234567

1 2 3 4 5 6 7 A(6,10) A(6,1)

Array item Template item 1 Processor 1

Figure Alignment of a D Array with a D Template and Distribution onto a D Pro cessor

Chain

P owns A

P owns A and A

P owns A and A

P owns A

It is also p ossible to collapse one ormore dimensions of an array onto a template see Figure

Fortran Course Notes File CourseNotesps

High Performance Fortran

1234567 A(1,1)

1234567

A(6,1) A(6,10)

Array item Template item1 Processor 1

Figure Alignment of a D Array with a D Template and Distribution onto a D Pro cessor

Chain

HPF PROCESSORS P

HPF TEMPLATE T

INTEGER DIMENSION A

HPF ALIGN AK WITH TK

HPF DISTRIBUTE TBLOCK ONTO P

This data distribution results in the same array elements b eing present on the same pro cessors as the

previous mapping

Septemb er University of Liverp o ol

ASCI I Collating Sequence

The following table represents the ASCI I character set Atthetopofthetableare hexadecimal digits

and to the left of the table are the digits F To determine the hexadecimal value of a given

ASCI I character use the hexadecimal value that corresp onds to the row in the units p osition and the

digitsthatcorresp onds to the column in the s p osition For example the value of the character

representing the tilde is E

NUL DLE SP P p

SOH DC A Q a q

STX DC B R b r

ETX DC C S c s

EOT DC D T d t

ENQ NAK E U e u

ACK SYN F V f v

BEL ETB G W g w

BS CAN H X h x

HT EM I Y i y

A LF SUB J Z j z

B VT ESC K k f

C FF FS L l

CR GS M m g D

E SO RS N n

F SI US O o DEL

ASCI I Collating Sequence

Fortran Course Notes File CourseNotesps

REFERENCES

where

NUL Null DLE Data link Escap e

SOH Start of Heading DC Device Control

STX Start of Text DC Device Control

ETX End of Text DC Device Control

EOT End of Transmission DC Device Control

ENQ Enquiry NAK Negative Acknowledgement

ACK Acknowledge SYN Synchronous Idle

BEL Bell ETB End of Transmission Blo ck

BS Backspace CAN Cancel

HT Horizontal Tab EM End of medium

LF Line Feed SUB Substitute

VT Vertical Tab ESC Escap e

FF Form Feed FS File Separator

CR Carriage Return GS Group Separator

SO Shift Out RS Record Separator

SI Shift In US Unit Separator

SP Space DEL Delete

References

Anonymous Fortran ISOIEC

CSEP Fortran and Computational Science Technical rep ort Oak Ridge National Lab oratory

S Davis C Programmers Companion AddisonWesley

High Performance Forum High Performance Fortran language sp ecication version Technical

rep ort Rice UniversityMay

Septemb er University of Liverp o ol