Java Program to Separate Odd and Even Numbers from an Array
In this post, you will learn how to separate odd and even numbers from an array using the Java programming language.
Algorithm: Separate Odd and Even Numbers
This algorithm ensures that the numbers are separated into two distinct arrays based on whether they are odd or even.
1. Initialize empty arrays:
oddArray = []
evenArray = []
2. For each element in the original array:
If element is even:
Append element to evenArray
Else:
Append element to oddArray
3. Output evenArray
4. Output oddArray
Java program to separate odd and even numbers
import java.util.Arrays;
public class SeparateOddEven {
public static void main(String[] args) {
int[] array = {21, 45, 6, 31, 88, 91, 66};
System.out.println("Original Array: " + Arrays.toString(array));
// Arrays to store odd and even numbers
int[] oddArray = new int[array.length];
int[] evenArray = new int[array.length];
int oddIndex = 0, evenIndex = 0;
// Separate odd and even numbers
for (int num : array) {
if (num % 2 == 0) {
evenArray[evenIndex++] = num;
} else {
oddArray[oddIndex++] = num;
}
}
// Trim arrays to remove trailing zeros
oddArray = Arrays.copyOf(oddArray, oddIndex);
evenArray = Arrays.copyOf(evenArray, evenIndex);
System.out.println("Even Numbers: " + Arrays.toString(evenArray));
System.out.println("Odd Numbers: " + Arrays.toString(oddArray));
}
}
Output of the above code:
Original Array: [21, 45, 6, 31, 88, 91, 66]
Even Numbers: [6, 88, 66]
Odd Numbers: [21, 45, 31, 91]
Code Explanation:
- Input Array: {21, 45, 6, 31, 88, 91, 66}
- The program separates the array into two new arrays: one for odd numbers and one for even numbers.
- It iterates over the original array, checking each element to see if it’s even or odd.
- Even numbers are added to evenArray, and odd numbers are added to oddArray.
- The arrays are then trimmed to remove unused elements (trailing zeros).
Related Articles
Number pattern programs in JavaJava program to find area of rectangle
Matrix multiplication in Java
Electricity bill program in Java
Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java
Check whether the given number is even or odd in java
Print prime numbers from 1 to 100 in Java
Java prime number program
Java program to convert celsius to fahrenheit
Fibonacci series program in Java
Java program to check leap year
Java program to find factorial of a number