Wrap-Up

Answers to Self Review Exercises

22.1

a) structure. b) bitwise AND (&). c) members. d) bitwise inclusive-OR (|). e) struct. f) typedef. g) bitwise exclusive-OR (^). h) mask. i) structure member (.), structure pointer (->). j) left-shift operator (<<), right-shift operator (>>).

22.2
  1. False. A structure can contain many data types.
  2. False. The members of separate structures can have the same names, but the members of the same structure must have unique names.
  3. False. typedef is used to define aliases for previously defined data types.
  4. False. Structures are passed to functions by value by default and may be passed by reference.
22.3
  1. struct Part { int partNumber; char partName[ 26 ]; };
  2. typedef part * partptr
  3. Part a; Part b[ 10 ]; Part *ptr;
  4. cin >> a.partNumber >> a.partName;
  5. b[ 3 ] = a;
  6. ptr = b;
  7. cout << ( ptr + 3 )->partNumber << ' ' << ( ptr + 3 )->partName << endl;
22.4
  1. Error: The parentheses that should enclose *cPtr have been omitted, causing the order of evaluation of the expression to be incorrect.
  2. Error: The array subscript has been omitted. The expression should be hearts[ 10 ].face.
  3. Error: A semicolon is required to end a structure definition.
  4. Error: Variables of different structure types cannot be assigned to one another.
22.5
  1. c = toupper( c );
  2. cout << ''' << c << "' " << ( isdigit( c ) ? "is a" : "is not a" ) << " digit" << endl;
  3. cout << atol( "1234567" ) << endl;
  4. cout << ''' << c << "' " << ( iscntrl( c ) ? "is a" : "is not a" ) << " control character" << endl;
  5. ptr = strrchr( s1, c );
  6. out << atof( "8.63582" ) << endl;
  7. cout << ''' << c << "' " << ( isalpha( c ) ? "is a" : "is not a" ) << " letter" << endl;
  8. ptr = strstr( s1, s2 );
  9. cout << ''' << c << "' " << ( isprint( c ) ? "is a" : "is not a" ) << " printing character" << endl;
  10. ptr = strpbrk( s1, s2 );
  11. ptr = strchr( s1, c );
  12. cout << atoi( "-21" ) << endl;

Exercises

22.6

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.
22.7

Consider the following structure definitions and variable declarations:

struct Customer {
 char lastName[ 15 ];
 char firstName[ 15 ];
 int customerNumber;

 struct {
 char phoneNumber[ 11 ];
 char address[ 50 ];
 char city[ 15 ];
 char state[ 3 ];
 char zipCode[ 6 ];
 } personal;

} customerRecord, *customerPtr;

customerPtr = &customerRecord;
 

Write a separate expression that accesses the structure members in each of the following parts:

  1. Member lastName of structure customerRecord.
  2. Member lastName of the structure pointed to by customerPtr.
  3. Member firstName of structure customerRecord.
  4. Member firstName of the structure pointed to by customerPtr.
  5. Member customerNumber of structure customerRecord.
  6. Member customerNumber of the structure pointed to by customerPtr.
  7. Member phoneNumber of member personal of structure customerRecord.
  8. Member phoneNumber of member personal of the structure pointed to by customerPtr.
  9. Member address of member personal of structure customerRecord.
  10. Member address of member personal of the structure pointed to by customerPtr.
  11. Member city of member personal of structure customerRecord.
  12. Member city of member personal of the structure pointed to by customerPtr.
  13. Member state of member personal of structure customerRecord.
  14. Member state of member personal of the structure pointed to by customerPtr.
  15. Member zipCode of member personal of structure customerRecord.
  16. Member zipCode of member personal of the structure pointed to by customerPtr.
22.8

Modify the program of Fig. 22.14 to shuffle the cards using a high-performance shuffle, as shown in Fig. 22.3. Print the resulting deck in two-column format, as in Fig. 22.4. Precede each card with its color.

22.9

Write a program that right-shifts an integer variable 4 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?

22.10

Left-shifting an unsigned integer by 1 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.

 
22.11

The left-shift operator can be used to pack two character values into a two-byte unsigned integer variable. Write a program that inputs two characters from the keyboard and passes them to function packCharacters. To pack two characters into an unsigned integer variable, assign the first character to the unsigned variable, shift the unsigned variable left by 8 bit positions and combine the unsigned variable with the second character using the bitwise inclusive-OR operator. The program should output the characters in their bit format before and after they are packed into the unsigned integer to prove that they are in fact packed correctly in the unsigned variable.

22.12

Using the right-shift operator, the bitwise AND operator and a mask, write function unpackCharacters that takes the unsigned integer from Exercise 22.11 and unpacks it into two characters. To unpack two characters from an unsigned two-byte integer, combine the unsigned integer with the mask 65280 (11111111 00000000) and right-shift the result 8 bits. Assign the resulting value to a char variable. Then, combine the unsigned integer with the mask 255 (00000000 11111111). Assign the result to another char variable. The program should print the unsigned integer in bits before it is unpacked, then print the characters in bits to confirm that they were unpacked correctly.

22.13

If your system uses four-byte integers, rewrite the program of Exercise 22.11 to pack four characters.

22.14

If your system uses four-byte integers, rewrite the function unpackCharacters of Exercise 22.12 to unpack four characters. Create the masks you need to unpack the 4 characters by left-shifting the value 255 in the mask variable by 8 bits 0, 1, 2 or 3 times (depending on the byte you are unpacking).

22.15

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.

22.16

Write a program that demonstrates passing an array by value. [Hint: Use a struct.] Prove that a copy was passed by modifying the array copy in the called function.

22.17

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.

22.18

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.19: ex22_19.cpp 2 // This program determines if a value is a multiple of X. 3 #include 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 bool multiple( int ); 10 11 int main() 12 { 13 int y; 14 15 cout << "Enter an integer between 1 and 32000: "; 16 cin >> y;
17 18 if ( multiple( y ) ) 19 cout << y << " is a multiple of X" << endl; 20 else 21 cout << y << " is not a multiple of X" << endl; 22 23 return 0; 24 25 } // end main 26 27 // determine if num is a multiple of X 28 bool multiple( int num ) 29 { 30 bool mult = true; 31 32 for ( int i = 0, mask = 1; i < 10; i++, mask <<= 1 ) 33 34 if ( ( num & mask ) != 0 ) { 35 mult = false; 36 break; 37 38 } // end if 39 40 return mult; 41 42 } // end function multiple
22.19

What does the following program do?

1 // Exercise 22.20: ex22_20.cpp 2 #include 3 4 using std::cout; 5 using std::cin; 6 using std::endl; 7 using std::boolalpha; 8 9 bool mystery( unsigned ); 10 11 int main() 12 { 13 unsigned x; 14 15 cout << "Enter an integer: "; 16 cin >> x; 17 cout << boolalpha 18 << "The result is " << mystery( x ) << endl; 19 20 return 0; 21 22 } // end main 23
24 // What does this function do? 25 bool mystery( unsigned bits ) 26 { 27 const int SHIFT = 8 * sizeof( unsigned ) - 1; 28 const unsigned MASK = 1 << SHIFT; 29 unsigned total = 0; 30 31 for ( int i = 0; i < SHIFT + 1; i++, bits <<= 1 ) 32 33 if ( ( bits & MASK ) == MASK ) 34 ++total; 35 36 return !( total % 2 ); 37 38 } // end function mystery
22.20

Write a program that inputs a line of text with istream member function getline (as in Chapter 15) into character array s[ 100 ]. Output the line in uppercase letters and lowercase letters.

22.21

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-style string-processing techniques shown in this chapter.

22.22

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-style string-processing techniques shown in this chapter.

22.23

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.]

22.24

Write a program based on the program of Exercise 22.23 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.

22.25

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.

22.26

Write a program based on the program of Exercise 22.25 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.

22.27

The chart in Appendix B shows the numeric code representations for the characters in the ASCII character set. Study this chart, and 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.
 
22.28

Write a program that reads a series of strings and prints only those strings beginning with the letter "b."

22.29

Write a program that reads a series of strings and prints only those strings that end with the letters "ED."

22.30

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 000255 and attempts to print the corresponding characters. What happens when this program is run?

22.31

Using the ASCII character chart in Appendix B as a guide, write your own versions of the character-handling functions in Fig. 22.17.

22.32

Write your own versions of the functions in Fig. 22.21 for converting strings to numbers.

22.33

Write your own versions of the functions in Fig. 22.28 for searching strings.

22.34

Write your own versions of the functions in Fig. 22.35 for manipulating blocks of memory.

22.35

(Project: A Spelling Checker) Many popular word-processing software packages have builtin spell checkers. We used spell-checking capabilities in preparing this book and discovered that, no matter how careful we thought we were in writing a chapter, the software was always able to find a few more spelling errors than we were able to catch manually.

In this project, you are asked to develop your own spell-checker utility. We make suggestions to help get you started. You should then consider adding more capabilities. You might find it helpful to use a computerized dictionary as a source of words.

Why do we type so many words with incorrect spellings? In some cases, it is because we simply do not know the correct spelling, so we make a "best guess." In some cases, it is because we transpose two letters (e.g., "defualt" instead of "default"). Sometimes we double-type a letter accidentally (e.g., "hanndy" instead of "handy"). Sometimes we type a nearby key instead of the one we intended (e.g., "biryhday" instead of "birthday"). And so on.

Design and implement a spell-checker program. Your program maintains an array wordList of character strings. You can either enter these strings or obtain them from a computerized dictionary.

Your program asks a user to enter a word. The program then looks up that word in the wordList array. If the word is present in the array, your program should print "Word is spelled correctly."

If the word is not present in the array, your program should print "Word is not spelled correctly." Then your program should try to locate other words in wordList that might be the word the user intended to type. For example, you can try all possible single transpositions of adjacent letters to discover that the word "default" is a direct match to a word in wordList. Of course, this implies that your program will check all other single transpositions, such as "edfault," "dfeault," "deafult," "defalut" and "defautl." When you find a new word that matches one in wordList, print that word in a message such as "Did you mean "default?"."

Implement other tests, such as the replacing of each double letter with a single letter and any other tests you can develop to improve the value of your spell checker.





C++ How to Program
C++ How to Program (5th Edition)
ISBN: 0131857576
EAN: 2147483647
Year: 2004
Pages: 627
Simiral book on Amazon

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