Reputation: 43
The exercise reads as : Exercise 32: The sum of a set of numbers
Create a program that calculates the sum 1+2+3+…+n where n is a number entered by the user.
Here's a part of working code:
int first = 1;
int sum = 0;
while (first <= read) {
sum = sum + first;
first++;
}
Changing above to below:
int first = 1;
int sum = 0;
while (first <= read) {
first++;
sum = sum + first;
}
Produces wrong answers.If read=3 then sum=9 instead of 6, if read=7 then sum=35 instead of 28 and so on.Why is that?
Upvotes: 1
Views: 109
Reputation: 9057
use a debugger to step through the code. This will give you insight into how to debug your code, teach you about how to use debugging tools, and it will easily help you spot the error.
You can avoid the (computationally) expensive loop. The direct formula for the sum of the first N numbers is (N * (N + 1)) / 2
Upvotes: 1
Reputation: 394116
In the second snippet you increment first
before adding it to sum
, which means you are calculating the sum
2 + 3 + ... + read + (read+1)
instead of
1 + 2 + ....... + read.
Upvotes: 4