0

I need my program to run and tell me the sum of the natural number entered also it needs to say along with the sum total i need it to show the sum of odd and even integers. This is what I have so far and it won't run correctly in C.

#include <stdio.h>
int main (void)
{
    int n, i, sum = 0;
    int sum1 = 0;
    int sum2 = 0;
    printf("enter a number and I will tell you the numbers sums.");
    scanf("%d", &n);

    for(i=1; i<= n; ++n)
    {
        sum2 = sum2 + n;
    }
    for(i=2; i<= n; ++n)
    {
        sum1 = sum1 + n;
    }
    for(i=1; i<= n; ++n)
    {
        sum += i;
    }
    printf("sum of integers is %d" ,sum);
    printf("sum of odd integers is %d" ,sum1);
    printf("sum of even integers is %d" ,sum2);

    return 0;
}
3
  • needs minimal reproducible example and a proper problem statement. Commented Feb 9, 2017 at 0:59
  • 1
    i.e. "Describe the problem. "It doesn't work" is not a problem statement. Tell us what the expected behavior should be. Tell us what the exact wording of the error message is, and which line of code is producing it. Put a brief summary of the problem in the title of your question." Commented Feb 9, 2017 at 1:00
  • two words - Young Gauss. Commented Feb 10, 2017 at 0:06

3 Answers 3

1

In your loops to count odd and even, you need to increment by 2 in the loop, not one. Instead of ++i, use i += 2:

for (i = 2; i <= n; i += 2)

And it should be i in the increment, not n. You're changing the value of your final variable. Further, unless I'm misunderstanding what you're trying to do, you should be adding i to your sums, not n.

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

Comments

1

The sum of the first N natural numbers is a well-known formula,

sum(range(1,N)) == N*(N+1)/2

Read this exposition, and then see if you can derive a formula for the sum of even or odd, http://mathandmultimedia.com/2010/09/15/sum-first-n-positive-integers/

(hint: the sum of every other number would be about 1/2)

Comments

0

You only require a one for loop here's how

sum = sum1= sum2 =0;
for(i=0; i<= n; i++)
{
sum = sum +i;
if(i %2 == 0)
sum2 += i;
else
sum1 +=i;
}

use if statement for filtering numbers and don't forget to initialise all sum var to 0

Comments

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.