SlideShare a Scribd company logo
1 of 64
Download to read offline
1
FORTRAN PROGRAMMING
AN INTRODUCTION
Arun Umrao
www.sites.google.com/view/arunumrao
DRAFT COPY - GPL LICENSING
2
Contents
0.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
0.2 Formatted I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
0.2.1 Print to Console . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
0.2.2 Read from Console . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
0.2.3 Quotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
0.2.4 Implicit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
0.3 Variables & Datatype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
0.3.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Real . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Complex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Constant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Boolean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Declaration, Initialization & Assignment . . . . . . . . . . . . . . . 14
0.4 FORTRAN Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
0.4.1 Logical Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
0.4.2 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . 16
0.4.3 Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 16
0.5 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
0.5.1 Remove Trailing Blank . . . . . . . . . . . . . . . . . . . . . . . . . 18
0.5.2 Adjust String Blank . . . . . . . . . . . . . . . . . . . . . . . . . . 18
0.5.3 Index of String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
0.5.4 String Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
0.5.5 String Length After Trim . . . . . . . . . . . . . . . . . . . . . . . 19
0.5.6 Lexical Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . 20
0.5.7 Covert to Char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
0.5.8 Repeat Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . 21
0.6 Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
0.6.1 Function Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . 22
0.6.2 Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
0.6.3 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
0.7 Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
0.7.1 If Condition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
0.7.2 If-else Condition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
0.7.3 If-else-if Condition . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
0.7.4 Select Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
0.7.5 Exit Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
0.7.6 Do Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
0.8 Core Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
0.8.1 Abort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
0.8.2 Alarm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
0.8.3 Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
0.8.4 Wait a Moment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
0.8.5 Get Process ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3
0.8.6 Get User ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
0.8.7 Get Host Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
0.9 Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
0.9.1 Arithmetic Function . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Absolute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Imaginary Part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Fraction Part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Whole Part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Ceiling Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Convert to Complex . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Conjugate to Complex . . . . . . . . . . . . . . . . . . . . . . . . . 34
Convert to Double . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Difference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Significant Digit . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Floor Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Convert to Integer . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Maximum Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Minimum Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Modulo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Nearest Integer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Convert to Real . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Exponent Part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Fraction Part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Sum of Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
0.9.2 Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . . 40
sin, cos & tan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
sinh, cosh & tanh . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
asin, acos & atan . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
0.9.3 Algebraic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Exponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Natural Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Common Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Square Root . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
0.9.4 Bitwise Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Bit Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Bit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Logical AND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Clear Bit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Extract Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Set Bit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Exclusive OR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Inclusive OR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Logical Shift Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Logical NOT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
0.10 Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
0.10.1 Rank of Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4
0.10.2 Extent of Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
0.10.3 Shape of Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
0.10.4 Size of Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
0.10.5 Passing Array to Function . . . . . . . . . . . . . . . . . . . . . . . 52
0.10.6 Shift Array Elements . . . . . . . . . . . . . . . . . . . . . . . . . . 53
0.11 Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
0.12 Input Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
0.12.1 Change Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
0.12.2 Get Current Directory . . . . . . . . . . . . . . . . . . . . . . . . . 56
0.12.3 Change Permission Mode . . . . . . . . . . . . . . . . . . . . . . . 56
0.12.4 Open a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
0.12.5 Close a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
0.12.6 Reading File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
0.12.7 Writing File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
0.12.8 Remove a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
0.12.9 Rename a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
0.12.10Current Position of Stream . . . . . . . . . . . . . . . . . . . . . . 60
0.12.11Read Single Char From Instream . . . . . . . . . . . . . . . . . . . 60
0.12.12Write Single Char in Outstream . . . . . . . . . . . . . . . . . . . 61
0.12.13Read Single Char From File Stream . . . . . . . . . . . . . . . . . 61
0.12.14Write Single Char in File Stream . . . . . . . . . . . . . . . . . . . 62
0.12.15File Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
0.13 Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
0.13.1 CPU Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
0.13.2 Convert Time into String . . . . . . . . . . . . . . . . . . . . . . . 63
0.13.3 Date & Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
0.14 Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
0.14.1 Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
0.14.2 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
0.15 Reserved Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
0.1 Introduction
FORTRAN is acronym of the language name “Formula Translation”. FORTRAN follows
code block protocol. Each block if initiated should be closed by using end keyword. For
example
✞
1 program MyProg
print*, "First FORTRAN Program"
3 emd program MyProg
✌
✆
Commenting inside FORTRAN program is also allowed. A new line or any part of
line which started with ‘!’ symbol is assumed as comment in program and excluded
by FORTRAN compilers. Occurrence of next ‘!’ does not have any meaning for that
comment line and it also assumed as comment.
✞
1 print*, " Hello" ! Hello ! string
✌
✆
0.2. FORMATTED I/O 5
In fortran, a line is terminated by end-of-line. Empty lines are also assumed as comments,
they are allowed but compiler just skipped them. Uppercase and lowercase, both types
of characters are allowed in fortran. Multiple values or strings or group of strings and
values can be written in single line by using comma (,) operator.
✞
1 program MyProg
print*, "First FORTRAN Program ", "is this ?"
3 end program MyProg
✌
✆
A block of program codes may be named or unnamed. A named block of program codes
must be closed with end keyword. A syntax of named code block in FORTRAN is given
below:
✞
1 myCode:
<statements >
3 end myCode
✌
✆
IWorking examples of this book are compiled with gfortran compiler of MinGW in Win-
dows platform and default FORTRAN library in Ubuntu OS in Linux platform. Codes
are written with help of NetBean IDE v7 and higher.
0.2 Formatted I/O
In FORTRAN the formatted specifiers consists a string containing a list of edit descriptors
in parentheses. By default, the FORTRAN formatting is right aligned. The descriptors
are:
‘a’ for character variable. It is suffixed with an integer like ‘a10’. It means that 10
places to be used to display the character variable. If character string is larger than 10
then there is no effect of descriptor. If no number is suffixed to ‘a’ then the places are
determined by actual size of the string.
‘i’ is descriptor for integers. It is used as ‘i10.5’, where 10 is field width and 5 is
minimum number of digits to be displayed.
‘f’ is descriptor for real numbers. It is used as ‘f10.5’, where 10 is field width and 5
is precision of displayed real numbers.
‘e’ is descriptor for real numbers also. Used to display numbers in scientific notation.
✞
1 program MyProg
print "(a50)", "First FORTRAN Program "
3 end program MyProg
✌
✆
✞
First FORTRAN Program
✌
✆
6
0.2.1 Print to Console
print keyword is used to print the contents in output console. The following asterisk
tells the compiler about default formatting type of contents. The string ‘Hello World’ is
printed in output console when this FORTRAN program is run.
✞
1 print*, ’Hello World’
end
✌
✆
✞
Hello World
✌
✆
0.2.2 Read from Console
The inputs for variables are read from console by using read operator as
✞
1 read *, x,y,z
✌
✆
Here, three continuous inputs are read and assigned to x, y and z.
✞
1 program MyProg
read *, i, j, k
3 print*, i, j, k
end program MyProg
✌
✆
✞
1
3
6
1 3 6
✌
✆
0.2.3 Quotes
In Fortran, single and double quotes are same. Both represents to string. See the example
below:
✞
program myQuot
2 print*, ’f’
print*, "F"
4 end program myQuot
✌
✆
✞
f
F
✌
✆
0.2. FORMATTED I/O 7
0.2.4 Implicit
Dictionary meaning of implicit is “inherent in the nature of something”, i.e. when a
variable is declared to certain datatype, then its nature is changed to that type until
unless those variables are not re-declared explicitly. Although only integer and real type
constants, variables and arrays have implicit types. But other datatype variables can also
declared implicit type. Syntax for this function is
✞
implicit <data type >
2 !or
implicit <data type > (<var 1>, <var 2>, ....)
✌
✆
Explicit type declarations override implicit type declarations. A program that has only
double datatype variable is declared as
✞
1 implicit double
✌
✆
If a implicit keyword is not used with the variable name, the variable is automatically
declared and accepted by the compiler according to the assigned value to that variable.
✞
1 program myImp
u = 2.0 ! by default real value
3 v = 3.0 ! by default real value
print*, complex(u, v)
5 end program myImp
✌
✆
✞
(2.00000000 , 3.00000000)
✌
✆
If, implicit keyword is used with none keyword, then it is compulsory to declare the data
type of the variable and assign proper values to them, so that the compiler can declare
those variables of proper data type.
✞
1 program myImp
implicit none ! no implicit
3 real :: u, v ! u, v must be declared
u = 2.0 ! real value
5 v = 3.0 ! real value
print*, complex(u, v)
7 end program myImp
✌
✆
✞
(2.00000000 , 3.00000000)
✌
✆
If a variable is fixed to certain datatype, then it can not be used as other data type. See
the example below:
✞
1 program myImp
implicit complex(u, v) ! u, v are complex implicit type
3 u = 2.0 ! complex value without imaginary part
v = 3.0 ! complex value without imaginary part
5 ! complex () function never accepts complex input
8
print*, complex(u, v)
7 end program myImp
✌
✆
Above program will show compile time error as complex() function does not accepts
complex values. It accepts real values. If the implicit variables are re-declared as explicit
type, then they override to the implicit type variables. Above program is modified as
given below:
✞
1 program myImp
implicit complex(u, v) ! u, v are complex implicit type
3 real :: u, v ! explicit re -declaration of u and v
u = 2.0 ! by default real value
5 v = 3.0 ! by default real value
print*, complex(u, v)
7 end program myImp
✌
✆
This program runs successfully and gives output as shown below:
✞
(2.00000000 , 3.00000000)
✌
✆
0.3 Variables & Datatype
Variables are multi-character names used to refer to some locations in memory that holds
a value to which we are using. A variable is equivalent to its assigned value. A variable
may be alphanumeric name with underscore character. First numeric character in a
variable name is not acceptable. Use of spaces and reserved special characters is invalid.
Similarly, use of comma, dot, symbol of question mark, symbols reserved for relational
operations, symbols reserved for bitwise operations, colon and line terminating symbol
are also considered as illegal if used in variable names. Identifiers in FORTRAN are case-
insensitive thus, PRINT and print are completely identical. The maximum character
length of variable in FORTRAN is 31 characters.
0.3.1 Variables
In FORTRAN a variable name and variable data type is separated by ‘::’ symbol. The
syntax of variable declaration is given below:
✞
1 <data type > :: <variable name >
✌
✆
For example, an integer type variable is declared as
✞
1 int :: a ! variable a of integer type
✌
✆
Multiple variables may also be declared in single line, separating them by comma operator
as shown below:
✞
1 <data type > :: <variable name 1>, <variable name 2>, ...
✌
✆
0.3. VARIABLES & DATATYPE 9
Characters
The keyword character is used to define a character type or a string type variable. Length
of string that is assigned to the character type variable is controlled by len keyword. A
character variable is declared as
✞
1 character (len =80) :: <char variable >
✌
✆
Here, len=80 controls the number of characters assigned to the string variable.
✞
1 program MyProg
character (len = 80) :: name
3 read *, name
print*, name
5 end program MyProg
✌
✆
✞
"This is my strig"
This is my strig
✌
✆
Integers
In FORTRAN an integer type variable is declared as
✞
int :: <variable name >
✌
✆
Multiple integer variables can be declared in a single line if they are separated by comma
operator as shown below:
✞
1 int :: <variable name 1>, <variable name 2>, ...
✌
✆
✞
1 program MyProg
integer :: i, j, k
3 read *, i, j
k = i * j
5 print*, k
end program MyProg
✌
✆
✞
2
5
10
✌
✆
Real
A real number is a pure integer or a decimal number. Real numbers in FORTRAN
are always written in their full precision form. This is why, subtraction of 2.5 from 5.2
does not returns 2.7 but it returns 2.69999981 approximating to 2.7, if round-off for first
decimal place is taken. See the example below:
10
✞
1 program myMath
print*, 5.2 - 2.5
3 end program myMath
✌
✆
✞
2.69999981
✌
✆
The real variable is declared as
✞
1 real :: r
✌
✆
Example of real datatype is given below:
✞
1 program real_no
implicit none
3 real :: a = 12.5
print*, a
5 end program real_no
✌
✆
✞
12.5000000
✌
✆
The implicit none statement allows the compiler to check whether our all variable datatypes
are declared properly or not. You must always use implicit none at the beginning of a
program. FORTRAN has definite precision points. There is a method to control the
precision of the real numbers. To do, we use kind keyword as shown below:
✞
1 real (kind =kind (1.0 d0)) :: <variable name >
✌
✆
See the example given below:
✞
1 program real_no
implicit none
3 real (kind (1.0 d0)):: a = 12.5
print*, a
5 end program real_no
✌
✆
✞
12.500000000000000
✌
✆
Complex
A complex number is a number which contains a real part and an imaginary part. A
complex number is represented by (a + bi), where i represents to imaginary part of the
complex number. Here, a and b are real numbers. In FORTRAN, a complex number is
represented as (a, b), which is equal to (a + bi). The complex variable is declared as
✞
1 complex :: z
✌
✆
0.3. VARIABLES & DATATYPE 11
If (a + bi) and (c + di) are two complex numbers then their complex product is given by
Z = (ac − bd) + (ad + bc)i
Take two complex numbers z1 = −2 + i and z2 = 1 − 2i. The complex product of these
two complex numbers is
z3 = z1 × z2 = (−2 + i) × (1 − 2i) = 0 + 5i
The FORTRAN program for this example is given below.
✞
1 program MyProg
complex :: z1 , z2 , z3
3 z1 = (-2, 1)
z2 = (1, -2)
5 z3 = z1 * z2
print*, z3
7 end program MyProg
✌
✆
✞
(0.00000000 , 5.00000000)
✌
✆
Constant
A constant is that data object whose value cannot be changed after initialization. A
literal constant is a constant value without a name, such as 3.14, .true. or .false.,“This”
etc. A named constant is a constant value with a name. Named constants and variables
must be declared at the beginning of a program. Named constants must be declared with
the parameter attribute:
✞
1 real , parameter :: pi = 3.1415
✌
✆
✞
1 program myPtr
implicit none
3
real , parameter :: pi = 3.1415
5 print *, pi
7 ! will show error as we try to change parameter
! values. To see it uncomment following lines.
9 !
11 ! pi = pi + 1.0 ! uncomment it
! print *, pi ! uncomment it
13 end program myPtr
✌
✆
✞
3.14150000
✌
✆
12
Boolean
There are only two logical values: .true. and .false. (note down the dots around the
words true and false). Symbolically, their output is ‘T’ and ‘F’ respectively.
✞
1 program myPtr
implicit none
3
print *, "True value ", .true .
5 print *, "False value", .false.
7 end program myPtr
✌
✆
✞
True value T
False value F
✌
✆
Declaration, Initialization & Assignment
A variable is a reference of a value, and it does not hold value itself. A variable in
FORTRAN is declared as
✞
real :: v ! variable v
✌
✆
A variable can be declared as a parameter by using parameter keyword as shown below
✞
1 real , parameter :: pi ! pi parameter
✌
✆
A variable or a parameter is either public or private. By default a variable or a parameter
has local scope. But its access can be make global by declaring it as public or its access
can be restricted by declaring it as private. The syntax of public and private parameters
are given below:
✞
1 real , parameter , private ::f !private parameter f
real , parameter , public ::g !public parameter g
3 real , public ::h !public variable h
✌
✆
We can initialize a variable by assigning them a value.
✞
1 real , public ::h !declare variable
h=2.05 !assigning value to variable
✌
✆
0.4 FORTRAN Operators
0.4.1 Logical Operator
In FORTRAN there are following logical operators.
0.4. FORTRAN OPERATORS 13
Operator Meaning
.not. Logical NOT, returns true if one value is not equal to other.
.and. Logical AND, returns true if both values are true.
.or. Logical OR, returns true if either of the values are true.
.eqv. Equivalent, returns true if both values are equal
✞
program myLog
2 real :: u, v
u = 2.0
4 v = 3.0
if (u == 2.0 .and. v == 3.0) then
6 print*, "Matched "
end if
8 end program myLog
✌
✆
✞
Matched
✌
✆
The logical operator is evaluated from left to right direction.
0.4.2 Arithmetic Operators
A list of five pure primary arithmetic operators is given in the following table. The list
includes, exponential (represented as y = b∗∗e), multiplication (represented as y = a∗b),
division (represented as y = a/b), addition (represented as y = a + b) and subtraction
(represented as y = a − b) operators.
Operator Meaning
** Exponential
* Multiplication
/ Division
+ Addition
- Subtraction
In above table, the precedence of the operator is high to low in top to bottom direction
in the table.
0.4.3 Relational Operators
A relational operator evaluates values according to the operator. If condition of evaluation
is true then successive block is evaluated otherwise next linked block is evaluated. In
FORTRAN there are following relational operators.
14
Operator Description
< Less than; returns true if left value is less than right
value
> Greater than; returns true if left value is greater than
right value
≤ Less than or equal to; returns true if left value is less
than or equals to right value
≥ Greater than or equal to; returns true if left value is
greater than or equals to right value
== Equals; returns true if left value is exactly equals to
right value
/ = Not equals; returns true if left value is not equals to
right value
See the example below:
✞
1 program if_cond
implicit none
3 integer :: i = 5, j
print*, "Enter an integer "
5 read *, j
if (i < j) then ! less than operator
7 print*, "i is less than j" ! print if true
else ! if condition is false , evaluate this block
9 print*, "i is greater than or equal to j"
end if
11 end program if_cond
✌
✆
✞
Enter an integer
2
i is greater than or equal to j
✌
✆
0.5 Strings
A character string in FORTRAN is declared and initialized as shown below:
✞
1 character (len=<n>) :: <string variable > ! declaration
<string variable >="My String" ! initialization
✌
✆
Here, len=< n > reserves the n character spaces for storing of string. If length size, n,
is less than the string size then only first n characters are stored in the memory space
indicated by string variable and rest of the characters are ignored. Opposite to C, in
which string terminator character (0) is used to terminate the string, in FORTRAN,
integer is used to control the length of string being read or write.
0.5. STRINGS 15
✞
program subStr
2 implicit none
character (len = 5) :: mystr ! declaration
4 mystr = "This is test string."! initialization
print*, mystr
6 end program subStr
✌
✆
✞
This
✌
✆
A part of string can be extracted by using range operator ‘:’.
✞
1 <string variable >(< lower index > : <upper index >)
✌
✆
Here ‘lower index’ and ‘upper index’ are the limits of the extracted substring. If the lower
subscript (‘lower index’) is omitted, it is assumed to be one, and if the upper subscript
(‘upper index’) is omitted, then upper limit is length of the string. Position index in
FORTRAN is started from 1 and continue rather than from 0 and continue.
✞
1 program subStr
implicit none
3 character (len = 50) :: mystr ! declaration
mystr = "This is test string."! initialization
5 print*, mystr (1:5)! string between first & fifth indices
end program subStr
✌
✆
✞
This
✌
✆
Another example with different indices range;
✞
1 program subStr
implicit none
3 character (len = 50) :: mystr ! declaration
mystr = "This is test string."! initialization
5 print*, mystr (4:5) !string between fourth & fifth indices
end program subStr
✌
✆
✞
s
✌
✆
0.5.1 Remove Trailing Blank
trim function is used to adjust trailing blank spaces from a string and inserting leading
blank space. See the example below:
✞
1 program subStr
implicit none
3 character (len = 6) :: mystr ! declaration
mystr = " This "! initialization
16
5 print*, "!!!!!!", trim (mystr), " !!!!!!"
end program subStr
✌
✆
✞
!!!!!! This !!!!!!
✌
✆
In above result, trailing blank space from string “ This ” is removed while leading blank
space is not remove.
0.5.2 Adjust String Blank
adjustl() function is used to adjust string left by removing any leading blanks and inserting
trailing blanks. See the example below
✞
1 program subStr
implicit none
3 character (len = 6) :: mystr ! declaration
mystr = " This "! initialization
5 print*, "!!!!!!", adjustl (mystr), "!!!!!!"
end program subStr
✌
✆
✞
!!!!!! This !!!!!!
✌
✆
adjustr() function is used to adjust string right by removing trailing blanks and inserting
leading blanks.
0.5.3 Index of String
index() function returns the leftmost or rightmost starting position of substring within
given string. Its syntax is
✞
1 index(<string >, <substring >, <true or false >)
✌
✆
If third argument of the function is true, then index returns the rightmost starting position
and if it is false then it returns the leftmost starting position.
✞
1 program myP
character (len = 80) :: name
3 name ="Somnath Temple is in Gujarat "
print*, index(name , "a", .true .)!last a at 27
5 print*, index(name , "a", .false.)!first a at 5
end program myP
✌
✆
✞
27
5
✌
✆
0.5. STRINGS 17
0.5.4 String Length
len() function is used to get the size of string. The use of this function is explained in
the following example.
✞
program subStr
2 implicit none
character (len = 5) :: mystr ! declaration
4 mystr = "This is test string."! initialization
print*, len(mystr)
6 end program subStr
✌
✆
✞
5
✌
✆
0.5.5 String Length After Trim
len() function includes the leading and trailing spaces in the count of string length. We
can use len trim() function to get the length of string without tailing spaces.
✞
1 program myStr
character (len = 10) :: str = "gfortran "
3 integer :: i
do i = 1, len_trim (str)
5 call fput (str(i:i))
end do
7 end program myStr
✌
✆
✞
gfortran
✌
✆
0.5.6 Lexical Comparison
lge(), lgt(), lle() and llt() functions are used to check the lexical comparison between two
strings. The syntax of these functions are
✞
1 lge (<string a>, <string b>)
lgt (<string a>, <string b>)
3 lle (<string a>, <string b>)
llt (<string a>, <string b>)
✌
✆
Here, lge is acronym of ‘lexical greater than or equals to’, lgt is acronym of ‘lexical greater
than’, lle is acronym of ‘lexical less than or equals to’ and llt is acronym of ‘lexical less
than’. The comparison is performed for ‘string a’ to ‘string b’. Functions returns true
(‘T’), if comparison conditions are satisfied, otherwise functions returns false (‘F’).
✞
program myP
2 character (len = 80) :: a
character (len = 80) :: b
4 a = " Somnath temple is in Gujarat "
18
b = " Somnath Temple is in Gujarat "
6 print*, lge(a, b)
end program myP
✌
✆
✞
T
✌
✆
0.5.7 Covert to Char
char() function is used to convert an character code, (character code 0 to character code
255) into corresponding character symbols. For example, character code 65 is equivalent
to character symbol ‘A’ and so on.
✞
1 program myChar
integer :: i
3 do i = 62, 70
print*, char (i)
5 end do
end program myChar
✌
✆
✞
>
?
@
A
B
C
D
E
F
✌
✆
0.5.8 Repeat Concatenation
repeat() function concatenate a string multiple times. Its example is given below:
✞
1 program RepStr
print*, repeat("x", 5)
3 end program RepStr
✌
✆
✞
xxxxx
✌
✆
This function receives two arguments, first the string and second the number of times,
the string is to be concatenate. This function returns string.
0.6 Function
In FORTRAN, a function is declared as
0.6. FUNCTION 19
✞
1 function <func name >(<args vars separated by comma >)
<expressions / statements >
3 end function <func name >
✌
✆
The declared function is called by passing the argument values. Calling of a function is
like
✞
1 <func name >(<args >)
✌
✆
This function returns a single quantity and it does not modify any of its arguments. The
result of a function may also be given a different name when the function is declared as
✞
1 function <func name >(<args var >) result (<result var >)
<expressions / statements >
3 end function <func name >
✌
✆
The result name must be different to the function name. A function can be declared
as a subroutine. A subroutine is different from function as subroutine can modify their
arguments.
✞
1 function prod (m, n) result(a)
real :: m, n
3 real :: a
a = m * n
5 end function prod
program myProg
7 print*, prod (3.0, 12.0)
end program myProg
✌
✆
✞
36.0000000
✌
✆
Remember, function name shall be a valid name. Function name started with numeric
symbol are illegal. Spaces in function name are trimmed, hence spaces are acceptable
upto a limited levels.
✞
1 function pr od _(m, n) result(a)
real :: m, n
3 real :: a
a = m * n
5 end function pr od _
program myProg
7 print*, pr od_ (3.0, 12.0)
end program myProg
✌
✆
✞
36.0000000
✌
✆
20
0.6.1 Function Arguments
An argument’s intention can be changed by using intent() function. For example, if
argument of a function are only to be used then this function is used as
✞
1 real , intent(in)::a
✌
✆
If argument is to be overwrite then use following syntax
✞
1 real , intent(out)::a
✌
✆
If argument is used and overwritten then syntax is used as
✞
1 real , intent(inout)::a
✌
✆
In the following example, a square function is created and called inside from the user
program.
✞
1 function square(p) result (s)
integer :: p
3 s = p * p
end function square
5 program MyProg
integer :: a
7 a = square (5);
print*, a
9 end program MyProg
✌
✆
✞
25
✌
✆
0.6.2 Interface
The interface block contains the name of procedure, and the names and attributes of all
dummy arguments. Its syntax is
✞
1 interface
subroutine <sr >(<v1 >, <v2 >)
3 real , intent(inout)::x,y
end subroutine <sr >
5 end interface
✌
✆
This interface block is placed at the beginning of the program together with the declara-
tion statements.
✞
1 program area
implicit none
3 interface
function circleArea (r)
5 real :: circleArea
real , intent(in) :: r
0.7. CONDITIONS 21
7 end function circleArea
end interface
9 print*, "Area of circle with radius", 2, " is", circleArea (2.0)
end program area
11 function circleArea (r)
implicit none
13 real :: circleArea
real , intent(in) :: r
15 real , parameter :: pi = 3.1415927
circleArea = pi * r * r
17 end function circleArea
✌
✆
✞
Area of circle with radius 2 is 12.5663710
✌
✆
0.6.3 Recursion
A procedure which calls itself directly or indirectly is called a recursive procedure. Its
declaration must be preceded by the word recursive. In recursion, result option must be
used.
✞
1 program myProg
integer :: Recur
3 print*, Recur(3, 12)
end program myProg
5
recursive function Recur(m, n) result(a)
7 integer , intent(in) :: m, n
integer :: a
9 if (m == 0) then
a = m + n
11 else
a = Recur(m - 1, n)
13 end if
end function Recur
✌
✆
✞
12
✌
✆
0.7 Conditions
In FORTRAN, each conditional operator is ended with end operator. Conditions are the
comparison statements those controls the execution of codes inside the conditional blocks.
0.7.1 If Condition
if () provides a way to instruct the program to execute a block of code only if certain
conditions have been met. if is followed by condition and then by then operator. Each
if opened should be closed by using keyword end. The syntax of if () construct is
22
✞
1 if(<conditions >) then ! if condition is true then
statement ! execute the condition .
3 end if
✌
✆
A simple example is
✞
1 program myLog
real :: u
3 u = 2.0
if (u == 2.0) then
5 print*, u
end if
7 end program myLog
✌
✆
✞
2.00000000
✌
✆
0.7.2 If-else Condition
if-else provides a way to instruct the program to execute a block of code only if certain
conditions have been met otherwise execute other block. All the conditions, except than
certain one defined for if, are true for else statement. This is why else has infinite numbers
of true conditions. The syntax of if-else construct is
✞
1 if(<conditions >) then ! if condition is true then
statement one ! execute the statement one.
3 else ! otherwise if condition is false
statement two ! execute the statement two.
5 end if
✌
✆
A simple example is
✞
1 program myLog
real :: u
3 u = 2.5
if (u == 2.0) then
5 print*, u
else
7 print*, 0
end if
9 end program myLog
✌
✆
✞
0
✌
✆
multi-line statement can be written one after another. Expression should be written
successively started with newline. Multi-line expressions within conditional keywords are
ended when a new conditional keyword is started or conditional keyword is closed with
end keyword.
0.7. CONDITIONS 23
✞
1 program myLog
real :: u
3 u = 2.5
if (u == 2.0) then ! begin of single line expression block
5 print*, u ! expression line one
else ! end of single line expression block and
7 ! begin of multiline expression block
print*, 0 ! expression line one
9 print*, 1 ! expressoin line two
print*, 2 ! expression line three
11 end if ! end of multiline expression block
end program myLog
✌
✆
✞
0
1
2
✌
✆
0.7.3 If-else-if Condition
Two if () conditions can be linked by else keyword. if-else-if provides a way to instruct
the program to execute a block of code only if certain conditions have been met otherwise
execute other block conditionally. All the conditions, except than certain ones defined
for the first if, are true for else-if statement. This is why, else-if has infinite numbers of
true conditions. These infinite numbers of conditions are again checked for if statement
and the corresponding block is executed if certain conditions are met, otherwise these
conditions are skipped to next else-if statement. The syntax of the linked if conditions
is
✞
1 if(<condition 1>) then
<expressions 1>
3 else if(< condition 2>) then
<expressions 2>
5 else if(< condition 2>) then
<expressions 3>
7 end if
✌
✆
An if-else-if-else conditional example is given below:
✞
1 program myLog
real :: u
3 u = 2.5
if (u == 2.0) then
5 print*, 2.0
else if (u == 2.5) then
7 print*, 2.5
else
9 print*, 0
end if
24
11 end program myLog
✌
✆
✞
2.50000000
✌
✆
0.7.4 Select Case
Use of a long chain of if-else-if-else-if-else is very complex and less readable. There’s a
solution by using the select-case construct. case() is similar to if statement except that
select- case accepts single argument only and compare the argument value with a range
of defined case() values. It executes the block of statements for which case() is matched.
In contrast to case(), if () is fixed type and executes succeeding block of statements. Each
select, which started at the beginning of a block must be closed by end keyword at the
end of the block. The basic syntax of this construction is given below.
✞
1 select case (<case variable >)
case (<var value 1>)
3 <first statements >
case (<var value 2>)
5 <second statements >
case (<var value 3>)
7 <third statements >
case default
9 <default statements >
end select
✌
✆
Here default case is executed if none of the cases is matched with select variable value.
The case default is optional, but with a case default, it is guaranteed that what ever is the
selector value, one of the statement will be used. There is no order to put case default,
yet in programming conventions, case default is put in the last.
✞
program mySelCase
2 integer :: i
i = 2
4 select case (i)
case (2)
6 print*, 2
case (3)
8 print*, 3
case default
10 print*, ""
end select
12 end program mySelCase
✌
✆
✞
2
✌
✆
case() in select-case switch, also accepts the range value of numbers. The range of numbers
is defined by using range operator ‘:’ (semi-colon). The preceding value of range operator
0.7. CONDITIONS 25
should be less than the succeeding value to the range operator. So, (-10:-9), (-1:0) and
(2:3) etc are acceptable while (3:2) is illegal.
✞
1 program mySelCase
integer :: i
3 i = 3
select case (i)
5 case (2:5)
print*, "Number is between 2 to 5"
7 case (6)
print*, "Number is 6"
9 case default
print*, ""
11 end select
end program mySelCase
✌
✆
✞
Number is between 2 to 5
✌
✆
In case(), we can use discrete ranges from ‘a’ to ‘b’ and ‘c’ to ‘d’ as shown below:
✞
1 case (a:b, c:d)
✌
✆
The literal characters may also be used in the case() if they are written in single quotes.
See the example below:
✞
1 program mySelCase
character (len =1) :: c
3 c=’d’
select case (c)
5 case (’a’:’g’)
print*, "Char is between a to g"
7 case default
print*, "Char is beyond g"
9 end select
end program mySelCase
✌
✆
✞
Char is between a to g
✌
✆
0.7.5 Exit Keyword
exit keyword is used by ForTran to exit from a loop. It should be always within a construct
otherwise the compiler will throw compile time error. exit keyword is also used to break
a continuous loop.
✞
1 program myMath
integer :: i
3 do i = 1, 10
if (i == 5) then
5 exit
26
end if
7 print*, i
end do
9 end program myMath
✌
✆
The output of above program is
✞
1
2
3
4
✌
✆
0.7.6 Do Loop
do operator is used to perform continuous iteration. It also accepts lower limit of iteration,
upper limit of iteration and iteration step size. Its syntax is
✞
do <var >=<from >, <to >
2 <statements >
end do
✌
✆
The syntax of do operator with iteration step size is given below:
✞
1 do <var >=<from >, <to >, <step size >
<statements >
3 end do
✌
✆
Encapsulation of do operator is allowed. The encapsulation of do operator is done as
below syntax.
✞
1 myBlock: do <var >=<from >, <to >, <step size >
<statements >
3 end do myBlock
✌
✆
✞
1 program myArr
!do loop
3 do k = 1, 5
print*, k;
5 end do
end program myArr
✌
✆
✞
1
2
3
4
5
✌
✆
The default step size of iteration is 1 if step size argument is absent or not supplied (see
following line in above example).
0.8. CORE FUNCTIONS 27
✞
1 do k = 1, 5 ! only two inputs for k
✌
✆
Third input or step size argument of do operator, changes the value of k as (k = k+2) <=
5. See the example given below:
✞
1 program myArr
!do loop
3 do k = 1, 5, 2 ! three inputs
print*, k;
5 end do
end program myArr
✌
✆
✞
1
3
5
✌
✆
0.8 Core Functions
0.8.1 Abort
abort() causes immediate termination of the program.
✞
1 program myTest
integer :: i = 1, j = 2
3 if (i /= j) call abort
end program myTest
✌
✆
0.8.2 Alarm
alarm() causes external subroutine to be executed after a delay of time. Its syntax is
✞
alarm(<delay >, <handle >)
2 !of
alarm(<delay >, <handle >, <st >)
✌
✆
If ‘st’ is supplied, it will be returned with the number of seconds remaining until any
previously scheduled alarm was due to be delivered, or zero if there was no previously
scheduled alarm.
✞
1 program myAlarm
external printIt
3 integer st
call alarm(2, printIt , st)
5 call sleep(10)
print *, st
7 end program myAlarm
subroutine printIt
28
9 print*, "Called"
end subroutine printIt
✌
✆
✞
Called
0
✌
✆
0.8.3 Signal
signal() causes external subroutine to be executed with a single integer argument when
signal occurs. If signal is called as a subroutine and the status argument is supplied, it is
set to the value returned by signal. It is used as
✞
program mySig
2 intrinsic signal
external printIt
4 integer st
call signal(2, printIt , st)
6 call sleep(1)
print *, st
8 end program mySig
subroutine printIt
10 print*, "Called"
end subroutine printIt
✌
✆
✞
0
✌
✆
0.8.4 Wait a Moment
sleep() function is used for wait a moment process. The wait time is controlled by the
value supplied to the sleep function. The argument value is number of seconds.
✞
1 program WaitFor
call sleep (5) ! wait for 5 seconds
3 end program WaitFor
✌
✆
0.8.5 Get Process ID
getpid() returns the numerical process id. It is used as
✞
1 print*, getpid ()
✌
✆
✞
1 program myP
character (len = 80) :: a
3 character (len = 80) :: b
a = " Somnath temple is in Gujarat "
5 b = " Somnath Temple is in Gujarat "
0.9. MATHEMATICS 29
print*, lge(a, b)
7 print*, getpid()
end program myP
✌
✆
✞
T
3320
✌
✆
0.8.6 Get User ID
getuid() returns the numerical user id. It is used as
✞
print*, getuid ()
✌
✆
0.8.7 Get Host Name
hostnm() subroutine is called to get the host name of the system. Its use is shown in the
following example.
✞
1 program HostName
character (len =50) ::h
3 call hostnm(h)
print*, h
5 end program HostName
✌
✆
✞
My Computer
✌
✆
0.9 Mathematics
0.9.1 Arithmetic Function
In FORTRAN, the arithmetic evaluation operators are shown in the following table.
Operator Meaning Order
** Exponential RL
* Multiplication RL
/ Division LR
+ Addition LR
– Subtraction LR
The above operators are given from higher to lower precedence order. Except this,
there are several other readymade functions which are used in number theories.
30
Absolute
abs() function is used to get the absolute value of a number. The number may be negative
or positive, but its absolute value shall be always positive. Mathematically, absolute
function is given by
|f(x)| =

−x if x  0
x if x ≥ 0
✞
1 program subStr
print *, abs ( -2.5)
3 end program subStr
✌
✆
✞
2.50000000
✌
✆
Imaginary Part
aimag() returns the imaginary part of a complex number. A complex number has two
real numbers in which one represent to the real part of the complex number and other is
coefficient of the imaginary part of the complex number. A complex number is represented
as
z = a + bi
The imaginary part of this number is bi and real number of imaginary part is b. The
syntax of this FORTRAN function is
✞
1 ip = aimag(z)
✌
✆
Example is
✞
1 program myCompl
complex :: z
3 z = complex (2, 3)
print*, Imaginary part is , aimag(z)
5 end program myCompl
✌
✆
✞
Imaginary part is 3.00000000
✌
✆
Fraction Part
aint() returns the integer part of a fraction number. For example, the integer part or
whole part of a number 2.35 is 2. This function accepts only real numbers. In case
of mathematical expression as argument then all the values except than mathematical
operators must be in real form. For example, 2/3 is not acceptable while 2.0/3.0 is
acceptable.
0.9. MATHEMATICS 31
✞
1 program myMath
real :: z
3 z = 2.35
print*, Whole part is , aint (z)
5 end program myMath
✌
✆
✞
Whole part is 2
✌
✆
Whole Part
anint() returns the whole part of a number. It is similar to ceiling. The argument to this
function should be real. For example, 2/3 is not acceptable while 2.0/3.0 is acceptable.
✞
1 program myMath
real :: z
3 z = 3.552
print*, Whole part is , anint(z)
5 end program myMath
✌
✆
✞
Whole part is 4
✌
✆
Ceiling Value
ceiling() returns the next greatest integer to the given real number. If a real number is
+3.2, then ceiling value will be +4. Similarly, if real value is −2.5, then ceiling value will
be −1. In number-line, the ceiling value of a real number is integer value just following
to it counted from left to right.
✞
1 program CeilValue
print*, Ceiling value of , +3.25 ,is , ceiling (+3.25)
3 print*, Ceiling value of , -3.25 ,is , ceiling ( -3.25)
end program CeilValue
✌
✆
✞
Ceiling value of 3.25000000 is 4
Ceiling value of -3.25000000 is -3
✌
✆
Convert to Complex
cmplx() function converts to the real variables into a complex number. If there is only
one input supplied to this function, then imaginary part becomes zero. Symbolically a
complex number is shown by (a, b).
✞
program myMath
2 real :: z
z = 3.552
32
4 print*, Complex number is , cmplx(z)
end program myMath
✌
✆
✞
Complex number is (3.55200005 , 0.00000000)
✌
✆
Complex conversion with two inputs to the function is shown in the example given below:
✞
1 program myMath
real :: z
3 z = 3.552
print*, Complex number is , cmplx(z, 2)
5 end program myMath
✌
✆
✞
Complex number is (3.55200005 , 2.00000000)
✌
✆
Conjugate to Complex
conjg() returns conjugate of a complex number. If a complex number is given by z = a+bi
then complex conjugate of this number is given by z̄ = a − bi.
✞
1 program myMath
complex :: z
3 z = (2, 3)
print*, Complex conjugate is , conjg(z)
5 end program myMath
✌
✆
✞
Complex conjugate is (2.0000000 , -3.00000000)
✌
✆
Convert to Double
dble() function returns the double precision real number of supplied integer. For example,
an integer 20 is zero precision number while 20.000000000000000 is double precision real
number as its decimal point value is significant upto 15th
decimal places.
✞
1 program myP
print*, dble (20)
3 end program myP
✌
✆
✞
20.000000000000000
✌
✆
0.9. MATHEMATICS 33
Difference
dim() returns the difference of two given numbers. The second argument of dim() function
is subtracted from the first argument of the function. If second argument is greater than
the first argument then result is zero. Mathematically, this function obeys the piecewise
function rule as
dim(a, b) =

