Write a C function to check if a given integer is odd or even using bitwise operators.

To determine if a given integer is odd or even we should check its least significant bit (LSB). If least significant bit of an integer is 1, it will be an odd number else it would be even. We can use bitwise AND (&) operator for checking if a given integer is odd or even. When bitwise AND is performed on an integer and 1 then result will be 1 if the integer is odd, else the result will be zero. Following program develops a small C function isOdd that receives an integer as input and return zero or one depending upon the inputted number is even or odd.

C program to check if a given integer is odd or even using bitwise operators.

/* Write a C program to check if a given 
   integer is odd or even using bitwise operators. 
 */
 
#include <stdio.h>
#include <string.h>
 
int isOdd (int n)
{
  if (n & 1)
    return 1;
  else
    return 0;
}
 
int main(void)
{
  unsigned int n;
  printf("Enter a positive integer: ");
  scanf("%u", &n);
  if (isOdd(n))
    printf("%d is odd", n);
  else
    printf("%d is even", n);
}
 
OUTPUT
======
Enter a positive integer: 11
11 is odd
 

Hope you have enjoyed reading C program that checks if a given integer is odd or even using bitwise operators. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!




Get Free Tutorials by Email

About the Author

is the main author for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.

Today's Tech News

Bees 'go online' in ManchesterPosted on Friday September 22, 2017

Rory visits a beekeeper in Manchester who is gluing wireless chips to his bees.

The long wait for a Persian iPhone keyboardPosted on Friday September 22, 2017

The new Apple's iOS has Persian keyboard. BBC Persian's Sam Farzaneh discusses why it is an important feature.

Uber London loses licence to operatePosted on Friday September 22, 2017

Ride-hailing app Uber is "not fit and proper" to operate in London, the transport regulator says.

Courtesy BBC News

AD BLOCKER DETECTED!

Advertisements help running this site for free.


To view the content please disable AdBlocker and refresh the page.

×