Ali Sobhani Ali Sobhani - 2 months ago 7
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\"!");

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

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

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

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

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

} while (number != 0);

system("pause");
return 0;
}

Answer

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.

Comments