# C Program to Swap two Numbers without using third variable

Write a c program to swap two numbers without using third variable. Given two input numbers, We have to write a code to swap two numbers without using third variable. In my previous post, I have explained a c program to swap two numbers using third variable. This question is generally asked in an interview.

Swap two numbers using Bitwise XOR Operator

### Algorithm to swap two numbers without using third variable

Let’s say we have two numbers a and b. We need to swap these two numbers without using any temp or third variable.

Step 1 – Add the value of a and b then assign the sum to variable a.

Step 2 – Subtract the value of variable b from variable a and assign it to variable b.

Step 3 – Subtract the value of variable a and b and assign it to variable a.

Let’s take an example to understand this algorithm. Suppose the value of variable a is 3 and variable b is 4.

a = 3 and b =4

Output – a = 4 and b = 3.

Subscribe Our Tutorials

C Program to Swap Two Numbers without using Third Variable

## C Program to Swap Two Numbers using Multiplication and Division

In this example, We write a code to swap two numbers using multiplication and division. We won’t use any third or temporary variable to swap two numbers.

Explanation

Input :  a  = 5  and b = 10

a = a * b ( 5 * 10 = 50)

b = a / b (50 / 10 = 5)

a = a/b (50 / 5 = 10)

Output : a = 10 and b = 5

Stack program in c

Conclusion

I have written and explained c program to swap two numbers without using third variable. If you still face any difficulty you can let us know through your comments.