Fortran

0
24

Fortran – Overlook at

Fortran, as derived from Formula Translating System, is a general-purpose, imperative programming language. It is used for numeric and scientific complaceing.

Fortran was firstly developed simply simply by IBM in the 1950s for scientific and engineering applications. Fortran rubrought this particular programming area for a durationy time and became very popular for high performance complaceing, because.

It supslots:

  • Numerical analysis and scientific complaceation
  • Structucrimson-coloucrimson programming
  • Array programming
  • Modular programming
  • Generic programming
  • High performance complaceing on supercomplaceers
  • Object oriented programming
  • Concurrent programming
  • Reasonable degree of slotpotential between complaceer systems

Fbehaves abaway Fortran

  • Fortran was developd simply simply by a team, brought simply simply by John Backus at IBM in 1957.

  • Initially the name used to be developd in all capital, but current standards and implementations only require the preliminary permitter to be capital.

  • Fortran stands for FORmula TRANslator.

  • Originally developed for scientific calculations, it had very limited supslot for charbehaveer strings and other structures needed for general purpose programming.

  • Later extensions and developments made it into a high level programming language with great degree of slotpotential.

  • Original versions, Fortran I, II and III are conaspectcrimson-coloucrimson obsopermite now.

  • Oldest version still in use is Fortran IV, and Fortran 66.

  • Most commonly used versions today are : Fortran 77, Fortran 90, and Fortran 95.

  • Fortran 77 added strings as a specific type.

  • Fortran 90 added various sorts of threading, and direct array procesperform.

Fortran – Environment Setup

Setting up Fortran in Windows

G95 is the GNU Fortran multi-architechtural compiler, used for setting up Fortran in Windows. The earndows version emulates a unix environment uperform MingW below earndows. The installer conaspectrs care of this particular and automatically adds g95 to the earndows PATH variable.

You can get the stable version of G95 from here :

installer setup
mini installer setup

How to use G95

During installation, g95 is automatically added to your PATH variable if you select the option “RECOMMENDED”. This means thead put on you can simply open a brand brand new Command Prompt earndow and type “g95” to provide up the compiler. Find a couple of fundamental commands below to get you started.

Command Description
g95 –c hello.f90 Compiles hello.f90 to an object file named hello.o
g95 hello.f90 Compiles hello.f90 and links it to produce an executable a.away
g95 -c h1.f90 h2.f90 h3.f90 Compiles multiple source files. If all goes well, object files h1.o, h2.o and h3.o are developd
g95 -o hello h1.f90 h2.f90 h3.f90 Compiles multiple source files and links all of them with every other to an executable file named 'hello'

Command series options for G95:

-c Compile only, do not operate the linker.
-o Specify the name of the awayplace file, possibly an object file or the executable.

Multiple source and object files can be specified at once. Fortran files are indicated simply simply by names ending in ".f", ".F", ".for", ".FOR", ".f90", ".F90", ".f95", ".F95", ".f03" and ".F03". Multiple source files can be specified. Object files can be specified as well and will be linked to form an executable file.

Fortran – Basic Syntax

A Fortran program is made of a collection of program device’s like a main program, modules, and external subprograms or procedures.

Each program contains one main program and may or may not contain other program device’s. The syntax of the main program is as follows:

program program_name      
implicit none      
! type declaration statements      
! executable statements  
end program program_name

A Simple Program in Fortran

Let’s write a program thead put on adds 2 numbers and prints the result:

program addNumbers                                          
! This easy program adds 2 numbers     
   implicit none
! Type declarations
   real :: a, b, result 
! Executable statements 
   a = 12.0
   b = 15.0
   result = a + b
   print *, 'The complete is ', result                   
end program addNumbers        

When you compile and execute the above program, it produces the folloearng result:

The complete is 27.0000000    

Please note thead put on:

  • All Fortran programs start with the keyword program and end with the keyword end program, followed simply simply by the name of the program.

  • The implicit none statement permit’s the compiler to check thead put on all your variable types are declacrimson-coloucrimson properly. You must always use implicit none at the start of every program.

  • Comments in Fortran are started with the exclamation mark (!), as all charbehaveers after this particular (other than in a charbehaveer string) are ignocrimson-coloucrimson simply simply by the compiler.

  • The print * command displays data on the screen.

  • Indentation of code seriess is a great prbehaveice for keeping a program readable.

  • Fortran permit’s both uppercase and lowercase permitters. Fortran is case-insensit down downive, other than for string literals.

Basics

The fundamental charbehaveer set of Fortran contains:

  • the permitters A … Z and a … z
  • the digit’s 0 … 9
  • the belowscore (_) charbehaveer
  • the special charbehaveers = : + blank – * / ( ) [ ] , . $ ' ! " % & ; < > ?

Tokens are made of charbehaveers in the fundamental charbehaveer set. A token could be a keyword, an identifier, a constant, a string literal, or a symbol.

Program statements are made of tokens.

Identifier

An identifier is a name used to identify a variable, procedure, or any kind of kind of other user-degreatd item. A name in Fortran must follow the folloearng rules:

  • It cannot be durationyer than 31 charbehaveers.

  • It must be composed of alphanumeric charbehaveers (all the permitters of the alphabet, and the digit’s 0 to 9) and belowscores (_).

  • First charbehaveer of a name must be a permitter.

  • Names are case-insensit down downive

Keywords

Keywords are special words, reserved for the language. These reserved words cannot be used as identifiers or names.

The folloearng table, lists the Fortran keywords:

The non-I/O keywords
allocatable allocate bumign bumignment block data
call case charbehaveer common complex
contains continue cycle data deallocate
default do double precision else else if
elsewhere end block data end do end function end if
end interface end module end program end select end subrawayine
end type end where enconaspectr equivalence exit
external function go to if implicit
in inaway integer intent interface
intrinsic kind len logical module
namelist nullify only operator optional
away parameter pause pointer private
program public real recursive result
return save select case cease subrawayine
target then type type() use
Where While
The I/O related keywords
backspace close up endfile format inquire
open print read reearnd Write

Fortran – Data Types

Fortran provides five intrinsic data types, however, you can derive your own data types as well. The five intrinsic types are:

  • Integer type
  • Real type
  • Complex type
  • Logical type
  • Charbehaveer type

Integer Type

The integer types can hold only integer values. The folloearng example extrbehaves the hugest value thead put on can be held in a usual four simply simply byte integer:

program checcalifornia kingInt
implicit none
   integer :: hugeval
   print *, huge(hugeval)
end program checcalifornia kingInt

When you compile and execute the above program it produces the folloearng result:

2147483647

Note thead put on the huge() function gives the hugest number thead put on can be held simply simply by the specific integer data type. You can furthermore specify the number of simply simply bytes uperform the kind specifier. The folloearng example demonstrates this particular:

program checcalifornia kingInt
implicit none
   !2 simply simply byte integer
   integer(kind=2) :: shortval
   !four simply simply byte integer
   integer(kind=4) :: durationyval
   !eight simply simply byte integer
   integer(kind=8) :: verydurationyval
   !sixteen simply simply byte integer
   integer(kind=16) :: veryverydurationyval
   !default integer 
   integer :: defval
        
   print *, huge(shortval)
   print *, huge(durationyval)
   print *, huge(verydurationyval)
   print *, huge(veryverydurationyval)
   print *, huge(defval)
end program checcalifornia kingInt

When you compile and execute the above program, it produces the folloearng result:

32767
2147483647
9223372036854775807
170141183460469231731687303715884105727
2147483647

Real Type

It stores the floating point numbers, such as 2.0, 3.1415, -100.876, etc.

Traditionally presently there are 2 various real types, the default real type and double precision type.

However, Fortran 90/95 provides more manage over the precision of real and integer data types through thekindspecifier, which we will study in the chapter on Numbers.

The folloearng example shows the use of real data type:

program division   
implicit none  
   ! Degreat real variables   
   real :: p, q, realRes 
   ! Degreat integer variables  
   integer :: i, j, intRes  
   ! Assigning  values   
   p = 2.0 
   q = 3.0    
   i = 2 
   j = 3  
   ! floating point division
   realRes = p/q  
   intRes = i/j
   
   print *, realRes
   print *, intRes
end program division  

When you compile and execute the above program it produces the folloearng result:

0.666666687    
0

Complex Type

This is used for storing complex numbers. A complex number has 2 parts, the real part and the imaginary part. Two consecutive numeric storage device’s store these 2 parts.

For example, the complex number (3.0, -5.0) is equal to 3.0 – 5.0i

We will speak about presently there Complex types in more detail, in the Numbers chapter.

Logical Type

There are only 2 logical values: .true. and .false.

Charbehaveer Type

The charbehaveer type stores charbehaveers and strings. The duration of the string can be specified simply simply by len specifier. If no duration is specified, it is 1.

For example,

charbehaveer (len=40) :: name  
name = “Zara Ali”

The expression, name(1:4) would give the substring “Zara”.

Implicit Typing

Older versions of Fortran permited a feature calbrought implicit typing, i.e., you do not have to declare the variables before use. If a variable is not declacrimson-coloucrimson, then the preliminary permitter of it’s name will figure out presently there it’s type.

Variable names starting with i, j, k, l, m, or n, are conaspectcrimson-coloucrimson to be for integer variable and others are real variables. However, you must declare all the variables as it is great programming prbehaveice. For thead put on you start your program with the statement:

implicit none

This statement turns away from implicit typing.

Fortran – Variables

A variable is noslimg but a name given to a storage area thead put on our programs can manipulate. Each variable need to have a specific type, which figure out presently there’s the dimension and layaway of the variable's memory; the range of values thead put on can be stocrimson-coloucrimson wislim thead put on memory; and the set of operations thead put on can be applayd to the variable.

The name of a variable can be composed of permitters, digit’s, and the belowscore charbehaveer. A name in Fortran must follow the folloearng rules:

  • It cannot be durationyer than 31 charbehaveers.

  • It must be composed of alphanumeric charbehaveers (all the permitters of the alphabet, and the digit’s 0 to 9) and belowscores (_).

  • First charbehaveer of a name must be a permitter.

  • Names are case-insensit down downive.

Based on the fundamental types exfundamentaled in previous chapter, folloearng are the variable types:

Type Description
Integer It can hold only integer values.
Real It stores the floating point numbers.
Complex It is used for storing complex numbers.
Logical It stores logical Boolean values.
Charbehaveer It stores charbehaveers or strings.

Variable Declaration

Variables are declacrimson-coloucrimson at the startning of a program (or subprogram) in a type declaration statement.

Syntax for variable declaration is as follows:

type-specifier :: variable_name

For example,

integer :: complete  	
real :: average 
complex :: cx  
logical :: done 
charbehaveer(len=80) :: message ! a string of 80 charbehaveers

Later you can bumign values to these variables, like,

complete = 20000  
average = 1666.67   
done = .true.   
message = “A huge Hello from Tutorials Point” 
cx = (3.0, 5.0) ! cx = 3.0 + 5.0i

You can furthermore use the intrinsic function cmplx, to bumign values to a complex variable:

cx = cmplx (1.0/2.0, -7.0) ! cx = 0.5 – 7.0i 
cx = cmplx (x, y) ! cx = x + yi

Example

The folloearng example demonstrates variable declaration, bumignment and display on screen:

program variableTesting
implicit none

   ! declaring variables
   integer :: complete      
   real :: average 
   complex :: cx  
   logical :: done 
   charbehaveer(len=80) :: message ! a string of 80 charbehaveers
   
   !bumigning values
   complete = 20000  
   average = 1666.67   
   done = .true.   
   message = "A huge Hello from Tutorials Point" 
   cx = (3.0, 5.0) ! cx = 3.0 + 5.0i

   Print *, complete
   Print *, average
   Print *, cx
   Print *, done
   Print *, message
end program variableTesting

When the above code is compibrought and executed, it produces the folloearng result:

20000
1666.67004    
(3.00000000, 5.00000000 )
T
A huge Hello from Tutorials Point         

Fortran – Constants

The constants refer to the fixed values thead put on the program cannot alter during it’s execution. These fixed values are furthermore calbrought literals.

Constants can be of any kind of kind of of the fundamental data types like an integer constant, a floating constant, a charbehaveer constant, a complex constant, or a string literal. There are only 2 logical constants : .true. and .false.

The constants are treated simply like regular variables, other than thead put on their particular values cannot be modified after their particular definition.

Named Constants and Literals

There are 2 types of constants:

  • Literal constants
  • Named constants

A literal constant have a value, but no name.

For example, folloearng are the literal constants:

Type Example
Integer constants 0 1 -1 300 123456789
Real constants 0.0 1.0 -1.0 123.456 7.1E+10 -52.715E-30
Complex constants (0.0, 0.0) (-123.456E+30, 987.654E-29)
Logical constants .true. .false.
Charbehaveer constants

"PQR" "a" "123'abc$%#@!"

" a quote "" "

'PQR' 'a' '123"abc$%#@!'

' an apostrophe '' '

A named constant has a value as well as a name.

Named constants need to be declacrimson-coloucrimson at the startning of a program or procedure, simply like a variable type declaration, indicating it’s name and type. Named constants are declacrimson-coloucrimson with the parameter attribute. For example,

real, parameter :: pi = 3.1415927

Example

The folloearng program calculates the displacement because of to vertical motion below gravity.

program gravitationalDisp
! this particular program calculates vertical motion below gravity 
implicit none  
   ! gravitational acceleration
   real, parameter :: g = 9.81   
   ! variable declaration
   real :: s ! displacement   
   real :: t ! time  
   real :: u ! preliminary speed  
   ! bumigning values 
   t = 5.0   
   u = 50  
   ! displacement   
   s = u * t - g * (t**2) / 2  
   ! awayplace 
   print *, "Time = ", t
   print *, 'Displacement = ',s  
end program gravitationalDisp

When the above code is compibrought and executed, it produces the folloearng result:

Time = 5.00000000    
Displacement = 127.374992    

Fortran – Operators

An operator is a symbol thead put on tells the compiler to perform specific maall of thematical or logical manipulations. Fortran provides the folloearng types of operators:

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators

Let us look at all these types of operators one simply simply by one.

Arithmetic Operators

Folloearng table shows all the arithmetic operators supsloted simply simply by Fortran. Assume variable A holds 5 and variable B holds 3 then:

Show Examples

Operator Description Example
+ Addition Operator, adds 2 operands. A + B will give 8
Subtrbehaveion Operator, subtrbehaves second operand from the preliminary. A – B will give 2
* Multiplication Operator, multiplays both operands. A * B will give 15
/ Division Operator, divides numerator simply simply by de-numerator. A / B will give 1
** Exponentiation Operator, raises one operand to the power of the other. A ** B will give 125

Relational Operators

Folloearng table shows all the relational operators supsloted simply simply by Fortran. Assume variable A holds 10 and variable B holds 20, then:

Show Examples

</=

Operator Equivalent Description Example
== .eq. Checks if the values of 2 operands are equal or not, if yes then condition becomes true. (A == B) is not true.
/= .ne. Checks if the values of 2 operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
> .gt. Checks if the value of left operand is greater than the value of appropriate operand, if yes then condition becomes true. (A > B) is not true.
< .lt. Checks if the value of left operand is less than the value of appropriate operand, if yes then condition becomes true. (A < B) is true.
>= .ge. Checks if the value of left operand is greater than or equal to the value of appropriate operand, if yes then condition becomes true. (A >= B) is not true.
<= .le. Checks if the value of left operand is less than or equal to the value of appropriate operand, if yes then condition becomes true. (A <= b)="" is="" true.

Operators Precedence in Fortran

Operator precedence figure out presently there’s the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is bumigned 13, not 20 because operator * has higher precedence than +, so it preliminary gets multiplayd with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom level. Wislim an expression, higher precedence operators will be evaluated preliminary.

Show Examples

Category Operator Associativity
Logical NOT and negative sign .not. (-) Left to appropriate
Exponentiation ** Left to appropriate
Multiplicative * / Left to appropriate
Additive + – Left to appropriate
Relational < >= Left to appropriate
Equality == != Left to appropriate
Logical AND .and. Left to appropriate
Logical OR .or. Left to appropriate
Assignment = Right to left

Fortran – Decisions

Decision macalifornia king structures require thead put on the programmer specify one or more conditions to be evaluated or checked simply simply by the program, adurationy with a statement or statements to be executed, if the condition is figure out presently thecrimson to be true, and optionally, other statements to be executed if the condition is figure out presently thecrimson to be false.

Folloearng is the general form of a typical decision macalifornia king structure found in many kind of kind of of the programming languages:

Decision Macalifornia king

Fortran provides the folloearng types of decision macalifornia king constructs.

Statement Description
If… then construct An if… then… end if statement consists of a logical expression followed simply simply by one or more statements.
If… then…else construct An if… then statement can be followed simply simply by an optional else statement, which executes when the logical expression is false.
nested if construct You can use one if or else if statement inaspect an additional if or else if statement(s).
select case construct select case statement permit’s a variable to be checked for equality against a list of values.
nested select case construct You can use one select case statement inaspect an additional select case statement(s).

Fortran – if…else if…else Statement

An if statement construct can have one or more optional else-if constructs. When the if condition fails, the immediately followed else-if is executed. When the else-if furthermore fails, it’s successor else-if statement (if any kind of kind of) is executed, and so on.

The optional else is placed at the end and it is executed when none of the above conditions hold true.

  • All else statements (else-if and else) are optional.
  • else-if can be used one or more times
  • else must always be placed at the end of construct and need to appear only once.

Syntax:

The syntax of an if…else if…else statement is:

[name:] 
if (logical expression 1) then 
   ! block 1   
else if (logical expression 2) then       
   ! block 2   
else if (logical expression 3) then       
   ! block 3  
else       
   ! block 4   
end if [name]

Example

program ifElseIfElseProg
implicit none
   ! local variable declaration
   integer :: a = 100
 
   ! check the logical condition uperform if statement
   if( a == 10 ) then
  
   ! if condition is true then print the folloearng 
   print*, "Value of a is 10" 
   
   else if( a == 20 ) then
  
   ! if else if condition is true 
   print*, "Value of a is 20" 
  
   else if( a == 30 ) then
   
   ! if else if condition is true  
   print*, "Value of a is 30" 
  
   else
   
   ! if none of the conditions is true 
   print*, "None of the values is match up uping" 
   end if
   
   print*, "exbehave value of a is ", a
 
end program ifElseIfElseProg

When the above code is compibrought and executed, it produces the folloearng result:

None of the values is match up uping
exbehave value of a is 100

Fortran – Loops

There may be a sit down downuation, when you need to execute a block of code various number of times. In general, statements are executed sequentially : The preliminary statement in a function is executed preliminary, followed simply simply by the second, and so on.

Programming languages provide various manage structures thead put on permit for more complicated execution paths.

A loop statement permit’s us to execute a statement or group of statements multiple times and folloearng is the general form of a loop statement in many kind of kind of of the programming languages:

If Conditional

Fortran provides the folloearng types of loop constructs to handle looping requirements. Click the folloearng links to check their particular detail.

Loop Type Description
do loop This construct enables a statement, or a series of statements, to be carried away iteratively, while a given condition is true.
do while loop Repeats a statement or group of statements while a given condition is true. It checks the condition before executing the loop body.
nested loops You can use one or more loop construct inaspect any kind of kind of other loop construct.

Loop Control Statements

Loop manage statements alter execution from it’s normal sequence. When execution departs a scope, all automatic objects thead put on were developd in thead put on scope are destroyed.

Fortran supslots the folloearng manage statements. Click the folloearng links to check their particular detail.

Control Statement Description
exit If the exit statement is executed, the loop is exited, and the execution of the program continues at the preliminary executable statement after the end do statement.
cycle If a cycle statement is executed, the program continues at the start of the next iteration.
cease If you wish execution of your program to cease, you can insert a cease statement

Fortran – Numbers

Numbers in Fortran are represented simply simply by 3 intrinsic data types:

  • Integer type
  • Real type
  • Complex type

Integer Type

The integer types can hold only integer values. The folloearng example extrbehaves the hugest value thead put on could be hold in a usual four simply simply byte integer:

program checcalifornia kingInt
implicit none
   integer :: hugeval
   print *, huge(hugeval)
end program checcalifornia kingInt

When you compile and execute the above program it produces the folloearng result:

2147483647

Please note thead put on the huge() function gives the hugest number thead put on can be held simply simply by the specific integer data type. You can furthermore specify the number of simply simply bytes uperform the kind specifier. The folloearng example demonstrates this particular:

program checcalifornia kingInt
implicit none
   !2 simply simply byte integer
   integer(kind=2) :: shortval
   !four simply simply byte integer
   integer(kind=4) :: durationyval
   !eight simply simply byte integer
   integer(kind=8) :: verydurationyval
   !sixteen simply simply byte integer
   integer(kind=16) :: veryverydurationyval
   !default integer 
   integer :: defval
        
   print *, huge(shortval)
   print *, huge(durationyval)
   print *, huge(verydurationyval)
   print *, huge(veryverydurationyval)
   print *, huge(defval)
end program checcalifornia kingInt

When you compile and execute the above program it produces the folloearng result:

32767
2147483647
9223372036854775807
170141183460469231731687303715884105727
2147483647

Real Type

It stores the floating point numbers, such as 2.0, 3.1415, -100.876, etc.

Traditionally presently there were 2 various real types : the default real type and double precision type.

However, Fortran 90/95 provides more manage over the precision of real and integer data types through the kind specifier, which we will study shortly.

The folloearng example shows the use of real data type:

program division   
implicit none  
   ! Degreat real variables   
   real :: p, q, realRes 
   ! Degreat integer variables  
   integer :: i, j, intRes  
   ! Assigning  values   
   p = 2.0 
   q = 3.0    
   i = 2 
   j = 3  
   ! floating point division
   realRes = p/q  
   intRes = i/j
   
   print *, realRes
   print *, intRes
end program division  

When you compile and execute the above program it produces the folloearng result:

0.666666687    
0

Complex Type

This is used for storing complex numbers. A complex number has 2 parts : the real part and the imaginary part. Two consecutive numeric storage device’s store these 2 parts.

For example, the complex number (3.0, -5.0) is equal to 3.0 – 5.0i

The generic function cmplx() develops a complex number. It produces a result who’s real and imaginary parts are performle precision, irrespective of the kind of the inplace arguments.

program developComplex
implicit none
   integer :: i = 10
   real :: x = 5.17
   print *, cmplx(i, x)
end program developComplex

When you compile and execute the above program it produces the folloearng result:

(10.0000000, 5.17000008)

The folloearng program demonstrates complex number arithmetic:

program ComplexArithmatic
implicit none
   complex, parameter :: i = (0, 1)   ! sqrt(-1)   
   complex :: x, y, z 
   x = (7, 8); 
   y = (5, -7)   
   write(*,*) i * x * y
   z = x + y
   print *, "z = x + y = ", z
   z = x - y
   print *, "z = x - y = ", z 
   z = x * y
   print *, "z = x * y = ", z 
   z = x / y
   print *, "z = x / y = ", z 
end program ComplexArithmatic

When you compile and execute the above program it produces the folloearng result:

(9.00000000, 91.0000000)
z = x + y = (12.0000000, 1.00000000)
z = x - y = (2.00000000, 15.0000000)
z = x * y = (91.0000000, -9.00000000)
z = x / y = (-0.283783793, 1.20270276)

The Range, Precision and Size of Numbers

The range on integer numbers, the precision and the dimension of floating point numbers depends on the number of bit’s allocated to the specific data type.

The folloearng table displays the number of bit’s and range for integers:

Number of bit’s Maximum value Reason
64 9,223,372,036,854,774,807 (2**63)–1
32 2,147,483,647 (2**31)–1

The folloearng table displays the number of bit’s, smallest and hugest value, and the precision for real numbers.

Number of bit’s Largest value Smallest value Precision
64 0.8E+308 0.5E–308 15–18
32 1.7E+38 0.3E–38 6-9

The folloearng examples demonstrate this particular:

program rangePrecision
implicit none
real:: x, y, z
x = 1.5e+40
y = 3.73e+40
z = x * y 
print *, z
end program rangePrecision

When you compile and execute the above program it produces the folloearng result:

x = 1.5e+40
    1
Error : Real cos it's kind at (1)
main.f95:5.12:

y = 3.73e+40
    1
Error : Real constant overflows it's kind at (1)

Now permit us use a smaller number:

program rangePrecision
implicit none
real:: x, y, z
x = 1.5e+20
y = 3.73e+20
z = x * y 
print *, z
z = x/y
print *, z
end program rangePrecision

When you compile and execute the above program it produces the folloearng result:

Infinity
0.402144760   

Now permit’s watch belowflow:

program rangePrecision
implicit none
real:: x, y, z
x = 1.5e-30
y = 3.73e-60
z = x * y 
print *, z
z = x/y
print *, z
end program rangePrecision

When you compile and execute the above program it produces the folloearng result:

y = 3.73e-60
    1
Warning : Real constant belowflows it's kind at (1)

Executing the program....
$demo 

0.00000000E+00
Infinity

The Kind Specifier

In scientific programming, one usually needs to belowstand the range and precision of data of the hardware platform on which the work is being done.

The intrinsic function kind() permit’s you to query the details of the hardware’s data representations before operatening a program.

program kindCheck
implicit none
   integer :: i 
   real :: r 
   complex :: cp 
   print *,' Integer ', kind(i) 
   print *,' Real ', kind(r) 
   print *,' Complex ', kind(cp) 
end program kindCheck

When you compile and execute the above program it produces the folloearng result:

Integer 4
Real 4
Complex 4

You can furthermore check the kind of all data types:

program checkKind
implicit none
   integer :: i 
   real :: r 
   charbehaveer*1 :: c 
   logical :: lg 
   complex :: cp 
   print *,' Integer ', kind(i) 
   print *,' Real ', kind(r) 
   print *,' Complex ', kind(cp)
   print *,' Charbehaveer ', kind(c) 
   print *,' Logical ', kind(lg)
end program checkKind

When you compile and execute the above program it produces the folloearng result:

Integer 4
Real 4
Complex 4
Charbehaveer 1
Logical 4

Fortran – Charbehaveers

The Fortran language can treat charbehaveers as performle charbehaveer or contiguous strings.

Charbehaveers could be any kind of kind of symbol conaspectrn from the fundamental charbehaveer set, i.e., from the permitters, the decimal digit’s, the belowscore, and 21 special charbehaveers.

A charbehaveer constant is a fixed valued charbehaveer string.

The intrinsic data type charbehaveer stores charbehaveers and strings. The duration of the string can be specified simply simply by len specifier. If no duration is specified, it is 1. You can refer individual charbehaveers wislim a string referring simply simply by posit down downion; the left many kind of kind of charbehaveer is at posit down downion 1.

Charbehaveer Declaration

Declaring a charbehaveer type data is same as other variables:

type-specifier :: variable_name

For example,

charbehaveer :: reply, macalifornia king love

you can bumign a value like,

reply = ‘N’ 
macalifornia king love = ‘F’

The folloearng example demonstrates declaration and use of charbehaveer data type:

program hello
implicit none
   charbehaveer(len=15) :: surname, preliminaryname 
   charbehaveer(len=6) :: title 
   charbehaveer(len=25)::greetings
   title = 'Mr. ' 
   preliminaryname = 'Rowan ' 
   surname = 'Atkinson'
   greetings = 'A huge hello from Mr. Bean'
   print *, 'Here is ', title, preliminaryname, surname
   print *, greetings
end program hello

When you compile and execute the above program it produces the folloearng result:

Here is Mr. Rowan Atkinson       
A huge hello from Mr. Bean

Concatenation of Charbehaveers

The concatenation operator //, concatenates charbehaveers.

The folloearng example demonstrates this particular:

program hello
implicit none
   charbehaveer(len=15) :: surname, preliminaryname 
   charbehaveer(len=6) :: title 
   charbehaveer(len=40):: name
   charbehaveer(len=25)::greetings
   title = 'Mr. ' 
   preliminaryname = 'Rowan ' 
   surname = 'Atkinson'
   name = title//preliminaryname//surname
   greetings = 'A huge hello from Mr. Bean'
   print *, 'Here is ', name
   print *, greetings
end program hello

When you compile and execute the above program it produces the folloearng result:

Here is Mr.Rowan Atkinson       
A huge hello from Mr.Bean

Some Charbehaveer Functions

The folloearng table shows a couple of commonly used charbehaveer functions adurationy with the description:

Function Description
len(string) It returns the duration of a charbehaveer string
index(string,sustring) It finds the location of a substring in an additional string, returns 0 if not found.
achar(int) It converts an integer into a charbehaveer
iachar(c) It converts a charbehaveer into an integer
trim(string) It returns the string with the trailing blanks removed.
scan(string, chars) It oceanrches the "string" from left to appropriate (unless back=.true.) for the preliminary occurrence of any kind of kind of charbehaveer contained in "chars". It returns an integer giving the posit down downion of thead put on charbehaveer, or zero if none of the charbehaveers in "chars" have been found.
verify(string, chars) It scans the "string" from left to appropriate (unless back=.true.) for the preliminary occurrence of any kind of kind of charbehaveer not contained in "chars". It returns an integer giving the posit down downion of thead put on charbehaveer, or zero if only the charbehaveers in "chars" have been found
adsimplyl(string) It left simplyifies charbehaveers contained in the "string"
adsimplyr(string) It appropriate simplyifies charbehaveers contained in the "string"
len_trim(string) It returns an integer equal to the duration of "string" (len(string)) minus the number of trailing blanks
repeat(string,nduplicate) It returns a string with duration equal to "nduplicate" times the duration of "string", and containing "nduplicate" concatenated copies of "string"

Example 1

This example shows the use of the index function:

program checcalifornia kingChars
implicit none
   charbehaveer (80) :: text 
   integer :: i 
   text = 'The intrinsic data type charbehaveer stores charbehaveers and   strings.'
   i=index(text,'charbehaveer') 
   if (i /= 0) then
   print *, ' The word charbehaveer found at posit down downion ',i 
   print *, ' in text: ', text 
   end if
end program checcalifornia kingChars

When you compile and execute the above program it produces the folloearng result:

The word charbehaveer found at posit down downion 25
in text : The intrinsic data type charbehaveer stores charbehaveers and strings.  

Example 2

This example demonstrates the use of the trim function:

program hello
implicit none
   charbehaveer(len=15) :: surname, preliminaryname 
   charbehaveer(len=6) :: title 
   charbehaveer(len=25)::greetings
   title = 'Mr.' 
   preliminaryname = 'Rowan' 
   surname = 'Atkinson'
   print *, 'Here is', title, preliminaryname, surname
   print *, 'Here is', trim(title),' ',trim(preliminaryname),' ', trim(surname)
 end program hello

When you compile and execute the above program it produces the folloearng result:

Here is Mr. Rowan Atkinson       
Here is Mr. Rowan Atkinson

Example 3

This example demonstrates the use of achar function

program checcalifornia kingChars
implicit none
   charbehaveer:: ch
   integer:: i
   do i=65, 90
   ch = achar(i)
   print*, i, ' ', ch
   end do
end program checcalifornia kingChars

When you compile and execute the above program it produces the folloearng result:

65  A
66  B
67  C
68  D
69  E
70  F
71  G
72  H
73  I
74  J
75  K
76  L
77  M
78  N
79  O
80  P
81  Q
82  R
83  S
84  T
85  U
86  V
87  W
88  X
89  Y
90  Z

Checcalifornia king Lexical Order of Charbehaveers

The folloearng functions figure out presently there the lexical sequence of charbehaveers:

Function Description
lle(char, char) Compares whether the preliminary charbehaveer is lexically less than or equal to the second
lge(char, char) Compares whether the preliminary charbehaveer is lexically greater than or equal to the second
lgt(char, char) Compares whether the preliminary charbehaveer is lexically greater than the second
llt(char, char) Compares whether the preliminary charbehaveer is lexically less than the second

Example 4

The folloearng function demonstrates the use:

program checcalifornia kingChars
implicit none
   charbehaveer:: a, b, c
   a = 'A'
   b = 'a'
   c = 'B'
   
   if(lgt(a,b)) then
   print *, 'A is lexically greater than a'
   else
   print *, 'a is lexically greater than A'
   end if
   if(lgt(a,c)) then
   print *, 'A is lexically greater than B'
   else
   print *, 'B is lexically greater than A'
   end if  
   if(llt(a,b)) then
   print *, 'A is lexically less than a'
   end if
   if(llt(a,c)) then
   print *, 'A is lexically less than B'
   end if
end program checcalifornia kingChars

When you compile and execute the above program it produces the folloearng result:

a is lexically greater than A
B is lexically greater than A
A is lexically less than a
A is lexically less than B

Fortran – Strings

The Fortran language can treat charbehaveers as performle charbehaveer or contiguous strings.

A charbehaveer string may be only one charbehaveer in duration, or it could furthermore be of zero duration. In Fortran, charbehaveer constants are given between a pair of double or performle quotes.

The intrinsic data type charbehaveer stores charbehaveers and strings. The duration of the string can be specified simply simply by len specifier. If no duration is specified, it is 1. You can refer individual charbehaveers wislim a string referring simply simply by posit down downion; the left many kind of kind of charbehaveer is at posit down downion 1.

String Declaration

Declaring a string is same as other variables:

type-specifier :: variable_name

For example,

Charbehaveer(len=20) :: preliminaryname, surname

you can bumign a value like,

charbehaveer (len=40) :: name  
name = “Zara Ali”

The folloearng example demonstrates declaration and use of charbehaveer data type:

program hello
implicit none
   charbehaveer(len=15) :: surname, preliminaryname 
   charbehaveer(len=6) :: title 
   charbehaveer(len=25)::greetings
   title = 'Mr.' 
   preliminaryname = 'Rowan' 
   surname = 'Atkinson'
   greetings = 'A huge hello from Mr. Beans'
   print *, 'Here is', title, preliminaryname, surname
   print *, greetings
end program hello

When you compile and execute the above program it produces the folloearng result:

Here is Mr. Rowan Atkinson       
 A huge hello from Mr. Bean

String Concatenation

The concatenation operator //, concatenates strings.

The folloearng example demonstrates this particular:

program hello
implicit none
   charbehaveer(len=15) :: surname, preliminaryname 
   charbehaveer(len=6) :: title 
   charbehaveer(len=40):: name
   charbehaveer(len=25)::greetings
   title = 'Mr.' 
   preliminaryname = 'Rowan' 
   surname = 'Atkinson'
   name = title//preliminaryname//surname
   greetings = 'A huge hello from Mr. Beans'
   print *, 'Here is', name
   print *, greetings
end program hello

When you compile and execute the above program it produces the folloearng result:

Here is Mr. Rowan Atkinson       
 A huge hello from Mr. Bean

Extrbehaveing Substrings

In Fortran, you can extrbehave a substring from a string simply simply by indexing the string, giving the start and the end index of the substring in a pair of brackets. This is calbrought extent specifier.

The folloearng example shows how to extrbehave the substring ‘world’ from the string ‘hello world’:

program subString
   charbehaveer(len=11)::hello
   hello = "Hello World"
   print*, hello(7:11)
end program subString 

When you compile and execute the above program it produces the folloearng result:

World

Example

The folloearng example uses the date_and_time function to give the date and time string. We use extent specifiers to extrbehave the yr, date, month, hr, minutes and second information separately.

program  datetime
   implicit none

   charbehaveer(len = 8) :: dateinfo ! ccyymmdd
   charbehaveer(len = 4) :: yr, month*2, day*2

   charbehaveer(len = 10) :: timeinfo ! hhmmss.sss
   charbehaveer(len = 2)  :: hr, minute, second*6

   call  date_and_time(dateinfo, timeinfo)

!  permit’s break dateinfo into yr, month and day.
!  dateinfo has a form of ccyymmdd, where cc = century, yy = yr
!  mm = month and dd = day

   yr  = dateinfo(1:4)
   month = dateinfo(5:6)
   day   = dateinfo(7:8)

   print*, 'Date String:', dateinfo
   print*, 'Year:', yr
   print *,'Month:', month
   print *,'Day:', day

!  permit’s break timeinfo into hr, minute and second.
!  timeinfo has a form of hhmmss.sss, where h = hr, m = minute
!  and s = second

   hr   = timeinfo(1:2)
   minute = timeinfo(3:4)
   second = timeinfo(5:10)

   print*, 'Time String:', timeinfo
   print*, 'Hour:', hr
   print*, 'Minute:', minute
   print*, 'Second:', second   
end program  datetime

When you compile and execute the above program, it gives the detaibrought date and time information:

Date String: 20140803
   Year: 2014
   Month: 08
   Day: 03
   Time String: 075835.466
   Hour: 07
   Minute: 58
	Second: 35.466

Trimming Strings

The trim function conaspectrs a string, and returns the inplace string after removing all trailing blanks.

Example

program trimString
implicit none
   charbehaveer (len=*), parameter :: fname="Susanne", sname="Rizwan"
   charbehaveer (len=20) :: completename 
   completename=fname//" "//sname !concatenating the strings
   print*,completename,", the wonderful dancer from the eastern!"
   print*,trim(completename),", the wonderful dancer from the eastern!"
