English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to display prime numbers between two given intervals (low and high). You will learn to do this using while and for loops in Java.
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 non-prime numbers if (low % i == 0) { flag = true; break; } } if (!flag && low != 0 && low != 1) System.out.print(low + ""); ++low; } } }
When running this program, the output is:
23 29 31 37 41 43 47
In this program, prime number tests are performed for each number between low and high. The inner for loop checks if the number is a prime number.
You can check:Java Program to Check Prime Numbersfor more details.
Compared to the interval, the difference in checking individual prime numbers is that you need to reset flag = false in each iteration of the while loop.
Note: If the check is from 0 to10interval. So, you need to exclude 0 and1. Because 0 and1Is not a prime number. The condition is:
if (!flag && low != 0 && low != 1)