Java Program to Print Odd and Even Numbers From an Array

Java program to print odd and even numbers from an array. even and odd elements of an array are separated in two arrays by a java program.  Enter the array’s size, followed by all of the array’s elements. Now, using the for loop and the if condition, we can determine whether the value is odd or not, and print it accordingly. the source code for a Java program that divides an array’s even and odd elements into two separate arrays.

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int n, j = 0, k = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter no of elements you want in array");
n = s.nextInt();
int a[] = new int[n];
int odd[] = new int[n];
int even[] = new int[n];
System.out.println("Enter all the elements");
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for(int i = 0; i < n; i++)
{
if(a[i] % 2 != 0)
{
odd[j] = a[i];
j++;
}
else
{
even[k] = a[i];
k++;
}
}
System.out.print("Odd");
if(j > 1)
{
for(int i = 0;i < (j-1); i++)
{
System.out.print(odd[i]+",");
}
System.out.print(odd[j-1]);
}
else
{
System.out.println("No number");
}
System.out.println("");
System.out.print("Even");
if(k > 1)
{
for(int i = 0; i < (k-1); i++)
{
System.out.print(even[i]+",");
}
System.out.print(even[k-1]);
}
else
{
System.out.println("No number");
}
}
}

 

Output:

Enter no. of elements you want in array 2
Enter all the elements
34
56
Odd No number

Even 34,56

Odd Number in Java

A simple whole number that cannot be split by two to get two equal whole numbers. The numbers 1, 3, 5, and 7 are all odd. Odd numbers are whole numbers that cannot be split into pairs exactly. When odd numbers are divided by two, the residual is one.

Even Number in Java

a whole number that may be split by two to provide two equal whole numbers An even number is any integer that can be split precisely by two. Even numbers usually have a final digit of 0, 2, 4, 6, or 8. Even numbers include 2, 4, 6, 8, 10, 12, 14, and 16. These are even numbers because they can be readily split by two.

If Else in Java Program

The if/else statement expands on the if statement by stating an action to be taken if the if (true/false expression) is false. The if/else statement instructs the program to execute either the true or false code block, therefore something is always done with an if/else statement.

Increment Operator in Java

A for loop does not accomplish anything. Your code in the for statement does this. It is totally up to you how/if/where/when you want to change I or any other variable. Using this increasing operator we can execute java program to print odd and even numbers from an array.