For..Next Loop


  • For..Next Loop is used to execute a group of statements repeatedly for a specified number of times.
  • For..Next loop enables the user to execute a block of statement repeatedly until a certain condition gets false.
  • for..Next loop is suitable for the situations where we exactly know how many time we have to execute the statements within the body of loop.
  • In for..Next loop condition is always checked before the execution of the Loop-Body.
  • It is also called as entry level looping statement because here condition is checked first then enters into the loop.
  • Next statement in For..Next loop increments the value of loop-counter.
  • The basic syntax of For..Next loop is given here:
  • For counter [As datatype] = start To end [Step step]
    [Statements]
    [Exit For]
    [Statements]
    Next[counter]

  • You can understand the concept of For..Next loop by the following diagram:
  • for-next-loop

Working with For..Next loop


Here we are going to create a project in which we are using a For..Next 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 For..Next Loop , and click OK as shown in figure:
  • for-next-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:
  • for-next-loop

  • Double-click the button “ShowOutput” to open the Button1.Click event handler. Add the following given code to it:
  • Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim number As Integer
    For number = 1 To 5
    MessageBox.Show(number)
    Next
    End Sub

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

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

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

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

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