00:00

Java Program to Find the Sum of n Natural Numbers

Last updated:

Natural numbers are the counting numbers 1, 2, 3, 4, 5 and so on. They do not include 0 or negative numbers. The sum of the first n natural numbers is 1 + 2 + 3 + ... + n; for example, the sum of the first 10 is 55.

You can compute it with a loop that adds each number, or directly with the formula:

sum = n × (n + 1) / 2

1. Sum of n Natural Numbers Using the Formula

The formula gives the answer in one step, however large n is. Using long keeps the result correct for large values of n.

SumNaturalFormula.java
public class SumNaturalFormula {
    public static void main(String[] args) {
        long n = 10;
        long sum = n * (n + 1) / 2;

        System.out.println("Sum of the first " + n + " natural numbers is " + sum);

        n = 100_000;
        System.out.println("Sum of the first " + n + " natural numbers is " + n * (n + 1) / 2);
    }
}
Output
Sum of the first 10 natural numbers is 55
Sum of the first 100000 natural numbers is 5000050000

2. Sum of n Natural Numbers Using a for Loop

The loop adds each number from 1 to n to a running total.

SumNaturalLoop.java
public class SumNaturalLoop {
    public static void main(String[] args) {
        int n = 50;
        int sum = 0;

        for (int i = 1; i <= n; i++) {
            sum += i;
        }

        System.out.println("Sum of 1 to " + n + " = " + sum);
    }
}
Output
Sum of 1 to 50 = 1275

3. Sum of Numbers in a Range Using a while Loop

This version asks the user for a start and an end value and adds every number in between, including both ends.

SumRange.java
import java.util.Scanner;

public class SumRange {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Start from: ");
        int start = scanner.nextInt();
        System.out.print("End at: ");
        int end = scanner.nextInt();
        scanner.close();

        int sum = 0;
        int i = start;
        while (i <= end) {
            sum += i;
            i++;
        }

        System.out.println("Sum of numbers from " + start + " to " + end + " = " + sum);
    }
}
Output (with sample input)
Start from: 5
End at: 15
Sum of numbers from 5 to 15 = 110

4. Summary

  • Natural numbers start from 1; 0 and negative numbers are not included.
  • The formula n * (n + 1) / 2 gives the sum instantly.
  • A for or while loop adds the numbers one by one and also works for any range.
  • Use long when n is large, because the sum grows quickly.

Related Programs