Chapter 4 Selection Structures if and switch Statements

  • Slides: 57
Download presentation
Chapter 4 Selection Structures: if and switch Statements Dr. J. -Y. Pan Dept. Comm.

Chapter 4 Selection Structures: if and switch Statements Dr. J. -Y. Pan Dept. Comm. Eng. Nat. Chung Cheng Univ. http: //ant. comm. ccu. edu. tw jypan@comm. ccu. edu. tw Copyright © 2004 Pearson Addison-Wesley. All rights reserved.

Outline v Conditions and if statement ²Short-circuit evaluation ²De. Morgan’s Theorem v Case study:

Outline v Conditions and if statement ²Short-circuit evaluation ²De. Morgan’s Theorem v Case study: (Decision, Data flow) Water Bill problem v Case study: (Modified with changed spec) Water Bill with Conservation Requirement v Nested if statements v Switch 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Control Structures v. Control the flow of execution in a program or function. v.

Control Structures v. Control the flow of execution in a program or function. v. Combine individual instruction into a single logical unit with one entry point and one exit point. v. Instructions are organized into three kinds of control structures to control execution flow: sequence, selection, and repetition. 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Compound Statement v A group of statements bracketed by {and} that are executed sequentially.

Compound Statement v A group of statements bracketed by {and} that are executed sequentially. { statement 1; statement 2; : : statement n; } 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Control Statement (先偷偷看一下 ) v. Conditional/Selection statements ²the if statements ²the switch statements v.

Control Statement (先偷偷看一下 ) v. Conditional/Selection statements ²the if statements ²the switch statements v. Repetition statements ²the for statements ²the while statements ²the do-while statements 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Conditions v. A program chooses among alternative statements by testing the value of key

Conditions v. A program chooses among alternative statements by testing the value of key variables. v. An expression that is either ² false (represented by 0) ²or true (usually represented by 1) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Relational and Equality operators 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Relational and Equality operators 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Logical Operators v. With the three logical operations-- && (and), ||(or), !(not) —we can

Logical Operators v. With the three logical operations-- && (and), ||(or), !(not) —we can form more complicated conditions or logical expressions. 家眷 補助: 大熱天: 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Logical Operators v The logical operators perform logical operations ! Logical not (TRUE if

Logical Operators v 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) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Operator Precedence Not, plus sign, minus sign, and address of 中正大學通訊 程系 潘仁義老師 Advanced

