ARTICLE

Loops in Visual Basic .NET

Posted by Atul Chaudhary Articles | Visual Basic 2010 December 30, 2010
In this article, I will explain you about Loops in Visual Basic .NET
 
Reader Level:

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 

Login to add your contents and source code to this article
share this article :
post comment
 
Nevron Diagram
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Become a Sponsor