Google
 

Monday, January 10, 2011

C++ Primer, Fourth Edition Notes:Chapter 6-Exercise

Exercise 6.1:

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

 

Exercise 6.2:

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

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.

Exercise 6.4:

In the while loop that solved the bookstore problem, what effect, if any, would removing the curly brace following the while and its corresponding close curly have on the program?

// Exercise 6.4.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main(int argc, _TCHAR* argv[])
{
// null statement
cout << "trying null statement...";
string a;
vector<string> vect;
while( (cin >> a ) && (a != "break") && cout << a << endl)
;

if( a == "break")
{
cout << "the program has been broken ..." << endl;
}

//int cnt = ivec.size();
//// add elements from size... 1 to ivec
//for(vector<int>::size_type ix = 0;
// ix != ivec.size(); ++ix, --cnt)
// ivec[ix] = cnt;

int i;
cin >> i;
return 0;
}

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 occurrence counter

(c) if (int 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++?

// Exercise 6.5.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main(int argc, _TCHAR* argv[])
{
int get_value();
//(a) if (ival1 != ival2)
// ival1 = ival2
//else ival1 = ival2 = 0;
int ival1(2), ival2(1);
if(ival1 != ival2)
ival1 = ival2;
else
{
ival1 = ival2 = 2;
}
//(b) if (ival < minval)
// minval = ival; // remember new minimum
//occurs = 1; // reset occurrence counter
int ival(2) , minval(2), occurs(0);
if(ival < minval)
{
minval = ival;
occurs = 1;
}

//(c) if (int ival = get_value())
// cout << "ival = " << ival << endl;
//if (!ival)
// cout << "ival = 0\n";
int ival0(0);
if(ival0 = get_value())
cout << "ival0 = " << ival0 << endl;
if( !ival0)
cout << "ival0 = 0\n" << endl;

//(d) if (ival = 0)
// ival = get_value();
int ival3(0);
if(ival3 == 0)
ival3 = get_value();

//dangling else
// oops: incorrect rewrite: This code won't work!
vector<int> ivec;
for (int i(0), occurs(0),minVal(0), input(0); i < 5 ; i++)
{
cin >> input;
ivec.push_back(input);
if (minVal <= ivec[i])
if (minVal == ivec[i])
++occurs;
else { // this else goes with the inner if, not the outer one!
minVal = ivec[i];
occurs = 1;
}
}

return 0;
}

int get_value()
{
return 3;
}

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 vowelthat is, your program should count both 'a' and 'A' as part of aCnt, and so forth.

// Exercise 6.7.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;

int main(int argc, _TCHAR* argv[])
{
cout << "Please input (0 for break):" << endl;
// a e, i o u
int aCnt(0), eCnt(0), iCnt(0), oCnt(0), uCnt(0), otherCnt(0);
char ch(0);
while(cin >> ch)
{
if(ch == '0')
break;

switch(ch)
{
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;
default:
++otherCnt;
}
}
cout << "Number of a is " << aCnt << endl
<< "Number of e is " << eCnt << endl
<< "Number of i is " << iCnt << endl
<< "Number of o is " << oCnt << endl
<< "Number of u is " << uCnt << endl
<< "Number of other char is " << otherCnt << endl;

int i;
cin >> i;
return 0;
}

Exercise 6.8:

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

// Exercise 6.7.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;

int main(int argc, _TCHAR* argv[])
{
cout << "Please input (0 for break):" << endl;
// a e, i o u
//blank spaces, tabs, and newlines read
int aCnt(0), eCnt(0), iCnt(0), oCnt(0), uCnt(0), otherCnt(0),blankCnt(0),tabCnt(0),newlineCnt(0);
int input(-1);
char ch('\0');
while(ch != '0')
{
ch = cin.get();
//ch = static_cast<char>(input);
switch(ch)
{
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 '\t':
++tabCnt;
break;
case ' ':
++blankCnt;
break;
case '\n':
++newlineCnt;
break;
default:
++otherCnt;
}
}
cout << "Number of a is " << aCnt << endl
<< "Number of e is " << eCnt << endl
<< "Number of i is " << iCnt << endl
<< "Number of o is " << oCnt << endl
<< "Number of u is " << uCnt << endl
<< "Number of blank is " << blankCnt << endl
<< "Number of tab is " << tabCnt << endl
<< "Number of newline is " << newlineCnt << endl
<< "Number of other char is " << otherCnt << endl;

int i;
cin >> i;
return 0;
}

Exercise 6.9:

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

Exercise 6.10:

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

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++;

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.

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)
// ...

Exercise 6.18:

Write a small program that requests 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.

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.

Exercise 6.20:

Write a program to read a 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.

 


 


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.


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.


Exercise 6.23:

The bitset operation 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.

Exercise 6.24:

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


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.

Exercise 6.26:

What happens in the following loop:

     string s;
while (cin >> s) {
assert(cin);
// process s
}

Explain whether this usage seems like a good application of the assert macro.

Exercise 6.27:

Explain this loop:

     string s;
while (cin >> s && s != sought) { } // empty body
assert(cin);
// process s

No comments: