In this article we will learn how to swap two values without creating a new storage location using C#. This type of question might be asked by an interviewer in an interview, so in this article I am explaining how to answer a question that is how to write a program to swap numbers in C# without creating the new storage location.
What is the swapping of numbers?
Conditions for swapping values
- The values of two variables are swapped with each other without creating a new storage location for the variables.
- After the swapping of the values of the two variables, then before swapped values need to be remain in that variable.
using System; namespace SwappingValues { class Program { static void SwapNum(ref int x, ref int y) { x = y; y = x; } static void Main(string[] args) { int a = 100; int b = 500; Console.WriteLine( "Value of a and b before sawapping"); Console.WriteLine(); Console.WriteLine("a=" + " " + a); Console.WriteLine( "b=" + " " + b); SwapNum(ref a, ref b); Console.WriteLine(); Console.WriteLine("Value of a and b after sawapping"); Console.WriteLine(); Console.WriteLine("a=" + " " + a); Console.WriteLine("b=" + " " + b); Console.ReadLine(); } } }
Post a Comment