In this tutorial, we will write a program to swap two numbers in C#. We will use a temporary variable to swap the numbers along with a user-defined function.
Question:
Write a C# program to Swap two Numbers using third variable.
Explanation:
The user input values are passed as an argument in SwapValue function where they are swapped using a third variable temp and the swapped output is displayed as shown in the program below.
C# Program to Swap two Numbers using the Third variable
Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | using System; public class Swap { public static void SwapValue(int a, int b) { Console.WriteLine("Entered Numbers are: A=" + a.ToString() + " B=" + b.ToString()); //temporary variable var temp = a; a = b; b = temp; //Display Console.WriteLine("The Swapped Numbers are: A=" + a.ToString() + " B=" + b.ToString()); } public static void Main(string[] arg) { Console.WriteLine("Enter the two numbers that you want to swap: "); var input = ""; input = Console.ReadLine(); var x = int.Parse(input); input = Console.ReadLine(); var y = int.Parse(input); SwapValue(x, y); } } |
Output: