In this article we will learn VB.NET Program to swap two numbers without third variable.
We can swap two numbers without using third variable. There are two common ways to swap two numbers without using third variable:
Program 1: Using ∗ and /
Let’s see a simple example VB.NET Program to swap two numbers without third variable
Imports System
Module Program
Sub Main(args As String())
Dim a As Integer, b As Integer
Console.Write(“Enter the Number for a = “)
a = Integer.Parse(Console.ReadLine())
Console.Write(“Enter the Number for b = “)
b = Integer.Parse(Console.ReadLine())
Console.WriteLine(“Before swap a= ” & a & ” b= ” & b)
a = a * b
b = a / b
a = a / b
Console.Write(“After swap a= ” & a & ” b= ” & b)
Console.ReadLine()
End Sub
End Module
Program 2: Using + and –
Let’s learn another example to swap two numbers using + and -.
Imports System
Module Program
Sub Main(args As String())
Dim a As Integer, b As Integer
Console.Write(“Enter the Number for a = “)
a = Integer.Parse(Console.ReadLine())
Console.Write(“Enter the Number for b = “)
b = Integer.Parse(Console.ReadLine())
Console.WriteLine(“Before swap a= ” & a & ” b= ” & b)
a = a + b
b = a – b
a = a – b
Console.Write(“After swap a= ” & a & ” b= ” & b)
Console.ReadLine()
End Sub
End Module
Output