C program to check even or odd using bitwise operator
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. Let's have a look at the below step by step logic to check whether the given number is even or odd.
Before writing any program you just imagine about output screen first. Like what input to be given, and output to be displayed. Let's have a look at the below example.
- INPUT
- Enter a number: 15
OUTPUT
15 is odd number.
Required knowledge for this exercise
Logic to check whether the given number is even or odd using bitwise operator:
To check whether the given number is even or odd, we need to check LSB of a number. If LSB is 1 then the given number is odd and If LSB is 0 then the given number is even.
Now perform bitwise AND & to check LSB of a number. like if (num & 1) it retrns LSB of a number either 1 or 0. If LSB is 1 then the given number is odd otherwise even number.
Note: if (num & 1) is equivalent to if (num & 1 == 1)
Program to check whether the given number is odd or even using bitwise operator:
-
#include <stdio.h>
int main()
{
int num;
printf("Enter any number: ");
scanf("%d", &num);
- /* if(num & 1) is equivalent to if(num & 1 == 1)
- * if it returns 1 the the number is odd else even
- */
if(num & 1)
{
printf("%d is odd number.", num);
}
else
{
printf("%d is even number.", num);
}
return 0;
}
Output:
- Enter any number: 15
- 15 is odd number
As you can see in above image,15 & 1
returns to 1. Since, LSB of 15 is 1. since the given number 15
is odd number.
Above program can also be written using ternary (conditional) operator to minimize the code:
-
#include <stdio.h>
int main()
{
int num;
printf("Enter any number: ");
scanf("%d", &num);
- /* if(num & 1) is equivalent to if(num & 1 == 1)
- * if it returns 1 the the number is odd else even
- */
(num & 1) ? printf("%d is odd number.", num)
- : printf("%d is even number.", num);
return 0;
}
Help others by sharing this page.
Ahmad Irshad
Author & Editor
I love blogging, teaching, learning computer science and sharing it to others. I've written and develped this site so that students may learn computer science related tutorials eaisly. MCA / MCITP
Thursday, July 16, 2020
C
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.