Chapter 4 Selection Structures: if and switch Statements - PowerPoint PPT Presentation

1 / 51
About This Presentation
Title:

Chapter 4 Selection Structures: if and switch Statements

Description:

An employee's pay is based upon the number of hours worked (to the nearest half ... Weekly hours exceeding 40 are paid at a rate of time and a half. ... – PowerPoint PPT presentation

Number of Views:62
Avg rating:3.0/5.0
Slides: 52
Provided by: michael808
Category:

less

Transcript and Presenter's Notes

Title: Chapter 4 Selection Structures: if and switch Statements


1
Chapter 4 - Selection Structuresif and switch
Statements
Jason C. H. Chen, Ph.D. Professor of MIS School
of Business Administration Gonzaga
University Spokane, WA 99258 chen_at_gonzaga.edu
2
Selection Statements
  • In this chapter we study statements that allow
    alternatives to straight sequential processing.
    In particular
  • if statements (do this only if a condition is
    true)
  • if-else statements (do either this or that)
  • Logical expressions (evaluate to true or false)
  • Boolean operators (not ! and or )

3
4.1 Control Structures
  • Programs must often anticipate a variety of
    situations.
  • Consider an Automated Teller Machine
  • ATMs must serve valid bank customers. They must
    also reject invalid PINs.
  • The code that controls an ATM must permit these
    different requests.
  • Software developers must implement code that
    anticipates all possible transactions.

4
4.2 Logical Expressions

False
False
True
True
5
Boolean Variables
  • bool variable
  • Included with C compiler
  • bool leapYear
  • leapYear true // Non zero return value
  • leapYear false // Zero return value

6
Boolean Expressions
  • Examples (Write T for True, or F for False)
  • int n1 55
  • int n2 75
  • n1 lt n2 // _____
  • n1 gt n2 // _____
  • (n1 35) gt n2 // _____
  • (n1-n2) lt 0.1 // _____
  • n1 n2 // _____

7
Logical Expressions
  • Logical expressions often use these relational
    operators (Table 4.1) p.171

8
Logical Operators
  • Logical operator ( means AND) used in an
    if...else statement
  • ( (tryIt gt 0) (tryIt lt 100) )
  • Logical operator ( means OR) used in an
    if...else statement
  • ( (tryIt gt 0) (tryIt lt 100) )

9
Using
  • Assume tryIt 90,
  • Is tryIt within the range of 0 and 100 ?
  • ( (tryIt gt 0) (tryIt lt 100) )

( ( 90 gt 0) ( 90 lt 100) )
( 1 1 )
1
10
Using
  • Assume tryIt 99
  • Is tryIt outside the range of 0 and 100 ?
  • ( (tryIt lt 0) (tryIt gt 100) )
  • ( ( 99 lt 0) ( 99 gt 100) )
  • ( 0 0 )
  • 0

11
Truth Tables for Boolean Operators
  • Truth tables Logical operators !, ,
  • 1 is a symbol for true
  • 0 is a symbol for false

See Table 4.3 4.5
12
Precedence of Operators
  • Precedence most operators are evaluated
    (grouped) in a left-to-right order
  • a / b / c / d is equivalent to
    (((a/b)/c)/d)
  • Assignment operators group in a right-to-left
    order so the expression
  • x y z 0.0 is equivalent to
    (x(y(z0.0)))

13
Precedence of Operators(Table 4.6 p.174)
Do Example 4.2 (p.172)
14
Boolean Assignment
  • bool same
  • same true
  • Form
  • variable expression
  • Example
  • same (x y)

Exercise 4.2 (p.176)
15
4.3 Introduction to the if Dependent Control
Statement
  • The if is the first statement that alters strict
    sequential control.
  • General form
  • if ( logical-expression )
  • true-part
  • logical-expression any expression that evaluates
    to nonzero (true) or zero (false).
  • In C, almost everything is true or false.

16
if Control Statementswith Two Alternatives
  • The logical expression is evaluated. When true,
    the true-part is executed and the false-part is
    disregarded. When the logical expression is
    false, the false-part executes.
  • General Form
  • if ( logical-expression )
  • true-part
  • else
  • false-part

17
What happens when an if statement executes?
Write in C
  • After the logical expression of the if statement
    evaluates, the true-part executes only if the
    logical expression was true.

False
gross gt100.0
if (gross gt 100.0) net gross-tax else
netgross
True
netgross-tax
netgross
18
Programming Tip
  • Using for is a common mistake. For example
    the following statements are legal
  • int x 25
  • Because assignment statements evaluate to the
  • expression on the right of , x 1 is always
  • 1, which is nonzero, which is true
  • if (x 1) // should be (x 1)

Exercise 4.3 (p.182)
19
4.4 if Statements with Compound Alternatives
  • General form (also known as a block)
  • statement-1
  • statement-2
  • ...
  • statement-N
  • The compound statement groups together many
    statements that are treated as one.

20
Writing Compound Statements
  • if (transactionType 'c')
  • // process check
  • cout ltlt "Check for " ltlt transactionAmount ltlt
    endl
  • balance balance - transactionAmount
  • else
  • // process deposit
  • cout ltlt "Deposit of " ltlt transactionAmount ltlt
    endl
  • balance balance transactionAmount

21
Exercise 4.4 (p.186)
1. Debug syntax errors?
  • If (x gt y)
  • x x 10.0
  • cout ltlt x bigger ltlt endl
  • else
  • cout ltlt x smaller ltlt endl
  • cout ltlt y is ltlt y ltlt endl

2. What is the output when a) x is 5
y is 3

b) x is 6 y is 9
22
Exercise 4.4 (p.186) - cont.
  • If (x gt y)
  • x x 10.0
  • cout ltlt x bigger ltlt endl
  • else
  • cout ltlt x smaller ltlt endl
  • cout ltlt y is ltlt y ltlt endl

What is the output when a) x is 5 y
is 3
b) x is 6 y is 9
23
Break ! (Ch. 4 - Part I)
24
4.5 Decision Steps in Algorithms
  • Algorithm steps that select from a choice of
    actions are called decision steps. The algorithm
    in the following case contains decisions steps to
    compute an employees gross and net pay after
    deductions. The decision steps are coded as if
    statements.
  • Payroll Case Study (p.187)

25
Decision Steps in Algorithms
  • Statement  Your company pays its hourly workers
    once a week. An employees pay is based upon the
    number of hours worked (to the nearest half hour)
    and the employees hourly pay rate. Weekly hours
    exceeding 40 are paid at a rate of time and a
    half. Employees who earn over 100 a week must
    pay union dues of 15 per week. Write a payroll
    program that will determine the gross pay and net
    pay for an employee.

26
Decision Steps in Algorithms
  • Analysis  The problem data include the input
    data for hours worked and hourly pay and two
    required outputs, gross pay and net pay. There
    are also several constants the union dues (15),
    the minimum weekly earnings before dues must be
    paid (100), the maximum hours before overtime
    must be paid (40), and the overtime rate (1.5
    times the usual hourly rate). With this
    information, we can begin to write the data
    requirements for this problem. We can model all
    data using the money (see Section 3.7) and float
    data types.

27
Decision Steps in Algorithms
  • Program Design  The problem solution requires
    that the program read the hours worked and the
    hourly rate before performing any computations.
    After reading these data, we need to compute and
    then display the gross pay and net pay. The
    structure chart for this problem (Figure 4.6)
    shows the decomposition of the original problem
    into five subproblems. We will write three of the
    subproblems as functions. For these three
    subproblems, the corresponding function name
    appears under its box in the structure chart.

28
Decision Steps in Algorithms
  • Display user instructions
  • (function instructUser).
  • Enter hours worked and hourly rate.
  • Compute gross pay (function computeGross).
  • Compute net pay (function computeNet).
  • Display gross pay and net pay.

29
payrollFunction.cpp
5
Output display gross salary, net salary
1
User input hours, hourly_rate
Level - 0
Level - 1
2
3
4
30
Payroll.cpp
  • Program output
  • This program computes gross and net salary.
  • A dues amount of 15.00 is deducted for an
  • employee who earns more than 100.00
  • Overtime is paid at the rate of 1.5 times the
  • regular rate on hours worked over 40
  • Enter hours worked and hourly rate on separate
  • lines after the prompts. Press ltreturngt after
  • typing each number.

31
Payroll.cpp
  • Program output
  • Hours worked 50
  • Hourly rate 6
  • Gross salary is 330.00
  • Net salary is 315.00

