While…End While Loop


  • While…End While Loop repeatedly executes a set of statement as long as a specified condition is true.
  • While statement always checks the condition first before executing the statements present in loop-body. When the control reaches the End While statement, the control is passed back to the While statement. If condition is still true, the statements inside the loop body are executed else exits the loop.
  • Like for..Next loop it also checks the condition before executing the Loop-Body but its syntax is different from for..Next loop.
  • It is also called as entry level looping statement because here condition is checked first then enters into the loop.
  • The basic syntax of While.. End While Loop is as follows:
  • While condition
    [Statements]
    End While

  • You can understand the concept of While..End While loop by the following diagram:
  • while-end-loop

Working with While..End While Loop


Here we are going to create a project in which we are using a While..End While 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 While..EndWhileLoop , and click OK as shown in figure: while-end-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:
  • while-end-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
    While number <= 5
    MessageBox.Show(number)
    number = number + 1
    End While
    End Sub

  • Now execute the project by pressing F5 key it will open a form as follows:
  • while-end-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:
  • while-end-loop

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

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

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

  • Again click on Ok button present on the message box this will show another message box as follows:
  • while-end-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.