Professional Documents
Culture Documents
Topic 3 - Selection Structure
Topic 3 - Selection Structure
CONTROL STRUCTURE
OBJECTIVES
Selection
Selection is used to execute different statement depending on certain
conditions
if, if-else, and switch
Repetition
Repetition is used to repeat statement while certain conditions are met
for, while, and do-while
INTRODUCTION (CONT.)
BOOLEAN EXPRESSION
Logical operators take logical values as operands and yield logical values
as results
Putting ! in front of a logical expression reverses its value
LOGICAL OPERATOR (CONT.)
LOGICAL OPERATOR (CONT.)
LOGICAL OPERATOR (CONT.)
LOGICAL OPERATOR (CONT.)
LOGICAL OPERATOR (CONT.)
found = 1
flag = 0
Int num=1,
a=5, b=8,
n=20
Double
x=5.2, y=3.4
Char ch=‘B’
LOGICAL OPERATOR (CONT.)
found = 1
flag = 0
Int num=1,
a=5, b=8,
n=20
Double
x=5.2, y=3.4
Char ch=‘B’
LOGICAL OPERATOR (CONT.)
LOGICAL OPERATOR (CONT.)
Example:
ONE -WAY if SELECTION (CONT.)
EXAMPLE OF ONE WAY if SELECTION
Example Output 1:
Example Output 2:
TWO -WAY if…else SELECTION
else
statement2;
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;
}
TWO -WAY if…else SELECTION (CONT.)
EXAMPLE OF TWO -WAY if…else
SELECTION
NESTED IF
Multiple selection
Nesting: one control statement in another
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
NESTED IF (CONT.)
NESTED IF (CONT.)
NESTED IF (CONT.)
EXAMPLE OF NESTED if
EXERCISES