Print “Even” or “Odd” without using conditional statement

Write a C/C++ 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 (if, else, switch, ternary operator,..etc) statement.

Method 1
Below is a tricky code can be used to print “Even” or “Odd” accordingly.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
#include<conio.h>
  
using namespace std;
  
int main()
{
  char arr[2][5] = {"Even", "Odd"};
  int no;
  cout << "Enter a number: ";
  cin >> no;
  cout << arr[no%2];
  getch();
  return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

arr = ["Even", "Odd"]
print ("Enter the number")
no = input()
print (arr[int(no) % 2])

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
$arr = ["Even", "Odd"]; 
$input = 5;
echo ($arr[$input % 2]);
  
// This code is contributed
// by Aman ojha
?>

chevron_right


Method 2
Below is another tricky code can be used to print “Even” or “Odd” accordingly. Thanks to student for suggesting this method.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<stdio.h>
int main()
{
    int no;
    printf("Enter a no: ");
    scanf("%d", &no);
    (no & 1 && printf("odd"))|| printf("even");
    return 0;
}

chevron_right


Please write comments if you find the above code incorrect, or find better ways to solve the same problem

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Improved By : Prateek Bajaj, Aman ojha

Article Tags :
Practice Tags :


8


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.