Which of the sets of statements below will add 1 to x if x is positive and subtract 1 from x if x is negative but
leave x alone if x is 0?
a) if (x > 0) x++;
else x--;
b) if (x > 0) x++;
else if (x < 0) x--;
c) if (x > 0) x++;
if (x < 0) x--;
else x = 0;
d) if (x == 0) x = 0;
else x++;
x--;
e) x++;
x--;
Answer: b. Explanation: if x is positive, x++ is performed else if x is negative x-- is performed and otherwise, nothing happens, or x is unaffected. In a, c, d and e, the logic is incorrect. In a, x-- is done if x is not positive, thus if x is 0, x becomes –1 which is the wrong answer. In c, if x is positive, then x++ is performed. In either case, the next statement is executed and if x is not negative, the else clause is performed setting x to 0. So if x is positive, it becomes 0 after this set of code. In d, x++ and x-- are both performed if x is not 0. And in e, this code does not attempt to determine if x is positive or negative, it just adds one and then subtracts 1 from x leaving x the same.