Do Loop


  • Do loop is used to execute a group of statements repeatedly as long as the condition is true or until the condition becomes true.
  • The basic syntax of the Do Loop is given below:
  • Do {while | Until} condition
    [Statements]
    [Exit Do]
    [Statements]
    Loop

    OR

    Do
    [Statements]
    [Exit Do]
    [Statements]
    Loop {While | Until} condition

  • You can understand the concept of Do loop by the following diagram:
  • do-loop

Working with Do Loop


Here we are going to create a project in which we are using a Do loop:


  • Create a new project in Visual Studio 2010 by selecting File -> New Project from the menu bar. In the New Project dialog, select Windows Forms Application from the right-hand pane, enter the project name as DoLoop , and click OK as shown in figure:
  • do-loop

  • Now drag and drop a Button control from the toolbox to the form and change its text property to “ShowOutput” as given below in the diagram:
  • do-loop

  • Double-click the button “ShowOutput” to open the Button1.Click event handler. Add either of the following code to it:
  • Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim number As Integer = 1
    Do While (number <= 5)
    MessageBox.Show(number)
    number = number + 1
    Loop
    or

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim number As Integer = 1
    Do Until (number = 6)
    MessageBox.Show(number)
    number = number + 1
    Loop
    End Sub

  • Now execute the project by pressing F5 key it will open a form as follows:
  • do-loop

  • This will shows message box five times to see them click on the button “ShowOutput” present on the form this will show you a message box as follows:
  • do-loop

  • Now click on Ok button present on the message box this will show another mess box as follows:
  • do-loop

  • Again click on Ok button present on the message box this will show another mess box as follows:
  • do-loop

  • Again click on Ok button present on the message box this will show another mess box as follows:
  • do-loop

  • Again click on Ok button present on the message box this will show another mess box as follows:
  • do-loop

  • Now if you click on the OK button this will not show another message box because loop counter is running from 1 to 5 only.