In this blog post, we will explore how to swap two numbers without using a third variable. This is a common programming task that can be achieved through various methods. Let’s dive into it with an example!
Swapping Of Two Numbers Without Using a Third Variable
The Problem
Suppose you have two variables, x
and y
, with the following values:
x = 10
y = 5
Our goal is to swap the values of these variables so that after swapping:
x
should hold the value5
y
should hold the value10
Method 1: Using Arithmetic Operations
One of the simplest ways to swap two numbers is by using arithmetic operations. Here’s how it works:
- Add both numbers and store the result in
x
. - Subtract the new value of
x
fromy
to get the original value ofx
and store it iny
. - Subtract the new value of
y
fromx
to get the original value ofy
and store it back inx
.
Here's the implementation in C#:
using System;
class Program
{
static void Main()
{
int x = 10;
int y = 5;
// Swapping using arithmetic
x = x + y; // x becomes 15 (10 + 5)
y = x - y; // y becomes 10 (15 - 5)
x = x - y; // x becomes 5 (15 - 10)
Console.WriteLine("After swapping:");
Console.WriteLine("x = " + x); // x = 5
Console.WriteLine("y = " + y); // y = 10
}
}
Method 2: Using Bitwise XOR
Another effective method for swapping two numbers without using a third variable is to use the bitwise XOR operation. This method works as follows:
- Perform XOR between
x
andy
, and store the result inx
. - Perform XOR between the new value of
x
andy
, and store it iny
. - Perform XOR between the new value of
x
and the new value ofy
, and store it back inx
.
Here’s how it looks in C#:
using System;
class Program
{
static void Main()
{
int x = 10;
int y = 5;
// Swapping using bitwise XOR
x = x ^ y; // x becomes 15 (binary: 1111)
y = x ^ y; // y becomes 10 (15 ^ 5 = 10)
x = x ^ y; // x becomes 5 (15 ^ 10 = 5)
Console.WriteLine("After swapping:");
Console.WriteLine("x = " + x); // x = 5
Console.WriteLine("y = " + y); // y = 10
}
}
Conclusion
In this post, we learned how to swap two numbers without using a third variable through both arithmetic operations and the bitwise XOR method. Both techniques are efficient and demonstrate fundamental programming concepts.
Feel free to try these methods in your code and see how they work for different values!
Thanks