Sum of Prime Numbers
This program calculates the sum of prime numbers up to 20 using for loop.
Problem Statement
Write a Java program that calculates the sum of prime numbers up to 20 using for loop.
Source Code
| 1 | public class SumPrimes { |
| 2 | public static void main(String[] args) { |
| 3 | int sum = 0; |
| 4 | for(int num=2; num<=20; num++) { |
| 5 | boolean prime = true; |
| 6 | for(int i=2; i<=num/2; i++) { |
| 7 | if(num % i == 0) { |
| 8 | prime = false; |
| 9 | break; |
| 10 | } |
| 11 | } |
| 12 | if(prime) { |
| 13 | sum += num; |
| 14 | } |
| 15 | } |
| 16 | System.out.println("Sum of primes = " + sum + " - Eduinq"); |
| 17 | } |
| 18 | } |
Program Output
Sum of primes = 77 - Eduinq
Explanation
The outer loop iterates through numbers 2 to 20. The inner loop checks divisibility. If prime, the number is added to sum. This demonstrates how nested loops can calculate sum of prime numbers. Shows how for loop can calculate sum of prime numbers.