# Swap Without Third Variable or Temporary Variable

## Program Description:

Write a C program to swap two numbers without using any third or temporary variable. We are not allowed to use the extra variable. So lets write a program to swap without third variable.

### Example 1:

Input:

Enter two numbers.

Output:

Output after swapping the numbers

## Swap Two Numbers without using Temporary or Extra Variable:

In this method, We are going to use a small math trick to swap the numbers. Here is the algorithm.

## Algorithm to Swap without Third variable:

1. Letâ€™s take two variables 'a'and 'b' and We are going to swap these two variables.
2. First of all, We are going to multiply both variables 'a'and variable 'b'.
3. And The result would be 'ab'. We will use this product as the Numerator for our division.
4. Then we are going to use (a=b) Operation. This means we are copying the value of â€˜bâ€™ into the variable â€˜aâ€™.
5. Now the variable â€˜aâ€™ have the desired value of â€˜bâ€™.
6. Then in the denominator, We got the final value as â€˜bâ€™.
7. Now we will divide our numerator â€˜abâ€™ with the denominator â€˜bâ€™, The result would be the value of â€˜aâ€™
8. Then we are assigning this result value i.e â€˜aâ€™ to variable â€˜bâ€™. Now the variable â€˜bâ€™ have the desired value of the variable 'a'
9. Finally, Two numbers are swapped without using any extra variable.

So by using above algorithm, We swapped the two integers without using temporary variable. And it is a very useful and elegant method to swap numbers.

There are other ways to swap the numbers, We have covered all those methods in the following article. Program to Swap Two Numbers | Swapping Program in C language â€“ SillyCodes

Letâ€™s write the code for the above logic.

## Swap without third variable Program Output:

We are using GCC compiler to compile and run the program.

## Conclusion:

In this article, We have discussed about the swapping the numbers without using the third or extra variable. This method is one way to swap the numbers but there are other methods as well.

Venkatesh

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

### 3 Responses

1. [â€¦] our previous articles, We have discussed different ways to swap the two numbers. In this article, We are going to discuss the swap two numbers without using third variable here we [â€¦]

2. [â€¦] We are using a temporary variable temp to swap the elements. We can also use other methods like Swapping without using temporary variables [â€¦]

3. [â€¦] We use the temporary variable to swap the numbers. If you want to swap numbers without using a temporary variable. Please check this article â€“ Swap two integers without using third variable [â€¦]