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
Program:
object myObject {
def main(args: Array[String]) {
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
Program:
object myObject {
def main(args: Array[String]) {
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
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 = tempProgram:
Output
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 - bProgram:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer