Chapter 7
Upcoming SlideShare
Loading in...5
×
 

Chapter 7

on

  • 685 views

C++ - 7 edition - Solution

C++ - 7 edition - Solution

Statistics

Views

Total Views
685
Views on SlideShare
685
Embed Views
0

Actions

Likes
0
Downloads
14
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

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

Chapter 7 Chapter 7 Document Transcript

  • Arrays and Vectors:Solutions 7 Now go, write it before them in a table, and note it in a book. —Isaiah 30:8 Begin at the beginning, … and go on till you come to the end: then stop. —Lewis Carroll To go beyond is as wrong as to fall short. —Confucius Objectives In this chapter you’ll learn: ■ To use the array data structure to represent a set of related data items. ■ To use arrays to store, sort and search lists and tables of values. ■ To declare arrays, initialize arrays and refer to the individual elements of arrays. ■ To pass arrays to functions. ■ Basic searching and sorting techniques. ■ To declare and manipulate multidimensional arrays. ■ To use C++ Standard Library class template vector. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 2 Chapter 7 Arrays and Vectors: Solutions Student Solution Exercises 7.10 (Salesperson Salary Ranges) Use a one-dimensional array to solve the following problem. A company pays its salespeople on a commission basis. The salespeople each receive $200 per week plus 9 percent of their gross sales for that week. For example, a salesperson who grosses $5000 in sales in a week receives $200 plus 9 percent of $5000, or a total of $650. Write a program (using an array of counters) that determines how many of the salespeople earned salaries in each of the follow- ing ranges (assume that each salesperson’s salary is truncated to an integer amount): a) $200–299 b) $300–399 c) $400–499 d) $500–599 e) $600–699 f) $700–799 g) $800–899 h) $900–999 i) $1000 and over ANS: 1 // Exercise 7.10 Solution: Ex07_10.cpp 2 #include <iostream> 3 #include <iomanip> 4 using namespace std; 5 6 void wages( int [] ); // function prototype 7 void display( const int [] ); // function prototype 8 9 int main()10 {11 int salaries[ 11 ] = {}; // array to hold salaries1213 cout << fixed << showpoint;14 wages( salaries ); // calculate wages15 display( salaries ); // display ranges of wages16 } // end main1718 // function that asks user to input gross sales19 // and calculates employee salary based on input20 void wages( int money[] )21 {22 double sales; // holds employee gross sales23 double i = 0.09; // 9%, used for calculating salary2425 // prompt user for gross sales and store it in sales26 cout << "Enter employee gross sales (-1 to end): ";27 cin >> sales;2829 // calculate salary based on sales30 // and prompt user for another employee sales amount31 while ( sales != -1 )32 {33 double salary = 200.0 + sales * i;34 cout << setprecision( 2 ) << "Employee Commission is $" © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • Student Solution Exercises 335 << salary << n;3637 int x = static_cast< int > ( salary ) / 100;38 money[ ( x < 10 ? x : 10 ) ]++;3940 cout << "nEnter employee gross sales (-1 to end): ";41 cin >> sales;42 } // end while43 } // end function wages4445 // function that displays table of salary ranges46 // and number of employees in each range47 void display( const int dollars[] )48 {49 // display table of ranges and employees in each range50 cout << "Employees in the range:";5152 for ( int i = 2; i < 10; i++ )53 cout << "n$" << i << "00-$" << i << "99 : " << dollars[ i ];5455 cout << "nOver $1000: " << dollars[ 10 ] << endl;56 } // end function displayEnter employee gross sales (-1 to end): 10000Employee Commission is $1100.00Enter employee gross sales (-1 to end): 4235Employee Commission is $581.15Enter employee gross sales (-1 to end): 600Employee Commission is $254.00Enter employee gross sales (-1 to end): 12500Employee Commission is $1325.00Enter employee gross sales (-1 to end): -1Employees in the range:$200-$299 : 1$300-$399 : 0$400-$499 : 0$500-$599 : 1$600-$699 : 0$700-$799 : 0$800-$899 : 0$900-$999 : 0Over $1000: 2 7.13 Write single statements that perform the following one-dimensional array operations: a) Initialize the 10 elements of integer array counts to zero. ANS: int counts[ 10 ] = {}; b) Add 1 to each of the 15 elements of integer array bonus. ANS: © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 4 Chapter 7 Arrays and Vectors: Solutions for ( int i = 0; i < 15; i++ ) ++bonus[ i ]; c) Read 12 values for double array monthlyTemperatures from the keyboard. ANS: for ( int p = 0; p < 12; p++ ) cin >> monthlyTemperatures[ p ]; d) Print the 5 values of integer array bestScores in column format. ANS: for ( int u = 0; u < 5; u++ ) cout << bestScores[ u ] << t; 7.15 (Duplicate Elimination)Use a one-dimensional array to solve the following problem. Read in 20 numbers, each of which is between 10 and 100, inclusive. As each number is read, validate it and store it in the array only if it is not a duplicate of a number already read. After reading all the values, display only the unique values that the user entered. Provide for the “worst case” in which all 20 numbers are different. Use the smallest possible array to solve this problem. ANS: 1 // Exercise 7.15 Solution: Ex07_15.cpp 2 #include <iostream> 3 using namespace std; 4 5 int main() 6 { 7 const int SIZE = 20; // size of array 8 int a[ SIZE ] = {}; 9 int subscript = 0;10 int duplicate;11 int value; // number entered by user1213 cout << "Enter 20 integers between 10 and 100:n";1415 // get 20 nonduplicate integers in the range between 10 and 10016 for ( int i = 0; i < SIZE; )17 {18 duplicate = 0;19 cin >> value;2021 // validate input and test if there is a duplicate22 if ( value >= 10 && value <= 100 )23 {24 for ( int j = 0; j < subscript; j++ )25 {26 if ( value == a[ j ] )27 {28 duplicate = 1;29 break;30 } // end if31 } // end for32 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • Student Solution Exercises 533 // if number is not a duplicate, enter it in array34 if ( !duplicate )35 {36 a[ subscript++ ] = value;37 ++i;38 } // end if39 else40 cout << "Duplicate number.n";41 } // end if42 else43 cout << "Invalid number.n";44 } // end for4546 cout << "nThe nonduplicate values are:n";4748 // display array of nonduplicates49 for ( int i = 0; i < SIZE; i++ )50 cout << a[ i ] << ;5152 cout << endl;53 } // end mainEnter 20 integers between 10 and 100:105Invalid number.2030405060708090100110Invalid number.10Duplicate number.11223344556677889945The nonduplicate values are:10 20 30 40 50 60 70 80 90 100 11 22 33 44 55 66 77 88 99 45 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 6 Chapter 7 Arrays and Vectors: Solutions 7.20 (Airline Reservations System) A small airline has just purchased a computer for its new au- tomated reservations system. You have been asked to program the new system. You are to write a program to assign seats on each flight of the airline’s only plane (capacity: 10 seats). Your program should display the following menu of alternatives—Please type 1 for "First Class" and Please type 2 for "Economy". If the person types 1, your program should assign a seat in the first class section (seats 1-5). If the person types 2, your program should assign a seat in the economy section (seats 6-10). Your program should print a boarding pass indicating the person’s seat number and whether it is in the first class or economy section of the plane. Use a one-dimensional array to represent the seating chart of the plane. Initialize all the ele- ments of the array to false to indicate that all seats are empty. As each seat is assigned, set the cor- responding elements of the array to true to indicate that the seat is no longer available. Your program should, of course, never assign a seat that has already been assigned. When the first class section is full, your program should ask the person if it is acceptable to be placed in the economy section (and vice versa). If yes, then make the appropriate seat assignment. If no, then print the message "Next flight leaves in 3 hours." ANS: 1 // Exercise 7.20 Solution: Ex07_20.cpp 2 #include <iostream> 3 #include <cctype> 4 using namespace std; 5 6 int main() 7 { 8 const int SEATS = 11; 9 int plane[ SEATS ] = {};10 int people = 0;11 int economy = 6;12 int firstClass = 1;13 int choice;14 char response;1516 // continue until plane is full17 while ( people < 10 )18 {19 cout << "nPlease type 1 for "firstClass"n"20 321 << "Please type 2 for "economy"n";22 cin >> choice;2324 // if user selects first class and seats available, assign seat25 if ( choice == 1 )26 {27 if ( !plane[ firstClass ] && firstClass <= 5 ) // seat available28 {29 cout << "Your seat assignment is " << firstClass30 << " in the first class section.n";31 plane[ firstClass++ ] = 1;32 people++;33 } // end if34 else if ( firstClass > 5 && economy <= 10 ) // take economy seat35 {36 cout << "The firstClass section is full.nWould you " © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • Student Solution Exercises 737 << "like to sit in the economy section (Y or N)? ";38 cin >> response;3940 // if economy is suitable, assign seat in economy section41 if ( response == Y || response == y )42 {43 cout << "Your seat assignment is " << economy44 << " in the economy section.n";45 plane[ economy++ ] = 1;46 people++;47 } // end if48 else // if economy seat not suitable, print next departure49 cout << "Next flight leaves in 3 hours.n";50 } // end outer else51 else // if no economy seats either, print next departure52 cout << "Next flight leaves in 3 hours.n";53 } // end outer if54 else // if user selects economy and seats available, assign seat55 {56 if ( !plane[ economy ] && economy <= 10 ) // seat available57 {58 cout << "Your seat assignment is " << economy59 << " in the economy section.n";60 plane[ economy++ ] = 1;61 people++;62 } // end if63 else if ( firstClass <= 5 ) // first class seat available64 {65 cout << "The economy section is full.nWould you like "66 << "to sit in the firstClass section (Y or N)? ";67 cin >> response;6869 if ( response == Y || response == y )70 {71 cout << "Your seat assignment is " << firstClass72 << " in the first class section.n";73 plane[ firstClass++ ] = 1;74 people++;75 } // end if76 else // if first class not suitable, print next departure77 cout << "Next flight leaves in 3 hours.n";78 } // end outer else79 else // if no seats left, print next departure80 cout << "Next flight leaves in 3 hours.n";81 } // end outer if82 } // end while8384 cout << "All seats for this flight are sold." << endl;85 } // end main © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 8 Chapter 7 Arrays and Vectors: SolutionsPlease type 1 for "firstClass"Please type 2 for "economy"1Your seat assignment is 1 in the first class section.Please type 1 for "firstClass"Please type 2 for "economy"2Your seat assignment is 6 in the economy section.Please type 1 for "firstClass"Please type 2 for "economy"...Please type 1 for "firstClass"Please type 2 for "economy"2The economy section is full.Would you like to sit in the firstClass section (Y or N)? YYour seat assignment is 5 in the first class section.All seats for this flight are sold.7.23 (Turtle Graphics) The Logo language, which is popular among elementary school children,made the concept of turtle graphics famous. Imagine a mechanical turtle that walks around the roomunder the control of a C++ program. The turtle holds a pen in one of two positions, up or down.While the pen is down, the turtle traces out shapes as it moves; while the pen is up, the turtle movesabout freely without writing anything. In this problem, you’ll simulate the operation of the turtleand create a computerized sketchpad as well. Use a 20-by-20 array floor that is initialized to false. Read commands from an array thatcontains them. Keep track of the current position of the turtle at all times and whether the pen iscurrently up or down. Assume that the turtle always starts at position (0, 0) of the floor with itspen up. The set of turtle commands your program must process are shown in Fig. 7.27. Command Meaning 1 Pen up 2 Pen down 3 Turn right 4 Turn left 5,10 Move forward 10 spaces (or a number other than 10) 6 Print the 20-by-20 array 9 End of data (sentinel) Fig. 7.1 | Turtle graphics commands. Suppose that the turtle is somewhere near the center of the floor. The following “program”would draw and print a 12-by-12 square and end with the pen in the up position: © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • Student Solution Exercises 9 2 5,12 3 5,12 3 5,12 3 5,12 1 6 9 As the turtle moves with the pen down, set the appropriate elements of array floor to true. When the 6 command (print) is given, wherever there is a true in the array, display an asterisk or some other character you choose. Wherever there is a zero, display a blank. Write a program to imple- ment the turtle graphics capabilities discussed here. Write several turtle graphics programs to draw interesting shapes. Add other commands to increase the power of your turtle graphics language. ANS: 1 // Exercise 7.23 Solution: Ex07_23.cpp 2 #include <iostream> 3 using namespace std; 4 5 // constant global variables 6 const int MAXCOMMANDS = 100; 7 const int SIZE = 20; 8 9 int turnRight( int ); // function prototype10 int turnLeft( int ); // function prototype11 void getCommands( int [][ 2 ] ); // function prototype12 void movePen( int, int [][ SIZE ], int, int ); // function prototype13 void printArray( const int [][ SIZE ] ); // function prototype1415 int main()16 {17 int floor[ SIZE ][ SIZE ] = {};18 int command;19 int direction = 0;20 int commandArray[ MAXCOMMANDS ][ 2 ] = {};21 int distance;22 int count = 0;23 bool penDown = false;2425 getCommands( commandArray );26 command = commandArray[ count ][ 0 ];2728 // continue receiving input until 9 is entered29 while ( command != 9 )30 {31 // determine what command was entered and perform desired action32 switch ( command )33 {34 case 1:35 penDown = false;36 break; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 10 Chapter 7 Arrays and Vectors: Solutions37 case 2:38 penDown = true;39 break;40 case 3:41 direction = turnRight( direction );42 break;43 case 4:44 direction = turnLeft( direction );45 break;46 case 5:47 distance = commandArray[ count ][ 1 ];48 movePen( penDown, floor, direction, distance );49 break;50 case 6:51 cout << "nThe drawing is:nn";52 printArray( floor );53 break;54 } // end switch5556 command = commandArray[ ++count ][ 0 ];57 } // end while58 } // end main5960 // function that prompts user for and keeps track of commands61 void getCommands( int commands[][ 2 ] )62 {63 int tempCommand, i;6465 cout << "Enter command (9 to end input): ";66 cin >> tempCommand;6768 // receive commands until 9 or 100 commands are entered69 for ( i = 0; tempCommand != 9 && i < MAXCOMMANDS; i++ )70 {71 commands[ i ][ 0 ] = tempCommand;7273 // ignore comma after 5 is entered74 if ( tempCommand == 5 )75 {76 cin.ignore(); // skip comma77 cin >> commands[ i ][ 1 ];78 } // end if7980 cout << "Enter command (9 to end input): ";81 cin >> tempCommand;82 } // end for8384 commands[ i ][ 0 ] = 9; // last command85 } // end function getCommands8687 // function to turn turtle to the right88 int turnRight( int d )89 {90 return ++d > 3 ? 0 : d; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • Student Solution Exercises 1191 } // end function turnRight9293 // function to turn turtle to the left94 int turnLeft( int d )95 {96 return --d < 0 ? 3 : d;97 } // end function turnLeft9899 // function to move the pen100 void movePen( int down, int a[][ SIZE ], int dir, int dist )101 {102 static int xPos = 0;103 static int yPos = 0;104 int j; // looping variable105106 // determine which way to move pen107 switch ( dir )108 {109 case 0: // move to the right110 for ( j = 0; j < dist && yPos + j < SIZE; j++ )111 {112 if ( down )113 a[ xPos ][ yPos + j ] = 1;114 } // end for115116 yPos += j - 1;117 break;118 case 1: // move down119 for ( j = 0; j < dist && xPos + j < SIZE; j++ )120 {121 if ( down )122 a[ xPos + j ][ yPos ] = 1;123 } // end for124125 xPos += j - 1;126 break;127 case 2: // move to the left128 for ( j = 0; j < dist && yPos - j >= 0; j++ )129 {130 if ( down )131 a[ xPos ][ yPos - j ] = 1;132 } // end for133134 yPos -= j - 1;135 break;136 case 3: // move up137 for ( j = 0; j < dist && xPos - j >= 0; j++ )138 {139 if ( down )140 a[ xPos - j ][ yPos ] = 1;141 } // end for142143 xPos -= j - 1;144 break; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 12 Chapter 7 Arrays and Vectors: Solutions145 } // end switch146 } // end function movePen147148 // function to print array drawing149 void printArray( const int a[][ SIZE ] )150 {151 // display array152 for ( int i = 0; i < SIZE; i++ )153 {154 for ( int j = 0; j < SIZE; j++ )155 cout << ( a[ i ][ j ] ? * : );156157 cout << endl;158 } // end outer for159 } // end function printArrayEnter command (9 to end input): 2Enter command (9 to end input): 5, 12Enter command (9 to end input): 3Enter command (9 to end input): 5, 12Enter command (9 to end input): 3Enter command (9 to end input): 5, 12Enter command (9 to end input): 3Enter command (9 to end input): 5, 12Enter command (9 to end input): 1Enter command (9 to end input): 6Enter command (9 to end input): 9The drawing is:************* ** ** ** ** ** ** ** ** ** ************* 7.29 (The Sieve of Eratosthenes) A prime integer is any integer that is evenly divisible only by itself and 1. The Sieve of Eratosthenes is a method of finding prime numbers. It operates as follows: a) Create an array with all elements initialized to 1 (true). Array elements with prime sub- scripts will remain 1. All other array elements will eventually be set to zero. You’ll ignore elements 0 and 1 in this exercise. b) Starting with array subscript 2, every time an array element is found whose value is 1, loop through the remainder of the array and set to zero every element whose subscript is a multiple of the subscript for the element with value 1. For array subscript 2, all el- ements beyond 2 in the array that are multiples of 2 will be set to zero (subscripts 4, 6, 8, 10, etc.); for array subscript 3, all elements beyond 3 in the array that are multiples of 3 will be set to zero (subscripts 6, 9, 12, 15, etc.); and so on. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • Student Solution Exercises 13 When this process is complete, the array elements that are still set to one indicate that the subscript is a prime number. These subscripts can then be printed. Write a program that uses an array of 1000 elements to determine and print the prime numbers between 2 and 999. Ignore element 0 of the array. ANS: 1 // Exercise 7.29 Solution: Ex07_29.cpp 2 #include <iostream> 3 #include <iomanip> 4 using namespace std; 5 6 int main() 7 { 8 const int SIZE = 1000; 9 int array[ SIZE ];10 int count = 0;1112 // set all array elements to 113 for ( int k = 0; k < SIZE; k++ )14 array[ k ] = 1;1516 // test for multiples of current subscript17 for ( int i = 1; i < SIZE; i++ )18 {19 if ( array[ i ] == 1 && i != 1 )20 {21 for ( int j = i; j < SIZE; j++ )22 {23 if ( j % i == 0 && j != i )24 array[ j ] = 0;25 } // end for26 } // end if27 } // end for2829 // display prime numbers30 // range 2 - 19731 for ( int q = 2; q < SIZE; q++ )32 {33 if ( array[ q ] == 1 )34 {35 cout << setw( 3 ) << q << " is a prime number.n";36 count++;37 } // end if38 } // end for3940 cout << "A total of " << count << " prime numbers were found." << endl;41 } // end main © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 14 Chapter 7 Arrays and Vectors: Solutions 2 is a prime number. 3 is a prime number. 5 is a prime number. 7 is a prime number.11 is a prime number.13 is a prime number.17 is a prime number.19 is a prime number.23 is a prime number.29 is a prime number.31 is a prime number....929 is a prime number.937 is a prime number.941 is a prime number.947 is a prime number.953 is a prime number.967 is a prime number.971 is a prime number.977 is a prime number.983 is a prime number.991 is a prime number.997 is a prime number.A total of 168 prime numbers were found.7.30 (Bucket Sort) A bucket sort begins with a one-dimensional array of positive integers to besorted and a two-dimensional array of integers with rows subscripted from 0 to 9 and columns sub-scripted from 0 to n – 1, where n is the number of values in the array to be sorted. Each row of thetwo-dimensional array is referred to as a bucket. Write a function bucketSort that takes an integerarray and the array size as arguments and performs as follows: a) Place each value of the one-dimensional array into a row of the bucket array based on the value’s ones digit. For example, 97 is placed in row 7, 3 is placed in row 3 and 100 is placed in row 0. This is called a “distribution pass.” b) Loop through the bucket array row by row, and copy the values back to the original ar- ray. This is called a “gathering pass.” The new order of the preceding values in the one- dimensional array is 100, 3 and 97. c) Repeat this process for each subsequent digit position (tens, hundreds, thousands, etc.).On the second pass, 100 is placed in row 0, 3 is placed in row 0 (because 3 has no tens digit) and97 is placed in row 9. After the gathering pass, the order of the values in the one-dimensional arrayis 100, 3 and 97. On the third pass, 100 is placed in row 1, 3 is placed in row zero and 97 is placedin row zero (after the 3). After the last gathering pass, the original array is now in sorted order. Note that the two-dimensional array of buckets is 10 times the size of the integer array beingsorted. This sorting technique provides better performance than a insertion sort, but requiresmuch more memory. The insertion sort requires space for only one additional element of data.This is an example of the space–time trade-off: The bucket sort uses more memory than the inser-tion sort, but performs better. This version of the bucket sort requires copying all the data back tothe original array on each pass. Another possibility is to create a second two-dimensional bucketarray and repeatedly swap the data between the two bucket arrays. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • Student Solution Exercises 15 ANS: 1 // Exercise 7.30 Solution: Ex07_30.cpp 2 #include <iostream> 3 #include <iomanip> 4 using namespace std; 5 6 // constant size must be defined as the array size for bucketSort to work 7 const int SIZE = 12; 8 9 void bucketSort( int [] );10 void distributeElements( int [], int [][ SIZE ], int );11 void collectElements( int [], int [][ SIZE ] );12 int numberOfDigits( int [], int );13 void zeroBucket( int [][ SIZE ] );1415 int main()16 {17 int array[ SIZE ] = { 19, 13, 5, 27, 1, 26, 31, 16, 2, 9, 11, 21 };1819 // display the unsorted array20 cout << "Array elements in original order:n";2122 for ( int i = 0; i < SIZE; i++ )23 cout << setw( 3 ) << array[ i ];2425 cout << n;26 bucketSort( array ); // sort the array2728 cout << "nArray elements in sorted order:n";2930 // display sorted array31 for ( int j = 0; j < SIZE; j++ )32 cout << setw( 3 ) << array[ j ];3334 cout << endl;35 } // end main3637 // Perform the bucket sort algorithm38 void bucketSort( int a[] )39 {40 int totalDigits;41 int bucket[ 10 ][ SIZE ] = {};4243 totalDigits = numberOfDigits( a, SIZE );4445 // put elements in buckets for sorting46 // once sorted, get elements from buckets47 for ( int i = 1; i <= totalDigits; i++ )48 {49 distributeElements( a, bucket, i );50 collectElements( a, bucket );5152 if ( i != totalDigits ) © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 16 Chapter 7 Arrays and Vectors: Solutions53 zeroBucket( bucket ); // set all bucket contents to zero54 } // end for55 } // end function bucketSort5657 // Determine the number of digits in the largest number58 int numberOfDigits( int b[], int arraySize )59 {60 int largest = b[ 0 ];61 int digits = 0;6263 // find largest array element64 for ( int i = 1; i < arraySize; i++ )65 {66 if ( b[ i ] > largest )67 largest = b[ i ];68 } // end for6970 // find number of digits of largest element71 while ( largest != 0 )72 {73 digits++;74 largest /= 10;75 } // end while7677 return digits;78 } // end function numberOfDigits7980 // Distribute elements into buckets based on specified digit81 void distributeElements( int a[], int buckets[][ SIZE ], int digit )82 {83 int divisor = 10;84 int bucketNumber;85 int elementNumber;8687 for ( int i = 1; i < digit; ++i ) // determine the divisor88 divisor *= 10; // used to get specific digit8990 for ( int k = 0; k < SIZE; ++k )91 {92 // bucketNumber example for hundreds digit:93 // (1234 % 1000 - 1234 % 100) / 100 --> 294 bucketNumber = ( a[ k ] % divisor - a[ k ] %95 ( divisor / 10 ) ) / ( divisor / 10 );9697 // retrieve value in buckets[bucketNumber][0] to determine98 // which element of the row to store a[i] in.99 elementNumber = ++buckets[ bucketNumber ][ 0 ];100 buckets[ bucketNumber ][ elementNumber ] = a[ k ];101 } // end for102 } // end function distributeElements103104 // Return elements to original array105 void collectElements( int a[], int buckets[][ SIZE ])106 { © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • Recursion Exercises 17107 int subscript = 0;108109 // retrieve elements from buckets110 for ( int i = 0; i < 10; i++ )111 {112 for ( int j = 1; j <= buckets[ i ][ 0 ]; j++ )113 a[ subscript++ ] = buckets[ i ][ j ];114 } // end for115 } // end function collectElements116117 // Set all buckets to zero118 void zeroBucket( int buckets[][ SIZE ] )119 {120 // set all array elements to zero121 for ( int i = 0; i < 10; i++ )122 {123 for ( int j = 0; j < SIZE; j++ )124 buckets[ i ][ j ] = 0;125 } // end for126 } // end function zeroBucketArray elements in original order: 19 13 5 27 1 26 31 16 2 9 11 21Array elements in sorted order: 1 2 5 9 11 13 16 19 21 26 27 31 Recursion Exercises 7.33 (Linear Search) Modify the program in Fig. 7.19 to use recursive function linearSearch to perform a linear search of the array. The function should receive an integer array and the size of the array as arguments. If the search key is found, return the array subscript; otherwise, return –1. ANS: 1 // Exercise 7.33 Solution: Ex07_33.cpp 2 #include <iostream> 3 using namespace std; 4 5 int linearSearch( const int [], int, int, int ); 6 7 int main() 8 { 9 const int SIZE = 100;10 int array[ SIZE ];11 int searchKey;12 int element;1314 // initialize array elements15 for ( int loop = 0; loop < SIZE; loop++ )16 array[ loop ] = 2 * loop;1718 // obtain search key from user © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • 18 Chapter 7 Arrays and Vectors: Solutions19 cout << "Enter the integer search key: ";20 cin >> searchKey;2122 // search array for search key23 element = linearSearch( array, searchKey, 0, SIZE - 1 );2425 // display if search key was found26 if ( element != -1 )27 cout << "Found value in element " << element << endl;28 else29 cout << "Value not found" << endl;30 } // end main3132 // function to search array for specified key33 int linearSearch( const int array[], int key, int low, int high )34 {35 // search array for key36 if ( array[low] == key )37 return low;38 else if ( low == high )39 return -1;40 else41 return linearSearch( array, key, low + 1, high );42 } // end function linearSearchEnter the integer search key: 18Found value in element 9Enter the integer search key: 17Value not found 7.37 (Find the Minimum Value in an Array) Write a recursive function recursiveMinimum that takes an integer array, a starting subscript and an ending subscript as arguments, and returns the smallest element of the array. The function should stop processing and return when the starting sub- script equals the ending subscript. ANS: 1 // Exercise 7.37 Solution: Ex07_37.cpp 2 #include <iostream> 3 #include <iomanip> 4 #include <cstdlib> 5 #include <ctime> 6 using namespace std; 7 8 const int MAXRANGE = 1000; 9 int recursiveMinimum( const int [], int, int );1011 int main()12 {13 const int SIZE = 10; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  • Recursion Exercises 1914 int array[ SIZE ];15 int smallest;1617 srand( time( 0 ) );1819 // initialize elements of array to random numbers20 for ( int loop = 0; loop < SIZE; loop++ )21 array[ loop ] = 1 + rand() % MAXRANGE;2223 // display array24 cout << "Array members are:n";2526 for ( int k = 0; k < SIZE; k++ )27 cout << setw( 5 ) << array[ k ];2829 // find and display smallest array element30 cout << n;31 smallest = recursiveMinimum( array, 0, SIZE - 1 );32 cout << "nSmallest element is: " << smallest << endl;33 } // end main3435 // function to recursively find minimum array element36 int recursiveMinimum( const int array[], int low, int high )37 {38 static int smallest = MAXRANGE;3940 // if first element of array is smallest so far41 // set smallest equal to that element42 if ( array[ low ] < smallest )43 smallest = array[ low ];4445 // if only one element in array, return smallest46 // else recursively call recursiveMinimum with new subarray47 return low == high ?48 smallest : recursiveMinimum( array, low + 1, high );49 } // end function recursiveMinimumArray members are: 309 893 72 270 109 830 338 487 240 505Smallest element is: 72 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.