Basic ForTran Programming - for Beginners - An Introduction by Arun Umrao
96 views
64 slides
Oct 10, 2021
Slide 1 of 64
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
About This Presentation
ForTran Programming Notes for Beginners. With complete example. Covers full syllabus. Well structured and commented for easy - self understanding. Good for Senior Secondary Students.
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.
✞
1programMyProg
print*," First FORTRAN Program " ," is this ?"
3end program MyProg
✌
✆
A block of program codes may be named or unnamed. A named block ofprogram codes
must be closed withendkeyword. A syntax of named code block in FORTRAN is given
below:
✞
1myCode :
< statements >
3endmyCode
✌
✆
IWorking examples of this book are compiled with gfortran compiler ofMinGW 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 alist 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.
✞
1programMyProg
print"( a50 )"," First FORTRAN Program "
3end program MyProg
✌
✆
✞
First FORTRAN Program
✌
✆
6
0.2.1 Print to Console
printkeyword 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.
✞
1print*,’ Hello World ’
end
✌
✆
✞
Hello World
✌
✆
0.2.2 Read from Console
The inputs for variables are read from console by usingreadoperator as
✞
1read*, x ,y ,z
✌
✆
Here, three continuous inputs are read and assigned to x, y and z.
✞
1programMyProg
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:
✞
programmyQuot
2 print*,’f ’
print*,"F"
4end program myQuot
✌
✆
✞
f
F
✌
✆
0.2. FORMATTED I/O 7
0.2.4 Implicit
Dictionary meaning ofimplicitis “inherent in the nature of something”, i.e. when a
variable is declared to certain datatype, then its nature is changedto that type until
unless those variables are not re-declared explicitly. Although onlyintegerandrealtype
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
doubledatatype variable is declared as
✞
1implicit double
✌
✆
If aimplicitkeyword 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.
✞
1programmyImp
u = 2.0! by default real value
3 v = 3.0! by default real value
print*,complex(u , v)
5end program myImp
✌
✆
✞
(2.00000000 , 3.00000000)
✌
✆
If,implicitkeyword is used withnonekeyword, 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.
✞
1programmyImp
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)
7end 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:
✞
1programmyImp
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)
7end program myImp
✌
✆
Above program will show compile time error ascomplex() function does not accepts
complex values. It accepts real values. If theimplicitvariables are re-declared as explicit
type, then they override to the implicit type variables. Above program is modified as
given below:
✞
1programmyImp
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)
7end 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 lineterminating 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> :: < variablename>
✌
✆
For example, an integer type variable is declared as
✞
1int :: 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> :: < variablename1>, < variablename2>, ...
✌
✆
0.3. VARIABLES & DATATYPE 9
Characters
The keywordcharacteris used to define a character type or a string type variable. Length
of string that is assigned to the character type variable is controlled bylenkeyword. A
character variable is declared as
✞
1character(len=80) :: <char variable >
✌
✆
Here,len=80 controls the number of characters assigned to the string variable.
✞
1programMyProg
character(len= 80) ::name
3 read*,name
print*,name
5end 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:
✞
1int :: < variable name1>, < variablename2>, ...
✌
✆
✞
1programMyProg
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 inFORTRAN
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
✞
1programmyMath
print*, 5.2 - 2.5
3end program myMath
✌
✆
✞
2.69999981
✌
✆
The real variable is declared as
✞
1real:: r
✌
✆
Example ofrealdatatype is given below:
✞
1programreal_no
implicit none
3 real:: a = 12.5
print*, a
5end program real_no
✌
✆
✞
12.5000000
✌
✆
Theimplicit nonestatement allows the compiler to check whether our all variable datatypes
are declared properly or not. You must always useimplicit noneat the beginning of a
program. FORTRAN has definite precision points. There is a method to control the
precision of therealnumbers. To do, we usekindkeyword as shown below:
✞
1real(kind=kind(1.0 d0 )) :: < variablename>
✌
✆
See the example given below:
✞
1programreal_no
implicit none
3 real(kind(1.0 d0 )) :: a = 12.5
print*, a
5end 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), whereirepresents to imaginary part of the
complex number. Here,aandbare real numbers. In FORTRAN, a complex number is
represented as (a, b), which is equal to (a+bi). The complex variable is declared as
✞
1complex:: 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 numbersz1=−2 +iandz2= 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.
✞
1programMyProg
complex:: z1 , z2 , z3
3 z1 = ( -2 , 1)
z2 = (1 , -2)
5 z3 = z1 * z2
print*, z3
7end 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
theparameterattribute:
✞
1real,parameter:: pi = 3.1415
✌
✆
✞
1programmyPtr
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
13end 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.
✞
1programmyPtr
implicit none
3
print*," True value ", . true .
5 print*," False value ", . false .
7end 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 usingparameterkeyword as shown below
✞
1real,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 aspublicor its access
can be restricted by declaring it asprivate. The syntax of public and private parameters
are given below:
✞
1real,parameter,private:: f! private parameter f
real,parameter,public:: g! public parameter g
3real,public:: h! public variable h
✌
✆
We can initialize a variable by assigning them a value.
✞
1real,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
OperatorMeaning
.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
✞
programmyLog
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
8end 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 asy=b∗ ∗e), multiplication (represented asy=a∗b),
division (represented asy=a/b), addition (represented asy=a+b) and subtraction
(represented asy=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 blockis evaluated. In
FORTRAN there are following relational operators.
14
OperatorDescription
< 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:
✞
1programif_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
11end 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:
✞
1character(len=<n >) :: < string variable > ! declaration
< string variable >=" My String "! initialization
✌
✆
Here,len=< n >reserves thencharacter spaces for storing of string. If length size,n,
is less than the string size then only firstncharacters 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
✞
programsubStr
2 implicit none
character(len= 5) :: mystr ! declaration
4 mystr =" This is test string ."! initialization
print*, mystr
6end 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.
✞
1programsubStr
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;
✞
1programsubStr
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
trimfunction is used to adjust trailing blank spaces from a string and inserting leading
blank space. See the example below:
✞
1programsubStr
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
✞
1programsubStr
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 ofsubstring within
given string. Its syntax is
✞
1index (< string >, < substring >, < true or false >)
✌
✆
If third argument of the function is true, thenindexreturns the rightmost starting position
and if it is false then it returns the leftmost starting position.
✞
1programmyP
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 functionis explained in
the following example.
✞
programsubStr
2 implicit none
character(len= 5) :: mystr ! declaration
4 mystr =" This is test string ."! initialization
print*,len( mystr )
6end 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 uselentrim() function to get the length of string without tailing spaces.
✞
1programmyStr
character(len= 10) :: str = " gfortran "
3 integer:: i
doi = 1, len_trim ( str )
5 callfput ( str (i :i))
end do
7end program myStr
✌
✆
✞
gfortran
✌
✆
0.5.6 Lexical Comparison
lge(),lgt(),lle() andllt() functions are used to check the lexical comparison between two
strings. The syntax of these functions are
✞
1lge (< string a >, < string b >)
lgt (< string a >, < string b >)
3lle (< string a >, < string b >)
llt (< string a >, < string b >)
✌
✆
Here,lgeis acronym of ‘lexical greater than or equals to’,lgtis acronym of ‘lexical greater
than’,lleis acronym of ‘lexical less than or equals to’ andlltis 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’).
✞
programmyP
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.
✞
1programmyChar
integer:: i
3 doi = 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:
✞
1programRepStr
print*, repeat ("x", 5)
3end program RepStr
✌
✆
✞
xxxxx
✌
✆
This function receives two arguments, first the string and secondthe 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
✞
1function< funcname>( < args vars separated by comma >)
< expressions / statements >
3end function < funcname>
✌
✆
The declared function is called by passing the argument values. Callingof a function is
like
✞
1< funcname>( < 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
✞
1function< funcname>( < args var >)result(<resultvar >)
< expressions / statements >
3end function < funcname>
✌
✆
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.
✞
1functionprod (m , n)result(a)
real:: m , n
3 real:: a
a = m * n
5end function prod
programmyProg
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.
✞
1functionpr od _(m , n)result(a)
real:: m , n
3 real:: a
a = m * n
5end function pr od _
programmyProg
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 usingintent() function. For example, if
argument of a function are only to be used then this function is usedas
✞
1real,intent(in) :: a
✌
✆
If argument is to be overwrite then use following syntax
✞
1real,intent(out) :: a
✌
✆
If argument is used and overwritten then syntax is used as
✞
1real,intent(inout) :: a
✌
✆
In the following example, a square function is created and called insidefrom the user
program.
✞
1functionsquare (p)result(s)
integer:: p
3 s = p * p
end function square
5programMyProg
integer:: a
7 a = square (5) ;
print*, a
9end 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
✞
1interface
subroutine<sr >( < v1 >, <v2 >)
3 real,intent(inout) :: x ,y
end subroutine <sr >
5end interface
✌
✆
This interface block is placed at the beginning of the program together with the declara-
tion statements.
✞
1programarea
implicit none
3 interface
functioncircleArea (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
11functioncircleArea (r)
implicit none
13 real:: circleArea
real,intent(in) :: r
15 real,parameter:: pi = 3.1415927
circleArea = pi * r * r
17end 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,resultoption must be
used.
✞
1programmyProg
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 withendoperator. 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.ifis followed by condition and then bythenoperator. Each
ifopened should be closed by using keywordend. The syntax ofif() construct is
22
✞
1if(< conditions >)then! if condition is true then
statement! execute the condition .
3end if
✌
✆
A simple example is
✞
1programmyLog
real:: u
3 u = 2.0
if(u == 2.0)then
5 print*, u
end if
7end program myLog
✌
✆
✞
2.00000000
✌
✆
0.7.2 If-else Condition
if-elseprovides 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 forif, are true forelsestatement. This is whyelsehas infinite numbers
of true conditions. The syntax ofif-elseconstruct is
✞
1if(< conditions >)then! if condition is true then
statement one ! execute the statement one .
3else! otherwise if condition is false
statement two ! execute the statement two .
5end if
✌
✆
A simple example is
✞
1programmyLog
real:: u
3 u = 2.5
if(u == 2.0)then
5 print*, u
else
7 print*, 0
end if
9end program myLog
✌
✆
✞
0
✌
✆
multi-line statement can be written one after another. Expressionshould 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
endkeyword.
0.7. CONDITIONS 23
✞
1programmyLog
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
Twoif() conditions can be linked byelsekeyword.if-else-ifprovides 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 firstif, are true forelse-ifstatement. This is why,else-ifhas infinite numbers of
true conditions. These infinite numbers of conditions are again checked forifstatement
and the corresponding block is executed if certain conditions are met, otherwise these
conditions are skipped to nextelse-ifstatement. The syntax of the linkedifconditions
is
✞
1if(< condition 1 >)then
< expressions 1>
3else if(< condition 2 >)then
< expressions 2>
5else if(< condition 2 >)then
< expressions 3>
7end if
✌
✆
Anif-else-if-elseconditional example is given below:
✞
1programmyLog
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
11end program myLog
✌
✆
✞
2.50000000
✌
✆
0.7.4 Select Case
Use of a long chain ofif-else-if-else-if-elseis very complex and less readable. There’s a
solution by using the select-case construct.case() is similar toifstatement except that
select-caseaccepts single argument only and compare the argument value with arange
of definedcase() values. It executes the block of statements for whichcase() is matched.
In contrast tocase(),if() is fixed type and executes succeeding block of statements. Each
select, which started at the beginning of a block must be closed byendkeyword at the
end of the block. The basic syntax of this construction is given below.
✞
1select case (<casevariable >)
case(< var value 1 >)
3 < first statements >
case(< var value 2 >)
5 < second statements >
case(< var value 3 >)
7 < third statements >
case default
9 <defaultstatements >
end select
✌
✆
Heredefaultcase is executed if none of the cases is matched withselectvariable value.
Thecase defaultis optional, but with acase default, it is guaranteed that what ever is the
selector value, one of the statement will be used. There is no orderto putcase default,
yet in programming conventions,case defaultis put in the last.
✞
programmySelCase
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
12end 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.
✞
1programmySelCase
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
✌
✆
Incase(), we can use discrete ranges from ‘a’ to ‘b’ and ‘c’ to ‘d’ as shown below:
✞
1case(a:b , c:d)
✌
✆
The literal characters may also be used in thecase() if they are written in single quotes.
See the example below:
✞
1programmySelCase
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
exitkeyword is used by ForTran to exit from a loop. It should be always within a construct
otherwise the compiler will throw compile time error.exitkeyword is also used to break
a continuous loop.
✞
1programmyMath
integer:: i
3 doi = 1, 10
if(i == 5)then
5 exit
26
end if
7 print*, i
end do
9end program myMath
✌
✆
The output of above program is
✞
1
2
3
4
✌
✆
0.7.6 Do Loop
dooperator is used to perform continuous iteration. It also acceptslower limit of iteration,
upper limit of iteration and iteration step size. Its syntax is
✞
do<var >= < from >, <to>
2 < statements >
end do
✌
✆
The syntax ofdooperator with iteration step size is given below:
✞
1do<var >= < from >, <to>, < stepsize>
< statements >
3end do
✌
✆
Encapsulation ofdooperator is allowed. The encapsulation ofdooperator is done as
below syntax.
✞
1myBlock :do<var >= < from >, <to>, < stepsize>
< statements >
3end domyBlock
✌
✆
✞
1programmyArr
! do loop
3 dok = 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
✞
1dok = 1, 5! only two inputs for k
✌
✆
Third input or step size argument ofdooperator, changes the value of k as (k=k+2)<=
5. See the example given below:
✞
1programmyArr
! do loop
3 dok = 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.
✞
1programmyTest
integer:: i = 1, j = 2
3 if(i /= j)callabort
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.
✞
1programmyAlarm
externalprintIt
3 integerst
callalarm (2 , printIt , st )
5 callsleep (10)
print*, st
7end program myAlarm
subroutineprintIt
28
9 print*," Called "
end subroutine printIt
✌
✆
✞
Called
0
✌
✆
0.8.3 Signal
signal() causes external subroutine to be executed with a single integerargument 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
✞
programmySig
2 intrinsicsignal
externalprintIt
4 integerst
callsignal (2 , printIt , st )
6 callsleep (1)
print*, st
8end program mySig
subroutineprintIt
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 thesleepfunction. The argument value is number of seconds.
✞
1programWaitFor
callsleep (5)! wait for 5 seconds
3end program WaitFor
✌
✆
0.8.5 Get Process ID
getpid() returns the numerical process id. It is used as
✞
1print*, getpid ()
✌
✆
✞
1programmyP
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 isshown in the
following example.
✞
1programHostName
character(len=50) :: h
3 callhostnm (h)
print*, h
5end 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)|=
−xifx <0
xifx≥0
✞
1programsubStr
print*, abs ( -2.5)
3end 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 isbiand real number of imaginary part isb. The
syntax of this FORTRAN function is
✞
1ip = aimag (z)
✌
✆
Example is
✞
1programmyCompl
complex:: z
3 z =complex(2 , 3)
print*," Imaginary part is " , aimag (z)
5end 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 acceptablewhile 2.0/3.0 is
acceptable.
0.9. MATHEMATICS 31
✞
1programmyMath
real:: z
3 z = 2.35
print*," Whole part is ", aint (z )
5end 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.
✞
1programmyMath
real:: z
3 z = 3.552
print*," Whole part is ", anint ( z)
5end 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.
✞
1programCeilValue
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).
✞
programmyMath
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:
✞
1programmyMath
real:: z
3 z = 3.552
print*," Complex number is " , cmplx (z , 2)
5end 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 byz=a+bi
then complex conjugate of this number is given by ˉz=a−bi.
✞
1programmyMath
complex:: z
3 z = (2 , 3)
print*," Complex conjugate is " , conjg (z)
5end 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 15
th
decimal places.
✞
1programmyP
print*, dble (20)
3end program myP
✌
✆
✞
20.000000000000000
✌
✆
0.9. MATHEMATICS 33
Difference
dim() returns the difference of two given numbers. The second argument ofdim() function
is subtracted from the first argument of the function. If secondargument is greater than
the first argument then result is zero. Mathematically, this function obeys the piecewise
function rule as
dim(a, b) =
a−bifa≥b
0 if a < b
See the ForTran program containingdim() function as given below:
✞
1programmyMath
print*, dim (5.2 , 2.5)
3 print*, dim (2.5 , 5.2)
end program myMath
✌
✆
✞
2.69999981
0.00000000
✌
✆
Significant Digit
Significant Scientific NumbersThe digits of mantissa of a number expressed in scien-
tific notation are called significant figures or significant digits. A zerois always significant
if it is right of the non zero digits or right of the decimal. For example
Number Scientific NotationSignificant Figures
132.00 1.3200×10
2
5
0.0123540 1 .23540×10
−2
6
-0.125 −1.25×10
−1
3
25250 2 .5250×10
4
5
A point is to be remember that 2.5250×10
4
and 2.525×10
4
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 integerdata format, 32 bits
are used in computation of the number.digits() returns mantissa bits. See the following
example:
✞
programmyProg
2 print*, digits (2.1000) ! Real number
print*, digits (21000) ! Integer
4end 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.
✞
programmyP
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.
✞
1programFloorValue
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 thereal part of the
number. The argument to this number should be a real type.
✞
programmyP
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.
✞
1programMaxValue
integer:: m
3 m = max (5 , 2, 3)
print*," Maximum value is ", m
5end program MaxValue
✌
✆
✞
Maximum value is 5
✌
✆
Minimum Value
min() returns the minimum value among all the values supplied to the function as its
arguments.
✞
1programMinValue
integer:: m
3 m = min (5 , 2, 3)
print*," Minimum value is ", m
5end program MinValue
✌
✆
✞
Minimum value is 2
✌
✆
Modulo
mod() ormodulo() returns the mod between two numbers. Mod is remainder value in
division of a number by other number.
✞
1programmyMod
integer:: m
3 m= mod (7 , 2)
print*," Mod is ", m
5end 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
✞
1programmyP
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, aninteger value ‘6’
is supplied to functionreal() which returns the real form of this integer.
✞
programmyP
2 print*,real(6)
end program myP
✌
✆
✞
6.00000000
✌
✆
Exponent Part
exponent() returns the exponent part of a number. An exponent is denoted byy=a
b
.
Here,bis exponent andais base of exponent. This function uses inequality to get the
exponent of the number. The inequality is
2
b−1
≤y <2
b
Wherebis exponent.
✞
1programmyP
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 writtenin form ofa/b
then fraction part is the decimal part of the result obtained from the division ofa/b.
✞
programmyMath
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
✞
1programmySum
integer:: x (10) , i , s
3 doi = 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() andtan() 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
✞
1programmyProg
print*, sin (2.0)
3 print*, cos (2.0)
print*, tan (2.0)
5end program myProg
✌
✆
✞
0.909297407
-0.416146845
-2.185039760
✌
✆
Principle of trigonometry are applied in the computation of these functions.
sinh, cosh & tanh
sinh(),cosh() andtanh() 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() andtan().
✞
1programmyProg
print*, sinh (1.0)
3 print*, cosh (1.0)
print*, tanh (12.0)
5end program myProg
✌
✆
✞
1.17520118
1.54308069
1.00000000
✌
✆
asin, acos & atan
asin(),acos() andatan() returns their respective angular results in radian when they are
supplied by inputs (arguments) in number. These functions are alsocalled inverse of the
primary trigonometric functions, i.e.sin(),cos() andtan().
Function Domain Range
sin
−1
[−1,1]
h
−
π
2
,
π
2
i
cos
−1
[−1,1] [0 , π]
tan
−1
(−∞,∞)
h
−
π
2
,
π
2
i
✞
1programmyProg
print*, asin (1.0)
3 print*, acos (1.0)
0.9. MATHEMATICS 39
print*, atan (12.0)
5end 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 toe
x
, wherexis a real number.eis universal natural
logarithmic base. The algebraic series representation ofexp(x) is given by
e
x
= 1 +x+
x
2
2!
+
x
3
3!
+
x
4
4!
+. . .
exp(1) is equal to 2.718281828.
✞
1programmyMath
print*, exp (2.0)
3end program myMath
✌
✆
✞
7.38905621
✌
✆
Natural Log
log() is logarithm of a number about natural basee. Natural logarithm of a number can
be converted into the common logarithm by using relation
log
e(a) =
log
10(a)
log
e(a)
Or
log
e
(a) = 2.30258×log
10
(a)
✞
1programmyMath
print*, log (2.0)
3end 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
log
e
(a) = 2.30258×log
10
(a)
✞
1programmyMath
print*, log10 (2.0)
3end 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.
✞
1programmyMath
print*," Square root ", 2.254 ," is ", sqrt (2.254)
3end 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
bitsize() returns the number of bits of a model. The input argument of thisfunction is
a binary form of number.
✞
1programmyMath
print*, bit_size (10001001)
3end 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.
✞
1programmyMath
print*, btest (10001001 , 2) !3 rd bit from LSB , F
3 print*, btest (10001001 , 3) !4 th 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
201010001 = 81
----------------AND
400010000 = 16
✌
✆
✞
programBitWise
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:
✞
100110010 = 50
% clear 2 nd bit from LSB , index = 1
300110000 = 48
✌
✆
Example in FORTRAN is given below:
✞
1programBitWise
print*, ibclr (50 , 1)
3end 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.
✞
1ibits (<number>, < index from LSB >, <numberof bits from LSB toMSB >)
✌
✆
Example is given below:
✞
1programmyMath
! 150 D = 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
9end 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 is0, it is reset to 1.
Its description is given below:
✞
00110010 = 50
2% set 3 rd bit from LSB , index = 2
00110110 = 50
✌
✆
Example in FORTRAN is given below:
✞
1programBitWise
print*, ibset (50 , 2)
3end 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
✞
100110010 = 50
01010001 = 81
3----------------XOR
01100011 = 99
✌
✆
✞
programBitWise
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
✞
100110010 = 50
01010001 = 81
3----------------OR
01110011 = 115
✌
✆
✞
programBitWise
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 200in decimal. The
example in FORTRAN is given below:
✞
1programBitWise
print*, ishft (50 , 2)
3end 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:
✞
1programBitWise
print*, ishft (50 , -2)
3end program BitWise
✌
✆
✞
12
✌
✆
Remember that in left shift by +nplaces,nnumber of 0 bits are post-fixed to the binary
number. Similarly in case of right shift by−nplaces,nnumbers 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:
✞
1programBitWise
! 50 D = 00110010 B
3 ! NOT of 50 D = 11001101 B
! 11001101 B = 205 D = -51 D
5 print*, not (50)
end program BitWise
✌
✆
✞
-51
✌
✆
0.10 Array
In ForTran, arrays are declared as
✞
1integer:: < arrayname>( <numberof elements >)
✌
✆
Here, keywordintegerspecified 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
✞
1programmyArr
! Array of 5 elements
3 integer:: myA (5)
! Add values to array
5 dok = 1, 5
myA (k) = 2 * k
0.10. ARRAY 45
7 end do
! Print array elements
9 dok = 1, 5
print*, myA (k)
11 end do
end program myArr
✌
✆
✞
2
4
6
8
10
✌
✆
A multidimensional array is declared as
✞
1integer:: < arrayname>( < rows dim >, < cols dim >)
✌
✆
Here, ‘rows dim’ is number of rows and ‘cols dim’ is number of columns in an integer
datatype array.
✞
1programmyArr
! Array of 2 rows 5 cols
3 integer:: myA (2 , 5)
! Add values to array
5 dok = 1, 2
dol = 1, 5
7 myA (k , l) = k + l
end do
9 end do
! Print array elements
11 dok = 1, 2
dol = 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 withdimensionkeyword followed by number of
element.
✞
1programmyArr
! Array of 4 elements
3 integer,dimension(4) :: myA
! Add values to array
5 dol = 1, 4
myA (l) = 2 * l
7 end do
! Print array elements
9 dol = 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.
✞
programmyArr
2 ! Array of 4 elements
integer,dimension(4) :: myA
4 ! Try to add 5 values to array
dol = 1, 5
6 myA (l) = 2 * l
end do
8end program myArr
✌
✆
A two dimensional array is declared as
✞
real,dimension(2 , 4) :: < array var >! 2 rows 4 columns
✌
✆
✞
1programmyArr
! Array of 2 row 5 cols
3 integer,dimension(2 , 5) :: myA
! Add values to array
5 dok = 1, 2
dol = 1, 5
7 myA (k , l) = k + l
end do
9 end do
! Print array elements
0.10. ARRAY 47
11 dok = 1, 2
dol = 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 indexof elements. For exam-
ple, array element should be indexed from ‘1’ to ‘5’. See the example below:
✞
1programmyArr
! array of 5 elements
3 integer,dimension(1:5) :: myA
! add values to array
5 dol = 1, 5
myA (l) = 2 * l
7 end do
! print elements of array
9 dol = 1, 5
print*, myA (l)
11 end do
end program myArr
✌
✆
✞
2
4
6
8
10
✌
✆
All the following type declaration statements are legal:
✞
1real,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.
✞
programmyArr
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
dok = 1, 5
8 dol = 2, 3
myA (k , l) = 2 * l + k
10 end do
end do
12 ! print elements of array
dok = 1, 5
14 dol = 2, 3
print*, myA (k , l)
16 end do
end do
18end 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,Ais
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.
✞
programmyArray
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 bym×n×. . .in whichm,n,
. . .represents to each dimension of the array.
✞
programtest_shape
2 integer,dimension( -1:1 , -1:2) :: A
write(* , *) shape (A )
4end program
✌
✆
✞
3 4
✌
✆
0.10.4 Size of Array
Size of array specified the number of elements present in an array.An array having
dimensionmrows andncolumns hasm×nsize or element.size() function is used to
get the number of element in matrix or dimension of the row.
✞
1programmyArray
implicit none
3 integer,dimension(6) :: myArr ! declaration
print*,size( myArr )
5end program myArray
✌
✆
✞
6
✌
✆
0.10.5 Passing Array to Function
Function in ForTran is called sub-routine.calloperator 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
✞
1subroutine< sname >( < arg >)
.....................
3end subroutine < sname >
!
5program< pname >
call< sname >( < arrayname>)
7end program < pname >
✌
✆
See the following example.
✞
1programpassArray
implicit none
3 integer,dimension(5) :: myArray
integer:: i
5 ! call subroutine and pass array as its argument
callAddValueToArr ( myArray )
7 ! call subroutine to print array elements
callPrintArrValues ( myArray )
9end program passArray
!
11subroutineAddValueToArr (a)
implicit none
13 integer,dimension(5) ,intent(out) :: a
integer:: i
15 doi = 1, 5
a (i) = i
17 end do
end subroutine AddValueToArr
19!
subroutinePrintArrValues (a)
21 integer,dimension(5) :: a
integer:: i
23 doi = 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 rankof the array or
matrix. The syntax of this function is
0.11. POINTER 51
✞
1cshift (< 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.
✞
1programArrayShift
integer:: k (5) , i
3 doi = 1, 5
k (i) = i
5 end do
k = cshift (k , 2, 1)
7 doi = 1, 5
print*, k(i)
9 end do
end program ArrayShift
✌
✆
✞
3
4
5
1
2
✌
✆
✞
1programArrayShift
integer:: k (5) , i
3 doi = 1, 5
k (i) = i
5 end do
k = cshift (k , -2, 1)
7 doi = 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 thepointerattribute. A pointer variable that is an
array must be a deffered-shape array. A pointer is allocated to a variable as
✞
1integer,pointer:: p! pointer to integer
real,pointer,dimension(:) :: rp! pointer to one dim array
3real,pointer,dimension(: ,:) :: r2p! pointer to two dim array
✌
✆
52
A pointer in FORTRAN points to an area of dynamically allocated memoryor a data
object of the same type as the pointer with the target attribute.Space for pointer is
allocated by usingallocate() function.
✞
1integer,pointer:: p! pointer to integer
allocate( p)! allocate dynamic memory to p
✌
✆
✞
programmyPtr
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.
✞
programmyP
2 integer,pointer:: p1
integer,target :: p2
4 p1 => p2
end program myP
✌
✆
The functionassociated() returns the association between pointer and its target. It
returns true, if the pointer is associated with target otherwise returns false. Its syntax is
✞
1associated (p1 , p2 )
✌
✆
loc() function returns the address of the variable. It is used as
✞
1programVarAddress
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.
✞
1programmyChdir
character(len= 255) :: path
3 callgetcwd ( path )
write(* , *) trim ( path )
5 callchdir ("C :/ ")
callgetcwd ( 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.
✞
programmyChdir
2 character(len= 255) :: path
callgetcwd ( 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
chmodutility as defined by the POSIX standard. The argument shall eitherbe a string
of a non-negative octal number or a symbolic mode.
✞
1programmyDir
implicit none
3 integer:: st
callchmod (’ test . dat ’,’u + x ’, st )
54
5 print*,’ Status : ’, st
end program myDir
✌
✆
✞
Status : 1
✌
✆
The POSIX based file permission modes are
ModePermission 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
✞
1open(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 fileis correctly opened,
‘iostat’ is set to zero otherwise positive integer.
✞
1programopen_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.
✞
1open(unit=<u >,file="/< name >",status=<st >,action=< act >)
✌
✆
0.12.5 Close a File
Each file which is opened byopen() function, must be closed byclose() function. Its
syntax is
✞
1close(unit=<u >,iostat=< state >,status=<st >)
✌
✆
✞
1programopen_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)
11end 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
✞
1read(unit=<u >,fmt=<read format>) <readbuffer variable >
✌
✆
Here, ‘u’ is the stream number of the previously opened file.
✞
1programopen_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
✞
1write(unit=<u >,fmt=<write format>) < content buffer variable >
✌
✆
See the example given below:
✞
1programopen_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
✌
✆
Ifwrite() function is used as
✞
write(* , *)
✌
✆
then the output is written in the output console.
✞
1programopen_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
✞
1programmyStr
callunlink ("a. txt ")
3end 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.
✞
1programrename_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
callunlink ( of )
31end 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 subroutinerename() can be used to rename the
existing file. It is used as
✞
1callrename (< 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.
✞
1programfTell
integer:: i
3 open(10 ,file="a. txt ")
callftell (10 , i)
5 write(* , *) i
close(10)
7end 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
✞
1fget (< string var >, <statusvar >)
✌
✆
See the example below:
✞
1programmyStr
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
callfget ( str (i :i) , st )
9 if( st /= 0 . OR . i > 10)exit
i = i + 1
11 end do
write(* , *) trim ( str )
13end 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
✞
1programmyStr
character(len= 10) :: str = " gfortran "
3 integer:: i
doi = 1, len_trim ( str )
5 callfput ( str (i :i))
end do
7end program myStr
✌
✆
✞
gfortran
✌
✆
0.12.13 Read Single Char From File Stream
fgetc() function is used to read a text file character by character. Thisfunction is used as
✞
1fgetc (<filestream >, <char var >, <position status>)
✌
✆
Example is given below:
✞
1programmyStr
integer:: st
3 character:: c
open(unit= 10 ,file="a. txt ",status=" old ")
5 do
callfgetc (10 , c , st )
7 if( st /= 0)exit
callfput (c)
9 end do
close(10)
11end 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.
✞
1programmyStr
character(len= 10) :: str = " gfortran "
3 open(unit=10 ,file="a. txt ",status=" new ")
doi = 1, len_trim ( str )
5 callfputc (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 theopen FORTRAN
I/O unit UNIT.
✞
programmyStr
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
cputime() function is used to get the CPU time at the moment.
✞
1programExecTime
real:: i
3 callcpu_time (i)
print*, i
5end 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 differencebetween two is time
taken by CPU to execute the codes.
✞
1programExecTime
integer:: k
3 real:: i , f
callcpu_time (i)
5 dok = 1, 5000000
if( mod (k , 1000000) == 0) then
7 print*, k
end if
9 end do
callcpu_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.
✞
programmyTime
2 integer(8) :: i
character(len= 30) :: date
4 i = time8 ()
callctime (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
dateandtime() 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.
✞
1programmyTime
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
calldate_and_time ( date , time , zone , values )
7 print"(a ,2 x ,a ,2 x ,a )", date , time , zone
print" (8 i5 )", values
9end 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 deriveddatatype 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 >
4end type<Name>
✌
✆
We can create object type usingtypekeyword as
✞
type(<Name>) :: <x >
✌
✆
The components of the structure can be accessed by using component selector character
% as
✞
1type(<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 withmodulekeyword.
✞
1module<module name>
implicit none
3 < specification statements >
contains
5 < procedures >
end module<module name>
✌
✆
The specification statements includes local variables, parametersetc. The procedure
block contains codes functions, subroutine etc. Modules are accessed byusecommand.
To access the module use following syntax
✞
use<module name>
✌
✆
Subroutines or procedures of module are accessed bycall() function.
✞
1call< procedure >
call<subroutine>
✌
✆
0.14. DATA STRUCTURES 63
✞
modulemyMod
2 implicit none
real,parameter:: pi = 3.1415926536
4contains
functionarea (r)result(a)
6 real:: a , r
a = pi * r * r
8 end function area
10end modulemyMod
12programmyProg
usemyMod
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 byprivateandpublicattributes. Everything that is declared asprivateis not
available outside the module. Thepublicattribute makes available all the elements of a
module outside the module. To restrict their access,onlyoptions restricts their access.
It is used as
✞
1use<module name>only:<publicvar 1>, <publicvar 2>, ...
✌
✆
The module codes can be wrote in the same file where they are used orin 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