Visual Basic .NET - Do Loop

In VB.NET, a Do Loop is a control statement that allows you to execute a block of code repeatedly until a certain condition is met. There are two types of Do Loop statements: Do While Loop and Do Until Loop. The Do While Loop executes the block of code while a condition is True, whereas the Do Until Loop executes the block of code until a condition becomes True.

Flow:

  • The Do While Loop starts by checking the condition, and if the condition is true, it executes the block of code inside the loop.
  • The loop continues to execute the code until the condition becomes false.
  • The Do Until Loop starts by checking the condition, and if the condition is false, it executes the block of code inside the loop.
  • The loop continues to execute the code until the condition becomes true.
' Do While Loop
Do While condition
    ' Code to be executed
Loop

' Do Until Loop
Do Until condition
    ' Code to be executed
Loop

Examples:

Do While Loop to print numbers from 1 to 5.

Dim i As Integer = 1
Do While i <= 5
    Console.WriteLine(i)
    i += 1
Loop

Do Until Loop to print numbers from 10 to 1.

Dim i As Integer = 10
Do Until i = 0
    Console.WriteLine(i)
    i -= 1
Loop

In both examples, the loop condition is checked at the beginning of each iteration, and the loop continues until the condition is no longer true for the Do While Loop or is true for the Do Until Loop.