DEV Community

loading...

Swapping two numbers using arithmetic operators

rakshithholla profile image Rakshith holla ・1 min read

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😊

Discussion (0)

pic
Editor guide