Popular Posts

June 14, 2024

C# Program To Swap Two Numbers

 

How to swap two numbers without using a temp variable, write code which is free from Integer overflow?

Here we will discuss how to swap two numbers without using a temp variable in C#

Swap two numeric values(like int, float etc) without a temporary variable as follows:

ANS:

a = a + b ;
b = a – b ;
a = a – b ;

We can also use XOR(^) operator for the same :

a = a^b;
b = b^a;
a = a^b;

This is a frequently asked interview question. Let’s look at the implementation in C#.

Without Using temp variable:

class Program
    {
        static void Main(string[] args)
        {
            int first, second;
            first = 100;
            second = 200;
            first = first + second;
            second = first - second;
            first = first - second;
            Console.WriteLine(first.ToString());
            Console.WriteLine(second.ToString());
            Console.ReadLine();
        }
    }

Output:

200
100


Program to swap numbers using XOR Operator:

ANS:

using System;

class Program
{
    static void Main()
    {
      int first, second;
 first = 100;
 second = 200;
 //swap numbers using XOR

 first = second^first;
 second = second^first;
 first = first^second;

 Console.WriteLine("first = " + first);
 Console.WriteLine("second = " + second);
    }
    }

Output:

200
100

Here's a simple C# program to swap two numbers using a temporary variable:

using System;

class Program
{
    static void Main(string[] args)
    {
        int a = 5; // First number
        int b = 10; // Second number

        Console.WriteLine($"Before swapping: a = {a}, b = {b}");

        // Swapping logic using a temporary variable
        int temp = a;
        a = b;
        b = temp;

        Console.WriteLine($"After swapping: a = {a}, b = {b}");
    }
}

This program initializes two variables a and b with values 5 and 10 respectively. Then, it swaps the values of a and b using a temporary variable temp. Finally, it prints out the values of a and b before and after swapping.

No comments:
Write comments