ECE321 LEC PART5 - Control Structure - Selection
ECE321 LEC PART5 - Control Structure - Selection
Selection
Control Structures I: Selection
Selection
>> the program executes particular statements depending on one or more conditions
Logical
false Expression true
statement 2 statement 1
Boolean Operator
Boolean Operator
Operator Description
! logical NOT Operation
&& logical AND Operation
II logical OR Operation
Boolean Operation
x y x && y x II y !x
Relational Operator
Relational Operator
if (boolean - expression)
{
statement 1;
statement 2;
...
statement n;
}
Flow Execution of If Statement
Logical
Expression true
statement 1
false
If – Else Statement
The syntax for an If – Else statement:
if (boolean - expression)
{
statement – list - 1
}
else
{
statement – list - 2
}
Flow Execution of If – Else Statement
Logical
false Expression true
statement 2 statement 1
Nested If – Else Statement
Syntax:
if (logical expression) {
if(logical expression 1)
statement – list – 1
else
statement – list – 2
}
else
{
if(logical expression 2)
statement – list – 3
else
statement – list – 4
}
Else – If Statement
Syntax:
if(logical expression 1) {
statement – list – 1
}
else if(logical expression 2) {
statement – list -2
}
else if(logical expression 3) {
statement – list -3
}
else {
Statement – list – n
}
Switch Statement
switch statement
- a variation of the if statement is the switch statement,
which performs a multi-way branch instead of a simple
binary branch.
Syntax :
switch (expression) {
case value : statement(s);
break;
case value : statement(s);
break;
.......
default : statement(s);
break;
}
Flow Execution of Switch Statement
statement 1
Case Value 1
true statement 1 break
false
Case Value n
true statement n break
false
Default
statement
SAMPLE PROBLEM
1. Write a program that would accepts two
integers and output the greatest number.(Two
numbers must be different)