Spread the love

Write a C/C++ program that accepts a number from the user and prints “Even” and “Odd”. Your are not allowed to use any comparison (==, <, >..etc) or conditional (if, else, switch, ternary operator,..etc) statement.

Method 1 

#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;
}

 

Explanation:- Shortest logic ever is arr[no%2] which would return remainder. If remainder become 1, it will print “Odd”. And if remainder become 0, it will print “Even”.

 Method 2

#include<stdio.h>

int main()
{
    int no;
    printf("Enter a no: ");
    scanf("%d", &no);
    (no & 1 && printf("odd"))|| printf("even");
    return 0;
}

 

 Explanation :- Here Most important line is 

/* Main Logic */

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

//(no & 1)     <----------First expression
  • Let us understand First expression “no && 1”, if you enter 5 in place of no, your computer will store 5 as in binary like 0000 0000 0000 0101, with this binary you will perform & operation with 0000 0000 0000 0001 (which is 1 in decimal), in result, you get 0000 0000 0000 0001 (which is 1 in decimal), So output of first expression would be 1.
  • Output of First expression only become 1 or 0 in every case.
  • If output of first expression is 1, then it will perform && operation with printf(“odd”) and it will print ‘odd’.
  • If output of first expression is 0, then it will perform && operation with printf(“odd”) which become false because of zero and than || operation is performed with printf(“even”) which will print ‘even’.

If you like this Article, then don’t forget to Click on Social likes buttons.