Home / Programs / Java Program - Find All Prime Numbers in a Range
Programming Example

Java Program - Find All Prime Numbers in a Range

👁 206 Views
💻 Practical Program
📘 Step by Step Learning

This program finds all prime numbers within a given range.

Information & Algorithm

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.

Given Input:

start = 10, end = 50;

Expected Output:

11
13
17
19
23
29
31
37
41
43
47

Program Code

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;
    }
}

Output

11
13
17
19
23
29
31
37
41
43
47

Explanation

Java Program to Find Prime Numbers in a User-Defined Range


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.

How to learn from this program

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.