C++ if else Statement

In this lesson, you will learn about the if..else statement in C++, its usage, and examples to better understand the topic.


C++ if else Statements

We intend to run a block of code in C++ when and if the condition is true and another piece of code when the condition is false. We use an if..else expression in this situation.

Basic Syntax

if (condition) {
  // statements
} else {
  // statements
}

In the above syntax, the condition is a Boolean one that returns True or False.

  • The statements within the body are performed if the condition is True.
  • If the condition is False, the statements inside the otherwise body are run.

Example

// Program determines whether an integer is even or odd.
#include <iostream>

using namespace std;
int main() {
  int checkNumber;
  cout << "Please enter a number: ";
  cin >> checkNumber;
  if (checkNumber % 2 == 0)
    cout << checkNumber << " is an even number.";
  else
    cout << checkNumber << " is an odd number.";
  return 0;
}

Output

Please enter a number: 7
7 is an odd number.

In the above program, an “if..else” statement is used in this program to determine whether or not checkNumber % 2 == 0 is true. If this statement is true, the “if” block will be executed, and the display statement will be even. Otherwise, “else” will be executed, and the display “number is an odd number.” So, 7 % 2 == 0 is false. “7 is an odd number.” Will be displayed.

This concludes the C++ if else Statement lesson. The next lesson will learn about the if..else..if Statement in C++.