Home » Scala programs » Scala basic programs

Scala program to swap two numbers

Scala | Swapping two numbers: Here, we are going to learn how to swap two numbers in Scala programming language?
Submitted by Shivang Yadav, on April 21, 2020

Given two numbers, we have to swap them.

Example:

    Input:
    a = 10
    b = 20

    Output:
    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 = 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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.