Java – Find Sum of First N Natural Numbers

The first n natural numbers are 1, 2, 3, ..., n. Their sum can be written as 1 + 2 + 3 + ... + n. In Java, you can calculate this sum with a loop, the formula n * (n + 1) / 2, or recursion.

sum = 1 + 2 + 3 + . . + n

For example, when n = 5, the sum is 1 + 2 + 3 + 4 + 5 = 15. When n = 10, the result is 55.

This tutorial starts with loop-based solutions because they show how the running total is built. It then uses the direct formula and recursion. The examples assume that n is a positive integer.

Steps to Find the Sum of First N Natural Numbers in Java

Following algorithm can be used to find the sum of first N natural numbers using Java looping statements.

  1. Start.
  2. Read n.
  3. Initialize sum with 0.
  4. Initialize i with 0.
  5. Check if i is less than or equal to n. If false go to step 8.
  6. Add i to sum.
  7. Increment i. Go to step 5.
  8. Print the sum.
  9. Stop.

Starting i at 0 is harmless because adding zero does not change the sum. The Java loop examples below start at 1, which directly matches the first natural number being added.

Find Sum of First N Natural Numbers using While Loop

In the following Java program, we use Java While Loop to implement the algorithm to find sum of first N natural numbers.

Example.java

</>
Copy
/**
 * Java Program - Sum of First N Natural Numbers
 */

public class Example {

	public static void main(String[] args) {
		int n = 10;
		int sum=0;
		
		int i=1;
		while (i<=n) {
			sum += i;
			i++;
		}
			
		System.out.println(sum);
	}
	
}

Output

55

The loop begins with i = 1. On every iteration, the current value of i is added to sum, and then i is incremented. For n = 10, the loop adds all integers from 1 through 10.

Find Sum of First N Natural Numbers using For Loop

In the following Java program, we use Java For Loop to implement the algorithm to find sum of first N natural numbers.

Example.java

</>
Copy
/**
 * Java Program - Sum of First N Natural Numbers
 */

public class Example {

	public static void main(String[] args) {
		int n = 10;
		int sum=0;
		
		for(int i=1; i<=n; i++)
			sum += i;
			
		System.out.println(sum);
	}
	
}

Output

55

A for loop is compact because initialization, the loop condition, and increment are written together. The loop performs the same additions as the while loop.

Find Sum of First N Natural Numbers using Formula

Formula to find the sum of first n Natural Numbers is n*(n+1)/2. In the following Java program, we shall use this formula.

Example.java

</>
Copy
/**
 * Java Program - Sum of First N Natural Numbers
 */

public class Example {

	public static void main(String[] args) {
		int n = 10;
		int sum = (n * (n + 1)) / 2;
			
		System.out.println(sum);
	}
	
}

Output

55

Why the n(n + 1) / 2 Formula Works

Write the sequence once in ascending order and once in descending order. Each pair adds to n + 1, and there are n such pairs across the two sequences. Therefore, twice the required sum is n * (n + 1), so the sum is n * (n + 1) / 2.

</>
Copy
S = 1 + 2 + 3 + ... + n
S = n + (n-1) + (n-2) + ... + 1
2S = n(n + 1)
S = n(n + 1) / 2

The formula performs a fixed number of arithmetic operations, so it is preferable when you only need the final sum and do not need to visit every number.

Find Sum of First N Natural Numbers using Recursion

We can also use recursion function to find the sum of first N natural numbers.

Example.java

</>
Copy
/**
 * Java Program - Sum of First N Natural Numbers
 */

public class Example {

	public static void main(String[] args) {
		int n = 10;
		int sum = sumOfN(n);
		System.out.println(sum);
	}
	
	static int sumOfN(int n) {
		if (n == 1)
			return 1;
		else
			return n + sumOfN(n-1);
	}
}

Output

55

The recursive relation is sum(n) = n + sum(n - 1). The existing example uses n == 1 as its base case, so it is intended for positive values of n. For n = 0 or a negative value, use input validation or a base case that explicitly handles zero.

Java Program to Read N and Calculate the Sum

When n should come from the user instead of being fixed in the program, read it with Scanner. The following example accepts only a non-negative value and uses long for the calculation.

</>
Copy
import java.util.Scanner;

public class Example {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter n: ");
        long n = scanner.nextLong();

        if (n < 0) {
            System.out.println("n must be non-negative.");
        } else {
            long sum = n * (n + 1) / 2;
            System.out.println("Sum = " + sum);
        }

        scanner.close();
    }
}

Sample output

Enter n: 10
Sum = 55

Using long to Reduce Overflow Risk in the Sum Formula

The original examples use int, which is sufficient for small values such as 10. For larger values, the intermediate product n * (n + 1) can overflow an int even when the intended mathematical formula is correct. Using long increases the available range.

</>
Copy
long n = 100000;
long sum = n * (n + 1) / 2;

System.out.println(sum);

Output

5000050000

If n itself is stored as an int, cast before multiplying so the multiplication is performed as long: (long) n * (n + 1) / 2.

Time and Space Complexity of the Java Sum Methods

MethodTime complexityExtra spaceWhen it fits
While loopO(n)O(1)Useful when learning or processing each number
For loopO(n)O(1)Compact iterative solution
FormulaO(1)O(1)Best when only the final sum is required
RecursionO(n)O(n)Useful for demonstrating recursive thinking

Recursion uses additional call-stack space for each recursive call. For large n, the direct formula avoids both repeated additions and recursive call depth.

Check the Sum for Common Values of N

nCalculationSum
111
51 + 2 + 3 + 4 + 515
101 + 2 + … + 1055
100100 × 101 / 25050

These values are useful for checking a program quickly. If the program prints 15 for n = 5 and 55 for n = 10, the basic accumulation logic is behaving as expected.

Choosing a Java Method for the Sum of First N Natural Numbers

Use a loop when the purpose is to practice iteration or when you need to perform work for every number from 1 to n. Use n * (n + 1) / 2 when you need only the sum. Recursion expresses the mathematical relationship clearly, but it uses more memory because each call remains on the call stack until the base case is reached.

Summary of Java Solutions for the First N Natural Numbers

In this Java Tutorial, we learned how to compute the sum of first n natural numbers with the help of different techniques in Java.

The loop-based methods add the numbers one by one, the formula calculates the result directly, and recursion repeatedly reduces the problem from n to n - 1. For general-purpose code that only needs the total, the formula with an appropriate numeric type is the most direct approach.