Copyright ©2004 Pearson Addison-Wesley. All rights reserved.
Chapter 4Selection Structures: if and switch StatementsDr. J.-Y. Pan Dept. Comm. Eng.Nat. Chung Cheng Univ.http://[email protected]
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Outline
Conditions and if statement Short-circuit evaluation DeMorgan’s Theorem
Case study: (Decision, Data flow) Water Bill problem
Case study: (Modified with changed spec)Water Bill with Conservation Requirement
Nested if statementsSwitch
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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.
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Compound Statement
A group of statements bracketed by {and} that are executed sequentially.
{
statement 1;
statement 2; : :
statement n; }
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Control Statement( 先偷偷看一下 )
Conditional/Selection statements the if statements the switch statements
Repetition statements the for statements the while statements the do-while statements
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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)
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Relational and Equality operators
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Logical Operators
With the three logical operations-- &&(and), ||(or), !(not) —we can form more complicated conditions or logical expressions.
家眷
補助 :
大熱天 :
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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)
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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 >= x - z)
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Short-Circuit EvaluationThe 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
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Writing English Conditions in C
Figure 4.2 Range of True Values for min <= x && x <= max
x = 3.0, y = 4.0, z = 2.0
Figure 4.3 Range of True Values for z > x || x > y
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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
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’)
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
The if statements
The if statement is used to express
alternations
if (bool-expr) stmt1 else stmt2
where the else clause is optionalThe 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.
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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 =?”); 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
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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 ; 12.5 Store old x in temp.
x = y ; 5.0 Store y in x.
y = temp ; 12.5 Store old x in y.
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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; }
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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.
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Case study water bill problem
基本費
使用費 逾期未繳
滯納費
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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.
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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
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
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Case Study : Water Bill Problems (cont) Analysis and Design of COMP_USE_CHARGE
Algorithm for COMP_USE_CHARGE
1. used is current – previous2. 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
Input parameter double unpaid
Return value double late_charge
Algorithm for COMP_LATE_CHARGE1. if unpaid > 0
assess late charge else
assess no late charge pseudocodea combination of English and C constructs to describe algorithm steps
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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.
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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 Technology Lab
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
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 4.8 Sample Run of Water Bill Program
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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_C
HG
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
More problem solvingAn 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
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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) Problem constants
OVER_CHG_RATE 2.0CONSERV_RATE 95
Problem inputsint use_last_year
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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 Technology Lab
4.7 Nested if statements and multiple-alternative decisions
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
4.7.2 Multiple-Alternative Decision Form of Nested if
Syntax:if (condition1)
statement1
else if (condition2)
statement2
.
.else if (conditio
nn)statementn
elsestatemente
Example:
if (x>0) num_pos = num_pos +1else if (x<0) num_neg = num_neg +1else num_zero = num_zero+1
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Example 4.17Computing 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- 1,4999.99 0.00 15
15,000.00- 29,999.99 2,250.00 18
30,000.00- 49,999.99 5,400.00 22
50,000.00- 79,999.99 11,000.00 27
80,000.00- 150,000.00 21,600.00 33
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 4.10 Function comp_tax
Salary = $25000
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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.
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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 ahead\n”);printf(“Stopping time doubled\n
”);}else {
printf(“Icy roads ahead\n”);printf(“Stopping time quardrupl
ed\n”);}
elseprintf(“Drive carefully!\n”);
假如 else 沒了
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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.
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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; }}
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 4.12 Example of a switch Statement with Type char Case Labels
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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) {..}
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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 0The two part of the conditon must be written
explicity using &&
( 0 < x ) && ( x < 10 )
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
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 requiredEach alternative is ended by a break