We can use a temporary variable to store the value of one of the variables before assigning it the value of second variable. Following is the algorithm to swap two variables a
& b
using temp
as the temporary variable :
- Assign value of
a
totemp
i.e.temp = a
- Assign value of
b
toa
i.e.a = b
- Finally, assign value of
temp
tob
i.e.b = temp
Implementation
Implementation
fun main() {
var a = 2; var b = 3
println("Before swapping: a=$a, b=$b")
// Swap
val temp = a
a = b
b = temp
println("After swapping: a=$a, b=$b")
}
/* Output :
Before swapping: a=2, b=3
After swapping: a=3, b=2
*/