end program trimString

When you compile and execute the above program it produces the folloearng result:

Susanne Rizwan, the wonderful dancer from the eastern!
Susanne Rizwan, the wonderful dancer from the eastern!

Left and Right Adsimplyment of Strings

The function adsimplyl conaspectrs a string and returns it simply simply by removing the leading blanks and appending all of them as trailing blanks.

The function adsimplyr conaspectrs a string and returns it simply simply by removing the trailing blanks and appending all of them as leading blanks.

Example

program hello
implicit none
   charbehaveer(len=15) :: surname, preliminaryname 
   charbehaveer(len=6) :: title 
   charbehaveer(len=40):: name
   charbehaveer(len=25):: greetings
   title = 'Mr. ' 
   preliminaryname = 'Rowan' 
   surname = 'Atkinson'
   greetings = 'A huge hello from Mr. Beans'
   name = adsimplyl(title)//adsimplyl(preliminaryname)//adsimplyl(surname)
   print *, 'Here is', name
   print *, greetings
   
   name = adsimplyr(title)//adsimplyr(preliminaryname)//adsimplyr(surname)
   print *, 'Here is', name
   print *, greetings
   
   name = trim(title)//trim(preliminaryname)//trim(surname)
   print *, 'Here is', name
   print *, greetings
end program hello

When you compile and execute the above program it produces the folloearng result:

Here is Mr. Rowan  Atkinson           
A huge hello from Mr. Bean
Here is Mr. Rowan Atkinson    
A huge hello from Mr. Bean
Here is Mr.RowanAtkinson                        
A huge hello from Mr. Bean

Searching for a Substring in a String

The index function conaspectrs 2 strings and checks if the second string is a substring of the preliminary string. If the second argument is a substring of the preliminary argument, then it returns an integer which is the starting index of the second string in the preliminary string, else it returns zero.

Example

program hello
implicit none
   charbehaveer(len=30) :: myString
   charbehaveer(len=10) :: checkString
   myString = 'This is a check'
   checkString = 'check'
   
   if(index(myString, checkString) == 0)then
   print *, 'check is not found'
   else
   print *, 'check is found at index: ', index(myString, checkString)
   end if
   
end program hello

When you compile and execute the above program it produces the folloearng result:

check is found at index: 11

Fortran – Arrays

Arrays can store a fixed-dimension sequential collection of elements of the same type. An array is used to store a collection of data, but it is usually more helpful to belayve of an array as a collection of variables of the same type.

All arrays consist of contiguous memory locations. The lowest adgown corresponds to the preliminary element and the highest adgown to the final element.

Numbers(1) Numbers(2) Numbers(3) Numbers(4)

Arrays can be one- dimensional (like vectors), 2-dimensional (like matrices) and Fortran permit’s you to develop up to 7-dimensional arrays.

Declaring Arrays

Arrays are declacrimson-coloucrimson with the dimension attribute.

For example, to declare a one-dimensional array named number, of real numbers containing 5 elements, you write,

real, dimension(5) :: numbers

The individual elements of arrays are referenced simply simply by specifying their particular subscripts. The preliminary element of an array has a subscript of one. The array numbers contains five real variables –numbers(1), numbers(2), numbers(3), numbers(4), and numbers(5).

To develop a 5 x 5 2-dimensional array of integers named matrix, you write:

integer, dimension (5,5) :: matrix  

You can furthermore declare an array with a couple of explicit lower bound, for example:

real, dimension(2:6) :: numbers
integer, dimension (-3:2,0:4) :: matrix  

Assigning Values

You can possibly bumign values to individual members, like,

numbers(1) = 2.0

or, you can use a loop,

do i=1,5
   numbers(i) = i * 2.0
end do

One dimensional array elements can be directly bumigned values uperform a short hand symbol, calbrought array constructor, like,

numbers = (/1.5, 3.2,4.5,0.9,7.2 /)

please note thead put on presently there are no spaces permited between the brackets ‘( ‘and the back slash ‘/’

Example

The folloearng example demonstrates the concepts speak about presently thereed above.

program arrayProg
   real :: numbers(5) !one dimensional integer array
   integer :: matrix(3,3), i , j !2 dimensional real array
   
   !bumigning a couple of values to the array numbers
   do i=1,5
   numbers(i) = i * 2.0
   end do
   !display the values
   do i = 1, 5
   Print *, numbers(i)
   end do
   !bumigning a couple of values to the array matrix
   do i=1,3
   do j = 1, 3
   matrix(i, j) = i+j
   end do
   end do
   !display the values
   do i=1,3
   do j = 1, 3
   Print *, matrix(i,j)
   end do
   end do
   !short hand bumignment
   numbers = (/1.5, 3.2,4.5,0.9,7.2 /)
   !display the values
   do i = 1, 5
   Print *, numbers(i)
   end do
end program arrayProg

When the above code is compibrought and executed, it produces the folloearng result:

 2.00000000    
 4.00000000    
 6.00000000    
 8.00000000    
 10.0000000    
         2
         3
         4
         3
         4
         5
         4
         5
         6
 1.50000000    
 3.20000005    
 4.50000000    
0.899999976    
 7.19999981    

Some Array Related Terms

The folloearng table gives a couple of array related terms:

Term Meaning
Rank It is the number of dimensions an array has. For example, for the array named matrix, rank is 2, and for the array named numbers, rank is 1.
Extent It is the number of elements adurationy a dimension. For example, the array numbers has extent 5 and the array named matrix has extent 3 in both dimensions.
Shape The shape of an array is a one-dimensional integer array, containing the number of elements (the extent) in every dimension. For example, for the array matrix, shape is (3, 3) and the array numbers it is (5).
Size It is the number of elements an array contains. For the array matrix, it is 9, and for the array numbers, it is 5.

Pbuming Arrays to Procedures

You can pbum an array to a procedure as an argument. The folloearng example demonstrates the concept:

program arrayToProcedure      
implicit none      
   integer, dimension (5) :: myArray  
   integer :: i
   call fillArray (myArray)      
   call printArray(myArray)
end program arrayToProcedure

subrawayine fillArray (a)      
implicit none      
   integer, dimension (5), intent (away) :: a      
   ! local variables     
   integer :: i     
   do i = 1, 5         
   a(i) = i      
   end do  
end subrawayine fillArray 

subrawayine printArray(a)
   integer, dimension (5) :: a  
   integer::i
   do i = 1, 5
   Print *, a(i)
   end do
end subrawayine printArray

When the above code is compibrought and executed, it produces the folloearng result:

1
2
3
4
5

In the above example, the subrawayine fillArray and printArray can only be calbrought with arrays with dimension 5. However, to write subrawayines thead put on can be used for arrays of any kind of kind of dimension, you can rewrite it uperform the folloearng technique:

program arrayToProcedure      
implicit  none      
   integer, dimension (10) :: myArray  
   integer :: i
   
   interface 
   subrawayine fillArray (a)
   integer, dimension(:), intent (away) :: a 
   integer :: i         
   end subrawayine fillArray      
       
   subrawayine printArray (a)
   integer, dimension(:) :: a 
   integer :: i         
   end subrawayine printArray   
   end interface 
   call fillArray (myArray)      
   call printArray(myArray)
end program arrayToProcedure

subrawayine fillArray (a)      
implicit none      
   integer,dimension (:), intent (away) :: a      
   ! local variables     
   integer :: i, arraySize  
   arraySize = dimension(a)
   do i = 1, arraySize         
   a(i) = i      
   end do  
end subrawayine fillArray 

subrawayine printArray(a)
implicit none
   integer,dimension (:) :: a  
   integer::i, arraySize
   arraySize = dimension(a)
   do i = 1, arraySize
   Print *, a(i)
   end do
end subrawayine printArray

Please note thead put on the program is uperform the dimension function to get the dimension of the array.

When the above code is compibrought and executed, it produces the folloearng result:

1
2
3
4
5
6
7
8
9
10

Array Sections

So far we have refercrimson-coloucrimson to the whole array, Fortran provides an easy way to refer various elements, or a section of an array, uperform a performle statement.

To access an array section, you need to provide the lower and the upper bound of the section, as well as a stride (increment), for all the dimensions. This notation is calbrought a subscript trippermit:

array ([lower]:[upper][:stride], ...)

When no lower and upper bounds are mentioned, it defaults to the extents you declacrimson-coloucrimson, and stride value defaults to 1.

The folloearng example demonstrates the concept:

program arraySubsection
   real, dimension(10) :: a, b
   integer:: i, adimension, bdimension
   a(1:7) = 5.0 ! a(1) to a(7) bumigned 5.0
   a(8:) = 0.0  ! rest are 0.0 
   b(2:10:2) = 3.9
   b(1:9:2) = 2.5
   
   !display
   adimension = dimension(a)
   bdimension = dimension(b)
   do i = 1, adimension
   Print *, a(i)
   end do
   do i = 1, bdimension
   Print *, b(i)
   end do
end program arraySubsection

When the above code is compibrought and executed, it produces the folloearng result:

5.00000000    
5.00000000    
5.00000000    
5.00000000    
5.00000000    
5.00000000    
5.00000000    
0.00000000E+00
0.00000000E+00
0.00000000E+00
2.50000000    
3.90000010    
2.50000000    
3.90000010    
2.50000000    
3.90000010    
2.50000000    
3.90000010    
2.50000000    
3.90000010 

Array Intrinsic Functions

Fortran 90/95 provides various intrinsic procedures. They can be divided into 7 categories.

Fortran – Dynamic Arrays

A dynamic array is an array, the dimension of which is not belowstandn at compile time, but will be belowstandn at execution time.

Dynamic arrays are declacrimson-coloucrimson with the attribute allocatable.

For example,

real, dimension (:,:), allocatable :: darray    

The rank of the array, i.e., the dimensions has to be mentioned however, to allocate memory to such an array, you use the allocate function.

allocate ( darray(s1,s2) )      

After the array is used, in the program, the memory developd need to be freed uperform the deallocate function

deallocate (darray)  

Example

The folloearng example demonstrates the concepts speak about presently thereed above.

program dynamic_array 
implicit none 
   !rank is 2, but dimension not belowstandn   
   real, dimension (:,:), allocatable :: darray    
   integer :: s1, s2     
   integer :: i, j     
   print*, "Enter the dimension of the array:"     
   read*, s1, s2      
   ! allocate memory      
   allocate ( darray(s1,s2) )      
   do i = 1, s1           
   do j = 1, s2                
   darray(i,j) = i*j               
   print*, "darray(",i,",",j,") = ", darray(i,j)           
   end do      
   end do      
   deallocate (darray)  
end program dynamic_array

When the above code is compibrought and executed, it produces the folloearng result:

Enter the dimension of the array: 3,4
darray( 1 , 1 ) = 1.00000000    
darray( 1 , 2 ) = 2.00000000    
darray( 1 , 3 ) = 3.00000000    
darray( 1 , 4 ) = 4.00000000    
darray( 2 , 1 ) = 2.00000000    
darray( 2 , 2 ) = 4.00000000    
darray( 2 , 3 ) = 6.00000000    
darray( 2 , 4 ) = 8.00000000    
darray( 3 , 1 ) = 3.00000000    
darray( 3 , 2 ) = 6.00000000    
darray( 3 , 3 ) = 9.00000000    
darray( 3 , 4 ) = 12.0000000   

Use of Data Statement

The data statement can be used for preliminaryiperform more than one array, or for array section preliminaryisation.

The syntax of data statement is:

data variable / list / ...

Example

The folloearng example demonstrates the concept:

program dataStatement
implicit none
   integer :: a(5), b(3,3), c(10),i, j
   data a /7,8,9,10,11/ 
   
   data b(1,:) /1,1,1/ 
   data b(2,:)/2,2,2/ 
   data b(3,:)/3,3,3/ 
   data (c(i),i=1,10,2) /4,5,6,7,8/ 
   data (c(i),i=2,10,2)/5*2/
   
   Print *, 'The A array:'
   do j = 1, 5                
   print*, a(j)           
   end do 
   
   Print *, 'The B array:'
   do i = lbound(b,1), ubound(b,1)
   write(*,*) (b(i,j), j = lbound(b,2), ubound(b,2))
   end do

   Print *, 'The C array:' 
   do j = 1, 10                
   print*, c(j)           
   end do      
end program dataStatement

When the above code is compibrought and executed, it produces the folloearng result:

The A array:
7
8
9
10
11
The B array:
1  1  1
2  2  2
3  3  3
The C array:
4
2
5
2
6
2
7
2
8
2

Use of Where Statement

The where statement permit’s you to use a couple of elements of an array in an expression, depending on the awaycome of a couple of logical condition. It permit’s the execution of the expression, on an element, if the given condition is true.

Example

The folloearng example demonstrates the concept:

program whereStatement
implicit none
   integer :: a(3,5), i , j
   
   do i = 1,3
   do j = 1, 5                
   a(i,j) = j-i          
   end do 
   end do
   Print *, 'The A array:'
   do i = lbound(a,1), ubound(a,1)
   write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))
   end do
   
   where( a<0 )="" a="1" elsewhere="" end="" where="" print="" *,="" 'the="" array:'="" do="" i="lbound(a,1)," ubound(a,1)="" write(*,*)="" (a(i,j),="" j="lbound(a,2)," ubound(a,2))="" program="" where'statement="" 

When the above code is compibrought and executed, it produces the folloearng result:

The A array:
0   1   2  3  4
-1  0   1  2  3
-2  -1  0  1  2
The A array:
5   5   5  5  5
1   5   5  5  5
1   1   5  5  5

Fortran - Derived Data Types

Fortran permit's you to degreat derived data types. A derived data type is furthermore calbrought a structure, and it can consist of data objects of various types.

Derived data types are used to represent a record. E.g. you like to keep track of your books in a library, you may want to track the folloearng attributes abaway every book:

  • Title
  • Author
  • Subject
  • Book ID

Defining a Derived data type

To degreat a derived data type, the type and end type statements are used. . The type statement degreats a brand brand new data type, with more than one member for your program. The format of the type statement is this particular:

type type_name      
   declarations
end type 

Here is the way you would declare the Book structure:

type Books
   charbehaveer(len=50) :: title
   charbehaveer(len=50) :: author
   charbehaveer(len=150) :: subject
   integer :: book_id
end type Books

Accesperform Structure Members

An object of a derived data type is calbrought a structure

A structure of type Books can be developd in a type declaration statement like:

type(Books) :: book1 

The components of the structure can be accessed uperform the component selector charbehaveer (%):

book1%title = "C Programming"
book1%author = "Nuha Ali"
book1%subject = "C Programming Tutorial"
book1%book_id = 6495407

Note thead put on presently there are no spaces before and after the % symbol.

Example

The folloearng program illustrates the above concepts:

program deriveDataType
   !type declaration
   type Books
   charbehaveer(len=50) :: title
   charbehaveer(len=50) :: author
   charbehaveer(len=150) :: subject
   integer :: book_id
   end type Books
   !declaring type variables
   type(Books) :: book1 
   type(Books) :: book2 
   
   !accesperform the components of the structure
   
   book1%title = "C Programming"
   book1%author = "Nuha Ali"
   book1%subject = "C Programming Tutorial"
   book1%book_id = 6495407 
   
   book2%title = "Telecom Billing"
   book2%author = "Zara Ali"
   book2%subject = "Telecom Billing Tutorial"
   book2%book_id = 6495700
  
   !display book info
   
   Print *, book1%title 
   Print *, book1%author 
   Print *, book1%subject 
   Print *, book1%book_id  
   
   Print *, book2%title 
   Print *, book2%author 
   Print *, book2%subject 
   Print *, book2%book_id  

end program deriveDataType

When the above code is compibrought and executed, it produces the folloearng result:

C Programming                                     
   Nuha Ali                                          
C Programming       Tutorial                                                                                                                                
   6495407
   Telecom Billing                                   
	Zara Ali                                          
   Telecom Billing Tutorial                                                                                                                              
   6495700

Array of Structures

You can furthermore develop arrays of a derived type:

type(Books), dimension(2) :: list

Individual elements of the array could be accessed as:

list(1)%title = "C Programming"
list(1)%author = "Nuha Ali"
list(1)%subject = "C Programming Tutorial"
list(1)%book_id = 6495407

The folloearng program illustrates the concept:

program deriveDataType
   !type declaration
   type Books
   charbehaveer(len=50) :: title
   charbehaveer(len=50) :: author
   charbehaveer(len=150) :: subject
   integer :: book_id
   end type Books
   !declaring array of books
   type(Books), dimension(2) :: list 
    
   !accesperform the components of the structure
   
   list(1)%title = "C Programming"
   list(1)%author = "Nuha Ali"
   list(1)%subject = "C Programming Tutorial"
   list(1)%book_id = 6495407 
   
   list(2)%title = "Telecom Billing"
   list(2)%author = "Zara Ali"
   list(2)%subject = "Telecom Billing Tutorial"
   list(2)%book_id = 6495700
  
   !display book info
   
   Print *, list(1)%title 
   Print *, list(1)%author 
   Print *, list(1)%subject 
   Print *, list(1)%book_id  
   
   Print *, list(1)%title 
   Print *, list(2)%author 
   Print *, list(2)%subject 
   Print *, list(2)%book_id  

end program deriveDataType

When the above code is compibrought and executed, it produces the folloearng result:

C Programming                                     
   Nuha Ali                                          
C Programming Tutorial                                                                                                                                
   6495407
C Programming                                     
   Zara Ali                                          
   Telecom Billing Tutorial                                                                                                                              
   6495700

Fortran - Pointers

In many kind of kind of programming languages, a pointer variable stores the memory adgown of an object. However, in Fortran, a pointer is a data object thead put on has more functionalilinks than simply storing the memory adgown. It contains more information abaway a particular object, like type, rank, extents, and memory adgown.

A pointer is bumociated with a target simply simply by allocation or pointer bumignment.

Declaring a Pointer Variable

A pointer variable is declacrimson-coloucrimson with the pointer attribute.

The folloearng examples shows declaration of pointer variables:

integer, pointer :: p1 ! pointer to integer  
real, pointer, dimension (:) :: pra ! pointer to 1-dim real array  
real, pointer, dimension (:,:) :: pra2 ! pointer to 2-dim real array

A pointer can point to:

  • an area of dynamically allocated memory
  • a data object of the same type as the pointer, with the target attribute

Allocating Space for a Pointer

The allocate statement permit's you to allocate space for a pointer object. For example:

program pointerExample
implicit none
   integer, pointer :: p1
   allocate(p1)
   p1 = 1
   Print *, p1
   p1 = p1 + 4
   Print *, p1
end program pointerExample

When the above code is compibrought and executed, it produces the folloearng result:

1
5

You need to empty the allocated storage space simply simply by the deallocate statement when it is no durationyer requicrimson-coloucrimson and avoid accumulation of unused and unusable memory space.

Targets and Association

A target is an additional normal variable, with space set aaspect for it. A target variable must be declacrimson-coloucrimson with the target attribute.

You bumociate a pointer variable with a target variable uperform the bumociation operator (=>).

Let us rewrite the previous example, to demonstrate the concept:

program pointerExample
implicit none
   integer, pointer :: p1
   integer, target :: t1 
   p1=>t1
   p1 = 1
   Print *, p1
   Print *, t1
   p1 = p1 + 4
   Print *, p1
   Print *, t1
   t1 = 8
   Print *, p1
   Print *, t1
end program pointerExample

When the above code is compibrought and executed, it produces the folloearng result:

1
1
5
5
8
8

A pointer can be:

  • Undegreatd
  • Associated
  • Disbumociated

In the above program, we have bumociated the pointer p1, with the target t1, uperform the => operator. The function bumociated, checks a pointer’s bumociation status.

The nullify statement disbumociates a pointer from a target.

Nullify does not empty the targets as presently there could be more than one pointer pointing to the same target. However, emptying the pointer implays nullification furthermore.

Example 1

The folloearng example demonstrates the concepts:

program pointerExample
implicit none
   integer, pointer :: p1
   integer, target :: t1 
   integer, target :: t2
   p1=>t1
   p1 = 1
   Print *, p1
   Print *, t1
   p1 = p1 + 4
   Print *, p1
   Print *, t1
   t1 = 8
   Print *, p1
   Print *, t1
   nullify(p1)
   Print *, t1
   p1=>t2
   Print *, bumociated(p1)
   Print*, bumociated(p1, t1)
   Print*, bumociated(p1, t2)
   !exbehavely whead put on is the value of p1 at present
   Print *, p1
   Print *, t2
   p1 = 10
   Print *, p1
   Print *, t2
end program pointerExample

When the above code is compibrought and executed, it produces the folloearng result:

1
1
5
5
8
8
8
T
F
T
952754640
952754640
10
10

Please note thead put on every time you operate the code, the memory adgownes will be various.

Example 2

program pointerExample
implicit none
   integer, pointer :: a, b
   integer, target :: t
   integer :: n
   t= 1
   a=>t
   t = 2
   b => t
   n = a + b
   Print *, a, b, t, n 
end program pointerExample

When the above code is compibrought and executed, it produces the folloearng result:

2  2  2  4

Fortran - Basic Inplace Outplace

We have so far seen thead put on we can read data from keyplank uperform the read * statement, and display awayplace to the screen uperform the print* statement, respectively. This form of inplace-awayplace is free format I/O, and it is calbrought list-directed inplace-awayplace.

The free format easy I/O has the form:

read(*,*) item1, item2, item3...
print *, item1, item2, item3
write(*,*) item1, item2, item3...

However the formatted I/O gives you more flexibility over data transfer.

Formatted Inplace Outplace

Formatted inplace awayplace has the syntax as follows:

read fmt, variable_list 
print fmt, variable_list 
write fmt, variable_list 

Where,

  • fmt is the format specification

  • variable-list is a list of the variables to be read from keyplank or developd on screen

Format specification degreats the way in which formatted data is displayed. It consists of a string, containing a list of edit descriptors in parentheses.

An edit descriptor specifies the exbehave format, for example, width, digit's after decimal point etc., in which charbehaveers and numbers are displayed.

For example:

Print "(f6.3)", pi

The folloearng table describes the descriptors:

Descriptor Description Example
I This is used for integer awayplace. This conaspectrs the form ‘rIw.m’ where the meanings of r, w and m are given in the table below. Integer values are appropriate simplyified in their particular fields. If the field width is not huge sufficient to accommodate an integer then the field is filbrought with asterisks. print "(3i5)", i, j, k
F This is used for real number awayplace. This conaspectrs the form ‘rFw.d’ where the meanings of r, w and d are given in the table below. Real values are appropriate simplyified in their particular fields. If the field width is not huge sufficient to accommodate the real number then the field is filbrought with asterisks. print "(f12.3)",pi
E

This is used for real awayplace in exponential notation. The ‘E’ descriptor statement conaspectrs the form ‘rEw.d’ where the meanings of r, w and d are given in the table below. Real values are appropriate simplyified in their particular fields. If the field width is not huge sufficient to accommodate the real number then the field is filbrought with asterisks.

Please note thead put on, to print away a real number with 3 decimal places a field width of at leastern ten is needed. One for the sign of the mantissa, 2 for the zero, four for the mantissa and 2 for the exponent it'self. In general, w ≥ d + 7.

print "(e10.3)",123456.0 gives ‘0.123e+06’
ES This is used for real awayplace (scientific notation). This conaspectrs the form ‘rESw.d’ where the meanings of r, w and d are given in the table below. The ‘E’ descriptor descrimattress above differs slightly from the traditional well belowstandn ‘scientific notation’. Scientific notation has the mantissa in the range 1.0 to 10.0 unlike the E descriptor which has the mantissa in the range 0.1 to 1.0. Real values are appropriate simplyified in their particular fields. If the field width is not huge sufficient to accommodate the real number then the field is filbrought with asterisks. Here furthermore, the width field must satisfy the expression
w ≥ d + 7
print "(es10.3)",123456.0 gives ‘1.235e+05’
A This is used for charbehaveer awayplace. This conaspectrs the form ‘rAw’ where the meanings of r and w are given in the table below. Charbehaveer types are appropriate simplyified in their particular fields. If the field width is not huge sufficient to accommodate the charbehaveer string then the field is filbrought with the first ‘w’ charbehaveers of the string. print "(a10)", str
X This is used for space awayplace. This conaspectrs the form ‘nX’ where ‘n’ is the number of desicrimson-coloucrimson spaces. print "(5x, a10)", str
/ Slash descriptor – used to insert blank seriess. This conaspectrs the form ‘/’ and forces the next data awayplace to be on a brand brand new series. print "(/,5x, a10)", str

Folloearng symbols are used with the format descriptors:

Symbol Description
c Column number
d Number of digit's to appropriate of the decimal place for real inplace or awayplace
m Minimum number of digit's to be displayed
n Number of spaces to skip
r Repeat count – the number of times to use a descriptor or group of descriptors
w Field width – the number of charbehaveers to use for the inplace or awayplace

Example 1

program printPi
   pi = 3.141592653589793238 
   
   Print "(f6.3)", pi 
   Print "(f10.7)", pi
   Print "(f20.15)", pi 
   Print "(e16.4)", pi/100 
end program printPi

When the above code is compibrought and executed, it produces the folloearng result:

3.142
3.1415927
3.141592741012573
0.3142E-01

Example 2

program printName
implicit none
charbehaveer (len=15) :: preliminary_name
   print *,' Enter your preliminary name.' 
   print *,' Up to 20 charbehaveers, please'
   read *,preliminary_name 
   print "(1x,a)",preliminary_name
end program printName

When the above code is compibrought and executed, it produces the folloearng result: (bumume the user enters the name Zara)

Enter your preliminary name.
   Up to 20 charbehaveers, please
   Zara 

Example 3

program formattedPrint
implicit none
real :: c = 1.2786456e-9, d = 0.1234567e3 
integer :: n = 300789, k = 45, i = 2
charbehaveer (len=15) :: str="Tutorials Point"
print "(i6)", k 
print "(i6.3)", k 
print "(3i10)", n, k, i 
print "(i10,i3,i5)", n, k, i 
print "(a15)",str 
print "(f12.3)", d
print "(e12.4)", c 
print '(/,3x,"n = ",i6, 3x, "d = ",f7.4)', n, d
end program formattedPrint

When the above code is compibrought and executed, it produces the folloearng result:


45
045
300789 45  2
300789 45  2
Tutorials Point
123.457
0.1279E-08

n = 300789 d = *******

The Format Statement

The format statement permit's you to mix and match up up charbehaveer, integer and real awayplace in one statement. The folloearng example demonstrates this particular:

program productDetails 
implicit none 
   charbehaveer (len=15) :: name
   integer :: id 
   real :: weight
   name = 'Ardupilot'
   id = 1
   weight = 0.08
   print *,' The product details are' 
   print 100
   100 format (7x,'Name:', 7x, 'Id:', 1x, 'Weight:')
   print 200, name, id, weight 
   200 format(1x, a, 2x, i3, 2x, f5.2) 
end program productDetails

When the above code is compibrought and executed, it produces the folloearng result:

The product details are
Name:       Id:    Weight:
Ardupilot   1       0.08

Fortran - File Inplace Outplace

Fortran permit's you to read data from, and write data into files.

In the final chapter, you have seen how to read data from, and write data to the terminal. In this particular chapter you will study file inplace and awayplace functionalilinks provided simply simply by Fortran.

You can read and write to one or more files. The OPEN, WRITE, READ and CLOSE statements permit you to achieve this particular.

Opening and Cloperform Files

Before uperform a file you must open the file. The open command is used to open files for reading or writing. The easyst form of the command is:

open (device = number, file = "name").

However, the open statement may have a general form:

open (list-of-specifiers)

The folloearng table describes the many kind of kind of commonly used specifiers:

Specifier Description
[UNIT=] u The device number u could be any kind of kind of number in the range 9-99 and it indicates the file, you may choose any kind of kind of number but every open file in the program must have a unique number
IOSTAT= ios It is the I/O status identifier and need to be an integer variable. If the open statement is successful then the ios value returned is zero else a non-zero value.
ERR = err It is a label to which the manage jumps in case of any kind of kind of error.
FILE = fname File name, a charbehaveer string.
STATUS = sta It shows the prior status of the file. A charbehaveer string and can have one of the 3 values NEW, OLD or SCRATCH. A scratch file is developd and depermited when close upd or the program ends.
ACCESS = acc It is the file access mode. Can have possibly of the 2 values, SEQUENTIAL or DIRECT. The default is SEQUENTIAL.
FORM= frm It gives the formatting status of the file. Can have possibly of the 2 values FORMATTED or UNFORMATTED. The default is UNFORMATTED
RECL = rl It specifies the duration of every record in a direct access file.

After the file has been opened, it is accessed simply simply by read and write statements. Once done, it need to be close upd uperform the close up statement.

The close up statement has the folloearng syntax:

close up ([UNIT=]u[,IOSTAT=ios,ERR=err,STATUS=sta])

Please note thead put on the parameters in brackets are optional.

Example

This example demonstrates opening a brand brand new file for writing a couple of data into the file.

program awayplacedata   
implicit none   
real, dimension(100) :: x, y  
real, dimension(100) :: p, q
integer :: i  
   ! data  
   do i=1,100  
   x(i) = i * 0.1 
   y(i) = sin(x(i)) * (1-cos(x(i)/3.0))  
   end do  
   ! awayplace data into a file 
   open(1, file='data1.dat', status='brand brand new')  
   do i=1,100  
   write(1,*) x(i), y(i)   
   end do  
   close up(1) 
end program awayplacedata

When the above code is compibrought and executed, it develops the file data1.dat and writes the x and y array values into it. And then close ups the file.

Reading from and Writing into the File

The read and write statements respectively are used for reading from and writing into a file respectively.

They have the folloearng syntax:

read ([UNIT=]u, [FMT=]fmt, IOSTAT=ios, ERR=err, END=s)
write([UNIT=]u, [FMT=]fmt, IOSTAT=ios, ERR=err, END=s)

Most of the specifiers have already been speak about presently thereed in the above table.

The END=s specifier is a statement label where the program jumps, when it reveryes end-of-file.

Example

This example demonstrates reading from and writing into a file.

In this particular program we read from the file, we developd in the final example, data1.dat, and display it on screen.

program awayplacedata   
implicit none   
real, dimension(100) :: x, y  
real, dimension(100) :: p, q
integer :: i  
   ! data  
   do i=1,100  
   x(i) = i * 0.1 
   y(i) = sin(x(i)) * (1-cos(x(i)/3.0))  
   end do  
   ! awayplace data into a file 
   open(1, file='data1.dat', status='brand brand new')  
   do i=1,100  
   write(1,*) x(i), y(i)   
   end do  
   close up(1) 
  
   ! opening the file for reading
   open (2, file='data1.dat', status='old')
  
   do i=1,100  
   read(2,*) p(i), q(i)
   end do 
   close up(2)
   do i=1,100  
   write(*,*) p(i), q(i)
   end do 
end program awayplacedata

When the above code is compibrought and executed, it produces the folloearng result:

0.100000001  5.54589933E-05
0.200000003  4.41325130E-04
0.300000012  1.47636665E-03
0.400000006  3.45637114E-03
0.500000000  6.64328877E-03
0.600000024  1.12552457E-02
0.699999988  1.74576249E-02
0.800000012  2.53552198E-02
0.900000036  3.49861123E-02
1.00000000   4.63171229E-02
1.10000002   5.92407547E-02
1.20000005   7.35742599E-02
1.30000007   8.90605897E-02
1.39999998   0.105371222    
1.50000000   0.122110792    
1.60000002   0.138823599    
1.70000005   0.155002072    
1.80000007   0.170096487    
1.89999998   0.183526158    
2.00000000   0.194692180    
2.10000014   0.202990443    
2.20000005   0.207826138    
2.29999995   0.208628103    
2.40000010   0.204863414    
2.50000000   0.196052119    
2.60000014   0.181780845    
2.70000005   0.161716297    
2.79999995   0.135617107    
2.90000010   0.103344671    
3.00000000   6.48725405E-02
3.10000014   2.02930309E-02
3.20000005  -3.01767997E-02
3.29999995  -8.61928314E-02
3.40000010  -0.147283033    
3.50000000  -0.212848678    
3.60000014  -0.282169819    
3.70000005  -0.354410470    
3.79999995  -0.428629100    
3.90000010  -0.503789663    
4.00000000  -0.578774154    
4.09999990  -0.652400017    
4.20000029  -0.723436713    
4.30000019  -0.790623367    
4.40000010  -0.852691114    
4.50000000  -0.908382416    
4.59999990  -0.956472993    
4.70000029  -0.995793998    
4.80000019  -1.02525222    
4.90000010  -1.04385209    
5.00000000  -1.05071592    
5.09999990  -1.04510069    
5.20000029  -1.02641726    
5.30000019  -0.994243503    
5.40000010  -0.948338211    
5.50000000  -0.888650239    
5.59999990  -0.815326691    
5.70000029  -0.728716135    
5.80000019  -0.629372001    
5.90000010  -0.518047631    
6.00000000  -0.395693362    
6.09999990  -0.263447165    
6.20000029  -0.122622721    
6.30000019   2.53026206E-02
6.40000010   0.178709000    
6.50000000   0.335851669    
6.59999990   0.494883657    
6.70000029   0.653881252    
6.80000019   0.810866773    
6.90000010   0.963840425    
7.00000000   1.11080539    
7.09999990   1.24979746    
7.20000029   1.37891412    
7.30000019   1.49633956    
7.40000010   1.60037732    
7.50000000   1.68947268    
7.59999990   1.76223695    
7.70000029   1.81747139    
7.80000019   1.85418403    
7.90000010   1.87160957    
8.00000000   1.86922085    
8.10000038   1.84674001    
8.19999981   1.80414569    
8.30000019   1.74167395    
8.40000057   1.65982044    
8.50000000   1.55933595    
8.60000038   1.44121361    
8.69999981   1.30668485    
8.80000019   1.15719533    
8.90000057   0.994394958    
9.00000000   0.820112705    
9.10000038   0.636327863    
9.19999981   0.445154816    
9.30000019   0.248800844    
9.40000057   4.95488606E-02
9.50000000  -0.150278628    
9.60000038  -0.348357052    
9.69999981  -0.542378068    
9.80000019  -0.730095863    
9.90000057  -0.909344316    
10.0000000  -1.07807255    

Fortran - Procedures

A procedure is a group of statements thead put on perform a well-degreatd task and can be invoked from your program. Information (or data) is pbumed to the calling program, to the procedure as arguments.

There are 2 types of procedures:

  • Functions
  • Subrawayines

Function

A function is a procedure thead put on returns a performle quantity. A function need to not modify it's arguments.

The returned quantity is belowstandn as function value, and it is denoted simply simply by the function name.

Syntax:

Syntax for a function is as follows:

function name(arg1, arg2, ....)  
   [declarations, including those for the arguments]   
   [executable statements] 
end function [name]

The folloearng example demonstrates a function named area_of_group. It calculates the area of a group with radius r.

program calling_func
   real :: a
   a = area_of_group(2.0) 
   Print *, "The area of a group with radius 2.0 is"
   Print *, a
end program calling_func

function area_of_group (r)  
! this particular function complacees the area of a group with radius r     
   implicit none      
! function result     
   real :: area_of_group   
! dummy arguments     
   real :: r     
! local variables     
   real :: pi    
   pi = 4 * atan (1.0)     
   area_of_group = pi * r**2  
end function area_of_group

When you compile and execute the above program, it produces the folloearng result:

The area of a group with radius 2.0 is
   12.5663710   

Please note thead put on:

  • You must specify implicit none in both the main program as well as the procedure.

  • The argument r in the calbrought function is calbrought dummy argument.

The result Option

If you like the returned value to be stocrimson-coloucrimson in a couple of other name than the function name, you can use the result option.

You can specify the return variable name as:

function name(arg1, arg2, ....) result (return_var_name)  
   [declarations, including those for the arguments]   
   [executable statements] 
end function [name]

Subrawayine

A subrawayine does not return a value, however it can modify it's arguments.

Syntax

subrawayine name(arg1, arg2, ....)    
   [declarations, including those for the arguments]    
   [executable statements]  
end subrawayine [name]

Calling a Subrawayine

You need to invoke a subrawayine uperform the call statement.

The folloearng example demonstrates the definition and use of a subrawayine swap, thead put on alters the values of it's arguments.

program calling_func
implicit none
   real :: a, b
   a = 2.0
   b = 3.0
   Print *, "Before calling swap"
   Print *, "a = ", a
   Print *, "b = ", b
   call swap(a, b)
   Print *, "After calling swap"
   Print *, "a = ", a
   Print *, "b = ", b
end program calling_func

   subrawayine swap(x, y) 
   implicit none
   real :: x, y, temp   
   temp = x  
   x = y 
   y = temp  
end subrawayine swap

When you compile and execute the above program, it produces the folloearng result:

