Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swap Too Numbers
using System;
namespace SwapTooNumbers
{
public class StartUp
{
// How to swap to numeric values
public static void Main(string[] args)
{
int first = 1;
int second = 2;
// with temp variable
Console.WriteLine("Swap with temporary variable: ");
SwapWithTempVariable(first, second);
// without temp variable - XOR(^)
Console.WriteLine("Swap without temp variable using XOR(^): ");
SwapWithXOR(first, second);
// with only plus and minus
Console.WriteLine("Swap without temp variable using plus(+) and minus(-): ");
SwapWithPlusAndMinus(first, second);
}
private static void SwapWithPlusAndMinus(int first, int second)
{
first = first + second;
second = first - second;
first = first - second;
PrintResult(first, second);
}
private static void SwapWithXOR(int first, int second)
{
first = first ^ second;
second = second ^ first;
first = first ^ second;
PrintResult(first, second);
}
private static void SwapWithTempVariable(int first, int second)
{
var temp = first;
first = second;
second = temp;
PrintResult(first, second);
}
private static void PrintResult(int first, int second)
{
Console.WriteLine(first);
Console.WriteLine(second);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment