programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# How do I get the sum of a single int in Java?

Jeff Sak
Ranch Hand
Posts: 38
For example, if the user input 5, i want to find 1+2+3+4+5=15. I have already input my main class and have it set up for n to be input by the user, but it doesn't seem like my loop is working. What other ways are there to get the correct result?

Carey Brown
Saloon Keeper
Posts: 3328
46
n += n + j ;
you either want
n += j;
or
n = n + j;

Jeff Sak
Ranch Hand
Posts: 38
I've tried both of those for the result but end up with "The sum of all the numbers in 3 is equal to -2147450877" I don't understand how it came up with such a low number, especially because I'm using addition for my loop and only using a single int(such as 3 or 7).

Carey Brown
Saloon Keeper
Posts: 3328
46
Jeff Sakaida wrote:I've tried both of those for the result but end up with "The sum of all the numbers in 3 is equal to -2147450877" I don't understand how it came up with such a low number, especially because I'm using addition for my loop and only using a single int(such as 3 or 7).

Ah. You have to initialize n to zero before entering loop.

Jeff Sak
Ranch Hand
Posts: 38
Can you please explain why that is Carey? In my head, if I initialize n to 0 before the loop starts, then won't the result be zero? I have it so the loop only goes till J <= N. I just want to understand why it works that way since I'm still learning.

Carey Brown
Saloon Keeper
Posts: 3328
46
Jeff Sakaida wrote:Can you please explain why that is Carey? In my head, if I initialize n to 0 before the loop starts, then won't the result be zero? I have it so the loop only goes till J <= N. I just want to understand why it works that way since I'm still learning.

Sorry, I've been too quick to fire back a response before thinking it through.

Jeff Sak
Ranch Hand
Posts: 38
Thank you Carey, that makes a lot more sense to me and also seemed to do the trick.

Greenhorn
Posts: 28
• 1
Formula for sum of n numbers is n(n+1)/2.
You can use it and get the sum for 5.

Campbell Ritchie
Marshal
Posts: 56570
172
• 1
That formula only works when the numbers are in sequence starting 1 … 1 2 3 etc.
The reason for such questions when beginning programming is to train people how to use loops, so they would not use the efficient formula. I think the strange negative result may be caused by an arithmetic overflow.