[Solved] C programming language help me?


Your summation is wrong:

s+=((2*i-1) -2*i );

gives -1.

You need:

s+=i*(2*(i%2) - 1);

It will give “-” to all even i‘s and “+” to all odd i‘s.

And since you are dealing with whole numbers only, i should be int, as well as all other variables you use:

#include <stdio.h>
int main ()
{
    int s = 0, c= 0, n = 0, i = 1;
    c = getch();
    printf ("\n Please write n:");
    scanf ("%d",&n);
    for (i=1; i<=n; i++)
    {
        s+=i*(2*(i%2) - 1);
    }
    printf("\n Sum =%d",s);
    getch ();
 }

Even simpler, using some easy math you can get it as:

if(n%2 == 0){
    s = -n/2;
}
else{
    s = n - n/2;
}

6

solved C programming language help me?