This article will explain 3 ways in which you can write a java program to calculate the sum of first n even numbers.
In the example programs given in this post, we will be calculating the sum of even numbers from 1 to 100.

Method 1: Using for loop
This method is based on the following algorithm steps.

1. Write a `for` loop to iterate from 1 to n or in this case from 1 to 100.
2. Declare a variable to hold the sum of even numbers and initialize it to 0.
3. Initialize a variable to hold the current even number and initialize it to 2 since 2 is the first even number.
4. In every iteration, add the current even number to sum and increment the value of current even number by 2 since all even numbers differ by 2.

Java program based on the above algorithm is given below.

```public class EvenNumberAdder { public static void main(String[] args) { int sum = 0, evenNumber = 2; // loop from 1 to 100 for (int count = 1; count <= 100; count++) { // add current even number to sum sum += evenNumber; // get the next even number evenNumber += 2; } System.out.println("Sum of even numbers is " + sum); } }```

Output of the above program is

Sum of even numbers is 10100

Method 2: Using while loop
It is also possible to find the sum of first n even numbers using a `while` loop. Replace the `for` loop in the above approach with a `while` loop.
Modified java program will be as follows.

```public class EvenNumberAdder { public static void main(String[] args) { int sum = 0, evenNumber = 2; int count = 1; // loop from 1 to 100 while (count <= 100) { // add current even number to sum sum += evenNumber; // get the next even number evenNumber += 2; // increment loop counter count++; } System.out.println("Sum of even numbers is " + sum); } }```

Output will be

Sum of even numbers is 10100

Method 3: Using formula
Even numbers starting from 1 can be represented as
2, 4, 6, 8, 10, …….
If you look carefully, this is an Arithmetic Progression(A.P.) and hence its sum can be calculated using the formula to find the sum of an A.P. as below

Sum of A.P. is (n/2) * [ 2 * a + (n – 1) * d ]

where, a is the first element of the series,
n is the total number of elements, and
d is the difference between the adjacent numbers.
In this case, a = 2 and d = 2.
Replacing these values in the above formula, it becomes

=> (n/2) * [ 2 * 2 + (n – 1) * 2 ] => (n/2) * [ 4 + 2n – 2 ] => (n/2) * [ 2 + 2n ] => (n/2) * 2[ 1 + n ] => n * (1 + n) or n * (n + 1)

Java program to calculate the sum of even numbers based on the above formula is given below.

```public class EvenNumberAdder { public static void main(String[] args) { // count of even numbers int n = 100; // apply formula int sum = n * (n + 1); System.out.println("Sum of even numbers is " + sum); } }```

Hit the clap button below if the article was useful.

5
Liked the article ? Spread the word...