Professional Documents
Culture Documents
CSC126 CHP 3
CSC126 CHP 3
SELECTION CONTROL
STRUCTURE
Prepared by: Siti Hasrinafasya Che Hassan
Reference to: D.S. Malik
Overview
• Condition
➢ To perform a test which compares two values
• Comparisons
➢ Needs a relational operators
Relational Description • Eg:
Operators – 8 < 15 evaluates to True
> Greater than – 6 != 6 evaluates to False
>= Greater than or equal – 2.5 > 5.8 evaluates to False
< Less than – 5.9 <= 7.5 evaluates to True
Instruction2
where:
➢ condition: a logical test enclosed in simple parenthesis.
➢ statement block: either a single statement or a group of
statements enclosed between the braces { }
If Selection (Examples)
Example 1
Example 2
Example 3
If… else Selection
if (num >= 0) Example
cout << “Positive number” << endl;
else if(num < 0)
cout << “negative number” << endl;
• Performs an action from two alternatives cout << “End of program…” <<;
• Syntax:
if (condition) True False
Condition
statement block1;
else
Instruction1 Instruction2
statement block2;
where: Instruction3
Example 2
Multiple Selection
• Executes multiple if statements if the condition is true
• Syntax:
if (condition1)
statement block1; True False
Condition1
else if (condition2)
statement block2;
Instruction1 True False
: Condition2
else
statement blockN; Instruction2 True
ConditionN
if (num > 0) Example
cout << “Positive number” << endl; InstructionN :
else if (num < 0)
cout << “negative number” << endl;
else
cout << “Zero number” << endl;
cout << “End of program…” <<;
Multiple Selection (Examples)
Example 1
Example 2 To avoid excessive identation, the above code also can be rewritten as follows:
Multiple Selection (Examples)
Example 3
Comparing if… else Statements with a
Series of if Statements(Example)
Example 4
Logical Expression