1 / 62

Examples of subprograms

Examples of subprograms. Write a program using either subroutine or function: read the edges of a rectangle, write a subprogram which calculate area of rectangle. program. subprogram. !this program is calculates area of a rectangle !using subroutine program area_calculation use rec

tyrell
Download Presentation

Examples of subprograms

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Examples of subprograms Write a program using either subroutine or function: • read the edges of a rectangle, • write a subprogram which calculate area of rectangle

  2. program subprogram !this program is calculates area of a rectangle !using subroutine program area_calculation use rec real::a,b,al print *, "enter two edges of the rectangle" read *, a,b call area (a,b,al) print *, "a=",a print*,"b=",b print *, "area_of_rectangle=",al endprogram area_calculation module rec public::area contains subroutine area(a,b,al) real, intent(in)::a,b real, intent (out)::al al=a*b return endsubroutine area end module rec

  3. program subprogram !this program is calculates area of a rectangle program area_calculation use rec real::a,b,al print *, "enter two edges of the rectangle" read *, a,b al=area (a,b) print *, "a=",a print*,"b=",b print *, "area_of_rectangle=",al endprogram area_calculation module rec public::area contains function area(a,b)result (al) real, intent(in)::a,b real::al al=a*b return endfunction area end module rec

  4. Write a program using either subroutine or function: • read the three edges of a triangle, • write a subprogram which calculate area of triangle

  5. program subprogram !this program calculate area of a triangle !using subroutine program triangle_area use ak real :: a,b,c,al print *,"a,b,c" read *,a,b,c call alan(a,b,c,al) print *,al end program triangle_area module ak public :: alan contains subroutine alan(a,b,c,al) real, intent (in)::a,b,c real, intent (out)::al real :: s s=(a+b+c)/2 al=sqrt(s*(s-a)*(s-b)*(s-c)) return end subroutine alan end module ak

  6. program subprogram module ak public :: alan contains function alan(a,b,c) result (al) real, intent(in) :: a,b,c real :: al real :: s s=(a+b+c)/2.0 al=sqrt(s*(s-a)*(s-b)*(s-c)) return end function alan end module ak program triangle_area use ak real :: a,b,c,al print *,"a,b,c" read *,a,b,c al= alan(a,b,c) print *,al end program triangle_area

  7. Write a program using function: • read the radius, • write a subprogram which calculate area of circle

  8. ! Example P.8. (Catherine Spade, 11 October 1999) ! Temperature Converter with Procedures. program A08 use A08M implicit none real :: Fahr, Cels ! start program A08 call Input( Fahr ) ! Subroutine reference Cels = Temp_C( Fahr ) ! Function reference call Output( Fahr, Cels ) ! Subroutine reference stop end program A08

  9. subroutine Input( F_Temp ) real, intent(out) :: F_Temp ! start subroutine Input write (unit = *, fmt = *) " Please enter the Fahrenheit temperature. " read (unit = *, fmt = *) F_Temp return end subroutine Input function Temp_C( F_Temp ) result( Temp_C_R ) real, intent(in) :: F_Temp real :: Temp_C_R real, parameter :: T_SCALE = 1.8, OFFSET = 32.0 ! start function Output Temp_C_R = (F_Temp - OFFSET) / T_SCALE return end function Temp_C subroutine Output( F_Temp, Temp_C_R ) real, intent(in) :: F_Temp, Temp_C_R ! start subroutine Output write (unit = *, fmt = *) F_Temp, " deg. F = ", Temp_C_R, " deg. C" return end subroutine Output module A08M implicit none public :: Input, Temp_C, Output contains subroutine Input( F_Temp ) function Temp_C( F_Temp ) result( Temp_C_R ) subroutine Output( F_Temp, Temp_C_R ) end module A08M

  10. module C14M implicit none public :: Input, Calculate, Output real, private :: Fahr, Cels contains subroutine Input( ) ! start subroutine Input write (unit = *, fmt = *) " Enter the Fahrenheit temperature. " read (unit = *, fmt = *) Fahr return end subroutine Input subroutine Calculate( ) real, parameter :: T_SCALE = 1.8, OFFSET = 32.0 ! start subroutine Calculate Cels = (Fahr - OFFSET) / T_SCALE return end subroutine Calculate subroutine Output( ) ! start subroutine Output write (unit = *, fmt = *) Fahr, " deg. F = ", Cels, " deg. C" return end subroutine Output end module C14M ! Example 2.14 program C14 use C14M implicit none ! start program C14 call Input( ) call Calculate( ) call Output( ) stop end program C14

  11. Question :(8 March 2002, Quiz 1) Prepare a computer program which calculates and prints, the bottom surface areaandthe volumeof a concrete cylinder block having the following initial values : *radius r = 210 cm * height h = 315 cm

  12. ! (8 March 2002, Quiz 1) program question4 real::r,h,bsa, vol real, parameter::pi=3.14 r=210 h=315 read *, r, h bsa=pi*r*r vol=bsa*h print*,"bottom surface area=",bsa, "cm2" print*,"volume=", vol, "cm3" end program question4

  13. Question : Write a function which, when supplied with the coordinates of two points (x1, y1) and (x2, y2), calculates the distance between the points by means of following formula. d = [ (x2 - x1) 2 + (y2 - y1) 2 ] 1/2

  14. program subprogram !this program is calculates distance !between two points program distance use distance_m real::x1,y1,x2,y2,d print *, "enter coordinates of two points" read *, x1,y1,x2,y2 d=dist(x1,y1,x2,y2) print *, "x1=",x1, "y1=",y1 print*,"x2=",x2,"y2=",y2 print *, "distance=",d endprogram distance module distance_m public::dist contains function dist(x1,y1,x2,y2)result (d) real, intent(in)::x1,y1,x2,y2 real::d d=sqrt((x2-x1)**2+(y2-y1)**2) return endfunction dist end module distance_m

  15. Desicion Making Flow Control

  16. Controlling the flow of your program In everyday life we frequently encounter a situation which involves several possible alternative courses of action, requiring us to choose one of them based on some decision-making criteria. The ability of a program to specify how these decisions are to be made is one of the most important aspects of programming.

  17. 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 hurrythen you should fly from Schwechat airport in Vienna to Ferihegy airport in Budapest * but ifyou are a romantic or like trainsthen you should take the Orient Express from Südbahnhof to Budapest’s Keleti palyudvar * but ifyou have plenty of timethen  you can travel on one of the boats which ply along the Danube * otherwise you can always go by road

  18. Choice and decision-making F provides a very similar construction for this decision-making problem as can be seen below : If criterion 1 then action 1 but if criterion 2 then action 2 but if criterion 3 then action 3 otherwise action 4

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

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

  21. logical variables • logical :: var_1, var_2, … • Logical valued functions functionname(arg1, …) resultlogical_variable logical :: logical_variable

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

  23. 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 ** 24 * a * c - b ** 2 < = 0

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

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

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

  27. Examples • (a<b) .or. (c>d) • (x<=y) .and. (y<=z) • .not. (a<b) .eqv. (x<y) • a<b .neqv. x<y INVALID EXPRESSIONS I == 1.or.2(A.and.B) /= 0.0 x > 0.0 .and. > 1.0 0.0 < x < 1.0

  28. 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. OperatorPriority .not. highest .and. .or. .eqv. and .neqv. lowest

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

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

  31. 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 block of F statements endif

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

  33. Example A) PROBLEM : A farmer has a triangular field which he wishes to sow with wheat.Write a program that readsthe 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

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

  35. PROBLEM : A function subprogram which returns the cube root , is needed to write down. function cube_root (x) result (root) ! This function program calculates the cube rootof any real number ! Dummy argument and result declarations real, intent (in) : :x real : : root !eliminate the zero case if ( x == 0.0 ) then root = 0.0 ! calculate the cube root by using logsnegative argument else if ( x < 0.0 ) then root = - exp ( log (-x) / 3.0 ) ! positive argument else root = exp ( log (x) / 3.0 end if end function cube_root

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

  37. Comparing character strings Flanguage lays down 6 rules for collecting sequence of letters, digits and other characters based on ANSII 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.

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

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

  40. 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 truebecause a blank comes before a digit “ADAM” < “Adam” ! is truebecause the second digit “D” < “d” (i.e. upper-case letters come before lower-case letters.

  41. Examples: “Adam” > “Eve” is false “Adam” < “Adamant” is true “120” < “1201” is true “ADAM” < “Adam” is true

  42. 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. EXAMPLE1: 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, ifit 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.

  43. 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 Fenerbahceis playing at home then go to Sukru Saracoglu and support the Canaries else if it is the football season and Fenerbahceis 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.

  44. The case construct Depending on the abovegiven example the following alternatives can be selected as appropriate case - structure : Case 1 : It is it is the football season and Fenerbahceis playing at home decision: go to Sukru Saracoglu and and support the Canaries Case 2 : it is the football season and Fenerbahceis 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.

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

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

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

  48. 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-listitem (in order) : 1.- if the value of selector expression is in the range of the label-listitem, 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.

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

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

More Related