Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Selection Structures: if and switch Statements Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering.

Similar presentations


Presentation on theme: "Chapter 4 Selection Structures: if and switch Statements Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering."— Presentation transcript:

1 Chapter 4 Selection Structures: if and switch Statements Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University of Technology

2 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-2 Control Structures control structure –a combination of individual instructions into a single logical unit with one entry point and one exit point three kinds of control structures to control execution flow: –sequence –selection –repetition

3 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-3 Control Structures (Cont’) compound statement –a group of statements bracketed by { and } that are executed sequentially { statement1; statement2;. statementn; } A function body consists of a single compound statement.

4 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-4 Control Structures (Cont’) selection control structure –a control structure that chooses among alternative program statements

5 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-5 Conditions A program chooses among alternative statements by testing the value of key variables. –rest_heart_rate > 75 condition –an expression that is either false (represented by 0) or true (usually represented by 1)

6 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-6 Relational and Equality Operators Most conditions that we use to perform comparisons will have one of these forms: –variable relational-operator variable –variable relational-operator constant –variable equality-operator variable –variable equality-operator constant

7 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-7 Relational and Equality Operators (Cont’)

8 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-8 Relational and Equality Operators (Cont’)

9 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-9 Logical Operators logical expression –an expression that uses one or more of the logical operators && (and), || (or), ! (not) salary 5 temperature > 90.0 && humidity > 0.90 n >= 0 && n <= <= n && n <= 100

10 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-10 Logical Operators (Cont’) logical complement (negation) –the complement of a condition has the value 1 (true) when the condition’s value is 0 (false); the complement of a condition has the value 0 (false) when the condition’s value is nonzero (true) –!(0 <= n && n <= 100) C accepts any nonzero value as a representation of true.

11 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-11 Logical Operators (Cont’)

12 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-12 Logical Operators (Cont’)

13 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-13 Logical Operators (Cont’)

14 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-14 Operator Precedence unary operator –an operator that has one operand The precedence of operators + and - depends on whether they have one operand or two. –-x - y * z the unary minus is evaluated first (-x), then *, and then the second -. use parentheses to change the order of operator evaluation. –(x 0.0

15 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-15 Operator Precedence (Cont’)

16 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-16 Operator Precedence (Cont’)

17 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-17 Figure 4.1 Evaluation Tree and Step-by- Step Evaluation for !flag || (y + z >= x - z)

18 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-18 Short-Circuit Evaluation An expression of the form a || b must be true if a is true, no matter what the value of b is. C stops evaluating the expression when it determines that the value of !flag is 1 (true). An expression of the form a && b must be false if a is false. C would stop evaluating such an expression if its first operand evaluates to 0. short-circuit evaluation stopping evaluation of a logical expression as soon as its value can be determined

19 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-19 Figure 4.2 Range of True Values for min <= x && x <= max

20 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-20 Writing English Conditions in C assuming x is 3.0, y is 4.0, and z is 2.0 for the English condition “x and y are greater than z.” You may be tempted to write this as x && y > z /* invalid logical expression */

21 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-21 Figure 4.3 Range of True Values for z > x || x > y

22 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-22 Comparing Characters the digit characters and letters are ordered as expected (that is, '0'<'1'<'2'<... <'8'<'9' and 'a'<'b'<'c'... <'y'<'z').

23 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-23 Logical Assignment Use assignment statements to set such variables to true (a nonzero value) or false (0). Example –int age; /* input - a person's age */ char gender; /* input - a person's gender */ int senior_citizen; /* logical - indicates senior status */ –senior_citizen = (age >= 65); /* Set senior status */ –!senior_citizen –senior_citizen && gender == 'M'

24 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-24 Logical Assignment (Cont’) Example –in_range = (n > -10 && n < 10); –is_letter = ('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z'); Example –even = (n % 2 == 0);

25 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-25 DeMorgan’s Theorem The complement of expr1 && expr2 is written as comp1 || comp2, where comp1 is the complement of expr1, and comp2 is the complement of expr2. The complement of expr1 || expr2 is written as comp1 && comp2, where comp1 is the complement of expr1, and comp2 is the complement of expr2. age > 25 && (status == 'S' || status == 'D') –Complement: age <= 25 || (status != 'S' && status != 'D')

26 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-26 Complementing a Condition item == SENT –!(item == SENT) –item != SENT The relational operator, =, and so on. Use the ! operator with more complicated expressions. status == 'S' && age > 25 –!(status == 'S' && age > 25) –status != ‘S’ || age <= 25

27 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-27 if Statement with Two Alternatives if (rest_heart_rate > 56) –printf("Keep up your exercise program!\n"); else –printf("Your heart is in excellent health!\n"); flowchart –a diagram that show the step-by-step execution of a control structure

28 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-28 Figure 4.4 Flowcharts of if Statements with (a) Two Alternatives and (b) One Alternative

29 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-29 if Statement with Two Alternatives (Cont’)

30 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-30 if Statement with One Alternative /* Multiply Product by a nonzero X */ if (x != 0.0) product = product * x;

31 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-31 Program Style Format of the if Statement Indenting statement T and statement F to improve program readability.

32 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-32 if Statements with Compound Statements computes the population growth from yesterday to today as a percentage of yesterday’s population. if (pop_today > pop_yesterday) { growth = pop_today - pop_yesterday; growth_pct = * growth / pop_yesterday; printf("The growth percentage is %.2f\n", growth_pct); }

33 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-33 if Statements with Compound Statements (Cont’) if (ctri <= MAX_SAFE_CTRI) { printf("Car #%d: safe\n", auto_id); safe = safe + 1; } else { printf("Car #%d: unsafe\n", auto_id); unsafe = unsafe + 1; } If you omit the braces enclosing the compound statements, the if statement would end after the first printf call. The compiler would mark the keyword else as an error. –if (ctri <= MAX_SAFE_CTRI) printf("Car #%d: safe\n", auto_id); safe = safe + 1; else { printf("Car #%d: unsafe\n", auto_id); unsafe = unsafe + 1; }

34 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-34 Program Style Writing if Statements with Compound True or False Statements The placement of the braces is a matter of personal preference. –The form shown in the previous example. if (condition) { true task } else { false task }

35 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-35 Tracing an if Statement hand trace (desk check) –step-by-step simulation of an algorithm’s execution For special situations, what would happen if x were equal to y?

36 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-36 Tracing an if Statement (Cont’)

37 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-37 Errors for the if statements Missing parentheses –if crsr_or_frgt == 'C‘ { printf("Cruiser\n"); printf("Combat ship\n"); } Missing braces –if (crsr_or_frgt == 'C‘) printf("Cruiser\n"); printf("Combat ship\n");

38 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-38 Errors for the if statements (Cont’d) improper placement of ; –if (crsr_or_frgt == 'C'); { printf("Cruiser\n"); printf("Combat ship\n"); } improper placement of else –if (crsr_or_frgt == 'C') printf("Cruiser\n"); else printf("Combat ship\n");

39 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-39 Decision Steps in Algorithms CASE STUDY Water Bill Problem –computes a customer’s water bill –$35 water demand charge –$1.10 for every thousand gallons used –$2 late charge

40 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-40 ANALYSIS and DATA REQUIREMENTS Problem Constants –DEMAND_CHG /* basic water demand charge */ –PER_1000_CHG 1.10 /* charge per thousand gallons used */ –LATE_CHG 2.00 /* surcharge on an unpaid balance */ Problem Inputs –int previous /* meter reading from previous quarter in thousands of gallons */ –int current /* meter reading from current quarter */ –double unpaid /* unpaid balance of previous bill */

41 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-41 ANALYSIS and DATA REQUIREMENTS (Cont’) Problem Outputs –double bill /* water bill */ –double use_charge /* charge for actual water use */ –double late_charge /* charge for nonpayment of part of previous balance */ Relevant Formulas –water bill = demand charge + use charge + unpaid balance + applicable late charge

42 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-42 DESIGN and INITIAL ALGORITHM 1.Display user instructions. 2.Get data: unpaid balance, previous and current meter readings. 3.Compute use charge. 4.Determine applicable late charge. 5.Figure bill amount. 6.Display the bill amount and charges.

43 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-43 Figure 4.6 Structure Chart for Water Bill Problem

44 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-44 ANALYSIS AND DESIGN OF COMP_USE_CHARGE DATA REQUIREMENTS FOR COMP_USE_CHARGE –Input Parameters int previous /* meter reading from previous quarter in thousands of gallons */ int current /* meter reading from current quarter */ –Return Value double use_charge /* charge for actual water use */ –Program Variable int used /* thousands of gallons used this quarter */ –Relevant Formulas used = current meter reading - previous meter reading use charge = used × charge per thousand gallons

45 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-45 ANALYSIS AND DESIGN OF COMP_USE_CHARGE (Cont’) ALGORITHM FOR COMP_USE_CHARGE 1.used is current - previous 2.use_charge is used * PER_1000_CHG

46 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-46 ANALYSIS AND DESIGN OF COMP_USE_CHARGE DATA REQUIREMENTS FOR COMP_LATE_CHARGE –Input Parameter double unpaid /* unpaid balance of previous bill */ –Return Value double late_charge /* charge for nonpayment of part of previous balance */

47 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-47 ANALYSIS AND DESIGN OF COMP_USE_CHARGE (Cont’) pseudo code –a combination of English phrases and C constructs to describe algorithm steps ALGORITHM FOR COMP_LATE_CHARGE –if unpaid > 0 assess late charge else assess no late charge

48 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-48 ANALYSIS AND DESIGN OF DISPLAY_BILL DATA REQUIREMENTS FOR DISPLAY_BILL –Input Parameters double late_charge /* charge for nonpayment of part of previous balance */ double bill /* bill amount */ double unpaid /* unpaid balance */ ALGORITHM FOR DISPLAY_BILL 1.if late_charge > 0 display late charge and unpaid balance 2.Display the bill amount.

49 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-49 IMPLEMENTATION To write each function subprogram, declare all identifiers listed in the function data requirements as either formal parameters or local variables, depending on how the identifier is used by the function. After you write each function heading, copy it into the function prototype area preceding function main.

50 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-50 Figure 4.7 Program for Water Bill Problem

51 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-51 Figure 4.7 Program for Water Bill Problem (cont’d)

52 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-52 Figure 4.7 Program for Water Bill Problem (cont’d)

53 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-53 Figure 4.7 Program for Water Bill Problem (cont’d)

54 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-54 Figure 4.8 Sample Run of Water Bill Program


Download ppt "Chapter 4 Selection Structures: if and switch Statements Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering."

Similar presentations


Ads by Google