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:
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();
}
}
}
Number Before swapping a= 5 and b= 10
Number After swapping a= 10 and b= 5
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();
}
}
}
Number Before swapping a= 5 and b= 10
Number After swapping a= 10 and b= 5
Comments