How to Swap Two Numbers Without Using Temporary Variable or Arithmetic Operators?

You have done swapping
of two numbers using temporary variable or by using arithmetic operators. It
can be done in following way.
Lets take two numbers
a=5 and b=7.
Using Temporary Variable

temp=a;            //temp becomes 5
a=b;                 //a becomes 7
b=temp;            //b becomes 5

Using Arithmetic Operators
a=a+b;              //a becomes 12
b=a-b;              //b becomes 5
a=a-b;               //a becomes 7
a=a*b;              //a becomes 35
b=a/b;              //b becomes 5
a=a/b;               //a becomes 7

In this article I am
sharing another method, may be you are already familiar with it. Swapping of
two numbers can also be done by using bitwise XOR operator i.e. ^. The XOR of two numbers a and b returns a number which has all the bits as 1 wherever bits of a and b differ. If bits are same then resultant bit will be 0.
For example binary of 5
is 0101 and 7 is 0111. If you do XOR of 5 and 7 then result will be 0010. A c program
is given below that uses this concept to swap values of two numbers.

#include <stdio.h>

int main()
a=a^b;  // a becomes 2 (0010)
b=a^b;  // b becomes 5 (0101)
a=a^b;  // a becomes 7 (0111)
printf(“After Swapping: a=%d,b=%d”,a,b);
  return 0;

How to Swap Two Numbers Without Using Temporary Variable or Arithmetic Operators?
If you have any doubts
or know any other method to swap values of two numbers then mention it in
comment section.
Happy Coding!! 🙂 🙂

9 thoughts on “How to Swap Two Numbers Without Using Temporary Variable or Arithmetic Operators?

  1. Cees Kaas

    I have a small concern about the arithmetic swap being the integer overflow that happens when you get close to half the max values or in case of the multiplication the square root of int.MaxValue.

    And besides that this is only usefull in cases where memory might be tight because it isn't faster (at least not in C# .net 4.5)

  2. Helge Selstø

    Nice code 🙂 I wanted to find uot which of the codes was the faster to execute, swapping or not swapping. I dont have good control of the PCs way of prosess things, but I put this loop "for (long i=1;i<10000000;i++)" around the swap and not swap-code and the swapping code was sligtly faster… I tried only 5-6 times on each but…

  3. Cho Yiu Ng

    It is fine to use XOR to swap but addition, subtraction and multiplication are not good options because of the possibility of overflow.

    1. Neeraj Mishra

      Yes your are right, XOR is good option. Thanks for your nice comment. 🙂

  4. cool buddy

    enter the values a and b bout when you print the values just change the result like this
    cout<<"Enter a and b";
    and then
    will it work in all cases?


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.