Loading...
C++ Program to Check Whether a Number is Even or Odd.

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

In this example, we used if...else statement and ternary operator to check whether a number entered by the user is even or odd.

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

Program to Check Whether a Number is Even or Odd.

  • Integers which are perfectly divisible by 2 are called even numbers.
  • And those integers which are not perfectly divisible by 2 are not known as odd number.
  • To check whether an integer is even or odd, the remainder is calculated when it is divided by 2 using modulus operator %. If remainder is zero, that integer is even if not that integer is odd.

Example 1: Program to Check Whether Number Entered by the User is Even or Odd using if else statement.

// Check Whether Number Entered by the user is Even or Odd.

#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: 20
20 is even.

Working of above Program

In this program, if..else statement is used to check whether n%2 == 0 is true or not. If this expression is true, n is even if not n is odd.

You can also use ternary operators ?: instead of if..else statement. Ternary operator is short hand notation of if...else statement.


Example 2: Program to Check Whether Number Entered by the user is Even or Odd using ternary operators.

// Check Whether Number Entered by the user is Even or Odd using Ternary Operator.

#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: 21
21 is odd.

Next Example

We hope that this Example helped you develop better understanding of the concept of Whether a Number is Even or Odd in C++.

Keep Learning : )

In the next Example, we will learn about C++ Check Whether an Alphabet is Vowel or Not.


- Related Topics