Ali Sobhani Ali Sobhani - 1 year ago 58
C Question

C programming - do while loop help (code almost done)

I have created a code that writes out the sum of all even numbers.
But every time it loops the sum of the last run is saved and added in the sum of the new run. how do i make it have a new loop?

sorry for my bad english, and thx in advance

int main()

int number = 0;
int sum = 0;
printf("Welcome to\"Sum Evens\"!");

printf("\ninput a number: ");
scanf(" %d", &number);
if (number == 0)
printf("Goodbye, have a nice day!\n");

if (number % 2 != 0)
number -= 1;

for (int i = 0; i <= number; i += 2)

printf(" %d ", i);
if (i != number)
sum += i;

printf("= %d\n", sum);

} while (number != 0);

return 0;

Answer Source

Watch these sort of problems melt away if you declare your variables as close to their first use as possible.

In your case, move int sum = 0; to just before the for loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download