Java Program to separate even and odd in two separate arrays

Java Program to separate even and odd in two separate arrays

In this tutorial you will be learning writing java program to separate the even and odd number in two different arrays. To perform this, we will create two array with name evenArr and oddArr. Now using percentile operator we can identify number is even or odd.

For example:

Suppose given array is arr =[2, 4, 1, 5, 6, 2, 8]

Now oddArr become [1, 5]

evenArr become [2, 4, 6, 2, 8]

Program : Program to separate even and odd number of array in two separate arrays

  • In the below program, we have an array to get the input from the users.
  • Now to separate even and odd number we will be using percentile operator.
  • If number will be divided by 2 then store it in evenArray and if the number won’t divided then store it in oddArray.
import java.util.*;
public class Main{
    public static void main (String[]args){
    Scanner sc = new Scanner (System.in);
    
    //taking array size and array element as input
    System.out.println ("Enter the size of array1: ");
    int size = sc.nextInt ();
    int j=0, k=0;
    int arr[] = new int[size];
    int evenArr[] = new int[size];
    int oddArr[] = new int[size];
    for (int i = 0; i < size; i++){
	    System.out.print ("Please give value for index " + i + " : ");
	    arr[i] = sc.nextInt ();
    }
    
    //Logic to store even number in even array
    //And odd element to odd array
    for (int i = 0; i < size; i++){
        if(arr[i]%2==0){
            evenArr[j] = arr[i];
	        j++;
        }
	    else{
	        oddArr[k] = arr[i];
	        k++;
	    }
    }
    System.out.println("The Even elements of array are : ");
    for (int i = 0; i < j; i++){
            System.out.println(evenArr[i]);
    }
    System.out.println("The Odd elements of array are : ");
    for (int i = 0; i < k; i++){
            System.out.println(oddArr[i]);
    }
    }
}

Output

Enter the size of array1: 
6
Please give value for index 0 : 1
Please give value for index 1 : 3
Please give value for index 2 : 2
Please give value for index 3 : 4
Please give value for index 4 : 5
Please give value for index 5 : 6
The Even elements of array are : 
2
4
6
The Odd elements of array are : 
1
3
5