Swapping 2 numbers patterns / algorithms

  Swapping 2 numbers with temporary variable


static void Swap2NumbersWithTempVariable()

{

int firstNumber = 111;

int secondNumber = 222;

int temp;

Console.WriteLine(“================”);

Console.WriteLine(“First Number:” + firstNumber);

Console.WriteLine(“Second Number:” + secondNumber);

temp = firstNumber;

firstNumber = secondNumber;

secondNumber = temp;

Console.WriteLine(“First Number:” + firstNumber);

Console.WriteLine(“Second Number:” + secondNumber);

Console.WriteLine(“================”);

}

Swapping 2 numbers without temporary variable

static void Swap2NumbersWithOutTempVariable()

{

int firstNumber = 111;

int secondNumber = 222;

Console.WriteLine(“================”);

Console.WriteLine(“First Number:” + firstNumber);

Console.WriteLine(“Second Number:”

+ secondNumber);

firstNumber = firstNumber + secondNumber;

secondNumber = firstNumber – secondNumber;

firstNumber = firstNumber – secondNumber;

Console.WriteLine(“First Number:” + firstNumber);

Console.WriteLine(“Second Number:” + secondNumber);

Console.WriteLine(“================”);

}

Swapping 2 numbers using bitwise XOR operator

static void Swap2NumbersUsingBitWiseXOR()

{

int firstNumber = 111;

int secondNumber = 222;

Console.WriteLine(“================”);

Console.WriteLine(“First Number:” + firstNumber);

Console.WriteLine(“Second Number:” + secondNumber);

firstNumber ^= secondNumber;

secondNumber ^= firstNumber;

firstNumber ^= secondNumber;

Console.WriteLine(“First Number:” + firstNumber);

Console.WriteLine(“Second Number:” + secondNumber);

Console.WriteLine(“================”);

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s