0% found this document useful (0 votes)
25 views91 pages

Cours Fortran

Uploaded by

sepeynithandre5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views91 pages

Cours Fortran

Uploaded by

sepeynithandre5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

Intro Basics Control Arrays Procedures I/O

Computer Programming using Fortran 90

Matthieu Marquillie
[email protected]

Université de Lille

Matthieu Marquillie Computer Programming using Fortran 90 1 of 91


Intro Basics Control Arrays Procedures I/O

Outline

1 Introduction

2 Fortran basics

3 Control constructs

4 Arrays

5 Procedures

6 Input/Output

Matthieu Marquillie Computer Programming using Fortran 90 2 of 91


Intro Basics Control Arrays Procedures I/O

Outline

1 Introduction

2 Fortran basics

3 Control constructs

4 Arrays

5 Procedures

6 Input/Output

Matthieu Marquillie Computer Programming using Fortran 90 3 of 91


Intro Basics Control Arrays Procedures I/O

Computer :

Hardware :
Memory (RAM) : store values during execution of a program (fast ).
CPU (central processor unit) : does the work.
Hard disk drive : store data permanently (slow ).
Keyboard : allow you to input information.
Screen, files, printer : output information.

Software :
Operating system : Unix, Linux, Windows, Mac-OS, ...
Editors : to write text (source code).
Fortran 90 program.
Compilers : transform source code in executable.

Matthieu Marquillie Computer Programming using Fortran 90 4 of 91


Intro Basics Control Arrays Procedures I/O

High level programming languages :

Assembler code :
Low level language :
Symbolic representation of the machine codes.
Specific for a given CPU architecture.
Complex, slow and not portable.

Fortran, ADA, C, Java :


High level languages.
More expressive, more secure and quicker to use.
Need a compiler (specific for a given architecture) to translate to machine code.
Portable.

Matthieu Marquillie Computer Programming using Fortran 90 5 of 91


Intro Basics Control Arrays Procedures I/O

Fortran :
First High level compiled language :
Developped in IBM as a more practical alternative to assembly language.
ForTran : The IBM Mathematical Formula Translating System.
Successful only because the compiler could generate optimized code.
Versions History :
First IBM compiler in 1957.
1958-1962 : IBM Fortan II, IBM Fortran III and IBM Fortran IV.
Fortran 66 : First official standard (the way to portability )
Fortran 77 : add a number of significant extensions.
Fortran 90 (and 95) : Free source form, modules, array operations, dynamic memory,
basic object-oriented programming.
Fortran 2003 (and 2008) : nearly complete object oriented language and add some
interesting features.
This course : Fortran 90
Fortran 2003 not fully implemented in compilers :
http://fortranwiki.org/fortran/show/Fortran+2003+status
Fortran 90 sufficient for small and medium code, object oriented code only needed when
writing large applications or libraries.
Matthieu Marquillie Computer Programming using Fortran 90 6 of 91
Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Outline

1 Introduction

2 Fortran basics
Syntax
Representation
Declarations
Operators and expressions

3 Control constructs

4 Arrays

5 Procedures

6 Input/Output
Matthieu Marquillie Computer Programming using Fortran 90 7 of 91
Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Free source form :

132 characters per line.


’ !’ comment initiator : everything on a line after this character is a comment.
myresults = data1 + data2 ! this is a comment
! this is another comment
one line = one statement
’&’ line continuation separator : statement on several lines.
myresults = data1 + data2 + &
data3 + data4 + &
data5 + data6
’;’ statement separator : more than one statement on one line.
res1 = data1 + data2 ; res2 = data3 + data4

Matthieu Marquillie Computer Programming using Fortran 90 8 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Character set :

Characters :
26 letters
0-9
Special characters :
! * + ’’ < ( = > ) ; % / - : , ? ’ . & $
The space character.
The underscore.
uppercase = lowercase
Names :
Variables, program, subroutines, functions, modules.
Must start with a letter.
May only use letters, digits and the underscore.
May not be longer than 31 characters.
myresults, my_results, res1, res_1 ! valid names
_myresults, 1res ! not valid names

Matthieu Marquillie Computer Programming using Fortran 90 9 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Program units and statement ordering:

Program units :
Main program : only one.
Procedures : subroutine and function.
Modules
Statement ordering :
Variables declarations.
Executable statement.
program test ! type of unit and his name
implicit none
! Declaration of variables :
integer(4) :: myresult,data1,data2
! executable statements
read(10,*)data1,data2
myresult=data1+data2
print*,myresults
end program test ! end the unit

Matthieu Marquillie Computer Programming using Fortran 90 10 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

First program : hello world

Source code :
program hello
implicit none
print*,’hello world’
end program hello

Open File and copy the source code :


xemacs hello.f90 &

Compile and execute :


gfortran hello.f90
./a.out

gfortran -o hello hello.f90


./hello

Matthieu Marquillie Computer Programming using Fortran 90 11 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Numerical representation :
Numeric storage :
Bit : value of 1 or 0, 8 Bits make up 1 Byte .
variables are always stored in a multiple of a Byte :
1, 2, 4, 8, 16 Bytes → 8, 16, 32, 64, 128 Bits
Integer :
If n is the number of Bits used for numeric storage of an integer, the range of
representation of a signed integer is : −2n−1 ≤ i ≤ 2n−1 − 1

Code begin Code end


program range_int ! initialize int1
implicit none int1=0
! declare 8 bits integer ! add 1 at each loop
integer(kind=1) :: int1 do i=1,300
! declare 32 bits integer int1=int1+1
integer(kind=4) :: i print*,int1
enddo
end program range_int

Matthieu Marquillie Computer Programming using Fortran 90 12 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Numerical representation :
32 bits real number :
Representation : 1.2 ∗ 10−38 ≤ |r | ≤ 3.4 ∗ 10+38
6 significant digits.
64 bits real number :
Representation : 2.2 ∗ 10−308 ≤ |r | ≤ 1.8 ∗ 10+308
15 significant digits.

32 bits 64 bits Precision


program real_test program real_test program real_prec
implicit none implicit none implicit none
integer(kind=4) :: i integer(kind=4) :: i integer(kind=4) :: i
real(kind=4) :: x real(kind=8) :: x real(kind=4) :: x
x=1. x=1. real(kind=8) :: y
do i=1,100 do i=1,500 x=1.+1.e-10 ; y=1.+1.e-10
x=x*10. x=x*10. print’(2es24.15)’,x,y
write(10,*)x write(10,*)x x=1.d0+1.d-10 ; y=1.d0+1.d-10
enddo enddo print’(2es24.15)’,x,y
end program real_test end program real_test end program real_prec
Matthieu Marquillie Computer Programming using Fortran 90 13 of 91
Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Intrinsic types :

