Section 6.2. Essentials of Counter-Controlled Repetition


6.2. Essentials of Counter-Controlled Repetition

This section uses the While repetition statement introduced in Chapter 5 to highlight the elements required to perform counter-controlled repetition. Counter-controlled repetition requires

  1. the name of a control variable (or loop counter) that is used to determine whether the loop continues to iterate

  2. the initial value of the control variable

  3. the increment (or decrement) by which the control variable is modified each time through the loop

  4. the condition that tests for the final value of the control variable (i.e., whether looping should continue)

The example in Fig. 6.1 uses the four elements of counter-controlled repetition to display the even integers in the range 210. The declaration in line 5 names the control variable (counter), indicates that it is of type Integer, reserves space for it in memory and sets it to an initial value of 2.

Figure 6.1. Counter-controlled repetition with the While...End While statement.

  1  ' Fig. 6.1: WhileCounter.vb  2  ' Using the While statement to demonstrate counter-controlled repetition.  3  Module WhileCounter  4     Sub Main()  5        Dim counter As Integer = 2 ' name and initialize loop counter  6  7        While counter <= 10 ' test final value of loop counter  8           Console.Write(counter & " ")                         9           counter += 2 ' increment counter                    10        End While                                              11 12        Console.WriteLine() 13     End Sub ' Main 14  End Module ' WhileCounter 

 2 4 6 8 10 



Consider the While statement (lines 710). Line 8 displays the current value of counter, and line 9 increments the control variable by 2 to prepare for the next iteration (repetition) of the loop. The loop-continuation condition in the While statement (line 7) tests whether the value of the control variable is less than or equal to 10the final value for which the condition is true. The body of the While is performed even when the control variable is 10. The loop terminates when the control variable exceeds 10 (i.e., when counter becomes 12, because the loop is incrementing by 2 each time).



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