Sum of N Natural Numbers
Calculate the sum of first N natural numbers using formula.
BeginnerTopic: Module 1: Basic Java Programs
Java Sum of N Natural Numbers Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter N: ");
int n = sc.nextInt();
int sum = n * (n + 1) / 2;
System.out.println("Sum of first " + n + " natural numbers = " + sum);
sc.close();
}
}Output
Enter N: 10 Sum of first 10 natural numbers = 55
Understanding Sum of N Natural Numbers
We use the mathematical formula for the sum of first N natural numbers: n(n + 1) / 2.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.