Java program to Print Prime Number in Given Range

In this tutorial, we will learn writing Java program to print all the prime numbers that are present in the given range.

Problem Statement

  • Our program will take two numbers as an input. For example user has given 3 and 13 as an input.
  • Now program will print all the prime numbers between 3 and 13.
  • So output will be 3, 5, 7, 11 and 13. Because this is the only five numbers which is prime.

What is Prime Number?

Prime Numbers are the numbers that have only 2 factors 1 and the number itself. It is only defined for the number which is greater than ‘1’. ‘2’ is the smallest prime number.

Some examples

  • 7 is a prime number because only factors of 7 are ‘1 and 7’.
  • 11 is a prime number because only factors of 11 are ‘1 and 11’.
  • 10 is not prime because the factors of 10 are ‘ 1,2,5 and 10’.
import java.util.*;
public class Main
{
    public static void main(String[] args) {
    int i=0,fNum,sNum, temp,temp1=1;
    Scanner sc = new Scanner(System.in);
    System.out.println("Please give the first number");
    fNum= sc.nextInt();
    System.out.println("Please give the second number");
    sNum= sc.nextInt();
    System.out.println("Prime numbers in range "+fNum+ " and " +sNum+"are");
    while(fNum<=sNum){
        temp=0;
        for(i=2;i<=(fNum/2);i++){
            if(fNum%i==0){
                temp=1;
                break;
            }
        }
        if(temp==0)
            System.out.println(fNum);
        fNum++;
    }
    }
}

Output

Please give the first number
5
Please give the second number
17
Prime numbers in range 5 and 17are
5
7
11
13
17

Explanation

The input numbers are 5and 20, so our program will check all the numbers smaller than 20 and greater than 5. The numbers that do not have any other factor other than 1 and itself, i.e. prime numbers in the given range are 5, 7, 11,13,17,19.