C# Program to Swap Two Numbers Using Third Variable

C# program to swap two numbers using third variable can be implemented by using another variable apart from the variables which store the two given numbers. Swapping of two numbers means the exchanging of values between them.






1. C#Program & output of to Swap Two Numbers using Third Variable

Code has been copied
/* *******************************************
           alphabetacoder.com
 C# program to swap two numbers using third variables
******************************************* */

using System;

namespace Swap {
    class Program {
        static void Main(string[] args) {
            //declare and initialize variables
            int num1 = 5, num2 = 10, temp;

            //show numbers before swapping
            Console.WriteLine("Before swapping: number1 = " + num1 + " and number2 = " + num2);

            //do swapping using xor(^)
            temp = num1;
            num1 = num2;
            num2 = temp;

            //show numbers after swapping
            Console.WriteLine("After swapping: number1 = " + num1 + " and number2 = " + num2);

            // wait for user to press any key
            Console.ReadKey();
        }
    }
}

Output


Enter two numbers = 5 10

Before swapping: number1 = 5 and number2 = 10

After swapping: number1 = 10 and number2 = 5