Coronavirus Outbreak - 2020, 100+ dead in China, effected several countries, Checkout WHO Advices to stay safe

Kotlin Program to Swap Two Numbers With Example

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

In this post, we will go through kotlin program to swap two numbers with example. There are different ways to swap two numbers in kotlin. Here, we will cover some of them –

  1. Using Third Variable
  2. Without Using Third Variable
  3. Using Scope Function(s)-

1. Kotlin Program to Swap Two Numbers Using Third Variable

Program to swap two numbers in kotlin –

import java.util.*

fun main(args: Array<String>) {

    val read = Scanner(System.`in`)

    println("Enter first integer number:")
    var a = read.nextInt()

    println("Enter second integer number:")
    var b = read.nextInt()

    println("Before Swap: a = $a, b: $b")

    // Swapping variables using third variable
    val c = b
    b = a
    a = c

    println("After Swap: a = $a, b: $b")
}

When you run the program, output will be –

Enter first integer number:
100
Enter second integer number:
200
Before Swap: a = 100, b: 200
After Swap: a = 200, b: 100

Explanation –

At first, we have accepted two inputs from user using console. Then, we stored it in a and b.

Logic to swap two numbers –

    val c = b
    b = a
    a = c

Here, we defined another variable c.

At first, we stored value of b in c.
Then, we assigned value of a to b.
Then, value of c to a.

Thus, variable has been swapped.

Let’s take some value to make it more clear.

Let’s assume
value of a = 100, value of b = 200

Now, define another variable c. Then,
store value of b in c. Now, c = 200.
Then, assign value of a to b. So, b = 100.
Now, assign value of c (which is 200) to a. So, a = 200.

Thus,

Before swap:
a = 100, b = 200

After swap:
a = 200, b = 100

2. Kotlin Program to Swap Two Numbers Without Using Third Variable

Program to swap two numbers in kotlin without using third variable –

import java.util.*

fun main(args: Array<String>) {

    val read = Scanner(System.`in`)

    println("Enter first integer number:")
    var a = read.nextInt()

    println("Enter second integer number:")
    var b = read.nextInt()


    println("Before Swap: a = $a, b: $b")

    // Swapping variables without using third variable
    a -= b
    b += a
    a = b - a

    println("After Swap: a = $a, b: $b")
}

When you run the program, output will be –

Enter first integer number:
100
Enter second integer number:
200
Before Swap: a = 100, b: 200
After Swap: a = 200, b: 100

Explanation –

At first, we have accepted two inputs from user using console. Then, we stored it in a and b.
Logic to swap two number –

    a -= b
    b += a
    a = b - a

Let’s take an example to make it more clear.

Assume we have –
a = 100,
b = 200

a -= b means a = a – b. So, a = (100 – 200) => Now, a = -100.
b += a means b = b + a. So, b = (200 + (-100) => b = (200 – 100) => Now, b = 100
a = b – a => a = 100 – (-100) => a = (100 + 100) => Now, a = 200

Thus,
Before swap:
a = 100, b = 200

After swap:
a = 200, b = 100

Is there any other way to swap two variables without using third variable ?

Yes! There are many ways –

    a = a ^ b
    b = a ^ b
    a = a ^ b

If and b are not 0.

    a = a * b
    b = a / b
    a = a / b 

Let us know in the comment section if you also know any.

3.1 Swap two variable using run function in Kotlin

We can use run function in kotlin to swap two variables (Here, it’s Integer) in kotlin.

Program to swap numbers –

import java.util.*

fun main(args: Array<String>) {

    val read = Scanner(System.`in`)

    println("Enter first integer number:")
    var a = read.nextInt()

    println("Enter second integer number:")
    var b = read.nextInt()


    println("Before Swap: a = $a, b: $b")

    // Logic to swap variables using run block
    run {
        val temp = a
        a = b
        b = temp
    }

    println("After Swap: a = $a, b: $b")
}

When you run the program, output will be –

Enter first integer number:
100
Enter second integer number:
200
Before Swap: first = 100, second: 200
After Swap: first = 200, second: 100

Explanation –

Code for this work is very clear. We have defined a variable temp in run block. Note that scope for this variable is only within run block. Rest of the part is very clear. You can just take example and check it.

3.2 Swap two variable using also function in Kotlin

Program to swap two variables –

import java.util.*

fun main(args: Array<String>) {

    val read = Scanner(System.`in`)

    println("Enter first integer number:")
    var a = read.nextInt()

    println("Enter second integer number:")
    var b = read.nextInt()


    println("Before Swap: a = $a, b: $b")

    // Logic to swap variables using also method
    // This is similar to a=b and b=a, executing both simultaneously.
    a = b.also {
        b = a
    }

    println("After Swap: a = $a, b: $b")
}

When you run the program, output will be –

Enter first integer number:
100
Enter second integer number:
200
Before Swap: a = 100, b: 200
After Swap: a = 200, b: 100

Explanation –

Logic to swap function is –

    a = b.also {
        b = a
    }

This syntax is shorthand for a = b.also({ b = a }). also method is being called on b with argument of lambda {b = a}.

also calls it’s parameter, then, return this.

So,{b = a} is called first. b is assigned with a.
Then, this is returned.

Now, result of also function is assigned to a, which is initial b.

Let’s take an example,

Let’s assume
a = 100, b = 200

At first,{b = a} is executed. So, new value of b is 100. But, return value of also method is initial value of b, which is 200. So, 200 will be assigned to a.

Thus,
a = 200, b = 100

3.3 Swap two variable using with function in Kotlin

Now, we will use with function in Kotlin to swap two variables in kotlin.

Check below program –

import java.util.*

// Solution 5 - Scope Function - with block
fun main(args: Array<String>) {

    val read = Scanner(System.`in`)

    println("Enter first integer number:")
    var a = read.nextInt()

    println("Enter second integer number:")
    var b = read.nextInt()


    println("Before Swap: a = $a, b: $b")

    // Swapping variables using with method
    // Here, with contains reference to a. Then, it is passed to b using this keyword.
    with(a) {
        a = b
        b = this
    }

    println("After Swap: a = $a, b: $b")
}

When you run the program, output will be –

Enter first integer number:
100
Enter second integer number:
200
Before Swap: a = 100, b: 200
After Swap: a = 200, b: 100

Explanation –

We have used with function in this example to swap two variable. You can read with function in Kotlin as –

“with this object, do the following.”

Remaining things are self explanatory. Just take example and check it.

3.4 Swap two variable using apply function in Kotlin

Now, we will use apply function in Kotlin to swap two variables in Kotlin.

Sourcecode –

import java.util.*

// Solution 6 - Scope Function - apply block
fun main(args: Array<String>) {

    val read = Scanner(System.`in`)

    println("Enter first integer number:")
    var a = read.nextInt()

    println("Enter second integer number:")
    var b = read.nextInt()


    println("Before Swap: a = $a, b: $b")

    // Swapping variables without using third variable
    a = b.apply {
        b = a
    }

    println("After Swap: a = $a, b: $b")
}

When you run the program, output will be –

Enter first integer number:
100
Enter second integer number:
200
Before Swap: a = 100, b: 200
After Swap: a = 200, b: 100

Explanation –

Here, we are using apply function in kotlin to swap two variables. It works same as also function. But, there is some difference. If you want to perform some operation on the variables inside lambda, then, go for also. Otherwise, choose apply.

Thus, we have seen how to swap two numbers in kotlin. Similarly, you do swap other variables in kotlin. We have seen how to swap variable using third variable, without using third variable. Then, we have seen how to swap variable using scope function in kotlin – run, also, apply, with etc.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners

Leave a Reply