C program to print given number is even or odd using bitwise AND operator

Ex: How to find given number is even or odd using bitwise AND operator. C program to print given number is even or odd using bitwise AND operator. What is the logic to print given number is even or odd using bitwise  operator.


Input from user:

Enter the number 
5

Expected Output:

Given number is Odd





   Logic to print given number is even or odd using bitwise operator:


Firstly you need to know how bitwise AND operator works. We can use bitwise AND (&) operator to check given number is even or odd. For example, consider one odd number ( 5 ).  So binary of 5(0101), (5 & 1 = 1). Means least significant of every odd number is 1. Therefore (Odd number & 1) is  always one and also (Even number & 1) is zero.

In Below program we will use bitwise AND operator to check whether given number is even or odd.  [if(no & 1)] means if this condition is true then number is odd otherwise number is even. Because List significant Bit(LSB) of every odd number is 1 and even number is 0. Which is shown above.





   Program to print given number is even or odd using bitwise AND operator:



#include<stdio.h>
void main()
{
int no;
printf("Enter the number\n");
scanf("%d",&no);
if(no & 1)
printf("Given number is Odd\n");
else
printf("Given number is Even\n");
}

Above program shows the following output:


C program to print given number is even or odd using bitwise AND operator


No comments:

Post a Comment

If you have any doubts, please discuss here...👇