Summary: In this programming example, we will learn different ways to calculate the sum of first n even numbers in Java.

Sum of even numbers

Method 1: Using For Loop

import java.util.Scanner;
 
public class Main
{
	public static void main(String[] args) {
	    Scanner in= new Scanner(System.in);
	    
		System.out.print("Enter the value of 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:

Enter the value of n: 3
Sum: 12

In the above program, we have used the count as the loop variable.

The count variable stores the count of the even numbers that have been added to the sum.

The num variable is the natural number which we test and increment in each iteration.

When the value of the count equals n, it means we have successfully added first n even numbers.

Method 2: Using while Loop

import java.util.Scanner;
 
public class Main
{
	public static void main(String[] args) {
	    Scanner in= new Scanner(System.in);
	    
		System.out.print("Enter the value of 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:

Enter the value of n: 10
Sum: 110

The logic used in this method is the same as the above program, only we have replaced for loop with a while loop.

The while loop runs until count != n.

Method 3: Using Formula

We can easily compute the sum of first n even numbers using the formula n*(n+1).

Let’s use it in our program to output the sum of the first 100 even numbers.

import java.util.Scanner;
 
public class Main
{
	public static void main(String[] args) {
	    Scanner in= new Scanner(System.in);
	    
		System.out.print("Enter the value of n: ");
		int n = in.nextInt();
		
		int sum= n*(n+1);
		
		System.out.println("Sum: "+sum);
	}
}

Output:

Enter the value of n: 100
Sum: 10100

Note: The above programs compute the sum of first n even numbers. They don’t calculate the sum of even numbers from 1 to n.

Leave a Reply

sixteen + seven =