C++ Program to check whether the number is odd or even

Before we start writing code let us understand what is odd number or even number and logic behind it.

An even number is any number that are perfectly divisible by 2. Example 2 , 4, 6, 8 ….

An odd number is any number that are not perfectly divisible by 2. Example 1, 3, 5, 7,….

Logic: The given number is even if it is divisible by 2 and take the remainder is 0 else the number is odd.

Example: -If we divide 10 by 2 then its remainder is 0 . Hence, 10 is an even number.
-If we divide 15 by 2 then its remainder will be 1. Hence 15 is an odd number.

In C++ programing we have modulo operator (%) that will give us remainder when one number is divided by another.

Example if we perform 10 % 3 then it will give 1 as a result.
Let’s implement it programmatically

Example 1: Program to Check Even or Odd Using If else Condition

#include < iostream >
using namespace std;
int main() {
int number;
cout << "Enter any number: ";
cin >> number;
if (number % 2 == 0) {
cout << "The given number is even";
} else {
cout << "The given number is odd";
}
return 0;
}

Output

Enter any number: 5
The given number is odd
Enter any number: 30
The given number is even

In above code, input from user is taken. We declared number variable as integer variable to store the input given from the user we have done it by

int number; //declare number as integer variable
cout<<"Enter any number: "; //display user to enter number
cin>>number; //store number enter by user

In expression

if(number%2==0){
cout<<"The given number is even";
}
else{
cout<<"The given number is odd";
}

Here, (number%2) is evaluated as we know modulo(%) returns 0 for even and other for odd.

‘==’ operator check whether the result is 0 or not. If test operation (number%2==0) returns true then, ‘if’ condition i.e. ”The given number is even” get executed, else test operation comes false and code inside ‘else’ condition i.e. “The given number is odd’ get executed.