├── README.md ├── chapter_02 ├── ProgrammingExercisesChapter_2.txt ├── sol-2-1.cpp ├── sol-2-2.cpp ├── sol-2-3.cpp ├── sol-2-4.cpp ├── sol-2-5.cpp ├── sol-2-6.cpp └── sol-2-7.cpp ├── chapter_03 ├── ProgrammingExercisesChapter_3.txt ├── sol-3-1.cpp ├── sol-3-2.cpp ├── sol-3-3.cpp ├── sol-3-4.cpp ├── sol-3-5.cpp ├── sol-3-6.cpp └── sol-3-7.cpp ├── chapter_04 ├── ProgrammingExercisesChapter_4.txt ├── sol-4-01.cpp ├── sol-4-02.cpp ├── sol-4-03.cpp ├── sol-4-04.cpp ├── sol-4-05.cpp ├── sol-4-06.cpp ├── sol-4-07.cpp ├── sol-4-08.cpp ├── sol-4-09.cpp └── sol-4-10.cpp ├── chapter_05 ├── ProgrammingExercisesChapter_5.txt ├── sol-5-01.cpp ├── sol-5-02.cpp ├── sol-5-03.cpp ├── sol-5-04.cpp ├── sol-5-05.cpp ├── sol-5-06.cpp ├── sol-5-07.cpp ├── sol-5-08.cpp ├── sol-5-09.cpp └── sol-5-10.cpp ├── chapter_06 ├── ProgrammingExercisesChapter_6.txt ├── sol-6-01.cpp ├── sol-6-02.cpp ├── sol-6-03.cpp ├── sol-6-04.cpp ├── sol-6-05.cpp ├── sol-6-06.cpp ├── sol-6-07.cpp ├── sol-6-08.cpp ├── sol-6-09.cpp ├── test_6_8.txt └── test_6_9.txt ├── chapter_07 ├── ProgrammingExercisesChapter_7.txt ├── sol-7-01.cpp ├── sol-7-02.cpp ├── sol-7-03.cpp ├── sol-7-04.cpp ├── sol-7-05.cpp ├── sol-7-06.cpp ├── sol-7-07.cpp ├── sol-7-08-1.cpp ├── sol-7-08-2.cpp ├── sol-7-09.cpp └── sol-7-10.cpp ├── chapter_08 ├── ProgrammingExercisesChapter_8.txt ├── sol-8-01.cpp ├── sol-8-02.cpp ├── sol-8-03.cpp ├── sol-8-04.cpp ├── sol-8-05.cpp ├── sol-8-06.cpp └── sol-8-07.cpp ├── chapter_09 ├── ProgrammingExercisesChapter_9.txt ├── sol-9-02.cpp ├── sol-9-03.cpp ├── sol_09_01 │ ├── golf.cpp │ ├── golf.h │ └── sol-9-01.cpp └── sol_09_04 │ ├── sales.cpp │ ├── sales.h │ └── sol-9-04.cpp ├── chapter_10 ├── ProgrammingExercisesChapter_10.txt ├── sol_10_01 │ ├── bank_10.cpp │ ├── bank_10.h │ └── sol-10-01.cpp ├── sol_10_02 │ ├── person_10.cpp │ ├── person_10.h │ └── sol-10-02.cpp ├── sol_10_03 │ ├── golf_10.cpp │ ├── golf_10.h │ └── sol-10-03.cpp ├── sol_10_04 │ ├── sales_10.cpp │ ├── sales_10.h │ └── sol-10-04.cpp ├── sol_10_05 │ ├── sol-10-05.cpp │ ├── stack_10.cpp │ └── stack_10.h ├── sol_10_06 │ ├── move_10.cpp │ ├── move_10.h │ └── sol-10-06.cpp ├── sol_10_07 │ ├── plorg_10.cpp │ ├── plorg_10.h │ └── sol-10-07.cpp └── sol_10_08 │ ├── list_10.cpp │ ├── list_10.h │ └── sol-10-08.cpp ├── chapter_11 ├── ProgrammingExercisesChapter_11.txt ├── sol_11_01 │ ├── sol-11-01.cpp │ ├── vect_11_01.cpp │ └── vect_11_01.h ├── sol_11_02 │ ├── sol-11-02.cpp │ ├── vect_11_02.cpp │ └── vect_11_02.h ├── sol_11_03 │ ├── sol-11-03.cpp │ ├── vect_11_03.cpp │ └── vect_11_03.h ├── sol_11_04 │ ├── mytime_11_04.cpp │ ├── mytime_11_04.h │ └── sol-11-04.cpp ├── sol_11_05 │ ├── sol-11-05.cpp │ ├── stonewt_11_05.cpp │ └── stonewt_11_05.h ├── sol_11_06 │ ├── sol-11-06.cpp │ ├── stonewt_11_06.cpp │ └── stonewt_11_06.h └── sol_11_07 │ ├── complex_11_07.cpp │ ├── complex_11_07.h │ └── sol-11-07.cpp ├── chapter_12 ├── ProgrammingExercisesChapter_12.txt ├── sol_12_01 │ ├── cow_12_01.cpp │ ├── cow_12_01.h │ └── sol-12-01.cpp ├── sol_12_02 │ ├── sol-12-02.cpp │ ├── string_12_02.cpp │ └── string_12_02.h ├── sol_12_03 │ ├── sol-12-03.cpp │ ├── stock_12_03.cpp │ └── stock_12_03.h └── sol_12_04 │ ├── sol-12-04.cpp │ ├── stack_12_04.cpp │ └── stack_12_04.h └── chapter_13 ├── ProgrammingExercisesChapter_11.txt ├── sol_13_01 ├── cd_13_01.cpp ├── cd_13_01.h └── sol_13_01.cpp └── sol_13_02 ├── cd_13_02.cpp ├── cd_13_02.h └── sol_13_02.cpp /README.md: -------------------------------------------------------------------------------- 1 | ###### __Stephen Prata__ 2 | 3 | # C++ Primer Plus 4 | 5 | ###### _Sixth Edition_ 6 | -------------------------------------------------------------------------------- 7 | 8 | This is my solutions of the exercises in the book C++ Primer Plus. 9 | 10 | | Chapter | Solution | 11 | |---------|----------| 12 | |01. Getting Started | No Programming Exercises | 13 | |02. Setting Out to C++|[exercises/chapter_02](https://github.com/gr0mazeka/StephenPrata/tree/master/chapter_02)| 14 | |03. Dealing with Data|[exercises/chapter_03](https://github.com/gr0mazeka/StephenPrata/tree/master/chapter_03)| 15 | |04. Compound Types|[exercises/chapter_04](https://github.com/gr0mazeka/StephenPrata/tree/master/chapter_04)| 16 | |05. Loops and Relational Expressions|[exercises/chapter_05](https://github.com/gr0mazeka/StephenPrata/tree/master/chapter_05)| 17 | |06. Branching Statements and Logical Operators|[exercises/chapter_06](https://github.com/gr0mazeka/StephenPrata/tree/master/chapter_06)| 18 | |07. Functions: C++'S Programming Modules|[exercises/chapter_07](https://github.com/gr0mazeka/StephenPrata/tree/master/chapter_07)| 19 | |08. Adventures in Functions|[exercises/chapter_08](https://github.com/gr0mazeka/StephenPrata/tree/master/chapter_08)| 20 | |09. Memory Models and Namespaces|[exercises/chapter_09](https://github.com/gr0mazeka/StephenPrata/tree/master/chapter_09)| 21 | |10. Objects and Classes|[exercises/chapter_10](https://github.com/gr0mazeka/StephenPrata/tree/master/chapter_10)| 22 | |11. Working with Classes|[exercises/chapter_11](https://github.com/gr0mazeka/StephenPrata/tree/master/chapter_11)| 23 | |12. Classes and Dynamic Memory Allocation|[exercises/chapter_12](https://github.com/gr0mazeka/StephenPrata/tree/master/chapter_12)| 24 | |13. Class Inheritance|[exercises/chapter_13](https://github.com/gr0mazeka/StephenPrata/tree/master/chapter_13)| 25 | |14. Reusing Code in C++|[exercises/chapter_14](https://github.com/gr0mazeka/StephenPrata)| 26 | |15. Friends, Exceptions, and More|[exercises/chapter_15](https://github.com/gr0mazeka/StephenPrata)| 27 | |16. The string Class and the Standard Template Library|[exercises/chapter_16](https://github.com/gr0mazeka/StephenPrata)| 28 | |17. Input, Output, and Files|[exercises/chapter_17](https://github.com/gr0mazeka/StephenPrata)| 29 | |18. Visiting with the New C++ Standard|[exercises/chapter_18](https://github.com/gr0mazeka/StephenPrata)| 30 | -------------------------------------------------------------------------------- /chapter_02/ProgrammingExercisesChapter_2.txt: -------------------------------------------------------------------------------- 1 | S.Prata C++ Primer Plus 6th ed. 2 | ================================================================================ 3 | PROGRAMMING EXERCISES CHAPTER 2 4 | 5 | 6 | 1. Write a C++ program that displays your name and address (or if you value 7 | your privacy, a fictitious name and address). 8 | 9 | 2. Write a C++ program that asks for a distance in furlongs and converts it to 10 | yards. (One furlong is 220 yards.) 11 | 12 | 3. Write a C++ program that uses three user-defined functions (counting main() 13 | as one) and produces the following output: 14 | 15 | Three blind mice 16 | Three blind mice 17 | See how they run 18 | See how they run 19 | 20 | One function, called two times, should produce the first two lines, and the 21 | remaining function, also called twice, should produce the remaining output. 22 | 23 | 4. Write a program that asks the user to enter his or her age. The program then 24 | should display the age in months: 25 | 26 | Enter your age: 29 27 | Your age in months is 384. 28 | 29 | 5. Write a program that has main() call a user-defined function that takes a 30 | Celsius temperature value as an argument and then returns the equivalent 31 | Fahrenheit value. The program should request the Celsius value as input from 32 | the user and display the result, as shown in the following code: 33 | 34 | Please enter a Celsius value: 20 35 | 20 degrees Celsius is 68 degrees Fahrenheit. 36 | 37 | For reference, here is the formula for making the conversion: 38 | 39 | Fahrenheit = 1.8 × degrees Celsius + 32.0 40 | 41 | 6. Write a program that has main() call a user-defined function that takes a 42 | distance in light years as an argument and then returns the distance in 43 | astronomical units. The program should request the light year value as input 44 | from the user and display the result, as shown in the following code: 45 | 46 | Enter the number of light years: 4.2 47 | 4.2 light years = 265608 astronomical units. 48 | 49 | An astronomical unit is the average distance from the earth to the sun 50 | (about 150,000,000 km or 93,000,000 miles), and a light year is the distance 51 | light travels in a year (about 10 trillion kilometers or 6 trillion miles). 52 | (The nearest star after the sun is about 4.2 light years away.) Use type 53 | double (as in Listing 2.4) and this conversion factor: 54 | 55 | 1 light year = 63,240 astronomical units 56 | 57 | 7. Write a program that asks the user to enter an hour value and a minute 58 | value. The main() function should then pass these two values to a type void 59 | function that displays the two values in the format shown in the following 60 | sample run: 61 | 62 | Enter the number of hours: 9 63 | Enter the number of minutes: 28 64 | Time: 9:28 65 | 66 | ================================================================================ 67 | -------------------------------------------------------------------------------- /chapter_02/sol-2-1.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 2.1 ------------------------- 3 | 4 | #include 5 | int main() 6 | { 7 | std::cout << " Name: Antonio\n Address: Italy, Rome" << std::endl; 8 | std::cin.get(); 9 | return 0; 10 | } 11 | -------------------------------------------------------------------------------- /chapter_02/sol-2-2.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 2.2 ------------------------- 3 | 4 | #include 5 | int converts(int f){ return f*220; } 6 | int main() 7 | { 8 | std::cout << "Enter furlongs: "; 9 | int fur; 10 | std::cin >> fur; 11 | std::cout << fur << " furlongs = "<< converts(fur) << " yards" << std::endl; 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /chapter_02/sol-2-3.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 2.3 ------------------------- 3 | 4 | #include 5 | void func_1(){ std::cout << "Three blind mice" << std::endl; } 6 | void func_2(){ std::cout << "See how they run" << std::endl; } 7 | int main() 8 | { 9 | func_1(); 10 | func_1(); 11 | func_2(); 12 | func_2(); 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /chapter_02/sol-2-4.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 2.4 ------------------------- 3 | 4 | #include 5 | int converts(int a){ return a*12; } 6 | int main() 7 | { 8 | std::cout << "Enter your age: "; 9 | int age; 10 | std::cin >> age; 11 | std::cout << "Your age in months is " << converts(age) << std::endl; 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /chapter_02/sol-2-5.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 2.5 ------------------------- 3 | 4 | #include 5 | double converts(int c){ return 1.8*c+32; } 6 | int main() 7 | { 8 | std::cout << "Please enter a Celsius value: "; 9 | int cels; 10 | std::cin >> cels; 11 | std::cout << cels << " degrers Celsium is " << converts(cels) 12 | << " degrees Fahrenheit." << std::endl; 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /chapter_02/sol-2-6.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 2.6 ------------------------- 3 | 4 | #include 5 | double convert(double y){ return y*63240; } 6 | int main() 7 | { 8 | std::cout << "Enter the number of light years: "; 9 | double year; 10 | std::cin >> year; 11 | std::cout << year << " light years = " << convert(year) 12 | << " astronomical units." << std::endl; 13 | return 0; 14 | } 15 | 16 | -------------------------------------------------------------------------------- /chapter_02/sol-2-7.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 2.7 ------------------------- 3 | 4 | #include 5 | void convert(int h, int m) 6 | { std::cout << "Time: " << h << ":" << m << std::endl; } 7 | int main() 8 | { 9 | std::cout << "Enter the number of hours: "; 10 | int hour, min; 11 | std::cin >> hour; 12 | std::cout << "Enter the number of minutes: "; 13 | std::cin >> min; 14 | convert(hour, min); 15 | return 0; 16 | } 17 | 18 | -------------------------------------------------------------------------------- /chapter_03/ProgrammingExercisesChapter_3.txt: -------------------------------------------------------------------------------- 1 | S.Prata C++ Primer Plus 6th ed. 2 | ================================================================================ 3 | PROGRAMMING EXERCISES CHAPTER 3 4 | 5 | 6 | 1. Write a short program that asks for your height in integer inches and then 7 | converts your height to feet and inches. Have the program use the underscore 8 | character to indicate where to type the response. Also use a const symbolic 9 | constant to represent the conversion factor. 10 | 11 | 2. Write a short program that asks for your height in feet and inches and your 12 | weight in pounds. (Use three variables to store the information.) Have the 13 | program report your body mass index (BMI). To calculate the BMI, first 14 | convert your height in feet and inches to your height in inches 15 | (1 foot = 12 inches). Then convert your height in inches to your height in 16 | meters by multiplying by 0.0254. Then convert your weight in pounds into 17 | your mass in kilograms by dividing by 2.2. Finally, compute your BMI by 18 | dividing your mass in kilograms by the square of your height in meters. Use 19 | symbolic constants to represent the various conversion factors. 20 | 21 | 3. Write a program that asks the user to enter a latitude in degrees, minutes, 22 | and seconds and that then displays the latitude in decimal format. There are 23 | 60 seconds of arc to a minute and 60 minutes of arc to a degree; represent 24 | these values with symbolic constants. You should use a separate variable for 25 | each input value. A sample run should look like this: 26 | 27 | Enter a latitude in degrees, minutes, and seconds: 28 | First, enter the degrees: 37 29 | Next, enter the minutes of arc: 51 30 | Finally, enter the seconds of arc: 19 31 | 37 degrees, 51 minutes, 19 seconds = 37.8553 degrees 32 | 33 | 4. Write a program that asks the user to enter the number of seconds as an 34 | integer value (use type long, or, if available, long long) and that then 35 | displays the equivalent time in days, hours, minutes, and seconds. Use 36 | symbolic constants to represent the number of hours in the day, the number 37 | of minutes in an hour, and the number of seconds in a minute. The output 38 | should look like this: 39 | 40 | Enter the number of seconds: 31600000 41 | 31600000 seconds = 365 days, 17 hours, 46 minutes, 40 seconds 42 | 43 | 5. Write a program that requests the user to enter the current world population 44 | and the current population of the U.S. (or of some other nation of your 45 | choice). Store the information in variables of type long long. Have the 46 | program display the percent that the U.S. (or other nation’s) population is 47 | of the world’s population. The output should look something like this: 48 | 49 | Enter the world's population: 6898758899 50 | Enter the population of the US: 310783781 51 | The population of the US is 4.50492% of the world population. 52 | 53 | You can use the Internet to get more recent figures. 54 | 55 | 6. Write a program that asks how many miles you have driven and how many 56 | gallons of gasoline you have used and then reports the miles per gallon your 57 | car has gotten. Or, if you prefer, the program can request distance in 58 | kilometers and petrol in liters and then report the result European style, 59 | in liters per 100 kilometers. 60 | 61 | 7. Write a program that asks you to enter an automobile gasoline consumption 62 | figure in the European style (liters per 100 kilometers) and converts to the 63 | U.S. style of miles per gallon. Note that in addition to using different 64 | units of measurement, the U.S. approach (distance / fuel) is the inverse of 65 | the European approach (fuel / distance). Note that 100 kilometers is 66 | 62.14 miles, and 1 gallon is 3.875 liters. Thus, 19 mpg is about 67 | 12.4 l/100 km, and 27 mpg is about 8.7 l/100 km. 68 | 69 | ================================================================================ 70 | -------------------------------------------------------------------------------- /chapter_03/sol-3-1.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 3.1 ------------------------- 3 | 4 | #include 5 | int main() 6 | { 7 | const int INCH_FT = 12; // 1 ft = 12 inches 8 | std::cout << "Enter your height in integer inches: ___\b\b\b"; 9 | int height; 10 | std::cin >> height; 11 | int feet = height/INCH_FT; 12 | int inch = height%INCH_FT; 13 | std::cout << "Yur height is "<< feet << " feets and "<< inch << " inches\n"; 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /chapter_03/sol-3-2.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 3.2 ------------------------- 3 | 4 | #include 5 | const int INCH_FT = 12; // 1 ft = 12 inches 6 | const double POUND_KG = 2.2; // 1 kg = 2.2 pounds 7 | const double METER_INCH = 0.0254; // 1 inch = 0.0254 meters 8 | double bmi(int f, int i, int p); 9 | int main() 10 | { 11 | std::cout << "Enter your height in feet and inches.\n"; 12 | std::cout << " feet: "; 13 | int ft, inch, pound; 14 | std::cin >> ft; 15 | std::cout << " inches: "; 16 | std::cin >> inch; 17 | std::cout << "Enter your weight in pounds: "; 18 | std::cin >> pound; 19 | std::cout << "Your BMI: " << bmi(ft, inch, pound) << std::endl; 20 | return 0; 21 | } 22 | double bmi(int f, int i, int p) 23 | { 24 | double mtr = (i+f*INCH_FT)*METER_INCH; 25 | double kg = p/POUND_KG; 26 | double bmi = kg/(mtr*mtr); 27 | return bmi; 28 | } 29 | -------------------------------------------------------------------------------- /chapter_03/sol-3-3.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 3.3 ------------------------- 3 | 4 | #include 5 | int main() 6 | { 7 | const int MIN_DEG = 60; // 1 deg = 60 min 8 | const int SEC_MIN = 60; // 1 min = 60 sec 9 | std::cout << "Enter a latitude in degrees, minutes, and seconds:\n" 10 | "First, enter the degrees: "; 11 | int deg, min, sec; 12 | std::cin >> deg; 13 | std::cout << "Next, enter the minutes of arc: "; 14 | std::cin >> min; 15 | std::cout << "Finally, enter the seconds of arc: "; 16 | std::cin >> sec; 17 | double convert = deg+(min+double(sec)/SEC_MIN)/MIN_DEG; 18 | std::cout << deg << " degrees, " << min << " minutes, " << sec 19 | << " seconds = " << convert << " degrees" << std::endl; 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /chapter_03/sol-3-4.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 3.4 ------------------------- 3 | 4 | #include 5 | int main() 6 | { 7 | const int HOUR_DAY = 24; 8 | const int MIN_HOUR = 60; 9 | const int SEC_MIN = 60; 10 | std::cout << "Enter the number of seconds: "; 11 | long sec, temp; 12 | std::cin >> sec; 13 | temp = sec; 14 | int second = temp%SEC_MIN; 15 | temp /= SEC_MIN; 16 | int minutes = temp%MIN_HOUR; 17 | temp /= MIN_HOUR; 18 | int hour = temp%HOUR_DAY; 19 | int day =temp/HOUR_DAY; 20 | std::cout << sec << " seconds = "<< day << " days, " << hour << " hours, " 21 | << minutes << " minutes, " << second << " seconds" << std::endl; 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /chapter_03/sol-3-5.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 3.5 ------------------------- 3 | 4 | #include 5 | int main() 6 | { 7 | std::cout << "Enter the world's population: "; 8 | long long popul, popul_us; 9 | std::cin >> popul; 10 | std::cout << "Enter the population of the US: "; 11 | std::cin >> popul_us; 12 | double prst = popul_us*100.0/popul; 13 | std::cout << "The population of the US is " << prst 14 | << "% of the world population." << std::endl; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /chapter_03/sol-3-6.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 3.6 ------------------------- 3 | 4 | #include 5 | int main() 6 | { 7 | std::cout << "Enter distance in kilomters: "; 8 | float km, lt; 9 | std::cin >> km; 10 | std::cout << "Enter petrol in liters: "; 11 | std::cin >> lt; 12 | std::cout << "Gasoline consuption (liters per 100 kilometers): " 13 | << lt/km*100 << " lt/100km" << std::endl; 14 | return 0; 15 | } 16 | 17 | -------------------------------------------------------------------------------- /chapter_03/sol-3-7.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 3.7 ------------------------- 3 | 4 | #include 5 | int main() 6 | { 7 | const double LITER_GAL = 3.875; // 1 gallon = 3.85 liters 8 | const double MIL_KM = 62.14; // 100 km = 62.14 miles 9 | std::cout << "Enter gasoline consumption (liters/100 kilometers): "; 10 | double consum; 11 | std::cin >> consum; 12 | int consum_us = MIL_KM/(consum/LITER_GAL); 13 | std::cout << "Your consumption = " << consum_us << " miles/gallon\n"; 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /chapter_04/ProgrammingExercisesChapter_4.txt: -------------------------------------------------------------------------------- 1 | S.Prata C++ Primer Plus 6th ed. 2 | ================================================================================ 3 | PROGRAMMING EXERCISES CHAPTER 4 4 | 5 | 6 | 1. Write a C++ program that requests and displays information as shown in the 7 | following example of output: 8 | 9 | What is your first name? Betty Sue 10 | What is your last name? Yewe 11 | What letter grade do you deserve? B 12 | What is your age? 22 13 | Name: Yewe, Betty Sue 14 | Grade: C 15 | Age: 22 16 | 17 | Note that the program should be able to accept first names that comprise 18 | more than one word. Also note that the program adjusts the grade 19 | downward—that is, up one letter. Assume that the user requests an A, a B, or 20 | a C so that you don’t have to worry about the gap between a D and an F. 21 | 22 | 2. Rewrite Listing 4.4, using the C++ string class instead of char arrays. 23 | 24 | 3. Write a program that asks the user to enter his or her first name and then 25 | last name, and that then constructs, stores, and displays a third string, 26 | consisting of the user’s last name followed by a comma, a space, and first 27 | name. Use char arrays and functions from the cstring header file. A sample 28 | run could look like this: 29 | 30 | Enter your first name: Flip 31 | Enter your last name: Fleming 32 | Here’s the information in a single string: Fleming, Flip 33 | 34 | 4. Write a program that asks the user to enter his or her first name and then 35 | last name, and that then constructs, stores, and displays a third string 36 | consisting of the user’s last name followed by a comma, a space, and first 37 | name. Use string objects and methods from the string header file. A sample 38 | run could look like this: 39 | 40 | Enter your first name: Flip 41 | Enter your last name: Fleming 42 | Here’s the information in a single string: Fleming, Flip 43 | 44 | 5. The CandyBar structure contains three members. The first member holds the 45 | brand name of a candy bar. The second member holds the weight (which may 46 | have a fractional part) of the candy bar, and the third member holds the 47 | number of calories (an integer value) in the candy bar. Write a program that 48 | declares such a structure and creates a CandyBar variable called snack, 49 | initializing its members to "Mocha Munch", 2.3, and 350, respectively. The 50 | initialization should be part of the declaration for snack. Finally, the 51 | program should display the contents of the snack variable. 52 | 53 | 6. The CandyBar structure contains three members, as described in Programming 54 | Exercise 5. Write a program that creates an array of three CandyBar 55 | structures, initializes them to values of your choice, and then displays the 56 | contents of each structure. 57 | 58 | 7. William Wingate runs a pizza-analysis service. For each pizza, he needs to 59 | record the following information: 60 | 61 | The name of the pizza company, which can consist of more than one word 62 | The diameter of the pizza 63 | The weight of the pizza 64 | 65 | Devise a structure that can hold this information and write a program that 66 | uses a structure variable of that type. The program should ask the user to 67 | enter each of the preceding items of information, and then the program 68 | should display that information. Use cin (or its methods) and cout. 69 | 70 | 8. Do Programming Exercise 7 but use new to allocate a structure instead of 71 | declaring a structure variable. Also have the program request the pizza 72 | diameter before it requests the pizza company name. 73 | 74 | 9. Do Programming Exercise 6, but instead of declaring an array of three 75 | CandyBar structures, use new to allocate the array dynamically. 76 | 77 | 10. Write a program that requests the user to enter three times for the 40-yd 78 | dash (or 40-meter, if you prefer) and then displays the times and the 79 | average. Use an array object to hold the data. (Use a built-in array if 80 | array is not available.) 81 | 82 | ================================================================================ 83 | -------------------------------------------------------------------------------- /chapter_04/sol-4-01.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 4.1 ------------------------- 3 | 4 | #include 5 | #include 6 | int main() 7 | { 8 | using namespace std; 9 | string fname, lname; 10 | cout << "What is your firs name? "; 11 | getline(cin, fname); 12 | cout << "What is your last name? "; 13 | getline(cin, lname); 14 | cout << "What letter grade do you deserve? "; 15 | char letter; 16 | cin >> letter; 17 | cout << "What is your age? "; 18 | int age; 19 | cin >> age; 20 | cout << "Name: " << lname << ", " << fname << "\nGrade: " << ++letter 21 | << "\nAge: " << age << endl; 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /chapter_04/sol-4-02.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 4.2 ------------------------- 3 | 4 | #include 5 | #include 6 | int main() 7 | { 8 | using namespace std; 9 | string name; 10 | string dessert; 11 | cout << "Enter your name:\n"; 12 | getline(cin, name); 13 | cout << "Enter your favorite dessert:\n"; 14 | getline(cin, dessert); 15 | cout << "I have some delicious " << dessert; 16 | cout << " for you, " << name << " .\n"; 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /chapter_04/sol-4-03.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 4.3 ------------------------- 3 | 4 | #include 5 | #include 6 | int main() 7 | { 8 | using namespace std; 9 | const int SIZE = 30; 10 | cout << "Enter your first name: "; 11 | char fname[SIZE]; 12 | cin.getline(fname, SIZE); 13 | cout << "Enter your last name: "; 14 | char lname[SIZE]; 15 | cin.getline(lname, SIZE); 16 | strcat(lname, ", "); 17 | strcat(lname, fname); 18 | cout << "Here’s the information in a single string: " << lname << endl; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /chapter_04/sol-4-04.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 4.4 ------------------------- 3 | 4 | #include 5 | #include 6 | int main() 7 | { 8 | using namespace std; 9 | string fname, lname; 10 | cout << "Enter your first name: "; 11 | getline(cin, fname); 12 | cout << "Enter your last name: "; 13 | getline(cin, lname); 14 | string fullname = fname + ", " + lname; 15 | cout << "Here’s the information in a single string: " << fullname << endl; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /chapter_04/sol-4-05.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 4.5 ------------------------- 3 | 4 | #include 5 | struct CandyBar 6 | { 7 | char brand[20]; 8 | float weight; 9 | int cal; 10 | }; 11 | int main() 12 | { 13 | CandyBar snack { "Mocha Munch", 2.3, 350 }; 14 | std::cout << "Struct snack\n Brand name: " << snack.brand << "\n Weight: " 15 | << snack.weight << "\n Calories: " << snack.cal << std::endl; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /chapter_04/sol-4-06.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 4.6 ------------------------- 3 | 4 | #include 5 | struct CandyBar 6 | { 7 | char brand[20]; 8 | float weight; 9 | int cal; 10 | }; 11 | int main() 12 | { 13 | using namespace std; 14 | CandyBar snack[3] 15 | { 16 | {"Mocha Munch", 2.3, 350}, 17 | {"Bambi", 2.5, 390}, 18 | {"Godzilla", 3.4, 400} 19 | }; 20 | cout << "Snack 1\n Brand name: " << snack[0].brand 21 | << "\n Weight: " << snack[0].weight 22 | << "\n Calories: " << snack[0].cal << endl; 23 | cout << "Snack 2\n Brand name: " << snack[1].brand 24 | << "\n Weight: " << snack[1].weight 25 | << "\n Calories: " << snack[1].cal << endl; 26 | cout << "Snack 3\n Brand name: " << snack[2].brand 27 | << "\n Weight: " << snack[2].weight 28 | << "\n Calories: " << snack[2].cal << endl; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /chapter_04/sol-4-07.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 4.7 ------------------------- 3 | 4 | #include 5 | struct pizza 6 | { 7 | char company[20]; 8 | float diameter; 9 | float weight; 10 | }; 11 | int main() 12 | { 13 | using namespace std; 14 | pizza will; 15 | cout << "Enter name of the pizza company: "; 16 | cin.getline(will.company, 20); 17 | cout << "Enter diameter: "; 18 | cin >> will.diameter; 19 | cout << "Enter weight: "; 20 | cin >> will.weight; 21 | cout << "\nPizza\n Company: " << will.company << "\n Diameter: " 22 | << will.diameter << "\n Weight: " << will.weight << endl; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /chapter_04/sol-4-08.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 4.8 ------------------------- 3 | 4 | #include 5 | struct pizza 6 | { 7 | char company[20]; 8 | float diameter; 9 | float weight; 10 | }; 11 | int main() 12 | { 13 | using namespace std; 14 | pizza *will = new pizza; 15 | cout << "Enter diameter: "; 16 | (cin >> will->diameter).get(); 17 | cout << "Enter name of the pizza company: "; 18 | cin.getline(will->company, 20); 19 | cout << "Enter weight: "; 20 | cin >> will->weight; 21 | cout << "\nPizza\n Company: " << will->company << "\n Diameter: " 22 | << will->diameter << "\n Weight: " << will->weight << endl; 23 | delete will; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /chapter_04/sol-4-09.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 4.9 ------------------------- 3 | 4 | #include 5 | #include 6 | struct CandyBar 7 | { 8 | char brand[20]; 9 | float weight; 10 | int cal; 11 | }; 12 | int main() 13 | { 14 | using namespace std; 15 | CandyBar *snack = new CandyBar[3]; 16 | strcpy(snack[0].brand, "Mocha Munch"); 17 | snack[0].weight = 2.3; 18 | snack[0].cal = 350; 19 | strcpy(snack[1].brand, "Bambi"); 20 | snack[1].weight = 2.5; 21 | snack[1].cal = 390; 22 | strcpy(snack[2].brand, "Godzilla"); 23 | snack[2].weight = 3.4; 24 | snack[2].cal = 400; 25 | cout << "Snack 1\n Brand name: " << snack[0].brand 26 | << "\n Weight: " << snack[0].weight 27 | << "\n Calories: " << snack[0].cal << endl; 28 | cout << "Snack 2\n Brand name: " << snack[1].brand 29 | << "\n Weight: " << snack[1].weight 30 | << "\n Calories: " << snack[1].cal << endl; 31 | cout << "Snack 3\n Brand name: " << snack[2].brand 32 | << "\n Weight: " << snack[2].weight 33 | << "\n Calories: " << snack[2].cal << endl; 34 | delete [] snack; 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /chapter_04/sol-4-10.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 4.10 ------------------------ 3 | 4 | #include 5 | #include 6 | int main() 7 | { 8 | using namespace std; 9 | array dash; 10 | cout << "Enter three times for the 40-meter dash\n 1: "; 11 | cin >> dash[0]; 12 | cout << " 2: "; 13 | cin >> dash[1]; 14 | cout << " 3: "; 15 | cin >> dash[2]; 16 | cout << "First dash: " << dash[0] << "; second: " << dash[1] << "; third: " 17 | << dash[2] << "; average time: "<< (dash[0]+dash[1]+dash[2])/3 << endl; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /chapter_05/ProgrammingExercisesChapter_5.txt: -------------------------------------------------------------------------------- 1 | S.Prata C++ Primer Plus 6th ed. 2 | ================================================================================ 3 | PROGRAMMING EXERCISES CHAPTER 5 4 | 5 | 6 | 1. Write a program that requests the user to enter two integers. The program 7 | should then calculate and report the sum of all the integers between and 8 | including the two integers. At this point, assume that the smaller integer 9 | is entered first. For example, if the user enters 2 and 9, the program 10 | should report that the sum of all the integers from 2 through 9 is 44. 11 | 12 | 2. Redo Listing 5.4 using a type array object instead of a built-in array and 13 | type long double instead of long long. Find the value of 100! 14 | 15 | 3. Write a program that asks the user to type in numbers.After each entry, the 16 | program should report the cumulative sum of the entries to date. The program 17 | should terminate when the user enters 0. 18 | 19 | 4. Daphne invests $100 at 10% simple interest. That is, every year, the 20 | investment earns 10% of the original investment, or $10 each and every year: 21 | 22 | interest = 0.10 × original balance 23 | 24 | At the same time, Cleo invests $100 at 5% compound interest. That is, 25 | interest is 5% of the current balance, including previous additions of 26 | interest: 27 | 28 | interest = 0.05 × current balance 29 | 30 | Cleo earns 5% of $100 the first year, giving her $105.The next year she 31 | earns 5% of $105, or $5.25, and so on.Write a program that finds how many 32 | years it takes for the value of Cleo’s investment to exceed the value of 33 | Daphne’s investment and then displays the value of both investments at that 34 | time. 35 | 36 | 5. You sell the book C++ for Fools. Write a program that has you enter a year’s 37 | worth of monthly sales (in terms of number of books, not of money). The 38 | program should use a loop to prompt you by month, using an array of char * 39 | (or an array of string objects, if you prefer) initialized to the month 40 | trings and storing the input data in an array of int. Then, the program 41 | should find the sum of the array contents and report the total sales for the 42 | year. 43 | 44 | 6. Do Programming Exercise 5 but use a two-dimensional array to store input for 45 | 3 years of monthly sales. Report the total sales for each individual year 46 | and for the combined years. 47 | 48 | 7. Design a structure called car that holds the following information about an 49 | automobile: its make, as a string in a character array or in a string 50 | object, and the year it was built, as an integer.Write a program that asks 51 | the user how many cars to catalog. The program should then use new to create 52 | a dynamic array of that many car structures. Next, it should prompt the user 53 | to input the make (which might consist of more than one word) and year 54 | information for each structure. Note that this requires some care because it 55 | alternates reading strings with numeric data (see Chapter 4). Finally, it 56 | should display the contents of each structure. A sample run should look 57 | something like the following: 58 | 59 | How many cars do you wish to catalog? 2 60 | Car #1: 61 | Please enter the make: Hudson Hornet 62 | Please enter the year made: 1952 63 | Car #2: 64 | Please enter the make: Kaiser 65 | Please enter the year made: 1951 66 | Here is your collection: 67 | 1952 Hudson Hornet 68 | 1951 Kaiser 69 | 70 | 8. Write a program that uses an array of char and a loop to read one word at a 71 | time until the word done is entered. The program should then report the 72 | number of words entered (not counting done). A sample run could look like 73 | this: 74 | 75 | Enter words (to stop, type the word done): 76 | anteater birthday category dumpster 77 | envy finagle geometry done for sure 78 | You entered a total of 7 words. 79 | 80 | You should include the cstring header file and use the strcmp() function to 81 | make the comparison test. 82 | 83 | 9. Write a program that matches the description of the program in Programming 84 | Exercise 8, but use a string class object instead of an array. Include the 85 | string header file and use a relational operator to make the comparison 86 | test. 87 | 88 | 10. Write a program using nested loops that asks the user to enter a value for 89 | the number of rows to display. It should then display that many rows of 90 | asterisks, with one asterisk in the first row, two in the second row, and so 91 | on. For each row, the asterisks are preceded by the number of periods needed 92 | to make all the rows display a total number of characters equal to the 93 | number of rows. A sample run would look like this: 94 | 95 | Enter number of rows: 5 96 | ....* 97 | ...** 98 | ..*** 99 | .**** 100 | ***** 101 | 102 | ================================================================================ 103 | -------------------------------------------------------------------------------- /chapter_05/sol-5-01.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 5.1 ------------------------- 3 | 4 | #include 5 | int main() 6 | { 7 | using namespace std; 8 | cout << "Enter two integers.\n 1: "; 9 | int a, b, c = 0; 10 | cin >> a; 11 | cout << " 2: "; 12 | cin >> b; 13 | for(int i = a; i <= b; i++) 14 | c += i; 15 | cout << "Sum of all the integers from " << a << " through " << b << " is " 16 | << c << endl; 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /chapter_05/sol-5-02.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 5.2 ------------------------- 3 | 4 | #include 5 | #include 6 | const int ArSize =100; 7 | int main() 8 | { 9 | std::array factorials; 10 | factorials[1] = factorials[0] = 1.0L; 11 | for (int i = 2; i < ArSize; i++) 12 | factorials[i] = i * factorials[i-1]; 13 | for (int i = 0; i < ArSize; i++) 14 | std::cout << i << "! = " << factorials[i] << std::endl; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /chapter_05/sol-5-03.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 5.3 ------------------------- 3 | 4 | #include 5 | int main() 6 | { 7 | using namespace std; 8 | cout << "Enter number (0 for terminate): "; 9 | int num, sum = 0; 10 | cin >> num; 11 | while(num != 0) 12 | { 13 | cout << "Sum = " << (sum += num) << endl; 14 | cin >> num; 15 | } 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /chapter_05/sol-5-04.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 5.4 ------------------------- 3 | 4 | #include 5 | int main() 6 | { 7 | double dafna, kleo; 8 | dafna = kleo = 100.0; 9 | for(int i = 1; dafna >= kleo; i++) 10 | { 11 | dafna += 10; 12 | kleo += kleo*0.05; 13 | std::cout << i << ". Dafna = " << dafna << " Kleo = " << kleo << "\n"; 14 | } 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /chapter_05/sol-5-05.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 5.5 ------------------------- 3 | 4 | #include 5 | int main() 6 | { 7 | const int YEAR = 12; 8 | const char *month[YEAR] { 9 | "January", "February", "March", "April", "May", "June", "July", 10 | "August", "September", "October", "November", "December" }; 11 | int sale[YEAR], sum = 0; 12 | for(int i = 0; i < YEAR; i++) 13 | { 14 | std::cout << "Sales for " << month[i] << ": "; 15 | std::cin >> sale[i]; 16 | sum += sale[i]; 17 | } 18 | std::cout << " Sum = " << sum << "\n"; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /chapter_05/sol-5-06.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 5.5 ------------------------- 3 | 4 | #include 5 | #include 6 | int main() 7 | { 8 | using namespace std; 9 | const int YEAR = 12; 10 | const int CNT = 3; 11 | string month[YEAR] = 12 | {"January", "February", "March", "April", "May", "June", "July", 13 | "August", "September", "October", "November", "December"}; 14 | int sale[CNT][YEAR], sum[CNT] = {0}, total = 0; 15 | for(int i = 0; i < CNT; i++) 16 | { 17 | cout << "Year " << i+1 << endl; 18 | for(int j = 0; j < YEAR; j++) 19 | { 20 | cout << "Sales for " << month[j] << ": "; 21 | cin >> sale[i][j]; 22 | sum[i] += sale[i][j]; 23 | } 24 | total += sum[i]; 25 | } 26 | for(int i = 0; i < CNT; i++) 27 | cout << i+1 << " year Sum = " << sum[i] << endl; 28 | cout << "Total = " << total << endl; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /chapter_05/sol-5-07.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 5.7 ------------------------- 3 | 4 | #include 5 | #include 6 | struct car 7 | { 8 | std::string make; 9 | int year; 10 | }; 11 | int main() 12 | { 13 | using namespace std; 14 | cout << "How many cars do you wish to catalog? "; 15 | int qty; 16 | (cin >> qty).get(); 17 | car *collection = new car[qty]; 18 | for(int i = 0; i < qty; i++) 19 | { 20 | cout << "Car #" << i+1 << ":\n"; 21 | cout << "Please enter the make: "; 22 | getline(cin, collection[i].make); 23 | cout << "Please enter the year made: "; 24 | (cin >> collection[i].year).get(); 25 | } 26 | cout << "Here is your collection:\n"; 27 | for(int i = 0; i < qty; i++) 28 | cout << collection[i].year << " " << collection[i].make << endl; 29 | delete [] collection; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /chapter_05/sol-5-08.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 5.8 ------------------------- 3 | 4 | #include 5 | #include 6 | int main() 7 | { 8 | char word[20]; 9 | int count = 0; 10 | std::cout << "Enter words (to stop, type the word done):\n"; 11 | std::cin >> word; 12 | while (strcmp(word, "done")) 13 | { 14 | std::cin >> word; 15 | count++; 16 | } 17 | std::cout << "You entered a total of " << count << " words." << "\n"; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /chapter_05/sol-5-09.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 5.9 ------------------------- 3 | 4 | #include 5 | #include 6 | int main() 7 | { 8 | std::string word; 9 | int count = 0; 10 | std::cout << "Enter words (to stop, type the word done):\n"; 11 | std::cin >> word; 12 | while(word != "done") 13 | { 14 | std::cin >> word; 15 | count++; 16 | } 17 | std::cout << "You entered a total of " << count << " words." << "\n"; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /chapter_05/sol-5-10.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 5.10 ------------------------ 3 | 4 | #include 5 | int main() 6 | { 7 | using namespace std; 8 | cout << "Enter number of rows: "; 9 | int row; 10 | cin >> row; 11 | for (int i = 1; i <= row; i++) 12 | { 13 | for (int a = i; a < row; a++) 14 | cout << '.'; 15 | for (int b = i; b !=0; b--) 16 | cout << '*'; 17 | cout << "\n"; 18 | } 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /chapter_06/ProgrammingExercisesChapter_6.txt: -------------------------------------------------------------------------------- 1 | S.Prata C++ Primer Plus 6th ed. 2 | ================================================================================ 3 | PROGRAMMING EXERCISES CHAPTER 6 4 | 5 | 6 | 1. Write a program that reads keyboard input to the @ symbol and that echoes 7 | the input except for digits, converting each uppercase character to 8 | lowercase, and vice versa. (Don’t forget the cctype family.) 9 | 10 | 2. Write a program that reads up to 10 donation values into an array of double. 11 | (Or, if you prefer, use an array template object.) The program should 12 | terminate input on non-numeric input. It should report the average of the 13 | numbers and also report how many numbers in the array are larger than the 14 | average. 15 | 16 | 3. Write a precursor to a menu-driven program.The program should display a menu 17 | offering four choices, each labeled with a letter. If the user responds with 18 | a letter other than one of the four valid choices, the program should prompt 19 | the user to enter a valid response until the user complies. Then the program 20 | should use a switch to select a simple action based on the user’s selection. 21 | A program run could look something like this: 22 | 23 | Please enter one of the following choices: 24 | c) carnivore p) pianist 25 | t) tree g) game 26 | f 27 | Please enter a c, p, t, or g: q 28 | Please enter a c, p, t, or g: t 29 | A maple is a tree. 30 | 31 | 4. When you join the Benevolent Order of Programmers, you can be known at BOP 32 | meetings by your real name, your job title, or your secret BOP name. Write a 33 | program that can list members by real name, by job title, by secret name, or 34 | by a member’s preference. Base the program on the following structure: 35 | 36 | // Benevolent Order of Programmers name structure 37 | struct bop { 38 | char fullname[strsize]; // real name 39 | char title[strsize]; // job title 40 | char bopname[strsize]; // secret BOP name 41 | int preference; // 0 = fullname, 1 = title, 2 = bopname 42 | }; 43 | 44 | In the program, create a small array of such structures and initialize it to 45 | suitable values. Have the program run a loop that lets the user select from 46 | different alternatives: 47 | 48 | a. display by name b. display by title 49 | c. display by bopname d. display by preference 50 | q. quit 51 | 52 | Note that “display by preference” does not mean display the 53 | preferencemember; it means display the member corresponding to the 54 | preference number. For instance, if preference is 1, choice d would display 55 | the programmer’s job title. A sample run may look something like the 56 | following: 57 | 58 | Benevolent Order of Programmers Report 59 | a. display by name b. display by title 60 | c. display by bopname d. display by preference 61 | q. quit 62 | Enter your choice: a 63 | Wimp Macho 64 | Raki Rhodes 65 | Celia Laiter 66 | Hoppy Hipman 67 | Pat Hand 68 | Next choice: d 69 | Wimp Macho 70 | Junior Programmer 71 | MIPS 72 | Analyst Trainee 73 | LOOPY 74 | Next choice: q 75 | Bye! 76 | 77 | 5. The Kingdom of Neutronia, where the unit of currency is the tvarp, has the 78 | following income tax code: 79 | 80 | First 5,000 tvarps: 0% tax 81 | Next 10,000 tvarps: 10% tax 82 | Next 20,000 tvarps: 15% tax 83 | Tvarps after 35,000: 20% tax 84 | 85 | For example, someone earning 38,000 tvarps would owe 5,000 × 0.00 + 10,000 × 86 | 0.10 + 20,000 × 0.15 + 3,000 × 0.20, or 4,600 tvarps. Write a program that 87 | uses a loop to solicit incomes and to report tax owed. The loop should 88 | terminate when the user enters a negative number or non-numeric input. 89 | 90 | 6. Put together a program that keeps track of monetary contributions to the 91 | Society for the Preservation of Rightful Influence. It should ask the user 92 | to enter the number of contributors and then solicit the user to enter the 93 | name and contribution of each contributor. The information should be stored 94 | in a dynamically allocated array of structures. Each structure should have 95 | two members: a character array (or else a string object) to store the name 96 | and a double member to hold the amount of the contribution. After reading 97 | all the data, the program should display the names and amounts donated for 98 | all donors who contributed $10,000 or more. This list should be headed by 99 | the label Grand Patrons.After that, the program should list the remaining 100 | donors. That list should be headed Patrons. If there are no donors in one 101 | of the categories, the program should print the word “none.” Aside from 102 | displaying two categories, the program need do no sorting. 103 | 104 | 7. Write a program that reads input a word at a time until a lone q is entered. 105 | The program should then report the number of words that began with vowels, 106 | the number that began with consonants, and the number that fit neither of 107 | those categories. One approach is to use isalpha() to discriminate between 108 | words beginning with letters and those that don’t and then use an if or 109 | switch statement to further identify those passing the isalpha() test that 110 | begin with vowels. A sample run might look like this: 111 | 112 | Enter words (q to quit): 113 | The 12 awesome oxen ambled 114 | quietly across 15 meters of lawn. q 115 | 5 words beginning with vowels 116 | 4 words beginning with consonants 117 | 2 others 118 | 119 | 8. Write a program that opens a text file, reads it character-by-character to 120 | the end of the file, and reports the number of characters in the file. 121 | 122 | 9. Do Programming Exercise 6 but modify it to get information from a file. The 123 | first item in the file should be the number of contributors, and the rest of 124 | the file should consist of pairs of lines, with the first line of each pair 125 | being a contributor’s name and the second line being a contribution. That 126 | is, the file should look like this: 127 | 128 | 4 129 | Sam Stone 130 | 2000 131 | Freida Flass 132 | 100500 133 | Tammy Tubbs 134 | 5000 135 | Rich Raptor 136 | 55000 137 | 138 | ================================================================================ 139 | -------------------------------------------------------------------------------- /chapter_06/sol-6-01.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 6.1 ------------------------- 3 | 4 | #include 5 | #include 6 | int main() 7 | { 8 | using namespace std; 9 | cout << "Enter text for analysis, and type @ to terminate input.\n"; 10 | char ch; 11 | cin.get(ch); 12 | while(ch != '@') 13 | { 14 | if(isdigit(ch)) 15 | { 16 | cin.get(ch); 17 | continue; 18 | } 19 | else if(islower(ch)) 20 | ch = toupper(ch); 21 | else if(isupper(ch)) 22 | ch = tolower(ch); 23 | cout << ch; 24 | cin.get(ch); 25 | } 26 | cout << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /chapter_06/sol-6-02.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 6.2 ------------------------- 3 | 4 | #include 5 | int main() 6 | { 7 | using namespace std; 8 | const int SIZE = 10; 9 | double arr[SIZE]; 10 | double donat, sum = 0.0; 11 | int cnt = 0, i = 0; 12 | cout << "Enter donation values: "; 13 | for(; i < SIZE && cin >> donat; i++) 14 | { 15 | arr[i] = donat; 16 | sum += donat; 17 | cout << "Enter donation values: "; 18 | } 19 | if (i != 0) 20 | { 21 | double avr = sum/i; 22 | for(int j = 0; j < i; j++) 23 | { 24 | if (arr[j] > avr) 25 | cnt++; 26 | } 27 | cout << "Average = " << avr << "; Numbers larger than average = " 28 | << cnt << endl; 29 | } else 30 | cout << "Ooops.. No data." << endl; 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /chapter_06/sol-6-03.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 6.3 ------------------------- 3 | 4 | #include 5 | int main() 6 | { 7 | using namespace std; 8 | cout << "Please enter one of the following choices:\n" 9 | " c) carnivore\t p) pianist\n" 10 | " t) tree\t g) game\n"; 11 | char ch; 12 | cin >> ch; 13 | while(ch !='c' && ch !='p' && ch !='t' && ch !='g') 14 | { 15 | cout << "Please enter a c, p, t, or g: "; 16 | cin >> ch; 17 | } 18 | switch(ch) 19 | { 20 | case 'c' : cout << "Carnivore\n"; break; 21 | case 'p' : cout << "Pianist\n"; break; 22 | case 't' : cout << "A maple is a tree.\n"; break; 23 | case 'g' : cout << "Game\n"; break; 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /chapter_06/sol-6-04.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 6.4 ------------------------- 3 | 4 | #include 5 | const int strsize = 20; 6 | const int SIZE = 5; 7 | struct bop { 8 | char fullname[strsize]; 9 | char title[strsize]; 10 | char bopname[strsize]; 11 | int preference; 12 | }; 13 | int main() 14 | { 15 | using namespace std; 16 | bop arrbop[SIZE]{ 17 | {"Wimp Macho", "Engineer", "STAR", 0}, 18 | {"Raki Rhodes", "Junior Programmer", "SUN", 1}, 19 | {"Celia Laiter", "Broker", "MIPS", 2}, 20 | {"Hoppy Hipman", "Analyst Trainee", "MAGIC", 1}, 21 | {"Pat Hand", "Electrician", "LOOPY", 2} 22 | }; 23 | cout << "Benevolent Order of Programmers Report\n" 24 | " a. display by name\t b. display by title\n" 25 | " c. display by bopname\t d. display by preference\n" 26 | " q. quit\n"; 27 | cout << "Enter your choice: "; 28 | char ch; 29 | cin >> ch; 30 | while(ch !='q') 31 | { 32 | switch (ch) 33 | { 34 | case 'a': { 35 | for(int i = 0; i < SIZE; i++) 36 | cout << arrbop[i].fullname << endl; 37 | break; } 38 | case 'b': { 39 | for(int i = 0; i < SIZE; i++) 40 | cout << arrbop[i].title << endl; 41 | break; } 42 | case 'c': { 43 | for(int i = 0; i < SIZE; i++) 44 | cout << arrbop[i].bopname << endl; 45 | break; } 46 | case 'd': { 47 | for(int i = 0; i < SIZE; i++) 48 | switch (arrbop[i].preference) 49 | { 50 | case 0: cout << arrbop[i].fullname << endl; break; 51 | case 1: cout << arrbop[i].title << endl; break; 52 | case 2: cout << arrbop[i].bopname << endl; break; 53 | } 54 | break; } 55 | } 56 | cout << "Next choice: "; 57 | cin >> ch; 58 | } 59 | cout << "Bye!" << endl; 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /chapter_06/sol-6-05.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 6.5 ------------------------- 3 | 4 | #include 5 | int main() 6 | { 7 | using namespace std; 8 | cout << "Enter tvarps (negative number or non-numeric for quit): "; 9 | int tvp; 10 | cin >> tvp; 11 | while(cin && tvp >= 0) 12 | { 13 | if(tvp <= 5000) 14 | cout << "tax = " << 0 << endl; 15 | else if(5000 < tvp && tvp <= 15000) 16 | cout << "tax = " << (tvp-5000)*0.1 << endl; 17 | else if(15000 < tvp && tvp <= 35000) 18 | cout << "tax = " << 10000*0.1+(tvp-15000)*0.15 << endl; 19 | else if(tvp > 35000) 20 | cout << "tax = " << 10000*0.1+20000*0.15+(tvp-35000)*0.2 << endl; 21 | cout << "Next: "; 22 | cin >> tvp; 23 | } 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /chapter_06/sol-6-06.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 6.6 ------------------------- 3 | 4 | #include 5 | #include 6 | struct donors{ 7 | std::string name; 8 | double donat; 9 | }; 10 | int main() 11 | { 12 | using namespace std; 13 | cout << "Enter members: "; 14 | int mem, cnt = 0; 15 | (cin >> mem).get(); 16 | donors *patron = new donors[mem]; 17 | for(int i = 0; i < mem; i++) 18 | { 19 | cout << i+1 << ". Name: "; 20 | getline(cin, patron[i].name); 21 | cout << "Contribution: "; 22 | (cin >> patron[i].donat).get(); 23 | } 24 | cout << "\nGrand Patron:\n"; 25 | for(int i = 0; i < mem; i++) 26 | { 27 | if(patron[i].donat >= 10000) 28 | { 29 | cout << patron[i].name << "\t" << patron[i].donat << endl; 30 | cnt++; 31 | } 32 | } 33 | if(cnt == 0) 34 | cout << " none\n"; 35 | cout << "Patron:\n"; 36 | if(cnt == mem) 37 | cout << " none\n"; 38 | else { 39 | for(int i = 0; i < mem; i++) 40 | { 41 | if(patron[i].donat < 10000) 42 | cout << patron[i].name << "\t" << patron[i].donat << endl; 43 | } 44 | } 45 | delete [] patron; 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /chapter_06/sol-6-07.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 6.7 ------------------------- 3 | 4 | #include 5 | #include 6 | #include 7 | int main() 8 | { 9 | using namespace std; 10 | int vowels = 0, consonants = 0, others = 0; 11 | cout << "Enter words (q to quit):\n"; 12 | string word; 13 | while (cin >> word && word != "q") 14 | { 15 | if (isalpha(word[0])) 16 | { 17 | switch (word[0]) 18 | { 19 | case 'A': case 'a': case 'E': case 'e': 20 | case 'I': case 'i': case 'U': case 'u': 21 | case 'Y': case 'y': case 'O': case 'o': 22 | vowels++; break; 23 | default: consonants++; 24 | } 25 | } 26 | else 27 | others++; 28 | } 29 | cout << vowels << " words beginning with vowels.\n" 30 | << consonants << " words beginning with consonants.\n" 31 | << others << " others.\n"; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /chapter_06/sol-6-08.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 6.8 ------------------------- 3 | 4 | #include 5 | #include 6 | const int SIZE = 60; 7 | int main() 8 | { 9 | using namespace std; 10 | ifstream inFile; 11 | char filename[SIZE]; 12 | cout << "Enter name of data file: "; 13 | cin.getline(filename, SIZE); 14 | inFile.open(filename); 15 | if(!inFile.is_open()) 16 | { 17 | cout << "Could not open the file " << filename << endl; 18 | cout << "Program terminating.\n"; 19 | exit(EXIT_FAILURE); 20 | } 21 | char ch; 22 | inFile >> ch; 23 | int count = 0; 24 | while(inFile.good()) 25 | { 26 | ++count; 27 | inFile >> ch; 28 | } 29 | cout << "Number of characters in the file: " << count << endl; 30 | inFile.close(); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /chapter_06/sol-6-09.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 6.9 ------------------------- 3 | 4 | #include 5 | #include 6 | #include 7 | struct donors{ 8 | std::string name; 9 | double donat; 10 | }; 11 | int main() 12 | { 13 | using namespace std; 14 | ifstream inFile; 15 | inFile.open("test_6_9.txt"); 16 | if (!inFile.is_open ()) 17 | { 18 | cout << "Could not open the file: \"test_6_9.txt\"" << endl; 19 | cout << "Program terminating.\n"; 20 | exit(EXIT_FAILURE); 21 | } 22 | int mem, cnt = 0; 23 | (inFile >> mem).get(); 24 | donors *patron = new donors[mem]; 25 | for(int i = 0; i < mem; i++) 26 | { 27 | getline(inFile, patron[i].name); 28 | (inFile >> patron[i].donat).get(); 29 | } 30 | cout << "Grand Patron:\n"; 31 | for(int i = 0; i < mem; i++) 32 | { 33 | if(patron[i].donat >= 10000) 34 | { 35 | cout << patron[i].name << "\t" << patron[i].donat << endl; 36 | cnt++; 37 | } 38 | } 39 | if(cnt == 0) 40 | cout << " none\n"; 41 | cout << "Patron:\n"; 42 | if(cnt == mem) 43 | cout << " none\n"; 44 | else { 45 | for(int i = 0; i < mem; i++) 46 | { 47 | if(patron[i].donat < 10000) 48 | cout << patron[i].name << "\t" << patron[i].donat << endl; 49 | } 50 | } 51 | inFile.close(); 52 | delete [] patron; 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /chapter_06/test_6_8.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis non vulputate 2 | risus. Integer id facilisis nibh. Nulla porta orci purus, non pharetra orci 3 | lobortis id. Aenean quis augue sit amet ligula tristique tincidunt nec vitae 4 | ante. Ut vel lacus id purus varius tristique nec vulputate leo posuere. 5 | -------------------------------------------------------------------------------- /chapter_06/test_6_9.txt: -------------------------------------------------------------------------------- 1 | 4 2 | Sam Stone 3 | 2000 4 | Freida Flass 5 | 100500 6 | Tammy Tubbs 7 | 5000 8 | Rich Raptor 9 | 55000 10 | -------------------------------------------------------------------------------- /chapter_07/ProgrammingExercisesChapter_7.txt: -------------------------------------------------------------------------------- 1 | S.Prata C++ Primer Plus 6th ed. 2 | ================================================================================ 3 | PROGRAMMING EXERCISES CHAPTER 7 4 | 5 | 6 | 1. Write a program that repeatedly asks the user to enter pairs of numbers 7 | until at least one of the pair is 0. For each pair, the program should use a 8 | function to calculate the harmonic mean of the numbers. The function should 9 | return the answer to main(), which should report the result. The harmonic 10 | mean of the numbers is the inverse of the average of the inverses and can be 11 | calculated as follows: 12 | 13 | harmonic mean = 2.0 × x × y / (x + y) 14 | 15 | 2. Write a program that asks the user to enter up to 10 golf scores, which are 16 | to be stored in an array. You should provide a means for the user to 17 | terminate input prior to entering 10 scores. The program should display all 18 | the scores on one line and report the average score. Handle input, display, 19 | and the average calculation with three separate array-processing functions. 20 | 21 | 3. Here is a structure declaration: 22 | 23 | struct box 24 | { 25 | char maker[40]; 26 | float height; 27 | float width; 28 | float length; 29 | float volume; 30 | }; 31 | 32 | a. Write a function that passes a box structure by value and that displays 33 | the value of each member. 34 | b. Write a function that passes the address of a box structure and that 35 | sets the volume member to the product of the other three dimensions. 36 | c. Write a simple program that uses these two functions. 37 | 38 | 4. Many state lotteries use a variation of the simple lottery portrayed by 39 | Listing 7.4. In these variations you choose several numbers from one set and 40 | call them the field numbers. For example, you might select five numbers from 41 | the field of 1–47). You also pick a single number (called a mega number or a 42 | power ball, etc.) from a second range, such as 1–27. To win the grand prize, 43 | you have to guess all the picks correctly. The chance of winning is the 44 | product of the probability of picking all the field numbers times the 45 | probability of picking the mega number. For instance, the probability of 46 | winning the example described here is the product of the probability of 47 | picking 5 out of 47 correctly times the probability of picking 1 out of 27 48 | correctly. Modify Listing 7.4 to calculate the probability of winning this 49 | kind of lottery. 50 | 51 | 5. Define a recursive function that takes an integer argument and returns the 52 | factorial of that argument. Recall that 3 factorial, written 3!, equals 53 | 3 × 2!, and so on, with 0! defined as 1. In general, if n is greater than 54 | zero, n! = n * (n - 1)!. Test your function in a program that uses a loop to 55 | allow the user to enter various values for which the program reports the 56 | factorial. 57 | 58 | 6. Write a program that uses the following functions: 59 | 60 | Fill_array() takes as arguments the name of an array of double values and an 61 | array size. It prompts the user to enter double values to be entered in the 62 | array. It ceases taking input when the array is full or when the user enters 63 | non-numeric input, and it returns the actual number of entries. 64 | 65 | Show_array() takes as arguments the name of an array of double values and an 66 | array size and displays the contents of the array. 67 | 68 | Reverse_array() takes as arguments the name of an array of double values and 69 | an array size and reverses the order of the values stored in the array. 70 | 71 | The program should use these functions to fill an array, show the array, 72 | reverse the array, show the array, reverse all but the first and last 73 | elements of the array, and then show the array. 74 | 75 | 7. Redo Listing 7.7, modifying the three array-handling functions to each use 76 | two pointer parameters to represent a range.The fill_array() function, 77 | instead of returning the actual number of items read, should return a 78 | pointer to the location after the last location filled; the other functions 79 | can use this pointer as the second argument to identify the end of the data. 80 | 81 | 8. Redo Listing 7.15 without using the array class. Do two versions: 82 | 83 | a. Use an ordinary array of const char * for the strings representing the 84 | season names, and use an ordinary array of double for the expenses. 85 | 86 | b. Use an ordinary array of const char * for the strings representing the 87 | season names, and use a structure whose sole member is an ordinary array 88 | of double for the expenses. (This design is similar to the basic design 89 | of the array class.) 90 | 91 | 9. This exercise provides practice in writing functions dealing with arrays and 92 | structures. The following is a program skeleton. Complete it by providing 93 | the described functions: 94 | 95 | #include 96 | using namespace std; 97 | const int SLEN = 30; 98 | struct student { 99 | char fullname[SLEN]; 100 | char hobby[SLEN]; 101 | int ooplevel; 102 | }; 103 | // getinfo() has two arguments: a pointer to the first element of 104 | // an array of student structures and an int representing the 105 | // number of elements of the array. The function solicits and 106 | // stores data about students. It terminates input upon filling 107 | // the array or upon encountering a blank line for the student 108 | // name. The function returns the actual number of array elements 109 | // filled. 110 | int getinfo(student pa[], int n); 111 | // display1() takes a student structure as an argument 112 | // and displays its contents 113 | void display1(student st); 114 | // display2() takes the address of student structure as an 115 | // argument and displays the structure’s contents 116 | void display2(const student * ps); 117 | // display3() takes the address of the first element of an array 118 | // of student structures and the number of array elements as 119 | // arguments and displays the contents of the structures 120 | void display3(const student pa[], int n); 121 | int main() 122 | { 123 | cout << “Enter class size: “; 124 | int class_size; 125 | cin >> class_size; 126 | while (cin.get() != '\n’) 127 | continue; 128 | student * ptr_stu = new student[class_size]; 129 | int entered = getinfo(ptr_stu, class_size); 130 | for (int i = 0; i < entered; i++) 131 | { 132 | display1(ptr_stu[i]); 133 | display2(&ptr_stu[i]); 134 | } 135 | display3(ptr_stu, entered); 136 | delete [] ptr_stu; 137 | cout << “Done\n”; 138 | return 0; 139 | } 140 | 141 | 10. Design a function calculate() that takes two type double values and a 142 | pointer to a function that takes two double arguments and returns a double. 143 | The calculate() function should also be type double, and it should return 144 | the value that the pointed-to function calculates, using the double 145 | arguments to calculate(). For example, suppose you have this definition for 146 | the add()function: 147 | 148 | double add(double x, double y) 149 | { 150 | return x + y; 151 | } 152 | 153 | Then, the function call in the following would cause calculate() to pass the 154 | values 2.5 and 10.4 to the add() function and then return the add() return 155 | value (12.9): 156 | 157 | double q = calculate(2.5, 10.4, add); 158 | 159 | Use these functions and at least one additional function in the add() mold 160 | in a program.The program should use a loop that allows the user to enter 161 | pairs of numbers. For each pair, use calculate() to invoke add() and at 162 | least one other function. If you are feeling adventurous, try creating an 163 | array of pointers to add()-style functions and use a loop to successively 164 | apply calculate() to a series of functions by using these pointers. Hint: 165 | Here’s how to declare such an array of three pointers: 166 | 167 | double (*pf[3])(double, double); 168 | 169 | You can initialize such an array by using the usual array initialization 170 | syntax and function names as addresses.') 171 | 172 | ================================================================================ 173 | -------------------------------------------------------------------------------- /chapter_07/sol-7-01.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 7.1 ------------------------- 3 | 4 | #include 5 | double harmonic(double x, double y) { return (2.0*x*y)/(x+y); } 6 | int main() 7 | { 8 | std::cout << "Enter pairs of numbers: (0 for terminate):\n"; 9 | double x, y; 10 | while (std::cin >> x && x != 0 && std::cin >> y && y != 0) 11 | std::cout << "Harmonic (" << x << ", " << y << ") = " << harmonic(x, y) 12 | << "\nEnter pair of numbers:\n"; 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /chapter_07/sol-7-02.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 7.2 ------------------------- 3 | 4 | #include 5 | const int SIZE = 10; 6 | int fill_ar(int ar[], int limit); 7 | void avrage(int ar[], int n); 8 | void show_ar(const int ar[], int n); 9 | int main() 10 | { 11 | int result[SIZE]; 12 | int size = fill_ar(result, SIZE); 13 | show_ar(result, size); 14 | avrage(result, size); 15 | return 0; 16 | } 17 | int fill_ar(int ar[], int limit) 18 | { 19 | int i, temp; 20 | std::cout << "Enter up to 10 golf scores (negative value to loop quit):\n"; 21 | for(i = 0; i < limit; i++) 22 | { 23 | std::cout << "Value #" << (i + 1) << ": "; 24 | std::cin >> temp; 25 | if(!std::cin) 26 | { 27 | std::cin.clear(); 28 | while(std::cin.get() != '\n') 29 | continue; 30 | std::cout << "Bad input; input process terminated.\n"; 31 | break; 32 | } else if (temp < 0) 33 | break; 34 | ar[i] = temp; 35 | } 36 | return i; 37 | } 38 | void avrage(int ar[], int n) 39 | { 40 | double temp = 0.0; 41 | for(int i = 0; i < n; i++) 42 | temp += ar[i]; 43 | if(n) std::cout << "Avrage score: " << temp/n << std::endl; 44 | } 45 | void show_ar(const int ar[], int n) 46 | { 47 | for(int i = 0; i < n; i++) 48 | std::cout << "Property #" << (i + 1) << ": " << ar[i] << std::endl; 49 | } 50 | -------------------------------------------------------------------------------- /chapter_07/sol-7-03.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 7.3 ------------------------- 3 | 4 | #include 5 | struct box 6 | { 7 | char maker[40]; 8 | float height; 9 | float width; 10 | float length; 11 | float volume; 12 | }; 13 | void show_box(const box t); 14 | void volume_box(box *t); 15 | int main() 16 | { 17 | box cube = {"Cube", 5, 4, 10, 0}; 18 | volume_box(&cube); 19 | show_box(cube); 20 | return 0; 21 | } 22 | void show_box(const box t) 23 | { 24 | std::cout << "Maker: " << t.maker << "\nHeight: " << t.height 25 | << "\nWidth: " << t.width << "\nLength: " << t.length 26 | << "\nVolume: " << t.volume << std::endl; 27 | } 28 | void volume_box(box * t) 29 | { 30 | t->volume = t->height * t->width * t->length; 31 | } 32 | -------------------------------------------------------------------------------- /chapter_07/sol-7-04.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 7.4 ------------------------- 3 | 4 | #include 5 | long double probability(unsigned numbers, unsigned picks); 6 | int main() 7 | { 8 | using namespace std; 9 | double total, choices, meganum, limit; 10 | cout << "Enter the total number of choices on the game card and\n" 11 | << "the number of picks allowed:\n"; 12 | while ((cin >> total >> choices) && choices <= total) 13 | { 14 | cout << "Enter the total number of choices on the game card and\n" 15 | << "the number of picks allowed for the Mega Number:\n"; 16 | if((cin >> limit >> meganum) && meganum <= limit); 17 | { 18 | cout << "You have one chance in "; 19 | cout << probability(total, choices) * probability(limit, meganum); 20 | cout << " of winning. \n"; 21 | } 22 | cout << "Next two numbers(q to quit): "; 23 | } 24 | cout << "bye\n"; 25 | return 0; 26 | } 27 | long double probability(unsigned numbers, unsigned picks) 28 | { 29 | long double result = 1.0; 30 | long double n; 31 | unsigned p; 32 | for (n = numbers, p = picks; p > 0; n--, p--) 33 | result = result * n / p; 34 | return result; 35 | } 36 | -------------------------------------------------------------------------------- /chapter_07/sol-7-05.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 7.5 ------------------------- 3 | 4 | #include 5 | unsigned long int factor(int n); 6 | int main() 7 | { 8 | std::cout << "Enter non-negative value (q to quit): "; 9 | int val; 10 | while (std::cin >> val && val >= 0) 11 | std::cout << val << "! " << factor(val) << "\nNext value: "; 12 | return 0; 13 | } 14 | unsigned long int factor(int n) 15 | { 16 | if (n == 0) 17 | return 1; 18 | else 19 | return n*factor(n - 1); 20 | } 21 | -------------------------------------------------------------------------------- /chapter_07/sol-7-06.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 7.6 ------------------------- 3 | 4 | #include 5 | const int SIZE = 10; 6 | int Fill_array(double*, int); 7 | void Reverse_array(double*, int); 8 | void Show_array(const double*, int); 9 | int main() 10 | { 11 | double arr[SIZE]; 12 | int size = Fill_array(arr, SIZE); 13 | Show_array(arr, size); 14 | Reverse_array(arr, size); 15 | Show_array(arr, size); 16 | return 0; 17 | } 18 | int Fill_array(double *ar, int n) 19 | { 20 | int i; 21 | double temp; 22 | std::cout << "Enter up to " << n << " values (q to quit):\n"; 23 | for(i = 0; i < n; i++) 24 | { 25 | std::cout << "Value #" << (i + 1) << ": "; 26 | std::cin >> temp; 27 | if(!std::cin) break; 28 | ar[i] = temp; 29 | } 30 | return i; 31 | } 32 | void Reverse_array(double *ar, int n) 33 | { 34 | double tmp; 35 | for(int j = 1, i = n-2; j < i; --i, ++j) 36 | { 37 | tmp = ar[i]; 38 | ar[i] = ar[j]; 39 | ar[j] = tmp; 40 | } 41 | } 42 | void Show_array(const double *ar, int n) 43 | { 44 | std::cout << "Array: "; 45 | for(int i = 0; i < n; i++) 46 | std::cout << ar[i] << " "; 47 | std::cout << std::endl; 48 | } 49 | -------------------------------------------------------------------------------- /chapter_07/sol-7-07.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 7.7 ------------------------- 3 | 4 | #include 5 | const int Max = 5; 6 | double *fill_array(double*, const double*); 7 | void show_array(const double*, const double*); 8 | void revalue(double, double*, const double*); 9 | int main() 10 | { 11 | using namespace std; 12 | double properties[Max]; 13 | double *pt_end = fill_array(properties, properties+Max); 14 | show_array(properties, pt_end); 15 | if ((pt_end - properties) > 0) 16 | { 17 | cout << "Enter revaluation factor: "; 18 | double factor; 19 | while (!(cin >> factor)) 20 | { 21 | cin.clear(); 22 | while (cin.get() != '\n') 23 | continue; 24 | cout << "Bad input; Please enter a number: "; 25 | } 26 | revalue(factor, properties, pt_end); 27 | show_array(properties, pt_end); 28 | } 29 | cout << "Done.\n"; 30 | cin.get(); 31 | cin.get(); 32 | return 0; 33 | } 34 | double *fill_array(double *begin, const double *end) 35 | { 36 | using namespace std; 37 | double temp; 38 | double *pt; 39 | for (pt = begin; pt != end; pt++) 40 | { 41 | cout << "Enter value #" << (pt - begin)+1 << ": "; 42 | cin >> temp; 43 | if (!cin) 44 | { 45 | cin.clear(); 46 | while (cin.get() != '\n') 47 | continue; 48 | cout << "Bad input; input process terminated.\n"; 49 | break; 50 | } 51 | else if (temp < 0) 52 | break; 53 | *pt = temp; 54 | } 55 | return pt; 56 | } 57 | void show_array(const double *begin, const double *end) 58 | { 59 | using namespace std; 60 | const double *pt; 61 | for (pt = begin; pt != end; pt++) 62 | { 63 | cout << "Property #" << (pt - begin)+1 << ": $"; 64 | cout << *pt << endl; 65 | } 66 | } 67 | void revalue(double r, double *begin, const double *end) 68 | { 69 | double *pt; 70 | for (pt = begin; pt != end; pt++) 71 | *pt *= r; 72 | } 73 | -------------------------------------------------------------------------------- /chapter_07/sol-7-08-1.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 7.8.1 ------------------------ 3 | 4 | #include 5 | const int Seasons = 4; 6 | const char *Snames[Seasons] = {"Spring", "Summer", "Fall", "Winter"}; 7 | void fill(double*, int); 8 | void show(double[], int); 9 | int main() 10 | { 11 | double expenses[Seasons]; 12 | fill(expenses, Seasons); 13 | show(expenses, Seasons); 14 | return 0; 15 | } 16 | void fill(double *pa, int n) 17 | { 18 | for(int i = 0; i < n; i++) 19 | { 20 | std::cout << "Enter " << Snames[i] << " expenses: "; 21 | std::cin >> pa[i]; 22 | } 23 | } 24 | void show(double da[], int n) 25 | { 26 | double total = 0.0; 27 | std::cout << "\nEXPENSES\n"; 28 | for(int i = 0; i < n; i++) 29 | { 30 | std::cout << Snames[i] << ": $" << da[i] << std::endl; 31 | total += da[i]; 32 | } 33 | std::cout << "Total Expenses: $" << total << std::endl; 34 | } 35 | -------------------------------------------------------------------------------- /chapter_07/sol-7-08-2.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 7.8.2 ------------------------ 3 | 4 | #include 5 | const int Seasons = 4; 6 | const char *Snames[Seasons] = {"Spring", "Summer", "Fall", "Winter"}; 7 | struct expenses { double value[Seasons]; }; 8 | void fill(expenses*); 9 | void show(expenses); 10 | int main() 11 | { 12 | expenses exp; 13 | fill(&exp); 14 | show(exp); 15 | return 0; 16 | } 17 | void fill(expenses *pa) 18 | { 19 | for(int i = 0; i < Seasons; i++) 20 | { 21 | std::cout << "Enter " << Snames[i] << " expenses: "; 22 | std::cin >> pa->value[i]; 23 | } 24 | } 25 | void show(expenses da) 26 | { 27 | double total = 0.0; 28 | std::cout << "\nEXPENSES\n"; 29 | for(int i = 0; i < Seasons; i++) 30 | { 31 | std::cout << Snames[i] << ": $" << da.value[i] << std::endl; 32 | total += da.value[i]; 33 | } 34 | std::cout << "Total Expenses: $" << total << std::endl; 35 | } 36 | -------------------------------------------------------------------------------- /chapter_07/sol-7-09.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 7.9 ------------------------- 3 | 4 | #include 5 | using namespace std; 6 | const int SLEN = 30; 7 | struct student { 8 | char fullname[SLEN]; 9 | char hobby[SLEN]; 10 | int ooplevel; 11 | }; 12 | int getinfo(student pa[], int n); 13 | void display1(student st); 14 | void display2(const student *ps); 15 | void display3(const student pa[], int n); 16 | int main() 17 | { 18 | cout << "Enter class size: "; 19 | int class_size; 20 | cin >> class_size; 21 | while (cin.get() != '\n') 22 | continue; 23 | student * ptr_stu = new student[class_size]; 24 | int entered = getinfo(ptr_stu, class_size); 25 | for (int i = 0; i < entered; i++) 26 | { 27 | display1(ptr_stu[i]); 28 | display2(&ptr_stu[i]); 29 | } 30 | display3(ptr_stu, entered); 31 | delete [] ptr_stu; 32 | cout << "Done\n"; 33 | return 0; 34 | } 35 | int getinfo(student pa[], int n) 36 | { 37 | int i; 38 | for(i = 0; i < n; i++) 39 | { 40 | cout << "Student #" << i+1 << "\n Full name: "; 41 | if(!(cin.get(pa[i].fullname, SLEN))) return i; 42 | while(cin.get() != '\n') continue; 43 | cout << " Hobby: "; 44 | cin.getline(pa[i].hobby, SLEN); 45 | cout << " opplevel: "; 46 | cin >> pa[i].ooplevel; 47 | cin.get(); 48 | } 49 | return i; 50 | } 51 | void display1(student st) 52 | { 53 | cout << "\n Full name: " << st.fullname 54 | << "\n Hobby: " << st.hobby 55 | << "\n opplevel: " << st.ooplevel << endl; 56 | } 57 | void display2(const student *ps) 58 | { 59 | cout << "\n Full name: " << ps->fullname 60 | << "\n Hobby: " << ps->hobby 61 | << "\n opplevel: " << ps->ooplevel << endl; 62 | } 63 | void display3(const student pa[], int n) 64 | { 65 | for(int i = 0; i < n; i++) 66 | { 67 | cout << "\n Full name: " << pa[i].fullname 68 | << "\n Hobby: " << pa[i].hobby 69 | << "\n opplevel: " << pa[i].ooplevel << endl; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /chapter_07/sol-7-10.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 7.10 ------------------------ 3 | 4 | #include 5 | const int SIZE = 3; 6 | double add(double x, double y) { return x + y; } 7 | double mult(double x, double y) { return x * y; } 8 | double sub(double x, double y) { return x - y; } 9 | void calculate(double, double, double (*pf[])(double, double), int); 10 | int main(void) 11 | { 12 | double (*pf[SIZE])(double, double) = {add, sub, mult}; 13 | double x, y; 14 | std::cout << "Enter two values (q to quit): \n"; 15 | while(std::cin >> x >> y) 16 | { 17 | std::cout << "Result (add, sub, mult): \n"; 18 | calculate(x, y, pf, SIZE); 19 | std::cout << "Next values: \n"; 20 | } 21 | return 0; 22 | } 23 | void calculate(double x, double y, double (*pf[])(double,double), int n) 24 | { 25 | for (int i = 0; i < n; i++) 26 | std::cout << pf[i](x, y) << std::endl; 27 | } 28 | -------------------------------------------------------------------------------- /chapter_08/ProgrammingExercisesChapter_8.txt: -------------------------------------------------------------------------------- 1 | S.Prata C++ Primer Plus 6th ed. 2 | ================================================================================ 3 | PROGRAMMING EXERCISES CHAPTER 8 4 | 5 | 6 | 1. Write a function that normally takes one argument, the address of a string, 7 | and prints that string once. However, if a second, type int, argument is 8 | provided and is nonzero, the function should print the string a number of 9 | times equal to the number of times that function has been called at that 10 | point. (Note that the number of times the string is printed is not equal to 11 | the value of the second argument; it is equal to the number of times the 12 | function has been called.) Yes, this is a silly function, but it makes you 13 | use some of the techniques discussed in this chapter. Use the function in a 14 | simple program that demonstrates how the function works. 15 | 16 | 2. The CandyBar structure contains three members. The first member holds the 17 | brand name of a candy bar.The second member holds the weight (which may have 18 | a fractional part) of the candy bar, and the third member holds the number 19 | of calories (an integer value) in the candy bar.Write a program that uses a 20 | function that takes as arguments a reference to CandyBar, a pointer-to-char, 21 | a double, and an int and uses the last three values to set the corresponding 22 | members of the structure. The last three arguments should have default 23 | values of “Millennium Munch,” 2.85, and 350. Also the program should use a 24 | function that takes a reference to a CandyBar as an argument and displays 25 | the contents of the structure. Use const where appropriate. 26 | 27 | 3. Write a function that takes a reference to a string object as its parameter 28 | and that converts the contents of the string to uppercase. Use the toupper() 29 | function described in Table 6.4 of Chapter 6.Write a program that uses a 30 | loop which allows you to test the function with different input. A sample 31 | run might look like this: 32 | 33 | Enter a string (q to quit): go away 34 | GO AWAY 35 | Next string (q to quit): good grief! 36 | GOOD GRIEF! 37 | Next string (q to quit): q 38 | Bye. 39 | 40 | 4. The following is a program skeleton: 41 | 42 | #include 43 | using namespace std; 44 | #include // for strlen(), strcpy() 45 | struct stringy { 46 | char * str; // points to a string 47 | int ct; // length of string (not counting '\0') 48 | }; 49 | // prototypes for set(), show(), and show() go here 50 | int main() 51 | { 52 | stringy beany; 53 | char testing[] = "Reality isn't what it used to be."; 54 | set(beany, testing); // first argument is a reference, 55 | // allocates space to hold copy of testing, 56 | // sets str member of beany to point to the 57 | // new block, copies testing to new block, 58 | // and sets ct member of beany 59 | show(beany); // prints member string once 60 | show(beany, 2); // prints member string twice 61 | testing[0] = 'D'; 62 | testing[1] = 'u'; 63 | show(testing); // prints testing string once 64 | show(testing, 3); // prints testing string thrice 65 | show("Done!"); 66 | return 0; 67 | } 68 | 69 | Complete this skeleton by providing the described functions and prototypes. 70 | Note that there should be two show() functions,each using default arguments. 71 | Use const arguments when appropriate. Note that set() should use new to 72 | allocate sufficient space to hold the designated string.The techniques used 73 | here are similar to those used in designing and implementing classes. (You 74 | might have to alter the header filenames and delete the using directive, 75 | depending on your compiler.) 76 | 77 | 5. Write a template function max5() that takes as its argument an array of five 78 | items of type T and returns the largest item in the array. (Because the size 79 | is fixed, it can be hard-coded into the loop instead of being passed as an 80 | argument.) Test it in a program that uses the function with an array of five 81 | int value and an array of five double values. 82 | 83 | 6. Write a template function maxn() that takes as its arguments an array of 84 | items of type T and an integer representing the number of elements in the 85 | array and that returns the largest item in the array. Test it in a program 86 | that uses the function template with an array of six int value and an array 87 | of four double values. The program should also include a specialization that 88 | takes an array of pointers-to-char as an argument and the number of pointers 89 | as a second argument and that returns the address of the longest string. If 90 | multiple strings are tied for having the longest length, the function should 91 | return the address of the first one tied for longest. Test the 92 | specialization with an array of five string pointers. 93 | 94 | 7. Modify Listing 8.14 so that it uses two template functions called SumArray() 95 | to return the sum of the array contents instead of displaying the contents. 96 | The program now should report the total number of things and the sum of all 97 | the debts. 98 | 99 | ================================================================================ 100 | -------------------------------------------------------------------------------- /chapter_08/sol-8-01.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 8.1 ------------------------- 3 | 4 | #include 5 | void show(const char*, int n = 0); 6 | int main(void) 7 | { 8 | char str[20] = "Hello, World!"; 9 | show(str); 10 | show(str); 11 | show(str, 1); 12 | return 0; 13 | } 14 | void show(const char *str, int n) 15 | { 16 | static int cnt = 0; 17 | if(!n) std::cout << str << "\n"; 18 | else 19 | for(int i = 0; i < cnt; i++) 20 | std::cout << str << "\n"; 21 | cnt++; 22 | } 23 | -------------------------------------------------------------------------------- /chapter_08/sol-8-02.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 8.2 ------------------------- 3 | 4 | #include 5 | #include 6 | const int SIZE = 20; 7 | struct CandyBar 8 | { 9 | char name[SIZE]; 10 | double weight; 11 | int cal; 12 | }; 13 | void fill 14 | (CandyBar &, const char *str="Millennium Munch", double w=2.85, int c=350); 15 | void display(const CandyBar &); 16 | int main(void) 17 | { 18 | CandyBar test; 19 | fill(test); 20 | display(test); 21 | fill(test, "Gold Star", 3.15, 410); 22 | display(test); 23 | return 0; 24 | } 25 | void fill(CandyBar &candy, const char *str, double w, int c) 26 | { 27 | strcpy(candy.name, str); 28 | candy.weight = w; 29 | candy.cal = c; 30 | } 31 | void display(const CandyBar &candy) 32 | { 33 | std::cout << "\nName: " << candy.name 34 | << "\nWeight: " << candy.weight 35 | << "\nCalories: " << candy.cal << std::endl; 36 | } 37 | -------------------------------------------------------------------------------- /chapter_08/sol-8-03.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 8.3 ------------------------- 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | void strUpp(string &); 8 | int main(void) 9 | { 10 | string str; 11 | cout << "Enter a string (q to quit): "; 12 | getline(cin, str); 13 | while(str != "q") 14 | { 15 | strUpp(str); 16 | cout << str << endl; 17 | cout << "Next string (q to quit): "; 18 | getline(cin, str); 19 | } 20 | cout << "Bye.\n"; 21 | return 0; 22 | } 23 | void strUpp(string &str) 24 | { 25 | for(int i = 0; i < str.length(); i++) 26 | str[i] = toupper(str[i]); 27 | } 28 | -------------------------------------------------------------------------------- /chapter_08/sol-8-04.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 8.4 ------------------------- 3 | 4 | #include 5 | #include 6 | struct stringy{ 7 | char *str; 8 | int ct; 9 | }; 10 | using namespace std; 11 | void set(stringy &, const char*); 12 | void show(const char*, int n = 1); 13 | void show(const stringy &, int n = 1); 14 | int main(void) 15 | { 16 | stringy beany; 17 | char testing[] = "Reality isn't what it used to be."; 18 | set(beany, testing); 19 | show(beany); 20 | show(beany, 2); 21 | testing[0] = 'D'; 22 | testing[1] = 'u'; 23 | show(testing); 24 | show(testing, 3); 25 | show("Done!"); 26 | delete[]beany.str; 27 | return 0; 28 | } 29 | void set(stringy &ps, const char *ch) 30 | { 31 | int len = strlen(ch); 32 | char *str = new char[len+1]; 33 | strcpy(str, ch); 34 | ps.str = str; 35 | ps.ct = len; 36 | } 37 | void show(const stringy &ps, int n) 38 | { 39 | for(int i = 0; i < n; i++) 40 | cout << ps.str << endl; 41 | } 42 | void show(const char *pc, int n) 43 | { 44 | for(int i = 0; i < n; i++) 45 | cout << pc << endl; 46 | } 47 | -------------------------------------------------------------------------------- /chapter_08/sol-8-05.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 8.5 ------------------------- 3 | 4 | #include 5 | template T max5(T ar[]); 6 | int main(void) 7 | { 8 | int ar1[] {1, 7, 5, 11, 9}; 9 | double ar2[] {1.3, 7.5, 9.5, 5.1, 9.3}; 10 | std::cout << "ar1: " << max5(ar1) << "\nar2: " << max5(ar2) << std::endl; 11 | return 0; 12 | } 13 | template T max5(T ar[]) 14 | { 15 | T max = ar[0]; 16 | for(int i = 0; i < 5; i++) 17 | if(max < ar[i]) max = ar[i]; 18 | return max; 19 | } 20 | -------------------------------------------------------------------------------- /chapter_08/sol-8-06.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 8.6 ------------------------- 3 | 4 | #include 5 | #include 6 | template T maxn(T ar[], int); 7 | template <> const char* maxn(const char* ar[], int); 8 | int main(void) 9 | { 10 | int ar1[6] = {1, 7, 5, 11, 9, 3}; 11 | double ar2[4] = {1.3, 7.5, 9.5, 5.1}; 12 | const char* ar3[5] = {"Fiat", "Honda", "Ferrari", "Volvo", "Bugatti"}; 13 | std::cout << "ar1: " << maxn(ar1, 6) 14 | << "\nar2: " << maxn(ar2, 4) 15 | << "\nar3: " << maxn(ar3, 5) << std::endl; 16 | return 0; 17 | } 18 | template T maxn(T ar[], int n) 19 | { 20 | T max = ar[0]; 21 | for(int i = 0; i < n; i++) 22 | if(max < ar[i]) max = ar[i]; 23 | return max; 24 | } 25 | template <> const char* maxn(const char* ar[], int n) 26 | { 27 | const char* str = ar[0]; 28 | for(int i = 0; i < n; i++) 29 | if(strlen(str) < strlen(ar[i])) str = ar[i]; 30 | return str; 31 | } 32 | -------------------------------------------------------------------------------- /chapter_08/sol-8-07.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 8.7 ------------------------- 3 | 4 | #include 5 | template T SumArray(T arr[], int); 6 | template T SumArray(T *arr[], int); 7 | struct debts 8 | { 9 | char name[50]; 10 | double amount; 11 | }; 12 | int main(void) 13 | { 14 | int things[6] = {13, 31, 103, 301, 310, 130}; 15 | struct debts mr_E[3] = 16 | { 17 | {"Ima Wolfe", 2400.0}, 18 | {"Ura Foxe", 1300.0}, 19 | {"Iby Stout", 1800.0} 20 | }; 21 | double *pd[3]; 22 | for(int i = 0; i < 3; i++) 23 | pd[i] = &mr_E[i].amount; 24 | std::cout << "Total number of things:\n" << SumArray(things, 6) << "\n"; 25 | std::cout << "Total sum of all debts:\n" << SumArray(pd, 3) << "\n"; 26 | return 0; 27 | } 28 | template T SumArray(T arr[], int n) 29 | { 30 | T sum = 0; 31 | for(int i = 0; i < n; i++) 32 | sum += arr[i]; 33 | return sum; 34 | } 35 | template T SumArray(T *arr[], int n) 36 | { 37 | T sum = 0; 38 | for(int i = 0; i < n; i++) 39 | sum += *arr[i]; 40 | return sum; 41 | } 42 | -------------------------------------------------------------------------------- /chapter_09/ProgrammingExercisesChapter_9.txt: -------------------------------------------------------------------------------- 1 | S.Prata C++ Primer Plus 6th ed. 2 | ================================================================================ 3 | PROGRAMMING EXERCISES CHAPTER 9 4 | 5 | 6 | 1. Here is a header file: 7 | 8 | // golf.h -- for pe9-1.cpp 9 | 10 | const int Len = 40; 11 | struct golf 12 | { 13 | char fullname[Len]; 14 | int handicap; 15 | }; 16 | 17 | // non-interactive version: 18 | // function sets golf structure to provided name, handicap 19 | // using values passed as arguments to the function 20 | void setgolf(golf & g, const char * name, int hc); 21 | 22 | // interactive version: 23 | // function solicits name and handicap from user 24 | // and sets the members of g to the values entered 25 | // returns 1 if name is entered, 0 if name is empty string 26 | int setgolf(golf & g); 27 | 28 | // function resets handicap to new value 29 | void handicap(golf & g, int hc); 30 | 31 | // function displays contents of golf structure 32 | void showgolf(const golf & g); 33 | 34 | Note that setgolf() is overloaded. Using the first version of setgolf() 35 | would look like this: 36 | 37 | golf ann; 38 | setgolf(ann, "Ann Birdfree", 24); 39 | 40 | The function call provides the information that’s stored in the ann 41 | structure. Using the second version of setgolf() would look like this: 42 | 43 | golf andy; 44 | setgolf(andy); 45 | 46 | The function would prompt the user to enter the name and handicap and store 47 | them in the andy structure.This function could (but doesn’t need to) use the 48 | first version internally. 49 | 50 | Put together a multifile program based on this header. One file, named 51 | golf.cpp, should provide suitable function definitions to match the 52 | prototypes in the header file. A second file should contain main() and 53 | demonstrate all the features of the prototyped functions. For example, a 54 | loop should solicit input for an array of golf structures and terminate when 55 | the array is full or the user enters an empty string for the golfer’s name. 56 | The main() function should use only the prototyped functions to access the 57 | golf structures. 58 | 59 | 2. Redo Listing 9.9, replacing the character array with a string object. The 60 | program should no longer have to check whether the input string fits, and it 61 | can compare the input string to "" to check for an empty line. 62 | 63 | 3. Begin with the following structure declaration: 64 | 65 | struct chaff 66 | { 67 | char dross[20]; 68 | int slag; 69 | }; 70 | 71 | Write a program that uses placement new to place an array of two such 72 | structures in a buffer. Then assign values to the structure members 73 | (remembering to use strcpy() for the char array) and use a loop to display 74 | the contents. Option 1 is to use a static array, like that in Listing 9.10, 75 | for the buffer. Option 2 is to use regular new to allocate the buffer. 76 | 77 | 4. Write a three-file program based on the following namespace: 78 | 79 | namespace SALES 80 | { 81 | const int QUARTERS = 4; 82 | struct Sales 83 | { 84 | double sales[QUARTERS]; 85 | double average; 86 | double max; 87 | double min; 88 | }; 89 | // copies the lesser of 4 or n items from the array ar 90 | // to the sales member of s and computes and stores the 91 | // average, maximum, and minimum values of the entered items; 92 | // remaining elements of sales, if any, set to 0 93 | void setSales(Sales & s, const double ar[], int n); 94 | // gathers sales for 4 quarters interactively, stores them 95 | // in the sales member of s and computes and stores the 96 | // average, maximum, and minimum values 97 | void setSales(Sales & s); 98 | // display all information in structure s 99 | void showSales(const Sales & s); 100 | } 101 | 102 | The first file should be a header file that contains the namespace. The 103 | second file should be a source code file that extends the namespace to 104 | provide definitions for the three prototyped functions. The third file 105 | should declare two Sales objects. It should use the interactive version of 106 | setSales() to provide values for one structure and the non-interactive 107 | version of setSales() to provide values for the second structure. It should 108 | display the contents of both structures by using showSales(). 109 | 110 | ================================================================================ 111 | -------------------------------------------------------------------------------- /chapter_09/sol-9-02.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 9.2 ------------------------- 3 | 4 | #include 5 | #include 6 | 7 | void strcount(const std::string); 8 | int main(void) 9 | { 10 | using namespace std; 11 | string input; 12 | cout << "Enter a line: \n"; 13 | while(getline(cin, input) && input != "") 14 | { 15 | strcount(input); 16 | cout << "Enter next line (empty line to quit):\n"; 17 | } 18 | cout << "Bye\n"; 19 | return 0; 20 | } 21 | void strcount(const std::string str) 22 | { 23 | using namespace std; 24 | static int total = 0; 25 | int count = str.length(); 26 | cout << "\"" << str << "\" contains "; 27 | total += count; 28 | cout << count << " characters\n"; 29 | cout << total << " characters total\n"; 30 | } 31 | -------------------------------------------------------------------------------- /chapter_09/sol-9-03.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 9.3 ------------------------- 3 | 4 | #include 5 | #include 6 | #include 7 | struct chaff 8 | { 9 | char dross[20]; 10 | int slag; 11 | }; 12 | char baffer[2*sizeof(chaff)]; 13 | int main(void) 14 | { 15 | //Option 1 16 | chaff *ps1 = new (baffer) chaff[2]; 17 | strcpy(ps1[0].dross, "option_1"); 18 | ps1[0].slag = 1; 19 | strcpy(ps1[1].dross, "OPTION_1"); 20 | ps1[1].slag = 2; 21 | //Option 2 22 | chaff *ps2 = new chaff[2]; 23 | strcpy(ps2[0].dross, "option_2"); 24 | ps2[0].slag = 100; 25 | strcpy(ps2[1].dross, "OPTION_2"); 26 | ps2[1].slag = 200; 27 | //Resume 28 | for(int i = 0; i < 2; i++) 29 | std::cout << "dross: " << ps1[i].dross << " slag: " << ps1[i].slag 30 | << "\ndross: " << ps2[i].dross << " slag: " << ps2[i].slag 31 | << std::endl; 32 | delete []ps2; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /chapter_09/sol_09_01/golf.cpp: -------------------------------------------------------------------------------- 1 | // golf.cpp --for sol-9-01.cpp 2 | 3 | #include "golf.h" 4 | #include 5 | #include 6 | 7 | void setgolf(golf &g, const char *name, int hc) 8 | { 9 | strcpy(g.fullname, name); 10 | g.handicap = hc; 11 | } 12 | int setgolf(golf &g) 13 | { 14 | std::cout << "Enter full name: "; 15 | char tmp[Len]; 16 | std::cin.get(tmp, Len); 17 | if(tmp[0] == '\0') 18 | { 19 | std::cin.clear(); 20 | return 0; 21 | } 22 | while(std::cin.get() != '\n') 23 | continue; 24 | strcpy(g.fullname, tmp); 25 | std::cout << "Enter handicap: "; 26 | (std::cin >> g.handicap).get(); 27 | return 1; 28 | } 29 | void handicap(golf &g, int hc) 30 | { 31 | g.handicap = hc; 32 | } 33 | void showgolf(const golf &g) 34 | { 35 | std::cout << "Name: " << g.fullname 36 | << "\nhandicap: " << g.handicap << std::endl; 37 | } 38 | -------------------------------------------------------------------------------- /chapter_09/sol_09_01/golf.h: -------------------------------------------------------------------------------- 1 | // golf.h --for sol-9-01.cpp 2 | 3 | #ifndef GOLF_H_ 4 | #define GOLF_H_ 5 | 6 | const int Len = 40; 7 | struct golf 8 | { 9 | char fullname[Len]; 10 | int handicap; 11 | }; 12 | void setgolf(golf &g, const char *name, int hc); 13 | int setgolf(golf &g); 14 | void handicap(golf &g, int hc); 15 | void showgolf(const golf &g); 16 | 17 | #endif 18 | -------------------------------------------------------------------------------- /chapter_09/sol_09_01/sol-9-01.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 9.1 ------------------------- 3 | 4 | #include "golf.h" 5 | 6 | const int SIZE = 5; 7 | int main() 8 | { 9 | golf ann; 10 | setgolf(ann, "Ann Birdfree", 24); 11 | showgolf(ann); 12 | handicap(ann, 30); 13 | showgolf(ann); 14 | golf arr[SIZE]; 15 | int player = 0; 16 | while(player < SIZE && setgolf(arr[player])) 17 | player++; 18 | for(int i = 0; i < player; i++) 19 | showgolf(arr[i]); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /chapter_09/sol_09_04/sales.cpp: -------------------------------------------------------------------------------- 1 | // sales.cpp --for sol-9-04.cpp 2 | 3 | #include "sales.h" 4 | #include 5 | 6 | namespace SALES 7 | { 8 | void setSales(Sales & s, const double ar[], int n) 9 | { 10 | double max, min, total = .0; 11 | for(int i = 0; i < QUARTERS; i++) 12 | { 13 | if(n > i) s.sales[i] = ar[i]; 14 | else s.sales[i] = .0; 15 | total += s.sales[i]; 16 | } 17 | max = min = s.sales[0]; 18 | for(int i = 0; i < n && i < QUARTERS; i++) 19 | { 20 | if(max < s.sales[i]) max = s.sales[i]; 21 | if(min > s.sales[i]) min = s.sales[i]; 22 | } 23 | s.max = max; 24 | s.min = min; 25 | s.average = (n < QUARTERS) ? total/n : total/QUARTERS; 26 | } 27 | void setSales(Sales & s) 28 | { 29 | double max, min, total = .0; 30 | for(int i = 0; i < QUARTERS; i++) 31 | { 32 | std::cout << "Enter sales #" << i+1 << ": "; 33 | std::cin >> s.sales[i]; 34 | total += s.sales[i]; 35 | } 36 | max = min = s.sales[0]; 37 | for(int i = 0; i < QUARTERS; i++) 38 | { 39 | if(max < s.sales[i]) max = s.sales[i]; 40 | if(min > s.sales[i]) min = s.sales[i]; 41 | } 42 | s.average = total/QUARTERS; 43 | s.max = max; 44 | s.min = min; 45 | } 46 | void showSales(const Sales & s) 47 | { 48 | for(int i = 0; i < QUARTERS; i++) 49 | std::cout << "sales #" << i+1 << ": " << s.sales[i] << std::endl; 50 | std::cout << "average: " << s.average << "\n" 51 | << "max: " << s.max << "\n" 52 | << "min: " << s.min << std::endl; 53 | } 54 | } // namespace SALES 55 | -------------------------------------------------------------------------------- /chapter_09/sol_09_04/sales.h: -------------------------------------------------------------------------------- 1 | // sales.h --for sol-9-04.cpp 2 | 3 | #ifndef SALES_H_ 4 | #define SALES_H_ 5 | 6 | namespace SALES 7 | { 8 | const int QUARTERS = 4; 9 | struct Sales 10 | { 11 | double sales[QUARTERS]; 12 | double average; 13 | double max; 14 | double min; 15 | }; 16 | void setSales(Sales & s, const double ar[], int n); 17 | void setSales(Sales & s); 18 | void showSales(const Sales & s); 19 | 20 | } // namespace SALES 21 | 22 | #endif // SALES_H_ 23 | -------------------------------------------------------------------------------- /chapter_09/sol_09_04/sol-9-04.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 9.4 ------------------------- 3 | 4 | #include "sales.h" 5 | 6 | int main(void) 7 | { 8 | SALES::Sales sal1; 9 | SALES::setSales(sal1); 10 | SALES::showSales(sal1); 11 | double ar[3] = {120.2, 302.5, 177.3}; 12 | SALES::Sales sal2; 13 | SALES::setSales(sal2, ar, 3); 14 | SALES::showSales(sal2); 15 | return 0; 16 | } 17 | 18 | -------------------------------------------------------------------------------- /chapter_10/ProgrammingExercisesChapter_10.txt: -------------------------------------------------------------------------------- 1 | S.Prata C++ Primer Plus 6th ed. 2 | ================================================================================ 3 | PROGRAMMING EXERCISES CHAPTER 10 4 | 5 | 6 | 1. Provide method definetions for the class described in Chapter Review 7 | Question 5 and write a short program that illustrates all the features. 8 | 9 | 2. Here is a rather simple class definition: 10 | 11 | class Person { 12 | private: 13 | static const LIMIT = 25; 14 | string lname; // Person’s last name 15 | char fname[LIMIT]; // Person’s first name 16 | public: 17 | Person() {lname = ""; fname[0] = ‘\0’; } // #1 18 | Person(const string & ln, const char * fn = "Heyyou"); // #2 19 | // the following methods display lname and fname 20 | void Show() const; // firstname lastname format 21 | void FormalShow() const; // lastname, firstname format 22 | }; 23 | 24 | (It uses both a string object and a character array so that you can compare 25 | how the two forms are used.) Write a program that completes the 26 | implementation by providing code for the undefined methods. The program in 27 | which you use the class should also use the three possible constructor calls 28 | (no arguments,one argument, and two arguments) and the two display methods. 29 | Here’s an example that uses the constructors and methods: 30 | 31 | Person one; // use default constructor 32 | Person two("Smythecraft"); // use #2 with one default argument 33 | Person three("Dimwiddy", "Sam"); // use #2, no defaults 34 | one.Show(); 35 | cout << endl; 36 | one.FormalShow(); 37 | // etc. for two and three 38 | 39 | 3. Do Programming Exercise 1 from Chapter 9 but replace the code shown there 40 | with an appropriate golf class declaration. Replace setgolf(golf &, const 41 | char*, int) with a constructor with the appropriate argument for providing 42 | initial values. Retain the interactive version of setgolf() but implement it 43 | by using the constructor. (For example,for the code for setgolf(), obtain 44 | the data,pass the data to the constructor to create a temporary object, and 45 | assign the temporary object to the invoking object, which is *this.) 46 | 47 | 4. Do Programming Exercise 4 from Chapter 9 but convert the Sales structure and 48 | its associated functions to a class and its methods. Replace the 49 | setSales(Sales &, double[], int) function with a constructor. Implement the 50 | interactive setSales(Sales &) method by using the constructor. Keep the 51 | class within the namespace SALES. 52 | 53 | 5. Consider the following structure declaration: 54 | 55 | struct customer { 56 | char fullname[35]; 57 | double payment; 58 | }; 59 | 60 | Write a program that adds and removes customer structures from a stack, 61 | represented by a Stack class declaration. Each time a customer is removed, 62 | his or her payment should be added to a running total, and the running total 63 | should be reported. Note: You should be able to use the Stack class 64 | unaltered; just change the typedef declaration so that Item is type customer 65 | instead of unsigned long. 66 | 67 | 6. Here’s a class declaration: 68 | 69 | class Move 70 | { 71 | private: 72 | double x; 73 | double y; 74 | public: 75 | Move(double a = 0, double b = 0); // sets x, y to a, b 76 | showmove() const; // shows current x, y values 77 | Move add(const Move & m) const; 78 | // this function adds x of m to x of invoking object to get new x, 79 | // adds y of m to y of invoking object to get new y, creates a new 80 | // move object initialized to new x, y values and returns it 81 | reset(double a = 0, double b = 0); // resets x, y to a, b 82 | }; 83 | 84 | Create member function definitions and a program that exercises the class. 85 | 86 | 7. A Betelgeusean plorg has these properties: 87 | 88 | Data 89 | A plorg has a name with no more than 19 letters. 90 | A plorg has a contentment index (CI), which is an integer. 91 | Operations 92 | A new plorg starts out with a name and a CI of 50. 93 | A plorg’s CI can change. 94 | A plorg can report its name and CI. 95 | The default plorg has the name "Plorga" . 96 | 97 | Write a Plorg class declaration (including data members and member function 98 | prototypes) that represents a plorg.Write the function definitions for the 99 | member functions. Write a short program that demonstrates all the features 100 | of the Plorg class. 101 | 102 | 8. You can describe a simple list as follows: 103 | 104 | - The simple list can hold zero or more items of some particular type. 105 | - You can create an empty list. 106 | - You can add items to the list. 107 | - You can determine whether the list is empty. 108 | - You can determine whether the list is full. 109 | - You can visit each item in the list and perform some action on it. 110 | 111 | As you can see, this list really is simple; it doesn’t allow insertion or 112 | deletion, for example. 113 | 114 | Design a List class to represent this abstract type. You should provide a 115 | list.h header file with the class declaration and a list.cpp file with the 116 | class method implementations. You should also create a short program that 117 | utilizes your design. 118 | 119 | The main reason for keeping the list specification simple is to simplify 120 | this programming exercise. You can implement the list as an array or, if 121 | you’re familiar with the data type, as a linked list. But the public 122 | interface should not depend on your choice. That is, the public interface 123 | should not have array indices,pointers to nodes, and so on. It should be 124 | expressed in the general concepts of creating a list, adding an item to the 125 | list, and so on. The usual way to handle visiting each item and performing 126 | an action is to use a function that takes a function pointer as an argument: 127 | 128 | void visit(void (*pf)(Item &)); 129 | 130 | Here pf points to a function (not a member function) that takes a reference 131 | to Item argument, where Item is the type for items in the list. The visit() 132 | function applies this function to each item in the list. You can use the 133 | Stack class as a general guide. 134 | 135 | ================================================================================ 136 | -------------------------------------------------------------------------------- /chapter_10/sol_10_01/bank_10.cpp: -------------------------------------------------------------------------------- 1 | // bank_10.cpp --for sol-10-01.cpp 2 | 3 | #include "bank_10.h" 4 | #include 5 | 6 | BankAccount::BankAccount(const std::string &client, const std::string &num, double bal) 7 | { 8 | name = client; 9 | acctnum = num; 10 | if(bal < 0) 11 | { 12 | std::cout << "Number of ballance can't be negative; balance set to 0.\n"; 13 | balance = .0; 14 | } 15 | else 16 | balance = bal; 17 | } 18 | void BankAccount::show(void) const 19 | { 20 | std::cout << "Name: " << name 21 | << "\naccount: " << acctnum 22 | << "\nbalance: " << balance << std::endl; 23 | } 24 | void BankAccount::deposit(double cash) 25 | { 26 | if(cash < 0) 27 | std::cout << "Number of deposit can't be negative. " 28 | << "Transaction is aborted.\n"; 29 | else 30 | balance += cash; 31 | } 32 | void BankAccount::withdraw(double cash) 33 | { 34 | if(cash < 0) 35 | std::cout << "Number of withdraw can't be negative. " 36 | << "Transaction is aborted.\n"; 37 | else if(cash > balance) 38 | std::cout << "You can't withdraw more than you have! " 39 | << "Transaction is aborted.\n"; 40 | else 41 | balance -= cash; 42 | } 43 | -------------------------------------------------------------------------------- /chapter_10/sol_10_01/bank_10.h: -------------------------------------------------------------------------------- 1 | // bank_10.h --for sol-10-01.cpp 2 | 3 | #ifndef BANK_H_ 4 | #define BANK_H_ 5 | 6 | #include 7 | 8 | class BankAccount 9 | { 10 | private: 11 | std::string name; 12 | std::string acctnum; 13 | double balance; 14 | public: 15 | BankAccount(const std::string &client, 16 | const std::string &num, double bal = 0.0); 17 | void show(void) const; 18 | void deposit(double cash); 19 | void withdraw(double cash); 20 | }; 21 | 22 | #endif // BANK_H_ 23 | -------------------------------------------------------------------------------- /chapter_10/sol_10_01/sol-10-01.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 10.1 ------------------------ 3 | 4 | #include "bank_10.h" 5 | 6 | int main(void) 7 | { 8 | BankAccount test {"Client", "test"}; 9 | test.show(); 10 | test.deposit(1000); 11 | test.show(); 12 | test.withdraw(300); 13 | test.show(); 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /chapter_10/sol_10_02/person_10.cpp: -------------------------------------------------------------------------------- 1 | // persone_10.cpp --for sol-10-02.cpp 2 | 3 | #include "person_10.h" 4 | #include 5 | #include 6 | 7 | Person::Person(const std::string &ln, const char *fn) 8 | { 9 | lname = ln; 10 | strncpy(fname, fn, LIMIT-1); 11 | fname[LIMIT-1] = '\0'; 12 | } 13 | void Person::Show() const 14 | { 15 | std::cout << "Name: " << lname << "\nfname: " << fname << std::endl; 16 | } 17 | void Person::FormalShow() const 18 | { 19 | std::cout << "Formal name: " << fname << " " << lname << std::endl; 20 | } 21 | -------------------------------------------------------------------------------- /chapter_10/sol_10_02/person_10.h: -------------------------------------------------------------------------------- 1 | // person_10.h --for sol-10-02.cpp 2 | 3 | #ifndef PERSON_H_ 4 | #define PERSON_H_ 5 | 6 | #include 7 | 8 | class Person 9 | { 10 | private: 11 | static const int LIMIT = 25; 12 | std::string lname; 13 | char fname[LIMIT]; 14 | public: 15 | Person(){lname = ""; fname[0] = '\0';} 16 | Person(const std::string &ln, const char *fn = "Heyyou"); 17 | void Show() const; 18 | void FormalShow() const; 19 | }; 20 | 21 | #endif // PERSON_H_ 22 | -------------------------------------------------------------------------------- /chapter_10/sol_10_02/sol-10-02.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 10.2 ------------------------ 3 | 4 | #include "person_10.h" 5 | #include 6 | 7 | int main(void) 8 | { 9 | Person one; 10 | Person two("Smythecraft"); 11 | Person three("Dimwiddy", "Sam"); 12 | one.Show(); 13 | one.FormalShow(); 14 | std::cout << std::endl; 15 | two.Show(); 16 | two.FormalShow(); 17 | std::cout << std::endl; 18 | three.Show(); 19 | three.FormalShow(); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /chapter_10/sol_10_03/golf_10.cpp: -------------------------------------------------------------------------------- 1 | // golf_10.cpp --for sol-10-03.cpp 2 | 3 | #include "golf_10.h" 4 | #include 5 | #include 6 | 7 | Golf::Golf(const char *name, int hc) 8 | { 9 | strncpy(fullname, name, Len-1); 10 | fullname[Len-1] = '\0'; 11 | handicap = hc; 12 | } 13 | int Golf::setgolf() 14 | { 15 | char str[Len]; 16 | int hand; 17 | std::cout << "Enter full name: "; 18 | std::cin.get(str, Len); 19 | if(str[0] == '\0') 20 | { 21 | std::cin.clear(); 22 | return 0; 23 | } 24 | while(std::cin.get() != '\n') 25 | continue; 26 | std::cout << "Enter handicap: "; 27 | (std::cin >> hand).get(); 28 | Golf tmp {str, hand}; 29 | *this = tmp; 30 | return 1; 31 | } 32 | void Golf::sethandicap(int hc) 33 | { 34 | handicap = hc; 35 | } 36 | void Golf::showgolf() const 37 | { 38 | std::cout << "Name: " << fullname 39 | << "\nhandicap: " << handicap << std::endl; 40 | } 41 | -------------------------------------------------------------------------------- /chapter_10/sol_10_03/golf_10.h: -------------------------------------------------------------------------------- 1 | // golf_10.h --for sol-10-03.cpp 2 | 3 | #ifndef GOLF_H_ 4 | #define GOLF_H_ 5 | 6 | class Golf 7 | { 8 | private: 9 | static const int Len = 40; 10 | char fullname[Len]; 11 | int handicap; 12 | public: 13 | Golf(const char *name = "", int hc = 0); 14 | int setgolf(); 15 | void sethandicap(int hc); 16 | void showgolf() const; 17 | }; 18 | 19 | #endif // GOLF_H_ 20 | -------------------------------------------------------------------------------- /chapter_10/sol_10_03/sol-10-03.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 10.3 ------------------------- 3 | 4 | #include "golf_10.h" 5 | 6 | const int SIZE = 5; 7 | int main(void) 8 | { 9 | Golf ann {"Ann Birdfree", 24}; 10 | ann.showgolf(); 11 | ann.sethandicap(30); 12 | ann.showgolf(); 13 | Golf arr[SIZE]; 14 | int player = 0; 15 | while(player < SIZE && arr[player].setgolf()) 16 | player++; 17 | for(int i = 0; i < player; i++) 18 | arr[i].showgolf(); 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /chapter_10/sol_10_04/sales_10.cpp: -------------------------------------------------------------------------------- 1 | // sales_10.cpp --for sol-9-04.cpp 2 | 3 | #include "sales_10.h" 4 | #include 5 | 6 | namespace SALES 7 | { 8 | Sales::Sales(const double ar[], int n) 9 | { 10 | double max, min, total = .0; 11 | for(int i = 0; i < QUARTERS; i++) 12 | { 13 | if(n > i) sales[i] = ar[i]; 14 | else sales[i] = .0; 15 | total += sales[i]; 16 | } 17 | max = min = sales[0]; 18 | for(int i = 0; i < n && i < QUARTERS; i++) 19 | { 20 | if(max < sales[i]) max = sales[i]; 21 | if(min > sales[i]) min = sales[i]; 22 | } 23 | s_max = max; 24 | s_min = min; 25 | average = (n < QUARTERS) ? total/n : total/QUARTERS; 26 | } 27 | void Sales::setSales() 28 | { 29 | double arr[QUARTERS]; 30 | for(int i = 0; i < QUARTERS; i++) 31 | { 32 | std::cout << "Enter sales #" << i+1 << ": "; 33 | std::cin >> arr[i]; 34 | } 35 | Sales tmp(arr, QUARTERS); 36 | *this = tmp; 37 | } 38 | void Sales::showSales() const 39 | { 40 | for(int i = 0; i < QUARTERS; i++) 41 | std::cout << "sales #" << i+1 << ": " << sales[i] << std::endl; 42 | std::cout << "average: " << average << "\n" 43 | << "max: " << s_max << "\n" 44 | << "min: " << s_min << std::endl; 45 | } 46 | } // namespace SALES 47 | -------------------------------------------------------------------------------- /chapter_10/sol_10_04/sales_10.h: -------------------------------------------------------------------------------- 1 | // sales_10.h --for sol-9-04.cpp 2 | 3 | #ifndef SALES_H_ 4 | #define SALES_H_ 5 | 6 | namespace SALES 7 | { 8 | class Sales 9 | { 10 | private: 11 | enum { QUARTERS = 4 }; 12 | double sales[QUARTERS]{}; 13 | double average; 14 | double s_max; 15 | double s_min; 16 | public: 17 | Sales(){ s_max = s_min = average = 0; } 18 | Sales(const double ar[], int n); 19 | void setSales(); 20 | void showSales() const; 21 | }; 22 | 23 | } // namespace SALES 24 | 25 | #endif // SALES_H_ 26 | -------------------------------------------------------------------------------- /chapter_10/sol_10_04/sol-10-04.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 10.4 ------------------------ 3 | 4 | #include "sales_10.h" 5 | 6 | int main(void) 7 | { 8 | SALES::Sales sal1; 9 | sal1.setSales(); 10 | sal1.showSales(); 11 | double ar[3] = {120.2, 302.5, 177.3}; 12 | SALES::Sales sal2(ar, 3); 13 | sal2.showSales(); 14 | return 0; 15 | } 16 | 17 | -------------------------------------------------------------------------------- /chapter_10/sol_10_05/sol-10-05.cpp: -------------------------------------------------------------------------------- 1 | #include "stack_10.h" 2 | #include 3 | #include 4 | 5 | int main(void) 6 | { 7 | Stack st; 8 | char ch; 9 | double total = 0; 10 | customer po; 11 | std::cout << "Pleace enter A to add customer, \n" 12 | << "P to process a PO, or Q to quit.\n"; 13 | while(std::cin >> ch && toupper(ch) != 'Q') 14 | { 15 | while(std::cin.get() != '\n') 16 | continue; 17 | if(!isalpha(ch)) 18 | { 19 | std::cout << '\a'; 20 | continue; 21 | } 22 | switch(ch) 23 | { 24 | case 'A': 25 | case 'a': std::cout << "Enter full name: "; 26 | std::cin.get(po.fullname, 35); 27 | while(std::cin.get() != '\n') 28 | continue; 29 | std::cout << "Enter payment amount: "; 30 | std::cin >> po.payment; 31 | if(st.isfull()) 32 | std::cout << "stack already full\n"; 33 | else 34 | st.push(po); 35 | break; 36 | case 'P': 37 | case 'p': if(st.isempty()) 38 | std::cout << "stack already empty\n"; 39 | else { 40 | st.pop(po); 41 | std::cout << "PO #" << (total += po.payment) << " popped\n"; 42 | } 43 | break; 44 | } 45 | std::cout << "Please enter A to add customer,\n" 46 | << "P to process a PO, or Q to quit.\n"; 47 | } 48 | std::cout << "Bye\n"; 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /chapter_10/sol_10_05/stack_10.cpp: -------------------------------------------------------------------------------- 1 | // stack.cpp --for sol-10-05.cpp 2 | 3 | #include "stack_10.h" 4 | 5 | bool Stack::isempty() const 6 | { 7 | return top == 0; 8 | } 9 | bool Stack::isfull() const 10 | { 11 | return top == MAX; 12 | } 13 | bool Stack::push(const Item & item) 14 | { 15 | if(top < MAX) 16 | { 17 | items[top++] = item; 18 | return true; 19 | } else 20 | return false; 21 | } 22 | bool Stack::pop(Item & item) 23 | { 24 | if(top > 0) 25 | { 26 | item = items[--top]; 27 | return true; 28 | } else 29 | return false; 30 | } 31 | -------------------------------------------------------------------------------- /chapter_10/sol_10_05/stack_10.h: -------------------------------------------------------------------------------- 1 | // stack.h --for sol-10-05.cpp 2 | 3 | #ifndef STACK_H_ 4 | #define STACK_H_ 5 | 6 | struct customer { 7 | char fullname[35]; 8 | double payment; 9 | }; 10 | typedef customer Item; 11 | class Stack 12 | { 13 | private: 14 | enum {MAX = 10}; 15 | Item items[MAX]{}; 16 | int top; 17 | public: 18 | Stack() { top = 0; } 19 | bool isempty() const; 20 | bool isfull() const; 21 | bool push(const Item & item); 22 | bool pop(Item & item); 23 | }; 24 | 25 | #endif // STACK_H_ 26 | -------------------------------------------------------------------------------- /chapter_10/sol_10_06/move_10.cpp: -------------------------------------------------------------------------------- 1 | // move_10.cpp --for sol-10-06.cpp 2 | 3 | #include "move_10.h" 4 | #include 5 | 6 | Move::Move(double a, double b) 7 | { 8 | x = a; 9 | y = b; 10 | } 11 | void Move::showmove() const 12 | { 13 | std::cout << "x = " << x << "; y = " << y << ";\n"; 14 | } 15 | Move Move::add(const Move & m) const 16 | { 17 | return Move(x + m.x, y + m.y); 18 | } 19 | void Move::reset(double a, double b) 20 | { 21 | x = a; 22 | y = b; 23 | } 24 | -------------------------------------------------------------------------------- /chapter_10/sol_10_06/move_10.h: -------------------------------------------------------------------------------- 1 | // move_10.h --for sol-10-06.cpp 2 | 3 | #ifndef MOVE_H_ 4 | #define MOVE_H_ 5 | 6 | class Move 7 | { 8 | private: 9 | double x; 10 | double y; 11 | public: 12 | Move(double a = 0, double b = 0); 13 | void showmove() const; 14 | Move add(const Move & m) const; 15 | void reset(double a = 0, double b = 0); 16 | }; 17 | 18 | #endif // MOVE_H_ 19 | -------------------------------------------------------------------------------- /chapter_10/sol_10_06/sol-10-06.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 10.6 ------------------------ 3 | 4 | #include "move_10.h" 5 | 6 | int main(void) 7 | { 8 | Move test0(7, 14); 9 | Move test1(100.3, 34.7); 10 | test0.showmove(); 11 | test1.showmove(); 12 | Move test2 = test0.add(test1); 13 | test2.showmove(); 14 | test2.reset(); 15 | test2.showmove(); 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /chapter_10/sol_10_07/plorg_10.cpp: -------------------------------------------------------------------------------- 1 | // plorg_10.cpp --for sol-10-07.cpp 2 | 3 | #include "plorg_10.h" 4 | #include 5 | #include 6 | 7 | Plorg::Plorg(const char *name, int i) 8 | { 9 | strncpy(fullname, name, Len); 10 | fullname[Len-1] = '\0'; 11 | ci = i; 12 | } 13 | void Plorg::show() const 14 | { 15 | std::cout << "Plorg\n name: " << fullname << "\n CI: " << ci << "\n"; 16 | } 17 | void Plorg::changeCI(int i) 18 | { 19 | ci = i; 20 | } 21 | -------------------------------------------------------------------------------- /chapter_10/sol_10_07/plorg_10.h: -------------------------------------------------------------------------------- 1 | // plorg_10.h --for sol-10-07.cpp 2 | 3 | #ifndef PLORG_H_ 4 | #define PLORG_H_ 5 | 6 | class Plorg 7 | { 8 | private: 9 | static const int Len = 19; 10 | char fullname[Len]; 11 | int ci; 12 | public: 13 | Plorg(const char *name = "Plorga", int i = 50); 14 | void show() const; 15 | void changeCI(int i); 16 | }; 17 | 18 | #endif // PLORG_H_ 19 | -------------------------------------------------------------------------------- /chapter_10/sol_10_07/sol-10-07.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 10.7 ------------------------ 3 | 4 | #include "plorg_10.h" 5 | 6 | int main(void) 7 | { 8 | Plorg pl0; 9 | pl0.show(); 10 | Plorg pl("Avatar", 37); 11 | pl.show(); 12 | pl.changeCI(77); 13 | pl.show(); 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /chapter_10/sol_10_08/list_10.cpp: -------------------------------------------------------------------------------- 1 | // list_10.cpp --for sol-10-08.cpp 2 | 3 | #include "list_10.h" 4 | #include 5 | 6 | List::List() 7 | { 8 | top = 0; 9 | } 10 | bool List::isempty() const 11 | { 12 | return top == 0; 13 | } 14 | bool List::isfull() const 15 | { 16 | return top == MAX; 17 | } 18 | void List::add(const Item & item) 19 | { 20 | if(top < MAX) 21 | items[top++] = item; 22 | } 23 | void List::visit(void (*pf)(Item &)) 24 | { 25 | for(int i = 0; i < top; i++) 26 | pf(items[i]); 27 | } 28 | void List::show() const 29 | { 30 | if(isempty()) 31 | std::cout << "List is empty.\n"; 32 | else 33 | for(int i = 0; i < top; i++) 34 | std::cout << "Item #" << i + 1 << ": " << items[i] << "\n"; 35 | } 36 | -------------------------------------------------------------------------------- /chapter_10/sol_10_08/list_10.h: -------------------------------------------------------------------------------- 1 | // list_10.h --for sol-10-08.cpp 2 | 3 | #ifndef LIST_H_ 4 | #define LIST_H_ 5 | 6 | typedef double Item; 7 | class List 8 | { 9 | private: 10 | enum{MAX = 10}; 11 | Item items[MAX]{}; 12 | int top; 13 | public: 14 | List(); 15 | bool isempty() const; 16 | bool isfull() const; 17 | void add(const Item &); 18 | void show() const; 19 | void visit(void (*pf)(Item &)); 20 | }; 21 | 22 | #endif // LIST_H_ 23 | -------------------------------------------------------------------------------- /chapter_10/sol_10_08/sol-10-08.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ------------------------ Programming Exercises 10.8 ------------------------ 3 | 4 | #include "list_10.h" 5 | #include 6 | 7 | void sqr(double & y){ y *= y; } 8 | int main(void) 9 | { 10 | List lst; 11 | double tmp; 12 | std::cout << "Enter a number (q to quit): "; 13 | while(std::cin >> tmp) 14 | { 15 | lst.add(tmp); 16 | if(lst.isfull()) break; 17 | std::cout << "Enter a number (q to quit): "; 18 | } 19 | lst.show(); 20 | lst.visit(sqr); 21 | lst.show(); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /chapter_11/ProgrammingExercisesChapter_11.txt: -------------------------------------------------------------------------------- 1 | S.Prata C++ Primer Plus 6th ed. 2 | ================================================================================ 3 | PROGRAMMING EXERCISES CHAPTER 11 4 | 5 | 6 | 1. Modify Listing 11.15 so that it writes the successive locations of the 7 | random walker into a file. Label each position with the step number. Also 8 | have the program write the initial conditions (target distance and step 9 | size) and the summarized results to the file. The file contents might look 10 | like this: 11 | 12 | Target Distance: 100, Step Size: 20 13 | 0: (x,y) = (0, 0) 14 | 1: (x,y) = (-11.4715, 16.383) 15 | 2: (x,y) = (-8.68807, -3.42232) 16 | ... 17 | 26: (x,y) = (42.2919, -78.2594) 18 | 27: (x,y) = (58.6749, -89.7309) 19 | After 27 steps, the subject has the following location: 20 | (x,y) = (58.6749, -89.7309) 21 | or 22 | (m,a) = (107.212, -56.8194) 23 | Average outward distance per step = 3.97081 24 | 25 | 2. Modify the Vector class header and implementation files (Listings 11.13 26 | and 11.14) so that the magnitude and angle are no longer stored as data 27 | components. Instead, they should be calculated on demand when the magval() 28 | and angval() methods are called. You should leave the public interface 29 | unchanged (the same public methods with the same arguments) but alter the 30 | private section, including some of the private method and the method 31 | implementations. Test the modified version with Listing 11.15, which should 32 | be left unchanged because the public interface of the Vector class is 33 | unchanged. 34 | 35 | 3. Modify Listing 11.15 so that instead of reporting the results of a single 36 | trial for a particular target/step combination, it reports the highest, 37 | lowest, and average number of steps for N trials, where N is an integer 38 | entered by the user. 39 | 40 | 4. Rewrite the final Time class example (Listings 11.10, 11.11, and 11.12) so 41 | that all the overloaded operators are implemented using friend functions. 42 | 43 | 5. Rewrite the Stonewt class (Listings 11.16 and 11.17) so that it has a state 44 | member that governs whether the object is interpreted in stone form, integer 45 | pounds form, or floating-point pounds form. Overload the << operator to 46 | replace the show_stn() and show_lbs() methods. Overload the addition, 47 | subtraction, and multiplication operators so that one can add, subtract, and 48 | multiply Stonewt values. Test your class with a short program that uses all 49 | the class methods and friends. 50 | 51 | 6. Rewrite the Stonewt class (Listings 11.16 and 11.17) so that it overloads 52 | all six relational operators. The operators should compare the pounds 53 | members and return a type bool value. Write a program that declares an 54 | arrayof six Stonewt objects and initializes the first three objects in the 55 | array declaration. Then it should use a loop to read in values used to set 56 | the remaining three array elements. Then it should report the smallest 57 | element, the largest element,and how many elements are greater or equal 58 | to 11 stone. (The simplest approach is to create a Stonewt object 59 | initialized to 11 stone and to compare the other objects with that object.) 60 | 61 | 7. A complex number has two parts:a real part and an imaginary part. One way to 62 | write an imaginary number is this: (3.0,4.0). Here 3.0 is the real part and 63 | 4.0 is the imaginary part. Suppose a = (A,Bi) and c = (C,Di). Here are some 64 | complex operations: 65 | 66 | - Addition: a + c = (A + C,(B + D)i) 67 | - Subtraction: a - c = (A - C,(B - D)i) 68 | - Multiplication: a × c = (A × C - B×D,(A×D + B×C)i) 69 | - Multiplication: (x a real number):x × c = (x×C,x×Di) 70 | - Conjugation:~a = (A,- Bi) 71 | 72 | Define a complex class so that the following program can use it with correct 73 | results: 74 | 75 | #include 76 | using namespace std; 77 | #include "complex0.h" // to avoid confusion with complex.h 78 | int main() 79 | { 80 | complex a(3.0, 4.0); // initialize to (3,4i) 81 | complex c; 82 | cout << "Enter a complex number (q to quit):\n"; 83 | while (cin >> c) 84 | { 85 | cout << "c is " << c << "\n"; 86 | cout << "complex conjugate is " << ~c << "\n"; 87 | cout << "a is " << a << "\n"; 88 | cout << "a + c is " << a + c << "\n'; 89 | cout << "a - c is " << a - c << "\n"; 90 | cout << "a * c is " << a * c << "\n"; 91 | cout << "2 * c is " << 2 * c << "\n"; 92 | cout << "Enter a complex number (q to quit):\n"; 93 | } 94 | cout << "Done!\n"; 95 | return 0; 96 | } 97 | 98 | Note that you have to overload the << and >> operators. Standard C++ already 99 | has complex support—-rather more extensive than in this example-—in a 100 | complex header file, so use complex0.h to avoid conflicts. Use const 101 | whenever warranted. 102 | 103 | Here is a sample run of the program: 104 | 105 | Enter a complex number (q to quit): 106 | real: 10 107 | imaginary: 12 108 | c is (10,12i) 109 | complex conjugate is (10,-12i) 110 | a is (3,4i) 111 | a + c is (13,16i) 112 | a - c is (-7,-8i) 113 | a * c is (-18,76i) 114 | 2 * c is (20,24i) 115 | Enter a complex number (q to quit): 116 | real: q 117 | Done! 118 | 119 | Note that cin >> c, through overloading,now prompts for real and imaginary 120 | parts. 121 | 122 | ================================================================================ 123 | -------------------------------------------------------------------------------- /chapter_11/sol_11_01/sol-11-01.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 11.1 ------------------------- 3 | 4 | #include "vect_11_01.h" 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | int main(void) 11 | { 12 | using namespace std; 13 | using VECTOR::Vector; 14 | ofstream fout; 15 | fout.open("vect_log.txt"); 16 | srand(time(0)); 17 | double direction; 18 | Vector step; 19 | Vector result(0.0, 0.0); 20 | unsigned long steps = 0; 21 | double target; 22 | double dstep; 23 | cout << "Enter target distance (q to quit): "; 24 | while(cin >> target) 25 | { 26 | cout << "Enter step length: "; 27 | if(!(cin >> dstep)) 28 | break; 29 | fout << "Target Distance: " << target << ", " 30 | << "Step Size: " << dstep << endl; 31 | while(result.magval() < target) 32 | { 33 | fout << steps << ": " << result << endl; 34 | direction = rand() % 360; 35 | step.reset(dstep, direction, Vector::POL); 36 | result = result + step; 37 | steps++; 38 | } 39 | fout << "After " << steps << " steps, the subject " 40 | "has the following location:\n" << result << endl; 41 | 42 | cout << "After " << steps << " steps, the subject " 43 | "has the following location:\n" << result << endl; 44 | result.polar_mode(); 45 | 46 | fout << " or\n" << result << endl; 47 | fout << "Average outward distance per step = " 48 | << result.magval()/steps << endl; 49 | 50 | cout << " or\n" << result << endl; 51 | cout << "Average outward distance per step = " 52 | << result.magval()/steps << endl; 53 | steps = 0; 54 | result.reset(0.0, 0.0); 55 | cout << "Enter target distance (q to quit): "; 56 | } 57 | fout.close(); 58 | cout << "Bye!\n"; 59 | cin.clear(); 60 | while(cin.get() != '\n') 61 | continue; 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /chapter_11/sol_11_01/vect_11_01.cpp: -------------------------------------------------------------------------------- 1 | // vect_11_01.cpp --for sol-11-01.cpp 2 | 3 | #include 4 | #include "vect_11_01.h" 5 | using std::sqrt; 6 | using std::sin; 7 | using std::cos; 8 | using std::atan; 9 | using std::atan2; 10 | using std::cout; 11 | namespace VECTOR 12 | { 13 | const double Rad_to_deg = 45.0/atan(1.0); 14 | void Vector::set_mag() 15 | { 16 | mag = sqrt(x*x+y*y); 17 | } 18 | void Vector::set_ang() 19 | { 20 | if(x == 0.0 && y == 0.0) 21 | ang = 0.0; 22 | else 23 | ang = atan2(y, x); 24 | } 25 | void Vector::set_x() 26 | { 27 | x = mag*cos(ang); 28 | } 29 | void Vector::set_y() 30 | { 31 | y = mag * sin(ang); 32 | } 33 | Vector::Vector() 34 | { 35 | x = y = mag = ang = 0.0; 36 | mode = RECT; 37 | } 38 | Vector::Vector(double n1, double n2, Mode form) 39 | { 40 | mode = form; 41 | if(form == RECT) 42 | { 43 | x = n1; 44 | y = n2; 45 | set_mag(); 46 | set_ang(); 47 | } 48 | else if(form == POL) 49 | { 50 | mag = n1; 51 | ang = n2/Rad_to_deg; 52 | set_x(); 53 | set_y(); 54 | } 55 | else 56 | { 57 | cout << "Incorrect 3rd argument to Vector() -- "; 58 | cout << "vector set to 0\n"; 59 | x = y = mag = ang = 0.0; 60 | mode = RECT; 61 | } 62 | } 63 | void Vector::reset(double n1, double n2, Mode form) 64 | { 65 | mode = form; 66 | if(form == RECT) 67 | { 68 | x = n1; 69 | y = n2; 70 | set_mag(); 71 | set_ang(); 72 | } 73 | else if(form == POL) 74 | { 75 | mag = n1; 76 | ang = n2/Rad_to_deg; 77 | set_x(); 78 | set_y(); 79 | } 80 | else 81 | { 82 | cout << "Incorrect 3rd argument to Vector() -- "; 83 | cout << "vector set to 0\n"; 84 | x = y = mag = ang = 0.0; 85 | mode = RECT; 86 | } 87 | } 88 | Vector::~Vector() 89 | { 90 | } 91 | void Vector::polar_mode() 92 | { 93 | mode = POL; 94 | } 95 | void Vector::rect_mode() 96 | { 97 | mode = RECT; 98 | } 99 | Vector Vector::operator+(const Vector & b) const 100 | { 101 | return Vector(x + b.x, y + b.y); 102 | } 103 | Vector Vector::operator-(const Vector & b) const 104 | { 105 | return Vector(x - b.x, y - b.y); 106 | } 107 | Vector Vector::operator-() const 108 | { 109 | return Vector(-x, -y); 110 | } 111 | Vector Vector::operator*(double n) const 112 | { 113 | return Vector(n * x, n * y); 114 | } 115 | Vector operator*(double n, const Vector & a) 116 | { 117 | return a * n; 118 | } 119 | std::ostream & operator<<(std::ostream & os, const Vector & v) 120 | { 121 | if(v.mode == Vector::RECT) 122 | os << "(x, y) = (" << v.x << ", " << v.y << ")"; 123 | else if(v.mode == Vector::POL) 124 | os << "(m, a) = (" << v.mag << ", " << v.ang * Rad_to_deg << ")"; 125 | else 126 | os << "Vector object mode is invalid"; 127 | return os; 128 | } 129 | } // namespace VECTOR 130 | -------------------------------------------------------------------------------- /chapter_11/sol_11_01/vect_11_01.h: -------------------------------------------------------------------------------- 1 | // vect_11_01.h --for sol-11-01.cpp 2 | 3 | #ifndef VECTOR_H_ 4 | #define VECTOR_H_ 5 | #include 6 | 7 | namespace VECTOR 8 | { 9 | class Vector 10 | { 11 | public: 12 | enum Mode {RECT, POL}; 13 | private: 14 | double x; 15 | double y; 16 | double mag; 17 | double ang; 18 | Mode mode; 19 | 20 | void set_mag(); 21 | void set_ang(); 22 | void set_x(); 23 | void set_y(); 24 | public: 25 | Vector(); 26 | Vector(double n1, double n2, Mode form = RECT); 27 | void reset(double n1, double n2, Mode form = RECT); 28 | ~Vector(); 29 | double xval() const {return x;} 30 | double yval() const {return y;} 31 | double magval() const {return mag;} 32 | double angval() const {return ang;} 33 | void polar_mode(); 34 | void rect_mode(); 35 | Vector operator+(const Vector & b) const; 36 | Vector operator-(const Vector & b) const; 37 | Vector operator-() const; 38 | Vector operator*(double n) const; 39 | friend Vector operator*(double n, const Vector & a); 40 | friend std::ostream & operator<<(std::ostream & os, const Vector & v); 41 | }; 42 | } // namespace VECTOR 43 | #endif // VECTOR_H_ 44 | -------------------------------------------------------------------------------- /chapter_11/sol_11_02/sol-11-02.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 11.2 ------------------------- 3 | 4 | #include "vect_11_02.h" 5 | #include 6 | #include 7 | #include 8 | 9 | int main(void) 10 | { 11 | using namespace std; 12 | using VECTOR::Vector; 13 | srand(time(0)); 14 | double direction; 15 | Vector step; 16 | Vector result(0.0, 0.0); 17 | unsigned long steps = 0; 18 | double target; 19 | double dstep; 20 | cout << "Enter target distance (q to quit): "; 21 | while(cin >> target) 22 | { 23 | cout << "Enter step length: "; 24 | if(!(cin >> dstep)) 25 | break; 26 | while(result.magval() < target) 27 | { 28 | direction = rand() % 360; 29 | step.reset(dstep, direction, Vector::POL); 30 | result = result + step; 31 | steps++; 32 | } 33 | cout << "After " << steps << " steps, the subject " 34 | "has the following location:\n"; 35 | cout << result << endl; 36 | result.polar_mode(); 37 | cout << " or\n" << result << endl; 38 | cout << "Average outward distance per step = " 39 | << result.magval()/steps << endl; 40 | steps = 0; 41 | result.reset(0.0, 0.0); 42 | cout << "Enter target distance (q to quit): "; 43 | } 44 | cout << "Bye!\n"; 45 | cin.clear(); 46 | while(cin.get() != '\n') 47 | continue; 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /chapter_11/sol_11_02/vect_11_02.cpp: -------------------------------------------------------------------------------- 1 | // vect_11_02.cpp --for sol-11-02.cpp 2 | 3 | #include 4 | #include "vect_11_02.h" 5 | 6 | using std::sqrt; 7 | using std::sin; 8 | using std::cos; 9 | using std::atan; 10 | using std::atan2; 11 | using std::cout; 12 | namespace VECTOR 13 | { 14 | const double Rad_to_deg = 45.0/atan(1.0); 15 | Vector::Vector() 16 | { 17 | x = y = 0.0; 18 | mode = RECT; 19 | } 20 | Vector::Vector(double n1, double n2, Mode form) 21 | { 22 | mode = form; 23 | if(form == RECT) 24 | { 25 | x = n1; 26 | y = n2; 27 | } 28 | else if(form == POL) 29 | { 30 | x = n1 * cos(n2/Rad_to_deg); 31 | y = n1 * sin(n2/Rad_to_deg); 32 | } 33 | else 34 | { 35 | cout << "Incorrect 3rd argument to Vector() -- "; 36 | cout << "vector set to 0\n"; 37 | x = y = 0.0; 38 | mode = RECT; 39 | } 40 | } 41 | void Vector::reset(double n1, double n2, Mode form) 42 | { 43 | mode = form; 44 | if(form == RECT) 45 | { 46 | x = n1; 47 | y = n2; 48 | } 49 | else if(form == POL) 50 | { 51 | x = n1 * cos(n2/Rad_to_deg); 52 | y = n1 * sin(n2/Rad_to_deg); 53 | } 54 | else 55 | { 56 | cout << "Incorrect 3rd argument to Vector() -- "; 57 | cout << "vector set to 0\n"; 58 | x = y = 0.0; 59 | mode = RECT; 60 | } 61 | } 62 | Vector::~Vector() 63 | { 64 | } 65 | void Vector::polar_mode() 66 | { 67 | mode = POL; 68 | } 69 | void Vector::rect_mode() 70 | { 71 | mode = RECT; 72 | } 73 | Vector Vector::operator+(const Vector & b) const 74 | { 75 | return Vector(x + b.x, y + b.y); 76 | } 77 | Vector Vector::operator-(const Vector & b) const 78 | { 79 | return Vector(x - b.x, y - b.y); 80 | } 81 | Vector Vector::operator-() const 82 | { 83 | return Vector(-x, -y); 84 | } 85 | Vector Vector::operator*(double n) const 86 | { 87 | return Vector(n * x, n * y); 88 | } 89 | Vector operator*(double n, const Vector & a) 90 | { 91 | return a * n; 92 | } 93 | std::ostream & operator<<(std::ostream & os, const Vector & v) 94 | { 95 | if(v.mode == Vector::RECT) 96 | os << "(x, y) = (" << v.x << ", " << v.y << ")"; 97 | else if(v.mode == Vector::POL) 98 | os <<"(m, a) = (" << v.magval()<<", "<< v.angval()*Rad_to_deg <<")"; 99 | else 100 | os << "Vector object mode is invalid"; 101 | return os; 102 | } 103 | double Vector::magval() const 104 | { 105 | return sqrt(x*x+y*y); 106 | } 107 | double Vector::angval() const 108 | { 109 | return (x == 0.0 && y == 0.0) ? 0.0 : atan2(y, x); 110 | } 111 | } // namespace VECTOR 112 | -------------------------------------------------------------------------------- /chapter_11/sol_11_02/vect_11_02.h: -------------------------------------------------------------------------------- 1 | // vect_11_02.h --for sol-11-02.cpp 2 | 3 | #ifndef VECTOR_H_ 4 | #define VECTOR_H_ 5 | #include 6 | 7 | namespace VECTOR 8 | { 9 | class Vector 10 | { 11 | public: 12 | enum Mode {RECT, POL}; 13 | private: 14 | double x; 15 | double y; 16 | Mode mode; 17 | public: 18 | Vector(); 19 | Vector(double n1, double n2, Mode form = RECT); 20 | void reset(double n1, double n2, Mode form = RECT); 21 | ~Vector(); 22 | double xval() const {return x;} 23 | double yval() const {return y;} 24 | double magval() const; 25 | double angval() const; 26 | void polar_mode(); 27 | void rect_mode(); 28 | Vector operator+(const Vector & b) const; 29 | Vector operator-(const Vector & b) const; 30 | Vector operator-() const; 31 | Vector operator*(double n) const; 32 | friend Vector operator*(double n, const Vector & a); 33 | friend std::ostream & operator<<(std::ostream & os, const Vector & v); 34 | }; 35 | } // namespace VECTOR 36 | #endif // VECTOR_H_ 37 | -------------------------------------------------------------------------------- /chapter_11/sol_11_03/sol-11-03.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 11.3 ------------------------- 3 | 4 | #include "vect_11_03.h" 5 | #include 6 | #include 7 | #include 8 | 9 | int main(void) 10 | { 11 | using namespace std; 12 | using VECTOR::Vector; 13 | srand(time(0)); 14 | double direction, target, dstep; 15 | Vector step; 16 | Vector result(0.0, 0.0); 17 | unsigned long steps = 0; 18 | unsigned long min, max, total; 19 | int trials; 20 | cout << "Enter target distance (q to quit): "; 21 | while(cin >> target) 22 | { 23 | cout << "Enter step length: "; 24 | if(!(cin >> dstep)) 25 | break; 26 | cout << "Enter trials: "; 27 | if(!(cin >> trials)) 28 | break; 29 | total = 0; 30 | for(int i = 0; i < trials; i++) 31 | { 32 | while(result.magval() < target) 33 | { 34 | direction = rand() % 360; 35 | step.reset(dstep, direction, Vector::POL); 36 | result = result + step; 37 | steps++; 38 | } 39 | total += steps; 40 | if(i == 0) min = max = steps; 41 | if(min > steps) min = steps; 42 | if(max < steps) max = steps; 43 | steps = 0; 44 | result.reset(0.0, 0.0); 45 | } 46 | cout << "The highest, lowest, and average number of steps for " 47 | << trials << " trials:\n"; 48 | cout << " Highest: " << max << "\n Lowest : " << min 49 | << "\n Average: " << total/trials << endl; 50 | cout << "Enter target distance (q to quit): "; 51 | } 52 | cout << "Bye!\n"; 53 | cin.clear(); 54 | while(cin.get() != '\n') 55 | continue; 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /chapter_11/sol_11_03/vect_11_03.cpp: -------------------------------------------------------------------------------- 1 | // vect_11_03.cpp --for sol-11-03.cpp 2 | 3 | #include 4 | #include "vect_11_03.h" 5 | using std::sqrt; 6 | using std::sin; 7 | using std::cos; 8 | using std::atan; 9 | using std::atan2; 10 | using std::cout; 11 | namespace VECTOR 12 | { 13 | const double Rad_to_deg = 45.0/atan(1.0); 14 | void Vector::set_mag() 15 | { 16 | mag = sqrt(x*x+y*y); 17 | } 18 | void Vector::set_ang() 19 | { 20 | if(x == 0.0 && y == 0.0) 21 | ang = 0.0; 22 | else 23 | ang = atan2(y, x); 24 | } 25 | void Vector::set_x() 26 | { 27 | x = mag*cos(ang); 28 | } 29 | void Vector::set_y() 30 | { 31 | y = mag * sin(ang); 32 | } 33 | Vector::Vector() 34 | { 35 | x = y = mag = ang = 0.0; 36 | mode = RECT; 37 | } 38 | Vector::Vector(double n1, double n2, Mode form) 39 | { 40 | mode = form; 41 | if(form == RECT) 42 | { 43 | x = n1; 44 | y = n2; 45 | set_mag(); 46 | set_ang(); 47 | } 48 | else if(form == POL) 49 | { 50 | mag = n1; 51 | ang = n2/Rad_to_deg; 52 | set_x(); 53 | set_y(); 54 | } 55 | else 56 | { 57 | cout << "Incorrect 3rd argument to Vector() -- "; 58 | cout << "vector set to 0\n"; 59 | x = y = mag = ang = 0.0; 60 | mode = RECT; 61 | } 62 | } 63 | void Vector::reset(double n1, double n2, Mode form) 64 | { 65 | mode = form; 66 | if(form == RECT) 67 | { 68 | x = n1; 69 | y = n2; 70 | set_mag(); 71 | set_ang(); 72 | } 73 | else if(form == POL) 74 | { 75 | mag = n1; 76 | ang = n2/Rad_to_deg; 77 | set_x(); 78 | set_y(); 79 | } 80 | else 81 | { 82 | cout << "Incorrect 3rd argument to Vector() -- "; 83 | cout << "vector set to 0\n"; 84 | x = y = mag = ang = 0.0; 85 | mode = RECT; 86 | } 87 | } 88 | Vector::~Vector() 89 | { 90 | } 91 | void Vector::polar_mode() 92 | { 93 | mode = POL; 94 | } 95 | void Vector::rect_mode() 96 | { 97 | mode = RECT; 98 | } 99 | Vector Vector::operator+(const Vector & b) const 100 | { 101 | return Vector(x + b.x, y + b.y); 102 | } 103 | Vector Vector::operator-(const Vector & b) const 104 | { 105 | return Vector(x - b.x, y - b.y); 106 | } 107 | Vector Vector::operator-() const 108 | { 109 | return Vector(-x, -y); 110 | } 111 | Vector Vector::operator*(double n) const 112 | { 113 | return Vector(n * x, n * y); 114 | } 115 | Vector operator*(double n, const Vector & a) 116 | { 117 | return a * n; 118 | } 119 | std::ostream & operator<<(std::ostream & os, const Vector & v) 120 | { 121 | if(v.mode == Vector::RECT) 122 | os << "(x, y) = (" << v.x << ", " << v.y << ")"; 123 | else if(v.mode == Vector::POL) 124 | os << "(m, a) = (" << v.mag << ", " << v.ang * Rad_to_deg << ")"; 125 | else 126 | os << "Vector object mode is invalid"; 127 | return os; 128 | } 129 | } // namespace VECTOR 130 | -------------------------------------------------------------------------------- /chapter_11/sol_11_03/vect_11_03.h: -------------------------------------------------------------------------------- 1 | // vect_11_03.h --for sol-11-03.cpp 2 | 3 | #ifndef VECTOR_H_ 4 | #define VECTOR_H_ 5 | #include 6 | 7 | namespace VECTOR 8 | { 9 | class Vector 10 | { 11 | public: 12 | enum Mode {RECT, POL}; 13 | private: 14 | double x; 15 | double y; 16 | double mag; 17 | double ang; 18 | Mode mode; 19 | 20 | void set_mag(); 21 | void set_ang(); 22 | void set_x(); 23 | void set_y(); 24 | public: 25 | Vector(); 26 | Vector(double n1, double n2, Mode form = RECT); 27 | void reset(double n1, double n2, Mode form = RECT); 28 | ~Vector(); 29 | double xval() const {return x;} 30 | double yval() const {return y;} 31 | double magval() const {return mag;} 32 | double angval() const {return ang;} 33 | void polar_mode(); 34 | void rect_mode(); 35 | Vector operator+(const Vector & b) const; 36 | Vector operator-(const Vector & b) const; 37 | Vector operator-() const; 38 | Vector operator*(double n) const; 39 | friend Vector operator*(double n, const Vector & a); 40 | friend std::ostream & operator<<(std::ostream & os, const Vector & v); 41 | }; 42 | } // namespace VECTOR 43 | #endif // VECTOR_H_ 44 | -------------------------------------------------------------------------------- /chapter_11/sol_11_04/mytime_11_04.cpp: -------------------------------------------------------------------------------- 1 | // mytime_11_04.cpp --for sol-11-04.cpp 2 | 3 | #include "mytime_11_04.h" 4 | 5 | Time::Time() 6 | { 7 | hours = minutes = 0; 8 | } 9 | Time::Time(int h, int m) 10 | { 11 | hours = h; 12 | minutes = m; 13 | } 14 | void Time::AddMin(int m) 15 | { 16 | minutes += m; 17 | hours += minutes/60; 18 | minutes %= 60; 19 | } 20 | void Time::AddHr(int h) 21 | { 22 | hours += h; 23 | } 24 | void Time::Reset(int h, int m) 25 | { 26 | hours = h; 27 | minutes = m; 28 | } 29 | Time operator+(const Time & t1, const Time & t2) 30 | { 31 | Time sum; 32 | sum.minutes = t1.minutes + t2.minutes; 33 | sum.hours = t1.hours + t2.hours + sum.minutes/60; 34 | sum.minutes %= 60; 35 | return sum; 36 | } 37 | Time operator-(const Time & t1, const Time & t2) 38 | { 39 | Time diff; 40 | int tot1, tot2; 41 | tot1 = t2.minutes + 60 * t2.hours; 42 | tot2 = t1.minutes + 60 * t1.hours; 43 | diff.minutes = (tot2 - tot1) % 60; 44 | diff.hours = (tot2 - tot1) / 60; 45 | return diff; 46 | } 47 | Time operator*(const Time & t, double mult) 48 | { 49 | Time result; 50 | long totalminutes = t.hours * mult * 60 + t.minutes * mult; 51 | result.hours = totalminutes / 60; 52 | result.minutes = totalminutes % 60; 53 | return result; 54 | } 55 | std::ostream & operator<<(std::ostream & os, const Time & t) 56 | { 57 | os << t.hours << " hours, " << t.minutes << " minutes"; 58 | return os; 59 | } 60 | -------------------------------------------------------------------------------- /chapter_11/sol_11_04/mytime_11_04.h: -------------------------------------------------------------------------------- 1 | // mytime_11_04.h --for sol-11-04.cpp 2 | 3 | #ifndef MYTIME_H_ 4 | #define MYTIME_H_ 5 | #include 6 | 7 | class Time 8 | { 9 | private: 10 | int hours; 11 | int minutes; 12 | public: 13 | Time(); 14 | Time(int h, int m = 0); 15 | void AddMin(int m); 16 | void AddHr(int h); 17 | void Reset(int h = 0, int m = 0); 18 | friend Time operator+(const Time & t1, const Time & t2); 19 | friend Time operator-(const Time & t1, const Time & t2); 20 | friend Time operator*(const Time & t, double n); 21 | friend Time operator*(double m, const Time & t){ return t*m; } 22 | friend std::ostream & operator<<(std::ostream & os, const Time & t); 23 | }; 24 | #endif // MYTIME_H_ 25 | -------------------------------------------------------------------------------- /chapter_11/sol_11_04/sol-11-04.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 11.4 ------------------------- 3 | 4 | #include "mytime_11_04.h" 5 | #include 6 | 7 | int main(void) 8 | { 9 | using std::cout; 10 | using std::endl; 11 | Time aida(3, 35); 12 | Time tosca(2, 48); 13 | Time temp; 14 | Time temp2; 15 | cout << "Aida and Tosca:\n"; 16 | cout << aida << "; " << tosca << endl; 17 | temp = aida + tosca; 18 | cout << "Aida + Tosca: " << temp << endl; 19 | temp2 = aida - tosca; 20 | cout << "Aida - Tosca: " << temp2 << endl; 21 | temp = aida * 1.17; 22 | cout << "Aida * 1.17: " << temp << endl; 23 | cout << "10.0 * Tosca: " << 10.0 * tosca << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /chapter_11/sol_11_05/sol-11-05.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 11.5 ------------------------- 3 | 4 | #include "stonewt_11_05.h" 5 | #include 6 | 7 | using std::cout; 8 | void display(const Stonewt & st, int n); 9 | int main(void) 10 | { 11 | Stonewt incognito = 275; 12 | Stonewt wolfe(285.7); 13 | Stonewt taft(21, 8); 14 | cout << "The celebrity weighed " << incognito; 15 | cout << "The detective weighed " << wolfe; 16 | cout << "The President weighed " << taft; 17 | incognito = 276.8; 18 | taft = 325; 19 | cout << "After dinner, the celebrity weighed " << taft; 20 | cout << "Celebrity + Detective: " << incognito + wolfe; 21 | cout << "President - Detective: " << taft - wolfe; 22 | cout << "Detective * 5: " << wolfe * 5; 23 | cout << "3 * Celebrity: " << 3 * incognito; 24 | incognito.setStnMode(); 25 | cout << "Celebrity Stone mode: " << incognito; 26 | incognito.setIntMode(); 27 | cout << "Celebrity Int mode: " << incognito; 28 | incognito.setFloatMode(); 29 | cout << "Celebrity Float mode: " << incognito; 30 | display(taft, 2); 31 | cout << "The wrestler weighed even more.\n"; 32 | display(422, 2); 33 | cout << "No stone left unearned\n"; 34 | return 0; 35 | } 36 | void display(const Stonewt & st, int n) 37 | { 38 | for(int i = 0; i < n; i++) 39 | cout << "Wow! " << st; 40 | } 41 | -------------------------------------------------------------------------------- /chapter_11/sol_11_05/stonewt_11_05.cpp: -------------------------------------------------------------------------------- 1 | // stonewt_11_05.cpp --for sol-11-05.cpp 2 | 3 | #include "stonewt_11_05.h" 4 | #include 5 | using std::cout; 6 | 7 | Stonewt::Stonewt(double lbs) 8 | { 9 | mode = STN; 10 | stone = int(lbs)/Lbs_per_stn; 11 | pds_left = int(lbs)% Lbs_per_stn + lbs - int(lbs); 12 | pounds = lbs; 13 | } 14 | Stonewt::Stonewt(int stn, double lbs, Mode form) 15 | { 16 | mode = form; 17 | if(mode == STN || mode == ILBS || mode == FLBS) 18 | { 19 | stone = stn; 20 | pds_left = lbs; 21 | pounds = stn * Lbs_per_stn + lbs; 22 | } 23 | else 24 | { 25 | cout << "Incorrect 3rd argument to Stonewt() --- "; 26 | cout << "weight set to 0\n"; 27 | stone = pds_left = pounds = 0; 28 | mode = STN; 29 | } 30 | } 31 | Stonewt::Stonewt() 32 | { 33 | mode = STN; 34 | stone = pounds = pds_left = 0; 35 | } 36 | Stonewt Stonewt::operator+(const Stonewt & s) const 37 | { 38 | return Stonewt(pounds + s.pounds); 39 | } 40 | Stonewt Stonewt::operator-(const Stonewt & s) const 41 | { 42 | return Stonewt(pounds - s.pounds); 43 | } 44 | Stonewt Stonewt::operator*(double n) const 45 | { 46 | return Stonewt(pounds * n); 47 | } 48 | Stonewt operator*(double n, Stonewt & s) 49 | { 50 | return Stonewt(s.pounds * n); 51 | } 52 | std::ostream & operator<<(std::ostream & os, const Stonewt & s) 53 | { 54 | if(s.mode == Stonewt::STN) 55 | os << s.stone << " stone, " << s.pds_left << " pounds\n"; 56 | else if(s.mode == Stonewt::ILBS) 57 | os << (int)s.pounds << " pounds\n"; 58 | else if(s.mode == Stonewt::FLBS) 59 | os << s.pounds << " pounds\n"; 60 | return os; 61 | } 62 | -------------------------------------------------------------------------------- /chapter_11/sol_11_05/stonewt_11_05.h: -------------------------------------------------------------------------------- 1 | // stonewt_11_05.h --for sol-11-05.cpp 2 | 3 | #ifndef STONEWT_H_ 4 | #define STONEWT_H_ 5 | #include 6 | 7 | class Stonewt 8 | { 9 | public: 10 | enum Mode {STN = 1, ILBS = 2, FLBS = 3}; 11 | private: 12 | enum {Lbs_per_stn = 14}; 13 | int stone; 14 | double pds_left; 15 | double pounds; 16 | Mode mode; 17 | public: 18 | Stonewt(double lbs); 19 | Stonewt(int stn, double lbs, Mode form = STN); 20 | Stonewt(); 21 | ~Stonewt(){}; 22 | void setStnMode(){ mode = STN; } 23 | void setIntMode(){ mode = ILBS; } 24 | void setFloatMode(){ mode = FLBS; } 25 | Stonewt operator+(const Stonewt & s) const; 26 | Stonewt operator-(const Stonewt & s) const; 27 | Stonewt operator*(double n) const; 28 | friend Stonewt operator*(double n, Stonewt & s); 29 | friend std::ostream & operator<<(std::ostream & os, const Stonewt & s); 30 | }; 31 | #endif // STONEWT_H_ 32 | -------------------------------------------------------------------------------- /chapter_11/sol_11_06/sol-11-06.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 11.6 ------------------------- 3 | 4 | #include "stonewt_11_06.h" 5 | #include 6 | 7 | int main(void) 8 | { 9 | const int SIZE = 6; 10 | Stonewt arr[SIZE] = {141, 275, 7}; 11 | Stonewt s11(11); 12 | int min, max, count; 13 | double pounds; 14 | for(int i = 3; i < SIZE; i++) 15 | { 16 | std::cout << "Enter pound: "; 17 | std::cin >> pounds; 18 | arr[i] = pounds; 19 | } 20 | min = max = count = 0; 21 | for(int i = 0; i < SIZE; i++) 22 | { 23 | if(arr[min] > arr[i]) min = i; 24 | if(arr[max] < arr[i]) max = i; 25 | if(arr[i] >= s11) count++; 26 | } 27 | std::cout << "The objects >= 11 pounds: " << count << "\n"; 28 | std::cout << "Max object: "; 29 | arr[max].show_lbs(); 30 | std::cout << "Min object: "; 31 | arr[min].show_lbs(); 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /chapter_11/sol_11_06/stonewt_11_06.cpp: -------------------------------------------------------------------------------- 1 | // stonewt_11_06.cpp --for sol-11-06.cpp 2 | 3 | #include "stonewt_11_06.h" 4 | #include 5 | using std::cout; 6 | 7 | Stonewt::Stonewt(double lbs) 8 | { 9 | stone = int(lbs)/Lbs_per_stn; 10 | pds_left = int(lbs)% Lbs_per_stn + lbs - int(lbs); 11 | pounds = lbs; 12 | } 13 | Stonewt::Stonewt(int stn, double lbs) 14 | { 15 | stone = stn; 16 | pds_left = lbs; 17 | pounds = stn * Lbs_per_stn + lbs; 18 | } 19 | Stonewt::Stonewt() 20 | { 21 | stone = pounds = pds_left = 0; 22 | } 23 | void Stonewt::show_lbs() const 24 | { 25 | cout << pounds << " pounds\n"; 26 | } 27 | void Stonewt::show_stn() const 28 | { 29 | cout << stone << " stones, " << pds_left << " pounds\n"; 30 | } 31 | bool operator>(const Stonewt & s1, const Stonewt & s2) 32 | { 33 | return s1.pounds > s2.pounds; 34 | } 35 | bool operator<(const Stonewt & s1, const Stonewt & s2) 36 | { 37 | return s1.pounds < s2.pounds; 38 | } 39 | bool operator>=(const Stonewt & s1, const Stonewt & s2) 40 | { 41 | return s1.pounds >= s2.pounds; 42 | } 43 | bool operator<=(const Stonewt & s1, const Stonewt & s2) 44 | { 45 | return s1.pounds <= s2.pounds; 46 | } 47 | bool operator==(const Stonewt & s1, const Stonewt & s2) 48 | { 49 | return s1.pounds == s2.pounds; 50 | } 51 | bool operator!=(const Stonewt & s1, const Stonewt & s2) 52 | { 53 | return s1.pounds != s2.pounds; 54 | } 55 | -------------------------------------------------------------------------------- /chapter_11/sol_11_06/stonewt_11_06.h: -------------------------------------------------------------------------------- 1 | // stonewt_11_06.h --for sol-11-06.cpp 2 | 3 | #ifndef STONEWT_H_ 4 | #define STONEWT_H_ 5 | #include 6 | 7 | class Stonewt 8 | { 9 | private: 10 | enum {Lbs_per_stn = 14}; 11 | int stone; 12 | double pds_left; 13 | double pounds; 14 | public: 15 | Stonewt(double lbs); 16 | Stonewt(int stn, double lbs); 17 | Stonewt(); 18 | ~Stonewt(){}; 19 | void show_lbs() const; 20 | void show_stn() const; 21 | friend bool operator>(const Stonewt & s1, const Stonewt & s2); 22 | friend bool operator<(const Stonewt & s1, const Stonewt & s2); 23 | friend bool operator>=(const Stonewt & s1, const Stonewt & s2); 24 | friend bool operator<=(const Stonewt & s1, const Stonewt & s2); 25 | friend bool operator==(const Stonewt & s1, const Stonewt & s2); 26 | friend bool operator!=(const Stonewt & s1, const Stonewt & s2); 27 | }; 28 | #endif // STONEWT_H_ 29 | -------------------------------------------------------------------------------- /chapter_11/sol_11_07/complex_11_07.cpp: -------------------------------------------------------------------------------- 1 | // complex_11_07.cpp --for sol-11-07.cpp 2 | 3 | #include "complex_11_07.h" 4 | #include 5 | 6 | Complex::Complex() 7 | { 8 | cA = cB = 0; 9 | } 10 | Complex::Complex(double r, double i) 11 | { 12 | cA = r; 13 | cB = i; 14 | } 15 | Complex Complex::operator+(const Complex & c) const 16 | { 17 | return Complex(cA+c.cA, cB+c.cB); 18 | } 19 | Complex Complex::operator-(const Complex & c) const 20 | { 21 | return Complex(cA-c.cA, cB-c.cB); 22 | } 23 | Complex Complex::operator*(const Complex & c) const 24 | { 25 | return Complex((cA*c.cA-cB*c.cB), (cA*c.cB+cB*c.cA)); 26 | } 27 | Complex Complex::operator~() const 28 | { 29 | return Complex(cA, -cB); 30 | } 31 | Complex Complex::operator*(double n) const 32 | { 33 | return Complex(cA*n, cB*n); 34 | } 35 | Complex operator*(double n, const Complex & c) 36 | { 37 | return c * n; 38 | } 39 | std::ostream & operator<<(std::ostream & os, const Complex & c) 40 | { 41 | os << "(" << c.cA << ", " << c.cB << "i)"; 42 | return os; 43 | } 44 | std::istream & operator>>(std::istream & is, Complex & c) 45 | { 46 | std::cout << "real: "; 47 | if(is >> c.cA) 48 | { 49 | std::cout << "imaginary: "; 50 | is >> c.cB; 51 | } 52 | return is; 53 | } 54 | -------------------------------------------------------------------------------- /chapter_11/sol_11_07/complex_11_07.h: -------------------------------------------------------------------------------- 1 | // complex_11_07.h --for sol-11-07.cpp 2 | 3 | #ifndef COMPLEX_H_ 4 | #define COMPLEX_H_ 5 | #include 6 | 7 | class Complex 8 | { 9 | private: 10 | double cA; 11 | double cB; 12 | public: 13 | Complex(); 14 | Complex(double a, double b); 15 | ~Complex(){} 16 | Complex operator+(const Complex & c) const; 17 | Complex operator-(const Complex & c) const; 18 | Complex operator~() const; 19 | Complex operator*(double n) const; 20 | Complex operator*(const Complex & c) const; 21 | friend Complex operator*(double n, const Complex & c); 22 | friend std::ostream & operator<<(std::ostream & os, const Complex & s); 23 | friend std::istream & operator>>(std::istream & is, Complex & c); 24 | }; 25 | #endif // COMPLEX_H_ 26 | -------------------------------------------------------------------------------- /chapter_11/sol_11_07/sol-11-07.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 11.7 ------------------------- 3 | 4 | #include "complex_11_07.h" 5 | #include 6 | using namespace std; 7 | int main(void) 8 | { 9 | Complex a(3.0, 4.0); 10 | Complex c; 11 | cout << "Enter a complex number (q to quit):\n"; 12 | while(cin >> c) 13 | { 14 | cout << "c is " << c << '\n'; 15 | cout << "complex cojugate is " << ~c << '\n'; 16 | cout << "a is " << a << '\n'; 17 | cout << "a + c is " << a + c << '\n'; 18 | cout << "a - c is " << a - c << '\n'; 19 | cout << "a * c is " << a * c << '\n'; 20 | cout << "2 * c is " << 2 * c << '\n'; 21 | cout << "Enter a complex number (q to quit):\n"; 22 | } 23 | cout << "Done!\n"; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /chapter_12/ProgrammingExercisesChapter_12.txt: -------------------------------------------------------------------------------- 1 | S.Prata C++ Primer Plus 6th ed. 2 | ================================================================================ 3 | PROGRAMMING EXERCISES CHAPTER 12 4 | 5 | 6 | 1. Consider the following class declaration: 7 | 8 | class Cow { 9 | char name[20]; 10 | char * hobby; 11 | double weight; 12 | public: 13 | Cow(); 14 | Cow(const char * nm, const char * ho, double wt); 15 | Cow(const Cow c&); 16 | ~Cow(); 17 | Cow & operator=(const Cow & c); 18 | void ShowCow() const; // display all cow data 19 | }; 20 | 21 | Provide the implementation for this class and write a short program that 22 | uses all the member functions. 23 | 24 | 2. Enhance the String class declaration (that is, upgrade string1.h to 25 | string2.h) by doing the following: 26 | 27 | a. Overload the + operator to allow you to join two strings into one. 28 | b. Provide a stringlow() member function that converts all alphabetic 29 | characters in a string to lowercase. (Don’t forget the cctype family of 30 | character functions.) 31 | c. Provide a stringup() member function that converts all alphabetic 32 | characters in a string to uppercase. 33 | d. Provide a member function that takes a char argument and returns the 34 | number of times the character appears in the string. 35 | 36 | Test your work in the following program: 37 | 38 | // pe12_2.cpp 39 | #include 40 | using namespace std; 41 | #include "string2.h" 42 | int main() 43 | { 44 | String s1(" and I am a C++ student."); 45 | String s2 = "Please enter your name: "; 46 | String s3; 47 | cout << s2; // overloaded << operator 48 | cin >> s3; // overloaded >> operator 49 | s2 = "My name is " + s3; // overloaded =, + operators 50 | cout << s2 << ".\n"; 51 | s2 = s2 + s1; 52 | s2.stringup(); // converts string to uppercase 53 | cout << "The string\n" << s2 << "\ncontains " << s2.has('A') 54 | << " 'A' characters in it.\n"; 55 | s1 = "red"; // String(const char *), 56 | // then String & operator=(const String&) 57 | String rgb[3] = { String(s1), String("green"), String("blue") }; 58 | cout << "Enter the name of a primary color for mixing light: "; 59 | String ans; 60 | bool success = false; 61 | while (cin >> ans) 62 | { 63 | ans.stringlow(); // converts string to lowercase 64 | for (int i = 0; i < 3; i++) 65 | { 66 | if (ans == rgb[i]) // overloaded == operator 67 | { 68 | cout << "That's right!\n"; 69 | success = true; 70 | break; 71 | } 72 | } 73 | if (success) 74 | break; 75 | else 76 | cout << "Try again!\n"; 77 | } 78 | cout << "Bye\n"; 79 | return 0; 80 | } 81 | 82 | Your output should look like this sample run: 83 | 84 | Please enter your name: Fretta Farbo 85 | My name is Fretta Farbo. 86 | The string 87 | MY NAME IS FRETTA FARBO AND I AM A C++ STUDENT. 88 | contains 6 'A' characters in it. 89 | Enter the name of a primary color for mixing light: yellow 90 | Try again! 91 | BLUE 92 | That's right! 93 | Bye 94 | 95 | 3. Rewrite the Stock class,as described in Listings 10.7 and 10.8 in Chapter 10 96 | so that it uses dynamically allocated memory directly instead of using 97 | string class objects to hold the stock names. Also replace the show() member 98 | function with an overloaded operator<<() definition. Test the new definition 99 | program in Listing 10.9. 100 | 101 | 4. Consider the following variation of the Stack class defined in 102 | Listing 10.10: 103 | 104 | // stack.h -- class declaration for the stack ADT 105 | typedef unsigned long Item; 106 | class Stack 107 | { 108 | private: 109 | enum {MAX = 10}; // constant specific to class 110 | Item * pitems; // holds stack items 111 | int size; // number of elements in stack 112 | int top; // index for top stack item 113 | public: 114 | Stack(int n = MAX); // creates stack with n elements 115 | Stack(const Stack & st); 116 | ~Stack(); 117 | bool isempty() const; 118 | bool isfull() const; 119 | // push() returns false if stack already is full, true otherwise 120 | bool push(const Item & item); // add item to stack 121 | // pop() returns false if stack already is empty, true otherwise 122 | bool pop(Item & item); // pop top into item 123 | Stack & operator=(const Stack & st); 124 | }; 125 | 126 | As the private members suggest,this class uses a dynamically allocated array 127 | to hold the stack items. Rewrite the methods to fit this new representation 128 | and write a program that demonstrates all the methods, including the copy 129 | constructor and assignment operator. 130 | 131 | 5. The Bank of Heather has performed a study showing that ATM customers won't 132 | wait more than one minute in line. Using the simulation from Listing 12.10, 133 | find a value for number of customers per hour that leads to an average wait 134 | time of one minute.(Use at least a 100-hour trial period.) 135 | 136 | 6. The Bank of Heather would like to know what would happen if it added a 137 | second ATM. Modify the simulation in this chapter so that it has two queues. 138 | Assume that a customer will join the first queue if it has fewer people in 139 | it than the second queue and that the customer will join the second queue 140 | otherwise. Again, find a value for number of customers per hour that leads 141 | to an average wait time of one minute. (Note: This is a nonlinear problem in 142 | that doubling the number of ATMs doesn’t double the number of customers who 143 | can be handled per hour with a one-minute wait maximum.) 144 | 145 | ================================================================================ 146 | -------------------------------------------------------------------------------- /chapter_12/sol_12_01/cow_12_01.cpp: -------------------------------------------------------------------------------- 1 | // cow_12_01.cpp --for sol-12-01.cpp 2 | 3 | #include "cow_12_01.h" 4 | #include 5 | #include 6 | 7 | Cow::Cow() 8 | { 9 | hobby = new char[1]; 10 | hobby[0] = '\0'; 11 | name[0] = '\0'; 12 | weight = 0; 13 | } 14 | Cow::Cow(const char * nm, const char * ho, double wt) 15 | { 16 | hobby = new char[std::strlen(ho) + 1]; 17 | std::strcpy(hobby, ho); 18 | std::strcpy(name, nm); 19 | weight = wt; 20 | } 21 | Cow::Cow(const Cow & c) 22 | { 23 | hobby = new char[std::strlen(c.hobby) + 1]; 24 | std::strcpy(hobby, c.hobby); 25 | std::strcpy(name, c.name); 26 | weight = c.weight; 27 | } 28 | Cow::~Cow() 29 | { 30 | delete [] hobby; 31 | } 32 | Cow & Cow::operator=(const Cow & c) 33 | { 34 | if(this == &c) 35 | return *this; 36 | delete [] hobby; 37 | hobby = new char[std::strlen(c.hobby) + 1]; 38 | std::strcpy(hobby, c.hobby); 39 | std::strcpy(name, c.name); 40 | weight = c.weight; 41 | return *this; 42 | } 43 | void Cow::ShowCow() const 44 | { 45 | std::cout << " Name: " << name << "\n Hobby: " << hobby 46 | << "\n Weight: " << weight << '\n'; 47 | } 48 | -------------------------------------------------------------------------------- /chapter_12/sol_12_01/cow_12_01.h: -------------------------------------------------------------------------------- 1 | // cow_12_01.h --for sol-12-01.cpp 2 | 3 | #ifndef COW_H_ 4 | #define COW_H_ 5 | 6 | class Cow 7 | { 8 | private: 9 | char name[20]; 10 | char * hobby; 11 | double weight; 12 | public: 13 | Cow(); 14 | Cow(const char * nm, const char * ho, double wt); 15 | Cow(const Cow &); 16 | ~Cow(); 17 | Cow & operator=(const Cow & c); 18 | void ShowCow() const; 19 | }; 20 | #endif // COW_H_ 21 | -------------------------------------------------------------------------------- /chapter_12/sol_12_01/sol-12-01.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 12.1 ------------------------- 3 | 4 | #include "cow_12_01.h" 5 | #include 6 | 7 | int main(void) 8 | { 9 | Cow test1; 10 | Cow test2("Ann", "Tennis", 117); 11 | Cow * test = new Cow("Peter", "Hockey", 127); 12 | std::cout << "test: \n"; 13 | test->ShowCow(); 14 | std::cout << "test1: \n"; 15 | test1.ShowCow(); 16 | std::cout << "test2: \n"; 17 | test2.ShowCow(); 18 | Cow test3(test2); 19 | std::cout << "test3: \n"; 20 | test3.ShowCow(); 21 | Cow test4 = test3; 22 | std::cout << "test4: \n"; 23 | test4.ShowCow(); 24 | delete test; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /chapter_12/sol_12_02/sol-12-02.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 12.2 ------------------------- 3 | 4 | #include "string_12_02.h" 5 | #include 6 | using namespace std; 7 | 8 | int main(void) 9 | { 10 | String s1(" and I am a C++ student."); 11 | String s2 = "Please enter your name: "; 12 | String s3; 13 | cout << s2; 14 | cin >> s3; 15 | s2 = "My name is " + s3; 16 | cout << s2 << ".\n"; 17 | s2 = s2 + s1; 18 | s2.stringup(); 19 | cout << "The string\n" << s2 << "\ncontains " << s2.has('A') 20 | << " 'A' characters in it.\n"; 21 | s1 = "red"; 22 | String rgb[3] = {String(s1), String("green"), String("blue")}; 23 | cout << "Enter the name of a primary coler for mixing light: "; 24 | String ans; 25 | bool success = false; 26 | while(cin >> ans) 27 | { 28 | ans.stringlow(); 29 | for(int i = 0; i < 3; i++) 30 | { 31 | if(ans == rgb[i]) 32 | { 33 | cout << "That's right!\n"; 34 | success = true; 35 | break; 36 | } 37 | } 38 | if(success) 39 | break; 40 | else 41 | cout << "Try again!\n"; 42 | } 43 | cout << "Bye\n"; 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /chapter_12/sol_12_02/string_12_02.cpp: -------------------------------------------------------------------------------- 1 | // string_12_02.cpp --for sol-12-02.cpp 2 | 3 | #include "string_12_02.h" 4 | #include 5 | using std::cin; 6 | using std::cout; 7 | 8 | int String::num_strings = 0; 9 | int String::HowMany() 10 | { 11 | return num_strings; 12 | } 13 | String::String(const char *s) 14 | { 15 | len = std::strlen(s); 16 | str = new char[len + 1]; 17 | std::strcpy(str, s); 18 | num_strings++; 19 | } 20 | String::String() 21 | { 22 | len = 4; 23 | str = new char[1]; 24 | str[0] ='\0'; 25 | num_strings++; 26 | } 27 | String::String(const String & st) 28 | { 29 | num_strings++; 30 | len = st.len; 31 | str = new char[len + 1]; 32 | std::strcpy(str, st.str); 33 | } 34 | String::~String() 35 | { 36 | --num_strings; 37 | delete [] str; 38 | } 39 | int String::has(const char s) 40 | { 41 | int cnt = 0; 42 | for(int i = 0; i < len; i++) 43 | if(str[i] == 'A') 44 | cnt++; 45 | return cnt; 46 | } 47 | void String::stringlow() 48 | { 49 | for(int i = 0; i < len; i++) 50 | str[i] = tolower(str[i]); 51 | } 52 | void String::stringup() 53 | { 54 | for(int i = 0; i < len; i++) 55 | str[i] = toupper(str[i]); 56 | } 57 | String operator+(const String &st1, const String &st2) 58 | { 59 | char tmp[st1.len + st2.len + 1]; 60 | std::strcat(std::strcpy(tmp, st1.str), st2.str); 61 | return String(tmp); 62 | } 63 | String operator+(const char *s, const String &st) 64 | { 65 | return String(s) + st; 66 | } 67 | String operator+(const String &st, const char *s) 68 | { 69 | return st + String(s); 70 | } 71 | String & String::operator=(const String & st) 72 | { 73 | if(this == &st) 74 | return *this; 75 | delete [] str; 76 | len = st.len; 77 | str = new char[len + 1]; 78 | std::strcpy(str, st.str); 79 | return *this; 80 | } 81 | String & String::operator=(const char *s) 82 | { 83 | delete [] str; 84 | len = std::strlen(s); 85 | str = new char[len + 1]; 86 | std::strcpy(str, s); 87 | return *this; 88 | } 89 | char & String::operator[](int i) 90 | { 91 | return str[i]; 92 | } 93 | const char & String::operator[](int i) const 94 | { 95 | return str[i]; 96 | } 97 | bool operator<(const String &st1, const String &st2) 98 | { 99 | return (std::strcmp(st1.str, st2.str) < 0); 100 | } 101 | bool operator>(const String &st1, const String &st2) 102 | { 103 | return st2.str < st1.str; 104 | } 105 | bool operator==(const String &st1, const String &st2) 106 | { 107 | return (std::strcmp(st1.str, st2.str) == 0); 108 | } 109 | ostream & operator<<(ostream &os, const String &st) 110 | { 111 | os << st.str; 112 | return os; 113 | } 114 | istream & operator>>(istream &is, String &st) 115 | { 116 | char temp[String::CINLIM]; 117 | is.get(temp, String::CINLIM); 118 | if(is) 119 | st = temp; 120 | while(is && is.get() != '\n') 121 | continue; 122 | return is; 123 | } 124 | -------------------------------------------------------------------------------- /chapter_12/sol_12_02/string_12_02.h: -------------------------------------------------------------------------------- 1 | // string_12_02.h --for sol-12-02.cpp 2 | 3 | #ifndef STRING_H_ 4 | #define STRING_H_ 5 | #include 6 | using std::ostream; 7 | using std::istream; 8 | 9 | class String 10 | { 11 | private: 12 | char *str; 13 | int len; 14 | static int num_strings; 15 | static const int CINLIM = 80; 16 | public: 17 | String(const char *s); 18 | String(); 19 | String(const String &); 20 | ~String(); 21 | int length() const {return len;} 22 | int has(const char); 23 | void stringlow(); 24 | void stringup(); 25 | String & operator=(const String &); 26 | String & operator=(const char *); 27 | char & operator[](int i); 28 | const char & operator[](int i) const; 29 | friend bool operator<(const String &st1, const String &st2); 30 | friend bool operator>(const String &st1, const String &st2); 31 | friend bool operator==(const String &st1, 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 String &st1, const String &st2); 35 | friend String operator+(const char *, const String &); 36 | friend String operator+(const String &, const char *); 37 | static int HowMany(); 38 | }; 39 | #endif // STRING_H_ 40 | -------------------------------------------------------------------------------- /chapter_12/sol_12_03/sol-12-03.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 12.3 ------------------------- 3 | 4 | #include "stock_12_03.h" 5 | #include 6 | const int STKS = 4; 7 | 8 | int main(void) 9 | { 10 | Stock stocks[STKS] = { 11 | Stock("NanoSmart", 12, 20.0), 12 | Stock("Boffo Object", 200, 2.0), 13 | Stock("Monolithic Obelisks", 130, 3.25), 14 | Stock("Fleep Enterprises", 60, 6.5) 15 | }; 16 | std::cout << "Stock holdings:\n"; 17 | int st; 18 | for(st = 0; st < STKS; st++) 19 | std::cout << stocks[st]; 20 | const Stock *top = &stocks[0]; 21 | for(st = 1; st < STKS; st++) 22 | top = &top->topval(stocks[st]); 23 | std::cout << "\nMost valuable holding:\n" << *top; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /chapter_12/sol_12_03/stock_12_03.cpp: -------------------------------------------------------------------------------- 1 | // stock_12_03.cpp --for sol-12-03.cpp 2 | 3 | #include "stock_12_03.h" 4 | #include 5 | #include 6 | 7 | Stock::Stock() 8 | { 9 | company = new char[8]; 10 | company = std::strcpy(company, "no name"); 11 | shares = 0; 12 | share_val = 0.0; 13 | total_val = 0.0; 14 | } 15 | Stock::Stock(const char *co, long n, double pr) 16 | { 17 | int len = std::strlen(co); 18 | company = new char[len + 1]; 19 | company = std::strcpy(company, co); 20 | if(n < 0) 21 | { 22 | std::cout << "Number of shares con't be negative; " 23 | << company << " shares set to 0.\n"; 24 | shares = 0; 25 | } 26 | else 27 | shares = n; 28 | share_val = pr; 29 | set_tot(); 30 | } 31 | Stock::Stock(const Stock & st) 32 | { 33 | int len = std::strlen(st.company); 34 | company = new char[len + 1]; 35 | company = std::strcpy(company, st.company); 36 | shares = st.shares; 37 | share_val = st.share_val; 38 | total_val = st.total_val; 39 | } 40 | Stock::~Stock() 41 | { 42 | delete [] company; 43 | } 44 | void Stock::buy(long num, double price) 45 | { 46 | if(num < 0) 47 | { 48 | std::cout << "Number of shares purchased can't be negative. " 49 | << "Transaction is aborted.\n"; 50 | } 51 | else 52 | { 53 | shares += num; 54 | share_val = price; 55 | set_tot(); 56 | } 57 | } 58 | void Stock::sell(long num, double price) 59 | { 60 | using std::cout; 61 | if(num < 0) 62 | { 63 | std::cout << "Number of shares sold can't be negative. " 64 | << "Transaction is aborted.\n"; 65 | } 66 | else if(num > shares) 67 | { 68 | cout << "You can't sell more than you have! " 69 | << "Transaction is aborted.\n"; 70 | } 71 | else 72 | { 73 | shares -= num; 74 | share_val = price; 75 | set_tot(); 76 | } 77 | } 78 | void Stock::update(double price) 79 | { 80 | share_val = price; 81 | set_tot(); 82 | } 83 | std::ostream & operator<<(std::ostream & os, const Stock & st) 84 | { 85 | using std::ios_base; 86 | ios_base::fmtflags orig = os.setf(ios_base::fixed, ios_base::floatfield); 87 | std::streamsize prec = os.precision(3); 88 | os << "Company: " << st.company 89 | << " Shares: " << st.shares << '\n'; 90 | os << " Share Price: $" << st.share_val; 91 | os.precision(2); 92 | os << " Total Worth: $" << st.total_val << '\n'; 93 | os.setf(orig, ios_base::floatfield); 94 | os.precision(prec); 95 | } 96 | const Stock & Stock::topval(const Stock & s) const 97 | { 98 | if(s.total_val > total_val) 99 | return s; 100 | else 101 | return *this; 102 | } 103 | -------------------------------------------------------------------------------- /chapter_12/sol_12_03/stock_12_03.h: -------------------------------------------------------------------------------- 1 | // stock_12_03.h --for sol-12-03.cpp 2 | 3 | #ifndef STOCK_H_ 4 | #define STOCK_H_ 5 | #include 6 | 7 | class Stock 8 | { 9 | private: 10 | char *company; 11 | int shares; 12 | double share_val; 13 | double total_val; 14 | void set_tot(){total_val = shares * share_val;} 15 | public: 16 | Stock(); 17 | Stock(const char *co, long n = 0, double pr = 0.0); 18 | Stock(const Stock & st); 19 | ~Stock(); 20 | void buy(long num, double price); 21 | void sell(long num, double price); 22 | void update(double price); 23 | const Stock & topval(const Stock & s) const; 24 | friend std::ostream & operator<<(std::ostream &os, const Stock & st); 25 | }; 26 | #endif // STOCK_H_ 27 | -------------------------------------------------------------------------------- /chapter_12/sol_12_04/sol-12-04.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 12.4 ------------------------- 3 | 4 | #include "stack_12_04.h" 5 | #include 6 | 7 | int main(void) 8 | { 9 | Stack st1(5); 10 | int x = 1; 11 | while(!st1.isfull()) 12 | st1.push(x++); 13 | Stack st2 = st1; 14 | Stack st3(st2); 15 | Item val {}; 16 | std::cout << "stack st1:\n"; 17 | while(st1.pop(val)) 18 | std::cout << val << '\n'; 19 | std::cout << "stack st2:\n"; 20 | while(st2.pop(val)) 21 | std::cout << val << '\n'; 22 | std::cout << "stack st3:\n"; 23 | while(st3.pop(val)) 24 | std::cout << val << '\n'; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /chapter_12/sol_12_04/stack_12_04.cpp: -------------------------------------------------------------------------------- 1 | // stack_12_04.cpp --for sol-12-04.cpp 2 | 3 | #include "stack_12_04.h" 4 | 5 | Stack::Stack(int n) 6 | { 7 | if(n < 0 || n > MAX) 8 | n = 10; 9 | pitems = new Item[n]; 10 | size = n; 11 | top = 0; 12 | } 13 | Stack::Stack(const Stack & st) 14 | { 15 | size = st.size; 16 | pitems = new Item[size]; 17 | for(int i = 0; i < size; i++) 18 | pitems[i] = st.pitems[i]; 19 | top = st.top; 20 | } 21 | Stack::~Stack() 22 | { 23 | delete [] pitems; 24 | } 25 | bool Stack::isempty() const 26 | { 27 | return top == 0; 28 | } 29 | bool Stack::isfull() const 30 | { 31 | return top == size; 32 | } 33 | bool Stack::push(const Item & item) 34 | { 35 | if(top < size) 36 | { 37 | pitems[top++] = item; 38 | return true; 39 | } 40 | else 41 | return false; 42 | } 43 | bool Stack::pop(Item & item) 44 | { 45 | if(top > 0) 46 | { 47 | item = pitems[--top]; 48 | return true; 49 | } 50 | else 51 | return false; 52 | } 53 | Stack & Stack::operator=(const Stack & st) 54 | { 55 | if(this == &st) 56 | return *this; 57 | delete [] pitems; 58 | size = st.size; 59 | top = st.top; 60 | pitems = new Item[size]; 61 | for(int i = 0; i < size; i++) 62 | pitems[i] = st.pitems[i]; 63 | return *this; 64 | } 65 | -------------------------------------------------------------------------------- /chapter_12/sol_12_04/stack_12_04.h: -------------------------------------------------------------------------------- 1 | // stack_12_04.h --for sol-12-04.cpp 2 | 3 | #ifndef STACK_H_ 4 | #define STACK_H_ 5 | typedef unsigned long Item; 6 | 7 | class Stack 8 | { 9 | private: 10 | enum {MAX = 10}; 11 | Item *pitems; 12 | int size; 13 | int top; 14 | public: 15 | Stack(int n = 10); 16 | Stack(const Stack & st); 17 | ~Stack(); 18 | bool isempty() const; 19 | bool isfull() const; 20 | bool push(const Item & item); 21 | bool pop(Item & item); 22 | Stack & operator=(const Stack & st); 23 | }; 24 | #endif // STACK_H_ 25 | -------------------------------------------------------------------------------- /chapter_13/ProgrammingExercisesChapter_11.txt: -------------------------------------------------------------------------------- 1 | S.Prata C++ Primer Plus 6th ed. 2 | ================================================================================ 3 | PROGRAMMING EXERCISES CHAPTER 13 4 | 5 | 6 | 1. Start with the following class declaration: 7 | 8 | // base class 9 | class Cd { // represents a CD disk 10 | private: 11 | char performers[50]; 12 | char label[20]; 13 | int selections; // number of selections 14 | double playtime; // playing time in minutes 15 | public: 16 | Cd(char * s1, char * s2, int n, double x); 17 | Cd(const Cd & d); 18 | Cd(); 19 | ~Cd(); 20 | void Report() const; // reports all CD data 21 | Cd & operator=(const Cd & d); 22 | }; 23 | 24 | Derive a Classic class that adds an array of char members that will hold a 25 | string identifying the primary work on the CD. If the base class requires 26 | that any functions be virtual,modify the base-class declaration to make it 27 | so. If a declared method is not needed,remove it from the definition. Test 28 | your product with the following program: 29 | 30 | #include 31 | using namespace std; 32 | #include "classic.h" // which will contain #include cd.h 33 | void Bravo(const Cd & disk); 34 | int main() 35 | { 36 | Cd c1("Beatles", "Capitol", 14, 35.5); 37 | Classic c2 = Classic("Piano Sonata in B flat, Fantasia in C", 38 | "Alfred Brendel", "Philips", 2, 57.17); 39 | Cd *pcd = &c1; 40 | cout << "Using object directly:\n"; 41 | c1.Report(); // use Cd method 42 | c2.Report(); // use Classic method 43 | cout << "Using type cd * pointer to objects:\n"; 44 | pcd->Report(); // use Cd method for cd object 45 | pcd = &c2; 46 | pcd->Report(); // use Classic method for classic object 47 | cout << "Calling a function with a Cd reference argument:\n"; 48 | Bravo(c1); 49 | Bravo(c2); 50 | cout << "Testing assignment: "; 51 | Classic copy; 52 | copy = c2; 53 | copy.Report() 54 | return 0; 55 | } 56 | void Bravo(const Cd & disk) 57 | { 58 | disk.Report(); 59 | } 60 | 61 | 2. Do Programming Exercise 1 but use dynamic memory allocation instead of 62 | fixed size arrays for the various strings tracked by the two classes. 63 | 64 | 3. Revise the baseDMA - lacksDMA - hasDMA class hierarchy so that all three 65 | classes are derived from an ABC. Test the result with a program similar to 66 | the one in Listing 13.10. That is, it should feature an array of pointers to 67 | the ABC and allow the user to make runtime decisions as to what types of 68 | objects are created. Add virtual View() methods to the class definitions to 69 | handle displaying the data. 70 | 71 | 4. The Benevolent Order of Programmers maintains a collection of bottled port. 72 | To describe it,the BOP Portmaster has devised a Port class,as declared here: 73 | 74 | #include 75 | using namespace std; 76 | class Port 77 | { 78 | private: 79 | char * brand; 80 | char style[20]; // i.e., tawny, ruby, vintage 81 | int bottles; 82 | public: 83 | Port(const char * br = "none", const char * st = "none", int b = 0); 84 | Port(const Port & p); // copy constructor 85 | virtual ~Port() { delete [] brand; } 86 | Port & operator=(const Port & p); 87 | Port & operator+=(int b); // adds b to bottles 88 | Port & operator-=(int b); // subtracts b from bottles, if available 89 | int BottleCount() const { return bottles; } 90 | virtual void Show() const; 91 | friend ostream & operator<<(ostream & os, const Port & p); 92 | }; 93 | 94 | The Show() method presents information in the following format: 95 | 96 | Brand: Gallo 97 | Kind: tawny 98 | Bottles: 20 99 | 100 | The operator<<() function presents information in the following format (with 101 | no newline character at the end): 102 | 103 | Gallo, tawny, 20 104 | 105 | The Portmaster completed the method definitions for the Port class and then 106 | derived the VintagePort class as follows before being relieved of his 107 | position for accidentally routing a bottle of ’45 Cockburn to someone 108 | preparing an experimental barbecue sauce: 109 | 110 | class VintagePort : public Port // style necessarily = "vintage" 111 | { 112 | private: 113 | char * nickname; // i.e., "The Noble" or "Old Velvet", etc. 114 | int year; // vintage year 115 | public: 116 | VintagePort(); 117 | VintagePort(const char * br, int b, const char * nn, int y); 118 | VintagePort(const VintagePort & vp); 119 | ~VintagePort() { delete [] nickname; } 120 | VintagePort & operator=(const VintagePort & vp); 121 | void Show() const; 122 | friend ostream & operator<<(ostream & os, const VintagePort & vp); 123 | }; 124 | 125 | You get the job of completing the VintagePort work. 126 | 127 | a. Your first task is to re-create the Port method definitions because the 128 | former Portmaster immolated his upon being relieved. 129 | b. Your second task is to explain why certain methods are redefined and 130 | others are not. 131 | c. Your third task is to explain why operator=() and operator<<() are not 132 | virtual. 133 | d. Your fourth task is to provide definitions for the VintagePort methods. 134 | 135 | ================================================================================ 136 | -------------------------------------------------------------------------------- /chapter_13/sol_13_01/cd_13_01.cpp: -------------------------------------------------------------------------------- 1 | // cd_13_01.cpp --for sol_13_01.cpp 2 | 3 | #include "cd_13_01.h" 4 | #include 5 | #include 6 | 7 | Cd::Cd(const char *s1, const char *s2, int n, double x) 8 | { 9 | performers = new char[std::strlen(s1) + 1]; 10 | label = new char[std::strlen(s2) + 1]; 11 | std::strcpy(performers, s1); 12 | std::strcpy(label, s2); 13 | selections = n; 14 | playtime = x; 15 | } 16 | Cd::Cd(const Cd & d) 17 | { 18 | performers = new char[std::strlen(d.performers) + 1]; 19 | label = new char[std::strlen(d.label) + 1]; 20 | std::strcpy(performers, d.performers); 21 | std::strcpy(label, d.label); 22 | selections = d.selections; 23 | playtime = d.playtime; 24 | } 25 | Cd::Cd() 26 | { 27 | performers = new char[1]; 28 | label = new char[1]; 29 | performers[0] = '\0'; 30 | label[0] = '\0'; 31 | selections = 0; 32 | playtime = 0; 33 | } 34 | Cd::~Cd() 35 | { 36 | delete [] performers; 37 | delete [] label; 38 | } 39 | void Cd::Report() const 40 | { 41 | std::cout << performers << '\n' << label << '\n' 42 | << selections << '\n' << playtime << '\n'; 43 | } 44 | Cd & Cd::operator=(const Cd & d) 45 | { 46 | if(this == &d) 47 | return *this; 48 | delete [] performers; 49 | delete [] label; 50 | performers = new char[std::strlen(d.performers) + 1]; 51 | label = new char[std::strlen(d.label) + 1]; 52 | std::strcpy(performers, d.performers); 53 | std::strcpy(label, d.label); 54 | selections = d.selections; 55 | playtime = d.playtime; 56 | return *this; 57 | } 58 | // Classic methods 59 | Classic::Classic(const char *sc, const char *s1, const char *s2, 60 | int n, double x) : Cd(s1, s2, n, x) 61 | { 62 | pr_work = new char[std::strlen(sc) + 1]; 63 | std::strcpy(pr_work, sc); 64 | } 65 | Classic::Classic(const Classic & d) : Cd(d) 66 | { 67 | pr_work = new char[std::strlen(d.pr_work) + 1]; 68 | std::strcpy(pr_work, d.pr_work); 69 | } 70 | Classic::Classic() : Cd() 71 | { 72 | pr_work = new char[1]; 73 | pr_work[0] = '\0'; 74 | } 75 | Classic::~Classic() 76 | { 77 | delete [] pr_work; 78 | } 79 | void Classic::Report() const 80 | { 81 | std::cout << pr_work << '\n'; 82 | Cd::Report(); 83 | } 84 | Classic & Classic::operator=(const Classic & d) 85 | { 86 | if(this == &d) 87 | return *this; 88 | Cd::operator=(d); 89 | delete [] pr_work; 90 | pr_work = new char[std::strlen(d.pr_work) + 1]; 91 | std::strcpy(pr_work, d.pr_work); 92 | return *this; 93 | } 94 | -------------------------------------------------------------------------------- /chapter_13/sol_13_01/cd_13_01.h: -------------------------------------------------------------------------------- 1 | // cd_13_01.h --for sol_13_01.cpp 2 | 3 | #ifndef CD_H_ 4 | #define CD_H_ 5 | 6 | // base class 7 | class Cd 8 | { // represents a CD disk 9 | private: 10 | char performers[50]; 11 | char label[20]; 12 | int selections; // number of selections 13 | double playtime; // playing time in minutes 14 | public: 15 | Cd(const char *s1, const char *s2, int n, double x); 16 | Cd(const Cd & d); 17 | Cd(); 18 | virtual ~Cd() {} 19 | virtual void Report() const; // reports all CD data 20 | Cd & operator=(const Cd & d); 21 | }; 22 | // Classic Class 23 | class Classic : public Cd 24 | { 25 | private: 26 | char pr_work[100]; 27 | public: 28 | Classic(const char *sc, const char *s1, const char *s2, 29 | int n, double x); 30 | Classic(const Classic & d); 31 | Classic(); 32 | virtual void Report() const; 33 | Classic & operator=(const Classic & d); 34 | }; 35 | #endif // CD_H_ 36 | -------------------------------------------------------------------------------- /chapter_13/sol_13_01/sol_13_01.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 13.1 ------------------------- 3 | 4 | #include 5 | #include "cd_13_01.h" 6 | 7 | void Bravo(const Cd & disk); 8 | int main(void) 9 | { 10 | Cd c1("Beatles", "Capitol", 14, 35.5); 11 | Classic c2 = Classic("Piano Sonata in B flat, Fantasia in C", 12 | "Alfred Brendel", "Philips", 2, 57.17); 13 | Cd *pcd = &c1; 14 | std::cout << "Using object directly:\n"; 15 | c1.Report(); // use Cd method 16 | c2.Report(); // use Classic method 17 | std::cout << "Using type cd * pointer to objects:\n"; 18 | pcd->Report(); // use Cd method for cd object 19 | pcd = &c2; 20 | pcd->Report(); // use Classic method for classic object 21 | std::cout << "Calling a function with a Cd reference argument:\n"; 22 | Bravo(c1); 23 | Bravo(c2); 24 | std::cout << "Testing assignment: "; 25 | Classic copy; 26 | copy = c2; 27 | copy.Report(); 28 | return 0; 29 | } 30 | void Bravo(const Cd & disk) 31 | { 32 | disk.Report(); 33 | } 34 | -------------------------------------------------------------------------------- /chapter_13/sol_13_02/cd_13_02.cpp: -------------------------------------------------------------------------------- 1 | // cd_13_02.cpp --for sol_13_02.cpp 2 | 3 | #include "cd_13_02.h" 4 | #include 5 | #include 6 | 7 | Cd::Cd(const char *s1, const char *s2, int n, double x) 8 | { 9 | performers = new char[std::strlen(s1) + 1]; 10 | label = new char[std::strlen(s2) + 1]; 11 | std::strcpy(performers, s1); 12 | std::strcpy(label, s2); 13 | selections = n; 14 | playtime = x; 15 | } 16 | Cd::Cd(const Cd & d) 17 | { 18 | performers = new char[std::strlen(d.performers) + 1]; 19 | label = new char[std::strlen(d.label) + 1]; 20 | std::strcpy(performers, d.performers); 21 | std::strcpy(label, d.label); 22 | selections = d.selections; 23 | playtime = d.playtime; 24 | } 25 | Cd::Cd() 26 | { 27 | performers = NULL; 28 | label = NULL; 29 | selections = 0; 30 | playtime = 0; 31 | } 32 | Cd::~Cd() 33 | { 34 | delete [] performers; 35 | delete [] label; 36 | } 37 | void Cd::Report() const 38 | { 39 | std::cout << performers << '\n' << label << '\n' 40 | << selections << '\n' << playtime << '\n'; 41 | } 42 | Cd & Cd::operator=(const Cd & d) 43 | { 44 | if(this == &d) 45 | return *this; 46 | delete [] performers; 47 | delete [] label; 48 | performers = new char[std::strlen(d.performers) + 1]; 49 | label = new char[std::strlen(d.label) + 1]; 50 | std::strcpy(performers, d.performers); 51 | std::strcpy(label, d.label); 52 | selections = d.selections; 53 | playtime = d.playtime; 54 | return *this; 55 | } 56 | // Classic methods 57 | Classic::Classic(const char *sc, const char *s1, const char *s2, 58 | int n, double x) : Cd(s1, s2, n, x) 59 | { 60 | pr_work = new char[std::strlen(sc) + 1]; 61 | std::strcpy(pr_work, sc); 62 | } 63 | Classic::Classic(const Classic & d) : Cd(d) 64 | { 65 | pr_work = new char[std::strlen(d.pr_work) + 1]; 66 | std::strcpy(pr_work, d.pr_work); 67 | } 68 | Classic::Classic() : Cd() 69 | { 70 | pr_work = NULL; 71 | } 72 | Classic::~Classic() 73 | { 74 | delete [] pr_work; 75 | } 76 | void Classic::Report() const 77 | { 78 | std::cout << pr_work << '\n'; 79 | Cd::Report(); 80 | } 81 | Classic & Classic::operator=(const Classic & d) 82 | { 83 | if(this == &d) 84 | return *this; 85 | delete [] pr_work; 86 | Cd::operator=(d); 87 | pr_work = new char[std::strlen(d.pr_work) + 1]; 88 | std::strcpy(pr_work, d.pr_work); 89 | return *this; 90 | } 91 | -------------------------------------------------------------------------------- /chapter_13/sol_13_02/cd_13_02.h: -------------------------------------------------------------------------------- 1 | // cd_13_02.h --for sol_13_02.cpp 2 | 3 | #ifndef CD_H_ 4 | #define CD_H_ 5 | 6 | // base class 7 | class Cd 8 | { // represents a CD disk 9 | private: 10 | char * performers; 11 | char * label; 12 | int selections; // number of selections 13 | double playtime; // playing time in minutes 14 | public: 15 | Cd(const char *s1, const char *s2, int n, double x); 16 | Cd(const Cd & d); 17 | Cd(); 18 | virtual ~Cd(); 19 | virtual void Report() const; // reports all CD data 20 | Cd & operator=(const Cd & d); 21 | }; 22 | // Classic Class 23 | class Classic : public Cd 24 | { 25 | private: 26 | char * pr_work; 27 | public: 28 | Classic(const char *sc, const char *s1, const char *s2, 29 | int n, double x); 30 | Classic(const Classic & d); 31 | Classic(); 32 | ~Classic(); 33 | virtual void Report() const; 34 | Classic & operator=(const Classic & d); 35 | }; 36 | #endif // CD_H_ 37 | -------------------------------------------------------------------------------- /chapter_13/sol_13_02/sol_13_02.cpp: -------------------------------------------------------------------------------- 1 | // --------------------- S.Prata C++ Primer Plus 6th ed. ---------------------- 2 | // ----------------------- Programming Exercises 13.2 ------------------------- 3 | 4 | #include 5 | #include "cd_13_02.h" 6 | 7 | void Bravo(const Cd & disk); 8 | int main(void) 9 | { 10 | Cd c1("Beatles", "Capitol", 14, 35.5); 11 | Classic c2 = Classic("Piano Sonata in B flat, Fantasia in C", 12 | "Alfred Brendel", "Philips", 2, 57.17); 13 | Cd *pcd = &c1; 14 | std::cout << "Using object directly:\n"; 15 | c1.Report(); // use Cd method 16 | c2.Report(); // use Classic method 17 | std::cout << "Using type cd * pointer to objects:\n"; 18 | pcd->Report(); // use Cd method for cd object 19 | pcd = &c2; 20 | pcd->Report(); // use Classic method for classic object 21 | std::cout << "Calling a function with a Cd reference argument:\n"; 22 | Bravo(c1); 23 | Bravo(c2); 24 | std::cout << "Testing assignment: "; 25 | Classic copy; 26 | copy = c2; 27 | copy.Report(); 28 | return 0; 29 | } 30 | void Bravo(const Cd & disk) 31 | { 32 | disk.Report(); 33 | } 34 | --------------------------------------------------------------------------------