Java program to print prime numbers from an array

Sai Vishwanath
1 min readJan 4, 2017

--

Prime number is the number that is only divisible by 1 and the number itself. If the number leaves remainder 0 when divided by numbers other than 1 and the number itself then, the number is not said to be a prime number. To print the prime numbers from an array, user has to declare the size of the array size and enter the elements of the array. Prime numbers are identified using iterations with the help of for loop and condition for prime number is specified using if statement. Then the numbers that satisfy the condition i.e, prime numbers are displayed on the screen as output.

import java.util.Scanner;
public class PrimeNumbers{
public static void main (String[] args){
int[] array = new int [5];
Scanner in = new Scanner (System.in);

System.out.println("Enter the elements of the array: ");
for(int i=0; i<5; i++)
{
array[i] = in.nextInt();
}
Elements in the array are looped one by one using for loop. for(int i=0; i<array.length; i++){
boolean isPrime = true;

Using for loop and if condition, prime numbers are identified from all the numbers that are entered in the array.
for (int j=2; j<i; j++){

if(i%j==0){
isPrime = false;
break;
}
}

All the prime numbers or the numbers that satisfy the if condition are displayed as output.
if(isPrime)

System.out.println(i + " are the prime numbers in the array ");
}
}
}

Output : enter the elements of the array : 5

4

3

7

8

5,3,7 are the prime numbers in the array.

--

--