Friday, July 31, 2009

How to check if a number is odd or even without using the modulus in c programming?

I assume that your number is an integer. Easiest is to use the bitwise "and" operation:





if ((x %26amp; 1) != 0) printf ("x is odd\n");





------------------


The questioner asked for further detail in email, so:





Well, if this is about an exam, I'm sure that they've covered bit operations in C.





C = A %26amp; B; means AND all of the bits of A and B together. Each bit in C is set if and only if both corresponding bits are set in A and B.





C = A | B; means OR all of the bits of A and B together. Each bit in C is set if either corresponding bit is set in A and B.





C = A ^ B; is an "exclusive OR" (XOR). Each bit in C is set if the corresponding bits bits in A and B are different.








So, in my original answer the result of the expression (A%26amp;1) will have 0's in all but the lowest bit. The lowest bit will be equal to the lowest bit of A.





And in binary, any even number has a lowest bit equal to zero, and any odd number has a low bit equal to 1. (It's kind of like in decimal, that any number divisible by 10 has a last digit of 0.)





There are other ways you could have done this, such as:





if ((a/2)*2 == a) printf ("a is even\n");





but the %26amp; example is much more efficient.





Good luck.

How to check if a number is odd or even without using the modulus in c programming?
if (x/2)=round(x/2) then even else odd?





I guess that would work.


No comments:

Post a Comment