Prime Numbers in Range
Print all prime numbers in a given range.
IntermediateTopic: Module 3: Loop Programs
Java Prime Numbers in Range Program
This program helps you to learn the fundamental structure and syntax of Java programming.
public class Main {
private static boolean isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}
}Output
2 3 5 7 11 13 ... 97
Understanding Prime Numbers in Range
We implement a simple primality test and loop through the range, printing primes.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.