Site icon Study Algorithms

Different ways to swap 2 numbers.

Question: Write a program to swap 2 numbers?

Input: a = 4, b = 19
Output: a = 19, b = 4

We will try to discuss the different ways to swap 2 numbers. To understand how swapping works, please visit this post.

Method 1 : Using a temporary variable

int a = 15;
int b = 9;

int temp = a; // temp is now 15
a = b; // a is now 9
b = a; // b is now 15

//swapping complete

Method 2 : Without a temporary variable

int a = 15;
int b = 9;

a = a + b; // a is now 24
b = a - b; // b is now (24 - 9) = 15
a = a - b; // a is now (24 - 15) = 9

//swapping complete

Method 3: Using multiplication and division

int a = 15;
int b = 9;

a = a * b; // a is now 135
b = a/b; // b is now (135/9) = 15
a = a/b; // a is now (135/15) = 9

//swapping complete

IMP: It is necessary here that numbers should be non-zero

Method 4: Using Bitwise XOR (^)

int a = 15; // a is 15(1111)
int b = 9; // b is 9 (1001)

a = a ^ b; // a is now (1111 ^ 1001) = 0110
b = a ^ b; // b is now (0110 ^ 1001) = 1111 (15)
a = a ^ b; // a is now (0110 ^ 1111) = 1001 (9)

//swapping complete

Method 5: Swapping in single line using arithmetic operator

int a = 15;
int b = 9;

b = a + b - (a = b);

//swapping complete

Method 6: Swapping in single line using Bitwise XOR

int a = 15;
int b = 9;

a ^= b ^= a ^= b;

//swapping complete
Exit mobile version