Three broad class of object type :


character.
boolean.
numeric.

Six simple intrinsic types :


character
integer
real
logical
double precision
complex

Matthieu Marquillie Computer Programming using Fortran 90 14 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Declaration :
General form of a declaration :
type[, attributes list] :: names
type : integer, real, character, ...
attributes : parameter, dimension, ...
parameter : value of the variable cannot be modified.
real(4),parameter :: pi=3.14
pi=4. !-> this is not possible, the compiler will make an error

implicit none :
If not present, there is implicit typing :
Variable starting with letters i-n : integer
Variable starting with others letters : real(4)
implicit none change this rule.
impose declaration of every variable.
better error management by the compiler.
mandatory in all units : program, subroutine, function, modules.
first instruction to appear after the unit name.

Matthieu Marquillie Computer Programming using Fortran 90 15 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Numeric variable declaration :

Declaration
program declaration
implicit none
integer(kind=2) :: k,l ! 16 bits integer
integer(kind=4) :: i1,j1 ! 32 bits integer
integer(4) :: i2,j2 ! 32 bits integer
integer :: i3,j3 ! 32 bits integer
integer(kind=8) :: m1,n1 ! 64 bits integer
integer(8) :: m2,n2 ! 64 bits integer
real :: x1 ! 32 bits real
real(kind=4) :: x2 ! 32 bits real
real(4) :: x3 ! 32 bits real
double precision :: y1 ! 64 bits real
real(kind=8) :: y2 ! 64 bits real
real(8) :: y3 ! 64 bits real
end program declaration

Matthieu Marquillie Computer Programming using Fortran 90 16 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Character and boolean variable declaration :

Declaration
program declaration
implicit none
character(len=1) :: c1 ! 1 character variable
character(1) :: c2 ! 1 character variable
character :: c3 ! 1 character variable
character(len=10) :: c4 ! 10 characters variable
character(10) :: c5 ! 10 characters variable

logical :: b1 ! logical variable :


end program declaration

Matthieu Marquillie Computer Programming using Fortran 90 17 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Writing constants:
Integer real(4) real(8)
0 0. 0.d0
+1 1. 1.d0
1 +1. +1.d0
123 1.0 1.0d0
-26 3.1415 3.1415d0
31415e-4 31415d-4
1.5e-19 1.5d-19
.0001 .0001d0
-2.5 -2.5d0

logical character
.true. ’text’
.false. ’Writing this’
"writing that"

Matthieu Marquillie Computer Programming using Fortran 90 18 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Numeric operators :

Only apply to numeric type : integer and real.

Numeric operators Examples


Operator Operation 3+4
5/3
+ addition (binary operator) 5./3.
+ plus (unary operator) 3.*7.e-3
- substraction (binary operator) -4.5
- minus (unary operator) a+b*c
(a+b)*(c+d)
* multiplication x**y
/ division
** exponentiation

Matthieu Marquillie Computer Programming using Fortran 90 19 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Relationnal operators :

Apply to numeric and character type : integer, real and character.

Relationnal operators Examples


Operator Operation n >= 4
x < y
< less than (a+b*c) > (d/e)
<= less than or equal to (a+b)*(c+d) == e
== equal to (b**2-4*a*c)>0
/= not equal to
> greater than
>= greater than or equal to

== and /= have no real meaning for real-valued expression.

Matthieu Marquillie Computer Programming using Fortran 90 20 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Logical operators :

Apply only to boolean expression of type logical.

Logical operators Examples


Operator Operation a>b.and.c>d
.not.a
.not. logical negation (a==b).or.(c==d)
.and. logical conjunction
.or. logical inclusive disjunction
.eqv. logical equivalence
.neqv. logical nonequivalence

Matthieu Marquillie Computer Programming using Fortran 90 21 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Truth tables :
Unary operator
l .not.l
.true. .false.
.false. .true.

Binary operators
l1 l2 l1.and.l2 l1.or.l2 l1.eqv.l2 l1.neqv.l2
.true. .true. .true. .true. .true. .false.
.true. .false. .false. .true. .false. .true.
.false. .true. .false. .true. .false. .true.
.false. .false. .false. .false. .true. .false.

Matthieu Marquillie Computer Programming using Fortran 90 22 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Assignment and implicit conversion :


Assignment :
lhs = rhs
Character variable can only be assigned to another character variable.
An integer variable can be assigned to a real variable.
A real variable can be assigned to an integer variable, in this case the fractional part of
the real value is truncated.
Implicit conversion :
Apply in case of mixed numeric operation : real(4)-integer, real(4)-real(8), ...
There is always promotion to the ”highest” type.
Implied ordering : integer → real(4) → real(8)

Examples
real(8) :: a
a=1/2 ! 1 and 2 are integer -> integer division -> conversion to real(8) : a=0.d0
a=1./2 ! 1. real(4), 2 converted to real(4) -> real division -> conversion to real(8)
! a=0.5d0 but with precision problem.
a=1.d0/2.d0 ! 1.d0 and 2.d0 are real(8), real(8) division -> a=0.5d0

Matthieu Marquillie Computer Programming using Fortran 90 23 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Concatenation operator and substrings:

Concatenation Apply only to type character.


Logical operators Examples
Expression Interpretation ’good’//’ day’ -> ’good day’
c1 // c2 join two strings

Substrings :
Examples
character(10) :: c
c1=’abcdefghij’
print*,c(1:1) ! -> write ’a’ on screen
print*,c(3:6) ! -> write ’cdef’ on screen

Matthieu Marquillie Computer Programming using Fortran 90 24 of 91


Intro Basics Control Arrays Procedures I/O Syntax Representation Declarations Operators and expressions

Operator precedence :

Binary operators
Operator Precedence
** Highest
* and /
+ and -
//
<,<=,==,/=,>,>=
.not.
.and.
.or.
.eqv and .neqv Lowest

Use parenthesis to change precedence.

Matthieu Marquillie Computer Programming using Fortran 90 25 of 91


Intro Basics Control Arrays Procedures I/O Conditional Loops

Outline

1 Introduction

2 Fortran basics

3 Control constructs
Conditional constructs
Loops constructs

4 Arrays

5 Procedures

6 Input/Output

Matthieu Marquillie Computer Programming using Fortran 90 26 of 91


Intro Basics Control Arrays Procedures I/O Conditional Loops

IF statement :

Syntax
if (logical_expression) executable_statement

If logical_expression evaluates to .true. then executable_statement


is executed, otherwise not.
In this syntax, only one executable statement .

