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

Slides:



Advertisements
Similar presentations
Selection Structures: if and switch Statements
Advertisements

ICS103: Programming in C 4: Selection Structures Muhamed F. Mudawar.
Chapter 4 Selection Structures: if and switch Statements Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering.
BBS514 Structured Programming (Yapısal Programlama)1 Selective Structures.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Chapter 4 Selection Structures: if and switch Statements.
Chapter 4 Selection Structures: if and switch Statements Instructor: Alkar / Demirer.
Chapter 7 Simple Date Types Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪.
Chapter 6 Modular Programming Dr. J.-Y. Pan Dept. Comm. Eng. Nat. Chung Cheng Univ.
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab Common Programming Errors Syntax Errors (Figure 2.15) –missing semicolon at the end of the variable.
Chapter 3 Top-Down Design with Functions Dr. J.-Y. Pan Dept. Comm. Eng. Nat. Chung Cheng Univ.
true (any other value but zero) false (zero) expression Statement 2
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
1 CS 201 Selection Structures (1) Debzani Deb. 2 Error in slide: scanf Function scanf(“%lf”, &miles); function name function arguments format string variable.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Review Ch 1~2 Overview of Computers and C Programming Dr. J.-Y. Pan Dept. Comm. Eng. Nat. Chung Cheng Univ.
C++ for Engineers and Scientists Third Edition
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 4: Selection Structures: if and switch Statements Problem Solving.
Chapter 4 Selection Structures: if and switch Statements Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
1 Chapter Four Boolean Expressions and Control Statements.
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 3 Making Decisions
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Structural Program Development: If, If-Else Outline.
CPS 125: Digital Computation and Programming Selection Structures: if and switch Statements.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 4 Selection Structures: if and switch Statements Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Selection Structures: if and switch Statements Problem Solving,
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Flow of Control Part 1: Selection
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
© The McGraw-Hill Companies, 2006 Chapter 2 Selection.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 3 (2) & 4 September 8 & 10, 2009.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
chap4 Chapter 4 Selection Structures: if and switch Statements.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
IT CS 200: C ONDITION Lect. Napat Amphaiphan. T HE ABILITY TO CONTROL THE FLOW OF YOUR PROGRAM, LETTING IT MAKE DECISIONS ON WHAT CODE TO EXECUTE 2.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Selection Structures: if and switch Statements Problem Solving.
Chapter 4 Selection Structures: if and switch Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
CHAPTER 5: SELECTION STRUCTURES: if and switch STATEMENTS Prepared By: Pn. Nik Maria Nik Mahamood Reference: Hanly, Koffman, C Problem Solving and Program.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 4 : Selection Structures: if and switch statement By Suraya Alias.
Lesson #4 Logical Operators and Selection Statements.
Lesson #4 Logical Operators and Selection Statements.
CHAPTER 5: SELECTION STRUCTURES: if and switch STATEMENTS
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Decisions Chapter 4.
The Selection Structure
CHAPTER 5: SELECTION STRUCTURES: if and switch STATEMENTS
Selection Structures: if and switch Statements
Decision I (if Statement)
Chapter 4: Selection Structures: if and switch Statements
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

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

中正大學通訊工程系 潘仁義老師 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 statements  Switch

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

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

中正大學通訊工程系 潘仁義老師 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 ExpressionValue ‘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 expr 1 && expr 2  comp 1 || comp 2  The complement of expr 1 || expr 2  comp 1 && comp 2  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) stmt 1 else stmt 2 where the else clause is optional  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 Alternative

中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab An Example #include 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 PartxytempEffect ? if (x>y) {12.5>5.0 is true. temp = x ;12.5Store old x in temp. x = y ;5.0Store y in x. y = temp ;12.5Store 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) { stmt T ; } else { stmt F ; }  The Cascading if statements  If(bool-expr 1 ) { stmt 1 ; } else if (bool-expr i ) { stmts i ; } else { stmts none ; }

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

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 – 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  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

中正大學通訊工程系 潘仁義老師 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_CHG

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

中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab Case Study : Water Bill with Conservation Requirement 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) Analysis (Additions to data requirements)  Problem constants  OVER_CHG_RATE 2.0  CONSERV_RATE 95  Problem inputs  int use_last_year

中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab Case Study : Water Bill with Conservation Requirement (cont) 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 Multiple-Alternative Decision Form of Nested if Syntax: if (condition 1 ) statement 1 else if (condition 2 ) statement 2. else if (condition n ) statement n else statement e 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  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 , , , , , , , , , , , , ,

中正大學通訊工程系 潘仁義老師 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 quardrupled\n”); } else printf(“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

An Example #include 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 0  The 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 required  Each alternative is ended by a break