Week 5 - PowerPoint PPT Presentation

1 / 48
About This Presentation
Title:

Week 5

Description:

Introduction to Scientific & Engineering Computing Controlling the flow of Your Program This chapter introduces the concept of comparison between two numbers or two ... – PowerPoint PPT presentation

Number of Views:21
Avg rating:3.0/5.0
Slides: 49
Provided by: tor9
Category:

less

Transcript and Presenter's Notes

Title: Week 5


1
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
2
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
3
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 endi
f
3
4
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. .fals
e.
4
5
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 lt b less than a lt b less than or equal to a
gt b greater than a gt b greater than or equal a
b equal a / b not equal
5
6
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 gt
4 a c b 2 - 4 a c gt 0 4
a c lt b 2 4 a c - b 2
lt 0
6
7
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 lt b ) .or. ( c lt d )?
( x lt y ) .and. ( y lt z )?
a lt b .or. c lt d , x lt y .and. y
lt z (no need for parenthesis)?
7
8
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
9
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
10
Examples
  • (altb) .or. (cgtd)?
  • (xlty) .and. (yltz)?
  • .not. (altb) .eqv. (xlty)?
  • altb .neqv. xlty

INVALID EXPRESSIONS   I 1.or.2 (A.and.B) /
0.0       x gt 0.0 .and. gt 1.0         0.0 lt
x lt 1.0
10
11
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 .a
nd. .or. .eqv. and .neqv. lowest
11
12
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 Realx Print,Enter a number
Read,x If (xgt0) then print,Root of the
number ,sqrt(x)? Endif Endprogram squareroot
12
13
The if construct
Program square_root Realx Print,Enter a
number Read,x If (xgt0) then print,root
of the number,sqrt(x)? else
print,There is no root the number you entered"
Endif Endprogram ......
EXAMPLE  if ( x gt 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
14
The if construct
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 block of F statements else if (logical
expression) then block of F statements else bl
ock of F statements endif
14
15
Simple if construct
if (logical expression) then block of F
statements endif
15
16
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) ) ½ gt
2s a b c  ?        read the sowing
density ?        calculate the quantity of wheat
seed required ?        calculate the number of 10
kilo bags this represents
a b c
16
17
program wheat_sowing ! This program calculates
the quantity of wheat ! required to sow a
triangular field ! Variable declarations reala,b
,c,s,area,density,quantity integernum_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 s0.5(abc)? areasqrt(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 quantitydensityarea ! any
part-full bag is excluded num_bags0.0001quant
ity ! check to see if another bag is
required if(quantitygt10000num_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
18
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
19
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
  •  digits are all collected before the letter A.
  • upper-case letters are collacted before any
    lower-case letters.

19
20
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
21
EXAMPLES A lt F is a true logical
expression m gt 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 lt dog ! is a
true logical expression.  cat lt cow
! is a true logical expression.  June
gt July ! is a true logical
expression.
21
22
EXAMPLES
Two strings with different lengths are compared
so that blanks are appended to the shorter
string.  cat lt cattle ! is a true
logical expression, because blank characters
(b) preceds all letters (catbbb lt
cattle)?  Adam gt Eve ! is false,
because A comes before E, thus, less than
E  Adam lt Adamant ! Adambbb lt Adamant !
is true, because Adam has been extended using
3 blanks a blank always comes before a letter
 120 lt 1201 ! 120b lt 1201 ! is true
because a blank comes before a digit  ADAM
lt Adam ! is true because the second digit
D lt d (i.e. upper-case letters come before
lower-case letters.
22
23
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
24
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
25
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 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
26
The case construct
select case (case_expression)? case
(case_selector)? block_of_statements ... case
default block_of_statements end select
26
27
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
28
The case construct
  • Case expression
  • either integer or character expression
  • Case selector
  • case_value
  • case_expression case_value
  • low_value
  • low_value lt case_expression
  • high_value
  • case_expression lt high_value
  • low_valuehigh_value
  • low_value lt case_expression .and.case_expression
    lt high_value

28
29
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
30
! ExampleRank 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 gt 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
30
31
! 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
31
32
! 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 lt 0.0) then Y 1.0 else
if (X lt 1.0) then ! Else if (Xgt0.0 .and.
Xlt1.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
32
33
(No Transcript)
34
!Write a program to analysis of ID Number Program
readdata ! This program is written for reading
your ID Integerfak,yil,bol,sira print,Please
enter your ID number? (010030323) Read(unit,fmt
(i2,i3,2i2))fak,yil,bol,sira If (fak1) then
print,You are student in Civil Engineering
else if(fak2) then print,You
are student in .... ................
else print,You are not student in
ITU endif endif Endprogram readdata
35
! 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
program ex_of_mod realx,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 D17
35
36
!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 D19
36
37
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 (len10) date ! variable
declarations character (len2) month !
variable declarations print , "please type a
date in the form yyyy-mm-dd" ! read date read
, date monthdate (67) ! 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
38
program labsrealxintegerid,ycharacter(len4
9)name Print,Please enter your
nameread,name Print,Please enter your ID
read,idxid/2.0 yid/2if (xy) thenprint,"
You must goto lab A"elseprint,"you must goto
labs B"end ifendprogram labs
! 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 (xgt0) then print ,"your
number is positive" else if (xlt0) 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) thenprint," You must
goto lab A"elseprint,"you must goto labs
B"end ifendprogram labs
38
39
!Write a program to find a given number is !
positive, zero or negative program exercise_1_2
real ,parameter r1e-6 real x
integer z print ,"please type a
number" read ,x zx/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
41
program excercise_3real i,p,vprint ,
Please type the power rating (watt) and supply
voltage (volt)" read ,p,v ip/v if
(ilt5)then print ,"You should buy 5 amps
cable" else if (5lti.and.ilt13) then print
,"You shuld buy 13 amps cable" else if
(13lti.and.ilt30) then print ,"You should buy 30
amps cable" else print ,"We do not have the
cable which you need" end ifend program
excercise_3
41
42
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
small1.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 b2-4ac d b2 -
4.0ac! calculate an print roots if (d gt
small) then! two roots case x1 (-b - sqrt(d))
/ (2.0a) x2 (-b sqrt(d)) / (2.0a) print
," The equation has two roots" print ,"
x1",x1," x2",x2 else if (-small lt d .and. d
lt small) then! two coincident roots case x1
-b / (2.0a) print ," The equation has two
coincident roots" print ," x1x2",x1
else! No root case print ," The equation has
no real roots" end if! end program
quadratic_equation_solution
42
43
program seasons! A program to calculate in which
season a specified date lies.! variable
declarations character(len10)
date character(len2) month! read
date print , "Please type a date in the form
dd-mm-yyy" read , date! extract month
number month date(45)! 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 selectend
program seasons
43
44
program watch_discount integer
number,gross_cost real discount,net_cost inte
ger ,parameter price15 print,"Please type
how many watch have you bought" read
,number select case(number) case
(1) discount0 gross_costpricenumber net_cost
gross_cost(1-discount) case (24) discount0.0
5 gross_costpricenumber net_costgross_cost(1
-discount) case (59) discount0.1 gross_costp
ricenumber net_costgross_cost(1-discount) cas
e (1029) discount0.15 gross_costpricenumber
net_costgross_cost(1-discount) case
(3099) discount0.2 gross_costpricenumber ne
t_costgross_cost(1-discount) case
(100299) discount0.25 gross_costpricenumber
net_costgross_cost(1-discount) case
default discount0.3 gross_costpricenumber ne
t_costgross_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
45
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
46
Write a program to read the coefficients of a
quadratic equation and print its roots
46
47
A firm produces pencil and sells them for 5 YTL
each. However, it gives a discount for multiple
orders as follows Number ordered Discount lt10 0
lt50 5 lt70 10 lt90 15 gt90 20
47
48
program aritmetitortalama integersay,urunadet,i,
tutar,uruntutar say0 tutar0 do
i1,3 read,urunadet,uruntutar saysayurunadet tu
tartutaruruntutarurunadet enddo print,"ortalam
a siparis adeti",say/3 print,"ortalama siparis
fiyati",tutar/say end program aritmetitortalama
48
Write a Comment
User Comments (0)
About PowerShow.com