Examples
if (x>y) max=x
if (i==j .and. j/=k) l=i+j
if (a>=b .or. c<=d) min=a+c

Matthieu Marquillie Computer Programming using Fortran 90 27 of 91


Intro Basics Control Arrays Procedures I/O Conditional Loops

IF THEN ENDIF statement :


Syntax
if (logical_expression) then
executable_statement_1
executable_statement_2
.
executable_statement_n
endif

If logical_expression evaluates to .true. then


executable_statement_i are executed, otherwise not.

Example 1 Example 2
if (x>y) then if (i==j .and. j/=k) then
max=x l=i+j
endif m=i-j
endif

Matthieu Marquillie Computer Programming using Fortran 90 28 of 91


Intro Basics Control Arrays Procedures I/O Conditional Loops

IF THEN ELSE ENDIF statement :

Syntax Example 1
if (logical_expression) then if (x>y) then
executable_statements_1 max=x
else min=y
executable_statements_2 else
endif max=y
min=x
endif

If logical_expression evaluates to .true. then


executable_statements_1 are executed, otherwise
executable_statements_2 are executed.

Matthieu Marquillie Computer Programming using Fortran 90 29 of 91


Intro Basics Control Arrays Procedures I/O Conditional Loops

IF THEN ELSEIF ENDIF statement :

Syntax Example 1
if (logical_expression_1) then if (a>b .and. c>d) then
executable_statements_1 x=a+c
elseif (logical_expression_2) then elseif (a>b .and c<d) then
executable_statements_2 x=a+d
. elseif (a<b .and c>d) then
elseif (logical_expression_n) then x=b+c
executable_statements_n elseif (a<b .and c<d) then
endif x=b+d
endif

If logical_expression_i evaluates to .true. then


executable_statements_i are executed.

Matthieu Marquillie Computer Programming using Fortran 90 30 of 91


Intro Basics Control Arrays Procedures I/O Conditional Loops

IF THEN ELSEIF ELSE ENDIF statement :

Syntax Example 1
if (logical_expression_1) then if (a>b .and. c>d) then
executable_statements_1 x=a+c
elseif (logical_expression_2) then elseif (a<b .and c<d) then
executable_statements_2 x=b+d
. else
elseif (logical_expression_n) then x=0
executable_statements_n endif
else
executable_statements_default
endif

If logical_expression_i evaluates to .true. then


executable_statements_i are executed. If no logical_expression_i are
.true. then executable_statements_default is executed.

Matthieu Marquillie Computer Programming using Fortran 90 31 of 91


Intro Basics Control Arrays Procedures I/O Conditional Loops

DO loops :
Indexed DO loop Infinite DO loop
do var=expr1,expr2,[expr3] do
executable_statements executable_statements
enddo enddo

var : loop variable which must be an integer. Never change the value of the
control variable inside the loop .
expr1 : integer expression, initial value of var.
expr2 : integer expression, terminating value of var.
expr3 : integer expression, increment (step). expr3 is optional. If absent, it
is assumed to be equal to 1.
The number of iterations is evaluated before execution of the loop. If this is
zero or negative, the loop is not executed.
Infinite loop needs special instructions to become useful.

Matthieu Marquillie Computer Programming using Fortran 90 32 of 91


Intro Basics Control Arrays Procedures I/O Conditional Loops

Indexed DO loops :

Example 1 Example 2 Example 3


integer(4) :: i integer(4) :: i integer(4) :: i
do i=1,100,1 do i=1,100 do i=100,1,-1
! i=1,2,...,100 ! i=1,2,...,100 ! i=100,99,...,1
a=a+1. a=a+1. a=a+1.
enddo enddo enddo

Example 4 Example 5 Example 6


integer(4) :: i integer(4) :: i integer(4) :: i
do i=1,10,2 do i=10,1,-2 do i=1,10,-1
! i=1,3,5,7,9 ! i=10,8,6,4,2 ! loop not executed
a=a+1. a=a+1. a=a+1.
enddo enddo enddo

Matthieu Marquillie Computer Programming using Fortran 90 33 of 91


Intro Basics Control Arrays Procedures I/O Conditional Loops

DO loops with conditional exit and cycle :

Cycle Exit
do [var=expr1,expr2,[expr3]] do [var=expr1,expr2,[expr3]]
executable_statements_1 executable_statements_1
if (logical_expression) cycle if (logical_expression) exit
executable_statements_2 executable_statements_2
enddo enddo

Conditional exit and cycle can be used with infinite loop and indexed loop
If logical_expression is true, exit terminate the loop without executing
the following executable statements.
If logical_expression is true, cycle jump to the next iteration without
executing the following executable statements.
Infinite loop always need an exit instruction to terminate the loop.

Matthieu Marquillie Computer Programming using Fortran 90 34 of 91


Intro Basics Control Arrays Procedures I/O Conditional Loops

DO loops with conditional exit and cycle :

Example 1 Example 2
do do i=1,1000
a=a+1. a=a+1.
if ((a>10.).and.(a<30.)) cycle if ((a>10.).and.(a<30.)) cycle
! following statements not executed ! following statements not executed
! if 10<a<30, jump to next iteration ! if 10<a<30, jump to next iteration
if (a>100.) exit if (a>100.) exit
! exit loop when a>100 ! exit loop when a>100 or i>1000
b=b+a b=b+a
enddo enddo

Matthieu Marquillie Computer Programming using Fortran 90 35 of 91


Intro Basics Control Arrays Procedures I/O Declaration Terminology Manipulation Dynamic Random

Outline
1 Introduction

2 Fortran basics

3 Control constructs

4 Arrays
Declaration
Terminology
Array manipulation
Dynamic arrays
Random arrays

5 Procedures

6 Input/Output
Matthieu Marquillie Computer Programming using Fortran 90 36 of 91
Intro Basics Control Arrays Procedures I/O Declaration Terminology Manipulation Dynamic Random

Declaration of arrays :

Declaration syntax
type, dimension(expr_1,...,expr_n) :: array1,array2,...
type :: array1(expr_1,...,expr_n),array2(expr_1,...,expr_n),...

Arrays (or matrices) hold a collection of different values of the same type.
n ≤ 7, the maximum number of dimensions of an array is 7.
expr_i indicate the extent in the corresponding dimension.
There is two way of specifying expr_i :
An integer variable (literal or constant). In this case, the lower bound of the dimension
is 1.
An expression of the form cst1:cst2 with cst1 and cst2 integer variable (literals
or constants) following cst1 ≤ cst2.

Matthieu Marquillie Computer Programming using Fortran 90 37 of 91


Intro Basics Control Arrays Procedures I/O Declaration Terminology Manipulation Dynamic Random