a − b if a ≥ b
0 if a  b
See the ForTran program containing dim() function as given below:
✞
1 program myMath
print*, dim (5.2, 2.5)
3 print*, dim (2.5, 5.2)
end program myMath
✌
✆
✞
2.69999981
0.00000000
✌
✆
Significant Digit
Significant Scientific Numbers The digits of mantissa of a number expressed in scien-
tific notation are called significant figures or significant digits. A zero is always significant
if it is right of the non zero digits or right of the decimal. For example
Number Scientific Notation Significant Figures
132.00 1.3200 × 102
5
0.0123540 1.23540 × 10−2
6
-0.125 −1.25 × 10−1
3
25250 2.5250 × 104
5
A point is to be remember that 2.5250 × 104
and 2.525 × 104
are same values but first
has five significant figures while second has four significant figures. In calculation first
number is more accurate because it give the precision value upto fourth place of decimal
while second number gives precision upto third place of decimal.
digits() returns the number of significant digits in a number. In ForTran real numbers
are represented in float data format of scientific notation. In float data format, 24 bits
are used as mantissa and 8 bits are used for exponents. In integer data format, 32 bits
are used in computation of the number. digits() returns mantissa bits. See the following
example:
✞
program myProg
2 print*, digits (2.1000) ! Real number
print*, digits (21000) ! Integer
4 end program myProg
✌
✆
34
✞
24
31
✌
✆
Product
dprod() returns the double precision real product of two supplied numbers. The numbers
must be real type. Application of this function is shown in following example.
✞
program myP
2 print*, dprod(5.0, 3.0)
end program myP
✌
✆
✞
15.000000000000000
✌
✆
Floor Value
floor() returns the greatest integer less than or equal to the given number. If a real
number is +3.2, then floor value will be +3. Similarly, if real value is −2.5, then floor
value will be −3. In number-line, the floor value of a real number is integer value just
preceding to it counted from left to right.
✞
1 program FloorValue
print*, Floor value of , +3.25 ,is , floor (+3.25)
3 print*, Floor value of , -3.25 ,is , floor ( -3.25)
end program FloorValue
✌
✆
✞
Floor value of 3.25000000 is 3
Floor value of -3.25000000 is -4
✌
✆
Convert to Integer
int() converts to real or integer into integer value by truncating the real part of the
number. The argument to this number should be a real type.
✞
program myP
2 print*, int (5.24587)
end program myP
✌
✆
✞
5
✌
✆
0.9. MATHEMATICS 35
Maximum Value
max() returns the maximum value among all the values supplied to the function as its
arguments.
✞
1 program MaxValue
integer :: m
3 m = max (5, 2, 3)
print*, Maximum value is , m
5 end program MaxValue
✌
✆
✞
Maximum value is 5
✌
✆
Minimum Value
min() returns the minimum value among all the values supplied to the function as its
arguments.
✞
1 program MinValue
integer :: m
3 m = min (5, 2, 3)
print*, Minimum value is , m
5 end program MinValue
✌
✆
✞
Minimum value is 2
✌
✆
Modulo
mod() or modulo() returns the mod between two numbers. Mod is remainder value in
division of a number by other number.
✞
1 program myMod
integer :: m
3 m=mod (7, 2)
print*, Mod is , m
5 end program mySum
✌
✆
✞
Mod is 1
✌
✆
Nearest Integer
nint() returns the nearest integer value to a real number. It is similar to rounding off
process. Its example is given below
36
✞
1 program myP
print*, nint (5.24587)
3 print*, nint (5.54587)
end program myP
✌
✆
✞
5
6
✌
✆
Convert to Real
real() converts an integer value into real value. In following example, an integer value ‘6’
is supplied to function real() which returns the real form of this integer.
✞
program myP
2 print*, real (6)
end program myP
✌
✆
✞
6.00000000
✌
✆
Exponent Part
exponent() returns the exponent part of a number. An exponent is denoted by y = ab
.
Here, b is exponent and a is base of exponent. This function uses inequality to get the
exponent of the number. The inequality is
2b−1
≤ y  2b
Where b is exponent.
✞
1 program myP
print*, exponent (1.0)
3 print*, exponent (2.0)
print*, exponent (3.0)
5 print*, exponent (4.0)
print*, exponent (5.0)
7 print*, exponent (6.0)
end program myP
✌
✆
✞
1
2
2
3
3
3
✌
✆
0.9. MATHEMATICS 37
Fraction Part
fraction() returns the fractional part of a number. If a number is written in form of a/b
then fraction part is the decimal part of the result obtained from the division of a/b.
✞
program myMath
2 real :: z
z = 2.0/3.0
4 print*, Fraction part is , fraction (z)
end program myMath
✌
✆
✞
Fraction part is 0.6666666
✌
✆
Sum of Array
sum() function is used for cumulative summation of all the numerical terms of an array.
It is used as
✞
1 program mySum
integer :: x(10) , i, s
3 do i = 1, 10
x(i) = i;
5 end do
s = sum(x)
7 print*, Sum is , s
end program mySum
✌
✆
✞
Sum is 55
✌
✆
0.9.2 Trigonometric Functions
ForTran supports trigonometric calculations. All principle, hyperbolic and inverse trigono-
metric function are inbuilt in the ForTran.
sin, cos  tan
sin(), cos() and tan() returns their respective numerical results when they are supplied by
inputs (arguments) in radian. The angle argument of these functions is called its domain
and their result is called range.
Function Domain Range
sin
h
−
π
2
,
π
2
i
[−1, 1]
cos [0, π] [−1, 1]
tan
h
−
π
2
,
π
2
i
(−∞, ∞)
38
✞
1 program myProg
print*, sin (2.0)
3 print*, cos (2.0)
print*, tan (2.0)
5 end program myProg
✌
✆
✞
0.909297407
-0.416146845
-2.185039760
✌
✆
Principle of trigonometry are applied in the computation of these functions.
sinh, cosh  tanh
sinh(), cosh() and tanh() returns their respective hyperbolic numerical results when they
are supplied by inputs (arguments) in radian. These functions are also called hyperbolic
of the primary trigonometric functions, i.e. sin(), cos() and tan().
✞
1 program myProg
print*, sinh (1.0)
3 print*, cosh (1.0)
print*, tanh (12.0)
5 end program myProg
✌
✆
✞
1.17520118
1.54308069
1.00000000
✌
✆
asin, acos  atan
asin(), acos() and atan() returns their respective angular results in radian when they are
supplied by inputs (arguments) in number. These functions are also called inverse of the
primary trigonometric functions, i.e. sin(), cos() and tan().
Function Domain Range
sin−1
[−1, 1]
h
−
π
2
,
π
2
i
cos−1
[−1, 1] [0, π]
tan−1
(−∞, ∞)
h
−
π
2
,
π
2
i
✞
1 program myProg
print*, asin (1.0)
3 print*, acos (1.0)
0.9. MATHEMATICS 39
print*, atan (12.0)
5 end program myProg
✌
✆
✞
1.57079637
0.00000000
1.48765504
✌
✆
Principle of trigonometry are applied in the computation of these functions.
0.9.3 Algebraic Functions
Exponent
exp() function is equivalent to ex
, where x is a real number. e is universal natural
logarithmic base. The algebraic series representation of exp(x) is given by
ex
= 1 + x +
x2
2!
+
x3
3!
+
x4
4!
+ . . .
exp(1) is equal to 2.718281828.
✞
1 program myMath
print*, exp (2.0)
3 end program myMath
✌
✆
✞
7.38905621
✌
✆
Natural Log
log() is logarithm of a number about natural base e. Natural logarithm of a number can
be converted into the common logarithm by using relation
loge(a) =
log10(a)
loge(a)
Or
loge(a) = 2.30258 × log10(a)
✞
1 program myMath
print*, log (2.0)
3 end program myMath
✌
✆
✞
0.693147182
✌
✆
40
Common Log
log10() is logarithm of a number about common base 10. Common base logarithm depends
on the natural logarithm as
loge(a) = 2.30258 × log10(a)
✞
1 program myMath
print*, log10 (2.0)
3 end program myMath
✌
✆
✞
0.301030010
✌
✆
Square Root
sqrt() returns the square root value of a number. Square root of a number is written as
y =
√
x.
✞
1 program myMath
print*, Square root , 2.254 ,  is , sqrt (2.254)
3 end program myMath
✌
✆
✞
Square root 2.254 is 1.50133276
✌
✆
If the number is negative then there is “Argument of SQRT at (1) has a negative value”
error.
0.9.4 Bitwise Functions
Bitwise functions are used in mathematical operations related to binary arithmetic.
Bit Size
bit size() returns the number of bits of a model. The input argument of this function is
a binary form of number.
✞
1 program myMath
print*, bit_size (10001001)
3 end program myMath
✌
✆
✞
32
✌
✆
0.9. MATHEMATICS 41
Bit Testing
btest() tests whether a bit is zero or one at specific index. It accepts two inputs, first
binary number and second bit index. The bit index value is started from 0 to continue.
✞
1 program myMath
print*, btest (10001001, 2) !3rd bit from LSB , F
3 print*, btest (10001001, 3) !4th bit from LSB , T
end program myMath
✌
✆
✞
F
T
✌
✆
Logical AND
iand() returns the result of two numbers which are bitwise ANDed logically. Assume two
numbers 50 and 81. In AND operation, result bit is high if all of the input bits are high.
The binary AND operation is performed as
✞
00110010 = 50
2 01010001 = 81
----------------AND
4 00010000 = 16
✌
✆
✞
program BitWise
2 print *, iand (50, 81)
end program BitWise
✌
✆
✞
16
✌
✆
Clear Bit
ibclr() clears the bit of a number at specific index from the LSB side. Position index is
started from 0 to 7 for one byte long data. If the bit at the index is 1, it is reset to 0. Its
description is given below:
✞
1 00110010 = 50
%clear 2nd bit from LSB , index = 1
3 00110000 = 48
✌
✆
Example in FORTRAN is given below:
✞
1 program BitWise
print *, ibclr(50, 1)
3 end program BitWise
✌
✆
✞
48
✌
✆
42
Extract Bits
ibits() function extracts the bits from a number and returns the number equivalent to
the extracted bits. The index position and length of bits to be extracted are specified by
index and length.
✞
1 ibits(number , index from LSB , number of bits from LSB to MSB )
✌
✆
Example is given below:
✞
1 program myMath
!150D = 1001 0110 B
3 print*, ibits(150, 0, 8)!From LSB 0 to 8 to MSB = 10010110
print*, ibits(150, 1, 8)!From LSB 1 to 8 to MSB = 1001011
5 print*, ibits(150, 2, 8)!From LSB 2 to 8 to MSB = 100101
print*, ibits(150, 3, 8)!From LSB 3 to 8 to MSB = 10010
7 print*, ibits(150, 4, 8)!From LSB 4 to 8 to MSB = 1001
print*, ibits(150, 5, 8)!From LSB 5 to 8 to MSB = 100
9 end program myMath
✌
✆
✞
150
75
37
18
9
4
✌
✆
Set Bit
ibset() function sets the bit in a number at specific index from LSB side. Position index
is started from 0 to 7 for one byte long data. If the bit at the index is 0, it is reset to 1.
Its description is given below:
✞
00110010 = 50
2 %set 3rd bit from LSB , index = 2
00110110 = 50
✌
✆
Example in FORTRAN is given below:
✞
1 program BitWise
print *, ibset(50, 2)
3 end program BitWise
✌
✆
✞
54
✌
✆
0.9. MATHEMATICS 43
Exclusive OR
ieor() returns the result of two numbers which are ORed exclusively. Assume two numbers
50 and 81. In XOR operation, result bit is high if only one of the two input bits is high.
The binary XOR operation is performed as
✞
1 00110010 = 50
01010001 = 81
3 ----------------XOR
01100011 = 99
✌
✆
✞
program BitWise
2 print *, ieor (50, 81)
end program BitWise
✌
✆
✞
99
✌
✆
Inclusive OR
ior() returns the result of two numbers which are ORed inclusively. Assume two numbers
50 and 81. In OR operation, result bit is high if any or all of the input bits are high. The
binary OR operation is performed as
✞
1 00110010 = 50
01010001 = 81
3 ----------------OR
01110011 = 115
✌
✆
✞
program BitWise
2 print *, ior(50, 81)
end program BitWise
✌
✆
✞
200
✌
✆
Logical Shift Bits
ishft() shifts the bits leftward or right word by a specific position. Assume a number 50
in decimal which is 00110010 (8-bit form). The logical bit shift by +2 (left shift) places
of the binary form of the number is 0011001000 which is equals to 200 in decimal. The
example in FORTRAN is given below:
✞
1 program BitWise
print *, ishft(50, 2)
3 end program BitWise
✌
✆
44
✞
200
✌
✆
Again, take the same number 50 in decimal which is 00110010 (8-bit form). The logical
bit shift by −2 (right shift) places of the binary form of the number is 00001100 (8-bit
form) which is equals to 12 in decimal. The example in FORTRAN is given below:
✞
1 program BitWise
print *, ishft(50, -2)
3 end program BitWise
✌
✆
✞
12
✌
✆
Remember that in left shift by +n places, n number of 0 bits are post-fixed to the binary
number. Similarly in case of right shift by −n places, n numbers of bits from the binary
form of the number are removed from LSB side.
Logical NOT
not() returns the logical complements of the bits of supplied number. Assume a number 50
in decimal which is 00110010 (8-bit form). The logical NOT (complement) of the binary
form of the number is 11001101 which is equals to 205 in decimal or 205 − 256 = −51 in
signed form. The example in FORTRAN is given below:
✞
1 program BitWise
!50D = 00110010 B
3 !NOT of 50D = 11001101 B
!11001101 B = 205D = -51D
5 print *, not (50)
end program BitWise
✌
✆
✞
-51
✌
✆
0.10 Array
In ForTran, arrays are declared as
✞
1 integer :: array name ( number of elements )
✌
✆
Here, keyword integer specified the data type of array. Array name is valid literals which
identify the array. Each array declared must have predefined size. See the example below
✞
1 program myArr
!Array of 5 elements
3 integer :: myA (5)
!Add values to array
5 do k = 1, 5
myA(k) = 2 * k
0.10. ARRAY 45
7 end do
!Print array elements
9 do k = 1, 5
print*, myA(k)
11 end do
end program myArr
✌
✆
✞
2
4
6
8
10
✌
✆
A multidimensional array is declared as
✞
1 integer :: array name ( rows dim , cols dim )
✌
✆
Here, ‘rows dim’ is number of rows and ‘cols dim’ is number of columns in an integer
datatype array.
✞
1 program myArr
!Array of 2 rows 5 cols
3 integer :: myA(2, 5)
!Add values to array
5 do k = 1, 2
do l = 1, 5
7 myA(k, l) = k + l
end do
9 end do
!Print array elements
11 do k = 1, 2
do l = 1, 5
13 print*, myA(k, l)
end do
15 end do
end program myArr
✌
✆
✞
2
3
4
5
6
3
4
5
6
7
✌
✆
Another way to declared an array is shown below:
46
✞
real , dimension (4) :: array var  ! one row
✌
✆
The dimension of an array is controlled with dimension keyword followed by number of
element.
✞
1 program myArr
!Array of 4 elements
3 integer , dimension (4) :: myA
!Add values to array
5 do l = 1, 4
myA(l) = 2 * l
7 end do
!Print array elements
9 do l = 1, 4
print*, myA(l)
11 end do
end program myArr
✌
✆
✞
2
4
6
8
✌
✆
If the number of elements assigned to the array are larger than the dimension of the array
then program returns invalid memory reference error.
✞
program myArr
2 !Array of 4 elements
integer , dimension (4) :: myA
4 !Try to add 5 values to array
do l = 1, 5
6 myA(l) = 2 * l
end do
8 end program myArr
✌
✆
A two dimensional array is declared as
✞
real , dimension (2, 4) :: array var  ! 2 rows 4 columns
✌
✆
✞
1 program myArr
!Array of 2 row 5 cols
3 integer , dimension (2, 5):: myA
!Add values to array
5 do k = 1, 2
do l = 1, 5
7 myA(k, l) = k + l
end do
9 end do
!Print array elements
0.10. ARRAY 47
11 do k = 1, 2
do l = 1, 5
13 print*, myA(k, l)
end do
15 end do
end program myArr
✌
✆
✞
2
3
4
5
6
3
4
5
6
7
✌
✆
The array vector could also have been declared with explicit lower bounds:
✞
real , dimension (1:5) :: array var  ! row of 5 elements
✌
✆
In above type declaration of matrix, (1:5) represents to the index of elements. For exam-
ple, array element should be indexed from ‘1’ to ‘5’. See the example below:
✞
1 program myArr
!array of 5 elements
3 integer , dimension (1:5) :: myA
!add values to array
5 do l = 1, 5
myA(l) = 2 * l
7 end do
!print elements of array
9 do l = 1, 5
print*, myA(l)
11 end do
end program myArr
✌
✆
✞
2
4
6
8
10
✌
✆
All the following type declaration statements are legal:
✞
1 real , dimension ( -10:8) :: array var  ! 1-dim array with 19
elements
integer , dimension (-3:3, -20:0, 1:2) :: grid var  ! 3-dim array
✌
✆
48
The number of elements of the integer array ‘grid var’ is 7 × 21 × 2 = 294. There
is restriction of use of arrays with more than 7 dimensions. In following example two
dimensional grid is used for matrix generation using ranged index.
✞
program myArr
2 !two dimensional array 5 rows 2 cols
!row indexed from 1 to 5
4 !col indexed from 2 to 3
integer , dimension (1:5, 2:3) :: myA
6 !add values to array
do k = 1, 5
8 do l = 2, 3
myA(k, l) = 2 * l + k
10 end do
end do
12 !print elements of array
do k = 1, 5
14 do l = 2, 3
print*, myA(k, l)
16 end do
end do
18 end program myArr
✌
✆
✞
5
7
6
8
7
9
8
10
9
11
✌
✆
0.10.1 Rank of Array
Rank of an array is number of array’s dimensions. For one dimensional array has rank 1.
For two dimensional array has rank of 2. Two dimensional array becomes a matrix. In
case of matrix, to get the rank, matrix should be in echelon form. Assume a matrix, A is
in echelon form
A =

1 0
0 1

