Summary BIL 106 Introduction to Scientific & Engineering Computing.

Slides:



Advertisements
Similar presentations
Introduction to arrays
Advertisements

Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
Chapter 4 Repetitive Execution. 2 Types of Repetition There are two basic types of repetition: 1) Repetition controlled by a counter; The body of the.
Summary of previous weeks Introduction to Scientific & Engineering Computing.
Chapter 7 Introduction to Arrays Part I Dr. Ali Can Takinacı İstanbul Technical University Faculty of Naval Architecture and Ocean Engineering İstanbul.
Chapter 2 Basic Elements of Fortan
1 Summary BIL 106E Introduction to Scientific & Engineering Computing.
Basic Building Blocks In all ways of life, the easiest way to solve most problems is to break them down into smaller sub_problems and then to deal with.
1 Chapter 2 Basic Fortran. 2 Attendance Requirements  Attendance is required for both class and lab. hours  Minimum %70 for class attendance  Minimum.
Introduction to C Programming
1 BIL106E Introduction to Scientific & Engineering Computing Organizational matters Fortran 90 ( subset F ): Basics Example programs in detail.
Summary of previous weeks BIL 102 Introduction to Scientific & Engineering Computing.
Structured Data Types. Date Types We have seen various data types –Integer, Real, Character, Logical All these types define data values of different kinds.
Fundamentals of Python: From First Programs Through Data Structures
Fortran: Specification Statements Session Six ICoCSIS.
Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.
Fundamentals of Python: First Programs
1 Week 12 Arrays, vectors, matrices and cubes. Introduction to Scientific & Engineering Computing 2 Array subscript expressions n Each subscript in an.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
Fortran 1- Basics Chapters 1-2 in your Fortran book.
Multi-Dimensional Arrays
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
1 Week 2 n Organizational matters n Fortran 90 (subset F): Basics n Example programs in detail.
Week 3 Let's review! Fundamental data types List-directed input/output.
BASICS CONCEPTS OF ‘C’.  C Character Set C Character Set  Tokens in C Tokens in C  Constants Constants  Variables Variables  Global Variables Global.
Basic Building Blocks In all ways of life, the easiest way to solve most problems is to break them down into smaller sub_problems and then to deal with.
An introduction to arrays WEEK 7 Introduction In scientific and engineering computing, it is very common to need to manipulate ordered sets of values,
Arrays Introduction In scientific and engineering computing, it is very common to need to manipulate ordered sets of values, such as vectors and matrices.
Week 4: Organizational matters Register yourself to CIMS (Course Information and Management System) by clicking on Homework at hidiv.cc.itu.edu.tr/~F90.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Fortran: Control Structures Session Three ICoCSIS.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter # 2 Part 2 Programs And data
Definition of the Programming Language CPRL
Chapter 10 Programming Fundamentals with JavaScript
Topics Designing a Program Input, Processing, and Output
Chapter 6 JavaScript: Introduction to Scripting
BASIC ELEMENTS OF A COMPUTER PROGRAM
Programming For Nuclear Engineers Lecture 6 Arrays
The Selection Structure
Introduction To Flowcharting
Fundamental of Java Programming Basics of Java Programming
Array processing and Matrix manipulation
JavaScript: Functions.
Programming Fundamentals
User-Defined Functions
MATLAB: Structures and File I/O
Formatted and Unformatted Input/Output Functions
IDENTIFIERS CSC 111.
Chapter 10 Programming Fundamentals with JavaScript
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Arithmetic operations, decisions and looping
Introduction to C++ Programming
Midterm Review Programming in Fortran
Chapter 6: User-Defined Functions I
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Language Constructs Construct means to build or put together. Language constructs refers to those parts which make up a high level programming language.
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Topics Designing a Program Input, Processing, and Output
Loop Construct.
Topics Designing a Program Input, Processing, and Output
Chapter 3: Selection Structures: Making Decisions
OPERATORS in C Programming
Array processing and Matrix manipulation
DATA TYPES AND OPERATIONS
Class code for pythonroom.com cchsp2cs
The Fundamentals of C++
OPERATORS in C Programming
Presentation transcript:

Summary BIL 106 Introduction to Scientific & Engineering Computing

Course Contentents Introduction to computing Basic F Selective execuation Repetitive execuation Input/output Programming with functions Arrays, Data types, Files Pointers and linked structures

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

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

Arithmetic operators in F Operator Meaning + Addition - Substraction * Multiplication / Division ** Exponentiation (or ‘rising the power of’)

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

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

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.

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

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

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=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.

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

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

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

Fundamental types of numbers Integers Whole numbers (positive/negative/zero) Examples: 1952 3456787890123 -2334567 Typical range on a 32-bit computer -2 x 109 to +2 x 109

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 - 0.923456 x 10-6 or -0.923456e-6

real and integer variables Variable declaration: type :: name type :: name1, name2, … integer :: a, b, c real :: x, y, z

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

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

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

Seven Golden Rules Always plan ahead Develop in stages Modularize Keep it simple Test throughly Document all programs Enjoy your programming

Programs and modules Main program unit program name use statements . Specification statements (for variables) Executable statements (for calculations) end program name

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.

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.

Module program unit module name use statements . Specification statements contains (Procedure definitions) subprogram_1 subprogram_2 subprogram_n end module name

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

Procedures name (argument_1, argument_2, ...) Examples: a + b * log (c) -b + sqrt ( b * b – 4.0 * a * c)

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

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

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

Subroutines call name (arg1, arg2, …) intent(in), intent(out), intent(inout)

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

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

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 ** 2 - 2.5 * y + 3.7 * y ** 2 x = 0.0 end function Fkt

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

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

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.

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

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

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

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.

logical variables logical :: var_1, var_2, … Logical valued functions function name(arg1, …) result logical_variable logical :: logical_variable

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

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

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

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

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

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

Simple if construct if (logical expression) then block of F statements endif

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

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.

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.

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.  

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

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

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

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

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.

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.

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

Examples do 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

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

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

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

Some flexibility... do . if (condition) then exit end if end do

Some more flexibility... do . if (condition) then cycle end if end do

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

The array concept 1 2 3 4 5 6 A

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

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)

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)

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

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

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

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

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

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

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

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)

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”

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

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

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)

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)

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

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 :

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

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)

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

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.

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!

Arrays and procedures Explicit-shape Assumed-shape Calling program

Arrays and procedures

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

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)

Example PROBLEM : 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  

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

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