Declaration of arrays :
Examples 1
real(4), dimension(100,100) :: r1,r2,r3,r4,r5,r6
real(4) :: s1(100,100),s2(100,100),s3(100,100),s4(100,100),s5(100,100),s6(100,100)

With several identical arrays, use the dimension keyword.

Examples 2
real(8), dimension(100,100) :: r1
real(8), dimension(100,50) :: r2
real(8), dimension(50,100) :: r3
real(8), dimension(50,50) :: r4
real(8), dimension(25,100) :: r5
real(8), dimension(100,25) :: r6
real(8) :: s1(100,100),s2(100,50),s3(50,100),s4(50,50),s5(25,100),s6(100,25)

With several different arrays, use the direct declaration.

Matthieu Marquillie Computer Programming using Fortran 90 38 of 91


Intro Basics Control Arrays Procedures I/O Declaration Terminology Manipulation Dynamic Random

Declaration of arrays :
Examples 3
Lower bound examples : integer(4) :: r1(1:10,1:10),r2(10,10)
integer(4) :: s1(-10:1,-5:5),s2(-20:-10)

Examples 4
character(10),dimension(10,10) :: r1,r2
All intrinsic types can be defined as
logical :: s1(15,5),s2(-10,10)
arrays : real(4) :: t1(20,2)
real(8) :: t2(100)
integer(4) :: u1(100,100,100)

When using integer variables for Examples 5


defining dimensions, define the integer(4),parameter :: n1=10,n2=6
integer variable before the array and real(4) :: r1(n1),r2(-n1/2:n1/2)
always use the parameter keyword : integer(4) :: s1(1+n1*n1,n2*2)

Matthieu Marquillie Computer Programming using Fortran 90 39 of 91


Intro Basics Control Arrays Procedures I/O Declaration Terminology Manipulation Dynamic Random

Array terminology :

Definition :
rank : number of dimensions.
bounds : upper and lower limits of indices.
extent : number of elements in dimension;
size : total number of elements.
shape : rank and extents;
conformable : same shape.

Conformance :
A scalar conforms to an array of any shape with the same value for every element.
Arrays used in the same expression must conform in their shape.

Matthieu Marquillie Computer Programming using Fortran 90 40 of 91


Intro Basics Control Arrays Procedures I/O Declaration Terminology Manipulation Dynamic Random

Array terminology :

Example
real(4), dimension(15) :: x
real(4), dimension(1:5,1:3) :: y,z

Rank of x is 1; rank of y and z is 2.


Bounds of x are 1 and 15; Bound of y and z are 1 and 5 and 1 and 3.
Extent of x is 15; extents of y and z are 5 and 3.
Size of x, y and z is 15.
Shape of x is 15; shape of y and z is 5,3.
y and z are conformable.

Matthieu Marquillie Computer Programming using Fortran 90 41 of 91


Intro Basics Control Arrays Procedures I/O Declaration Terminology Manipulation Dynamic Random

Array element ordering :

Arrays elements in memory are ordered in column-major order.


The subscript of the lowest dimensions vary first.

Example
Declaration :
real(4) :: x(3,2,3)

Order in memory :
x(1,1,1), x(2,1,1), x(3,1,1), x(1,2,1), x(2,2,1), x(3,2,1),
x(1,1,2), x(2,1,2), x(3,1,2), x(1,2,2), x(2,2,2), x(3,2,2),
x(1,1,3), x(2,1,3), x(3,1,3), x(1,2,3), x(2,2,3), x(3,2,3)

Knowing array ordering in memory is important in two situations :


Passing arrays are arguments in subroutines and functions.
Writing arrays in files and at the screen.

Matthieu Marquillie Computer Programming using Fortran 90 42 of 91


Intro Basics Control Arrays Procedures I/O Declaration Terminology Manipulation Dynamic Random

Array manipulation : Elements by elements


Examples 1 :
real(4) :: a(15),b(-4:0,0:2),c(5,3),d(0:4,0:2)
a(1)=0. ! sets element a(1) to zero
b(0,0)=a(3)+c(5,3) ! sets an element of b to the sum of two other elements

Examples 2 :
integer(4) :: i,j
real(4) :: a(15),b(-4:0,0:2),c(5,3),d(0:4,0:2)
do i=1,15
a(i)=0. ! sets all elements of a to zero
enddo
do j=1,3
do i=1,5
b(i-5,j-1)=c(i,j) ! sets all element of b to elements of c
enddo
enddo

Matthieu Marquillie Computer Programming using Fortran 90 43 of 91


Intro Basics Control Arrays Procedures I/O Declaration Terminology Manipulation Dynamic Random

Array manipulation : Whole arrays

Examples 1 :
real(4) :: a(15),b(-4:0,0:2),c(5,3),d(0:4,0:2)
a=0. ! sets whole array a to zero
b=c+d ! adds c and d then assigns result to b
b=sinc(c)+cos(d) ! functions are applied element by element

Examples 2 :
real(4) :: a(15),b(-4:0,0:2),c(5,3),d(0:4,0:2)
b=c*d-b**2 ! this is equivalent to concurrent execution of :
! b(-4,0) = c(1,1)*d(0,0)-b(-4,0)**2
! b(-3,0) = c(2,1)*d(1,0)-b(-3,0)**2
! ...
! b(-4,1) = c(1,2)*d(0,1)-b(-4,1)**2
! ...
! b(0,2) = c(5,3)*d(4,2)-b(0,2)**2

Matthieu Marquillie Computer Programming using Fortran 90 44 of 91


Intro Basics Control Arrays Procedures I/O Declaration Terminology Manipulation Dynamic Random

Array manipulation : Arrays sections

Sub-arrays are specified by subscript-triplets : bound1:bound2:stride


This is equivalent to a pseudo-loop.
The section start at bound1 and ends at or before bound2. stride is the increment
by which the locations are selected.
bound1, bound2 and stride are integer expressions.
An array section is also an array.

Examples 1 :
real(4) :: a(15),b(-4:0,0:2),c(5,3),d(0:4,0:2)
a(2:4)=0. ! sets a(2), a(3) and a(4) to zero
b(-1:0,1:2)=c(1:2,2:3)+1. ! adds one to the subsection of c and assigns
! to the subsection of b

Matthieu Marquillie Computer Programming using Fortran 90 45 of 91


Intro Basics Control Arrays Procedures I/O Declaration Terminology Manipulation Dynamic Random

Array manipulation : Arrays sections

