Home / Programs / Java Program - Sum of Prime Numbers in a Range
Programming Example

Java Program - Sum of Prime Numbers in a Range

👁 132 Views
💻 Practical Program
📘 Step by Step Learning

This program calculates the sum of all prime numbers in a given range.

Information & Algorithm

Given Input:


Expected Output:


Program Code

public class SumOfPrimes {
    public static void main(String[] args) {
        int start = 10, end = 50;
        int sum = 0;

        for (int i = start; i <= end; i++) {
            if (isPrime(i))
                sum += i;
        }
        System.out.println("Sum of prime numbers between " + start + " and " + end + " is: " + sum);
    }

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

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.