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

In this post, we will learn how to check whether a number is even or odd using the C++ Programming language.

Any number which is exactly divisible by 2 is called an even number. For example: 2, 8, 32, 246, . . . , etc.

Similarly, any number which returns a remainder when divided by 2 is called an odd number. For example: 3, 7, 15, 19, . . . , etc.

We will use the following methods to check whether a number is even or odd.

  1. Using Modulus Operator
  2. Using Bitwise Operator

So, without further ado, let’s begin this tutorial.

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

// C++ Program to Check Whether Number is Even or Odd Using Modulus Operator
#include <iostream>
using namespace std;

int main(){
    int n;
    
    // Asking for input
    cout << "Enter an integer to check: ";
    cin >> n;
    
    // Check Even or Odd
    if (n % 2 == 0){
        cout << n << " is an even number." << endl;
    }
    else {
        cout << n << " is an odd number." << endl;
    }
    return 0;
}

Output 1

Enter an integer to check: 25
25 is an odd number.

Output 2

Enter an integer to check: 16
16 is an even number.

How Does This Program Work ?

    int n;

In this program, we have declared an integer data type variable named n.

    // Asking for input
    cout << "Enter an integer to check: ";
    cin >> n;

The user is asked to enter an integer to check for Odd and Even numbers.

    // Check Even or Odd
    if (n % 2 == 0){
        cout << n << " is an even number." << endl;
    }
    else {
        cout << n << " is an odd number." << endl;
    }

Now, we use the (%) modulus operator to check the number. Modulus (%) operator returns the remainder after division. If the remainder is equal to 0, then the entered number is an even number otherwise the entered number is an odd number.

C++ Program to Check Whether a Number is Even or Odd Using Bitwise Operator

// C++ Program to Check Whether a Number is Even or Odd Using Bitwise Operator
#include <iostream>
using namespace std;

int main(){
    int n;
    
    // Asking for input
    cout << "Enter an integer to check Odd/Even: ";
    cin >> n;
    
    // Checking using bitwise operator
    (n % 2 == 0) ? cout << n << " is an even number." : cout << n << " is an odd number.";
    return 0;
}

Output 1

Enter an integer to check Odd/Even: 19
19 is an odd number.

Output 2

Enter an integer to check Odd/Even: 26
26 is an even number.

Conclusion

I hope after going through this post, you understand how to check whether a number is even or odd using the C++ Programming language.

If you have any doubt regarding the program, then contact us in the comment section. We will be delighted to solve your doubts.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *