Home »
Java Programs »
Java Array Programs
Java program to find prime and non-prime numbers in the array
Given/input an integer array, we have to find prime and non-prime numbers in the array.
By Nidhi Last updated : December 23, 2023
Problem statement
In this program, we will create an array of integers then we will find prime and non-prime numbers in the array.
Java program to find prime and non-prime numbers in the array
The source code to find Prime and Non-Prime numbers in the array is given below. The given program is compiled and executed successfully.
// Java program to find prime and non-prime
// numbers in the array
public class Main {
public static void main(String[] args) {
int cnt = 0;
int i = 0;
int flag = 0;
int intArr[] = {10, 11, 13, 15, 17, 19, 23, 25, 30};
for (cnt = 0; cnt < intArr.length; cnt++) {
flag = 0;
for (i = 2; i < intArr[cnt] / 2; i++) {
if (intArr[cnt] % i == 0) {
flag = 1;
break;
}
}
System.out.printf("%3d - %s\n", intArr[cnt], (flag == 0 ? "Prime" : "Not Prime"));
}
System.out.println();
}
}
Output
10 - Not Prime
11 - Prime
13 - Prime
15 - Not Prime
17 - Prime
19 - Prime
23 - Prime
25 - Not Prime
30 - Not Prime
Explanation
In the above program, we created a public class Main. It contains a static method main().
The main() method is an entry point for the program. Here, we created an array intArr with integer elements and find the prime and non-prime members in the array and printed them.
Java Array Programs »