Operator Precedence Not, plus sign, minus sign, and address of 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Figure 4. 1 Evaluation Tree and Step-by-Step Evaluation for !flag || (y + z

Figure 4. 1 Evaluation Tree and Step-by-Step Evaluation for !flag || (y + z >= x - z) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Short-Circuit Evaluation v. The evaluation of a Boolean expression stops as soon as its

Short-Circuit Evaluation v. The evaluation of a Boolean expression stops as soon as its answer is known. This style of evaluation is called short-circuit evaluation. v. 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 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Writing English Conditions in C Figure 4. 2 Range of True Values for min

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 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Comparing Characters Expression Value ‘ 9’ >= ‘ 0’ 1(true) ‘a’ < ‘e’ 1(true)

Comparing Characters Expression Value ‘ 9’ >= ‘ 0’ 1(true) ‘a’ < ‘e’ 1(true) ‘B’ <= ‘A’ 0(false) ‘Z’ == ‘z’ 0(false) ‘a’ <= ‘A’ system dependent 0(false, in ascii) ‘a’ <= ch && ch <= ‘z’ 1(true) if ch is a lowercase letter 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Complementing a Condition v. De. Morgan’s Theorem ²The complement of expr 1 && expr

Complementing a Condition v. De. Morgan’s Theorem ²The complement of expr 1 && expr 2 v comp 1 || comp 2 ²The complement of expr 1 || expr 2 v comp 1 && comp 2 v. Example (Example 4. 7 & 4. 8) age > 25 && (status == ‘S’ || status == ‘D’) age <= 25 || (status != ‘S’ && status != ‘D’) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

The if statements v. The if statement is used to express alternations if (bool-expr)

The if statements v. The if statement is used to express alternations if (bool-expr) stmt 1 else stmt 2 where the else clause is optional v. The bool-expr is evaluated. ²If it is TRUE, stmt 1 is executed. ²If it is FALSE and if there is an else clause , stmt 2 is executed instead. 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Figure 4. 4 Flowcharts of if Statements with (a) Two Alternatives and (b) One

Figure 4. 4 Flowcharts of if Statements with (a) Two Alternatives and (b) One Alternative 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

An Example #include <stdio. h> main( ) { int score; printf (“score =? ”);

An Example #include <stdio. h> main( ) { int score; printf (“score =? ”); scanf (“%d”, & score); If (score>=60) printf (“ pass!n”); else printf (“ fail! n ”); } 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Figure 4. 5 Example: if Statement to Order x and y 中正大學通訊 程系 潘仁義老師

Figure 4. 5 Example: if Statement to Order x and y 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Table 4. 9 Tracing an if Statement Part x y 12. 5 5. 0

Table 4. 9 Tracing an if Statement Part x y 12. 5 5. 0 if (x>y) { y = temp ; Effect ? 12. 5>5. 0 is true. temp = x ; x=y; temp 12. 5 Store old x in temp. 5. 0 Store y in x. 12. 5 Store old x in y. 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Four if-statements forms v. The Single-line if statements ²If (bool-expr) stmt; v. The Multi-line

Four if-statements forms v. The Single-line if statements ²If (bool-expr) stmt; v. The Multi-line if statements ²If (bool-expr) { stmt; } v. The If-else statements ²If (bool-expr) { stmt. T; } else { stmt. F; } v. The Cascading if statements ²If(bool-expr 1) { stmt 1; } else if (bool-expri ) { stmtsi; } else { stmtsnone; } 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Decision steps in algorithms v. Algorithm steps that select from a choice of actions

Decision steps in algorithms v. Algorithm steps that select from a choice of actions are called decision steps. v. Case study: water bill problem This case contains decision steps to compute and display a customer’s water bill based on usage. 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Case study water bill problem 滯納費 基本 費 使用費 逾期未 繳 中正大學通訊 程系 潘仁義老師

Case study water bill problem 滯納費 基本 費 使用費 逾期未 繳 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Case Study :Water Bill Problems (cont) v. Design (Figure 4. 6) ²Initial algorithm 1.

Case Study :Water Bill Problems (cont) v. 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. 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Figure 4. 6 Structure Chart for Water Bill Problem 請由這開始看 Data flow 所有費用相 中正大學通訊

Figure 4. 6 Structure Chart for Water Bill Problem 請由這開始看 Data flow 所有費用相 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Case Study :Water Bill Problems (cont) Analysis and Design of COMP_USE_CHARGE v Input parameters

Case Study :Water Bill Problems (cont) Analysis and Design of COMP_USE_CHARGE v Input parameters ²int previous ²int current v Return value ²double use_charge v Program variable ²int used v Relevant formulas ²used = current meter reading – previous meter reading ²use charge = used x charge per thousand gallons 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Case Study :Water Bill Problems (cont) Analysis and Design of COMP_USE_CHARGE v Algorithm for

Case Study :Water Bill Problems (cont) Analysis and Design of COMP_USE_CHARGE v Algorithm for COMP_USE_CHARGE 1. used is current – previous 2. use charge = used x charge per thousand gallons 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Case Study:Water Bill Problems (cont) Analysis and Design of COMP_LATE_CHARGE v. Input parameter ²double

Case Study:Water Bill Problems (cont) Analysis and Design of COMP_LATE_CHARGE v. Input parameter ²double unpaid v. Return value ²double late_charge v. 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 Technology Lab 中正大學通訊 程系 潘仁義老師 Advanced Network

Case Study:Water Bill Problems (cont) Analysis and Design of DISPLAY_BILL v. Input parameters ²double

Case Study:Water Bill Problems (cont) Analysis and Design of DISPLAY_BILL v. Input parameters ²double late_charge ²double bill ²double unpaid v. Algorithm for DISPLAY_BILL ² 1. if late_charge > 0 display late charge and unpaid balance ² 2. Display the bill amount. 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Figure 4. 7 Program for Water Bill Problem Constant macros 中正大學通訊 程系 潘仁義老師 Advanced

Figure 4. 7 Program for Water Bill Problem Constant macros 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Figure 4. 7 Program for Water Bill Problem (cont’d) 中正大學通訊 程系 潘仁義老師 Advanced Network

Figure 4. 7 Program for Water Bill Problem (cont’d) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Figure 4. 7 Program for Water Bill Problem (cont’d) Cohesive Function: Performs a single

Figure 4. 7 Program for Water Bill Problem (cont’d) Cohesive Function: Performs a single operation 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Figure 4. 7 Program for Water Bill Problem and Sample Run 中正大學通訊 程系 潘仁義老師

Figure 4. 7 Program for Water Bill Problem and Sample Run 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Figure 4. 8 Sample Run of Water Bill Program 中正大學通訊 程系 潘仁義老師 Advanced Network

Figure 4. 8 Sample Run of Water Bill Program 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Program Style v. Consistent use of names in functions ²Avoid the confusion from using

Program Style v. Consistent use of names in functions ²Avoid the confusion from using different names to reference the same information ²Ex. late_charge v. Cohesive(有結合力的) functions ²a function that performs a single operation ²easier to read, write, debug, maintain, reusable v. Using constant macros ²to enhance readability and ease maintenance ²Ex. DEMAND_CHG, PER_1000_CHG, LATE_CHG 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

More problem solving An example of maintenance and update v. Often what appears to

More problem solving An example of maintenance and update v. Often what appears to be a new problem will turn out to be a variation of one that you have already solved. v. An important skill: ability to recognize one problem is similar to another solved earlier v. If the original program is well designed and modular, you can accommodate changing spec with minimum effort 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Case Study:Water Bill with Conservation Requirement <Step 1> Problem ²We need to modify the

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. 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Case Study:Water Bill with Conservation Requirement (cont) <Step 2> Analysis (Additions to data requirements)

Case Study:Water Bill with Conservation Requirement (cont) <Step 2> Analysis (Additions to data requirements) ²Problem constants v. OVER_CHG_RATE 2. 0 v. CONSERV_RATE 95 ²Problem inputs vint use_last_year 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Case Study:Water Bill with Conservation Requirement (cont) <Step 3> Algorithm for COMP_USE_CHANGE ² 1.

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) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Figure 4. 9( CASE STUDY ) Function comp_use_charge Revised 中正大學通訊 程系 潘仁義老師 Advanced Network

Figure 4. 9( CASE STUDY ) Function comp_use_charge Revised 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

4. 7 Nested if statements and multiplealternative decisions 中正大學通訊 程系 潘仁義老師 Advanced Network Technology

4. 7 Nested if statements and multiplealternative decisions 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

4. 7. 2 Multiple-Alternative Decision Form of Nested if Syntax: if (condition 1) statement

4. 7. 2 Multiple-Alternative Decision Form of Nested if Syntax: if (condition 1) statement 1 else if (condition 2) statement 2. . 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 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Example 4. 17 Computing tax v Use a multiple-alternative if statement to implement a

Example 4. 17 Computing tax v Use a multiple-alternative if statement to implement a decision table that describes several alternatives. (Figure 4. 10) Salary Range($) 0. 00 - 1, 4999. 99 15, 000. 00 - 29, 999. 99 30, 000. 00 - 49, 999. 99 50, 000. 00 - 79, 999. 99 80, 000. 00 - 150, 000. 00 Base Tax($) Percentage of Excess 0. 00 15 2, 250. 00 18 5, 400. 00 22 11, 000. 00 21, 600. 00 27 33 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Figure 4. 10 Function comp_tax Salary = $25000 中正大學通訊 程系 潘仁義老師 Advanced Network Technology

Figure 4. 10 Function comp_tax Salary = $25000 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Example 4. 19 Warning signal controller (Figure 4. 11) v. Control the warning signs

Example 4. 19 Warning signal controller (Figure 4. 11) v. Control the warning signs at the exists of major tunnels. v. 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. v. Access to current temperature for checking whether the temperature is below or above freezing. 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Figure 4. 11 Flowchart of Road Sign Decision Process 中正大學通訊 程系 潘仁義老師 Advanced Network

Figure 4. 11 Flowchart of Road Sign Decision Process 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Example 4. 19 (cont) if (road_status == ‘S’ ) if (temp >0){ printf(“Wet roads

Example 4. 19 (cont) if (road_status == ‘S’ ) if (temp >0){ printf(“Wet roads aheadn”); 假如 else沒 printf(“Stopping time doubledn”); 了 }else { printf(“Icy roads aheadn”); printf(“Stopping time quardrupledn”); } else printf(“Drive carefully!n”); 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

The switch statement v. The switch statement is especially useful when the selection is

The switch statement v. 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) v. The value of this expression may be of type int or char , but not of type double or string. 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

An Example #include <stdio. h> int main(void) { int card. Rank; printf (“card. Rank=?

An Example #include <stdio. h> int main(void) { int card. Rank; printf (“card. Rank=? ) ; scanf(“%d”, &card. Rank); switch (card. Rank) { case 1: printf(“Acen”); break; case 11: printf(“Jackn”); break; case 12: printf(“Queenn”); break; case 13: printf(Kingn”); break; default: printf(“%dn”, card. Rank); break; } } 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Figure 4. 12 Example of a switch Statement with Type char Case Labels 中正大學通訊

Figure 4. 12 Example of a switch Statement with Type char Case Labels 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Common programming errors(1/4) v. When testing for equality , be sure to use the“

Common programming errors(1/4) v. 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 */ velse跟最近的if成對,如果不是,記得用{ } v. Multiple-alternative, 舉例: leap year 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Common programming errors(2/4) v. Be careful when using logical operators because human languages can

Common programming errors(2/4) v. 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) {. . } 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Common programming errors(3/4) v. To test whether a number is in a particular range

Common programming errors(3/4) v. 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 < 10 v. The two part of the conditon must be written explicity using && ( 0 < x ) && ( x < 10 ) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab

Common programming errors(4/4) v. In switch statement, control expression and case labels are of

Common programming errors(4/4) v. In switch statement, control expression and case labels are of the same permitted type (int or char but not double) v“default” if required v. Each alternative is ended by a break 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab