cover-img

6 Techniques by which you can swap 2 numbers.

in this show i have shared the 6 ways by which you can swap 2 variables.

19 December, 2022

1

1

0

(1) using third temporary variable (everyone knows!!)

temp = a
a = b
b = temp

(2) using + and - operators

b = a + b
a = b - a
b = b - a

(3) using bitwise operators

a = a ^ b
b = b ^ a
a = a ^ b

(4) using * and / operators

handle the number = 0 case here.
b = a * b
a = b / a
b = b / a

(5) using in-built swap() function

swap(a , b)

(6) one liner way

b = a - b + (a = b)

Do Like and share if it helped you😊.

1

1

0

Hiren Timbadiya
Programmer & Developer & Learner

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2025. Showcase Creators Inc. All rights reserved.