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

Slides:



Advertisements
Similar presentations
Selection Structures: if and switch Statements
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Selective Structures.
Chapter 6 Modular Programming J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
1 ICS103 Programming in C Ch4: Selection Structures.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS
Chapter 4 Selection Structures: if and switch Statements.
Chapter 4 Selection Structures: if and switch Statements Instructor: Alkar / Demirer.
Control Structures 4 Control structures control the flow of execution of a program 4 The categories of control structures are: –Sequence –Selection –Repetition.
1 Selection in C. 2 If / else if statement:  The else part of an if statement can be another if statement. if (condition) … else if (condition) … else.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Lab 6 rOperators l Relational Operators l Equality Operators l Logical Operators rIf statement l One Alternative l With Compound Statement l Nested If.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
CS 201 Selection Structures (2) and Repetition
1 CS 201 Selection Structures (1) Debzani Deb. 2 Error in slide: scanf Function scanf(“%lf”, &miles); function name function arguments format string variable.
C++ for Engineers and Scientists Third Edition
1 ICS103 Programming in C Lecture 6: Selection Structures.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 4: Selection Structures: if and switch Statements Problem Solving.
Selection in C.
Chapter 4 Selection Structures: if and switch Statements Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
19/5/2015CS150 Introduction to Computer Science 1 Announcements  1st Assignment due next Monday, Sep 15, 2003  1st Exam next Friday, Sep 19, 2003  1st.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 2 Overview of C Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
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.
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 Selection Structures: if and switch Statements Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Selection Structures: if and switch Statements Problem Solving,
(4-2) Selection Structures in C H&K Chapter 4 Instructor - Andrew S. O’Fallon CptS 121 (September 16, 2015) Washington State University.
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.
Chapter 8 Arrays Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University of.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Chapter 5 Repetition and Loop Statements J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
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.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
chap4 Chapter 4 Selection Structures: if and switch Statements.
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.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
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 : Selection Structures: if and switch statement By Suraya Alias.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Lesson #4 Logical Operators and Selection Statements.
Lesson #4 Logical Operators and Selection Statements.
CHAPTER 5: SELECTION STRUCTURES: if and switch STATEMENTS
CNG 140 C Programming (Lecture set 3)
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.
The Selection Structure
CHAPTER 5: SELECTION STRUCTURES: if and switch STATEMENTS
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Making Decisions.
Selection Structures: if and switch Statements
1) C program development 2) Selection structure
Chapter 4: Selection Structures: if and switch Statements
ICS103: Programming in C 4: Selection Structures
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-4 Control Structures (Cont’) selection control structure –a control structure that chooses among alternative program statements

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-7 Relational and Equality Operators (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-8 Relational and Equality Operators (Cont’)

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 <= <= 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-11 Logical Operators (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-12 Logical Operators (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-13 Logical Operators (Cont’)

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-15 Operator Precedence (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-16 Operator Precedence (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-17 Figure 4.1 Evaluation Tree and Step-by- Step Evaluation for !flag || (y + z >= x - z)

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-19 Figure 4.2 Range of True Values for min <= x && x <= max

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-21 Figure 4.3 Range of True Values for z > x || x > y

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-22 Comparing Characters the digit characters and letters are ordered as expected (that is, '0'<'1'<'2'<... <'8'<'9' and 'a'<'b'<'c'... <'y'<'z').

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-27 if Statement with Two Alternatives if (rest_heart_rate > 56) –printf("Keep up your exercise program!\n"); else –printf("Your heart is in excellent health!\n"); flowchart –a diagram that show the step-by-step execution of a control structure

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-28 Figure 4.4 Flowcharts of if Statements with (a) Two Alternatives and (b) One Alternative

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-29 if Statement with Two Alternatives (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-30 if Statement with One Alternative /* Multiply Product by a nonzero X */ if (x != 0.0) product = product * x;

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-31 Program Style Format of the if Statement Indenting statement T and statement F to improve program readability.

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 = * 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-35 Tracing an if Statement hand trace (desk check) –step-by-step simulation of an algorithm’s execution For special situations, what would happen if x were equal to y?

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-36 Tracing an if Statement (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-37 Errors for the if statements Missing parentheses –if crsr_or_frgt == 'C‘ { printf("Cruiser\n"); printf("Combat ship\n"); } Missing braces –if (crsr_or_frgt == 'C‘) printf("Cruiser\n"); printf("Combat ship\n");

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 /* 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-43 Figure 4.6 Structure Chart for Water Bill Problem

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-45 ANALYSIS AND DESIGN OF COMP_USE_CHARGE (Cont’) ALGORITHM FOR COMP_USE_CHARGE 1.used is current - previous 2.use_charge is used * PER_1000_CHG

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.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-50 Figure 4.7 Program for Water Bill Problem

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-51 Figure 4.7 Program for Water Bill Problem (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-52 Figure 4.7 Program for Water Bill Problem (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-53 Figure 4.7 Program for Water Bill Problem (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-54 Figure 4.8 Sample Run of Water Bill Program