Swapping of 2 Numbers without using 3rd Variable


In this post we will see how to swap two numbers without using third variable. Check below sample codes.

1. Using (+,-)

a = a+b = 4+5 = 9     // Should Not Overflow
b = a-b = 9-5 = 4
a = a-b = 9-4 = 5

2. Using (*,/)

a = a*b = 4*5 = 20    // Should Not Overflow
b = a/b = 20/5 = 4    // Should Not Overflow and Should Not be Irrational Number
a = a/b = 20/4 = 5    // Should Not Overflow and Should Not be Irrational Number

VB.NET Example :

Module SwappingDemo
    Sub main()
        Dim a, b As Integer
        Console.Write("Enter the values of a and b:")
        a = CInt(Console.ReadLine())
        b = CInt(Console.ReadLine())
        Console.WriteLine("Before swapping values of a=" + a.ToString() + " b=" + b.ToString())
        a = a + b
        b = a - b
        a = a - b
        Console.WriteLine("After swapping values of a=" + a.ToString() + " b=" + b.ToString())
        Console.ReadLine()
    End Sub
End Module

C#.NET Example

static class SwappingDemo
{
	public static void main()
	{
		int a = 0;
		int b = 0;
		Console.Write("Enter the values of a and b:");
		a = Convert.ToInt32(Console.ReadLine());
		b = Convert.ToInt32(Console.ReadLine());
		Console.WriteLine("Before swapping values of a=" + a.ToString() + " b=" + b.ToString());
		a = a + b;
		b = a - b;
		a = a - b;
		Console.WriteLine("After swapping values of a=" + a.ToString() + " b=" + b.ToString());
		Console.ReadLine();
	}
}
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