Find if a number is even or odd without using any conditional statement

Given a number, find out if it is even or odd without using any conditional statement (if-else) or ternary operator.


 

Method 1: (Using short-circuiting in boolean expressions)

 

We can take advantage of short-circuiting in boolean expressions. We know that in boolean AND operation such as x && y, y is evaluated only if x is true. If x is false, then y is not evaluated, because the whole expression would be false which can be deduced without even evaluating y. Similarly, for boolean OR operation such as x || y, y is evaluated only if x is false. If x is true, then y is not evaluated. This is called short-circuiting in boolean expressions.

We can apply this logic to solve given problem. Consider below code snippet –

((num & 1) && printf("odd")) || printf("even");

Initially we check if num is odd or even. If num is odd, the first subexpression of AND becomes true and its second subexpression printf("odd") will be evaluated else if num is even, the first subexpression of OR will become false and its second subexpression printf("even") will be evaluated.
 

OR

 
 

Method 2: (Using string array)

 

OR

 
 

Method 3: (Using while loop)

 

OR

 

Don’t forget to share with us if you find any more interesting methods to solve this problem.
 
 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
Sort by:   newest | oldest | most voted
Marco Giordano
Guest
Marco Giordano
Although true, that in the code there is not an expllicit if statement, the codes boils down to branch instructions, please check the disassembly here: https://godbolt.org/g/fv6GK2 The code still has jump instruction like “jne” etc, so avoiding to write explitely an if statment doesnt mean that there are no branches.… Read more »
Jan Dolinár
Guest
Jan Dolinár

Marco is right, only the second method (string array) is branch-free. The first and third just hide the ‘if’ in different syntax.

Another funky way to do this without branching is with a bit of bit arithmetic: http://cpp.sh/4alwg. This also produces code without any branching instructions, as can be seen here.

wpDiscuz