write a program to accept two integer values of int type and swap their values without using third value
computer
bluej
fastly
Answers
I am writing a C++ program in which it will accept two integer values by the user and their values will be swapped without using any third variable. Kindly have a look over it.
#include<iostream.h>
#include<conio.h>
void main ()
{
clrscr() ;
int a, b ;
cout<<"Enter any two integer values of your choice \n";
cin>>a>>b;
{
a=a+b;
b=a-b;
a=a-b;
}
cout<<"After swapping the values are as under:- "<<endl;
cout<<" a = "<<a<<endl;
cout<<" b = "<<b<<endl;
getch();
}
Explanation by an example!
Suppose the values entered by the user are :-
a = 5
&
b = 7
So, according to the formula applied above:-
1) a = a + b
=> a = 5 + 7
a= 12
2) b = a - b
=> b = 12 - 7
b = 5
3) a = a - b
=> a = 12 - 5
a = 7
So, the program will swap the values in this way.
The code is written in python language
________CODE_________
a=int(input('please enter the first number:'))
b=int(input('please enter the second number:'))
a,b=b,a #Swap
print('The new numbers are:',a,',',b,'respectively')
#PYTHON IS THE BEST
_________END___________
Hope this helps