Java Program to find Even and Odd Numbers in the arrays

There occurs a situation where we want to sort array according to even and odd numbers,with the help of this program we can serve this purpose.

Array-->1,2,3,4,5,6,7,8,9,10
Even Number in Array are:
 2 4 6 8 10
Odd Number in Array are:
 1 3 5 7 9

From the Above example it is very clear what we wants to do.

Note: Using Simple even odd logic we can code for this program

Logic: if(array[i]%2==0) then even.Else odd

For This Program we are going to take Two example. In Example-1 we will be taking static Inputs(i.e predefined inputs). And in Example-2 we will be taking User defined Inputs.

Example 1: Static Inputs

Algorithm/Program Explanation

  1. start
  2. define array[]={data};
  3. define for loop
  4. for(int i=0;i<array.length;i++)
    • check for condition
      • if(array[i]%2==0)
      • print even=array[i];
  5. for(int i=0;i< array.length;i++)
    • check for condition
      • if(array[i]%2!=0)
      • print odd=array[i];
  6. end
/*
Java program To Find Even Odd Number in an Array */
import java.util.*;
public class evenoddarray{
 public static void main(String args[]) {
  int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  System.out.println("Even Elements in Arrays are:");
  for (int i = 0; i < array.length; i++) {
   if (array[i] % 2 == 0) {
    System.out.println(array[i]);
   }

  }
  System.out.println("Odd Elements in Array are:");
  for (int i = 0; i < array.length; i++) {
   if (array[i] % 2 != 0) {
    System.out.println(array[i]);
   }
  }
 }}
Even Elements in Arrays are:
2
4
6
8
10
Odd Elements in Array are:
1
3
5
7
9

Example 2-Taking User Defined Inputs

import java.util.*;
public class evenoddarray{
 public static void main(String args[]) {
  int size;
  System.out.println("Enter the Size of Array:");
  Scanner sc=new Scanner(System.in);
  size=sc.nextInt();
  int array[] = new  int[size];
  System.out.println("Enter All Elements in Array:");
  for(int i=0;i<size;i++){
   array[i]=sc.nextInt();}
  System.out.println("Even Elements in Arrays are:");
  for (int i = 0; i < array.length; i++) {
   if (array[i] % 2 == 0) {
    System.out.println(array[i]);
   }

  }
  System.out.println("Odd Elements in Array are:");
  for (int i = 0; i < array.length; i++) {
   if (array[i] % 2 != 0) {
    System.out.println(array[i]);
   }
  }
 }}
Enter the Size of Array:
10
Enter All Elements in Array:
1 2 3 4 5 6 7 8 9 10
Even Elements in Arrays are:
2
4
6
8
10
Odd Elements in Array are:
1
3
5
7
9

Related Topics

Leave a Comment