Kotlin Program to Swap Two Numbers

In this post, we will learn how to write a Kotlin program to swap two numbers using temporary variable.

Kotlin Program to Swap Two Numbers

package com.kotlin.programs

fun main(args: Array < String > ) {

    var number1 = 10
    var number2 = 20

    println("--Before swap--")
    println("First number = $number1")
    println("Second number = $number2")

    // Value of first is assigned to temporary
    val temporary = number1

    // Value of second is assigned to first
    number1 = number2

    // Value of temporary (which contains the initial value of first) is assigned to second
    number2 = temporary

    println("--After swap--")
    println("First number = $number1")
    println("Second number = $number2")
}
Output:
--Before swap--
First number = 10
Second number = 20
--After swap--
First number = 20
Second number = 10


Comments