Reputation: 15
Hi sorry this one may be a stupid question but I'm just moving my first steps in C and I couldn't find any specific answer, so:
Let's say I have to sum up some integers, why the expression sum += sum
, in this code returns just only the last number I enter time 2 (lastNumber*2)?
unsigned int count = 0, sum = 0;
printf("How many numbers do you want to sum: ");
scanf("%u", &count);
for (int i = 1; i <= count; ++i) {
printf("enter the integer: ");
scanf("%u", &sum);
sum += sum;
}
printf("the sum of all the %u numbers is: %u\n", count, sum);
PS: This problem is solved if I replace the expression with sum += x
;
But I can't understand why.
Upvotes: 0
Views: 71
Reputation: 969
Because sum += sum;
equivalent to sum = sum + sum;
and (sum + sum) equivalent to (2 * sum).
Upvotes: 0
Reputation: 50775
You probably want this:
unsigned int count = 0, sum = 0;
printf("How many numbers do you want to sum: ");
scanf("%u", &count);
for (int i = 1; i <= count; ++i) {
printf("enter the integer: ");
unsigned int value;
scanf("%u", &value);
sum += value; // or sum = sum + value;
}
printf("the sum of all the %u numbers is: %u\n", count, sum);
Upvotes: 0
Reputation: 23
When you doing scanf(..., &sum) you actually override its value. So, each iterate you doing nothing. Generally, it is good practice to dedicate variable to each purpose. Which means- variable contains the sum, and other one gets the user input.
Upvotes: 0
Reputation: 2138
With the line
scanf ("%u", &sum); // Let's say the user enters "7"
you override the value of sum on every iteration with a new value entered by the user. Afterwards you add the user variable again with
sum = sum + sum; // equivalent to sum = 7 + 7;
You can avoid that by using two variables:
int sum = 0;
int userIn = 0;
scanf ("%u", &userIn); // userIn has now the value of the user input
sum += userin; // Add that value to the sum
Upvotes: 1