VOOZH about

URL: https://www.geeksforgeeks.org/dsa/swap-two-numbers/

⇱ Swap Two Numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Swap Two Numbers

Last Updated : 19 Apr, 2026

Given two numbers a and b, the task is to swap them.

Examples:

Input: a = 2, b = 3
Output: 3 2

Input: a = 20, b = 0
Output: 0 20

Input: a = 10, b = 10
Output: 10 10

Using a Third Variable

The idea is to use a third variable, say temp to store the original value of one of the variables during the swap.

Let us understand with an example, a = 10, b = 20

  • Store the value of a in temp, temp = 10
  • Assign the value of b to a, a = 20
  • Assign the value of temp to b, b = 10

Output
20 10

Without a Third Variable – Using Arithmetic Operations

The idea is to store sum in a variable so that we can get both values without third variable.

Let us understand with an example, a = 10, b = 20

  • Store the sum of a and b in a, a = a + b = 10 + 20 = 30
  • Get the original value of a and store it in b, b = a - b = 30 - 20 = 10
  • Get the original value of b and store it in a, a = a - b = 30 - 10 = 20
  • Final result: a = 20, b = 10

Output
20 10

Without a Third Variable – Using Bitwise XOR

The idea is to use the properties of XOR to swap the two variables.

Let us understand with an example, a = 10, b = 20

  • Store the XOR of a and b in a, a = a ^ b = 10 ^ 20 = 30
  • Get the original value of a and store it in b, b = a ^ b = 30 ^ 20 = 10
  • Get the original value of b and store it in a, a = a ^ b = 30 ^ 10 = 20
  • Final result: a = 20, b = 10

Output
20 10

Using Built-in Swap Methods

We can also swap using built-in functionalities like swap() function in C++, tuple unpacking in Python, destructuring assignment in JavaScript.


Output
20 10
Comment
Article Tags: