Write a program that accepts a number from the user and prints “Even” if the entered number is even and prints “Odd” if the number is odd. You are not allowed to use any comparison (==, <,>,…etc) or conditional statements (if, else, switch, ternary operator,. Etc).
Method 1
Below is a tricky code can be used to print “Even” or “Odd” accordingly.
#include using namespace std; int main() { char arr[2][5] = { "Even", "Odd" }; int no; cout << "Enter a number: "; cin >> no; cout << arr[no % 2]; getchar(); return 0; }
Method 2
Below is another tricky code can be used to print “Even” or “Odd” accordingly. Thanks to student for suggesting this method.
#include int main() { int no; printf("Enter a no: "); scanf("%d", &no); (no & 1 && printf("odd"))|| printf("even"); return 0; }
Output
Enter a no: even
Please write comments if you find the above code incorrect, or find better ways to solve the same problem
Method 3
This can also be done using a concept known as Branchless Programming. Essentially, make use of the fact that a true statement in Python (other some other languages) evaluates to 1 and a false statements evaluates to false.
# code n = int(input("Enter a number: ")) print("Even" * (n % 2 == 0), "Odd" * (n % 2 != 0))
Output
Enter a number: Even