Скачать презентацию Introduction to Scientific Engineering Computing Controlling the Скачать презентацию Introduction to Scientific Engineering Computing Controlling the

b9abefb0d225fcca7cdc02b6963d0a0a.ppt

  • Количество слайдов: 48

Introduction to Scientific & Engineering Computing Controlling the flow of Your Program This chapter Introduction to Scientific & Engineering Computing Controlling the flow of Your Program This chapter introduces the concept of comparison between two numbers or two character strings, and explains how such comparisons can be used to determine which of two, or more, alternatives sections of the code obeyed. 1

In everyday life we frequently encounter a situation which involves several possible alternative courses 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 decisionmaking criteria. The ability of a program to specify how these decisions are to be made is one of the most important aspects of programming. 2

Choice and decision-making if (criterion_1) then action_1 else if (criterion_2) then action_2 else if 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 3

Logical variables and expressions Logical variables + logical constants + logical operators Decision criterion 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. 4

Logical (relational) operators An assertion or expression which can take one of the local 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 a a < b <= b >= b == b /= b less than or equal to greater than or equal not equal 5

Logical (relational) operators Similar to the relational operators, arithmetic expressions seen below can also Logical (relational) operators Similar to the relational operators, arithmetic expressions seen below can also be performed in F language so that all arithmetic operators have a higher priority than any relational operators : expression_1 relational operator expression_2 where expression_i can be numeric, character and logical expressions. Examples for these mixed typed logical examples which contain both arithmetic operators and relational operators can be seen below : b ** 2 > = 4 * a *c b ** 2 - 4 * a * c > = 0 4 * a * c < = b ** 2 4 * a * c - b ** 2 < = 0 6

Compound logical expressions In F language composite or compound expressions are formed by combining Compound logical expressions In F language composite or compound expressions are formed by combining logical expressions by using the logical operators given below regarding the priority rules also given at the end of this section : EXAMPLES : ( a < b ). or. ( c < d ) ( x < = y ). and. ( y < = z ) a < b . or. c < d , x < = y . and. y < = z (no need for parenthesis) 7

Logical operators L 1 L 2 L 1. or. L 2 true false true Logical operators L 1 L 2 L 1. or. L 2 true false true false L 1. and. L 2 true false 8

Logical operators L 1 L 2 L 1. eqv. L 2 true false true Logical operators L 1 L 2 L 1. eqv. L 2 true false true false true L 1. neqv. L 2 false true false 9

Examples (a<b). or. (c>d) (x<=y). and. (y<=z) . not. (a<b). eqv. (x<y) a<b. neqv. Examples (ad) (x<=y). and. (y<=z) . not. (a 0. 0. and. > 1. 0 0. 0 < x < 1. 0 10

Logical operator priorities The operations are performed in the following order (priority rules): 1. Logical operator priorities The operations are performed in the following order (priority rules): 1. - arithmetic operations and functions 2. - relational operations 3. - logical operarions in the order mentioned before. Operator Priority. not. highest. and. . or. . eqv. and. neqv. lowest 11

The if construct In the simplest selection structure, a sequence of statements (called a 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 Program squareroot Real: : x Print*, ”Enter a number ” Read*, x İf (x>0) then print*, ”Root of the number= “, sqrt(x) Endif Endprogram squareroot 12

The if construct EXAMPLE : if ( x >= 0. 0 ) then y The if construct EXAMPLE : if ( x >= 0. 0 ) then y = x * x z = sqrt (x) end if Program square_root Real: : x Print*, ”Enter a number” Read*, x İf (x>0) then print*, ”root of the number=“, sqrt(x) else print*, ”There is no root the number you entered" Endif Endprogram. . . 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 13

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

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

Example A) PROBLEM : A farmer has a triangular field which he wishes to Example A) PROBLEM : A farmer has a triangular field which he wishes to sow with wheat. Write a program that reads the lenghts of the 3 sides of the field (in meters) and the sowing density (in grams per square meters) Print the number of 10 kilo bags of wheat he must purchase in order to sow the whole field. B. ) ANALYSIS : STRUCTURE PLAN of the PROBLEM Read lenghts of the sides of the field ( a, b, c ), calculate the area of the field area = ( s (s-a)(s-b)(s-c) ) ½ ===> 2 s = a + b + c read the sowing density calculate the quantity of wheat seed required a b calculate the number of 10 kilo bags this represents c 16

