The answer is probably correct I am trying to under why it comes to that result. The first part of the for loop adds 1 to 0 and so on until it reaches 10. Then it moves on to the next part wich is "total+=i" and I think that is the part I have not yet figured out since this is an example were the point is to understand why it returns the value 45.
Norm Radder wrote:
Why does this program return the answer 45
What value do you expect to be printed?
Have you desk checked the code to see what the correct output should be?
When just starting out, one of your BEST friends is "System.out.println".
When something isn't working like you'd expect, throw some of those bad boys in. If "total" isn't what you think it should be, print out its value every time it changes. Using it is a great way to see what's happening beneath the cover, so to speak.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
When you have worked out how your loop works, delete that class, or at least rename it and delete the Math.class file. You will have no end of confusion in a few weeks because you have written a class with the same name as another in the java.lang package.
Remove the import because you aren't using it.
Since OP seems to have gone away, and somebody else might come across this thread, I shall let the cat out of the bag. Because the loop includes i < 10 (line 8), it will run until i equals 9 and then stop. The sum of natural numbers 0...9inc is 45.