Introduction To
Computer Programming
(CSC425)
Lecturer : Assoc Prof Ts Dr Nur Atiqah Sia Abdullah
Credited to Afiza Ismail and DS Malik for the presentation slides and notes
1
Control Structure:
Selection
Topic 3
2
Contents
Introduction
Selection criteria with Boolean expression
if statement
if..else statement
if..else if statement
Nested if statement
switch statement
3
Introduction
A computer can proceed:
In sequence
Selectively (branch) - making a choice
Repetitively (iteratively) - looping
Some statements are executed only if certain
conditions are met.
A condition is represented by a logical (Boolean)
expression that can be true or false.
A condition is met if the expression evaluation is
true.
4
Introduction (cont.)
5
Selection criteria with Boolean expression
Boolean expression is a sequence of operands and
operators that combine to produce one of the Boolean
values, true or false.
2 types of Boolean expression :
- simple Boolean expression
- compound Boolean expression
6
Selection criteria with Boolean expression
(cont.)
Simple Boolean expression :
is of the form
expression1 relational-operator expression2
Relational operators:
Allow comparisons
Require two operands
Return 1 if expression is true, otherwise 0
7
Selection criteria with Boolean expression
(cont.)
Relational operators can be any of the following operators :
8
Selection criteria with Boolean expression
(cont.)
Relational operator can be applied to compare the value
of the variables.
Suppose we have the following declarations:
int num1 = 1;
int num2 = 2;
int num3 = 3;
int num4 = 4;
Expression Value of Expression
num1 > num2
num2 <= num3
num4 != num3
num1 > num4
9
Selection criteria with Boolean expression
(cont.)
Relational operator can be applied to compare the value
of the variables.
Suppose we have the following declarations:
int num1 = 1;
int num2 = 2;
int num3 = 3;
int num4 = 4;
Expression Value of Expression
num1 > num2 False
num2 <= num3 True
num4 != num3 True
num1 > num4 False
10
Selection criteria with Boolean expression
(cont.)
Relational operator can be applied to characters.
11
Selection criteria with Boolean expression
(cont.)
Relational operators can be applied to strings
Strings are compared character by character, starting with
the first character, and following by other characters.
Suppose we have the following declarations:
string str1 = "Hello";
string str2 = "Hi";
string str3 = "Air";
string str4 = "Bill";
12
Selection criteria with Boolean expression
(cont.)
Hello Hi
Hello
Air
13
Selection criteria with Boolean expression
(cont.)
Hello
Air Bill
Hi Bill
14
Selection criteria with Boolean expression
(cont.)
Bill
Big
15
Selection criteria with Boolean expression
(cont.)
Compound Boolean expression :
is formed by combining simple Boolean expressions with the
following logical operator :
16
Selection criteria with Boolean expression
(cont.)
For example, the expression such as
5 <= x <= 10
can be written as the following compound
Boolean expression:
( 5 <= x) && ( x <= 10)
For example, the expression contains number of
dependant is more than 5 or the income is less
than or equal to RM3000 can be written as :
(dependant >5) || (income <=3000)
17
Selection criteria with Boolean expression
(cont.)
18
Selection criteria with Boolean expression
(cont.)
If one of the expression is false, then the combined condition is false.
Only both expressions are true, then the combined condition is true.
19
Selection criteria with Boolean expression
(cont.)
20
Selection criteria with Boolean expression
(cont.)
If one of the expression is true, then the combined condition is true.
Only both expressions are false, then the combined condition is false.
21
Selection criteria with Boolean expression
(cont.)
22
if statement
Used in a one-way selection false
The syntax :
if (condition) true
statement;
statement is executed if the value of the condition
is true
statement is bypassed if the value of the condition is
false; program goes to the next statement
23
if statement (cont.)
Example :
24
if statement (cont.)
Exercise 1:
If the mark is more than 50, the grade is ‘P’.
Exercise 2:
If the income is more than or equal to RM5000, the status
is “Average Income”.
Exercise 3:
If the room type is ‘S’, the room rate is RM180.
25
if statement (cont.)
Exercise 1: if (mark > 50)
If the mark is more than grade = ‘P’;
50, the grade is ‘P’.
Exercise 2:
If the income is more if (income >= 5000)
than or equal to status = “Average Income”;
RM5000, the status is
“Average Income”.
Exercise 3:
If the room type is ‘S’, if (roomType == ‘S’)
the room rate is roomRate = 180;
RM180.
26
if..else statement
Two-way selection takes the form: false
if (expression)
statement1; true
else
statement2;
If expression is true, statement1 is executed
otherwise statement2 is executed
statement1 and statement2 are any C++
statements
else is a reserved word
27
if..else statement (cont.)
If the statements are more than one, you have to use { } to
make them as the compound statements.
The selection takes the form:
if (expression)
{
statement1;
statement2;
}
else
{
statement3;
statement4;
}
28
if..else statement (cont.)
Example :
If the score is more than or equal to 50, the status is pass.
Else the status is fail.
if (score >= 50)
status = “pass”;
else
status = “fail”;
29
if..else statement (cont.)
Example :
If the score is more than or equal to 50, display the score and
the status is pass. Else display the score and the status is fail.
if (score >= 50)
{
cout << “The score is ” << score;
status = “pass”;
}
else
{
cout << “The score is ” << score;
status = “fail”;
}
30
if..else statement (cont.)
Exercise 1:
If the mark is more than or equal to 80, the grade is ‘A’.
Else the grade is ‘B’.
Exercise 2:
If the income is more than or equal to RM5000, the status
is “Average Income”, else the status is “Lower Income”.
Exercise 3:
If the room type is ‘S’, display the room type is Standard
and the room rate is RM180, else display the room type is
Others and the room rate is RM250.
31
if..else statement (cont.)
Exercise 1: if (mark >= 80)
grade = ‘A’;
If the mark is more than
else
or equal to 80, the grade grade = ‘B’;
is ‘A’. Else the grade is ‘B’.
Exercise 2:
If the income is more
if (income >= 5000)
than or equal to RM5000, status = “Average Income”;
the status is “Average else
Income”, else the status is status = “Lower Income”;
“Lower Income”.
32
if..else statement (cont.)
Exercise 3:
if (roomType == ‘S’)
If the room type is ‘S’, {
display the room type is roomType = “Standard”;
Standard and the room roomRate = 180;
}
rate is RM180, else display else
the room type is Others {
roomType = “Others”;
and the room rate is roomRate = 250;
RM250. }
33
if..else if statement
Multiple selection
When one control statement is located within another
(nested)
The rule :
- Pairing and else with an if
An else is associated with the most recent if that has
not been paired with an else ( an else is always
belongs to the closest if)
34
if..else if statement
Score True Display
>=90 “The grade is A.”
Score Grade False
90 - 100 A Score
True
Display
>=80 “The grade is B.”
80 - 89 B
False
70 - 79 C
Score True
Display
60 - 69 D >=70 “The grade is C.”
< 60 F False
True
Score Display
>=60 “The grade is D.”
False
Display
“The grade is F.”
35
if..else if statement (cont.)
pair
pair
pair
pair
36
if..else if statement (cont.)
Exercise 1: Write the selection structure based on the
following table:
Room Type Room Rate (RM)
Standard (S) 180
Deluxe (D) 250
Supreme (U) 320
37
if..else if statement (cont.)
Exercise 1: Write the selection structure based on the
following table:
Room Type Room Rate (RM)
Standard (S) 180
Deluxe (D) 250
Supreme (U) 320
if (roomType == ‘S’)
roomRate = 180;
else if (roomType == ‘D’)
roomRate = 250;
else if (roomType == ‘U’)
roomRate = 320;
38
if..else if statement (cont.)
Exercise 2: Write the selection structure based on the
following table:
Income (RM) Status
<=3000 Lower Income
3000 < Income <= 5000 Middle Income
>5000 High Income
39
if..else if statement (cont.)
Exercise 2: Write the selection structure based on the
following table:
Income (RM) Status
<=3000 Lower Income
3000 < Income <= 5000 Middle Income
>5000 High Income
if (income <= 3000)
status = “Lower Income”;
else if (income > 3000 && income <= 5000)
status = “Middle Income”;
else if (income > 5000)
status = “High Income”;
40
Nested if statement (cont.)
Consider the following statements :
False Current GPA is below
GPA>=2.0 graduation requirement.
See your Academic Advisor
True
True Happy
GPA<3.9
Graduation!
False
True
Dean’s
GPA>=3.9
Honor List
41
Nested if statement (cont.)
Consider the following statements :
False Current GPA is below
GPA>=2.0 graduation requirement.
See your Academic Advisor
True
True Happy
GPA<3.9
Graduation!
What is the value of
False GPA if the display is
True “Happy Graduation!”?
Dean’s
GPA>=3.9
Honor List
42
Nested if statement (cont.)
Consider the following statements :
False Current GPA is below
GPA>=2.0 graduation requirement.
See your Academic Advisor
True
True Happy
GPA<3.9
Graduation!
False
True
Dean’s
GPA>=3.9
Honor List
What is the value of
GPA if the display is
“Dean’s Honor List”?
43
Nested if statement (cont.)
Consider the following statements :
44
Nested if statement (cont.)
Consider the following case :
Nation’s Air force has asked you to write a program to
label supersonic aircraft as military or civilian. Your
program is to be given the plane’s observed speed in
km/h and its estimated length in meters. For planes
traveling in excess of 1100km/h, you will label those
longer than 52 meters “civilian” and shorter aircraft as
“military”. For planes traveling at slower speeds, you
will issue an “aircraft type unknown” message.
45
Nested if statement (cont.)
Consider the following statements :
False Display
Speed >1100 “Aircraft Type
Unknown”
True
True Display
length > 52
“Civilian”
False
Display
“Military”
46
Nested if statement (cont.)
47
Nested if statement (cont.)
Exercise 1: Write the selection structure based on the
following table:
Income (RM) Criteria Tax Rate (%)
<1800 0
<=3000
>=1800 3
3000 < Income <= 5000 6
>5000 10
48
Nested if statement (cont.)
Exercise 1: Write the selection structure based on the
following table:
if (income <= 3000)
{
if (income < 1800)
taxRate = 0;
else if (income >= 1800)
taxRate = 0.03;
}
else if (income > 3000 && income <= 5000)
taxRate = 0.06;
else if (income > 5000)
taxRate = 0.10;
49
switch statement
switch expression is evaluated first
Value of the expression determines which corresponding
action is taken
Expression is sometimes called the selector
Expression value can be only integral
Its value determines which statement is selected for
execution
A particular case value should appear only once
50
switch statement
switch structure: alternate to if..else
51
switch statement (cont.)
One or more statements may follow a case label
Braces are not needed to turn multiple statements into a
single compound statement
The break statement may or may not appear after each
statement
switch, case, break, and default are reserved
words
52
switch statement (cont.)
Rules :
When value of the expression is matched against a case
value,
Statements execute until break statement is found or the
end of switch structure is reached
If value of the expression does not match any of the case
values
Statements following the default label execute If no
default label, and if no match, the entire switch
statement is skipped
A break statement causes an immediate exit from the
switch structure
53
switch statement (cont.)
Exercise 1:
Based on the following table, design a switch selection
structure to display the type of room and room rate.
Choice Room Type Room Rate (RM)
S Standard 180
D Deluxe 250
P Supreme 320
54
switch statement (cont.)
Exercise 1:
Based on the following table, design a switch selection
structure to display the type of room and room rate.
Choice Room Room switch (choice)
Type Rate (RM) {
case ‘S’: cout << “Standard Room”;
S Standard 180 roomRate = 180;
D Deluxe 250 break;
case ‘D’: cout << “Deluxe Room”;
P Supreme 320 roomRate = 250;
break;
case ‘U’: cout << “Supreme Room”;
roomRate = 320;
break;
default: cout << “Invalid choice”;
}
55
switch statement (cont.)
Exercise 2:
Write a program to read two numbers. Prompt to the
user a menu to choose the arithmetic operation:
Choice Arithmetic Operation
1 Addition
2 Multiplication
3 Subtraction
Based on the choice, design a switch selection structure
to carry out the operation and display the result.
56
switch statement (cont.)
57
4.6
The switch statement (cont.)
58