Sum of N Natural Numbers in Java
Calculate the sum of first N natural numbers using formula.
BeginnerModule 1: Basic Java ProgramsExample 15 of 20
sum-of-n-natural-numbers.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);67 System.out.print("Enter N: ");8 int n = sc.nextInt();910 int sum = n * (n + 1) / 2;11 System.out.println("Sum of first " + n + " natural numbers = " + sum);1213 sc.close();14 }15}
Output
Enter N: 10 Sum of first 10 natural numbers = 55
What's going on
We use the mathematical formula for the sum of first N natural numbers: n(n + 1) / 2.