dmubu
dmubu

Reputation: 1133

Incorrect sum - For loop in C

I am trying to sum values in a for loop with C. The initial value of variable x = 1 and I want to double it a set number of times and add the result. I have made the for loop, but my sum is always off by the initial value.

For example, if x = 1, the pattern should go:

1, 2, 4, 8, 16

...and the total should be 31. Unfortunately, total is off by one.

int x = 1;
int y = 10;
int total;

for(int i = 1; i < y; i++)
{   
   x *= 2;
   total += x;
}

printf("Total: %d\n", total);

This is off by one. How can I have the loop start with 1 instead of 2?

Upvotes: 0

Views: 296

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320491

As is usually the case with erroneous code, there is more that one way to "fix" it. While you made it sufficiently clear as to what you are trying to implement, nobody knows how you are trying to implement it.

  • As @Ray Toal already noted in his answer, the correct result can be obtained by initializing total to 0 before the cycle and doing x *= 2 after the addition inside the cycle.

  • Alternatively, one can say that the cycle is OK as it is in the original code. You just have to initialize the total to 1 before the cycle.

Which approach is closer to what you were trying to implement originally - only you know. In both cases make sure you make the correct number of iterations.

Upvotes: 0

Ray Toal
Ray Toal

Reputation: 88378

Switch the two statements in the body of the for loop. Also it is a good idea to initialize total to 0, in case you want to move all of this into a function.

Upvotes: 2

Related Questions