Control Flow - Conditional Statements

Prateek Narang

Topics

  • Conditional Statements

  • if

  • if-else

  • else if

  • Ternary operator

  • Switch case

Conditional Statements

if statement

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
}


else statement

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
}


else if

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.

Ternary Operator [ ? : ]

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 Case

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}
  • The switch expression is evaluated once
  • The value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed

Switch Case

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

Examples

Made with Slides.com