-4
// Swapping value between two integer without using temp variable.
        int a = 5;
        int b = 7;

        Console.WriteLine("Before Swap.");
        Console.WriteLine("value of A is: {0}", a);
        Console.WriteLine("value of B is: {0}", b);

        Console.ReadLine();

O/P: Before Swap. value of A is: 5 value of A is: 7

After Swap. value of A is: 7 value of A is: 5

So how can you swap two integer value without using temp variable?

Sander
  • 1,256
  • 1
  • 15
  • 26
DotNetKida
  • 29
  • 3
  • You are posting a brain teaser, but this is not really the right place for it. I even think I saw the solution before the edit... Perhaps you should post to puzzling.stackexchange.com ? – samy Oct 09 '14 at 09:20

4 Answers4

2

Try:

 a = a + b;
 b = a - b;
 a = a - b;
blfuentes
  • 2,577
  • 4
  • 42
  • 65
2

first method

a = a + b;
b = a - b;
a = a - b;

second method

a ^= b;
b ^= a;
a ^= b;
isxaker
  • 7,090
  • 10
  • 54
  • 81
0
a = a + b;
b = a - b;
a = a - b;
Christian St.
  • 1,657
  • 2
  • 19
  • 40
0

You need to use the XOR operator:

a = a ^ b;
b = a ^ b;
a = a ^ b;

This works because applying two times the XOR with the same value cancel the operation:

a ^ b ^ b => a
SylvainL
  • 3,896
  • 3
  • 18
  • 24