#include<iostream.h>
using namespace std;
int main(){
int v1,v2;
cout<<"Enter the two Values:"<<endl;
cin>>v1>>v2;
cout<<"Values Before Swapping:"<<v1<<" and "<<v2<<endl;
//Program Logic
v1=v1+v2;
v2=v1-v2;
v1=v1-v2;
cout<<"Values After Swapping:"<<v1<<" and "<<v2<<endl;
return 0;
}
using namespace std;
int main(){
int v1,v2;
cout<<"Enter the two Values:"<<endl;
cin>>v1>>v2;
cout<<"Values Before Swapping:"<<v1<<" and "<<v2<<endl;
//Program Logic
v1=v1+v2;
v2=v1-v2;
v1=v1-v2;
cout<<"Values After Swapping:"<<v1<<" and "<<v2<<endl;
return 0;
}
In this program, we require only two variables to store the values. Here we name the variables as v1 and v2,
The logic is very simple!
For ex: we assign v1=20 and v2=30
Now, we assign v1=v1+v2; so v1 will contain the sum of v1 and v2.i.e., 20+30=50
Through the second step, we will be assigning v2=v1-v2; i.e., 50-30=20,
Next, to the final step of the logic, we assign v1=v1-v2; i.e., 50-20=30,
So at final, the Variable v1 will contain value 30 and v2 will contain value 20.
v1=20; v2=30
v1=v1+v2; //v1=20+30 ;Therefore, v1=50;
v2=v1-v2; //v2=50-30 ; Therefore v2=20;
v1=v1-v2; //v1=50-20; Therefore v1=30;
Output:
Enter the two Value:
15 20
Values before swapping: 15 and 20
values after swapping: 20 and 15
Comments
Post a Comment