How to use For Each loop in VB.NET
The For Each Loop is also called a iterative loop. Whenever you want to repeat a task in programming several time or a given condition in this situation we use loop statements to achieve your desired results. This article defines the For Each Loop that how it repeat a task several time like FOR NEXT Loop, WHILE Loop.
The For Each Loop is a iterative loop. Whenever you want to repeat a task in programming several time or a given condition in this situation we use loop statements to achieve your desired results. This article defines the For Each loop that how it repeat a task several time like For Next loop, While loop.
For Each loop
For loop is a iterative loop. it is used to execute a single item and item in group like every single element in an Array, or every single files in a folder or , every character in a String.
Example
If we want to display every character in the web site name "HTTP://vbdotnetheaven.COM" . In that situation for loop is very useful.
Module Module1
Sub Main()
Dim Name As String
Dim sinChar As Char
Name = "HTTP://vbdotnetheaven.COM" 'Assigning the site name in a variable
For Each sinChar In Name 'This line is extracting the single item from the group
Console.WriteLine(sinChar)
Next
End Sub
End Module
Now you execute this program you will get each character of the string in console window.
Output
Figure 1.
For Each loop with array
For Each loop is also used to work with array elements. the below example defines how to sort the array elements with for each loop.
For example
This example describes that how to sort the array elements.
Module Module1
Sub Main()
Dim num As Integer() = New Integer(4) {}
Console.WriteLine("Enter {0} number : ", num.Length)
For i As Integer = 0 To num.Length - 1
num(i) = Integer.Parse(Console.ReadLine())
Next
Array.Sort(num)
Console.WriteLine("sorted array is :")
For Each n As Integer In num
Console.WriteLine(n)
Next
End Sub
End Module
OUTPUT
Figure 2.