Answers for "java sum 1 to n"

1

java sum 1 to n

public class Main {
  public static void main(String[] args) {
    var scanner = new java.util.Scanner(System.in);
    System.out.print("What is n? ");
    int n = scanner.nextInt();
    int sum = 0;
    for (int i = 1; i <= n; ++i) {
      sum += i;
    }
    System.out.println("The sum of 1..n is " + sum);
  }
}
Posted by: Guest on January-25-2021

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language