C (programming language)

Logic to print given number is even or odd using bitwise AND (&) operator

Understanding the Problem

  • Goal: Create logic to determine whether a given number is even or odd using the bitwise AND operator.
  • Key Concepts:
    • Bitwise operations: Manipulating individual bits within numbers.
    • AND operator (&): Compares corresponding bits and produces a 1 only when both bits are 1.
    • Least significant bit (LSB): The rightmost bit in a binary representation, indicating even or odd.

Step-by-Step Guide

1. Check the Least Significant Bit

  • Explanation: The LSB determines even or odd:
    • 0 for even numbers (e.g., 10 = 1010 in binary, LSB is 0).
    • 1 for odd numbers (e.g., 9 = 1001 in binary, LSB is 1).

2. Apply Bitwise AND with 1

C

if (number & 1 == 0) {
    // Number is even
} else {
    // Number is odd
}
  • Explanation:
    • number & 1: Performs a bitwise AND with 1, isolating the LSB.
    • == 0: Checks if the LSB is 0 (even) or 1 (odd).

Example Code

C

#include <stdio.h>

int main() {
    int number = 12;  // Change this to test different numbers

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

    return 0;
}

Explanation of the Code:

  1. The number variable holds the value to be checked (e.g., 12).
  2. The if statement uses bitwise AND with 1 and compares the result to 0:
    • If number & 1 is 0, the LSB is 0, indicating an even number.
    • If number & 1 is not 0, the LSB is 1, indicating an odd number.
  3. The appropriate message is printed based on the result.

Key Points

  • The bitwise AND operator is efficient for determining even or odd numbers.
  • It directly examines the LSB, which holds the parity information.
  • This logic can be incorporated into various programming tasks involving even/odd number checks.

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button