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:


Enter two numbers.


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.

Program: Swap two numbers without third variable:

Swap without third variable Program Output:

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


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.


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

You may also like...

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 […]

Leave a Reply