├── Chapter02 ├── PE01.cpp ├── PE02.cpp ├── PE03.cpp ├── PE04.cpp ├── PE05.cpp ├── PE06.cpp └── PE07.cpp ├── Chapter03 ├── PE01.cpp ├── PE02.cpp ├── PE03.cpp ├── PE04.cpp ├── PE05.cpp ├── PE06.cpp └── PE07.cpp ├── Chapter04 ├── PE01.cpp ├── PE02.cpp ├── PE03.cpp ├── PE04.cpp ├── PE05.cpp ├── PE06.cpp ├── PE07.cpp ├── PE08.cpp ├── PE09.cpp └── PE10.cpp ├── Chapter05 ├── PE01.cpp ├── PE02.cpp ├── PE03.cpp ├── PE04.cpp ├── PE05.cpp ├── PE06.cpp ├── PE07.cpp ├── PE08.cpp ├── PE09.cpp └── PE10.cpp ├── Chapter06 ├── PE01.cpp ├── PE02.cpp ├── PE03.cpp ├── PE04.cpp ├── PE05.cpp ├── PE06.cpp ├── PE07.cpp ├── PE08.cpp ├── PE08.txt ├── PE09.cpp └── PE09.txt ├── Chapter07 ├── PE01.cpp ├── PE02.cpp ├── PE03.cpp ├── PE04.cpp ├── PE05.cpp ├── PE06.cpp ├── PE07.cpp ├── PE08.cpp ├── PE09.cpp ├── PE10.cpp └── README.md ├── Chapter08 ├── PE01.cpp ├── PE02.cpp ├── PE03.cpp ├── PE04.cpp ├── PE05.cpp ├── PE06.cpp ├── PE07.cpp └── README.md ├── Chapter09 ├── PE01 │ ├── Makefile │ ├── golf.cpp │ ├── golf.h │ └── main.cpp ├── PE02 │ ├── Makefile │ ├── main.cpp │ ├── strcount.cpp │ └── strcount.h ├── PE03 │ ├── Makefile │ ├── main.cpp │ ├── placementnew.cpp │ └── placementnew.h └── PE04 │ ├── Makefile │ ├── main.cpp │ ├── sales.cpp │ └── sales.h ├── Chapter10 ├── PE01 │ ├── Makefile │ ├── bank_account.cpp │ ├── bank_account.h │ └── main.cpp ├── PE02 │ ├── Makefile │ ├── main.cpp │ ├── person.cpp │ └── person.h ├── PE03 │ ├── Makefile │ ├── golf.cpp │ ├── golf.h │ └── main.cpp ├── PE04 │ ├── Makefile │ ├── main.cpp │ ├── sales.cpp │ └── sales.h ├── PE05 │ ├── Makefile │ ├── main.cpp │ ├── stack.cpp │ └── stack.h ├── PE06 │ ├── Makefile │ ├── main.cpp │ ├── move.cpp │ └── move.h ├── PE07 │ ├── Makefile │ ├── main.cpp │ ├── plorg.cpp │ └── plorg.h └── PE08 │ ├── Makefile │ ├── list.cpp │ ├── list.h │ └── main.cpp ├── Chapter11 ├── PE01 │ ├── Makefile │ ├── PE01.txt │ ├── main.cpp │ ├── vector.cpp │ └── vector.h ├── PE02 │ ├── Makefile │ ├── main.cpp │ ├── vector.cpp │ └── vector.h ├── PE03 │ ├── Makefile │ ├── main.cpp │ ├── vector.cpp │ └── vector.h ├── PE04 │ ├── Makefile │ ├── main.cpp │ ├── mytime.cpp │ └── mytime.h ├── PE05 │ ├── Makefile │ ├── main.cpp │ ├── stonewt.cpp │ └── stonewt.h ├── PE06 │ ├── Makefile │ ├── main.cpp │ ├── stonewt.cpp │ └── stonewt.h ├── PE07 │ ├── Makefile │ ├── complex0.cpp │ ├── complex0.h │ └── main.cpp └── README.md ├── Chapter12 ├── PE01 │ ├── Makefile │ ├── cow.cpp │ ├── cow.h │ └── main.cpp ├── PE02 │ ├── Makefile │ ├── main.cpp │ ├── string2.cpp │ └── string2.h ├── PE03 │ ├── Makefile │ ├── main.cpp │ ├── stock.cpp │ └── stock.h ├── PE04 │ ├── Makefile │ ├── main.cpp │ ├── stack.cpp │ └── stack.h ├── PE05 │ ├── Makefile │ ├── main.cpp │ ├── queue.cpp │ └── queue.h ├── PE06 │ ├── Makefile │ ├── main.cpp │ ├── queue.cpp │ └── queue.h └── README.md ├── Chapter13 ├── PE01 │ ├── Makefile │ ├── cd.cpp │ ├── cd.h │ ├── classic.cpp │ ├── classic.h │ └── main.cpp ├── PE02 │ ├── Makefile │ ├── cd.cpp │ ├── cd.h │ ├── classic.cpp │ ├── classic.h │ └── main.cpp ├── PE03 │ ├── Makefile │ ├── dma.cpp │ ├── dma.h │ └── main.cpp └── PE04 │ ├── Makefile │ ├── main.cpp │ ├── port.cpp │ ├── port.h │ ├── vintageport.cpp │ └── vintageport.h ├── Chapter14 ├── PE01 │ ├── Makefile │ ├── main.cpp │ ├── pairs.h │ ├── wine.cpp │ └── wine.h ├── PE02 │ ├── Makefile │ ├── main.cpp │ ├── pairs.h │ ├── wine.cpp │ └── wine.h ├── PE03 │ ├── Makefile │ ├── main.cpp │ ├── queuetp.h │ ├── worker.cpp │ └── worker.h ├── PE04 │ ├── Makefile │ ├── baddude.cpp │ ├── baddude.h │ ├── gunslinger.cpp │ ├── gunslinger.h │ ├── main.cpp │ ├── person.cpp │ ├── person.h │ ├── pokerplayer.cpp │ └── pokerplayer.h ├── PE05 │ ├── Makefile │ ├── emp.cpp │ ├── emp.h │ └── main.cpp └── README.md ├── Chapter15 ├── PE01 │ ├── Makefile │ ├── main.cpp │ ├── tv.cpp │ └── tv.h ├── PE02 │ ├── Makefile │ ├── exc_mean.h │ └── main.cpp └── README.md ├── Chapter16 ├── PE01 │ ├── Makefile │ ├── main.cpp │ └── palindrome.h ├── PE02 │ ├── Makefile │ ├── main.cpp │ └── palindrome.h ├── PE03 │ ├── Makefile │ ├── PE03.txt │ └── hangman.cpp └── PE04 │ ├── Makefile │ └── main.cpp ├── README.md └── _config.yml /Chapter02/PE01.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 2.1 2 | #include 3 | 4 | int main() { 5 | using std::cout; 6 | using std::endl; 7 | 8 | cout << "Baruch College" << endl; 9 | cout << "Address: 55 Lexington Ave, New York, NY 10010" << endl; 10 | 11 | return 0; 12 | } -------------------------------------------------------------------------------- /Chapter02/PE02.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 2.2 2 | #include 3 | 4 | int main() { 5 | using std::cin; 6 | using std::cout; 7 | 8 | double furlongs; 9 | cout << "Enter a distance in furlongs: "; 10 | cin >> furlongs; 11 | cout << "It's equivalent to " << furlongs * 220 << " yards.\n"; 12 | 13 | return 0; 14 | } -------------------------------------------------------------------------------- /Chapter02/PE03.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 2.3 2 | #include 3 | 4 | using std::cout; 5 | using std::endl; 6 | 7 | void printThree(); 8 | void printSee(); 9 | 10 | int main() { 11 | printThree(); 12 | printThree(); 13 | printSee(); 14 | printSee(); 15 | 16 | return 0; 17 | } 18 | 19 | void printThree() { 20 | cout << "Three blind mice" << endl; 21 | } 22 | 23 | void printSee() { 24 | cout << "See how they run" << endl; 25 | } -------------------------------------------------------------------------------- /Chapter02/PE04.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 2.4 2 | #include 3 | 4 | int main() { 5 | using std::cin; 6 | using std::cout; 7 | using std::endl; 8 | 9 | int age; 10 | cout << "Enter your age: "; 11 | cin >> age; 12 | cout << "Your age in months is " << age * 12 << endl; 13 | 14 | return 0; 15 | } -------------------------------------------------------------------------------- /Chapter02/PE05.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 2.5 2 | #include 3 | 4 | double celsiumToFahrenheit(double celsius); 5 | 6 | int main() { 7 | using std::cin; 8 | using std::cout; 9 | using std::endl; 10 | 11 | double celsius; 12 | cout << "Please enter a Celsius value: "; 13 | cin >> celsius; 14 | cout << celsius << " degrees Celsius is " 15 | << celsiumToFahrenheit(celsius) 16 | << " degrees Fahrenheit.\n"; 17 | 18 | return 0; 19 | } 20 | 21 | double celsiumToFahrenheit(double celsius) { 22 | return 1.8 * celsius + 32.0; 23 | } -------------------------------------------------------------------------------- /Chapter02/PE06.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 2.6 2 | #include 3 | 4 | int main() { 5 | using std::cin; 6 | using std::cout; 7 | 8 | double numLightYear; 9 | cout << "Enter the number of light years: "; 10 | cin >> numLightYear; 11 | cout << numLightYear << "light years = " 12 | << numLightYear * 63240 << " astronomical units.\n"; 13 | 14 | return 0; 15 | } -------------------------------------------------------------------------------- /Chapter02/PE07.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 2.7 2 | #include 3 | 4 | int main() { 5 | using std::cin; 6 | using std::cout; 7 | using std::endl; 8 | 9 | int hours, minutes; 10 | cout << "Enter the number of hours: "; 11 | cin >> hours; 12 | cout << "Enter the number of minutes: "; 13 | cin >> minutes; 14 | cout << "Time: " << hours << ":" << minutes << endl; 15 | 16 | return 0; 17 | } -------------------------------------------------------------------------------- /Chapter03/PE01.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 3.1 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | // It is better to capitalize the first letter of the const. 9 | const int ConversionFactor = 12; 10 | 11 | int main() { 12 | int heightInInches; 13 | 14 | cout << "What is your height in integer inches? ________\b\b\b\b\b\b\b\b"; 15 | cin >> heightInInches; 16 | cout << "You height can also be " << heightInInches / ConversionFactor; 17 | cout << " feet and " << heightInInches % ConversionFactor << " inches.\n"; 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /Chapter03/PE02.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 3.2 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | const int FootToInchesCF = 12; 9 | const double InchesToMetersCF = 0.0254; 10 | const double PoundsToKilogramsCF = 2.2; 11 | 12 | int main() { 13 | double height, weight; 14 | int heightInFeet, heightInInches; 15 | int weightInPounds; 16 | 17 | 18 | cout << "What is your height in feet and inches " 19 | << "(separate by a space)? ________\b\b\b\b\b\b\b\b"; 20 | cin >> heightInFeet >> heightInInches; 21 | cout << "What is your weight in pounds? ________\b\b\b\b\b\b\b\b"; 22 | cin >> weightInPounds; 23 | 24 | height = (heightInFeet * FootToInchesCF + heightInInches) * InchesToMetersCF; 25 | weight = weightInPounds / PoundsToKilogramsCF; 26 | 27 | cout << "Your BMI is " << weight / height / height << ".\n"; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Chapter03/PE03.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 3.3 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | const double ConversionFactor = 60.0; 9 | 10 | int main() { 11 | double degrees, minutes, seconds; 12 | 13 | cout << "Enter a latitude in degrees, minutes, and seconds:\n"; 14 | cout << "First, enter the degrees: "; 15 | cin >> degrees; 16 | cout << "Next, enter the minutes of arc: "; 17 | cin >> minutes; 18 | cout << "Finally, enter the seconds of arc: "; 19 | cin >> seconds; 20 | cout << degrees << " degress, " << minutes << " minutes, " << seconds << " seconds = "; 21 | cout << degrees + minutes / ConversionFactor + 22 | seconds / ConversionFactor / ConversionFactor << " degress\n"; 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Chapter03/PE04.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 3.4 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | const double HoursMinutesSecondsCF = 60.0; 9 | const double HoursToDays = 24.0; 10 | 11 | int main() { 12 | long long secondsInput; 13 | int days, hours, minutes, secondsOutput; 14 | 15 | cout << "Enter the number of seconds: "; 16 | cin >> secondsInput; 17 | 18 | days = int(secondsInput / HoursMinutesSecondsCF / 19 | HoursMinutesSecondsCF / HoursToDays); 20 | hours = int(secondsInput / HoursMinutesSecondsCF / HoursMinutesSecondsCF - 21 | days * HoursToDays); 22 | minutes = int(secondsInput / HoursMinutesSecondsCF - 23 | days * HoursMinutesSecondsCF * HoursToDays - 24 | hours * HoursMinutesSecondsCF); 25 | secondsOutput = secondsInput % int(HoursMinutesSecondsCF); 26 | 27 | cout << secondsInput << " seconds = " << days << " days, " 28 | << hours << " hours, " << minutes << " minutes, " 29 | << secondsOutput << " seconds\n"; 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /Chapter03/PE05.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 3.5 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | int main() { 9 | long long worldPopulation; 10 | long long USPopulation; 11 | 12 | cout << "Enter the world's population: "; 13 | cin >> worldPopulation; 14 | cout << "Enter the population of the US: "; 15 | cin >> USPopulation; 16 | cout << "The population of the US is "; 17 | cout << USPopulation / (long double)(worldPopulation) * 100 18 | << "% of the world population.\n"; 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Chapter03/PE06.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 3.6 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | int main() { 9 | double miles, gallons; 10 | cout << "How many miles have you driven? "; 11 | cin >> miles; 12 | cout << "How many gallons of gasoline have you used? "; 13 | cin >> gallons; 14 | cout << "Your car has gotten " << gallons / miles 15 | << " gallons/miles." << endl; 16 | 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /Chapter03/PE07.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 3.7 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | const double kmToMiles = 62.14; 9 | const double gallonToLiters = 3.875; 10 | 11 | 12 | int main() { 13 | double european, us; 14 | 15 | cout << "How many liters per 100 kilometers? "; 16 | cin >> european; 17 | us = 1 / (european / gallonToLiters / kmToMiles); 18 | cout << "It is equivalent to " << int(us) << " mpg.\n"; 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Chapter04/PE01.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 4.1 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | const int ArrSize = 20; 9 | 10 | int main() { 11 | char firstName[ArrSize], lastName[ArrSize], letter; 12 | int age; 13 | 14 | // Because a number was enteredin the main function, when cin reads the 15 | // number, it leaves the newline generated by the Enter key in the input 16 | // queue. Then, cin.getline() reads the newline as an empty line and assigns 17 | // a null string to the first name. cin.get() function solves this problem. 18 | // cin.get(); It was added in the main, which can solve the issue in each 19 | // function. 20 | cout << "What is your first name? "; 21 | cin.getline(firstName, ArrSize); 22 | cout << "What is your last name? "; 23 | cin.getline(lastName, ArrSize); 24 | cout << "What letter grade do you deserve? (A or B or C) "; 25 | cin >> letter; 26 | cout << "What is your age? "; 27 | (cin >> age).get(); 28 | 29 | cout << "Name: " << lastName << ", " << firstName << endl; 30 | cout << "Grade: " << char(letter + 1) << endl; 31 | cout << "Age: " << age << endl; 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Chapter04/PE02.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 4.2 2 | #include 3 | #include 4 | 5 | using std::string; 6 | 7 | using std::cin; 8 | using std::cout; 9 | using std::endl; 10 | using std::getline; 11 | 12 | int main() { 13 | string name, dessert; 14 | 15 | cout << "Enter your name:\n"; 16 | getline(cin, name); // getline is a great function to remember for string. 17 | cout << "Enter your favorite dessert:\n"; 18 | getline(cin, dessert); 19 | cout << "I have some delicious " << dessert; 20 | cout << " for you, " << name << ".\n"; 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /Chapter04/PE03.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 4.3 2 | #include 3 | #include 4 | 5 | using std::cin; 6 | using std::cout; 7 | using std::endl; 8 | 9 | int main() { 10 | const int ArrSize = 20; 11 | char firstName[ArrSize], lastName[ArrSize]; 12 | 13 | cout << "Enter your first name: "; 14 | cin.getline(firstName, ArrSize); 15 | cout << "Enter your last name: "; 16 | cin.getline(lastName, ArrSize); 17 | 18 | char fullname[ArrSize + ArrSize] = {'\0'}; 19 | // To let strcat function works in Microsoft Visual Studio 2017, 20 | // Project -> Properties -> Configuration Properties -> C/C++ -> Preprocessor 21 | // -> Preprocessor Definitions -> -> Add "_CRT_SECURE_NO_WARNINGS" 22 | strcat(strcat(strcat(fullname, firstName), ", "), lastName); 23 | cout << "Here's the information in a single string: " << fullname << endl; 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /Chapter04/PE04.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 4.4 2 | #include 3 | #include 4 | 5 | using std::string; 6 | 7 | using std::cin; 8 | using std::cout; 9 | using std::endl; 10 | using std::getline; 11 | 12 | int main() { 13 | string firstName, lastName; 14 | 15 | cout << "Enter your first name: "; 16 | getline(cin, firstName); 17 | cout << "Enter your last name: "; 18 | getline(cin, lastName); 19 | cout << "Here's the information in a single string: " 20 | << firstName + ", " + lastName << endl; 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /Chapter04/PE05.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 4.5 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | int main() { 9 | struct CandyBar { 10 | char brandName[20]; 11 | double weight; 12 | int calories; 13 | }; 14 | 15 | CandyBar snack = {"Mocha Munch", 2.3, 350}; 16 | cout << "The cany bar's brand name is " << snack.brandName 17 | << ".\nIt is " << snack.weight << " pounds.\nAnd, it has " 18 | << snack.calories << " calories." << endl; 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /Chapter04/PE06.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 4.6 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | int main() { 9 | struct CandyBar { 10 | char brandName[20]; 11 | double weight; 12 | int calories; 13 | }; 14 | 15 | CandyBar candyBar[3]; 16 | candyBar[0] = { "Hershey", 2.3, 350 }; 17 | candyBar[1] = { "Lindt", 1.8, 220 }; 18 | candyBar[2] = { "Mars", 3.5, 410 }; 19 | 20 | cout << "The candy bar's brand name is " << candyBar[0].brandName 21 | << ".\nIt is " << candyBar[0].weight << " pounds.\nAnd, it has " 22 | << candyBar[0].calories << " calories.\n" << endl; 23 | 24 | cout << "The candy bar's brand name is " << candyBar[1].brandName 25 | << ".\nIt is " << candyBar[1].weight << " pounds.\nAnd, it has " 26 | << candyBar[1].calories << " calories.\n" << endl; 27 | 28 | cout << "The candy bar's brand name is " << candyBar[2].brandName 29 | << ".\nIt is " << candyBar[2].weight << " pounds.\nAnd, it has " 30 | << candyBar[2].calories << " calories." << endl; 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /Chapter04/PE07.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 4.7 2 | #include 3 | #include 4 | 5 | using std::string; 6 | 7 | using std::cin; 8 | using std::cout; 9 | using std::endl; 10 | using std::getline; 11 | 12 | int main() { 13 | struct Pizza { 14 | string name; 15 | double diameter; 16 | double weight; 17 | }; 18 | 19 | Pizza onePizza; 20 | cout << "Please create a pizza:\n"; 21 | cout << "Enter the name of the pizza: "; 22 | getline(cin, onePizza.name); 23 | cout << "Enter the diameter of the pizza (inch): "; 24 | cin >> onePizza.diameter; 25 | cout << "Enter the weight of the pizza (pound): "; 26 | cin >> onePizza.weight; 27 | 28 | cout << "The pizza's name is " << onePizza.name 29 | << ". Its diameter is " << onePizza.diameter << " inches and weight is " 30 | << onePizza.weight << " pounds." << endl; 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /Chapter04/PE08.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 4.8 2 | #include 3 | #include 4 | 5 | using std::string; 6 | 7 | using std::cin; 8 | using std::cout; 9 | using std::endl; 10 | using std::getline; 11 | 12 | int main() { 13 | struct Pizza { 14 | string name; 15 | double diameter; 16 | double weight; 17 | }; 18 | 19 | Pizza* ptrOnePizza = new Pizza; 20 | cout << "Please create a pizza:\n"; 21 | cout << "Enter the name of the pizza: "; 22 | getline(cin, (*ptrOnePizza).name); 23 | cout << "Enter the diameter of the pizza (inch): "; 24 | cin >> (*ptrOnePizza).diameter; 25 | cout << "Enter the weight of the pizza (pound): "; 26 | cin >> (*ptrOnePizza).weight; 27 | 28 | cout << "The pizza's name is " << (*ptrOnePizza).name 29 | << ". Its diameter is " << (*ptrOnePizza).diameter << " inches and weight is " 30 | << (*ptrOnePizza).weight << " pounds." << endl; 31 | delete ptrOnePizza; 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Chapter04/PE09.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 4.9 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | int main() { 9 | struct CandyBar { 10 | char brandName[20]; 11 | double weight; 12 | int calories; 13 | }; 14 | 15 | CandyBar* ptrCandyBar = new CandyBar[3]; 16 | ptrCandyBar[0] = { "Hershey", 2.3, 350 }; 17 | ptrCandyBar[1] = { "Lindt", 1.8, 220 }; 18 | ptrCandyBar[2] = { "Mars", 3.5, 410 }; 19 | 20 | cout << "The candy bar's brand name is " << ptrCandyBar[0].brandName 21 | << ".\nIt is " << ptrCandyBar[0].weight << " pounds.\nAnd, it has " 22 | << ptrCandyBar[0].calories << " calories.\n" << endl; 23 | 24 | cout << "The candy bar's brand name is " << ptrCandyBar[1].brandName 25 | << ".\nIt is " << ptrCandyBar[1].weight << " pounds.\nAnd, it has " 26 | << ptrCandyBar[1].calories << " calories.\n" << endl; 27 | 28 | cout << "The candy bar's brand name is " << ptrCandyBar[2].brandName 29 | << ".\nIt is " << ptrCandyBar[2].weight << " pounds.\nAnd, it has " 30 | << ptrCandyBar[2].calories << " calories." << endl; 31 | delete[] ptrCandyBar; 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Chapter04/PE10.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 4.10 2 | #include 3 | #include 4 | 5 | using std::array; 6 | 7 | using std::cin; 8 | using std::cout; 9 | using std::endl; 10 | 11 | int main() { 12 | array dash; 13 | double average; 14 | 15 | cout << "Enter the 1st time for the 40-yd dash: "; 16 | cin >> dash[0]; 17 | cout << "Enter the 2nd time for the 40-yd dash: "; 18 | cin >> dash[1]; 19 | cout << "Enter the 3rd time for the 40-yd dash: "; 20 | cin >> dash[2]; 21 | 22 | average = (dash[0] + dash[1] + dash[2]) / 3.0; 23 | cout << "\nThe 1st time is " << dash[0] << "s."; 24 | cout << "\nThe 2nd time is " << dash[1] << "s."; 25 | cout << "\nThe 3rd time is " << dash[2] << "s."; 26 | cout << "\nThe average time is " << average << "s.\n"; 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /Chapter05/PE01.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 5.1 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | int main() { 9 | int small, large, sum = 0; 10 | 11 | cout << "Enter the smaller integer: "; 12 | cin >> small; 13 | cout << "Enter the larger integer: "; 14 | cin >> large; 15 | 16 | for (int i = small; i < large + 1; ++i) { 17 | sum += i; 18 | } 19 | 20 | cout << "The sum of all the integers from " 21 | << small << " through " << large 22 | << " is " << sum << ".\n"; 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Chapter05/PE02.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 5.2 2 | #include 3 | #include 4 | 5 | using std::array; 6 | 7 | using std::cin; 8 | using std::cout; 9 | using std::endl; 10 | 11 | int main() { 12 | array factorials; 13 | 14 | factorials[0] = factorials[1] = 1.0; 15 | for (int i = 2; i < 101; ++i) { 16 | factorials[i] = factorials[i - 1] * i; 17 | } 18 | 19 | cout << "The valus of 100! is " << factorials[100] << ".\n"; 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Chapter05/PE03.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 5.3 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | 7 | int main() { 8 | int newNum, sum = 0; 9 | 10 | cout << "Enter a new number: "; 11 | while (cin >> newNum && newNum != 0) { 12 | sum += newNum; 13 | cout << "The cumulative sum is " << sum << ".\n"; 14 | cout << "Enter a new number: "; 15 | } 16 | cout << "The final cumulative sum is " << sum << ".\n"; 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /Chapter05/PE04.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 5.4 2 | #include 3 | #include 4 | 5 | using std::cin; 6 | using std::cout; 7 | 8 | int main() { 9 | cout.setf(std::ios_base::fixed, std::ios_base::floatfield); 10 | 11 | int yrNum = 0; 12 | double daphne = 0.0, cleo = 0.0; 13 | 14 | while (cleo <= daphne) { 15 | daphne = 100 + yrNum * 10; 16 | cleo = 100 * pow((1 + 0.05), yrNum); 17 | yrNum++; 18 | } 19 | cout << "In year " << yrNum - 1 << ":\n"; 20 | cout << "Cleo's investment is $" << cleo << ".\n"; 21 | cout << "Dephne's investment is $" << daphne << ".\n"; 22 | 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /Chapter05/PE05.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 5.5 2 | #include 3 | #include 4 | #include 5 | 6 | using std::string; 7 | using std::array; 8 | 9 | using std::cin; 10 | using std::cout; 11 | using std::endl; 12 | 13 | int main() { 14 | string Month[12] = { "January", "February", "March", 15 | "April", "May", "June", 16 | "July", "August", "September", 17 | "October", "November", "December" }; 18 | array sales; 19 | int sumOfSales = 0; 20 | 21 | for (int i = 0; i < 12; ++i) { 22 | cout << "Enter the sales in " << Month[i] << ": \t"; 23 | cin >> sales[i]; 24 | sumOfSales += sales[i]; 25 | } 26 | cout << "------------------------------------" << endl; 27 | cout << "The total sales for the year is " << sumOfSales << ".\n"; 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Chapter05/PE06.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 5.6 2 | #include 3 | #include 4 | #include 5 | 6 | using std::string; 7 | using std::array; 8 | 9 | using std::cin; 10 | using std::cout; 11 | using std::endl; 12 | 13 | int main() { 14 | string Month[12] = { "January", "February", "March", 15 | "April", "May", "June", 16 | "July", "August", "September", 17 | "October", "November", "December" }; 18 | array, 3> sales; 19 | int sumOfSales[3] = { 0 }; 20 | 21 | for (int yr = 0; yr < 3; ++yr) { 22 | cout << "Enter the sales in year " << yr + 1 << ":\n"; 23 | for (int mm = 0; mm < 12; ++mm) { 24 | cout << "\tEnter the sales in " << Month[mm] << ": \t"; 25 | cin >> sales[yr][mm]; 26 | sumOfSales[yr] += sales[yr][mm]; 27 | } 28 | } 29 | cout << "------------------------------------------" << endl; 30 | cout << "The total sales for year 1 is " << sumOfSales[0] << ".\n"; 31 | cout << "The total sales for year 2 is " << sumOfSales[1] << ".\n"; 32 | cout << "The total sales for year 3 is " << sumOfSales[2] << ".\n"; 33 | 34 | cout << "------------------------------------------" << endl; 35 | cout << "The total sales for 3 years is " 36 | << sumOfSales[0] + sumOfSales[1] + sumOfSales[2] << ".\n"; 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Chapter05/PE07.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 5.7 2 | #include 3 | #include 4 | 5 | using std::string; 6 | 7 | using std::cin; 8 | using std::cout; 9 | using std::endl; 10 | using std::getline; 11 | 12 | int main() { 13 | struct Car { 14 | string make; 15 | int yearBuilt; 16 | }; 17 | 18 | cout << "How many cars do you with to catalog? "; 19 | int numCarCatelog; 20 | (cin >> numCarCatelog).get(); 21 | 22 | Car* pt = new Car[numCarCatelog]; 23 | for (int i = 0; i < numCarCatelog; ++i) { 24 | cout << "Car #" << i + 1 << endl; 25 | cout << "Please enter the make: "; 26 | getline(cin, pt[i].make); 27 | cout << "Please enter the year made: "; 28 | (cin >> pt[i].yearBuilt).get(); 29 | } 30 | cout << "Here is your collection:" << endl; 31 | int i = 0; 32 | while (i < numCarCatelog) { 33 | cout << pt[i].yearBuilt << " " << pt[i].make << endl; 34 | i++; 35 | } 36 | delete[] pt; 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Chapter05/PE08.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 5.8 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | const int ArraySize = 20; 9 | 10 | int main() { 11 | char input[ArraySize]; 12 | int cnt = 0; 13 | 14 | cout << "Enter words (to stop, type the word done)\n"; 15 | cout << "(each input cannot be longer than 20 characters):" << endl; 16 | while (cin >> input && strcmp(input, "done")) { 17 | ++cnt; 18 | } 19 | 20 | // Because the program can read more words after "done", there will 21 | // be more words in cin. The following while loop clear all words 22 | // after "done", so that it won't affect the while loop in main 23 | // function. 24 | while (cin.get() != '\n') { 25 | continue; 26 | } 27 | cout << "You entered a total of " << cnt << " words.\n"; 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Chapter05/PE09.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 5.9 2 | #include 3 | #include 4 | 5 | using std::string; 6 | 7 | using std::cin; 8 | using std::cout; 9 | using std::endl; 10 | 11 | int main() { 12 | string input; 13 | int cnt = 0; 14 | 15 | cout << "Enter words (to stop, type the word done):" << endl; 16 | while (cin >> input && input != "done") { 17 | ++cnt; 18 | } 19 | 20 | while (cin.get() != '\n') { 21 | continue; 22 | } 23 | cout << "You entered a total of " << cnt << " words.\n"; 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Chapter05/PE10.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 5.10 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | int main() { 9 | cout << "Enter number of rows: "; 10 | int rowNum; 11 | cin >> rowNum; 12 | 13 | int periods = rowNum - 1, asterisks = 1; 14 | for (int i = 0; i < rowNum; ++i) { 15 | for (int period = 0; period < periods; ++period) { 16 | cout << "."; 17 | } 18 | for (int asterisk = 0; asterisk < asterisks; ++asterisk) { 19 | cout << "*"; 20 | } 21 | cout << endl; 22 | --periods; 23 | ++asterisks; 24 | } 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Chapter06/PE01.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 6.1 2 | #include 3 | #include 4 | 5 | using std::cin; 6 | using std::cout; 7 | using std::endl; 8 | 9 | int main() { 10 | char ch; 11 | cout << "Enter from keyboard (using to \"@\" to stop):\n"; 12 | 13 | cin.get(ch); 14 | while (ch != '@') { 15 | if (!isdigit(ch)) { 16 | if (islower(ch)) { 17 | cout << char(toupper(ch)); 18 | } 19 | else if (isupper(ch)) { 20 | cout << char(tolower(ch)); 21 | } 22 | else { 23 | cout << ch; 24 | } 25 | } 26 | cin.get(ch); 27 | } 28 | cout << endl; 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /Chapter06/PE02.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 6.2 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using std::array; 8 | using std::string; 9 | 10 | using std::cin; 11 | using std::cout; 12 | using std::endl; 13 | 14 | const int numDonation = 10; 15 | 16 | int main() { 17 | array donation; 18 | double input, sum = 0.0, average; 19 | int idx = 0, cnt = 0; 20 | 21 | while (cin >> input && idx < numDonation) { 22 | donation[idx] = input; 23 | sum += input; 24 | ++idx; 25 | } 26 | // The number idx is one more than the number of inputs. 27 | average = sum / double(idx); 28 | for (int i = 0; i < idx; ++i) { 29 | if (donation[i] > average) { 30 | ++cnt; 31 | } 32 | } 33 | 34 | cout << "The average of the numbers is " << average << ".\n"; 35 | cout << cnt << " numbers in the array are larger than the average.\n"; 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /Chapter06/PE03.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 6.3 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | int main() { 9 | char ch; 10 | 11 | cout << "Please enter one of the following choices:\n"; 12 | cout << "c) carnivore\tp) pianist\n"; 13 | cout << "t) tree\t\tg) game\n"; 14 | 15 | while (cin.get(ch)) { 16 | if (!(ch == 'c' || ch == 'p' || ch == 't' || ch == 'g')) { 17 | cout << "Please enter a c, p, t, or g: "; 18 | cin.clear(); 19 | while (cin.get() != '\n') 20 | continue; 21 | } 22 | else { 23 | switch (ch) 24 | { 25 | case 'c': 26 | cout << "A tiger is a carnivore." << endl; 27 | break; 28 | case 'p': 29 | cout << "Lang lang is a pianist." << endl; 30 | break; 31 | case 't': 32 | cout << "A maple is a tree." << endl; 33 | break; 34 | case 'g': 35 | cout << "FIFA is a game." << endl; 36 | break; 37 | default: 38 | break; 39 | } 40 | break; 41 | } 42 | } 43 | 44 | return 0; 45 | } -------------------------------------------------------------------------------- /Chapter06/PE05.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 6.5 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | int main() { 9 | double input; 10 | 11 | cout << "Enter your income: "; 12 | while (cin >> input) { 13 | if (input >= 0) { 14 | double tax; 15 | if (input > 35000) { 16 | tax = 10000 * 0.1 + 20000 * 0.15 + (input - 35000) * 0.2; 17 | } 18 | else if (input > 20000) { 19 | tax = 10000 * 0.1 + (input - 20000) * 0.15; 20 | } 21 | else if (input > 10000) { 22 | tax = (input - 10000) * 0.1; 23 | } 24 | else { 25 | tax = 0.0; 26 | } 27 | 28 | cout << "Your solicit income is " << input << " tvarps.\n"; 29 | cout << "You would owe " << tax << " tvarps.\n"; 30 | cout << "Enter another income\n"; 31 | cout << "(enter a negative number or non-numeric input "; 32 | cout << "to terminate): "; 33 | } 34 | else { 35 | break; 36 | } 37 | } 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /Chapter06/PE06.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 6.6 2 | #include 3 | #include 4 | 5 | using std::string; 6 | 7 | using std::cin; 8 | using std::cout; 9 | using std::endl; 10 | 11 | struct Contribution { 12 | string member; 13 | double contribution; 14 | }; 15 | 16 | int main() { 17 | int numContributors; 18 | cout << "Enter the number of contributors: " << endl; 19 | (cin >> numContributors).get(); 20 | 21 | Contribution* ptrContribution = new Contribution[numContributors]; 22 | bool* ptrGrandPatrons = new bool[numContributors]; 23 | for (int i = 0; i < numContributors; ++i) { 24 | cout << "Enter the contributor's name: "; 25 | getline(cin, ptrContribution[i].member); 26 | cout << "Enter the amount of the contribution: "; 27 | (cin >> ptrContribution[i].contribution).get(); 28 | 29 | if (ptrContribution[i].contribution > 10000) { 30 | ptrGrandPatrons[i] = true; 31 | } 32 | else { 33 | ptrGrandPatrons[i] = false; 34 | } 35 | } 36 | 37 | int cnt = 0; 38 | cout << "Grand Patrons: " << endl; 39 | for (int i = 0; i < numContributors; ++i) { 40 | if (ptrGrandPatrons[i]) { 41 | ++cnt; 42 | cout << "Donor " << ptrContribution[i].member; 43 | cout << " contributed $" << ptrContribution[i].contribution << ".\n"; 44 | } 45 | } 46 | if (cnt == 0) { 47 | cout << "none." << endl; 48 | } 49 | cnt = 0; 50 | 51 | cout << "Patrons: " << endl; 52 | for (int i = 0; i < numContributors; ++i) { 53 | if (!ptrGrandPatrons[i]) { 54 | ++cnt; 55 | cout << "Donor " << ptrContribution[i].member; 56 | cout << " contributed $" << ptrContribution[i].contribution << ".\n"; 57 | } 58 | } 59 | if (cnt == 0) { 60 | cout << "none." << endl; 61 | } 62 | 63 | delete[] ptrContribution; 64 | delete[] ptrGrandPatrons; 65 | 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /Chapter06/PE07.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 6.7 2 | #include 3 | #include 4 | #include 5 | 6 | using std::string; 7 | 8 | using std::cin; 9 | using std::cout; 10 | using std::endl; 11 | 12 | int main() { 13 | string word; 14 | int numVowels = 0, numConsonants = 0, numOthers = 0; 15 | cout << "Enter words (q to quit): " << endl; 16 | while (cin >> word) { 17 | if (word == "q") { 18 | break; 19 | } 20 | else if (isalpha(word[0])) { 21 | switch (word[0]) { 22 | case 'a': 23 | case 'e': 24 | case 'i': 25 | case 'o': 26 | case 'u': 27 | ++numVowels; 28 | break; 29 | default: 30 | ++numConsonants; 31 | break; 32 | } 33 | } 34 | else { 35 | ++numOthers; 36 | } 37 | } 38 | 39 | cout << numVowels << " words beginning with vowels\n"; 40 | cout << numConsonants << " words beginning with consonants\n"; 41 | cout << numOthers << " others\n"; 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Chapter06/PE08.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 6.8 2 | #include 3 | #include 4 | #include 5 | 6 | using std::ifstream; 7 | 8 | using std::cout; 9 | using std::endl; 10 | 11 | int main() { 12 | ifstream inFile; 13 | inFile.open("PE08.txt"); 14 | 15 | // Check if the file is successfully opened. 16 | if (!inFile.is_open()) { 17 | cout << "Could not open the file PE08.txt" << endl; 18 | cout << "Program terminating." << endl; 19 | exit(EXIT_FAILURE); 20 | } 21 | 22 | char ch; 23 | int cnt = 0; 24 | while (inFile >> ch) { 25 | ++cnt; 26 | } 27 | 28 | // Check if the file is read to the end. 29 | if (inFile.eof()) { 30 | cout << "End of file reached.\n"; 31 | } 32 | else if (inFile.fail()) { 33 | cout << "Input terminated by data mismatch.\n"; 34 | } 35 | else { 36 | cout << "Input terminated for unknown reason.\n"; 37 | } 38 | 39 | // Show the result 40 | if (cnt == 0) { 41 | cout << "No data processed.\n"; 42 | } 43 | else { 44 | cout << "The total number of character should be " << cnt << endl; 45 | } 46 | 47 | inFile.close(); 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /Chapter06/PE08.txt: -------------------------------------------------------------------------------- 1 | This is the txt test file for PE08.cpp. 2 | Write a program that opens a text file, reads it character-by-character to the end of 3 | the file,and reports the number of characters in the file. 4 | The total number of character should be 189. -------------------------------------------------------------------------------- /Chapter06/PE09.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 6.9 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using std::string; 8 | using std::ifstream; 9 | 10 | using std::cin; 11 | using std::cout; 12 | using std::endl; 13 | using std::getline; 14 | 15 | struct Contribution { 16 | string member; 17 | double contribution; 18 | }; 19 | 20 | int main() { 21 | ifstream inFile; 22 | inFile.open("PE09.txt"); 23 | 24 | if (!inFile.is_open()) { 25 | cout << "Could not open the file PE09.txt" << endl; 26 | cout << "Program terminating." << endl; 27 | exit(EXIT_FAILURE); 28 | } 29 | 30 | int numContributors; 31 | (inFile >> numContributors).get(); 32 | 33 | Contribution* ptrContribution = new Contribution[numContributors]; 34 | bool* ptrGrandPatrons = new bool[numContributors]; 35 | for (int i = 0; i < numContributors; ++i) { 36 | getline(inFile, ptrContribution[i].member); 37 | (inFile >> ptrContribution[i].contribution).get(); 38 | 39 | if (ptrContribution[i].contribution > 10000) { 40 | ptrGrandPatrons[i] = true; 41 | } 42 | else { 43 | ptrGrandPatrons[i] = false; 44 | } 45 | } 46 | 47 | int cnt = 0; 48 | cout << "Grand Patrons: " << endl; 49 | for (int i = 0; i < numContributors; ++i) { 50 | if (ptrGrandPatrons[i]) { 51 | ++cnt; 52 | cout << "Donor " << ptrContribution[i].member; 53 | cout << " contributed $" << ptrContribution[i].contribution << ".\n"; 54 | } 55 | } 56 | if (cnt == 0) { 57 | cout << "none." << endl; 58 | } 59 | cnt = 0; 60 | 61 | cout << "Patrons: " << endl; 62 | for (int i = 0; i < numContributors; ++i) { 63 | if (!ptrGrandPatrons[i]) { 64 | ++cnt; 65 | cout << "Donor " << ptrContribution[i].member; 66 | cout << " contributed $" << ptrContribution[i].contribution << ".\n"; 67 | } 68 | } 69 | if (cnt == 0) { 70 | cout << "none." << endl; 71 | } 72 | 73 | delete[] ptrContribution; 74 | delete[] ptrGrandPatrons; 75 | 76 | inFile.close(); 77 | 78 | return 0; 79 | } -------------------------------------------------------------------------------- /Chapter06/PE09.txt: -------------------------------------------------------------------------------- 1 | 4 2 | Sam Stone 3 | 2000 4 | Freida Flass 5 | 100500 6 | Tammy Tubbs 7 | 5000 8 | Rich Raptor 9 | 55000 -------------------------------------------------------------------------------- /Chapter07/PE01.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 7.1 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | double harmonicMean(double x, double y); 9 | 10 | int main() { 11 | double x, y; 12 | cout << "Enter a pair of numbers: (to stop enter a pair of 0) " << endl; 13 | while (cin >> x >> y && !(x == 0 && y == 0)) { 14 | cout << "The harmonic mean is " << harmonicMean(x, y) << ".\n"; 15 | cout << "Enter another pair of numbers: " << endl; 16 | } 17 | 18 | return 0; 19 | } 20 | 21 | double harmonicMean(double x, double y) { 22 | return 2.0 * x * y / (x + y); 23 | } -------------------------------------------------------------------------------- /Chapter07/PE02.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 7.2 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | const int NumScores = 10; 9 | 10 | int input(double* ptrScores); 11 | void display(double* ptrScores, int size); 12 | double average(double* ptrScores, int size); 13 | 14 | int main() { 15 | int size; 16 | double score, avg; 17 | double scores[NumScores]; 18 | double* ptrScores = scores; 19 | 20 | size = input(ptrScores); 21 | display(ptrScores, size); 22 | avg = average(ptrScores, size); 23 | 24 | cout << "The average is " << avg << ".\n"; 25 | 26 | return 0; 27 | } 28 | 29 | int input(double* ptrScores) { 30 | double score; 31 | int cnt = 0; 32 | 33 | // Read scores from user input 34 | cout << "Enter up to 10 golf scores (to stop enter a non-digit):" << endl; 35 | for (int i = 0; i < NumScores; ++i) { 36 | if (cin >> score) { 37 | ptrScores[i] = score; 38 | ++cnt; 39 | } 40 | else { 41 | break; 42 | } 43 | } 44 | return cnt; 45 | } 46 | 47 | void display(double* ptrScores, int size) { 48 | cout << "The scores are "; 49 | for (int i = 0; i < size; ++i) { 50 | if (ptrScores[i] >= 0) { 51 | cout << ptrScores[i] << " "; 52 | } 53 | } 54 | cout << endl; 55 | } 56 | 57 | double average(double* ptrScores, int size) { 58 | double sum = 0.0; 59 | 60 | for (int i = 0; i < size; ++i) { 61 | sum += ptrScores[i]; 62 | } 63 | 64 | return sum / double(size); 65 | } -------------------------------------------------------------------------------- /Chapter07/PE03.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 7.3 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | struct Box { 9 | char maker[40]; 10 | float height; 11 | float width; 12 | float length; 13 | float volume; 14 | }; 15 | 16 | void displayBox(Box box); 17 | void setVolume(Box* ptrBox); 18 | 19 | int main() { 20 | Box box = { "Box1", 1.1, 2.2, 3.3, 0.0 }; 21 | Box* ptrBox = &box; 22 | 23 | cout << "Box 1 has following characters:" << endl; 24 | displayBox(box); 25 | 26 | cout << "The volume need to be calculated." << endl; 27 | cout << "After calculation, it becomes to: " << endl; 28 | setVolume(ptrBox); 29 | displayBox(box); 30 | 31 | return 0; 32 | } 33 | 34 | void displayBox(Box box) { 35 | cout << "The maker is " << box.maker << endl; 36 | cout << "The height is " << box.height << endl; 37 | cout << "The width is " << box.width << endl; 38 | cout << "The length is " << box.length << endl; 39 | cout << "The volume is " << box.volume << endl; 40 | } 41 | 42 | void setVolume(Box* ptrBox) { 43 | ptrBox->volume = ptrBox->length * ptrBox->width * ptrBox->height; 44 | } -------------------------------------------------------------------------------- /Chapter07/PE04.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 7.4 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | long double probability(unsigned int numbers, unsigned int picks); 9 | 10 | int main() { 11 | cout << "The probability of winning a Mega is " 12 | << probability(47, 5) * probability(27, 1) << ".\n"; 13 | 14 | return 0; 15 | } 16 | 17 | long double probability(unsigned int numbers, unsigned int picks) { 18 | long double result = 1.0; 19 | long double n; 20 | unsigned int p; 21 | 22 | for (n = numbers, p = picks; p > 0; n--, p--) { 23 | result = result * n / p; 24 | } 25 | 26 | return result; 27 | } -------------------------------------------------------------------------------- /Chapter07/PE05.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 7.5 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | long double factorial(int num); 9 | 10 | int main() { 11 | int num; 12 | cout << "Enter an integer for its factorial: "; 13 | while (cin >> num) { 14 | cout << num << "! = " << factorial(num) << endl; 15 | cout << "Enter another integer: "; 16 | } 17 | 18 | return 0; 19 | } 20 | 21 | long double factorial(int num) { 22 | if (num == 0) { 23 | return 1; 24 | } 25 | 26 | return num * factorial(num - 1); 27 | } -------------------------------------------------------------------------------- /Chapter07/PE06.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 7.6 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | const int arrSize = 10; 9 | 10 | int Fill_array(double arr[], int size); 11 | void Show_array(const double arr[], int size); 12 | void Reverse_array(double arr[], int size); 13 | 14 | int main() { 15 | double testArr[arrSize]; 16 | 17 | // Fill an array 18 | int testArrSize = Fill_array(testArr, arrSize); 19 | cout << "The size of the input array is " << testArrSize << ".\n"; 20 | 21 | // Show the array 22 | Show_array(testArr, testArrSize); 23 | 24 | // Reverse the array 25 | Reverse_array(testArr, testArrSize); 26 | 27 | // Show the array 28 | cout << "After reversing the array:" << endl; 29 | Show_array(testArr, testArrSize); 30 | 31 | // Reverse all but the first and last elements of the array 32 | Reverse_array(testArr + 1, testArrSize - 2); 33 | 34 | // Show the array 35 | cout << "After reversing all but the first and last element " 36 | << "of the array:\n"; 37 | Show_array(testArr, testArrSize); 38 | 39 | return 0; 40 | } 41 | 42 | int Fill_array(double arr[], int size) { 43 | int i; 44 | for (i = 0; i < size; ++i) { 45 | int temp; 46 | cout << "Enter value #" << i + 1 << ": "; 47 | if (cin >> temp) { 48 | arr[i] = temp; 49 | } 50 | else { 51 | break; 52 | } 53 | } 54 | return i; 55 | } 56 | 57 | void Show_array(const double arr[], int size) { 58 | cout << "The array is "; 59 | for (int i = 0; i < size; ++i) { 60 | cout << arr[i] << " "; 61 | } 62 | cout << endl; 63 | } 64 | 65 | void Reverse_array(double arr[], int size) { 66 | for (int i = 0, j = size - 1; i < j; ++i, --j) { 67 | double temp = arr[j]; 68 | arr[j] = arr[i]; 69 | arr[i] = temp; 70 | } 71 | } -------------------------------------------------------------------------------- /Chapter07/PE07.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 7.7 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | const int Max = 5; 9 | 10 | double* fill_array(double* begin, double* end); 11 | void show_array(const double* begin, const double* end); 12 | void revalue(double r, double* begin, double* end); 13 | 14 | int main() { 15 | double properties[Max]; 16 | 17 | double* endProperties = fill_array(properties, properties + Max); 18 | show_array(properties, endProperties); 19 | if (endProperties != properties) { 20 | cout << "Enter revaluation factor: "; 21 | double factor; 22 | while (!(cin >> factor)) { 23 | cin.clear(); 24 | while (cin.get() != '\n') { 25 | continue; 26 | } 27 | cout << "Bad input; Please enter a number: "; 28 | } 29 | revalue(factor, properties, endProperties); 30 | show_array(properties, endProperties); 31 | } 32 | cout << "Done.\n"; 33 | cin.get(); 34 | 35 | return 0; 36 | } 37 | 38 | double* fill_array(double* begin, double* end) { 39 | double temp; 40 | double* tempPtr; 41 | int cnt = 1; 42 | for (tempPtr = begin; tempPtr != end; ++tempPtr) { 43 | cout << "Enter value #" << cnt << ": "; 44 | cin >> temp; 45 | if (!cin) { 46 | cin.clear(); 47 | while (cin.get() != '\n') { 48 | continue; 49 | } 50 | cout << "Badinput;" << endl; 51 | break; 52 | } 53 | else if (temp < 0) { 54 | break; 55 | } 56 | *tempPtr = temp; 57 | ++cnt; 58 | } 59 | return tempPtr; 60 | } 61 | 62 | void show_array(const double* begin, const double* end) { 63 | int cnt = 1; 64 | for (const double* tempPtr = begin; tempPtr != end; ++tempPtr) { 65 | cout << "Property #" << cnt << ": $"; 66 | cout << *tempPtr << endl; 67 | ++cnt; 68 | } 69 | } 70 | 71 | void revalue(double r, double* begin, double* end) { 72 | for (double* tempPtr = begin; tempPtr != end; ++tempPtr) { 73 | *tempPtr *= r; 74 | } 75 | } 76 | 77 | -------------------------------------------------------------------------------- /Chapter07/PE08.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 7.8 2 | #include 3 | #include 4 | #include 5 | 6 | using std::array; 7 | using std::string; 8 | 9 | using std::cin; 10 | using std::cout; 11 | using std::endl; 12 | 13 | const int Seasons = 4; 14 | const char* Snames[Seasons] = { "Spring", "Summer", "Fall", "Winter"}; 15 | 16 | struct Expenses { 17 | double expenses[Seasons]; 18 | }; 19 | 20 | void fillA(double* pa); 21 | void showA(const double* da); 22 | 23 | void fillB(Expenses* pa); 24 | void showB(const Expenses da); 25 | 26 | int main() { 27 | cout << "Version a:" << endl; 28 | double expensesA[4]; 29 | // Pass the array == pass the address of the array 30 | fillA(expensesA); 31 | showA(expensesA); 32 | cout << endl; 33 | 34 | cout << "Version b:" << endl; 35 | Expenses expensesB; 36 | fillB(&expensesB); 37 | showB(expensesB); 38 | 39 | return 0; 40 | } 41 | 42 | void fillA(double* pa) { 43 | for (int i = 0; i < Seasons; ++i) { 44 | cout << "Enter " << Snames[i] << " expenses: "; 45 | cin >> pa[i]; 46 | } 47 | } 48 | 49 | void showA(const double* da) { 50 | double total = 0.0; 51 | cout << "\nEXPRESSES\n"; 52 | for (int i = 0; i < Seasons; ++i) { 53 | cout << Snames[i] << ": $" << da[i] << endl; 54 | total += da[i]; 55 | } 56 | cout << "Total Expenses: $" << total << endl; 57 | } 58 | 59 | void fillB(Expenses* pa) { 60 | for (int i = 0; i < Seasons; ++i) { 61 | cout << "Enter " << Snames[i] << " expenses: "; 62 | cin >> pa->expenses[i]; 63 | } 64 | } 65 | 66 | void showB(const Expenses da) { 67 | double total = 0.0; 68 | cout << "\nEXPRESSES\n"; 69 | for (int i = 0; i < Seasons; ++i) { 70 | cout << Snames[i] << ": $" << da.expenses[i] << endl; 71 | total += da.expenses[i]; 72 | } 73 | cout << "Total Expenses: $" << total << endl; 74 | } -------------------------------------------------------------------------------- /Chapter07/PE10.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 7.10 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::endl; 7 | 8 | const int Operations = 4; 9 | 10 | double calculate(const double x, const double y, 11 | double (*ptr)(const double, const double)); 12 | double add(const double x, const double y); 13 | double subtract(const double x, const double y); 14 | double multiply(const double x, const double y); 15 | double divide(const double x, const double y); 16 | 17 | int main() { 18 | double xInput, yInput; 19 | cout << "Enter a pair of x and y: "; 20 | while (cin >> xInput >> yInput) { 21 | // add <- ptrFcn[0] 22 | // subtract <- ptrFcn[1] 23 | // multiply <- ptrFcn[2] 24 | // divide <- ptrFcn[3] 25 | double (*ptrFcn[Operations])(const double, const double) = { 26 | add, subtract, multiply, divide 27 | }; 28 | 29 | for (int i = 0; i < Operations; ++i) { 30 | if (i == 0) { 31 | cout << "calculate(x, y, add): "; 32 | } 33 | else if (i == 1) { 34 | cout << "calculate(x, y, subtract): "; 35 | } 36 | else if (i == 2) { 37 | cout << "calculate(x, y, multiply): "; 38 | } 39 | else { // i == 3 40 | cout << "calculate(x, y, divide): "; 41 | } 42 | cout << calculate(xInput, yInput, ptrFcn[i]) << endl; 43 | } 44 | cout << "=====================================" << endl; 45 | cout << "Enter another pair of x and y: "; 46 | } 47 | 48 | return 0; 49 | } 50 | 51 | double calculate(const double x, const double y, 52 | double (*ptr)(const double, const double)) { 53 | return ptr(x, y); 54 | } 55 | 56 | double add(const double x, const double y) { 57 | return x + y; 58 | } 59 | 60 | double subtract(const double x, const double y) { 61 | return x - y; 62 | } 63 | 64 | double multiply(const double x, const double y) { 65 | return x * y; 66 | } 67 | 68 | double divide(const double x, const double y) { 69 | return x / y; 70 | } -------------------------------------------------------------------------------- /Chapter07/README.md: -------------------------------------------------------------------------------- 1 | # Re-do Questions: 2 | - [ ] Programming Exercise 7.8 3 | - [ ] Programming Exercise 7.10 4 | # Notes: 5 | - Pointer declaration: 6 | - _`int* ptr`_ is a pointer to an int (* is close to the variable type) 7 | - _`int (*ptrFcn)(double, double)`_ is a pointer to functions (* is close to the pointer) 8 | - Dereference operator (*): 9 | - _`*ptr`_ returns the value of the pointer points to (* is close to the pointer) -------------------------------------------------------------------------------- /Chapter08/PE01.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 8.1 2 | #include 3 | #include 4 | 5 | using std::cin; 6 | using std::cout; 7 | using std::endl; 8 | using std::string; 9 | 10 | static int timesCalled = 0; 11 | 12 | void printString(const string* ptrStr, int num = 0); 13 | 14 | int main() { 15 | string inputString; 16 | int times; 17 | 18 | cout << "Enter a string: "; 19 | getline(cin, inputString); 20 | cout << "Enter a number of times: "; 21 | while (cin >> times) { 22 | if (times == 0) { 23 | // Use the default argument. 24 | // It will be print once. 25 | printString(&inputString); 26 | } 27 | else { 28 | printString(&inputString, times); 29 | } 30 | cout << "Enter another number of times: "; 31 | cin.get(); 32 | } 33 | 34 | return 0; 35 | } 36 | 37 | void printString(const string* ptrStr, int num) { 38 | // The number of times the string is printed 39 | // is not equal to the value of the second 40 | // argument; it is equal to the number of 41 | // times the function has been called. 42 | ++timesCalled; 43 | if (num == 0) { 44 | cout << *ptrStr << endl; 45 | } 46 | else { 47 | for (int i = 0; i < timesCalled; ++i) { 48 | cout << *ptrStr << endl; 49 | } 50 | } 51 | 52 | } -------------------------------------------------------------------------------- /Chapter08/PE02.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 8.2 2 | #include 3 | #include 4 | 5 | using std::cin; 6 | using std::cout; 7 | using std::endl; 8 | 9 | const int brandNameSize = 20; 10 | 11 | struct CandyBar { 12 | char brandName[brandNameSize]; 13 | double weight; 14 | int calories; 15 | }; 16 | 17 | // To set the default value for brand name, it is better to and const. 18 | // Otherwise, a warning message "ISO C++ forbids converting a string 19 | // constant to 'char*'" will be pop out. 20 | const CandyBar& setCandyBar(CandyBar& candyBar, 21 | const char* _brandName = "Millennium Munch", 22 | const double _weight = 2.85, 23 | const int _calories = 350); 24 | void displayCandyBar(const CandyBar& candyBar); 25 | 26 | int main() { 27 | CandyBar candyBar1; 28 | cout << "Set the candy bar from default arguments:" << endl; 29 | setCandyBar(candyBar1); 30 | displayCandyBar(candyBar1); 31 | cout << "=========================================" << endl; 32 | 33 | CandyBar candyBar2; 34 | char iBrandName[brandNameSize]; 35 | double iWeight; 36 | int iCalories; 37 | cout << "Please input a candy bar:" << endl; 38 | cout << "Enter the brand name: "; 39 | cin.getline(iBrandName, brandNameSize); 40 | cout << "Enter the weight: "; 41 | cin >> iWeight; 42 | cout << "Enter the calories: "; 43 | cin >> iCalories; 44 | displayCandyBar(setCandyBar(candyBar2, iBrandName, iWeight, iCalories)); 45 | 46 | return 0; 47 | } 48 | 49 | const CandyBar& setCandyBar(CandyBar& candyBar, 50 | const char* _brandName, 51 | const double _weight, 52 | const int _calories) { 53 | strcpy(candyBar.brandName, _brandName); 54 | candyBar.weight = _weight; 55 | candyBar.calories = _calories; 56 | 57 | return candyBar; 58 | } 59 | 60 | void displayCandyBar(const CandyBar& candyBar) { 61 | cout << "The information of the candy bar:" << endl; 62 | cout << "Its brand name is " << candyBar.brandName << endl; 63 | cout << "Its weight is " << candyBar.weight << endl; 64 | cout << "Its calories is " << candyBar.calories << endl; 65 | } -------------------------------------------------------------------------------- /Chapter08/PE03.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 8.3 2 | #include 3 | #include 4 | #include 5 | 6 | using std::cin; 7 | using std::cout; 8 | using std::endl; 9 | using std::getline; 10 | using std::string; 11 | 12 | string myToupper(string& str); 13 | 14 | int main() { 15 | string input; 16 | cout << "Enter a string (q to quit): "; 17 | while (getline(cin, input) && input != "q") { 18 | cout << myToupper(input) << endl; 19 | cout << "Enter a string (q to quit): "; 20 | } 21 | cout << "Bye." << endl; 22 | 23 | return 0; 24 | } 25 | 26 | string myToupper(string& str) { 27 | for (int i = 0; i < str.size(); ++i) { 28 | str[i] = toupper(str[i]); 29 | } 30 | return str; 31 | } -------------------------------------------------------------------------------- /Chapter08/PE04.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include // for strlen(), strcpy() 3 | using namespace std; 4 | 5 | struct stringy { 6 | char* str; // points to a string 7 | int ct; // length of string (not counting '\0') 8 | }; 9 | 10 | // prototypes for set(), show(), and show() go here 11 | void set(stringy& beany, char charArr[]); 12 | void show(const stringy& beany, int times = 1); 13 | void show(const char* ptrStr, int times = 1); 14 | 15 | int main() { 16 | stringy beany; 17 | char testing[] = "Reality isn't what it used to be."; 18 | 19 | set(beany, testing); 20 | // first argument is a reference, 21 | // allocates space to hold copy of testing, 22 | // sets str member of beany to point to the 23 | // new block, copies testing to new block, 24 | // and sets ct member of beany 25 | show(beany); // prints member string once 26 | show(beany, 2); // prints member string twice 27 | 28 | testing[0] = 'D'; 29 | testing[1] = 'u'; 30 | show(testing); // prints testing string once 31 | show(testing, 3); // prints testing string thrice 32 | 33 | show("Done!"); 34 | 35 | delete[] beany.str; 36 | 37 | return 0; 38 | } 39 | 40 | void set(stringy& beany, char charArr[]) { 41 | beany.ct = strlen(charArr); 42 | beany.str = new char[beany.ct + 1]; 43 | strcpy(beany.str, charArr); 44 | } 45 | 46 | void show(const stringy& beany, int times) { 47 | for (int i = 0; i < times; ++i) { 48 | cout << "The str is \"" << beany.str << "\".\n"; 49 | cout << "And, the ct is " << beany.ct << ".\n"; 50 | } 51 | cout << "===============================================" << endl; 52 | } 53 | 54 | void show(const char* ptrStr, int times) { 55 | for (int i = 0; i < times; ++i) { 56 | for (int j = 0; ptrStr[j] != '\0'; ++j) { 57 | cout << ptrStr[j]; 58 | } 59 | cout << endl; 60 | } 61 | cout << "===============================================" << endl; 62 | } -------------------------------------------------------------------------------- /Chapter08/PE05.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 8.5 2 | #include 3 | 4 | using std::cout; 5 | 6 | const int size = 5; 7 | 8 | template 9 | T max5(const T arr[]); 10 | 11 | int main() { 12 | int testInt[size] = { 1, 5, 4, 3, 2 }; 13 | double testDouble[size] = { 1.1, 5.5, 4.4, 3.3, 2.2 }; 14 | 15 | cout << "The largest number for the array of five int is " 16 | << max5(testInt) << ".\n"; 17 | 18 | cout << "The largest number for the array of five doulbe is " 19 | << max5(testDouble) << ".\n"; 20 | 21 | return 0; 22 | } 23 | 24 | template 25 | T max5(const T arr[]) { 26 | T maxNum = arr[0]; 27 | for (int i = 0; i < size; ++i) { 28 | maxNum = maxNum > arr[i] ? maxNum : arr[i]; 29 | } 30 | return maxNum; 31 | } -------------------------------------------------------------------------------- /Chapter08/PE06.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 8.6 2 | #include 3 | #include 4 | 5 | using std::cout; 6 | using std::endl; 7 | 8 | template 9 | T maxn(T arr[], int arrSize); 10 | 11 | // Because char* arr[] is a pointer to pointers, const cannot be used. 12 | // So, the previous template cannot have const either. 13 | template <> 14 | char* maxn(char* arr[], int arrSize); 15 | 16 | int main() { 17 | int testInt[] = { 1, 6, 5, 2, 3, 4 }; 18 | double testDouble[] = { 1.1, 4.4, 2.2, 3.3 }; 19 | // 1. Should not have "const" in front of char* testChar[5]. 20 | // Otherwise, it will call the first template. 21 | // 2. If (char*) are not added, a warning message will pop out as 22 | // "ISO C++ forbids converting a string constant to 'char*'". 23 | // To avoid the warning message, there are 3 solutions: 24 | // Solution 1: const char* testChar[5]... 25 | // Solution 2: string testChar[5]... 26 | // Solution 3: char* testChar[5] = (char*)"..." 27 | char* testChar[5] = { (char*)"apple", 28 | (char*)"evening", 29 | (char*)"daily", 30 | (char*)"car", 31 | (char*)"bed" }; 32 | 33 | cout << "The largest number for the array of six int is " 34 | << maxn(testInt, 6) << ".\n"; 35 | 36 | cout << "The largest number for the array of four doulbe is " 37 | << maxn(testDouble, 4) << ".\n"; 38 | 39 | cout << "The longest string for the array of five char is " 40 | << maxn(testChar, 5) << ".\n"; 41 | 42 | return 0; 43 | } 44 | 45 | template 46 | T maxn(T arr[], int arrSize) { 47 | cout << "General template is called." << endl; 48 | T maxNum = arr[0]; 49 | for (int i = 0; i < arrSize; ++i) { 50 | maxNum = maxNum > arr[i] ? maxNum : arr[i]; 51 | } 52 | return maxNum; 53 | } 54 | 55 | template <> 56 | char* maxn(char* arr[], int arrSize) { 57 | cout << "Specialization is called." << endl; 58 | char* maxStr = arr[0]; 59 | for (int i = 0; i < arrSize; ++i) { 60 | maxStr = strlen(maxStr) > strlen(arr[i]) ? maxStr : arr[i]; 61 | } 62 | return maxStr; 63 | } -------------------------------------------------------------------------------- /Chapter08/PE07.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 8.7 2 | #include 3 | 4 | using std::cout; 5 | using std::endl; 6 | 7 | struct debts { 8 | char name[50]; 9 | double amount; 10 | }; 11 | 12 | template 13 | T SumArray(T arr[], int n); 14 | 15 | template 16 | T SumArray(T* arr[], int n); 17 | 18 | 19 | int main() { 20 | int things[6] = { 13, 31, 103, 301, 310, 130 }; 21 | struct debts mr_E[3] = { {"Ima Wolfe", 2400.0}, 22 | {"Ura Foxe", 1300.0}, 23 | {"Iby Stout", 1800.0} }; 24 | double* pd[3]; 25 | 26 | for (int i = 0; i < 3; ++i) { 27 | pd[i] = &mr_E[i].amount; 28 | } 29 | 30 | cout << "Listing Mr. E's counts of things:\n"; 31 | cout << SumArray(things, 6) << endl; 32 | cout << "Listing Mr. E's debts:\n"; 33 | cout << SumArray(pd, 3) << endl; 34 | 35 | return 0; 36 | } 37 | 38 | template 39 | T SumArray(T arr[], int n) { 40 | cout << "template A\n"; 41 | T res = arr[0]; 42 | for (int i = 1; i < n; ++i) { 43 | res += arr[i]; 44 | } 45 | return res; 46 | } 47 | 48 | template 49 | T SumArray(T* arr[], int n) { 50 | cout << "template B\n"; 51 | T res = *arr[0]; 52 | for (int i = 1; i < n; ++i) { 53 | res += *arr[i]; 54 | } 55 | return res; 56 | } -------------------------------------------------------------------------------- /Chapter08/README.md: -------------------------------------------------------------------------------- 1 | # Re-do Questions: 2 | - [ ] Programming Exercise 8.6 3 | # Notes: 4 | - Reference declaration: 5 | - _`int& variable`_ is a reference of the int variable (& is close to the variable type) 6 | - Address-of operator (&): 7 | - _`&variable`_ returns the address of the variable (& is close to the variable) 8 | # Reference: 9 | To avoid the warning message `"ISO C++ forbids converting a string constant to 'char*'"`, 10 | the reference for solutions is from [WIKIBOOKS](https://en.wikibooks.org/wiki/GCC_Debugging/g%2B%2B/Warnings/deprecated_conversion_from_string_constant). 11 | -------------------------------------------------------------------------------- /Chapter09/PE01/Makefile: -------------------------------------------------------------------------------- 1 | PE01: main.o golf.o 2 | g++ -o PE01 main.o golf.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | golf.o: golf.cpp 8 | g++ -c golf.cpp 9 | 10 | clean: 11 | rm *.o PE01 -------------------------------------------------------------------------------- /Chapter09/PE01/golf.cpp: -------------------------------------------------------------------------------- 1 | // golf.cpp -- set values of golf and show golf 2 | #include 3 | #include 4 | #include "golf.h" 5 | 6 | using std::cin; 7 | using std::cout; 8 | using std::endl; 9 | 10 | void setgolf(golf& g, const char* name, int hc) { 11 | strcpy(g.fullname, name); 12 | g.handicap = hc; 13 | } 14 | 15 | int setgolf(golf& g) { 16 | cout << "Enter the name: "; 17 | cin.getline(g.fullname, Len); 18 | if (g.fullname[0] != '\0') { 19 | cout << "Enter the hanicap: "; 20 | cin >> g.handicap; 21 | cin.get(); 22 | return 1; 23 | } 24 | else { 25 | return 0; 26 | } 27 | } 28 | 29 | void hanicap(golf& g, int hc) { 30 | g.handicap = hc; 31 | } 32 | 33 | void showgolf(const golf& g) { 34 | cout << "The name is " << g.fullname << ".\n"; 35 | cout << "The handicap is " << g.handicap << ".\n"; 36 | } -------------------------------------------------------------------------------- /Chapter09/PE01/golf.h: -------------------------------------------------------------------------------- 1 | // golf.h -- for golf.cpp 2 | #ifndef GOLF_H 3 | #define GOLF_H 4 | 5 | const int Len = 40; 6 | const int arrSize = 10; 7 | struct golf { 8 | char fullname[Len]; 9 | int handicap; 10 | }; 11 | 12 | // non-interactive version: 13 | // function sets golf structure to provided name, handicap 14 | // using values passed as arguments to the function 15 | void setgolf(golf& g, const char* name, int hc); 16 | 17 | // interactive version: 18 | // function solicits name and handicap from user 19 | // and sets the members of g to the values entered 20 | // returns 1 if name is entered, 0 if name is empty string 21 | int setgolf(golf& g); 22 | 23 | // function resets handicap to new value 24 | void handicap(golf& g, int hc); 25 | 26 | // function displays contents of golf structure 27 | void showgolf(const golf& g); 28 | 29 | #endif /* GOLF_H */ -------------------------------------------------------------------------------- /Chapter09/PE01/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 9.1 2 | #include 3 | #include "golf.h" 4 | 5 | using std::cout; 6 | using std::endl; 7 | 8 | int main() { 9 | cout << "TEST: non-interactive version:" << endl; 10 | golf ann; 11 | setgolf(ann, "Ann Birdfree", 24); 12 | showgolf(ann); 13 | cout << "===================================" << endl; 14 | 15 | cout << "TEST: interactive version:" << endl; 16 | golf andy; 17 | int showOrNot = setgolf(andy); 18 | if (showOrNot) { 19 | showgolf(andy); 20 | } 21 | cout << "===================================" << endl; 22 | 23 | cout << "TEST: an array of 10 golfs:" << endl; 24 | cout << "Enter information section:" << endl; 25 | golf arr[arrSize]; 26 | int i; 27 | for (i = 0; i < arrSize; ++i) { 28 | if (setgolf(arr[i])) { 29 | continue; 30 | } 31 | else { 32 | break; 33 | } 34 | } 35 | cout << "Show entered information section:" << endl; 36 | for (int j = 0; j < i; ++j) { 37 | showgolf(arr[j]); 38 | } 39 | cout << "===================================" << endl; 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /Chapter09/PE02/Makefile: -------------------------------------------------------------------------------- 1 | PE02: main.o strcount.o 2 | g++ -o PE02 main.o strcount.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | strcount.o: strcount.cpp 8 | g++ -c strcount.cpp 9 | 10 | clean: 11 | rm *.o PE02 -------------------------------------------------------------------------------- /Chapter09/PE02/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 9.2 2 | #include 3 | #include 4 | #include "strcount.h" 5 | 6 | using std::cin; 7 | using std::cout; 8 | using std::getline; 9 | using std::string; 10 | 11 | int main() { 12 | string input; 13 | 14 | cout << "Enter a line:\n"; 15 | while (getline(cin, input) && input != "") { 16 | strcount(input); 17 | cout << "Enter next line (empty line to quit):\n"; 18 | } 19 | cout << "Bye\n"; 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Chapter09/PE02/strcount.cpp: -------------------------------------------------------------------------------- 1 | // strcount.cpp -- count the number of characters 2 | #include 3 | #include 4 | #include "strcount.h" 5 | 6 | using std::cout; 7 | using std::string; 8 | 9 | void strcount(const string str) { 10 | static int total = 0; 11 | int count = 0; 12 | 13 | cout << "\"" << str << "\" contains "; 14 | for (int i = 0; i < str.size(); ++i) { 15 | ++count; 16 | } 17 | total += count; 18 | cout << count << " characters\n"; 19 | cout << total << " characters total\n"; 20 | } -------------------------------------------------------------------------------- /Chapter09/PE02/strcount.h: -------------------------------------------------------------------------------- 1 | // strcount.h -- for strcount.cpp 2 | #ifndef STRCOUNT_H 3 | #define STRCOUNT_H 4 | 5 | #include 6 | #include 7 | 8 | using std::string; 9 | 10 | void strcount(const string str); 11 | 12 | #endif /* STRCOUNT_H */ -------------------------------------------------------------------------------- /Chapter09/PE03/Makefile: -------------------------------------------------------------------------------- 1 | PE03: main.o placementnew.o 2 | g++ -o PE03 main.o placementnew.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | placementnew.o: placementnew.cpp 8 | g++ -c placementnew.cpp 9 | 10 | clean: 11 | rm *.o PE03 -------------------------------------------------------------------------------- /Chapter09/PE03/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 9.3 2 | #include 3 | #include 4 | #include "placementnew.h" 5 | 6 | using std::cin; 7 | using std::cout; 8 | using std::endl; 9 | 10 | const int BUF = 1024; 11 | const int arraySize = 2; 12 | 13 | char buffer[BUF]; 14 | 15 | int main() { 16 | Chaff* ptr; 17 | ptr = new (buffer) Chaff[arraySize]; 18 | 19 | // Showing the address of buffer is the same as the address of ptr 20 | cout << "Memory address:\n" << " buffer: " << (void*)buffer 21 | << "\n ptr: " << ptr << endl; 22 | 23 | setChaff(*ptr, (char*)"Test dross", 3); 24 | setChaff(*(ptr + 1), (char*)"Test dross again", 10); 25 | 26 | cout << "Display Chaff: " << endl; 27 | for (int i = 0; i < arraySize; ++i) { 28 | cout << "The chaff #" << (i + 1) << "'s dross is " 29 | << (ptr + i)->dross << ".\n"; 30 | cout << "The chaff #" << (i + 1) << "'s slag if " 31 | << (ptr + i)->slag << ".\n"; 32 | } 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Chapter09/PE03/placementnew.cpp: -------------------------------------------------------------------------------- 1 | // placement.cpp -- use placement new 2 | #include 3 | #include 4 | #include "placementnew.h" 5 | 6 | void setChaff(Chaff& chaff, char arr[], int n) { 7 | strcpy(chaff.dross, arr); 8 | chaff.slag = n; 9 | } 10 | -------------------------------------------------------------------------------- /Chapter09/PE03/placementnew.h: -------------------------------------------------------------------------------- 1 | // placement.h -- for placement.cpp 2 | #ifndef PLACEMENTNEW_H_ 3 | #define PLACEMENTNEW_H_ 4 | 5 | struct Chaff { 6 | char dross[20]; 7 | int slag; 8 | }; 9 | 10 | void setChaff(Chaff& chaff, char arr[], int n); 11 | 12 | #endif /* PLACEMENTNEW_H_ */ -------------------------------------------------------------------------------- /Chapter09/PE04/Makefile: -------------------------------------------------------------------------------- 1 | PE04: main.o sales.o 2 | g++ -o PE04 main.o sales.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | sales.o: sales.cpp 8 | g++ -c sales.cpp 9 | 10 | clean: 11 | rm *.o PE04 -------------------------------------------------------------------------------- /Chapter09/PE04/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 9.4 2 | #include 3 | #include "sales.h" 4 | 5 | using std::cin; 6 | using std::cout; 7 | using std::endl; 8 | 9 | int main() { 10 | using namespace SALES; 11 | 12 | Sales obj1, obj2; 13 | const double setZeros[] = { 0.0, 0.0, 0.0, 0.0 }; 14 | const double testArr[] = { 100.1, 200.2, 300.3 }; 15 | 16 | // use the interactive version of setSales() 17 | cout << "The interactove version:" << endl; 18 | setSales(obj1); 19 | showSales(obj1); 20 | cout << "===============================" << endl; 21 | 22 | // use the non-interactive version of setSales() 23 | cout << "The non-interactive version:" << endl; 24 | setSales(obj2, setZeros, 4); 25 | setSales(obj2, testArr, 3); 26 | showSales(obj2); 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Chapter09/PE04/sales.cpp: -------------------------------------------------------------------------------- 1 | // sales.cpp -- set and show Sales 2 | #include 3 | #include "sales.h" 4 | 5 | namespace SALES { 6 | using std::cin; 7 | using std::cout; 8 | using std::endl; 9 | 10 | void setSales(Sales& s, const double arr[], int n) { 11 | double sum = 0.0; 12 | s.max = arr[0], s.min = arr[0]; 13 | int size = n > QUARTERS ? QUARTERS : n; 14 | for (int i = 0; i < size; ++i) { 15 | s.sales[i] = arr[i]; 16 | sum += arr[i]; 17 | s.max = s.max > arr[i] ? s.max : arr[i]; 18 | s.min = s.min > arr[i] ? arr[i] : s.min; 19 | } 20 | s.average = sum / double(size); 21 | } 22 | 23 | void setSales(Sales& s) { 24 | double sum = 0.0; 25 | cout << "Please enter 4 sales for each quater:" << endl; 26 | for (int i = 0; i < QUARTERS; ++i) { 27 | cout << "Enter #" << (i + 1) << " sale: "; 28 | cin >> s.sales[i]; 29 | sum += s.sales[i]; 30 | 31 | if (i == 0) { 32 | s.max = s.sales[i]; 33 | s.min = s.sales[i]; 34 | } 35 | else { 36 | s.max = s.max > s.sales[i] ? s.max : s.sales[i]; 37 | s.min = s.min > s.sales[i] ? s.sales[i] : s.min; 38 | } 39 | } 40 | s.average = sum / double(QUARTERS); 41 | } 42 | 43 | void showSales(const Sales& s) { 44 | for (int i = 0; i < QUARTERS; ++i) { 45 | cout << "#" << (i + 1) << " sale is " << s.sales[i] << ".\n"; 46 | } 47 | cout << "The average sale is " << s.average << ".\n"; 48 | cout << "The maximum sale is " << s.max << ".\n"; 49 | cout << "The minimum sale is " << s.min << ".\n"; 50 | } 51 | } -------------------------------------------------------------------------------- /Chapter09/PE04/sales.h: -------------------------------------------------------------------------------- 1 | // sales.h -- for sales.cpp 2 | #ifndef SALES_H 3 | #define SALES_H 4 | 5 | namespace SALES { 6 | const int QUARTERS = 4; 7 | struct Sales { 8 | double sales[QUARTERS]; 9 | double average; 10 | double max; 11 | double min; 12 | }; 13 | 14 | // copies the lesser of 4 or n iterms from the array ar 15 | // to the sales member of s and computers and stores the 16 | // average, maximum, and minimum values of the entered items; 17 | // remaining elements of sales, if any, set to 0 18 | void setSales(Sales& s, const double arr[], int n); 19 | 20 | // gathers sales for 4 quarters interactively, stores them 21 | // in the sales member of s and computers and stores the 22 | // average, maximum, and minimum values 23 | void setSales(Sales& s); 24 | 25 | // display all information in structure s 26 | void showSales(const Sales& s); 27 | } 28 | 29 | #endif /* SALES_H */ -------------------------------------------------------------------------------- /Chapter10/PE01/Makefile: -------------------------------------------------------------------------------- 1 | PE01: main.o bank_account.o 2 | g++ -o PE01 main.o bank_account.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | bank_account.o: bank_account.cpp 8 | g++ -c bank_account.cpp 9 | 10 | clean: 11 | rm *.o PE01 -------------------------------------------------------------------------------- /Chapter10/PE01/bank_account.cpp: -------------------------------------------------------------------------------- 1 | // bank_account.cpp -- implementing the BankAccount class 2 | #include 3 | #include "bank_account.h" 4 | 5 | BankAccount::BankAccount() { 6 | depositorName_ = "no name"; 7 | accountNum_ = "none"; 8 | balance_ = 0.0; 9 | } 10 | 11 | BankAccount::BankAccount(const string& depositorName, 12 | const string& accountNum, 13 | double balance) { 14 | depositorName_ = depositorName; 15 | accountNum_ = accountNum; 16 | balance_ = balance; 17 | } 18 | 19 | BankAccount::~BankAccount() {} 20 | 21 | void BankAccount::showBankAccount() const { 22 | using std::cout; 23 | using std::ios_base; 24 | cout.setf(ios_base::fixed, ios_base::floatfield); 25 | cout.precision(2); 26 | 27 | cout << "Show details:\n"; 28 | cout << "\tThe depositor's name is " << depositorName_ << ".\n"; 29 | cout << "\tHis/her account number is " << accountNum_ << ".\n"; 30 | cout << "\tHis/her account balance is " << balance_ << ".\n"; 31 | cout << "==============================================\n"; 32 | } 33 | 34 | void BankAccount::deposite(const double& amount) { 35 | balance_ += amount; 36 | } 37 | 38 | void BankAccount::withdraw(const double& amount) { 39 | if (balance_ >= amount) { 40 | balance_ -= amount; 41 | } 42 | else { 43 | std::cout << "The amount is not valid, because the amount is larger " 44 | << "than the account balance.\n"; 45 | } 46 | } -------------------------------------------------------------------------------- /Chapter10/PE01/bank_account.h: -------------------------------------------------------------------------------- 1 | // bank_account.h -- BankAccount interface 2 | #ifndef BANK_ACCOUNT_H 3 | #define BANK_ACCOUNT_H 4 | 5 | #include 6 | #include 7 | 8 | using std::string; 9 | 10 | class BankAccount { 11 | private: 12 | string depositorName_; 13 | string accountNum_; 14 | double balance_; 15 | public: 16 | BankAccount(); 17 | BankAccount(const string& depositorName, 18 | const string& accountNum, 19 | double balance); 20 | ~BankAccount(); 21 | void showBankAccount() const; 22 | void deposite(const double& amount); 23 | void withdraw(const double& amount); 24 | }; 25 | 26 | #endif /* BANK_ACCOUNT_H */ -------------------------------------------------------------------------------- /Chapter10/PE01/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 10.1 2 | #include 3 | #include "bank_account.h" 4 | 5 | 6 | int main() { 7 | BankAccount obj1, obj2("Adam Yu Wen", "12345678", 999999); 8 | obj1.showBankAccount(); 9 | obj2.showBankAccount(); 10 | 11 | obj2.deposite(1); 12 | obj2.showBankAccount(); 13 | 14 | obj2.withdraw(1000001); 15 | obj2.showBankAccount(); 16 | 17 | obj2.withdraw(50000); 18 | obj2.showBankAccount(); 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Chapter10/PE02/Makefile: -------------------------------------------------------------------------------- 1 | PE02: main.o person.o 2 | g++ -o PE02 main.o person.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | person.o: person.cpp 8 | g++ -c person.cpp 9 | 10 | clean: 11 | rm *.o PE02 -------------------------------------------------------------------------------- /Chapter10/PE02/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 10.2 2 | #include 3 | #include "person.h" 4 | 5 | int main() { 6 | using std::cout; 7 | using std::endl; 8 | 9 | Person one; 10 | Person two("Smythecraft"); 11 | Person three("Dimwiddy", "Sam"); 12 | 13 | cout << "Person one:" << endl; 14 | one.Show(); 15 | one.FormalShow(); 16 | cout << endl; 17 | 18 | cout << "Person two:" << endl; 19 | two.Show(); 20 | two.FormalShow(); 21 | cout << endl; 22 | 23 | cout << "Person three:" << endl; 24 | three.Show(); 25 | three.FormalShow(); 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /Chapter10/PE02/person.cpp: -------------------------------------------------------------------------------- 1 | // person.cpp -- implementing the Person class 2 | #include 3 | #include 4 | #include 5 | #include "person.h" 6 | 7 | Person::Person(const std::string& ln, const char* fn) { 8 | lname = ln; 9 | strcpy(fname, fn); 10 | } 11 | 12 | void Person::Show() const { 13 | std::cout << fname << " " << lname << std::endl; 14 | } 15 | 16 | void Person::FormalShow() const { 17 | std::cout << lname << ", " << fname << std::endl; 18 | } -------------------------------------------------------------------------------- /Chapter10/PE02/person.h: -------------------------------------------------------------------------------- 1 | // person.h -- Person interface 2 | #ifndef PERSON_H 3 | #define PERSON_H 4 | 5 | #include 6 | 7 | class Person { 8 | private: 9 | static const int LIMIT = 25; 10 | std::string lname; 11 | char fname[LIMIT]; 12 | public: 13 | Person() { lname = ""; fname[0] = '\0'; } 14 | Person(const std::string& ln, const char* fn = "Heyyou"); 15 | void Show() const; 16 | void FormalShow() const; 17 | }; 18 | 19 | #endif /* PERSON_H */ -------------------------------------------------------------------------------- /Chapter10/PE03/Makefile: -------------------------------------------------------------------------------- 1 | PE03: main.o golf.o 2 | g++ -o PE03 main.o golf.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | golf.o: golf.cpp 8 | g++ -c golf.cpp 9 | 10 | clean: 11 | rm *.o PE03 -------------------------------------------------------------------------------- /Chapter10/PE03/golf.cpp: -------------------------------------------------------------------------------- 1 | // golf.cpp -- implementing the Golf class 2 | #include 3 | #include 4 | #include "golf.h" 5 | 6 | Golf::Golf() { 7 | strcpy(fullname, "no name"); 8 | handicap = 0; 9 | } 10 | 11 | Golf::Golf(const char* name, int hc) { 12 | strcpy(fullname, name); 13 | handicap = hc; 14 | } 15 | 16 | Golf::~Golf() {} 17 | 18 | int Golf::setgolf() { 19 | using std::cin; 20 | using std::cout; 21 | 22 | Golf g; 23 | 24 | cout << "Enter the name: "; 25 | cin.getline(g.fullname, Len); 26 | if (g.fullname[0] != '\0') { 27 | cout << "Enter the hanicap: "; 28 | cin >> g.handicap; 29 | cin.get(); 30 | *this = g; 31 | return 1; 32 | } 33 | else { 34 | return 0; 35 | } 36 | } 37 | 38 | void Golf::sethandicap(const int& hc) { 39 | handicap = hc; 40 | } 41 | 42 | void Golf::showgolf() const { 43 | std::cout << "The name is " << fullname << ".\n"; 44 | std::cout << "The handicap is " << handicap << ".\n"; 45 | } -------------------------------------------------------------------------------- /Chapter10/PE03/golf.h: -------------------------------------------------------------------------------- 1 | // golf.h -- Golf interface 2 | #ifndef GOLF_H 3 | #define GOLF_H 4 | 5 | const int arrSize = 10; 6 | 7 | class Golf { 8 | private: 9 | static const int Len = 40; 10 | char fullname[Len]; 11 | int handicap; 12 | public: 13 | Golf(); 14 | Golf(const char* name, int hc); 15 | ~Golf(); 16 | 17 | // interactive version: 18 | // function solicits name and handicap from user 19 | // and sets the members of g to the values entered 20 | // returns 1 if name is entered, 0 if name is empty string 21 | int setgolf(); 22 | 23 | // function resets handicap to new value 24 | void sethandicap(const int& hc); 25 | 26 | // function displays contents of golf structure 27 | void showgolf() const; 28 | }; 29 | 30 | #endif /* GOLF_H */ -------------------------------------------------------------------------------- /Chapter10/PE03/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 10.3 2 | #include 3 | #include "golf.h" 4 | 5 | int main() { 6 | using std::cout; 7 | using std::endl; 8 | 9 | cout << "TEST: non-interactive version (constructor):" << endl; 10 | Golf ann("Ann Birdfree", 24); 11 | ann.showgolf(); 12 | ann.sethandicap(36); 13 | ann.showgolf(); 14 | cout << "===================================" << endl; 15 | 16 | cout << "TEST: interactive version:" << endl; 17 | Golf andy; 18 | int showOrNot = andy.setgolf(); 19 | if (showOrNot) { 20 | andy.showgolf(); 21 | } 22 | cout << "===================================" << endl; 23 | 24 | cout << "TEST: an array of 10 golfs:" << endl; 25 | cout << "Enter information section:" << endl; 26 | Golf arr[arrSize]; 27 | int i; 28 | for (i = 0; i < arrSize; ++i) { 29 | if (arr[i].setgolf()) { 30 | continue; 31 | } 32 | else { 33 | break; 34 | } 35 | } 36 | cout << "Show entered information section:" << endl; 37 | for (int j = 0; j < i; ++j) { 38 | arr[j].showgolf(); 39 | } 40 | cout << "===================================" << endl; 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /Chapter10/PE04/Makefile: -------------------------------------------------------------------------------- 1 | PE04: main.o sales.o 2 | g++ -o PE04 main.o sales.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | sales.o: sales.cpp 8 | g++ -c sales.cpp 9 | 10 | clean: 11 | rm *.o PE04 -------------------------------------------------------------------------------- /Chapter10/PE04/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 9.4 2 | #include 3 | #include "sales.h" 4 | 5 | using std::cin; 6 | using std::cout; 7 | using std::endl; 8 | 9 | int main() { 10 | using namespace SALES; 11 | 12 | const double testArr[] = { 100.1, 200.2, 300.3 }; 13 | Sales obj1, obj2(testArr, 3); 14 | 15 | // use the non-interactive version of setSales() 16 | cout << "The non-interactive version:" << endl; 17 | cout << " Default constructor:" << endl; 18 | obj1.showSales(); 19 | cout << " Constructor:" << endl; 20 | obj2.showSales(); 21 | cout << "===============================" << endl; 22 | 23 | // use the interactive version of setSales() 24 | cout << "The interactove version:" << endl; 25 | obj1.setSales(); 26 | obj1.showSales(); 27 | 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Chapter10/PE04/sales.cpp: -------------------------------------------------------------------------------- 1 | // sales.cpp -- implementing the Sales class 2 | #include 3 | #include "sales.h" 4 | 5 | namespace SALES { 6 | Sales::Sales() { 7 | sales[0] = sales[1] = sales[2] = sales[3] = 0.0; 8 | average = max = min = 0.0; 9 | } 10 | 11 | Sales::Sales(const double arr[], int n) { 12 | for (int i = 0; i < QUARTERS; ++i) { 13 | sales[i] = 0.0; 14 | } 15 | 16 | double sum = 0.0; 17 | max = arr[0], min = arr[0]; 18 | int size = n > QUARTERS ? QUARTERS : n; 19 | for (int i = 0; i < size; ++i) { 20 | sales[i] = arr[i]; 21 | sum += arr[i]; 22 | max = max > arr[i] ? max : arr[i]; 23 | min = min > arr[i] ? arr[i] : min; 24 | } 25 | average = sum / double(size); 26 | } 27 | 28 | Sales::~Sales() {} 29 | 30 | void Sales::setSales() { 31 | using std::cin; 32 | using std::cout; 33 | using std::endl; 34 | 35 | double temp[QUARTERS]; 36 | 37 | double sum = 0.0; 38 | cout << "Please enter 4 sales for each quater:" << endl; 39 | for (int i = 0; i < QUARTERS; ++i) { 40 | cout << "Enter #" << (i + 1) << " sale: "; 41 | cin >> temp[i]; 42 | } 43 | *this = Sales(temp, QUARTERS); 44 | } 45 | 46 | void Sales::showSales() const { 47 | using std::cout; 48 | 49 | for (int i = 0; i < QUARTERS; ++i) { 50 | cout << "#" << (i + 1) << " sale is " << sales[i] << ".\n"; 51 | } 52 | cout << "The average sale is " << average << ".\n"; 53 | cout << "The maximum sale is " << max << ".\n"; 54 | cout << "The minimum sale is " << min << ".\n"; 55 | } 56 | } -------------------------------------------------------------------------------- /Chapter10/PE04/sales.h: -------------------------------------------------------------------------------- 1 | // sales.h -- Sales interface 2 | #ifndef SALES_H 3 | #define SALES_H 4 | 5 | namespace SALES { 6 | class Sales { 7 | private: 8 | enum {QUARTERS = 4}; 9 | double sales[QUARTERS]; 10 | double average; 11 | double max; 12 | double min; 13 | public: 14 | Sales(); 15 | // copies the lesser of 4 or n iterms from the array ar 16 | // to the sales member of s and computers and stores the 17 | // average, maximum, and minimum values of the entered items; 18 | // remaining elements of sales, if any, set to 0 19 | Sales(const double arr[], int n); 20 | ~Sales(); 21 | 22 | // gathers sales for 4 quarters interactively, stores them 23 | // in the sales member of s and computers and stores the 24 | // average, maximum, and minimum values 25 | void setSales(); 26 | 27 | // display all information in structure s 28 | void showSales() const; 29 | }; 30 | } 31 | 32 | #endif /* SALES_H */ -------------------------------------------------------------------------------- /Chapter10/PE05/Makefile: -------------------------------------------------------------------------------- 1 | PE05: main.o stack.o 2 | g++ -o PE05 main.o stack.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | stack.o: stack.cpp 8 | g++ -c stack.cpp 9 | 10 | clean: 11 | rm *.o PE05 -------------------------------------------------------------------------------- /Chapter10/PE05/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 10.5 2 | // stacker.cpp -- testing the Stack class 3 | #include 4 | #include // or ctype.h 5 | #include "stack.h" 6 | 7 | int main() { 8 | using namespace std; 9 | 10 | Stack st; // create an empty stack 11 | char ch; 12 | customer c; 13 | double total = 0.0; 14 | 15 | cout << "Please enter A to add a customer,\n" 16 | << "P to remove a customer, or Q to quit.\n"; 17 | while (cin >> ch && toupper(ch) != 'Q') { 18 | while (cin.get() != '\n') { 19 | continue; 20 | } 21 | if (!isalpha(ch)) { 22 | cout << '\a'; 23 | continue; 24 | } 25 | switch(ch) { 26 | case 'A': 27 | case 'a': 28 | cout << "Enter a customer's fullname: "; 29 | cin.getline(c.fullname, 35); 30 | cout << "Enter the customer's payment: "; 31 | (cin >> c.payment).get(); 32 | if (st.isfull()) { 33 | cout << "stack already full\n"; 34 | } 35 | else { 36 | st.push(c); 37 | } 38 | break; 39 | case 'P': 40 | case 'p': 41 | if (st.isempty()) { 42 | cout << "stack already empty\n"; 43 | } 44 | else { 45 | st.pop(c); 46 | cout << "Customer " << c.fullname << " popped\n"; 47 | total += c.payment; 48 | } 49 | break; 50 | } 51 | cout << "The total payment is " << total << endl; 52 | cout << "Please enter A to add a customer,\n" 53 | << "P to remove a customer, or Q to quit.\n"; 54 | } 55 | cout << "Bye\n"; 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /Chapter10/PE05/stack.cpp: -------------------------------------------------------------------------------- 1 | // stack.cpp -- Stack member functions 2 | #include "stack.h" 3 | 4 | Stack::Stack() { 5 | top = 0; 6 | } 7 | 8 | bool Stack::isempty() const { 9 | return top == 0; 10 | } 11 | 12 | bool Stack::isfull() const { 13 | return top == MAX; 14 | } 15 | 16 | bool Stack::push(const Item & item) { 17 | if (top < MAX) { 18 | items[top++] = item; 19 | return true; 20 | } 21 | else { 22 | return false; 23 | } 24 | } 25 | 26 | bool Stack::pop(Item & item) { 27 | if (top > 0) { 28 | item = items[--top]; 29 | return true; 30 | } 31 | else { 32 | return false; 33 | } 34 | } -------------------------------------------------------------------------------- /Chapter10/PE05/stack.h: -------------------------------------------------------------------------------- 1 | // stack.h -- class definition for the stack ADT 2 | #ifndef STACK_H 3 | #define STACK_H 4 | 5 | struct customer { 6 | char fullname[35]; 7 | double payment; 8 | }; 9 | 10 | typedef customer Item; 11 | 12 | class Stack { 13 | private: 14 | enum { MAX = 10 }; // constant specific to class 15 | Item items[MAX]; // holds stack items 16 | int top; // index for top stack item 17 | public: 18 | Stack(); 19 | bool isempty() const; 20 | bool isfull() const; 21 | // push() returns false if stack already is full, true otherwise 22 | bool push(const Item & item); // add item to stack 23 | // pop() returns false if stack already is empty, true otherwise 24 | bool pop(Item & item); // pop top into item 25 | }; 26 | 27 | #endif /* STACK_H */ -------------------------------------------------------------------------------- /Chapter10/PE06/Makefile: -------------------------------------------------------------------------------- 1 | PE06: main.o move.o 2 | g++ -o PE06 main.o move.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | move.o: move.cpp 8 | g++ -c move.cpp 9 | 10 | clean: 11 | rm *.o PE06 -------------------------------------------------------------------------------- /Chapter10/PE06/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 10.6 2 | #include 3 | #include "move.h" 4 | 5 | int main() { 6 | using std::cout; 7 | using std::endl; 8 | 9 | cout << "Create a object #1:" << endl; 10 | Move obj1; 11 | obj1.showmove(); 12 | 13 | cout << "Create a object #2:" << endl; 14 | Move obj2(3, 4); 15 | obj2.showmove(); 16 | 17 | cout << "Added object #2 to object #1:" << endl; 18 | obj1 = obj1.add(obj2); 19 | obj1.showmove(); 20 | 21 | cout << "Reset object #1:" << endl; 22 | obj1.reset(); 23 | obj1.showmove(); 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Chapter10/PE06/move.cpp: -------------------------------------------------------------------------------- 1 | // move.cpp -- impletmenting the Move class 2 | #include 3 | #include "move.h" 4 | 5 | Move::Move(double a, double b) { 6 | x = a; 7 | y = b; 8 | } 9 | 10 | void Move::showmove() const { 11 | std::cout << "The move to x = " << x << ", y = " << y << std::endl; 12 | } 13 | 14 | Move Move::add(const Move& m) const { 15 | Move res; 16 | res.x += m.x; 17 | res.y += m.y; 18 | return res; 19 | } 20 | 21 | void Move::reset(double a, double b) { 22 | x = a; 23 | y = b; 24 | } -------------------------------------------------------------------------------- /Chapter10/PE06/move.h: -------------------------------------------------------------------------------- 1 | // move.h -- Move interface 2 | #ifndef MOVE_H 3 | #define MOVE_H 4 | 5 | class Move { 6 | private: 7 | double x; 8 | double y; 9 | public: 10 | Move(double a = 0, double b = 0); // sets x, y to a, b 11 | void showmove() const; // shows current x, y values 12 | Move add(const Move& m) const; 13 | // this function adds x of m to x of invoking object to get new x, 14 | // adds y of m to y of invoking object to get new y, creates a new 15 | // move object initialzed to new x, y values and returns it 16 | void reset(double a = 0, double b = 0); // resets x, y to a, b 17 | }; 18 | 19 | #endif /* MOVE_H */ -------------------------------------------------------------------------------- /Chapter10/PE07/Makefile: -------------------------------------------------------------------------------- 1 | PE07: main.o plorg.o 2 | g++ -o PE07 main.o plorg.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | plorg.o: plorg.cpp 8 | g++ -c plorg.cpp 9 | 10 | clean: 11 | rm *.o PE07 -------------------------------------------------------------------------------- /Chapter10/PE07/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 10.7 2 | #include 3 | #include "plorg.h" 4 | 5 | int main() { 6 | using std::cout; 7 | using std::endl; 8 | 9 | cout << "Create a plorg by using default constructor:" << endl; 10 | Plorg org1; 11 | org1.showPlorg(); 12 | 13 | cout << endl << "Create a plorg by using constructor:" << endl; 14 | Plorg org2("testing"); 15 | org2.showPlorg(); 16 | Plorg org3("testing", 30); 17 | org3.showPlorg(); 18 | 19 | cout << endl << "Reset the CI:" << endl; 20 | org3.setCI(20); 21 | org3.showPlorg(); 22 | 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /Chapter10/PE07/plorg.cpp: -------------------------------------------------------------------------------- 1 | // plorg.cpp -- implementing the Plorg class 2 | #include 3 | #include 4 | #include "plorg.h" 5 | 6 | Plorg::Plorg() { 7 | strcpy(name_, "Plorga"); 8 | ci_ = 0; 9 | } 10 | 11 | Plorg::Plorg(const char* name, int ci) { 12 | strcpy(name_, name); 13 | ci_ = ci; 14 | } 15 | 16 | Plorg::~Plorg() {} 17 | 18 | void Plorg::setCI(const int& ci) { 19 | ci_ = ci; 20 | } 21 | 22 | void Plorg::showPlorg() const { 23 | std::cout << "The plorg's name is " << name_ 24 | << " and its contentment index is " << ci_ << ".\n"; 25 | } 26 | -------------------------------------------------------------------------------- /Chapter10/PE07/plorg.h: -------------------------------------------------------------------------------- 1 | // plorg.h -- Plorg interface 2 | #ifndef PLORG_H 3 | #define PLORG_H 4 | 5 | class Plorg { 6 | private: 7 | static const int nameSize = 19; 8 | char name_[nameSize]; 9 | int ci_; 10 | public: 11 | Plorg(); 12 | Plorg(const char* name, int ci = 50); 13 | ~Plorg(); 14 | 15 | void setCI(const int& ci); 16 | void showPlorg() const; 17 | }; 18 | 19 | #endif /* PLORG_H */ -------------------------------------------------------------------------------- /Chapter10/PE08/Makefile: -------------------------------------------------------------------------------- 1 | PE08: main.o list.o 2 | g++ -o PE08 main.o list.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | list.o: list.cpp 8 | g++ -c list.cpp 9 | 10 | clean: 11 | rm *.o PE08 -------------------------------------------------------------------------------- /Chapter10/PE08/list.cpp: -------------------------------------------------------------------------------- 1 | // list.cpp -- impletmenting the List class 2 | #include 3 | #include "list.h" 4 | 5 | List::List() { 6 | listSize_ = 0; 7 | } 8 | 9 | List::List(Item* list, int listSize) { 10 | if (listSize <= maxListSize) { 11 | listSize_ = listSize; 12 | for (int i = 0; i < listSize; ++i) { 13 | list_[i] = list[i]; 14 | } 15 | } 16 | else { 17 | std::cout << "Invalid input. The list size is larger than " 18 | << maxListSize << ".\n"; 19 | } 20 | } 21 | 22 | List::~List() {} 23 | 24 | void List::add(const Item& node) { 25 | if (isfull()) { 26 | std::cout << "Can NOT add any more." << std::endl; 27 | } 28 | else { 29 | ++listSize_; 30 | list_[listSize_ - 1] = node; 31 | } 32 | } 33 | 34 | bool List::isempty() const { 35 | if (listSize_ == 0) { 36 | std::cout << "The list is empty." << std::endl; 37 | return true; 38 | } 39 | else { 40 | std::cout << "The list is NOT empty." << std::endl; 41 | return false; 42 | 43 | } 44 | } 45 | 46 | bool List::isfull() const { 47 | if (listSize_ == maxListSize) { 48 | std::cout << "The list is full." << std::endl; 49 | return true; 50 | } 51 | else { 52 | std::cout << "The list is NOT full." << std::endl; 53 | return false; 54 | } 55 | } 56 | 57 | void List::showList() const { 58 | using std::cout; 59 | 60 | cout << "The list has " << listSize_ << " elements.\n" 61 | << "They are"; 62 | for (int i = 0; i < listSize_; ++i) { 63 | cout << " " << list_[i]; 64 | } 65 | cout << ".\n"; 66 | } 67 | 68 | void List::visit(void (*pf)(Item& node)) { 69 | for (int i = 0; i < listSize_; ++i) { 70 | (*pf)(list_[i]); 71 | } 72 | } 73 | 74 | void addone(Item& node) { 75 | node += 1; 76 | } -------------------------------------------------------------------------------- /Chapter10/PE08/list.h: -------------------------------------------------------------------------------- 1 | // list.h -- List interface 2 | #ifndef LIST_H 3 | #define LIST_H 4 | 5 | typedef int Item; 6 | 7 | class List { 8 | private: 9 | static const int maxListSize = 5; 10 | Item list_[maxListSize]; 11 | int listSize_; 12 | public: 13 | List(); 14 | List(Item* list, int listSize); 15 | ~List(); 16 | 17 | void add(const Item& node); 18 | bool isempty() const; 19 | bool isfull() const; 20 | void showList() const; 21 | void visit(void (*pf)(Item& node)); 22 | }; 23 | 24 | void addone(Item& node); 25 | 26 | #endif /* LIST_H */ -------------------------------------------------------------------------------- /Chapter10/PE08/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 10.8 2 | #include 3 | #include "list.h" 4 | 5 | int main() { 6 | using std::cout; 7 | using std::endl; 8 | 9 | cout << "Create a list by using default constructor:" << endl; 10 | List org1; 11 | org1.showList(); 12 | cout << "Is it empty?" << endl; 13 | org1.isempty(); 14 | 15 | cout << endl << "Create a list by using constructor:" << endl; 16 | cout << " 1st time:\n"; 17 | Item temp1[6] = { 1, 2, 3, 4, 5, 6 }; 18 | List org2(temp1, 6); 19 | cout << " 2nd time:\n"; 20 | Item temp2[4] = { 10, 20, 30, 40 }; 21 | List org3(temp2, 4); 22 | org3.showList(); 23 | cout << "Is it empty?" << endl; 24 | org3.isempty(); 25 | 26 | cout << endl << "Add a node to the list:" << endl; 27 | org3.add(50); 28 | org3.showList(); 29 | org3.add(60); 30 | org3.showList(); 31 | 32 | cout << endl << "Visit a node:" << endl; 33 | org3.visit(addone); 34 | org3.showList(); 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Chapter11/PE01/Makefile: -------------------------------------------------------------------------------- 1 | PE01: main.o vector.o 2 | g++ -o PE01 main.o vector.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | vector.o: vector.cpp 8 | g++ -c vector.cpp 9 | 10 | clean: 11 | rm *.o PE01 -------------------------------------------------------------------------------- /Chapter11/PE01/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 11.1 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include "vector.h" 7 | 8 | int main() { 9 | using std::cin; 10 | using std::cout; 11 | using std::endl; 12 | using std::ofstream; 13 | using vector::Vector; 14 | 15 | ofstream fout; 16 | fout.open("PE01.txt"); 17 | 18 | srand(time(0)); 19 | double direction, target, dstep; 20 | Vector step, result(0.0, 0.0); 21 | unsigned long steps = 0; 22 | 23 | cout << "Enter target distance (q to quit): "; 24 | while (cin >> target) { 25 | cout << "Enter step length: "; 26 | if (!(cin >> dstep)) { 27 | break; 28 | } 29 | 30 | fout << "Target Distance: " << target << ", " 31 | << "Step Size: " << dstep << endl; 32 | fout << steps << ": " << result << endl; 33 | while (result.mag() < target) { 34 | direction = rand() % 360; 35 | step.reset(dstep, direction, Vector::POL); 36 | result = result + step; 37 | ++steps; 38 | fout << steps << ": " << result << endl; 39 | } 40 | fout << "After " << steps << " steps, the subject " 41 | << "has the following location:\n"; 42 | fout << result << endl; 43 | result.polar_mode(); 44 | fout << " or\n" << result << endl; 45 | 46 | fout << "Average outward distance per step = " 47 | << result.mag() / steps << endl; 48 | fout << "=====================================================\n"; 49 | 50 | cout << "After " << steps << " steps, the subject " 51 | << "has the following location:\n"; 52 | cout << result << endl; 53 | result.polar_mode(); 54 | cout << " or\n" << result << endl; 55 | 56 | cout << "Average outward distance per step = " 57 | << result.mag() / steps << endl; 58 | cout << "=====================================================\n"; 59 | 60 | steps = 0; 61 | result.reset(0.0, 0.0); 62 | cout << "Enter target distance (q to quit): "; 63 | } 64 | 65 | fout.close(); 66 | cout << "Bye!\n"; 67 | 68 | cin.clear(); 69 | while (cin.get() != '\n') { 70 | continue; 71 | } 72 | 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /Chapter11/PE01/vector.h: -------------------------------------------------------------------------------- 1 | // vector.h -- Vector class 2 | #ifndef VECTOR_H_ 3 | #define VECTOR_H_ 4 | 5 | #include 6 | 7 | namespace vector { 8 | class Vector { 9 | public: 10 | // RECT for rectangular, POL for Polar modes 11 | enum Mode { RECT, POL }; 12 | 13 | Vector(); 14 | Vector(double n1, double n2, Mode form = RECT); 15 | void reset(double n1, double n2, Mode form = RECT); 16 | ~Vector(); 17 | 18 | double x() const { return x_; } // report x values 19 | double y() const { return y_; } // report y values 20 | double mag() const { return mag_; } // report magnitude 21 | double ang() const { return ang_; } // report angle 22 | 23 | void polar_mode(); // set model to POL 24 | void rect_mode(); // set model to RECT 25 | 26 | Vector operator+(const Vector& b) const; 27 | Vector operator-(const Vector& b) const; 28 | Vector operator-() const; 29 | Vector operator*(double n) const; 30 | friend Vector operator*(double n, const Vector& a); 31 | friend std::ostream& operator<<(std::ostream& os, const Vector& v); 32 | 33 | private: 34 | double x_; // horizontal value 35 | double y_; // vertical value 36 | double mag_; // length of vector 37 | double ang_; // direction of vector in degrees 38 | Mode mode_; // RECT or POL 39 | 40 | void set_x(); 41 | void set_y(); 42 | void set_mag(); 43 | void set_ang(); 44 | }; 45 | } // namespace vector 46 | 47 | #endif // VECTOR_H_ -------------------------------------------------------------------------------- /Chapter11/PE02/Makefile: -------------------------------------------------------------------------------- 1 | PE02: main.o vector.o 2 | g++ -o PE02 main.o vector.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | vector.o: vector.cpp 8 | g++ -c vector.cpp 9 | 10 | clean: 11 | rm *.o PE02 -------------------------------------------------------------------------------- /Chapter11/PE02/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 11.2 2 | #include 3 | #include 4 | #include 5 | #include "vector.h" 6 | 7 | int main() { 8 | using std::cin; 9 | using std::cout; 10 | using std::endl; 11 | using vector::Vector; 12 | 13 | srand(time(0)); 14 | double direction, target, dstep; 15 | Vector step, result(0.0, 0.0); 16 | unsigned long steps = 0; 17 | 18 | cout << "Enter target distance (q to quit): "; 19 | while (cin >> target) { 20 | cout << "Enter step length: "; 21 | if (!(cin >> dstep)) { 22 | break; 23 | } 24 | 25 | while (result.set_mag() < target) { 26 | direction = rand() % 360; 27 | step.reset(dstep, direction, Vector::POL); 28 | result = result + step; 29 | ++steps; 30 | } 31 | 32 | cout << "After " << steps << " steps, the subject " 33 | << "has the following location:\n"; 34 | cout << result << endl; 35 | result.polar_mode(); 36 | cout << " or\n" << result << endl; 37 | 38 | cout << "Average outward distance per step = " 39 | << result.set_mag() / steps << endl; 40 | cout << "=====================================================\n"; 41 | 42 | steps = 0; 43 | result.reset(0.0, 0.0); 44 | cout << "Enter target distance (q to quit): "; 45 | } 46 | 47 | cout << "Bye!\n"; 48 | 49 | cin.clear(); 50 | while (cin.get() != '\n') { 51 | continue; 52 | } 53 | 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /Chapter11/PE02/vector.h: -------------------------------------------------------------------------------- 1 | // vector.h -- Vector class 2 | #ifndef VECTOR_H_ 3 | #define VECTOR_H_ 4 | 5 | #include 6 | 7 | namespace vector { 8 | class Vector { 9 | public: 10 | // RECT for rectangular, POL for Polar modes 11 | enum Mode { RECT, POL }; 12 | 13 | Vector(); 14 | Vector(double n1, double n2, Mode form = RECT); 15 | void reset(double n1, double n2, Mode form = RECT); 16 | ~Vector(); 17 | 18 | double x() const { return x_; } // report x values 19 | double y() const { return y_; } // report y values 20 | double set_mag() const; // set the length of vector 21 | double set_ang() const; // set the direction of vector in degrees 22 | 23 | void polar_mode(); // set model to POL 24 | void rect_mode(); // set model to RECT 25 | 26 | Vector operator+(const Vector& b) const; 27 | Vector operator-(const Vector& b) const; 28 | Vector operator-() const; 29 | Vector operator*(double n) const; 30 | friend Vector operator*(double n, const Vector& a); 31 | friend std::ostream& operator<<(std::ostream& os, const Vector& v); 32 | 33 | private: 34 | double x_; // horizontal value 35 | double y_; // vertical value 36 | Mode mode_; // RECT or POL 37 | 38 | void set_x(const double& mag, const double& ang); 39 | void set_y(const double& mag, const double& ang); 40 | 41 | }; 42 | } // namespace vector 43 | 44 | #endif // VECTOR_H_ -------------------------------------------------------------------------------- /Chapter11/PE03/Makefile: -------------------------------------------------------------------------------- 1 | PE03: main.o vector.o 2 | g++ -o PE03 main.o vector.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | vector.o: vector.cpp 8 | g++ -c vector.cpp 9 | 10 | clean: 11 | rm *.o PE03 -------------------------------------------------------------------------------- /Chapter11/PE03/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 11.3 2 | #include 3 | #include 4 | #include 5 | #include "vector.h" 6 | 7 | int main() { 8 | using std::cin; 9 | using std::cout; 10 | using std::endl; 11 | using vector::Vector; 12 | 13 | srand(time(0)); 14 | int N; 15 | double direction, target = 50.0, dstep = 2.0; 16 | Vector step, result(0.0, 0.0); 17 | unsigned long steps = 0, highest, lowest, sum; 18 | 19 | cout << "Enter the number of trails: "; 20 | cin >> N; 21 | 22 | for (int i = 0; i < N; ++i) { 23 | while (result.mag() < target) { 24 | direction = rand() % 360; 25 | step.reset(dstep, direction, Vector::POL); 26 | result = result + step; 27 | ++steps; 28 | } 29 | 30 | cout << "After " << steps << " steps, the subject " 31 | << "has the following location:\n"; 32 | cout << result << endl; 33 | result.polar_mode(); 34 | cout << "========================================================\n"; 35 | 36 | if (i == 0) { 37 | highest = steps; 38 | lowest = steps; 39 | } else { 40 | highest = highest > steps ? highest : steps; 41 | lowest = lowest < steps ? lowest : steps; 42 | } 43 | sum += steps; 44 | 45 | steps = 0; 46 | result.reset(0.0, 0.0); 47 | } 48 | cout << "The highest number of step for N trails is " << highest << ".\n"; 49 | cout << "The lowest number of step for N trails is " << lowest << ".\n"; 50 | cout << "The average number of step for N trails is " 51 | << sum / (double)N << ".\n"; 52 | 53 | cout << "Bye!\n"; 54 | 55 | cin.clear(); 56 | while (cin.get() != '\n') { 57 | continue; 58 | } 59 | 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /Chapter11/PE03/vector.h: -------------------------------------------------------------------------------- 1 | // vector.h -- Vector class 2 | #ifndef VECTOR_H_ 3 | #define VECTOR_H_ 4 | 5 | #include 6 | 7 | namespace vector { 8 | class Vector { 9 | public: 10 | // RECT for rectangular, POL for Polar modes 11 | enum Mode { RECT, POL }; 12 | 13 | Vector(); 14 | Vector(double n1, double n2, Mode form = RECT); 15 | void reset(double n1, double n2, Mode form = RECT); 16 | ~Vector(); 17 | 18 | double x() const { return x_; } // report x values 19 | double y() const { return y_; } // report y values 20 | double mag() const { return mag_; } // report magnitude 21 | double ang() const { return ang_; } // report angle 22 | 23 | void polar_mode(); // set model to POL 24 | void rect_mode(); // set model to RECT 25 | 26 | Vector operator+(const Vector& b) const; 27 | Vector operator-(const Vector& b) const; 28 | Vector operator-() const; 29 | Vector operator*(double n) const; 30 | friend Vector operator*(double n, const Vector& a); 31 | friend std::ostream& operator<<(std::ostream& os, const Vector& v); 32 | 33 | private: 34 | double x_; // horizontal value 35 | double y_; // vertical value 36 | double mag_; // length of vector 37 | double ang_; // direction of vector in degrees 38 | Mode mode_; // RECT or POL 39 | 40 | void set_x(); 41 | void set_y(); 42 | void set_mag(); 43 | void set_ang(); 44 | }; 45 | } // namespace vector 46 | 47 | #endif // VECTOR_H_ -------------------------------------------------------------------------------- /Chapter11/PE04/Makefile: -------------------------------------------------------------------------------- 1 | PE04: main.o mytime.o 2 | g++ -o PE04 main.o mytime.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | mytime.o: mytime.cpp 8 | g++ -c mytime.cpp 9 | 10 | clean: 11 | rm *.o PE04 -------------------------------------------------------------------------------- /Chapter11/PE04/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 11.4 2 | #include 3 | #include "mytime.h" 4 | 5 | int main() { 6 | using std::cout; 7 | using std::endl; 8 | cout << "OK" << endl; 9 | 10 | Time aida(3, 35); 11 | Time tosca(2, 48); 12 | Time temp; 13 | 14 | cout << "Aida and Tosca:\n"; 15 | cout << aida << "; " << tosca << endl; 16 | temp = aida + tosca; 17 | cout << "Aida + Tosca: " << temp << endl; 18 | temp = aida * 1.17; 19 | cout << "Aida * 1.17: " << temp << endl; 20 | cout << "10.0 * Tosca: " << 10.0 * tosca << endl; 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /Chapter11/PE04/mytime.cpp: -------------------------------------------------------------------------------- 1 | // mytime.cpp -- implementing Time methods 2 | #include "mytime.h" 3 | 4 | Time::Time() { 5 | hours = minutes = 0; 6 | } 7 | 8 | Time::Time(int h, int m) { 9 | hours = h; 10 | minutes = m; 11 | } 12 | 13 | void Time::AddMin(int m) { 14 | minutes += m; 15 | hours += minutes / 60; 16 | minutes %= 60; 17 | } 18 | 19 | void Time::AddHr(int h) { 20 | hours += h; 21 | } 22 | 23 | void Time::Reset(int h, int m) { 24 | hours = h; 25 | minutes = m; 26 | } 27 | 28 | Time operator+(const Time& t1, const Time& t2) { 29 | Time sum; 30 | sum.minutes = t1.minutes + t2.minutes; 31 | sum.hours = t1.hours + t2.hours + sum.minutes / 60; 32 | sum.minutes %= 60; 33 | return sum; 34 | } 35 | 36 | Time operator-(const Time& t1, const Time& t2) { 37 | Time diff; 38 | int tot1, tot2; 39 | tot1 = t1.minutes + 60 * t1.hours; 40 | tot2 = t2.minutes + 60 * t2.hours; 41 | diff.minutes = (tot2 - tot1) % 60; 42 | diff.hours = (tot2 - tot1) / 60; 43 | return diff; 44 | } 45 | 46 | Time operator*(const Time& t, double mult) { 47 | Time result; 48 | long totalminutes = t.hours * mult * 60 + t.minutes * mult; 49 | result.hours = totalminutes / 60; 50 | result.minutes = totalminutes % 60; 51 | return result; 52 | } 53 | 54 | std::ostream& operator<<(std::ostream& os, const Time& t) { 55 | os << t.hours << " hours, " << t.minutes << " minutes"; 56 | return os; 57 | } -------------------------------------------------------------------------------- /Chapter11/PE04/mytime.h: -------------------------------------------------------------------------------- 1 | // mytime.h -- Time class interface 2 | #ifndef MYTIME_H_ 3 | #define MYTIME_H_ 4 | 5 | #include 6 | 7 | class Time { 8 | public: 9 | Time(); 10 | Time(int h, int m = 0); 11 | 12 | void AddMin(int m); 13 | void AddHr(int h); 14 | void Reset(int h = 0, int m = 0); 15 | 16 | friend Time operator+(const Time& t1, const Time& t2); 17 | friend Time operator-(const Time& t1, const Time& t2); 18 | friend Time operator*(const Time& t, double m); 19 | friend Time operator*(double m, const Time& t) { return t * m; } 20 | friend std::ostream& operator<<(std::ostream& os, const Time& t); 21 | 22 | private: 23 | int hours; 24 | int minutes; 25 | }; 26 | 27 | #endif // MYTIME_H_ -------------------------------------------------------------------------------- /Chapter11/PE05/Makefile: -------------------------------------------------------------------------------- 1 | PE05: main.o stonewt.o 2 | g++ -o PE05 main.o stonewt.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | stonewt.o: stonewt.cpp 8 | g++ -c stonewt.cpp 9 | 10 | clean: 11 | rm *.o PE05 -------------------------------------------------------------------------------- /Chapter11/PE05/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 11.5 2 | #include 3 | #include "stonewt.h" 4 | 5 | int main() { 6 | using std::cout; 7 | using std::endl; 8 | 9 | Stonewt incognito = 275; // uses constructor to initialize 10 | Stonewt wolfe(285.7); // same as Stonewt wolfe = 285.7 11 | Stonewt taft(21, 8); 12 | 13 | cout << "Test addition and set to STONE mode:\n"; 14 | cout << (incognito + wolfe).set_stone_mode() << endl << endl; 15 | 16 | cout << "Test subtract:\n"; 17 | Stonewt testSubtract = wolfe - incognito; 18 | cout << testSubtract << endl; 19 | cout << "Change the mode to INTPOUNDS:\n"; 20 | testSubtract.set_intpounds_mode(); 21 | cout << testSubtract << endl; 22 | cout << "Change the mode to FLOATPOUNDS:\n"; 23 | testSubtract.set_folatpounds_mode(); 24 | cout << testSubtract << endl << endl; 25 | 26 | cout << "Test multiply:\n"; 27 | cout << taft * 2 << endl; 28 | cout << 2 * taft << endl; 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /Chapter11/PE05/stonewt.cpp: -------------------------------------------------------------------------------- 1 | // stonewt.cpp -- Stonewt methods 2 | #include 3 | #include "stonewt.h" 4 | 5 | // construct Stonewt object from double value 6 | Stonewt::Stonewt(double lbs) { 7 | stone = int(lbs) / Lbs_per_stn; // integer division 8 | pds_left = int(lbs) % Lbs_per_stn + lbs - int(lbs); 9 | pounds = lbs; 10 | mode = FLOATPOUNDS; 11 | } 12 | 13 | // construct Stronewt object from stone, double values 14 | Stonewt::Stonewt(int stn, double lbs) { 15 | stone = stn; 16 | pds_left = lbs; 17 | pounds = stn * Lbs_per_stn + lbs; 18 | mode = STONE; 19 | } 20 | 21 | // default constructor, wt = 0 22 | Stonewt::Stonewt() { 23 | stone = pounds = pds_left = 0; 24 | mode = STONE; 25 | } 26 | 27 | // destructor 28 | Stonewt::~Stonewt() {} 29 | 30 | // set to stone form 31 | Stonewt Stonewt::set_stone_mode() { 32 | mode = STONE; 33 | return *this; 34 | } 35 | 36 | // set to integer pounds form 37 | Stonewt Stonewt::set_intpounds_mode() { 38 | mode = INTPOUNDS; 39 | return *this; 40 | } 41 | 42 | // set to floating-point pounds form 43 | Stonewt Stonewt::set_folatpounds_mode() { 44 | mode = FLOATPOUNDS; 45 | return *this; 46 | } 47 | 48 | // addition operator overloading 49 | Stonewt Stonewt::operator+(const Stonewt& stonewt) const { 50 | double sum; 51 | sum = pounds + stonewt.pounds; 52 | return Stonewt(sum); 53 | } 54 | 55 | // subtract operator overloading 56 | Stonewt Stonewt::operator-(const Stonewt& stonewt) const { 57 | double diff; 58 | diff = pounds - stonewt.pounds; 59 | return Stonewt(diff); 60 | } 61 | 62 | // multiply operator overloading (Stonewt * n) 63 | Stonewt Stonewt::operator*(double n) const { 64 | double mult; 65 | mult = pounds * n; 66 | return Stonewt(mult); 67 | } 68 | 69 | // multiply operator overloading (n * Stonewt) 70 | Stonewt operator*(double n, Stonewt& stonewt) { 71 | return stonewt * n; 72 | } 73 | 74 | // ostream operator overloading 75 | std::ostream& operator<<(std::ostream& os, const Stonewt& stonewt) { 76 | if (stonewt.mode == Stonewt::STONE) { 77 | os << stonewt.stone << " stone, " << stonewt.pds_left << " pounds"; 78 | } else if (stonewt.mode == Stonewt::INTPOUNDS) { 79 | os << int(stonewt.pounds) << " pounds"; 80 | } else if (stonewt.mode == Stonewt::FLOATPOUNDS) { 81 | os << stonewt.pounds << " pounds"; 82 | } else { 83 | std::cout << "It should not be other modes." << std::endl; 84 | } 85 | return os; 86 | } -------------------------------------------------------------------------------- /Chapter11/PE05/stonewt.h: -------------------------------------------------------------------------------- 1 | // stonewt.h -- definition for the Stonewt class 2 | #ifndef STONEWT_H_ 3 | #define STONEWT_H_ 4 | 5 | #include 6 | 7 | class Stonewt { 8 | public: 9 | enum Mode { STONE, INTPOUNDS, FLOATPOUNDS }; 10 | 11 | Stonewt(double lbs); 12 | Stonewt(int stn, double lbs); 13 | Stonewt(); 14 | ~Stonewt(); 15 | 16 | Stonewt set_stone_mode(); 17 | Stonewt set_intpounds_mode(); 18 | Stonewt set_folatpounds_mode(); 19 | 20 | Stonewt operator+(const Stonewt& stonewt) const; 21 | Stonewt operator-(const Stonewt& stonewt) const; 22 | Stonewt operator*(double n) const; 23 | 24 | friend Stonewt operator*(double n, Stonewt& stonewt); 25 | friend std::ostream& operator<<(std::ostream& os, const Stonewt& stonewt); 26 | private: 27 | enum { Lbs_per_stn = 14 }; 28 | int stone; 29 | double pds_left; 30 | double pounds; 31 | Mode mode; 32 | }; 33 | 34 | #endif // STONEWT_H_ -------------------------------------------------------------------------------- /Chapter11/PE06/Makefile: -------------------------------------------------------------------------------- 1 | PE06: main.o stonewt.o 2 | g++ -o PE06 main.o stonewt.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | stonewt.o: stonewt.cpp 8 | g++ -c stonewt.cpp 9 | 10 | clean: 11 | rm *.o PE06 12 | -------------------------------------------------------------------------------- /Chapter11/PE06/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 11.5 2 | #include 3 | #include 4 | #include "stonewt.h" 5 | 6 | int main() { 7 | using std::cout; 8 | using std::endl; 9 | cout << std::boolalpha; 10 | 11 | Stonewt incognito = 275; // uses constructor to initialize 12 | Stonewt wolfe(285.7); // same as Stonewt wolfe = 285.7 13 | 14 | // The priority of << is higher than the priority of comparison operator. 15 | // And, they are also higher than the priority of equality / inequality. 16 | // So, () need to be added here. 17 | cout << "Test == / !=:" << endl; 18 | cout << "incognito is "; 19 | incognito.show_lbs(); 20 | cout << "wolfe is "; 21 | wolfe.show_lbs(); 22 | cout << "Are they equal? " << (incognito == wolfe) << endl; 23 | cout << "Are they NOT equal? " << (incognito != wolfe) << endl; 24 | incognito = wolfe; 25 | cout << "After incognito = wolfe:" << endl; 26 | cout << "Are they equal? " << (incognito == wolfe) << endl; 27 | cout << "Are they NOT equal? " << (incognito != wolfe) << endl << endl; 28 | 29 | wolfe = 285; 30 | cout << "incognito is "; 31 | incognito.show_lbs(); 32 | cout << "wolfe is "; 33 | wolfe.show_lbs(); 34 | cout << "incognito < wolfe? " << (incognito < wolfe) << endl; 35 | cout << "incognito <= wolfe? " << (incognito <= wolfe) << endl; 36 | cout << "incognito > wolfe? " << (incognito > wolfe) << endl; 37 | cout << "incognito >= wolfe? " << (incognito >= wolfe) << endl << endl; 38 | 39 | wolfe = 285.7; 40 | cout << "incognito is "; 41 | incognito.show_lbs(); 42 | cout << "wolfe is "; 43 | wolfe.show_lbs(); 44 | cout << "incognito < wolfe? " << (incognito < wolfe) << endl; 45 | cout << "incognito <= wolfe? " << (incognito <= wolfe) << endl; 46 | cout << "incognito > wolfe? " << (incognito > wolfe) << endl; 47 | cout << "incognito >= wolfe? " << (incognito >= wolfe) << endl << endl; 48 | 49 | wolfe = 286; 50 | cout << "incognito is "; 51 | incognito.show_lbs(); 52 | cout << "wolfe is "; 53 | wolfe.show_lbs(); 54 | cout << "incognito < wolfe? " << (incognito < wolfe) << endl; 55 | cout << "incognito <= wolfe? " << (incognito <= wolfe) << endl; 56 | cout << "incognito > wolfe? " << (incognito > wolfe) << endl; 57 | cout << "incognito >= wolfe? " << (incognito >= wolfe) << endl << endl; 58 | 59 | return 0; 60 | } -------------------------------------------------------------------------------- /Chapter11/PE06/stonewt.cpp: -------------------------------------------------------------------------------- 1 | // stonewt.cpp -- Stonewt methods 2 | #include "stonewt.h" 3 | 4 | // construct Stonewt object from double value 5 | Stonewt::Stonewt(double lbs) { 6 | stone = int(lbs) / Lbs_per_stn; // integer division 7 | pds_left = int(lbs) % Lbs_per_stn + lbs - int(lbs); 8 | pounds = lbs; 9 | } 10 | 11 | // construct Stronewt object from stone, double values 12 | Stonewt::Stonewt(int stn, double lbs) { 13 | stone = stn; 14 | pds_left = lbs; 15 | pounds = stn * Lbs_per_stn + lbs; 16 | } 17 | 18 | // default constructor, wt = 0 19 | Stonewt::Stonewt() { 20 | stone = pounds = pds_left = 0; 21 | } 22 | 23 | // destructor 24 | Stonewt::~Stonewt() {} 25 | 26 | // show weight in stones 27 | void Stonewt::show_stn() const { 28 | std::cout << stone << " stone, " << pds_left << " pounds\n"; 29 | } 30 | 31 | // show weight in pounds 32 | void Stonewt::show_lbs() const { 33 | std::cout << pounds << " pounds\n"; 34 | } 35 | 36 | // equality operator overloading 37 | bool Stonewt::operator==(const Stonewt& stonewt) const { 38 | if (pounds == stonewt.pounds) { 39 | return true; 40 | } else { 41 | return false; 42 | } 43 | } 44 | 45 | // inequality operator overloading 46 | bool Stonewt::operator!=(const Stonewt& stonewt) const { 47 | if (pounds != stonewt.pounds) { 48 | return true; 49 | } else { 50 | return false; 51 | } 52 | } 53 | 54 | // comparison operator overloading (<) 55 | bool Stonewt::operator<(const Stonewt& stonewt) const { 56 | if (pounds < stonewt.pounds) { 57 | return true; 58 | } else { 59 | return false; 60 | } 61 | } 62 | 63 | // comparison operator overloading (<=) 64 | bool Stonewt::operator<=(const Stonewt& stonewt) const { 65 | if (pounds <= stonewt.pounds) { 66 | return true; 67 | } else { 68 | return false; 69 | } 70 | } 71 | 72 | // comparison operator overloading (>) 73 | bool Stonewt::operator>(const Stonewt& stonewt) const { 74 | if (pounds > stonewt.pounds) { 75 | return true; 76 | } else { 77 | return false; 78 | } 79 | } 80 | 81 | // comparison operator overloading (>=) 82 | bool Stonewt::operator>=(const Stonewt& stonewt) const { 83 | if (pounds >= stonewt.pounds) { 84 | return true; 85 | } else { 86 | return false; 87 | } 88 | } -------------------------------------------------------------------------------- /Chapter11/PE06/stonewt.h: -------------------------------------------------------------------------------- 1 | // stonewt.h -- definition for the Stonewt class 2 | #ifndef STONEWT_H_ 3 | #define STONEWT_H_ 4 | 5 | #include 6 | 7 | class Stonewt { 8 | public: 9 | enum Mode { STONE, INTPOUNDS, FLOATPOUNDS }; 10 | 11 | Stonewt(double lbs); 12 | Stonewt(int stn, double lbs); 13 | Stonewt(); 14 | ~Stonewt(); 15 | 16 | void show_lbs() const; 17 | void show_stn() const; 18 | 19 | bool operator==(const Stonewt& stonewt) const; 20 | bool operator!=(const Stonewt& stonewt) const; 21 | bool operator<(const Stonewt& stonewt) const; 22 | bool operator<=(const Stonewt& stonewt) const; 23 | bool operator>(const Stonewt& stonewt) const; 24 | bool operator>=(const Stonewt& stonewt) const; 25 | private: 26 | enum { Lbs_per_stn = 14 }; 27 | int stone; 28 | double pds_left; 29 | double pounds; 30 | }; 31 | 32 | #endif // STONEWT_H_ -------------------------------------------------------------------------------- /Chapter11/PE07/Makefile: -------------------------------------------------------------------------------- 1 | PE07: main.o complex0.o 2 | g++ -o PE07 main.o complex0.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | complex0.o: complex0.cpp 8 | g++ -c complex0.cpp 9 | 10 | clean: 11 | rm *.o PE07 -------------------------------------------------------------------------------- /Chapter11/PE07/complex0.cpp: -------------------------------------------------------------------------------- 1 | // complex0.cpp -- implementing Mycomplex class 2 | #include "complex0.h" 3 | 4 | // constructor 5 | Mycomplex::Mycomplex(double real, double imaginary) { 6 | real_ = real; 7 | imaginary_ = imaginary; 8 | } 9 | 10 | // default constructor 11 | Mycomplex::Mycomplex() { 12 | real_ = imaginary_ = 0.0; 13 | } 14 | 15 | // destructor 16 | Mycomplex::~Mycomplex() {} 17 | 18 | // operator loading addition 19 | Mycomplex Mycomplex::operator+(const Mycomplex& complex) const { 20 | return Mycomplex(real_ + complex.real_, imaginary_ + complex.imaginary_); 21 | } 22 | 23 | // operator loading subtraction 24 | Mycomplex Mycomplex::operator-(const Mycomplex& complex) const { 25 | return Mycomplex(real_ - complex.real_, imaginary_ - complex.imaginary_); 26 | } 27 | 28 | // operator loading multiplication (complex * complex) 29 | Mycomplex Mycomplex::operator*(const Mycomplex& complex) const { 30 | return Mycomplex(real_ * complex.real_ - imaginary_ * complex.imaginary_, 31 | real_ * complex.imaginary_ + imaginary_ * complex.real_); 32 | } 33 | 34 | // operator loading multiplication (complex * n) 35 | Mycomplex Mycomplex::operator*(double n) const { 36 | return Mycomplex(n * real_, n * imaginary_); 37 | } 38 | 39 | // operator loading multiplication (n * complex) 40 | Mycomplex operator*(double n, const Mycomplex& complex) { 41 | return complex * n; 42 | } 43 | 44 | // operator loading conjugation 45 | Mycomplex Mycomplex::operator~() const { 46 | return Mycomplex(real_, -imaginary_); 47 | } 48 | 49 | // operator loading istream 50 | std::istream& operator>>(std::istream& is, Mycomplex& complex) { 51 | std::cout << "real: "; 52 | is >> complex.real_; 53 | std::cout << "imaginary: "; 54 | is >> complex.imaginary_; 55 | return is; 56 | } 57 | 58 | // operator loading ostream 59 | std::ostream& operator<<(std::ostream& os, const Mycomplex& complex) { 60 | os << "(" << complex.real_ << "," << complex.imaginary_ << "i)"; 61 | return os; 62 | } -------------------------------------------------------------------------------- /Chapter11/PE07/complex0.h: -------------------------------------------------------------------------------- 1 | // complex0.h -- Mycomplex class interface 2 | #include 3 | 4 | class Mycomplex { 5 | public: 6 | Mycomplex(double real, double imaginary); 7 | Mycomplex(); 8 | ~Mycomplex(); 9 | 10 | Mycomplex operator+(const Mycomplex& complex) const; 11 | Mycomplex operator-(const Mycomplex& complex) const; 12 | Mycomplex operator*(const Mycomplex& complex) const; 13 | Mycomplex operator*(double n) const; 14 | Mycomplex operator~() const; 15 | 16 | friend Mycomplex operator*(double n, const Mycomplex& complex); 17 | friend std::istream& operator>>(std::istream& is, Mycomplex& complex); 18 | friend std::ostream& operator<<(std::ostream& os, const Mycomplex& complex); 19 | private: 20 | double real_; 21 | double imaginary_; 22 | }; -------------------------------------------------------------------------------- /Chapter11/PE07/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 11.7 2 | #include 3 | #include "complex0.h" 4 | 5 | int main() { 6 | using std::cout; 7 | 8 | Mycomplex a(3.0, 4.0); 9 | Mycomplex c; 10 | cout << "Enter a complex number (q to quit):\n"; 11 | while (std::cin >> c) { 12 | cout << "c is " << c << '\n'; 13 | cout << "complex conjugate is " << ~c << '\n'; 14 | cout << "a is " << a << '\n'; 15 | cout << "a + c is " << a + c << '\n'; 16 | cout << "a - c is " << a - c << '\n'; 17 | cout << "a * c is " << a * c << '\n'; 18 | cout << "2 * c is " << 2 * c << '\n'; 19 | cout << "Enter a complex number (q to quit):\n"; 20 | } 21 | cout << "Done!\n"; 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /Chapter11/README.md: -------------------------------------------------------------------------------- 1 | # Notes: 2 | According to a question on [stackoverflow](https://stackoverflow.com/questions/15960015/c-printing-boolean-what-is-displayed): 3 | 4 | The standard streams have a boolalpha flag that determines what gets displayed -- when it's false, they'll display as 0 and 1. When it's true, they'll display as false and true. 5 | 6 | There's also an std::boolalpha manipulator to set the flag, so this: 7 | 8 | ``` 9 | #include 10 | #include 11 | 12 | int main() { 13 | std::cout< 3 | #include 4 | #include "cow.h" 5 | 6 | Cow::Cow() { 7 | std::cout << "default constructor:\n"; 8 | name[0] = '\0'; 9 | hobby = new char[1]; 10 | hobby[0] = '\0'; 11 | // If hobby is assigned to nullptr, the operator<< need to be updated. 12 | // Otherwise, ShowCow for the object won't work. 13 | // hobby = nullptr; 14 | weight = 0.0; 15 | } 16 | 17 | Cow::Cow(const char* nm, const char* ho, double wt) { 18 | std::cout << "constructor:\n"; 19 | std::strcpy(name, nm); 20 | 21 | int len = std::strlen(ho); 22 | hobby = new char[len + 1]; 23 | std::strcpy(hobby, ho); 24 | 25 | weight = wt; 26 | } 27 | 28 | Cow::Cow(const Cow& c) { 29 | std::cout << "copy constructor:\n"; 30 | 31 | std::strcpy(name, c.name); 32 | 33 | int len = std::strlen(c.hobby); 34 | hobby = new char[len + 1]; 35 | std::strcpy(hobby, c.hobby); 36 | 37 | weight = c.weight; 38 | } 39 | 40 | Cow::~Cow() { 41 | std::cout << "destructor: "; 42 | std::cout << "\"" << hobby << "\" removed.\n"; 43 | delete[] hobby; 44 | } 45 | 46 | Cow& Cow::operator=(const Cow& c) { 47 | std::cout << "assignment operator:\n"; 48 | if (this == &c) { 49 | return *this; 50 | } else { 51 | delete[] hobby; 52 | 53 | std::strcpy(name, c.name); 54 | 55 | int len = std::strlen(c.hobby); 56 | hobby = new char [len + 1]; 57 | std::strcpy(hobby, c.hobby); 58 | 59 | weight = c.weight; 60 | 61 | return *this; 62 | } 63 | } 64 | 65 | void Cow::ShowCow() const { 66 | using std::cout; 67 | cout << "The cow's name is " << name << ".\n"; 68 | cout << "The hobby is " << hobby << ".\n"; 69 | cout << "The weight is " << weight << ".\n"; 70 | } -------------------------------------------------------------------------------- /Chapter12/PE01/cow.h: -------------------------------------------------------------------------------- 1 | // cow.h -- Cow class interface 2 | #ifndef COW_H_ 3 | #define COW_H_ 4 | 5 | class Cow { 6 | public: 7 | Cow(); 8 | Cow(const char* nm, const char* ho, double wt); 9 | Cow(const Cow& c); 10 | ~Cow(); 11 | Cow& operator=(const Cow& c); 12 | void ShowCow() const; 13 | private: 14 | char name[20]; 15 | char* hobby; 16 | double weight; 17 | }; 18 | 19 | #endif // COW_H_ -------------------------------------------------------------------------------- /Chapter12/PE01/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 12.1 2 | #include 3 | #include "cow.h" 4 | 5 | int main() { 6 | using std::cout; 7 | using std::endl; 8 | { 9 | cout << "Starting an inner block.\n\n"; 10 | 11 | Cow obj1; 12 | obj1.ShowCow(); 13 | cout << endl; 14 | 15 | Cow obj2("Adam", "Snooker", 180.50); 16 | obj2.ShowCow(); 17 | cout << endl; 18 | 19 | Cow obj3 = obj2; 20 | obj3.ShowCow(); 21 | cout << endl; 22 | 23 | obj1 = obj3; 24 | obj1.ShowCow(); 25 | 26 | cout << "\nExiting the block.\n"; 27 | } 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Chapter12/PE02/Makefile: -------------------------------------------------------------------------------- 1 | PE02: main.o string2.o 2 | g++ -o PE02 main.o string2.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | string2.o: string2.cpp 8 | g++ -c string2.cpp 9 | 10 | clean: 11 | rm *.o PE02 -------------------------------------------------------------------------------- /Chapter12/PE02/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 12.2 2 | #include 3 | #include "string2.h" 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | String s1(" and I am a C++ student."); 9 | String s2 = "Please enter your name: "; 10 | String s3; 11 | cout << s2; // overloaded << operator 12 | cin >> s3; // overloaded >> operator 13 | 14 | s2 = "My name is " + s3; // overloaded =, + operators 15 | cout << s2 << ".\n"; 16 | s2 = s2 + s1; 17 | s2.stringup(); // converts string to uppercase 18 | cout << "The string\n" << s2 << "\ncontains " << s2.has('A') 19 | << " 'A' characters in it.\n"; 20 | 21 | s1 = "red"; // String(const char *), 22 | // then String & operator=(const String&) 23 | String rgb[3] = { String(s1), String("green"), String("blue")}; 24 | cout << "Enter the name of a primary color for mixing light: "; 25 | String ans; 26 | bool success = false; 27 | while (cin >> ans) { 28 | ans.stringlow(); // converts string to lowercase 29 | for (int i = 0; i < 3; i++) { 30 | if (ans == rgb[i]) { // overloaded == operator 31 | cout << "That's right!\n"; 32 | success = true; 33 | break; 34 | } 35 | } 36 | if (success) { 37 | break; 38 | } 39 | else { 40 | cout << "Try again!\n"; 41 | } 42 | } 43 | cout << "Bye\n"; 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /Chapter12/PE02/string2.h: -------------------------------------------------------------------------------- 1 | // string2.h -- fixed and augmented string class definition 2 | #ifndef STRING2_H_ 3 | #define STRING2_H_ 4 | 5 | #include 6 | 7 | using std::ostream; 8 | using std::istream; 9 | 10 | class String { 11 | public: 12 | // constructors and other methods 13 | String(const char* s); // constructor 14 | String(); // default constructor 15 | String(const String&); // copy constructor 16 | ~String(); // destructor 17 | // simple member methods 18 | void stringlow(); 19 | void stringup(); 20 | int has(const char) const; 21 | // overloaded operator methods 22 | String& operator=(const String&); 23 | String& operator=(const char*); 24 | char& operator[](int i); 25 | const char& operator[](int i) const; 26 | String& operator+(const String&); 27 | String& operator+(const char*); 28 | // overloaded operator friends 29 | friend bool operator<(const String& st, const String& st2); 30 | friend bool operator>(const String& st1, const String& st2); 31 | friend bool operator==(const String& st, const String& st2); 32 | friend ostream& operator<<(ostream& os, const String& st); 33 | friend istream& operator>>(istream& is, String& st); 34 | friend String& operator+(const char*, String&); 35 | // get len function 36 | int length () const { return len; } 37 | // static function 38 | static int HowMany(); 39 | private: 40 | static int num_strings; // number of objects 41 | static const int CINLIM = 80; // cin input limit 42 | char* str; // pointer to string 43 | int len; // length of string 44 | }; 45 | 46 | #endif -------------------------------------------------------------------------------- /Chapter12/PE03/Makefile: -------------------------------------------------------------------------------- 1 | PE03: main.o stock.o 2 | g++ -o PE03 main.o stock.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | stock.o: stock.cpp 8 | g++ -c stock.cpp 9 | 10 | clean: 11 | rm *.o PE03 -------------------------------------------------------------------------------- /Chapter12/PE03/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 12.3 2 | #include 3 | #include "stock.h" 4 | 5 | const int STKS = 4; 6 | 7 | int main() { 8 | using std::cout; 9 | using std::endl; 10 | 11 | cout << "Test constructor:" << endl; 12 | // create an array of initialized objects 13 | Stock stocks[STKS] = { 14 | Stock("NanoSmart", 12, 20.0), 15 | Stock("Boffo Objects", 200, 2.0), 16 | Stock("Monolithic Obelisks", 130, 3.25), 17 | Stock("Fleep Enterprises", 60, 6.5) 18 | }; 19 | 20 | std::cout << "Stock holdings:\n"; 21 | for (int i = 0; i < STKS; ++i) { 22 | cout << stocks[i]; 23 | } 24 | 25 | cout << "\nTest default constructor:" << endl; 26 | Stock obj1; 27 | cout << obj1; 28 | 29 | cout << "\nTest copy constructor:" << endl; 30 | Stock obj2 = stocks[1]; 31 | cout << obj2; 32 | 33 | cout << "\nTest assignment operator:" << endl; 34 | obj1 = stocks[0]; 35 | cout << obj1; 36 | 37 | cout << "\nTest Buy function:" << endl; 38 | obj1.Buy(100, 12.34); 39 | cout << obj1; 40 | 41 | cout << "\nTest Sell function:" << endl; 42 | obj1.Sell(62, 34.1); 43 | cout << obj1; 44 | 45 | cout << "\nTest Update function:" << endl; 46 | obj1.Update(5.23); 47 | cout << obj1; 48 | 49 | cout << "\nTest Topval function:" << endl; 50 | Stock top; 51 | for (int i = 0; i < STKS - 1; ++i) { 52 | top = stocks[i].Topval(stocks[i + 1]); 53 | } 54 | cout << top; 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /Chapter12/PE03/stock.h: -------------------------------------------------------------------------------- 1 | // stock.h -- Stock class interface 2 | #ifndef STOCK_H_ 3 | #define STOCK_H_ 4 | 5 | #include 6 | 7 | class Stock { 8 | public: 9 | Stock(const char* company, // constructor 10 | long shares = 0, 11 | double shareVal = 0.0); 12 | Stock(); // default constructor 13 | Stock(const Stock& stock); // copy constuctor 14 | ~Stock(); // destructor 15 | Stock& operator=(const Stock& stock); // assignment operator 16 | 17 | void Buy(long shares, double shareVal); // buy stocks 18 | void Sell(long shares, double shareVal); // sell stocks 19 | void Update(double shareVal); // update the total value 20 | const Stock& Topval(const Stock& stock) const; // compare total values 21 | 22 | friend std::ostream& operator<<(std::ostream& os, const Stock& stock); 23 | private: 24 | char* company_; // company name 25 | int shares_; // the number of shares of the company 26 | double shareVal_; // the price of each share 27 | double totalVal_; // the total value of the stock 28 | void setTotalVal() { totalVal_ = shares_ * shareVal_; } 29 | }; 30 | 31 | #endif // STOCK_H_ -------------------------------------------------------------------------------- /Chapter12/PE04/Makefile: -------------------------------------------------------------------------------- 1 | PE04: main.o stack.o 2 | g++ -o PE04 main.o stack.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | stack.o: stack.cpp 8 | g++ -c stack.cpp 9 | 10 | clean: 11 | rm *.o PE04 -------------------------------------------------------------------------------- /Chapter12/PE04/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 12.4 2 | #include 3 | #include 4 | #include "stack.h" 5 | 6 | int main() { 7 | using std::cout; 8 | using std::endl; 9 | 10 | cout << "Test constructor:\n"; 11 | Stack st(3); 12 | cout << "It is empty.\n"; 13 | 14 | cout << "\nTest isempty function:\n"; 15 | cout << "Empty?: " << std::boolalpha << st.isempty() << endl; 16 | 17 | cout << "\nTest add function:\n"; 18 | unsigned long temp = 17885; 19 | st.push(temp); 20 | temp = 17965; 21 | st.push(temp); 22 | temp = 18002; 23 | st.push(temp); 24 | cout << st; 25 | 26 | cout << "\nTest isfull function:\n"; 27 | cout << "Full?: " << std::boolalpha << st.isfull() << endl; 28 | 29 | cout << "\nTest copy constructor:\n"; 30 | Stack st1 = st; 31 | cout << st1; 32 | 33 | cout << "\nTest assignment operator:\n"; 34 | Stack st2; 35 | st2 = st; 36 | cout << st2; 37 | 38 | cout << "\nTest pop function:\n"; 39 | temp = 1; // change the temp to a number not equals to 18002 40 | st.pop(temp); // in the pop function, temp will be assigned to 18002 41 | cout << "temp = " << temp << endl; 42 | cout << st; 43 | 44 | return 0; 45 | } -------------------------------------------------------------------------------- /Chapter12/PE04/stack.cpp: -------------------------------------------------------------------------------- 1 | // stack.cpp -- implementing the Stack class 2 | #include "stack.h" 3 | 4 | // constructor or default constructor 5 | Stack::Stack(int n) { 6 | pitems = new Item[n]; 7 | size = n; 8 | top = 0; 9 | } 10 | 11 | // copy constructor 12 | Stack::Stack(const Stack& st) { 13 | pitems = new Item[st.size]; 14 | for (int i = 0; i < st.top; ++i) { 15 | pitems[i] = st.pitems[i]; 16 | } 17 | size = st.size; 18 | top = st.top; 19 | } 20 | 21 | // destructor 22 | Stack::~Stack() { 23 | delete[] pitems; 24 | } 25 | 26 | // assignment operator 27 | Stack& Stack::operator=(const Stack& st) { 28 | if (this == &st) { 29 | return *this; 30 | } else { 31 | delete[] pitems; 32 | pitems = new Item[st.size]; 33 | for (int i = 0; i < st.top; ++i) { 34 | pitems[i] = st.pitems[i]; 35 | } 36 | size = st.size; 37 | top = st.top; 38 | } 39 | } 40 | 41 | // if the Stack is empty or not 42 | bool Stack::isempty() const { 43 | return top == 0; 44 | } 45 | 46 | // if the Stack is full or not 47 | bool Stack::isfull() const { 48 | return top == size; 49 | } 50 | 51 | // add item to stack 52 | bool Stack::push(const Item& item) { 53 | if (top < size) { 54 | pitems[top++] = item; 55 | return true; 56 | } else { 57 | return false; 58 | } 59 | } 60 | 61 | // pop top into item 62 | bool Stack::pop(Item& item) { 63 | if (top > 0) { 64 | item = pitems[--top]; 65 | return true; 66 | } else { 67 | return false; 68 | } 69 | } 70 | 71 | // overloaded operator << 72 | std::ostream& operator<<(std::ostream& os, const Stack& st) { 73 | std::cout << "The stack includes:\n"; 74 | for (int i = 0; i < st.top; ++i) { 75 | std::cout << st.pitems[i] << " "; 76 | } 77 | std::cout << std::endl; 78 | return os; 79 | } -------------------------------------------------------------------------------- /Chapter12/PE04/stack.h: -------------------------------------------------------------------------------- 1 | // stack.h -- class declaration for the stack ADT 2 | #ifndef STACK_H_ 3 | #define STACK_H_ 4 | 5 | #include 6 | 7 | typedef unsigned long Item; 8 | 9 | class Stack { 10 | public: 11 | Stack(int n = MAX); // creates stack with n elements 12 | Stack(const Stack& st); 13 | ~Stack(); 14 | Stack& operator=(const Stack& st); 15 | 16 | bool isempty() const; 17 | bool isfull() const; 18 | 19 | // push() returns false if stack already is full, true otherwise 20 | bool push(const Item& item); // add item to stack 21 | // pop() returns false if stack already is empty, true otherwise 22 | bool pop(Item& item); // pop top into item 23 | 24 | friend std::ostream& operator<<(std::ostream& os, const Stack& st); 25 | private: 26 | enum {MAX = 10}; // constant specific to class 27 | Item* pitems; // holds stack items 28 | int size; // number of elements in stack 29 | int top; // index for top stack item 30 | }; 31 | 32 | #endif // STACK_H_ -------------------------------------------------------------------------------- /Chapter12/PE05/Makefile: -------------------------------------------------------------------------------- 1 | PE05: main.o queue.o 2 | g++ -o PE05 main.o queue.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | queue.o: queue.cpp 8 | g++ -c queue.cpp 9 | 10 | clean: 11 | rm *.o PE05 -------------------------------------------------------------------------------- /Chapter12/PE05/queue.cpp: -------------------------------------------------------------------------------- 1 | // queue.cpp -- Queue and Customer methods 2 | #include "queue.h" 3 | #include // (or stdlib.h) for rand() 4 | 5 | // customer method 6 | // when is the time at which the customer arrives 7 | // the arrival time is set to when and the processing 8 | // time set to a random value in the range 1 - 3 9 | void Customer::set(long when) { 10 | processtime = std::rand() % 3 + 1; 11 | arrive = when; 12 | } 13 | 14 | // Queue methods 15 | Queue::Queue(int qs) : qsize(qs) { 16 | front = rear = NULL; // or nullptr 17 | items = 0; 18 | } 19 | 20 | Queue::~Queue() { 21 | Node* temp; 22 | while (front != NULL) { // while queue is not yet empty 23 | temp = front; // save address of front item 24 | front = front->next;// reset pointer to next item 25 | delete temp; // delete former front 26 | } 27 | } 28 | 29 | bool Queue::isempty() const { 30 | return items == 0; 31 | } 32 | 33 | bool Queue::isfull() const { 34 | return items == qsize; 35 | } 36 | 37 | int Queue::queuecount() const { 38 | return items; 39 | } 40 | 41 | // Add item to queue 42 | bool Queue::enqueue(const Item& item) { 43 | if (isfull()) { 44 | return false; 45 | } 46 | Node* add = new Node; // create node 47 | // on failure, new throws std::bad_alloc exception 48 | add->item = item; // set node pointers 49 | add->next = NULL; // or nullptr; 50 | items++; 51 | if (front == NULL) { // if queue is empty, 52 | front = add; // place item at front 53 | } 54 | else { 55 | rear->next = add; // else place at rear 56 | } 57 | rear = add; // have rear point to new node 58 | return true; 59 | } 60 | 61 | // Place front item into item variable and remove from queue 62 | bool Queue::dequeue(Item& item) { 63 | if (front == NULL) { 64 | return false; 65 | } 66 | item = front->item; // set item to first item in queue 67 | items--; 68 | Node* temp = front; // save location of first item 69 | front = front->next; // reset front to next item 70 | delete temp; // delete former first item 71 | if (items == 0) { 72 | rear = NULL; 73 | } 74 | return true; 75 | } -------------------------------------------------------------------------------- /Chapter12/PE05/queue.h: -------------------------------------------------------------------------------- 1 | // queue.h -- interface for a queue 2 | #ifndef QUEUE_H_ 3 | #define QUEUE_H_ 4 | 5 | // This queue will contain Customer items 6 | class Customer { 7 | public: 8 | Customer() { arrive = processtime = 0; } 9 | void set(long when); 10 | long when() const { return arrive; } 11 | int ptime() const { return processtime; } 12 | private: 13 | long arrive; // arrival time for customer 14 | int processtime; // processing time for customer 15 | 16 | }; 17 | 18 | typedef Customer Item; 19 | 20 | class Queue { 21 | public: 22 | Queue(int qs = Q_SIZE); // create queue with a qs limit 23 | ~Queue(); 24 | bool isempty() const; 25 | bool isfull() const; 26 | int queuecount() const; 27 | bool enqueue(const Item& item); // add item to end 28 | bool dequeue(Item& item); // remove item from front 29 | private: 30 | // class scope definitions 31 | // Node is a nested structure definition local to this class 32 | struct Node { Item item; struct Node* next; }; 33 | enum {Q_SIZE = 10}; 34 | // private class members 35 | Node* front; // pointer to front of Queue 36 | Node* rear; // pointer to rear of Queue 37 | int items; // current number of items in Queue 38 | const int qsize; // maximum number of items in Queue 39 | // preemptive definitions to prevent public copying 40 | Queue(const Queue& q) : qsize(0) { } 41 | Queue& operator=(const Queue& q) { return *this; } 42 | }; 43 | 44 | #endif // QUEUE_H_ -------------------------------------------------------------------------------- /Chapter12/PE06/Makefile: -------------------------------------------------------------------------------- 1 | PE06: main.o queue.o 2 | g++ -o PE06 main.o queue.o 3 | 4 | main.o: main.cpp 5 | g++ -c main.cpp 6 | 7 | queue.o: queue.cpp 8 | g++ -c queue.cpp 9 | 10 | clean: 11 | rm *.o PE06 -------------------------------------------------------------------------------- /Chapter12/PE06/queue.cpp: -------------------------------------------------------------------------------- 1 | // queue.cpp -- Queue and Customer methods 2 | #include "queue.h" 3 | #include // (or stdlib.h) for rand() 4 | 5 | // customer method 6 | // when is the time at which the customer arrives 7 | // the arrival time is set to when and the processing 8 | // time set to a random value in the range 1 - 3 9 | void Customer::set(long when) { 10 | processtime = std::rand() % 3 + 1; 11 | arrive = when; 12 | } 13 | 14 | // Queue methods 15 | Queue::Queue(int qs) : qsize(qs) { 16 | front = rear = NULL; // or nullptr 17 | items = 0; 18 | } 19 | 20 | Queue::~Queue() { 21 | Node* temp; 22 | while (front != NULL) { // while queue is not yet empty 23 | temp = front; // save address of front item 24 | front = front->next;// reset pointer to next item 25 | delete temp; // delete former front 26 | } 27 | } 28 | 29 | bool Queue::isempty() const { 30 | return items == 0; 31 | } 32 | 33 | bool Queue::isfull() const { 34 | return items == qsize; 35 | } 36 | 37 | int Queue::queuecount() const { 38 | return items; 39 | } 40 | 41 | // Add item to queue 42 | bool Queue::enqueue(const Item& item) { 43 | if (isfull()) { 44 | return false; 45 | } 46 | Node* add = new Node; // create node 47 | // on failure, new throws std::bad_alloc exception 48 | add->item = item; // set node pointers 49 | add->next = NULL; // or nullptr; 50 | items++; 51 | if (front == NULL) { // if queue is empty, 52 | front = add; // place item at front 53 | } 54 | else { 55 | rear->next = add; // else place at rear 56 | } 57 | rear = add; // have rear point to new node 58 | return true; 59 | } 60 | 61 | // Place front item into item variable and remove from queue 62 | bool Queue::dequeue(Item& item) { 63 | if (front == NULL) { 64 | return false; 65 | } 66 | item = front->item; // set item to first item in queue 67 | items--; 68 | Node* temp = front; // save location of first item 69 | front = front->next; // reset front to next item 70 | delete temp; // delete former first item 71 | if (items == 0) { 72 | rear = NULL; 73 | } 74 | return true; 75 | } -------------------------------------------------------------------------------- /Chapter12/PE06/queue.h: -------------------------------------------------------------------------------- 1 | // queue.h -- interface for a queue 2 | #ifndef QUEUE_H_ 3 | #define QUEUE_H_ 4 | 5 | // This queue will contain Customer items 6 | class Customer { 7 | public: 8 | Customer() { arrive = processtime = 0; } 9 | void set(long when); 10 | long when() const { return arrive; } 11 | int ptime() const { return processtime; } 12 | private: 13 | long arrive; // arrival time for customer 14 | int processtime; // processing time for customer 15 | 16 | }; 17 | 18 | typedef Customer Item; 19 | 20 | class Queue { 21 | public: 22 | Queue(int qs = Q_SIZE); // create queue with a qs limit 23 | ~Queue(); 24 | bool isempty() const; 25 | bool isfull() const; 26 | int queuecount() const; 27 | bool enqueue(const Item& item); // add item to end 28 | bool dequeue(Item& item); // remove item from front 29 | private: 30 | // class scope definitions 31 | // Node is a nested structure definition local to this class 32 | struct Node { Item item; struct Node* next; }; 33 | enum {Q_SIZE = 10}; 34 | // private class members 35 | Node* front; // pointer to front of Queue 36 | Node* rear; // pointer to rear of Queue 37 | int items; // current number of items in Queue 38 | const int qsize; // maximum number of items in Queue 39 | // preemptive definitions to prevent public copying 40 | Queue(const Queue& q) : qsize(0) { } 41 | Queue& operator=(const Queue& q) { return *this; } 42 | }; 43 | 44 | #endif // QUEUE_H_ -------------------------------------------------------------------------------- /Chapter13/PE01/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = -ggdb -Wall 3 | LDFLAGS = 4 | OBJFILES = main.o cd.o classic.o 5 | TARGET = PE01 6 | 7 | all: $(TARGET) 8 | 9 | $(TARGET): $(OBJFILES) 10 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS) 11 | 12 | clean: 13 | rm -f $(OBJFILES) $(TARGET) -------------------------------------------------------------------------------- /Chapter13/PE01/cd.cpp: -------------------------------------------------------------------------------- 1 | // cd.cpp -- implementing the Cd class 2 | #include 3 | #include 4 | #include "cd.h" 5 | 6 | // constructor 7 | Cd::Cd(const char* performer, const char* label, int selections, 8 | double playtime) { 9 | std::strcpy(performer_, performer); 10 | std::strcpy(label_, label); 11 | selections_ = selections; 12 | playtime_ = playtime; 13 | } 14 | 15 | // copy constructor 16 | Cd::Cd(const Cd& cd) { 17 | std::strcpy(performer_, cd.performer_); 18 | std::strcpy(label_, cd.label_); 19 | selections_ = cd.selections_; 20 | playtime_ = cd.playtime_; 21 | } 22 | 23 | // default constructor 24 | Cd::Cd() { 25 | std::strcpy(performer_, "none"); 26 | std::strcpy(label_, "none"); 27 | selections_ = 0; 28 | playtime_ = 0.0; 29 | } 30 | 31 | // destrcutor 32 | Cd::~Cd() {} 33 | 34 | // reports all CD data 35 | void Cd::Report() const { 36 | using std::cout; 37 | using std::endl; 38 | cout << "The performer is " << performer_ << ".\n"; 39 | cout << "The label is " << label_ << ".\n"; 40 | cout << "The selections is " << selections_ << ".\n"; 41 | cout << "The playtime is " << playtime_ << ".\n"; 42 | } 43 | 44 | // overload assignment operator 45 | Cd& Cd::operator=(const Cd& cd) { 46 | if (this == &cd) { 47 | return *this; 48 | } else { 49 | std::strcpy(performer_, cd.performer_); 50 | std::strcpy(label_, cd.label_); 51 | selections_ = cd.selections_; 52 | playtime_ = cd.playtime_; 53 | return *this; 54 | } 55 | } -------------------------------------------------------------------------------- /Chapter13/PE01/cd.h: -------------------------------------------------------------------------------- 1 | // cd.h -- Cd class interface 2 | #ifndef CD_H_ 3 | #define CD_H_ 4 | 5 | // base class 6 | class Cd { // represents a CD disk 7 | public: 8 | Cd(const char* performer, const char* label, int selections, 9 | double playtime); 10 | Cd(const Cd& cd); 11 | Cd(); 12 | virtual ~Cd(); 13 | virtual void Report() const; // reports all CD data 14 | virtual Cd& operator=(const Cd& cd); 15 | private: 16 | char performer_[50]; 17 | char label_[20]; 18 | int selections_; // number of selections 19 | double playtime_; // playing time in minutes 20 | }; 21 | 22 | #endif // CD_H_ -------------------------------------------------------------------------------- /Chapter13/PE01/classic.cpp: -------------------------------------------------------------------------------- 1 | // classic.cpp -- implementing the Classic class 2 | #include 3 | #include 4 | #include "classic.h" 5 | 6 | // constructor 7 | Classic::Classic(const char* primary, const char* performer, 8 | const char* label, int selections, double playtime) 9 | : Cd(performer, label, selections, playtime) { 10 | std::strcpy(primary_, primary); 11 | 12 | } 13 | 14 | // copy constructor 15 | Classic::Classic(const Classic& classic) 16 | : Cd(classic) { 17 | std::strcpy(primary_, classic.primary_); 18 | } 19 | 20 | // default constructor 21 | Classic::Classic() 22 | : Cd() { 23 | std::strcpy(primary_, "none"); 24 | } 25 | 26 | // destructor 27 | Classic::~Classic() {} 28 | 29 | // reports all Classic data 30 | void Classic::Report() const { 31 | std::cout << "The primary is " << primary_ << ".\n"; 32 | Cd::Report(); 33 | } 34 | 35 | // overload assignment operator 36 | Classic& Classic::operator=(const Classic& classic) { 37 | if (this == &classic) { 38 | return *this; 39 | } else { 40 | Cd::operator=(classic); 41 | std::strcpy(primary_, classic.primary_); 42 | return *this; 43 | } 44 | } -------------------------------------------------------------------------------- /Chapter13/PE01/classic.h: -------------------------------------------------------------------------------- 1 | // classic.h -- Classic class interface 2 | #ifndef CLASSIC_H_ 3 | #define CLASSIC_H_ 4 | 5 | #include "cd.h" 6 | 7 | class Classic : public Cd { 8 | public: 9 | Classic(const char* primary, const char* performer, const char* label, 10 | int selections, double playtime); 11 | Classic(const Classic& classic); 12 | Classic(); 13 | virtual ~Classic(); 14 | virtual void Report() const; 15 | virtual Classic& operator=(const Classic& classic); 16 | private: 17 | char primary_[100]; 18 | }; 19 | 20 | #endif // CLASSIC_H_ -------------------------------------------------------------------------------- /Chapter13/PE01/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 13.1 2 | #include 3 | #include "cd.h" 4 | #include "classic.h" 5 | 6 | using std::cout; 7 | 8 | void Bravo(const Cd& disk); 9 | 10 | int main() { 11 | Cd c1("Beatles", "Capitol", 14, 35.5); 12 | Classic c2 = Classic("Piano Sonata in B flat, Fantasia in C", 13 | "Alfred Brendel", "Philips", 2, 57.17); 14 | Cd* pcd = &c1; 15 | 16 | cout << "Using object directly:\n"; 17 | c1.Report(); // use Cd method 18 | c2.Report(); // use Classic method 19 | cout << "\n"; 20 | 21 | cout << "Using type cd* pointer to objects:\n"; 22 | pcd->Report(); // use Cd method for cd object 23 | pcd = &c2; 24 | pcd->Report(); // use Classic method for classic object 25 | cout << "\n"; 26 | 27 | cout << "Calling a function with a Cd reference argument:\n"; 28 | Bravo(c1); 29 | Bravo(c2); 30 | cout << "\n"; 31 | 32 | cout << "Testing assignment:\n"; 33 | Classic copy; 34 | copy = c2; 35 | copy.Report(); 36 | 37 | return 0; 38 | } 39 | 40 | void Bravo(const Cd& disk) { 41 | disk.Report(); 42 | } -------------------------------------------------------------------------------- /Chapter13/PE02/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = -ggdb -Wall 3 | LDFLAGS = 4 | OBJFILES = main.o cd.o classic.o 5 | TARGET = PE02 6 | 7 | all: $(TARGET) 8 | 9 | $(TARGET): $(OBJFILES) 10 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS) 11 | 12 | clean: 13 | rm -f $(OBJFILES) $(TARGET) -------------------------------------------------------------------------------- /Chapter13/PE02/cd.cpp: -------------------------------------------------------------------------------- 1 | // cd.cpp -- implementing the Cd class 2 | #include 3 | #include 4 | #include "cd.h" 5 | 6 | // constructor 7 | Cd::Cd(const char* performer, const char* label, int selections, 8 | double playtime) { 9 | performer_ = new char[std::strlen(performer) + 1]; 10 | std::strcpy(performer_, performer); 11 | label_ = new char[std::strlen(label) + 1]; 12 | std::strcpy(label_, label); 13 | selections_ = selections; 14 | playtime_ = playtime; 15 | } 16 | 17 | // copy constructor 18 | Cd::Cd(const Cd& cd) { 19 | performer_ = new char[std::strlen(cd.performer_) + 1]; 20 | std::strcpy(performer_, cd.performer_); 21 | label_ = new char[std::strlen(cd.label_) + 1]; 22 | std::strcpy(label_, cd.label_); 23 | selections_ = cd.selections_; 24 | playtime_ = cd.playtime_; 25 | } 26 | 27 | // default constructor 28 | Cd::Cd() { 29 | performer_ = new char[5]; 30 | std::strcpy(performer_, "none"); 31 | label_ = new char[5]; 32 | std::strcpy(label_, "none"); 33 | selections_ = 0; 34 | playtime_ = 0.0; 35 | } 36 | 37 | // destrcutor 38 | Cd::~Cd() { 39 | delete performer_; 40 | delete label_; 41 | } 42 | 43 | // reports all CD data 44 | void Cd::Report() const { 45 | using std::cout; 46 | using std::endl; 47 | cout << "The performer is " << performer_ << ".\n"; 48 | cout << "The label is " << label_ << ".\n"; 49 | cout << "The selections is " << selections_ << ".\n"; 50 | cout << "The playtime is " << playtime_ << ".\n"; 51 | } 52 | 53 | // overload assignment operator 54 | Cd& Cd::operator=(const Cd& cd) { 55 | if (this == &cd) { 56 | return *this; 57 | } else { 58 | delete performer_; 59 | delete label_; 60 | performer_ = new char[std::strlen(cd.performer_) + 1]; 61 | std::strcpy(performer_, cd.performer_); 62 | label_ = new char[std::strlen(cd.label_) + 1]; 63 | std::strcpy(label_, cd.label_); 64 | selections_ = cd.selections_; 65 | playtime_ = cd.playtime_; 66 | return *this; 67 | } 68 | } -------------------------------------------------------------------------------- /Chapter13/PE02/cd.h: -------------------------------------------------------------------------------- 1 | // cd.h -- Cd class interface 2 | #ifndef CD_H_ 3 | #define CD_H_ 4 | 5 | // base class 6 | class Cd { // represents a CD disk 7 | public: 8 | Cd(const char* performer, const char* label, int selections, 9 | double playtime); 10 | Cd(const Cd& cd); 11 | Cd(); 12 | virtual ~Cd(); 13 | virtual void Report() const; // reports all CD data 14 | virtual Cd& operator=(const Cd& cd); 15 | private: 16 | char* performer_; 17 | char* label_; 18 | int selections_; // number of selections 19 | double playtime_; // playing time in minutes 20 | }; 21 | 22 | #endif // CD_H_ -------------------------------------------------------------------------------- /Chapter13/PE02/classic.cpp: -------------------------------------------------------------------------------- 1 | // classic.cpp -- implementing the Classic class 2 | #include 3 | #include 4 | #include "classic.h" 5 | 6 | // constructor 7 | Classic::Classic(const char* primary, const char* performer, 8 | const char* label, int selections, double playtime) 9 | : Cd(performer, label, selections, playtime) { 10 | primary_ = new char[std::strlen(primary) + 1]; 11 | std::strcpy(primary_, primary); 12 | 13 | } 14 | 15 | // copy constructor 16 | Classic::Classic(const Classic& classic) 17 | : Cd(classic) { 18 | primary_ = new char[std::strlen(classic.primary_) + 1]; 19 | std::strcpy(primary_, classic.primary_); 20 | } 21 | 22 | // default constructor 23 | Classic::Classic() 24 | : Cd() { 25 | primary_ = new char[5]; 26 | std::strcpy(primary_, "none"); 27 | } 28 | 29 | // destructor 30 | Classic::~Classic() { 31 | delete primary_; 32 | } 33 | 34 | // reports all Classic data 35 | void Classic::Report() const { 36 | std::cout << "The primary is " << primary_ << ".\n"; 37 | Cd::Report(); 38 | } 39 | 40 | // overload assignment operator 41 | Classic& Classic::operator=(const Classic& classic) { 42 | if (this == &classic) { 43 | return *this; 44 | } else { 45 | Cd::operator=(classic); 46 | delete primary_; 47 | primary_ = new char[std::strlen(classic.primary_) + 1]; 48 | std::strcpy(primary_, classic.primary_); 49 | return *this; 50 | } 51 | } -------------------------------------------------------------------------------- /Chapter13/PE02/classic.h: -------------------------------------------------------------------------------- 1 | // classic.h -- Classic class interface 2 | #ifndef CLASSIC_H_ 3 | #define CLASSIC_H_ 4 | 5 | #include "cd.h" 6 | 7 | class Classic : public Cd { 8 | public: 9 | Classic(const char* primary, const char* performer, const char* label, 10 | int selections, double playtime); 11 | Classic(const Classic& classic); 12 | Classic(); 13 | virtual ~Classic(); 14 | virtual void Report() const; 15 | virtual Classic& operator=(const Classic& classic); 16 | private: 17 | char* primary_; 18 | }; 19 | 20 | #endif // CLASSIC_H_ -------------------------------------------------------------------------------- /Chapter13/PE02/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 13.2 2 | #include 3 | #include "cd.h" 4 | #include "classic.h" 5 | 6 | using std::cout; 7 | 8 | void Bravo(const Cd& disk); 9 | 10 | int main() { 11 | Cd c1("Beatles", "Capitol", 14, 35.5); 12 | Classic c2 = Classic("Piano Sonata in B flat, Fantasia in C", 13 | "Alfred Brendel", "Philips", 2, 57.17); 14 | Cd* pcd = &c1; 15 | 16 | cout << "Using object directly:\n"; 17 | c1.Report(); // use Cd method 18 | c2.Report(); // use Classic method 19 | cout << "\n"; 20 | 21 | cout << "Using type cd* pointer to objects:\n"; 22 | pcd->Report(); // use Cd method for cd object 23 | pcd = &c2; 24 | pcd->Report(); // use Classic method for classic object 25 | cout << "\n"; 26 | 27 | cout << "Calling a function with a Cd reference argument:\n"; 28 | Bravo(c1); 29 | Bravo(c2); 30 | cout << "\n"; 31 | 32 | cout << "Testing assignment:\n"; 33 | Classic copy; 34 | copy = c2; 35 | copy.Report(); 36 | 37 | return 0; 38 | } 39 | 40 | void Bravo(const Cd& disk) { 41 | disk.Report(); 42 | } -------------------------------------------------------------------------------- /Chapter13/PE03/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = -Wall 3 | LDFLAGS = 4 | OBJFILES = main.o dma.o 5 | TARGET = PE03 6 | 7 | all: $(TARGET) 8 | 9 | $(TARGET): $(OBJFILES) 10 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS) 11 | 12 | clean: 13 | rm -f $(OBJFILES) $(TARGET) -------------------------------------------------------------------------------- /Chapter13/PE03/dma.h: -------------------------------------------------------------------------------- 1 | // dma.h -- inheritance and dynamic memory allocation 2 | #ifndef DMA_H_ 3 | #define DMA_H_ 4 | 5 | #include 6 | 7 | // base class 8 | class DMAABC { 9 | public: 10 | DMAABC(const char* l = "null", int r = 0); 11 | DMAABC(const DMAABC& abcs); 12 | virtual ~DMAABC(); 13 | DMAABC& operator=(const DMAABC& abcs); 14 | virtual void View() = 0; 15 | friend std::ostream& operator<<(std::ostream& os, const DMAABC& abcs); 16 | protected: 17 | char* label; 18 | int rating; 19 | }; 20 | 21 | // class using DMA 22 | class baseDMA : public DMAABC { 23 | public: 24 | baseDMA(const char* l = "null", int r = 0); 25 | baseDMA(const baseDMA& bs); 26 | virtual ~baseDMA(); 27 | baseDMA& operator=(const baseDMA& bs); 28 | virtual void View(); 29 | friend std::ostream& operator<<(std::ostream& os, const baseDMA& bs); 30 | }; 31 | 32 | // derived class without DMA 33 | // no destructor needed 34 | // uses implicit copy constructor 35 | // uses implicit assignment operator 36 | class lacksDMA : public DMAABC { 37 | public: 38 | lacksDMA(const char* c = "blank", const char* l = "null", int r = 0); 39 | lacksDMA(const char* c, const DMAABC& ls); 40 | virtual void View(); 41 | friend std::ostream& operator<<(std::ostream& os, const lacksDMA& ls); 42 | private: 43 | enum { COL_LEN = 40 }; 44 | char color[COL_LEN]; 45 | }; 46 | 47 | // derived class with DMA 48 | class hasDMA : public DMAABC { 49 | public: 50 | hasDMA(const char* s = "none", const char* l = "null", int r = 0); 51 | hasDMA(const char* s, const DMAABC& hs); 52 | hasDMA(const hasDMA& hs); 53 | ~hasDMA(); 54 | hasDMA& operator=(const hasDMA& hs); 55 | virtual void View(); 56 | friend std::ostream& operator<<(std::ostream& os, const hasDMA& hs); 57 | private: 58 | char* style; 59 | }; 60 | 61 | #endif -------------------------------------------------------------------------------- /Chapter13/PE03/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 13.3 2 | // usedma.cpp -- inheritance, friends and DMA 3 | // compile with dma.cpp 4 | #include 5 | #include "dma.h" 6 | 7 | const int NUMDMA = 4; 8 | 9 | int main() { 10 | using std::cout; 11 | using std::endl; 12 | 13 | DMAABC* pDMA[NUMDMA]; 14 | pDMA[0] = new baseDMA("portabelly", 8); 15 | pDMA[1] = new lacksDMA("red", "Blimpo", 4); 16 | pDMA[2] = new hasDMA("Mercator", "Buffalo Keys", 5); 17 | pDMA[3] = new baseDMA("2nd portabelly", 12); 18 | 19 | for (int i = 0; i < NUMDMA; ++i) { 20 | pDMA[i]->View(); 21 | cout << endl; 22 | } 23 | cout << "=========================================\n"; 24 | 25 | for (int i = 0; i < NUMDMA; ++i) { 26 | delete pDMA[i]; 27 | } 28 | 29 | cout << "Test assignment operators and operator<<\n"; 30 | baseDMA obj1; 31 | obj1 = baseDMA("portabelly", 8); 32 | cout << obj1 << endl; 33 | lacksDMA obj2; 34 | obj2 = lacksDMA("red", "Blimpo", 4); 35 | cout << obj2 << endl; 36 | hasDMA obj3; 37 | obj3 = hasDMA("Mercator", "Buffalo Keys", 5); 38 | cout << obj3 << endl; 39 | 40 | cout << "=========================================\n"; 41 | cout << "Test copy constructors\n"; 42 | baseDMA obj4 = obj1; 43 | cout << obj4 << endl; 44 | lacksDMA obj5 = obj2; 45 | cout << obj5 << endl; 46 | hasDMA obj6 = obj3; 47 | cout << obj6 << endl; 48 | 49 | cout << "=========================================\n"; 50 | cout << "Test constructors with DMAABC\n"; 51 | cout << "The following two functions are never used, becasue it is not\n" 52 | << "allowed to create an object of abstract class type.\n"; 53 | cout << "lacksDMA::lacksDMA(const char* c, const DMAABC& ls) : DMAABC(ls)\n"; 54 | cout << "hasDMA::hasDMA(const char* s, const DMAABC& hs) : DMAABC(hs)\n"; 55 | 56 | cout << "Done.\n"; 57 | 58 | return 0; 59 | } -------------------------------------------------------------------------------- /Chapter13/PE04/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = -Wall 3 | LDFLAGS = 4 | OBJFILES = main.o port.o vintageport.o 5 | TARGET = PE04 6 | 7 | all: $(TARGET) 8 | 9 | $(TARGET): $(OBJFILES) 10 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS) 11 | 12 | clean: 13 | rm -f $(OBJFILES) $(TARGET) -------------------------------------------------------------------------------- /Chapter13/PE04/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 13.4 2 | #include 3 | #include "port.h" 4 | #include "vintageport.h" 5 | 6 | int main() { 7 | // b. Certain methods are redefined because 8 | // we want to define differently. 9 | // Certain methods are not redefined because 10 | // they are inherited from class Port. 11 | 12 | // c. A derived class doesn't inherit the 13 | // base-class constructors, destructors, 14 | // and assignment operators. 15 | // Friends are not inherited eigher. 16 | 17 | using std::cout; 18 | using std::endl; 19 | 20 | Port obj1 = Port("Gallo", "tawny", 20); 21 | Port obj2 = obj1; 22 | Port obj3; 23 | obj3 = obj1; 24 | 25 | obj2 += 10; 26 | obj3 -= 10; 27 | 28 | cout << obj1 << endl; 29 | cout << obj2 << endl; 30 | obj3.Show(); 31 | cout << endl; 32 | 33 | VintagePort obj4 = VintagePort("45 Cockburn", 40, "Old Velvet", 1888); 34 | VintagePort obj5 = obj4; 35 | VintagePort obj6; 36 | obj6 = obj4; 37 | obj5 += 10; 38 | obj6 -= 10; 39 | 40 | cout << obj4 << endl; 41 | cout << obj5 << endl; 42 | obj6.Show(); 43 | cout << endl; 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /Chapter13/PE04/port.cpp: -------------------------------------------------------------------------------- 1 | // port.cpp -- implementing the class Port 2 | #include 3 | #include "port.h" 4 | 5 | // constructor and default constructor 6 | Port::Port(const char* br, const char* st, int b) { 7 | brand = new char[std::strlen(br) + 1]; 8 | std::strcpy(brand, br); 9 | std::strcpy(style, st); 10 | bottles = b; 11 | } 12 | 13 | // copy constructor 14 | Port::Port(const Port& p) { 15 | brand = new char[std::strlen(p.brand) + 1]; 16 | std::strcpy(brand, p.brand); 17 | std::strcpy(style, p.style); 18 | bottles = p.bottles; 19 | } 20 | 21 | // overload assignment operator 22 | Port& Port::operator=(const Port& p) { 23 | if (this == &p) { 24 | return *this; 25 | } else { 26 | delete[] brand; 27 | brand = new char[std::strlen(p.brand) + 1]; 28 | std::strcpy(brand, p.brand); 29 | std::strcpy(style, p.style); 30 | bottles = p.bottles; 31 | return *this; 32 | } 33 | } 34 | 35 | // overload operator+= 36 | Port& Port::operator+=(int b) { 37 | bottles += b; 38 | return *this; 39 | } 40 | 41 | // overload operator-= 42 | Port& Port::operator-=(int b) { 43 | if (bottles >= b) { 44 | bottles -= b; 45 | } else { 46 | std::cout << "b is larger than the number of bottles. Set to 0"; 47 | bottles = 0; 48 | } 49 | return *this; 50 | } 51 | 52 | // function Show 53 | void Port::Show() const { 54 | std::cout << "Brand: " << brand << std::endl; 55 | std::cout << "Kind: " << style << std::endl; 56 | std::cout << "Bottles: " << bottles << std::endl; 57 | } 58 | 59 | // overload operator<< 60 | ostream& operator<<(ostream& os, const Port& p) { 61 | std::cout << p.brand << ", " << p.style << ", " << p.bottles; 62 | return os; 63 | } -------------------------------------------------------------------------------- /Chapter13/PE04/port.h: -------------------------------------------------------------------------------- 1 | // port.h -- class Port interface 2 | #ifndef PORT_H_ 3 | #define PORT_H_ 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Port { 10 | public: 11 | Port(const char* br = "none", const char* st = "none", int b = 0); 12 | Port(const Port& p); // copy constructor 13 | virtual ~Port() { delete[] brand; } 14 | Port& operator=(const Port& p); 15 | Port& operator+=(int b); // adds b to bottles 16 | Port& operator-=(int b); // subtracts b from bottles, if available 17 | int BottleCount() const { return bottles; } 18 | virtual void Show() const; 19 | friend ostream& operator<<(ostream& os, const Port& p); 20 | private: 21 | char* brand; 22 | char style[20]; // i.e., tawny, ruby, vintage 23 | int bottles; 24 | }; 25 | 26 | #endif // PORT_H_ -------------------------------------------------------------------------------- /Chapter13/PE04/vintageport.cpp: -------------------------------------------------------------------------------- 1 | // vintageport.cpp -- implementing class VintagePort 2 | #include "vintageport.h" 3 | #include 4 | 5 | // default constructor 6 | VintagePort::VintagePort() : Port("none", "vintage", 0) { 7 | nickname = new char[10]; 8 | std::strcpy(nickname, "The Noble"); 9 | year = 0; 10 | } 11 | 12 | // constructor 13 | VintagePort::VintagePort(const char* br, int b, const char* nn, int y) 14 | : Port(br, "vintage", b) { 15 | nickname = new char[std::strlen(nn)]; 16 | std::strcpy(nickname, nn); 17 | year = y; 18 | } 19 | 20 | // copy constructor 21 | VintagePort::VintagePort(const VintagePort& vp) : Port(vp) { 22 | nickname = new char[std::strlen(vp.nickname)]; 23 | std::strcpy(nickname, vp.nickname); 24 | year = vp.year; 25 | } 26 | 27 | // overload assignment operator 28 | VintagePort& VintagePort::operator=(const VintagePort& vp) { 29 | if (this == &vp) { 30 | return *this; 31 | } else { 32 | delete[] nickname; 33 | Port::operator=(vp); 34 | nickname = new char[std::strlen(vp.nickname)]; 35 | std::strcpy(nickname, vp.nickname); 36 | year = vp.year; 37 | return *this; 38 | } 39 | } 40 | 41 | // function Show 42 | void VintagePort::Show() const { 43 | Port::Show(); 44 | std::cout << "Nickname: " << nickname << std::endl; 45 | std::cout << "Year: " << year << std::endl; 46 | } 47 | 48 | // overload operator<< 49 | ostream& operator<<(ostream& os, const VintagePort& vp) { 50 | os << (const Port&) vp; 51 | os << ", " << vp.nickname << ", " << vp.year; 52 | return os; 53 | } -------------------------------------------------------------------------------- /Chapter13/PE04/vintageport.h: -------------------------------------------------------------------------------- 1 | // vintageport.h -- class VintagePort interface 2 | #ifndef VINTAGEPORT_H_ 3 | #define VINTAGEPORT_H_ 4 | 5 | #include 6 | #include "port.h" 7 | 8 | class VintagePort : public Port { // style necessarily = "vintage" 9 | public: 10 | VintagePort(); 11 | VintagePort(const char* br, int b, const char* nn, int y); 12 | VintagePort(const VintagePort& vp); 13 | virtual ~VintagePort() { delete[] nickname; } 14 | VintagePort& operator=(const VintagePort& vp); 15 | virtual void Show() const; 16 | friend ostream& operator<<(ostream& os, const VintagePort& vp); 17 | private: 18 | char* nickname; // i.e., "The Noble" or "Old Velvet", etc. 19 | int year; // vintage year 20 | }; 21 | 22 | #endif // VINTAGEPORT_H_ -------------------------------------------------------------------------------- /Chapter14/PE01/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = -Wall 3 | LDFLAGS = 4 | OBJFILES = main.o wine.o 5 | TARGET = PE01 6 | 7 | all: $(TARGET) 8 | 9 | $(TARGET): $(OBJFILES) 10 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS) 11 | 12 | clean: 13 | rm -f $(OBJFILES) $(TARGET) -------------------------------------------------------------------------------- /Chapter14/PE01/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 14.1 2 | // pe14-1.cpp -- using Wine class with containment 3 | #include 4 | #include "pairs.h" 5 | #include "wine.h" 6 | 7 | int main () { 8 | using std::cin; 9 | using std::cout; 10 | using std::endl; 11 | 12 | cout << "Enter name of wine: "; 13 | char lab[50]; 14 | cin.getline(lab, 50); 15 | cout << "Enter number of years: "; 16 | int yrs; 17 | cin >> yrs; 18 | 19 | Wine holding(lab, yrs); // store label, years, give arrays yrs elements 20 | holding.GetBottles(); // solicit input for year, bottle count 21 | holding.Show(); // display object contents 22 | 23 | const int YRS = 3; 24 | int y[YRS] = { 1993, 1995, 1998 }; 25 | int b[YRS] = { 48, 60, 72 }; 26 | // create new object, initialize using data in arrays y and b 27 | Wine more("Gushing Grape Red", YRS, y, b); 28 | more.Show(); 29 | cout << "Total bottles for " << more.Label() // use Label() method 30 | << ": " << more.sum() << endl; // use sum() method 31 | cout << "Bye\n"; 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Chapter14/PE01/pairs.h: -------------------------------------------------------------------------------- 1 | // pairs.h -- defining and using a Pair template 2 | #ifndef PAIRS_H_ 3 | #define PAIRS_H_ 4 | 5 | #include 6 | #include 7 | 8 | template 9 | class Pair { 10 | public: 11 | Pair(const T1& aval, const T2& bval) : a(aval), b(bval) {} 12 | Pair() {} 13 | T1& first(); 14 | T2& second(); 15 | T1 first() const { return a; } 16 | T2 second() const { return b; } 17 | private: 18 | T1 a; 19 | T2 b; 20 | }; 21 | 22 | template 23 | T1& Pair::first() { 24 | return a; 25 | } 26 | 27 | template 28 | T2& Pair::second() { 29 | return b; 30 | } 31 | 32 | #endif // PAIRS_H_ -------------------------------------------------------------------------------- /Chapter14/PE01/wine.cpp: -------------------------------------------------------------------------------- 1 | // wine.cpp -- implementing class Wine 2 | #include "wine.h" 3 | 4 | // initialize label to l, number of years to y, 5 | // vintage years to yr[], bottles to bot[] 6 | Wine::Wine(const char* l, int y, const int yr[], const int bot[]) 7 | : label_(l), num_years_(y), 8 | years_bottles_(ArrayInt(yr, y), ArrayInt(bot, y)) {} 9 | 10 | // initialize label to l, number of year to y, 11 | // create array objects of length y 12 | Wine::Wine(const char* l, int y) 13 | : label_(l), num_years_(y), 14 | years_bottles_(ArrayInt(y), ArrayInt(y)){} 15 | 16 | void Wine::GetBottles() { 17 | using std::cin; 18 | using std::cout; 19 | cout << "Enter " << label_ << " data for " << num_years_ << " year(s):\n"; 20 | for (int i = 0; i < num_years_; ++i) { 21 | cout << "Enter year: "; 22 | cin >> years_bottles_.first()[i]; 23 | cout << "Enter bottles for that year: "; 24 | cin >> years_bottles_.second()[i]; 25 | } 26 | } 27 | 28 | std::string Wine::Label() const { 29 | return label_; 30 | } 31 | 32 | int Wine::sum() const { 33 | return years_bottles_.second().sum(); 34 | } 35 | 36 | void Wine::Show() const { 37 | using std::cout; 38 | using std::endl; 39 | cout << "Wine: " << label_ << endl; 40 | cout << "\tYear\tBottles\n"; 41 | for (int i = 0; i < num_years_; ++i) { 42 | cout << "\t" << years_bottles_.first()[i]; 43 | cout << "\t" << years_bottles_.second()[i]; 44 | cout << endl; 45 | } 46 | } -------------------------------------------------------------------------------- /Chapter14/PE01/wine.h: -------------------------------------------------------------------------------- 1 | // wine.h -- class Wine interface 2 | #ifndef WINE_H_ 3 | #define WINE_H_ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "pairs.h" 10 | 11 | class Wine { 12 | public: 13 | Wine(const char* l, int y, const int yr[], const int bot[]); 14 | Wine(const char* l, int y); 15 | 16 | void GetBottles(); 17 | std::string Label() const; 18 | int sum() const; 19 | void Show() const; 20 | private: 21 | typedef std::valarray ArrayInt; 22 | typedef Pair PairArray; 23 | std::string label_; 24 | int num_years_; 25 | PairArray years_bottles_; 26 | }; 27 | 28 | #endif // WINE_H_ -------------------------------------------------------------------------------- /Chapter14/PE02/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = 3 | LDFLAGS = 4 | OBJFILES = main.o wine.o 5 | TARGET = PE02 6 | 7 | all: $(TARGET) 8 | 9 | $(TARGET): $(OBJFILES) 10 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS) 11 | 12 | clean: 13 | rm -f $(OBJFILES) $(TARGET) -------------------------------------------------------------------------------- /Chapter14/PE02/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 14.1 2 | // pe14-2.cpp -- using Wine class with containment 3 | #include 4 | #include "pairs.h" 5 | #include "wine.h" 6 | 7 | int main () { 8 | using std::cin; 9 | using std::cout; 10 | using std::endl; 11 | 12 | cout << "Enter name of wine: "; 13 | char lab[50]; 14 | cin.getline(lab, 50); 15 | cout << "Enter number of years: "; 16 | int yrs; 17 | cin >> yrs; 18 | 19 | Wine holding(lab, yrs); // store label, years, give arrays yrs elements 20 | holding.GetBottles(); // solicit input for year, bottle count 21 | holding.Show(); // display object contents 22 | 23 | const int YRS = 3; 24 | int y[YRS] = { 1993, 1995, 1998 }; 25 | int b[YRS] = { 48, 60, 72 }; 26 | // create new object, initialize using data in arrays y and b 27 | Wine more("Gushing Grape Red", YRS, y, b); 28 | more.Show(); 29 | cout << "Total bottles for " << more.Label() // use Label() method 30 | << ": " << more.sum() << endl; // use sum() method 31 | cout << "Bye\n"; 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Chapter14/PE02/pairs.h: -------------------------------------------------------------------------------- 1 | // pairs.h -- defining and using a Pair template 2 | #ifndef PAIRS_H_ 3 | #define PAIRS_H_ 4 | 5 | #include 6 | #include 7 | 8 | template 9 | class Pair { 10 | public: 11 | Pair(const T1& aval, const T2& bval) : a(aval), b(bval) {} 12 | Pair() {} 13 | T1& first(); 14 | T2& second(); 15 | T1 first() const { return a; } 16 | T2 second() const { return b; } 17 | private: 18 | T1 a; 19 | T2 b; 20 | }; 21 | 22 | template 23 | T1& Pair::first() { 24 | return a; 25 | } 26 | 27 | template 28 | T2& Pair::second() { 29 | return b; 30 | } 31 | 32 | #endif // PAIRS_H_ -------------------------------------------------------------------------------- /Chapter14/PE02/wine.cpp: -------------------------------------------------------------------------------- 1 | // wine.cpp -- implementing class Wine 2 | #include "wine.h" 3 | 4 | // initialize label to l, number of years to y, 5 | // vintage years to yr[], bottles to bot[] 6 | Wine::Wine(const char* l, int y, const int yr[], const int bot[]) 7 | : std::string(l), num_years_(y), 8 | PairArray(ArrayInt(yr, y), ArrayInt(bot, y)) {} 9 | 10 | // initialize label to l, number of year to y, 11 | // create array objects of length y 12 | Wine::Wine(const char* l, int y) 13 | : std::string(l), num_years_(y), 14 | PairArray(ArrayInt(y), ArrayInt(y)){} 15 | 16 | void Wine::GetBottles() { 17 | using std::cin; 18 | using std::cout; 19 | cout << "Enter " << (const std::string&) *this 20 | << " data for " << num_years_ << " year(s):\n"; 21 | for (int i = 0; i < num_years_; ++i) { 22 | cout << "Enter year: "; 23 | cin >> PairArray::first()[i]; 24 | cout << "Enter bottles for that year: "; 25 | cin >> PairArray::second()[i]; 26 | } 27 | } 28 | 29 | std::string Wine::Label() const { 30 | return (const std::string&) *this; 31 | } 32 | 33 | int Wine::sum() const { 34 | return PairArray::second().sum(); 35 | } 36 | 37 | void Wine::Show() const { 38 | using std::cout; 39 | using std::endl; 40 | cout << "Wine: " << (const std::string&) *this << endl; 41 | cout << "\tYear\tBottles\n"; 42 | for (int i = 0; i < num_years_; ++i) { 43 | cout << "\t" << PairArray::first()[i]; 44 | cout << "\t" << PairArray::second()[i]; 45 | cout << endl; 46 | } 47 | } -------------------------------------------------------------------------------- /Chapter14/PE02/wine.h: -------------------------------------------------------------------------------- 1 | // wine.h -- class Wine interface 2 | #ifndef WINE_H_ 3 | #define WINE_H_ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "pairs.h" 10 | 11 | class Wine : private std::string, 12 | private Pair< std::valarray, std::valarray > { 13 | public: 14 | Wine(const char* l, int y, const int yr[], const int bot[]); 15 | Wine(const char* l, int y); 16 | 17 | void GetBottles(); 18 | std::string Label() const; 19 | int sum() const; 20 | void Show() const; 21 | private: 22 | typedef std::valarray ArrayInt; 23 | typedef Pair PairArray; 24 | int num_years_; 25 | }; 26 | 27 | #endif // WINE_H_ -------------------------------------------------------------------------------- /Chapter14/PE03/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = -Wall 3 | LDFLAGS = 4 | OBJFILES = main.o worker.o 5 | TARGET = PE03 6 | 7 | all: $(TARGET) 8 | 9 | $(TARGET): $(OBJFILES) 10 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS) 11 | 12 | clean: 13 | rm -f $(OBJFILES) $(TARGET) -------------------------------------------------------------------------------- /Chapter14/PE03/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 14.3 2 | #include 3 | #include "queuetp.h" 4 | #include "worker.h" 5 | 6 | const int WORKERSIZE = 3; 7 | 8 | int main() { 9 | using std::cout; 10 | using std::endl; 11 | 12 | Worker* ptrWorker[WORKERSIZE]; 13 | for (int i = 0; i < WORKERSIZE; ++i) { 14 | ptrWorker[i] = new Worker(); 15 | ptrWorker[i]->Set(); 16 | } 17 | 18 | for (int i = 0; i < WORKERSIZE; ++i) { 19 | ptrWorker[i]->Show(); 20 | } 21 | 22 | cout << endl; 23 | QueueTP queueWorker(WORKERSIZE); 24 | cout << "Is the queue empty?" << endl; 25 | cout << (queueWorker.isempty() ? "True" : "False") << endl; 26 | 27 | for (int i = 0; i < WORKERSIZE; ++i) { 28 | queueWorker.enqueue(*ptrWorker[i]); 29 | } 30 | cout << "What is number of elements in the queue?" << endl; 31 | cout << queueWorker.queuecount() << endl; 32 | cout << "Is the queue full?" << endl; 33 | cout << (queueWorker.isfull() ? "True" : "False") << endl; 34 | 35 | for (int i = 0; i < WORKERSIZE; ++i) { 36 | delete ptrWorker[i]; 37 | } 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Chapter14/PE03/queuetp.h: -------------------------------------------------------------------------------- 1 | // queuetp.h -- template class queuetp 2 | #ifndef QUEUETP_H_ 3 | #define QUEUETP_H_ 4 | 5 | template 6 | class QueueTP { 7 | public: 8 | QueueTP(int qs = Q_SIZE); 9 | ~QueueTP(); 10 | bool isempty() const; 11 | bool isfull() const; 12 | int queuecount() const; 13 | bool enqueue(const Type& val); 14 | bool dequeue(Type& val); 15 | private: 16 | enum { Q_SIZE = 10 }; 17 | struct Node { 18 | Type currVal; 19 | Node* next; 20 | }; 21 | Node* front; // pointer to front of QueueTP 22 | Node* rear; // pointer to rear of QueueTP 23 | int numElements; // current number of QueueTP 24 | const int qsize; // maximum number of QueueTP 25 | }; 26 | 27 | template 28 | QueueTP::QueueTP(int qs) : qsize(qs) { 29 | front = rear = NULL; 30 | numElements = 0; 31 | } 32 | 33 | template 34 | QueueTP::~QueueTP() { 35 | Node* temp; 36 | while (front != NULL) { 37 | temp = front; 38 | front = front->next; 39 | delete temp; 40 | } 41 | } 42 | 43 | template 44 | bool QueueTP::isempty() const { 45 | return numElements == 0; 46 | } 47 | 48 | template 49 | bool QueueTP::isfull() const { 50 | return numElements == qsize; 51 | } 52 | 53 | template 54 | int QueueTP::queuecount() const { 55 | return numElements; 56 | } 57 | 58 | template 59 | bool QueueTP::enqueue(const Type& val) { 60 | if (isfull()) { 61 | return false; 62 | } else { 63 | Node* temp = new Node; 64 | temp->currVal = val; 65 | temp->next = NULL; 66 | if (front == NULL) { 67 | front = rear = temp; 68 | } else { 69 | rear->next = temp; 70 | rear = temp; 71 | } 72 | ++numElements; 73 | return true; 74 | } 75 | } 76 | 77 | template 78 | bool QueueTP::dequeue(Type& val) { 79 | if (isempty()) { 80 | return false; 81 | } else { 82 | val = front->currVal; 83 | Node* temp; 84 | temp = front; 85 | front = front->next; 86 | delete temp; 87 | --numElements; 88 | return true; 89 | } 90 | } 91 | 92 | #endif // QUEUETP_H_ -------------------------------------------------------------------------------- /Chapter14/PE03/worker.cpp: -------------------------------------------------------------------------------- 1 | // worker.cpp -- implementing class Worker 2 | #include "worker.h" 3 | 4 | Worker::Worker(const std::string& s, long n) : fullname(s), id(n) {} 5 | 6 | Worker::Worker() : fullname("no one"), id(0L) {} 7 | 8 | Worker::~Worker() {} 9 | 10 | void Worker::Set() { 11 | std::cout << "Enter worker's full name: "; 12 | std::getline(std::cin, fullname); 13 | std::cout << "Enter worker's ID: "; 14 | std::cin >> id; 15 | while (std::cin.get() != '\n') { 16 | continue; 17 | } 18 | } 19 | 20 | void Worker::Show() const { 21 | std::cout << "Name: " << fullname << std::endl; 22 | std::cout << "Employee ID: " << id << std::endl; 23 | } -------------------------------------------------------------------------------- /Chapter14/PE03/worker.h: -------------------------------------------------------------------------------- 1 | // worker.h -- class Worker interface 2 | #ifndef WORKER_H_ 3 | #define WORKER_H_ 4 | 5 | #include 6 | #include 7 | 8 | class Worker { 9 | public: 10 | Worker(const std::string& s, long n); 11 | Worker(); 12 | ~Worker(); 13 | void Set(); 14 | void Show() const; 15 | private: 16 | std::string fullname; 17 | long id; 18 | }; 19 | 20 | #endif // WORKER_H_ -------------------------------------------------------------------------------- /Chapter14/PE04/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = -Wall -Wno-comment 3 | LDFLAGS = 4 | OBJFILES = main.o person.o gunslinger.o pokerplayer.o baddude.o 5 | TARGET = PE04 6 | 7 | all: $(TARGET) 8 | 9 | $(TARGET): $(OBJFILES) 10 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS) 11 | 12 | clean: 13 | rm -f $(OBJFILES) $(TARGET) 14 | -------------------------------------------------------------------------------- /Chapter14/PE04/baddude.cpp: -------------------------------------------------------------------------------- 1 | // baddude.cpp -- implementing class BadDude 2 | #include 3 | #include "baddude.h" 4 | 5 | BadDude::BadDude(std::string firstName, std::string lastName, 6 | double drawTime, int numNotches) 7 | : Person(firstName, lastName), 8 | Gunslinger(firstName, lastName, drawTime, numNotches) {} 9 | 10 | BadDude::BadDude() : Person(), Gunslinger() {} 11 | 12 | double BadDude::Gdraw() const { 13 | return Gunslinger::Draw(); 14 | } 15 | 16 | int BadDude::Cdraw() const { 17 | return PokerPlayer::Draw(); 18 | } 19 | 20 | void BadDude::Show() const { 21 | Person::Data(); 22 | Gunslinger::Data(); 23 | std::cout << "Bad dude's draw time: " << Gdraw() << std::endl; 24 | std::cout << "The next card drawn: " << Cdraw() << std::endl; 25 | } -------------------------------------------------------------------------------- /Chapter14/PE04/baddude.h: -------------------------------------------------------------------------------- 1 | // baddude.h -- class BadDude interface 2 | #ifndef BADDUDE_H_ 3 | #define BADDUDE_H_ 4 | 5 | #include "gunslinger.h" 6 | #include "pokerplayer.h" 7 | 8 | class BadDude : public Gunslinger, public PokerPlayer { 9 | public: 10 | BadDude(std::string firstName, std::string lastName, 11 | double drawTime, int numNotches); 12 | BadDude(); 13 | double Gdraw() const; 14 | int Cdraw() const; 15 | virtual void Show() const; 16 | }; 17 | 18 | #endif // BADDUDE_H_ -------------------------------------------------------------------------------- /Chapter14/PE04/gunslinger.cpp: -------------------------------------------------------------------------------- 1 | // gunslinger.cpp -- implementing class Gunslinger 2 | #include 3 | #include "gunslinger.h" 4 | 5 | Gunslinger::Gunslinger(std::string firstName, std::string lastName, 6 | double drawTime, int numNotches) 7 | : Person(firstName, lastName), drawTime_(drawTime), 8 | numNotches_(numNotches) {} 9 | 10 | Gunslinger::Gunslinger(Person& person, double drawTime, int numNotches) 11 | : Person(person), drawTime_(drawTime), numNotches_(numNotches) {} 12 | 13 | Gunslinger::Gunslinger(double drawTime, int numNotches) 14 | : Person(), drawTime_(drawTime), numNotches_(numNotches) {} 15 | 16 | Gunslinger::~Gunslinger() {} 17 | 18 | double Gunslinger::Draw() const { 19 | return drawTime_; 20 | } 21 | 22 | void Gunslinger::Set() { 23 | Person::Set(); 24 | Get(); 25 | } 26 | 27 | void Gunslinger::Show() const { 28 | Person::Data(); 29 | std::cout << "Draw time: " << drawTime_ << std::endl; 30 | std::cout << "Number of notches: " << numNotches_ << std::endl; 31 | } 32 | 33 | void Gunslinger::Get() { 34 | std::cout << "Enter draw time: "; 35 | std::cin >> drawTime_; 36 | std::cout << "Enter the number of notches: "; 37 | std::cin >> numNotches_; 38 | while (std::cin.get() != '\n') { 39 | continue; 40 | } 41 | } 42 | 43 | void Gunslinger::Data() const { 44 | std::cout << "Gunslinger's draw time: " << drawTime_ << std::endl; 45 | std::cout << "The number of notches: " << numNotches_ << std::endl; 46 | } -------------------------------------------------------------------------------- /Chapter14/PE04/gunslinger.h: -------------------------------------------------------------------------------- 1 | // gunslinger.h -- class Gunslinger interface 2 | #ifndef GUNSLINGER_H_ 3 | #define GUNSLINGER_H_ 4 | 5 | #include "person.h" 6 | 7 | class Gunslinger : virtual public Person { 8 | public: 9 | Gunslinger(std::string firstName, std::string lastName, 10 | double drawTime = 0.0, int numNotches = 0); 11 | Gunslinger(Person& person, double drawTime = 0.0, int numNotches = 0); 12 | Gunslinger(double drawTime = 0.0, int numNotches = 0); 13 | virtual ~Gunslinger(); 14 | double Draw() const; 15 | virtual void Set(); 16 | virtual void Show() const; 17 | protected: 18 | void Get(); 19 | void Data() const; 20 | private: 21 | double drawTime_; 22 | int numNotches_; 23 | }; 24 | 25 | #endif // GUNSLINGER_H_ -------------------------------------------------------------------------------- /Chapter14/PE04/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 14.4 2 | // Person 3 | // / \ 4 | // Gunslinger PokerPlayer 5 | // \ / 6 | // BadDude 7 | 8 | #include 9 | #include 10 | #include "person.h" 11 | #include "gunslinger.h" 12 | #include "pokerplayer.h" 13 | #include "baddude.h" 14 | 15 | const int SIZE = 5; 16 | 17 | int main() { 18 | using std::cin; 19 | using std::cout; 20 | using std::endl; 21 | using std::strchr; 22 | 23 | Person* ptr[SIZE]; 24 | 25 | for (int i = 0; i < SIZE; ++i) { 26 | char choice; 27 | cout << "Enter the person category:\n" 28 | << "p: Person\tg:Gunslinger\t" 29 | << "o: PokerPlayer\tb:BadDude\t" 30 | << "q: quit\n"; 31 | cin >> choice; 32 | while (strchr("pgobq", choice) == NULL) { 33 | cout << "Please enter a p, g, o, b, q: "; 34 | cin >> choice; 35 | } 36 | if (choice == 'q') { 37 | break; 38 | } else { 39 | switch(choice) { 40 | case 'p': ptr[i] = new Person; break; 41 | case 'g': ptr[i] = new Gunslinger; break; 42 | case 'o': ptr[i] = new PokerPlayer; break; 43 | case 'b': ptr[i] = new BadDude; break; 44 | } 45 | cin.get(); 46 | ptr[i]->Set(); 47 | } 48 | } 49 | 50 | cout << "\nHere are results:\n"; 51 | for (int i = 0; i < SIZE; ++i) { 52 | cout << endl; 53 | ptr[i]->Show(); 54 | } 55 | 56 | for (int i = 0; i < SIZE; ++i) { 57 | delete ptr[i]; 58 | } 59 | cout << "Bye.\n"; 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /Chapter14/PE04/person.cpp: -------------------------------------------------------------------------------- 1 | // person.cpp -- implementing class Person 2 | #include 3 | #include "person.h" 4 | 5 | Person::Person(std::string firstName, std::string lastName) 6 | : firstName_(firstName), lastName_(lastName) {} 7 | 8 | Person::Person(const char* firstName, const char* lastName) 9 | : firstName_(firstName), lastName_(lastName) {} 10 | 11 | Person::Person() : firstName_("none"), lastName_("none") {} 12 | 13 | Person::~Person() {} 14 | 15 | void Person::Set() { 16 | Get(); 17 | } 18 | 19 | void Person::Show() const { 20 | Person::Data(); 21 | } 22 | 23 | void Person::Get() { 24 | std::cout << "Enter the person's first name: "; 25 | std::getline(std::cin, firstName_); 26 | std::cout << "Enter the person's last name: "; 27 | std::getline(std::cin, lastName_); 28 | } 29 | 30 | void Person::Data() const { 31 | std::cout << "First name: " << firstName_ << std::endl; 32 | std::cout << "Last name: " << lastName_ << std::endl; 33 | } -------------------------------------------------------------------------------- /Chapter14/PE04/person.h: -------------------------------------------------------------------------------- 1 | // person.h -- class Person interface 2 | #ifndef PERSON_H_ 3 | #define PERSON_H_ 4 | 5 | #include 6 | 7 | class Person { 8 | public: 9 | Person(std::string firstName, std::string lastName); 10 | Person(const char* firstName, const char* lastName); 11 | Person(); 12 | virtual ~Person(); 13 | virtual void Set(); 14 | virtual void Show() const; 15 | protected: 16 | void Get(); 17 | void Data() const; 18 | private: 19 | std::string firstName_; 20 | std::string lastName_; 21 | }; 22 | 23 | #endif // PERSON_H_ -------------------------------------------------------------------------------- /Chapter14/PE04/pokerplayer.cpp: -------------------------------------------------------------------------------- 1 | // pokerplayer.cpp -- implementing class PokerPlayer 2 | #include 3 | #include 4 | #include "pokerplayer.h" 5 | 6 | PokerPlayer::PokerPlayer(std::string firstName, std::string lastName) 7 | : Person(firstName, lastName) {} 8 | 9 | PokerPlayer::PokerPlayer(Person& person) : Person(person) {} 10 | 11 | PokerPlayer::PokerPlayer() : Person() {} 12 | 13 | PokerPlayer::~PokerPlayer() {} 14 | 15 | int PokerPlayer::Draw() const { 16 | srand(time(0)); 17 | return int(rand()) % 52; 18 | } -------------------------------------------------------------------------------- /Chapter14/PE04/pokerplayer.h: -------------------------------------------------------------------------------- 1 | // pokerplayer.h -- class PokerPlayer interface 2 | #ifndef POKERPLAYER_H_ 3 | #define POKERPLAYER_H_ 4 | 5 | #include "person.h" 6 | 7 | class PokerPlayer : virtual public Person { 8 | public: 9 | PokerPlayer(std::string firstName, std::string lastName); 10 | PokerPlayer(Person& person); 11 | PokerPlayer(); 12 | virtual ~PokerPlayer(); 13 | int Draw() const; 14 | }; 15 | 16 | #endif // POKERPLAYER_H_ -------------------------------------------------------------------------------- /Chapter14/PE05/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = -Wall 3 | LDFLAGS = 4 | OBJFILES = main.o emp.o 5 | TARGET = PE05 6 | 7 | all: $(TARGET) 8 | 9 | $(TARGET): $(OBJFILES) 10 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS) 11 | 12 | clean: 13 | rm -f $(OBJFILES) $(TARGET) -------------------------------------------------------------------------------- /Chapter14/PE05/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 14.5 2 | // useemp1.cpp -- using the abstr_emp classes 3 | #include 4 | #include "emp.h" 5 | using namespace std; 6 | 7 | int main() { 8 | employee em("Trip", "Harris", "Thumper"); 9 | cout << em << endl; 10 | em.ShowAll(); 11 | 12 | manager ma("Amorphia", "Spindragon", "Nuancer", 5); 13 | cout << ma << endl; 14 | ma.ShowAll(); 15 | 16 | fink fi("Matt", "Oggs", "Oiler", "Juno Barr"); 17 | cout << fi << endl; 18 | fi.ShowAll(); 19 | 20 | highfink hf(ma, "Curly Kew"); // recruitment? 21 | hf.ShowAll(); 22 | 23 | cout << "Press a key for next phase:\n"; 24 | cin.get(); 25 | 26 | highfink hf2; 27 | hf2.SetAll(); 28 | 29 | cout << "Using an abstr_emp* pointer:\n"; 30 | abstr_emp* tri[4] = { &em, &fi, &hf, &hf2 }; 31 | for (int i = 0; i < 4; i++) { 32 | tri[i]->ShowAll(); 33 | } 34 | 35 | /* 36 | 1. Why is no assignment operator defined? 37 | The default assignment operators work well. 38 | 39 | 2. Why are ShowAll() and SetAll virtual? 40 | Would like to have different outputs for different classes. 41 | 42 | 3. Why is abstr_emp a virtual base class? 43 | virtual ~abstr_emp() = 0; It is a pure absact base class. 44 | 45 | 4. Why does the highfink class have no data section? 46 | It doesn't need addtional information. It inherits data from bases 47 | classes. 48 | 49 | 5. Why is only one version of operator<<() needed? 50 | All derived classes inherit the operator<<() from the base class. 51 | 52 | 6. What would heppen if the end of the program were replaced with this code? 53 | abstr_emp tri[4] = { em, fi, hf, hf2 }; 54 | for (int i = 0; i < 4, i++) 55 | tri[i].ShowAll(); 56 | abstr_emp is a pure abstract base class, so no objects can be created for 57 | this class. 58 | */ 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /Chapter14/README.md: -------------------------------------------------------------------------------- 1 | # Re-do Questions: 2 | - [ ] Programming Exercise 14.1 3 | - [ ] Programming Exercise 14.2 -------------------------------------------------------------------------------- /Chapter15/PE01/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = 3 | LDFLAGS = 4 | OBJFILES = main.o tv.o 5 | TARGET = PE01 6 | 7 | all: $(TARGET) 8 | 9 | $(TARGET): $(OBJFILES) 10 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS) 11 | 12 | clean: 13 | rm -f $(OBJFILES) $(TARGET) -------------------------------------------------------------------------------- /Chapter15/PE01/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 15.1 2 | //use_tv.cpp -- using the Tv and Remote classes 3 | #include 4 | #include "tv.h" 5 | 6 | int main() { 7 | using std::cout; 8 | 9 | Tv s42; 10 | cout << "Initial settings for 42\" TV:\n"; 11 | s42.settings(); 12 | s42.onoff(); 13 | s42.chanup(); 14 | cout << "\nAdjusted settings for 42\" TV:\n"; 15 | s42.settings(); 16 | 17 | Remote grey; 18 | grey.set_chan(s42, 10); 19 | grey.volup(s42); 20 | grey.volup(s42); 21 | cout << "\n42\" settings after using remote:\n"; 22 | s42.settings(); 23 | 24 | cout << "\nTesting new functions:\n"; 25 | s42.show_remote_mode(grey); 26 | s42.set_remote_mode(grey); 27 | s42.onoff(); 28 | grey.set_remote_mode(s42); 29 | grey.show_remote_mode(); 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /Chapter15/PE01/tv.cpp: -------------------------------------------------------------------------------- 1 | // tv.cpp -- methods for the Tv class (Remote methods are inline) 2 | #include 3 | #include "tv.h" 4 | 5 | bool Tv::volup() { 6 | if (volume < MaxVal) { 7 | volume++; 8 | return true; 9 | } 10 | else { 11 | return false; 12 | } 13 | } 14 | 15 | bool Tv::voldown() { 16 | if (volume > MinVal) { 17 | volume--; 18 | return true; 19 | } 20 | else { 21 | return false; 22 | } 23 | } 24 | 25 | void Tv::chanup() { 26 | if (channel < maxchannel) { 27 | channel++; 28 | } 29 | else { 30 | channel = 1; 31 | } 32 | } 33 | 34 | void Tv::chandown() { 35 | if (channel > 1) { 36 | channel--; 37 | } 38 | else { 39 | channel = maxchannel; 40 | } 41 | } 42 | 43 | void Tv::settings() const { 44 | using std::cout; 45 | using std::endl; 46 | cout << "TV is " << (state == Off? "Off" : "On") << endl; 47 | if (state == On) { 48 | cout << "Volume setting = " << volume << endl; 49 | cout << "Channel setting = " << channel << endl; 50 | cout << "Mode = " << (mode == Antenna ? "Antenna" : "Cable") << endl; 51 | cout << "Input = " << (input == TV ? "TV" : "DVD") << endl; 52 | } 53 | } 54 | 55 | void Remote::set_remote_mode(Tv& t) { 56 | if (t.state == Tv::On) { 57 | remote_mode = (remote_mode == Normal) ? Interactive : Normal; 58 | } else { 59 | std::cout << "The TV is OFF. Cannot set the remote mode.\n"; 60 | } 61 | } 62 | 63 | void Remote::show_remote_mode() const { 64 | std::cout << "Remote mode = " 65 | << (remote_mode == Remote::Normal ? "Normal" : "Interactive") 66 | << std::endl; 67 | } -------------------------------------------------------------------------------- /Chapter15/PE01/tv.h: -------------------------------------------------------------------------------- 1 | // tv.h -- Tv and Remote classes 2 | #ifndef TV_H_ 3 | #define TV_H_ 4 | 5 | #include 6 | 7 | class Remote; 8 | 9 | class Tv { 10 | public: 11 | enum { Off, On }; 12 | enum { MinVal, MaxVal = 20 }; 13 | enum { Antenna, Cable }; 14 | enum { TV, DVD }; 15 | 16 | friend class Remote; // Remote can access Tv private parts 17 | 18 | Tv(int s = Off, int mc = 125) : state(s), volume(5), 19 | maxchannel(mc), channel(2), mode(Cable), input(TV) {} 20 | void onoff() { state = (state == On) ? Off : On; } 21 | bool ison() const { return state == On; } 22 | bool volup(); 23 | bool voldown(); 24 | void chanup(); 25 | void chandown(); 26 | void set_mode() { mode = (mode == Antenna) ? Cable : Antenna; } 27 | void set_input() { input = (input == TV)? DVD : TV; } 28 | void settings() const; // display all settings 29 | 30 | void set_remote_mode(Remote& r); 31 | void show_remote_mode(Remote& r) const; 32 | private: 33 | int state; // on or off 34 | int volume; // assumed to be digitized 35 | int maxchannel; // maximum number of channels 36 | int channel; // current channel setting 37 | int mode; // broadcast or cable 38 | int input; // TV or DVD 39 | }; 40 | 41 | class Remote { 42 | public: 43 | enum { Normal, Interactive }; 44 | 45 | friend class Tv; 46 | 47 | Remote(int m = Tv::TV) : mode(m), remote_mode(Normal) {} 48 | bool volup(Tv& t) { return t.volup(); } 49 | bool voldown(Tv& t) { return t.voldown(); } 50 | void onoff(Tv& t) { t.onoff(); } 51 | void chanup(Tv& t) { t.chanup(); } 52 | void chandown(Tv& t) { t.chandown(); } 53 | void set_chan(Tv& t, int c) { t.channel = c; } 54 | void set_mode(Tv& t) { t.set_mode(); } 55 | void set_input(Tv& t) { t.set_input(); } 56 | 57 | void set_remote_mode(Tv& t); 58 | void show_remote_mode() const; 59 | private: 60 | int mode; // controls TV or DVD 61 | int remote_mode; // Normal or Interactive 62 | }; 63 | 64 | inline void Tv::set_remote_mode(Remote& r) { 65 | r.set_remote_mode(*this); 66 | } 67 | 68 | inline void Tv::show_remote_mode(Remote& r) const { 69 | std::cout << "Remote mode = " 70 | << (r.remote_mode == Remote::Normal ? "Normal" : "Interactive") 71 | << std::endl; 72 | } 73 | 74 | #endif -------------------------------------------------------------------------------- /Chapter15/PE02/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = -Wall 3 | LDFLAGS = 4 | OBJFILES = main.o 5 | TARGET = PE02 6 | 7 | all: $(TARGET) 8 | 9 | $(TARGET): $(OBJFILES) 10 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS) 11 | 12 | clean: 13 | rm -f $(OBJFILES) $(TARGET) -------------------------------------------------------------------------------- /Chapter15/PE02/exc_mean.h: -------------------------------------------------------------------------------- 1 | // exc_mean.h -- exception classes for hmean(), gmean() 2 | #ifndef EXC_MEAN_H_ 3 | #define EXC_MEAN_H_ 4 | 5 | #include 6 | #include 7 | 8 | using std::logic_error; 9 | 10 | class bad_hmean : public logic_error { 11 | public: 12 | explicit bad_hmean() : logic_error("hmean invalid arguments: a = -b\n") {}; 13 | }; 14 | 15 | class bad_gmean : public logic_error { 16 | public: 17 | explicit bad_gmean() : logic_error("gmean() arguments should be >= 0\n") {}; 18 | }; 19 | 20 | #endif // EXC_MEAN_H_ -------------------------------------------------------------------------------- /Chapter15/PE02/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 15.2 2 | #include 3 | #include 4 | #include "exc_mean.h" 5 | 6 | double hmean(double a, double b); 7 | double gmean(double a, double b); 8 | 9 | int main() { 10 | using std::cout; 11 | using std::cin; 12 | using std::endl; 13 | 14 | double x, y, z; 15 | 16 | cout << "Enter two numbers: "; 17 | while (cin >> x >> y) { 18 | try { // start of try block 19 | z = hmean(x,y); 20 | cout << "Harmonic mean of " << x << " and " << y 21 | << " is " << z << endl; 22 | cout << "Geometric mean of " << x << " and " << y 23 | << " is " << gmean(x, y) << endl; 24 | cout << "Enter next set of numbers : "; 25 | } // end of try block 26 | catch (bad_hmean& bg) { // start of catch block 27 | cout << bg.what(); 28 | cout << "Try again.\n"; 29 | continue; 30 | } 31 | catch (bad_gmean& hg) { 32 | cout << hg.what(); 33 | cout << "Sorry, you don't get to play any more.\n"; 34 | break; 35 | } // end of catch block 36 | } 37 | cout << "Bye!\n"; 38 | 39 | return 0; 40 | } 41 | 42 | double hmean(double a, double b) { 43 | if (a == -b) { 44 | throw bad_hmean(); 45 | } 46 | return 2.0 * a * b / (a + b); 47 | } 48 | 49 | double gmean(double a, double b) { 50 | if (a < 0 || b < 0) { 51 | throw bad_gmean(); 52 | } 53 | return std::sqrt(a * b); 54 | } -------------------------------------------------------------------------------- /Chapter15/README.md: -------------------------------------------------------------------------------- 1 | # Re-do Questions: 2 | - [ ] Programming Exercise 15.2 3 | - [ ] Programming Exercise 15.3 -------------------------------------------------------------------------------- /Chapter16/PE01/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = -Wall 3 | LDFLAGS = 4 | OBJFILES = main.o 5 | TARGET = PE01 6 | 7 | all: $(TARGET) 8 | 9 | $(TARGET): $(OBJFILES) 10 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS) 11 | 12 | clean: 13 | rm -f $(OBJFILES) $(TARGET) -------------------------------------------------------------------------------- /Chapter16/PE01/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 16.1 2 | #include "palindrome.h" 3 | 4 | int main() { 5 | string str = getString(); 6 | if (isPalindrome(str)) { 7 | cout << "It is a palindrome.\n"; 8 | } else { 9 | cout << "It is NOT a palindrome.\n"; 10 | } 11 | 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /Chapter16/PE01/palindrome.h: -------------------------------------------------------------------------------- 1 | // palindrome.h -- get string and check palindrome functions 2 | #include 3 | #include 4 | 5 | using std::cout; 6 | using std::cin; 7 | using std::string; 8 | 9 | string getString() { 10 | string str; 11 | cout << "Enter a string:\n"; 12 | cin >> str; 13 | return str; 14 | } 15 | 16 | bool isPalindrome(string& str) { 17 | for (int i = 0, j = str.size() - 1; i <= j; ++i, --j) { 18 | if (str[i] != str[j]) { 19 | return false; 20 | } 21 | } 22 | return true; 23 | } -------------------------------------------------------------------------------- /Chapter16/PE02/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = -Wall 3 | LDFLAGS = 4 | OBJFILES = main.o 5 | TARGET = PE02 6 | 7 | all: $(TARGET) 8 | 9 | $(TARGET): $(OBJFILES) 10 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS) 11 | 12 | clean: 13 | rm -f $(OBJFILES) $(TARGET) -------------------------------------------------------------------------------- /Chapter16/PE02/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 16.2 2 | #include "palindrome.h" 3 | 4 | int main() { 5 | string str = getString(); 6 | if (isPalindrome(str)) { 7 | cout << "It is a palindrome.\n"; 8 | } else { 9 | cout << "It is NOT a palindrome.\n"; 10 | } 11 | 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /Chapter16/PE02/palindrome.h: -------------------------------------------------------------------------------- 1 | // palindrome.h -- get string and check palindrome functions 2 | #include 3 | #include 4 | #include 5 | 6 | using std::cout; 7 | using std::cin; 8 | using std::string; 9 | 10 | string getString() { 11 | string str; 12 | cout << "Enter a string:\n"; 13 | cin >> str; 14 | return str; 15 | } 16 | 17 | bool isPalindrome(string& str) { 18 | int i = 0, j = str.size() - 1; 19 | while(i <= j) { 20 | if (!isalpha(str[i])) { 21 | ++i; 22 | continue; 23 | } 24 | if (!isalpha(str[j])) { 25 | --j; 26 | continue; 27 | } 28 | if (isupper(str[i])) { 29 | str[i] = tolower(str[i]); 30 | } 31 | if (isupper(str[j])) { 32 | str[j] = tolower(str[j]); 33 | } 34 | if (str[i] != str[j]) { 35 | return false; 36 | } 37 | ++i; 38 | --j; 39 | } 40 | return true; 41 | } -------------------------------------------------------------------------------- /Chapter16/PE03/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = -Wall 3 | LDFLAGS = 4 | OBJFILES = hangman.o 5 | TARGET = PE03 6 | 7 | all: $(TARGET) 8 | 9 | $(TARGET): $(OBJFILES) 10 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS) 11 | 12 | clean: 13 | rm -f $(OBJFILES) $(TARGET) -------------------------------------------------------------------------------- /Chapter16/PE03/PE03.txt: -------------------------------------------------------------------------------- 1 | apiary beetle cereal danger ensign florid garage health nsult 2 | jackal keeper loaner manage nonce onset plaid quilt remote 3 | stolid train useful valid whence xenon yearn zippy -------------------------------------------------------------------------------- /Chapter16/PE04/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = -Wall 3 | LDFLAGS = 4 | OBJFILES = main.o 5 | TARGET = PE04 6 | 7 | all: $(TARGET) 8 | 9 | $(TARGET): $(OBJFILES) 10 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS) 11 | 12 | clean: 13 | rm -f $(OBJFILES) $(TARGET) -------------------------------------------------------------------------------- /Chapter16/PE04/main.cpp: -------------------------------------------------------------------------------- 1 | // Programming Exercise 16.4 2 | #include 3 | #include 4 | #include 5 | 6 | using std::cout; 7 | using std::endl; 8 | using std::sort; 9 | using std::set; 10 | 11 | int reduce(long ar[], int n); 12 | void show(long ar[], int n); 13 | 14 | int main() { 15 | long test1[] = { 7, 8, 8, 3, 3, 3, 4, 4, 3, 8 }; 16 | cout << "The reduced size should be 4." << endl; 17 | cout << "The outcome from reduce is " << reduce(test1, 10) << ".\n"; 18 | cout << "After reduce function, the array becomes to\n"; 19 | show(test1, reduce(test1, 10)); 20 | cout << endl; 21 | 22 | long test2[] = { 12, 12, 5, 6, 11, 5, 6, 77, 11, 12 }; 23 | cout << "The reduced size should be 5." << endl; 24 | cout << "The outcome from reduce is " << reduce(test2, 10) << ".\n"; 25 | cout << "After reduce function, the array becomes to\n"; 26 | show(test2, reduce(test2, 10)); 27 | 28 | return 0; 29 | } 30 | 31 | int reduce(long ar[], int n) { 32 | sort(ar, ar + n); 33 | set setAr(ar, ar + n); 34 | int i = 0; 35 | for (auto element : setAr) { 36 | ar[i] = element; 37 | ++i; 38 | } 39 | return setAr.size(); 40 | } 41 | 42 | void show(long ar[], int n) { 43 | for (int i = 0; i < n; ++i) { 44 | cout << ar[i] << " "; 45 | } 46 | cout << endl; 47 | } -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman --------------------------------------------------------------------------------