Wrap-Up

Answers to Self Review Exercises

8.1

a) address. b) 0, NULL, an address. c)0.

8.2
  1. False. The operand of the address operator must be an lvalue; the address operator cannot be applied to constants or to expressions that do not result in references.
  2. False. A pointer to void cannot be dereferenced. Such a pointer does not have a type that enables the compiler to determine the number of bytes of memory to dereference and the type of the data to which the pointer points.
  3. False. Pointers of any type can be assigned to void pointers. Pointers of type void can be assigned to pointers of other types only with an explicit type cast.
8.3
  1. double numbers[ SIZE ] = { 0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9 };
  2. double *nPtr;
  3. cout << fixed << showpoint << setprecision( 1 ); for ( int i = 0; i < SIZE; i++ ) cout << numbers[ i ] <<' ';
  4. nPtr = numbers; nPtr = &numbers[ 0 ];
  5. cout << fixed << showpoint << setprecision( 1 ); for ( int j = 0; j < SIZE; j++ ) cout << *( nPtr + j ) << ' ';
  6. cout << fixed << showpoint << setprecision( 1 ); for ( int k = 0; k < SIZE; k++ ) cout << *( numbers + k ) << ' ';
  7. cout << fixed << showpoint << setprecision( 1 ); for ( int m = 0; m < SIZE; m++ ) cout << nPtr[ m ] << ' ';
  8. numbers[ 3 ] *( numbers + 3 ) nPtr[ 3 ] *( nPtr + 3 )
  9. The address is 1002500 + 8 * 8 = 1002564. The value is 8.8.
  10. The address of numbers[ 5 ] is 1002500 + 5 * 8 = 1002540.

    The address of nPtr -= 4 is 1002540 - 4 * 8 = 1002508.

    The value at that location is 1.1.

8.4
  1. double *fPtr;
  2. fPtr = &number1;
  3. cout << "The value of *fPtr is " << *fPtr << endl;
  4. number2 = *fPtr;
  5. cout << "The value of number2 is " << number2 << endl;
  6. cout << "The address of number1 is " << &number1 << endl;
  7. cout << "The address stored in fPtr is " << fPtr << endl;

    Yes, the value is the same.

  8. strcpy( s1, s2 );
  9. cout << "strcmp(s1, s2) = " << strcmp( s1, s2 ) << endl;
  10. strncat( s1, s2, 10 );
  11. cout << "strlen(s1) = " << strlen( s1 ) << endl;
  12. ptr = strtok( s2, "," );
8.5
  1. void exchange( double *x, double *y )
  2. void exchange( double *, double * );
  3. int evaluate( int x, int (*poly)( int ) )
  4. int evaluate( int, int (*)( int ) );
  5. char vowel[] = "AEIOU";

    char vowel[] = { 'A', 'E', 'I', 'O', 'U', '' };

8.6
  1. Error: zPtr has not been initialized.

    Correction: Initialize zPtr with zPtr = z;

  2. Error: The pointer is not dereferenced.

    Correction: Change the statement to number = *zPtr;

  3. Error: zPtr[ 2 ] is not a pointer and should not be dereferenced.

    Correction: Change *zPtr[ 2 ] to zPtr[ 2 ].

  4. Error: Referring to an array element outside the array bounds with pointer subscripting.

    Correction: To prevent this, change the relational operator in the for statement to <.

  5. Error: Dereferencing a void pointer.

    Correction: To dereference the void pointer, it must first be cast to an integer pointer. Change the statement to number = *static_cast< int * >( sPtr );

  6. Error: Trying to modify an array name with pointer arithmetic.

    Correction: Use a pointer variable instead of the array name to accomplish pointer arithmetic, or subscript the array name to refer to a specific element.

  7. Error: Function strncpy does not write a terminating null character to array s, because its third argument is equal to the length of the string "hello".

    Correction: Make 6 the third argument of strncpy or assign '' to s[ 5 ] to ensure that the terminating null character is added to the string.

  8. Error: Character array s is not large enough to store the terminating null character.

    Correction: Declare the array with more elements.

  9. Error: Function strcmp will return 0 if the strings are equal; therefore, the condition in the if statement will be false, and the output statement will not be executed.

    Correction: Explicitly compare the result of strcmp with 0 in the condition of the if statement.

8.7
  1. jill
  2. jack and jill
  3. 8
  4. 13

Exercises

8.8

State whether the following are true or false. If false, explain why.

  1. Two pointers that point to different arrays cannot be compared meaningfully.
  2. Because the name of an array is a pointer to the first element of the array, array names can be manipulated in precisely the same manner as pointers.
8.9

For each of the following, write C++ statements that perform the specified task. Assume that unsigned integers are stored in two bytes and that the starting address of the array is at location 1002500 in memory.

  1. Declare an array of type unsigned int called values with five elements, and initialize the elements to the even integers from 2 to 10. Assume that the symbolic constant SIZE has been defined as 5.
  2. Declare a pointer vPtr that points to an object of type unsigned int.
  3. Use a for statement to print the elements of array values using array subscript notation.
  4. Write two separate statements that assign the starting address of array values to pointer variable vPtr.
  5. Use a for statement to print the elements of array values using pointer/offset notation.
  6. Use a for statement to print the elements of array values using pointer/offset notation with the array name as the pointer.
  7. Use a for statement to print the elements of array values by subscripting the pointer to the array.
  8. Refer to the fifth element of values using array subscript notation, pointer/offset notation with the array name as the pointer, pointer subscript notation and pointer/offset notation.
  9. What address is referenced by vPtr + 3? What value is stored at that location?
  10. Assuming that vPtr points to values[ 4 ], what address is referenced by vPtr -= 4? What value is stored at that location?
8.10

For each of the following, write a single statement that performs the specified task. Assume that long integer variables value1 and value2 have been declared and value1 has been initialized to 200000.


  1. Declare the variable longPtr to be a pointer to an object of type long.
  2. Assign the address of variable value1 to pointer variable longPtr.
  3. Print the value of the object pointed to by longPtr.
  4. Assign the value of the object pointed to by longPtr to variable value2.
  5. Print the value of value2.
  6. Print the address of value1.
  7. Print the address stored in longPtr. Is the value printed the same as value1's address?
8.11

Perform the task specified by each of the following statements:

  1. Write the function header for function zero that takes a long integer array parameter bigIntegers and does not return a value.
  2. Write the function prototype for the function in part (a).
  3. Write the function header for function add1AndSum that takes an integer array parameter oneTooSmall and returns an integer.
  4. Write the function prototype for the function described in part (c).

Note: Exercise 8.12 through Exercise 8.15 are reasonably challenging. Once you have solved these problems, you ought to be able to implement many popular card games.

8.12

Modify the program in Fig. 8.27 so that the card dealing function deals a five-card poker hand. Then write functions to accomplish each of the following:

  1. Determine whether the hand contains a pair.
  2. Determine whether the hand contains two pairs.
  3. Determine whether the hand contains three of a kind (e.g., three jacks).
  4. Determine whether the hand contains four of a kind (e.g., four aces).
  5. Determine whether the hand contains a flush (i.e., all five cards of the same suit).
  6. Determine whether the contains a straight (i.e., five cards of consecutive face values).
8.13

Use the functions developed in Exercise 8.12 to write a program that deals two five-card poker hands, evaluates each hand and determines which is the better hand.

8.14

Modify the program developed in Exercise 8.13 so that it can simulate the dealer. The dealer's five-card hand is dealt "face down" so the player cannot see it. The program should then evaluate the dealer's hand, and, based on the quality of the hand, the dealer should draw one, two or three more cards to replace the corresponding number of unneeded cards in the original hand. The program should then reevaluate the dealer's hand. [Caution: This is a difficult problem!]

8.15

Modify the program developed in Exercise 8.14 so that it handles the dealer's hand, but the player is allowed to decide which cards of the player's hand to replace. The program should then evaluate both hands and determine who wins. Now use this new program to play 20 games against the computer. Who wins more games, you or the computer? Have one of your friends play 20 games against the computer. Who wins more games? Based on the results of these games, make appropriate modifications to refine your poker-playing program. [Note: This, too, is a difficult problem.] Play 20 more games. Does your modified program play a better game?

8.16

In the card shuffling and dealing program of Figs. 8.258.27, we intentionally used an inefficient shuffling algorithm that introduced the possibility of indefinite postponement. In this problem, you will create a high-performance shuffling algorithm that avoids indefinite postponement.

Modify Figs. 8.258.27 as follows. Initialize the deck array as shown in Fig. 8.36. Modify the shuffle function to loop row by row and column by column through the array, touching every element once. Each element should be swapped with a randomly selected element of the array. Print the resulting array to determine whether the deck is satisfactorily shuffled (as in Fig. 8.37, for example). You may want your program to call the shuffle function several times to ensure a satisfactory shuffle.

Figure 8.36. Unshuffled deck array.

(This item is displayed on page 463 in the print version)

Unshuffled deck array

 

0

1

2

3

4

5

6

7

8

9

10

11

12

0

1

2

3

4

5

6

7

8

9

10

11

12

13

1

14

15

16

17

18

19

20

21

22

23

24

25

26

2

27

28

29

30

31

32

33

34

35

36

37

38

39

3

40

41

42

43

44

45

46

47

48

49

50

51

52

 

Figure 8.37. Sample shuffled deck array.

(This item is displayed on page 463 in the print version)

Sample shuffled deck array

 

0

1

2

3

4

5

6

7

8

9

10

11

12

0

19

40

27

25

36

46

10

34

35

41

18

2

44

1

13

28

14

16

21

30

8

11

31

17

24

7

1

2

12

33

15

42

43

23

45

3

29

32

4

47

26

3

50

38

52

39

48

51

9

5

37

49

22

6

20

 

Note that, although the approach in this problem improves the shuffling algorithm, the dealing algorithm still requires searching the deck array for card 1, then card 2, then card 3 and so on. Worse yet, even after the dealing algorithm locates and deals the card, the algorithm continues searching through the remainder of the deck. Modify the program of Figs. 8.258.27 so that once a card is dealt, no further attempts are made to match that card number, and the program immediately proceeds with dealing the next card.

 
8.17

(Simulation: The Tortoise and the Hare) In this exercise, you will re-create the classic race of the tortoise and the hare. You will use random number generation to develop a simulation of this memorable event.

Our contenders begin the race at "square 1" of 70 squares. Each square represents a possible position along the race course. The finish line is at square 70. The first contender to reach or pass square 70 is rewarded with a pail of fresh carrots and lettuce. The course weaves its way up the side of a slippery mountain, so occasionally the contenders lose ground.

There is a clock that ticks once per second. With each tick of the clock, your program should adjust the position of the animals according to the rules in Fig. 8.38.

Figure 8.38. Rules for moving the tortoise and the hare.

(This item is displayed on page 464 in the print version)

Animal

Move type

Percentage of the time

Actual move

Tortoise

Fast plod

50%

3 squares to the right

Slip

20%

6 squares to the left

Slow plod

30%

1 square to the right

Hare

Sleep

20%

No move at all

Big hop

20%

9 squares to the right

Big slip

10%

12 squares to the left

Small hop

30%

1 square to the right

Small slip

20%

2 squares to the left

 

Use variables to keep track of the positions of the animals (i.e., position numbers are 170). Start each animal at position 1 (i.e., the "starting gate"). If an animal slips left before square 1, move the animal back to square 1.

Generate the percentages in the preceding table by producing a random integer i in the range 1 10. For the tortoise, perform a "fast plod" when 1 images/U2264.jpg border=0> 5, a "slip" when 6 images/U2264.jpg border=0> 7 or a "slow plod" when 8 images/U2264.jpg border=0> images/U2264.jpg border=0> 10. Use a similar technique to move the hare.

Begin the race by printing

BANG !!!!!
AND THEY'RE OFF !!!!!
 

For each tick of the clock (i.e., each repetition of a loop), print a 70-position line showing the letter T in the tortoise's position and the letter H in the hare's position. Occasionally, the contenders land on the same square. In this case, the tortoise bites the hare and your program should print OUCH!!! beginning at that position. All print positions other than the T, the H or the OUCH!!! (in case of a tie) should be blank.

After printing each line, test if either animal has reached or passed square 70. If so, print the winner and terminate the simulation. If the tortoise wins, print TORTOISE WINS!!! YAY!!! If the hare wins, print Hare wins. Yuch. If both animals win on the same clock tick, you may want to favor the tortoise (the "underdog"), or you may want to print It's a tie. If neither animal wins, perform the loop again to simulate the next tick of the clock. When you are ready to run your program, assemble a group of fans to watch the race. You'll be amazed how involved the audience gets!


Introduction to Computers, the Internet and World Wide Web

Introduction to C++ Programming

Introduction to Classes and Objects

Control Statements: Part 1

Control Statements: Part 2

Functions and an Introduction to Recursion

Arrays and Vectors

Pointers and Pointer-Based Strings

Classes: A Deeper Look, Part 1

Classes: A Deeper Look, Part 2

Operator Overloading; String and Array Objects

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

Templates

Stream Input/Output

Exception Handling

File Processing

Class string and String Stream Processing

Web Programming

Searching and Sorting

Data Structures

Bits, Characters, C-Strings and structs

Standard Template Library (STL)

Other Topics

Appendix A. Operator Precedence and Associativity Chart

Appendix B. ASCII Character Set

Appendix C. Fundamental Types

Appendix D. Number Systems

Appendix E. C Legacy Code Topics

Appendix F. Preprocessor

Appendix G. ATM Case Study Code

Appendix H. UML 2: Additional Diagram Types

Appendix I. C++ Internet and Web Resources

Appendix J. Introduction to XHTML

Appendix K. XHTML Special Characters

Appendix L. Using the Visual Studio .NET Debugger

Appendix M. Using the GNU C++ Debugger

Bibliography



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

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