Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 6: Write a Java program to print all prime numbers between 1 to n (n is the number entered by the user).

Prime.java

import java.util.Scanner;

public class Prime
{
	public static void main(String[] args)
	{
		Scanner s= new Scanner(System.in);

		//Declaring Variables
		int n;
		int cur=2;

		System.out.println("Enter the number");
		n=s.nextInt();
	
		while(cur<=n)
		{
			int d=2;
			boolean dividend= false;

			while(d < cur)
			{
				if(cur%d==0)
				{
					dividend=true;
				}
				d=d+1;
			}

			if(!dividend)
			{
				System.out.println(cur);
			}

			cur=cur+1;
		}
   }
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.