Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap two variables without using a temporary variable

Tags:

c#

algorithm

swap

I'd like to be able to swap two variables without the use of a temporary variable in C#. Can this be done?

decimal startAngle = Convert.ToDecimal(159.9); decimal stopAngle = Convert.ToDecimal(355.87);  // Swap each: //   startAngle becomes: 355.87 //   stopAngle becomes: 159.9 
like image 900
Sreedhar Avatar asked Apr 29 '09 23:04

Sreedhar


People also ask

How do you swap two variables without using a temporary variable?

Given two variables, x, and y, swap two variables without using a third variable. The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum.

How do you swap two numbers with a temporary variable?

Swap Numbers Using Temporary Variable In the above program, the temp variable is assigned the value of the first variable. Then, the value of the first variable is assigned to the second variable. Finally, the temp (which holds the initial value of first ) is assigned to second . This completes the swapping process.

How do you swap two integers without using a temporary variable python?

Without a temporary variable (Tuple swap) Another way to swap the values of two variables, without using a temporary variable, is to use tuple packing and sequence unpacking. Tuples can be constructed in a number of ways, one of which is by separating tuple items using commas.


1 Answers

C# 7 introduced tuples which enables swapping two variables without a temporary one:

int a = 10; int b = 2; (a, b) = (b, a); 

This assigns b to a and a to b.

like image 66
TimothyP Avatar answered Oct 07 '22 03:10

TimothyP