Question & Answer

Which of the following code segments can be used to interchange the values of the variables num1 and num2?

Which of the following code segments can be used to interchange the values of the variables num1 and num2?
A
num1 ⇔ num2
num2 ⇔ num1

B
temp ⇔ num1
num1 ⇔ temp
num2 ⇔ num1

C
temp ⇔ num1
num2 ⇔ num1
num1 ⇔ temp

D
temp ⇔ num1
num1 ⇔ num2
num2 ⇔ temp

1 Answer

Verified archive
Quizzma TeamJanuary 5, 2025

The correct answer is D.

Explanation:

In option D, the steps performed are:

1. `temp ⇔ num1`: Store the value of `num1` in `temp`.
2. `num1 ⇔ num2`: Assign the value of `num2` to `num1`.
3. `num2 ⇔ temp`: Finally, assign the value stored in `temp` (original `num1`) to `num2`.

This effectively swaps the values of `num1` and `num2`. Other options do not correctly perform the swap without losing one of the values.