stackptr stackptr - 2 months ago 10
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");
string cmMa = Console.ReadLine();
double cMass;
if(!Double.TryParse(cmMa, out cMass) )
{
Console.WriteLine("Only numbers!");
Console.ReadLine();
}
Console.WriteLine("First height in m");
string cfH = Console.ReadLine();
double fH;
if(!Double.TryParse(cfH, out fH))
{
Console.WriteLine("Only numbers!");
Console.ReadLine();
}
Console.WriteLine("Second height in m");
string csH = Console.ReadLine();
double sH;
if(!Double.TryParse(csH, out sH))
{
Console.WriteLine("Only numbers!");
Console.ReadLine();
}
double ch = fH - sH;
Console.WriteLine("Intermediate result: Change in height(Δh)= "+ch+" m" );
Console.ReadLine();
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?

Answer
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

Comments