Create a simple code fragment that will swap the values of two variables num1 and num2.
Create a simple code fragment that will swap the values of two variables num1 and num2.
Create a simple code fragment that will swap the values of two variables num1 and num2.
Best answer
int temp;
temp = num1;
num1 = num2;
num2 = temp;Answer:
int temp;
temp = num1;
num1 = num2;
num2 = temp;
A third variable temp is needed because assigning num1 = num2 directly would overwrite the value of num1 and lose it.
temp = num1; saves the original value of num1.num1 = num2; copies num2 into num1.num2 = temp; puts the saved original num1 into num2.Example: num1 = 3, num2 = 8 → temp = 3 → num1 = 8 → num2 = 3.
Without a temporary variable (for integers) you can also write:
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;Log in or create a free account to answer this question.