Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swapping two integer values in different ways.
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();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment