### calculating

How would i write a code that calculates 1*1+2*2-3*3+4*4-5*5+...+100*100?
Ever hear of a loop?

Try writing some code and we will try and help if you get stuck.
i know we would use a loop but i jus didnt know how to start it. ok hold on one sec
OK and yes i have i just don't know how to start it its confusing
You've got the right idea, but your statement at line 7 is not right.

 `` `` `` sum += pow(i,i);``

You probably want to make sum a long, or even an int64 (depending on your implementation). Your series will probably exceed the capacity of an int.

And of course, your loop condition in line 6 needs to be i<=100.

Edit: What happened to your code?

Edit #2: Missed the alternating sign.
Last edited on
By initializing 'sum' to 1, you take care of the (1*1) term. Now you need a loop to accumulate +(2*2), -(3*3), +(4*4), etc.. The number itself is represented by i in the loop. If you say `sum += i*i;` in the loop, that's like saying +(2*2), +(3*3), +(4*4), etc...

You're pretty close to handling how to get the sign to flip on every other term using the pow function. Instead of pow(-1, 1) (which always equals -1) you should say pow(-1, i), which will be +1 if i is an even number and -1 if i is odd. Multiplying this by each term as you go along will effectively flip the sign of each successive term.
Last edited on
Topic archived. No new replies allowed.