0% found this document useful (0 votes)
11 views49 pages

Chap05 - Selection Control

Uploaded by

black hello
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views49 pages

Chap05 - Selection Control

Uploaded by

black hello
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

C++ Programming:

Problem Solving and


Programming

Chapter 5
Selection Control
Objectives
5.1 Selection Control Structure
5.2 Two Way Selection Structure: if-else Statements
5.2.1 Single-Alternative (Unary) Selection Structure
5.2.2 Dual-Alternative (Binary) Selection Structure
5.2.3 Compound Statements
5.2.4 Conditional Expression (?:)
5.3 Nested if Statements
5.4 Multiple Selection Structure
5.4.1 else-if Statements
5.4.2 switch Statements
5.4.3 Nested switch Statements
Control Structures

Three types of control structure :


• Sequence
• Selection
• Loop Action
false true false
Condition Condition

Action
true
Action Action
Action

Action

(a) Sequence (b) Selection (c) Loop


One-Way (if) Selection
• Syntax:
if (expression) false Expression true
statement
Action

• Action / statement is executed only if the


value of the expression is true
• No action is executed if the expression is
false; program goes to the next statement
One-Way (if) Selection - Example
If the student score more than 50 marks or equal to
50 marks, system must shows their result passed.

Pseudocode:

No score Yes If score >= 50 then


>= 50 Print “Passed”
End If
Print
“Passed” C++ statements:

if (score >= 50)


cout << "Passed";
Two-Way (if…else) Selection
• Syntax
if(expression) false Expression true
statement1
else Action 2 Action 1
statement2

• If expression is true, action 1 is executed


otherwise action 2 is executed
Two-Way (if…else) Selection
- Example
Many organizations pay employees overtime rate 1.5
times their usual hourly rate if employees work more
than 40 hours per month. Pseudocode:
If hoursWorked >= 40 then
grossPay = hoursWorked * rate +
false true
hoursWorked 200
>= 40 Else
grossPay = hoursWorked * rate
grossPay = grossPay = End If
hoursWorked * hoursWorked * rate C++ statements:
rate + 200 if (hoursWorked >= 40)
grossPay = hoursWorked * rate +

200;
else
PYQ:
Convert the following algorithm written in pseudocode
into a complete flowchart and program.

Start
Read sales
If sales >= 5000.00 then
Set rate = 0.20
Else
Set rate = 0.10
End If
Set comm = sales * rate
Display comm
End
PYQ:
Flowchart:
PYQ:
Program: #include <iostream>
using namespace std;
void main()
{
double sales, rate, comm;
cout << “Enter sales: ”;
cin >> sales;
if (sales >= 5000.00)
rate = 0.20;
else
rate = 0.10;
comm = sales * rate
cout << “Commission: ” << comm;
}
Compound (Block of) Statement
• Compound statement (block of statements):
{
statement 1;
statement 2; More than 1 related
. statements to be
. executed as a group
.
statement n;
}

• A compound statement is a single statement


Compound Statement - Example
If (age > 18)
{
cout<<" Eligible to vote."<<endl;
cout<<" No longer a minor."<<endl;
}
else
{
cout<<"Not eligible to vote."<<endl;
cout<<"Still a minor."<<endl;
}
Conditional Operator (?:)
• Alternative to Two-way (if..else) selection
structure
• Syntax: expression1 ? expression2 :
expression3

e.g. mark>=40 ? cout<<“Passed” : cout<<“Failed”;


SAME AS
if (mark >= 40)
cout<<“Passed”;
else
cout<<“Failed”;
Conditional Operator (?:) - Example
• Convert the following if-else statement to conditional
expression.
if (score >= 80)
grade = 'A';
else
grade = 'B';

score >= 80 ? grade = 'A' : grade = 'B';


OR
grade = (score >= 80 ? 'A' : 'B');
Conditional Operator (?:) - Exercise
1. Show the output of the following program segment:
int a=10, b=2,num;
a=10, num=13
num = a>=9?a+3:a+5;
cout << “a=” << a << “, num=” << num;

2. Show the output of the following program segment:


int a=10, b=2,num;
num = a>=9? b>3? a+3 : a-1 : a+5;
cout << “a=” << a << “, num=” << num;
a=10, num=9
Nested if
• One if statement is found in another
• An else statement is associated with the most
recent if
Nested if - Example
if (exam_mark >= 80)
if (coursework >= 70)
cout<<“Grade is A”;
else cout<<“Grade is B+”;
else if (exam_mark >= 60)
if (coursework >= 70)
cout<<“Grade is C”;
else cout<<“Grade is D”;
else cout<<“Grade is F”;
if (member==‘N’)
Nested if - Example discount = 0;
else
if (member_type==‘A’)
discount = 0.1;
Yes member No
=‘N’ else
discount = 0.2;

discount=0 Yes member No


_type=‘A’

discount=0.1 discount=0.2
Nested if - Example
• TAR Computers gives discount to customers
(members and non-members) when they are buying
computer hardware based on the following table:
Customer Type Discount
Given
Member 10%
Non-member No discount

• Write a C++ program that calculates and display


amount payable by the customer after applying the
discount given. Draw a flowchart for the program.
Nested if - Example
#include<iostream>
using namespace std;
void main() {
char ismember;
double purchase, payable, discount_rate;

cout<< “Are you member(Y/N) ? ”;


cin >> ismember;
cout << “Enter purchase: ”;
cin >> purchase;

if (ismember == ‘Y’)
discount_rate = 0.1;
else
discount_rate = 0;

discount = purchase * discount_rate;


payable = purchase – discount;
cout << purchase, discount, payable;
}
Nested if - Example
• TAR Computers gives discount to customers
(members and non-members) when they are buying
computer hardware based on the following table:
Customer Type Amount Discount
Purchase Given
Member >= RM500.00 20%
< RM500.00 10%
Non-member >= RM500.00 10%
< RM500.00 No discount
• Write a C++ program that calculates and display
amount payable by the customer after applying the
discount given. Draw a flowchart for the program.
Nested if -
Example

Try out the program yourself


Multiple Selection
• Multiple selection occurs when there are more
than 2 alternative that a single if-else statement
can cater for.
• Two commands used for multiple selection
structure:
− else-if statement
− switch statement
Multiple Selection – else if

Syntax:

if (condition 1)
statement 1;
else if (condition 2)
statement 2;

else if (condition n)
statement n;
else
statement default;
Multiple Selection – else if
- Example
• Write an else-if statement to test if an integer is
positive, negative or zero.
if (integer > 0)
cout<< integer << “ is positive\n";
else if (integer < 0)
cout<< integer << “ is negative\n";
else
cout<< integer << “ is zero\n";
Flowcha
rt
C++ false integer true
statements >0

false true Print integer


integer
“is positive”
<0
Print integer Print integer
“is zero” “is negative”
Multiple Selection – else if
Method 1:
if (integer > 0)
cout<< integer << “ is positive\n"; More efficient!
Lesser checking
else if (integer < 0)
when certain
cout<< integer << “ is negative\n"; conditions are
else true and thus
cout<< integer << “ is zero\n"; save CPU
processing time
Method 2: and program can
run faster.
if (integer > 0)
cout<< integer << “ is positive\n";
if (integer < 0)
cout<< integer << “ is negative\n";
if (integer == 0)
cout<< integer << “ is zero\n";
Multiple Selection – else if
- Exercise
• Write a C++ program that reads a test score,
calculates the letter grade based on the table below,
and prints it.

Test Score Grade


90 – 100 A
80 – 89 B
70 – 79 C
60 – 69 D
Below 60 F
Multiple Selection – else if
- Exercise
C++ program:
Multiple Selection – switch
Syntax : • expression type is int or char only
switch (expression) • The value of expression is
{ compared against label1 through
case label 1 labeln.
Statement 1; • If expression matches value
break; labeln, program branches to the
case label 2 statement following labeln
Statement 2; • If no matching value is found, the
break;
program branches to the statement

after default
default
• break is used to exit the switch
Statement default;
} statement
• default is optional
Multiple Selection - switch
Example:
switch (letter) This switch statement
{ and this else-if
case 'A': statement generate the
cout << "Argentina"; same result.
break;
case 'B':
cout << "Brazil"; if (letter == 'A')
break; cout << "Argentina";
case 'C': else if (letter == 'B')
cout << "China"; cout << "Brazil";
break; else if (letter == 'C')
default: cout << "China";
cout <<"Unknown letter"; else
} cout << "Unknown
letter";
30
Multiple Selection - switch

• Flowchart:

letter
?
‘A’ ‘B’ ‘C’ default

Print Print Print Print


“Argentina” “Brazil” “China” “Unknown
Letter”
Multiple Selection - Exercise
Write a else-if and switch statement that test a
letter grade entered by user:
 If the grade is A, B or C, display the message
“Credit passed” and assign 100 to variable
award.
 If the grade is D or E, display the message
“Passed” and assign 50 to variable award.
 If the grade is F, display the message
“Failed” and assign value 0 to variable award.
 Display the message “Invalid grade” if it is
other letters.
Multiple Selection - Exercise
else-
if:
Multiple Selection - Exercise
switch
:
Multiple Selection - Comparison
Multiple Selection: Switch statement:

if (gender == ‘M’) switch (gender)


