Session2 Decision Structure
Session2 Decision Structure
STRUCTURES
if condition and switch case statement
Presentators:
JOHN MICHAEL LEGASPI
CONDITIONAL STATEMENTS
• if statement
• if-else statement
• switch statement
FLOW OF CONTROL
if ( condition )
statement;
condition
evaluated
true
false
statement
THE IFSTATEMENT
• An example of an if statement:
if (FirstNo > SecondNo)
result = FirstNo - SecondNo;
cout<<"The resultant is"<< result;
• First the condition is evaluated -- the value of FirstNo is either greater than the
value of SecondNo, or it is not
!= not equal to
• Note the difference between the equality operator (==) and the assignment
operator (=)
LOGICAL OPERATORS
• The logical NOT operation is also called logical negation or logical complement
• If some condition a is true, then !a is false; if a is false, then !a is true
• Logical expressions can be shown using a truth table
a !a
True False
False True
LOGICAL AND & LOGICAL OR
condition
evaluated
true false
statement1 statement2
THE CONDITIONAL OPERATOR
• C++ provides and operator to create short expressions that work like if-else
statements.
BooleanExpression ? Value1 : Value2;
• If BooleanExpression is true, Value1 is returned
• If BooleanExpression is false, Value2 is returned
• Example:
if (score < 50)
cout<<“Sorry! You Have Failed…";
else
cout<<"You Have Successfully Passed! ";
THE IF-ELSE IF STATEMENT
• General form:
if (BooleanExpression1)
statement or block 1
else if (BooleanExpression2)
statement or block 2
else
statement or block 3
• If BooleanExpression1 is true, then statement or block 1 is executed.
• If BooleanExpression1 is false, then BooleanExpression2 is tested.
• If BooleanExpression2 is true, then statement or block 2 ais executed.
• If BooleanExpression2 is false, then statement or block 3 is executed.
• Switch case statement is used when we have multiple conditions and we need to perform
different action based on the condition. When we have multiple conditions and we need to
execute a block of statements when a particular condition is satisfied.
int main(){
int num=5;
switch(num+2) {
case 1:
cout<<"Case1: Value is: "<<num<<endl;
case 2:
cout<<"Case2: Value is: "<<num<<endl;
case 3:
cout<<"Case3: Value is: "<<num<<endl;
default:
cout<<"Default: Value is: "<<num<<endl;
}
return 0;
}
THE END
ANY QUESTION