Fortran 90 BasicsFortran 90 Basics
I don’t know what the programming languageI don t know what the programming language
of the year 2000 will look like, but I know it
will be called FORTRAN.
1
Charles Anthony Richard Hoare
Fall 2010
F90 Program StructureF90 Program Structure
A Fortran 90 program has the following form:A Fortran 90 program has the following form:
program-name is the name of that program
specification-part execution-part andspecification part, execution part, and
subprogram-part are optional.
Although IMPLICIT NONE is also optional, this isg p ,
required in this course to write safe programs.
PROGRAM program-name
IMPLICIT NONE
[ ifi ti t][specification-part]
[execution-part]
[subprogram-part]
2
[subprogram part]
END PROGRAM program-name
Program CommentsProgram Comments
Comments start with a !Comments start with a !
Everything following ! will be ignored
This is similar to // in C/C++This is similar to // in C/C++
! This is an example
!
PROGRAM Comment
..........
READ(*,*) Year ! read in the value of Year
....................
Year = Year + 1 ! add 1 to Year
..........
END PROGRAM Comment
3
END PROGRAM Comment
Continuation LinesContinuation Lines
Fortran 90 is not completely format-free!Fortran 90 is not completely format free!
A statement must starts with a new line.
If t t t i t l t fit li it hIf a statement is too long to fit on one line, it has
to be continued.
The continuation character is &, which is not
part of the statement.
Total = Total + &
Amount * Payments
! Total = Total + Amount*Payments! Total = Total + Amount*Payments
PROGRAM &
i i i
4
ContinuationLine
! PROGRAM ContinuationLine
AlphabetsAlphabets
Fortran 90 alphabets include the following:Fortran 90 alphabets include the following:
Upper and lower cases letters
Di itDigits
Special characters
space
' "
( ) * + - / : =
_ ! & $ ; < >
% ? , .
5
Constants: 1/6Constants: 1/6
A Fortran 90 constant may be an integer, real,A Fortran 90 constant may be an integer, real,
logical, complex, and character string.
We will not discuss complex constantsWe will not discuss complex constants.
An integer constant is a string of digits with an
optional sign: 12345 345 +789 +0optional sign: 12345, -345, +789, +0.
6
Constants: 2/6Constants: 2/6
A real constant has two forms, decimal andA real constant has two forms, decimal and
exponential:
In the decimal form a real constant is aIn the decimal form, a real constant is a
string of digits with exactly one decimal
point A real constant may include anpoint. A real constant may include an
optional sign. Example: 2.45, .13, 13.,
-0 12 - 120.12, .12.
7
Constants: 3/6Constants: 3/6
A real constant has two forms, decimal andA real constant has two forms, decimal and
exponential:
In the exponential form a real constantIn the exponential form, a real constant
starts with an integer/real, followed by a E/e,
followed by an integer (i e the exponent)followed by an integer (i.e., the exponent).
Examples:
12E3 (12 103) 12e3 ( 12 103)12E3 (12 103), -12e3 (-12 103),
3.45E-8 (3.45 10-8), -3.45e-8
( 3 45 10-8)(-3.45 10-8).
0E0 (0 100=0). 12.34-5 is wrong!
8
Constants: 4/6Constants: 4/6
A logical constant is either .TRUE. or .FALSE.g S
Note that the periods surrounding TRUE and
FALSE are required!FALSE are required!
9
Constants: 5/6Constants: 5/6
A character string or character constant is aA character string or character constant is a
string of characters enclosed between two
double quotes or two single quotes. Examples:double quotes or two single quotes. Examples:
“abc”, ‘John Dow’, “#$%^”, and ‘()()’.
The content of a character string consists of allThe content of a character string consists of all
characters between the quotes. Example: The
content of ‘John Dow’ is John Dowcontent of John Dow is John Dow.
The length of a string is the number of
h t b t th t Th l th fcharacters between the quotes. The length of
‘John Dow’is 8, space included.
10
Constants: 6/6Constants: 6/6
A string has length zero (i.e., no content) is ang g ( , )
empty string.
If single (or double) quotes are used in a string,g ( ) q g,
then use double (or single) quotes as delimiters.
Examples: “Adam’s cat” and ‘I said
“go away”’.
Two consecutive quotes are treated as one!
‘Lori’’s Apple’ is Lori’s Apple
“double quote””” is double quote”
`abc’’def”x’’y’ is abc’def”x’y
“abc””def’x””y” is abc”def’x”y
11
abc def x y is abc def x y
Identifiers: 1/2Identifiers: 1/2
A Fortran 90 identifier can have no more thanA Fortran 90 identifier can have no more than
31 characters.
The first one must be a letter The remainingThe first one must be a letter. The remaining
characters, if any, may be letters, digits, or
underscoresunderscores.
Fortran 90 identifiers are CASE INSENSITIVE.
Examples: A, Name, toTAL123, System_,
myFile_01, my_1st_F90_program_X_.
Identifiers Name, nAmE, naME and NamE are
the same.
12
Identifiers: 2/2Identifiers: 2/2
Unlike Java, C, C++, etc, Fortran 90 does not, , , ,
have reserved words. This means one may use
Fortran keywords as identifiers.
Therefore, PROGRAM, end, IF, then, DO, etc
may be used as identifiers. Fortran 90
compilers are able to recognize keywords from
their “positions” in a statement.
Yes, end = program + if/(goto –
while) is legal!
However, avoid the use of Fortran 90 keywords
as identifiers to minimize confusion.
13
Declarations: 1/3Declarations: 1/3
Fortran 90 uses the following for variableFortran 90 uses the following for variable
declarations, where type-specifier is one
of the following keywords: INTEGER, REAL,g y , ,
LOGICAL, COMPLEX and CHARACTER, and
list is a sequence of identifiers separated byq p y
commas.
type-specifier :: listtype specifier :: list
Examples:
INTEGER :: Zip, Total, counter
REAL :: AVERAGE, x, Difference
LOGICAL :: Condition, OK
14
COMPLEX :: Conjugate
Declarations: 2/3Declarations: 2/3
Character variables require additionalCharacter variables require additional
information, the string length:
Keyword CHARACTER must be followed byKeyword CHARACTER must be followed by
a length attribute (LEN = l) , where l is
the length of the stringthe length of the string.
The LEN= part is optional.
If the length of a string is 1, one may use
CHARACTER without length attribute.
Other length attributes will be discussed
later.
15
Declarations: 3/3Declarations: 3/3
Examples:Examples:
CHARACTER(LEN=20) :: Answer, Quote
Variables Answer and Quote can holdVariables Answer and Quote can hold
strings up to 20 characters.
CHARACTER(20) :: Answer, Quote is
the same as above.
CHARACTER :: Keypress means variable
Keypress can only hold ONE character (i.e.,
length 1).
16
The PARAMETER Attribute: 1/4The PARAMETER Attribute: 1/4
A PARAMETER identifier is a name whose value
cannot be modified. In other words, it is a
named constant.named constant.
The PARAMETER attribute is used after the type
keywordkeyword.
Each identifier is followed by a = and followed
b l f th t id tifiby a value for that identifier.
INTEGER PARAMETER :: MAXIMUM = 10INTEGER, PARAMETER :: MAXIMUM = 10
REAL, PARAMETER :: PI = 3.1415926, E = 2.17828
LOGICAL, PARAMETER :: TRUE = .true., FALSE = .false.
17
The PARAMETER Attribute: 2/4The PARAMETER Attribute: 2/4
Since CHARACTER identifiers have a lengthg
attribute, it is a little more complex when used
with PARAMETER.
Use (LEN = *) if one does not want to count
the number of characters in a PARAMETERthe number of characters in a PARAMETER
character string, where = * means the length of
this string is determined elsewherethis string is determined elsewhere.
CHARACTER(LEN=3), PARAMETER :: YES = “yes” ! Len = 3y
CHARACTER(LEN=2), PARAMETER :: NO = “no” ! Len = 2
CHARACTER(LEN=*), PARAMETER :: &
PROMPT = “What do you want?” ! Len = 17
18
The PARAMETER Attribute: 3/4The PARAMETER Attribute: 3/4
Since Fortran 90 strings are of fixed length, oneSince Fortran 90 strings are of fixed length, one
must remember the following:
If a string is longer than the PARAMETERIf a string is longer than the PARAMETER
length, the right end is truncated.
If a string is shorter than the PARAMETERIf a string is shorter than the PARAMETER
length, spaces will be added to the right.
CHARACTER(LEN=4), PARAMETER :: ABC = “abcdef”
CHARACTER(LEN=4), PARAMETER :: XYZ = “xy”
a b c dABC = x yXYZ =
19
a b c dABC yXYZ
The PARAMETER Attribute: 4/4The PARAMETER Attribute: 4/4
By convention, PARAMETER identifiers use ally ,
upper cases. However, this is not mandatory.
For maximum flexibility constants other than 0For maximum flexibility, constants other than 0
and 1 should be PARAMETERized.
A PARAMETER is an alias of a value and is not aA PARAMETER is an alias of a value and is not a
variable. Hence, one cannot modify the content of
a PARAMETER identifiera PARAMETER identifier.
One can may a PARAMETER identifier anywhere
in a program. It is equivalent to replacing the
identifier with its value.
20
The value part can use expressions.
Variable Initialization: 1/2Variable Initialization: 1/2
A variable receives its value withA variable receives its value with
Initialization: It is done once before the
program runsprogram runs.
Assignment: It is done when the program
t i t t t texecutes an assignment statement.
Input: It is done with a READ statement.
21
Variable Initialization: 2/2Variable Initialization: 2/2
Variable initialization is very similar to what weVariable initialization is very similar to what we
learned with PARAMETER.
A variable name is followed by a = followed byA variable name is followed by a =, followed by
an expression in which all identifiers must be
constants or PARAMETERs defined previouslyconstants or PARAMETERs defined previously.
Using an un-initialized variable may cause un-
t d ti di t ltexpected, sometimes disastrous results.
REAL :: Offset = 0.1, Length = 10.0, tolerance = 1.E-7
CHARACTER(LEN=2) :: State1 = "MI", State2 = "MD“
INTEGER, PARAMETER :: Quantity = 10, Amount = 435
INTEGER, PARAMETER :: Period = 3
22
INTEGER :: Pay = Quantity*Amount, Received = Period+5
Arithmetic OperatorsArithmetic Operators
There are four types of operators in Fortran 90:There are four types of operators in Fortran 90:
arithmetic, relational, logical and character.
The following shows the first three types:The following shows the first three types:
Type Operator Associativity
Arithmetic
** right to left
* / left to right
+ - left to right+ - left to right
Relational < <= > >= == /= none
.NOT. right to left
Logical
g f
.AND. left to right
.OR. left to right
23
.EQV. .NEQV. left to right
Operator PriorityOperator Priority
** is the highest; * and / are the next, followedg ; / ,
by + and -. All relational operators are next.
Of the 5 logical operators EQV and NEQVOf the 5 logical operators, .EQV. and .NEQV.
are the lowest.
Type Operator Associativity hi hType Operator Associativity
Arithmetic
** right to left
* / left to right
highest
priority
+ - left to right
Relational < <= > >= == /= none
Logical
.NOT. right to left
.AND. left to right
.OR. left to right
24
.OR. left to right
.EQV. .NEQV. left to right
Expression EvaluationExpression Evaluation
Expressions are evaluated from left to right.Expressions are evaluated from left to right.
If an operator is encountered in the process of
evaluation its priority is compared with that ofevaluation, its priority is compared with that of
the next one
if th t i l l t th tif the next one is lower, evaluate the current
operator with its operands;
if the next one is equal to the current, the
associativity laws are used to determine
which one should be evaluated;
if the next one is higher, scanning continues
25
Single Mode ExpressionSingle Mode Expression
A single mode arithmetic expression is anA single mode arithmetic expression is an
expression all of whose operands are of the
same type.same type.
If the operands are INTEGERs (resp., REALs),
the result is also an INTEGER (resp REAL)the result is also an INTEGER (resp., REAL).
1.0 + 2.0 * 3.0 / ( 6.0*6.0 + 5.0*44.0) ** 0.25
--> 1.0 + 6.0 / (6.0*6.0 + 5.0*44.0) ** 0.25
--> 1.0 + 6.0 / (36.0 + 5.0*44.0) ** 0.25
--> 1.0 + 6.0 / (36.0 + 220.0) ** 0.25
1 0 6 0 / 256 0 ** 0 25--> 1.0 + 6.0 / 256.0 ** 0.25
--> 1.0 + 6.0 / 4.0
--> 1.0 + 1.5
> 2 5
26
--> 2.5
Mixed Mode Expression: 1/2Mixed Mode Expression: 1/2
If operands have different types, it is mixedIf operands have different types, it is mixed
mode.
INTEGER and REAL yields REAL and theINTEGER and REAL yields REAL, and the
INTEGER operand is converted to REAL before
evaluation Example: 3 5*4 is converted toevaluation. Example: 3.5 4 is converted to
3.5*4.0 becoming single mode.
Exception: x**INTEGER: x**3 is x*x*x andException: x**INTEGER: x**3 is x*x*x and
x**(-3) is 1.0/(x*x*x).
i l d i h dx**REAL is evaluated with log() and exp().
Logical and character cannot be mixed with
27
arithmetic operands.
Mixed Mode Expression: 2/2Mixed Mode Expression: 2/2
Note that a**b**c is a**(b**c) instead of( )
(a**b)**c, and a**(b**c) (a**b)**c.
This can be a big trap!This can be a big trap!
5 * (11.0 - 5) ** 2 / 4 + 9
--> 5 * (11.0 - 5.0) ** 2 / 4 + 9
--> 5 * 6.0 ** 2 / 4 + 9
/--> 5 * 36.0 / 4 + 9
--> 5.0 * 36.0 / 4 + 9
--> 180.0 / 4 + 9
> 180 0 / 4 0 + 9
6.0**2 is evaluated as 6.0*6.0
rather than converted to 6.0**2.0!
--> 180.0 / 4.0 + 9
--> 45.0 + 9
--> 45.0 + 9.0
> 54 0
28
--> 54.0
red: type conversion
The Assignment Statement: 1/2The Assignment Statement: 1/2
The assignment statement has a form ofThe assignment statement has a form of
variable = expression
If the type of ariable and e pression areIf the type of variable and expression are
identical, the result is saved to variable.
If the type of variable and expression are
not identical, the result of expression is
fconverted to the type of variable.
If expression is REAL and variable is
INTEGER, the result is truncated.
29
The Assignment Statement: 2/2The Assignment Statement: 2/2
The left example uses an initialized variableThe left example uses an initialized variable
Unit, and the right uses a PARAMETER PI.
INTEGER :: Total, Amount
INTEGER :: Unit = 5
REAL, PARAMETER :: PI = 3.1415926
REAL :: Area
INTEGER :: Radius
Amount = 100.99
Total = Unit * Amount
INTEGER :: Radius
Radius = 5
Area = (Radius ** 2) * PI
This one is equivalent to Radius ** 2 * PI
30
Fortran Intrinsic Functions: 1/4Fortran Intrinsic Functions: 1/4
Fortran provides many commonly usedFortran provides many commonly used
functions, referred to as intrinsic functions.
To use an intrinsic function we need to know:To use an intrinsic function, we need to know:
Name and meaning of the function (e.g.,
SQRT() for square root)SQRT() for square root)
Number of arguments
The type and range of each argument (e.g.,
the argument of SQRT() must be non-
negative)
The type of the returned function value.
31
e ype o e e u ed u c o v ue.
Fortran Intrinsic Functions: 2/4Fortran Intrinsic Functions: 2/4
Some mathematical functions:Some mathematical functions:
Function Meaning Arg. Type Return Type
b l l f
INTEGER INTEGER
ABS(x) absolute value of x
REAL REAL
SQRT(x) square root of x REAL REAL
SIN(x) sine of x radian REAL REAL
COS(x) cosine of x radian REAL REAL
TAN(x) tangent of x radian REAL REALTAN(x) tangent of x radian REAL REAL
ASIN(x) arc sine of x REAL REAL
ACOS(x) arc cosine of x REAL REAL
ATAN(x) arc tangent of x REAL REAL
EXP(x) exponential ex REAL REAL
32
LOG(x) natural logarithm of x REAL REAL
LOG10(x) is the common logarithm of x!
Fortran Intrinsic Functions: 3/4Fortran Intrinsic Functions: 3/4
Some conversion functions:Some conversion functions:
Function Meaning Arg. Type Return Type
INT(x) truncate to integer part x REAL INTEGERINT(x) truncate to integer part x REAL INTEGER
NINT(x) round nearest integer to x REAL INTEGER
FLOOR(x) greatest integer less than or equal to x REAL INTEGER
FRACTION(x) the fractional part of x REAL REAL
REAL(x) convert x to REAL INTEGER REAL
INT(-3.5) -3
NINT(3.5) 4Examples:
NINT(-3.4) -3
FLOOR(3.6) 3
FLOOR(-3.5) -4
C O (12 3) 0 3
33
FRACTION(12.3) 0.3
REAL(-10) -10.0
Fortran Intrinsic Functions: 4/4Fortran Intrinsic Functions: 4/4
Other functions:Other functions:
Function Meaning Arg. Type Return Type
INTEGER INTEGER
MAX(x1, x2, ..., xn) maximum of x1, x2, ... xn
INTEGER INTEGER
REAL REAL
MIN(x1 x2 xn) minimum of x1 x2 xn
INTEGER INTEGER
MIN(x1, x2, ..., xn) minimum of x1, x2, ... xn
REAL REAL
MOD(x,y) remainder x - INT(x/y)*y
INTEGER INTEGER
REAL REAL
34
Expression EvaluationExpression Evaluation
Functions have the highest priority.
Function arguments are evaluated first.
The returned function value is treated as aThe returned function value is treated as a
value in the expression.
REAL :: A = 1.0, B = -5.0, C = 6.0, RREAL :: A 1.0, B 5.0, C 6.0, R
R = (-B + SQRT(B*B - 4.0*A*C))/(2.0*A)
/
R gets 3.0
(-B + SQRT(B*B - 4.0*A*C))/(2.0*A)
--> (5.0 + SQRT(B*B - 4.0*A*C))/(2.0*A)
--> (5.0 + SQRT(25.0 - 4.0*A*C))/(2.0*A)
--> (5.0 + SQRT(25.0 - 4.0*C))/(2.0*A)(5.0 SQRT(25.0 4.0 C))/(2.0 A)
--> (5.0 + SQRT(25.0 - 24.0))/(2.0*A)
--> (5.0 + SQRT(1.0))/(2.0*A)
--> (5.0 + 1.0)/(2.0*A)
6 0/(2 0* )
35
--> 6.0/(2.0*A)
--> 6.0/2.0
--> 3.0
What is IMPLICIT NONE?What is IMPLICIT NONE?
Fortran has an interesting tradition: allg
variables starting with i, j, k, l, m and n, if
not declared, are of the INTEGER type by
default.
This handy feature can cause serious
consequences if it is not used with care.
IMPLICIT NONE means all names must be
declared and there is no implicitly assumed
INTEGER type.
All programs in this class must use IMPLICIT
NONE. Points will be deducted if you do not use itPoints will be deducted if you do not use it!
36
List-Directed READ: 1/5List Directed READ: 1/5
Fortran 90 uses the READ(*,*) statement to( , )
read data into variables from keyboard:
READ(* *) v1 v2 vnREAD( , ) v1, v2, …, vn
READ(*,*)
The second form has a special meaning that will
be discussed later.
INTEGER :: Age
REAL :: Amount, Rate
CHARACTER(LEN=10) :: Name
READ(*,*) Name, Age, Rate, Amount
37
List-Directed READ: 2/5List Directed READ: 2/5
Data Preparation GuidelinesData Preparation Guidelines
READ(*,*) reads data from keyboard by
default although one may use inputdefault, although one may use input
redirection to read from a file.
If READ(* *) has n variables there mustIf READ(*,*) has n variables, there must
be n Fortran constants.
Each constant must have the type of the
corresponding variable. Integers can be
d i i bl b iread into REAL variables but not vice versa.
Data items are separated by spaces and may
38
spread into multiple lines.
List-Directed READ: 3/5List Directed READ: 3/5
The execution of READ(*,*) always starts withf ( , ) y
a new line!
Then it reads each constant into theThen, it reads each constant into the
corresponding variable.
CHARACTER(LEN=5) :: Name
REAL :: height, length
INTEGER :: count, MaxLength
READ(*,*) Name, height, count, length, MaxLength
"Smith" 100.0 25 123.579 10000Input:
39
put:
List-Directed READ: 4/5List Directed READ: 4/5
Be careful when input items are on multiple lines.Be careful when input items are on multiple lines.
INTEGER :: I,J,K,L,M,N
Input:
READ(*,*) I, J
READ(*,*) K, L, M
READ(*,*) N
100 200
300 400 500
600
INTEGER :: I,J,K,L,M,N
ignored!
READ(*,*) I, J, K
READ(*,*) L, M, N
100 200 300 400
500 600 700 800
900
READ(*,*) always starts with a new line
40
List-Directed READ: 5/5List Directed READ: 5/5
Since READ(*,*) always starts with a new line,( , ) y ,
a READ(*,*) without any variable means
skipping the input line!skipping the input line!
INTEGER :: P, Q, R, SINTEGER :: P, Q, R, S
READ(*,*) P, Q
READ(*,*)
100 200 300
400 500 600( , )
READ(*,*) R, S
400 500 600
700 800 900
41
List-Directed WRITE: 1/3List Directed WRITE: 1/3
Fortran 90 uses the WRITE(*,*) statement to( , )
write information to screen.
WRITE(* *) has two forms where exp1WRITE( , ) has two forms, where exp1,
exp2, …, expn are expressions
WRITE(* *) e p1 e p2 e pnWRITE(*,*) exp1, exp2, …, expn
WRITE(*,*)
WRITE(*,*) evaluates the result of each
expression and prints it on screen.
WRITE(*,*) always starts with a new line!
42
List-Directed WRITE: 2/3List Directed WRITE: 2/3
Here is a simple example:Here is a simple example:
INTEGER :: Target
means length is determined by actual count
REAL :: Angle, Distance
CHARACTER(LEN=*), PARAMETER :: &
Time = "The time to hit target “, &
IS = " is “, &
UNIT = " sec."
ti ti li Output:Target = 10
Angle = 20.0
Distance = 1350.0
WRITE(* *) 'A l ' A l
continuation lines Output:
Angle = 20.0
Distance = 1350.0
The time to hit target 10 is 27000.0 sec.
WRITE(*,*) 'Angle = ', Angle
WRITE(*,*) 'Distance = ', Distance
WRITE(*,*)
WRITE(* *) Time Target IS &
The time to hit target 10 is 27000.0 sec.
43
WRITE(*,*) Time, Target, IS, &
Angle * Distance, UNIT
print a blank line
List-Directed WRITE: 3/3List Directed WRITE: 3/3
The previous example used LEN=* , whichp p ,
means the length of a CHARACTER constant is
determined by actual count.
WRITE(*,*) without any expression advances
to the next line, producing a blank one.
A Fortran 90 compiler will use the best way to
print each value. Thus, indentation and
alignment are difficult to achieve with
WRITE(*,*).
One must use the FORMAT statement to produce
good looking output.
44
Complete Example: 1/4Complete Example: 1/4
This program computes the position (x and yp g p p ( y
coordinates) and the velocity (magnitude and direction)
of a projectile, given t, the time since launch, u, the
i i i i ilaunch velocity, a, the initial angle of launch (in degree),
and g=9.8, the acceleration due to gravity.
The horizontal and vertical displacements, x and y, are
computed as follows:
x u a tcos( )
g t2
y u a t
g t
sin( )
2
45
2
Complete Example: 2/4Complete Example: 2/4
The horizontal and vertical components of the velocityp y
vector are computed as
cos( )V u acos( )xV u a
sin( )yV u a g t
The magnitude of the velocity vector is
( )y g
V V V2 2
The angle between the ground and the velocity vector is
V V Vx y
2 2
tan( )
V
V
x
46
Vy
Complete Example: 3/4Complete Example: 3/4
Write a program to read in the launch angle a, the timep g g ,
since launch t, and the launch velocity u, and compute
the position, the velocity and the angle with the ground.
PROGRAM Projectile
IMPLICIT NONE
REAL, PARAMETER :: g = 9.8 ! acceleration due to gravity
REAL, PARAMETER :: PI = 3.1415926 ! you know this. don't you?
REAL :: Angle ! launch angle in degree
REAL :: Time ! time to flight
REAL :: Theta ! direction at time in degreeREAL :: Theta ! direction at time in degree
REAL :: U ! launch velocity
REAL :: V ! resultant velocity
REAL :: Vx ! horizontal velocity
REAL :: Vy ! vertical velocity
REAL :: X ! horizontal displacement
REAL :: Y ! vertical displacement
Other executable statements
47
…… Other executable statements ……
END PROGRAM Projectile
Complete Example: 4/4Complete Example: 4/4
Write a program to read in the launch angle a, the timep g g ,
since launch t, and the launch velocity u, and compute
the position, the velocity and the angle with the ground.
READ(*,*) Angle, Time, U
Angle = Angle * PI / 180.0 ! convert to radianAngle Angle PI / 180.0 ! convert to radian
X = U * COS(Angle) * Time
Y = U * SIN(Angle) * Time - g*Time*Time / 2.0
Vx = U * COS(Angle)g
Vy = U * SIN(Angle) - g * Time
V = SQRT(Vx*Vx + Vy*Vy)
Theta = ATAN(Vy/Vx) * 180.0 / PI ! convert to degree
WRITE(*,*) 'Horizontal displacement : ', X
WRITE(*,*) 'Vertical displacement : ', Y
48
WRITE(*,*) 'Resultant velocity : ', V
WRITE(*,*) 'Direction (in degree) : ', Theta
CHARACTER Operator //CHARACTER Operator //
Fortran 90 uses // to concatenate two strings.// g
If strings A and B have lengths m and n, the
concatenation A // B is a string of length m+nconcatenation A // B is a string of length m+n.
CHARACTER(LEN=4) :: John = "John", Sam = "Sam"
CHARACTER(LEN=6) :: Lori = "Lori", Reagan = "Reagan"
CHARACTER(LEN=10) :: Ans1, Ans2, Ans3, Ans4
Ans1 = John // Lori ! Ans1 = “JohnLori ”
Ans2 = Sam // Reagan ! Ans2 = “Sam Reagan”
Ans3 = Reagan // Sam ! Ans3 = “ReaganSam ”
Ans4 = Lori // Sam ! Ans4 = “Lori Sam ”
49
CHARACTER Substring: 1/3CHARACTER Substring: 1/3
A consecutive portion of a string is a substring.p g g
To use substrings, one may add an extent
specifier to a CHARACTER variable.p f
An extent specifier has the following form:
( integer-exp1 : integer-exp2 )( integer-exp1 : integer-exp2 )
The first and the second expressions indicate
the start and end: (3:8) means 3 to 8the start and end: (3:8) means 3 to 8,
If A = “abcdefg” , then A(3:5) means A’s
substring from position 3 to position 5 (i esubstring from position 3 to position 5 (i.e.,
“cde” ).
50
CHARACTER Substring: 2/3CHARACTER Substring: 2/3
In (integer-exp1:integer-exp2), if the( g p g p ),
first exp1 is missing, the substring starts from
the first character, and if exp2 is missing, the, p g,
substring ends at the last character.
If A = “12345678” then A(:5) is “12345”If A = 12345678 , then A(:5) is 12345
and A(3+x:) is “5678” where x is 2.
A d i ti i lAs a good programming practice, in general,
the first expression exp1 should be no less than
1 and the second expression exp2 should be no1, and the second expression exp2 should be no
greater than the length of the string.
51
CHARACTER Substring: 3/3CHARACTER Substring: 3/3
Substrings can be used on either side of theg
assignment operator.
Suppose LeftHand = “123456789”pp
(length is 10) .
LeftHand(3:5) = "abc” yields LeftHand =
“12abc67890”
LeftHand(4:) = "lmnopqr” yields
LeftHand = "123lmnopqr“LeftHand = "123lmnopqr“
LeftHand(3:8) = "abc” yields LeftHand =
"12abc 90“
LeftHand(4:7) = "lmnopq” yields
LeftHand = "123lmno890"
52
Example: 1/5Example: 1/5
This program uses the DATE AND TIME()p g _ _ ()
Fortran 90 intrinsic function to retrieve the
system date and system time. Then, it convertssystem date and system time. Then, it converts
the date and time information to a readable
format. This program demonstrates the use offormat. This program demonstrates the use of
concatenation operator // and substring.
System date is a string ccyymmdd where cc =System date is a string ccyymmdd, where cc
century, yy = year, mm = month, and dd = day.
System time is a string hhmmss.sss, where hh
= hour, mm = minute, and ss.sss = second.
53
Example: 2/5Example: 2/5
The following shows the specification part.g p p
Note the handy way of changing string length.
PROGRAM DateTime
IMPLICIT NONE
CHARACTER(LEN = 8) :: DateINFO ! ccyymmdd
CHARACTER(LEN = 4) :: Year, Month*2, Day*2
CHARACTER(LEN = 10) :: TimeINFO, PrettyTime*12 ! hhmmss.sss
CHARACTER(LEN = 2) :: Hour, Minute, Second*6
CALL DATE_AND_TIME(DateINFO, TimeINFO)
…… other executable statements ……
END PROGRAM DateTime
54
This is a handy way of changing string length
Example: 3/5Example: 3/5
Decompose DateINFO into year, month andp y ,
day. DateINFO has a form of ccyymmdd,
where cc = century, yy = year, mm = month,y, yy y , ,
and dd = day.
Year = DateINFO(1:4)
Month = DateINFO(5:6)
Day = DateINFO(7:8)
WRITE(* *) 'Date information -> ' DateINFOWRITE(*,*) Date information -> , DateINFO
WRITE(*,*) ' Year -> ', Year
WRITE(*,*) ' Month -> ', Month
WRITE(*,*) ' Day -> ', Day
Date information -> 19970811
Year -> 1997
Output:
55
Year -> 1997
Month -> 08
Day -> 11
Example: 4/5Example: 4/5
Now do the same for time:Now do the same for time:
Hour = TimeINFO(1:2)
Minute = TimeINFO(3:4)Minute = TimeINFO(3:4)
Second = TimeINFO(5:10)
PrettyTime = Hour // ':' // Minute // ':' // Second
WRITE(*,*)
WRITE(*,*) 'Time Information -> ', TimeINFO
WRITE(*,*) ' Hour -> ', Hour
WRITE(*,*) ' Minute -> ', Minute
WRITE(*,*) ' Second -> ', SecondWRITE( , ) Second > , Second
WRITE(*,*) ' Pretty Time -> ', PrettyTime
Time Information -> 010717.620
Hour -> 01
Minute -> 07
S d 17 620
Output:
56
Second -> 17.620
Pretty Time -> 01:07:17.620
Example: 5/5Example: 5/5
We may also use substring to achieve the samey g
result:
PrettyTime = “ “ ! Initialize to all blanks
PrettyTime( :2) = Hour
PrettyTime(3:3) = ':'PrettyTime(3:3) = ':'
PrettyTime(4:5) = Minute
PrettyTime(6:6) = ':'
PrettyTime(7: ) = SecondPrettyTime(7: ) = Second
WRITE(*,*)
WRITE(*,*) ' Pretty Time -> ', PrettyTimeWRITE( , ) Pretty Time > , PrettyTime
57
What KIND Is It?What KIND Is It?
Fortran 90 has a KIND attribute for selectingg
the precision of a numerical constant/variable.
The KIND of a constant/variable is a positiveThe KIND of a constant/variable is a positive
integer (more on this later) that can be attached
to a constantto a constant.
Example:
i i f126_3 : 126 is an integer of KIND 3
3.1415926_8 : 3.1415926 is a real of
KIND 8
58
What KIND Is It (INTEGER)? 1/2What KIND Is It (INTEGER)? 1/2
Function SELECTED_INT_KIND(k) selects the_ _
KIND of an integer, where the value of k, a
positive integer, means the selected integer
k kKIND has a value between -10k and 10k.
Thus, the value of k is approximately the
number of digits of that KIND. For example,
SELECTED_INT_KIND(10) means an integer
KIND of no more than 10 digitsKIND of no more than 10 digits.
If SELECTED_INT_KIND() returns -1, this
th h d d t t thmeans the hardware does not support the
requested KIND.
59
What KIND Is It (INTEGER)? 2/2What KIND Is It (INTEGER)? 2/2
SELECTED_INT_KIND() is usually used in the_ _ y
specification part like the following:
INTEGER, PARAMETER :: SHORT = SELECTED_INT_KIND(2)_ _
INTEGER(KIND=SHORT) :: x, y
The above declares an INTEGER PARAMETER
SHORT with SELECTED_INT_KIND(2), which is
the KIND of 2-digit integers.
Then, the KIND= attribute specifies that INTEGER
variables x and y can hold 2-digit integers.
In a program, one may use -12_SHORT and
9_SHORT to write constants of that KIND.
60
What KIND Is It (REAL)? 1/2What KIND Is It (REAL)? 1/2
Use SELECTED REAL KIND(k,e) to specify aS _ _ ( , ) p y
KIND for REAL constants/variables, where k is
the number of significant digits and e is thethe number of significant digits and e is the
number of digits in the exponent. Both k and e
must be positive integers.must be positive integers.
Note that e is optional.
SELECTED REAL KIND(7 3) selects a REALSELECTED_REAL_KIND(7,3) selects a REAL
KIND of 7 significant digits and 3 digits for the
t 0 10 yyyexponent: 0.xxxxxxx 10 yyy
61
What KIND Is It (REAL)? 2/2What KIND Is It (REAL)? 2/2
Here is an example:Here is an example:
INTEGER, PARAMETER :: &
SINGLE=SELECTED REAL KIND(7,2), &SINGLE=SELECTED_REAL_KIND(7,2), &
DOUBLE=SELECTED_REAL_KIND(15,3)
REAL(KIND=SINGLE) :: x
REAL(KIND=DOUBLE) :: Sum
123 4x = 123.45E-5_SINGLE
Sum = Sum + 12345.67890_DOUBLE
62
Why KIND, etc? 1/2Why KIND, etc? 1/2
Old Fortran used INTEGER*2, REAL*8,, ,
DOUBLE PRECISION, etc to specify the
“precision” of a variable. For example,
REAL*8 means the use of 8 bytes to store a real
value.
This is not very portable because some
computers may not use bytes as their basic
t it hil th t 2storage unit, while some others cannot use 2
bytes for a short integer (i.e., INTEGER*2).
M l t t h d fiMoreover, we also want to have more and finer
precision control.
63
Why KIND, etc? 2/2Why KIND, etc? 2/2
Due to the differences among computerDue to the differences among computer
hardware architectures, we have to be careful:
The requested KIND may not be satisfiedThe requested KIND may not be satisfied.
For example, SELECTED_INT_KIND(100)
may not be realistic on most computersmay not be realistic on most computers.
Compilers will find the best way good enough
(i e larger) for the requested KIND(i.e., larger) for the requested KIND.
If a “larger” KIND value is stored to a
“ ll ” i bl di bl“smaller” KIND variable, unpredictable
result may occur.
64
Use KIND carefully for maximum portability.
Fortran 90 Control StructuresFortran 90 Control Structures
Computer programming is an art form,
like the creation of poetry or music.
1
Donald Ervin Knuth
Fall 2010
LOGICAL VariablesLOGICAL Variables
A LOGIAL variable can only hold either .TRUE.y
or .FALSE. , and cannot hold values of any
other type.other type.
Use T or F for LOGICAL variable READ(*,*)
WRITE(* *) prints T or F for TRUEWRITE(*,*) prints T or F for .TRUE.
and .FALSE., respectively.
LOGICAL, PARAMETER :: Test = .TRUE.
LOGICAL :: C1, C2
C1 = .true. ! correct
C2 = 123 ! Wrong
READ(*,*) C1, C2
2
C2 = .false.
WRITE(*,*) C1, C2
Relational Operators: 1/4Relational Operators: 1/4
Fortran 90 has six relational operators: <, <=,p , ,
>, >=, ==, /=.
Each of these six relational operators takes twop
expressions, compares their values, and
yields .TRUE. or .FALSE.
Thus, a < b < c is wrong, because a < b is
LOGICAL and c is REAL or INTEGER.
COMPLEX values can only use == and /=
LOGICAL values should use .EQV. or .NEQV.
for equal and not-equal comparison.
3
Relational Operators: 2/4Relational Operators: 2/4
Relational operators have lower priority thanRelational operators have lower priority than
arithmetic operators, and //.
Thus 3 + 5 > 10 is FALSE and “a” //Thus, 3 + 5 > 10 is .FALSE. and a //
“b” == “ab” is .TRUE.
Ch t l d d Diff tCharacter values are encoded. Different
standards (e.g., BCD, EBCDIC, ANSI) have
diff t didifferent encoding sequences.
These encoding sequences may not be
compatible with each other.
4
Relational Operators: 3/4Relational Operators: 3/4
For maximum portability, only assume thep y, y
following orders for letters and digits.
Thus, “A” < “X”, ‘f’ <= “u”, and “2” <, , ,
“7” yield .TRUE. But, we don’t know the
results of “S” < “s” and “t” >= “%”.
However, equal and not-equal such as “S” /=
“s” and “t” == “5” are fine.
A < B < C < D < E < F < G < H < I < J < K < L < M < N
< O < P < Q < R < S < T < U < V < W < X < Y < Z
a < b < c < d < e < f < g < h < i < j < k < l < m < n
< o < p < q < r < s < t < u < v < w < x < y < z
5
0 < 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9
Relational Operators: 4/4Relational Operators: 4/4
String comparison rules:g p
Start scanning from the first character.
If the current two are equal go for the nextIf the current two are equal, go for the next
If there is no more characters to compare, the
strings are equal (e.g., “abc” == “abc”)
If one string has no more character, the shorter
string is smaller (e.g., “ab” < “abc”
is TRUE )is .TRUE.)
If the current two are not equal, the string
has the smaller character is smaller (e ghas the smaller character is smaller (e.g.,
“abcd” is smaller than “abct”).
6
LOGICAL Operators: 1/2LOGICAL Operators: 1/2
There are 5 LOGICAL operators in Fortranp
90: .NOT., .OR., .AND., .EQV. and .NEQV.
NOT is the highest followed by OR.NOT. is the highest, followed by .OR.
and .AND., .EQV. and .NEQV. are the lowest.
Recall that NOT is evaluated from right to leftRecall that .NOT. is evaluated from right to left.
If both operands of .EQV. (equivalence) are the
isame, .EQV. yields .TRUE..
.NEQV. is the opposite of .EQV. (not equivalence).
If the operands of .NEQV. have different
values, .NEQV. yields .TRUE.
7
LOGICAL Operators: 2/2LOGICAL Operators: 2/2
If INTEGER variables m, n, x and y have, , y
values 3, 5, 4 and 2, respectively.
.NOT. (m > n .AND. x < y) .NEQV. (m <= n .AND. x >= y)
.NOT. (3 > 5 .AND. 4 < 2) .NEQV. (3 <= 5 .AND. 4 >= 2)
.NOT. (.FALSE. .AND. 4 < 2) .NEQV. (3 <= 5 .AND. 4 >= 2)
.NOT. (.FALSE. .AND. .FALSE.) .NEQV. (3 <= 5 .AND. 4 >= 2)
.NOT. .FALSE. .NEQV. (3 <= 5 .AND. 4 >= 2)
TRUE NEQV (3 5 AND 4 2).TRUE. .NEQV. (3 <= 5 .AND. 4 >= 2)
.TRUE. .NEQV. (.TRUE. .AND. 4 >= 2)
.TRUE. .NEQV. (.TRUE. .AND. .TRUE.)
TRUE NEQV TRUE.TRUE. .NEQV. .TRUE.
.FALSE.
8
.NOT. is higher than .NEQV.
IF-THEN-ELSE Statement: 1/4IF THEN ELSE Statement: 1/4
Fortran 90 has three if-then-else forms.
The most complete one is the IF-THEN-ELSE-
IF-END IF
An old logical IF statement may be very handy
when it is needed.
There is an old and obsolete arithmetic IF that
you are not encouraged to use. We won’t talky g
about it at all.
Details are in the next few slides.
9
IF-THEN-ELSE Statement: 2/4IF THEN ELSE Statement: 2/4
IF-THEN-ELSE-IF-END IF is the following.g
Logical expressions are evaluated sequentially (i.e., top-
down). The statement sequence that corresponds to the
expression evaluated to .TRUE. will be executed.
Otherwise, the ELSE sequence is executed.
IF (logical-expression-1) THEN
statement sequence 1
ELSE IF (logical expression 2) THENELSE IF (logical-expression-2) THEN
statement seqence 2
ELSE IF (logical-expression-3) THEN
statement sequence 3statement sequence 3
ELSE IF (.....) THEN
...........
ELSE
10
ELSE
statement sequence ELSE
END IF
IF-THEN-ELSE Statement: 3/4IF THEN ELSE Statement: 3/4
Two Examples:Two Examples:
Find the minimum of a, b and c
and saves the result to Result Letter grade for x
IF (a < b .AND. a < c) THEN
Result = a
ELSE IF (b < a .AND. b < c) THEN
INTEGER :: x
CHARACTER(LEN=1) :: Grade
and saves the result to Result g f
( )
Result = b
ELSE
Result = c
END IF
IF (x < 50) THEN
Grade = 'F'
ELSE IF (x < 60) THEN
G d 'D'END IF Grade = 'D'
ELSE IF (x < 70) THEN
Grade = 'C'
ELSE IF (x < 80) THEN( )
Grade = 'B'
ELSE
Grade = 'A'
END IF
11
END IF
IF-THEN-ELSE Statement: 4/4IF THEN ELSE Statement: 4/4
The ELSE-IF part and ELSE part are optional.p p p
If the ELSE part is missing and none of the
logical expressions is .TRUE., the IF-THEN-g p ,
ELSE has no effect.
no ELSE-IF no ELSE
IF (logical-expression-1) THEN
statement sequence 1
ELSE
IF (logical-expression-1) THEN
statement sequence 1
ELSE IF (logical-expression-2) THEN
statement sequence ELSE
END IF
statement sequence 2
ELSE IF (logical-expression-3) THEN
statement sequence 3
ELSE IF ( ) THENELSE IF (.....) THEN
...........
END IF
12
Example: 1/2Example: 1/2
Given a quadratic equation ax2 +bx + c = 0,Given a quadratic equation ax bx c 0,
where a 0, its roots are computed as follows:
b b2
4
x
b b a c
a
2
4
2
However, this is a very poor and unreliable way
of computing roots. Will return to this soon.
PROGRAM QuadraticEquation
IMPLICIT NONE
REAL :: a, b, c
REAL :: d
REAL :: root1, root2
13
…… other executable statement ……
END PROGRAM QuadraticEquation
Example: 2/2Example: 2/2
The following shows the executable partThe following shows the executable part
READ(*,*) a, b, c
WRITE(*,*) 'a = ', a
WRITE(*,*) 'b = ', b
WRITE(*,*) 'c = ', c
WRITE(*,*)
d = b*b - 4.0*a*c
IF (d >= 0.0) THEN ! is it solvable?
d = SQRT(d)
root1 = (-b + d)/(2.0*a) ! first root
root2 = (-b - d)/(2.0*a) ! second root
WRITE(* *) 'R t ' t1 ' d ' t2WRITE(*,*) 'Roots are ', root1, ' and ', root2
ELSE ! complex roots
WRITE(*,*) 'There is no real roots!'
WRITE(* *) 'Discriminant = ' d
14
WRITE(*,*) 'Discriminant = ', d
END IF
IF-THEN-ELSE Can be Nested: 1/2IF THEN ELSE Can be Nested: 1/2
Another look at the quadratic equation solver.Another look at the quadratic equation solver.
IF (a == 0.0) THEN ! could be a linear equation
IF (b == 0 0) THEN ! the input becomes c = 0IF (b == 0.0) THEN ! the input becomes c = 0
IF (c == 0.0) THEN ! all numbers are roots
WRITE(*,*) 'All numbers are roots'
ELSE ! unsolvableELSE ! unsolvable
WRITE(*,*) 'Unsolvable equation'
END IF
ELSE ! linear equation bx + c = 0ELSE ! linear equation bx + c 0
WRITE(*,*) 'This is linear equation, root = ', -c/b
END IF
ELSE ! ok, we have a quadratic equation, q q
...... solve the equation here ……
END IF
15
IF-THEN-ELSE Can be Nested: 2/2IF THEN ELSE Can be Nested: 2/2
Here is the big ELSE part:g S p
d b*b 4 0*a*cd = b*b - 4.0*a*c
IF (d > 0.0) THEN ! distinct roots?
d = SQRT(d)
root1 = (-b + d)/(2 0*a) ! first rootroot1 = (-b + d)/(2.0*a) ! first root
root2 = (-b - d)/(2.0*a) ! second root
WRITE(*,*) 'Roots are ', root1, ' and ', root2
ELSE IF (d == 0.0) THEN ! repeated roots?ELSE IF (d == 0.0) THEN ! repeated roots?
WRITE(*,*) 'The repeated root is ', -b/(2.0*a)
ELSE ! complex roots
WRITE(*,*) 'There is no real roots!'( , )
WRITE(*,*) 'Discriminant = ', d
END IF
16
Logical IFLogical IF
The logical IF is from Fortran 66, which is ang ,
improvement over the Fortran I arithmetic IF.
If logical-expression is .TRUE. , statement isg p ,
executed. Otherwise, execution goes though.
The statement can be assignment andg
input/output.
IF (logical-expression) statementIF (logical expression) statement
Smallest = b Cnt = Cnt + 1Smallest = b
IF (a < b) Smallest = a
Cnt = Cnt + 1
IF (MOD(Cnt,10) == 0) WRITE(*,*) Cnt
17
The SELECT CASE Statement: 1/7The SELECT CASE Statement: 1/7
Fortran 90 has the SELECT CASE statement forS S
selective execution if the selection criteria are
based on simple values in INTEGER, LOGICALp ,
and CHARACTER. No, REAL is not applicable.
SELECT CASE (selector)
CASE (label-list-1)
statements-1
CASE (label-list-2)
2
selector is an expression evaluated
to an INTEGER, LOGICAL or
CHARACTER value
statements-2
CASE (label-list-3)
statements-3
other cases
label-list is a set of constants or
PARAMETERS of the same type
…… other cases ……
CASE (label-list-n)
statements-n
CASE DEFAULT
yp
as the selector
statements is one or more
18
CASE DEFAULT
statements-DEFAULT
END SELECT
statements s o e o o e
executable statements
The SELECT CASE Statement: 2/7The SELECT CASE Statement: 2/7
The label-list is a list of the following forms:The label list is a list of the following forms:
value a specific value
al e1 al e2 values betweenvalue1 : value2 values between
value1 and value2, including value1 and
al e2 and al e1 < al e2value2, and value1 <= value2
value1 : values larger than or equal to
value1
: value2 values less than or equal to
value2
Reminder: value, value1 and value2 must
19
,
be constants or PARAMETERs.
The SELECT CASE Statement: 3/7The SELECT CASE Statement: 3/7
The SELECT CASE statement is SELECT CASE (selector)
executed as follows:
Compare the value of
SELECT CASE (selector)
CASE (label-list-1)
statements-1
CASE (label-list-2)
selector with the labels in
each case. If a match is
f d t th
( )
statements-2
CASE (label-list-3)
statements-3
found, execute the
corresponding statements.
If no match is found and if
…… other cases ……
CASE (label-list-n)
statements-n
If no match is found and if
CASE DEFAULT is there,
execute the statements-
CASE DEFAULT
statements-DEFAULT
END SELECT
DEFAULT.
Execute the next statement optional
20
following the SELECT CASE.
The SELECT CASE Statement: 4/7The SELECT CASE Statement: 4/7
Some important notes:Some important notes:
The values in label-lists should be unique.
Otherwise it is not known which CASEOtherwise, it is not known which CASE
would be selected.
CASE DEFAULT should be used whenever itCASE DEFAULT should be used whenever it
is possible, because it guarantees that there is
l t d thi ( )a place to do something (e.g., error message)
if no match is found.
b h iCASE DEFAULT can be anywhere in a
SELECT CASE statement; but, a preferred
l i h l i h li
21
place is the last in the CASE list.
The SELECT CASE Statement: 5/7The SELECT CASE Statement: 5/7
Two examples of SELECT CASE:p S S
CHARACTER(LEN=4) :: Title
INTEGER :: DrMD = 0, PhD = 0
CHARACTER(LEN=1) :: c
INTEGER :: DrMD 0, PhD 0
INTEGER :: MS = 0, BS = 0
INTEGER ::Others = 0
i
SELECT CASE (c)
CASE ('a' : 'j')
WRITE(*,*) ‘First ten letters'
SELECT CASE (Title)
CASE ("DrMD")
DrMD = DrMD + 1
CASE ("PhD")
CASE ('l' : 'p', 'u' : 'y')
WRITE(*,*) &
'One of l,m,n,o,p,u,v,w,x,y'
CASE ('z', 'q' : 't')CASE ( PhD )
PhD = PhD + 1
CASE ("MS")
MS = MS + 1
( )
CASE ( z , q : t )
WRITE(*,*) 'One of z,q,r,s,t'
CASE DEFAULT
WRITE(*,*) 'Other characters'
CASE ("BS")
BS = BS + 1
CASE DEFAULT
Others = Others + 1
END SELECT
22
Ot e s Ot e s
END SELECT
The SELECT CASE Statement: 6/7The SELECT CASE Statement: 6/7
Here is a more complex example:Here is a more complex example:
INTEGER :: Number, Range Number Range Why?
<= -10 1 CASE (:-10, 10:)
SELECT CASE (Number)
CASE ( : -10, 10 : )
Range = 1
<= 10 1 CASE (: 10, 10:)
-9,-8,-7,-6 6 CASE DEFAULT
-5,-4,-3 2 CASE (-5:-3, 6:9)
CASE (-5:-3, 6:9)
Range = 2
CASE (-2:2)
-2,-1,0,1,2 3 CASE (-2:2)
3 4 CASE (3, 5)
Range = 3
CASE (3, 5)
Range = 4
4 5 CASE (4)
5 4 CASE (3, 5)
6,7,8,9 2 CASE (-5:-3, 6:9)
CASE (4)
Range = 5
CASE DEFAULT
R 6
6,7,8,9 2 CASE ( 5: 3, 6:9)
>= 10 1 CASE (:-10, 10:)
23
Range = 6
END SELECT
The SELECT CASE Statement: 7/7The SELECT CASE Statement: 7/7
PROGRAM CharacterTesting
IMPLICIT NONE
CHARACTER(LEN=1) :: Input
This program reads in a character and
determines if it is a vowel, a consonant,
CHARACTER(LEN=1) :: Input
READ(*,*) Input
SELECT CASE (Input)
CASE ('A' : 'Z', 'a' : 'z') ! rule out letters
a digit, one of the four arithmetic operators,
a space, or something else (i.e., %, $, @, etc).
WRITE(*,*) 'A letter is found : "', Input, '"'
SELECT CASE (Input) ! a vowel ?
CASE ('A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o','u')
WRITE(* *) 'It is a vowel'WRITE( , ) It is a vowel
CASE DEFAULT ! it must be a consonant
WRITE(*,*) 'It is a consonant'
END SELECT
CASE ('0' : '9') ! a digit
WRITE(*,*) 'A digit is found : "', Input, '"'
CASE ('+', '-', '*', '/') ! an operator
WRITE(*,*) 'An operator is found : "', Input, '"'WRITE( , ) An operator is found : , Input,
CASE (' ') ! space
WRITE(*,*) 'A space is found : "', Input, '"'
CASE DEFAULT ! something else
24
WRITE(*,*) 'Something else found : "', Input, '"'
END SELECT
END PROGRAM CharacterTesting
The Counting DO Loop: 1/6The Counting DO Loop: 1/6
Fortran 90 has two forms of DO loop: thep
counting DO and the general DO.
The counting DO has the following form:The counting DO has the following form:
DO control-var = initial, final [, step]
statementsstatements
END DO
control-var is an INTEGER variable,control var is an INTEGER variable,
initial, final and step are INTEGER
expressions; however, step cannot be zero.expressions; however, step cannot be zero.
If step is omitted, its default value is 1.
t bl t t t f th O
25
statements are executable statements of the DO.
The Counting DO Loop: 2/6The Counting DO Loop: 2/6
Before a DO-loop starts, expressions initial,p , p ,
final and step are evaluated exactly once.
When executing the DO-loop, these values willg p,
not be re-evaluated.
Note again the value of step cannot be zeroNote again, the value of step cannot be zero.
If step is positive, this DO counts up; if step is
negative this DO counts downnegative, this DO counts down
DO control-var = initial final [ step]DO control-var = initial, final [, step]
statements
END DO
26
The Counting DO Loop: 3/6The Counting DO Loop: 3/6
If step is positive:p p
The control-var receives the value of initial.
If the value of control-var is less than or equal toIf the value of control var is less than or equal to
the value of final, the statements part is executed.
Then, the value of step is added to control-var,
and goes back and compares the values of
control-var and final.
If the value of control-var is greater than the
value of final, the DO-loop completes and the
statement following END DO is executedstatement following END DO is executed.
27
The Counting DO Loop: 4/6The Counting DO Loop: 4/6
If step is negative:p g
The control-var receives the value of initial.
If the value of control-var is greater than orIf the value of control var is greater than or
equal to the value of final, the statements part is
executed. Then, the value of step is added to
control-var, goes back and compares the values
of control-var and final.
If the value of control-var is less than the value
of final, the DO-loop completes and the statement
following END DO is executedfollowing END DO is executed.
28
The Counting DO Loop: 5/6The Counting DO Loop: 5/6
Two simple examples:Two simple examples:
INTEGER :: N, k odd integers
between 1 & N
READ(*,*) N
WRITE(*,*) “Odd number between 1 and “, N
DO k = 1, N, 2
between 1 & N
WRITE(*,*) k
END DO
INTEGER, PARAMETER :: LONG = SELECTED_INT_KIND(15)
INTEGER(KIND=LONG) :: Factorial, i, N
READ(* *) N
factorial of N
READ(*,*) N
Factorial = 1_LONG
DO i = 1, N
Factorial = Factorial * i
29
END DO
WRITE(*,*) N, “! = “, Factorial
The Counting DO Loop: 6/6The Counting DO Loop: 6/6
Important Notes:Important Notes:
The step size step cannot be zero
N h th l f i bl iNever change the value of any variable in
control-var and initial, final, and
stepstep.
For a count-down DO-loop, step must be
i “ ” inegative. Thus, “do i = 10, -10” is not
a count-down DO-loop, and the statements
portion is not executed.
Fortran 77 allows REAL variables in DO; but,
30
don’t use it as it is not safe.
General DO-Loop with EXIT: 1/2General DO Loop with EXIT: 1/2
The general DO-loop has the following form:The general DO loop has the following form:
DO
statementsstatements
END DO
t t t ill b t d t dlstatements will be executed repeatedly.
To exit the DO-loop, use the EXIT or CYCLE
statement.
The EXIT statement brings the flow of control to
the statement following (i.e., exiting) the END DO.
The CYCLE statement starts the next iteration
31
e C C state e t sta ts t e e t te at o
(i.e., executing statements again).
General DO-Loop with EXIT: 2/2General DO Loop with EXIT: 2/2
REAL PARAMETER :: Lower = 1 0 Upper = 1 0 Step = 0 25REAL, PARAMETER :: Lower = -1.0, Upper = 1.0, Step = 0.25
REAL :: x
x = Lower ! initialize the control variable
DO
IF (x > Upper) EXIT ! is it > final-value?
WRITE(*,*) x ! no, do the loop body
x = x + Step ! increase by step-sizex = x + Step ! increase by step-size
END DO
INTEGER :: InputINTEGER :: Input
DO
WRITE(*,*) 'Type in an integer in [0, 10] please --> '
READ(*,*) Input
IF (0 <= Input .AND. Input <= 10) EXIT
WRITE(*,*) 'Your input is out of range. Try again'
END DO
32
END DO
Example, exp(x): 1/2Example, exp(x): 1/2
The exp(x) function has an infinite series:The exp(x) function has an infinite series:
exp( )
! !
....
!
......x x
x x x
i
i
1
2 3
2 3
Sum each term until a term’s absolute value is
! ! !i2 3
less than a tolerance, say 0.00001.
PROGRAM Exponential
IMPLICIT NONE
INTEGER :: Count ! # of terms used
REAL :: Term ! a term
REAL :: Sum ! the sum
REAL :: X ! the input x
REAL, PARAMETER :: Tolerance = 0.00001 ! tolerance
33
…… executable statements ……
END PROGRAM Exponential
Example, exp(x): 2/2Example, exp(x): 2/2
Note:
1
( 1)! ! 1
i i
x x x
i i i
This is not a good solution, though.
( 1)! ! 1i i i
This is not a good solution, though.
READ(*,*) X ! read in x
Count = 1 ! the first term is 1
iSum = 1.0 ! thus, the sum starts with 1
Term = X ! the second term is x
DO ! for each term
IF (ABS(T ) < T l ) EXIT ! if t ll itIF (ABS(Term) < Tolerance) EXIT ! if too small, exit
Sum = Sum + Term ! otherwise, add to sum
Count = Count + 1 ! count indicates the next term
Term = Term * (X / Count) ! compute the value of next termTerm = Term * (X / Count) ! compute the value of next term
END DO
WRITE(*,*) 'After ', Count, ' iterations:'
WRITE(* *) ' Exp(' X ') = ' Sum
34
WRITE( , ) Exp( , X, ) = , Sum
WRITE(*,*) ' From EXP() = ', EXP(X)
WRITE(*,*) ' Abs(Error) = ', ABS(Sum - EXP(X))
Example, Prime Checking: 1/2Example, Prime Checking: 1/2
A positive integer n >= 2 is a prime number if theA positive integer n 2 is a prime number if the
only divisors of this integer are 1 and itself.
If n = 2 it is a primeIf n = 2, it is a prime.
If n > 2 is even (i.e., MOD(n,2) == 0), not a prime.
If n is odd, then:
If the odd numbers between 3 and n-1 cannot
divide n, n is a prime!
Do we have to go up to n-1? No, SQRT(n) isg p , Q ( )
good enough. Why?
35
Example, Prime Checking: 2/2Example, Prime Checking: 2/2
INTEGER :: Number ! the input number
INTEGER :: Divisor ! the running divisor
READ(*,*) Number ! read in the input
IF (Number < 2) THEN ! not a prime if < 2
WRITE(* *) 'Illegal input'WRITE(*,*) 'Illegal input'
ELSE IF (Number == 2) THEN ! is a prime if = 2
WRITE(*,*) Number, ' is a prime'
ELSE IF (MOD(Number,2) == 0) THEN ! not a prime if even
WRITE(*,*) Number, ' is NOT a prime'
ELSE ! an odd number here
Divisor = 3 ! divisor starts with 3
DO ! divide the input numberDO ! divide the input number
IF (Divisor*Divisor > Number .OR. MOD(Number, Divisor) == 0) EXIT
Divisor = Divisor + 2 ! increase to next odd
END DO
IF (Divisor*Divisor > Number) THEN ! which condition fails?
WRITE(*,*) Number, ' is a prime'
ELSE
WRITE(* *) Number ' is NOT a prime'
36
WRITE(*,*) Number, is NOT a prime
END IF
END IF
this is better than SQRT(REAL(Divisor)) > Number
Finding All Primes in [2,n]: 1/2Finding All Primes in [2,n]: 1/2
The previous program can be modified to findThe previous program can be modified to find
all prime numbers between 2 and n.
PROGRAM Primes
IMPLICIT NONE
INTEGER :: Range, Number, Divisor, Count
WRITE(*,*) 'What is the range ? '
DO ! keep trying to read a good input
READ(*,*) Range ! ask for an input integer
IF (Range >= 2) EXIT ! if it is GOOD, exit
WRITE(*,*) 'The range value must be >= 2. Your input = ', Range
WRITE(*,*) 'Please try again:' ! otherwise, bug the user
END DOEND DO
…… we have a valid input to work on here ……
END PROGRAM Primes
37
Finding All Primes in [2,n]: 2/2Finding All Primes in [2,n]: 2/2
Count = 1 ! input is correct. start counting
WRITE(*,*) ! 2 is a prime
WRITE(*,*) 'Prime number #', Count, ': ', 2
DO Number = 3, Range, 2 ! try all odd numbers 3, 5, 7, ...
Divisor = 3 ! divisor starts with 3
DO
i i i i i iIF (Divisor*Divisor > Number .OR. MOD(Number,Divisor) == 0) EXIT
Divisor = Divisor + 2 ! not a divisor, try next
END DO
IF (Divisor*Divisor > Number) THEN ! divisors exhausted?IF (Divisor Divisor > Number) THEN ! divisors exhausted?
Count = Count + 1 ! yes, this Number is a prime
WRITE(*,*) 'Prime number #', Count, ': ', Number
END IF
END DO
WRITE(*,*)
WRITE(*,*) 'There are ', Count, ' primes in the range of 2 and ', Range
38
( , ) e e a e , Cou t, p es t e a ge o a d , a ge
Factoring a Number: 1/3Factoring a Number: 1/3
Given a positive integer, one can always factorizep g , y
it into prime factors. The following is an
example:
586390350 = 2 3 52 72 13 17 192
Here, 2, 3, 5, 7, 13, 17 and 19 are prime factors., , , , , , p
It is not difficult to find all prime factors.
We can repeatedly divide the input by 2.We can repeatedly divide the input by 2.
Do the same for odd numbers 3, 5, 7, 9, ….
But we said “prime” factors No problemBut, we said “prime” factors. No problem,
multiples of 9 are eliminated by 3 in an earlier
stage!
39
stage!
Factoring a Number: 2/3Factoring a Number: 2/3
PROGRAM Factorize
IMPLICIT NONE
INTEGER :: Input
INTEGER :: Divisor
INTEGER :: Count
WRITE(*,*) 'This program factorizes any integer >= 2 --> '
READ(*,*) Input
Count = 0
DO ! remove all factors of 2
IF (MOD(I t 2) / 0 OR I t 1) EXITIF (MOD(Input,2) /= 0 .OR. Input == 1) EXIT
Count = Count + 1 ! increase count
WRITE(*,*) 'Factor # ', Count, ': ', 2
Input = Input / 2 ! remove this factorInput = Input / 2 ! remove this factor
END DO
…… use odd numbers here ……
END PROGRAM Factorize
40
END PROGRAM Factorize
Factoring a Number: 3/3Factoring a Number: 3/3
Divisor = 3 ! now we only worry about odd factors
DO ! Try 3, 5, 7, 9, 11 ....
IF (Divisor > Input) EXIT ! factor is too large, exit and done
DO ! try this factor repeatedlyDO ! try this factor repeatedly
IF (MOD(Input,Divisor) /= 0 .OR. Input == 1) EXIT
Count = Count + 1
WRITE(*,*) 'Factor # ', Count, ': ', Divisor
Input = Input / Divisor ! remove this factor from Input
END DO
Divisor = Divisor + 2 ! move to next odd number
END DOEND DO
Note that even 9 15 49 will be used they would only be usedNote that even 9, 15, 49, … will be used, they would only be used
once because Divisor = 3 removes all multiples of 3 (e.g., 9, 15, …),
Divisor = 5 removes all multiples of 5 (e.g., 15, 25, …), and
Divisor = 7 removes all multiples of 7 (e.g., 21, 35, 49, …), etc.
41
Divisor 7 removes all multiples of 7 (e.g., 21, 35, 49, …), etc.
Handling End-of-File: 1/3Handling End of File: 1/3
Very frequently we don’t know the number ofVery frequently we don t know the number of
data items in the input.
Fortran uses IOSTAT= for I/O error handling:Fortran uses IOSTAT= for I/O error handling:
READ(*,*,IOSTAT=v) v1, v2, …, vn
In the above, v is an INTEGER variable.
After the execution of READ(*,*):
If v = 0, READ(*,*) was executed successfully
If v > 0, an error occurred in READ(*,*) and not
all variables received values.
If v < 0, encountered end-of-file, and not all
42
variables received values.
Handling End-of-File: 2/3Handling End of File: 2/3
Every file is ended with a special character.Every file is ended with a special character.
Unix and Windows use Ctrl-D and Ctrl-Z.
When using keyboard to enter data toWhen using keyboard to enter data to
READ(*,*), Ctrl-D means end-of-file in Unix.
If IOSTAT returns a positive value we onlyIf IOSTAT= returns a positive value, we only
know something was wrong in READ(*,*) such
t i t h h fil d i tas type mismatch, no such file, device error, etc.
We really don’t know exactly what happened
because the returned value is system dependent.
43
Handling End-of-File: 3/3Handling End of File: 3/3
i t t t
INTEGER :: io, x, sum 1
3
The total is 8
input output
sum = 0
DO
READ(*,*,IOSTAT=io) x
IF (io > 0) THEN
4
inputIF (io > 0) THEN
WRITE(*,*) 'Check input. Something was wrong'
EXIT
ELSE IF (io < 0) THEN
(* *) h l i
1
&
4
no output
WRITE(*,*) 'The total is ', sum
EXIT
ELSE
sum = sum + x
END IF
END DO
44
Computing Means, etc: 1/4Computing Means, etc: 1/4
Let us compute the arithmetic, geometric andLet us compute the arithmetic, geometric and
harmonic means of unknown number of values:
arithmetic mean =
x x xn1 2 ......
arithmetic mean =
geometric mean =
n
x x xn
n
1 2 ......
harmonic mean =
n
1 1 1
Note that only positive values will be considered
x x xn1 2
......
Note that only positive values will be considered.
This naïve way is not a good method.
45
Computing Means, etc: 2/4Computing Means, etc: 2/4
PROGRAM ComputingMeansPROGRAM ComputingMeans
IMPLICIT NONE
REAL :: X
REAL :: Sum, Product, InverseSum, ,
REAL :: Arithmetic, Geometric, Harmonic
INTEGER :: Count, TotalValid
INTEGER :: IO ! for IOSTAT=
Sum = 0.0
Product = 1.0
InverseSum = 0.0
TotalValid = 0
Count = 0
…… other computation part ……
END PROGRAM ComputingMeans
46
Computing Means, etc: 3/4Computing Means, etc: 3/4
DO
READ(*,*,IOSTAT=IO) X ! read in data
IF (IO < 0) EXIT ! IO < 0 means end-of-file reached
Count = Count + 1 ! otherwise, got some value
IF (IO > 0) THEN ! IO > 0 means something wrongIF (IO > 0) THEN ! IO > 0 means something wrong
WRITE(*,*) 'ERROR: something wrong in your input'
WRITE(*,*) 'Try again please'
ELSE ! IO = 0 means everything is normal
WRITE(*,*) 'Input item ', Count, ' --> ', X
IF (X <= 0.0) THEN
WRITE(*,*) 'Input <= 0. Ignored'
ELSEELSE
TotalValid = TotalValid + 1
Sum = Sum + X
Product = Product * X
InverseSum = InverseSum + 1.0/X
END IF
END IF
END DO
47
END DO
Computing Means, etc: 4/4Computing Means, etc: 4/4
WRITE(*,*)
IF (TotalValid > 0) THEN
Arithmetic = Sum / TotalValid
Geometric = Product**(1.0/TotalValid)
Harmonic = TotalValid / InverseSum
WRITE(*,*) '# of items read --> ', Count
WRITE(*,*) '# of valid items -> ', TotalValidWRITE( , ) # of valid items > , TotalValid
WRITE(*,*) 'Arithmetic mean --> ', Arithmetic
WRITE(*,*) 'Geometric mean --> ', Geometric
WRITE(*,*) 'Harmonic mean --> ', Harmonic
ELSE
WRITE(*,*) 'ERROR: none of the input is positive'
END IF
48
Fortran 90 ArraysFortran 90 Arrays
Program testing can be used to show the presence of bugsProgram testing can be used to show the presence of bugs,
but never to show their absence
Edsger W. Dijkstra
1
Fall 2009
The DIMENSION Attribute: 1/6The DIMENSION Attribute: 1/6
A Fortran 90 program uses the DIMENSIONp g
attribute to declare arrays.
The DIMENSION attribute requires threeq
components in order to complete an array
specification, rank, shape, and extent.
The rank of an array is the number of “indices”
or “subscripts.” The maximum rank is 7 (i.e.,
seven-dimensional).
The shape of an array indicates the number of
elements in each “dimension.”
2
The DIMENSION Attribute: 2/6The DIMENSION Attribute: 2/6
The rank and shape of an array is representedThe rank and shape of an array is represented
as (s1,s2,…,sn), where n is the rank of the array
and si (1 i n) is the number of elements in theand si (1 i n) is the number of elements in the
i-th dimension.
(7) means a rank 1 array with 7 elements(7) means a rank 1 array with 7 elements
(5,9) means a rank 2 array (i.e., a table)
h fi t d d di i h 5whose first and second dimensions have 5
and 9 elements, respectively.
(10,10,10,10) means a rank 4 array that has
10 elements in each dimension.
3
The DIMENSION Attribute: 3/6The DIMENSION Attribute: 3/6
The extent is written as m:n, where m and n (mThe extent is written as m:n, where m and n (m
n) are INTEGERs. We saw this in the SELECT
CASE, substring, etc., g,
Each dimension has its own extent.
A t t f di i i th f itAn extent of a dimension is the range of its
index. If m: is omitted, the default is 1.
i i i 3 2 1 0-3:2 means possible indices are -3, -2 , -1, 0,
1, 2
5:8 means possible indices are 5,6,7,8
7 means possible indices are 1,2,3,4,5,6,7
4
p , , , , , ,
The DIMENSION Attribute: 4/6The DIMENSION Attribute: 4/6
The DIMENSION attribute has the followingg
form:
DIMENSION(extent-1, extent-2, …, extent-n)( , , , )
Here, extent-i is the extent of dimension i.
This means an array of dimension n (i.e., nThis means an array of dimension n (i.e., n
indices) whose i-th dimension index has a range
given by extent-i.g y
Just a reminder: Fortran 90 only allows
maximum 7 dimensions.
Exercise: given a DIMENSION attribute,
determine its shape.
5
p
The DIMENSION Attribute: 5/6The DIMENSION Attribute: 5/6
Here are some examples:Here are some examples:
DIMENSION(-1:1) is a 1-dimensional
array with possible indices -1 0 1array with possible indices -1,0,1
DIMENSION(0:2,3) is a 2-dimensional
(i t bl ) P ibl l f tharray (i.e., a table). Possible values of the
first index are 0,1,2 and the second 1,2,3
i 3 i iDIMENSION(3,4,5) is a 3-dimensional
array. Possible values of the first index are
1,2,3, the second 1,2,3,4, and the third
1,2,3,4,5.
6
The DIMENSION Attribute: 6/6The DIMENSION Attribute: 6/6
Array declaration is simple. Add they p
DIMENSION attribute to a type declaration.
Values in the DIMENSION attribute are usuallyy
PARAMETERs to make program modifications
easier.
INTEGER, PARAMETER :: SIZE=5, LOWER=3, UPPER = 5
INTEGER, PARAMETER :: SMALL = 10, LARGE = 15
REAL, DIMENSION(1:SIZE) :: x
INTEGER, DIMENSION(LOWER:UPPER,SMALL:LARGE) :: a,b, ( , ) ,
LOGICAL, DIMENSION(2,2) :: Truth_Table
7
Use of Arrays: 1/3Use of Arrays: 1/3
Fortran 90 has, in general, three different ways, g , y
to use arrays: referring to individual array
element, referring to the whole array, and
referring to a section of an array.
The first one is very easy. One just starts with
the array name, followed by () between which
are the indices separated by ,.
Note that each index must be an INTEGER or an
expression evaluated to an INTEGER, and the
l f i d t b i th f thvalue of an index must be in the range of the
corresponding extent. But, Fortran 90 won’t
check it for you
8
check it for you.
Use of Arrays: 2/3Use of Arrays: 2/3
Suppose we have the following declarationsSuppose we have the following declarations
INTEGER, PARAMETER :: L_BOUND = 3, U_BOUND = 10
INTEGER, DIMENSION(L BOUND:U BOUND) :: xINTEGER, DIMENSION(L_BOUND:U_BOUND) :: x
DO i = L_BOUND, U_BOUND
x(i) = i
DO i = L_BOUND, U_BOUND
IF (MOD(i,2) == 0) THEN
iEND DO x(i) = 0
ELSE
x(i) = 1
array x() has 3,4,5,…, 10
END IF
END DO
array x() has 1 0 1 0 1 0 1 0
9
array x() has 1,0,1,0,1,0,1,0
Use of Arrays: 3/3Use of Arrays: 3/3
Suppose we have the following declarations:
INTEGER, PARAMETER :: L_BOUND = 3, U_BOUND = 10
INTEGER, DIMENSION(L_BOUND:U_BOUND, &
L_BOUND:U_BOUND) :: a
DO i = L_BOUND, U_BOUND
DO j = L_BOUND, U_BOUND
a(i j) = 0
DO i = L_BOUND, U_BOUND
DO j = i+1, U_BOUND
t = a(i,j)a(i,j) = 0
END DO
a(i,i) = 1
t a(i,j)
a(i,j) = a(j,i)
a(j,i) = t
END DO
END DO END DO
generate an identity matrix Swapping the lower and
upper diagonal parts (i e
10
upper diagonal parts (i.e.,
the transpose of a matrix)
The Implied DO: 1/7The Implied DO: 1/7
Fortran has the implied DO that can generatep g
efficiently a set of values and/or elements.
The implied DO is a variation of the DO-loop.p p
The implied DO has the following syntax:
(item-1 item-2 item-n v=initial final step)(item 1, item 2, …,item n, v=initial,final,step)
Here, item-1, item-2, …, item-n are
variables or expressions, v is an INTEGERvariables or expressions, v is an INTEGER
variable, and initial, final, and step are
INTEGER expressions.p
“v=initial,final,step” is exactly what we
saw in a DO-loop.
11
p
The Implied DO: 2/7The Implied DO: 2/7
The execution of an implied DO below lets variablep
v to start with initial, and step though to
final with a step size step.
(item 1 item 2 item n v=initial final step)(item-1, item-2, …,item-n, v=initial,final,step)
The result is a sequence of items.
(i+1, i=1,3) generates 2 3 4(i+1, i=1,3) generates 2, 3, 4.
(i*k, i+k*i, i=1,8,2) generates k, 1+k (i
= 1), 3*k, 3+k*3 (i = 3), 5*k, 5+k*5 (i = 5),), , ( ), , ( ),
7*k, 7+k*7 (i = 7).
(a(i),a(i+2),a(i*3-1),i*4,i=3,5)
t (3) ( ) (8) 12 (i 3) (4)generates a(3), a(5), a(8) , 12 (i=3), a(4),
a(6), a(11), 16 (i=4), a(5), a(7), a(14), 20.
12
The Implied DO: 3/7The Implied DO: 3/7
Implied DO may be nested.p y
(i*k,(j*j,i*j,j=1,3), i=2,4)
In the above (j*j i*j j 1 3) is nested inIn the above, (j*j,i*j,j=1,3) is nested in
the implied i loop.
Here are the results:
When i = 2, the implied DO generates
2*k, (j*j,2*j,j=1,3)
Then j goes from 1 to 3 and generatesThen, j goes from 1 to 3 and generates
2*k, 1*1, 2*1, 2*2, 2*2, 3*3, 2*3
j = 1 j = 2 j = 3
13
j = 1 j = 2 j = 3
The Implied DO: 4/7The Implied DO: 4/7
Continue with the previous examplep p
(i*k,(j*j,i*j,j=1,3), i=2,4)
When i = 3, it generates the following:g g
3*k, (j*j,3*j,j=1,3)
Expanding the j loop yields:p g j p y
3*k, 1*1, 3*1, 2*2, 3*2, 3*3, 3*3
When i = 4, the i loop generates, p g
4*k, (j*j, 4*j, j=1,3)
Expanding the j loop yieldsp g j p y
4*k, 1*1, 4*1, 2*2, 4*2, 3*3, 4*3
14j = 1 j = 2 j = 3
The Implied DO: 5/7The Implied DO: 5/7
The following generates a multiplication table:The following generates a multiplication table:
((i*j,j=1,9),i=1,9)
When i 1 the inner j implied DO loopWhen i = 1, the inner j implied DO-loop
produces 1*1, 1*2, …, 1*9
When i = 2, the inner j implied DO-loop
produces 2*1, 2*2, …, 2*9
When i = 9, the inner j implied DO-loop
produces 9*1, 9*2, …, 9*9
15
The Implied DO: 6/7The Implied DO: 6/7
The following produces all upper triangularThe following produces all upper triangular
entries, row-by-row, of a 2-dimensional array:
((a(p q) q = p n) p = 1 n)((a(p,q),q = p,n),p = 1,n)
When p = 1, the inner q loop produces a(1,1),
a(1 2) a(1 n)a(1,2), …, a(1,n)
When p=2, the inner q loop produces a(2,2),
a(2,3), …., a(2,n)
When p=3, the inner q loop produces a(3,3),
a(3,4), …, a(3,n)
When p=n, the inner q loop produces a(n,n)
16
p , q p p ( , )
The Implied DO: 7/7The Implied DO: 7/7
The following produces all upper triangularThe following produces all upper triangular
entries, column-by-column:
((a(p q) p = 1 q) q = 1 n)((a(p,q),p = 1,q),q = 1,n)
When q=1, the inner p loop produces a(1,1)
When q=2, the inner p loop produces a(1,2),
a(2,2)
When q=3, the inner p loop produces a(1,3),
a(2,3), …, a(3,3)
When q=n, the inner p loop produces a(1,n),
a(2,n), a(3,n), …, a(n,n)
17
( , ), ( , ), , ( , )
Array Input/Output: 1/8Array Input/Output: 1/8
Implied DO can be used in READ(*,*) andp ( , )
WRITE(*,*) statements.
When an implied DO is used it is equivalent toWhen an implied DO is used, it is equivalent to
execute the I/O statement with the generated
elementselements.
The following prints out a multiplication table
(* *)((i * j i*j j 1 9) i 1 9)WRITE(*,*)((i,“*”,j,“=“,i*j,j=1,9),i=1,9)
The following has a better format (i.e., 9 rows):
DO i = 1, 9
WRITE(*,*) (i, “*”, j, “=“, i*j, j=1,9)
18
END DO
Array Input/Output: 2/8Array Input/Output: 2/8
The following shows three ways of reading ng y g
data items into an one dimensional array a().
Are they the same?Are they the same?
READ(*,*) n,(a(i),i=1,n)(1)
READ(*,*) n
i i
( )
(2)
READ(*,*) (a(i),i=1,n)
READ(* *) n(3) READ(*,*) n
DO i = 1, n
READ(*,*) a(i)
(3)
19
END DO
Array Input/Output: 3/8Array Input/Output: 3/8
Suppose we wish to fill a(1), a(2) and a(3)pp ( ), ( ) ( )
with 10, 20 and 30. The input may be:
3 10 20 303 10 20 30
Each READ starts from a new line!
OKREAD(*,*) n,(a(i),i=1,n)
READ(* *) n
(1)
(2)
OK
Wrong! n gets 3 andREAD(*,*) n
READ(*,*) (a(i),i=1,n)
(2)
Wrong! n gets 3 and
the second READ fails
READ(*,*) n
DO i = 1, n
(3) Wrong! n gets 3 and
the three READs fail
20
READ(*,*) a(i)
END DO
Array Input/Output: 4/8Array Input/Output: 4/8
What if the input is changed to the following?What if the input is changed to the following?
3
10 20 30
OK
10 20 30
READ(*,*) n,(a(i),i=1,n)
READ(* *) n
(1)
(2)
OK
OK. Why????READ(*,*) n
READ(*,*) (a(i),i=1,n)
(2)
OK. Why????
READ(*,*) n
DO i = 1, n
(3) Wrong! n gets 3, a(1) has
10; but, the next two
READs fail
21
READ(*,*) a(i)
END DO
READs fail
Array Input/Output: 5/8Array Input/Output: 5/8
What if the input is changed to the following?What if the input is changed to the following?
3
10
20
OK
20
30
READ(*,*) n,(a(i),i=1,n)
READ(* *) n
(1)
(2)
OK
OKREAD(*,*) n
READ(*,*) (a(i),i=1,n)
(2)
OK
READ(*,*) n
DO i = 1, n
(3) OK
22
READ(*,*) a(i)
END DO
Array Input/Output: 6/8Array Input/Output: 6/8
Suppose we have a two-dimensional array a():pp y ()
INTEGER, DIMENSION(2:4,0:1) :: a
Suppose further the READ is the following:Suppose further the READ is the following:
READ(*,*) ((a(i,j),j=0,1),i=2,4)
What are the results for the following input?
1 2 3
1 2 3 4 5 6
1 2 3
4 5 6
7 8 9
0 1 0 1
1 2
3 4
1 2
3 4
2
3
2
3
0 1 0 1
23
3 4
5 6
3 4
5 64 4
Array Input/Output: 7/8Array Input/Output: 7/8
Suppose we have a two-dimensional array a():pp y ()
INTEGER, DIMENSION(2:4,0:1) :: a
DO i = 2 4DO i = 2, 4
READ(*,*) (a(i,j),j=0,1)
END DOEND DO
What are the results for the following input?
1 2 3 4 5 6
1 2 3
4 5 6
7 8 97 8 9
1 2 1 2A(2,0)=1 row-by-row2
0 1 0 1
24
? ?
? ?
4 5
7 8
A(2,1)=2
then error!
y
3
4
Array Input/Output: 8/8Array Input/Output: 8/8
Suppose we have a two-dimensional array a():pp y ()
INTEGER, DIMENSION(2:4,0:1) :: a
DO j = 0 1DO j = 0, 1
READ(*,*) (a(i,j),i=2,4)
END DOEND DO
What are the results for the following input?
1 2 3 4 5 6
1 2 3
4 5 6
7 8 97 8 9
1 ? 1 4
A(2,0)=1
A(3,0)=2 column-by-column2
0 1 0 1
25
2 ?
3 ?
2 5
3 6
A(4,0)=3
then error!
y
3
4
Matrix Multiplication: 1/2Matrix Multiplication: 1/2
Read a l m matrix Al m and a m n matrix Bm n,Read a l m matrix Al m and a m n matrix Bm n,
and compute their product Cl n = Al m Bm n.
PROGRAM Matrix MultiplicationPROGRAM Matrix_Multiplication
IMPLICIT NONE
INTEGER, PARAMETER :: SIZE = 100
INTEGER DIMENSION(1:SIZE 1:SIZE) :: A B CINTEGER, DIMENSION(1:SIZE,1:SIZE) :: A, B, C
INTEGER :: L, M, N, i, j, k
READ(*,*) L, M, N ! read sizes <= 100
iDO i = 1, L
READ(*,*) (A(i,j), j=1,M) ! A() is L-by-M
END DO
DO i = 1, M
READ(*,*) (B(i,j), j=1,N) ! B() is M-by-N
END DO
26
…… other statements ……
END PROGRAM Matrix_Multiplication
Matrix Multiplication: 2/2Matrix Multiplication: 2/2
The following does multiplication and outputThe following does multiplication and output
DO i = 1, L
DO j = 1, N
C(i,j) = 0 ! for each C(i,j)
DO k = 1, M ! (row i of A)*(col j of B)
C(i,j) = C(i,j) + A(i,k)*B(k,j)
END DO
END DOEND DO
END DO
DO i = 1 L ! print row-by-rowDO i = 1, L ! print row-by-row
WRITE(*,*) (C(i,j), j=1, N)
END DO
27
Arrays as Arguments: 1/4Arrays as Arguments: 1/4
Arrays may also be used as arguments passingy y g p g
to functions and subroutines.
Formal argument arrays may be declared asg y y
usual; however, Fortran 90 recommends the use
of assumed-shape arrays.
An assumed-shape array has its lower bound in
each extent specified; but, the upper bound is
not used.
formal arguments
REAL, DIMENSION(-3:,1:), INTENT(IN) :: x, y
INTEGER, DIMENSION(:), INTENT(OUT) :: a, b
28assumed-shape
Arrays as Arguments: 2/4Arrays as Arguments: 2/4
The extent in each dimension is an expressionThe extent in each dimension is an expression
that uses constants or other non-array formal
arguments with INTENT(IN) :g ( )
SUBROUTINE Test(x,y,z,w,l,m,n)
I PLICIT NONE
assumed-shape
IMPLICIT NONE
INTEGER, INTENT(IN) :: l, m, n
REAL, DIMENSION(10:),INTENT(IN) :: x
INTEGER, DIMENSION(-1:,m:), INTENT(OUT) :: y
LOGICAL, DIMENSION(m,n:), INTENT(OUT) :: z
REAL, DIMENSION(-5:5), INTENT(IN) :: w
…… other statements ……
END SUBROUTINE Test DIMENSION(1:m,n:)
29not assumed-shape
Arrays as Arguments: 3/4Arrays as Arguments: 3/4
Fortran 90 automatically passes an array and itsFortran 90 automatically passes an array and its
shape to a formal argument.
A subprogram receives the shape and uses theA subprogram receives the shape and uses the
lower bound of each extent to recover the upper
boundbound.
INTEGER,DIMENSION(2:10)::Score
……
CALL Funny(Score) shape is (9)
SUBROUTINE Funny(x)
IMPLICIT NONE
INTEGER,DIMENSION(-1:),INTENT(IN) :: x
30
…… other statements ……
END SUBROUTINE Funny (-1:7)
Arrays as Arguments: 4/4Arrays as Arguments: 4/4
One more exampleOne more example
REAL, DIMENSION(1:3,1:4) :: x, ( , )
INTEGER :: p = 3, q = 2
CALL Fast(x,p,q) shape is (3,4)
SUBROUTINE Fast(a,m,n)( , , )
IMPLICIT NONE
INTEGER,INTENT(IN) :: m,n
REAL DIMENSION(-m: n:) INTENT(IN)::aREAL,DIMENSION( m:,n:),INTENT(IN)::a
…… other statements ……
END SUBROUTINE Fast
31
(-m:,n:) becomes (-3:-1,2:5)
The SIZE() Intrinsic Function: 1/2The SIZE() Intrinsic Function: 1/2
How do I know the shape of an array?p y
Use the SIZE() intrinsic function.
SIZE() requires two arguments, an arraySIZE() requires two arguments, an array
name and an INTEGER, and returns the size of
the array in the given “dimension.”y g
INTEGER,DIMENSION(-3:5,0:100):: a
shape is (9,101)
WRITE(*,*) SIZE(a,1), SIZE(a,2)
CALL ArraySize(a)
(1:9,5:105)
SUBROUTINE ArraySize(x)
INTEGER,DIMENSION(1:,5:),… :: x
Both WRITE prints
9 and 101
32
WRITE(*,*) SIZE(x,1), SIZE(x,2)
9 and 101
The SIZE() Intrinsic Function : 2/2The SIZE() Intrinsic Function : 2/2
INTEGER,DIMENSION(-1:1,3:6):: Empty
CALL Fill(Empty)CALL Fill(Empty)
DO i = -1,1
WRITE(*,*) (Empty(i,j),j=3,6)
END DO
SUBROUTINE Fill(y)
I PLICIT NONE
END DO shape is (3,4)
IMPLICIT NONE
INTEGER,DIMENSION(1:,1:),INTENT(OUT)::y
INTEGER :: U1, U2, i, j
output U1 = SIZE(y,1)
U2 = SIZE(y,2)
DO i = 1, U1
2 3 4 5
3 4 5 6
4 5 6 7
output
(1:3 1:4)
DO j = 1, U2
y(i,j) = i + j
END DO
4 5 6 7 (1:3,1:4)
33
END DO
END DO
END SUBROUTINE Fill
Local Arrays: 1/2Local Arrays: 1/2
Fortran 90 permits to declare local arrays usingFortran 90 permits to declare local arrays using
INTEGER formal arguments with the
INTENT(IN) attribute.( )
SUBROUTINE Compute(X m n)INTEGER, & SUBROUTINE Compute(X, m, n)
IMPLICIT NONE
INTEGER,INTENT(IN) :: m, n
INTEGER DIMENSION(1 1 ) &
INTEGER, &
DIMENSION(100,100) &
::a, z
W(1:3) Y(1:3,1:15)
INTEGER,DIMENSION(1:,1:), &
INTENT(IN) :: X
INTEGER,DIMENSION(1:m) :: W
local arrays
CALL Compute(a,3,5)
CALL Compute(z,6,8)
REAL,DIMENSION(1:m,1:m*n)::Y
…… other statements ……
END SUBROUTINE ComputeW(1:6) Y(1:6,1:48)
34
W(1:6) Y(1:6,1:48)
Local Arrays: 2/2Local Arrays: 2/2
Just like you learned in C/C++ and Java,
memory of local variables and local arrays in
Fortran 90 is allocated before entering a
subprogram and deallocated on return.
Fortran 90 uses the formal arguments tog
compute the extents of local arrays.
Therefore, different calls with different valuesTherefore, different calls with different values
of actual arguments produce different shape
and extent for the same local array. However,and extent for the same local array. However,
the rank of a local array will not change.
35
The ALLOCATBLE AttributeThe ALLOCATBLE Attribute
In many situations, one does not know exactlyIn many situations, one does not know exactly
the shape or extents of an array. As a result,
one can only declare a “large enough” array.one can only declare a large enough array.
The ALLOCATABLE attribute comes to rescue.
The ALLOCATABLE attribute indicates that atThe ALLOCATABLE attribute indicates that at
the declaration time one only knows the rank of
b t t it t tan array but not its extent.
Therefore, each extent has only a colon :.
INTEGER,ALLOCATABLE,DIMENSION(:) :: a
REAL,ALLOCATABLE,DIMENSION(:,:) :: b
36
LOGICAL,ALLOCATABLE,DIMENSION(:,:,:) :: c
The ALLOCATE Statement: 1/3The ALLOCATE Statement: 1/3
The ALLOCATE statement has the followingg
syntax:
ALLOCATE(array-1 array-n STAT=v)ALLOCATE(array-1,…,array-n,STAT=v)
Here, array-1, …, array-n are array names
with complete extents as in the DIMENSIONwith complete extents as in the DIMENSION
attribute, and v is an INTEGER variable.
Af i f if 0After the execution of ALLOCATE, if v 0, then
at least one arrays did not get memory.
REAL,ALLOCATABLE,DIMENSION(:) :: a
LOGICAL,ALLOCATABLE,DIMENSION(:,:) :: x
37
INTEGER :: status
ALLOCATE(a(3:5), x(-10:10,1:8), STAT=status)
The ALLOCATE Statement: 2/3The ALLOCATE Statement: 2/3
ALLOCATE only allocates arrays with they y
ALLOCATABLE attribute.
The extents in ALLOCATE can use INTEGERThe extents in ALLOCATE can use INTEGER
expressions. Make sure all involved variables
have been initialized properlyhave been initialized properly.
INTEGER,ALLOCATABLE,DIMENSION(:,:) :: x
INTEGER,ALLOCATABLE,DIMENSION(:) :: aINTEGER,ALLOCATABLE,DIMENSION(:) :: a
INTEGER :: m, n, p
READ(*,*) m, n
ALLOCATE(x(1:m m+n:m*n) a(-(m*n):m*n) STAT=p)ALLOCATE(x(1:m,m+n:m*n),a(-(m*n):m*n),STAT=p)
IF (p /= 0) THEN
…… report error here ……
38
If m = 3 and n = 5, then we have
x(1:3,8:15) and a(-15:15)
The ALLOCATE Statement: 3/3The ALLOCATE Statement: 3/3
ALLOCATE can be used in subprograms.p g
Formal arrays are not ALLOCATABLE.
I l ll t d i bIn general, an array allocated in a subprogram
is a local entity, and is automatically
d ll t d h th b tdeallocated when the subprogram returns.
Watch for the following odd use:
PROGRAM Try_not_to_do_this
IMPLICIT NONE
REAL,ALLOCATABLE,DIMENSION(:) :: x
CONTAINS
SUBROUTINE Hey(…)
ALLOCATE(x(1:10))
39
ALLOCATE(x(1:10))
END SUBROUTINE Hey
END PROGRAM Try_not_to_do_this
The DEALLOCATE StatementThe DEALLOCATE Statement
Allocated arrays may be deallocated by theAllocated arrays may be deallocated by the
DEALLOCATE() statement as shown below:
DEALLOCATE(array-1 array-n STAT=v)DEALLOCATE(array-1,…,array-n,STAT=v)
Here, array-1, …, array-n are the names of
allocated arrays and is an INTEGER variableallocated arrays, and v is an INTEGER variable.
If deallocation fails (e.g., some arrays were not
) i iallocated), the value in v is non-zero.
After deallocation of an array, it is not available
and any access will cause a program error.
DEALLOCATE(a b c STAT=status)
40
DEALLOCATE(a, b, c, STAT=status)
The ALLOCATED Intrinsic FunctionThe ALLOCATED Intrinsic Function
The ALLOCATED(a) function returns .TRUE.( )
if ALLOCATABLE array a has been allocated.
Otherwise, it returns .FALSE.,
INTEGER,ALLOCATABLE,DIMENSION(:) :: Mat
INTEGER :: status
ALLOCATE(Mat(1:100),STAT=status)
…… ALLOCATED(Mat) returns .TRUE. …..
…… other statements ……
DEALLOCATE(Mat,STAT=status)DEALLOCATE(Mat,STAT status)
…… ALLOCATED(Mat) returns .FALSE. ……
41
Fortran 90 SubprogramsFortran 90 Subprograms
If Fortran is the lingua franca, then certainly it must
be true that BASIC is the lingua playpen
1
Thomas E. Kurtz
Co-Designer of the BASIC language
Fall 2010
Functions and SubroutinesFunctions and Subroutines
Fortran 90 has two types of subprograms,Fortran 90 has two types of subprograms,
functions and subroutines.
A Fortran 90 function is a function like those inA Fortran 90 function is a function like those in
C/C++. Thus, a function returns a computed
result via the function nameresult via the function name.
If a function does not have to return a function
l b tivalue, use subroutine.
2
Function Syntax: 1/3Function Syntax: 1/3
A Fortran function, or function subprogram,, p g ,
has the following syntax:
type FUNCTION function-name (arg1, arg2, ..., argn)
IMPLICIT NONE
[specification part]
[execution part]p
[subprogram part]
END FUNCTION function-name
type is a Fortran 90 type (e g INTEGERtype is a Fortran 90 type (e.g., INTEGER,
REAL, LOGICAL, etc) with or without KIND.
function name is a Fortran 90 identifierfunction-name is a Fortran 90 identifier
arg1, …, argn are formal arguments.
3
Function Syntax: 2/3Function Syntax: 2/3
A function is a self-contained unit that receives
some “input” from the outside world via its
formal arguments, does some computations, and
returns the result with the name of the function.
Somewhere in a function there has to be one or
more assignment statements like this:
function-name = expression
where the result of expression is saved to the
name of the function.
Note that function-name cannot appear in
the right-hand side of any expression.
4
Function Syntax: 3/3Function Syntax: 3/3
In a type specification, formal argumentsyp p , g
should have a new attribute INTENT(IN).
The meaning of INTENT(IN) is that theg
function only takes the value from a formal
argument and does not change its content.
Any statements that can be used in PROGRAM
can also be used in a FUNCTION.
5
Function ExampleFunction Example
Note that functions can have no formal argument.Note that functions can have no formal argument.
But, () is still required.
INTEGER FUNCTION Factorial(n)
IMPLICIT NONE
REAL FUNCTION GetNumber()
IMPLICIT NONE
Factorial computation Read and return a positive real number
IMPLICIT NONE
INTEGER, INTENT(IN) :: n
INTEGER :: i, Ans
IMPLICIT NONE
REAL :: Input_Value
DO
WRITE(*,*) 'A positive number: '
Ans = 1
DO i = 1, n
Ans = Ans * i
END DO
( , ) p
READ(*,*) Input_Value
IF (Input_Value > 0.0) EXIT
WRITE(*,*) 'ERROR. try again.'
END DOEND DO
Factorial = Ans
END FUNCTION Factorial
END DO
GetNumber = Input_Value
END FUNCTION GetNumber
6
Common Problems: 1/2Common Problems: 1/2
forget function type forget INTENT(IN) not an error
FUNCTION DoSomething(a, b)
IMPLICIT NONE
INTEGER, INTENT(IN) :: a, b
REAL FUNCTION DoSomething(a, b)
IMPLICIT NONE
INTEGER :: a, b
g yp g
DoSomthing = SQRT(a*a + b*b)
END FUNCTION DoSomething
DoSomthing = SQRT(a*a + b*b)
END FUNCTION DoSomething
REAL FUNCTION DoSomething(a, b)
IMPLICIT NONE
REAL FUNCTION DoSomething(a, b)
IMPLICIT NONE
change INTENT(IN) argument forget to return a value
INTEGER, INTENT(IN) :: a, b
IF (a > b) THEN
a = a - b
ELSE
INTEGER, INTENT(IN) :: a, b
INTEGER :: c
c = SQRT(a*a + b*b)
END FUNCTION DoSomethingELSE
a = a + b
END IF
DoSomthing = SQRT(a*a+b*b)
END FUNCTION DoSomething
7
END FUNCTION DoSomething
Common Problems: 2/2Common Problems: 2/2
REAL FUNCTION DoSomething(a, b)
IMPLICIT NONE
REAL FUNCTION DoSomething(a, b)
IMPLICIT NONE
incorrect use of function name only the most recent value is returned
IMPLICIT NONE
INTEGER, INTENT(IN) :: a, b
DoSomething = a*a + b*b
DoSomething = SQRT(DoSomething)
IMPLICIT NONE
INTEGER, INTENT(IN) :: a, b
DoSomething = a*a + b*b
DoSomething = SQRT(a*a - b*b)
END FUNCTION DoSomething END FUNCTION DoSomething
8
Using FunctionsUsing Functions
The use of a user-defined function is similar toThe use of a user defined function is similar to
the use of a Fortran 90 intrinsic function.
The following uses function Factorial(n) toThe following uses function Factorial(n) to
compute the combinatorial coefficient C(m,n) ,
where m and n are actual arguments:where m and n are actual arguments:
Cmn = Factorial(m)/(Factorial(n)*Factorial(m-n))
Note that the combinatorial coefficient is
defined as follows, although it is not the most
efficient way:
C m n
m
( )
!
9
C m n
n m n
( , )
! ( )!
Argument Association : 1/5Argument Association : 1/5
Argument association is a way of passing valuesArgument association is a way of passing values
from actual arguments to formal arguments.
If an actual argument is an expression it isIf an actual argument is an expression, it is
evaluated and stored in a temporary location
from which the value is passed to thefrom which the value is passed to the
corresponding formal argument.
If t l t i i bl it l iIf an actual argument is a variable, its value is
passed to the corresponding formal argument.
C d h i i blConstant and (A), where A is variable, are
considered expressions.
10
Argument Association : 2/5Argument Association : 2/5
Actual arguments are variables:Actual arguments are variables:
a b cWRITE(*,*) Sum(a,b,c)
x y z
INTEGER FUNCTION Sum(x,y,z)
IMPLICIT NONE
INTEGER INTENT(IN)::x y z x y zINTEGER,INTENT(IN)::x,y,z
……..
END FUNCTION Sum
11
Argument Association : 3/5Argument Association : 3/5
Expressions as actual arguments. Dashed lineExpressions as actual arguments. Dashed line
boxes are temporary locations.
a+b b+c cWRITE(*,*) Sum(a+b,b+c,c)
x y z
INTEGER FUNCTION Sum(x,y,z)
IMPLICIT NONE
INTEGER INTENT(IN)::x y z x y zINTEGER,INTENT(IN)::x,y,z
……..
END FUNCTION Sum
12
Argument Association : 4/5Argument Association : 4/5
Constants as actual arguments. Dashed lineConstants as actual arguments. Dashed line
boxes are temporary locations.
1 2 3WRITE(*,*) Sum(1, 2, 3)
x y z
INTEGER FUNCTION Sum(x,y,z)
IMPLICIT NONE
INTEGER INTENT(IN)::x y z x y zINTEGER,INTENT(IN)::x,y,z
……..
END FUNCTION Sum
13
Argument Association : 5/5Argument Association : 5/5
A variable in () is considered as an expression.() p
Dashed line boxes are temporary locations.
(a) (b) (c)WRITE(*,*) Sum((a), (b), (c))
x y z
INTEGER FUNCTION Sum(x,y,z)
IMPLICIT NONE
INTEGER INTENT(IN)::x y z x y zINTEGER,INTENT(IN)::x,y,z
……..
END FUNCTION Sum
14
Where Do Functions Go: 1/2Where Do Functions Go: 1/2
Fortran 90 functions can be internal or external.Fortran 90 functions can be internal or external.
Internal functions are inside of a PROGRAM, the
main program:main program:
PROGRAM program-name
IMPLICIT NONEC NON
[specification part]
[execution part]
CONTAINSCONTAINS
[functions]
END PROGRAM program-name
Although a function can contain other functions,
i t l f ti t h i t l f ti
15
internal functions cannot have internal functions.
Where Do Functions Go: 2/2Where Do Functions Go: 2/2
The right shows PROGRAM TwoFunctionsg
two internal
functions,
PROGRAM TwoFunctions
IMPLICIT NONE
REAL :: a, b, A_Mean, G_Mean
READ(*,*) a, b
ArithMean()
and GeoMean().
A_Mean = ArithMean(a, b)
G_Mean = GeoMean(a,b)
WRITE(*,*) a, b, A_Mean, G_Mean
CONTAINS
They take two
REAL actual
t d
CONTAINS
REAL FUNCTION ArithMean(a, b)
IMPLICIT NONE
REAL, INTENT(IN) :: a, b
arguments and
compute and
return a REAL
ArithMean = (a+b)/2.0
END FUNCTION ArithMean
REAL FUNCTION GeoMean(a, b)
IMPLICIT NONEreturn a REAL
function value.
IMPLICIT NONE
REAL, INTENT(IN) :: a, b
GeoMean = SQRT(a*b)
END FUNCTION GeoMean
16
END PROGRAM TwoFunctions
Scope Rules: 1/5Scope Rules: 1/5
Scope rules tell us if an entity (i.e., variable,Scope rules tell us if an entity (i.e., variable,
parameter and function) is visible or accessible
at certain places.at certain places.
Places where an entity can be accessed or visible
is referred as the scope of that entityis referred as the scope of that entity.
17
Scope Rules: 2/5Scope Rules: 2/5
Scope Rule #1: The scope of an entity is the
program or function in which it is declared.
PROGRAM Scope_1 Scope of PI, m and n
IMPLICIT NONE
REAL, PARAMETER :: PI = 3.1415926
INTEGER :: m, n
...................
CONTAINS
INTEGER FUNCTION Funct1(k)
IMPLICIT NONE
Scope of k, f and g
local to Funct1()
INTEGER, INTENT(IN) :: k
REAL :: f, g
..........
END FUNCTION Funct1END FUNCTION Funct1
REAL FUNCTION Funct2(u, v)
IMPLICIT NONE
REAL, INTENT(IN) :: u, v
Scope of u and v
local to Funct2()
18
..........
END FUNCTION Funct2
END PROGRAM Scope_1
Scope Rules: 3/5Scope Rules: 3/5
Scope Rule #2 :A global entity is visible to allp
contained functions.
PROGRAM Scope_2
IMPLICIT NONE
INTEGER :: a = 1, b = 2, c = 3
WRITE(*,*) Add(a)
a, b and c are global
The first Add(a) returns 4
Th d dd tc = 4
WRITE(*,*) Add(a)
WRITE(*,*) Mul(b,c)
CONTAINS
The second Add(a) returns 5
Mul(b,c) returns 8
INTEGER FUNCTION Add(q)
IMPLICIT NONE
INTEGER, INTENT(IN) :: q
Add = q + c
Thus, the two Add(a)’s produce different
results, even though the formal arguments
are the same! This is usually referred toEND FUNCTION Add
INTEGER FUNCTION Mul(x, y)
IMPLICIT NONE
INTEGER, INTENT(IN) :: x, y
are the same! This is usually referred to
as side effect.
Avoid using global entities!
19
Mul = x * y
END FUNCTION Mul
END PROGRAM Scope_2
Avoid using global entities!
Scope Rules: 4/5Scope Rules: 4/5
Scope Rule #2 :A global entity is visible to allp
contained functions.
PROGRAM Global
IMPLICIT NONE
INTEGER :: a = 10, b = 20
The first Add(a,b) returns 30
It also changes b to 30
Th 2 d WRITE(* *) h 30
INTEGER :: a 10, b 20
WRITE(*,*) Add(a,b)
WRITE(*,*) b
WRITE(*,*) Add(a,b)
The 2nd WRITE(*,*) shows 30
The 2nd Add(a,b) returns 40
This is a bad side effect
CONTAINS
INTEGER FUNCTION Add(x,y)
IMPLICIT NONE
Avoid using global entities!
INTEGER, INTENT(IN)::x, y
b = x+y
Add = b
20
END FUNCTION Add
END PROGRAM Global
Scope Rules: 5/5Scope Rules: 5/5
Scope Rule #3 :An entity declared in the scope of
th tit i l diff t ifanother entity is always a different one even if
their names are identical.
PROGRAM Scope_3
IMPLICIT NONE
INTEGER :: i, Max = 5
DO i 1 Max
Although PROGRAM and FUNCTION
Sum() both have INTEGER variable i,
They are TWO different entities.
DO i = 1, Max
Write(*,*) Sum(i)
END DO
CONTAINS
y
Hence, any changes to i in Sum() will
not affect the i in PROGRAM.
INTEGER FUNCTION Sum(n)
IMPLICIT NONE
INTEGER, INTENT(IN) :: n
INTEGER :: i sINTEGER :: i, s
s = 0
…… other computation ……
Sum = s
21
END FUNCTION Sum
END PROGRAM Scope_3
Example: 1/4Example: 1/4
If a triangle has side lengths a, b and c, the HeronIf a triangle has side lengths a, b and c, the Heron
formula computes the triangle area as follows,
where s = (a+b+c)/2:where s (a b c)/2:
Area s s a s b s c( ) ( ) ( )
To form a triangle, a, b and c must fulfill the
following two conditions:
a > 0, b > 0 and c > 0
a+b > c, a+c > b and b+c > a
22
Example: 2/4Example: 2/4
LOGICAL Function TriangleTest() makesg ()
sure all sides are positive, and the sum of any
two is larger than the third.two is larger than the third.
LOGICAL FUNCTION TriangleTest(a, b, c)LOGICAL FUNCTION TriangleTest(a, b, c)
IMPLICIT NONE
REAL, INTENT(IN) :: a, b, c
LOGICAL :: test1, test2OG C :: test , test
test1 = (a > 0.0) .AND. (b > 0.0) .AND. (c > 0.0)
test2 = (a + b > c) .AND. (a + c > b) .AND. (b + c > a)
TriangleTest = test1 .AND. test2 ! both must be .TRUE.
END FUNCTION TriangleTest
23
Example: 3/4Example: 3/4
This function implements the Heron formula.This function implements the Heron formula.
Note that a, b and c must form a triangle.
REAL FUNCTION Area(a, b, c)
IMPLICIT NONE
REAL, INTENT(IN) :: a, b, c
REAL :: s
s = (a + b + c) / 2.0
A SQRT( *( )*( b)*( ))Area = SQRT(s*(s-a)*(s-b)*(s-c))
END FUNCTION Area
24
Example: 4/4Example: 4/4
Here is the main program!
PROGRAM HeronFormula
IMPLICIT NONE
REAL :: a, b, c, TriangleArea
DODO
WRITE(*,*) 'Three sides of a triangle please --> '
READ(*,*) a, b, c
WRITE(*,*) 'Input sides are ', a, b, c
IF (TriangleTest(a, b, c)) EXIT ! exit if they form a triangle
WRITE(*,*) 'Your input CANNOT form a triangle. Try again'
END DO
TriangleArea = Area(a b c)TriangleArea = Area(a, b, c)
WRITE(*,*) 'Triangle area is ', TriangleArea
CONTAINS
LOGICAL FUNCTION TriangleTest(a, b, c)
……
END FUNCTION TriangleTest
REAL FUNCTION Area(a, b, c)
25
……
END FUNCTION Area
END PROGRAM HeronFormula
Subroutines: 1/2Subroutines: 1/2
A Fortran 90 function takes values from itsA Fortran 90 function takes values from its
formal arguments, and returns a single value
with the function name.with the function name.
A Fortran 90 subroutine takes values from its
formal arguments and returns some computedformal arguments, and returns some computed
results with its formal arguments.
A F t 90 b ti d t tA Fortran 90 subroutine does not return any
value with its name.
26
Subroutines: 2/2Subroutines: 2/2
The following is Fortran 90 subroutine syntax:The following is Fortran 90 subroutine syntax:
SUBROUTINE subroutine-name(arg1,arg2,...,argn)
IMPLICIT NONE
[specification part]
[ ti t][execution part]
[subprogram part]
END SUBROUTINE subroutine-nameEND SUBROUTINE subroutine name
If a subroutine does not require any formal
arguments “arg1 arg2 argn” can be removed;arguments, arg1,arg2,...,argn can be removed;
however, () must be there.
S b ti i il t f ti
27
Subroutines are similar to functions.
The INTENT() Attribute: 1/2The INTENT() Attribute: 1/2
Since subroutines use formal arguments toSince subroutines use formal arguments to
receive values and to pass results back, in
addition to INTENT(IN), there are( ),
INTENT(OUT) and INTENT(INOUT).
INTENT(OUT) means a formal argument doesINTENT(OUT) means a formal argument does
not receive a value; but, it will return a value to
its corresponding actual argumentits corresponding actual argument.
INTENT(INOUT) means a formal argument
i l f d t l t itreceives a value from and returns a value to its
corresponding actual argument.
28
The INTENT() Attribute: 2/2The INTENT() Attribute: 2/2
Two simple examples:Two simple examples:
SUBROUTINE Means(a, b, c, Am, Gm, Hm)
IMPLICIT NONE
Am, Gm and Hm are used to return the results
REAL, INTENT(IN) :: a, b, c
REAL, INTENT(OUT) :: Am, Gm, Hm
Am = (a+b+c)/3.0
Gm = (a*b*c)**(1 0/3 0)Gm = (a*b*c)**(1.0/3.0)
Hm = 3.0/(1.0/a + 1.0/b + 1.0/c)
END SUBROUTINE Means
values of a and b are swapped
SUBROUTINE Swap(a, b)
IMPLICIT NONE
INTEGER, INTENT(INOUT) :: a, b
INTEGER :: cINTEGER :: c
c = a
a = b
b = c
29
END SUBROUTINE Swap
The CALL Statement: 1/2The CALL Statement: 1/2
Unlike C/C++ and Java, to use a Fortran 90Unlike C/C and Java, to use a Fortran 90
subroutine, the CALL statement is needed.
The CALL statement may have one of the threeThe CALL statement may have one of the three
forms:
CALL sub name(arg1 arg2 argn)CALL sub-name(arg1,arg2,…,argn)
CALL sub-name( )
CALL sub-name
The last two forms are equivalent and are forThe last two forms are equivalent and are for
calling a subroutine without formal arguments.
30
The CALL Statement: 2/2The CALL Statement: 2/2
PROGRAM Test PROGRAM SecondDegreePROGRAM Test
IMPLICIT NONE
REAL :: a, b
READ(*,*) a, b
PROGRAM SecondDegree
IMPLICIT NONE
REAL :: a, b, c, r1, r2
LOGICAL :: OK
CALL Swap(a,b)
WRITE(*,*) a, b
CONTAINS
SUBROUTINE Swap(x y)
READ(*,*) a, b, c
CALL Solver(a,b,c,r1,r2,OK)
IF (.NOT. OK) THEN
WRITE(* *) “No root”SUBROUTINE Swap(x,y)
IMPLICIT NONE
REAL, INTENT(INOUT) :: x,y
REAL :: z
WRITE(*,*) “No root”
ELSE
WRITE(*,*) a, b, c, r1, r2
END IF
z = x
x = y
y = z
END SUBROUTINE Swap
CONTAINS
SUBROUTINE Solver(a,b,c,x,y,L)
IMPLICIT NONE
REAL INTENT(IN) :: a b cEND SUBROUTINE Swap
END PROGRAM Test
REAL, INTENT(IN) :: a,b,c
REAL, INTENT(OUT) :: x, y
LOGICAL, INTENT(OUT) :: L
………
31
END SUBROUTINE Solver
END PROGRAM SecondDegree
More Argument Association: 1/2More Argument Association: 1/2
Since a formal argument with the INTENT(OUT)g ( )
or INTENT(INOUT) attribute will pass a value
back to the corresponding actual argument, theback to the corresponding actual argument, the
actual argument must be a variable.
PROGRAM Errors SUBROUTINE Sub(u,v,w,p,q)
IMPLICIT NONE IMPLICIT NONE
INTEGER :: a, b, c INTEGER, INTENT(OUT) :: uINTEGER :: a, b, c INTEGER, INTENT(OUT) :: u
.......... INTEGER, INTENT(INOUT) :: v
CALL Sub(1,a,b+c,(c),1+a) INTEGER, INTENT(IN) :: w
.......... INTEGER, INTENT(OUT) :: p, p
END PROGRAM Errors INTEGER, INTENT(IN) :: q
..........
END SUBROUTINE Sub
32these two are incorrect!
More Argument Association: 2/2More Argument Association: 2/2
The number of arguments and their types mustThe number of arguments and their types must
match properly.
There is no type-conversion between arguments!There is no type-conversion between arguments!
PROGRAM Error SUBROUTINE ABC(p, q)
IMPLICIT NONE IMPLICIT NONE
INTEGER :: a, b INTEGER, INTENT(IN) :: pINTEGER :: a, b INTEGER, INTENT(IN) :: p
CALL ABC(a, b) REAL, INTENT(OUT) :: q
CALL ABC(a) ………
CONTAINS END SUBROUTINE ABC
type mismatch
wrong # of arguments
………
END PROGRAM Error
g g
33
Fortran 90 Modules: 1/4Fortran 90 Modules: 1/4
One may collect all relevant functions andOne may collect all relevant functions and
subroutines together into a module.
A module in OO’s language is perhaps close toA module, in OO s language, is perhaps close to
a static class that has public/private information
and methodsand methods.
So, in some sense, Fortran 90’s module provides
t f bj t b d th th bj ta sort of object-based rather than object-
oriented programming paradigm.
34
Fortran 90 Modules: 2/4Fortran 90 Modules: 2/4
A Fortran 90 module has the following syntax:A Fortran 90 module has the following syntax:
MODULE module-name
IMPLICIT NONE
[specification part]
CONTAINS
[internal functions/subroutines][ / ]
END MODULE module-name
The specification part and internal functions andp p
subroutines are optional.
A module looks like a PROGRAM, except that itA module looks like a PROGRAM, except that it
does not have the executable part. Hence, a
main program must be there to use modules.
35
main program must be there to use modules.
Fortran 90 Modules: 3/4Fortran 90 Modules: 3/4
Examples:Examples:
Module SomeConstants does not
have the subprogram part
Module SumAverage does not
have the specification part
MODULE SomeConstants
IMPLICIT NONE
REAL, PARAMETER :: PI=3.1415926
REAL PARAMETER 980
MODULE SumAverage
CONTAINS
REAL FUNCTION S ( b c)
p g p p p
REAL, PARAMETER :: g = 980
INTEGER :: Counter
END MODULE SomeConstants
REAL FUNCTION Sum(a, b, c)
IMPLICIT NONE
REAL, INTENT(IN) :: a, b, c
Sum = a + b + c
END FUNCTION Sum
REAL FUNCTION Average(a, b, c)
IMPLICIT NONE
REAL INTENT(IN) :: a b cREAL, INTENT(IN) :: a, b, c
Average = Sum(a,b,c)/2.0
END FUNCTION Average
END MODULE SumAverage
36
Fortran 90 Modules: 4/4Fortran 90 Modules: 4/4
The right module MODULE DegreeRadianConversiong
has both the
specification
d
IMPLICIT NONE
REAL, PARAMETER :: PI = 3.1415926
REAL, PARAMETER :: Degree180 = 180.0
part and
internal
functions
CONTAINS
REAL FUNCTION DegreeToRadian(Degree)
IMPLICIT NONE
functions.
Normally, this is
the case.
REAL, INTENT(IN) :: Degree
DegreeToRadian = Degree*PI/Degree180
END FUNCTION DegreeToRadian
REAL FUNCTION RadianToDegree(radian)the case. REAL FUNCTION RadianToDegree(radian)
IMPLICIT NONE
REAL, INTENT(IN) :: Radian
RadianToDegree = Radian*Degree180/PI
END FUNCTION RadianToDegree
END MODULE DegreeRadianConversion
37
Some Privacy: 1/2Some Privacy: 1/2
Fortran 90 allows a module to have private andp
public items. However, all global entities of a
module, by default, are public (i.e., visible in all
other programs and modules)other programs and modules).
To specify public and private, do the following:
PUBLIC :: name 1 name 2 name nPUBLIC :: name-1, name-2, …, name-n
PRIVATE :: name-1, name-2, …, name-n
The PRIVATE statement without a name makes
all entities in a module private. To make some
entities visible, use PUBLIC.
d l b d iPUBLIC and PRIVATE may also be used in
type specification:
38
INTEGER, PRIVATE :: Sum, Phone_Number
Some Privacy: 2/2Some Privacy: 2/2
Any global entity MODULE TheForcey g y
(e.g., PARAMETER,
variable, function,
i
MODULE TheForce
IMPLICIT NONE
INTEGER :: SkyWalker, Princess
REAL, PRIVATE :: BlackKnight
Is this public?
subroutine, etc)
can be in PUBLIC
or PRIVATE
LOGICAL :: DeathStar
REAL, PARAMETER :: SecretConstant = 0.123456
PUBLIC :: SkyWalker, Princess
PRIVATE :: VolumeOfDeathStaror PRIVATE
statements.
PRIVATE :: VolumeOfDeathStar
PRIVATE :: SecretConstant
CONTAINS
INTEGER FUNCTION VolumeOfDeathStar()
..........
END FUNCTION WolumeOfDeathStar
REAL FUNCTION WeaponPower(SomeWeapon)
..........
END FUNCTION ..........
END MODULE TheForce
39
By default, this PUBLIC statement
does not make much sense
Using a Module: 1/5Using a Module: 1/5
A PROGRAM or MODULE can use PUBLIC entities
in any other modules. However, one must
declare this intention (of use).
There are two forms of the USE statement for
this task:
USE module-name
USE module-name, ONLY: name-1, name-2, ..., name-n
The first USE indicates all PUBLIC entities of
MODULE module-name will be used.
The second makes use only the names listed after
the ONLY keyword.
40
Using a Module: 2/5Using a Module: 2/5
Two simple examples:p p
MODULE SomeConstants
PROGRAM Main
USE SomeConstants
IMPLICIT NONEMODULE SomeConstants
IMPLICIT NONE
REAL, PARAMETER :: PI = 3.1415926
REAL, PARAMETER :: g = 980
..........
END PROGRAM Main
, g
INTEGER :: Counter
END MODULE SomeConstants
MODULE DoSomething
USE SomeConstants, ONLY : g, Counter
IMPLICIT NONE PI is not available
CONTAINS
SUBROUTINE Something(…)
……
END SUBROUTINE S thi
41
END SUBROUTINE Something
END MODULE DoSomething
Using a Module: 3/5Using a Module: 3/5
Sometimes, the “imported” entities from aSometimes, the imported entities from a
MODULE may have identical names with names
in the “importing” PROGRAM or MODULE.p g
If this happens, one may use the “renaming”
feature of USEfeature of USE.
For each identifier in USE to be renamed, use the
f ll i tfollowing syntax:
name-in-this-PROGRAM => name-in-module
In this program, the use of name-in-this-
PROGRAM is equivalent to the use of name-in-
42
module in the “imported” MODULE.
Using a Module: 4/5Using a Module: 4/5
The following uses module MyModule.g y
Identifiers Counter and Test in module
MyModule are renamed as MyCounter andMyModule are renamed as MyCounter and
MyTest in this module, respectively:
USE MyModule, MyCounter => Counter &USE MyModule, MyCounter => Counter &
MyTest => Test
The following only uses identifiers Ans,The following only uses identifiers Ans,
Condition and X from module Package with
Condition renamed as Status:Condition renamed as Status:
USE Package, ONLY : Ans, Status => Condition, X
43
Using a Module: 5/5Using a Module: 5/5
Two USE and => examples GravityG is the g in the module;S p
MODULE SomeConstants
PROGRAM Test
USE SomeConstants, &
however, g is the “g” in Test
MODULE SomeConstants
IMPLICIT NONE
REAL, PARAMETER :: PI = 3.1415926
REAL, PARAMETER :: g = 980
USE SomeConstants, &
GravityG => g
IMPLICIT NONE
INTEGER :: g, g
INTEGER :: Counter
END MODULE SomeConstants
g
……
END PROGRAM Test
MODULE Compute
USE SomeConstants, ONLY : PI, g
IMPLICIT NONE
REAL :: Counter
CONTAINS
without ONLY, Counter would
appear in MODULE Compute
causing a name conflict!
44
……
END MODULE Compute
causing a name conflict!
Compile Your Program: 1/4Compile Your Program: 1/4
Suppose a program consists of the mainSuppose a program consists of the main
program main.f90 and 2 modules Test.f90
and Compute.f90. In general, they can bep g , y
compiled in the following way:
f90 main.f90 Test.f90 Compute.f90 –o mainf90 main.f90 Test.f90 Compute.f90 o main
However, some compilers may be a little more
restrictive List those modules that do not use anyrestrictive. List those modules that do not use any
other modules first, followed by those modules that
only use those listed modules followed by youronly use those listed modules, followed by your
main program.
45
Compile Your Program: 2/4Compile Your Program: 2/4
Suppose we have modules A, B, C, D and E, and Cpp , , , ,
uses A, D uses B, and E uses A, C and D, then a
safest way to compile your program is thesafest way to compile your program is the
following command:
f90 A.f90 B.f90 C.f90 D.f90 E.f90 main.f90 –o main
Since modules are supposed to be designed and
developed separately, they can also be compileddeveloped separately, they can also be compiled
separately to object codes:
f90 c test f90f90 –c test.f90
The above compiles a module/program in file
t t f90 t it bj t d t t
46
test.f90 to its object code test.o
This means compile only
Compile Your Program: 3/4Compile Your Program: 3/4
Suppose we have modules A, B, C, D and E, and Cpp
uses A, D uses B, and E uses A, C and D.
Since modules are developed separately with
ifi f ti lit i i dsome specific functionality in mind, one may
compile each module to object code as follows:
f90 –c A.f90f90 c A.f90
f90 –c B.f90
f90 –c C.f90 If your compiler is picky, some modules
may have to compiled together!
f90 –c D.f90
f90 –c E.f90
N t th t th d i till i t t Th b
may have to compiled together!
Note that the order is still important. The above
generates object files A.o, B.o, C.o, D.o
and E.o
47
and E.o
Compile Your Program: 4/4Compile Your Program: 4/4
If a main program in file prog2.f90 usesp g p g
modules in A.f90 and B.f90, one may compile
and generate executable code for prog2 asg p g
follows:
f90 A.o B.o prog2.f90 –o prog2f90 A.o B.o prog2.f90 o prog2
If prog2.f90 uses module E.f90 only, the
following must be used since E f90 uses A f90following must be used since E.f90 uses A.f90,
C.f90 and D.f90:
f90 A o C o D o E o prog2 f90 o prog2f90 A.o C.o D.o E.o prog2.f90 –o prog2
Note the order of the object files.
48
Example 1Example 1
The combinatorial coefficient of m and n (m n) isThe combinatorial coefficient of m and n (m n) is
Cm,n = m!/(n! (m-n)!).
MODULE FactorialModule
IMPLICIT NONE
CONTAINS
i l( )
PROGRAM ComputeFactorial
USE FactorialModule
IMPLICIT NONE
INTEGER N RINTEGER FUNCTION Factorial(n)
IMPLICIT NONE
INTEGER, INTENT(IN) :: n
… other statements …
INTEGER :: N, R
READ(*,*) N, R
WRITE(*,*) Factorial(N)
WRITE(*,*) Combinatorial(N,R)… ot e state e ts …
END FUNCTION Factorial
INTEGER FUNCTION Combinatorial(n, r)
IMPLICIT NONE
G ( )
END PROGRAM ComputeFactorial
INTEGER, INTENT(IN) :: n, r
… other statements …
END FUNCTION Combinatorial
END MODULE FactorialModule
Combinatorial(n,r) uses
Factorial(n)
49
Example 2Example 2
Trigonometric functions use degree.Trigonometric functions use degree.
MODULE MyTrigonometricFunctions
IMPLICIT NONE
PROGRAM TrigonFunctTest
USE MyTrigonometricFunctions
REAL, PARAMETER :: PI = 3.1415926
REAL, PARAMETER :: Degree180 = 180.0
REAL, PARAMETER :: R_to_D=Degree180/PI
REAL, PARAMETER :: D to R=PI/Degree180
IMPLICIT NONE
REAL :: Begin = -180.0
REAL :: Final = 180.0
REAL :: Step = 10.0REAL, PARAMETER :: D_to_R PI/Degree180
CONTAINS
REAL FUNCTION DegreeToRadian(Degree)
IMPLICIT NONE
( )
REAL :: Step 10.0
REAL :: x
x = Begin
DO
( i l)REAL, INTENT(IN) :: Degree
DegreeToRadian = Degree * D_to_R
END FUNCTION DegreeToRadian
REAL FUNCTION MySIN(x)
IF (x > Final) EXIT
WRITE(*,*) MySIN(x)
x = x + Step
END DOyS ( )
IMPLICIT NONE
REAL, INTENT(IN) :: x
MySIN = SIN(DegreeToRadian(x))
END FUNCTION SIN
END PROGRAM TrigonFunctTest
50
END FUNCTION MySIN
… other functions …
END MODULE MyTrigonometricFunctions
INTERFACE Blocks: 1/5INTERFACE Blocks: 1/5
Legacy Fortran programs do not have internalLegacy Fortran programs do not have internal
subprograms in PROGRAMs or MODULEs.
These subprograms are in separate files TheseThese subprograms are in separate files. These
are external subprograms that may cause some
compilation problems in Fortran 90compilation problems in Fortran 90.
Therefore, Fortran 90 has the INTERFACE block
f d l t k th t ffor a program or a module to know the type of
the subprograms, the intent and type of each
t targument, etc.
51
INTERFACE Blocks: 2/5INTERFACE Blocks: 2/5
Consider the following triangle area program.Consider the following triangle area program.
How does the main program know the type and
number of arguments of the two functions?number of arguments of the two functions?
LOGICAL FUNCTION Test(a, b, c)
IMPLICIT NONE
PROGRAM HeronFormula
IMPLICIT NONE
REAL, INTENT(IN) :: a, b, c
LOGICAL :: test1, test2
test1 = (a>0.0) .AND. (b>0.0) .AND. (c>0.0)
test2 = (a+b>c) .AND. (a+c>b) .AND. (b+c>a)
… some important here …
REAL :: a, b, c
REAL :: TriangleArea
DO
Test = test1 .AND. test2
END FUNCTION Test
REAL FUNCTION Area(a, b, c)
READ(*,*) a, b, c
IF (Test(a,b,c)) EXIT
END DO
TriangleArea = Area(a, b, c)
IMPLICIT NONE
REAL, INTENT(IN) :: a, b, c
REAL :: s = (a + b + c) / 2.0
Area = SQRT(s*(s-a)*(s-b)*(s-c))
g
WRITE(*,*) TriangleArea
END PROGRAM HeronFormula
52
END FUNCTION Area
file area.f90 file main.f90
INTERFACE Blocks: 3/5INTERFACE Blocks: 3/5
An INTERFACE block has the following syntax:g y
INTERFACE
type FUNCTION name(arg-1, arg-2, ..., arg-n)
type, INTENT(IN) :: arg-1
type, INTENT(IN) :: arg-2
..........
type INTENT(IN) :: arg ntype, INTENT(IN) :: arg-n
END FUNCTION name
SUBROUTINE name(arg-1, arg-2, …, arg-n)
type, INTENT(IN or OUT or INOUT) :: arg-1
type, INTENT(IN or OUT or INOUT) :: arg-2
..........
type, INTENT(IN or OUT or INOUT) :: arg-n
END SUBROUTINE nameEND SUBROUTINE name
....... other functions/subroutines .......
END INTERFACE
53
INTERFACE Blocks: 4/5INTERFACE Blocks: 4/5
All external subprograms should be listedAll external subprograms should be listed
between INTERFACE and END INTERFACE.
However only the FUNCTION and SUBROUTINEHowever, only the FUNCTION and SUBROUTINE
headings, argument types and INTENTs are
needed No executable statements should beneeded. No executable statements should be
included.
Th t d t h t b id ti lThe argument names do not have to be identical
to those of the formal arguments, because they
are “place holders” in an INTERFACE blockare “place-holders” in an INTERFACE block.
Thus, a main program or subprogram will be
54
able to know exactly how to use a subprogram.
INTERFACE Blocks: 5/5INTERFACE Blocks: 5/5
Return to Heron’s formula for triangle area.g
The following shows the INTERFACE block in a
main program.p g
LOGICAL FUNCTION Test(a, b, c)
IMPLICIT NONE
REAL INTENT(IN) :: a b c
PROGRAM HeronFormula
IMPLICIT NONE
INTERFACEREAL, INTENT(IN) :: a, b, c
LOGICAL :: test1, test2
test1 = (a>0.0) .AND. (b>0.0) .AND. (c>0.0)
test2 = (a+b>c) .AND. (a+c>b) .AND. (b+c>a)
Test = test1 AND test2
INTERFACE
LOGICAL FUNCTION Test(x,y,z)
REAL, INTENT(IN)::x,y,z
END FUNCTION TestTest = test1 .AND. test2
END FUNCTION Test
REAL FUNCTION Area(a, b, c)
IMPLICIT NONE
REAL FUNCTION Area(l,m,n)
REAL, INTENT(IN)::l,m,n
END FUNCTION Area
END INTERFACEIMPLICIT NONE
REAL, INTENT(IN) :: a, b, c
REAL :: s
s = (a + b + c) / 2.0
Area = SQRT(s*(s-a)*(s-b)*(s-c))
END INTERFACE
…… other statements …
END PROGRAM HeronFormula
55
Area = SQRT(s*(s-a)*(s-b)*(s-c))
END FUNCTION Area
file area.f90 file main.f90
The EndThe End
56

Fortran 90 Basics

  • 1.
    Fortran 90 BasicsFortran90 Basics I don’t know what the programming languageI don t know what the programming language of the year 2000 will look like, but I know it will be called FORTRAN. 1 Charles Anthony Richard Hoare Fall 2010
  • 2.
    F90 Program StructureF90Program Structure A Fortran 90 program has the following form:A Fortran 90 program has the following form: program-name is the name of that program specification-part execution-part andspecification part, execution part, and subprogram-part are optional. Although IMPLICIT NONE is also optional, this isg p , required in this course to write safe programs. PROGRAM program-name IMPLICIT NONE [ ifi ti t][specification-part] [execution-part] [subprogram-part] 2 [subprogram part] END PROGRAM program-name
  • 3.
    Program CommentsProgram Comments Commentsstart with a !Comments start with a ! Everything following ! will be ignored This is similar to // in C/C++This is similar to // in C/C++ ! This is an example ! PROGRAM Comment .......... READ(*,*) Year ! read in the value of Year .................... Year = Year + 1 ! add 1 to Year .......... END PROGRAM Comment 3 END PROGRAM Comment
  • 4.
    Continuation LinesContinuation Lines Fortran90 is not completely format-free!Fortran 90 is not completely format free! A statement must starts with a new line. If t t t i t l t fit li it hIf a statement is too long to fit on one line, it has to be continued. The continuation character is &, which is not part of the statement. Total = Total + & Amount * Payments ! Total = Total + Amount*Payments! Total = Total + Amount*Payments PROGRAM & i i i 4 ContinuationLine ! PROGRAM ContinuationLine
  • 5.
    AlphabetsAlphabets Fortran 90 alphabetsinclude the following:Fortran 90 alphabets include the following: Upper and lower cases letters Di itDigits Special characters space ' " ( ) * + - / : = _ ! & $ ; < > % ? , . 5
  • 6.
    Constants: 1/6Constants: 1/6 AFortran 90 constant may be an integer, real,A Fortran 90 constant may be an integer, real, logical, complex, and character string. We will not discuss complex constantsWe will not discuss complex constants. An integer constant is a string of digits with an optional sign: 12345 345 +789 +0optional sign: 12345, -345, +789, +0. 6
  • 7.
    Constants: 2/6Constants: 2/6 Areal constant has two forms, decimal andA real constant has two forms, decimal and exponential: In the decimal form a real constant is aIn the decimal form, a real constant is a string of digits with exactly one decimal point A real constant may include anpoint. A real constant may include an optional sign. Example: 2.45, .13, 13., -0 12 - 120.12, .12. 7
  • 8.
    Constants: 3/6Constants: 3/6 Areal constant has two forms, decimal andA real constant has two forms, decimal and exponential: In the exponential form a real constantIn the exponential form, a real constant starts with an integer/real, followed by a E/e, followed by an integer (i e the exponent)followed by an integer (i.e., the exponent). Examples: 12E3 (12 103) 12e3 ( 12 103)12E3 (12 103), -12e3 (-12 103), 3.45E-8 (3.45 10-8), -3.45e-8 ( 3 45 10-8)(-3.45 10-8). 0E0 (0 100=0). 12.34-5 is wrong! 8
  • 9.
    Constants: 4/6Constants: 4/6 Alogical constant is either .TRUE. or .FALSE.g S Note that the periods surrounding TRUE and FALSE are required!FALSE are required! 9
  • 10.
    Constants: 5/6Constants: 5/6 Acharacter string or character constant is aA character string or character constant is a string of characters enclosed between two double quotes or two single quotes. Examples:double quotes or two single quotes. Examples: “abc”, ‘John Dow’, “#$%^”, and ‘()()’. The content of a character string consists of allThe content of a character string consists of all characters between the quotes. Example: The content of ‘John Dow’ is John Dowcontent of John Dow is John Dow. The length of a string is the number of h t b t th t Th l th fcharacters between the quotes. The length of ‘John Dow’is 8, space included. 10
  • 11.
    Constants: 6/6Constants: 6/6 Astring has length zero (i.e., no content) is ang g ( , ) empty string. If single (or double) quotes are used in a string,g ( ) q g, then use double (or single) quotes as delimiters. Examples: “Adam’s cat” and ‘I said “go away”’. Two consecutive quotes are treated as one! ‘Lori’’s Apple’ is Lori’s Apple “double quote””” is double quote” `abc’’def”x’’y’ is abc’def”x’y “abc””def’x””y” is abc”def’x”y 11 abc def x y is abc def x y
  • 12.
    Identifiers: 1/2Identifiers: 1/2 AFortran 90 identifier can have no more thanA Fortran 90 identifier can have no more than 31 characters. The first one must be a letter The remainingThe first one must be a letter. The remaining characters, if any, may be letters, digits, or underscoresunderscores. Fortran 90 identifiers are CASE INSENSITIVE. Examples: A, Name, toTAL123, System_, myFile_01, my_1st_F90_program_X_. Identifiers Name, nAmE, naME and NamE are the same. 12
  • 13.
    Identifiers: 2/2Identifiers: 2/2 UnlikeJava, C, C++, etc, Fortran 90 does not, , , , have reserved words. This means one may use Fortran keywords as identifiers. Therefore, PROGRAM, end, IF, then, DO, etc may be used as identifiers. Fortran 90 compilers are able to recognize keywords from their “positions” in a statement. Yes, end = program + if/(goto – while) is legal! However, avoid the use of Fortran 90 keywords as identifiers to minimize confusion. 13
  • 14.
    Declarations: 1/3Declarations: 1/3 Fortran90 uses the following for variableFortran 90 uses the following for variable declarations, where type-specifier is one of the following keywords: INTEGER, REAL,g y , , LOGICAL, COMPLEX and CHARACTER, and list is a sequence of identifiers separated byq p y commas. type-specifier :: listtype specifier :: list Examples: INTEGER :: Zip, Total, counter REAL :: AVERAGE, x, Difference LOGICAL :: Condition, OK 14 COMPLEX :: Conjugate
  • 15.
    Declarations: 2/3Declarations: 2/3 Charactervariables require additionalCharacter variables require additional information, the string length: Keyword CHARACTER must be followed byKeyword CHARACTER must be followed by a length attribute (LEN = l) , where l is the length of the stringthe length of the string. The LEN= part is optional. If the length of a string is 1, one may use CHARACTER without length attribute. Other length attributes will be discussed later. 15
  • 16.
    Declarations: 3/3Declarations: 3/3 Examples:Examples: CHARACTER(LEN=20):: Answer, Quote Variables Answer and Quote can holdVariables Answer and Quote can hold strings up to 20 characters. CHARACTER(20) :: Answer, Quote is the same as above. CHARACTER :: Keypress means variable Keypress can only hold ONE character (i.e., length 1). 16
  • 17.
    The PARAMETER Attribute:1/4The PARAMETER Attribute: 1/4 A PARAMETER identifier is a name whose value cannot be modified. In other words, it is a named constant.named constant. The PARAMETER attribute is used after the type keywordkeyword. Each identifier is followed by a = and followed b l f th t id tifiby a value for that identifier. INTEGER PARAMETER :: MAXIMUM = 10INTEGER, PARAMETER :: MAXIMUM = 10 REAL, PARAMETER :: PI = 3.1415926, E = 2.17828 LOGICAL, PARAMETER :: TRUE = .true., FALSE = .false. 17
  • 18.
    The PARAMETER Attribute:2/4The PARAMETER Attribute: 2/4 Since CHARACTER identifiers have a lengthg attribute, it is a little more complex when used with PARAMETER. Use (LEN = *) if one does not want to count the number of characters in a PARAMETERthe number of characters in a PARAMETER character string, where = * means the length of this string is determined elsewherethis string is determined elsewhere. CHARACTER(LEN=3), PARAMETER :: YES = “yes” ! Len = 3y CHARACTER(LEN=2), PARAMETER :: NO = “no” ! Len = 2 CHARACTER(LEN=*), PARAMETER :: & PROMPT = “What do you want?” ! Len = 17 18
  • 19.
    The PARAMETER Attribute:3/4The PARAMETER Attribute: 3/4 Since Fortran 90 strings are of fixed length, oneSince Fortran 90 strings are of fixed length, one must remember the following: If a string is longer than the PARAMETERIf a string is longer than the PARAMETER length, the right end is truncated. If a string is shorter than the PARAMETERIf a string is shorter than the PARAMETER length, spaces will be added to the right. CHARACTER(LEN=4), PARAMETER :: ABC = “abcdef” CHARACTER(LEN=4), PARAMETER :: XYZ = “xy” a b c dABC = x yXYZ = 19 a b c dABC yXYZ
  • 20.
    The PARAMETER Attribute:4/4The PARAMETER Attribute: 4/4 By convention, PARAMETER identifiers use ally , upper cases. However, this is not mandatory. For maximum flexibility constants other than 0For maximum flexibility, constants other than 0 and 1 should be PARAMETERized. A PARAMETER is an alias of a value and is not aA PARAMETER is an alias of a value and is not a variable. Hence, one cannot modify the content of a PARAMETER identifiera PARAMETER identifier. One can may a PARAMETER identifier anywhere in a program. It is equivalent to replacing the identifier with its value. 20 The value part can use expressions.
  • 21.
    Variable Initialization: 1/2VariableInitialization: 1/2 A variable receives its value withA variable receives its value with Initialization: It is done once before the program runsprogram runs. Assignment: It is done when the program t i t t t texecutes an assignment statement. Input: It is done with a READ statement. 21
  • 22.
    Variable Initialization: 2/2VariableInitialization: 2/2 Variable initialization is very similar to what weVariable initialization is very similar to what we learned with PARAMETER. A variable name is followed by a = followed byA variable name is followed by a =, followed by an expression in which all identifiers must be constants or PARAMETERs defined previouslyconstants or PARAMETERs defined previously. Using an un-initialized variable may cause un- t d ti di t ltexpected, sometimes disastrous results. REAL :: Offset = 0.1, Length = 10.0, tolerance = 1.E-7 CHARACTER(LEN=2) :: State1 = "MI", State2 = "MD“ INTEGER, PARAMETER :: Quantity = 10, Amount = 435 INTEGER, PARAMETER :: Period = 3 22 INTEGER :: Pay = Quantity*Amount, Received = Period+5
  • 23.
    Arithmetic OperatorsArithmetic Operators Thereare four types of operators in Fortran 90:There are four types of operators in Fortran 90: arithmetic, relational, logical and character. The following shows the first three types:The following shows the first three types: Type Operator Associativity Arithmetic ** right to left * / left to right + - left to right+ - left to right Relational < <= > >= == /= none .NOT. right to left Logical g f .AND. left to right .OR. left to right 23 .EQV. .NEQV. left to right
  • 24.
    Operator PriorityOperator Priority **is the highest; * and / are the next, followedg ; / , by + and -. All relational operators are next. Of the 5 logical operators EQV and NEQVOf the 5 logical operators, .EQV. and .NEQV. are the lowest. Type Operator Associativity hi hType Operator Associativity Arithmetic ** right to left * / left to right highest priority + - left to right Relational < <= > >= == /= none Logical .NOT. right to left .AND. left to right .OR. left to right 24 .OR. left to right .EQV. .NEQV. left to right
  • 25.
    Expression EvaluationExpression Evaluation Expressionsare evaluated from left to right.Expressions are evaluated from left to right. If an operator is encountered in the process of evaluation its priority is compared with that ofevaluation, its priority is compared with that of the next one if th t i l l t th tif the next one is lower, evaluate the current operator with its operands; if the next one is equal to the current, the associativity laws are used to determine which one should be evaluated; if the next one is higher, scanning continues 25
  • 26.
    Single Mode ExpressionSingleMode Expression A single mode arithmetic expression is anA single mode arithmetic expression is an expression all of whose operands are of the same type.same type. If the operands are INTEGERs (resp., REALs), the result is also an INTEGER (resp REAL)the result is also an INTEGER (resp., REAL). 1.0 + 2.0 * 3.0 / ( 6.0*6.0 + 5.0*44.0) ** 0.25 --> 1.0 + 6.0 / (6.0*6.0 + 5.0*44.0) ** 0.25 --> 1.0 + 6.0 / (36.0 + 5.0*44.0) ** 0.25 --> 1.0 + 6.0 / (36.0 + 220.0) ** 0.25 1 0 6 0 / 256 0 ** 0 25--> 1.0 + 6.0 / 256.0 ** 0.25 --> 1.0 + 6.0 / 4.0 --> 1.0 + 1.5 > 2 5 26 --> 2.5
  • 27.
    Mixed Mode Expression:1/2Mixed Mode Expression: 1/2 If operands have different types, it is mixedIf operands have different types, it is mixed mode. INTEGER and REAL yields REAL and theINTEGER and REAL yields REAL, and the INTEGER operand is converted to REAL before evaluation Example: 3 5*4 is converted toevaluation. Example: 3.5 4 is converted to 3.5*4.0 becoming single mode. Exception: x**INTEGER: x**3 is x*x*x andException: x**INTEGER: x**3 is x*x*x and x**(-3) is 1.0/(x*x*x). i l d i h dx**REAL is evaluated with log() and exp(). Logical and character cannot be mixed with 27 arithmetic operands.
  • 28.
    Mixed Mode Expression:2/2Mixed Mode Expression: 2/2 Note that a**b**c is a**(b**c) instead of( ) (a**b)**c, and a**(b**c) (a**b)**c. This can be a big trap!This can be a big trap! 5 * (11.0 - 5) ** 2 / 4 + 9 --> 5 * (11.0 - 5.0) ** 2 / 4 + 9 --> 5 * 6.0 ** 2 / 4 + 9 /--> 5 * 36.0 / 4 + 9 --> 5.0 * 36.0 / 4 + 9 --> 180.0 / 4 + 9 > 180 0 / 4 0 + 9 6.0**2 is evaluated as 6.0*6.0 rather than converted to 6.0**2.0! --> 180.0 / 4.0 + 9 --> 45.0 + 9 --> 45.0 + 9.0 > 54 0 28 --> 54.0 red: type conversion
  • 29.
    The Assignment Statement:1/2The Assignment Statement: 1/2 The assignment statement has a form ofThe assignment statement has a form of variable = expression If the type of ariable and e pression areIf the type of variable and expression are identical, the result is saved to variable. If the type of variable and expression are not identical, the result of expression is fconverted to the type of variable. If expression is REAL and variable is INTEGER, the result is truncated. 29
  • 30.
    The Assignment Statement:2/2The Assignment Statement: 2/2 The left example uses an initialized variableThe left example uses an initialized variable Unit, and the right uses a PARAMETER PI. INTEGER :: Total, Amount INTEGER :: Unit = 5 REAL, PARAMETER :: PI = 3.1415926 REAL :: Area INTEGER :: Radius Amount = 100.99 Total = Unit * Amount INTEGER :: Radius Radius = 5 Area = (Radius ** 2) * PI This one is equivalent to Radius ** 2 * PI 30
  • 31.
    Fortran Intrinsic Functions:1/4Fortran Intrinsic Functions: 1/4 Fortran provides many commonly usedFortran provides many commonly used functions, referred to as intrinsic functions. To use an intrinsic function we need to know:To use an intrinsic function, we need to know: Name and meaning of the function (e.g., SQRT() for square root)SQRT() for square root) Number of arguments The type and range of each argument (e.g., the argument of SQRT() must be non- negative) The type of the returned function value. 31 e ype o e e u ed u c o v ue.
  • 32.
    Fortran Intrinsic Functions:2/4Fortran Intrinsic Functions: 2/4 Some mathematical functions:Some mathematical functions: Function Meaning Arg. Type Return Type b l l f INTEGER INTEGER ABS(x) absolute value of x REAL REAL SQRT(x) square root of x REAL REAL SIN(x) sine of x radian REAL REAL COS(x) cosine of x radian REAL REAL TAN(x) tangent of x radian REAL REALTAN(x) tangent of x radian REAL REAL ASIN(x) arc sine of x REAL REAL ACOS(x) arc cosine of x REAL REAL ATAN(x) arc tangent of x REAL REAL EXP(x) exponential ex REAL REAL 32 LOG(x) natural logarithm of x REAL REAL LOG10(x) is the common logarithm of x!
  • 33.
    Fortran Intrinsic Functions:3/4Fortran Intrinsic Functions: 3/4 Some conversion functions:Some conversion functions: Function Meaning Arg. Type Return Type INT(x) truncate to integer part x REAL INTEGERINT(x) truncate to integer part x REAL INTEGER NINT(x) round nearest integer to x REAL INTEGER FLOOR(x) greatest integer less than or equal to x REAL INTEGER FRACTION(x) the fractional part of x REAL REAL REAL(x) convert x to REAL INTEGER REAL INT(-3.5) -3 NINT(3.5) 4Examples: NINT(-3.4) -3 FLOOR(3.6) 3 FLOOR(-3.5) -4 C O (12 3) 0 3 33 FRACTION(12.3) 0.3 REAL(-10) -10.0
  • 34.
    Fortran Intrinsic Functions:4/4Fortran Intrinsic Functions: 4/4 Other functions:Other functions: Function Meaning Arg. Type Return Type INTEGER INTEGER MAX(x1, x2, ..., xn) maximum of x1, x2, ... xn INTEGER INTEGER REAL REAL MIN(x1 x2 xn) minimum of x1 x2 xn INTEGER INTEGER MIN(x1, x2, ..., xn) minimum of x1, x2, ... xn REAL REAL MOD(x,y) remainder x - INT(x/y)*y INTEGER INTEGER REAL REAL 34
  • 35.
    Expression EvaluationExpression Evaluation Functionshave the highest priority. Function arguments are evaluated first. The returned function value is treated as aThe returned function value is treated as a value in the expression. REAL :: A = 1.0, B = -5.0, C = 6.0, RREAL :: A 1.0, B 5.0, C 6.0, R R = (-B + SQRT(B*B - 4.0*A*C))/(2.0*A) / R gets 3.0 (-B + SQRT(B*B - 4.0*A*C))/(2.0*A) --> (5.0 + SQRT(B*B - 4.0*A*C))/(2.0*A) --> (5.0 + SQRT(25.0 - 4.0*A*C))/(2.0*A) --> (5.0 + SQRT(25.0 - 4.0*C))/(2.0*A)(5.0 SQRT(25.0 4.0 C))/(2.0 A) --> (5.0 + SQRT(25.0 - 24.0))/(2.0*A) --> (5.0 + SQRT(1.0))/(2.0*A) --> (5.0 + 1.0)/(2.0*A) 6 0/(2 0* ) 35 --> 6.0/(2.0*A) --> 6.0/2.0 --> 3.0
  • 36.
    What is IMPLICITNONE?What is IMPLICIT NONE? Fortran has an interesting tradition: allg variables starting with i, j, k, l, m and n, if not declared, are of the INTEGER type by default. This handy feature can cause serious consequences if it is not used with care. IMPLICIT NONE means all names must be declared and there is no implicitly assumed INTEGER type. All programs in this class must use IMPLICIT NONE. Points will be deducted if you do not use itPoints will be deducted if you do not use it! 36
  • 37.
    List-Directed READ: 1/5ListDirected READ: 1/5 Fortran 90 uses the READ(*,*) statement to( , ) read data into variables from keyboard: READ(* *) v1 v2 vnREAD( , ) v1, v2, …, vn READ(*,*) The second form has a special meaning that will be discussed later. INTEGER :: Age REAL :: Amount, Rate CHARACTER(LEN=10) :: Name READ(*,*) Name, Age, Rate, Amount 37
  • 38.
    List-Directed READ: 2/5ListDirected READ: 2/5 Data Preparation GuidelinesData Preparation Guidelines READ(*,*) reads data from keyboard by default although one may use inputdefault, although one may use input redirection to read from a file. If READ(* *) has n variables there mustIf READ(*,*) has n variables, there must be n Fortran constants. Each constant must have the type of the corresponding variable. Integers can be d i i bl b iread into REAL variables but not vice versa. Data items are separated by spaces and may 38 spread into multiple lines.
  • 39.
    List-Directed READ: 3/5ListDirected READ: 3/5 The execution of READ(*,*) always starts withf ( , ) y a new line! Then it reads each constant into theThen, it reads each constant into the corresponding variable. CHARACTER(LEN=5) :: Name REAL :: height, length INTEGER :: count, MaxLength READ(*,*) Name, height, count, length, MaxLength "Smith" 100.0 25 123.579 10000Input: 39 put:
  • 40.
    List-Directed READ: 4/5ListDirected READ: 4/5 Be careful when input items are on multiple lines.Be careful when input items are on multiple lines. INTEGER :: I,J,K,L,M,N Input: READ(*,*) I, J READ(*,*) K, L, M READ(*,*) N 100 200 300 400 500 600 INTEGER :: I,J,K,L,M,N ignored! READ(*,*) I, J, K READ(*,*) L, M, N 100 200 300 400 500 600 700 800 900 READ(*,*) always starts with a new line 40
  • 41.
    List-Directed READ: 5/5ListDirected READ: 5/5 Since READ(*,*) always starts with a new line,( , ) y , a READ(*,*) without any variable means skipping the input line!skipping the input line! INTEGER :: P, Q, R, SINTEGER :: P, Q, R, S READ(*,*) P, Q READ(*,*) 100 200 300 400 500 600( , ) READ(*,*) R, S 400 500 600 700 800 900 41
  • 42.
    List-Directed WRITE: 1/3ListDirected WRITE: 1/3 Fortran 90 uses the WRITE(*,*) statement to( , ) write information to screen. WRITE(* *) has two forms where exp1WRITE( , ) has two forms, where exp1, exp2, …, expn are expressions WRITE(* *) e p1 e p2 e pnWRITE(*,*) exp1, exp2, …, expn WRITE(*,*) WRITE(*,*) evaluates the result of each expression and prints it on screen. WRITE(*,*) always starts with a new line! 42
  • 43.
    List-Directed WRITE: 2/3ListDirected WRITE: 2/3 Here is a simple example:Here is a simple example: INTEGER :: Target means length is determined by actual count REAL :: Angle, Distance CHARACTER(LEN=*), PARAMETER :: & Time = "The time to hit target “, & IS = " is “, & UNIT = " sec." ti ti li Output:Target = 10 Angle = 20.0 Distance = 1350.0 WRITE(* *) 'A l ' A l continuation lines Output: Angle = 20.0 Distance = 1350.0 The time to hit target 10 is 27000.0 sec. WRITE(*,*) 'Angle = ', Angle WRITE(*,*) 'Distance = ', Distance WRITE(*,*) WRITE(* *) Time Target IS & The time to hit target 10 is 27000.0 sec. 43 WRITE(*,*) Time, Target, IS, & Angle * Distance, UNIT print a blank line
  • 44.
    List-Directed WRITE: 3/3ListDirected WRITE: 3/3 The previous example used LEN=* , whichp p , means the length of a CHARACTER constant is determined by actual count. WRITE(*,*) without any expression advances to the next line, producing a blank one. A Fortran 90 compiler will use the best way to print each value. Thus, indentation and alignment are difficult to achieve with WRITE(*,*). One must use the FORMAT statement to produce good looking output. 44
  • 45.
    Complete Example: 1/4CompleteExample: 1/4 This program computes the position (x and yp g p p ( y coordinates) and the velocity (magnitude and direction) of a projectile, given t, the time since launch, u, the i i i i ilaunch velocity, a, the initial angle of launch (in degree), and g=9.8, the acceleration due to gravity. The horizontal and vertical displacements, x and y, are computed as follows: x u a tcos( ) g t2 y u a t g t sin( ) 2 45 2
  • 46.
    Complete Example: 2/4CompleteExample: 2/4 The horizontal and vertical components of the velocityp y vector are computed as cos( )V u acos( )xV u a sin( )yV u a g t The magnitude of the velocity vector is ( )y g V V V2 2 The angle between the ground and the velocity vector is V V Vx y 2 2 tan( ) V V x 46 Vy
  • 47.
    Complete Example: 3/4CompleteExample: 3/4 Write a program to read in the launch angle a, the timep g g , since launch t, and the launch velocity u, and compute the position, the velocity and the angle with the ground. PROGRAM Projectile IMPLICIT NONE REAL, PARAMETER :: g = 9.8 ! acceleration due to gravity REAL, PARAMETER :: PI = 3.1415926 ! you know this. don't you? REAL :: Angle ! launch angle in degree REAL :: Time ! time to flight REAL :: Theta ! direction at time in degreeREAL :: Theta ! direction at time in degree REAL :: U ! launch velocity REAL :: V ! resultant velocity REAL :: Vx ! horizontal velocity REAL :: Vy ! vertical velocity REAL :: X ! horizontal displacement REAL :: Y ! vertical displacement Other executable statements 47 …… Other executable statements …… END PROGRAM Projectile
  • 48.
    Complete Example: 4/4CompleteExample: 4/4 Write a program to read in the launch angle a, the timep g g , since launch t, and the launch velocity u, and compute the position, the velocity and the angle with the ground. READ(*,*) Angle, Time, U Angle = Angle * PI / 180.0 ! convert to radianAngle Angle PI / 180.0 ! convert to radian X = U * COS(Angle) * Time Y = U * SIN(Angle) * Time - g*Time*Time / 2.0 Vx = U * COS(Angle)g Vy = U * SIN(Angle) - g * Time V = SQRT(Vx*Vx + Vy*Vy) Theta = ATAN(Vy/Vx) * 180.0 / PI ! convert to degree WRITE(*,*) 'Horizontal displacement : ', X WRITE(*,*) 'Vertical displacement : ', Y 48 WRITE(*,*) 'Resultant velocity : ', V WRITE(*,*) 'Direction (in degree) : ', Theta
  • 49.
    CHARACTER Operator //CHARACTEROperator // Fortran 90 uses // to concatenate two strings.// g If strings A and B have lengths m and n, the concatenation A // B is a string of length m+nconcatenation A // B is a string of length m+n. CHARACTER(LEN=4) :: John = "John", Sam = "Sam" CHARACTER(LEN=6) :: Lori = "Lori", Reagan = "Reagan" CHARACTER(LEN=10) :: Ans1, Ans2, Ans3, Ans4 Ans1 = John // Lori ! Ans1 = “JohnLori ” Ans2 = Sam // Reagan ! Ans2 = “Sam Reagan” Ans3 = Reagan // Sam ! Ans3 = “ReaganSam ” Ans4 = Lori // Sam ! Ans4 = “Lori Sam ” 49
  • 50.
    CHARACTER Substring: 1/3CHARACTERSubstring: 1/3 A consecutive portion of a string is a substring.p g g To use substrings, one may add an extent specifier to a CHARACTER variable.p f An extent specifier has the following form: ( integer-exp1 : integer-exp2 )( integer-exp1 : integer-exp2 ) The first and the second expressions indicate the start and end: (3:8) means 3 to 8the start and end: (3:8) means 3 to 8, If A = “abcdefg” , then A(3:5) means A’s substring from position 3 to position 5 (i esubstring from position 3 to position 5 (i.e., “cde” ). 50
  • 51.
    CHARACTER Substring: 2/3CHARACTERSubstring: 2/3 In (integer-exp1:integer-exp2), if the( g p g p ), first exp1 is missing, the substring starts from the first character, and if exp2 is missing, the, p g, substring ends at the last character. If A = “12345678” then A(:5) is “12345”If A = 12345678 , then A(:5) is 12345 and A(3+x:) is “5678” where x is 2. A d i ti i lAs a good programming practice, in general, the first expression exp1 should be no less than 1 and the second expression exp2 should be no1, and the second expression exp2 should be no greater than the length of the string. 51
  • 52.
    CHARACTER Substring: 3/3CHARACTERSubstring: 3/3 Substrings can be used on either side of theg assignment operator. Suppose LeftHand = “123456789”pp (length is 10) . LeftHand(3:5) = "abc” yields LeftHand = “12abc67890” LeftHand(4:) = "lmnopqr” yields LeftHand = "123lmnopqr“LeftHand = "123lmnopqr“ LeftHand(3:8) = "abc” yields LeftHand = "12abc 90“ LeftHand(4:7) = "lmnopq” yields LeftHand = "123lmno890" 52
  • 53.
    Example: 1/5Example: 1/5 Thisprogram uses the DATE AND TIME()p g _ _ () Fortran 90 intrinsic function to retrieve the system date and system time. Then, it convertssystem date and system time. Then, it converts the date and time information to a readable format. This program demonstrates the use offormat. This program demonstrates the use of concatenation operator // and substring. System date is a string ccyymmdd where cc =System date is a string ccyymmdd, where cc century, yy = year, mm = month, and dd = day. System time is a string hhmmss.sss, where hh = hour, mm = minute, and ss.sss = second. 53
  • 54.
    Example: 2/5Example: 2/5 Thefollowing shows the specification part.g p p Note the handy way of changing string length. PROGRAM DateTime IMPLICIT NONE CHARACTER(LEN = 8) :: DateINFO ! ccyymmdd CHARACTER(LEN = 4) :: Year, Month*2, Day*2 CHARACTER(LEN = 10) :: TimeINFO, PrettyTime*12 ! hhmmss.sss CHARACTER(LEN = 2) :: Hour, Minute, Second*6 CALL DATE_AND_TIME(DateINFO, TimeINFO) …… other executable statements …… END PROGRAM DateTime 54 This is a handy way of changing string length
  • 55.
    Example: 3/5Example: 3/5 DecomposeDateINFO into year, month andp y , day. DateINFO has a form of ccyymmdd, where cc = century, yy = year, mm = month,y, yy y , , and dd = day. Year = DateINFO(1:4) Month = DateINFO(5:6) Day = DateINFO(7:8) WRITE(* *) 'Date information -> ' DateINFOWRITE(*,*) Date information -> , DateINFO WRITE(*,*) ' Year -> ', Year WRITE(*,*) ' Month -> ', Month WRITE(*,*) ' Day -> ', Day Date information -> 19970811 Year -> 1997 Output: 55 Year -> 1997 Month -> 08 Day -> 11
  • 56.
    Example: 4/5Example: 4/5 Nowdo the same for time:Now do the same for time: Hour = TimeINFO(1:2) Minute = TimeINFO(3:4)Minute = TimeINFO(3:4) Second = TimeINFO(5:10) PrettyTime = Hour // ':' // Minute // ':' // Second WRITE(*,*) WRITE(*,*) 'Time Information -> ', TimeINFO WRITE(*,*) ' Hour -> ', Hour WRITE(*,*) ' Minute -> ', Minute WRITE(*,*) ' Second -> ', SecondWRITE( , ) Second > , Second WRITE(*,*) ' Pretty Time -> ', PrettyTime Time Information -> 010717.620 Hour -> 01 Minute -> 07 S d 17 620 Output: 56 Second -> 17.620 Pretty Time -> 01:07:17.620
  • 57.
    Example: 5/5Example: 5/5 Wemay also use substring to achieve the samey g result: PrettyTime = “ “ ! Initialize to all blanks PrettyTime( :2) = Hour PrettyTime(3:3) = ':'PrettyTime(3:3) = ':' PrettyTime(4:5) = Minute PrettyTime(6:6) = ':' PrettyTime(7: ) = SecondPrettyTime(7: ) = Second WRITE(*,*) WRITE(*,*) ' Pretty Time -> ', PrettyTimeWRITE( , ) Pretty Time > , PrettyTime 57
  • 58.
    What KIND IsIt?What KIND Is It? Fortran 90 has a KIND attribute for selectingg the precision of a numerical constant/variable. The KIND of a constant/variable is a positiveThe KIND of a constant/variable is a positive integer (more on this later) that can be attached to a constantto a constant. Example: i i f126_3 : 126 is an integer of KIND 3 3.1415926_8 : 3.1415926 is a real of KIND 8 58
  • 59.
    What KIND IsIt (INTEGER)? 1/2What KIND Is It (INTEGER)? 1/2 Function SELECTED_INT_KIND(k) selects the_ _ KIND of an integer, where the value of k, a positive integer, means the selected integer k kKIND has a value between -10k and 10k. Thus, the value of k is approximately the number of digits of that KIND. For example, SELECTED_INT_KIND(10) means an integer KIND of no more than 10 digitsKIND of no more than 10 digits. If SELECTED_INT_KIND() returns -1, this th h d d t t thmeans the hardware does not support the requested KIND. 59
  • 60.
    What KIND IsIt (INTEGER)? 2/2What KIND Is It (INTEGER)? 2/2 SELECTED_INT_KIND() is usually used in the_ _ y specification part like the following: INTEGER, PARAMETER :: SHORT = SELECTED_INT_KIND(2)_ _ INTEGER(KIND=SHORT) :: x, y The above declares an INTEGER PARAMETER SHORT with SELECTED_INT_KIND(2), which is the KIND of 2-digit integers. Then, the KIND= attribute specifies that INTEGER variables x and y can hold 2-digit integers. In a program, one may use -12_SHORT and 9_SHORT to write constants of that KIND. 60
  • 61.
    What KIND IsIt (REAL)? 1/2What KIND Is It (REAL)? 1/2 Use SELECTED REAL KIND(k,e) to specify aS _ _ ( , ) p y KIND for REAL constants/variables, where k is the number of significant digits and e is thethe number of significant digits and e is the number of digits in the exponent. Both k and e must be positive integers.must be positive integers. Note that e is optional. SELECTED REAL KIND(7 3) selects a REALSELECTED_REAL_KIND(7,3) selects a REAL KIND of 7 significant digits and 3 digits for the t 0 10 yyyexponent: 0.xxxxxxx 10 yyy 61
  • 62.
    What KIND IsIt (REAL)? 2/2What KIND Is It (REAL)? 2/2 Here is an example:Here is an example: INTEGER, PARAMETER :: & SINGLE=SELECTED REAL KIND(7,2), &SINGLE=SELECTED_REAL_KIND(7,2), & DOUBLE=SELECTED_REAL_KIND(15,3) REAL(KIND=SINGLE) :: x REAL(KIND=DOUBLE) :: Sum 123 4x = 123.45E-5_SINGLE Sum = Sum + 12345.67890_DOUBLE 62
  • 63.
    Why KIND, etc?1/2Why KIND, etc? 1/2 Old Fortran used INTEGER*2, REAL*8,, , DOUBLE PRECISION, etc to specify the “precision” of a variable. For example, REAL*8 means the use of 8 bytes to store a real value. This is not very portable because some computers may not use bytes as their basic t it hil th t 2storage unit, while some others cannot use 2 bytes for a short integer (i.e., INTEGER*2). M l t t h d fiMoreover, we also want to have more and finer precision control. 63
  • 64.
    Why KIND, etc?2/2Why KIND, etc? 2/2 Due to the differences among computerDue to the differences among computer hardware architectures, we have to be careful: The requested KIND may not be satisfiedThe requested KIND may not be satisfied. For example, SELECTED_INT_KIND(100) may not be realistic on most computersmay not be realistic on most computers. Compilers will find the best way good enough (i e larger) for the requested KIND(i.e., larger) for the requested KIND. If a “larger” KIND value is stored to a “ ll ” i bl di bl“smaller” KIND variable, unpredictable result may occur. 64 Use KIND carefully for maximum portability.
  • 65.
    Fortran 90 ControlStructuresFortran 90 Control Structures Computer programming is an art form, like the creation of poetry or music. 1 Donald Ervin Knuth Fall 2010
  • 66.
    LOGICAL VariablesLOGICAL Variables ALOGIAL variable can only hold either .TRUE.y or .FALSE. , and cannot hold values of any other type.other type. Use T or F for LOGICAL variable READ(*,*) WRITE(* *) prints T or F for TRUEWRITE(*,*) prints T or F for .TRUE. and .FALSE., respectively. LOGICAL, PARAMETER :: Test = .TRUE. LOGICAL :: C1, C2 C1 = .true. ! correct C2 = 123 ! Wrong READ(*,*) C1, C2 2 C2 = .false. WRITE(*,*) C1, C2
  • 67.
    Relational Operators: 1/4RelationalOperators: 1/4 Fortran 90 has six relational operators: <, <=,p , , >, >=, ==, /=. Each of these six relational operators takes twop expressions, compares their values, and yields .TRUE. or .FALSE. Thus, a < b < c is wrong, because a < b is LOGICAL and c is REAL or INTEGER. COMPLEX values can only use == and /= LOGICAL values should use .EQV. or .NEQV. for equal and not-equal comparison. 3
  • 68.
    Relational Operators: 2/4RelationalOperators: 2/4 Relational operators have lower priority thanRelational operators have lower priority than arithmetic operators, and //. Thus 3 + 5 > 10 is FALSE and “a” //Thus, 3 + 5 > 10 is .FALSE. and a // “b” == “ab” is .TRUE. Ch t l d d Diff tCharacter values are encoded. Different standards (e.g., BCD, EBCDIC, ANSI) have diff t didifferent encoding sequences. These encoding sequences may not be compatible with each other. 4
  • 69.
    Relational Operators: 3/4RelationalOperators: 3/4 For maximum portability, only assume thep y, y following orders for letters and digits. Thus, “A” < “X”, ‘f’ <= “u”, and “2” <, , , “7” yield .TRUE. But, we don’t know the results of “S” < “s” and “t” >= “%”. However, equal and not-equal such as “S” /= “s” and “t” == “5” are fine. A < B < C < D < E < F < G < H < I < J < K < L < M < N < O < P < Q < R < S < T < U < V < W < X < Y < Z a < b < c < d < e < f < g < h < i < j < k < l < m < n < o < p < q < r < s < t < u < v < w < x < y < z 5 0 < 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9
  • 70.
    Relational Operators: 4/4RelationalOperators: 4/4 String comparison rules:g p Start scanning from the first character. If the current two are equal go for the nextIf the current two are equal, go for the next If there is no more characters to compare, the strings are equal (e.g., “abc” == “abc”) If one string has no more character, the shorter string is smaller (e.g., “ab” < “abc” is TRUE )is .TRUE.) If the current two are not equal, the string has the smaller character is smaller (e ghas the smaller character is smaller (e.g., “abcd” is smaller than “abct”). 6
  • 71.
    LOGICAL Operators: 1/2LOGICALOperators: 1/2 There are 5 LOGICAL operators in Fortranp 90: .NOT., .OR., .AND., .EQV. and .NEQV. NOT is the highest followed by OR.NOT. is the highest, followed by .OR. and .AND., .EQV. and .NEQV. are the lowest. Recall that NOT is evaluated from right to leftRecall that .NOT. is evaluated from right to left. If both operands of .EQV. (equivalence) are the isame, .EQV. yields .TRUE.. .NEQV. is the opposite of .EQV. (not equivalence). If the operands of .NEQV. have different values, .NEQV. yields .TRUE. 7
  • 72.
    LOGICAL Operators: 2/2LOGICALOperators: 2/2 If INTEGER variables m, n, x and y have, , y values 3, 5, 4 and 2, respectively. .NOT. (m > n .AND. x < y) .NEQV. (m <= n .AND. x >= y) .NOT. (3 > 5 .AND. 4 < 2) .NEQV. (3 <= 5 .AND. 4 >= 2) .NOT. (.FALSE. .AND. 4 < 2) .NEQV. (3 <= 5 .AND. 4 >= 2) .NOT. (.FALSE. .AND. .FALSE.) .NEQV. (3 <= 5 .AND. 4 >= 2) .NOT. .FALSE. .NEQV. (3 <= 5 .AND. 4 >= 2) TRUE NEQV (3 5 AND 4 2).TRUE. .NEQV. (3 <= 5 .AND. 4 >= 2) .TRUE. .NEQV. (.TRUE. .AND. 4 >= 2) .TRUE. .NEQV. (.TRUE. .AND. .TRUE.) TRUE NEQV TRUE.TRUE. .NEQV. .TRUE. .FALSE. 8 .NOT. is higher than .NEQV.
  • 73.
    IF-THEN-ELSE Statement: 1/4IFTHEN ELSE Statement: 1/4 Fortran 90 has three if-then-else forms. The most complete one is the IF-THEN-ELSE- IF-END IF An old logical IF statement may be very handy when it is needed. There is an old and obsolete arithmetic IF that you are not encouraged to use. We won’t talky g about it at all. Details are in the next few slides. 9
  • 74.
    IF-THEN-ELSE Statement: 2/4IFTHEN ELSE Statement: 2/4 IF-THEN-ELSE-IF-END IF is the following.g Logical expressions are evaluated sequentially (i.e., top- down). The statement sequence that corresponds to the expression evaluated to .TRUE. will be executed. Otherwise, the ELSE sequence is executed. IF (logical-expression-1) THEN statement sequence 1 ELSE IF (logical expression 2) THENELSE IF (logical-expression-2) THEN statement seqence 2 ELSE IF (logical-expression-3) THEN statement sequence 3statement sequence 3 ELSE IF (.....) THEN ........... ELSE 10 ELSE statement sequence ELSE END IF
  • 75.
    IF-THEN-ELSE Statement: 3/4IFTHEN ELSE Statement: 3/4 Two Examples:Two Examples: Find the minimum of a, b and c and saves the result to Result Letter grade for x IF (a < b .AND. a < c) THEN Result = a ELSE IF (b < a .AND. b < c) THEN INTEGER :: x CHARACTER(LEN=1) :: Grade and saves the result to Result g f ( ) Result = b ELSE Result = c END IF IF (x < 50) THEN Grade = 'F' ELSE IF (x < 60) THEN G d 'D'END IF Grade = 'D' ELSE IF (x < 70) THEN Grade = 'C' ELSE IF (x < 80) THEN( ) Grade = 'B' ELSE Grade = 'A' END IF 11 END IF
  • 76.
    IF-THEN-ELSE Statement: 4/4IFTHEN ELSE Statement: 4/4 The ELSE-IF part and ELSE part are optional.p p p If the ELSE part is missing and none of the logical expressions is .TRUE., the IF-THEN-g p , ELSE has no effect. no ELSE-IF no ELSE IF (logical-expression-1) THEN statement sequence 1 ELSE IF (logical-expression-1) THEN statement sequence 1 ELSE IF (logical-expression-2) THEN statement sequence ELSE END IF statement sequence 2 ELSE IF (logical-expression-3) THEN statement sequence 3 ELSE IF ( ) THENELSE IF (.....) THEN ........... END IF 12
  • 77.
    Example: 1/2Example: 1/2 Givena quadratic equation ax2 +bx + c = 0,Given a quadratic equation ax bx c 0, where a 0, its roots are computed as follows: b b2 4 x b b a c a 2 4 2 However, this is a very poor and unreliable way of computing roots. Will return to this soon. PROGRAM QuadraticEquation IMPLICIT NONE REAL :: a, b, c REAL :: d REAL :: root1, root2 13 …… other executable statement …… END PROGRAM QuadraticEquation
  • 78.
    Example: 2/2Example: 2/2 Thefollowing shows the executable partThe following shows the executable part READ(*,*) a, b, c WRITE(*,*) 'a = ', a WRITE(*,*) 'b = ', b WRITE(*,*) 'c = ', c WRITE(*,*) d = b*b - 4.0*a*c IF (d >= 0.0) THEN ! is it solvable? d = SQRT(d) root1 = (-b + d)/(2.0*a) ! first root root2 = (-b - d)/(2.0*a) ! second root WRITE(* *) 'R t ' t1 ' d ' t2WRITE(*,*) 'Roots are ', root1, ' and ', root2 ELSE ! complex roots WRITE(*,*) 'There is no real roots!' WRITE(* *) 'Discriminant = ' d 14 WRITE(*,*) 'Discriminant = ', d END IF
  • 79.
    IF-THEN-ELSE Can beNested: 1/2IF THEN ELSE Can be Nested: 1/2 Another look at the quadratic equation solver.Another look at the quadratic equation solver. IF (a == 0.0) THEN ! could be a linear equation IF (b == 0 0) THEN ! the input becomes c = 0IF (b == 0.0) THEN ! the input becomes c = 0 IF (c == 0.0) THEN ! all numbers are roots WRITE(*,*) 'All numbers are roots' ELSE ! unsolvableELSE ! unsolvable WRITE(*,*) 'Unsolvable equation' END IF ELSE ! linear equation bx + c = 0ELSE ! linear equation bx + c 0 WRITE(*,*) 'This is linear equation, root = ', -c/b END IF ELSE ! ok, we have a quadratic equation, q q ...... solve the equation here …… END IF 15
  • 80.
    IF-THEN-ELSE Can beNested: 2/2IF THEN ELSE Can be Nested: 2/2 Here is the big ELSE part:g S p d b*b 4 0*a*cd = b*b - 4.0*a*c IF (d > 0.0) THEN ! distinct roots? d = SQRT(d) root1 = (-b + d)/(2 0*a) ! first rootroot1 = (-b + d)/(2.0*a) ! first root root2 = (-b - d)/(2.0*a) ! second root WRITE(*,*) 'Roots are ', root1, ' and ', root2 ELSE IF (d == 0.0) THEN ! repeated roots?ELSE IF (d == 0.0) THEN ! repeated roots? WRITE(*,*) 'The repeated root is ', -b/(2.0*a) ELSE ! complex roots WRITE(*,*) 'There is no real roots!'( , ) WRITE(*,*) 'Discriminant = ', d END IF 16
  • 81.
    Logical IFLogical IF Thelogical IF is from Fortran 66, which is ang , improvement over the Fortran I arithmetic IF. If logical-expression is .TRUE. , statement isg p , executed. Otherwise, execution goes though. The statement can be assignment andg input/output. IF (logical-expression) statementIF (logical expression) statement Smallest = b Cnt = Cnt + 1Smallest = b IF (a < b) Smallest = a Cnt = Cnt + 1 IF (MOD(Cnt,10) == 0) WRITE(*,*) Cnt 17
  • 82.
    The SELECT CASEStatement: 1/7The SELECT CASE Statement: 1/7 Fortran 90 has the SELECT CASE statement forS S selective execution if the selection criteria are based on simple values in INTEGER, LOGICALp , and CHARACTER. No, REAL is not applicable. SELECT CASE (selector) CASE (label-list-1) statements-1 CASE (label-list-2) 2 selector is an expression evaluated to an INTEGER, LOGICAL or CHARACTER value statements-2 CASE (label-list-3) statements-3 other cases label-list is a set of constants or PARAMETERS of the same type …… other cases …… CASE (label-list-n) statements-n CASE DEFAULT yp as the selector statements is one or more 18 CASE DEFAULT statements-DEFAULT END SELECT statements s o e o o e executable statements
  • 83.
    The SELECT CASEStatement: 2/7The SELECT CASE Statement: 2/7 The label-list is a list of the following forms:The label list is a list of the following forms: value a specific value al e1 al e2 values betweenvalue1 : value2 values between value1 and value2, including value1 and al e2 and al e1 < al e2value2, and value1 <= value2 value1 : values larger than or equal to value1 : value2 values less than or equal to value2 Reminder: value, value1 and value2 must 19 , be constants or PARAMETERs.
  • 84.
    The SELECT CASEStatement: 3/7The SELECT CASE Statement: 3/7 The SELECT CASE statement is SELECT CASE (selector) executed as follows: Compare the value of SELECT CASE (selector) CASE (label-list-1) statements-1 CASE (label-list-2) selector with the labels in each case. If a match is f d t th ( ) statements-2 CASE (label-list-3) statements-3 found, execute the corresponding statements. If no match is found and if …… other cases …… CASE (label-list-n) statements-n If no match is found and if CASE DEFAULT is there, execute the statements- CASE DEFAULT statements-DEFAULT END SELECT DEFAULT. Execute the next statement optional 20 following the SELECT CASE.
  • 85.
    The SELECT CASEStatement: 4/7The SELECT CASE Statement: 4/7 Some important notes:Some important notes: The values in label-lists should be unique. Otherwise it is not known which CASEOtherwise, it is not known which CASE would be selected. CASE DEFAULT should be used whenever itCASE DEFAULT should be used whenever it is possible, because it guarantees that there is l t d thi ( )a place to do something (e.g., error message) if no match is found. b h iCASE DEFAULT can be anywhere in a SELECT CASE statement; but, a preferred l i h l i h li 21 place is the last in the CASE list.
  • 86.
    The SELECT CASEStatement: 5/7The SELECT CASE Statement: 5/7 Two examples of SELECT CASE:p S S CHARACTER(LEN=4) :: Title INTEGER :: DrMD = 0, PhD = 0 CHARACTER(LEN=1) :: c INTEGER :: DrMD 0, PhD 0 INTEGER :: MS = 0, BS = 0 INTEGER ::Others = 0 i SELECT CASE (c) CASE ('a' : 'j') WRITE(*,*) ‘First ten letters' SELECT CASE (Title) CASE ("DrMD") DrMD = DrMD + 1 CASE ("PhD") CASE ('l' : 'p', 'u' : 'y') WRITE(*,*) & 'One of l,m,n,o,p,u,v,w,x,y' CASE ('z', 'q' : 't')CASE ( PhD ) PhD = PhD + 1 CASE ("MS") MS = MS + 1 ( ) CASE ( z , q : t ) WRITE(*,*) 'One of z,q,r,s,t' CASE DEFAULT WRITE(*,*) 'Other characters' CASE ("BS") BS = BS + 1 CASE DEFAULT Others = Others + 1 END SELECT 22 Ot e s Ot e s END SELECT
  • 87.
    The SELECT CASEStatement: 6/7The SELECT CASE Statement: 6/7 Here is a more complex example:Here is a more complex example: INTEGER :: Number, Range Number Range Why? <= -10 1 CASE (:-10, 10:) SELECT CASE (Number) CASE ( : -10, 10 : ) Range = 1 <= 10 1 CASE (: 10, 10:) -9,-8,-7,-6 6 CASE DEFAULT -5,-4,-3 2 CASE (-5:-3, 6:9) CASE (-5:-3, 6:9) Range = 2 CASE (-2:2) -2,-1,0,1,2 3 CASE (-2:2) 3 4 CASE (3, 5) Range = 3 CASE (3, 5) Range = 4 4 5 CASE (4) 5 4 CASE (3, 5) 6,7,8,9 2 CASE (-5:-3, 6:9) CASE (4) Range = 5 CASE DEFAULT R 6 6,7,8,9 2 CASE ( 5: 3, 6:9) >= 10 1 CASE (:-10, 10:) 23 Range = 6 END SELECT
  • 88.
    The SELECT CASEStatement: 7/7The SELECT CASE Statement: 7/7 PROGRAM CharacterTesting IMPLICIT NONE CHARACTER(LEN=1) :: Input This program reads in a character and determines if it is a vowel, a consonant, CHARACTER(LEN=1) :: Input READ(*,*) Input SELECT CASE (Input) CASE ('A' : 'Z', 'a' : 'z') ! rule out letters a digit, one of the four arithmetic operators, a space, or something else (i.e., %, $, @, etc). WRITE(*,*) 'A letter is found : "', Input, '"' SELECT CASE (Input) ! a vowel ? CASE ('A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o','u') WRITE(* *) 'It is a vowel'WRITE( , ) It is a vowel CASE DEFAULT ! it must be a consonant WRITE(*,*) 'It is a consonant' END SELECT CASE ('0' : '9') ! a digit WRITE(*,*) 'A digit is found : "', Input, '"' CASE ('+', '-', '*', '/') ! an operator WRITE(*,*) 'An operator is found : "', Input, '"'WRITE( , ) An operator is found : , Input, CASE (' ') ! space WRITE(*,*) 'A space is found : "', Input, '"' CASE DEFAULT ! something else 24 WRITE(*,*) 'Something else found : "', Input, '"' END SELECT END PROGRAM CharacterTesting
  • 89.
    The Counting DOLoop: 1/6The Counting DO Loop: 1/6 Fortran 90 has two forms of DO loop: thep counting DO and the general DO. The counting DO has the following form:The counting DO has the following form: DO control-var = initial, final [, step] statementsstatements END DO control-var is an INTEGER variable,control var is an INTEGER variable, initial, final and step are INTEGER expressions; however, step cannot be zero.expressions; however, step cannot be zero. If step is omitted, its default value is 1. t bl t t t f th O 25 statements are executable statements of the DO.
  • 90.
    The Counting DOLoop: 2/6The Counting DO Loop: 2/6 Before a DO-loop starts, expressions initial,p , p , final and step are evaluated exactly once. When executing the DO-loop, these values willg p, not be re-evaluated. Note again the value of step cannot be zeroNote again, the value of step cannot be zero. If step is positive, this DO counts up; if step is negative this DO counts downnegative, this DO counts down DO control-var = initial final [ step]DO control-var = initial, final [, step] statements END DO 26
  • 91.
    The Counting DOLoop: 3/6The Counting DO Loop: 3/6 If step is positive:p p The control-var receives the value of initial. If the value of control-var is less than or equal toIf the value of control var is less than or equal to the value of final, the statements part is executed. Then, the value of step is added to control-var, and goes back and compares the values of control-var and final. If the value of control-var is greater than the value of final, the DO-loop completes and the statement following END DO is executedstatement following END DO is executed. 27
  • 92.
    The Counting DOLoop: 4/6The Counting DO Loop: 4/6 If step is negative:p g The control-var receives the value of initial. If the value of control-var is greater than orIf the value of control var is greater than or equal to the value of final, the statements part is executed. Then, the value of step is added to control-var, goes back and compares the values of control-var and final. If the value of control-var is less than the value of final, the DO-loop completes and the statement following END DO is executedfollowing END DO is executed. 28
  • 93.
    The Counting DOLoop: 5/6The Counting DO Loop: 5/6 Two simple examples:Two simple examples: INTEGER :: N, k odd integers between 1 & N READ(*,*) N WRITE(*,*) “Odd number between 1 and “, N DO k = 1, N, 2 between 1 & N WRITE(*,*) k END DO INTEGER, PARAMETER :: LONG = SELECTED_INT_KIND(15) INTEGER(KIND=LONG) :: Factorial, i, N READ(* *) N factorial of N READ(*,*) N Factorial = 1_LONG DO i = 1, N Factorial = Factorial * i 29 END DO WRITE(*,*) N, “! = “, Factorial
  • 94.
    The Counting DOLoop: 6/6The Counting DO Loop: 6/6 Important Notes:Important Notes: The step size step cannot be zero N h th l f i bl iNever change the value of any variable in control-var and initial, final, and stepstep. For a count-down DO-loop, step must be i “ ” inegative. Thus, “do i = 10, -10” is not a count-down DO-loop, and the statements portion is not executed. Fortran 77 allows REAL variables in DO; but, 30 don’t use it as it is not safe.
  • 95.
    General DO-Loop withEXIT: 1/2General DO Loop with EXIT: 1/2 The general DO-loop has the following form:The general DO loop has the following form: DO statementsstatements END DO t t t ill b t d t dlstatements will be executed repeatedly. To exit the DO-loop, use the EXIT or CYCLE statement. The EXIT statement brings the flow of control to the statement following (i.e., exiting) the END DO. The CYCLE statement starts the next iteration 31 e C C state e t sta ts t e e t te at o (i.e., executing statements again).
  • 96.
    General DO-Loop withEXIT: 2/2General DO Loop with EXIT: 2/2 REAL PARAMETER :: Lower = 1 0 Upper = 1 0 Step = 0 25REAL, PARAMETER :: Lower = -1.0, Upper = 1.0, Step = 0.25 REAL :: x x = Lower ! initialize the control variable DO IF (x > Upper) EXIT ! is it > final-value? WRITE(*,*) x ! no, do the loop body x = x + Step ! increase by step-sizex = x + Step ! increase by step-size END DO INTEGER :: InputINTEGER :: Input DO WRITE(*,*) 'Type in an integer in [0, 10] please --> ' READ(*,*) Input IF (0 <= Input .AND. Input <= 10) EXIT WRITE(*,*) 'Your input is out of range. Try again' END DO 32 END DO
  • 97.
    Example, exp(x): 1/2Example,exp(x): 1/2 The exp(x) function has an infinite series:The exp(x) function has an infinite series: exp( ) ! ! .... ! ......x x x x x i i 1 2 3 2 3 Sum each term until a term’s absolute value is ! ! !i2 3 less than a tolerance, say 0.00001. PROGRAM Exponential IMPLICIT NONE INTEGER :: Count ! # of terms used REAL :: Term ! a term REAL :: Sum ! the sum REAL :: X ! the input x REAL, PARAMETER :: Tolerance = 0.00001 ! tolerance 33 …… executable statements …… END PROGRAM Exponential
  • 98.
    Example, exp(x): 2/2Example,exp(x): 2/2 Note: 1 ( 1)! ! 1 i i x x x i i i This is not a good solution, though. ( 1)! ! 1i i i This is not a good solution, though. READ(*,*) X ! read in x Count = 1 ! the first term is 1 iSum = 1.0 ! thus, the sum starts with 1 Term = X ! the second term is x DO ! for each term IF (ABS(T ) < T l ) EXIT ! if t ll itIF (ABS(Term) < Tolerance) EXIT ! if too small, exit Sum = Sum + Term ! otherwise, add to sum Count = Count + 1 ! count indicates the next term Term = Term * (X / Count) ! compute the value of next termTerm = Term * (X / Count) ! compute the value of next term END DO WRITE(*,*) 'After ', Count, ' iterations:' WRITE(* *) ' Exp(' X ') = ' Sum 34 WRITE( , ) Exp( , X, ) = , Sum WRITE(*,*) ' From EXP() = ', EXP(X) WRITE(*,*) ' Abs(Error) = ', ABS(Sum - EXP(X))
  • 99.
    Example, Prime Checking:1/2Example, Prime Checking: 1/2 A positive integer n >= 2 is a prime number if theA positive integer n 2 is a prime number if the only divisors of this integer are 1 and itself. If n = 2 it is a primeIf n = 2, it is a prime. If n > 2 is even (i.e., MOD(n,2) == 0), not a prime. If n is odd, then: If the odd numbers between 3 and n-1 cannot divide n, n is a prime! Do we have to go up to n-1? No, SQRT(n) isg p , Q ( ) good enough. Why? 35
  • 100.
    Example, Prime Checking:2/2Example, Prime Checking: 2/2 INTEGER :: Number ! the input number INTEGER :: Divisor ! the running divisor READ(*,*) Number ! read in the input IF (Number < 2) THEN ! not a prime if < 2 WRITE(* *) 'Illegal input'WRITE(*,*) 'Illegal input' ELSE IF (Number == 2) THEN ! is a prime if = 2 WRITE(*,*) Number, ' is a prime' ELSE IF (MOD(Number,2) == 0) THEN ! not a prime if even WRITE(*,*) Number, ' is NOT a prime' ELSE ! an odd number here Divisor = 3 ! divisor starts with 3 DO ! divide the input numberDO ! divide the input number IF (Divisor*Divisor > Number .OR. MOD(Number, Divisor) == 0) EXIT Divisor = Divisor + 2 ! increase to next odd END DO IF (Divisor*Divisor > Number) THEN ! which condition fails? WRITE(*,*) Number, ' is a prime' ELSE WRITE(* *) Number ' is NOT a prime' 36 WRITE(*,*) Number, is NOT a prime END IF END IF this is better than SQRT(REAL(Divisor)) > Number
  • 101.
    Finding All Primesin [2,n]: 1/2Finding All Primes in [2,n]: 1/2 The previous program can be modified to findThe previous program can be modified to find all prime numbers between 2 and n. PROGRAM Primes IMPLICIT NONE INTEGER :: Range, Number, Divisor, Count WRITE(*,*) 'What is the range ? ' DO ! keep trying to read a good input READ(*,*) Range ! ask for an input integer IF (Range >= 2) EXIT ! if it is GOOD, exit WRITE(*,*) 'The range value must be >= 2. Your input = ', Range WRITE(*,*) 'Please try again:' ! otherwise, bug the user END DOEND DO …… we have a valid input to work on here …… END PROGRAM Primes 37
  • 102.
    Finding All Primesin [2,n]: 2/2Finding All Primes in [2,n]: 2/2 Count = 1 ! input is correct. start counting WRITE(*,*) ! 2 is a prime WRITE(*,*) 'Prime number #', Count, ': ', 2 DO Number = 3, Range, 2 ! try all odd numbers 3, 5, 7, ... Divisor = 3 ! divisor starts with 3 DO i i i i i iIF (Divisor*Divisor > Number .OR. MOD(Number,Divisor) == 0) EXIT Divisor = Divisor + 2 ! not a divisor, try next END DO IF (Divisor*Divisor > Number) THEN ! divisors exhausted?IF (Divisor Divisor > Number) THEN ! divisors exhausted? Count = Count + 1 ! yes, this Number is a prime WRITE(*,*) 'Prime number #', Count, ': ', Number END IF END DO WRITE(*,*) WRITE(*,*) 'There are ', Count, ' primes in the range of 2 and ', Range 38 ( , ) e e a e , Cou t, p es t e a ge o a d , a ge
  • 103.
    Factoring a Number:1/3Factoring a Number: 1/3 Given a positive integer, one can always factorizep g , y it into prime factors. The following is an example: 586390350 = 2 3 52 72 13 17 192 Here, 2, 3, 5, 7, 13, 17 and 19 are prime factors., , , , , , p It is not difficult to find all prime factors. We can repeatedly divide the input by 2.We can repeatedly divide the input by 2. Do the same for odd numbers 3, 5, 7, 9, …. But we said “prime” factors No problemBut, we said “prime” factors. No problem, multiples of 9 are eliminated by 3 in an earlier stage! 39 stage!
  • 104.
    Factoring a Number:2/3Factoring a Number: 2/3 PROGRAM Factorize IMPLICIT NONE INTEGER :: Input INTEGER :: Divisor INTEGER :: Count WRITE(*,*) 'This program factorizes any integer >= 2 --> ' READ(*,*) Input Count = 0 DO ! remove all factors of 2 IF (MOD(I t 2) / 0 OR I t 1) EXITIF (MOD(Input,2) /= 0 .OR. Input == 1) EXIT Count = Count + 1 ! increase count WRITE(*,*) 'Factor # ', Count, ': ', 2 Input = Input / 2 ! remove this factorInput = Input / 2 ! remove this factor END DO …… use odd numbers here …… END PROGRAM Factorize 40 END PROGRAM Factorize
  • 105.
    Factoring a Number:3/3Factoring a Number: 3/3 Divisor = 3 ! now we only worry about odd factors DO ! Try 3, 5, 7, 9, 11 .... IF (Divisor > Input) EXIT ! factor is too large, exit and done DO ! try this factor repeatedlyDO ! try this factor repeatedly IF (MOD(Input,Divisor) /= 0 .OR. Input == 1) EXIT Count = Count + 1 WRITE(*,*) 'Factor # ', Count, ': ', Divisor Input = Input / Divisor ! remove this factor from Input END DO Divisor = Divisor + 2 ! move to next odd number END DOEND DO Note that even 9 15 49 will be used they would only be usedNote that even 9, 15, 49, … will be used, they would only be used once because Divisor = 3 removes all multiples of 3 (e.g., 9, 15, …), Divisor = 5 removes all multiples of 5 (e.g., 15, 25, …), and Divisor = 7 removes all multiples of 7 (e.g., 21, 35, 49, …), etc. 41 Divisor 7 removes all multiples of 7 (e.g., 21, 35, 49, …), etc.
  • 106.
    Handling End-of-File: 1/3HandlingEnd of File: 1/3 Very frequently we don’t know the number ofVery frequently we don t know the number of data items in the input. Fortran uses IOSTAT= for I/O error handling:Fortran uses IOSTAT= for I/O error handling: READ(*,*,IOSTAT=v) v1, v2, …, vn In the above, v is an INTEGER variable. After the execution of READ(*,*): If v = 0, READ(*,*) was executed successfully If v > 0, an error occurred in READ(*,*) and not all variables received values. If v < 0, encountered end-of-file, and not all 42 variables received values.
  • 107.
    Handling End-of-File: 2/3HandlingEnd of File: 2/3 Every file is ended with a special character.Every file is ended with a special character. Unix and Windows use Ctrl-D and Ctrl-Z. When using keyboard to enter data toWhen using keyboard to enter data to READ(*,*), Ctrl-D means end-of-file in Unix. If IOSTAT returns a positive value we onlyIf IOSTAT= returns a positive value, we only know something was wrong in READ(*,*) such t i t h h fil d i tas type mismatch, no such file, device error, etc. We really don’t know exactly what happened because the returned value is system dependent. 43
  • 108.
    Handling End-of-File: 3/3HandlingEnd of File: 3/3 i t t t INTEGER :: io, x, sum 1 3 The total is 8 input output sum = 0 DO READ(*,*,IOSTAT=io) x IF (io > 0) THEN 4 inputIF (io > 0) THEN WRITE(*,*) 'Check input. Something was wrong' EXIT ELSE IF (io < 0) THEN (* *) h l i 1 & 4 no output WRITE(*,*) 'The total is ', sum EXIT ELSE sum = sum + x END IF END DO 44
  • 109.
    Computing Means, etc:1/4Computing Means, etc: 1/4 Let us compute the arithmetic, geometric andLet us compute the arithmetic, geometric and harmonic means of unknown number of values: arithmetic mean = x x xn1 2 ...... arithmetic mean = geometric mean = n x x xn n 1 2 ...... harmonic mean = n 1 1 1 Note that only positive values will be considered x x xn1 2 ...... Note that only positive values will be considered. This naïve way is not a good method. 45
  • 110.
    Computing Means, etc:2/4Computing Means, etc: 2/4 PROGRAM ComputingMeansPROGRAM ComputingMeans IMPLICIT NONE REAL :: X REAL :: Sum, Product, InverseSum, , REAL :: Arithmetic, Geometric, Harmonic INTEGER :: Count, TotalValid INTEGER :: IO ! for IOSTAT= Sum = 0.0 Product = 1.0 InverseSum = 0.0 TotalValid = 0 Count = 0 …… other computation part …… END PROGRAM ComputingMeans 46
  • 111.
    Computing Means, etc:3/4Computing Means, etc: 3/4 DO READ(*,*,IOSTAT=IO) X ! read in data IF (IO < 0) EXIT ! IO < 0 means end-of-file reached Count = Count + 1 ! otherwise, got some value IF (IO > 0) THEN ! IO > 0 means something wrongIF (IO > 0) THEN ! IO > 0 means something wrong WRITE(*,*) 'ERROR: something wrong in your input' WRITE(*,*) 'Try again please' ELSE ! IO = 0 means everything is normal WRITE(*,*) 'Input item ', Count, ' --> ', X IF (X <= 0.0) THEN WRITE(*,*) 'Input <= 0. Ignored' ELSEELSE TotalValid = TotalValid + 1 Sum = Sum + X Product = Product * X InverseSum = InverseSum + 1.0/X END IF END IF END DO 47 END DO
  • 112.
    Computing Means, etc:4/4Computing Means, etc: 4/4 WRITE(*,*) IF (TotalValid > 0) THEN Arithmetic = Sum / TotalValid Geometric = Product**(1.0/TotalValid) Harmonic = TotalValid / InverseSum WRITE(*,*) '# of items read --> ', Count WRITE(*,*) '# of valid items -> ', TotalValidWRITE( , ) # of valid items > , TotalValid WRITE(*,*) 'Arithmetic mean --> ', Arithmetic WRITE(*,*) 'Geometric mean --> ', Geometric WRITE(*,*) 'Harmonic mean --> ', Harmonic ELSE WRITE(*,*) 'ERROR: none of the input is positive' END IF 48
  • 113.
    Fortran 90 ArraysFortran90 Arrays Program testing can be used to show the presence of bugsProgram testing can be used to show the presence of bugs, but never to show their absence Edsger W. Dijkstra 1 Fall 2009
  • 114.
    The DIMENSION Attribute:1/6The DIMENSION Attribute: 1/6 A Fortran 90 program uses the DIMENSIONp g attribute to declare arrays. The DIMENSION attribute requires threeq components in order to complete an array specification, rank, shape, and extent. The rank of an array is the number of “indices” or “subscripts.” The maximum rank is 7 (i.e., seven-dimensional). The shape of an array indicates the number of elements in each “dimension.” 2
  • 115.
    The DIMENSION Attribute:2/6The DIMENSION Attribute: 2/6 The rank and shape of an array is representedThe rank and shape of an array is represented as (s1,s2,…,sn), where n is the rank of the array and si (1 i n) is the number of elements in theand si (1 i n) is the number of elements in the i-th dimension. (7) means a rank 1 array with 7 elements(7) means a rank 1 array with 7 elements (5,9) means a rank 2 array (i.e., a table) h fi t d d di i h 5whose first and second dimensions have 5 and 9 elements, respectively. (10,10,10,10) means a rank 4 array that has 10 elements in each dimension. 3
  • 116.
    The DIMENSION Attribute:3/6The DIMENSION Attribute: 3/6 The extent is written as m:n, where m and n (mThe extent is written as m:n, where m and n (m n) are INTEGERs. We saw this in the SELECT CASE, substring, etc., g, Each dimension has its own extent. A t t f di i i th f itAn extent of a dimension is the range of its index. If m: is omitted, the default is 1. i i i 3 2 1 0-3:2 means possible indices are -3, -2 , -1, 0, 1, 2 5:8 means possible indices are 5,6,7,8 7 means possible indices are 1,2,3,4,5,6,7 4 p , , , , , ,
  • 117.
    The DIMENSION Attribute:4/6The DIMENSION Attribute: 4/6 The DIMENSION attribute has the followingg form: DIMENSION(extent-1, extent-2, …, extent-n)( , , , ) Here, extent-i is the extent of dimension i. This means an array of dimension n (i.e., nThis means an array of dimension n (i.e., n indices) whose i-th dimension index has a range given by extent-i.g y Just a reminder: Fortran 90 only allows maximum 7 dimensions. Exercise: given a DIMENSION attribute, determine its shape. 5 p
  • 118.
    The DIMENSION Attribute:5/6The DIMENSION Attribute: 5/6 Here are some examples:Here are some examples: DIMENSION(-1:1) is a 1-dimensional array with possible indices -1 0 1array with possible indices -1,0,1 DIMENSION(0:2,3) is a 2-dimensional (i t bl ) P ibl l f tharray (i.e., a table). Possible values of the first index are 0,1,2 and the second 1,2,3 i 3 i iDIMENSION(3,4,5) is a 3-dimensional array. Possible values of the first index are 1,2,3, the second 1,2,3,4, and the third 1,2,3,4,5. 6
  • 119.
    The DIMENSION Attribute:6/6The DIMENSION Attribute: 6/6 Array declaration is simple. Add they p DIMENSION attribute to a type declaration. Values in the DIMENSION attribute are usuallyy PARAMETERs to make program modifications easier. INTEGER, PARAMETER :: SIZE=5, LOWER=3, UPPER = 5 INTEGER, PARAMETER :: SMALL = 10, LARGE = 15 REAL, DIMENSION(1:SIZE) :: x INTEGER, DIMENSION(LOWER:UPPER,SMALL:LARGE) :: a,b, ( , ) , LOGICAL, DIMENSION(2,2) :: Truth_Table 7
  • 120.
    Use of Arrays:1/3Use of Arrays: 1/3 Fortran 90 has, in general, three different ways, g , y to use arrays: referring to individual array element, referring to the whole array, and referring to a section of an array. The first one is very easy. One just starts with the array name, followed by () between which are the indices separated by ,. Note that each index must be an INTEGER or an expression evaluated to an INTEGER, and the l f i d t b i th f thvalue of an index must be in the range of the corresponding extent. But, Fortran 90 won’t check it for you 8 check it for you.
  • 121.
    Use of Arrays:2/3Use of Arrays: 2/3 Suppose we have the following declarationsSuppose we have the following declarations INTEGER, PARAMETER :: L_BOUND = 3, U_BOUND = 10 INTEGER, DIMENSION(L BOUND:U BOUND) :: xINTEGER, DIMENSION(L_BOUND:U_BOUND) :: x DO i = L_BOUND, U_BOUND x(i) = i DO i = L_BOUND, U_BOUND IF (MOD(i,2) == 0) THEN iEND DO x(i) = 0 ELSE x(i) = 1 array x() has 3,4,5,…, 10 END IF END DO array x() has 1 0 1 0 1 0 1 0 9 array x() has 1,0,1,0,1,0,1,0
  • 122.
    Use of Arrays:3/3Use of Arrays: 3/3 Suppose we have the following declarations: INTEGER, PARAMETER :: L_BOUND = 3, U_BOUND = 10 INTEGER, DIMENSION(L_BOUND:U_BOUND, & L_BOUND:U_BOUND) :: a DO i = L_BOUND, U_BOUND DO j = L_BOUND, U_BOUND a(i j) = 0 DO i = L_BOUND, U_BOUND DO j = i+1, U_BOUND t = a(i,j)a(i,j) = 0 END DO a(i,i) = 1 t a(i,j) a(i,j) = a(j,i) a(j,i) = t END DO END DO END DO generate an identity matrix Swapping the lower and upper diagonal parts (i e 10 upper diagonal parts (i.e., the transpose of a matrix)
  • 123.
    The Implied DO:1/7The Implied DO: 1/7 Fortran has the implied DO that can generatep g efficiently a set of values and/or elements. The implied DO is a variation of the DO-loop.p p The implied DO has the following syntax: (item-1 item-2 item-n v=initial final step)(item 1, item 2, …,item n, v=initial,final,step) Here, item-1, item-2, …, item-n are variables or expressions, v is an INTEGERvariables or expressions, v is an INTEGER variable, and initial, final, and step are INTEGER expressions.p “v=initial,final,step” is exactly what we saw in a DO-loop. 11 p
  • 124.
    The Implied DO:2/7The Implied DO: 2/7 The execution of an implied DO below lets variablep v to start with initial, and step though to final with a step size step. (item 1 item 2 item n v=initial final step)(item-1, item-2, …,item-n, v=initial,final,step) The result is a sequence of items. (i+1, i=1,3) generates 2 3 4(i+1, i=1,3) generates 2, 3, 4. (i*k, i+k*i, i=1,8,2) generates k, 1+k (i = 1), 3*k, 3+k*3 (i = 3), 5*k, 5+k*5 (i = 5),), , ( ), , ( ), 7*k, 7+k*7 (i = 7). (a(i),a(i+2),a(i*3-1),i*4,i=3,5) t (3) ( ) (8) 12 (i 3) (4)generates a(3), a(5), a(8) , 12 (i=3), a(4), a(6), a(11), 16 (i=4), a(5), a(7), a(14), 20. 12
  • 125.
    The Implied DO:3/7The Implied DO: 3/7 Implied DO may be nested.p y (i*k,(j*j,i*j,j=1,3), i=2,4) In the above (j*j i*j j 1 3) is nested inIn the above, (j*j,i*j,j=1,3) is nested in the implied i loop. Here are the results: When i = 2, the implied DO generates 2*k, (j*j,2*j,j=1,3) Then j goes from 1 to 3 and generatesThen, j goes from 1 to 3 and generates 2*k, 1*1, 2*1, 2*2, 2*2, 3*3, 2*3 j = 1 j = 2 j = 3 13 j = 1 j = 2 j = 3
  • 126.
    The Implied DO:4/7The Implied DO: 4/7 Continue with the previous examplep p (i*k,(j*j,i*j,j=1,3), i=2,4) When i = 3, it generates the following:g g 3*k, (j*j,3*j,j=1,3) Expanding the j loop yields:p g j p y 3*k, 1*1, 3*1, 2*2, 3*2, 3*3, 3*3 When i = 4, the i loop generates, p g 4*k, (j*j, 4*j, j=1,3) Expanding the j loop yieldsp g j p y 4*k, 1*1, 4*1, 2*2, 4*2, 3*3, 4*3 14j = 1 j = 2 j = 3
  • 127.
    The Implied DO:5/7The Implied DO: 5/7 The following generates a multiplication table:The following generates a multiplication table: ((i*j,j=1,9),i=1,9) When i 1 the inner j implied DO loopWhen i = 1, the inner j implied DO-loop produces 1*1, 1*2, …, 1*9 When i = 2, the inner j implied DO-loop produces 2*1, 2*2, …, 2*9 When i = 9, the inner j implied DO-loop produces 9*1, 9*2, …, 9*9 15
  • 128.
    The Implied DO:6/7The Implied DO: 6/7 The following produces all upper triangularThe following produces all upper triangular entries, row-by-row, of a 2-dimensional array: ((a(p q) q = p n) p = 1 n)((a(p,q),q = p,n),p = 1,n) When p = 1, the inner q loop produces a(1,1), a(1 2) a(1 n)a(1,2), …, a(1,n) When p=2, the inner q loop produces a(2,2), a(2,3), …., a(2,n) When p=3, the inner q loop produces a(3,3), a(3,4), …, a(3,n) When p=n, the inner q loop produces a(n,n) 16 p , q p p ( , )
  • 129.
    The Implied DO:7/7The Implied DO: 7/7 The following produces all upper triangularThe following produces all upper triangular entries, column-by-column: ((a(p q) p = 1 q) q = 1 n)((a(p,q),p = 1,q),q = 1,n) When q=1, the inner p loop produces a(1,1) When q=2, the inner p loop produces a(1,2), a(2,2) When q=3, the inner p loop produces a(1,3), a(2,3), …, a(3,3) When q=n, the inner p loop produces a(1,n), a(2,n), a(3,n), …, a(n,n) 17 ( , ), ( , ), , ( , )
  • 130.
    Array Input/Output: 1/8ArrayInput/Output: 1/8 Implied DO can be used in READ(*,*) andp ( , ) WRITE(*,*) statements. When an implied DO is used it is equivalent toWhen an implied DO is used, it is equivalent to execute the I/O statement with the generated elementselements. The following prints out a multiplication table (* *)((i * j i*j j 1 9) i 1 9)WRITE(*,*)((i,“*”,j,“=“,i*j,j=1,9),i=1,9) The following has a better format (i.e., 9 rows): DO i = 1, 9 WRITE(*,*) (i, “*”, j, “=“, i*j, j=1,9) 18 END DO
  • 131.
    Array Input/Output: 2/8ArrayInput/Output: 2/8 The following shows three ways of reading ng y g data items into an one dimensional array a(). Are they the same?Are they the same? READ(*,*) n,(a(i),i=1,n)(1) READ(*,*) n i i ( ) (2) READ(*,*) (a(i),i=1,n) READ(* *) n(3) READ(*,*) n DO i = 1, n READ(*,*) a(i) (3) 19 END DO
  • 132.
    Array Input/Output: 3/8ArrayInput/Output: 3/8 Suppose we wish to fill a(1), a(2) and a(3)pp ( ), ( ) ( ) with 10, 20 and 30. The input may be: 3 10 20 303 10 20 30 Each READ starts from a new line! OKREAD(*,*) n,(a(i),i=1,n) READ(* *) n (1) (2) OK Wrong! n gets 3 andREAD(*,*) n READ(*,*) (a(i),i=1,n) (2) Wrong! n gets 3 and the second READ fails READ(*,*) n DO i = 1, n (3) Wrong! n gets 3 and the three READs fail 20 READ(*,*) a(i) END DO
  • 133.
    Array Input/Output: 4/8ArrayInput/Output: 4/8 What if the input is changed to the following?What if the input is changed to the following? 3 10 20 30 OK 10 20 30 READ(*,*) n,(a(i),i=1,n) READ(* *) n (1) (2) OK OK. Why????READ(*,*) n READ(*,*) (a(i),i=1,n) (2) OK. Why???? READ(*,*) n DO i = 1, n (3) Wrong! n gets 3, a(1) has 10; but, the next two READs fail 21 READ(*,*) a(i) END DO READs fail
  • 134.
    Array Input/Output: 5/8ArrayInput/Output: 5/8 What if the input is changed to the following?What if the input is changed to the following? 3 10 20 OK 20 30 READ(*,*) n,(a(i),i=1,n) READ(* *) n (1) (2) OK OKREAD(*,*) n READ(*,*) (a(i),i=1,n) (2) OK READ(*,*) n DO i = 1, n (3) OK 22 READ(*,*) a(i) END DO
  • 135.
    Array Input/Output: 6/8ArrayInput/Output: 6/8 Suppose we have a two-dimensional array a():pp y () INTEGER, DIMENSION(2:4,0:1) :: a Suppose further the READ is the following:Suppose further the READ is the following: READ(*,*) ((a(i,j),j=0,1),i=2,4) What are the results for the following input? 1 2 3 1 2 3 4 5 6 1 2 3 4 5 6 7 8 9 0 1 0 1 1 2 3 4 1 2 3 4 2 3 2 3 0 1 0 1 23 3 4 5 6 3 4 5 64 4
  • 136.
    Array Input/Output: 7/8ArrayInput/Output: 7/8 Suppose we have a two-dimensional array a():pp y () INTEGER, DIMENSION(2:4,0:1) :: a DO i = 2 4DO i = 2, 4 READ(*,*) (a(i,j),j=0,1) END DOEND DO What are the results for the following input? 1 2 3 4 5 6 1 2 3 4 5 6 7 8 97 8 9 1 2 1 2A(2,0)=1 row-by-row2 0 1 0 1 24 ? ? ? ? 4 5 7 8 A(2,1)=2 then error! y 3 4
  • 137.
    Array Input/Output: 8/8ArrayInput/Output: 8/8 Suppose we have a two-dimensional array a():pp y () INTEGER, DIMENSION(2:4,0:1) :: a DO j = 0 1DO j = 0, 1 READ(*,*) (a(i,j),i=2,4) END DOEND DO What are the results for the following input? 1 2 3 4 5 6 1 2 3 4 5 6 7 8 97 8 9 1 ? 1 4 A(2,0)=1 A(3,0)=2 column-by-column2 0 1 0 1 25 2 ? 3 ? 2 5 3 6 A(4,0)=3 then error! y 3 4
  • 138.
    Matrix Multiplication: 1/2MatrixMultiplication: 1/2 Read a l m matrix Al m and a m n matrix Bm n,Read a l m matrix Al m and a m n matrix Bm n, and compute their product Cl n = Al m Bm n. PROGRAM Matrix MultiplicationPROGRAM Matrix_Multiplication IMPLICIT NONE INTEGER, PARAMETER :: SIZE = 100 INTEGER DIMENSION(1:SIZE 1:SIZE) :: A B CINTEGER, DIMENSION(1:SIZE,1:SIZE) :: A, B, C INTEGER :: L, M, N, i, j, k READ(*,*) L, M, N ! read sizes <= 100 iDO i = 1, L READ(*,*) (A(i,j), j=1,M) ! A() is L-by-M END DO DO i = 1, M READ(*,*) (B(i,j), j=1,N) ! B() is M-by-N END DO 26 …… other statements …… END PROGRAM Matrix_Multiplication
  • 139.
    Matrix Multiplication: 2/2MatrixMultiplication: 2/2 The following does multiplication and outputThe following does multiplication and output DO i = 1, L DO j = 1, N C(i,j) = 0 ! for each C(i,j) DO k = 1, M ! (row i of A)*(col j of B) C(i,j) = C(i,j) + A(i,k)*B(k,j) END DO END DOEND DO END DO DO i = 1 L ! print row-by-rowDO i = 1, L ! print row-by-row WRITE(*,*) (C(i,j), j=1, N) END DO 27
  • 140.
    Arrays as Arguments:1/4Arrays as Arguments: 1/4 Arrays may also be used as arguments passingy y g p g to functions and subroutines. Formal argument arrays may be declared asg y y usual; however, Fortran 90 recommends the use of assumed-shape arrays. An assumed-shape array has its lower bound in each extent specified; but, the upper bound is not used. formal arguments REAL, DIMENSION(-3:,1:), INTENT(IN) :: x, y INTEGER, DIMENSION(:), INTENT(OUT) :: a, b 28assumed-shape
  • 141.
    Arrays as Arguments:2/4Arrays as Arguments: 2/4 The extent in each dimension is an expressionThe extent in each dimension is an expression that uses constants or other non-array formal arguments with INTENT(IN) :g ( ) SUBROUTINE Test(x,y,z,w,l,m,n) I PLICIT NONE assumed-shape IMPLICIT NONE INTEGER, INTENT(IN) :: l, m, n REAL, DIMENSION(10:),INTENT(IN) :: x INTEGER, DIMENSION(-1:,m:), INTENT(OUT) :: y LOGICAL, DIMENSION(m,n:), INTENT(OUT) :: z REAL, DIMENSION(-5:5), INTENT(IN) :: w …… other statements …… END SUBROUTINE Test DIMENSION(1:m,n:) 29not assumed-shape
  • 142.
    Arrays as Arguments:3/4Arrays as Arguments: 3/4 Fortran 90 automatically passes an array and itsFortran 90 automatically passes an array and its shape to a formal argument. A subprogram receives the shape and uses theA subprogram receives the shape and uses the lower bound of each extent to recover the upper boundbound. INTEGER,DIMENSION(2:10)::Score …… CALL Funny(Score) shape is (9) SUBROUTINE Funny(x) IMPLICIT NONE INTEGER,DIMENSION(-1:),INTENT(IN) :: x 30 …… other statements …… END SUBROUTINE Funny (-1:7)
  • 143.
    Arrays as Arguments:4/4Arrays as Arguments: 4/4 One more exampleOne more example REAL, DIMENSION(1:3,1:4) :: x, ( , ) INTEGER :: p = 3, q = 2 CALL Fast(x,p,q) shape is (3,4) SUBROUTINE Fast(a,m,n)( , , ) IMPLICIT NONE INTEGER,INTENT(IN) :: m,n REAL DIMENSION(-m: n:) INTENT(IN)::aREAL,DIMENSION( m:,n:),INTENT(IN)::a …… other statements …… END SUBROUTINE Fast 31 (-m:,n:) becomes (-3:-1,2:5)
  • 144.
    The SIZE() IntrinsicFunction: 1/2The SIZE() Intrinsic Function: 1/2 How do I know the shape of an array?p y Use the SIZE() intrinsic function. SIZE() requires two arguments, an arraySIZE() requires two arguments, an array name and an INTEGER, and returns the size of the array in the given “dimension.”y g INTEGER,DIMENSION(-3:5,0:100):: a shape is (9,101) WRITE(*,*) SIZE(a,1), SIZE(a,2) CALL ArraySize(a) (1:9,5:105) SUBROUTINE ArraySize(x) INTEGER,DIMENSION(1:,5:),… :: x Both WRITE prints 9 and 101 32 WRITE(*,*) SIZE(x,1), SIZE(x,2) 9 and 101
  • 145.
    The SIZE() IntrinsicFunction : 2/2The SIZE() Intrinsic Function : 2/2 INTEGER,DIMENSION(-1:1,3:6):: Empty CALL Fill(Empty)CALL Fill(Empty) DO i = -1,1 WRITE(*,*) (Empty(i,j),j=3,6) END DO SUBROUTINE Fill(y) I PLICIT NONE END DO shape is (3,4) IMPLICIT NONE INTEGER,DIMENSION(1:,1:),INTENT(OUT)::y INTEGER :: U1, U2, i, j output U1 = SIZE(y,1) U2 = SIZE(y,2) DO i = 1, U1 2 3 4 5 3 4 5 6 4 5 6 7 output (1:3 1:4) DO j = 1, U2 y(i,j) = i + j END DO 4 5 6 7 (1:3,1:4) 33 END DO END DO END SUBROUTINE Fill
  • 146.
    Local Arrays: 1/2LocalArrays: 1/2 Fortran 90 permits to declare local arrays usingFortran 90 permits to declare local arrays using INTEGER formal arguments with the INTENT(IN) attribute.( ) SUBROUTINE Compute(X m n)INTEGER, & SUBROUTINE Compute(X, m, n) IMPLICIT NONE INTEGER,INTENT(IN) :: m, n INTEGER DIMENSION(1 1 ) & INTEGER, & DIMENSION(100,100) & ::a, z W(1:3) Y(1:3,1:15) INTEGER,DIMENSION(1:,1:), & INTENT(IN) :: X INTEGER,DIMENSION(1:m) :: W local arrays CALL Compute(a,3,5) CALL Compute(z,6,8) REAL,DIMENSION(1:m,1:m*n)::Y …… other statements …… END SUBROUTINE ComputeW(1:6) Y(1:6,1:48) 34 W(1:6) Y(1:6,1:48)
  • 147.
    Local Arrays: 2/2LocalArrays: 2/2 Just like you learned in C/C++ and Java, memory of local variables and local arrays in Fortran 90 is allocated before entering a subprogram and deallocated on return. Fortran 90 uses the formal arguments tog compute the extents of local arrays. Therefore, different calls with different valuesTherefore, different calls with different values of actual arguments produce different shape and extent for the same local array. However,and extent for the same local array. However, the rank of a local array will not change. 35
  • 148.
    The ALLOCATBLE AttributeTheALLOCATBLE Attribute In many situations, one does not know exactlyIn many situations, one does not know exactly the shape or extents of an array. As a result, one can only declare a “large enough” array.one can only declare a large enough array. The ALLOCATABLE attribute comes to rescue. The ALLOCATABLE attribute indicates that atThe ALLOCATABLE attribute indicates that at the declaration time one only knows the rank of b t t it t tan array but not its extent. Therefore, each extent has only a colon :. INTEGER,ALLOCATABLE,DIMENSION(:) :: a REAL,ALLOCATABLE,DIMENSION(:,:) :: b 36 LOGICAL,ALLOCATABLE,DIMENSION(:,:,:) :: c
  • 149.
    The ALLOCATE Statement:1/3The ALLOCATE Statement: 1/3 The ALLOCATE statement has the followingg syntax: ALLOCATE(array-1 array-n STAT=v)ALLOCATE(array-1,…,array-n,STAT=v) Here, array-1, …, array-n are array names with complete extents as in the DIMENSIONwith complete extents as in the DIMENSION attribute, and v is an INTEGER variable. Af i f if 0After the execution of ALLOCATE, if v 0, then at least one arrays did not get memory. REAL,ALLOCATABLE,DIMENSION(:) :: a LOGICAL,ALLOCATABLE,DIMENSION(:,:) :: x 37 INTEGER :: status ALLOCATE(a(3:5), x(-10:10,1:8), STAT=status)
  • 150.
    The ALLOCATE Statement:2/3The ALLOCATE Statement: 2/3 ALLOCATE only allocates arrays with they y ALLOCATABLE attribute. The extents in ALLOCATE can use INTEGERThe extents in ALLOCATE can use INTEGER expressions. Make sure all involved variables have been initialized properlyhave been initialized properly. INTEGER,ALLOCATABLE,DIMENSION(:,:) :: x INTEGER,ALLOCATABLE,DIMENSION(:) :: aINTEGER,ALLOCATABLE,DIMENSION(:) :: a INTEGER :: m, n, p READ(*,*) m, n ALLOCATE(x(1:m m+n:m*n) a(-(m*n):m*n) STAT=p)ALLOCATE(x(1:m,m+n:m*n),a(-(m*n):m*n),STAT=p) IF (p /= 0) THEN …… report error here …… 38 If m = 3 and n = 5, then we have x(1:3,8:15) and a(-15:15)
  • 151.
    The ALLOCATE Statement:3/3The ALLOCATE Statement: 3/3 ALLOCATE can be used in subprograms.p g Formal arrays are not ALLOCATABLE. I l ll t d i bIn general, an array allocated in a subprogram is a local entity, and is automatically d ll t d h th b tdeallocated when the subprogram returns. Watch for the following odd use: PROGRAM Try_not_to_do_this IMPLICIT NONE REAL,ALLOCATABLE,DIMENSION(:) :: x CONTAINS SUBROUTINE Hey(…) ALLOCATE(x(1:10)) 39 ALLOCATE(x(1:10)) END SUBROUTINE Hey END PROGRAM Try_not_to_do_this
  • 152.
    The DEALLOCATE StatementTheDEALLOCATE Statement Allocated arrays may be deallocated by theAllocated arrays may be deallocated by the DEALLOCATE() statement as shown below: DEALLOCATE(array-1 array-n STAT=v)DEALLOCATE(array-1,…,array-n,STAT=v) Here, array-1, …, array-n are the names of allocated arrays and is an INTEGER variableallocated arrays, and v is an INTEGER variable. If deallocation fails (e.g., some arrays were not ) i iallocated), the value in v is non-zero. After deallocation of an array, it is not available and any access will cause a program error. DEALLOCATE(a b c STAT=status) 40 DEALLOCATE(a, b, c, STAT=status)
  • 153.
    The ALLOCATED IntrinsicFunctionThe ALLOCATED Intrinsic Function The ALLOCATED(a) function returns .TRUE.( ) if ALLOCATABLE array a has been allocated. Otherwise, it returns .FALSE., INTEGER,ALLOCATABLE,DIMENSION(:) :: Mat INTEGER :: status ALLOCATE(Mat(1:100),STAT=status) …… ALLOCATED(Mat) returns .TRUE. ….. …… other statements …… DEALLOCATE(Mat,STAT=status)DEALLOCATE(Mat,STAT status) …… ALLOCATED(Mat) returns .FALSE. …… 41
  • 154.
    Fortran 90 SubprogramsFortran90 Subprograms If Fortran is the lingua franca, then certainly it must be true that BASIC is the lingua playpen 1 Thomas E. Kurtz Co-Designer of the BASIC language Fall 2010
  • 155.
    Functions and SubroutinesFunctionsand Subroutines Fortran 90 has two types of subprograms,Fortran 90 has two types of subprograms, functions and subroutines. A Fortran 90 function is a function like those inA Fortran 90 function is a function like those in C/C++. Thus, a function returns a computed result via the function nameresult via the function name. If a function does not have to return a function l b tivalue, use subroutine. 2
  • 156.
    Function Syntax: 1/3FunctionSyntax: 1/3 A Fortran function, or function subprogram,, p g , has the following syntax: type FUNCTION function-name (arg1, arg2, ..., argn) IMPLICIT NONE [specification part] [execution part]p [subprogram part] END FUNCTION function-name type is a Fortran 90 type (e g INTEGERtype is a Fortran 90 type (e.g., INTEGER, REAL, LOGICAL, etc) with or without KIND. function name is a Fortran 90 identifierfunction-name is a Fortran 90 identifier arg1, …, argn are formal arguments. 3
  • 157.
    Function Syntax: 2/3FunctionSyntax: 2/3 A function is a self-contained unit that receives some “input” from the outside world via its formal arguments, does some computations, and returns the result with the name of the function. Somewhere in a function there has to be one or more assignment statements like this: function-name = expression where the result of expression is saved to the name of the function. Note that function-name cannot appear in the right-hand side of any expression. 4
  • 158.
    Function Syntax: 3/3FunctionSyntax: 3/3 In a type specification, formal argumentsyp p , g should have a new attribute INTENT(IN). The meaning of INTENT(IN) is that theg function only takes the value from a formal argument and does not change its content. Any statements that can be used in PROGRAM can also be used in a FUNCTION. 5
  • 159.
    Function ExampleFunction Example Notethat functions can have no formal argument.Note that functions can have no formal argument. But, () is still required. INTEGER FUNCTION Factorial(n) IMPLICIT NONE REAL FUNCTION GetNumber() IMPLICIT NONE Factorial computation Read and return a positive real number IMPLICIT NONE INTEGER, INTENT(IN) :: n INTEGER :: i, Ans IMPLICIT NONE REAL :: Input_Value DO WRITE(*,*) 'A positive number: ' Ans = 1 DO i = 1, n Ans = Ans * i END DO ( , ) p READ(*,*) Input_Value IF (Input_Value > 0.0) EXIT WRITE(*,*) 'ERROR. try again.' END DOEND DO Factorial = Ans END FUNCTION Factorial END DO GetNumber = Input_Value END FUNCTION GetNumber 6
  • 160.
    Common Problems: 1/2CommonProblems: 1/2 forget function type forget INTENT(IN) not an error FUNCTION DoSomething(a, b) IMPLICIT NONE INTEGER, INTENT(IN) :: a, b REAL FUNCTION DoSomething(a, b) IMPLICIT NONE INTEGER :: a, b g yp g DoSomthing = SQRT(a*a + b*b) END FUNCTION DoSomething DoSomthing = SQRT(a*a + b*b) END FUNCTION DoSomething REAL FUNCTION DoSomething(a, b) IMPLICIT NONE REAL FUNCTION DoSomething(a, b) IMPLICIT NONE change INTENT(IN) argument forget to return a value INTEGER, INTENT(IN) :: a, b IF (a > b) THEN a = a - b ELSE INTEGER, INTENT(IN) :: a, b INTEGER :: c c = SQRT(a*a + b*b) END FUNCTION DoSomethingELSE a = a + b END IF DoSomthing = SQRT(a*a+b*b) END FUNCTION DoSomething 7 END FUNCTION DoSomething
  • 161.
    Common Problems: 2/2CommonProblems: 2/2 REAL FUNCTION DoSomething(a, b) IMPLICIT NONE REAL FUNCTION DoSomething(a, b) IMPLICIT NONE incorrect use of function name only the most recent value is returned IMPLICIT NONE INTEGER, INTENT(IN) :: a, b DoSomething = a*a + b*b DoSomething = SQRT(DoSomething) IMPLICIT NONE INTEGER, INTENT(IN) :: a, b DoSomething = a*a + b*b DoSomething = SQRT(a*a - b*b) END FUNCTION DoSomething END FUNCTION DoSomething 8
  • 162.
    Using FunctionsUsing Functions Theuse of a user-defined function is similar toThe use of a user defined function is similar to the use of a Fortran 90 intrinsic function. The following uses function Factorial(n) toThe following uses function Factorial(n) to compute the combinatorial coefficient C(m,n) , where m and n are actual arguments:where m and n are actual arguments: Cmn = Factorial(m)/(Factorial(n)*Factorial(m-n)) Note that the combinatorial coefficient is defined as follows, although it is not the most efficient way: C m n m ( ) ! 9 C m n n m n ( , ) ! ( )!
  • 163.
    Argument Association :1/5Argument Association : 1/5 Argument association is a way of passing valuesArgument association is a way of passing values from actual arguments to formal arguments. If an actual argument is an expression it isIf an actual argument is an expression, it is evaluated and stored in a temporary location from which the value is passed to thefrom which the value is passed to the corresponding formal argument. If t l t i i bl it l iIf an actual argument is a variable, its value is passed to the corresponding formal argument. C d h i i blConstant and (A), where A is variable, are considered expressions. 10
  • 164.
    Argument Association :2/5Argument Association : 2/5 Actual arguments are variables:Actual arguments are variables: a b cWRITE(*,*) Sum(a,b,c) x y z INTEGER FUNCTION Sum(x,y,z) IMPLICIT NONE INTEGER INTENT(IN)::x y z x y zINTEGER,INTENT(IN)::x,y,z …….. END FUNCTION Sum 11
  • 165.
    Argument Association :3/5Argument Association : 3/5 Expressions as actual arguments. Dashed lineExpressions as actual arguments. Dashed line boxes are temporary locations. a+b b+c cWRITE(*,*) Sum(a+b,b+c,c) x y z INTEGER FUNCTION Sum(x,y,z) IMPLICIT NONE INTEGER INTENT(IN)::x y z x y zINTEGER,INTENT(IN)::x,y,z …….. END FUNCTION Sum 12
  • 166.
    Argument Association :4/5Argument Association : 4/5 Constants as actual arguments. Dashed lineConstants as actual arguments. Dashed line boxes are temporary locations. 1 2 3WRITE(*,*) Sum(1, 2, 3) x y z INTEGER FUNCTION Sum(x,y,z) IMPLICIT NONE INTEGER INTENT(IN)::x y z x y zINTEGER,INTENT(IN)::x,y,z …….. END FUNCTION Sum 13
  • 167.
    Argument Association :5/5Argument Association : 5/5 A variable in () is considered as an expression.() p Dashed line boxes are temporary locations. (a) (b) (c)WRITE(*,*) Sum((a), (b), (c)) x y z INTEGER FUNCTION Sum(x,y,z) IMPLICIT NONE INTEGER INTENT(IN)::x y z x y zINTEGER,INTENT(IN)::x,y,z …….. END FUNCTION Sum 14
  • 168.
    Where Do FunctionsGo: 1/2Where Do Functions Go: 1/2 Fortran 90 functions can be internal or external.Fortran 90 functions can be internal or external. Internal functions are inside of a PROGRAM, the main program:main program: PROGRAM program-name IMPLICIT NONEC NON [specification part] [execution part] CONTAINSCONTAINS [functions] END PROGRAM program-name Although a function can contain other functions, i t l f ti t h i t l f ti 15 internal functions cannot have internal functions.
  • 169.
    Where Do FunctionsGo: 2/2Where Do Functions Go: 2/2 The right shows PROGRAM TwoFunctionsg two internal functions, PROGRAM TwoFunctions IMPLICIT NONE REAL :: a, b, A_Mean, G_Mean READ(*,*) a, b ArithMean() and GeoMean(). A_Mean = ArithMean(a, b) G_Mean = GeoMean(a,b) WRITE(*,*) a, b, A_Mean, G_Mean CONTAINS They take two REAL actual t d CONTAINS REAL FUNCTION ArithMean(a, b) IMPLICIT NONE REAL, INTENT(IN) :: a, b arguments and compute and return a REAL ArithMean = (a+b)/2.0 END FUNCTION ArithMean REAL FUNCTION GeoMean(a, b) IMPLICIT NONEreturn a REAL function value. IMPLICIT NONE REAL, INTENT(IN) :: a, b GeoMean = SQRT(a*b) END FUNCTION GeoMean 16 END PROGRAM TwoFunctions
  • 170.
    Scope Rules: 1/5ScopeRules: 1/5 Scope rules tell us if an entity (i.e., variable,Scope rules tell us if an entity (i.e., variable, parameter and function) is visible or accessible at certain places.at certain places. Places where an entity can be accessed or visible is referred as the scope of that entityis referred as the scope of that entity. 17
  • 171.
    Scope Rules: 2/5ScopeRules: 2/5 Scope Rule #1: The scope of an entity is the program or function in which it is declared. PROGRAM Scope_1 Scope of PI, m and n IMPLICIT NONE REAL, PARAMETER :: PI = 3.1415926 INTEGER :: m, n ................... CONTAINS INTEGER FUNCTION Funct1(k) IMPLICIT NONE Scope of k, f and g local to Funct1() INTEGER, INTENT(IN) :: k REAL :: f, g .......... END FUNCTION Funct1END FUNCTION Funct1 REAL FUNCTION Funct2(u, v) IMPLICIT NONE REAL, INTENT(IN) :: u, v Scope of u and v local to Funct2() 18 .......... END FUNCTION Funct2 END PROGRAM Scope_1
  • 172.
    Scope Rules: 3/5ScopeRules: 3/5 Scope Rule #2 :A global entity is visible to allp contained functions. PROGRAM Scope_2 IMPLICIT NONE INTEGER :: a = 1, b = 2, c = 3 WRITE(*,*) Add(a) a, b and c are global The first Add(a) returns 4 Th d dd tc = 4 WRITE(*,*) Add(a) WRITE(*,*) Mul(b,c) CONTAINS The second Add(a) returns 5 Mul(b,c) returns 8 INTEGER FUNCTION Add(q) IMPLICIT NONE INTEGER, INTENT(IN) :: q Add = q + c Thus, the two Add(a)’s produce different results, even though the formal arguments are the same! This is usually referred toEND FUNCTION Add INTEGER FUNCTION Mul(x, y) IMPLICIT NONE INTEGER, INTENT(IN) :: x, y are the same! This is usually referred to as side effect. Avoid using global entities! 19 Mul = x * y END FUNCTION Mul END PROGRAM Scope_2 Avoid using global entities!
  • 173.
    Scope Rules: 4/5ScopeRules: 4/5 Scope Rule #2 :A global entity is visible to allp contained functions. PROGRAM Global IMPLICIT NONE INTEGER :: a = 10, b = 20 The first Add(a,b) returns 30 It also changes b to 30 Th 2 d WRITE(* *) h 30 INTEGER :: a 10, b 20 WRITE(*,*) Add(a,b) WRITE(*,*) b WRITE(*,*) Add(a,b) The 2nd WRITE(*,*) shows 30 The 2nd Add(a,b) returns 40 This is a bad side effect CONTAINS INTEGER FUNCTION Add(x,y) IMPLICIT NONE Avoid using global entities! INTEGER, INTENT(IN)::x, y b = x+y Add = b 20 END FUNCTION Add END PROGRAM Global
  • 174.
    Scope Rules: 5/5ScopeRules: 5/5 Scope Rule #3 :An entity declared in the scope of th tit i l diff t ifanother entity is always a different one even if their names are identical. PROGRAM Scope_3 IMPLICIT NONE INTEGER :: i, Max = 5 DO i 1 Max Although PROGRAM and FUNCTION Sum() both have INTEGER variable i, They are TWO different entities. DO i = 1, Max Write(*,*) Sum(i) END DO CONTAINS y Hence, any changes to i in Sum() will not affect the i in PROGRAM. INTEGER FUNCTION Sum(n) IMPLICIT NONE INTEGER, INTENT(IN) :: n INTEGER :: i sINTEGER :: i, s s = 0 …… other computation …… Sum = s 21 END FUNCTION Sum END PROGRAM Scope_3
  • 175.
    Example: 1/4Example: 1/4 Ifa triangle has side lengths a, b and c, the HeronIf a triangle has side lengths a, b and c, the Heron formula computes the triangle area as follows, where s = (a+b+c)/2:where s (a b c)/2: Area s s a s b s c( ) ( ) ( ) To form a triangle, a, b and c must fulfill the following two conditions: a > 0, b > 0 and c > 0 a+b > c, a+c > b and b+c > a 22
  • 176.
    Example: 2/4Example: 2/4 LOGICALFunction TriangleTest() makesg () sure all sides are positive, and the sum of any two is larger than the third.two is larger than the third. LOGICAL FUNCTION TriangleTest(a, b, c)LOGICAL FUNCTION TriangleTest(a, b, c) IMPLICIT NONE REAL, INTENT(IN) :: a, b, c LOGICAL :: test1, test2OG C :: test , test test1 = (a > 0.0) .AND. (b > 0.0) .AND. (c > 0.0) test2 = (a + b > c) .AND. (a + c > b) .AND. (b + c > a) TriangleTest = test1 .AND. test2 ! both must be .TRUE. END FUNCTION TriangleTest 23
  • 177.
    Example: 3/4Example: 3/4 Thisfunction implements the Heron formula.This function implements the Heron formula. Note that a, b and c must form a triangle. REAL FUNCTION Area(a, b, c) IMPLICIT NONE REAL, INTENT(IN) :: a, b, c REAL :: s s = (a + b + c) / 2.0 A SQRT( *( )*( b)*( ))Area = SQRT(s*(s-a)*(s-b)*(s-c)) END FUNCTION Area 24
  • 178.
    Example: 4/4Example: 4/4 Hereis the main program! PROGRAM HeronFormula IMPLICIT NONE REAL :: a, b, c, TriangleArea DODO WRITE(*,*) 'Three sides of a triangle please --> ' READ(*,*) a, b, c WRITE(*,*) 'Input sides are ', a, b, c IF (TriangleTest(a, b, c)) EXIT ! exit if they form a triangle WRITE(*,*) 'Your input CANNOT form a triangle. Try again' END DO TriangleArea = Area(a b c)TriangleArea = Area(a, b, c) WRITE(*,*) 'Triangle area is ', TriangleArea CONTAINS LOGICAL FUNCTION TriangleTest(a, b, c) …… END FUNCTION TriangleTest REAL FUNCTION Area(a, b, c) 25 …… END FUNCTION Area END PROGRAM HeronFormula
  • 179.
    Subroutines: 1/2Subroutines: 1/2 AFortran 90 function takes values from itsA Fortran 90 function takes values from its formal arguments, and returns a single value with the function name.with the function name. A Fortran 90 subroutine takes values from its formal arguments and returns some computedformal arguments, and returns some computed results with its formal arguments. A F t 90 b ti d t tA Fortran 90 subroutine does not return any value with its name. 26
  • 180.
    Subroutines: 2/2Subroutines: 2/2 Thefollowing is Fortran 90 subroutine syntax:The following is Fortran 90 subroutine syntax: SUBROUTINE subroutine-name(arg1,arg2,...,argn) IMPLICIT NONE [specification part] [ ti t][execution part] [subprogram part] END SUBROUTINE subroutine-nameEND SUBROUTINE subroutine name If a subroutine does not require any formal arguments “arg1 arg2 argn” can be removed;arguments, arg1,arg2,...,argn can be removed; however, () must be there. S b ti i il t f ti 27 Subroutines are similar to functions.
  • 181.
    The INTENT() Attribute:1/2The INTENT() Attribute: 1/2 Since subroutines use formal arguments toSince subroutines use formal arguments to receive values and to pass results back, in addition to INTENT(IN), there are( ), INTENT(OUT) and INTENT(INOUT). INTENT(OUT) means a formal argument doesINTENT(OUT) means a formal argument does not receive a value; but, it will return a value to its corresponding actual argumentits corresponding actual argument. INTENT(INOUT) means a formal argument i l f d t l t itreceives a value from and returns a value to its corresponding actual argument. 28
  • 182.
    The INTENT() Attribute:2/2The INTENT() Attribute: 2/2 Two simple examples:Two simple examples: SUBROUTINE Means(a, b, c, Am, Gm, Hm) IMPLICIT NONE Am, Gm and Hm are used to return the results REAL, INTENT(IN) :: a, b, c REAL, INTENT(OUT) :: Am, Gm, Hm Am = (a+b+c)/3.0 Gm = (a*b*c)**(1 0/3 0)Gm = (a*b*c)**(1.0/3.0) Hm = 3.0/(1.0/a + 1.0/b + 1.0/c) END SUBROUTINE Means values of a and b are swapped SUBROUTINE Swap(a, b) IMPLICIT NONE INTEGER, INTENT(INOUT) :: a, b INTEGER :: cINTEGER :: c c = a a = b b = c 29 END SUBROUTINE Swap
  • 183.
    The CALL Statement:1/2The CALL Statement: 1/2 Unlike C/C++ and Java, to use a Fortran 90Unlike C/C and Java, to use a Fortran 90 subroutine, the CALL statement is needed. The CALL statement may have one of the threeThe CALL statement may have one of the three forms: CALL sub name(arg1 arg2 argn)CALL sub-name(arg1,arg2,…,argn) CALL sub-name( ) CALL sub-name The last two forms are equivalent and are forThe last two forms are equivalent and are for calling a subroutine without formal arguments. 30
  • 184.
    The CALL Statement:2/2The CALL Statement: 2/2 PROGRAM Test PROGRAM SecondDegreePROGRAM Test IMPLICIT NONE REAL :: a, b READ(*,*) a, b PROGRAM SecondDegree IMPLICIT NONE REAL :: a, b, c, r1, r2 LOGICAL :: OK CALL Swap(a,b) WRITE(*,*) a, b CONTAINS SUBROUTINE Swap(x y) READ(*,*) a, b, c CALL Solver(a,b,c,r1,r2,OK) IF (.NOT. OK) THEN WRITE(* *) “No root”SUBROUTINE Swap(x,y) IMPLICIT NONE REAL, INTENT(INOUT) :: x,y REAL :: z WRITE(*,*) “No root” ELSE WRITE(*,*) a, b, c, r1, r2 END IF z = x x = y y = z END SUBROUTINE Swap CONTAINS SUBROUTINE Solver(a,b,c,x,y,L) IMPLICIT NONE REAL INTENT(IN) :: a b cEND SUBROUTINE Swap END PROGRAM Test REAL, INTENT(IN) :: a,b,c REAL, INTENT(OUT) :: x, y LOGICAL, INTENT(OUT) :: L ……… 31 END SUBROUTINE Solver END PROGRAM SecondDegree
  • 185.
    More Argument Association:1/2More Argument Association: 1/2 Since a formal argument with the INTENT(OUT)g ( ) or INTENT(INOUT) attribute will pass a value back to the corresponding actual argument, theback to the corresponding actual argument, the actual argument must be a variable. PROGRAM Errors SUBROUTINE Sub(u,v,w,p,q) IMPLICIT NONE IMPLICIT NONE INTEGER :: a, b, c INTEGER, INTENT(OUT) :: uINTEGER :: a, b, c INTEGER, INTENT(OUT) :: u .......... INTEGER, INTENT(INOUT) :: v CALL Sub(1,a,b+c,(c),1+a) INTEGER, INTENT(IN) :: w .......... INTEGER, INTENT(OUT) :: p, p END PROGRAM Errors INTEGER, INTENT(IN) :: q .......... END SUBROUTINE Sub 32these two are incorrect!
  • 186.
    More Argument Association:2/2More Argument Association: 2/2 The number of arguments and their types mustThe number of arguments and their types must match properly. There is no type-conversion between arguments!There is no type-conversion between arguments! PROGRAM Error SUBROUTINE ABC(p, q) IMPLICIT NONE IMPLICIT NONE INTEGER :: a, b INTEGER, INTENT(IN) :: pINTEGER :: a, b INTEGER, INTENT(IN) :: p CALL ABC(a, b) REAL, INTENT(OUT) :: q CALL ABC(a) ……… CONTAINS END SUBROUTINE ABC type mismatch wrong # of arguments ……… END PROGRAM Error g g 33
  • 187.
    Fortran 90 Modules:1/4Fortran 90 Modules: 1/4 One may collect all relevant functions andOne may collect all relevant functions and subroutines together into a module. A module in OO’s language is perhaps close toA module, in OO s language, is perhaps close to a static class that has public/private information and methodsand methods. So, in some sense, Fortran 90’s module provides t f bj t b d th th bj ta sort of object-based rather than object- oriented programming paradigm. 34
  • 188.
    Fortran 90 Modules:2/4Fortran 90 Modules: 2/4 A Fortran 90 module has the following syntax:A Fortran 90 module has the following syntax: MODULE module-name IMPLICIT NONE [specification part] CONTAINS [internal functions/subroutines][ / ] END MODULE module-name The specification part and internal functions andp p subroutines are optional. A module looks like a PROGRAM, except that itA module looks like a PROGRAM, except that it does not have the executable part. Hence, a main program must be there to use modules. 35 main program must be there to use modules.
  • 189.
    Fortran 90 Modules:3/4Fortran 90 Modules: 3/4 Examples:Examples: Module SomeConstants does not have the subprogram part Module SumAverage does not have the specification part MODULE SomeConstants IMPLICIT NONE REAL, PARAMETER :: PI=3.1415926 REAL PARAMETER 980 MODULE SumAverage CONTAINS REAL FUNCTION S ( b c) p g p p p REAL, PARAMETER :: g = 980 INTEGER :: Counter END MODULE SomeConstants REAL FUNCTION Sum(a, b, c) IMPLICIT NONE REAL, INTENT(IN) :: a, b, c Sum = a + b + c END FUNCTION Sum REAL FUNCTION Average(a, b, c) IMPLICIT NONE REAL INTENT(IN) :: a b cREAL, INTENT(IN) :: a, b, c Average = Sum(a,b,c)/2.0 END FUNCTION Average END MODULE SumAverage 36
  • 190.
    Fortran 90 Modules:4/4Fortran 90 Modules: 4/4 The right module MODULE DegreeRadianConversiong has both the specification d IMPLICIT NONE REAL, PARAMETER :: PI = 3.1415926 REAL, PARAMETER :: Degree180 = 180.0 part and internal functions CONTAINS REAL FUNCTION DegreeToRadian(Degree) IMPLICIT NONE functions. Normally, this is the case. REAL, INTENT(IN) :: Degree DegreeToRadian = Degree*PI/Degree180 END FUNCTION DegreeToRadian REAL FUNCTION RadianToDegree(radian)the case. REAL FUNCTION RadianToDegree(radian) IMPLICIT NONE REAL, INTENT(IN) :: Radian RadianToDegree = Radian*Degree180/PI END FUNCTION RadianToDegree END MODULE DegreeRadianConversion 37
  • 191.
    Some Privacy: 1/2SomePrivacy: 1/2 Fortran 90 allows a module to have private andp public items. However, all global entities of a module, by default, are public (i.e., visible in all other programs and modules)other programs and modules). To specify public and private, do the following: PUBLIC :: name 1 name 2 name nPUBLIC :: name-1, name-2, …, name-n PRIVATE :: name-1, name-2, …, name-n The PRIVATE statement without a name makes all entities in a module private. To make some entities visible, use PUBLIC. d l b d iPUBLIC and PRIVATE may also be used in type specification: 38 INTEGER, PRIVATE :: Sum, Phone_Number
  • 192.
    Some Privacy: 2/2SomePrivacy: 2/2 Any global entity MODULE TheForcey g y (e.g., PARAMETER, variable, function, i MODULE TheForce IMPLICIT NONE INTEGER :: SkyWalker, Princess REAL, PRIVATE :: BlackKnight Is this public? subroutine, etc) can be in PUBLIC or PRIVATE LOGICAL :: DeathStar REAL, PARAMETER :: SecretConstant = 0.123456 PUBLIC :: SkyWalker, Princess PRIVATE :: VolumeOfDeathStaror PRIVATE statements. PRIVATE :: VolumeOfDeathStar PRIVATE :: SecretConstant CONTAINS INTEGER FUNCTION VolumeOfDeathStar() .......... END FUNCTION WolumeOfDeathStar REAL FUNCTION WeaponPower(SomeWeapon) .......... END FUNCTION .......... END MODULE TheForce 39 By default, this PUBLIC statement does not make much sense
  • 193.
    Using a Module:1/5Using a Module: 1/5 A PROGRAM or MODULE can use PUBLIC entities in any other modules. However, one must declare this intention (of use). There are two forms of the USE statement for this task: USE module-name USE module-name, ONLY: name-1, name-2, ..., name-n The first USE indicates all PUBLIC entities of MODULE module-name will be used. The second makes use only the names listed after the ONLY keyword. 40
  • 194.
    Using a Module:2/5Using a Module: 2/5 Two simple examples:p p MODULE SomeConstants PROGRAM Main USE SomeConstants IMPLICIT NONEMODULE SomeConstants IMPLICIT NONE REAL, PARAMETER :: PI = 3.1415926 REAL, PARAMETER :: g = 980 .......... END PROGRAM Main , g INTEGER :: Counter END MODULE SomeConstants MODULE DoSomething USE SomeConstants, ONLY : g, Counter IMPLICIT NONE PI is not available CONTAINS SUBROUTINE Something(…) …… END SUBROUTINE S thi 41 END SUBROUTINE Something END MODULE DoSomething
  • 195.
    Using a Module:3/5Using a Module: 3/5 Sometimes, the “imported” entities from aSometimes, the imported entities from a MODULE may have identical names with names in the “importing” PROGRAM or MODULE.p g If this happens, one may use the “renaming” feature of USEfeature of USE. For each identifier in USE to be renamed, use the f ll i tfollowing syntax: name-in-this-PROGRAM => name-in-module In this program, the use of name-in-this- PROGRAM is equivalent to the use of name-in- 42 module in the “imported” MODULE.
  • 196.
    Using a Module:4/5Using a Module: 4/5 The following uses module MyModule.g y Identifiers Counter and Test in module MyModule are renamed as MyCounter andMyModule are renamed as MyCounter and MyTest in this module, respectively: USE MyModule, MyCounter => Counter &USE MyModule, MyCounter => Counter & MyTest => Test The following only uses identifiers Ans,The following only uses identifiers Ans, Condition and X from module Package with Condition renamed as Status:Condition renamed as Status: USE Package, ONLY : Ans, Status => Condition, X 43
  • 197.
    Using a Module:5/5Using a Module: 5/5 Two USE and => examples GravityG is the g in the module;S p MODULE SomeConstants PROGRAM Test USE SomeConstants, & however, g is the “g” in Test MODULE SomeConstants IMPLICIT NONE REAL, PARAMETER :: PI = 3.1415926 REAL, PARAMETER :: g = 980 USE SomeConstants, & GravityG => g IMPLICIT NONE INTEGER :: g, g INTEGER :: Counter END MODULE SomeConstants g …… END PROGRAM Test MODULE Compute USE SomeConstants, ONLY : PI, g IMPLICIT NONE REAL :: Counter CONTAINS without ONLY, Counter would appear in MODULE Compute causing a name conflict! 44 …… END MODULE Compute causing a name conflict!
  • 198.
    Compile Your Program:1/4Compile Your Program: 1/4 Suppose a program consists of the mainSuppose a program consists of the main program main.f90 and 2 modules Test.f90 and Compute.f90. In general, they can bep g , y compiled in the following way: f90 main.f90 Test.f90 Compute.f90 –o mainf90 main.f90 Test.f90 Compute.f90 o main However, some compilers may be a little more restrictive List those modules that do not use anyrestrictive. List those modules that do not use any other modules first, followed by those modules that only use those listed modules followed by youronly use those listed modules, followed by your main program. 45
  • 199.
    Compile Your Program:2/4Compile Your Program: 2/4 Suppose we have modules A, B, C, D and E, and Cpp , , , , uses A, D uses B, and E uses A, C and D, then a safest way to compile your program is thesafest way to compile your program is the following command: f90 A.f90 B.f90 C.f90 D.f90 E.f90 main.f90 –o main Since modules are supposed to be designed and developed separately, they can also be compileddeveloped separately, they can also be compiled separately to object codes: f90 c test f90f90 –c test.f90 The above compiles a module/program in file t t f90 t it bj t d t t 46 test.f90 to its object code test.o This means compile only
  • 200.
    Compile Your Program:3/4Compile Your Program: 3/4 Suppose we have modules A, B, C, D and E, and Cpp uses A, D uses B, and E uses A, C and D. Since modules are developed separately with ifi f ti lit i i dsome specific functionality in mind, one may compile each module to object code as follows: f90 –c A.f90f90 c A.f90 f90 –c B.f90 f90 –c C.f90 If your compiler is picky, some modules may have to compiled together! f90 –c D.f90 f90 –c E.f90 N t th t th d i till i t t Th b may have to compiled together! Note that the order is still important. The above generates object files A.o, B.o, C.o, D.o and E.o 47 and E.o
  • 201.
    Compile Your Program:4/4Compile Your Program: 4/4 If a main program in file prog2.f90 usesp g p g modules in A.f90 and B.f90, one may compile and generate executable code for prog2 asg p g follows: f90 A.o B.o prog2.f90 –o prog2f90 A.o B.o prog2.f90 o prog2 If prog2.f90 uses module E.f90 only, the following must be used since E f90 uses A f90following must be used since E.f90 uses A.f90, C.f90 and D.f90: f90 A o C o D o E o prog2 f90 o prog2f90 A.o C.o D.o E.o prog2.f90 –o prog2 Note the order of the object files. 48
  • 202.
    Example 1Example 1 Thecombinatorial coefficient of m and n (m n) isThe combinatorial coefficient of m and n (m n) is Cm,n = m!/(n! (m-n)!). MODULE FactorialModule IMPLICIT NONE CONTAINS i l( ) PROGRAM ComputeFactorial USE FactorialModule IMPLICIT NONE INTEGER N RINTEGER FUNCTION Factorial(n) IMPLICIT NONE INTEGER, INTENT(IN) :: n … other statements … INTEGER :: N, R READ(*,*) N, R WRITE(*,*) Factorial(N) WRITE(*,*) Combinatorial(N,R)… ot e state e ts … END FUNCTION Factorial INTEGER FUNCTION Combinatorial(n, r) IMPLICIT NONE G ( ) END PROGRAM ComputeFactorial INTEGER, INTENT(IN) :: n, r … other statements … END FUNCTION Combinatorial END MODULE FactorialModule Combinatorial(n,r) uses Factorial(n) 49
  • 203.
    Example 2Example 2 Trigonometricfunctions use degree.Trigonometric functions use degree. MODULE MyTrigonometricFunctions IMPLICIT NONE PROGRAM TrigonFunctTest USE MyTrigonometricFunctions REAL, PARAMETER :: PI = 3.1415926 REAL, PARAMETER :: Degree180 = 180.0 REAL, PARAMETER :: R_to_D=Degree180/PI REAL, PARAMETER :: D to R=PI/Degree180 IMPLICIT NONE REAL :: Begin = -180.0 REAL :: Final = 180.0 REAL :: Step = 10.0REAL, PARAMETER :: D_to_R PI/Degree180 CONTAINS REAL FUNCTION DegreeToRadian(Degree) IMPLICIT NONE ( ) REAL :: Step 10.0 REAL :: x x = Begin DO ( i l)REAL, INTENT(IN) :: Degree DegreeToRadian = Degree * D_to_R END FUNCTION DegreeToRadian REAL FUNCTION MySIN(x) IF (x > Final) EXIT WRITE(*,*) MySIN(x) x = x + Step END DOyS ( ) IMPLICIT NONE REAL, INTENT(IN) :: x MySIN = SIN(DegreeToRadian(x)) END FUNCTION SIN END PROGRAM TrigonFunctTest 50 END FUNCTION MySIN … other functions … END MODULE MyTrigonometricFunctions
  • 204.
    INTERFACE Blocks: 1/5INTERFACEBlocks: 1/5 Legacy Fortran programs do not have internalLegacy Fortran programs do not have internal subprograms in PROGRAMs or MODULEs. These subprograms are in separate files TheseThese subprograms are in separate files. These are external subprograms that may cause some compilation problems in Fortran 90compilation problems in Fortran 90. Therefore, Fortran 90 has the INTERFACE block f d l t k th t ffor a program or a module to know the type of the subprograms, the intent and type of each t targument, etc. 51
  • 205.
    INTERFACE Blocks: 2/5INTERFACEBlocks: 2/5 Consider the following triangle area program.Consider the following triangle area program. How does the main program know the type and number of arguments of the two functions?number of arguments of the two functions? LOGICAL FUNCTION Test(a, b, c) IMPLICIT NONE PROGRAM HeronFormula IMPLICIT NONE REAL, INTENT(IN) :: a, b, c LOGICAL :: test1, test2 test1 = (a>0.0) .AND. (b>0.0) .AND. (c>0.0) test2 = (a+b>c) .AND. (a+c>b) .AND. (b+c>a) … some important here … REAL :: a, b, c REAL :: TriangleArea DO Test = test1 .AND. test2 END FUNCTION Test REAL FUNCTION Area(a, b, c) READ(*,*) a, b, c IF (Test(a,b,c)) EXIT END DO TriangleArea = Area(a, b, c) IMPLICIT NONE REAL, INTENT(IN) :: a, b, c REAL :: s = (a + b + c) / 2.0 Area = SQRT(s*(s-a)*(s-b)*(s-c)) g WRITE(*,*) TriangleArea END PROGRAM HeronFormula 52 END FUNCTION Area file area.f90 file main.f90
  • 206.
    INTERFACE Blocks: 3/5INTERFACEBlocks: 3/5 An INTERFACE block has the following syntax:g y INTERFACE type FUNCTION name(arg-1, arg-2, ..., arg-n) type, INTENT(IN) :: arg-1 type, INTENT(IN) :: arg-2 .......... type INTENT(IN) :: arg ntype, INTENT(IN) :: arg-n END FUNCTION name SUBROUTINE name(arg-1, arg-2, …, arg-n) type, INTENT(IN or OUT or INOUT) :: arg-1 type, INTENT(IN or OUT or INOUT) :: arg-2 .......... type, INTENT(IN or OUT or INOUT) :: arg-n END SUBROUTINE nameEND SUBROUTINE name ....... other functions/subroutines ....... END INTERFACE 53
  • 207.
    INTERFACE Blocks: 4/5INTERFACEBlocks: 4/5 All external subprograms should be listedAll external subprograms should be listed between INTERFACE and END INTERFACE. However only the FUNCTION and SUBROUTINEHowever, only the FUNCTION and SUBROUTINE headings, argument types and INTENTs are needed No executable statements should beneeded. No executable statements should be included. Th t d t h t b id ti lThe argument names do not have to be identical to those of the formal arguments, because they are “place holders” in an INTERFACE blockare “place-holders” in an INTERFACE block. Thus, a main program or subprogram will be 54 able to know exactly how to use a subprogram.
  • 208.
    INTERFACE Blocks: 5/5INTERFACEBlocks: 5/5 Return to Heron’s formula for triangle area.g The following shows the INTERFACE block in a main program.p g LOGICAL FUNCTION Test(a, b, c) IMPLICIT NONE REAL INTENT(IN) :: a b c PROGRAM HeronFormula IMPLICIT NONE INTERFACEREAL, INTENT(IN) :: a, b, c LOGICAL :: test1, test2 test1 = (a>0.0) .AND. (b>0.0) .AND. (c>0.0) test2 = (a+b>c) .AND. (a+c>b) .AND. (b+c>a) Test = test1 AND test2 INTERFACE LOGICAL FUNCTION Test(x,y,z) REAL, INTENT(IN)::x,y,z END FUNCTION TestTest = test1 .AND. test2 END FUNCTION Test REAL FUNCTION Area(a, b, c) IMPLICIT NONE REAL FUNCTION Area(l,m,n) REAL, INTENT(IN)::l,m,n END FUNCTION Area END INTERFACEIMPLICIT NONE REAL, INTENT(IN) :: a, b, c REAL :: s s = (a + b + c) / 2.0 Area = SQRT(s*(s-a)*(s-b)*(s-c)) END INTERFACE …… other statements … END PROGRAM HeronFormula 55 Area = SQRT(s*(s-a)*(s-b)*(s-c)) END FUNCTION Area file area.f90 file main.f90
  • 209.