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.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...