├── .vscode └── settings.json ├── Chapter 10 ├── exercise1.cpp └── exercise2.cpp ├── Chapter 2 ├── ex1.cpp ├── ex10.cpp ├── ex11.cpp ├── ex12.cpp ├── ex13.cpp ├── ex14.cpp ├── ex15.cpp ├── ex16.cpp ├── ex18.cpp ├── ex19.cpp ├── ex2.cpp ├── ex20.cpp ├── ex21.cpp ├── ex24.cpp ├── ex25.cpp ├── ex3.cpp ├── ex4.cpp ├── ex5.cpp ├── ex6.cpp ├── ex7.cpp ├── ex8.cpp └── ex9.cpp ├── Chapter 3 ├── a.out ├── exercise1.cc ├── exercise2.cc ├── inData.txt ├── outData.txt └── testdata.dat ├── Chapter 4 ├── a.bak ├── a.out ├── exercise10.cpp ├── exercise12.cpp ├── exercise15.cpp ├── exercise17.cpp ├── exercise7.cpp └── exercise9.cpp ├── Chapter 5 ├── exercise1.cpp ├── exercise3.cpp ├── exercise4.cpp ├── exercise5.cpp └── exercise6.cpp ├── Chapter 6 ├── exercise1.cpp ├── exercise10.cpp ├── exercise12.cpp ├── exercise2.cpp ├── exercise3.cpp ├── exercise4.cpp └── exercise5.cpp ├── Chapter 7 ├── exercise1.cpp ├── exercise6.cpp ├── exercise8.cpp ├── genUAIData.rb ├── uaidata.txt └── uaiout.txt ├── Chapter 9 ├── a.out ├── ch9ex6.txt ├── exercise1.cpp ├── exercise2.cpp ├── exercise3.cpp ├── exercise5.cpp ├── exercise6.cpp ├── exercise7.cpp └── generate_ch9ex6_data.rb └── README.md /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "locale": "cpp", 4 | "iostream": "cpp", 5 | "__locale": "cpp", 6 | "string": "cpp", 7 | "iomanip": "cpp" 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter 10/exercise1.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 10 - Exercise 1 4 | markdhoad@gmail.com 5 | 6 | Write a program to test the function seqOrderedSearch. Use either the 7 | function bubbleSort or selectionSort to sort the list before the search. 8 | *****************************************************************************/ 9 | 10 | 11 | #include 12 | 13 | using namespace std; 14 | 15 | void bubbleSort(int list[ ] , int length); 16 | int seqOrderedSearch(const int list[], int listLength, int searchItem); 17 | 18 | int main() 19 | { 20 | int list[] = {2, 56, 34, 25, 73, 46, 89, 10, 5, 16}; 21 | bubbleSort(list, 10); 22 | int pos = seqOrderedSearch(list, 10, 46); 23 | cout << "The element 46 was found at position: " << pos << endl; 24 | 25 | return 0; 26 | } 27 | 28 | void bubbleSort(int list[], int length) { 29 | int temp; 30 | int iteration; 31 | int index; 32 | for (iteration = 1; iteration < length; iteration++) { 33 | for (index = 0; index < length - iteration; index++) if (list[index] > list[index + 1]) 34 | { 35 | temp = list[index]; list[index] = list[index + 1]; list[index + 1] = temp; 36 | } 37 | } 38 | } 39 | 40 | int seqOrderedSearch(const int list[], int listLength, int searchItem) { 41 | int loc; 42 | bool found = false; 43 | for (loc = 0; loc < listLength; loc++) if (list[loc] >= searchItem){ 44 | found = true; 45 | break; 46 | } 47 | if (found) 48 | if (list[loc] == searchItem) 49 | return loc; 50 | else 51 | return -1; 52 | } 53 | -------------------------------------------------------------------------------- /Chapter 10/exercise2.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 10 - Exercise 2 4 | markdhoad@gmail.com 5 | 6 | Write a program to test the function binarySearch. 7 | Use either the function bubbleSort or selectionSort to sort the list before the search. 8 | *****************************************************************************/ 9 | 10 | 11 | #include 12 | 13 | using namespace std; 14 | 15 | void bubbleSort(int list[ ] , int length); 16 | int binarySearch(const int list[], int listLength, int searchItem); 17 | int main() 18 | { 19 | int list[] = {2, 56, 34, 25, 73, 46, 89, 10, 5, 16}; 20 | bubbleSort(list, 10); 21 | int pos = binarySearch(list, 10, 89); 22 | cout << "The element 89 was found at position: " << pos << endl; 23 | 24 | return 0; 25 | } 26 | 27 | void bubbleSort(int list[], int length) { 28 | int temp; 29 | int iteration; 30 | int index; 31 | for (iteration = 1; iteration < length; iteration++) { 32 | for (index = 0; index < length - iteration; index++) if (list[index] > list[index + 1]) 33 | { 34 | temp = list[index]; list[index] = list[index + 1]; list[index + 1] = temp; 35 | } 36 | } 37 | } 38 | 39 | int binarySearch(const int list[], int listLength, int searchItem) { 40 | int first = 0; 41 | int last = listLength - 1; 42 | int mid; 43 | bool found = false; 44 | 45 | while (first <= last && !found) 46 | { 47 | mid = (first + last) / 2; 48 | 49 | if (list[mid] == searchItem) 50 | found = true; 51 | else if (list[mid] > searchItem) 52 | last = (mid - 1); 53 | else 54 | first = (mid + 1); 55 | } 56 | if (found) 57 | return mid; 58 | else 59 | return -1; 60 | }//end binarySearch -------------------------------------------------------------------------------- /Chapter 2/ex1.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 2 - Exercise 1 4 | markdhoad@gmail.com 5 | 6 | Write a program that produces the following output: 7 | 8 | ********************************** 9 | * Programming Assignment 1 * 10 | * Computer Programming 1 * 11 | * Author: ??? * 12 | * Due Date: Thursday Jan. 24 * 13 | ********************************** 14 | 15 | *****************************************************************************/ 16 | 17 | #include 18 | #include 19 | 20 | using namespace std; 21 | 22 | int main() 23 | { 24 | cout << "**********************************" << endl; 25 | cout << "*" << setw(28) << "Programming Assignment 1" << setw(5) << "*" << endl; 26 | cout << "*" << setw(27) << "Computer Programming 1" << setw(6) << "*" << endl; 27 | cout << "*" << setw(21) << "Author: ???" << setw(12) << "*" << endl; 28 | cout << "*" << setw(29) << "Due Date: Thursday Jan. 24" << setw(4) << "*" << endl; 29 | cout << "**********************************" << endl; 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /Chapter 2/ex10.cpp: -------------------------------------------------------------------------------- 1 | 2 | /***************************************************************************** 3 | C++ Programming - From Problem Analysis to Program Design 6th Edition 4 | Chapter 2 - Exercise 11 5 | markdhoad@gmail.com 6 | 7 | Write a program that does the following: 8 | a. Prompts the user to input five decimal numbers. 9 | b. Prints the five decimal numbers. 10 | c. Converts each decimal number to the nearest integer. 11 | d. Adds the five integers. 12 | e. Prints the sum and average of the five integers. 13 | 14 | *****************************************************************************/ 15 | 16 | #include 17 | 18 | using namespace std; 19 | 20 | int main() 21 | { 22 | double test1, test2, test3, test4, test5; 23 | 24 | cout << "Please enter 5 decimal numbers: \n"; 25 | cin >> test1 >> test2 >> test3 >> test4 >> test5; 26 | double total = test1 + test2 + test3 + test4 + test5; 27 | 28 | cout << "The total of all the numbers is: " << static_cast(total) << endl; 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /Chapter 2/ex11.cpp: -------------------------------------------------------------------------------- 1 | 2 | /***************************************************************************** 3 | C++ Programming - From Problem Analysis to Program Design 6th Edition 4 | Chapter 2 - Exercise 11 5 | markdhoad@gmail.com 6 | 7 | Write a program that does the following: 8 | a. Prompts the user to input five decimal numbers. 9 | b. Prints the five decimal numbers. 10 | c. Converts each decimal number to the nearest integer. 11 | d. Adds the five integers. 12 | e. Prints the sum and average of the five integers. 13 | 14 | *****************************************************************************/ 15 | 16 | #include 17 | 18 | using namespace std; 19 | 20 | int main() 21 | { 22 | double test1, test2, test3, test4, test5; 23 | int int1, int2, int3, int4, int5; 24 | 25 | cout << "Please enter 5 decimal numbers: \n"; 26 | cin >> test1 >> test2 >> test3 >> test4 >> test5; 27 | cout << test1 << " " << test2 << " " << test3 << " " << test4 << " " << test5 << endl; 28 | 29 | int1 = static_cast(test1); 30 | int2 = static_cast(test2); 31 | int3 = static_cast(test3); 32 | int4 = static_cast(test4); 33 | int5 = static_cast(test5); 34 | 35 | 36 | int total = int1 + int2 + int3 + int4 + int5; 37 | double average = (int1 + int2 + int3 + int4 + int5) / 5; 38 | 39 | cout << "The total of all the numbers is: " << total << endl; 40 | cout << "The average of all the numbers is: " << average << endl; 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /Chapter 2/ex12.cpp: -------------------------------------------------------------------------------- 1 | 2 | /***************************************************************************** 3 | C++ Programming - From Problem Analysis to Program Design 6th Edition 4 | Chapter 2 - Exercise 12 5 | markdhoad@gmail.com 6 | 7 | Write a program that prompts the capacity, in gallons, of an automobile fuel tank 8 | and the miles per gallon the automobile can be driven. 9 | 10 | The program outputs the number of miles the automobile can be 11 | driven without refueling. 12 | 13 | *****************************************************************************/ 14 | 15 | #include 16 | 17 | using namespace std; 18 | 19 | int main() 20 | { 21 | int milesPerGallon, tankCapacity; 22 | 23 | cout << "Please enter the capacity of the tank: "; 24 | cin >> tankCapacity; 25 | 26 | cout << "Please enter the miles per gallons: "; 27 | cin >> milesPerGallon; 28 | 29 | cout << "This mean that you can drive " << tankCapacity * milesPerGallon << " miles on a full tank." << endl; 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /Chapter 2/ex13.cpp: -------------------------------------------------------------------------------- 1 | 2 | /***************************************************************************** 3 | C++ Programming - From Problem Analysis to Program Design 6th Edition 4 | Chapter 2 - Exercise 13 5 | markdhoad@gmail.com 6 | 7 | Write a C++ program that prompts the user to input the elapsed time for an 8 | event in seconds. 9 | 10 | The program then outputs the elapsed time in hours, minutes, 11 | and seconds. (For example, if the elapsed time is 9630 seconds, 12 | then the output is 2:40:30.) 13 | 14 | *****************************************************************************/ 15 | 16 | #include 17 | 18 | using namespace std; 19 | 20 | int main() 21 | { 22 | int secondsElapsed, hours, minutes, seconds; 23 | 24 | const int secondsPerMinute = 60; 25 | const int secondsPerHour = 60 * secondsPerMinute; 26 | 27 | cout << "Please enter the number of seconds elapsed: "; 28 | cin >> secondsElapsed; 29 | 30 | hours = secondsElapsed / secondsPerHour; 31 | secondsElapsed = secondsElapsed % secondsPerHour; 32 | minutes = secondsElapsed / secondsPerMinute; 33 | seconds = secondsElapsed % secondsPerMinute; 34 | 35 | cout << hours << ":" << minutes << ":" << seconds << endl; 36 | return 0; 37 | } -------------------------------------------------------------------------------- /Chapter 2/ex14.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 6th Edition 3 | Chapter 2 - Exercise 14 4 | markdhoad@gmail.com 5 | 6 | Write a C++ program that prompts the user to input the elapsed time for an 7 | event in hours, minutes, and seconds. 8 | 9 | The program then outputs the elapsed time in seconds. 10 | 11 | *****************************************************************************/ 12 | 13 | #include 14 | 15 | using namespace std; 16 | 17 | int main() 18 | { 19 | int hours, minutes, seconds, totalSeconds; 20 | const int secondsPerMinute = 60; 21 | const int secondsPerHour = 60 * secondsPerMinute; 22 | 23 | cout << "Please input the hours minutes and seconds: "; 24 | cin >> hours >> minutes >> seconds; 25 | 26 | totalSeconds = seconds + (minutes * secondsPerMinute) + (hours * secondsPerHour); 27 | 28 | cout << "That equals a total of " << totalSeconds << " seconds." << endl; 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /Chapter 2/ex15.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 6th Edition 3 | Chapter 2 - Exercise 15 4 | markdhoad@gmail.com 5 | 6 | To make a profit, a local store marks up the prices of its items by a certain percentage. 7 | Write a C++ program that reads the original price of the item sold, the percentage of 8 | the marked-up price, and the sales tax rate. The program then outputs the original 9 | price of the item, the percentage of the mark-up, the store’s selling price of the 10 | item, the sales tax rate, the sales tax, and the final price of the item. 11 | 12 | (The final price of the item is the selling price plus the sales tax.) 13 | 14 | *****************************************************************************/ 15 | 16 | #include 17 | 18 | using namespace std; 19 | 20 | int main() 21 | { 22 | double originalPrice, salesTaxRate, totalPrice, markupPercentage, salesTaxPrice, markupPrice; 23 | 24 | cout << "Please enter the original price: $"; 25 | cin >> originalPrice; 26 | 27 | cout << "Please enter the mark-up percentage: "; 28 | cin >> markupPercentage; 29 | 30 | cout << "Please enter the sales tax percentage: "; 31 | cin >> salesTaxRate; 32 | 33 | markupPrice = originalPrice * (markupPercentage / 100); 34 | salesTaxPrice = originalPrice * (salesTaxRate / 100); 35 | totalPrice = originalPrice + salesTaxPrice + markupPrice; 36 | 37 | cout << "Original Price: $" << originalPrice << endl; 38 | cout << "Sales Tax: $" << salesTaxPrice << endl; 39 | cout << "Mark-Up: $" << markupPrice << endl; 40 | cout << "Total Price: $" << totalPrice << endl; 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /Chapter 2/ex16.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 6th Edition 3 | Chapter 2 - Exercise 16 4 | markdhoad@gmail.com 5 | 6 | If you buy a 40GB hard drive, then chances are that the actual storage on the hard drive 7 | is not 40GB. This is due to the fact that, typically, a manufacturer uses 1000 bytes 8 | as the value of 1K bytes, 1000K bytes as the value of 1MB, 1000MB as the value of 1GB. 9 | Therefore, a 40GB byte hard drive contains 40,000,000,000 bytes. However, in computer 10 | memory, as given in Table 1-1 (Chapter 1), 1KB is equal to 1024 bytes, and so on. 11 | So the actual storage on a 40GB hard drive is approximately 37.25GB. 12 | (You might like to read the fine print next time you buy a hard drive.) 13 | 14 | Write a program that prompts the user to enter the size of the hard drive specified 15 | by the manufacturer, on the hard drive box, and outputs the actual 16 | storage capacity of the hard drive. 17 | *****************************************************************************/ 18 | 19 | 20 | #include 21 | 22 | using namespace std; 23 | 24 | int main(){ 25 | double hddSpecifiedSize, hddRealSize; 26 | 27 | cout << "Please enter the size of the HDD: "; 28 | cin >> hddSpecifiedSize; 29 | 30 | hddSpecifiedSize = hddSpecifiedSize * 1000 * 1000; //Give the size in bytes 31 | hddRealSize = hddSpecifiedSize / 1024 / 1024; //Recompile to GB 32 | 33 | cout << "Hard Drive is actually: " << hddRealSize << "GB" << endl; 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /Chapter 2/ex18.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 6th Edition 3 | Chapter 2 - Exercise 18 4 | markdhoad@gmail.com 5 | 6 | A milk carton can hold 3.78 liters of milk. Each morning, a dairy farm ships 7 | cartons of milk to a local grocery store. The cost of producing one liter of 8 | milk is $0.38, and the profit of each carton of milk is $0.27. 9 | 10 | Write a program that does the following: 11 | a. Prompts the user to enter the total amount of milk produced in the morning. 12 | b. Outputs the number of milk cartons needed to hold milk. (Round your answer to the nearest integer.) 13 | c. Outputs the cost of producing milk. 14 | d. Outputs the profit for producing milk. 15 | *****************************************************************************/ 16 | 17 | 18 | #include 19 | #include 20 | 21 | using namespace std; 22 | 23 | int main(){ 24 | double milkProduced, cartonsRequired; 25 | 26 | const double cartonSize = 3.78; 27 | const double productionCost = 0.38; 28 | const double cartonProfit = 0.27; 29 | 30 | cout << "How much milk did you produce? "; 31 | cin >> milkProduced; 32 | 33 | cartonsRequired = milkProduced / cartonSize; 34 | 35 | cout << fixed << showpoint << setprecision(2); 36 | 37 | cout << "That is going to require " << static_cast(cartonsRequired) << " cartons" << endl; 38 | cout << "Total Cost to Produce: $" << cartonsRequired * productionCost << endl; 39 | cout << "Total Profit: $" << cartonsRequired * cartonProfit << endl; 40 | 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /Chapter 2/ex19.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 6th Edition 3 | Chapter 2 - Exercise 19 4 | markdhoad@gmail.com 5 | 6 | Redo Programming Exercise 18 so that the user can also input the cost of 7 | producing one liter of milk and the profit on each carton of milk. 8 | 9 | *****************************************************************************/ 10 | 11 | 12 | #include 13 | #include 14 | 15 | using namespace std; 16 | 17 | int main(){ 18 | double milkProduced, cartonsRequired, productionCost, cartonProfit; 19 | 20 | const double cartonSize = 3.78; 21 | 22 | cout << "How much milk did you produce? "; 23 | cin >> milkProduced; 24 | 25 | cout << "How much does it cost to produce? $"; 26 | cin >> productionCost; 27 | 28 | cout << "How much profit do you make? $"; 29 | cin >> cartonProfit; 30 | 31 | cartonsRequired = milkProduced / cartonSize; 32 | 33 | cout << fixed << showpoint << setprecision(2); 34 | 35 | cout << "That is going to require " << static_cast(cartonsRequired) << " cartons" << endl; 36 | cout << "Total Cost to Produce: $" << cartonsRequired * productionCost << endl; 37 | cout << "Total Profit: $" << cartonsRequired * cartonProfit << endl; 38 | 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /Chapter 2/ex2.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 2 - Exercise 2 4 | markdhoad@gmail.com 5 | 6 | Write a program that produces the following output: 7 | 8 | CCCCCCCCC ++ ++ 9 | CC ++ ++ 10 | CC ++++++++++++++ +++++++++++++++ 11 | CC ++++++++++++++ +++++++++++++++ 12 | CC ++ ++ 13 | CCCCCCCCC ++ ++ 14 | 15 | *****************************************************************************/ 16 | 17 | #include 18 | #include 19 | 20 | using namespace std; 21 | 22 | int main() 23 | { 24 | cout << "CCCCCCCCCC" << setw(15) << "++" << setw(20) << "++" << endl; 25 | cout << "CC" << setw(23) << "++" << setw(20) << "++" << endl; 26 | cout << "CC" << setw(30) << "++++++++++++++" << setw(20) << "++++++++++++++" << endl; 27 | cout << "CC" << setw(30) << "++++++++++++++" << setw(20) << "++++++++++++++" << endl; 28 | cout << "CC" << setw(23) << "++" << setw(20) << "++" << endl; 29 | cout << "CCCCCCCCCC" << setw(15) << "++" << setw(20) << "++" << endl; 30 | return 0; 31 | } -------------------------------------------------------------------------------- /Chapter 2/ex20.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 6th Edition 3 | Chapter 2 - Exercise 20 4 | markdhoad@gmail.com 5 | 6 | You found an exciting summer job for five weeks. It pays, say, $15.50 per hour. 7 | Suppose that the total tax you pay on your summer job income is 14%. 8 | After paying the taxes, you spend 10% of your net income to buy new clothes and 9 | other accessories for the next school year and 1% to buy school supplies. 10 | After buying clothes and school supplies, you use 25% of the remaining money to 11 | buy savings bonds. For each dollar you spend to buy savings bonds, your parents 12 | spend $0.50 to buy additional savings bonds for you. 13 | 14 | Write a program that prompts the user to enter the pay rate for an hour and the 15 | number of hours you worked each week. 16 | 17 | The program then outputs the following: 18 | a. Your income before and after taxes from your summer job. 19 | b. The money you spend on clothes and other accessories. 20 | c. The money you spend on school supplies. 21 | d. The money you spend to buy savings bonds. 22 | e. The money your parents spend to buy additional savings bonds for you. 23 | 24 | *****************************************************************************/ 25 | 26 | 27 | #include 28 | #include 29 | 30 | using namespace std; 31 | 32 | int main(){ 33 | double payRate, grossIncome, netIncome, schoolAmount, bondsAmount; 34 | double clothesAmount, parentsBondsAmount, hoursWorked; 35 | 36 | const double TAX_RATE = 0.14; 37 | const double CLOTHES_PERCENTAGE_OF_INCOME = 0.10; 38 | const double SCHOOL_PERCENTAGE_OF_INCOME = 0.01; 39 | const double SAVINGS_BONDS_PERCENTAGE_OF_INCOME = 0.25; 40 | const double PARENTS_CO_CONTRIBUTION_AMOUNT = 0.50; 41 | 42 | cout << "How many hours did you work: "; 43 | cin >> hoursWorked; 44 | 45 | cout << "What was the hourly rate: $"; 46 | cin >> payRate; 47 | 48 | grossIncome = hoursWorked * payRate; 49 | netIncome = grossIncome *= TAX_RATE; 50 | clothesAmount = netIncome * CLOTHES_PERCENTAGE_OF_INCOME; 51 | schoolAmount = netIncome * SCHOOL_PERCENTAGE_OF_INCOME; 52 | netIncome -= (clothesAmount + schoolAmount); // Calculate what is now left 53 | bondsAmount = netIncome * SAVINGS_BONDS_PERCENTAGE_OF_INCOME; 54 | parentsBondsAmount = bondsAmount * PARENTS_CO_CONTRIBUTION_AMOUNT; 55 | 56 | cout << fixed << showpoint << setprecision(2); 57 | 58 | cout << "Gross Income: $" << grossIncome << endl; 59 | cout << "Net Income: $" << netIncome << endl; 60 | cout << "Clothes & Accessories: $" << clothesAmount << endl; 61 | cout << "School Supplies: $" << schoolAmount << endl; 62 | cout << "Savings Bonds: $" << bondsAmount << endl; 63 | cout << "Parents Bonds Co-Contribution: $" < 16 | 17 | using namespace std; 18 | 19 | int main(){ 20 | char letterOne, letterTwo, letterThree; 21 | 22 | cout << "Please enter 3 letters seperated by a space: "; 23 | cin >> letterOne >> letterTwo >> letterThree; 24 | 25 | cout << "Here are all the possible permutations of those letters: " << endl; 26 | cout << letterOne << letterTwo << letterThree << endl; 27 | cout << letterTwo << letterThree << letterOne << endl; 28 | cout << letterThree << letterOne << letterTwo << endl; 29 | cout << letterOne << letterThree << letterTwo << endl; 30 | cout << letterTwo << letterOne << letterThree << endl; 31 | cout << letterThree << letterTwo << letterOne << endl; 32 | return 0; 33 | } -------------------------------------------------------------------------------- /Chapter 2/ex24.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 6th Edition 3 | Chapter 2 - Exercise 24 4 | markdhoad@gmail.com 5 | 6 | One metric ton is approximately 2205 pounds. Write a program that prompts the 7 | user to input the amount of rice, in pounds, in a bag. The program outputs 8 | the number of bags needed to store one metric ton of rice. 9 | 10 | *****************************************************************************/ 11 | 12 | 13 | #include 14 | 15 | using namespace std; 16 | 17 | int main(){ 18 | double bagCapacity; 19 | 20 | cout << "How many pounds can the bag hold? "; 21 | cin >> bagCapacity; 22 | 23 | cout << "You would need " << 2205 / bagCapacity << " bags to store a ton" << endl; 24 | return 0; 25 | } -------------------------------------------------------------------------------- /Chapter 2/ex25.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 6th Edition 3 | Chapter 2 - Exercise 25 4 | markdhoad@gmail.com 5 | 6 | Cindy uses the services of a brokerage firm to buy and sell stocks. 7 | The firm charges 1.5% service charges on the total amount for each transaction, 8 | buy or sell. When Cindy sells stocks, she would like to know if she gained or 9 | lost on a particular investment. Write a program that allows Cindy to input 10 | the number of shares sold, the purchase price of each share, and the selling 11 | price of each share. The program outputs the amount invested, the total 12 | service charges, amount gained or lost, and the amount received after selling the stock. 13 | 14 | *****************************************************************************/ 15 | 16 | 17 | #include 18 | #include 19 | 20 | 21 | using namespace std; 22 | 23 | int main(){ 24 | const double BROKERAGE_FEE = 0.015; 25 | double purchasePrice, salePrice, netAmount, originalInvestment, totalFees; 26 | int sharesSold; 27 | 28 | cout << "How many shares did you sell? "; 29 | cin >> sharesSold; 30 | cout << "What was the sale price: $"; 31 | cin >> salePrice; 32 | cout << "What was the purchase price: $"; 33 | cin >> purchasePrice; 34 | 35 | originalInvestment = sharesSold * purchasePrice; 36 | totalFees = (sharesSold * salePrice) * BROKERAGE_FEE; 37 | netAmount = (sharesSold * salePrice) - totalFees; 38 | 39 | cout << fixed << showpoint << setprecision(2); 40 | 41 | cout << "Amount invested: $" << originalInvestment << endl; 42 | cout << "Service charges: $" << totalFees << endl; 43 | cout << "Profit / Loss: $" << netAmount - originalInvestment << endl; 44 | return 0; 45 | } -------------------------------------------------------------------------------- /Chapter 2/ex3.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 2 - Exercise 3 4 | markdhoad@gmail.com 5 | 6 | Consider the following program segment: 7 | 8 | //include statement(s) 9 | //using namespace statement 10 | 11 | int main() 12 | { 13 | //variable declaration 14 | //executable statements 15 | //return statement 16 | } 17 | 18 | 19 | a. Write C++ statements that include the header files iostream. 20 | b. Write a C++ statement that allows you to use cin, cout, and endl 21 | without the prefix std::. 22 | c. Write C++ statements that declare the following variables: num1, num2, 23 | num3, and average of type int. 24 | d. Write C++ statements that store 125 into num1, 28 into num2, and 25 | -25 into num3. 26 | e. Write a C++ statement that stores the average of num1, num2, and 27 | num3, into average. 28 | f. Write C++ statements that output the values of num1, num2, num3, 29 | and average. 30 | g. Compile and run your program. 31 | 32 | 33 | *****************************************************************************/ 34 | 35 | #include 36 | 37 | using namespace std; 38 | 39 | int main() 40 | { 41 | int num1, num2, num3; 42 | 43 | num1 = 125; 44 | num2 = 28; 45 | num3 = -25; 46 | 47 | int average = (num1 + num2 + num3) / 3; 48 | 49 | cout << "Num 1 = " << num1 << endl; 50 | cout << "Num 2 = " << num2 << endl; 51 | cout << "Num 3 = " << num3 << endl; 52 | cout << "Average = " << average << endl; 53 | 54 | return 0; 55 | } -------------------------------------------------------------------------------- /Chapter 2/ex4.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 2 - Exercise 4 4 | markdhoad@gmail.com 5 | 6 | Repeat Exercise 3 by declaring num1, num2, and num3, and average of type double. 7 | Store 75.35 into num1, -35.56 into num2, and 15.76 into num3. 8 | 9 | 10 | *****************************************************************************/ 11 | 12 | #include 13 | 14 | using namespace std; 15 | 16 | int main() 17 | { 18 | double num1, num2, num3; 19 | 20 | num1 = 75.35; 21 | num2 = -35.56; 22 | num3 = 15.76; 23 | 24 | double average = (num1 + num2 + num3) / 3; 25 | 26 | cout << "Num 1 = " << num1 << endl; 27 | cout << "Num 2 = " << num2 << endl; 28 | cout << "Num 3 = " << num3 << endl; 29 | cout << "Average = " << average << endl; 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /Chapter 2/ex5.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 2 - Exercise 5 4 | markdhoad@gmail.com 5 | 6 | Consider the following C++ program in which the statements are in the incorrect order. 7 | Rearrange the statements so that it prompts the user to input the length and 8 | width of a rectangle and output the area and perimeter of the rectangle. 9 | 10 | #include { 11 | int main() 12 | cout << "Enter the length: "; 13 | cin >> length; 14 | cout << endl; 15 | int length; 16 | area = length * width; 17 | return 0; 18 | int width; 19 | cin>> width; 20 | cout << "Enter the width: " 21 | cout << endl; 22 | cout << "Area = " << area << endl; 23 | cout << "Perimeter = " << perimeter << endl; 24 | int area; 25 | using namespace std; 26 | int perimeter; 27 | } 28 | 29 | *****************************************************************************/ 30 | 31 | #include 32 | 33 | using namespace std; 34 | 35 | int main() 36 | { 37 | int length; 38 | int width; 39 | int perimeter; 40 | int area; 41 | 42 | cout << "Enter the length: "; 43 | cin >> length; 44 | 45 | cout << "Enter the width: "; 46 | cin>> width; 47 | 48 | area = length * width; 49 | perimeter = (length * 2) + (width * 2); 50 | 51 | cout << "Area = " << area << endl; 52 | cout << "Perimeter = " << perimeter << endl; 53 | 54 | return 0; 55 | } -------------------------------------------------------------------------------- /Chapter 2/ex6.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 2 - Exercise 6 4 | markdhoad@gmail.com 5 | 6 | Consider the following program segment: 7 | 8 | //include statement(s) 9 | //using namespace statement 10 | 11 | int main() 12 | { 13 | //variable declaration 14 | //executable statements 15 | //return statement 16 | } 17 | 18 | 19 | a. Write C++ statements that include the header files iostream and string. 20 | b. Write a C++ statement that allows you to use cin, cout, and endl 21 | without the prefix std::. 22 | c. Write C++ statements that declare the following variables: name of 23 | type string and studyHours of type double. 24 | d. Write C++ statements that prompt and input a string into name 25 | and a double value into studyHours. 26 | e. Write a C++ statement that outputs the values of name and studyHours 27 | with the appropriate text. For example, if the value of name is "Donald" 28 | and the value of studyHours is 4.5, the output is: 29 | 30 | Hello, Donald! on Saturday, you need to study 4.5 hours for the exam. 31 | 32 | f. Compile and run your program. 33 | 34 | 35 | *****************************************************************************/ 36 | 37 | #include 38 | #include 39 | 40 | using namespace std; 41 | 42 | int main() 43 | { 44 | string name; 45 | double studyHours; 46 | 47 | cout << "Please enter your name: "; 48 | cin >> name; 49 | cout << "Please enter the number of study hours: "; 50 | cin >> studyHours; 51 | 52 | cout << "Hello " << name << "! on Saturday, you need to study " << studyHours; 53 | cout << " hours for the exam. " << endl; 54 | 55 | return 0; 56 | } -------------------------------------------------------------------------------- /Chapter 2/ex7.cpp: -------------------------------------------------------------------------------- 1 | 2 | /***************************************************************************** 3 | C++ Programming - From Problem Analysis to Program Design 5th Edition 4 | Chapter 2 - Exercise 7 5 | markdhoad@gmail.com 6 | 7 | Write a program that prompts the user to input a decimal number and 8 | outputs the number rounded to the nearest integer. 9 | 10 | *****************************************************************************/ 11 | 12 | #include 13 | #include 14 | 15 | using namespace std; 16 | 17 | int main() 18 | { 19 | double userNumber; 20 | 21 | cout << "Enter a decimal number: "; 22 | cin >> userNumber; 23 | 24 | cout << setprecision(0) << userNumber << endl; 25 | 26 | return 0; 27 | } -------------------------------------------------------------------------------- /Chapter 2/ex8.cpp: -------------------------------------------------------------------------------- 1 | 2 | /***************************************************************************** 3 | C++ Programming - From Problem Analysis to Program Design 5th Edition 4 | Chapter 2 - Exercise 8 5 | markdhoad@gmail.com 6 | 7 | Consider the following program segment: 8 | 9 | //include statement(s) 10 | //using namespace statement 11 | 12 | int main() 13 | { 14 | //variable declaration 15 | //executable statements 16 | //return statement 17 | } 18 | 19 | a. Write C++ statements that include the header files iostream. 20 | b. Write a C++ statement that allows you to use cin, cout, and endl 21 | without the prefix std::. 22 | c. Write C++ statements that declare and initialize the following 23 | named constants: SECRET of type int initialized to 11 and RATE of 24 | type double initialized to 12.50. 25 | d. Write C++ statements that declare the following variables: 26 | num1, num2, and newNum of type int; name of type string; 27 | and hoursWorked and wages of type double. 28 | e. Write C++ statements that prompt the user to input two 29 | integers and store the first number in num1 and the second number in num2. 30 | f. Write a C++ statement(s) that outputs the values of num1 and num2, 31 | indicating which is num1 and which is num2. For example, if num1 is 8 32 | and num2 is 5, then the output is: 33 | 34 | The value of num1 = 8 and the value of num2 = 5. 35 | 36 | g. Write a C++ statement that multiplies the value of num1 by 2, adds the 37 | value of num2 to it, and then stores the result in newNum. Then, 38 | write a C++ statement that outputs the value of newNum. 39 | h. Write a C++ statement that updates the value of newNum by adding the value 40 | of the named constant SECRET. Then, write a C++ statement that outputs 41 | the value of newNum with an appropriate message. 42 | i. Write C++ statements that prompt the user to enter a person’s last name 43 | and then store the last name into the variable name. 44 | j. Write C++ statements that prompt the user to enter a decimal number 45 | between 0 and 70 and then store the number entered into hoursWorked. 46 | k. Write a C++ statement that multiplies the value of the named constant RATE 47 | with the value of hoursWorked and then stores the result into the variable wages. 48 | l. Write C++ statements that produce the following output: 49 | 50 | Name: //Output the name variable 51 | Pay Rate: $ //Output the rate variable 52 | Hours Worked: //Output the hoursWorked variable 53 | Salary: $ //Output the value of the wages variable 54 | 55 | For example, if the value of name is "Rainbow" and hoursWorked is 56 | 45.50, then the output is: 57 | 58 | Name: Rainbow 59 | Pay Rate: $12.50 60 | Hours Worked: 45.50 61 | Salary: $568.75 62 | 63 | m. Write a C++ program that tests each of the C++ statements that you wrote 64 | in parts a through l. Place the statements at the appropriate place in 65 | the previous C++ program segment. Test run your program (twice) on 66 | the following input data: 67 | 68 | a. num1 = 13, num2 = 28; name = "Jacobson"; hoursWorked = 48.30. 69 | b. num1 = 32, num2 = 15; name = "Crawford"; hoursWorked = 58.45. 70 | 71 | *****************************************************************************/ 72 | 73 | #include 74 | #include 75 | 76 | using namespace std; 77 | 78 | int main() 79 | { 80 | int const SECRET = 11; 81 | double const RATE = 12.50; 82 | int num1, num2, newNum; 83 | string name; 84 | double hoursWorked, wages; 85 | 86 | cout << "Please input 2 numbers: "; 87 | cin >> num1 >> num2; 88 | cout << "The value of num1 = " << num1 << " and the value of num2 = " << num2 << endl; 89 | 90 | newNum = num1 * 2 + num2; 91 | 92 | cout << "newNum = " << newNum << endl; 93 | 94 | newNum += SECRET; 95 | 96 | cout << "newNum now = " << newNum << endl; 97 | 98 | cout << "Please enter your surname: "; 99 | cin >> name; 100 | cout << "Please enter the number of hours worked (0 - 70): "; 101 | cin >> hoursWorked; 102 | 103 | wages = hoursWorked * RATE; 104 | 105 | cout << "Name: " << name << endl; 106 | cout << "Pay Rate: $" << RATE << endl; 107 | cout << "Hours Worked: " << hoursWorked << endl; 108 | cout << "Salary: $" << wages << endl; 109 | 110 | return 0; 111 | } -------------------------------------------------------------------------------- /Chapter 2/ex9.cpp: -------------------------------------------------------------------------------- 1 | 2 | /***************************************************************************** 3 | C++ Programming - From Problem Analysis to Program Design 6th Edition 4 | Chapter 2 - Exercise 9 5 | markdhoad@gmail.com 6 | 7 | Write a program that prompts the user to enter five test scores and then prints 8 | the average test score. (Assume that the test scores are decimal numbers.) 9 | 10 | *****************************************************************************/ 11 | 12 | #include 13 | 14 | using namespace std; 15 | 16 | int main() 17 | { 18 | double test1, test2, test3, test4, test5; 19 | 20 | cout << "Please enter 5 test scores as decimals \n"; 21 | cin >> test1 >> test2 >> test3 >> test4 >> test5; 22 | double average = (test1 + test2 + test3 + test4 + test5) / 5; 23 | 24 | cout << "The average test score is: " << average << endl; 25 | 26 | return 0; 27 | } -------------------------------------------------------------------------------- /Chapter 3/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhoad/cpp_book/8fada5b4a2bb8df1af53b4c16088468daa64753e/Chapter 3/a.out -------------------------------------------------------------------------------- /Chapter 3/exercise1.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | int main() { 10 | ifstream inFile; 11 | ofstream outFile; 12 | double width, length, parameter, radius, circumference; 13 | double balance, interestRate; 14 | char ch; 15 | int age; 16 | string firstName, lastName; 17 | const double PI = 3.1416; 18 | 19 | inFile.open("inData.txt"); 20 | outFile.open("outData.txt"); 21 | 22 | inFile >> length >> width >> radius >> firstName 23 | >> lastName >> age >> balance >> interestRate >> ch; 24 | 25 | cout << fixed << showpoint << setprecision(2);; 26 | 27 | cout << "Rectange:" << endl; 28 | cout << "Length = " << length << ", Width: " << width 29 | << ", Area = " << length * width 30 | << ", Parameter = " << (length + width) * 2 << endl; 31 | cout << endl; 32 | 33 | cout << "Circle: " << endl; 34 | cout << "Radius: " << radius << ", Area: " << PI * pow(radius, 2) 35 | << ", Circumference: " << 2 * PI * radius << endl; 36 | cout << endl; 37 | 38 | cout << "Name: " << firstName << " " << lastName << ", Age: " << age << endl; 39 | cout << "Beginning Balance = $" << balance << ", Interest Rate: " << interestRate << endl; 40 | cout << "Balance at end of the month: $" 41 | << balance * (interestRate / 100 / 12) + balance << endl; 42 | cout << endl; 43 | 44 | cout << "The ASCII character that comes after " << ch << " is " << ++ch << endl; 45 | inFile.close(); 46 | outFile.close(); 47 | 48 | return 0; 49 | } -------------------------------------------------------------------------------- /Chapter 3/exercise2.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | double height, radius; 9 | const double PI = 3.14159; 10 | 11 | cout << fixed << showpoint << setprecision(2); 12 | cout << "Enter the radius of the base of the cylinder: "; 13 | cin >> height; 14 | cout << endl; 15 | 16 | cout << "Enter the height of the cylinder: "; 17 | cin >> radius; 18 | cout << endl; 19 | 20 | cout << "Surface area: " 21 | << 2 * PI * radius * height + 2 * PI * pow(radius, 2.0) << endl; 22 | 23 | cout << "Volume of the cylinder = " << PI * pow(radius, 2.0)* height << endl; 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /Chapter 3/inData.txt: -------------------------------------------------------------------------------- 1 | 10.20 5.35 2 | 15.6 3 | Randy Gill 31 4 | 18500 3.5 5 | A -------------------------------------------------------------------------------- /Chapter 3/outData.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhoad/cpp_book/8fada5b4a2bb8df1af53b4c16088468daa64753e/Chapter 3/outData.txt -------------------------------------------------------------------------------- /Chapter 3/testdata.dat: -------------------------------------------------------------------------------- 1 | 38 26 * 67 33 2 | 24 $ 55 # 34 3 | # & 63 85 -------------------------------------------------------------------------------- /Chapter 4/a.bak: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhoad/cpp_book/8fada5b4a2bb8df1af53b4c16088468daa64753e/Chapter 4/a.bak -------------------------------------------------------------------------------- /Chapter 4/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhoad/cpp_book/8fada5b4a2bb8df1af53b4c16088468daa64753e/Chapter 4/a.out -------------------------------------------------------------------------------- /Chapter 4/exercise10.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 4 - Exercise 10 4 | markdhoad@gmail.com 5 | 6 | Redo Chapter 4 Exercise 9 to handle floating-point numbers. 7 | (Format your output to two decimal places.) 8 | *****************************************************************************/ 9 | 10 | 11 | #include 12 | #include 13 | 14 | using namespace std; 15 | int main() 16 | { 17 | float numerator, denominator; 18 | char operation; 19 | 20 | cout << "Enter your calculation: "; 21 | cin >> numerator >> operation >> denominator; 22 | 23 | cout << fixed << showpoint << setprecision(2); 24 | 25 | switch (operation) { 26 | case 'x': 27 | case '*': 28 | cout << numerator * denominator << endl; 29 | break; 30 | case '+': 31 | cout << numerator + denominator << endl; 32 | break; 33 | case '-': 34 | cout << numerator - denominator << endl; 35 | break; 36 | case '/': 37 | case '%': 38 | if (numerator == 0 || denominator == 0) { 39 | cout << "Cannot divide by zero" << endl; 40 | return 1; 41 | } 42 | cout << numerator / denominator << endl; 43 | break; 44 | default: 45 | cout << "There was an error with your input" << endl; 46 | return 1; 47 | break; 48 | } 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /Chapter 4/exercise12.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 4 - Exercise 12 4 | markdhoad@gmail.com 5 | 6 | A bank in your town updates its customers’ accounts at the end of each month. 7 | The bank offers two types of accounts: savings and checking. 8 | Every customer must maintain a minimum balance. If a customer’s balance falls below the 9 | minimum balance, there is a service charge of $10.00 for savings accounts and $25.00 for 10 | checking accounts. If the balance at the end of the month is at least the minimum balance, 11 | the account receives interest as follows: 12 | 13 | * Savings accounts receive 4% interest. 14 | * Checking accounts with balances of up to $5,000 more than the 15 | minimum balance receive 3% interest; otherwise, the interest is 5%. 16 | 17 | Write a program that reads a customer’s account number (int type), account type 18 | (char) s for savings, c for checking, minimum balance that the account should maintain, 19 | and current balance. The program should then output the account number, account type, 20 | current balance, and an appropriate message. 21 | 22 | Test your program by running it five times,using the following data: 23 | 24 | 46728 S 1000 2700 25 | 87324 C 1500 7689 26 | 79873 S 1000 800 27 | 89832 C 2000 3000 28 | 98322 C 1000 750 29 | *****************************************************************************/ 30 | 31 | 32 | #include 33 | #include 34 | 35 | using namespace std; 36 | int main() 37 | { 38 | int accountNumber; 39 | float minimumBalance, currentBalance; 40 | char accountType; 41 | 42 | const float SAVINGS_SERVICE_CHARGE = 10.00; 43 | const float CHECKING_SERVICE_CHARGE = 25.00; 44 | const float SAVINGS_INTEREST_RATE = 0.04; 45 | const float CHECKING_LOW_INTEREST_RATE = 0.03; 46 | const float CHECKING_DEFAULT_INTEREST_RATE = 0.05; 47 | 48 | cout << "Please enter the account details: "; 49 | cin >> accountNumber >> accountType >> minimumBalance >> currentBalance; 50 | 51 | switch (accountType) { 52 | case 's': 53 | case 'S': 54 | cout << "Account Number: " << accountNumber << endl; 55 | cout << fixed << showpoint << setprecision(2); 56 | cout << "Account Type: Savings" << endl; 57 | cout << "Minimum Balance: $" << minimumBalance << endl; 58 | cout << "Current Balance: $" << currentBalance << endl; 59 | 60 | if (currentBalance < minimumBalance) { 61 | cout << "Service Fee: $" << SAVINGS_SERVICE_CHARGE << endl; 62 | } else { 63 | cout << "Interest Earned: $" << currentBalance * SAVINGS_INTEREST_RATE 64 | << " at " << SAVINGS_INTEREST_RATE*100 << "% p.a" << endl; 65 | } 66 | break; 67 | case 'c': 68 | case 'C': 69 | cout << "Account Number: " << accountNumber << endl; 70 | cout << fixed << showpoint << setprecision(2); 71 | cout << "Account Type: Checking" << endl; 72 | cout << "Minimum Balance: $" << minimumBalance << endl; 73 | cout << "Current Balance: $" << currentBalance << endl; 74 | 75 | if (currentBalance < minimumBalance) { 76 | cout << "Service Fee: $" << CHECKING_SERVICE_CHARGE << endl; 77 | } else if (currentBalance <= (minimumBalance + 5000.00)) { 78 | cout << "Interest Earned: $" << currentBalance * CHECKING_LOW_INTEREST_RATE 79 | << " at " << CHECKING_LOW_INTEREST_RATE*100 << "% p.a" << endl; 80 | } else { 81 | cout << "Interest Earned: $" << currentBalance * CHECKING_DEFAULT_INTEREST_RATE 82 | << " at " << CHECKING_DEFAULT_INTEREST_RATE*100 << "% p.a" << endl; 83 | } 84 | break; 85 | default: 86 | cout << "There was an error with your input" << endl; 87 | return 1; 88 | break; 89 | } 90 | 91 | return 0; 92 | } -------------------------------------------------------------------------------- /Chapter 4/exercise15.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 4 - Exercise 15 4 | markdhoad@gmail.com 5 | 6 | Write a program that calculates and prints the bill for a cellular telephone company. 7 | The company offers two types of service: regular and premium. Its rates vary, depending 8 | on the type of service. The rates are computed as follows: 9 | 10 | Regular Service: $10.00 plus first 50 minutes are free. 11 | - Charges for over 50 minutes are $0.20 per minute. 12 | Premium service: $25.00 plus 13 | - For calls made from 6:00 a.m. to 6:00 p.m.,the first 75 minutes are free; 14 | charges for more than 75 minutes are $0.10 per minute. 15 | - For calls made from 6:00 p.m. to 6:00 a.m., the first 100 minutes are 16 | free; charges for more than 100 minutes are $0.05 per minute. 17 | 18 | Your program should prompt the user to enter an account number, a service code (type char), 19 | and the number of minutes the service was used. A service code of r or R means regular service; 20 | a service code of p or P means premium service. Treat any other character as an error. 21 | Your program should output the account number, type of service, number of minutes the 22 | telephone service was used, and the amount due from the user. 23 | 24 | For the premium service, the customer may be using the service during the day and the night. 25 | Therefore, to calculate the bill, you must ask the user to input the number of minutes the service 26 | was used during the day and the number of minutes the service was used during the night. 27 | *****************************************************************************/ 28 | 29 | 30 | #include 31 | #include 32 | 33 | using namespace std; 34 | int main() 35 | { 36 | int accountNumber, regularMinutesUsed, premiumDayMinutes, premiumNightMinutes; 37 | float totalBill = 0; 38 | char serviceCode; 39 | 40 | const float REGULAR_ACCOUNT_FEE = 10.00; 41 | const float REGULAR_RATE = 0.20; 42 | const float PREMIUM_ACCOUNT_FEE = 25.00; 43 | const float PREMIUM_DAY_RATE = 0.10; 44 | const float PREMIUM_NIGHT_RATE = 0.05; 45 | 46 | cout << "Please enter an account number and a service code: "; 47 | cin >> accountNumber >> serviceCode; 48 | 49 | switch (serviceCode) { 50 | case 'r': 51 | case 'R': 52 | cout << "Please enter the number of minutes used: "; 53 | cin >> regularMinutesUsed; 54 | if (regularMinutesUsed > 50) { 55 | totalBill = ((regularMinutesUsed - 50) * REGULAR_RATE) + REGULAR_ACCOUNT_FEE; 56 | } else { 57 | totalBill = REGULAR_ACCOUNT_FEE; 58 | } 59 | break; 60 | case 'p': 61 | case 'P': 62 | cout << "Please enter the number of day minutes used: "; 63 | cin >> premiumDayMinutes; 64 | cout << "Please enter the number of night minutes used: "; 65 | cin >> premiumNightMinutes; 66 | if (premiumDayMinutes > 75) { 67 | totalBill = (premiumDayMinutes - 75) * PREMIUM_DAY_RATE; 68 | } 69 | if (premiumNightMinutes > 100) { 70 | totalBill = (premiumNightMinutes - 100) * PREMIUM_NIGHT_RATE; 71 | } 72 | totalBill += PREMIUM_ACCOUNT_FEE; 73 | break; 74 | default: 75 | cout << "You have entered an invalid service code" << endl; 76 | return 1; 77 | break; 78 | } 79 | cout << "Your bill is: $" << totalBill << endl; 80 | 81 | return 0; 82 | } -------------------------------------------------------------------------------- /Chapter 4/exercise17.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 4 - Exercise 17 4 | markdhoad@gmail.com 5 | 6 | You have several pictures of different sizes that you would like to frame. 7 | A local picture-framing store offers two types of frames—regular and fancy. 8 | The frames are available in white and can be ordered in any color the customer desires. 9 | Suppose that each frame is 1 inch wide. The cost of coloring the frame is $0.10 per inch. 10 | The cost of a regular frame is $0.15 per inch, and the cost of a fancy frame is $0.25 per inch. 11 | The cost of putting a cardboard paper behind the picture is $0.02 per square inch, and the cost 12 | of putting glass on top of the picture is $0.07 per square inch. The customer can also choose to 13 | put crowns on the corners, which costs $0.35 per crown. 14 | 15 | Write a program that prompts the user to input the following information and then 16 | output the cost of framing the picture: 17 | 18 | a. The length and width, in inches, of the picture 19 | b. The type of the frame 20 | c. Customer’s choice of color to color the frame 21 | d. If the user wants to put the crowns, then the number of crowns 22 | *****************************************************************************/ 23 | 24 | 25 | #include 26 | #include 27 | #include 28 | 29 | using namespace std; 30 | int main() 31 | { 32 | int pictureLength, pictureWidth, pictureSquareInchSize, picturePerimiter, numberOfStars; 33 | char frameType; 34 | string frameColour; 35 | float totalPrice; 36 | 37 | //values below represent cost per inch 38 | const float FRAME_COLOURING_PRICE = 0.10; 39 | const float REGULAR_FRAME_PRICE = 0.15; 40 | const float FANCY_FRAME_PRICE = 0.25; 41 | 42 | //values below represent cost per square inch 43 | const float CARDBOARD_PRICE = 0.02; 44 | const float GLASS_PRICE = 0.07; 45 | 46 | const float STARS_PRICE = 0.35; 47 | 48 | cout << "Please enter the length & width of the picture: "; 49 | cin >> pictureLength >> pictureWidth; 50 | pictureSquareInchSize = pictureLength * pictureWidth; 51 | picturePerimiter = (pictureLength * 2) + (pictureWidth * 2); 52 | cout << "Please select your frame type (r for regular & f for fancy): "; 53 | cin >> frameType; 54 | 55 | // Calculate cost of the frame type 56 | switch (frameType) { 57 | case 'r': 58 | case 'R': 59 | totalPrice = picturePerimiter * REGULAR_FRAME_PRICE; 60 | break; 61 | case 'f': 62 | case 'F': 63 | totalPrice = picturePerimiter * FANCY_FRAME_PRICE; 64 | break; 65 | default: 66 | cout << "You entered an invalid fram type" << endl; 67 | return 1; 68 | break; 69 | } 70 | 71 | cout << "Please enter which colour frame you would like (Note: white is default): "; 72 | cin >> frameColour; 73 | 74 | // Only charge for colouring if they want something other than the default 75 | if (frameColour != "white" || frameColour != "") { 76 | totalPrice += FRAME_COLOURING_PRICE * picturePerimiter; 77 | } 78 | 79 | cout << "Please enter the total number of stars you wish to have on your frame: "; 80 | cin >> numberOfStars; 81 | 82 | if (numberOfStars > 0) { 83 | totalPrice += numberOfStars * STARS_PRICE; 84 | } 85 | 86 | //Calculate costs for glass and cardboard dependent on picture size 87 | totalPrice += (GLASS_PRICE * pictureSquareInchSize) + (CARDBOARD_PRICE * pictureSquareInchSize); 88 | 89 | cout << fixed << showpoint << setprecision(2); 90 | cout << "Your total bill for your frame comes to: $" << totalPrice << endl; 91 | 92 | return 0; 93 | } -------------------------------------------------------------------------------- /Chapter 4/exercise7.cpp: -------------------------------------------------------------------------------- 1 | // C++ Programming - From Problem Analysis to Program Design 5th Edition 2 | // Chapter 4 - Exercise 7 3 | // markdhoad@gmail.com 4 | 5 | #include 6 | 7 | int main() 8 | { 9 | const int COOKIES_PER_BOX = 24; 10 | const int BOXES_PER_CONTAINER = 75; 11 | int numberOfCookies, boxesRequired, containersRequired; 12 | 13 | std::cout << "Enter the total number of cookies: "; 14 | std::cin >> numberOfCookies; 15 | 16 | boxesRequired = numberOfCookies / COOKIES_PER_BOX; 17 | containersRequired = numberOfCookies / (COOKIES_PER_BOX * BOXES_PER_CONTAINER); 18 | 19 | std::cout << "That will require " << boxesRequired << " boxes and " << containersRequired+1 << " containers" << std::endl; 20 | std::cout << "There are also " << numberOfCookies % COOKIES_PER_BOX << " cookies left over" << std::endl; 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /Chapter 4/exercise9.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 4 - Exercise 9 4 | markdhoad@gmail.com 5 | 6 | Write a program that mimics a calculator. The program should take as input two integers and the 7 | operation to be performed. It should then output the numbers, the operator, and the result. 8 | (For division, if the denominator is zero, output an appropriate message.) 9 | Some sample outputs follow: 10 | 3+4=7 13 *5=65 11 | *****************************************************************************/ 12 | 13 | 14 | #include 15 | 16 | using namespace std; 17 | int main() 18 | { 19 | int numerator, denominator; 20 | char operation; 21 | 22 | cout << "Enter your calculation: "; 23 | cin >> numerator >> operation >> denominator; 24 | 25 | switch (operation) { 26 | case 'x': 27 | case '*': 28 | cout << numerator * denominator << endl; 29 | break; 30 | case '+': 31 | cout << numerator + denominator << endl; 32 | break; 33 | case '-': 34 | cout << numerator - denominator << endl; 35 | break; 36 | case '/': 37 | case '%': 38 | if (numerator == 0 || denominator == 0) { 39 | cout << "Cannot divide by zero" << endl; 40 | return 1; 41 | } 42 | cout << numerator / denominator << endl; 43 | break; 44 | default: 45 | cout << "There was an error with your input" << endl; 46 | return 1; 47 | break; 48 | } 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /Chapter 5/exercise1.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 5 - Exercise 1 4 | markdhoad@gmail.com 5 | 6 | Write a program that prompts the user to input an integer and then outputs both the individual 7 | digits of the number and the sum of the digits. For example, it should output the individual 8 | digits of 3456 as 3 4 5 6, output the individual digits of 8030 as 8 0 3 0, output the individual 9 | digits of 2345526 as 2 3 4 5 5 2 6, output the individual digits of 4000 as 4 0 0 0, and 10 | output the individual digits of -2345 as 2 3 4 5. 11 | *****************************************************************************/ 12 | 13 | 14 | #include 15 | #include 16 | 17 | using namespace std; 18 | 19 | int main() 20 | { 21 | int inputNumber, sum, individualNumber; 22 | cin >> inputNumber; 23 | 24 | inputNumber = abs(inputNumber); //Handle negative numbers 25 | sum = 0; 26 | 27 | do { 28 | individualNumber = inputNumber % 10; //Extract the last digit of the number 29 | sum += individualNumber; 30 | inputNumber = inputNumber / 10; //Remove the last digit 31 | } while (inputNumber > 0); 32 | 33 | cout << "The sum of the individual numbers is: " << sum << endl; 34 | 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /Chapter 5/exercise3.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 5 - Exercise 3 4 | markdhoad@gmail.com 5 | 6 | Rewrite the program of Example 5-5, Telephone Digits. Replace the statements from 7 | Line 10 to Line 28 so that the program uses only a switch structure to find the 8 | digit that corresponds to an uppercase letter. 9 | *****************************************************************************/ 10 | 11 | 12 | #include 13 | 14 | using namespace std; 15 | 16 | int main() 17 | { 18 | char letter; 19 | 20 | cout << "Program to convert letters to their corresponding telephone digits" << endl; 21 | cout << "To stop the program press #" << endl; 22 | 23 | cout << "Enter a letter: " ; 24 | cin >> letter; 25 | 26 | while (letter != '#' && letter >= 'A' && letter <= 'Z') { 27 | cout << "The letter you entered is: " << letter << endl; 28 | cout << "The corresponding telephone digit is: "; 29 | 30 | 31 | switch (letter) { 32 | case 'A': 33 | case 'B': 34 | case 'C': 35 | cout << "2" << endl; 36 | break; 37 | case 'D': 38 | case 'E': 39 | case 'F': 40 | cout << "3" << endl; 41 | break; 42 | case 'G': 43 | case 'H': 44 | case 'I': 45 | cout << "4" << endl; 46 | break; 47 | case 'J': 48 | case 'K': 49 | case 'L': 50 | cout << "5" << endl; 51 | break; 52 | case 'M': 53 | case 'N': 54 | case 'O': 55 | cout << "6" << endl; 56 | break; 57 | case 'P': 58 | case 'Q': 59 | case 'R': 60 | case 'S': 61 | cout << "7" << endl; 62 | break; 63 | case 'T': 64 | case 'U': 65 | case 'V': 66 | cout << "8" << endl; 67 | break; 68 | case 'W': 69 | case 'X': 70 | case 'Y': 71 | case 'Z': 72 | cout << "9" << endl; 73 | break; 74 | default: 75 | break; 76 | } 77 | 78 | cout << "Enter another letter to find out the number: "; 79 | cin >> letter; 80 | } 81 | return 0; 82 | } -------------------------------------------------------------------------------- /Chapter 5/exercise4.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 5 - Exercise 4 4 | markdhoad@gmail.com 5 | 6 | The program Telephone Digits outputs only telephone digits that correspond to 7 | uppercase letters. Rewrite the program so that it processes both uppercase and 8 | lowercase letters and outputs the corresponding telephone digit. 9 | If the input is something other than an uppercase or lowercase letter, 10 | the program must output an appropriate error message. 11 | *****************************************************************************/ 12 | 13 | 14 | #include 15 | 16 | using namespace std; 17 | 18 | int main() 19 | { 20 | char letter; 21 | 22 | cout << "Program to convert letters to their corresponding telephone digits" << endl; 23 | cout << "To stop the program press #" << endl; 24 | 25 | cout << "Enter a letter: " ; 26 | cin >> letter; 27 | 28 | 29 | while (letter != '#' && letter >= 'A' && letter <= 'z') { 30 | cout << "The letter you entered is: " << letter << endl; 31 | cout << "The corresponding telephone digit is: "; 32 | 33 | if (letter > 'Z') { 34 | letter = (int)letter-32; // Convert lowercase to uppercase if required. 35 | } 36 | 37 | switch (letter) { 38 | case 'A': 39 | case 'B': 40 | case 'C': 41 | cout << "2" << endl; 42 | break; 43 | case 'D': 44 | case 'E': 45 | case 'F': 46 | cout << "3" << endl; 47 | break; 48 | case 'G': 49 | case 'H': 50 | case 'I': 51 | cout << "4" << endl; 52 | break; 53 | case 'J': 54 | case 'K': 55 | case 'L': 56 | cout << "5" << endl; 57 | break; 58 | case 'M': 59 | case 'N': 60 | case 'O': 61 | cout << "6" << endl; 62 | break; 63 | case 'P': 64 | case 'Q': 65 | case 'R': 66 | case 'S': 67 | cout << "7" << endl; 68 | break; 69 | case 'T': 70 | case 'U': 71 | case 'V': 72 | cout << "8" << endl; 73 | break; 74 | case 'W': 75 | case 'X': 76 | case 'Y': 77 | case 'Z': 78 | cout << "9" << endl; 79 | break; 80 | default: 81 | break; 82 | } 83 | 84 | cout << "Enter another letter to find out the number: "; 85 | cin >> letter; 86 | } 87 | return 0; 88 | } -------------------------------------------------------------------------------- /Chapter 5/exercise5.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 5 - Exercise 5 4 | markdhoad@gmail.com 5 | 6 | To make telephone numbers easier to remember, some companies use letters to show their 7 | telephone number. For example, using letters, the telephone number 438-5626 can be shown as 8 | GET LOAN. In some cases, to make a telephone number meaningful, companies might use more 9 | than seven letters. For example, 225-5466 can be displayed as CALL HOME, which uses eight 10 | letters. Write a program that prompts the user to enter a telephone number expressed in 11 | letters and outputs the corresponding telephone number in digits. 12 | 13 | If the user enters more than seven letters, then process only the first seven letters. 14 | Also output the – (hyphen) after the third digit. Allow the user to use both uppercase 15 | and lowercase letters as well as spaces between words. 16 | *****************************************************************************/ 17 | 18 | 19 | #include 20 | 21 | using namespace std; 22 | 23 | int main() 24 | { 25 | char letter; 26 | int counter = 0; 27 | 28 | cout << "Program to convert letters to their corresponding telephone digits" << endl; 29 | 30 | while (cin.get(letter) && counter < 7 ) { 31 | 32 | if (letter != ' ' && letter >= 'A' && letter <= 'z') { 33 | counter++; // Only increment the counter for valid characters 34 | if (letter > 'Z') { 35 | letter = (int)letter-32; // Convert lowercase to uppercase if required. 36 | } 37 | 38 | if (counter == 4) { 39 | cout << "-"; // Print the hyphen when required 40 | } 41 | 42 | switch (letter) { 43 | case 'A': 44 | case 'B': 45 | case 'C': 46 | cout << "2"; 47 | break; 48 | case 'D': 49 | case 'E': 50 | case 'F': 51 | cout << "3"; 52 | break; 53 | case 'G': 54 | case 'H': 55 | case 'I': 56 | cout << "4"; 57 | break; 58 | case 'J': 59 | case 'K': 60 | case 'L': 61 | cout << "5"; 62 | break; 63 | case 'M': 64 | case 'N': 65 | case 'O': 66 | cout << "6"; 67 | break; 68 | case 'P': 69 | case 'Q': 70 | case 'R': 71 | case 'S': 72 | cout << "7"; 73 | break; 74 | case 'T': 75 | case 'U': 76 | case 'V': 77 | cout << "8"; 78 | break; 79 | case 'W': 80 | case 'X': 81 | case 'Y': 82 | case 'Z': 83 | cout << "9"; 84 | break; 85 | default: 86 | break; 87 | } 88 | } 89 | 90 | } 91 | return 0; 92 | } -------------------------------------------------------------------------------- /Chapter 5/exercise6.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 5 - Exercise 6 4 | markdhoad@gmail.com 5 | 6 | Write a program that reads a set of integers and then finds and prints the 7 | sum of the even and odd integers. 8 | 9 | Note: I haven't bothered to do any error or input checking 10 | *****************************************************************************/ 11 | 12 | 13 | #include 14 | 15 | using namespace std; 16 | 17 | int main() 18 | { 19 | int numberOfNumbers, totalOddNumbers, totalEvenNumbers, sumOfNumbers, currentNumber; 20 | 21 | totalEvenNumbers = 0; totalOddNumbers = 0; sumOfNumbers = 0; //initilise required variables 22 | 23 | cout << "How many numbers will you be entering: "; 24 | cin >> numberOfNumbers; 25 | 26 | for (int i = 0; i <= numberOfNumbers-1; i++) { 27 | cin >> currentNumber; 28 | if (currentNumber % 2 == 0) { 29 | totalEvenNumbers += 1; 30 | sumOfNumbers += currentNumber; 31 | } else { 32 | totalOddNumbers += 1; 33 | sumOfNumbers += currentNumber; 34 | } 35 | } 36 | 37 | cout << "The sum of the " << numberOfNumbers << " numbers is: " << sumOfNumbers << endl; 38 | cout << "There were " << totalOddNumbers << " odd numbers and " << totalEvenNumbers << " even numbers" << endl; 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /Chapter 6/exercise1.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 6 - Exercise 1 4 | markdhoad@gmail.com 5 | 6 | Write a program that uses the function isNumPalindrome given in Example 6-5 (Palindrome Number). 7 | Test your program on the following numbers: 10, 34, 22, 333, 678, 67876, 44444, and 123454321. 8 | *****************************************************************************/ 9 | 10 | 11 | #include 12 | #include 13 | 14 | using namespace std; 15 | 16 | bool isNumPalindrome(int num); 17 | 18 | int main() 19 | { 20 | cout << "The following lines indicate if a number is a palindrome or not where 0 = false and 1 = true" << endl; 21 | cout << "Is 10 a palindrome? : " << isNumPalindrome(10) << endl; 22 | cout << "Is 34 a palindrome? : " << isNumPalindrome(34) << endl; 23 | cout << "Is 22 a palindrome? : " << isNumPalindrome(22) << endl; 24 | cout << "Is 333 a palindrome? : " << isNumPalindrome(333) << endl; 25 | cout << "Is 678 a palindrome? : " << isNumPalindrome(678) << endl; 26 | cout << "Is 67876 a palindrome? : " << isNumPalindrome(67876) << endl; 27 | cout << "Is 44444 a palindrome? : " << isNumPalindrome(44444) << endl; 28 | cout << "Is 123454321 a palindrome? : " << isNumPalindrome(123454321) << endl; 29 | 30 | 31 | return 0; 32 | } 33 | 34 | bool isNumPalindrome(int num) { 35 | int pwr = 0; 36 | if (num < 10) return true; 37 | else { 38 | while (num / static_cast(pow(10.0, pwr)) >= 10) pwr++; 39 | while (num >= 10) 40 | { 41 | int tenTopwr = static_cast(pow(10.0, pwr)); 42 | if ((num / tenTopwr) != (num % 10)) 43 | return false; 44 | else { 45 | num = num % tenTopwr; 46 | num = num / 10; 47 | pwr = pwr - 2; 48 | } 49 | } 50 | return true; 51 | } 52 | } -------------------------------------------------------------------------------- /Chapter 6/exercise10.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 6 - Exercise 10 4 | markdhoad@gmail.com 5 | 6 | Write a program that takes as input five numbers and outputs the mean (average) 7 | and standard deviation of the numbers. 8 | *****************************************************************************/ 9 | 10 | 11 | #include 12 | #include 13 | 14 | using namespace std; 15 | 16 | double mean(int num1, int num2, int num3, int num4, int num5); 17 | double stddev(int num1, int num2, int num3, int num4, int num5); 18 | 19 | int main() 20 | { 21 | int num1, num2, num3, num4, num5; 22 | 23 | cout << "Please enter 5 numbers seperated by spaces: "; 24 | cin >> num1 >> num2 >> num3 >> num4 >> num5; 25 | cout << "The average is: " << mean(num1, num2, num3, num4, num5) << endl; 26 | cout << "The standard deviation is: " << stddev(num1, num2, num3, num4, num5) << endl; 27 | return 0; 28 | } 29 | 30 | double mean(int num1, int num2, int num3, int num4, int num5) { 31 | return ((num1 + num2 + num3 + num4 + num5)/5); 32 | } 33 | 34 | double stddev(int num1, int num2, int num3, int num4, int num5) { 35 | double average = mean(num1, num2, num3, num4, num5); 36 | double numerator = (pow(num1 - average, 2) + pow(num2 - average, 2) + pow(num3 - average, 2) + pow(num4 - average, 2) + pow(num5 - average, 2)); 37 | return sqrt(numerator/5); 38 | } -------------------------------------------------------------------------------- /Chapter 6/exercise12.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 6 - Exercise 12 4 | markdhoad@gmail.com 5 | 6 | During the tax season, every Friday, J&J accounting firm provides assistance to 7 | people who prepare their own tax returns. 8 | Their charges are as follows. 9 | 10 | a. If a person has low income (<= 25,000) and the consulting time is less 11 | than or equal to 30 minutes, there are no charges; otherwise, the service 12 | charges are 40% of the regular hourly rate for the time over 30 minutes. 13 | b. For others, if the consulting time is less than or equal to 20 minutes, 14 | there are no service charges; otherwise, service charges are 70% of the regular 15 | hourly rate for the time over 20 minutes. 16 | 17 | For example, suppose that a person has low income and spent 1 hour and 15 minutes, 18 | and the hourly rate is $70.00. Then the billing amount is 70.00 * 0.40 * (45 / 60) = $21.00. 19 | 20 | Write a program that prompts the user to enter the hourly rate, the total consulting time, 21 | and whether the person has low income. 22 | 23 | The program should output the billing amount. Your program must contain a function that 24 | takes as input the hourly rate, the total consulting time, and a value indicating whether 25 | the person has low income. The function should return the billing amount. 26 | 27 | Your program may prompt the user to enter the consulting time in minutes. 28 | *****************************************************************************/ 29 | 30 | 31 | #include 32 | #include 33 | 34 | using namespace std; 35 | 36 | double calculateBill(int income, int consultingMinutes, double hourlyRate); 37 | 38 | int main() 39 | { 40 | int income, consultingMinutes; 41 | double hourlyRate; 42 | 43 | cout << "Please enter the clients income: $" ; 44 | cin >> income; 45 | cout << "Please enter the consulting time in minutes: "; 46 | cin >> consultingMinutes; 47 | cout << "Please enter the hourly rate: $"; 48 | cin >> hourlyRate; 49 | cout << fixed << showpoint << setprecision(2); 50 | cout << "Your total bill ammount comes to: $" << calculateBill(income, consultingMinutes, hourlyRate) << endl; 51 | return 0; 52 | } 53 | 54 | double calculateBill(int income, int consultingMinutes, double hourlyRate){ 55 | if (income <= 25000) { 56 | if (consultingMinutes <= 30) 57 | return 0; 58 | else 59 | return hourlyRate * 0.40 * ((consultingMinutes - 30) / 60); 60 | } 61 | else { 62 | if (consultingMinutes <= 20) 63 | return 0; 64 | else 65 | return hourlyRate * 0.70 * ((consultingMinutes - 20) / 60); 66 | 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Chapter 6/exercise2.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 6 - Exercise 2 4 | markdhoad@gmail.com 5 | 6 | Write a value-returning function, isVowel, that returns the value true if a 7 | given character is a vowel and otherwise returns false. 8 | *****************************************************************************/ 9 | 10 | 11 | #include 12 | 13 | using namespace std; 14 | 15 | bool isVowel(char letter); 16 | 17 | int main() 18 | { 19 | char userChar; 20 | 21 | cout << "Please enter a character: "; 22 | cin >> userChar; 23 | 24 | if (isVowel(userChar)) 25 | cout << userChar << " is a vowel" << endl; 26 | else 27 | cout << userChar << " is not a vowel" << endl; 28 | 29 | return 0; 30 | } 31 | 32 | bool isVowel(char letter) { 33 | switch (letter) { 34 | case 'a': 35 | case 'e': 36 | case 'i': 37 | case 'o': 38 | case 'u': 39 | return true; 40 | default: 41 | return false; 42 | } 43 | } -------------------------------------------------------------------------------- /Chapter 6/exercise3.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 6 - Exercise 3 4 | markdhoad@gmail.com 5 | 6 | Write a program that prompts the user to input a sequence of characters 7 | and outputs the number of vowels. 8 | *****************************************************************************/ 9 | 10 | 11 | #include 12 | 13 | using namespace std; 14 | 15 | bool isVowel(char letter); 16 | 17 | int main() 18 | { 19 | char userChar; 20 | int vowelCount = 0; 21 | int charCount = 0; 22 | 23 | 24 | cout << "This program will check the letters you input to check for vowels." << endl; 25 | cout << "To terminate the program simply enter the '#' symbol " << endl; 26 | 27 | do { 28 | cout << "Please enter a character: "; 29 | cin >> userChar; 30 | charCount++; 31 | if (isVowel(userChar)) 32 | vowelCount++; 33 | } while (userChar != '#'); 34 | 35 | cout << "Of the " << charCount << " characters you entered " << vowelCount << " were vowels." << endl; 36 | 37 | return 0; 38 | } 39 | 40 | bool isVowel(char letter) { 41 | switch (letter) { 42 | case 'a': 43 | case 'e': 44 | case 'i': 45 | case 'o': 46 | case 'u': 47 | return true; 48 | default: 49 | return false; 50 | } 51 | } -------------------------------------------------------------------------------- /Chapter 6/exercise4.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 3rd Edition 3 | Chapter 6 - Exercise 4 4 | markdhoad@gmail.com 5 | 6 | Write the definition of function one so that it returns the sum of x and y if 7 | x is greater than y; otherwise it should return x minus 2 times y. 8 | 9 | Write the definition of function two as follows: 10 | 1) Read a number and store it in z 11 | 2) Update the value of z by adding the value of a to its previous value 12 | 3) Assign the variable first the value returned by function one with params 6 & 8 13 | 4) Update the value of first by adding the value of x to its previous value 14 | 5) If the value of z is more than twice the value of first return z; otherwise 15 | return 2 times first minus z 16 | 17 | Write a program that tests the above. Declare extra variables if needed. 18 | *****************************************************************************/ 19 | 20 | #include 21 | 22 | using namespace std; 23 | 24 | int one(int x, int y); 25 | double two(int x, double a); 26 | 27 | int main() 28 | { 29 | int num; 30 | double dec; 31 | 32 | num = one(5, 6); 33 | dec = two(6, 3.4); 34 | 35 | cout << "The num variable = " << num << endl; 36 | cout << "The dec variable = " << dec << endl; 37 | 38 | 39 | return 0; 40 | } 41 | 42 | int one(int x, int y) 43 | { 44 | if (x > y) 45 | return x+y; 46 | else 47 | return (x-2)*y; 48 | } 49 | 50 | double two(int x, double a) 51 | { 52 | int first; 53 | double z; 54 | 55 | cout << "Enter a number: "; 56 | cin >> z; 57 | 58 | z += a; 59 | first = one(6,8); 60 | first += x; 61 | 62 | if (z > (2 * first)) 63 | return z; 64 | else 65 | return 2*first - z; 66 | } -------------------------------------------------------------------------------- /Chapter 6/exercise5.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 3rd Edition 3 | Chapter 6 - Exercise 5 4 | markdhoad@gmail.com 5 | 6 | Write a function reverseDigit, that takes an integer as a parameter and returns 7 | the number with its digits reversed. For example the value of reverseDigit(5600) 8 | is 65, the value of reverseDigit(7008) is 8007; and the value of 9 | reverseDigit(-532) is -235 10 | *****************************************************************************/ 11 | 12 | #include 13 | 14 | using namespace std; 15 | 16 | int reverseDigit(int x); 17 | 18 | int main() 19 | { 20 | cout << "5600 = " << reverseDigit(5600) << endl; 21 | cout << "7008 = " << reverseDigit(7008) << endl; 22 | cout << "-532 = " << reverseDigit(-532) << endl; 23 | return 0; 24 | } 25 | 26 | int reverseDigit(int x) 27 | { 28 | // Algorithm adapted from 29 | // https://www.programiz.com/cpp-programming/examples/reverse-number 30 | int remainder, reversedNumber = 0; 31 | while(x != 0) 32 | { 33 | remainder = x%10; 34 | reversedNumber = reversedNumber*10 + remainder; 35 | x /= 10; 36 | } 37 | 38 | return reversedNumber; 39 | } -------------------------------------------------------------------------------- /Chapter 7/exercise1.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 7 - Exercise 1 4 | markdhoad@gmail.com 5 | 6 | a) Write the definition of the function initialize that initializes x and y 7 | to 0 and z to the blank character. 8 | 9 | b) Write the definition of the function getHoursRate that prompts the user to 10 | input the hours worked and rate per hour to initialize the variables hours and 11 | rate of the function main. 12 | 13 | c) Write the definition of the value-returning function payCheck that calculates 14 | and returns the amount to be paid to an employee based on the hours worked and 15 | rate per hour. The hours worked and rate per hour are stored in the variables hours 16 | and rate, respectively, of the function main. The formula for calculating the amount 17 | to be paid is as follows: For the first 40 hours, the rate is the given rate; for 18 | hours over 40, the rate is 1.5 times the given rate. 19 | 20 | d) Write the definition of the function printCheck that prints the hours worked, 21 | rate per hour, and the salary. 22 | 23 | e) Write the definition of the function funcOne that prompts the user to input a number. 24 | The function then changes the value of x by assigning the value of the expression 2 25 | times the (old) value of x plus the value of y minus the value entered by the user. 26 | 27 | f) Write the definition of the function nextChar that sets the value of z to the 28 | next character stored in z. 29 | 30 | g) Write the definition of a function main that tests each of these functions. 31 | *****************************************************************************/ 32 | 33 | 34 | #include 35 | #include 36 | 37 | using namespace std; 38 | 39 | void initialise(int& x, int& y, char& z); 40 | void getHoursRate(double& rate, double& hours); 41 | double payCheck(double rate, double hours); 42 | void printCheck(double rate, double hours, double amount); 43 | void funcOne(int& x, int y); 44 | void nextChar(char& z); 45 | 46 | int main() 47 | { 48 | int x, y; 49 | char z; 50 | double rate, hours; 51 | double amount; 52 | 53 | initialise(x, y, z); 54 | getHoursRate(rate, hours); 55 | amount = payCheck(rate, hours); 56 | printCheck(rate, hours, amount); 57 | cout << "The value of x is currently: " << x << endl; 58 | funcOne(x, y); 59 | cout << "The value of x is now: " << x << endl; 60 | nextChar(z); 61 | cout << "The value of z is now: " << z << endl; 62 | 63 | return 0; 64 | } 65 | 66 | void initialise(int& x, int& y, char& z) { 67 | x = 0; 68 | y = 0; 69 | z = ' '; 70 | } 71 | 72 | void getHoursRate(double& rate, double& hours) { 73 | cout << "Please enter the hourly rate: "; 74 | cin >> rate; 75 | cout << "Please enter the hours worked: "; 76 | cin >> hours; 77 | } 78 | 79 | double payCheck(double rate, double hours) { 80 | double amount = 0; 81 | 82 | if (hours > 40) { 83 | amount += ((hours - 40) * rate) * 1.5; 84 | amount += 40 * rate; 85 | return amount; 86 | } else { 87 | amount = hours * rate; 88 | return amount; 89 | } 90 | } 91 | 92 | void printCheck(double rate, double hours, double amount) { 93 | cout << "For working " << hours << " hours at $" << rate << "/hr you get a total of $"; 94 | cout << fixed << showpoint << setprecision(2); 95 | cout << amount << endl; 96 | } 97 | 98 | void funcOne(int& x, int y) { 99 | int tempNum; 100 | cout << "Please enter a number: "; 101 | cin >> tempNum; 102 | 103 | x = (x * 2) + y - tempNum; 104 | } 105 | 106 | void nextChar(char& z) { 107 | z++; 108 | } -------------------------------------------------------------------------------- /Chapter 7/exercise6.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 7 - Exercise 6 4 | markdhoad@gmail.com 5 | 6 | For research purposes and to better help students, the admissions office of your 7 | local university wants to know how well female and male students perform in certain 8 | courses. You receive a file that contains female and male student UAIs for certain 9 | courses. Due to confidentiality, the letter code f is used for female students 10 | and m for male students. Every file entry consists of a letter code followed by a UAI. 11 | Each line has one entry. The number of entries in the file is unknown. 12 | Write a program that computes and outputs the average UAI for both female and male students. 13 | Format your results to two decimal places. Your program should use the following functions: 14 | 15 | a. Function openFiles: This function opens the input and output files, and sets the output 16 | of the floating-point numbers to two decimal places in a fixed decimal format with a 17 | decimal point and trailing zeros. 18 | b. Function initialize: This function initializes variables such as countFemale, 19 | countMale, sumFemaleUAI, and sumMaleUAI. 20 | c. Function sumGrades: This function finds the sum of the female and male students’ UAIs. 21 | d. Function averageGrade: This function finds the average UAI for female and male students. 22 | e. Function printResults: This function outputs the relevant results. 23 | f. There can be no global variables. Use the appropriate parameters to pass 24 | information in and out of functions. 25 | *****************************************************************************/ 26 | 27 | 28 | #include 29 | #include 30 | #include 31 | 32 | using namespace std; 33 | 34 | void openFiles(ifstream& inData, ofstream& outData); 35 | void initialise(int& countFemale, int& countMale, double& sumFemaleUAI, double& sumMaleUAI); 36 | void sumGrades(ifstream& inData, int& countFemale, int& countMale, double& sumFemaleUAI, double& sumMaleUAI); 37 | void averageGrade(int countMale, int countFemale, double sumFemaleUAI, double sumMaleUAI, double& avgMaleUAI, double& avgFemaleUAI); 38 | void printResults(double avgMaleUAI, double avgFemaleUAI, ofstream& outData); 39 | 40 | int main() 41 | { 42 | // Declare all relevant variables 43 | ifstream inData; 44 | ofstream outData; 45 | int countFemale, countMale; 46 | double sumFemaleUAI, sumMaleUAI, avgMaleUAI, avgFemaleUAI; 47 | 48 | openFiles(inData, outData); 49 | initialise(countFemale, countMale, sumFemaleUAI, sumMaleUAI); 50 | sumGrades(inData, countFemale, countMale, sumFemaleUAI, sumMaleUAI); 51 | cout << "There are " << countMale << " males and " << countFemale << " females." << endl; 52 | averageGrade(countMale, countFemale, sumFemaleUAI, sumMaleUAI, avgMaleUAI, avgFemaleUAI); 53 | cout << fixed << showpoint << setprecision(2); 54 | cout << "The average male UAI is: " << avgMaleUAI << " and the average female UAI is: " << avgFemaleUAI << endl; 55 | printResults(avgMaleUAI, avgFemaleUAI, outData); 56 | return 0; 57 | } 58 | 59 | void printResults(double avgMaleUAI, double avgFemaleUAI, ofstream& outData) { 60 | outData << "Average male UAI: " << avgMaleUAI << endl; 61 | outData << "Average female UAI: " << avgFemaleUAI << endl; 62 | } 63 | 64 | void averageGrade(int countMale, int countFemale, double sumFemaleUAI, double sumMaleUAI, double& avgMaleUAI, double& avgFemaleUAI) { 65 | avgFemaleUAI = sumFemaleUAI / countFemale; 66 | avgMaleUAI = sumMaleUAI / countMale; 67 | } 68 | 69 | void sumGrades(ifstream& inData, int& countFemale, int& countMale, double& sumFemaleUAI, double& sumMaleUAI) { 70 | char gender; 71 | double uaiScore; 72 | while (!inData.eof()) { 73 | inData >> gender >> uaiScore; 74 | switch (gender) { 75 | case 'm': 76 | countMale += 1; 77 | sumMaleUAI += uaiScore; 78 | break; 79 | case 'f': 80 | countFemale += 1; 81 | sumFemaleUAI += uaiScore; 82 | default: 83 | break; 84 | } 85 | } 86 | } 87 | 88 | void initialise(int& countFemale, int& countMale, double& sumFemaleUAI, double& sumMaleUAI) { 89 | countFemale = 0; 90 | countMale = 0; 91 | sumFemaleUAI = 0.00; 92 | sumMaleUAI = 0.00; 93 | } 94 | 95 | void openFiles(ifstream& inData, ofstream& outData) { 96 | // Open both the input and output data files. 97 | // If there is an error with either, exit the program with the appropriate message. 98 | 99 | inData.open("/Users/mark/Code/cpp/Malik Book/Chapter 7/uaidata.txt"); 100 | if (!inData){ 101 | cout << "There was an error opening the input file" << endl; 102 | exit(1); 103 | } 104 | outData.open("/Users/mark/Code/cpp/Malik Book/Chapter 7/uaiout.txt"); 105 | if (!outData) { 106 | cout << "There was an error writing to the output file" << endl; 107 | exit(1); 108 | } else { 109 | outData << fixed << showpoint << setprecision(2); 110 | } 111 | } 112 | 113 | -------------------------------------------------------------------------------- /Chapter 7/exercise8.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 7 - Exercise 8 4 | markdhoad@gmail.com 5 | 6 | Write a progam that reads a string and outputs the number of times each lowercase 7 | vowel appears in it. Your program must contain a function with one of its parameters 8 | as a string variable, and return the number of times each lowercase vowel appears in it. 9 | Also write a program to test your function. (Note that if str is a variable of type 10 | string, then str.at(i) returns the character at the ith position. The position of 11 | the first character is 0. Also, str.length() returns the length of the str, that is, 12 | the number of characters in str.) 13 | *****************************************************************************/ 14 | 15 | 16 | #include 17 | #include 18 | 19 | using namespace std; 20 | 21 | void countVowels(string userString); 22 | 23 | int main() 24 | { 25 | string userString; 26 | cout << "Please enter a string: "; 27 | getline(cin,userString,'\n'); 28 | countVowels(userString); 29 | 30 | return 0; 31 | } 32 | 33 | void countVowels(string userString){ 34 | char currentChar; 35 | int a = 0, e = 0, i = 0, o = 0, u = 0; //variables to hold the number of instances of each vowel 36 | 37 | for (int x = 0; x < userString.length(); x++) { 38 | currentChar = userString.at(x); 39 | switch (currentChar) { 40 | case 'a': 41 | a += 1; 42 | break; 43 | case 'e': 44 | e += 1; 45 | break; 46 | case 'i': 47 | i += 1; 48 | break; 49 | case 'o': 50 | o += 1; 51 | break; 52 | case 'u': 53 | u += 1; 54 | break; 55 | default: 56 | break; 57 | } 58 | } 59 | cout << "Out of the " << userString.length() << " characters you entered." << endl; 60 | cout << a << " were the letter a" << endl; 61 | cout << e << " were the letter e" << endl; 62 | cout << i << " were the letter i" << endl; 63 | cout << o << " were the letter o" << endl; 64 | cout << u << " were the letter u" << endl; 65 | } 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /Chapter 7/genUAIData.rb: -------------------------------------------------------------------------------- 1 | # A short ruby script to generate the data file required for Chapter 7 Exercise 6. 2 | # As I am not American I have no idea how GPA scores work and replaced it with our local version here in Australia 3 | 4 | File.open("uaidata.txt", 'w') do |file| 5 | rand(50..100).times do 6 | file.write("#{["m", "f"].sample} #{rand(35.00..99.99).round(2)} \n") 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /Chapter 7/uaidata.txt: -------------------------------------------------------------------------------- 1 | m 99.83 2 | f 84.87 3 | m 59.68 4 | m 65.85 5 | m 73.09 6 | m 81.29 7 | m 96.38 8 | m 96.89 9 | m 49.44 10 | f 49.97 11 | f 39.34 12 | m 92.0 13 | f 47.26 14 | f 59.46 15 | f 36.49 16 | f 55.47 17 | m 85.07 18 | f 69.67 19 | m 92.37 20 | f 66.73 21 | m 76.94 22 | m 76.44 23 | m 74.33 24 | f 88.98 25 | m 74.19 26 | f 84.6 27 | f 57.23 28 | m 73.23 29 | f 54.4 30 | m 99.82 31 | m 74.03 32 | m 68.58 33 | m 96.16 34 | f 72.59 35 | f 61.38 36 | m 65.85 37 | f 73.99 38 | f 96.14 39 | m 45.28 40 | m 74.4 41 | f 84.14 42 | m 67.06 43 | m 49.72 44 | m 57.07 45 | m 91.28 46 | m 36.23 47 | f 39.19 48 | m 69.62 49 | f 98.96 50 | m 39.16 51 | f 99.56 52 | m 81.1 53 | m 98.95 54 | m 68.49 55 | f 36.13 56 | f 72.53 57 | m 66.11 58 | -------------------------------------------------------------------------------- /Chapter 7/uaiout.txt: -------------------------------------------------------------------------------- 1 | Average male UAI: 73.77 2 | Average female UAI: 66.48 3 | -------------------------------------------------------------------------------- /Chapter 9/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhoad/cpp_book/8fada5b4a2bb8df1af53b4c16088468daa64753e/Chapter 9/a.out -------------------------------------------------------------------------------- /Chapter 9/ch9ex6.txt: -------------------------------------------------------------------------------- 1 | FFTTFTTFFFTFFTTFTTTF 2 | ABC12072 TFF F FFFTFFF F TF 3 | ABC14794 T FTFFFTFFFF TTF FT 4 | ABC56989 FF TF F T F TTF 5 | ABC35662 F FFTF T FFFFTFF T 6 | ABC58503 FTFFFFFFFFT F TTF FT 7 | ABC56756 TTFT FT FTFTFTTTT 8 | ABC12611 TTFT TTTTT F T T F 9 | ABC17071 FT FT TTFFTTT TF T 10 | ABC57279 T FFFFFFTT TT FF FF 11 | ABC15409 TFTFFFT FF FT TFT F 12 | ABC10497 FF TFT T F TT FTT 13 | ABC27041 FF T TFTTFTF F TT 14 | ABC24667 TFTF FTTT TF F FFT 15 | ABC14387 TTFFFTTFF T F 16 | ABC24722 FTT FT TFTT TFTFTTTF 17 | ABC36943 FTFTFT TFTFF FT T 18 | ABC44573 FF F TFF TTF FF F 19 | ABC11988 TFTTTTF FFTF FTTF TT 20 | ABC46764 TTFF TF FF TFTTF FFT 21 | ABC33367 FTT F FT FTTF TFTT 22 | ABC24104 F F TTTTFFTFT FFT 23 | ABC18209 FFTTTF TF FTTFTTFT 24 | ABC26135 FFTFFFTFT T FFFTFTT 25 | ABC30278 TTTT FF TT T TTTF 26 | ABC11832 T FFFT F F F T FFT 27 | ABC16774 T F F F F FF FFTT 28 | ABC27421 FFTF TT FF FFTFF 29 | ABC36479 TT FT T FTF F F T 30 | ABC43479 TFF TTF TTTT FTTFFT 31 | ABC37360 TTFTF F T FF T F 32 | ABC36346 F F FT T TTTT FFFT 33 | ABC10834 F T F F TFTT FFFTT 34 | ABC46532 FT F FFTTFF TFT F F 35 | ABC27883 TFT FT FFF TTFTFFF 36 | ABC22617 TTFTFTTTFTF TF T T 37 | ABC16853 TTF F FFTFFFTFF FF 38 | ABC49332 F TFTF FTF T FFT 39 | ABC51955 T F F T TT FT F 40 | ABC37829 TF FF T TF TF F 41 | ABC45930 T TT F FFF TT 42 | ABC42885 FTF FTFTF FF FFTF 43 | ABC55236 T TF FTTFTTTTTTT 44 | ABC22115 FT TT F FFF FTFFTFTF 45 | ABC32067 FTTFTFF TT TF FF T 46 | ABC12844 FF TT FFFT TT TTT 47 | ABC46612 TTT TFT F T T TF F 48 | ABC33346 TT FTFT FTTFTT FT F 49 | ABC19043 FTFFF T TTTT TT FF 50 | ABC44094 T FF T FTTFT FFFT TF 51 | ABC17987 F F FFTTTFTF TTF F T -------------------------------------------------------------------------------- /Chapter 9/exercise1.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 9 - Exercise 1 4 | markdhoad@gmail.com 5 | 6 | Write a C++ program that declares an array alpha of 50 components of type double. 7 | Initialize the array so that the first 25 components are equal to the square of 8 | the index variable, and the last 25 components are equal to three times the 9 | index variable. Output the array so that 10 elements per line are printed. 10 | *****************************************************************************/ 11 | 12 | 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | void initialise_array(double alpha[]); 19 | void print_array(const double alpha[]); 20 | 21 | int main() 22 | { 23 | double alpha[50]; 24 | initialise_array(alpha); 25 | print_array(alpha); 26 | return 0; 27 | } 28 | 29 | void initialise_array(double alpha[]) { 30 | for (int i = 0; i < 50; i++) { 31 | if (i < 25) 32 | alpha[i] = i * i; 33 | else 34 | alpha[i] = i * 3; 35 | } 36 | } 37 | 38 | void print_array(const double alpha[]) { 39 | int counter = 0; 40 | for (int j = 1; j <= 5; j++) { 41 | for (int i = 1; i <= 10; i++) { 42 | if (counter < 50) 43 | cout << setw(5) << alpha[counter]; 44 | else 45 | break; 46 | counter++; 47 | } 48 | cout << endl; 49 | } 50 | } -------------------------------------------------------------------------------- /Chapter 9/exercise2.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 9 - Exercise 2 4 | markdhoad@gmail.com 5 | 6 | Write a C++ function, smallestIndex, that takes as parameters an int array and 7 | its size and returns the index of the first occurrence of the smallest element 8 | in the array. Also, write a program to test your function. 9 | *****************************************************************************/ 10 | 11 | 12 | #include 13 | 14 | using namespace std; 15 | 16 | int smallestIndex(int numberArray[], int arraySize); 17 | 18 | int main() 19 | { 20 | const int MAX_ARRAY_SIZE = 10; 21 | int testArray[MAX_ARRAY_SIZE] {10, 18, 43, 1, 2, 18, 1, 22, 2, 91}; 22 | int smallestPosition = smallestIndex(testArray, MAX_ARRAY_SIZE); 23 | cout << "The smallest index was position: " << smallestPosition; 24 | cout << " with a value of: " << testArray[smallestPosition]; 25 | return 0; 26 | } 27 | 28 | int smallestIndex(int numberArray[], int arraySize) { 29 | int smallest = 0; 30 | for (int i = 0; i < arraySize-1; i++) { 31 | if (numberArray[i] < numberArray[smallest]) 32 | smallest = i; 33 | } 34 | return smallest; 35 | } 36 | -------------------------------------------------------------------------------- /Chapter 9/exercise3.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 9 - Exercise 3 4 | markdhoad@gmail.com 5 | 6 | Write a C++ function, lastLargestIndex, that takes as parameters an int array 7 | and its size and returns the index of the last occurrence of the largest 8 | element in the array. Also, write a program to test your function. 9 | *****************************************************************************/ 10 | 11 | 12 | #include 13 | 14 | using namespace std; 15 | 16 | int lastLargestIndex(int numberArray[], int arraySize); 17 | 18 | int main() 19 | { 20 | const int MAX_ARRAY_SIZE = 10; 21 | int testArray[MAX_ARRAY_SIZE] {10, 18, 43, 1, 2, 18, 1, 91, 2, 91}; 22 | int largestIndexPos = lastLargestIndex(testArray, MAX_ARRAY_SIZE); 23 | cout << "The largest index was position: " << largestIndexPos; 24 | cout << " with a value of: " << testArray[largestIndexPos]; 25 | return 0; 26 | } 27 | 28 | int lastLargestIndex(int numberArray[], int arraySize) { 29 | int largestIndex = 0; 30 | 31 | for (int i = 0; i < arraySize; i++) { 32 | if (numberArray[i] >= largestIndex) 33 | largestIndex = i; 34 | } 35 | return largestIndex; 36 | } -------------------------------------------------------------------------------- /Chapter 9/exercise5.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 9 - Exercise 5 4 | markdhoad@gmail.com 5 | 6 | Write a program that prompts the user to input a string and outputs the string 7 | in uppercase letters. (Use a character array to store the string.) 8 | *****************************************************************************/ 9 | 10 | 11 | #include 12 | 13 | using namespace std; 14 | 15 | int main() 16 | { 17 | char userInput[50]; 18 | 19 | cout << "Enter a word in lowercase letters: "; 20 | cin >> userInput; 21 | for (int i = 0; i <= strlen(userInput); i++) { 22 | userInput[i] = toupper(userInput[i]); 23 | } 24 | cout << userInput; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Chapter 9/exercise6.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 9 - Exercise 6 4 | markdhoad@gmail.com 5 | 6 | The history teacher at your school needs help in grading a True/False test. 7 | The students’ IDs and test answers are stored in a file. The first entry in the 8 | file contains answers to the test in the form: 9 | TFFTFFTTTTFFTFTFTFTT 10 | Every other entry in the file is the student ID, followed by a blank, followed by 11 | the student’s responses. For example, the entry: 12 | ABC54301 TFTFTFTT TFTFTFFTTFT 13 | indicates that the student ID is ABC54301 and the answer to question 1 is True, 14 | the answer to question 2 is False, and so on. This student did not answer question 9. 15 | The exam has 20 questions, and the class has more than 150 students. Each correct 16 | answer is awarded two points, each wrong answer gets one point deducted, and no 17 | answer gets zero points. Write a program that processes the test data. 18 | The output should be the student’s ID, followed by the answers, followed by 19 | the test score, followed by the test grade. Assume the following grade scale: 20 | 90%–100%, A; 80%–89.99%, B; 70%–79.99%, C; 60%–69.99%, D; and 0%–59.99%, F. 21 | *****************************************************************************/ 22 | 23 | 24 | #include 25 | #include 26 | #include 27 | 28 | using namespace std; 29 | 30 | const int NUMBER_OF_QUESTIONS = 20; 31 | const int NUMBER_OF_STUDENTS = 50; 32 | 33 | void readFile(ifstream& inFile); 34 | void markTest(char studentAnswers[][NUMBER_OF_QUESTIONS], string studentIDs[], char correctAnswers[]); 35 | char assignGrade(int score); 36 | 37 | 38 | int main() 39 | { 40 | 41 | string studentIDs[NUMBER_OF_STUDENTS]; 42 | char correctAnswers[NUMBER_OF_QUESTIONS+1]; 43 | char studentAnswers[NUMBER_OF_STUDENTS][NUMBER_OF_QUESTIONS]; 44 | ifstream inFile; 45 | 46 | readFile(inFile); 47 | 48 | // Read the correct answers first 49 | inFile.getline(correctAnswers, '/n'); 50 | 51 | // Read each students ID and answers 52 | for (int i = 0; i < NUMBER_OF_STUDENTS; i++) { 53 | inFile >> studentIDs[i]; // Grab the student IDs 54 | inFile.get(); // Discard the space between the student ID and the answers 55 | for (int j = 0; j < NUMBER_OF_QUESTIONS; j++) 56 | studentAnswers[i][j] = inFile.get(); // Grab the students answers 57 | } 58 | 59 | markTest(studentAnswers, studentIDs, correctAnswers); 60 | 61 | return 0; 62 | } 63 | 64 | void markTest(char studentAnswers[][NUMBER_OF_QUESTIONS], string studentIDs[], char correctAnswers[]) { 65 | for (int i = 0; i < NUMBER_OF_STUDENTS; i++) { 66 | cout << "Student ID: " << studentIDs[i] << endl; 67 | int score = 0; 68 | cout << "Answers: "; 69 | for (int j = 0; j < NUMBER_OF_QUESTIONS; j++) { 70 | cout << studentAnswers[i][j]; 71 | if (studentAnswers[i][j] == correctAnswers[j]) 72 | score += 2; // Correct answer 73 | else if (studentAnswers[i][j] != correctAnswers[j] && studentAnswers[i][j] != ' ') 74 | score -= 1; // Incorrect answer but not a blank 75 | } 76 | if (score < 0) 77 | score = 0; // Don't allow for minus scores 78 | 79 | cout << endl; 80 | char grade = assignGrade(score); 81 | cout << "Grade: " << grade << endl << endl; 82 | } 83 | } 84 | 85 | char assignGrade(int score) { 86 | double percentScore = static_cast(score) / (NUMBER_OF_QUESTIONS*2); 87 | cout << "Score: " << percentScore*100 << "%" << endl; 88 | if (percentScore >= 0.9) 89 | return 'A'; 90 | else if (percentScore >= 0.8) 91 | return 'B'; 92 | else if (percentScore >= 0.7) 93 | return 'C'; 94 | else if (percentScore >= 0.6) 95 | return 'D'; 96 | else 97 | return 'F'; 98 | } 99 | 100 | void readFile(ifstream& inFile) { 101 | inFile.open("/Users/Mark/Code/C++/cpp_book/Chapter 9/ch9ex6.txt"); 102 | if (!inFile){ 103 | cout << "There was an error opening the input file" << endl; 104 | exit(1); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /Chapter 9/exercise7.cpp: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | C++ Programming - From Problem Analysis to Program Design 5th Edition 3 | Chapter 9 - Exercise 7 4 | markdhoad@gmail.com 5 | 6 | Write a program that allows the user to enter the last names of five candidates 7 | in a local election and the number of votes received by each candidate. The 8 | program should then output each candidate’s name, the number of votes 9 | received, and the percentage of the total votes received by the candidate. 10 | Your program should also output the winner of the election. 11 | *****************************************************************************/ 12 | 13 | 14 | #include 15 | #include 16 | 17 | using namespace std; 18 | 19 | int findWinner(int votes[]); 20 | void printResults(string candidates[], int votes[]); 21 | double calculatePercentage(int votes[], int vote); 22 | 23 | const int NUMBER_OF_CANDIDATES = 5; 24 | 25 | int main() 26 | { 27 | 28 | string candidates[NUMBER_OF_CANDIDATES]; 29 | int votes[NUMBER_OF_CANDIDATES]; 30 | 31 | cout << "Please input the 5 candidates followed by the votes they recieved i.e. Smith 5000: "; 32 | for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) { 33 | cin >> candidates[i] >> votes[i]; 34 | } 35 | printResults(candidates, votes); 36 | cout << "And the winner is: " << candidates[findWinner(votes)] << endl; 37 | return 0; 38 | } 39 | 40 | double calculatePercentage(int votes[], int vote){ 41 | int sumOfVotes = 0; 42 | 43 | for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) { 44 | sumOfVotes += votes[i]; 45 | } 46 | 47 | double percentage = static_cast(vote) / sumOfVotes; 48 | 49 | return percentage*100; 50 | } 51 | 52 | 53 | void printResults(string candidates[], int votes[]){ 54 | cout << "Name:" << setw(15) << "Votes:" << setw(15) << "Percentage:" << endl; 55 | for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) { 56 | cout << candidates[i] << setw(15) << votes[i] << setw(15); 57 | int percentage = calculatePercentage(votes, votes[i]); 58 | cout << percentage << "%" << endl; 59 | 60 | } 61 | } 62 | 63 | int findWinner(int votes[]){ 64 | int winner = 0; 65 | for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) { 66 | if (votes[i] > winner) 67 | winner = i; 68 | } 69 | return winner; 70 | } -------------------------------------------------------------------------------- /Chapter 9/generate_ch9ex6_data.rb: -------------------------------------------------------------------------------- 1 | # A short ruby script to generate the data file required for Chapter 9 Exercise 6. 2 | 3 | File.open("ch9ex6.txt", 'w') do |file| 4 | 5 | # Generate the answers to the test 6 | 20.times do 7 | file.write("#{["T", "F"].sample}") 8 | end 9 | 10 | # Ensure you create data in the format of: ABC54301 TFTFTFTT TFTFTFFTTFT 11 | 50.times do 12 | file.write("\nABC#{rand(10000..60000)} ") 13 | 20.times do 14 | file.write("#{["T", "F", " "].sample}") 15 | end 16 | end 17 | end -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | C++ Programming 2 | ======== 3 | From Problem Analysis to Program Design 5th Edition 4 | ------------- 5 | 6 | This repo is a collection of answers to the programming challenges and exercises outlined in 7 | [C++ Programming - From Problem Analysis to Program Design 5th Edition](http://www.amazon.com/gp/product/1133626386/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1133626386&linkCode=as2&tag=thegoemypay-20) by D.S Malik 8 | 9 | This is probably the single most verbose programming text book that I have ever seen with 10 | hundreds of different exercises that force the student to learn and re-learn concepts until 11 | they become second nature. 12 | 13 | I have decided to make it an on-going effort to go through this book in its entirty and complete 14 | as many of the exercises as possible to teach myself coding from more of a traditional 15 | Computer Science perspective. 16 | 17 | Chapters are outlined as follows: 18 | 19 | 1. An Overview of Computers and Programming Languages 20 | 2. Basic Elements of C++ 21 | 3. Input / Output 22 | 4. Control Structures 1 (Selection) 23 | 5. Control Structures 2 (Repetition) 24 | 6. User-Defined Functions 1 25 | 7. User-Defined Functions 2 26 | 8. User-Defined Simple Data Types, Namespaces and the string type 27 | 9. Arrays and Strings 28 | 10. Applications of Arrays (Searching and Sorting) and the vector type 29 | 11. Records (structs) 30 | 12. Classes & Data Abstractions 31 | 13. Inheritence and Composition 32 | 14. Pointers, Classes, Virtual Functions and Abstract Classes 33 | 15. Overloading and Templates 34 | 16. Exception Handling 35 | 17. Recursion 36 | 18. Linked Lists 37 | 19. Stacks and Queues 38 | 39 | Any feedback on the code contained within this repo is not only appreciated but encouraged. 40 | --------------------------------------------------------------------------------