Write a program in Java to generate first n prime numbers [JAVA sem 5]

  • The prime numbers can be divided by themself or by 1 without any remainder. 
  • in this program we have to print the first 10 prime numbers : 2,3,5,7,11,13,17,19,23,29.
  • Let's do some java to print the first 10 prime numbers. here is the code below.
Create a Primes.java file and write this code in it.

public class Primes
{  
    public static void main(String[] args)   
    {  
    	int ct=0,n=0,i=1,j=1;  
	while(n<10)  
	{  
          j=1;  
	  ct=0;  
	  while(j<=i)  
	  {  
		if(i%j==0)  
		ct++;  
		j++;   
	  }  
	  if(ct==2)  
	  {  
		System.out.printf("%d ",i);  
		n++;  
	  }  
	  i++;  
	  }  
    }  
}  

The output will be something like this. 



Comments