Documente Academic
Documente Profesional
Documente Cultură
Computer Programming
(CSC425)
by
PUAN AFIZA ISMAIL
Faculty of Computer & Mathematical Sciences
UiTM MALAYSIA
2013
Selection Structures
Chapter 4
Contents
4.1 Introduction
4.2 Selection criteria with Boolean expression
4.3 The if statement
4.4 The if..else statement
4.5 Nested if statement / if..else chain
4.6 The switch statement
October 1, 2013
4.1
Introduction
In sequence
Selectively (branch) - making a choice
Repetitively (iteratively) - looping
October 1, 2013
4.1
Introduction (cont.)
October 1, 2013
4.2
October 1, 2013
4.2
(cont.)
is of the form
expression1 relational-operator expression2
Relational operators:
Allow comparisons
Require two operands
Return 1 if expression is true, 0 otherwise
October 1, 2013
4.2
(cont.)
October 1, 2013
4.2
(cont.)
October 1, 2013
4.2
(cont.)
string
string
string
string
October 1, 2013
str1
str2
str3
str4
=
=
=
=
"Hello";
"Hi";
"Air";
"Bill";
10
4.2
(cont.)
October 1, 2013
11
4.2
(cont.)
October 1, 2013
12
4.2
(cont.)
October 1, 2013
13
4.2
(cont.)
October 1, 2013
14
4.2
(cont.)
October 1, 2013
15
4.2
(cont.)
October 1, 2013
16
4.2
(cont.)
October 1, 2013
17
4.2
(cont.)
October 1, 2013
18
4.2
(cont.)
October 1, 2013
19
4.2
(cont.)
October 1, 2013
20
4.3
The if statement
October 1, 2013
21
4.3
Example :
October 1, 2013
22
4.3
Example :
Exercise 21
Exercise 22
October 1, 2013
23
4.4
The if..else statement
October 1, 2013
24
4.4
Example :
Exercise 23
Exercise 24 :
Consider the following statements :
if final_score >= 60
status = pass
else
status = fail
Write in C++ statement.
October 1, 2013
25
4.5
The nested 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)
October 1, 2013
26
4.5
pair
pair
October 1, 2013
27
4.5
October 1, 2013
28
4.5
October 1, 2013
29
4.5
October 1, 2013
30
4.6
The switch statement
October 1, 2013
31
4.6
The switch statement
October 1, 2013
32
4.6
October 1, 2013
33
4.6
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
October 1, 2013
34
4.6
October 1, 2013
35
4.6
October 1, 2013
36
4.6
October 1, 2013
37