How to Swap Two Numbers using C#


Swapping of two numbers refers to the exchanging values of two variables.
Here are two methods which we can use for swapping two integers

  1. Swap using a temporary variable
  2. Swap without using a temporary variable

Swap two integer using a temporary variable

This swap operation is performed by using a third variable (a temporary variable).

Here is the simple code example of swapping using a temporary variable:

using System;
namespace SwapTwoIntegers
{
    class Program
    {
         static void Main(string[] args)
        {
            int Number1, Number2, TempNumber;

            Console.Write("\nPlease enter the 1st number: ");
            Number1 = int.Parse(Console.ReadLine());

            Console.Write("\nPlease enter the 2nd number: ");
            Number2 = int.Parse(Console.ReadLine());

            TempNumber = Number1;
            Number1 = Number2;
            Number2 = TempNumber;

            Console.Write("\nAfter Swapping: ");
            Console.Write("\n1st Number: " + Number1);
            Console.Write("\n2nd Number: " + Number2);

            Console.ReadLine();
        }
    }
}

Output

Swap two integer using a temporary variable

Swap without using a temp variable

using System;
namespace SwapTwoInteger
{
    class Program
    {
   static void Main(string[] args)
        {
            int Number1 = 16;
            int Number2 = 23;
            Console.WriteLine("Initial two numbers:");
            Console.WriteLine("\nNumber1 : {0} ", Number1);
            Console.WriteLine("\nNumber2 : {0} ", Number2);

            Number1 = Number1 + Number2; //x1=110 (50+60)      
            Number2 = Number1 - Number2; //x2=50 (110-60)      
            Number1 = Number1 - Number2; //a=60 (110-50)   
            Console.WriteLine("\nSwapped numbers");

            Console.WriteLine("\nNumber1 : {0} ", Number1);
            Console.WriteLine("\nNumber2 : {0} ", Number2);

            Console.ReadLine();

        }
    }
}

Output

Swap two integers without using a temp variable

Asha Shoukeir

About Asha shoukeir

Software Developer and System Administrator

View all posts by Asha shoukeir →