Sum of Even Numbers

This program calculates the sum of even numbers from 1 to 20 using for loop.

Problem Statement

Write a Java program that calculates the sum of even numbers from 1 to 20 using for loop.

Source Code

1 public class SumEven {
2 public static void main(String[] args) {
3 int sum = 0;
4 for(int i=2; i<=20; i+=2) {
5 sum += i;
6 }
7 System.out.println("Sum of even numbers = " + sum + " - Eduinq");
8 }
9 }

Program Output

Sum of even numbers = 110 - Eduinq

Explanation

The program uses a for loop starting from 2 and increments by 2 each time to cover even numbers. Each iteration adds the current even number to sum. After the loop ends, the total sum is printed. Shows how for loop can calculate sum of even numbers.

Quick Links to Explore