C / C++ FAQs & Programming Resources - ProkutFAQ : EvenOddWithoutModulus

HomePage Recent Changes Recently Commented Login/Register
Quick Links
Categories
Links

How to find whether a given number is even or odd without using % (modulus) operator ?

A newbie question. Here is a simple C++ solution.

bool isOdd(int num){
    return num&1?true:false;
}


If the number is odd then it's least significant bit (LSB) is set i.e. it is 1. If it is even then it is 0. When you bitwise and (&) this number with 1, the result would be either 1 if the number is odd or zero if it is even.

As rightly pointed out by SpS, the same code can be implemented in C (following C99 standard) as

#include <stdbool.h>
bool isOdd(int num){
       return (num&1)?true:false;
}


Here stdbool.h defines the macros bool, true and false. The macro bool is defined to be _Bool (the boolean type according to C99 standard). true is a macro which expands to the decimal constant 1 and false is a macro which expands to decimal constant 0.

For C89 sticklers

int isOdd(int num){
       return (num&1);
}


You can use the returned value to determine if the number is odd or not. If the value returned is 0, the number is even. It is odd otherwise.


CategoryPuzzles
 Comments [Hide comments/form]
I think one has to be explicit about what standard we are taking into consideration.
C89 doesn't have any bool type.
C99 has _Bool which can take two values true and false. It also has bool, true and false as macros defined in <stdbool.h>
-- SpS (2006-11-07 09:38:08)
"So here the value returned is automatically converted to bool behind the scenes and you get the expected results"

I think above statement needs more explanation.
Since there is lot of existing code which uses "int" as a flag, the compiler implicitly converts "int" to "bool". Though good compilers will still show warning for this.
-- SpS (2006-11-07 09:41:09)
@SpS,

Yeah you are right. I should have mentioned that this is a C++ code snippet. And thanks for that suggestion on implicit conversion from "int" to "bool". I will add more to this section tonite.
-- PriyaSridharan (2006-11-08 13:52:06)
2nd code is worthful..... but were can i get C99 compiler Software.... which site??
-- 203.153.35.72 (2007-12-22 06:06:02)
Page was generated in 0.0394 seconds