Home >>VB.Net Programs >VB.Net program to swap two numbers using a BITWISE XOR operator

VB.Net program to swap two numbers using a BITWISE XOR operator

Write a program to swap two numbers in VB.Net

Here, using the bitwise "Xor" operator, we can interchange the value of two integer numbers.

Program :

Below is the source code to swap two numbers using the bitwise "Xor" operator. The program given is compiled and successfully executed.

Example


Module Module1

    Sub Main()
        Dim X As Integer = 15
        Dim Y As Integer = 25

        Console.WriteLine("Number Before Swapping : ")
        Console.WriteLine("X: {0}", X)
        Console.WriteLine("Y: {0}", Y)

        X = X Xor Y
        X = X Xor Y
        X = X Xor Y

        Console.WriteLine()
        Console.WriteLine("Number After Swapping : ")
        Console.WriteLine("X: {0}", Y)
        Console.WriteLine("X: {0}", Y)

        Console.ReadLine()
    End Sub
End Module
	
Output:
Number Before Swapping:
X: 15
Y: 25

Number After Swapping:
X: 25
Y: 15

Explanation:

We created a Module1 module in the above program that contains the function Main(). We declared two integer variables X and Y in the Main() function that are initialized with 15 and 25, respectively.

X = X Xor Y
Y = X Xor Y
X = X Xor Y

We swapped the X and Y values here using the bitwise "Xor" operator. After that, the swap value is printed on the console screen.


No Sidebar ads