Java Program - Find All Prime Numbers in a Range
This program finds all prime numbers within a given range.
This program finds all prime numbers within a given range.
This Java program finds and prints all prime numbers within a specified range, from 10 to 50. The main method iterates through each number in the range and checks if it's prime using the isPrime method. The isPrime method returns true if the number is greater than 1 and has no divisors other than 1 and itself. If a number is prime, it's printed to the console. This process efficiently determines and displays prime numbers in the given range.
start = 10, end = 50;
11 13 17 19 23 29 31 37 41 43 47
public class PrimeNumbersInRange {
public static void main(String[] args) {
int start = 10, end = 50;
for (int i = start; i <= end; i++) {
if (isPrime(i))
System.out.println(i);
}
}
public static boolean isPrime(int number) {
if (number <= 1)
return false;
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0)
return false;
}
return true;
}
}
11
13
17
19
23
29
31
37
41
43
47
import java.util.Scanner; public class PrimeNumbersInRange { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the start of the range: "); int start = scanner.nextInt(); System.out.print("Enter the end of the range: "); int end = scanner.nextInt(); System.out.println("Prime numbers between " + start + " and " + end + " are:"); for (int i = start; i <= end; i++) { if (isPrime(i)) System.out.println(i); } } public static boolean isPrime(int number) { if (number <= 1) return false; for (int i = 2; i <= number / 2; i++) { if (number % i == 0) return false; } return true; } }
This Java program prompts the user to input a start and end value for a range. It then finds and prints all prime numbers within that range. The isPrime method determines if a number is prime by checking for divisors up to half of the number. If no divisors are found, the number is prime and printed to the console. This program efficiently identifies and displays prime numbers in the user-specified range.
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.