and it has two non zero rows, then the rank of matrix is 2. rank() function is used to get
the number of rank of a matrix.
✞
program myArray
2 implicit none
integer , dimension (6) :: myArrA
4 integer , dimension (6, 2) :: myArrB
0.10. ARRAY 49
print*, Rank of myArrA , rank ( myArrA)
6 print*, Rank of myArrB , rank ( myArrB)
end program myArray
✌
✆
✞
Rank of myArrA 1
Rank of myArrB 2
✌
✆
0.10.2 Extent of Array
Extent of an array is the number of elements counted along a dimension.
0.10.3 Shape of Array
The shape of an array is a one-dimensional integer array, containing the number of ele-
ments in each dimension. The shape of array is denoted by m × n × . . . in which m, n,
. . . represents to each dimension of the array.
✞
program test_shape
2 integer , dimension (-1:1, -1:2) :: A
write(*, *) shape(A)
4 end program
✌
✆
✞
3 4
✌
✆
0.10.4 Size of Array
Size of array specified the number of elements present in an array. An array having
dimension m rows and n columns has m × n size or element. size() function is used to
get the number of element in matrix or dimension of the row.
✞
1 program myArray
implicit none
3 integer , dimension (6) :: myArr ! declaration
print*, size (myArr)
5 end program myArray
✌
✆
✞
6
✌
✆
0.10.5 Passing Array to Function
Function in ForTran is called sub-routine. call operator is used to call a sub-routine from
a program or from a sub-routine. Arrays can be passed to a function (sub-routine) as its
argument.
50
✞
1 subroutine sname (arg )
.....................
3 end subroutine sname 
!
5 program pname 
call sname ( array name )
7 end program pname 
✌
✆
See the following example.
✞
1 program passArray
implicit none
3 integer , dimension (5) :: myArray
integer :: i
5 !call subroutine and pass array as its argument
call AddValueToArr ( myArray)
7 !call subroutine to print array elements
call PrintArrValues (myArray)
9 end program passArray
!
11 subroutine AddValueToArr (a)
implicit none
13 integer , dimension (5) , intent (out) :: a
integer :: i
15 do i = 1, 5
a(i) = i
17 end do
end subroutine AddValueToArr
19 !
subroutine PrintArrValues (a)
21 integer , dimension (5) :: a
integer :: i
23 do i = 1, 5
Print *, a(i)
25 end do
end subroutine PrintArrValues
✌
✆
✞
1
2
3
4
5
✌
✆
0.10.6 Shift Array Elements
cshift() performs a circular shift on elements of array along the dimension. This function
takes three argument. Last argument is dimension number. If it is not given to function
then it is taken 1 by default. Its value should not be larger than rank of the array or
matrix. The syntax of this function is
0.11. POINTER 51
✞
1 cshift(array , shift positions , array dim )
✌
✆
Shift positions may be positive or negative value. If it is positive value then array shift
is from left to right otherwise right to left.
✞
1 program ArrayShift
integer :: k(5) , i
3 do i = 1, 5
k(i) = i
5 end do
k = cshift(k, 2, 1)
7 do i = 1, 5
print*, k(i)
9 end do
end program ArrayShift
✌
✆
✞
3
4
5
1
2
✌
✆
✞
1 program ArrayShift
integer :: k(5) , i
3 do i = 1, 5
k(i) = i
5 end do
k = cshift(k, -2, 1)
7 do i = 1, 5
print*, k(i)
9 end do
end program ArrayShift
✌
✆
✞
4
5
1
2
3
✌
✆
0.11 Pointer
A pointer variable is declared with the pointer attribute. A pointer variable that is an
array must be a deffered-shape array. A pointer is allocated to a variable as
✞
1 integer , pointer :: p ! pointer to integer
real , pointer , dimension (:) :: rp !pointer to one dim array
3 real , pointer , dimension (:,:) :: r2p ! pointer to two dim array
✌
✆
52
A pointer in FORTRAN points to an area of dynamically allocated memory or a data
object of the same type as the pointer with the target attribute. Space for pointer is
allocated by using allocate() function.
✞
1 integer , pointer :: p ! pointer to integer
allocate (p) ! allocate dynamic memory to p
✌
✆
✞
program myPtr
2 implicit none
!pointer myP
4 integer , pointer :: myP
6 !allocate dynamic memory space for variable myP
allocate (myP)
8
myP = 1
10 print *, myP
12 myP = myP + 4
print *, myP
14
end program myPtr
✌
✆
✞
1
5
✌
✆
A target object is an ordinary variable, with space set aside for it. To act as a target for
a pointer is must be declared with the target attribute.
✞
program myP
2 integer , pointer :: p1
integer , target :: p2
4 p1=p2
end program myP
✌
✆
The function associated() returns the association between pointer and its target. It
returns true, if the pointer is associated with target otherwise returns false. Its syntax is
✞
1 associated (p1 , p2)
✌
✆
loc() function returns the address of the variable. It is used as
✞
1 program VarAddress
character (len =50) ::h
3 print*, loc(h)
end program VarAddress
✌
✆
✞
2293534
✌
✆
0.12. INPUT OUTPUT 53
0.12 Input Output
Program needs to fetch data or write data to a local file. FORTRAN has ability to read
or write data from or to a file.
0.12.1 Change Directory
chdir() function is used to change the current working directory. The current working
directory is directory where FORTRAN puts its temporary files or creates and read stored
data files.
✞
1 program myChdir
character (len = 255) :: path
3 call getcwd(path )
write(*, *) trim (path )
5 call chdir(C:/)
call getcwd(path )
7 write(*, *) trim (path )
end program myChdir
✌
✆
✞
C: NetBeansProjects fortran
C:
✌
✆
0.12.2 Get Current Directory
getcwd() function returns the current working directory. It returns full path of the current
working directory.
✞
program myChdir
2 character (len = 255) :: path
call getcwd(path )
4 write(*, *) trim (path )
end program myChdir
✌
✆
✞
C: NetBeansProjects fortran
✌
✆
0.12.3 Change Permission Mode
chmod()function changes the permission mode of the file. Here, mode of file are scalar
characters of default kind giving the file permission. Mode uses the same syntax as the
chmod utility as defined by the POSIX standard. The argument shall either be a string
of a non-negative octal number or a symbolic mode.
✞
1 program myDir
implicit none
3 integer :: st
call chmod(’test .dat ’, ’u + x’, st)
54
5 print *, ’Status: ’, st
end program myDir
✌
✆
✞
Status: 1
✌
✆
The POSIX based file permission modes are
Mode Permission Description
0.12.4 Open a File
To open a file to make it available to the program, open() function is used. Its syntax is
✞
1 open (unit =u, file =name , status=st , action=act )
✌
✆
Here ‘u’ is a positive integer. Unit number should be positive ranging from 1 to 99. This
number is handle which identify to the file stream through which compiler either read
or write. ‘st’ is status of file. It can be “new” if file is not exists or “old” if file exists
is system. “replace” created a new file if file does not exists and replaces to file if it
exists. “scratch” is temporary file used during the program run. When program ended,
it is deleted. ‘name’ is name of the file. ‘act’ is the action to be performed into the file
and is similar to the mode of operation in C. The file action mode in FORTRAN are
“read”, “write” and “readwrite”. “read” is used to read from file, “write” is used to write
something to the file and “readwrite” is used to read as well as write. There are another
option which is used to check the status of file. It is ‘iostat’. If the file is correctly opened,
‘iostat’ is set to zero otherwise positive integer.
✞
1 program open_file
implicit none
3 character (50) :: line
integer :: err
5 ! open file a.txt with stream id 5
open (unit = 5, file = a.txt, status = old, iostat = err)
7 if (err  0) then
print*, unable to open file .
9 stop
end if
11 do
! read line by line of the a.txt
13 read (5, (a), iostat = err) line
if (err == -1) exit ! EOF detected
15 print*,line ;
end do
17 close (5)
end program open_file
✌
✆
✞
This is file a.txt
✌
✆
0.12. INPUT OUTPUT 55
By default, FORTRAN creates a file in the current directory. But if file name is preceded
by a slash (‘/’) then file is opened in root directory.
✞
1 open (unit =u, file =/name , status=st , action=act )
✌
✆
0.12.5 Close a File
Each file which is opened by open() function, must be closed by close() function. Its
syntax is
✞
1 close(unit =u, iostat=state , status=st )
✌
✆
✞
1 program open_file
implicit none
3 integer :: err
! open file a.txt with stream id 5
5 open (unit = 5, file = a.txt, status = old, iostat = err)
if (err  0) then
7 print*, unable to open file .
stop
9 end if
close (5)
11 end program open_file
✌
✆
✞
This is file a.txt
✌
✆
0.12.6 Reading File
To read data from a file, read() function is used. Its syntax is
✞
1 read (unit =u, fmt=read format ) read buffer variable 
✌
✆
Here, ‘u’ is the stream number of the previously opened file.
✞
1 program open_file
implicit none
3 character (50) :: line
integer :: err
5 ! open file a.txt with stream id 5
open (unit = 5, file = a.txt, status = old, iostat = err)
7 if (err  0) then
print*, unable to open file .
9 stop
end if
11 do
! read line by line of the a.txt
13 read (5, (a), iostat = err) line
if (err == -1) exit ! EOF detected
56
15 print*,line ;
end do
17 close (5)
end program open_file
✌
✆
✞
This is file a.txt
✌
✆
0.12.7 Writing File
To write contents into an opened file, write() function is used. Its syntax is
✞
1 write(unit =u, fmt=write format ) content buffer variable 
✌
✆
See the example given below:
✞
1 program open_file
implicit none
3 character (50) :: line
integer :: err
5 open (unit = 5, file = a.txt, status = old, iostat = err)
if (err  0) then
7 print*, unable to open file .
stop
9 end if
write(5, (a), iostat = err) This is test string.
11 close (5)
end program open_file
✌
✆
If write() function is used as
✞
write(*, *)
✌
✆
then the output is written in the output console.
✞
1 program open_file
implicit none
3 write(*, *) This is test string.
end program open_file
✌
✆
✞
This is test string.
✌
✆
0.12.8 Remove a File
To remove an existing file, unlink() function is used. If a file is already open, and being
removed, then the file should be closed before using this function.
0.12. INPUT OUTPUT 57
✞
1 program myStr
call unlink(a.txt)
3 end program myStr
✌
✆
It will remove the existing file ‘a.txt’.
0.12.9 Rename a File
To rename a file, create a new file with new name, copy the contents from the old file into
this new file. After successful copying of data, delete the old file.
✞
1 program rename_file
implicit none
3 character (20) :: of , rnf
character (50) :: line
5 integer :: err
read *, of
7 read *, rnf
! open a old file with stream id 5
9 open (unit = 5, file = of , status = old, iostat = err)
if (err  0) then
11 print*, unable to open file , of
stop
13 end if
! open a new file with stream id 6
15 open (unit = 6, file = rnf , status = new, iostat = err)
if (err  0) then
17 print*, unable to open file , rnf
stop
19 end if
do
21 ! read line by line from the old file
read (5, (a), iostat = err) line
23 if (err == -1) exit ! EOF detected
! write contents to the new file
25 write(6, (a), iostat = err) line ;
end do
27 close (5)
close (6)
29 ! delete old file
call unlink(of)
31 end program rename_file
✌
✆
To check the result, open the project directory and you will see that file a.txt is not
existed in the directory. The ready-made subroutine rename() can be used to rename the
existing file. It is used as
✞
1 call rename(old path , new path , st )
✌
✆
‘sr’ returns the status of file renaming operation.
58
0.12.10 Current Position of Stream
ftell() retrieves the current position within an open file. This intrinsic is provided in both
subroutine and function forms; however, only one form can be used in any given program
unit.
✞
1 program fTell
integer :: i
3 open (10, file = a.txt)
call ftell(10, i)
5 write(*, *) i
close (10)
7 end program fTell
✌
✆
✞
0
✌
✆
0.12.11 Read Single Char From Instream
fget() function is used to get the input contents from instream. Its syntax is
✞
1 fget (string var , status var )
✌
✆
See the example below:
✞
1 program myStr
integer :: st , i = 1
3 character (len = 10) :: str = 
write (*, *) Enter text :
5 !Receive the contents .
!At end of line ENTER key is pressed
7 do
call fget (str(i:i), st)
9 if (st /= 0 .OR. i  10) exit
i = i + 1
11 end do
write (*, *) trim (str)
13 end program myStr
✌
✆
✞
Enter text :
this is my string
this is my
✌
✆
0.12.12 Write Single Char in Outstream
fput() function is used to put a single character in stream mode to stdout by bypassing
normal formatted output.
0.12. INPUT OUTPUT 59
✞
1 program myStr
character (len = 10) :: str = gfortran 
3 integer :: i
do i = 1, len_trim (str)
5 call fput (str(i:i))
end do
7 end program myStr
✌
✆
✞
gfortran
✌
✆
0.12.13 Read Single Char From File Stream
fgetc() function is used to read a text file character by character. This function is used as
✞
1 fgetc(file stream , char var , position status )
✌
✆
Example is given below:
✞
1 program myStr
integer :: st
3 character :: c
open (unit = 10, file = a.txt, status = old)
5 do
call fgetc(10, c, st)
7 if (st /= 0) exit
call fput (c)
9 end do
close (10)
11 end program myStr
✌
✆
✞
Hi , my name is arun .
✌
✆
0.12.14 Write Single Char in File Stream
fputc() function is used to put a single character in file stream by bypassing normal
formatted output.
✞
1 program myStr
character (len = 10) :: str = gfortran 
3 open (unit =10, file = a.txt, status = new)
do i = 1, len_trim (str)
5 call fputc(10, str(i:i))
end do
7 close (10)
end program myStr
✌
✆
See the file ‘a.txt’ in the project directory. The contents “gfortran” is wrote in this file.
60
0.12.15 File Number
fnum() returns the POSIX file descriptor number corresponding to the open FORTRAN
I/O unit UNIT.
✞
program myStr
2 integer :: i
open (unit =10, status = scratch )
4 i = fnum (10)
print *, i
6 close (10)
end program myStr
✌
✆
✞
3
✌
✆
0.13 Time
0.13.1 CPU Time
cpu time() function is used to get the CPU time at the moment.
✞
1 program ExecTime
real :: i
3 call cpu_time (i)
print*, i
5 end program ExecTime
✌
✆
✞
3.12500000 E-02
✌
✆
Execution time of a code program, we get the two consecutive CPU times. First at the
beginning of the code and second at the end of code. The difference between two is time
taken by CPU to execute the codes.
✞
1 program ExecTime
integer :: k
3 real :: i, f
call cpu_time (i)
5 do k = 1, 5000000
if (mod(k, 1000000) == 0) then
7 print*, k
end if
9 end do
call cpu_time (f)
11 print*, (Time = , f - i,  seconds .)
end program ExecTime
✌
✆
0.13. TIME 61
✞
1000000
2000000
3000000
4000000
5000000
(Time = 1.56250000 E -02 seconds .)
✌
✆
0.13.2 Convert Time into String
ctime() converts a system time into a string. The converted string contains day name,
month name, day of month, time in hours, minutes  second and year.
✞
program myTime
2 integer (8) :: i
character (len = 30) :: date
4 i = time8()
call ctime(i, date )
6 print *, Date time is , date
end program myTime
✌
✆
✞
Date time is Fri Feb 3 11:22:59 2017
✌
✆
0.13.3 Date  Time
date and time() gets the corresponding date and time information from the real-time
system clock. Date is in form of yyyymmdd. Time has form hhmmss.mls. Zone has
form (+-)hhmm, representing the difference with respect to Coordinated Universal Time
(UTC). Unavailable time and date parameters return blanks.
✞
1 program myTime
character (8) :: date !8 bytes long , yyyymmdd
3 character (10) :: time !10 bytes long , hhmmss.mls
character (5) :: zone !5 bytes long , +-hhmm
5 integer , dimension (8) :: values !8 parts of date  time
call date_and_time (date , time , zone , values)
7 print (a,2x,a,2x,a), date , time , zone
print (8i5), values
9 end program myTime
✌
✆
✞
201723 115847.406 +530
2017 2 3 330 11 58 47 406
✌
✆
62
0.14 Data Structures
0.14.1 Structure
In FORTRAN, there is a special data type commonly known as derived datatype or
structure. It is used to object with different type of variables. The derived datatype is
declared as
✞
type :: Name 
2 character :: lable 
int :: age 
4 end type Name 
✌
✆
We can create object type using type keyword as
✞
type (Name ):: x
✌
✆
The components of the structure can be accessed by using component selector character
% as
✞
1 type (Name ):: x
x%lable  = K
3 x%age  = 10
✌
✆
0.14.2 Modules
In FORTRAN, a module is package of code which can be used recursively as and when
required. A module is declared with module keyword.
✞
1 module module name 
implicit none
3 specification statements 
contains
5 procedures 
end module module name 
✌
✆
The specification statements includes local variables, parameters etc. The procedure
block contains codes functions, subroutine etc. Modules are accessed by use command.
To access the module use following syntax
✞
use module name 
✌
✆
Subroutines or procedures of module are accessed by call() function.
✞
1 call procedure 
call subroutine 
✌
✆
0.14. DATA STRUCTURES 63
✞
module myMod
2 implicit none
real , parameter :: pi = 3.1415926536
4 contains
function area (r) result (a)
6 real :: a, r
a = pi * r * r
8 end function area
10 end module myMod
12 program myProg
use myMod
14 implicit none
16 print*, Area is , area (2.0)
end program myProg
✌
✆
✞
Area is 12.5663710
✌
✆
By default, everything in a module is publicly available. However, accessibility can be
controlled by private and public attributes. Everything that is declared as private is not
available outside the module. The public attribute makes available all the elements of a
module outside the module. To restrict their access, only options restricts their access.
It is used as
✞
1 use module name  only : public var 1, public var 2, ...
✌
✆
The module codes can be wrote in the same file where they are used or in separate file.
If module is written in separate file then the file should be named as module name with
extension ‘.mod’.
64
0.15 Reserved Keywords
allocatable allocate assign assignment block
call case character common complex
contains continue cycle data deallocate
default do double precision else if
elsewhere end entry equivalence exit
external function go to if implicit
in inout integer intent interface
intrinsic kind len logical module
namelist nullify only operator optional
out parameter pause pointer private
program public real recursive result
return save select stop subroutine
target then type type() use
Where While backspace close endfile
format inquire open print read
rewind Write

More Related Content

Similar to Fortran programming help book

Modlica an introduction by Arun Umrao
Modlica an introduction by Arun UmraoModlica an introduction by Arun Umrao
Modlica an introduction by Arun Umraossuserd6b1fd
 
Modelica programming help book
Modelica programming help bookModelica programming help book
Modelica programming help bookArun Umrao
 
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...ssuserd6b1fd
 
Xcos simulation
Xcos simulationXcos simulation
Xcos simulationArun Umrao
 
Scilab help book 1 of 2
Scilab help book 1 of 2Scilab help book 1 of 2
Scilab help book 1 of 2Arun Umrao
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...ssuserd6b1fd
 
A_Practical_Introduction_to_Python_Programming_Heinold.pdf
A_Practical_Introduction_to_Python_Programming_Heinold.pdfA_Practical_Introduction_to_Python_Programming_Heinold.pdf
A_Practical_Introduction_to_Python_Programming_Heinold.pdfssuser7fcce2
 
A practical introduction_to_python_programming_heinold
A practical introduction_to_python_programming_heinoldA practical introduction_to_python_programming_heinold
A practical introduction_to_python_programming_heinoldthe_matrix
 
A Practical Introduction To Python Programming
A Practical Introduction To Python ProgrammingA Practical Introduction To Python Programming
A Practical Introduction To Python ProgrammingNat Rice
 
A practical introduction_to_python_programming_heinold
A practical introduction_to_python_programming_heinoldA practical introduction_to_python_programming_heinold
A practical introduction_to_python_programming_heinoldFaruqolayinkaSalako
 
A_Practical_Introduction_to_Python_Programming_Heinold.pdf
A_Practical_Introduction_to_Python_Programming_Heinold.pdfA_Practical_Introduction_to_Python_Programming_Heinold.pdf
A_Practical_Introduction_to_Python_Programming_Heinold.pdfTariqSaeed80
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...ssuserd6b1fd
 
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...ssuserd6b1fd
 
Learn python the right way
Learn python the right wayLearn python the right way
Learn python the right wayDianaLaCruz2
 
python learn basic tutorial learn easy..
python learn basic tutorial learn easy..python learn basic tutorial learn easy..
python learn basic tutorial learn easy..MURTHYVENKAT2
 
Haltermanpythonbook.pdf
Haltermanpythonbook.pdfHaltermanpythonbook.pdf
Haltermanpythonbook.pdfnebulaa2
 
Math for programmers
Math for programmersMath for programmers
Math for programmersmustafa sarac
 

Similar to Fortran programming help book (20)

Modlica an introduction by Arun Umrao
Modlica an introduction by Arun UmraoModlica an introduction by Arun Umrao
Modlica an introduction by Arun Umrao
 
Modelica programming help book
Modelica programming help bookModelica programming help book
Modelica programming help book
 
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
 
Xcos simulation
Xcos simulationXcos simulation
Xcos simulation
 
Scilab help book 1 of 2
Scilab help book 1 of 2Scilab help book 1 of 2
Scilab help book 1 of 2
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
 
tutorial.pdf
tutorial.pdftutorial.pdf
tutorial.pdf
 
A_Practical_Introduction_to_Python_Programming_Heinold.pdf
A_Practical_Introduction_to_Python_Programming_Heinold.pdfA_Practical_Introduction_to_Python_Programming_Heinold.pdf
A_Practical_Introduction_to_Python_Programming_Heinold.pdf
 
A practical introduction_to_python_programming_heinold
A practical introduction_to_python_programming_heinoldA practical introduction_to_python_programming_heinold
A practical introduction_to_python_programming_heinold
 
A Practical Introduction To Python Programming
A Practical Introduction To Python ProgrammingA Practical Introduction To Python Programming
A Practical Introduction To Python Programming
 
A practical introduction_to_python_programming_heinold
A practical introduction_to_python_programming_heinoldA practical introduction_to_python_programming_heinold
A practical introduction_to_python_programming_heinold
 
A_Practical_Introduction_to_Python_Programming_Heinold.pdf
A_Practical_Introduction_to_Python_Programming_Heinold.pdfA_Practical_Introduction_to_Python_Programming_Heinold.pdf
A_Practical_Introduction_to_Python_Programming_Heinold.pdf
 
thinkcspy3.pdf
thinkcspy3.pdfthinkcspy3.pdf
thinkcspy3.pdf
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
 
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
 
c programming
c programmingc programming
c programming
 
Learn python the right way
Learn python the right wayLearn python the right way
Learn python the right way
 
python learn basic tutorial learn easy..
python learn basic tutorial learn easy..python learn basic tutorial learn easy..
python learn basic tutorial learn easy..
 
Haltermanpythonbook.pdf
Haltermanpythonbook.pdfHaltermanpythonbook.pdf
Haltermanpythonbook.pdf
 
Math for programmers
Math for programmersMath for programmers
Math for programmers
 

More from Arun Umrao

maths_practice_sheet_28.12.23 (copy).pdf
maths_practice_sheet_28.12.23 (copy).pdfmaths_practice_sheet_28.12.23 (copy).pdf
maths_practice_sheet_28.12.23 (copy).pdfArun Umrao
 
