How to Swap Two Numbers in C#?

In this C# tutorial, I will show you how to swap two numbers in C#. In detail, we will discuss how to write a C# program to swap two numbers.

To swap two numbers in C#, you can use a temporary variable. First, assign the value of the first number to the temporary variable, then assign the second number’s value to the first, and finally, assign the temporary variable’s value to the second number. This simple method ensures a smooth swap without losing any values.

Write C# program to swap two numbers

Let’s understand what it means to swap two numbers in C#. Swapping involves exchanging the values of two variables. For example, if you have two variables a and b, with values 5 and 10, respectively, after swapping, a should have the value 10, and b should have the value 5.

Here’s the complete C# code to swap two numbers:

using System;

class Program
{
    static void Main()
    {
        // Declare and initialize two numbers
        int number1 = 5, number2 = 10;
        
        Console.WriteLine("Before swapping:");
        Console.WriteLine("Number 1: " + number1);
        Console.WriteLine("Number 2: " + number2);

        // Swapping
        int temp = number1;
        number1 = number2;
        number2 = temp;

        Console.WriteLine("After swapping:");
        Console.WriteLine("Number 1: " + number1);
        Console.WriteLine("Number 2: " + number2);

        Console.ReadLine();
    }
}

You can see the output in the screenshot below after I ran the code using a Visual Studio console application.

How to Swap Two Numbers in C#

Here is the complete code explanation:

  • Initialization: We start by declaring two integer variables, number1, and number2, and initializing them with the values 5 and 10.
  • Display Initial Values: We then print these values to the console to show the numbers before the swap.
  • Swapping Process:
    • We introduce a temporary variable temp and assign it the value of number1.
    • Next, we assign the value of number2 to number1.
    • Finally, we assign the value stored in temp (which is the original value of number1) to number2.
  • Display Swapped Values: After the swapping, we print the values of number1 and number2 again to demonstrate that they have been swapped.

The temporary variable temp plays a crucial role in the swapping process. It temporarily holds the value of one of the variables (in this case, number1) so that we can safely assign the value of number2 to number1 without losing the original value of number1.

Conclusion

In this C# tutorial, we discussed how to swap two numbers in C# using the above complete C# code.

You may also like: