Kotlin Program to Swap Two Numbers Without Using Temporary Variable

In this post, we will learn how to write a Kotlin Program to Swap two numbers without using temporary variable.

Kotlin Program to Swap two numbers without using temporary variable

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")

    number1 = number1 - number2
    number2 = number1 + number2
    number1 = number2 - number1

    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