Write a program to Swap two numbers in C#
In many Interviews, the Interviewer asks the Interviewee to write a program to swap two numbers. There are multiple methods/ways to swap numbers in C#, out of which two popular methodologies are Swapping two numbers with third/temporary variable and another is swapping two numbers without using a third/temporary variable (using + and – arithmetic operator). Let’s see both approaches in detail.
int num1, num2, temp; //Get two number from the user to swap Console.WriteLine("Enter
first number"); num1 = int.Parse(Console.ReadLine()); Console.WriteLine("Enter
second number"); num2 = int.Parse(Console.ReadLine()); Console.WriteLine("Values
before swapping: num1=" + num1 + " and num2=" + num2); temp = num1; num1 = num2; num2 = temp; Console.WriteLine("Values
after swapping: num1=" + num1 + " and num2=" + num2); //Console.ReadLine() to hold the screen after the execution of
the program Console.ReadLine(); |
int num1, num2; //Get two number from the user to swap Console.WriteLine("Enter
first number"); num1 = int.Parse(Console.ReadLine()); Console.WriteLine("Enter
second number"); num2 = int.Parse(Console.ReadLine()); Console.WriteLine("Values
before swapping: num1=" + num1 + " and num2=" + num2); num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2; Console.WriteLine("Values
after swapping: num1=" + num1 + " and num2=" + num2); //Console.ReadLine() to hold the screen after the execution of
the program Console.ReadLine(); |
0 comments:
Post a Comment