Check EVEN or ODD without using Modulus (%) Operator in C

By: IncludeHelp, on 26 JAN 2017

The way that most of the programmers are use to check whether a given number is EVEN or ODD is: to check number is divisible by 2 or not.

If the number is divisible by 2 that mean number is EVEN otherwise Number is ODD.

Since there may many logics to do one task, EVEN or ODD number can also be checked with many logic, here I am sharing a simple logic by using it you check find whether a number is EVEN or ODD.

Checking EVEN or ODD using Bitwise AND operator

Yes, we can check whether given number is EVEN or ODD by using Bitwise AND operator, we should know that each ODD number's first bit is 1, so here I will check first bit only, if it is high (1) that means number is ODD otherwise number is EVEN.

Here is the program

#include <stdio.h>

int main()
{
	int a=36;
	int b=25;
	
	if(a&(0x01))
		printf("%d is ODD number\n",a);
	else
		printf("%d is EVEN number\n",a);

	if(b&(0x01))
		printf("%d is ODD number\n",b);
	else
		printf("%d is EVEN number\n",b);	
	
	return 0;
}

Output

    36 is EVEN number 
    25 is ODD number

Here, 0x01 is the value to check first (0th bit of a number)





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.