Print Primes in Range in Java: Explanation & Practice
Print all prime numbers in a range
Problem summary
Write a program that prints all prime numbers between 2 and n (inclusive).
Starter code
public class Main {
public static void main(String[] args) {
int n = 20; // Test case 1
// Print all primes from 2 to n
// Each on a new line
}
}Expected output and test cases
- Primes up to 20
2 3 5 7 11 13 17 19
- Primes up to 10
2 3 5 7
- Primes up to 5
2 3
Hints
- Outer loop goes through each number
- For each number, check if it's prime
- Use nested loop or helper logic for prime check
Related Control Flow exercises
- Practice Prime Number Check in Java
- Practice Nth Fibonacci Number in Java
- Practice Sum of Series in Java
Practice all Control Flow exercises · Run this idea in the Java compiler