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

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.

Let's look at one iteration at a time:
First, we start with
sum = 0
.The first iteration we have
i = 1
. The value ofsum
, which is zero, becomes 1 when we dosum += 1
.The second iteration we have
i = 2
. The value ofsum
, which is one, becomes 3 when we dosum += 2
.The third iteration we have
i = 3
. The value ofsum
, which is three, becomes 6 when we dosum += 3
.The fourth iteration we have
i = 4
. The value ofsum
, which is six, becomes 10 when we dosum += 4
.The fifth iteration we have
i = 5
. The value ofsum
, which is ten, becomes 15 when we dosum += 5
.The sixth iteration we have
i = 6
. The value ofsum
, which is fifteen, becomes 21 when we dosum += 6
.The seventh iteration we have
i = 7
. The value ofsum
, which is twentyone, becomes 28 when we dosum += 7
.The eighth iteration we have
i = 8
. The value ofsum
, which is twentyeight, becomes 36 when we dosum += 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 asi < 9
. At this point, the value ofsum
is 36.