Java Program to print Prime numbers in a given range

Prime numbers in a given range using java :

In this article we will create a java program to find all prime numbers between the given range. For this purpose we will ask the user to enter starting range and ending range so that all prime numbers between this range can be find and prime number are the whole numbers which have two factors i.e. 1 and the number by itself. Some of the facts for the prime numbers are given below :-

  • 0 and 1 are not considered as prime number.
  • Except for 0 and 1, a number is either a prime number or a composite number.
  • Numbers that have more than two factors are called composite numbers.
  • The  1 is neither prime nor composite.
  • Except 2, all other even numbers are not prime.

The first 25 prime numbers (all the prime numbers less than 100) are : 2, 3, 5, 7, 11, 13, 17, 19, 23
29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97.

Prime numbers in a given range using Java

Working :

Step 1 : Ask the user to enter two ranges , one starting range and second ending range.

Step 2 : Use  a loop to find all prime numbers between starting range and ending range.

Step 3 : Use the logic for checking number is prime or not for every number between the given range and then display the result. 

Code in Java :

//Java program to print prime numbers in a given range
import java.util.Scanner;
public class prime_numbers_in_a_given_range
{
public static void main(String[] args)
{
//scanner class object creation
Scanner sc=new Scanner(System.in);
//input from user
System.out.print("Enter Starting Number : ");
int start = sc.nextInt();
System.out.print("Enter Ending Number : ");
int end = sc.nextInt();
System.out.println("Prime numbers between "+start+" and "+end+" are : ");
int count;
//loop for finding and printing all prime numbers between given range
for(int i = start ; i <= end ; i++)
{
//logic for checking number is prime or not
count = 0;
for(int j = 1 ; j <= i ; j++)
{
if(i % j == 0)
count = count+1;
}
if(count == 2)
System.out.println(i);
}
//closing scanner class(not mandatory but good practice)
sc.close();
}
}

Output : 

Enter Starting Number : 13
Enter Ending Number : 27
Prime numbers between 13 and 27 are :
13 17 19 23

Please Login/Signup to comment