Java program to put even & odd elements of an array in 2 separate arrays

Let’s learn java program to put even & odd elements of an array in 2 separate arrays.

Java program to put even & odd elements of an array in 2 separate arrays

In the below program to put even & odd elements of an array in 2 separate arrays first user is allowed to enter size and elements of one dimensional array using nextInt() method Scanner class.

Now to put even & odd elements of an array in 2 separate arrays use for loop and if condition. Finally print the seperated even & odd elements of an array in 2 seperate arrays. Here’s java program.

import java.util.Scanner;
public class EvenOdd2SeperateArrays
{
   public static void main(String[] args) 
   {
      int number, b = 0, c = 0;
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter number of elements in an array: ");
      number = sc.nextInt();
      int[] arrNumber = new int[number];
      int[] oddNumber = new int[number];
      int[] evenNumber = new int[number];
      System.out.println("Please enter all the elements in an array: ");
      for(int a = 0; a < number; a++)
      {
         arrNumber[a] = sc.nextInt();
      }
      for(int a = 0; a < number; a++)
      {
         if(arrNumber[a] % 2 != 0)
         {
            oddNumber[b] = arrNumber[a];
            b++;
         }
         else
         {
            evenNumber[c] = arrNumber[a];
            c++;
         }
      }
      System.out.print("Odd elements in an array: ");
      if(b > 1)
      {
         for(int a = 0; a < (b - 1); a++)
         {
            System.out.print(oddNumber[a] + ",");
         }
         System.out.print(oddNumber[b - 1]);
      }
      else
      {
         System.out.println("number not entered");
      }
      System.out.println("");
      System.out.print("Even elements in an array: ");
      if(c > 1)
      {
         for(int a = 0; a < (c - 1); a++)
         {
            System.out.print(evenNumber[a] + ",");
         }
         System.out.print(evenNumber[c - 1]);
      }
      else
      {
         System.out.println("number not entered");
      }
      sc.close();
   }
}


Output:

Please enter number of elements in an array: 10
Please enter all the elements in an array:
1
2
3
4
5
6
7
8
9
10
Odd elements in an array: 1,3,5,7,9
Even elements in an array: 2,4,6,8,10


Also read – major features of java