Check number even or odd without using modulo operator

To Check odd or even without using modulus operator in java  we have different methods . Let’s dicuss these methods step by step.

Method 1. Program to check if the number is odd or even using bitwise (&) operator

We can check any number is odd or even with the help of bitwise & operator. if any number is odd it must have right most bit 1.
example:
int i=5;
binary form i= 0101
now use & operator bitwise operator
int j=i&1;[0101&1]
here j is 0001; so i is odd

Now if i =8 then binary is i=1000                                                                                            Now j=i&1[1000&1]                                                                                                            Here j is 0000 , so i is even

public class CheckEvenOrOdd {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n;
		System.out.println("Enter the number :");
		n = sc.nextInt();
		if (isEven(n) == 0)
			System.out.print("Even\n");
		else
			System.out.print("Odd\n");
	}

	private static int isEven(int n) {
		return n & 1;
	}

}

Output:

Enter the number :
9
Odd

Method 2. Program to check if the number is odd or even by divide and multiply by 2 method

We divide a number by 2 and then multiply by 2 and number is same as input then number is even otherwise odd.

import java.util.Scanner;

public class CheckEvenOrOdd2 {
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n;
		System.out.println("Enter the number :");
		n = sc.nextInt();
		if (isEven(n))
			System.out.print("Even\n");
		else
			System.out.print("Odd\n");
	}

	private static boolean isEven(int n) {
		return (n/2)*2==n;
	}

}

Output :

Enter the number :
10
Even

Method 3. Program to check if the number is odd or even using loop

In this method we will take a flag with value true then switch it n times . If result is true then given number is even otherwise odd.

import java.util.Scanner;

public class CheckEvenOrOdd3 {
		public static void main(String[] args) {
			Scanner sc = new Scanner(System.in);
			int n;
			System.out.println("Enter the number :");
			n = sc.nextInt();
			if (isEven(n))
				System.out.print("Even\n");
			else
				System.out.print("Odd\n");
		}

		private static boolean isEven(int n) {
			boolean even = true ;
			for (int i = 0; i < n ; i++) {
				even = !even;
			}
			return even;
		}
	
}

Output:

Enter the number :
10
Even

In this tutorial we have learned how to check given number is odd or even without using modulus operator in java . you can see more java coding question for interview preparation .

Leave a Reply

Your email address will not be published. Required fields are marked *

− 1 = 1