Before calling swap
a = 2.00000000    
b = 3.00000000    
After calling swap
a = 3.00000000    
b = 2.00000000   

Specifying the Intent of the Arguments

The intent attribute permit's you to specify the intention with which arguments are used in the procedure. The folloearng table provides the values of the intent attribute:

Value Used as Explanation
in intent(in) Used as inplace values, not alterd in the function
away intent(away) Used as awayplace value, they are overdevelopd
inaway intent(inaway) Arguments are both used and overdevelopd

The folloearng example demonstrates the concept:

program calling_func
implicit none
   real :: x, y, z, disc
   x= 1.0
   y = 5.0
   z = 2.0
   call intent_example(x, y, z, disc)
   Print *, "The value of the discriminant is"
   Print *, disc
end program calling_func

subrawayine intent_example (a, b, c, d)     
   implicit none     
   ! dummy arguments      
   real, intent (in) :: a     
   real, intent (in) :: b      
   real, intent (in) :: c    
   real, intent (away) :: d   
   d = b*b - 4.0*a*c 
end subrawayine intent_example

When you compile and execute the above program, it produces the folloearng result:

The value of the discriminant is
   17.0000000    

Recursive Procedures

Recursion occurs when a programming languages permit's you to call a function inaspect the same function. It is calbrought recursive call of the function.

When a procedure calls it'self, directly or indirectly, is calbrought a recursive procedure. You need to declare this particular type of procedures simply simply by preceding the word recursive before it's declaration.

When a function is used recursively, the result option has to be used.

Folloearng is an example, which calculates fbehaveorial for a given number uperform a recursive procedure:

program calling_func
implicit none
   integer :: i, f
   i = 15
   Print *, "The value of fbehaveorial 15 is"
   f = myfbehaveorial(15)
   Print *, f
end program calling_func

recursive function myfbehaveorial (n) result (fac)  
   ! complacees the fbehaveorial of n (n!)      
   implicit none     
   ! function result     
   integer :: fac     
   ! dummy arguments     
   integer, intent (in) :: n     
   select case (n)         
   case (0:1)         
   fac = 1         
   case default    
   fac = n * myfbehaveorial (n-1)  
   end select 
end function myfbehaveorial

Internal Procedures

When a procedure is contained wislim a program, it is calbrought the internal procedure of the program. The syntax for containing an internal procedure is as follows:

program program_name     
   implicit none         
   ! type declaration statements         
   ! executable statements    
   . . .     
   contains         
   ! internal procedures      
   . . .  
end program program_name

The folloearng example demonstrates the concept:

program mainprog  
implicit none 
real :: a, b 
   a = 2.0
   b = 3.0
   Print *, "Before calling swap"
   Print *, "a = ", a
   Print *, "b = ", b
   call swap(a, b)
   Print *, "After calling swap"
   Print *, "a = ", a
   Print *, "b = ", b
 
   contains   
   subrawayine swap(x, y)     
   real :: x, y, temp      
   temp = x 
   x = y  
   y = temp   
   end subrawayine swap 
end program mainprog   

When you compile and execute the above program, it produces the folloearng result:

Before calling swap
a = 2.00000000    
b = 3.00000000    
After calling swap
a = 3.00000000    
b = 2.00000000   

Fortran - Modules

A module is like a package where you can keep your functions and subrawayines, in case you are writing an extremely huge program, or your functions or subrawayines can be used in more than one program.

Modules provide you a way of splitting your programs between multiple files.

Modules are used for:

  • Packaging subprograms, data and interface blocks.
  • Defining global data thead put on can be used simply simply by more than one rawayine.
  • Declaring variables thead put on can be made available wislim any kind of kind of rawayines you choose.
  • Imsloting a module entirely, for use, into an additional program or subrawayine.

Syntax of a Module

A module consists of 2 parts:

  • a specification part for statements declaration
  • a contains part for subrawayine and function definitions

The general form of a module is:

module name     
   [statement declarations]  
   [contains [subrawayine and function definitions] ] 
end module [name]

Uperform a Module into your Program

You can incorporate a module in a program or subrawayine simply simply by the use statement:

use name  

Please note thead put on

  • You can add as many kind of kind of modules as needed, every will be in separate files and compibrought separately.

  • A module can be used in various various programs.

  • A module can be used many kind of kind of times in the same program.

  • The variables declacrimson-coloucrimson in a module specification part, are global to the module.

  • The variables declacrimson-coloucrimson in a module become global variables in any kind of kind of program or rawayine where the module is used.

  • The use statement can appear in the main program, or any kind of kind of other subrawayine or module which uses the rawayines or variables declacrimson-coloucrimson in a particular module.

Example

The folloearng example demonstrates the concept:

module constants  
implicit none 
   real, parameter :: pi = 3.1415926536  
   real, parameter :: e = 2.7182818285 
contains      
   subrawayine show_consts()          
   print*, "Pi = ", pi          
   print*,  "e = ", e     
   end subrawayine show_consts 
end module constants 

program module_example     
use constants      
implicit none     
   real :: x, ePowerx, area, radius 
   x = 2.0
   radius = 7.0
   ePowerx = e ** x
   area = pi * radius**2     
   call show_consts() 
   print*, "e raised to the power of 2.0 = ", ePowerx
   print*, "Area of a group with radius 7.0 = ", area  
end program module_example

When you compile and execute the above program, it produces the folloearng result:

Pi = 3.14159274    
e =  2.71828175    
e raised to the power of 2.0 = 7.38905573    
Area of a group with radius 7.0 = 153.938049   

Accessibility of Variables and Subrawayines in a Module

By default, all the variables and subrawayines in a module is made available to the program thead put on is uperform the module code, simply simply by the use statement.

However, you can manage the accessibility of module code uperform the private and public attributes. When you declare a couple of variable or subrawayine as private, it is not available awayaspect the module.

Example

The folloearng example illustrates the concept:

In the previous example, we had 2 module variables, e and pi. Let us create all of them private and observe the awayplace:

module constants  
implicit none 
   real, parameter,private :: pi = 3.1415926536  
   real, parameter, private :: e = 2.7182818285 
contains      
   subrawayine show_consts()          
   print*, "Pi = ", pi          
   print*, "e = ", e     
   end subrawayine show_consts 
end module constants 

program module_example     
use constants      
implicit none     
   real :: x, ePowerx, area, radius 
   x = 2.0
   radius = 7.0
   ePowerx = e ** x
   area = pi * radius**2     
   call show_consts() 
   print*, "e raised to the power of 2.0 = ", ePowerx
   print*, "Area of a group with radius 7.0 = ", area  
end program module_example

When you compile and execute the above program, it gives the folloearng error message:

   ePowerx = e ** x
   1
Error: Symbol 'e' at (1) has no IMPLICIT type
main.f95:19.13:

   area = pi * radius**2     
   1
Error: Symbol 'pi' at (1) has no IMPLICIT type

Since e and pi, both are declacrimson-coloucrimson private, the program module_example cannot access these variables any kind of kind ofmore.

However, other module subrawayines can access all of them:

module constants  
implicit none 
   real, parameter,private :: pi = 3.1415926536  
   real, parameter, private :: e = 2.7182818285 
contains      
   subrawayine show_consts()          
   print*, "Pi = ", pi          
   print*, "e = ", e     
   end subrawayine show_consts 
   function ePowerx(x)result(ePx) 
   implicit none
   real::x
   real::ePx
   ePx = e ** x
   end function ePowerx
    
   function areaCircle(r)result(a)  
implicit none
   real::r
   real::a
   a = pi * r**2  
   end function areaCircle
    
end module constants 

program module_example     
use constants      
implicit none     
   call show_consts() 
   Print*, "e raised to the power of 2.0 = ", ePowerx(2.0)
   print*, "Area of a group with radius 7.0 = ", areaCircle(7.0)  
end program module_example

When you compile and execute the above program, it produces the folloearng result:

Pi = 3.14159274    
e = 2.71828175    
e raised to the power of 2.0 = 7.38905573    
Area of a group with radius 7.0 = 153.938049   

Fortran - Intrinsic Functions

Intrinsic functions are a couple of common and imslotant functions thead put on are provided as a part of the Fortran language. We have already speak about presently thereed a couple of of these functions in the Arrays, Charbehaveers and String chapters.

Intrinsic functions can be categorised as:

  • Numeric Functions
  • Maall of thematical Functions
  • Numeric Inquiry Functions
  • Floating-Point Manipulation Functions
  • Bit Manipulation Functions
  • Charbehaveer Functions
  • Kind Functions
  • Logical Functions
  • Array Functions.

We have speak about presently thereed the array functions in the Arrays chapter. In the folloearng section we provide brief descriptions of all these functions from other categories.

In the function name column,

  • A represents any kind of kind of type of numeric variable
  • R represents a real or integer variable
  • X and Y represent real variables
  • Z represents complex variable
  • W represents real or complex variable

Numeric Functions

Function Description
ABS (A) It returns the absolute value of A
AIMAG (Z) It returns the imaginary part of a complex number Z
AINT (A [, KIND]) It toperatecates frbehaveional part of A towards zero, returning a real, whole number.
ANINT (A [, KIND]) It returns a real value, the nearest integer or whole number.
CEILING (A [, KIND]) It returns the leastern integer greater than or equal to number A.
CMPLX (X [, Y, KIND]) It converts the real variables X and Y to a complex number X+iY; if Y is absent, 0 is used.
CONJG (Z) It returns the complex conjugate of any kind of kind of complex number Z.
DBLE (A) It converts A to a double precision real number.
DIM (X, Y) It returns the posit down downive difference of X and Y.
DPROD (X, Y) It returns the double precision real product of X and Y.
FLOOR (A [, KIND]) It provides the greveryeck integer less than or equal to number A.
INT (A [, KIND]) It converts a number (real or integer) to integer, toperatecating the real part towards zero.
MAX (A1, A2 [, A3,...]) It returns the maximum value from the arguments, all being of same type.
MIN (A1, A2 [, A3,...]) It returns the minimum value from the arguments, all being of same type.
MOD (A, P) It returns the remainder of A on division simply simply by P, both arguments being of the same type (A-INT(A/P)*P)
MODULO (A, P) It returns A modulo P: (A-FLOOR(A/P)*P)
NINT (A [, KIND]) It returns the nearest integer of number A
REAL (A [, KIND]) It Converts to real type
SIGN (A, B) It returns the absolute value of A multiplayd simply simply by the sign of P. Basically it transfers the of sign of B to A.

Example

program numericFunctions
implicit none  
   ! degreat constants  
   !degreat variables
   real :: a, b 
   complex :: z
   !values for a, b 
   a = 15.2345
   b = -20.7689
    
   write(*,*) 'abs(a): ',abs(a),' abs(b): ',abs(b)   
   write(*,*) 'aint(a): ',aint(a),' aint(b): ',aint(b) 
   write(*,*) 'ceiling(a): ',ceiling(a),' ceiling(b): ',ceiling(b)   
   write(*,*) 'floor(a): ',floor(a),' floor(b): ',floor(b)  
    
   z = cmplx(a, b)
   write(*,*) 'z: ',z   
end program numericFunctions

When you compile and execute the above program, it produces the folloearng result:

abs(a): 15.2344999   abs(b): 20.7688999    
aint(a): 15.0000000  aint(b): -20.0000000    
ceiling(a): 16  ceiling(b): -20
floor(a): 15  floor(b): -21
z: (15.2344999, -20.7688999)

Maall of thematical Functions

Function Description
ACOS (X) It returns the inverse cosine in the range (0, π), in radians.
ASIN (X) It returns the inverse sine in the range (-π/2, π/2), in radians.
ATAN (X) It returns the inverse tangent in the range (-π/2, π/2), in radians.
ATAN2 (Y, X) It returns the inverse tangent in the range (-π, π), in radians.
COS (X) It returns the cosine of argument in radians.
COSH (X) It returns the hyperbolic cosine of argument in radians.
EXP (X) It returns the exponential value of X.
LOG (X) It returns the natural logarithmic value of X.
LOG10 (X) It returns the common logarithmic (base 10) value of X.
SIN (X) It returns the sine of argument in radians.
SINH (X) It returns the hyperbolic sine of argument in radians.
SQRT (X) It returns square fundamental of X.
TAN (X) It returns the tangent of argument in radians.
TANH (X) It returns the hyperbolic tangent of argument in radians.

Example

The folloearng program complacees the horizontal and vertical posit down downion x and y respectively of a projectile after a time, t:

Where, x = u t cos a and y = u t sin a - g t2 / 2

