Program opened below. You can scroll through the algorithm, Java code and output.
Program 25
Prime, Even and Odd Array Arrangement
Question
Read ten different integers. Copy them into another array with prime values first, followed by nonprime even values, followed by nonprime odd values; preserve order within each group.
Algorithm
Step 1: Start and declare original and destination arrays of ten integers.
Step 2: Accept ten distinct integer values.
Step 3: Initialize the destination index to zero.
Step 4: Define a function that checks whether a number is prime.
Step 5: Reject numbers below two in that function.
Step 6: Test divisibility through the square root for other values.
Step 7: Scan the original array from left to right.
Step 8: Copy all prime numbers to the destination.
Step 9: Scan the original array a second time.
Step 10: Copy all nonprime even numbers to the next available positions.
Step 11: Scan the original array a third time.
Step 12: Copy all nonprime odd numbers to the remaining positions.
Step 13: Use the same destination index across all three passes.
Step 14: Display the completed destination array.
Step 15: Stop.
Java program
Javaimport java.util.*;
class PrimeEvenOdd {
static boolean prime(int n) {
if (n < 2) {
return false;
}
for (int i = 2; i <= n / i; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] a = new int[10];
int[] b = new int[10];
int k = 0;
for (int i = 0; i < 10; i++) {
a[i] = sc.nextInt();
}
for (int i = 0; i < 10; i++) {
if (prime(a[i])) {
b[k++] = a[i];
}
}
for (int i = 0; i < 10; i++) {
if (!prime(a[i]) && a[i] % 2 == 0) {
b[k++] = a[i];
}
}
for (int i = 0; i < 10; i++) {
if (!prime(a[i]) && a[i] % 2 != 0) {
b[k++] = a[i];
}
}
for (int x : b) {
System.out.print(x + " ");
}
}
}Sample output
Input: 2 4 7 9 6 11 8 15 13 10
Output: 2 7 11 13 4 6 8 10 9 15