DEV Community

Rakshith holla
Rakshith holla

Posted on

2 2

Swapping two numbers using arithmetic operators

We can perform swapping of two numbers without using temp variable and just by using arithmetic operators.

Operators used are +, - or *, /

First, let us perform the swap using +, - operators,

let a = 5;
let b = 10;

//swap operations
a = a + b; //a = 15
b = a - b; //b = 5
a = a - b; //a = 10

//swap complete

console.log(a); //a is now 10
console.log(b); //b is now 5
Enter fullscreen mode Exit fullscreen mode

Now, let us perform the swap using *, / operators,

let a = 7;
let b = 5;

//swap operations
a = a * b; //a = 35
b = a / b; //b = 7
a = a / b; //a = 5

//swap complete

console.log(a); //a is now 5
console.log(b); //b is now 7
Enter fullscreen mode Exit fullscreen mode

Hope this was helpful😊

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay