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.



Method 2: (Using string array)




Method 3: (Using while loop)




Don’t forget to share with us if you find any more interesting methods to solve this problem.
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding đŸ™‚

Leave a Reply

newest oldest most voted
Notify of
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:

The code still has jump instruction like “jne” etc, so avoiding to write explitely an if statment doesnt mean that there are no branches.
Also be mindful of concatenaded logic &&, c++ standard enforce short ciruit, meaning that if the left hand side evaluate to false, there is no point to evaluate the right hand side, since no matter the value the condition will be false, again that is handled at instruction level with jump instructions.

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: This also produces code without any branching instructions, as can be seen here.