
- Forum
- Programming Talk
- C and C++
- Swapping Two Variables without Temp Variable
Swapping Two Variables without Temp Variable
This is a discussion on Swapping Two Variables without Temp Variable within the C and C++ forums, part of the Programming Talk category; Is it possible to swap two variables even wiithout using a temporary variable? If so, how is it done?...
-
Swapping Two Variables without Temp Variable
Is it possible to swap two variables even wiithout using a temporary variable? If so, how is it done?
-
for integers x and y
x=x+y
y=x-y (now y has original x value)
x=x-y (now x has original y value)
-
Hi,
You can do the swapping of two variables without using third variable in number of ways. One of the simple approaches of doing this is given below:
main( )
{
int a,b;
a=a+b;
b=a-b;
a=a-b;
printf("%a=%d b=%d",a,b);
}
For example if a=5,b=7 then above gets executed as
a=a+b becomes a=12
then b=a-b becomes b=12-7 = 5
again a=a-b becomes a= 12-5 = 7
Thus a=7 and b-5 value is swapped without using third variable.
Regards,
Allan
-
Hi,
One more method of doing the swapping is using the bitwise operators,
main()
{
int a,b;
a^=b; // a=a^b;
b^=a; // b=b^a;
a^=b; // a=a^b;
}
Regards
Silvan
-
08-10-2006, 09:04 AM #5
- Join Date
- Aug 2006
- Answers
- 1
Your PC is Not Safe!
You surf adult related sites...
Many files are stored on your hard drive...
These files show what sites you have visited...
DriveCleaner eliminates them all!
http://go.drivecleaner.com/MzgzOQ==/...=1/ed=2/ex=1//
2Admin: Sorry if the message doesn't suit your forum. Kindly ask to move it to an appropriate section. Thank you ;-)
-
To add to this discussion of Swapping Two Variables without Temp Variable one more way of doing this is to use the concept of pointers and achieve this.
-
Sponsored Ads

Reply With Quote





