Input 10 numbers in 1d array and print only the prime numbers from it in Java
One Dimensional Array - Question 4
In this question, we will see how to input 10 numbers in a one dimensional integer array and print only the prime numbers from it in Java programming. To know more about one dimensional array click on the one dimensional array lesson.
Q4) Write a program in Java to input 10 numbers in a one dimensional integer array and print only the prime numbers from it.
A prime number is a number which is divisible by 1 and itself. Example: 13, 17, 19, etc.
Program
import java.util.Scanner;
public class Q4
{
public static void main(String args[])
{
int a[]=new int[10], i,j,c=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter 10 numbers");
for(i=0; i<10; i++)
{
a[i]=sc.nextInt();
}
System.out.println("\nPrime Numbers");
for(i=0; i<10; i++)
{
c=0;
for(j=1; j<=a[i]; j++)
{
if(a[i]%j==0)
{
c++;
}
}
if(c==2)
{
System.out.print(a[i]+" ");
}
}
}
}
Output
Enter 10 numbers 5 12 18 23 17 45 93 62 7 54 Prime Numbers 5 23 17 7