Hi Guys,
I'm relatively new to C# programming and am still trying to find my feet a little. I need a hand with creating a program that can swap the values between two integer variables. I've set them to two fixed values, ie: priceOne and priceTwo, however I would like to be able to run a program that can swap these variables..
Any help is appreciated.
Code to swap values between two variables.
Page 1 of 13 Replies - 2712 Views - Last Post: 18 October 2010 - 06:56 AM
Replies To: Code to swap values between two variables.
#2
Re: Code to swap values between two variables.
Posted 18 October 2010 - 02:41 AM
Maybe this will help: same question at Stack Overflow
#3
Re: Code to swap values between two variables.
Posted 18 October 2010 - 04:14 AM
Another way you might want to look at doing this is creating a temporary variable.
Imagine having 2 glasses of water and wanting to keep the contents separate. You need to dump one of them into a third container to be able to trade glasses.
x = 1;
y = 2;
z;
z = x;
x = y;
y = z;
z = 0; (just clearing z)
end result------
x = 2
y = 1
z = 0
Imagine having 2 glasses of water and wanting to keep the contents separate. You need to dump one of them into a third container to be able to trade glasses.
x = 1;
y = 2;
z;
z = x;
x = y;
y = z;
z = 0; (just clearing z)
end result------
x = 2
y = 1
z = 0
#4
Re: Code to swap values between two variables.
Posted 18 October 2010 - 06:56 AM
As the second answer at the linked SO thread said, the best way to do it is simply create a third, temporary variable.
All the other ways in most contexts are just showing off. Yes, you can do a little math to swap numeric values in place. No, you probably shouldn't, because it's neither intuitive or necessary in the vast majority of cases. Unless you're working on the most memory-intensive of applications, you'll never feel that extra int/double.
The only use for this skill is interview questions or homework problems.
All the other ways in most contexts are just showing off. Yes, you can do a little math to swap numeric values in place. No, you probably shouldn't, because it's neither intuitive or necessary in the vast majority of cases. Unless you're working on the most memory-intensive of applications, you'll never feel that extra int/double.
The only use for this skill is interview questions or homework problems.
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote



|