In this tutorial, we will learn how to write a Java program to find the sum of the first N natural numbers. We will understand different approaches to calculate the sum of the first N natural numbers.
- Using for loop
- Using while loop
- Using mathematical formula
- Using recursion
For example, if the user enters a number 10, the program will calculate the sum of the first 10 natural numbers as follows:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
Therefore, the sum of the first 10 natural numbers is 55.
Before writing the Java programs, let’s first understand what natural numbers are and how to calculate their sum.
What Are Natural Numbers?
Natural numbers are positive counting numbers that start from 1 and continue indefinitely. For example:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
The sum of the first N natural numbers means adding all integers starting from 1 up to N.
For example:
- Sum of the first 3 natural numbers = 1 + 2 + 3 = 6
- Sum of the first 5 natural numbers = 1 + 2 + 3 + 4 + 5 = 15
- Sum of the first 10 natural numbers = 1 + 2 + 3 + … + 10 = 55
Mathematical Formula to Find the Sum of First N Natural Numbers
We can calculate the sum of the first N natural numbers using the following mathematical formula:
Sum = N × (N + 1) / 2
Where:
- N represents the total number of natural numbers.
- Sum represents the total of all natural numbers from 1 to N.
For example, if N = 10:
Sum = 10 × (10 + 1) / 2 Sum = 10 × 11 / 2 Sum = 110 / 2 Sum = 55
Therefore, the sum of the first 10 natural numbers is 55. We can use this formula in Java to calculate the sum of the first N natural numbers without executing a loop.
Java Program to Find Sum of First N Natural Numbers Using for Loop
The for loop is one of the simplest ways to calculate the sum of the first N natural numbers in Java.
In this approach, we initialize a variable named sum with 0 and use a for loop to iterate from 1 to N. During each iteration, the for loop adds the current number (i) to the variable sum. If N is 0 or less, the loop does not execute and the sum remains 0.
Let’s write a complete Java program to calculate the sum of the first N natural numbers using a for loop.
Java Program
import java.util.Scanner;
public class SumOfNaturalNumbers {
public static void main(String[] args) {
// Create a Scanner object to read input from the user.
Scanner scanner = new Scanner(System.in);
// Ask the user to enter a number.
System.out.print("Enter the value of N: ");
int n = scanner.nextInt();
// Initialize the variable sum to 0.
long sum = 0;
// Check whether the input is valid or not using if statement.
if (n >= 1) {
// Calculate the sum using for loop.
for (long i = 1; i <= n; i++) {
sum = sum + i;
}
// Display the result.
System.out.println("Sum of first " + n + " natural numbers is: " + sum);
} else {
System.out.println("Please enter a positive integer.");
}
// Close the Scanner.
scanner.close();
}
}Output:
Enter the value of N: 10 Sum of first 10 natural numbers is: 55
Explanation of the Java Program
Let’s understand how this Java program works step by step.
- Import the Scanner class: First, we import the Scanner class from the java.util package to accept input from the keyboard.
- Create a Scanner object: We create an object of the Scanner class to read the integer entered by the user.
- Read the value of N: We use the nextInt() method of the Scanner class to read the input and store it in the variable named n.
- Initialize the sum variable: We declare a variable named sum of type long and initialize it with 0. This variable stores the running total of natural numbers.
- Validate the input: We use an if statement to check whether the entered number is greater than or equal to 1.
- Initialize the loop variable: Inside the for loop, we initialize the variable i with 1 because natural numbers start from 1.
- Check the loop condition: The condition
i <= nensures that the loop executes until the value of i becomes greater than N. - Calculate the sum: The statement
sum = sum + iadds the current value of i to the previous sum. - Increment the variable: The increment operator (
i++) increases the value of i by 1 after each iteration. - Display the result: After the loop terminates, we print the calculated sum using the
System.out.println()method. - Close the Scanner: Finally, we close the Scanner object to release the associated resource.
As a result, the program calculates and displays the sum of all natural numbers from 1 to N.
Execution of the Java Program
Let’s understand the execution of the for loop by taking N = 5. The loop variable starts with i = 1 and continues until i <= 5.
| Iteration | Value of i | Calculation | Sum |
|---|---|---|---|
| 1 | 1 | 0 + 1 | 1 |
| 2 | 2 | 1 + 2 | 3 |
| 3 | 3 | 3 + 3 | 6 |
| 4 | 4 | 6 + 4 | 10 |
| 5 | 5 | 10 + 5 | 15 |
After the fifth iteration, the value of i becomes 6. Since the condition i <= 5 becomes false, the loop terminates. Therefore, the final sum is 15.
Java Program to Find Sum of Natural Numbers Using while Loop
In Java, we can also calculate the sum of the first N natural numbers using a while loop. In this approach, we initialize a variable i with 1 and a variable sum with 0 before the loop starts.
Inside the while loop, we add the current value of i to sum and increase the value of i by 1. If n is less than 1, the loop does not run and the program prompts for a positive integer. Let’s see the complete Java program.
Java Program
import java.util.Scanner;
public class SumUsingWhileLoop {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read input from the user.
System.out.print("Enter the value of N: ");
int n = scanner.nextInt();
// Initialize variables sum and i.
long sum = 0;
long i = 1;
// Check input validity.
if (n >= 1) {
// Calculate the sum of the first n natural numbers using while loop.
while (i <= n) {
sum = sum + i;
i++;
}
// Display the result.
System.out.println("Sum of first " + n + " natural numbers is: " + sum);
} else {
System.out.println("Please enter a positive integer.");
}
// Close Scanner
scanner.close();
}
}Output:
Enter the value of N: 15 Sum of first 15 natural numbers is: 120
Explanation of the Java Program
Let’s understand the important statements used in this program.
- Initialize the variables: We initialize
sum = 0to store the total andi = 1to start counting from the first natural number. - Check the while loop condition: The condition
i <= nensures that the loop executes until the current number is less than or equal to n. - Calculate the sum: Inside the loop, the statement
sum = sum + iadds the current number to the running total. - Increment the variable: The statement
i++increases the value of i by 1 after every iteration. - Terminate the loop: When i becomes greater than n, the condition becomes false, and the loop terminates.
- Display the result: Finally, the program prints the calculated sum.
Thus, we can calculate the sum of the first n natural numbers using a while loop.
Find Sum of First N Natural Numbers Using Mathematical Formula
You can also find the sum of the first N natural numbers directly using a mathematical formula. The general mathematical formula to calculate the sum of the natural numbers is:
Sum = N × (N + 1) / 2
This approach is more efficient than using a loop because it calculates the result directly without iterating through every natural number. Let’s write a complete Java program to find the sum of natural numbers.
Complete Java Program
import java.util.Scanner;
public class SumUsingFormula {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of N: ");
int n = scanner.nextInt();
// Check the entered number is positive or not.
if (n >= 1) {
// Calculate sum using mathematical formula.
long sum = (long) n * (n + 1L) / 2;
System.out.println("Sum of first " + n + " natural numbers is: " + sum);
} else {
System.out.println("Please enter a positive integer.");
}
scanner.close();
}
}Output:
Enter the value of N: 5 Sum of first 5 natural numbers is: 15
In this example, we have applied the mathematical formula
N × (N + 1) / 2
to calculate the sum. We stored the calculated result in a variable of type long. Finally, we displayed the sum using the System.out.println() method.
Why do we use long instead of int?
The sum of natural numbers can become larger than the maximum value supported by the int data type. Therefore, we use long to store the result and cast n to long before multiplication to avoid integer overflow during the calculation.
The expression (long) n * (n + 1L) / 2 ensures that the multiplication is performed using the long data type.
Java Program to Find Sum of Natural Numbers Using Recursion
Recursion is another way to calculate the sum of the first n natural numbers in Java. A recursive method is a method that calls itself repeatedly until a specified base condition is satisfied. In this method, we define a method named calculateSum() that accepts an integer n as an argument and returns the sum from 1 to n.
The recursive logic is as follows:
- Base case: If n is 0, return 0. This is the base condition.
- Recursive step: Otherwise, return n plus the sum of the previous natural numbers (i.e.,
n + calculateSum(n - 1)).
The recursive expression is:
sum(n) = n + sum(n - 1)
Let’s write the complete Java program.
Java Program
import java.util.Scanner;
public class SumUsingRecursion {
// Recursive method to calculate the sum of integers from 1 to n.
static long calculateSum(int n) {
// Base condition: stop recursion and return 0 when n reaches 0.
if (n == 0) {
return 0;
}
// Recursive step: add current n to the sum of numbers from 1 to (n - 1).
return n + calculateSum(n - 1);
}
public static void main(String[] args) {
// Create a Scanner object to read input from standard input.
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the value of N.
System.out.print("Enter the value of N: ");
int n = scanner.nextInt();
// Ensure N is a positive integer before invoking recursion.
if (n >= 1) {
// Compute the sum and store it in a long to prevent overflow.
long sum = calculateSum(n);
// Print the final calculated sum.
System.out.println("Sum of first " + n + " natural numbers is: " + sum);
} else {
// Inform the user when N is zero or negative.
System.out.println("Please enter a positive integer.");
}
// Close the Scanner to release the input stream resource.
scanner.close();
}
}Output:
Enter the value of N: 12 Sum of first 12 natural numbers is: 78
Explanation of the Java Program
Let’s understand how recursion calculates the sum of the first n natural numbers when n = 5. The recursive method calls itself with decreasing values of n.
calculateSum(5) = 5 + calculateSum(4) = 5 + 4 + calculateSum(3) = 5 + 4 + 3 + calculateSum(2) = 5 + 4 + 3 + 2 + calculateSum(1) = 5 + 4 + 3 + 2 + 1 + calculateSum(0)
When n becomes 0, the base condition is satisfied, and the method returns 0.
Now, the recursive calls return their values:
calculateSum(1) = 1 + 0 = 1 calculateSum(2) = 2 + 1 = 3 calculateSum(3) = 3 + 3 = 6 calculateSum(4) = 4 + 6 = 10 calculateSum(5) = 5 + 10 = 15
Therefore, the final sum is 15.
Note: Recursion uses additional stack memory for method calls. For very large values of N, it may cause a StackOverflowError. Therefore, an iterative approach or mathematical formula is generally preferable for large inputs.
Time Complexity and Space Complexity
Here, we looked at different approaches to calculate the sum of natural numbers in Java, which have different time and space complexities.
| Approach | Time Complexity | Auxiliary Space |
|---|---|---|
| For loop | O(N) | O(1) |
| While loop | O(N) | O(1) |
| Mathematical formula | O(1) | O(1) |
| Recursion | O(N) | O(N) |
Explanation:
- For loop: The loop executes N times, so its time complexity is O(N).
- While loop: The loop also executes N times, resulting in O(N) time complexity.
- Mathematical formula: It performs a fixed number of arithmetic operations, so its time complexity is O(1).
- Recursion: The recursive method makes N method calls, resulting in O(N) time and O(N) auxiliary stack space.
Therefore, the mathematical formula is the most efficient approach when you only need to calculate the sum of the natural numbers in Java.
Coding Challenge: Find the Sum of Natural Numbers Using do-while Loop in Java
Your Task:
Write a Java program to calculate the sum of the first N natural numbers using a do-while loop.
Follow these instructions:
- Ask the user to enter a positive integer N.
- Initialize a variable i with 1.
- Initialize a variable sum with 0.
- Use a do-while loop to add all natural numbers from 1 to N.
- Increment the value of i by 1 after each iteration.
- Display the final sum.
- Handle zero and negative input appropriately.






