Swapping of variables is when we assign the value of one variable to another programmatically. In this shot, we'll see how we can swap the value of one variable with another, since there is no default method that can allow us to do this.
There are basically two ways to achieve this:
Let's see these possibilities in the syntax below.
c = a; a = b; b = c;
a = a + b; b = a - b; a = a - b;
c
: This is the third variable.
b
: This is the second number variable.
a
: This is the first number variable.
We'll see swapping with and without using a third variable.
object Main extends App { var a = 5 var b = 10 // print values before swapping println("Before Swapping a = " +a+ " b =" +b) // swap var c = a a = b b = c // print the values after swapping println("After Swapping a = " +a+ " b =" +b) }
c
.object Main extends App { var a = 5 var b = 10 // print values before swapping println("Before Swapping a = " +a+ " b =" +b) // swap a = a + b b = a - b a = a - b // print the values after swapping println("After Swapping a = " +a+ " b =" +b) }
RELATED TAGS
CONTRIBUTOR
View all Courses