Reputation: 1173
int main (){
int i, total;
printf("Loop to one hundred.\n");
for(i=1; i<=100; i+=2){
printf("%d ",i);
total += i;
}
printf("\nTotal: %d", total);
return 0;
}
So I have a C programming code up on it, and I have the result as well. But what I found is the result isn't what the answer that I want. I was expecting the result is 2500 but it gave 2516.
Can someone point it out what's wrong on my code?
If someone suggest using while loop, yes while loop can gave me the correct answer which is 2500 but I want to know why I use for loop it gave me 2516.
Upvotes: 0
Views: 785
Reputation: 75062
You forgot to initialize the variable total
before starting additions.
int i, total;
should be
int i, total = 0;
Upvotes: 3