F90 basics
-
Upload
tariqul-dipu -
Category
Education
-
view
1.902 -
download
1
Transcript of F90 basics
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
zA 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 and�specification part, execution part, and subprogram-part are optional.�Although IMPLICIT NONE is also optional, this is g p ,
required in this course to write safe programs.
PROGRAM program-nameIMPLICIT NONE
[ ifi ti t][specification-part] [execution-part] [subprogram-part]
2
[subprogram part] END PROGRAM program-name
Program CommentsProgram Comments
zComments start with a !Comments start with a !zEverything following ! will be ignoredzThis is similar to // in C/C++zThis 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
zFortran 90 is not completely format-free!Fortran 90 is not completely format free!zA statement must starts with a new line. zIf t t t i t l t fit li it hzIf a statement is too long to fit on one line, it has
to be continued.zThe 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
zFortran 90 alphabets include the following:Fortran 90 alphabets include the following:�Upper and lower cases letters�Di it�Digits�Special characters
space
' " ( ) * + - / : = _ ! & $ ; < > % ? , .
5
Constants: 1/6Constants: 1/6
zA Fortran 90 constant may be an integer, real,A Fortran 90 constant may be an integer, real, logical, complex, and character string.zWe will not discuss complex constantszWe will not discuss complex constants.zAn 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
zA real constant has two forms, decimal andA real constant has two forms, decimal and exponential:�In the decimal form a real constant is a�In 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
z A real constant has two forms, decimal andA real constant has two forms, decimal and exponential:�In the exponential form a real constant�In 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 (12u103) 12e3 ( 12u103)�12E3 (12u103), -12e3 (-12u103), 3.45E-8 (3.45u10-8), -3.45e-8 ( 3 45u10-8)(-3.45u10-8).
�0E0 (0u100=0). 12.34-5 is wrong!
8
Constants: 4/6Constants: 4/6
zA logical constant is either .TRUE. or .FALSE.g S
zNote that the periods surrounding TRUE and FALSE are required!FALSE are required!
9
Constants: 5/6Constants: 5/6
zA 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 ‘()()’.zThe content of a character string consists of allzThe 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.zThe 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
zA string has length zero (i.e., no content) is an g g ( , )empty string.zIf 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”’.zTwo 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
zA Fortran 90 identifier can have no more thanA Fortran 90 identifier can have no more than 31 characters.zThe first one must be a letter The remainingzThe first one must be a letter. The remaining
characters, if any, may be letters, digits, or underscoresunderscores.zFortran 90 identifiers are CASE INSENSITIVE.zExamples: A, Name, toTAL123, System_, myFile_01, my_1st_F90_program_X_.zIdentifiers Name, nAmE, naME and NamE are
the same.12
Identifiers: 2/2Identifiers: 2/2
zUnlike Java, C, C++, etc, Fortran 90 does not , , , ,have reserved words. This means one may use Fortran keywords as identifiers.zTherefore, 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.zYes, end = program + if/(goto –while) is legal!zHowever, avoid the use of Fortran 90 keywords
as identifiers to minimize confusion.
13
Declarations: 1/3Declarations: 1/3
zFortran 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 by q p ycommas.
type-specifier :: listtype specifier :: list
zExamples:INTEGER :: Zip, Total, counter
REAL :: AVERAGE, x, Difference
LOGICAL :: Condition, OK
14COMPLEX :: Conjugate
Declarations: 2/3Declarations: 2/3
zCharacter variables require additionalCharacter variables require additional information, the string length:� Keyword CHARACTER must be followed by� Keyword 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
zExamples: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
zA PARAMETER identifier is a name whose value cannot be modified. In other words, it is a named constant.named constant.zThe PARAMETER attribute is used after the type
keywordkeyword.zEach 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
zSince CHARACTER identifiers have a length gattribute, it is a little more complex when used with PARAMETER.zUse (LEN = *) if one does not want to count
the number of characters in a PARAMETERthe number of characters in a PARAMETERcharacter 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
zSince 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 PARAMETER�If a string is longer than the PARAMETER
length, the right end is truncated.�If a string is shorter than the PARAMETER�If 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
zBy convention, PARAMETER identifiers use all y ,upper cases. However, this is not mandatory.zFor maximum flexibility constants other than 0zFor maximum flexibility, constants other than 0
and 1 should be PARAMETERized.zA PARAMETER is an alias of a value and is not azA PARAMETER is an alias of a value and is not a
variable. Hence, one cannot modify the content of a PARAMETER identifiera PARAMETER identifier.zOne can may a PARAMETER identifier anywhere
in a program. It is equivalent to replacing the identifier with its value.
20zThe value part can use expressions.
Variable Initialization: 1/2Variable Initialization: 1/2
zA 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
zVariable initialization is very similar to what weVariable initialization is very similar to what we learned with PARAMETER.zA variable name is followed by a = followed byzA 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.zUsing 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
22INTEGER :: Pay = Quantity*Amount, Received = Period+5
Arithmetic OperatorsArithmetic Operators
zThere are four types of operators in Fortran 90:There are four types of operators in Fortran 90: arithmetic, relational, logical and character. zThe following shows the first three types:zThe 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
z** is the highest; * and / are the next, followed g ; / ,by + and -. All relational operators are next.zOf the 5 logical operators EQV and NEQVzOf 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
zExpressions are evaluated from left to right.Expressions are evaluated from left to right.zIf 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 t� if 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 continues25
Single Mode ExpressionSingle Mode Expression
zA single mode arithmetic expression is anA single mode arithmetic expression is an expression all of whose operands are of the same type.same type.zIf 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
zIf operands have different types, it is mixedIf operands have different types, it is mixed mode.zINTEGER and REAL yields REAL and thezINTEGER 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.zException: x**INTEGER: x**3 is x*x*x andzException: x**INTEGER: x**3 is x*x*x and x**(-3) is 1.0/(x*x*x).
i l d i h dzx**REAL is evaluated with log() and exp().zLogical and character cannot be mixed with
27arithmetic operands.
Mixed Mode Expression: 2/2Mixed Mode Expression: 2/2
zNote that a**b**c is a**(b**c) instead of ( )
(a**b)**c, and a**(b**c) z (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.0rather 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
zThe assignment statement has a form ofThe assignment statement has a form ofvariable = expression
zIf the type of ariable and e pression arezIf the type of variable and expression are identical, the result is saved to variable.zIf the type of variable and expression are
not identical, the result of expression is fconverted to the type of variable.
zIf expression is REAL and variable is INTEGER, the result is truncated.
29
The Assignment Statement: 2/2The Assignment Statement: 2/2
zThe 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
zFortran provides many commonly usedFortran provides many commonly used functions, referred to as intrinsic functions.zTo use an intrinsic function we need to know:zTo 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
zSome mathematical functions:Some mathematical functions:Function Meaning Arg. Type Return Type
b l l fINTEGER INTEGER
ABS(x) absolute value of xREAL 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 REAL TAN(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
32LOG(x) natural logarithm of x REAL REAL
LOG10(x) is the common logarithm of x!
Fortran Intrinsic Functions: 3/4Fortran Intrinsic Functions: 3/4
zSome 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
zOther functions:Other functions:Function Meaning Arg. Type Return Type
INTEGER INTEGERMAX(x1, x2, ..., xn) maximum of x1, x2, ... xn
INTEGER INTEGER
REAL REAL
MIN(x1 x2 xn) minimum of x1 x2 xnINTEGER INTEGER
MIN(x1, x2, ..., xn) minimum of x1, x2, ... xnREAL REAL
MOD(x,y) remainder x - INT(x/y)*yINTEGER INTEGER
REAL REAL
34
Expression EvaluationExpression EvaluationzFunctions have the highest priority.zFunction arguments are evaluated first.zThe returned function value is treated as azThe returned function value is treated as a
value in the expression.REAL :: A = 1.0, B = -5.0, C = 6.0, R REAL :: 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?
zFortran has an interesting tradition: all gvariables starting with i, j, k, l, m and n, if not declared, are of the INTEGER type by default.zThis handy feature can cause serious
consequences if it is not used with care.zIMPLICIT NONE means all names must be
declared and there is no implicitly assumed INTEGER type.zAll 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
zFortran 90 uses the READ(*,*) statement to ( , )
read data into variables from keyboard:READ(* *) v1 v2 vnREAD( , ) v1, v2, …, vn
READ(*,*)
zThe 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
zData 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 must� If 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
38spread into multiple lines.
List-Directed READ: 3/5List Directed READ: 3/5
zThe execution of READ(*,*) always starts with f ( , ) ya new line!zThen it reads each constant into thezThen, 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
zBe 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
zSince 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, S INTEGER :: P, Q, R, S
READ(*,*) P, Q
READ(*,*) 100 200 300
400 500 600 ( , )
READ(*,*) R, S400 500 600
700 800 900
41
List-Directed WRITE: 1/3List Directed WRITE: 1/3
zFortran 90 uses the WRITE(*,*) statement to ( , )
write information to screen. zWRITE(* *) has two forms where exp1zWRITE( , ) has two forms, where exp1, exp2, …, expn are expressions
WRITE(* *) e p1 e p2 e pnWRITE(*,*) exp1, exp2, …, expn
WRITE(*,*)
zWRITE(*,*) evaluates the result of each expression and prints it on screen.zWRITE(*,*) always starts with a new line!
42
List-Directed WRITE: 2/3List Directed WRITE: 2/3
zHere 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
zThe previous example used LEN=* , which p p ,means the length of a CHARACTER constant is determined by actual count.zWRITE(*,*) without any expression advances
to the next line, producing a blank one.zA Fortran 90 compiler will use the best way to
print each value. Thus, indentation and alignment are difficult to achieve with WRITE(*,*).zOne must use the FORMAT statement to produce
good looking output.
44
Complete Example: 1/4Complete Example: 1/4
zThis program computes the position (x and yp g p p ( ycoordinates) 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.
zThe horizontal and vertical displacements, x and y, are computed as follows:
x u a t u ucos( )g tu 2
y u a t g t u u � usin( )2
45
2
Complete Example: 2/4Complete Example: 2/4
zThe horizontal and vertical components of the velocity p yvector are computed as
cos( )V u a ucos( )xV u a usin( )yV u a g t u � u
zThe magnitude of the velocity vector is
( )y g
V V V2 2
zThe angle between the ground and the velocity vector isV V Vx y �2 2
tan( )T VVx
46
Vy
Complete Example: 3/4Complete Example: 3/4
zWrite a program to read in the launch angle a, the time p 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 degree REAL :: 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
zWrite a program to read in the launch angle a, the time p 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
48WRITE(*,*) 'Resultant velocity : ', V
WRITE(*,*) 'Direction (in degree) : ', Theta
CHARACTER Operator //CHARACTER Operator //
zFortran 90 uses // to concatenate two strings.// gzIf 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
zA consecutive portion of a string is a substring.p g gzTo use substrings, one may add an extent
specifier to a CHARACTER variable. p fzAn extent specifier has the following form:
( integer-exp1 : integer-exp2 )( integer-exp1 : integer-exp2 )
zThe 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, zIf 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
zIn (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.zIf A = “12345678” then A(:5) is “12345”zIf A = 12345678 , then A(:5) is 12345
and A(3+x:) is “5678” where x is 2.zA d i ti i lzAs 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
zSubstrings can be used on either side of the gassignment operator.zSuppose LeftHand = “123456789”pp
(length is 10) . � LeftHand(3:5) = "abc” yields LeftHand = “12abc67890”
� LeftHand(4:) = "lmnopqr” yieldsLeftHand = "123lmnopqr“LeftHand = "123lmnopqr“
� LeftHand(3:8) = "abc” yields LeftHand = "12abc���90“���
� LeftHand(4:7) = "lmnopq” yieldsLeftHand = "123lmno890"
52
Example: 1/5Example: 1/5
zThis 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.zSystem date is a string ccyymmdd where cc =zSystem date is a string ccyymmdd, where cc
century, yy = year, mm = month, and dd = day.zSystem time is a string hhmmss.sss, where hh
= hour, mm = minute, and ss.sss = second.53
Example: 2/5Example: 2/5
zThe following shows the specification part. g p pNote 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
54This is a handy way of changing string length
Example: 3/5Example: 3/5
zDecompose DateINFO into year, month and p 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 -> ' DateINFO WRITE(*,*) 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
zNow 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 -> ', Second WRITE( , ) 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
zWe may also use substring to achieve the same y gresult:
PrettyTime = “ “ ! Initialize to all blanks
PrettyTime( :2) = Hour
PrettyTime(3:3) = ':' PrettyTime(3:3) = ':'
PrettyTime(4:5) = Minute
PrettyTime(6:6) = ':'
PrettyTime(7: ) = Second PrettyTime(7: ) = Second
WRITE(*,*)
WRITE(*,*) ' Pretty Time -> ', PrettyTime WRITE( , ) Pretty Time > , PrettyTime
57
What KIND Is It?What KIND Is It?
zFortran 90 has a KIND attribute for selecting gthe precision of a numerical constant/variable.zThe KIND of a constant/variable is a positivezThe KIND of a constant/variable is a positive
integer (more on this later) that can be attached to a constantto a constant.zExample:
i i f� 126_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
zFunction 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.zThus, 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.zIf 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
zSELECTED_INT_KIND() is usually used in the _ _ yspecification part like the following:INTEGER, PARAMETER :: SHORT = SELECTED_INT_KIND(2)_ _
INTEGER(KIND=SHORT) :: x, y
zThe above declares an INTEGER PARAMETER SHORT with SELECTED_INT_KIND(2), which is the KIND of 2-digit integers.zThen, the KIND= attribute specifies that INTEGER
variables x and y can hold 2-digit integers.zIn 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
zUse SELECTED REAL KIND(k,e) to specify a S _ _ ( , ) p yKIND 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 emust be positive integers.must be positive integers.zNote that e is optional.zSELECTED REAL KIND(7 3) selects a REALzSELECTED_REAL_KIND(7,3) selects a REALKIND of 7 significant digits and 3 digits for the
t r0 u10ryyyexponent: r0.xxxxxxxu10ryyy
61
What KIND Is It (REAL)? 2/2What KIND Is It (REAL)? 2/2
zHere 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
zOld 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.zThis 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).zM l t t h d fizMoreover, we also want to have more and finer
precision control.
63
Why KIND, etc? 2/2Why KIND, etc? 2/2
zDue to the differences among computerDue to the differences among computer hardware architectures, we have to be careful:� The requested KIND may not be satisfied� The 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.
64zUse 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.
1Donald Ervin Knuth
Fall 2010
LOGICAL VariablesLOGICAL Variables
zA LOGIAL variable can only hold either .TRUE.yor .FALSE. , and cannot hold values of any other type.other type.zUse T or F for LOGICAL variable READ(*,*)zWRITE(* *) prints T or F for TRUEzWRITE(*,*) prints T or F for .TRUE.
and .FALSE., respectively.LOGICAL, PARAMETER :: Test = .TRUE.LOGICAL :: C1, C2
C1 = .true. ! correctC2 = 123 ! WrongREAD(*,*) C1, C2
2C2 = .false.WRITE(*,*) C1, C2
Relational Operators: 1/4Relational Operators: 1/4
zFortran 90 has six relational operators: <, <=,p , ,>, >=, ==, /=.zEach of these six relational operators takes two p
expressions, compares their values, and yields .TRUE. or .FALSE.zThus, a < b < c is wrong, because a < b is LOGICAL and c is REAL or INTEGER.zCOMPLEX values can only use == and /=zLOGICAL values should use .EQV. or .NEQV.
for equal and not-equal comparison.
3
Relational Operators: 2/4Relational Operators: 2/4
zRelational operators have lower priority thanRelational operators have lower priority than arithmetic operators, and //.zThus 3 + 5 > 10 is FALSE and “a” // zThus, 3 + 5 > 10 is .FALSE. and a // “b” == “ab” is .TRUE.zCh t l d d Diff tzCharacter values are encoded. Different
standards (e.g., BCD, EBCDIC, ANSI) have diff t didifferent encoding sequences. zThese encoding sequences may not be
compatible with each other.
4
Relational Operators: 3/4Relational Operators: 3/4
zFor maximum portability, only assume the p y, yfollowing orders for letters and digits.zThus, “A” < “X”, ‘f’ <= “u”, and “2” < , , ,“7” yield .TRUE. But, we don’t know the results of “S” < “s” and “t” >= “%”.zHowever, 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
50 < 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9
Relational Operators: 4/4Relational Operators: 4/4
zString comparison rules:g p�Start scanning from the first character.�If the current two are equal go for the next�If 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
zThere are 5 LOGICAL operators in Fortran p90: .NOT., .OR., .AND., .EQV. and .NEQV.z NOT is the highest followed by ORz.NOT. is the highest, followed by .OR.
and .AND., .EQV. and .NEQV. are the lowest.zRecall that NOT is evaluated from right to leftzRecall that .NOT. is evaluated from right to left.zIf both operands of .EQV. (equivalence) are the
isame, .EQV. yields .TRUE.. z.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
z If INTEGER variables m, n, x and y have , , yvalues 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
zFortran 90 has three if-then-else forms.zThe most complete one is the IF-THEN-ELSE-IF-END IFzAn old logical IF statement may be very handy
when it is needed.zThere is an old and obsolete arithmetic IF that
you are not encouraged to use. We won’t talk y gabout it at all.zDetails are in the next few slides.
9
IF-THEN-ELSE Statement: 2/4IF THEN ELSE Statement: 2/4
zIF-THEN-ELSE-IF-END IF is the following.gzLogical expressions are evaluated sequentially (i.e., top-
down). The statement sequence that corresponds to the expression evaluated to .TRUE. will be executed.zOtherwise, the ELSE sequence is executed.
IF (logical-expression-1) THEN statement sequence 1
ELSE IF (logical expression 2) THEN ELSE 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
zTwo Examples:Two Examples:Find the minimum of a, b and cand 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
zThe ELSE-IF part and ELSE part are optional.p p pzIf 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 ELSEIF (logical-expression-1) THEN
statement sequence 1ELSE
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 ( ) THEN ELSE IF (.....) THEN ...........
END IF
12
Example: 1/2Example: 1/2
zGiven a quadratic equation ax2 +bx + c = 0,Given a quadratic equation ax bx c 0, where az0, its roots are computed as follows:
b br u u2 4x b b a ca
� r � u uu
2 42
zHowever, 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
zThe following shows the executable partThe following shows the executable partREAD(*,*) 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 rootroot2 = (-b - d)/(2.0*a) ! second rootWRITE(* *) 'R t ' t1 ' d ' t2 WRITE(*,*) 'Roots are ', root1, ' and ', root2
ELSE ! complex rootsWRITE(*,*) '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
zAnother look at the quadratic equation solver.Another look at the quadratic equation solver.
IF (a == 0.0) THEN ! could be a linear equationIF (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 rootsWRITE(*,*) 'All numbers are roots'
ELSE ! unsolvableELSE ! unsolvableWRITE(*,*) '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
zHere is the big ELSE part:g S p
d b*b 4 0*a*c d = 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 rootroot2 = (-b - d)/(2.0*a) ! second rootWRITE(*,*) '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 rootsWRITE(*,*) 'There is no real roots!' ( , )WRITE(*,*) 'Discriminant = ', d
END IF
16
Logical IFLogical IF
zThe logical IF is from Fortran 66, which is an g ,improvement over the Fortran I arithmetic IF.zIf logical-expression is .TRUE. , statement is g p ,
executed. Otherwise, execution goes though.zThe statement can be assignment and g
input/output.IF (logical-expression) statementIF (logical expression) statement
Smallest = b Cnt = Cnt + 1Smallest = bIF (a < b) Smallest = a
Cnt = Cnt + 1IF (MOD(Cnt,10) == 0) WRITE(*,*) Cnt
17
The SELECT CASE Statement: 1/7The SELECT CASE Statement: 1/7
zFortran 90 has the SELECT CASE statement for S Sselective 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 evaluatedto an INTEGER, LOGICAL orCHARACTER value
statements-2CASE (label-list-3)
statements-3 other cases
label-list is a set of constants orPARAMETERS of the same type…… other cases ……
CASE (label-list-n) statements-n
CASE DEFAULT
ypas the selector
statements is one or more
18
CASE DEFAULT statements-DEFAULT
END SELECT
statements s o e o o eexecutable statements
The SELECT CASE Statement: 2/7The SELECT CASE Statement: 2/7
zThe 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 between� value1 : 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
zReminder: value, value1 and value2 must 19
,be constants or PARAMETERs.
The SELECT CASE Statement: 3/7The SELECT CASE Statement: 3/7zThe SELECT CASE statement is SELECT CASE (selector)
executed as follows:� Compare the value of
SELECT CASE (selector) CASE (label-list-1)
statements-1CASE (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-3found, 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
20following the SELECT CASE.
The SELECT CASE Statement: 4/7The SELECT CASE Statement: 4/7
zSome 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 CASEwould be selected.
� CASE DEFAULT should be used whenever it� CASE 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 i� CASE DEFAULT can be anywhere in a SELECT CASE statement; but, a preferred
l i h l i h li21
place is the last in the CASE list.
The SELECT CASE Statement: 5/7The SELECT CASE Statement: 5/7
zTwo examples of SELECT CASE:p S S
CHARACTER(LEN=4) :: Title INTEGER :: DrMD = 0, PhD = 0
CHARACTER(LEN=1) :: c INTEGER :: DrMD 0, PhD 0INTEGER :: MS = 0, BS = 0INTEGER ::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
zHere 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/7PROGRAM 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 consonantWRITE(*,*) '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
zFortran 90 has two forms of DO loop: the pcounting DO and the general DO.zThe counting DO has the following form:zThe counting DO has the following form:
DO control-var = initial, final [, step]
statementsstatementsEND DO
zcontrol-var is an INTEGER variable,zcontrol var is an INTEGER variable, initial, final and step are INTEGERexpressions; however, step cannot be zero.expressions; however, step cannot be zero.zIf step is omitted, its default value is 1.z t bl t t t f th O
25zstatements are executable statements of the DO.
The Counting DO Loop: 2/6The Counting DO Loop: 2/6
zBefore a DO-loop starts, expressions initial, p , p ,final and step are evaluated exactly once. When executing the DO-loop, these values will g p,not be re-evaluated.zNote again the value of step cannot be zerozNote again, the value of step cannot be zero.zIf 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
zIf step is positive:p p� The control-var receives the value of initial.� If the value of control-var is less than or equal to� If 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
zIf step is negative:p g� The control-var receives the value of initial.� If the value of control-var is greater than or� If the value of control var is greater than or
equal to the value of final, the statements part is executed. Then, the value of step is added to control-var, goes back and compares the 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
zTwo simple examples:Two simple examples:
INTEGER :: N, k odd integersbetween 1 & N
READ(*,*) NWRITE(*,*) “Odd number between 1 and “, NDO k = 1, N, 2
between 1 & N
WRITE(*,*) kEND DO
INTEGER, PARAMETER :: LONG = SELECTED_INT_KIND(15)INTEGER(KIND=LONG) :: Factorial, i, N
READ(* *) N
factorial of N
READ(*,*) NFactorial = 1_LONGDO i = 1, N
Factorial = Factorial * i
29END DOWRITE(*,*) N, “! = “, Factorial
The Counting DO Loop: 6/6The Counting DO Loop: 6/6
zImportant Notes:Important Notes:� The step size step cannot be zero�N h th l f i bl i�Never 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 statementsportion 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
zThe general DO-loop has the following form:The general DO loop has the following form:DO
statementsstatementsEND DO
z t t t ill b t d t dlzstatements will be executed repeatedly.zTo exit the DO-loop, use the EXIT or CYCLE
statement.zThe EXIT statement brings the flow of control to
the statement following (i.e., exiting) the END DO.zThe 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.25REAL :: x
x = Lower ! initialize the control variableDO
IF (x > Upper) EXIT ! is it > final-value?WRITE(*,*) x ! no, do the loop bodyx = x + Step ! increase by step-sizex = x + Step ! increase by step-size
END DO
INTEGER :: Input INTEGER :: 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
zThe exp(x) function has an infinite series:The exp(x) function has an infinite series:
exp( )! !
....!......x x x x x
i
i
� � � � � �12 3
2 3
zSum 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 usedREAL :: Term ! a termREAL :: Sum ! the sumREAL :: X ! the input xREAL, PARAMETER :: Tolerance = 0.00001 ! tolerance
33…… executable statements ……
END PROGRAM Exponential
Example, exp(x): 2/2Example, exp(x): 2/2zNote:
1
( 1)! ! 1
i ix x xi i i
� § · § · u¨ ¸ ¨ ¸© ¹© ¹
zThis is not a good solution, though.
( 1)! ! 1i i i¨ ¸ ¨ ¸� �© ¹© ¹
zThis is not a good solution, though.READ(*,*) X ! read in xCount = 1 ! the first term is 1
iSum = 1.0 ! thus, the sum starts with 1Term = X ! the second term is xDO ! for each term
IF (ABS(T ) < T l ) EXIT ! if t ll itIF (ABS(Term) < Tolerance) EXIT ! if too small, exitSum = Sum + Term ! otherwise, add to sumCount = Count + 1 ! count indicates the next termTerm = 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
zA 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.zIf n = 2 it is a primezIf n = 2, it is a prime.zIf n > 2 is even (i.e., MOD(n,2) == 0), not a prime.zIf 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) is g p , Q ( )
good enough. Why?
35
Example, Prime Checking: 2/2Example, Prime Checking: 2/2INTEGER :: Number ! the input numberINTEGER :: Divisor ! the running divisor
READ(*,*) Number ! read in the inputIF (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) EXITDivisor = 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
zThe 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 integerIF (Range >= 2) EXIT ! if it is GOOD, exitWRITE(*,*) 'The range value must be >= 2. Your input = ', Range WRITE(*,*) 'Please try again:' ! otherwise, bug the user
END DO END 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 countingWRITE(*,*) ! 2 is a primeWRITE(*,*) 'Prime number #', Count, ': ', 2
DO Number = 3, Range, 2 ! try all odd numbers 3, 5, 7, ...Divisor = 3 ! divisor starts with 3DO
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 primeWRITE(*,*) '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/3zGiven a positive integer, one can always factorize p g , y
it into prime factors. The following is an example:
586390350 = 2u3u52u72u13u17u192
zHere, 2, 3, 5, 7, 13, 17 and 19 are prime factors., , , , , , pzIt 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, ….
zBut we said “prime” factors No problemzBut, 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/3PROGRAM 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 2IF (MOD(I t 2) / 0 OR I t 1) EXIT IF (MOD(Input,2) /= 0 .OR. Input == 1) EXIT Count = Count + 1 ! increase countWRITE(*,*) '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 factorsDO ! Try 3, 5, 7, 9, 11 .... IF (Divisor > Input) EXIT ! factor is too large, exit and done DO ! try this factor repeatedly DO ! 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 DO END 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, …), andDivisor = 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
zVery frequently we don’t know the number ofVery frequently we don t know the number of data items in the input.zFortran uses IOSTAT= for I/O error handling:zFortran uses IOSTAT= for I/O error handling:
READ(*,*,IOSTAT=v) v1, v2, …, vn
zIn the above, v is an INTEGER variable.zAfter 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
42variables received values.
Handling End-of-File: 2/3Handling End of File: 2/3
zEvery file is ended with a special character.Every file is ended with a special character. Unix and Windows use Ctrl-D and Ctrl-Z.zWhen using keyboard to enter data tozWhen using keyboard to enter data to
READ(*,*), Ctrl-D means end-of-file in Unix.zIf IOSTAT returns a positive value we onlyzIf 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.
zWe 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 tINTEGER :: io, x, sum 1
3The 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
zLet 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 xnn1 2u u u......
harmonic mean =n
1 1 1� � �
zNote that only positive values will be considered
x x xn1 2
� � �......
zNote that only positive values will be considered.zThis naïve way is not a good method.
45
Computing Means, etc: 2/4Computing Means, etc: 2/4
PROGRAM ComputingMeans PROGRAM 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/4DO
READ(*,*,IOSTAT=IO) X ! read in data IF (IO < 0) EXIT ! IO < 0 means end-of-file reachedCount = Count + 1 ! otherwise, got some valueIF (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 normalWRITE(*,*) 'Input item ', Count, ' --> ', X IF (X <= 0.0) THEN
WRITE(*,*) 'Input <= 0. Ignored' ELSE ELSE
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 -> ', TotalValid WRITE( , ) # 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
1Fall 2009
The DIMENSION Attribute: 1/6The DIMENSION Attribute: 1/6
zA Fortran 90 program uses the DIMENSIONp gattribute to declare arrays.zThe DIMENSION attribute requires three q
components in order to complete an array specification, rank, shape, and extent.zThe rank of an array is the number of “indices”
or “subscripts.” The maximum rank is 7 (i.e., seven-dimensional).zThe shape of an array indicates the number of
elements in each “dimension.”
2
The DIMENSION Attribute: 2/6The DIMENSION Attribute: 2/6
zThe 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 (1d i d n) is the number of elements in theand si (1d i d 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
zThe extent is written as m:n, where m and n (mThe extent is written as m:n, where m and n (md n) are INTEGERs. We saw this in the SELECT CASE, substring, etc., g,zEach dimension has its own extent.zA t t f di i i th f itzAn 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
zThe DIMENSION attribute has the following gform:
DIMENSION(extent-1, extent-2, …, extent-n)( , , , )zHere, extent-i is the extent of dimension i.zThis means an array of dimension n (i.e., nzThis means an array of dimension n (i.e., n
indices) whose i-th dimension index has a range given by extent-i.g yzJust a reminder: Fortran 90 only allows
maximum 7 dimensions.zExercise: given a DIMENSION attribute,
determine its shape. 5
p
The DIMENSION Attribute: 5/6The DIMENSION Attribute: 5/6
zHere 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 i�DIMENSION(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
zArray declaration is simple. Add the y pDIMENSION attribute to a type declaration.zValues in the DIMENSION attribute are usually yPARAMETERs to make program modifications easier.
INTEGER, PARAMETER :: SIZE=5, LOWER=3, UPPER = 5INTEGER, PARAMETER :: SMALL = 10, LARGE = 15REAL, DIMENSION(1:SIZE) :: xINTEGER, DIMENSION(LOWER:UPPER,SMALL:LARGE) :: a,b, ( , ) ,LOGICAL, DIMENSION(2,2) :: Truth_Table
7
Use of Arrays: 1/3Use of Arrays: 1/3
z Fortran 90 has, in general, three different ways , g , yto use arrays: referring to individual array element, referring to the whole array, and referring to a section of an array.
z The first one is very easy. One just starts with the array name, followed by () between which are the indices separated by ,.
z 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
zSuppose we have the following declarationsSuppose we have the following declarationsINTEGER, 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_BOUNDx(i) = i
DO i = L_BOUND, U_BOUNDIF (MOD(i,2) == 0) THEN
iEND DO x(i) = 0ELSE
x(i) = 1array x() has 3,4,5,…, 10
END IFEND 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/3zSuppose we have the following declarations:
INTEGER, PARAMETER :: L_BOUND = 3, U_BOUND = 10INTEGER, DIMENSION(L_BOUND:U_BOUND, &
L_BOUND:U_BOUND) :: a
DO i = L_BOUND, U_BOUNDDO j = L_BOUND, U_BOUND
a(i j) = 0
DO i = L_BOUND, U_BOUNDDO j = i+1, U_BOUNDt = a(i,j)a(i,j) = 0
END DOa(i,i) = 1
t a(i,j)a(i,j) = a(j,i)a(j,i) = t
END DOEND 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
zFortran has the implied DO that can generate p gefficiently a set of values and/or elements.zThe implied DO is a variation of the DO-loop.p pzThe 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)
zHere, item-1, item-2, …, item-n are variables or expressions, v is an INTEGERvariables or expressions, v is an INTEGERvariable, and initial, final, and step are INTEGER expressions.pz“v=initial,final,step” is exactly what we
saw in a DO-loop.11
p
The Implied DO: 2/7The Implied DO: 2/7
zThe execution of an implied DO below lets variable pv 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)
zThe result is a sequence of items.z(i+1, i=1,3) generates 2 3 4z(i+1, i=1,3) generates 2, 3, 4.z(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).z(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
zImplied DO may be nested.p y(i*k,(j*j,i*j,j=1,3), i=2,4)
zIn the above (j*j i*j j 1 3) is nested inzIn the above, (j*j,i*j,j=1,3) is nested in the implied i loop.zHere 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 generates�Then, j goes from 1 to 3 and generates2*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
zContinue with the previous examplep p(i*k,(j*j,i*j,j=1,3), i=2,4)
zWhen i = 3, it generates the following:g g3*k, (j*j,3*j,j=1,3)
zExpanding the j loop yields:p g j p y3*k, 1*1, 3*1, 2*2, 3*2, 3*3, 3*3
zWhen i = 4, the i loop generates, p g4*k, (j*j, 4*j, j=1,3)
zExpanding the j loop yieldsp g j p y4*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
zThe following generates a multiplication table:The following generates a multiplication table:((i*j,j=1,9),i=1,9)
zWhen i 1 the inner j implied DO loopzWhen i = 1, the inner j implied DO-loop produces 1*1, 1*2, …, 1*9zWhen i = 2, the inner j implied DO-loop
produces 2*1, 2*2, …, 2*9zWhen 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
zThe 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)
zWhen p = 1, the inner q loop produces a(1,1), a(1 2) a(1 n)a(1,2), …, a(1,n)zWhen p=2, the inner q loop produces a(2,2), a(2,3), …., a(2,n)zWhen p=3, the inner q loop produces a(3,3), a(3,4), …, a(3,n)zWhen p=n, the inner q loop produces a(n,n)
16
p , q p p ( , )
The Implied DO: 7/7The Implied DO: 7/7
zThe 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)
zWhen q=1, the inner p loop produces a(1,1)zWhen q=2, the inner p loop produces a(1,2), a(2,2)
zWhen q=3, the inner p loop produces a(1,3), a(2,3), …, a(3,3)zWhen 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
zImplied DO can be used in READ(*,*) and p ( , )WRITE(*,*) statements.zWhen an implied DO is used it is equivalent tozWhen an implied DO is used, it is equivalent to
execute the I/O statement with the generated elementselements.zThe 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)
zThe following has a better format (i.e., 9 rows):DO i = 1, 9
WRITE(*,*) (i, “*”, j, “=“, i*j, j=1,9)
18END DO
Array Input/Output: 2/8Array Input/Output: 2/8
zThe following shows three ways of reading ng y gdata items into an one dimensional array a().zAre they the same?zAre they the same?
READ(*,*) n,(a(i),i=1,n)(1)
READ(*,*) ni i
( )
(2)READ(*,*) (a(i),i=1,n)
READ(* *) n(3) READ(*,*) nDO i = 1, n
READ(*,*) a(i)
(3)
19END DO
Array Input/Output: 3/8Array Input/Output: 3/8
zSuppose 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
zEach READ starts from a new line!OKREAD(*,*) n,(a(i),i=1,n)
READ(* *) n
(1)
(2)
OK
Wrong! n gets 3 andREAD(*,*) nREAD(*,*) (a(i),i=1,n)
(2) Wrong! n gets 3 and the second READ fails
READ(*,*) nDO i = 1, n
(3) Wrong! n gets 3 and the three READs fail
20READ(*,*) a(i)
END DO
Array Input/Output: 4/8Array Input/Output: 4/8
zWhat if the input is changed to the following?What if the input is changed to the following?
310 20 30
OK
10 20 30
READ(*,*) n,(a(i),i=1,n)
READ(* *) n
(1)
(2)
OK
OK. Why????READ(*,*) nREAD(*,*) (a(i),i=1,n)
(2) OK. Why????
READ(*,*) nDO i = 1, n
(3) Wrong! n gets 3, a(1) has10; but, the next two READs fail
21READ(*,*) a(i)
END DO
READs fail
Array Input/Output: 5/8Array Input/Output: 5/8
zWhat if the input is changed to the following?What if the input is changed to the following?31020
OK
2030
READ(*,*) n,(a(i),i=1,n)
READ(* *) n
(1)
(2)
OK
OKREAD(*,*) nREAD(*,*) (a(i),i=1,n)
(2) OK
READ(*,*) nDO i = 1, n
(3) OK
22READ(*,*) a(i)
END DO
Array Input/Output: 6/8Array Input/Output: 6/8
zSuppose we have a two-dimensional array a():pp y ()
INTEGER, DIMENSION(2:4,0:1) :: a
zSuppose further the READ is the following:zSuppose further the READ is the following:READ(*,*) ((a(i,j),j=0,1),i=2,4)
zWhat are the results for the following input?1 2 3
1 2 3 4 5 61 2 34 5 67 8 9
0 1 0 11 23 4
1 23 4
23
23
0 1 0 1
23
3 45 6
3 45 64 4
Array Input/Output: 7/8Array Input/Output: 7/8
zSuppose 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
zWhat are the results for the following input?
1 2 3 4 5 61 2 34 5 67 8 97 8 9
1 2 1 2A(2,0)=1 row-by-row20 1 0 1
24? ?? ?
4 57 8
A(2,1)=2then error!
y34
Array Input/Output: 8/8Array Input/Output: 8/8
zSuppose 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
zWhat are the results for the following input?
1 2 3 4 5 61 2 34 5 67 8 97 8 9
1 ? 1 4A(2,0)=1A(3,0)=2 column-by-column2
0 1 0 1
252 ?3 ?
2 53 6
A(4,0)=3then error!
y34
Matrix Multiplication: 1/2Matrix Multiplication: 1/2
zRead a lummatrix Alum and a munmatrix Bmun,Read a lummatrix Alum and a munmatrix Bmun, and compute their product Clun = Alumx Bmun.
PROGRAM Matrix MultiplicationPROGRAM Matrix_MultiplicationIMPLICIT NONEINTEGER, PARAMETER :: SIZE = 100INTEGER DIMENSION(1:SIZE 1:SIZE) :: A B CINTEGER, DIMENSION(1:SIZE,1:SIZE) :: A, B, CINTEGER :: L, M, N, i, j, kREAD(*,*) L, M, N ! read sizes <= 100
iDO i = 1, LREAD(*,*) (A(i,j), j=1,M) ! A() is L-by-M
END DODO i = 1, M
READ(*,*) (B(i,j), j=1,N) ! B() is M-by-NEND DO
26…… other statements ……
END PROGRAM Matrix_Multiplication
Matrix Multiplication: 2/2Matrix Multiplication: 2/2
zThe following does multiplication and outputThe following does multiplication and output
DO i = 1, LDO 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 DOEND DO
DO i = 1 L ! print row-by-rowDO i = 1, L ! print row-by-rowWRITE(*,*) (C(i,j), j=1, N)
END DO
27
Arrays as Arguments: 1/4Arrays as Arguments: 1/4
zArrays may also be used as arguments passing y y g p gto functions and subroutines.zFormal argument arrays may be declared as g y y
usual; however, Fortran 90 recommends the use of assumed-shape arrays.zAn 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, yINTEGER, DIMENSION(:), INTENT(OUT) :: a, b
28assumed-shape
Arrays as Arguments: 2/4Arrays as Arguments: 2/4
zThe 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 NONEINTEGER, INTENT(IN) :: l, m, nREAL, DIMENSION(10:),INTENT(IN) :: xINTEGER, DIMENSION(-1:,m:), INTENT(OUT) :: yLOGICAL, DIMENSION(m,n:), INTENT(OUT) :: zREAL, 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
zFortran 90 automatically passes an array and itsFortran 90 automatically passes an array and its shape to a formal argument.zA subprogram receives the shape and uses thezA 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 NONEINTEGER,DIMENSION(-1:),INTENT(IN) :: x
30…… other statements ……
END SUBROUTINE Funny (-1:7)
Arrays as Arguments: 4/4Arrays as Arguments: 4/4
zOne 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 NONEINTEGER,INTENT(IN) :: m,nREAL 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
zHow do I know the shape of an array?p yzUse the SIZE() intrinsic function.zSIZE() requires two arguments, an arrayzSIZE() 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):: ashape 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 prints9 and 101
32WRITE(*,*) SIZE(x,1), SIZE(x,2)
9 and 101
The SIZE() Intrinsic Function : 2/2The SIZE() Intrinsic Function : 2/2INTEGER,DIMENSION(-1:1,3:6):: EmptyCALL Fill(Empty)CALL Fill(Empty)DO i = -1,1WRITE(*,*) (Empty(i,j),j=3,6)
END DO
SUBROUTINE Fill(y)I PLICIT NONE
END DO shape is (3,4)
IMPLICIT NONEINTEGER,DIMENSION(1:,1:),INTENT(OUT)::yINTEGER :: U1, U2, i, j
output U1 = SIZE(y,1)U2 = SIZE(y,2)DO i = 1, U1
2 3 4 53 4 5 64 5 6 7
output
(1:3 1:4)DO j = 1, U2
y(i,j) = i + jEND DO
4 5 6 7 (1:3,1:4)
33
END DOEND DO
END SUBROUTINE Fill
Local Arrays: 1/2Local Arrays: 1/2
zFortran 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 NONEINTEGER,INTENT(IN) :: m, nINTEGER 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) :: Wlocal arraysCALL 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/2zJust 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.zFortran 90 uses the formal arguments to g
compute the extents of local arrays.zTherefore, different calls with different valueszTherefore, 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
zIn 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.zThe ALLOCATABLE attribute comes to rescue.zThe ALLOCATABLE attribute indicates that atzThe 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.
zTherefore, each extent has only a colon :.
INTEGER,ALLOCATABLE,DIMENSION(:) :: aREAL,ALLOCATABLE,DIMENSION(:,:) :: b
36LOGICAL,ALLOCATABLE,DIMENSION(:,:,:) :: c
The ALLOCATE Statement: 1/3The ALLOCATE Statement: 1/3
zThe ALLOCATE statement has the following gsyntax:ALLOCATE(array-1 array-n STAT=v)ALLOCATE(array-1,…,array-n,STAT=v)
zHere, array-1, …, array-n are array names with complete extents as in the DIMENSION with complete extents as in the DIMENSION attribute, and v is an INTEGER variable.Af i f if 0zAfter the execution of ALLOCATE, if v z 0, then at least one arrays did not get memory.REAL,ALLOCATABLE,DIMENSION(:) :: aLOGICAL,ALLOCATABLE,DIMENSION(:,:) :: x
37INTEGER :: statusALLOCATE(a(3:5), x(-10:10,1:8), STAT=status)
The ALLOCATE Statement: 2/3The ALLOCATE Statement: 2/3
zALLOCATE only allocates arrays with the y yALLOCATABLE attribute.zThe extents in ALLOCATE can use INTEGER zThe extents in ALLOCATE can use INTEGER
expressions. Make sure all involved variables have been initialized properlyhave been initialized properly. INTEGER,ALLOCATABLE,DIMENSION(:,:) :: xINTEGER,ALLOCATABLE,DIMENSION(:) :: aINTEGER,ALLOCATABLE,DIMENSION(:) :: aINTEGER :: m, n, pREAD(*,*) m, nALLOCATE(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 ……
38If 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
zALLOCATE can be used in subprograms.p gzFormal arrays are not ALLOCATABLE.zI l ll t d i bzIn 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.zWatch for the following odd use:
PROGRAM Try_not_to_do_thisIMPLICIT NONEREAL,ALLOCATABLE,DIMENSION(:) :: x
CONTAINSSUBROUTINE 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
zAllocated 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)
zHere, array-1, …, array-n are the names of allocated arrays and is an INTEGER variableallocated arrays, and v is an INTEGER variable.zIf deallocation fails (e.g., some arrays were not
) i iallocated), the value in v is non-zero.zAfter 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
zThe ALLOCATED(a) function returns .TRUE.( )if ALLOCATABLE array a has been allocated. Otherwise, it returns .FALSE.,
INTEGER,ALLOCATABLE,DIMENSION(:) :: MatINTEGER :: 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 mustbe true that BASIC is the lingua playpen
1Thomas E. Kurtz
Co-Designer of the BASIC languageFall 2010
Functions and SubroutinesFunctions and Subroutines
zFortran 90 has two types of subprograms,Fortran 90 has two types of subprograms, functions and subroutines.zA Fortran 90 function is a function like those inzA 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.zIf a function does not have to return a function
l b tivalue, use subroutine.
2
Function Syntax: 1/3Function Syntax: 1/3
zA 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
ztype is a Fortran 90 type (e g INTEGERztype is a Fortran 90 type (e.g., INTEGER, REAL, LOGICAL, etc) with or without KIND.zfunction name is a Fortran 90 identifierzfunction-name is a Fortran 90 identifierzarg1, …, argn are formal arguments.
3
Function Syntax: 2/3Function Syntax: 2/3
zA 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.zSomewhere 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. zNote that function-name cannot appear in
the right-hand side of any expression.4
Function Syntax: 3/3Function Syntax: 3/3
zIn a type specification, formal arguments yp p , gshould have a new attribute INTENT(IN). zThe meaning of INTENT(IN) is that the g
function only takes the value from a formal argument and does not change its content.zAny statements that can be used in PROGRAM
can also be used in a FUNCTION.
5
Function ExampleFunction Example
zNote that functions can have no formal argument.Note that functions can have no formal argument.zBut, () 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_ValueDO
WRITE(*,*) 'A positive number: ' Ans = 1 DO i = 1, n
Ans = Ans * i END DO
( , ) pREAD(*,*) Input_Value IF (Input_Value > 0.0) EXIT WRITE(*,*) 'ERROR. try again.'
END DO END 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 errorFUNCTION 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, bIF (a > b) THEN
a = a - b ELSE
INTEGER, INTENT(IN) :: a, b INTEGER :: c c = SQRT(a*a + b*b)
END FUNCTION DoSomething ELSE a = a + b
END IF DoSomthing = SQRT(a*a+b*b)
END FUNCTION DoSomething
7END 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
z 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.
z The following uses function Factorial(n) toz The 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))
z Note that the combinatorial coefficient is defined as follows, although it is not the most efficient way:
C m n m( ) !9
C m nn m n
( , )! ( )!
u �
Argument Association : 1/5Argument Association : 1/5
zArgument association is a way of passing valuesArgument association is a way of passing values from actual arguments to formal arguments.zIf an actual argument is an expression it iszIf an actual argument is an expression, it is
evaluated and stored in a temporary locationfrom which the value is passed to thefrom which the value is passed to the corresponding formal argument.zIf t l t i i bl it l izIf an actual argument is a variable, its value is
passed to the corresponding formal argument.C d h i i blzConstant and (A), where A is variable, are considered expressions.
10
Argument Association : 2/5Argument Association : 2/5
zActual arguments are variables:Actual arguments are variables:
a b cWRITE(*,*) Sum(a,b,c)
x y z
INTEGER FUNCTION Sum(x,y,z)IMPLICIT NONEINTEGER INTENT(IN)::x y z x y zINTEGER,INTENT(IN)::x,y,z
……..END FUNCTION Sum
11
Argument Association : 3/5Argument Association : 3/5
zExpressions 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 NONEINTEGER INTENT(IN)::x y z x y zINTEGER,INTENT(IN)::x,y,z
……..END FUNCTION Sum
12
Argument Association : 4/5Argument Association : 4/5
zConstants 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 NONEINTEGER INTENT(IN)::x y z x y zINTEGER,INTENT(IN)::x,y,z
……..END FUNCTION Sum
13
Argument Association : 5/5Argument Association : 5/5
zA variable in () is considered as an expression. () pDashed line boxes are temporary locations.
(a) (b) (c)WRITE(*,*) Sum((a), (b), (c))
x y z
INTEGER FUNCTION Sum(x,y,z)IMPLICIT NONEINTEGER 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
zFortran 90 functions can be internal or external.Fortran 90 functions can be internal or external.zInternal functions are inside of a PROGRAM, the
main program:main program:PROGRAM program-name
IMPLICIT NONEC NON[specification part][execution part]
CONTAINS CONTAINS [functions]
END PROGRAM program-name
zAlthough 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
zThe right shows PROGRAM TwoFunctions gtwo 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 zThey 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.0END FUNCTION ArithMeanREAL FUNCTION GeoMean(a, b)
IMPLICIT NONE return a REALfunction value.
IMPLICIT NONE REAL, INTENT(IN) :: a, b GeoMean = SQRT(a*b)
END FUNCTION GeoMean
16END PROGRAM TwoFunctions
Scope Rules: 1/5Scope Rules: 1/5
zScope 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 accessibleat certain places.at certain places. zPlaces 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/5zScope 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 glocal to Funct1()
INTEGER, INTENT(IN) :: k REAL :: f, g
.......... END FUNCTION Funct1 END FUNCTION Funct1 REAL FUNCTION Funct2(u, v)
IMPLICIT NONE REAL, INTENT(IN) :: u, v
Scope of u and vlocal to Funct2()
18
.......... END FUNCTION Funct2
END PROGRAM Scope_1
Scope Rules: 3/5Scope Rules: 3/5
zScope Rule #2 :A global entity is visible to all pcontained 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 to
END 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
zScope Rule #2 :A global entity is visible to all pcontained functions.
PROGRAM GlobalIMPLICIT NONEINTEGER :: a = 10, b = 20
¾The first Add(a,b) returns 30¾It also changes b to 30¾Th 2 d WRITE(* *) h 30INTEGER :: a 10, b 20
WRITE(*,*) Add(a,b)WRITE(*,*) bWRITE(*,*) Add(a,b)
¾The 2nd WRITE(*,*) shows 30¾The 2nd Add(a,b) returns 40¾This is a bad side effect
CONTAINSINTEGER FUNCTION Add(x,y)IMPLICIT NONE
¾Avoid using global entities!
INTEGER, INTENT(IN)::x, yb = x+yAdd = b
20END FUNCTION Add
END PROGRAM Global
Scope Rules: 5/5Scope Rules: 5/5zScope 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 FUNCTIONSum() 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() willnot affect the i in PROGRAM.
INTEGER FUNCTION Sum(n) IMPLICIT NONE INTEGER, INTENT(IN) :: n INTEGER :: i s INTEGER :: i, s s = 0 …… other computation ……Sum = s
21END FUNCTION Sum
END PROGRAM Scope_3
Example: 1/4Example: 1/4
zIf 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 u � u � u �( ) ( ) ( )
zTo form a triangle, a, b and cmust 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
zLOGICAL Function TriangleTest() makes g ()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, test2 OG 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
zThis function implements the Heron formula.This function implements the Heron formula.zNote that a, b and cmust 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/4zHere is the main program!
PROGRAM HeronFormula IMPLICIT NONE REAL :: a, b, c, TriangleArea DO DO
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
CONTAINSLOGICAL 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
zA Fortran 90 function takes values from itsA Fortran 90 function takes values from its formal arguments, and returns a single valuewith the function name.with the function name.zA Fortran 90 subroutine takes values from its
formal arguments and returns some computedformal arguments, and returns some computed results with its formal arguments.zA F t 90 b ti d t tzA Fortran 90 subroutine does not return any
value with its name.
26
Subroutines: 2/2Subroutines: 2/2
zThe 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
zIf 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.zS b ti i il t f ti
27
zSubroutines are similar to functions.
The INTENT() Attribute: 1/2The INTENT() Attribute: 1/2
zSince 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).zINTENT(OUT) means a formal argument doeszINTENT(OUT) means a formal argument does
not receive a value; but, it will return a value to its corresponding actual argumentits corresponding actual argument.zINTENT(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
zTwo 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.0Gm = (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 swappedSUBROUTINE Swap(a, b)
IMPLICIT NONE INTEGER, INTENT(INOUT) :: a, bINTEGER :: cINTEGER :: cc = aa = bb = c
29
END SUBROUTINE Swap
The CALL Statement: 1/2The CALL Statement: 1/2
zUnlike C/C++ and Java, to use a Fortran 90Unlike C/C and Java, to use a Fortran 90 subroutine, the CALL statement is needed.zThe CALL statement may have one of the threezThe 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
zThe 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 TestIMPLICIT NONEREAL :: a, bREAD(*,*) a, b
PROGRAM SecondDegreeIMPLICIT NONEREAL :: a, b, c, r1, r2LOGICAL :: OK
CALL Swap(a,b)WRITE(*,*) a, b
CONTAINSSUBROUTINE Swap(x y)
READ(*,*) a, b, cCALL Solver(a,b,c,r1,r2,OK)IF (.NOT. OK) THEN
WRITE(* *) “No root”SUBROUTINE Swap(x,y)IMPLICIT NONEREAL, INTENT(INOUT) :: x,yREAL :: z
WRITE(*,*) “No root”ELSE
WRITE(*,*) a, b, c, r1, r2END IF
z = xx = yy = z
END SUBROUTINE Swap
CONTAINSSUBROUTINE Solver(a,b,c,x,y,L)
IMPLICIT NONEREAL INTENT(IN) :: a b cEND SUBROUTINE Swap
END PROGRAM TestREAL, INTENT(IN) :: a,b,cREAL, INTENT(OUT) :: x, yLOGICAL, INTENT(OUT) :: L………
31END SUBROUTINE Solver
END PROGRAM SecondDegree
More Argument Association: 1/2More Argument Association: 1/2zSince 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) :: u INTEGER :: 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
zThe number of arguments and their types mustThe number of arguments and their types must match properly.zThere is no type-conversion between arguments!zThere is no type-conversion between arguments!
PROGRAM Error SUBROUTINE ABC(p, q)IMPLICIT NONE IMPLICIT NONEINTEGER :: a, b INTEGER, INTENT(IN) :: pINTEGER :: a, b INTEGER, INTENT(IN) :: pCALL ABC(a, b) REAL, INTENT(OUT) :: qCALL ABC(a) ………
CONTAINS END SUBROUTINE ABCtype mismatch
wrong # of arguments………
END PROGRAM Error
g g
33
Fortran 90 Modules: 1/4Fortran 90 Modules: 1/4
zOne may collect all relevant functions andOne may collect all relevant functions and subroutines together into a module. zA module in OO’s language is perhaps close tozA module, in OO s language, is perhaps close to
a static class that has public/private information and methodsand methods.zSo, 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
zA 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
zThe specification part and internal functions and p psubroutines are optional.zA module looks like a PROGRAM, except that itzA 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
zExamples:Examples:Module SomeConstants does not
have the subprogram partModule SumAverage does not
have the specification partMODULE SomeConstants IMPLICIT NONE REAL, PARAMETER :: PI=3.1415926REAL 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, cSum = a + b + c
END FUNCTION Sum REAL FUNCTION Average(a, b, c)
IMPLICIT NONE REAL INTENT(IN) :: a b c REAL, 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/4zThe right module MODULE DegreeRadianConversion g
has both the specification
d
IMPLICIT NONE REAL, PARAMETER :: PI = 3.1415926 REAL, PARAMETER :: Degree180 = 180.0
part and internal functions
CONTAINSREAL FUNCTION DegreeToRadian(Degree)
IMPLICIT NONE functions.zNormally, 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/2zFortran 90 allows a module to have private and p
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).zTo specify public and private, do the following:
PUBLIC :: name 1 name 2 name nPUBLIC :: name-1, name-2, …, name-nPRIVATE :: name-1, name-2, …, name-n
zThe PRIVATE statement without a name makes all entities in a module private. To make some entities visible, use PUBLIC.z d l b d izPUBLIC and PRIVATE may also be used in
type specification:
38INTEGER, PRIVATE :: Sum, Phone_Number
Some Privacy: 2/2Some Privacy: 2/2zAny global entity MODULE TheForce y g y
(e.g., PARAMETER, variable, function,
i
MODULE TheForce IMPLICIT NONE INTEGER :: SkyWalker, PrincessREAL, PRIVATE :: BlackKnight
Is this public?
subroutine, etc) can be in PUBLICor PRIVATE
LOGICAL :: DeathStar REAL, PARAMETER :: SecretConstant = 0.123456PUBLIC :: SkyWalker, PrincessPRIVATE :: VolumeOfDeathStaror PRIVATE
statements.PRIVATE :: VolumeOfDeathStarPRIVATE :: SecretConstant
CONTAINS INTEGER FUNCTION VolumeOfDeathStar()
.......... END FUNCTION WolumeOfDeathStar REAL FUNCTION WeaponPower(SomeWeapon)
.......... END FUNCTION ..........
END MODULE TheForce
39By default, this PUBLIC statementdoes not make much sense
Using a Module: 1/5Using a Module: 1/5zA PROGRAM or MODULE can use PUBLIC entities
in any other modules. However, one must declare this intention (of use).zThere are two forms of the USE statement for
this task:USE module-name
USE module-name, ONLY: name-1, name-2, ..., name-n
zThe first USE indicates all PUBLIC entities of MODULE module-name will be used.zThe second makes use only the names listed after
the ONLY keyword.
40
Using a Module: 2/5Using a Module: 2/5zTwo simple examples:p p
MODULE SomeConstants
PROGRAM Main USE SomeConstantsIMPLICIT NONE MODULE SomeConstants
IMPLICIT NONE REAL, PARAMETER :: PI = 3.1415926REAL, PARAMETER :: g = 980
.......... END PROGRAM Main
, gINTEGER :: Counter
END MODULE SomeConstants
MODULE DoSomethingUSE SomeConstants, ONLY : g, CounterIMPLICIT NONE PI is not available
CONTAINSSUBROUTINE Something(…)……
END SUBROUTINE S thi
41
END SUBROUTINE SomethingEND MODULE DoSomething
Using a Module: 3/5Using a Module: 3/5
zSometimes, the “imported” entities from aSometimes, the imported entities from a MODULE may have identical names with names in the “importing” PROGRAM or MODULE.p gzIf this happens, one may use the “renaming”
feature of USEfeature of USE.zFor each identifier in USE to be renamed, use the
f ll i tfollowing syntax:name-in-this-PROGRAM => name-in-module
zIn this program, the use of name-in-this-PROGRAM is equivalent to the use of name-in-
42module in the “imported” MODULE.
Using a Module: 4/5Using a Module: 4/5zThe following uses module MyModule. g y
zIdentifiers Counter and Test in module MyModule are renamed as MyCounter andMyModule are renamed as MyCounter and MyTest in thismodule, respectively:USE MyModule, MyCounter => Counter &USE MyModule, MyCounter => Counter &
MyTest => Test
zThe following only uses identifiers Ans,zThe 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/5zTwo USE and => examples GravityG is the g in the module;S p
MODULE SomeConstants PROGRAM TestUSE SomeConstants, &
however, g is the “g” in Test
MODULE SomeConstants IMPLICIT NONE REAL, PARAMETER :: PI = 3.1415926REAL, PARAMETER :: g = 980
USE SomeConstants, &GravityG => g
IMPLICIT NONEINTEGER :: g, g
INTEGER :: Counter END MODULE SomeConstants
g……
END PROGRAM Test
MODULE ComputeUSE SomeConstants, ONLY : PI, gIMPLICIT NONEREAL :: Counter
CONTAINS
without ONLY, Counter wouldappear in MODULE Computecausing a name conflict!
44……
END MODULE Compute
causing a name conflict!
Compile Your Program: 1/4Compile Your Program: 1/4
zSuppose a program consists of the mainSuppose a program consists of the main program main.f90 and 2 modules Test.f90and Compute.f90. In general, they can be p g , ycompiled in the following way:f90 main.f90 Test.f90 Compute.f90 –o mainf90 main.f90 Test.f90 Compute.f90 o main
zHowever, 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/4zSuppose 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
zSince 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
zThe above compiles a module/program in file t t f90 t it bj t d t t
46test.f90 to its object code test.o
This means compile only
Compile Your Program: 3/4Compile Your Program: 3/4zSuppose we have modules A, B, C, D and E, and Cpp
uses A, D uses B, and E uses A, C and D.zSince 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.f90f90 –c B.f90f90 –c C.f90 If your compiler is picky, some modules
may have to compiled together!f90 –c D.f90f90 –c E.f90
zN t th t th d i till i t t Th b
may have to compiled together!
zNote that the order is still important. The above generates object files A.o, B.o, C.o, D.oand E.o
47
and E.o
Compile Your Program: 4/4Compile Your Program: 4/4zIf a main program in file prog2.f90 uses p g p g
modules in A.f90 and B.f90, one may compile and generate executable code for prog2 as g p gfollows:
f90 A.o B.o prog2.f90 –o prog2f90 A.o B.o prog2.f90 o prog2
zIf 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
zNote the order of the object files.
48
Example 1Example 1
zThe combinatorial coefficient of m and n (mtn) isThe combinatorial coefficient of m and n (mtn) is Cm,n = m!/(n!u(m-n)!).
MODULE FactorialModuleIMPLICIT NONE
CONTAINSi l( )
PROGRAM ComputeFactorial USE FactorialModuleIMPLICIT NONE INTEGER N R INTEGER 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) usesFactorial(n)
49
Example 2Example 2
zTrigonometric functions use degree.Trigonometric functions use degree.MODULE MyTrigonometricFunctions IMPLICIT NONE
PROGRAM TrigonFunctTest USE MyTrigonometricFunctions
REAL, PARAMETER :: PI = 3.1415926REAL, PARAMETER :: Degree180 = 180.0REAL, PARAMETER :: R_to_D=Degree180/PIREAL, PARAMETER :: D to R=PI/Degree180
IMPLICIT NONE REAL :: Begin = -180.0REAL :: Final = 180.0REAL :: Step = 10.0REAL, PARAMETER :: D_to_R PI/Degree180
CONTAINSREAL FUNCTION DegreeToRadian(Degree)
IMPLICIT NONE ( )
REAL :: Step 10.0REAL :: x x = BeginDO
( i l)REAL, INTENT(IN) :: Degree DegreeToRadian = Degree * D_to_R
END FUNCTION DegreeToRadianREAL FUNCTION MySIN(x)
IF (x > Final) EXITWRITE(*,*) MySIN(x)x = x + Step
END DO yS ( )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
zLegacy Fortran programs do not have internalLegacy Fortran programs do not have internal subprograms in PROGRAMs or MODULEs.zThese subprograms are in separate files ThesezThese subprograms are in separate files. These
are external subprograms that may cause some compilation problems in Fortran 90compilation problems in Fortran 90.zTherefore, 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
zConsider the following triangle area program.Consider the following triangle area program.zHow 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, cREAL :: 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))
gWRITE(*,*) TriangleArea
END PROGRAM HeronFormula
52END FUNCTION Area
file area.f90 file main.f90
INTERFACE Blocks: 3/5INTERFACE Blocks: 3/5
zAn INTERFACE block has the following syntax:g yINTERFACE
type FUNCTION name(arg-1, arg-2, ..., arg-n) type, INTENT(IN) :: arg-1type, 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-1type, 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
zAll external subprograms should be listedAll external subprograms should be listed between INTERFACE and END INTERFACE.zHowever only the FUNCTION and SUBROUTINEzHowever, only the FUNCTION and SUBROUTINE
headings, argument types and INTENTs are needed No executable statements should beneeded. No executable statements should be included.zTh t d t h t b id ti lzThe 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.zThus, a main program or subprogram will be
54able to know exactly how to use a subprogram.
INTERFACE Blocks: 5/5INTERFACE Blocks: 5/5
zReturn to Heron’s formula for triangle area.gzThe following shows the INTERFACE block in a
main program.p gLOGICAL FUNCTION Test(a, b, c)
IMPLICIT NONE REAL INTENT(IN) :: a b c
PROGRAM HeronFormula IMPLICIT NONE INTERFACE 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)Test = test1 AND test2
INTERFACE LOGICAL FUNCTION Test(x,y,z)
REAL, INTENT(IN)::x,y,z END FUNCTION Test Test = 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 INTERFACE IMPLICIT 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