Examples 2 :
a(:) ! the whole array
a(3:9) ! a(3) to a(9) in steps of 1
a(3:9:1) ! as above
a(m:n) ! a(m) to a(n)
a(m:n:k) ! a(m) to a(n) in steps of k
a(8:3:-1) ! a(8) to a(3) in steps of -1
a(8:3) ! a(8) to a(3) step 1 => zero size
a(m:) ! from a(m) to default upper bound
a(:n) ! from default lower bound to a(n)
a(::2) ! from default lower bound to upper bound, steps of 2
a(m:m) ! 1 element section (not a scalar!)
a(m) ! scalar element - not a section

Matthieu Marquillie Computer Programming using Fortran 90 46 of 91


Intro Basics Control Arrays Procedures I/O Declaration Terminology Manipulation Dynamic Random

An array expression is evaluated before being assigned


Code 1 : Code 2 : Code 3 :
integer(4) :: i,x(4) integer(4) :: i,x(4) integer(4) :: i,x(4),tmp(4)
do i=1,4 do i=1,4 do i=1,4
x(i)=i x(i)=i x(i)=i
enddo enddo enddo
print*,x print*,x print*,x
x(:)=x(4:1:-1) do i=1,4 do i=1,4
print*,x x(i)=x(5-i) tmp(i)=x(i)
enddo enddo
print*,x do i=1,4
x(i)=tmp(5-i)
enddo
print*,x

Code 1 output : Code 2 output : Code 3 output :


1 2 3 4 1 2 3 4 1 2 3 4
4 3 2 1 4 3 3 4 4 3 2 1

Matthieu Marquillie Computer Programming using Fortran 90 47 of 91


Intro Basics Control Arrays Procedures I/O Declaration Terminology Manipulation Dynamic Random

Array manipulation : conformance


Example :
real(4) :: x(6,8)

1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
x(1:3,1:4) x(2:6:2,1:7:3) x(2:5,7), x(2:5,7:7) x(1:6:2,1:8:2)

x(1:3,1:4)=1.0 are valid.


x(1:3,1:4)=x(1:6:2,1:8:2)
x(2:6:2,1:7:3)=x(1:3,1:4) and x(2:6:2,1:7:3)=x(2:5,7) are not.
x(2:5,7) is a 1D section.
x(2:5,7:7) is a 2D section.

Matthieu Marquillie Computer Programming using Fortran 90 48 of 91


Intro Basics Control Arrays Procedures I/O Declaration Terminology Manipulation Dynamic Random

Dynamic arrays :
Arrays can be allocated dynamically :
Use the allocatable attribute.
Rank is fixed.

Declaration : Allocation 2 :
integer(4) :: n1,n2,n3,ierr read*,n2,n3
integer(4), allocatable :: t(:) allocate(x(n2,n3),stat=ierr)
real(4), allocatable :: x(:,:) if (ierr/=0) then
print*,’array t : allocation error’
stop
endif

Allocation 1 : Deallocation :
read*,n1 deallocate(t)
allocate(t(n1)) deallocate(x)

Matthieu Marquillie Computer Programming using Fortran 90 49 of 91


Intro Basics Control Arrays Procedures I/O Declaration Terminology Manipulation Dynamic Random

Random arrays:

random_number subroutine will return a scalar (or array of) pseudorandom


number in the range 0 ≤ x ≤ 1:

example 1 : example 2 :
real(4) :: x(2,2) real(4) :: x(2,2)
! real random numbers 0 < x < 1 ! real random numbers 0 < x < 10
call random_number(x) call random_number(x)
x=x*10.
example 3 : example 4 :
real(4) :: x(2,2) real(4) :: x(2,2)
integer :: t(2,2) integer :: t(2,2)
! integer random numbers 0 < x < 10 ! integer random numbers -5 < x < 5
call random_number(x) call random_number(x)
t=int(x*10.1) x=int(x*10.1)-5

Matthieu Marquillie Computer Programming using Fortran 90 50 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Outline
1 Introduction

2 Fortran basics

3 Control constructs

4 Arrays

5 Procedures
Subroutine
Function
Arguments
Function or Subroutine ?
Intrinsics subroutine and function

6 Input/Output
Matthieu Marquillie Computer Programming using Fortran 90 51 of 91
Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Program Units

Two main program units :

main PROGRAM : only one and where execution begin.


MODULE : can contain procedures and declarations.

Two types of procedures :

SUBROUTINE is a parameterised named sequence of code which performs one or more


specific tasks and can be invoked from within other program units.
FUNCTION as a subroutine but returns a result in the function name (of any
specified type and kind).

Matthieu Marquillie Computer Programming using Fortran 90 52 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Subroutine example

Main program Subroutine


program example subroutine print_list(list_size,list)
implicit none implicit none
integer,parameter :: n=10 integer,intent(in) :: list_size
real(4) :: a(n) real(4),intent(in) :: list(list_size)
.... integer :: i
call print_list(n,a)
.... do i=1,list_size
end program example print’(1es17.8)’,list(i)
enddo
n and a : actual arguments
transmitted to the subroutine. end subroutine print_list

list_size and size : dummy arguments


corresponding to the transmitted arguments.
i : local variable.

Matthieu Marquillie Computer Programming using Fortran 90 53 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Subroutine specifications

A subroutine is used with the instruction call followed by the name of the
subroutine with the list of arguments inside parenthesis.
n and a are the actual arguments, list_size and list are the dummy
arguments.
In the subroutine, only variables from the calling unit transmitted by
arguments are knows (here variables n and a).
dummy arguments have the same type as there actual arguments.
You can declare internal variables inside subroutines (here variable i).
In Fortran, arguments are passed by reference (In C, they are passed by value).

Matthieu Marquillie Computer Programming using Fortran 90 54 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Function example

Main program Function


program example function negative(value)
implicit none implicit none
real(4) :: x,y,negative real(4) :: negative
.... real(4),intent(in) :: value
y=negative(x)
.... negative=-value
end program example
end function negative
x : actual arguments transmitted to
the subroutine. value : dummy argument corresponding
negative : return a value → has a to the transmitted argument.
type and is declared. negative : asign return value of the
function → has a type, is declared.

Matthieu Marquillie Computer Programming using Fortran 90 55 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Function specifications

A function return a value, so it is used inside an instruction.


The name of the function has to be declared inside the function and in the
calling unit.
x is the actual arguments, value is the dummy arguments.
In the function, only variables from the calling unit transmitted by arguments
are knows (here variable X).
dummy arguments have the same type as there actual arguments.
You can declare local variables inside functions.
In Fortran, arguments are passed by reference (In C, they are passed by value).

Matthieu Marquillie Computer Programming using Fortran 90 56 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Arguments checking and local objects

Arguments checking with INTENT attribute :


only be referenced : INTENT(IN)
only be assigned : INTENT(OUT)
be referenced and assigned to : INTENT(INOUT)
The use of INTENT attributes is recommended as it allows good compilers to check for
coding errors, and facilitates efficient compilation and optimisation.

Local objects :
are created each time the procedure is invoked.
are destroyed when the procedure completes.
do not retain their values between calls.
do not exist in the program’s memory between calls.

Matthieu Marquillie Computer Programming using Fortran 90 57 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Array argument

Main program Subroutine


program example subroutine print_list(list_size,list)
implicit none implicit none
integer,parameter :: n=10 integer,intent(in) :: list_size
real(4) :: a(n) real(4),intent(in) :: list(list_size)
... integer :: i
call print_list(n,a) do i=1,list_size
.... print’(1es17.8)’,list(i)
end program example enddo
end subroutine print_list

Array elements equivalence


list(1)=a(1),list(2)=a(2),...,list(10)=a(10)

Matthieu Marquillie Computer Programming using Fortran 90 58 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Array argument

Main program Subroutine


program example subroutine print_list(list_size,list)
implicit none implicit none
integer,parameter :: n=10 integer,intent(in) :: list_size
real(4) :: a(n) real(4),intent(in) :: list(list_size)
... integer :: i
call print_list(5,a(5)) do i=1,list_size
.... print’(1es17.8)’,list(i)
end program example enddo
end subroutine print_list

Array elements equivalence


list(1)=a(5),list(2)=a(6),...,list(5)=a(10)

Matthieu Marquillie Computer Programming using Fortran 90 59 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Array argument

Main program Subroutine


program example subroutine print_list(list_size,list)
implicit none implicit none
integer,parameter :: n=10 integer,intent(in) :: list_size
real(4) :: a(n,n) real(4),intent(in) :: list(list_size)
... integer :: i
call print_list(n,a(1,3)) do i=1,list_size
.... print’(1es17.8)’,list(i)
end program example enddo
end subroutine print_list

Array elements equivalence


list(1)=a(1,3),list(2)=a(2,3),...,list(10)=a(10,3)

Matthieu Marquillie Computer Programming using Fortran 90 60 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Function or subroutine ?

Functions should only have dummy arguments with INTENT(IN) attributes.


Functions should not perform operation on external files.
Functions should not contains a STOP statement.
If it is necessary for a procedure to include any of the above limitation : write
a subroutine !

Matthieu Marquillie Computer Programming using Fortran 90 61 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Array intrinsics

function dot_product(vec1,vec2) : inner (dot) product of 2 rank 1 arrays.


function matmul(mat1,mat2) : matrix-matrix multiplication.
If mat1 has shape (n, m) and mat2 has shape (m, k), the resulting matrix has
shape (n, k).
function minloc(mat) : location of a minimum value in a array.
function maxloc(mat) : location of a maximum value in a array.
function minval(mat) : minimum value in a array.
function maxval(mat) : maximum value in a array.
function product(mat) : product of the array elements.
function sum(mat) : sum of the array elements.
function transpose(mat) : transpose an array of rank two.

Matthieu Marquillie Computer Programming using Fortran 90 62 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Intrinsics

function int(x) : conversion to integer, real part truncated.


function nint(x) : return the nearest integer.
function real(i,4) : convert an integer to a real(4).
function real(i,8) : convert an integer to a real(8).
function abs(x) : return the absolute value of x.

function mod(a,p) : returns the value a-p*int(a/p) if p 6= 0


Practical use of mod function
p=0.
do i=1,10000
p=p+1
if (mod(i,100)==0) print*,p ! print p every 100 iterations
enddo

Matthieu Marquillie Computer Programming using Fortran 90 63 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Intrinsics

function sqrt(x) : square root of x.


function exp(x) : e x of x.
function log(x) : returns loge (x).
function log10(x) : returns log10 (x).
functions sin(x) and cos(x) : sine and cosine x.
functions asin(x) and acos(x) : arcsine and arcosine of x.
functions tan(x) and atan(x) : tangent and inverse tangent x.
function sinh(x) : hyperbolic sine of x.
function cosh(x) : hyperbolic cosine of x.
function tanh(x) : hyperbolic tangent of x.

Matthieu Marquillie Computer Programming using Fortran 90 64 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Module : example
Main program : example.f90 Module myio.f90
program example module my_io
use my_io
implicit none contains
integer,parameter :: n=10
real(4) :: a(n) subroutine print_list(list_size,list)
.... implicit none
call print_list(n,a) integer,intent(in) :: list_size
.... real(4),intent(in) :: list(list_size)
end program example integer :: i

do i=1,list_size
print’(1es17.8)’,list(i)
enddo

end subroutine print_list


end module my_io

Matthieu Marquillie Computer Programming using Fortran 90 65 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Modules :

Procedures in a module can be use in any program unit if the corresponding


use statement is used.
A module used in another unit must be compiled before this unit :
gfortran myio.f90 example.f90
Arguments of procedures when contained inside a module are checked at the
compilation.
Modules is the new way of having global variables (COMMON in fortran 77).

Matthieu Marquillie Computer Programming using Fortran 90 66 of 91


Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Module : global variable


Main program : example.f90 Module myio.f90
program example module my_data
use my_data integer :: index=0
implicit none contains
integer,parameter :: n=10 subroutine increment_index()
implicit none
do i=1,n index=index+1
call increment_index() end subroutine print_list
enddo end module my_data

print*,index
end program example

Try to never use global variables !


Matthieu Marquillie Computer Programming using Fortran 90 67 of 91
Intro Basics Control Arrays Procedures I/O Subroutine Function Arguments Function or Subroutine ? Intrinsics

Timing in fortran 90

cpu time system clock


real(8) :: t1,t2,time integer(8) :: t1,t2,irate
real(8) :: time
call cpu_time(t1)
do i=1,n call system_clock(t1,irate)
call compute(...) do i=1,n
enddo call compute(...)
call cpu_time(t2) enddo
time=t2-t1 call system_clock(t2,irate)
time=real(t2-t1)/real(irate)

Both gives the time in seconds.


cpu_time gives the time consumed by the CPU : doesn’t work in OpenMP.
system_clock gives the time elapsed : work in OpenMP.

Matthieu Marquillie Computer Programming using Fortran 90 68 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Outline

1 Introduction

2 Fortran basics

3 Control constructs

4 Arrays

5 Procedures

6 Input/Output
Introduction
Sequential access files
Direct access files
Format
Matthieu Marquillie Computer Programming using Fortran 90 69 of 91
Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Files access and type


