Scala program to swap two numbers (3 ways)

How to swap two numbers in the Scala programming language? In this post, we are going to see three different methods to do this program. The first method is by using the XOR operator, the second is by using a temp variable and the last one is by without using the temp variable.

Scala program to swap two numbers using the XOR operator

object divineseo{
    def main(args: Array[String]){
        var num1: Int = 0
        var num2: Int = 0
        
        Console.println("Enter 1st number :")
        num1 = scala.io.StdIn.readInt()
        
        Console.println("Enter 2nd number :")
        num2= scala.io.StdIn.readInt()
        
        Console.println("Befor Swapping")
        printf("\n num1: %d",num1)
        printf("\n num2: %d\n ",num2)
        
        num1 = num1^num2
        num2 = num1^num2
        num1 = num1^num2
        
        Console.println("\n After Swapping")
        printf("\n num1: %d",num1)
        printf("\n num2: %d",num2)
    }
}
Scala

Output

Enter 1st number : 40
Enter 2nd number : 20
Befor Swapping

 num1: 40
 num2: 20
 
 After Swapping

 num1: 20
 num2: 40

Scala program to swap two numbers using temp variable

object divineseo{
    def main(args: Array[String]){
        
        var x: Int = 0
        var y: Int = 0
        var temp: Int = 0
        
        Console.println("Enter the value of X : ")
        x= scala.io.StdIn.readInt()
        
        Console.println("Enter the value of Y : ")
        y=scala.io.StdIn.readInt()
        
        Console.println("\n Before Swapping")
        printf("\n x = %d", x)
        printf("\n y = %d\n ", y)
        
        temp = x
        x = y
        y = temp
        
        Console.println("\n After Swapping")
        printf("\n x = %d", x)
        printf("\n y = %d", y)
    }
    
}
Scala

Output

Enter the value of X
Enter the value of Y

 Before Swapping

 x = 40
 y = 20
 
 After Swapping

 x = 20
 y = 40

Scala program to swap two numbers Without using temp variable

object divineseo{
    def main(args: Array[String]){
        
        var x: Int = 0
        var y: Int = 0
        
        Console.println("Enter the value of X: ")
        x= scala.io.StdIn.readInt()
        
        Console.println("Enter the value of Y: ")
        y= scala.io.StdIn.readInt()
        
        Console.println("\n Before Swapping")
        println("x = " +x+ ", y = "+y)
        
        x = x + y
        y = x - y
        x = x - y
        
        Console.println("\n After Swapping")
        println("x = " +x+ ", y = "+y)

    }
}
Scala

Output

Enter the value of X: 40
Enter the value of Y: 34

 Before Swapping
x = 40, y = 34

 After Swapping
x = 34, y = 40

Leave a Comment