Sunday, 18 January 2015

Java Program to Print Prime Numbers


                                  Java Program to Print Prime Numbers

This java program prints prime numbers between the input value provided by the user. The smallest prime number starts with 2.



1:  import java.util.Scanner;  
2:  public class Prime {  
3:       /**  
4:        * @param args  
5:        */  
6:       public static void main(String[] args) {  
7:            int iNumber,iRemainderValue;  
8:            //Scanner class used for I/O operations  
9:            Scanner scanner=new Scanner(System.in);  
10:            System.out.println("Enter the number till which you want to generate prime numbers:");  
11:            iNumber=scanner.nextInt();  
12:            //outer loop iterates till iNumber value   
13:            for(int i=2;i<iNumber;i++)  
14:            {  
15:                 iRemainderValue=0;  
16:                 //inner loop checks if value of i is divisible by j values and sets the   
17:                 //iRemainderValue value accordingly.  
18:                 for(int j=2;j<i;j++)  
19:                 {  
20:                      if(i%j==0)  
21:                           iRemainderValue=1;  
22:                 }  
23:                 if(iRemainderValue==0)  
24:                 {  
25:                      System.out.print(i +" ");  
26:                 }  
27:            }  
28:       }  
29:  }  


Enjoy Reading.

No comments:

Post a Comment