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


This is a Java program to find the sum of numbers up to a given limit. The program first takes input from the user for the limit, i.e., the number up to which the sum has to be calculated. It then initializes a variable called sum to zero.

The program then uses a for loop to iterate from 1 up to the limit number. In each iteration, the current value of s is added to the sum variable using the expression sum = sum + s.

Finally, the program prints the value of the sum variable, which represents the sum of all the numbers from 1 up to the limit number entered by the user.

Source Code

import java.util.Scanner;
class Sum_Numbers
{
	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++)
		{
			sum = sum + s;
 
		}
		System.out.println("Sum of Numbers :"+sum);
	}
}

Output

Enter The Number of Limit : 20
Sum of Numbers :210

Example Programs