### Java Program to Print Prime Numbers between 1 to N - The Coding Shala

Home >> Java Programs >> Print Prime Numbers between 1 to N

In this post, we will learn how to display prime numbers between 1 to n using the Java program.

## Java Program to Print Prime Numbers between 1 to N

Write a Java Program to print prime numbers between 1 to given n.

Example 1:
Input: 10
Output: 2
3
5
7

Approach:

We are going to check every number from 1 to n, if it is prime then will print it.

Prime numbers are only divisible by 1 and the number itself, so if the given number is divisible by any other numbers from 2 to n-1 then it's not a prime number.

Java Program:

```/**
* https://www.thecodingshala.com/
*/

import java.util.Scanner;

public class Main {

public static boolean checkPrime(int num) {
if(num < 2) return false;

for(int i = 2; i * i <= num; i++) {
if(num % i == 0) return false;
}
return true;
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of n");
int n = sc.nextInt();
System.out.println("Prime number from 1 to " + n + " are: ");
for (int i=2; i <= n; i++) {
if (checkPrime(i)) {
System.out.println(i);
}
}
}
}
```

Output:

```Enter the value of n
15
Prime number from 1 to 15 are:
2
3
5
7
11
13
```

Other Posts You May Like