Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

Sunday 6 September 2020

Program to Swap two numbers in C#

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. 


Swap two numbers by using third/temporary variable:
As you can see in the below image, it’s very simple to swap two numbers with a third temporary variable.
Program to swap two numbers by using third/temporary variable in C# is provided below:

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();

Output:

Swap two numbers without using any third/temporary variable:
As you can see in below image it’s very easy to swap the two numbers without using third variable. 
Program to swap two numbers without using third/temporary variable is provided below:

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();

Output:
I hope this article will help you in your interview preparation.
Thanks



0 comments:

Post a Comment

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook

Blog Archive