program projectileMotion  
implicit none  
   ! degreat constants  
   real, parameter :: g = 9.8  
   real, parameter :: pi = 3.1415927  
   !degreat variables
   real :: a, t, u, x, y   
   !values for a, t, and u 
   a = 45.0
   t = 20.0
   u = 10.0
   ! convert angle to radians  
   a = a * pi / 180.0  
   x = u * cos(a) * t   
   y = u * sin(a) * t - 0.5 * g * t * t  
   write(*,*) 'x: ',x,'  y: ',y   
end program projectileMotion

When you compile and execute the above program, it produces the folloearng result:

x: 141.421356  y: -1818.57861  

Numeric Inquiry Functions

These functions work with a particular model of integer and floating-point arithmetic. The functions return properlinks of numbers of the same kind as the variable X, which can be real and in a couple of cases integer.

Function Description
DIGITS (X) It returns the number of significan't digit's of the model.
EPSILON (X) It returns the number thead put on is almany kind of kind of negligible compacrimson-coloucrimson to one. In other words, it returns the smallest value such thead put on REAL( 1.0, KIND(X)) + EPSILON(X) is not equal to REAL( 1.0, KIND(X)).
HUGE (X) It returns the hugest number of the model
MAXEXPONENT (X) It returns the maximum exponent of the model
MINEXPONENT (X) It returns the minimum exponent of the model
PRECISION (X) It returns the decimal precision
RADIX (X) It returns the base of the model
RANGE (X) It returns the decimal exponent range
TINY (X) It returns the smallest posit down downive number of the model

Floating-Point Manipulation Functions

Function Description
EXPONENT (X) It returns the exponent part of a model number
FRACTION (X) It returns the frbehaveional part of a number
NEAREST (X, S) It returns the nearest various processor number in given direction
RRSPACING (X) It returns the reciprocal of the relative spacing of model numbers near given number
SCALE (X, I) It multiplays a real simply simply by it's base to an integer power
SET_EXPONENT (X, I) it returns the exponent part of a number
SPACING (X) It returns the absolute spacing of model numbers near given number

Bit Manipulation Functions

Function Description
BIT_SIZE (I) It returns the number of bit's of the model
BTEST (I, POS) Bit checcalifornia king
IAND (I, J) Logical AND
IBCLR (I, POS) Clear bit
IBITS (I, POS, LEN) Bit extrbehaveion
IBSET (I, POS) Set bit
IEOR (I, J) Exclusive OR
IOR (I, J) Inclusive OR
ISHFT (I, SHIFT) Logical shift
ISHFTC (I, SHIFT [, SIZE]) Circular shift
NOT (I) Logical complement

Charbehaveer Functions

Function Description
ACHAR (I) It returns the Ith charbehaveer in the ASCII collating sequence.
ADJUSTL (STRING) It adsimplys string left simply simply by removing any kind of kind of leading blanks and inserting trailing blanks
ADJUSTR (STRING) It adsimplys string appropriate simply simply by removing trailing blanks and inserting leading blanks.
CHAR (I [, KIND]) It returns the Ith charbehaveer in the machine specific collating sequence
IACHAR (C) It returns the posit down downion of the charbehaveer in the ASCII collating sequence.
ICHAR (C) It returns the posit down downion of the charbehaveer in the machine (processor) specific collating sequence.
INDEX (STRING, SUBSTRING [, BACK]) It returns the leftmany kind of kind of (appropriatemany kind of kind of if BACK is .TRUE.) starting posit down downion of SUBSTRING wislim STRING.
LEN (STRING) It returns the duration of a string.
LEN_TRIM (STRING) It returns the duration of a string withaway trailing blank charbehaveers.
LGE (STRING_A, STRING_B) Lexically greater than or equal
LGT (STRING_A, STRING_B) Lexically greater than
LLE (STRING_A, STRING_B) Lexically less than or equal
LLT (STRING_A, STRING_B) Lexically less than
REPEAT (STRING, NCOPIES) Repeated concatenation
SCAN (STRING, SET [, BACK]) It returns the index of the leftmany kind of kind of (appropriatemany kind of kind of if BACK is .TRUE.) charbehaveer of STRING thead put on mattressurationy to SET, or 0 if none mattressurationy.
TRIM (STRING) Removes trailing blank charbehaveers
VERIFY (STRING, SET [, BACK]) Verifies the set of charbehaveers in a string

Kind Functions

Function Description
KIND (X) It returns the kind type parameter value.
SELECTED_INT_KIND (R) It returns kind of type parameter for specified exponent range.
SELECTED_REAL_KIND ([P, R]) Real kind type parameter value, given precision and range

Logical Function

Function Description
LOGICAL (L [, KIND]) Convert between objects of type logical with various kind type parameters

Fortran - Numeric Precision

We have already speak about presently thereed thead put on, in older versions of Fortran, presently there were 2 real types: the default real type and double precision type.

However, Fortran 90/95 provides more manage over the precision of real and integer data types through the kind specifie.

The Kind Attribute

Different kind of numbers are stocrimson-coloucrimson variously inaspect the complaceer. The kind attribute permit's you to specify how a number is stocrimson-coloucrimson internally. For example,

real, kind = 2 :: a, b, c
real, kind = 4 :: e, f, g
integer, kind = 2 :: i, j, k
integer, kind = 3 :: l, m, n

In the above declaration, the real variables e, f and g have more precision than the real variables a, b and c. The integer variables l, m and n, can store huger values and have more digit's for storage than the integer variables i, j and k. Although this particular is machine dependent.

Example

program kindSpecifier
implicit none
   real(kind = 4) :: a, b, c
   real(kind = 8) :: e, f, g
   integer(kind = 2) :: i, j, k
   integer(kind = 4) :: l, m, n
   integer :: kind_a, kind_i, kind_e, kind_l
   kind_a = kind(a)
   kind_i = kind(i)
   kind_e = kind(e)
   kind_l = kind(l)
   print *,'default kind for real is', kind_a
   print *,'default kind for int is', kind_i
   print *,'extended kind for real is', kind_e
   print *,'default kind for int is', kind_l
end program kindSpecifier

When you compile and execute the above program it produces the folloearng result:

default kind for real is 4
default kind for int is 2
extended kind for real is 8
default kind for int is 4

Inquiring the Size of Variables

There are a number of intrinsic functions thead put on permit's you to interrogate the dimension of numbers.

For example, the bit_dimension(i) intrinsic function specifies the number of bit's used for storage. For real numbers, the precision(x) intrinsic function, returns the number of decimal digit's of precision, while the range(x) intrinsic function returns the decimal range of the exponent.

Example

program getSize
implicit none
   real (kind = 4) :: a
   real (kind = 8) :: b
   integer (kind = 2) :: i
   integer (kind = 4) :: j

   print *,'precision of real(4) =', precision(a)
   print *,'precision of real(8) =', precision(b)
   
   print *,'range of real(4) =', range(a)
   print *,'range of real(8) =', range(b)
   

   print *,'maximum exponent of real(4) =' , maxexponent(a)
   print *,'maximum exponent of real(8) =' , maxexponent(b)
  
   print *,'minimum exponent of real(4) =' , minexponent(a)
   print *,'minimum exponent of real(8) =' , minexponent(b)
   
   print *,'bit's in integer(2) =' , bit_dimension(i)
   print *,'bit's in integer(4) =' , bit_dimension(j)
   
end program getSize

When you compile and execute the above program it produces the folloearng result:

precision of real(4) = 6
precision of real(8) = 15
range of real(4) = 37
range of real(8) = 307
maximum exponent of real(4) = 128
maximum exponent of real(8) = 1024
minimum exponent of real(4) = -125
minimum exponent of real(8) = -1021
bit's in integer(2) = 16
bit's in integer(4) = 32

Obtaining the Kind Value

Fortran provides 2 more intrinsic functions to obtain the kind value for the requicrimson-coloucrimson precision of integers and reals:

  • selected_int_kind (r)
  • selected_real_kind ([p, r])

The selected_real_kind function returns an integer thead put on is the kind type parameter value essential for a given decimal precision p and decimal exponent range r. The decimal precision is the number of significan't digit's, and the decimal exponent range specifies the smallest and hugest representable number. The range is thus from 10-r to 10+r.

For example, selected_real_kind (p = 10, r = 99) returns the kind value needed for a precision of 10 decimal places, and a range of at leastern 10-99 to 10+99.

Example

program getKind
implicit none
   integer:: i
   i = selected_real_kind (p = 10, r = 99) 
   print *,'selected_real_kind (p = 10, r = 99)', i
end program getKind

When you compile and execute the above program it produces the folloearng result:

selected_real_kind (p = 10, r = 99) 8

Fortran - Program Libraries

There are various Fortran tools and libraries. Some are free and a couple of are paid services.

Folloearng are a couple of free libraries:

  • RANDLIB, random number and statistical distribution generators
  • BLAS
  • EISPACK
  • GAMS–NIST Guide to Available Math Software
  • Some statistical and other rawayines from NIST
  • LAPACK
  • LINPACK
  • MINPACK
  • MUDPACK
  • NCAR Maall of thematical Library
  • The Netlib collection of maall of thematical delicateware, papers, and databases.
  • ODEPACK
  • ODERPACK, a set of rawayines for rancalifornia king and ordering.
  • Expokit for complaceing matrix exponentials
  • SLATEC
  • SPECFUN
  • STARPAC
  • StatLib statistical library
  • TOMS
  • Sorting and merging strings

The folloearng libraries are not free:

  • The NAG Fortran numerical library
  • The Visual Numerics IMSL library
  • Numerical Recipes

Fortran - Programming Style

Programming style is all abaway folloearng a couple of rules while developing programs. These great prbehaveices impart values like readpotential, and unamhugeuity into your program.

A great program need to have the folloearng charbehaveeristics:

  • Readpotential
  • Proper logical structure
  • Self-explanatory notes and comments

For example, if you create a comment like the folloearng, it will not be of a lot help:

! loop from 1 to 10 
do i=1,10  

However, if you are calculating binomial coefficient, and need this particular loop for nCr then a comment like this particular will be helpful:

! loop to calculate nCr 
do i=1,10
  • Indented code blocks to create various levels of code clear.

  • Self-checcalifornia king codes to ensure presently there will be no numerical errors like division simply simply by zero, square fundamental of a negative real number or logarithm of a negative real number.

  • Including codes thead put on ensure variables do not conaspectr unlawful or away of range values, i.e., inplace validation.

  • Not placeting checks where it would be unessential and sluggishs down the execution. For example:

real :: x 
x = sin(y) + 1.0
if (x >= 0.0) then
z = sqrt(x)
end if
  • Clearlayr developd code uperform appropriate algorithms.
  • Splitting the durationy expressions uperform the continuation marker ‘&’.
  • Macalifornia king meaningful variable names.

Fortran - Debugging Program

A debugger tool is used to oceanrch for errors in the programs.

A debugger program steps through the code and permit's you to examine the values in the variables and other data objects during execution of the program.

It loads the source code and you are meant to operate the program wislim the debugger. Debuggers debug a program simply simply by:

  • Setting breakpoints,
  • Stepping through the source code,
  • Setting watch points.

Breakpoints specify where the program need to cease, specifically after a critical series of code. Program executions after the variables are checked at a breakpoint.

Debugger programs furthermore check the source code series simply simply by series.

Watch points are the points where the values of a couple of variables are needed to be checked, particularly after a read or write operation.

The gdb Debugger

The gdb debugger, the GNU debugger comes with Linux operating system. For X earndows system, gdb comes with a graphical interface and the program is named xxgdb.

Folloearng table provides a couple of commands in gdb:

Command Purpose
break Setting a breakpoint
operate Starts execution
cont Continues execution
next Executes only the next series of source code, withaway stepping into any kind of kind of function call
step Execute the next series of source code simply simply by stepping into a function in case of a function call.

The dbx Debugger

There is an additional debugger, the dbx debugger, for Linux.

The folloearng table provides a couple of commands in dbx:

Command Purpose
cease[var] Sets a breakpoint when the value of variable var alters.
cease in [proc] It ceases execution when a procedure proc is entecrimson-coloucrimson
cease at [series] It sets a breakpoint at a specified series.
operate Starts execution.
cont Continues execution.
next Executes only the next series of source code, withaway stepping into any kind of kind of function call.
step Execute the next series of source code simply simply by stepping into a function in case of a function call.
SHARE
Previous articleApache Pig
Next articleLucene

NO COMMENTS

LEAVE A REPLY