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

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

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

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

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.

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)

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

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 <= 100 0 <= n && n <= 100

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.

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

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

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

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'

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);

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')

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

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 = 100.0 * growth / pop_yesterday; printf("The growth percentage is %.2f\n", growth_pct); }

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; }

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 }

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");

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

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-40 ANALYSIS and DATA REQUIREMENTS Problem Constants –DEMAND_CHG 35.00 /* 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 */

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

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.

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

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

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

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.

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.