C Program – Check Whether Number is Even or Odd - Modulus & Bitwise

Even or Odd Using Modulus

#include <stdio.h>
int main() {
    int num;
    printf("Enter an integer: ");
    scanf("%d", &num);
    if (num % 2 == 0) {
        printf("%d is even\n", num);
    } else {
        printf("%d is odd\n", num);
    }
    return 0;
}
Enter an integer: 9
9 is odd
        

The modulus operator returns the remainder of a division. An even number yields a remainder of zero when divided by 2; otherwise the number is odd.

Even or Odd Using Bitwise AND

#include <stdio.h>
int main() {
    int num;
    printf("Enter an integer: ");
    scanf("%d", &num);
    if ((num & 1) == 0) {
        printf("%d is even\n", num);
    } else {
        printf("%d is odd\n", num);
    }
    return 0;
}
Enter an integer: 12
12 is even
        

An integer's least significant bit is 0 for even numbers and 1 for odd numbers. Bitwise AND with 1 quickly checks this bit and determines parity.

Sai Kishore Randhi, author
About the author

Sai Kishore Randhi

Embedded systems, VLSI, and chip design

Sai Kishore writes about embedded systems, VLSI, chip design, and the programming concepts behind modern hardware.

View LinkedIn profile ↗