Chapter 6:Statements (Exercises Solutions)

Exercise 6.1: What is a null statement? Give an example of when you might use a null statement.

A single semicolon.
For example, we might want to read an input stream, ignoring everything we read until encounter a particular value:
    // read until we hit end-of-file or find an input equal to sought.
    while (cin >> s && s != sought)
        ; // null statement

 Exercise 6.2: What is a block? Give an example of when you might use a block.

A compound statement, usually referred to as a block, is a (possibly empty) sequence of statements surrounded by a pair of curly braces.
As an example, recall the while loop from our solution to the bookstore problem on page 26:

    // if so, read the transaction records
    while (std::cin >> trans)
        if (total.same_isbn(trans))
            // match: update the running total
            total = total + trans;
        else {
            // no match: print & assign to total
            std::cout << total << std::endl;
            total = trans;
        }      

 Exercise 6.3: Use the comma operator (Section 5.9, p. 168) to rewrite the else branch in the while loop from the bookstore problem so that it no longer requires a block. Explain whether this rewrite improves or          diminishes the readability of this code. 

while (std::cin >> trans)
    if (total.same_isbn (trans))
        // match: update the running total
        total = total + trans;
    else
        // no match: print  assign to total 
        std::cout << total << std::endl, total = trans;

In some cases it will improve, but usually it diminishes the readability of this code.

 Exercise 6.4: In the while loop that solved the bookstore problem, what effects, if any, would removing the curly brace following the while and its corresponding close curly have on the program.

It will only evaluate and print total and reset total to trans

Exercise 6.5: Correct each of the following      

(a) if (ival1 != ival2)
         ival1 = ival2;
   else ival1 = ival2 = 0;
(b) if (ival < minval) {
         minval = ival;  // remember new minimum
     occurs = 1;    // reset occurence counter
      }
(c) int ival;
     if (ival = get_value())
      cout << "ival = " << ival << endl;
   if (!ival)
       cout << "ival = 0\n";
(d) if (ival == 0)
        ival = get_value();

Exercise 6.6: What is a "dangling else"? How are else clauses resolved in C++?

When a statement contains more if clauses than else clauses, to which if does each else clause belong?
In C++, however, the dangling-else ambiguity is resolved by matching the else with the last occurring unmatched if.

Exercise 6.7:There is one problem with our vowel-counting program as we've implemented it: It doesn't count capital letters as vowels. Write a program that counts both lower-and                                   uppercase letters as the appropriate vowel - that is, your program should count both 'a' and 'A' as part of aCnt, and so forth.

switch (ch) {
    case 'a':
    case 'A':
        ++aCnt;
        break;
    case 'a':
    case 'A':
        ++aCnt;
        break;
    case 'e':
    case 'E':
        ++eCnt;
        break;
    case 'i':
    case 'I':
        ++iCnt;
        break;
    case 'o':
    case 'O':
        ++oCnt;
        break;
    case 'u':
    case 'U':
        ++uCnt;
        break;
}

 Exercise 6.8:Modify our vowel-count program so that it also counts the number of blank spaces, tabs, and newlines read.

switch (ch) {
    case 'a':
    case 'A':
        ++aCnt;
        break;
    case 'a':
    case 'A':
        ++aCnt;
        break;
    case 'e':
    case 'E':
        ++eCnt;
        break;
    case 'i':
    case 'I':
        ++iCnt;
        break;
    case 'o':
    case 'O':
        ++oCnt;
        break;
    case 'u':
    case 'U':
        ++uCnt;
        break;
    case ' ':
        ++spaceCnt;
        break;
    case '\t':
         ++tabCnt;
         break;
     case '\n':
         ++newlineCnt;
         break; 
}

 Exercise 6.9: Modify our vowel-count program so that it also counts the number of occurences of the following two-character sequences: ff, fl, and fi.

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
    char currCh =, preCh = '\0';
    
    int ffCnt = 0, flCnt =0, fiCnt = 0;
    while (cin >> currCh)
        if (preCh == 'f')
            switch (currCh) {
                case 'f':
                    ++ffCnt;
                    break;
                case 'i':
                    ++iCnt;
                    break; 
                case 'l':
                    ++flCnt;
                    break;
        }
   preCh
= currCh; return 0; }

 Exercise 6.10:Each of the programs in the highlighted text on page 206 contains a common programming error. Identify and correct each error.

(a) switch (ival) {
         case 'a': aCnt++, break;
         case 'e': eCnt++, break;
         default: iouCnt++;
     }
(b) switch (ival) {
         case 1:
             ivec[ix] = ival;
             break;
         default:
             int ix = get_value();
             ix = ivec.size() - 1;
             ivec[ix] = ival;
     }
(c) switch (ival) {
         case 1: case 3: case 5: case 7: case 9:
             oddcnt++;
             break;
         case 2: case 4: case 6: case 8: case 10:
             evencnt++;
             break;
     }
(d) int ival = 512, jval = 1024, kval = 4096;
     int bufsize;
     // ...
     switch (swt) {
         case 512:
             bufsize = ival * sizeof(int);
             break;
         case 1024:
             bufsize = ival * sizeof(int);
             break;
         case 4096:
             bufsize = ival * sizeof(int);
             break;
     }   
                

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(); }

(a) Get two strings once the loop executed until encounter the end-of-file
(b) Go through all the elements in the ivec.
     vector<int>::iterator iter = ivec.begin();
     while (iter++ != ivec.end())
     { /*   ...    */}
(c) Continue the loop until ptr = 0.
     while (ptr == 0)
         ptr = find_a_value();
(d) Invoke the get_next_word to assign the value to word and executes until word is not found.
     word = get_next_word();
     while (bool status = find(word))
     { word = get_next_word(); }   

 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 maxium 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 the word "now" occured three times.

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;

int main()
{
    string preWord, currWord;
    string repWord;
    
    int currCnt = 0, maxCnt = 1;
    
    cout << "Enter some words(Ctrl+Z to end):" << endl;
    while (cin >> currWord) {
        if (currWord == preWord)
            ++currCnt;
        else {
            if (currCnt > maxCnt) {
                maxCnt = currCnt;
                repWord = preWord;
            }
            currCnt = 1;
        }
        preWord = currWord;
    }
    if (maxCnt != 1)
        cout << '"' << repWord << '"'
               << " repeated for " << maxCnt
               << " times." << endl;
    else
        cout << "There is no repeated word." << endl;

    return 0;     
}

 Exercise 6.13: Explain in detail how the statement in the while loop is excuted:

              *dest++ = *source++;

First the statement executes like this:
                   *(dest++) = *(source++);
dest++ and source++ first returns dest and source then increments their values.

Finally the statement will be:
*dest = *source; ++dest, ++source;

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)  { /*  ...   */ }

        (d) int ix;

           for (ix != sz; ++ix)  { /*  ...   */ }

        (e) for (int ix = 0; ix != sz; ++ix, ++sz)  { /*  ...   */ }

(a) Process all the elements in ia array.
     for (int *ptr = ia, ix = 0; ptr != ia + size; ++ptr, ++ix)
         { /*  ...  */ }
     // ptr should initialize to ia not &ia. Additionally ix != size and ptr != ia + size is the same condition, so we can discard one of them.
(b) Iterate until encounter some_condition is true.
(c)  Executes the loop when ix != sz.
(d)  Executes the loop when ix != sz.
      int ix;
      for (; ix != sz; ++ix)     { /*  ...  */ }
      // The init-statement is omitted but a null statement is still needed.
(e) If sz doesn't equal to 0, then this loop will become a indefinite loop.  

 Exercise 6.15: The while loop is particularly good at excuting 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?

(a) while-loop:
     string word, text;
     while (cin >> word)
         text += word;
     for-loop:
     string word, text;
     for (;;) {
         cin >> word;
         text += word;
     }
(b) for-loop:
     const int size = 10;
     int ia[size];
     for (int ix = 0; ix != size; ++ix)
         ia[ix] =  ix;
     while-loop:
     const int size = 10;
     int ia[size];
     int ix = 0;
     while (ix != size) {
          ia[ix] = ix;
          ++ix;
     }

I prefer the while-loop. First of all for-loop can do everything for-loop can do, and I think while-loop is very flexible. In the addition, I feel free using while-loop in format.

 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

       small vector. For example, given the vectors (0,1,1,2) and (0,1,1,2,3,5,8), your program should return true.

if (ivec1.size() > ivec2.size())
    return false;
else {
     for (vector<int> size_type iv = 0; iv != ivec1.size(); ++iv)
         if (ivec1[iv] != ivec2[iv])
              return false; 
     return true;
}      

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

        (a) do

             int v1, v2;

             cout << "Please enter two numbers to sum:";

             cin >> v1 >> v2;

             if (cin)

               cout << "Sum is: "

                <<  v1 + v2 << endl;

           while (cin);

        (b) do {

             // ...

           } while (int ival = get_response());

        (c) do {

             int ival = get_response();

             if (ival == some_value())

               break;

           } while (ival);

           if (!ival)

             // ...

(a) Iterates get two numbers and print their sum until encounter end-of-file.
     do {
          int v1, v2;
          cout << "Please enter two numbers to sum: ";
          cin >> v1 >> v2;
          if (cin)
              cout << "Sum is: "
                     << v1 + v2 << endl;
          } while (cin);
     // Missing the curly braces.
(b) Itertates until get_response is false.
     int ival = get_response();
     do {
         // ...
     } while (ival = get_response());
     // Cannot declare a variable in a do-while condition.        
(c) Iterates while ival is not false and not equal to some_value. And then processes something.
     int ival = get_response();
     do {
          if (ival == some_value())
              break;
     } while (ival);
     if (!ival)
          // ...
     A variable defined in do-while body is not referred outside.

 Exercise 6.18:Write a small program that requests the two strings from the user and reports which string is lexicographically less than the other (that is, comes before the other                                         alphabetically). Continue to solicit the user until the user requests to quit. Use the string type, the string less-than operator, and a do while loop. 

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string rsp;
    do {
     cout << "Please enter two words: ";
     string s1, s2;
     cin >> s1 >> s2;
     cout << ((s1 <s2) ? s1 : s2) << " is lexicographically less.\n\n"
          <<  "More? [yes][no] ";
     cin >> rsp;
    } while (!rsp.empty() && rsp[0] != 'n');

    return 0;
}

Exercise 6.19: The first program in this section could be written more succinctly. In fact, its action could be contained entirely in the condition in the while. Rewrite the  loop so that it has an

       empty body and does the work of finding the element in the condition.

while (iter != vec.end() && value != iter++)

 Exercise 6.20: Write a program to read sequence of strings from standard input until either the same word occurs twice in succession or all the words  have been read. Use a while loop to

       read the text one word at a time. Use the break statement to terminate the loop if a word occurs twice in succession. Print the word if it occurs twice in succession, or else

         print a message saying that no word was repeated. 

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main()
{
    string preWord, currWord;
    bool ifRep = false;

    while (cin >> currWord) {
        if (preWord == currWord) {
             ifRep = true;
             break;
        }
        preWord = currWord;
    }
    if (ifRep)
        cout << currWord << endl;
    else
        cout << "No word is repeated." << endl;

    return 0;
} 

Exercise 6.21:Revise the program from the last exercise in Section 6.10 (p. 213) so that it looks only for duplicated words that start with an uppercase letter.

#include <iostream>
#include <string>
#include <cctype>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main()
{
    string preWord, currWord;
    bool ifRep = false;

    while (cin >> currWord) {
        if (preWord == currWord && isupper(preWord[0])) {
             ifRep = true;
             break;
        }
        preWord = currWord;
    }
    if (ifRep)
        cout << currWord << endl;
    else
        cout << "No word is repeated." << endl;

    return 0;
} 

Exercise 6.22:The last example in this section that jumped back to begin could be better written using a loop. Rewrite the code to eliminate the goto.

int sz = get_size();
while (sz <=0)
    sz = get_size();

Exercise 6.23:The bitset operator to_ulong throws an overflow_error exception if the bitset is larger than the size of an unsigned long. Write a program that generates this exception.

#include <iostream>
#include <bitset>

using std::bitset;
using std::cout;
using std::endl;

int main()
{
    bitset<100> bs;

    for (size_t ix = 0; ix != bs.size(); ++ix)
        bs[ix] = 1;
    
    bs.to_ulong();

    return 0;
}

 Exercise 6.24:Revise your program to catch this exception and print a message.

#include <iostream>
#include <bitset>
#include <stdexcept>

using std::bitset;
using std::cout;
using std::endl;
using std::runtime_error;

int main()
{
    bitset<100> bs;

    for (size_t ix = 0; ix != bs.size(); ++ix)
        bs[ix] = 1;
    
    try {
    bs.to_ulong();
    } catch (runtime_error err) {
    cout << err.what() << endl;
    }

return 0;
}

Exercise 6.25: Revise the program you wrote for the exercise in Section 6.11 (p. 214) to conditionally print information about its execution. For example, you might print each word as it is

                        read to let you determine whether the loop correctly finds the first duplicated word that begins with an uppercase letter. Compile and run the program with debugging turned

                        on and again with it turned off.

#include <iostream>
#include <string>
#include <cctype>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main()
{
    string preWord, currWord;
    bool ifRep = false;

    while (cin >> currWord) {
        if (preWord == currWord && isupper(preWord[0])) {
             ifRep = true;
             break;
        }
        preWord = currWord;
    }
    if (ifRep)
        cout << currWord << endl;
    else
        cout << "No word is repeated." << endl;

    return 0;

 

Exercise 6.26: What happens in the following loop:

            string s;

            while (cin >> s) {

              assert (cin);

            }

The loop will get a sequence of words and process.
Assert is useless, because while the cin is false, the loop won't be executed.

 

Exercise 6.27: Explain this loop:

          string s;

          while (cin >> s && s != sought)  {  }

          assert (cin);

When the NDEBUG is defined, the loop will get a sequence of words until encounter end-of-file or get sought.
When encounter end-of-file with no sought found, assert will generate a error and abort the program.

转载于:https://www.cnblogs.com/alldots/archive/2012/05/09/2491040.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值