5.3. for Repetition Statement

In addition to while, C++ provides the for repetition statement, which specifies the counter-controlled repetition details in a single line of code. To illustrate the power of for, let’s rewrite the program of Fig. 5.1. The result is shown in Fig. 5.2.


 1   // Fig. 5.2: fig05_02.cpp
 2   // Counter-controlled repetition with the for statement.
 3   #include <iostream>
 4   using namespace std;
 5
 6   int main()
 7   {
 8      // for statement header includes initialization,          
 9      // loop-continuation condition and increment.             
10      for ( unsigned int counter = 1; counter <= 10; ++counter )
11         cout << counter << " ";                                
12
13      cout << endl; // output a newline
14   } // end main


1 2 3 4 5 6 7 8 9 10


Fig. 5.2. Counter-controlled repetition with the for statement.

When the for statement (lines 10–11) begins executing, the control variable counter is declared and initialized to 1. Then, the loop-continuation condition (line 10 between the semicolons) counter <= 10 is checked. The initial value of counter is 1, so the condition is satisfied and the body statement (line 11) prints the value of counter, namely 1. Then, the expression ++counter increments control variable counter and the loop begins again with the loop-continuation test. The control variable is now 2, so the final value is not exceeded and the program performs the body statement again. This process continues until the loop body has executed 10 times and the control variable counter is incremented to 11—this causes the loop-continuation test to fail, so repetition terminates. The program continues by performing the first statement after the for statement (in this case, the output statement in line 13).

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

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