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

Slides:



Advertisements
Similar presentations
Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
Advertisements

 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 3 Program Design and Branching Structures Dr. Ali Can Takinacı İstanbul Technical University Faculty of Naval Architecture and Ocean Engineering.
Summary of previous weeks Introduction to Scientific & Engineering Computing.
true (any other value but zero) false (zero) expression Statement 2
Basic Building Blocks In all ways of life, the easiest way to solve most problems is to break them down into smaller sub_problems and then to deal with.
C++ for Engineers and Scientists Third Edition
IS 1181 IS 118 Introduction to Development Tools VB Chapter 03.
Chapter 3 Applications & Logical Constructs. 2 Application 1 Temperature Conversion: Write a program that will convert a Celsius temperature to the corresponding.
1 BIL106E Introduction to Scientific & Engineering Computing Organizational matters Fortran 90 ( subset F ): Basics Example programs in detail.
Implementing Control Logic in C# Svetlin Nakov Telerik Corporation
Fundamentals of Python: From First Programs Through Data Structures
Chapter Seven Advanced Shell Programming. 2 Lesson A Developing a Fully Featured Program.
Fundamentals of Python: First Programs
Controlling the flow of Your Program This chapter introduces the concept of comparison between two numbers or two character strings, and explains how such.
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Fall, 2006Introduction to FORTRAN1 (2 + 2 = ???) Numbers, Arithmetic Nathan Friedman Fall, 2006.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CPS120: Introduction to Computer Science
Chapter 8 High-Level Programming Languages. 8-2 Chapter Goals Describe the translation process and distinguish between assembly, compilation, interpretation,
1 Week 2 n Organizational matters n Fortran 90 (subset F): Basics n Example programs in detail.
Selection Control Structures. Simple Program Design, Fourth Edition Chapter 4 2 Objectives In this chapter you will be able to: Elaborate on the uses.
Flow of Control Part 1: Selection
Fall, 2006Selection1 Choices, Choices, Choices! Selection in FORTRAN Nathan Friedman Fall, 2006.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
Week 3 Let's review! Fundamental data types List-directed input/output.
PROBLEM SOLVING & ALGORITHMS CHAPTER 5: CONTROL STRUCTURES - SELECTION.
Control Structures (A) Topics to cover here: Introduction to Control Structures in the algorithmic language Sequencing.
BASICS CONCEPTS OF ‘C’.  C Character Set C Character Set  Tokens in C Tokens in C  Constants Constants  Variables Variables  Global Variables Global.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Selection Relational Expressions A condition or logical expression is an expression that can only take the values true or false. A.
Compound Statements If you want to do more than one statement if an if- else case, you can form a block of statements, or compound statement, by enclosing.
CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 5, Lecture 1 (Monday)
Week 4: Organizational matters Register yourself to CIMS (Course Information and Management System) by clicking on Homework at hidiv.cc.itu.edu.tr/~F90.
8-1 Compilers Compiler A program that translates a high-level language program into machine code High-level languages provide a richer set of instructions.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
A First Book of C++ Chapter 4 Selection.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Unsur-unsur Algoritma
CNG 140 C Programming (Lecture set 3)
The if…else Selection Statement
Chapter 5 Controlling the flow of your program
The Selection Structure
Control Structures – Selection
Chapter 4: Control Structures I (Selection)
Summary BIL 106 Introduction to Scientific & Engineering Computing.
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Chapter 3: Selection Structures: Making Decisions
Presentation transcript:

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.

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.

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

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 :

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

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.

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

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

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

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)

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

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

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

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.

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

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

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 :

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

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

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

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)

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

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

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.

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.

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.

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.

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.

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

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

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.

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

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.

! 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

! 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

! 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 else Y = * X end if write (unit = *, fmt = *) " The values of X and Y are: ", X, Y stop end program D12

! 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

! 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

! 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

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

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

! 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

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

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

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

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

! 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

! 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

! 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

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

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

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

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 : “Physics” : “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.