ProgrammingHard

int s = 0; for (int i = 1; i <= 4; i++) s += i * (i % 2 ? 1 : -1); printf("%d", s); What is printed?

  1. A. 3
  2. B. -2
  3. C. 4
  4. D. -5

Correct answer: B. -2

i % 2 is 1 for odd i, so odd terms are added and even terms subtracted: 1 - 2 + 3 - 4 = -2. 4 keeps only the odd terms and forgets to subtract the even ones.

More C Programming questions

Exams that ask this topic