VB.Net program to copy stack elements into an array using the collection

Here, we are going to learn how to copy stack elements into an array using the collection in VB.Net?
Submitted by Nidhi, on January 17, 2021 [Last updated : March 08, 2023]

Copy stack elements into an array in VB.Net

Here, we will use CopyTo() function to copy the elements of the stack into an array from the specified index in the array.

Program/Source Code:

The source code to copy stack elements into the array using collection is given below. The given program is compiled and executed successfully.

VB.Net code to copy stack elements into an array using the collection

'VB.Net program to copy stack elements into 
'an array using the collection.

Imports System
Imports System.Collections

Module Module1
    Sub Main()
        Dim stk As New Stack(5)
        Dim arr(4) As Integer

        stk.Push(40)
        stk.Push(30)
        stk.Push(20)
        stk.Push(10)

        stk.CopyTo(arr, 0)

        Console.WriteLine("Array elements are:")
        For i = 0 To 3 Step 1
            Console.WriteLine(vbTab & "Item[" & (i + 1) & "]: " & arr(i))
        Next
    End Sub
End Module

Output

Array elements are:
        Item[1]: 10
        Item[2]: 20
        Item[3]: 30
        Item[4]: 40
Press any key to continue . . .

Explanation

In the above program, we created a module Module1 that contains the Main() function. The Main() function is the entry point for the program, And, we created an object of Stack collection class for 5 elements. After that, we inserted 4 items using the Push() method into the stack and then we copied the elements of the stack into an integer array "arr" and then print all array elements using the "for" loop on the console screen.

VB.Net Data Structure Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.