Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

What does the expression S+=i*(2*(i%2)-1) mean while writing a code in C?

I know that % 2 mean dividing something and the remainder is our answer but how about the whole thing?

share|improve this question
add comment

closed as off topic by tdammers, thorsten müller, Blrfl, Giorgio, Kilian Foth Apr 24 '13 at 11:37

Questions on Programmers Stack Exchange are expected to relate to software development within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer

up vote 6 down vote accepted

Lets assume the code is something like this :

double S;
for(int i ; i < BIG_NUMBER ; ++i){

S is call an accumulator, because each step you will take the last value and add to that the result of i*(2*(i%2)-1).

The i*(2*(i%2)-1) is pretty simple :

  • i%2 will be either 0 or 1
  • 2*(i%2) will be either 0 or 2
  • (2*(i%2) - 1) will be either -1 or 1
  • i*(2*(i%2)-1) will be -i or i;

So basically if the number is even you add -i, if the number is not even you add i to S.

Here what S looks like

share|improve this answer
I love you very much. –  user2310758 Apr 24 '13 at 7:15
Accept his/her answer then! –  Alan B Apr 24 '13 at 9:44
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.