program wheat_sowing ! This program calculates the quantity of wheat ! required to sow program wheat_sowing ! This program calculates the quantity of wheat ! required to sow a triangular field ! Variable declarations real: : a, b, c, s, area, density, quantity integer: : num_bags ! read the lengths of the sides of the field print*, "type the lengths of the 3 sides of the field in metres : " read*, a, b, c ! calculate the area of the field s=0. 5*(a+b+c) area=sqrt(s*(s-a)*(s- b)*(s-c) ) ! read sowing density print*, " What is the sowing density (gms/sq. m) ? " read*, density ! calculate quantity of wheat in grams ! and the number of ! full 10 kg bags quantity=density*area ! any part-full bag is excluded num_bags=0. 0001*quantity ! check to see if another bag is required if(quantity>10000*num_bags) then num_bags = num_bags + 1 end if ! print results print*, "the area of the field is “, & area , “sq. metres" print*, "and", num_bags, "10 kilo bags will be required" end program wheat_sowing 17

Comparing numbers Accuracy/round-off – Number of significant digits for real numbers Do not test Comparing numbers Accuracy/round-off – Number of significant digits for real numbers Do not test whether two numbers are equal Test whether their difference is acceptably small 18

Comparing character strings collecting sequence of letters, digits and other characters based on ASCII Comparing character strings collecting sequence of letters, digits and other characters based on ASCII standard. 26 upper-case letters can be collected in the following order : ABCDEFGHIJKLMNOPRSTUVWXYZ 26 lower-case letters can be collected in the following order : abcdefghijklmnoprstuvwxyz the 10 digits can be collected in the following order : 0 1 2 3 4 5 6 7 8 9 a space (or blank) is collected before both letters and digits are all collected before the letter A. upper-case letters are collacted before any lower-case letters. 19

When 2 character operands are being compared there are 3 distinct stages in the When 2 character operands are being compared there are 3 distinct stages in the process : 1. - If two operands are not the same length, the shorter one is treated as though it were extended on the right with blanks until it is the same length as the longer one. 2. - The two operands are compared character by character, starting with the left-most character, until either a difference is found or the end of the operand is reached. 3. - If a difference is found, then the relationship between these two different characters defines the relationship between the two operands, with the character which comes earlier in collating sequence being deemed to be the lesser of the two. If no difference is found, then the strings are considered to be equal. 20

EXAMPLES : “A” < “F” is a “true” logical expression “m” > “b” is 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. 21

EXAMPLES : Two strings with different lengths are compared so that blanks are appended 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” ! “ 120 b” < “ 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. 22

The case construct In some situations it is necessary to have an ordering built The case construct In some situations it is necessary to have an ordering built into the decision as to which choice to take, because there is an overlap between some of the possible decision criteria. EXAMPLE 1 : Consider that you are a basketball addict, but especially a Efes-Pilsen fun, then the decision as to what to do on Saturday afternoon might look like this, if it is the basketball season and the Efess are at home then go to Abdi Ipekci else if it is the basketball season and the EPs game is on TV then get a six-pack and watch the game on TV else if it is the basketball season then go to any nearby basketball game else rent a basketball video and watch it at home. 23

EXAMPLE 2 : Consider that you are a Fenerbahce soccer fan, and are only EXAMPLE 2 : Consider that you are a Fenerbahce soccer fan, and are only interested in watching football matches in which they are playing (whether at home or away), then your Saturday evening decision plan might be rather different : if (it is the football season and Fenerbahce is playing at home) then go to Sukru Saracoglu and support the Canaries else if (it is the football season and Fenerbahce is playing away ) then go to whenever they are playing and support the Canaries else get a six-pack and watch some of your old Fenerbahce videos at home. endif 24

The case construct Depending on the above given example the following alternatives can be The case construct Depending on the above given 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 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. 25

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

The case construct selector : (i. e. case_expression) is an integer, character or logical The case construct selector : (i. e. case_expression) is an integer, character or logical expressions label_list i : (i. e. case_selector_i) each of this list is a list of one and more possible values of the selector, enclosed in parentheses. The case_selector_i can take one of the four forms : ( case_value ) ( low_value : ) ( : high_value ) ( low_value : high_value ) case : case - values that determine which block is to be executed must be specified by initialization expressions, which are simple expressions that may contain constants but no variables (see selector). case - values must not overlap ; thus, no block can be eligible for selection in more than one case. 27

The case construct Case expression: – either integer or character expression Case selector: – 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 28

Exacution of the case - construct Execution of the case – construct begins with Exacution of the case - construct Execution of the case – construct begins with evaluation of the selector expression in the “select case” – statement. The case – statements are then executed in the order of their appearance ; that is, in each case – statement, the value of selector expression is compared with the label-list item (in order) : 1. - if the value of selector expression is in the range of the label-list item, a match occurs. 2. - if no match occurs during examination of the label_list in all case statements and case default statement is present, case default is then selected for execution. 3. - if a case block is selected, its execution proceeds normally, beginning with the first statement in the block. 29

! Example: Rank two numbers. program D 04 implicit none real : : X, ! Example: Rank two numbers. program D 04 implicit none real : : X, Y character (len = 7) : : X_Rank, Y_Rank ! start program D 04 write (unit = *, fmt = *) " Please enter a pair of real numbers to be ranked. " read (unit = *, fmt = *) X, Y write (unit = *, fmt = *) " You have entered: ", X, Y if (X > Y) then X_Rank = "larger " Y_Rank = "smaller" else X_Rank = "smaller" Y_Rank = "larger " end if write (unit = *, fmt = *) X, " is ", X_Rank, " and ", Y, " is ", Y_Rank end program D 04 30

! Example: Trade the values 1 and 2. program D 05 implicit none integer ! Example: Trade the values 1 and 2. program D 05 implicit none integer : : I ! start program D 05 write (unit = *, fmt = *) " Please enter 1 or 2. " read (unit = *, fmt = *) I write (unit = *, fmt = *) " Thank you. You have entered: ", I if (I == 1) then ! if construct I = 2 ! if construct else ! if construct I = 1 ! if construct end if ! if construct write (unit = *, fmt = *) " Your value was changed to: ", I stop end program D 05 31

! Example: Compute Y by one of three formulas, depending on X. program D ! Example: Compute Y by one of three formulas, depending on X. program D 12 implicit none real : : X, Y write (unit = *, fmt = *) " Please enter the value of X. " read (unit = *, fmt = *) X if (X < 0. 0) then Y = 1. 0 else if (X <= 1. 0) then ! Else if (X>=0. 0. and. X<=1. 0) then Y = 4. 0 * X + 1. 0 else Y = -10. 0 * X + 15. 0 end if write (unit = *, fmt = *) " The values of X and Y are: ", X, Y stop end program D 12 32

! Example: Choose formula for Z according to (X, Y) quadrant. program D 13 ! Example: Choose formula for Z according to (X, Y) quadrant. program D 13 implicit none real : : X, Y, Z write (unit = *, fmt = *) " Please enter values of X and Y. " read (unit = *, fmt = *) X, Y if (Y > 0. 0) then ! Northeast and northwest quadrants Z = sqrt( Y ) else if (X < 0. 0) then ! Southwest quadrant Z = Y else ! Southeast quadrant Z = X * Y end if write (unit = *, fmt = *) " Values of X, Y, and Z are: ", X, Y, Z end program D 13 33

