Kotlin Program to Swap Two Numbers

Here you will learn different ways to swap values of two numbers.

Let’s say our two numbers are a=10 and b=20. So after swapping the values should be a=20 and b=10.

Now we will see how we can implement this in kotlin. We can do this in two ways, with and without using a temp variable.

Method 1: Swap Two Numbers Using Temporary Variable

fun main(args: Array<String>) {

    var a = 10
    var b = 20

    println("Values before swapping\na=$a b=$b")

    var temp = a
    a = b
    b = temp
    
    println("\nValues after swapping\na=$a \nb=$b")
}

Output:

Values before swapping
a=10 b=20

Values after swapping
a=20 
b=10

Method 2: Swap Two Numbers Without Temporary Variable

fun main(args: Array<String>) {

    var a = 10
    var b = 20

    println("Values before swapping\na=$a b=$b")

    a = a+b
    b = a-b
    a = a-b
    
    println("\nValues after swapping\na=$a \nb=$b")
}

Let’s understand how it works. After a = a+b, a holds 30. Then after b = a-b, b holds 10. And finally, after a = a-b, a holds 20.

Comment down below if you have any queries regarding the swapping of two numbers in kotlin.

Leave a Comment

Your email address will not be published. Required fields are marked *