In most swap operations, we use a third variable. The following code snippet shows how we can use just two int variables to swap their values.
- using System;
- namespace swap
- {
- class Program
- {
- static void Main(string[] args)
- {
- int first, second;
- Console.WriteLine("ENTER THE FIRST NO");
- first = int.Parse(Console.ReadLine());
- Console.WriteLine("ENTER THE Second NO");
- second = int.Parse(Console.ReadLine());
- if (first != second)
- {
- first = first + second;
- second = first - second;
- first = first - second;
- Console.WriteLine("The First No is After Swapping {0}", first);
- Console.WriteLine("The Second No is After Swapping {0}", second);
- Console.ReadLine();
- }
- else
- Console.WriteLine("The First and Second No Should be Different");
- Console.ReadLine();
- }
- }
- }
kumar vPosted Mar 19, 2019, 11:50 AM
how to handle overflow?
Tharindu AthapattuPosted Mar 7, 2019, 5:27 AM
This only works when the first>second
Faisal PathanPosted Mar 7, 2019, 12:37 AM
Or even with one line like : first = first ^ second ^ (second = first);
Faisal PathanPosted Mar 7, 2019, 12:30 AM
Nice blog for beginner, but you can use like this also (first ^= second ^= first; second ^= first;)
Jimmy CrabPosted Mar 6, 2019, 7:28 PM
Very cool tips!
Jeeva SubburajPosted Mar 6, 2019, 2:11 PM
With ValueTuple in C# 7 and above, you can swap the variable in just one line. (first, second) = (second, first);