Check If a Number is Odd or Even in C++

Exercise:

Write a C++ Program to check if a number is odd or even.

Method 1: Checking if a Number is Odd or Even Using an if… else Statement:

Click Here to View the Solution!
#include <iostream>
using namespace std;
int main()
{
    int i;
    cout << "Enter an integer:\n ";
    cin >> i;
    if ( i % 2 == 0)
        cout << i << " is an even number";
    else
        cout << i << " is an odd number";
    return 0;
}
Click Here to View the Output!
Enter an integer:
  45
45 is an odd number
Click Here to View the Explanation!
  • Even numbers are divisible by two, and odd numbers are not. This means that odd numbers give a remainder of 1 when divided by 2 and even numbers give a remainder of zero.
  • Use the modulus operator % to divide by 2 and check if the remainder is zero.
  • Then use the if else statement. Put the condition if x % 2 == 0 meaning, if the remainder is equal to zero, the output should be The inserted number is even number.
  • If the condition is not satisfied, the else statement is used and the output The inserted number is an odd number is displayed on the screen.

Method 2: Checking if a Number is Odd or Even Using Ternary Operator:

Click Here to View the Solution!
#include <iostream>
using namespace std;
int main()
{
    int i;
    cout << "Enter an integer:\n ";
    cin >> i;
    (i % 2 == 0) ? cout<< i <<" is an even number" : cout<< i <<" is an odd number";
    return 0;
}
Click Here to View the Output!
Enter an integer:
  24
24 is an even number
Click Here to View the Explanation!
  • A short way to add an if... else statement is ternary operators.
  • (i % 2 == 0) ? checks if the condition is true, it forwards to the statement right after. Otherwise, it skips to the statement placed after :.
  • (i % 2 ==0) ? cout << i << "is an even number" : cout << i << "is an odd number" ;
  • The output is displayed on the screen accordingly.