Skip to content

Swap Two Numbers Without Using Temp Variable

Here, we are going to swap 2 integers without using any intermediate or temporary variable.

In order to execute the code I’ve created a simple console application to print out the result.

Please find complete code below:

using System;

namespace PracticeConsole
{
   class Program
   {
      static void Main(string[] args)
      {
         int firstNumber = 19;
         int secondNumber = 21;
         Console.WriteLine("Numbers before swapping are: " + firstNumber + " and " + secondNumber);
         firstNumber = firstNumber + secondNumber;
         secondNumber = firstNumber - secondNumber;
         firstNumber = firstNumber - secondNumber;
         Tuple<int, int>  myTupleResult = new Tuple<int, int>(firstNumber, secondNumber);
         Console.WriteLine("Numbers after swapping are: " + myTupleResult.Item1 + " and " + myTupleResult.Item2);
         Console.ReadLine();
      }
   }
}

Result: