Skip to content
doubtly

2 answers

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.

  1. temp = num1; saves the original value of num1.
  2. num1 = num2; copies num2 into num1.
  3. 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;
Doubtly AI · 24 Oct 2026 AI-verified · Oct 2026 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.