Transcript
Page 1: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

8Pointers and Pointer-Based Strings

O B J E C T I V E SIn this chapter you will 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 among pointers, arrays and strings.

■ To use pointers to functions.

■ To declare and use arrays of strings.

Addresses are given to us to conceal our whereabouts.—Saki (H. H. Munro)

By indirection find direction out.—William Shakespeare

Many things, having full referenceTo one consent, may work contrariously.—William Shakespeare

You will find it a very good practice always to verify your references, sir!—Dr. Routh

You can’t trust code that you did not totally create yourself. (Especially code from companies that employ people like me.)—Ken Thompson

cpphtp5_08_IM.fm Page 502 Thursday, December 23, 2004 4:14 PM

Page 2: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Self-Review Exercises 503

Self-Review Exercises8.1 Answer each of the following:

a) A pointer is a variable that contains as its value the of another variable.ANS: address.b) The three values that can be used to initialize a pointer are ,

and .ANS: 0, NULL, an address. c) The only integer that can be assigned directly to a pointer is .ANS: 0.

8.2 State whether the following are true or false. If the answer is false, explain why.a) The address operator & can be applied only to constants and to expressions.ANS: 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.b) A pointer that is declared to be of type void * can be dereferenced.ANS: 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 dereferenceand the type of the data to which the pointer points.

c) Pointers of different types can never be assigned to one another without a cast opera-tion.

ANS: False. Pointers of any type can be assigned to void pointers. Pointers of type void canbe assigned to pointers of other types only with an explicit type cast.

8.3 For each of the following, write C++ statements that perform the specified task. Assumethat double-precision, floating-point numbers are stored in eight bytes and that the starting addressof the array is at location 1002500 in memory. Each part of the exercise should use the results ofprevious parts where appropriate.

a) Declare an array of type double called numbers with 10 elements, and initialize the ele-ments to the values 0.0, 1.1, 2.2, …, 9.9. Assume that the symbolic constant SIZE hasbeen defined as 10.

ANS: double numbers[ SIZE ] = { 0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8,

9.9 };

b) Declare a pointer nPtr that points to a variable of type double.ANS: double *nPtr;

c) Use a for statement to print the elements of array numbers using array subscript nota-tion. Print each number with one position of precision to the right of the decimal point.

ANS: cout << fixed << showpoint << setprecision( 1 );for ( int i = 0; i < SIZE; i++ ) cout << numbers[ i ] << ' ';

d) Write two separate statements that each assign the starting address of array numbers tothe pointer variable nPtr.

ANS: nPtr = numbers;

nPtr = &numbers[ 0 ];

e) Use a for statement to print the elements of array numbers using pointer/offset notationwith pointer nPtr.

ANS: cout << fixed << showpoint << setprecision( 1 );for ( int j = 0; j < SIZE; j++ )

cout << *( nPtr + j ) << ' ';

cpphtp5_08_IM.fm Page 503 Thursday, December 23, 2004 4:14 PM

Page 3: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

504 Chapter 8 Pointers and Pointer-Based Strings

f) Use a for statement to print the elements of array numbers using pointer/offset notationwith the array name as the pointer.

ANS: cout << fixed << showpoint << setprecision( 1 );for ( int k = 0; k < SIZE; k++ )

cout << *( numbers + k ) << ' ';

g) Use a for statement to print the elements of array numbers using pointer/subscript no-tation with pointer nPtr.

ANS: cout << fixed << showpoint << setprecision( 1 );for ( int m = 0; m < SIZE; m++ )

cout << nPtr[ m ] << ' ';

h) Refer to the fourth element of array numbers using array subscript notation, pointer/off-set notation with the array name as the pointer, pointer subscript notation with nPtrand pointer/offset notation with nPtr.

ANS: numbers[ 3 ]

*( numbers + 3 )

nPtr[ 3 ]

*( nPtr + 3 )

i) Assuming that nPtr points to the beginning of array numbers, what address is referencedby nPtr + 8? What value is stored at that location?

ANS: The address is 1002500 + 8 * 8 = 1002564. The value is 8.8.j) Assuming that nPtr points to numbers[ 5 ], what address is referenced by nPtr after

nPtr -= 4 is executed? What is the value stored at that location?ANS: 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 For each of the following, write a single statement that performs the specified task. Assumethat floating-point variables number1 and number2 have been declared and that number1 has been ini-tialized to 7.3. Assume that variable ptr is of type char *. Assume that arrays s1 and s2 are each100-element char arrays that are initialized with string literals.

a) Declare the variable fPtr to be a pointer to an object of type double.ANS: double *fPtr;

b) Assign the address of variable number1 to pointer variable fPtr.ANS: fPtr = &number1;

c) Print the value of the object pointed to by fPtr.ANS: cout << "The value of *fPtr is " << *fPtr << endl;

d) Assign the value of the object pointed to by fPtr to variable number2.ANS: number2 = *fPtr;

e) Print the value of number2. ANS: cout << "The value of number2 is " << number2 << endl;

f) Print the address of number1. ANS: cout << "The address of number1 is " << &number1 << endl; g) Print the address stored in fPtr. Is the value printed the same as the address of number1?ANS: cout << "The address stored in fPtr is " << fPtr << endl;

Yes, the value is the same. h) Copy the string stored in array s2 into array s1.ANS: strcpy( s1, s2 );

i) Compare the string in s1 with the string in s2, and print the result.ANS: cout << "strcmp(s1, s2) = " << strcmp( s1, s2 ) << endl;

j) Append the first 10 characters from the string in s2 to the string in s1.ANS: strncat( s1, s2, 10 );

cpphtp5_08_IM.fm Page 504 Thursday, December 23, 2004 4:14 PM

Page 4: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Self-Review Exercises 505

k) Determine the length of the string in s1, and print the result.ANS: cout << "strlen(s1) = " << strlen( s1 ) << endl;

l) Assign to ptr the location of the first token in s2. The tokens delimiters are commas (,).ANS: ptr = strtok( s2, "," );

8.5 Perform the task specified by each of the following statements:a) Write the function header for a function called exchange that takes two pointers to dou-

ble-precision, floating-point numbers x and y as parameters and does not return a value.ANS: void exchange( double *x, double *y )

b) Write the function prototype for the function in part (a).ANS: void exchange( double *, double * );

c) Write the function header for a function called evaluate that returns an integer andthat takes as parameters integer x and a pointer to function poly. Function poly takesan integer parameter and returns an integer.

ANS: int evaluate( int x, int (*poly)( int ) )

d) Write the function prototype for the function in part (c).ANS: int evaluate( int, int (*)( int ) ); e) Write two statements that each initialize character array vowel with the string of vowels,

"AEIOU".ANS: char vowel[] = "AEIOU";

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

8.6 Find the error in each of the following program segments. Assume the following declara-tions and statements:

int *zPtr; // zPtr will reference array zint *aPtr = 0;void *sPtr = 0;int number;int z[ 5 ] = { 1, 2, 3, 4, 5 };

a) ++zPtr; ANS: Error: zPtr has not been initialized.

Correction: Initialize zPtr with zPtr = z;b) // use pointer to get first value of array

number = zPtr; ANS: Error: The pointer is not dereferenced.

Correction: Change the statement to number = *zPtr;c) // assign array element 2 (the value 3) to number

number = *zPtr[ 2 ]; ANS: Error: zPtr[ 2 ] is not a pointer and should not be dereferenced.

Correction: Change *zPtr[ 2 ] to zPtr[ 2 ].d) // print entire array z

for ( int i = 0; i <= 5; i++ )

cout << zPtr[ i ] << endl; ANS: Error: Referring to an array element outside the array bounds with pointer subscript-

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

e) // assign the value pointed to by sPtr to number

number = *sPtr; ANS: Error: Dereferencing a void pointer.

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

cpphtp5_08_IM.fm Page 505 Thursday, December 23, 2004 4:14 PM

Page 5: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

506 Chapter 8 Pointers and Pointer-Based Strings

f) ++z; ANS: Error: Trying to modify an array name with pointer arithmetic.

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

g) char s[ 10 ];

cout << strncpy( s, "hello", 5 ) << endl; ANS: Error: Function strncpy does not write a terminating null character to array s, be-

cause its third argument is equal to the length of the string "hello".Correction: Make 6 the third argument of strncpy or assign '\0' to s[ 5 ] to ensurethat the terminating null character is added to the string.

h) char s[ 12 ];

strcpy( s, "Welcome Home" ); ANS: Error: Character array s is not large enough to store the terminating null character.

Correction: Declare the array with more elements.i) if ( strcmp( string1, string2 ) )

cout << "The strings are equal" << endl; ANS: 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 ifstatement.

8.7 What (if anything) prints when each of the following statements is performed? If the state-ment contains an error, describe the error and indicate how to correct it. Assume the following vari-able declarations:

char s1[ 50 ] = "jack";char s2[ 50 ] = "jill";char s3[ 50 ];

a) cout << strcpy( s3, s2 ) << endl; ANS: jill

b) cout << strcat( strcat( strcpy( s3, s1 ), " and " ), s2 )

<< endl; ANS: jack and jill c) cout << strlen( s1 ) + strlen( s2 ) << endl; ANS: 8

d) cout << strlen( s3 ) << endl; ANS: 13

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

a) Two pointers that point to different arrays cannot be compared meaningfully.ANS: True.b) 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.ANS: False. An array name cannot be used to refer to another location in memory.

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

cpphtp5_08_IM.fm Page 506 Thursday, December 23, 2004 4:14 PM

Page 6: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Exercises 507

a) Declare an array of type unsigned int called values with five elements, and initializethe elements to the even integers from 2 to 10. Assume that the symbolic constant SIZEhas 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 pointervariable 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 notationwith 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 pointerto 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 notationwith 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.10 For each of the following, write a single statement that performs the specified task. Assume thatlong integer variables value1 and value2 have been declared and value1 has been initialized to 200000.

a) Declare the variable longPtr to be a pointer to an object of type long.ANS: long *lPtr; b) Assign the address of variable value1 to pointer variable longPtr.ANS: lPtr = &value1; c) Print the value of the object pointed to by longPtr.ANS: cout << *lPtr << '\n'; d) Assign the value of the object pointed to by longPtr to variable value2.ANS: value2 = *lPtr; e) Print the value of value2. ANS: cout << value2 << '\n'; f) Print the address of value1.ANS: cout << &value1 << '\n'; g) Print the address stored in longPtr. Is the value printed the same as value1’s address?ANS: cout << lPtr << '\n'; yes.

cpphtp5_08_IM.fm Page 507 Thursday, December 23, 2004 4:14 PM

Page 7: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

508 Chapter 8 Pointers and Pointer-Based Strings

8.11 Perform the task specified by each of the following statements:a) Write the function header for function zero that takes a long integer array parameter

bigIntegers and does not return a value.ANS: void zero( long bigIntegers[] ) or

void zero( long *bigIntegers )b) Write the function prototype for the function in part (a).ANS: void zero( long [] ); or

void zero( long * );c) Write the function header for function add1AndSum that takes an integer array parameter

oneTooSmall and returns an integer.ANS: int add1Andsum( int oneTooSmall[] ) or

int add1Andsum( int *oneTooSmall )d) Write the function prototype for the function described in part (c).ANS: int add1Andsum( int [] ); or int add1Andsum( int * );

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 pokerhand. Then write functions to accomplish each of the following:

a) Determine whether the hand contains a pair.b) Determine whether the hand contains two pairs.c) Determine whether the hand contains three of a kind (e.g., three jacks).d) Determine whether the hand contains four of a kind (e.g., four aces).e) Determine whether the hand contains a flush (i.e., all five cards of the same suit).f) Determine whether the contains a straight (i.e., five cards of consecutive face values).ANS:

1 // Exercise 8.12 Solution: DeckOfCards.h2 // Definition of class DeckOfCards that 3 // represents a deck of playing cards.45 // DeckOfCards class definition6 class DeckOfCards7 {8 public:9 DeckOfCards(); // constructor initializes deck

10 void shuffle(); // shuffle the deck11 void deal(); // deal a five card poker hand12 void pair(); // pair determines if the hand contains one or two pair13 void threeOfKind(); // check if three of a kind14 void fourOfKind(); // check if four of a kind15 void flushHand(); // check for a flush16 void straightHand(); // check for a straight hand17 private:18 int deck[ 4 ][ 13 ]; // represents deck of cards19 const char *suit[ 4 ]; // card suit20 const char *face[ 13 ]; // card face21 int hand[ 5 ][ 2 ]; // represents five-card poker hand22 }; // end class DeckOfCards

cpphtp5_08_IM.fm Page 508 Thursday, December 23, 2004 4:14 PM

Page 8: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Exercises 509

1 // Exercise 8.12: DeckOfCards.cpp2 // Member-function definitions for class DeckOfCards that simulates3 // the shuffling and dealing of a deck of playing cards.4 #include <iostream>5 using std::cout;6 using std::left;7 using std::right;89 #include <iomanip>

10 using std::setw;1112 #include <cstdlib> // prototypes for rand and srand13 using std::rand;14 using std::srand;1516 #include <ctime> // prototype for time17 using std::time;1819 #include "DeckOfCards.h" // DeckOfCards class definition2021 // DeckOfCards default constructor initializes deck22 DeckOfCards::DeckOfCards()23 {24 char *suitValue[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" };25 char *faceValue[ 13 ] = { "Ace", "Deuce", "Three", "Four", "Five", 26 "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };2728 // initialize suit29 for ( int i = 0; i < 4; i++ )30 suit[ i ] = suitValue[ i ];3132 // initialize face33 for ( int i = 0; i < 13; i++ )34 face[ i ] = faceValue[ i ];3536 // loop through rows of deck37 for ( int row = 0; row <= 3; row++ )38 {39 // loop through columns of deck for current row40 for ( int column = 0; column <= 12; column++ )41 {42 deck[ row ][ column ] = 0; // initialize slot of deck to 043 } // end inner for44 } // end outer for45 46 srand( time( 0 ) ); // seed random number generator47 } // end DeckOfCards default constructor4849 // shuffle cards in deck50 void DeckOfCards::shuffle()51 {52 int row; // represents suit value of card53 int column; // represents face value of card5455 // for each of the 52 cards, choose a slot of the deck randomly

cpphtp5_08_IM.fm Page 509 Thursday, December 23, 2004 4:14 PM

Page 9: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

510 Chapter 8 Pointers and Pointer-Based Strings

56 for ( int card = 1; card <= 52; card++ ) 57 {58 do // choose a new random location until unoccupied slot is found59 { 60 row = rand() % 4; // randomly select the row61 column = rand() % 13; // randomly select the column62 } while( deck[ row ][ column ] != 0 ); // end do...while6364 // place card number in chosen slot of deck65 deck[ row ][ column ] = card;66 } // end for67 } // end function shuffle6869 // deal a five card poker hand70 void DeckOfCards::deal()71 {72 int r = 0;7374 cout << "The hand is:\n";7576 // loop to distrubute the cards77 for ( int card = 1; card < 6; card++ )7879 for ( int row = 0; row <= 3; row++ )8081 for ( int column = 0; column <= 12; column++ )8283 if ( deck[ row ][ column ] == card ) 84 {85 hand[ r ][ 0 ] = row;86 hand[ r ][ 1 ] = column;87 cout << setw( 5 ) << face[ column ] << " of " 88 << setw( 8 ) << left << suit[ row ] 89 << ( card % 2 == 0 ? '\n' : '\t' ) << left;90 r++;91 } // end if9293 cout << '\n';94 } // end function deal9596 // pair determines if the hand contains one or two pair97 void DeckOfCards::pair()98 {99 int counter[ 13 ] = { 0 };100101 // check 102 for ( int r = 0; r < 5; r++ )103 counter[ hand[ r ][ 1 ] ]++;104105 cout << '\n';106107 // print result if there is a pair108 for ( int p = 0; p < 13; p++ )109110 if ( counter[ p ] == 2 )

cpphtp5_08_IM.fm Page 510 Thursday, December 23, 2004 4:14 PM

Page 10: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Exercises 511

111 cout << "The hand contains a pair of " << face[ p ] << "'s.\n";112 } // end function pair113114 // check if three of a kind 115 void DeckOfCards::threeOfKind()116 {117 int counter[ 13 ] = { 0 };118119 for ( int r = 0; r < 5; r++ )120 counter[ hand[ r ][ 1 ] ]++;121122 for ( int t = 0; t < 13; t++ )123124 if ( counter[ t ] == 3 )125 cout << "The hand contains three " << face[ t ] << "'s.\n";126 } // end function threeOfKind127128 // check if four of a kind129 void DeckOfCards::fourOfKind()130 {131 int counter[ 13 ] = { 0 };132133 for ( int r = 0; r < 5; r++ )134 counter[ hand[ r ][ 1 ] ]++;135136 for ( int k = 0; k < 13; k++ )137138 if ( counter[ k ] == 4 ) 139 cout << "The hand contains four " << face[ k ] << "'s.\n";140 } // end function fourOfKind141142 // check for a flush143 void DeckOfCards::flushHand()144 {145 int count[ 4 ] = { 0 };146147 for ( int r = 0; r < 5; r++ )148 count[ hand[ r ][ 0 ] ]++;149150 for ( int f = 0; f < 4; f++ )151152 if ( count[ f ] == 5 )153 cout << "The hand contains a flush of " << suit[ f ] << "'s.\n";154 } // end function flushHand155156 // check the hand dealt157 void DeckOfCards::straightHand()158 {159 int s[ 5 ] = { 0 }; // to hold a copy of wHand160 int temp;161162 // copy column locations to sort163 for ( int r = 0; r < 5; r++ )164 s[ r ] = hand[ r ][ 1 ];165

cpphtp5_08_IM.fm Page 511 Thursday, December 23, 2004 4:14 PM

Page 11: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

512 Chapter 8 Pointers and Pointer-Based Strings

166 // bubble sort column locations167 for ( int pass = 1; pass < 5; pass++ )168169 for ( int comp = 0; comp < 4; comp++ )170171 if ( s[ comp ] > s[ comp + 1 ] ) 172 {173 temp = s[ comp ];174 s[ comp ] = s[ comp + 1 ];175 s[ comp + 1 ] = temp;176 } // end if177178 // check if sorted columns are a straight179 if ( s[ 4 ] - 1 == s[ 3 ] && s[ 3 ] - 1 == s[ 2 ] 180 && s[ 2 ] - 1 == s[ 1 ] && s[ 1 ] - 1 == s[ 0 ] ) 181 {182 cout << "The hand contains a straight consisting of\n";183 184 for ( int j = 0; j < 5; j++ )185 cout << face[ hand[ j ][ 1 ] ] << " of " 186 << suit[ hand[ j ][ 0 ] ] << '\n';187 } // end if188 } // end function straightHand

1 // Exercise 8.12: Ex08_12.cpp2 // Card shuffling and dealing program.3 #include "DeckOfCards.h" // DeckOfCards class definition45 int main()6 {7 DeckOfCards deckOfCards; // create DeckOfCards object8 9 deckOfCards.shuffle(); // shuffle the cards in the deck

10 deckOfCards.deal(); // deal the cards in the deck1112 // checks if hand equal one of these:13 deckOfCards.pair();14 deckOfCards.threeOfKind();15 deckOfCards.fourOfKind();16 deckOfCards.flushHand();17 deckOfCards.straightHand();18 return 0; // indicates successful termination19 } // end main

The hand is:Deuce of Spades King of ClubsNine of Diamonds Jack of SpadesJack of Hearts

The hand contains a pair of Jack's.

cpphtp5_08_IM.fm Page 512 Thursday, December 23, 2004 4:14 PM

Page 12: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Exercises 513

8.13 Use the functions developed in Exercise 8.12 to write a program that deals two five-cardpoker 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 deal-er’s five-card hand is dealt “face down” so the player cannot see it. The program should then evaluatethe dealer’s hand, and, based on the quality of the hand, the dealer should draw one, two or threemore cards to replace the corresponding number of unneeded cards in the original hand. The pro-gram 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 theplayer is allowed to decide which cards of the player’s hand to replace. The program should thenevaluate both hands and determine who wins. Now use this new program to play 20 games againstthe computer. Who wins more games, you or the computer? Have one of your friends play 20 gamesagainst the computer. Who wins more games? Based on the results of these games, make appropriatemodifications to refine your poker-playing program. [Note: This, too, is a difficult problem.] Play20 more games. Does your modified program play a better game?

8.16 In the card shuffling and dealing program of Fig. 8.27, we intentionally used an inefficientshuffling algorithm that introduced the possibility of indefinite postponement. In this problem, youwill create a high-performance shuffling algorithm that avoids indefinite postponement.

Modify Fig. 8.27 as follows. Initialize the deck array as shown in Fig. 8.36. Modify the shuf-fle function to loop row by row and column by column through the array, touching every elementonce. Each element should be swapped with a randomly selected element of the array. Print theresulting 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.

Note that, although the approach in this problem improves the shuffling algorithm, the deal-ing 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 continuessearching through the remainder of the deck. Modify the program of Fig. 8.27 so that once a cardis dealt, no further attempts are made to match that card number, and the program immediatelyproceeds with dealing the next card.

cpphtp5_08_IM.fm Page 513 Thursday, December 23, 2004 4:14 PM

Page 13: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

514 Chapter 8 Pointers and Pointer-Based Strings

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

Our contenders begin the race at “square 1” of 70 squares. Each square represents a possibleposition along the race course. The finish line is at square 70. The first contender to reach or passsquare 70 is rewarded with a pail of fresh carrots and lettuce. The course weaves its way up the sideof 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 shouldadjust the position of the animals according to the rules in Fig. 8.38.

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

Fig. 8.36 | Unshuffled deck array.

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

Fig. 8.37 | Sample shuffled deck array.

cpphtp5_08_IM.fm Page 514 Thursday, December 23, 2004 4:14 PM

Page 14: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Exercises 515

Use variables to keep track of the positions of the animals (i.e., position numbers are 1–70).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 range1 ≤ i ≤ 10. For the tortoise, perform a “fast plod” when 1 ≤ i ≤ 5, a “slip” when 6 ≤ i ≤ 7 or a “slowplod” when 8 ≤ i ≤ 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 theletter T in the tortoise’s position and the letter H in the hare’s position. Occasionally, the contendersland on the same square. In this case, the tortoise bites the hare and your program should printOUCH!!! beginning at that position. All print positions other than the T, the H or the OUCH!!! (incase of a tie) should be blank.

After printing each line, test if either animal has reached or passed square 70. If so, print thewinner and terminate the simulation. If the tortoise wins, print TORTOISE WINS!!! YAY!!! If theare wins, print Hare wins. Yuch. If both animals win on the same clock tick, you may want tofavor 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 pro-gram, assemble a group of fans to watch the race. You’ll be amazed how involved the audience gets!

ANS:

Animal Move typePercentage 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

Fig. 8.38 | Rules for moving the tortoise and the hare.

1 // Exercise 8.17 Solution: Ex08_17.cpp2 #include <iostream> 3 using std::cout; 4 using std::endl; 56 #include <cstdlib>7 using std::rand;8 using std::srand;9

10 #include <ctime>

cpphtp5_08_IM.fm Page 515 Thursday, December 23, 2004 4:14 PM

Page 15: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

516 Chapter 8 Pointers and Pointer-Based Strings

11 using std::time;1213 #include <iomanip> 14 using std::setw; 1516 const int RACE_END = 70;1718 // prototypes19 void moveTortoise( int *const );20 void moveHare( int *const );21 void printCurrentPositions( const int *const, const int *const );2223 int main()24 {25 int tortoise = 1;26 int hare = 1;27 int timer = 0; 2829 srand( time( 0 ) );3031 cout << "ON YOUR MARK, GET SET\nBANG !!!!"32 << "\nAND THEY'RE OFF !!!!\n";33 34 // loop through the events35 while ( tortoise != RACE_END && hare != RACE_END ) 36 {37 moveTortoise( &tortoise );38 moveHare( &hare );39 printCurrentPositions( &tortoise, &hare );40 timer++;41 } // end loop4243 if ( tortoise >= hare )44 cout << "\nTORTOISE WINS!!! YAY!!!\n";45 else46 cout << "Hare wins. Yuch.\n";4748 cout << "TIME ELAPSED = " << timer << " seconds" << endl;49 return 0; // indicates successful termination50 } // end main5152 // progress for the tortoise53 void moveTortoise( int * const turtlePtr )54 {55 int x = 1 + rand() % 10; // random number 1-105657 if ( x >= 1 && x <= 5 ) // fast plod58 *turtlePtr += 3;59 else if ( x == 6 || x == 7 ) // slip60 *turtlePtr -= 6;61 else // slow plod62 ++( *turtlePtr );63 64 if ( *turtlePtr < 1 )65 *turtlePtr = 1;

cpphtp5_08_IM.fm Page 516 Thursday, December 23, 2004 4:14 PM

Page 16: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Exercises 517

66 else if ( *turtlePtr > RACE_END )67 *turtlePtr = RACE_END;68 } // end function moveTortoise6970 // progress for the hare71 void moveHare( int * const rabbitPtr )72 {73 int y = 1 + rand() % 10; // random number 1-107475 if ( y == 3 || y == 4 ) // big hop76 *rabbitPtr += 9;77 else if ( y == 5 ) // big slip78 *rabbitPtr -= 12;79 else if ( y >= 6 && y <= 8 ) // small hop80 ++( *rabbitPtr );81 else if ( y > 8 ) // small slip82 *rabbitPtr -= 2;8384 if ( *rabbitPtr < 1 )85 *rabbitPtr = 1;86 else if ( *rabbitPtr > RACE_END )87 *rabbitPtr = RACE_END;88 } // end function moveHare8990 // display new position91 void printCurrentPositions( const int * const snapperPtr, 92 const int * const bunnyPtr )93 {94 if ( *bunnyPtr == *snapperPtr ) 95 cout << setw( *bunnyPtr ) << "OUCH!!!"; 96 else if ( *bunnyPtr < *snapperPtr ) 97 cout << setw( *bunnyPtr ) << 'H' 98 << setw( *snapperPtr - *bunnyPtr ) << 'T';99 else100 cout << setw( *snapperPtr ) << 'T' 101 << setw( *bunnyPtr - *snapperPtr ) << 'H';102103 cout << '\n';104 } // end function printCurrentPositions

ON YOUR MARK, GET SETBANG !!!!AND THEY'RE OFF !!!! H T H T T HH TH TH T H TH T H TH TH T

cpphtp5_08_IM.fm Page 517 Thursday, December 23, 2004 4:14 PM

Page 17: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

518 Chapter 8 Pointers and Pointer-Based Strings

Special Section: Building Your Own ComputerIn the next several problems, we take a temporary diversion away from the world of high-level-lan-guage programming. We “peel open” a computer and look at its internal structure. We introducemachine-language programming and write several machine-language programs. To make this an

H TH T H T

H T H T H TH TH T H T H T H T H TH TH T H T H T H T H TH TH T H T H T H T H T H T H T H T H T H T H T H T H T H T H T H T H T H T H T H T

H T H T H T H T HT

TORTOISE WINS!!! YAY!!!TIME ELAPSED = 55 seconds

cpphtp5_08_IM.fm Page 518 Thursday, December 23, 2004 4:14 PM

Page 18: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Special Section: Building Your Own Computer 519

especially valuable experience, we then build a computer (using software-based simulation) onwhich you can execute your machine-language programs!

8.18 (Machine-Language Programming) Let us create a computer we will call the Simpletron. Asits name implies, it is a simple machine, but, as we will soon see, it is a powerful one as well. TheSimpletron runs programs written in the only language it directly understands, that is, SimpletronMachine Language, or SML for short.

The Simpletron contains an accumulator—a “special register” in which information is putbefore the Simpletron uses that information in calculations or examines it in various ways. Allinformation in the Simpletron is handled in terms of words. A word is a signed four-digit decimalnumber, such as +3364, -1293, +0007, -0001, etc. The Simpletron is equipped with a 100-wordmemory, and these words are referenced by their location numbers 00, 01, …, 99.

Before running an SML program, we must load, or place, the program into memory. The firstinstruction (or statement) of every SML program is always placed in location 00. The simulatorwill start executing at this location.

Each instruction written in SML occupies one word of the Simpletron’s memory; thus,instructions are signed four-digit decimal numbers. Assume that the sign of an SML instruction isalways plus, but the sign of a data word may be either plus or minus. Each location in the Sim-pletron’s memory may contain an instruction, a data value used by a program or an unused (andhence undefined) area of memory. The first two digits of each SML instruction are the operationcode that specifies the operation to be performed. SML operation codes are shown in Fig. 8.39.

The last two digits of an SML instruction are the operand—the address of the memory loca-tion containing the word to which the operation applies.

cpphtp5_08_IM.fm Page 519 Thursday, December 23, 2004 4:14 PM

Page 19: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

520 Chapter 8 Pointers and Pointer-Based Strings

The last two digits of an SML instruction are the operand—the address of the memory loca-tion containing the word to which the operation applies.

Now let us consider two simple SML programs. The first SML program (Fig. 8.40) reads twonumbers from the keyboard and computes and prints their sum. The instruction +1007 reads thefirst number from the keyboard and places it into location 07 (which has been initialized to zero).Instruction +1008 reads the next number into location 08. The load instruction, +2007, places (cop-ies) the first number into the accumulator, and the add instruction, +3008, adds the second numberto the number in the accumulator. All SML arithmetic instructions leave their results in the accumula-tor. The store instruction, +2109, places (copies) the result back into memory location 09. Then the

Operation code Meaning

Input/output operations

const int READ = 10; Read a word from the keyboard into a specific loca-tion in memory.

const int WRITE = 11; Write a word from a specific location in memory to the screen.

Load and store operations

const int LOAD = 20; Load a word from a specific location in memory into the accumulator.

const int STORE = 21; Store a word from the accumulator into a specific location in memory.

Arithmetic operations

const int ADD = 30; Add a word from a specific location in memory to the word in the accumulator (leave result in accumu-lator).

const int SUBTRACT = 31; Subtract a word from a specific location in memory from the word in the accumulator (leave result in accumulator).

const int DIVIDE = 32; Divide a word from a specific location in memory into the word in the accumulator (leave result in accumulator).

const int MULTIPLY = 33; Multiply a word from a specific location in memory by the word in the accumulator (leave result in accu-mulator).

Transfer-of-control operations

const int BRANCH = 40; Branch to a specific location in memory.

const int BRANCHNEG = 41; Branch to a specific location in memory if the accu-mulator is negative.

const int BRANCHZERO = 42; Branch to a specific location in memory if the accu-mulator is zero.

const int HALT = 43; Halt—the program has completed its task.

Fig. 8.39 | Simpletron Machine Language (SML) operation codes.

cpphtp5_08_IM.fm Page 520 Thursday, December 23, 2004 4:14 PM

Page 20: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Special Section: Building Your Own Computer 521

write instruction, +1109, takes the number and prints it (as a signed four-digit decimal number).The halt instruction, +4300, terminates execution.

cpphtp5_08_IM.fm Page 521 Thursday, December 23, 2004 4:14 PM

Page 21: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

522 Chapter 8 Pointers and Pointer-Based Strings

The SML program in Fig. 8.41 reads two numbers from the keyboard, then determines andprints the larger value. Note the use of the instruction +4107 as a conditional transfer of control,much the same as C++’s if statement.

Now write SML programs to accomplish each of the following tasks:a) Use a sentinel-controlled loop to read positive numbers and compute and print their

sum. Terminate input when a negative number is entered.ANS: Note: This program terminates when a negative number is input. The problem state-

ment should state that only positive numbers should be input.00+1009(Read Value)

Location Number Instruction

00 +1007 (Read A)

01 +1008 (Read B)

02 +2007 (Load A)

03 +3008 (Add B)

04 +2109 (Store C)

05 +1109 (Write C)

06 +4300 (Halt)

07 +0000 (Variable A)

08 +0000 (Variable B)

09 +0000 (Result C)

Fig. 8.40 | SML Example 1.

Location Number Instruction

00 +1009 (Read A)

01 +1010 (Read B)

02 +2009 (Load A)

03 +3110 (Subtract B)

04 +4107 (Branch negative to 07)

05 +1109 (Write A)

06 +4300 (Halt)

07 +1110 (Write B)

08 +4300 (Halt)

09 +0000 (Variable A)

10 +0000 (Variable B)

Fig. 8.41 | SML Example 2.

cpphtp5_08_IM.fm Page 522 Thursday, December 23, 2004 4:14 PM

Page 22: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Special Section: Building Your Own Computer 523

01+2009(Load Value)02+4106(Branch negative to 06)03+3008(Add Sum)04+2108(Store Sum)05+4000(Branch 00)06+1108(Write Sum)07+4300(Halt)08+0000(Storage for Sum)09+0000 (Storage for Value)

b) Use a counter-controlled loop to read seven numbers, some positive and some negative,and compute and print their average.

ANS:00+2018(Load Counter)01+3121(Subtract Termination)02+4211(Branch zero to 11)03+2018(Load Counter)04+3019(Add Increment)05+2118(Store Counter)06+1017(Read Value)07+2016(Load Sum)08+3017(Add Value)09+2116(Store Sum)10+4000(Branch 00)11+2016(Load Sum)12+3218(Divide Counter)13+2120(Store Result)14+1120(Write Result)15+4300(Halt)16+0000(Variable Sum)17+0000(Variable Value)18+0000(Variable Counter)19+0001(Variable Increment)20+0000(Variable Result)21+0007(Variable Termination)

c) Read a series of numbers, and determine and print the largest number. The first numberread indicates how many numbers should be processed.

ANS:00+1017(Read Endvalue)01+2018(Load Counter)02+3117(Subtract Endvalue)03+4215(Branch zero to 15)04+2018(Load Counter)05+3021(Add Increment)06+2118(Store Counter)07+1019(Read Value)08+2020(Load Largest)09+3119(Subtract Value)10+4112(Branch negative to 12)11+4001(Branch 01)12+2019(Load Value)13+2120(Store Largest)14+4001(Branch 01)15+1120(Write Largest)16+4300(Halt)17+0000(Variable EndValue)18+0000(Variable Counter)19+0000(Variable Value)20+0000(Variable Largest)21+0001(Variable Increment)

8.19 (Computer Simulator) It may at first seem outrageous, but in this problem you are going tobuild your own computer. No, you will not be soldering components together. Rather, you will use thepowerful technique of software-based simulation to create a software model of the Simpletron. You willnot be disappointed. Your Simpletron simulator will turn the computer you are using into a Simpletron,and you actually will be able to run, test and debug the SML programs you wrote in Exercise 8.18.

cpphtp5_08_IM.fm Page 523 Thursday, December 23, 2004 4:14 PM

Page 23: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

524 Chapter 8 Pointers and Pointer-Based Strings

When you run your Simpletron simulator, it should begin by printing

*** Welcome to Simpletron! ***

*** Please enter your program one instruction ****** (or data word) at a time. I will type the ****** location number and a question mark (?). ****** You then type the word for that location. ****** Type the sentinel -99999 to stop entering ****** your program. ***

Your program should simulate the Simpletron’s memory with a single-subscripted, 100-ele-ment array memory. Now assume that the simulator is running, and let us examine the dialog as weenter the program of Example 2 of Exercise 8.18:

00 ? +100901 ? +101002 ? +200903 ? +311004 ? +410705 ? +110906 ? +430007 ? +111008 ? +430009 ? +000010 ? +000011 ? -99999

*** Program loading completed ****** Program execution begins ***

Note that the numbers to the right of each ? in the preceding dialog represent the SML programinstructions input by the user.

The SML program has now been placed (or loaded) into array memory. Now the Simpletronexecutes your SML program. Execution begins with the instruction in location 00 and, like C++,continues sequentially, unless directed to some other part of the program by a transfer of control.

Use variable accumulator to represent the accumulator register. Use variable counter to keeptrack of the location in memory that contains the instruction being performed. Use variable oper-ationCode to indicate the operation currently being performed (i.e., the left two digits of theinstruction word). Use variable operand to indicate the memory location on which the currentinstruction operates. Thus, operand is the rightmost two digits of the instruction currently beingperformed. Do not execute instructions directly from memory. Rather, transfer the next instruc-tion to be performed from memory to a variable called instructionRegister. Then “pick off ” theleft two digits and place them in operationCode, and “pick off ” the right two digits and place themin operand. When Simpletron begins execution, the special registers are all initialized to zero.

Now let us “walk through” the execution of the first SML instruction, +1009 in memory loca-tion 00. This is called an instruction execution cycle.

The counter tells us the location of the next instruction to be performed. We fetch the con-tents of that location from memory by using the C++ statement

instructionRegister = memory[ counter ];

The operation code and operand are extracted from the instruction register by the statements

operationCode = instructionRegister / 100;operand = instructionRegister % 100;

Now, the Simpletron must determine that the operation code is actually a read (versus a write,a load, etc.). A switch differentiates among the 12 operations of SML.

In the switch statement, the behavior of various SML instructions is simulated as shown inFig. 8.42 (we leave the others to the reader).

cpphtp5_08_IM.fm Page 524 Thursday, December 23, 2004 4:14 PM

Page 24: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Special Section: Building Your Own Computer 525

The halt instruction also causes the Simpletron to print the name and contents of each regis-ter, as well as the complete contents of memory. Such a printout is often called a computer dump(and, no, a computer dump is not a place where old computers go). To help you program yourdump function, a sample dump format is shown in Fig. 8.43. Note that a dump after executing aSimpletron program would show the actual values of instructions and data values at the momentexecution terminated. To format numbers with their sign as shown in the dump, use streammanipulator showpos. To disable the display of the sign, use stream manipulator noshowpos. Fornumbers that have fewer than four digits, you can format numbers with leading zeros between thesign and the value by using the following statement before outputting the value:

cout << setfill( '0' ) << internal;

Parameterized stream manipulator setfill (from header <iomanip>) specifies the fill characterthat will appear between the sign and the value when a number is displayed with a field width offive characters but does not have four digits. (One position in the field width is reserved for thesign.) Stream manipulator internal indicates that the fill characters should appear between thesign and the numeric value .

Let us proceed with the execution of our program’s first instruction—+1009 in location 00. Aswe have indicated, the switch statement simulates this by performing the C++ statement

read: cin >> memory[ operand ];

load: accumulator = memory[ operand ];

add: accumulator += memory[ operand ];

branch: We will discuss the branch instructions shortly.

halt: This instruction prints the message*** Simpletron execution terminated ***

Fig. 8.42 | Behavior of SML instructions.

REGISTERS:accumulator +0000counter 00instructionRegister +0000operationCode 00operand 00

MEMORY: 0 1 2 3 4 5 6 7 8 9 0 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +000010 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +000020 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +000030 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +000040 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +000050 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +000060 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +000070 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +000080 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +000090 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000

Fig. 8.43 | A sample dump.

cpphtp5_08_IM.fm Page 525 Thursday, December 23, 2004 4:14 PM

Page 25: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

526 Chapter 8 Pointers and Pointer-Based Strings

cin >> memory[ operand ];

A question mark (?) should be displayed on the screen before the cin statement executes toprompt the user for input. The Simpletron waits for the user to type a value and press the Enterkey. The value is then read into location 09.

At this point, simulation of the first instruction is complete. All that remains is to prepare theSimpletron to execute the next instruction. The instruction just performed was not a transfer ofcontrol, so we need merely increment the instruction counter register as follows:

++counter;

This completes the simulated execution of the first instruction. The entire process (i.e., theinstruction execution cycle) begins anew with the fetch of the next instruction to execute.

Now let us consider how to simulate the branching instructions (i.e., the transfers of control).All we need to do is adjust the value in the instruction counter appropriately. Therefore, theunconditional branch instruction (40) is simulated in the switch as

counter = operand;

The conditional “branch if accumulator is zero” instruction is simulated as

if ( accumulator == 0 ) counter = operand;

At this point, you should implement your Simpletron simulator and run each of the SMLprograms you wrote in Exercise 8.18. You may embellish SML with additional features and pro-vide for these in your simulator.

Your simulator should check for various types of errors. During the program loading phase,for example, each number the user types into the Simpletron’s memory must be in the range -9999to +9999. Your simulator should use a while loop to test that each number entered is in this rangeand, if not, keep prompting the user to reenter the number until the user enters a correct number.

During the execution phase, your simulator should check for various serious errors, such asattempts to divide by zero, attempts to execute invalid operation codes, accumulator overflows(i.e., arithmetic operations resulting in values larger than +9999 or smaller than -9999) and the like.Such serious errors are called fatal errors. When a fatal error is detected, your simulator shouldprint an error message such as

*** Attempt to divide by zero ****** Simpletron execution abnormally terminated ***

and should print a full computer dump in the format we have discussed previously. This will helpthe user locate the error in the program.

cpphtp5_08_IM.fm Page 526 Thursday, December 23, 2004 4:14 PM

Page 26: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

More Pointer Exercises 527

More Pointer Exercises8.20 Modify the card shuffling and dealing program of Figs. 8.25–8.27 so the shuffling and deal-ing operations are performed by the same function (shuffleAndDeal). The function should containone nested looping statement that is similar to function shuffle in Fig. 8.26.

ANS:

1 // Exercise 8.20: DeckOfCards.h2 // Definition of class DeckOfCards that 3 // represents a deck of playing cards.45 // DeckOfCards class definition6 class DeckOfCards7 {8 public:9 DeckOfCards(); // constructor initializes deck

10 void shuffleAndDeal(); // shuffles and deals cards in deck11 private:12 int deck[ 4 ][ 13 ]; // represents deck of cards13 }; // end class DeckOfCards

1 // Exercise 8.20: DeckOfCards.cpp2 // Member-function definitions for class DeckOfCards that simulates3 // the shuffling and dealing of a deck of playing cards.4 #include <iostream>5 using std::cout;6 using std::left;7 using std::right;89 #include <iomanip>

10 using std::setw;1112 #include <cstdlib> // prototypes for rand and srand13 using std::rand;14 using std::srand;1516 #include <ctime> // prototype for time17 using std::time;1819 #include "DeckOfCards.h" // DeckOfCards class definition2021 // DeckOfCards default constructor initializes deck22 DeckOfCards::DeckOfCards()23 {24 // loop through rows of deck25 for ( int row = 0; row <= 3; row++ )26 {27 // loop through columns of deck for current row28 for ( int column = 0; column <= 12; column++ )29 {30 deck[ row ][ column ] = 0; // initialize slot of deck to 031 } // end inner for

cpphtp5_08_IM.fm Page 527 Thursday, December 23, 2004 4:14 PM

Page 27: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

528 Chapter 8 Pointers and Pointer-Based Strings

32 } // end outer for33 34 srand( time( 0 ) ); // seed random number generator35 } // end DeckOfCards default constructor3637 // shuffle cards in deck38 void DeckOfCards::shuffleAndDeal()39 {40 int row; // represents suit value of card41 int column; // represents face value of card4243 // initialize suit array 44 static const char *suit[ 4 ] = 45 { "Hearts", "Diamonds", "Clubs", "Spades" };4647 // initialize face array 48 static const char *face[ 13 ] = 49 { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven",50 "Eight", "Nine", "Ten", "Jack", "Queen", "King" }; 5152 // loop through the deck of cards53 // shuffle and print the card54 for ( int card = 1; card <= 52; card++ ) 55 {56 do 57 {58 row = rand() % 4;59 column = rand() % 13;60 } while ( deck[ row ][ column ] != 0 ); 6162 deck[ row ][ column ] = card;63 cout << setw( 5 ) << left << face[ column ] << " of " << left 64 << setw( 8 ) << suit[ row ] << left65 << ( card % 2 == 0 ? '\n' : '\t' );66 } // end for67 } // end function shufleAndDeal

1 // Exercise 8.20: Ex08_20.cpp2 // Card shuffling and dealing program.3 #include "DeckOfCards.h" // DeckOfCards class definition45 int main()6 {7 DeckOfCards deckOfCards; // create DeckOfCards object8 9 deckOfCards.shuffleAndDeal(); // shuffle and deal the cards in the deck

10 return 0; // indicates successful termination11 } // end main

cpphtp5_08_IM.fm Page 528 Thursday, December 23, 2004 4:14 PM

Page 28: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

More Pointer Exercises 529

8.21 What does this program do?

Three of Hearts Ten of SpadesJack of Spades Six of SpadesFive of Clubs Three of SpadesEight of Diamonds King of SpadesQueen of Clubs Seven of ClubsJack of Clubs King of HeartsAce of Diamonds Ace of ClubsFive of Spades Deuce of HeartsEight of Hearts Six of HeartsFour of Hearts Queen of DiamondsNine of Diamonds King of DiamondsNine of Hearts Three of ClubsEight of Clubs Five of HeartsAce of Spades Queen of SpadesEight of Spades Ace of HeartsNine of Clubs Six of ClubsSeven of Diamonds Deuce of DiamondsFour of Clubs Deuce of ClubsFour of Spades Seven of HeartsKing of Clubs Five of DiamondsJack of Hearts Jack of DiamondsSix of Diamonds Ten of HeartsThree of Diamonds Ten of DiamondsDeuce of Spades Queen of HeartsSeven of Spades Nine of SpadesFour of Diamonds Ten of Clubs

cpphtp5_08_IM.fm Page 529 Thursday, December 23, 2004 4:14 PM

Page 29: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

530 Chapter 8 Pointers and Pointer-Based Strings

8.22 What does this program do?

1 // Ex. 8.21: ex08_21.cpp2 // What does this program do?3 #include <iostream>4 using std::cout;5 using std::cin;6 using std::endl;78 void mystery1( char *, const char * ); // prototype9

10 int main()11 {12 char string1[ 80 ];13 char string2[ 80 ];1415 cout << "Enter two strings: ";16 cin >> string1 >> string2;17 mystery1( string1, string2 );18 cout << string1 << endl;19 return 0; // indicates successful termination20 } // end main2122 // What does this function do?23 void mystery1( char *s1, const char *s2 )24 {25 while ( *s1 != '\0' )26 ++s1;2728 for ( ; *s1 = *s2; s1++, s2++ )29 ; // empty statement30 } // end function mystery1

Enter two strings: string1 string2string1string2

1 // Ex. 8.22: ex08_22.cpp2 // What does this program do?3 #include <iostream>4 using std::cout;5 using std::cin;6 using std::endl;78 int mystery2( const char * ); // prototype9

10 int main()11 {12 char string1[ 80 ];1314 cout << "Enter a string: ";15 cin >> string1;16 cout << mystery2( string1 ) << endl;

cpphtp5_08_IM.fm Page 530 Thursday, December 23, 2004 4:14 PM

Page 30: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

More Pointer Exercises 531

8.23 Find the error in each of the following segments. If the error can be corrected, explain how. a) int *number;

cout << number << endl; ANS: Pointer number does not "point" to a valid address. Assigning number to an address

would correct the problem.b) double *realPtr;

long *integerPtr;

integerPtr = realPtr; ANS: A pointer of type double cannot be directly assigned to a pointer of type long.c) int * x, y;

x = y; ANS: Variable y is not a pointer, and therefore cannot be assigned to x. Change the assign-

ment statement to x = &y;.d) char s[] = "this is a character array";

for ( ; *s != '\0'; s++ )

cout << *s << ' '; ANS: s is not a modifiable value. Attempting to use operator ++ is a syntax error. Changing

to [] notation corrects the problem as in: for ( int t = 0; s[ t ] != '\0'; t++ ) cout << s[ t ] << ' ';

e) short *numPtr, result;

void *genericPtr = numPtr;

result = *genericPtr + 7; ANS: A void * pointer cannot be dereferenced.f) double x = 19.34;

double xPtr = &x;cout << xPtr << endl;

ANS: xPtr is not a pointer and therefore cannot be assigned an address. Place a * beforexPtr (in the declaration) to correct the problem. The cout statement display’s the ad-dress to which xPtr points (once the previous correction is made)—this is not an er-ror.

g) char *s;cout << s << endl;

ANS: s does not "point" to anything. s should be provided with an address.

17 return 0; // indicates successful termination18 } // end main1920 // What does this function do?21 int mystery2( const char *s ) 22 {23 int x;2425 for ( x = 0; *s != '\0'; s++ )26 ++x;2728 return x;29 } // end function mystery2

Enter a string: length6

cpphtp5_08_IM.fm Page 531 Thursday, December 23, 2004 4:14 PM

Page 31: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

532 Chapter 8 Pointers and Pointer-Based Strings

8.24 (Quicksort) You have previously seen the sorting techniques of the bucket sort and selectionsort. We now present the recursive sorting technique called Quicksort. The basic algorithm for asingle-subscripted array of values is as follows:

a) Partitioning Step: Take the first element of the unsorted array and determine its final lo-cation in the sorted array (i.e., all values to the left of the element in the array are less thanthe element, and all values to the right of the element in the array are greater than theelement). We now have one element in its proper location and two unsorted subarrays.

b) Recursive Step: Perform Step 1 on each unsorted subarray.

Each time Step 1 is performed on a subarray, another element is placed in its final location of thesorted array, and two unsorted subarrays are created. When a subarray consists of one element, thatsubarray must be sorted; therefore, that element is in its final location.

The basic algorithm seems simple enough, but how do we determine the final position of thefirst element of each subarray? As an example, consider the following set of values (the element inbold is the partitioning element—it will be placed in its final location in the sorted array):

37 2 6 4 89 8 10 12 68 45

a) Starting from the rightmost element of the array, compare each element with 37 untilan element less than 37 is found. Then swap 37 and that element. The first element lessthan 37 is 12, so 37 and 12 are swapped. The values now reside in the array as follows:

12 2 6 4 89 8 10 37 68 45

Element 12 is in italics to indicate that it was just swapped with 37.b) Starting from the left of the array, but beginning with the element after 12, compare

each element with 37 until an element greater than 37 is found. Then swap 37 and thatelement. The first element greater than 37 is 89, so 37 and 89 are swapped. The valuesnow reside in the array as follows:

12 2 6 4 37 8 10 89 68 45

c) Starting from the right, but beginning with the element before 89, compare each ele-ment with 37 until an element less than 37 is found. Then swap 37 and that element.The first element less than 37 is 10, so 37 and 10 are swapped. The values now residein the array as follows:

12 2 6 4 10 8 37 89 68 45

d) Starting from the left, but beginning with the element after 10, compare each elementwith 37 until an element greater than 37 is found. Then swap 37 and that element.There are no more elements greater than 37, so when we compare 37 with itself, weknow that 37 has been placed in its final location of the sorted array.

Once the partition has been applied to the array, there are two unsorted subarrays. The subarraywith values less than 37 contains 12, 2, 6, 4, 10 and 8. The subarray with values greater than 37contains 89, 68 and 45. The sort continues with both subarrays being partitioned in the samemanner as the original array.

Based on the preceding discussion, write recursive function quickSort to sort a single-sub-scripted integer array. The function should receive as arguments an integer array, a starting sub-script and an ending subscript. Function partition should be called by quickSort to perform thepartitioning step.

ANS:

1 // Exercise 8.24 Solution: Ex08_24.cpp

cpphtp5_08_IM.fm Page 532 Thursday, December 23, 2004 4:14 PM

Page 32: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

More Pointer Exercises 533

2 #include <iostream> 3 using std::cout; 4 using std::endl; 56 #include <iomanip> 7 using std::setw; 89 #include <cstdlib>

10 using std::rand;11 using std::srand;1213 #include <ctime>14 using std::time;1516 const int SIZE = 10;17 const int MAX_NUMBER = 1000;1819 // function prototypes20 void quicksort( int * const, int, int );21 void swap( int * const, int * const );2223 int main()24 {25 int arrayToBeSorted[ SIZE ] = { 0 };26 int loop;2728 srand( time( 0 ) );2930 // randomly generate content 31 for ( loop = 0; loop < SIZE; loop++ )32 arrayToBeSorted[ loop ] = rand() % MAX_NUMBER;3334 cout << "Initial array values are:\n";35 36 // print out values of the array37 for ( loop = 0; loop < SIZE; loop++ )38 cout << setw( 4 ) << arrayToBeSorted[ loop ];3940 cout << "\n\n";4142 // if there is only one element43 if ( SIZE == 1 )44 cout << "Array is sorted: " << arrayToBeSorted[ 0 ] << '\n';45 else 46 {47 quicksort( arrayToBeSorted, 0, SIZE - 1 );48 cout << "The sorted array values are:\n";4950 for ( loop = 0; loop < SIZE; loop++ )51 cout << setw( 4 ) << arrayToBeSorted[ loop ];5253 cout << endl;54 } // end else5556 return 0; // indicates successful termination

cpphtp5_08_IM.fm Page 533 Thursday, December 23, 2004 4:14 PM

Page 33: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

534 Chapter 8 Pointers and Pointer-Based Strings

57 } // end main5859 // recursive function to sort array60 void quicksort( int * const array, int first, int last )61 {62 int partition( int * const, int, int );63 int currentLocation;6465 if ( first >= last )66 return;6768 currentLocation = partition( array, first, last ); // place an element69 quicksort( array, first, currentLocation - 1 ); // sort left side70 quicksort( array, currentLocation + 1, last ); // sort right side71 } // end function quicksort7273 // partition the array into multiple sections74 int partition( int * const array, int left, int right )75 {76 int position = left;7778 // loop through the portion of the array79 while ( true ) 80 {81 while ( array[ position ] <= array[ right ] && position != right )82 right--;8384 if ( position == right )85 return position;8687 if ( array[ position ] > array[ right ]) 88 {89 swap( &array[ position ], &array[ right ] );90 position = right;91 } // end if9293 while ( array[ left ] <= array[ position ] && left != position )94 left++;9596 if ( position == left )97 return position;9899 if ( array[ left ] > array[ position ] ) 100 {101 swap( &array[ position ], &array[ left ] );102 position = left;103 } // end if104 } // end while105 } // end function partition106107 // swap locations108 void swap( int * const ptr1, int * const ptr2 )109 {110 int temp;111

cpphtp5_08_IM.fm Page 534 Thursday, December 23, 2004 4:14 PM

Page 34: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

More Pointer Exercises 535

8.25 (Maze Traversal) The grid of hashes (#) and dots (.) in Fig. 8.44 is a two-dimensional arrayrepresentation of a maze. In the two-dimensional array, the hashes represent the walls of the mazeand the dots represent squares in the possible paths through the maze. Moves can be made only toa location in the array that contains a dot.

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 will arrive at the starting location again.Place your right hand on the wall to your right and begin walking forward. Never remove yourhand from the wall. If the maze turns to the right, you follow the wall to the right. As long as youdo not remove your hand from the wall, eventually you will arrive at the exit of the maze. Theremay be a shorter path than the one you have taken, but you are guaranteed to get out of the mazeif you follow the algorithm.

Write recursive function mazeTraverse to walk through the maze. The function shouldreceive arguments that include a 12-by-12 character array representing the maze and the startinglocation of the maze. As mazeTraverse attempts to locate the exit from the maze, it should placethe character 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:

112 temp = *ptr1;113 *ptr1 = *ptr2;114 *ptr2 = temp;115 } // end function swap

Initial array values are: 630 971 223 286 354 322 134 846 615 224

The sorted array values are: 134 223 224 286 322 354 615 630 846 971

# # # # # # # # # # # ## . . . # . . . . . . #. . # . # . # # # # . ## # # . # . . . . # . ## . . . . # # # . # . .# # # # . # . # . # . ## . . # . # . # . # . ## # . # . # . # . # . ## . . . . . . . . # . ## # # # # # . # # # . ## . . . . . . # . . . ## # # # # # # # # # # #

Fig. 8.44 | Two-dimensional array representation of a maze.

1 // Exercise 8.25 Solution: Ex08_25.cpp2 // This solution assumes that there is only one3 // entrance and one exit for a given maze, and4 // these are the only two zeroes on the borders.5 #include <iostream> 6 using std::cin;

cpphtp5_08_IM.fm Page 535 Thursday, December 23, 2004 4:14 PM

Page 35: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

536 Chapter 8 Pointers and Pointer-Based Strings

7 using std::cout; 89 enum Direction { DOWN, RIGHT, UP, LEFT };

1011 // function prototypes12 void mazeTraversal( char [][ 12 ], const int, const int, int, 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 { {'#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#'},21 {'#', '.', '.', '.', '#', '.', '.', '.', '.', '.', '.', '#'},22 {'.', '.', '#', '.', '#', '.', '#', '#', '#', '#', '.', '#'},23 {'#', '#', '#', '.', '#', '.', '.', '.', '.', '#', '.', '#'},24 {'#', '.', '.', '.', '.', '#', '#', '#', '.', '#', '.', '.'},25 {'#', '#', '#', '#', '.', '#', '.', '#', '.', '#', '.', '#'},26 {'#', '.', '.', '#', '.', '#', '.', '#', '.', '#', '.', '#'},27 {'#', '#', '.', '#', '.', '#', '.', '#', '.', '#', '.', '#'},28 {'#', '.', '.', '.', '.', '.', '.', '.', '.', '#', '.', '#'},29 {'#', '#', '#', '#', '#', '#', '.', '#', '#', '#', '.', '#'},30 {'#', '.', '.', '.', '.', '.', '.', '#', '.', '.', '.', '#'},31 {'#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#'} };3233 int xStart = 2; // starting X and Y coordinates for maze34 int yStart = 0;35 int x = xStart; // current X and Y coordinates36 int y = yStart;3738 mazeTraversal( maze, xStart, yStart, x, y, RIGHT );39 return 0;40 } // end main4142 // Assume that there is exactly 1 entrance and exactly 1 exit to the maze.43 void mazeTraversal( char maze[][ 12 ], const int xStart, const int yStart,44 int xCoord, int yCoord, int direction )45 {46 static bool flag = false;4748 maze[ xCoord ][ yCoord ] = 'x';49 printMaze( maze );5051 if ( coordsAreEdge( xCoord, yCoord ) && xCoord != xStart && 52 yCoord != yStart ) 53 {54 cout << "\nMaze successfully exited!\n\n";55 return; // maze is complete56 } // end if57 else if ( xCoord == xStart && yCoord == yStart && flag ) 58 {59 cout << "\nArrived back at the starting location.\n\n";60 return;61 } // end else if

cpphtp5_08_IM.fm Page 536 Thursday, December 23, 2004 4:14 PM

Page 36: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

More Pointer Exercises 537

