Home »
Scala »
Scala Programs
Scala program to swap two numbers
Scala | Swapping two numbers: Here, we are going to learn how to swap two numbers in Scala programming language?
Submitted by Shivang Yadav, on April 21, 2020 [Last updated : March 09, 2023]
Scala – Swap Two Numbers
Given two numbers, we have to swap them. There are two ways to swap two numbers. They are,
- Using third variable
- Without using third variable
Example:
Input:
a = 10
b = 20
Output:
a = 20
b = 10
1) Swapping two numbers using third variable
To swap two values, there is a simple approach is using a temporary variable that stores the element for swapping.
Algorithm
Let, variable a contains first value, variable b contains second value and temp is the temporary variable.
Step 1: temp = a
Step 2: a = b
Step 3: b = temp
Scala code to swap two number using third variable
object myObject {
def main(args: Array[String]): Unit = {
var a = 10
var b = 20
println("Values before swapping:\t a= " + a + ", b= " + b)
// swapping
var temp = a
a = b
b = temp
println("Values after swapping:\t a= " + a + ", b= " + b)
}
}
Output
Values before swapping: a= 10, b= 20
Values after swapping: a= 20, b= 10
2) Swapping two numbers without using third variable
We can also swap two numbers without using the third variable. This method saves computation space hence is more effective.
Let, variable a contains first value, variable b contains second value.
Step 1: a = a + b
Step 2: a = a - b
Step 3: b = a - b
Scala code to swap two number without using third variable
object myObject {
def main(args: Array[String]): Unit = {
var a = 10
var b = 20
println("Values before swapping:\t a= " + a + ", b= " + b)
// swapping
a = a + b
b = a - b
a = a - b
println("Values after swapping:\t a= " + a + ", b= " + b)
}
}
Output
Values before swapping: a= 10, b= 20
Values after swapping: a= 20, b= 10
Scala Basic Programs »