File access :
Sequential access :
Records are processed “sequentially”, one after the other.
Slow to access information anywhere in the file.
No constraints on the size of records.
Direct access :
Records are accessed directly.
Fast to access information anywhere in a file.
Constraints on the size of records.
File type :
Formatted files :
Information written with characters.
Portable, readable with other programs.
Much bigger files compare to binary and slower to process.
Non-formatted (binary) files :
Information written in binary format.
Not always portable (depends on architecture), only readable with a code.
Much smaller files compare to formatted and faster to process.

Matthieu Marquillie Computer Programming using Fortran 90 70 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

OPEN and CLOSE instructions

OPEN :
open(unit=10,file=’file_name_1’,access=’sequential’,form=’formatted’)
open(unit=11,file=’file_name_2’,access=’direct’,form=’unformatted’,recl=32)
unit= :
Connect one file to one unit number (used in read/write statements).
Only use number ≥ 10
file= : name of the file (character variable).
access= : access type → sequential (default) or direct.
form= :
formatted (default for a sequential file).
unformatted (default for a direct access file).
recl= : length of record for direct access size (generally in Byte, but not always !)
CLOSE :
close(unit=10)

Matthieu Marquillie Computer Programming using Fortran 90 71 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Sequential formatted files


OPEN : These three statements are equivalent :
open(unit=10,file=’file_name_1’,access=’sequential’,form=’formatted’)
open(unit=10,file=’file_name_1’)
open(10,file=’file_name1’)

READ : read(<unit number>,<format>)<variables>


read(10,*)i,j,x,y
read(10,’(2i6,2es17.8)’)i,j,x,y

WRITE : write(<unit number>,<format>)<variables>


write(10,*)i,j,x,y
write(10,’(2i6,2es17.8)’)i,j,x,y

CLOSE : close(<unit number>)


close(10)

Each write or read statement is followed by a new line .

Matthieu Marquillie Computer Programming using Fortran 90 72 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Sequential unformatted files


OPEN : These two statements are equivalent :
open(unit=10,file=’file_name_1’,access=’sequential’,form=’unformatted’)
open(unit=10,file=’file_name_1,form=’unformatted’)

READ : read(<unit number>)<variables>


read(10)i,j,x,y

WRITE : write(<unit number>)<variables>


write(10)i,j,x,y

CLOSE : close(<unit number>)


close(10)

Each write or read statement write control words enclosing the data.
Sequential unformatted files are difficult to read with other programming language (C for
example). If you need to write binary data in Fortran and read the data in another
programming language use direct access unformatted files.
Matthieu Marquillie Computer Programming using Fortran 90 73 of 91
Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Direct access unformatted files


OPEN : These two statements are equivalent :
open(unit=10,file=’file_name_1’,access=’direct’,form=’unformatted’,recl=16)
open(unit=10,file=’file_name_1,access=’direct’,recl=16)

READ : read(<unit number>,<record number>)<variables>


read(10,rec=1)i,j,x,y
read(10,rec=10)i,j,x,y

WRITE : write(<unit number>,<record number>)<variables>


write(10,rec=1)i,j,x,y
write(10,rec=10)i,j,x,y

CLOSE : close(<unit number>)


close(10)

recl : size in byte (not always, depend of compiler) of one record.


rec= in read and write statement → record number.
Matthieu Marquillie Computer Programming using Fortran 90 74 of 91
Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Direct access unformatted files

Example 1 :
integer :: i,j,l
real(8) :: x,y
open(10,file=’test.dat’,access=’direct’,recl=2*4+2*8 )
do l=1,10
call compute_routine(i,j,x,y)
write(10,rec=l )i,j,x,y
enddo
close(10)

2 integer (4 bytes) + 2 real(8) (8 bytes) → recl=2*4+2*8


For each loop iteration, we write a new record in the file.
10 records of 24 bytes → size of file : 240 bytes

Matthieu Marquillie Computer Programming using Fortran 90 75 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Direct access unformatted files

Example 2 :
integer,parameter :: nx=128,ny=97
real(8) :: x(nx),y(ny),u(nx,ny,3)
open(10,file=’test.dat’,access=’direct’,recl=2*4+(nx+ny+nx*ny*3)*8 )
write(10,rec=1 )nx,ny,x,y,u
close(10)

File with only one big record → use this instead of unformatted sequential file when data
has to be read with other language.

Matthieu Marquillie Computer Programming using Fortran 90 76 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Direct access unformatted files

Example 3 : How to read previous file when you don’t know nx and ny.
integer:: nx,ny
real(8),allocatable :: x(:),y(:),u(:,:,:)
open(10,file=’test.dat’,access=’direct’,recl=2*4 )
read(10,rec=1)nx,ny
close(10)
allocate(x(nx),y(ny),u(nx,ny,3))
open(10,file=’test.dat’,access=’direct’,recl=2*4+(nx+ny+nx*ny*3)*8 )
read(10,rec=1)nx,ny,x,y,u
close(10)
First read dimensions.
Then read full set of data.

Matthieu Marquillie Computer Programming using Fortran 90 77 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Format specifications

Files output :
read(<unit number>,<format>)<variables>
write(<unit number>,<format>)<variables>

Screen output
read <format>,<variables>
print <format>,<variables>

Format : character string


<format> : ’(code1,code2,...)’

Matthieu Marquillie Computer Programming using Fortran 90 78 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Integer format

Iw[.d] : write INTEGER with w characters. If d is present, tells the compiler


how many characters should be written, padding with zeros at the beginning
of the number.

Code Output
integer :: i,j,k -12517561791
i=-125 ^-125^^1756^^1791
j=1756 -00125001756001791
k=1791
write(10,’(i4,i4,i4)’)i,j,k
write(10,’(i5,i6,i6)’)i,j,k
write(10,’(i6.5,i6.6,i6.6)’)i,j,k

Matthieu Marquillie Computer Programming using Fortran 90 79 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Real format 1

Fw.d : write REAL with w characters including the decimal point and the sign,
d corresponding to the number of characters for the fractional part.
w ≥ d+2

Code Output
real :: x,y,z 3.14159^-15.137^799.4732
x=3.14159 ^^3.14^-15.1370^799.74329
y=-15.137
z=799.74328
write(10,’(f7.5,f8.3,f9.4)’)x,y,z
write(10,’(f6.2,f9.4,f10.5)’)x,y,z

Matthieu Marquillie Computer Programming using Fortran 90 80 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Real format 2

Ew.d and ESw.d : write REAL in exponential notation with w characters,


including the decimal point, the sign and the characters needed for the
exponent, d corresponding to the number of characters for the fractional part.
w ≥ d+6

