Sum Numbers From 1 To N
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
You can use the following test cases to verify your code logics.
ID | Input | Ouput |
---|---|---|
1 | 3 | 6 |
2 | 10 | 55 |
3 | 20 | 210 |
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 } }
Here is the answer to the question above.
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); } }