C program to find odd or even number using bitmasking

In this article, we are going to see how to check a number odd or even using bitwise operators?
Submitted by Radib Kar, on December 30, 2018

Problem statement: Write a C program to find odd or even no using bitwise operators.

Solution: We can use bitwise operator here to solve the problem.

Solution

```    Let n be a number
n &1 = 0000000d where d is the LSB of n
So,
If LSB ==1
It's odd number
Else
Even no
```

To understand the concept of "LSB" & bitwise operators please read: Bitwise Operators and their working with Examples in C

Example:

```    Let n be 7 //00000111
n & 1 = 1
00000111(7) & 00000001(1) =00000001 (1)
Thus it's an odd number
Let n be 6 //00000110
N&1=0
00000110(6) & 00000001(1) =00000000 (0)
Thus it's an even number
```

C implementation

```#include <stdio.h>

int main()
{
int n;

printf("enter no: ");

scanf("%d",&n);

//n&1 actually results in 0000000d where d is your LSB
if(n&1==1)
printf("it's odd no");//for odd no LSB 1
else
printf("it's even no");//for even no LSB 0

return 0;
}
```

Output

```First run:
enter no: 7
it's odd no

Second run:
enter no: 6
it's even no
```

TOP Interview Coding Problems/Challenges

Learn PCB Designing: PCB DESIGNING TUTORIAL

 Recommended posts C Tips & Tricks, C++ Tips & Tricks Introduction to Linux (Its modes, Safety, Most popular Applications) Linux Best Distros of 2018 C programming optimization techniques Differences b/w C & Embedded C? Embedded C Interview Q. & A. C programming tips for Embedded Development Basic rules of writing a C program Important points (rules) to remember while writing C/C++ program Top 5 Websites for solving programming challenges Read more...

 Others... Computer G.K. (MCQ) Most viewed pages... Categories...

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates