Conditional Statements
if
if-else
else if
Ternary operator
Switch case
Use the if statement to specify a block of C++ code to be executed if a condition is true.
if(condition){
// block gets executed if the condition is true
// some logic here
}
The else statement is used along with the if block.
Use the else statement to specify a block of code to be executed if the condition is false.
if(condition){
// block gets executed if the condition is true
// some code here
}
else{
// some code, execute when the condition is false
}
if (condition1) {
// block of code to be executed if condition1 is true
}
else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
}
else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Use the else if statement to specify a new condition if the previous blocks condition is false.
It consists of three operands, hence the name ternary operator.
It is often used to replace simple if else statements:
// Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Use the switch statement to select one of many code blocks to be executed.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}