Let x be an integer which can take a value of 0 or 1. The statement if(x = =0)…

2004

Let x be an integer which can take a value of 0 or 1. The statement if(x = =0) x = 1; else x = 0; is equivalent to which one of the following?

  1. A.

    x = 1 + x;

  2. B.

    x = 1 - x;

  3. C.

    x = x - 1;

  4. D.

    x = 1 % x;

Attempted by 552 students.

Show answer & explanation

Correct answer: B

Correct expression: x = 1 - x;

Reasoning:

  • If x = 0, then 1 - x = 1, so x becomes 1.

  • If x = 1, then 1 - x = 0, so x becomes 0.

Notes on the other expressions:

  • x = 1 + x; produces values 1 or 2, so it does not toggle between 0 and 1.

  • x = x - 1; produces -1 or 0, so it does not implement the intended toggle.

  • x = 1 % x; is invalid when x = 0 (division by zero) and therefore cannot be used as an equivalent toggle. For x = 1 it yields 0, but the expression is unsafe.

  • Alternative concise correct form: x = x ^ 1; (bitwise XOR) also flips a value constrained to 0 or 1.

Explore the full course: Gate Guidance By Sanchit Sir