Java Arithmetic Operator sum a list of numbers

Question

We would like to write a program that displays the result of

1 +  2  +  3  +  4  +  5  +  6  +  7  + 8  +  9


public class Main {
  public static void main(String[] args) {
    System.out.println(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9);
  }
}

Note

We can also use a for loop:

public class Main {
  public static void main(String[] args) {
    int result = 0;
    for (int i = 1; i <= 9; i++) {
      result += i;//w  w w. jav a 2 s .co m
    }
    System.out.println(result);
  }
}



PreviousNext

Related