How to swap two numbers without using a temporary variable?

30 Jun, 2022
Given two variables, x, and y, swap two variables without using a third variable. 
Method 1 (Using Arithmetic Operators) 
The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum. 
C++
C
Java
Python3
C#
PHP
Javascript
// C++ Program to swap two numbers  without// using temporary variable#include <bits/stdc++.h>using namespace std; int main(){    int x = 10, y = 5;     // Code to swap 'x' and 'y'    x = x + y; // x now becomes 15    y = x - y; // y becomes 10    x = x - y; // x becomes 5    cout << "After Swapping: x =" << x << ", y=" << y;} // This code is contributed by mohit kumar.
#include <stdio.h>int main(){    int x = 10, y = 5;     // Code to swap 'x' and 'y'    x = x + y; // x now becomes 15    y = x - y; // y becomes 10    x = x - y; // x becomes 5     printf("After Swapping: x = %d, y = %d", x, y);     return 0;}
// Java Program to swap two numbers  without// using temporary variableimport java.io.*; class Geeks {     public static void main(String a[])    {        int x = 10;        int y = 5;        x = x + y;        y = x - y;        x = x - y;        System.out.println("After swapping:"                           + " x = " + x + ", y = " + y);    }} // This code is contributed by Mayank Tyagi
x = 10y = 5 # Code to swap 'x' and 'y' # x now becomes 15x = x + y # y becomes 10y = x - y # x becomes 5x = x - yprint("After Swapping: x =", x, " y =", y) # This code is contributed# by Sumit Sudhakar
// Program to swap two numbers  without// using temporary variableusing System; class GFG {    public static void Main()    {        int x = 10;        int y = 5;         x = x + y;        y = x - y;        x = x - y;        Console.WriteLine("After swapping: x = " + x                          + ", y = " + y);    }} // This code is contributed by Sam007
<?php// PHP Program to swap two// numbers without using// temporary variable$x = 10; $y = 5; // Code to swap 'x' and 'y'$x = $x + $y; // x now becomes 15$y = $x - $y; // y becomes 10$x = $x - $y; // x becomes 5 echo "After Swapping: x = ",       $x, ", ", "y = ", $y; // This code is contributed by m_kit?>
<script> // Javascript program to swap two// numbers without using temporary// variable let x = 10, y = 5; // Code to swap 'x' and 'y' // x now becomes 15x = x + y; // y becomes 10y = x - y; // x becomes 5x = x - y; document.write("After Swapping: x =" + x + ", y=" + y); // This code is contributed by mukesh07 </script>
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
After Swapping: x =5, y=10
Time Complexity: O(1).Auxiliary Space: O(1).
Multiplication and division can also be used for swapping.  
C++
C
Java
Python3
C#
PHP
Javascript
// C++ Program to swap two numbers without using temporary// variable#include <bits/stdc++.h>using namespace std; int main(){ // NOTE - for this code to work in a generalised sense, y  // !- 0 to prevent zero division    int x = 10, y = 5;     // Code to swap 'x' and 'y'    x = x * y; // x now becomes 50    y = x / y; // y becomes 10    x = x / y; // x becomes 5    cout << "After Swapping: x =" << x << ", y=" << y;} // This code is contributed by Aditya Kumar (adityakumar129)
// C Program to swap two numbers without using temporary// variable#include <stdio.h>int main(){    int x = 10, y = 5;     // Code to swap 'x' and 'y'    x = x * y; // x now becomes 50    y = x / y; // y becomes 10    x = x / y; // x becomes 5     printf("After Swapping: x = %d, y = %d", x, y);     return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java Program to swap two numbers without using temporary// variableimport java.io.*; class GFG {    public static void main(String[] args)    {        int x = 10;        int y = 5;         // Code to swap 'x' and 'y'        x = x * y; // x now becomes 50        y = x / y; // y becomes 10        x = x / y; // x becomes 5         System.out.println("After swaping:"                           + " x = " + x + ", y = " + y);    }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 program to# swap two numbers# without using# temporary variablex = 10y = 5 # code to swap# 'x' and 'y' # x now becomes 50x = x * y # y becomes 10y = x // y; # x becomes 5x = x // y; print("After Swapping: x =",              x, " y =", y); # This code is contributed# by @ajit
// C# Program to swap two// numbers without using// temporary variableusing System; class GFG {    static public void Main()    {        int x = 10;        int y = 5;         // Code to swap 'x' and 'y'        x = x * y; // x now becomes 50        y = x / y; // y becomes 10        x = x / y; // x becomes 5         Console.WriteLine("After swaping:"                          + " x = " + x + ", y = " + y);    }} // This code is contributed by ajit.
<?php// Driver code    $x = 10;    $y = 5; // Code to swap 'x' and 'y'    $x = $x * $y; // x now becomes 50    $y = $x / $y; // y becomes 10    $x = $x / $y; // x becomes 5 echo "After Swapping: x = ", $x,                " ", "y = ", $y; // This code is contributed by m_kit?>
<script> // Javascript program to swap two numbers// without using temporary variablevar x = 10;var y = 5; // Code to swap 'x' and 'y'x = x * y; // x now becomes 50y = x / y; // y becomes 10x = x / y; // x becomes 5 document.write("After swaping:" + " x = " +               x + ", y = " + y); // This code is contributed by shikhasingrajput </script>
After Swapping: x =5, y=10
Time Complexity: O(1).Auxiliary Space: O(1).
Method 2 (Using Bitwise XOR) The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number that has all the bits as 1 wherever bits of x and y differ. For example, XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111, and XOR of 7 (0111) and 5 (0101) is (0010). 
C++
C
Java
Python3
C#
PHP
Javascript
// C++ code to swap using XOR#include <bits/stdc++.h> using namespace std; int main(){    int x = 10, y = 5;    // Code to swap 'x' (1010) and 'y' (0101)    x = x ^ y; // x now becomes 15 (1111)    y = x ^ y; // y becomes 10 (1010)    x = x ^ y; // x becomes 5 (0101)    cout << "After Swapping: x =" << x << ", y=" << y;    return 0;} // This code is contributed by mohit kumar.
// C code to swap using XOR#include <stdio.h>int main(){    int x = 10, y = 5;     // Code to swap 'x' (1010) and 'y' (0101)    x = x ^ y; // x now becomes 15 (1111)    y = x ^ y; // y becomes 10 (1010)    x = x ^ y; // x becomes 5 (0101)     printf("After Swapping: x = %d, y = %d", x, y);     return 0;}
// Java code to swap using XORimport java.io.*; public class GFG {     public static void main(String a[])    {        int x = 10;        int y = 5;         // Code to swap 'x' (1010) and 'y' (0101)        x = x ^ y; // x now becomes 15 (1111)        y = x ^ y; // y becomes 10 (1010)        x = x ^ y; // x becomes 5 (0101)         System.out.println("After swap: x = "                           + x + ", y = " + y);    }} // This code is contributed by Mayank Tyagi
# Python3 code to swap using XOR x = 10y = 5 # Code to swap 'x' and 'y'x = x ^ y; # x now becomes 15 (1111)y = x ^ y; # y becomes 10 (1010)x = x ^ y; # x becomes 5 (0101) print ("After Swapping: x = ", x, " y =", y) # This code is contributed by# Sumit Sudhakar
// C# program to swap using XORusing System; class GFG {    public static void Main()    {        int x = 10;        int y = 5;         // Code to swap 'x' (1010)        // and 'y' (0101)         // x now becomes 15 (1111)        x = x ^ y;         // y becomes 10 (1010)        y = x ^ y;         // x becomes 5 (0101)        x = x ^ y;         Console.WriteLine("After swap: x = " + x + ", y = " + y);    }} // This code is contributed by ajit
<?php // Driver Code$x = 10;$y = 5; // Code to swap 'x' (1010)// and 'y' (0101) // x now becomes 15 (1111)$x = $x ^ $y; // y becomes 10 (1010)$y = $x ^ $y; // x becomes 5 (0101)$x = $x ^ $y; echo "After Swapping: x = ", $x,                ", ", "y = ", $y; // This code is contributed by aj_36?>
<script> // Javascript code to swap using XOR let x = 10, y = 5; // Code to swap 'x' (1010) and 'y' (0101)x = x ^ y; // x now becomes 15 (1111)y = x ^ y; // y becomes 10 (1010)x = x ^ y; // x becomes 5 (0101) document.write("After Swapping: x =" +               x + ", y=" + y); // This code is contributed by Mayank Tyagi     </script>
After Swapping: x =5, y=10
Time Complexity: O(1).Auxiliary Space: O(1).
Problems with the above methods 1) The multiplication and division-based approach doesn’t work if one of the numbers is 0 as the product becomes 0 irrespective of the other number.2) Both Arithmetic solutions may cause an arithmetic overflow. If x and y are too large, addition and multiplication may go out of the integer range.3) When we use pointers to variable and make a function swap, all the above methods fail when both pointers point to the same variable. Let’s take a look at what will happen in this case if both are pointing to the same variable.
// Bitwise XOR based method x = x ^ x; // x becomes 0 x = x ^ x; // x remains 0 x = x ^ x; // x remains 0// Arithmetic based method x = x + x; // x becomes 2x x = x – x; // x becomes 0 x = x – x; // x remains 0
Let us see the following program. 
C++
C
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std;void swap(int* xp, int* yp){    *xp = *xp ^ *yp;    *yp = *xp ^ *yp;    *xp = *xp ^ *yp;} // Driver codeint main(){    int x = 10;    swap(&x, &x);    cout << "After swap(&x, &x): x = " << x;    return 0;} // This code is contributed by rathbhupendra
#include <stdio.h>void swap(int* xp, int* yp){    *xp = *xp ^ *yp;    *yp = *xp ^ *yp;    *xp = *xp ^ *yp;} int main(){    int x = 10;    swap(&x, &x);    printf("After swap(&x, &x): x = %d", x);    return 0;}
class GFG {    static void swap(int[] xp, int[] yp)    {        xp[0] = xp[0] ^ yp[0];        yp[0] = xp[0] ^ yp[0];        xp[0] = xp[0] ^ yp[0];    }     // Driver code    public static void main(String[] args)    {        int[] x = { 10 };        swap(x, x);        System.out.println("After swap(&x, &x): x = " + x[0]);    }} // This code is contributed by Aditya Kumar (adityakumar129)
def swap(xp, yp):     xp[0] = xp[0] ^ yp[0]    yp[0] = xp[0] ^ yp[0]    xp[0] = xp[0] ^ yp[0]  # Driver codex = [10]swap(x, x)print("After swap(&x, &x): x = ", x[0]) # This code is contributed by SHUBHAMSINGH10
// C# program to implement// the above approachusing System;class GFG {     static void swap(int[] xp, int[] yp)    {        xp[0] = xp[0] ^ yp[0];        yp[0] = xp[0] ^ yp[0];        xp[0] = xp[0] ^ yp[0];    }     // Driver code    static void Main()    {        int[] x = { 10 };        swap(x, x);        Console.WriteLine("After swap(&x,"                          + "&x): x = " + x[0]);    }} // This code is contributed by divyeshrabadiya07
<?phpfunction swap(&$xp, &$yp){    $xp = $xp ^ $yp;    $yp = $xp ^ $yp;    $xp = $xp ^ $yp;} // Driver Code$x = 10;swap($x, $x);print("After swap(&x, &x): x = " . $x); // This code is contributed// by chandan_jnu?>
<script>         function swap(xp,yp)    {        xp[0] = xp[0] ^ yp[0];        yp[0] = xp[0] ^ yp[0];        xp[0] = xp[0] ^ yp[0];    }         // Driver code         let x=[10];    swap(x, x);    document.write("After swap(&x, &x): x = "                           + x[0]);              // This code is contributed by unknown2108     </script>
After swap(&x, &x): x = 0
Time Complexity: O(1).Auxiliary Space: O(1).
Swapping a variable with itself may be needed in many standard algorithms. For example, see this implementation of QuickSort where we may swap a variable with itself. The above problem can be avoided by putting a condition before the swapping.
C++
C
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std;void swap(int* xp, int* yp){     // Check if the two addresses are same    if (xp == yp)        return;    *xp = *xp + *yp;    *yp = *xp - *yp;    *xp = *xp - *yp;} // Driver Codeint main(){    int x = 10;    swap(&x, &x);    cout << "After swap(&x, &x): x = " << x;    return 0;} // This code is contributed by rathbhupendra
#include <stdio.h>void swap(int* xp, int* yp){    if (xp == yp) // Check if the two addresses are same        return;    *xp = *xp + *yp;    *yp = *xp - *yp;    *xp = *xp - *yp;}int main(){    int x = 10;    swap(&x, &x);    printf("After swap(&x, &x): x = %d", x);    return 0;}
// Java program of above approachclass GFG {     static void swap(int xp, int yp)    {        if (xp == yp) // Check if the two addresses are same            return;        xp = xp + yp;        yp = xp - yp;        xp = xp - yp;    }     // Driver code    public static void main(String[] args)    {        int x = 10;        swap(x, x);        System.out.println("After swap(&x, &x): x = " + x);    }} // This code is Contributed by Code_Mech.
# Python3 program of above approachdef swap(xp, yp):     # Check if the two addresses are same    if (xp[0] == yp[0]):        return    xp[0] = xp[0] + yp[0]    yp[0] = xp[0] - yp[0]    xp[0] = xp[0] - yp[0]  # Driver Codex = [10]swap(x, x)print("After swap(&x, &x): x = ", x[0]) # This code is contributed by SHUBHAMSINGH10
// C# program of above approachusing System;class GFG {     static void swap(int xp, int yp)    {        if (xp == yp) // Check if the two addresses are same            return;        xp = xp + yp;        yp = xp - yp;        xp = xp - yp;    }     // Driver code    public static void Main()    {        int x = 10;        swap(x, x);        Console.WriteLine("After swap(&x, &x): x = " + x);    }} // This code is Contributed by Code_Mech.
<?phpfunction swap($xp, $yp){    // Check if the two addresses    // are same    if ($xp == $yp)        return;    $xp = $xp + $yp;    $yp = $xp - $yp;    $xp = $xp - $yp;} // Driver Code$x = 10;swap($x, $x);echo("After swap(&x, &x): x = " . $x);return 0; // This code is contributed// by Code_Mech.
<script>   function swap(xp, yp){      // Check if the two addresses are same    if (xp == yp)        return;    xp[0] = xp[0] + yp[0];    yp[0] = xp[0] - yp[0];    xp[0]= xp[0] - yp[0];}  // Driver Code     x = 10;    swap(x, x);    document.write("After swap(&x , &x) : x = " + x);//This code is contributed by simranarora5sos</script>
After swap(&x, &x): x = 10
Time Complexity: O(1).Auxiliary Space: O(1).
Method 3 (A mixture of bitwise operators and arithmetic operators) The idea is the same as discussed in Method 1 but uses Bitwise addition and subtraction for swapping. 
Below is the implementation of the above approach. 
C++
C
Java
Python3
C#
Javascript
PHP
// C++ program to swap two numbers#include <bits/stdc++.h>using namespace std; // Function to swap the numbers.void swap(int& a, int& b){    // same as a = a + b    a = (a & b) + (a | b);    // same as b = a - b    b = a + (~b) + 1;    // same as a = a - b    a = a + (~b) + 1;} // Driver Codeint main(){    int a = 5, b = 10;    // Function Call    swap(a, b);    cout << "After swapping: a = " << a << ", b = " << b;    return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C++ program to swap two numbers#include <stdio.h> // Function to swap the numbers.void swap(int a, int b){    // same as a = a + b    a = (a & b) + (a | b);    // same as b = a - b    b = a + (~b) + 1;    // same as a = a - b    a = a + (~b) + 1;      printf("After swapping: a = %d , b = %d ",a,b);} // Driver Codeint main(){    int a = 5, b = 10;    // Function Call    swap(a, b);    return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to swap two numbersimport java.io.*; class GFG {    public static void swap(int a, int b)    {        // same as a = a + b        a = (a & b) + (a | b);        // same as b = a - b        b = a + (~b) + 1;        // same as a = a - b        a = a + (~b) + 1;        System.out.print("After swapping: a = " + a + ", b = " + b);    }    public static void main(String[] args)    {        int a = 5, b = 10;        // Function Call        swap(a, b);    }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 program to swap two numbers # Function to swap the numbers  def swap(a, b):     # Same as a = a + b    a = (a & b) + (a | b)     # Same as b = a - b    b = a + (~b) + 1     # Same as a = a - b    a = a + (~b) + 1     print("After Swapping: a = ", a, ", b = ", b)  # Driver codea = 5b = 10 # Function callswap(a, b) # This code is contributed by bunnyram19
// C# program to swap two numbersusing System;class GFG {     static void swap(int a, int b)    {        // same as a = a + b        a = (a & b) + (a | b);         // same as b = a - b        b = a + (~b) + 1;         // same as a = a - b        a = a + (~b) + 1;         Console.Write("After swapping: a = " + a                      + ", b = " + b);    }     static void Main()    {        int a = 5, b = 10;         // Function Call        swap(a, b);    }} // This code is contributed by divyesh072019
<script>    // Javascript program to swap two numbers         function swap(a, b)    {        // same as a = a + b        a = (a & b) + (a | b);          // same as b = a - b        b = a + (~b) + 1;          // same as a = a - b        a = a + (~b) + 1;          document.write("After swapping: a = " + a + ", b = " + b);    }         let a = 5, b = 10;      // Function Call    swap(a, b);         // This code is contributed by suresh07.</script>
<?php  // Driver Code$a = 5;$b = 10; echo("Before swap(a and b) " . $a . "and". $b."<br>");// same as a = a + b    $a = ($a & $b) + ($a | $b);      // same as b = a - b    $b = $a + (~$b) + 1;      // same as a = a - b    $a = $a + (~$b) + 1; echo("After swap(a and b) " . $a. "and". $b);return 0; ?>
After swapping: a = 10, b = 5
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 4 (One Line Expression) 
We can write only one line to swap two numbers.
x = x ^ y ^ (y = x);
x = x + y – (y = x);
x = (x * y) / (y = x);
x , y = y, x (In Python)
C++
C
Java
Python3
C#
Javascript
#include <iostream>using namespace std;  int main(){    int x = 10, y = 5;    x = (x * y) / (y = x);    cout << x << " " << y;    return 0;} // This code is contributed by isha307
#include <stdio.h> int main() {    int x = 10, y = 5;    x = (x * y) / (y = x);    printf("After Swapping: x = %d, y = %d", x, y);    return 0;} // This code is contributed by isha307
/*package whatever //do not write package name here */import java.io.*; class GFG {    public static void main(String[] args)    {        int x = 10;        int y = 5;        x = (x * y) / (y = x);        System.out.println("After swaping:"                           + " x = " + x + ", y = " + y);    }} // This code is contributed by isha307
# Python3 program to swap two numbers # Function to swap the numbersdef swap(x, y):  x , y = y, x  print("After Swapping: x = ", x, ", y = ", y)   # Driver codex = 10y = 5  # Function callswap(x, y)  # This code is contributed by kothavvsaakash
// C# program to swap two numbers using System; public class GFG{    static public void Main ()    {        int x = 10;        int y = 5;        x = (x * y) / (y = x);        Console.Write("After swaping:"  + " x = " + x + ", y = " + y);    }} // This code is contributed by kothavvsaakash
<script> // Javascript program to swap two// numbers without using temporary// variable let x = 10, y = 5; // Code to swap 'x' and 'y'x = (x * y)/(x = y); document.write("After Swapping: x =" + x + ", y=" + y); // This code is contributed by Abhijeet Kumar(abhijeet19403) </script>
5 10
Time Complexity: O(1)
Auxiliary Space: O(1)
To know more about swapping two variables in one line, click here.
Please comment if you find anything incorrect, or if you want to share more information about the topic discussed above 
jit_t
mohit kumar 29
Chandan_Kumar
Code_Mech
ujjwalmittal
rathbhupendra
SHUBHAMSINGH10
Rajput-Ji
yashbeersingh42
divyeshrabadiya07
bunnyram19
divyesh072019
mayanktyagi1709
mukesh07
shikhasingrajput
suresh07
unknown2108
simranarora5sos
himanshu6003
akshitsaxenaa09
saurabh1990aror
adityakumar129
anandkumarshivam2266
chandan309kr
isha307
kothavvsaakash
abhijeet19403
Bitwise-XOR
Swap-Program
Bit Magic
Mathematical
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.