Java program to split the Even and Odd elements into two different lists


To split the Even and Odd elements into two different lists, the Java code is as follows −

Example

 Live Demo

import java.util.Scanner;
public class Demo{
   public static void main(String[] args){
      int n, j = 0, k = 0;
      Scanner s = new Scanner(System.in);
      System.out.println("Enter the number of elements required :");
      n = s.nextInt();
      int my_arr[] = new int[n];
      int odd_vals[] = new int[n];
      int even_vals[] = new int[n];
      System.out.println("Enter the elements of the array(even and add numbers) :");
      for(int i = 0; i < n; i++){
         my_arr[i] = s.nextInt();
      }
      for(int i = 0; i < n; i++){
         if(my_arr[i] % 2 != 0){
            odd_vals[j] = my_arr[i];
            j++;
         } else {
            even_vals[k] = my_arr[i];
            k++;
         }
      }
      System.out.print("The odd numbers in the array : ");
      if(j > 1){
         for(int i = 0;i < (j-1); i++){
            if(odd_vals[i]==1){
               System.out.println("1 is niether even nor odd");
            }
            else
            System.out.print(odd_vals[i]+",");
         }
         System.out.print(odd_vals[j-1]);
      } else {
         System.out.println("There are no odd numbers.");
      }
      System.out.println("");
      System.out.print("The even numbers in the array : ");
      if(k > 1){
         for(int i = 0; i < (k-1); i++){
            if(even_vals[i]==1){
               System.out.println("1 is niether even nor odd");
            }
            else
            System.out.print(even_vals[i]+",");
         }
         System.out.print(even_vals[k-1]);
      } else {
         System.out.println("There are no even numbers in the array.");
      }
   }
}

Output

Enter the number of elements required :
Enter the elements of the array(even and add numbers) :
The odd numbers in the array : 1 is niether even nor odd
9
The even numbers in the array : 2,4,6

Console input

5
1 2 4 6 9

A class named ‘Demo’ contains the main function that asks for the number of elements that should be stored in the array and declares two new arrays that will store the odd values and even values respectively. The array elements are taken from the user and a ‘for’ loop is run to check if the number is divisible by 0, i.e checking if the remainder when the number is divided by 2 is 0. If yes, then that number from the main array will be stored in the even array, and in the odd array otherwise. Since 1 is neither even nor odd, it prints the message while storing 1 in the even or odd array.

Updated on: 07-Jul-2020

674 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements