Loops in VB.NET: For Each, Do While, While End, For Next

Loops in VB.NET: The use of Loop is done for repeating any same process multiple times till the specified condition in a program is fulfilled. A Loop provides the programmer the authority to repeat multiple no. of statements up to the required no. of repetitions. The statements in program can be repeated according to suitability and requirement of the loop by the programmer. This helps in minimizing the program complexity and helps to understand and debug the program easily.

Types of Loops

Different types of Loop are available in VB.NET:

  1. For Each Loop
  2. Do While Loop
  3. While End Loop
  4. For Next Loop

1. For Each Loop

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

With the help of Each Loop, it becomes easier to work with collection objects like the lists, layouts, etc., by executing each item for the arrays or the group. And when the repetition of each item in the list or collection is completed, control is transmitted to the further statement.

What is For Each?

For Each is the command of Loops. These statements could be used whenever a duplicate set of everything is required. The contents can be easily managed in collection or list with the help of this loop.

Syntax:

For each var_nameAs [DataType] In Collection_Object
[Statements to be executed]
Next

For Each loop is used to read each item from the collection object or from the arrays. The data type represents a variable type, and the var_name is a variable name to access items from the same members or group to be used in the body of each loop.

Flowchart for each loop

The flowchart represents the performance of each subsequent loop in order to adjust the programmed objects in the VB.NET programming language.

Loops 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. The availability of the elements is verified with the help of Variables in the For Each Loop. The execution of For Each Loop will be done till the condition remains True.The control is shifted to end statement after executing every item of the array.

Example:-

  1. Write a program that prints Vegetables names and uses VB.NET Loop.

INPUT:

Imports System
      Module For_Each_loop
      SubMain()
    ' The input array.
      DimVegetables() AsString = {"Potato",
      "Tomato",
      "Carrot",
      "Raddish"}
       ' Loop over each element with For Each.
       ForEach Vegetable AsStringIn Vegetables
       Console.WriteLine(Vegetable)
       Next
       EndSub
       EndModule

Output:

Loops in VB.NET

2. Write a simple program that uses of For Each Next loop in VB.NET.

INPUT

 Imports System
ModuleFor_Each_loop
SubMain()
'declare and initialize an array as integer 
DimAn_array() AsInteger = {4, 8, 12, 16, 20}
DimiAsInteger'Declarei as Integer 
ForEachiInAn_array
Console.WriteLine(" Value of i is {0}", i)
Next
Console.WriteLine("Press any key to exit...")
Console.ReadLine()
EndSub
EndModule

Output:

Loops in VB.NET

2. Do While Loop

In VB.NET, Do While loop is used to execute blocks of statements in the program, as long as the condition remains true. The loop at first checks the specified state, if the condition is true, a loop statement is made. While in the Do loop, as opposed to a while loop, it means it uses Do statements, and then checks the status.

Syntax:

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

The syntax above describes how the Do keyword follows the block of statements, on the other hand While Keyword verifies Boolean_expression when the first Do statement is executed.

Flowchart of Do loop

Loops in VB.NET

This Flowchart shows the Do While Loop flow. In this, the flow of statements is controlled in such a way that the statement is executed once before verifying the While and Until condition. When condition is True, the similar task will be executed tillcondition becomes false.

Example:-

Write a program to print the numbers from 5 to 15 with the use of Do While Loop.

INPUT:

Imports System
ModuleDo_loop
SubMain()
' Initialization and Declaration of variable i
Dim a AsInteger = 5
Do
' Executes the following Statement 
Console.WriteLine(" Value of Variable a is : {0}", a)
a = a + 1 'Increment the variable a by 1 
LoopWhile a <= 15 ' Define the While Condition 
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
EndSub
EndModule

Output:

Loops in VB.NET

Nested Do While Loop Statement

In the Nested Do While Loop, a Do While Loop is used in the body of the other Do While Loop. This is called a Nested Do While Statement.

Syntax

Do
// Statement of the outer loop  
Do  
// Statement of outer loop  
While (condition -2)  
// Statement of outer loop  
While (condition -1)  

Example:-

Write a program using the Nested Do While Loop.

INPUT