Payroll Case Study payroolFunctions.cpp (p.192)
32
// File payrollFunctions_money.cpp (p.192) //
Computes and displays gross pay and net pay given
an hourly // rate and number of hours worked.
Deducts union dues of 15 // if gross salary
exceeds 100 otherwise, deducts no
dues. include ltiostreamgt include
"money.cpp using namespace std // Functions
prototypes ... void instructUser() money
computeGross(float, money) money
computeNet(money) //GLOBAL VARIABLES // max
earnings before dues (dollars) const money
MAX_NO_DUES 100.00 // dues amount
(dollars) const money dues 15.00 // max hours
before overtime const float MAX_NO_OVERTIME
40.0 const float OVERTIME_RATE 1.5 //
overtime rate int main () float hours
// input hours worked float rate
// input hourly pay rate
(dollars) money gross //
output gross pay (dollars) money net
// output net pay (dollars)
//Function Call // Display user instructions.
instructUser() // Enter hours and rate.
cout ltlt "Hours worked " cin gtgt hours
cout ltlt "Hourly rate " cin gtgt rate
//Function Call // Compute gross salary.
gross computeGross(hours, rate) // Compute
net salary. net computeNet(gross) //
Print gross and net. cout ltlt "Gross salary is
" ltlt gross ltlt endl cout ltlt "Net salary is "
ltlt net ltlt endl return 0
33
Funciton instructUser
// Insert lower-level functions here. // ... //
Displays user instructions void instructUser()
cout ltlt "This program computes gross and net
salary." ltlt endl cout ltlt "A dues amount of "
ltlt dues ltlt " is deducted for" ltlt endl cout ltlt
"an employee who earns more than " ltlt MAX_NO_DUES
ltlt endl ltlt endl cout ltlt "Overtime is
paid at the rate of " ltlt OVERTIME_RATE ltlt endl
cout ltlt "times the regular rate for hours worked
over " ltlt MAX_NO_OVERTIME ltlt
endl ltlt endl cout ltlt "Enter hours worked and
hourly rate" ltlt endl cout ltlt "on separate
lines after the prompts." ltlt endl cout ltlt
"Press ltreturngt after typing each number." ltlt
endl ltlt endl // end instructUser
34
Two Functions computeGross computeNet
//Function Definitions // FIND THE GROSS
PAY money computeGross (float hours,
// IN number of hours worked money rate)
// IN hourly pay rate (dollars)
// Local data ... money gross
// RESULT gross pay (dollars) money
regularPay // pay for first 40 hours
money overtimePay // pay for hours in excess
of 40 // Compute gross pay. if (hours gt
MAX_NO_OVERTIME) regularPay
MAX_NO_OVERTIME rate overtimePay
(hours - MAX_NO_OVERTIME)
OVERTIME_RATE rate gross regularPay
overtimePay else gross hours
rate return gross // end computeGross
// FIND THE NET PAY money computeNet (money
gross) // IN gross salary (dollars) //
Local data ... money net // RESULT
net pay (dollars) // Compute net pay. if
(gross gt MAX_NO_DUES) net gross - dues
// deduct dues amount else net gross
// no deductions return net // end
computeNet
35
4.6 Checking the Correctness of an Algorithm
  • Verifying the correctness of an algorithm is a
    critical step in algorithm design and often saves
    hours of coding and testing time.
  • We will now trace the execution of the refined
    algorithm for the payroll problem solved in the
    last section.

36
Checking the Correctness of an Algorithm
  • 1. Display user instructions.
  • 2. Enter hours worked and hourly rate.
  • 3. Compute gross pay.
  • 3.1. If the hours worked exceed 40.0 (max hours
    before overtime)
  • 3.1.1. Compute regularPay.
  • 3.1.2. Compute overtimePay.
  • 3.1.3. Add regularPay to overtimePay to get
    gross.
  • else

37
Checking the Correctness of an Algorithm
  • 3.1.4. Compute gross as hours rate.
  • 4. Compute net pay.
  • 4.1. If gross is larger than 100.00
  • 4.1.1. Deduct the dues of 15.00 from gross
    pay.
  • else
  • 4.1.2. Deduct no dues.
  • 5. Display gross and net pay.

38
4.7 Nested if Statements and Multiple
Alternative Decisions
  • Nested logic is one control structure containing
    another similar control structure.
  • An if...else inside another if...else. e.g. (the
    2nd if is placed on the same line as the 1st)

39
Example of nested logic(p.203)
  • if(x gt 0)
  • numPos numPos 1
  • else
  • if (x lt 0)
  • numNeg numNeg 1
  • else // x equals 0
  • numZero numZero 1

Assume all variables initialized to 0
X numPos numNeg numZero 3.0 _______
_______ _______ -3.6 _______ _______
_______ 4.0 _______ _______ _______
40
Writing a Nested if as a Multiple-Alternative
Decision
  • Nested if statements can become quite complex. If
    there are more than three alternatives and
    indentation is not consistent, it may be
    difficult to determine the logical structure of
    the if statement.

41
Order of Conditions (p.203)
  • if (score gt 60)
  • cout ltlt "Grade is D " ltlt endl
  • else if (score gt 70)
  • cout ltlt "Grade is C " ltlt endl
  • else if (score gt 80)
  • cout ltlt "Grade is B " ltlt endl
  • else if (score gt 90)
  • cout ltlt "Grade is A " ltlt endl
  • else
  • cout ltlt "Grade is F " ltlt endl

Is this a correct logic?
42
Function displayGrade (p.202)
  • void displayGrade ( int score)
  • if (score gt 90)
  • cout ltlt "Grade is A " ltlt endl
  • else if (score gt 80)
  • cout ltlt "Grade is B " ltlt endl
  • else if (score gt 70)
  • cout ltlt "Grade is C " ltlt endl
  • else if (score gt 60)
  • cout ltlt "Grade is D " ltlt endl
  • else
  • cout ltlt "Grade is F " ltlt endl

43
Short Circuit Evaluation
  • (single y gender m age gt 18)
  • //If single is false, gender and age are not
    evaluated
  • (single y gender m age gt 18)
  • //If single is true, gender and age are not
    evaluated

44
4.8 The switch Control Statement
  • switch ( switch-expression )
  • case value-1
  • statement(s)-1
  • break ... // many cases are allowed
  • case value-n
  • statement(s)-n
  • break
  • default
  • default-statement(s)

45
Switch Control
  • When a switch statement is encountered, the
    switch-expression is evaluated. This value is
    compared to each case value until
    switch-expression case value. All statements
    after the colon are executed
  • It is important to include the break statement

46
Example switch Statement (p.209)
  • switch(watts) // Assume char option '?
  • case 25
  • cout ltlt " Life expectancy is 2500 hours. "
    ltlt endl
  • break
  • case 40
  • case 60
  • cout ltlt " Life expectancy is 1000 hours. "
    ltlt endl
  • break
  • case 75
  • case 100
  • cout ltlt " Life expectancy is 750 hours. "
    ltlt endl
  • break
  • default cout ltlt "Invalid Bulb !!" ltlt endl
  • // end switch
  • Show output when
  • watts '?' ____________?
  • watts 40 ____________?
  • watts 10' ____________?
  • watts 200' ____________?
  • watts 100' ____________?

1 Exercises 4.8 (p.211)
47
4.9 Common Programming Errors
  • Failing to use and
  • if(Grade gt 3.5)
  • // The true-part is the first cout only
  • cout ltlt"You receive an A !!!"
  • cout ltlt"You made it by " ltlt (Grade-3.5) ltlt "
    points"
  • else

Any compilation error?
48
4.9 Common Programming Errors (cont.)
// File grade_if_else_syntax_error.cpp include
ltiostreamgt using namespace std int
main() float Grade cout ltlt "Please enter
your grade (a numeric) " cin gtgt Grade
if(Grade gt 3.5) // The true-part is the
first cout only cout ltlt"You receive an A
!!!" cout ltlt"You made it by " ltlt
(Grade-3.5) ltlt " points"
else cout ltlt "Sorry, you missed an A. "
cout ltlt "You missed it by " ltlt 3.5-Grade
ltlt " points" return 0 //main
49
4.9 Common Programming Errors (cont.)
// File grade_if_else_logic_error.cpp include
ltiostreamgt using namespace std int
main() float Grade cout ltlt "Please enter
your grade (a numeric) " cin gtgt Grade
if(Grade gt 3.5) // The true-part is
the first cout only cout ltlt"You receive an A
!!!\n" cout ltlt"You made it by " ltlt (Grade -
3.5) ltlt " points\n"
else cout ltlt "Sorry, you missed an A.\n "
cout ltlt "You missed it by " ltlt (3.5 -
Grade) ltlt " points\n" return 0 //main
With the above false part, you could get this
confusing output (when Grade 3.9) You
received an A !!!. You made it by 0.4 points.
You missed it by -0.4 points
50
4.9 Common Programming Errors (cont.)
else cout ltlt "Sorry, you missed an A.
\n" cout ltlt "You missed it by " ltlt
(3.5 - Grade) ltlt " points\n" return
0 //main
// File grade_if_else_correct.cpp include
ltiostreamgt using namespace std int main()
float Grade cout ltlt "Please enter your grade
(a numeric) " cin gtgt Grade if(Grade gt
3.5) cout ltlt"You receive an A !!!\n"
cout ltlt"You made it by " ltlt (Grade - 3.5)
ltlt " points\n"
51
Next Assignment 3
  • WATER
  • Using functions (or NO points)
  • using switch
  • Run hw3-water_Chen_Jason_Do_While.exe
Write a Comment
User Comments (0)
About PowerShow.com