-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,264
  • 1
  • 16
  • 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,731
  • 5
  • 44
  • 72
2

first method

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

second method

a ^= b;
b ^= a;
a ^= b;
isxaker
  • 8,446
  • 12
  • 60
  • 87
0
a = a + b;
b = a - b;
a = a - b;
Christian St.
  • 1,751
  • 2
  • 22
  • 41
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,926
  • 3
  • 20
  • 24