Home Misc Different ways to swap 2 numbers.

Different ways to swap 2 numbers.

by nikoo28
3 comments

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

You may also like

3 comments

Shantun Rubal February 12, 2015 - 11:24

method 4 is very tricky with precedence ,order of evaluation and associativity

nikoo28 February 21, 2015 - 01:13

Why do you think Method 4 is tricky?

Shantun Rubal February 22, 2015 - 23:53

sorry ,I meant method 5

Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More