cout<<“Male”; {
else if (gender == ‘F’) case ‘M’:
cout<<“Female”;
else cout<<“Male”;
cout<<“Others”; break;
case ‘F’:

cout<<“Female”;
break;
default:
Multiple Selection - Comparison
Multiple Selection: Switch statement:

if (a == 1) switch (a)
b=1; {
else if (a == 2) case 1:
b=3; b=1;
else break;
b=5; case 2:
b=3;
break;
default:
b=5;
}
Multiple Selection - Comparison
Switch statement:
Multiple Selection: switch (num)
{
case 1:
if (num == 1) a=10;
a = 10; break;
else if (num == 2 || num ==8) case 2:
a = 20; case 8:
else if (num >=4 && num <= 6) a=20;
a = 30; break;
else case 4:
a = 40; case 5:
case 6:
a=30;
break;
default:
a=40;
}
Multiple Selection - Comparison
switch (class){ if (class==’1’)
case '1': classA += 1; {
classA += 1;
case '2': goodClass += 1; goodClass += 1;
break; }
else if (class ==’2’)
case '3': goodClass += 1;
if (average > 3.0) else if (class ==’3’)
classB1 += 1; {
else if (average > 3.0)
classB2 += 1; classB1 += 1;
totalclassB += classB1 else
+ classB2; classB2 += 1;
break; totalclassB += classB1 + classB2;
}
default: poorClass += 1; else
} poorClass += 1;
Nested Switch
A switch statement is nested switch (a)
within another switch. { case 1:
nested if: if (b == 10)
cout<<“Yes”;
if ( a == 1) else if (b == 20)
if (b == 10) cout<<“Yes
cout<<“Yes”; Yes”;
else if (b == 20) break;
cout<<“Yes Yes”; case 2:
else if (a == 2) if (b == 10)
if (b == 10) cout<<“No”;
cout<<“No”; else if (b == 20)
else if (b == 20) cout<<“No
cout<<“No No”; No”;
break;
Nested Switch switch (a)
{ case 1:
switch (b)
switch (a)
{ case 10:
{ case 1:
cout<<“Yes”;
if (b == 10)
break;
cout<<“Yes”;
case 20:
else if (b == 20)
cout<<“Yes
cout<<“Yes Yes”;
Yes”;
}
break;
case 2: break;
if (b == 10) case 2:
cout<<“No”; if (b == 10)
else if (b == 20) cout<<“No”;
cout<<“No else if (b == 20)
No”;
cout <<“No
break; No”;
Nested Switch - Example
• A manufacturer sells machinery parts to its
customers. The price of machinery parts for different
model of machine is listed below:
Model No. Part No. Price (RM)
100 300 1500.00
600 3000.00
200 400 2500.00
800 4000.00
• Use switch statements to get the price of a
particular machinery part based on the model
number and part number. Display an error message
if the model number or part number is unmatched.
Nested Switch - Example
switch (model) case 200:
{ switch (part)
case 100: {
switch (part) case 400: price = 2500.00;
{ break;
case 300: price = 1500.00; case 800: price = 4000.00;
break; break;
case 600: price = 3000.00; default:
break; cout<<"Invalid part num";
default: }
cout<<"Invalid part num"; break;
} default:
break; cout<<“Invalid model num";
}
Nested Switch - Exercise
• Assume that the cost of a product manufactured in year
2016 and year 2019 is 200.50 and 350.30 respectively
without considering the product code. The cost for year
2017 or year 2018 is determined by code as shown in the
table below.
Year Code Cost(RM)
2016 200.50
2017 or A 89.00
2018 B 105.90
Others 79.80
2019 350.30
• Write a program that using nested switch to display the
tuition fee based on user input of year and code.
Nested Switch - Exercise
C++ program:
Summary:
• Single Alternative selection:
if (a != 5) False
a!=5
True

b = 10;
b = 10

• Dual Alternatives selection:


if (a != 5) False True
a!=5
b = 10;
else
b = 20 b = 10
b = 20;
Summary:
• Nested if: False True
a!=5
if (a != 5)
b = 10; False True b = 10
a=1
else
if (a == 1)
b = 30 b = 20
b = 20;
else
b = 30;
Summary:
• else-if statement: False True
a!=5
if (a != 5)
False True
b = 10; a=1

else if (a == 1)
False True b = 10
b = 20; a >= b = 20
7
else if (a >= 7)
b = 30; b = 40 b = 30

else
b=40;
Summary:
• Switch statement:
switch (num) num
{ =?
case 1:
a= 1 2 default
10; a = 10 a = 20 a = 30

break;
case 2:
a=
20;

break;
default:
Summary:
• Nested-switch statement:
switch (num) num
{ =?
case 1: a = 10;
break;
case 2: switch(digit) 1 2 default
{ a = 10 digit a = 30
case 11: =?
a=
20;
11 33
break;
a = 20 a = 40
case 33:
a=
40;
}
break;

You might also like