How to swap two variable without using 3rd variable?
Hi Friends.
Today we will see how we can swap value of two variable without using the third variable.
For that will perform the below steps.
Step 1. Declare both variables.
var x=13;
var y=21;
Step 2. Add both variable and assign to the first variable.
x=x+y; //13+21, x =34
Step 3. Subtract second variable from first variable as it contains the sum of both variables and assign to the second variable. By doing this, second variable will hold the value of first variable value which was assign in the beginning.
y=x-y; //34-21, y=13Step 4. Now subtract second variable from first variable as it contains the sum of both variables and assign to the first variable. By doing this, first variable will hold the value of second variable value which was assign in the beginning.
x=x-y; //34-13. x=21Complete code:-
var x=13;
var y=21;
x=x+y; //13+21, x =34
y=x-y; //34-21, y=13
x=x-y; //34-13. x=21
No comments:
Post a Comment