Basic Introduction to FORTRAN
-
Upload
harilal-remesan -
Category
Documents
-
view
257 -
download
0
Transcript of Basic Introduction to FORTRAN
-
8/10/2019 Basic Introduction to FORTRAN
1/81
A Basic Introduction to
Programming in Fortran
Course notes for EP241 & EP208
Dr. Ahmet BinglUniversity of Gaziantep
With contributions from:Dr. Andrew BeddallDr. Bahattin Kanber
Version 2.1
Feb 2010
-
8/10/2019 Basic Introduction to FORTRAN
2/81
Preface
Computer programming is an essential part of the work of many scientists andengineers. Fortran is a powerful language for numerical programming and is easy to
learn at a basic level. This guide is intended as a first introduction to Fortran 90(compatible with Fortran 95/2003). It is primarily written as a supplement toprogramming courses taken by engineering faculty students, but is also suitable forstudents of science and mathematics. The guide is not comprehensive; after thestudent has familiarised her self with the topics presented in this guide she is advisedto find a more detailed and comprehensive text book.
This course is for the Engineering of Physics students in the University ofGaziantep. You can find more details of this course, program sources, and otherrelated links on the course web page at:
http://www1.gantep.edu.tr/~bingul
A local web site dedicated to Fortran can also be found at:
http://www.fortran.gantep.edu.tr/
Trke: Temel Ynleriyle Fortran 90 / 95 / 2003
http://www1.gantep.edu.tr/~bingul/f95
The author can be contacted by email at:
bingul(at)gantep.edu.tr
-
8/10/2019 Basic Introduction to FORTRAN
3/81
Contents
Section Page
1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12. Algorithms, Flow Charts and Problem Solving . . . . . . . . . . . . . 63. Program Structure, Data Types, Arithmetic Operators . . . . . . 84. Intrinsic Functions, I/O, Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 135. Control Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176. Repetitive Structures (Iteration) . . . . . . . . . . . . . . . . . . . . . . . . 247. Program Flow and Tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308. Formatted I/O and File Processing . . . . . . . . . . . . . . . . . . . . . . 349. Subprograms: Programmer-defined Functions . . . . . . . . . . . . . 38
10. Subprograms: Programmer-defined Subroutines . . . . . . . . . . 4511. Arrays and Array Processing . . . . . . . . . . . . . . . . . . . . . . . . . . 5412. Selected Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67Topics Not Covered . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72Appendix. List of Fortran 90 Intrinsics . . . . . . . . . . . . . . . . . . . . . . . 74
-
8/10/2019 Basic Introduction to FORTRAN
4/81
A Basic Introduction to Programming in Fortran1
1. Introduction
1.1 This Guide
This guide is a very basic introduction to the Fortrancomputer programming language. The
scope of the guide includes the basics of: input/output, data types and arithmetic operations,
intrinsic functions, control statments and repetitive structures, program tracing, file
processing, functions and subroutines, and array processing, numerical KINDs and some
interesting topics. However, some more advanced topics that are not covered in this guide are
listed at the end. A list of Fortran 95 intrinsics is given in the appendix.
We have tried to make this guide concise, avoiding detailed descriptions of the language and
providing only a small number of example programs in each topic. By studying the example
programs carefully you should be able to realise some of the features of Fortran that are
otherwise unexplained in the text. We encourage the reader to persue further studies with amore complete Fortran text book.
1.2 Computers and Programming and Fortran
A computer is an automatic device that performs calculations, making decisions, and has
capacity for storing and processing vast amounts of information. A computer has two main
parts:
Hardware (=DONANIM)
Hardware is the electronic and mechanical parts of the computer (see Figure 1.1).Hardware includes:
Input Units Keyboard, Mouse, Scanner
Process Units CPU, Central Processing Unit. This coordinates the operation of
computer system and performs arithmetic logic operations.
RAM, Random Access Memory
HDD, Hard Disc Driver
FDD, Floppy Disc Driver
CD-ROM, Compact DiscRead Only Memory
Output Units Monitor, Printer, Plotter, Scanner, Modem, Speaker
-
8/10/2019 Basic Introduction to FORTRAN
5/81
A Basic Introduction to Programming in Fortran2
Figure 1.1:Block diagram for the hardware parts of a digital computer
Software (=YAZILIM)The software consists of all the programs running on the computer. It includes:
Operating System (OS) is a program written by manufacturer (e.g. Microsoft). It interfacebetween computer and user. All the programs run under the OS.
Examples are: MS-DOS, Windows, Unix, Linux, BEOS.
Compilers can also be called translator. Very computer language has its own
compiler. The compiler translates the statements of program written
in a high level language into a low level language, the machine code.
Examples are: Fortran, C, C++, Java, Pascal, Basic.
Application Programs are programs written by the users for their own needs.
For example: Word, Excel, Logo, AutoCAD, Flash.
Science and engineering has always been closely tied to the evolution of new tools and
technologies. Computer technology continues to provide powerful new tools in all areas of
science and engineering. The strength of the computer lies in its ability to manipulate and
store data. The speed at which computers can manipulate data, and the amount of data they
can store, has increased dramatically over the years doubling about every 18 months!
(Moore's law). Although the computer has already made an enormous impact on science and
engineering and of course elsewhere (such as mathematics and economics) its potential is
only just beginning to be tapped. A knowledge of using and programming computers is
essential for scientists and engineers.
1.3 Creating and Running a Program
Editing, Compiling, and RunningTo create and execute a program you need to invoke three environments; the first is the editor
environment where you will create the program source, the second is the compilation
environment where your source program will be converted into a machine language program,
the third is the execution environment where your program will be run. In this guide it is
assumed that you will invoke these three environments on a local Linux server in the
University of Gaziantep. For this, three easy to use commands are available:
RAM
CPUInput
UnitsOutput
Units
Storage Units
-
8/10/2019 Basic Introduction to FORTRAN
6/81
A Basic Introduction to Programming in Fortran3
$ edit myprogram.f90 to invoke the editor and compose the program source
$ fortran myprogram.f90 to compile the source into an executable program
$ run myprogram to run the executable program
The details of using these commands are left to programming laboratory sessions.
Steps of Program DevelopmentA program consists of a set of instructions written by the programmer. Normally a high level
language (such as Basic, C, or Fortran) is used to create a source code written with English-
like expressions, for example:
REAL :: A, B, CPRINT *, "Enter two numbers"READ *, A, BC = A + BPRINT *, "the sum is ", CEND
A compiler is then used to translate the source code into machine code (a low level language),the compiled code is called the object code. The object code may require an additional stage
where it is linked with other object code that readies the program for execution. The machine
code created by the linker is called the executable code or executable program. Instructions in
the program are finally executed when the executable program is executed (run). During the
stages of compilation, linking, and running, error messages may occur that require the
programmer to make corrections to the program source (debugging). The cycle of modifying
the source code, compiling, linking, and running continues until the program is complete and
free of errors. This cycle is illustrated in the Figure 1.2.
Figure 1.2:Steps of program development. Programming is often an iterative process of
writing, compiling, running a program.
Examples of various types of errors are given below.
Write the source program
Compile to obtain the object
Link the object code to obtainthe executable ro ram
Execute (run) the program
Compile-time
Link-timeerrors
Run-timeerrors
DEBUGGING
Inputs Outputs
-
8/10/2019 Basic Introduction to FORTRAN
7/81
A Basic Introduction to Programming in Fortran4
Compile-time errorsThese are errors that occur during compilation of the source code into object code. They are
usually due to incorrect usage of the programming language, for example:
READ *, A, BC = A + B
PRNT *, CEND
Compilation of this program results in a compile-time error something like:
PRNT *, C1Error: Unclassifiable statement at (1)
PRNTis a misspelling of the output statement PRINT. This error is corrected by replacing PRNT
with PRINT in the source code and then recompiling the program, this process is called
debugging. Object code is only created when there are no detected compile-time errors.
Compile-time warnings may also occur, these provide the programmer with advice about
parts of the program that may be using non-standard syntax or that may potentially cause
errors. Compile-time warnings do not prevent the creation of object code. Example:
REAL :: CPRINT *, CEND
Compilation of this program may result in the compile-time warning something like:
REAL :: C
1Warning (113): Variable 'c' at (1) is used but not set
An executable is created, but will give an undetermined result.
Link-time errorsThese are errors that occur during the linking stage. They result when, for example, an
external object required by the program cannot be found. Example:
PRINT *,SIN(4.3)PRINT *,ARCSIN(.78)END
Compilation of this program results in a link-time error something like:
PRINT *,ARCSIN(.78)1
Error: Function 'arcsin' at (1) has no implicit type
In this case the program is compiled into object code but then fails to link the external
functionARCSINthat does not exist in any library known to the compiler. When a link-time
error occurs the executable is not created. This program may be corrected by replacing in the
source code the statementARCSINwithASIN(the standard Fortran statement representing the
inverse sine of a number) or by providing the reference subprogram. Again link-timewarningsmay also occur.
-
8/10/2019 Basic Introduction to FORTRAN
8/81
A Basic Introduction to Programming in Fortran5
Run-time errorsThese are errors that occur during the execution of the program (when the program is
running). Such errors usually occur when the logic of the program is at fault or when an
unexpected input is given (unexpected inputs or faulty logic does not necessarily result in run-
time error messages, such programming errors should be detected by rigorously testing your
program). When a run-time error occurs the program terminates with an appropriate errormessage. Example:
REAL :: A(5)INTEGER :: IDO I=1,6A(I)=I**2
END DOPRINT *, AEND
This program compiles and links without errors, but when executed may result in the program
terminating with a run-time error something like:
Fortran runtime error: Array element out of bounds: 6 in (1:5), dim=1
Run-time errors result from run-time checking that the compiler builds into the object code.
Compiler options can be used to switch on and off various run-time checks, compile-time
warnings, code optimisation, and various other compiler features.
1.4 Questions
[1].What compiler options are you using when you compile your Fortran source?[2].How can you find out what other compiler options are available and switch them
on and off?
NotesUse this section to note down commands and procedures for editing, compiling, and running
your programs on your computer platform.
-
8/10/2019 Basic Introduction to FORTRAN
9/81
A Basic Introduction to Programming in Fortran6
2. Algorithms, Flow Chartsand Problem Solving
2.1 Introduction
In this section we introduce ideas about problem solving with computers; we make use of
flowcharts, algorithms, and consider the importance of defining a problem sufficiently and
what assumptions we may make during the solution.
Consider the calculation of the twist factor of a yarn. Twist Factor, Tf, of a yarn is given by:
1000
mNTf
whereN(turn/m) is the number of twist of a yarn per unit length and mis measured in tex (a
yarn count standard) that is mass in grams of a yarn whose length is 1 km. Write a Fortran
program to calculate twist factor of a yarn for givenNand m.
A solution might look something like twist.f90, the key section is below:
PROGRAM Twist_FactorIMPLICIT NONEREAL :: Tf,mINTEGER :: N
PRINT *,"Input the value of N and m"READ *,N,m
Tf = N*SQRT(m/1000.0)
PRINT *,"The twist factor is",TF
END PROGRAM Twist_Factor
But maybe it is not as simple as this: was the problem defined clearly? what assumptions did
we make in the solution, are they valid? This is discussed in detail in the lecture; some notes
are given below.
2.2 Problem Solving
Problem solving with computers involves several steps:
1. Clearly define the problem.
2. Analyse the problem and formulate a method to solve it (see also validation).
3. Describe the solution in the form of an algorithm.
4. Draw a flowchart of the algorithm.
5. Write the computer program.
6. Compile and run the program (debugging).
7. Test the program (debugging) (see also verification).
8. Interpretation of results.
-
8/10/2019 Basic Introduction to FORTRAN
10/81
A Basic Introduction to Programming in Fortran7
Verification and ValidationIf the program has an important application, for example to calculate student grades or guide a
rocket, then it is important to test the program to make sure it does what the programmer
intends it to do and that it is actually a valid solution to the problem. The tests are commonly
divided as follows:
Verification verify that program does what you intended it to do; steps 7(8)
above attempt to do this.
Validation does the program actual solve the original problem i.e. is it valid? This goes
back to steps 1 and 2 - if you get these steps wrong then your program is not a
valid solution.
2.3 Algorithms
The algorithm gives a step-by-step description of the solution. This may be written in a non-
formal language and structure. An example is given in the lecture.
2.4 Flow Charts
A flow chart gives the logical flow of the solution in a diagrammatic form, and provides a
plan from which the computer program can be written. The logical flow of an algorithm can
be seen by tracing through the flowchart. Some standard symbols used in the formation of
flow charts are given below.
An oval is used to indicate the beginning
or end of an algorithm.
A parallelogram indicates the input
or output of information.
A rectangle indicates a computation, with the
result of the computation assigned to a variable.
A diamond indicates a point where a decision
is made.
A hexagon indicates the beginning of the
repetition structure.
A double lined rectangle is used at a point
where a subprogram is used.
An arrow indicates the direction of flow of the algorithm.
Circles with arrows connect the flowchart between pages.
-
8/10/2019 Basic Introduction to FORTRAN
11/81
A Basic Introduction to Programming in Fortran8
3. Program Structure,Data Types, Arithmetic Operators
3.1 Introduction
In this section, you will learn the basic structure of Fortran 90, how Fortran 90 handles
different data types, and study arithmetic operations in Fortran.
3.2 Fortran Program Structure
The basic program structure used in this guide is:
PROGRAMA_Program_Name! Comment explaining the purpose of the program
IMPLICIT NONEREAL :: Var1, Var2 a declaration part...INTEGER :: Var3, Var4
Var1 = 0. an initialisation part ...Var2 = 0.Var3 = 0.Var4 = 0.
... some operations ...
PRINT *, some output
END PROGRAMA_Program_Name
You are free to indent with spaces and add empty lines as you wish, the aim is to improve the
readability of the program source.
3.3 Data Types and Constants
A key component of a program is the use of objects that store data. There are five data types:
REAL, INTEGER, COMPLEX, CHARACTER, LOGICAL. Most commonly used in numerical work are
type REALand type INTEGER. In the following example program we have objects namedA,V,
andMomentum that are declared to store type realdata (numbers with decimal points), and
objects named Count,Missed, and Decay, that are declared to store type integerdata, and an
object namedMonth declared to store type character data. All these objects are called
variables as their values can be changed (varied) during program execution.
-
8/10/2019 Basic Introduction to FORTRAN
12/81
A Basic Introduction to Programming in Fortran9
PROGRAM Variables!--------------------------------------! Example declaration, initialisation,! and output of variables!--------------------------------------IMPLICIT NONE
REAL :: A, V, MomentumINTEGER :: Count, Missed, DecaysCHARACTER(LEN=9) :: Month
A = 4.03V = 15.6E3Count = 13535Missed = 34Momentum = V/ADecays = Count + MissedMonth = "January"PRINT *, Momentum, Decays, Month
END PROGRAM Variables
Note that in the assignmentV = 15.6E3the expression 15.6E3in Fortran represents the
value 15.6 103= 15600. The output of this program (from the PRINTstatement) is:
3870.968 13569 January
Named constantsare declared with the PARAMETERattribute. Such data is assigned a value at
declaration and cannot be changed during program execution; for example:
PROGRAM Convert_FtoM
!-------------------------------------------! Program to convert a length given in feet! to the corresponding length in metres.!-------------------------------------------
IMPLICIT NONEREAL, PARAMETER :: FtoM = 0.3048REAL Feet, Metres
PRINT *, "Type the length in feet"READ *, FeetMetres = Feet * FtoMPRINT *, Feet, " feet = ", Metres, " metres."
END PROGRAM Convert_FtoM
Example execution:
Type the length in feet12.012.00000 feet = 3.657600 metres.
Here, identifier FtoM (an object that can store a real value) is declared as a constant (the
PARAMETERattribute). The value of FtoM is defined in its declaration and cannot be change
during the execution of the program. In this program it is not necessary to give identifier
FtoMthe PARAMETERattribute; but, as we do not intend the value of FtoMto change during
program execution it is good programming practice to declare it as a constant.
-
8/10/2019 Basic Introduction to FORTRAN
13/81
A Basic Introduction to Programming in Fortran10
3.4 Arithmetic Operations
OperatorsThe symbols ( ) * / + - **are used in arithmetic operations. They represent parenthesis,
multiplication, division, addition, subtraction and exponentiation, respectively.
Priority RulesArithmetic operations follow the normal priority; proceeding left to right, with
exponentiation performed first, followed by multiplication and division, and finally addition
and subtraction. Parenthesis can be used to control priority.
Mixed-mode, and integer operationsIf integers and reals are mixed in arithmetic operations the result is a real. Operations
involving only reals yield a type real result. Operations involving only integers yield a type
integer result. Be especially careful when dividing two integers - the result is truncated to an
integer; for example, 3/2 = 1, and 1/2 = 0. This is illustrated in the program below.
PROGRAM Operations!--------------------------------------------------! Program to test integer and mixed mode operations!--------------------------------------------------IMPLICIT NONEREAL :: A, B, CINTEGER :: I, J, K
A = 3.B = 4.I = 5
J = 3C = A + I / JK = A / I + 2 * B / J
PRINT *, C, K
END PROGRAM Operations
The output of this program is
4.000000 3
and is explained as follows:
Type real object Cis assigned the result ofA+I/J= 3.0+5/3 = 3.0+1 = 4.0. Here, the result ofthe integer operation 5/3 is an integer and so 1.66666 is truncated to 1; the value of C is
output.
Type integer object K is assigned the result ofA/I+2*B/J= 3.0/5+2*4.0/3 which, using the
priority rules evaluates as (3.0/5)+2*4.0/3. Remember that mixed-mode arithmetic results in a
type real value and so the result is 0.6+2.66666 = 3.266666. The assignment however is to a
type integer object and so the value is truncated to 3; the value of Kis output.
-
8/10/2019 Basic Introduction to FORTRAN
14/81
A Basic Introduction to Programming in Fortran11
It is advisable to avoid integer division, get into the habit of using the following forms in
operations:
Real constants should always be written with a decimal point
e.g., instead of X=A/5write X=A/5.
Integer identifiers should be converted to real type in operationse.g., instead of X=A/Nwrite X=A/REAL(N)if that is what you mean.
IfAis type real then both these case are not necessary - but it is good programming practice
to make a habit of using these forms (write explicitly what you mean).
Long arithmetic expressionsWhen writing long arithmetic expressions it can be useful to break them down into
constituent parts. For example the expression:
Z = ( (X**2 + 2.*X + 3.)/(5.+Y)**0.5 - ((15. - 77.*X**3)/Y**1.5)**0.5 )
/ (X**2 - 4.*X*Y - 5.*X**(-0.8))can be written more clearly (and carefully) as
A = (X**2 + 2.*X + 3.) / (5.+ Y)**0.5B = (15.- 77.*X**3) / Y**1.5C = X**2 - 4.*X*Y - 5.*X**(-0.8)Z = ( A - B**0.5 ) / C
This is implemented in the program below:
PROGRAM Equation
IMPLICIT NONEREAL :: X = 0.2, Y = 1.9REAL :: A, B, C, Z
A = (X**2+2.*X+3.) / (5.+Y)**0.5B = (15.-77.*X**3) / Y**1.5C = X**2 - 4.*X*Y - 5.*X**(-0.8)
Z = ( A - B**0.5 ) / C
PRINT *, Z
END PROGRAM Equation
If you dont want to seperate an expression into parts you can use & operator as follows:
Z = ( (X**2 + 2.*X + 3.)/(5.+Y)**0.5 - &((15. - 77.*X**3)/Y**1.5)**0.5 ) / &(X**2 - 4.*X*Y - 5.*X**(-0.8))
-
8/10/2019 Basic Introduction to FORTRAN
15/81
A Basic Introduction to Programming in Fortran12
3.5 Declaring and Initialising Variables
Again, it is good programming practice to get into the habit of:
Always use IMPLICIT NONE. This forces you to declare all variable you use and so
avoids the potential of using a misspelled identifier.
Always initialise variables; an uninitialised variable will take, depending on the
particular compiler or compiler options you are using, a value which is either zero or
an unpredictable value. You can remove such uncertainties by initialising all variables
you declare.
For example:
INTEGER :: KREAL :: SK = 0S = 0.
.
.
or
INTEGER :: K = 0REAL :: S = 0...
Note that the second form in subprograms gives the variables the SAVEattribute (see other
texts for an explanation).
-
8/10/2019 Basic Introduction to FORTRAN
16/81
A Basic Introduction to Programming in Fortran13
4. Intrinsic Functions,I/O, Arrays
4.1 Introduction
In this section, you will learn some Fortran intrinsic mathematical functions such as SIN, EXP,
ABS, the basics of the input/output (I/O) and an introduction to arrays (arrays are covered in
more detail in a later section).
4.2 Intrinsic Functions
These are functions that are built in to the compiler. Some are shown in the table below (the
the appendix at the end of this guide for a full list of Fortran 90 intrinsics):
Function Meaning ExampleLOG(x) Natural logarithm; ln(x) Y = LOG(2./X)
LOG10(x) Logarithm for base 10; log10(x) Y = LOG10(X/3.5)
COS(x) Cosine of a number in radians Y = COS(X)
ATAN(x) Angle in radian whose tangent is x R = ATAN(Y/X)
EXP(x) Natural exponent ex G=EXP(-((X-M)/S)**2/2.)
SQRT(x) Square-root of a real value Root = SQRT(Y)
INT(x) Truncate to an integer K = INT(X)
NINT(x) Nearest integer of a real value K = NINT(X)
MOD(x,y) x (mod y) Remainder = MOD(X,5)ABS(x) Absolute value of x Y = ABS(X)
The Gaussian probability function is defined as:
22 2/)(
2
1)( mxexG
This can be written using intrinsic functions as follows:
G = EXP( -0.5*((X-M)/S)**2 ) / (S*SQRT(2*3.141593))
The test for the number, X, even or odd can be made by:
R = MOD(X,2)
MOD(X,2)returns an integer value which is 0 or 1.
if R=0then the number, X, is even
otherwise R=1the number is odd.
-
8/10/2019 Basic Introduction to FORTRAN
17/81
A Basic Introduction to Programming in Fortran14
Example 4.1
In the following program the values for the position x, mean m,and standard deviation are
input, and value of the gaussian probability function is output.
PROGRAM Gaussian
!--------------------------------------------------------------! The Gaussian probability density function is symmetric about! and maximum at X = M and has a standard deviation of S. The! integrated function is normalised to unity.!--------------------------------------------------------------IMPLICIT NONEREAL, PARAMETER :: TwoPi = 6.283185REAL :: X, M, S ! inputsREAL :: G ! output
PRINT *, "Input the position X, mean M, and sigma S"READ *, X, M, S
G = EXP( -0.5*((X-M)/S)**2 ) / (S*SQRT(TwoPi))
PRINT *, G
END PROGRAM Gaussian
Note that the symbol (sigma) is not permitted in a Fortran program (only characters from
the standard ASCII character set are permitted) and so this is replaced with the letter Swhich
in this case is short forsigma.
Example execution:
Input the position X, mean M, and sigma S
-0.651.212.60.1187972
4.3 Input/Output (I/O)
The idea of input and output devices is introduced very briefly. Inputs for a Fortran program
are usually from a keyboard or a file. Outputs are normally to a screen or a file:
Two pairs of I/O statements are used, the first is for I/O involving the "standard"
keyboard/screen, and the second for I/O involving files.
Program
READ ...PRINT ...WRITE ...
Keyboard
File File
Screen
INPUTS OUTPUTS
-
8/10/2019 Basic Introduction to FORTRAN
18/81
A Basic Introduction to Programming in Fortran15
Keyboard/Screen I/O statements:
READformat specifier, input list
PRINTformat specifier, output list
whereformat specifierspecifies the format of the output.
Examples:
READ *, APRINT *, A
Here Ais input and output in a "free format", i.e. the compiler decides what the format isdepending on the type of data.
PRINT '(F6.3)', A
Here the format of the output is given as:
Fmeans a real value
6means 6 digits (including the decimal place)
3means 3 decimal places.
For example 63.78953 will be output as 63.790(the value is rounded to the nearest decimal
place).
File I/O statements:
READ(unit number,format specifier) input list
WRITE(unit number,format specifier) output list
where unit numberspecifies a number given to the file.
4.4 Introduction to Arrays
A basic introduction to arrays is given here, more details are covered in Section 10. An array
is a group of variables or constants, all of the same type, which is referred to by a single
name. If the following can represent a single value:
REAL :: Mass
A set of 5 values can be represented by the array
REAL :: Mass(5)
The 5 elementsof the array can be assigned as follows:
Mass(1) = 8.471Mass(2) = 3.683Mass(3) = 9.107Mass(4) = 4.739Mass(5) = 3.918
or more concisely using an array constant:
-
8/10/2019 Basic Introduction to FORTRAN
19/81
A Basic Introduction to Programming in Fortran16
Mass = (/ 8.471, 3.683, 9.107, 4.739, 3.918 /)
Consider the following program section;
REAL :: Mass(5)Mass = (/ 8.471, 3.683, 9.107, 4.739, 3.918 /)PRINT *, Mass
The output is:
8.471000 3.683000 9.107000 4.739000 3.918000
We can operate on individual elements, for example
Weight = Mass(5) * 9.81
here, Weightis a scalar. Or we can operate on a whole array in a single statement:
Weight = Mass * 9.81
Here both Weightand Massare arrays with 5 elements (the two arrays must conform).Consider the following program section;
REAL :: Mass(5), Weight(5)Mass = (/ 8.471, 3.683, 9.107, 4.739, 3.918 /)Weight = Mass * 9.81PRINT *, MassPRINT *, Weight
The above program section is implemented in the example program below; operations
involving a whole array are indicated in bold.
Example 4.2
PROGRAM Weights!----------------------------------------------------! Given an array of masses, this program computes! a second array of weights using a "whole array! assignment". The arrays must have the same! number of elements.!----------------------------------------------------IMPLICIT NONEREAL, PARAMETER :: g = 9.81REAL :: Mass(5), Weight(5)
Mass = (/ 8.471,3.683,9.107,4.739,3.918 /) ! Assign the mass valuesWeight = Mass*g ! Compute the weights
PRINT *, MassPRINT *, Weight
END PROGRAM Weights
The output is:8.471000 3.683000 9.107000 4.739000 3.91800083.10051 36.13023 89.33968 46.48959 38.43558
-
8/10/2019 Basic Introduction to FORTRAN
20/81
A Basic Introduction to Programming in Fortran17
5. Control Statements
5.1 Introduction
Control statements allow us to make decisions - the program takes one course of action or
another depending on the value of a variable. Here we introduce four constructs and
understand how to use them: the simple IFconstruct, the block IFconstruct, the IF-ELSE
construct, IF-ELSE IF-ELSEconstruct and CASEconstruct.
5.2 Relational Operators and their Compound FormsControl statements use relation operators; there are six relational operators as follows:
< less than
greater than
>= greater than or equal to
== equal to. Note that this is not the same as the assignmentoperator =
/= not equal to
Relational expressions can therefore be formed, for example
A < BA == 5B >= 1.
Compound relation expressions can be formed using the .AND. and .OR., (and other)operators; for example:
A < B .AND. C==5.
this statement is true if bothAis less than B, and, Cis equal to 5.
A >= 0 .OR. B > 1.
this statement is true if eitherAis greater or equal to zero, or, Bis greater than one.
5.3 The SimpleIFConstruct
IF ( a simple or compound logical expression)a single statement
For example:
IF ( X > 0 ) Y = SQRT(X)
5.4 The BlockIFConstruct
IF (a simple or compound logical expression) THENstatement 1statement 2.
.END IF
-
8/10/2019 Basic Introduction to FORTRAN
21/81
A Basic Introduction to Programming in Fortran18
For example:
IF ( Poem == "Yes" ) THENPRINT *, "A computer, to print out a fact,"PRINT *, "Will divide, multiply, and subtract."PRINT *, "But this output can be"
PRINT *, "No more than debris,"PRINT *, "If the input was short of exact."PRINT *, " -- Gigo"
END IF
5.5 TheIF-ELSEConstruct
IF (a simple or compound logical expression) THENstatement sequence 1.
ELSEstatement sequence 2
.END IF
For example:
IF (A < B) THENResult = A/BPRINT *, "x = ", Result
ELSEResult = B/APRINT *, "1/x = ", Result
END IF
NestingYou can nest IF ELSEcontruct such that:
IF (a simple or compound logical expression) THENstatement sequence 1IF (a simple or compound logical expression) THEN
statement sequence 2ELSE
statement sequence 3END IF
ELSEstatement sequence 4
IF (a simple or compound logical expression) THENstatement sequence 5
ELSEstatement sequence 6
END IFEND IF
5.6 IF-ELSE IFConstruct
The selection structures considered thus so far have invloved selecting one of two
alternatives. It is also possible to use the IF construct to design selection structures that
contain more than two alternatives:
-
8/10/2019 Basic Introduction to FORTRAN
22/81
A Basic Introduction to Programming in Fortran19
IF (a simple or compound logical expression) THENstatement sequence 1
ELSE IF (a simple or compound logical expression) THENstatement sequence 2
ELSE IF (a simple or compound logical expression) THEN
statement sequence 3...ELSE IF (a simple or compound logical expression) THENstatement sequence n-1
ELSEstatement sequence n
END IF
Example 5.1consider the following piecewise function:
1if1
10if0if
)( 2
x
xxxx
xf
To evaluate the function, following program can be implemented:
PROGRAM Composite_FunctionIMPLICIT NONEREAL :: x,F
PRINT *, "Input the value of x"READ *, x
IF (x 0 .AND. x
-
8/10/2019 Basic Introduction to FORTRAN
23/81
A Basic Introduction to Programming in Fortran20
5.7 CASEConstruct
In this section the CASEconstruct which is an alternative of IF-ELSE IFconstruct and
useful for implementing some selection structures. A CASEcontruct has the following
form:
SELECT CASE (selector) THENCASE(label list 1)
statement sequence 1CASE(label list 2)
statement sequence 2...
CASE(label list n)statement sequence n
END SELECT
where
selector is an integer, character or logical expression
label list i is a list of one or more possible values of the selector and
the values in this list may have any of the forms:
Value denotes a single valuevalue1: value2 denotes from value1to value2value1: denotes the set of all values greater than or equal to value1: value2 denotes the set of all values less than or equal to value2
For example, following CASE construct can be used to display the class name thatcorresponds to a numeric class code:
SELECT CASE(ClassCode)
CASE(1)PRINT *,"Freshman"
CASE(2)PRINT *,"Sophmore"
CASE(3)PRINT *,"Junior"
CASE(4)PRINT *,"Graduate"
CASE DEFAULTPRINT *,"Illegal class code", ClassCode
END SELECT
Note that the use CASE DEFAULTstatement to display an error message in case the value of
the selector ClassCodeis none of 1,2,3,4 or 5. Although the CASE DEFAULTstatement can
be placed anywhere in the list of CASEstatement.
-
8/10/2019 Basic Introduction to FORTRAN
24/81
A Basic Introduction to Programming in Fortran21
Example 5.2 Finding a Leap Year
A leap year is a year in which one extra day (February 29) is added to the regular calendar.
Most of us know that the leap years are the years that are divisible by 4. For example 1992
and 1996 are leap years. Most people, however, do not know that there is an exception to
this rule: centennial years are not leap years. For example, 1800 and 1900 were not leap
years. Furthermore, there is an exception to the exception: centennial years which aredivisible by 400 are leap years. Thus 2000 is a leap year. The following program checks if
the given year is leap or not.
PROGRAM Leap_Year!-----------------------------------------! Finding a leap year!-----------------------------------------IMPLICIT NONEINTEGER :: Y
PRINT *,"Enter a year"READ *,Y
IF( MOD(Y,4) == 0 .AND. MOD(Y,100) /= 0 .OR. &MOD(Y,400) == 0) THENPRINT *,Year," is a leap year."
ELSEPRINT *,Year," is not a leap year."
END IF
END PROGRAM Leap_Year
I
Example 5.3: Ratio of two numbers
PROGRAM Fractional_Ratio!-------------------------------------! The ratio of two numbers such! that it is positive and a fraction.!-------------------------------------
IMPLICIT NONEREAL A, B, Ratio
PRINT *, "Input two numbers."READ *, A, B
A=ABS(A); B=ABS(B)
IF (A < B) THENRatio = A/B
ELSERatio = B/A
END IF
PRINT *, "The ratio is ", Ratio
END PROGRAM Fractional_Ratio
-
8/10/2019 Basic Introduction to FORTRAN
25/81
-
8/10/2019 Basic Introduction to FORTRAN
26/81
A Basic Introduction to Programming in Fortran23
Example 5.5 Grade calculation
PROGRAM Grade_Calculation!--------------------------------------------------! Grade calculation from the weighted 0-39 FF
! average of three exams. The first, 40-49 FD! second and final exam scores are 50-59 DD! weighted by 0.3, 0.3, and 0.4 60-69 DC! respectively. The average score is 70-74 CC! converted to a grade from the grade 75-79 CB! table (right). 80-84 BB! 85-89 BA! 90-100 AA!--------------------------------------------------
IMPLICIT NONEREAL :: MT1, MT2, Final, AverageCHARACTER :: Grade*2
PRINT *, "Enter the three exam scores (%)"READ *, MT1, MT2, Final
Average = 0.3*MT1 + 0.3*MT2 + 0.4*FinalPRINT '(A22,F5.1,A1)', "The weighted score is ", Average, "%"
SELECT CASE(NINT(Average)) ! convert Avrage to nearest integer
CASE(:39); Grade="FF"CASE(40:49); Grade="FD"CASE(50:59); Grade="DD"CASE(60:69); Grade="DC"CASE(70:74); Grade="CC"CASE(75:79); Grade="CB"CASE(80:84); Grade="BB"CASE(85:89); Grade="BA"CASE(90:); Grade="AA"
END SELECT
PRINT *, "The grade is ", Grade
END PROGRAM Grade_Calculation
-
8/10/2019 Basic Introduction to FORTRAN
27/81
A Basic Introduction to Programming in Fortran24
6. Repetitive Structures(Iteration)
6.1 Introduction
We can cause a program to repeat sections of statements (iterate) by using the DO loop
construct. There are two forms; the DOloop with a counter, and the endlessDOloop.
6.2 The DOloop with a counter
In this type of looping, the repetition is controlled by a counter. This has the general form:
DOcounter= initial value, limit, step size
.statement sequence.
END DO
For example
DO I = 4, 12, 2PRINT *, I, I**2, I**3
END DO
gives:
4 16 646 36 2168 64 51210 100 100012 144 1728
The counter variable Itakes values starting from 4 and ending at 12 with increments of 2 (the
step size) in between. The number of iterations in this loop is therefore 5. The DO loop
parameters counter, initial value, limit, andstep sizemust all be type integer. To create a loop
with a type real counter we can use, for example, something like the following scheme.
DO I = 0, 10, 2R = 0.1*REAL(I)PRINT *, R, R**2, R**3
END DO
Here, the real variable Ris derived from the integer counter I; the result is:
0.000000E+00 0.000000E+00 0.000000E+000.2000000 4.000000E-02 8.000000E-030.4000000 0.1600000 6.400000E-020.6000000 0.3600000 0.21600000.8000000 0.6400000 0.51200001.000000 1.000000 1.000000
-
8/10/2019 Basic Introduction to FORTRAN
28/81
A Basic Introduction to Programming in Fortran25
6.2 General DOloops
In this type of looping, the repetition is controlled by a logical expression.
DO-EXITConstruct
This has the general form:
DOstatement sequence 1IF ( a simple or compound logical expression) EXITstatement sequence 2
END DO
The loop is reated until the condition (a logical epression) in IFstatement becomes false. If
the condition is true, the loop is terminated by EXITstatement. This is useful for when we
do not know how many iterations will be required.
Example of the use of an DO-EXITconstruct:
DOPRINT *, "Input a positive number."READ *, AIF ( A >= 0.) EXITPRINT *, "That is not positive! try again."
END DO
This program section loops until a positive number in input.
Example execution:
Input a positive number.-34.2That is not positive! try again.Input a positive number.-1That is not positive! try again.Input a positive number.3.4the loop terminates
The following program section outputs the even numbers 10, 8, ..., 2 and their squares:
N=10
DOPRINT *,N,N**2IF(N
-
8/10/2019 Basic Introduction to FORTRAN
29/81
A Basic Introduction to Programming in Fortran26
DO-CYCLEConstructThis has the general form:
DOstatement sequence 1IF ( a simple or compound logical expression) CYCLEstatement sequence 2IF ( a simple or compound logical expression) EXITstatement sequence 3
END DO
When the CYCLEstatement is executed control goes back to the topof the loop. When the
EXITstatement is executed control goes to the endof the loop and the loop terminates.
Example of the use of an DO-CYCLEconstruct:
DO
READ *,XIF (X == 0) CYCLEF = 1.0/XPRINT *,X,FIF(X0.
DO-WHILEConstructThis has the general form:
DOWHILE(a simple or compound logical expression )...statement sequence...
END DO
The logical expression is executed during the condition is true, otherwise the loop is skipped.
Example of the use of an DO-WHILEconstruct:
N=10DO WHILE(N>=2)
PRINT *,N,N**2N=N-2
END DO
The program section given above will output the even numbers 10, 8, ..., 2 and their squares
while N>=2. The results is same as the program section given in page 25.
-
8/10/2019 Basic Introduction to FORTRAN
30/81
A Basic Introduction to Programming in Fortran27
6.4 Endless or Infinite DOloops
The logical expressions given in DO-EXIT, DO-CYCLEand DO-WHILEcan result in an infinite
(endless) loop under proper contions. It is normal to provide the user with some way out of a
loop; if you program loops infinitely then you can break out with the key sequence: Crtl-C.
What can you say about the output of the following program sections?
DO WHILE(2>1)PRINT *,"Engineering"
END DO
I=1DOIF(I==0) EXITPRINT *,"Engineering"
END DO
I=1DOPRINT *,"Engineering"IF(I/=0) CYCLE
END DO
Y = 2.0DOPRINT *,"Engineering"IF(Y
-
8/10/2019 Basic Introduction to FORTRAN
31/81
A Basic Introduction to Programming in Fortran28
Example 6.1 Calculatingn! (n factorial)
PROGRAM N_Factorial!---------------------------------------------------------! Program to compute the factorial of a positive integer.
! It is assumed that N is positive ( N >= 0 )!---------------------------------------------------------
IMPLICIT NONEINTEGER :: I, N, Factorial
PRINT *, "Input N"READ *, N
Factorial = 1DO I = 2, N
Factorial = Factorial*IEND DO
PRINT *, N, " factorial = ", Factorial
END PROGRAM N_Factorial
Example execution:
Input N5
5 factorial = 120
Example 6.2 The mean (excluding zeros) of a list of real values.
PROGRAM Mean!-------------------------------------------! A list of values is input terminated by a! negative number. The mean of all non-zero! entries is calculated.!-------------------------------------------
IMPLICIT NONEINTEGER :: CountREAL :: V, Summation
Summation = 0.
Count = 0
PRINT *, "Input the values, terminating by a negative value."
DOREAD *, VIF ( V==0. ) CYCLEIF ( V < 0. ) EXITSummation = Summation + VCount = Count + 1
END DO
PRINT *, "The sum is ", SummationPRINT *, "The mean is ",Summation / REAL(Count)
END PROGRAM Mean
-
8/10/2019 Basic Introduction to FORTRAN
32/81
A Basic Introduction to Programming in Fortran29
Example execution:
18.343.623.689.378.80.045.70.034.6-1The sum is 333.9000The mean is 47.70000
Example 320-by-20 table of products
PROGRAM Table_of_Products!---------------------------------------------! This program outputs a table of products! using an implied DO loop inside a DO loop.!---------------------------------------------
IMPLICIT NONEINTEGER :: I, J
DO I = 1, 20PRINT '(20(1x,I3))', (I*J, J=1,20)
END DO
END PROGRAM Table_of_Products
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 202 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 403 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 604 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 805 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 1006 12 18 24 30 36 42 48 54 60 66 72 78 84 90 96 102 108 114 1207 14 21 28 35 42 49 56 63 70 77 84 91 98 105 112 119 126 133 1408 16 24 32 40 48 56 64 72 80 88 96 104 112 120 128 136 144 152 160
9 18 27 36 45 54 63 72 81 90 99 108 117 126 135 144 153 162 171 18010 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 20011 22 33 44 55 66 77 88 99 110 121 132 143 154 165 176 187 198 209 22012 24 36 48 60 72 84 96 108 120 132 144 156 168 180 192 204 216 228 24013 26 39 52 65 78 91 104 117 130 143 156 169 182 195 208 221 234 247 26014 28 42 56 70 84 98 112 126 140 154 168 182 196 210 224 238 252 266 28015 30 45 60 75 90 105 120 135 150 165 180 195 210 225 240 255 270 285 30016 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256 272 288 304 32017 34 51 68 85 102 119 136 153 170 187 204 221 238 255 272 289 306 323 34018 36 54 72 90 108 126 144 162 180 198 216 234 252 270 288 306 324 342 36019 38 57 76 95 114 133 152 171 190 209 228 247 266 285 304 323 342 361 38020 40 60 80 100 120 140 160 180 200 220 240 260 280 300 320 340 360 380 400
-
8/10/2019 Basic Introduction to FORTRAN
33/81
A Basic Introduction to Programming in Fortran30
7. Program Flowand Tracing
7.1 Introduction
In this section more examples of programs using loops are given with emphasis placed on
using program tracing.
7.2 The Program Trace
Flow charts help us to visualise the flow of a program, especially when the program includes
control statements and loops. As well as being an aid to program design, a flowchart can also
help in the debugging of a program. Another aid to debugging is the program trace. Here,
the values that variables take are output during the program execution. This is achieved by
placing output statements at appropriate points in the program.
Example 7.1
The output statements shown in bold in the following program create a program trace:
PROGRAM Max_Int!-------------------------------------------------! Program to find the maximum of N integer values! A program trace is acheived by using the output! statements indicated by "! TRACE".!-------------------------------------------------
IMPLICIT NONEINTEGER, PARAMETER :: N = 6INTEGER :: V(N), I, MaxPRINT *,"Input ", N, " integers"READ *, VMax = V(1)PRINT *, " I N V(I) Max" ! TRACEPRINT '(4(1X,I4))', 1, N, V(1), Max ! TRACEDO I = 2, N
IF ( V(I) > Max ) Max = V(I)PRINT '(4(1X,I4))', I, N, V(I), Max ! TRACE
END DOPRINT *, "The maximum value is ", Max
END PROGRAM Max_Int
The output of the program (the trace is shown in bold) is:
K V(K) Max1 12 122 -56 123 34 344 89 895 0 896 31 89The maximum value is 89
The evolution of the values can be seen for each iteration of the loop.
-
8/10/2019 Basic Introduction to FORTRAN
34/81
A Basic Introduction to Programming in Fortran31
Example 7.2
PROGRAM Newtons_Square_Root!----------------------------------------------------! This program uses Newton's method to compute the! square root of a positive number P. The formula:
!! Xnew = ( Xold + P / Xold ) / 2!! is iterated until the difference |Xnew - Xold| is! zero* i.e X has converged to the square root of P.!----------------------------------------------------! * here "zero" means there is no difference within! the limited storage precision.!----------------------------------------------------! A program trace is acheived by using the output! statement indicated by "! TRACE".!----------------------------------------------------IMPLICIT NONE
REAL :: P, Xold, Xnew
PRINT *, "Input a positive number"READ *, PXold = PDO
Xnew = ( Xold + P/Xold ) / 2.PRINT *, P, Xnew, Xnew-Xold ! TRACEIF ( Xnew - Xold == 0. ) EXITXold = Xnew
END DOPRINT *, "The square root is ", Xnew
END PROGRAM Newtons_Square_Root
Example executions:
$ run program20traceInput a positive number3.0 [Enter]3.000000 2.000000 -1.0000003.000000 1.750000 -0.25000003.000000 1.732143 -0.017857193.000000 1.732051 -0.000092029573.000000 1.732051 0.0000000The square root is 1.732051
$ run program20traceInput a positive number8673.4756 [Enter]8673.476 4337.238 -4336.2388673.476 2169.619 -2167.6198673.476 1086.808 -1082.8118673.476 547.3945 -539.41388673.476 281.6198 -265.77478673.476 156.2092 -125.41068673.476 105.8670 -50.342198673.476 93.89751 -11.969448673.476 93.13462 -0.7628937
8673.476 93.13149 -0.0031280528673.476 93.13149 0.0000000The square root is 93.13149
-
8/10/2019 Basic Introduction to FORTRAN
35/81
A Basic Introduction to Programming in Fortran32
Example 7.3exis computed using the series expansion:
ex= 1 + x + x2/2! + x3/3! + x4/4! + ... + xi/i! + ...
It requires some thought to correctly initialise the variables and compute correctly following
terms. This is a good example where a program trace can help in debugging.
PROGRAM ExpX!-------------------------------------------------------------! Program to compute e^x by the series expansion:! e^x = 1 + x + x^2/2! + x^3/3! + x^4/4! + ... + x^i/i! + ...! As we soon run out of range when computing i! (i=13 gives! integer overflow) an alternative method is used to allow us! to include more terms; we see that:! the (i+1)th term = the (i)th term * x/i! New terms are computed and added to the series until a term! is less than 0.000001.!-------------------------------------------------------------IMPLICIT NONEINTEGER :: IREAL :: X, E, TermPRINT *, "Input a number."READ *, XTerm = 1. ! the zeroth termE = TermI = 0PRINT *, I, Term, E ! TRACEDO
I = I + 1 ! the next termTerm = Term * X/REAL(I)E = E + TermPRINT *, I, Term, E ! TRACEIF ( Term < 0.000001 ) EXIT
END DOPRINT *, "exp(", X, ") = ", E
END PROGRAM ExpX
Example execution:
Input a number.30 1.000000 1.0000001 3.000000 4.0000002 4.500000 8.5000003 4.500000 13.000004 3.375000 16.375005 2.025000 18.400006 1.012500 19.412507 0.4339286 19.846438 0.1627232 20.009159 0.05424107 20.0633910 0.01627232 20.0796711 0.004437906 20.0841012 0.001109476 20.0852113 0.0002560330 20.0854714 0.00005486422 20.0855315 0.00001097284 20.0855416 0.000002057408 20.08554
17 3.630721E-7 20.08554exp( 3.000000 ) = 20.08554
-
8/10/2019 Basic Introduction to FORTRAN
36/81
A Basic Introduction to Programming in Fortran33
Example 7.4The greatest common divisor of two integers is computed using Euclid's method. A program
trace shows Euclid's algorithm in action. Again, if the program does no work correctly the
program trace is a useful tool for debugging.
PROGRAM GCD!------------------------------------------------! Program to compute the greatest common divisor! of two integers using the Euclid method:!! Given a >= b!! 1. Compute the remainder c of the division a/b! 2. If c is zero then b is the gcd! 3. If c is not zero then! - replace a with b! - replace b with c! - go back to step 1.
!------------------------------------------------IMPLICIT NONEINTEGER :: A, B, C
PRINT *, "Input two integers."READ *, A, BDO
C = MOD(A,B) ! the remainder of A/BPRINT *, A, B, C ! TRACEIF (C==0) EXIT ! gcd is BA = BB = C
END DO
PRINT *, "The gcd is ", B
END PROGRAM GCD
Example program executions:
Input two integers.21 12
21 12 912 9 39 3 0
The gcd is 3
Input two integers.364 723
364 723 364723 364 359364 359 5359 5 4
5 4 14 1 0
The gcd is 1
If a program does not work as you intend it to, it is often useful to use a trace to help you find
the error.
-
8/10/2019 Basic Introduction to FORTRAN
37/81
A Basic Introduction to Programming in Fortran34
8. Formatted I/Oand File Processing
8.1 Introduction
In this section you will learn how to use the formatted PRINT,WRITEand READstatements and
study input from and output to files.
8.2 Formatted Output
We have already seen formatted output statements, for example
DO Deg = 0, 90, 5Rad = REAL(Deg)*Pi/180. ! convert to radians
PRINT '(1X,I2,2(1X,F8.6))', Deg, SIN(Rad), COS(Rad)END DO
Here, 1Xgives a blank space, I2 indicates that the value is a 2-digit type integer, and F8.6
indicates that the value is an 8-digit type real with 6 decimal places (the decimal point is
counted as one digit). The output (first 3 lines only) of this program is:
0 0.000000 1.0000005 0.087156 0.99619510 0.173648 0.984808.
The free-format version is less tidy and less easy to read (and compiler dependent):PRINT *, Deg, SIN(Rad), COS(Rad)
0 0.000000E+00 1.0000005 8.715575E-02 0.996194710 0.1736482 0.9848077.
The list of format descriptors in Fortran is:
Iw Bw Ow Zw Fw.d Ew.d ESw.d ENw.d Gw.a A"x.. x" Lw Tc nX /
Specifications of the width and number of decimal places can be omitted, for example:F:decimal notation, ES:scientific notation, EN:engineering notation (powers of 10
3) .
REAL :: A = 12345.67PRINT ('( F)'), A => 12345.6699219PRINT ('(ES)'), A => 1.2345670E+04PRINT ('(EN)'), A => 12.3456699E+03
8.3 Input/Output with Files
It is often useful to input data from a file and output data to a file. This is a achieved in
Fortran by using the OPENstatement to open a file for read/write, the READ()statement toread data from a file, and theWRITE()statement to write data to a file.
-
8/10/2019 Basic Introduction to FORTRAN
38/81
A Basic Introduction to Programming in Fortran35
The OPENstatementThe OPENstatement has many specifiers giving, for example, the file name, its unit number,
the intended action (read or write), and so on. We look at only a basic form of the statement:
OPEN(UNIT=unit-number, FILE="filename",ACTION="READorWRITE")
.. I/O statements
.CLOSE(unit-number)
The READandWRITEstatements
The READstatement is used to read data from a file, theWRITEstatement is used to write data
to a file, they have the following basic forms:
.READ(UNIT=unit-number, FMT="formatted-specifier")variable-list.
WRITE(UNIT=unit-number, FMT="formatted-specifier")data-list.
Example 8.1
The following program reads a list of values from a file values.dat; the I/O program
statements are shown in bold.
PROGRAM Mean_Value
IMPLICIT NONEINTEGER, PARAMETER :: N=8
INTEGER :: IREAL :: Value, Total=0.
OPEN(UNIT=1, FILE="values.dat", ACTION="READ")
DO I = 1, NREAD(UNIT=1, FMT=*) ValueTotal = Total + Value
END DO
CLOSE(1)
PRINT *, "The mean is ", Total/REAL(N)
END PROGRAM Mean_Value
values.dat
12.345.2
19.474.356.361.965.294.4
The program output is:
The mean is 53.62500
Here, the data file values.dat is opened and given the unit number 1, this unit number is
referenced instead of the name of the file in the READandWRITEstatements. Values are read
from unit 1 in free format (FMT=*) and stored, one line at a time, in variableValue. Finally the
file is closed. Note the optionalACTION="READ"specifier; this permits only reading from (and
not writing to) the file.
-
8/10/2019 Basic Introduction to FORTRAN
39/81
A Basic Introduction to Programming in Fortran36
Example 8.2
A data file scores.datcontains student names and three exam scores. The data is stored in
the file in four columns with the format:
abcdefghiIIIJJJKKK
where abcdefgh represents a 9 character name, III, JJJ, and KKKare three 3-digit integers
representing percentage scores. The content of this file is:
Semra 94 95 89Mustafa 66 71 75Ceyhun 42 37 52Asl 14 28 35Leyla 78 69 81
In Fortran this format is represented by '(A9,3I3)'. The following program reads the
student scores with the above format. Assuming that the number of records in the file is
unknown, the optional END=labelclause is used to exit the read loop when then end of thefile is reached.
PROGRAM Student_Scores
IMPLICIT NONECHARACTER(LEN=9) :: NameINTEGER :: MT1, MT2, MT3REAL :: Total
OPEN(UNIT=2, FILE="scores.dat", ACTION="READ")DO
READ(UNIT=2, FMT='(A9,3I3)', END=10)&Name, MT1, MT2, MT3Total = 0.3*MT1 + 0.3*MT2 + 0.4*MT3PRINT '(A9,3(1X,I3)," =>",F5.1,"%")',&Name, MT1, MT2, MT3, Total
END DO10 CONTINUECLOSE(2)
END PROGRAM Student_Scores
The program output is:
Semra 94 95 89 => 92.3%Mustafa 66 71 75 => 71.1%Ceyhun 42 37 52 => 44.5%Asl 14 28 35 => 26.6%Leyla 78 69 81 => 76.5%
The free format specification FMT=*maybe used for input from files if each data is separated
by one or more spaces. However, a record such as
A. Yilmaz 87 98100
will appear to a free formatted input as two character fields and two integer fields, whereasthe format '(A9,3I3)'will correctly read the data as
-
8/10/2019 Basic Introduction to FORTRAN
40/81
A Basic Introduction to Programming in Fortran37
Name="A. Yilmaz", MT1=87, MT2=98, MT3=100.
The output of this program can be sent to a file instead of the screen by opening a second file
and using theWRITEstatement. The modifications to the above program are indicated in bold
in the prorgam below:
PROGRAM Student_Scores
IMPLICIT NONECHARACTER(LEN=9) :: NameINTEGER :: MT1, MT2, MT3REAL :: Total
OPEN(UNIT=2, FILE="scores.dat", ACTION="READ")OPEN(UNIT=3, FILE="scores.out", ACTION="WRITE")
DOREAD(UNIT=2, FMT='(A9,3I3)', END=10)&
Name, MT1, MT2, MT3Total = 0.3*MT1 + 0.3*MT2 + 0.4*MT3WRITE(UNIT=3, FMT='(A9,3(1X,I3)," =>",F5.1,"%")') &Name, MT1, MT2, MT3, Total
END DO10 CONTINUE
CLOSE(2)CLOSE(3)
END PROGRAM Student_Scores
Notes:
The first file has the ACTION="READ" attribute and the second has the
ACTION="WRITE" attribute; it is therefore not possible to accidentally read from or
write to the wrong file.
The second file is given a different unit number, 3. Unit numbers 5 and 6 are reserved
for the keyboard and screen respectively so be careful using these numbers.
8.4 Non-advancing Output
A useful specifier in theWRITEstatement is theADVANCE='NO'specifier:
WRITE (*, FMT='(A)', ADVANCE='NO') "Input a number: "READ *, A
the read prompt is positioned at the end of the text instead of on the next line, for example:
Input a number: 23
-
8/10/2019 Basic Introduction to FORTRAN
41/81
A Basic Introduction to Programming in Fortran38
9. Subprograms:Programmer-Defined Functions
9.1 Introduction
We have seen intrinsic functions such as the SIN, ABS and SQRT functions (there are also
some intrinsic subroutines). Additional functions and subroutines can be defined by the
programmer, these are called programmer defined subprograms. In this section we will look
at how to write programmer defined functions, and in the following section we will look at
how to writeprogrammer defined subroutines. For simplicity we will only consider internal
subprograms. You can read about external subprogramsand moduleselsewhere; if you are
writing a large program then I advise that you make use of modules.
9.2 The Concept of a Function
A function accepts some inputs and outputs a result depending on the inputs. Every function
has a name and independent values of inputs. The inputs are called parameters or arguments.
Figure 9.1 show a box notation of a function.
Figure 9.1:Box notation of a function
A function may have one or more inputs but has to have only one output called return value.
Figure 9.2 shows the examples of one- and two-input functions:
Figure 9.2: The box notations of a one-input x function and a two-input yxyxf ),(
function
-
8/10/2019 Basic Introduction to FORTRAN
42/81
A Basic Introduction to Programming in Fortran39
9.3 Programmer-defined Functions
Fortran allows user to write this type of functions. The general form of a function must be:
data typeFUNCTION name(list of arguments)
...name= an expression
...END FUNCTION name
where
data type is the type of the function (or type of the return value) such as REAL
Function name is given by name
list of arguments (or local variables) are inputs to the function
For example a function that returns sum of two integers can be defined as follows:
Function declaration_________________ Identity card of the function_____________INTEGER FUNCTIONAdd(A,B)INTEGER, INTENT(IN) :: A,BAdd= A+BEND FUNCTIONAdd
Type INTEGER
Name Add
Input parameters A,B
Return value A+B
9.4 Internal and External Functions
Fortran 90/95 provides two basic type of function:
Internal Functions
They are placed after the main program section between a CONTAINSstatement and the END
PROGRAMstatement.
+----------------------------+| PROGRAM Main || || IMPLICIT NONE || REAL :: X || INTEGER :: Y |
| . || X = Fun1(Z) || Y = Fun2(Z) || . || || CONTAINS || || REALFUNCTION Fun1(A) || . || END FUNCTION Fun1 || || INTEGERFUNCTION Fun2(B)|| . || END FUNCTION Fun2 || |
| END PROGRAM Main |+----------------------------+
Notes:
Fun1and Fun2are internal functions.
They are used in the same way as for intrinsic
functions.
The IMPLICITNONEstatement applies to both themain section and the internal functions.
Data declared in the main program section is also
visible in the functions (it isglobal).
Data declared in a function is only visible in that
function, it is localto the function and so is not seen
by the rest of the program unit.
Arguments can be given the INTENT(IN)attribute to
protect the variable from being changed accidentallyby the function.
-
8/10/2019 Basic Introduction to FORTRAN
43/81
A Basic Introduction to Programming in Fortran40
External Functions
They are placed after the main program section (i.e. after the END PROGRAMstatement)
+----------------------------+| PROGRAM Main || || IMPLICIT NONE || REAL :: X, Fun1 || INTEGER :: Y, Fun2 || . || X = Fun1(Z) || Y = Fun2(Z) || . || || END PROGRAM Main || || || REALFUNCTION Fun1(A) |
| . || END FUNCTION Fun1 || || INTEGERFUNCTION Fun2(B) || . || END FUNCTION Fun2 |+----------------------------+
Notes:
Fun1and Fun2are external functions.They are used in the same way as for intrinsic
functions. You have to declare functions in main
program.
The IMPLICITNONEstatement does not apply to
both the main section and the external functions.
Data declared in the main program section is not
visible in the functions.
Data declared in a function is only visible in thatfunction, it is localto the function and so is not seen
by the rest of the program unit.
Arguments can be given the INTENT(IN)attribute to
protect the variable from being changed accidentally
by the function.
As an example the functionAdddefined at the begining of this section can be used as follows:
Usage of an internal function____________ Usage of an external function_____________PROGRAM SummationIMPLICIT NONEINTEGER :: I,J,K
PRINT *,"Input two integers:"READ *,I,JK = Add(I,J)PRINT *,"The sum is ",K
CONTAINS
INTEGER FUNCTION Add(A,B)INTEGER, INTENT(IN) :: A,BAdd = A+BEND FUNCTION Add
END PROGRAM Summation
PROGRAM SummationIMPLICIT NONEINTEGER :: I,J,K,Add
PRINT *,"Input two integers:"READ *,I,JK = Add(I,J)PRINT *,"The sum is ",K
END PROGRAM Summation
INTEGER FUNCTION Add(A,B)INTEGER, INTENT(IN) :: A,BAdd = A+BEND FUNCTION Add
The output of both program section is:
Input two integers:1422
The sum is 36
Note that, we will consider only internal functions in the course.
-
8/10/2019 Basic Introduction to FORTRAN
44/81
A Basic Introduction to Programming in Fortran41
9.5 Examples of Internal Functions:
Function references and definitions are indicated in boldface.
Example 9.1Function to convert degrees to radians.
In this exmple we will consider the conversion of angles among degrees and radians.
The formula for conversion is defined by:
RD
180
whereDis the angle measured in degrees andRis in radians and the number 141592.3
PROGRAM Degrees2Radians
IMPLICIT NONEREAL :: Degrees ! inputREAL :: Radians ! output
PRINT *, "Input the angle in degrees"READ *, Degrees
Radians = Rad(Degrees)
PRINT *, Degrees, " degrees = ", Radians, "Radians."
CONTAINS
REAL FUNCTION Rad(A)REAL, INTENT(IN) :: AREAL, PARAMETER :: Pi = 3.141593Rad=A* Pi/180.
END FUNCTION Rad
END PROGRAM Degrees2Radians
Example execution:
Input the angle in degrees90
90.00000 degrees = 1.570796 Radians.
Notes:
The function is declared as type real i.e. it returns a type real value.
As for intrinsic functions, an internal function can take for its arguments: variables,
constants, or expressions.
The IMPLICITNONE statement applies to the whole program unit (the main section
and to the function sections); therefore, the argument variable A must be declared
somewhere in the program unit. It this case it is declared inside the function (and so is
local to the function) and is given the INTENT(IN)attribute, this is a safer policy.
-
8/10/2019 Basic Introduction to FORTRAN
45/81
A Basic Introduction to Programming in Fortran42
Example 9.2Functions to convert Celsius to Fahrenheit, and Fahrenheit to Celsius.
The formula for converting temperature measured in Fahrenheit to Celcius is:
)32(9
5FC
whereFis the Fahrenheit temperature and Cis the Celcius temperature. Suppose we wish
to define and use a function that performs this conversion.
PROGRAM Temp_Conv
IMPLICIT NONE
PRINT *, Fahrenheit(50.)
PRINT *, Celsius(400.)
CONTAINS
REAL FUNCTION Fahrenheit(X)REAL, INTENT(IN) :: XFahrenheit= X*1.8 + 32.
END FUNCTION Fahrenheit
REAL FUNCTION Celsius(X)REAL, INTENT(IN) :: XCelsius= (X-32.)/1.8
END FUNCTION Celsius
END PROGRAM Temp_Conv
Note that we may include more than one programmer-defined function. The output is:
122.0000204.4445
Example 9.3A Gaussian function.
PROGRAM GaussianIMPLICIT NONE
REAL :: X, M, S
PRINT *, "Input the position X, mean M, and sigma S"READ *, X, M, SPRINT *, Gauss(X, M, S)
CONTAINS
REAL FUNCTION Gauss(Position, Mean, Sigma)REAL, INTENT(IN) :: Position, Mean, SigmaREAL, PARAMETER :: TwoPi = 6.283185Gauss= EXP( -0.5*((Position-Mean)/Sigma)**2 ) / &(Sigma*SQRT(TwoPi))
END FUNCTION Gauss
END PROGRAM Gaussian
-
8/10/2019 Basic Introduction to FORTRAN
46/81
A Basic Introduction to Programming in Fortran43
Example execution:
Input the position X, mean M, and sigma S1.8 1.0 0.60.2733502
Notes:
The number and order of the actual argumentsmust be the same as that of the formal
arguments, in this case there are three arguments representing the position, mean, and
standard deviation (in that order).
Be careful not misspell variable names inside a function, if the variable exists in themain program section then it will be valid and used without a run-time error!
Similarly, all variables you use in the function should be declared in the function, in
this way you will not modify a global variable by mistake.
Example 9.4 A factorial function
PROGRAM N_Factorial
IMPLICIT NONEINTEGER :: IDO I =-2,14
PRINT *, I, Factorial(I)END DO
CONTAINS
INTEGER FUNCTION Factorial(N)INTEGER, INTENT(IN) :: NINTEGER :: IIF (N< 0 .OR.N> 12 ) THEN
Factorial= 0ELSE
Factorial= 1DO I = 2,N
Factorial= Factorial*IEND DO
END IFEND FUNCTION Factorial
END PROGRAM N_Factorial
The output is: -2 0-1 00 11 12 23 64 245 1206 7207 50408 403209 362880
10 362880011 3991680012 47900160013 0
14 0
-
8/10/2019 Basic Introduction to FORTRAN
47/81
A Basic Introduction to Programming in Fortran44
Notes:
Factorialis an integer function, i.e. it returns an integer value.
The argument of the function is also integer.
Identifier Iis used both in the main program section and in the function. It therefore
must be declared also in the function (thus making it local to the function) otherwise
the two data will conflict.If the argumentNis negative or too large then the function does not return an
incorrect result, instead it indicates that there is a problem by returning a zero value.
This condition can be checked for by the programmer.
9.6 Good Programming Practice:
Declare all function variables; this makes them local so that they do not affect
variables of the same name in the main program section.
Give all function arguments the INTENT(IN) attribute. If, by mistake, you try to
modify the argument value inside the function then an error will occur at compilation
time.
Be careful not to misspell variable names inside a function, if the variable exists in
the main program section then it will be valid and used without a run-time error!
(modulesare safer in this respect).
-
8/10/2019 Basic Introduction to FORTRAN
48/81
A Basic Introduction to Programming in Fortran45
10. Subprograms:Programmer-defined Subroutines
10.1 Introduction
As well as programmer defined functions, a Fortran program can also contain programmer
defined subroutines. Unlike functions, subroutines do not return a value. Instead, a subroutine
contains a separate program section that can be calledat any point in a program via the CALL
statement. This is useful if the program section that the subroutine contains is to be executed
more than once. It also helps the programmer to organise the program in a modular form.
In this guide we will only consider internal subroutines. You can read about external
subroutinesand moduleselsewhere; if you are writing a large program then I advise that you
make use of modules.
10.2 The Concept of a Subroutine
A subroutine accepts no input or one or more inputs and may output no or one or more many
outputs. This is assumed to be many purpose function. Figure 10.1 show a box notation of a
subroutine:
Figure 10.1:Box notation of a subroutine
The advantage of using a subroutine is, it may have more than one return value. This is not
the case in a function. Figure 10.2 shows the examples of subroutines:
Figure 10.2: The box notations of one-input and two-output subroutine S, and
two-input and two-output subroutine Rect.
9.3 Programmer-defined Subroutine
-
8/10/2019 Basic Introduction to FORTRAN
49/81
A Basic Introduction to Programming in Fortran46
The general form of a subrotine type subprogram is:
SUBROUTINE name(list of arguments)..
.END SUBROUTINE name
where
Subroutine name is given by name
list of arguments (or local variables) are inputs to the subroutine
For example, a subroutine that returns area and circumference of a rectangle with sides aand
bcan defined as follows:
Subroutine declaration_________________ Identity card of the function_____________SUBROUTINE Rect(A,B,Area,Circ)REAL, INTENT(IN) :: A,BREAL, INTENT(OUT) :: Area,CircArea= A*BCirc= A+B
END SUBROUTINE Rect
Type -
Name Rect
Input parameters A,B
Output parameters Area, Circ
10.4 Internal and External Subroutines
Internal Subroutine
As for internal functions, internal subroutines are placed after the main program sectionbetween a CONTAINSstatement and the END PROGRAMstatement.
+----------------------------+| PROGRAM Main || || IMPLICIT NONE || . || CALL Sub1(X,Y) || CALL Sub2(X,Z) || . || || CONTAINS || || SUBROUTINE Sub1(A,B) || . || END SUBROUTINE Sub1 || || SUBROUTINE Sub2(A,B) || . || END SUBROUTINE Sub2 || || END PROGRAM Main |+----------------------------+
Notes:
Sub1and Sub2are external functions.
They are used in the same way as for intrinsic
functions.
The IMPLICITNONEstatement applies to both the
main section and the internal subroutines.
Data declared in the main program section is visible
in the subroutines.
Arguments can be given INTENT(IN/OUT/INOUT)
attributes attributes to make the programmers intent
clear.
-
8/10/2019 Basic Introduction to FORTRAN
50/81
A Basic Introduction to Programming in Fortran47
External Subroutine
They are placed after the main program section (i.e. after the END PROGRAMstatement)
+----------------------------+| PROGRAM Main || || IMPLICIT NONE || . || CALL Sub1(X,Y) || CALL Sub2(X,Z) || . || || END PROGRAM Main || || || SUBROUTINE Sub1(A,B) || . || END SUBROUTINE Sub1 |
| || SUBROUTINE Sub2(A,B) || . || END SUBROUTINE Sub2 |+----------------------------+
Notes:
Sub1and Sub2are external functions.They are used in the same way as for intrinsic
functions.
The IMPLICITNONEstatement does not apply to
both the main section and the external subroutines.
Data declared in the main program section is not
visible in the functions.
Arguments can be given INTENT(IN/OUT/INOUT)
attributes attributes to make the programmers intentclear.
As an example the subroutine Rectcan be implemented as follows:
Usage of an internal subroutine__________ Usage of an external subroutine____________
PROGRAM RectangleIMPLICIT NONEREAL :: X,Y,Alan,Cevre
PRINT *,"Input the sides:"READ *,X,YCALL Rect(X,Y,Alan,Cevre)PRINT *,"Area is ",AlanPRINT *,"Circum. is ",Cevre
CONTAINS
SUBROUTINE Rect(A,B,Area,Circ)REAL, INTENT(IN) :: A,BREAL, INTENT(OUT) :: Area,CircArea = A*BCirc = A+BEND SUBROUTINE Rect
END PROGRAM Rectangle
PROGRAM RectangleIMPLICIT NONEREAL :: X,Y,Alan,Cevre
PRINT *,"Input the sides:"READ *,X,YCALL Rect(X,Y,Alan,Cevre)PRINT *,"Area is ",AlanPRINT *,"Circum. is ",Cevre
END PROGRAM Rectangle
SUBROUTINE Rect(A,B,Area,Circ)REAL, INTENT(IN) :: A,BREAL, INTENT(OUT) :: Area,CircArea = A*BCirc = A+BEND SUBROUTINE Rect
The output of both program is:
Input the sides:4.0 2.0
Area is 8.000000Circum. is 6.000000
Note that, we will consider only internal functions in the course.
-
8/10/2019 Basic Introduction to FORTRAN
51/81
A Basic Introduction to Programming in Fortran48
Data can be passed to, and return from, the subroutine via arguments. As for function
arguments, arguments in subroutines can be given INTENT attributes; they include the
INTENT(IN), INTENT(OUT), and INTENT(INOUT)attributes, examples are given below:
10.3 Examples of Subroutines:Subroutine references and definitions are indicated in boldface.
Example 10.1The following program inputs the radius of a sphere and then employs an internal subroutine
to compute the sphere's surface area and volume, and output the results.
PROGRAM Sphere!-----------------------------------------------------! Program to compute the volume and surface area of a! sphere radius R. An internal subroutine is emloyed.!-----------------------------------------------------
IMPLICIT NONEREAL :: Radius
PRINT *, "Input the radius of the sphere."READ *, Radius
CALL Results(Radius)
CONTAINS
SUBROUTINE Results(R)
REAL, INTENT(IN) :: RREAL, PARAMETER :: Pi=3.141593REAL :: Area, Volume
Area = 4.*Pi*R**2Volume = 4./3.*Pi*R**3
PRINT *, "Surface area is ", Area
-
8/10/2019 Basic Introduction to FORTRAN
52/81
A Basic Introduction to Programming in Fortran49
PRINT *, "Volume is ", Volume
END SUBROUTINE Results
END PROGRAM Sphere
Example execution:
Input the radius of the sphere.12.6Surface area is 1995.037Volume is 8379.157
Notes:
It is not necessary to place an IMPLICIT NONEstatement in an internal subroutine as
the statement in the main program section applies to the whole program unit.
In this subroutine the argument has the INTENT(IN)attribute as it is only intended to
pass into the subroutine; this is illustrated below.
Example 10.2In the following example, we will consider the calculation of the twist factor of a yarn. Twist
Factor, Tf, of a yarn is given by:
1000
mNTf
whereN(turn/m) is the number of twist of a yarn per unit length and mis measured in tex (a
yarn count standard) that is mass in grams of a yarn whose length is 1 km. The program first
needs a value of m. Then, the value of of Tfis calculated for different value ofNwhich takes
values from 100 to 1000 with step 100.
PROGRAM MainIMPLICIT NONEREAL :: Tf,mINTEGER :: N
PRINT *,"Input the value of m (tex)"READ *,m
DO N=100,1000,100CALL TwistFactor(N,m,Tf)PRINT *,N,Tf
END DO
-
8/10/2019 Basic Introduction to FORTRAN
53/81
-
8/10/2019 Basic Introduction to FORTRAN
54/81
A Basic Introduction to Programming in Fortran51
Example execution:
Input the length of the side of the cube.12.The volume of the cube is 1728.000
The surface area of the cube is 864.0000
Note:
There are three arguments in the subroutine. The first argument L has the INTENT(IN)
attribute as it passes data into the subroutine. The second and third argumentsVandAhave
the INTENT(OUT)attributes as they are only intended to pass data out of the subroutine. This
is illustrated below:
Note that the number of and order of the
arguments should be the same in the call (the
actual arguments) and in the subroutine (the
formal arguments).
Example 10.4
The following program illustrates the use of an argument with an INTENT(INOUT)attribute.
PROGRAM Money_Owed
IMPLICIT NONEREAL :: Owed = 1000., Payment
DOPRINT *, "Input the payment"READ *, PaymentCALL Payback(Owed, Payment)! Subtract from the money owed.IF ( Owed == 0. ) EXIT ! Repeat until no more money is owed.
END DO
CONTAINS
SUBROUTINE Payback(Owed ,Payment)
REAL, INTENT(INOUT) :: OwedREAL, INTENT(IN) :: Payment
REAL :: Overpaid = 0.
Owed= Owed- Payment
IF ( Owed< 0. ) THENOverpaid = - OwedOwed= 0.
END IF
PRINT *, "Payment made ", Payment, ", amount owed is now ", OwedIF ( Overpaid /= 0. ) PRINT *, "You over paid by ", Overpaid
END SUBROUTINE Payback
END PROGRAM Money_Owed
-
8/10/2019 Basic Introduction to FORTRAN
55/81
A Basic Introduction to Programming in Fortran52
Example execution:
Input the payment350Payment made 350.0000 , amount owed is now 650.0000Input the payment350Payment made 350.0000 , amount owed is now 300.0000Input the payment350Payment made 350.0000 , amount owed is now 0.000000You over paid by 50.00000
Notes:
Argument Owed has the INTENT(INOUT)
attribute; it passes a value into the subroutine
which then passes it back via the same
argument after modifying it. Argument
Paymentonly passes data into the subroutineand so has the INTENT(IN) attribute. This is
illustrated rigth.
10.4 Good Programming Practice:
Declare all arguments used in the subroutine; this makes them local so that they donot affect variables of the same name in the main program section.
Give all arguments the appropriate INTENT(IN), INTENT(OUT)or INTENT(INOUT),
attribute.
Be careful not misspell variable names inside a subroutine, if the variable exists in the
main program section then it will be valid and used without a run-time error!(modulesare safer in this respect).
-
8/10/2019 Basic Introduction to FORTRAN
56/81
-
8/10/2019 Basic Introduction to FORTRAN
57/81
A Basic Introduction to Programming in Fortran54
11.3 TheWHEREStatement and Construct
We can make the whole array assignment conditional with the WHEREstatement. For example
we have an array Vof values that we want to take the square-root of, but only for positive
values:
WHERE ( V >= 0. ) V = SQRT(V)
This is equivalent to
DO I = 1, NIF ( V(I) >= 0. ) V(I) = SQRT(V(I))
END DO
where N is the size of the array. Or, we have an array Vof values that we want to take the
reciprocal of, but only for non-zero values:
WHERE (V /= 0. ) V = 1./V
This is equivalent to
DO I = 1, NIF ( V(I) /= 0. ) V(I) = 1./V(I)
END DO
where Nis the size of the array.
The WHERE construct allows for a block of statements and the inclusion of an ELSEWHERE
statement:
WHERE ( V >= 0. )V = SQRT(V)
ELSEWHEREV = -1.
ENDWHERE
11.4 Array Sections
We can write the whole array assignment
Weight = Mass * 9.81
in the form of an array section:
Weight(1:N) = Mass(1:N) * 9.81
where Nis the size of the array.
Here the section 1:Nrepresents the elements 1to N. A part of an array (an array section) can
be written, for example, as:
Weight(2:5) = Mass(2:5) * 9.81
-
8/10/2019 Basic Introduction to FORTRAN
58/81
A Basic Introduction to Programming in Fortran55
which is equivalent to
DO I = 2, 5Weight(I) = Mass(I) * 9.81
END DO
Array sections are also useful for initialising arrays, for example:
A(1:4) = 0.A(5:10) = 1.
is equivalent to the array constant assignment:
A = (/ 0., 0., 0., 0., 1., 1., 1., 1., 1., 1. /)
A third index indicates increments:
A(2:10:2) = 5.
is equivalent to
DO I = 2, 10, 2A(I) = 5.
END DO
More examples of array sections are shown below. The 10 elements of array Aare representedby a series of boxes. The elements referenced by the array section are shaded.
11.5 Array Indices
In the following array declaration
REAL :: A(9)
the index for the elements of the array go from 1 to 9. The index does not have to begin at 1, it
can be zero or even negative; this is achieved with the ":"symbol:
REAL :: A(0:8), B(-4:4), C(-8:0)
All the above arrays have 9 elements. The index ofAruns from 0 to 8, the index of B runs
from -4 to 4 (including zero), and the index of Cruns from -8 to 0.
-
8/10/2019 Basic Introduction to FORTRAN
59/81
A Basic Introduction to Programming in Fortran56
11.6 Assignment using Implied Loops
An array can be assigned using an implied loop, For example
A = (/ (I*0.1, I=1,9)/)
assigns to array Athe values:
0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9
The implied loop (in bold) appears in an array constant.
11.7 Multi-dimensional Arrays
In the array declaration
REAL :: A(9)
array Ahas one dimension (one index); such an array is called a vector. An array can havemore than one dimension, for example the declaration of a two-dimensional array Bmay be as
follows:
REAL :: B(9,4)
A two-dimensional array has two indices and is called a matrix. The above vector and matrix
are visualised below, vector Ahas 9 elements, matrix Bhas 36 elements arranged in 9 rowsand 4 columns:
An array can have many dimensions, though it is not common to go above three-dimensions.
11.8 Array Input/Output
We will now look at input and output of arrays. Only one-dimensional arrays will be
considered; for two-dimensional arrays the principle is the same except that you need to think
about whether the I/O should be row-wise or column-wise.
Consider an array Adeclared as:
REAL :: A(9)
The array can be input and output as a whole array:
-
8/10/2019 Basic Introduction to FORTRAN
60/81
A Basic Introduction to Programming in Fortran57
READ *, APRINT *, A
which is equivalent to the implied loops:
READ *, ( A(I), I = 1, 9 )PRINT *, ( A(I), I = 1, 9 )
or individual elements can be referenced:
READ *, A(4)PRINT *, A(4)
There are various methods for output of arrays; consider the array:
REAL :: A(9) = (/ (I*0.1, I = 1, 9) /)
Array Atakes the values 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, and 0.9 . The free format
output of the whole array
PRINT *, A
which is equivalent to the implied loop:
PRINT *, (A(I), I = 1, 9)
will appear something like:
0.1000000 0.2000000 0.3000000 0.4000000 0.50000000.6000000 0.7000000 0.8000000 0.9000000
A formatted output, for example,
PRINT '(9(F3.1,1X))', A
gives:
0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9
If the multiplier is omitted then the output will be given line by line; i.e.
PRINT '(F3.1,1X)', A
gives:0.10.20.30.40.50.60.70.8
0.9
-
8/10/2019 Basic Introduction to FORTRAN
61/81
A Basic Introduction to Programming in Fortran58
This is equivalent to the DOloop:
DO I = 1, 9PRINT '(F3.1,1X)', A(I)
END DO
Array sections can also be referenced, for example:
PRINT '(9(F3.1,1X))', A(3:8)
gives:0.3 0.4 0.5 0.6 0.7 0.8
Note that the multiplier in the format specifier can be 6 or greater.
11.9 Intrinsic Functions for Arrays
Most intrinsic functions that we use for scalars, for example SIN, INT, and ABS, are
elemental; i.e. they can also apply to arrays. For example:
REAL :: A= (/ 0.2, 0.3, 0.4, 0.5, 0.6 /)PRINT *, SIN(A)
gives0.1986693 0.2955202 0.3894183 0.4794255 0.5646425
There are, in addition to the elemental functions, intrinsic functions whose arguments are
specifically arrays. Some them are listed below (see elsewhere for a more complete list).
Function DescriptionMAXVAL(A) Gives the maximum value of array AMINVAL(A) Gives the minimum value of array AMAXLOC(A) Index location of maximum value of AMINLOC(A) Index location of minimum value of APRODUCT(A) Gives product of the values in array ASIZE(A) Gives the number of values of array ASUM(A) Gives the sum of the values in array AMATMUL(A,B) Gives the cross product of arrays Aand B
TRANSPOSE(A) Gives the transpose of array A
11.10