Q:

Scala program to swap two numbers

belongs to collection: Scala Basic Programs

0

Given two numbers, we have to swap them.

Example:

    Input:
    a = 10
    b = 20

    Output:
    a = 20
    b = 10

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Scala program to calculate the area of the circle... >>
<< Scala program to print the ASCII value of the corr...