Kotlin – Swap Two Numbers

How to Swap Two Numbers in Kotlin

In Kotlin, you can swap the values of two variables using a temporary variable or without using an extra variable. This tutorial will guide you through both methods.

Method 1: Using a Temporary Variable

Step 1: Define Variables

Start by defining two variables that you want to swap.

``````var num1 = 5
var num2 = 10``````

Step 2: Swap Numbers Using Temporary Variable

Create a temporary variable to store the value of one variable, then assign the value of the second variable to the first variable, and finally assign the value of the temporary variable to the second variable.

``````val temp = num1
num1 = num2
num2 = temp``````

Step 3: Print the Swapped Numbers

Print the swapped values to verify the result.

``println("After swapping, num1 = \$num1 and num2 = \$num2")``

Complete Kotlin Program

The following is the complete Kotlin program to swap two numbers using both methods.

Kotlin Program

``````fun main() {
// Method 1: Using Temporary Variable
var num1 = 5
var num2 = 10
val temp = num1
num1 = num2
num2 = temp
println("After swapping, num1 = \$num1 and num2 = \$num2")
}``````

Output

``After swapping, num1 = 10 and num2 = 5``

Method 2: Without Using a Temporary Variable

Step 1: Define Variables

Start by defining two variables that you want to swap.

``````var a = 5
var b = 10``````

Step 2: Swap Numbers Without Using Temporary Variable

You can swap two numbers without using a temporary variable by using arithmetic operations.

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

Step 3: Print the Swapped Numbers

Print the swapped values to verify the result.

``println("After swapping, a = \$a and b = \$b")``

Complete Kotlin Program

The following is the complete Kotlin program to swap two numbers using both methods.

Kotlin Program

``````fun main() {
// Method 2: Without Using Temporary Variable
var a = 5
var b = 10
a = a + b
b = a - b
a = a - b
println("After swapping, a = \$a and b = \$b")
}``````

Output

``After swapping, a = 10 and b = 5``

Summary

By following these methods, you can easily swap the values of two variables in Kotlin.