java sum 1 to n

Solutions on MaxInterview for java sum 1 to n by the best coders in the world

showing results for - "java sum 1 to n"
Hanna
03 Jan 2021
1public class Main {
2  public static void main(String[] args) {
3    var scanner = new java.util.Scanner(System.in);
4    System.out.print("What is n? ");
5    int n = scanner.nextInt();
6    int sum = 0;
7    for (int i = 1; i <= n; ++i) {
8      sum += i;
9    }
10    System.out.println("The sum of 1..n is " + sum);
11  }
12}