Wednesday, 9 October 2013

JAVA PROGRAMS 3

C)    Write a Java program that prompts the user for an integer and then prints out all prime numbers up to that integer.

Program:
import java.io.*;
class Prime
{
         int i,j,count;
         void seq(int n)
         {
                System.out.print("The Prime Numbers Upto "+n+" Are: ");
                for(i=1;i<=n;i++)
                        {
                        count=0;
                        for(j=1;j<=i;j++)
                                    {
                                                if(i%j == 0)
                                                            count++;
                                    }
                                    if(count==2)
                                                System.out.print(" "+i);
                        }                               
         }
         public static void main(String args[]) throws IOException
         {
           int n;
           Prime ob=new Prime();
           BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
           System.out.print("\nEnter The Value Of n: ");
           n=Integer.parseInt(br.readLine());
           ob.seq(n);
         }
}       

Output:
Enter The Value Of n: 21

The Prime Numbers Upto 21 Are: 2  3  5  7  11  13  17  19

FREE HIT COUNTERS