Write a program to find sum of all even numbers between 1 to n


This program asks the user to enter the limit and then calculates the sum of all even numbers from 1 up to the entered limit. Here's how the program works:

  • The user is prompted to enter the limit, which is stored in the variable l.
  • The variable sum is initialized to 0.
  • The program uses a for loop to iterate through all numbers from 1 up to the limit l.
  • Within the loop, the program checks whether the current number s is even by using the modulo operator %. If s is even, the program adds s to the variable sum.
  • After the loop is finished, the program prints out the value of sum, which is the sum of all even numbers from 1 up to the limit l.

Source Code

import java.util.Scanner;
class Sum_Even_Number
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter The Number of Limit : ");
		int l =input.nextInt();
		int sum = 0;
		for(int s=1;s<=l;s++)
		{
			if(s%2==0)
				sum = sum + s;
 
		}
		System.out.println("Sum of Even Numbers :"+sum);
	}
}

Output

Enter The Number of Limit : 30
Sum of Even Numbers :240

Example Programs