Loop why result is 36 explain please

explain someone why result of program is value 36? In java I'm just beginner.

public static void main(String[] args) {

    int sum = 0;
    for (int i = 1; i < 9 ; i++) {

        sum+=i;
    }
    System.out.println(sum);


}

2 answers

  • answered 2018-01-14 13:28 rwp

    The loop is computing the sum of an arithmetic series, with values from 1 to 8 inclusive. Using the standard formula, this is the number of terms (8) times the average of the first and last values (1+8)/2, which works out as 36.

  • answered 2018-01-14 13:42 R.F. Nelson

    Let's look at one iteration at a time:

    First, we start with sum = 0.

    The first iteration we have i = 1. The value of sum, which is zero, becomes 1 when we do sum += 1.

    The second iteration we have i = 2. The value of sum, which is one, becomes 3 when we do sum += 2.

    The third iteration we have i = 3. The value of sum, which is three, becomes 6 when we do sum += 3.

    The fourth iteration we have i = 4. The value of sum, which is six, becomes 10 when we do sum += 4.

    The fifth iteration we have i = 5. The value of sum, which is ten, becomes 15 when we do sum += 5.

    The sixth iteration we have i = 6. The value of sum, which is fifteen, becomes 21 when we do sum += 6.

    The seventh iteration we have i = 7. The value of sum, which is twenty-one, becomes 28 when we do sum += 7.

    The eighth iteration we have i = 8. The value of sum, which is twenty-eight, becomes 36 when we do sum += 8.

    We have now completed the for loop since the next value for i would be 9 and we specified the loop would only continue so long as i < 9. At this point, the value of sum is 36.