510 likes | 526 Views
Starting Out with C++: From Control Structures through Objects 7 th edition By Tony Gaddis Source Code Chapter 8. Program 8-1. 1 // This program demonstrates the searchList function , which // performs a linear search on an integer array. 3 #include <iostream> 4 using namespace std; 5
E N D
Starting Out with C++:From Control Structures through Objects 7th edition By Tony Gaddis Source Code Chapter 8
Program 8-1 • 1 // This program demonstrates the searchList function, which • // performs a linear search on an integer array. • 3 #include <iostream> • 4 using namespace std; • 5 • 6 • 7 int searchList(const int [ ], int, int); • 8 const int SIZE = 5; • 9 • 10 int main() • 11 { • 12 inttests[SIZE] = {87, 75, 98, 100, 82}; • 13 int results; • 14 • (continued…)
16 results= searchList(tests, SIZE, 100); • 17 • 19 if (results == -1) • 20 cout << "You did not earn 100 points on any test\n"; • 21 else • 22 { • 25 cout << "You earned 100 points on test "; • 26 cout << (results + 1) << endl; • 27 } • return 0; • 29 } // end main() • (continued…)
30 • 31 //***************************************************************************** • 32 // The searchList function performs a linear search on an • 33 // integer array. The array list, which has a maximum of numElems • 34 // elements, is searched for the number stored in value. If the • 35 // number is found, its array subscript is returned. Otherwise, • 36 // -1 is returned indicating the value was not in the array. • 37 //****************************************************************************** • 38
int searchList(const int list [ ], int numElems, int value) • { • int index = 0; • 42 int position = -1; • 43 bool found = false; • 44 • 45 while(index < numElems &&!found) • 46 { • 47 if (list[index] == value) //Found it! • 48 { • 49 found = true; • 50 position = index; // Here! • 51 } • 52 index++; • 53 } • 54 return position; // Return the position, or -1 • 55 } // end searchList()
Program 8-2 • 1 // This program demonstrates the binarySearch function, which • // performs a binary search on an integer array. • 3 #include <iostream> • 4 using namespace std; • 5 • 6 • 7 int binarySearch( const int [ ], int, int ); • 8 const int SIZE = 20; • 9 • 10 int main() • 11 { • //Array with employee IDs sorted in ascending order. • 13 int idNums[SIZE] = {101, 142, 147, 189, 199, 207, 222, • 234, 289, 296, 310, 319, 388, 394, • 15 417, 429, 437, 521, 536, 600}; • (continued…)
16 int results; // To hold the search results • 17 int empID; // To hold an employee ID • 18 • 19 • 20 cout << "Enter the employee ID you wish to search for: "; • 21 cin >> empID; • 22 • 23 • 24 results = binarySearch( idNums, SIZE, empID ); • 25 • 26 // If results contains -1 the ID was not found. • 27 if (results == -1) • 28 cout << "That number does not exist in the array.\n"; • (continued…)
29 else • 30 { • 31 // Otherwise results contains the subscript of • 32 // the specified employee ID in the array. • 33 cout << "That ID is found at element " << results; • 34 cout << " in the array.\n"; • 35 } • 36 return 0; • 37 } • 38 • 39 //******************************************************************************* • 40 // The binarySearch function performs a binary search on an • 41 // integer array. array, which has a maximum of size elements, • 42 // is searched for the number stored in value. If the number is • (continued…)
43 // found, its array subscript is returned. Otherwise, -1 is • 44 // returned indicating the value was not in the array. • 45 //******************************************************************************** • 46 • 47 int binarySearch( const int array[ ], int size, int value ) • 48 { • 49 int first = 0, // First array element • 50 last = size - 1, // Last array element • 51 middle, // Mid point of search • 52 position = -1; // Position of search value • 53 bool found = false; // Flag • 54 • (continued…)
55 while( !found&&first<= last) • 56 { • 57 middle = (first + last) / 2; // Calculate mid point • 58 if (array[middle] == value) // Found it! • 59 { • 60 found = true; • 61 position = middle; • 62 } • 63 else if (array[middle] > value) // value is in lower half • 64 last = middle - 1; • 65 else • 66 first = middle + 1; // value is in upper half • 67 } • 68 returnposition; • 69 }
Program 8-3 • 1 // Demetris Leadership Center (DLC) product lookup program • 2 // This program allows the user to enter a product number • 3 // and then displays the title, description, and price of • // that product. • 5 #include <iostream> • 6 #include <string> • 7 using namespace std; • 8 • 9 const int NUM_PRODS = 9; // The number of products produced • 10 const int MIN_PRODNUM = 914; // The lowest product number • 11 const int MAX_PRODNUM = 922; // The highest product number • 12 • 13 • 14 int getProdNum(); • (continued…)
15 int binarySearch (const int [ ], int, int); • 16 void displayProd(const string [ ], const string [ ], const double [ ], int); • 17 • 18 int main() • 19 { • 20 • 21 int id[NUM_PRODS] = {914, 915, 916, 917, 918, 919, 920, • 22 921, 922}; • 23 • 24 • 25 string title[NUM_PRODS] = { "Six Steps to Leadership", • 27 "Six Steps to Leadership", • 28 "The Road to Excellence", • (continued…)
29 "Seven Lessons of Quality", • 30 "Seven Lessons of Quality", • 31 "Seven Lessons of Quality", • 32 "Teams Are Made, Not Born", • 33 "Leadership for the Future", • 34 "Leadership for the Future" • 35 }; • 36 • 37 // • 38 string description[NUM_PRODS] = { "Book", "Audio CD", "DVD", • 40 "Book", "Audio CD", "DVD", • 41 "Book", "Book", "Audio CD" • 42 }; • (continued…)
43 • 44 // Array of product prices • 45 double prices[NUM_PRODS] = {12.95, 14.95, 18.95, 16.95, 21.95, • 46 31.95, 14.95, 14.95, 16.95}; • 47 • 48 int prodNum; // To hold a product number • 49 int index; // To hold search results • 50 char again; // To hold a Y or N • 51 • (continued…)
52 do • 53 { • 54 prodNum = getProdNum(); • 55 • 58 index = binarySearch(id, NUM_PRODS, prodNum); • 59 • 61 if (index == -1) • 62 cout << "That product number was not found.\n"; • 63 else • 64 displayProd(title, description, prices, index); • 65 • 67 cout << "Would you like to look up another product? (y/n) "; • cin >> again; • } while ( again == 'y' || again == 'Y’ ); • return 0; • 71 } // end-main() • (continued…)
72 • 73 //*************************************************************** • // Definition of getProdNum function • 75 // The getProdNum function asks the user to enter a • 76 // product number. The input is validated, and when • 77 // a valid number is entered, it is returned. • 78 //**************************************************************** • 79 • 80 int getProdNum() • 81 { • 82 int prodNum; // Product number • 83 • 84 cout << "Enter the item's product number: "; • (continued…)
85 cin >> prodNum; // Loop to Validate input. • 86 • 87 while(prodNum < MIN_PRODNUM ||prodNum > MAX_PRODNUM) • 88 { • 89 cout << "Enter a number in the range of " << MIN_PRODNUM; • 90 cout <<" through " << MAX_PRODNUM << ".\n"; • 91 cin >> prodNum; • 92 } • 93 return prodNum; • 94 } • 95 • 96 //*********************************************************************** • 97 // Definition of binarySearch function • 98 // The binarySearch function performs a binary search on an • (continued…)
99 // integer array. array, which has a maximum of numElems • 100 // elements, is searched for the number stored in value. If the • 101 // number is found, its array subscript is returned. Otherwise, • 102 // -1 is returned indicating the value was not in the array. • 103 //*********************************************************************** • 104 • 105 int binarySearch( const int array[ ], int numElems, int value ) • 106 { • 107 int first = 0, // First array element • 108 last = numElems - 1, // Last array element • 109 middle, // Midpoint of search • 110 position = -1; // Position of search value • 111 bool found = false; // Flag • 112 • (continued…)
113 while ( !found&&first <= last ) • 114 { • 115 middle = (first + last) / 2; // Calculate midpoint • 116 if (array[middle]==value) // value is found • 117 { • 118 found = true; • 119 position = middle; • 120 } • 121 else if (array[middle]>value) // value is in lower half • 122 last = middle - 1; • 123 else • 124 first = middle + 1; // value is in upper half • 125 } • 126 return position;
Program 8-4 • 1 // This program uses the bubble sort algorithm to sort an • // array in ascending order. • 3 #include <iostream> • 4 using namespace std; • 5 • 6 • 7 void sortArray(int [], int); • 8 void showArray(const int [], int); • 9 • 10 int main() • 11 { • 12 // Array of unsorted values • 13 int values[6] = {7, 2, 3, 8, 9, 1}; • 14 • (continued…)
15 • 16 cout << "The unsorted values are:\n"; • 17 showArray(values, 6); • 18 • 19 // Sort the values. • 20 sortArray(values, 6); • 21 • cout << "The sorted values are:\n"; • 24 showArray(values, 6); • 25 return 0; • 26 } • 27 • 28 //*********************************************************** • (continued…)
29 // Definition of function sortArray • 30 // This function performs an ascending order bubble sort on • 31 // array. size is the number of elements in the array. • 32 //************************************************************************ • 33 • 34 void sortArray(int array[ ], int size) • 35 { • 36 bool swap; • int temp; • 38 • (continued…)
39 do • 40 { • 41 swap = false; • 42 for( int count = 0; count < (size – 1); count++) • 43 { • 44 if (array[count] > array[count + 1]) // IF true- swap element values! • 45 { • 46 temp = array[count]; • 47 array[count] = array[count + 1]; • 48 array[count + 1] = temp; • 49 swap = true; • 50 } • 51 } • 52 }while (swap); // IFfalse- sort is finished! • 53 } • 54 • 55 //************************************************************* • 56 // Definition of function showArray. • (continued…)
57 // This function displays the contents of array. size is the • 58 // number of elements. • 59 //********************************************************************* • 60 • 61 void showArray(const int array[ ], int size) • 62 { • 63 for (int count = 0; count < size; count++) • 64 cout << array[count] << " "; • 65 cout << endl; • 66 }
Program 8-5 • 1 // This program uses the selection sort algorithm to sort an • // array in ascending order. • 3 #include <iostream> • 4 using namespace std; • 5 • 6 // Function prototypes • 7 void selectionSort(int [], int); • 8 void showArray(int [], int); • 9 • 10 int main() • 11 { • 12 • 13 const int SIZE = 6; • 14 int values[SIZE] = {5, 7, 2, 8, 9, 1}; • (continued…)
15 • 16 • 17 cout << "The unsorted values are\n"; • 18 showArray(values, SIZE); • 19 • 20 // Sort the values. • 21 selectionSort(values, SIZE); • 22 • 23 // Display the values again. • 24 cout << "The sorted values are\n"; • 25 showArray(values, SIZE); • 26 return 0; • 27 } • 28 • (continued…)
29 //***********************************************************************29 //*********************************************************************** • 30 // Definition of function selectionSort. • 31 // This function performs an ascending order selection sort on • 32 // array. size is the number of elements in the array. • 33 //*********************************************************************** • 34 • 35 void selectionSort(int array[], int size) • 36 { • 37 int startScan, minIndex, minValue; • 38 • (continued…)
39 for( startScan = 0; startScan < (size -1); startScan++) • 40 { • 41 minIndex = startScan; • 42 minvalue = array[startScan]; • 43 for(int index = startScan + 1; index < size; index++) • 44 { • 45 if (array[index] < minValue) // IF TRUE-Found NEW LOW! • 46 { • 47 minValue = array[index]; • 48 minIndex = index; • 49 } • 50 } • 51 array[minIndex] = array[startScan]; // Exchange the two values! • 52 array[startScan] = minValue; • 53 } • 54 } // end function • 55 • 56 //************************************************************** • (continued…)
57 // Definition of function showArray. • 58 // This function displays the contents of array. size is the • 59 // number of elements. • 60 //****************************************************************** • 61 • 62 void showArray(int array[], int size) • 63 { • 64 for (int count = 0; count < size; count++) • 65 cout << array[count] << " "; • 66 cout << endl; • 67 }
Program 8-6 • 1 // This program produces a sales report for DLC, Inc. • 2 #include <iostream> • 3 #include <iomanip> • 4 using namespace std; • 5 • // Function prototypes • 7 void calcSales(const int [ ], const double [ ], double [ ], int); • 8 voidshowOrder(const double [ ], const int [ ], int); • 9 void dualSort(int [ ], double [ ], int); • 10 void showTotals(const double [ ], const int [ ], int); • 11 • 12 // NUM_PRODS is the number of products produced. • 13 const int NUM_PRODS = 9; • 14 • (continued…)
15 int main() • 16 { • 18 int id[NUM_PRODS] = {914, 915, 916 , 917, 918, 919, 920, • 19 921, 922}; • 20 • 21 // Number of units sold for each product • 22 int units[NUM_PRODS] = {842, 416, 127, 514, 437, 269, 97, • 23 492, 212}; • 24 • 25 // Product prices • 26 double prices[NUM_PRODS] = {12.95, 14.95, 18.95, 16.95, 21.95, • 27 31.95, 14.95, 14.95, 16.95}; • 28 • (continued…)
29 // Holds the computed sales amounts • 30 double sales[NUM_PRODS]; • 31 • 32 • 33 calcSales( units, prices, sales, NUM_PRODS ); • 34 • 35 // Sort the elements in the sales array in descending • 36 // order and shuffle the ID numbers in the id array to • // keep them in parallel. • 38 dualSort( id, sales, NUM_PRODS ); • 39 • 40 // Set the numeric output formatting. • 41 cout << setprecision(2) << fixed << showpoint; • 42 • (continued…)
43 // Display the products and sales amounts. • 44 showOrder( sales, id, NUM_PRODS ); • 45 • 46 // Display total units sold and total sales. • 47 showTotals( sales, units, NUM_PRODS ); • 48 return 0; • 49 } • 50 • 51 //*********************************************************************************** • // Definition of calcSales. Accepts units, prices, and sales • 53 // arrays as arguments. The size of these arrays is passed • 54 // into the num parameter. This function calculates each • // product's sales by multiplying its units sold by each unit's • // price. The result is stored in the sales array. • //**************************************************************************** • (continued…)
57 //****************************************************************************************57 //**************************************************************************************** • 58 • 59 void calcSales(const int units[ ], const double prices[ ], double sales[ ], intnum) • 60 { • 61 for (int index = 0; index < num; index++) • 62 sales[index] = units[index] * prices[index]; • 63 } • 64 • 65 //**************************************************************************** • 66 // Definition of function dualSort. Accepts id and sales arrays • 67 // as arguments. The size of these arrays is passed into size. • 68 // This function performs a descending order selection sort on • 69 // the sales array. The elements of the id array are exchanged • 70 // identically as those of the sales array. size is the number • (continued…)
71 // of elements in each array. • 72 //*************************************************************** • 73 • 74 void dualSort(int id[ ], double sales[ ], int size) • 75 { • 76 int startScan, maxIndex, tempid; • 77 double maxValue; • 78 • 79 for (startScan = 0; startScan < (size - 1); startScan++) • 80 { • 81 maxIndex = startScan; • 82 maxValue = sales[startScan]; • 83 tempid = id[startScan]; • (continued…)
84 for(int index = startscan+1; index < size: index++) • 85 { • 86 if (sales[index] > maxValue) // IF true-found new High! • 87 { • 88 maxValue = sales[index]; • 89 tempid = id[index]; • 90 maxIndex = index; • 91 } • 92 } // end inner-for • 93 sales[maxIndex] = sales[startScan]; // Exchange in both Arrays! • 94 id[maxIndex] = id[startScan]; • 95 sales[startScan] = maxValue; • 96 id[startScan] = tempid; • 97 } // end outer-for • 98 } // end-dualSort() • (continued…)
99 • 100 //***************************************************************************** • 101 // Definition of showOrder function. Accepts sales and id arrays • 102 // as arguments. The size of these arrays is passed into num. • 103 // The function first displays a heading, then the sorted list • 104 // of product numbers and sales. • 105 //****************************************************************************** • 106 • 107 void showOrder(const double sales[ ], const int id[ ], int num) • 108 { • 109 cout << "Product Number\tSales\n"; • 110 cout << "----------------------------------\n"; • (continued…)
111 for (index = 0; index < num; index++) • 112 { • 113 cout << id[index] << "\t\t$"; • 114 cout << setw(8) << sales[index] << endl; • 115 } • 116 cout << endl; • 117 } • 118 • 119 //********************************************************************************* • 120 // Definition of showTotals function. Accepts sales and id arrays • 121 // as arguments. The size of these arrays is passed into num. • 122 // The function first calculates the total units (of all • 123 // products) sold and the total sales. It then displays these • 124 // amounts. • 125 //********************************************************************************* • 126 • (continued…)
127 void showTotals(const double sales[], const int units[], int num) • 128 { • 129 int totalUnits = 0; • 130 double totalSales = 0.0; • 131 • 132 for (int index = 0; index < num; index++) • 133 { • 134 totalUnits += units[index]; • 135 totalSales += sales[index]; • 136 } • 137 cout << "Total units Sold: " << totalUnits << endl; • 138 cout << "Total sales: $" << totalSales << endl; • 139 }
Program 8-7 • 1 // This program produces a sales report for DLC, Inc. • 2 // This version of the program uses STL vectors instead of arrays. • 3 #include <iostream> • 4 #include <iomanip> • 5 #include <vector> • 6 using namespace std; • 7 • // Function prototypes • 9 void initVectors(vector<int> &, vector<int> &, vector<double> &); • 10 void calcSales(vector<int>, vector<double>, vector<double> &); • 11 void showOrder(vector<double>, vector<int>); • 12 void dualSort(vector<int> &, vector<double> &); • 13 void showTotals(vector<double>, vector<int>); • 14 • (continued…)
Program 8-7 (cont.) • 15 int main() • 16 { • 17 vector<int> id; // Product ID numbers • 18 vector<int> units; // Units sold • 19 vector<double> prices; // Product prices • 20 vector<double> sales; // To hold product sales • 21 • 22 • 23 initVectors( id, units, prices ); • 24 • 25 // Calculate each product's sales. • 26 calcSales( units, prices, sales ); • 27 • 28 // Sort the elements in the sales array in descending • (continued…)
29 // order and shuffle the ID numbers in the id array to • 30 // keep them in parallel. • 31 dualSort( id, sales ); • 32 • 33 // Set the numeric output formatting. • 34 cout << fixed << showpoint << setprecision(2); • 35 • 36 // Display the products and sales amounts. • 37 showOrder( sales, id ); • 38 • 39 // Display total units sold and total sales. • 40 showTotals( sales, units ); • 41 return 0; • 42 } • (continued…)
43 • 44 //************************************************************************************************ • 45 // Definition of initVectors. Accepts id, units, and prices • 46 // vectors as reference arguments. This function initializes each • // vector to a set of starting values. Vectors must be passed-by-ref to modify them. • // The [ ] operator can’t be used to store a NEW value in a vector(only in an • // existing element. • 49 //************************************************************************************************ • 49 • 50 void initVectors(vector<int> &id, vector<int> &units, • 51 vector<double> &prices) • 52 { • 53 // Initialize the id vector with the ID numbers • 54 • 55 for (int value = 914; value <= 922; value++) • 56 id.push_back(value); • (continued…)
57 • 58 // Initialize the units vector with data. • 59 units.push_back(842); • 60 units.push_back(416); • 61 units.push_back(127); • 62 units.push_back(514); • 63 units.push_back(437); • 64 units.push_back(269); • 65 units.push_back(97); • 66 units.push_back(492); • 67 units.push_back(212); • 68 • 69 // Initialize the prices vector. • 70 prices.push_back(12.95); • (continued…)
71 prices.push_back(14.95); • 72 prices.push_back(18.95); • 73 prices.push_back(16.95); • 74 prices.push_back(21.95); • 75 prices.push_back(31.95); • 76 prices.push_back(14.95); • 77 prices.push_back(14.95); • 78 prices.push_back(16.95); • 79 } • 80 • 81 • 82 //********************************************************************* • 83 // Definition of calcSales. Accepts units, prices, and sales • 84 // vectors as arguments. The sales vector is passed into a • (continued…)
85 // reference parameter. This function calculates each product's • 86 // sales by multiplying its units sold by each unit's price. The • 87 // result is stored in the sales vector. • 88 //************************************************************************* • 89 • 90 void calcSales(vector<int> units, vector<double> prices, • 91 vector<double> &sales) • 92 { • 93 for (int index = 0; index < units.size(); index++) • 94 sales.push_back(units[index] *prices[index]); • 95 } • 96 • 97 //********************************************************************** • 98 // Definition of function dualSort. Accepts id and sales vectors • (continued…)
99 // as reference arguments. This function performs a descending • 100 // order selection sort on the sales vector. The elements of the • 101 // id vector are exchanged identically as those of the sales • 102 // vector. • 103 //***************************************************************************** • 104 • 105 void dualSort(vector<int> &id, vector<double> &sales) • 106 { • 107 int startScan, maxIndex, tempid, size; • 108 double maxValue; • 109 • 110 size =id.size(); • 111 for (startScan = 0; startScan < (size - 1); startScan++) • 112 { • (continued…)
113 maxIndex = startScan; • 114 maxValue = sales[startScan]; • 115 tempid = id[startScan]; • 116 for (int index = startScan + 1; index < size; index++) • 117 { • 118 if (sales[index] > maxValue) • 119 { • 120 maxValue = sales[index]; • 121 tempid = id[index]; • 122 maxIndex = index; • 123 } • 124 } • 125 sales[maxIndex] = sales[startScan]; • 126 id[maxIndex] = id[startScan]; • (continued…)
127 sales[startScan] = maxValue; • 128 id[startScan] = tempid; • 129 } • 130 } • 131 • 132 //***************************************************************** • 133 // Definition of showOrder function. Accepts sales and id vectors * • 134 // as arguments. The function first displays a heading, then the * • 135 // sorted list of product numbers and sales. * • 136 //***************************************************************** • 137 • 138 voidshowOrder(vector<double> sales, vector<int> id) • 139 { • 140 cout << "Product Number\tSales\n"; • (continued…)
141 cout << "----------------------------------\n"; • 142 for (int index = 0; index < id.size(); index++) • 143 { • 144 cout << id[index] << "\t\t$"; • 145 cout << setw(8) << sales[index] << endl; • 146 } • 147 cout << endl; • 148 } • 149 • 150 //***************************************************************************** • 151 // Definition of showTotals function. Accepts sales and id vectors • 152 // as arguments. The function first calculates the total units (of • 153 // all products) sold and the total sales. It then displays these • 154 // amounts. • (continued…)