Java Online Compiler
Example: Print Prime Numbers in a Range in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Print Prime Numbers in a Range import java.util.Scanner; // Main class containing the entry point of the program public class Main { // Method to check if a number is prime public static boolean isPrime(int num) { if (num <= 1) { return false; // Numbers less than or equal to 1 are not prime } // Check for divisibility from 2 up to the square root of the number // If a number has a divisor greater than its square root, it must also have a divisor smaller than its square root. for (int i = 2; i * i <= num; i++) { if (num % i == 0) { return false; // If divisible, it's not prime } } return true; // If no divisors found, it's prime } public static void main(String[] args) { // Step 1: Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter the start and end of the range System.out.print("Enter the starting number of the range: "); int start = scanner.nextInt(); System.out.print("Enter the ending number of the range: "); int end = scanner.nextInt(); // Step 3: Validate the input range if (start > end || start < 0) { System.out.println("Invalid range. Start number must be less than or equal to end number and non-negative."); scanner.close(); return; } // Step 4: Print a message indicating the prime numbers found System.out.println("Prime numbers between " + start + " and " + end + " are:"); // Step 5: Iterate through the range and check each number for primality for (int i = start; i <= end; i++) { if (isPrime(i)) { System.out.print(i + " "); } } System.out.println(); // For a new line at the end // Step 6: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS