Swapping two variables using temporary third variable. – Computer Sir Ki Class
  

Login
[lwa]



Code Learning #JAVA#3777 siteicon   siteicon   siteicon  

Swapping two variables using temporary third variable.

Swapping of value between two integer variables using the intermediate third variable.

Learning Objectives

  • Simple way to swap two variables using the third temporary variable.

Source Code

TC++ #3777

Source Code

Alternate (?) :

Run Output

Before swapping: a = 10 b = 20
After swapping : a = 20 b = 10

Code Understanding

int a=10,b=20,temp;
Variable a, b and temp declared. temp will be used later as the intermediate variable. a is given initial value 10 and b as 20.

System.out.println(“Before swapping: a = “+a+” b = “+ b);
Here we print the values before swapping.

temp=a; //First value  a is shifted to a temporary variable temp
a=b;      //Second value b is shifted to first value a as first value is already save in temp
b=temp; //First value a which is saved in temp variable is brought  into second value b

System.out.println(“After swapping : a = “+a+” b = “+b);
Here we print the values after swapping.

Notes

  • This method will be frequently used while using arrays and reversal programs.
  • This method can easily be used for any data type; char, int, long, float, double etc.

Common Errors

  • Erroneously some students shift b to a first and then move a to b. This will obviously destroy initial value of a. Watch -a=b; temp=a; b=temp; //This is incorrect
    temp=a; a=b; b=temp; //This is correct


Suggested Filename(s): SwapTemp.java



Share

sunmitra| Created: 5-Mar-2018 | Updated: 5-Mar-2018|






Back