Kotlin Program to swap two numbers without using third variable


In this program, You will learn how to swap two numbers without using third variable in Kotlin.


10 20 => 20 10

Example: How to swap two numbers without using third variable in Kotlin.

import java.util.Scanner

fun main(args: Array<String>) {

    var x: Int
    var y: Int

    var sc = Scanner(System.`in`)

    print("Enter two numbers:")
    x = sc.nextInt()
    y = sc.nextInt()

    x = x + y
    y = x - y
    x = x - y

    println("After swap x is:$x")
    println("After Swap y is:$y")
}

Output:

Enter two numbers:10 20
After swap x is:20
After Swap y is:10