Java program to store 20 numbers in an array and find out prime and composite numbers in it
Answers
import java.util.Scanner;
class prime_composite {
public static void Print(Object _object_) {
System.out.print(_object_);
}
public static void main(String[] args) {
long[] data = new long[20];
Scanner getInput = new Scanner(System.in);
for (int i = 0; i < data.length; i++) {
int l = i + 1;
Print("Enter a number (" + l + "): ");
data[i] = getInput.nextLong();
Print("\n");
}
getInput.close();
Print("Prime numbers: ");
for (int i = 0; i < data.length; i++) {
if (!isPrime(data[i])) {
if (data[i] != 0)
Print(data[i] + " ");
}
}
// using 2 for loop becuase of formatting issue
Print("\nNon-prime number: ");
for (int i = 0; i < data.length; i++) {
if (isPrime(data[i]))
Print(data[i] + " ");
}
Print("\nComposite numbers: ");
for (int i = 0; i < data.length; i++) {
if (isComposite(data[i]))
Print(data[i] + " ");
}
// again using 2 for loop because of formatting issue
Print("\nNon-composite numbers: ");
for (int i = 0; i < data.length; i++) {
if (!isComposite(data[i])) {
if (data[i] != 0)
Print(data[i] + " ");
}
}
}
public static boolean isComposite(long number) {
if (number > 0)
return true;
else
return false;
}
public static boolean isPrime(long number) {
boolean flag = false;
for (long i = 2; i <= number / 2; i++) {
if (number % i == 0) {
flag = true;
break;
}
}
if (!flag)
return flag;
else
return flag;
}
}