Saturday, January 23, 2010

Find odd or even without Relational operators

#include< stdio.h >
main()
{
int a;
scanf("%d",&a);
if(a&1)
printf("odd");
else
printf("even");
}

How it works?
'&' logical 'and' operator, this will 'and' a with 1.
all odd numbers have last bit value '1'. for example









Odd
1 have 0001
3 have 0011
5 have 0101








Even
2 have 0010
4 have 0100
6 have 0110


from above table we can come to one decision i.e., odd numbers will have last bit value as '1'. so we'and' the number with '1'. if result is 1, then 'if' will work and print "odd". if result is 0, then 'else' will work and print "even"

0 comments:

Post a Comment