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();
- }
- }
- }