Bitwise operator exercises
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. Logic to check even odd using bitwise operator in C programming.
Required knowledge
Operators, Data Types in c, Variables in C, Basic input/output,
Logic to check even or odd using bitwise operator
Least Significant Bit of an odd number is always set (1). To check whether a number is even or odd we need to figure out if LSB is set or not.

We use Bitwise AND & operator to check whether a bit is set or not. Similarly on performing num & 1 it return LSB of num. If LSB is 1 then the given number is odd otherwise even.

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 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; }
The statement if(num & 1) is equivalent to if((num & 1) == 1).
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 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.