Section 6.3. For...Next Repetition Statement


6.3. For...Next Repetition Statement

Section 6.2 presented the essentials of counter-controlled repetition with the While statement. Visual Basic also provides the For...Next repetition statement, which specifies the counter-controlled repetition details in a single line of code. To illustrate the power of For...Next, we rewrite the program of Fig. 6.1 using the For...Next statement in Fig. 6.2.

Figure 6.2. Counter-controlled repetition with the For...Next statement.

  1  ' Fig. 6.2: ForCounter.vb  2  ' Using the For...Next statement for counter-controlled repetition.  3  Module ForCounter  4     Sub Main()  5        ' initialization, repetition condition and               6        ' incrementing are all included in For...Next statement  7        For counter As Integer = 2 To 10 Step 2                  8           Console.Write(counter & " " )                         9        Next                                                    10 11        Console.WriteLine() 12     End Sub ' Main 13  End Module ' ForCounter 

 2 4 6 8 10 



The Main method of the program operates as follows: When the For...Next statement (lines 79) begins its execution, the control variable counter is declared as an Integer and initialized to 2, thus addressing the first two elements of counter-controlled repetitioncontrol variable name and initial value. Next, the implied loop-continuation condition counter <= 10 is tested. The To keyword is required in the For...Next statement. The optional Step keyword specifies the increment (i.e., the amount that is added to counter each time the For...Next body is executed). If Step and the value following it are omitted, the increment defaults to 1. The increment of a For...Next statement could be negative, in which case it is a decrement, and the loop counts downwards.

In this example, the initial value of counter is 2, so the implied condition is satisfied (i.e., true), and the counter's value 2 is output in line 8. The required Next keyword marks the end of the For...Next repetition statement. When the Next keyword is reached, variable counter is incremented by the specified value of 2, and the loop begins again with the loop-continuation test.

At this point, the control variable is equal to 4. This value does not exceed the final value, so the program performs the body statement again. This process continues until the counter value of 10 has been printed and the control variable counter is incremented to 12, causing the (implied) loop-continuation test to fail and repetition to terminate. The program continues by performing the first statement after the For...Next statement. (In this case, method Main terminates, because the program reaches the End Sub statement at line 12.)

Error-Prevention Tip 6.1

Use a For...Next loop for counter-controlled repetition. Off-by-one errors (which occur when a loop is executed for one more or one less iteration than is necessary) tend to disappear, because the terminating value is clear.


For...Next Statement Header Components

Figure 6.3 takes a closer look at the For...Next statement from Fig. 6.2. The first line of the For...Next statement sometimes is called the For...Next header. Note that the For...Next header specifies each of the items needed for counter-controlled repetition with a control variable.

Figure 6.3. For...Next header components.


The general form of the For...Next statement is

 For initialization To finalValue Step increment     statement Next 


where the initialization expression initializes the loop's control variable, finalValue determines whether the loop should continue executing (if the control variable is less than or equal to finalValue) and increment specifies the amount the control variable should be incremented each time through the loop. In most cases, the For...Next statement can be represented by an equivalent While statement, as follows:

 initialization While variable <= finalValue    statement    increment End While 


There is an exception to this rule, which we discuss in Section 6.9.

Note in Fig. 6.3 that the counter variable is both initialized and declared in the For...Next header. The counter variable may be declared before the For...Next statement. For example, the code in Fig. 6.2 could have been written as

 Dim counter As Integer For counter = 2 To 10 Step  2    Console.Write(counter &  " ") Next 


Although both forms are correct, declaring the control variable in the For...Next header is more clear and concise. The difference between the two forms is that if the initialization expression in the For...Next statement header declares the control variable (as we have done in Fig. 6.2), the control variable can be used only in the body of the For...Next statementit will be unknown outside the For...Next statement. This restricted use of the control variable name is known as the variable's scope. The scope of a variable specifies where it can be used in a program. Scope is discussed in detail in Chapter 7, Methods: A Deeper Look. If the control variable is declared before the For...Next statement, it can be used from the point of declaration, inside the control statement and after it as well.

The starting value, ending value and increment portions of a For...Next statement can contain arithmetic expressions. The expressions are evaluated once (when the For...Next statement begins executing) and used as the starting value, ending value and increment of the For...Next statement's header. For example, assume that value1 = 2 and value2 = 10. The header

 For j As Integer = value1 To 4 * value1 * value2 Step value2 \ value1 


is equivalent to the header

 For j As Integer = 2 To 80 Step 5 


If the loop-continuation condition is initially false (e.g., if the starting value is greater than the ending value and the increment is positive), the For...Next's body is not performed. Instead, execution proceeds with the first statement after the For...Next statement.

The control variable frequently is printed or used in calculations in the For...Next body, but it does not have to be. It is common to use the control variable exclusively to control repetition and never mention it in the For...Next body.

Common Programming Error 6.1

Counter-controlled loops should not be controlled with floating-point variables. Floating-point values are represented only approximately in memory; this can lead to imprecise counter values and inaccurate tests for termination.


Error-Prevention Tip 6.2

Although the value of the control variable can be changed in the body of a For...Next loop, avoid doing so, because this practice can lead to subtle errors.


Common Programming Error 6.2

In nested For...Next loops, the use of the same control-variable name in more than one loop is a compilation error.


For Statement UML Activity Diagram

The activity diagram for the For...Next statement is similar to that of the While statement (Fig. 5.5). For example, the activity diagram of the For...Next statement

 For counter As Integer = 1 To 10    Console.WriteLine(counter) Next 


is shown in Fig. 6.4. This activity diagram makes it clear that the initialization occurs only once and that incrementing occurs after each execution of the body statement. Note that (besides an initial state, transition arrows, a merge, a final state and several notes) the diagram contains only action states and a decision.

Figure 6.4. For...Next repetition statement activity diagram.




Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net