Skip to content

Latest commit

 

History

History

chap03

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Answers To Non-programming Exercises

Contents

Exercise 3.1

Rewrite the exercises from § 1.4.1 (p. 13) and § 2.6.2 (p. 76) with appropriate using declarations.

Exer03_01_1.cpp | Exer03_01_2.cpp | Exer03_01_3.cpp

Exercise 3.2

Write a program to read the standard input a line at a time. Modify your program to read a word at a time.

Exer03_02_1.cpp | Exer03_02_2.cpp

Exercise 3.3

Explain how whitespace characters are handled in the string input operator and in the getline function.

  • The string input operator reads and discards any leading whitespace(e.g., spaces, newlinew, tabs). It then read characters until the next whitespace character is encountered.
  • The getline function reads the given stream up to and including the first newline and stores what is read--not including the newline--in its string argument. After getline sees a newline, even if it is the first character in the input, it stops reading and returns. If the first character in the input is a newline, then the resulting string is the empty string.

Exercise 3.4

Write a program to read two strings and report whether the strings are equal. If not, report which of the two is larger. Now, change the program to report whether the strings have the same length, and if not, report which is longer.

Exer03_04.cpp

Exercise 3.5

Write a program to read strings from the standard input, concatenating what is read into one large string. Print the concatenated string. Next, change the program to separate adjacent input strings by a space.

Exer03_05.cpp

Exercise 3.6

Use a range for to change all the characters in a string to X.

Exer03_06.cpp

Exercise 3.7

What would happen if you define the loop control variable in the previous exercise as type char? Predict the results and then change your program to use a char to see if you were right.

Exer03_07.cpp

If we use char rather than char&, we just get a copy of every character in the string, when we assign to the loop variable, we are changing the copy rather than the original character.

Exercise 3.8

Rewrite the program in the first exercise, first using a while and again using a traditional for loop. Which of the three approaches do you prefer and why?

Exer03_08.cpp

Apparently, range for is simpler to use here.

Exercise 3.9

What does the following program do? Is it valid? If not, why not?

string s;
cout << s[0] << endl;

No, it's not valid. Because string is default initialized as empty. Subscripting an empty string is undefined.

Exercise 3.10

Write a program that reads a string of characters including punctuation and writes what was read but with the punctuation removed.

Exer03_10.cpp

Exercise 3.11

Is the following range for legal? If so, what is the type of c?

const string s = "Keep out!";
for (auto &c : s){ /*... */ }

The type of c is const char&. If there is no operation that tries to change the value of c, it's legal, otherwise illegal.

Exer03_11.cpp

Exercise 3.12

Which, if any, of the following vector definitions are in error? For those that are legal, explain what the definition does. For those that are not legal, explain why they are illegal.

(a) vector<vector<int>> ivec;
(b) vector<string> svec = ivec;
(c) vector<string> svec(10, "null");

(a) legal: define and value initialize a vector whose elements are vector of int.

(b) illegal: types of svec and ivec are different, we can't initialize a vector with another of different types.

(c) legal: define and initialize a vector of string which has 10 elements with the same initial value "null".

Exer03_12.cpp

Exercise 3.13

How many elements are there in each of the following vectors? What are the values of the elements?

(a) vector<int> v1;        
(b) vector<int> v2(10);    
(c) vector<int> v3(10, 42);
(d) vector<int> v4{ 10 };    
(e) vector<int> v5{ 10, 42 };
(f) vector<string> v6{ 10 }; 
(g) vector<string> v7{ 10, "hi" };

(a) 0 element.

(b) 10 elements, each has value 0.

(c) 10 elements, each has value 42.

(d) 1 element, the value is 10.

(e) 2 elements, the values of them are 10 and 42 respectively.

(f) 10 elements, each is an empty string.

(g) 10 elements, eahc has value "hi".

Exer03_13.cpp

Exercise 3.14

Write a program to read a sequence of ints from cin and store those values in a vector.

Exer03_14.cpp

Exercise 3.15

Repeat the previous program but read strings this time.

Exer03_15.cpp

Exercise 3.16

Write a program to print the size and contents of the vectors from exercise 3.13. Check whether your answers to that exercise were correct. If not, restudy § 3.3.1 (p. 97) until you understand why you were wrong.

Exer03_16.cpp

Exercise 3.17

Read a sequence of words from cin and store the values a vector. After you’ve read all the words, process the vector and change each word to uppercase. Print the transformed elements, eight words to a line.

Exer03_17.cpp

Exercise 3.18

Is the following program legal? If not, how might you fix it?

vector<int> ivec;
ivec[0] = 42;

Illegal, subscripting an empty vector is undefined, we should use push_back:

vector<int> ivec;
ivec.push_back(42);

Exercise 3.19

List three ways to define a vector and give it ten elements, each with the value 42. Indicate whether there is a preferred way to do so and why.

way 1:

vector<int> ivec(10, 42);

way 2:

vector<int> ivec{42, 42, 42, 42, 42, 42, 42, 42, 42, 42,};

way 3:

vector<int> ivec(10);
for (auto &i : ivec) {
    i = 42;
}

Apparently, the first way is the best.

Exercise 3.20

Read a set of integers into a vector. Print the sum of each pair of adjacent elements. Change your program so that it prints the sum of the first and last elements, followed by the sum of the second and second-tolast, and so on.

Exer03_20.cpp

Exercise 3.21

Redo the first exercise from § 3.3.3 (p. 105) using iterators.

Exer03_21_1.cpp | Exer03_21_2.cpp

Exercise 3.22

Revise the loop that printed the first paragraph in text to instead change the elements in text that correspond to the first paragraph to all uppercase. After you’ve updated text, print its contents.

Exer03_22.cpp

Exercise 3.23

Write a program to create a vector with ten int elements. Using an iterator, assign each element a value that is twice its current value. Test your program by printing the vector.

Exer03_23.cpp

Exercise 3.24

Redo the last exercise from § 3.3.3 (p. 105) using iterators.

Exer03_24.cpp

Exercise 3.25

Rewrite the grade clustering program from § 3.3.3 (p. 104) using iterators instead of subscripts.

Exer03_25.cpp

Exercise 3.26

In the binary search program on page 112, why did we write mid=beg+(end-beg)/2; instead of mid=(beg+end) /2;?

We use mid=beg+(end-beg)/2; instead of mid=(beg+end) /2; because there is no definition of adding two iterators.

Exercise 3.27

Assuming txt_size is a function that takes no arguments and returns an int value, which of the following definitions are illegal? Explain why.

unsigned buf_size = 1024;
(a) int ia[buf_size];  
(b) int ia[4 * 7 - 14];
(c) int ia[txt_size()];
(d) char st[11] = "fundamental";

(a) illegal, we cannot use non-const value as the size of an array.

(b) legal, 4 * 7 - 14 is a const expression and can be evaluated at compile time.

(c) illegal, the return value of txt_size is not a const expression.

(d) illegal, there is a null terminator at the end of the string literal, thus its size is 12 rather than 11.

Exer03_27.cpp

Exercise 3.28

What are the values in the following arrays?

string sa[10];
int ia[10];
int main() 
{
    string sa2[10];
    int ia2[10];
}

sa: ten empty strings.

ia: ten ints whose values are all 0.

sa2: ten empty strings.

ia2: ten uninitialized ints.

Exercise 3.29:

List some of the drawbacks of using an array instead of a vector.

  • Size of an array is fixed at the time of declaration, while the length of a vector is changeable.
  • An array defined in a block is not initialized, while a vector is value initialized.

Exercise 3.30

Identify the indexing errors in the following code:

constexpr size_t array_size = 10;
int ia[array_size];
for (size_t ix = 1; ix <= array_size; ++ix)
    ia[ix] = ix;

The maximum index of ia is 9 rather than 10. When ix grows to 10, it will be out of range.

Exercise 3.31

Write a program to define an array of ten ints. Give each element the same value as its position in the array.

Exer03_31.cpp

Exercise 3.32

Copy the array you defined in the previous exercise into another array. Rewrite your program to use vectors.

Exer03_32_1.cpp | Exer03_32_2.cpp

Exercise 3.33

What would happen if we did not initialize the scores array in the program on page 116?

If we don't initialize scores, the value of every element in it is undefined. When we access them, there might be unexpected results.

Exercise 3.34

Given that p1 and p2 point to elements in the same array, what does the following code do? Are there values of p1 or p2 that make this code illegal?

p1 += p2 - p1;

This code makes p1 points to the position of p2. If p1 or p2 per se is illegal, the result might be illegal.

Exercise 3.35

Using pointers, write a program to set the elements in an array to zero.

Exer03_35.cpp

Exercise 3.36

Write a program to compare two arrays for equality. Write a similar program to compare two vectors.

Exer03_36_1.cpp | Exer03_36_2.cpp

Exercise 3.37

What does the following program do?

const char ca[] = { 'h', 'e', 'l', 'l', 'o' };
const char *cp = ca;
while (*cp) {
    cout << *cp << endl;
    ++cp;
}

This code tries to output the const char array ca. The problem is that ca doesn't have null terminator. The loop might not end as expected.

Exercise 3.38

In this section, we noted that it was not only illegal but meaningless to try to add two pointers. Why would adding two pointers be meaningless?

Because the value of a pointer in actually an address. There is no meaning to add two addresses: we can't know whether the result is a valid address or an address that stores a value of the same type.

Exercise 3.39

Write a program to compare two strings. Now write a program to compare the values of two C-style character strings.

Exer03_39.cpp

Exercise 3.40

Write a program to define two character arrays initialized from string literals. Now define a third character array to hold the concatenation of the two arrays. Use strcpy and strcat to copy the two arrays into the third.

Exer03_40.cpp

Exercise 3.41

Write a program to initialize a vector from an array of ints.

Exer03_41.cpp

Exercise 3.42

Write a program to copy a vector of ints into an array of ints.

Exer03_42.cpp

Exercise 3.43

Write three different versions of a program to print the elements of ia. One version should use a range for to manage the iteration, the other two should use an ordinary for loop in one case using subscripts and in the other using pointers. In all three programs write all the types directly. That is, do not use a type alias, auto, or decltype to simplify the code.

Exer03_43.cpp

Exercise 3.44

Rewrite the programs from the previous exercises using a type alias for the type of the loop control variables.

Exer03_44.cpp

Exercise 3.45

Rewrite the programs again, this time using auto.

Exer03_45.cpp