PCEP-30-02 · Question #100
What will be the output of the following snippet? `` 1 a = 1 2 b = 0 3 a = a ^ b 4 b = a ^ b 5 a = a ^ b 6 print(a, b) ``
The correct answer is D. 1 0. Important note: the provided answer key appears to contain an error. Tracing the XOR swap step-by-step reveals the actual output is 0 1 - option C, not D. Step-by-step trace: | Line | Operation | a | b | |------|-----------|---|---| | 1-2 | Initial values | 1 | 0 | | 3 | a = 1…
Question
1 a = 1
2 b = 0
3 a = a ^ b
4 b = a ^ b
5 a = a ^ b
6 print(a, b)
Options
- A0 0
- B1 1
- C0 1
- D1 0
How the community answered
(64 responses)- A6% (4)
- B13% (8)
- C3% (2)
- D78% (50)
Explanation
Important note: the provided answer key appears to contain an error. Tracing the XOR swap step-by-step reveals the actual output is 0 1 - option C, not D.
Step-by-step trace:
| Line | Operation | a | b |
|---|---|---|---|
| 1-2 | Initial values | 1 | 0 |
| 3 | a = 1 ^ 0 | 1 | 0 |
| 4 | b = 1 ^ 0 | 1 | 1 |
| 5 | a = 1 ^ 1 | 0 | 1 |
| 6 | print(a, b) | → 0 1 |
This is the classic XOR swap algorithm, which exchanges two variables without a temporary variable. Starting with a=1, b=0, the swap produces a=0, b=1.
Why the distractors are wrong:
- A (0 0): XOR of a value with itself gives 0, but that never happens here.
- B (1 1): This would only occur if
aandbstarted equal. - D (1 0): This is the original unchanged values - the swap clearly executes.
Memory tip: Remember x ^ x = 0 and x ^ 0 = x. The XOR swap always exchanges the two values - trace the final state, not the initial one.
Community Discussion
No community discussion yet for this question.