### How Many Different Ways Of Swapping Two Numbers

Well the first thing comes in our mind when we are a beginner is how many ways we can swap two variable but honestly, there are multiple ways of doing it. Generally, for swapping two variables we use a temporary third variable, but there are various other ways where we do not even require the help of any third variable.

1.#method 3

2.a=50

3.b=5

4.a = a * b

5.b = a // b

6.a = a // b

7.print(a,b)

1.#method 4

2.a=50

3.b=5

4.a = a ^ b

5.b = a ^ b

6.a = a ^ b

7.print(a,b)
1.# method 5

2.a=50

3.b=5

4.a,b=b,a

5.print(a,b)

So let's see

**Method 1:- The simple method using a third variable**

1.# method 1

2.a=50

3.b=5

4.temp=a

5.a=b

5.b=temp

6.print(a,b)

2.a=50

3.b=5

4.temp=a

5.a=b

5.b=temp

6.print(a,b)

**Method 2:- Using arithmetic operators + and -**

1.#method 2

2.a=50

3.b=5

4.a = a + b

5.b = a - b

6.a = a - b

7.print(a,b)

2.a=50

3.b=5

4.a = a + b

5.b = a - b

6.a = a - b

7.print(a,b)

**Method 3:- Using arithmetic operators * and /**

2.a=50

3.b=5

4.a = a * b

5.b = a // b

6.a = a // b

7.print(a,b)

**Method 4:- Using bitwise XOR operator ^**

1.#method 4

2.a=50

3.b=5

4.a = a ^ b

5.b = a ^ b

6.a = a ^ b

7.print(a,b)

**It can also be written in a more compact manner like this:**

`1.a=50 `

2.b=5

3.a ^= b

4.b ^= a

5.a ^= b

6.print(a,b)

Method 5:- The simple method using two variables

2.a=50

3.b=5

4.a,b=b,a

5.print(a,b)

## Comments

## Post a Comment

Please give us your valuable feedback