java

How to find the sum of even numbers in Java

In this tutorial, we are going to see how to write a Java program to calculate the sum of the even numbers from 1 to N using the For loop and the While loop. Any number divisible by 2 is an even number.
 

Calculate the sum of even numbers using the For loop

The following Java code allows the user to enter a limit value. Then, this Java program finds the sum of the even numbers from 1 to the cutoff value using the If statement and the For loop.

import java.util.Scanner;

public class Main {
	public static void main(String[] args) 
	{
		int n, i, p = 0;
		Scanner sc = new Scanner(System.in);
		
		System.out.print("Enter a number:");
		n = sc.nextInt();	
		
		for(i = 1; i <= n; i++)
		{
			if(i % 2 == 0)
			{
				p = p + i; 
			}
		}
		System.out.println("The sum of even numbers from 1 to "+n+"  =  "+p);
	}
}

Output:

Enter a number: 100                                                                                                       
The sum of even numbers from 1 to 100 = 2550

 

 

Calculate the Sum of Even Numbers Using the While Loop

The following Java code allows the user to enter a limit value. Then, this Java program finds the sum of the even numbers from 1 to the cutoff value using the If statement and the While Loop.

import java.util.Scanner;

public class Main {
	public static void main(String[] args) 
	{
		int n, i = 2, p = 0;
		Scanner sc = new Scanner(System.in);
		
		System.out.print("Enter a number: ");
		n = sc.nextInt();	
		
		while(i <= n)
		{
			p = p + i; 
			i = i + 2;
		}
		System.out.println("The sum of even numbers from 1 to "+n+"  =  "+p);
	}
}

Output:

Enter a number: 100                                                                                                       
The sum of even numbers from 1 to 100 = 2550
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *