Ali Sobhani
Ali Sobhani

Reputation: 13

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;
    }

Upvotes: 1

Views: 66

Answers (1)

user6300394
user6300394

Reputation:

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.

Upvotes: 3

Related Questions