C++ Program to check if a Number Is Even or odd
Check if a Number is Even or odd in C++
Given an integer input, the objective is to write a code to Check if a Number is Even or odd in C Language.
For Instance,
Input: Num = -5
Output: The number is Negative
Check if a Number is Even or odd in C++
Given an integer input, the objective is to check whether the given integer is Even or odd. In order to do so we have the following methods:
- Method 1: Using Brute Force
- Method 2: Using Nested if-else Statements
- Method 3: Using the ternary operator
C++ Program to Check Whether a Number is Even or Odd
Given an integer input, the objective is to write a C++ program to check whether a number is Even or Odd.
Method 1: Using Brute Force
#include <iostream>
using namespace std;
int main () {
int number;
cout << "Enter a number:";
cin >> number;
if (number % 2 == 0)
cout << number << " : Even";
else
cout << number << " : Odd";
return 0;
}
Output:
Enter a number: 4 4 : Even
Method 2: Using Ternary Operator
#include <iostream>
using namespace std;
int main () {
int number;
cout << "Enter a number:";
cin >> number;
number % 2 == 0 ? cout << "Even" : cout << "Odd";
return 0;
}
Output:
Enter a number: 17 Odd
Method 3: Using Bitwise Operator
#include <iostream>
using namespace std;
bool isEven(int number) {
return (!(number & 1));
}
int main() {
int number;
cout << "Enter the number: ";
cin >> number;
isEven(number) ? cout << "Even" : cout << "Odd";
return 0;
}
Output:
Enter a number: 13 Odd