Operators Assignment 11 — Check Even/Odd Using Bitwise AND
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Check if a Number is Even or Odd Using Bitwise AND

📑 On this page:
  • Why bitwise AND works
  • Bitwise AND vs. modulo
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How the least significant bit determines even/odd
  • Why n & 1 is faster than n % 2 on most CPUs
  • Why n & 1 gives the right answer for negative numbers, while n % 2 can give −1
  • How to combine the check with a ternary expression for clean output
  • Why this pattern is a gateway to more complex bit manipulation

Why bitwise AND works

In binary, every integer's parity (even/odd) is determined by its least significant bit (LSB, bit 0). If the LSB is 0, the number is even. If the LSB is 1, the number is odd. That's because every power of 2 except 20 = 1 is even — so a number's parity is entirely determined by whether its 1's place is set.

The expression n & 1 isolates the LSB by ANDing with 1 (binary 0000 0001). Every bit above position 0 is zeroed out; only bit 0 survives. So n & 1 returns:

  • 0 — if n is even (LSB = 0)
  • 1 — if n is odd (LSB = 1)

That's the whole check. No loops, no division, no modulo — a single AND instruction, evaluated in one CPU cycle.

💡 In one line: n & 1 extracts the least significant bit — 0 for even, 1 for odd. It's the simplest and fastest parity check in C.
Even/odd check using bitwise AND in C — comparing the least significant bit of several integers.

Examples with binary:

4 = 0100 (LSB = 0 → even) 4 & 1 = 0 5 = 0101 (LSB = 1 → odd) 5 & 1 = 1 6 = 0110 (LSB = 0 → even) 6 & 1 = 0 7 = 0111 (LSB = 1 → odd) 7 & 1 = 1 8 = 1000 (LSB = 0 → even) 8 & 1 = 0

Bitwise AND vs. modulo

The classic way to check even/odd is n % 2. Both work, but there are two differences worth knowing:

1. Speed. The AND instruction is one CPU cycle; modulo requires a division operation (or a compiler-inserted AND, if the compiler is smart). Modern compilers optimize n % 2 into n & 1 automatically, so the practical speed difference is zero in optimized builds. But in hand-written code, n & 1 is unambiguously one instruction.

2. Behavior on negatives. This is the more important difference. Consider n = −7:

  • n % 2 = −1 (in C99 and later — the sign of the remainder matches the dividend).
  • n & 1 = 1 (bit 0 of −7 in two's complement is 1).

Both are "nonzero" and therefore "true," so if (n % 2) and if (n & 1) agree for negatives in practice. But if you're comparing against a specific value (e.g., if (n % 2 == 1)), the modulo check fails for negatives because −7 % 2 is −1, not 1. The bitwise version is safe: if ((n & 1) == 1) correctly identifies −7 as odd.

This is why n & 1 is the preferred idiom when working with signed integers, especially in code that might handle negatives. It's also the reason C textbooks and coding-interview solutions often use it — it's unambiguous.

Complete C Program

Here is the program — using if/else:

Program: Even/odd using if/else

#include <stdio.h>

int main(void) {
    int n;

    printf("Enter an integer: ");
    scanf("%d", &n);

    if (n & 1) {
        printf("%d is odd\n", n);
    } else {
        printf("%d is even\n", n);
    }

    return 0;
}
                                

A compact variant using the ternary operator:

Variant: Compact ternary form

#include <stdio.h>

int main(void) {
    int n;

    printf("Enter an integer: ");
    scanf("%d", &n);

    printf("%d is %s\n", n, (n & 1) ? "odd" : "even");

    return 0;
}
                                

Same logic, one line of output — perfect for scripting and quick tests.

A third variant — testing multiple numbers in a loop:

Variant: Test multiple numbers

#include <stdio.h>

int main(void) {
    int n;

    printf("Enter an integer (0 to stop): ");
    while (scanf("%d", &n) == 1 && n != 0) {
        printf("%d is %s\n", n, (n & 1) ? "odd" : "even");
        printf("Next: ");
    }

    return 0;
}
                                

This version reads integers until the user enters 0 or invalid input. Useful for testing the check against positive, negative, and zero values in one run.

Program Output

Sample run — even number:

Enter an integer: 42
42 is even
                            

42 = 101010 in binary — LSB is 0, so even. Correct.

Odd number:

Enter an integer: 27
27 is odd
                            

27 = 11011 — LSB is 1, so odd. Correct.

Negative odd number — where modulo would be tricky:

Enter an integer: -7
-7 is odd
                            

−7 % 2 would give −1 (nonzero, so "odd" either way), but −7 & 1 = 1 is unambiguously "the LSB is 1." The bitwise check is clean.

Zero — even by definition:

Enter an integer: 0
0 is even
                            

The multi-value variant:

Enter an integer (0 to stop): 4
4 is even
Next: 5
5 is odd
Next: -8
-8 is even
Next: -9
-9 is odd
Next: 0
                            

The check works uniformly for positive, negative, and zero values — as expected from a bit-level test.

Step-by-Step Explanation

1. Read an integer: scanf("%d", &n) reads a signed integer. The & here is the address-of operator (not bitwise AND). For a robust check, you might verify the return value: if (scanf("%d", &n) != 1) { /* error */ }.

2. The bitwise AND: n & 1 isolates the least significant bit. The constant 1 is 0000 0001 in binary (for a 32-bit int), so n & 1 clears all bits except bit 0. The result is 0 or 1.

3. The condition: if (n & 1) evaluates to true when the LSB is 1 (odd), false when it's 0 (even). This is a standard C idiom — if (x) means if (x != 0), and any nonzero value is truthy.

4. Parenthesization: The expression n & 1 is already at the "top level" of the condition, so no extra parentheses are needed. But if you combine it with other operators — e.g., if ((n & 1) == 1) — you must parenthesize the AND, because == has higher precedence than &. Without parentheses, n & 1 == 1 parses as n & (1 == 1), which is always n & 1 — actually that particular case happens to work out, but the principle is dangerous. Always parenthesize.

5. Ternary form: (n & 1) ? "odd" : "even" uses the conditional operator to pick a string. The result is passed to printf's %s format. This is a clean, concise idiom for simple branchless output.

6. Why it works for negatives: In two's complement, the LSB of −1 is 1, of −2 is 0, of −3 is 1, and so on. The parity is preserved: −7 = ...11111001, LSB is 1, odd. n & 1 correctly identifies every integer's parity, regardless of sign.

7. Comparison to n % 2: Both n & 1 and n % 2 answer the same question. The difference:

  • n & 1 returns 0 or 1 — always non-negative.
  • n % 2 returns 0 or ±1 — −1 for negative odd numbers.

So if (n & 1) and if (n % 2) behave identically (both are "true" for odd). But if (n % 2 == 1) is wrong for negative odd numbers (−7 % 2 == −1, so the check fails). if ((n & 1) == 1) is always correct. Use the bitwise form when you need exactness.

8. Performance: The AND instruction is one CPU cycle (LATENCY=1). The DIV/IDIV instruction (used by %) is 20–40 cycles on x86. So n & 1 is potentially 20–40× faster than n % 2. In practice, modern compilers optimize n % 2 to n & 1 for signed integers because they know the divisor is a power of 2 — so the speed difference is usually negligible in optimized builds. But if you're writing hand-optimized code (or working on a very old compiler), the AND is a clear win.

🎯 Key idea: n & 1 tests the least significant bit. Result 0 = even, 1 = odd. It's simpler and safer than n % 2, especially for negative numbers. It's the canonical example of "use bitwise operations when you're working with bits."

Frequently Asked Questions

1. Why does n & 1 work for even/odd?

Because the parity of a number is determined entirely by its least significant bit. If the LSB is 0, the number is a multiple of 2 (even). If it's 1, the number is odd. The AND with 1 isolates the LSB — every higher bit is cleared. So n & 1 is 0 for even and 1 for odd. This works for all integers, positive or negative, because two's complement preserves the parity in the LSB.

2. Is n & 1 faster than n % 2?

At the machine level, yes — bitwise AND is one instruction (1 cycle), while modulo involves division (20+ cycles). But modern compilers almost always optimize n % 2 to n & 1 automatically, because they recognize the divisor is a power of 2. In optimized builds, the two forms produce identical machine code. Use n & 1 when you want to make the intent explicit (you're testing a bit), or n % 2 when you want to say "I'm testing divisibility by 2." Both are idiomatic.

3. What about negative numbers?

n & 1 correctly identifies parity for negative numbers. In two's complement, −7 = ...11111001, LSB = 1 → odd. −8 = ...11111000, LSB = 0 → even. The AND works because it operates on the bit pattern, and the LSB is always the parity bit regardless of sign. This is one reason n & 1 is preferred over n % 2 == 1, which fails for negative odd numbers (because −7 % 2 == −1).

4. Can I write n & 1 == 1 without parentheses?

You can, but you shouldn't. == has higher precedence than &, so n & 1 == 1 parses as n & (1 == 1) = n & 1. In this particular case, the result is the same as (n & 1) == 1 because (1 == 1) = 1 and n & 1 is 0 or 1 — so the "wrong" parse gives the same answer. But this is a coincidence. In general, always parenthesize: (n & 1) == 1. It's clearer, and it's correct even when the "wrong" parse would give a different result (e.g., n & 1 != 0 parses as n & (1 != 0) = n & 1, which happens to also work, but n & 3 == 3 parses as n & (3 == 3) = n & 1, which is different from (n & 3) == 3). Parenthesize.

5. How would I check if a number is a multiple of 4?

Use n & 3 (binary 11). If the result is 0, the number is a multiple of 4 (its low 2 bits are both 0). If nonzero, it's not. Similarly: n & 7 == 0 tests divisibility by 8, n & 15 == 0 by 16, and so on. In general, n & (2k − 1) == 0 tests divisibility by 2k. This works because a multiple of 2k has its low k bits all zero — the mask 2k − 1 isolates exactly those bits. This is the "fast modulo for powers of 2" pattern.

💡 Tip: once this works, try these follow-ups: (a) check divisibility by 4 with n & 3, by 8 with n & 7, (b) check if a number is a power of 2 with n & (n - 1) == 0 (and n > 0), (c) implement a fast modulo for powers of 2: n & (m - 1) instead of n % m when m is a power of 2, (d) toggle a bit with n ^ (1 << k). Each uses the same bit-level thinking.

📖 Related Tutorials

  • Previous: Bitwise Right Shift Using '>>'
  • Next: Swap Two Numbers Without a Temp Variable
  • Bitwise AND on Two Numbers Using '&'
  • Bitwise XOR on Two Numbers Using '^'
  • Bitwise Operators in C — Full Tutorial
  • All 15 Operator Assignments in C
  • Operators FAQ

Previous Topic: -->> 10. Bitwise Right Shift on a Number Using the '>>' Operator   ||   Next Topic: -->> 12. Swap Two Numbers Without a Temporary Variable


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.