How to write a C# Program to swap two numbers, how to swap two numbers with temporary variable,how to swap two numbers without using third variable.
What is Swapping of Numbers ?
The act of swapping two variables refers to mutually exchanging the values of the variables. Generally, this is done with the data in memory.
Swap Two Numbers with Third Variable
The simplest method to swap two variables is to use a third temporary variable .
Algorithm of swapping two numbers with temporary variable:
Step 1: Define 3 variables x, y and temp;
Step 2: give values to the x and y;
Step 3: temp = x ;
Step 4: x = y ;
Step 5: y = temp;
Step 6: Print values of x and y;
Program of swapping two numbers with temporary variable in C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Program { class Program { static void Main(string[] args) { int num1, num2, temp; Console.Write("\n Enter the First Number : "); num1 = int.Parse(Console.ReadLine()); Console.Write("\n Enter the Second Number : "); num2 = int.Parse(Console.ReadLine()); temp = num1; num1 = num2; num2 = temp; Console.Write("\n After Swapping : "); Console.Write("\n First Number : "+num1); Console.Write("\n Second Number : "+num2); Console.Read(); } } }
Input & output:
Enter the First Number : 5 Enter the Second Number : 7 After Swapping : First Number : 7 Second Number : 5
How to swap two numbers without using a temporary variable
If given two variables are x, and y, swap two variables without using a third variable.There is a common way to swap two numbers without using third variable.
Using Arithmetic Operators : The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum.
C# Program to Swap Two Numbers without third variable
using System; namespace CSharpProgram { class Program { static void Main(string[] args) { Console.WriteLine("\n Enter first number"); int n1 = int.Parse(Console.ReadLine()); Console.WriteLine("\n Enter second number"); int n2 = int.Parse(Console.ReadLine()); Console.WriteLine("\n Numbers Before swap n1 = " + n1 + " n2 = " + n2); n1 = n1 * n2; //n1=50 (5*10) n2 = n1 / n2; //n2=5 (50/10) n1 = n1 / n2; //n1=10 (50/5) Console.Write("\n After swap n1 = " + n1 + " n2 = " + n2); Console.ReadLine(); } } }
Input & Output:
Enter first number 27 Enter second number 15 Numbers Before swap n1 = 27 n2 = 15 After swap n1 = 15 n2 = 27
So in this post we have learn how to swap two numbers using temporary variable or without using temporary variable.