Swapping Numbers in C#

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?

Exchanging the values of two variables each other is called swapping of two numbers.


Before Swapping


After Swapping


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.
Depending on the preceding condition, we need to swap the values. Maybe you are thinking, how is it possible, but it is possible by using the ref keyword of C# that does not create the new storage location for the values. You can refer to the following article for more details.
Now let's start creating the console application by using the Visual Studio or Visual Studio Code. If you are new, then watch the following video to know how to create the console application.

Use the following code to swap the numbers in C#.

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("a=" + " " + a);  
            Console.WriteLine( "b=" + " " + b);  
            SwapNum(ref a, ref b);  
            Console.WriteLine("Value of a and b after sawapping");  
            Console.WriteLine("a=" + " " + a);  
            Console.WriteLine("b=" + " " + b);  


From the preceding program it's clear that we have swapped the values of two variables without creating a new storage location and the original values of a and b also remain as they were at the beginning.

Post a Comment


Protected by Copyscape
Copyright © Compilemode