Hello, as a beginner I am struggling to understand the algorithm of sum of a series. In my perception, the way I see the solution is negative infinity. Let me tell you my understanding about this problem.
first, n<=6. Here n = 0. second, while n is less than or equal to 6, which is true, then sum += n--, that means sum = sum + n, which is (0+0), and n-- = 0 - 1.
I can't break it down anymore. Need your explanation. Here the sum = -1073741824
Well, after n has decremented, the loop condition is checked again, it sees that n is still less than 6 (and will be for a loooong time, since we're decrementng n and not incrementing it), so the loop is run again, but this time with n = -1.
This continues running for n = -1, n = -2, n = -3, etc. All the time, the sum will become more and more negative, because you're adding negative numbers with an increasing magnitude to it.
Java's primitive integral types have this property that they "underflow". This means that when they reach their minimal possible value and you decrement them, the value wraps around to the maximum possible value.
So after the value -2,147,483,648 (the minimum for int) n wraps around to 2,147,483,647 (the maximum for int), the loop condition sees that this value is greater than 6 and the loop terminates.
So really, you're just summing all negative values from -1 to -2,147,483,648. However, integer underflow strikes again: The sum of these values is so negative, that the sum variable underflows multiple times and ends up with a very random looking value.
Seeing as there is so much underflow occurring, and seeing as it doesn't matter which positive value you use in the loop condition, leads me to believe that the application was never meant to use the decrement operator. Instead, you will probably want to use the increment operator to get the sum 1+2+3+4+5+6.