Write a Java Program to Calculate the Sum of Natural Numbers

In Java, we can calculate the sum of natural numbers using a loop.

A natural number is a positive integer greater than or equal to 1.

The sum of the first n natural numbers can be calculated using the formula n(n+1)/2.

Here’s how you can write a Java program to calculate the sum of natural numbers:

import java.util.Scanner;

public class SumOfNaturalNumbers {
   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       System.out.print("Enter the value of n: ");
       int n = scanner.nextInt();
       int sum = 0;
       for(int i = 1; i <= n; i++) {
           sum += i;
       }
       System.out.println("The sum of first " + n + " natural numbers is " + sum);
   }
}

In the code above, we first import the Scanner class to take user input.

We then prompt the user to enter the value of n, which is the number of natural numbers we want to sum.

We then declare a variable called sum and initialize it to 0.

Next, we use a for loop to iterate from 1 to n. In each iteration, we add the current value of i to sum. Once the loop finishes, we print the result using System.out.println().

To test the program, you can compile and run it using a Java compiler.

When you run the program, it will prompt you to enter the value of n.

Once you enter the value, the program will calculate the sum of the first n natural numbers and display the result on the console.


In conclusion, calculating the sum of natural numbers in Java is a simple task that can be accomplished using a loop.

The program we’ve created above takes user input, performs the necessary calculations, and displays the result on the console.

By understanding the logic behind the program, you can easily modify it to suit your needs.