How to check in PHP or JavaScript to display a given digit is EVEN or ODD without using conditional operators or control structures (i.e. without if, for, foreach, do-while, etc)?
For example, If my input is 20 then system should output "EVEN" and for the input 21 output should be "ODD" . Likewise for any numbers.
Any help will be appreciated.
PHP
$vals = ['EVEN','ODD'];
echo $vals[$digit % 2];
I do not know if it counts, but Java could do System.out.println(input % 2 == 0 ? "even" : "odd");
... It is a hidden if()
though
C# How about
var x = new []{"EVEN", "ODD"}[(i & 1)];
Sure, in C# it would look like this:
var evenodd = new[] { "even", "odd" };
var digit = 1; // or however you get your digit
Console.WriteLine(evenodd[digit % 2]);
Pretty simple - by doing % 2
on the value you get either a 1 or 0 back, which you can then use as an index into the array. You would be able to use this method in any of the languages you list.
In javascript, using bitwise operator &
var n = 3;
['EVEN', 'ODD'][n & 1]; // ODD
var n = 4;
['EVEN', 'ODD'][n & 1]; // EVEN
Snippet:
document.write(['EVEN', 'ODD'][3 & 1]);
document.write('<br>')
document.write(['EVEN', 'ODD'][4 & 1]);
</div>
Based off @Mark Baker's nifty little (PHP) code:
$eo = function($d, $a = ['EVEN','ODD']) {
return $a[$d % 2];
};
echo $eo($digit);