VB.net Loops – For Each, Do While, While End, For Next

What is VB.net Loops?

A VB.net Loops or looping statement is used to repeat the same process multiple times until it meets the specified condition in a program.

By using a loop in a program, a programmer can repeat any number of statements up to the desired number of repetitions.

There can be instances where you need to run a block of code repeatedly.

The first statement in a function is executed first, then the second, and so on. In general, statements are executed in order.

The general form of a loop statement in most programming languages is as follows. A loop statement allows us to run a statement or collection of statements several times.

VB.net Loops Flow Chart:

VB NET Loops Diagram
VB NET Loops Diagram

Types of Loop in VB.net

VB.net provides the following types of loops to handle looping requirements.

Loop Types in VB.netDescription
Do LoopIt repeats the enclosed block of statements while a Boolean condition is True or until the condition becomes True. It could be terminated at any time with the Exit Do statement.
For…NextIt repeats a group of statements a specified number of times and a loop index counts the number of loop iterations as the loop executes.
For Each…NextIt repeats a group of statements for each element in a collection. This loop is used for accessing and manipulating all elements in an array or a VB.Net collection.
While… End WhileIt executes a series of statements as long as a given condition is True.
Types of Loop in VB.net

Do Loop in VB.net

The Do While loop In VB.NET is used to execute blocks of statements in the program, as long as the condition remains true.

It is similar to the While End Loop, but there is a slight difference between them.

The while loop initially checks the defined condition, if the condition becomes true, the while loop’s statement is executed.

Whereas in the Do loop, is the opposite of the while loop, which means that it executes the Do statements, and then it checks the condition.

Syntax:

Do  
[ Statements to be executed]  
Loop While Boolean_expression  
// or  
Do   
[Statement to be executed]  
Loop Until Boolean_expression  

In the above syntax, the Do keyword follows a block of statements, and the While keyword checks Boolean_expression after the execution of the first Do statement.

Data Flow Diagram:

Do Loop Data Flow Diagram in VB NET
Do Loop Data Flow Diagram in VB NET

The above flow chart represents the flow of the Do While loop.

It is used to control the flow of statements, such that it executes the statement at least once before checking the While or Until condition.

If the condition is true, the next iteration will be executed till the condition becomes false.

Example Program of Do Loop in VB.net

Example 1. Write a simple program to print a number from 1 to 10 using the Do While loop in VB.net.

Imports System  
Module Do_loop  
    Sub Main()  
        ' Initializatio and Declaration of variable i  
        Dim i As Integer = 1  
        Do  
            ' Executes the following Statement  
            Console.WriteLine(" Value of variable I is : {0}", i)  
            i = i + 1 'Increment the variable i by 1  
        Loop While i <= 10 ' Define the While Condition  
  
        Console.WriteLine(" Press any key to exit...")  
        Console.ReadKey()  
    End Sub  
End Module  

When the above code is compiled and executed, it produces the following result:

Value of variable I is : 1
Value of variable I is : 2
Value of variable I is : 3
Value of variable I is : 4
Value of variable I is : 5
Value of variable I is : 6
Value of variable I is : 7
Value of variable I is : 8
Value of variable I is : 9
Value of variable I is : 10
Press any key to exit…

In the above program, the Do While loop executes the body until the given condition becomes false.

When the condition becomes false the loop will be terminated.

You can test the above example here! ➡ VB.net Online Compiler

For the Next Loop in VB.net

A For Next loop in VB.net is used to repeatedly execute a sequence of code or a block of code until a given condition is satisfied.

A For loop is useful in such a case when we know how many times a block of code has to be executed. In VB.NET, the For loop is also known as For Next Loop.

Syntax:

'syntax of for next loop'

For variable_name As [ DataType ] = start To end [ Step step ]  
[ Statements to be executed ]  
Next  

Let’s Understand the Next Loop in Detail.

  1. For: It is the keyword that is present at the beginning of the definition.
  1. variable_name: It is a variable name, which is required in the For loop Statement. The value of the variable determines when to exit from the For-Next loop, and the value should only be numeric.
  1. [Data Type]: It represents the Data Type of the variable_name.
  1. start To end: The start and end are the two important parameters representing the initial and final values of the variable_name.
    • These parameters are helpful while the execution begins, the initial value of the variable is set by the start. Before the completion of each repetition, the variable’s current value is compared with the end value.
    • And if the value of the variable is less than the end value, the execution continues until the variable’s current value is greater than the end value. And if the value is exceeded, the loop is terminated.
  1. Step: A step parameter is used to determine by which the counter value of a variable is increased or decreased after each iteration in a program. If the counter value is not specified; It uses 1 as the default value.
  1. Statements: A statement can be a single statement or group of statements that execute during the completion of each iteration in a loop.
  1. Next: In VB.net a Next is a keyword that represents the end of the For loop’s

Data Flow Diagram:

For Next Loop Data Flow Diagram in VB NET
For Next Loop Data Flow Diagram in VB NET

In the above flow chart, the first step is to initialize the variable name with the start value.

Then, the value of the variable will be compared to the end expression or value.

If the condition is true, the control enters the loop body and executes the statements.

After that, the value of a variable will be automatically incremented by the compiler.

Upon completion of each iteration, the current value of a variable will be again compared to the end expression. If the condition is not true, the controlled exit from the loop.

Example Program of For Next Loop in VB.net

Example 1. Write a simple program to print the number from 1 to 10 using the For Next loop.

Imports System  
Module Number  
    Sub Main()  
        ' It is a simple print statement, and 'vbCrLf' is used to jump in the next line.  
        Console.Write(" The number starts from 1 to 10 " & vbCrLf)  
        ' declare and initialize variable i  
        For i As Integer = 1 To 10 Step 1  
            ' if the condition is true, the following statement will be executed  
            Console.WriteLine(" Number is {0} ", i)  
            ' after completion of each iteration, next will update the variable counter  
        Next  
        Console.WriteLine(" Press any key to exit... ")  
        Console.ReadKey()  
    End Sub  
End Module

When the above code is compiled and executed, it produces the following result:

The number starts from 1 to 10
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10
Press any key to exit…

In the above example, we have initialized an integer variable i with an initial value of 1.

The For loop will continuously execute its body until the value of i is smaller or equal to 10.

After each iteration, the value of i is automatically increased with ‘Step 1‘.

If the value of i reached 10, the loop would be terminated, and the control transfer to the Main() function.

You can test the above example here! ➡ VB.net Online Compiler

For Each Loop in VB.net

For Each loop In the VB.net is used to iterate a block of statements in an array or collection of objects.

Using For Each loop, we can easily work with collection objects such as lists, arrays, etc., to execute each element of an array or in a collection.

When iteration through each element in the array or collection is complete, the control is transferred to the next statement to end the loop.

Syntax:

'syntax of for each loop'

For Each var_name As [ DataType ] In Collection_Object  
[ Statements to be executed]  
Next  

For Each loop is used to read each element from the collection object or an array.

The Data Type represents the type of the variable, and var_name is the name of the variable to access elements from the array or collection object so that it can be used in the body of For Each loop.

Data Flow Diagram:

For Each Loop Data Flow Diagram in VB NET
For Each Loop Data Flow Diagram in VB NET

The first step is to initialize an array or collection object to execute each element of the array with the help of variables in For Each loop.

A variable is used in For Each loop to check whether the element is available or not.

If the element is available in the collection object, the For Each block will be executed until the condition remains true.

After the execution of each element of an array, the control transfers to the end statement.

Example Program of For Each Loop in VB.net

Example 1: Write a simple program to understand the uses of For Each Next loop in VB.net.

Imports System  
Module For_Each_loop  
    Sub Main()  
        'declare and initialize an array as integer  
        Dim An_array() As Integer = {1, 2, 3, 4, 5}  
        Dim i As Integer 'Declare i as Integer  
  
        For Each i In An_array  
            Console.WriteLine(" Value of i is {0}", i)  
        Next  
        Console.WriteLine("Press any key to exit...")  
        Console.ReadLine()  
    End Sub  
End Module  

When the above code is compiled and executed, it produces the following result:

Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
Value of i is 5
Press any key to exit…

In the above example, we create an integer array with the name An_array (), and For Each loop is used to iterate each element of the array with the help of the defined variable ‘i‘.

You can test the above example here! ➡ VB.net Online Compiler

While End Loop in VB.net

The While End loop in VB.net is used to execute blocks of code or statements in a program, as long as the given condition is true. It is useful when the number of executions of a block is not known.

It is also known as an entry-controlled loop statement, which means it initially checks all loop conditions. If the condition is true, the body of the while loop is executed.

This process of repeated execution of the body continues until the condition is not false. And if the condition is false, control is transferred out of the loop.

Syntax:

'syntax of while end loop'

While [condition]  
    [ Statement to be executed ]  
End While  

Here, the condition represents any Boolean condition, and if the logical condition is true, the single or block of statements defined inside the body of the while loop is executed.

Data Flow Diagram:

While End Loop Data Flow Diagram in VB NET
While End Loop Data Flow Diagram in VB NET

As we know, the While End loop is an entry-controlled loop used to determine if the condition is true, the statements defined in the body of the loop are executed, and the execution process continues till the condition is satisfied.

Furthermore, after each iteration, the value of the counter variable is incremented.

It again checks whether the defined condition is true; And if the condition is again true, the body of the While loop is executed.

And when the condition is not true, the control is transferred to the end of the loop.

Example Program of While End Loop in VB.net:

Example 1: Write a simple program to print the number from 1 to 10 using the While End loop in VB.net.

Imports System  
Module while_number  
    Sub Main()  
        'declare x as an integer variable  
        Dim x As Integer  
        x = 1  
        ' Use While End condition  
        While x <= 10  
            'If the condition is true, the statement will be executed.  
            Console.WriteLine(" Number {0}", x)  
            x = x + 1 ' Statement that change the value of the condition  
        End While  
        Console.WriteLine(" Press any key to exit...")  
        Console.ReadKey()  
    End Sub  
End Module  

When the above code is compiled and executed, it produces the following result:

Number 1
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 8
Number 9
Number 10
Press any key to exit…

In the above example, while loop executes its body or statement up to the defined state (i <= 10). When the value of the variable i is 11, the defined condition will be false; the loop will be terminated.

You can test the above example here! ➡ VB.net Online Compiler

Summary

For this tutorial, we already discussed the different types of Loops in VB.net and their meanings, examples, and uses in different ways.

VB.net loop structures allow you to run one or more lines of code repetitively.

You can repeat the statements in a loop structure until a condition is True until a condition is False, a specified number of times, or once for each element in a collection.


Leave a Comment