Find Even or Odd without using if and switch case
This blog explains about how to Find Even or Odd without using if and switch case and is illustrated below :
_______________________________________________________________________________
Hi Friends,
Today, we are going to find Even or Odd Without using if and switch case. The question asked here is – Write a program to find out if the given number is odd or even without using conditional statement like if or switch case.
Solution :
It is mentioned that We should not use if and switch case. That is the clue we should remember here. Hence, for finding out odd or even without those, we can go for array concept. Let me try a simple Java program with a String array which consists of just two elements.
Print “Even” or “Odd” without using conditional statement
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#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
1
2
3
4
5
6
7
8
9
10
|
#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
1
2
3
4
5
|
/* Main Logic */
(no & 1 && printf(“odd”))|| printf(“even”);
//(no & 1) <———-First expression
|
Declare the two string values in the array with index o and 1.
o => Even
1=> Odd
Any number divide with two its give remainder as o or 1. Thus, this remainder can be used in array index value.
Program:
public class EvenOdd {
public static void main(String[] args) {
String evenOdd[] = {“Even”,”Odd”}; // String array with only two elements
int number = 3;
int remainder= number % 2; // remainder is calculated.
System.out.println(evenOdd[remainder]);
}
}
Output:
Odd
_______________________________________________________________________________
REFERENCES :
http://www.firmcodes.com/print-even-odd-without-using-conditional-statement/