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:
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:
