Java Program - Sum of Prime Numbers in a Range
This program calculates the sum of all prime numbers in a given range.
This program calculates the sum of all prime numbers in a given range.
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;
}
}
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.