This post originated from an RSS feed registered with Java Buzz
by instanceof java.
Original Post: Program Check even or odd Without using modulus and division operators
Feed Title: Instance Of Java
Feed URL: http://feeds.feedburner.com/blogspot/TXghwE
Feed Description: Instance of Java. A place where you can learn java in simple way each and every topic covered with many points and sample programs.
Checking the number even or odd program is very easy. Anybody can solve this but there is a condition we need to see.
When we get this question in interview "write a program to check given number is even or odd" always continues with "without using modulus and division operators".
Before going to actual program lets see how to check a number is even or odd by using modulus.
Program to check number is even or odd by using modulus "%" operator
package instanceofjava;
import java.util.Scanner;
public class EvenorOdd {
public static void main(String []args ) {
int number;
Scanner in= new Scanner(System.in);
System.out.println("Enter a number to check even or odd");
number=in.nextInt();
if((number % 2)==0){
System.out.println(+number+" is Even number");
}else{
System.out.println(+number+" is Odd Number");
}
}
}
Enter a number to check even or odd
37
37 is Odd Number
Program to check number is even or odd by using division "/" operator
package instanceofjava;
import java.util.Scanner;
public class EvenorOdd {
public static void main(String []args ) {
int number;
Scanner in= new Scanner(System.in);
System.out.println("Enter a number to check even or odd");
number=in.nextInt();
if((number / 2)*2=number){
System.out.println(+number+" is Even number");
}else{
System.out.println(+number+" is Odd Number");
}
}
}
Enter a number to check even or odd
46
46 is Even Number
Without using modulus and division operators:
The above two programs will check number is even or odd and displays result.
Now we need to write a program to check even or odd without using modulus and division operators.
It is very simple if you know about operators including "BIT WISE".
Yes using Bit Wise AND "&" operator we can check a number is even or odd.
Before starting our program lets see how this bit wise AND "&" operator will work.
Bitwise Operators :
Bit wise operators will work on bits at a time.
AND : 1 & 1=1
OR : 0 | 1= 1 , 1 | 0=1 , 1| 1= 1
XOR: 0 | 1= 1 , 1 | 0=1
NOT : !0=1
Take two number 2 and 3
010 : 2 011 : 3 ------ 010 : 2
------
Take two numbers 2 and 1
010 :2 001 :1 ----- 000 :0 -----
From above example we can say that on every even number & 1 gives 0.
So this is our logic to be implemented in our program if "Number & 1==0" then its even number.
Program to check number is even or odd by using "/" operator and "%" operator
package instanceofjava;
import java.util.Scanner;
public class EvenorOdd {
public static void main(String []args ) {
int number;
Scanner in= new Scanner(System.in);
System.out.println("Enter a number to check even or odd");