Q:

# C# program to swap two numbers with and without using third variable

Given two integer numbers and we have to swap them.

We are swapping numbers using two methods:

### 1) Swapping using third variable

To swap numbers, we use a temporary variable to holds the value, firstly we assign first variable to the temporary variable then assign second variable to the first variablecand finally assigns value which is in temporary variable (which holds first number) to the second variable.

Consider the program:

``````using System;
namespace swap
{
class ab
{
static void Main(String[] args)
{
int a=5,b=3,temp;

//swapping
temp=a;
a=b;
b=temp;

Console.WriteLine("Values after swapping are:");
Console.WriteLine("a="+a);
Console.WriteLine("b="+b);
}
}
}``````

Output

```Values after swapping are:
a=3
b=5
```

### 2) Swapping without using third variable

Here, we do not use any extra variable to swap the numbers. There are some set of statements (with mathematical operations which performs on the numbers), which swaps the values of variable which are using in these operations.

Example: If we have to swap the values of variable a and b, then the set of statements to swap them, are:

```a=a+b;
b=a-b;
a=a-b;
```

Consider the program:

``````using System;
namespace swap
{
class ab
{
static void Main(String[] args)
{
int a=10,b=20;

//swapping
a=a+b;
b=a-b;
a=a-b;

Console.WriteLine("Values after swapping are:");
Console.WriteLine("a="+a);
Console.WriteLine("b="+b);
}
}
}``````

Output

```Values after swapping are:
a=20
b=10
```