Swapping of values stored in two variables
Swapping is the process of exchanging or interchanging the values stored in two variables. Swapping of two number is done by two or three variable methods. This program is done by two variable method. E.g. a=4 and b=9 then after swapping the values, we get a=9 and b=4.
Write a program in C++ to swap the value of two integer variables by using two variable method.
Firstly we will take two variables as input from the user and store it in a and b. Then we will perform some addition and subtraction to swap the values in the variables as in the example.
E.g. a=9; b=4;
Action Result
a=a+b; a=9+4=13;
b=a-b; b=13-4=9;
a=a-b; a=13-9=4;
Final result: a=4; b=9;
E.g. a=9; b=4;
Action Result
a=a+b; a=9+4=13;
b=a-b; b=13-4=9;
a=a-b; a=13-9=4;
Final result: a=4; b=9;
Program
#include<iostream.h>
#include<conio.h>void main()
{
int a,b;
clrscr();
cout<<"Enter first number in a=";
cin>>a;
cout<<"Enter second number in b=";
cin>>b;
a=a+b;
b=a-b;
a=a-b;
cout<<"\nAfter swapping:"<<endl;
cout<<"The value in a="<<a<<endl;
cout<<"The value in b="<<b;
getch();
}
Output
SWAPPING OF TWO VALUES USING TWO VARIABLES |
Explanation
In this program, we swapped the values of a and b without using any other variables. After entering the values in a and b we performed addition and subtraction to interchanged the values. Firstly, we added the two numbers and stored in a. Then subtracted a and b and stored the value in b. Finally, we again subtracted the value of a and b and stored in a. Thus we obtained the interchanged values of the two variables.
No comments:
Post a Comment