Java program to print prime numbers from 2 to n

Let’s learn java program to print prime numbers from 2 to n.

Java program to print prime numbers from 2 to n

To print prime numbers from 2 to n first create checkPrime() method.

In checkPrime() method we have for loop from 2 to number/2.

Here if number divides by some number between 2 to (number/2)-1 then number will not be prime.

Here’s program to print prime numbers from 2 to n.

import java.util.Scanner;
public class PrimeNumberFrom2Ton
{
   public static void main(String[] args) 
   {
      int loop, num;
      System.out.println("Please enter value of n: ");
      Scanner sc = new Scanner(System.in);
      num = sc.nextInt();
      for(loop = 2; loop < num; ++loop)
      {
         if(checkPrime(loop))
         {
            System.out.println(loop);
         }
      }
      sc.close();
   }
   public static boolean checkPrime(int number)
   {
      int a;
      boolean boolPrime = true;
      for(a = 2; a < number / 2; a++)
      {
         if(number%a == 0)
         {
            boolPrime = false;
            break;
         }
      }
      return boolPrime;
   }
}


Output:

Please enter value of n: 20
2
3
4
5
7
11
13
17
19

Please enter value of n: 30
2
3
4
5
7
11
13
17
19
23
29