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

  1. Outer loop goes through each number
  2. For each number, check if it's prime
  3. Use nested loop or helper logic for prime check

Related Control Flow exercises

Practice all Control Flow exercises · Run this idea in the Java compiler