62 else 63 {64 flag = true;6566 // for loop uses switch to determine appropriate move 67 for ( int move = direction, count = 0; count < 4; count++, 68 move++, move %= 4 )69 {70 switch( move ) 71 {72 case DOWN: // move down73 if ( validMove( maze, xCoord + 1, yCoord ) ) 74 {75 mazeTraversal( 76 maze, xStart, yStart, xCoord + 1, yCoord, LEFT );77 return;78 } // end if79 break;80 case RIGHT: // move right81 if ( validMove( maze, xCoord, yCoord + 1 ) ) 82 {83 mazeTraversal( 84 maze, xStart, yStart, xCoord, yCoord + 1, DOWN );85 return;86 } // end if87 break;88 case UP: // move up89 if ( validMove( maze, xCoord - 1, yCoord ) ) 90 {91 mazeTraversal( 92 maze, xStart, yStart, xCoord - 1, yCoord, RIGHT );93 return;94 } // end if95 break;96 case LEFT: // move left97 if ( validMove( maze, xCoord, yCoord - 1 ) ) 98 {99 mazeTraversal( 100 maze, xStart, yStart, xCoord, yCoord - 1, UP );101 return;102 } // end if103 break;104 } // end switch105 } // end for106 } // end else107 } // end function mazeTraversal108109 // validate move110 bool validMove( const char maze[][ 12 ], int r, int c )111 {112 return 113 ( r >= 0 && r <= 11 && c >= 0 && c <= 11 && maze[ r ][ c ] != '#' );114 } // end function validate115116 // function to check coordinates

cpphtp5_08_IM.fm Page 537 Thursday, December 23, 2004 4:14 PM

Page 37: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

538 Chapter 8 Pointers and Pointer-Based Strings

117 bool coordsAreEdge( int x, int y )118 {119 if ( ( x == 0 || x == 11 ) && ( y >= 0 && y <= 11 ) )120 return true;121 else if ( ( y == 0 || y == 11 ) && ( x >= 0 && x <= 11 ) )122 return true;123 else124 return false;125 } // end function coordsAreEdge126127 // print the current state of the maze128 void printMaze( const char maze[][ 12 ] )129 {130 // nested for loops to iterate through maze131 for ( int x = 0; x < 12; x++ ) 132 {133 for ( int y = 0; y < 12; y++ )134 cout << maze[ x ][ y ] << ' ';135136 cout << '\n';137 } // end for138139 cout << "\nHit return to see next move\n";140 cin.get();141 } // end function printMaze

cpphtp5_08_IM.fm Page 538 Thursday, December 23, 2004 4:14 PM

Page 38: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

More Pointer Exercises 539

8.26 (Generating Mazes Randomly) Write a function mazeGenerator that takes as an argument atwo-dimensional 12-by-12 character array and randomly produces a maze. The function should alsoprovide the starting and ending locations of the maze. Try your function mazeTraverse fromExercise 8.25, using several randomly generated mazes.

ANS:

# # # # # # # # # # # ## . . . # . . . . . . #x . # . # . # # # # . ## # # . # . . . . # . ## . . . . # # # . # . .# # # # . # . # . # . ## . . # . # . # . # . ## # . # . # . # . # . ## . . . . . . . . # . ## # # # # # . # # # . ## . . . . . . # . . . ## # # # # # # # # # # #

Hit return to see next move...

# # # # # # # # # # # ## 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 move

Maze successfully exited!

1 // Exercise 8.26 Solution: Ex08_26.cpp2 #include <iostream> 3 using std::cin; 4 using std::cout; 56 #include <cstdlib>7 using std::rand;8 using std::srand;9

10 #include <ctime>11 using std::time;1213 enum Direction { DOWN, RIGHT, UP, LEFT };

cpphtp5_08_IM.fm Page 539 Thursday, December 23, 2004 4:14 PM

Page 39: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

540 Chapter 8 Pointers and Pointer-Based Strings

14 const int MAX_DOTS = 100; // maximum possible dots for maze1516 // function prototypes17 void mazeTraversal( char [][ 12 ], const int, const int, int, int, int );18 void mazeGenerator( char [][ 12 ], int *, int * );19 void printMaze( const char[][ 12 ] );20 bool validMove( const char [][ 12 ], int, int );21 bool coordsAreEdge( int, int );2223 int main()24 {25 char maze[ 12 ][ 12 ];26 int xStart; // represent starting coordinates:27 int yStart;28 int x; // current coordinates:29 int y;3031 srand( time( 0 ) );3233 // loop to generate hashes (#)34 for ( int loop = 0; loop < 12; loop++ )3536 for ( int loop2 = 0; loop2 < 12; loop2++ )37 maze[ loop ][ loop2 ] = '#';3839 mazeGenerator( maze, &xStart, &yStart ); // generate the maze4041 x = xStart; // initialize x42 y = yStart; // initialize y4344 mazeTraversal( maze, xStart, yStart, x, y, RIGHT ); // traverse maze45 return 0; // indicates successful termination46 } // end main4748 // Assume that there is exactly 1 entrance and exactly 1 exit to the maze.49 void mazeTraversal( char maze[][ 12 ], const int xStart, const int yStart,50 int xCoord, int yCoord, int direction )51 {52 static bool flag = false;5354 maze[ xCoord ][ yCoord ] = 'x';55 printMaze( maze );5657 if ( coordsAreEdge( xCoord, yCoord ) && xCoord != xStart && 58 yCoord != yStart ) 59 {60 cout << "\nMaze successfully exited!\n\n";61 return; // maze is complete62 } // end if63 else if ( xCoord == xStart && yCoord == yStart && flag ) 64 {65 cout << "\nArrived back at the starting location.\n\n";66 return;67 } // end else if68 else

cpphtp5_08_IM.fm Page 540 Thursday, December 23, 2004 4:14 PM

Page 40: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

More Pointer Exercises 541

69 {70 flag = true;7172 // for loop uses switch to determine appropriate move 73 for ( int move = direction, count = 0; count < 4; count++, 74 move++, move %= 4 )75 {76 switch( move ) 77 {78 case DOWN: // move down79 if ( validMove( maze, xCoord + 1, yCoord ) ) 80 {81 mazeTraversal( 82 maze, xStart, yStart, xCoord + 1, yCoord, LEFT );83 return;84 } // end if85 break;86 case RIGHT: // move right87 if ( validMove( maze, xCoord, yCoord + 1 ) ) 88 {89 mazeTraversal( 90 maze, xStart, yStart, xCoord, yCoord + 1, DOWN );91 return;92 } // end if93 break;94 case UP: // move up95 if ( validMove( maze, xCoord - 1, yCoord ) ) 96 {97 mazeTraversal( 98 maze, xStart, yStart, xCoord - 1, yCoord, RIGHT );99 return;100 } // end if101 break;102 case LEFT: // move left103 if ( validMove( maze, xCoord, yCoord - 1 ) ) 104 {105 mazeTraversal( 106 maze, xStart, yStart, xCoord, yCoord - 1, UP );107 return;108 } // end if109 break;110 } // end switch111 } // end for112 } // end else113 } // end function mazeTraversal114115 // validate move116 bool validMove( const char maze[][ 12 ], int r, int c )117 {118 return 119 ( r >= 0 && r <= 11 && c >= 0 && c <= 11 && maze[ r ][ c ] != '#' );120 } // end function validMove121122 // check boundaries of coordinates123 bool coordsAreEdge( int x, int y )

cpphtp5_08_IM.fm Page 541 Thursday, December 23, 2004 4:14 PM

Page 41: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

542 Chapter 8 Pointers and Pointer-Based Strings

124 {125 if ( ( x == 0 || x == 11 ) && ( y >= 0 && y <= 11 ) )126 return true;127 else if ( ( y == 0 || y == 11 ) && ( x >= 0 && x <= 11 ) )128 return true;129 else130 return false;131 } // end function coordsAreEdge132133 // print the maze134 void printMaze( const char maze[][ 12 ] )135 {136 for ( int x = 0; x < 12; x++ ) 137 {138 for ( int y = 0; y < 12; y++ )139 cout << maze[ x ][ y ] << ' ';140141 cout << '\n';142 } // end for143144 cout << "\nHit return to see next move\n";145 cin.get();146 } // end function printMaze147148 // random feature of making a maze149 void mazeGenerator( char maze[][ 12 ], int *xPtr, int *yPtr )150 {151 int a; // store random numbers:152 int entry;153 int exit;154 int x;155 int y;156157 do 158 {159 entry = rand() % 4;160 exit = rand() % 4;161 } while ( entry == exit );162163 // Determine entry position164 if ( entry == 0 ) 165 {166 *xPtr = 1 + rand() % 10; // avoid corners167 *yPtr = 0;168 maze[ *xPtr ][ 0 ] = '.';169 } // end if170 else if ( entry == 1 ) 171 {172 *xPtr = 0;173 *yPtr = 1 + rand() % 10;174 maze[ 0 ][ *yPtr ] = '.';175 } // end else if176 else if ( entry == 2 ) 177 {178 *xPtr = 1 + rand() % 10;

cpphtp5_08_IM.fm Page 542 Thursday, December 23, 2004 4:14 PM

Page 42: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

More Pointer Exercises 543

179 *yPtr = 11;180 maze[ *xPtr ][ 11 ] = '.';181 } // end if182 else 183 {184 *xPtr = 11;185 *yPtr = 1 + rand() % 10;186 maze[ 11 ][ *yPtr ] = '.';187 } // end else188189 // Determine exit location190 if ( exit == 0 ) 191 {192 a = 1 + rand() % 10;193 maze[ a ][ 0 ] = '.';194 } // end if195 else if ( exit == 1 ) 196 {197 a = 1 + rand() % 10;198 maze[ 0 ][ a ] = '.';199 } // end else if200 else if ( exit == 2 ) 201 {202 a = 1 + rand() % 10;203 maze[ a ][ 11 ] = '.';204 } // end else if205 else 206 {207 a = 1 + rand() % 10;208 maze[ 11 ][ a ] = '.';209 } // end else210211 for ( int loop = 1; loop < MAX_DOTS; loop++ ) // add dots randomly212 {213 x = 1 + rand() % 10;214 y = 1 + rand() % 10;215 maze[ x ][ y ] = '.';216 } // end for217 } // end mazeGenerator

cpphtp5_08_IM.fm Page 543 Thursday, December 23, 2004 4:14 PM

Page 43: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

544 Chapter 8 Pointers and Pointer-Based Strings

8.27 (Mazes of Any Size) Generalize functions mazeTraverse and mazeGenerator of Exercise 8.25and Exercise 8.26 to process mazes of any width and height.

ANS:

# # # # # # # # # # # ## # # . . . . . . . . ## . # # # # # # . . . ## . . # # # # . . . . ## . . . . . . . . . . ## # . . . # # . # # . ## # # . . . # . . # . ## . # # . # . # . . . ## . . . # # . . . . # ## . . . . . . . . # # #x . # . . . . # # # . ## # # . # # # # # # # #

Hit return to see next move

.

.

.

# # # # # # # # # # # ## # # . . . . . . . . ## . # # # # # # . . . ## . . # # # # . . . . ## . . . . . . . . . . ## # . . . # # . # # . ## # # . . . # . . # . ## . # # . # . # . . . ## . . . # # . . . . # ## x x x . . . . . # # #x x # x . . . # # # . ## # # x # # # # # # # #

Hit return to see next move

Maze successfully exited!

1 // Exercise 8.27 Solution: Ex08_27.cpp2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl;67 #include <cstdlib>8 using std::rand;9 using std::srand;

1011 #include <ctime>12 using std::time;13

cpphtp5_08_IM.fm Page 544 Thursday, December 23, 2004 4:14 PM

Page 44: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

More Pointer Exercises 545

14 enum Direction { DOWN, RIGHT, UP, LEFT };15 const int ROWS = 15;16 const int COLS = 30;1718 // function prototypes19 void mazeTraversal( 20 char [][ COLS ], const int, const int, int, int, int );21 void mazeGenerator( char [][ COLS ], int *, int * );22 void printMaze( const char[][ COLS ] );23 bool validMove( const char [][ COLS ], int, int );24 bool coordsAreEdge( int, int );2526 int main()27 {28 char maze[ ROWS ][ COLS ];29 int xStart; // starting X-coordinate30 int yStart; // starting Y-coordinate31 int x; // current X-coordinate32 int y; // current Y-coordinate3334 srand( time( 0 ) );35 36 // initialize array to have hash symbol37 for ( int loop = 0; loop < ROWS; loop++ )3839 for ( int loop2 = 0; loop2 < COLS; loop2++ )40 maze[ loop ][ loop2 ] = '#';4142 mazeGenerator( maze, &xStart, &yStart );4344 x = xStart; // initialize x45 y = yStart; // initialize y4647 mazeTraversal( maze, xStart, yStart, x, y, RIGHT );48 return 0; // indicates successful termination49 } // end main 5051 // Assume that there is exactly 1 entrance and exactly 1 exit to the maze.52 void mazeTraversal( char maze[][ COLS ], const int xStart, 53 const int yStart, int xCoord, int yCoord, int direction )54 {55 static bool flag = false; // starting position flag5657 maze[ xCoord ][ yCoord ] = 'x'; // insert x at current location58 printMaze( maze );5960 if ( coordsAreEdge( xCoord, yCoord ) && xCoord != xStart 61 && yCoord != yStart ) 62 {63 cout << endl << "Maze successfully exited!\n\n";64 return; // maze is complete65 } // end if66 else if ( xCoord == xStart && yCoord == yStart && flag ) 67 {68 cout << "\nArrived back at the starting location.\n\n";

cpphtp5_08_IM.fm Page 545 Thursday, December 23, 2004 4:14 PM

Page 45: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

546 Chapter 8 Pointers and Pointer-Based Strings

69 return;70 } // end else if71 else 72 {73 flag = true;7475 for ( int move = direction, count = 0; count < 4; 76 count++, move++, move %= 4 )77 {78 switch( move ) 79 {80 case DOWN: // move down81 if ( validMove( maze, xCoord + 1, yCoord ) ) 82 {83 mazeTraversal( 84 maze, xStart, yStart, xCoord + 1, yCoord, LEFT );85 return;86 } // end if87 break;88 case RIGHT: // move right89 if ( validMove( maze, xCoord, yCoord + 1 ) ) 90 {91 mazeTraversal( 92 maze, xStart, yStart, xCoord, yCoord + 1, DOWN );93 return;94 } // end if95 break;96 case UP: // move up97 if ( validMove( maze, xCoord - 1, yCoord ) ) 98 {99 mazeTraversal( 100 maze, xStart, yStart, xCoord - 1, yCoord, RIGHT );101 return;102 } // end if103 break;104 case LEFT: // move left105 if ( validMove( maze, xCoord, yCoord - 1 ) ) 106 {107 mazeTraversal( 108 maze, xStart, yStart, xCoord, yCoord - 1, UP );109 return;110 } // end if111 break;112 } // end switch113 } // end for114 } // end else115 } // end function mazeTraversal 116117 // validate move118 bool validMove( const char maze[][ COLS ], int r, int c )119 {120 return ( r >= 0 && r <= ROWS - 1 && c >= 0 && c <= COLS - 1 &&121 maze[ r ][ c ] != '#' ); // a valid move122 } // end function validMove123

cpphtp5_08_IM.fm Page 546 Thursday, December 23, 2004 4:14 PM

Page 46: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

More Pointer Exercises 547

124 // check bounds of coordinates125 bool coordsAreEdge( int x, int y )126 {127 if ( ( x == 0 || x == ROWS - 1 ) && ( y >= 0 && y <= COLS - 1 ) )128 return true;129 else if ( ( y == 0 || y == COLS - 1 ) && ( x >= 0 && x <= ROWS - 1 ) )130 return true;131 else132 return false;133 } // end function coordsAreEdge134135 // print maze136 void printMaze( const char maze[][ COLS ] )137 {138 // loop through and print maze139 for ( int x = 0; x < ROWS; x++ ) 140 {141 for ( int y = 0; y < COLS; y++ )142 cout << maze[ x ][ y ] << ' ';143144 cout << '\n';145 } // end for146147 cout << "\nHit return to see next move\n";148 cin.get();149 } // end function printMaze150151 // generate the maze152 void mazeGenerator( char maze[][ COLS ], int *xPtr, int *yPtr )153 {154 // local variables155 int a;156 int x;157 int y;158 int entry;159 int exit;160161 do 162 {163 entry = rand() % 4;164 exit = rand() % 4;165 } while ( entry == exit );166167 // Determine entry position168 if ( entry == 0 ) 169 {170 *xPtr = 1 + rand() % ( ROWS - 2 ); // avoid corners171 *yPtr = 0;172 maze[ *xPtr ][ *yPtr ] = '.';173 } // end if174 else if ( entry == 1 ) 175 {176 *xPtr = 0;177 *yPtr = 1 + rand() % ( COLS - 2 );178 maze[ *xPtr ][ *yPtr ] = '.';

cpphtp5_08_IM.fm Page 547 Thursday, December 23, 2004 4:14 PM

Page 47: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

548 Chapter 8 Pointers and Pointer-Based Strings

179 } // end else if180 else if ( entry == 2 ) 181 {182 *xPtr = 1 + rand() % ( ROWS - 2 );183 *yPtr = COLS - 1;184 maze[ *xPtr ][ *yPtr ] = '.';185 } // end else if186 else 187 {188 *xPtr = ROWS - 1;189 *yPtr = 1 + rand() % ( COLS - 2 );190 maze[ *xPtr ][ *yPtr ] = '.';191 } // end else192193 // Determine exit location194 if ( exit == 0 ) 195 {196 a = 1 + rand() % ( ROWS - 2 );197 maze[ a ][ 0 ] = '.';198 } // end if199 else if ( exit == 1 ) 200 {201 a = 1 + rand() % ( COLS - 2 );202 maze[ 0 ][ a ] = '.';203 } // end else if204 else if ( exit == 2 ) 205 {206 a = 1 + rand() % ( ROWS - 2 );207 maze[ a ][ COLS - 1 ] = '.';208 } // end else if209 else 210 {211 a = 1 + rand() % ( COLS - 2 );212 maze[ ROWS - 1 ][ a ] = '.';213 } // end else214215 for ( int loop = 1; loop < ( ROWS - 2 ) * ( COLS - 2 ); ++loop ) 216 {217 x = 1 + rand() % ( ROWS - 2 ); // add dots to maze218 y = 1 + rand() % ( COLS - 2 );219 maze[ x ][ y ] = '.';220 } // end for221 } // end function mazeGenerator

cpphtp5_08_IM.fm Page 548 Thursday, December 23, 2004 4:14 PM

Page 48: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

More Pointer Exercises 549

8.28 (Modifications to the Simpletron Simulator) In Exercise 8.19, you wrote a software simula-tion of a computer that executes programs written in Simpletron Machine Language (SML). In thisexercise, we propose several modifications and enhancements to the Simpletron Simulator. InExercise 21.26 and Exercise 21.27, we propose building a compiler that converts programs writtenin a high-level programming language (a variation of BASIC) to SML. Some of the following mod-ifications and enhancements may be required to execute the programs produced by the compiler.[Note: Some modifications may conflict with others and therefore must be done separately.]

a) Extend the Simpletron Simulator’s memory to contain 1000 memory locations to en-able the Simpletron to handle larger programs.

b) Allow the simulator to perform modulus calculations. This requires an additional Sim-pletron Machine Language instruction.

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # ## . # . # # . . . . . # . . . # . . . . # . . . . . . . # ## . # . # # . . # # # # . . . . . . . . # . # # # # . # # ## . . # . . # . . # . . . . . # # . # . . # . # . . . . . ## # . . # . # . # # # . # # . . . . # . # # . # . # # # # ## # . . . . . . . # . . . . . . . . . . . # # # . # . . . ## # . . . # . # . . # # # # . # . # . . . . # # . . # . # ## # # # . # . . . . . . . # # . . . . . . . # # # . . . . ## . # # . . . . # # . . . # . . # # # . # . . . . . . . . ## # # . # . # # . . # # . # . # . . . . # . # # # . . . . ## . . # . . # # . . . # . . . . . . # # . . # . . # . . . ## # . # # . . . # . . . # # . . . # . . # # # . . # # . . ## # # . . . # # . . . . . . # . # # # . # . # # . # . # # #x . . # . # . # . . . . # # . . . . . # . . . # . . # . # ## # # # # # # # . # # # # # # # # # # # # # # # # # # # # #

Hit return to see next move...

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # ## . # . # # . . . . . # . . . # . . . . # . . . . . . . # ## . # . # # . . # # # # . . . . . . . . # . # # # # . # # ## . . # . . # . . # . . . . . # # . # . . # . # . . . . . ## # . . # . # . # # # . # # . . . . # . # # . # . # # # # ## # . . . . . . . # . . . . . . . . . . . # # # . # . . . ## # . . . # . # . . # # # # . # . # . . . . # # . . # . # ## # # # . # . . . . . . . # # . . . . . . . # # # . . . . ## . # # . . . . # # . . . # . . # # # . # . . . . . . . . ## # # . # . # # . . # # . # . # . . . . # . # # # . . . . ## . . # . . # # . . . # . . . . . . # # . . # . . # . . . ## # . # # . . . # . . . # # . . . # . . # # # . . # # . . ## # # . . . # # . . . . . . # . # # # . # . # # . # . # # #x x x # . # . # . . . . # # . . . . . # . . . # . . # . # ## # # # # # # # . # # # # # # # # # # # # # # # # # # # # #

Hit return to see next move

Arrived back at the starting location.

cpphtp5_08_IM.fm Page 549 Thursday, December 23, 2004 4:14 PM

Page 49: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

550 Chapter 8 Pointers and Pointer-Based Strings

c) Allow the simulator to perform exponentiation calculations. This requires an additionalSimpletron Machine Language instruction.

d) Modify the simulator to use hexadecimal values rather than integer values to representSimpletron Machine Language instructions.

e) Modify the simulator to allow output of a newline. This requires an additional Sim-pletron Machine Language instruction.

f) Modify the simulator to process floating-point values in addition to integer values.g) Modify the simulator to handle string input. [Hint: Each Simpletron word can be di-

vided into two groups, each holding a two-digit integer. Each two-digit integer repre-sents the ASCII decimal equivalent of a character. Add a machine-language instructionthat will input a string and store the string beginning at a specific Simpletron memorylocation. The first half of the word at that location will be a count of the number ofcharacters in the string (i.e., the length of the string). Each succeeding half-word con-tains one ASCII character expressed as two decimal digits. The machine-language in-struction converts each character into its ASCII equivalent and assigns it to a half-word.]

h) Modify the simulator to handle output of strings stored in the format of part (g). [Hint:Add a machine-language instruction that will print a string beginning at a certain Sim-pletron memory location. The first half of the word at that location is a count of thenumber of characters in the string (i.e., the length of the string). Each succeeding half-word contains one ASCII character expressed as two decimal digits. The machine-lan-guage instruction checks the length and prints the string by translating each two-digitnumber into its equivalent character.]

i) Modify the simulator to include instruction SML_DEBUG that prints a memory dump af-ter each instruction executes. Give SML_DEBUG an operation code of 44. The word +4401turns on debug mode, and +4400 turns off debug mode.

cpphtp5_08_IM.fm Page 550 Thursday, December 23, 2004 4:14 PM

Page 50: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

String-Manipulation Exercises 551

8.29 What does this program do?

ANS: Function mystery3 compares two strings for equality.

String-Manipulation Exercises[Note: The following exercises should be implemented using C-style, pointer-based strings.]

8.30 Write a program that uses function strcmp to compare two strings input by the user. Theprogram should state whether the first string is less than, equal to or greater than the second string.

ANS:

1 // Ex. 8.30: ex08_30.cpp2 // What does this program do?3 #include <iostream>4 using std::cout;5 using std::cin;6 using std::endl;78 bool mystery3( const char *, const char * ); // prototype9

10 int main()11 {12 char string1[ 80 ], string2[ 80 ];1314 cout << "Enter two strings: ";15 cin >> string1 >> string2;16 cout << "The result is " << mystery3( string1, string2 ) << endl;17 return 0; // indicates successful termination18 } // end main1920 // What does this function do?21 bool mystery3( const char *s1, const char *s2 )22 {23 for ( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ )2425 if ( *s1 != *s2 )26 return false;2728 return true;29 } // end function mystery3

1 // Exercise 8.30 Solution: Ex08_30.cpp2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl; 67 #include <cstring> 8 using std::strcmp;9

10 const int SIZE = 20;11

cpphtp5_08_IM.fm Page 551 Thursday, December 23, 2004 4:14 PM

Page 51: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

552 Chapter 8 Pointers and Pointer-Based Strings

8.31 Write a program that uses function strncmp to compare two strings input by the user. Theprogram should input the number of characters to compare. The program should state whether thefirst string is less than, equal to or greater than the second string.

ANS:

12 int main()13 {14 char string1[ SIZE ];15 char string2[ SIZE ];16 int result;1718 cout << "Enter two strings: ";19 cin >> string1 >> string2;20 21 // uses function strcmp to compare the two strings22 result = strcmp( string1, string2 );23 24 if ( result > 0 )25 cout << '\"' << string1 << '\"' << " is greater than \""26 << string2 << '\"' << endl;27 else if ( result == 0 )28 cout << '\"' << string1 << '\"' << " is equal to \"" << string229 << '\"' << endl;30 else31 cout << '\"' << string1 << '\"' << " is less than \"" << string232 << '\"' << endl;3334 return 0; // indicates successful termination35 } // end main

Enter two strings: green leaf"green" is less than "leaf"

1 // Exercise 8.31 Solution: Ex08_31.cpp2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl; 67 #include <cstring> 8 using std::strncmp;9

10 const int SIZE = 20;1112 int main()13 {14 char string1[ SIZE ];15 char string2[ SIZE ];16 int result;17 int compareCount; // number of characters to compare18 19 cout << "Enter two strings: ";20 cin >> string1 >> string2;

cpphtp5_08_IM.fm Page 552 Thursday, December 23, 2004 4:14 PM

Page 52: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

String-Manipulation Exercises 553

8.32 Write a program that uses random number generation to create sentences. The programshould use four arrays of pointers to char called article, noun, verb and preposition. The programshould create a sentence by selecting a word at random from each array in the following order: ar-ticle, noun, verb, preposition, article and noun. As each word is picked, it should be concatenat-ed to the previous words in an array that is large enough to hold the entire sentence. The wordsshould be separated by spaces. When the final sentence is output, it should start with a capital letterand 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 thesesentences. (How about the possibility of a random term-paper writer!)

ANS:

21 cout << "How many characters should be compared: ";22 cin >> compareCount;23 24 // call function strncmp to compare the two strings25 result = strncmp( string1, string2, compareCount );26 27 if ( result > 0 )28 cout << '\"' << string1 << "\" is greater than \"" << string229 << "\" up to " << compareCount << " characters\n";30 else if ( result == 0 )31 cout << '\"' << string1 << "\" is equal to \"" << string232 << "\" up to " << compareCount << " characters\n";33 else34 cout << '\"' << string1 << "\" is less than \"" << string235 << "\" up to " << compareCount << " characters\n";36 37 cout << endl;38 return 0; // indicates successful termination39 } // end main

Enter two strings: sand sandpaperHow many characters should be compared: 4"sand" is equal to "sandpaper" up to 4 characters

1 // Exercise 8.32 Solution: Ex08_32.cpp2 #include <iostream> 3 using std::cout; 4 using std::endl; 56 #include <cstdlib>7 using std::rand;8 using std::srand;9

10 #include <ctime>11 using std::time;12

cpphtp5_08_IM.fm Page 553 Thursday, December 23, 2004 4:14 PM

Page 53: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

554 Chapter 8 Pointers and Pointer-Based Strings

13 #include <cctype>14 using std::toupper;1516 const int SIZE = 100;1718 int main()19 {20 // arrays declared for articale, noun, verb, and preposition21 const char *article[] = { "the", "a", "one", "some", "any" };22 const char *noun[] = { "boy", "girl", "dog", "town", "car" };23 const char *verb[] = { "drove", "jumped", "ran", "walked", "skipped" };24 const char *preposition[] = { "to", "from", "over", "under", "on" };25 char sentence[ SIZE ] = ""; // to hold the sentence2627 srand( time( 0 ) ); // seed random number generator2829 // loop through and make 20 random sentences out of the given arrays30 for ( int i = 1; i <= 20; ++i ) 31 {32 // uses function strcat to concatenate random sentences33 strcat( sentence, article[ rand() % 5 ] );34 strcat( sentence, " " );35 strcat( sentence, noun[ rand() % 5 ] );36 strcat( sentence, " " );37 strcat( sentence, verb[ rand() % 5 ] );38 strcat( sentence, " " );39 strcat( sentence, preposition[ rand() % 5 ] );40 strcat( sentence, " " );41 strcat( sentence, article[ rand() % 5 ] );42 strcat( sentence, " " );43 strcat( sentence, noun[ rand() % 5 ] );44 45 // print the current sentence46 cout << static_cast< char > ( toupper( sentence[ 0 ] ) ) 47 << &sentence[ 1 ] << ".\n";48 49 sentence[ 0 ] = '\0'; // reset the sentence50 } // end for5152 cout << endl;53 return 0; // indicates successful termination54 } // end main

cpphtp5_08_IM.fm Page 554 Thursday, December 23, 2004 4:14 PM

Page 54: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

String-Manipulation Exercises 555

8.33 (Limericks) A limerick is a humorous five-line verse in which the first and second linesrhyme with the fifth, and the third line rhymes with the fourth. Using techniques similar to thosedeveloped in Exercise 8.32, write a C++ program that produces random limericks. Polishing thisprogram to produce good limericks is a challenging problem, but the result will be worth the effort!

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

ANS:

A dog ran under a dog.Any town walked to any dog.Any town drove on any dog.The dog skipped over one town.Some girl walked to the dog.The girl ran to a car.The dog jumped from the boy.Some boy walked over the girl.A dog drove on a girl.Some car jumped from any car.A boy jumped to some girl.Some girl ran over any boy.One town skipped from some car.Any girl jumped on a car.Some dog jumped on a town.A boy drove from the boy.One town skipped under the girl.One boy skipped to some dog.Any car ran on a town.The car jumped to one boy.

1 // Exercise 8.34 Solution: Ex08_34.cpp2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl; 67 #include <cstring> 8 using std::strtok;9

10 const int SIZE = 80;1112 // function prototype13 void printLatinWord( char const * const );14

cpphtp5_08_IM.fm Page 555 Thursday, December 23, 2004 4:14 PM

Page 55: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

556 Chapter 8 Pointers and Pointer-Based Strings

8.35 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 ofthe phone number as a token, and the last four digits of the phone number as a token. The sevendigits of the phone number should be concatenated into one string. Both the area code and thephone number should be printed.

ANS:

15 int main()16 {17 char sentence[ SIZE ];18 char *tokenPtr;19 20 cout << "Enter a sentence:\n";21 cin.getline( sentence, SIZE ); // read in, but only up to 80 characters22 cout << "\nThe sentence in Pig Latin is:\n";23 24 // call function strtok to alter the sentence25 tokenPtr = strtok( sentence, " .,;" );26 27 // if there is still word in tokenPtr28 while ( tokenPtr ) 29 {30 printLatinWord( tokenPtr );31 tokenPtr = strtok( 0, " .,;" );32 33 if ( tokenPtr )34 cout << ' ';35 } // end while36 37 cout << '.' << endl;38 return 0;39 } // end main4041 // print out the English word in pig latin form42 void printLatinWord( char const * const wordPtr )43 {44 int len = strlen( wordPtr );4546 // loop through the word47 for (int i = 1; i < len; i++ )48 cout << *( wordPtr + i );4950 cout << *wordPtr << "ay";51 } // end printLatinWord

Enter a sentence:mirror mirror on the wall

The sentence in Pig Latin is:irrormay irrormay noay hetay allway.

1 // Exercise 8.35 Solution: Ex08_35.cpp2 #include <iostream>

cpphtp5_08_IM.fm Page 556 Thursday, December 23, 2004 4:14 PM

Page 56: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

String-Manipulation Exercises 557

3 using std::cin; 4 using std::cout; 5 using std::endl; 67 #include <cstring> 8 using std::strtok;9

10 #include <cstdlib>1112 int main()13 {14 const int SIZE1 = 20;15 const int SIZE2 = 10;16 17 char p[ SIZE1 ];18 char phoneNumber[ SIZE2 ] = { '\0' };19 20 char *tokenPtr; // store temporary token21 char *areaCode; // store area code22 char *phone; // store the phone number23 24 cout << "Enter a phone number in the form (555) 555-5555:\n";25 cin.getline( p, SIZE1 );26 27 // pick apart the area code from the entire string28 areaCode = strtok( p, "()" );29 30 // function strtok to take the next token in the string31 tokenPtr = strtok( 0, "-" );3233 // copies the result from the second call to strtok into phoneNumber34 strcpy( phoneNumber, tokenPtr );3536 // the last call to strtok to take the last 4 digits37 tokenPtr = strtok( 0, "" );3839 // concatenate the result with the current phoneNumber40 strcat( phoneNumber, tokenPtr );4142 phone = phoneNumber;43 44 cout << "\nThe area code is " << areaCode 45 << "\nThe phone number is " << phone << endl;4647 return 0; // indicates successful termination48 } // end main

Enter a phone number in the form (555) 555-5555:(555) 429-4195

The area code is 555The phone number is 4294195

cpphtp5_08_IM.fm Page 557 Thursday, December 23, 2004 4:14 PM

Page 57: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

558 Chapter 8 Pointers and Pointer-Based Strings

8.36 Write a program that inputs a line of text, tokenizes the line with function strtok and out-puts the tokens in reverse order.

ANS:

1 // Exercise 8.36 Solution: Ex08_36.cpp2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl; 67 #include <cstring> 8 using std::strtok;9

10 void reverseTokens( char * const ); // prototype1112 int main()13 {14 const int SIZE = 80;15 char text[ SIZE ];16 17 cout << "Enter a line of text:\n";18 cin.getline( text, SIZE );19 20 // call to function reverseTokens21 reverseTokens( text );22 cout << endl;23 return 0; // indicate successful termination24 } // end main2526 // function to reverse the individual tokens 27 void reverseTokens( char * const sentence )28 {29 char *pointers[ 50 ]; // array to store entire sentence30 char *temp; // store each word3132 int count = 0; // serve as array counter33 34 // call function strtok to take first word out of sentence35 temp = strtok( sentence, " " );36 37 // while temp is not empty38 while ( temp ) 39 {40 // add the word into the array41 pointers[ count++ ] = temp;42 43 // get each subsequent word from the sentence44 temp = strtok( 0, " " );45 } // end loop46 47 cout << "\nThe tokens in reverse order are:\n";4849 // loop through the array backwards 50 for ( int i = count - 1; i >= 0; i-- )

cpphtp5_08_IM.fm Page 558 Thursday, December 23, 2004 4:14 PM

Page 58: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

String-Manipulation Exercises 559

8.37 Use the string-comparison functions discussed in Section 8.13.2 and the techniques forsorting arrays developed in Chapter 7 to write a program that alphabetizes a list of strings. Use thenames of 10 or 15 towns in your area as data for your program.

ANS:

51 cout << pointers[ i ] << ' ';52 } // end function reverseTokens

Enter a line of text:twinkle twinkle little star

The tokens in reverse order are:star little twinkle twinkle

1 // Exercise 8.37 Solution: Ex08_37.cpp2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl; 67 #include <cstring> 8 using std::strcmp;9

10 const int SIZE = 50;1112 void insertionSort( char [][ SIZE ] ); // prototype1314 int main()15 {16 char array[ 10 ][ SIZE ]; // character array17 int i; // index1819 // loop to take in 10 strings20 for ( i = 0; i < 10; i++ ) 21 {22 cout << "Enter a string: ";23 cin >> &array[ i ][ 0 ];24 } // end for25 26 // call function insertionSort to sort the array content27 insertionSort( array );28 cout << "\nThe strings in sorted order are:\n";29 30 // print out the sorted array31 for ( i = 0; i < 10; i++ )32 cout << &array[ i ][ 0 ] << endl;3334 return 0; // indicates successful termination35 } // end main3637 // sorting function38 void insertionSort( char a[][ SIZE ] )39 {

cpphtp5_08_IM.fm Page 559 Thursday, December 23, 2004 4:14 PM

Page 59: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

560 Chapter 8 Pointers and Pointer-Based Strings

8.38 Write two versions of each string copy and string-concatenation function in Fig. 8.30. Thefirst version should use array subscripting, and the second should use pointers and pointer arithmetic.

ANS:

40 char insert[ SIZE ]; // temporary variable to hold element to insert4142 // loop over elements43 for ( int next = 1; next < 10; next++ )44 {45 strcpy( insert, a[ next ] ); // store value in current element46 int moveItem = next; // initialize location to place element4748 // search for place to put current element49 while ( moveItem > 0 && strcmp( a[ moveItem - 1 ], insert ) > 0 )50 {51 // shift element right one slot52 strcpy( a[ moveItem ], a[ moveItem - 1 ] );53 moveItem--;54 } // end while5556 strcpy( a[ moveItem ], insert ); // place inserted element57 } // end for58 } // end function insertionSort

Enter a string: WeymouthEnter a string: BraintreeEnter a string: QuincyEnter a string: SudburyEnter a string: WaylandEnter a string: WestonEnter a string: HansonEnter a string: BourneEnter a string: BridgewaterEnter a string: Carver

The strings in sorted order are:BourneBraintreeBridgewaterCarverHansonQuincySudburyWaylandWestonWeymouth

1 // Exercise 8.38 Solution: Ex08_38.cpp2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl; 67 // function prototypes

cpphtp5_08_IM.fm Page 560 Thursday, December 23, 2004 4:14 PM

Page 60: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

String-Manipulation Exercises 561

8 char *stringCopy1( char *, const char * );9 char *stringCopy2( char *, const char * );

10 char *stringNCopy1( char *, const char *, unsigned );11 char *stringNCopy2( char *, const char *, unsigned );12 char *stringCat1( char *, const char * );13 char *stringCat2( char *, const char * );14 char *stringNCat1( char *, const char *, unsigned );15 char *stringNCat2( char *, const char *, unsigned );1617 int main()18 {19 int n = 4;20 char string1[ 100 ];21 char string2[ 100 ];2223 cout << "Enter a string: ";24 cin >> string2;2526 // copy string2 into string1 using different functions27 cout << "Copied string returned from stringCopy1 is "28 << stringCopy1( string1, string2 ) 29 << "\nCopied string returned from stringCopy2 is "30 << stringCopy2( string1, string2 );31 32 cout << "\nCopied " << n << " elements returned from stringNCopy1 is "33 << stringNCopy1( string1, string2, n )34 << "\nCopied " << n << " elements returned from stringNCopy2 is "35 << stringNCopy2(string1, string2, n);36 37 cout << "\nConcatenated string returned from stringCat1 is "38 << stringCat1( string1, string2 )39 << "\nConcatenated string returned from stringCat2 is "40 << stringCat2( string1, string2 );41 42 cout << "\nConcatenated string returned from stringNCat1 is "43 << stringNCat1( string1, string2, n )44 << "\nConcatenated string returned from stringNCat2 is "45 << stringNCat2( string1, string2, n ) << endl;46 return 0; // indicates successful termination47 } // end main4849 // copying string with array subscripting50 char *stringCopy1( char *s1, const char *s2 )51 {52 // loop53 for ( int sub = 0; s1[ sub ] = s2[ sub ]; sub++ )54 ; // empty body5556 return s1;57 } // end function stringCopy15859 // copying string with pointers and pointer arithmetic60 char *stringCopy2( char *s1, const char *s2 )61 {62 char *ptr = s1;

cpphtp5_08_IM.fm Page 561 Thursday, December 23, 2004 4:14 PM

Page 61: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

562 Chapter 8 Pointers and Pointer-Based Strings

6364 for ( ; *s1 = *s2; s1++, s2++ )65 ; // empty body6667 return ptr;68 } // end function stringCopy26970 // string copy using aray71 char *stringNCopy1( char *s1, const char *s2, unsigned n )72 {73 unsigned c;7475 for ( c = 0; c < n && ( s1[ c ] = s2[ c ] ); c++ )76 ; // empty body7778 s1[ c ] = '\0';79 return s1;80 } // end function stringNCopy18182 // string copy using pointers83 char *stringNCopy2( char *s1, const char *s2, unsigned n )84 {85 char *ptr = s1;86 87 for ( unsigned c = 0; c < n; c++, s1++, s2++ )88 *s1 = *s2;8990 *s1 = '\0';91 return ptr;92 } // end function stringNCopy29394 // string concatenation using arrays95 char *stringCat1( char *s1, const char *s2 )96 {97 int x;9899 for ( x = 0; s1[ x ] != '\0'; x++ )100 ; // empty body101102 for ( int y = 0; s1[ x ] = s2[ y ]; x++, y++ )103 ; // empty body104105 return s1;106 } // end function stringCat1107108 // string concatenation using pointers109 char *stringCat2( char *s1, const char *s2 )110 {111 char *ptr = s1;112113 for ( ; *s1 != '\0'; s1++ )114 ; // empty body115116 for ( ; *s1 = *s2; s1++, s2++ )117 ; // empty body

cpphtp5_08_IM.fm Page 562 Thursday, December 23, 2004 4:14 PM

Page 62: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

String-Manipulation Exercises 563

8.39 Write two versions of each string-comparison function in Fig. 8.30. The first versionshould use array subscripting, and the second should use pointers and pointer arithmetic.

ANS:

118119 return ptr;120 } // end function stringCat2121122 // another version of string concatenation using arrays123 char *stringNCat1( char *s1, const char *s2, unsigned n )124 {125 int x;126127 for ( x = 0; s1[ x ] != '\0'; x++ )128 ; // empty body129130 for ( unsigned y = 0; y < n && ( s1[ x ] = s2[ y ] ); x++, y++ )131 ; // empty body132133 s1[ x ] = '\0';134 return s1;135 } // end function stringNCat1136137 // another form of string concatenation using pointers138 char *stringNCat2( char *s1, const char *s2, unsigned n )139 {140 char *ptr = s1;141142 for ( ; *s1 != '\0'; s1++ )143 ; // empty body144145 for ( unsigned c = 0 ; c < n && ( *s1 = *s2 ); s1++, s2++ )146 ; // empty body147148 *s1 = '\0';149 return ptr;150 } // end function stringNCat2

Enter a string: cooCopied string returned from stringCopy1 is cooCopied string returned from stringCopy2 is cooCopied 4 elements returned from stringNCopy1 is cooCopied 4 elements returned from stringNCopy2 is cooConcatenated string returned from stringCat1 is coocooConcatenated string returned from stringCat2 is coocoocooConcatenated string returned from stringNCat1 is coocoocoocooConcatenated string returned from stringNCat2 is coocoocoocoocoo

1 // Exercise 8.39 Solution: Ex08_39.cpp2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl;

cpphtp5_08_IM.fm Page 563 Thursday, December 23, 2004 4:14 PM

Page 63: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

564 Chapter 8 Pointers and Pointer-Based Strings

67 int stringCompare1( const char *, const char * );8 int stringCompare2( const char *, const char * );9 int stringNCompare1( const char *, const char *, unsigned );

10 int stringNCompare2( const char *, const char *, unsigned );1112 int main()13 {14 char string1[ 100 ], string2[ 100 ];15 unsigned n = 3; // number of characters to be compared1617 cout << "Enter two strings: ";18 cin >> string1 >> string2;1920 cout << "The value returned from stringCompare1(\"" << string121 << "\", \"" << string2 << "\") is "22 << stringCompare1(string1, string2) 23 << "\nThe value returned from stringCompare2(\"" << string124 << "\", \"" << string2 << "\") is "25 << stringCompare2(string1, string2) << '\n';2627 cout << "\nThe value returned from stringNCompare1(\"" << string128 << "\", \"" << string2 << "\", " << n << ") is "29 << stringNCompare1(string1, string2, n) 30 << "\nThe value returned from stringNCompare2(\"" << string131 << "\", \"" << string2 << "\", " << n << ") is "32 << stringNCompare2( string1, string2, n ) << endl;33 return 0;34 } // end main3536 int stringCompare1( const char *s1, const char *s2 )37 {38 int sub;3940 // array subscript notation41 for ( sub = 0; s1[ sub ] == s2[ sub ]; sub++ )42 ; // empty statement4344 sub--;4546 if ( s1[ sub ] == '\0' && s2[ sub ] == '\0' )47 return 0;48 else if ( s1[ sub] < s2[ sub ] )49 return -1;50 else51 return 1; 52 } // end function stringCompare15354 int stringCompare2( const char *s1, const char *s2 )55 {56 // pointer notation57 for ( ; *s1 == *s2; s1++, s2++ )58 ; // empty statement5960 s1--;

cpphtp5_08_IM.fm Page 564 Thursday, December 23, 2004 4:14 PM

Page 64: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

String-Manipulation Exercises 565

61 s2--;6263 if ( *s1 == '\0' && *s2 == '\0' )64 return 0;65 else if ( *s1 < *s2 )66 return -1;67 else68 return 1;69 } // end function stringCompare27071 int stringNCompare1( const char *s1, const char *s2, unsigned n )72 {73 unsigned sub;7475 // array subscript notation76 for ( sub = 0; sub < n && ( s1[ sub ] == s2[ sub ] ); sub++ )77 ; // empty body7879 sub--;8081 if ( s1[ sub ] == s2[ sub ] ) 82 return 0;83 else if ( s1[ sub ] < s2[ sub ] )84 return -1;85 else86 return 1;87 } // end function stringNCompare18889 int stringNCompare2( const char *s1, const char *s2, unsigned n )90 {91 // pointer notation92 for ( unsigned c = 0; c < n && (*s1 == *s2); c++, s1++, s2++ )93 ; // empty statement9495 s1--;96 s2--;9798 if ( *s1 == *s2 )99 return 0;100 else if ( *s1 < *s2 )101 return -1;102 else103 return 1;104 } // end function stringNCompare2

Enter two strings: tommy tomatoThe value returned from stringCompare1("tommy", "tomato") is 1The value returned from stringCompare2("tommy", "tomato") is 1

The value returned from stringNCompare1("tommy", "tomato", 3) is 0The value returned from stringNCompare2("tommy", "tomato", 3) is 0

cpphtp5_08_IM.fm Page 565 Thursday, December 23, 2004 4:14 PM

Page 65: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

566 Chapter 8 Pointers and Pointer-Based Strings

8.40 Write two versions of function strlen in Fig. 8.30. The first version should use array sub-scripting, and the second should use pointers and pointer arithmetic.

ANS:

1 // Exercise 8.40 Solution: Ex08_40.cpp2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl; 67 // prototype8 unsigned long stringLength1( const char * );9 unsigned long stringLength2( const char * );

1011 int main()12 {13 char string[ 100 ];1415 cout << "Enter a string: ";16 cin >> string;1718 cout << "\nAccording to stringLength1 the string length is: "19 << stringLength1( string ) 20 << "\nAccording to stringLength2 the string length is: "21 << stringLength2( string ) << endl;2223 return 0; // indicate successful termination24 } // end main2526 // finding string length using arrays27 unsigned long stringLength1( const char *sPtr )28 {29 // array subscript notation30 for ( int length = 0; sPtr[ length ] != '\0'; length++ )31 ; // empty body3233 return length;34 } // end function stringLength13536 // finding string length using pointers37 unsigned long stringLength2( const char *sPtr )38 {39 // pointer notation40 for ( int length = 0; *sPtr != '\0'; sPtr++, length++ )41 ; // empty body4243 return length;44 } // end function stringLength2

Enter a string: length

According to stringLength1 the string length is: 6According to stringLength2 the string length is: 6

cpphtp5_08_IM.fm Page 566 Thursday, December 23, 2004 4:14 PM

Page 66: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Special Section: Advanced String-Manipulation Exercises 567

Special Section: Advanced String-Manipulation ExercisesThe preceding exercises are keyed to the text and designed to test the reader’s understanding of fun-damental string-manipulation concepts. This section includes a collection of intermediate andadvanced string-manipulation exercises. The reader should find these problems challenging, yetenjoyable. The problems vary considerably in difficulty. Some require an hour or two of programwriting and implementation. Others are useful for lab assignments that might require two or threeweeks of study and implementation. Some are challenging term projects.

8.41 (Text Analysis) The availability of computers with string-manipulation capabilities has re-sulted in some rather interesting approaches to analyzing the writings of great authors. Much atten-tion has been focused on whether William Shakespeare ever lived. Some scholars believe there issubstantial evidence indicating that Christopher Marlowe or other authors actually penned the mas-terpieces attributed to Shakespeare. Researchers have used computers to find similarities in the writ-ings of these two authors. This exercise examines three methods for analyzing texts with a computer.Note that thousands of texts, including Shakespeare, are available online at www.gutenberg.org.

a) Write a program that reads several lines of text from the keyboard and prints a table in-dicating the number of occurrences of each letter of the alphabet in the text. For exam-ple, the phrase

To be, or not to be: that is the question:

contains one “a,” two “b’s,” no “c’s,” etc.b) Write a program that reads several lines of text and prints a table indicating the number

of one-letter words, two-letter words, three-letter words, etc., appearing in the text. Forexample, the phrase

Whether 'tis nobler in the mind to suffer

contains the following word lengths and occurrences:

c) Write a program that reads several lines of text and prints a table indicating the numberof occurrences of each different word in the text. The first version of your programshould include the words in the table in the same order in which they appear in the text.For example, the lines

To be, or not to be: that is the question: Whether 'tis nobler in the mind to suffer

Word length Occurrences

1 0

2 2

3 1

4 2 (including 'tis)

5 0

6 2

7 1

cpphtp5_08_IM.fm Page 567 Thursday, December 23, 2004 4:14 PM

Page 67: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

568 Chapter 8 Pointers and Pointer-Based Strings

contain the words “to” three times, the word “be” two times, the word “or” once, etc. Amore interesting (and useful) printout should then be attempted in which the wordsare sorted alphabetically.

ANS:

1 // Exercise 8.41 Part A Solution: Ex_08.cpp2 #include <iostream> 3 using std::cin;4 using std::cout; 5 using std::endl; 67 #include <iomanip> 8 using std::setw; 9

10 #include <cctype>11 using std::tolower;1213 const int SIZE = 80;1415 int main()16 {17 char letters[ 26 ] = { 0 };18 char text[ 3 ][ SIZE ];19 char i; // index variable20 21 cout << "Enter three lines of text:\n";22 23 // make sure there are three lines of text24 for ( i = 0; i <= 2; ++i )25 cin.getline( &text[ i ][ 0 ], SIZE );26 27 // for each line28 for ( i = 0; i <= 2; i++ )29 30 // for each word in the line31 for ( int j = 0; text[ i ][ j ] != '\0'; j++ )32 33 // function isalpha returns true if the element is 34 // an alphabetic character 35 if ( isalpha( text[ i ][ j ] ) )3637 // increment the proper location in the letters array38 letters[ tolower( text[ i ][ j ] ) - 'a' ]++; 39 40 cout << "\nTotal letter counts:\n";41 42 // loop through and print the tally for each character43 for ( i = 0; i <= 25; i++ )44 cout << setw( 3 ) << static_cast< char > ( 'a' + i ) << ':' 45 << setw( 3 ) << static_cast< int > ( letters[ i ] ) << endl;4647 return 0; // indicate successful termination48 } // end main

cpphtp5_08_IM.fm Page 568 Thursday, December 23, 2004 4:14 PM

Page 68: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Special Section: Advanced String-Manipulation Exercises 569

Enter three lines of text:when the cats are away the mice will playstill waters run deepout of sight out of mind

Total letter counts: a: 6 b: 0 c: 2 d: 2 e: 8 f: 2 g: 1 h: 4 i: 5 j: 0 k: 0 l: 5 m: 2 n: 3 o: 4 p: 2 q: 0 r: 3 s: 4 t: 8 u: 3 v: 0 w: 4 x: 0 y: 2 z: 0

1 // Exercise 8.41 Part B Solution: Ex08_41.cpp2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl; 67 #include <cstring> 8 using std::strtok;9

10 int main()11 {12 const int SIZE = 80;13 char text[ 3 ][ SIZE ];14 char *temp;15 int lengths[ 20 ] = { 0 };16 int i; 1718 cout << "Enter three lines of text:\n";19 20 // gets three lines of text21 for ( i = 0; i <= 2; i++ )

cpphtp5_08_IM.fm Page 569 Thursday, December 23, 2004 4:14 PM

Page 69: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

570 Chapter 8 Pointers and Pointer-Based Strings

22 cin.getline( &text[ i ][ 0 ], SIZE );23 24 // break each word into tokens by using function strtok25 for ( i = 0; i <= 2; i++ ) 26 {27 temp = strtok( &text[ i ][ 0 ], ". \n" );28 29 // while there is still a word30 while ( temp ) 31 {32 // increment the proper place in the length array33 lengths[ strlen( temp ) ]++;3435 // continue to break down the sentence36 temp = strtok( 0, ". \n" );37 } // end while 38 } // end for39 40 cout << '\n';41 42 // produce the output43 for ( i = 1; i <= 19; i++ )4445 if ( lengths[ i ] )46 cout << lengths[ i ] << " word(s) of length: " << i << endl;4748 return 0; // indicates successful termination49 } // end main

Enter three lines of text:the two teams will play again next saturdaythe winner will take the championship homeit is all or nothing

3 word(s) of length: 25 word(s) of length: 36 word(s) of length: 42 word(s) of length: 51 word(s) of length: 61 word(s) of length: 71 word(s) of length: 81 word(s) of length: 12

1 // Exercise 8.41 Part C Solution: Ex08_41.cpp2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl; 67 #include <cstring> 8 using std::strcmp;

cpphtp5_08_IM.fm Page 570 Thursday, December 23, 2004 4:14 PM

Page 70: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Special Section: Advanced String-Manipulation Exercises 571

9 using std::strtok;1011 const int SIZE = 80;1213 int main()14 {15 char text[ 3 ][ SIZE ];16 char *temp;17 char words[ 100 ][ 20 ] = { "" };18 int count[ 100 ] = { 0 };19 int i;20 21 cout << "Enter three lines of text:\n";22 23 // make sure that there are three lines of text24 for ( i = 0; i <= 2; i++ )25 cin.getline( &text[ i ][ 0 ], SIZE );26 27 // make sure that each sentence gets processed28 for ( i = 0; i <= 2; i++ ) 29 {30 // uses function strtok to break each word into tokens31 temp = strtok( &text[ i ][ 0 ], ". \n" );32 33 // while temp is not empty 34 while ( temp ) 35 {36 int j; // indexing variable 3738 for ( j = 0; words[ j ][ 0 ] && 39 strcmp( temp, &words[ j ][ 0 ] ) != 0; j++ )40 ; // empty body41 42 count[ j ]++;43 44 if ( !words[ j ][ 0 ] )45 strcpy( &words[ j ][ 0 ], temp );46 47 temp = strtok( 0, ". \n" ); // make another token48 } // end while49 } // end for 50 51 cout << '\n';52 53 // output the result54 for ( int k = 0; words[ k ][ 0 ] != '\0' && k <= 99; k++ )55 cout << "\"" << &words[ k ][ 0 ] << "\" appeared " << count[ k ]56 << " time(s)\n";5758 cout << endl;59 return 0; // indicates successful termination60 } // end main

cpphtp5_08_IM.fm Page 571 Thursday, December 23, 2004 4:14 PM

Page 71: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

572 Chapter 8 Pointers and Pointer-Based Strings

8.42 (Word Processing) One important function in word-processing systems is type justification—the alignment of words to both the left and right margins of a page. This generates a professional-looking document that gives the appearance of being set in type rather than prepared on a typewrit-er. Type justification can be accomplished on computer systems by inserting blank characters be-tween each of the words in a line so that the rightmost word aligns with the right margin.

Write a program that reads several lines of text and prints this text in type-justified format.Assume that the text is to be printed on paper 8 1/2 inches wide and that one-inch margins are to beallowed on both the left and right sides. Assume that the computer prints 10 characters to the hori-zontal inch. Therefore, your program should print 6-1/2 inches of text, or 65 characters per line.

8.43 (Printing Dates in Various Formats) Dates are commonly printed in several different formatsin business correspondence. Two of the more common formats are

07/21/1955July 21, 1955

Write a program that reads a date in the first format and prints that date in the second format.ANS:

Enter three lines of text:lovebirds make great petsmoisture is the key factor in a great floorpeach faced lovebirds are small birds

"lovebirds" appeared 2 time(s)"make" appeared 1 time(s)"great" appeared 2 time(s)"pets" appeared 1 time(s)"moisture" appeared 1 time(s)"is" appeared 1 time(s)"the" appeared 1 time(s)"key" appeared 1 time(s)"factor" appeared 1 time(s)"in" appeared 1 time(s)"a" appeared 1 time(s)"floor" appeared 1 time(s)"peach" appeared 1 time(s)"faced" appeared 1 time(s)"are" appeared 1 time(s)"small" appeared 1 time(s)"birds" appeared 1 time(s)

1 // Exercise 8.43 Solution: Ex08_43.cpp2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl; 67 int main()8 {9 // array to store twelve months of a year

10 const char *months[ 13 ] = { "", "January", "February", "March", 11 "April", "May", "June", "July", "August", "September", 12 "October", "November", "December" };

cpphtp5_08_IM.fm Page 572 Thursday, December 23, 2004 4:14 PM

Page 72: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Special Section: Advanced String-Manipulation Exercises 573

8.44 (Check Protection) Computers are frequently employed in check-writing systems such aspayroll and accounts-payable applications. Many strange stories circulate regarding weekly pay-checks being printed (by mistake) for amounts in excess of $1 million. Weird amounts are printedby computerized check-writing systems, because of human error or machine failure. Systems design-ers build controls into their systems to prevent such erroneous checks from being issued.

Another serious problem is the intentional alteration of a check amount by someone whointends to cash a check fraudulently. To prevent a dollar amount from being altered, mostcomputerized check-writing systems employ a technique called check protection.

Checks designed for imprinting by computer contain a fixed number of spaces in which thecomputer may print an amount. Suppose that a paycheck contains eight blank spaces in which thecomputer is supposed to print the amount of a weekly paycheck. If the amount is large, then alleight of those spaces will be filled, for example,

1,230.60 (check amount)--------12345678 (position numbers)

On the other hand, if the amount is less than $1000, then several of the spaces would ordi-narily be left blank. For example,

99.87--------12345678

contains three blank spaces. If a check is printed with blank spaces, it is easier for someone to alterthe amount of the check. To prevent a check from being altered, many check-writing systems insertleading asterisks to protect the amount as follows:

***99.87--------12345678

13 int m; // integer for month14 int d; // day15 int y; // year16 17 cout << "Enter a date in the form mm/dd/yy: \n";18 cin >> m;19 cin.ignore();20 cin >> d;21 cin.ignore();22 cin >> y;23 cout << "The date is: " << months[ m ] << ' ' << d << ", " 24 << ( ( y < 50 ) ? y + 2000 : y + 1900 ) << endl;2526 return 0; // indicates successful termination27 } // end main

Enter a date in the form mm/dd/yy:7/18/02The date is: July 18, 2002

cpphtp5_08_IM.fm Page 573 Thursday, December 23, 2004 4:14 PM

Page 73: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

574 Chapter 8 Pointers and Pointer-Based Strings

Write a program that inputs a dollar amount to be printed on a check and then prints theamount in check-protected format with leading asterisks if necessary. Assume that nine spaces areavailable for printing an amount.

ANS:

8.45 (Writing the Word Equivalent of a Check Amount) Continuing the discussion of the previousexample, we reiterate the importance of designing check-writing systems to prevent alteration ofcheck amounts. One common security method requires that the check amount be both written innumbers and “spelled out” in words. Even if someone is able to alter the numerical amount of thecheck, it is extremely difficult to change the amount in words.

Write a program that inputs a numeric check amount and writes the word equivalent of theamount. Your program should be able to handle check amounts as large as $99.99. For example,the amount 112.43 should be written as

1 // Exercise 8.44 Solution: Ex08_44.cpp2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl; 6 using std::ios;78 #include <iomanip> 9 using std::fixed;

10 using std::setfill;11 using std::setprecision;12 using std::setw; 1314 int main()15 {16 double amount;17 double base = 100000.0;18 int i;19 20 cout << "Enter check amount: ";21 cin >> amount;22 cout << "The protected amount is $";23 24 // calculate how many leading asterisk to insert25 for ( i = 0; amount < base; i++ )26 base /= 10;27 28 // insert the asterisk(s)29 for ( int j = 1; j <= i; j++ )30 cout << '*';3132 cout << fixed << setw( 9 - i ) << setfill( '*' ) 33 << setprecision( 2 ) << amount << endl;34 return 0; // indicates successful termination35 } // end main

Enter check amount: 22.88The protected amount is $****22.88

cpphtp5_08_IM.fm Page 574 Thursday, December 23, 2004 4:14 PM

Page 74: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

Special Section: Advanced String-Manipulation Exercises 575

ONE HUNDRED TWELVE and 43/100

ANS:

1 // Exercise 8.45 Solution: Ex08_45.cpp2 // NOTE: THIS PROGRAM ONLY HANDLES VALUES UP TO $99.993 // The program is easily modified to process larger values4 #include <iostream> 5 using std::cin; 6 using std::cout; 7 using std::endl; 89 int main()

10 {11 // array representing string of values from 1-912 const char *digits[ 10 ] = { "", "ONE", "TWO", "THREE", "FOUR", "FIVE",13 "SIX", "SEVEN", "EIGHT", "NINE" };14 15 // array representing string of values from 10-1916 const char *teens[ 10 ] = { "TEN", "ELEVEN", "TWELVE", "THIRTEEN", 17 "FOURTEEN", "FIFTEEN", "SIXTEEN", 18 "SEVENTEEN", "EIGHTEEN", "NINETEEN"};19 20 // array representing string of values from 10-9021 const char *tens[ 10 ] = { "", "TEN", "TWENTY", "THIRTY", "FORTY", 22 "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY" };2324 int dollars;25 int cents;26 int digit1;27 int digit2;28 29 cout << "Enter the check amount (0.00 to 99.99): ";30 cin >> dollars;31 cin.ignore();32 cin >> cents;33 cout << "The check amount in words is:\n";34 35 // test if the integer amount correspond to a certain array36 if ( dollars < 10 )37 cout << digits[ dollars ] << ' ';38 else if ( dollars < 20 )39 cout << teens[ dollars - 10 ] << ' ';40 else 41 {42 digit1 = dollars / 10;43 digit2 = dollars % 10;44 45 if ( !digit2 )46 cout << tens[ digit1 ] << ' ';47 else48 cout << tens[ digit1 ] << "-" << digits[ digit2 ] << ' ';49 } // end else50 51 cout << "and " << cents << "/100" << endl;

cpphtp5_08_IM.fm Page 575 Thursday, December 23, 2004 4:14 PM

Page 75: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

576 Chapter 8 Pointers and Pointer-Based Strings

8.46 (Morse Code) Perhaps the most famous of all coding schemes is the Morse code, developedby Samuel Morse in 1832 for use with the telegraph system. The Morse code assigns a series of dotsand dashes to each letter of the alphabet, each digit and a few special characters (such as period, com-ma, colon and semicolon). In sound-oriented systems, the dot represents a short sound, and thedash represents a long sound. Other representations of dots and dashes are used with light-orientedsystems and signal-flag systems.

Separation between words is indicated by a space, or, quite simply, the absence of a dot ordash. In a sound-oriented system, a space is indicated by a short period of time during which nosound is transmitted. The international version of the Morse code appears in Fig. 8.45.

Write a program that reads an English-language phrase and encodes it into Morse code. Also writea program that reads a phrase in Morse code and converts it into the English-language equivalent. Useone blank between each Morse-coded letter and three blanks between each Morse-coded word.

52 return 0; // indicates successful termination53 } // end main

Enter the check amount (0.00 to 99.99): 72.68The check amount in words is:SEVENTY-TWO and 68/100

Character Code Character Code

A .- N -.

B -... O ---

C -.-. P .--.

D -.. Q --.-

E . R .-.

F ..-. S ...

G --. T -

H .... U ..-

I .. V ...-

J .--- W .--

K -.- X -..-

L .-.. Y -.--

M -- Z --..

Digits

1 .---- 6 -....

2 ..--- 7 --...

3 ...-- 8 ---..

Fig. 8.45 | Morse code alphabet. (Part 1 of 2.)

cpphtp5_08_IM.fm Page 576 Thursday, December 23, 2004 4:14 PM

Page 76: Pointers and Pointer-Based Strings - Deekle.Netdeekle.net/Jones/FallAndWinter2005-6/COP/08.pdfSelf-Review Exercises ... 504 Chapter 8 Pointers and Pointer-Based Strings f) Use a for

A Challenging String-Manipulation Project 577

8.47 (A Metric Conversion Program) Write a program that will assist the user with metric con-versions. Your program should allow the user to specify the names of the units as strings (i.e., cen-timeters, liters, grams, etc., for the metric system and inches, quarts, pounds, etc., for the Englishsystem) and should respond to simple questions such as

"How many inches are in 2 meters?""How many liters are in 10 quarts?"

Your program should recognize invalid conversions. For example, the question

"How many feet are in 5 kilograms?"

is not meaningful, because "feet" are units of length, while "kilograms" are units of weight.

A Challenging String-Manipulation Project8.48 (A Crossword Puzzle Generator) Most people have worked a crossword puzzle, but few haveever attempted to generate one. Generating a crossword puzzle is a difficult problem. It is suggestedhere as a string-manipulation project requiring substantial sophistication and effort. There are manyissues that the programmer must resolve to get even the simplest crossword puzzle generator pro-gram working. For example, how does one represent the grid of a crossword puzzle inside the com-puter? Should one use a series of strings, or should two-dimensional arrays be used? Theprogrammer needs a source of words (i.e., a computerized dictionary) that can be directly referencedby the program. In what form should these words be stored to facilitate the complex manipulationsrequired by the program? The really ambitious reader will want to generate the “clues” portion ofthe puzzle, in which the brief hints for each “across” word and each “down” word are printed forthe puzzle worker. Merely printing a version of the blank puzzle itself is not a simple problem.

4 ....- 9 ----.

5 ..... 0 -----

Character Code Character Code

Fig. 8.45 | Morse code alphabet. (Part 2 of 2.)

cpphtp5_08_IM.fm Page 577 Thursday, December 23, 2004 4:14 PM


Top Related