;

C# program to swap two numbers without using a third variable


Tutorialsrack 02/05/2019 C# Programs

In this C# program, we will learn how to swap two numbers without using the third variable or using a temporary variable.

There are many ways to swap two numbers without using the third variable or using a temporary variable.

We are using two common ways to swap two numbers without using the third variable:

  1. By using + and - operator
  2. By using * and  / operator

Program By Using 1st way: By using + and – operator

Code - Program By Using 1st way: By using + and – operator
using System;

namespace SwapNumberWithoutUsing3rdVariable
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 5, b = 10;
            Console.WriteLine("Number Before swapping a= {0} and b= {1}", a, b);
            a = a + b; //Here, a=15 (5+10)      
            b = a - b; //Here, b=5  (15-10)      
            a = a - b; //Here, a=10 (15-5)   
            Console.Write("Number After swapping a= {0} and b= {1}", a, b);
            Console.ReadLine();
        }
    }
}
Output

Number Before swapping a= 5 and b= 10

Number After swapping a= 10 and b= 5

Program By Using 2nd way: By using * and / operator

Code - Program By Using 2nd way: By using * and / operator
using System;

namespace SwapNumberWithoutUsing3rdVariable
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 5, b = 10;
            Console.WriteLine("Number Before swapping a= {0} and b= {1}", a, b);
            a = a * b; //Here, a=50 (5*10)      
            b = a / b; //Here, b=5  (50/10)      
            a = a / b; //Here, a=10 (50/5)    
            Console.Write("Number After swapping a= {0} and b= {1}", a, b);
            Console.ReadLine();
        }
    }
}
Output

Number Before swapping a= 5 and b= 10

Number After swapping a= 10 and b= 5


Related Posts



Comments

Recent Posts
Tags