Write a code snippet for swapping two variables without using third variable..

 Posted by Nagasundar_Tn on 11/14/2012 | Category: C# Interview questions | Views: 3406 | Points: 40

For Integers
           int i = 10;

int j = 15;
i = i + j;
j = i - j;
i = i - j;
Console.WriteLine("The swapped values are i={0},j={1}", i, j);

In the above code I am adding the two variables. Here i+j = 25 and assigning to i. Now I am subtracting j from i which is 25-15 is equals 10 and assigning to j. In third line I am subtracting j (currently it is 10) from i and assigning to i. So here 25-10=15. At last we will be having the values swapped i=15 and j=10.

For String:
I used replace function here. If any one has better solution then this please let me know.

            string a = "Naga";

string b = "Sundar";
a = a + b;
b = a.Replace(b, "");
a = a.Replace(b, "");
Console.WriteLine("The swapped values are a={0},b={1}", a, b);

I am using the same logic that I used for Integers. I am appending string "a" and "b" and saving it in "a". Now the variable "a" contains text "Nagasundar". From here I am using replace function and eliminates "Sundar". Now string "b" contains "Naga". Once again I am using replace function so that I am removing string "b" (currently "Naga") from "a". So I am getting "Sundar" in variable "a" and "Naga" in variable "b"

Asked In: In my last interview | Alert Moderator 

Comments or Responses

Login to post response