C Program to Check Even or Odd using Bitwise Operator

In this article, we will create a C program to check even or odd using bitwise operator.

The program takes a number from the user as input and prints if it is even or odd on the screen as output.

Sample Input:

Enter the number: 25

Output:

25 is an Odd Number

A number is called an even number if it is divisible by 2 such as 2, 4, 6, etc. but if the number is not divisible by 2, it is called an odd number such as 1, 3, 5, etc.

A most commonly used approach to check if the number is even or odd in C programming is to use the modulus operator(%). But the modulus operator(%) makes the program execution a bit slower, therefore, we should use other approaches such as a bitwise operator.

If you take a closer look at the binary equivalents of even and odd numbers, you will find that the least significant bit(last bit) of all the even numbers is always 0, whereas the least significant bit of all the odd numbers is always 1.

Binary equivalent of decimal numbers to check last bit

So to check if a given number is even or odd, we can check its last bit. If the last bit is 0, it means the given number is even and if it is 1, it means the given number is an odd number.

To get the last bit of a number we can perform a bitwise AND(&) operation on that number. It will give you 0 for even numbers and 1 for odd numbers.

Check even odd with bitwise AND operator

The following C program shows how you can check if a number is even or odd using the bitwise & operator:

// C program to check even odd using bitwise & operator
#include <stdio.h>

int main(){
	
	int number;
	
	printf("Enter the number: ");
	scanf("%d", &number);
	
	// Check if the last bit is 0
	if((number & 1) == 0){
		printf("%d is an Even Number", number);
	}
	else{
		printf("%d is an Odd Number", number);
	}
	
    return 0;
    
}

Output:

Enter the number: 25
25 is an Odd Number

Code Explanation:

  • The program first asks the user to enter a number and store it in the number variable.
  • It then performs a bitwise AND(&) operation on the number and checks if the result is 0 or 1. If the result of the bitwise AND operation is 0, the if block runs and prints that the number is even.
  • If the result of the bitwise AND is 1, the else block runs and prints that the given number is odd.

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts