This post on Java Program to list Prime numbers using for loop is the same as the **Java Program to check whether a number is prime or not**.

The **explanation **is the same as checking for prime number, the only difference is that we set the last range number that is we take user input for the* last number* and check for prime number from 1 to that *last number*.

And if the boolean variable *isPrime *is true after checking for each number, it will print the number for each iteration.

## Example: Java Program to list Prime Numbers using for Loop.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | //list Prime numbers using for loop import java.util.Scanner; public class ListingPrimeNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the last number:"); int num = scanner.nextInt(); System.out.println("Displaying Prime numbers between 1 to " +num); for(int i = 1; i < num; i++) { boolean isPrime = true; //checking for prime for(int j=2; j < i ; j++) { if(i % j == 0) { isPrime = false; break; } } //Displaying the numbersr if(isPrime) System.out.print(i + " "); } } } |

**Output:**

1 2 3 4 | Enter the last number: 50 Displaying Prime numbers between 1 to 50 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 |