Write a Java program that prints the first n prime numbers, where n is a positiv
ID: 3935006 • Letter: W
Question
Write a Java program that prints the first n prime numbers, where n is a positive integer that is given as input (from the user). For example, if the user enters 8, the program prints out the first 8 primes as follows: The first 8 primes are: 2, 3, 5, 7, 11, 13, 17, 19. The program must print out the first n primes for every n given by the user. The program should terminate only when the user enters a number that is not positive (the sentinel value). As an example, the following is the output of a sample run of the program:Explanation / Answer
/* Java Programme for Prime Number */
import java.util.Scanner;
public class Prime
{
public static void main(String []args)
{
int n,c,i;
System.out.println("Enter a positive integer ");
while(1==1)
{
i=2;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
if(n<0)
{
break;
}
else
{
if ( n >= 1 )
{
System.out.println("The First "+n+" prime numbers are : ");
}
for ( int count = 1 ; count <= n ; ) //repeat loop for display n prime numbers
{
for ( c = 2 ; c <= i - 1 ; c++ ) //loop used for a number i is prime or not
{
if ( i%c == 0 )
break;
}
if ( c == i ) //display if prime
{
System.out.println(" "+i);
count++;
}
i++;
}
}
System.out.println("Enter another positive integer ");
}
}
}
Output :
Enter another positive integer
8
The First 8 prime numbers are :
2
3
5
7
11
13
17
19
Enter another positive integer
-1
Ok.Bye..
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.