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?
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.