Making a Program Repeat Actions: Looping with the For...Next Loop
Updated: April 2009
In this lesson, you will learn how to use the For...Next statement to repeat actions in your program, and to count how many times these actions have been performed.
When you write a program, you frequently need to repeat actions. For example, suppose you are writing a method that displays a series of numbers on screen. You will want to repeat the line of code that displays the numbers as many times as necessary.
The For...Next loop allows you to specify a number, and then repeat code contained within that loop for the specified number of times. The following example shows how a For...Next loop appears in code.
The For...Next loop begins with a counter variable, i. This is a variable that the loop uses to count the number of times it has executed. The next line (For i = 1 to 10) tells the program how many times to repeat the loop and the values i is going to have.
When the code enters the For...Next loop, it starts with i containing the first value (in this case 1). The program then executes the lines of code between the For line and the Next line, in this case calling the DisplayNumber method with a parameter of i (in this case also 1).
When the line Next is reached, 1 is added to i and program execution jumps back to the For line again. This repeats until the value of i is larger than the second number in the For line, in this case 10. When this occurs, the program continues with any code after the Next line.
To use the For...Next statement
On the File menu, choose New Project.
In the New Project dialog box, in the Templates pane, click Windows Application.
In the Name box, type ForNext and then click OK.
A new Windows Forms project opens.
From the Toolbox, drag one TextBox control and one Button control onto the form.
Double-click the Button to open the Code Editor
In the Button1_Click event handler, type the following code:
Press F5 to run the program.
In the text box, type a number and click the button.
A message box appears as many times as you indicated in the text box.
If you want to stop the program before the end of the loop is reached, on the Debug menu, click Stop Debugging.
In this topic, you have learned how to use the For...Next loop to repeat code a specified number of times. At this point, you can either go on to the next lesson in the series, Making a Program Choose Between Two Possibilities: The If...Then Statement or you can explore another kind of looping in Closer Look: Using Do...While and Do...Until to Repeat Until a Condition Is Met.