C# Program to swap two numbers without using the third variable

In this C# program, we will swap two numbers without using the third variable. We will use two methods to swap numbers 1) By using Addition and Subtraction 2) By using Multiplication and Division

 

C# Program to swap two numbers using Addition and Subtraction Code:

        private static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            int a = 10, b = 20;
            Console.WriteLine("Before Swappping a=" + a + " b=" + b);
            a = a + b; //Here a=30 (10+20=30)      
            b = a - b; //Here b=10 (30-20=10)      
            a = a - b; //Here a=20 (30-10=20)   
            Console.Write("After Swaping a=" + a + " b=" + b);
            Console.ReadLine();
        }

C# Program to swap two numbers without using the third variable Output:

C#-Program-to-swap-two-numbers-without-using-the-third-variable

C# Program to Multiplication and Division Code:

       private static void Main(string[] args)
       {
            Console.ForegroundColor= ConsoleColor.Yellow;
            int a = 10, b = 20;
            Console.WriteLine("Before Swappping a=" + a + " b=" + b);
            a = a * b; //Here a=200 (10*20=200)      
            b = a / b; //Here b=10 (200/20=10)      
            a = a / b; //Here a=20 (200/10=20)   
            Console.Write("After Swaping a=" + a + " b=" + b);
            Console.ReadLine();
        }

C# Program to swap two numbers without using the third variable Output:

C#-Program-to-swap-two-numbers-without-using-the-third-variable

 
We are nothing without our users ! You can help us offer even more high quality content. Please share our page !
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
5 + 5 =
 
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2022 CodingFusion
75 Important SQL Server queries you should know