C++ programming involving swaping values of two variables.?
anonymous
1970-01-01 00:00:00 UTC
C++ programming involving swaping values of two variables.?
Five answers:
selvey
2016-10-18 13:14:15 UTC
the undertaking-unfastened occasion is the XOR swap, which comprises employing the bitwise XOR operator on the two values in a definite series. be conscious that this demands that the two values be in diverse memory places. See the link decrease than for an occasion. that's generally no longer a specifically sensible way in maximum certainly-international situations, because of the fact the utilising a short lived variable is likely rapid than utilising repeated XORs (that are no longer in a position to be parallelized).
PokerChip
2008-04-10 10:41:23 UTC
Here is the basics.
Say you want to swap the values
of variables A and B. Use a third
variable C.
C = A
A = B
B = C
mapighimagsik_so
2008-04-10 10:29:43 UTC
Why don't you try it yourself? This is painfully simple. Just pass the values by reference.
Rahul Ghose
2008-04-10 11:14:43 UTC
Here's a cool bit-hack:
say a and b are two variables.
after the operation:
a^=b^=a^=b;
a and b have swapped values!
Kushal C
2008-04-10 20:59:55 UTC
Hi Edward,
The best way to learn any programming language is to give it a try yourself first. Anyways, you have been already answered. Nevertheless, I could not resist myself from posting this small program. The beauty of this program is that it does everything using just the 2 variables, without using a 3rd temporary variable. I have tried to code the program exactly as it is asked in the highschool, to make things as clear and lucid as possible. I hope next time you will give it a try.
# include
# include
void swap(int &m,int &n);
void main()
{
int a,b;
clrscr();
cout << "Enter two numbers " << endl;
cin >> a >> b;
cout << endl;
cout << "Before swapping the values are : " << endl;
cout << "The value of a is " << a << endl;
cout << "The value of b is " << b << endl << endl;
swap(a,b);
cout << "After swapping the values are : " << endl;
cout << "The value of a is " << a << endl;
cout << "The value of b is " << b << endl;
getch();
}
void swap(int &m,int &n)
{
m = m + n;
n = m - n;
m = m - n;
}
Peace and have a very good day !
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.