Code Output
real :: x,y,z 0.314159E+01^-0.15137E+02
x=3.14159 ^0.79974323E+03
y=-15.137 3.141590E+00^-1.51370E+01
z=799.7432 ^7.99743225E+02
write(10,’(e12.6,e13.5)’)x,y
write(10,’(e15.8)’)z
write(10,’(es12.6,es13.5)’)x,y
write(10,’(es15.8)’)z

Matthieu Marquillie Computer Programming using Fortran 90 81 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Character format

A[w] : write characters string. w is optionnal, gives the length if indicated.


If w is longer than the string, it will be padded by blanks on the left
If w is shorter than the string, only left characters will be written.
If w is missing, the output length will be the length of the string.

Code Output
character(len=9) :: c ^^^beethoven
c=’beethoven’ beetho
write(10,’(a12)’)c beethoven
write(10,’(a6)’)c
write(10,’(a)’)c

Matthieu Marquillie Computer Programming using Fortran 90 82 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Format control

nX : space of n characters.
Code Output
real :: x,y,z 0.314159E+01^^^^^-0.15137E+02
x=3.14159 ; y=-15.137
write(10,’(e12.6,4X,e13.5)’)x,y

/ : go to newline
Code Output
real :: x,y,z 0.314159E+01
x=3.14159 ; y=-15.137 ^-0.15137E+02
write(10,’(e12.6,/,e13.5)’)x,y

Matthieu Marquillie Computer Programming using Fortran 90 83 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Format repetition

Repetition factor :
Code Output
integer :: i,j,k ^-125^1756^1791
i=-125 ; j=1756 ; k=1791 ^-125^1756^1791
write(10,’(i5,i5,i5)’)i,j,k ^-125^^^1756^^^1791^^
write(10,’(3i5)’)i,j,k
write(10,’(3(i5,2X))’)i,j,k

Matthieu Marquillie Computer Programming using Fortran 90 84 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

List directed formattting

* : instead of format specification.


The compiler select the format.
Always use this for reading formatted data.
When writing for debugging purpose or small information, using list directed
formatting is fast.
When writing data, it is better to specify the format to be sure to have always
the same output.

Matthieu Marquillie Computer Programming using Fortran 90 85 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Format scanning
The number of variables is less than the number of edit descriptors :
All unused edit descriptors are simply ignored.
Code Output
integer :: i,j,k ^-125^1756^1791
i=-125 ; j=1756 ; k=1791
write(10,’(6i5)’)i,j,k

The number of variables is greater than the number of edit descriptors :


Fortran will reuse the format until all variables are printed.
Code Output
integer :: i,j,k,l ^-125^1756
i=-125 ; j=1756 ; k=1791 ; l=23 ^1791^^^23
write(10,’(2i5)’)i,j,k,l

Matthieu Marquillie Computer Programming using Fortran 90 86 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Format scanning

Each time Fortran rescan the format, the following variables are written on a
new line.
Without grouping (parenthesis) Fortran rescan the format from the very
beginning.
With grouping (parenthesis) Fortran rescan the format starting with the
right-most left parenthesis (including its repetition factor).

Examples Examples
’( I6, 10X,I5, 3F10.2 )’ ’( F6.2, (2F4.1,2X,I4, 4(I7,F7.2)) )’
|------------------- |--------------------------
’( I6, 10X,I5, (3F10.2) )’ ’( F6.2, 2(2F4.1,2X,I4), 4(I7,F7.2) )’
|-------- |----------
’( I6,(10X,I5), 3F10.2 )’ ’( F6.2,(2(2F4.1,2X,I4), 4(I7,F7.2)) )’
|---------------- |-----------------------------

Matthieu Marquillie Computer Programming using Fortran 90 87 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Implicit do loops
Implicit do loop can only be used on input/output statements.
Loop variable and parameters are integer variable and can be constants or
constant expressions.
Implicit loop are enclosed in parenthesis, inner parenthesis are executed first.

Examples 1D Examples 2D
integer, parameter :: n=20 integer, parameter :: n1=20,n2=10
integer :: i integer :: i,j
real(8) :: x(n) real(8) :: x(n1,n2)

! write x(1),x(2),...,x(n) ! write x(1,1),x(2,1),...,x(n1,1),...,x(n1,n2)


write(10,*)(x(i),i=1,n) write(10,*)((x(i,j),i=1,n1),j=1,n2)

! write x(n),x(n-1),...,x(1) ! write x(1,1),x(1,2),...,x(1,n2),...,x(n1,n2)


write(10,*)(x(i),i=n,1,-1) write(10,*)((x(i,j),j=1,n2),i=1,n1)

Matthieu Marquillie Computer Programming using Fortran 90 88 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Formatted array writing example


Code Output
integer, parameter :: n1=4,n2=3 x(1,1)
integer :: i,j ..
real(8) :: x(n1,n2) .
do j=1,n2 x(n1,1)
do i=1,n1 x(1,2)
write(10,’(10es17.8)’)x(i,j) ..
.
enddo x(n1,n2)
enddo
Code Output
integer, parameter :: n1=4,n2=3 x(1,1)
integer :: i,j ..
real(8) :: x(n1,n2) .
do i=1,n1 x(1,n2)
do j=1,n2 x(2,1)
write(10,’(10es17.8)’)x(i,j) ..
.
enddo x(n1,n2)
enddo
Matthieu Marquillie Computer Programming using Fortran 90 89 of 91
Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Formatted array writing example

Code Output
integer, parameter :: n1=4,n2=3 x(1,1) x(2,1) x(3,1) x(4,1)
integer :: i,j
real(8) :: x(n1,n2) x(1,2) x(2,2) x(3,2) x(4,2)
x(1,3) x(2,3) x(3,3) x(4,3)
do j=1,n2
write(10,’(10es17.8)’)(x(i,j),i=1,n1)
enddo

write(10,’(4es17.8)’)((x(i,j),i=1,n1),j=1,n2)

write(10,’(4es17.8)’)x

Matthieu Marquillie Computer Programming using Fortran 90 90 of 91


Intro Basics Control Arrays Procedures I/O Intro Sequential Direct Format

Formatted array writing example

Code Output
integer, parameter :: n1=4,n2=3 x(1,1) x(1,2) x(1,3)
integer :: i,j
real(8) :: x(n1,n2) x(2,1) x(2,2) x(2,3)
x(3,1) x(2,2) x(3,3)
do i=1,n1 x(4,1) x(2,2) x(4,3)
write(10,’(10es17.8)’)(x(i,j),j=1,n2)
enddo

write(10,’(3es17.8)’)((x(i,j),j=1,n2),i=1,n1)

Matthieu Marquillie Computer Programming using Fortran 90 91 of 91

You might also like