Title: Selection: the if-else and switch-case instructions
1Chapter 4
- Selection the if-else and switch-case
instructions
2Some observations
- The instructions we have learned allow us to do
any kind of computations (non-numeric processing
will be discussed later) as long as we can
convert a problem to appropriate C code. - But we are faced with inflexibility, as
illustrated in the following simple payroll
problem.
3Simple payroll problem to compute weekly pay for
hourly workers
- Problem definition/specification a worker pay is
based on hours worked and hourly rate. In
addition, overtime hours (those hours above 40)
are paid at twice the regular rate, and any
worker may work overtime. Now we have two
different formulas to compute the pay for a
worker, but only one will be used depending on
whether the worker worker worked overtime or not.
The two formulas are as follows - pay hours hourly_rate // non-overtime
- or pay 40.0 hourly_rate (hours 40) 2.0
hourly_rate // overtime
4Simple payroll problem to compute weekly pay for
hourly workers continued
- One way to get around the problem is to write two
programs, one with the formula for workers who
did not work overtime and the other with the
formula for those who worked overtime. But that
is too much work, not to mention the fact that
the input data must be separately into two
groups a process that is time-consuming and
potentially error prone. Can we do better? Yes,
with the help of selection instructions or
structures (the if-else or switch-case
instructions). But first, let us define a set of
operators known as relational operators.
5Relational operators
- Relational
- operator Meaning Example
- lt less than age lt 30
- gt greater than height gt 6.2
- lt less than or equal to tax lt 10000
- gt greater than or equal to temp gt 90.0
- equal to gender 'M'
- ! not equal to x ! (y z)
- Using relational operator, one can write simple
logical expressions (not arithmetic expressions)
as shown in the "Example" column. Unlike an
arithmetic expression which is evaluated to an
numeric value, a logical expression is evaluated
to a logical or Boolean value of either true or
false. In C/C true is represented by 1 (or any
non-zero value) and false by 0.
6Example demonstrating Boolean data type
- include ltiostream.hgt
- int main( )
-
- bool result
- result (3 lt 4)
- cout ltlt "The value of 3 lt 4 is" ltlt result
- result (2.0 gt 3.0)
- cout ltlt "\nThe value of 2.0 gt 3.0 is "
- ltlt result ltlt endl
- return 0
-
7Example demonstrating logical values
- include ltiostream.hgt
- int main( )
-
- cout ltlt "The value of 3 lt 4 is" ltlt (3 lt 4)
- cout ltlt "\nThe value of 2.0 gt 3.0 is "
- ltlt ( 2.0 gt 3.0) ltlt endl
- return 0
-
- What will be printed?
8More examples
- Expression value interpretation
- 'A' gt 'C' 0 false
- 'D' lt 'Z' 1 true
- 'E' 'F' 0 false
- 'B' ! 'C' 1 true
9The selection structure the if-else structure
- format
- if ( logical expression )
- true task
- else
- false task
-
- where logical expression is evaluated first if
true, the true task will be executed, otherwise,
the false task will be executed. The true task or
false task shown in the format is a block (of
group) of any C/C instructions. Notice that a
block of instructions is enclosed in a pair of
braces (or curly brackets). If the block contains
only one instruction, the braces may be skipped.
10Hourly payroll problem revisited
- include ltiostream.hgt
- int main( )
-
- double rate, hours, total_pay
- cout ltlt "Enter hourly rate and hours worked "
- cin gtgt rate gtgt hours
- if ( hours lt 40 )
- total_pay hours rate
- else
- total_pay 40 rate (hours 40) 2
rate - cout ltlt "\nThe total pay is " ltlt total_pay ltlt
endl - return 0
-
-
11Program determines if an arbitrary integer is
even or odd
12Think of 11 cases where if-else (selection) are
needed
- Each student contributes one.
13Temperature conversion problem
- include ltiostream.hgt
- include ltiomanip.hgt
- int main( )
-
- char tempType
- double temp, fahren, celsius
- cout ltlt "Enter temperature to be converted "
- cin gtgt temp
- cout ltlt"Enter f is the temperature is in
Fahrenheit " - cout ltlt "or c is the temperature is in Celcius
" - cin gtgt tempType
- cout ltlt setiosflags ( iosfixed) ltlt setiosflags
( iosshowpoint) - ltlt setprecision ( 2 )
-
14Temperature conversion problem continued
-
- if ( tempType 'f' )
- celsius ( 5.0 / 9.0 ) ( temp 32.0 )
- cout ltlt "\nThe equivalent Celsius is " ltlt
celsius ltlt endl - else
- fahren ( 9.0 / 5.0 ) temp 32.0
- cout ltlt "\nThe equivalent Fahrenheit is " ltlt
fahren ltlt endl -
- return 0
-
- What is the user enters F or C instead of f or c?
15Scope and lifetime of a variable
- A variable comes to life (or is born) after it is
declared. From this point on, it can used or
referenced from this point on for as long as the
variable is within its scope. - Scope of a variable
- global scope variables declared outside of a
function these variables are known as global
variables. - local scope variables declared within a
function these variables are known as local
variables. - block scope defined in a block of a function
- function scope declared in a function
16Example on scope
- include ltiostream.hgt
- int main( )
-
- int a 22, b 33, c 44 // a, b, and c have
function scope - cout ltlt "a " ltlt a ltlt "\tb " ltlt b ltlt "\tc "
ltlt c ltlt endl - // beginning of a block in a function
- int a 44, b 55 // a new set of a and b
are born! - // note a, b are not the same a, b declared
above - cout ltlt "a " ltlt a ltlt "\tb " ltlt b ltlt "\tc
" ltlt c ltlt endl - c
- cout ltlt "c now becomes " ltlt c ltlt endl
- // the end of the block a and b are now
'dead' - cout ltlt "a " ltlt a ltlt "\tb " ltlt b ltlt "\tc "
ltlt c ltlt endl - return 0
-
-
17One way selection
- An if statement without else branch (no false
task). - format
- if (expression)
- true task
-
-
18One way selection example extra 5-point for
perfect attendance
- include ltiostream.hgt
- int main( )
-
- int score
- char perfectAttendance
- const extraPoint 5
- cout ltlt "Enter overall score for student "
- cin gtgt score
- cout ltlt "Perfect attendance? Enter y or n "
- cin gtgt perfectAttendance
- if ( perfectAttendance 'y' )
- score extraPoint
-
- cout ltlt "\nTotal score for the student is " ltlt
score - return 0
-
19Nested if-else statement
- If the true-task or false-task of an if-else
statement contain other if-else or if statement,
the overall statement is a nested if-else
statement, as illustrated in the following
example.
20Nested if-else example convert a numeric to a
letter grade and then print out the letter grade
- include ltiostream.hgt
- int main( )
-
- int score
- char grade
- cout ltlt "Enter a score "
- cin gtgt score
- if ( score lt 60 ) cout ltlt "\nScore " ltlt score
ltlt " Grade " ltlt 'F' - else if ( score lt 70 ) cout ltlt "\nScore " ltlt
score ltlt " Grade " ltlt 'D' - else if ( score lt 80 ) cout ltlt "\nScore " ltlt
score ltlt " Grade " ltlt 'C' - else if ( score lt 90 ) cout ltlt "\nScore " ltlt
score ltlt " Grade " ltlt 'B' - else cout ltlt "\nScore " ltlt score ltlt " Grade
" ltlt 'A' - return 0
-
21Additional example salesperson income problem
p148
-
- if ( sales gt 50000.00 )
- income 375.00 .16 sales
- else if ( sales gt 40000.00 )
- income 350.00 .14 sales
- else if ( sales gt 30000.00 )
- income 325.00 .12 sales
- else if ( sales gt 20000.00 )
- income 300.00 .09 sales
- else ( sales gt 10000.00 )
- income 250.00 .05 sales
- else
- income 200.00 .03 sales
22switch-case selection structure
- Format
- switch (expression)
-
- case value_1
-
- reak
- case value_2
-
- break
-
- case value_n
-
- break
- default
-
-
23switch-case example
- int number
-
- switch (number)
-
- case 1 cout ltlt "Good morning." ltlt endl break
- case 2 cout ltlt "Happy day." ltlt endl break
- case 3
- case 4
- case 5 cout ltlt "Nice evening." ltlt endl
-