Exchanging (Swapping) the value of two variables
Exchanging the value of two variables means interchanging or swapping their values Suppose we have two values which is assigned into the two variables such as x and y are two variables and suppose we take two values in it as x=10 and y=20 then after the interchanging of values the output will be x=20 and y=10. There is different method for exchanging the values of two variables which is as follows:
Using the temporary variable
In this method we take another variable as temporary. So there are three variable as a, b and temp. Here temp is the temporary variable.
Logic:
Suppose we take two values in a and b, a=10, b=20 respectively.
temp=a;
a=b;
b=temp;
After the operation of this statement, the value of two variable a and b will be interchanged.
Output:
A=20, B=10;
Algorithm:
Step 1: Start
Step 2: Take the value of variables a and b.
Step 3: Assign the value of variable a into the temp variable.
Step 4: Assign the value of variable b into a variable.
Step 5: Assign the value of variable temp into the b variable.
Step 6: Print the value of a and b.
Step 7: Stop
Without using the third variable
Here we will use arithmetic operator (+, -). We use addition and subtraction operation on these variables.
Logic:
a=a+b;
b=a-b;
a=a-b;
Algorithm:
Step1: Start
Step 2: Take the value of variables a and b.
Step 3: Add the values of the a and b and assign it to the variable a.
Step 4: Subtract the values of a and b and assign it to the variable b. (Here the value of a is changed due
to the step 3).
Step 5: Subtract the values of a and b and assign it to the variable a.
Step 6: Print the value of a and b.
Step 7: Stop
Without using third variable and without using arithmetic operator
Here we will use the Exclusive OR bit-wise operator.
Logic:
a=a^b;
b=a^b;
a=a^b;
Algorithm:
Step 1: Start
Step 2: Take the value of variables a and b.
Step 3: Operate Exclusive OR operation on variable a and b and assign the exclusive OR output in a
variable. (Here value of a is changed)
Step 4: Operate Exclusive OR operation on variable a and b and assign the exclusive OR output in b
variable. (Here value of b is changed)
Step 5: Operate Exclusive OR operation on variable a and b and assign the exclusive OR output in a
variable. (Here value of a is again changed)
Step 6: Stop.