In this example, i’ll show you how to swap two numbers without using temporary variables in C#.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | static void Main(string[] args) { int a = 5, b = 10; Console.WriteLine("Before swapping."); Console.WriteLine("a={0} b={1}",a,b); a = a + b; b = a - b; a = a - b; Console.WriteLine("After swapping."); Console.WriteLine("a={0} b={1}", a, b); Console.ReadKey(); } |
- Initially,
a = 5
andb = 10
. - Then, we add a and b and store it in a with the code
a = a + b
. This meansa = 5 + 10
. So,a = 15
now. - Then we use the code
b = a - b
. This meansb = 15 - 10
. So,b = 5
now. - Again, we use the code
a = a - b
. This meansa = 15 - 5
. So finally,a = 10
.
Hence, the numbers have been swapped.
Output:
1 2 3 4 5 6 7 | Before swapping. a = 5, b = 10 After swapping. a = 10, b = 5 |