1

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;
    }
3
  • 3
    You need to put the sum=0 into the loop, before summing it Commented Sep 22, 2016 at 16:13
  • 2
    Try moving the definition of the variable sum into the loop. Commented Sep 22, 2016 at 16:13
  • Thx guys. you go blind working on your own code cheers! Commented Sep 22, 2016 at 16:17

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent advice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.