In C++, it is straightforward to check whether a number is even or odd.
The modulo operator (%) can be used to determine whether a number is divisible by two or not.
If a number is divisible by two, it is an even number, and if not, it is an odd number.
Here’s the C++ code to check whether a number is even or odd:
#include <iostream> using namespace std; int main() { int number; cout << "Enter a number: "; cin >> number; if (number % 2 == 0) { cout << number << " is even." << endl; } else { cout << number << " is odd." << endl; } return 0; }
In the code above, we first prompt the user to enter a number. Then we use the modulo operator to check if the number is divisible by two.
If the remainder of the division is zero, the number is even, and we print a message stating that.
If the remainder is one, the number is odd, and we print a different message.
That’s it! With just a few lines of code, we can easily determine whether a number is even or odd in C++.