Write a program in Java to calculate the sum of first n even numbers.
Sum of First n Even Numbers using For Loop
To find the sum of first n even numbers we will check each natural number starting from 1 whether they are even or not. If yes then we add that number to the sum
and increment the value of count
, else we check for the next number.
We will use count
as the loop variable because if count
value reaches n
then it mean we have successfully added n even numbers.
See the java source code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in= new Scanner(System.in); System.out.println("Enter n"); int n = in.nextInt(); int sum=0, num = 1; for(int count=1; count<=n; ){ //if num is even then increment 'count' if(num%2 == 0){ sum += num; count++; } num++; } System.out.println("Sum: "+sum); } } |
output
1 2 3 | Enter n 3 Sum: 12 |
Sum of First n Even Numbers using while Loop
The logic of the program is the same as the above program only we have replaced for loop with while loop. While loop should run until count is less than n.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in= new Scanner(System.in); System.out.println("Enter n"); int n = in.nextInt(); int sum=0, num = 1, count=0; while(count<n){ //if num is even then increment 'count' if(num%2 == 0){ sum += num; count++; } num++; } System.out.println("Sum: "+sum); } } |
output
1 2 3 | Enter n 10 Sum: 110 |
Sum of Even Numbers using Formula
Formula n*(n+1) gives the sum of first n even numbers. Let’s use it in our java program to output the sum of the first 100 even numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in= new Scanner(System.in); System.out.println("Enter n"); int n = in.nextInt(); int sum= n*(n+1); System.out.println("Sum: "+sum); } } |
output
1 2 3 | Enter n 100 Sum: 10100 |
Note: The above programs computes the sum of first n even numbers. They don’t calculate the sum of even numbers from 1 to n.
Comment below if you have any doubts or suggestions.