Programming Example
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 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.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.