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.
This method is based on the following algorithm steps.
- Write a
for
loop to iterate from 1 to n or in this case from 1 to 100. - Declare a variable to hold the sum of even numbers and initialize it to 0.
- Initialize a variable to hold the current even number and initialize it to 2 since 2 is the first even number.
- 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
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
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.
1 comment on “How to find the sum of first n even numbers using java program”
Leave a Reply
You must be logged in to post a comment.
HI ! WHEN USING THE FORMULA N*(N+1) FOR N TOO LARGE MEANS 200000 IT FAILED, IT GIVES I NCORRECT ANSWER 1410165408