Exercises

  1. 22.4 (Defining Structures) Provide the definition for each of the following structures:

    1. Structure Inventory, containing character array partName[30], integer partNumber, floating-point price, integer stock and integer reorder.

    2. A structure called Address that contains character arrays streetAddress[25], city[20],

      state[3] and zipCode[6].

    3. Structure Student, containing arrays firstName[15] and lastName[15] and variable

      homeAddress of type struct Address from part (b).

    4. Structure Test, containing 16 bit fields with widths of 1 bit. The names of the bit fields are the letters a to p.

  2. 22.5 (Card Shufflling and Dealing) Modify Fig. 22.16 to shuffle the cards using the shuffle algorithm in Fig. 22.3. Print the resulting deck in two-column format. Precede each card with its color.

  3. 22.6 (Shifting and Printing an Integer) Write a program that right-shifts an integer variable four bits. The program should print the integer in bits before and after the shift operation. Does your system place zeros or ones in the vacated bits?

  4. 22.7 (Multiplication Via Bit Shifting) Left-shifting an unsigned integer by one bit is equivalent to multiplying the value by 2. Write function power2 that takes two integer arguments, number and pow, and calculates

    
    number * 2pow
    

    Use a shift operator to calculate the result. The program should print the values as integers and as bits.

  5. 22.8 (Packing Characters into Unsigned Integers) The left-shift operator can be used to pack four character values into a four-byte unsigned integer variable. Write a program that inputs four characters from the keyboard and passes them to function packCharacters. To pack four characters into an unsigned integer variable, assign the first character to the unsigned variable, shift the unsigned variable left by eight bit positions and combine the unsigned variable with the second character using the bitwise inclusive-OR operator, etc. The program should output the characters in their bit format before and after they’re packed into the unsigned integer to prove that they’re in fact packed correctly in the unsigned variable.

  6. 22.9 (Unpacking Characters from Unsigned Integers) Using the right-shift operator, the bitwise AND operator and a mask, write function unpackCharacters that takes the unsigned integer from Exercise 22.8 and unpacks it into four characters. To unpack characters from an unsigned four-byte integer, combine the unsigned integer with a mask and right-shift the result. To create the masks you’ll need to unpack the four characters, left-shift the value 255 in the mask variable by eight bits 0, 1, 2 or 3 times (depending on the byte you are unpacking). Then take the combined result each time and right shift it by eight bits the same number of times. Assign each resulting value to a char variable. The program should print the unsigned integer in bits before it’s unpacked, then print the characters in bits to confirm that they were unpacked correctly.

  7. 22.10 (Reversing Bits) Write a program that reverses the order of the bits in an unsigned integer value. The program should input the value from the user and call function reverseBits to print the bits in reverse order. Print the value in bits both before and after the bits are reversed to confirm that the bits are reversed properly.

  8. 22.11 (Testing Characters with the <cctype> Functions) Write a program that inputs a character from the keyboard and tests the character with each function in the character-handling library. Print the value returned by each function.

  9. 22.12 (Determine the Value) The following program uses function multiple to determine whether the integer entered from the keyboard is a multiple of some integer X. Examine function multiple, then determine the value of X.

    
     1  // Exercise 22.12: Ex22_12.cpp
     2  // This program determines if a value is a multiple of X.
     3  #include <iostream>
     4  using namespace std;
     5
     6  bool multiple(int);
     7
     8  int main() {
     9     int y{0};
    10
    11     cout << "Enter an integer between 1 and 32000: ";
    12     cin >> y;
    13
    14     if (multiple(y)) {
    15        cout << y << " is a multiple of X" << endl;
    16     }
    17     else {
    18        cout << y << " is not a multiple of X" << endl;
    19     }
    20  }
    21
    22  // determine if num is a multiple of X
    23  bool multiple(int num) {
    24     bool mult{true};
    25
    26     for (int i{0}, mask{1}; i < 10; ++i, mask <<= 1) {
    27        if ((num & mask) != 0) {
    28           mult = false;
    29           break;
    30        }
    31     }
    32
    33     return mult;
    34  }
    
  10. 22.13 What does the following program do?

    
     1  // Exercise 22.13: Ex22_13.cpp
     2  #include <iostream>
     3  using namespace std;
     4
     5  bool mystery(unsigned);
     6
     7  int main() {
     8  {
     9     unsigned x;
    10     cout << "Enter an integer: ";
    11     cin >> x;
    12     cout << boolalpha
    13          << "The result is " << mystery(x) << endl;
    14  }
    15
    16  // What does this function do?
    17  bool mystery(unsigned bits)
    18  {
    19     const int SHIFT{8 * sizeof(unsigned) - 1};
    20     const unsigned MASK{1 << SHIFT};
    21     unsigned total{0};
    22
    23     for (int i{0}; i < SHIFT + 1; ++i, bits <<= 1) {
    24        if ((bits & MASK) == MASK) {
    25           ++total;
    26        }
    27     }
    28
    29     return !(total % 2);
    30  }
    
  11. 22.14 Write a program that inputs a line of text with istream member function getline (as in Chapter 13) into character array s[100]. Output the line in uppercase letters and lowercase letters.

  12. 22.15 (Converting Strings to Integers) Write a program that inputs four strings that represent integers, converts the strings to integers, sums the values and prints the total of the four values. Use only the C string-processing techniques discussed in this chapter.

  13. 22.16 (Converting Strings to Floating-Point Numbers) Write a program that inputs four strings that represent floating-point values, converts the strings to double values, sums the values and prints the total of the four values. Use only the C string-processing techniques shown in this chapter.

  14. 22.17 (Searching for Substrings) Write a program that inputs a line of text and a search string from the keyboard. Using function strstr, locate the first occurrence of the search string in the line of text, and assign the location to variable searchPtr of type char*. If the search string is found, print the remainder of the line of text beginning with the search string. Then use strstr again to locate the next occurrence of the search string in the line of text. If a second occurrence is found, print the remainder of the line of text beginning with the second occurrence. [Hint: The second call to strstr should contain the expression searchPtr + 1 as its first argument.]

  15. 22.18 (Searching for Substrings) Write a program based on the program of Exercise 22.17 that inputs several lines of text and a search string, then uses function strstr to determine the total number of occurrences of the string in the lines of text. Print the result.

  16. 22.19 (Searching for Characters) Write a program that inputs several lines of text and a search character and uses function strchr to determine the total number of occurrences of the character in the lines of text.

  17. 22.20 (Searching for Characters) Write a program based on the program of Exercise 22.19 that inputs several lines of text and uses function strchr to determine the total number of occurrences of each letter of the alphabet in the text. Uppercase and lowercase letters should be counted together. Store the totals for each letter in an array, and print the values in tabular format after the totals have been determined.

  18. 22.21 (ASCII Character Set) The chart in Appendix B shows the numeric code representations for the characters in the ASCII character set. Study this chart, then state whether each of the following is true or false:

    1. The letter “A” comes before the letter “B.”

    2. The digit “9” comes before the digit “0.”

    3. The commonly used symbols for addition, subtraction, multiplication and division all come before any of the digits.

    4. The digits come before the letters.

    5. If a sort program sorts strings into ascending sequence, then the program will place the symbol for a right parenthesis before the symbol for a left parenthesis.

  19. 22.22 (Strings Beginning with b) Write a program that reads a series of strings and prints only those strings beginning with the letter “b.”

  20. 22.23 (Strings Ending with ED) Write a program that reads a series of strings and prints only those strings that end with the letters “ED.”

  21. 22.24 (Displaying Characters for Given ASCII Codes) Write a program that inputs an ASCII code and prints the corresponding character. Modify this program so that it generates all possible three-digit codes in the range 000–255 and attempts to print the corresponding characters. What happens when this program is run?

  22. 22.25 (Write Your Own Character Handling Functions) Using the ASCII character chart in Appendix B as a guide, write your own versions of the character-handling functions in Fig. 22.17.

  23. 22.26 (Write Your Own String Conversion Functions) Write your own versions of the functions in Fig. 22.27 for converting strings to numbers.

  24. 22.27 (Write Your Own String Searching Functions) Write your own versions of the functions in Fig. 22.34 for searching strings.

  25. 22.28 (Write Your Own Memory Handling Functions) Write your own versions of the functions in Fig. 22.41 for manipulating blocks of memory.

  26. 22.29 (What Does the Program Do?) What does this program do?

    
     1  // Ex. 22.29: Ex22_29.cpp
     2  // What does this program do?
     3  #include <iostream>
     4  using namespace std;
     5
     6  bool mystery3(const char*, const char*); // prototype
     7
     8  int main() {
     9     char string1[80], string2[80];
    10
    11     cout << "Enter two strings: ";
    12     cin >> string1 >> string2;
    13     cout << "The result is " << mystery3(string1, string2) << endl;
    14  }
    15
    16  // What does this function do?
    17  bool mystery3(const char* s1, const char* s2) {
    18     for (; *s1 != '' && *s2 != ''; ++s1, ++s2) [
    19        if (*s1 != *s2) {
    20        return false;
    21        }
    22     }
    23
    24     return true;
    25  }
    
  27. 22.30 (Comparing Strings) Write a program that uses function strcmp to compare two strings input by the user. The program should state whether the first string is less than, equal to or greater than the second string.

  28. 22.31 (Comparing Strings) Write a program that uses function strncmp to compare two strings input by the user. The program should input the number of characters to compare. The program should state whether the first string is less than, equal to or greater than the second string.

  29. 22.32 (Randomly Creating Sentences) Write a program that uses random number generation to create sentences. The program should use four arrays of pointers to char called article, noun, verb and preposition. The program should create a sentence by selecting a word at random from each array in the following order: article, noun, verb, preposition, article and noun. As each word is picked, it should be concatenated to the previous words in a character array that’s large enough to hold the entire sentence. The words should be separated by spaces. When the final sentence is output, it should start with a capital letter and end with a period. The program should generate 20 such sentences.

    The arrays should be filled as follows: The article array should contain the articles "the", "a", "one", "some" and "any"; the noun array should contain the nouns "boy", "girl", "dog", "town" and "car"; the verb array should contain the verbs "drove", "jumped", "ran", "walked" and "skipped"; the preposition array should contain the prepositions "to", "from", "over", "under" and "on".

    After completing the program, modify it to produce a short story consisting of several of these sentences. (How about a random term-paper writer!)

  30. 22.33 (Limericks) A limerick is a humorous five-line verse in which the first and second lines rhyme with the fifth, and the third line rhymes with the fourth. Using techniques similar to those developed in Exercise 22.32, write a C++ program that produces random limericks. Polishing this program to produce good limericks is a challenging problem, but the result will be worth the effort!

  31. 22.34 (Pig Latin) Write a program that encodes English language phrases into pig Latin. Pig Latin is a form of coded language often used for amusement. Many variations exist in the methods used to form pig Latin phrases. For simplicity, use the following algorithm: To form a pig-Latin phrase from an English-language phrase, tokenize the phrase into words with function strtok. To translate each English word into a pig-Latin word, place the first letter of the English word at the end of the English word and add the letters “ay.” Thus, the word “jump” becomes “umpjay,” the word “the” becomes “hetay” and the word “computer” becomes “omputercay.” Blanks between words remain as blanks. Assume that the English phrase consists of words separated by blanks, there are no punctuation marks and all words have two or more letters. Function printLatinWord should display each word. [Hint: Each time a token is found in a call to strtok, pass the token pointer to function printLatinWord and print the pig-Latin word.]

  32. 22.35 (Tokenizing Phone Numbers) Write a program that inputs a telephone number as a string in the form (555) 555-5555. The program should use function strtok to extract the area code as a token, the first three digits of the phone number as a token, and the last four digits of the phone number as a token. The seven digits of the phone number should be concatenated into one string. Both the area code and the phone number should be printed.

  33. 22.36 (Tokenizing and Reversing a Sentence) Write a program that inputs a line of text, tokenizes the line with function strtok and outputs the tokens in reverse order.

  34. 22.37 (Alphabetizing Strings) Use the string-comparison functions discussed in Section 22.8 and the techniques for sorting arrays developed in Chapter 7 to write a program that alphabetizes a list of strings. Use the names of 10 towns in your area as data for your program.

  35. 22.38 (Write Your Own String Copy and Concatenation Functions) Write two versions of each string-copy and string-concatenation function in Fig. 22.21. The first version should use array subscripting, and the second should use pointers and pointer arithmetic.

  36. 22.39 (Write Your Own String Comparison Functions) Write two versions of each string-comparison function in Fig. 22.21. The first version should use array subscripting, and the second should use pointers and pointer arithmetic.

  37. 22.40 (Write Your Own String Length Function) Write two versions of function strlen in Fig. 22.21. The first version should use array subscripting, and the second should use pointers and pointer arithmetic.

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

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