Java - Sum Numbers From 1 To N

Sum Numbers From 1 To N

Description

Sum Numbers From 1 To N

N is the value bigger than 1

If N is 3, the answer is 6, since 1 + 2 + 3 = 6

Test cases

You can use the following test cases to verify your code logics.

ID Input Ouput
13 6
210 55
320 210

Code template

Cut and paste the following code snippet to start solve this problem.

public class Main {
    public static void main(String[] args) {
      test(3);
      System.out.println();
      test(10);
      System.out.println();
      test(20);
    }
    public static void test(int max) {
       
      //your code here
    }
}

Answer

Here is the answer to the question above.

Demo

public class Main {
    public static void main(String[] args) {
      test(3);//ww w.  jav  a2s  .co m
      System.out.println();
      test(10);
      System.out.println();
      test(20);
    }
    public static void test(int max) {
       
      int sum = 0;
      for (int i = 1; i <= max; i++) {
          sum += i;
      }
      System.out.printf("Sum from 1 to %d is: ", max);
      System.out.println(sum);
    }
}

Related Quiz