Advertisements

Checking for Odd or Even without using any Conditional Statements

Last day my friend asked me a question to write a program which tells whether a given number is odd or even without using any conditional statements. It is very simple. There may be several solutions. Two of the solutions are given below. The code is given below

Using Array


public void OddEven(int num)
	{
		String []store = {"even","odd"};
		System.out.println("The number is "+store[(num%2)]);	
	}

Using try-catch

public void EvenOdd ( int num)
	{
		int temp = num%2;
		try {
			int ans = 10/temp;
			System.out.println("Number is odd");
		}
		catch (Exception e) {
			System.out.println("Number is Even");
		}
	}
Advertisements