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
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
Hope this was helpful😊
Top comments (0)