Java Program to find prime numbers in an array


In this program, You will learn how to find prime numbers in an array in Java.


Some list of prime numbers is: 2 3 5 7 9 11 13


Example: How to find prime numbers in an array in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int i, s, j, p;
        int arr[] = new int[100];
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter Size of An Array :");
        s = sc.nextInt();

        System.out.print("\nEnter Array Elements :");
        for (i = 0; i < s; i++) {
            arr[i] = sc.nextInt();
        }

        System.out.print("\nAll Prime Numbers are :");

        for (i = 0; i < s; i++) {
            j = 2;
            p = 1;
            while (j < arr[i]) {
                if (arr[i] % j == 0) {
                    p = 0;
                    break;
                }
                j++;
            }
            if (p == 1) {
                System.out.print(" " + arr[i]);
            }
        }

    }
}

Output:

Enter Size of An Array :5
Enter Array Elements :2 3 4 5 6
All Prime Numbers are : 2 3 5