Write a program in C# to create a function to swap the values of two integers.

Answer:

using System;

namespace SwapNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            int num1, num2;

            // Taking input from the user
            Console.WriteLine("Enter the first number: ");
            num1 = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Enter the second number: ");
            num2 = Convert.ToInt32(Console.ReadLine());

            // Displaying the values before swap
            Console.WriteLine("\nBefore Swap:" + num1 + " and " + num2);

            // Swapping the values
            Swap(ref num1, ref num2);

            // Displaying the values after swap
            Console.WriteLine("\nAfter Swap:" + num1 + " and " + num2);
            Console.ReadLine();
        }

        // Function to swap two integers
        static void Swap(ref int a, ref int b)
        {
            int temp = a;
            a = b;
            b = temp;
        }
    }
}
Scroll to Top