What makes you think the final result should be 91? Note that, at Line 9, the loop will continue each time sum is less than max. Well, if sum were 91, it would be less than 100, wouldn't it? That means the loop will continue for another pass. Line 10 will print the value of i (13, I believe), then i will increase by 1 (to 14, I believe), then, at Line 8, i will again be added to sum. At which point, what value will sum have? And, having that value, what will happen when Line 9 next executes?
Jesper de Jong wrote:Hrvoje, can you explain what the code is supposed to do? It's hard to point out the error if we don't know what exactly the code should calculate.
Sorry, my question wasn't clear.
Write a program that prints the numbers from 1 to N with the condition that their sum is less than a constant value SUM_MAX.
So the answer should looks like this:
Enter N: 20
Enter sum: 100
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
Sum of numbers from 1 do 13 is 91 ( < 100 ).
My problem is that I don't wont that final pass.
When the "sum = sum + i" is before if statement I got 1, ... 13 and that is OK (when I put it after if statement --> 1, ... 14 which is not OK).
But, the loop passes once more and at the end I've got 105 which is wrong, because the condition (sum < sum_max) is not OK. I can't put the result "sum" into the loop, I need it at the end.
Thanks to all.
salvin francis wrote:Can you explain the condition sum < max in your code ? I think you mean (sum + i > max) instead
Thank you so much. I can't explain the condition (sum < max), it was wrong. I've missed "+ i", it should be (sum + i > max) and it works.
Final code is:
Hrvoje Jug wrote:Final code is:...
Well done! But you still have a small mistake, and you can also save yourself quite a bit of typing:
I don't know if you've seen the conditional operator ('? :') yet; but it's worth getting to know.
Also: What happens if your user enters '0' or '1' (or indeed '-53') for either N or SUM_MAX?
Hrvoje Jug wrote:You've shown me, but I forgot to change.
But the most important thing is to understand why it's wrong.
My suggestion: leave the code as it is and try out the values I suggested; then maybe add a couple of extra debug print() statements to find out why it prints the wrong values. That'll help you to avoid similar mistakes in the future.