Print Prime Numbers from 1 to N in Java

In this code sample, you will learn how to print prime numbers from 1 to N using java. The program will read the N value, entered by the user, then check whether a number is prime or not. The program will print all print numbers between 1 and N to the output.

What is a prime number?

A prime number is divided by 1 and itself, without a reminder.

1,2,3,4,7,11,12....

Get prime numbers between two integers using Java

The program will run an increment loop form 1 to the number (N) entered by the user; if the number cannot be divided by either one of itself, it’s a prime number, otherwise, it’s not.

import java.util. * ;

class Main {

  public static void main(String args[]) {
    int loop,
    n;

    System.out.print("Enter a value of N: ");
    Scanner scanner = new Scanner(System.in );
    n = scanner.nextInt();

    for (int i = 1; i < n; i++) {
      if (i % 2 != 0) {

        System.out.println(i);

      }

    }
    scanner.close();
  }
}

Output

1
3
5
7
9
11
13
15
17
19

One Reply to “Print Prime Numbers from 1 to N in Java”

Leave a Reply

Your email address will not be published. Required fields are marked *