!Write a program to analysis of ID Number Program readdata ! This program is !Write a program to analysis of ID Number Program readdata ! This program is written for reading your ID İnteger: : fak, yil, bol, sira print*, ”Please enter your ID number? (010030323)” Read(unit=*, fmt=“(i 2, i 3, 2 i 2)”)fak, yil, bol, sira İf (fak==1) then print*, ”You are student in Civil Engineering” else if(fak==2) then print*, ”You are student in. . ”. . . . else print*, ”You are not student in ITU” endif Endprogram readdata

! Write a program to find Days of the month program D 17 integer ! Write a program to find Days of the month program D 17 integer : : Month, Year, NDays write (unit = *, fmt = *) " Please enter the year (4 digits). " read (unit = *, fmt = *) Year write (unit = *, fmt = *) " Please enter the month number (1 to 12). " read (unit = *, fmt = *) Month select case (Month) case (9, 4, 6, 11) ! Sep, Apr, Jun, Nov NDays = 30 case (2) ! February if (modulo( Year, 4 ) == 0) then NDays = 29 !Leap year else NDays = 28 end if program ex_of_mod real: : x, y print*, "modunu almak istediginiz sayiyi ve kacinci modunu almak istiyorsaniz giriniz? " read*, x, y print*, x, "in ", y, " e gore modu=", modulo(x, y) endprogram ex_of_mod case default ! Jan, Mar, May, Jul, Aug, Oct, Dec NDays = 31 end select write (unit = *, fmt = *) " The number of days in month: ", Month, " is: ", NDays stop end program D 17 35

!Write a program to find a month in the fall or spring semesters. program !Write a program to find a month in the fall or spring semesters. program D 19 implicit none integer : : M write (unit = *, fmt = *) " Please enter a month number between 1 and 12. " read (unit = *, fmt = *) M select case (M) case (9: 12, 1) write (unit = *, fmt = *) " Month ", M, " is in the fall semester. " case (2: 6) write (unit = *, fmt = *) " Month ", M, " is in the spring semester. " case default write (unit = *, fmt = *) " School is not in session during month ", M end select stop end program D 19 36

PROBLEM : Read a date in the International Standard form ( yyyy-mm-dd) and print 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 character (len=10) : : date ! variable declarations character (len=2) : : month ! variable declarations print *, "please type a date in the form yyyy-mm-dd" ! read date read *, date month=date (6: 7) ! extract month number select case (month) ! print season 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 37

program labs real: : x integer: : id, y character(len=49): : name Print*, ”Please program labs real: : x integer: : id, y character(len=49): : name Print*, ”Please enter your name” read*, name Print*, ”Please enter your ID” read*, id x=id/2. 0 y=id/2 if (x==y) then print*, " You must goto lab A" else print*, "you must goto labs B" end if endprogram labs ! Name : ! Address : ! Date : ! Comments : This program written to find which student goto lab A or lab B depending on their ID even or odd program exercise_1_1 real : : x print *, "please type a number" read *, x if (x>0) then print *, "your number is positive" else if (x<0) then print *, "your number is negative" else print *, "your number is zero" end if end program exercise_1_1 if (modulo(id, 2)==0. 0) then print*, " You must goto lab A" else print*, "you must goto labs B" end if endprogram labs 38

!Write a program to find a given number is ! positive, zero or negative !Write a program to find a given number is ! positive, zero or negative program exercise_1_2 real , parameter : : r=1 e-6 real : : x integer : : z print *, "please type a number" read *, x z=x/r select case (z) case (1: ) print *, "your number is positive" case (0) print *, "your number is zero" case (: -1) print *, "your number is negative" end select end program exercise_1_2 39

40 40

program excercise_3 real : : i, p, v print *, ”Please type the power program excercise_3 real : : i, p, v print *, ”Please type the power rating (watt) and supply voltage (volt)" read *, p, v i=p/v if (i<5)then print *, "You should buy 5 amps cable" else if (5<=i. and. i<13) then print *, "You shuld buy 13 amps cable" else if (13<=i. and. i<30) then print *, "You should buy 30 amps cable" else print *, "We do not have the cable which you need" end if end program excercise_3 41

 program quadratic_equation_solution ! A program to solve a quadratic equation using an if program quadratic_equation_solution ! A program to solve a quadratic equation using an if ! construct to distinguish between the three cases. !! Constant declaration real, parameter : : small=1. e-6 ! Variable declarations real : : a, b, c, d, x 1, x 2 !! read coefficients print *, " Type three coefficients a, b and c" read *, a, b, c ! Calculate b^2 -4 ac d = b**2 - 4. 0**a*c ! calculate an print roots if (d > small) then ! two roots case x 1 = (-b - sqrt(d)) / (2. 0*a) x 2 = (-b + sqrt(d)) / (2. 0*a) print *, " The equation has two roots: " print *, " x 1=", x 1, " x 2=", x 2 else if (-small <= d. and. d <= small) then ! two coincident roots case x 1 = -b / (2. 0*a) print *, " The equation has two coincident roots: " print *, " x 1=x 2=", x 1 else ! No root case print *, " The equation has no real roots" end if ! end program quadratic_equation_solution 42

program seasons ! A program to calculate in which season a specified date lies. 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 dd-mm-yyy" read *, date ! extract month number month = date(4: 5) ! extract from 4 th to 5 th character of string date and assign them to character variable month ! print season select case(month) ! case("03", "04", "05") case("03": "05") print *, date , " is in the spring" case("06", "07", "08") print *, date , " is in the summer" case("09", "10", "11") print *, date , " is in the fall" case("12", "01", "02") print *, date , " is in the winter" case default print *, date , " is invalid date" end select 43 end program seasons

program watch_discount integer : : number, gross_cost real : : discount, net_cost integer , program watch_discount integer : : number, gross_cost real : : discount, net_cost integer , parameter : : price=15 print*, "Please type how many watch have you bought" read *, number select case(number) case (1) discount=0 gross_cost=price*number net_cost=gross_cost*(1 -discount) case (2: 4) discount=0. 05 gross_cost=price*number net_cost=gross_cost*(1 -discount) case (5: 9) discount=0. 1 gross_cost=price*number net_cost=gross_cost*(1 -discount) case (10: 29) discount=0. 15 gross_cost=price*number net_cost=gross_cost*(1 -discount) case (30: 99) discount=0. 2 gross_cost=price*number net_cost=gross_cost*(1 -discount) case (100: 299) discount=0. 25 gross_cost=price*number net_cost=gross_cost*(1 -discount) case default discount=0. 3 gross_cost=price*number net_cost=gross_cost*(1 -discount) end select print *, "gross cost is equal to", gross_cost print *, "net cost is equal to", net_cost end program watch_discount 44

HOMEWORK Using a case – structure prepare a computer program which shows your program HOMEWORK Using a case – structure prepare a computer program which shows your program on Thursday and on Friday, as can be seen below : Thursday 09. 00 : 10. 50 “Physics” 11. 00 : 12. 50 “Chemistry” --- etc. Then, carry out 2 sample runs for different days and hours. Print the input values as well as the messages obtained as results. 45

Write a program to read the coefficients of a quadratic equation and print its Write a program to read the coefficients of a quadratic equation and print its roots 46

A firm produces pencil and sells them for 5 YTL each. However, it gives A firm produces pencil and sells them for 5 YTL each. However, it gives a discount for multiple orders as follows: Number ordered <10 <50 <70 <90 >=90 Discount 0% 5 % 10 % 15 % 20 % 47

program aritmetitortalama integer: : say, urunadet, i, tutar, uruntutar say=0 tutar=0 do i=1, 3 program aritmetitortalama integer: : say, urunadet, i, tutar, uruntutar say=0 tutar=0 do i=1, 3 read*, urunadet, uruntutar say=say+urunadet tutar=tutar+uruntutar*urunadet enddo print*, "ortalama siparis adeti", say/3 print*, "ortalama siparis fiyati", tutar/say end program aritmetitortalama 48