Skip to content
Devtoolry

Basics · beginner

C Program to Check Whether a Number is Even or Odd

Check whether a number is even or odd in C with the % operator and if/else, see why -3 % 2 is -1, and write the same test with the conditional operator.

An integer is even when dividing it by 2 leaves no remainder. In C the % operator gives the remainder, so n % 2 == 0 means even.

Since C99, the result of % has the sign of the left operand: -3 % 2 is -1, not 1. Checking == 0 for even is therefore safer than checking == 1 for odd.

The program

C
#include <stdio.h>

int main(void) {
    int numbers[] = {7, 12, 0, -3};
    int count = sizeof numbers / sizeof numbers[0];

    for (int i = 0; i < count; i++) {
        int n = numbers[i];
        if (n % 2 == 0)
            printf("%d is even\n", n);
        else
            printf("%d is odd\n", n);
    }
    printf("-3 %% 2 is %d\n", -3 % 2);
    return 0;
}
Output
7 is odd
12 is even
0 is even
-3 is odd
-3 % 2 is -1

How it works

  1. sizeof numbers / sizeof numbers[0] is the number of elements in the array (4).
  2. The for loop visits each element; n % 2 is its remainder after dividing by 2.
  3. A remainder of 0 means even; anything else (1 or -1) means odd.
  4. In printf, %% prints a literal percent sign.

Another way: With the conditional operator

The conditional operator ?: chooses between two expressions and fits inside printf. The bitwise test n & 1 is also common for integers.

C
#include <stdio.h>

int main(void) {
    int n = 15;
    printf("%d is %s\n", n, n % 2 == 0 ? "even" : "odd");
    printf("%s\n", (-3 & 1) ? "odd" : "even");
    return 0;
}
Output
15 is odd
odd

Common mistakes

  • Writing if (n % 2 == 1) for odd numbers, which is false for negative odd numbers.
  • Using = instead of ==: if (n % 2 = 0) does not compile.
  • Using % on a double: it only works on integers. Use fmod() from math.h for floating-point values.

Try it yourself

  • Read numbers with scanf until the input ends and count how many are even.
  • Print the even numbers from 1 to 20 with a loop that steps by 2.

Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 C examples, or write your own program in the online C Compiler.