Check for Even Odd in C++
Check even or odd in C++ with n % 2. Remainder 0 is even.
1#include <iostream>2using namespace std;34int main() {5 int num;67 cout << "Enter a number: ";8 cin >> num;910 if (num % 2 == 0) {11 cout << num << " is even" << endl;12 } else {13 cout << num << " is odd" << endl;14 }1516 return 0;17}
Output
Enter a number: 7 7 is odd
What's going on
This C++ program checks even vs odd with n % 2 == 0. Remainder 0 means even. That's the whole test.
#include <iostream>
Need it for cout and cin.
int num;
The value to test. Until cin fills it, don't print it.
cout << "Enter a number: ";
cin >> num;
Letters leave cin failed. Later the if then compares leftover junk.
if (num % 2 == 0)
% is remainder, not percent. 7 % 2 is 1, so odd. 8 % 2 is 0, so even.
Keep the == 0. if (num % 2) works because nonzero is true, and it's harder to read at 1 a.m.
Negatives: -3 % 2 is usually -1 in C++, not 1. == 0 still calls even numbers even. Don't rewrite the test to == 1 or -3 falls through the wrong branch.
0 is even. 0 % 2 == 0.
Sample: input 7 → remainder 1 → "7 is odd", which matches the output on this page.