Function Analysis v.2
Function Analysis v.2Function Analysis v.2
Function Analysis v.2Arun Umrao
 
Average value by integral method
Average value by integral methodAverage value by integral method
Average value by integral methodArun Umrao
 
Work and energy
Work and energyWork and energy
Work and energyArun Umrao
 
Units of physical quantities
Units of physical quantitiesUnits of physical quantities
Units of physical quantitiesArun Umrao
 
Scilab help book 2 of 2
Scilab help book 2 of 2Scilab help book 2 of 2
Scilab help book 2 of 2Arun Umrao
 
Measurements and errors
Measurements and errorsMeasurements and errors
Measurements and errorsArun Umrao
 
Linear motion for k12 students
Linear motion for k12 studentsLinear motion for k12 students
Linear motion for k12 studentsArun Umrao
 
Gnu octave help book 02 of 02
Gnu octave help book 02 of 02Gnu octave help book 02 of 02
Gnu octave help book 02 of 02Arun Umrao
 
Gnu octave help book 01 of 02
Gnu octave help book 01 of 02Gnu octave help book 01 of 02
Gnu octave help book 01 of 02Arun Umrao
 
Force and its application for k12 students
Force and its application for k12 studentsForce and its application for k12 students
Force and its application for k12 studentsArun Umrao
 
Electric field for k12 student
Electric field for k12 studentElectric field for k12 student
Electric field for k12 studentArun Umrao
 
Dictionary of physics
Dictionary of physicsDictionary of physics
Dictionary of physicsArun Umrao
 
Decreasing and increasing function
Decreasing and increasing functionDecreasing and increasing function
Decreasing and increasing functionArun Umrao
 
Circular motion
Circular motionCircular motion
Circular motionArun Umrao
 
Angular motion
Angular motionAngular motion
Angular motionArun Umrao
 
Who is successful
Who is successfulWho is successful
Who is successfulArun Umrao
 
Energy and power source
Energy and power sourceEnergy and power source
Energy and power sourceArun Umrao
 
Definitions related to measurements
Definitions related to measurementsDefinitions related to measurements
Definitions related to measurementsArun Umrao
 
Errors in Measurement
Errors in MeasurementErrors in Measurement
Errors in MeasurementArun Umrao
 

More from Arun Umrao (20)

maths_practice_sheet_28.12.23 (copy).pdf
maths_practice_sheet_28.12.23 (copy).pdfmaths_practice_sheet_28.12.23 (copy).pdf
maths_practice_sheet_28.12.23 (copy).pdf
 
Function Analysis v.2
Function Analysis v.2Function Analysis v.2
Function Analysis v.2
 
Average value by integral method
Average value by integral methodAverage value by integral method
Average value by integral method
 
Work and energy
Work and energyWork and energy
Work and energy
 
Units of physical quantities
Units of physical quantitiesUnits of physical quantities
Units of physical quantities
 
Scilab help book 2 of 2
Scilab help book 2 of 2Scilab help book 2 of 2
Scilab help book 2 of 2
 
Measurements and errors
Measurements and errorsMeasurements and errors
Measurements and errors
 
Linear motion for k12 students
Linear motion for k12 studentsLinear motion for k12 students
Linear motion for k12 students
 
Gnu octave help book 02 of 02
Gnu octave help book 02 of 02Gnu octave help book 02 of 02
Gnu octave help book 02 of 02
 
Gnu octave help book 01 of 02
Gnu octave help book 01 of 02Gnu octave help book 01 of 02
Gnu octave help book 01 of 02
 
Force and its application for k12 students
Force and its application for k12 studentsForce and its application for k12 students
Force and its application for k12 students
 
Electric field for k12 student
Electric field for k12 studentElectric field for k12 student
Electric field for k12 student
 
Dictionary of physics
Dictionary of physicsDictionary of physics
Dictionary of physics
 
Decreasing and increasing function
Decreasing and increasing functionDecreasing and increasing function
Decreasing and increasing function
 
Circular motion
Circular motionCircular motion
Circular motion
 
Angular motion
Angular motionAngular motion
Angular motion
 
Who is successful
Who is successfulWho is successful
Who is successful
 
Energy and power source
Energy and power sourceEnergy and power source
Energy and power source
 
Definitions related to measurements
Definitions related to measurementsDefinitions related to measurements
Definitions related to measurements
 
Errors in Measurement
Errors in MeasurementErrors in Measurement
Errors in Measurement
 

Recently uploaded

