In this article, we will show you, How to write a Java Program to Print Prime Numbers from 1 to N using For Loop, While Loop, and Functions.

**TIP:** Please refer Java Program to Check Prime Number article to understand the steps involved in checking Prime Number

## Java Program to Print Prime Numbers from 1 to N using For Loop

This program allows the user to enter any integer value. Next, it will print all the Prime numbers from 1 to 100 using For Loop.

// Java Program to Print Prime Numbers from 1 to N public class PrintPrimeNumbers1 { public static void main(String[] args) { int i, number, count; System.out.println(" Prime Numbers from 1 to 100 are : "); for(number = 1; number <= 100; number++) { count = 0; for (i = 2; i <= number/2; i++) { if(number % i == 0) { count++; break; } } if(count == 0 && number != 1 ) { System.out.print(number + " "); } } } }

**OUTPUT**

## Java Program to Print Prime Numbers from 1 to N using While Loop

This program will print list of prime numbers from 1 to 100 using While Loop.

// Java Program to Print Prime Numbers from 1 to N public class PrintPrimeNumbers2 { public static void main(String[] args) { int i, number = 1, count; System.out.println(" Prime Numbers from 1 to 100 are : "); while(number <= 100) { count = 0; i = 2; while(i <= number/2 ) { if(number % i == 0) { count++; break; } i++; } if(count == 0 && number != 1 ) { System.out.print(number + " "); } number++; } } }

We just replaced the For loop in the above example with the While loop. If you don’t understand the While Loop, please refer: WHILE LOOP

## Java Program to Print Prime Numbers from 1 to N using Method

This program is same as first example but we separated the logic and placed it in the separate method.

// Java Program to Print Prime Numbers between Minimum and Maximum import java.util.Scanner; public class PrintPrimeNumbers3 { private static Scanner sc; public static void main(String[] args) { int number, minimum, maximum, i, count; sc = new Scanner(System.in); System.out.print(" Please Enter the Minimum value : "); minimum = sc.nextInt(); System.out.print(" Please Enter the Maximum value : "); maximum = sc.nextInt(); System.out.println(" Prime Numbers from 1 to 100 are : "); for(number = minimum; number <= maximum; number++) { count = 0; for (i = 2; i <= number/2; i++) { if(number % i == 0) { count++; break; } } if(count == 0 && number != 1 ) { System.out.print(number + " "); } } } }

**OUTPUT**

Thank you for Visiting Our Blog

## Leave a Reply