Presentation is loading. Please wait.

Presentation is loading. Please wait.

Selection Structures: if and switch Statements

Similar presentations


Presentation on theme: "Selection Structures: if and switch Statements"— Presentation transcript:

1 Selection Structures: if and switch Statements
Chapter 4 Selection Structures: if and switch Statements Dr. J.-Y. Pan Dept. Comm. Eng. Nat. Chung Cheng Univ. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

2 Outline Conditions and if statement Case study: (Decision, Data flow) Water Bill problem Case study: (Modified with changed spec) Water Bill with Conservation Requirement Nested if statements Switch

3 Control Structures Control the flow of execution in a program or function. Combine individual instruction into a single logical unit with one entry point and one exit point. Instructions are organized into three kinds of control structures to control execution flow: sequence, selection, and repetition.

4 Compound Statement A group of statements bracketed by {and} that are executed sequentially. { statement 1; statement 2; : statement n; }

5 Control Statement (先偷偷看一下 )
Conditional/Selection statements the if statements the switch statements Repetition statements the for statements the while statements the do-while statements

6 An expression that is either
Conditions A program chooses among alternative statements by testing the value of key variables. An expression that is either false (represented by 0) or true (usually represented by 1)

7 Relational and Equality operators

8

9 Logical Operators With the three logical operations-- && (and), ||(or), !(not) —we can form more complicated conditions or logical expressions. 家眷 補助: 大熱天:

10 Logical Operators The logical operators perform logical operations
! Logical not (TRUE if the operand is FALSE) && Logical and (TRUE if both operand are TRUE) || Logical or (TRUE if either or both operands are TRUE)

11 Not, plus sign, minus sign, and address of
Operator Precedence Not, plus sign, minus sign, and address of

12 Figure 4. 1 Evaluation Tree and Step-by-Step Evaluation for
Figure 4.1 Evaluation Tree and Step-by-Step Evaluation for !flag || (y + z >= x - z)

13 Short-Circuit Evaluation
The evaluation of a Boolean expression stops as soon as its answer is known. This style of evaluation is called short-circuit evaluation. Stopping evaluation of a logical expression as soon as its value can be determined. (0 && ?) …… True or false? (1 || ?) …… True or false? Figure 4.1

14 Writing English Conditions in C
Figure 4.2 Range of True Values for min <= x && x <= max Figure 4.3 Range of True Values for z > x || x > y x = 3.0, y = 4.0, z = 2.0

15 Comparing Characters Expression Value ‘9’ >= ‘0’ 1(true)
‘a’ < ‘e’ ‘B’ <= ‘A’ 0(false) ‘Z’ == ‘z’ ‘a’ <= ‘A’ system dependent 0(false, in ascii) ‘a’ <= ch && ch <= ‘z’ 1(true) if ch is a lowercase letter

16 Complementing a Condition
DeMorgan’s Theorem The complement of expr1 && expr2  comp1 || comp2 The complement of expr1 || expr2  comp1 && comp2 Example (Example 4.7 & 4.8) age > 25 && (status == ‘S’ || status == ‘D’) age <= 25 || (status != ‘S’ && status != ‘D’)

17 The if statements The if statement is used to express alternations
if (bool-expr) stmt1 else stmt2 where the else clause is optional The bool-expr is evaluated. If it is TRUE, stmt1 is executed. If it is FALSE and if there is an else clause , stmt2 is executed instead.

18 Figure 4.4 Flowcharts of if Statements with (a) Two Alternatives and (b) One Alternative

19 An Example #include <stdio.h> main( ) { int score;
printf (“score =?”); scanf (“%d”, & score); If (score>=60) printf (“ pass!\n”); else printf (“ fail! \n ”); }

20 Figure 4.5 Example: if Statement to Order x and y

