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

 
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
4 + 6 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice