Advertisement

Latest Post

Sunday, 1 January 2017

How to Swap values of two variables using a third variable [C#]

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

Following is the simple C# code :


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

            int first, second;
            Console.WriteLine("Enter the First value : ");
            first = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter the  Second value : ");
            second = int.Parse(Console.ReadLine());

            Console.WriteLine("Before swaps  : ");
            Console.WriteLine("the First value :" + first.ToString());
            Console.WriteLine("the Second value :" + second.ToString());

            first = first + second;
            second = first - second;
            first = first - second;

            Console.WriteLine("\nAfter swaps : ");
            Console.WriteLine("the First value :" + first.ToString());
            Console.WriteLine("the Second value :" + second.ToString());
            Console.ReadLine();

        }
    }

Output:-
Enter the First value :
45
Enter the  Second value :
23
Before swaps  :
the First value :45
the Second value :23

After swaps :
the First value :23
the Second value :45

Government Jobs