C# - Swap two numbers
There are two common ways to swap the value of two variables:
- Swap the value of two variables using a temporary variable
- Swap the value of two variables without using temporary variable
Method 1: Swap the value of two variables using a temporary variable
In the example below, the initial value of variables x and y are 10 and 25. A temporary variable called temp is created to store the value of x and then the value of y is assigned to x. Finally, value of temp (which stores values of x) is assigned to variable y. The final value of variables x and y after swap are 25 and 10 respectively.
using System; class MyProgram { static void swap(int x, int y) { Console.WriteLine("Before Swap."); Console.WriteLine("x = " + x); Console.WriteLine("y = " + y); //Swap technique int temp = x; x = y; y = temp; Console.WriteLine("After Swap."); Console.WriteLine("x = " + x); Console.WriteLine("y = " + y); } static void Main(string[] args) { swap(10, 25); } }
The above code will give the following output:
Before Swap. x = 10 y = 25 After Swap. x = 25 y = 10
Method 2: Swap the value of two variables without using temporary variable
+ operator is used to swap the value of two variables. In this method no temporary variable is used. See the example below for syntax.
using System; class MyProgram { static void swap(int x, int y) { Console.WriteLine("Before Swap."); Console.WriteLine("x = " + x); Console.WriteLine("y = " + y); //Swap technique x = x + y; y = x - y; x = x - y; Console.WriteLine("After Swap."); Console.WriteLine("x = " + x); Console.WriteLine("y = " + y); } static void Main(string[] args) { swap(10, 25); } }
The above code will give the following output:
Before Swap. x = 10 y = 25 After Swap. x = 25 y = 10
Similarly, others operators can also be used in this method. Please see the page: C# - Swap two numbers without using Temporary Variable.
Recommended Pages
- C# Program - To Check Prime Number
- C# Program - Bubble Sort
- C# Program - Selection Sort
- C# Program - Maximum Subarray Sum
- C# Program - Reverse digits of a given Integer
- C# Program - Merge Sort
- C# Program - Shell Sort
- Stack in C#
- Queue in C#
- C# Program - Find LCM of Two Numbers
- C# Program - To Check Whether a Number is Palindrome or Not
- C# Program - To Check Whether a String is Palindrome or Not
- C# Program - Heap Sort
- C# Program - Quick Sort
- C# - Swap Two Numbers without using Temporary Variable
- C# Program - To Check Armstrong Number
- C# Program - Counting Sort
- C# Program - Radix Sort
- C# Program - Find Largest Number among Three Numbers
- C# Program - Print Floyd's Triangle