C program to check even or odd using bitwise operator

Write a C program to input any number and check whether the given number is even or odd using bitwise operator. How to check whether a number is even or odd using bitwise operator in C programming. How to use bitwise AND operator to check whether a number is even or odd in C programming.

Example

Input

Input number: 12

Output

12 is even

Required knowledge

Basic C programming, Bitwise operator, If else

Check this program using other approaches.

Read more -

Logic to check even or odd using bitwise operator

To check even or odd numbers you can use bitwise AND & operator. Bitwise operator operates on bit level, hence to check a number is odd we only need to check if its Least Significant Bit (LSB) is set or not. If 0th bit of a number is set (1) then the number is odd otherwise even.

Even odd using bitwise operator

In the above image you can see that if the number is even then its LSB is 0 otherwise LSB is 1. To check the status of any bit you can use bitwise AND operator. If num & 1 evaluates to 1 then the number is odd otherwise even.

Even odd using bitwise operator

Program to check even or odd using bitwise operator

/**
 * C program to check even or odd number using bitwise operator
 */

#include <stdio.h>

int main()
{
    int num;

    // Input a number from user
    printf("Enter any number: ");
    scanf("%d", &num);

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

    return 0;
}

Note: You can also use conditional operator to short the program as done below.

Program to check even or odd using conditional and bitwise operator

/**
 * C program to check whether a number is even or odd using bitwise operator
 */

#include <stdio.h>

int main()
{
    int num;

    // Input a number from user
    printf("Enter any number: ");
    scanf("%d", &num);

    (num & 1) ? printf("%d is odd.", num) : printf("%d is even.", num);

    return 0;
}

Output

Enter any number: 15
15 is odd.

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>