Advertisement

Latest Post

Sunday, 1 January 2017

How to swap values of 2 variables without using a third variable [C#]

Write a program in C# that swaps values of two variables without using a third variable.

Following is the simple C# code :


class Lab
    {
        static void Main(string[] args)
        {

            int firstValue = 50;
            int secondValue = 100;
            Console.WriteLine("Before swap firstValue = {0} and secondValue = {1}", firstValue, secondValue);
            firstValue = firstValue + secondValue;
            secondValue = firstValue - secondValue;
            firstValue = firstValue - secondValue;
            Console.WriteLine("\nAfter swap firstValue = {0} and secondValue = {1}", firstValue, secondValue);
            Console.ReadLine();

        }
    }

Output:-

Before swap firstValue = 50 and secondValue = 100

After swap firstValue = 100 and secondValue = 50

Government Jobs