Advertisements
Advertisements
Question
Write a program in Java to store 20 numbers in a Single Dimensional Array (SDA). Display the numbers which are prime.
Sample Input:
n[0] | n[1] | n[2] | n[3] | n[4] | n[5] | n[6] | n[7] | n[8] | n[9] |
45 | 65 | 77 | 71 | 90 | 67 | 82 | 19 | 31 | 52 |
Sample Output: 71, 67, 19, 31
Answer in Brief
Solution
import java.util.*;
public class AQ4{
public static void main(String[] pj){
Scanner ob = new Scanner(System.in);
int i, x, cnt = 0;
int n[] = new int[20];
// INPUT
System.out.println("Enter the numbers");
for (i = 0; i < n.length; i++)
n[i] = ob.nextInt();
// CHECKING OF INPUT AND OUTPUT OF ONLY PRIME NUMBERS
System.out.println("The Prime numbers are :");
for (i = 0; i < n.length; i++)
{
cnt = 0; // reset cnt for each input value
for (int j = 1; j <= n[i] / 2; j++)
{if (n[i] % j == 0)
cnt++;
}
if (cnt == 1)
System.out.printin(n[i]);
}
}}
shaalaa.com
Is there an error in this question or solution?