Presentation is loading. Please wait.

Presentation is loading. Please wait.

Summary BIL 106 Introduction to Scientific & Engineering Computing.

Similar presentations


Presentation on theme: "Summary BIL 106 Introduction to Scientific & Engineering Computing."— Presentation transcript:

1 Summary BIL 106 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 F The F language F & Fortran 90 Easy to learn to implement
to understand Powerful enough for use in large programs F Fortran 77 Fortran 90

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 Non-numerical data types Logical data values

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: 1952 Typical range on a 32-bit computer -2 x 109 to +2 x 109

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 10e x 10-6 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 (,) Space Slash (/) End-of-line

19 Named constants type, parameter :: name1=constant_expression1, …
real, parameter :: pi= , pi_by_2 = pi/2.0 integer, parameter :: max_lines = 200

20 Example 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

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 Procedures (subprograms) – form
“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 FUNCTION SUBPROGRAM 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
F provides a very similar construction for this decision-making problem as can be seen below : If criterion 1 then action 1 but if criterion 2 then action 2 but if criterion 3 then action 3 otherwise action 4

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 L1 L2 L1 .or. L2 L1 .and. L2 true true true true
true false true false false true true false false false 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
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

48 The if construct if (logical expression) then block of F statements
A typical structure for an general if – construct can be seen below : if (logical expression) then block of F statements else if (logical expression) then else endif

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 The case construct 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.

54 The case construct select case (case_expression) case (case_selector)
block_of_statements ... case default end select

55 The case construct Case expression: Case selector:
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, 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 statement iteration 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, ,11,15,19 do q = 4, 5, do r = 6, 5, (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 Example 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

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 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 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 The array concept 1 2 3 4 5 6 A

69 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, …

70 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)

71 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)

72 The array concept A20 A 1 2 3 4 -1 A31

73 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

74 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

75 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

76 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 5th location of the array “arr”  arr ( 7 ) = 12 arr ( 10 ) = 22

77 Array constructors (/ value_1, value_2, … /)
Regular patterns are common: implied do (/ value_list, implied_do_control /) arr = (/ (i, i = 1, 10) /) arr = (/ -1, (0, i = 1, 48), 1 /)

78 Initialization You can declare and initialize an array at the same time: integer, dimension(50) :: my_array = (/ (0, i = 1, 50) /)

79 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)

80 Examples 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 2nd location of the array “q” print *, p ! displays all the values storen in the array “p”

81 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

82 Using arrays and array elements...
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. . real, dimension(20) :: a, b, c a = b*c do i = 1, 20 a(i) = b(i)*c(i) end do

83 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 ) ! will result d = (/ 3, 7, 11, 15 /) d(6) d(7) d(8) d(9)

84 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)

85 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”.

86 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 :

87 Example real, dimension ( 10 ) : : arr arr ( 1 : 10 ) arr ( : )
! rank-one array containing all the elements of arr. 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).

88 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)

89 Type of printing sub-arrays
work = ( / 3, 7, 2 /) print *, work (1), work (2), work (3) ! or print *, work ( 1 : 3 ) print *, work ( : : 1 ) 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) )

90 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 ) ! a(1) = a(2) +1 ! a(3) = a(4) +1 ! a(5) = a(6) +1 ! etc.

91 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!

92 Arrays and procedures Explicit-shape Assumed-shape Calling program

93 Arrays and procedures

94 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 ) .

95 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)

96 Example PROBLEM : Write a subroutine that will sort a set of names into alphabetic order. İnitial order After 1st exc After 2nd exc After 3rd exc After 4th exc After 5th exc After 6th exc After 7th exc

97 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

98 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


Download ppt "Summary BIL 106 Introduction to Scientific & Engineering Computing."

Similar presentations


Ads by Google