Even Odd Program in Java
The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4, 8, -2, -16 are even numbers and the numbers -1, 1, 3, 5, 7, 9, 11 are odd. In this section, we have created Java programs with different approaches to check the number is even or odd.
The Modulus Operator Approach
Filename: ForLoopExample.java
Output:
Explanation: We are iterating over every element of the input array and invoking the method isEven(). The method uses the modulus operator (%) that finds the remainder when we divide the number by 2. If we get the remainder 0 the given number is even, else the number is odd.
Iterative Approach
Filename: EvenOddExample1.java
Output:
Explanation: We know that 0 is a multiple of 2. Therefore, 0 is an even number. Also, the sum of two even numbers is always an even number and the sum of one odd, and one even number is an odd number (For example, 2 + 6 = 8, 7 + 2 = 9). These concepts serve as the basis for distinguishing between even and odd numbers. We try to reduce every element of the input array to 0 by incrementing or decrementing by 2. If we become successful, the number is an even number, otherwise an odd number.
Recursive Approach
Filename: EvenOddExample2.java
Output:
Explanation: The concept used in the recursive approach is similar to what we have in the iterative approach. The only difference is instead of using a loop to reduce the input numbers to 0; we are reducing the number using the recursion.
Bitwise AND operator Approach
Filename: EvenOddExample3.java
Output:
Explanation: Apart from getting completely divisible by 2, the even numbers have one more unique feature. To learn about it, observe the following table:
Notice the rightmost bit of every number. We learn by the observation that for every odd number, the rightmost bit (or LSB) is 1, and for even numbers, it is 0. With the help of this concept, we are able to distinguish between an even and an odd number.
Usually, we should use the bitwise AND (&) or the modulus operator (%) approach to check the number is even or odd. Because these two approaches do not use the loop or recursion. However, during interview time, an interviewer may trick and can ask to write the logic to check the number is even or odd without using the modulus operator and loop. Therefore, we must know the iterative as well as the recursive approach, but, when given the liberty, the first and fourth approach should always take precedence over the second and third one.