Find Even or Odd without using if and switch case

Find Even or Odd without using if and switch case

This blog explains about how to Find Even or Odd Number without Conditional Statement 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

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

 Explanation :- Here Most important line is

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/

We are a team of passionate trainers and professionals at Payilagam, dedicated to helping learners build strong technical and professional skills. Our mission is to provide quality training, real-time project experience, and career guidance that empowers individuals to achieve success in the IT industry.
Scroll to Top