Print sum of all even numbers between 1 to n using Java while loop

Print sum of all even numbers between 1 to n using while loop

Any number divisible by 2 is an even number. Here we are using a while loop to iterate the given numbers range. And calculating the sum of all even numbers and printing them.

Steps :

  1. Here we are using a “scanner” to take input for value n from users.
  2. In the below program, we are starting iteration with 1 and checking its divisibility by 2 to check number is even or not.
  3. If the condition satisfied means the number is even, we are adding only that number to a variable “sum” to find the calculation of all even numbers.
  4. For eg . 4%2 = 0, conditions satisfied. Now 4 is qualified to be added to the sum variable. (sum = sum +4).

Java Program to find sum of all even numbers between 1 to n

import java.util.*;
public class Main
{
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		int start = 1;
		System.out.println("Ender Number till you want Even number sum : ");
		int end = sc.nextInt();
		int sum = 0;
		while(start<=end) {
			if(start%2 == 0) {
			    sum = sum + start;
			}
			start++;
		}
		System.out.println("Sum of all Even numbers is : " +sum+ ".");
		sc.close();
	}
}

Output

Ender Number till you want Even number sum : 
20
Sum of all Even numbers is : 110.