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

To understand this example, you should have the knowledge of the following C++ programming topics:


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

And those integers that are not perfectly divisible by 2 are 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.


Example 1: Check Whether Number is Even or Odd using if else

#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: 23
23 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.

You can also use ternary operators ?: instead of if..else statement. The ternary operator is a shorthand notation of if...else statement.


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

#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;
}

Also Read:

Before we wrap up, let's put your understanding of this example to the test! Can you solve the following challenge?

Challenge:

Write a function to check if a number is odd or even.

  • If the number is even, return "Even". If the number is odd, return "Odd".
  • For example, if num = 4, the output should be "Even".
Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community