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.

Programming questions on linked list

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.

1 2 3 4 | //Steps to swap two numbers without using third variable a = a + b b = a - b a = a - b; |

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

1 2 3 | a = a + b = 3 + 4 = 7 // 7 is assigned b = a - b = 7 - 4 = 3 // Now the value of b is 3 a = a - b = 7 - 3 = 4 |

Output – a = 4 and b = 3.

## C Program to Swap Two Numbers without Using Third Variable

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <stdio.h> int main() { /* Declare two variables. */ int a, b; /* Take user input. */ printf("Enter two numbers a and b "); scanf("%d%d",&a ,&b); printf("\n Before swapping a = %d and b =%d", a, b); /* Logic to swap two numbers. */ a = a + b; b = a - b; a = a - b; printf("\n After swapping a = %d b = %d",a ,b); return 0; } |

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include int main(void) { /* Declare two variables. */ int a, b; /* Take user input. */ printf("Enter two numbers a and b \n"); scanf("%d %d",&a ,&b); printf("\n Before swapping a = %d and b =%d", a, b); a = a * b; b = a / b; a = a / b; printf("\n After swapping a = %d and b =%d", a, b); return 0; } |

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

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.