This is a Java Program to Put Even & Odd Elements of an Array in 2 Separate Arrays.
Enter size of array and then enter all the elements of that array. Now with the help of for loop and if condition we check whether its odd or not and hence print it accordingly.
Here is the source code of the Java Program to Put Even & Odd Elements of an Array in 2 Separate Arrays. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
import java.util.Scanner;
public class Even_Odd
{
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:
$ javac Even_Odd.java $ java Even_Odd Enter no. of elements you want in array:8 Enter all the elements: 1 2 3 4 5 6 7 8 Odd:1,3,5,7 Even:2,4,6,8
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
advertisement
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Practice Programming MCQs
- Practice BCA MCQs
- Check Java Books
- Check Programming Books
- Apply for Java Internship