Monday, September 10, 2007

A new way of swapping values in C.... The one line method...

I was just wandering in the digit forum and came across a query by a user. Or a challenge rather. How to swap values in a program using only one syntax line? I found the answer.

Most of the people use the following method for swapping. They create a temporary variable and swap values.

Code :

int a = 5, b = 7 ,temp;

temp = a; // temp = 5
a = b; // a = 7
b = temp; // b = 5

There is nothing wrong with this method except that is uses another variable. Meaning more memory. Alternate way to do this is making use of only the 2 variables and using the following code.
Code :

int a = 5, b = 7;

a = a + b; // a = 12
b = a - b; // b = 5
a = a - b; // a = 7

But there is another way. I scratched my head a little and found this out. If this is an old trick then I am sorry for repost. But I found it by myself (imagine... no google :-D).

Here it is :-

Code :

#include<iostream>

using namespace std;

main()
{

int a, b;

cout << "Enter A and B"
;
cout << "a = ";
cin >> a;
cout << "b = ";
cin >>b;

a = ((b - a) + (b = a));

cout << " a = " << a << endl;
cout << " b = " << b;

return 0;

}

And the output of the program is :-

EXECUTING:
/home/aditya/test
----------------------------------------------
Enter A and B
a = 7

b = 23

a = 23
b = 7
----------------------------------------------
Program exited successfully with errcode (0)
Press the Enter key to close this terminal ...

The main line that does the swapping is this :-

a = ((b - a) + (b = a));

  1. First the value of (b-a) is calculated. In the above example, it is 16.
  2. Then 'b' is assigned the value of 'a', that is 7.
  3. And a is the sum of (b-a) which is 16 and 'b' which is now 7 so 'a' becomes 23.
Thus values are swapped.

I think it's a cool way to swap the values.... Nice find. At least the start of the day was good. (It's after midnight :-D).

No comments: