C++ Program to Check Whether Number is Even or Odd

In the following example of C++ program if...else statement is used to check whether a number entered by the user is even or odd.

* Integers that are perfectly divisible by 2 are called even numbers.

* And those integers that are not perfectly divisible by 2 are not known as odd numbers.

* To check whether an integer is even or odd, the remainder is calculated when it is divided by 2 using modulus operator %. If the remainder is zero, that integer is even if not that integer is odd.

Check Whether Number is Even or Odd using if else :

Program :
#include <iostream>
using namespace std;

int main() {
  int n;

  cout << "Enter an integer: ";
  cin >> n;

  if ( n % 2 == 0)
    cout << n << " is even.";
  else
    cout << n << " is odd.";

  return 0;
}
Output :
Enter an integer: 7
7 is odd.
In this program, an if..else statement is used to check whether n % 2 == 0 is true or not.

If this expression is true, n is even. Else, n is odd.

Example 2 : Check Whether Number is Even or Odd using ternary operators :

Program :
#include <iostream>
using namespace std;

int main() {
  int n;

  cout << "Enter an integer: ";
  cin >> n;
    
  (n % 2 == 0) ? cout << n << " is even." :  cout << n << " is odd.";
    
  return 0;
}
Output :
Enter an integer: 12
12 is even.