Swap two numbers without using a temp variable in C#
We can swap two numeric value without a temporary variable as follows :
public static void
SwapNumbers() { int a =
100; int b =
200; a = a
+ b; b = a
- b; a = a
- b;
Console.WriteLine(a);
Console.WriteLine(b); } |
We can also use XOR(^) operator for the same :
public static void
SwapNumbers() { int a =
100; int b =
200; a = a
^ b; b = b
^ a; a = a
^ b;
Console.WriteLine(a);
Console.WriteLine(b); } |
Output
EmoticonEmoticon