Imports System
ModuleNest_Do_While
SubMain()
' Declare a and b as Integer variable 
Dim a AsInteger = 1
Do
' Outer loop statement 
Console.WriteLine(" Execution of Outer loop is {0}", a &" times")
Dim b AsInteger = 1
Do
'Inner loop statement 
Console.WriteLine(" Execution of Inner loop is {0}", b)
b = b + 1 ' Increment Inner Counter variable by 1 
LoopWhile b < 2
Console.WriteLine()
a = a + 1 ' Increment Outer Counter variable by 1 
LoopWhile a < 3
Console.WriteLine(" Exit from the loop")
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
EndSub
EndModule

Output:

Loops in VB.NET

3. While End Loop

In While End loop, the execution of code blocks or the whole statement is performed till the condition provided is true. It is helpful when block executions count is unknown. Also called as an entry-controlled loop statement, which suggests we first check all loop conditions. If the condition is correct, a while loop body is performed. The repetition of execution is performed till the condition is true. The control will be moved out of the loop, when the condition is False.

Syntax:

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

When the logical condition is true, then the execution of the single or block of statements defined inside the body of the while loop is performed.

Flow Diagram of the While End Loop in VB.NET

Loops in VB.NET

The While End loop is an entry-controlled loop. It is used inevaluating theconditions. Statements explainedin the body of the loop are created and the procedure continues till the condition is fulfilled. The value of the variable counter also increases on every iteration.The statements within the loop will be executed when the condition is true and if condition is False,the control will be moved to the end part of the loop.

Example:-

1. Write a program to print a number from 5 to 15 with the use of While End Loop.

INPUT

Imports System
Modulewhile_number
SubMain()
'declare x as an integer variable 
Dim x AsInteger
x = 5
' Use While End condition 
While x <= 15
'If the condition is true, the statement will be executed. 
Console.WriteLine(" Value {0}", x)
x = x + 1 ' Statement that change the value of the condition 
EndWhile
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
EndSub
EndModule

Output:

Loops in VB.NET

Nested While End Loop

In VB.NET, when we write a While End loop inside the body of another While End loop, it is called Nested While End loop.

Syntax

While (condition -1)  
// body of the outer while loop  
While (condition -2)  
// body of inner while loop  
End While  
// body of the outer loop  
End While  

Example:-

Write a program to show the use of Nested While End Loop.

INPUT

Imports System
ModuleNest_While
SubMain()
' Declare a and b as Integer variable 
Dim a AsInteger = 2
While a < 6
' Outer loop statement 
Console.WriteLine(" Counter value of Outer loop is {0}", a)
Dim b AsInteger = 2
While b < 2
'Inner loop statement 
Console.WriteLine(" Counter value of Inner loop is {0}", b)
b = b + 1 ' Increment Inner Counter variable by 1 
EndWhile
Console.WriteLine() 'print space 
a = a + 1   ' Increment Outer Counter variable by 1 
EndWhile
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
EndSub
EndModule

Output:

Loops in VB.NET

4. For Next Loop

In this loop, the execution of a series of code or a code block is performed till the required condition is satisfied. The use of this loop is beneficial in situation where we know how often the code block should be executed. The For loop is also known as For Next Loop in VB.NET.

Syntax

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

Flowchart: 

The representation of functioning of For Next Loop in the VB.NET is depicted in this flowchart.

Loops in VB.NET

In the flowchart above, firstly the initialization of variable with the start value is performed. Secondly, the comparison of variables and end values are shown.

If the condition is true, the execution of the statements is performed. Then, an automatic surge in value of variable is done by the compiler. Finally, the present value of variable will be re-compared with the last expression at the end of every iteration. The control exits the loop when the condition is False.

Example:-

Write a program to show the use of For Next Loop.

ModuleFor_Next_Loop
SubMain()
DimArray() AsInteger = {9, 12, 3, 6, 13}
Dim value AsInteger
ForEach value In Array
Console.WriteLine(value)
Next
Console.ReadKey()
EndSub
EndModule

Output

Loops in VB.NET

Advantages of VB.NET loop

  • Loop provides the functionality of code iteration within a program.
  • The Loops is used in execution of statement until the condition provided is True.
  • With the help of Loop, size of the code can be reduced.
  • Loop also helps in reducing the compile time.