(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 

Recently uploaded (20)

(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 

Fortran programming help book

  • 1. 1 FORTRAN PROGRAMMING AN INTRODUCTION Arun Umrao www.sites.google.com/view/arunumrao DRAFT COPY - GPL LICENSING
  • 2. 2 Contents 0.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 0.2 Formatted I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 0.2.1 Print to Console . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 0.2.2 Read from Console . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 0.2.3 Quotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 0.2.4 Implicit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 0.3 Variables & Datatype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 0.3.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Real . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Complex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Constant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Boolean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Declaration, Initialization & Assignment . . . . . . . . . . . . . . . 14 0.4 FORTRAN Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 0.4.1 Logical Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 0.4.2 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . 16 0.4.3 Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 16 0.5 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 0.5.1 Remove Trailing Blank . . . . . . . . . . . . . . . . . . . . . . . . . 18 0.5.2 Adjust String Blank . . . . . . . . . . . . . . . . . . . . . . . . . . 18 0.5.3 Index of String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 0.5.4 String Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 0.5.5 String Length After Trim . . . . . . . . . . . . . . . . . . . . . . . 19 0.5.6 Lexical Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . 20 0.5.7 Covert to Char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 0.5.8 Repeat Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . 21 0.6 Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 0.6.1 Function Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . 22 0.6.2 Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 0.6.3 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 0.7 Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 0.7.1 If Condition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 0.7.2 If-else Condition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 0.7.3 If-else-if Condition . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 0.7.4 Select Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 0.7.5 Exit Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 0.7.6 Do Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 0.8 Core Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 0.8.1 Abort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 0.8.2 Alarm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 0.8.3 Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 0.8.4 Wait a Moment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 0.8.5 Get Process ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
  • 3. 3 0.8.6 Get User ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 0.8.7 Get Host Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 0.9 Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 0.9.1 Arithmetic Function . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Absolute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Imaginary Part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Fraction Part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Whole Part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Ceiling Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Convert to Complex . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Conjugate to Complex . . . . . . . . . . . . . . . . . . . . . . . . . 34 Convert to Double . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 Difference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 Significant Digit . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 Product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Floor Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Convert to Integer . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Maximum Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Minimum Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Modulo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Nearest Integer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Convert to Real . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Exponent Part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Fraction Part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Sum of Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 0.9.2 Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . . 40 sin, cos & tan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 sinh, cosh & tanh . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 asin, acos & atan . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 0.9.3 Algebraic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Exponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Natural Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Common Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Square Root . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 0.9.4 Bitwise Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Bit Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Bit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Logical AND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Clear Bit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Extract Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Set Bit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Exclusive OR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Inclusive OR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Logical Shift Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Logical NOT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 0.10 Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 0.10.1 Rank of Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
  • 4. 4 0.10.2 Extent of Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 0.10.3 Shape of Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 0.10.4 Size of Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 0.10.5 Passing Array to Function . . . . . . . . . . . . . . . . . . . . . . . 52 0.10.6 Shift Array Elements . . . . . . . . . . . . . . . . . . . . . . . . . . 53 0.11 Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 0.12 Input Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 0.12.1 Change Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 0.12.2 Get Current Directory . . . . . . . . . . . . . . . . . . . . . . . . . 56 0.12.3 Change Permission Mode . . . . . . . . . . . . . . . . . . . . . . . 56 0.12.4 Open a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 0.12.5 Close a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 0.12.6 Reading File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 0.12.7 Writing File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 0.12.8 Remove a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 0.12.9 Rename a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 0.12.10Current Position of Stream . . . . . . . . . . . . . . . . . . . . . . 60 0.12.11Read Single Char From Instream . . . . . . . . . . . . . . . . . . . 60 0.12.12Write Single Char in Outstream . . . . . . . . . . . . . . . . . . . 61 0.12.13Read Single Char From File Stream . . . . . . . . . . . . . . . . . 61 0.12.14Write Single Char in File Stream . . . . . . . . . . . . . . . . . . . 62 0.12.15File Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 0.13 Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 0.13.1 CPU Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 0.13.2 Convert Time into String . . . . . . . . . . . . . . . . . . . . . . . 63 0.13.3 Date & Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 0.14 Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 0.14.1 Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 0.14.2 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 0.15 Reserved Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 0.1 Introduction FORTRAN is acronym of the language name “Formula Translation”. FORTRAN follows code block protocol. Each block if initiated should be closed by using end keyword. For example ✞ 1 program MyProg print*, "First FORTRAN Program" 3 emd program MyProg ✌ ✆ Commenting inside FORTRAN program is also allowed. A new line or any part of line which started with ‘!’ symbol is assumed as comment in program and excluded by FORTRAN compilers. Occurrence of next ‘!’ does not have any meaning for that comment line and it also assumed as comment. ✞ 1 print*, " Hello" ! Hello ! string ✌ ✆
  • 5. 0.2. FORMATTED I/O 5 In fortran, a line is terminated by end-of-line. Empty lines are also assumed as comments, they are allowed but compiler just skipped them. Uppercase and lowercase, both types of characters are allowed in fortran. Multiple values or strings or group of strings and values can be written in single line by using comma (,) operator. ✞ 1 program MyProg print*, "First FORTRAN Program ", "is this ?" 3 end program MyProg ✌ ✆ A block of program codes may be named or unnamed. A named block of program codes must be closed with end keyword. A syntax of named code block in FORTRAN is given below: ✞ 1 myCode: <statements > 3 end myCode ✌ ✆ IWorking examples of this book are compiled with gfortran compiler of MinGW in Win- dows platform and default FORTRAN library in Ubuntu OS in Linux platform. Codes are written with help of NetBean IDE v7 and higher. 0.2 Formatted I/O In FORTRAN the formatted specifiers consists a string containing a list of edit descriptors in parentheses. By default, the FORTRAN formatting is right aligned. The descriptors are: ‘a’ for character variable. It is suffixed with an integer like ‘a10’. It means that 10 places to be used to display the character variable. If character string is larger than 10 then there is no effect of descriptor. If no number is suffixed to ‘a’ then the places are determined by actual size of the string. ‘i’ is descriptor for integers. It is used as ‘i10.5’, where 10 is field width and 5 is minimum number of digits to be displayed. ‘f’ is descriptor for real numbers. It is used as ‘f10.5’, where 10 is field width and 5 is precision of displayed real numbers. ‘e’ is descriptor for real numbers also. Used to display numbers in scientific notation. ✞ 1 program MyProg print "(a50)", "First FORTRAN Program " 3 end program MyProg ✌ ✆ ✞ First FORTRAN Program ✌ ✆
  • 6. 6 0.2.1 Print to Console print keyword is used to print the contents in output console. The following asterisk tells the compiler about default formatting type of contents. The string ‘Hello World’ is printed in output console when this FORTRAN program is run. ✞ 1 print*, ’Hello World’ end ✌ ✆ ✞ Hello World ✌ ✆ 0.2.2 Read from Console The inputs for variables are read from console by using read operator as ✞ 1 read *, x,y,z ✌ ✆ Here, three continuous inputs are read and assigned to x, y and z. ✞ 1 program MyProg read *, i, j, k 3 print*, i, j, k end program MyProg ✌ ✆ ✞ 1 3 6 1 3 6 ✌ ✆ 0.2.3 Quotes In Fortran, single and double quotes are same. Both represents to string. See the example below: ✞ program myQuot 2 print*, ’f’ print*, "F" 4 end program myQuot ✌ ✆ ✞ f F ✌ ✆
  • 7. 0.2. FORMATTED I/O 7 0.2.4 Implicit Dictionary meaning of implicit is “inherent in the nature of something”, i.e. when a variable is declared to certain datatype, then its nature is changed to that type until unless those variables are not re-declared explicitly. Although only integer and real type constants, variables and arrays have implicit types. But other datatype variables can also declared implicit type. Syntax for this function is ✞ implicit <data type > 2 !or implicit <data type > (<var 1>, <var 2>, ....) ✌ ✆ Explicit type declarations override implicit type declarations. A program that has only double datatype variable is declared as ✞ 1 implicit double ✌ ✆ If a implicit keyword is not used with the variable name, the variable is automatically declared and accepted by the compiler according to the assigned value to that variable. ✞ 1 program myImp u = 2.0 ! by default real value 3 v = 3.0 ! by default real value print*, complex(u, v) 5 end program myImp ✌ ✆ ✞ (2.00000000 , 3.00000000) ✌ ✆ If, implicit keyword is used with none keyword, then it is compulsory to declare the data type of the variable and assign proper values to them, so that the compiler can declare those variables of proper data type. ✞ 1 program myImp implicit none ! no implicit 3 real :: u, v ! u, v must be declared u = 2.0 ! real value 5 v = 3.0 ! real value print*, complex(u, v) 7 end program myImp ✌ ✆ ✞ (2.00000000 , 3.00000000) ✌ ✆ If a variable is fixed to certain datatype, then it can not be used as other data type. See the example below: ✞ 1 program myImp implicit complex(u, v) ! u, v are complex implicit type 3 u = 2.0 ! complex value without imaginary part v = 3.0 ! complex value without imaginary part 5 ! complex () function never accepts complex input
  • 8. 8 print*, complex(u, v) 7 end program myImp ✌ ✆ Above program will show compile time error as complex() function does not accepts complex values. It accepts real values. If the implicit variables are re-declared as explicit type, then they override to the implicit type variables. Above program is modified as given below: ✞ 1 program myImp implicit complex(u, v) ! u, v are complex implicit type 3 real :: u, v ! explicit re -declaration of u and v u = 2.0 ! by default real value 5 v = 3.0 ! by default real value print*, complex(u, v) 7 end program myImp ✌ ✆ This program runs successfully and gives output as shown below: ✞ (2.00000000 , 3.00000000) ✌ ✆ 0.3 Variables & Datatype Variables are multi-character names used to refer to some locations in memory that holds a value to which we are using. A variable is equivalent to its assigned value. A variable may be alphanumeric name with underscore character. First numeric character in a variable name is not acceptable. Use of spaces and reserved special characters is invalid. Similarly, use of comma, dot, symbol of question mark, symbols reserved for relational operations, symbols reserved for bitwise operations, colon and line terminating symbol are also considered as illegal if used in variable names. Identifiers in FORTRAN are case- insensitive thus, PRINT and print are completely identical. The maximum character length of variable in FORTRAN is 31 characters. 0.3.1 Variables In FORTRAN a variable name and variable data type is separated by ‘::’ symbol. The syntax of variable declaration is given below: ✞ 1 <data type > :: <variable name > ✌ ✆ For example, an integer type variable is declared as ✞ 1 int :: a ! variable a of integer type ✌ ✆ Multiple variables may also be declared in single line, separating them by comma operator as shown below: ✞ 1 <data type > :: <variable name 1>, <variable name 2>, ... ✌ ✆
  • 9. 0.3. VARIABLES & DATATYPE 9 Characters The keyword character is used to define a character type or a string type variable. Length of string that is assigned to the character type variable is controlled by len keyword. A character variable is declared as ✞ 1 character (len =80) :: <char variable > ✌ ✆ Here, len=80 controls the number of characters assigned to the string variable. ✞ 1 program MyProg character (len = 80) :: name 3 read *, name print*, name 5 end program MyProg ✌ ✆ ✞ "This is my strig" This is my strig ✌ ✆ Integers In FORTRAN an integer type variable is declared as ✞ int :: <variable name > ✌ ✆ Multiple integer variables can be declared in a single line if they are separated by comma operator as shown below: ✞ 1 int :: <variable name 1>, <variable name 2>, ... ✌ ✆ ✞ 1 program MyProg integer :: i, j, k 3 read *, i, j k = i * j 5 print*, k end program MyProg ✌ ✆ ✞ 2 5 10 ✌ ✆ Real A real number is a pure integer or a decimal number. Real numbers in FORTRAN are always written in their full precision form. This is why, subtraction of 2.5 from 5.2 does not returns 2.7 but it returns 2.69999981 approximating to 2.7, if round-off for first decimal place is taken. See the example below:
  • 10. 10 ✞ 1 program myMath print*, 5.2 - 2.5 3 end program myMath ✌ ✆ ✞ 2.69999981 ✌ ✆ The real variable is declared as ✞ 1 real :: r ✌ ✆ Example of real datatype is given below: ✞ 1 program real_no implicit none 3 real :: a = 12.5 print*, a 5 end program real_no ✌ ✆ ✞ 12.5000000 ✌ ✆ The implicit none statement allows the compiler to check whether our all variable datatypes are declared properly or not. You must always use implicit none at the beginning of a program. FORTRAN has definite precision points. There is a method to control the precision of the real numbers. To do, we use kind keyword as shown below: ✞ 1 real (kind =kind (1.0 d0)) :: <variable name > ✌ ✆ See the example given below: ✞ 1 program real_no implicit none 3 real (kind (1.0 d0)):: a = 12.5 print*, a 5 end program real_no ✌ ✆ ✞ 12.500000000000000 ✌ ✆ Complex A complex number is a number which contains a real part and an imaginary part. A complex number is represented by (a + bi), where i represents to imaginary part of the complex number. Here, a and b are real numbers. In FORTRAN, a complex number is represented as (a, b), which is equal to (a + bi). The complex variable is declared as ✞ 1 complex :: z ✌ ✆
  • 11. 0.3. VARIABLES & DATATYPE 11 If (a + bi) and (c + di) are two complex numbers then their complex product is given by Z = (ac − bd) + (ad + bc)i Take two complex numbers z1 = −2 + i and z2 = 1 − 2i. The complex product of these two complex numbers is z3 = z1 × z2 = (−2 + i) × (1 − 2i) = 0 + 5i The FORTRAN program for this example is given below. ✞ 1 program MyProg complex :: z1 , z2 , z3 3 z1 = (-2, 1) z2 = (1, -2) 5 z3 = z1 * z2 print*, z3 7 end program MyProg ✌ ✆ ✞ (0.00000000 , 5.00000000) ✌ ✆ Constant A constant is that data object whose value cannot be changed after initialization. A literal constant is a constant value without a name, such as 3.14, .true. or .false.,“This” etc. A named constant is a constant value with a name. Named constants and variables must be declared at the beginning of a program. Named constants must be declared with the parameter attribute: ✞ 1 real , parameter :: pi = 3.1415 ✌ ✆ ✞ 1 program myPtr implicit none 3 real , parameter :: pi = 3.1415 5 print *, pi 7 ! will show error as we try to change parameter ! values. To see it uncomment following lines. 9 ! 11 ! pi = pi + 1.0 ! uncomment it ! print *, pi ! uncomment it 13 end program myPtr ✌ ✆ ✞ 3.14150000 ✌ ✆
  • 12. 12 Boolean There are only two logical values: .true. and .false. (note down the dots around the words true and false). Symbolically, their output is ‘T’ and ‘F’ respectively. ✞ 1 program myPtr implicit none 3 print *, "True value ", .true . 5 print *, "False value", .false. 7 end program myPtr ✌ ✆ ✞ True value T False value F ✌ ✆ Declaration, Initialization & Assignment A variable is a reference of a value, and it does not hold value itself. A variable in FORTRAN is declared as ✞ real :: v ! variable v ✌ ✆ A variable can be declared as a parameter by using parameter keyword as shown below ✞ 1 real , parameter :: pi ! pi parameter ✌ ✆ A variable or a parameter is either public or private. By default a variable or a parameter has local scope. But its access can be make global by declaring it as public or its access can be restricted by declaring it as private. The syntax of public and private parameters are given below: ✞ 1 real , parameter , private ::f !private parameter f real , parameter , public ::g !public parameter g 3 real , public ::h !public variable h ✌ ✆ We can initialize a variable by assigning them a value. ✞ 1 real , public ::h !declare variable h=2.05 !assigning value to variable ✌ ✆ 0.4 FORTRAN Operators 0.4.1 Logical Operator In FORTRAN there are following logical operators.
  • 13. 0.4. FORTRAN OPERATORS 13 Operator Meaning .not. Logical NOT, returns true if one value is not equal to other. .and. Logical AND, returns true if both values are true. .or. Logical OR, returns true if either of the values are true. .eqv. Equivalent, returns true if both values are equal ✞ program myLog 2 real :: u, v u = 2.0 4 v = 3.0 if (u == 2.0 .and. v == 3.0) then 6 print*, "Matched " end if 8 end program myLog ✌ ✆ ✞ Matched ✌ ✆ The logical operator is evaluated from left to right direction. 0.4.2 Arithmetic Operators A list of five pure primary arithmetic operators is given in the following table. The list includes, exponential (represented as y = b∗∗e), multiplication (represented as y = a∗b), division (represented as y = a/b), addition (represented as y = a + b) and subtraction (represented as y = a − b) operators. Operator Meaning ** Exponential * Multiplication / Division + Addition - Subtraction In above table, the precedence of the operator is high to low in top to bottom direction in the table. 0.4.3 Relational Operators A relational operator evaluates values according to the operator. If condition of evaluation is true then successive block is evaluated otherwise next linked block is evaluated. In FORTRAN there are following relational operators.
  • 14. 14 Operator Description < Less than; returns true if left value is less than right value > Greater than; returns true if left value is greater than right value ≤ Less than or equal to; returns true if left value is less than or equals to right value ≥ Greater than or equal to; returns true if left value is greater than or equals to right value == Equals; returns true if left value is exactly equals to right value / = Not equals; returns true if left value is not equals to right value See the example below: ✞ 1 program if_cond implicit none 3 integer :: i = 5, j print*, "Enter an integer " 5 read *, j if (i < j) then ! less than operator 7 print*, "i is less than j" ! print if true else ! if condition is false , evaluate this block 9 print*, "i is greater than or equal to j" end if 11 end program if_cond ✌ ✆ ✞ Enter an integer 2 i is greater than or equal to j ✌ ✆ 0.5 Strings A character string in FORTRAN is declared and initialized as shown below: ✞ 1 character (len=<n>) :: <string variable > ! declaration <string variable >="My String" ! initialization ✌ ✆ Here, len=< n > reserves the n character spaces for storing of string. If length size, n, is less than the string size then only first n characters are stored in the memory space indicated by string variable and rest of the characters are ignored. Opposite to C, in which string terminator character (0) is used to terminate the string, in FORTRAN, integer is used to control the length of string being read or write.
  • 15. 0.5. STRINGS 15 ✞ program subStr 2 implicit none character (len = 5) :: mystr ! declaration 4 mystr = "This is test string."! initialization print*, mystr 6 end program subStr ✌ ✆ ✞ This ✌ ✆ A part of string can be extracted by using range operator ‘:’. ✞ 1 <string variable >(< lower index > : <upper index >) ✌ ✆ Here ‘lower index’ and ‘upper index’ are the limits of the extracted substring. If the lower subscript (‘lower index’) is omitted, it is assumed to be one, and if the upper subscript (‘upper index’) is omitted, then upper limit is length of the string. Position index in FORTRAN is started from 1 and continue rather than from 0 and continue. ✞ 1 program subStr implicit none 3 character (len = 50) :: mystr ! declaration mystr = "This is test string."! initialization 5 print*, mystr (1:5)! string between first & fifth indices end program subStr ✌ ✆ ✞ This ✌ ✆ Another example with different indices range; ✞ 1 program subStr implicit none 3 character (len = 50) :: mystr ! declaration mystr = "This is test string."! initialization 5 print*, mystr (4:5) !string between fourth & fifth indices end program subStr ✌ ✆ ✞ s ✌ ✆ 0.5.1 Remove Trailing Blank trim function is used to adjust trailing blank spaces from a string and inserting leading blank space. See the example below: ✞ 1 program subStr implicit none 3 character (len = 6) :: mystr ! declaration mystr = " This "! initialization
  • 16. 16 5 print*, "!!!!!!", trim (mystr), " !!!!!!" end program subStr ✌ ✆ ✞ !!!!!! This !!!!!! ✌ ✆ In above result, trailing blank space from string “ This ” is removed while leading blank space is not remove. 0.5.2 Adjust String Blank adjustl() function is used to adjust string left by removing any leading blanks and inserting trailing blanks. See the example below ✞ 1 program subStr implicit none 3 character (len = 6) :: mystr ! declaration mystr = " This "! initialization 5 print*, "!!!!!!", adjustl (mystr), "!!!!!!" end program subStr ✌ ✆ ✞ !!!!!! This !!!!!! ✌ ✆ adjustr() function is used to adjust string right by removing trailing blanks and inserting leading blanks. 0.5.3 Index of String index() function returns the leftmost or rightmost starting position of substring within given string. Its syntax is ✞ 1 index(<string >, <substring >, <true or false >) ✌ ✆ If third argument of the function is true, then index returns the rightmost starting position and if it is false then it returns the leftmost starting position. ✞ 1 program myP character (len = 80) :: name 3 name ="Somnath Temple is in Gujarat " print*, index(name , "a", .true .)!last a at 27 5 print*, index(name , "a", .false.)!first a at 5 end program myP ✌ ✆ ✞ 27 5 ✌ ✆
  • 17. 0.5. STRINGS 17 0.5.4 String Length len() function is used to get the size of string. The use of this function is explained in the following example. ✞ program subStr 2 implicit none character (len = 5) :: mystr ! declaration 4 mystr = "This is test string."! initialization print*, len(mystr) 6 end program subStr ✌ ✆ ✞ 5 ✌ ✆ 0.5.5 String Length After Trim len() function includes the leading and trailing spaces in the count of string length. We can use len trim() function to get the length of string without tailing spaces. ✞ 1 program myStr character (len = 10) :: str = "gfortran " 3 integer :: i do i = 1, len_trim (str) 5 call fput (str(i:i)) end do 7 end program myStr ✌ ✆ ✞ gfortran ✌ ✆ 0.5.6 Lexical Comparison lge(), lgt(), lle() and llt() functions are used to check the lexical comparison between two strings. The syntax of these functions are ✞ 1 lge (<string a>, <string b>) lgt (<string a>, <string b>) 3 lle (<string a>, <string b>) llt (<string a>, <string b>) ✌ ✆ Here, lge is acronym of ‘lexical greater than or equals to’, lgt is acronym of ‘lexical greater than’, lle is acronym of ‘lexical less than or equals to’ and llt is acronym of ‘lexical less than’. The comparison is performed for ‘string a’ to ‘string b’. Functions returns true (‘T’), if comparison conditions are satisfied, otherwise functions returns false (‘F’). ✞ program myP 2 character (len = 80) :: a character (len = 80) :: b 4 a = " Somnath temple is in Gujarat "
  • 18. 18 b = " Somnath Temple is in Gujarat " 6 print*, lge(a, b) end program myP ✌ ✆ ✞ T ✌ ✆ 0.5.7 Covert to Char char() function is used to convert an character code, (character code 0 to character code 255) into corresponding character symbols. For example, character code 65 is equivalent to character symbol ‘A’ and so on. ✞ 1 program myChar integer :: i 3 do i = 62, 70 print*, char (i) 5 end do end program myChar ✌ ✆ ✞ > ? @ A B C D E F ✌ ✆ 0.5.8 Repeat Concatenation repeat() function concatenate a string multiple times. Its example is given below: ✞ 1 program RepStr print*, repeat("x", 5) 3 end program RepStr ✌ ✆ ✞ xxxxx ✌ ✆ This function receives two arguments, first the string and second the number of times, the string is to be concatenate. This function returns string. 0.6 Function In FORTRAN, a function is declared as
  • 19. 0.6. FUNCTION 19 ✞ 1 function <func name >(<args vars separated by comma >) <expressions / statements > 3 end function <func name > ✌ ✆ The declared function is called by passing the argument values. Calling of a function is like ✞ 1 <func name >(<args >) ✌ ✆ This function returns a single quantity and it does not modify any of its arguments. The result of a function may also be given a different name when the function is declared as ✞ 1 function <func name >(<args var >) result (<result var >) <expressions / statements > 3 end function <func name > ✌ ✆ The result name must be different to the function name. A function can be declared as a subroutine. A subroutine is different from function as subroutine can modify their arguments. ✞ 1 function prod (m, n) result(a) real :: m, n 3 real :: a a = m * n 5 end function prod program myProg 7 print*, prod (3.0, 12.0) end program myProg ✌ ✆ ✞ 36.0000000 ✌ ✆ Remember, function name shall be a valid name. Function name started with numeric symbol are illegal. Spaces in function name are trimmed, hence spaces are acceptable upto a limited levels. ✞ 1 function pr od _(m, n) result(a) real :: m, n 3 real :: a a = m * n 5 end function pr od _ program myProg 7 print*, pr od_ (3.0, 12.0) end program myProg ✌ ✆ ✞ 36.0000000 ✌ ✆
  • 20. 20 0.6.1 Function Arguments An argument’s intention can be changed by using intent() function. For example, if argument of a function are only to be used then this function is used as ✞ 1 real , intent(in)::a ✌ ✆ If argument is to be overwrite then use following syntax ✞ 1 real , intent(out)::a ✌ ✆ If argument is used and overwritten then syntax is used as ✞ 1 real , intent(inout)::a ✌ ✆ In the following example, a square function is created and called inside from the user program. ✞ 1 function square(p) result (s) integer :: p 3 s = p * p end function square 5 program MyProg integer :: a 7 a = square (5); print*, a 9 end program MyProg ✌ ✆ ✞ 25 ✌ ✆ 0.6.2 Interface The interface block contains the name of procedure, and the names and attributes of all dummy arguments. Its syntax is ✞ 1 interface subroutine <sr >(<v1 >, <v2 >) 3 real , intent(inout)::x,y end subroutine <sr > 5 end interface ✌ ✆ This interface block is placed at the beginning of the program together with the declara- tion statements. ✞ 1 program area implicit none 3 interface function circleArea (r) 5 real :: circleArea real , intent(in) :: r
  • 21. 0.7. CONDITIONS 21 7 end function circleArea end interface 9 print*, "Area of circle with radius", 2, " is", circleArea (2.0) end program area 11 function circleArea (r) implicit none 13 real :: circleArea real , intent(in) :: r 15 real , parameter :: pi = 3.1415927 circleArea = pi * r * r 17 end function circleArea ✌ ✆ ✞ Area of circle with radius 2 is 12.5663710 ✌ ✆ 0.6.3 Recursion A procedure which calls itself directly or indirectly is called a recursive procedure. Its declaration must be preceded by the word recursive. In recursion, result option must be used. ✞ 1 program myProg integer :: Recur 3 print*, Recur(3, 12) end program myProg 5 recursive function Recur(m, n) result(a) 7 integer , intent(in) :: m, n integer :: a 9 if (m == 0) then a = m + n 11 else a = Recur(m - 1, n) 13 end if end function Recur ✌ ✆ ✞ 12 ✌ ✆ 0.7 Conditions In FORTRAN, each conditional operator is ended with end operator. Conditions are the comparison statements those controls the execution of codes inside the conditional blocks. 0.7.1 If Condition if () provides a way to instruct the program to execute a block of code only if certain conditions have been met. if is followed by condition and then by then operator. Each if opened should be closed by using keyword end. The syntax of if () construct is
  • 22. 22 ✞ 1 if(<conditions >) then ! if condition is true then statement ! execute the condition . 3 end if ✌ ✆ A simple example is ✞ 1 program myLog real :: u 3 u = 2.0 if (u == 2.0) then 5 print*, u end if 7 end program myLog ✌ ✆ ✞ 2.00000000 ✌ ✆ 0.7.2 If-else Condition if-else provides a way to instruct the program to execute a block of code only if certain conditions have been met otherwise execute other block. All the conditions, except than certain one defined for if, are true for else statement. This is why else has infinite numbers of true conditions. The syntax of if-else construct is ✞ 1 if(<conditions >) then ! if condition is true then statement one ! execute the statement one. 3 else ! otherwise if condition is false statement two ! execute the statement two. 5 end if ✌ ✆ A simple example is ✞ 1 program myLog real :: u 3 u = 2.5 if (u == 2.0) then 5 print*, u else 7 print*, 0 end if 9 end program myLog ✌ ✆ ✞ 0 ✌ ✆ multi-line statement can be written one after another. Expression should be written successively started with newline. Multi-line expressions within conditional keywords are ended when a new conditional keyword is started or conditional keyword is closed with end keyword.
  • 23. 0.7. CONDITIONS 23 ✞ 1 program myLog real :: u 3 u = 2.5 if (u == 2.0) then ! begin of single line expression block 5 print*, u ! expression line one else ! end of single line expression block and 7 ! begin of multiline expression block print*, 0 ! expression line one 9 print*, 1 ! expressoin line two print*, 2 ! expression line three 11 end if ! end of multiline expression block end program myLog ✌ ✆ ✞ 0 1 2 ✌ ✆ 0.7.3 If-else-if Condition Two if () conditions can be linked by else keyword. if-else-if provides a way to instruct the program to execute a block of code only if certain conditions have been met otherwise execute other block conditionally. All the conditions, except than certain ones defined for the first if, are true for else-if statement. This is why, else-if has infinite numbers of true conditions. These infinite numbers of conditions are again checked for if statement and the corresponding block is executed if certain conditions are met, otherwise these conditions are skipped to next else-if statement. The syntax of the linked if conditions is ✞ 1 if(<condition 1>) then <expressions 1> 3 else if(< condition 2>) then <expressions 2> 5 else if(< condition 2>) then <expressions 3> 7 end if ✌ ✆ An if-else-if-else conditional example is given below: ✞ 1 program myLog real :: u 3 u = 2.5 if (u == 2.0) then 5 print*, 2.0 else if (u == 2.5) then 7 print*, 2.5 else 9 print*, 0 end if
  • 24. 24 11 end program myLog ✌ ✆ ✞ 2.50000000 ✌ ✆ 0.7.4 Select Case Use of a long chain of if-else-if-else-if-else is very complex and less readable. There’s a solution by using the select-case construct. case() is similar to if statement except that select- case accepts single argument only and compare the argument value with a range of defined case() values. It executes the block of statements for which case() is matched. In contrast to case(), if () is fixed type and executes succeeding block of statements. Each select, which started at the beginning of a block must be closed by end keyword at the end of the block. The basic syntax of this construction is given below. ✞ 1 select case (<case variable >) case (<var value 1>) 3 <first statements > case (<var value 2>) 5 <second statements > case (<var value 3>) 7 <third statements > case default 9 <default statements > end select ✌ ✆ Here default case is executed if none of the cases is matched with select variable value. The case default is optional, but with a case default, it is guaranteed that what ever is the selector value, one of the statement will be used. There is no order to put case default, yet in programming conventions, case default is put in the last. ✞ program mySelCase 2 integer :: i i = 2 4 select case (i) case (2) 6 print*, 2 case (3) 8 print*, 3 case default 10 print*, "" end select 12 end program mySelCase ✌ ✆ ✞ 2 ✌ ✆ case() in select-case switch, also accepts the range value of numbers. The range of numbers is defined by using range operator ‘:’ (semi-colon). The preceding value of range operator
  • 25. 0.7. CONDITIONS 25 should be less than the succeeding value to the range operator. So, (-10:-9), (-1:0) and (2:3) etc are acceptable while (3:2) is illegal. ✞ 1 program mySelCase integer :: i 3 i = 3 select case (i) 5 case (2:5) print*, "Number is between 2 to 5" 7 case (6) print*, "Number is 6" 9 case default print*, "" 11 end select end program mySelCase ✌ ✆ ✞ Number is between 2 to 5 ✌ ✆ In case(), we can use discrete ranges from ‘a’ to ‘b’ and ‘c’ to ‘d’ as shown below: ✞ 1 case (a:b, c:d) ✌ ✆ The literal characters may also be used in the case() if they are written in single quotes. See the example below: ✞ 1 program mySelCase character (len =1) :: c 3 c=’d’ select case (c) 5 case (’a’:’g’) print*, "Char is between a to g" 7 case default print*, "Char is beyond g" 9 end select end program mySelCase ✌ ✆ ✞ Char is between a to g ✌ ✆ 0.7.5 Exit Keyword exit keyword is used by ForTran to exit from a loop. It should be always within a construct otherwise the compiler will throw compile time error. exit keyword is also used to break a continuous loop. ✞ 1 program myMath integer :: i 3 do i = 1, 10 if (i == 5) then 5 exit
  • 26. 26 end if 7 print*, i end do 9 end program myMath ✌ ✆ The output of above program is ✞ 1 2 3 4 ✌ ✆ 0.7.6 Do Loop do operator is used to perform continuous iteration. It also accepts lower limit of iteration, upper limit of iteration and iteration step size. Its syntax is ✞ do <var >=<from >, <to > 2 <statements > end do ✌ ✆ The syntax of do operator with iteration step size is given below: ✞ 1 do <var >=<from >, <to >, <step size > <statements > 3 end do ✌ ✆ Encapsulation of do operator is allowed. The encapsulation of do operator is done as below syntax. ✞ 1 myBlock: do <var >=<from >, <to >, <step size > <statements > 3 end do myBlock ✌ ✆ ✞ 1 program myArr !do loop 3 do k = 1, 5 print*, k; 5 end do end program myArr ✌ ✆ ✞ 1 2 3 4 5 ✌ ✆ The default step size of iteration is 1 if step size argument is absent or not supplied (see following line in above example).
  • 27. 0.8. CORE FUNCTIONS 27 ✞ 1 do k = 1, 5 ! only two inputs for k ✌ ✆ Third input or step size argument of do operator, changes the value of k as (k = k+2) <= 5. See the example given below: ✞ 1 program myArr !do loop 3 do k = 1, 5, 2 ! three inputs print*, k; 5 end do end program myArr ✌ ✆ ✞ 1 3 5 ✌ ✆ 0.8 Core Functions 0.8.1 Abort abort() causes immediate termination of the program. ✞ 1 program myTest integer :: i = 1, j = 2 3 if (i /= j) call abort end program myTest ✌ ✆ 0.8.2 Alarm alarm() causes external subroutine to be executed after a delay of time. Its syntax is ✞ alarm(<delay >, <handle >) 2 !of alarm(<delay >, <handle >, <st >) ✌ ✆ If ‘st’ is supplied, it will be returned with the number of seconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm. ✞ 1 program myAlarm external printIt 3 integer st call alarm(2, printIt , st) 5 call sleep(10) print *, st 7 end program myAlarm subroutine printIt
  • 28. 28 9 print*, "Called" end subroutine printIt ✌ ✆ ✞ Called 0 ✌ ✆ 0.8.3 Signal signal() causes external subroutine to be executed with a single integer argument when signal occurs. If signal is called as a subroutine and the status argument is supplied, it is set to the value returned by signal. It is used as ✞ program mySig 2 intrinsic signal external printIt 4 integer st call signal(2, printIt , st) 6 call sleep(1) print *, st 8 end program mySig subroutine printIt 10 print*, "Called" end subroutine printIt ✌ ✆ ✞ 0 ✌ ✆ 0.8.4 Wait a Moment sleep() function is used for wait a moment process. The wait time is controlled by the value supplied to the sleep function. The argument value is number of seconds. ✞ 1 program WaitFor call sleep (5) ! wait for 5 seconds 3 end program WaitFor ✌ ✆ 0.8.5 Get Process ID getpid() returns the numerical process id. It is used as ✞ 1 print*, getpid () ✌ ✆ ✞ 1 program myP character (len = 80) :: a 3 character (len = 80) :: b a = " Somnath temple is in Gujarat " 5 b = " Somnath Temple is in Gujarat "
  • 29. 0.9. MATHEMATICS 29 print*, lge(a, b) 7 print*, getpid() end program myP ✌ ✆ ✞ T 3320 ✌ ✆ 0.8.6 Get User ID getuid() returns the numerical user id. It is used as ✞ print*, getuid () ✌ ✆ 0.8.7 Get Host Name hostnm() subroutine is called to get the host name of the system. Its use is shown in the following example. ✞ 1 program HostName character (len =50) ::h 3 call hostnm(h) print*, h 5 end program HostName ✌ ✆ ✞ My Computer ✌ ✆ 0.9 Mathematics 0.9.1 Arithmetic Function In FORTRAN, the arithmetic evaluation operators are shown in the following table. Operator Meaning Order ** Exponential RL * Multiplication RL / Division LR + Addition LR – Subtraction LR The above operators are given from higher to lower precedence order. Except this, there are several other readymade functions which are used in number theories.
  • 30. 30 Absolute abs() function is used to get the absolute value of a number. The number may be negative or positive, but its absolute value shall be always positive. Mathematically, absolute function is given by |f(x)| = −x if x 0 x if x ≥ 0 ✞ 1 program subStr print *, abs ( -2.5) 3 end program subStr ✌ ✆ ✞ 2.50000000 ✌ ✆ Imaginary Part aimag() returns the imaginary part of a complex number. A complex number has two real numbers in which one represent to the real part of the complex number and other is coefficient of the imaginary part of the complex number. A complex number is represented as z = a + bi The imaginary part of this number is bi and real number of imaginary part is b. The syntax of this FORTRAN function is ✞ 1 ip = aimag(z) ✌ ✆ Example is ✞ 1 program myCompl complex :: z 3 z = complex (2, 3) print*, Imaginary part is , aimag(z) 5 end program myCompl ✌ ✆ ✞ Imaginary part is 3.00000000 ✌ ✆ Fraction Part aint() returns the integer part of a fraction number. For example, the integer part or whole part of a number 2.35 is 2. This function accepts only real numbers. In case of mathematical expression as argument then all the values except than mathematical operators must be in real form. For example, 2/3 is not acceptable while 2.0/3.0 is acceptable.
  • 31. 0.9. MATHEMATICS 31 ✞ 1 program myMath real :: z 3 z = 2.35 print*, Whole part is , aint (z) 5 end program myMath ✌ ✆ ✞ Whole part is 2 ✌ ✆ Whole Part anint() returns the whole part of a number. It is similar to ceiling. The argument to this function should be real. For example, 2/3 is not acceptable while 2.0/3.0 is acceptable. ✞ 1 program myMath real :: z 3 z = 3.552 print*, Whole part is , anint(z) 5 end program myMath ✌ ✆ ✞ Whole part is 4 ✌ ✆ Ceiling Value ceiling() returns the next greatest integer to the given real number. If a real number is +3.2, then ceiling value will be +4. Similarly, if real value is −2.5, then ceiling value will be −1. In number-line, the ceiling value of a real number is integer value just following to it counted from left to right. ✞ 1 program CeilValue print*, Ceiling value of , +3.25 ,is , ceiling (+3.25) 3 print*, Ceiling value of , -3.25 ,is , ceiling ( -3.25) end program CeilValue ✌ ✆ ✞ Ceiling value of 3.25000000 is 4 Ceiling value of -3.25000000 is -3 ✌ ✆ Convert to Complex cmplx() function converts to the real variables into a complex number. If there is only one input supplied to this function, then imaginary part becomes zero. Symbolically a complex number is shown by (a, b). ✞ program myMath 2 real :: z z = 3.552
  • 32. 32 4 print*, Complex number is , cmplx(z) end program myMath ✌ ✆ ✞ Complex number is (3.55200005 , 0.00000000) ✌ ✆ Complex conversion with two inputs to the function is shown in the example given below: ✞ 1 program myMath real :: z 3 z = 3.552 print*, Complex number is , cmplx(z, 2) 5 end program myMath ✌ ✆ ✞ Complex number is (3.55200005 , 2.00000000) ✌ ✆ Conjugate to Complex conjg() returns conjugate of a complex number. If a complex number is given by z = a+bi then complex conjugate of this number is given by z̄ = a − bi. ✞ 1 program myMath complex :: z 3 z = (2, 3) print*, Complex conjugate is , conjg(z) 5 end program myMath ✌ ✆ ✞ Complex conjugate is (2.0000000 , -3.00000000) ✌ ✆ Convert to Double dble() function returns the double precision real number of supplied integer. For example, an integer 20 is zero precision number while 20.000000000000000 is double precision real number as its decimal point value is significant upto 15th decimal places. ✞ 1 program myP print*, dble (20) 3 end program myP ✌ ✆ ✞ 20.000000000000000 ✌ ✆
  • 33. 0.9. MATHEMATICS 33 Difference dim() returns the difference of two given numbers. The second argument of dim() function is subtracted from the first argument of the function. If second argument is greater than the first argument then result is zero. Mathematically, this function obeys the piecewise function rule as dim(a, b) = a − b if a ≥ b 0 if a b See the ForTran program containing dim() function as given below: ✞ 1 program myMath print*, dim (5.2, 2.5) 3 print*, dim (2.5, 5.2) end program myMath ✌ ✆ ✞ 2.69999981 0.00000000 ✌ ✆ Significant Digit Significant Scientific Numbers The digits of mantissa of a number expressed in scien- tific notation are called significant figures or significant digits. A zero is always significant if it is right of the non zero digits or right of the decimal. For example Number Scientific Notation Significant Figures 132.00 1.3200 × 102 5 0.0123540 1.23540 × 10−2 6 -0.125 −1.25 × 10−1 3 25250 2.5250 × 104 5 A point is to be remember that 2.5250 × 104 and 2.525 × 104 are same values but first has five significant figures while second has four significant figures. In calculation first number is more accurate because it give the precision value upto fourth place of decimal while second number gives precision upto third place of decimal. digits() returns the number of significant digits in a number. In ForTran real numbers are represented in float data format of scientific notation. In float data format, 24 bits are used as mantissa and 8 bits are used for exponents. In integer data format, 32 bits are used in computation of the number. digits() returns mantissa bits. See the following example: ✞ program myProg 2 print*, digits (2.1000) ! Real number print*, digits (21000) ! Integer 4 end program myProg ✌ ✆
  • 34. 34 ✞ 24 31 ✌ ✆ Product dprod() returns the double precision real product of two supplied numbers. The numbers must be real type. Application of this function is shown in following example. ✞ program myP 2 print*, dprod(5.0, 3.0) end program myP ✌ ✆ ✞ 15.000000000000000 ✌ ✆ Floor Value floor() returns the greatest integer less than or equal to the given number. If a real number is +3.2, then floor value will be +3. Similarly, if real value is −2.5, then floor value will be −3. In number-line, the floor value of a real number is integer value just preceding to it counted from left to right. ✞ 1 program FloorValue print*, Floor value of , +3.25 ,is , floor (+3.25) 3 print*, Floor value of , -3.25 ,is , floor ( -3.25) end program FloorValue ✌ ✆ ✞ Floor value of 3.25000000 is 3 Floor value of -3.25000000 is -4 ✌ ✆ Convert to Integer int() converts to real or integer into integer value by truncating the real part of the number. The argument to this number should be a real type. ✞ program myP 2 print*, int (5.24587) end program myP ✌ ✆ ✞ 5 ✌ ✆
  • 35. 0.9. MATHEMATICS 35 Maximum Value max() returns the maximum value among all the values supplied to the function as its arguments. ✞ 1 program MaxValue integer :: m 3 m = max (5, 2, 3) print*, Maximum value is , m 5 end program MaxValue ✌ ✆ ✞ Maximum value is 5 ✌ ✆ Minimum Value min() returns the minimum value among all the values supplied to the function as its arguments. ✞ 1 program MinValue integer :: m 3 m = min (5, 2, 3) print*, Minimum value is , m 5 end program MinValue ✌ ✆ ✞ Minimum value is 2 ✌ ✆ Modulo mod() or modulo() returns the mod between two numbers. Mod is remainder value in division of a number by other number. ✞ 1 program myMod integer :: m 3 m=mod (7, 2) print*, Mod is , m 5 end program mySum ✌ ✆ ✞ Mod is 1 ✌ ✆ Nearest Integer nint() returns the nearest integer value to a real number. It is similar to rounding off process. Its example is given below
  • 36. 36 ✞ 1 program myP print*, nint (5.24587) 3 print*, nint (5.54587) end program myP ✌ ✆ ✞ 5 6 ✌ ✆ Convert to Real real() converts an integer value into real value. In following example, an integer value ‘6’ is supplied to function real() which returns the real form of this integer. ✞ program myP 2 print*, real (6) end program myP ✌ ✆ ✞ 6.00000000 ✌ ✆ Exponent Part exponent() returns the exponent part of a number. An exponent is denoted by y = ab . Here, b is exponent and a is base of exponent. This function uses inequality to get the exponent of the number. The inequality is 2b−1 ≤ y 2b Where b is exponent. ✞ 1 program myP print*, exponent (1.0) 3 print*, exponent (2.0) print*, exponent (3.0) 5 print*, exponent (4.0) print*, exponent (5.0) 7 print*, exponent (6.0) end program myP ✌ ✆ ✞ 1 2 2 3 3 3 ✌ ✆
  • 37. 0.9. MATHEMATICS 37 Fraction Part fraction() returns the fractional part of a number. If a number is written in form of a/b then fraction part is the decimal part of the result obtained from the division of a/b. ✞ program myMath 2 real :: z z = 2.0/3.0 4 print*, Fraction part is , fraction (z) end program myMath ✌ ✆ ✞ Fraction part is 0.6666666 ✌ ✆ Sum of Array sum() function is used for cumulative summation of all the numerical terms of an array. It is used as ✞ 1 program mySum integer :: x(10) , i, s 3 do i = 1, 10 x(i) = i; 5 end do s = sum(x) 7 print*, Sum is , s end program mySum ✌ ✆ ✞ Sum is 55 ✌ ✆ 0.9.2 Trigonometric Functions ForTran supports trigonometric calculations. All principle, hyperbolic and inverse trigono- metric function are inbuilt in the ForTran. sin, cos tan sin(), cos() and tan() returns their respective numerical results when they are supplied by inputs (arguments) in radian. The angle argument of these functions is called its domain and their result is called range. Function Domain Range sin h − π 2 , π 2 i [−1, 1] cos [0, π] [−1, 1] tan h − π 2 , π 2 i (−∞, ∞)
  • 38. 38 ✞ 1 program myProg print*, sin (2.0) 3 print*, cos (2.0) print*, tan (2.0) 5 end program myProg ✌ ✆ ✞ 0.909297407 -0.416146845 -2.185039760 ✌ ✆ Principle of trigonometry are applied in the computation of these functions. sinh, cosh tanh sinh(), cosh() and tanh() returns their respective hyperbolic numerical results when they are supplied by inputs (arguments) in radian. These functions are also called hyperbolic of the primary trigonometric functions, i.e. sin(), cos() and tan(). ✞ 1 program myProg print*, sinh (1.0) 3 print*, cosh (1.0) print*, tanh (12.0) 5 end program myProg ✌ ✆ ✞ 1.17520118 1.54308069 1.00000000 ✌ ✆ asin, acos atan asin(), acos() and atan() returns their respective angular results in radian when they are supplied by inputs (arguments) in number. These functions are also called inverse of the primary trigonometric functions, i.e. sin(), cos() and tan(). Function Domain Range sin−1 [−1, 1] h − π 2 , π 2 i cos−1 [−1, 1] [0, π] tan−1 (−∞, ∞) h − π 2 , π 2 i ✞ 1 program myProg print*, asin (1.0) 3 print*, acos (1.0)
  • 39. 0.9. MATHEMATICS 39 print*, atan (12.0) 5 end program myProg ✌ ✆ ✞ 1.57079637 0.00000000 1.48765504 ✌ ✆ Principle of trigonometry are applied in the computation of these functions. 0.9.3 Algebraic Functions Exponent exp() function is equivalent to ex , where x is a real number. e is universal natural logarithmic base. The algebraic series representation of exp(x) is given by ex = 1 + x + x2 2! + x3 3! + x4 4! + . . . exp(1) is equal to 2.718281828. ✞ 1 program myMath print*, exp (2.0) 3 end program myMath ✌ ✆ ✞ 7.38905621 ✌ ✆ Natural Log log() is logarithm of a number about natural base e. Natural logarithm of a number can be converted into the common logarithm by using relation loge(a) = log10(a) loge(a) Or loge(a) = 2.30258 × log10(a) ✞ 1 program myMath print*, log (2.0) 3 end program myMath ✌ ✆ ✞ 0.693147182 ✌ ✆
  • 40. 40 Common Log log10() is logarithm of a number about common base 10. Common base logarithm depends on the natural logarithm as loge(a) = 2.30258 × log10(a) ✞ 1 program myMath print*, log10 (2.0) 3 end program myMath ✌ ✆ ✞ 0.301030010 ✌ ✆ Square Root sqrt() returns the square root value of a number. Square root of a number is written as y = √ x. ✞ 1 program myMath print*, Square root , 2.254 , is , sqrt (2.254) 3 end program myMath ✌ ✆ ✞ Square root 2.254 is 1.50133276 ✌ ✆ If the number is negative then there is “Argument of SQRT at (1) has a negative value” error. 0.9.4 Bitwise Functions Bitwise functions are used in mathematical operations related to binary arithmetic. Bit Size bit size() returns the number of bits of a model. The input argument of this function is a binary form of number. ✞ 1 program myMath print*, bit_size (10001001) 3 end program myMath ✌ ✆ ✞ 32 ✌ ✆
  • 41. 0.9. MATHEMATICS 41 Bit Testing btest() tests whether a bit is zero or one at specific index. It accepts two inputs, first binary number and second bit index. The bit index value is started from 0 to continue. ✞ 1 program myMath print*, btest (10001001, 2) !3rd bit from LSB , F 3 print*, btest (10001001, 3) !4th bit from LSB , T end program myMath ✌ ✆ ✞ F T ✌ ✆ Logical AND iand() returns the result of two numbers which are bitwise ANDed logically. Assume two numbers 50 and 81. In AND operation, result bit is high if all of the input bits are high. The binary AND operation is performed as ✞ 00110010 = 50 2 01010001 = 81 ----------------AND 4 00010000 = 16 ✌ ✆ ✞ program BitWise 2 print *, iand (50, 81) end program BitWise ✌ ✆ ✞ 16 ✌ ✆ Clear Bit ibclr() clears the bit of a number at specific index from the LSB side. Position index is started from 0 to 7 for one byte long data. If the bit at the index is 1, it is reset to 0. Its description is given below: ✞ 1 00110010 = 50 %clear 2nd bit from LSB , index = 1 3 00110000 = 48 ✌ ✆ Example in FORTRAN is given below: ✞ 1 program BitWise print *, ibclr(50, 1) 3 end program BitWise ✌ ✆ ✞ 48 ✌ ✆
  • 42. 42 Extract Bits ibits() function extracts the bits from a number and returns the number equivalent to the extracted bits. The index position and length of bits to be extracted are specified by index and length. ✞ 1 ibits(number , index from LSB , number of bits from LSB to MSB ) ✌ ✆ Example is given below: ✞ 1 program myMath !150D = 1001 0110 B 3 print*, ibits(150, 0, 8)!From LSB 0 to 8 to MSB = 10010110 print*, ibits(150, 1, 8)!From LSB 1 to 8 to MSB = 1001011 5 print*, ibits(150, 2, 8)!From LSB 2 to 8 to MSB = 100101 print*, ibits(150, 3, 8)!From LSB 3 to 8 to MSB = 10010 7 print*, ibits(150, 4, 8)!From LSB 4 to 8 to MSB = 1001 print*, ibits(150, 5, 8)!From LSB 5 to 8 to MSB = 100 9 end program myMath ✌ ✆ ✞ 150 75 37 18 9 4 ✌ ✆ Set Bit ibset() function sets the bit in a number at specific index from LSB side. Position index is started from 0 to 7 for one byte long data. If the bit at the index is 0, it is reset to 1. Its description is given below: ✞ 00110010 = 50 2 %set 3rd bit from LSB , index = 2 00110110 = 50 ✌ ✆ Example in FORTRAN is given below: ✞ 1 program BitWise print *, ibset(50, 2) 3 end program BitWise ✌ ✆ ✞ 54 ✌ ✆
  • 43. 0.9. MATHEMATICS 43 Exclusive OR ieor() returns the result of two numbers which are ORed exclusively. Assume two numbers 50 and 81. In XOR operation, result bit is high if only one of the two input bits is high. The binary XOR operation is performed as ✞ 1 00110010 = 50 01010001 = 81 3 ----------------XOR 01100011 = 99 ✌ ✆ ✞ program BitWise 2 print *, ieor (50, 81) end program BitWise ✌ ✆ ✞ 99 ✌ ✆ Inclusive OR ior() returns the result of two numbers which are ORed inclusively. Assume two numbers 50 and 81. In OR operation, result bit is high if any or all of the input bits are high. The binary OR operation is performed as ✞ 1 00110010 = 50 01010001 = 81 3 ----------------OR 01110011 = 115 ✌ ✆ ✞ program BitWise 2 print *, ior(50, 81) end program BitWise ✌ ✆ ✞ 200 ✌ ✆ Logical Shift Bits ishft() shifts the bits leftward or right word by a specific position. Assume a number 50 in decimal which is 00110010 (8-bit form). The logical bit shift by +2 (left shift) places of the binary form of the number is 0011001000 which is equals to 200 in decimal. The example in FORTRAN is given below: ✞ 1 program BitWise print *, ishft(50, 2) 3 end program BitWise ✌ ✆
  • 44. 44 ✞ 200 ✌ ✆ Again, take the same number 50 in decimal which is 00110010 (8-bit form). The logical bit shift by −2 (right shift) places of the binary form of the number is 00001100 (8-bit form) which is equals to 12 in decimal. The example in FORTRAN is given below: ✞ 1 program BitWise print *, ishft(50, -2) 3 end program BitWise ✌ ✆ ✞ 12 ✌ ✆ Remember that in left shift by +n places, n number of 0 bits are post-fixed to the binary number. Similarly in case of right shift by −n places, n numbers of bits from the binary form of the number are removed from LSB side. Logical NOT not() returns the logical complements of the bits of supplied number. Assume a number 50 in decimal which is 00110010 (8-bit form). The logical NOT (complement) of the binary form of the number is 11001101 which is equals to 205 in decimal or 205 − 256 = −51 in signed form. The example in FORTRAN is given below: ✞ 1 program BitWise !50D = 00110010 B 3 !NOT of 50D = 11001101 B !11001101 B = 205D = -51D 5 print *, not (50) end program BitWise ✌ ✆ ✞ -51 ✌ ✆ 0.10 Array In ForTran, arrays are declared as ✞ 1 integer :: array name ( number of elements ) ✌ ✆ Here, keyword integer specified the data type of array. Array name is valid literals which identify the array. Each array declared must have predefined size. See the example below ✞ 1 program myArr !Array of 5 elements 3 integer :: myA (5) !Add values to array 5 do k = 1, 5 myA(k) = 2 * k
  • 45. 0.10. ARRAY 45 7 end do !Print array elements 9 do k = 1, 5 print*, myA(k) 11 end do end program myArr ✌ ✆ ✞ 2 4 6 8 10 ✌ ✆ A multidimensional array is declared as ✞ 1 integer :: array name ( rows dim , cols dim ) ✌ ✆ Here, ‘rows dim’ is number of rows and ‘cols dim’ is number of columns in an integer datatype array. ✞ 1 program myArr !Array of 2 rows 5 cols 3 integer :: myA(2, 5) !Add values to array 5 do k = 1, 2 do l = 1, 5 7 myA(k, l) = k + l end do 9 end do !Print array elements 11 do k = 1, 2 do l = 1, 5 13 print*, myA(k, l) end do 15 end do end program myArr ✌ ✆ ✞ 2 3 4 5 6 3 4 5 6 7 ✌ ✆ Another way to declared an array is shown below:
  • 46. 46 ✞ real , dimension (4) :: array var ! one row ✌ ✆ The dimension of an array is controlled with dimension keyword followed by number of element. ✞ 1 program myArr !Array of 4 elements 3 integer , dimension (4) :: myA !Add values to array 5 do l = 1, 4 myA(l) = 2 * l 7 end do !Print array elements 9 do l = 1, 4 print*, myA(l) 11 end do end program myArr ✌ ✆ ✞ 2 4 6 8 ✌ ✆ If the number of elements assigned to the array are larger than the dimension of the array then program returns invalid memory reference error. ✞ program myArr 2 !Array of 4 elements integer , dimension (4) :: myA 4 !Try to add 5 values to array do l = 1, 5 6 myA(l) = 2 * l end do 8 end program myArr ✌ ✆ A two dimensional array is declared as ✞ real , dimension (2, 4) :: array var ! 2 rows 4 columns ✌ ✆ ✞ 1 program myArr !Array of 2 row 5 cols 3 integer , dimension (2, 5):: myA !Add values to array 5 do k = 1, 2 do l = 1, 5 7 myA(k, l) = k + l end do 9 end do !Print array elements
  • 47. 0.10. ARRAY 47 11 do k = 1, 2 do l = 1, 5 13 print*, myA(k, l) end do 15 end do end program myArr ✌ ✆ ✞ 2 3 4 5 6 3 4 5 6 7 ✌ ✆ The array vector could also have been declared with explicit lower bounds: ✞ real , dimension (1:5) :: array var ! row of 5 elements ✌ ✆ In above type declaration of matrix, (1:5) represents to the index of elements. For exam- ple, array element should be indexed from ‘1’ to ‘5’. See the example below: ✞ 1 program myArr !array of 5 elements 3 integer , dimension (1:5) :: myA !add values to array 5 do l = 1, 5 myA(l) = 2 * l 7 end do !print elements of array 9 do l = 1, 5 print*, myA(l) 11 end do end program myArr ✌ ✆ ✞ 2 4 6 8 10 ✌ ✆ All the following type declaration statements are legal: ✞ 1 real , dimension ( -10:8) :: array var ! 1-dim array with 19 elements integer , dimension (-3:3, -20:0, 1:2) :: grid var ! 3-dim array ✌ ✆
  • 48. 48 The number of elements of the integer array ‘grid var’ is 7 × 21 × 2 = 294. There is restriction of use of arrays with more than 7 dimensions. In following example two dimensional grid is used for matrix generation using ranged index. ✞ program myArr 2 !two dimensional array 5 rows 2 cols !row indexed from 1 to 5 4 !col indexed from 2 to 3 integer , dimension (1:5, 2:3) :: myA 6 !add values to array do k = 1, 5 8 do l = 2, 3 myA(k, l) = 2 * l + k 10 end do end do 12 !print elements of array do k = 1, 5 14 do l = 2, 3 print*, myA(k, l) 16 end do end do 18 end program myArr ✌ ✆ ✞ 5 7 6 8 7 9 8 10 9 11 ✌ ✆ 0.10.1 Rank of Array Rank of an array is number of array’s dimensions. For one dimensional array has rank 1. For two dimensional array has rank of 2. Two dimensional array becomes a matrix. In case of matrix, to get the rank, matrix should be in echelon form. Assume a matrix, A is in echelon form A = 1 0 0 1 and it has two non zero rows, then the rank of matrix is 2. rank() function is used to get the number of rank of a matrix. ✞ program myArray 2 implicit none integer , dimension (6) :: myArrA 4 integer , dimension (6, 2) :: myArrB
  • 49. 0.10. ARRAY 49 print*, Rank of myArrA , rank ( myArrA) 6 print*, Rank of myArrB , rank ( myArrB) end program myArray ✌ ✆ ✞ Rank of myArrA 1 Rank of myArrB 2 ✌ ✆ 0.10.2 Extent of Array Extent of an array is the number of elements counted along a dimension. 0.10.3 Shape of Array The shape of an array is a one-dimensional integer array, containing the number of ele- ments in each dimension. The shape of array is denoted by m × n × . . . in which m, n, . . . represents to each dimension of the array. ✞ program test_shape 2 integer , dimension (-1:1, -1:2) :: A write(*, *) shape(A) 4 end program ✌ ✆ ✞ 3 4 ✌ ✆ 0.10.4 Size of Array Size of array specified the number of elements present in an array. An array having dimension m rows and n columns has m × n size or element. size() function is used to get the number of element in matrix or dimension of the row. ✞ 1 program myArray implicit none 3 integer , dimension (6) :: myArr ! declaration print*, size (myArr) 5 end program myArray ✌ ✆ ✞ 6 ✌ ✆ 0.10.5 Passing Array to Function Function in ForTran is called sub-routine. call operator is used to call a sub-routine from a program or from a sub-routine. Arrays can be passed to a function (sub-routine) as its argument.
  • 50. 50 ✞ 1 subroutine sname (arg ) ..................... 3 end subroutine sname ! 5 program pname call sname ( array name ) 7 end program pname ✌ ✆ See the following example. ✞ 1 program passArray implicit none 3 integer , dimension (5) :: myArray integer :: i 5 !call subroutine and pass array as its argument call AddValueToArr ( myArray) 7 !call subroutine to print array elements call PrintArrValues (myArray) 9 end program passArray ! 11 subroutine AddValueToArr (a) implicit none 13 integer , dimension (5) , intent (out) :: a integer :: i 15 do i = 1, 5 a(i) = i 17 end do end subroutine AddValueToArr 19 ! subroutine PrintArrValues (a) 21 integer , dimension (5) :: a integer :: i 23 do i = 1, 5 Print *, a(i) 25 end do end subroutine PrintArrValues ✌ ✆ ✞ 1 2 3 4 5 ✌ ✆ 0.10.6 Shift Array Elements cshift() performs a circular shift on elements of array along the dimension. This function takes three argument. Last argument is dimension number. If it is not given to function then it is taken 1 by default. Its value should not be larger than rank of the array or matrix. The syntax of this function is
  • 51. 0.11. POINTER 51 ✞ 1 cshift(array , shift positions , array dim ) ✌ ✆ Shift positions may be positive or negative value. If it is positive value then array shift is from left to right otherwise right to left. ✞ 1 program ArrayShift integer :: k(5) , i 3 do i = 1, 5 k(i) = i 5 end do k = cshift(k, 2, 1) 7 do i = 1, 5 print*, k(i) 9 end do end program ArrayShift ✌ ✆ ✞ 3 4 5 1 2 ✌ ✆ ✞ 1 program ArrayShift integer :: k(5) , i 3 do i = 1, 5 k(i) = i 5 end do k = cshift(k, -2, 1) 7 do i = 1, 5 print*, k(i) 9 end do end program ArrayShift ✌ ✆ ✞ 4 5 1 2 3 ✌ ✆ 0.11 Pointer A pointer variable is declared with the pointer attribute. A pointer variable that is an array must be a deffered-shape array. A pointer is allocated to a variable as ✞ 1 integer , pointer :: p ! pointer to integer real , pointer , dimension (:) :: rp !pointer to one dim array 3 real , pointer , dimension (:,:) :: r2p ! pointer to two dim array ✌ ✆
  • 52. 52 A pointer in FORTRAN points to an area of dynamically allocated memory or a data object of the same type as the pointer with the target attribute. Space for pointer is allocated by using allocate() function. ✞ 1 integer , pointer :: p ! pointer to integer allocate (p) ! allocate dynamic memory to p ✌ ✆ ✞ program myPtr 2 implicit none !pointer myP 4 integer , pointer :: myP 6 !allocate dynamic memory space for variable myP allocate (myP) 8 myP = 1 10 print *, myP 12 myP = myP + 4 print *, myP 14 end program myPtr ✌ ✆ ✞ 1 5 ✌ ✆ A target object is an ordinary variable, with space set aside for it. To act as a target for a pointer is must be declared with the target attribute. ✞ program myP 2 integer , pointer :: p1 integer , target :: p2 4 p1=p2 end program myP ✌ ✆ The function associated() returns the association between pointer and its target. It returns true, if the pointer is associated with target otherwise returns false. Its syntax is ✞ 1 associated (p1 , p2) ✌ ✆ loc() function returns the address of the variable. It is used as ✞ 1 program VarAddress character (len =50) ::h 3 print*, loc(h) end program VarAddress ✌ ✆ ✞ 2293534 ✌ ✆
  • 53. 0.12. INPUT OUTPUT 53 0.12 Input Output Program needs to fetch data or write data to a local file. FORTRAN has ability to read or write data from or to a file. 0.12.1 Change Directory chdir() function is used to change the current working directory. The current working directory is directory where FORTRAN puts its temporary files or creates and read stored data files. ✞ 1 program myChdir character (len = 255) :: path 3 call getcwd(path ) write(*, *) trim (path ) 5 call chdir(C:/) call getcwd(path ) 7 write(*, *) trim (path ) end program myChdir ✌ ✆ ✞ C: NetBeansProjects fortran C: ✌ ✆ 0.12.2 Get Current Directory getcwd() function returns the current working directory. It returns full path of the current working directory. ✞ program myChdir 2 character (len = 255) :: path call getcwd(path ) 4 write(*, *) trim (path ) end program myChdir ✌ ✆ ✞ C: NetBeansProjects fortran ✌ ✆ 0.12.3 Change Permission Mode chmod()function changes the permission mode of the file. Here, mode of file are scalar characters of default kind giving the file permission. Mode uses the same syntax as the chmod utility as defined by the POSIX standard. The argument shall either be a string of a non-negative octal number or a symbolic mode. ✞ 1 program myDir implicit none 3 integer :: st call chmod(’test .dat ’, ’u + x’, st)
  • 54. 54 5 print *, ’Status: ’, st end program myDir ✌ ✆ ✞ Status: 1 ✌ ✆ The POSIX based file permission modes are Mode Permission Description 0.12.4 Open a File To open a file to make it available to the program, open() function is used. Its syntax is ✞ 1 open (unit =u, file =name , status=st , action=act ) ✌ ✆ Here ‘u’ is a positive integer. Unit number should be positive ranging from 1 to 99. This number is handle which identify to the file stream through which compiler either read or write. ‘st’ is status of file. It can be “new” if file is not exists or “old” if file exists is system. “replace” created a new file if file does not exists and replaces to file if it exists. “scratch” is temporary file used during the program run. When program ended, it is deleted. ‘name’ is name of the file. ‘act’ is the action to be performed into the file and is similar to the mode of operation in C. The file action mode in FORTRAN are “read”, “write” and “readwrite”. “read” is used to read from file, “write” is used to write something to the file and “readwrite” is used to read as well as write. There are another option which is used to check the status of file. It is ‘iostat’. If the file is correctly opened, ‘iostat’ is set to zero otherwise positive integer. ✞ 1 program open_file implicit none 3 character (50) :: line integer :: err 5 ! open file a.txt with stream id 5 open (unit = 5, file = a.txt, status = old, iostat = err) 7 if (err 0) then print*, unable to open file . 9 stop end if 11 do ! read line by line of the a.txt 13 read (5, (a), iostat = err) line if (err == -1) exit ! EOF detected 15 print*,line ; end do 17 close (5) end program open_file ✌ ✆ ✞ This is file a.txt ✌ ✆
  • 55. 0.12. INPUT OUTPUT 55 By default, FORTRAN creates a file in the current directory. But if file name is preceded by a slash (‘/’) then file is opened in root directory. ✞ 1 open (unit =u, file =/name , status=st , action=act ) ✌ ✆ 0.12.5 Close a File Each file which is opened by open() function, must be closed by close() function. Its syntax is ✞ 1 close(unit =u, iostat=state , status=st ) ✌ ✆ ✞ 1 program open_file implicit none 3 integer :: err ! open file a.txt with stream id 5 5 open (unit = 5, file = a.txt, status = old, iostat = err) if (err 0) then 7 print*, unable to open file . stop 9 end if close (5) 11 end program open_file ✌ ✆ ✞ This is file a.txt ✌ ✆ 0.12.6 Reading File To read data from a file, read() function is used. Its syntax is ✞ 1 read (unit =u, fmt=read format ) read buffer variable ✌ ✆ Here, ‘u’ is the stream number of the previously opened file. ✞ 1 program open_file implicit none 3 character (50) :: line integer :: err 5 ! open file a.txt with stream id 5 open (unit = 5, file = a.txt, status = old, iostat = err) 7 if (err 0) then print*, unable to open file . 9 stop end if 11 do ! read line by line of the a.txt 13 read (5, (a), iostat = err) line if (err == -1) exit ! EOF detected
  • 56. 56 15 print*,line ; end do 17 close (5) end program open_file ✌ ✆ ✞ This is file a.txt ✌ ✆ 0.12.7 Writing File To write contents into an opened file, write() function is used. Its syntax is ✞ 1 write(unit =u, fmt=write format ) content buffer variable ✌ ✆ See the example given below: ✞ 1 program open_file implicit none 3 character (50) :: line integer :: err 5 open (unit = 5, file = a.txt, status = old, iostat = err) if (err 0) then 7 print*, unable to open file . stop 9 end if write(5, (a), iostat = err) This is test string. 11 close (5) end program open_file ✌ ✆ If write() function is used as ✞ write(*, *) ✌ ✆ then the output is written in the output console. ✞ 1 program open_file implicit none 3 write(*, *) This is test string. end program open_file ✌ ✆ ✞ This is test string. ✌ ✆ 0.12.8 Remove a File To remove an existing file, unlink() function is used. If a file is already open, and being removed, then the file should be closed before using this function.
  • 57. 0.12. INPUT OUTPUT 57 ✞ 1 program myStr call unlink(a.txt) 3 end program myStr ✌ ✆ It will remove the existing file ‘a.txt’. 0.12.9 Rename a File To rename a file, create a new file with new name, copy the contents from the old file into this new file. After successful copying of data, delete the old file. ✞ 1 program rename_file implicit none 3 character (20) :: of , rnf character (50) :: line 5 integer :: err read *, of 7 read *, rnf ! open a old file with stream id 5 9 open (unit = 5, file = of , status = old, iostat = err) if (err 0) then 11 print*, unable to open file , of stop 13 end if ! open a new file with stream id 6 15 open (unit = 6, file = rnf , status = new, iostat = err) if (err 0) then 17 print*, unable to open file , rnf stop 19 end if do 21 ! read line by line from the old file read (5, (a), iostat = err) line 23 if (err == -1) exit ! EOF detected ! write contents to the new file 25 write(6, (a), iostat = err) line ; end do 27 close (5) close (6) 29 ! delete old file call unlink(of) 31 end program rename_file ✌ ✆ To check the result, open the project directory and you will see that file a.txt is not existed in the directory. The ready-made subroutine rename() can be used to rename the existing file. It is used as ✞ 1 call rename(old path , new path , st ) ✌ ✆ ‘sr’ returns the status of file renaming operation.
  • 58. 58 0.12.10 Current Position of Stream ftell() retrieves the current position within an open file. This intrinsic is provided in both subroutine and function forms; however, only one form can be used in any given program unit. ✞ 1 program fTell integer :: i 3 open (10, file = a.txt) call ftell(10, i) 5 write(*, *) i close (10) 7 end program fTell ✌ ✆ ✞ 0 ✌ ✆ 0.12.11 Read Single Char From Instream fget() function is used to get the input contents from instream. Its syntax is ✞ 1 fget (string var , status var ) ✌ ✆ See the example below: ✞ 1 program myStr integer :: st , i = 1 3 character (len = 10) :: str = write (*, *) Enter text : 5 !Receive the contents . !At end of line ENTER key is pressed 7 do call fget (str(i:i), st) 9 if (st /= 0 .OR. i 10) exit i = i + 1 11 end do write (*, *) trim (str) 13 end program myStr ✌ ✆ ✞ Enter text : this is my string this is my ✌ ✆ 0.12.12 Write Single Char in Outstream fput() function is used to put a single character in stream mode to stdout by bypassing normal formatted output.
  • 59. 0.12. INPUT OUTPUT 59 ✞ 1 program myStr character (len = 10) :: str = gfortran 3 integer :: i do i = 1, len_trim (str) 5 call fput (str(i:i)) end do 7 end program myStr ✌ ✆ ✞ gfortran ✌ ✆ 0.12.13 Read Single Char From File Stream fgetc() function is used to read a text file character by character. This function is used as ✞ 1 fgetc(file stream , char var , position status ) ✌ ✆ Example is given below: ✞ 1 program myStr integer :: st 3 character :: c open (unit = 10, file = a.txt, status = old) 5 do call fgetc(10, c, st) 7 if (st /= 0) exit call fput (c) 9 end do close (10) 11 end program myStr ✌ ✆ ✞ Hi , my name is arun . ✌ ✆ 0.12.14 Write Single Char in File Stream fputc() function is used to put a single character in file stream by bypassing normal formatted output. ✞ 1 program myStr character (len = 10) :: str = gfortran 3 open (unit =10, file = a.txt, status = new) do i = 1, len_trim (str) 5 call fputc(10, str(i:i)) end do 7 close (10) end program myStr ✌ ✆ See the file ‘a.txt’ in the project directory. The contents “gfortran” is wrote in this file.
  • 60. 60 0.12.15 File Number fnum() returns the POSIX file descriptor number corresponding to the open FORTRAN I/O unit UNIT. ✞ program myStr 2 integer :: i open (unit =10, status = scratch ) 4 i = fnum (10) print *, i 6 close (10) end program myStr ✌ ✆ ✞ 3 ✌ ✆ 0.13 Time 0.13.1 CPU Time cpu time() function is used to get the CPU time at the moment. ✞ 1 program ExecTime real :: i 3 call cpu_time (i) print*, i 5 end program ExecTime ✌ ✆ ✞ 3.12500000 E-02 ✌ ✆ Execution time of a code program, we get the two consecutive CPU times. First at the beginning of the code and second at the end of code. The difference between two is time taken by CPU to execute the codes. ✞ 1 program ExecTime integer :: k 3 real :: i, f call cpu_time (i) 5 do k = 1, 5000000 if (mod(k, 1000000) == 0) then 7 print*, k end if 9 end do call cpu_time (f) 11 print*, (Time = , f - i, seconds .) end program ExecTime ✌ ✆
  • 61. 0.13. TIME 61 ✞ 1000000 2000000 3000000 4000000 5000000 (Time = 1.56250000 E -02 seconds .) ✌ ✆ 0.13.2 Convert Time into String ctime() converts a system time into a string. The converted string contains day name, month name, day of month, time in hours, minutes second and year. ✞ program myTime 2 integer (8) :: i character (len = 30) :: date 4 i = time8() call ctime(i, date ) 6 print *, Date time is , date end program myTime ✌ ✆ ✞ Date time is Fri Feb 3 11:22:59 2017 ✌ ✆ 0.13.3 Date Time date and time() gets the corresponding date and time information from the real-time system clock. Date is in form of yyyymmdd. Time has form hhmmss.mls. Zone has form (+-)hhmm, representing the difference with respect to Coordinated Universal Time (UTC). Unavailable time and date parameters return blanks. ✞ 1 program myTime character (8) :: date !8 bytes long , yyyymmdd 3 character (10) :: time !10 bytes long , hhmmss.mls character (5) :: zone !5 bytes long , +-hhmm 5 integer , dimension (8) :: values !8 parts of date time call date_and_time (date , time , zone , values) 7 print (a,2x,a,2x,a), date , time , zone print (8i5), values 9 end program myTime ✌ ✆ ✞ 201723 115847.406 +530 2017 2 3 330 11 58 47 406 ✌ ✆
  • 62. 62 0.14 Data Structures 0.14.1 Structure In FORTRAN, there is a special data type commonly known as derived datatype or structure. It is used to object with different type of variables. The derived datatype is declared as ✞ type :: Name 2 character :: lable int :: age 4 end type Name ✌ ✆ We can create object type using type keyword as ✞ type (Name ):: x ✌ ✆ The components of the structure can be accessed by using component selector character % as ✞ 1 type (Name ):: x x%lable = K 3 x%age = 10 ✌ ✆ 0.14.2 Modules In FORTRAN, a module is package of code which can be used recursively as and when required. A module is declared with module keyword. ✞ 1 module module name implicit none 3 specification statements contains 5 procedures end module module name ✌ ✆ The specification statements includes local variables, parameters etc. The procedure block contains codes functions, subroutine etc. Modules are accessed by use command. To access the module use following syntax ✞ use module name ✌ ✆ Subroutines or procedures of module are accessed by call() function. ✞ 1 call procedure call subroutine ✌ ✆
  • 63. 0.14. DATA STRUCTURES 63 ✞ module myMod 2 implicit none real , parameter :: pi = 3.1415926536 4 contains function area (r) result (a) 6 real :: a, r a = pi * r * r 8 end function area 10 end module myMod 12 program myProg use myMod 14 implicit none 16 print*, Area is , area (2.0) end program myProg ✌ ✆ ✞ Area is 12.5663710 ✌ ✆ By default, everything in a module is publicly available. However, accessibility can be controlled by private and public attributes. Everything that is declared as private is not available outside the module. The public attribute makes available all the elements of a module outside the module. To restrict their access, only options restricts their access. It is used as ✞ 1 use module name only : public var 1, public var 2, ... ✌ ✆ The module codes can be wrote in the same file where they are used or in separate file. If module is written in separate file then the file should be named as module name with extension ‘.mod’.
  • 64. 64 0.15 Reserved Keywords allocatable allocate assign assignment block call case character common complex contains continue cycle data deallocate default do double precision else if elsewhere end entry equivalence exit external function go to if implicit in inout integer intent interface intrinsic kind len logical module namelist nullify only operator optional out parameter pause pointer private program public real recursive result return save select stop subroutine target then type type() use Where While backspace close endfile format inquire open print read rewind Write