Saturday, April 25, 2009

Swapping Values between two variables without using temp variable

There is an easy way to swapping values of two variables by using a temporary variable. But here am trying to get interchanged values between those variables without using any temporary variable. Just look in to this…


public int a = 10;

public int b = 20;


//Before swapping

textBox1.Text = a.ToString();

textBox2.Text = b.ToString();

//After swapping

a = a + b;

b = a - b;

a = a - b;

textBox1.Text = a.ToString();

textBox2.Text = b.ToString();

//For strings

String name1 = "Hello";

String name2 = "World";

name1 = name1 + name2;

name2 = name1.Substring(0, (name1.Length - name2.Length));

name1=name1.Substring(name2.Length);

Response.Write(name1);

Response.Write(name2);

No comments:

Post a Comment