stackptr - 1 year ago 113
C# Question

# How to swap two variable values?

I'm writing a complex program that calculates change in potential energy( ΔPE= mgΔh ).

``````Console.WriteLine("Mass in kg");
double cMass;
if(!Double.TryParse(cmMa, out cMass) )
{
Console.WriteLine("Only numbers!");
}
Console.WriteLine("First height in m");
double fH;
if(!Double.TryParse(cfH, out fH))
{
Console.WriteLine("Only numbers!");
}
Console.WriteLine("Second height in m");
double sH;
if(!Double.TryParse(csH, out sH))
{
Console.WriteLine("Only numbers!");
}
double ch = fH - sH;
Console.WriteLine("Intermediate result: Change in height(Δh)= "+ch+" m" );
double ng = 9.81;  //   m/s^2
Console.WriteLine("CHANGE IN POTENTIAL ENERGY: "+ch*cMass*ng+" J");
``````

At the end, I want to add an if statement that if sH>fH, then their values are swapped. What concept should I apply?

``````if (sH > fH) {
double temp = sH;
sH = fH;
fH = temp;
}
``````

The swapping can be accomplished by using a temporary third variable. Store sH in a temporary variable and assign sH to fH. This way the value of sH is cached and not lost when reassigning. Lastly, assign fH to temp. The values are now swapped.

Hope this helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download