DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

swapping two variables without using temp/third variable and using temp/third variable in .NET

By Ashok Nalam on 21 Dec 2012 | Category: C# | Tagged: variable swap 
In this snippet we will see how swap two variables without using temp/third variable and using temp/third variable in .NET.
  Discuss Add Comment   |  
Add rating Rate this resource   

In many of interviews, interviewers will ask write a program to swap two numbers without using a third variable or temporary (temp) variable. So in this snippet we will see how to swap two numbers with/without using third variable.

Program : Swapping 2 numbers With temp variable

class SwapTwoNumbersUsingTempVariable
{
public static void Main()
{
Console.WriteLine("/****** Program to swap 2 numbers using temporary variable *******/");
int a = 10, b = 20;
Console.WriteLine(" Values before swapping a={0} , b={1}", a, b);
int tempVar = 0; //temporary variable
tempVar = a;
a = b;
b = tempVar;
Console.WriteLine(" Values after swapping a={0} , b={1}", a, b);
Console.ReadKey();
}
}

output:

Program : Swapping 2 numbers Without temp variable

class SwapTwoNumbersWithoutUsingThirdVariable
{
public static void Main()
{
Console.WriteLine("/****** Program to swap 2 numbers without using temporary variable *******/");
int a = 10, b = 20;
Console.WriteLine(" Values before swapping a={0} , b={1}", a, b);
a = a + b;
b = a - b;
a = a - b;
Console.WriteLine(" Values after swapping a={0} , b={1}", a, b);
Console.ReadKey();
}

}

Output:

  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9226  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (0)
No comments found, click here to add comment.
 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys