In c language , How to get 2 values in single variable and swap them ???

1 reply [Last post]
Offline
Last seen: 33 weeks 2 days ago
Joined: 09/27/2011
Posts:

In C programming , How to get 2 values in a single variable and swap them ??? Help me with some examples(im a beginner :) ) !! Thanks in advance !!!!

Offline
Last seen: 27 weeks 2 days ago
Joined: 09/29/2011
Posts:
In c language , How to get 2 values in single variable and swap

I assume by "single variable" you mean without using an extra temp variable. In that case, just using the two original variables, you can do the following math to swap them:

int a = 5;
int b = 6;

// Commence the swapping!
a = a + b; // a will now equal 11, b will stay at 6
b = a - b; // a stays at 11, b becomes 5
a = a - b; // a now equals 6, b stays at 5

And there you go. You just swapped two integer variables without using a temp variable!
I would, however, recommend using a temp variable though, which eliminates the math and uses pure assignments, therefore making the procedure suitable for non-numbers and roundoff-sensitive values.