For Loop
The For loop is the most popular loop. For loops enable us to execute a series of expressions multiple numbers of times. The For loop in VB .NET needs a loop index which counts the number of loop iterations as the loop executes. The syntax for the For loop looks like this:
For index=start to end[Step step]
[statements]
[Exit For]
[statements]
Next[index]
The index variable is set to start automatically when the loop starts. Each time in the loop, index is incremented by step and when index equals end, the loop ends.
Example on For loop
Module Module1
Sub Main()
Dim d As Integer
For d = 0 To 2
System.Console.WriteLine("In the For Loop")
Next d
End Sub
End Module
The image below displays output from above code.

While loop
While loop keeps executing until the condition against which it tests remain true. The syntax of while loop looks like this:
While condition
[statements]
End While
Example on While loop
Module Module1
Sub Main()
Dim d, e As Integer
d = 0
e = 6
While e > 4
e -= 1
d += 1
End While
System.Console.WriteLine("The Loop ran " & e & "times")
End Sub
End Module
The image below displays output from above code.

Do Loop
The Do loop can be used to execute a fixed block of statements indefinite number of times. The Do loop keeps executing it's statements while or until the condition is true. Two keywords, while and until can be used with the do loop. The Do loop also supports an Exit Do statement which makes the loop to exit at any moment. The syntax of Do loop looks like this:
Do[{while | Until} condition]
[statements]
[Exit Do]
[statements]
Loop
Example on Do loop
Module Module1
Sub Main()
Dim str As String
Do Until str = "Cool"
System.Console.WriteLine("What to do?")
str = System.Console.ReadLine()
Loop
End Sub
End Module
The image below displays output from above code.

No comments:
Post a Comment