Note :This post is first published on Nov-2011 in my previous blog Techkindle. Moving the content here.

Swapping Two Integers using different methods.

  1. Using Temporary variable
  2. Using Arithmetic Operators
  3. Using EX-OR operator

Here is the complete source code.

using System;
namespace Swapping
{
class Swap
{
static void Main()
{
Console.WriteLine("Swapping Two Integers using different methods.\n");
Console.WriteLine("Using Temporary variable.");
Console.WriteLine("—————————–");
int number1 = 10, number2 = 20;
Console.WriteLine("Before Swapping \n");
Console.WriteLine("number1 = " + number1);
Console.WriteLine("number2 = " + number2);
Console.WriteLine("\n");
int temp;
temp = number1;
number1 = number2;
number2 = temp;
Console.WriteLine("After Swapping \n");
Console.WriteLine("number1 = " + number1);
Console.WriteLine("number2 = " + number2);
Console.WriteLine("\n");
Console.WriteLine("Using Arithmetic Operators.");
Console.WriteLine("—————————–");
number1 = 10; number2 = 20;
Console.WriteLine("Before Swapping \n");
Console.WriteLine("number1 = " + number1);
Console.WriteLine("number2 = " + number2);
Console.WriteLine("\n");
number1 = number1 + number2;
number2 = number1 – number2;
number1 = number1 – number2;
Console.WriteLine("After Swapping \n");
Console.WriteLine("number1 = " + number1);
Console.WriteLine("number2 = " + number2);
Console.WriteLine("\n");
Console.WriteLine("Using EX-OR operator");
Console.WriteLine("—————————–");
number1 = 10; number2 = 20;
Console.WriteLine("Before Swapping \n");
Console.WriteLine("number1 = " + number1);
Console.WriteLine("number2 = " + number2);
Console.WriteLine("\n");
number1 = number1 ^ number2;
number2 = number1 ^ number2;
number1 = number1 ^ number2;
Console.WriteLine("After Swapping \n");
Console.WriteLine("number1 = " + number1);
Console.WriteLine("number2 = " + number2);
Console.ReadLine();
}
}
}

view raw
SwapIntegers
hosted with ❤ by GitHub

Output it as shown Below:

Happy Learning 🙂