6.2 Essentials of Counter-Controlled Iteration

This section uses the while iteration statement introduced in Chapter 5 to formalize the elements of counter-controlled iteration:

  1. a control variable (or loop counter),

  2. the control variable’s initial value,

  3. the control variable’s increment that’s applied during each iteration of the loop,

  4. the loop-continuation condition that determines if looping should continue.

Consider the application of Fig. 6.1, which uses a loop to display the numbers from 1 through 10.

Fig. 6.1 Counter-controlled iteration with the while iteration statement.

Alternate View

  1    // Fig. 6.1: WhileCounter.cs
  2    // Counter-controlled iteration with the while iteration statement.
  3    using System;
  4
  5    class WhileCounter
  6    {
  7       static void Main()
  8       {
  9          int counter = 1; // declare and initialize control variable
 10
 11          while (counter <= 10) // loop-continuation condition
 12          {
 13             Console.Write($"{counter} ");
 14             ++counter; // increment control variable
 15          }
 16
 17          Console.WriteLine();
 18      }
 19    }

1   2    3    4   5   6   7   8    9   10

In Fig. 6.1, the elements of counter-controlled iteration are defined in lines 9, 11 and 14. Line 9 declares the control variable (counter) as an int, reserves space for it in memory and sets its initial value to 1.

Line 13 displays control variable counter’s value per iteration of the loop. Line 14 increments the control variable by 1 for each iteration of the loop. The while’s loop-continuation condition (line 11) tests whether the value of the control variable is less than or equal to 10 (the final value for which the condition is true). The program performs the while’s body even when the control variable is 10. The loop terminates when the control variable exceeds 10 (that is, when counter becomes 11).

Error-Prevention Tip 6.1

Floating-point values are approximate, so controlling counting loops with floating-point variables of types float or double can result in imprecise counter values and inaccurate tests for termination. Use integer values to control counting loops.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset