controlling the flow of your program this chapter introduces the concept of comparison between two...
TRANSCRIPT
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.
Introduction to Scientific & Engineering Computing
1
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.
2
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 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 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 thana <= b less than or equal toa > b greater thana >= b greater than or equala == b equala /= b not equal
5
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 expressionsIn 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
L1 L2 L1 .or. L2 L1 .and. L2
true true true true
true false true false
false true true false
false false false false
8
Logical operators
L1 L2 L1 .eqv. L2 L1 .neqv. L2
true true true false
true false false true
false true false true
false false true false
9
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.010
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.
11
The if constructIn 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
12
Program squarerootReal::xPrint*,”Enter a number ”Read*,xİf (x>0) then print*,”Root of the number= “,sqrt(x)EndifEndprogram squareroot
The if constructEXAMPLE :
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 13
Program square_rootReal::xPrint*,”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" EndifEndprogram ......
The if construct
if (logical expression) thenblock of F statements
else if (logical expression) thenblock of F statements
else if (logical expression) thenblock of F statements
elseblock of F statements
endif
A typical structure for an general if – construct can be seen below :
14
Simple if construct
if (logical expression) then
block of F statements
endif
15
ExampleA) 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) ) ½ ===> 2s = a + b + c
read the sowing density
calculate the quantity of wheat seed required
calculate the number of 10 kilo bags this represents
16
a b
c
program wheat_sowing! This program calculates the quantity of wheat ! required to sow a triangular field! Variable declarationsreal::a,b,c,s,area,density,quantityinteger::num_bags! read the lengths of the sides of the fieldprint*,"type the lengths of the 3 sides of the field in metres : "read*,a,b,c! calculate the area of the fields=0.5*(a+b+c)area=sqrt(s*(s-a)*(s- b)*(s-c) ) ! read sowing densityprint*," What is the sowing density (gms/sq.m) ?"read*,density! calculate quantity of wheat in grams ! and the number of
17
! full 10 kg bagsquantity=density*area! any part-full bag is excludednum_bags=0.0001*quantity! check to see if another bag is requiredif(quantity>10000*num_bags) thennum_bags = num_bags + 1end if! print resultsprint*,"the area of the field is “, & area , “sq. metres"print*,"and",num_bags,"10 kilo bags will be required"end program wheat_sowing
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 stringscollecting sequence of letters, digits and other characters based on ASCII standard.
26 upper-case letters can be collected in the following order : ABCDEFGHIJKLMNOPRSTUVWXYZ26 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 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 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 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 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.
22
The case constructIn 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 thenget 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 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
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 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
25
The case construct
select case (case_expression)
case (case_selector)
block_of_statements
...
case default
block_of_statements
end select
26
The case constructselector : (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:
– 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 - constructExecution 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 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 D0430
! 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 D0531
! 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 ! 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 D1232
! Example: Choose formula for Z according to (X, Y) quadrant. program D13 implicit none real :: X, Y, Zwrite (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, Zend program D13
33
x
y
Z=sqrt(Y)
Z = Y Z = X * Y
!Write a program to analysis of ID NumberProgram readdata! This program is written for reading your IDİnteger::fak,yil,bol,siraprint*,”Please enter your ID number? (010030323)”Read(unit=*,fmt=“(i2,i3,2i2)”)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 endifEndprogram readdata
! Write a program to find Days of the month
program D17
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 35
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
program ex_of_modreal::x,yprint*,"modunu almak istediginiz sayiyi ve kacinci modunu almak istiyorsaniz giriniz?"read*,x,yprint*,x,"in ",y," e gore modu=",modulo(x,y)endprogram ex_of_mod
!Write a program to find a month in the fall or spring semesters.
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 D1936
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 defaultprint*,date,"is in not valid date"end selectend program seasons
37
! Name :! Address :! Date :! Comments : This program written to find which student goto lab A or lab B depending on their ID even or oddprogram 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
program labsreal::xinteger::id,ycharacter(len=49)::namePrint*,”Please enter your name”read*,namePrint*,”Please enter your ID” read*,idx=id/2.0y=id/2if (x==y) thenprint*," You must goto lab A"elseprint*,"you must goto labs B"end ifendprogram labs
38
if (modulo(id,2)==0.0) thenprint*," You must goto lab A"elseprint*,"you must goto labs B"end ifendprogram labs
!Write a program to find a given number is ! positive, zero or negativeprogram 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
39
40
program excercise_3real :: i,p,vprint *, ”Please type the power rating (watt) and supply voltage (volt)"
read *,p,vi=p/vif (i<5)thenprint *,"You should buy 5 amps cable"else if (5<=i.and.i<13) thenprint *,"You shuld buy 13 amps cable" else if (13<=i.and.i<30) thenprint *,"You should buy 30 amps cable" elseprint *,"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 ! 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-4acd = b**2 - 4.0**a*c
! calculate an print rootsif (d > small) then
! two roots casex1 = (-b - sqrt(d)) / (2.0*a)x2 = (-b + sqrt(d)) / (2.0*a)print *," The equation has two roots:"print *," x1=",x1," x2=",x2else if (-small <= d .and. d <= small) then
! two coincident roots casex1 = -b / (2.0*a)print *," The equation has two coincident roots:"print *," x1=x2=",x1 else
! No root caseprint *," 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.! variable declarations
character(len=10) :: datecharacter(len=2) :: month
! read dateprint *, "Please type a date in the form dd-mm-yyy"read *, date
! extract month numbermonth = 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 defaultprint *, date , " is invalid date"end select
end program seasons 43
program watch_discount integer :: number,gross_cost
real :: discount,net_costinteger ,parameter :: price=15print*,"Please type how many watch have you bought"read *,numberselect case(number)case (1)discount=0gross_cost=price*numbernet_cost=gross_cost*(1-discount)case (2:4)discount=0.05gross_cost=price*numbernet_cost=gross_cost*(1-discount)case (5:9)discount=0.1gross_cost=price*numbernet_cost=gross_cost*(1-discount)case (10:29)discount=0.15gross_cost=price*numbernet_cost=gross_cost*(1-discount)case (30:99)discount=0.2gross_cost=price*numbernet_cost=gross_cost*(1-discount)case (100:299)discount=0.25gross_cost=price*numbernet_cost=gross_cost*(1-discount)case defaultdiscount=0.3gross_cost=price*numbernet_cost=gross_cost*(1-discount)end selectprint *,"gross cost is equal to",gross_costprint *,"net cost is equal to",net_costend program watch_discount
44
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 roots
46
A firm produces pencil and sells them for 5 YTL each. However, it gives a discount for multiple orders as follows:
Number ordered Discount
<10 0%
<50 5 %
<70 10 %
<90 15 %
>=90 20 %
47
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 aritmetitortalama48