Presentation is loading. Please wait.

Presentation is loading. Please wait.

Controlling the flow of Your Program Week 5 This chapter introduces the concept of comparison between two numbers or two character strings, and explains.

Similar presentations


Presentation on theme: "Controlling the flow of Your Program Week 5 This chapter introduces the concept of comparison between two numbers or two character strings, and explains."— Presentation transcript:

1

2 Controlling the flow of Your Program Week 5 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.

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

4 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

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

6 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

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

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

9 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

10 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 *cb ** 2 - 4 * a * c > = 0 4 * a * c < = b ** 2 4 * a * c - b ** 2 < = 0

11 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 :.not. (negation) highest priority.and. (conjunction)..or. (disjunction)..eqv. (equivalence)..neqv. (notequivalence)lowest priority 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)

12 Logical operators L1L2L1.or. L2L1.and. L2 true true truefalse true false falsetrue true false falsefalse false false

13 Logical operators L1L2L1.eqv. L2L1.neqv. L2 true true truefalse truefalse falsetrue falsetrue falsefalse truefalse

14 Examples n (a d) n (x<=y).and. (y<=z) n.not. (a<b).eqv. (x<y) n 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

15 Logical operator priorities Operator Priority.not. highest.and..or..eqv. and.neqv. lowest 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.

16 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

17 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

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

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

20 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) ) ½ and 2s = a + b + c  read the sowing density  calculate the quantity of wheat seed required  calculate the number of 10 kilo bags this represents

21 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

22 module testcube public::cube_root contains function cube_root(x) result(root) ! This function program calculates the cube root of any real number ! Dummy argument and result declarations !Dummy argument declaration real, intent(in)::x !Result variable declaration real::root !Local variable declaration real::log_x !eliminate the zero case if(x==0.0) then root = 0.0 !Calculate cube root by using logs else if (x<0.0) then ! calculate the cube root by using logs negative argument log_x = log(-x) root = -exp(log_x/3.0) else !positive argument log_x = log(x) root = exp(log_x/3.0) end if end function cube_root end module testcube Write a function, which will return the cube root of its argument. Structure plan Function cube_root(x) İf x=0 Return zero Else if x<0 Return –exp(log(-x)/3) Else Return exp(log(x)/3)

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

24 Comparing character strings F language lays down 6 rules for 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 upper-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 digits are all collected before the letter A. upper-case letters are collacted before any lower-case letters.

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

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

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

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

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

30 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

31 select case (case_expression) case (case_selector) block_of_statements... case default block_of_statements end select

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

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

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

35 ! Example:Rank two numbers. program D04 implicit none real :: X, Y character (len = 7) :: X_Rank, Y_Rank ! start program D04 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 D04

36 ! Example: Trade the values 1 and 2. program D05 implicit none integer :: I ! start program D05 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 D05

37 ! Example: Compute Y by one of three formulas, depending on X. program D12 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 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 D12

38 ! Example: Choose formula for Z according to (X, Y) quadrant. program D13 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 stop end program D13

39 ! Example: Days of the month program D17 implicit none 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 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 D17

40 ! Example: Fall and spring semesters, by months. program D19 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 D19

41 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

42 PROBLEM : Read a date in the International Standard form ( yyyy-mm-dd) and print a message of month name.

43 ! Name : ! Address : ! Date : ! Comments: 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

44 program exercise_1_2 real,parameter :: r=1e-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

45 program exercise_2 !taxation parameter declarations integer, parameter ::first=5000,second=15000 real, parameter ::first_per=0.10,second_per=0.25,next_per=0.30 !variable declaration integer :: income, total_tax !read the income print *," Type total income in US dollars" read *, income !do if blocks if (income first.and. income < second) then total_tax = second_per*income else total_tax = next_per*income end if !print the result print *," total income = ",income print *," taotal tax charged = ",total_tax end program exercise_2

46 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

47 program test_cube_root real :: x print *," type real positive number" read *, x print *,"the cube root of x=",x," is",cube_root(x) end program test_cube_root function cube_root(x) result(root) !Dummy argument declaration real::x !Result variable declaration real::root !Local variable declaration real::log_x !eliminate the zero case if(x==0.0) then root = 0.0 !Calculate cube root by using logs else if (x<0.0) then !first deal with negative arguments log_x = log(-x) root = -exp(log_x/3.0) else log_x = log(x) root = exp(log_x/3.0) end if !positive argument end function cube_root

48 ! Name : ! Address : ! Date : ! Comments: program test_cube_root use testcube real :: x print *," type real positive number" read *, x print *,"the cube root of x=",x," is",cube_root(x) end program test_cube_root module testcube public::cube_root contains function cube_root(x) result(root) ! This function program calculates the cube root of any real number ! Dummy argument and result declarations !Dummy argument declaration real, intent(in)::x !Result variable declaration real::root !Local variable declaration real::log_x !eliminate the zero case if(x==0.0) then root = 0.0 !Calculate cube root by using logs else if (x<0.0) then ! calculate the cube root by using logs negative argument log_x = log(-x) root = -exp(log_x/3.0) else !positive argument log_x = log(x) root = exp(log_x/3.0) end if end function cube_root end module testcube

49 ! Name : ! Address : ! Date : ! Comments: program character_converter !variable declaration !character(len=1) ::input_char,change_case !read the character from the monitor print *,"enter a character" read *, input_char !execution and output print *,"input character = ",input_char print *,"output character = ",change_case(input_char) end program character_converter function change_case(ch) result(ch_new) !this function changes the case of its argument ! if it is alphabetic !Dummy arguments and result character (len=*), intent(in)::ch character (len=1) :: ch_new !Check if argument is upper-case - convert lower-case if (ch>="A".and. ch ="a".and. ch<="z") then ch_new = char(ichar(ch) - 32) else !not alphabetic ch_new = ch end if ! end function change_case

50 ! Name : ! Address : ! Date : ! Comments: program character_converter use characterconv !variable declaration character(len=1) ::input_char,change_case !read the character from the monitor print *,"enter a character" read *, input_char !execution and output print *,"input character = ",input_char print *,"output character = ",change_case(input_char) end program character_converter n module characterconv n public::change_case n contains n function change_case(ch) result(ch_new) n !this function changes the case of its argument n !if it is alphabetic n !Dummy arguments and result n character (len=*),intent(in)::ch n character (len=1)::ch_new n !Check if argument is upper-case - convert lower-case n if (ch>="A".and. ch<="Z") then n ch_new = char(ichar(ch) + 32) n !Check if argument is lower-case - convert upper-case n else if (ch>="a".and. ch<="z") then n ch_new = char(ichar(ch) - 32) n else n !not alphabetic n ch_new = ch n end if n end function change_case n end module charactercon

51 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,x1,x2 !!read coefficients print *," Type the three coefficients a, b and c" read *, a,b,c !Calculate b^2-4ac d = b**2 - 4.0**a*c !calculate an print roots if (d > small) then !two roots case x1 = (-b - sqrt(d)) / (2.0*a) x2 = (-b + sqrt(d)) / (2.0*a) print *," The equation has two roots:" print *," x1=",x1," x2=",x2 else if (-small <= d.and. d <= small) then !two coincident roots case x1 = -b / (2.0*a) print *," The equation has two coincident roots:" print *," x1=x2=",x1 else !No root case print *," The equation has no real roots" end if !end program quadratic_equation_solution

52 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 4th to 5th 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 ! end program seasons

53 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

54 HOMEWORK 3 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.


Download ppt "Controlling the flow of Your Program Week 5 This chapter introduces the concept of comparison between two numbers or two character strings, and explains."

Similar presentations


Ads by Google