Snippets Zone

Swap two numbers using temporary variable in C#

By Anoop Kumar Sharma    643  28-June-2021

This snippet shows how to swap two numbers using temporary variable in C#


In this snippet, we will see the program to swap two numbers using the third or temporary variable in C#. Swapping program is one of the basic programs which is asked can be asked during exams or by the interviewer. 

Program to swap two numbers using the third or temporary variable in C#:

static void Main(string[] args)
{
            //Variable to hold an input number
            //tempVariable is used for swapping
            int firstNumber, secondNumber, tempVariable;
            Console.WriteLine("Enter first number :");
            firstNumber = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter second number :");
            secondNumber = int.Parse(Console.ReadLine());
            //Before swapping
            Console.WriteLine("Before swapping, first number is {0} and second number is {1}.", firstNumber, secondNumber);
            //Swapping using third/temporary variable
            tempVariable = firstNumber;
            firstNumber = secondNumber;
            secondNumber = tempVariable;
            //After swapping
            Console.WriteLine("After swapping, first number is {0} and second number is {1}.", firstNumber, secondNumber);
            //Console.ReadLine() to hold the screen after the execution of the program
            Console.ReadLine();
}

Preview:

I hope this program will help you in your interview/exam.