C# Program to Swap Two Numbers

In this program, you'll learn two techniques to swap two numbers in C#. The first one uses a temporary variable for swapping, while the second one doesn't use any temporary variables.

C# Program to Swap Two Numbers


// Include namespace system
using System;
public class SwapNumbers
{
	public static void Main(String[] args)
	{
		var first = 1.2;
		var second = 2.45;
		Console.WriteLine("--Before swap--");
		Console.WriteLine("First number = " + first.ToString());
		Console.WriteLine("Second number = " + second.ToString());
		// Value of first is assigned to temporary
		var temporary = first;
		// Value of second is assigned to first
		first = second;
		// Value of temporary (which contains the initial value of first) is assigned to second
		second = temporary;
		Console.WriteLine("--After swap--");
		Console.WriteLine("First number = " + first.ToString());
		Console.WriteLine("Second number = " + second.ToString());
	}
}

Output:

--Before swap--

First number = 1.2

Second number = 2.45

--After swap--

First number = 2.45

Second number = 1.2

In the above program, two numbers 1.20 and 2.45 which are to be swapped are stored in variables: first and second respectively.

The variables are printed before swapping using Console.WriteLine() method to see the results clearly after swapping is done.
  • First, the value of first is stored in variable temporary (temporary = 1.20f).
  • Then, the value of the second is stored in first (first = 2.45f).
  • And, finally, the value of temporary is stored in the second (second = 1.20f).
  • This completes the swapping process and the variables are printed on the screen.
Remember, the only use of temporary is to hold the value of first before swapping. You can also swap the numbers without using them temporarily.

Swap two numbers without using temporary variable

In the below program, instead of using temporary variable, we use simple mathematics to swap the numbers.


// Include namespace system
using System;
public class SwapNumbers
{
	public static void Main(String[] args)
	{
		var first = 10;
		var second = 20;
		Console.WriteLine("--Before swap--");
		Console.WriteLine("First number = " + first);
		Console.WriteLine("Second number = " + second);
		first = first - second;
		second = first + second;
		first = second - first;
		Console.WriteLine("--After swap--");
		Console.WriteLine("First number = " + first);
		Console.WriteLine("Second number = " + second);
	}
}

Output:

--Before swap--

First number = 10

Second number = 20

--After swap--

First number = 20

Second number = 10


Comments