0

$$\sum_{i=1}^5 (-1)^{i+1}*i^2 $$ I thought it would be something like this but i always get 36 or -36. This is c also.

for(i = 1; i <= n; i++)
    if(i++ % 2 == 0) {
        count = pow(-1,n+1)*pow(n,2);
    } else{
        count = pow(-1,n+1)*pow(n,2);
    }

3 Answers3

2

This should suffice

int count = 0;
for(i=1;i<=n;i++)
{
    count += pow(-1,i+1)*i*i;
}

n is just the stop condition, it doesn't need to be referenced explicitly in the loop.

Also you can probably see that you don't need to break the addition into conditions since the arithmetic is the same for both.

kojak
  • 511
0

First thing you have to find sum for 5 terms. So loop should be from n=1 to 5.

Second here is no need of even odd concept.

Amar
  • 847
0

$2$ things I would like to point out:

  1. First of all, the if statement will be
    if(i%2 == 0)
  2. Secondly, the body of both the if and else statements should contain $\mathrm{pow(i,2)}$ rather than $\mathrm{pow(n,2)}$.
  3. Thirdly, the body of both the if and else statements should also contain $\mathrm{count +=}$ rather than $\mathrm{count=}$

Hope this helps.