C program to check Least Significant Bit (LSB) of a number is set or not

Write a C program to input any number from user and check whether the Least Significant Bit (LSB) of the given number is set (1) or not (0). How to check whether the least significant bit of a number is set or unset using bitwise operator in C programming. C program to get the status of least significant bit of a number.

Example

Input

```Input number: 11
```

Output

```Least Significant Bit of 11 is set (1).
```

Logic to check Least Significant Bit (LSB) of a number

We use Bitwise AND `&` operator to check status of any bit. Bitwise AND `&` operator evaluate each bit of the resultant value as 1, if corresponding bits of both operands are 1.

To check LSB of a number we need to perform bitwise ANDing. The bitwise AND operation `number & 1` will evaluate to 1 if LSB of number is set i.e. 1 otherwise evaluates to 0.

As you can see in above image `12 & 1` evaluate to 0. Since, LSB of 12 is 0. Whereas, `15 & 1` evaluate to 1 since LSB of 15 is 1.

Program to check Least Significant Bit (LSB) of a number

``````/**
* C program to check Least Significant Bit (LSB) of a 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) evaluates to 1 */
if(num & 1)
printf("LSB of %d is set (1).", num);
else
printf("LSB of %d is unset (0).", num);

return 0;
}``````

Important note: The statement `if(num & 1)` is equivalent to `if(num & 1 == 1)`.

Output

```Enter any number: 11
LSB of 11 is set (1).```

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