Home » Java programs » Java basic programs

Java program to print prime numbers between given range



Here, we are implementing java program that will read a minimum and maximum number and print the all prime numbers between the given range.
Submitted by IncludeHelp, on December 11, 2017

Given range (starting and end numbers) and we have to print the all prime numbers between the range using java program.

Example:

    Input:
    Enter the lower limit : 20
    Enter the upper limit :120

    Output:
    Prime numbers between given range are :
    23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113

Program to print prime numbers between range in java

import java.util.Scanner;

public class PrimeBetweenRange
{
	public static void main(String args[])
	{
		// initialize and declare here.
		int s1, s2,count = 0, i, j;
		Scanner s = new Scanner(System.in);
		System.out.print("Enter the lower limit : "); 
		s1 = s.nextInt();
		System.out.print("Enter the upper limit :"); 
		s2 = s.nextInt();
		System.out.println("Prime numbers between given range are :");

		for(i = s1; i <= s2; i++)
		{
			for( j = 2; j < i; j++)
			{
				if(i % j == 0)
				{
					count = 0;
					break;
				}
				else
				{
					count = 1;
				}
			}
			if(count == 1)
			{
				System.out.println(i);
			}
		}
	}
}

Output

Enter the lower limit : 20
Enter the upper limit :120
Prime numbers between given range are :
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
101
103
107
109
113





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.