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 F Fortran 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-numerical data 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 characters 2) The first character of a name must be a letter 3) 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 none integer :: Counts, Loop_Index real :: 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 initializations where each list item has the form Name = Value definition The value definition is an explicit constant. Examples: integer, parameter :: LENGTH=12 real, parameter :: PLANK= e-34, PI= real, parameter :: GRAVITY=9.807, AVAGADRO= e23, & 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
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 structured 3) Each program unit should be documented 4) A program should be formatted in a style that enhances its readability 5) Programs should be readable and understandable 6) Programs should be general and flexible
15 Fundamental types of numbers Integers Whole numbers (positive/negative/zero) Examples: Typical range on a 32-bit computer -2 x 10 9 to +2 x 10 9
16 Fundamental types of numbers Reals +/- xxx.yyyyy xxx integer part yyyyy fractional part A better representation: Sign:+/- Mantissa:a fraction between 0.1 and 1.0 Exponent:x 10 e x or e-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= , pi_by_2 = pi/2.0 integer, parameter :: max_lines = 200
20 program list_directed_input_example !integers integer::int_1, int_2, int_3 real::real_1, real_2, real_3 !initial values int_1=-1 int_2=-2 int_3=-3 real_1=-1.0 real_2=-2.0 real_3=-3.0 !read data read*, int_1, real_1, int_2, real_2,int_3, real_3 !print new values print*, int_1, real_1, int_2, real_2,int_3, real_3 end 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_1 subprogram_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 Subroutines subroutine 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, use real, 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 ** * y * 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-making EXAMPLE : 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 then action 1 but if criterion 2 then action 2 but if criterion 3 then action 3 otherwise action 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) operators An 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 than a <= b less than or equal to a > b greater than a >= b greater than or equal a == b equal a /= b not equal
44 Logical operators L1L2L1.or. L2L1.and. L2 true true truefalse true false falsetrue true false falsefalse false false
45 Examples (a 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. > < 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) then block of F statements else if (logical expression) then block of F statements else if (logical expression) then block of F statements else block 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 5 o C intervals from 0 o C till to 100 o C 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 5 o C 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, inc block of statements end do loop 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 Examples do statementiteration count do variable values do i = 1, ,2,3,4,5,6,7,8,9,10 do j = 20, 50, ,25,30,35,40,45,50 do p = 7, 19, 4 47,11,15,19 do q = 4, 5, do r = 6, 5, 4 0 (6) do x = -20,20, ,-14,-8,-2,4,10,16 do n = 25, 0, ,20,15,10,5,0 do m = 20, -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 : Example
63 Count-controlled do loops do count = initial, final, inc do 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 OUTPUT
65 Some flexibility... do. if (condition) then exit end if. end do.
66 Some more flexibility... do. if (condition) then cycle end 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 cubes One-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 cubes Three-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 A 1, A 2, A 3, …
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 A 20 A 31
74 Array declarations type, 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 Examples integer, 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 5 th 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 too EXAMPLE : integer, dimension ( 5 ) : : value read *, value read *, value(3)
82 real, dimension(5) :: p, q integer, dimension(4) :: r print *, p, q(3), r read *, p(3), r(1), q print *, p, q (3), q (4), r print *, q (2) ! displays the value in the 2 nd 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 Example integer, 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 RESULT:
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
88 Intrinsic procedures with arrays Elemental intrinsic procedures with arrays array_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_2 subscript_1 : subscript_1 : : stride : subscript_2 : subscript_2 : stride : : stride :
91 Example real, 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-arrays work = ( / 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-arrays integer, 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 Example integer, 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 Example PROBLEM : Write a subroutine that will sort a set of names into alphabetic order. İnitial order After 1 st exc After 2 nd exc After 3 rd exc After 4 th exc After 5 th exc After 6 th exc After 7 th exc
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 Example Write 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 2006) then cycle else write(unit=2,fmt="(a8,2i7,a,a)")istadi,istno,yil,s1,s2 end if end do close (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 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,a12 character(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,a1 1,a12 if (ios<0) then exit end if if (gun==0) then print*,istadi,yil,gun cycle else if (a1=="") then a1="999.9" end if if (a2=="") then a2="999.9" end if if (a3=="") then a3="999.9" end if if (a4=="") then a4="999.9" end if if (a5=="") then a5="999.9" end if if (a6=="") then a6="999.9" end if if (a7=="") then a7="999.9" end if if (a8=="") then a8="999.9" end if if (a9=="") then a9="999.9" end if if (a10=="") then a10="999.9" end if if (a11=="") then a11="999.9" end if if (a12=="") then a12="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,a1 0,a11,a12 end if end do close (unit=1) close (unit=2) end program verisuz2