Csc126 Chapter 3
Csc126 Chapter 3
Csc126 Chapter 3
Prepared for:
CSC126 - Fundamentals of Algorithms & Computer Problem Solving
OBJECTIVES OF THIS CHAPTER
Able to control the flow of the program based on the decision made
Decision is made by evaluating the conditions given, which can
either be:
True
• Condition is met
Boolean • Represents 1
expression False
Condition is not met
Represents 0
RELATIONAL OPERATORS
Relational Operators:
Are used to compare values between 2 operands
The result of comparison will either be:
True
False
Relation Operator Description Example
== Equal to X == Y
!= Not equal to X != Y
< Less than X<Y
<= Less than or equal to X <= Y
> Greater than X>Y
>= Greater than or equal to X >= Y
QUICK EXERCISE
Let a = 7 and b = 5
a) a != b
b) a > b
c) b <= 7
LOGICAL OPERATORS
Logical Operators:
Are used when there are more than one relational expression to evaluate
at a time
Allows you to combine the relational expressions
The result of comparison will either be:
True
False
Logical Description Unary or Binary Rule Example
Operator Operator
! NOT Unary Produce opposite ! (a < b)
relation
&& AND Binary Both operand must (a < b) && (a < c)
be true
|| OR Binary At least one operand (a == b) || (a == c)
must be true
QUICK EXERCISE
Order of Precedence:
Determine the order of evaluation in an expression
QUICK EXERCISE
One-Way Selection:
Only involve an if statement (without else statement)
If the condition is TRUE, the statement inside if.. will be executed
If condition is FALSE, the control goes to the next statement placed
outside the if statement (the if statement is ignored)
Condition is formed as a
Boolean expression
Executed afterwards
QUICK EXERCISE
Multiple Selection:
Is used when there are multiple conditions involved
Can be implemented using any of the 3 ways:
1. if …. else if statement
2. Nested if Statement
3. switch Statement
MULTIPLE SELECTION - if…else if
if…else if Statement:
Is used when there are multiple conditions based on the
same subject
The program will continuously check each condition
starting from the top to the bottom until it has found
the condition that is TRUE
Once the condition is evaluated as TRUE,
the statement inside if.. will be executed and the other
if statements will be ignored
If there are no condition that can be evaluated as TRUE,
the last else.. statement will be executed (if exist)
Executed afterwards
QUICK EXERCISE
Executed afterwards
QUICK EXERCISE