Loops in Visual Basic .NET

In this article, I will explain you about Loops in Visual Basic .NET.
  • 4243

In this article, I will explain you about Loops in Visual Basic .NET

For Loop

For loop enables you to execute a block of statements a certain number of times. The For loop in Visual Basic .NET requires you to provide a top index, a bottom index which counts the number of loop iterations as the loop executes. Each time in the top index is incremented by step and when top index is equal to bottom index, the loop ends. It is a powerful and expressive way to iterate through numbers.

Example:

Imports System.Console
Module Module1
 
    Sub Main()
        Dim A As Integer
        For A = 0 To 4
            System.Console.WriteLine("This is For Loop")
        Next A
        Read()
    End Sub
 
End Module

The Output of above program is:

Output1.gif

While Loop


The while loop is a very clear loop structure, but until the condition against which it tests is remain true While loop keep executing. Some time it can lead to infinite loops if you are not careful.

Example:

Imports System.Console
Module Module1
 
    Sub Main()
        Dim A, B As Integer
        A = 0
        B = 6
        While B > 5
            B -= 1
            A += 1
        End While
        System.Console.WriteLine("The While Loop rans " & B & " times")
        Read()
    End Sub
 
End Module

The Output of above program is:

Output2.gif

Do Loop

When we want to execute a fixed block of expression indefinite number of time then we use Do loop. While or until the condition in the expression is true, the Do loop keeps executing the expression. While and Until are the two keywords which we use with the do loop, Exit Do statement is use to exit the loop at any moment.

Example:

Imports System.Console
Module Module1
 
    Sub Main()
        Dim arr As String
        Do Until arr = "Atul"
            System.Console.WriteLine("What are you doing")
        Loop
        Read()
    End Sub
 
End Module

The Output of above program is:

Output3.gif

Summary

I hope this article help you to understand about Loops in Visual Basic .NET

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.