Scala Program to Swap Two Numbers

Posted in

Sangeeta Gulia
Last updated on January 13, 2023

    Swapping in computer programing is a memory management technique. It is an act of exchanging values between two variables mutually. Swapping takes place with the data in memory.

    Here is a pseudocode to understand the concept of swapping:

    var x = 1
    var y = 0
    swap (x,y)

    After you use the swap function, the value of x becomes 0, and the value of y becomes 1. In short, the variables, x and y, will exchange their values mutually.

    In this article, we will help you learn how to swap two numbers in Scala. You can swap two numbers in a variety of ways. Here, we shall write Scala programs to swap two numbers using a few approaches.

    So, let us begin!

    Scala Program to Swap Two Numbers

    Here, we shall swap two numbers in Scala using two different methods:

    • Using a mutable variable
    • Using recursion

    Let us discuss each of these methods in detail below.

    1. Using a Mutable Variable

    Scala is a functional programming language that has mutable variables. However, it does not recommend using mutable variables.

    Many popular programming languages , like C++, Java, and C#, use mutable variables to swap two numbers.

    Note: Please note that Scala's best practices do not recommend using var type in code.

    Example:

    objectSwapExampleextendsApp {
    
    var number1 = 15
    var number2 = 3
    
    println("Before Swap: number1 = " + number1)
    println("Before Swap: number2 = " + number2)
    
    val temp = number1
    number1 = number2
    number2 = temp
    
    println("After Swap: number1 = " + number1)
    println("After Swap: number2 = " + number2)
    
    }

    Output:

    BeforeSwap: number1 = 15
    BeforeSwap: number2 = 3
    AfterSwap: number1 = 3
    AfterSwap: number2 = 15

    In the above program, we have created two mutable input variables: number1 and number2. We created them as mutable variables because, in the end, we wanted their state to be changed or we wanted to perform reassignment to these variables.

    Next, we created one variable temp to temporarily store the value of the variable while performing the swap operation. The temp variable is of the type val since swapping only requires a one-time assignment.

    The following lines of code represent the swapping process:

    val temp = number1
    number1 = number2
    number2 = temp

    In the end, we printed the result on the output console with the numbers swapped, as you can see in the output.

    2. Using Recursion

    Recursion is a process in which a function calls itself directly or indirectly for. The corresponding function is known as a recursive function.

    With the help of the below example, we will see how we can eliminate the use of mutable variables and use recursion to swap two variables.

    Example:

    objectSwapExampleextendsApp {
    
    val number1 = 15
    val number2 = 3
    
    defswap(number1: Int, number2: Int, exit:Int = 0): (Int, Int) = {
    if (exit == 1)
    (number1, number2)
    else
    swap( number2, number1, 1)
    }
    
    val result = swap(number1, number2)
    
    println("Before Swap: number1 = " + number1)
    println("Before Swap: number2 = " + number2)
    
    println("After Swap: number1 = " + result._1)
    println("After Swap: number2 = " + result._2)
    
    }

    Output:

    BeforeSwap: number1 = 15
    BeforeSwap: number2 = 3
    AfterSwap: number1 = 3
    AfterSwap: number2 = 15

    In the above example, we have used the tail recursion technique to swap the variables. Since each recursive call has its own local variables, we don’t need to use mutable variables now.

    Let us understand how the above program works with the following steps:

    • We started by creating two input variables: number1 and number2.
    • Later, we created a function to perform the swap operation. It should take two numbers as input and yield the result with the variables swapped. Also, note that this is the function intended to be called recursively.
    • Then, we need to decide on a base condition where we can exit and return the result.
    • To mark exit, we created a flag named ‘exit’. When initialized to 0, the function should perform a recursive call and should return the swapped variables when initialized to 1.
    • Since we know that we need to swap only once, the program makes only one recursive call to swap two numbers. Hence, in the recursive call to swap, we initialized exit to 1, which marks that the variables are swapped.
    • Since the output requires two variables, we created a tuple as the return type of this function that can store two integers.
    • In the end, we printed the result using the println() function.
    • To extract values from the tuple, you can use the ._1 and ._2 methods defined for all the tuples, where ._1 defines the first variable and ._2 defines the second variable.

    Conclusion

    We have discussed two methods of swapping two variables in Scala: a mutable variable and recursion. As it is not advisable to use mutable variables in Scala, you can go with the second method, i.e., recursion, to swap two numbers. We hope the Scala programs we have mentioned in this article will help you understand the concept.

    Keep Coding, Keep Learning!

    FAQs


    Mutable variables are those variables whose state can be changed. In other words, reassignment to these types of variables is possible. They are created with the help of the var keyword. Scala does not recommend the use of mutable variables until their use becomes a necessity.

    Tail recursion is defined as a recursive function in which the recursive call is the last computation executed by the function. No further computation is done after that to complete the execution of that function. Some people confuse tail recursion with a recursive call in which the last statement calls the function recursively. However, in the last statement, a recursive call is not the last operation to be executed. In those cases, it will not be tail recursion.

    Tail recursion eliminates the O(n) stack space required to store function arguments in memory when performing recursive calls. The “n” here refers to the number of recursive calls done before hitting the base case. Using tail recursion, you can reduce O(n) stack space into O(1) stack space by reusing the stack frame for each recursive call rather than creating a new one for each call.

    Leave a Comment on this Post

    0 Comments