Home »
        VB.Net »
        VB.Net Programs
    
    VB.Net program to swap adjacent elements of a one-dimensional array
    
    
    
    
	    
		    By Nidhi Last Updated : November 16, 2024
	    
    
    
    Swap adjacent elements of a one-dimensional array
    Here, we will create an array and read elements from the user then we swap adjacent elements of the array. After that print the updated array on the console screen.
    Program/Source Code:
    The source code to swap adjacent elements of a one-dimensional array is given below. The given program is compiled and executed successfully.
    VB.Net code to swap adjacent elements of a one-dimensional array
'VB.Net program to swap adjacent elements of a one-dimensional array
Module Module1
    Sub ReadArray(ByVal arr() As Integer)
        For i = 0 To 5 Step 1
            Console.Write("Element[{0}]: ", i)
            arr(i) = Integer.Parse(Console.ReadLine())
        Next
    End Sub
    Sub PrintArray(ByVal arr() As Integer)
        For i = 0 To 5 Step 1
            Console.Write("{0} ", arr(i))
        Next
        Console.WriteLine()
    End Sub
    Sub Main()
        Dim arr As Integer() = New Integer(6) {}
        Dim temp As Integer = 0
        Console.WriteLine("Enter array elements: ")
        ReadArray(arr)
        'swap adjacent elements
        For i = 0 To 5 Step 2
            temp = arr(i)
            arr(i) = arr(i + 1)
            arr(i + 1) = temp
        Next
        Console.WriteLine("Array elements after swapping adjacent elements:")
        PrintArray(arr)
    End Sub
End Module
Output
Enter array elements:
Element[0]: 10
Element[1]: 20
Element[2]: 30
Element[3]: 40
Element[4]: 50
Element[5]: 60
Array elements after swapping adjacent elements:
20 10 40 30 60 50
Press any key to continue . . .
    Explanation
    In the above program, we created a module Module1 that contains a function Main(). In the Main() we created an array arr and read the elements of the array and then swapped the adjacent elements of the array then print the console screen.
    VB.Net Array Programs »
    
    
    
    
   
    
  
    Advertisement
    
    
    
  
  
    Advertisement