Java Program to Display Prime Numbers Between Two Intervals
![Display Prime Numbers Between two Intervals](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9zNr1IBUFWSyjwz7qqQ38Sqe082JvpH8yzCTdV6byICPauOix9K3cgmDwehwwPTs1VdDjYPPpzF0-3N5nUUUXsKHzr1vNr4r0XqC-ObHgVmIJTw7LEzgY1oXStExt8NCgbyEer6_ZqLm0/w320-h240/w400h300_017.jpg)
In this program, you'll learn to display prime numbers between two given intervals, low and high. You'll learn to do this using a while and a for loop in Java.
Display Prime Numbers Between two Intervals
public class Prime
{
public static void main(String[] args)
{
int low = 20, high = 50;
while (low < high)
{
boolean flag = false;
for(int i = 2; i <= low/2; ++i)
{
// condition for nonprime number
if(low % i == 0)
{
flag = true;
break;
}
}
if (!flag && low != 0 && low != 1)
System.out.print(low + " ");
++low;
}
}
}
When you run the program, the output will be:
23 29 31 37 41 43 47
In this program, each number between low and high are tested for prime. The inner for loop checks whether the number is prime or not.
The difference between checking a single prime number compared to an interval is, you need to reset the value of flag = false on each iteration of while loop.
Note: If you check the interval from 0 to 10. Then, you need to exclude 0 and 1. As 0 and 1 are not prime numbers. The condition will be:
if (!flag && low != 0 && low != 1)