C++ If...Else

C++ If...Else Statements

Conditional statements are used to perform different actions based on different conditions.

The if Statement

Use if to specify a block of code to be executed if a condition is true.

Example

int time = 20;
if (time < 18) {
  cout << "Good day.";
}

The else Statement

Use else to specify a block of code to be executed if the condition is false.

Example

int time = 20;
if (time < 18) {
  cout << "Good day.";
} else {
  cout << "Good evening.";
}
// Outputs: Good evening.

The else if Statement

Use else if to specify a new condition if the first condition is false.

Example

int time = 22;
if (time < 10) {
  cout << "Good morning.";
} else if (time < 20) {
  cout << "Good day.";
} else {
  cout << "Good evening.";
}

By combining these statements, your programs can make decisions on the fly!


Exercise

?

Which statement is used to specify a new condition if the first condition is false?