21 Table 4.9 Tracing an if Statement
Statement Part x y temp Effect 12.5 5.0 ? if (x>y) { 12.5>5.0 is true. temp = x ; Store old x in temp. x = y ; Store y in x. y = temp ; Store old x in y.

22 Four if-statements forms
The Single-line if statements If (bool-expr) stmt; The Multi-line if statements If (bool-expr) { stmt; } The If-else statements If (bool-expr) { stmtT; } else { stmtF; } The Cascading if statements If(bool-expr1) { stmt1; } else if (bool-expri ) { stmtsi; } else { stmtsnone; }

23 Decision steps in algorithms
Algorithm steps that select from a choice of actions are called decision steps. Case study: water bill problem This case contains decision steps to compute and display a customer’s water bill based on usage.

24 Case study water bill problem
滯納費 使用費 逾期未繳 基本費

25

26 Case Study :Water Bill Problems (cont)
Design (Figure 4.6) 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.

27 Figure 4.6 Structure Chart for Water Bill Problem
Data flow 請由這開始看 所有費用相加

28 Case Study :Water Bill Problems (cont) Analysis and Design of COMP_USE_CHARGE
Input parameters int previous int current Return value double use_charge Program variable int used Relevant formulas used = current meter reading – previous meter reading use charge = used x charge per thousand gallons

29 Case Study :Water Bill Problems (cont) Analysis and Design of COMP_USE_CHARGE
Algorithm for COMP_USE_CHARGE 1. used is current – previous 2. use charge = used x charge per thousand gallons

30 Algorithm for COMP_LATE_CHARGE
Case Study:Water Bill Problems (cont) Analysis and Design of COMP_LATE_CHARGE Input parameter double unpaid Return value double late_charge Algorithm for COMP_LATE_CHARGE 1. if unpaid > 0 assess late charge else assess no late charge pseudocode a combination of English and C constructs to describe algorithm steps

31 Algorithm for DISPLAY_BILL
Case Study:Water Bill Problems (cont) Analysis and Design of DISPLAY_BILL Input parameters double late_charge double bill double unpaid Algorithm for DISPLAY_BILL 1. if late_charge > 0 display late charge and unpaid balance 2. Display the bill amount.

32 Figure 4.7 Program for Water Bill Problem
Constant macros

33 Figure 4.7 Program for Water Bill Problem (cont’d)

34 Figure 4.7 Program for Water Bill Problem (cont’d)
Cohesive Function: Performs a single operation

35 Figure 4.7 Program for Water Bill Problem and Sample Run

36 Figure 4.8 Sample Run of Water Bill Program

37 Consistent use of names in functions
Program Style Consistent use of names in functions Avoid the confusion from using different names to reference the same information Ex. late_charge Cohesive(有結合力的) functions a function that performs a single operation easier to read, write, debug, maintain, reusable Using constant macros to enhance readability and ease maintenance Ex.DEMAND_CHG, PER_1000_CHG, LATE_CHG

38 More problem solving An example of maintenance and update
Often what appears to be a new problem will turn out to be a variation of one that you have already solved . An important skill: ability to recognize one problem is similar to another solved earlier If the original program is well designed and modular, you can accommodate changing spec with minimum effort

39 Case Study:Water Bill with Conservation Requirement
<Step 1> Problem We need to modify the water bill program so that customers who fail to meet conservation requirements are charged for all their water use at twice the rate of customers who meet the guidelines. Residents of this water district are required to use no more than 95% of the amount of water they used in the same quarter last year in order to qualify for the lower use rate of $1.10 per thousand gallons.

40 Case Study:Water Bill with Conservation Requirement (cont)
<Step 2> Analysis (Additions to data requirements) Problem constants OVER_CHG_RATE 2.0 CONSERV_RATE 95 Problem inputs int use_last_year

41 Case Study:Water Bill with Conservation Requirement (cont)
<Step 3> Algorithm for COMP_USE_CHANGE 1. used is current – previous 2. if guidelines are met use_charge is used*PER_1000_CHANGE else notify customer of overuse use_charge is used*overuse_chg_rate * PER_1000_CHANGE (Figure 4.9)

42 Figure 4.9( CASE STUDY ) Function comp_use_charge Revised

43 4.7 Nested if statements and multiple-alternative decisions

44 4.7.2 Multiple-Alternative Decision Form of Nested if
Syntax: if (condition1) statement1 else if (condition2) statement2 . else if (conditionn) statementn else statemente Example: if (x>0) num_pos = num_pos +1 else if (x<0) num_neg = num_neg +1 else num_zero = num_zero+1

45 Example 4.17 Computing tax Use a multiple-alternative if statement to implement a decision table that describes several alternatives. (Figure 4.10) Salary Range($) Base Tax($) Percentage of Excess , 0.00 15 15, ,999.99 2,250.00 18 30, ,999.99 5,400.00 22 50, ,999.99 11,000.00 27 80, ,000.00 21,600.00 33

46 Figure 4.10 Function comp_tax
Salary = $25000

47 Example 4.19 Warning signal controller (Figure 4.11)
Control the warning signs at the exists of major tunnels. If roads are slick, you want to advise drivers that stopping times are doubled or quadrupled, depending on whether the roads are wet or icy. Access to current temperature for checking whether the temperature is below or above freezing.

48 Figure 4.11 Flowchart of Road Sign Decision Process

49 Example 4.19 (cont) if (road_status == ‘S’ ) if (temp >0){
printf(“Wet roads ahead\n”); printf(“Stopping time doubled\n”); }else { printf(“Icy roads ahead\n”); printf(“Stopping time quardrupled\n”); } else printf(“Drive carefully!\n”); 假如 else沒了

50 The switch statement The switch statement is especially useful when the selection is base in the value of a single variable or of a simple expression (called the controlling expression) The value of this expression may be of type int or char ,but not of type double or string.

51

52 An Example #include <stdio.h> int main(void) { int cardRank;
printf (“cardRank=?) ; scanf(“%d”,&cardRank); switch (cardRank) { case1:printf(“Ace\n”);break; case11:printf(“Jack\n”);break; case12:printf(“Queen\n”);break; case13:printf(King\n”);break; default:printf(“%d\n”,cardRank);break; }

53 Figure 4.12 Example of a switch Statement with Type char Case Labels

54 Common programming errors(1/4)
When testing for equality , be sure to use the“ == “operator instead of the“ =“ operator . This error is extremely common if (x==0) {…} if (x=0) {…} /*always FALSE */ else跟最近的if成對,如果不是,記得用{ } Multiple-alternative, 舉例: leap year

55 Common programming errors(2/4)
Be careful when using logical operators because human languages can be somewhat funny in expressing logic “ x is not equal to either 2 or 3 ” if (x!=2 || x!=3) {…} if (!(x==2 || x==3)) {…} if (x!=2&&x!=3) {..}

56 Common programming errors(3/4)
To test whether a number is in a particular range ,it is not sufficient to combine relational operators , as is conventional in mathematics 0 < x < 1 0 The two part of the conditon must be written explicity using && ( 0 < x ) && ( x < 10 )

57 Common programming errors(4/4)
In switch statement, control expression and case labels are of the same permitted type (int or char but not double) “default” if required Each alternative is ended by a break


Download ppt "Selection Structures: if and switch Statements"

Similar presentations


Ads by Google