Sum of N Natural Numbers

Calculate the sum of first N natural numbers using formula.

JavaBeginner
Java
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

We use the mathematical formula for the sum of first N natural numbers: n(n + 1) / 2.