• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Chapter 8
 

Chapter 8

on

  • 1,246 views

C++ - 7 edition - Solution Manual

C++ - 7 edition - Solution Manual

Statistics

Views

Total Views
1,246
Views on SlideShare
1,246
Embed Views
0

Actions

Likes
0
Downloads
32
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Chapter 8 Chapter 8 Document Transcript

    • 8 Pointers: SolutionsAddresses are given to us toconceal our whereabouts.—Saki (H. H. Munro)By indirection find directionout.—William ShakespeareMany things, having fullreferenceTo one consent, may workcontrariously.—William ShakespeareYou will find it a very goodpractice always to verify yourreferences, sir!—Dr. RouthObjectivesIn this chapter you’ll learn:■ What pointers are.■ The similarities and differences between pointers and references, and when to use each.■ To use pointers to pass arguments to functions by reference.■ The close relationships between pointers and arrays.■ To use pointers to functions. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
    • 2 Chapter 8 Pointers: SolutionsStudent Solution Exercises8.8 For each of the following, write C++ statements that perform the specified task. Assumethat unsigned integers are stored in two bytes and that the starting address of the array is at location1002500 in memory. a) 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. ANS: unsigned values[ SIZE ] = { 2, 4, 6, 8, 10 }; b) Declare a pointer vPtr that points to an object of type unsigned int. ANS: unsigned *vPtr; c) Use a for statement to print the elements of array values using array subscript notation. ANS: for ( int i = 0; i < SIZE; i++ ) cout << setw( 4 ) << values[ i ]; d) Write two separate statements that assign the starting address of array values to pointer variable vPtr. ANS: vPtr = values; and vPtr = &values[ 0 ]; e) Use a for statement to print the elements of array values using pointer/offset notation. ANS: for ( int i = 0; i < SIZE; i++ ) cout << setw( 4 ) << *( vPtr + i ); f) Use a for statement to print the elements of array values using pointer/offset notation with the array name as the pointer. ANS: for ( int i = 0; i < SIZE; i++ ) cout << setw( 4 ) << *( values + i ); g) Use a for statement to print the elements of array values by subscripting the pointer to the array. ANS: for ( int i = 0; i < SIZE; i++ ) cout << setw( 4 ) << vPtr[ i ]; h) Refer to the fifth element of values using array subscript notation, pointer/offset nota- tion with the array name as the pointer, pointer subscript notation and pointer/offset notation. ANS: values[ 4 ], *( values + 4 ), vPtr[ 4 ], *( vPtr + 4 ) i) What address is referenced by vPtr + 3? What value is stored at that location? ANS: The address of the location pertaining to values[ 3 ] (i.e., 1002506). 8. j) Assuming that vPtr points to values[ 4 ], what address is referenced by vPtr -= 4? What value is stored at that location? ANS: The address of where values begins in memory (i.e., 1002500). 2.8.14 What does this program do?1 // Ex. 8.14: ex08_14.cpp2 // What does this program do?3 #include <iostream>4 using namespace std;56 int mystery2( const char * ); // prototype78 int main() © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
    • Student Solution Exercises 3 9 { 10 char string1[ 80 ]; 11 12 cout << "Enter a string: "; 13 cin >> string1; 14 cout << mystery2( string1 ) << endl; 15 } // end main 16 17 // What does this function do? 18 int mystery2( const char *s ) 19 { 20 int x; 21 22 for ( x = 0; *s != 0; s++ ) 23 ++x; 24 25 return x; 26 } // end function mystery2 Enter a string: length 6 8.16 (Maze Traversal) The grid of hashes (#) and dots (.) in Fig. 8.44 is a two-dimensional array representation of a maze. In the two-dimensional array, the hashes represent the walls of the maze and the dots represent squares in the possible paths through the maze. Moves can be made only to a location in the array that contains a dot. # # # # # # # # # # # # # . . . # . . . . . . # . . # . # . # # # # . # # # # . # . . . . # . # # . . . . # # # . # . . # # # # . # . # . # . # # . . # . # . # . # . # # # . # . # . # . # . # # . . . . . . . . # . # # # # # # # . # # # . # # . . . . . . # . . . # # # # # # # # # # # # #Fig. 8.1 | Two-dimensional array representation of a maze. There is a simple algorithm for walking through a maze that guarantees finding the exit (assuming that there is an exit). If there is not an exit, you’ll arrive at the starting location again. Place your right hand on the wall to your right and begin walking forward. Never remove your hand from the wall. If the maze turns to the right, you follow the wall to the right. As long as you do not remove your hand from the wall, eventually you’ll arrive at the exit of the maze. There may be a shorter path than the one you have taken, but you are guaranteed to get out of the maze if you follow the algorithm. Write recursive function mazeTraverse to walk through the maze. The function should receive arguments that include a 12-by-12 character array representing the maze and the starting location of the maze. As mazeTraverse attempts to locate the exit from the maze, it should place the charac- © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
    • 4 Chapter 8 Pointers: Solutions ter X in each square in the path. The function should display the maze after each move, so the user can watch as the maze is solved. ANS: 1 // Exercise 8.16 Solution: Ex08_16.cpp 2 // This solution assumes that there is only one 3 // entrance and one exit for a given maze, and 4 // these are the only two dots on the borders. 5 #include <iostream> 6 using namespace std; 7 8 enum Direction { DOWN, RIGHT, UP, LEFT }; 910 // function prototypes11 void mazeTraversal( char [][ 12 ], const int, const int, int, int, int );12 void printMaze( const char[][ 12 ] );13 bool validMove( const char [][ 12 ], int, int );14 bool coordsAreEdge( int, int );1516 int main()17 {18 char maze[ 12 ][ 12 ] =19 { {#, #, #, #, #, #, #, #, #, #, #, #},20 {#, ., ., ., #, ., ., ., ., ., ., #},21 {., ., #, ., #, ., #, #, #, #, ., #},22 {#, #, #, ., #, ., ., ., ., #, ., #},23 {#, ., ., ., ., #, #, #, ., #, ., .},24 {#, #, #, #, ., #, ., #, ., #, ., #},25 {#, ., ., #, ., #, ., #, ., #, ., #},26 {#, #, ., #, ., #, ., #, ., #, ., #},27 {#, ., ., ., ., ., ., ., ., #, ., #},28 {#, #, #, #, #, #, ., #, #, #, ., #},29 {#, ., ., ., ., ., ., #, ., ., ., #},30 {#, #, #, #, #, #, #, #, #, #, #, #} };3132 int xStart = 2; // starting X and Y coordinates for maze33 int yStart = 0;34 int x = xStart; // current X and Y coordinates35 int y = yStart;3637 mazeTraversal( maze, xStart, yStart, x, y, RIGHT );38 } // end main3940 // Assume that there is exactly 1 entrance and exactly 1 exit to the maze.41 void mazeTraversal( char maze[][ 12 ], const int xStart, const int yStart,42 int xCoord, int yCoord, int direction )43 {44 static bool flag = false;4546 maze[ xCoord ][ yCoord ] = x;47 printMaze( maze );4849 if ( coordsAreEdge( xCoord, yCoord ) && xCoord != xStart &&50 yCoord != yStart ) © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
    • Student Solution Exercises 551 {52 cout << "nMaze successfully exited!nn";53 return; // maze is complete54 } // end if55 else if ( xCoord == xStart && yCoord == yStart && flag )56 {57 cout << "nArrived back at the starting location.nn";58 return;59 } // end else if60 else61 {62 flag = true;6364 // for loop uses switch to determine appropriate move65 for ( int move = direction, count = 0; count < 4; count++,66 move++, move %= 4 )67 {68 switch( move )69 {70 case DOWN: // move down71 if ( validMove( maze, xCoord + 1, yCoord ) )72 {73 mazeTraversal(74 maze, xStart, yStart, xCoord + 1, yCoord, LEFT );75 return;76 } // end if77 break;78 case RIGHT: // move right79 if ( validMove( maze, xCoord, yCoord + 1 ) )80 {81 mazeTraversal(82 maze, xStart, yStart, xCoord, yCoord + 1, DOWN );83 return;84 } // end if85 break;86 case UP: // move up87 if ( validMove( maze, xCoord - 1, yCoord ) )88 {89 mazeTraversal(90 maze, xStart, yStart, xCoord - 1, yCoord, RIGHT );91 return;92 } // end if93 break;94 case LEFT: // move left95 if ( validMove( maze, xCoord, yCoord - 1 ) )96 {97 mazeTraversal(98 maze, xStart, yStart, xCoord, yCoord - 1, UP );99 return;100 } // end if101 break;102 } // end switch103 } // end for104 } // end else © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
    • 6 Chapter 8 Pointers: Solutions105 } // end function mazeTraversal106107 // validate move108 bool validMove( const char maze[][ 12 ], int r, int c )109 {110 return111 ( r >= 0 && r <= 11 && c >= 0 && c <= 11 && maze[ r ][ c ] != # );112 } // end function validate113114 // function to check coordinates115 bool coordsAreEdge( int x, int y )116 {117 if ( ( x == 0 || x == 11 ) && ( y >= 0 && y <= 11 ) )118 return true;119 else if ( ( y == 0 || y == 11 ) && ( x >= 0 && x <= 11 ) )120 return true;121 else122 return false;123 } // end function coordsAreEdge124125 // print the current state of the maze126 void printMaze( const char maze[][ 12 ] )127 {128 // nested for loops to iterate through maze129 for ( int x = 0; x < 12; x++ )130 {131 for ( int y = 0; y < 12; y++ )132 cout << maze[ x ][ y ] << ;133134 cout << n;135 } // end for136137 cout << "nHit return to see next moven";138 cin.get();139 } // end function printMaze# # # # # # # # # # # ## . . . # . . . . . . #x . # . # . # # # # . ## # # . # . . . . # . ## . . . . # # # . # . .# # # # . # . # . # . ## . . # . # . # . # . ## # . # . # . # . # . ## . . . . . . . . # . ## # # # # # . # # # . ## . . . . . . # . . . ## # # # # # # # # # # #Hit return to see next move... © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
    • Student Solution Exercises 7# # # # # # # # # # # ## x x x # x x x x x x #x x # x # x # # # # x ## # # x # x x x x # x ## x x x x # # # x # x x# # # # x # . # x # x ## x x # x # . # x # x ## # x # x # . # x # x ## x x x x x x x x # x ## # # # # # x # # # x ## x x x x x x # x x x ## # # # # # # # # # # #Hit return to see next moveMaze successfully exited! 8.17 (Generating Mazes Randomly) Write a function mazeGenerator that randomly produces a maze. The function should take as arguments a two-dimensional 12-by-12 character array and pointers to the int variables that represent the row and column of the maze’s entry point. Try your function mazeTraverse from Exercise 8.25, using several randomly generated mazes. ANS: 1 // Exercise 8.17 Solution: Ex08_17.cpp 2 #include <iostream> 3 #include <cstdlib> 4 #include <ctime> 5 using namespace std; 6 7 enum Direction { DOWN, RIGHT, UP, LEFT }; 8 const int MAX_DOTS = 100; // maximum possible dots for maze 910 // function prototypes11 void mazeTraversal( char [][ 12 ], const int, const int, int, int, int );12 void mazeGenerator( char [][ 12 ], int *, int * );13 void printMaze( const char[][ 12 ] );14 bool validMove( const char [][ 12 ], int, int );15 bool coordsAreEdge( int, int );1617 int main()18 {19 char maze[ 12 ][ 12 ];20 int xStart; // represent starting coordinates:21 int yStart;22 int x; // current coordinates:23 int y;2425 srand( time( 0 ) );2627 // loop to generate hashes (#)28 for ( int loop = 0; loop < 12; loop++ )29 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
    • 8 Chapter 8 Pointers: Solutions30 for ( int loop2 = 0; loop2 < 12; loop2++ )31 maze[ loop ][ loop2 ] = #;3233 mazeGenerator( maze, &xStart, &yStart ); // generate the maze3435 x = xStart; // initialize x36 y = yStart; // initialize y3738 mazeTraversal( maze, xStart, yStart, x, y, RIGHT ); // traverse maze39 } // end main4041 // Assume that there is exactly 1 entrance and exactly 1 exit to the maze.42 void mazeTraversal( char maze[][ 12 ], const int xStart, const int yStart,43 int xCoord, int yCoord, int direction )44 {45 static bool flag = false;4647 maze[ xCoord ][ yCoord ] = x;48 printMaze( maze );4950 if ( coordsAreEdge( xCoord, yCoord ) && xCoord != xStart &&51 yCoord != yStart )52 {53 cout << "nMaze successfully exited!nn";54 return; // maze is complete55 } // end if56 else if ( xCoord == xStart && yCoord == yStart && flag )57 {58 cout << "nArrived back at the starting location.nn";59 return;60 } // end else if61 else62 {63 flag = true;6465 // for loop uses switch to determine appropriate move66 for ( int move = direction, count = 0; count < 4; count++,67 move++, move %= 4 )68 {69 switch( move )70 {71 case DOWN: // move down72 if ( validMove( maze, xCoord + 1, yCoord ) )73 {74 mazeTraversal(75 maze, xStart, yStart, xCoord + 1, yCoord, LEFT );76 return;77 } // end if78 break;79 case RIGHT: // move right80 if ( validMove( maze, xCoord, yCoord + 1 ) )81 {82 mazeTraversal(83 maze, xStart, yStart, xCoord, yCoord + 1, DOWN ); © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
    • Student Solution Exercises 984 return;85 } // end if86 break;87 case UP: // move up88 if ( validMove( maze, xCoord - 1, yCoord ) )89 {90 mazeTraversal(91 maze, xStart, yStart, xCoord - 1, yCoord, RIGHT );92 return;93 } // end if94 break;95 case LEFT: // move left96 if ( validMove( maze, xCoord, yCoord - 1 ) )97 {98 mazeTraversal(99 maze, xStart, yStart, xCoord, yCoord - 1, UP );100 return;101 } // end if102 break;103 } // end switch104 } // end for105 } // end else106 } // end function mazeTraversal107108 // validate move109 bool validMove( const char maze[][ 12 ], int r, int c )110 {111 return112 ( r >= 0 && r <= 11 && c >= 0 && c <= 11 && maze[ r ][ c ] != # );113 } // end function validMove114115 // check boundaries of coordinates116 bool coordsAreEdge( int x, int y )117 {118 if ( ( x == 0 || x == 11 ) && ( y >= 0 && y <= 11 ) )119 return true;120 else if ( ( y == 0 || y == 11 ) && ( x >= 0 && x <= 11 ) )121 return true;122 else123 return false;124 } // end function coordsAreEdge125126 // print the maze127 void printMaze( const char maze[][ 12 ] )128 {129 for ( int x = 0; x < 12; x++ )130 {131 for ( int y = 0; y < 12; y++ )132 cout << maze[ x ][ y ] << ;133134 cout << n;135 } // end for136137 cout << "nHit return to see next moven"; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
    • 10 Chapter 8 Pointers: Solutions138 cin.get();139 } // end function printMaze140141 // random feature of making a maze142 void mazeGenerator( char maze[][ 12 ], int *xPtr, int *yPtr )143 {144 int a; // store random numbers:145 int entry;146 int exit;147 int x;148 int y;149150 do151 {152 entry = rand() % 4;153 exit = rand() % 4;154 } while ( entry == exit );155156 // Determine entry position157 if ( entry == 0 )158 {159 *xPtr = 1 + rand() % 10; // avoid corners160 *yPtr = 0;161 maze[ *xPtr ][ 0 ] = .;162 } // end if163 else if ( entry == 1 )164 {165 *xPtr = 0;166 *yPtr = 1 + rand() % 10;167 maze[ 0 ][ *yPtr ] = .;168 } // end else if169 else if ( entry == 2 )170 {171 *xPtr = 1 + rand() % 10;172 *yPtr = 11;173 maze[ *xPtr ][ 11 ] = .;174 } // end if175 else176 {177 *xPtr = 11;178 *yPtr = 1 + rand() % 10;179 maze[ 11 ][ *yPtr ] = .;180 } // end else181182 // Determine exit location183 if ( exit == 0 )184 {185 a = 1 + rand() % 10;186 maze[ a ][ 0 ] = .;187 } // end if188 else if ( exit == 1 )189 {190 a = 1 + rand() % 10;191 maze[ 0 ][ a ] = .; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
    • Student Solution Exercises 11192 } // end else if193 else if ( exit == 2 )194 {195 a = 1 + rand() % 10;196 maze[ a ][ 11 ] = .;197 } // end else if198 else199 {200 a = 1 + rand() % 10;201 maze[ 11 ][ a ] = .;202 } // end else203204 for ( int loop = 1; loop < MAX_DOTS; loop++ ) // add dots randomly205 {206 x = 1 + rand() % 10;207 y = 1 + rand() % 10;208 maze[ x ][ y ] = .;209 } // end for210 } // end mazeGenerator# # # # # # # # # # # ## # # . . . . . . . . ## . # # # # # # . . . ## . . # # # # . . . . ## . . . . . . . . . . ## # . . . # # . # # . ## # # . . . # . . # . ## . # # . # . # . . . ## . . . # # . . . . # ## . . . . . . . . # # #x . # . . . . # # # . ## # # . # # # # # # # #Hit return to see next move...# # # # # # # # # # # ## # # . . . . . . . . ## . # # # # # # . . . ## . . # # # # . . . . ## . . . . . . . . . . ## # . . . # # . # # . ## # # . . . # . . # . ## . # # . # . # . . . ## . . . # # . . . . # ## x x x . . . . . # # #x x # x . . . # # # . ## # # x # # # # # # # #Hit return to see next moveMaze successfully exited! © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.