Methods
Java Program to Display Prime Numbers Between Intervals Using Function
A Java program to display prime numbers between two intervals using a user-defined function.
Problem Description
Write a Java program to display all prime numbers between two given intervals using a function.
Code
public class PrimeIntervals {
public static void main(String[] args) {
int low = 20, high = 50;
while (low < high) {
if(checkPrime(low))
System.out.print(low + " ");
++low;
}
}
public static boolean checkPrime(int num) {
boolean flag = true;
for(int i = 2; i <= num/2; ++i) {
if(num % i == 0) {
flag = false;
break;
}
}
return flag;
}
}Output
23 29 31 37 41 43 47 Explanation
checkPrime(): A separate method to check if a number is prime.- Loop: Iterates from
lowtohighand callscheckPrimefor each number.
