check even or odd c++
To check whether a number is even or odd in C++, you can use the modulo operator (%) to determine the remainder when the number is divided by 2. Here's the step-by-step explanation:
- Declare a variable to store the number:
int number;
- Prompt the user to enter a number:
cout << "Enter a number: ";
cin >> number;
- Use the modulo operator to check if the remainder is 0:
if (number % 2 == 0) {
// The number is even
} else {
// The number is odd
}
- Print the result:
if (number % 2 == 0) {
cout << "The number is even." << endl;
} else {
cout << "The number is odd." << endl;
}
In this code, the modulo operator (%) returns the remainder of the division operation. If the remainder is 0, it means the number is divisible by 2 and therefore even. If the remainder is not 0, it means the number is not divisible by 2 and therefore odd.
Note: The code assumes that you have included the necessary header files, such as <iostream>
for input/output operations.