Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Check for Even Odd in C++

Check whether an integer is even or odd in C++ using the % operator and an if/else. Covers zero, negative numbers, and why == 1 is the wrong test for odd.

BeginnerConditional ProgramsExample 1 of 4
check-for-even-odd.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int num;
6
7 cout << "Enter a number: ";
8 cin >> num;
9
10 if (num % 2 == 0) {
11 cout << num << " is even" << endl;
12 } else {
13 cout << num << " is odd" << endl;
14 }
15
16 return 0;
17}

Sample Output

7 is odd

7 % 2 is 1, so the else branch ran.

In this one

  • How % gives the remainder after division
  • How if/else picks one of two branches
  • Why 0 counts as even
  • Why negative odd numbers give -1, not 1, with % 2

How it works

  1. 1

    Read num (7 in the sample).

  2. 2

    Compute num % 2, which is 1 for 7.

  3. 3

    Compare the remainder with 0.

  4. 4

    Because 1 is not 0, the else branch prints "7 is odd".

Edge cases

Negative odd number

Enter -3.

-3 % 2 is -1 in C++, so the test == 0 is false and the program correctly prints odd. A version that tests == 1 would wrongly call -3 even.

Zero

Enter 0.

0 % 2 is 0, so 0 is even. That matches the math definition.

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.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is -5 % 2 in C++?

Pick an answer to check it.

Question 2

Which input prints "is even"?

Pick an answer to check it.

Questions people ask

Is there a faster way than %?

num & 1 checks the lowest bit and is 1 for odd numbers. Compilers usually produce the same code for % 2, so pick whichever is clearer.

Can I check even/odd for a double?

% does not work on double. Convert to an integer first, or use fmod from <cmath>.

Why keep == 0 instead of if (num % 2)?

Both work, but == 0 says exactly what you mean and is easier to read.