if Statements and Control Flow

AP Computer Science A· difficulty 2/5

int y;
if (x > 0) y = 1;
else y = -1;

Which single statement is equivalent?

  • A

    int y = x > 0 ? -1 : 1;

  • B

    int y = x ? 1 : -1;

  • C

    int y = x > 0 ? 1 : -1;

    check_circle
  • D

    int y = (x > 0) - 1;

Explanation

The ternary cond ? a : b returns a when true, b when false: y becomes 1 if x > 0, otherwise -1.

Want 10 more like this — adaptive to your weak spots?

Related questions