In this part of the short tutorial series on C++, we will show you how to check whether a number entered by the user is Even or Odd.
- The number which can be divided by 2 is even
- The number that can’t be divided by 2 is odd
First Program – Using % operator in if else
The % operator is used to return the remainder after division.
As such, the remainder of a number that can be divided by two is always zero – we can use it to achieve our task i.e. a number input by the user is even or odd.
See the C++ program below that uses the % operator with if..else statements. For taking user input, we used C++ cin as shown in the program below:
#include <iostream> using namespace std; int main() { int number; //Asking user input to check for even or odd cout << "Please enter a number? "; cin >> number; //Using if with % operator to check if number is even or odd if ( number % 2 == 0) cout <<"The given number " << number << " is EVEN!" <<"\n\n"; else cout <<"The given number " << number << " is ODD!" <<"\n\n"; return 0; }
Sample Output 1:
Sample Output 2
Second Approach – Using Bitwise operator AND
This C++ program uses the AND bitwise operator to check if the number is Even or Odd:
#include <iostream> using namespace std; int main() { int number; //Asking user input to check for even or odd cout << "Please enter a number? "; cin >> number; //Using bitwise operator AND if((number & 1) == 0) cout <<"The given number " << number << " is EVEN!" <<"\n\n"; else cout <<"The given number " << number << " is ODD!" <<"\n\n"; return 0; }
Sample output 1
Sample output 1
Third Approach – Using ternary operator example
This program also tells if the entered number is even or odd by using the ternary operator.
Have a look at the code and sample outputs:
#include <iostream> using namespace std; int main() { int number; //Asking user input to check for even or odd cout << "Please enter a number? "; cin >> number; //Ternary operator to check a number is even or odd (number % 2 == 0) ? cout << number << " is an EVEN number!" : cout << number << " is and ODD number!"; return 0; }
Output:
Fourth Solution – Using Switch Case Statement
As such, the switch case is also a decision-making statement in C++. We include this example just to add another option if you get this assignment.
This example also uses the modulus operator (%), just like the if statement and remainder options are used as cases.
See the code and sample output below:
#include <iostream> using namespace std; int main(){ int number; //Asking user input to check for even or odd cout << "Please enter a number? "; cin >> number; switch(number % 2) { case 0: cout <<"The given number " << number << " is EVEN!" <<"\n\n"; break; case 1: cout <<"The given number " << number << " is ODD!" <<"\n\n"; break; } return 0; }
Output: