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 value`5`

`y`

should hold the value`10`

### 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`

from`y`

to get the original value of`x`

and store it in`y`

. - Subtract the new value of
`y`

from`x`

to get the original value of`y`

and store it back in`x`

.

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`

and`y`

, and store the result in`x`

. - Perform XOR between the new value of
`x`

and`y`

, and store it in`y`

. - Perform XOR between the new value of
`x`

and the new value of`y`

, and store it back in`x`

.

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**