Kotlin Program to Swap Two Numbers

Kotlin Server Side ProgrammingProgramming

In this article, we will understand how to how to swap two numbers in Kotlin. This is done using a temporary variable.

Below is a demonstration of the same

Suppose our input is

val1 : 45
val2 : 60

The desired output would be

val1 : 60
val2 : 45

Algorithm

  • Step 1 − Start

  • Step 2 − Declare three integers: val1, val2 and tempVal

  • Step 3 − Define the values

  • Step 4 − Assign val1 to temporary variable

  • Step 5 − Assign val2 to val1

  • Step 6 − Assign temporary tempVal variable to val2

  • Step 7 − Display the two values

  • Step 8 − Stop

Example 1

In this example, we will swap two numbers using a temporary variable −

fun main() { var val1 = 45 var val2 = 60 println("The first value is defined as: $val1") println("The second value is defined as: $val2") val tempVal = val1 val1 = val2 val2 = tempVal println("
After swapping"
) println("The first value is = $val1") println("The second value is = $val2") }

Output

The first value is defined as: 45
The second value is defined as: 60

After swapping
The first value is = 60
The second value is = 45

Example 2

In this example, we will swap two numbers without using a temporary variable −

fun main() { var val1 = 25 var val2 = 55 println("The first value is defined as: $val1") println("The second value is defined as: $val2") val1 = val1 + val2 val2 = val1 - val2 val1 = val1 - val2 println("
After swapping"
) println("
The first value is = $val1"
) println("The second value is = $val2") }

Output

The first value is defined as: 25
The second value is defined as: 55

After swapping
The first value is = 55
The second value is = 25

Example 3

We can also swap two numbers using the following code

fun main() { var val1 = 20 var val2 = 10 println("The first value is defined as: $val1") println("The second value is defined as: $val2") val1 = val1 - val2 val2 = val1 + val2 val1 = val2 - val1 println("
After swapping"
) println("
The first value is = $val1"
) println("The second value is = $val2") }

Output

The first value is defined as: 20
The second value is defined as: 10

After swapping

The first value is = 10
The second value is = 20
raja
Updated on 13-Oct-2022 12:26:30

Advertisements