programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Tim Cooke
• Ron McLeod
• Jeanne Boyarsky
• Paul Clapham
Sheriffs:
• Liutauras Vilda
• Henry Wong
• Devaka Cooray
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Tim Holloway
• Al Hobbs
• Carey Brown
Bartenders:
• Piet Souris
• Mikalai Zaikin
• Himai Minh

# Decrement of numbers using while loop

Greenhorn
Posts: 5
• Number of slices to send:
Optional 'thank-you' note:
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

Saloon Keeper
Posts: 14093
319
• Number of slices to send:
Optional 'thank-you' note:
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.

Marshal
Posts: 76085
362
• Number of slices to send:
Optional 'thank-you' note:

Stephan van Hulst wrote:. . . use the increment operator to get the sum 1+2+3+4+5+6.

I think that loop will run 7× and you will actually get the sum 0+1+2+3+4+5+6. It will give the same result, 21.

 Don't get me started about those stupid light bulbs.