Science, asked by jiog3625, 1 year ago

Print 'Even' or 'Odd' without using conditional statement.

Answers

Answered by gourab2717guha
0

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

1) #include<iostream>

2) #include<conio.h>


4) using namespace std;

 5)

6) int main()

7) {

8) char arr[2][5] = {"Even", "Odd"};

9)  int no;

10)  cout << "Enter a number: ";

11)  cin >> no;

12)  cout << arr[no%2];

13) getch();

14)  return 0;  

15) }

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

1) #include<stdio.h>

2) int main()

3) {

4)   int no;

5)  printf("Enter a no: ");

6)  scanf("%d", &no);

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

8) return 0;

9) }

10) }

Explanation :- Here Most important line is

1) /* Main Logic */

2)

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

4)

5) //(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’.

Thank u, hope it will help. Mark me as brainliest if you wish.


gourab2717guha: Please do some corrections. In method 1, no. 3 is the space I left, and no. 5 is one space backward.
Similar questions