Even Odd-tutorial
This Java program checks each element in an array to determine whether it is even or odd. It is a basic and commonly asked programming question in Java interviews and coding exercises.
Example: Find Even and Odd Numbers
Output:
Explanation
Logic
- Even Number - divisible by 2 (i.e. number % 2 == 0)
- Odd Number - not divisible by 2 (i.e. number % 2 != 0)
Example: Find Even and Odd Numbers
import java.util.Scanner;
public class Main { public static void main(String[ ] args) { System.out.println("Even Odd Array Program");
Scanner input = new Scanner(System.in); System.out.println("Enter Array Size"); int size = input.nextInt(); // taking size input
int[] arr = new int[10]; // initialize array
System.out.println("Enter Array Values"); // taking array values for (int i = 0; i < size; i++) { arr[i] = input.nextInt(); }
EvenOdd(arr, size); // calling method }
public static void EvenOdd(int[] arr, int size) { for (int j = 0; j < size; j++) { if (arr[j] % 2 == 0) { System.out.println("Even : " + arr[j]); } else { System.out.println("Odd : " + arr[j]); } } }}
Output:
Even Odd Array ProgramEnter Array Size5Enter Array Values2220978Even : 22 Even : 20 Odd : 9 Odd : 7 Even : 8
Explanation
Value | Condition | Result |
---|---|---|
22 | 22 % 2 == 0 - true | Even |
20 | 20 % 2 == 0 - true | Even |
9 | 9 % 2 == 1 - true | Odd |
7 | 7 % 2 == 1 - true | Odd |
8 | 8 % 2 == 0 - true | Even |
Key Point
- % is the modulus operator used to get the remainder.
- The logic applies to both positive and negative integers.
- Ideal for practicing control structures and arrays.