Section 6.8. The for Loop Statement


6.8. The for Loop Statement

The syntactic form of a for statement is

      for (init-statement condition; expression)            statement 

The init-statement must be a declaration statement, an expression statement, or a null statement. Each of these statements is terminated by a semicolon, so the syntactic form can also be thought of as

      for (initializer; condition; expression)            statement 

although technically speaking, the semicolon after the initializer is part of the statement that begins the for header.

In general, the init-statement is used to initialize or assign a starting value that is modified over the course of the loop. The condition serves as the loop control. As long as condition evaluates as true, statement is executed. If the first evaluation of condition evaluates to false, statement is not executed. The expression usually is used to modify the variable(s) initialized in init-statement and tested in condition. It is evaluated after each iteration of the loop. If condition evaluates to false on the first iteration, expression is never executed. As usual, statement can be either a single or a compound statement.

Exercises Section 6.7

Exercise 6.11:

Explain each of the following loops. Correct any problems you detect.

      (a) string bufString, word;          while (cin >> bufString >> word) { /* ... */ }      (b) while (vector<int>::iterator iter != ivec.end())          {/*... */ }      (c) while (ptr = 0)              ptr = find_a_value();      (d) while (bool status = find(word))          { word = get_next_word(); }          if (!status)               cout << "Did not find any words\n"; 

Exercise 6.12:

Write a small program to read a sequence of strings from standard input looking for duplicated words. The program should find places in the input where one word is followed immediately by itself. Keep track of the largest number of times a single repetition occurs and which word is repeated. Print the maximum number of duplicates, or else print a message saying that no word was repeated. For example, if the input is

      how, now now now brown cow cow 

the output should indicate that the word "now" occurred three times.

Exercise 6.13:

Explain in detail how the statement in the while loop is executed:

      *dest++ = *source++; 


Using a for Loop

Given the following for loop, which prints the contents of a vector,

      for (vector<string>::size_type ind = 0;                    ind != svec.size(); ++ind) {          cout << svec[ind]; // print current element          // if not the last element, print a space to separate from the next one          if (ind + 1 != svec.size())             cout << " ";      } 

the order of evaluation is as follows:

1.

The init-statement is executed once at the start of the loop. In this example, ind is defined and initialized to zero.

2.

Next, condition is evaluated. If ind is not equal to svec.size(), then the for body is executed. Otherwise, the loop terminates. If the condition is false on the first trip, then the for body is not executed.

3.

If the condition is true, the for body executes. In this case, the for body prints the current element and then tests whether this element is the last one. If not, it prints a space to separate it from the next element.

4.

Finally, expression is evaluated. In this example, ind is incremented by 1.

These four steps represent the first iteration of the for loop. Step 2 is now repeated, followed by steps 3 and 4, until the condition evaluates to falsethat is, when ind is equal to svec.size().

It is worth remembering that the visibility of any object defined within the for header is limited to the body of the for loop. Thus, in this example, ind is inaccessible after the for completes.



6.8.1. Omitting Parts of the for Header

A for header can omit any (or all) of init-statement, condition, or expression.

The init-statement is omitted if an initialization is unnecessary or occurs elsewhere. For example, if we rewrote the program to print the contents of a vector using iterators instead of subscripts, we might, for readability reasons, move the initialization outside the loop:

      vector<string>::iterator iter = svec.begin();      for( /* null */ ; iter != svec.end(); ++iter) {          cout << *iter; // print current element          // if not the last element, print a space to separate from the next one          if (iter+1 != svec.end())              cout << " ";      } 

Note that the semicolon is necessary to indicate the absence of the init-statement more precisely, the semicolon represents a null init-statement.

If the condition is omitted, then it is equivalent to having written true as the condition:

      for (int i = 0; /* no condition */ ; ++i) 

It is as if the program were written as

      for (int i = 0; true ; ++i) 

It is essential that the body of the loop contain a break or return statement. Otherwise the loop will execute until it exhausts the system resources. Similarly, if the expression is omitted, then the loop must exit through a break or return or the loop body must arrange to change the value tested in the condition:

      for (int i = 0; i != 10; /* no expression */ ) {         // body must change i or the loop won't terminate      } 

If the body doesn't change the value of i, then i remains 0 and the test will always succeed.

6.8.2. Multiple Definitions in the for Header

Multiple objects may be defined in the init-statement; however, only one statement may appear, so all the objects must be of the same general type:

      const int size = 42;      int val = 0, ia[size];      // declare 3 variables local to the for loop:      // ival is an int, pi a pointer to int, and ri a reference to int      for (int ival = 0, *pi = ia, &ri = val;            ival != size;            ++ival, ++pi, ++ri)                    // ... 

Exercises Section 6.8.2

Exercise 6.14:

Explain each of the following loops. Correct any problems you detect.

      (a) for (int *ptr = &ia, ix = 0;                ix != size && ptr != ia+size;                ++ix, ++ptr)   { /* ... */ }      (b) for (; ;) {                if (some_condition) return;                // ...          }      (c) for (int ix = 0; ix != sz; ++ix) { /* ... */ }          if (ix != sz)               // ...      (d) int ix;          for (ix != sz; ++ix) { /* ... */ }      (e) for (int ix = 0; ix != sz; ++ix, ++ sz) { /* ... */ } 

Exercise 6.15:

The while loop is particularly good at executing while some condition holds; for example, while the end-of-file is not reached, read a next value. The for loop is generally thought of as a step loop: An index steps through a range of values in a collection. Write an idiomatic use of each loop and then rewrite each using the other loop construct. If you were able to program with only one loop, which construct would you choose? Why?

Exercise 6.16:

Given two vectors of ints, write a program to determine whether one vectors is a prefix of the other. For vectors of unequal length, compare the number of elements of the smaller vector. For example, given the vectors (0,1,1,2) and (0,1,1,2,3,5,8), your program should return TRue.




C++ Primer
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2006
Pages: 223
Authors: Stephen Prata

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