1 Summary BIL 106E Introduction to Scientific & Engineering Computing.
-
date post
21-Dec-2015 -
Category
Documents
-
view
215 -
download
2
Transcript of 1 Summary BIL 106E Introduction to Scientific & Engineering Computing.
1
Summary
BIL 106E
Introduction to Scientific & Engineering
Computing
2
Course Contentents Introduction to computing Basic F Selective execuation Repetitive execuation Input/output Programming with functions Arrays, Data types, Files Pointers and linked structures
3
The F language
F & Fortran 90
FFortran 77
Fortran 90
Easy to learn to implement to understand
Powerful enough for use in large programs
4
2.1 Data types
There are five basic data types in fortran 1) INTEGER 2) REAL 3) COMPLEX 4) CHARACTER 5) LOGICAL
Numerical-data types
Strings of characters
Logical data values
Non-numericaldata types
5
Arithmetic operators in F
Operator Meaning+ Addition- Substraction* Multiplication/ Division** Exponentiation (or ‘rising the power of’)
6
Arithmetic operator priorities
Operator Priority** High* and / Medium+ and - Low
Examples: W=c/d*b
Total=2**3+5*2=18 W=x+z-y
7
Names & Declarations
A data object is a constant that never changes or a variable that can change during program execution.
Data object may have names. For example, Average, X, Y, Einstein, or Potential_Energy.
Names in a program must conform to 3 rules:1) A name may contain up to 31 letters, digits, and underscore
characters2) The first character of a name must be a letter3) Imbedded blank characters are not permitted in a name
IMPORTANT: keywords such as program, write, and end are not actually names
8
Type Declarations
implicit noneinteger :: Counts, Loop_Indexreal :: Current, Resistance, Voltage
Names defined as part of the F language, including keywords and intrinsic function names (such as sin, tan, abs, etc.), must be written in lower case. Names that you invent can use any combination of upper and lower case, but each name must be written consistently.
9
Type properties: Kind & Length
Kind : A variable of any numerical type has a kind type parameter, which designates a subtype or variant of the type.
Each type has a default computer representation For each numerical data type, F defines a set of integers to be used
as kind type parameter values (i.e., the number 4 for real representation, number 8 for the higher-precision variant)
Length : A variable of character data type has a string length property.
A character type declaration must specify string length
A type declaration appears in parentheses after the type name. If no
kind parameter is specified, F selects the default computer representa-
tion Type name (Type properties) :: List of names
10
Constants The name of a constant looks like the name of a
variable and it must be listed in the type declaration The keyword parameter designates a named constant Houdini Principle: Don’t use magic numbers
use a named constant rather than a explicit constant give always explanations ( use !)
11
Declaration for a Named Constant
Declaration of a named constant is as follows: Type name, parameter :: List of initializationswhere each list item has the form Name = Value definitionThe value definition is an explicit constant.Examples: integer, parameter :: LENGTH=12 real, parameter :: PLANK=6.6260755e-34, PI=3.141593 real, parameter :: GRAVITY=9.807,
AVAGADRO=6.0221367e23, & twoPI=2.0*PI integer, parameter :: A=20, HIGH=30, NEON=67 character (Len=2), parameter :: units=”Cm”
ATTENTION: Continuation line with ampersand symbol.
12
Simple Input & Output
Read (unit = *, fmt = *) Input List Write (unit = *, fmt = *) Output List
An asterisk as the unit in a read or write control list designates the default input device (the keyboard) or the default output device (The terminal screen)
An asterisk as the format designates list-directed formatting. Input data values for on-line list-directed input are entered at the computer keyboard in free form. Consecutive values must be separated by blanks.
For example: read (unit = *, fmt = *) Radii, I, Current, Top can be entered as 9.75 10 15.32 765.3
13
Mixed-mode assignment
Assume that, b is a real variable whose value is 100.0, while c and d are
integers having the values 9 and 10, respectively. a = b*c/d result is 90.0 a = c/d*b a gets 0 value.
This phenomenon is known as integer division
14
Program style and design
A program must be correct, readable, and understandable. The basic principles for developing a good program are as follows:
1) Programs cannot be considered correct until they have been validated using test data.
2) Programs should be well structured3) Each program unit should be documented4) A program should be formatted in a style that enhances
its readability5) Programs should be readable and understandable6) Programs should be general and flexible
15
Fundamental types of numbers
Integers Whole numbers
(positive/negative/zero) Examples:
195234567878901230-2334567
Typical range on a 32-bit computer-2 x 109 to +2 x 109
16
Fundamental types of numbers
Reals+/- xxx.yyyyy
xxx integer partyyyyy fractional part
A better representation: Sign: +/- Mantissa: a fraction between 0.1 and 1.0 Exponent: x 10e
- 0.923456 x 10-6 or -0.923456e-6
17
real and integer variables
Variable declaration:type :: name
type :: name1, name2, … integer :: a, b, c real :: x, y, z
18
List-directed input and output
read *, var_1, var_2, … only variables!
print *, item_1, item_2, … variables, constants, expressions, …
Value separators: Comma (,) Slash (/) End-of-line Space
19
Named constants type, parameter :: name1=constant_expression1, …
real, parameter :: pi=3.1415926, pi_by_2 = pi/2.0
integer, parameter :: max_lines = 200
20
program list_directed_input_example!integersinteger::int_1, int_2, int_3real::real_1, real_2, real_3!initial valuesint_1=-1int_2=-2int_3=-3real_1=-1.0real_2=-2.0real_3=-3.0!read dataread*, int_1, real_1, int_2, real_2,int_3, real_3!print new valuesprint*, int_1, real_1, int_2, real_2,int_3, real_3end program list_directed_input_example
Example
21
Seven Golden Rules
Always plan ahead
Develop in stages
Modularize
Keep it simple
Test throughly
Document all programs
Enjoy your programming
22
Programs and modules
Main program unit
program name
use statements...Specification statements (for variables)...Executable statements (for calculations)...
end program name
23
Modules
Programs for solving complex problems should be designed in a modular fashion.
The problem should be divided into simpler subproblems, so that the subprograms can be written to solve each of them.
Every program must include exactly one main program and may also include one or more modules.
24
Modules
•Modules are a second type of program unit.
•The basic structure of a module is similar to the main program unit.
•The initial module statement of each module specifies the name of
that module based on the F language rules.
•A module unit ends with an end program statement incuding its
name.
•A module does not contain any executable statements.
•A module may contain any number of subprograms which are
seperated from the other statements by a contain statement.
25
Module program unit
module name
use statements...Specification statements.
contains(Procedure definitions)
subprogram_1subprogram_2..subprogram_n
end module name
26
Procedures
Procedures - origin “Write your own” (homemade) Intrinsic (built-in, comes with F )
sin(x), cos(x), abs(x), … Written by someone else (libraries)
Procedures (subprograms) – form Functions Subroutines
27
Procedures
name (argument_1, argument_2, ...)
Examples:
a + b * log (c)
-b + sqrt ( b * b – 4.0 * a * c)
28
Functions
function name (d1, d2, …) result(result_name)
Specifications part..
Execution part end function name Variables
Internal (local) variables Result variable (keyword result) Dummy argument (keyword intent(in))
attribute
29
Functions
function cube_root result(root)! A function to calculate the cube root of ! a positive real number! Dummy argument declaration
real, intent(in) :: x! Result variable declaration
real :: root! Local variable declaration
real :: log_x! Calculate cube root by using logs
log_x = log(x)root = exp(log_x/3.0)
end function cube_root
30
Subroutinessubroutine roots (x, square_root, cube_root, fourth_root, & fifth_root)! Subroutine to calculate various roots of positive real! Number supplied as the first argument, and return them in! the second to fifth arguments
! Dummy argument declarations real, intent(in) :: x real, intent(out) :: square_root, cube_root, & fourth_root, fifth_root ! Local variable declaration real :: log_x ! Calculate square root using intrinsic sqrt square_root = sqrt(x) ! Calculate other roots by using logs log_x = log(x) cube_root = exp(log_x/3.0) fourth_root = exp(log_x/4.0) fifth_root = exp(log_x/5.0)end subroutine roots
31
Subroutines
call name (arg1, arg2, …) intent(in), intent(out), intent(inout)
32
Attributes
intent (in): the dummy argument only provides information to the procedure and is not allowed to change its value any way
intent (out): the dummy argument only returns information from the procedure to the calling program
intent (inout): the dummy argument provides
information in both directions
33
Saving the values of local objects
Local entities within a procedure are not accessible from outside that procedure
Once an exit has been made, they cease to exist
If you want their values to ‘survive’ between calls, usereal, save :: list of real variables
real, save::a, b=1.23, c
İnteger, save::count=0
34
Example
MAIN PROGRAM
program ……..
real : : Alpha, Beta, Gamma
.
.
Alpha = Fkt ( Beta, Gamma )
.
.
end program ……….
FUNCTION SUBPROGRAM
function Fkt ( x, y )
real : : Fkt
real : : x, y
Fkt = x ** 2 - 2.5 * y + 3.7 * y ** 2
x = 0.0
end function Fkt
35
Example: Write a subprogram which calculates the cube root of a positive real number
MAIN PROGRAM
program test_cube_root
use maths
real : : x
print *, “Type a positive real number”
read *, x
Print *, “ The cube root of “,x,” is “, cube_root(x)
.
a = b * cube_root(x) + d
.
end program test_cube_root
36
module maths
Public::cube_root
contains
function cube_root (x) result (root)
! a function to calculate the cube root of a positive real number
! Dummy arguments
real , intent (in) : : x
! Result variable declaration
real : : root
! Local variable declaration
real : : log_x
! Calculate cube root by using logs
log_x = log (x)
root = exp (log_x / 3.0)
function cube_root
end module maths
37
Controlling the flow of your program
In everyday life we frequently encounter a situation which involves several possible alternative courses of action, requiring us to choose one of them based on some decision-making criteria.
The ability of a program to specify how these decisions are to be made is one of the most important aspects of programming.
38
Choice and decision-makingEXAMPLE : Q : How do I get to Budapest from Vienna ?
A : It depends how you want to travel :
* if you are in hurry then
you should fly from Schwechat airport in Vienna to Ferihegy airport in Budapest
* but if you are a romantic or like trains then
you should take the Orient Express from Südbahnhof
to Budapest’s Keleti palyudvar
* but if you have plenty of time then
you can travel on one of the boats which ply along the Danube
* otherwise
you can always go by road
39
Choice and decision-making
If criterion 1 thenaction 1
but if criterion 2 thenaction 2
but if criterion 3 thenaction 3
otherwiseaction 4
F provides a very similar construction for this decision-making problem as can be seen below :
40
Choice and decision-making
if (criterion_1) then
action_1
else if (criterion_2) then
action_2
else if (criterion_3) then
action_3
else
action_4
endif
41
Logical variables and expressions
Logical variables + logical constants + logical operators
Decision criterion in F language depends upon whether assertion is “true” or “false”, which are called logical variables and are declared as follows :
logical : : var_1, var_2, var_3
In F language we can simply write these logical values enclosed between dots :
.true.
.false.
42
logical variables logical :: var_1, var_2, … Logical valued functions
function name(arg1, …) result logical_variable
logical :: logical_variable
43
Logical (relational) operatorsAn assertion or expression which can take one of the local variables “true” and “false”, is called a logical expression. The simplest forms of logical (relational) expressions are those expressing the relationship between 2 numeric values as,
a < b less thana <= b less than or equal toa > b greater thana >= b greater than or equala == b equala /= b not equal
44
Logical operators
L1 L2 L1 .or. L2 L1 .and. L2
true true true true
true false true false
falsetrue true false
falsefalse false false
45
Examples
(a<b) .or. (c>d) (x<=y) .and. (y<=z) .not. (a<b) .eqv. (x<y) a<b .neqv. x<y
INVALID EXPRESSIONS
I == 1.or.2(A.and.B) /= 0.0
x > 0.0 .and. > 1.0
0.0 < x < 1.0
46
The if construct
In the simplest selection structure, a sequence of statements (called a block of statements) is executed or bypassed depending on whether a given logical expression is true or false.
If the logical expression is “true”, then the specified sequence of statements is executed ; otherwise it is bypassed.
In either case, execution continues with the statement in the program following the “end if” statement.
if ( logical_expression ) then
statement sequence
end if
47
The if construct
EXAMPLE :
if ( x >= 0.0 ) then
y = x * x
z = sqrt (x)
end if
On the other hand, a general form of an if – construct has the following form:
if ( logical_expression ) then
statement_sequence_1
else
statement_sequence_2
end if
48
The if construct
if (logical expression) thenblock of F statements
else if (logical expression) thenblock of F statements
else if (logical expression) thenblock of F statements
elseblock of F statements
endif
A typical structure for an general if – construct can be seen below :
49
Simple if construct
if (logical expression) then
block of F statements
endif
50
PROBLEM : A function subprogram which returns the cube root , is needed to write down.
function cube_root (x) result (root)
! This function program calculates the cube root of any real number
! Dummy argument and result declarations
real, intent (in) : : x
real : : root
! eliminate the zero case
if ( x == 0.0 ) then
root = 0.0
! calculate the cube root by using logs negative argument
else if ( x < 0.0 ) then
root = - exp ( log (-x) / 3.0 )
! positive argument
else
root = exp ( log (x) / 3.0
end if
end function cube_root
51
EXAMPLES :
“A” < “F” is a “true” logical expression
“m” > “b” is a “true“ logical expression
Comparisons of 2 strings is done character by character, considering the numeric codes. If the first characters of the strings are the same, the second characters are compared, if these are the same, then the third characters are compared, etc.
“cat” < “dog” ! is a “true” logical expression.
“cat” < “cow” ! is a “true” logical expression.
“June” > “July” ! is a “true” logical expression.
52
EXAMPLES :
Two strings with different lengths are compared so that blanks are appended to the shorter string.
“cat” < “cattle”
! is a “true” logical expression, because blank characters (b) preceds all letters : (“catbbb” < “cattle”)
“Adam” > “Eve”
! is false, because A comes before E, thus, less than E
“Adam” < “Adamant” ! “Adambbb” < “Adamant”
! is true, because “Adam” has been extended using 3 blanks; a blank always comes before a letter
“120” < “1201” ! “120b” < “1201”
! is true because a blank comes before a digit
“ADAM” < “Adam”
! is true because the second digit “D” < “d” (i.e. upper-case letters come before lower-case letters.
53
Depending on the abovegiven example the following alternatives can be selected as appropriate case - structure :
Case 1 : It is it is the football season and Fenerbahce is playing at home
decision: go to Sukru Saracoglu and and support the Canaries
Case 2 : it is the football season and Fenerbahce is playing away
decision: go to wherever they are playing and support the Canaries
Case 3 : any other situation
decision: get a six-pack and whatch some of your old Fenerbahce videos at home
As is clearly seen from the above- given example, case – construct is not as general as “else if” – construct ; but it is useful for implementing some selection structures and provides better program comprehensibility and reliability.
The case construct
54
The case construct
select case (case_expression)
case (case_selector)
block_of_statements
...
case default
block_of_statements
end select
55
The case construct
Case expression: either integer or character expression
Case selector: case_value
case_expression = = case_value low_value:
low_value <= case_expression :high_value
case_expression <= high_value low_value:high_value
low_value <= case_expression .and.case_expression <= high_value
56
EXAMPLE : PROBLEM : Read a date in the International Standard form ( yyyy-mm-dd) and print a message to indicate whether on this date in Istanbul, Turkey, it will be winter, spring, summer or autumn.
program seasons
! a program to calculate in which season a specified date lies
! variable declarations
character (len= 10) : : date
character (len= 2) : : month
! read date
print *, “please type a date in the form yyyy-mm-dd”
read *, date
! extract month number
month = date ( 6 : 7 )
! print season
57
select case (month)
case (“09” : “11”)
print *, date, “is in the autumn”
case (“12” , “01” : “02”)
print *, date, “is in the winter”
case (“03” : “05”)
print *, date, “is in the spring”
case (“06” : “08”)
print *, date, “is in the summer”
case default
print *, date, “is in not valid date”
end select
end program seasons
58
Program repetition
In many cases, we have to repeat certain sections of a program
Many numerical methods involve repetition/iteration
We have to have construct to repeat a group of statements, to end the repetition, or to restart it when certain condition is fulfilled.
59
EXAMPLE for a TYPICAL CYCLE :
Repeat the following 3 steps 21 times considering 5oC intervals from 0oC till to 100oC without the need for any data to be read at all :
1.step : read the initial and last Celcius temperature
2.step : calculate the corresponding Fahrenheit temperature for 5oC intervals
3.step : print both tempratures
A sequence of statements which are repeated is called a “loop.“
The do – constructs provides the means for controlling the repetition of statements within a loop.
60
do construct
do count = initial, final, incblock of statements
end doloop
count_variable : must be an integer
initial_value, final_value : are arbitrary expressions of integer type
selected step_size = inc : must be an integer
61
Examplesdo statement iteration count do variable values
do i = 1,10 10 1,2,3,4,5,6,7,8,9,10
do j = 20, 50, 5 7 20,25,30,35,40,45,50
do p = 7, 19, 4 4 7,11,15,19
do q = 4, 5, 6 1 4
do r = 6, 5, 4 0 (6)
do x = -20,20, 6 7 -20,-14,-8,-2,4,10,16
do n = 25, 0, -5 6 25,20,15,10,5,0
do m = 20, -20, -6 7 20,14,8,2,-4,-10,-16
62
do number = 1, 10, 2
print *, number, number **2
end do
OUTPUT produced will display following results :
1 1
3 9
5 25
7 49
9 81
Example
63
Count-controlled do loops
do count = initial, final, incdo count = initial, final (inc = 1)do
Iteration count:How many times we will go through the loop?
max((final-initial+inc)/inc, 0)
Integer variable
64
NESTED DO - LOOPS
The body of a do loop may contain another do loop. In this case,the second do loop is said to be “nested” within the first do loop.
EXAMPLE :
do m = 1, 4
do n = 1, 3
product = m * n
print *, m, n, product
end do
end do
OUTPUT
1 1 1
1 2 2
1 3 3
2 1 2
2 2 4
2 3 6
3 1 3
3 2 6
3 3 9
4 1 4
4 2 8
4 3 12
65
Some flexibility...do
.
.
.if (condition) then
exitend if
.
.
.end do.
66
Some more flexibility...
do ...if (condition) then
cycleend if
.
.
.end do.
67
Dealing with exceptional situations:
stop statement simply terminates execution
return statement causes execution of the procedure to
be terminated immediately and control transferred back to the program unit which called or referenced the procedure
68
Vectors, matrices and cubesOne-dimensional and two-dimensional arrays may be interpreted
in special ways according to the rules of linear algebra. An array of rank 1 is a vector, an array of rank 2 is a matrix and an array of rank 3 may be viewed as a stack of cubes forming a large block (parallelepiped).
Examples:One-dimensional array; vector:
integer, dimension(3) :: A
Two-dimensional array; integer, dimension(3,3) :: B
A(1) A(2) A(3)
B(1,1) B(1,2) B(1,3)
B(2,1) B(2,2) B(2,3)
B(3,1) B(3,2) B(3,3)
69
Vectors, matrices and cubesThree-dimensional array;Integer, dimension(3,3,3) :: C
C(1,1,1) C(1,1,2) C(1,1,3)
C(1,2,1) C(1,2,2) C(1,2,3)
C(1,3,1) C(1,3,2) C(1,3,3)
C(2,1,1) C(2,1,2) C(2,1,3)
C(2,2,1) C(2,2,2) C(2,2,3)
C(2,3,1) C(2,3,2) C(2,3,3)
C(3,1,1) C(3,1,2) C(3,1,3)
C(3,2,1) C(3,2,2) C(3,2,3)
C(3,3,1) C(3,3,2) C(3,3,3)
70
The array concept A set with n (=6) object, named A In mathematical terms, we can call
A, a vector And we refer to its elements as
A1, A2, A3, …
71
The array concept In F, we call such an ordered set of
related variables an array Individual items within an array
array elements A(1), A(2), A(3), …, A(n)
72
The array concept Subscripts can be:
x(10)
y(i+4)
z(3*i+max(i, j, k))
x(int(y(i)*z(j)+x(k)))
x(1)=x(2)+x(4)+1
print*,x(5)
73
The array concept
A
1
2
3
4
-1 0 1 2 3
A20
A31
74
Array declarationstype, dimension(subscript bounds) ::
list_of_array_names
type, dimension(n:m) :: variable_name_list
real, dimension(0:4) :: gravity, pressure
integer, dimension(1:100) :: scores
logical, dimension(-1, 3) :: table
75
Examples for Shape Arrays
real, dimension ( 0 : 49 ) : : z
! the array “z” has 50 elements
real, dimension ( 11 : 60 ) : : a, b, c
! a,b,c has 50 elements
real, dimension ( -20 : -1 ) : : x
! the array “x” has 20 elements
real, dimension ( -9 : 10 ) : : y
! the array “y” has 20 elements
76
Array sections with increment (stride) designator
real, dimension (18) :: V
V(2:9)
V(1: 15: 2)
V(2: 17: 5)
77
Array declarations Up to 7 dimensions Number of permissible subscripts:
rank Number of elements in a particular
dimension: extent Total number of elements of an array:
size Shape of an array is determined by its
rank and the extent of each dimension
78
Examplesinteger, dimension ( 10 ) : : arr
arr = (/ 3, 5, 7, 3, 27, 8, 12, 31, 4, 22 /)
arr ( 1 ) = 3
arr ( 5 ) = 27
! the value 27 is storen in the 5th location of the array “arr”
arr ( 7 ) = 12
arr ( 10 ) = 22
79
Array constructors
(/ value_1, value_2, … /) arr = (/ 123, 234, 567, 987 /) Regular patterns are common:
implied do(/ value_list, implied_do_control /)
arr = (/ (i, i = 1, 10) /) arr = (/ -1, (0, i = 1, 48), 1 /)
80
Initialization
You can declare and initialize an array at the same time:
integer, dimension(50) :: my_array = (/ (0, i = 1, 50) /)
81
Input and output Array elements treated as scalar
variables Array name may appear: whole
array Subarrays can be referred tooEXAMPLE :
integer, dimension ( 5 ) : : value
read *, value
read *, value(3)
82
real, dimension(5) :: p, qinteger, dimension(4) :: rprint *, p, q(3), rread *, p(3), r(1), qprint *, p, q (3), q (4), rprint *, q (2)
! displays the value in the 2nd location of the array “q”
print *, p! displays all the values storen in the array “p”
Examples
83
Using arrays and array elements...
An array can be treated as a single object Two arrays are conformable if they
have the same shape A scalar, including a constant, is
conformable with any array All intrinsic operations are defined
between two conformable objects
84
Using arrays and array elements...
.real, dimension(20) :: a, b, c..a = b*c
do i = 1, 20 a(i) = b(i)*c(i)end do
Arrays having the same number of elements may be applied to arrays and simple expressions. In this case, operation applied toan array are carried out elementwise.
85
Exampleinteger, dimension ( 4 ) : : a, b
integer, dimension ( 0 : 3 ) : : c
integer, dimension ( 6 : 9 ) : : d
a = (/ 1, 2, 3, 4 /)
b = (/ 5, 6, 7, 8 /)
c = (/ -1, 3, -5, 7 /)
c(0) c(1) c(2) c(3)
a = a + b ! will result a = (/ 6, 8, 10, 12 /)
d = 2 * abs ( c ) + 1 ! will result d = (/ 3, 7, 11, 15 /)
d(6) d(7) d(8) d(9)
86
do I = 1, 3 do J=1, 3 B(I,J) = I + J end do end do
RESULT: 2 3 4 3 4 5 4 5 6
87
do I =1, 3 do J = 1, 3 if ( I < J) then A(I,J) = -1 else if (I == J) then A(I,J)= 0 else A(I,J) = 1 end if end do end do
88
Intrinsic procedures with arrays Elemental intrinsic procedures with
arraysarray_1 = sin(array_2)
arr_max = max(100.0, a, b, c, d, e)
Some special intrinsic functions:maxval(arr)
maxloc(arr)
minval(arr)
minloc(arr)
size(arr)
sum(arr)
89
Sub-arrays Array sections can be extracted from a
parent array in a rectangular grid usinf subscript triplet notation or using vector subscript notation
Subscript triplet:subscript_1 : subscript_2 : stride
Similar to the do – loops, a subscript triplet defines an ordered set of subscripts
beginning with subscript_1, ending with subscript_2 and
considering a seperation of stride between the consecutive subscripts. The value of stride must not be “zero”.
90
Sub-arrays
Subscript triplet:subscript_1 : subscript_2 :
stride Simpler forms:
subscript_1 : subscript_2subscript_1 :subscript_1 : : stride: subscript_2: subscript_2 : stride: : stride:
91
Examplereal, dimension ( 10 ) : : arr
arr ( 1 : 10 )
! rank-one array containing all the elements of arr.
arr ( : )
! rank-one array containing all the elements of arr.
arr ( 3 : 5 )
! rank-one array containing the elements arr (3), arr(4), arr(5).
arr ( : 9 )
! rank-one array containing the elements arr (1), arr(2),…., arr(9).
arr ( : : 4 )
! rank-one array containing the elements arr (1), arr(5),arr(9).
92
Example
integer, dimension ( 10 ) : : a
integer, dimension ( 5 ) : : b, i
integer : : j
a = (/ 11, 22, 33, 44, 55, 66, 77, 88, 99, 110 /)
i = (/ 6, 5, 3, 9, 1 /)
b = a ( i ) ! will result b = ( 66, 55, 33, 99, 11 /)
a ( 2 : 10 : 2 ) ! will result a = ( 22, 44, 66, 88, 110 /)
a ( 1 : 10 : 2 ) = (/ j ** 2, ( j = 1, 5 ) /)
! will result a = ( 1, 4, 9, 16, 25 /)
a(1) a(3) a(5) a(7) a(9)
93
Type of printing sub-arrayswork = ( / 3, 7, 2 /)
print *, work (1), work (2), work (3)
! or
print *, work ( 1 : 3 )
! or
print *, work ( : : 1 )
! or
integer : : i
do i = 1, 3, 1
print *, work (i)
end do
! or another example
print *, sum ( work (1: 3) )
! or another example
print *, sum ( work (1: 3 : 2) )
94
Type of INPUT of sub-arraysinteger, dimension ( 10 ) : : a
integer, dimension ( 3 ) : : b
.
b = a ( 4 : 6 ) ! b (1 ) = a (4)
! b (2 ) = a (5)
! b (3 ) = a (6)
.
a ( 1 : 3 ) = 0 ! a(1) = a(2) = a(3) = 0
a ( 1 : : 2 ) = 1 ! a(1) = a(3) =…….= a(9) = 1
a ( 1 : : 2 ) = a ( 2 : : 2 ) + 1 ! a(1) = a(2) +1
! a(3) = a(4) +1
! a(5) = a(6) +1
! etc.
95
Arrays and procedures Explicit-shape array: no
freedom! Assumed-shape array
If an array is a procedure dummy argument, it must be declared in the procedure as an assumed-shape array!
96
Arrays and procedures
97
Example
main program unit: real, dimension ( b : 40 ) : : a
subprogram: real, dimension ( d : ) : : x
x ( d ) ---------------------- a ( b )
x ( d + 1 ) ---------------------- a ( b + 1 )
x ( d + 2 ) ---------------------- a ( b + 2 )
x ( d + 3 ) ---------------------- a ( b + 3 )
.
.
98
Exampleinteger , dimension ( 4 ) : : section = (/ 5, 1, 2, 3 /)
real , dimension ( 9 ) : : a
call array_example_3 ( a ( 4 : 8 : 2 ), a ( section ) )
dummy_array_1 = (/ a (4), a (6), a (8) /)
dummy_array_2 = (/ a (5), a (1), a (2), a (3) /)
dummy_argument_2 (4) dummy_argument_2 (3)
dummy_argument_2 (2)
dummy_argument_2 (1)
99
ExamplePROBLEM : Write a subroutine that will sort a set of names into alphabetic order.
İnitial order 7 1 8 4 6 3 5 2
After 1st exc. 1 7 8 4 6 3 5 2
After 2nd exc. 1 2 8 4 6 3 5 7
After 3rd exc. 1 2 3 4 6 8 5 7
After 4th exc. 1 2 3 4 6 8 5 7
After 5th exc. 1 2 3 4 5 8 6 7
After 6th exc. 1 2 3 4 5 6 8 7
After 7th exc. 1 2 3 4 5 6 7 8
100
Array-valued functions A function can return an array Such a function is called an
array-valued function
function name(…..) result(arr)real, dimension(dim) :: arr...
end function name
Explicit-shape
101
ExampleWrite a function that takes 2 real arrays as its arguments, returns an array in which each element is the maximum of the 2 corresponding elements in the input array
function max_array ( array_1, array_2 ) result (maximum_array)
! this function returns the maximum of 2 arrays on an element-by-element basis dummy arguments
real, dimension ( : ) , intent (in) : : array_1, array_2
! result variable
real, dimension ( size (array_1) ) : : maximum_array
! use the intrinsic function “max” to compare elements
maximum_array = max ( array_1, array_2)
! or use a do-loop instead of the intrinsic function max to compare elements
do i = 1, size (array_2)
maximum_array ( i ) = max ( array_1 ( i ), array_2 ( i ) )
end do
end function max_array
102
! Bu program açıklamalar, boşluklar ve gun 12 ay verisi şeklinde devam eden peşpeşe yıllar ve farklı istasyon verilerini okuyup istenilen yillarin verileri yazmak için yazılmıştır. program verisuz character(len=50)::istadi,s1,s2,s3 integer::i,j,istno,yil,ios open(unit=1,file="gunortsi.out",status="old",action="read") open(unit=2,file="gunortsi.dat",status="unknown",action="write") print*,"Lütfen Bekleyiniz"do read(unit=1,fmt="(a8,2i7,a,a)",iostat=ios)istadi,istno,yil,s1,s2 if (ios<0) then exit end if if (yil<1965 .or. yil>2006) then cycle else write(unit=2,fmt="(a8,2i7,a,a)")istadi,istno,yil,s1,s2 end if end doclose (unit=1)close (unit=2)end program verisuz
103
! Bu program istadı, no, gun 12 ay verisi şeklinde devam eden peşpeşe yıllar ve! farklı istasyon verilerini okuyup boşlara 9999.9 yazmak için yazılmıştır. program verisuz2 character(len=86)::istadi,s1 integer::i,j,istno,yil,gun,ios! real::a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12character(len=7)::a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12 open(unit=1,file="gunmaksi.dat",status="old",action="read") open(unit=2,file="gunmaksi.a",status="unknown",action="write") print*,"Lutfen Bekleyiniz"
do read(unit=1,fmt="(a8,3i7,12a7)",iostat=ios)istadi,istno,yil,gun,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12 if (ios<0) then exit end if if (gun==0) then print*,istadi,yil,gun cycle else if (a1=="") thena1="999.9" end if if (a2=="") then a2="999.9" end if if (a3=="") thena3="999.9" end if if (a4=="") thena4="999.9" end if if (a5=="") then a5="999.9" end if if (a6=="") thena6="999.9" end if if (a7=="") thena7="999.9" end if if (a8=="") thena8="999.9" end if if (a9=="") thena9="999.9" end if if (a10=="") thena10="999.9" end if if (a11=="") thena11="999.9" end if if (a12=="") thena12="999.9" end if write(unit=2,fmt="(a8,3i7,3x,12a7)",iostat=ios)istadi,istno,yil,gun,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12 end ifend do
close (unit=1)
close (unit=2)end program verisuz2